content string |
|---|
import simulations.dynamics.onepop_discrete_replicator as dr
import simulations.dynamics.replicator_fastfuncs as fastfuncs
import simulations.simulation as simulation
import math
import numpy as np
from nose.tools import assert_equal
class PDSim(dr.OnePopDiscreteReplicatorDynamics):
_payoffs = [[3, 0], [4, 1]]
... |
"""
Tests for L{twisted.words.protocols.jabber.jid}.
"""
from twisted.trial import unittest
from twisted.words.protocols.jabber import jid
class JIDParsingTests(unittest.TestCase):
def test_parse(self):
"""
Test different forms of JIDs.
"""
# Basic forms
self.assertEqual(j... |
from typing import Set
from . import characterLib as char
from . import exceptionsLib as ex
from .interface import JsonInterface
class Spell:
def __init__(self, jf: JsonInterface):
self.record = jf
self.name: str = jf.get('/name')
self.level: int = jf.get('/level')
self.effect: st... |
"""This script is used to synthesize generated parts of this library."""
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.ruby as ruby
import logging
import os
logging.basicConfig(level=logging.DEBUG)
# Wrapper for monitoring V3
gapic = gcp.GAPICMicrogenerator()
library = gapic.ruby_libra... |
def makeRunBWAScript(fastqFileListFileName, saiFileListFileName, outputFilePath, referenceGenomeFileName, outputFileNameSuffix, scriptFileName):
# Make a script that will run bwa sampe for paired-end sequencing data
# ASSUMES THAT, IN THE FILE WITH NAME fastqFileListFileName and saiFileListFileName, ALL PAIRS ARE LIS... |
from .monitor import Shower
try:
import collectd
except:
print 'not running from collectd, do something fun here!'
else:
nt = Shower()
def configure_callback(*args, **kwargs):
"""
This method is a workaround - collectd won't call a configure method that
is not defined in this f... |
from controller.base import BaseController
from flask import request
from models.config import ConfigManager
from models.locations import Locations
from models.notifiers import Notifiers
from models.sensors import Sensors
from models.subscribers import Subscribers
from utils.utils import Validate
class ConfigControll... |
"""This module provide functions for generating names.
"""
__author__ = "Alexander Weigl"
__date__ = "2014-06-06"
class IdentifierGenerator(object):
"""Generates identifier with a given `prefix` and `suffx`.
An instance can check, if the generated name was generated by him.
The counter starts by 1.
... |
__author__ = '<EMAIL>'
__date__ = '2017-02-15'
__copyright__ = 'Copyright 2017, Nyall Dawson'
import unittest
# This import is to enable SIP API V2
# noinspection PyUnresolvedReferences
import qgis # pylint: disable=unused-import
from utilities import get_qgis_app
from qgis.core import (QgsProject)
from writerRegis... |
"""
board2img.py - Convert an Pxls .dat file into a .png image
Author: Martín "Netux" Rodriguez
"""
from PIL import Image
from math import floor
from pathlib import Path
from struct import unpack
def get_config_path():
parent = Path(__file__).parent
config_path = None
for i in range(2):
parent = parent / '..'
... |
#!/usr/bin/env python3
import os
import subprocess
def get_changed_files():
try:
raw = subprocess.check_output(['git', 'diff', '--name-only', os.environ['TRAVIS_COMMIT_RANGE']])
except (KeyError, subprocess.CalledProcessError) as e:
if 'TRAVIS_PULL_REQUEST' in os.environ and os.environ['TRAVIS... |
"""
Returns X, Y, and Z coordinates (presumably longitude,
latitude, and level), as well as a value for shapes from
a shapefile. The missing value separates coordinates
between shapes.
"""
from __future__ import print_function
import numpy
import pyferret
import shapefile
def ferret_init(efid):
"""
Initiali... |
import hashlib
from django.db import models
from django.contrib.auth.models import Group, User
from django.utils.translation import ugettext_lazy as _
from domain.models import Domain
from reporters.models import Reporter, ReporterGroup
from hq.processor import REGISTRATION_XMLNS, create_phone_user
import xformmanage... |
"""
Code taken directly from http://preshing.com/20110822/penrose-tiling-in-obfuscated-python/
"""
_ =\
"""if!
1:"e,V=100
0,(0j-1)**-.2;
v,S=.5/ V.real,
... |
import urllib2 as URL
import xml.etree.ElementTree as ET
import json
purgeDir = " E:\Purge"
content = URL.urlopen("http://127.0.0.1:32400/library/all").read()
root = ET.fromstring(content)
child = root.find("Video")
csvOutput = open('./testfile.csv','w')
movieLibList = []
csvOutput.write("Title, Rotten Tomato Rating... |
'''
Copyright (c) 2011-2012 Johannes Mitlmeier
This file is part of Jazzy.
Jazzy is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Th... |
from rdkit import Chem
from rdkit.Chem import AllChem
import numpy as np
def GetMoments(mol, includeWeights):
conf = mol.GetConformer()
if includeWeights:
masses = np.array([x.GetMass() for x in mol.GetAtoms()])
else:
masses = [1.0] * mol.GetNumAtoms()
ps = conf.GetPositions()
mps = [x*y for x,y in... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
ConfigDialog.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**************************... |
# -*- coding: utf-8 -*-
try:
from ztec.zdb import DB
except:
from zdb import DB
db=DB()
db.load=True
db('users').campo('username',db.str,True,True,False,False,0,-1,None,None)
db('users').campo('email',db.email,False,True,False,False,0,-1,None,None)
db('users').campo('password',db.password,False,True,False,False,0,-1,... |
from core.utils.urns import URNUtils
from rspecs.commons import DEFAULT_XMLNS, DEFAULT_XS, DEFAULT_SCHEMA_LOCATION,\
DSL_PREFIX, PROTOGENI_PREFIX
from rspecs.formatter_base import FormatterBase
from lxml import etree
DEFAULT_AD_SCHEMA_LOCATION = DEFAULT_SCHEMA_LOCATION
DEFAULT_AD_SCHEMA_LOCATION += DSL_PREFIX + "3... |
from dataclasses import dataclass
from tempfile import mkdtemp
from typing import Optional
import coloredlogs
import zipfile
import os
from .const import LOGGING_FMT, LOGGING_STYLE
"""
Module containing various utility functions
"""
# = DATA UTILITIES = #
@dataclass
class ConversionOpts:
"""Toggles for the wh... |
"""Utility functions for hashing.
"""
import os
import hmac
from hashlib import sha1
from ganeti import compat
def Sha1Hmac(key, msg, salt=None):
"""Calculates the HMAC-SHA1 digest of a message.
HMAC is defined in RFC2104.
@type key: string
@param key: Secret key
@type msg: string or bytes
"""
ke... |
from oslo.config import cfg
from nova import conductor
from nova import context
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging
from nova.openstack.common import memorycache
from nova.openstack.common import timeutils
from nova.servicegroup import api
CONF = cfg.CONF... |
"""Utilities for working with SEG image instances."""
from typing import Iterator
import numpy as np
from pydicom.dataset import Dataset
def iter_segments(dataset: Dataset) -> Iterator:
"""Iterates over segments of a Segmentation image instance.
Parameters
----------
dataset: pydicom.dataset.Dataset... |
from dataunit.commands.base import DataUnitCommand
from dataunit.context import Context
from utils.database_connector import DatabaseConnector
import pandas as pd
class LoadSheetToTableCommand(DataUnitCommand):
"""
Class for the command that loads test data from the workbook to a database table
"""
c... |
import uuid
from statistics import mean, median
from celery import shared_task
from django.db.models import Q
from grandchallenge.challenges.models import Challenge
from grandchallenge.evaluation.models import Result, Config
from grandchallenge.evaluation.utils import rank_results, Metric
def filter_by_creators_mos... |
from tree import TreeNode
def min_depth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
if root.left is not None or root.right is not None:
return max(self.minDepth(root.left), self.minDepth(root.right))+1
return min(self.minDepth(root.left),... |
from recipe_engine import recipe_api
from recipe_engine import config_types
class CheckoutApi(recipe_api.RecipeApi):
@property
def default_checkout_root(self):
"""The default location for cached persistent checkouts."""
return self.m.vars.cache_dir.join('work')
def git(self, checkout_root):
"""Run... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
Aspect.py
---------------------
Date : October 2016
Copyright : (C) 2016 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
******************... |
import codecs
from numpy.testing import assert_allclose
import numpy as np
from overrides import overrides
from duplicate_questions.data.embedding_manager import EmbeddingManager
from duplicate_questions.data.data_indexer import DataIndexer
from ..common.test_case import DuplicateTestCase
class TestEmbeddingManager... |
# -*- coding: utf-8 -*-
# Python script for converting Skandiabanken CSV to YNAB import format
import sys, os
from datetime import date
import logging
logging.basicConfig(level=logging.INFO)
files = os.listdir()
csv = []
for f in files:
if f.lower().endswith('.csv') and f.lower() != 'new_trans.csv':
cs... |
from stix2.v21 import (Bundle)
for obj in bundle.objects:
if obj == malware:
print("------------------")
print("== MALWARE ==")
print("------------------")
print("ID: " + obj.id)
print("Created: " + str(obj.created))
print("Modified: " + str(obj.modified))
pr... |
# ******************************************
#
# Python wrapper for libtelldus on Linux
#
# Developed by David Karlsson
# (<EMAIL>)
#
# Released as is without any garantees on
# functionality.
#
# *******************************************
import platform
import time
# from ctypes import c_int, c_ubyte, c_... |
from django.views.generic import TemplateView
from horizon import usage
class ProjectOverview(usage.UsageView):
table_class = usage.TenantUsageTable
usage_class = usage.TenantUsage
template_name = 'project/overview/usage.html'
def get_data(self):
super(ProjectOverview, self).get_data()
... |
# -----------------------------
# File: Deep Q-Learning Algorithm
# -----------------------------
import tensorflow as tf
import numpy as np
import random
from collections import deque
# Hyper Parameters:
FRAME_PER_ACTION = 1
GAMMA = 0.99 # decay rate of past observations
OBSERVE = 100. # timesteps to observe before ... |
# Django settings for demo project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '<EMAIL>'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'db.sqlite', ... |
# -*- coding: utf-8 -*-
###############################################################################
# (C) 2012 Oliver Gutiérrez
###############################################################################
"""
:mod:`evogtk.tools.keyrings` --
===================================
.. module:: evogtk.tools.keyrings
... |
import asyncio
import time
import logging
log = logging.getLogger(__name__)
from xwing.exceptions import HeartbeatFailureError, ConnectionAlreadyExists
EOL = b'\n'
HEARTBEAT = b'HEARTBEAT'
HEARTBEAT_SIGNAL = b'HEARTBEAT_SIGNAL'
HEARTBEAT_ACK = b'HEARTBEAT_ACK'
INITIAL_HEARBEAT_LIVENESS = 3
class Repository:
d... |
import unittest
from mantid.simpleapi import config, mtd, CloneWorkspace, D7YIGPositionCalibration, Load
from mantid.api import ITableWorkspace, WorkspaceGroup
import os.path
from os import path
import tempfile
class D7YIGPositionCalibrationTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
c... |
from sympy.core import S, Symbol, sympify
from sympy.utilities.source import get_class
from sympy.assumptions import Q, ask
from sympy.logic.boolalg import fuzzy_not
def refine(expr, assumptions=True):
"""
Simplify an expression using assumptions.
Gives the form of expr that would be obtained if symbols
... |
import responses
from django.core.management import call_command
from django.conf import settings
from treeherder.model.models import FailureLine, Repository, RepositoryGroup
from ..sampledata import SampleData
def test_store_error_summary(activate_responses, jm, eleven_jobs_stored, initial_data):
log_path = Sam... |
from dal import autocomplete
from .models import GermanLemma, ForeignLemma, Quote
from vocabs.models import SkosConcept, SkosConceptScheme
from . import dal_views
class ForeignLemmaGermanAC(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = GermanLemma.objects.all()
if self.q:
... |
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import codecs
from stacker.session_cache import get_session
from . import LookupHandler
from ...util import read_value_from_path
TYPE_NAME = "kms"
class KmsLookup(LookupHandler):
@classmethod
def han... |
import mock
from nailgun import consts
from oslo_serialization import jsonutils
from nailgun.db.sqlalchemy.models import Release
from nailgun.settings import settings
from nailgun.test.base import BaseIntegrationTest
from nailgun.utils import reverse
class TestHandlers(BaseIntegrationTest):
def test_release_put... |
import DeepFried2 as df
import scipy.io
import numpy as np
def model_head(fully_conv=True):
if fully_conv:
return [
df.SpatialConvolutionCUDNN( 512, 4096, (7,7), border='valid'), df.ReLU(),
df.Dropout(0.5),
df.SpatialConvolutionCUDNN(4096, 4096, (1,1), border='valid'),... |
from environment import Environment
from MCLearning import MCLearning
from TDLearning import TDLearning
from LinearFuncApprox import LinearFuncApprox
import matplotlib.pyplot as plt
import numpy as np
env = Environment()
# test monte carlo
mcl = MCLearning(env)
mcl.evaluation(1000000)
mcl.plot()
# test temporal di... |
#!/usr/bin/env python
'''
Project: Geothon (https://github.com/MBoustani/Geothon)
File: Vector/create_wkt_multipolygon.py
Description: This code creates a wkt multi polygons from some polygons
Author: Maziyar Boustani (github.com/MBoustani)
'''
try:
import ogr
except ImportError:
from ... |
from .base_position import BasePosition
from ...environment import Environment
from ...const import SIDE, POSITION_EFFECT, ACCOUNT_TYPE
class FuturePosition(BasePosition):
def __init__(self, order_book_id):
super(FuturePosition, self).__init__(order_book_id)
self._buy_old_holding_list = []
... |
import scipy.stats as ss
import os, sys
import scipy
from scipy import interpolate
import fio
import numpy as np
import matplotlib as mpl
#mpl.use('ps')
import matplotlib.pyplot as plt
import myfun
label = 'm_25_2b_particles'
basename = 'mli'
dayi = 0
dayf = 49
days = 1
## READ archive (too many points... somehow... |
from django.template.loader import render_to_string
from django.contrib.auth.decorators import login_required
from django.core.mail import EmailMessage
from django.conf import settings
from django.contrib.sites.models import Site
from src.basic.invitations import Invitation, InvitationAllotment
from src.basic.invitati... |
from blist import sortedset
# Logging
import logging
from newsreap.Logging import NEWSREAP_HOOKS
logger = logging.getLogger(NEWSREAP_HOOKS)
class Hook(object):
"""
Hooks allow us to define external functions and execute them at key times.
Hooks allow external users to define their own logic that they'd ... |
"""
KMP string matching algorithm
"""
def kmp(haystack, needle):
"""
Run KMP search on haystack on needle and return all matching indexes
Return empty list on no result
:param haystack:
:param needle:
:return:
"""
needle = list(needle)
len_needle = len(needle)
shifts = [1] ... |
from pybuilder.core import use_plugin, task, after, init
from pybuilder.utils import assert_can_execute, read_file
from pybuilder.plugins.python.python_plugin_helper import execute_tool_on_source_files
use_plugin("python.core")
@init
def init_pep8_properties(project):
project.plugin_depends_on("pep8")
@after("... |
"""Tests for qutebrowser.commands.runners."""
import pytest
from qutebrowser.commands import runners, cmdexc
class TestCommandRunner:
"""Tests for CommandRunner."""
def test_parse_all(self, cmdline_test):
"""Test parsing of commands.
See https://github.com/The-Compiler/qutebrowser/issues/... |
from os.path import abspath, basename, dirname, join
from firedrake import *
from firedrake.petsc import PETSc
from incflow import *
import pytest
import numpy as np
import matplotlib.pyplot as plt
cwd = abspath(dirname(__file__))
data_dir = join(cwd, "data")
def plot_results(u1, re):
mr = {100: 1, 1000: 2, 3200... |
import nhtsa
class API(nhtsa.API):
def __init__(self):
super(API, self).__init__('https://www.nhtsa.gov/webapi/api/SafetyRatings')
def get_all_model_years(self):
return self.do_api_request('')
def get_all_makes_for_year(self, year):
return self.do_api_request('/modelyear/{0}', year)
def get_all_models_fo... |
import socket
import select
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('', 5555))
server_socket.listen(5)
poll = select.poll()
poll.register(server_socket.fileno(), select... |
from testtools import matchers
from murano.dsl import dsl
from murano.dsl import serializer
from murano.tests.unit.dsl.foundation import object_model as om
from murano.tests.unit.dsl.foundation import test_case
class TestConstruction(test_case.DslTestCase):
def setUp(self):
super(TestConstruction, self).... |
"""
<EMAIL>
"""
from __future__ import absolute_import
from __future__ import print_function
import logging
logger = logging.getLogger(__name__)
import sys, os
import numpy as np
from PyQt5 import QtCore
from PyQt5 import QtGui, QtWidgets
from PyQt5 import QtOpenGL
import OpenGL.GL as gl
import OpenGL.arrays.vbo a... |
import docker
import time
import argparse
import os
import requests
import logging
import logging.config
import json
from datetime import datetime
from datetime import timedelta
STDOUT = "stdout"
SLACK = "slack"
NOTIFICATION_CHANNELS = [STDOUT, SLACK]
DOCKER_SOCKET_URL = 'unix://var/run/docker.sock'
DEFAULT_POLLING_TI... |
import os, random, string, time
from django.conf import settings
from django.db import models, IntegrityError
from django.template.loader import render_to_string
from django.core.urlresolvers import reverse, NoReverseMatch
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
from has... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# pylint: disable-msg=R0901, R0904
"""
photocat.engine.image
-- engine do obsługi obrazów
Photo Catalog v 1.0 (photocat)
Copyright (c) Karol Będkowski, 2004-2012
This file is part of Photo Catalog
"""
__author__ = 'Karol Będkowski'
__copyright__ = 'Copyright (c) Karol Będko... |
"""PISI source/package index"""
import os
import gettext
__trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext
import pisi
import pisi.context as ctx
import specfile
import metadata
import pisi.util as util
from pisi.data.package import Package
from pisi.exml.xmlfile import XmlFile
from pisi.file... |
import numbers
import re
def main():
try:
book = Book("", "ISBN 0321635906", 54.99, 7830)
assert False, "failed empty string test"
except ValueError as err:
assert str(err).endswith("may not be empty")
try:
book = Book(88, "ISBN 0321635906", 54.99, 7830)
... |
import openerp.tests.common as common
from openerp import exceptions
class TestSaleOrderCreateEventSessionNumber(common.TransactionCase):
def setUp(self):
super(TestSaleOrderCreateEventSessionNumber, self).setUp()
self.task_model = self.env['project.task']
self.sale_model = self.env['sale... |
from unittest import TestCase
from jsonschema import validate
import json
def validatejson(body):
with open('schema.json') as json_data:
schema = json.load(json_data)
return validate(json.loads(body), schema)
class EmptyHash(TestCase):
def test(self):
self.assertIsNone(validatejson('{}')... |
def sokr(type, jid, nick, text):
target = ''
text = text.strip()
if not text: msg = L('What?','%s/%s'%(jid,nick))
else:
if re.search('\A\d+?(-\d+?)? ', text): target, text = text.split(' ', 1)
if re.match('[a-zA-Z]+\Z', text):
data = load_page('http://www.abbreviations.com/%s' % text)
results = re.findall... |
#!/usr/bin/env python3
from dogtail import logging, predicate, rawinput, tree, utils
# Roles
ROLE_FILLER = "filler"
ROLE_FRAME = "frame"
ROLE_LABEL = "label"
ROLE_MENU_ITEM = "menu item"
ROLE_PANEL = "panel"
ROLE_PUSH_BUTTON = "push button"
ROLE_TOGGLE_BUTTON = "toggle button"
ROLE_WINDOW = "window"
# start gnome-t... |
# Imports
import time
import random
import string
import re
import os
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash, Markup, send_file
from flask_hashing import Hashing
from werkzeug import secure_filename
app = Flask(__name__) # create ... |
"""Read gravitational-wave frame (GWF) files using the LALFrame API
The frame format is defined in LIGO-T970130 available from dcc.ligo.org.
"""
import os.path
import warnings
# import in this order so that lalframe throws the ImportError
# to give the user a bit more information
import lalframe
import lal
from ..... |
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
import os.path
import guard
import importlib
import mock
import pretend
import pytest
from werkzeug.exceptions import HTTPException
from werkzeug.test import create_environ
import warehouse
from warehouse impor... |
import os
import sys
from dev_tools import prepared_env, shell_tools
from dev_tools.incremental_coverage import check_for_uncovered_lines
def main():
if len(sys.argv) < 2:
print(
shell_tools.highlight(
'Must specify a comparison branch '
'(e.g. "origin/master"... |
"""
Facebook OAuth support.
This contribution adds support for Facebook OAuth service. The settings
FACEBOOK_APP_ID and FACEBOOK_API_SECRET must be defined with the values
given by Facebook application registration process.
Extended permissions are supported by defining FACEBOOK_EXTENDED_PERMISSIONS
setting, it must ... |
from ranstring import randomByteString
from zope.interface import implements
from twisted.internet import reactor, interfaces
from autobahn.websocket import WebSocketProtocol, WebSocketClientFactory, WebSocketClientProtocol, connectWS
FRAME_SIZE = 0x7FFFFFFFFFFFFFFF # 2^63 - This is the maximum imposed by the WS ... |
import platform
import select
import socket
import ssl
from unittest import mock
import pytest
from dummyserver.server import DEFAULT_CA, DEFAULT_CERTS
from dummyserver.testcase import SocketDummyServerTestCase, consume_socket
from urllib3.util import ssl_
from urllib3.util.ssltransport import SSLTransport
# consume... |
"""Provide lists and annotations for compartment names and reactions.
Please send a PR if you want to add something here :)
"""
# A dictionary having keys as reaction types and keys as prefixes of
# reaction IDs that usually indicate that the reaction is *not* a reaction
# of the specified type.
excludes = {
"de... |
from tomograph import ParallelComputedTomography as PCT
from skimage.measure import compare_ssim as ssim
import numpy as np
from skimage.transform import rescale
from skimage.io import imread
import time
def mse(img1, img2):
err = np.sum((img1.astype("float") - img2.astype("float")) ** 2)
err /= float(img1.sh... |
"""
Types for objects parsed from the configuration.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import re
from collections import namedtuple
import six
from ..const import COMPOSEFILE_V1 as V1
from .errors import ConfigurationError
from compose.const import IS_WINDOW... |
from __future__ import print_function
import numpy as np
from selection.tests.instance import gaussian_instance,logistic_instance
import regreg.api as rr
from selection.randomized.M_estimator_group_lasso import restricted_Mest
from selection.randomized.M_estimator_group_lasso import M_estimator
import selection.tests.... |
import copy
from unittest import mock
from oslo_config import cfg
from heat.common import exception
from heat.common import template_format
from heat.engine.clients.os import magnum as mc
from heat.engine.clients.os import nova
from heat.engine import resource
from heat.engine.resources.openstack.magnum import cluste... |
import wx
import datetime
from wxbanker.plots import plotfactory
try:
from wxbanker.plots import baseplot
except plotfactory.BasePlotImportException:
raise plotfactory.PlotLibraryImportException('wx', 'python-numpy')
import wx.lib.plot as pyplot
class WxPlotFactory(baseplot.BaseFactory):
def __... |
import fechbase
class Records(fechbase.RecordsBase):
def __init__(self):
fechbase.RecordsBase.__init__(self)
self.fields = [
{'name': 'FORM TYPE', 'number': '1'},
{'name': 'FILER COMMITTEE ID NUMBER', 'number': '2'},
{'name': 'TRANSACTION ID NUMBER', 'number': '3'... |
"""Tests for lingvo.core.steps.rnn_steps."""
from lingvo import compat as tf
from lingvo.core import py_utils
from lingvo.core import step
from lingvo.core import test_utils
from lingvo.core.steps import rnn_steps
class RnnStepsTest(test_utils.TestCase):
def testRnnStep(self):
with self.session(use_gpu=False)... |
# abstractions for LED strip
import time
import colorsys
import random as Random
from neopixel import *
# LED strip configuration:
# LED_COUNT = 300 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).
## LED_PIN = 10 # GPIO pin connected to the pi... |
from dci import auth
from dci import dci_config
import mock
import datetime
def test_api_with_unauthorized_credentials(unauthorized, topic_id):
assert unauthorized.get(
'/api/v1/topics/%s/components' % topic_id).status_code == 401
assert unauthorized.get('/api/v1/jobs').status_code == 401
assert ... |
import cadquery as cq
from Helpers import show
__title__ = "make assorted rotary coded switches (type Nidec SH70xx) 3D models"
__author__ = "maurice, hyOzd, Stefan, Terje, mountyrox"
__Comment__ = 'make make assorted rotary coded switches (type Nidec SH70xx) 3D models exported to STEP and VRML'
___ver___ = "1.0.0 21... |
'''
Manage npm (aka node aka Node.js) packages.
'''
from __future__ import unicode_literals
from pyinfra.api import operation
from .util.packaging import ensure_packages
@operation
def packages(packages=None, present=True, latest=False, directory=None, state=None, host=None):
'''
Install/remove/update npm ... |
"""Provides AbstractTrainer/Evaluator base classes, defining train/eval APIs."""
import abc
from typing import Dict, Optional, Union
import numpy as np
import tensorflow as tf
Output = Dict[str, Union[tf.Tensor, float, np.number, np.ndarray, 'Output']] # pytype: disable=not-supported-yet
class AbstractTrainer(t... |
from __future__ import unicode_literals
import socket
import subprocess
import tempfile
from fabric.api import env, hosts, task
from fabric.colors import green
from fabric.utils import puts
from fh_fablib import run_local, require_services
def own_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
... |
import json
from urllib.request import Request, urlopen
from urllib.error import HTTPError
from urllib.parse import urlencode
class RestClient(object):
@staticmethod
def get(url, params={}):
"""Invoke an HTTP GET request on a url
Args:
url (string): URL endpoint to request
... |
from openerp.osv import fields, osv
from datetime import *
class clv_abcfarma_history(osv.osv):
_name = 'clv_abcfarma.history'
_order = "date desc"
_columns = {
'abcfarma_id': fields.many2one('clv_abcfarma', 'abcfarma', required=True, ondelete='cascade'),
'user_id':fields.many2one ('res.u... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2017 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the righ... |
import flask
import flask_bootstrap
import redis
from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore
from mailu import utils, debug, models, manage, configuration
def create_app_from_config(config):
""" Create a new application based on the given configuration
"""... |
from oslo_serialization import jsonutils
from six.moves import http_client
import webtest
from keystone.tests import unit
from keystone.tests.unit import default_fixtures
from keystone.tests.unit import ksfixtures
from keystone.tests.unit.ksfixtures import database
class RestfulTestCase(unit.TestCase):
"""Perfor... |
# -*- coding: utf-8 -*-
import re
from ..internal.SimpleHoster import SimpleHoster
class UptoboxCom(SimpleHoster):
__name__ = "UptoboxCom"
__type__ = "hoster"
__version__ = "0.37"
__status__ = "testing"
__pattern__ = r'https?://(?:www\.)?(uptobox|uptostream)\.com/\w{12}'
__config__ = [("act... |
import gtk
from zim.fs import TrashNotSupportedError
from zim.config import XDG_DATA_HOME, data_file
from zim.templates import list_template_categories, list_templates
from zim.gui.widgets import Dialog, BrowserTreeView, Button, ScrolledWindow
class TemplateEditorDialog(Dialog):
'''Dialog with a tree of available t... |
from .. import preprocessing as pre
ADJS = 0
ADVS = 1
VERBS = 2
ALL = 3
ADJS_AND_ADVS = 4
ADJS_AND_VERBS = 5
ADVS_AND_VERBS = 6
ADJS_AND_BI_ADV_ADJ = 7
ADVS_AND_BI_ADV_ADV = 8
VERBS_AND_BI_ADV_VERB = 9
ALL_NON_GENERAL_BIGRAMS = 10
def set_pos_tags_codes(unigram_type=ADJS):
pos_tags_codes = pre.POS_TAGS.ADJS
... |
"""
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed ... |
# -*- coding: utf-8 -*-
"""
(c) 2014 - Copyright Red Hat Inc
Authors:
Pierre-Yves Chibon <<EMAIL>>
"""
from anitya.lib.backends import BaseBackend, get_versions_by_regex
REGEX = '<a href="/projects/[^/]*/releases/[0-9]*">([^<]*)</a>'
class FreshmeatBackend(BaseBackend):
''' The custom class for project... |
'''
Copyright 2011 Mikel Azkolain
This file is part of Spotimc.
Spotimc 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.
Spotimc is distrib... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.