content string |
|---|
# coding=utf-8
from django.contrib.contenttypes.models import ContentType
from .models import PLUGIN_MODELS
def get_plugins_by_type(plugin_type):
"""
Функция возвращает список плагинов типа plugin_type.
:param plugin_type: str Тип плагинов, напремер "Forecast".
:returns: list Плагины типа plugin_ty... |
#!/usr/bin/python
print " __ "
print " |__|____ ___ __ "
print " | \__ \\\\ \/ / "
print " | |/ __ \\\\ / "
print " /\__| (____ /\_/ "
print " \______| \/ "
p... |
"""Tests for header_control middleware."""
from django.http import HttpRequest, HttpResponse
from django.test import TestCase
from openedx.core.djangoapps.header_control import force_header_for_response, remove_headers_from_response
from openedx.core.djangoapps.header_control.middleware import HeaderControlMiddlewar... |
__all__ = ['approx_equal', 'as_number', 'isint', 'argmax', 'argmin', 'mean', 'median', 'factorial', 'perm']
try:
from itertools import izip
except:
# 3.x compatibility
izip = zip
xrange = range
basestring = unicode = str
import math
import sys
def approx_equal(A, B, abstol, reltol):
if abstol... |
import json
import numpy
class Fit:
"""
Loads a fit from a json file into a `figure.Fit` object.
"""
def __init__(self, path=None):
self.path = path
"""
Path to the json file containing fit to load.
"""
@property
def path(self):
return self._path
@... |
#!/usr/bin python
# -*- coding: utf-8 -*-
from __future__ import division
from math import sqrt
from math import exp
import numpy as np
from numpy import arctan
def h(t=[], x=0,
A=1., omega=0.5, phi0=0.,
rho=1000.,
alpha=1.e-8, beta=4.8e-10, theta=0.35,
L=0., K1=1.e-6, b1=1.,
K... |
#!/usr/bin/env python
import logging
import os
import sys
from huey.consumer import Consumer
from huey.consumer_options import ConsumerConfig
from huey.consumer_options import OptionParserHandler
from huey.utils import load_class
def err(s):
sys.stderr.write('\033[91m%s\033[0m\n' % s)
def load_huey(path):
... |
"""
General utilities for ERMREST.
"""
# Right now these are all DB related utilities. We should keep it that way.
import web
import urllib
import uuid
import base64
import collections
from webauthn2.util import urlquote, negotiated_content_type
__version__ = '0.3.1'
def urlunquote(url):
text = urllib.parse.unq... |
#!/usr/bin/env python3
"""Assess if Juju tracks the model when the current model is destroyed."""
from __future__ import print_function
import argparse
import logging
import sys
import subprocess
import time
from deploy_stack import (
BootstrapManager,
)
from utility import (
add_basic_testing_arguments,... |
from rain.redis._placeholder import BaseMix
from rain.redis.others import do_scan
class HashMix(BaseMix):
async def hdel(self, key, *fields):
return await self._send(b'HDEL', key, *fields)
async def hexists(self, key, field):
return await self._send(b'HEXISTS', key, field)
async def hget(self, key, field):
... |
# AMG8833 Overlay Demo
#
# This example shows off how to overlay a heatmap onto your OpenMV Cam's
# live video output from the main camera.
import sensor, image, time, fir
ALT_OVERLAY = False # Set to True to allocate a second ir image.
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.Q... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
#
# Generate the init string for Xilinx LUT.
#
import sys, string, subprocess, bisect
if len(sys.argv) != 2:
print "Usage: lutgen input.txt"
sys.exit (1)
#
# Get bit value: 0, 1 or ? (as -1).
#
def getbit(str):
if str == "?":
return -1
return int(str... |
import io
import re
import xlsxwriter
import json
from django.conf import settings
from django.http import HttpResponse
from xlsxwriter.utility import xl_rowcol_to_cell
from democracy.models import SectionComment
from .section_comment import SectionCommentSerializer
class HearingReport(object):
def __init__(se... |
import re, logging
from autotest.client.shared import error
from virttest import utils_misc, aexpect, utils_test
@error.context_aware
def run_sr_iov_hotplug(test, params, env):
"""
Test hotplug of sr-iov devices.
(Elements between [] are configurable test parameters)
1) Set up sr-iov test environment ... |
import os
import sys
import shutil
import re
import numpy as np
import sqlite3
import traceback
from util_rec import fields_view
#-----------------------------------------------------------------------------#
def register_sqlite3_numpy_dtypes():
"""
Map numpy data-types to the limited sqlite data-types. This... |
from openerp.osv import fields, osv
from openerp import SUPERUSER_ID
class enter_refusal_password(osv.osv_memory):
_name = "enter.refusal.password"
_description = "Enter Password"
_columns = {
'password': fields.char('Enter Password', size=16, required=True)
}
def refuse_applica... |
"""Adds accounts to the specified multi-client account, in a single batch."""
import argparse
import sys
from apiclient import sample_tools
from apiclient.http import BatchHttpRequest
from oauth2client import client
import shopping_common
# Number of accounts to insert.
BATCH_SIZE = 5
# Declare command-line flags.
... |
bl_info = {
"name": "ShaderTools Next Gen",
"author": "GRETETE Karim (Tinangel)",
"version": (1, 0, 3),
"blender": (2, 6, 8),
"api": 58536,
"location": "User Preferences",
"description": "Shader tools for blender",
"warning": "",
"wiki_url": "http://shadertoolsng.free.fr/help/",
... |
#!/share/apps/local/anacondaz/bin/python
import sys,os
sys.path.append(".")
import numpy as np
import multiprocessing
import sassie.interface.input_filter as input_filter
import bayesian_ensemble_estimator as ensemble_fit
from mpi4py import MPI
svariables = {}
#### MPI Environment ####
comm=MPI.COMM_WORLD
rank=comm.G... |
from django.conf.urls import include
from django.conf.urls.static import static
from django.conf import settings
from django.urls import path, re_path
from graphene_django.views import GraphQLView
from rest_framework import permissions, routers
from rest_framework.authtoken import views
from rest_framework.documentatio... |
"""
Helper functions and classes to support tests which need to connect through
the tor network.
::
ProxyError - Base error for proxy issues.
+- SocksError - Reports problems returned by the SOCKS proxy.
Socks - Communicate through a SOCKS5 proxy with a socket interface
SocksPatch - Force socket-using cod... |
from CTFd.models import Challenges
from CTFd.utils import set_config
from tests.helpers import (
create_ctfd,
destroy_ctfd,
gen_challenge,
gen_flag,
login_as_user,
register_user,
)
def test_create_new_challenge():
"""Test that an admin can create a challenge properly"""
app = create_ct... |
# -*- coding: utf-8 -*-
"""
Use nose
`$ pip install nose`
`$ nosetests`
"""
from hyde.ext.plugins.meta import MetaPlugin
from hyde.ext.plugins.sorter import SorterPlugin
from hyde.fs import File, Folder
from hyde.generator import Generator
from hyde.site import Site
from hyde.model import Config, Expando
import yaml
f... |
#!/usr/bin/env python
"""
A Stepper Motor Driver class for Replicape.
Author: Elias Bakken
email: elias(dot)bakken(at)gmail(dot)com
Website: http://www.thing-printer.com
License: GNU GPL v3: http://www.gnu.org/copyleft/gpl.html
Redeem is free software: you can redistribute it and/or modify
it under the terms of the... |
from __future__ import absolute_import
import os
import re
import time
import logging
import posixpath
from sentry.models import Project, EventError
from sentry.plugins import Plugin2
from sentry.lang.native.symbolizer import Symbolizer, have_symsynd
from sentry.lang.native.utils import find_all_stacktraces, \
fi... |
#!/usr/bin/python
# -*- coding: iso8859-1 -*-
# Script para testear las distintas máquinas implementadas.
from othello import OthelloGame
from game2 import play
from bots import *
from othello_gui import GUIPlayer
# Cada una de estas instancias es una partida entre dos jugadores Othello.
class Match:
def __init__(... |
"""
The implementation of this Sudoku solver is based on the paper:
"A SAT-based Sudoku solver" by Tjark Weber
https://www.lri.fr/~conchon/mpri/weber.pdf
If you want to understand the code below, in particular the function valid(),
which calculates the 324 clauses corresponding to 9 cells, you are strongly
e... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Request',
fields=[
('id', models.AutoField(verb... |
import logging
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon.utils import memoized
from horizon import workflows
from openstack_dashboard import api
from opens... |
"""Example Airflow DAG that creates a Cloud Dataflow workflow which takes a
text file and adds the rows to a BigQuery table.
This DAG relies on four Airflow variables
https://airflow.apache.org/concepts.html#variables
* project_id - Google Cloud Project ID to use for the Cloud Dataflow cluster.
* gce_zone - Google Com... |
from django.contrib.auth.models import Group
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.shortcuts import get_object_or_404
from community.constants import COMMUNITY_ADMIN
from community.utils import (create_groups, assign_permissions, remove_groups,
... |
# This contains our frontend; since it is a bit messy to use the @app.route
# decorator style when using application factories, all of our routes are
# inside blueprints. This is the front-facing blueprint.
#
# You can find out more about blueprints at
# http://flask.pocoo.org/docs/blueprints/
from flask import Bluepr... |
from __future__ import print_function
import argparse
import code
import ast
import sys
import os
import astor.codegen
import hy
from hy.lex import LexException, PrematureEndOfInput, tokenize
from hy.compiler import hy_compile, HyTypeError
from hy.importer import (ast_compile, import_buffer_to_module,
... |
"""Support for Vera scenes."""
from typing import Any, Callable, Dict, List, Optional
import pyvera as veraApi
from homeassistant.components.scene import Scene
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import Entity
from homeass... |
from nose2.tools import params
from pronunciation_master.tests.testlib import testcase
from pronunciation_master.src import language_codes
class LanguageCodeTest(testcase.BaseTestCase):
def setUp(self):
self.fun = language_codes.LanguageCodes.map
def test_for_unknown_language(self):
with sel... |
__author__ = 'Emanuele Tamponi'
DATASET_DEFINITIONS = [
# EASY DATASETS
(
"easy1",
[
"Arts/Crafts",
"Business/Textiles_and_Nonwovens"
]
),
(
"easy2",
[
"Arts/Literature",
"Computers/Security"
]
),
(... |
#!/usr/bin/env python3.3
candidate_paths = "bin obs-plugins data".split()
plist_path = "../cmake/osxbundle/Info.plist"
icon_path = "../cmake/osxbundle/tachyon.icns"
run_path = "../cmake/osxbundle/obslaunch.sh"
#not copied
blacklist = """/usr /System""".split()
#copied
whitelist = """/usr/local""".split()
#
#
#
f... |
from django.urls import path
from . import api_views
urlpatterns = [
path('users/', api_views.UserList.as_view(), name='user-list'),
path('users/<int:pk>/', api_views.UserDetail.as_view(), name='user-detail'),
path('users/self/', api_views.UserSelfDetail.as_view(), name='user-self-detail'),
path('use... |
from TopicModel import TopicModel
from TopicModel import read_sample
def print_top_words(model, feature_names, n_top_words):
for topic_idx, topic in enumerate(model.components_):
print("Topic #%d:" % topic_idx)
print(" ".join([feature_names[i]
for i in topic.argsort()[:-n_t... |
from flask import render_template, request, jsonify
from app import app
from random import choice
import MySQLdb
@app.route('/')
@app.route('/index')
def index():
return render_template("index.html",
title = 'Home')
@app.route('/get')
def get():
cnxn = MySQLdb.connect(host = "localhost", user = "root... |
import proto # type: ignore
from google.ads.googleads.v7.common.types import ad_type_infos
from google.ads.googleads.v7.common.types import custom_parameter
from google.ads.googleads.v7.common.types import final_app_url
from google.ads.googleads.v7.common.types import url_collection
from google.ads.googleads.v7.enums... |
from subprocess import check_output, STDOUT
def uci_get(path, config_directory=None):
args = ["uci", "get"]
if config_directory:
args.extend(["-c", config_directory])
args.append(path)
# crop newline at the end
return check_output(args)[:-1]
def uci_is_empty(path, config_directory=None):... |
# coding: utf-8
"""
Server API
Reference for Server API (REST/Json)
OpenAPI spec version: 1.4.41
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kinow_client
from kinow_client.rest import ... |
"""Messaging library for Python."""
from __future__ import absolute_import, unicode_literals
import os
import re
import sys
if sys.version_info < (2, 7): # pragma: no cover
raise Exception('Kombu 4.6 requires Python versions 2.7 or later.')
from collections import namedtuple # noqa
__version__ = '4.6.8'
__aut... |
# 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 'Subscription.last_activation_at'
db.add_column('chargify_subscription', 'last_activation_a... |
import pyqtgraph as pg
import numpy as np
view = pg.GraphicsView()
l = pg.GraphicsLayout(border=(100,100,100))
view.setCentralItem(l)
def graphPlasticityPerCell(trials, baseDir, columns=3):
cells = list(set(trials['CellDir']))
plots = []
for i in range(len(cells)):
if i % columns == 0:
... |
__author__ = 'zz'
#win_version disable color output
from threading import Lock
from .setting import connect_fail_prompt_bound
from random import choice
from functools import wraps
from .decorators import threading_lock, prefix_print
from shutil import get_terminal_size
from contextlib import contextmanager
error_lo... |
import collections
import sdl2, sdl2.ext
import pybasic.window
import pybasic.draw as draw
from pybasic.proxy import Proxy
__all__ = ['use_software_renderer', 'use_texture_renderer', 'rectangle', 'render']
GlRenderer = None
_factory = None
_renderer = None
_renderQueue = []
class SpriteProxy(Proxy):
def __del__(... |
"""Python wrapper for post training quantization with calibration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import dtypes
from tensorflow.python.util.lazy_loader import LazyLoader
# Lazy load si... |
import arrayfire as af
from . import _util
def simple_statistics(verbose=False):
display_func = _util.display_func(verbose)
print_func = _util.print_func(verbose)
a = af.randu(5, 5)
b = af.randu(5, 5)
w = af.randu(5, 1)
display_func(af.mean(a, dim=0))
display_func(af.mean(a, weights=w, ... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
import os
import urllib2,time
import datetime
import sys
sys.path.append('.')
from internal.realtime_obj import *
from internal.trade_date import *
REALTM_PRE_FD = "../data/"
def get_rt_props(f, dtObj, verObj, bTrade=False):
finalTm = ''
pos = 0
preLine = ''
headLine = ... |
#!/usr/bin/env python
# "chat" and "conv_chat", "sid" -- those we are using in this turn
sid = ""
#
# Handle Recieved message
#
nonce_sended = 0
init_mess_count = 0
def receivedMessage(account, sender, message, conversation, flags):
global conv_chat, chat, nonce_sended, init_mess_count
if conversation == conv_... |
from queue import Queue
import collections
import dropbox
import logging
import os
import threading
import time
class IsDirError(Exception):
pass
class IsFileError(Exception):
pass
class Directory(object):
def __init__(self):
self.children = {}
# lowered -> original
self.orig_name... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import importlib
import sys
#
# Process our command line arguments.
#
p = argparse.ArgumentParser(description='Exfiltrate data.')
data = p.add_mutually_exclusive_group()
data.add_argument('-d', metavar='string', help='String of data to exfiltrate.')
data.... |
from PySide import QtGui, QtCore
from ..fe import FE
from ..widget_factory import EditorFactory
from ..base_editor import BaseValueEditor
class LineEdit(QtGui.QLineEdit):
def minimumSizeHint(self):
return QtCore.QSize(10, 25)
def sizeHint(self):
return self.minimumSizeHint()
class QuatEdito... |
import numpy as np
import os
import unittest
from tkp.testutil.decorators import requires_data
import tkp.sourcefinder
from tkp.sourcefinder import image as sfimage
from tkp.sourcefinder.image import ImageData
from tkp import accessors
from tkp.utility.uncertain import Uncertain
from tkp.testutil.data import DATAPATH... |
import os
import linuxcnc
import collections
# Set up logging
import logger
log = logger.getLogger(__name__)
# Set the log level for this module
log.setLevel(logger.INFO) # One of DEBUG, INFO, WARNING, ERROR, CRITICAL
try:
LINUXCNCVERSION = os.environ['LINUXCNCVERSION']
except:
LINUXCNCVERSION = 'UNAVAILABLE'... |
#!/usr/bin/env python
# $Id: sframe_input.py 344 2012-12-13 13:10:53Z krasznaa $
#***************************************************************************
#* @Project: SFrame - ROOT-based analysis framework for ATLAS
#* @Package: Core
#*
#* @author Stefan Ask <<EMAIL>> - Manchester
#* @author David B... |
import gettext
class PawnError(Exception):
pass
class Pawn(object):
def __init__(self, name):
self._loc = None
self._name = name
self._player = None
self._tickets = {}
def getLocation(self):
return self._loc
def getName(self):
return self._name
def getP... |
# automated tests for credentials.py
from sheetDB.credentials import *
from nose.tools import *
from mock import patch, MagicMock
from sheetDB.errors import DataError
# main class tests
@patch('sheetDB.credentials.gspread.authorize')
@patch('sheetDB.credentials.OAuthCreds.from_json_keyfile_name')
def test_credential... |
# example: https://raw.githubusercontent.com/freshdesk/fresh-samples/master/Python/create_ticket.py
import json
import logging
from django import forms
import requests
from zentral.utils.forms import CommaSeparatedQuotedStringField
from .base import BaseAction, BaseActionForm
logger = logging.getLogger('zentral.core.a... |
from pecan import rest
from wsme import types as wtypes
import wsmeext.pecan as wsme_pecan
from rally.api.controllers import v1
from rally.api import types
class Root(wtypes.Base):
name = wtypes.text
description = wtypes.text
versions = [types.Version]
@classmethod
def convert(self, name, descr... |
import matplotlib.pyplot as plt
from convexhull import Point, readDataPts, isPtOnSegment, segmentIntn
def plot_points(listPts, plane, color = 'red', size = 4):
"""Plots a given list of (x, y) values on a given figure"""
x = []
y = []
for points in listPts:
x.append(points[0])
y.append(p... |
#GetDatacenters.py
from VMWConfigFile import *
from pyVim import connect
from pyVim.connect import SmartConnect, Disconnect
from pyVmomi import vim, vmodl
import atexit
import os
import ssl
import requests
import argparse
import time
# Disabling urllib3 ssl warnings
requests.packages.urllib3.disable_warnings()
# D... |
"""empty message
Revision ID: 37f2b2fb136
Revises: None
Create Date: 2016-12-15 23:36:44.238919
"""
# revision identifiers, used by Alembic.
revision = '37f2b2fb136'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
... |
"""
Contains useful functions and utilities that are not neccessarily only useful
for this module. But are also used in differing modules insidide the same
project, and so do not belong to anything specific.
"""
import os
import logging
import imp
import sys
from dateutil import parser, tz
from datetime import dateti... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import sys
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from giterm.observer import Trigger
# Prevent tracking '.goutputstream-*' files (known Ubuntu bug)
GIT_BLACK_LIST = ['.goutputstream']
GIT... |
import re
from django.db.backends import BaseDatabaseIntrospection
# This light wrapper "fakes" a dictionary interface, because some SQLite data
# types include variables in them -- e.g. "varchar(30)" -- and can't be matched
# as a simple dictionary lookup.
class FlexibleFieldLookupDict:
# Maps SQL types to Django... |
from ..script import opcodes, tools
from ..script.check_signature import parse_signature_blob
from ..script.der import UnexpectedDER
from ... import ecdsa
from ... import encoding
from ...serialize import b2h
from ..exceptions import SolvingError
from .ScriptType import ScriptType, DEFAULT_PLACEHOLDER_SIGNATURE
#... |
from django.conf import settings
from django.contrib import messages
from django.http import Http404, HttpResponse
from django.shortcuts import redirect, render_to_response
from django.template.context import RequestContext
from django.utils.translation import ugettext as _
from django.views.decorators.csrf impor... |
import operator
from ..util.compat import py3k
class NoValue(object):
"""Describe a missing cache value.
The :attr:`.NO_VALUE` module global
should be used.
"""
@property
def payload(self):
return self
def __repr__(self):
"""Ensure __repr__ is a consistent value in cas... |
"""
This file contains the default classes that are used to receive events
from the XML parser. All these classes are meant to be subclassed (or
imitated) by clients that want to handle these functions themselves.
Application is the class that receives document data from the parser,
and is probably the one most pe... |
import asyncio
import re
from cloudbot import hook
correction_re = re.compile(r"^[sS]/([^/]*)/([^/]*)(/.*)?\s*$")
@asyncio.coroutine
@hook.regex(correction_re)
def correction(match, conn, chan, message):
"""
:type match: re.__Match
:type conn: cloudbot.client.Client
:type chan: str
"""
print... |
class PyEmbedError(Exception):
"""Generic error class for PyEmbed.""" |
"""Authorization example."""
from flask import Flask
from flask_apscheduler import APScheduler
from flask_apscheduler.auth import HTTPBasicAuth
class Config:
"""App configuration."""
JOBS = [
{
"id": "job1",
"func": "__main__:job1",
"args": (1, 2),
"t... |
# encoding=utf-8
'''
Created on Aug 24, 2015
@author: lowitty
'''
import logging
logCommonFunc = logging.getLogger('server.CommonFunc')
from twisted.cred import portal
from twisted.conch import avatar, recvline, interfaces as conchinterfaces
from twisted.conch.ssh import session, factory, keys, userauth, connection
... |
import Sea
from Coupling import Coupling
class Coupling3DPlateCavity(Coupling, Sea.model.couplings.Coupling3DPlateCavity):
"""
A coupling describing the relation between a 2D plate and a 3D cavity.
"""
name = "PlateToCavity"
description = "A coupling describing the relation between a plate and a ca... |
from numpy import *
from time import *
import numpy.random as rnd
from matplotlib import cm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import Ellipse
###############
### USED WITH OUTPUT FROM EX3
###############
WP = loadtxt('out/normWorkPrec.txt', skiprows=1)
WP2 ... |
# -*- coding: utf-8 -*-
from parser import *
from downloader import *
from converter import *
from htmlReader import *
import shutil
class Finder(object):
def __init__(self):
self.downloader = Downloader()
self.crawler = Crawler()
self.files = self.crawler.getFiles()
self.downloaded = self.downloader.get(se... |
import os
import pytest
from doit import version
from doit.cmdparse import CmdParseError, CmdOption
from doit.exceptions import InvalidCommand, InvalidDodoFile
from doit.task import Task
from doit.cmd_base import version_tuple, Command, DoitCmdBase
from doit.cmd_base import ModuleTaskLoader, DodoTaskLoader
from doit.... |
import cherrypy
from Expose import expose
from Expire import strongly_expire
from Validate import validate, Valid_int, Valid_string, Valid_bool
from Notebooks import Notebooks
from Users import Users, grab_user_id
from Groups import Groups
from Files import Files
from Forums import Forums, Forum
from Database import V... |
from django.contrib import admin
from .models import Agency, Office
class OfficeAdmin(admin.ModelAdmin):
list_display = ('name', 'agency')
# def formfield_for_foreignkey(self, db_field, request, **kwargs):
# print "blasfe"
# if db_field.name == "main_office":
# kwargs["queryset"] ... |
"""
GPIO: The GPIO modules are imported only with running the start method. GPIO is only available on the Raspberry Pi
and must not be loaded on other machines (e.g. the developers osx system).
"""
import logging
import threading
import time
from Queue import Queue
from math import floor
from telewall.core.util impor... |
import openmc
###############################################################################
# Simulation Input File Parameters
###############################################################################
# OpenMC simulation parameters
batches = 15
inactive = 5
particles = 10000
##########... |
"""Test for the user_score example."""
# pytype: skip-file
import logging
import unittest
import apache_beam as beam
from apache_beam.examples.complete.game import user_score
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that
from apache_beam.testing.util impo... |
import re
from openerp.osv import osv, fields
class res_partner_email(osv.osv):
_name = "res.partner.email"
_description = "partner email ids"
_rec_name = 'email'
_columns = {
'email': fields.char(
'Emails', size=240, required=True), 'res_partner_id': fields.many2one(
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from .iconitem import IconItem
import random
class ItemManager(QObject):
itemRemoved = pyqtSignal(unicode)
itemsChanged = pyqtSignal(list)
def __init__(self, parent=None):
... |
import os
import sys
from setuptools import setup, find_packages
from setuptools.command.install import install
from mlagents.plugins import ML_AGENTS_STATS_WRITER
import mlagents.trainers
VERSION = mlagents.trainers.__version__
EXPECTED_TAG = mlagents.trainers.__release_tag__
here = os.path.abspath(os.path.dirname(... |
from flask import request
from sqlalchemy import or_, and_
from grano.model import Project, Permission, Attribute
PROPERTY = 'property-'
ALIASES = 'aliases-'
def property_filters(args):
for key in args.keys():
if not key.startswith(PROPERTY):
continue
prop = key[len(PROPERTY):]
... |
# -*- coding: utf-8 -*-
import wx
from outwiker.gui.baseaction import BaseAction
from ..i18n import get_
from ..gui.insertdiagramdialog import (InsertDiagramDialog,
InsertDiagramController)
class InsertDiagramAction(BaseAction):
"""
Описание действия
"""
def _... |
# vim: set encoding=utf-8
from unittest import TestCase
from mock import Mock
from regulations.generator.html_builder import *
from regulations.generator.layers.layers_applier import InlineLayersApplier
from regulations.generator.layers.layers_applier import ParagraphLayersApplier
from regulations.generator.node_types... |
"""
Unit test cases.
"""
from __future__ import unicode_literals
from __future__ import print_function
import unittest
import os
import sys
import io
import logging
import logging.config
try:
# check to see if pyxml is installed
from xml.sax.saxlib import LexicalHandler
use_lexical_handler = 1
e... |
import re
from sqlalchemy.schema import Column, ForeignKey, UniqueConstraint
from sqlalchemy.types import Boolean, Integer, String, DateTime
from sqlalchemy.orm import relationship, synonym
from sqlalchemy.ext.declarative import declared_attr
from flask import url_for
from ..db import Base
from ..util.sqla import Enum... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para videos externos de facebook
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import re
import urllib
from core impor... |
#!/usr/bin/python
"""Commands and control for the Onkyo TX-NR708 eISCP interface.
Model website:
http://www.us.onkyo.com/model.cfm?m=TX-NR708&class=Receiver&p=i
Manual for the reciever:
http://63.148.251.135/redirect_service.cfm?type=own_manuals
&file=SN29400317_TX-NR708_En_web.pdf
"""
__author__ = 'Will Nowak... |
# -*- coding: utf-8 -*-
import math
from activations import activations
class Config:
def check(self):
if self.ale_screen_channels != 1 and self.ale_screen_channels != 3:
raise Exception("Invalid channels for ale_screen_channels.")
if self.q_conv_activation_function not in activations:
raise Exception("Inv... |
import logging
import re
import time
import datetime
import dateutil.tz
import traceback
import eva.exceptions
def retry_n(func, args=(), kwargs={}, interval=5, exceptions=(Exception,), warning=1, error=3, give_up=5, logger=logging):
"""
Call `func(*args, **kwargs)` and, if it throws anything listed in
`... |
c,P,V,n,T,R=input("1) Combined Gas Law\n2) Ideal Gas Law\n>>> "),{"P1":raw_input("P1: ").split()},{"V1":raw_input("V1: ").split()},{"n1":raw_input("n1: ").split()},{"T1":raw_input("T1: ").split()},0.082057
if c == 1:P["P2"],V["V2"],n["n2"],T["T2"]=raw_input("\nP2: ").split(),raw_input("V2: ").split(),raw_input("n2: "... |
"""
Shared test fixtures.
pytest automatically makes these available in all test modules.
"""
import wave
# kivy parses sys.argv on import, breaking tests when we pass args to pytest.
# Hack around this by clearing the args.
import sys
sys.argv = sys.argv[:1]
import pytest
import numpy as np
np.random.seed(1)
@p... |
"""
A lightweight server framework.
To use this module, import the 'application' function, which will dispatch
requests based on handlers. To define a handler, decorate a function with
the 'handler' decorator. Example:
>>> from turkic.server import handler, application
... @handler
... def spam():
... return Tru... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.