content stringlengths 4 20k |
|---|
import os.path
import shutil
def pwd():
"""
Returns the current working directory.
This is just a convinience function to access `os.getcwd()`.
"""
return os.getcwd()
def cd(path):
"""
Change the current directory.
The return value can be used with the `with` statement to
automa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
author: hcylus
license: GPL
site: https://github.com/hcylus
file: gitpull.py
time: 2017/4/1 上午10:56
copyright: © DevOps
"""
from __future__ import unicode_literals
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import os, subprocess, time
# try:
from urllib... |
from __future__ import print_function, division
from PyQt4 import QtGui, uic
from clas12_wiremap import initialize_session, dc_fill_tables, dc_find_connections
class DBTab(QtGui.QTabWidget):
def __init__(self,parent=None):
super(QtGui.QTabWidget, self).__init__(parent)
uic.loadUi('DBTab.u... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import time
import errno
from abc import ABCMeta, abstractmethod
from collections import MutableMapping
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.six import with... |
''' These define the standard error codes and messages for Bokeh
validation checks.
1001 *(BAD_COLUMN_NAME)*
A glyph has a property set to a field name that does not correspond to any
column in the |GlyphRenderer|'s data source.
1002 *(MISSING_GLYPH)*
A |GlyphRenderer| has no glyph configured.
1003 *(NO_... |
"""The `gcloud compute xpn list-associated-resources` command."""
from googlecloudsdk.api_lib.compute import xpn_api
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute.xpn import flags
from googlecloudsdk.command_lib.compute.xpn import util as command_lib_util
class ListAssociatedResourc... |
from pywr.nodes import Node, Domain, Input, Output, Link, Storage, PiecewiseLink, MultiSplitLink
from pywr.parameters import pop_kwarg_parameter, ConstantParameter, Parameter, load_parameter
from pywr.parameters.control_curves import ControlCurveParameter
DEFAULT_RIVER_DOMAIN = Domain(name='river', color='#33CCFF')
c... |
""" API routes definition """
from flask_restful import Api
from bigchaindb.web.views import (
assets,
blocks,
info,
statuses,
transactions as tx,
outputs,
votes,
)
def add_routes(app):
""" Add the routes to an app """
for (prefix, routes) in API_SECTIONS:
api = Api(app, pr... |
import cv2
import os,sys
from multiprocessing.pool import ThreadPool
import numpy as np
from collections import deque
max_value=255
def sinv(x):
global max_value
return max(x,max_value-x)
def semi_inverse_image(image):
func = np.vectorize(sinv)
image[:,:,0]=func(image[:,:,0])
image[:,:,1]=func(im... |
from __future__ import print_function, division
import numpy as np
from mdtraj.utils import ensure_type
from mdtraj.geometry import _geometry, distance
import warnings
__all__ = ['compute_angles']
##############################################################################
# Functions
##############################... |
from runtests.mpi import MPITest
from nbodykit.tutorials import download_example_data
from nbodykit import setup_logging, CurrentMPIComm
from six.moves.urllib.error import HTTPError
import pytest
import shutil
import os
import tempfile
setup_logging()
@pytest.mark.xfail(raises=HTTPError)
@MPITest([1])
def test_downlo... |
import tensorflow as tf
import numpy as np
NUM_FACIES = 9
NUM_INPUTS = 9
forms_replace = {'A1 LM': 1,
'A1 SH': 2,
'B1 LM': 3,
'B1 SH': 4,
'B2 LM': 5,
'B2 SH': 6,
'B3 LM': 7,
'B3 SH': 7,
... |
#!/bin/python
import evdev
from evdev import InputDevice, UInput
from select import select
import time
iDevices = map(evdev.InputDevice, (evdev.list_devices()))
iDevices = {dev.fd: dev for dev in iDevices if evdev.events.EV_KEY in dev.capabilities()}
uDevices = {}
for fd in iDevices:
dev = iDevices[fd]
cap = ... |
from copy import deepcopy
import numpy as np
from ..rowland import RowlandTorus, GratingArrayStructure
from ..uncertainties import generate_facet_uncertainty
from ...optics import FlatGrating, OrderSelector
def test_uncertainty_generation():
'''The best way to test that the output format is reasonable is to use i... |
"""Setup mocks for the Plugwise integration tests."""
from functools import partial
import re
from unittest.mock import AsyncMock, Mock, patch
import jsonpickle
from plugwise.exceptions import (
ConnectionFailedError,
InvalidAuthentication,
PlugwiseException,
XMLDataMissingError,
)
import pytest
from... |
#!/usr/bin/env python2
__author__ = "Ryon Sherman"
__email__ = "<EMAIL>"
__license__ = "MIT"
__copyright__ = """
The MIT License (MIT)
Copyright (c) 2014 Ryon Sherman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#Snapper Nautilus Extension
#Luca Béla Palkovics
#https://github.com/KoKuToru/nautilus-snapper-extension.git
import urllib
import os
from datetime import datetime
from gi.repository import Nautilus, GObject, Gtk
def search_path_list(p, r=None):
if p == "/":
return... |
# -*- coding: utf-8 -*-
#
from django.dispatch import receiver
from django.db.models.signals import m2m_changed
from django_auth_ldap.backend import populate_user
from django.conf import settings
from django_cas_ng.signals import cas_user_authenticated
from jms_oidc_rp.signals import openid_create_or_update_user
fro... |
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.air_distribution import OutdoorAirMixer
log = logging.getLogger(__name__)
class TestOutdoorAirMixer(unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfi... |
###############################
#
# (c) Vlad Zat 2017
# Student No: C14714071
# Course: DT228
#
# Title: Testing Feature Detection Algorithms
import numpy as np
import cv2
import easygui
# help(cv2.drawKeypoints)
# help(cv2.drawMatches)
imagesPath = 'images/'
outputPath = 'output/'
fileExtension = '.jpg'
I1 =... |
from __future__ import unicode_literals
from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from mezzanine.conf import settings
from mezzanine.core.views import direct_to_template
settings.use_editable()
admin.autodiscover()
# Add the ... |
import numpy as np
from numpy.testing import assert_array_equal
from nose.tools import assert_true
from sklearn.datasets import make_blobs
from pystruct.models import BinaryClf
from pystruct.learners import (NSlackSSVM, SubgradientSSVM,
OneSlackSSVM)
def test_model_1d():
# 10 1d d... |
#!/usr/bin/env python
import pexpect
import unittest
import PexpectTestCase
import gc
import time
class TestCaseDestructor(PexpectTestCase.PexpectTestCase):
def test_destructor (self):
p1 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN)
p2 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN)
... |
"""The tests for the time automation."""
from datetime import timedelta
from unittest.mock import Mock, patch
import pytest
import voluptuous as vol
from homeassistant.components import automation, sensor
from homeassistant.components.homeassistant.triggers import time
from homeassistant.const import ATTR_DEVICE_CLAS... |
# -*- coding:utf-8 -*-
# !/usr/bin/env python
#
# Email: <EMAIL>
#
# This is the task module of eater package.
from .. import app, utils
from .schedules import celery
from ..zabber.models import Host, HostGroup
from .models import execute, ITEquipment, IP, Group, ITModel, OSUser, \
Connection, Network
... |
import fb_req
import copy
import zmeyka_db_models
from datetime import datetime
# Этот вариант использования токена не безопасен, но для нас подходит
#источник https://developers.facebook.com/docs/facebook-login/access-tokens/
access_token = '202410180169576|db44d093d33ac41b648218a8e6dfe773'
def fb_save_data_to... |
"""
==========================================================================================
Utilities without a direct connection to medical image processing (:mod:`medpy.utilities`)
==========================================================================================
.. currentmodule:: medpy.utilities
Note th... |
"""
Shared code between AMQP based openstack.common.rpc implementations.
The code in this module is shared between the rpc implemenations based on AMQP.
Specifically, this includes impl_kombu and impl_qpid. impl_carrot also uses
AMQP, but is deprecated and predates this code.
"""
import inspect
import sys
import uui... |
import pycuda.compiler as nvcc
import pycuda.gpuarray as gpu
import pycuda.driver as cu
import pycuda.autoinit
from sys import argv
from ws_utils import *
# Read and compile CUDA kernels.
print "Compiling CUDA kernels..."
# PyCUDA wrapper for watershed.
def watershed(I, mask=None):
kernel_source = open("Dwatershed... |
#!/usr/bin/env python
"""Helper script for running endtoend tests."""
import unittest
import logging
# pylint: disable=unused-import,g-bad-import-order
from grr.lib import server_plugins
# pylint: enable=unused-import,g-bad-import-order
from grr.endtoend_tests import base
from grr.lib import access_control
from grr... |
# -*- coding: utf-8 -*-
from logging import getLogger
from django.conf import settings
from django.contrib import messages
from django.contrib.sites.models import Site
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.core.urlresolvers import NoReverseMatch
from django... |
import argparse
import sys
import logging
import os
import math
DEBUG=False
NotDEBUG=not DEBUG
parser = argparse.ArgumentParser(description="Generate scatter interval files",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', acti... |
"""
Logger wrapper and helper class.
"""
from __future__ import absolute_import, division, print_function
import sys
from structlog._utils import until_not_interrupted
class PrintLoggerFactory(object):
"""
Produces :class:`PrintLogger`\ s.
To be used with :func:`structlog.configure`\ 's `logger_factor... |
from __future__ import print_function
import os, sys, unittest
fife_path = os.path.join('..','..','engine','python')
if os.path.isdir(fife_path) and fife_path not in sys.path:
sys.path.insert(0,fife_path)
from fife import fife
print("Using the FIFE python module found here: ", os.path.dirname(fife.__file__))
from f... |
import re
from django.db.backends.base.introspection import (
BaseDatabaseIntrospection, FieldInfo, TableInfo,
)
from django.db.models.indexes import Index
field_size_re = re.compile(r'^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$')
def get_field_size(name):
""" Extract the size number from a "varchar(11)" type na... |
import os
import argparse
from payu import cli
from payu.experiment import Experiment
from payu.laboratory import Laboratory
import payu.subcommands.args as args
from payu import fsops
from payu.manifest import Manifest
title = 'run'
parameters = {'description': 'Run the model experiment'}
arguments = [args.model, a... |
import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... |
class NecroException(Exception):
def __init__(self, err_str: str = None):
self._err_str = err_str
def __str__(self):
if self._err_str is None:
return type(self)
else:
return '{type}: {what}'.format(type=type(self).__name__, what=self._err_str)
class NoMatchupEx... |
''' Simple build error dialog, access to logs etc. '''
import os.path
import os
os.environ['NO_AT_BRIDGE'] = '0'
from gi.repository import Gtk # pylint:disable=no-name-in-module
class Handler(object):
''' Implicit signal handlers declared in glade. '''
def on_build_error_dialog_destroy(self, *args):... |
import re
def fix_urls(text):
"""
Wraps urls in a string with anchor tags
http://stackoverflow.com/questions/1071191/detect-urls-in-a-string-and-wrap-with-a-href-tag#answer-1071240
"""
pat_url = re.compile( r'''
(?x)( # verbose identify URLs within text
(http|ftp|gop... |
from mycroft.client.enclosure.enclosure import Enclosure
from mycroft.skills.displayservice import DisplayService
__author__ = "jarbas"
class DesktopEnclosure(Enclosure):
def __init__(self, emitter, name = "DesktopEnclosure"):
super(DesktopEnclosure, self).__init__(emitter, name)
self.display_ser... |
import abc
import six
from neutron.api import extensions
from neutron.extensions import availability_zone as az_ext
EXTENDED_ATTRIBUTES_2_0 = {
'networks': {
az_ext.AVAILABILITY_ZONES: {'allow_post': False, 'allow_put': False,
'is_visible': True},
az_ext.AZ_HI... |
r"""
Support module file for the dstauffman.estimation code. It defines the supporting code to use within
the more generic batch parameter estimator included in the library.
Notes
-----
#. Written by David C. Stauffer in April 2016.
#. Pulled into dstauffman by David C. Stauffer in July 2020.
"""
#%% Imports
impor... |
{
'name': 'Sale Contract Restrict Domain',
'version': '1.0',
'category': 'Projects & Services',
'sequence': 14,
'summary': '',
'description': """
Sale Contract Restrict Domain
=============================
""",
'author': 'ADHOC SA',
'website': 'www.adhoc.com.ar',
'images': [
... |
{
'name': 'Product warranty',
'version': '11.0',
'category': 'Generic Modules/Product',
'description': """
Product Warranty
================
Extend the product warranty management with warranty details on product / supplier relation:
* supplier warranty duration
* Set default return address for compan... |
#!/usr/bin/env python
# GUI for library in pygtk
import pygtk
pygtk.require('2.0')
import gtk
from backendGui import *
class LibraryGui:
def addBookC(self, widget, bn, ban, bal):
bookn = bn.get_text()
autn = ban.get_text()
autf = bal.get_text()
add_book(bookn, autn, autf)
... |
"""
myupload urlresolver plugin
Copyright (C) 2018 Resolveurl
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 option) any later version.
This program is ... |
########################################################################
#
# File Name: __init__.py
#
# Documentation: http://docs.4suite.org/4DOM/ext/reader/__init__.py.html
#
"""
The 4DOM reader module has routines for deserializing XML and HTML to DOM
WWW: http://4suite.org/4DOM e-m... |
from django.contrib.auth.models import User, check_password
class GasistaFeliceBackend(object):
"""
Authenticate against User database in Gasista Felice
it uses database alias 'gasistafelice'
"""
supports_inactive_user = False
supports_anonymous_user = False
supports_object_permissions = ... |
import os
import sys
import glob
import parted
# Default options
default_options = {
"vfat": ("quiet", "shortname=mixed", "dmask=007", "fmask=117", "utf8", "gid=6"),
"ext3": ("noatime", ),
"ext2": ("noatime", ),
"ntfs-3g": ("dmask=007", "fmask=117", "gid=6"),
"reiserfs": ("noatime", )... |
from cloudbridge.base import helpers as cb_helpers
from cloudbridge.interfaces.resources import DnsRecord
from cloudbridge.interfaces.resources import DnsRecordType
from cloudbridge.interfaces.resources import DnsZone
from tests import helpers
from tests.helpers import ProviderTestBase
from tests.helpers import standa... |
class AB:
def createString(self, N, K):
if self.__checkInitialCondition(N, K) == False:
return ""
arrData = ['B'] * N
if K == 0:
arrData[N-1] = 'A'
return ''.join(arrData)
l_Value = 0
for i in range(1, N):
l_Value = (N-i)*i
... |
import os.path
from datetime import datetime
import tables
from numpy import cos, histogram, linspace, mean, pi, radians, sqrt
from numpy.random import normal
from artist import Plot
from sapphire import ReconstructESDEvents, download_data
from sapphire.utils import norm_angle
DATASTORE = "/Users/arne/Datastore/z... |
"""
Copyright 2010 Google Inc. All Rights Reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
Parse UDP packet for DNS queries and timings.
TODO(lsong): A detailed description of dns.
"""
__author__ = '<EMAIL> (Libo Song)'
import sys
import dpkt
import loggi... |
import urllib, httplib
import datetime
import sickbeard
from lib import MultipartPostHandler
import urllib2, cookielib
try:
import json
except ImportError:
from lib import simplejson as json
from sickbeard.common import USER_AGENT
from sickbeard import logger
from sickbeard.exceptions import ex... |
# coding=utf-8
"""Provider code for HDSpace."""
from __future__ import unicode_literals
import logging
import re
from medusa import tv
from medusa.bs4_parser import BS4Parser
from medusa.helper.common import (
convert_size,
try_int,
)
from medusa.logger.adapters.style import BraceAdapter
from medusa.provide... |
# -*- coding: utf-8 -*-
from gi.repository import Gtk, GObject
import gettext
from gettext import gettext as _
from softwarecenter.ui.gtk3.em import StockEms
class Suggestions(Gtk.VBox):
__gsignals__ = {
"activate-link": (GObject.SignalFlags.RUN_LAST,
None,
... |
from opus_core.variables.variable import Variable
from urbansim.functions import attribute_label
from variable_functions import my_attribute_label
class number_of_SSS_buildings(Variable):
"""Computes the number of buildings of the given type for a gridcell"""
_return_type="int32"
def __init__(se... |
"""Tests for `tf.data.experimental.assert_next()`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.data.experimental.ops import optimization
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops i... |
import os
import subprocess
import sys
from io import BytesIO
from translate.storage import factory, mo, test_base
from translate.tools import pocompile
class TestMOUnit(test_base.TestTranslationUnit):
UnitClass = mo.mounit
def test_context(self):
unit = self.UnitClass("Message")
unit.setcon... |
""" main.py is the top level script.
Return "Hello World" at the root URL.
"""
import os
import webapp2
import sys
# Import the Flask Framework
from flask import Flask, request
from flask import render_template
import urllib2
import json
import random
import uuid
from google.appengine.api import users
from google.ap... |
# project
from checks import AgentCheck
from checks.libs.wmi.sampler import WMISampler
from collections import namedtuple
WMIMetric = namedtuple('WMIMetric', ['name', 'value', 'tags'])
class InvalidWMIQuery(Exception):
"""
Invalid WMI Query.
"""
pass
class MissingTagBy(Exception):
"""
WMI ... |
# -*- coding: utf-8 -*-
'''
Created on 3 Mar 2013
@author: tedlaz
'''
from PyQt4 import QtGui, Qt
import qt_table_report as tr
import dbutils as dbu
import dbmodel as model
class printGridForm(QtGui.QDialog):
def __init__(self, sql, tbl, db, parent):
QtGui.QDialog.__init__(self)
s... |
# -*- coding: utf-8 -*-
from django.conf import settings
def common_settings(request):
""" Passing custom CONSTANT in Settings into RequestContext. """
COMMON_CONTEXT = {
'MAILCHIMP_UUID': settings.MAILCHIMP_UUID,
'MAILCHIMP_ACTION_URL': settings.MAILCHIMP_ACTION_URL,
}
if hasattr(se... |
#!/usr/bin/env python
import bson
from bson import son
import collections
import itertools
import pymongo
import random
import os
import queue
import sys
import threading
import time
class ChunkGenerator(threading.Thread):
def __init__(self, iterable, chunksize, queue):
threading.Thread.__init__(self)
... |
from __future__ import print_function
import sys
# This is not required if you've installed pycparser into
# your site-packages/ with setup.py
#
sys.path.extend(['.', '..'])
from pycparser import c_parser, c_ast, parse_file
# A simple visitor for FuncDef nodes that prints the names and
# locations of function defin... |
# A library of util functions, without any tool invocation
from etb.wrapper import Tool, Substitutions, Lemmata, Success, Failure
import etb.terms
class Utils(Tool):
"""Library of util functions, without tool invocation"""
@Tool.sync
@Tool.predicate("+low: value, +up: value, result: value")
def in_r... |
from __future__ import unicode_literals
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
try:
from django.contrib.auth import get_user_model # Django 1.5
except ImportError:
from postman.future_1_5 import get_user_model
try:
fro... |
import os
import stat
import urllib
import urllib2
import rfc822
DEBUG = None
try:
from cStringIO import StringIO
except ImportError, msg:
from StringIO import StringIO
class RangeError(IOError):
"""Error raised when an unsatisfiable range is requested."""
pass
class HTTPRangeHandler(urllib... |
"""A live word cloud for Twitch chat.
"""
from __future__ import division
from collections import deque
from pubsub import pub
import wx
import gui
import plugins
class Tail(object):
def __init__(self, length=100):
self._words = {}
self._tail = deque(maxlen=length)
self._length = length
... |
from MaKaC.webinterface import wcomponents
import os
import pkg_resources
import MaKaC.common.Configuration as Configuration
from copy import copy
from MaKaC.plugins.EPayment import worldPay
class WTemplated(wcomponents.WTemplated):
def _setTPLFile(self):
"""Sets the TPL (template) file for the object. I... |
"""Support for Sensibo wifi-enabled home thermostats."""
import asyncio
import logging
import aiohttp
import async_timeout
import pysensibo
import voluptuous as vol
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity
from homeassistant.components.climate.const import (
HVAC_MODE_COOL,
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 22 15:59:51 2017
@author: scram
"""
import numpy as np
from pystruct.models import GraphCRF
import pystruct.learners as learners
import cPickle as pickle
event_feature_dic ={}
with open("event_model_dic","r")as modelfile:
event_feature_dic =pickle.load(modelfile)
... |
"""Mako template handler."""
from __future__ import unicode_literals, print_function, absolute_import
import os
import shutil
import sys
import tempfile
from mako import util, lexer, parsetree
from mako.lookup import TemplateLookup
from mako.template import Template
from markupsafe import Markup # It's ok, Mako requ... |
import sys
from abc import abstractmethod, ABCMeta
from pyspark import since, keyword_only
from pyspark.ml.wrapper import JavaParams
from pyspark.ml.param import Param, Params, TypeConverters
from pyspark.ml.param.shared import HasLabelCol, HasPredictionCol, HasRawPredictionCol, \
HasFeaturesCol, HasWeightCol
from... |
import logging
from typing import Optional
from flask_appbuilder.models.sqla import Model
from flask_appbuilder.security.sqla.models import User
from flask_babel import lazy_gettext as _
from superset.charts.commands.exceptions import (
ChartDeleteFailedError,
ChartDeleteFailedReportsExistError,
ChartForb... |
from six.moves import zip
from numpy import array, zeros
from pyNastran.op2.result_objects.op2_objects import ScalarObject
from pyNastran.f06.f06_formatting import write_floats_13e, write_imag_floats_13e
class AppliedLoadsVectorArray(ScalarObject):
def __init__(self, data_code, is_sort1, isubcase, dt):
Sc... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
class AssetMovement(Document):
def validate(self):
self.validate_asset()
self.validate_location()
self.validate_employee()
def validate_asset(self):
for d in self.assets:
status, company ... |
from twisted.internet import reactor, defer
def runQuery(sql_query, sql_args):
print "sql_query is {}, sql_args are {}".format(sql_query, sql_args)
d = defer.Deferred()
reactor.callLater(0.5, d.callback, "DATA")
return d
def load_player(player_id):
print "load_player begin"
d = runQuery("selec... |
import os
import re
import prestans.devel.gen
import prestans.types
def udl_to_cc(text, ignore_first=False):
text = text.lower()
camel_case = re.sub(r"_(.)", lambda pat: pat.group(1).upper(), text)
if not ignore_first:
camel_case = camel_case[0:1].upper()+camel_case[1:]
return camel_case
cl... |
'''Common fixtures for use in testing the twister tool.'''
import os
import sys
import pytest
ZEPHYR_BASE = os.getenv("ZEPHYR_BASE")
sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts/pylib/twister"))
from twisterlib import TestSuite, TestInstance
@pytest.fixture(name='test_data')
def _test_data():
""" Pytest... |
import sys
import unittest
sys.path.insert(0, ".")
from coalib.bearlib.abstractions.Lint import Lint
from coalib.results.SourceRange import SourceRange
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
class LintTest(unittest.TestCase):
def test_process_output(self):
self.uut = Lint()
ou... |
"""
Utility functions for validating forms
"""
from importlib import import_module
import re
from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.contrib.auth.forms import PasswordResetForm
from django.contr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Web api."""
__author__="Wenjun Xiao"
import functools, re, logging
from http import redirect, found, seeother, httpctx
ctx = httpctx
REQ_GET = 'GET'
REQ_POST = 'POST'
RE_ROUTE = re.compile(r'(\:[a-zA-Z_]\w*)')
_RE_REG_ARGS = re.compile(r'(\<[a-zA-Z_]\w*)\>')
def re... |
"""
This module provides the main Scheduler logic of the program.
"""
from constraint import Problem
from constraints import MachineBreaksConstraint
from printer import pprint, BLUE, YELLOW, RED
class Scheduler(object):
"""
This class provides the constraint-based Scheduler.
"""
def __init__(self, plant, orderList... |
#!/usr/bin/env python3
# Imports.
import sys
import os
import urllib.request
from PyQt4 import QtGui, QtCore
# Info about app.
Main_app = QtGui.QApplication(sys.argv)
Desktop = QtGui.QApplication.desktop()
x, y = Desktop.width(), Desktop.height()
# Root widget.
Root_window = QtGui.QWidget()
Root_window.setWindowFla... |
# test script to evaluate Cobbler API performance
#
# Michael DeHaan <<EMAIL>>
import os
import cobbler.api as capi
import time
import sys
import random
N = 10000
print "sample size is %s" % N
api = capi.BootAPI()
# part one ... create our test systems for benchmarking purposes if
# they do not seem to exist.
if n... |
r"""Monte Carlo integration and helpers.
## Background
Monte Carlo integration refers to the practice of estimating an expectation with
a sample mean. For example, given random variable `Z in R^k` with density `p`,
the expectation of function `f` can be approximated like:
```
E_p[f(Z)] = \int f(z) p(z) dz
... |
"""passlib.tests.tox_support - helper script for tox tests"""
#=============================================================================
# init script env
#=============================================================================
import os, sys
root_dir = os.path.join(os.path.dirname(__file__), os.pardir, os.pa... |
from django.conf import settings
from django.http import HttpResponse
from django.utils.decorators import decorator_from_middleware
from .middleware import WebSocketMiddleware
__all__ = ('accept_websocket', 'require_websocket')
WEBSOCKET_MIDDLEWARE_INSTALLED = 'django_websocket.middleware.WebSocketMiddleware' in set... |
# -*- coding: UTF-8 -*-
#/usr/bin/python
import os
import string
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def manual():
print """
usage:
python remote_scp.py [port] [user] [ppk] [host_file] [remote_folder] [local_file1] [local_file2] ...
sample:
python remote_scp.py 22 jobs ... |
"""This module provides a set of helper functions for tests.
Attributes:
LOG_LINE_SEARCH_INTERVAL (decimal): Defines (in seconds), intervals
between subsequent scans of log buffers.
"""
import code
import logging
import os
import re
import signal
import time
import traceback
from contextlib im... |
from oslo_db import exception as db_exc
from oslo_log import log as logging
from oslo_utils import excutils
from oslo_utils import timeutils
from oslo_utils import uuidutils
from sqlalchemy import exc as sql_exc
from sqlalchemy.orm import exc
from neutron.db import common_db_mixin
from neutron.plugins.common import co... |
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
... |
# Raspberry Pi - Manulal Danse Macabre
# Using the joystick hardware from MagPi 49
# By Mike Cook - August 2016
import pygame, time, os, math
from pygame.locals import *
import wiringpi2 as io
pygame.init() # initialise graphics interface
screen = pygame.display.set_mode((0, 0)) # with window bar - ... |
from SimPEG import Mesh, Regularization, Maps, Utils, EM
from SimPEG.EM.Static import DC
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
import copy
import pandas as pd
from scipy.sparse import csr_matrix, spdiags, dia_matrix,diags
from scipy.sparse.linalg import spsolve
from scipy.stats import... |
#!/usr/bin/env python
"""
Manage
- the configuration S3 bucket
- the CloudFormation stacks
INSTALL
$ pip install boto3
$ pip install click
BUCKET STRUCTURE
"""
import boto3
import click
@click.group()
def cli():
pass
@cli.command()
def list_buckets():
"""Print out bucket names"""
s3 = boto3.resourc... |
import pacman, re
class package:
def short_name(self):
return "extravars"
def long_name(self):
return "Verifies that extra variables start with an underscore"
def prereq(self):
return ""
def analyze(self, pkginfo, tar):
stdvars = ['arch', 'license', 'depends', 'makedepends',
'provides', 'conflicts' , ... |
"""
42. Storing files according to a custom storage system
``FileField`` and its variations can take a ``storage`` argument to specify how
and where files should be stored.
"""
import random
import tempfile
from django.db import models
from django.core.files.base import ContentFile
from django.core.files.storage imp... |
from getgauge.python import step, before_scenario, Messages
import os, random, fnmatch, subprocess, datetime
from subprocess import Popen
import shutil
# Re-use some of the functionalities
import assets
# ------------------------
# Helpful Not-Step Methods
# ------------------------
def doesKhassetFileExist(sPathUnti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.