repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1 value | license stringclasses 15 values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
gotche/django-basic-project | project_name/project_name/settings/base.py | Python | apache-2.0 | 1,387 | 0.000721 | import os
from configurations import values
from django.conf import global_settin | gs
class DjangoSettings(object):
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = values.SecretValue()
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
| 'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = '{{ project_name }}.urls'
WSGI_APPLICATION = '{{ project_name }}.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
class BaseSettings(DjangoSettings):
pass
|
JamesMura/sentry | tests/sentry/web/frontend/test_create_organization.py | Python | bsd-3-clause | 1,205 | 0 | from __future__ import absolute_import
from django.core.urlresolvers import reverse
from exam import fixture
from sentry.models import Organization, OrganizationMember
from sentry.testutils import TestCase
class CreateOrganizationTest(TestCase):
@fixture
def path(self):
return reverse('sentry-create-organization')
def test_renders_with_context(self):
self.login_as(self.user)
resp = self.client.get(self.path)
assert resp.status_code == 200
self.assertTemplateUsed(resp, 'sentry/create-organization.html')
assert resp.context['form']
def test_valid_params(self):
self.logi | n_as(self.user)
resp = self.client.post(self.path, {
'name': 'bar',
})
assert resp.status_code == 302
org = Or | ganization.objects.get(name='bar')
assert OrganizationMember.objects.filter(
organization=org,
user=self.user,
role='owner',
).exists()
assert org.team_set.exists()
redirect_uri = reverse('sentry-create-project', args=[org.slug])
assert resp['Location'] == 'http://testserver%s' % (
redirect_uri,
)
|
laurencium/CausalInference | tests/test_tools.py | Python | bsd-3-clause | 1,433 | 0.028611 | from nose.tools import *
import numpy as np
import causalinference.utils.tools as t
def test_convert_to_formatting( | ):
entry_types = ['string', 'float', 'integer', 'float']
ans = ['s', '.3f', | '.0f', '.3f']
assert_equal(list(t.convert_to_formatting(entry_types)), ans)
def test_add_row():
entries1 = ('Variable', 'Mean', 'S.d.', 'Mean', 'S.d.', 'Raw diff')
entry_types1 = ['string']*6
col_spans1 = [1]*6
width1 = 80
ans1 = ' Variable Mean S.d. Mean S.d. Raw diff\n'
assert_equal(t.add_row(entries1, entry_types1, col_spans1, width1), ans1)
entries2 = [12, 13.2, -3.14, 9.8765]
entry_types2 = ['integer', 'integer', 'float', 'float']
col_spans2 = [1, 2, 2, 1]
width2 = 80
ans2 = ' 12 13 -3.140 9.877\n'
assert_equal(t.add_row(entries2, entry_types2, col_spans2, width2), ans2)
def test_add_line():
width = 30
ans = '------------------------------\n'
assert_equal(t.add_line(width), ans)
def test_gen_reg_entries():
varname = 'Income'
coef = 0.5
se = 0.25
ans1 = 'Income'
ans2 = 0.5
ans3 = 0.25
ans4 = 2
ans5 = 0.045500
ans6 = 0.01
ans7 = 0.99
v, c, s, z, p, lw, up = t.gen_reg_entries(varname, coef, se)
assert_equal(v, ans1)
assert_equal(c, ans2)
assert_equal(s, ans3)
assert_equal(z, ans4)
assert np.allclose(p, ans5)
assert np.allclose(lw, ans6)
assert np.allclose(up, ans7)
|
GeotrekCE/Geotrek-admin | geotrek/common/translation.py | Python | bsd-2-clause | 470 | 0 | from modeltranslation.translator import translator, TranslationOptions
from geotrek.common.models | import TargetPortal, Theme, Label
class ThemeTO(TranslationOptions):
fields = ('label', )
class TargetPortalTO(TranslationOptions):
fields = ('title', 'description')
class LabelTO(TranslationOptions):
fields = ('name', 'advi | ce')
translator.register(Theme, ThemeTO)
translator.register(TargetPortal, TargetPortalTO)
translator.register(Label, LabelTO)
|
7kbird/chrome | android_webview/tools/webview_licenses.py | Python | bsd-3-clause | 13,334 | 0.011999 | #!/usr/bin/python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Checks third-party licenses for the purposes of the Android WebView build.
The Android tree includes a snapshot of Chromium in order to power the system
WebView. This tool checks that all code uses open-source licenses compatible
with Android, and that we meet the requirements of those licenses. It can also
be used to generate an Android NOTICE file for the third-party code.
It makes use of src/tools/licenses.py and the README.chromium files on which
it depends. It also makes use of a data file, third_party_files_whitelist.txt,
which whitelists indicidual files which contain third-party code but which
aren't in a third-party directory with a README.chromium file.
"""
import glob
import imp
import optparse
import os
import re
import subprocess
import sys
import textwrap
REPOSITORY_ROOT = os.path.abspath(os.path.join(
os.path.dirname(__file__), '..', '..'))
# Import third_party/PRESUBMIT.py via imp to avoid importing a random
# PRESUBMIT.py from $PATH, also make sure we don't generate a .pyc file.
sys.dont_write_bytecode = True
third_party = \
imp.load_source('PRESUBMIT', \
os.path.join(REPOSITORY_ROOT, 'third_party', 'PRESUBMIT.py'))
sys.path.append(os.path.join(REPOSITORY_ROOT, 'tools'))
import licenses
import known_issues
class InputApi(object):
def __init__(self):
self.re = re
def GetIncompatibleDirectories():
"""Gets a list of third-party directories which use licenses incompatible
with Android. This is used by the snapshot tool.
Returns:
A list of directories.
"""
result = []
for directory in _FindThirdPartyDirs():
if directory in known_issues.KNOWN_ISSUES:
result.append(directory)
continue
try:
metadata = licenses.ParseDir(directory, REPOSITORY_ROOT,
require_license_file=False)
except licenses.LicenseError as e:
print 'Got LicenseError while scanning ' + directory
raise
if metadata.get('License Android Compatible', 'no').upper() == 'YES':
continue
license = re.split(' [Ll]icenses?$', metadata['License'])[0]
if not third_party.LicenseIsCompatibleWithAndroid(InputApi(), license):
result.append(directory)
return result
def GetUnknownIncompatibleDirectories():
"""Gets a list of third-party directories which use licenses incompatible
with Android which are not present in the known_issues.py file.
This is used by the AOSP bot.
Returns:
A list of directories.
"""
incompatible_directories = frozenset(GetIncompatibleDirectories())
known_incompatible = []
for path, exclude_list in known_issues.KNOWN_INCOMPATIBLE.iteritems():
for exclude in exclude_list:
if glob.has_magic(exclude):
exclude_dirname = os.path.dirname(exclude)
if glob.has_magic(exclude_dirname):
print ('Exclude path %s contains an unexpected glob expression,' \
' skipping.' % exclude)
exclude = exclude_dirname
known_incompatible.append(os.path.normpath(os.path.join(path, exclude)))
known_incompatible = frozenset(known_incompatible)
return incompatible_directories.difference(known_incompatible)
class ScanResult(object):
Ok, Warnings, Errors = range(3)
def _CheckLicenseHeaders(excluded_dirs_list, whitelisted_files):
"""Checks that all files which are not in a listed third-party directory,
and which do not use the standard Chromium license, are whitelisted.
Args:
excluded_dirs_list: The list of directories to exclude from scanning.
whitelisted_files: The whitelist of files.
Returns:
ScanResult.Ok if all files with non-standard license headers are whitelisted
and the whitelist contains no stale entries;
ScanResult.Warnings if there are stale entries;
ScanResult.Errors if new non-whitelisted entries found.
"""
excluded_dirs_list = [d for d in excluded_dirs_list if not 'third_party' in d]
# Using a common pattern for third-partyies makes the ignore reg | exp shorter
excluded_dirs_list.append('third_party')
# VCS dirs
excluded_dirs_list.append('.git')
excluded_dirs_l | ist.append('.svn')
# Build output
excluded_dirs_list.append('out/Debug')
excluded_dirs_list.append('out/Release')
# 'Copyright' appears in license agreements
excluded_dirs_list.append('chrome/app/resources')
# Quickoffice js files from internal src used on buildbots. crbug.com/350472.
excluded_dirs_list.append('chrome/browser/resources/chromeos/quickoffice')
# This is a test output directory
excluded_dirs_list.append('chrome/tools/test/reference_build')
# blink style copy right headers.
excluded_dirs_list.append('content/shell/renderer/test_runner')
# blink style copy right headers.
excluded_dirs_list.append('content/shell/tools/plugin')
# This is tests directory, doesn't exist in the snapshot
excluded_dirs_list.append('content/test/data')
# This is a tests directory that doesn't exist in the shipped product.
excluded_dirs_list.append('gin/test')
# This is a test output directory
excluded_dirs_list.append('data/dom_perf')
# This is a tests directory that doesn't exist in the shipped product.
excluded_dirs_list.append('tools/perf/page_sets')
excluded_dirs_list.append('tools/perf/page_sets/tough_animation_cases')
# Histogram tools, doesn't exist in the snapshot
excluded_dirs_list.append('tools/histograms')
# Swarming tools, doesn't exist in the snapshot
excluded_dirs_list.append('tools/swarming_client')
# Arm sysroot tools, doesn't exist in the snapshot
excluded_dirs_list.append('arm-sysroot')
# Data is not part of open source chromium, but are included on some bots.
excluded_dirs_list.append('data')
# This is not part of open source chromium, but are included on some bots.
excluded_dirs_list.append('skia/tools/clusterfuzz-data')
args = ['android_webview/tools/find_copyrights.pl',
'.'
] + excluded_dirs_list
p = subprocess.Popen(args=args, cwd=REPOSITORY_ROOT, stdout=subprocess.PIPE)
lines = p.communicate()[0].splitlines()
offending_files = []
allowed_copyrights = '^(?:\*No copyright\*' \
'|20[0-9][0-9](?:-20[0-9][0-9])? The Chromium Authors\. ' \
'All rights reserved.*)$'
allowed_copyrights_re = re.compile(allowed_copyrights)
for l in lines:
entries = l.split('\t')
if entries[1] == "GENERATED FILE":
continue
copyrights = entries[1].split(' / ')
for c in copyrights:
if c and not allowed_copyrights_re.match(c):
offending_files.append(os.path.normpath(entries[0]))
break
unknown = set(offending_files) - set(whitelisted_files)
if unknown:
print 'The following files contain a third-party license but are not in ' \
'a listed third-party directory and are not whitelisted. You must ' \
'add the following files to the whitelist.\n%s' % \
'\n'.join(sorted(unknown))
stale = set(whitelisted_files) - set(offending_files)
if stale:
print 'The following files are whitelisted unnecessarily. You must ' \
'remove the following files from the whitelist.\n%s' % \
'\n'.join(sorted(stale))
missing = [f for f in whitelisted_files if not os.path.exists(f)]
if missing:
print 'The following files are whitelisted, but do not exist.\n%s' % \
'\n'.join(sorted(missing))
if unknown:
return ScanResult.Errors
elif stale or missing:
return ScanResult.Warnings
else:
return ScanResult.Ok
def _ReadFile(path):
"""Reads a file from disk.
Args:
path: The path of the file to read, relative to the root of the repository.
Returns:
The contents of the file as a string.
"""
return open(os.path.join(REPOSITORY_ROOT, path), 'rb').read()
def _FindThirdPartyDirs():
"""Gets the list of third-party directories.
Returns:
The list of third-party directories.
"""
# Please don't add here paths that have problems with license files,
# as they will end up included in Android WebView snapshot.
# In |
isard-vdi/isard | engine/engine/engine/services/db/downloads.py | Python | agpl-3.0 | 1,652 | 0.001211 | from engine.services.db import close_rethink_connection, new_rethink_connection
from engine.services.log import *
from rethinkdb import r
def get_media(id_media):
r_conn = new_rethink_connection()
d = r.table("media").get(id_media).run(r_conn)
close_rethink_connection(r_conn)
return d
def get_downloads_in_progress():
r_conn = new_rethink_connection()
try:
d = ( |
r.table("media")
.get_all(r.args(["DownloadStarting", "Downloading"]), index="status")
| .pluck("id", "path", "isard-web", "status")
.run(r_conn)
)
except r.ReqlNonExistenceError:
d = []
close_rethink_connection(r_conn)
return d
def update_status_table(table, status, id_table, detail=""):
r_conn = new_rethink_connection()
detail = str(detail)
d = {"status": status, "detail": str(detail)}
try:
r.table(table).get(id_table).update(d).run(r_conn)
except Exception as e:
logs.exception_id.debug("0042")
logs.main.error(
f"Error when updated status in table: {table}, status: {status}, id: {id_table}, detail: {detail}"
)
close_rethink_connection(r_conn)
def update_status_media_from_path(path, status, detail=""):
r_conn = new_rethink_connection()
r.table("media").filter({"path_downloaded": path}).update(
{"status": status, "detail": detail}
).run(r_conn)
close_rethink_connection(r_conn)
def update_download_percent(done, table, id):
r_conn = new_rethink_connection()
r.table(table).get(id).update({"progress": done}).run(r_conn)
close_rethink_connection(r_conn)
|
dmwelch/Py6S | setup.py | Python | gpl-3.0 | 2,575 | 0.014757 | #!/usr/bin/env python
# This file is part of Py6S.
#
# Copyright 2012 Robin Wilson and contributors listed in the CONTRIBUTORS file.
#
# Py6S is free software: you can redistribute it and/or modify
# i | t under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Py6S is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHA | NTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Py6S. If not, see <http://www.gnu.org/licenses/>.
import os
from setuptools import setup
PROJECT_ROOT = os.path.dirname(__file__)
def read_file(filepath, root=PROJECT_ROOT):
"""
Return the contents of the specified `filepath`.
* `root` is the base path and it defaults to the `PROJECT_ROOT` directory.
* `filepath` should be a relative path, starting from `root`.
"""
with open(os.path.join(root, filepath)) as fd:
text = fd.read()
return text
LONG_DESCRIPTION = read_file("README.rst")
SHORT_DESCRIPTION = "A wrapper for the 6S Radiative Transfer Model to make it easy to run simulations with a variety of input parameters, and to produce outputs in an easily processable form."
REQS = [
'pysolar==0.6',
'matplotlib',
'scipy'
]
setup(
name = "Py6S",
packages = ['Py6S', 'Py6S.Params', 'Py6S.SixSHelpers'],
install_requires = REQS,
version = "1.6.2",
author = "Robin Wilson",
author_email = "robin@rtwilson.com",
description = SHORT_DESCRIPTION,
license = "GPL",
test_suite = 'nose.collector',
url = "http://py6s.rtwilson.com/",
long_description = LONG_DESCRIPTION,
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Atmospheric Science",
"Topic :: Scientific/Engineering :: Physics",
"Topic :: Software Development :: Libraries :: Python Modules",
"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 2"
],
)
|
mrnamingo/vix4-34-enigma2-bcm | lib/python/Screens/PluginBrowser.py | Python | gpl-2.0 | 17,217 | 0.027531 | from boxbranding import getImageVersion
from urllib import urlopen
import socket
import os
from enigma import eConsoleAppContainer, eDVBDB
from Screens.Screen import Screen
from Components.ActionMap import ActionMap
from Components.PluginComponent import plugins
from Components.PluginList import PluginList, PluginEntryComponent, PluginCategoryComponent, PluginDownloadComponent
from Components.Label import Label
from Components.Language import language
from Components.Button import Button
from Components.Harddisk import harddiskmanager
from Components.Sources.StaticText import StaticText
from Components import Ipkg
from Components.config import config
from Screens.MessageBox import MessageBox
from Screens.ChoiceBox import ChoiceBox
from Screens.Console import Console
from Plugins.Plugin import PluginDescriptor
from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_ACTIVE_SKIN
from Tools.LoadPixmap import LoadPixmap
language.addCallback(plugins.reloadPlugins)
class PluginBrowserSummary(Screen):
def __init__(self, session, parent):
Screen.__init__(self, session, parent = parent)
self["entry"] = StaticText("")
self["desc"] = StaticText("")
self.onShow.append(self.addWatcher)
self.onHide.append(self.removeWatcher)
def addWatcher(self):
self.parent.onChangedEntry.append(self.selectionChanged)
self.parent.selectionChanged()
def removeWatcher(self):
self.parent.onChangedEntry.remove(self.selectionChanged)
def selectionChanged(self, name, desc):
self["entry"].text = name
self["desc"].text = desc
class PluginBrowser(Screen):
def __init__(self, session):
Screen.__init__(self, session)
Screen.setTitle(self, _("Plugin Browser"))
self.firsttime = True
self["key_red"] = Button(_("Remove plugins"))
self["key_green"] = Button(_("Download plugins"))
self.list = []
self["list"] = PluginList(self.list)
if config.usage.sort_pluginlist.value:
self["list"].list.sort()
self["actions"] = ActionMap(["WizardActions", "MenuActions"],
{
"ok": self.save,
"back": self.close,
"menu": self.openSetup,
})
self["PluginDownloadActions"] = ActionMap(["ColorActions"],
{
"red": self.delete,
"green": self.download
})
self.onFirstExecBegin.append(self.checkWarnings)
self.onShown.append(self.updateList)
self.onChangedEntry = []
self["list"].onSelectionChanged.append(self.selectionChanged)
self.onLayoutFinish.append(self.saveListsize)
def openSetup(self):
from Screens.Setup import Setup
self.session.open | (Setup, "pluginbrowsersetup")
def saveListsize(self):
listsize = self["list"].instance.size()
self.listWidth = listsize.width()
self.listHeight = listsize.height()
def createSummary(self):
return PluginBrowserSummary
| def selectionChanged(self):
item = self["list"].getCurrent()
if item:
p = item[0]
name = p.name
desc = p.description
else:
name = "-"
desc = ""
for cb in self.onChangedEntry:
cb(name, desc)
def checkWarnings(self):
if len(plugins.warnings):
text = _("Some plugins are not available:\n")
for (pluginname, error) in plugins.warnings:
text += _("%s (%s)\n") % (pluginname, error)
plugins.resetWarnings()
self.session.open(MessageBox, text = text, type = MessageBox.TYPE_WARNING)
def save(self):
self.run()
def run(self):
plugin = self["list"].l.getCurrentSelection()[0]
plugin(session=self.session)
def updateList(self):
self.pluginlist = plugins.getPlugins(PluginDescriptor.WHERE_PLUGINMENU)
self.list = [PluginEntryComponent(plugin, self.listWidth) for plugin in self.pluginlist]
self["list"].l.setList(self.list)
def delete(self):
self.session.openWithCallback(self.PluginDownloadBrowserClosed, PluginDownloadBrowser, PluginDownloadBrowser.REMOVE)
def download(self):
self.session.openWithCallback(self.PluginDownloadBrowserClosed, PluginDownloadBrowser, PluginDownloadBrowser.DOWNLOAD, self.firsttime)
self.firsttime = False
def PluginDownloadBrowserClosed(self):
self.updateList()
self.checkWarnings()
def openExtensionmanager(self):
if fileExists(resolveFilename(SCOPE_PLUGINS, "SystemPlugins/SoftwareManager/plugin.py")):
try:
from Plugins.SystemPlugins.SoftwareManager.plugin import PluginManager
except ImportError:
self.session.open(MessageBox, _("The software management extension is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
else:
self.session.openWithCallback(self.PluginDownloadBrowserClosed, PluginManager)
class PluginDownloadBrowser(Screen):
DOWNLOAD = 0
REMOVE = 1
PLUGIN_PREFIX = 'enigma2-plugin-'
lastDownloadDate = None
def __init__(self, session, type = 0, needupdate = True):
Screen.__init__(self, session)
self.type = type
self.needupdate = needupdate
self.container = eConsoleAppContainer()
self.container.appClosed.append(self.runFinished)
self.container.dataAvail.append(self.dataAvail)
self.onLayoutFinish.append(self.startRun)
self.onShown.append(self.setWindowTitle)
self.list = []
self["list"] = PluginList(self.list)
self.pluginlist = []
self.expanded = []
self.installedplugins = []
self.plugins_changed = False
self.reload_settings = False
self.check_settings = False
self.check_bootlogo = False
self.install_settings_name = ''
self.remove_settings_name = ''
if self.type == self.DOWNLOAD:
self["text"] = Label(_("Downloading plugin information. Please wait..."))
elif self.type == self.REMOVE:
self["text"] = Label(_("Getting plugin information. Please wait..."))
self.run = 0
self.remainingdata = ""
self["actions"] = ActionMap(["WizardActions"],
{
"ok": self.go,
"back": self.requestClose,
})
if os.path.isfile('/usr/bin/opkg'):
self.ipkg = '/usr/bin/opkg'
self.ipkg_install = self.ipkg + ' install'
self.ipkg_remove = self.ipkg + ' remove --autoremove'
else:
self.ipkg = 'ipkg'
self.ipkg_install = 'ipkg install -force-defaults'
self.ipkg_remove = self.ipkg + ' remove'
def go(self):
sel = self["list"].l.getCurrentSelection()
if sel is None:
return
sel = sel[0]
if isinstance(sel, str): # category
if sel in self.expanded:
self.expanded.remove(sel)
else:
self.expanded.append(sel)
self.updateList()
else:
if self.type == self.DOWNLOAD:
mbox=self.session.openWithCallback(self.runInstall, MessageBox, _("Do you really want to download the plugin \"%s\"?") % sel.name)
mbox.setTitle(_("Download plugins"))
elif self.type == self.REMOVE:
mbox=self.session.openWithCallback(self.runInstall, MessageBox, _("Do you really want to remove the plugin \"%s\"?") % sel.name, default = False)
mbox.setTitle(_("Remove plugins"))
def requestClose(self):
if self.plugins_changed:
plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
if self.reload_settings:
self["text"].setText(_("Reloading bouquets and services..."))
eDVBDB.getInstance().reloadBouquets()
eDVBDB.getInstance().reloadServicelist()
plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
self.container.appClosed.remove(self.runFinished)
self.container.dataAvail.remove(self.dataAvail)
self.close()
def resetPostInstall(self):
try:
del self.postInstallCall
except:
pass
def installDestinationCallback(self, result):
if result is not None:
dest = result[1]
if dest.startswith('/'):
# Custom install path, add it to the list too
dest = os.path.normpath(dest)
extra = '--add-dest %s:%s -d %s' % (dest,dest,dest)
Ipkg.opkgAddDestination(dest)
else:
extra = '-d ' + dest
self.doInstall(self.installFinished, self["list"].l.getCurrentSelection()[0].name + ' ' + extra)
else:
self.resetPostInstall()
def runInstall(self, val):
if val:
if self.type == self.DOWNLOAD:
if self["list"].l.getCurrentSelection()[0].name.startswith("picons-"):
supported_filesystems = frozenset(('ext4', 'ext3', 'ext2', 'reiser', 'reiser4', 'jffs2', 'ubifs', 'rootfs'))
candidates = []
import Components.Harddisk
mounts = Components.Harddisk.getProcMounts()
for partition in harddiskmanager.getMountedPartitions(False, mounts):
if partition.filesyste |
tpeek/django-imager | imagersite/imager_images/migrations/0006_auto_20150729_1539.py | Python | mit | 729 | 0.002743 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('imager_images', '0005_auto_20150728_0129'),
]
operations = [
migrations. | AlterField(
model_name='album',
name='privacy',
field=models.CharField(max_length=64, choices=[(b'Private', b'Private'), (b'Shared', b'Shared'), (b'Public', b'Public')]),
),
migrations.AlterField(
model_name='photo',
name='privacy',
field=models.CharField(max_length=64, choices=[(b'Private', b'Private'), (b'Shared', b'Shared'), (b'Public', b'Public')]),
| ),
]
|
MTG/essentia | test/src/unittests/streaming/test_tensortopool.py | Python | agpl-3.0 | 7,481 | 0.002673 | #!/usr/bin/env python
# Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the Affero GNU General Public License
# version 3 along with this program. If not, see http://www.gnu.org/licenses/
from essentia_test import *
from essentia.streaming import *
class TestTensorToPool(TestCase):
def identityOperation(self, frameSize=1024, hopSize=512, patchSize=187,
lastPatchMode='discard', accumulate=False):
batchHopSize = -1 if accumulate else 1
filename = join(testdata.audio_dir, 'recorded', 'cat_purrrr.wav')
namespace='tensor'
ml = MonoLoader(filename=filename)
fc = FrameCutter(frameSize=frameSize, hopSize=hopSize)
vtt = VectorRealToTensor(shape=[1, 1, patchSize, frameSize],
lastPatchMode=lastPatchMode)
ttp = TensorToPool(namespace=namespace)
ptt = PoolToTensor(namespace=namespace)
ttv = TensorToVectorReal()
pool = Pool()
ml.audio >> fc.signal
fc.frame >> vtt.frame
fc.frame >> (pool, "framesIn")
vtt.tensor >> ttp.tensor
ttp.pool >> ptt.pool
ptt.tensor >> ttv.tensor
ttv.frame >> (pool, "framesOut")
run(ml)
return pool['framesOut'], pool['framesIn']
def testFramesToTensorAndBackToFramesDiscard(self):
# The test audio file has 430 frames.
# Setting the patchSize to produce exactly 10 patches.
numberOfFrames = 43
found, expected = self.identityOperation(patchSize=numberOfFrames,
lastPatchMode='discard')
self.assertAlmostEqualMatrix(found, expected, 1e-8)
# Now the number of frames does not match an exact number of patches.
# The expected output is trimmed to the found shape as with
# lastPatchMode='discard' the remaining frames not fitting into a
# patch are discarded.
found, expected = self.identityOperation(frameSize=256, hopSize=128,
lastPatchMode='discard')
self.assertAlmostEqualMatrix(found, expected[:found.shape[0], :], 1e-8)
# Increase the patch size.
found, expected = self.identityOperation(frameSize=256, hopSize=128,
patchSize=300, lastPatchMode='discard')
self.assertAlmostEqualMatrix(found, expected[:found.shape[0], :], 1e-8)
def testFramesToTensorAndBackToFramesDiscardAccumulate(self):
# Repeat the tests in accumulate mode. Here the patches are stored
# internally and pushed at once at the end of the stream.
numberOfFrames = 43
found, expected = self.identityOperation(patchSize=numberOfFrames,
lastPatchMode='discard',
accumulate=True)
self.assertAlmostEqualMatrix(found, expected, 1e-8)
found, expected = self.identityOperation(frameSize=256, hopSize=128,
lastPatchMode='discard',
accumulate=True)
self.assertAlmostEqualMatrix(found, expected[:found.shape[0], :], 1e-8)
found, expected = self.identityOperation(frameSize=256, hopSize=128,
patchSize=300, lastPatchMode='discard',
accumulate=True)
self.assertAlmostEqualMatrix(found, expected[:found.shape[0], :], 1e-8)
def testFramesToTensorAndBackToFramesRepeat(self):
# Repeat the experiments with lastPatchMode='repeat'. Now if there
# are remaining frames they will be looped into a final patch.
# The found shape will be equal or bigger than the exp | ected one.
# Found values will be trimmed to | fit the expected shape.
# No remaining frames.
numberOfFrames = 43
found, expected = self.identityOperation(patchSize=numberOfFrames,
lastPatchMode='repeat')
self.assertAlmostEqualMatrix(found, expected, 1e-8)
# Some remaining frames.
found, expected = self.identityOperation(frameSize=256, hopSize=128,
lastPatchMode='repeat')
self.assertAlmostEqualMatrix(found[:expected.shape[0], :], expected, 1e-8)
# Increase the patch size.
found, expected = self.identityOperation(frameSize=256, hopSize=128,
patchSize=300, lastPatchMode='repeat')
self.assertAlmostEqualMatrix(found[:expected.shape[0], :], expected, 1e-8)
def testFramesToTensorAndBackToFramesRepeatAccumulate(self):
# The behavior should be the same in accumulate mode.
numberOfFrames = 43
found, expected = self.identityOperation(patchSize=numberOfFrames,
lastPatchMode='repeat',
accumulate=True)
self.assertAlmostEqualMatrix(found, expected, 1e-8)
found, expected = self.identityOperation(frameSize=256, hopSize=128,
lastPatchMode='repeat',
accumulate=True)
self.assertAlmostEqualMatrix(found[:expected.shape[0], :], expected, 1e-8)
found, expected = self.identityOperation(frameSize=256, hopSize=128,
patchSize=300, lastPatchMode='repeat',
accumulate=True)
self.assertAlmostEqualMatrix(found[:expected.shape[0], :], expected, 1e-8)
def testInvalidParam(self):
self.assertConfigureFails(TensorToPool(), {'mode': ''})
def testRepeatMode(self):
# The test audio file has 430 frames. If patchSize is set to 428 with
# lastPatchMode='repeat' VectorRealToTensor will produce a second
# patch of 428 frames by looping the last two spare samples.
numberOfFrames = 428
loopFrames = 430 - numberOfFrames
found, expected = self.identityOperation(patchSize=numberOfFrames,
lastPatchMode='repeat')
expected = numpy.vstack([expected[:numberOfFrames]] + # frames for the first patch
[expected[numberOfFrames:numberOfFrames + loopFrames]] * # remaining frames for the second patch
(numberOfFrames // loopFrames)) # number of repetitions to fill the second patch
self.assertAlmostEqualMatrix(found, expected, 1e-8)
suite = allTests(TestTensorToPool)
if __name__ == '__main__':
TextTestRunner(verbosity=2).run(suite)
|
inventree/InvenTree | InvenTree/stock/migrations/0068_stockitem_serial_int.py | Python | mit | 390 | 0 | # Generated by Django 3.2.5 on 2021-11-09 23:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stock', '0067_al | ter_stockitem_part'),
]
operations = [
migrations. | AddField(
model_name='stockitem',
name='serial_int',
field=models.IntegerField(default=0),
),
]
|
tiffanyjaya/kai | vendors/pdfminer.six/pdfminer/pdfdevice.py | Python | mit | 5,469 | 0.001828 |
from .pdffont import PDFUnicodeNotDefined
from . import utils
## PDFDevice
##
class PDFDevice(object):
def __init__(self, rsrcmgr):
self.rsrcmgr = rsrcmgr
self.ctm = None
return
def __repr__(self):
return '<PDFDevice>'
def close(self):
return
def set_ctm(self, ctm):
self.ctm = ctm
return
def begin_tag(self, tag, props=None):
return
def end_tag(self):
return
def do_tag(self, tag, props=None):
return
def begin_page(self, page, ctm):
return
def end_page(self, page):
return
def begin_figure(self, name, bbox, matrix):
return
def end_figure(self, name):
return
def paint_path(self, graphicstate, stroke, fill, evenodd, path):
return
def render_image(self, name, stream):
return
def render_string(self, textstate, seq):
return
## PDFTextDevice
##
class PDFTextDevice(PDFDevice):
def render_string(self, textstate, seq):
matrix = utils.mult_matrix(textstate.matrix, self.ctm)
font = textstate.font
fontsize = textstate.fontsize
scaling = textstate.scaling * .01
charspace = textstate.charspace * scaling
wordspace = textstate.wordspace * scaling
rise = textstate.rise
if font.is_multibyte():
wordspace = 0
dxscale = .001 * fontsize * scaling
if font.is_vertical():
textstate.linematrix = self.render_string_vertical(
seq, matrix, textstate.linematrix, font, fontsize,
scaling, charspace, wordspace, rise, dxscale)
else:
textstate.linematrix = self.render_string_horizontal(
seq, matrix, textstate.linematrix, font, fontsize,
scaling, charspace, wordspace, rise, dxscale)
return
def render_string_horizontal(self, seq, matrix, pos,
font, fontsize, scaling, charspace, wordspace, rise, dxscale):
(x, y) = pos
needcharspace = False
for obj in seq:
if utils.isnumber(obj):
x -= obj*dxscale
needcharspace = True
else:
for cid in font.decode(obj):
if needcharspace:
x += charspace
x += self.render_char(utils.translate_matrix(matrix, (x, y)),
font, fontsize, scaling, rise, cid)
if cid == 32 and wordspace:
x += wordspace
needcharspace = True
return (x, y)
def render_string_vertical(self, seq, matrix, pos,
font, fontsize, scaling, charspace, wordspace, rise, dxscale):
(x, y) = pos
needcharspace = False
for obj in seq:
if utils.isnumber(obj):
y -= obj*dxscale
needcharspace = True
else:
for cid in font.decode(obj):
if needcharspace:
y += charspace
y += self.render_char(utils.translate_matrix(matrix, (x, y)),
font, fontsize, scaling, rise, cid)
if cid == 32 and wordspace:
y += wordspace
needcharspace = True
return (x, y)
def render_char(self, matrix, | font, fontsize, scaling, rise, cid):
return 0
## TagExtractor
##
class TagExtractor(PDFDevice):
def __init__(self, rsrcmgr, outfp, codec='utf-8'):
PDFDevice.__init__(self, rsrcmgr)
self.outfp = outfp
self.codec = codec
self.pageno = 0
| self._stack = []
return
def render_string(self, textstate, seq):
font = textstate.font
text = ''
for obj in seq:
obj = utils.make_compat_str(obj)
if not isinstance(obj, str):
continue
chars = font.decode(obj)
for cid in chars:
try:
char = font.to_unichr(cid)
text += char
except PDFUnicodeNotDefined:
print(chars)
pass
self.outfp.write(utils.enc(text, self.codec))
return
def begin_page(self, page, ctm):
output = '<page id="%s" bbox="%s" rotate="%d">' % (self.pageno, utils.bbox2str(page.mediabox), page.rotate)
self.outfp.write(utils.make_compat_bytes(output))
return
def end_page(self, page):
self.outfp.write(utils.make_compat_bytes('</page>\n'))
self.pageno += 1
return
def begin_tag(self, tag, props=None):
s = ''
if isinstance(props, dict):
s = ''.join(' %s="%s"' % (utils.enc(k), utils.enc(str(v))) for (k, v)
in sorted(props.iteritems()))
out_s = '<%s%s>' % (utils.enc(tag.name), s)
self.outfp.write(utils.make_compat_bytes(out_s))
self._stack.append(tag)
return
def end_tag(self):
assert self._stack, str(self.pageno)
tag = self._stack.pop(-1)
out_s = '</%s>' % utils.enc(tag.name)
self.outfp.write(utils.make_compat_bytes(out_s))
return
def do_tag(self, tag, props=None):
self.begin_tag(tag, props)
self._stack.pop(-1)
return
|
sebp/scikit-survival | doc/conf.py | Python | gpl-3.0 | 12,460 | 0.001926 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# scikit-survival documentation build configuration file
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
from datetime import datetime
import inspect
import os
from pathlib import Path
import re
import sys
from nbconvert.preprocessors import Preprocessor
import nbsphinx
from setuptools_scm import get_version
# on_rtd is whether we are on readthedocs.org, this line of code grabbed from docs.readthedocs.org
# https://docs.readthedocs.io/en/latest/faq.html?highlight=environ#how-do-i-change-behavior-for-read-the-docs
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
if on_rtd:
sys.path.insert(0, os.path.abspath(os.path.pardir))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.8'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.coverage',
'sphinx.ext.extlinks',
'sphinx.ext.linkcode',
'sphinx.ext.mathjax',
'sphinx.ext.napoleon',
'nbsphinx',
]
autosummary_generate = True
autodoc_default_options = {
'members': None,
'inherited-members': None,
}
# Napoleon settings
napoleon_google_docstring = False
napoleon_include_init_with_doc = False
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'scikit-survival'
current_year = datetime.utcnow().year
copyright = f'2015-{current_year}, Sebastian Pölsterl and contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The full version, including alpha/beta/rc tags.
if on_rtd:
release = get_version(root='..', relative_to=__file__)
else:
import sksurv
release = sksurv.__version__
# The short X.Y.Z version.
version = '.'.join(release.split('.')[:3])
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# The default language to highlight source code in.
highlight_language = 'none'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build', '**/README.*', 'Thumbs.db', '.DS_Store']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
# pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
nbsphinx_execute = 'never'
nbsphinx_prolog = r"""
{% set docna | me = "doc/" + env.doc2path(env.docname, base=None) %}
{% set notebook = env.doc2path(env.docname, base=None)|replace("user_guide/", "notebooks/") %}
{% set branch = 'master' if 'dev' in env.config.release else 'v{}'.format(env.config.release) %}
.. raw:: html
<div class | ="admonition note" style="line-height: 150%;">
This page was generated from
<a class="reference external" href="https://github.com/sebp/scikit-survival/blob/{{ branch|e }}/{{ docname|e }}">{{ docname|e }}</a>.<br/>
Interactive online version:
<span style="white-space: nowrap;"><a href="https://mybinder.org/v2/gh/sebp/scikit-survival/{{ branch|e }}?urlpath=lab/tree/{{ notebook|e }}"><img alt="Binder badge" src="https://mybinder.org/badge_logo.svg" style="vertical-align:text-bottom"></a>.</span>
</div>
"""
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'pydata_sphinx_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
"github_url": "https://github.com/sebp/scikit-survival",
}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = "scikit-survival {0}".format(version)
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
html_css_files = ['custom.css']
html_js_files = ['buttons.js']
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
extlinks = {
'issue': ('https://github.com/sebp/scikit-survival/issues/%s', '#'),
}
def linkcode_resolve(domain, info):
"""
Determine the URL corresponding to Python object
Adapted from scipy.
"""
import sksurv
if domain != 'py':
return None
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
return None
obj = submod
for part in fullname.split('.'):
try:
obj = getattr(obj, part)
except AttributeError:
return None
try:
fn = inspect.getsourcefile(obj)
except TypeError:
fn = None
if fn is None and hasattr(obj, '__module__'):
fn = inspect.getsourcefile(sys.modules[obj.__module__])
if fn is None:
return None
try:
source, lineno = inspect.getsourcelines(obj)
except ValueError:
lineno = None
if lineno:
linespec = '#L%d-L%d' % (lineno, lineno + len(source) - 1)
else:
linespec = ''
startdir = Path(sksurv.__file__).parent.parent.absolute()
if not fn.startswith(str(startdir)): # not in sksurv
return None
fn = '/'.join(Path(fn).relative_to(startdir).parts)
if fn.startswith('sksurv/'):
m = re.match(r'^.*dev[0-9]+\+g([a-f0-9]+)$', release)
if m:
branch = m.group(1)
elif 'dev' in release:
branch = 'master'
else:
branch = 'v{}'.format(release)
return 'https://github.com/sebp/scikit-survival/blob/{branch}/{filename}{linespec}'.format(
branch=branch,
|
chenjj/dionaea | modules/python/scripts/ihandlers.py | Python | gpl-2.0 | 5,570 | 0.024237 | #********************************************************************************
#* Dionaea
#* - catches bugs -
#*
#*
#*
#* Copyright (C) 2010 Markus Koetter & Tan Kean Siong
#* Copyright (C) 2009 Paul Baecher & Markus Koetter & Mark Schloesser
#*
#* 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.
#*
#* This program is distributed in the hope that it will be useful,
#* but WITHOUT ANY WARRANTY; without even the implied warranty of
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#* GNU General Public License for more details.
#*
#* You should have received a copy of the GNU General Public License
#* along with this program; if not, write to the Free Software
#* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#*
#*
#* contact nepenthesdev@gmail.com
#*
#*******************************************************************************/
import logging
import os
import imp
from dionaea.core import g_dionaea
# service imports
import dionaea.tftp
import dionaea.cmd
import dionaea.emu
import dionaea.store
import dionaea.test
import dionaea.ftp
logger = logging.getLogger('ihandlers')
logger.setLevel(logging.DEBUG)
# reload service imports
#imp.reload(dionaea.tftp)
#imp.reload(dionaea.ftp)
#imp.reload(dionaea.cmd)
#imp.reload(dionaea.emu)
#imp.reload(dionaea.store)
# global handler list
# keeps a ref on our handlers
# allows restarting
global g_handlers
def start():
logger.warn("START THE IHANDLERS")
for i in g_handlers:
method = getattr(i, "start", None)
if method != None:
method()
def new():
global g_handlers
g_handlers = []
if "hpfeeds" in g_dionaea.config()['modules']['python']['ihandlers']['handlers'] and 'hpfeeds' in g_dionaea.config()['modules']['python']:
import dionaea.hpfeeds
for client in g_dionaea.config()['modules']['python']['hpfeeds']:
conf = g_dionaea.config()['modules']['python']['hpfeeds'][client]
x = dionaea.hpfeeds.hpfeedihandler(conf)
g_handlers.append(x)
if "ftpdownload" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.ftp
g_handlers.append(dionaea.ftp.ftpdownloadhandler('dionaea.download.offer'))
if "tftpdownload" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
g_handlers.append(dionaea.tftp.tftpdownloadhandler('dionaea.download.offer'))
if "emuprofile" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
g_handlers.append(dionaea.emu.emuprofilehandler('dionaea.module.emu.profile'))
if "cmdshell" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
g_handlers.append(dionaea.cmd.cmdshellhandler('dionaea.service.shell.*'))
if "store" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
g_handlers.append(dionaea.store.storehandler('dionaea.download.complete'))
if "uniquedownload" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
g_handlers.append(dionaea.test.uniquedownloadihandler('dionaea.download.complete.unique'))
if "surfids" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.surfids
g_handlers.append(dionaea.surfids.surfidshandler('*'))
if "logsql" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.logsql
g_handlers.append(dionaea.logsql.logsqlhandler("*"))
if "p0f" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.p0f
g_handlers.append(dionaea.p0f.p0fhandler(g_dionaea.config()['modules']['python']['p0f']['path']))
if "logxmpp" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.logxmpp
from random import choice
import stri | ng
for client in g_dionaea.config()['modules']['python']['logxmpp']:
conf = g_dionaea.config()['modules']['python']['logxmpp'][client]
if 'resource' in conf:
resource = conf['resource']
else:
resource = ''.join([choice(string.ascii_letters) for i in range(8)])
print("client %s \n\tserver %s:%s username %s password %s resource %s muc %s\n\t%s" % (client, conf['server'], conf['port'], conf['username'], conf['password'], | resource, conf['muc'], conf['config']))
x = dionaea.logxmpp.logxmpp(conf['server'], int(conf['port']), conf['username'], conf['password'], resource, conf['muc'], conf['config'])
g_handlers.append(x)
if "nfq" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.nfq
g_handlers.append(dionaea.nfq.nfqhandler())
if "virustotal" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.virustotal
g_handlers.append(dionaea.virustotal.virustotalhandler('*'))
if "mwserv" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.mwserv
g_handlers.append(dionaea.mwserv.mwservhandler('*'))
if "submit_http" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.submit_http
g_handlers.append(dionaea.submit_http.handler('*'))
if "fail2ban" in g_dionaea.config()['modules']['python']['ihandlers']['handlers']:
import dionaea.fail2ban
g_handlers.append(dionaea.fail2ban.fail2banhandler())
def stop():
global g_handlers
for i in g_handlers:
logger.debug("deleting %s" % str(i))
i.stop()
del i
del g_handlers
|
OpnSrcConstruction/OSCbashRCs | .ipython/profile_debug/ipython_config.py | Python | unlicense | 23,357 | 0.014043 | # Configuration file for ipython.
#------------------------------------------------------------------------------
# InteractiveShellApp(Configurable) configuration
#------------------------------------------------------------------------------
## A Mixin for applications that start InteractiveShell instances.
#
# Provides configurables for loading extensions and executing files as part of
# configuring a Shell environment.
#
# The following methods should be called by the :meth:`initialize` method of the
# subclass:
#
# - :meth:`init_path`
# - :meth:`init_shell` (to be implemented by the subclass)
# - :meth:`init_gui_pylab`
# - :meth:`init_extensions`
# - :meth:`init_code`
## Execute the given command string.
#c.InteractiveShellApp.code_to_run = ''
## Run the file referenced by the PYTHONSTARTUP environment variable at IPython
# startup.
#c.InteractiveShellApp.exec_PYTHONSTARTUP = True
## List of files to run at IPython startup.
#c.InteractiveShellApp.exec_files = []
## lines of code to run at IPython startup.
#c.InteractiveShellApp.exec_lines = []
## A list of dotted module names of IPython extensions to load.
#c.InteractiveShellApp.extensions = []
## dotted module name of an IPython extension to load.
#c.InteractiveShellApp.extra_extension = ''
## A file to be run
#c.InteractiveShellApp.file_to_run = ''
## Enable GUI event loop integration with any of ('glut', 'gtk', 'gtk2', 'gtk3',
# 'osx', 'pyglet', 'qt', 'qt4', 'qt5', 'tk', 'wx', 'gtk2', 'qt4').
#c.InteractiveShellApp.gui = None
## Should variables loaded at startup (by startup files, exec_lines, etc.) be
# hidden from tools like %who?
#c.InteractiveShellApp.hide_initial_ns = True
## Configure matplotlib for interactive use with the default matplotlib backend.
#c.InteractiveShellApp.matplotlib = None
## Run the module as a script.
#c.InteractiveShellApp.module_to_run = ''
## Pre-load matplotlib and numpy for interactive use, selecting a particular
# matplotlib backend and loop integration.
#c.InteractiveShellApp.pylab = None
## If true, IPython will populate the user namespace with numpy, pylab, etc. and
# an ``import *`` is done from numpy and pylab, when using pylab mode.
#
# When False, pylab mode should not import any names into the user namespace.
#c.InteractiveShellApp.pylab_import_all = True
## Reraise exceptions encountered loading IPython extensions?
#c.InteractiveShellApp.reraise_ipython_extension_failures = False
#------------------------------------------------------------------------------
# Application(SingletonConfigurable) configuration
#------------------------------------------------------------------------------
## This is an application.
## The date format used by logging formatters for %(asctime)s
#c.Application.log_datefmt = '%Y-%m-%d %H:%M:%S'
## The Logging format template
#c.Application.log_format = '[%(name)s]%(highlevel)s %(message)s'
## Set the log level by value or name.
#c.Application.log_level = 30
#------------------------------------------------------------------------------
# BaseIPythonApplication(Application) configuration
#------------------------------------------------------------------------------
## IPython: an enhanced interactive Python shell.
## Whether to create profile dir if it doesn't exist
#c.BaseIPythonApplication.auto_create = False
## Whether to install the default config files into the profile dir. If a new
# profile is being created, and IPython contains config files for that profile,
# then they will be staged into the new directory. Otherwise, default config
# files will be automatically generated.
#c.BaseIPythonApplication.copy_config_files = False
## Path to an extra config file to load.
#
# If specified, load this config file in addition to any other IPython config.
#c.BaseIPythonApplication.extra_config_file = ''
## The name of the IPython directory. This directory is used for logging
# configuration (through profiles), history storage, etc. The default is usually
# $HOME/.ipython. This option can also be specified through the environment
# variable IPYTHONDIR.
#c.BaseIPythonApplication.ipython_dir = ''
## Whether to overwrite existing config files when copying
#c.BaseIPythonApplication.overwrite = False
## The IPython profile to use.
#c.BaseIPythonApplication.profile = 'default'
## Create a massive crash report when IPython encounters what may be an internal
# error. The default is to append a short message to the usual traceback
#c.BaseIPythonApplication.verbose_crash = False
#------------------------------------------------------------------------------
# TerminalIPythonApp(BaseIPythonApplication,InteractiveShellApp) configuration
#------------------------------------------------------------------------------
## Whether to display a banner upon starting IPython.
#c.TerminalIPythonApp.display_banner = True
## If a command or file is given via the command-line, e.g. 'ipython foo.py',
# start an interactive shell after executing the file or command.
#c.TerminalIPythonApp.force_interact = False
## Class to use to instantiate the TerminalInteractiveShell object. Useful for
# custom Frontends
#c.TerminalIPythonApp.interactive_shell_class = 'IPython.terminal.interactiveshell.TerminalInteractiveShell'
## Start IPython quickly by skipping the loading of config files.
#c.TerminalIPythonApp.quick = False
#------------------------------------------------------------------------------
# InteractiveShell(SingletonConfigurable) configuration
#------------------------------------------------------------------------------
## An enhanced, interactive shell for Python.
## 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying which
# nodes should be run interactively (displaying output from expressions).
#c.InteractiveShell.ast_node_interactivity = 'last_expr'
## A list of ast.NodeTransformer subclass instances, which will be applied to
# user input before code is run.
#c.InteractiveShell.ast_transformers = []
## Make IPython automatically call any callable object even if you didn't type
# explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically.
# The value can be '0' to disable the feature, '1' for 'smart' autocall, where
# it is not applied if there are no more arguments on the line, and '2' for
# 'full' autocall, where all callable objects are automatically called (even if
# no arguments are present).
#c.InteractiveShell.autocall = 0
## Autoindent IPython code entered interactively.
#c.InteractiveShell.autoindent = True
## Enable magic commands to be called without the leading %.
#c.InteractiveShell.automagic = True
## The part of the banner to be printed before the profile
#c.InteractiveShell.banner1 = "Python | 3.5.2 (default, Nov 23 2017, 16:37:01) \nType 'copyright', 'credits' or 'license' for more information\nIPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.\n"
## The part of the banner to be printed after the profile
#c.InteractiveShell.b | anner2 = ''
## Set the size of the output cache. The default is 1000, you can change it
# permanently in your config file. Setting it to 0 completely disables the
# caching system, and the minimum value accepted is 3 (if you provide a value
# less than 3, it is reset to 0 and a warning is issued). This limit is defined
# because otherwise you'll spend more time re-flushing a too small cache than
# working
#c.InteractiveShell.cache_size = 1000
## Use colors for displaying information about objects. Because this information
# is passed through a pager (like 'less'), and some pagers get confused with
# color codes, this capability can be turned off.
#c.InteractiveShell.color_info = True
## Set the color scheme (NoColor, Neutral, Linux, or LightBG).
#c.InteractiveShell.colors = 'Neutral'
##
#c.InteractiveShell.debug = False
## Don't call post-execute functions that have failed in the past.
#c.InteractiveShell.disable_failing_post_execute = False
## If True, anything that would be passed to the pager will be displayed as
# regular output instead.
#c.InteractiveShell.display_page = False
## (Provisional API) enables html re |
donhoffman/pi-keypad-controller | src/door_latch.py | Python | gpl-2.0 | 4,286 | 0.0028 | import datetime
import logging
import sqlite3
import time
from os import environ
import relays
class Latch:
DIGIT_TIMEOUT = 60
LOCKOUT_TIMEOUT = 300
LOCKOUT_THRESHOLD = 5
VALID_CH = set('0123456789#*')
def __init__(self, latch_id, latch_index):
self._logger = logging.getLogger(__name__)
self._latch_id = unicode(latch_id).lower()
self._latch_index = int(latch_index)
self._digits = ''
self._time_lastchar = 0
self._time_end_lockout = None
self._invalid_count = 0
# noinspection PyMethodMayBeStatic
def _db_connect(self):
db_name = environ.get('DB_BASE_PATH', './') + 'keypad.db'
return sqlite3.connect(db_name, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
def input(self, c):
c = str(c)
if c not in self.VALID_CH:
return
now = time.time()
if (now - self._time_lastchar) > self.DIGIT_TIMEOUT:
self._digits = ''
self._time_lastchar = now
if c not in '#*':
self._digits += c
return
if self._digits == '':
logging.info('Empty code entered')
return
code = int(self._digits)
self._digits = ''
if c == '#':
if self._validate_code(code):
logging.info('Opening door \'%s\'', self._latch_id)
relays.fire(self._latch_index)
if c == '*':
self._do_command(code)
def _validate_code(self, code):
#Check for lockout
if self._time_end_lockout:
if time.time() < self._time_end_lockout:
logging.error("Code entered during lockout.")
return False
self._time_end_lockout = None
logging.info('Lockout period ended.')
conn = None
try:
conn = self._db_connect()
c = conn.cursor()
#Is this a valid user
c.execute('SELECT name FROM users WHERE code=?', (int(code),) )
row = c.fetchone()
if not row:
logging.error('Unknown code entered.')
self._invalid_count += 1
if self._invalid_count > self.LOCKOUT_THRESHOLD:
logging.info( | 'Too may attempts. Lockout for %s seconds', int(self.LOCKOUT_TIMEOUT))
self._invalid_count = 0
self._time_end_lockout = time.time() + self.LOCKOUT_TIMEOUT
return False
#Note: we don't lock out on permission issues
#Valid user. Check permissions.
name = unicode( | row[0])
c.execute('''
SELECT enabled, use_timeout, not_before, not_after
FROM permissions WHERE name=? AND keypad_id=?''', (name, self._latch_id))
row = c.fetchone()
if not row:
logging.error('User \'%s\' has no permissions.', name)
return False
enabled = bool(row[0])
if not enabled:
logging.error("Attempt to use disabled code for user %s", name)
return False
# noinspection PyUnusedLocal
use_timeout = row[1]
not_before = row[2]
not_after = row[3]
if not_before and datetime.now() < not_before:
logging.error("Attempt to use code too soon for user %s", name)
return False
if not_after and datetime.now() > not_after:
logging.error("Attempt to use expired code for user %s", name)
return False
logging.info("Valid code entered by user %s", name)
self._invalid_count = 0
return True
except sqlite3.Error as e:
logging.error("Database error: %s", e)
return False
finally:
if conn:
conn.close()
def _do_command(self, code):
pass
if __name__ == '__main__':
import logging
logging.basicConfig(filename='./keypad.log', level=logging.DEBUG,
format='%(asctime)s | %(levelname)s | %(message)s')
test_code = '12345#'
latch = Latch('Outside', 0)
for ch in test_code:
latch.input(ch)
|
ArcherSys/ArcherSys | skulpt/src/lib/pythonds/graphs/adjGraph.py | Python | mit | 3,004 | 0.015313 | #
# adjGraph
#
# Created by Brad Miller on 2005-02-24.
# Copyright (c) 2005 Brad Miller, David Ranum, Luther College. All rights reserved.
#
import sys
import os
import unittest
class Graph:
def __init__(self):
self.vertices = {}
self.numVertices = 0
def addVertex(self,key):
self.numVertices = self.numVertices + 1
newVertex = Vertex(key)
self.vertices[key] = newVertex
return newVertex
def getVertex(self,n):
if n in self.vertices:
return self.vertices[n]
else:
return None
def __contains__(self,n):
return n in self.vertices
def addEdge(self,f,t,cost=0):
if f not in self.vertices:
nv = self.addVertex(f)
if t not in self.vertices:
nv = self.addVertex(t)
self.vertices[f].addNeighbor(self.vertices[t],cost)
def getVertices(self):
return list(self.vertices.keys())
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self,num):
self.id = num
self.connectedTo = {}
self.color = 'white'
se | lf.dist = sys.maxsize
self.pred = None
| self.disc = 0
self.fin = 0
# def __lt__(self,o):
# return self.id < o.id
def addNeighbor(self,nbr,weight=0):
self.connectedTo[nbr] = weight
def setColor(self,color):
self.color = color
def setDistance(self,d):
self.dist = d
def setPred(self,p):
self.pred = p
def setDiscovery(self,dtime):
self.disc = dtime
def setFinish(self,ftime):
self.fin = ftime
def getFinish(self):
return self.fin
def getDiscovery(self):
return self.disc
def getPred(self):
return self.pred
def getDistance(self):
return self.dist
def getColor(self):
return self.color
def getConnections(self):
return self.connectedTo.keys()
def getWeight(self,nbr):
return self.connectedTo[nbr]
def __str__(self):
return str(self.id) + ":color " + self.color + ":disc " + str(self.disc) + ":fin " + str(self.fin) + ":dist " + str(self.dist) + ":pred \n\t[" + str(self.pred)+ "]\n"
def getId(self):
return self.id
class adjGraphTests(unittest.TestCase):
def setUp(self):
self.tGraph = Graph()
def testMakeGraph(self):
gFile = open("test.dat")
for line in gFile:
fVertex, tVertex = line.split('|')
fVertex = int(fVertex)
tVertex = int(tVertex)
self.tGraph.addEdge(fVertex,tVertex)
for i in self.tGraph:
adj = i.getAdj()
for k in adj:
print(i, k)
if __name__ == '__main__':
unittest.main()
|
MungoRae/home-assistant | tests/components/device_tracker/test_init.py | Python | apache-2.0 | 29,746 | 0.000034 | """The tests for the device tracker component."""
# pylint: disable=protected-access
import asyncio
import json
import logging
import unittest
from unittest.mock import call, patch
from datetime import datetime, timedelta
import os
from homeassistant.components import zone
from homeassistant.core import callback, State
from homeassistant.setup import setup_component
from homeassistant.helpers import discovery
from homeassistant.loader import get_component
from homeassistant.util.async import run_coroutine_threadsafe
import homeassistant.util.dt as dt_util
from homeassistant.const import (
ATTR_ENTITY_ID, ATTR_ENTITY_PICTURE, ATTR_FRIENDLY_NAME, ATTR_HIDDEN,
STATE_HOME, STATE_NOT_HOME, CONF_PLATFORM, ATTR_ICON)
import homeassistant.components.device_tracker as device_tracker
from homeassistant.exceptions import HomeAssistantError
from homeassistant.remote import JSONEncoder
from tests.common import (
get_test_home_assistant, fire_time_changed, fire_service_discovered,
patch_yaml_files, assert_setup_component, mock_restore_cache, mock_coro)
from ...test_util.aiohttp import mock_aiohttp_client
TEST_PLATFORM = {device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}}
_LOGGER = logging.getLogger(__name__)
class TestComponentsDeviceTracker(unittest.TestCase):
"""Test the Device tracker."""
hass = None # HomeAssistant
yaml_devices = None # type: str
# pylint: disable=invalid-name
def setUp(self):
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
self.yaml_devices = self.hass.config.path(device_tracker.YAML_DEVICES)
# pylint: disable=invalid-name
def tearDown(self):
"""Stop everything that was started."""
if os.path.isfile(self.yaml_devices):
os.remove(self.yaml_devices)
self.hass.stop()
def test_is_on(self):
"""Test is_on method."""
entity_id = device_tracker.ENTITY_ID_FORMAT.format('test')
self.hass.states.set(entity_id, STATE_HOME)
self.assertTrue(device_tracker.is_on(self.hass, entity_id))
self.hass.states.set(entity_id, STATE_NOT_HOME)
self.assertFalse(device_tracker.is_on(self.hass, entity_id))
# pylint: disable=no-self-use
def test_reading_broken_yaml_config(self):
"""Test when known devices contains invalid data."""
files = {'empty.yaml': '',
'nodict.yaml': '100',
'badkey.yaml': '@:\n name: Device',
'noname.yaml': 'my_device:\n',
'allok.yaml': 'My Device:\n name: Device',
'oneok.yaml': ('My Device!:\n name: Device\n'
'bad_device:\n nme: Device')}
args = {'hass': self.hass, 'consider_home': timedelta(seconds=60)}
with patch_yaml_files(files):
assert device_tracker.load_config('empty.yaml', **args) == []
assert device_tracker.load_config('nodict.yaml', **args) == []
assert device_tracker.load_config('noname.yaml', **args) == []
assert device_tracker.load_config('badkey.yaml', **args) == []
res = device_tracker.load_config('allok.yaml', **args)
assert len(res) == 1
assert res[0].name == 'Device'
assert res[0].dev_id == 'my_device'
res = device_tracker.load_config('oneok.yaml', **args)
assert len(res) == 1
assert res[0].name == 'Device'
assert res[0].dev_id == 'my_device'
def test_reading_yaml_config(self):
"""Test the rendering of the YAML configuration."""
dev_id = 'test'
device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id,
'AB:CD:EF:GH:IJ', 'Test name', picture='http://test.picture',
hide_if_away=True, icon='mdi:kettle')
device_tracker.update_config(self.yaml_devices, dev_id, device)
with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN,
TEST_PLATFORM)
config = device_tracker.load_config(self.yaml_devices, self.hass,
device.consider_home)[0]
self.assertEqual(device.dev_id, config.dev_id)
self.assertEqual(device.track, config.track)
self.assertEqual(device.mac, config.mac)
self.assertEqual(device.config_picture, config.config_picture)
self.assertEqual(device.away_hide, config.away_hide)
self.assertEqual(device.consider_home, config.consider_home)
self.assertEqual(device.vendor, config.vendor)
self.assertEqual(device.icon, config.icon)
# pylint: disable=invalid-name
@patch('homeassistant.components.device_tracker._LOGGER.warning')
def test_track_with_duplicate_mac_dev_id(self, mock_warning):
"""Test adding duplicate MACs or device IDs to DeviceTracker."""
devices = [
device_tracker.Device(self.hass, True, True, 'my_device', 'AB:01',
'My device', None, None, False),
device_tracker.Device(self.hass, True, True, 'your_device',
'AB:01', 'Your device', None, None, False)]
device_tracker.DeviceTracker(self.hass, False, True, devices)
_LOGGER.debug(mock_warning.call_args_list)
assert mock_warning.call_count == 1, \
"The only warning call should be duplicates (check DEBUG)"
args, _ = mock_warning.call_args
assert 'Duplicate device MAC' in args[0], \
'Duplicate MAC warning expected'
mock_warning.reset_mock()
devices = [
device_tracker.Device(self.hass, True, True, 'my_device',
'AB:01', 'My device', None, None, False),
device_tracker.Device(self.hass, True, True, 'my_device',
None, 'Your device', None, None, False)]
device_tracker.DeviceTracker(self.hass, False, True, devices)
_LOGGER.debug(mock_warning.call_args_list)
assert mock_warning.call_count == 1, \
"The only warning call should be duplicates (check DEBUG)"
args, _ | = mock_warning.call_args
assert 'Duplicate device IDs' in args[0], \
'Duplicate device IDs warning expected'
def test_setup_without_yaml_file(self):
"""Test with no YAML file."""
with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN,
TEST_PLATFORM)
# pylint: disable=invalid-name
def test_adding_unknown_device_to_config(self):
| """Test the adding of unknown devices to configuration file."""
scanner = get_component('device_tracker.test').SCANNER
scanner.reset()
scanner.come_home('DEV1')
with assert_setup_component(1, device_tracker.DOMAIN):
assert setup_component(self.hass, device_tracker.DOMAIN, {
device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}})
# wait for async calls (macvendor) to finish
self.hass.block_till_done()
config = device_tracker.load_config(self.yaml_devices, self.hass,
timedelta(seconds=0))
assert len(config) == 1
assert config[0].dev_id == 'dev1'
assert config[0].track
def test_gravatar(self):
"""Test the Gravatar generation."""
dev_id = 'test'
device = device_tracker.Device(
self.hass, timedelta(seconds=180), True, dev_id,
'AB:CD:EF:GH:IJ', 'Test name', gravatar='test@example.com')
gravatar_url = ("https://www.gravatar.com/avatar/"
"55502f40dc8b7c769880b10874abc9d0.jpg?s=80&d=wavatar")
self.assertEqual(device.config_picture, gravatar_url)
def test_gravatar_and_picture(self):
"""Test that Gravatar overrides picture."""
dev_id = 'test'
device = device_tracker.Device(
self.hass, timedelta(seconds=180), Tr |
jkatzer/flask-restless | flask_restless/views.py | Python | agpl-3.0 | 72,094 | 0.000236 | """
flask.ext.restless.views
~~~~~~~~~~~~~~~~~~~~~~~~
Provides the following view classes, subclasses of
:class:`flask.MethodView` which provide generic endpoints for interacting
with an entity of the database:
:class:`flask.ext.restless.views.API`
Provides the endpoints for each of the basic HTTP methods. This is the
main class used by the
:meth:`flask.ext.restless.manager.APIManager.create_api` method to create
endpoints.
:class:`flask.ext.restless.views.FunctionAPI`
Provides a :http:method:`get` endpoint which returns the result of
evaluating some function on the entire collection of a given model.
:copyright: 2011 by Lincoln de Sousa <lincoln@comum.org>
:copyright: 2012, 2013, 2014, 2015 Jeffrey Finkelstein
<jeffrey.finkelstein@gmail.com> and contributors.
:license: GNU AGPLv3+ or BSD
"""
from __future__ import division
from collections import defaultdict
from functools import wraps
import math
import warnings
from flask import current_app
from flask import json
from flask import jsonify as _jsonify
from flask import request
from flask.views import MethodView
from mimerender import FlaskMimeRender
from sqlalchemy import Column
from sqlalchemy.exc import DataError
from sqlalchemy.exc import IntegrityError
from sqlalchemy.exc import OperationalError
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.ext.associationproxy import AssociationProxy
from sqlalchemy.orm.attributes import InstrumentedAttribute
from sqlalchemy.orm.exc import MultipleResultsFound
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.orm.query import Query
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import HTTPException
from werkzeug.urls import url_quote_plus
from .helpers import count
from .helpers import evaluate_functions
from .helpers import get_by
from .helpers import get_columns
from .helpers import get_or_create
from .helpers import get_related_model
from .helpers import get_relations
from .helpers import has_field
from .helpers import is_like_list
from .helpers import partition
from .helpers import primary_key_name
from .helpers import query_by_primary_key
from .helpers import session_query
from .helpers import strings_to_dates
from .helpers import to_dict
from .helpers import upper_keys
from .helpers import get_related_association_proxy_model
from .search import create_query
from .search import search
#: Format string for creating Link headers in paginated responses.
LINKTEMPLATE = '<{0}?page={1}&results_per_page={2}>; rel="{3}"'
#: String used internally as a dictionary key for passing header information
#: from view functions to the :func:`jsonpify` function.
_HEADERS = '__restless_headers'
#: String used internally as a dictionary key for passing status code
#: information from view functions to the :func:`jsonpify` function.
_STATUS = '__restless_status_code'
class ProcessingException(HTTPException):
"""Raised when a preprocessor or postprocessor encounters a problem.
This exception should be raised by functions supplied in the
``preprocessors`` and ``postprocessors`` keyword arguments to
:class:`APIManager.create_api`. When this exception is raised, all
preprocessing or postprocessing halts, so any processors appearing later in
the list will not be invoked.
`code` is the HTTP status code of the response supplied to the client in
the case that this exception is raised. `description` is an error message
describing the cause of this exception. This message will appear in the
JSON object in the body of the response to the client.
"""
def __init__(self, description='', code=400, *args, **kwargs):
super(ProcessingException, self).__init__(*args, **kwargs)
self.code = code
self.description = description
class NotAuthorizedException(HTTPException):
"""Raised whenever you want a 403.
"""
def __init__(self, description='Not Authorized', code=403, *args, **kwargs):
super(NotAuthorizedException, self).__init__(*args, **kwargs)
self.code = code
self.description = description
class ValidationError(Exception):
"""Raised when there is a problem deserializing a dictionary into an
instance of a SQLAlchemy model.
"""
pass
def _is_msie8or9():
"""Returns ``True`` if and only if the user agent of the client making the
request indicates that it | is Microsoft Internet Explorer 8 or 9.
.. note::
We have no way of knowing if the user agent is lying, so we just make
our best guess based on the information provided.
"""
# request.user_agent.version comes as a string, so we have to parse it
version = lambda ua: tuple(int(d) for d in ua.version.split('.'))
return (request.user_agent is not None
and request.user_agent.version is not None
and request.user_agent.browser | == 'msie'
and (8, 0) <= version(request.user_agent) < (10, 0))
def create_link_string(page, last_page, per_page):
"""Returns a string representing the value of the ``Link`` header.
`page` is the number of the current page, `last_page` is the last page in
the pagination, and `per_page` is the number of results per page.
"""
linkstring = ''
if page < last_page:
next_page = page + 1
linkstring = LINKTEMPLATE.format(request.base_url, next_page,
per_page, 'next') + ', '
linkstring += LINKTEMPLATE.format(request.base_url, last_page,
per_page, 'last')
return linkstring
def catch_processing_exceptions(func):
"""Decorator that catches :exc:`ProcessingException`s and subsequently
returns a JSON-ified error response.
"""
@wraps(func)
def decorator(*args, **kw):
try:
return func(*args, **kw)
except ProcessingException as exception:
status = exception.code
message = exception.description or str(exception)
return jsonify(message=message), status
return decorator
def catch_integrity_errors(session):
"""Returns a decorator that catches database integrity errors.
`session` is the SQLAlchemy session in which all database transactions will
be performed.
View methods can be wrapped like this::
@catch_integrity_errors(session)
def get(self, *args, **kw):
return '...'
Specifically, functions wrapped with the returned decorator catch
:exc:`IntegrityError`s, :exc:`DataError`s, and
:exc:`ProgrammingError`s. After the exceptions are caught, the session is
rolled back, the exception is logged on the current Flask application, and
an error response is returned to the client.
"""
def decorator(func):
@wraps(func)
def wrapped(*args, **kw):
try:
return func(*args, **kw)
# TODO should `sqlalchemy.exc.InvalidRequestError`s also be caught?
except (DataError, IntegrityError, ProgrammingError) as exception:
session.rollback()
current_app.logger.exception(str(exception))
return dict(message=type(exception).__name__), 400
return wrapped
return decorator
def set_headers(response, headers):
"""Sets the specified headers on the specified response.
`response` is a Flask response object, and `headers` is a dictionary of
headers to set on the specified response. Any existing headers that
conflict with `headers` will be overwritten.
"""
for key, value in headers.items():
response.headers[key] = value
def jsonify(*args, **kw):
"""Same as :func:`flask.jsonify`, but sets response headers.
If ``headers`` is a keyword argument, this function will construct the JSON
response via :func:`flask.jsonify`, then set the specified ``headers`` on
the response. ``headers`` must be a dictionary mapping strings to strings.
"""
response = _jsonify(*args, **kw)
if 'headers' in kw:
set_headers(response, kw['headers'])
|
diogo149/CauseEffectPairsPaper | configs/max_aggregate_only.py | Python | mit | 7,294 | 0.001508 | import numpy as np
from scipy.stats import skew, kurtosis, shapiro, pearsonr, ansari, mood, levene, fligner, bartlett, mannwhitneyu
from scipy.spatial.distance import braycurtis, canberra, chebyshev, cityblock, correlati | on, cosine, euclidean, hamming, jaccard, kulsinski, matching, russellrao, sqeucl | idean
from sklearn.preprocessing import LabelBinarizer
from sklearn.linear_model import Ridge, LinearRegression, LogisticRegression
from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, RandomForestClassifier, GradientBoostingClassifier
from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import explained_variance_score, mean_absolute_error, mean_squared_error, r2_score, accuracy_score, roc_auc_score, average_precision_score, f1_score, hinge_loss, matthews_corrcoef, precision_score, recall_score, zero_one_loss
from sklearn.metrics.cluster import adjusted_mutual_info_score, adjusted_rand_score, completeness_score, homogeneity_completeness_v_measure, homogeneity_score, mutual_info_score, normalized_mutual_info_score, v_measure_score
from boomlet.utils.aggregators import to_aggregator
from boomlet.metrics import max_error, error_variance, relative_error_variance, gini_loss, categorical_gini_loss
from boomlet.transform.type_conversion import Discretizer
from autocause.feature_functions import *
"""
Functions used to combine a list of features into one coherent one.
Sample use:
1. to convert categorical to numerical, we perform a one hot encoding
2. treat each binary column as a separate numerical feature
3. compute numerical features as usual
4. use each of the following functions to create a new feature
(with the input as the nth feature for each of the columns)
WARNING: these will be used in various locations throughout the code base
and will result in feature size growing at faster than a linear rate
"""
AGGREGATORS = [
to_aggregator("max"),
# to_aggregator("min"),
# to_aggregator("median"),
# to_aggregator("mode"),
# to_aggregator("mean"),
# to_aggregator("sum"),
]
"""
Boolean flags specifying whether or not to perform conversions
"""
CONVERT_TO_NUMERICAL = True
CONVERT_TO_CATEGORICAL = True
"""
Functions that compute a metric on a single 1-D array
"""
UNARY_NUMERICAL_FEATURES = [
normalized_entropy,
skew,
kurtosis,
np.std,
shapiro,
]
UNARY_CATEGORICAL_FEATURES = [
lambda x: len(set(x)), # number of unique
]
"""
Functions that compute a metric on two 1-D arrays
"""
BINARY_NN_FEATURES = [
independent_component,
chi_square,
pearsonr,
correlation_magnitude,
braycurtis,
canberra,
chebyshev,
cityblock,
correlation,
cosine,
euclidean,
hamming,
sqeuclidean,
ansari,
mood,
levene,
fligner,
bartlett,
mannwhitneyu,
]
BINARY_NC_FEATURES = [
]
BINARY_CN_FEATURES = [
categorical_numerical_homogeneity,
bucket_variance,
anova,
]
BINARY_CC_FEATURES = [
categorical_categorical_homogeneity,
anova,
dice_,
jaccard,
kulsinski,
matching,
rogerstanimoto_,
russellrao,
sokalmichener_,
sokalsneath_,
yule_,
adjusted_mutual_info_score,
adjusted_rand_score,
completeness_score,
homogeneity_completeness_v_measure,
homogeneity_score,
mutual_info_score,
normalized_mutual_info_score,
v_measure_score,
]
"""
Dictionaries of input type (e.g. B corresponds to pairs where binary
data is the input) to pairs of converter functions and a boolean flag
of whether or not to aggregate over the output of the converter function
converter functions should have the type signature:
converter(X_raw, X_current_type, Y_raw, Y_type)
where X_raw is the data to convert
"""
NUMERICAL_CONVERTERS = dict(
N=lambda x, *args: x, # identity function
B=lambda x, *args: x, # identity function
C=lambda x, *args: LabelBinarizer().fit_transform(x),
)
CATEGORICAL_CONVERTERS = dict(
N=lambda x, *args: Discretizer().fit_transform(x).flatten(),
B=lambda x, *args: x, # identity function
C=lambda x, *args: x, # identity function
)
"""
Whether or not the converters can result in a 2D output. This must be set to True
if any of the respective converts can return a 2D output.
"""
NUMERICAL_CAN_BE_2D = True
CATEGORICAL_CAN_BE_2D = False
"""
Estimators used to provide a fit for a variable
"""
REGRESSION_ESTIMATORS = [
Ridge(),
LinearRegression(),
DecisionTreeRegressor(random_state=0),
RandomForestRegressor(random_state=0),
GradientBoostingRegressor(subsample=0.5, n_estimators=10, random_state=0),
KNeighborsRegressor(),
]
CLASSIFICATION_ESTIMATORS = [
LogisticRegression(random_state=0),
DecisionTreeClassifier(random_state=0),
RandomForestClassifier(random_state=0),
GradientBoostingClassifier(subsample=0.5, n_estimators=10, random_state=0),
KNeighborsClassifier(),
GaussianNB(),
]
"""
Functions to provide a value of how good a fit on a variable is
"""
REGRESSION_METRICS = [
explained_variance_score,
mean_absolute_error,
mean_squared_error,
r2_score,
max_error,
error_variance,
relative_error_variance,
gini_loss,
] + BINARY_NN_FEATURES
REGRESSION_RESIDUAL_METRICS = [
] + UNARY_NUMERICAL_FEATURES
BINARY_PROBABILITY_CLASSIFICATION_METRICS = [
roc_auc_score,
hinge_loss,
] + REGRESSION_METRICS
RESIDUAL_PROBABILITY_CLASSIFICATION_METRICS = [
] + REGRESSION_RESIDUAL_METRICS
BINARY_CLASSIFICATION_METRICS = [
accuracy_score,
average_precision_score,
f1_score,
matthews_corrcoef,
precision_score,
recall_score,
zero_one_loss,
categorical_gini_loss,
]
ND_CLASSIFICATION_METRICS = [ # metrics for N-dimensional classification
] + BINARY_CC_FEATURES
"""
Functions to assess the model (e.g. complexity) of the fit on a numerical variable
of type signature:
metric(clf, X, y)
"""
REGRESSION_MODEL_METRICS = [
# TODO model complexity metrics
]
CLASSIFICATION_MODEL_METRICS = [
# TODO use regression model metrics on predict_proba
]
"""
The operations to perform on the A->B features and B->A features.
"""
RELATIVE_FEATURES = [
# Identity functions, comment out the next 2 lines for only relative features
lambda x, y: x,
lambda x, y: y,
lambda x, y: x - y,
]
"""
Whether or not to treat each observation (A,B) as two observations: (A,B) and (B,A)
If this is done and training labels are given, those labels will have to be
reflected as well. The reflection is performed through appending at the end.
(e.g. if we have N training examples, observation N+1 in the output will be
the first example reflected)
"""
REFLECT_DATA = False
"""
Whether or not metafeatures based on the types of A and B are generated.
e.g. 1/0 feature on whether or not A is Numerical, etc.
"""
ADD_METAFEATURES = True
"""
Whether or not to generate combination features between the computed
features and metafeatures.
e.g. for each feature and metafeature, generate a new feature which is the
product of the two
WARNING: will generate a LOT of features (approximately 21 times as many)
"""
COMPUTE_METAFEATURE_COMBINATIONS = False
|
seecr/meresco-components | test/_http/pathfiltertest.py | Python | gpl-2.0 | 3,628 | 0.002756 | ## begin license ##
#
# "Meresco Components" are components to build searchengines, repositories
# and archives, based on "Meresco Core".
#
# Copyright (C) 2007-2009 SURF Foundation. http://www.surf.nl
# Copyright (C) 2007 SURFnet. http://www.surfnet.nl
# Copyright (C) 2007-2010 Seek You Too (CQ2) http://www.cq2.nl
# Copyright (C) 2007-2009 Stichting Kennisnet Ict op school. http://www.kennisnetictopschool.nl
# Copyright (C) 2012, 2016, 2020 Seecr (Seek You Too B.V.) https://seecr.nl
# Copyright (C) 2016 SURFmarket https://surf.nl
# Copyright (C) 2020 Data Archiving and Network Services https://dans.knaw.nl
# Copyright (C) 2020 SURF https://www.surf.nl
# Copyright (C) 2020 Stichting Kennisnet https://www.kennisnet.nl
# Copyright (C) 2020 The Netherlands Institute for Sound and Vision https://beeldengeluid.nl
#
# This file is part of "Meresco Components"
#
# "Meresco Components" 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.
#
# "Meresco Components" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with "Meresco Components"; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
## end license ##
from seecr.test import SeecrTestCase, CallTrace
from meresco.components.http import PathFilter
from weightless.core import consume
class PathFilterTest(SeecrTestCase):
def setUp(self):
SeecrTestCase.setUp(self)
self.interceptor = CallTrace('Interceptor', methods={'handleRequest': lambda *args, **kwargs: (x for x in [])})
def testSimplePath(self):
f = PathFilter('/path')
f.addObserver(self.interceptor)
consume(f.handleRequest(path='/path', otherArgument='value'))
self.assertEqual(1, len(self.interceptor.calledMethods))
self.assertEqual('handleRequest', self.interceptor.calledMethods[0].name)
self.assertEqual({'path':'/path', 'otherArgument':'value'}, self.interceptor.calledMethods[0].kwargs)
def testOtherPa | th(self):
f = PathFilter('/path')
f.addObserver(self.interceptor)
consume(f.handleRequest(path='/other/path'))
self.assertEqual(0, len(self.interceptor.calledMethods))
def testPaths(self):
f = PathFilter(['/pat | h', '/other/path'])
f.addObserver(self.interceptor)
consume(f.handleRequest(path='/other/path'))
self.assertEqual(1, len(self.interceptor.calledMethods))
def testExcludingPaths(self):
f = PathFilter('/path', excluding=['/path/not/this'])
f.addObserver(self.interceptor)
consume(f.handleRequest(path='/path/not/this/path'))
self.assertEqual(0, len(self.interceptor.calledMethods))
consume(f.handleRequest(path='/path/other'))
self.assertEqual(1, len(self.interceptor.calledMethods))
def testUpdatePaths(self):
f = PathFilter('/')
f.addObserver(self.interceptor)
f.updatePaths('/path', excluding=['/path/not/this'])
consume(f.handleRequest(path='/path/not/this/path'))
self.assertEqual(0, len(self.interceptor.calledMethods))
consume(f.handleRequest(path='/path/other'))
self.assertEqual(1, len(self.interceptor.calledMethods))
|
PabloCastellano/nodeshot | nodeshot/ui/default/tests/selenium.py | Python | gpl-3.0 | 50,260 | 0.005611 | from __future__ import absolute_import
from time import sleep
from django.core.urlresolvers import reverse
from django.test import TestCase
from nodeshot.core.base.tests import user_fixtures
from nodeshot.core.nodes.models import Node
from nodeshot.ui.default import settings as local_settings
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
class DefaultUiSeleniumTest(TestCase):
fixtures = [
'initial_data.json',
user_fixtures,
'test_layers.json',
'test_status.json',
'test_nodes.json',
'test_images.json',
'test_pages.json'
]
INDEX_URL = '%s%s' % (local_settings.settings.SITE_URL, reverse('ui:index'))
LEAFLET_MAP = 'Ns.body.currentView.content.currentView.map'
def _wait_until_ajax_complete(self, seconds, message):
""" waits until all ajax requests are complete """
def condition(driver):
return driver.execute_script("return typeof(jQuery) !== 'undefined' && jQuery.active === 0")
WebDriverWait(self.browser, seconds).until(condition, message)
def _wait_until_element_visible(self, selector, seconds, message):
""" waits until css selector is present and visible """
WebDriverWait(self.browser, seconds).until(
expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, selector)),
message
)
def _hashchange(self, hash):
self.browser.get('%s%s' % (self.INDEX_URL, hash))
self._wai | t_until_ajax_complete(10, 'Timeout')
def _reset(self):
""" reset and reload browser (clear localstorage and go to index) """
self._hashchange('#/')
self.browser.execute_script('l | ocalStorage.clear()')
self.browser.delete_all_cookies()
self.browser.refresh()
self._wait_until_ajax_complete(10, 'Timeout')
def _login(self, username='admin', password='tester', open_modal=True):
if open_modal:
# open sign in modal
self.browser.find_element_by_css_selector('#main-actions a[data-target="#signin-modal"]').click()
self._wait_until_element_visible('#js-signin-form', 3, 'signin modal not visible')
# insert credentials
username_field = self.browser.find_element_by_css_selector('#js-signin-form input[name=username]')
username_field.clear()
username_field.send_keys(username)
password_field = self.browser.find_element_by_css_selector('#js-signin-form input[name=password]')
password_field.clear()
password_field.send_keys(password)
# log in
self.browser.find_element_by_css_selector('#js-signin-form button.btn-default').click()
self._wait_until_ajax_complete(5, 'timeout')
self._wait_until_element_visible('#js-username', 3, 'username after login not visible')
# check username
self.assertEqual(self.browser.find_element_by_css_selector('#js-username').text, 'admin')
def _logout(self):
# open account menu
self.browser.find_element_by_css_selector('#js-username').click()
# log out
self._wait_until_element_visible('#js-logout', 3, '#js-logout not visible')
self.browser.find_element_by_css_selector('#js-logout').click()
self._wait_until_ajax_complete(5, 'timeout')
# ensure UI has gone back to initial state
self._wait_until_element_visible('#main-actions a[data-target="#signin-modal"]', 3, 'sign in link not visible after logout')
@classmethod
def setUpClass(cls):
cls.browser = webdriver.Firefox()
cls.browser.get(cls.INDEX_URL)
super(DefaultUiSeleniumTest, cls).setUpClass()
@classmethod
def tearDownClass(cls):
cls.browser.quit()
super(DefaultUiSeleniumTest, cls).tearDownClass()
def setUp(self):
""" reset browser to initial state """
browser = self.browser
browser.execute_script('localStorage.clear()')
browser.delete_all_cookies()
browser.execute_script("Ns.db.user.clear(); Ns.db.user.trigger('logout');")
browser.set_window_size(1100, 700)
def test_home(self):
self._hashchange('#')
self.assertEqual(self.browser.find_element_by_css_selector('article.center-stage h1').text, 'Home')
self.assertTrue(self.browser.execute_script('return Ns.db.pages.get("home") !== undefined'))
self.assertEqual(self.browser.title, 'Home - Nodeshot')
def test_menu_already_active(self):
self._hashchange('#')
# ensure clicking multiple times on a level1 menu item still displays it as active
self.browser.find_element_by_css_selector('#nav-bar li.active a').click()
self.browser.find_element_by_css_selector('#nav-bar li.active a').click()
# ensure the same on a nested menu item
self.browser.find_element_by_css_selector('#nav-bar a.dropdown-toggle').click()
self.browser.find_element_by_css_selector("a[href='#pages/about']").click()
self._wait_until_ajax_complete(1, 'page timeout')
self.browser.find_element_by_css_selector('#nav-bar li.active a.dropdown-toggle').click()
self.browser.find_element_by_css_selector("a[href='#pages/about']").click()
self._wait_until_ajax_complete(1, 'page timeout')
self.browser.find_element_by_css_selector('#nav-bar li.active a.dropdown-toggle').click()
def test_map(self):
self._reset()
self._hashchange('#map')
browser = self.browser
LEAFLET_MAP = self.LEAFLET_MAP
# test title
self.assertEqual(browser.title, 'Map - Nodeshot')
# basic test
self.assertTrue(browser.execute_script("return Ns.body.currentView.$el.attr('id') == 'map-container'"))
browser.find_element_by_css_selector('#map-js.leaflet-container')
self.assertTrue(browser.execute_script("return %s._leaflet_id > -1" % LEAFLET_MAP))
# layers control
browser.find_element_by_css_selector('#map-js .leaflet-control-layers-list')
LAYERS_CONTROLS = 'return _.values(%s.layerscontrol._layers)' % LEAFLET_MAP
self.assertEqual(browser.execute_script('%s[0].name' % LAYERS_CONTROLS), 'Map')
self.assertEqual(browser.execute_script('%s[1].name' % LAYERS_CONTROLS), 'Satellite')
# ensure coordinates are correct
self.assertEqual(browser.execute_script("return %s.getZoom()" % LEAFLET_MAP), local_settings.MAP_ZOOM)
# leaflet coordinates are approximated when zoom is low, so let's check Nodeshot JS settings
self.assertEqual(browser.execute_script("return Ns.settings.map.lat"), local_settings.MAP_CENTER[0])
self.assertEqual(browser.execute_script("return Ns.settings.map.lng"), local_settings.MAP_CENTER[1])
self.assertEqual(browser.execute_script("return Ns.settings.map.zoom"), local_settings.MAP_ZOOM)
# ensure rememberCoordinates() works
browser.execute_script("%s.setView([42.111111, 12.111111], 17)" % LEAFLET_MAP)
sleep(0.5)
self._hashchange('#')
self.assertEqual(browser.execute_script("return localStorage.getObject('map').lat.toString().substr(0, 7)"), "42.1111")
self.assertEqual(browser.execute_script("return localStorage.getObject('map').lng.toString().substr(0, 7)"), "12.1111")
self.assertEqual(browser.execute_script("return localStorage.getObject('map').zoom"), 17)
self._hashchange('#/map')
self.assertEqual(browser.execute_script("return %s.getZoom()" % LEAFLET_MAP), 17)
self.assertEqual(browser.execute_script("return %s.getCenter().lat.toString().substr(0, 7)" % LEAFLET_MAP), "42.1111")
self.assertEqual(browser.execute_script("return %s.getCenter().lng.toString().substr(0, 7)" % LEAFLET_MAP), "12.1111")
# map is resized when window is resized
window_size = browser.get_window_size()
map_size = {}
map_size['width'] = browser.execute_script("return $('#map-js').wid |
dexy/cashew | example/classes1.py | Python | mit | 748 | 0.012032 | ### "imports"
from example.classes import Data
### "other-imports"
import csv
import json
from example.utils import tempdir
### "csv-subclass"
class Csv(Data):
"""
CSV type.
"""
aliases = ['csv']
def present(self):
with tempdir():
with open("dictionary.csv", "w") as f:
headers = list(self.data[0].keys())
writer = csv.DictWriter(f, headers)
writer.writeheader()
writer.writerows(self.data)
with open("dictionary.csv", "r") as f:
return f.read()
### "json-subclass"
class Json(Data):
"""
| JSON type.
"""
| aliases = ['json']
def present(self):
return json.dumps(self.data)
|
Johnzero/erp | openerp/addons/hr_timesheet/wizard/hr_timesheet_sign_in_out.py | Python | agpl-3.0 | 8,655 | 0.006009 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from osv import osv, fields
from tools.translate import _
class hr_so_project(osv.osv_memory):
_name = 'hr.sign.out.project'
_description = 'Sign Out By Project'
_columns = {
'account_id': fields.many2one('account.analytic.account', 'Project / Analytic Account', domain=[('type','=','normal')]),
'info': fields.char('Work Description', size=256, required=True),
'date_start': fields.datetime('Starting Date', readonly=True),
'date': fields.datetime('Closing Date'),
'analytic_amount': fields.float('Minimum Analytic Amount'),
'name': fields.char('Employees name', size=32, required=True, readonly=True),
'state': fields.related('emp_id', 'state', string='Current state', type='char', required=True, readonly=True),
'server_date': fields.datetime('Current Date', required=True, readonly=True),
'emp_id': fields.many2one('hr.employee', 'Employee ID')
}
def _get_empid(self, cr, uid, context=None):
emp_obj = self.pool.get('hr.employee')
emp_ids = emp_obj.search(cr, uid, [('user_id', '=', uid)], context=context)
if emp_ids:
for employee in emp_obj.browse(cr, uid, emp_ids, context=context):
return {'name': employee.name, 'state': employee.state, 'emp_id': emp_ids[0], 'server_date':time.strftime('%Y-%m-%d %H:%M:%S')}
def _get_empid2(self, cr, uid, context=None):
res = self._get_empid(cr, uid, context=context)
cr.execute('select name,action from hr_attendance where employee_id=%s order by name desc limit 1', (res['emp_id'],))
res['server_date'] = time.strftime('%Y-%m-%d %H:%M:%S')
date_start = cr.fetchone()
if date_start:
res['date_start'] = date_start[0]
return res
def default_get(self, cr, uid, fields_list, context=None):
res = super(hr_so_project, self).default_get(cr, uid, fields_list, context=context)
res.update(self._get_empid2(cr, uid, context=context))
return res
def _write(self, cr, uid, data, emp_id, context=None):
timesheet_obj = self.pool.get('hr.analytic.timesheet')
emp_obj = self.pool.get('hr.employee')
if context is None:
context = {}
hour = (time.mktime(time.strptime(data['date'] or time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')) -
time.mktime(time.strptime(data['date_start'], '%Y-%m-%d %H:%M:%S'))) / 3600.0
minimum = data['analytic_amount']
if minimum:
hour = round(round((hour + minimum / 2) / minimum) * minimum, 2)
res = timesheet_obj.default_get(cr, uid, ['product_id','product_uom_id'], context=context)
if not res['product_uom_id']:
raise osv.except_osv(_('UserError'), _('No cost unit defined for this employee !'))
up = timesheet_obj.on_change_unit_amount(cr, uid, False, res['product_id'], hour,False, res['product_uom_id'])['value']
res['name'] = data['info']
res['account_id'] = data['account_id'].id
res['unit_amount'] = hour
emp_journal = emp_obj.browse(cr, uid, emp_id, context=context).journal_id
res['journal_id'] = emp_journal and emp_journal.id or False
res.update(up)
up = timesheet_obj.on_change_account_id(cr, uid, [], res['account_id']).get('value', {})
res.update(up)
return timesheet_obj.create(cr, uid, res, context=context)
def sign_out_result_end(self, cr, uid, ids, context=None):
emp_obj = self.pool.get('hr.employee')
for data in self.browse(cr, uid, ids, context=context):
emp_id = data.emp_id.id
emp_obj.attendance_action_change(cr, uid, [emp_id], type='sign_out', dt=data.date)
self._write(cr, uid, data, emp_id, context=context)
return {'type': 'ir.actions.act_window_close'}
def sign_out_result(self, cr, uid, ids, context=None):
emp_obj = self.pool.get('hr.employee')
for data in self.browse(cr, uid, ids, context=context):
emp_id = data.emp_id.id
emp_obj.attendance_action_change(cr, uid, [emp_id], type='action', dt=data.date)
self._write(cr, uid, data, emp_id, context=context)
return {'type': 'ir.actions.act_window_close'}
hr_so_project()
class hr_si_project(osv.osv_memory):
_name = 'hr.sign.in.project'
_description = 'Sign In By Project'
_columns = {
'name': fields.char('Employees name', size=32, readonly=True),
's | tate': fields.related('emp_id', 'state', string='Current state', type='char', required=True, readonly=True),
'date': fields.datetime('Starting Date'),
'server_date': fields.datetime('Current Date', readonly=True),
'emp_i | d': fields.many2one('hr.employee', 'Employee ID')
}
def view_init(self, cr, uid, fields, context=None):
"""
This function checks for precondition before wizard executes
@param self: The object pointer
@param cr: the current row, from the database cursor,
@param uid: the current user’s ID for security checks,
@param fields: List of fields for default value
@param context: A standard dictionary for contextual values
"""
emp_obj = self.pool.get('hr.employee')
emp_id = emp_obj.search(cr, uid, [('user_id', '=', uid)], context=context)
if not emp_id:
raise osv.except_osv(_('UserError'), _('No employee defined for your user !'))
return False
def check_state(self, cr, uid, ids, context=None):
obj_model = self.pool.get('ir.model.data')
emp_id = self.default_get(cr, uid, context)['emp_id']
# get the latest action (sign_in or out) for this employee
cr.execute('select action from hr_attendance where employee_id=%s and action in (\'sign_in\',\'sign_out\') order by name desc limit 1', (emp_id,))
res = (cr.fetchone() or ('sign_out',))[0]
in_out = (res == 'sign_out') and 'in' or 'out'
#TODO: invert sign_in et sign_out
model_data_ids = obj_model.search(cr,uid,[('model','=','ir.ui.view'),('name','=','view_hr_timesheet_sign_%s' % in_out)], context=context)
resource_id = obj_model.read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id']
return {
'name': 'Sign in / Sign out',
'view_type': 'form',
'view_mode': 'tree,form',
'res_model': 'hr.sign.%s.project' % in_out,
'views': [(False,'tree'), (resource_id,'form')],
'type': 'ir.actions.act_window',
'target': 'new'
}
def sign_in_result(self, cr, uid, ids, context=None):
emp_obj = self.pool.get('hr.employee')
for data in self.browse(cr, uid, ids, context=context):
emp_id = data.emp_id.id
emp_obj.attendance_action_change(cr, uid, [emp_id], type = 'sign_in' ,dt=data.date or False)
return {'type': 'ir.actions.act_window_close'}
def default_get(self, cr, uid, fields_list, context=None):
res = super(hr_si_project, self).default_get(cr, uid, fields_list, context=context)
|
xuru/pyvisdk | pyvisdk/enums/event_category.py | Python | mit | 239 | 0 |
############### | #########################
# Automatically generated, do not edit.
########################################
from pyvisdk.thirdparty import Enum
EventCategory = Enum(
'error',
'info', |
'user',
'warning',
)
|
vegitron/django-handlebars-i18n | setup.py | Python | apache-2.0 | 284 | 0.007042 | #!/usr/bin/env python
from distutils.core import setup
setup(name='Django-Handlebars-I18N',
version='1.0',
description='Tools for using django translations in handlebars templa | tes, and making it easier to use translations.' | ,
install_requires=['importlib'],
)
|
petrmikheev/miksys | miksys_soft/pack_usb.py | Python | gpl-3.0 | 662 | 0.009063 | #!/usr/bin/python
#coding: utf8
import sys, struct
data_size = 2*1024*1024
if len(sys.argv) != 3:
print 'Using: ./pack_usb.py input.bin output.bin'
sys.exit(0)
fin = file(sys.argv[1], 'rb')
data = fin.read()
print 'Size: %d bytes' % len(data)
if len(data) > data_size-2:
print 'Error: too | big'
sys.exit(0)
data += b'\xa5'*(data_size-2-len(data))
fout = file(sys.argv[-1], 'wb')
fout.write(data)
checksum = sum([struct.unpack('<H', data[i:i+2])[0] for i in range(0, len(data), 2)]) % 0x10000
#fout.write(b'\0'*(data_size-2-len(d | ata)))
print 'Checksum: 0x%04x' % checksum
fout.write(struct.pack('<H', (0x1aa55-checksum)%0x10000))
fout.close()
|
jib/aws-analysis-tools | instances.py | Python | mit | 6,405 | 0.02217 | #!python
import re
import sys
import logging
import boto.ec2
from texttable import Texttable
from pprint import PrettyPrinter
from optparse import OptionParser
PP = PrettyPrinter( indent=2 )
###################
### Arg parsing
###################
parser = OptionParser("usage: %prog [options]" )
parser.add_option( "-v", "--verbose", default=None, action="store_true",
help="enable debug output" )
parser.add_option( "-H", "--no-header", default=None, action="store_true",
help="suppress table header" )
parser.add_option( "-r", "--region", default='us-east-1',
help="ec2 region to connect to" )
parser.add_option( "-g", "--group", default=None,
help="Include instances from these groups only (regex)" )
parser.add_option( "-G", "--exclude-group",default=None,
help="Exclude instances from these groups (regex)" )
parser.add_option( "-n", "--name", default=None,
help="Include instances with these names only (regex)" )
parser.add_option( "-N", "--exclude-name", default=None,
| help="Exclude instances with | these names (regex)" )
parser.add_option( "-t", "--type", default=None,
help="Include instances with these types only (regex)" )
parser.add_option( "-T", "--exclude-type", default=None,
help="Exclude instances with these types (regex)" )
parser.add_option( "-z", "--zone", default=None,
help="Include instances with these zones only (regex)" )
parser.add_option( "-Z", "--exclude-zone", default=None,
help="Exclude instances with these zones (regex)" )
parser.add_option( "-s", "--state", default=None,
help="Include instances with these states only (regex)" )
parser.add_option( "-S", "--exclude-state",default=None,
help="Exclude instances with these states (regex)" )
(options, args) = parser.parse_args()
###################
### Logging
###################
if options.verbose: log_level = logging.DEBUG
else: log_level = logging.INFO
logging.basicConfig(stream=sys.stdout, level=log_level)
logging.basicConfig(stream=sys.stderr, level=(logging.ERROR,logging.CRITICAL))
###################
### Connection
###################
conn = boto.ec2.connect_to_region( options.region )
###################
### Regexes
###################
regexes = {}
for opt in [ 'group', 'exclude_group', 'name', 'exclude_name',
'type', 'exclude_type', 'zone', 'exclude_zone',
'state', 'exclude_state' ]:
### we have a regex we should build
if options.__dict__.get( opt, None ):
regexes[ opt ] = re.compile( options.__dict__.get( opt ), re.IGNORECASE )
#PP.pprint( regexes )
def get_instances():
instances = [ i for r in conn.get_all_instances()
for i in r.instances ]
rv = [];
for i in instances:
### we will assume this node is one of the nodes we want
### to operate on, and we will unset this flag if any of
### the criteria fail
wanted_node = True
for re_name, regex in regexes.iteritems():
### What's the value we will be testing against?
if re.search( 'group', re_name ):
value = i.groups[0].name
elif re.search( 'name', re_name ):
value = i.tags.get( 'Name', '' )
elif re.search( 'type', re_name ):
value = i.instance_type
elif re.search( 'state', re_name ):
value = i.state
elif re.search( 'zone', re_name ):
### i.region is an object. i._placement is a string.
value = str(i._placement)
else:
logging.error( "Don't know what to do with: %s" % re_name )
continue
#PP.pprint( "name = %s value = %s pattern = %s" % ( re_name, value, regex.pattern ) )
### Should the regex match or not match?
if re.search( 'exclude', re_name ):
rv_value = None
else:
rv_value = True
### if the match is not what we expect, then clearly we
### don't care about the node
result = regex.search( value )
### we expected to get no results, excellent
if result == None and rv_value == None:
pass
### we expected to get some match, excellent
elif result is not None and rv_value is not None:
pass
### we don't care about this node
else:
wanted_node = False
break
if wanted_node:
rv.append( i )
return rv
def list_instances():
table = Texttable( max_width=0 )
table.set_deco( Texttable.HEADER )
table.set_cols_dtype( [ 't', 't', 't', 't', 't', 't', 't', 't' ] )
table.set_cols_align( [ 'l', 'l', 'l', 'l', 'l', 'l', 'l', 't' ] )
if not options.no_header:
### using add_row, so the headers aren't being centered, for easier grepping
table.add_row(
[ '# id', 'Name', 'Type', 'Zone', 'Group', 'State', 'Root', 'Volumes' ] )
instances = get_instances()
for i in instances:
### XXX there's a bug where you can't get the size of the volumes, it's
### always reported as None :(
volumes = ", ".join( [ ebs.volume_id for ebs in i.block_device_mapping.values()
if ebs.delete_on_termination == False ] )
### you can use i.region instead of i._placement, but it pretty
### prints to RegionInfo:us-east-1. For now, use the private version
### XXX EVERY column in this output had better have a non-zero length
### or texttable blows up with 'width must be greater than 0' error
table.add_row( [ i.id, i.tags.get( 'Name', ' ' ), i.instance_type,
i._placement , i.groups[0].name, i.state,
i.root_device_type, volumes or '-' ] )
#PP.pprint( i.__dict__ )
### table.draw() blows up if there is nothing to print
if instances or not options.no_header:
print table.draw()
if __name__ == '__main__':
list_instances()
|
rahulunair/nova | nova/conductor/tasks/base.py | Python | apache-2.0 | 1,651 | 0 | # 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 under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import functools
from oslo_utils import excutils
import six
def rollback_wrapper(original):
@functools.wraps(original)
def wrap(self):
try:
return original(self)
except Exception as ex:
with excutils.save_an | d_reraise_exception():
self.rollback(ex)
return wrap
@six.add_metaclass(abc.ABCMeta)
class TaskBase(object):
def __init__(self, context, instance):
self.context = context
self.instance = instance
@rollback_wrapper
def execute(self):
"""Run task's logic, written in _execute() method
"""
re | turn self._execute()
@abc.abstractmethod
def _execute(self):
"""Descendants should place task's logic here, while resource
initialization should be performed over __init__
"""
pass
def rollback(self, ex):
"""Rollback failed task
Descendants should implement this method to allow task user to
rollback status to state before execute method was call
"""
pass
|
wood-galaxy/FreeCAD | src/Mod/Fem/FemTools.py | Python | lgpl-2.1 | 29,560 | 0.004432 | # ***************************************************************************
# * *
# * Copyright (c) 2015 - Przemo Firszt <przemo@firszt.eu> *
# * Copyright (c) 2015 - Bernd Hahnebach <bernd@bimstatik.org> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the impl | ied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * | *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
__title__ = "Fem Tools super class"
__author__ = "Przemo Firszt, Bernd Hahnebach"
__url__ = "http://www.freecadweb.org"
import FreeCAD
from PySide import QtCore
class FemTools(QtCore.QRunnable, QtCore.QObject):
## The constructor
# @param analysis - analysis object to be used as the core object.
# "__init__" tries to use current active analysis in analysis is left empty.
# Rises exception if analysis is not set and there is no active analysis
# The constructur of FemTools is for use of analysis without solver object
def __init__(self, analysis=None, solver=None):
if analysis:
## @var analysis
# FEM analysis - the core object. Has to be present.
# It's set to analysis passed in "__init__" or set to current active analysis by default if nothing has been passed to "__init__".
self.analysis = analysis
else:
import FemGui
self.analysis = FemGui.getActiveAnalysis()
if solver:
## @var solver
# solver of the analysis. Used to store the active solver and analysis parameters
self.solver = solver
else:
self.solver = None
if self.analysis:
self.update_objects()
self.results_present = False
self.result_object = None
else:
raise Exception('FEM: No active analysis found!')
## Removes all result objects
# @param self The python object self
def purge_results(self):
for m in self.analysis.Member:
if (m.isDerivedFrom('Fem::FemResultObject')):
self.analysis.Document.removeObject(m.Name)
self.results_present = False
## Resets mesh deformation
# @param self The python object self
def reset_mesh_deformation(self):
if self.mesh:
self.mesh.ViewObject.applyDisplacement(0.0)
## Resets mesh color
# @param self The python object self
def reset_mesh_color(self):
if self.mesh:
self.mesh.ViewObject.NodeColor = {}
self.mesh.ViewObject.ElementColor = {}
self.mesh.ViewObject.setNodeColorByScalars()
## Resets mesh color, deformation and removes all result objects if preferences to keep them is not set
# @param self The python object self
def reset_mesh_purge_results_checked(self):
self.fem_prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/General")
keep_results_on_rerun = self.fem_prefs.GetBool("KeepResultsOnReRun", False)
if not keep_results_on_rerun:
self.purge_results()
self.reset_mesh_color()
self.reset_mesh_deformation()
## Resets mesh color, deformation and removes all result objects
# @param self The python object self
def reset_all(self):
self.purge_results()
self.reset_mesh_color()
self.reset_mesh_deformation()
## Sets mesh color using selected type of results (Sabs by default)
# @param self The python object self
# @param result_type Type of FEM result, allowed are:
# - U1, U2, U3 - deformation
# - Uabs - absolute deformation
# - Sabs - Von Mises stress
# @param limit cutoff value. All values over the limit are treated as equal to the limit. Useful for filtering out hot spots.
def show_result(self, result_type="Sabs", limit=None):
self.update_objects()
if result_type == "None":
self.reset_mesh_color()
return
if self.result_object:
if FreeCAD.GuiUp:
if self.result_object.Mesh.ViewObject.Visibility is False:
self.result_object.Mesh.ViewObject.Visibility = True
if result_type == "Sabs":
values = self.result_object.StressValues
elif result_type == "Uabs":
values = self.result_object.DisplacementLengths
else:
match = {"U1": 0, "U2": 1, "U3": 2}
d = zip(*self.result_object.DisplacementVectors)
values = list(d[match[result_type]])
self.show_color_by_scalar_with_cutoff(values, limit)
## Sets mesh color using list of values. Internally used by show_result function.
# @param self The python object self
# @param values list of values
# @param limit cutoff value. All values over the limit are treated as equel to the limit. Useful for filtering out hot spots.
def show_color_by_scalar_with_cutoff(self, values, limit=None):
if limit:
filtered_values = []
for v in values:
if v > limit:
filtered_values.append(limit)
else:
filtered_values.append(v)
else:
filtered_values = values
self.mesh.ViewObject.setNodeColorByScalars(self.result_object.NodeNumbers, filtered_values)
def show_displacement(self, displacement_factor=0.0):
self.mesh.ViewObject.setNodeDisplacementByVectors(self.result_object.NodeNumbers,
self.result_object.DisplacementVectors)
self.mesh.ViewObject.applyDisplacement(displacement_factor)
def update_objects(self):
# [{'Object':materials_linear}, {}, ...]
# [{'Object':materials_nonlinear}, {}, ...]
# [{'Object':fixed_constraints, 'NodeSupports':bool}, {}, ...]
# [{'Object':force_constraints, 'NodeLoad':value}, {}, ...
# [{'Object':pressure_constraints, 'xxxxxxxx':value}, {}, ...]
# [{'Object':temerature_constraints, 'xxxxxxxx':value}, {}, ...]
# [{'Object':heatflux_constraints, 'xxxxxxxx':value}, {}, ...]
# [{'Object':initialtemperature_constraints, 'xxxxxxxx':value}, {}, ...]
# [{'Object':beam_sections, 'xxxxxxxx':value}, {}, ...]
# [{'Object':shell_thicknesses, 'xxxxxxxx':value}, {}, ...]
# [{'Object':contact_constraints, 'xxxxxxxx':value}, {}, ...]
## @var mesh
# mesh of the analysis. Used to generate .inp file and to show results
self.mesh = None
## @var materials_linear
# set of linear materials from the analysis. Updated with update_objects
# Individual materials are "App::MaterialObjectPython" type
self.materials_linear = []
## @var materials_nonlinear
# set of nonlinear materials from the analysis |
mizahnyx/panda3dplanetgen | mecha01/character_controller.py | Python | bsd-3-clause | 66 | 0 | class CharacterContr | oller():
def __init__(sel | f):
pass
|
Itxaka/st2 | st2tests/st2tests/fixturesloader.py | Python | apache-2.0 | 13,382 | 0.002167 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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 under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import os
import six
from st2common.content.loader import MetaLoader
from st2common.models.api.action import (ActionAPI, LiveActionAPI, ActionExecutionStateAPI,
RunnerTypeAPI, ActionAliasAPI)
from st2common.models.api.execution import (ActionExecutionAPI)
from st2common.models.api.policy import (PolicyTypeAPI, PolicyAPI)
from st2common.models.api.rule import (RuleAPI)
from st2common.models.api.sensor import SensorTypeAPI
from st2common.models.api.trace import TraceAPI
from st2common.models.api.trigger import (TriggerAPI, TriggerTypeAPI, TriggerInstanceAPI)
from st2common.models.db.action import ActionDB
from st2common.models.db.actionalias import ActionAliasDB
from st2common.models.db.liveaction import LiveActionDB
from st2common.models.db.executionstate import ActionExecutionStateDB
from st2common.models.db.runner import RunnerTypeDB
from st2common.models.db.execution import (ActionExecutionDB)
from st2common.models.db.policy import (PolicyTypeDB, PolicyDB)
from st2common.models.db.rule import RuleDB
from st2common.models.db.sensor import SensorTypeDB
from st2common.models.db.trace import TraceDB
from st2common.models.db.trigger import (TriggerDB, TriggerTypeDB, TriggerInstanceDB)
from st2common.persistence.action import Action
from st2common.persistence.actionalias import ActionAlias
from st2common.persistence.execution import ActionExecution
from st2common.persistence.executionstate import ActionExecutionState
from st2common.persistence.liveaction import LiveAction
from st2common.persistence.runner import RunnerType
from st2common.persistence.policy import (PolicyType, Policy)
from st2common.persistence.rule import Rule
from st2common.persistence.sensor import SensorType
from st2common.persistence.trace import Trace
from st2common.persistence.trigger import (Trigger, TriggerType, TriggerInstance)
ALLOWED_DB_FIXTURES = ['actions', 'actionstates', 'aliases', 'executions', 'liveactions',
'policies', 'policytypes', 'rules', 'runners', 'sensors',
'triggertypes', 'triggers', 'triggerinstances', 'traces']
ALLOWED_FIXTURES = copy.copy(ALLOWED_DB_FIXTURES)
ALLOWED_FIXTURES.extend(['actionchains', 'workflows'])
FIXTURE_DB_MODEL = {
'actions': ActionDB,
'aliases': ActionAliasDB,
'actionstates': ActionExecutionStateDB,
'executions': ActionExecutionDB,
'liveactions': LiveActionDB,
'policies': PolicyDB,
'policytypes': PolicyTypeDB,
'rules': RuleDB,
'runners': RunnerTypeDB,
'sensors': SensorTypeDB,
'traces': TraceDB,
'triggertypes': TriggerTypeDB,
'triggers': TriggerDB,
'triggerinstances': TriggerInstanceDB
}
FIXTURE_API_MODEL = {
'actions': ActionAPI,
'aliases': ActionAliasAPI,
'actionstates': ActionExecutionStateAPI,
'executions': ActionExecutionAPI,
'liveactions': LiveActionAPI,
'policies': PolicyAPI,
'policytypes': PolicyTypeAPI,
'rules': RuleAPI,
'runners': RunnerTypeAPI,
'sensors': SensorTypeAPI,
'traces': TraceAPI,
'triggertypes': TriggerTypeAPI,
'triggers': TriggerAPI,
'triggerinstances': TriggerInstanceAPI
}
FIXTURE_PERSISTENCE_MODEL = {
'actions': Action,
'aliases': ActionAlias,
'actionstates': ActionExecutionState,
'executions': ActionExecution,
'liveactions': LiveAction,
'policies': Policy,
'policytypes': PolicyType,
'rules': Rule,
'runners': RunnerType,
'sensors': SensorType,
'traces': Trace,
'triggertypes': TriggerType,
'triggers': Trigger,
'triggerinstances': TriggerInstance
}
def get_fixtures_base_path():
return os.path.join(os.path.dirname(__file__), 'fixtures')
def get_resources_base_path():
return os.path.join(os.path.dirname(__file__), 'resources')
class FixturesLoader(object):
def __init__(self):
self.meta_loader = MetaLoader()
def save_fixtures_to_db(self, fixtures_pack='generic', fixtures_dict=None):
"""
Loads fixtures specified in fixtures_dict into the database
and returns DB models for the fixtures.
fixtures_dict should be of the form:
{
'actions': ['action-1.yaml', 'action-2.yaml'],
'rules': ['rule-1.yaml'],
'liveactions': ['execution-1.yaml']
}
:param fixtures_pack: Name of the pack to load fixtures from.
:type fixtures_pack: ``str``
:param fixtures_dict: Dictionary specifying the fixtures to load for each type.
:type fixtures_dict: ``dict``
:rtype: ``dict``
"""
if fixtures_dict is None:
fixtures_dict = {}
fixtures_pack_path = self._validate_fixtures_pack(fixtures_pack)
self._validate_fixture_dict(fixtures_dict, allowed=ALLOWED_DB_FIXTURES)
db_models = {}
for fixture_type, fixtures in six.iteritems(fixtures_dict):
API_MODEL = FIXTURE_API_MODEL.get(fixture_type, None)
PERSISTENCE_MODEL = FIXTURE_PERSISTENCE_MODEL.get(fixture_type, None)
loaded_fixtures = {}
for fixture in fixtures:
fixture_dict = self.meta_loader.load(
self._get_fixture_file_path_abs(fixtures_pack_path, fixture_type, fixture))
api_model = API_MODEL(**fixture_dict)
db_model = API_MODEL.to_model(api_model)
db_model = PERSISTENCE_MODEL.add_or_update(db_model)
loaded_fixtures[fixture] = db_model
db_models[fixture_type] = loaded_fixtures
return db_models
def load_fixtures(self, fixtures_pack='generic', fixtures_dict=None):
"""
Loads fixtures specified in fixtures_dict. We
simply want to load the meta into dict objects.
fixtures_dict should be of the form:
{
'actionchains': ['actionchain1.yaml', 'actionchain2.yaml'],
'workflows': ['workflow.yaml']
}
:param fixtures_pack: Name of the pack to load fixtures from.
:type fixtures_pack: ``str``
:param fixtures_dict: Dictionary specifying the fixtures to load for each type.
:type fixtures_dict: ``dict``
:rtype: ``dict``
"""
if not fixtures_dict:
return {}
fixtures_pack_path = self._validate_fixtures_pack(fixtures_pack)
self._validate_fixture_dict(fixtures_dict)
all_fixtures = {}
for fixture_type, fixtures in six.iteritems(fixtures_dict):
loaded_fixtures = {}
for fixture in fixtures:
fixture_dict = self.meta_loader.load(
self._get_fixture_file_path_abs(fixtures_pack_path, fixture_type, fixture))
loaded_fixtures[fixture] = fixture_d | ict
all_fixtures[fixture_type] = loaded_fixtures
return all_fixtures
def load_models(self, fixtures_pack='generic', fixtures_dict=None):
"""
Loads fixtures specified in fixtures_dict as db models. This method must be
used for fixtures that h | ave associated DB models. We simply want to load the
meta as DB models but don't want to save them to db.
fixtures_dict should be of the form:
{
'actions': ['action-1.yaml', 'action-2.yaml'],
'rules': ['rule-1.yaml'],
'liveactions': ['execution-1.yaml']
|
nicholasRutherford/nBodySimulator | examples/figureEight.py | Python | mit | 669 | 0.007474 | from nBody.src.body import Body
from nBody.src.nBodySimulator import NBodySimulator
time_step = 0.01
frame_step = 1
length = 20
plot_size = 1.5
file_name = 'figure_eight.mp4'
# X | Y Xv Yv Mass
b1 = Body( 0.9700436, -0.24308753, 0.4666203685, 0.43236573, 1.0)
b2 = Body( -0.9700436, 0.24308753, 0.4666203685, 0.43236573, 1.0)
b3 = Body( 0.0, 0.0, -2*0.4666203685, -2*0. | 43236573, 1.0)
bodies = [b1, b2, b3]
sim = NBodySimulator(bodies)
sim.setG(1)
sim.run(bodies, time_step=time_step, frame_step=frame_step,
length=length, plot_size=plot_size, file_name=file_name)
|
novoid/Memacs | memacs/git.py | Python | gpl-3.0 | 7,503 | 0.001466 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Time-stamp: <2019-11-06 15:23:39 vk>
import logging
import os
import sys
import time
from orgformat import OrgFormat
from memacs.lib.memacs import Memacs
from memacs.lib.orgproperty import OrgProperties
class Commit(object):
"""
class for representing one commit
"""
def __init__(self):
"""
Ctor
"""
self.__empty = True
self.__subject = ""
self.__body = ""
self.__timestamp = ""
self.__author = ""
self.__properties = OrgProperties()
def __set_author_timestamp(self, line):
"""
extracts the date + time from line:
author Forename Lastname <mail> 1234567890 +0000
@param line
"""
self.__empty = False
date_info = line[-16:] # 1234567890 +0000
seconds_since_epoch = float(date_info[:10])
#timezone_info = date_info[11:]
self.__timestamp = OrgFormat.date(
time.localtime(seconds_since_epoch), show_time=True)
self.__author = line[7:line.find("<")].strip()
def add_header(self, line):
"""
adds line to the header
if line contains "author" this method
calls self.__set_author_timestamp(line)
for setting right author + datetime created
every line will be added as property
i.e:
commit <hashtag>
would then be following property:
:COMMIT: <hashtag>
@param line:
"""
se | lf.__em | pty = False
if line != "":
whitespace = line.find(" ")
tag = line[:whitespace].upper()
value = line[whitespace:]
self.__properties.add(tag, value)
if tag == "AUTHOR":
self.__set_author_timestamp(line)
def add_body(self, line):
"""
adds a line to the body
if line starts with Signed-off-by,
also a property of that line is added
"""
line = line.strip()
if line != "":
if line[:14] == "Signed-off-by:":
self.__properties.add("SIGNED-OFF-BY", line[15:])
elif self.__subject == "":
self.__subject = line
else:
self.__body += line + "\n"
def is_empty(self):
"""
@return: True - empty commit
False - not empty commit
"""
return self.__empty
def get_output(self):
"""
@return tuple: output,properties,body for Orgwriter.write_sub_item()
"""
output = self.__author + ": " + self.__subject
return output, self.__properties, self.__body, self.__author, \
self.__timestamp
class GitMemacs(Memacs):
def _parser_add_arguments(self):
"""
overwritten method of class Memacs
add additional arguments
"""
Memacs._parser_add_arguments(self)
self._parser.add_argument(
"-f", "--file", dest="gitrevfile",
action="store",
help="path to a an file which contains output from " + \
" following git command: git rev-list --all --pretty=raw")
self._parser.add_argument(
"-g", "--grep-user", dest="grepuser",
action="store",
help="if you wanna parse only commit from a specific person. " + \
"format:<Forname Lastname> of user to grep")
self._parser.add_argument(
"-e", "--encoding", dest="encoding",
action="store",
help="default encoding utf-8, see " + \
"http://docs.python.org/library/codecs.html#standard-encodings" + \
"for possible encodings")
def _parser_parse_args(self):
"""
overwritten method of class Memacs
all additional arguments are parsed in here
"""
Memacs._parser_parse_args(self)
if self._args.gitrevfile and not \
(os.path.exists(self._args.gitrevfile) or \
os.access(self._args.gitrevfile, os.R_OK)):
self._parser.error("input file not found or not readable")
if not self._args.encoding:
self._args.encoding = "utf-8"
def get_line_from_stream(self, input_stream):
try:
return input_stream.readline()
except UnicodeError as e:
logging.error("Can't decode to encoding %s, " + \
"use argument -e or --encoding see help",
self._args.encoding)
sys.exit(1)
def _main(self):
"""
get's automatically called from Memacs class
read the lines from git-rev-list file,parse and write them to org file
"""
# read file
if self._args.gitrevfile:
logging.debug("using as %s input_stream",
self._args.gitrevfile)
input_stream = open(self._args.gitrevfile)
else:
logging.debug("using sys.stdin as input_stream")
input_stream = sys.stdin
# now go through the file
# Logic (see example commit below)
# first we are in an header and not in an body
# every newline toggles output
# if we are in body then add the body to commit class
# if we are in header then add the header to commit class
#
# commit 6fb35035c5fa7ead66901073413a42742a323e89
# tree 7027c628031b3ad07ad5401991f5a12aead8237a
# parent 05ba138e6aa1481db2c815ddd2acb52d3597852f
# author Armin Wieser <armin.wieser@example.com> 1324422878 +0100
# committer Armin Wieser <armin.wieser@example.com> 1324422878 +0100
#
# PEP8
# Signed-off-by: Armin Wieser <armin.wieser@gmail.com>
was_in_body = False
commit = Commit()
commits = []
line = self.get_line_from_stream(input_stream)
while line:
line = line.rstrip() # removing \n
logging.debug("got line: %s", line)
if line.strip() == "" or len(line) != len(line.lstrip()):
commit.add_body(line)
was_in_body = True
else:
if was_in_body:
commits.append(commit)
commit = Commit()
commit.add_header(line)
was_in_body = False
line = self.get_line_from_stream(input_stream)
# adding last commit
if not commit.is_empty():
commits.append(commit)
logging.debug("got %d commits", len(commits))
if len(commits) == 0:
logging.error("Is there an error? Because i found no commits.")
# time to write all commits to org-file
for commit in commits:
output, properties, note, author, timestamp = commit.get_output()
if not(self._args.grepuser) or \
(self._args.grepuser and self._args.grepuser == author):
# only write to stream if
# * grepuser is not set or
# * grepuser is set and we got an entry with the right author
self._writer.write_org_subitem(output=output,
timestamp=timestamp,
properties=properties,
note=note)
if self._args.gitrevfile:
input_stream.close()
|
openstack/swift | test/unit/container/test_reconciler.py | Python | apache-2.0 | 96,529 | 0 | # 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 under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import numbers
import shutil
from tempfile import mkdtemp
import mock
import operator
import time
import unittest
import socket
import os
import errno
import itertools
import random
import eventlet
from collections import defaultdict
from datetime import datetime
import six
from six.moves import urllib
from swift.common.storage_policy import StoragePolicy, ECStoragePolicy
from swift.common.swob import Request
from swift.container import reconciler
from swift.container.server import gen_resp_headers, ContainerController
from swift.common.direct_client import ClientException
from swift.common import swob
from swift.common.header_key_dict import HeaderKeyDict
from swift.common.utils import split_path, Timestamp, encode_timestamps, mkdirs
from test.debug_logger import debug_logger
from test.unit import FakeRing, fake_http_connect, patch_policies, \
DEFAULT_TEST_EC_TYPE, make_timestamp_iter
from test.unit.common.middleware import helpers
def timestamp_to_last_modified(timestamp):
return datetime.utcfromtimestamp(
float(Timestamp(timestamp))).strftime('%Y-%m-%dT%H:%M:%S.%f')
def container_resp_headers(**kwargs):
return HeaderKeyDict(gen_resp_headers(kwargs))
class FakeStoragePolicySwift(object):
def __init__(self):
self.storage_policy = defaultdict(helpers.FakeSwift)
self._mock_oldest_spi_map = {}
def __getattribute__(self, name):
try:
return object.__getattribute__(self, name)
except AttributeError:
return getattr(self.storage_policy[None], name)
def __call__(self, env, start_response):
method = env['REQUEST_METHOD']
path = env['PATH_INFO']
_, acc, cont, obj = split_path(env['PATH_INFO'], 0, 4,
rest_with_last=True)
if not obj:
policy_index = None
else:
policy_index = self._mock_oldest_spi_map.get(cont, 0)
# allow backend policy override
if 'HTTP_X_BACKEND_STORAGE_POLICY_INDEX' in env:
policy_index = int(env['HTTP_X_BACKEND_STORAGE_POLICY_INDEX'])
try:
return self.storage_policy[policy_index].__call__(
env, start_response)
except KeyError:
pass
if method == 'PUT':
resp_class = swob.HTTPCreated
else:
resp_class = swob.HTTPNotFound
self.storage_policy[policy_index].register(
method, path, resp_class, {}, '')
return self.storage_policy[policy_index].__call__(
env, start_response)
class FakeInternalClient(reconciler.InternalClient):
def __init__(self, listings=None):
self.app = FakeStoragePolicySwift()
self.user_agent = 'fake-internal-client'
self.request_tries = 1
self.use_replication_network = True
self.parse(listings)
self.container_ring = FakeRing()
def parse(self, listings):
listings = listings or {}
self.accounts = defaultdict(lambda: defaultdict(list))
for item, timestamp in listings.items():
# XXX this interface is stupid
if isinstance(timestamp, tuple):
timestamp, content_type = timestamp
else:
timestamp, content_type = timestamp, 'application/x-put'
storage_policy_index, path = item
if six.PY2 and isinstance(path, six.text_type):
path = path.encode('utf-8')
account, container_name, obj_name = split_path(
path, 0, 3, rest_with_last=True)
self.accounts[account][container_name].append(
(obj_name, storage_policy_index, timestamp, content_type))
for account_name, containers in self.accounts.items():
for con in containers:
self.accounts[account_name][con].sort(key=lambda t: t[0])
for account, containers in self.accounts.items():
account_listing_data = []
account_path = '/v1/%s' % account
for container, objects in containers.items():
container_path = account_path + '/' + container
container_listing_data = []
for entry in objects:
(obj_name, storage_policy_index,
timestamp, content_type) = entry
if storage_policy_index is None and not obj_name:
# empty container
continue
obj_path = swob.str_to_wsgi(
container_path + '/' + obj_name)
ts = Timestamp(timestamp)
headers = {'X-Timestamp': ts.normal,
'X-Backend-Timestamp': ts.internal}
# register object response
self.app.storage_policy[storage_policy_index].register(
'GET', obj_path, swob.HTTPOk, headers)
self.app.storage_policy[storage_policy_index].register(
'DELETE', obj_path, swob.HTTPNoContent, {})
# container listing entry
last_modified = timestamp_to_last_modified(timestamp)
# some tests setup mock listings using floats, some use
# strings, so normalize here
if isinstance(timestamp, numbers.Number):
timestamp = '%f' % timestamp
if six.PY2:
obj_name = obj_name.decode('utf-8')
timestamp = timestamp.decode('utf-8')
obj_data = {
'bytes': 0,
# listing data is unicode
'name': obj_name,
'last_modified': last_modified,
'hash': timestamp,
'content_type': content_type,
}
container_listing_data.append(obj_data)
container_listing_data.sort(key=operator.itemgetter('name'))
# register container listing response
container_headers = {}
container_qry_string = helpers.normalize_query_string(
'?format=json&marker=&end_marker=&prefix=')
self.app.register('GET', container_path + container_qry_string,
swob.HTTPOk, container_headers,
json.dumps(container_listing_data))
if container_listing_data:
obj_name = container_listing_data[-1]['name']
# client should quote and encode marker
end_qry_string = helpers.normalize_query_string(
'?format=json&marker=%s&end_marker=&prefix=' % (
urllib.parse.quote(obj_name.encode('utf-8'))))
self.app.register('GET', container_path + end_qry_string,
swob.HTTPOk, container_headers,
json.dumps([]))
self.app | .register('DELETE', container_path,
swob.HTTPConflict, {}, '')
# simple account listing entry
container_data = {'name': container}
account_listing_data.append(container_data)
# register account response
account_listing_data.sort(key=operator.itemgetter('name'))
account_headers = {}
account_qry_string = '?format=json&marker=&end_marker=&prefix | =' |
phiros/nepi | src/nepi/execution/runner.py | Python | gpl-3.0 | 6,329 | 0.009164 | #
# NEPI, a framework to manage network experiments
# Copyright (C) 2013 INRIA
#
# 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 distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Author: Alina Quereilhac <alina.quereilhac@inria.fr>
from nepi.execution.ec import ExperimentController, ECState
import math
import numpy
import os
import time
class ExperimentRunner(object):
""" The ExperimentRunner entity is responsible of
re-running an experiment described by an ExperimentController
multiple time
"""
def __init__(self):
super(ExperimentRunner, self).__init__()
def run(self, ec, min_runs = 1, max_runs = -1, wait_time = 0,
wait_guids = [], compute_metric_callback = None,
evaluate_convergence_callback = None ):
""" Run a same experiment independently multiple times, until the
evaluate_convergence_callback function returns True
:param ec: Description of experiment to replicate.
The runner takes care of deploying the EC, so ec.deploy()
must not be invoked directly before or after invoking
runner.run().
:type ec: ExperimentController
:param min_runs: Minimum number of times the experiment must be
replicated
:type min_runs: int
:param max_runs: Maximum number of times the experiment can be
replicated
:type max_runs: int
:param wait_time: Time to wait in seconds on each run between invoking
ec.deploy() and ec.release().
:type wait_time: float
:param wait_guids: List of guids wait for finalization on each run.
This list is passed to ec.wait_finished()
:type wait_guids: list
:param compute_metric_callback: User defined function invoked after
each experiment run to compute a metric. The metric is usually
a network measurement obtained from the data collected
during experiment execution.
The function is invoked passing the ec and the run number as arguments.
It must return the value for the computed metric(s) (usually a single
numerical v | alue, but it can be several).
metric = compute_metric_callback(ec, run)
:type compute_metric_callback: function
:param evaluate_convergence_callback: User defined function invoked after
computing the metric on each run, to evaluate the experiment was
run enough times. It takes the list of cumulated metrics produced by
| the compute_metric_callback up to the current run, and decided
whether the metrics have statistically converged to a meaningful value
or not. It must return either True or False.
stop = evaluate_convergence_callback(ec, run, metrics)
If stop is True, then the runner will exit.
:type evaluate_convergence_callback: function
"""
if (not max_runs or max_runs < 0) and not compute_metric_callback:
msg = "Undefined STOP condition, set stop_callback or max_runs"
raise RuntimeError, msg
if compute_metric_callback and not evaluate_convergence_callback:
evaluate_convergence_callback = self.evaluate_normal_convergence
ec.logger.info(" Treating data as normal to evaluate convergence. "
"Experiment will stop when the standard error with 95% "
"confidence interval is >= 5% of the mean of the collected samples ")
# Force persistence of experiment controller
ec._persist = True
filepath = ec.save(dirpath = ec.exp_dir)
samples = []
run = 0
stop = False
while not stop:
run += 1
ec = self.run_experiment(filepath, wait_time, wait_guids)
ec.logger.info(" RUN %d \n" % run)
if compute_metric_callback:
metric = compute_metric_callback(ec, run)
if metric is not None:
samples.append(metric)
if run >= min_runs and evaluate_convergence_callback:
if evaluate_convergence_callback(ec, run, samples):
stop = True
if run >= min_runs and max_runs > -1 and run >= max_runs :
stop = True
ec.shutdown()
del ec
return run
def evaluate_normal_convergence(self, ec, run, metrics):
""" Returns True when the confidence interval of the sample mean is
less than 5% of the mean value, for a 95% confidence level,
assuming normal distribution of the data
"""
if len(metrics) == 0:
msg = "0 samples collected"
raise RuntimeError, msg
x = numpy.array(metrics)
n = len(metrics)
std = x.std()
se = std / math.sqrt(n)
m = x.mean()
# Confidence interval for 95% confidence level,
# assuming normally distributed data.
ci95 = se * 2
ec.logger.info(" RUN %d - SAMPLES %d MEAN %.2f STD %.2f CI (95%%) %.2f \n" % (
run, n, m, std, ci95 ) )
return m * 0.05 >= ci95
def run_experiment(self, filepath, wait_time, wait_guids):
""" Run an experiment based on the description stored
in filepath.
"""
ec = ExperimentController.load(filepath)
ec.deploy()
ec.wait_finished(wait_guids)
time.sleep(wait_time)
ec.release()
if ec.state == ECState.FAILED:
raise RuntimeError, "Experiment failed"
return ec
|
MTG/essentia | src/python/essentia/algorithms.py | Python | agpl-3.0 | 5,502 | 0.007997 | # Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the Affero GNU General Public License
# version 3 along with this program. If not, see http://www.gnu.org/licenses/
def create_python_algorithms(essentia):
'''
# Spectral Decrease
class SpectralDecrease(essentia.Decrease):
def configure(self, sampleRate = 44100, **kwargs):
essentia.Decrease.configure(self, range = sampleRate*0.5)
setattr(essentia, 'SpectralDecrease', SpectralDecrease)
# AudioDecrease
class AudioDecrease(essentia. | Decrease):
def configure(self, blockSize, | sampleRate = 44100, **kwargs):
essentia.Decrease.configure(self, range = (blockSize-1.0)/sampleRate)
setattr(essentia, 'AudioDecrease', AudioDecrease)
# SpectralCentroid
class SpectralCentroid(essentia.Centroid):
def configure(self, sampleRate = 44100, **kwargs):
essentia.Centroid.configure(self, range = sampleRate*0.5)
setattr(essentia, 'SpectralCentroid', SpectralCentroid)
# AudioCentroid
class AudioCentroid(essentia.Centroid):
def configure(self, blockSize, sampleRate = 44100, **kwargs):
essentia.Centroid.configure(self, range = (blockSize-1.0)/sampleRate)
setattr(essentia, 'AudioCentroid', AudioCentroid)
# SpectralCentralMoments
class SpectralCentralMoments(essentia.CentralMoments):
def configure(self, sampleRate = 44100, **kwargs):
essentia.CentralMoments.configure(self, range = sampleRate*0.5)
setattr(essentia, 'SpectralCentralMoments', SpectralCentralMoments)
# AudioCentralMoments
class AudioCentralMoments(essentia.CentralMoments):
def configure(self, blockSize, sampleRate = 44100, **kwargs):
essentia.CentralMoments.configure(self, range = (blockSize-1.0)/sampleRate)
setattr(essentia, 'AudioCentralMoments', AudioCentralMoments)
'''
default_fc = essentia.FrameCutter()
# FrameGenerator
class FrameGenerator(object):
__struct__ = { 'name': 'FrameGenerator',
'category': 'Standard',
'inputs': [],
'outputs': [],
'parameters': default_fc.__struct__['parameters'],
'description': '''The FrameGenerator is a Python generator for the FrameCutter algorithm. It is not available in C++.
FrameGenerator inherits all the parameters of the FrameCutter. The way to use it in Python is the following:
for frame in FrameGenerator(audio, frameSize, hopSize):
do_something()
''' }
def __init__(self, audio, frameSize = default_fc.paramValue('frameSize'),
hopSize = default_fc.paramValue('hopSize'),
startFromZero = default_fc.paramValue('startFromZero'),
validFrameThresholdRatio = default_fc.paramValue('validFrameThresholdRatio'),
lastFrameToEndOfFile=default_fc.paramValue('lastFrameToEndOfFile')):
self.audio = audio
self.frameSize = frameSize
self.hopSize = hopSize
self.startFromZero = startFromZero
self.validFrameThresholdRatio = validFrameThresholdRatio
self.lastFrameToEndOfFile=lastFrameToEndOfFile
self.frame_creator = essentia.FrameCutter(frameSize = frameSize,
hopSize = hopSize,
startFromZero = startFromZero,
validFrameThresholdRatio=validFrameThresholdRatio,
lastFrameToEndOfFile=lastFrameToEndOfFile)
def __iter__(self):
return self
def __next__(self):
frame = self.frame_creator.compute(self.audio)
if frame.size == 0:
raise StopIteration
else:
return frame
next = __next__ # Python 2
def num_frames(self):
if self.startFromZero:
if not self.lastFrameToEndOfFile:
size = int(round(len(self.audio) / float(self.hopSize)))
else:
size = int(round((len(self.audio)+self.frameSize) / float(self.hopSize)))
else:
size = int(round((len(self.audio)+self.frameSize/2.0)/float(self.hopSize)))
return size
def frame_times(self, sampleRate):
times = []
if self.startFromZero:
start = self.frameSize/2.0
else:
start = 0.
for i in range(self.num_frames()):
times.append((start + self.hopSize * i) / sampleRate)
return times
setattr(essentia, 'FrameGenerator', FrameGenerator)
|
sniperganso/python-manilaclient | manilaclient/v2/share_servers.py | Python | apache-2.0 | 3,246 | 0 | # Copyright 2014 OpenStack Foundation.
# All Rights Reserved.
#
# 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 under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import six
try:
from urllib import urlencode # noqa
except ImportError:
from urllib.parse import urlencode # noqa
from manilaclient import base
from manilaclient.openstack.common.apiclient import base as common_base
RESOURCES_PATH = '/share-servers'
RESOURCE_PATH = '/share-servers/%s'
RESOURCES_NAME = 'share_servers'
RESOURCE_NAME = 'share_server'
class ShareServer(common_base.Resource):
def __repr__(self):
return "<ShareServer: %s>" % self.id
def __getattr__(self, attr):
if attr == 'share_network':
attr = 'share_network_name'
return super(ShareServer, self).__getattr__(attr)
class ShareServerManager(base.Manager):
"""Manage :class:`ShareServer` resources."""
resource_class = ShareServer
def get(self, server_id):
"""Get a share server.
:param server_id: The ID of the share server to get.
:rtype: :class:`ShareServer`
"""
server = self._get("%s/%s" % (RESOURCES_PATH, server_id),
RESOURCE_NAME)
# Split big d | ict 'backend_details' to separated strings
# as next:
# +---------------------+------------------------------------+
# | Property | Value |
# +------------- | --------+------------------------------------+
# | details:instance_id |35203a78-c733-4b1f-b82c-faded312e537|
# +---------------------+------------------------------------+
for k, v in six.iteritems(server._info["backend_details"]):
server._info["details:%s" % k] = v
return server
def details(self, server_id):
"""Get a share server details.
:param server_id: The ID of the share server to get details from.
:rtype: list of :class:`ShareServerBackendDetails
"""
return self._get("%s/%s/details" % (RESOURCES_PATH, server_id),
"details")
def delete(self, server_id):
"""Delete share server.
:param server_id: id of share server to be deleted.
"""
self._delete(RESOURCE_PATH % server_id)
def list(self, search_opts=None):
"""Get a list of share servers.
:rtype: list of :class:`ShareServer`
"""
query_string = ''
if search_opts:
opts = sorted(
[(k, v) for (k, v) in six.iteritems(search_opts) if v])
query_string = urlencode(opts)
query_string = '?' + query_string if query_string else ''
return self._list(RESOURCES_PATH + query_string, RESOURCES_NAME)
|
amd77/parker | inventario/models.py | Python | gpl-2.0 | 7,559 | 0.005558 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from django.db import models
from django.apps import apps
from empresa.models import Empresa
import json
import os
import tempfile
import datetime
import requests
class Parking(models.Model):
empresa = models.OneToOneField(Empresa)
nombre = models.CharField(max_length=40)
plazas = models.IntegerField()
def __unicode__(self):
return "{} ({})".format(self.nombre, self.empresa)
def tupla_tarifa(self):
"Obtener un tarifario dada una recta definida por puntos"
# creamos una lista de listas
lista = map(list, self.tarifa_set.values_list('precio', 'hora'))
# agregamos el rango final de tiempo sacado de la siguiente linea
n = len(lista)
for i in range(n-1):
lista[i].append(lista[i+1][1])
# el rango final ponemos que es 24h
lista[n-1].append(datetime.timedelta(days=1))
# devolvemos [precio, hora_start, hora_end_no_inclusive]
return lista
def tabla_tarifa(self):
"Tarifario con hh:mm para visualizar"
for precio, min0, min1 in self.tupla_tarifa():
t = min1 - datetime.timedelta(seconds=1)
yield min0, t, precio
def get_dia(self):
return float(self.tarifa_set.last().precio)
def get_tarifa(self, td):
"Obtener una tarifa del tarifario"
# calculo de dias completos
precio_dias = td.days * self.get_dia()
# calculo de la fraccion de dia
td = datetime.timedelta(seconds=td.seconds)
for precio, min0, min1 in self.tupla_tarifa():
if min0 <= td < min1:
return precio_dias + float(precio)
def barreras_entrada(self):
return self.barrera_set.filter(entrada=True)
def barreras_salida(self):
return self.barrera_set.filter(entrada=False)
def nodos_remotos(self):
return self.nodoremoto_set.all()
@property
def entrada_set(self):
Entrada = apps.get_model('tickets.Entrada')
return Entrada.objects.por_parking(self)
@property
def coches_hoy(self):
return self.entrada_set.de_hoy().count()
@property
def coches_dentro(self):
return self.entrada_set.de_hoy().dentro().count()
class Expendedor(models.Model):
parking = models.ForeignKey(Parking)
nombre = models.CharField(max_length=40)
mac = models.CharField(max_length=17)
camera_command = models.CharField(max_length=255, blank=True, null=True, help_text="Comando para la camara, "
"con {} donde queramos poner el output filename")
def saca_foto(self):
contenido = None
if self.camera_command:
filename = tempfile.mktemp()
ret = os.system(self.camera_command.format(filename))
if ret == 0:
contenido = open(filename).read()
if os.path.isfile(filename):
os.unlink(filename)
return contenido
def __unicode__(self):
return "{} de {}".format(self.nombre, self.parking.nombre)
class Meta:
verbose_name = 'expendedor'
verbose_name_plural = 'expendedores'
class Barrera(models.Model):
parking = models.ForeignKey(Parking)
nombre = models.CharField(max_length=40)
slug = models.CharField(max_length=40, unique=True)
entrada = models.BooleanField()
abre_url = models.URLField(max_length=100, blank=True, null=True, help_text="si hay url es que esta activo")
abre_post = models.CharField(max_length=100, blank=True, null=True, help_text="post data en formato json")
abresiempre_url = models.URLField(max_length=100, blank=True, null=True, help_text="si hay url es que esta activo")
abresiempre_post = models.CharField(max_length=100, blank=True, null=True, help_text="post data en formato json")
cierra_url = models.URLField(max_length=100, blank=True, null=True, help_text="si hay url es que esta activo")
cierra_post = models.CharField(max_length=100, blank=True, null=True, help_text="post data en formato json")
def abre(self):
if self.abre_post:
r = requests.post(self.abre_url, data=json.loads(self.abre_post))
else:
| r = requests.get(self.abre_url)
return r.status_code == 200
def abresiempre(self):
if self.abresiempre_post:
r = requests.post(self.abresiempre_url, data=json.loads(self.abresiempre_post))
else:
r = requests.get(self.abresiempre_url)
return r.status_code == 200
def cierra(self):
if self.cierra_post:
r = requests.post(self.cierra_url, data=json.loads(s | elf.cierra_post))
else:
r = requests.get(self.cierra_url)
return r.status_code == 200
def __unicode__(self):
return "{} ({} de {})".format(self.slug, "entrada" if self.entrada else "salida", self.parking.nombre)
class Meta:
verbose_name = 'barrera'
verbose_name_plural = 'barreras'
class Tarifa(models.Model):
parking = models.ForeignKey(Parking)
precio = models.DecimalField(max_digits=5, decimal_places=2)
hora = models.DurationField(help_text="hora a partir de la cual aplica este precio")
def __unicode__(self):
return "{} = {:.2f} €".format(self.hora, self.precio)
class Meta:
ordering = ('hora', )
class NodoRemoto(models.Model):
parking = models.ForeignKey(Parking)
host_name = models.CharField(max_length = 100, blank = True, null = True, help_text = 'Nombre del Host')
url = models.CharField(max_length = 100, blank=True, null=True, help_text = ' url del demonio nameko' )
nombre = models.CharField(max_length=100, blank=True, null=True, help_text = 'Nombre del demonio nameko')
def __unicode__(self):
return "{} [{}]".format(self.nombre, self.url)
def comandos(self):
return self.comandoremoto_set.all()
class Meta:
verbose_name = 'Nodo Remoto'
verbose_name_plural = 'Nodos Remotos'
class ComandoRemoto(models.Model):
nombre = models.CharField(max_length = 100, blank=True, null=True, help_text = 'nombre del comando')
comando = models.CharField(max_length = 100, blank=True, null=True, help_text= 'comando')
nodoremoto = models.ForeignKey(NodoRemoto)
def __unicode__(self):
return "{}: {}.{}()".format(self.nombre, self.nodoremoto, self.comando)
class Meta:
verbose_name = 'comando Remoto'
verbose_name_plural = 'Comandos Remotos'
# from django.db.models.signals import pre_save
# from django.dispatch import receiver
# @receiver(pre_save, sender=Tarifa)
# def anula_date(sender, instance, using, **kwargs):
# if isinstance(instance, datetime.datetime):
# instance.hora = instance.hora.replace(year=1970, month=1, day=1)
class Visor(models.Model):
url = models.URLField(default="http://192.168.1.1:8000")
descripcion = models.CharField(default="visor colocado en ...", max_length=200)
parking = models.ForeignKey(Parking)
def mostrar_importe(self, importe):
imprte_str = "{:.2f}".format(importe)
# print("importe " + imprte_str)
try:
r = requests.post(self.url, json={"importe": importe})
except:
return False
r = requests.post(self.url, json={"importe": importe})
return r.status_code == 200
def __str__(self):
return self.descripcion
class Meta:
verbose_name_plural = 'Visores'
|
astrand/pyobfuscate | test/testfiles/power.py | Python | gpl-2.0 | 40 | 0 |
import sys
x = 2
| y = | x**2
sys.exit(y)
|
warrenatmindset/DjangoFlowApp | questionnaires/migrations/0002_auto_20171113_0933.py | Python | mit | 440 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017 | -11-13 09:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('questionnaires', '0001_initial'),
]
operations = [
migrat | ions.RenameModel(
old_name='AttentionRelatedCognitiveErrors',
new_name='AttentionRelatedCognitiveError',
),
]
|
ricoen/drip_boot | drip_boot.py | Python | gpl-3.0 | 1,411 | 0.002126 | from sklearn import tree
import pyfirmata
import time
import pandas
from pandas.tools.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
url = "https://raw.githubusercontent.com/ricoen/drip_boot/master/data/coba.data"
names = ['moisture', 'action']
dataset = pandas.read_csv(url, names=names)
array = dataset.value | s
moisture = array[:,:]
temp = [30, 30, 25, 25]
magic = tree.DecisionTreeClassifier()
magic = magic.fit(moisture, temp)
pin= 13
port = 'COM3'
board = pyfirmata.Arduino(port)
a = input('moisture? \n')
b = input('t | emp? \n')
data = int(a)
if b.lower() >= '30':
temp = 30
elif b.lower() <= '30':
temp = 25
else:
print('kondisi anomali, harap periksa alat')
c = magic.predict([[data, temp]])
if c == 30:
d = 'Siram'
board.digital[pin].write(1)
else:
d = 'Tidak perlu disiram'
board.digital[pin].write(0)
print('\n {}'.format(d))
board.exit()
|
ESS-LLP/frappe | frappe/data_migration/doctype/data_migration_connector/connectors/calendar_connector.py | Python | mit | 8,438 | 0.028206 | from __future__ import unicode_literals
import frappe
from frappe.data_migration.doctype.data_migration_connector.connectors.base import BaseConnection
import googleapiclient.discovery
import google.oauth2.credentials
from googleapiclient.errors import HttpError
import time
from datetime import datetime
from frappe.utils import add_days, add_years
class CalendarConnector(BaseConnection):
def __init__(self, connector):
self.connector = connector
settings = frappe.get_doc("GCalendar Settings", None)
self.account = frappe.get_doc("GCalendar Account", connector.username)
self.credentials_dict = {
'token': self.account.get_password(fieldname='session_token', raise_exception=False),
'refresh_token': self.account.get_password(fieldname='refresh_token', raise_exception=False),
'token_uri': 'https://www.googleapis.com/oauth2/v4/token',
'client_id': settings.client_id,
'client_secret': settings.get_password(fieldname='client_secret', raise_exception=False),
'scopes':'https://www.googleapis.com/auth/calendar'
}
self.name_field = 'id'
self.credentials = google.oauth2.credentials.Credentials(**self.credentials_dict)
self.gcalendar = googleapiclient.discovery.build('calendar', 'v3', credentials=self.credentials)
self.check_remote_calendar()
def check_remote_calendar(self):
def _create_calendar():
timezone = frappe.db.get_value("System Settings", None, "time_zone")
calendar = {
'summary': self.account.calendar_name,
'timeZone': timezone
}
try:
created_calendar = self.gcalendar.calendars().insert(body=calendar).execute()
frappe.db.set_value("GCalendar Account", self.account.name, "gcalendar_id", created_calendar["id"])
except Exception:
frappe.log_error(frappe.get_traceback())
try:
if self.account.gcalendar_id is not None:
try:
self.gcalendar.calendars().get(calendarId=self.account.gcalendar_id).execute()
except Exception:
frappe.log_error(frappe.get_traceback())
else:
_create_calendar()
except HttpError as err:
if err.resp.status in [403, 500, 503]:
time.sleep(5)
elif err.resp.status in [404]:
_create_calendar()
else: raise
def get(self, remote_objectname, fields=None, filters=None, start=0, page_length=10):
return self.get_events(remote_objectname, filters, page_length)
def insert(self, doctype, doc):
if doctype == 'Events':
from frappe.desk.doctype.event.event import has_permission
d = frappe.get_doc("Event", doc["name"])
if has_permission(d, self.account.name):
if doc["start_datetime"] >= datetime.now():
try:
doctype = "Event"
e = self.insert_events(doctype, doc)
return e
except Exception:
frappe.log_error(frappe.get_traceback(), "GCalendar Synchronization Error")
def update(self, doctype, doc, migration_id):
if doctype == 'Events':
from frappe.desk.doctype.event.event import has_permission
d = frappe.get_doc("Event", doc["name"])
if has_permission(d, self.account.name):
if doc["start_datetime"] >= datetime.now() and migration_id is not None:
try:
doctype = "Event"
return self.update_events(doctype, doc, migration_id)
except Exception:
frappe.log_error(frappe.get_traceback(), "GCalendar Synchronization Error")
def delete(self, doctype, migration_id):
if doctype == 'Events':
try:
return self.delete_events(migration_id)
except Exception:
frappe.log_error(frappe.ge | t_traceback(), "GCalendar Synchronization Error")
def get_events(self, remote_objectname, filters, page_length):
page_token = None
results = []
events = {"items": []}
while True:
try:
events = self.gcalendar.events().list(calendarId=self.account.gcalendar_id, maxResults=page_length,
singleEvents=False, showDeleted=Tr | ue, syncToken=self.account.next_sync_token or None).execute()
except HttpError as err:
if err.resp.status in [410]:
events = self.gcalendar.events().list(calendarId=self.account.gcalendar_id, maxResults=page_length,
singleEvents=False, showDeleted=True, timeMin=add_years(None, -1).strftime('%Y-%m-%dT%H:%M:%SZ')).execute()
else:
frappe.log_error(err.resp, "GCalendar Events Fetch Error")
for event in events['items']:
event.update({'account': self.account.name})
event.update({'calendar_tz': events['timeZone']})
results.append(event)
page_token = events.get('nextPageToken')
if not page_token:
if events.get('nextSyncToken'):
frappe.db.set_value("GCalendar Account", self.connector.username, "next_sync_token", events.get('nextSyncToken'))
break
return list(results)
def insert_events(self, doctype, doc, migration_id=None):
event = {
'summary': doc.summary,
'description': doc.description
}
dates = self.return_dates(doc)
event.update(dates)
if migration_id:
event.update({"id": migration_id})
if doc.repeat_this_event != 0:
recurrence = self.return_recurrence(doctype, doc)
if not not recurrence:
event.update({"recurrence": ["RRULE:" + str(recurrence)]})
try:
remote_event = self.gcalendar.events().insert(calendarId=self.account.gcalendar_id, body=event).execute()
return {self.name_field: remote_event["id"]}
except Exception:
frappe.log_error(frappe.get_traceback(), "GCalendar Synchronization Error")
def update_events(self, doctype, doc, migration_id):
try:
event = self.gcalendar.events().get(calendarId=self.account.gcalendar_id, eventId=migration_id).execute()
event = {
'summary': doc.summary,
'description': doc.description
}
if doc.event_type == "Cancel":
event.update({"status": "cancelled"})
dates = self.return_dates(doc)
event.update(dates)
if doc.repeat_this_event != 0:
recurrence = self.return_recurrence(doctype, doc)
if recurrence:
event.update({"recurrence": ["RRULE:" + str(recurrence)]})
try:
updated_event = self.gcalendar.events().update(calendarId=self.account.gcalendar_id, eventId=migration_id, body=event).execute()
return {self.name_field: updated_event["id"]}
except Exception as e:
frappe.log_error(e, "GCalendar Synchronization Error")
except HttpError as err:
if err.resp.status in [404]:
self.insert_events(doctype, doc, migration_id)
else:
frappe.log_error(err.resp, "GCalendar Synchronization Error")
def delete_events(self, migration_id):
try:
self.gcalendar.events().delete(calendarId=self.account.gcalendar_id, eventId=migration_id).execute()
except HttpError as err:
if err.resp.status in [410]:
pass
def return_dates(self, doc):
timezone = frappe.db.get_value("System Settings", None, "time_zone")
if doc.end_datetime is None:
doc.end_datetime = doc.start_datetime
if doc.all_day == 1:
return {
'start': {
'date': doc.start_datetime.date().isoformat(),
'timeZone': timezone,
},
'end': {
'date': add_days(doc.end_datetime.date(), 1).isoformat(),
'timeZone': timezone,
}
}
else:
return {
'start': {
'dateTime': doc.start_datetime.isoformat(),
'timeZone': timezone,
},
'end': {
'dateTime': doc.end_datetime.isoformat(),
'timeZone': timezone,
}
}
def return_recurrence(self, doctype, doc):
e = frappe.get_doc(doctype, doc.name)
if e.repeat_till is not None:
end_date = datetime.combine(e.repeat_till, datetime.min.time()).strftime('UNTIL=%Y%m%dT%H%M%SZ')
else:
end_date = None
day = []
if e.repeat_on == "Every Day":
if e.monday is not None:
day.append("MO")
if e.tuesday is not None:
day.append("TU")
if e.wednesday is not None:
day.append("WE")
if e.thursday is not None:
day.append("TH")
if e.friday is not None:
day.append("FR")
if e.saturday is not None:
day.append("SA")
if e.sunday is not None:
day.append("SU")
day = "BYDAY=" + ",".join(str(d) for d in day)
frequency = "FREQ=DAILY"
elif e.repeat_on == "Every Week":
frequency = "FREQ=WEEKLY"
elif e.repeat_on == "Every Month":
frequency = "FREQ=MONTHLY;BYDAY=SU,MO,TU,WE,TH,FR,SA;BYSETPOS=-1"
end_date = datetime.combine(add_days(e.repeat_till, 1), datetime.min.time()).strf |
johnmgregoire/vanDover_CHESS | ui_highlowDialog.py | Python | bsd-3-clause | 2,451 | 0.00408 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\JohnnyG\Documents\XRDproject_Python_11June2010Release backup\highlowDialog.ui'
#
# Created: Mon Jun 14 16:20:37 2010
# by: PyQt4 UI code generator 4.5.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_highlowDialog(object):
def setupUi(self, highlowDialog):
highlowDialog.setObjectName("highlowDialog")
highlowDialog.resize(352, 128)
self.buttonBox = QtGui.QDialogButtonBox(highlowDialog)
self.buttonBox.setGeometry(QtCore.QRect(0, 70, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.lowSpinBox = QtGui.QDoubleSpinBox(highlowDialog)
self.lowSpinBox.setGeometry(QtCore.QRect(20, 40, 62, 22))
self.lowSpinBox.setMinimum(-1000000.0)
self.lowSpinBox.setMaximum(1000000.0)
self.lowSpinBox | .setObjectName("lowSpinBox")
self.highSpinBox = QtGui.QDoubleSpinBox(highlowDialog)
self.highSpinBox.setGeometry(QtCore.QRect(100, 40, 62, 20))
self.highSpinBox.setMinimum(-1000000.0)
self.highSpinBox.setMaximum(1000000.0)
self.highSpinBox.setObjectName("highSpinBox")
self.label = QtGui.QLabel(highlowDialog)
self.label.setGeomet | ry(QtCore.QRect(20, 20, 71, 16))
self.label.setObjectName("label")
self.label_2 = QtGui.QLabel(highlowDialog)
self.label_2.setGeometry(QtCore.QRect(100, 20, 76, 16))
self.label_2.setObjectName("label_2")
self.retranslateUi(highlowDialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), highlowDialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), highlowDialog.reject)
QtCore.QMetaObject.connectSlotsByName(highlowDialog)
def retranslateUi(self, highlowDialog):
highlowDialog.setWindowTitle(QtGui.QApplication.translate("highlowDialog", "Enter range for colorbar", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("highlowDialog", "low value", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("highlowDialog", "high value", None, QtGui.QApplication.UnicodeUTF8))
|
ericholscher/django | django/utils/datetime_safe.py | Python | bsd-3-clause | 2,751 | 0.002908 | # Python's datetime strftime doesn't handle dates before 1900.
# These classes override date and datetime to support the formatting of a date
# through its full "proleptic Gregorian" date range.
#
# Based on code submitted to comp.lang.python by Andrew Dalke
#
# >>> datetime_safe.date(1850, 8, 2).strftime("%Y/%m/%d was a %A")
# '1850/08/02 was a Friday'
from datetime import date as real_date, datetime as real_datetime
import re
import time
class date(real_date):
def strftime(self, fmt):
return strftime(self, fmt)
class datetime(real_datetime):
def strftime(self, fmt):
return strftime(self, fmt)
@classmethod
def combine(cls, date, time):
return cls(date.year, date.month, date.day,
time.hour, time.minute, time.second,
time.microsecond, time.tzinfo)
def date(self):
return date(self.year, self.month, self.day)
def new_date(d):
"Generate a safe date from a datetime.date object."
return date(d.year, d.month, d.day)
def new_datetime(d):
"""
Generate a safe datetime from a datetime.date or datetime.datetime object.
"""
kw = [d.year, d.month, d.day]
if isinstance(d, real_datetime):
kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo])
return datetime(*kw)
# This library does not support strftime's "%s" or "%y" format strings.
# Allowed if there's an even number of "%"s because they are escaped.
_illegal_formatting = re.compile(r"((^|[^%])(%%)*%[sy])")
def _findall(text, substr):
# Also finds overlaps
sites = []
i = 0
while 1:
j = text.find(substr, i)
if j == -1:
break
sites.append(j)
i = j + 1
return sites
def strftime(dt, fmt):
if dt.year >= 1900:
return super(type(dt), dt).strftime(fmt)
illegal_formatting = _illegal_formatting.search(fmt)
if illegal_formatting:
raise TypeError("strftime of dates before 1900 does not handle" + illegal_formatting.group(0))
year = dt.year
# For every non-leap year century, advance by
# 6 years to get into the 28-year repeat cycle
delta = 2000 - year
off = 6 * (delta // 100 + delta // 400 | )
year = year + off
# Move to around the year 2000
year = year + ((2000 - year) // 28) * 28
timetuple = dt.timetuple()
s1 = time.strftime(fmt, (year,) + timetuple[1:])
sites1 = _findall(s1, str(year))
s2 = time.strftime(fmt, (year+28,) + timetuple[1:])
sites2 = _findall(s2, str(year+28))
sites = []
for site in sites1:
if site in sites2:
sites.append(site)
s = s1
syear = "%04d" % (dt.year,)
for site in sites:
s = s[:site] + s | year + s[site+4:]
return s
|
petr-devaikin/commonview | web/env_settings.py | Python | gpl-2.0 | 395 | 0.022785 | from os import environ
def load_env(app):
if 'DATABASE_URI' in environ: app.config['DATABASE_URI'] = environ.get('DATABASE_URI')
if 'INSTA_ID' in environ: app.config['INSTA_ID'] = environ.get('INSTA_ID')
if 'INSTA_SECR | ET' in environ: app.config['INSTA_SECRET'] = environ.get('INSTA_SECRET')
if 'SECRET_KEY' in environ: app | .config['SECRET_KEY'] = environ.get('SECRET_KEY')
|
tseaver/google-cloud-python | spanner/google/cloud/spanner_admin_database_v1/gapic/database_admin_client_config.py | Python | apache-2.0 | 2,633 | 0 | config = {
"interfaces": {
"google.spanner.admin.database.v1.DatabaseAdmin": {
"retry_codes": {
"idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"],
"non_idempotent": [],
},
"retry_params": {
"default": {
"initial_retry_delay_millis": 1000,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 32000,
"initial_rpc_timeout_millis": 60000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 60000,
"total_timeout_millis": 600000,
}
},
"methods": {
"ListDatabases": {
"timeout_millis": 30000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"CreateDatabase": {
| "timeout_millis | ": 3600000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
"GetDatabase": {
"timeout_millis": 30000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"UpdateDatabaseDdl": {
"timeout_millis": 3600000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"DropDatabase": {
"timeout_millis": 3600000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"GetDatabaseDdl": {
"timeout_millis": 30000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"SetIamPolicy": {
"timeout_millis": 30000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
"GetIamPolicy": {
"timeout_millis": 30000,
"retry_codes_name": "idempotent",
"retry_params_name": "default",
},
"TestIamPermissions": {
"timeout_millis": 30000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default",
},
},
}
}
}
|
rohitranjan1991/home-assistant | homeassistant/components/progettihwsw/switch.py | Python | mit | 2,686 | 0.000372 | """Control switches."""
from datetime import timedelta
import logging
from ProgettiHWSW.relay import Relay
import async_timeout
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
)
from . import setup_switch
from .const import DEFAULT_POLLING_INTERVAL_SEC, DOMAIN
_LOGGER = logging.getLogger(DOMAIN)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the switches from a config entry."""
board_api = hass.data[DOMAIN][config_entry.entry_id]
relay_count = config_entry.data["relay_count"]
switches = []
async def async_update_data():
"""Fetch data from API endpoint of board."""
async with async_timeout.timeout(5):
return await board_api.get_switches()
coordinator = DataUpdateCoordinator(
hass,
_LOGGER,
name="switch",
update_method=async_update_data,
update_interval=timedelta(seconds=DEFAULT_POLLING_INTERVAL_SEC),
)
await coordinator.async_refresh()
for i in range(1, int(relay_count) + 1):
switches.append(
ProgettihwswSwitch(
coordinator,
f"Relay #{i}",
setup_switch(board_api, i, config_entry.data[f"relay_{str(i)}"]),
)
)
async_add_entities(switches)
class ProgettihwswSwitch(CoordinatorEntity, SwitchEntity):
"""Represent a switch entity."""
def __init__(self, coordinator, name, switch: Relay):
"""Initialize the values."""
super().__init__(coordinator)
self._switch = sw | itch
self._name = name
async def async_turn_on(self, **kwargs):
"""Turn the switch on."""
await self._switch.control(True)
await self.coordinator.async_request_refresh()
async def async_turn_off(self, **kwargs | ):
"""Turn the switch off."""
await self._switch.control(False)
await self.coordinator.async_request_refresh()
async def async_toggle(self, **kwargs):
"""Toggle the state of switch."""
await self._switch.toggle()
await self.coordinator.async_request_refresh()
@property
def name(self):
"""Return the switch name."""
return self._name
@property
def is_on(self):
"""Get switch state."""
return self.coordinator.data[self._switch.id]
|
helfertool/helfertool | src/badges/views/settings.py | Python | agpl-3.0 | 4,316 | 0.000463 | from django.conf import settings as django_settings
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.http import HttpResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.cache import never_cache
from helfertool.utils import nopermission
from registration.models import Event
from registration.permissions import has_access, ACCESS_BADGES_EDIT
from ..forms import BadgeSettingsForm, BadgeDefaultsForm, BadgeJobDefaultsForm
from .utils import notactive
@login_required
@never_cache
def settings(request, event_url_name):
event = get_object_or_404(Event, url_name=event_url_name)
# check permission
if not has_access(request.user, event, ACCESS_BADGES_EDIT):
return nopermission(re | quest)
# check if badge system is active
if not event.badges:
return notactive(request)
# roles
roles = event.badge_settings.badgerole_set.all()
# designs
designs = event.badge_settings.badgedesign_set.all()
# forms for defaults
defaults_form = Ba | dgeDefaultsForm(request.POST or None,
instance=event.badge_settings.defaults,
settings=event.badge_settings,
prefix='event')
job_defaults_form = BadgeJobDefaultsForm(request.POST or None, event=event,
prefix='jobs')
if defaults_form.is_valid() and job_defaults_form.is_valid():
defaults_form.save()
job_defaults_form.save()
return redirect('badges:settings', event_url_name=event.url_name)
context = {'event': event,
'roles': roles,
'designs': designs,
'defaults_form': defaults_form,
'job_defaults_form': job_defaults_form}
return render(request, 'badges/settings.html', context)
@login_required
@never_cache
def settings_advanced(request, event_url_name):
event = get_object_or_404(Event, url_name=event_url_name)
# check permission
if not has_access(request.user, event, ACCESS_BADGES_EDIT):
return nopermission(request)
# check if badge system is active
if not event.badges:
return notactive(request)
# form for settings
form = BadgeSettingsForm(request.POST or None, request.FILES or None,
instance=event.badge_settings)
# for for permissions
permissions = event.badge_settings.badgepermission_set.all()
if form.is_valid():
form.save()
return redirect('badges:settings_advanced', event_url_name=event.url_name)
# render
context = {'event': event,
'form': form,
'permissions': permissions}
return render(request, 'badges/settings_advanced.html',
context)
@login_required
@never_cache
def default_template(request, event_url_name):
event = get_object_or_404(Event, url_name=event_url_name)
# check permission
if not has_access(request.user, event, ACCESS_BADGES_EDIT):
return nopermission(request)
# check if badge system is active
if not event.badges:
return notactive(request)
# output
response = HttpResponse(content_type='application/x-tex')
response['Content-Disposition'] = 'attachment; filename="template.tex"'
# send file
with open(django_settings.BADGE_DEFAULT_TEMPLATE, 'rb') as f:
response.write(f.read())
return response
@login_required
@never_cache
def current_template(request, event_url_name):
event = get_object_or_404(Event, url_name=event_url_name)
# check permission
if not has_access(request.user, event, ACCESS_BADGES_EDIT):
return nopermission(request)
# check if badge system is active
if not event.badges:
return notactive(request)
# check if file is there
if not event.badge_settings.latex_template:
raise Http404()
# output
response = HttpResponse(content_type='application/x-tex')
response['Content-Disposition'] = 'attachment; filename="template_{}.tex"'.format(event.url_name)
# send file
with event.badge_settings.latex_template.open('rb') as f:
response.write(f.read())
return response
|
turbokongen/home-assistant | tests/components/zha/conftest.py | Python | apache-2.0 | 6,990 | 0.001144 | """Test configuration for the ZHA component."""
from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
import pytest
import zigpy
from zigpy.application import ControllerApplication
import zigpy.config
import zigpy.group
import zigpy.types
from homeassistant.components.zha import DOMAIN
import homeassistant.components.zha.core.const as zha_const
import homeassistant.components.zha.core.device as zha_core_device
from homeassistant.setup import async_setup_component
from .common import FakeDevice, FakeEndpoint, get_zha_gateway
from tests.common import MockConfigEntry
from tests.components.light.conftest import mock_light_profiles # noqa
FIXTURE_GRP_ID = 0x1001
FIXTURE_GRP_NAME = "fixture group"
@pytest.fixture
def zigpy_app_controller():
"""Zigpy ApplicationController fixture."""
app = MagicMock(spec_set=ControllerApplication)
app.startup = AsyncMock()
app.shutdown = AsyncMock()
groups = zigpy.group.Groups(app)
groups.add_group(FIXTURE_GRP_ID, FIXTURE_GRP_NAME, suppress_event=True)
app.configure_mock(groups=groups)
type(app).ieee = PropertyMock()
app.ieee.return_value = zigpy.types.EUI64.convert("00:15:8d:00:02:32:4f:32")
type(app).nwk = PropertyMock(return_value=zigpy.types.NWK(0x0000))
type(app).devices = PropertyMock(return_value={})
return app
@pytest.fixture(name="config_entry")
async def config_entry_fixture(hass):
"""Fixture representing a config entry."""
entry = MockConfigEntry(
version=2,
domain=zha_const.DOMAIN,
data={
zigpy.config.CONF_DEVICE: {zigpy.config.CONF_DEVICE_PATH: "/dev/ttyUSB0"},
zha_const.CONF_RADIO_TYPE: "ezsp",
},
)
entry.add_to_hass(hass)
return entry
@pytest.fixture
def setup_zha(hass, config_entry, zigpy_app_controller):
"""Set up ZHA component."""
zha_config = {zha_const.CONF_ENABLE_QUIRKS: False}
p1 = patch(
"bellows.zigbee.application.ControllerApplication.new",
return_value=zigpy_app_controller,
)
async def _setup(config=None):
config = config or {}
with p1:
status = await async_setup_component(
hass, zha_const.DOMAIN, {zha_const.DOMAIN: {**zha_config, **config}}
)
assert status is True
await hass.async_block_till_done()
return _setup
@pytest.fixture
def channel():
"""Channel mock factory fixture."""
def channel(name: str, cluster_id: int, endpoint_id: int = 1):
ch = MagicMock()
ch.name = name
ch.generic_id = f"channel_0x{cluster_id:04x}"
ch.id = f"{endpoint_id}:0x{cluster_id:04x}"
ch.async_configure = AsyncMock()
ch.async_initialize = AsyncMock()
return ch
return channel
@pytest.fixture
def zigpy_device_mock(zigpy_app_controller):
"""Make a fake device using the specified cluster classes."""
def _mock_dev(
endpoints,
ieee="00:0d:6f:00:0a:90:69:e7",
manufacturer="FakeManufacturer",
model="FakeModel",
node_descriptor=b"\x02@\x807\x10\x7fd\x00\x00*d\x00\x00",
nwk=0xB79C,
patch_cluster=True,
):
"""Make a fake device using the specified cluster classes."""
device = FakeDevice(
zigpy_app_controller, ieee, manufacturer, model, node_descriptor, nwk=nwk
)
for epid, ep in endpoints.items():
endpoint = FakeEndpoint(manufacturer, model, epid)
endpoint.device = device
device.endpoints[epid] = endpoint
endpoint.device_type = ep["device_type"]
profile_id = ep.get("profile_id")
if profile_id:
endpoint.profile_id = profile_id
for cluster_id in ep.get("in_clusters", []):
endpoint.add_input_cluster(cluster_id, _patch_cluster=patch_cluster)
for cluster_id in ep.get("out_clusters", []):
endpoint.add_output_cluster(cluster_id, _patch_cluster=patch_cluster)
return device
return _mock_dev
@pytest.fixture
def zha_device_joined(hass, setup_zha):
"""Return a newly joined ZHA device."""
async def _zha_device(zigpy_dev):
await setup_zha()
zha_gateway = get_zha_gateway(hass)
await zha_gateway.async_device_initialized(zigpy_dev)
await hass.async_block_till_done()
return zha_gateway.get_device(zigpy_dev.ieee)
return _zha_device
@pytest.fixture
def zha_device_restored(hass, zigpy_app_controller, setup_zha, hass_storage):
"""Return a restored ZHA device."""
async def _zha_device(zigpy_dev, last_seen=None):
zigpy_app_controller.devices[zigpy_dev.ieee] = zigpy_dev
if last_seen is not None:
hass_storage[f"{DOMAIN}.storage"] = {
"key": f"{DOMAIN}.storage",
"version": 1,
"data": {
"devices": [
{
"ieee": str(zigpy_dev.ieee),
"last_seen": last_seen,
"name": f"{zigpy_dev.manufacturer} {zigpy_dev.model}",
}
],
},
}
await setup_zha()
zha_gateway = hass.data[zha_const.DATA_ZHA][zha_const.DATA_ZHA_GATEWAY]
return zha_gateway.get_device(zigpy_dev.ieee)
return _zha_device
@pytest.fixture(params=["zha_device_joined", "zha_device_restored"])
def zha_device_joined_restored(request):
"""Join or restore ZHA device."""
named_method = request.getfixturevalue(request.param)
named_method.name = request.param
return named_method
@pytest.fixture
def zha_device_mock(hass, zigpy_device_mock):
"""Return a zha Device factory."""
def _zha_device(
endpoints=None,
ieee="00:11:22:33:44:55:66:77",
manufacturer="mock manufacturer",
model="mock model",
node_desc=b"\x02@\x807\x10\x7fd\x00\x00*d\x00\x00",
patch_cluster=True,
):
if endpoints is None:
endpoints = {
1: {
"in_clusters": [0, 1, 8, 768],
"out_clusters": [0x19],
"device_type": 0x0105,
},
2: {
"in_clusters": [0],
"out_clusters": [6, 8, 0x19, 768],
"device_type": 0x0810,
},
}
zigpy_device = zigpy_device_mock(
endpoints, ieee, manufacturer, model, node_desc, patch_cluster=patch_cluster
)
zha_device = zha_core_device.ZHADevice(hass, zigpy_device, MagicMock())
return zha_device
return _zha_device
@pytest.fixture
def hass_disable_services(hass):
"""Mock serv | ice register."""
with patch.object( | hass.services, "async_register"), patch.object(
hass.services, "has_service", return_value=True
):
yield hass
|
charbeljc/maintainer-tools | oca/tools/check_contrib.py | Python | agpl-3.0 | 4,010 | 0.000249 | #!/usr/bin/python
from __future__ import division
import subprocess
import itertools
import operator
import argparse
import os.path as osp
import sys
from oca_ | projects import OCA_PROJECTS, url
def get_contributions(projects, since, merges):
cmd = ['git', 'log', '--pretty=format:%ai %ae']
if since is not None:
cmd += ['--since', since]
if merges:
cmd += ['--merges']
if isinstance(projects, (str, unicode)):
projects = [projects]
for project in projects:
contributions = {}
for repo in OCA_PROJECTS[project]:
if not osp.isdir(repo):
| status = subprocess.call(['git', 'clone', '--quiet',
url(repo), repo])
if status != 0:
sys.stderr.write("%s not found on github\n" % repo)
continue
pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, cwd=repo)
out, error = pipe.communicate()
for line in out.splitlines():
try:
date, hour, tz, author = line.split()
except ValueError:
sys.stderr.write('error parsing line:\n%s\n' % line)
continue
contributions.setdefault(author, []).append(date)
yield project, contributions
def top_contributors(projects, since=None, merges=False, top=5):
for project, contributions in get_contributions(projects, since, merges):
contributors = sorted(contributions.iteritems(),
key=lambda x: len(x[1]),
reverse=True)
nb_contribs = sum(len(contribs) for author, contribs in contributors)
for author, contribs in contributors[:top]:
yield (project, author, len(contribs),
len(contribs) / nb_contribs, min(contribs), max(contribs))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--since',
metavar='YYYY-MM-DD',
default=None,
help='only consider contributions since YYYY-MM-DD')
parser.add_argument('--merges',
default=False,
action='store_true',
help='only consider merges')
parser.add_argument('--nb-contrib',
default=5,
type=int,
help='number of contributors to consider')
parser.add_argument('--csv',
default=False,
action='store_true',
help='produce CSV output')
project_names = sorted(OCA_PROJECTS)
args = parser.parse_args()
grouped = itertools.groupby(top_contributors(project_names,
since=args.since,
merges=args.merges,
top=args.nb_contrib),
operator.itemgetter(0))
if args.csv:
print 'project,author,nb contrib,nb contrib(%),earliest,latest'
template = '%(project)s,%(author)s,%(nb_contrib)d,' \
'%(percent_contrib).0f,%(earliest)s,%(latest)s'
else:
template = ' %(author)-35s:\t%(nb_contrib) 4d' \
' [%(percent_contrib) 3.0f%%] %(earliest)s %(latest)s'
for project, contribs in grouped:
if not args.csv:
print project
for (_p, author, nb_contrib, percent_contrib,
earliest, latest) in contribs:
info = {'project': project,
'author': author,
'percent_contrib': percent_contrib * 100,
'nb_contrib': nb_contrib,
'earliest': earliest,
'latest': latest}
print template % info
if not args.csv:
print
if __name__ == "__main__":
main()
|
mkacik/bcc | tools/btrfsslower.py | Python | apache-2.0 | 9,760 | 0.001025 | #!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# btrfsslower Trace slow btrfs operations.
# For Linux, uses BCC, eBPF.
#
# USAGE: btrfsslower [-h] [-j] [-p PID] [min_ms]
#
# This script traces common btrfs file operations: reads, writes, opens, and
# syncs. It measures the time spent in these operations, and prints details
# for each that exceeded a threshold.
#
# WARNING: This adds low-overhead instrumentation to these btrfs operations,
# including reads and writes from the file system cache. Such reads and writes
# can be very frequent (depending on the workload; eg, 1M/sec), at which
# point the overhead of this tool (even if it prints no "slower" events) can
# begin to become significant.
#
# By default, a minimum millisecond threshold of 10 is used.
#
# Copyright 2016 Netflix, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 15-Feb-2016 Brendan Gregg Created this.
# 16-Oct-2016 Dina Goldshtein -p to filter by process ID.
from __future__ import print_function
from bcc import BPF
import argparse
from time import strftime
import ctypes as ct
# symbols
kallsyms = "/proc/kallsyms"
# arguments
examples = """examples:
./btrfsslower # trace operations slower than 10 ms (default)
./btrfsslower 1 # trace operations slower than 1 ms
./btrfsslower -j 1 # ... 1 ms, parsable output (csv)
./btrfsslower 0 # trace all operations (warning: verbose)
./btrfsslower -p 185 # trace PID 185 only
"""
parser = argparse.ArgumentParser(
description="Trace common btrfs file operations slower than a threshold",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=examples)
parser.add_argument("-j", "--csv", action="store_true",
help="just print fields: comma-separated values")
parser.add_argument("-p", "--pid",
help="trace this PID only")
parser.add_argument("min_ms", nargs="?", default='10',
help="minimum I/O duration to trace, in ms (default 10)")
args = parser.parse_args()
min_ms = int(args.min_ms)
pid = args.pid
csv = args.csv
debug = 0
# define BPF program
bpf_text = """
#include <uapi/linux/ptrace.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/dcache.h>
// XXX: switch these to char's when supported
#define TRACE_READ 0
#define TRACE_WRITE 1
#define TRACE_OPEN 2
#define TRACE_FSYNC 3
struct val_t {
u64 ts;
u64 offset;
struct file *fp;
};
struct data_t {
// XXX: switch some to u32's when supported
u64 ts_us;
u64 type;
u64 size;
u64 offset;
u64 delta_us;
u64 pid;
char task[TASK_COMM_LEN];
char file[DNAME_INLINE_LEN];
};
BPF_HASH(entryinfo, u64, struct val_t);
BPF_PERF_OUTPUT(events);
//
// Store timestamp and size on entry
//
// The current btrfs (Linux 4.5) uses generic_file_read_iter() instead of it's
// own read function. So we need to trace that and then filter on btrfs, which
// I do by checking file->f_op.
int trace_read_entry(struct pt_regs *ctx, struct kiocb *iocb)
{
u64 id = bpf_get_current_pid_tgid();
u32 pid = id >> 32; // PID is higher part
if (FILTER_PID)
return 0;
// btrfs filter on file->f_op == btrfs_file_operations
struct file *fp = iocb->ki_filp;
if ((u64)fp->f_op != BTRFS_FILE_OPERATIONS)
return 0;
// store filep and timestamp by pid
struct val_t val = {};
val.ts = bpf_ktime_get_ns();
val.fp = fp;
val.offset = iocb->ki_pos;
if (val.fp)
entryinfo.update(&id, &val);
return 0;
}
// btrfs_file_write_iter():
int trace_write_entry(struct pt_regs *ctx, struct kiocb *iocb)
{
u64 id = bpf_get_current_pid_tgid();
u32 pid = id >> 32; // PID is higher part
if (FILTER_PID)
return 0;
// store filep and timestamp by id
struct val_t val = {};
val.ts = bpf_ktime_get_ns();
val.fp = iocb->ki_filp;
val.offset = iocb->ki_pos;
if (val.fp)
entryinfo.update(&id, &val);
return 0;
}
// The current btrfs (Linux 4.5) uses generic_file_open(), instead of it's own
// function. Same as with reads. Trace the generic path and filter:
int trace_open_entry(struct pt_regs *ctx, struct inode *inode,
struct file *file)
{
u64 id = bpf_get_current_pid_tgid();
u32 pid = id >> 32; // PID is higher part
if (FILTER_PID)
return 0;
// btrfs filter on file->f_op == btrfs_file_operations
if ((u64)file->f_op != BTRFS_FILE_OPERATIONS)
return 0;
// store filep and timestamp by id
struct val_t val = {};
val.ts = bpf_ktime_get_ns();
val.fp = file;
val.offset = 0;
if (val.fp)
entryinfo.update(&id, &val);
return 0;
}
// btrfs_sync_file():
int trace_fsync_entry(struct pt_regs *ctx, struct file *file)
{
u64 id = bpf_get_current_pid_tgid();
u32 pid = id >> 32; // PID is higher part
if (FILTER_PID)
return 0;
// store filep and timestamp by id
struct val_t val = {};
val.ts = bpf_ktime_get_ns();
val.fp = file;
val.offset = 0;
if (val.fp)
entryinfo.update(&id, &val);
return 0;
}
//
// Output
//
static int trace_return(struct pt_regs *ctx, int type)
{
struct val_t *valp;
u64 id = bpf_get_c | urrent_pid_tgid();
u32 pid = id >> 32; // PID is higher part
| valp = entryinfo.lookup(&id);
if (valp == 0) {
// missed tracing issue or filtered
return 0;
}
// calculate delta
u64 ts = bpf_ktime_get_ns();
u64 delta_us = (ts - valp->ts) / 1000;
entryinfo.delete(&id);
if (FILTER_US)
return 0;
// populate output struct
u32 size = PT_REGS_RC(ctx);
struct data_t data = {.type = type, .size = size, .delta_us = delta_us,
.pid = pid};
data.ts_us = ts / 1000;
data.offset = valp->offset;
bpf_get_current_comm(&data.task, sizeof(data.task));
// workaround (rewriter should handle file to d_name in one step):
struct dentry *de = NULL;
struct qstr qs = {};
bpf_probe_read(&de, sizeof(de), &valp->fp->f_path.dentry);
bpf_probe_read(&qs, sizeof(qs), (void *)&de->d_name);
if (qs.len == 0)
return 0;
bpf_probe_read(&data.file, sizeof(data.file), (void *)qs.name);
// output
events.perf_submit(ctx, &data, sizeof(data));
return 0;
}
int trace_read_return(struct pt_regs *ctx)
{
return trace_return(ctx, TRACE_READ);
}
int trace_write_return(struct pt_regs *ctx)
{
return trace_return(ctx, TRACE_WRITE);
}
int trace_open_return(struct pt_regs *ctx)
{
return trace_return(ctx, TRACE_OPEN);
}
int trace_fsync_return(struct pt_regs *ctx)
{
return trace_return(ctx, TRACE_FSYNC);
}
"""
# code replacements
with open(kallsyms) as syms:
ops = ''
for line in syms:
a = line.rstrip().split()
(addr, name) = (a[0], a[2])
name = name.split("\t")[0]
if name == "btrfs_file_operations":
ops = "0x" + addr
break
if ops == '':
print("ERROR: no btrfs_file_operations in /proc/kallsyms. Exiting.")
exit()
bpf_text = bpf_text.replace('BTRFS_FILE_OPERATIONS', ops)
if min_ms == 0:
bpf_text = bpf_text.replace('FILTER_US', '0')
else:
bpf_text = bpf_text.replace('FILTER_US',
'delta_us <= %s' % str(min_ms * 1000))
if args.pid:
bpf_text = bpf_text.replace('FILTER_PID', 'pid != %s' % pid)
else:
bpf_text = bpf_text.replace('FILTER_PID', '0')
if debug:
print(bpf_text)
# kernel->user event data: struct data_t
DNAME_INLINE_LEN = 32 # linux/dcache.h
TASK_COMM_LEN = 16 # linux/sched.h
class Data(ct.Structure):
_fields_ = [
("ts_us", ct.c_ulonglong),
("type", ct.c_ulonglong),
("size", ct.c_ulonglong),
("offset", ct.c_ulonglong),
("delta_us", ct.c_ulonglong),
("pid", ct.c_ulonglong),
("task", ct.c_char * TASK_COMM_LEN),
("file", ct.c_char * DNAME_INLINE_LEN)
]
# process event
def print_event(cpu, data, size):
event = ct.cast(data, ct.POINTER(Data)).contents
type = 'R'
if event.type == 1:
type = 'W'
elif event.type == 2:
type = 'O'
elif event.type = |
eustislab/horton | horton/io/test/test_molecule.py | Python | gpl-3.0 | 3,917 | 0.001532 | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2015 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON 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.
#
# HORTON is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>
#
#--
#pylint: skip-file
import numpy as np
from nose.tools import assert_raises
from horton import *
def test_typecheck():
m = IOData(coordinates=np.array([[1, 2, 3], [2, 3, 1]]))
assert issubclass(m.coordinates.dtype.type, float)
assert not hasattr(m, 'numbers')
m = IOData(numbers=np.array([2, 3]), coordinates=np.array([[1, 2, 3], [2, 3, 1]]))
m = IOData(numbers=np.array([2.0, 3.0]), pseudo_numbers=np.array([1, 1]), coordinates=np.array([[1, 2, 3], [2, 3, 1]]))
assert issubclass(m.numbers.dtype.type, int)
assert issubclass(m.pseudo_numbers.dtype.type, float)
assert hasattr(m, 'numbers')
del m.numbers
assert not hasattr(m, 'numbers')
m = IOData(cube_data=np.array([[[1, 2], [2, 3], [3, 2]]]), coordinates=np.array([[1, 2, 3]]))
with assert_raises(TypeError):
| IOData(coordinates=np.array([[1, 2], [2, 3]]))
with assert_raises(Type | Error):
IOData(numbers=np.array([[1, 2], [2, 3]]))
with assert_raises(TypeError):
IOData(numbers=np.array([2, 3]), pseudo_numbers=np.array([1]))
with assert_raises(TypeError):
IOData(numbers=np.array([2, 3]), coordinates=np.array([[1, 2, 3]]))
with assert_raises(TypeError):
IOData(cube_data=np.array([[1, 2], [2, 3], [3, 2]]), coordinates=np.array([[1, 2, 3]]))
with assert_raises(TypeError):
IOData(cube_data=np.array([1, 2]))
def test_copy():
fn_fchk = context.get_fn('test/water_sto3g_hf_g03.fchk')
fn_log = context.get_fn('test/water_sto3g_hf_g03.log')
mol1 = IOData.from_file(fn_fchk, fn_log)
mol2 = mol1.copy()
assert mol1 != mol2
vars1 = vars(mol1)
vars2 = vars(mol2)
assert len(vars1) == len(vars2)
for key1, value1 in vars1.iteritems():
assert value1 is vars2[key1]
def test_dm_water_sto3g_hf():
fn_fchk = context.get_fn('test/water_sto3g_hf_g03.fchk')
mol = IOData.from_file(fn_fchk)
dm = mol.get_dm_full()
assert abs(dm.get_element(0, 0) - 2.10503807) < 1e-7
assert abs(dm.get_element(0, 1) - -0.439115917) < 1e-7
assert abs(dm.get_element(1, 1) - 1.93312061) < 1e-7
def test_dm_lih_sto3g_hf():
fn_fchk = context.get_fn('test/li_h_3-21G_hf_g09.fchk')
mol = IOData.from_file(fn_fchk)
dm = mol.get_dm_full()
assert abs(dm.get_element(0, 0) - 1.96589709) < 1e-7
assert abs(dm.get_element(0, 1) - 0.122114249) < 1e-7
assert abs(dm.get_element(1, 1) - 0.0133112081) < 1e-7
assert abs(dm.get_element(10, 10) - 4.23924688E-01) < 1e-7
dm = mol.get_dm_spin()
assert abs(dm.get_element(0, 0) - 1.40210760E-03) < 1e-9
assert abs(dm.get_element(0, 1) - -2.65370873E-03) < 1e-9
assert abs(dm.get_element(1, 1) - 5.38701212E-03) < 1e-9
assert abs(dm.get_element(10, 10) - 4.23889148E-01) < 1e-7
def test_dm_ch3_rohf_g03():
fn_fchk = context.get_fn('test/ch3_rohf_sto3g_g03.fchk')
mol = IOData.from_file(fn_fchk)
olp = mol.obasis.compute_overlap(mol.lf)
dm = mol.get_dm_full()
assert abs(olp.contract_two('ab,ab', dm) - 9) < 1e-6
dm = mol.get_dm_spin()
assert abs(olp.contract_two('ab,ab', dm) - 1) < 1e-6
|
youtube/cobalt | starboard/android/x86/cobalt/configuration.py | Python | bsd-3-clause | 2,386 | 0.002096 | # Copyright 2017-2021 The Cobalt Authors. All Rights Reserved.
#
# 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 under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Starboard Android x86 Cobalt configuration."""
from starboard.android.shared.cobalt import configuration
from starboard.tools.testing import test_filter
class CobaltAndroidX86Configuration(configuration.CobaltAndroidConfiguration):
"""Starboard Android x86 Cobalt configuration."""
def GetTestFilters(self):
filters = super(CobaltAndroidX86Configuration, self).GetTestFilters()
for target, tests in self.__FILTERED_TESTS.iteritems():
filters.extend(test_ | filter.TestFilter(target, test) for test in tests)
return filters
# A map of failing or crashing tests per target
__FILTERED_TESTS = { # pylint: disable=invalid-name
| 'graphics_system_test': [
test_filter.FILTER_ALL
],
'layout_tests': [ # Old Android versions don't have matching fonts
'CSS3FontsLayoutTests/Layout.Test'
'/5_2_use_first_available_listed_font_family',
'CSS3FontsLayoutTests/Layout.Test'
'/5_2_use_specified_font_family_if_available',
'CSS3FontsLayoutTests/Layout.Test'
'/5_2_use_system_fallback_if_no_matching_family_is_found*',
'CSS3FontsLayoutTests/Layout.Test'
'/synthetic_bolding_should_not_occur_on_bold_font',
'CSS3FontsLayoutTests/Layout.Test'
'/synthetic_bolding_should_occur_on_non_bold_font',
],
'net_unittests': [ # Net tests are very unstable on Android L
test_filter.FILTER_ALL
],
'renderer_test': [
'LottieCoveragePixelTest*skottie_matte_blendmode_json',
'PixelTest.SimpleTextInRed40PtChineseFont',
'PixelTest.SimpleTextInRed40PtThaiFont',
'PixelTest.YUV422UYVYImageScaledUpSupport',
'PixelTest.YUV422UYVYImageScaledAndTranslated',
],
}
|
vikramvgarg/libmesh | doc/statistics/libmesh_citations.py | Python | lgpl-2.1 | 2,350 | 0.001702 | #!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
# Number of "papers using libmesh" by year.
#
# Note 1: this does not count citations "only," the authors must have actually
# used libmesh in part of their work. Therefore, these counts do not include
# things like Wolfgang citing us in his papers to show how Deal.II is
# superior...
#
# Note 2: I typically update this data after regenerating the web page,
# since bibtex2html renumbers the references starting from "1" each year.
#
# Note 3: These citations include anything that is not a dissertation/thesis.
# So, some are conference papers, some are journal articles, etc.
#
# Note 4: The libmesh paper came out in 2006, but there are some citations
# prior to that date, obviously. These counts include citations of the
# website libmesh.sf.net as well...
#
# Note 5: Preprints are listed as the "current year + 1" and are constantly
# being moved to their respective years after being published.
data = [
'\'04', 5,
'\'05', 2,
'\'06', 13,
'\'07', 8,
'\'08', 23,
'\'09', 29,
'\'10', 25,
'\'11', 32,
'\'12', 53,
'\'13', 78,
'\'14', 63,
'\'15', 79,
'\'16', 84,
'\'17', 31,
'T', 62
]
# Extract the x-axis labels from the data array
xlabels = d | ata[0::2]
# Extract the publication counts from the data array
n_papers = data[1::2]
# The number of data points
N = len(xlabels);
# Get a reference to the figure
fig = plt.figure()
# 111 is equivalent to Matlab's subplot(1,1,1) command
ax = fig.add_subplot(111)
# Create an x-axis for plotting
x = np.linspace(1, N, N)
# Width of the bars
width | = 0.8
# Make the bar chart. Plot years in blue, preprints and theses in green.
ax.bar(x[0:N-1], n_papers[0:N-1], width, color='b')
ax.bar(x[N-1:N], n_papers[N-1:N], width, color='g')
# Label the x-axis
plt.xlabel('T=PhD, MS, and BS Theses')
# Set up the xtick locations and labels. Note that you have to offset
# the position of the ticks by width/2, where width is the width of
# the bars.
ax.set_xticks(np.linspace(1,N,N) + width/2)
ax.set_xticklabels(xlabels)
# Create a title string
title_string = 'Papers by People Using LibMesh, (' + str(sum(n_papers)) + ' Total)'
fig.suptitle(title_string)
# Save as PDF
plt.savefig('libmesh_citations.pdf')
# Local Variables:
# python-indent: 2
# End:
|
Dubrzr/dsfaker | dsfaker/generators/__init__.py | Python | mit | 220 | 0 | # -*- coding | : utf-8 -*-
from .base import *
from .utils import *
from .distributions import *
from .autoincrement import *
from .date import *
from .series import *
from .timeseries import *
from .trigonometric impo | rt *
|
Keisuke69/libcloud | libcloud/compute/types.py | Python | apache-2.0 | 3,992 | 0.002004 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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 under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Base types used by other parts of libcloud
"""
from libcloud.common.types import LibcloudError, MalformedResponseError
from libcloud.common.types import InvalidCredsError, InvalidCredsException
__all__ = [
"Provider",
"NodeState",
"DeploymentError",
"DeploymentException",
# @@TR: should the unused imports below be exported?
"LibcloudError",
"MalformedResponseError",
"InvalidCredsError",
"InvalidCredsException"
]
class Provider(object):
"""
Defines for each of the supported providers
@cvar DUMMY: Example provider
@cvar EC2_US_EAST: Amazon AWS US N. Virgina
@cvar EC2_US_WEST: Amazon AWS US N. California
@cvar EC2_EU_WEST: Amazon AWS EU Ireland
@cvar RACKSPACE: Rackspace Cloud Servers
@cvar RACKSPACE_UK: Rackspace UK Cloud Servers
@cvar SLICEHOST: Slicehost.com
@cvar GOGRID: GoGrid
@cvar VPSNET: VPS.net
@cvar LINODE: Linode.com
@cvar VCLOUD: vmware vCloud
@cvar RIMUHOSTING: RimuHosting.com
@cvar ECP: Enomaly
@cvar IBM: IBM Developer Cloud
@cvar OPENNEBULA: OpenNebula.org
@cvar DREAMHOST: DreamHost Private Server
@cvar CLOUDSIGMA: CloudSigma
@cvar NIMBUS: Nimbus
@cvar BLUEBOX: Bluebox
@cvar OPSOURCE: Opsource Cloud
@cvar NINEFOLD: Ninefold
@cvar TERREMARK: Terremark
@cvar: EC2_US_WEST_OREGON: Amazon AWS US West 2 (Oregon)
@cvar CLOUDSTACK: CloudStack
"""
DUMMY = 0
EC2 = 1 # deprecated name
EC2_US_EAST = 1
EC2_EU = 2 # deprecated name
EC2_EU_WEST = 2
RACKSPACE = 3
SLICEHOST = 4
GOGRID = 5
VPSNET = 6
LINODE = 7
VCLOUD = 8
RIMUHOSTING = 9
EC2_US_WEST = 10
VOXEL = 11
SOFTLAYER = 12
EUCALYPTUS = 13
ECP = 14
IBM = 15
OPENNEBULA = 16
DREAMHOST = 17
ELASTICHOSTS = 18
ELAST | ICHOSTS_UK1 = 19
ELASTICHOSTS_UK2 = 20
ELASTICHOSTS_US1 = 21
EC2_AP_SOUTHEAST = 22
RACKSPACE_UK = 23
BRIGHTBOX = 24
CLOUDSIGMA = 25
EC2_AP_NORTHEAST = 26
NIMBUS = 27
BLUEBOX = 28
GANDI = 29
OPSOURCE = 30
OPENSTACK = 31
SKALICLOUD = 32
SERVERLOVE = 33
NINEFO | LD = 34
TERREMARK = 35
EC2_US_WEST_OREGON = 36
CLOUDSTACK = 37
class NodeState(object):
"""
Standard states for a node
@cvar RUNNING: Node is running
@cvar REBOOTING: Node is rebooting
@cvar TERMINATED: Node is terminated
@cvar PENDING: Node is pending
@cvar UNKNOWN: Node state is unknown
"""
RUNNING = 0
REBOOTING = 1
TERMINATED = 2
PENDING = 3
UNKNOWN = 4
class Architecture(object):
"""
Image and size architectures.
@cvar I386: i386 (32 bt)
@cvar X86_64: x86_64 (64 bit)
"""
I386 = 0
X86_X64 = 1
class DeploymentError(LibcloudError):
"""
Exception used when a Deployment Task failed.
@ivar node: L{Node} on which this exception happened, you might want to call L{Node.destroy}
"""
def __init__(self, node, original_exception=None):
self.node = node
self.value = original_exception
def __str__(self):
return repr(self.value)
"""Deprecated alias of L{DeploymentException}"""
DeploymentException = DeploymentError
|
plamut/ggrc-core | src/ggrc_risk_assessments/migrations/versions/20160804101106_4d4b04a5b9c6_fix_tracking_columns.py | Python | apache-2.0 | 771 | 0.005188 | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Fix tracking columns (SLOW!)
Create Date: 2016-08-04 10:11:06.471654
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
from ggrc.migrations.utils.fix_tracking_columns import (
upgrade_tables,
downgrade_tables,
)
# revision identifiers, used by Alembic.
revision = '4 | d4b04a5b9c6'
down_revision = '5b29b4becf8'
def upgrade():
"""Upgrade database schema and/or data, creating a new revision."""
upgrade_tables("ggrc_risk_assessments")
def downgrade():
"""Downgrade database schema and/or data back to the previous revisi | on."""
downgrade_tables("ggrc_risk_assessments")
|
tobiasgehring/qudi | hardware/spectrometer/spectrometer_dummy.py | Python | gpl-3.0 | 3,308 | 0.002721 | # -*- coding: utf-8 -*-
"""
This module contains fake spectrometer.
Qudi 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.
Qudi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Qudi. If not, see <http://www.gnu.org/licenses/>.
Copyright (c) the Qudi Developers. See the COPYRIGHT.txt file at the
top-level directory of this distribution and at <https://github.com/Ulm-IQO/qudi/>
"""
from core.base import Base
from interface.spectrometer_interface import SpectrometerInterface
from time import strftime, localtime
import time
import numpy as np
class SpectrometerInterfaceDummy(Base,SpectrometerInterface):
""" Dummy spectrometer module.
Shows a sil | icon vacancy spectrum at liquid helium temperatures.
"""
_connectors = {'fitlogic': 'FitLogic'}
def on_activate(self):
""" Activate module.
"""
self._fitLogic = self.get_connector('fitlogic')
self.exposure = 0.1
def on_deactivate(self):
""" Deactivate module.
"""
pass
def recordSpectrum(self):
""" Record a dummy | spectrum.
@return ndarray: 1024-value ndarray containing wavelength and intensity of simulated spectrum
"""
length = 1024
data = np.empty((2, length), dtype=np.double)
data[0] = np.arange(730, 750, 20/length)
data[1] = np.random.uniform(0, 2000, length)
lorentz, params = self._fitLogic.make_multiplelorentzian_model(no_of_functions=4)
sigma = 0.05
params.add('l0_amplitude', value=2000)
params.add('l0_center', value=736.46)
params.add('l0_sigma', value=1.5*sigma)
params.add('l1_amplitude', value=5800)
params.add('l1_center', value=736.545)
params.add('l1_sigma', value=sigma)
params.add('l2_amplitude', value=7500)
params.add('l2_center', value=736.923)
params.add('l2_sigma', value=sigma)
params.add('l3_amplitude', value=1000)
params.add('l3_center', value=736.99)
params.add('l3_sigma', value=1.5*sigma)
params.add('offset', value=50000.)
data[1] += lorentz.eval(x=data[0], params=params)
time.sleep(self.exposure)
return data
def saveSpectrum(self, path, postfix = ''):
""" Dummy save function.
@param str path: path of saved spectrum
@param str postfix: postfix of saved spectrum file
"""
timestr = strftime("%Y%m%d-%H%M-%S_", localtime())
print( 'Dummy would save to: ' + str(path) + timestr + str(postfix) + ".spe" )
def getExposure(self):
""" Get exposure time.
@return float: exposure time
"""
return self.exposure
def setExposure(self, exposureTime):
""" Set exposure time.
@param float exposureTime: exposure time
"""
self.exposure = exposureTime
|
HenryHu/pybbs | Login.py | Python | bsd-2-clause | 4,609 | 0.004339 | from UtmpHead import UtmpHead
import Config
from Log import Log
class Login:
def __eq__(self, other):
if (other == None):
return (self._loginid == 0)
return (self._loginid == other._loginid)
def __ne__(self, other):
return not self.__eq__(other)
def __init__(self, loginid):
self._loginid = loginid
def get_loginid(self):
return self._loginid
def get_userid(self):
from Utmp import Utmp
return Utmp.GetUserId(self._loginid - 1)
# UtmpHead.LIST
@staticmethod
def list_head():
listhead = UtmpHead.GetListHead()
return Login(listhead)
def list_next(self):
return Login(UtmpHead.GetListNext(self._loginid - 1))
def list_prev(self):
return Login(UtmpHead.GetListPrev(self._loginid - 1))
def set_listnext(self, listnext):
return UtmpHead.SetListNext(self._loginid - 1, listnext._loginid)
def set_listprev(self, listprev):
return UtmpHead.SetListPrev(self._loginid - 1, listprev._loginid)
def list_remove(self):
if (Login.list_head() == self):
UtmpHead.SetListHead(self.list_next()._loginid)
self.list_prev().set_listnext(self.list_next())
self.list_next().set_listprev(self.list_prev())
def list_add(self, userid = None):
if (userid == No | ne):
userid = self.get_userid()
if (userid == None or userid == ''):
raise Exception("illegal call to list_add")
node = Login.list_head()
if (node == None):
# empty list -> single element
self.set_listprev(self)
self.set_listnext(self)
UtmpHead.SetListHead(self._loginid)
return True
if (node.get_us | erid().lower() >= userid.lower()):
# insert at head
self.set_listprev(node.list_prev())
self.set_listnext(node)
node.set_listprev(self)
self.list_prev().set_listnext(self)
UtmpHead.SetListHead(self._loginid)
return True
count = 0
node = node.list_next()
while ((node.get_userid().lower() < userid.lower()) and (node != Login.list_head())):
node = node.list_next()
count += 1
if (count > Config.USHM_SIZE):
UtmpHead.SetListHead(0)
from Utmp import Utmp
Utmp.RebuildList()
return False
self.set_listprev(node.list_prev())
self.set_listnext(node)
node.set_listprev(self)
self.list_prev().set_listnext(self)
return True
# UtmpHead.HASH
@staticmethod
def hash_head(userid):
from Utmp import Utmp
hashkey = Utmp.Hash(userid)
hashhead = UtmpHead.GetHashHead(hashkey)
return hashkey, Login(hashhead)
def set_hashnext(self, hashnext):
UtmpHead.SetNext(self._loginid - 1, hashnext._loginid)
def hash_next(self):
nextid = UtmpHead.GetNext(self._loginid - 1)
return Login(nextid)
def hash_remove(self, userid = None): # userid: for debugging
if (userid == None):
from Utmp import Utmp
userid = Utmp.GetUserId(self._loginid - 1)
hashkey, pos = Login.hash_head(userid)
if (pos == None):
Log.error("Login.hash_remove: hash list empty!")
return False
if (pos == self):
UtmpHead.SetHashHead(hashkey, self.hash_next()._loginid)
else:
while (pos.hash_next() != None and pos.hash_next() != self):
pos = pos.hash_next()
if (pos.hash_next() == None):
Log.error("Login.hash_remove: can't find in hash list")
return False
else:
pos.set_hashnext(self.hash_next())
# add to free list
self.set_hashnext(Login.free_list())
Login.set_freelist(self)
return True
def hash_add(self, userid = None):
if (userid == None):
userid = self.get_userid()
if (userid == None or userid == ''):
raise Exception("illegal call to hash_add")
# remove from free list
Login.set_freelist(self.hash_next())
hashkey, node = Login.hash_head(userid)
self.set_hashnext(node)
UtmpHead.SetHashHead(hashkey, self._loginid)
@staticmethod
def free_list():
hashhead = UtmpHead.GetHashHead(0)
return Login(hashhead)
@staticmethod
def set_freelist(login):
UtmpHead.SetHashHead(0, login._loginid)
|
metacloud/python-cinderclient | cinderclient/v2/contrib/list_extensions.py | Python | apache-2.0 | 1,439 | 0 | # Copyright (c) 2013 OpenStack Foundation
# All Rights Reserved.
#
# 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 under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from cinderclient import base
from cinderclient import utils
class ListExtResource(base.Resource):
@property
def summary(self):
descr = self.description.strip()
if not descr:
return '??'
lines = descr.split("\n")
if len(lines) == 1:
return lines[0]
else:
return lines[0] + "..."
class ListExtManager(base.Manager):
resource_class = ListExtResource
def show_all(self):
return self._list("/extensions", 'extensions')
@utils.service_type('volumev2')
def do_list_extensions(client, _args):
"""List all the os-api extensions that are available."""
extensions = client.list_extensions.show_all()
fields = ["Name", "Summary", "Alias", "Updated"]
utils.print_list(extensions, fields)
|
bweck/cssbot | cssbot/process.py | Python | mit | 4,907 | 0.034848 |
#
# Copyright (C) 2011 by Brian Weck
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#
import pymongo, time
from . import log, config, reddit, queue
import utils
#
# match configured magic words by author or by mod
#
class Matcher:
matched_items = []
#
def __init__(self, subreddit, words=[], moderators=[]):
self.log = log.getLogger("cssbot.process.Matcher")
#
self.subreddit = subreddit
self.words = words
self.moderators = moderators
#
self.reddit = reddit.APIWrapper()
self.queue = queue.Queue()
#
# get a list of authorized authors which can say the magic words
#
def authorized_authors(self, authors=None):
_authors = list( self.moderators )
if isinstance(authors, list):
_authors.extend( authors )
else:
_authors.append( authors )
return _authors
#
#
#
def _magic_word_in(self, str):
#print "*** searching: %s" % str
if any(word in str.lower() for word in self.words):
return True
else:
return False
#
# check to see if a post selftext matches.
#
def _is_matched_t3(self, thing):
#print "%s..." % (thing["data"]["selftext"])[0:25]
return self._magic_word_in(thing["data"]["selftext"])
#
# check to see if a comment is matched
#
def _is_matched_t1(self, thing, authorized_authors):
#print "%s..." % (thing["data"]["body"])[0:25]
is_mw = self._magic_word_in(thing["data"]["body"])
is_aa = (thing["data"]["author"] in authorized_authors)
return is_mw and is_aa
#
#
#
def _walk_ds(self, thing, authorized_authors):
if not thing or "kind" not in thing:
return False;
# grab the kind, switch off that.
kind = thing["kind"]
self.log.debug("processing '%s'", kind)
# if it is a listing, enumerate the children.
if kind == "Listing":
if not thing["data"]["children"]:
self.log.debug("reached end of line")
return False
# data / children
for child in thing["data"]["children"]:
pop = thing["data"]["children"].pop()
return self._walk_ds(pop, authorized_authors) or self._walk_ds(thing, authorized_authors)
# if it is a post, check the post.
elif kind == "t3":
#
# search selftext
#print "%s..." % (d["data"]["selftext"])[0:25]
return self._is_matched_t3(thing)
# if it is a comment, check the comment + any replies it may have.
elif kind == "t1":
#
#print "%s..." % (d["data"]["body"])[0:25]
# check.
if self._is_matched_t1(thing, authorized_authors):
return True
# if the comment has replies, _walk_ds that next.
if "replies" in thing["data"]:
return self._walk_ds(thing["data"]["replies"], authorized_authors)
return False
# otherwise, say no.
self.log.debug("skipping %s", thing)
return False
#
#
#
def check_thread(self, thread):
# get the latest copy of the thread
# check for matched/unmatched
# update / requeue as needed.
#
self.log.debug("checking id=%s title=%s author=%s", thread["data"]["i | d"], thread["data"]["title | "].replace("\n", " "), thread["data"]["author"])
#
authorized_authors = self.authorized_authors( thread["data"]["author"] )
self.log.debug("authorized_authors = %s", authorized_authors)
# get the latest copy of the thread
resp = self.reddit.get_comments( thread["data"]["id"] )
if not resp or len(resp) != 2:
# most likely a json error, skip the element, leave queued up for next spin.
return False
# check for matched/unmatched
if self._walk_ds(resp[0], authorized_authors) or self._walk_ds(resp[1], authorized_authors):
self.log.info("id:%s MATCHED", thread["data"]["id"])
#
thread["data"]["matched"] = "Y"
thread["data"]["matched_ts"] = int(time.time())
self.matched_items.append(thread)
#
self.queue.save(thread)
self.queue.dequeue(thread)
return True
else:
# requeue
self.log.info("id:%s REQUEUED", thread["data"]["id"])
self.queue.requeue(thread)
return False
#
#
#
def check_items(self, threads):
for thread in threads:
self.check_thread(thread)
#
# check if the matched items have changed.
#
def is_dirty(self):
#
if self.matched_items:
return True
return False
#
#
#
def run(self):
threads = self.queue.next({"data.subreddit":self.subreddit}) #, "data.matched":"N"}) #matched items are dequeued, no need to filter.
self.check_items(threads)
|
neuroidss/nupic.research | tests/regions/location_region_test.py | Python | agpl-3.0 | 11,848 | 0.005149 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2018, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
import json
import math
import random
import unittest
from collections import defaultdict
import numpy as np
from nupic.engine import Network
from htmresearch.frameworks.location.path_integration_union_narrowing import (
computeRatModuleParametersFromReadoutResolution)
from htmresearch.support.register_regions import registerAllResearchRegions
NUM_OF_COLUMNS = 150
CELLS_PER_COLUMN = 16
NUM_OF_CELLS = NUM_OF_COLUMNS * CELLS_PER_COLUMN
FEATURE_ACTIVE_COLUMNS = {
"A": np.random.choice(NUM_OF_COLUMNS, NUM_OF_COLUMNS / 10).tolist(),
"B": np.random.choice(NUM_OF_COLUMNS, NUM_OF_COLUMNS / 10).tolist(),
}
FEATURE_CANDIDATE_SDR = {
"A": np.random.choice(NUM_OF_CELLS, NUM_OF_CELLS / 10).tolist(),
"B": np.random.choice(NUM_OF_CELLS, NUM_OF_CELLS / 10).tolist(),
}
OBJECTS = [
{"name": "Object 1",
"features": [{"top": 0, "left": 0, "width": 10, "height": 10, "name": "A"},
{"top": 0, "left": 10, "width": 10, "height": 10, "name": "B"},
{"top": 0, "left": 20, "width": 10, "height": 10, "name": "A"},
{"top": 10, "left": 0, "width": 10, "height": 10, "name": "A"},
{"top": 10, "left": 20, "width": 10, "height": 10, "name": "A"}]},
{"name": "Object 2",
"features": [{"top": 0, "left": 10, "width": 10, "height": 10, "name": "A"},
{"top": 10, "left": 0, "width": 10, "height": 10, "name": "B"},
{"top": 10, "left": 10, "width": 10, "height": 10, "name": "B"},
{"top": 10, "left": 20, "width": 10, "height": 10, "name": "B"},
{"top": 20, "left": 10, "width": 10, "height": 10, "name": "A"}]},
{"name": "Object 3",
"features": [{"top": 0, "left": 10, "width": 10, "height": 10, "name": "A"},
{"top": 10, "left": 0, "width": 10, "height": 10, "name": "A"},
{"top": 10, "left": 10, "width": 10, "height": 10, "name": "B"},
{"top": 10, "left": 20, "width": 10, "height": 10, "name": "A"},
{"top": 20, "left": 0, "width": 10, "height": 10, "name": "B"},
{"top": 20, "left": 10, "width": 10, "height": 10, "name": "A"},
{"top": 20, "left": 20, "width": 10, "height": 10, "name": "B"}]},
{"name": "Object 4",
"features": [{"top": 0, "left": 0, "width": 10, "height": 10, "name": "A"},
{"top": 0, "left": 10, "width": 10, "height": 10, "name": "A"},
{"top": 0, "left": 20, "width": 10, "height": 10, "name": "A"},
{"top": 10, "left": 0, "width": 10, "height": 10, "name": "A"},
{"top": 10, "left": 20, "width": 10, "height": 10, "name": "B"},
{"top": 20, "left": 0, "width": 10, "height": 10, "name": "B"},
{"top": 20, "left": 10, "width": 10, "height": 10, "name": "B"},
{"top": 20, "left": 20, "width": 10, "height": 10, "name": "B"}]},
]
def _createNetwork(inverseReadoutResolution, anchorInputSize, dualPhase=False):
"""
Create a simple network connecting sensor and motor inputs to the location
region. Use :meth:`RawSensor.addDataToQueue` to add sensor input and growth
candidates. Use :meth:`RawValues.addDataToQueue` to add motor input.
::
+----------+
[ sensor* ] --> | | --> [ activeCells ]
[ candidates* ] --> | location | --> [ learnableCells ]
[ motor ] --> | | --> [ sensoryAssociatedCells ]
+----------+
:param inverseReadoutResolution:
Specifies the diameter of the circle of pha | ses in the rhombus encoded by a
bump.
:type inverseReadoutResolution: int
:type anchorInputSize: int
:param anchorInputSize:
The number of input bits in the anchor input.
.. note::
(*) This function will only add the 'sensor' and 'candidates' regions when
'anchorInputSize' is greater than zero. This is useful if you would like to
compute locations ignoring sensor input
.. seealso::
- :py:func:`htmresearch.frameworks.l | ocation.path_integration_union_narrowing.createRatModuleFromReadoutResolution`
"""
net = Network()
# Create simple region to pass motor commands as displacement vectors (dx, dy)
net.addRegion("motor", "py.RawValues", json.dumps({
"outputWidth": 2
}))
if anchorInputSize > 0:
# Create simple region to pass growth candidates
net.addRegion("candidates", "py.RawSensor", json.dumps({
"outputWidth": anchorInputSize
}))
# Create simple region to pass sensor input
net.addRegion("sensor", "py.RawSensor", json.dumps({
"outputWidth": anchorInputSize
}))
# Initialize region with 5 modules varying scale by sqrt(2) and 4 different
# random orientations for each scale
scale = []
orientation = []
for i in xrange(5):
for _ in xrange(4):
angle = np.radians(random.gauss(7.5, 7.5))
orientation.append(random.choice([angle, -angle]))
scale.append(10.0 * (math.sqrt(2) ** i))
# Create location region
params = computeRatModuleParametersFromReadoutResolution(inverseReadoutResolution)
params.update({
"moduleCount": len(scale),
"scale": scale,
"orientation": orientation,
"anchorInputSize": anchorInputSize,
"activationThreshold": 8,
"initialPermanence": 1.0,
"connectedPermanence": 0.5,
"learningThreshold": 8,
"sampleSize": 10,
"permanenceIncrement": 0.1,
"permanenceDecrement": 0.0,
"dualPhase": dualPhase,
"bumpOverlapMethod": "probabilistic"
})
net.addRegion("location", "py.Guassian2DLocationRegion", json.dumps(params))
if anchorInputSize > 0:
# Link sensor
net.link("sensor", "location", "UniformLink", "",
srcOutput="dataOut", destInput="anchorInput")
net.link("sensor", "location", "UniformLink", "",
srcOutput="resetOut", destInput="resetIn")
net.link("candidates", "location", "UniformLink", "",
srcOutput="dataOut", destInput="anchorGrowthCandidates")
# Link motor input
net.link("motor", "location", "UniformLink", "",
srcOutput="dataOut", destInput="displacement")
# Initialize network objects
net.initialize()
return net
class Guassian2DLocationRegionTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
registerAllResearchRegions()
def testPathIntegration(self):
"""
Test the region path integration properties by moving the sensor around
verifying the location representations are different when the sensor moves
and matches the initial representation when returning to the start location
"""
# Create location only network
net = _createNetwork(anchorInputSize=0,
inverseReadoutResolution=8)
location = net.regions['location']
motor = net.regions['motor'].getSelf()
# Start from a random location
location.executeCommand(["activateRandomLocation"])
motor.addDataToQueue([0, 0])
net.run(1)
start = location.getOutputData("activeCells").nonzero()[0]
# Move up 10
motor.addDataToQueue([0, 10])
net.run(1)
# mid location should not match the start location
mid = location.getOutputData("activeCells").no |
valohai/valohai-cli | valohai_cli/utils/hashing.py | Python | mit | 377 | 0 | import hashlib
from typing import BinaryIO
def get_fp_sha256(fp: BinaryIO) -> str:
"""
Get the SHA-256 checksum of the data in the file `fp`.
:return: hex | string
"""
fp.seek(0)
hasher = hashlib.sha256()
| while True:
chunk = fp.read(524288)
if not chunk:
break
hasher.update(chunk)
return hasher.hexdigest()
|
hareevs/pgbarman | tests/test_output.py | Python | gpl-3.0 | 36,915 | 0 | # Copyright (C) 2013-2016 2ndQuadrant Italia Srl
#
# This file is part of Barman.
#
# Barman 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.
#
# Barman is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Barman. If not, see <http://www. | gnu.org/licenses/>.
import mock
import pytest
from barman import output
from barman.infofile import BackupInfo
from barman.utils import pretty_size
from testing_helpers import build_test_backup_info, mock_backup_ext_info
def teardown_module(module):
"""
Set the output API to a functional state, after testing it
"""
output.set_output_writer(output.DEFAULT_WRITER)
# noinspection PyMethodMayBeStatic
class TestOutputAPI(object):
@staticmethod
def _mock_writer():
# install a fresh mocked output writer
writer = mock.Mock()
output.set_output_writer(writer)
# reset the error status
output.error_occurred = False
return writer
# noinspection PyProtectedMember,PyUnresolvedReferences
@mock.patch.dict(output.AVAILABLE_WRITERS, mock=mock.Mock())
def test_set_output_writer_close(self):
old_writer = mock.Mock()
output.set_output_writer(old_writer)
assert output._writer == old_writer
args = ('1', 'two')
kwargs = dict(three=3, four=5)
output.set_output_writer('mock', *args, **kwargs)
old_writer.close.assert_called_once_with()
output.AVAILABLE_WRITERS['mock'].assert_called_once_with(*args,
**kwargs)
def test_debug(self, caplog):
# preparation
writer = self._mock_writer()
msg = 'test message'
output.debug(msg)
# logging test
for record in caplog.records:
assert record.levelname == 'DEBUG'
assert record.name == __name__
assert msg in caplog.text
# writer test
assert not writer.error_occurred.called
writer.debug.assert_called_once_with(msg)
# global status test
assert not output.error_occurred
def test_debug_with_args(self, caplog):
# preparation
writer = self._mock_writer()
msg = 'test format %02d %s'
args = (1, '2nd')
output.debug(msg, *args)
# logging test
for record in caplog.records:
assert record.levelname == 'DEBUG'
assert record.name == __name__
assert msg % args in caplog.text
# writer test
assert not writer.error_occurred.called
writer.debug.assert_called_once_with(msg, *args)
# global status test
assert not output.error_occurred
def test_debug_error(self, caplog):
# preparation
writer = self._mock_writer()
msg = 'test message'
output.debug(msg, is_error=True)
# logging test
for record in caplog.records:
assert record.levelname == 'DEBUG'
assert record.name == __name__
assert msg in caplog.text
# writer test
writer.error_occurred.assert_called_once_with()
writer.debug.assert_called_once_with(msg)
# global status test
assert output.error_occurred
def test_debug_with_kwargs(self):
# preparation
self._mock_writer()
with pytest.raises(TypeError):
output.debug('message', bad_arg=True)
def test_info(self, caplog):
# preparation
writer = self._mock_writer()
msg = 'test message'
output.info(msg)
# logging test
for record in caplog.records:
assert record.levelname == 'INFO'
assert record.name == __name__
assert msg in caplog.text
# writer test
assert not writer.error_occurred.called
writer.info.assert_called_once_with(msg)
# global status test
assert not output.error_occurred
def test_info_with_args(self, caplog):
# preparation
writer = self._mock_writer()
msg = 'test format %02d %s'
args = (1, '2nd')
output.info(msg, *args)
# logging test
for record in caplog.records:
assert record.levelname == 'INFO'
assert record.name == __name__
assert msg % args in caplog.text
# writer test
assert not writer.error_occurred.called
writer.info.assert_called_once_with(msg, *args)
# global status test
assert not output.error_occurred
def test_info_error(self, caplog):
# preparation
writer = self._mock_writer()
msg = 'test message'
output.info(msg, is_error=True)
# logging test
for record in caplog.records:
assert record.levelname == 'INFO'
assert record.name == __name__
assert msg in caplog.text
# writer test
writer.error_occurred.assert_called_once_with()
writer.info.assert_called_once_with(msg)
# global status test
assert output.error_occurred
def test_warning(self, caplog):
# preparation
writer = self._mock_writer()
msg = 'test message'
output.warning(msg)
# logging test
for record in caplog.records:
assert record.levelname == 'WARNING'
assert record.name == __name__
assert msg in caplog.text
# writer test
assert not writer.error_occurred.called
writer.warning.assert_called_once_with(msg)
# global status test
assert not output.error_occurred
def test_warning_with_args(self, caplog):
# preparation
writer = self._mock_writer()
msg = 'test format %02d %s'
args = (1, '2nd')
output.warning(msg, *args)
# logging test
for record in caplog.records:
assert record.levelname == 'WARNING'
assert record.name == __name__
assert msg % args in caplog.text
# writer test
assert not writer.error_occurred.called
writer.warning.assert_called_once_with(msg, *args)
# global status test
assert not output.error_occurred
def test_warning_error(self, caplog):
# preparation
writer = self._mock_writer()
msg = 'test message'
output.warning(msg, is_error=True)
# logging test
for record in caplog.records:
assert record.levelname == 'WARNING'
assert record.name == __name__
assert msg in caplog.text
# writer test
writer.error_occurred.assert_called_once_with()
writer.warning.assert_called_once_with(msg)
# global status test
assert output.error_occurred
def test_error(self, caplog):
# preparation
writer = self._mock_writer()
msg = 'test message'
output.error(msg)
# logging test
for record in caplog.records:
assert record.levelname == 'ERROR'
assert record.name == __name__
assert msg in caplog.text
# writer test
writer.error_occurred.assert_called_once_with()
writer.error.assert_called_once_with(msg)
# global status test
assert output.error_occurred
def test_error_with_args(self, caplog):
# preparation
writer = self._mock_writer()
msg = 'test format %02d %s'
args = (1, '2nd')
output.error(msg, *args)
# logging test
for record in caplog.records:
assert record.levelname == 'ERROR'
assert record.name == __name__
assert msg % args in caplog.text
# writer test
writer.error |
mozillazg/django-simple-projects | projects/admin_readonly_model/admin_readonly_model/wsgi.py | Python | mit | 417 | 0.002398 | """
WSGI config for admin_readonly_model project.
It exposes the WSGI callable as a module-level variable named ``app | lication``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "admin_readonly_model.settings")
applic | ation = get_wsgi_application()
|
DailyActie/Surrogate-Model | 01-codes/OpenMDAO-Framework-dev/openmdao.util/src/openmdao/util/typegroups.py | Python | mit | 558 | 0 | import array
import numbers
real_types = [numbers. | Real]
int_types = [numbers.Integral]
iterable_types = [set, list, tuple, array.array]
try:
import numpy
except ImportError:
pass
else:
real_types.extend([numpy.float32, numpy.float64])
int_types.extend([numpy.int32, numpy.int64])
iterable_types.append(numpy.ndarray)
# use these with isinstance to test for various types that include builtins
# and numpy types (if numpy is available)
real_types = tuple(real_types)
int_types = tuple(int_types)
iterable_types = | tuple(iterable_types)
|
fsquillace/golpy | mvc.py | Python | gpl-2.0 | 431 | 0.00232 | """
MVC Design Pattern
@author: Filippo Squillace
@date: 03/12/2011
"""
class | Observer:
def update(*args, **kwargs):
raise NotImplementedError
class Observable:
def __init__(self):
self.observers = []
pass
def register(self, observer):
self.observers.append(observer)
def notify(self, *args, **kwargs):
fo | r obs in self.observers:
obs.update(args, kwargs)
|
OpenSystemsLab/rethinkengine | tests/test_fields.py | Python | bsd-2-clause | 5,550 | 0 | from rethinkengine.fields import *
import unittest2 as unittest
class PrimaryKeyFieldTestCase(unittest.TestCase):
def test_default(self):
f = ObjectIdField()
self.assertEqual(f._default, None)
with self.assertRaises(TypeError):
ObjectIdField(default='')
def test_required(self):
with self.assertRaises(TypeError):
ObjectIdField(required=False)
def test_is_valid(self):
f = ObjectIdField()
self.assertTrue(f.is_valid('cdc14784-3327-492b-a1db-ad8a3b8abcef'))
def test_too_short(self):
f = ObjectIdField()
self.assertFalse(f.is_valid('cdc14784-3327-492b-a1db-ad8a3b8abce'))
def test_too_long(self):
f = ObjectIdField()
self.assertFalse(f.is_valid('cdc14784-3327- | 492b-a1db-ad8a3b8abcefa'))
def test_wrong_chars(self):
f = ObjectIdField()
self.assertFalse(f.is_valid('zzzzzzzz-3327-492b-a1db-ad8a3b8abcef'))
def test_wro | ng_type(self):
f = ObjectIdField()
self.assertFalse(f.is_valid(123))
class StringFieldTestCase(unittest.TestCase):
def test_default(self):
f = StringField()
self.assertEqual(f._default, None)
f = StringField(default='foo')
self.assertEqual(f._default, 'foo')
def test_none(self):
f = StringField(required=False)
self.assertTrue(f.is_valid(None))
f = StringField(required=True)
self.assertFalse(f.is_valid(None))
def test_is_valid(self):
f = StringField()
self.assertTrue(f.is_valid('foo'))
self.assertTrue(f.is_valid(''))
def test_wrong_type(self):
f = StringField()
self.assertFalse(f.is_valid(123))
class IntegerFieldTestCase(unittest.TestCase):
def test_default(self):
f = IntegerField()
self.assertEqual(f._default, None)
f = IntegerField(default=42)
self.assertEqual(f._default, 42)
def test_none(self):
f = IntegerField(required=False)
self.assertTrue(f.is_valid(None))
f = IntegerField(required=True)
self.assertFalse(f.is_valid(None))
def test_is_valid(self):
f = IntegerField()
self.assertTrue(f.is_valid(123))
def test_wrong_type(self):
f = IntegerField()
self.assertFalse(f.is_valid('foo'))
class FloatFieldTestCase(unittest.TestCase):
def test_default(self):
f = FloatField()
self.assertEqual(f._default, None)
f = FloatField(default=4.2)
self.assertEqual(f._default, 4.2)
def test_none(self):
f = FloatField(required=False)
self.assertTrue(f.is_valid(None))
f = FloatField(required=True)
self.assertFalse(f.is_valid(None))
def test_is_valid(self):
f = FloatField()
self.assertTrue(f.is_valid(123.456))
def test_wrong_type(self):
f = FloatField()
self.assertFalse(f.is_valid('foo'))
self.assertFalse(f.is_valid(0))
class ListFieldTestCase(unittest.TestCase):
def test_default(self):
f = ListField()
self.assertEqual(f._default, None)
f = ListField(default=[1, 2, 3])
self.assertEqual(f._default, [1, 2, 3])
def test_none(self):
f = ListField(required=False)
self.assertTrue(f.is_valid(None))
f = ListField(required=True)
self.assertFalse(f.is_valid(None))
def test_is_valid(self):
f = ListField()
self.assertTrue(f.is_valid([1, 2, 3]))
def test_is_valid_tuple(self):
f = ListField()
self.assertTrue(f.is_valid((1, 2, 3)))
def test_wrong_type(self):
f = ListField()
self.assertFalse(f.is_valid('foo'))
def test_element_type_string(self):
f = ListField(StringField)
self.assertEqual(f._element_type, StringField)
def test_element_type_invalid(self):
with self.assertRaises(TypeError):
f = ListField(str)
def test_element_type_is_valid(self):
f = ListField(StringField)
self.assertTrue(f.is_valid(['foo']))
def test_element_type_is_invalid(self):
f = ListField(StringField)
self.assertFalse(f.is_valid([42]))
class DictFieldTestCase(unittest.TestCase):
def test_default(self):
f = DictField()
self.assertEqual(f._default, None)
f = DictField(default={'foo': 'bar'})
self.assertEqual(f._default, {'foo': 'bar'})
def test_none(self):
f = DictField(required=False)
self.assertTrue(f.is_valid(None))
f = DictField(required=True)
self.assertFalse(f.is_valid(None))
def test_is_valid(self):
f = DictField()
self.assertTrue(f.is_valid({}))
self.assertTrue(f.is_valid({'foo': 1, 'bar': 2}))
def test_wrong_type(self):
f = DictField()
self.assertFalse(f.is_valid('foo'))
class BooleanFieldTestCase(unittest.TestCase):
def test_default(self):
f = BooleanField()
self.assertEqual(f._default, None)
f = BooleanField(default=True)
self.assertEqual(f._default, True)
def test_none(self):
f = BooleanField(required=False)
self.assertTrue(f.is_valid(None))
f = BooleanField(required=True)
self.assertFalse(f.is_valid(None))
def test_is_valid(self):
f = BooleanField()
self.assertTrue(f.is_valid(False))
self.assertTrue(f.is_valid(True))
def test_wrong_type(self):
f = BooleanField()
self.assertFalse(f.is_valid('foo'))
|
datosgobar/pydatajson | tests/test_federation.py | Python | mit | 38,400 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import os
import re
import json
try:
from mock import patch, MagicMock, ANY
except ImportError:
from unittest.mock import patch, MagicMock, ANY
from .context import pydatajson
from pydatajson.federation import *
from pydatajson.helpers import is_local_andino_resource
from ckanapi.errors import NotFound, CKANAPIError
SAMPLES_DIR = os.path.join("tests", "samples")
class FederationSuite(unittest.TestCase):
@classmethod
def get_sample(cls, sample_filename):
return os.path.join(SAMPLES_DIR, sample_filename)
@patch('pydatajson.federation.RemoteCKAN')
class PushDatasetTestCase(FederationSuite):
@classmethod
def setUpClass(cls):
cls.catalog = pydatajson.DataJson(cls.get_sample('full_data.json'))
cls.catalog_id = cls.catalog.get('identifier', re.sub(
r'[^a-z-_]+', '', cls.catalog['title']).lower())
cls.dataset = cls.catalog.datasets[0]
cls.dataset_id = cls.dataset['identifier']
cls.distribution = cls.catalog.distributions[0]
cls.distribution_id = cls.distribution['identifier']
cls.minimum_catalog = pydatajson.DataJson(
cls.get_sample('minimum_data.json'))
cls.minimum_catalog_id = cls.minimum_catalog.get('identifier', re.sub(
r'[^a-z-_]+', '', cls.minimum_catalog['title']).lower())
cls.minimum_dataset = cls.minimum_catalog.datasets[0]
# PATCH: minimum_data no tiene los identificadores obligatorios.
# Se los agrego aca, pero hay que refactorizar
# tests y samples desactualizados para cumplir con los perfiles nuevos
cls.minimum_dataset['identifier'] = cls.dataset['identifier']
cls.minimum_dataset['distribution'][0][
'identifier'] = cls.dataset['distribution'][0]['identifier']
def test_id_is_created_correctly(self, mock_portal):
def mock_call_action(action, data_dict=None):
if action == 'package_update':
raise NotFound
if action == 'package_create':
return data_dict
else:
return []
mock_portal.return_value.call_action = mock_call_action
res_id = push_dataset_to_ckan(
self.catalog,
'owner',
self.dataset_id,
'portal',
'key',
catalog_id=self.catalog_id)
self.assertEqual(self.catalog_id + '_' + self.dataset_id, res_id)
def test_id_is_updated_correctly(self, mock_portal):
def mock_call_action(action, data_dict=None):
if action == 'package_update':
return data_dict
if action == 'package_create':
self.fail('should not be called')
else:
return []
mock_portal.return_value.call_action = mock_call_action
res_id = push_dataset_to_ckan(
self.catalog,
'owner',
self.dataset_id,
'portal',
'key',
catalog_id=self.catalog_id)
self.assertEqual(self.catalog_id + '_' + self.dataset_id, res_id)
def test_dataset_id_is_preserved_if_catalog_id_is_not_passed(
self, mock_portal):
def mock_call_action(action, data_dict=None):
if action == 'package_update':
return data_dict
if action == 'package_create':
self.fail('should not be called')
else:
return []
mock_portal.return_value.call_action = mock_call_action
res_id = push_dataset_to_ckan(self.catalog, 'owner', self.dataset_id,
'portal', 'key')
self.assertEqual(self.dataset_id, res_id)
def test_tags_are_passed_correctly(self, mock_portal):
themes = self.dataset['theme']
keywords = [kw for kw in self.dataset['keyword']]
for theme in themes:
label = self.catalog.get_theme(identifier=theme)['label']
label = re.sub(r'[^\w .-]+', '', label, flags=re.UNICODE)
keywords.append(label)
def mock_call_action(action, data_dict=None):
if action == 'package_update':
try:
self.assertItemsEqual(
keywords, [
tag['name'] for tag in data_dict['tags']])
except AttributeError:
self.assertCountEqual(
keywords, [
tag['name'] for tag in data_dict['tags']])
return data_dict
if action == 'package_create':
self.fail('should not be called')
else:
return []
mock_portal.return_value.call_action = mock_call_action
res_id = push_dataset_to_ckan(
self.catalog,
'owner',
self.dataset_id,
'portal',
'key',
catalog_id=self.catalog_id)
self.assertEqual(self.catalog_id + '_' + self.dataset_id, res_id)
def test_licenses_are_interpreted_correctly(self, mock_portal):
def mock_call_action(action, data_dict=None):
if action == 'license_list':
return [{'title': 'somelicense',
'url': 'somelicense.com', 'id': '1'},
{'title': 'otherlicense',
'url': 'otherlicense.com', 'id': '2'}]
elif action == 'package_update':
self.assertEqual('notspecified', data_dict['license_id'])
return data_dict
else:
return []
mock_portal.return_value.call_action = mock_call_action
push_dataset_to_ckan(self.catalog, 'owner', self.dataset_id,
'portal', 'key', catalog_id=self.catalog_id)
def test_dataset_without_license_sets_notspecified(self, mock_portal):
def mock_call_action(action, data_dict=None):
if action == 'license_list':
return [{'title': 'somelicense',
'url': 'somelicense.com', 'id': '1'},
{'title': 'otherlicense',
'url': 'otherlicense.com', 'id': '2'}]
elif action == 'package_update':
self.assertEqual('notspecified', data_dict['license_id'])
return data_dict
else:
return []
mock_portal.return_value.call_action = mock_call_action
push_dataset_to_ckan(
self.minimum_catalog,
'owner',
self.minimum_dataset['identifier'],
'portal',
'key',
catalog_id=self.minimum_catalog_id)
def test_dataset_level_wrappers(self, mock_portal):
def mock_call_action(action, data_dict=None):
if action == 'package_update':
return data_dict
else:
return []
mock_portal.return_value.call_action = mock_call_action
restored_id = restore_dataset_to_ckan(
self.catalog, 'owner', self.dataset_id, 'portal', 'key')
harvested_id = harvest_dataset_to_ckan(
self.catalog,
'owner',
self.dataset_id,
'portal',
'key',
self.catalog_id)
self.assertEqual(self.dataset_id, restored_id)
self.assertE | qual(self.catalog_id + '_' + self.dataset_id, harvested_id)
def test_harvest_catalog_with_no_optional_parametres(self, mock_portal):
def mock_call_action(action, data_dict=None):
if action == 'package_update':
self.assertTrue(
data_dict['id'].startswith(
self.catalo | g_id + '_'))
self.assertTrue(
data_dict['name'].startswith(
self.catalog_id + '-'))
self.assertEqual(self.catalog_id, data_dict['owner_org'])
return data_dict
else:
return []
mock_portal.return_value.call_action = mock_call_action
|
csudmath/ma3ecg | source/conf.py | Python | gpl-2.0 | 7,658 | 0.004576 | # -*- coding: utf-8 -*-
#
# Développement d'une application web de création de quiz documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 29 18:28:40 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../modules'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'sphinx.ext.autodoc',
'sphinxcontrib.youtube',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Mathématiques 3ECG'
copyright = u'Cédric Donner'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = "fr"
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
theme = 'readthedocs'
try:
#raise Exception
if theme == 'readthedocs':
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
elif theme == 'bootstrap':
import sphinx_bootstrap_theme
from bootstrap_theme_options import *
html_theme = 'bootstrap'
html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()
except Exception as e:
import sys
print(str(e))
sys.exit(1)
html_theme = 'sphinxdoc'
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'tp'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
'papersize':"a4" | ,
'author': "Cédric Donner",
'date': "Version 2016-2017",
'title': "Mathématiques 3ECG",
'release' : "",
'releasename' : "",
'fontpkg': '\\usepackage{times}',
'babel': '\\usepackage[francais]{babel}',
'figure_align': 'H',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or ow | n class]).
latex_documents = [
('index', 'ma3ecg.tex', u'Mathématiques 3ECG',
u'Cédric Donner', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
latex_show_pagerefs = True
# If true, show URL addresses after external links.
latex_show_urls = True
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'oci-poo', u'Mathématiques 3ECG',
[u'Cédric Donner'], 1)
]
|
hyperNURb/ggrc-core | src/ggrc_risk_assessments/migrations/versions/20150716192442_5b29b4becf8_add_slug_to_risk_assessment.py | Python | apache-2.0 | 1,107 | 0.007227 |
"""add slug to risk_assessment
Revision ID: 5b29b4becf8
Revises: cd51533c624
Create Date: 2015-07-16 19:24:42.473531
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5b29b4becf8'
down_revision = 'cd51533c624'
_table_name = "risk_assessments"
_column_name = "slug"
_slug_prefix = "RISKASSESSMENT-"
_constraint_name = "unique_{}".format(_column_name)
def upgrade():
""" Add and fill a unique slug column """
op.add_column(
| _table_name,
sa.Column(_column_name, sa.String(length=250), nullable=True)
)
op.execute("UPDATE {table_name} SET slug = CONCAT('{prefix}', id)".format(
table_name=_table_name,
prefix=_slug_prefix
))
op.alter_column(
_table_name,
_column_name,
existing_type=sa.String(length=250),
nullable=False
)
op.create_unique_co | nstraint(_constraint_name, _table_name, [_column_name])
def downgrade():
""" Remove slug column from task group tasks """
op.drop_constraint(_constraint_name, _table_name, type_="unique")
op.drop_column(_table_name, _column_name)
|
morgenst/PyAnalysisTools | PyAnalysisTools/base/Modules.py | Python | mit | 2,275 | 0.00044 | from builtins import object
from PyAnalysisTools.base import _logger
from PyAnalysisTools.base.YAMLHandle import YAMLLoader
from PyAnalysisTools.AnalysisTools.FakeEstimator import MuonFakeEstimator # noqa: F401
from PyAnalysisTools.AnalysisTools.RegionBuilder import RegionBuilder # noqa: F401
from PyAnalysisTools.AnalysisTools.SubtractionHandle import SubtractionHandle # noqa: F401
from PyAnalysisTools.AnalysisTools.ProcessFilter import ProcessFilter # noqa: F401
from PyAnalysisTools.AnalysisTools.RegionSummaryModule import RegionSummaryModule # noqa: F401
from PyAnalysisTools.AnalysisTools.ExtrapolationModule import ExtrapolationModule, TopExtrapolationModule # noqa: F401
from PyAnalysisTools.AnalysisTools.ExtrapolationModule import QCDExtrapolationModule # noqa: F401
class Module(object):
pass
def load_modules(config_files, callee):
"""
Load all modules defined in configuration files
:param config_files: list of configuration file names
:type config_files: list
:param callee: instance | of calling object
:type callee: object
:return: list of initialised modules
:rtype: list
"""
modules = []
if not isinstance(config_files, list):
config_files = [config_files]
try:
for cfg_file in config_files:
if cfg_file is None:
continue
config = YAMLLoader.read_yaml(cfg_file)
modules | += build_module_instances(config, callee)
except TypeError:
_logger.warning("Config files not iterable")
return modules
def build_module_instances(config, callee):
"""
Construct a specific module instance from a config. If the callee is needed for the initialisation needs to be
passed and reflected in config
:param config: module configuration
:type config: dict
:param callee: optional calling class
:type callee: object
:return:
:rtype:
"""
modules = []
for module, mod_config in list(config.items()):
mod_name = globals()[module]
for key, val in list(mod_config.items()):
if isinstance(val, str) and 'callee' in val:
mod_config[key] = eval(val)
instance = mod_name(**mod_config)
modules.append(instance)
return modules
|
eProsima/Fast-DDS | test/performance/video/video_tests.py | Python | apache-2.0 | 5,555 | 0.00162 | # Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
#
# 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 under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import subprocess
import os
def assert_positive_int(str_number, str_name):
"""
Check whether a string represents a positive integer.
:param str_number: The string representation.
:param str_name: The name to print on error.
:return: The string representation if it was a positive interger.
Exits with error code 12 otherwise.
"""
# Check that samples is positive
if str.isdigit(str_number) and int(str_number) > 0:
return str(str_number)
else:
print(
'"{}" must be a positive integer, NOT {}'.format(
str_name,
str_number
)
)
exit(1) # Exit with error
if __name__ == '__main__':
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
'-x',
'--xml_file',
help='A Fast-RTPS XML configuration file',
required=False
)
parser.add_argument(
'-n',
'--number_of_samples',
help='The number of measurements to take for each payload',
required=False,
default='10000'
)
parser.add_argument(
'-H',
'--height',
help='Height of the video',
required=False,
default='720'
)
parser.add_argument(
'-w',
'--width',
help='Width of the video',
required=False,
default='1024'
)
parser.add_argument(
' | -r',
'--frame_rate',
help='Frame rate of the video [Hz]',
required=False,
default='30'
)
p | arser.add_argument(
'-t',
'--test_duration',
help='The duration of the test [s]',
required=False,
default=2
)
parser.add_argument(
'-s',
'--security',
action='store_true',
help='Enables security (Defaults: disable)',
required=False
)
# Parse arguments
args = parser.parse_args()
xml_file = args.xml_file
security = args.security
# XML options
xml_options = []
if xml_file:
if not os.path.isfile(xml_file):
print('XML file "{}" is NOT a file'.format(xml_file))
exit(1) # Exit with error
else:
xml_options = ['--xml', xml_file]
samples = assert_positive_int(str(args.number_of_samples), "number_of_samples")
height = assert_positive_int(str(args.height), "height")
width = assert_positive_int(str(args.width), "width")
frame_rate = assert_positive_int(str(args.frame_rate), "frame_rate")
test_duration = assert_positive_int(str(args.test_duration), "test_duration")
# Environment variables
executable = os.environ.get('VIDEO_TEST_BIN')
certs_path = os.environ.get('CERTS_PATH')
# Check that executable exists
if executable:
if not os.path.isfile(executable):
print('VIDEO_TEST_BIN does NOT specify a file')
exit(1) # Exit with error
else:
print('VIDEO_TEST_BIN is NOT set')
exit(1) # Exit with error
# Security
security_options = []
if security is True:
if certs_path:
if os.path.isdir(certs_path):
security_options = ['--security=true', '--certs=' + certs_path]
else:
print('CERTS_PATH does NOT specify a directory')
exit(1) # Exit with error
else:
print('Cannot find CERTS_PATH environment variable')
exit(1) # Exit with error
# Domain
domain = str(os.getpid() % 230)
domain_options = ['--domain', domain]
# Base of test command for publisher agent
pub_command = [
executable,
'publisher',
'--samples',
samples,
'--testtime',
test_duration,
'--width',
width,
'--height',
height,
'--rate',
frame_rate
]
# Base of test command for subscriber agent
sub_command = [
executable,
'subscriber',
]
# Manage security
if security is True:
pub_command += security_options
sub_command += security_options
pub_command += domain_options
pub_command += xml_options
sub_command += domain_options
sub_command += xml_options
print('Publisher command: {}'.format(
' '.join(element for element in pub_command)),
flush=True
)
print('Subscriber command: {}'.format(
' '.join(element for element in sub_command)),
flush=True
)
# Spawn processes
publisher = subprocess.Popen(pub_command)
subscriber = subprocess.Popen(sub_command)
# Wait until finish
subscriber.communicate()
publisher.communicate()
if subscriber.returncode != 0:
exit(subscriber.returncode)
elif publisher.returncode != 0:
exit(publisher.returncode)
|
immenz/pyload | module/plugins/hooks/RestartSlow.py | Python | gpl-3.0 | 2,111 | 0.018001 | # -*- coding: utf-8 -*-
import pycurl
from module.plugins.Hook import Hook
class RestartSlow(Hook):
__name__ = "RestartSlow"
__type__ = "hook"
__version__ = "0.04"
__config__ = [("free_limit" , "int" , "Transfer speed threshold in kilobytes" , 100 ),
("free_time" , "int" , "Sample interval in minutes" , 5 ),
("premium_limit", "int" , "Transfer speed threshold for premium download in kilobytes", 300 ),
("premium_time" , "int" , "Sample interval for premium download in minutes" , 2 ),
("safe_mode" , "bool", "Don't restart if download is not resumable" , True)]
__description__ = """Restart slow downloads"""
__license__ = "GPLv3"
__authors__ = [("Walter Purcaro", "vuolter@gmail.com")]
event_list = ["downloadStarts"]
def setup(self):
self.info = {'chunk': {}}
def initPeriodical(self):
pass
def p | eriodical(self):
if not self.pyfile.plugin.req.dl:
return
if self.getConfig("safe_mode") and not self.pyfile.plugin.resumeDownload:
time = 30
limit = 5
else:
type = "premium" if self.pyfile.plugin.premium else "free"
time = max(30, self.getConfig("%s_time" % type) * 60)
limit = max(5, self.getConfig("%s_limit" % type) * 1024)
chunks = [chunk | for chunk in self.pyfile.plugin.req.dl.chunks \
if chunk.id not in self.info['chunk'] or self.info['chunk'][chunk.id] is not (time, limit)]
for chunk in chunks:
chunk.c.setopt(pycurl.LOW_SPEED_TIME , time)
chunk.c.setopt(pycurl.LOW_SPEED_LIMIT, limit)
self.info['chunk'][chunk.id] = (time, limit)
def downloadStarts(self, pyfile, url, filename):
if self.cb or (self.getConfig("safe_mode") and not pyfile.plugin.resumeDownload):
return
self.pyfile = pyfile
super(RestartSlow, self).initPeriodical()
|
flowersteam/naminggamesal | naminggamesal/tools/efficient_minimal_ng.py | Python | agpl-3.0 | 4,257 | 0.03876 |
import numpy | as np
import random
import time
from collections import defaultdict
from memory_profiler import memory_usage
def stop_condition(T,pop,Tmax,monitor_T):
if T == monitor_T:
print(memory_usage())
return (T >= Tmax) or (T>0 and len(pop) == 1)
def new_stop_condition(T,pop,Tmax,monitor_T):
if T == monitor_T:
#print(memory_usage())
pass
return (T >= Tmax) or (T>0 and len(pop[' | d1']) == 1)
def pop_add(ag,pop):
s = pop['d1'][ag]+1
pop['d1'][ag] = s
if s > 1:
pop['d2'][s-1].remove(ag)
pop['d2bis'][s-1]-=1
if pop['d2bis'][s-1] == 0:
del pop['d2bis'][s-1]
del pop['d2'][s-1]
pop['d2bis'][s]+=1
pop['d2'][s].add(ag)
pop['N'] += 1
def pop_rm(ag,pop):
s = pop['d1'][ag]-1
if s > 0:
pop['d1'][ag] = s
pop['d2bis'][s] += 1
pop['d2'][s].add(ag)
else:
del pop['d1'][ag]
pop['d2'][s+1].remove(ag)
pop['d2bis'][s+1]-=1
if pop['d2bis'][s+1] == 0:
del pop['d2bis'][s+1]
del pop['d2'][s+1]
pop['N'] -= 1
def pop_init(N):
pop = {'d1':defaultdict(int),'d2':defaultdict(set),'d2bis':defaultdict(int)}
pop['d1'][()] = N
pop['d2'][N].add(())
pop['d2bis'][N] = 1
pop['N'] = float(N)
return pop
def pick_size(pop):
keys = list(pop['d2bis'].keys())
# print(keys)
if len(keys) == 1:
return keys[0]
# keys = np.asarray(keys)
values = [k*pop['d2bis'][k]/pop['N'] for k in keys]
try:
s = np.random.choice(keys,p=values)
except:
print(values)
print(pop['d2bis'])
print(sum(values))
raise
# print(values)
return s
def new_pick_agent(pop):
s = pick_size(pop=pop)
# print(s)
# print(pop['d2'],'blah')
ag = random.sample(pop['d2'][s],1)[0]
pop_rm(ag=ag,pop=pop)
return ag
def new_run(Tmax,N):
if N in [0,1,2]:
return 0.
try:
pop = pop_init(N=N)
max_word = -1
monitor_T = int(1./np.sqrt(2.)*N**(1.5))
T = 0
while not new_stop_condition(T,pop,Tmax,N):
sp = new_pick_agent(pop)
hr = new_pick_agent(pop)
if sp == ():
max_word += 1
sp = (max_word,)
# hr = tuple(sorted((*hr,max_word)))
hr = tuple(sorted(hr+(max_word,)))
else:
w = np.random.choice(sp)
if w in hr:
sp = (w,)
hr = (w,)
else:
# hr = tuple(sorted((*hr,w)))
hr = tuple(sorted(hr+(w,)))
pop_add(pop=pop,ag=sp)
pop_add(pop=pop,ag=hr)
T += 1
# print('end',N,memory_usage(),max_word,pop)
return T
except:
print('T',T)
print('mem',memory_usage())
print('len d1',len(pop['d1']))
print('len d2',len(pop['d2']))
raise
#################
# def pick_agent(pop):
# p = np.asarray(list(pop.values()),dtype=float)
# if len(p) == 1.:
# return list(pop.keys())[0]
# p /= p.sum()
# try:
# ans = np.random.choice(list(pop.keys()),p=p)
# except KeyboardInterrupt:
# raise
# except:
# print(len(pop))
# print(list(pop.keys()))
# print(list(pop.values()))
# return list(pop.keys())[0]
# pop[ans] -= 1
# if pop[ans] == 0:
# del pop[ans]
# return ans
# def run(Tmax,N):
# try:
# pop = defaultdict(int)
# pop[()] = N
# max_word = -1
# monitor_T = int(1./np.sqrt(2.)*N**(1.5))
# T = 0
# while not stop_condition(T,pop,Tmax,N):
# sp = pick_agent(pop)
# hr = pick_agent(pop)
# if sp == ():
# max_word += 1
# sp = (max_word,)
# # hr = tuple(sorted((*hr,max_word)))
# hr = tuple(sorted(hr+(max_word,)))
# if pop[()] == 0:
# del pop[()]
# pop[sp] += 1
# pop[hr] += 1
# else:
# w = np.random.choice(sp)
# if w in hr:
# pop[(w,)] += 2
# else:
# hr = tuple(sorted(hr+(w,)))
# # hr = tuple(sorted((*hr,w)))
# pop[sp] += 1
# pop[hr] += 1
# T += 1
# print('end',N,memory_usage(),max_word)
# return T
# except:
# print('T',T)
# print('mem',memory_usage())
# print('len',len(pop))
# raise
if __name__ == '__main__':
start = time.time()
# print(memory_usage())
# N=10000
# print('N',N)
# try:
# t = new_run(Tmax=100000, N=N)
# print(t)
# finally:
# print(time.time()-start,'seconds')
ans = defaultdict(list)
for N in range(100,101):
print(N)
for i in range(1000):
print(N,i)
t = new_run(Tmax=100000,N=N)
ans[N].append(t)
ans[N] = np.mean(ans[N])
print(ans)
print(time.time()-start,'seconds')
with open('tconv_dict.txt','w') as f:
f.write(str(ans) + str(time.time()-start) + ' seconds')
|
niekas/Hack4LT | src/hack4lt/templatetags/utils.py | Python | bsd-3-clause | 123 | 0 | from django import template
register = template.Library()
@register.filter
def value(value, key):
return value | [key]
| |
maxdl/Vesicle.py | vesicle/version.py | Python | mit | 444 | 0 | import os.path
import sys
version = "1.1.3"
date = ("June", "11", "2018")
title = "Vesicle"
author = "Max Larsson"
email = "max.larsson@liu.se"
homepage = "www.liu.se/medfak/forskning/larsson-max/software"
if hasattr(sys, 'frozen'):
if '_MEIP | ASS2' in os.environ:
path = os.envi | ron['_MEIPASS2']
else:
path = sys.argv[0]
else:
path = __file__
app_path = os.path.dirname(path)
icon = os.path.join(app_path, "ves.ico")
|
lhilt/scipy | scipy/stats/tests/test_morestats.py | Python | bsd-3-clause | 70,469 | 0.000298 | # Author: Travis Oliphant, 2002
#
# Further enhancements and tests added by numerous SciPy developers.
#
from __future__ import division, print_function | , absolute_import
import warnings
import numpy as np
from numpy.random import RandomState
from numpy.testing import (assert_array | _equal,
assert_almost_equal, assert_array_less, assert_array_almost_equal,
assert_, assert_allclose, assert_equal, assert_warns)
import pytest
from pytest import raises as assert_raises
from scipy._lib._numpy_compat import suppress_warnings
from scipy import stats
from .common_tests import check_named_results
# Matplotlib is not a scipy dependency but is optionally used in probplot, so
# check if it's available
try:
import matplotlib
matplotlib.rcParams['backend'] = 'Agg'
import matplotlib.pyplot as plt
have_matplotlib = True
except Exception:
have_matplotlib = False
# test data gear.dat from NIST for Levene and Bartlett test
# https://www.itl.nist.gov/div898/handbook/eda/section3/eda3581.htm
g1 = [1.006, 0.996, 0.998, 1.000, 0.992, 0.993, 1.002, 0.999, 0.994, 1.000]
g2 = [0.998, 1.006, 1.000, 1.002, 0.997, 0.998, 0.996, 1.000, 1.006, 0.988]
g3 = [0.991, 0.987, 0.997, 0.999, 0.995, 0.994, 1.000, 0.999, 0.996, 0.996]
g4 = [1.005, 1.002, 0.994, 1.000, 0.995, 0.994, 0.998, 0.996, 1.002, 0.996]
g5 = [0.998, 0.998, 0.982, 0.990, 1.002, 0.984, 0.996, 0.993, 0.980, 0.996]
g6 = [1.009, 1.013, 1.009, 0.997, 0.988, 1.002, 0.995, 0.998, 0.981, 0.996]
g7 = [0.990, 1.004, 0.996, 1.001, 0.998, 1.000, 1.018, 1.010, 0.996, 1.002]
g8 = [0.998, 1.000, 1.006, 1.000, 1.002, 0.996, 0.998, 0.996, 1.002, 1.006]
g9 = [1.002, 0.998, 0.996, 0.995, 0.996, 1.004, 1.004, 0.998, 0.999, 0.991]
g10 = [0.991, 0.995, 0.984, 0.994, 0.997, 0.997, 0.991, 0.998, 1.004, 0.997]
class TestBayes_mvs(object):
def test_basic(self):
# Expected values in this test simply taken from the function. For
# some checks regarding correctness of implementation, see review in
# gh-674
data = [6, 9, 12, 7, 8, 8, 13]
mean, var, std = stats.bayes_mvs(data)
assert_almost_equal(mean.statistic, 9.0)
assert_allclose(mean.minmax, (7.1036502226125329, 10.896349777387467),
rtol=1e-14)
assert_almost_equal(var.statistic, 10.0)
assert_allclose(var.minmax, (3.1767242068607087, 24.45910381334018),
rtol=1e-09)
assert_almost_equal(std.statistic, 2.9724954732045084, decimal=14)
assert_allclose(std.minmax, (1.7823367265645145, 4.9456146050146312),
rtol=1e-14)
def test_empty_input(self):
assert_raises(ValueError, stats.bayes_mvs, [])
def test_result_attributes(self):
x = np.arange(15)
attributes = ('statistic', 'minmax')
res = stats.bayes_mvs(x)
for i in res:
check_named_results(i, attributes)
class TestMvsdist(object):
def test_basic(self):
data = [6, 9, 12, 7, 8, 8, 13]
mean, var, std = stats.mvsdist(data)
assert_almost_equal(mean.mean(), 9.0)
assert_allclose(mean.interval(0.9), (7.1036502226125329,
10.896349777387467), rtol=1e-14)
assert_almost_equal(var.mean(), 10.0)
assert_allclose(var.interval(0.9), (3.1767242068607087,
24.45910381334018), rtol=1e-09)
assert_almost_equal(std.mean(), 2.9724954732045084, decimal=14)
assert_allclose(std.interval(0.9), (1.7823367265645145,
4.9456146050146312), rtol=1e-14)
def test_empty_input(self):
assert_raises(ValueError, stats.mvsdist, [])
def test_bad_arg(self):
# Raise ValueError if fewer than two data points are given.
data = [1]
assert_raises(ValueError, stats.mvsdist, data)
def test_warns(self):
# regression test for gh-5270
# make sure there are no spurious divide-by-zero warnings
with warnings.catch_warnings():
warnings.simplefilter('error', RuntimeWarning)
[x.mean() for x in stats.mvsdist([1, 2, 3])]
[x.mean() for x in stats.mvsdist([1, 2, 3, 4, 5])]
class TestShapiro(object):
def test_basic(self):
x1 = [0.11, 7.87, 4.61, 10.14, 7.95, 3.14, 0.46,
4.43, 0.21, 4.75, 0.71, 1.52, 3.24,
0.93, 0.42, 4.97, 9.53, 4.55, 0.47, 6.66]
w, pw = stats.shapiro(x1)
assert_almost_equal(w, 0.90047299861907959, 6)
assert_almost_equal(pw, 0.042089745402336121, 6)
x2 = [1.36, 1.14, 2.92, 2.55, 1.46, 1.06, 5.27, -1.11,
3.48, 1.10, 0.88, -0.51, 1.46, 0.52, 6.20, 1.69,
0.08, 3.67, 2.81, 3.49]
w, pw = stats.shapiro(x2)
assert_almost_equal(w, 0.9590270, 6)
assert_almost_equal(pw, 0.52460, 3)
# Verified against R
np.random.seed(12345678)
x3 = stats.norm.rvs(loc=5, scale=3, size=100)
w, pw = stats.shapiro(x3)
assert_almost_equal(w, 0.9772805571556091, decimal=6)
assert_almost_equal(pw, 0.08144091814756393, decimal=3)
# Extracted from original paper
x4 = [0.139, 0.157, 0.175, 0.256, 0.344, 0.413, 0.503, 0.577, 0.614,
0.655, 0.954, 1.392, 1.557, 1.648, 1.690, 1.994, 2.174, 2.206,
3.245, 3.510, 3.571, 4.354, 4.980, 6.084, 8.351]
W_expected = 0.83467
p_expected = 0.000914
w, pw = stats.shapiro(x4)
assert_almost_equal(w, W_expected, decimal=4)
assert_almost_equal(pw, p_expected, decimal=5)
def test_2d(self):
x1 = [[0.11, 7.87, 4.61, 10.14, 7.95, 3.14, 0.46,
4.43, 0.21, 4.75], [0.71, 1.52, 3.24,
0.93, 0.42, 4.97, 9.53, 4.55, 0.47, 6.66]]
w, pw = stats.shapiro(x1)
assert_almost_equal(w, 0.90047299861907959, 6)
assert_almost_equal(pw, 0.042089745402336121, 6)
x2 = [[1.36, 1.14, 2.92, 2.55, 1.46, 1.06, 5.27, -1.11,
3.48, 1.10], [0.88, -0.51, 1.46, 0.52, 6.20, 1.69,
0.08, 3.67, 2.81, 3.49]]
w, pw = stats.shapiro(x2)
assert_almost_equal(w, 0.9590270, 6)
assert_almost_equal(pw, 0.52460, 3)
def test_empty_input(self):
assert_raises(ValueError, stats.shapiro, [])
assert_raises(ValueError, stats.shapiro, [[], [], []])
def test_not_enough_values(self):
assert_raises(ValueError, stats.shapiro, [1, 2])
assert_raises(ValueError, stats.shapiro, [[], [2]])
def test_bad_arg(self):
# Length of x is less than 3.
x = [1]
assert_raises(ValueError, stats.shapiro, x)
def test_nan_input(self):
x = np.arange(10.)
x[9] = np.nan
w, pw = stats.shapiro(x)
assert_equal(w, np.nan)
assert_almost_equal(pw, 1.0)
class TestAnderson(object):
def test_normal(self):
rs = RandomState(1234567890)
x1 = rs.standard_exponential(size=50)
x2 = rs.standard_normal(size=50)
A, crit, sig = stats.anderson(x1)
assert_array_less(crit[:-1], A)
A, crit, sig = stats.anderson(x2)
assert_array_less(A, crit[-2:])
v = np.ones(10)
v[0] = 0
A, crit, sig = stats.anderson(v)
# The expected statistic 3.208057 was computed independently of scipy.
# For example, in R:
# > library(nortest)
# > v <- rep(1, 10)
# > v[1] <- 0
# > result <- ad.test(v)
# > result$statistic
# A
# 3.208057
assert_allclose(A, 3.208057)
def test_expon(self):
rs = RandomState(1234567890)
x1 = rs.standard_exponential(size=50)
x2 = rs.standard_normal(size=50)
A, crit, sig = stats.anderson(x1, 'expon')
assert_array_less(A, crit[-2:])
olderr = np.seterr(all='ignore')
try:
A, crit, sig = stats.anderson(x2, 'expon')
finally:
np.seterr(**olderr)
assert_(A > crit[-1])
def test_gumbel(self):
# Regression test for gh-6306. Before that issue was fixed,
|
sayoun/workalendar | workalendar/tests/test_asia.py | Python | mit | 17,173 | 0 | from datetime import date
from workalendar.tests import GenericCalendarTest
from workalendar.asia import HongKong, Japan, Qatar, Singapore
from workalendar.asia import SouthKorea, Taiwan, Malaysia
class HongKongTest(GenericCalendarTest):
cal_class = HongKong
def test_year_2010(self):
""" Interesting because Christmas fell on a Saturday and CNY fell
on a Sunday, so didn't roll, and Ching Ming was on the same day
as Easter Monday """
holidays = self.cal.holidays_set(2010)
self.assertIn(date(2010, 1, 1), holidays) # New Year
self.assertIn(date(2010, 2, 13), holidays) # Chinese new year (shift)
self.assertIn(date(2010, 2, 15), holidays) # Chinese new year
self.assertIn(date(2010, 2, 16), holidays) # Chinese new year
self.assertNotIn(date(2010, 2, 17), holidays) # Not Chinese new year
self.assertIn(date(2010, 4, 2), holidays) # Good Friday
self.assertIn(date(2010, 4, 3), holidays) # Day after Good Friday
self.assertIn(date(2010, 4, 5), holidays) # Easter Monday
self.assertIn(date(2010, 4, 6), holidays) # Ching Ming (shifted)
self.assertIn(date(2010, 5, 1), holidays) # Labour Day
self.assertIn(date(2010, 5, 21), holidays) # Buddha's Birthday
self.assertIn(date(2010, 6, 16), holidays) # Tuen Ng Festival
self.assertIn(date(2010, 7, 1), holidays) # HK SAR Establishment Day
self.assertIn(date(2010, 9, 23), holidays) # Day after Mid-Autumn
self.assertIn(date(2010, 10, 1), holidays) # National Day
self.assertIn(date(2010, 10, 16), holidays) # Chung Yeung Festival
self.assertIn(date(2010, 12, 25), holidays) # Christmas Day
self.assertIn(date(2010, 12, 27), holidays) # Boxing Day (shifted)
def test_year_2013(self):
holidays = self.cal.holidays_set(2013)
self.assertIn(date(2013, 1, 1), holidays) # New Year
self.assertIn(date(2013, 2, 11), holidays) # Chinese new year
self.assertIn(date(2013, 2, 12), holidays) # Chinese new year
self.assertIn(date(2013, 2, 13), holidays) # Chinese new year
self.assertIn(date(2013, 3, 29), holidays) # Good Friday
self.assertIn(date(2013, 3, 30), holidays) # Day after Good Friday
self.assertIn(date(2013, 4, 1), holidays) # Easter Monday
self.assertIn(date(2013, 4, 4), holidays) # Ching Ming
self.assertIn(date(2013, 5, 1), holidays) # Labour Day
self.assertIn(date(2013, 5, 17), holidays) # Buddha's Birthday
self.assertIn(date(2013, 6, 12), holidays) # Tuen Ng Festival
self.assertIn(date(2013, 7, 1), holidays) # HK SAR Establishment Day
self.assertIn(date(2013, 9, 20), holidays) # Day after Mid-Autumn
self.assertIn(date(2013, 10, 1), holidays) # National Day
self.assertIn(date(2013, 10, 14), holidays) # Chung Yeung Festival
self.assertIn(date(2013, 12, 25), holidays) # Christmas Day
self.assertIn(date(2013, 12, 26), holidays) # Boxing Day
def test_year_2016(self):
holidays = self.cal.holidays_set(2016)
self.assertIn(date(2016, 1, 1), holidays) # New Year
self.assertIn(date(2016, 2, 8), holidays) # Chinese new year
self.assertIn(date(2016, 2, 9), holidays) # Chinese new year
self.assertIn(date(2016, 2, 10), holidays) # Chinese new year
self.assertIn(date(2016, 3, 25), holidays) # Good Friday
self.assertIn(date(2016, 3, 26), holidays) # Day after Good Friday
self.assertIn(date(2016, 3, 28), holidays) # Easter Monday
self.assertIn(date(2016, 4, 4), holidays) # Ching Ming
self.assertIn(date(2016, 5, 2), holidays) # Labour Day (shifted)
self.assertIn(date(2016, 5, 14), holidays) # Buddha's Birthday
self.assertIn(date(2016, 6, 9), holidays) # Tuen Ng Festival
self.assertIn(date(2016, 7, 1), holidays) # HK SAR Establishment Day
self.assertIn(date(2016, 9, 16), holidays) # Day after Mid-Autumn
self.assertIn(date(2016, 10, 1), holidays) # National Day
self.assertIn(date(2016, 10, 10), holidays) # Chung Yeung Festival
self.assertIn(date(2016, 12, 26), holidays) # Christmas Day (shifted)
self.assertIn(date(2016, 12, 27), holidays) # Boxing Day (shifted)
def test_year_2017(self):
holidays = self.cal.holidays_set(2017)
self.assertIn(date(2017, 1, 2), holidays) # New Year (shifted)
self.assertIn(date(2017, 1, 28), holidays) # Chinese new year
self.assertIn(date(2017, 1, 30), holidays) # Chinese new year
self.assertIn(date(2017, 1, 31), holidays) # Chinese new year
self.assertIn(date(2017, 4, 4), holidays) # Ching Ming
self.assertIn(date(2017, 4, 14), holidays) # Good Friday
self.assertIn(date(2017, 4, 15), holidays) # Day after Good Friday
self.assertIn(date(2017, 4, 17), holidays) # Easter Monday
self.assertIn(date(2017, 5, 1), holidays) # Labour Day
self.assertIn(date(2017, 5, 3), holidays) # Buddha's Birthday
self.assertIn(date(2017, 5, 30), holidays) # Tuen Ng Festival
self.assertIn(date(2017, 7, 1), holidays) # HK SAR Establishment Day
self.assertIn(date(2017, 10, 2), holidays) # National Day (shifted)
self.assertIn(date(2017, 10, 5), holidays) # Day after Mid-Autumn
self.assertIn(date(2017, 10, 28), holidays) # Chung Yeung Festival
self.assertIn(date(2017, 12, 25), holidays) # Christmas Day
self.assertIn(date(2017, 12, 26), holidays) # | Boxing Day
def test_chingming_festival(self):
# This is the same as the Taiwan test, just different spelling
# Could move this into a Core test
self.assertI | n(date(2005, 4, 5), self.cal.holidays_set(2005))
self.assertIn(date(2006, 4, 5), self.cal.holidays_set(2006))
self.assertIn(date(2007, 4, 5), self.cal.holidays_set(2007))
self.assertIn(date(2008, 4, 4), self.cal.holidays_set(2008))
self.assertIn(date(2010, 4, 5), self.cal.holidays_set(2010))
self.assertIn(date(2011, 4, 5), self.cal.holidays_set(2011))
self.assertIn(date(2012, 4, 4), self.cal.holidays_set(2012))
self.assertIn(date(2013, 4, 4), self.cal.holidays_set(2013))
self.assertIn(date(2014, 4, 5), self.cal.holidays_set(2014))
self.assertIn(date(2015, 4, 4), self.cal.holidays_set(2015))
self.assertIn(date(2016, 4, 4), self.cal.holidays_set(2016))
self.assertIn(date(2017, 4, 4), self.cal.holidays_set(2017))
self.assertIn(date(2018, 4, 5), self.cal.holidays_set(2018))
class JapanTest(GenericCalendarTest):
cal_class = Japan
def test_year_2013(self):
holidays = self.cal.holidays_set(2013)
self.assertIn(date(2013, 1, 1), holidays) # new year
self.assertIn(date(2013, 2, 11), holidays) # Foundation Day
self.assertIn(date(2013, 3, 20), holidays) # Vernal Equinox Day
self.assertIn(date(2013, 4, 29), holidays) # Showa Day
self.assertIn(date(2013, 5, 3), holidays) # Constitution Memorial Day
self.assertIn(date(2013, 5, 4), holidays) # Greenery Day
self.assertIn(date(2013, 5, 5), holidays) # Children's Day
self.assertIn(date(2013, 9, 23), holidays) # Autumnal Equinox Day
self.assertIn(date(2013, 11, 3), holidays) # Culture Day
self.assertIn(date(2013, 11, 23), holidays) # Labour Thanksgiving Day
self.assertIn(date(2013, 12, 23), holidays) # The Emperor's Birthday
# Variable days
self.assertIn(date(2013, 1, 14), holidays) # Coming of Age Day
self.assertIn(date(2013, 7, 15), holidays) # Marine Day
self.assertIn(date(2013, 9, 16), holidays) # Respect-for-the-Aged Day
self.assertIn(date(2013, 10, 14), holidays) # Health and Sports Day
def test_year_2016(self):
# Before 2016, no Mountain Day
holidays = self.cal.holidays_set(2014)
self.assertNot |
brunobord/critica | apps/admin/sites.py | Python | gpl-3.0 | 2,410 | 0.007469 | # -*- coding: utf-8 -*-
from datetime import datetime
from django.contrib.admin.sites import AdminSite
from django import http, template
from django.shortcuts import render_to_response
from django.template import RequestContex | t
from django.utils.translation import ugettext_lazy, ugettext as _
from django.views.decorators.cache import never_cache
from django.contrib.auth.decorators import login_required
# Basic admin
# ------------------------------------------------------------------------------
class BasicAdminSite(AdminSite):
"""
An AdminSite object encapsulates an instance of the Django admin application, ready
to be hooked in to your URLConf. Models are registered with the AdminSi | te using the
register() method, and the root() method can then be used as a Django view function
that presents a full admin interface for the collection of registered models.
BasicAdminSite is a basic Django admin with lightweight customizations.
"""
index_template = 'basic_admin/index.html'
# Advanced admin
# ------------------------------------------------------------------------------
class AdvancedAdminSite(AdminSite):
"""
An AdminSite object encapsulates an instance of the Django admin application, ready
to be hooked in to your URLConf. Models are registered with the AdminSite using the
register() method, and the root() method can then be used as a Django view function
that presents a full admin interface for the collection of registered models.
AdvancedAdminSite is an advanced Django admin with heavy customizations.
"""
index_template = 'advanced_admin/index.html'
# Sites
# ------------------------------------------------------------------------------
basic_site = BasicAdminSite()
advanced_site = AdvancedAdminSite()
# Default registers
# ------------------------------------------------------------------------------
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin, GroupAdmin
basic_site.register(User, UserAdmin)
basic_site.register(Group, GroupAdmin)
advanced_site.register(User, UserAdmin)
advanced_site.register(Group, GroupAdmin)
from django.contrib.sites.models import Site
from django.contrib.sites.admin import SiteAdmin
basic_site.register(Site, SiteAdmin)
advanced_site.register(Site, SiteAdmin)
|
DuVale/snapboard | setup.py | Python | bsd-3-clause | 2,058 | 0.00243 | #!/usr/bin/python
from distutils.core import setup
setup(
name='snapboard',
version='0.2.1',
author='Bo Shi',
maintainer='SNAPboard developers',
maintainer_email='snapboard-discuss@googlegroups.com',
url='http://code.google.com/p/snapboard/',
description='Bulletin board application for Django.',
long_description='''SNAPboard is forum/bulletin board application based on the Django web
framework. It integrates easily in any Django project.
Among its features are:
* Editable posts with all revisions publicly available
* Messages posted within threads can be made visible only to selected
users
* BBCode, Markdown and Textile supported for post formatting
* BBCode toolbar
* Multiple forums with four types of permissions
* Forum permissions can be a | ssigned to custom groups of users
* Group administration can be delegated to end users on a per-group basis
* Moderators for each forum
* User preferences
* Watched topics
* Abuse reports
* User and IP address bans that don't automatically spread to other Django
applications within the project
* i18n hooks to create your own translations
* Included translations: French, Russian
| SNAPboard requires Django 1.0.''',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: New BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Communications :: BBS',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Message Boards',
],
packages=['snapboard',],
package_dir={'snapboard': 'snapboard'},
package_data={'snapboard': [
'media/*/*.*',
'media/*/*/*.*',
'templates/*.*',
'templates/snapboard/*.*',
'templates/notification/*.*',
'templates/notification/*/*.*',
]},
)
# vim: ai ts=4 sts=4 et sw=4
|
dmlc/tvm | python/tvm/contrib/tedd.py | Python | apache-2.0 | 27,567 | 0.001306 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=import-outside-toplevel
"""Tensor Expression Debug Display (TEDD), visualizing Tensor Expression"""
import html
import json
import warnings
from graphviz import Digraph
from graphviz import Source
import tvm
TVMDD_TABLE_BODY_WIDTH = 30
# Must match enum IterVarType defined in include/tvm/expr.h
ITERVAR_TYPE_STRING_MAP = {
0: ("kDataPar", "#FFFFFF"),
1: ("kThreadIndex", "#2980B9"),
2: ("kCommReduce", "#FAD7A0"),
3: ("kOrdered", "#D35400"),
4: ("kOpaque", "#ABB2B9"),
5: ("kUnrolled", "#D2B4DE"),
6: ("kVectorized", "#AED6F1"),
7: ("kParallelized", "#F5B7B1"),
8: ("kTensorized", "#A9DFBF"),
}
PALETTE = {
0: "#000000",
1: "#922B21",
2: "#76448A",
3: "#1F618D",
4: "#148F77",
5: "#B7950B",
6: "#AF601A",
7: "#F5B7B1",
8: "#A9DFBF",
}
PALETTE_SIZE = 9
def dom_path_to_string(dom_path, prefix=""):
path_string = prefix
for index in dom_path:
path_string = path_string + "_" + str(index)
return path_string
def insert_dot_id(sch):
"""Insert unique ID for each node in the DOM tree.
They are used as Dot node ID.
"""
for stage_idx, stage in enumerate(sch["stages"]):
dom_path = [stage_idx]
stage["id"] = dom_path_to_string(dom_path, stage["type"])
for itervar_idx, itervar in enumerate(stage["all_itervars"]):
dom_path = [stage_idx, itervar_idx]
itervar["id"] = dom_path_to_string(dom_path, itervar["type"])
for rel_idx, rel in enumerate(stage["relations"]):
dom_path = [stage_idx, rel_idx]
rel["id"] = dom_path_to_string(dom_path, rel["type"])
for tensor_idx, tensor in enumerate(stage["output_tensors"]):
dom_path = [stage_idx, tensor_idx]
tensor["id"] = dom_path_to_string(dom_path, tensor["type"])
return sch
class ObjectManager:
"""A helper class tracking schedule objects, e.g. stage, IterVar,
relationship, and tensor, to their DOM path."""
def __init__(self, sch):
self.dict = {}
for stage_idx, stage in enumerate(sch.stages):
self.dict[stage] = [stage_idx]
for itervar_idx, itervar in enumerate(stage.all_iter_vars):
self.dict[itervar] = [stage_idx, itervar_idx]
for rel_idx, rel in enumerate(stage.relations):
self.dict[rel] = [stage_idx, rel_idx]
for tensor_idx in range(stage.op.num_outputs):
self.dict[frozenset({stage.op.name, tensor_idx})] = [stage_idx, tensor_idx]
def get_dom_path(self, obj):
if obj is None:
return None
assert obj in self.dict, "Node is no found."
return self.dict[obj]
def get_or_create_dot_id(obj, prefix="", assert_on_missing=False):
"""If obj's ID has been registered, return it.
If not, either assert or create a unique and legal ID, register and
return it, according to assert_on_missing.
ID must be a unique and legal Dotty ID.
Parameters
----------
obj : objet
Serve as the key to the ID.
prefix : string
Prefix to attach to the ID. Usually use obj's non-unique
name as prefix.
assert_on_missing : bool
Assert or not if object doesn't have a registered ID.
"""
prefix = prefix.replace(".", "_")
if not hasattr(get_or_create_dot_id, "obj_id_dict"):
get_or_create_dot_id.obj_id_dict = {}
if obj not in get_or_create_dot_id.obj_id_dict:
if assert_on_missing:
assert False, "dot_id " + str(obj) + " has not been registered."
else:
get_or_create_dot_id.obj_id_dict[obj] = prefix + hex(id(obj))
return get_or_create_dot_id.obj_id_dict[obj]
def get_port_id(is_input, index):
return "I_" + str(index) if is_input else "O_" + str(index)
def get_itervar_type_info(iter_type):
assert iter_type < len(ITERVAR_TYPE_STRING_MAP), "Unknown IterVar type: " + str(iter_type)
return ITERVAR_TYPE_STRING_MAP[iter_type]
def get_itervar_label_color(itervar, iv_type):
type_info = get_itervar_type_info(iv_type)
return (
linebrk(str(itervar["name"]) + "(" + type_info[0] + ")", TVMDD_TABLE_BODY_WIDTH),
type_info[1],
)
def linebrk(s, n):
"""Break input string s with <br/> for every n charactors."""
result = ""
j = 0
for i, c in enumerate(s):
if j == n and i != len(s) - 1:
result = result + "\n"
j = 0
j = j + 1
result = result + c
result = html.escape(str(result), quote=True)
result = result.replace("\n", "<br/>")
return result
def create_graph(name="", rankdir="BT"):
graph = Digraph(name=name)
graph.graph_attr["rankdir"] = rankdir
return graph
def itervar_label(itervar, index, index_color, label):
return (
'<TR><TD PORT="'
+ itervar["id"]
+ '" BGCOLOR="'
+ index_color
+ '">'
+ str(index)
+ '</TD><TD BGCOLOR="white" PORT="itervar">'
+ label
+ "<br/>"
+ str(itervar["properties"]["range"])
+ "</TD></TR>"
)
def stage_label(stage):
return stage["name"] + "<br/>Scope: " + stage["properties"]["scope"]
def legend_label():
"""Generate legend labels."""
label = '<<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="4">'
for iter_type in ITERVAR_TYPE_STRING_MAP:
name, color = ITERVAR_TYPE_STRING_MAP[iter_type]
label += (
'<TR><TD BGCOLOR="' + color + '"></TD>' + '<TD BGCOLOR="white">' + name + "</TD></TR>"
)
label += "</TABLE>>"
return label
def leaf_itervars(stage):
filtered = filter(lambda x: (x["index"] >= 0), stage["all_itervars"])
return sorted(filtered, key=lambda x: x["index"])
def legend_dot(g):
with g.subgraph(name="cluster_legend") as subgraph:
subgraph.attr(label="Legend")
label = legend_label()
subgraph.node("legend", label, shape="none", margin="0")
def extract_dom_for_viz(sch, need_range=True):
json_str = dump_json(sch, need_range)
s = json.loads(json_str)
s = insert_dot_id(s)
return s
def dump_graph(dot_string, show_svg=True, dot_file_path="", output_dot_string=False):
"""Output dot_string in various formats."""
if dot_file_path:
try:
dot_file = open(dot_file_path, "w+")
dot_file.write(dot_string)
dot_file.close()
except IOError:
print("Cannot open file: " + dot_file_path)
if show_svg:
from IPython.display import display
from IPython.display import SVG
| src = Source(dot_string)
display(SVG(src.pipe(format="svg")))
if output_dot_string:
return dot_string
return None
def dump_json(sch, need_range):
"""Serialize data for visualization from a schedule in JSON format.
Parameters
----------
sch : schedule
| The schedule object to serialize
Returns
-------
json : string
Serialized JSON string
"""
def encode_itervar(itervar, stage, index, range_map):
"""Extract and encode IterVar visualization data to a dictionary"""
ivrange = range_map[itervar] if range_map is not None and itervar in range_map else None
bind_thread = None
tensor_intrin = None |
kaynfiretvguru/Eldritch | plugin.program.echowizard/resources/lib/modules/extract.py | Python | gpl-2.0 | 2,897 | 0.022092 | """
Copyright (C) 2016 ECHO Wizard
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 distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import zipfile, xbmcgui
def auto(_in, _out):
return allNoProgress(_in, _out)
def all(_in, _out, dp=None):
if dp:
return allWithProgress(_in, _out, dp)
return allNoProgress(_in, _out)
def all_update(_in, _out, dp=None):
if dp:
return allWithProgress_update(_in, _out, dp)
return allNoProgress_update(_in, _out)
def allNoProgress(_in, _out):
try:
zin = zipfile.ZipFile(_in, 'r')
zin.extractall(_out)
except Exception, e:
print str(e)
return False
return True
def allWithProgress(_in, _out, dp):
zin = zipfile.ZipFile(_in, 'r')
nFiles = float(len(zin.infolist()))
count = 0
try:
for i | tem in zin.infolist():
count += 1
update = count / nFiles * 100
dp.update(int(update),'','','[COLOR dodgerblue][B]' + str(item.filename) + '[/B][/COLOR]')
try:
zin.extract(item, _out)
except Exception, e:
print str(e)
except Exception, e:
print str(e)
return False
return True
def allWithProgress_update( | _in, _out, dp):
zin = zipfile.ZipFile(_in, 'r')
nFiles = float(len(zin.infolist()))
count = 0
skin_selected = 0
#try:
for item in zin.infolist():
count += 1
update = count / nFiles * 100
dp.update(int(update),'','','[COLOR dodgerblue][B]' + str(item.filename) + '[/B][/COLOR]')
if "userdata/skin" in str(item.filename):
if skin_selected == 0:
choice = xbmcgui.Dialog().yesno("IMPORTANT INFORMATION", "We have detected that this segment of the update contains changes to the skin files. If you agree to install this segment of the update it could result in you losing menu items etc that you have set. Would you like to install this segment of the update?" ,yeslabel='[B][COLOR green]YES[/COLOR][/B]',nolabel='[B][COLOR red]NO[/COLOR][/B]')
skin_selected = 1
if choice == 1:
try:
zin.extract(item, _out)
except Exception, e:
print str(e)
else:
try:
zin.extract(item, _out)
except Exception, e:
print str(e)
#except Exception, e:
# print str(e)
# return False
return True |
Dawny33/Code | Code_Forces/Contest 277/A.py | Python | gpl-3.0 | 66 | 0.045455 | T = input()
if T%2==0:
print T | /2
else:
print ((T-1)/2)-T | |
daikeren/opbeat_python | tests/instrumentation/python_memcached_tests.py | Python | bsd-3-clause | 2,007 | 0 | from functools import partial
from django.test import TestCase
import mock
import memcache
import opbeat
from tests.contrib.django.django_tests import get_client
class InstrumentMemcachedTest(TestCase):
def setUp(self):
self.client = get_client()
opbeat.instrumentation.control.instrument(self.client)
@mock.patch("opbeat.traces.RequestsStore.should_collect")
def test_memcached(self, should_collect):
should_collect.return_value = False
self.client.begin_transaction()
with self.client.capture_trace("test_memcached", "test"):
conn = memcache.Client(['127.0.0.1:11211'], debug=0)
conn.set("mykey", "a")
assert "a" == conn.get("mykey")
assert {"mykey": "a"} == conn.get_multi(["mykey", "myotherkey"])
self.client.e | nd_transaction(None, "test")
transactions, traces = self.client.instrumentation_store.get_all()
expected_signatures = ['transaction', 'test_memcached',
'Client.set', 'Client.get',
'Client.get_multi']
self.assertEqual(set([t['signature'] for t in traces]),
set(expected_signatures))
# Reorder according to the kinds list | so we can just test them
sig_dict = dict([(t['signature'], t) for t in traces])
traces = [sig_dict[k] for k in expected_signatures]
self.assertEqual(traces[0]['signature'], 'transaction')
self.assertEqual(traces[0]['kind'], 'transaction')
self.assertEqual(traces[0]['transaction'], 'test')
self.assertEqual(traces[1]['signature'], 'test_memcached')
self.assertEqual(traces[1]['kind'], 'test')
self.assertEqual(traces[1]['transaction'], 'test')
self.assertEqual(traces[2]['signature'], 'Client.set')
self.assertEqual(traces[2]['kind'], 'cache.memcached')
self.assertEqual(traces[2]['transaction'], 'test')
self.assertEqual(len(traces), 5)
|
zooniverse/aggregation | experimental/algorithms/test.py | Python | apache-2.0 | 475 | 0.027368 | import cv2
import numpy as np
fi | lename = '/home/greg/Databases/images/0c9a02a8-2b7d-484e-ba18-e35d33800774.jpeg'
img = cv2.imread(filename)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv2.cornerHarris(gray,2,3,0.04)
#result is dilated for marking the corners, not important
dst = cv2.dilate(dst,None)
# Threshold for an optimal value, it may vary depending on the image.
img[dst>0.01*dst.max()]=[0,0,255]
cv | 2.imwrite('/home/greg/1.jpg',img) |
cxxgtxy/tensorflow | tensorflow/python/keras/saving/saved_model/json_utils_test.py | Python | apache-2.0 | 2,675 | 0.002243 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# 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 under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# pylint: disable=protected-access
"""Tests the JSON encoder and decoder."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_spec
from tensorflow.python.keras.saving.saved_model import json_utils
from tensorflow.python.platform import test
class JsonUtilsTest(test.TestCase):
def test_encode_decode_tensor_shape(self):
metadata = {
'key1': tensor_shape.TensorShape(None),
'key2': [tensor_shape.TensorShape([None]),
tensor_shape.TensorShape([3, None, 5])]}
string = json_utils.Encoder().encode(metadata)
loaded = json_utils.decode(string)
self.assertEqual(set(loaded.keys()), {'key1', 'key2'})
s | elf.assertAllEqual(loaded['key1'].rank, None)
self.assertAllEqual(loaded['key2'][0].as_list(), [None])
self.assertAllEqual(loaded['key2'][1].as_list(), [3, None, 5])
def test_encode_decode_tuple(self):
metadata = {
'key1': (3, 5),
'key2': [(1, (3, 4)), (1,)]}
string = json_utils.Encoder().encode(metadata)
loaded = json_utils.decode(string)
self.assertEqual(set(load | ed.keys()), {'key1', 'key2'})
self.assertAllEqual(loaded['key1'], (3, 5))
self.assertAllEqual(loaded['key2'], [(1, (3, 4)), (1,)])
def test_encode_decode_type_spec(self):
spec = tensor_spec.TensorSpec((1, 5), dtypes.float32)
string = json_utils.Encoder().encode(spec)
loaded = json_utils.decode(string)
self.assertEqual(spec, loaded)
invalid_type_spec = {'class_name': 'TypeSpec', 'type_spec': 'Invalid Type',
'serialized': None}
string = json_utils.Encoder().encode(invalid_type_spec)
with self.assertRaisesRegexp(ValueError, 'No TypeSpec has been registered'):
loaded = json_utils.decode(string)
if __name__ == '__main__':
test.main()
|
timmahrt/ProMo | examples/pitch_morph_to_pitch_contour.py | Python | mit | 2,635 | 0 | '''
Created on Jun 29, 2016
This file shows an example of morphing to a pitch tier.
In f0_morph.py, the target pitch contour is extracted in the
script from another file. In this example, the pitch tier
could come from any source (hand sculpted or generated).
WARNING: If you attempt to morph to a pitch track that has
few sample points, the morph process will fail.
@author: Tim
'''
import os
from os.path import join
from praatio import pit | ch_and_intensity
from praatio import dataio
from promo impor | t f0_morph
from promo.morph_utils import utils
from promo.morph_utils import interpolation
# Define the arguments for the code
root = os.path.abspath(join('.', 'files'))
praatEXE = r"C:\Praat.exe" # Windows paths
praatEXE = "/Applications/Praat.app/Contents/MacOS/Praat" # Mac paths
minPitch = 50
maxPitch = 350
stepList = utils.generateStepList(3)
fromName = "mary1"
fromWavFN = fromName + ".wav"
fromPitchFN = fromName + ".txt"
fromTGFN = join(root, fromName + ".TextGrid")
toName = "mary1_stylized"
toPitchFN = toName + ".PitchTier"
# Prepare the data for morphing
# 1st load it into memory
fromPitchList = pitch_and_intensity.extractPI(join(root, fromWavFN),
join(root, fromPitchFN),
praatEXE, minPitch,
maxPitch, forceRegenerate=False)
fromPitchList = [(time, pitch) for time, pitch, _ in fromPitchList]
# Load in the target pitch contour
pitchTier = dataio.open2DPointObject(join(root, toPitchFN))
toPitchList = [(time, pitch) for time, pitch in pitchTier.pointList]
# The target contour doesn't contain enough sample points, so interpolate
# over the provided samples
# (this step can be skipped if there are enough sample points--a warning
# will be issued if there are any potential problems)
toPitchList = interpolation.quadraticInterpolation(toPitchList, 4, 1000, 0)
# 3rd select which sections to align.
# We'll use textgrids for this purpose.
tierName = "words"
fromPitch = f0_morph.getPitchForIntervals(fromPitchList, fromTGFN, tierName)
toPitch = f0_morph.getPitchForIntervals(toPitchList, fromTGFN, tierName)
# Run the morph process
f0_morph.f0Morph(fromWavFN=join(root, fromWavFN),
pitchPath=root,
stepList=stepList,
outputName="%s_%s_f0_morph" % (fromName, toName),
doPlotPitchSteps=True,
fromPitchData=fromPitch,
toPitchData=toPitch,
outputMinPitch=minPitch,
outputMaxPitch=maxPitch,
praatEXE=praatEXE)
|
arunkgupta/gramps | gramps/gui/widgets/validatedcomboentry.py | Python | gpl-2.0 | 8,370 | 0.007168 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2008 Zsolt Foldvari
#
# 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id$
"The ValidatedComboEntry widget class."
__all__ = ["ValidatedComboEntry"]
#-------------------------------------------------------------------------
#
# Python modules
#
#-------------------------------------------------------------------------
import logging
_LOG = logging.getLogger(".widgets.validatedcomboentry")
#-------------------------------------------------------------------------
#
# GTK modules
#
#-------------------------------------------------------------------------
from gi.repository import GObject
from gi.repository import Gdk
from gi.repository import Gtk
#-------------------------------------------------------------------------
#
# ValidatedComboEntry class
#
#-------------------------------------------------------------------------
class ValidatedComboEntry(Gtk.ComboBox):
"""A ComboBoxEntry widget with validation.
ValidatedComboEntry may have data type other then string, and is set
with the C{datatype} contructor parameter.
Its behaviour is different from Gtk.ComboBoxEntry in the way how
the entry part of the widget is handled. While Gtk.ComboBoxEntry
emits the 'changed' signal immediatelly the text in the entry is
changed, ValidatedComboEntry emits the signal only after the text is
activated (enter is pressed, the focus is moved out) and validated.
Validation function is an optional feature and activated only if a
validator function is given at instantiation.
The entry can be set as editable or not editable using the
L{set_entry_editable} method.
"""
__gtype_name__ = "ValidatedComboEntry"
def __init__(self, datatype, model=None, column=-1, validator=None, width=-1):
#GObject.GObject.__init__(self, model)
Gtk.ComboBox.__init__(self, model=model)
self._entry = Gtk.Entry()
self._entry.set_width_chars(width)
# <hack description="set the GTK_ENTRY(self._entry)->is_cell_renderer
# flag to TRUE in order to tell the entry to fill its allocation.">
dummy_event = Gdk.Event(Gdk.EventType.NOTHING)
self._entry.start_editing(dummy_event)
# </hack>
self.add(self._entry)
self._entry.show()
self._text_renderer = Gtk.CellRendererText()
self.pack_start(self._text_renderer, False)
self._data_type = datatype
self._data_column = -1
self.set_data_column(column)
self._active_text = ''
self._active_data = None
self.set_active(-1)
self._validator = validator
self._entry.connect('activate', self._on_entry_activate)
self._entry.connect('focus-in-event', self._on_entry_focus_in_event)
self._entry.connect('focus-out-event', self._on_entry_focus_out_event)
self._entry.connect('key-press-event', self._on_entry_key_press_event)
self.connect('changed', self._on_changed)
self._internal_change = False
self._has_frame_changed()
self.connect('notify', self._on_notify)
# Virtual overriden methods
def do_mnemonic_activate(self, group_cycling):
self._entry.grab_focus()
return True
def do_grab_focus(self):
self._entry.grab_focus()
# Signal handlers
def _on_entry_activate(self, entry):
"""Signal handler.
Called when the entry is activated.
"""
self._entry_changed(entry)
def _on_entry_focus_in_event(self, widget, event):
"""Signal handler.
Called when the focus enters the entry, and is used for saving
the entry's text for later comparison.
"""
self._text_on_focus_in = self._entry.get_text()
def _on_entry_focus_out_event(self, widget, event):
"""Signal handler.
Called when the focus leaves the entry.
"""
if (self._entry.get_text() != self._text_on_focus_in):
self._entry_changed(widget)
def _on_entry_key_press_event(self, entry, event):
"""Signal handler.
Its purpose is to handle escape button.
"""
# FIXME Escape never reaches here, the dialog eats it, I assume.
if event.keyval == Gdk.KEY_Escape:
entry.set_text(self._active_text)
entry.set_position(-1)
return True
return False
def _on_changed(self, combobox):
"""Signal handler.
Called when the active row is changed in the combo box.
"""
if self._internal_change:
return
iter = self.get_active_iter()
if iter:
model = self.get_model()
self._active_data = model.get_value(iter, self._data_column)
self._active_text = str(self._active_data)
self._entry.set_text(self._active_text)
def _on_notify(self, object, gparamspec):
"""Signal handler.
Called whenever a property of the object is changed.
"""
if gparamspec and gparamspec.name == 'has-frame':
self._has_frame_changed()
# Private methods
def _entry_changed(self, entry):
new_text = entry.get_text()
try:
new_data = self._data_type(new_text)
if (self._validator is not None) and not self._validator(new_data):
raise ValueError
except ValueError:
entry.set_text(self._active_text)
entry.set_position(-1)
return
self._active_text = new_text
self._active_data = new_data
self._internal_change = True
new_iter = self._is_in_model(new_data)
if new_iter is None:
self.set_active(-1)
else:
self.set_active_iter(new_iter)
self._internal_change = False
def _h | as_frame_changed(self):
has_frame = self.get_property('has-frame')
| self._entry.set_has_frame(has_frame)
def _is_in_model(self, data):
"""Check if given data is in the model or not.
@param data: data value to check
@type data: depends on the actual data type of the object
@returns: position of 'data' in the model
@returntype: Gtk.TreeIter or None
"""
model = self.get_model()
iter = model.get_iter_first()
while iter:
if model.get_value(iter, self._data_column) == data:
break
iter = model.iter_next(iter)
return iter
# Public methods
def set_data_column(self, data_column):
if data_column < 0:
return
model = self.get_model()
if model is None:
return
if data_column > model.get_n_columns():
return
if self._data_column == -1:
self._data_column = data_column
self.add_attribute(self._text_renderer, "text", data_column)
def get_data_column(self):
return self._data_column
def set_active_data(self, data):
# set it via entry so that it will be also validated
if self._entry:
self._entry.set_text(str(data))
se |
mythmon/kitsune | kitsune/customercare/tests/test_badges.py | Python | bsd-3-clause | 1,176 | 0 | from datetime import date
from kitsune.customercare.badges import AOA_BADGE
from kitsune.customercare.tests import ReplyFactory
from kitsune.kbadge.tests import BadgeFactory
from kitsune.sumo.tests import TestCase
from kitsune.users.tests import UserFac | tory
from kitsune.customercare.badges import register_signals
class TestAOABadges(TestCase):
def setUp | (self):
# Make sure the badges hear this.
register_signals()
def test_aoa_badge(self):
"""Verify the KB Badge is awarded properly."""
# Create the user and badge.
year = date.today().year
u = UserFactory()
b = BadgeFactory(
slug=AOA_BADGE['slug'].format(year=year),
title=AOA_BADGE['title'].format(year=year),
description=AOA_BADGE['description'].format(year=year))
# Create 49 replies.
# FIXME: Do this as a batch
for _ in range(49):
ReplyFactory(user=u)
# User should NOT have the badge yet.
assert not b.is_awarded_to(u)
# Create 1 more reply.
ReplyFactory(user=u)
# User should have the badge now.
assert b.is_awarded_to(u)
|
patricmutwiri/pombola | pombola/projects/views.py | Python | agpl-3.0 | 504 | 0.007937 | import models
import pombola.core.models
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404, redirect
def in_place(requ | est, slug):
place = get_object_or_404( pombola.core.models.Place, slug=slug)
projects = place.project_set
return render_to_response(
'projects/in_place.html',
{
'place': place,
'projects': projects,
| },
context_instance=RequestContext(request)
)
|
textbook/flash_services | tests/test_auth.py | Python | isc | 391 | 0 | from flash_services.auth import BasicAu | thHeaderMixin
from flash_services.core import Service
class BasicAuthParent(BasicAuth | HeaderMixin, Service):
def update(self): pass
def format_data(self, data): pass
def test_basic_auth():
service = BasicAuthParent(username='username', password='password')
assert service.headers['Authorization'] == 'Basic dXNlcm5hbWU6cGFzc3dvcmQ='
|
daGrevis/daGrevis.lv | dagrevis_lv/legacy/routers.py | Python | mit | 438 | 0 | class LegacyRouter(object):
def db_for_read(self, model, **hints):
| if model._meta.app_label == "legacy":
return "legacy"
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == "legacy":
return "legacy"
return None
def allow_relation(self, obj1, obj2, **hints):
return False
d | ef allow_syncdb(self, db, model):
return False
|
davy39/eric | Plugins/CheckerPlugins/CodeStyleChecker/Ui_CodeStyleCheckerDialog.py | Python | gpl-3.0 | 18,215 | 0.005215 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleCheckerDialog.ui'
#
# Created: Tue Nov 18 17:53:57 2014
# by: PyQt5 UI code generator 5.3.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_CodeStyleCheckerDialog(object):
def setupUi(self, CodeStyleCheckerDialog):
CodeStyleCheckerDialog.setObjectName("CodeStyleCheckerDialog")
CodeStyleCheckerDialog.resize(650, 700)
CodeStyleCheckerDialog.setSizeGripEnabled(True)
self.verticalLayout_2 = QtWidgets.QVBoxLayout(CodeStyleCheckerDialog)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.filterFrame = QtWidgets.QFrame(CodeStyleCheckerDialog)
self.filterFrame.setFrameShape(QtWidgets.QFrame.NoFrame)
self.filterFrame.setObjectName("filterFrame")
self.gridLayout = QtWidgets.QGridLayout(self.filterFrame)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.label_2 = QtWidgets.QLabel(self.filterFrame)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1)
self.excludeFilesEdit = E5ClearableLineEdit(self.filterFrame)
self.excludeFilesEdit.setObjectName("excludeFilesEdit")
self.gridLayout.addWidget(self.excludeFilesEdit, 0, 1, 1, 1)
self.line = QtWidgets.QFrame(self.filterFrame)
self.line.setLineWidth(2)
self.line.setFrameShape(QtWidgets.QFrame.VLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.gridLayout.addWidget(self.line, 0, 3, 9, 1)
self.verticalLayout = QtWidgets.QVBoxLayout()
self.verticalLayout.setObjectName("verticalLayout")
self.startButton = QtWidgets.QPushButton(self.filterFrame)
self.startButton.setObjectName("startButton")
self.verticalLayout.addWidget(self.startButton)
self.fixButton = QtWidgets.QPushButton(self.filterFrame)
self.fixButton.setObjectName("fixButton")
self.verticalLayout.addWidget(self.fixButton)
spacerItem = QtWidgets.QSpacerItem(20, 18, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem)
self.loadDefaultButton = QtWidgets.QPushButton(self.filterFrame)
self.loadDefaultButton.setObjectName("loadDefaultButton")
self.verticalLayout.addWidget(self.loadDefaultButton)
self.storeDefaultButton = QtWidgets.QPushButton(self.filterFrame)
self.storeDefaultButton.setObjectName("storeDefaultButton" | )
self.verticalLayout.addWidget(self.storeDefaultButton)
self.resetDefaultButton = QtWidgets.QPushButton(self.filterFrame)
self.resetDefaultButton.setObjectName("resetDefaultButton")
self.verticalLayout.addWidget(self.resetDefaultButton)
self.gridLayout.addLayout(self.verticalLayout, 0, 4, 9, 1)
self.label = QtWidgets.QLabel(self.filterFrame)
self.label.setObjectName("label")
self.gridLayou | t.addWidget(self.label, 1, 0, 1, 1)
self.excludeMessagesEdit = E5ClearableLineEdit(self.filterFrame)
self.excludeMessagesEdit.setObjectName("excludeMessagesEdit")
self.gridLayout.addWidget(self.excludeMessagesEdit, 1, 1, 1, 1)
self.excludeMessagesSelectButton = QtWidgets.QToolButton(self.filterFrame)
self.excludeMessagesSelectButton.setObjectName("excludeMessagesSelectButton")
self.gridLayout.addWidget(self.excludeMessagesSelectButton, 1, 2, 1, 1)
self.label_3 = QtWidgets.QLabel(self.filterFrame)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 2, 0, 1, 1)
self.includeMessagesEdit = E5ClearableLineEdit(self.filterFrame)
self.includeMessagesEdit.setObjectName("includeMessagesEdit")
self.gridLayout.addWidget(self.includeMessagesEdit, 2, 1, 1, 1)
self.includeMessagesSelectButton = QtWidgets.QToolButton(self.filterFrame)
self.includeMessagesSelectButton.setObjectName("includeMessagesSelectButton")
self.gridLayout.addWidget(self.includeMessagesSelectButton, 2, 2, 1, 1)
self.label_4 = QtWidgets.QLabel(self.filterFrame)
self.label_4.setObjectName("label_4")
self.gridLayout.addWidget(self.label_4, 3, 0, 1, 1)
self.fixIssuesEdit = E5ClearableLineEdit(self.filterFrame)
self.fixIssuesEdit.setObjectName("fixIssuesEdit")
self.gridLayout.addWidget(self.fixIssuesEdit, 3, 1, 1, 1)
self.fixIssuesSelectButton = QtWidgets.QToolButton(self.filterFrame)
self.fixIssuesSelectButton.setObjectName("fixIssuesSelectButton")
self.gridLayout.addWidget(self.fixIssuesSelectButton, 3, 2, 1, 1)
self.label_6 = QtWidgets.QLabel(self.filterFrame)
self.label_6.setObjectName("label_6")
self.gridLayout.addWidget(self.label_6, 4, 0, 1, 1)
self.noFixIssuesEdit = E5ClearableLineEdit(self.filterFrame)
self.noFixIssuesEdit.setObjectName("noFixIssuesEdit")
self.gridLayout.addWidget(self.noFixIssuesEdit, 4, 1, 1, 1)
self.noFixIssuesSelectButton = QtWidgets.QToolButton(self.filterFrame)
self.noFixIssuesSelectButton.setObjectName("noFixIssuesSelectButton")
self.gridLayout.addWidget(self.noFixIssuesSelectButton, 4, 2, 1, 1)
self.label_5 = QtWidgets.QLabel(self.filterFrame)
self.label_5.setObjectName("label_5")
self.gridLayout.addWidget(self.label_5, 5, 0, 1, 1)
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.lineLengthSpinBox = QtWidgets.QSpinBox(self.filterFrame)
self.lineLengthSpinBox.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.lineLengthSpinBox.setMinimum(60)
self.lineLengthSpinBox.setMaximum(119)
self.lineLengthSpinBox.setProperty("value", 79)
self.lineLengthSpinBox.setObjectName("lineLengthSpinBox")
self.horizontalLayout_3.addWidget(self.lineLengthSpinBox)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_3.addItem(spacerItem1)
self.gridLayout.addLayout(self.horizontalLayout_3, 5, 1, 1, 2)
self.label_7 = QtWidgets.QLabel(self.filterFrame)
self.label_7.setObjectName("label_7")
self.gridLayout.addWidget(self.label_7, 6, 0, 1, 1)
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.docTypeComboBox = QtWidgets.QComboBox(self.filterFrame)
self.docTypeComboBox.setObjectName("docTypeComboBox")
self.horizontalLayout_4.addWidget(self.docTypeComboBox)
spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem2)
self.gridLayout.addLayout(self.horizontalLayout_4, 6, 1, 1, 2)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.hangClosingCheckBox = QtWidgets.QCheckBox(self.filterFrame)
self.hangClosingCheckBox.setObjectName("hangClosingCheckBox")
self.horizontalLayout_2.addWidget(self.hangClosingCheckBox)
spacerItem3 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem3)
self.gridLayout.addLayout(self.horizontalLayout_2, 7, 0, 1, 3)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.repeatCheckBox = QtWidgets.QCheckBox(self.filterFrame)
self.repeatCheckBox.setObjectName("repeatCheckBox")
self.horizontalLayout.addWidget(self.repeatCheckBox)
self.fixIssuesCheckBox = QtWidgets.QCheckBox(self.filterFrame)
self.fixIs |
5agado/intro-ai | src/test/housePricing.py | Python | apache-2.0 | 2,178 | 0.015611 | from util import utils
import os
import numpy as np
from mpl_toolkits.mplot3d import *
from sklearn import linear_model
F = None #num of features
N = None #num of training samples
T = None #num of test samples
def readData(filename):
filePath = os.path.join(utils.getResourcesPath(), filename)
f = open(filePath, 'r')
global F, N, T
F, N = map(int, f.readline().strip().split())
data = []
for _ in range(0, N):
line = list(map(float, f.readline().strip().split()))
data.append((line[:-1], line[-1]))
T = int(f.readline().strip())
test = []
for _ in range(0, T):
line = list(map(float, f.readline().strip().split()))
| test.append(line)
return data, test
def gradientDescent(features, values, nIter = 500, lRate = 0.001):
X = np.append(features, np.ones((len(features),1)), axis=1) #dummy column for intercept weight
weights = np.random.random(X.shape[1]) #consider intercept weight
history = []
for _ in range(nIter):
pred = X.dot(weights).flatten()
for i in range(F+1):
| #errors2 = [(values[i]-np.dot(weights,X[i]))*X[i] for i in range(N)]
errors = (values - pred)* X[:, i]
weights[i] += lRate * errors.sum()
#necessary 1/n factor??
e = sum([(values[i]-np.dot(weights,X[i]))**2 for i in range(N)])
history.append(e)
#history.append(weights)
return weights, history
data, test = readData('hackerrank\\housePricing.txt')
features = np.array([[row[0][x] for x in range(F)] for row in data])
values = np.array([row[1] for row in data])
weights, history = gradientDescent(features, values)
test = np.array([[row[x] for x in range(F)] for row in test])
mTest = np.append(test, np.ones((T, 1)), axis=1)
for v in mTest.dot(weights):
print("{0:.2f}".format(float(v)))
#Using sklearn
# Create linear regression object
regr = linear_model.LinearRegression()
# Train the model using the training sets
regr.fit(features, values)
for v in test.dot(regr.coef_):
print("{0:.2f}".format(float(v))) |
BTA-BATA/electrum-bta-master | lib/wallet.py | Python | gpl-3.0 | 72,921 | 0.00314 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 thomasv@gitorious
#
# 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 distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import os
import hashlib
import ast
import threading
import random
import time
import math
import json
import copy
from operator import itemgetter
from util import print_msg, print_error, NotEnoughFunds
from util import profiler
from bitcoin import *
from account import *
from version import *
from transaction import Transaction
from plugins import run_hook
import bitcoin
from synchronizer import WalletSynchronizer
from mnemonic import Mnemonic
# internal ID for imported account
IMPORTED_ACCOUNT = '/x'
class WalletStorage(object):
def __init__(self, path):
self.lock = threading.RLock()
self.data = {}
self.path = path
self.file_exists = False
print_error( "wallet path", self.path )
if self.path:
self.read(self.path)
def read(self, path):
"""Read the contents of the wallet file."""
try:
with open(self.path, "r") as f:
data = f.read()
except IOError:
return
try:
self.data = json.loads(data)
except:
try:
d = ast.literal_eval(data) #parse raw data from reading wallet file
except Exception as e:
raise IOError("Cannot read wallet file '%s'" % self.path)
self.data = {}
# In old versions of Electrum labels were latin1 encoded, this fixes breakage.
labels = d.get('labels', {})
for i, label in labels.items():
try:
unicode(label)
except UnicodeDecodeError:
d['labels'][i] = unicode(label.decode('latin1'))
for key, value in d.items():
try:
json.dumps(key)
json.dumps(value)
except:
print_error('Failed to convert label to json format', key)
continue
self.data[key] = value
self.file_exists = True
def get(self, key, default=None):
with self.lock:
v = self.data.get(key)
if v is None:
v = default
else:
v = copy.deepcopy(v)
return v
def put(self, key, value, save = True):
try:
json.dumps(key)
json.dumps(value)
except:
print_error("json error: cannot save", key)
return
with self.lock:
if value is not None:
| self.data[key] = copy.deepcopy(value)
elif key in self.data:
self.data.pop(key)
if save:
self.write()
def write(self):
assert not threading.currentThread() | .isDaemon()
temp_path = "%s.tmp.%s" % (self.path, os.getpid())
s = json.dumps(self.data, indent=4, sort_keys=True)
with open(temp_path, "w") as f:
f.write(s)
f.flush()
os.fsync(f.fileno())
# perform atomic write on POSIX systems
try:
os.rename(temp_path, self.path)
except:
os.remove(self.path)
os.rename(temp_path, self.path)
if 'ANDROID_DATA' not in os.environ:
import stat
os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
class Abstract_Wallet(object):
"""
Wallet classes are created to handle various address generation methods.
Completion states (watching-only, single account, no seed, etc) are handled inside classes.
"""
def __init__(self, storage):
self.storage = storage
self.electrum_version = ELECTRUM_VERSION
self.gap_limit_for_change = 6 # constant
# saved fields
self.seed_version = storage.get('seed_version', NEW_SEED_VERSION)
self.use_change = storage.get('use_change',True)
self.use_encryption = storage.get('use_encryption', False)
self.seed = storage.get('seed', '') # encrypted
self.labels = storage.get('labels', {})
self.frozen_addresses = set(storage.get('frozen_addresses',[]))
self.stored_height = storage.get('stored_height', 0) # last known height (for offline mode)
self.history = storage.get('addr_history',{}) # address -> list(txid, height)
self.fee_per_kb = int(storage.get('fee_per_kb', RECOMMENDED_FEE))
# This attribute is set when wallet.start_threads is called.
self.synchronizer = None
# imported_keys is deprecated. The GUI should call convert_imported_keys
self.imported_keys = self.storage.get('imported_keys',{})
self.load_accounts()
self.load_transactions()
self.build_reverse_history()
# load requests
self.receive_requests = self.storage.get('payment_requests', {})
# spv
self.verifier = None
# Transactions pending verification. Each value is the transaction height. Access with self.lock.
self.unverified_tx = {}
# Verified transactions. Each value is a (height, timestamp, block_pos) tuple. Access with self.lock.
self.verified_tx = storage.get('verified_tx3',{})
# there is a difference between wallet.up_to_date and interface.is_up_to_date()
# interface.is_up_to_date() returns true when all requests have been answered and processed
# wallet.up_to_date is true when the wallet is synchronized (stronger requirement)
self.up_to_date = False
self.lock = threading.Lock()
self.transaction_lock = threading.Lock()
self.tx_event = threading.Event()
self.check_history()
# save wallet type the first time
if self.storage.get('wallet_type') is None:
self.storage.put('wallet_type', self.wallet_type, True)
@profiler
def load_transactions(self):
self.txi = self.storage.get('txi', {})
self.txo = self.storage.get('txo', {})
self.pruned_txo = self.storage.get('pruned_txo', {})
tx_list = self.storage.get('transactions', {})
self.transactions = {}
for tx_hash, raw in tx_list.items():
tx = Transaction(raw)
self.transactions[tx_hash] = tx
if self.txi.get(tx_hash) is None and self.txo.get(tx_hash) is None and (tx_hash not in self.pruned_txo.values()):
print_error("removing unreferenced tx", tx_hash)
self.transactions.pop(tx_hash)
@profiler
def save_transactions(self):
with self.transaction_lock:
tx = {}
for k,v in self.transactions.items():
tx[k] = str(v)
# Flush storage only with the last put
self.storage.put('transactions', tx, False)
self.storage.put('txi', self.txi, False)
self.storage.put('txo', self.txo, False)
self.storage.put('pruned_txo', self.pruned_txo, True)
def clear_history(self):
with self.transaction_lock:
self.txi = {}
self.txo = {}
self.pruned_txo = {}
self.save_transactions()
with self.lock:
self.history = {}
self.tx_addr_hist = {}
self.storage.put('addr_history', self.history, True)
@profiler
def build_reverse_history(self):
self.tx_ |
deapplegate/wtgpipeline | OLDadam_THESIS_CRN_performance_metrics.py | Python | mit | 7,803 | 0.045752 | #! /usr/bin/env python
#adam-predecessor# this derives from adam_THESIS_CRN_number_of_masks.py
from matplotlib.pylab import *
import astropy
from glob import glob
import scipy.ndimage
import os
import pymorph
import skimage
from skimage import measure
from skimage import morphology
import mahotas
import sys ; sys.path.append('/u/ki/awright/InstallingSoftware/pythons')
from import_tools import *
conn8=array([[1,1,1],[1,1,1],[1,1,1]])
conn4=array([[0,1,0],[1,1,1],[0,1,0]])
connS=array([[0,1,1,0],[1,1,1,1],[1,1,1,1],[0,1,1,0]],dtype=bool)
from adam_quicktools_ArgCleaner import ArgCleaner
args=ArgCleaner(sys.argv)
print "args=", args
#/u/ki/awright/data/eyes/coadds-pretty_for_10_3_cr.2/
import pickle
fl=open('/u/ki/awright/thiswork/eyes/Prettys_info.2.1.pkl','rb')
Pinfo=pickle.load(fl) #CRbads[filter][CRnum]['CCDnum','weight_file','file','dark_file','CRtag'] only 'file' and 'CRtag' are useful here
fl.close()
import astropy.io.fits as pyfits
from adam_quicktools_header_key_add import add_key_val
CRfl='/u/ki/awright/thiswork/eyes/CRbads_info.2.1.pkl'
CRfo=open(CRfl)
CRinfo=pickle.load(CRfo)
CRfo.close()
#args=glob('/u/ki/awright/data/eyes/CRNitschke_output/data_SCIENCE_compare/BB_ERASED_*_3.fits')
#/u/ki/awright/data/eyes/CRNitschke_output/data_SCIENCE_cosmics/SEGMENTATION_CRN-cosmics_MACS0429-02_W-J-B.SUPA0154630_1.fits
tinput_dir='/nfs/slac/kipac/fs1/u/awright/eyes/eye-10_3_cr.2.1/W-C-RC/both/edge_out/inputs/'
toutput_dir='/nfs/slac/kipac/fs1/u/awright/eyes/eye-10_3_cr.2.1/W-C-RC/both/edge_out/outputs/'
OUTDIR="/u/ki/awright/my_data/thesis_stuff/CRN_final_purecomp/"
tinputfls=glob('/nfs/slac/kipac/fs1/u/awright/eyes/eye-10_3_cr.2.1/W-C-RC/both/edge_out/inputs/eye_CRnum[0-9]_Pnum*.fits')
tinputfls+=glob('/nfs/slac/kipac/fs1/u/awright/eyes/eye-10_3_cr.2.1/W-C-RC/both/edge_out/inputs/eye_CRnum1[0-9]_Pnum*.fits')
tinputfls+=glob('/nfs/slac/kipac/fs1/u/awright/eyes/eye-10_3_cr.2.1/W-C-RC/both/edge_out/inputs/eye_CRnum20_Pnum*.fits')
#tinputfls=glob(OUTDIR+'CRNmask_eye_CRnum0_Pnum*.fits')
compdir='/u/ki/awright/data/eyes/CRNitschke_output/data_SCIENCE_compare/'
alldir='/u/ki/awright/data/eyes/CRNitschke_output/data_SCIENCE_cosmics/'
time=[]
rms=[]
seeing=[]
CRN_Ntracks=[]
pure_mask_level=[]
pure_mask_overmask_frac=[]
comp_mask_level=[]
comp_pix_level=[]
for fl in tinputfls:
try:
flname=os.path.basename(fl).split('.')[0]
if 'OCF' in fl:
BASE=os.path.basename(fl).split('OCF')[0]
else:
BASE=flname
#CR_segfl=alldir+'SEGMENTATION_CRN-cosmics_'+fl.split('_BBCR_')[-1]
CR_segfl=OUTDIR+'OLDmask_'+BASE+".fits"
CRNfo=astropy.io.fits.open(CR_segfl)
CRNheader=CRNfo[0].header
CRN_seg=CRNfo[0].data
CRN_Nlabels=CRN_seg.max()
CRN_labels=arange(CRN_Nlabels)+1
CRN_mask=CRNfo[0].data>0
CRN_slices=scipy.ndimage.find_objects(CRN_seg)
CR_expsegfl=OUTDIR+'OLDmask_expanded_'+BASE+".fits"
CRNexpfo=astropy.io.fits.open(CR_expsegfl)
CRN_exp_mask=asarray(CRNexpfo[0].data,dtype=bool)
#print (CRN_exp_mask[truth]>0.0).mean()
tofl=toutput_dir+BASE+".fits"
tofo=astropy.io.fits.open(tofl)
toheader=tofo[0].header
toim=tofo[0].data
truth=tofo[0].data>0
#adam-tmp# put BB or BBSS in here depending on the final output
#CR_newsegfl=alldir+'SEGMENTATION_BBSS_CRN-cosmics_'+fl.split('_BBCR_')[-1]
#fo=astropy.io.fits.open(fl)
#fo=astropy.io.fits.open(fl)
tifo=astropy.io.fits.open(fl)
tiheader=tifo[0].header
tiim=tifo[0].data
true_seg,true_Nlabels=scipy.ndimage.label(truth,conn8)
true_labels=arange(true_Nlabels)+1
true_slices=scipy.ndimage.find_objects(true_seg)
CRN_exp_seg,CRN_exp_Nlabels=scipy.ndimage.label(CRN_exp_mask,conn8)
CRN_exp_labels=arange(CRN_exp_Nlabels)+1
CRN_exp_slices=scipy.ndimage.find_objects(CRN_exp_seg)
hits=[]
frac_necessarys=[]
for l in CRN_labels:
sl=CRN_slices[l-1]
spots=CRN_seg[sl]==l
true_spots=truth[sl]
true_at_CRNl=true_spots[spots]
hit=true_at_CRNl.any()
frac_necessary=true_at_CRNl.mean()
#lseg_num=spots.sum()
hits.append(hit)
frac_necessarys.append(frac_necessary)
CRNl_frac_true=array(frac_necessarys)
CRNl_hit=array(hits)
pure_mask=CRNl_hit.mean()
# true hit CRN?
thits=[]
tfrac_necessarys=[]
for l in true_labels:
sl=true_slices[l-1]
spots=true_seg[sl]==l
CRN_spots=CRN_exp_mask[sl]
CRN_at_truel=CRN_spots[spots]
thit=CRN_at_truel.any()
tfrac_necessary=CRN_at_truel.mean()
#lseg_num=spots.sum()
thits.append(thit)
tfrac_necessarys.append(tfrac_necessary)
truel_frac_CRN=array(tfrac_necessarys)
truel_hit=array(thits)
comp_mask=truel_hit.mean()
#fo=astropy.io.fits.open(CR_newsegfl)
#CRN_seg=fo[0].data
CRmasksN=CRN_seg.max()
CRpixN=(CRN_seg>0).sum()
comp_pix=(CRN_exp_mask[truth]>0.0).mean()
pure_pix=(truth[CRN_mask]>0.0).mean()
print comp_pix , pure_mask, pure_pix , CRN_exp_Nlabels,true_Nlabels,tiheader['MYSEEING'],tiheader['EXPTIME'],tiheader['MYRMS']
#fo=astropy.io.fits.open(CR_segfl)
#seginit=fo[0].data
#seginit.max()
#CRmasks0=seginit.max()
#CRpix0=(seginit>0).sum()
pure_mask_level.append(pure_mask)
pure_mask_overmask_frac.append(1-CRNl_frac_true.mean())
comp_mask_level.append(comp_mask)
comp_pix_level.append(comp_pix)
seeing.append(tiheader['MYSEEING'])
time.append(tiheader['EXPTIME'])
rms.append(tiheader['MYRMS'])
CRN_Ntracks.append(CRN_Nlabels)
except IOError as e:
print e
continue
ACRN_Ntracks=array(CRN_Ntracks)
Aseeing=array(seeing)
Arms=array(rms)
Apure_mask_level=array(pure_mask_level)
Acomp_mask_level=array(comp_mask_level)
Apure_mask_overmask_frac=array(pure_mask_overmask_frac)
Acomp_pix_level=array(comp_pix_level)
Atime=array(time)
ANmasksNrate=array(ACRN_Ntracks)/Atime
def seeing_binned(Aprop):
less_pt6=Aprop[Aseeing<=0.6]
pt6_to_pt7=Aprop[(Aseeing>0.6) * (Aseeing<0.7)]
great_pt7=Aprop[Aseeing>=0.7]
print '<=0.6:',less_pt6.mean()
print '0.6<seeing<0.7:',pt6_to_pt7.mean()
print '>=0.7:',great_pt7.mean()
return round(less_pt6.mean(),2),round(pt6_to_pt7.mean(),2),round(great_pt7.mean(),2)
print '\n# purity at mask level:'
pure=seeing_binned(Apure_mask_level)
print '\n# overmasking by this amount on average:'
om=seeing_binned(Apure_mask_overmask_frac)
print '\n# completeness at mask level :'
compm=seeing_binned(Acomp_mask_level)
print '\n# completeness at pixel level :'
compp=seeing_binned(Acomp_pix_level)
print '\nCRN masks per exptime:'
Nmask=seeing_binned(ANmasks | Nrate)
|
seeings=['seeing<=0.6','0.6<seeing<0.7','seeing>=0.7']
import astropy.table as tbl
Seeings=['Seeing$\leq 0\\arcsecf6$','$0\\arcsecf6<$Seeing$<0\\arcsecf7$','Seeing$\geq0\\arcsecf7$']
tab=tbl.Table(data=[Seeings , pure, compp , compm ],names=['Seeing Range','Purity per mask','Completeness per pixel','Completeness per mask'])
#tab=tbl.Table(data=[Seeings , pure, compp , compm , om ],names=['Seeing Range','Purity at mask level','Completeness at pixel level','Completeness at mask level', 'Frac. Mask Outside'])
tab.write('OLD_table.tex',format='latex',overwrite=True)
## for BB masks:
# masks, 0 and N:
#<=0.6: 1041.33333333
#0.6<seeing<0.7: 1074.14516129
#>=0.7: 779.873786408
#<=0.6: 593.855072464
#0.6<seeing<0.7: 561.225806452
#>=0.7: 353.32038835
## pixels, 0 and N:
#<=0.6: 11096.8985507
#0.6<seeing<0.7: 13478.0
#>=0.7: 9933.27184466
#<=0.6: 22824.4202899
#0.6<seeing<0.7: 26138.3870968
#>=0.7: 18999.7378641
#mask rate:
#<=0.6: 3.49563607085
#0.6<seeing<0.7: 2.98745519713
#>=0.7: 1.69027777778
## for BB masks:
#mask-pixels rate at 0:
#<=0.6: 65.8068639291
#0.6<seeing<0.7: 71.0849171147
#>=0.7: 47.9930690399
#mask-pixels rate at N:
#<=0.6: 134.256549919
#0.6<seeing<0.7: 136.891610663
#>=0.7: 90.5776240561
## for BBSS masks:
#mask-pixels rate at 0:
#<=0.6: 65.8068639291
#0.6<seeing<0.7: 71.0849171147
#>=0.7: 47.9930690399
#mask-pixels rate at N:
#<=0.6: 102.991151369
#0.6<seeing<0.7: 114.216966846
#>=0.7: 86.5826941748
|
LarsDu/DeepNucDecomp | scripts/ExtractGff3.py | Python | gpl-3.0 | 962 | 0.017672 | import gflags
import sys
import os
#Go one directory up and append to path to access the deepdna packa | ge
#The following statement is equiv to sys.path.append("../")
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__),os.path.pardir)))
FLAGS = gflags.FLAGS
gflags.DEFINE_string('genome_file','',"""A genome reference file in fasta format""")
gflags.DEFINE_string('gff3_file','',"""GFF3 annotation file""")
gflags.DEFINE_string('feature','',"""The feature to extract from a given genome""")
gflags.DEFINE_string('output','',"""The output format. Can b | e""")
def main(argv):
#Parse gflags
try:
py_file = FLAGS(argv) # parse flags
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, sys.argv[0], FLAGS)
sys.exit(1)
test_parser = Gff3Parser(FLAGS.gff3_file,FLAGS.feature)
for _ in range(20):
print test_parser.next()['start']
if __name__ == "__main__":
main()
|
FedoraScientific/salome-paravis | test/VisuPrs/Vectors/A0.py | Python | lgpl-2.1 | 1,491 | 0.002683 | # Copyright (C) 2010-2014 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at yo | ur option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
| # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
# This case corresponds to: /visu/Vectors/A0 case
# Create Vectors for all data of the given MED file
import sys
from paravistest import datadir, pictureext, get_picture_dir
from presentations import CreatePrsForFile, PrsTypeEnum
import pvserver as paravis
# Create presentations
myParavis = paravis.myParavis
# Directory for saving snapshots
picturedir = get_picture_dir("Vectors/A0")
file = datadir + "fra.med"
print " --------------------------------- "
print "file ", file
print " --------------------------------- "
print "CreatePrsForFile..."
CreatePrsForFile(myParavis, file, [PrsTypeEnum.VECTORS], picturedir, pictureext)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.