content stringlengths 4 20k |
|---|
import numpy as np
from hyperspy.component import Component
class Lorentzian(Component):
r"""Cauchy-Lorentz distribution (a.k.a. Lorentzian function) component
.. math::
f(x)=\frac{a}{\pi}\left[\frac{\gamma}{\left(x-x_{0}\right)^{2}+\gamma^{2}}\right]
+---------------------+-----------+
|... |
import csv
import re
import io
import json
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import requests
# This script generates gumroad discounts and emails them to backers from a CSV file.
# It can be run on any computer that has Python3 installed.
##### Fo... |
#!/usr/bin/python
# TODO: issues with new oauth2 stuff. Keep using older version of Python for now.
# #!/usr/bin/env python
import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
import datetime
from participantCollection import ParticipantCollection
# Edit Me!
participantFileNames =... |
from neutron.agent.linux import dhcp
from neutron.openstack.common import log as logging
LOG = logging.getLogger(__name__)
class DhcpNoOpDriver(dhcp.DhcpLocalProcess):
@classmethod
def existing_dhcp_networks(cls, conf):
"""Return a list of existing networks ids that we have configs for."""
r... |
"""
test_key
----------------------------------
Tests for `key` module.
"""
from kiteclient.tests import base
from kiteclient.tests.v1 import utils
from kiteclient.v1 import key
import base64
import six
class TestKey(base.TestCase):
def setUp(self):
super(base.TestCase, self).setUp()
self.dum... |
#prints the tower for towers of Hanoi.
def printTowers(towers):
maxLength = max(len(towers[0]),len(towers[1]),len(towers[2]))
for i in range(maxLength-1,-1,-1):
for j in range(0,3):
if(i == 0 and len(towers[j]) == 0):
print("_",end=" ")
else:
try:
print(str(towers[j][i]), end=" ")
except:... |
from datetime import datetime, timedelta
from django.test import TestCase
from django.test.client import Client
from math import sqrt
from tracker.views import update
from tracker.models import *
import time
class UpdateTestCase(TestCase):
fixtures = ['location.json', 'bus_66.json', 'schedule.json']
def test... |
import random
import unittest
import time
from silk.config import wpan_constants as wpan
from silk.node.wpan_node import WpanCredentials
from silk.tools import wpan_table_parser
from silk.tools import wpan_util
from silk.tools.wpan_util import verify, verify_within
from silk.utils import process_cleanup
import silk.hw... |
"""
This file is part of HexACO.
HexACO 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.
HexACO is distribut... |
# coding: utf-8
"""
Cloudbreak API
Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloud... |
import modules.plugins.Salesforce.utility as util
import modules.botlog as log
def SFDCVersion(messageDetail):
ep = util.sfdcBaseURL + '/services/data/'
response = util.SFDC_REST('GET', ep, {})
ver = response.JSON[0]['label']
messageDetail.ReplyToSender(ver)
def AccountSearch(messageDetail):
e... |
"""distutils.core
The only module that needs to be imported to use the Distutils; provides
the 'setup' function (which is to be called from the setup script). Also
indirectly provides the Distribution and Command classes, although they are
really defined in distutils.dist and distutils.cmd.
"""
# This module should ... |
import asyncio, re, logging, json, random
import plugins
logger = logging.getLogger(__name__)
def _initialise(bot):
plugins.register_handler(_handle_autoreply, type="message")
plugins.register_admin_command(["autoreply"])
def _handle_autoreply(bot, event, command):
config_autoreplies = bot.get_config... |
import sys
tokens = ('DEFINE',
'NAME',
'TICK',
'SQUOTE',
'OBRACE',
'CBRACE',
'SEMI',
'OPAREN',
'CPAREN',
'COMMA')
reserved = {
'define' : 'DEFINE' }
t_TICK = r'\`'
t_SQUOTE = r'\''
t_OBRACE = r'\{'
t_CBRACE = ... |
"""regresstest - test the regress module.
Not to be confused with the regression tests.
"""
import unittest
from commontest import *
from rdiff_backup import regress, Time
Log.setverbosity(3)
class RegressTest(unittest.TestCase):
output_rp = rpath.RPath(Globals.local_connection, "testfiles/output")
output_rbdir_... |
""" A module for handling HiSeq-specific files and folders
"""
import os
import glob
import csv
import scilifelab.illumina as illumina
class HiSeqRun(illumina.IlluminaRun):
def __init__(self, run_dir, samplesheet=None):
illumina.IlluminaRun.__init__(self, run_dir, samplesheet)
if self.samplesheet_... |
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... |
"""ErrorRendezvous handler for collecting errors from multiple threads."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import sys
import threading
import time
import six
import tensorflow as tf
from tensorflow_estimator.python.estimat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
import shutil
import os
import numpy as np
from tempfile import mkdtemp
from psychopy import data
thisPath = os.path.split(__file__)[0]
fixturesPath = os.path.join(thisPath, '..', 'data')
class TestMultiStairHandler(object):
def setup_class(self):
... |
import sys
# check python version
if sys.version_info < (3, 4, 0):
print("CloudBot requires Python 3.4 or newer.")
sys.exit(1)
import json
import logging.config
import logging
import os
__version__ = "1.0.9"
__all__ = ["util", "bot", "connection", "config", "permissions", "plugin", "event", "hook", "logging... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# http://binux.me
# Created on 2015-05-22 20:54:01
import time
import umsgpack
from kombu import Connection, enable_insecure_serializers
from kombu.serialization import register
from kombu.exceptions import Channel... |
#substitution cipher
#The user will supply an alphabet as a key.
import random
#You will need to write the methods to encode and decode given a key.
#-------------------------------------------------------------------
def encode(message, key):
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
message = message.upper()
... |
import os
import subprocess
import sys
import unittest
# The below files must not have any Python code in them;
# there should be a comment in each of them explaining why.
EMPTY_INIT_FILES = {
'edb/__init__.py',
'edb/common/__init__.py',
'edb/tools/__init__.py',
}
def find_edgedb_root():
return os.p... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 8 15:09:56 2015
@author: stamylew
"""
from os import listdir
from os.path import isfile, join
import vigra as vg
import numpy as np
def make_vol(x):
onlyfiles = [f for f in listdir(x) if (isfile(join(x,f))) and (".png" in f)] #holt die .png files aus dem Zielordn... |
import random
from django.test import TestCase
from mock import Mock
from .test_lib.mock_suite import MockSuite
from silk.views.requests import RequestsView
class TestRootViewDefaults(TestCase):
def test_path(self):
requests = [MockSuite().mock_request() for _ in range(0, 3)]
paths = RequestsVie... |
#!/usr/bin/env python
# _*_ coding: utf-8 -*-
import immlib
import os
import sys
from immlib import AccessViolationHook
from immlib import LogBpHook
import socket
import time
DESC="Automate the process to find bad char"
def get_allchar(bad_chars=[]):
bad_chars_ord=[x for x in bad_chars]
ret=""
len=0
for i ... |
'''
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
Hide Tags Dynamic Programming String
Hide Similar... |
"""Utility to convert ReST markup to XML for xml2rfc
Command-line utility that takes a single ReST file
and converts it into XML suitable for processing
by xml2rfc.
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
import docutils
import os
import os.path
import re
import sys
import time
... |
#! {{condiment_python}}
from py.path import local
import click
import setup
default_prefix = setup.default_prefix
def _options(prefix=default_prefix):
from py.path import local
return str(local(prefix).join('build', 'etc', 'salt', 'minion'))
@click.group()
def cli():
pass
cli.add_command(setup.cli, 's... |
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cryptography.exceptions import InvalidSignature, InvalidKey
from time import time
from u2flib_server import u2f
from u2flib_server.model import DeviceRegistration
from sentr... |
import io
import os
import setuptools
# Package metadata.
name = 'google-cloud-dataproc'
description = 'Google Cloud Dataproc API client library'
version = '0.2.0'
# Should be one of:
# 'Development Status :: 3 - Alpha'
# 'Development Status :: 4 - Beta'
# 'Development Status :: 5 - Production/Stable'
release_statu... |
from matplotlib.dates import MinuteLocator, HourLocator, DayLocator
from matplotlib.dates import WeekdayLocator, MonthLocator, YearLocator
def parse_break_str(txt):
"parses '10 weeks' into tuple (10, week)."
txt = txt.strip()
if len(txt.split()) == 2:
n, units = txt.split()
else:
n,unit... |
from tempest.common import compute
from tempest.common.utils import data_utils
from tempest.common import waiters
from tempest import config
from tempest.lib.common.utils import test_utils
from tempest.lib import exceptions
import tempest.test
CONF = config.CONF
class BaseVolumeTest(tempest.test.BaseTestCase):
"... |
"""Unittest for utils.py module."""
from google_compute_engine.distro_lib.debian_9 import utils
from google_compute_engine.test_compat import mock
from google_compute_engine.test_compat import unittest
class UtilsTest(unittest.TestCase):
def setUp(self):
self.mock_logger = mock.Mock()
self.mock_setup = mo... |
try:
import Image
import ExifTags
except ImportError:
try:
from PIL import Image
from PIL import ExifTags
except ImportError:
raise ImportError("The Python Imaging Library was not found.")
from filer.utils import pexif
def get_exif(im):
try:
exif_raw = im._getexif() ... |
from __future__ import absolute_import
import os
from datetime import datetime
from pytz import utc
from kazoo.exceptions import NoNodeError, NodeExistsError
from apscheduler.jobstores.base import BaseJobStore, JobLookupError, ConflictingIdError
from apscheduler.util import maybe_ref, datetime_to_utc_timestamp, utc_... |
from pyanaconda.ui.tui.spokes import EditTUISpoke
from pyanaconda.ui.tui.spokes import EditTUISpokeEntry as Entry
from pyanaconda.ui.common import FirstbootSpokeMixIn
from pyanaconda.ui.tui.simpleline import TextWidget
from pyanaconda.ui.tui import YesNoDialog
from pyanaconda.users import guess_username
from pyanaconda... |
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from home.models import Home
from images.models import Image, ImageCollection
from posts.models import Post
from project.models import Project
def first_page(request):
try:
home ... |
# A quick and simple opengl font library that uses GNU freetype2, written
# and distributed as part of a tutorial for nehe.gamedev.net.
# Sven Olsen, 2003
# Translated to PyOpenGL by Brian Leair, 2004
#
#
# import freetype
# We are going to use Python Image Library's font handling
# From PIL 1.1.4:
import ImageFont... |
import abc
from modules.shared.graphInteraction import Interaction, DrawData
from modules.shared.dialogs.edge import EdgeDialog
################
## Base class ##
################
class Behaviour():
def _init_(self):
pass
@abc.abstractmethod
def getTriggers():
pass
@abc.abstractmethod
def processDrawData()... |
"""Python client library for the Facebook Platform.
This client library is designed to support the Graph API and the
official Facebook JavaScript SDK, which is the canonical way to
implement Facebook authentication. Read more about the Graph API at
http://developers.facebook.com/docs/api. You can download the Facebook... |
import sys
# get version
py3 = (sys.version_info[0] >= 3)
py2 = (not py3)
if not py3:
import codecs
import warnings
def open(file, mode='r', buffering=-1, encoding=None,
errors=None, newline=None, closefd=True, opener=None):
if newline is not None:
warnings.warn('newline i... |
#!/bin/env python
'''
Annokey: a NCBI Gene Database Keyword Search Tool
------------------------------------------------
Authors: Daniel Park, Sori Kang, Bernie Pope, Tu Nguyen-Dumont.
Copyright: 2013, 2014
Website: https://github.com/bjpop/annokey
License: BSD, see LICENCE file in source distribution.
Searche... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from math import pi as Pi
from txt2py import *
from matplotlib.ticker import MultipleLocator
A = txt2py("aquisicao_circulo_PIDt_lambda35_11.txt")
#aquisicao_circulo_PIDSMCx_lambda70_phi6_k70_0_3: e_quad = 0.912252649215 | tau_quad = 0.23892940... |
#Extra Smiting: Complete Warrior, p. 98
#Note: This version will give 2 smites to each smite ability. Arguably
#the wording could be interpreted differently.
from templeplus.pymod import PythonModifier
from toee import *
import tpdp
print "Registering Extra Smiting"
def ExtraSmitingNewDayDestructionDomain(attach... |
import string
import requests
import urllib
import urllib.request
import urllib.error
import socket
import zlib
import random
class YikYakAPI:
endPointIP = "107.170.53.122"
endPointURL = "http://yikyakapp.com/YikYakFiles/"
def __init__(self, proxyIP, proxyPort):
self.proxyIP = proxyIP
... |
"""
Helper module for managing versioning information.
"""
##########################################################################
## Versioning
##########################################################################
__version_info__ = {
'major': 0,
'minor': 3,
'micro': 0,
'releaselevel': 'final... |
"""Uses the `KeyFinder` program to add the `initial_key` field.
"""
from __future__ import division, absolute_import, print_function
import os.path
import subprocess
from beets import ui
from beets import util
from beets.plugins import BeetsPlugin
class KeyFinderPlugin(BeetsPlugin):
def __init__(self):
... |
import unittest
import ossie.utils.testing
import os
from omniORB import any
class ComponentTests(ossie.utils.testing.ScaComponentTestCase):
"""Test for all component implementations in chunks_to_symbols_bf"""
def testScaBasicBehavior(self):
############################################################... |
from java.io import FileInputStream
propInputStream = FileInputStream("createMultipleDataSource.properties")
configProps = Properties()
configProps.load(propInputStream)
domainName=configProps.get("domain.name")
adminURL=configProps.get("admin.url")
adminUserName=configProps.get("admin.userName")
adminPassword=conf... |
import xbmc
import xbmcaddon
import xbmcgui
import time
class VPNAPI:
def __init__(self):
# Class initialisation. Fails with a RuntimeError exception if VPN Manager add-on is not available, or too old
self.filtered_addons = []
self.filtered_windows = []
self.primary_vpns = []
... |
import sys
sys.path.insert(0, '../3rdparty')
sys.path.insert(0, '../lib')
import ofx
import unittest
class ValidatorTests(unittest.TestCase):
def setUp(self):
self.good_aba = ofx.RoutingNumber("314074269")
self.bad_aba = ofx.RoutingNumber("123456789")
def test_not_a_number(self):
... |
# Convert a derep mapping file to an OTU table
import pandas as pd
import argparse
import numpy as np
import util
parser = argparse.ArgumentParser()
parser.add_argument('--fst', help='Input fasta sequences (optional)', default='')
parser.add_argument('--map', help='Input mapping file', required=True)
parser.add_argum... |
#!/usr/bin/python2.5
""" Hunt the wumpus! """
from random import choice
def create_tunnel(cave_from, cave_to):
""" Create a tunnel between cave_from and cave_to """
caves[cave_from].append(cave_to)
caves[cave_to].append(cave_from)
def visit_cave(cave_number):
""" Mark a cave as visited """
v... |
import os
import sys
import errno
import uuid
from atomicwrites import atomic_write
__version__ = '0.1.0'
PY2 = sys.version_info[0] == 2
class cached_property(object):
'''A read-only @property that is only evaluated once. Only usable on class
instances' methods.
'''
def __init__(self, fget, doc=Non... |
"""
Copyright 2007, 2008, 2009 Free Software Foundation, Inc.
This file is part of GNU Radio
OpenCV Companion 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 2
of the License, or (at your option) a... |
from flumotion.common import messages
from flumotion.common.i18n import N_, gettexter
from flumotion.component import feedcomponent
from flumotion.worker.checks import check
__version__ = "$Rev$"
T_ = gettexter()
class VP8(feedcomponent.EncoderComponent):
checkTimestamp = True
checkOffset = True
def ge... |
"""Fixer for dict methods.
d.keys() -> list(d.keys())
d.items() -> list(d.items())
d.values() -> list(d.values())
d.iterkeys() -> iter(d.keys())
d.iteritems() -> iter(d.items())
d.itervalues() -> iter(d.values())
d.viewkeys() -> d.keys()
d.viewitems() -> d.items()
d.viewvalues() -> d.values()
Except i... |
"""Controllers for the gallery page."""
__author__ = '<EMAIL> (Sean Lip)'
import json
from apps.exploration.models import Exploration
from controllers.base import BaseHandler
import utils
from google.appengine.api import users
class GalleryPage(BaseHandler):
"""The exploration gallery page."""
def get(se... |
class RLPException(Exception):
"""Base class for exceptions raised by this package."""
pass
class EncodingError(RLPException):
"""Exception raised if encoding fails.
:ivar obj: the object that could not be encoded
"""
def __init__(self, message, obj):
super(EncodingError, self)._... |
import getopt
import os
import re
import string
import subprocess
import sys
def usage():
print "\
Usage: modify-license.py -[hm]\n\
-h --help print this help\n\
-m --modify modify license of identified files\n\
"
# Utilities
def pattern_in_string(pattern, string):
return re.match(".*"+patt... |
#!/usr/bin/python
import os
import sys
import platform
import shutil
import subprocess
def create_page(orig_path, page_name, page_header):
orig = open(orig_path)
dest = open("Temp/" + os.path.split(orig_path)[1] + ".txt", "w")
dest.write("/** @page " + page_name + " " + page_header + "\n")
dest.write(... |
#!/usr/bin/python2.7
import unittest
import config
from time import sleep
from base import skipUnlessTrue
class MultiSmartBridge(config.scenarios, unittest.TestCase):
def modeSetUp(self):
self.bridge_mode=True
self.host_is_router=True
self.support.backbone.prefix=config.wsn_prefix
... |
"""Utilities for vectorizing code."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import warnings
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.internal import distribution_util
from tensorflo... |
"""optik.errors
Exception classes used by Optik.
"""
__revision__ = "$Id$"
# Copyright (c) 2001-2003 Gregory P. Ward. All rights reserved.
# See the README.txt distributed with Optik for licensing terms.
# created 2001/10/17 GPW (from optik.py)
__all__ = ['OptikError', 'OptionError', 'OptionConflictError',
... |
"""
Django settings for tallerdeprogramacion project.
Generated by 'django-admin startproject' using Django 1.9.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
... |
# -*- coding: utf-8 -*-
"""
requests.async
~~~~~~~~~~~~~~
This module contains an asynchronous replica of ``requests.api``, powered
by gevent. All API methods return a ``Request`` instance (as opposed to
``Response``). A list of requests can be sent with ``map()``.
"""
try:
import gevent
from gevent import m... |
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '<EMAIL>'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'TEST_NAME': ':memory:',
},
}
# Hosts/domain names that are valid for this site; require... |
#!/usr/bin/python3 -tt
# Project : mud-ish-book
# File : view
# Status : at work
import curses
class Graphics(object):
def __init__(self):
self._screen = curses.initscr()
self._string_bfr = []
def start(self):
curses.echo()
curses.cbreak()
# curses.curs_se... |
"""
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum
to n.
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
"""
import math
import sys
__author__ = 'Daniel'
class Solution(object):
F = [0] ... |
__author__ = 'Artur Barseghyan <<EMAIL>>'
__copyright__ = 'Copyright (c) 2013 Artur Barseghyan'
__license__ = 'GPL 2.0/LGPL 2.1'
__all__ = ('BaseWeatherPlugin',)
from six.moves.urllib.request import urlopen
from django.utils.translation import ugettext_lazy as _
from django.core.cache import cache
from dash.json_pac... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
from ... |
import json
import time
import pytest
from tests.util.base import default_namespace
from inbox.models import Namespace
from inbox.util.url import url_concat
@pytest.yield_fixture
def streaming_test_client(db):
from inbox.api.srv import app
app.config['TESTING'] = True
with app.test_client() as c:
... |
# -*- coding: utf-8 -*-
import os.path
from django import VERSION
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
from django.utils.encoding import python_2_unicode_compatible
from django... |
"""
Usage:
sii xml [options] read <infile>...
sii xml [options] bundle dte [--inplace | --suffixed] <infile>...
sii xml [options] bundle enviodte (--sii | --exchange) <outfile> <infile>...
sii xml [options] bundle lv <outfile> <infile>...
sii xml [options] unbundle envi... |
from django.conf import settings
from django.template.loader import render_to_string
from allianceauth import hooks
from allianceauth.services.hooks import ServicesHook
from .tasks import Ips4Tasks
from .urls import urlpatterns
class Ips4Service(ServicesHook):
def __init__(self):
ServicesHook.__init__(se... |
import urllib
import urlparse
from babelsubs.parsers.dfxp import DFXPParser
from django.core.urlresolvers import reverse
from django.test import TestCase
from subtitles.templatetags import new_subtitles_tags
from utils.test_utils import reload_obj
from videos.models import Video
from videos.tests.data import (
ge... |
#!/usr/bin/env python
__author__ = "Patrick K. O'Brien <<EMAIL>>"
__cvsid__ = "$Id$"
__revision__ = "$Revision$"[11:-2]
import unittest
import types
# Import from this module's parent directory.
import os
import sys
sys.path.insert(0, os.pardir)
import version
del sys.path[0]
del sys
del os
""... |
# -*- 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 unique constraint on 'State', fields ['country', 'name']
db.create_unique('udj_state', ['country_id... |
"""Mrs: MapReduce - a Simple implementation
Your Mrs MapReduce program might look something like this:
import mrs
class Mrs_Program(mrs.MapReduce):
def map(key, value):
yield newkey, newvalue
def reduce(key, values):
yield newvalue
if __name__ == '__main__':
mrs.main(Mrs_Program)
"""
#... |
import doctest
import pytest
from insights.parsers import upstart, SkipException
from insights.parsers.upstart import UpstartInitctlList
from insights.tests import context_wrap
INITCTL_LIST = """
rc stop/waiting
vmware-tools start/running
tty (/dev/tty3) start/running, process 9499
tty (/dev/tty2) start/running, proc... |
# -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749
~~~~~~~~~~~~~~~~~~~~~~~
This module is an implementation of various logic needed
for consuming and providing OAuth 2.0 RFC6749.
"""
from __future__ import absolute_import, unicode_literals
from ..parameters import parse_token_response, prepare_token_request
from .ba... |
import pytest
from pyDEA.core.models.multiplier_model_base import MultiplierModelBase
from pyDEA.core.models.multiplier_model import MultiplierInputOrientedModel
from pyDEA.core.models.multiplier_model_decorators import MultiplierModelVRSDecorator
from pyDEA.core.data_processing.read_data_from_xls import read_data
fro... |
# -*- coding: utf-8 -*-
from sqlalchemy import func
from sqlalchemy.exc import IntegrityError
from ..core import db
from ..models import UserGroupPermission
def create(user_group_id, permission_id):
user_group_permission = UserGroupPermission(
user_group_id=user_group_id,
permission_id=permission_... |
from selenium.webdriver.common import service
class Service(service.Service):
"""Object that manages the starting and stopping of the
GeckoDriver."""
def __init__(self, executable_path, port=0, service_args=None,
log_path="geckodriver.log", env=None):
"""Creates a new instance of the ... |
"""
Unittests for acronym.lidar.transform
"""
import sys
import unittest
from acronym import lidar
#/* ======================================================================= */#
#/* Commandline test execution
#/* ======================================================================= */#
if __name__ == '__ma... |
from .views import *
'''
Serves the view bottle building page if the user is allowed to view that design.
Otherwise, the user is told they are unauthorized.
'''
#===============================================================================
@never_cache
@ensure_csrf_cookie
def view_bottle_building(request, bu... |
from behave import given, when, then
from hamcrest.core import assert_that
from hamcrest.core.core.isequal import equal_to
from hamcrest.library.text.stringcontains import contains_string
# Category checkbox
@when(u'I click the checkbox for "{category_name}"')
def step(context, category_name):
context.newsroom.cl... |
import requests
import json
from datetime import datetime
__author__ = 'Steel'
"""Библиотека API для полного контроля и управления серверами на платформе 1Cloud.ru
Документация по API: https://1cloud.ru/api
"""
# Maximum requests per second allowed by 1cloud.ru for each request type
MAX_REQUESTS = {
'GET': 1.5,
... |
import sys
import unittest
from libcloud.utils.py3 import httplib
from libcloud.common.types import InvalidCredsError, LibcloudError
from libcloud.dns.types import RecordType, ZoneDoesNotExistError
from libcloud.dns.types import RecordDoesNotExistError
from libcloud.dns.drivers.zerigo import ZerigoDNSDriver, ... |
import os
import json
import subprocess
class File:
@staticmethod
def check_filepath(filepath):
d = os.path.dirname(filepath)
if not os.path.exists(d):
os.makedirs(d)
return filepath
@staticmethod
def read_file(filepath):
"""return content of a file"""
... |
import math
# D. verbing
# Given a string, if its length is at least 3,
# add 'ing' to its end.
# Unless it already ends in 'ing', in which case
# add 'ly' instead.
# If the string length is less than 3, leave it unchanged.
# Return the resulting string.
def verbing(s):
if len(s) >= 3:
if s.endswith('ing'... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: mysql_variables
short_description: Manage MySQL global vari... |
# -*- coding: UTF-8 -*-
"""
Kodi urlresolver plugin
Copyright (C) 2016 alifrezser
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your... |
import os
import sys
import itertools
import datetime
import math
import subprocess
def subDirs(path):
if os.path.isdir(path):
return next(os.walk(path))[1]
else:
return []
def toPath(*list):
return "/".join(list)
def useForwardSlash(path):
return "/".join(path.split(os.sep))
def addPostfix(file, postfix):... |
from depth_computation_app import *
from binding_site_prediction_app import*
from pka_prediction_app import *
from cavity_detection_app import * |
"""Tests for dsrf_report_manager."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from os import path
import sys
import unittest
import six
from dsrf import constants
from dsrf import error
from dsrf.parsers import dsrf_report_manager
from dsrf.proto i... |
import math
import subprocess
import os
import time
# Code borrowed from http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
def retry(tries=5, delay=3):
'''Retries a function or method until it returns True.
delay sets the initial delay in seconds.
'''
tries = tries * 1.0
tries = math.floor... |
# merge script for staging releases
import os
import logging
import requests
import subprocess
archiver_url = "https://hg.mozilla.org/build/tools/raw-file/default/buildfarm/utils/archiver_client.py" # noqa: E501
archiver_filename = archiver_url.split("/")[-1]
def run_merge(args):
path = args.merge_dir
fro... |
import struct, socket
# pylint: disable = C0301, C0103, C0111, R0903, R0913
UDP_CONTROL_PORT = 49152
UDP_MAX_XFER_BYTES = 1024
UDP_TIMEOUT = 1
UDP_POLL_INTERVAL = 0.10 #in seconds
USRP2_CONTROL_PROTO_VERSION = 11 # Must match firmware proto. We're setting it in detect()
supported_control_proto_versions = [11, 12]
# s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.