code stringlengths 1 199k |
|---|
"""
Compatibility library for older versions of python
"""
import sys
if sys.version_info[:2] > (2, 6):
from logging import NullHandler
else:
from logging import Handler
class NullHandler(Handler):
def emit(self, record):
pass |
import math as m
import decmath as dm
from test import abteq, msteq
def test_degrees():
assert abteq(dm.degrees(.5), m.degrees(.5))
assert abteq(dm.degrees(7.1), m.degrees(7.1))
assert abteq(dm.degrees(-.5), m.degrees(-.5))
assert abteq(dm.degrees(-7.1), m.degrees(-7.1))
assert dm.degrees(dm.pi) == ... |
import os
import argparse
def launch_training(**kwargs):
# Launch training
if kwargs["dset"] == "toy":
train_WGAN.train_toy(**kwargs)
else:
train_WGAN.train(**kwargs)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Train model')
parser.add_argument('--backend... |
from kivy.properties import NumericProperty
from kivy.uix.effectwidget import EffectBase
class GlowEffect(EffectBase):
"""GLSL effect to apply a glowing effect to a texture."""
blur_size = NumericProperty(4.0)
intensity = NumericProperty(.5)
glow_amplitude = NumericProperty(0.1)
glow_speed = Numeric... |
import sys
def login(user, passwd, reddit):
try:
reddit.login(user, passwd)
print('> Logged in as ' + user)
except:
print('> Failed to connect to Reddit. Check your credentials.')
sys.exit() |
class foo(object):
class bar(object):
def msg(self):
print("bar")
def msg(self):
print("foo")
b = self.bar()
b.msg()
f = foo.bar()
f.msg()
f = foo()
f.msg() |
if __name__ == '__main__':
s = "Hello" |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('gallery', '0007_auto_20150829_0924'),
]
operations = [
migrations.AlterField(
model_name='gallerysection',
name='slug',
... |
from datetime import datetime as datetime
import pytz
from khal.khalendar.event import create_timezone
berlin = pytz.timezone('Europe/Berlin')
bogota = pytz.timezone('America/Bogota')
atime = datetime(2014, 10, 28, 10, 10)
btime = datetime(2016, 10, 28, 10, 10)
def test_berlin():
vberlin_std = b'\r\n'.join(
... |
"""
===========================
Pipeline bamstats
===========================
:Author: Adam Cribbs
:Release: $Id$
:Date: |today|
:Tags: Python
The intention of this pipeline is to perform QC statistics on
`.bam` files that are produced following mapping of fastq
files.
The pipeline requires a `.bam` file as an in... |
import os
import shutil
import unittest
from collections import namedtuple
from conans.client.cmd.export import _replace_scm_data_in_conanfile
from conans.client.loader import _parse_conanfile
from conans.model.scm import SCMData
from conans.test.utils.test_files import temp_folder
from conans.test.utils.tools import T... |
from __future__ import unicode_literals
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
}
INSTALLED_APPS = (
'gum',
'gum.tests',
'gum.tests.test_app',
)
GUM_DEBUG = True
GUM_ELASTICSEARCH_URLS = ["http://127.0.0.1:9200/"]
GUM_ELASTICSEARCH_URLS... |
ASYNC = True
REDIS_HOST = 'localhost'
REDIS_DB = 0
REDIS_PORT = 6379 |
import ctypes
collect_ignore = ["hook-keyring.backend.py"]
def macos_api_ignore():
"""
Starting with macOS 11, the security API becomes
non-viable except on universal2 binaries.
Ref #525.
"""
try:
ctypes.CDLL(ctypes.util.find_library('Security')).SecItemAdd
return False
excep... |
'''
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
'''
class Solution:
def firstMissingPositi... |
with open("/home/cmsprod/.phedexrequests","r") as f:
data = f.read()
requests = data.split("\n")
for request in requests:
print " Id: %s" + request |
import feedparser
__program__ = "reuters.py"
__author__ = "Jaiden D. DeChon"
__copyright__ = "Copyright (C) 2017 Jaiden D. DeChon"
__license__ = "MIT"
__version__ = "1.1.0"
__maintainer__ = "Jaiden D. DeChon"
__contact__ = "dechonjaiden@gmail.com"
__status__ = "Development"
"""
To Do:
- Reuters generally has a sli... |
def wrap_decor(user_func):
def wrapped_func(): # No need to pass the function as argument
print "Hacking into a user supplied function: %s" % user_func.__name__
raw = user_func()
message = ''
if isinstance(raw, str):
message = raw.lower() + " was h4xx0r3d!"
print ... |
"""
Compatibility module to provide backwards compatibility for useful Python
features.
This is mainly for use of internal Twisted code. We encourage you to use
the latest version of Python directly from your code, if possible.
@var unicode: The type of Unicode strings, C{unicode} on Python 2 and C{str}
on Python 3... |
import numpy as np
from nilabels.tools.aux_methods.utils_nib import set_new_data
def get_rgb_image_from_segmentation_and_label_descriptor(im_segm, ldm, invert_black_white=False, dtype_output=np.int32):
"""
From the labels descriptor and a nibabel segmentation image.
:param im_segm: nibabel segmentation whos... |
from . import v
assert v # Silence pyflakes
def test_item_repr(v):
v.scan(
"""\
import os
message = "foobar"
class Foo:
def bar():
pass
"""
)
for item in v.get_unused_code():
assert repr(item) == f"'{item.name}'"
def test_item_attr(v):
v.scan("foo.bar = 'bar'")
assert le... |
from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize("analysis.pyx")
) |
from unittest import TestCase
from regparser.grammar.interpretation_headers import *
class GrammarInterpretationHeadersTest(TestCase):
def test_par(self):
match = parser.parseString("3(c)(4) Pandas")
self.assertEqual('3', match.section)
self.assertEqual('c', match.p1)
self.assertEqua... |
get_ipython().run_line_magic('matplotlib', 'inline')
from sklearn import datasets
from sklearn.svm import SVC, LinearSVC
from sklearn.linear_model import SGDClassifier
from sklearn.preprocessing import StandardScaler
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xti... |
import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'BIOMD0000000456.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return... |
import re
import requests
from connector import Connector
from commit import Commit
import xml.etree.ElementTree as ET
from geogigexception import GeoGigException
import geogig
SHA_MATCHER = re.compile(r"\b([a-f0-9]{40})\b")
class GeoGigServerConnector(Connector):
''' A connector that connects to a geogig repo thro... |
"""
Plots the k-means clustering
"""
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cm as cm
import PVReadWeights as rw
import PVConversions as conv
import scipy.cluster.vq as sp
import math
if len(sys.argv) < 2:
print "usage: kclustering filename on, f... |
'''
@copyright (c) 2010-2013 IBM Corporation
All rights reserved.
This program and the accompanying materials are made available under the
terms of the Eclipse Public License v1.0 which accompanies this
distribution, and is available at http://www.eclipse.org/legal/epl-v10.html
@author: jinghe
'''
import logging
... |
"""Color and brush history view widgets"""
import gi
from gi.repository import Gtk
from gi.repository import GObject
from gi.repository import GdkPixbuf
from lib.color import RGBColor
from colors import ColorAdjuster
from lib.observable import event
import widgets
HISTORY_PREVIEW_SIZE = 32
class BrushHistoryView (Gtk.H... |
register(GRAMPLET,
id="Descendant Count Gramplet",
name=_("Descendant Count"),
description = _("Gramplet for showing people and descendant counts"),
status= STABLE,
fname="DescendantCount.py",
authors=["Douglas S. Blank, Paul Culley"],
authors_email=["doug.... |
"""
***************************************************************************
GdalAlgorithm.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**************************************************... |
class KorgMidiReader:
"""
Select the first attached Korg NANOKontrol2 then update the current state of the controller whenever read_events() is callled.
# NANOKontrol Magic Values:
# 0x00 - 0x07: sliders
# 0x10 - 0x17: knobs
# 0x20 - 0x27: S buttons
# 0x30 - 0x37: M buttons
# 0x40 - 0x47: R buttons
"""
knobs ... |
import os
import pyric.pyw as pyw
from AuxiliaryModules.events import SuccessfulEvent
from SessionManager.sessionmanager import SessionManager
from etfexceptions import InvalidConfigurationException
from netaddr import EUI
from subprocess import Popen, PIPE, check_output
from textwrap import dedent
from threading impor... |
from decimal import Decimal as D
from django.db import models
from django.core.exceptions import FieldError
from simple_history.models import HistoricalRecords
from parametros.models import Periodo
from core.models import Equipos, Obras
from zweb_utils.models import BaseModel
from .managers import ValoresManager
class ... |
import atexit
import logging
from pysphere import VIServer
class connection(object):
"""
This class is the network configuration stager.
It is responsible to start a config and turn on the requisite
machines.
It is also the class that handles the interactions to the libvirt
module.
"""
#... |
"""
VirtualBox Validation Kit - Storage snapshotting and merging testcase.
"""
__copyright__ = \
"""
Copyright (C) 2013-2015 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
you can redistribute it and/or modify it und... |
import urllib
from PIL import Image
def getDimensions(image):
urllib.urlretrieve(image, 'tempimage')
im = Image.open('tempimage')
return im.size # (width,height) tuple
def setAlbumArtClass(image):
if image != 'NULL':
artSize = getDimensions(image)
ALBUM_ART_W = artSize[0]
ALBUM_... |
import sys, binascii, json, threading, time, datetime, logging
DEBUG = True
T = None
def LOG(msg):
logging.debug(msg)
def DEBUG_LOG(msg):
logging.debug(msg)
def ERROR(txt='',hide_tb=False,notify=False):
logging.debug('An error has occurred ' + txt)
def Version(ver_string):
return None
def _processSettin... |
"""
Support for ATLAS as toolchain linear algebra library.
:author: Stijn De Weirdt (Ghent University)
:author: Kenneth Hoste (Ghent University)
"""
from easybuild.tools.toolchain.linalg import LinAlg
TC_CONSTANT_ATLAS = 'ATLAS'
class Atlas(LinAlg):
"""
Provides ATLAS BLAS/LAPACK support.
LAPACK is a build ... |
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@gmail.com
**************... |
"""cool.py - it's just silly """
from moobot_module import MooBotModule
handler_list=["cool"]
class cool(MooBotModule):
def __init__(self):
self.regex = "^cool .+"
def handler(self, **args):
"""it's just silly"""
from irclib import Event
# Split the string and take every word after the first two as the
# wo... |
class Employee(object):
def __init__(self, salary, title, boss):
class Manager(Employee):
def __init__(self, salary, title, boss):
self.employees = []
def add_employee(self, employee):
def bonus(self, multiplier):
def total_subsalary(self):
rachell = Manager(1000, "Founder", None)
jin = Mana... |
__author__ = 'jeuna'
"""
superclass for criteria
"""
class Criteria:
def getCriteriaType(self):
return "not defined" |
import os
import copy
import pyudev
from .. import errors
from .. import util
from ..flags import flags
from ..storage_log import log_method_call
from .. import udev
from ..formats import getFormat
from ..size import Size
import logging
log = logging.getLogger("blivet")
from .device import Device
from .network import N... |
"""
Test output of docker rmi command
docker rmi full_name
1. Find full_name (tag) which not exists.
2. Try to remove new full_name
3. Check if rmi command failed
"""
from autotest.client import utils
from dockertest.images import DockerImages
from dockertest.output import OutputGood
from rmi import rmi_base
class dele... |
print('this is SD-CARD config_')
class PyGuitarConf():
class Vocab():
configKeys=['Name', # 0
'M', # vol, tone # 1
'A', # 2
'B', # 3
'C', # 4
'D', ... |
import eConsoleImpl
import eBaseImpl
import enigma
enigma.eTimer = eBaseImpl.eTimer
enigma.eSocketNotifier = eBaseImpl.eSocketNotifier
enigma.eConsoleAppContainer = eConsoleImpl.eConsoleAppContainer
from Tools.Profile import profile, profile_final
profile("PYTHON_START")
from enigma import runMainloop, eDVBDB, eTimer, ... |
"""
udp-ipv6 protocl support class(es)
http://libvirt.org/formatnwfilter.html#nwfelemsRulesProtoTCP-ipv6
"""
from virttest.libvirt_xml import accessors, xcepts
from virttest.libvirt_xml.nwfilter_protocols import base
class Udp_ipv6(base.TypedDeviceBase):
"""
Create new Udp_ipv6 xml instances
Properties:
... |
from core import *
from config import HIRES
__all__ = ['Sizer', 'HSizer', 'VSizer']
class BlankBox:
'''
An empty space that you can
put in a BoxSizer
'''
def size(self, l, t, r, b):
pass
class Box:
'''
A box that holds a window.
It should not be used directly, but it is used
when you pass ... |
__author__ = 'drichner'
"""
docklr -- models.py
Copyright (C) 2014 Dan Richner
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 2 of the License, or
(at your option) any later version.... |
import os
import sys
from os.path import exists, expandvars, join
_CODE_DEACTIVATE = 5000
_CODE_RESTART = 6000
ARGV = " ".join(["Build.py"] + sys.argv[1:])
HOME = os.environ.get("WORKON_HOME", expandvars("%USERPROFILE%\Envs"))
if hasattr(sys, "real_prefix"):
NAME = sys.prefix.split("\\")[-1]
PATH = sys.prefix
... |
import sys, os
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Python Audio Tools'
copyright = u'2012, Brian Langenberger'
version = '2.19'
release = '2.19beta1'
exclude_trees = []
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
htm... |
from sqlalchemy import Column, Integer, String, Text, schema,SmallInteger
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import ForeignKey, DateTime, Boolean, func
from sqlalchemy.orm import relationship, backref
from models import UHPBase
import json,time
BASE = declarative_base()
class CallBa... |
import codecs # UTF-8 support for the text files
import datetime
import json
def text2file(txt, filename):
"""Write the txt to the file."""
outputfile = codecs.open(filename, "a", "utf-8")
outputfile.write(txt)
outputfile.close()
json_data=open('/var/www/html/finnish-tor-campaign/relays_fi.json')
data ... |
import connection
import pyamf
from pyamf import remoting
class ViewerExperienceRequest(object):
def __init__(self, URL, contentOverrides, experienceId, playerKey, TTLToken = ''):
self.TTLToken = TTLToken
self.URL = URL
self.deliveryType = float(0)
self.contentOverrides = contentOverrides
self.experienceId =... |
import unittest
import uuid
import random
import datetime
import time
import string
import pprint
from selenium.webdriver.common.by import By
from pypop.pageobjects.base_page_object import PageObject
from pypop.pageobjects.base_page_element import InputField, PasswordField, Button
import os.path
class LoginPageObject(P... |
"""
(c) 2015 - Copyright Red Hat Inc
Authors:
Pierre-Yves Chibon <pingou@pingoured.fr>
"""
__requires__ = ['SQLAlchemy >= 0.8']
import pkg_resources
import unittest
import shutil
import sys
import os
import json
from mock import patch
sys.path.insert(0, os.path.join(os.path.dirname(
os.path.abspath(__file__)),... |
"""SCons.Tool.default
Initialization with a default tool list.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
__revision__ = "src/engine/SCons/Tool/default.py rel_2.3.5:3329:275e75118ad4 2015/06/20 11:18:26 bdb... |
"""
Contains the critical decorators for ripozo.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from functools import wraps, update_wrapper
import logging
import warnings
import six
_logger = logging.getLogger(__na... |
import socket, sys
def getaddrinfo_pref(host, port, socketype, famliypreference = socket.AF_INET):
"""Given a host, port, and socketype(usually socket.SOCK_STREAM or
socket.SOCK_DGRAM), looks up information with ipv4 and ipv6. If
information is found corresponding to the famliyperference, it is
returned... |
import os
from enigma import eEnv, getDesktop
from re import compile
from stat import S_IMODE
pathExists = os.path.exists
isMount = os.path.ismount # Only used in OpenATV /lib/python/Plugins/SystemPlugins/NFIFlash/downloader.py.
SCOPE_TRANSPONDERDATA = 0
SCOPE_SYSETC = 1
SCOPE_FONTS = 2
SCOPE_SKIN = 3
SCOPE_SKIN_IMAGE... |
from django.contrib import admin
from .models import Basket
admin.site.register(Basket) |
import logging
import os
import json
settings = {
"settings": {
# To be used by Flask: DEVELOPMENT ONLY
"debug": True,
# Flask host: DEVELOPMENT ONLY
"host": "localhost",
# Flask port: DEVELOPMENT ONLY
"port": 5555,
# Logging configurations
"logging": ... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('lists', '0004_item_list'),
]
operations = [
migrations.AlterUniqueTogether(
name='item',
unique_together=set([('list', 'text')]),... |
import logging
import re
from collections import namedtuple
from functools import lru_cache
from core import constants as C
from core.exceptions import InvalidMeowURIError
from util import coercers
from util.misc import flatten_sequence_type
log = logging.getLogger(__name__)
MeowURIParts = namedtuple('MeowURIParts', 'r... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "criminal.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
"""
***************************************************************************
PointsInPolygon.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
************************************************... |
import os
import tempfile
import pythoncom
from win32com.shell import shell, shellcon
import win32con
import win32process
import win32event
import win32ui
import win32gui
import win32gui_struct
import win32api
import _winreg
from tgitutil import *
import sys
def write_err(self, *args):
for a in args:
sys.st... |
__author__ = 'cpaulson'
from apscheduler.schedulers.background import BlockingScheduler
import dill as pickle
import numpy as np
import time
class dataStorage():
def __init__(self, dataqueue, statusQueue, title=None, dis=None):
self.x = np.array([])
self.y = np.array([])
self.firstTime = Non... |
from twython import Twython, TwythonError, TwythonAuthError
from .config import (
app_key, app_secret, oauth_token, oauth_token_secret,
protected_twitter_1, protected_twitter_2, screen_name,
test_tweet_id, test_list_slug, test_list_owner_screen_name,
access_token, test_tweet_object, test_tweet_html
)
im... |
class Profile:
def __init__(self, name):
self.name = name
def getName(self):
return self.name
def getDirName(self):
return self.name.replace('/', '.')
def __eq__(self, other):
return isinstance(other, Profile) and self.name == other.name
def __ne__(self, other):
... |
from core import game
def main():
scr_width = int(input('SCREEN_WIDTH: '))
scr_height = int(input('SCREEN_HEIGHT: '))
new_game = game.Game(scr_width, scr_height)
new_game.run()
print('Thanks for playing! ;)')
if __name__ == "__main__":
main() |
from distutils import dir_util # virtualenv problem pylint: disable=E0611
import logging
import os
import glob
import shutil
import sys
from avocado.utils import path as utils_path
from avocado.utils import process
from avocado.utils import genio
from avocado.utils import linux_modules
from . import utils_misc
from . ... |
"""Script for testing ganeti.tools.ensure_dirs"""
import errno
import stat
import unittest
import os.path
from ganeti.tools import ensure_dirs
import testutils
class TestEnsureDirsFunctions(unittest.TestCase):
def _NoopMkdir(self, _):
self.mkdir_called = True
@staticmethod
def _MockStatResult(mode, pre_fn=lam... |
from models import Comment
from utils.response import json_response
from article.models import Article
from message.models import UserMessage
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
@login_required
def comment_create(request):
article_id = int(request.P... |
import os
import pysftp
from jdt.csv2mongo import csv2mongo
from jdt.ndjson2mongo import ndjson2mongo
def download_files_from_ftp(
sftp_host,
sftp_username,
sftp_private_key_path,
known_hosts_path,
remote_path_to_download,
local_destination_path=""):
cnopts = pysftp.C... |
from __future__ import division
from collections import defaultdict
import os.path
import re
import datetime
import numpy as N
from . import colors
from ..compat import citems, cstr, cexec
from .. import setting
from .. import utils
from .. import datasets
from .. import qtall as qt
identifier_re = re.compile(r'^[A-Za-... |
import json
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from django.views.generic import CreateView, DetailView, ListView, TemplateView, View
from django.views.generic.edit... |
'''
Exodus Add-on
Copyright (C) 2016 Exodus
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 pro... |
"""ipdevpoll plugin to collect chassis and module information from ENTITY-MIB.
This will collect anything that looks like a field-replaceable module
with a serial number from the entPhysicalTable. If a module has a
name that can be interpreted as a number, it will have its
module_number field set to this number.
The c... |
"""Base class for sources with a transaction link that specifies a unique id."""
from typing import Dict, List, Any, Optional, FrozenSet, Union, Set
from beancount.core.data import Open, Transaction, Posting, Amount, Pad, Balance, Entries, Directive
from . import ImportResult, SourceResults, Source, InvalidSourceRefere... |
from PyQt5.QtCore import Qt
from PyQt5.QtPrintSupport import QPrinter, QPrinterInfo, QPrintPreviewDialog
from PyQt5.QtWidgets import QFileDialog
class printer:
def __init__(self):
pass
@staticmethod
def process(data, args):
printer = QPrinter(QPrinterInfo.defaultPrinter())
printer.se... |
from common import Constant
from storage.model import m
from main.logger_helper import L
import abc
from common import utils
def update_custom_relay(pin_code, pin_value, notify=False, ignore_missing=False):
relay = m.ZoneCustomRelay.find_one({m.ZoneCustomRelay.gpio_pin_code: pin_code,
... |
st = [1, 2, 3, 4]
def powersets(s):
if len(s) == 0:
return [[]]
p1 = powersets(s[1:])
p2 = []
for sets in p1:
p2.append(sets+[s[0]])
return p1+p2
result = powersets(st)
print result
print
for sets in result:
print sets |
import gettext
import logging
import os
import sys
from mimetypes import guess_type
import apt_pkg
from apt.cache import Cache
from .DebPackage import (
ClickPackage,
DebPackage,
)
if sys.version_info[0] == 3:
from gettext import gettext as _
def py3utf8(s):
return s
utf8 = py3utf8
unico... |
from .env import *
def _mahalanobis(covar, offset):
return (offset *
tensordot(offset,inverse(covar),((offset.ndim-1,),(1,)))
).sum(axis=offset.ndim-1)
def _indent(text, n):
return text.replace("\n", "\n"+" "*n)
class Mvnormal(object):
def __init__(self, mean, covar):
self.me... |
"""
"""
from .microchip8_splittedPMarea_hasResetPC import *
class Chip_Pic16F1509sip6(microchip8_splittedPMarea_hasResetPC):
nLatches = 32
rowSize = 32
def __init__(self):
microchip8_splittedPMarea_hasResetPC.__init__(self,
chipPackage = "DIP10",
chipPinVCC = 9,
chipPinsVPP = 10,
chipPinGND = 8,
sig... |
import argparse, os.path
from diagram import Diagram
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Process UMLDown files.')
parser.add_argument('file', metavar='FILE', type=str, nargs=1,
help='the file to process')
args = parser.parse_args()
fn = args.file[0]
dia = ... |
from Screens.MessageBox import MessageBox
'''
class FactoryReset(MessageBox):
def __init__(self, session):
MessageBox.__init__(self, session, _("When you do a factory reset, you will lose ALL your configuration data\n"
"(including bouquets, services, satellite data ...)\n"
"After completion of factory reset, y... |
""" Mockery demonstrates using mocks for unit testing.
1) using the "mock" package to quickly mock up objects
2) patching mock objects into subject code
3) using the more specialized "betamax" package to mock requests.
mock was added to the standard library in Python 3.3 and is
available from pip for earlier versions. ... |
import launcher
tool = launcher.Launcher( 'umake' )
tool.run() |
from xml.dom import minidom
import libvirt
from libvirt import libvirtError
from libvirttestapi.src import sharedmod
required_params = ('guestname', )
optional_params = {'memory': 1048576,
'maxmem': 4194304,
}
def get_memory_config(domobj):
"""get domain config current memory a... |
"""
Rule that checks for a family with a particular tag.
"""
from ....ggettext import gettext as _
from .._hastagbase import HasTagBase
class HasTag(HasTagBase):
"""
Rule that checks for a family with a particular tag.
"""
labels = [ _('Tag:') ]
name = _('Families with the <tag>')
de... |
import PyKDE4.kdeui as __PyKDE4_kdeui
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
class KPropertiesDialog(__PyKDE4_kdeui.KPageDialog):
# no doc
def abortApplying(self, *args, **kwargs): # real signature unknown
pass
def applied(self, *args, **kwargs): # real signature u... |
'''
Tulip routine libraries, based on lambda's lamlib
Author Twilight0
License summary below, for more details please read license.txt file
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
th... |
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('block', '0002_auto_20160511_0430'),
]
operations = [
migrations.AlterField(
model_name='block',
... |
try:
from pygame import *
except:
import sys
import Log
Log.critical("Can't import SDL bindings...")
Log.critical("Please install them from http://www.pygame.org/")
sys.exit(1) |
"""@package generate_data
Script that generates Monte Carlo sim output for many cases at once, for specified initial distributions, sample rates, & other variables
"""
import sys
sys.path.append('../')
import cp_dynamics
import numpy as np
import matplotlib.pyplot as plt
import time
def etaCalc(k,kmax,dt):
dtest = ... |
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
... |
from sklearn.linear_model import LogisticRegression
from gensim.models import Doc2Vec
from GeneraVectores import GeneraVectores
import numpy as np
from sklearn import svm
from NNet import NeuralNet
if __name__ == '__main__':
model_dbow = Doc2Vec.load('./imdb_dbow.d2v')
model_dm = Doc2Vec.load('./imdb_dm.d2v')
dim = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.