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 |
|---|---|---|---|---|---|---|---|---|
geekosphere/zgeist | test/routes/test_frontend.py | Python | agpl-3.0 | 715 | 0.005594 | """
Test Frontend
"""
import json
from nose.tools import *
from datetime import date | time
from zg.error import NotFound |
from zg.objects import Item, Tag
from zg.objects.event import EventRecorder
from zg.app import app
def test_index():
with app.test_client() as client:
rv = client.get('/')
assert_in('/upload', rv.headers['Location'])
def test_upload():
with app.test_client() as client:
rv = client.get('/upload')
assert_in('<form', rv.data)
def test_suggest():
Tag.create(name='my partial tag')
with app.test_client() as client:
resp = client.get('/tag/suggest?q=partial')
assert_equals(dict(tags=['my partial tag']), json.loads(resp.data))
|
midokura/python-midonetclient | script/remove-tags.py | Python | apache-2.0 | 519 | 0.009634 | #!/usr/bin/env python
from midonetclient.api import MidonetApi
import sys
def main():
mn_uri = 'http://localhost:8081'
my_laptop = 'c1b9eb8a-c83b-43d3-b7b8-8613f921dbe7'
mc = MidonetApi(mn_uri, 'admin', 'password')
bridges = mc.get_bridges({'tenant_id': my_laptop})
for bridge in bridges:
print("Bridge %s" % bridge.get_id())
tags = bridge.get_tags()
for tag in tags:
| print("Deleting tag: %s" % tag.get_tag())
tag.delet | e()
if __name__ == '__main__':
main()
|
papedaniel/oioioi | oioioi/gamification/profile.py | Python | gpl-3.0 | 1,330 | 0.002256 | from django.template.loader import render_to_string
from oioioi.base.menu import OrderedRegistry
from oioioi.gamification.friends import UserFriends
profile_registry = OrderedRegistry()
def profile_section(order):
""" Decorator for registering profile view sections.
The decorat | ed function is passed the request and shown user.
It may return a string, a TemplateResponse or HttpResponseRedirect.
"""
return profile_registry.register_decorator(order)
@profile_section(order=80)
def friend_finder_section( | request, user):
if user != request.user:
return ''
return render_to_string('gamification/profile/invite-friends.html')
@profile_section(order=90)
def invite_list_section(request, user):
if user != request.user:
return ''
requests = UserFriends(user).requests_for_me\
.select_related('sender__user')
if not requests.exists():
return ''
senders = (r.sender.user for r in requests.all())
return render_to_string('gamification/profile/invites-list.html',
{'users': senders})
@profile_section(order=100)
def friend_list_section(request, user):
if user != request.user:
return ''
return render_to_string('gamification/profile/friends-list.html',
{'users': UserFriends(user).friends})
|
Accent-/WasedaU_Library | wine.py | Python | mit | 1,004 | 0.004202 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import json
import tim | e
def keys(filename):
with open(filename) as f:
secret_keys = json.load(f)
return secret_keys
def access_listpage(secret_keys, driver):
driver.get("https://wine.wul.waseda.ac.jp/patroninfo*jpn")
time.sleep(5)
elem = | driver.find_element_by_name("extpatid")
elem.send_keys(secret_keys["user"])
elem2 = driver.find_element_by_name("extpatpw")
elem2.send_keys(secret_keys["pw"])
submit = driver.find_element_by_link_text("送信")
submit.click()
time.sleep(5)
list_all = driver.find_element_by_partial_link_text("貸出中です")
list_all.click()
time.sleep(5)
def send_extension(driver):
"""
前提:借りている書籍のリストにいること
"""
driver.find_element_by_name("requestRenewAll").click()
time.sleep(5)
driver.find_element_by_name("renewall").click()
time.sleep(5)
|
MOA-2011/enigma2-plugin-extensions-openwebif | plugin/controllers/views/ajax/satellites.py | Python | gpl-2.0 | 5,571 | 0.013104 | #!/usr/bin/env python
##################################################
## DEPENDENCIES
import sys
import os
import os.path
try:
import builtins as builtin
except ImportError:
import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion
from Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTuple
from Cheetah.Template import Template
from Cheetah.DummyTransaction import *
from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList
from Cheetah.CacheRegion import CacheRegion
import Cheetah.Filters as Filters
import Cheetah.ErrorCatchers as ErrorCatchers
from urllib import quote
from Plugins.Extensions.OpenWebif.local import tstrings
##################################################
## MODULE CONSTANTS
VFFSL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '2.4.4'
__CHEETAH_versionTuple__ = (2, 4, 4, 'development', 0)
__CHEETAH_genTime__ = 1406885499.299002
__CHEETAH_genTimestamp__ = 'Fri Aug 1 18:31:39 2014'
__CHEETAH_src__ = '/home/wslee2/models/5-wo/force1plus/openpli3.0/build-force1plus/tmp/work/mips32el-oe-linux/enigma2-plugin-extensions-openwebif-1+git5+3c0c4fbdb28d7153bf2140459b553b3d5cdd4149-r0/git/plugin/controlle | rs/views/ajax/satellites.tmpl'
__CHEETAH_srcLastModified__ = 'Fri Aug 1 18:30:05 2014'
__CHEETAH_docstring__ = 'Autogenerated by Cheetah: The Python-Powered Template Engine'
if __CHEETAH_versionTuple__ < | RequiredCheetahVersionTuple:
raise AssertionError(
'This template was compiled with Cheetah version'
' %s. Templates compiled before version %s must be recompiled.'%(
__CHEETAH_version__, RequiredCheetahVersion))
##################################################
## CLASSES
class satellites(Template):
##################################################
## CHEETAH GENERATED METHODS
def __init__(self, *args, **KWs):
super(satellites, self).__init__(*args, **KWs)
if not self._CHEETAH__instanceInitialized:
cheetahKWArgs = {}
allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split()
for k,v in KWs.items():
if k in allowedKWs: cheetahKWArgs[k] = v
self._initCheetahInstance(**cheetahKWArgs)
def respond(self, trans=None):
## CHEETAH: main method generated for this template
if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
trans = self.transaction # is None unless self.awake() was called
if not trans:
trans = DummyTransaction()
_dummyTrans = True
else: _dummyTrans = False
write = trans.response().write
SL = self._CHEETAH__searchList
_filter = self._CHEETAH__currentFilter
########################################
## START - generated method body
write(u'''<script>
$(function() { InitAccordeon("#accordionS");});
</script>
<div id="accordionS">
''')
for satellite in VFFSL(SL,"satellites",True): # generated from line 7, col 1
write(u'''\t<h1><a href="#" id="ajax/channels?id=''')
_v = VFFSL(SL,"quote",False)(VFFSL(SL,"satellite.service",True)) # u'$quote($satellite.service)' on line 8, col 39
if _v is not None: write(_filter(_v, rawExpr=u'$quote($satellite.service)')) # from line 8, col 39.
write(u'''&stype=''')
_v = VFFSL(SL,"stype",True) # u'$stype' on line 8, col 72
if _v is not None: write(_filter(_v, rawExpr=u'$stype')) # from line 8, col 72.
write(u'''">''')
_v = VFFSL(SL,"satellite.name",True) # u'$satellite.name' on line 8, col 80
if _v is not None: write(_filter(_v, rawExpr=u'$satellite.name')) # from line 8, col 80.
write(u'''</a></h1>
<div>
''')
_v = VFFSL(SL,"tstrings",True)['loading'] # u"$tstrings['loading']" on line 10, col 1
if _v is not None: write(_filter(_v, rawExpr=u"$tstrings['loading']")) # from line 10, col 1.
write(u''' ...
\t</div>
''')
write(u'''</div>''')
########################################
## END - generated method body
return _dummyTrans and trans.response().getvalue() or ""
##################################################
## CHEETAH GENERATED ATTRIBUTES
_CHEETAH__instanceInitialized = False
_CHEETAH_version = __CHEETAH_version__
_CHEETAH_versionTuple = __CHEETAH_versionTuple__
_CHEETAH_genTime = __CHEETAH_genTime__
_CHEETAH_genTimestamp = __CHEETAH_genTimestamp__
_CHEETAH_src = __CHEETAH_src__
_CHEETAH_srcLastModified = __CHEETAH_srcLastModified__
_mainCheetahMethod_for_satellites= 'respond'
## END CLASS DEFINITION
if not hasattr(satellites, '_initCheetahAttributes'):
templateAPIClass = getattr(satellites, '_CHEETAH_templateClass', Template)
templateAPIClass._addCheetahPlumbingCodeToClass(satellites)
# CHEETAH was developed by Tavis Rudd and Mike Orr
# with code, advice and input from many other volunteers.
# For more information visit http://www.CheetahTemplate.org/
##################################################
## if run from command line:
if __name__ == '__main__':
from Cheetah.TemplateCmdLineIface import CmdLineIface
CmdLineIface(templateObj=satellites()).run()
|
werkzeuge/gimp-plugins-simplest | bdfix.py | Python | mit | 2,693 | 0.025871 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# см. также http://habrahabr.ru/post/135863/
# "Как написать дополнение для GIMP на языке Python"
# Импортируем необходимые модули
from gimpfu import *
## fix
def bdfix(image, drawable, w0, c0, w1, c1):
# for Undo
pdb.gimp_context_push()
pdb.gimp_image_undo_group_start(image)
# border-0
pdb.gimp_image_resize(image, image.width + w0*2, image.height + w0*2, w0, w0)
cz = pdb.gimp_context_get_background()
pdb.gimp_context_set_background(c0)
pdb.gimp_image_flatten(image)
pdb.gimp_context_set_background(cz)
# border-1
pdb.gimp_image_resize(image, image.width + w1*2, image.height + w1*2, w1, w1)
cz = pdb.gimp_context_get_background()
pdb.gimp_context_set_background(c1)
pdb.gimp_image_flatten(image)
pdb.gimp_context_set_background(cz)
# Refresh
pdb.gimp_displays_flush()
# Undo
pdb.gimp_image_undo_group_end(image)
pdb.gimp_context_pop()
# | Регистрируем функцию в PDB
register(
"python-fu-bdfix", # Имя регистрируемой функции
"Добавление рамки к изображению", # Информация о дополнении
"Помещает вокруг изображения рамку", # Короткое описание выполняемых скриптом дейст | вий
"Александр Лубягин", # Информация об авторе
"Александр Лубягин", # Информация о правах
"15.01.2015", # Дата изготовления
"Добавить рамку", # Название пункта меню, с помощью которого дополнение будет запускаться
"*", # Типы изображений, с которыми работает дополнение
[
(PF_IMAGE, "image", "Исходное изображение", None), # Указатель на изображение
(PF_DRAWABLE, "drawable", "Исходный слой", None), # Указатель на слой
(PF_INT, "w0", "Ширина рамки, px", "9"), # Ширина рамки
(PF_COLOR, "c0", "Цвет рамки", (255,255,255)), # Цвет рамки
(PF_INT, "w1", "Ширина рамки, px", "1"), # Ширина рамки
(PF_COLOR, "c1", "Цвет рамки", (0,0,0)) # Цвет рамки
],
[], # Список переменных которые вернет дополнение
bdfix, menu="<Image>/ТЕСТ/") # Имя исходной функции, и меню, в которое будет помещён пункт
# Запускаем скрипт
main()
|
kalaspuff/tomodachi | tomodachi/envelope/__init__.py | Python | mit | 1,527 | 0.00262 | from typing import Any, Dict, Tuple, U | nion
__cached_defs: Dict[str, Any] = {}
def __getattr__(name: str) -> Any:
import importlib # noqa # isort:skip
if name in __cached_defs:
return __cached_defs[name]
if name == "JsonBase":
module = importlib.import_module(".json_bas | e", "tomodachi.envelope")
elif name == "ProtobufBase":
try:
module = importlib.import_module(".protobuf_base", "tomodachi.envelope")
except Exception: # pragma: no cover
class ProtobufBase(object):
@classmethod
def validate(cls, **kwargs: Any) -> None:
raise Exception("google.protobuf package not installed")
@classmethod
async def build_message(cls, service: Any, topic: str, data: Any, **kwargs: Any) -> str:
raise Exception("google.protobuf package not installed")
@classmethod
async def parse_message(
cls, payload: str, proto_class: Any = None, validator: Any = None, **kwargs: Any
) -> Union[Dict, Tuple]:
raise Exception("google.protobuf package not installed")
__cached_defs[name] = ProtobufBase
return __cached_defs[name]
else:
raise AttributeError("module 'tomodachi.envelope' has no attribute '{}'".format(name))
__cached_defs[name] = getattr(module, name)
return __cached_defs[name]
__all__ = ["JsonBase", "ProtobufBase"]
|
hail-is/hail | hail/python/hailtop/__init__.py | Python | mit | 332 | 0.003012 | _VE | RSION = None
def version() -> str:
global _VERSION
if _VERSION is None:
import pkg_resources # pylint: disable=import-outside-toplevel
_VERSION = pkg_resources.resource_string(__name__, 'hail_version').decode().strip()
return _VERSION
def pip_version() -> str:
return vers | ion().split('-')[0]
|
OpenDaisy/daisy-api | daisy/search/api/v0_1/search.py | Python | apache-2.0 | 13,617 | 0 | # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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
from oslo.config import cfg
from oslo_log import log as logging
import six
import webob.exc
from daisy.api import policy
from daisy.common import exception
from daisy.common import utils
from daisy.common import wsgi
import daisy.db
import daisy.gateway
from daisy import i18n
import daisy.notifier
import daisy.schema
LOG = logging.getLogger(__name__)
_ = i18n._
_LE = i18n._LE
CONF = cfg.CONF
class SearchController(object):
def __init__(self, plugins=None, es_api=None, policy_enforcer=None):
self.es_api = es_api or daisy.search.get_api()
self.policy = policy_enforcer or p | olicy.Enforcer()
self.gateway = daisy.gateway.Gateway(
es_api=self.es_api,
policy_enforcer=self.policy)
self.plugins = plugins or []
def search(self, req, query, index, doc_type=None, fie | lds=None, offset=0,
limit=10):
if fields is None:
fields = []
try:
search_repo = self.gateway.get_catalog_search_repo(req.context)
result = search_repo.search(index,
doc_type,
query,
fields,
offset,
limit,
True)
for plugin in self.plugins:
result = plugin.obj.filter_result(result, req.context)
return result
except exception.Forbidden as e:
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
raise webob.exc.HTTPInternalServerError()
def plugins_info(self, req):
try:
search_repo = self.gateway.get_catalog_search_repo(req.context)
return search_repo.plugins_info()
except exception.Forbidden as e:
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
raise webob.exc.HTTPInternalServerError()
def index(self, req, actions, default_index=None, default_type=None):
try:
search_repo = self.gateway.get_catalog_search_repo(req.context)
success, errors = search_repo.index(
default_index,
default_type,
actions)
return {
'success': success,
'failed': len(errors),
'errors': errors,
}
except exception.Forbidden as e:
raise webob.exc.HTTPForbidden(explanation=e.msg)
except exception.NotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.msg)
except exception.Duplicate as e:
raise webob.exc.HTTPConflict(explanation=e.msg)
except Exception as e:
LOG.error(utils.exception_to_str(e))
raise webob.exc.HTTPInternalServerError()
class RequestDeserializer(wsgi.JSONRequestDeserializer):
_disallowed_properties = ['self', 'schema']
def __init__(self, plugins, schema=None):
super(RequestDeserializer, self).__init__()
self.plugins = plugins
def _get_request_body(self, request):
output = super(RequestDeserializer, self).default(request)
if 'body' not in output:
msg = _('Body expected in request.')
raise webob.exc.HTTPBadRequest(explanation=msg)
return output['body']
@classmethod
def _check_allowed(cls, query):
for key in cls._disallowed_properties:
if key in query:
msg = _("Attribute '%s' is read-only.") % key
raise webob.exc.HTTPForbidden(explanation=msg)
def _get_available_indices(self):
return list(set([p.obj.get_index_name() for p in self.plugins]))
def _get_available_types(self):
return list(set([p.obj.get_document_type() for p in self.plugins]))
def _validate_index(self, index):
available_indices = self._get_available_indices()
if index not in available_indices:
msg = _("Index '%s' is not supported.") % index
raise webob.exc.HTTPBadRequest(explanation=msg)
return index
def _validate_doc_type(self, doc_type):
available_types = self._get_available_types()
if doc_type not in available_types:
msg = _("Document type '%s' is not supported.") % doc_type
raise webob.exc.HTTPBadRequest(explanation=msg)
return doc_type
def _validate_offset(self, offset):
try:
offset = int(offset)
except ValueError:
msg = _("offset param must be an integer")
raise webob.exc.HTTPBadRequest(explanation=msg)
if offset < 0:
msg = _("offset param must be positive")
raise webob.exc.HTTPBadRequest(explanation=msg)
return offset
def _validate_limit(self, limit):
try:
limit = int(limit)
except ValueError:
msg = _("limit param must be an integer")
raise webob.exc.HTTPBadRequest(explanation=msg)
if limit < 1:
msg = _("limit param must be positive")
raise webob.exc.HTTPBadRequest(explanation=msg)
return limit
def _validate_actions(self, actions):
if not actions:
msg = _("actions param cannot be empty")
raise webob.exc.HTTPBadRequest(explanation=msg)
output = []
allowed_action_types = ['create', 'update', 'delete', 'index']
for action in actions:
action_type = action.get('action', 'index')
document_id = action.get('id')
document_type = action.get('type')
index_name = action.get('index')
data = action.get('data', {})
script = action.get('script')
if index_name is not None:
index_name = self._validate_index(index_name)
if document_type is not None:
document_type = self._validate_doc_type(document_type)
if action_type not in allowed_action_types:
msg = _("Invalid action type: '%s'") % action_type
raise webob.exc.HTTPBadRequest(explanation=msg)
elif (action_type in ['create', 'update', 'index'] and
not any([data, script])):
msg = (_("Action type '%s' requires data or script param.") %
action_type)
raise webob.exc.HTTPBadRequest(explanation=msg)
elif action_type in ['update', 'delete'] and not document_id:
msg = (_("Action type '%s' requires ID of the document.") %
action_type)
raise webob.exc.HTTPBadRequest(explanation=msg)
bulk_action = {
'_op_type': action_type,
'_id': document_id,
'_index': index_name,
'_type': document_type,
}
if script:
data_field = 'params'
bulk_action['script'] = script
elif action_type == 'update':
|
rebost/django | django/conf/project_template/project_name/settings.py | Python | bsd-3-clause | 5,206 | 0.001537 | # Django settings for {{ project_name }} project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', | # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating sys | tems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '{{ secret_key }}'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = '{{ project_name }}.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = '{{ project_name }}.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
|
Rudde/pyroscope | pyroscope/pyroscope/controllers/error.py | Python | gpl-2.0 | 1,655 | 0.001813 | import cgi
from paste.urlparser import PkgResourcesParser
from pylons import request
from pylons.controllers.util import forward
from pylons.middleware import error_document_template
from webhelpers.html.builder import literal
from pyroscope.lib.base import BaseController
class ErrorController(BaseController):
""" Generates error documents as and when they are required.
The ErrorDocuments middleware forwards to ErrorController when error
related status codes are returned from the application.
This behaviour can be altered by changing the parameters to the
ErrorDocuments middleware in your config/middleware.py file.
"""
def document(self):
"""Render the error document"""
resp = request.environ.get('pylons.original_response')
content = literal(resp.body) or cgi.escape(request.GET.get('message', ''))
page = error_document_template % \
dict(prefix=request.environ.get('SCRIPT_NAME', ''),
code=cgi.escape(request.GET.get('code', str(resp.status_int))),
message=content)
r | eturn page
def img(self, id):
"""Serve Pylons' stock images"""
return self._ser | ve_file('/'.join(['media/img', id]))
def style(self, id):
"""Serve Pylons' stock stylesheets"""
return self._serve_file('/'.join(['media/style', id]))
def _serve_file(self, path):
""" Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
"""
request.environ['PATH_INFO'] = '/%s' % path
return forward(PkgResourcesParser('pylons', 'pylons'))
|
anhstudios/swganh | data/scripts/templates/object/draft_schematic/droid/component/shared_advanced_droid_frame.py | Python | mit | 465 | 0.047312 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR | EXAMPLES
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/droid/component/shared_advanced_droid_frame.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICAT | IONS ####
return result |
markruys/gw2pvo | gw2pvo/pvo_api.py | Python | mit | 3,200 | 0.005 | import logging
import time
import requests
__author__ = "Mark Ruys"
__copyright__ = "Copyright 2017, Mark Ruys"
__license__ = "MIT"
__email__ = "mark@paracas.nl"
class PVOutputApi:
def __init__(self, system_id, api_key):
self.m_system_id = system_id
self.m_api_key = api_key
def add_status(self, pgrid_w, eday_kwh, temperature, voltage):
t = time.localtime()
payload = {
'd' : "{:04}{:02}{:02}".format(t.tm_year, t.tm_mon, t.tm_mday),
't' : "{:02}:{:02}".format(t.tm_hour, t.tm_min),
'v1' : round(eday_kwh * 1000),
'v2' : round(pgrid_w)
| }
if temperature is not None:
payload['v5'] = temperature
if voltage is not None:
payload['v6'] = voltage
self | .call("https://pvoutput.org/service/r2/addstatus.jsp", payload)
def add_day(self, data, temperatures):
# Send day data in batches of 30.
for chunk in [ data[i:i + 30] for i in range(0, len(data), 30) ]:
readings = []
for reading in chunk:
dt = reading['dt']
fields = [
dt.strftime('%Y%m%d'),
dt.strftime('%H:%M'),
str(round(reading['eday_kwh'] * 1000)),
str(reading['pgrid_w'])
]
if temperatures is not None:
fields.append('')
fields.append('')
temperature = list(filter(lambda x: dt.timestamp() > x['time'], temperatures))[-1]
fields.append(str(temperature['temperature']))
readings.append(",".join(fields))
payload = {
'data' : ";".join(readings)
}
self.call("https://pvoutput.org/service/r2/addbatchstatus.jsp", payload)
def call(self, url, payload):
logging.debug(payload)
headers = {
'X-Pvoutput-Apikey' : self.m_api_key,
'X-Pvoutput-SystemId' : self.m_system_id,
'X-Rate-Limit': '1'
}
for i in range(1, 4):
try:
r = requests.post(url, headers=headers, data=payload, timeout=10)
if 'X-Rate-Limit-Reset' in r.headers:
reset = round(float(r.headers['X-Rate-Limit-Reset']) - time.time())
else:
reset = 0
if 'X-Rate-Limit-Remaining' in r.headers:
if int(r.headers['X-Rate-Limit-Remaining']) < 10:
logging.warning("Only {} requests left, reset after {} seconds".format(
r.headers['X-Rate-Limit-Remaining'],
reset))
if r.status_code == 403:
logging.warning("Forbidden: " + r.reason)
time.sleep(reset + 1)
else:
r.raise_for_status()
break
except requests.exceptions.RequestException as arg:
logging.warning(r.text or str(arg))
time.sleep(i ** 3)
else:
logging.error("Failed to call PVOutput API")
|
xenoxaos/pithos | pithos/pithosconfig.py | Python | gpl-3.0 | 2,682 | 0.008576 | # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*-
### BEGIN LICENSE
# Copyright (C) 2010-2012 Kevin Mehall <km@kevinmehall.net>
#This program is free software: you can redistribute it and/or modify it
#under the terms of the GNU General 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 warranties of
#MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
#PURPOSE. See the GNU General Public License for more details.
#
#You should have received a c | opy of the GNU General Public License along
#with this program. If not, see <http://www.gnu.org/licenses/>.
### END LICENSE |
# where your project will head for your data (for instance, images and ui files)
# by default, this is data, relative your trunk layout
__pithos_data_directory__ = 'data/'
__license__ = 'GPL-3'
VERSION = '1.1.1'
import os
class project_path_not_found(Exception):
pass
ui_files = {
'about': 'AboutPithosDialog.ui',
'preferences': 'PreferencesPithosDialog.ui',
'search': 'SearchDialog.ui',
'stations': 'StationsDialog.ui',
'main': 'PithosWindow.ui',
'menu': 'app_menu.ui'
}
media_files = {
'icon': 'icon.svg',
'rate': 'rate_bg.png',
'album': 'album_default.png'
}
def get_media_file(name):
media = os.path.join(getdatapath(), 'media', media_files[name])
if not os.path.exists(media):
media = None
return media
def get_ui_file(name):
ui_filename = os.path.join(getdatapath(), 'ui', ui_files[name])
if not os.path.exists(ui_filename):
ui_filename = None
return ui_filename
def get_data_file(*path_segments):
"""Get the full path to a data file.
Returns the path to a file underneath the data directory (as defined by
`get_data_path`). Equivalent to os.path.join(get_data_path(),
*path_segments).
"""
return os.path.join(getdatapath(), *path_segments)
def getdatapath():
"""Retrieve pithos data path
This path is by default <pithos_lib_path>/../data/ in trunk
and /usr/share/pithos in an installed version but this path
is specified at installation time.
"""
# get pathname absolute or relative
if __pithos_data_directory__.startswith('/'):
pathname = __pithos_data_directory__
else:
pathname = os.path.dirname(__file__) + '/' + __pithos_data_directory__
abs_data_path = os.path.abspath(pathname)
if os.path.exists(abs_data_path):
return abs_data_path
else:
raise project_path_not_found
if __name__=='__main__':
print(VERSION)
|
cbednarski/ifs-python | ifs/source/nginx.py | Python | isc | 644 | 0 | version = '1.10.0'
version_cmd = 'nginx -v'
depends = ['buil | d-essential', 'libpcre3-dev', 'zlib1g-dev', 'libssl-dev']
download_url = 'http://nginx.org/download/nginx-VERSION.tar.gz'
install_script = """
tar -xzf nginx-VERSION.tar.gz
cd nginx-VERSION/
./configure \
--with-http_ssl_module \
--with-http_auth_request_module \
| --prefix=/etc/nginx \
--conf-path=/etc/nginx/nginx.conf \
--sbin-path=/usr/sbin/nginx \
--pid-path=/var/run/nginx.pid \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log
make
make install
mkdir -p /etc/nginx/sites-enabled
chmod -R 0700 /etc/nginx
"""
|
its-dirg/Flask-pyoidc | tests/test_redirect_uri_config.py | Python | apache-2.0 | 1,687 | 0.003557 | import pytest
from flask_pyoidc.redirect_uri_config import RedirectUriConfig
class TestRedirectUriConfig(object):
LEGACY_CONFIG = {'SERVER_NAME': 'example.com', 'PREFERRED_URL_SCHEME': ' | http'}
def test_legacy_config_defaults(self):
config = RedirectUriConfig.from_config(self.LEGACY_CONFIG)
assert config.endpoint == 'redirect_uri'
assert config.full_uri == 'http://example.com/redirect_uri'
def test_legacy_config_endpoint(self):
config = RedirectUriConfig.from_config({'OIDC_REDIRECT_ENDPOINT': '/foo', **self. | LEGACY_CONFIG})
assert config.endpoint == 'foo'
def test_legacy_config_domain(self):
config = {
'OIDC_REDIRECT_DOMAIN': 'other.example.com:6000', # should be preferred over SERVER_NAME
**self.LEGACY_CONFIG
}
redirect_uri_config = RedirectUriConfig.from_config(config)
assert redirect_uri_config.full_uri == 'http://other.example.com:6000/redirect_uri'
def test_redirect_uri_config(self):
config = {
'OIDC_REDIRECT_URI': 'https://myexample.com:6000/callback', # should be preferred over all other config
'OIDC_REDIRECT_DOMAIN': 'other.example.com:6000',
**self.LEGACY_CONFIG
}
redirect_uri_config = RedirectUriConfig.from_config(config)
assert redirect_uri_config.full_uri == 'https://myexample.com:6000/callback'
assert redirect_uri_config.endpoint == 'callback'
def test_should_raise_if_missing_all_config(self):
with pytest.raises(ValueError) as exc_info:
RedirectUriConfig.from_config({})
assert 'OIDC_REDIRECT_URI' in str(exc_info.value)
|
wmles/scholarium | Scholien/migrations/0002_auto_20170225_1111.py | Python | bsd-2-clause | 552 | 0.001812 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-02-25 11:11
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Scholien', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='artikel',
options={'ordering': ['-datum_publizieren'], 'verbose_name_plural': 'Artikel'},
),
| migrations.RemoveField(
model_name='artikel',
name | ='titel',
),
]
|
Laurawly/tvm-1 | tests/python/driver/tvmc/test_model.py | Python | apache-2.0 | 2,481 | 0.000806 | # 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 Apach | e 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 pytest
import os
from os import path
from tvm.driver import tvmc
from tvm.driver.tvmc.model import TVMCModel, TVMCPackage, TVMCResult
from tvm.runtime.module import BenchmarkResult
def test_tvmc_workflow(keras_simple):
pytest.importorskip("tensorflow")
tvmc_model = tvmc.load(keras_simple)
tuning_records = tvmc.tune(tvmc_model, target="llvm", enable_autoscheduler=True, trials=2)
tvmc_package = tvmc.compile(tvmc_model, tuning_records=tuning_records, target="llvm")
result = tvmc.run(tvmc_package, device="cpu")
assert type(tvmc_model) is TVMCModel
assert type(tvmc_package) is TVMCPackage
assert type(result) is TVMCResult
assert path.exists(tuning_records)
assert type(result.outputs) is dict
assert type(result.times) is BenchmarkResult
assert "output_0" in result.outputs.keys()
def test_save_load_model(keras_simple, tmpdir_factory):
pytest.importorskip("onnx")
tmpdir = tmpdir_factory.mktemp("data")
tvmc_model = tvmc.load(keras_simple)
# Create tuning artifacts
tvmc.tune(tvmc_model, target="llvm", trials=2)
# Create package artifacts
tvmc.compile(tvmc_model, target="llvm")
# Save the model to disk
model_path = os.path.join(tmpdir, "saved_model.tar")
tvmc_model.save(model_path)
# Load the model into a new TVMCModel
new_tvmc_model = TVMCModel(model_path=model_path)
# Check that the two models match.
assert str(new_tvmc_model.mod) == str(tvmc_model.mod)
# Check that tuning records and the compiled package are recoverable.
assert path.exists(new_tvmc_model.default_package_path())
assert path.exists(new_tvmc_model.default_tuning_records_path())
|
Sarvatt/backports | lib/bpgpg.py | Python | gpl-2.0 | 625 | 0.008 | import subprocess | , os
class GpgError(Exception):
pass
class ExecutionError(GpgError):
def __init__(self, errcode):
self.error_code = errcode
def sign(input_file, extra_args=[]):
cmd = ['gpg', '--sign']
cmd.extend(extra_args)
cmd.append(input_file)
process = subprocess.Popen(cmd,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
close_fds=True, | universal_newlines=True)
stdout = process.communicate()[0]
process.wait()
if process.returncode != 0:
raise ExecutionError(process.returncode)
return stdout
|
gmfrasca/pointstreak-groupme | psgroupme/util/encode_strings.py | Python | gpl-3.0 | 337 | 0 | def encode_strings(data):
if isinstance(data, str):
| return str(data)
elif isinstance(data, list):
return [encode_strings(x) for x in data]
elif isinstance(data, dict):
res = {}
for k, v in data.items():
res[encode_strings(k)] = | encode_strings(v)
return res
return data
|
cr/fxos-certsuite | web-platform-tests/tests/eventsource/resources/cors-cookie.py | Python | mpl-2.0 | 1,220 | 0.003279 | from datetime import datetime
def main(request, response):
last_event_id = request.headers.get("Last-Event-Id", "")
ident = request.GET.first('ident', "test")
cookie = "COOKIE" if ident in request.cookies else "NO_COOKIE"
origin = request.GET.first('origin', request.headers["origin"])
credentials = request.GET.first('credentials', 'true')
headers = []
if origin != 'none':
headers.append(("Access-Control-Allow-Origin", origin));
if credentials != 'none':
headers.append(("Access-Control-Allow-Credentials", credentials));
if last_event_id == '':
hea | ders.append(("Content-Type", "text/event-stream"))
response.set_cookie(ident, "COOKIE")
data = "id: 1\nretry: 200\ndata: first %s\n\n" % cookie
elif last_event_id == '1':
headers.append(("Content-Type", "text/event-stream"))
long_long_time_ago = datetime.now().repl | ace(year=2001, month=7, day=27)
response.set_cookie(ident, "COOKIE", expires=long_long_time_ago)
data = "id: 2\ndata: second %s\n\n" % cookie
else:
headers.append(("Content-Type", "stop"))
data = "data: " + last_event_id + cookie + "\n\n";
return headers, data
|
openspending/os-conductor | conductor/app.py | Python | mit | 1,606 | 0.004359 | import os
from dotenv import load_dotenv
dotenv_path = os.path.join(os.path.dirname(__file__), '../.env')
load_dotenv(dotenv_path)
# pylama:ignore=E402
from flask import Flask
from flask.ext.cors import CORS
from flask.ext.session import Session
from werkzeug.contrib.fixers import ProxyFix
from raven.contrib.flask import Sentry
from .blueprints import datastore, package, user, search
from .blueprints.logger import logger
def create():
"""Create application.
"""
# Create application
app = Flask('service', static_folder=None)
app.config['DEBUG'] = True
# Respect X-Forwarding-* headers
app.wsgi_app = ProxyFix(app.wsgi_app)
# CORS support
CORS(app, supports_credentials=True)
# Exception logging
Sentry(app, dsn=os.environ.get('SENTRY_DSN', ''))
# Session
sess = Session()
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SECRET_KEY'] = 'openspending rocks'
sess | .init_app(app)
# Register blueprints
logger.info("Creating Datastore Blueprint")
app.register_blueprint(datastore.create(), url_prefix='/datastore/')
logger.info("Creating Package Blueprint")
app.register_blueprint(package.create(), url_prefix='/package/')
logger.info("Creating Authentication Blueprint")
app.register_blueprint(user.oauth_create(), url_prefix='/oauth/ | ')
logger.info("Creating Users Blueprint")
app.register_blueprint(user.create(), url_prefix='/user/')
logger.info("Creating Search Blueprint")
app.register_blueprint(search.create(), url_prefix='/search/')
# Return application
return app
|
eric-stanley/NewsBlur | apps/profile/urls.py | Python | mit | 1,662 | 0.006017 | from django.conf.urls import *
from apps.profile import views
urlpatterns = patterns('',
url(r'^get_preferences?/?', views.get_preference),
url(r'^set_preference/?', views.set_preference),
url(r'^set_account_settings/?', views.set_account_settings),
url(r'^get_view_setting/?', views.get_view_setting),
url(r'^set_view_setting/?', views.set_view_setting),
url(r'^set_collapsed_folders/?', views.set_collapsed_folders),
url(r'^paypal_form/?', views.paypal_form),
url(r'^paypal_return/?', views.paypal_return, name='paypal-return'),
url(r'^is_premium/?', views.profile_is_premium, name='profile-is-premium'),
url(r'^paypal_ipn/?', include('paypal.standard.ipn.urls'), name='paypal-ipn'),
url(r'^stripe_form/?', views.stripe_form, name='stripe-form'),
u | rl(r'^activities/?', views.load_activities, name='profile-activities'),
url(r'^payment_hi | story/?', views.payment_history, name='profile-payment-history'),
url(r'^cancel_premium/?', views.cancel_premium, name='profile-cancel-premium'),
url(r'^refund_premium/?', views.refund_premium, name='profile-refund-premium'),
url(r'^upgrade_premium/?', views.upgrade_premium, name='profile-upgrade-premium'),
url(r'^delete_account/?', views.delete_account, name='profile-delete-account'),
url(r'^forgot_password_return/?', views.forgot_password_return, name='profile-forgot-password-return'),
url(r'^forgot_password/?', views.forgot_password, name='profile-forgot-password'),
url(r'^delete_all_sites/?', views.delete_all_sites, name='profile-delete-all-sites'),
url(r'^email_optout/?', views.email_optout, name='profile-email-optout'),
)
|
mistercrunch/airflow | airflow/providers/microsoft/azure/hooks/fileshare.py | Python | apache-2.0 | 13,121 | 0.002439 | #
# 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.
#
import warnings
from typing import IO, Any, Dict, List, Optional
from azure.storage.file import File, FileService
from airflow.hooks.base import BaseHook
class AzureFileShareHook(BaseHook):
"""
Interacts with Azure FileShare Storage.
:param azure_fileshare_conn_id: Reference to the
:ref:`Azure Container Volume connection id<howto/connection:azure_fileshare>`
of an Azure account of which container volumes should be used.
"""
conn_name_attr = "azure_fileshare_conn_id"
default_conn_name = 'azure_fileshare_default'
conn_type = 'azure_fileshare'
hook_name = 'Azure FileShare'
def __init__(self, azure_fileshare_conn_id: str = 'azure_fileshare_default') -> None:
super().__init__()
self.conn_id = azure_fileshare_conn_id
self._conn = None
@staticmethod
def get_connection_form_widgets() -> Dict[str, Any]:
"""Returns connection widgets to add to connection form"""
from flask_appbuilder.fieldwidgets import BS3PasswordFieldWidget, BS3TextFieldWidget
from flask_babel import lazy_gettext
from wtforms import PasswordField, StringField
return {
"extra__azure_fileshare__sas_token": PasswordField(
lazy_gettext('SAS Token (optional)'), widget=BS3PasswordFieldWidget()
),
"extra__azure_fileshare__connection_string": StringField(
lazy_gettext('Connection String (optional)'), widget=BS3TextFieldWidget()
),
"extra__azure_fileshare__protocol": StringField(
lazy_gettext('Account URL or token (optional)'), widget=BS3TextFieldWidget()
),
}
@staticmethod
def get_ui_field_behaviour() -> Dict:
"""Returns custom field behaviour"""
return {
"hidden_fields": ['schema', 'port', 'host', 'extra'],
"relabeling": {
'login': 'Blob Storage Login (optional)',
'password': 'Blob Storage Key (optional)',
},
"placeholders": {
'login': 'account name',
'password': 'secret',
'extra__azure_fileshare__sas_token': 'account url or token (optional)',
'extra__azure_fileshare__connection_string': 'account url or token (optional)',
'extra__azure_fileshare__protocol': 'account url or token (optional)',
},
}
def get_conn(self) -> FileService:
"""Return the FileService object."""
prefix = "extra__azure_fileshare__"
if self._conn:
return self._conn
conn = self.get_connection(self.conn_id)
service_options_with_prefix = conn.extra_dejson
service_options = {}
for key, value in service_options_with_prefix.items():
# in case dedicated FileShareHook is used, the connection will use the extras from UI.
# in case deprecated wasb hook is used, the old extras will work as well
if key.startswith(prefix):
if value != '':
service_options[key[len(prefix) :]] = value
else:
# warn if the deprecated wasb_connection is used
warnings.warn(
"You are using deprecated connection for AzureFileShareHook."
" Please change it to `Azure FileShare`.",
DeprecationWarning,
)
else:
service_options[key] = value
# warn if the old non-prefixed value is used
warnings.warn(
"You are using deprecated connection for AzureFileShareHook."
" Please change it to `Azure FileShare`.",
DeprecationWarning,
)
self._conn = FileService(account_name=conn.login, account_key=conn.password, **service_options)
return self._conn
def check_for_directory(self, share_name: str, directory_name: str, **kwargs) -> bool:
"""
Check if a directory exists on Azure File Share.
:param share_name: Name of the share.
:type share_name: str
:param directory_name: Name of the directory.
:type directory_name: str
:param kwargs: Optional keyword arguments that
`FileService.exists()` takes.
:type kwargs: object
:return: True if the file exists, False otherwise.
:rtype: bool
"""
return self.get_conn().exists(share_name, directory_name, **kwargs)
def check_for_file(self, share_name: str, directory_name: str, file_name: str, **kwargs) -> bool:
"""
Check if a file exists on Azure File Share.
:param share_name: Name of the share.
:type share_name: str
:param directory_name: Name of the directory.
:type directory_name: str
:param file_name: Name of the file.
:type file_name: str
:param kwargs: Optional keyword arguments that
`FileService.exists()` takes.
:type kwargs: object
:return: True if the file exists, False otherwise.
:rtype: bool
"""
return self.get_conn().exists(share_name, directory_name, file_name, **kwargs)
def list_directories_and_files(
self, share_name: s | tr, directory_name: Optional[str] = None, **kwargs
) -> list:
"""
Return the list of directories and files stored on a Azure File Share.
:param share_name: Name of the share.
:type share_name: str
:param directory_name: Name of the directory.
:type | directory_name: str
:param kwargs: Optional keyword arguments that
`FileService.list_directories_and_files()` takes.
:type kwargs: object
:return: A list of files and directories
:rtype: list
"""
return self.get_conn().list_directories_and_files(share_name, directory_name, **kwargs)
def list_files(self, share_name: str, directory_name: Optional[str] = None, **kwargs) -> List[str]:
"""
Return the list of files stored on a Azure File Share.
:param share_name: Name of the share.
:type share_name: str
:param directory_name: Name of the directory.
:type directory_name: str
:param kwargs: Optional keyword arguments that
`FileService.list_directories_and_files()` takes.
:type kwargs: object
:return: A list of files
:rtype: list
"""
return [
obj.name
for obj in self.list_directories_and_files(share_name, directory_name, **kwargs)
if isinstance(obj, File)
]
def create_share(self, share_name: str, **kwargs) -> bool:
"""
Create new Azure File Share.
:param share_name: Name of the share.
:type share_name: str
:param kwargs: Optional keyword arguments that
`FileService.create_share()` takes.
:type kwargs: object
:return: True if share is created, False if share already exists.
:rtype: bool
"""
return self.get_conn().create_share(share_name, **kwargs)
def delete_share(self, share_name: str, **kwargs) -> bool:
"""
Delete existing Azure File Share.
:param share_ |
erick84/uip-iiiq2016-prog3 | laboratorio3/Juanelcallado/Juan.py | Python | mit | 284 | 0.007042 | print("hola me llamo juan")
a = 'ofi'
b = 'chilea'
c = 'Mmm'
d = 'me da igual'
bandera = True
carac = input()
if carac.endswith('?'): |
print(a)
elif carac.isupper():
print (b)
elif carac.isalnum():
print(d)
else:
| print(c)
|
planetlab/NodeManager | plugins/sliverauth.py | Python | bsd-3-clause | 5,118 | 0.016999 | #!/usr/bin/python -tt
# vim:set ts=4 sw=4 expandtab:
#
# NodeManager plugin for creating credentials in slivers
# (*) empower slivers to make API calls throught hmac
# (*) also create a ssh key - used by the OMF resource controller
# for authenticating itself with its Experiment Controller
# in order to avoid spamming the DB with huge amounts of such tags,
# (*) slices need to have the 'enable_hmac' tag set
# (*) or the 'omf_control' tag set, respectively
"""
Sliver authentication support for NodeManager.
"""
import os
import random
import string
import tempfile
import socket
import logger
import tools
def start():
logger.log("sliverauth: (dummy) plugin starting up...")
def GetSlivers(data, config, plc):
if 'OVERRIDES' in dir(config):
if config.OVERRIDES.get('sliverauth') == '-1':
logger.log("sliverauth: Disabled", 2)
return
if 'slivers' not in data:
logger.log_missing_data("sliverauth.GetSlivers", 'slivers')
return
for sliver in data['slivers']:
path = '/vservers/%s' % sliver['name']
if not os.path.exists(path):
# ignore all non-plc-instantiated slivers
instantiation = sliver.get('instantiation','')
if instantiation == 'plc-instantiated':
logger.log("sliverauth: plc-instantiated slice %s does not yet exist. IGNORING!" % sliver['name'])
continue
system_slice = False
for chunk in sliver['attributes']:
if chunk['tagname'] == "system":
if chunk['value'] in (True, 1, '1') or chunk['value'].lower() == "true":
system_slice = True
for chunk in sliver['attributes']:
if chunk['tagname']=='enable_hmac' and not system_slice:
manage_hmac (plc, sliver)
if chunk['tagname']=='omf_control':
manage_sshkey (plc, sliver)
def SetSliverTag(plc, slice, tagname, value):
node_id = tools.node_id()
slivertags=plc.GetSliceTags({"name":slice,"node_id":node_id,"tagname":tagname})
if len(slivertags)==0:
# looks like GetSlivers reports about delegated/nm-controller slices that do *not* belong to this node
# and this is something that AddSliceTag does not like
try:
slivertag_id=plc.AddSliceTag(slice,tagname,value,node_id)
except:
logger.log_exc ("sliverauth.SetSliverTag (probably delegated) slice=%(slice)s tag=%(tagname)s node_id=%(node_id)d"%locals())
pass
else:
slivertag_id=slivertags[0]['slice_tag_id']
plc.UpdateSliceTag(slivertag_id,value)
def find_tag (sliver, tagname):
for attribute in sliver['attributes']:
# for legacy, try the old-fashioned 'name' as well
name = attribute.get('tagname',attribute.get('name',''))
if name == tagname:
return attribute['value']
return None
def manage_hmac (plc, sliver):
hmac = find_tag (sliver, 'hmac')
if not hmac:
# let python do its thing
random.seed()
d = [random.choice(string.letters) for x in xrange(32)]
hmac = "".join(d)
SetSliverTag(plc,sliver['name'],'hmac',hmac)
logger.log("sliverauth: %s: setting hmac" % sliver['name'])
path = '/vservers/%s/etc/planetlab' % sliver['name']
if os.path.exists(pa | th):
keyfile = '%s/key' % path
if (tools.replace_file_with_string(keyfile,hmac,chmod=0400)):
logger.log ("sliverauth: (o | ver)wrote hmac into %s " % keyfile)
# create the key if needed and returns the key contents
def generate_sshkey (sliver):
# initial version was storing stuff in the sliver directly
# keyfile="/vservers/%s/home/%s/.ssh/id_rsa"%(sliver['name'],sliver['name'])
# we're now storing this in the same place as the authorized_keys, which in turn
# gets mounted to the user's home directory in the sliver
keyfile="/home/%s/.ssh/id_rsa"%(sliver['name'])
pubfile="%s.pub"%keyfile
dotssh=os.path.dirname(keyfile)
# create dir if needed
if not os.path.isdir (dotssh):
os.mkdir (dotssh, 0700)
logger.log_call ( [ 'chown', "%s:slices"%(sliver['name']), dotssh ] )
if not os.path.isfile (pubfile):
comment="%s@%s"%(sliver['name'],socket.gethostname())
logger.log_call( [ 'ssh-keygen', '-t', 'rsa', '-N', '', '-f', keyfile , '-C', comment] )
os.chmod (keyfile, 0400)
logger.log_call ( [ 'chown', "%s:slices"%(sliver['name']), keyfile, pubfile ] )
return file(pubfile).read().strip()
# a sliver can get created, deleted and re-created
# the slice having the tag is not sufficient to skip key geneneration
def manage_sshkey (plc, sliver):
# regardless of whether the tag is there or not, we need to grab the file
# if it's lost b/c e.g. the sliver was destroyed we cannot save the tags content
ssh_key = generate_sshkey(sliver)
old_tag = find_tag (sliver, 'ssh_key')
if ssh_key <> old_tag:
SetSliverTag(plc, sliver['name'], 'ssh_key', ssh_key)
logger.log ("sliverauth: %s: setting ssh_key" % sliver['name'])
|
qiyuangong/Machine_Learning_in_Action_QYG | 03_ID3/treePlotter.py | Python | mit | 3,229 | 0.001548 | import matplotlib
import matplotlib.pyplot as plt
decisionNoe = dict(boxstyle="sawtooth", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-")
def plotNoe(nodeTxt, centerPt, parentPt, nodeType):
createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction',
xytext=centerPt, textcoords='axes fraction',
va="center", ha="center", bbox=nodeType,
arrowprops=arrow_args)
def createPlot():
fig = plt.figure(1, facecolor='white')
fig.clf()
createPlot.ax1 = plt.subplot(111, frameon=False)
plotNoe('Decision Node', (0.5, 0.1), (0.1, 0.5), decisionNoe)
plotNoe('Lea fNode', (0.8, 0.1), (0.3, 0.8), leafNode)
plt.show()
def getNumLeafs(myTree):
numLeafs = 0
firstStr = myTree.keys()[0]
secondDict = myTree[firstStr]
for key in secondDict.keys():
if type(secondDict[key]).__name__ == 'dict':
numLeafs += getNumLeafs(secondDict[key])
else:
numLeafs += 1
return numLeafs
def getTreeDepth(myTree):
maxDepth = 0
firstStr = myTree.keys()[0]
secondDict = myTree[firstStr]
for key in secondDict.keys():
if type(secondDict[key]).__name__ == 'dict':
thisDepth = 1 + getTreeDepth(secondDict[key])
else:
thisDepth = 1
if thisDepth > maxDepth:
maxDepth = thisDepth
return maxDepth
def retrieveTree(i):
listOfTrees = [{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}},
{'no surfacing': {0: 'no', 1: {'flippers': {0: {'head': {0: 'no', 1: 'yes'}}, 1: 'no'}}}}]
return listOfTrees[i]
def plotMidText(cntrPt, parentPt, txtString):
xMid = (parentPt[0] - cntrPt[0]) / 2.0 + cntrPt[0]
yMid = (parentPt[1] - cntrPt[1]) / 2.0 + cntrPt[1]
createPlot.ax1.text(xMid, yMid, txtString, va="center", ha="center", rotation=30)
def plotTree(myTree, parentPt, nodeTxt):
numLeafs = getNumLeafs(myTree)
depth = getTreeDepth(myTree)
firstStr = myTree.keys()[0]
cntrPt = (plotTree.xoff + (1.0 + float(numLeafs)) / 2.0 / plotTree.totalW, plotTree.yoff)
plotMidText(cntrPt, parentPt, nodeTxt)
plotNoe(firstStr, cntrPt, parentPt, decisionN | oe)
secondDict = myTree[firstStr]
plotTree.yoff = plotTree.yoff - 1.0 / plotTree.totalD
for key in secondDict.keys(): |
if type(secondDict[key]).__name__ == 'dict':
plotTree(secondDict[key], cntrPt, str(key))
else:
plotTree.xoff = plotTree.xoff + 1.0 / plotTree.totalW
plotNoe(secondDict[key], (plotTree.xoff, plotTree.yoff), cntrPt, leafNode)
plotMidText((plotTree.xoff, plotTree.yoff), cntrPt, str(key))
plotTree.yoff = plotTree.yoff + 1.0 / plotTree.totalD
def createPlot(inTree):
fig = plt.figure(1, facecolor='white')
fig.clf()
axprops = dict(xticks=[], yticks=[])
createPlot.ax1 = plt.subplot(111, frameon=False, **axprops)
plotTree.totalW = float(getNumLeafs(inTree))
plotTree.totalD = float(getTreeDepth(inTree))
plotTree.xoff = - 0.5 / plotTree.totalW
plotTree.yoff = 1.0
plotTree(inTree, (0.5, 1.0), '')
plt.show()
|
matclayton/OpenSocial-Python | tests/run_online_tests.py | Python | apache-2.0 | 1,350 | 0.004444 | #!/usr/bin/python
#
# Copyright (C) 2007, 2008 Google Inc.
#
# 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 govern | ing permissions and
# limitations under the License.
__author__ = 'davidbyttow@google.com (David Byttow)'
import module_test_runner
import opensocial_tests.orkut_test
import opensocial_tests.myspace_test
import opensocial_tests.partuza_test
import opensocial_tests.oauth_test
import opensocial_tests.google_sandbox_test
import opensocial_tests.myspace09_test
def RunOnlineTests | ():
test_runner = module_test_runner.ModuleTestRunner()
test_runner.modules = [
opensocial_tests.orkut_test,
opensocial_tests.myspace_test,
opensocial_tests.myspace09_test,
opensocial_tests.partuza_test,
opensocial_tests.oauth_test,
opensocial_tests.google_sandbox_test,
]
test_runner.RunAllTests()
if __name__ == '__main__':
RunOnlineTests()
|
AEDA-Solutions/matweb | backend/Models/Sala/RespostaListar.py | Python | mit | 224 | 0.026786 | from Framework.Resposta impo | rt Resposta
from Models.Sala.Sala import Sala as ModelSala
class RespostaListar(Resposta):
def __init__(self,salas):
self.corpo = []
for sala in salas:
self.corpo.append(ModelSa | la(sala))
|
ojii/django-nani | hvad/tests/fieldtranslator.py | Python | bsd-3-clause | 971 | 0.00309 | # -*- coding: utf-8 -*-
from hv | ad.fieldtranslator import translate
from hvad.test_utils.testcase import NaniTestCase
from testproject.app.models import Related
class FieldtranslatorTests(NaniTestCase):
def test_simple(self):
INPUT = 'normal__shared_field' |
query_string, joins = translate(INPUT, Related)
self.assertEqual(query_string, INPUT)
self.assertEqual(joins, ['normal__translations__language_code'])
def test_query_bit(self):
INPUT = 'normal__shared_field__exact'
query_string, joins = translate(INPUT, Related)
self.assertEqual(query_string, INPUT)
self.assertEqual(joins, ['normal__translations__language_code'])
INPUT = 'normal__translated_field__exact'
query_string, joins = translate(INPUT, Related)
self.assertEqual(query_string, 'normal__translations__translated_field__exact')
self.assertEqual(joins, ['normal__translations__language_code']) |
inkenbrandt/Snake_Valley | untitled1.py | Python | gpl-2.0 | 205 | 0.009756 | # -*- coding: utf | -8 -*-
"""
Created on Mon Jul 13 09:11:25 2015
@author: paulinkenbrandt
"""
import py_compile
py_compile.compile("C:\\Users\\PAULINKENBRANDT\\Documents\\GitHub\\Snak | e_Valley\\snake.py") |
roycem90/python-o365 | tests/test_attachment.py | Python | apache-2.0 | 1,812 | 0.032561 | from O365 import attachment
import unittest
import json
import base64
from random import randint
att_rep = open('attachment.json','r').read()
att_j = json.loads(att_r | ep)
class TestAttachment (unittest.TestCase):
def setUp(self):
self.att = attachment.Attachment(att_j['value'][0])
def test_isType(self):
| self.assertTrue(self.att.isType('txt'))
def test_getType(self):
self.assertEqual(self.att.getType(),'.txt')
def test_save(self):
name = self.att.json['Name']
name1 = self.newFileName(name)
self.att.json['Name'] = name1
self.assertTrue(self.att.save('/tmp'))
with open('/tmp/'+name1,'r') as ins:
f = ins.read()
self.assertEqual('testing w00t!',f)
name2 = self.newFileName(name)
self.att.json['Name'] = name2
self.assertTrue(self.att.save('/tmp/'))
with open('/tmp/'+name2,'r') as ins:
f = ins.read()
self.assertEqual('testing w00t!',f)
def newFileName(self,val):
for i in range(4):
val = str(randint(0,9)) + val
return val
def test_getByteString(self):
self.assertEqual(self.att.getByteString(),b'testing w00t!')
def test_getBase64(self):
self.assertEqual(self.att.getBase64(),'dGVzdGluZyB3MDB0IQ==\n')
def test_setByteString(self):
test_string = b'testing testie test'
self.att.setByteString(test_string)
enc = base64.encodebytes(test_string)
self.assertEqual(self.att.json['ContentBytes'],enc)
def setBase64(self):
wrong_test_string = 'I am sooooo not base64 encoded.'
right_test_string = 'Base64 <3 all around!'
enc = base64.encodestring(right_test_string)
self.assertRaises(self.att.setBase64(wrong_test_string))
self.assertEqual(self.att.json['ContentBytes'],'dGVzdGluZyB3MDB0IQ==\n')
self.att.setBase64(enc)
self.assertEqual(self.att.json['ContentBytes'],enc)
if __name__ == '__main__':
unittest.main()
|
adrn/MDM | mdm/triand.py | Python | mit | 1,923 | 0.00416 | # coding: utf-8
""" TriAnd RR Lyrae """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard library
import os, sys
from datetime import datetime, timedelta
# Third-party
import astropy.coordinates as coord
import astropy.units as u
from astropy.io import ascii
from astropy.time import Time
from astropy.table import Table, Column, join
import numpy as np
# Project
from streams.coordinates import sex_to_dec
from streams.observation.time import gmst_to_utc, lmst_to_gmst
from streams.observation.rrlyrae import time_to_phase, phase_to_time
from streams.util import project_root
data_file = os.path.join(project_root, "data", "catalog", "TriAnd_RRLyr.txt")
stars = ascii.read(data_file,
converters={'objectID' : [ascii.convert_numpy(np.str)]},
header_start=0,
data_start=1,
delimiter=" ")
# Need to wrap so RA's go 22,23,24,0,1,etc.
ras = np.array(stars['ra'])
ras[ras > 90.] = ras[ras > 90.] - 360.
idx = np.argsort(ras)
stars = stars[idx]
names = ["TriAndRRL{0}".format(ii+1) for ii in range(len(stars))]
stars.add_column(Column(names, name='name'))
# Read in RR Lyrae standards
RRLyr_stds1 = ascii.read("/Users/adrian/Documents/GraduateSchool/Observing/Std RR Lyrae/nemec_RRLyrae.txt")
RRLyr_stds2 = ascii.read("/Users/adrian/Documents/GraduateSchool/Observing/Std RR Lyrae/bi-qing_for2011_RRLyr.txt", delimiter=',')
RRLyr_stds2.add_column(Column(RRLyr_stds2['hjd0_2450000'] + 2450000., name | ='rhjd0'))
RRLyr_stds2['ra'] = [coord.Angle(x, unit=u.hour).degree for x in RRLyr_stds2['ra_str']]
RRLyr_stds2['dec'] = [coord.Angle(x, unit=u.degree).degree for x in RRLyr_stds2['dec_str']]
standards = join(RRLyr_stds1, RRLyr_stds2, join_type='outer')
all_stars = join(stars, RRLyr_stds1, join_type='outer')
all_stars = join(all_st | ars, RRLyr_stds2, join_type='outer')
triand_stars = stars |
exepulveda/swfc | python/clustering_ga.py | Python | gpl-3.0 | 15,844 | 0.02796 | import sys
import logging
import collections
import math
import sys
sys.path += ['..']
import clusteringlib as cl
import numpy as np
from deap import algorithms
from deap import base
from deap import creator
from deap import tools
from copy import deepcopy
from cluster_utils import fix_weights
class CentroidIndividual(object):
def __init__(self,NC,ND,min_values,max_values):
self.NC = NC
self.ND = ND
self.min_values = min_values
self.max_values = max_values
self.centroid = np.empty((NC,ND))
self.fitness = creator.FitnessMin()
self.u = None
def clone(self):
new_obj = CentroidIndividual(self.NC,self.ND,self.min_values,self.max_values)
new_obj.fitness = deepcopy(self.fitness)
new_obj.centroid[:,:] = self.centroid
new_obj.u = self.u.copy()
return new_obj
def check(self):
| for i in range(self.NC):
for j in range(self.ND): |
if not(self.min_values[j] <= self.centroid[i,j] <= self.max_values[j]):
print(i,j,self.centroid[i,j],self.min_values[j],self.max_values[j])
assert False, "PROBLEM 2222"
def __deepcopy__(self,memo):
return self.clone()
def clone_centroid(sol):
return sol.clone()
def create_ga_centroids(data,weights,m,lambda_value,types,cat_values):
"""
Helper method to configure evolution algorithm.
Uses toolbox from deap and potentially could use scoop to distribute or
parallelize.
"""
creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
toolbox = base.Toolbox()
toolbox.register("clone", clone_centroid)
toolbox.register("mate", crossover_centroid)
toolbox.register("evaluate", evaluate_centroid,data=data,weights=weights,m=m,lambda_value=lambda_value)
toolbox.register("mutate", mutate_centroid,types=types,cat_values=cat_values)
toolbox.register("select", tools.selTournament, tournsize=9)
return toolbox
def mutate_centroid(ind,types,cat_values):
new_solution = ind.centroid.copy()
NC,ND = new_solution.shape
#select at random a cluster to modify
sel_cluster = np.random.randint(NC)
#select at random a dimension to modify
sel_dim = np.random.randint(ND)
new_solution[sel_cluster,sel_dim] += np.random.normal(loc=0.0, scale=0.1)
new_solution[sel_cluster,sel_dim] = np.clip(new_solution[sel_cluster,sel_dim],ind.min_values[sel_dim],ind.max_values[sel_dim])
ind.centroid[:,:] = new_solution
return ind,
def crossover_centroid(ind1,ind2):
ind1.check()
ind2.check()
child1, child2 = tools.cxUniform(ind1.centroid.flatten(),ind2.centroid.flatten(),indpb=0.5)
ind1.centroid[:,:] = child1.reshape((ind1.NC,ind1.ND))
ind2.centroid[:,:] = child2.reshape((ind2.NC,ind2.ND))
ind1.check()
ind2.check()
return ind1, ind2
def similar_op_centroid(ind1,ind2):
return np.array_equal(ind1.centroid,ind2.centroid)
def evolve_centroids(toolbox,initial_centroids,values,min_values,max_values,npop,ngen,stop_after,cxpb,mutpb,verbose=False):
NC,ND = initial_centroids.shape
N = len(values)
pop = [CentroidIndividual(NC,ND,min_values,max_values) for _ in range(npop)]
for i,ind in enumerate(pop):
if i == 0:
ind.centroid[:,:] = initial_centroids
else:
#random
for k in range(NC):
j = np.random.choice(N)
ind.centroid[k,:] = values[j,:]
ind.check()
hof = tools.HallOfFame(1,similar=similar_op_centroid)
stats = tools.Statistics(key=lambda ind: ind.fitness.values)
stats.register("avg", np.mean)
stats.register("min", np.min)
stats.register("max", np.max)
logbook = tools.Logbook()
logbook.header = "gen", "min", "avg", "max", "best"
#logger.info("Evaluating initial population")
# Evaluate the individuals with an invalid fitness
invalid_ind = [ind for ind in pop if not ind.fitness.valid]
fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit
hof.update(pop)
record = stats.compile(pop) if stats else {}
logbook.record(gen=0,best=hof[0].fitness.values[0], **record)
if verbose: print(logbook.stream)
evaluations = 0
no_improvements = 0
#logger.info("Starting evolution!")
for gen in range(1, ngen+1):
prev_fitness = hof[0].fitness.values[0]
# Select the next generation individuals
offspring = toolbox.select(pop, len(pop))
# Vary the pool of individuals
offspring = algorithms.varAnd(offspring, toolbox, cxpb, mutpb)
# Evaluate the individuals with an invalid fitness
invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit
evals_gen = len(invalid_ind)
# Update the hall of fame with the generated individuals
if hof is not None:
hof.update(offspring)
current_fitness = hof[0].fitness.values[0]
# Replace the current population by the offspring
pop[:] = offspring
# Append the current generation statistics to the logbook
record = stats.compile(pop) if stats else {}
logbook.record(gen=gen,best=hof[0].fitness.values[0], **record)
#logger.info(logbook.stream)
if verbose: print(logbook.stream)
evaluations += evals_gen
if current_fitness >= prev_fitness: #worse fitness
no_improvements += 1
else:
no_improvements = 0
if no_improvements > stop_after:
break
return pop, stats, hof, logbook, gen, evaluations
def evaluate_centroid(ind,data,weights,m,lambda_value,verbose=0):
centroid = ind.centroid
ret = evaluate(centroid,data,weights,m,lambda_value,verbose=0)
ind.u = ret[1]
return ret
def evaluate(centroid,data,weights,m,lambda_value,C=5.0,verbose=0):
N,ND = data.shape
NC,ND2 = weights.shape
NC2,ND3 = centroid.shape
assert ND2 == ND,"weigths and data shape: %d, %d"%(ND2,ND)
assert ND2 == ND3,"weigths adn centroid shape: %d, %d"%(ND2,ND3)
assert NC == NC2,"weigths adn centroid shape: %d, %d"%(NC,NC2)
#assert C == C2,"%s,%s"%(weights.shape,centroid.shape)
#assert P == P2,"%s,%s"%(weights.shape,centroid.shape)
u = np.asfortranarray(np.empty((N,NC)),dtype=np.float32)
centroid_F = np.asfortranarray(centroid,dtype=np.float32)
data_F = np.asfortranarray(data,dtype=np.float32)
weights_F = np.asfortranarray(weights,dtype=np.float32)
cl.clustering.update_membership(data_F,centroid_F,m,u,weights_F,verbose)
#centroid,data,m,u,weights,verbose
verbose = 0
if verbose > 2:
print("centroid",centroid)
print("m",m)
print("weights",weights)
print("lambda_value",lambda_value)
index1,jm,min_cluster_distance = cl.clustering.compactness_weighted(data_F,centroid_F,m,u,weights_F,1,lambda_value,verbose)
#print("evaluate",index1,min_cluster_distance,jm )
#assert min_cluster_distance > 0.0
if np.isnan(index1):
print("u",u)
print("centroid",centroid)
print("weights",weights)
np.savetxt("../../bm_clusters.csv",centroid,delimiter=",",fmt="%.4f")
np.savetxt("../../bm_weights.csv",weights,delimiter=",",fmt="%.4f")
np.savetxt("../../bm_u.csv",u,delimiter=",",fmt="%.4f")
assert False
#print('jm',jm,'separation',min_cluster_distance)
#return index1 + 100.0/min_cluster_distance,jm,u
#return index1/min_cluster_distance,jm,u
if min_cluster_distance != 0.0:
return jm + C/min_cluster_distance,u,index1,jm,min_cluster_distance
else:
return jm + C,u,index1,jm,min_cluster_distance
def optimize_centroids(data,current |
outini/sandcrawler | libraries/sc_systems.py | Python | gpl-3.0 | 6,623 | 0.002265 | # -*- coding: iso-latin-1 -*-
"""
systems specifics for sandcrawler
"""
__docformat__ = 'restructuredtext en'
__author__ = "Denis 'jawa' Pompilio"
__credits__ = "Denis 'jawa' Pompilio"
__license__ = "GPLv3"
__maintainer__ = "Denis 'jawa' Pompilio"
__email__ = "denis.pompilio@gmail.com"
__status__ = "Development"
import sys
import types
import collections
import sc_logs as LOG
import sc_common as scc
import fabric_wrp as fapi
class CallBacks():
""" class to store callbacks """
def __init__(self, trunk, parent, module, search_paths):
LOG.log_d("initialising Callbacks class %s" % (module))
self.trk = trunk
self.mom = parent
modlist = list()
generic_module = "generic_callbacks.%s" % (module)
LOG.log_d("generic module is %s" % (generic_module))
generic_imported = self.try_import(generic_module)
if generic_imported is not None:
LOG.log_d("generic module successfully imported")
modlist.extend([generic_imported])
# add users' callbacks_path prefix
for path in search_paths:
path = '.'.join(path.split('/'))
target_module = "callbacks.%s.%s" % (path, module)
specific_imported = self.try_import(target_module)
if specific_imported is not None:
LOG.log_d("%s successfully imported" % (target_module))
modlist.extend([specific_imported])
if not len(modlist):
raise ImportError("unable to import required callbacks: %s" % (
module))
LOG.log_d("importing methods and attributes from each module")
self.retriev_attrs_and_methods(modlist)
@staticmethod
def try_import(module):
""" try to import module """
# add generic_callbacks methods and attribute | s if found
try:
__import__(module)
return sys.modules[module]
except ImportError:
LOG.log_d("module '%s' not found" % (module))
return None
def retriev_attrs_and_methods(self, modules_list):
""" retrieve a | ttributes and methods from each module """
for mod in modules_list:
LOG.log_d("importing from %s" % (mod.__name__))
for attr in dir(mod):
# import everything but builtins and privates
if attr[0:2] == "__":
continue
module_attr = getattr(mod, attr)
## store callback, if callable self refer to the callback
if isinstance(module_attr, collections.Callable):
setattr(self, attr,
types.MethodType(module_attr, self))
else:
setattr(self, attr, module_attr)
return True
def fapi_wrapper(method_name):
""" trying metaclass """
def _method(self, *argl, **argd):
# adding self.srv_ip as first argument for every fapi invocations
# all the fabric_wrp methods MUST take the ip as first argument
argl = list(argl)
argl.insert(0, self.srv_ip)
argl = tuple(argl)
return getattr(fapi, '%s' % method_name)(*argl,**argd)
return _method
class Server:
""" server class with os/distribs callbacks """
def __init__(self, srv_ip, load=True, systemtype=None):
LOG.log_d("initialising Server(%s, %s, %s)" % (srv_ip, load,
systemtype))
self.srv_ip = srv_ip
self.hostname = None
self.systemtype = systemtype
self.callbacks_paths = list()
self.fapi = scc.AttStr('fapi calls wrapper')
self.load_fapi()
if load:
LOG.log_d("guessing server's system type")
self.guess_system(systemtype)
def is_up(self, port = 22):
""" check if host is UP """
return scc.is_host_up(self.srv_ip, int(port))
def __getparent(self, callback_name):
""" get parent from callback name """
splitted = callback_name.split('.')
if len(splitted) == 1:
return None
parent = self
for member in splitted[:-1]:
if not hasattr(parent, member):
parent.load_callbacks(member)
parent = getattr(parent, member)
return parent
def load_callbacks(self, callback):
""" callbacks loader """
if self.systemtype == None and not self.guess_system():
return False
# load callback specified by arg, split by dot and recurse load
callback_name = callback.split('.')[-1]
parent = self.__getparent(callback)
if parent is None or not hasattr(parent, 'trk'):
trunk = parent = self
else:
trunk = parent.trk
setattr(parent, callback_name, CallBacks(trunk, parent, callback,
self.callbacks_paths))
return True
def load_fapi(self):
"""
wrap methods from fabric_wrp module
wrapper assume that the first argument of each fapi methods is srv_ip
all invocations have to be done without the first argument (srv_ip)
"""
for attr in dir(fapi):
if attr[0:2] == "__" or attr == "with_statement":
continue
module_attr = getattr(fapi, attr)
if isinstance(module_attr, collections.Callable):
setattr(self.fapi, attr,
types.MethodType(fapi_wrapper(attr), self))
else:
setattr(self, attr, module_attr)
return True
def guess_system(self, systype = None):
""" guess on system of remote target """
if systype is None:
if not self.is_up():
return False
try:
sysinfos_mod = "callbacks.systems_infos"
__import__(sysinfos_mod)
except ImportError:
sysinfos_mod = "generic_callbacks.systems_infos"
__import__(sysinfos_mod)
LOG.log_d("guessing system using '%s'" % (sysinfos_mod))
guess = sys.modules[sysinfos_mod].sysguess
requisites = sys.modules[sysinfos_mod].check_prerequisites
requisites(self.srv_ip)
(self.hostname,
self.systemtype,
self.callbacks_paths) = guess(self.srv_ip)
LOG.log_d("system guessed as %s" % (self.systemtype))
else:
self.systemtype = systype
self.callbacks_paths.append(systype)
return True
|
franek/weboob | modules/attilasub/__init__.py | Python | agpl-3.0 | 802 | 0 | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Julien Veyssier
#
# This file is part of weboob.
#
# weboob 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.
#
# weboob 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 Pu | blic License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
from .backend import AttilasubBacke | nd
__all__ = ['AttilasubBackend']
|
liuguoyaolgy/Stock | m_wangge.py | Python | gpl-2.0 | 13,472 | 0.017862 |
import tushare as ts
from m_load_update_data import load
import m_draw
import matplotlib.pyplot as plt
import string
import m_smtp
import datetime
price = ''
class cw_dsp():
def __init__(self):
self.bishu=0.0
self.buyamt=0.0
self.buyprice=0.0
class CW():
def __init__(self):
self.canjy = '1'
self.cw_part = 6
self.remainder_Amt=100000.0
self.bili = 0 # 共分六份
self.jycnt = 0
self.C1 = cw_dsp()
self.C2 = cw_dsp()
self.C3 = cw_dsp()
self.C4 = cw_dsp()
self.C5 = cw_dsp()
self.C6 = cw_dsp()
self.C7 = cw_dsp()
class CW_ctr():
def jc(self,ma20,price):
if 0 == cw.bili:
print('jc')
if price <= ma20*p7:
cw.C7.bishu = int(cw.remainder_Amt / (cw.cw_part - cw.bili) / price / 100)
cw.C7.buyamt = cw.C7.bishu * 100 * price
cw.C7.buyprice = price
cw.bili += 1
cw.remainder_Amt -= cw.C7.buyamt
if price <= ma20*p6:
cw.C6.bishu = int(cw.remainder_Amt / (cw.cw_part - cw.bili) / price / 100)
cw.C6.buyamt = cw.C6.bishu * 100 * price
cw.C6.buyprice = price
cw.bili += 1
cw.remainder_Amt -= cw.C6.buyamt
if price <= ma20*p5:
cw.C5.bishu = int(cw.remainder_Amt / (cw.cw_part - cw.bili) / price / 100)
cw.C5.buyamt = cw.C5.bishu * 100 * price
cw.C5.buyprice = price
cw.bili += 1
cw.remainder_Amt -= cw.C5.buyamt
cw.C1.bishu=int(cw.remainder_Amt/(cw.cw_part-cw.bili)/price/100)
cw.C1.buyamt=cw.C1.bishu*100*price
cw.C1.buyprice = price
cw.bili+=1
cw.remainder_Amt -= cw.C1.buyamt
cw.C2.bishu=int(cw.remainder_Amt/(cw.cw_part-cw.bili)/price/100)
cw.C2.buyamt=cw.C2.bishu*100*price
cw.C2.buyprice = price
cw.bili+=1
cw.jycnt += 1
cw.remainder_Amt -= cw.C2.buyamt
cw.C3.bishu=int(cw.remainder_Amt/(cw.cw_part-cw.bili)/price/100)
cw.C3.buyamt=cw.C3.bishu*100*price
cw.C3.buyprice = price
cw.bili+=1
cw.jycnt += 1
cw.remainder_Amt -= cw.C3.buyamt
return
return
def buy(self,price,cwno,date):
if 4 == cw.bili :
#清仓
#self.qc(price,date)
return
elif 0 == cw.bili and 1 == cwno :
print('amtdiff:BUY:',cw.bili,date,price)
cw.C1.bishu=int(cw.remainder_Amt/(cw.cw_part-cw.bili)/price/100)
cw.C1.buyamt=cw.C1.bishu*100*price
cw.C1.buyprice = price
cw.bili+=1
cw.remainder_Amt -= cw.C1.buyamt
return
elif 1 == cw.bili and 2 == cwno:
print('amtdiff:BUY:', cw.bili, date, round(price,2))
cw.C2.bishu=int(cw.remainder_Amt/(cw.cw_part-cw.bili)/price/100)
cw.C2.buyamt=cw.C2.bishu*100*price
cw.C2.buyprice = price
cw.bili+=1
cw.remainder_Amt -= cw.C2.buyamt
return
elif 2 == cw.bili and 3 == cwno:
print('amtdiff:BUY:', cw.bili, date, round(price,2))
cw.C3.bishu=int(cw.remainder_Amt/(cw.cw_part-cw.bili)/price/100)
cw.C3.buyamt=cw.C3.bishu*100*price
cw.C3.buyprice = price
cw.bili+=1
cw.remainder_Amt -= cw.C3.buyamt
return
elif 3 == cw.bili and 5 == cwno:
print('amtdiff:BUY:', cw.bili, date, round(price,2))
cw.C5.bishu=int(cw.remainder_Amt/(cw.cw_part-cw.bili)/price/100)
cw.C5.buyamt=cw.C5.bishu*100*price
cw.C5.buyprice = price
cw.bili+=1
cw.remainder_Amt -= cw.C5.buyamt
return
elif 4 == cw.bili and 6 == cwno:
print('amtdiff:BUY:', cw.bili, date, round(price,2))
cw.C6.bishu=int(cw.remainder_Amt/(cw.cw_part-cw.bili)/price/100)
cw.C6.buyamt=cw.C6.bishu*100*price
cw.C6.buyprice = price
cw.bili+=1
cw.remainder_Amt -= cw.C6.buyamt
return
elif 5 == cw.bili and 7 == cwno:
print('amtdiff:BUY:', cw.bili, date, round(price,2))
cw.C7.bishu=int(cw.remainder_Amt/(cw.cw_part-cw.bili)/price/100)
cw.C7.buyamt=cw.C7.bishu*100*price
cw.C7.buyprice = price
cw.bili+=1
cw.remainder_Amt -= cw.C7.buyamt
return
else:
return
def sale(self,price,cwno,date):
if 0 == cw.bili:
return
if 1 == cw.bili and 1 == cwno:
return
print('amtdiff:',cw.bili,date,round(cw.C1.buyprice,2),'->',round(price,2),round(cw.C1.bishu*price*100-cw.C1.buyamt))
cw.bili -= 1
cw.remainder_Amt += cw.C1.bishu*price*100
cw.C1.bishu = 0.0
cw.C1.buyamt = 0.0
cw.C1.buyprice = 0.0
cw.jycnt += 1
return
if 2 == cw.bili and 2 == cwno:
print('amtdiff:',cw.bili,date,round(cw.C2.buyprice,2),'->',round(price,2),round(cw.C2.bishu*price*100-cw.C2.buyamt))
cw.bili -= 1
cw.remainder_Amt += cw.C2.bishu*price*100
cw.C2.bishu = 0.0
cw.C2.buyamt = 0.0
cw.C2.buyprice = 0.0
cw.jycnt += 1
return
if 3 == cw.bili and 3 == cwno:
print('amtdiff:',cw.bili,date,round(cw.C3.buyprice,2),'->',round(price,2),round(cw.C3.bishu*price*100-cw.C3.buyamt))
cw.bili -= 1
cw.remainder_Amt += cw.C3.bishu*price*100
cw.C3.bishu = 0.0
cw.C3.buyamt = 0.0
cw.C3.buyprice = 0.0
| cw.jycnt += 1
return
if 4 == cw.bili and 5 == cwno:
print('amtdiff:',cw.bili,date,round(cw.C5.buyprice,2),'->',round(price,2),round(cw.C5.bishu*price*100-cw.C5.buyamt))
cw.bili -= 1
| cw.remainder_Amt += cw.C5.bishu*price*100
cw.C5.bishu = 0.0
cw.C5.buyamt = 0.0
cw.C5.buyprice = 0.0
cw.jycnt += 1
return
if 5 == cw.bili and 6 == cwno:
print('amtdiff:',cw.bili,date,round(cw.C6.buyprice,2),'->',round(price,2),round(cw.C6.bishu*price*100-cw.C6.buyamt))
cw.bili -= 1
cw.remainder_Amt += cw.C6.bishu*price*100
cw.C6.bishu = 0.0
cw.C6.buyamt = 0.0
cw.C6.buyprice = 0.0
cw.jycnt += 1
return
if 6 == cw.bili and 7 == cwno:
print('amtdiff:',cw.bili,date,round(cw.C7.buyprice,2),'->',round(price,2),round(cw.C7.bishu*price*100-cw.C7.buyamt))
cw.bili -= 1
cw.remainder_Amt += cw.C7.bishu*price*100
cw.C7.bishu = 0.0
cw.C7.buyamt = 0.0
cw.C7.buyprice = 0.0
cw.jycnt += 1
return
def amt(self,price):
return cw.remainder_Amt+cw.C1.bishu*price*100+cw.C2.bishu*price*100+cw.C3.bishu*price*100+cw.C5.bishu*price*100+cw.C6.bishu*price*100+cw.C7.bishu*price*100
def amt2(self):
return cw.remainder_Amt+cw.C1.buyamt+cw.C2.buyamt+cw.C3.buyamt+cw.C5.buyamt+cw.C7.buyamt+cw.C7.buyamt
def qc(self,price,date):
# if cw.bili == 0 :
# return
cw.remainder_Amt=self.amt(price)
print('amtdiff:', cw.bili, date, round(self.amt(price)-self.amt2()),'qqqqqqcccccc')
cw.bili = 0
cw.C1.bishu = 0.0
cw.C1.buyamt = 0.0
cw.C1.buyprice = 0.0
cw.C2.bishu = 0.0
cw.C2.buyamt = 0.0
cw.C2.buyprice = 0.0
cw.C3.bishu = 0.0
cw.C3.buyamt = 0.0
cw.C3.buyprice = 0.0
cw.C4.bishu = 0.0
cw.C4.buyamt = 0.0
cw.C4.buyprice = 0.0
cw.C5.bishu = 0.0
cw.C5.buyamt = 0.0
cw.C5.buyprice = 0.0
cw.C6.bishu = 0.0
cw.C6.buyamt = 0.0
cw.C6.buyprice = 0.0
cw.C7.bishu = 0.0
cw.C7.buyamt = 0.0
c |
Saevon/AnkiHelpers | kana.py | Python | mit | 7,233 | 0.003811 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
from jcconv import kata2hira, hira2kata
from itertools import chain
from printable import PrintableDict, PrintableList
__by_vowels = PrintableDict(**{
u'ア': u'ワラヤャマハナタサカアァ',
u'イ': u'リミヒニちシキイィ',
u'ウ': u'ルユュムフヌツスクウゥ',
u'エ': u'レメヘネテセケエェ',
u'オ': u'ヲロヨョモホノトソコオォ',
})
__to_dakuten = PrintableDict(**{
u'か': u'が',
u'き': u'ぎ',
u'く': u'ぐ',
u'け': u'げ',
u'こ': u'ご',
u'さ': u'ざ',
u'し': u'じ',
u'す': u'ず',
u'せ': u'ぜ',
u'そ': u'ぞ',
u'た': u'だ',
u'ち': u'ぢ',
u'つ': u'づ',
u'て': u'で',
u'と': u'ど',
u'は': u'ばぱ',
u'ひ': u'びぴ',
u'ふ': u'ぶぷ',
u'へ': u'べぺ',
u'ほ': u'ぼぽ',
})
__to_mini = PrintableDict(**{
u'く': u'っ',
u'つ': u'っ',
u'や': u'ゃ',
u'よ': u'ょ',
u'ゆ': u'ゅ',
u'わ': u'ゎ',
u'か': u'ゕ',
u'け': u'ゖ',
u'あ': u'ぁ',
u'い': u'ぃ',
u'う': u'ぅ',
u'え': u'ぇ',
u'お': u'ぉ',
})
EXTENDABLE_MINIS = (
u'つ',
u'く',
)
__by_dakuten = PrintableDict()
for vowel, letters in __to_dakuten.iteritems():
for letter in letters:
__by_dakuten[letter] = vowel
__to_vowels = PrintableDict()
for vowel, letters in __by_vowels.iteritems():
for letter in letters:
__to_vowels[letter] = vowel
def codepoint_range(start, end):
for val in range(start, end):
try:
yield unichr(val)
except ValueError:
# Sometimes certain codepoints can't be used on a machine
pass
def char_set(value):
if isinstance(value, list) or isinstance(value, tuple):
return codepoint_range(*value)
else:
return [value]
def unipairs(lst):
return PrintableList(reduce(lambda a, b: chain(a, b), map(char_set, lst)))
__KATAKANA = (
# Katakana: http://en.wikipedia.org/wiki/Katakana
(0x30A0, 0x30FF + 1),
(0x31F0, 0x31FF + 1),
(0x3200, 0x32FF + 1),
(0xFF00, 0xFFEF + 1),
)
__HIRAGANA = (
# Hiragana: http://en.wikipedia.org/wiki/Hiragana
(0x3040, 0x309F + 1),
(0x1B000, 0x1B0FF + 1),
)
__KANJI = (
(0x4e00, 0x9faf + 1),
)
__BONUS_KANA = (
u'〜',
)
KATAKANA = unipairs(__KATAKANA)
HIRAGANA = unipairs(__HIRAGANA)
KANA = PrintableList(KATAKANA + HIRAGANA + unipairs(__BONUS_KANA))
KANJI = unipairs(__KANJI)
d | ef __is_katakana(char):
return char in KATAKANA
def is_katakana(string):
for char in string:
if not __is_katakana(char):
return False
return True
def __is_h | iragana(char):
return char in HIRAGANA
def is_hiragana(string):
for char in string:
if not __is_hiragana(char):
return False
return True
def __is_kana(char):
return char in KANA
def is_kana(string):
for char in string:
if not __is_kana(char):
return False
return True
def __is_kanji(char):
return char in KANJI
def is_kanji(string):
for char in string:
if not __is_kanji(char):
return False
return True
def kana_minus_dakuten(char):
if is_katakana(char):
hira = kata2hira(char)
hira = __by_dakuten.get(hira, hira)
return hira2kata(hira)
else:
return __by_dakuten.get(char, char)
def kana_plus_dakuten(char):
yield char
is_kata = is_katakana(char)
if is_kata:
char = kata2hira(char)
for char in __to_dakuten.get(char, ''):
yield hira2kata(char) if is_kata else char
def kana_plus_mini(char):
yield char
is_kata = is_katakana(char)
if is_kata:
char = kata2hira(char)
for char in __to_mini.get(char, ''):
yield hira2kata(char) if is_kata else char
def extend_dakuten_reading(string):
if len(string) == 0:
yield ''
return
char = string[0]
for mult in kana_plus_dakuten(char):
yield mult + string[1:]
def extend_mini_reading(string):
if len(string) == 0:
yield ''
return
char = string[-1]
if char not in EXTENDABLE_MINIS:
yield string
return
for substr in kana_plus_mini(char):
yield string[:-1] + substr
def char_to_base_vowel(char):
char = kana_minus_dakuten(char)
translated = __to_vowels.get(char, False) or __to_vowels.get(hira2kata(char), False)
if translated is False:
raise Exception(u"Can't convert")
return translated
def all_to_hiragana(string):
out = u''
for index, char in enumerate(string):
if char == u'ー' or char == u'|':
char = char_to_base_vowel(out[-1])
char = kata2hira(char)
out += char
return out
if __name__ == u'__main__':
from tester import *
test_equal(kana_minus_dakuten(u'は'), u'は', u"No Dakuten failure")
test_equal(kana_minus_dakuten(u'ば'), u'は', u"No Dakuten failure")
test_equal(kana_minus_dakuten(u'ぱ'), u'は', u"No Dakuten failure")
test_equal(kana_minus_dakuten(u'ジ'), u'シ', u"Katakana failure")
test_equal(kana_minus_dakuten(u'本'), u'本', u"Kanji changed")
test_true(is_katakana(u'ハ'), u"Katakana check wrong")
test_true(is_katakana(u'ー'), u"Katakana check wrong")
test_true(is_katakana(u'ジ'), u"Katakana check wrong")
test_true(is_katakana(u'ッ'), u"Katakana check wrong")
test_true(not is_katakana(u'本'), u"Katakana Kanji check wrong")
test_true(not is_katakana(u'っ'), u"Katakana small hiragana check wrong")
test_true(not is_katakana(u'は'), u"Katakana hiragana wrong")
test_true(is_hiragana(u'っ'), u"Hiragana check wrong")
test_true(is_hiragana(u'つ'), u"Hiragana check wrong")
test_true(is_hiragana(u'を'), u"Hiragana check wrong")
test_true(not is_hiragana(u'本'), u"Hiragana Kanji check wrong")
test_true(not is_hiragana(u'ッ'), u"Hiragana small katakana check wrong")
test_true(not is_hiragana(u'ハ'), u"Hiragana katakana check wrong")
test_true(is_kana(u'っ'), u"Kana check wrong")
test_true(is_kana(u'つ'), u"Kana check wrong")
test_true(is_kana(u'を'), u"Kana check wrong")
test_true(is_kana(u'ッ'), u"Kana check wrong")
test_true(is_kana(u'ハ'), u"Kana check wrong")
test_true(is_kana(u'〜・'), u"Kana special check wrong")
test_true(not is_kana(u'本'), u"Kana check wrong")
test_equal(kana_minus_dakuten(u'は'), u'は')
test_equal(kana_minus_dakuten(u'ば'), u'は')
test_equal(kana_minus_dakuten(u'バ'), u'ハ')
test_equal(kana_minus_dakuten(u'本'), u'本')
test_equal(''.join(kana_plus_dakuten(u'は')), u'はばぱ')
test_equal(''.join(kana_plus_dakuten(u'本')), u'本')
test_equal(''.join(kana_plus_dakuten(u'シ')), u'シジ')
test_list_equal(extend_dakuten_reading(u'しゃし'), [u'しゃし', u'じゃし'])
test_list_equal(extend_mini_reading(u'し'), [u'し'])
test_list_equal(extend_mini_reading(u'いつ'), [u'いつ', u'いっ'])
test_equal(all_to_hiragana(u'ジータ'), u'じいた')
|
westurner/i3wm-formula | tests/test_i3wm-formula.py | Python | bsd-3-clause | 407 | 0.004914 | #!/usr/bin/env python
# -*- codi | ng: utf-8 -*-
"""
test_i3wm-formula
----------------------------------
Tests for `i3wm-formula` module.
"""
import unittest
fro | m i3wm-formula import i3wm-formula
class TestI3wm-formula(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main() |
benkonrath/transip-api | transip/service/webhosting.py | Python | mit | 2,545 | 0.00275 | """
Implementation of the WebhostingService API endpoint
"""
from transip.client import MODE_RW, Client
class WebhostingService(Client):
"""
Transip_WebhostingService
"""
def __init__(self, *args, **kwargs):
super().__init__('WebhostingService', *args, **kwargs)
def get_webhosting_domain_names(self):
"""
Transip_WebhostingService::getWebhostingDomainNames
"""
return self._simple_request('getWebhostingDomainNames')
def get_available_packages(self):
"""
Transip_WebhostingService::getAvailablePackages
"""
return self._simple_request('getAvailablePackages')
def get_info(self, domain):
"""
Transip_WebhostingService::getInfo
"""
return self._simple_request('getInfo', domain)
def get_available_upgrades(self, domain):
"""
Transip_WebhostingService::getAvailableUpgrades
"""
return self._simple_request('getAvailableUpgrades', domain)
def create_mailbox(self, domain, mailbox):
"""
Transip_WebhostingService::createMailBox
"""
return self._simple_request('createMailBox', domain, mailbox, mode=MODE_RW)
def set_mailbox_password(self, domain, mailbox, password):
"""
Transip_WebhostingService::setMailBoxPassword
"""
return self._simple_request('setMailBoxPassword', domain, mailbox, password, mode=MODE_RW)
def update_mailbox(self, domain, mailbox):
"""
Transip_Webh | ostingService::modifyMailBox
"""
return self._simple_request('modifyMailB | ox', domain, mailbox, mode=MODE_RW)
def delete_mailbox(self, domain, mailbox):
"""
Transip_WebhostingService::deleteMailBox
"""
return self._simple_request('deleteMailBox', domain, mailbox, mode=MODE_RW)
def create_mail_forward(self, domain, mailforward):
"""
Transip_WebhostingService::createMailForward
"""
return self._simple_request('createMailForward', domain, mailforward, mode=MODE_RW)
def update_mail_forward(self, domain, mailforward):
"""
Transip_WebhostingService::modifyMailForward
"""
return self._simple_request('modifyMailForward', domain, mailforward, mode=MODE_RW)
def delete_mail_forward(self, domain, mailforward):
"""
Transip_WebhostingService::deleteMailForward
"""
return self._simple_request('deleteMailForward', domain, mailforward, mode=MODE_RW)
|
Orav/kbengine | kbe/src/lib/python/Lib/test/test_zipimport.py | Python | lgpl-3.0 | 18,625 | 0.000859 | import sys
import os
import marshal
import importlib.util
import struct
import time
import unittest
from test import support
from zipfile import ZipFile, ZipInfo, ZIP_STORED, ZIP_DEFLATED
import zipimport
import linecache
import doctest
import inspect
import io
from traceback import extract_tb, extract_stack, print_tb
test_src = """\
def get_name():
return __name__
def get_file():
return __file__
"""
test_co = compile(test_src, "<???>", "exec")
raise_src = 'def do_raise(): raise TypeError\n'
def make_pyc(co, mtime, size):
data = marshal.dumps(co)
if type(mtime) is type(0.0):
# Mac mtimes need a bit of special casing
if mtime < 0x7fffffff:
mtime = int(mtime)
else:
mtime = int(-0x100000000 + int(mtime))
pyc = (importlib.util.MAGIC_NUMBER +
struct.pack("<ii", int(mtime), size & 0xFFFFFFFF) + data)
return pyc
def module_path_to_dotted_name(path):
return path.replace(os.sep, '.')
NOW = time.time()
test_pyc = make_pyc(test_co, NOW, len(test_src))
TESTMOD = "ziptestmodule"
TESTPACK = "ziptestpackage"
TESTPACK2 = "ziptestpackage2"
TEMP_ZIP = os.path.abspath("junk95142.zip")
pyc_file = importlib.util.cache_from_source(TESTMOD + '.py')
pyc_ext = ('.pyc' if __debug__ else '.pyo')
class ImportHooksBaseTestCase(unittest.TestCase):
def setUp(self):
self.path = sys.path[:]
self.meta_path = sys.meta_path[:]
self.path_hooks = sys.path_hooks[:]
sys.path_importer_cache.clear()
self.modules_before = support.modules_setup()
def tearDown(self):
sys.path[:] = self.path
sys.meta_path[:] = self.meta_path
sys.path_hooks[:] = self.path_hooks
sys.path_importer_cache.clear()
support.modules_cleanup(*self.modules_before)
class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
compression = ZIP_STORED
def setUp(self):
# We're reusing the zip archive path, so we must clear the
# cached directory info and linecache
linecache.clearcache()
zipimport._zip_directory_cache.clear()
ImportHooksBaseTestCase.setUp(self)
def doTest(self, expected_ext, files, *modules, **kw):
z = ZipFile(TEMP_ZIP, "w")
try:
for name, (mtime, data) in files.items():
zinfo = ZipInfo(name, time.localtime(mtime))
zinfo.compress_type = self.compression
z.writestr(zinfo, data)
z.close()
stuff = kw.get("stuff", None)
if stuff is not None:
# Prepend 'stuff' to the start of the zipfile
with open(TEMP_ZIP, "rb") as f:
data = f.read()
with open(TEMP_ZIP, "wb") as f:
f.write(stuff)
f.write(data)
sys.path.insert(0, TEMP_ZIP)
mod = __import__(".".join(modules), globals(), locals(),
["__dummy__"])
call = kw.get('call')
if call is not None:
call(mod)
if expected_ext:
file = mod.get_file()
self.assertEqual(file, os.path.join(TEMP_ZIP,
*modules) + expected_ext)
finally:
z.close()
os.remove(TEMP_ZIP)
def testAFakeZlib(self):
#
# This could cause a stack overflow before: importing zlib.py
# from a compressed archive would cause zlib to be imported
# which would find zlib.py in the archive, which would... etc.
#
# This test *must* be executed first: it must be the first one
# to trigger zipimport to import zlib (zipimport caches the
# zlib.decompress function object, after which the problem being
# tested here wouldn't be a problem anymore...
# (Hence the 'A' in the test method name: to make it the first
# item in a list sorted by name, like unittest.makeSuite() does.)
#
# This test fails on platforms on which the zlib module is
# statically linked, but the problem it tests for can't
# occur in that case (builtin modules are always found first),
# so we'll simply skip it then. Bug #765456.
#
if "zlib" in sys.builtin_module_names:
self.skipTest('zlib is a builtin module')
if "zlib" in sys.modules:
del sys.modules["zlib"]
files = {"zlib.py": (NOW, test_src)}
try:
self.doTest(".py", files, "zlib")
except ImportError:
if self.compression != ZIP_DEFLATED:
self.fail("expected test to not raise ImportError")
else:
if self.compression != ZIP_STORED:
self.fail("expected test to raise ImportError")
def testPy(self):
files = {TESTMOD + ".py": (NOW, test_src)}
self.doTest(".py", files, TESTMOD)
def testPyc(self):
files = {TESTMOD + pyc_ext: (NOW, test_pyc)}
self.doTest(pyc_ext, files, TESTMOD)
def testBoth(self):
files = {TESTMOD + ".py": (NOW, test_src),
TESTMOD + pyc_ext: (NOW, test_pyc)}
self.doTest(pyc_ext, files, TESTMOD)
def testEmptyPy(self):
files = {TESTMOD + ".py": (NOW, "")}
self.doTest(None, files, TESTMOD)
def testBadMagic(self):
# make pyc magic word invalid, forcing loading from .py
badmagic_pyc = bytearray(test_pyc)
badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
files = {TESTMOD + ".py": (NOW, test_src),
TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
self.doTest(".py", files, TESTMOD)
def testBadMagic2(self):
# make pyc magic word invalid, causing an ImportError
badmagic_pyc = bytearray(test_pyc)
badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
files = {TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
try:
self.doTest(".py", files, TESTMOD)
except ImportError:
pass
else:
self.fail("expected ImportError; import from bad pyc")
def testBadMTime(self):
badtime_pyc = bytearray(test_pyc)
# flip the second bit -- not the first as that one isn't stored in the
# .py's mtime in the zip archive.
| badtime_pyc[7] ^= 0x02
files = {TESTMOD + ".py": (NOW, test_src),
TESTMOD + pyc_ext: (NOW, badtime_pyc)}
self.doTest(".py", files, TESTMOD)
def testPackage(self):
packdir = TESTPACK + os.sep
files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
packdir + TESTMOD + pyc_ext: (NOW, test_pyc)}
self.doTest(pyc_ext, files, TESTPACK, TESTMOD)
d | ef testDeepPackage(self):
packdir = TESTPACK + os.sep
packdir2 = packdir + TESTPACK2 + os.sep
files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
self.doTest(pyc_ext, files, TESTPACK, TESTPACK2, TESTMOD)
def testZipImporterMethods(self):
packdir = TESTPACK + os.sep
packdir2 = packdir + TESTPACK2 + os.sep
files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
z = ZipFile(TEMP_ZIP, "w")
try:
for name, (mtime, data) in files.items():
zinfo = ZipInfo(name, time.localtime(mtime))
zinfo.compress_type = self.compression
zinfo.comment = b"spam"
z.writestr(zinfo, data)
z.close()
zi = zipimport.zipimporter(TEMP_ZIP)
self.assertEqual(zi.archive, TEMP_ZIP)
self.assertEqual(zi.is_package(TESTPACK), True)
|
daviferreira/leticiastallone.com | leticiastallone/blog/migrations/0001_initial.py | Python | mit | 1,393 | 0.006461 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Post'
db.create_table(u'blog_post', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=60)),
('body', self.gf('django.db.models.fields.TextField')()),
('tags', self.gf('django.db.models.fields.TextField')()),
('created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
))
db.send_create_signal(u'blog', ['Post'])
def backwards(self, orm):
# Deleting model 'Post'
db.delete_table(u'blog_post')
models = {
u'blog.post': {
'Meta': {'object_name': 'Post'},
'body': ('django.db.models.fields.TextField', [], {}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'Tru | e'}),
u'id': ('django | .db.models.fields.AutoField', [], {'primary_key': 'True'}),
'tags': ('django.db.models.fields.TextField', [], {}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '60'})
}
}
complete_apps = ['blog'] |
1024inc/django-rq | django_rq/management/commands/rqenqueue.py | Python | mit | 1,223 | 0 | from distutils.version import LooseVersion
from django.core.management.base import BaseCommand
from django.utils.version import | get_version
from django_rq import get_queue
class Command(BaseCommand):
"""
Queue a function with the given arguments.
"""
help = __doc__
args = '<function arg arg ...>'
def add_arguments(self, parser):
parser.add_argument('--queue', '-q', dest='queue', default='default',
help= | 'Specify the queue [default]')
parser.add_argument('--timeout', '-t', type=int, dest='timeout',
help='A timeout in seconds')
if LooseVersion(get_version()) >= LooseVersion('1.9'):
parser.add_argument('args', nargs='*')
def handle(self, *args, **options):
"""
Queues the function given with the first argument with the
parameters given with the rest of the argument list.
"""
verbosity = int(options.get('verbosity', 1))
timeout = options.get('timeout')
queue = get_queue(options.get('queue'))
job = queue.enqueue_call(args[0], args=args[1:], timeout=timeout)
if verbosity:
print('Job %s created' % job.id)
|
enigmampc/catalyst | catalyst/exchange/exchange_errors.py | Python | apache-2.0 | 10,006 | 0 | import sys
import traceback
from catalyst.errors import ZiplineError
def silent_except_hook(exctype, excvalue, exctraceback):
if exctype in [PricingDataBeforeTradingError, PricingDataNotLoadedError,
SymbolNotFoundOnExchange, NoDataAvailableOnExchange,
ExchangeAuthEmpty]:
fn = traceback.extract_tb(exctraceback)[-1][0]
ln = traceback.extract_tb(exctraceback)[-1][1]
print("Error traceback: {1} (line {2})\n"
"{0.__name__}: {3}".format(exctype, fn, ln, excvalue))
else:
sys.__excepthook__(exctype, excvalue | , exctraceback)
sy | s.excepthook = silent_except_hook
class ExchangeRequestError(ZiplineError):
msg = (
'Request failed: {error}'
).strip()
class ExchangeRequestErrorTooManyAttempts(ZiplineError):
msg = (
'Request failed: {error}, giving up after {attempts} attempts'
).strip()
class ExchangeBarDataError(ZiplineError):
msg = (
'Unable to retrieve bar data: {data_type}, ' +
'giving up after {attempts} attempts: {error}'
).strip()
class ExchangePortfolioDataError(ZiplineError):
msg = (
'Unable to retrieve portfolio data: {data_type}, ' +
'giving up after {attempts} attempts: {error}'
).strip()
class ExchangeTransactionError(ZiplineError):
msg = (
'Unable to execute transaction: {transaction_type}, ' +
'giving up after {attempts} attempts: {error}'
).strip()
class ExchangeNotFoundError(ZiplineError):
msg = (
'Exchange {exchange_name} not found. Please specify exchanges '
'supported by Catalyst and verify spelling for accuracy.'
).strip()
class ExchangeAuthNotFound(ZiplineError):
msg = (
'Please create an auth.json file containing the api token and key for '
'exchange {exchange}. Place the file here: {filename}'
).strip()
class ExchangeAuthEmpty(ZiplineError):
msg = (
'Please enter your API token key and secret for exchange {exchange} '
'in the following file: {filename}'
).strip()
class RemoteAuthEmpty(ZiplineError):
msg = (
'Please enter your API token key and secret for the remote server '
'in the following file: {filename}'
).strip()
class ExchangeSymbolsNotFound(ZiplineError):
msg = (
'Unable to download or find a local copy of symbols.json for exchange '
'{exchange}. The file should be here: {filename}'
).strip()
class AlgoPickleNotFound(ZiplineError):
msg = (
'Pickle not found for algo {algo} in path {filename}'
).strip()
class InvalidHistoryFrequencyAlias(ZiplineError):
msg = (
'Invalid frequency alias {freq}. Valid suffixes are M (minute) '
'and D (day). For example, these aliases would be valid '
'1M, 5M, 1D.'
).strip()
class InvalidHistoryFrequencyError(ZiplineError):
msg = (
'Frequency {frequency} not supported by the exchange.'
).strip()
class UnsupportedHistoryFrequencyError(ZiplineError):
msg = (
'{exchange} does not support candle frequency {freq}, please choose '
'from: {freqs}.'
).strip()
class InvalidHistoryTimeframeError(ZiplineError):
msg = (
'CCXT timeframe {timeframe} not supported by the exchange.'
).strip()
class MismatchingFrequencyError(ZiplineError):
msg = (
'Bar aggregate frequency {frequency} not compatible with '
'data frequency {data_frequency}.'
).strip()
class InvalidSymbolError(ZiplineError):
msg = (
'Invalid trading pair symbol: {symbol}. '
'Catalyst symbols must follow this convention: '
'[Base Currency]_[Quote Currency]. For example: eth_usd, btc_usd, '
'neo_eth, ubq_btc. Error details: {error}'
).strip()
class InvalidOrderStyle(ZiplineError):
msg = (
'Order style {style} not supported by exchange {exchange}.'
).strip()
class CreateOrderError(ZiplineError):
msg = (
'Unable to create order on exchange {exchange} {error}.'
).strip()
class OrderNotFound(ZiplineError):
msg = (
'Order {order_id} not found on exchange {exchange}.'
).strip()
class OrphanOrderError(ZiplineError):
msg = (
'Order {order_id} found in exchange {exchange} but not tracked by '
'the algorithm.'
).strip()
class OrphanOrderReverseError(ZiplineError):
msg = (
'Order {order_id} tracked by algorithm, but not found in exchange '
'{exchange}.'
).strip()
class OrderCancelError(ZiplineError):
msg = (
'Unable to cancel order {order_id} on exchange {exchange} {error}.'
).strip()
class SidHashError(ZiplineError):
msg = (
'Unable to hash sid from symbol {symbol}.'
).strip()
class QuoteCurrencyNotFoundError(ZiplineError):
msg = (
'Algorithm quote currency {quote_currency} not found in account '
'balances on {exchange}: {balances}'
).strip()
class MismatchingQuoteCurrencies(ZiplineError):
msg = (
'Unable to trade with quote currency {quote_currency} when the '
'algorithm uses {algo_currency}.'
).strip()
class MismatchingQuoteCurrenciesExchanges(ZiplineError):
msg = (
'Unable to trade with quote currency {quote_currency} when the '
'exchange {exchange_name} users {exchange_currency}.'
).strip()
class SymbolNotFoundOnExchange(ZiplineError):
"""
Raised when a symbol() call contains a non-existent symbol.
"""
msg = ('Symbol {symbol} not found on exchange {exchange}. '
'Choose from: {supported_symbols}').strip()
class BundleNotFoundError(ZiplineError):
msg = ('Unable to find bundle data for exchange {exchange} and '
'data frequency {data_frequency}.'
'Please ingest some price data.'
'See `catalyst ingest-exchange --help` for details.').strip()
class TempBundleNotFoundError(ZiplineError):
msg = ('Temporary bundle not found in: {path}.').strip()
class EmptyValuesInBundleError(ZiplineError):
msg = ('{name} with end minute {end_minute} has empty rows '
'in ranges: {dates}').strip()
class PricingDataBeforeTradingError(ZiplineError):
msg = ('Pricing data for trading pairs {symbols} on exchange {exchange} '
'starts on {first_trading_day}, but you are either trying to trade '
'or retrieve pricing data on {dt}. Adjust your dates accordingly.'
).strip()
class PricingDataNotLoadedError(ZiplineError):
msg = ('Missing data for {exchange} {symbols} in date range '
'[{start_dt} - {end_dt}]'
'\nPlease run: `catalyst ingest-exchange -x {exchange} -f '
'{data_frequency} -i {symbol_list}`. See catalyst documentation '
'for details.').strip()
class PricingDataValueError(ZiplineError):
msg = ('Unable to retrieve pricing data for {exchange} {symbol} '
'[{start_dt} - {end_dt}]: {error}').strip()
class DataCorruptionError(ZiplineError):
msg = (
'Unable to validate data for {exchange} {symbols} in date range '
'[{start_dt} - {end_dt}]. The data is either corrupted or '
'unavailable. Please try deleting this bundle:'
'\n`catalyst clean-exchange -x {exchange}\n'
'Then, ingest the data again. Please contact the Catalyst team if '
'the issue persists.'
).strip()
class ApiCandlesError(ZiplineError):
msg = (
'Unable to fetch candles from the remote API: {error}.'
).strip()
class NoDataAvailableOnExchange(ZiplineError):
msg = (
'Requested data for trading pair {symbol} is not available on '
'exchange {exchange} '
'in `{data_frequency}` frequency at this time. '
'Check `http://enigma.co/catalyst/status` for market coverage.'
).strip()
class NoValueForField(ZiplineError):
msg = (
'Value not found for field: {field}.'
).strip()
class OrderTypeNotSupported(ZiplineError):
msg = (
'Order type `{order_type}` currently not supported by Catalyst. '
'Please use `limit` or `market` orders only.'
).strip()
cla |
yancz1989/cancer | scan.py | Python | mit | 2,610 | 0.012261 | # -*- coding: utf-8 -*-
# @Author: yancz1989
# @Date: 2017-01-17 23:43:18
# @Last Modified by: yancz1989
# @Last Modified time: 2017-02-22 20:33:29
import utilities as util
from utilities import parse_image_file, filterBoxes, voxel_2_world, mkdir
import numpy as np
import os
import json
import sys
from PIL import Image, ImageDraw
import SimpleITK as sitk
from env import *
def generate_scan_image(subset):
list_dirs = os.walk(TRUNK_DIR + subset)
jsobjs = []
output_dir = SAMPLE_DIR + subset
mkdir(output_dir)
for root, dirs, files in list_dirs:
for f in files:
if f.lower().endswith('mhd'):
key = os.path.split | ext(f)[0]
numpyImage, numpyOrigin, numpySpacing = (
util.load_itk_image(
os.path.join(root, f)))
for z in range(numpyImage.shape[0]):
patch = numpyImage[z, 0:512, 0:512]
patch = util.normalizePlanes(patch)
im = | Image.fromarray(patch * 255).convert('L')
output_filename = (
subset + "-" + key + "-" + str(z) + "-scan.bmp")
print(subset + '/' + output_filename)
im.save(os.path.join(
output_dir, output_filename))
jsobjs.append({
"image_path": subset + '/' + output_filename,
"rects":[]
}
)
with open(META_DIR + subset + '-scan.json', 'w') as f:
json.dump(jsobjs, f)
def get_image_map(data_root, input_file, threshold):
result_map = {}
with open(input_file) as f:
result_list = json.load(f)
for it in result_list:
key, subset, z = parse_image_file(it['file'])
src_file = os.path.join(
data_root, subset, key + ".mhd")
boxes = filterBoxes(it['box'], threshold)
if not result_map.get(src_file):
result_map[src_file] = []
result_map[src_file].append((key, z, boxes))
return result_map
def generate_result(result_map, output_file):
with open(output_file) as fout:
fout.write("seriesuid,coordX,coordY,coordZ,probability\n")
for fkey, val in result_map.items():
itkimage = sitk.ReadImage(fkey)
for it in val:
key, z, boxes = val
for box in boxes:
world_box = voxel_2_world(
[z, box[1], box[0]], itkimage)
csv_line = key + "," + str(world_box[2]) + "," + str(world_box[1]) + "," + str(world_box[0]) + "," + str(box[4])
fout.write(csv_line + "\n")
if __name__ == '__main__':
if sys.argv[1] == 'gen':
generate_scan_image(sys.argv[2])
else:
result_map = get_image_map(TRUNK_DIR, sys.argv[2], 0.01)
generate_result(result_map, OUTPUT_FILE) |
unifispot/unifispot-free | manage.py | Python | mit | 510 | 0.001961 | #! flask/bin/python
from os.path import abspath
fr | om flask import current_app
from flask.ext.script import Manager
from flask.ext.assets import ManageAssets
from flask.ext.migrate import Migrate, MigrateCommand
from bluespot import create_app
from bluespot.extensions import db
| app = create_app(mode='development')
manager = Manager(app)
manager.add_command('assets', ManageAssets())
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
manager.run()
#app.run(host='0.0.0.0',debug = True)
|
adamatus/boldsim | benchmark/benchmark.py | Python | gpl-2.0 | 17,981 | 0.010344 | #!/usr/bin/env python
import numpy as np
import boldsim.sim as sim
import timeit
import argparse
parser = argparse.ArgumentParser(description='Run BOLDsim benchmarks.',
epilog='By default no benchmarks will be run, so make sure to specify one!')
parser.add_argument('-a', '--all', action='store_true', help='Run the full suite of benchmarks')
parser.add_argument('-v','--sim-vol', action='store_true', help='Run the simVOL benchmarks')
parser.add_argument('-t','--sim-ts', action='store_true', help='Run the simTS benchmarks')
parser.add_argument('-n', '--noise', action='store_true', help='Run the full suite of noise benchmarks')
parser.add_argument('--stimfunc', action='store_true', help='Run the stimfunction benchmarks')
parser.add_argument('--specdesign', action='store_true', help='Run the specifydesign benchmarks')
parser.add_argument('--specregion', action='store_true', help='Run the specifyregion benchmarks')
parser.add_argument('--systemnoise', action='store_true', help='Run the systemnoise benchmarks')
parser.add_argument('--lowfreq', action='store_true', help='Run the lowfreqnoise benchmarks')
parser.add_argument('--phys', action='store_true', help='Run the physnoise benchmarks')
parser.add_argument('--task-related', action='store_true', help='Run the task-related noise benchmarks')
parser.add_argument('--temporal', action='store_true', help='Run the temporally correlated noise benchmarks')
parser.add_argument('--spatial', action='store_true', help='Run the spatially correlated noise benchmarks')
def run_test(title, test, setup, repeats=10):
print '{:>60}'.format(title+':'),
x = timeit.Timer(test, setup=setup).repeat(repeats,1)
print '{:>9.3f} {:>9.3f} {:>9.3f} {:9d}'.format(min(x), np.mean(x), max(x), repeats)
def print_header(title):
print '\n{:<60}'.format(title)
print '{:<61}{:>9} {:>9} {:>9} {:>9}'.format('', 'min','mean','max','reps')
setup = """
import numpy as np
from boldsim import sim
"""
really_slow = 1
slow = 3
normal = 10
#################
def benchmark_stimfunction():
print_header('Stimfunction benchmarks')
run_test('Few events, 200 TRs',
"s = sim.stimfunction(400, [2, 12], 2, .1)",
setup=setup)
run_test('More events, 200 TRs',
"s = sim.stimfunction(400, [1,2,3,4,5,6,7,8,9,10,11,12,13,14], 2, .1)",
setup=setup)
run_test('More events, 2000 TRs',
"s = sim.stimfunction(4000, onsets, 2, .1)",
setup=setup + """
onsets = np.arange(1995)
""")
##################
def benchmark_specifydesign():
print_header('Specifydesign benchmarks')
setup_short_few = setup + """
total_time = 400
onsets = [[0, 30, 60], [25, 75]]
dur = [[10],[3]]
effect_sizes = [3, 10]
acc = .5
"""
setup_long_few = setup + """
total_time = 4000
onsets = [[0, 30, 60], [550, 650]]
dur = [[10],[3]]
effect_sizes = [3, 10]
acc = .5
"""
setup_long_many = setup + """
total_time = 4000
onsets = [np.arange(1,979,20), np.arange(2,979,19)]
dur = [[10],[3]]
effect_sizes = [3, 10]
acc = .5
"""
setup_long_many_conds = setup + """
total_time = 4000
onsets = [np.arange(1,979,20), np.arange(2,979,19),
np.arange(3,979,18), np.arange(4,979,17),
np.arange(5,979,16), np.arange(6,979,15),
np.arange(7,979,14), np.arange(8,979,13),
np.arange(9,979,12), np.arange(10,979,11),
]
dur = [[10],[9],[8],[7],[6],[5],[4],[3],[2],[1]]
effect_sizes = [3, 10, 2, 6, 7, 1, 5, 4, 9, 8]
acc = .5
"""
titles = ['2 conds, 200 TRs, few events, {}',
'2 conds, 2000 TRs, few events, {}',
'2 conds, 2000 TRs, many events, {}',
'10 conds, 2000 TRs, many events, {}',
]
setups = [setup_short_few, setup_long_few, setup_long_many, setup_long_many_conds]
for hrf in ['none','gamma','double-gamma']:
for title, specific_setup in zip(titles, setups):
run_test(title.format(hrf),
"""d = sim.specifydesign(total_time, onsets=onsets, durations=dur, accuracy=acc,
effect_sizes=effect_sizes, TR=2, conv='{}')""".format(hrf),
setup=specific_setup, repeats=normal)
def benchmark_specifyregion():
print_header('Specifyregion benchmarks')
for shape in ['cube','sphere','manual']:
run_test('Toy space [10x10], 2 regions, {}'.format(shape),
"""s = sim.specifyregion(dim=[10,10],coord=[[1,1],[7,7]],radius=[1,2],
form='{}', fading=0)""".format(shape),
setup=setup, repeats=normal)
run_test('Highres Slice [256x256], 2 regions, {}'.format(shape),
"""s = sim.specifyregion(dim=[256,256],coord=[[1,1],[240,240]],radius=[13,22],
form='{}', fading=0)""".format(shape),
setup=setup, repeats=normal)
for fade in [0, .5, 1]:
run_test('Highres slice [256x256], 50 regions, fade {}, {}'.format(fade, shape),
"""s = sim.specifyregion(dim=[256,256],coord=coords,radius=radii,
form='{}', fading={})""".format(shape,fade),
repeats=slow, setup=setup + """
coords = [[np.random.randint(low=0, high=255),
np.random.randint(low=0, high=255)] for x in range(50)]
radii = [np.random.randint(low=1, high=20) for x in range(50)]
""")
for fade in [0, .5, 1]:
run_test('Wholebrain [64x64x32], 50 regions, fade {}, {}'.format(fade, shape),
"""s = sim.specifyregion(dim=[64,64,32],coord=coords,radius=radii,
form='{}', fading={})""".format(shape, fade),
repeats=really_slow, setup=setup + """
coords = [[np.random.randint(low=0, high=63),
np.random.randint(low=0, high=63),
np.random.randint(low=0, high=31)] for x in range(50)]
radii = [np.random.randint(low=1, high=20) for x in range(50)]""")
def benchmark_systemnoise():
print_header('System noise benchmarks')
for noise_type in ['gaussian','rayleigh']:
run_test('Single voxel, 200 TRs, {}'.format(noise_type),
"""s = sim.system_noise(nscan=200, sigma=1.5,
dim=(1,), noise_dist='{}')""".format(noise_type),
setup=setup, repeats=normal)
run_test('Single voxel, 200000 TRs, {}'.format(noise_type),
"""s = sim.system_noise(nscan=200000, sigma=1.5,
dim=(1,), noise_dist='{}')""".format(noise_type),
setup=setup, repeats=normal)
run_test('Wholebrain voxels [64x64x32], 200 TRs, {}'.format(noise_type),
"""s = sim.system_noise(nscan=200, sigma=1.5,
dim=(64,64,32), noise_dist='{}')""".format(noise_type),
setup=setup, repeats=slow)
def benchmark_lowfreqnoise():
print_header('Low frequency noise benchmarks')
run_test('Single voxel, 200 TRs',
'noise = sim.lowfreqdrift(nscan=200, freq=128.0, dim=(1,))',
setup=setup, repeats=normal)
run_test('Single voxel, 2000 TRs',
'noise = sim.lowfreqdrift(nscan=2000, freq=128.0, dim=(1,))',
setup=setup, repeats=normal)
run_test('Whole slice [64x64], 200 TRs',
'noise = sim.lowfreqdrift(nscan=200, freq=128.0, dim=(64,64))',
setup=setup, repeats=really_slow)
run_test('Wholebrain [64x64x32], 200 TRs',
'noise = sim.lowfreqdrift(nscan=200, freq=128.0, dim=(64,64,32))',
setup=setup, repeats=really_slow)
def benchmark_physnoise():
print_header('Physiological noise benchmarks')
run_test('Single voxel, 200 TRs',
'noise = sim.physnoise(nscan=200, dim=(1,))',
setup=setup)
run_test('Single voxel, 2000 TRs',
'noise = sim.physnoise(nscan=2000, dim=(1,))' | ,
setup=setup)
run_test('Wholebrain [64x64x32], 200 TRs',
'noise = sim.phys | noise(nscan=200, |
Bedrock02/General-Coding | Sorting/mergesort.py | Python | mit | 1,720 | 0.05 | #!/usr/bin/env python2.7
#Author:Steven Jimenez
#Subject: Python Programming
#HW 1
#Merge Sort that Calls a non-recursive function to sort lists
def mergesort(a):
#if singleton return singleton
if len(a)==1:
return a
#find mindpoint of list
n = len(a)/2
#split the list into sorted halves. left-Right
left = mergesort(a[:n])
right = mergesort(a[n:])
#Combine sorted halves
return mergelists(left,right)
#Takes in unsorted lists and returns a sorted list
def mergelists(lft,rgt):
#New list that will be sorted
sorted = []
#While the lists are not empty compare and sort them in new list
while len(lft) and len(rgt):
if lft[0] < rgt[0]:
sorted.append(lft.pop(0))
else:
sorted.append(rgt.pop(0 | ))
#If one of the lists are empty, send the non empty list to the new list
if len(lft):
sorted.extend(lft);
if len(rgt):
sorted.extend(rgt)
return sorted
#Merge Sort that calls a recursive function to sort list
def mergesort2(a):
#If list is a singleton return singleton
if len(a)==1:
return a
#Find midpoint of lists
n = le | n(a)/2
#Divide current list into two halves and call function to sort
left = mergesort2(a[:n])
right = mergesort2(a[n:])
#Bring together the new sorted lists
return mergelists2(left,right)
def mergelists2(lft,rgt):
#If one list is empty return the other
if lft == []:
return rgt
if rgt == []:
return lft
#Find which element is the lesser of the two elements
#Send that element to the array and continue merging the rest
if lft[0] < rgt[0]:
return [lft[0]] + mergelists2(lft[1:],rgt)
else:
return [rgt[0]]+ mergelists2(lft,rgt[1:])
|
liqd/adhocracy4 | adhocracy4/comments/serializers.py | Python | agpl-3.0 | 7,379 | 0 | import warnings
from django.conf import settings
from django.utils.translation import gettext as _
from rest_framework import serializers
from rest_framework.utils import model_meta
from .models import Comment
class CommentSerializer(serializers.ModelSerializer):
"""Attention: This class is deprecated, use
comments_async.serializers.CommentSerializer instead
"""
user_name = serializers.SerializerMethodField()
user_profile_url = serializers.SerializerMethodField()
is_deleted = serializers.SerializerMethodField()
ratings = serializers.SerializerMethodField()
is_moderator = serializers.SerializerMethodField()
class Meta:
model = Comment
read_only_fields = ('modified', 'created', 'id',
'user_name', 'ratings', 'content_type',
'object_pk', 'last_discussed',
'is_moderator_marked')
exclude = ('creator', 'is_blocked')
def to_representation(self, instance):
"""
Gets the categories and adds them along with their values
to a dictionary
"""
warnings.warn(
"comments.serializers.CommentSerializer is deprecated, "
"use comments_async.serializers.CommentSerializer instead",
DeprecationWarning
)
ret = super().to_representation(instance)
categories = {}
if ret['comment_categories']:
category_choices = getattr(settings,
'A4_COMMENT_CATEGORIES', '')
if category_choices:
category_choices = dict((x, str(y)) for x, y
in category_choices)
category_list = ret['comment_categories'].strip('[]').split(',')
for category in category_list:
if category in category_choices:
categories[category] = category_choices[category]
else:
categories[category] = category
ret['comment_categories'] = categories
return ret
def to_internal_value(self, data):
warnings.warn(
"comments.serializers.CommentSerializer is deprecated, "
"use comments_async.serializers.CommentSerializer instead",
DeprecationWarning
)
data = super().to_internal_value(data)
if 'comment_categories' in data:
value = data.get('comment_categories')
if value == '' or value == '[]':
raise serializers.ValidationError({
'comment_categories': _('Please choose a cate | gory')
})
return data
def get_user_name(self, obj):
"""
Don't show username if comment is marked removed or censored
"""
if(obj.is_censored or obj.is_removed):
return _('unknown user')
return str(obj.creator.username)
def get_user_profile_url(self, obj):
if obj.is_censored or obj.is_removed:
return ''
try:
return obj.creator.get_absolute_url()
except A | ttributeError:
return ''
def get_is_moderator(self, obj):
return obj.project.has_moderator(obj.creator)
def get_is_deleted(self, obj):
"""
Returns true is one of the flags is set
"""
return (obj.is_censored or obj.is_removed)
def get_ratings(self, comment):
"""
Gets positve and negative rating count as well as
info on the request users rating
"""
user = self.context['request'].user
positive_ratings = comment.ratings.filter(value=1).count()
negative_ratings = comment.ratings.filter(value=-1).count()
if user.is_authenticated:
user_rating = comment.ratings.filter(creator=user).first()
else:
user_rating = None
if user_rating:
user_rating_value = user_rating.value
user_rating_id = user_rating.pk
else:
user_rating_value = None
user_rating_id = None
result = {
'positive_ratings': positive_ratings,
'negative_ratings': negative_ratings,
'current_user_rating_value': user_rating_value,
'current_user_rating_id': user_rating_id
}
return result
class ThreadSerializer(CommentSerializer):
"""
Serializes a comment including child comment (replies).
Attention: This class is deprecated, use
comments_async.serializers.ThreadSerializer instead
"""
child_comments = CommentSerializer(many=True, read_only=True)
class CommentModerateSerializer(serializers.ModelSerializer):
def to_representation(self, instance):
"""
Create a dictionary form categories.
Gets the categories and adds them along with their values
to a dictionary.
"""
ret = super().to_representation(instance)
categories = {}
if ret['comment_categories']:
category_choices = getattr(settings,
'A4_COMMENT_CATEGORIES', '')
if category_choices:
category_choices = dict((x, str(y)) for x, y
in category_choices)
category_list = ret['comment_categories'].strip('[]').split(',')
for category in category_list:
if category in category_choices:
categories[category] = category_choices[category]
else:
categories[category] = category
ret['comment_categories'] = categories
return ret
def to_internal_value(self, data):
data = super().to_internal_value(data)
if 'comment_categories' in data:
value = data.get('comment_categories')
if value == '' or value == '[]':
raise serializers.ValidationError({
'comment_categories': _('Please choose a category')
})
return data
def update(self, instance, validated_data):
serializers.raise_errors_on_nested_writes('update', self,
validated_data)
info = model_meta.get_field_info(instance)
# Simply set each attribute on the instance, and then save it.
# Note that unlike `.create()` we don't need to treat many-to-many
# relationships as being a special case. During updates we already
# have an instance pk for the relationships to be associated with.
for attr, value in validated_data.items():
if attr in info.relations and info.relations[attr].to_many:
field = getattr(instance, attr)
field.set(value)
else:
setattr(instance, attr, value)
instance.save(ignore_modified=True)
return instance
class Meta:
model = Comment
fields = ('is_moderator_marked', 'modified', 'created', 'id',
'content_type', 'object_pk', 'last_discussed', 'comment',
'comment_categories')
read_only_fields = ('modified', 'created', 'id', 'content_type',
'object_pk', 'last_discussed', 'comment',
'comment_categories')
|
SCPR/kpcc_backroom_handshakes | election_registrar/migrations/0006_election_election_kpcc_page.py | Python | mit | 544 | 0.001838 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-03-07 20:43
from __future__ import uni | code_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('election_registrar', '0005_auto_20170307_1104'),
]
operations = [
migrations.AddField(
model_name='election',
name='election_kpcc_page',
field=models | .URLField(blank=True, max_length=1024, null=True, verbose_name=b'URL on KPCC.org hosting results'),
),
]
|
pablocarderam/genetargeter | gRNAScores/azimuth/models/DNN.py | Python | mit | 3,012 | 0.001328 | # from copy import deepcopy
#
# import numpy as np
# import theanets
#
# # from ke | ras.wrappers import scikit_learn
# from scipy.stats import spearmanr
# from sklearn.model_selection import StratifiedKFold
# from sklearn.preprocessing import LabelEncoder
#
# from .. import predict
#
#
# def DNN_on_fold(train, test, y_all, X, learn_options):
# y = np.array(y_all[learn_options["DNN target variable"]].values, dtype=float)
# y_train, X_train = y[train][:, None], X[train]
# y_test, X_test = y[test][:, None], X[test]
#
# | num_hidden_layers = [1] # , 2, 3]
# num_units = [2] # , 5, 8, 10, 15, 20, 25, 30, 40, 50, 60]
# accuracies = np.zeros((len(num_hidden_layers), len(num_units)))
# best_score = None
# best_model = None
#
# for i, hl in enumerate(num_hidden_layers):
# for j, nu in enumerate(num_units):
# architecture = np.zeros((2 + hl,))
# architecture[0] = X_train.shape[1]
# architecture[-1] = 1 # len(np.unique(y_train))
# architecture[1:-1] = [nu for l in range(hl)]
#
# if learn_options["cv"] == "stratified":
# label_encoder = LabelEncoder()
# label_encoder.fit(y_all["Target gene"].values[train])
# gene_classes = label_encoder.transform(
# y_all["Target gene"].values[train]
# )
# n_splits = len(np.unique(gene_classes))
# skf = StratifiedKFold(n_splits=n_splits, shuffle=True)
# cv = skf.split(np.zeros(len(gene_classes), dtype=np.bool), gene_classes)
# elif learn_options["cv"] == "gene":
# gene_list = np.unique(y_all["Target gene"].values[train])
# cv = []
# for gene in gene_list:
# cv.append(predict.get_train_test(gene, y_all[train]))
# n_splits = len(cv)
#
# for train_ind, valid_ind in cv:
# # f = scikit_learn.
# e = theanets.Experiment(
# theanets.Regressor, layers=architecture, train_batches=32
# )
#
# e.train(
# (X_train[train_ind], y_train[train_ind]),
# (X_train[valid_ind], y_train[valid_ind]),
# )
# pred = e.network.predict(X_train[valid_ind])
#
# accuracies[i, j] += spearmanr(
# pred.flatten(), y_train[valid_ind].flatten()
# )[0]
#
# accuracies[i, j] /= float(n_splits)
#
# if best_score is None or accuracies[i, j] > best_score:
# best_score = accuracies[i, j]
# best_model = deepcopy(e)
#
# print(
# f"DNN with {hl} hidden layers and {nu} units, accuracy: {accuracies[i, j]:.4f}"
# )
#
# best_model.run((X_train, y_train), (X_test, y_test))
# y_pred = best_model.network.predict(X[test])
#
# return y_pred, None
|
pbs/thespian | setup.py | Python | unlicense | 630 | 0.001587 | from setuptools import setup, find_packages
def get_dependencies(filename):
dependencies = []
with open("REQUIREMENTS") as f:
dependencies = f.read().splitlines()
return dependencies
setup(
na | me="thespian",
version="0.0.1",
packages=find_packages('src'),
package_dir={'': 'src'},
install_requires=get_dependencies("REQUIREMENTS"),
package_data={
'': ['*.txt'],
},
# metadata for upload to PyPI
author="Radu Ciorba",
author_email="radu.ciorba@3pillarglobal.com",
description="Multip | rocessing based Actor Model",
url="http://github.com/pbs/thespian",
)
|
greggian/TapdIn | django/db/backends/postgresql/client.py | Python | apache-2.0 | 795 | 0.002516 | import os
import sys
from django.db.backends import BaseDatabaseClient
class DatabaseClient(BaseDatabaseClient):
executable_name = 'psql'
def runshell(self):
settings_dict = self.connection.s | ettings_dict
args = [self.executable_name]
if settings_dict['DATABASE_USER']:
args += ["-U", settings_dict['DATABASE_USER']]
if settings_dict['DATABASE_HOST']:
args.extend(["-h", settings_dict['DATABASE_HOST']])
if settings_dict['DATABASE_PORT']:
args.extend(["-p", str(settings_dict['DATABASE_PORT'])])
args += [settings_dict['DATABASE_NAME']]
if os.n | ame == 'nt':
sys.exit(os.system(" ".join(args)))
else:
os.execvp(self.executable_name, args)
|
vel21ripn/nDPI | python/ndpi.py | Python | lgpl-3.0 | 40,747 | 0.001767 | """
file: ndpi.py
This file is part of nfstream.
Copyright (C) 2019-20 - nfstream.org
nfstream 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.
nfstream 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 nfstream.
If not, see <http://www.gnu.org/licenses/>.
"""
from os.path import abspath, dirname
import cffi
cc_ndpi_network_headers = """
struct ptr_uint32 {
uint32_t value;
};
struct ndpi_chdlc
{
uint8_t addr; /* 0x0F (Unicast) - 0x8F (Broadcast) */
uint8_t ctrl; /* always 0x00 */
uint16_t proto_code; /* protocol type (e.g. 0x0800 IP) */
};
/* SLARP - Serial Line ARP http://tinyurl.com/qa54e95 */
struct ndpi_slarp
{
/* address requests (0x00)
address replies (0x01)
keep-alive (0x02)
*/
uint32_t slarp_type;
uint32_t addr_1;
uint32_t addr_2;
};
/* Cisco Discovery Protocol http://tinyurl.com/qa6yw9l */
struct ndpi_cdp
{
uint8_t version;
uint8_t ttl;
uint16_t checksum;
uint16_t type;
uint16_t length;
};
/* +++++++++++++++ Ethernet header (IEEE 802.3) +++++++++++++++ */
struct ndpi_ethhdr
{
uint8_t h_dest[6]; /* destination eth addr */
uint8_t h_source[6]; /* source ether addr */
uint16_t h_proto; /* data length (<= 1500) or type ID proto (>=1536) */
};
/* +++++++++++++++ ARP header +++++++++++++++ */
struct ndpi_arphdr {
uint16_t ar_hrd;/* Format of hardware address. */
uint16_t ar_pro;/* Format of protocol address. */
uint8_t ar_hln;/* Length of hardware address. */
uint8_t ar_pln;/* Length of protocol address. */
uint16_t ar_op;/* ARP opcode (command). */
uint8_t arp_sha[6];/* sender hardware address */
uint32_t arp_spa;/* sender protocol address */
uint8_t arp_tha[6];/* target hardware address */
uint32_t arp_tpa;/* target protocol address */
};
/* +++++++++++++++ DHCP header +++++++++++++++ */
struct ndpi_dhcphdr {
uint8_t msgType;
uint8_t htype;
uint8_t hlen;
uint8_t hops;
uint32_t xid;/* 4 */
uint16_t secs;/* 8 */
uint16_t flags;
uint32_t ciaddr;/* 12 */
uint32_t yiaddr;/* 16 */
uint32_t siaddr;/* 20 */
uint32_t giaddr;/* 24 */
uint8_t chaddr[16]; /* 28 */
uint8_t sname[64]; /* 44 */
uint8_t file[128]; /* 108 */
uint32_t magic; /* 236 */
uint8_t options[308];
};
/* +++++++++++++++ MDNS rsp header +++++++++++++++ */
struct ndpi_mdns_rsp_entry {
uint16_t rsp_type, rsp_class;
uint32_t ttl;
uint16_t data_len;
};
/* +++++++++++++++++++ LLC header (IEEE 802.2) ++++++++++++++++ */
struct ndpi_snap_extension
{
uint16_t oui;
uint8_t oui2;
uint16_t proto_ID;
};
struct ndpi_llc_header_snap
{
uint8_t dsap;
uint8_t ssap;
uint8_t ctrl;
struct ndpi_snap_extension snap;
};
/* ++++++++++ RADIO TAP header (for IEEE 802.11) +++++++++++++ */
struct ndpi_radiotap_header
{
uint8_t version; /* set to 0 */
uint8_t pad;
uint16_t len;
uint32_t present;
uint64_t MAC_timestamp;
uint8_t flags;
};
/* ++++++++++++ Wireless header (IEEE 802.11) ++++++++++++++++ */
struct ndpi_wifi_header
{
uint16_t fc;
uint16_t duration;
uint8_t rcvr[6];
uint8_t trsm[6];
uint8_t dest[6];
uint16_t seq_ctrl;
/* uint64_t ccmp - for data encryption only - check fc.flag */
};
/* +++++++++++++++++++++++ MPLS header +++++++++++++++++++++++ */
struct ndpi_mpls_header
{
/* Before using this strcut to parse an MPLS header, you will need to convert
* the 4-byte data to the correct endianess with ntohl(). */
uint32_t ttl:8, s:1, exp:3, label:20;
};
extern union mpls {
uint32_t u32;
struct ndpi_mpls_header mpls;
} mpls;
/* ++++++++++++++++++++++++ IP header ++++++++++++++++++++++++ */
struct ndpi_iphdr {
uint8_t ihl:4, version:4;
uint8_t tos;
uint16_t tot_len;
uint16_t id;
uint16_t frag_off;
uint8_t ttl;
uint8_t protocol;
uint16_t check;
uint32_t saddr;
uint32_t daddr;
};
/* +++++++++++++++++++++++ IPv6 header +++++++++++++++++++++++ */
/* rfc3542 */
struct ndpi_in6_addr {
union {
uint8_t u6_addr8[16];
uint16_t u6_addr16[8];
uint32_t u6_addr32[4];
uint64_t u6_addr64[2];
} u6_addr; /* 128-bit IP6 address */
};
struct ndpi_ip6_hdrctl {
uint32_t ip6_un1_flow;
uint16_t ip6_un1_plen;
uint8_t ip6_un1_nxt;
uint8_t ip6_un1_hlim;
};
struct ndpi_ipv6hdr {
struct ndpi_ip6_hdrctl ip6_hdr;
struct ndpi_in6_addr ip6_src;
struct ndpi_in6_addr ip6_dst;
};
/* +++++++++++++++++++++++ TCP header +++++++++++++++++++++++ */
struct ndpi_tcphdr
{
uint16_t source;
uint16_t dest;
uint32_t seq;
uint32_t ack_seq;
uint16_t res1:4, doff:4, fin:1, syn:1, rst:1, psh:1, ack:1, urg:1, ece:1, cwr:1;
uint16_t window;
uint16_t check;
uint16_t urg_ptr;
};
/* +++++++++++++++++++++++ UDP header +++++++++++++++++++++++ */
struct ndpi_udphdr
{
uint16_t source;
uint16_t dest;
uint16_t len;
uint16_t check;
};
struct ndpi_dns_packet_header {
uint16_t tr_id;
uint16_t flags;
uint16_t num_queries;
uint16_t num_answers;
uint16_t authority_rrs;
uint16_t additional_rrs;
};
/* +++++++++++++++++++++++ ICMP header +++++++++++++++++++++++ */
struct ndpi_icmphdr {
uint8_t type;/* message type */
uint8_t code;/* type sub-code */
uint16_t checksum;
union {
struct {
uint16_t id;
uint16_t sequence;
} echo; /* echo datagram */
uint32_t gateway; /* gateway address */
struct {
uint16_t _unused;
uint16_t mtu;
} frag;/* path mtu discovery */
} un;
};
/* +++++++++++++++++++++++ ICMP6 header +++++++++++++++++++++++ */
struct ndpi_icmp6hdr {
uint8_t icmp6_type; /* type field */
uint8_t icmp6_code; /* code field */
uint16_t icmp6_cksum; /* checksum field */
union {
uint32_t icmp6_un_data32[1]; /* type-specific field */
uint16_t icmp6_un_data16[2]; /* type-specific field */
uint8_t icmp6_un_data8[4]; /* type-specific field */
} icmp6_dataun;
};
/* +++++++++++++++++++++++ VXLAN header +++++++++++++++++++++++ */
struct ndpi_vxlanhdr {
uint16_t flags;
uint16_t groupPolicy;
uint32_t vni;
};
struct tinc_cache_entry {
uint32_t src_address;
uint32_t dst_address;
uint16_t dst_port;
};
"""
cc_ndpi_stuctures = """
#define NDPI_MAX_NUM_TLS_APPL_BLOCKS 8
typedef enum {
NDPI_LOG_ERROR,
NDPI_LOG_TRACE,
NDPI_LOG_DEBUG,
NDPI_LOG_DEBUG_EXTRA
} ndpi_log_level_t;
typedef enum {
ndpi_l4_proto_unknown = 0,
ndpi_l4_proto_tcp_only,
ndpi_l4_proto_udp_only,
ndpi_l4_proto_tcp_and_udp,
} ndpi_l4_proto_info;
typedef enum {
ndpi_no_tunnel = 0,
ndpi_gtp_tunnel,
ndpi_capwap_tunnel,
ndpi_tzsp_tunnel,
ndpi_l2tp_tunnel,
} ndpi_packet_tunnel;
typede | f enum {
NDPI_NO_RISK = 0,
NDPI_URL_POSSIBLE_XSS,
NDPI_URL_POSSIBLE_SQL_INJECTION,
NDPI_URL_POSSIBLE_R | CE_INJECTION,
NDPI_BINARY_APPLICATION_TRANSFER,
NDPI_KNOWN_PROTOCOL_ON_NON_STANDARD_PORT,
NDPI_TLS_SELFSIGNED_CERTIFICATE,
NDPI_TLS_OBSOLETE_VERSION,
NDPI_TLS_WEAK_CIPHER,
NDPI_TLS_CERTIFICATE_EXPIRED,
NDPI_TLS_CERTIFICATE_MISMATCH,
NDPI_HTTP_SUSPICIOUS_USER_AGENT,
NDPI_HTTP_NUMERIC_IP_HOST,
NDPI_HTTP_SUSPICIOUS_URL,
NDPI_HTTP_SUSPICIOUS_HEADER,
NDPI_TLS_NOT_CARRYING_HTTPS,
NDPI_SUSPICIOUS_DGA_DOMAIN,
NDPI_MALFORMED_PACKET,
NDPI_SSH_OBSOLETE_CLIENT_VERSION_OR_CIPHER,
NDPI_SSH_OBSOLETE_SERVER_VERSION_OR_CIPHER,
NDPI_SMB_INSECURE_VERSION,
NDPI_TLS_SUSPICIOUS_ESNI_USAGE,
NDPI_UNSAFE_PROTOCOL,
NDPI_DNS_SUSPICIOUS_TRAFFIC,
NDPI_TLS_MISSING_SNI,
NDPI_HTTP_SUSPICIOUS_CONTENT,
NDPI_RISKY_ASN,
NDPI_RISKY_DOMAIN,
NDPI_MALICIOUS_JA3,
NDPI_MALICIOUS_SHA1_CERTIFICATE,
NDPI_DESKTOP_OR_FILE_SHARING_SESSION,
NDPI_TLS_UNCOMMON_ALPN,
NDPI_TLS_CERT_VALIDITY_TOO_LONG,
NDPI_TLS_SUSPICIOUS_EX |
minhphung171093/OpenERP_V8 | openerp/addons/google_spreadsheet/google_spreadsheet.py | Python | agpl-3.0 | 5,617 | 0.003205 | ##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2012 OpenERP SA (<http://www.openerp.com>).
#
# 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 cgi
import simplejson
import logging
from lxml import etree
import re
import werkzeug.urls
import urllib2
from openerp.osv import osv
from openerp.addons.google_account import TIMEOUT
_logger = logging.getLogger(__name__)
class config(osv.osv):
_inherit = 'google.drive.config'
def get_google_scope(self):
scope = super(config, self).get_google_scope()
return '%s https://spreadsheets.google.com/feeds' % scope
def write_config_formula(self, cr, uid, attachment_id, spreadsheet_key, model, domain, groupbys, view | _id, context=None):
access_token = self.get_access_token(cr, uid, scope='https://spreadsheets.google.com/feeds', context=context)
fields = self.pool.get(model).fields_view_get(cr, uid, view_id=view_id, view_type='tree')
doc = etree.XML(fields.get('arch') | )
display_fields = []
for node in doc.xpath("//field"):
if node.get('modifiers'):
modifiers = simplejson.loads(node.get('modifiers'))
if not modifiers.get('invisible') and not modifiers.get('tree_invisible'):
display_fields.append(node.get('name'))
fields = " ".join(display_fields)
domain = domain.replace("'", r"\'").replace('"', "'")
if groupbys:
fields = "%s %s" % (groupbys, fields)
formula = '=oe_read_group("%s";"%s";"%s";"%s")' % (model, fields, groupbys, domain)
else:
formula = '=oe_browse("%s";"%s";"%s")' % (model, fields, domain)
url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
dbname = cr.dbname
user = self.pool['res.users'].read(cr, uid, [uid], ['login', 'password'], context=context)[0]
username = user['login']
password = user['password']
if not password:
config_formula = '=oe_settings("%s";"%s")' % (url, dbname)
else:
config_formula = '=oe_settings("%s";"%s";"%s";"%s")' % (url, dbname, username, password)
request = '''<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:batch="http://schemas.google.com/gdata/batch"
xmlns:gs="http://schemas.google.com/spreadsheets/2006">
<id>https://spreadsheets.google.com/feeds/cells/{key}/od6/private/full</id>
<entry>
<batch:id>A1</batch:id>
<batch:operation type="update"/>
<id>https://spreadsheets.google.com/feeds/cells/{key}/od6/private/full/R1C1</id>
<link rel="edit" type="application/atom+xml"
href="https://spreadsheets.google.com/feeds/cells/{key}/od6/private/full/R1C1"/>
<gs:cell row="1" col="1" inputValue="{formula}"/>
</entry>
<entry>
<batch:id>A2</batch:id>
<batch:operation type="update"/>
<id>https://spreadsheets.google.com/feeds/cells/{key}/od6/private/full/R60C15</id>
<link rel="edit" type="application/atom+xml"
href="https://spreadsheets.google.com/feeds/cells/{key}/od6/private/full/R60C15"/>
<gs:cell row="60" col="15" inputValue="{config}"/>
</entry>
</feed>''' .format(key=spreadsheet_key, formula=cgi.escape(formula, quote=True), config=cgi.escape(config_formula, quote=True))
try:
req = urllib2.Request(
'https://spreadsheets.google.com/feeds/cells/%s/od6/private/full/batch?%s' % (spreadsheet_key, werkzeug.url_encode({'v': 3, 'access_token': access_token})),
data=request,
headers={'content-type': 'application/atom+xml', 'If-Match': '*'})
urllib2.urlopen(req, timeout=TIMEOUT)
except (urllib2.HTTPError, urllib2.URLError):
_logger.warning("An error occured while writting the formula on the Google Spreadsheet.")
description = '''
formula: %s
''' % formula
if attachment_id:
self.pool['ir.attachment'].write(cr, uid, attachment_id, {'description': description}, context=context)
return True
def set_spreadsheet(self, cr, uid, model, domain, groupbys, view_id, context=None):
try:
config_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'google_spreadsheet', 'google_spreadsheet_template')[1]
except ValueError:
raise
config = self.browse(cr, uid, config_id, context=context)
title = 'Spreadsheet %s' % model
res = self.copy_doc(cr, uid, False, config.google_drive_resource_id, title, model, context=context)
mo = re.search("(key=|/d/)([A-Za-z0-9-_]+)", res['url'])
if mo:
key = mo.group(2)
self.write_config_formula(cr, uid, res.get('id'), key, model, domain, groupbys, view_id, context=context)
return res
|
widoptimization-willett/feature-extraction | feature_extraction/measurements/__init__.py | Python | apache-2.0 | 885 | 0.030508 | from collections import defaultdict
from ..util import AttributeDict
class Measurement(object):
"""
A generic feature measurement.
Attributes
----------
default_options
Can be set by subclasses to set default option values
"""
default_options = {}
def __init__(self, options=None):
"""
When initializing this measurement, options can be passed.
These are expo | sed to internal algorithms as `self.options`.
Parameters
----------
options : dict
A dict of options for this measurement.
"""
self.options = AttributeDict()
self.options.update(self.default_options or {})
self.options.update(options or {})
from .pixelaverage import PixelAverage
from .texture_haralick import HaralickTexture
from .granularity import Granularity
from .edge_intensity_ratio import EdgeIntensityRatio
from .e | uler_number import EulerNumber
# from .caffenet import Caffenet
|
daneos/Tango-RedPitaya | src/rp_board/service.py | Python | gpl-2.0 | 875 | 0.049143 | # This file should go to /usr/lib/python2.7/site-packages/PyRedPitaya/ directory on the device's SD card
import rpyc
import os
from raw_memory import BoardRawMemory
class MyService(rpyc.Service):
def on_connect(self):
print | "CONNECTION"
self._mem = BoardRawMemory()
self._conn._config.update(dict(
allow_all_attrs = True,
allow_pickle = False,
allow_getattr = True,
allow_setattr = True,
allow_delattr = True,
import_custom_exceptions = True,
instantiate_custom_exceptions = True,
instantiate_oldstyle_exceptions = True,
))
def exposed_mem(self):
return self._mem
pass
| # this allows to execute commands on server
def exposed_run_command(self, cmd):
return os.popen(cmd).read()
if __name__=="__main__":
from rpyc.utils.server import ThreadedServer
print 'START SERVER'
t = ThreadedServer(MyService, port = 18861)
t.start()
|
mark-burnett/lsf-python | tests/test_request.py | Python | gpl-3.0 | 376 | 0 | import lsf
import unittest
class RequestTests(unittest.TestCase):
def test_submit_to_default_que | ue(self):
job = lsf.submit('ls')
self.assertGreater(job.job_id, 0)
def test_submit_to_illegal_q | ueue(self):
with self.assertRaises(lsf.exceptions.LSFBindingException):
lsf.submit('ls', options={'queue': 'nonexistantqueuefortesting'})
|
sam-m888/addons-source | PhpGedView/phpgedview.gpr.py | Python | gpl-2.0 | 1,398 | 0.02289 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2007 Martin Hawlisch
#
# 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.
#
register(TOOL,
id = 'PhpGedView',
name = _("PhpGedView"),
description = _("Download a GEDCOM file from a phpGedView server."),
version = '0.0.8',
gramps_target_version = "5.1",
| include_in_listing = False,
status = UNSTABLE,
fname = 'phpgedviewconnector.py',
authors = ["Martin Hawlisch"],
authors_email = ["martin.hawlisch@gmx.de"],
category = TOOL_UTILS,
toolclass = 'PHPGedViewConnector',
optionclass = 'phpGedViewImporter',
tool_modes = [TOOL_MODE_GUI],
)
|
wgnet/webium | examples/8_finds.py | Python | apache-2.0 | 368 | 0 | from selenium.webdriver.common.by import By
from webium import BasePage, Finds
class LinksPage(BasePage):
l | inks = Finds(by=By. | TAG_NAME, value='a')
def __init__(self):
super(LinksPage, self).__init__(url='http://wargaming.net')
if __name__ == '__main__':
page = LinksPage()
page.open()
print('Number of links: ' + str(len(page.links)))
|
JburkeRSAC/PizzaCat-Web | threat_recon_to_CSV.py | Python | mit | 2,231 | 0.017929 | import urllib
from urllib2 import urlopen, quote
import urllib2
import json
import time
import datetime
import csv
import unicodedata
import sys
timestring = time.time()
formatted_timestring = datetime.datetime.fromtimestamp(timestring).strftime('%Y_%m_%d')
search = sys.argv[1]
api_key = 'YOUR_API_KEY'
def query_threat_recon(indicator, api_key):
params = urllib.urlencode({'api_key': api_key, 'indicator': indicator})
f = urllib2.urlopen("https://api.threatrecon.co/api/v1/search", params)
data = json.load(f)
results = data["Results"]
#print json.dumps(data, indent=4, sort_keys=False)
return results
results = query_threat_recon(search, api_key)
csv_file_name = 'TR_search_'+formatted_timestring+'.csv'
with open(csv_file_name, 'wb') as csvfile:
indicatorwriter = csv.writer(csvfile, delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
indicatorwriter.writerow(['INDICATOR','REFERENCE','SOURCE','KILLCHAIN','FIRST_SEEN','LAST_SEEN','ATTRIBUTION','PROCESS_TYPE','RNAME', 'RDATA','ROOT_NODE','COUNTRY','TAGS','COMMENT','CONFIDENCE'])
for item in results:
indicator = search
reference = str(item["Reference"]).decode('utf-8')
source = str(item["Source"]).decode('utf-8')
killchain = str(item["KillChain"]).decode('utf-8')
first_seen = str(item["FirstSeen"]).decode('utf-8')
last_seen = str(item["LastSeen"]).decode('utf-8')
attribution = str(item["Attribution"]).decode('utf-8')
process_type = str(item["ProcessType"]).decode('utf-8')
rrname = str(item["Rrname"])
rdata = str(item["Rdata"])
rootnode = str(item["RootNode"])
country = str(item["Country"]).decode('utf-8')
tags = str(item["Tags"]).decod | e('utf-8')
comment = item["Comment"]
comment2 = unicodedata.normalize('NFKD', comment).encode('ascii','ignore')
confidence = str(item["Confidence"]).decode('utf-8')
indicatorwriter.writerow([indicator,reference,source,killchain,first_seen,last_seen,attribution,process_type,rrname,rdata,rootnode, | country,tags,comment2,confidence])
lenresults = str(len(results))
print csv_file_name
#print lenresults +' records added to CSV'
|
skangas/zombieswtf | scripts/network/packets/client.py | Python | gpl-3.0 | 2,495 | 0.022044 | # -*- coding: utf-8 -*-
########################################################################
# Copyright (C) 2011 The Unknown Horizons Team <team@unknown-horizons.org>
########################################################################
# This file is part of ZombiesWTF.
#
# ZombiesWTF 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 t | he
# 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/>.
# ###################################################
from horizons.network.packets import *
class cmd_creategame(packet):
def __init__(self, clientver, mapname, maxplayers, playername):
self.clientversion = clientver
self. | mapname = mapname
self.maxplayers = maxplayers
self.playername = playername
packetlist.append(cmd_creategame)
#-------------------------------------------------------------------------------
class cmd_listgames(packet):
def __init__(self, clientver, mapname = None, maxplayers = None):
self.clientversion = clientver
self.mapname = mapname
self.maxplayers = maxplayers
packetlist.append(cmd_listgames)
#-------------------------------------------------------------------------------
class cmd_joingame(packet):
def __init__(self, uuid, clientver, playername):
if type(uuid) == str:
self.uuid = UUID(uuid)
else:
self.uuid = uuid
self.clientversion = clientver
self.playername = playername
packetlist.append(cmd_joingame)
#-------------------------------------------------------------------------------
class cmd_leavegame(packet):
def __init__(self):
"""ctor"""
packetlist.append(cmd_leavegame)
#-------------------------------------------------------------------------------
class cmd_chatmsg(packet):
def __init__(self, msg):
self.chatmsg = msg
packetlist.append(cmd_chatmsg)
#-------------------------------------------------------------------------------
class cmd_holepunchingok(packet):
def __init__(self):
"""hole punching done"""
packetlist.append(cmd_holepunchingok)
|
zzragida/PythonExamples | MemberShip/db/base.py | Python | mit | 2,027 | 0.009867 | # -*- coding:utf-8 -*-
import unittest
from datetime import datetime
from datetime import timedelta
from SQLRelay import PySQLRClient
SQLRELAY_HOST = 'localhost'
SQLRELAY_PORT = 9002
SQLRELAY_USER = 'sqlruser'
SQLRELAY_PASS = 'sqlrpass'
SQLRELAY_DEBUG = False
class SQLRelayTestCase(unittest.TestCase):
"""Base test case for SQLRelay"""
con = None
cur = None
def setUp(self):
self.con = PySQLRClient.sqlrconnection(
SQLRELAY_HOST,
SQLRELAY_PORT,
'',
SQLRELAY_USER,
SQLRELAY_PASS,
0, 1)
if SQLRELAY_DEBUG: self.con.debugOn()
self.cur = PySQLRClient.sqlrcursor(self.con)
def tearDown(self):
if self.cur:
del self.cur
if self.con:
if SQLRELAY_DEBUG: self.con.debugOff()
self.con.endSession()
del self.con
def call_member_info(self,
app_id,
udid,
| device_platform,
service_platform,
facebook_id = 0,
| facebook_email = None,
facebook_phone = None,
status = 1):
self.cur.prepareQuery('CALL member_info(:app_id, :udid, :device_platform, :service_platform, :facebook_id, :facebook_email, :facebook_phone, :status)')
self.cur.inputBind('app_id', app_id)
self.cur.inputBind('udid', udid)
self.cur.inputBind('device_platform', device_platform)
self.cur.inputBind('service_platform', service_platform)
self.cur.inputBind('facebook_id', facebook_id)
self.cur.inputBind('facebook_email', facebook_email)
self.cur.inputBind('facebook_phone', facebook_phone)
self.cur.inputBind('status', status)
self.cur.executeQuery()
member_id = self.cur.getFieldAsInteger(0, 0)
return member_id
|
CentechMTL/TableauDeBord | app/experiment/migrations/0005_auto_20160330_1625.py | Python | gpl-3.0 | 919 | 0.003264 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependen | cies = [
('experiment', '0004_auto_20150727_1405'),
]
operations = [
migrations.AlterField(
model_name='customerexperiment',
name='experiment_description',
field=models.TextField(max_length=1024, verbose_name='Experiment description'),
),
migrations.AlterField(
model_name='customerexperiment',
n | ame='test_subject_count',
field=models.PositiveIntegerField(default=0, verbose_name='Number of test participants'),
),
migrations.AlterField(
model_name='customerexperiment',
name='test_subject_description',
field=models.TextField(max_length=512, verbose_name='Test description'),
),
]
|
Naburimannu/libtcodpy-tutorial | components.py | Python | bsd-3-clause | 4,487 | 0 | """
Simple entity system: any renderable Object can have
a number of Components attached.
"""
import math
import algebra
class Object:
"""
This is a generic object: the player, a monster, an item, the stairs...
It's always represented by a character on screen.
"""
def __init__(self, pos, char, name, color,
blocks=False, always_visible=False,
fighter=None, ai=None, item=None, equipment=None):
self.pos = pos
self.char = char
self.name = name
self.color = color
self.blocks = blocks
self.always_visible = always_visible
self.fighter = | fighter
self._ensure_ownership(fighter)
self.ai = ai
self._ensure_ownership(ai)
self.item = item
self._ensure_ownership(item)
self.equipment = equipment
self. | _ensure_ownership(equipment)
@property
def x(self):
return self.pos.x
@property
def y(self):
return self.pos.y
def _ensure_ownership(self, component):
if (component):
component.set_owner(self)
def distance_to(self, other):
"""
Return the distance to another object.
"""
dx = other.x - self.x
dy = other.y - self.y
return math.sqrt(dx ** 2 + dy ** 2)
def distance(self, x, y):
"""
Return the distance to some coordinates.
"""
return math.sqrt((x - self.x) ** 2 + (y - self.y) ** 2)
def distance(self, pos):
"""
Return the distance to some coordinates.
"""
return math.sqrt((pos.x - self.x) ** 2 + (pos.y - self.y) ** 2)
class Component:
"""
Base class for components to minimize boilerplate.
"""
def set_owner(self, entity):
self.owner = entity
class Fighter(Component):
"""
Combat-related properties and methods (monster, player, NPC).
"""
def __init__(self, hp, defense, power, xp, death_function=None):
self.base_max_hp = hp
self.hp = hp
self.base_defense = defense
self.base_power = power
self.xp = xp
self.death_function = death_function
@property
def power(self):
bonus = sum(equipment.power_bonus for equipment
in _get_all_equipped(self.owner))
return self.base_power + bonus
@property
def defense(self):
bonus = sum(equipment.defense_bonus for equipment
in _get_all_equipped(self.owner))
return self.base_defense + bonus
@property
def max_hp(self):
bonus = sum(equipment.max_hp_bonus for equipment
in _get_all_equipped(self.owner))
return self.base_max_hp + bonus
class Item(Component):
"""
An item that can be picked up and used.
"""
def __init__(self, description=None, count=1, use_function=None):
self.description = description
self.use_function = use_function
self.count = count
def can_combine(self, other):
"""
Returns true if other can stack with self.
Terribly simple for now.
"""
return other.item and other.name == self.owner.name
class Equipment(Component):
"""
An object that can be equipped, yielding bonuses.
Requires an Item component.
"""
def __init__(self, slot, power_bonus=0, defense_bonus=0, max_hp_bonus=0):
self.power_bonus = power_bonus
self.defense_bonus = defense_bonus
self.max_hp_bonus = max_hp_bonus
self.slot = slot
self.is_equipped = False
def set_owner(self, entity):
Component.set_owner(self, entity)
# There must be an Item component for the Equipment
# component to work properly.
if entity.item is None:
entity.item = Item()
entity.item.set_owner(entity)
class AI(Component):
def __init__(self, take_turn, metadata=None):
self._turn_function = take_turn
self._metadata = metadata
def take_turn(self, player):
self._turn_function(self.owner, player, self._metadata)
def _get_all_equipped(obj):
"""
Returns a list of all equipped items.
"""
if hasattr(obj, 'inventory'):
equipped_list = []
for item in obj.inventory:
if item.equipment and item.equipment.is_equipped:
equipped_list.append(item.equipment)
return equipped_list
else:
return []
|
mchristopher/PokemonGo-DesktopMap | app/pylibs/osx64/Cryptodome/PublicKey/RSA.py | Python | mit | 28,324 | 0.001024 | # ===================================================================
#
# Copyright (c) 2016, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
"""RSA public-key cryptography algorithm (signature and encryption).
RSA_ is the most widespread and used public key algorithm. Its security is
based on the difficulty of factoring large integers. The algorithm has
withstood attacks for 30 years, and it is therefore considered reasonably
secure for new designs.
The algorithm can be used for both confidentiality (encryption) and
authentication (digital signature). It is worth noting that signing and
decryption are significantly slower than verification and encryption.
The cryptograhic strength is primarily linked to the length of the modulus *n*.
In 2012, a sufficient length is deemed to be 2048 bits. For more information,
see the most recent ECRYPT_ report.
Both RSA ciphertext and RSA signature are as big as the modulus *n* (256
bytes if *n* is 2048 bit long).
This module provides facilities for generating fresh, new RSA keys,
constructing them from known components, exporting them, and importing them.
>>> from Cryptodome.PublicKey import RSA
>>>
>>> key = RSA.generate(2048)
>>> f = open('mykey.pem','w')
>>> f.write(key.exportKey('PEM'))
>>> f.close()
...
>>> f = open('mykey.pem','r')
>>> key = RSA.import_key(f.read())
Even though you may choose to directly use the methods of an RSA key object
to perform the primitive cryptographic operations (e.g. `RsaKey._encrypt`),
it is recommended to use one of the standardized schemes instead (like
`Cryptodome.Cipher.PKCS1_v1_5` or `Cryptodome.Signature.PKCS1_v1_5`).
.. _RSA: http://en.wikipedia.org/wiki/RSA_%28algorithm%29
.. _ECRYPT: http://www.ecrypt.eu.org/documents/D.SPA.17.pdf
:sort: generate,construct,import_key
"""
__all__ = ['generate', 'construct', 'import_key',
'RsaKey', 'oid']
import binascii
import struct
from Cryptodome import Random
from Cryptodome.IO import PKCS8, PEM
from Cryptodome.Util.py3compat import tobytes, bord, bchr, b, tostr
from Cryptodome.Util.asn1 import DerSequence
from Cryptodome.Math.Numbers import Integer
from Cryptodome.Math.Primality import (test_probable_prime,
| generate_probable_prime, COMPOSITE)
from Cryptodome.PublicKey import (_expand_subject_public_key_info,
_create_subject_public_key_info,
_extract_subject_public_key_info)
class RsaKey(object):
"""Class defining an actual RSA key.
:undocumented: __init__, __repr__, __getstate__, __eq__, __ne__, __str__,
sign, verify, encrypt, decrypt, blind, unblind, size
"""
def __init__(self, | **kwargs):
"""Build an RSA key.
:Keywords:
n : integer
The modulus.
e : integer
The public exponent.
d : integer
The private exponent. Only required for private keys.
p : integer
The first factor of the modulus. Only required for private keys.
q : integer
The second factor of the modulus. Only required for private keys.
u : integer
The CRT coefficient (inverse of p modulo q). Only required for
privta keys.
"""
input_set = set(kwargs.keys())
public_set = set(('n', 'e'))
private_set = public_set | set(('p', 'q', 'd', 'u'))
if input_set not in (private_set, public_set):
raise ValueError("Some RSA components are missing")
for component, value in kwargs.items():
setattr(self, "_" + component, value)
@property
def n(self):
"""Modulus"""
return int(self._n)
@property
def e(self):
"""Public exponent"""
return int(self._e)
@property
def d(self):
"""Private exponent"""
if not self.has_private():
raise AttributeError("No private exponent available for public keys")
return int(self._d)
@property
def p(self):
"""First factor of the modulus"""
if not self.has_private():
raise AttributeError("No CRT component 'p' available for public keys")
return int(self._p)
@property
def q(self):
"""Second factor of the modulus"""
if not self.has_private():
raise AttributeError("No CRT component 'q' available for public keys")
return int(self._q)
@property
def u(self):
"""Chinese remainder component (inverse of *p* modulo *q*)"""
if not self.has_private():
raise AttributeError("No CRT component 'u' available for public keys")
return int(self._u)
def size_in_bits(self):
"""Size of the RSA modulus in bits"""
return self._n.size_in_bits()
def size_in_bytes(self):
"""The minimal amount of bytes that can hold the RSA modulus"""
return (self._n.size_in_bits() - 1) // 8 + 1
def _encrypt(self, plaintext):
if not 0 < plaintext < self._n:
raise ValueError("Plaintext too large")
return int(pow(Integer(plaintext), self._e, self._n))
def _decrypt(self, ciphertext):
if not 0 < ciphertext < self._n:
raise ValueError("Ciphertext too large")
if not self.has_private():
raise TypeError("This is not a private key")
# Blinded RSA decryption (to prevent timing attacks):
# Step 1: Generate random secret blinding factor r,
# such that 0 < r < n-1
r = Integer.random_range(min_inclusive=1, max_exclusive=self._n)
# Step 2: Compute c' = c * r**e mod n
cp = Integer(ciphertext) * pow(r, self._e, self._n) % self._n
# Step 3: Compute m' = c'**d mod n (ordinary RSA decryption)
m1 = pow(cp, self._d % (self._p - 1), self._p)
m2 = pow(cp, self._d % (self._q - 1), self._q)
h = m2 - m1
while h < 0:
h += self._q
h = (h * self._u) % self._q
mp = h * self._p + m1
# Step 4: Compute m = m**(r-1) mod n
result = (r.inverse(self._n) * mp) % self._n
# Verify no faults occured
if ciphertext != pow(result, self._e, self._n):
raise ValueError("Fault detected in RSA decryption")
return result
def has_private(self):
return hasattr(self, "_d")
def can_encrypt(self):
return True
def can_sign(self):
return True
def publickey(self):
return RsaKey(n=self._n, e=self._e)
def __eq__(self, other):
if self.has_private() != other.has_private():
return False
if self.n != other.n or self.e != other.e:
return False
if not self.has_private():
|
MediffRobotics/DeepRobotics | DeepRobSite/DeepRobSite/wsgi.py | Python | gpl-3.0 | 399 | 0 | """
WSGI config for DeepRobSite project.
It exposes the WSGI callable as a module- | level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DeepRobSite.settings")
application = get_wsgi_applica | tion()
|
callowayproject/django-staff | staff/settings.py | Python | apache-2.0 | 436 | 0.002294 | from dja | ngo.conf import settings
DEFAULT_SETTINGS = {
'PHOTO_STORAGE': settings.DEFAULT_FILE_STORAGE,
'ORDERING': ('last_name', 'first_name'),
}
USER_SETTINGS = DEFAULT_SETTINGS.copy()
if hasattr(settings, 'STAFF_ORDERING'):
USER_SETTINGS['ORDERING'] = settings.STAFF_ORDERING
if hasattr(set | tings, 'STAFF_PHOTO_STORAGE'):
USER_SETTINGS['PHOTO_STORAGE'] = settings.STAFF_PHOTO_STORAGE
globals().update(USER_SETTINGS) |
LouvainVerificationLab/pynusmv | pynusmv/utils.py | Python | lgpl-3.0 | 22,573 | 0.002614 | """
The :mod:`pynusmv.utils` module contains some secondary functions and classes
used by PyNuSMV internals.
"""
__all__ = ['PointerWrapper', 'fixpoint', 'update', 'StdioFile','writeonly',
'indexed']
from pynusmv_lower_interface.nusmv.utils import utils
from pynusmv.init import _register_wrapper
class PointerWrapper(object):
"""
Superclass wrapper for NuSMV pointers.
Every pointer to a NuSMV structure is wrapped in a PointerWrapper
or in a subclass of PointerWrapper.
Every subclass instance takes a pointer to a NuSMV structure as constructor
parameter.
It is the responsibility of PointerWrapper and its subclasses to free
the wrapped pointer. Some pointers have to be freed like `bdd_ptr`,
but other do not have to be freed since NuSMV takes care of this;
for example, `BddFrm_ptr` does not have to be freed.
To ensure that a pointer is freed only once, PyNuSMV ensures that
any pointer is wrapped by only one PointerWrapper (or subclass of it)
if the pointer have to be freed.
"""
def __init__(self, pointer, freeit=False):
"""
Create a new PointerWrapper.
:param pointer: the pointer to wrap
:param freeit: whether the pointer has to be freed when this wrapper
is destroyed
"""
self._ptr = pointer
self._freeit = freeit
_register_wrapper(self)
def _free(self):
"""
Every subclass must implement `_free` if there is something to free.
"""
pass
def __del__(self):
if self._freeit and self._ptr is not None:
self._free()
def __hash__(self):
"""
Makes this object hashable.
.. warning::
Beware it uses the pointer to implement the hashing function.
So it is IDENTITY dependent (in C) and not value dependant.
:return: an object that can serve as key to perform the lookup in a dict.
"""
return self._ptr.__hash__()
def __eq__(self, other):
"""
Equality test between two objects.
.. warning::
Beware it uses the pointer to implement the hashing function.
So it is IDENTITY dependent (in C) and not value dependant.
:return: True iff the two object are the same
"""
return self._ptr == other._ptr
class AttributeDict(dict):
"""
An `AttributeDict` is a dictionary for which elements can be accessed by
using their keys as attribute names.
"""
def __init__(self, *args, **kwargs):
super(AttributeDict, self).__init__(*args, **kwargs)
self.__dict__ = self
def fixpoint(funct, start):
"""
Return the fixpoint of `funct`, as a BDD, starting with `start` BDD.
:rtype: :class:`BDD <pynusmv.dd.BDD>`
.. note:: mu Z.f(Z) least fixpoint is implemented with
`fixpoint(funct, false)`.
nu Z.f(Z) greatest fixpoint is implemented with
`fixpoint(funct, true)`.
"""
old = start
new = funct(start)
while old != new:
old = new
new = funct(old)
return old
def update(old, new):
"""
Update `old` with `new`. `old` is assumed to have the `extend` or `update`
method, and `new` is assumed to be a good argument for the corresponding
method.
:param old: the data to update.
:param new: the date to update with.
"""
try:
old.extend(new)
except AttributeError:
old.update(new)
class StdioFile:
"""
Wrapper class that provides a context manager to access a FILE* whenever the
lower interface needs one. This makes for a more pythonic way to interact
with APIs that need a standard file handle without having to deal with the
low level open/close instructions. Example::
# opens an arbitrary file of your choice.
with StdioFile.for_name('my_output_file', 'w') as f:
lower_interface_do_something_smart(f)
This wrapper also gives you access to stdin, stdout and stderr which, are
never closed despite the fact that they may be used with a `with` statement::
# stdio is ALREADY open at this time
with StdioFile.stdout() as out:
lower_interface_do_something_smart(out)
# stdio is STILL open here
"""
def __init__(self, fname, mode):
"""
Creates a new instance that will open the file `fname` in the `mode`
mode.
:param fname: the name of the file to be opened (more info -> stdio.h)
:param mode: the mode in which to open the file (more info -> stdio.h)
"""
self._fname = fname
self._mode = mode
self._ptr = None
self._isspecial = False
@staticmethod
def for_name(fname=None, mode='w'):
"""
This function acts like a generic factory that either return a handle
for standard file if the name is specified or to stdin or stdout if the
name is not specified (it depends on the mode)
:return: a stdiofile for the given name or stdin/stdout if no name is
specified depending on the value of the mode
"""
if fname is None:
return StdioFile.stdin() if mode == "r" else StdioFile.stdout()
else:
return StdioFile(fname, mode)
@staticmethod
def stdin():
"""Standard input"""
ret = StdioFile("(standard input)", "r")
ret._ptr = utils.stdio_stdin()
ret._isspecial = True
return ret
@staticmethod
def stdout():
"""standard | output"""
ret = StdioFile("(standard output)", "w")
ret._ptr = utils.stdio_stdout()
ret._isspecial = True
return ret
@staticmethod
def stderr():
"""standard error"""
ret = StdioFile("(standard error)", "w")
ret._ptr = utils.stdio_stderr()
ret._isspecial = True
return ret
def __enter__(s | elf):
"""Opens the file"""
if not self._isspecial:
self._ptr = utils.stdio_fopen(self._fname, self._mode)
return self
def __exit__(self, exception_type, exception_value, trace):
"""Makes sure the file is closed"""
if self._ptr is not None and not self._isspecial:
utils.stdio_fclose(self._ptr)
self._ptr = None
@property
def handle(self):
""":return: a FILE* handle to the opened stream"""
return self._ptr
#===============================================================================
#====== Decorators =============================================================
#===============================================================================
class writeonly:
"""
writeonly provides a write only decorator for properties that do not
have a getter accessor. This makes for pythonic property-lik APIs where your
class defines should have defined a setter. Example::
class Dummy(PointerWrapper):
# .. code elided ...
@writeonly
def config_tweak(self, new_value_of_tweak):
lower_interface_set_tweak(self._ptr, new_value_of_tweak)
Can be used the following way::
d = Dummy()
# this is now perfectly OK
d.config_tweak = 42
# this will however fail since no getter was defined
d.config_tweak
"""
def __init__(self, fn):
"""Creates the decorator memeorizing the decorated func"""
self._fn = fn
self.__doc__ = fn.__doc__ # be nice with the user documentation
def __call__(self):
"""
Executes the decoration (takes care itself to apply the decorated fn
"""
return self
def __set__(self, obj, value):
"""
Executes the decorated setter function
"""
self._fn(obj, value)
def __get__(self, obj, _type):
"""
Makes sure this property is only accessed in write only mode
"""
msg = '{} is defined as a write only property'.format(self._fn.__name__)
raise AttributeError(msg)
clas |
indygreg/lua-protobuf | setup.py | Python | apache-2.0 | 1,098 | 0.030055 | # Copyright 2010 Gregory Szorc
#
# 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 unde | r the License.
from setuptools import setup, find_packages
setup(
name = 'lua-protobuf',
version = '0.0.1',
packages = [ 'lua_protobuf' ],
scripts = ['protoc-gen-lua'],
install_requires = [ 'protobuf>=2.3.0' ],
author = 'Gregory Szorc',
author_email = 'gregory.szorc@gmail.com',
description = 'Lua protocol buffer code generator',
license = 'Apache 2.0',
url = | 'http://github.com/indygreg/lua-protobuf'
)
|
mvaled/sentry | src/sentry/south_migrations/0408_identity_provider_external_id.py | Python | bsd-3-clause | 105,752 | 0.00799 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from sentry.utils.query import RangeQuerySetWrapperWithProgressBar
class Migration(DataMigration):
# Flag to indicate if this migration is too risky
# to run online and needs to be coordinated for offline
is_dangerous = False
def forwards(self, orm):
db.commit_transaction()
try:
self._forwards(orm)
except Exception:
db.start_transaction()
raise
db.start_transaction()
def _forwards(self, orm):
idps = orm.IdentityProvider.objects.filter(external_id=None)
for r in RangeQuerySetWrapperWithProgressBar(idps):
try:
# Limit to one integration. It *is possible* that multiple
# integrations could have been configured and only one identity
# provider would have been setup, but at the time of writing
# this, in getsentry, there are no cases like such.
integration = orm.Integration.objects.filter(organizations=r.organization_id)[0]
except IndexError:
# Identity provider exists without an external_id. Nothing we
# can do to determine the external ID.
continue
orm.IdentityProvider.objects.filter(id=r.id, external_id=None).update(external_id=integration.external_id)
def backwards(self, orm):
"Write your backwards methods here."
models = {
'sentry.activity': {
'Meta': {'object_name': 'Activity'},
'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {'null': 'True'}),
'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'group': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Group']", 'null': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'ident': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True'}),
'project': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.Project']"}),
'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleFor | eignKey', [], {'to': "orm['sentry.User']", 'null': 'True'})
},
'sentry.apiapplication': {
'Meta': {'object_name': ' | ApiApplication'},
'allowed_origins': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'client_id': ('django.db.models.fields.CharField', [], {'default': "'7659033185d64a589638801d051ec5fa77cdbd017cbe4b6a84bea5d474b31e70'", 'unique': 'True', 'max_length': '64'}),
'client_secret': ('sentry.db.models.fields.encrypted.EncryptedTextField', [], {'default': "'34ea9b3a3a1f4840a604ed94e65dd7538e9eee68b1f64942a5afad91a8e8a0d1'"}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'homepage_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'default': "'Ideal Monkfish'", 'max_length': '64', 'blank': 'True'}),
'owner': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"}),
'privacy_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True'}),
'redirect_uris': ('django.db.models.fields.TextField', [], {}),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'}),
'terms_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True'})
},
'sentry.apiauthorization': {
'Meta': {'unique_together': "(('user', 'application'),)", 'object_name': 'ApiAuthorization'},
'application': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.ApiApplication']", 'null': 'True'}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'scope_list': ('sentry.db.models.fields.array.ArrayField', [], {'of': ('django.db.models.fields.TextField', [], {})}),
'scopes': ('django.db.models.fields.BigIntegerField', [], {'default': 'None'}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"})
},
'sentry.apigrant': {
'Meta': {'object_name': 'ApiGrant'},
'application': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.ApiApplication']"}),
'code': ('django.db.models.fields.CharField', [], {'default': "'70dc648487874d2386767832f2c4185a'", 'max_length': '64', 'db_index': 'True'}),
'expires_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2018, 4, 25, 0, 0)', 'db_index': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'redirect_uri': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'scope_list': ('sentry.db.models.fields.array.ArrayField', [], {'of': ('django.db.models.fields.TextField', [], {})}),
'scopes': ('django.db.models.fields.BigIntegerField', [], {'default': 'None'}),
'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']"})
},
'sentry.apikey': {
'Meta': {'object_name': 'ApiKey'},
'allowed_origins': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}),
'label': ('django.db.models.fields.CharField', [], {'default': "'Default'", 'max_length': '64', 'blank': 'True'}),
'organization': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'related_name': "'key_set'", 'to': "orm['sentry.Organization']"}),
'scope_list': ('sentry.db.models.fields.array.ArrayField', [], {'of': ('django.db.models.fields.TextField', [], {})}),
'scopes': ('django.db.models.fields.BigIntegerField', [], {'default': 'None'}),
'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {'default': '0', 'db_index': 'True'})
},
'sentry.apitoken': {
'Meta': {'object_name': 'ApiToken'},
'application': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.ApiApplication']", 'null': 'True'}),
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'expires_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2018, 5, 25, 0, 0)', 'null': 'True'}),
'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], {'primary_key': 'True'}),
'refresh_token': ('django.db.models.fields.CharField', [], {'default': "'084bec36d9554d97a2fd071c29ff3f996df84065b4084507a692308b55fd5cf6'", 'max_length': '64', 'unique': 'True', 'null': 'True'}),
'scope_list': ('sentry.db.models.fields.array.ArrayField', [], {'of': ('django.db.models.fields.TextField', [], {})}),
'scopes': ('django.db.models.fields.BigIntegerField', [], {'def |
ajdavis/mongo-mockup-db | docs/conf.py | Python | apache-2.0 | 8,880 | 0.00518 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# mongo-mockup-db documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# 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('.'))
# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)
import mockupdb
# -- 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.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.coverage',
'sphinx.ext.todo',
'sphinx.ext.intersphinx',
]
intersphinx_mapping = {
'python': ('https://docs.python.org/3/', None),
'pymongo': ('http://api.mongodb.com/python/current/', None),
}
primary_domain = 'py'
default_role = 'py:obj'
doctest_global_setup = """
from collections import OrderedDict
from mockupdb import *
"""
# 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 = 'MockupDB'
copyright = '2015, MongoDB, Inc.'
# 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 = mockupdb.__version__
# The full version, including alpha/beta/rc tags.
release = mockupdb.__version__
# 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'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be app | ended 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 gratefully vendored from CPython source.
html_theme = "pydoctheme"
html_theme_path = ["."]
html_theme_options = {'collapsiblesidebar': True}
# 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 = {}
# 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 = 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']
# 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 = True
# 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 = 'mockupdbdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'mockupdb.tex',
'MockupDB Documentation',
'A. Jesse Jiryu Davis', '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 = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# 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', 'mockupdb',
'MockupDB Documentation',
['A. Jesse Jiryu Davis'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of |
foursquare/pants | contrib/python/src/python/pants/contrib/python/checks/tasks/checkstyle/trailing_whitespace.py | Python | apache-2.0 | 2,252 | 0.010657 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import tokenize
from builtins import range
from collections import defaultdict
from pants.contrib.python.checks.tasks.checkstyle.common import CheckstylePlugin
class TrailingWhitespace(CheckstylePlugin):
"""Warn on invalid trailing whitespace."""
@classmethod
def build_exception_map(cls, tokens):
"""Generates a set of ranges where we accept trailing slashes, specifically within comments
and strings.
"""
exception_ranges = defaultdict(list)
for token in tokens:
token_type, _, token_start, token_end = token[0:4]
if token_type in (tokenize.COMMENT, tokenize.STRING):
if token_start[0] == token_end[0]:
exception_ranges[token_start[0]].append((token_start[1], token_end[1]))
else:
exception_ranges[token_start[0]].append((token_start[1], sys.maxsize))
for line in range(token_start[0] + 1, tok | en_end[0]):
exception_ranges[line].append((0, sys.maxsize))
exception_ranges[token_end[0]].append((0, token_end[1]))
return exception_ranges
def __init__(self, *args, **kw):
super(TrailingWhitespace, self).__init__(*args, **kw)
self._exception_map = self.build_exception_map(self.python_file.tokens)
def has_exception(self, line_number, exception_start, exception_end=None):
exception_end = exception_end or exception_start
for start, end in self._exception_ma | p.get(line_number, ()):
if start <= exception_start and exception_end <= end:
return True
return False
def nits(self):
for line_number, line in self.python_file.enumerate():
stripped_line = line.rstrip()
if stripped_line != line and not self.has_exception(line_number,
len(stripped_line), len(line)):
yield self.error('T200', 'Line has trailing whitespace.', line_number)
if line.rstrip().endswith('\\'):
if not self.has_exception(line_number, len(line.rstrip()) - 1):
yield self.error('T201', 'Line has trailing slashes.', line_number)
|
imiric/ork | ork/task.py | Python | mit | 1,945 | 0 | import importlib
import functools
import multiprocessing as mp
from .brokers import get_broker
from .config import load_config
_TASK_NAME_PREFIX = 'ork'
def task(name=''):
def _outer_wrapper(wrapped_task):
def delay(*args, **kwargs):
task_name = '{}:{}'.format(
_TASK_NAME_PREFIX,
name or '{}.{}'.format(
wrapped_task.__module__,
wrapped_task.__name__))
config = load_config()
t = Task(task_name, get_broker(config), wrapped_task,
*args, **kwargs)
t.start()
return t
wrapped_task.delay = delay
@functools.wraps(wrap | ped_task)
def _wrapper(*args, **kwargs):
return | wrapped_task(*args, **kwargs)
return _wrapper
return _outer_wrapper
class Task:
def __init__(self, name, broker, task=None, *args, **kwargs):
self.name = name
self._broker = broker
self._task = task
self._process = mp.Process(target=self._work, args=args, kwargs=kwargs)
def __repr__(self):
return '<{}:{}>'.format(self.__class__.__name__, self.name)
def get(self):
"""Return the result of this task
This is a blocking method.
"""
return self._broker.get(self.name)
def start(self):
"""Start a worker subprocess for this task"""
self._process.start()
def _work(self, *args, **kwargs):
"""Process the task's inputs and store its result in a queue
This is a blocking method.
"""
inputs = list(args[:])
for i, inp in enumerate(inputs):
if isinstance(inp, Task):
inputs[i] = inp.get()
result = self._task(*inputs)
if result:
self._broker.set(self.name, result)
def load_tasks(config):
for tmod in config:
importlib.import_module(tmod)
|
ciechowoj/haste-format | make_data_t.py | Python | mit | 5,303 | 0.014332 | #!/usr/bin/python3
from itertools import *
KINDS = ['unorm', 'snorm', 'uint', 'sint', 'float']
PRECS = [8, 16, 32, 64]
def value(kind, prec, ndim):
ikind = KINDS.index(kind)
iprec = PRECS.index(prec)
index = ikind * len(PRECS) + iprec
return index << 16 | KINDS.index(kind) << 12 | iprec << 8 | (ndim - 1) << 10 | ((prec + 7) // 8 * ndim);
data_t_hpp = open("include/haste/data_t.hpp", "w+")
data_t_cpp = open("data_t.cpp", "w+")
data_t_hpp.write("#pragma once\n")
data_t_hpp.write("#include <cstddef>\n")
data_t_hpp.write("\n")
data_t_hpp.write("namespace haste {\n")
data_t_hpp.write("\n")
data_t_hpp.write("using std::size_t;\n")
data_t_hpp.write("\n")
data_t_hpp.write("enum class data_t {\n")
for kind in KINDS:
for prec in PRECS:
for d in range(1, 5):
if kind != 'float' or prec != '8':
v = value(kind, prec, d)
data_t_hpp.write('\t{}{}x{} = 0x{:08x}u,\n'.format(kind, prec, d, v))
for kind in KINDS:
for prec in PRECS:
if kind != 'float' or prec != '8':
v = value(kind, prec, 1) & 0xffff
data_t_hpp.write('\t{}{} = 0x{:08x}u,\n'.format(kind, prec, v))
data_t_hpp.write("};\n")
data_t_hpp.write("\n")
data_t_hpp.write("void datacpy(void* dst, const void* src, data_t dtype, data_t stype);\n")
data_t_hpp.write("\n")
data_t_hpp.write("inline size_t stride(data_t dtype) {\n")
data_t_hpp.write("\treturn size_t(dtype) & 0xffu;\n")
data_t_hpp.write("}\n")
data_t_hpp.write("\n")
ndim_func = """\
inline size_t ndim(data_t dtype) {
return ((size_t(dtype) >> 10) & 0x3u) + 1;
}
"""
prec_func = """\
inline size_t prec(data_t dtype) {
return 1u << (((size_t(dtype) >> 8) & 0x3u) + 3);
}
"""
subtype_func = """\
inline data_t subtype(data_t dtype) {
return data_t((unsigned(dtype) & 0xf300u) | prec(dtype) / 8);
}
"""
data_t_hpp.write(ndim_func)
data_t_hpp.write(prec_func)
data_t_hpp.write(subtype_func)
data_t_hpp.write("data_t unorm8(size_t components);\n")
data_t_hpp.write("\n")
data_t_hpp.write("}\n")
data_t_cpp.write("#include <haste/data_t.hpp>\n")
data_t_cpp.write("#include <algorithm>\n")
data_t_cpp.write("#include <cstdint>\n")
data_t_cpp.write("#include <cstring>\n")
data_t_cpp.write("\n")
data_t_cpp.write("namespace haste {\n")
data_t_cpp.write("\n")
data_t_cpp.write("using namespace std;\n")
data_t_cpp.write("\n")
data_t_cpp.write("using float8_t = uint8_t;\n")
data_t_cpp.write("using float16_t = uint16_t;\n")
data_t_cpp.write("using float32_t = float;\n")
data_t_cpp.write("using float64_t = double;\n")
data_t_cpp.write("\n")
data_t_cpp.write("typedef void (*datacpy_t)(void*, const void*, size_t);\n")
data_t_cpp.write("\n")
data_t_cpp.write("inline size_t index(data_t dtype) {\n")
data_t_cpp.write("\treturn size_t(dtype) >> 16;\n")
data_t_cpp.write("}\n")
data_t_cpp.write("\n")
UNORM_MAX = {
('unorm', 8) : 255,
('unorm', 16) : 65535,
('unorm', 32) : 2 ** 32 - 1,
('unorm', 64) : 2 ** 64 - 1,
}
UNORM_MAX_INV = {
('unorm', 8) : 1 / 255,
('unorm', 16) : 1 / 65535,
('unorm', 32) : 1 / (2 ** 32 - 1),
('unorm', 64) : 1 / (2 ** 64 - 1),
}
def datacpy_name(dst, src):
dstn = '{}{}'.format(dst[0], dst[1])
srcn = '{}{}'.format(src[0], src[1])
return "datacpy_{}_{}".format(dstn, srcn)
def conversion(dst, src):
name = datacpy_name(dst, src)
data_t_cpp.write("static void {}(void* dst, const void* src, size_t n) {{\n".format(name))
if dst == src:
data_t_cpp.write("\t::memcpy(dst, src, {} * n);\n".format(dst[1] // 8))
else:
data_t_cpp.write("\tfor (size_t i = 0; i < n; ++i) {\n")
if dst[0] == 'unorm':
if src[0] == 'float':
data_t_cpp.write("\t\t((uint{0}_t*)dst)[i] = uint{0}_t(((float{1}_t*)src)[i] * {2}u);\n".format(dst[1], src[1], UNORM_MAX[dst]))
elif dst[0] == 'float':
if src[0] == 'unorm':
template = "\t\t((float{0}_t*)dst)[i] = float{0}_t(((uint{1}_t*)src)[i]) * {2};\n"
k = ('{}' if dst[1] == 64 else '{}f').format(UNORM_MAX_INV[src])
data_t_cpp.write(template.format(dst[1], src[1], k))
elif src[0] == 'float':
template = "\t\t((float{0}_t*)dst)[i] = float{0}_t(((float{1}_t*)src)[i]);\n"
data_t_cpp.write(template.format(dst[1], src[1]))
data_t_cpp.write("\t}\n")
data_t_cpp.write("}\n\n")
for dst in product(KINDS, PRECS):
for src in product(KINDS, PRECS):
conversion(dst, src)
data_t_cpp.write("static datacpy_t datacpy_table[] = {\n")
for dst in product(KINDS, PRECS):
for src in product(KINDS, PRECS):
data_t_cpp.write("\t{},\n".format(datacpy_name(dst, src)))
data_t_cpp.write("};\n")
data_t_cpp.write("\n")
data_t_cpp.write("void datacpy(void* dst, const void* src, data_t dtype, data_t stype) {\n")
SIZE = len(list(product(KINDS, PRECS)))
data_t_cpp.write("\tdatacpy_table[index(dtype) * {} + index(stype)](dst, src, min(ndim(dtype), ndim(stype)));\n".format(SIZE))
data_t_cpp.write("}\n")
| data_t_cpp.write("\n")
data_t_cpp.write("data_t unorm8(size_t components) {\n")
data_t_cpp.write("\tswitch(components) {\n")
| data_t_cpp.write("\t\tcase 1: return data_t::unorm8x1;\n")
data_t_cpp.write("\t\tcase 2: return data_t::unorm8x2;\n")
data_t_cpp.write("\t\tcase 3: return data_t::unorm8x3;\n")
data_t_cpp.write("\t\tcase 4: return data_t::unorm8x4;\n")
data_t_cpp.write("\t\tdefault: return data_t::unorm8x4;\n")
data_t_cpp.write("\t}\n")
data_t_cpp.write("}\n")
data_t_cpp.write("\n")
data_t_cpp.write("}\n")
|
ayiis/python | pcap_usage.py | Python | mit | 2,503 | 0.003638 | # -*- coding:utf-8 -*-
import socket
import time
import struct
from struct import pack
import traceback
import rand | om
import pcap
import q
def checksum(tcp_header):
s = 0
for i in range(0, len(tcp_header), 2):
w = (tcp_header[i] << 8) + (tcp_header[i + | 1])
s = s + w
s = (s >> 16) + (s & 0xffff)
s = ~s & 0xffff
return s
def pPacket(source_address, source_port, remote_address, remote_port):
get_ipheader = lambda iph_checksum: pack("!BBHHHBBH4s4s", 69, 0, 40, 0, 0, 64, 6, iph_checksum, source_address, remote_address)
ip_header = get_ipheader(0)
iph_checksum = checksum(ip_header)
ip_header = get_ipheader(iph_checksum)
get_tcpheader = lambda tcph_checksum: pack("!HHLLBBHHH", source_port, remote_port, 1000000001, 0, 80, 2, 53270, tcph_checksum, 0)
tcp_header = get_tcpheader(0)
psh = pack("!4s4sBBH", source_address, remote_address, 0, 6, 20)
tcph_checksum = checksum(psh + tcp_header)
tcp_header = get_tcpheader(tcph_checksum)
return ip_header + tcp_header
def main():
pp_socket = pcap.pcap(name="en0")
"""
网关自带防攻击和过滤数据包的能力,要避免被网关影响判断
我的 mac "18:65:90:cc:45:b9"
网关 mac "00:ff:ea:6e:8f:0b"
目标 mac "00:50:56:26:82:d1"
"""
source_address = socket.inet_aton("192.168.8.111") # 伪造任意IP,如果不是自己的 IP,网关把响应数据发到这个 IP (有猫腻)
remote_address = socket.inet_aton("192.168.1.112") # 目标的 IP,网关会自动解析 (有猫腻)
packet = pPacket(source_address, 60002, remote_address, 12345) # 我的端口 - 目标端口
local_mac = "18:65:90:cc:45:b9"
# local_mac = "00:ff:ea:6e:8f:0b"
# local_mac = "00:50:56:26:82:d1"
# local_mac = "00:00:00:00:00:00" # 理论上任意一个 mac 都可以,但会被网关过滤 (有猫腻)
# gateway_mac = "18:65:90:cc:45:b9"
# gateway_mac = "00:ff:ea:6e:8f:0b"
# gateway_mac = "00:50:56:26:82:d1"
gateway_mac = "00:00:00:00:00:00" # 只要不是自己的 mac 就可以,网关会自动处理 (有猫腻)
ether = b"%s%s%s" % (bytes.fromhex(gateway_mac.replace(":", "")), bytes.fromhex(local_mac.replace(":", "")), bytes.fromhex("0800"))
packet = ether + packet
# 这里发送的是 完全的,原始的 packet,直接把任意的内容丢出去到网关
pcap.pcap.sendpacket(pp_socket, packet)
if __name__ == "__main__":
main()
|
itielshwartz/BackendApi | lib/pyasn1_modules/rfc3447.py | Python | apache-2.0 | 1,399 | 0.00143 | #
# PKCS#1 syntax
#
# ASN.1 source from:
# ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.asn
#
# Sample captures could be obtained with "openssl genrsa" command
#
from pyasn1_modules.rfc2437 import *
class OtherPrimeInfo(univ.Sequence):
componentType = namedtype.NamedTypes(
namedtype.NamedType('prime', univ.Integer()),
namedtype.NamedType('exponent', univ.Integer()),
namedtype.NamedType('coefficient', univ.Integer())
)
class OtherPrimeInfos(univ.SequenceOf):
componentType = OtherPrimeInfo()
subtypeSpec = univ.SequenceOf.subtypeSpec + \
constraint.ValueSizeConstraint(1, MAX)
class RSAPrivateKey(univ.Sequence):
componentType = namedtype.NamedTypes(
namedtype.NamedType('version', univ.Integer(namedValues=namedval.NamedValues(('two-prime', 0), ('multi', 1)))),
namedtype.NamedType('modulus', univ.Integer()),
namedtype.NamedType('publicExponent', univ.Integer()),
namedtype.NamedType('privateExponent', univ.Integer()),
namedtype.NamedType('prime1', univ.Integer()),
namedtype.NamedType('prime2', univ.Integer()),
namedtype.NamedType('exponent | 1', univ.Integer()),
| namedtype.NamedType('exponent2', univ.Integer()),
namedtype.NamedType('coefficient', univ.Integer()),
namedtype.OptionalNamedType('otherPrimeInfos', OtherPrimeInfos())
)
|
ondra-novak/chromium.src | tools/telemetry/telemetry/core/backends/chrome/tracing_backend_unittest.py | Python | bsd-3-clause | 2,594 | 0.004626 | # Copyright 2013 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.
import cStringIO
import json
import logging
import unittest
from telemetry.core import util
from telemetry.timeline import model
from telemetry.timeline import tracing_timeline_data
from telemetry.unittest import tab_test_case
class TracingBackendTest(tab_test_case.TabTestCase):
def _StartServer(self):
self._browser.SetHTTPServerDirectories(util.GetUnittestDataDir())
def _WaitForAnimationFrame(self):
def _IsDone():
js_is_done = """done"""
return bool(self._tab.EvaluateJavaScript(js_is_done))
util.WaitFor(_IsDone, 5)
def testGotTrace(self):
if not self._browser.supports_tracing:
logging.warning('Browser does not support tracing, skipping test.')
return
self._StartServer()
self._browser.StartTracing()
self._browser.StopTracing()
# TODO(tengs): check model for correctness after trace_event_importer
# is implemented (crbug.com/173327).
class ChromeTraceResultTest(unittest.TestCase):
def __init__(self, method_name):
super(ChromeTraceResultTest, self).__init__(method_name)
def testWrite1(self):
ri = tracing_timeline_data.TracingTimelineData(map(json.loads, []))
f = cStringIO.StringIO()
ri.Serialize(f)
v = f.getvalue()
j = json.loads(v)
assert 'traceEvents' in j
self.assertEquals(j['traceEvents'], [])
def testWrite2(self):
ri = tracing_timeline_data.TracingTimelineData(map(json.loads, [
'"foo"',
'"bar"']))
f = cStringIO.StringIO()
ri.Serialize(f)
v = f.getvalue()
j = json.loads(v)
assert 'traceEvents' in j
self.assertEquals(j['traceEvents'], ['foo', 'bar'])
def testWrite3(self):
ri = tracing_timeline_data.TracingTimelineData(map(json.loads, [
'"foo"',
'"bar"',
'"baz"']))
f = cStringIO.StringIO()
ri.Serialize(f)
v = f.getvalue()
j = json.loads(v)
assert 'traceEvents' in j
self.assertEquals(j['traceEvents'],
['foo', 'bar', 'baz'])
def testBrowserProcess(self):
ri = tracing_timeline_data.TracingTimelineData(map(json.loads, [
'{"name": "process_name",'
| '"args": {"name": "Browser"},'
'"pid": | 5, "ph": "M"}',
'{"name": "thread_name",'
'"args": {"name": "CrBrowserMain"},'
'"pid": 5, "tid": 32578, "ph": "M"}']))
timeline_model = model.TimelineModel(ri)
self.assertEquals(timeline_model.browser_process.pid, 5)
|
zubair-arbi/dota-world | dota_world/settings.py | Python | mit | 8,644 | 0.001157 | """
Django settings for dota_world project.
Generated by 'django-admin startproject' using Django 1.11.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
import sys
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '(4c=bbck6l7(ws%o9%7q-$_*zlbidtmd38w4763_5*_-d_dss)'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrap3',
'django_ses',
'account',
# Local apps
'heros',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'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',
'whitenoise.middleware.WhiteNoiseMiddleware',
'account.middleware.LocaleMiddleware',
'account.middleware.TimezoneMiddleware',
# Custom middlewares
]
ROOT_URLCONF = 'dota_world.urls'
APPEND_SLASH = True
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'dota_world.context_processors.site_processor',
],
},
},
]
WSGI_APPLICATION = 'dota_world.wsgi.application'
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
# CACHE CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#caches
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
# END CACHE CONFIGURATION
# ------------------------------
# Database Configuration
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
#
# Development database
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.postgresql_psycopg2',
# 'NAME': 'dotadb',
# 'USER': 'dotauser',
# 'PASSWORD': 'doTaSecret',
# 'HOST': 'localhost',
# 'PORT': '5432',
# }
# }
# # Production database
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME': 'DB_NAME',
# 'USER': 'DB_USER',
# 'PASSWORD': 'DB_PASSWORD',
# 'HOST': 'localhost', # Or an IP Address that your DB is hosted on
# 'PORT': '3306',
# }
# }
# ------------------------------
# Heroku Database Configuration
import dj_database_url
DATABASES = {
'default': dj_database_url.config()
}
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
# AUTH_PASSWORD_VALIDATORS = [
# {
# 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
# },
# {
# 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
# },
# {
# 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
# },
# {
# 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
# },
# ]
# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id
SITE_ID = 1
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# ------------------------------
# Logging Configuration
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler',
'formatter': 'verbose'
},
'console': {
'level': 'ERROR',
'class': 'logging.StreamHandler',
'stream': sys.stdout,
'formatter': 'verbose'
},
'file': {
'level': 'ERROR',
'class': 'logging.FileHandler',
'filename': 'logs/dota_world.log',
'formatter': 'verbose'
},
},
'loggers': {
'django': {
'handlers': ['file'],
'propagate': True,
'level': 'ERROR',
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'': { # generic logger for all django apps. For specific app use format like 'cms.views'.
'handlers': ['console', 'file'],
'level': 'ERROR'
},
}
}
# ------------------------------
# Media Configuration
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
# STATIC_ROOT = os.path.join(BASE_DIR, "static/")
# STATIC_ROOT = 'staticfiles'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
# Add media directory and its base url for user uploads
MEDIA_URL = '/site_media/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "site_media/")
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'project_static'),
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
# STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
# ------------------------------
# Account configuration (django-user-accounts)
ACCOUNT_EMAIL_UNIQUE = True
ACCO | UNT_EMAIL_CONFIRMATION_EMAIL = False
ACCOUNT_EMAIL_CONFIRMATION_REQUIRED = False
ACCOUNT_OPEN_SIGNUP = False |
# AUTHENTICATION_BACKENDS = {
# "account.auth_backends.EmailAuthenticationBackend"
# }
# Specified in seconds. Enable caching by setting this to a value greater than 0.
RESPONSE_CACHE_TTL = 60 * 60
# ------------------------------
# Email configuration
DEFAULT_FROM_EMAIL = 'DotaWorld <noreply@mydomain.com>'
# # Email settings (SMTP from Google)
# EMAIL_HOST = 'smtp.gmail.com'
# EMAIL_HOST_USER = ''
# EMAIL_HOST_PASSWORD = ''
# EMAIL_USE_TLS = True
# EMAIL_PORT = 587
# Email settings (SES from AWS)
EMAIL_BACKEND = 'django_ses.SESBackend'
# These are optional -- if they're set as environment variables they won't
# need to be set here as well
AWS_ACCESS_KEY_ID = 'YOUR-AWS-ACCESS-KEY'
AWS_SECRET_ACCESS_KEY = 'YOUR-AWS-SECRET-KEY'
# Additionally, you can specify an optional region, like so:
AWS_SES_REGION_NAME = 'us-w |
CroissanceCommune/autonomie | autonomie/forms/holiday.py | Python | gpl-3.0 | 2,323 | 0.000864 | # -*- coding: utf-8 -*-
# * Copyright (C) 2012-2013 Croissance Commune
# * Authors:
# * Arezki Feth <f.a@majerti.fr>;
# * Miotte Julien <j.m@majerti.fr>;
# * Pettier Gabriel;
# * TJEBBES Gaston <g.t@majerti.fr>
#
# This file is part of Autonomie : Progiciel de gestion de CAE.
#
# Autonomie 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.
#
# Autonomie 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 Autonomie. If not, see <http://www.gnu.org/licenses/>.
#
"""
form schemas for holiday declaration
"""
import colander
import logging
from deform import widget
from autonomie.forms.user import contractor_filter_node_factory
log = logging.getLogger(__name__)
def date_validator(form, value):
if value['start_date'] >= value['end_date']:
exc | = colander.Invalid(form,
u"La date de début doit précéder la date de fin")
exc['start_date'] = u"Doit précéder la date de fin"
raise exc
class HolidaySchema(colander.MappingSchema):
start_date = colander.SchemaNode(colander.Date | (), title=u"Date de début")
end_date = colander.SchemaNode(colander.Date(), title=u"Date de fin")
class HolidaysList(colander.SequenceSchema):
holiday = HolidaySchema(title=u"Période", validator=date_validator)
class HolidaysSchema(colander.MappingSchema):
holidays = HolidaysList(title=u"",
widget=widget.SequenceWidget(min_len=1))
class SearchHolidaysSchema(colander.MappingSchema):
start_date = colander.SchemaNode(colander.Date(), title=u"Date de début")
end_date = colander.SchemaNode(colander.Date(), title=u"Date de fin")
user_id = contractor_filter_node_factory()
searchSchema = SearchHolidaysSchema(
title=u"Rechercher les congés des entrepreneurs",
validator=date_validator)
|
AnalogJ/lexicon | lexicon/providers/aliyun.py | Python | mit | 8,095 | 0.001482 | """Module provider for Aliyun"""
import base64
import datetime
import hmac
import logging
import random
import sys
import time
from hashlib import sha1
import requests
from six.moves import urllib
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = logging.getLogger(__name__)
NAMESERVER_DOMAINS = ["hichina.com"]
ALIYUN_DNS_API_ENDPOINT = "https://alidns.aliyuncs.com"
def provider_parser(subparser):
"""Module provider for Aliyun"""
subparser.description = """
Aliyun Provider requires an access key id and access secret with full rights on dns.
Better to use RAM on Aliyun cloud to create a specified user for the dns operation.
The referrence for Aliyun DNS production:
https://help.aliyun.com/product/29697.html"""
subparser.add_argument(
"--auth-key-id", help="specify access key id for authentication"
)
subparser.add_argument(
"--auth-secret", help="specify access secret for authentication"
)
class Provider(BaseProvider):
"""Provider class for Aliyun"""
def _authenticate(self):
response = self._request_aliyun("DescribeDomainInfo")
if "DomainId" not in response:
raise AuthenticationError(
f"failed to fetch basic domain info for {self.domain}"
)
self.domain_id = response["DomainId"]
return self
def _create_record(self, rtype, name, content):
if not self._list_records(rtype, name, content):
query_params = {
"Value": content,
"Type": rtype,
"RR": self._relative_name(name),
"TTL": self._get_lexicon_option("ttl"),
}
self._request_aliyun("AddDomainRecord", query_params=query_params)
return True
# List all records. Return an empty list if no records found
# type, name and content are used to filter records.
# If possible filter during the query, otherwise filter after response is received.
def _list_records(self, rtype=None, name=None, content=None):
query_params = {}
if rtype:
query_params["TypeKeyWord"] = rtype
if name:
query_params["RRKeyWord"] = self._relative_name(name)
if content:
query_params["ValueKeyWord"] = content
response = self._request_aliyun(
"DescribeDomainRecords", query_params=query_params
)
resource_list = response["DomainRecords"]["Record"]
processed_records = []
for resource in resource_list:
processed_records.append(
{
"id": resource["R | ecordId"],
"type": resource["Type"],
"name": self._full_name(resource["RR"]),
"ttl": resource["TTL"],
"content": resource["Value"],
}
)
LOGGER.debug("list_records: %s", p | rocessed_records)
return processed_records
# Create or update a record.
def _update_record(self, identifier, rtype=None, name=None, content=None):
resources = self._list_records(rtype, name, None)
for record in resources:
if (
rtype == record["type"]
and (self._relative_name(name) == self._relative_name(record["name"]))
and (content == record["content"])
):
return True
if not identifier:
record = resources[0] if resources else None
identifier = record["id"] if record else None
if not identifier:
raise ValueError(f"updating {identifier} identifier not exists")
if len(resources) > 1:
LOGGER.warning(
"""There's more than one records match the given critiaria,
only the first one would be updated"""
)
LOGGER.debug("update_record: %s", identifier)
query_params = {"RecordId": identifier}
if rtype:
query_params["Type"] = rtype
if name:
query_params["RR"] = self._relative_name(name)
if content:
query_params["Value"] = content
query_params["TTL"] = self._get_lexicon_option("ttl")
self._request_aliyun("UpdateDomainRecord", query_params=query_params)
return True
# Delete an existing record.
# If record does not exist, do nothing.
def _delete_record(self, identifier=None, rtype=None, name=None, content=None):
delete_resource_id = []
if not identifier:
resources = self._list_records(rtype, name, content)
delete_resource_id = [resource["id"] for resource in resources]
else:
delete_resource_id.append(identifier)
LOGGER.debug("delete_records: %s", delete_resource_id)
for resource_id in delete_resource_id:
self._request_aliyun(
"DeleteDomainRecord", query_params={"RecordId": resource_id}
)
return True
def _request(self, action="GET", url="/", data=None, query_params=None):
response = requests.request("GET", ALIYUN_DNS_API_ENDPOINT, params=query_params)
response.raise_for_status()
try:
return response.json()
except ValueError as invalid_json_ve:
LOGGER.error(
"aliyun dns api responsed with invalid json content, %s", response.text
)
raise invalid_json_ve
def _request_aliyun(self, action, query_params=None):
if query_params is None:
query_params = {}
query_params.update(self._build_default_query_params(action))
query_params.update(self._build_signature_parameters())
query_params.update(
{"Signature": self._calculate_signature("GET", query_params)}
)
return self._request(url=ALIYUN_DNS_API_ENDPOINT, query_params=query_params)
def _calculate_signature(self, http_method, query_params):
access_secret = self._get_provider_option("auth_secret")
if not access_secret:
raise ValueError(
"auth-secret (access secret) is not specified, did you forget that?"
)
sign_secret = access_secret + "&"
query_list = list(query_params.items())
query_list.sort(key=lambda t: t[0])
canonicalized_query_string = urllib.parse.urlencode(query_list)
string_to_sign = "&".join(
[
http_method,
urllib.parse.quote_plus("/"),
urllib.parse.quote_plus(canonicalized_query_string),
]
)
if sys.version_info.major > 2:
sign_secret_bytes = bytes(sign_secret, "utf-8")
string_to_sign_bytes = bytes(string_to_sign, "utf-8")
sign = hmac.new(sign_secret_bytes, string_to_sign_bytes, sha1)
signature = base64.b64encode(sign.digest()).decode()
else:
sign = hmac.new(sign_secret, string_to_sign, sha1)
signature = sign.digest().encode("base64").rstrip("\n")
return signature
def _build_signature_parameters(self):
access_key_id = self._get_provider_option("auth_key_id")
if not access_key_id:
raise ValueError(
"auth-key-id (access key id) is not specified, did you forget that?"
)
signature_nonce = str(int(time.time())) + str(random.randint(1000, 9999))
return {
"SignatureMethod": "HMAC-SHA1",
"SignatureVersion": "1.0",
"SignatureNonce": signature_nonce,
"Timestamp": datetime.datetime.utcnow().replace(microsecond=0).isoformat()
+ "Z",
"AccessKeyId": access_key_id,
}
def _build_default_query_params(self, action):
return {
"Action": action,
"DomainName": self.domain,
"Format": "json",
"Version": "2015-01-09",
}
|
sudoes/UTEM-Vote | config.py | Python | mit | 105 | 0 | class Config(object | ):
DEBUG = False
TESTING = False
class DevConfig(Config | ):
DEBUG = False
|
Jortolsa/l10n-spain | l10n_es_aeat_mod303/models/mod303.py | Python | agpl-3.0 | 7,898 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# 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/.
#
##############################################################################
from openerp import models, fields, api, exceptions, _
class L10nEsAeatMod303Report(models.Model):
_inherit = "l10n.es.aeat.report"
_name = "l10n.es.aeat.mod303.report"
_description = "AEAT 303 Report"
def _get_export_conf(self):
try:
return self.env.ref(
'l10n_es_aeat_mod303.aeat_mod303_main_export_config').id
except ValueError:
return self.env['aeat.model.export.config']
def _default_counterpart_303(self):
return self.env['account.account'].search(
[('code', 'like', '4750%'), ('type', '!=', 'view')])[:1]
currency_id = fields.Many2one(
comodel_name='res.currency', string='Currency',
related='company_id.currency_id', store=True)
number = fields.Char(default='303')
export_config = fields.Many2one(default=_get_export_conf)
company_partner_id = fields.Many2one('res.partner', string='Partner',
relation='company_id.partner_id',
store=True)
devolucion_mensual = fields.Boolean(
string="Devolución mensual", states={'done': [('readonly', True)]},
help="Inscrito en el Registro de Devolución Mensual")
total_devengado = fields.Float(string="[27] IVA devengado", readonly=True)
total_deducir = fields.Float(string="[45] IVA a deducir", readonly=True)
casilla_46 = fields.Float(
string="[46] Resultado régimen general", readonly=True,
help="(IVA devengado - IVA deducible)")
porcentaje_atribuible_estado = fields.Float(
string="[65] % atribuible al Estado",
states={'done': [('readonly', True)]},
help="Los sujetos pasivos que tributen conjuntamente a la "
"Administración del Estado y a las Diputaciones Forales del País "
"Vasco o a la Comunidad Foral de Navarra, consignarán en esta "
"casilla el porcentaje del volumen de operaciones en territorio "
"común. Los demás sujetos pasivos consignarán en esta casilla el "
"100%", default=100)
atribuible_estado = fields.Float(
string="[66] Atribuible a la Administración", readonly=True)
cuota_compensar = fields.Float(
string="[67] Cuotas a compensar", default=0,
states={'done': [('readonly', True)]},
help="Cuota a compensar de periodos anteriores, en los que su "
"declaración fue a devolver y se escogió la opción de "
"compensación posterior")
regularizacion_anual = fields.Float(
string="[68] Regularización anual",
states={'done': [('readonly', True)]},
help="En la última autoliquidación del año (la del período 4T o mes "
"12) se hará constar, con el signo que corresponda, el resultado "
"de la regularización anual conforme disponen las Leyes por las "
"que se aprueban el Concierto Económico entre el Estado y la "
"Comunidad Autónoma del País Vasco y el Convenio Económico entre "
"el Estado y la Comunidad Foral de Navarra.""")
casilla_69 = fields.Float(
string="[69] | Resultado", readonly=True,
help="Atribuible a la Administración [66] - Cuotas a compensar [67] + "
"Regularización anual [68]""")
previous_result = fields.Float(
string="[70] A deducir",
help="Resultado d | e la anterior o anteriores declaraciones del mismo "
"concepto, ejercicio y periodo",
states={'done': [('readonly', True)]})
resultado_liquidacion = fields.Float(
string="[71] Result. liquidación", readonly=True)
result_type = fields.Selection(
selection=[('I', 'A ingresar'),
('D', 'A devolver'),
('N', 'Sin actividad/Resultado cero')],
compute="_compute_result_type")
compensate = fields.Boolean(
string="Compensate", states={'done': [('readonly', True)]},
help="Si se marca, indicará que el importe a devolver se compensará "
"en posteriores declaraciones")
bank_account = fields.Many2one(
comodel_name="res.partner.bank", string="Bank account",
states={'done': [('readonly', True)]})
counterpart_account = fields.Many2one(default=_default_counterpart_303)
allow_posting = fields.Boolean(default=True)
def __init__(self, pool, cr):
self._aeat_number = '303'
super(L10nEsAeatMod303Report, self).__init__(pool, cr)
@api.one
def _compute_allow_posting(self):
self.allow_posting = True
@api.one
@api.depends('resultado_liquidacion')
def _compute_result_type(self):
if self.resultado_liquidacion == 0:
self.result_type = 'N'
elif self.resultado_liquidacion > 0:
self.result_type = 'I'
else:
self.result_type = 'D'
@api.onchange('period_type', 'fiscalyear_id')
def onchange_period_type(self):
super(L10nEsAeatMod303Report, self).onchange_period_type()
if self.period_type not in ('4T', '12'):
self.regularizacion_anual = 0
@api.onchange('type')
def onchange_type(self):
if self.type != 'C':
self.previous_result = 0
@api.onchange('result_type')
def onchange_result_type(self):
if self.result_type != 'B':
self.compensate = False
@api.multi
def calculate(self):
res = super(L10nEsAeatMod303Report, self).calculate()
for mod303 in self:
total_devengado = mod303.tax_lines.filtered(
lambda x: x.field_number == 27).amount
total_deducir = mod303.tax_lines.filtered(
lambda x: x.field_number == 45).amount
casilla_46 = total_devengado - total_deducir
atribuible_estado = (
casilla_46 * mod303.porcentaje_atribuible_estado / 100)
casilla_69 = (atribuible_estado - mod303.cuota_compensar +
mod303.regularizacion_anual)
resultado_liquidacion = casilla_69 - mod303.previous_result
vals = {
'total_devengado': total_devengado,
'total_deducir': total_deducir,
'casilla_46': casilla_46,
'atribuible_estado': atribuible_estado,
'casilla_69': casilla_69,
'resultado_liquidacion': resultado_liquidacion,
}
mod303.write(vals)
return res
@api.multi
def button_confirm(self):
"""Check records"""
msg = ""
for mod303 in self:
if mod303.result_type == 'I' and not mod303.bank_account:
msg = _('Select an account for making the charge')
if mod303.result_type == 'B' and not not mod303.bank_account:
msg = _('Select an account for receiving the money')
if msg:
raise exceptions.Warning(msg)
return super(L10nEsAeatMod303Report, self).button_confirm()
|
jiadaizhao/LeetCode | 0101-0200/0199-Binary Tree Right Side View/0199-Binary Tree Right Side View.py | Python | mit | 493 | 0.004057 | # Definition f | or a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if root is None:
return []
level = [root]
result = []
while level:
result.append(level[-1].val)
level = [child for node in level for child in (node.left, node.right) if child]
return result
| |
FTAsr/STS | monolingual-word-aligner/wordSim.py | Python | mit | 2,728 | 0.008431 | from config import *
################################################################################
def loadPPDB(ppdbFileName = '../monolingual-word-aligner/ppdb-1.0-xxxl-lexical.extended.synonyms.uniquepairs'):
global ppdbSim
global ppdbDict
count = 0
ppdbFile = open(ppdbFileName, 'r')
for line in ppdbFile:
if line == '\n':
continue
tokens = line.split()
tokens[1] = tokens[1].strip()
ppdbDict[ | (tokens[0], tokens[1])] = ppdbSim
count += 1
################################################################################
################################################################################
def presentInPPDB(word1, word2):
global ppdbDict
if (word1.lower(), word2.lower()) in ppdbDict:
return True
if (word2.lower(), word1.lower()) in ppdbDict:
return True
# | ###############################################################################
##############################################################################################################################
def wordRelatedness(word1, pos1, word2, pos2):
global stemmer
global ppdbSim
global punctuations
if len(word1) > 1:
canonicalWord1 = word1.replace('.', '')
canonicalWord1 = canonicalWord1.replace('-', '')
canonicalWord1 = canonicalWord1.replace(',', '')
else:
canonicalWord1 = word1
if len(word2) > 1:
canonicalWord2 = word2.replace('.', '')
canonicalWord2 = canonicalWord2.replace('-', '')
canonicalWord2 = canonicalWord2.replace(',', '')
else:
canonicalWord2 = word2
if canonicalWord1.lower() == canonicalWord2.lower():
return 1
if stemmer.stem(word1).lower() == stemmer.stem(word2).lower():
return 1
if canonicalWord1.isdigit() and canonicalWord2.isdigit() and canonicalWord1 <> canonicalWord2:
return 0
if pos1.lower() == 'cd' and pos2.lower() == 'cd' and (not canonicalWord1.isdigit() and not canonicalWord2.isdigit()) and canonicalWord1 <> canonicalWord2:
return 0
# stopwords can be similar to only stopwords
if (word1.lower() in stopwords and word2.lower() not in stopwords) or (word1.lower() not in stopwords and word2.lower() in stopwords):
return 0
# punctuations can only be either identical or totally dissimilar
if word1 in punctuations or word2 in punctuations:
return 0
if presentInPPDB(word1.lower(), word2.lower()):
return ppdbSim
else:
return 0
##############################################################################################################################
loadPPDB()
|
theKono/mobile-push | tests/factories/topic.py | Python | apache-2.0 | 422 | 0.00237 | #!/usr/bin/env python
# standard li | brary imports
# third party related imports
import factory
# local library imports
from mobile_push.db import Session, Topic
class TopicFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta(object):
model = Topic
sqlalchemy_session = Session
name = factory.Sequence(lambda n: 'topic-%s' % n)
arn = factory.Sequence(lambda | n: 'topic-arn-%s' % n)
|
andrevmatos/Librix-ThinClient | src/__init__.py | Python | gpl-2.0 | 777 | 0.005148 | #!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Lice | nse as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient 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 librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
__all__ = [
'ui',
'lib',
'daemon',
'modules',
]
|
thatneat/petl | petl/test/transform/test_basics.py | Python | mit | 17,148 | 0.000058 | from __future__ import absolute_import, print_function, division
from petl.test.helpers import ieq
from petl.util import expr, empty, coalesce
from petl.transform.basics import cut, cat, addfield, rowslice, h | ead, tail, \
cutout, skipcomments, annex, addrownumbers, addcolumn, \
addfieldusingcontext, movefield, stack
def test_cut():
table = (('foo', 'bar', 'baz'),
('A', 1, 2),
('B', '2', '3.4'),
(u'B', u'3', u'7.8 | ', True),
('D', 'xyz', 9.0),
('E', None))
cut1 = cut(table, 'foo')
expectation = (('foo',),
('A',),
('B',),
(u'B',),
('D',),
('E',))
ieq(expectation, cut1)
cut2 = cut(table, 'foo', 'baz')
expectation = (('foo', 'baz'),
('A', 2),
('B', '3.4'),
(u'B', u'7.8'),
('D', 9.0),
('E', None))
ieq(expectation, cut2)
cut3 = cut(table, 0, 2)
expectation = (('foo', 'baz'),
('A', 2),
('B', '3.4'),
(u'B', u'7.8'),
('D', 9.0),
('E', None))
ieq(expectation, cut3)
cut4 = cut(table, 'bar', 0)
expectation = (('bar', 'foo'),
(1, 'A'),
('2', 'B'),
(u'3', u'B'),
('xyz', 'D'),
(None, 'E'))
ieq(expectation, cut4)
cut5 = cut(table, ('foo', 'baz'))
expectation = (('foo', 'baz'),
('A', 2),
('B', '3.4'),
(u'B', u'7.8'),
('D', 9.0),
('E', None))
ieq(expectation, cut5)
def test_cut_empty():
table = (('foo', 'bar'),)
expect = (('bar',),)
actual = cut(table, 'bar')
ieq(expect, actual)
def test_cutout():
table = (('foo', 'bar', 'baz'),
('A', 1, 2),
('B', '2', '3.4'),
(u'B', u'3', u'7.8', True),
('D', 'xyz', 9.0),
('E', None))
cut1 = cutout(table, 'bar', 'baz')
expectation = (('foo',),
('A',),
('B',),
(u'B',),
('D',),
('E',))
ieq(expectation, cut1)
cut2 = cutout(table, 'bar')
expectation = (('foo', 'baz'),
('A', 2),
('B', '3.4'),
(u'B', u'7.8'),
('D', 9.0),
('E', None))
ieq(expectation, cut2)
cut3 = cutout(table, 1)
expectation = (('foo', 'baz'),
('A', 2),
('B', '3.4'),
(u'B', u'7.8'),
('D', 9.0),
('E', None))
ieq(expectation, cut3)
def test_cat():
table1 = (('foo', 'bar'),
(1, 'A'),
(2, 'B'))
table2 = (('bar', 'baz'),
('C', True),
('D', False))
cat1 = cat(table1, table2, missing=None)
expectation = (('foo', 'bar', 'baz'),
(1, 'A', None),
(2, 'B', None),
(None, 'C', True),
(None, 'D', False))
ieq(expectation, cat1)
# how does cat cope with uneven rows?
table3 = (('foo', 'bar', 'baz'),
('A', 1, 2),
('B', '2', '3.4'),
(u'B', u'3', u'7.8', True),
('D', 'xyz', 9.0),
('E', None))
cat3 = cat(table3, missing=None)
expectation = (('foo', 'bar', 'baz'),
('A', 1, 2),
('B', '2', '3.4'),
(u'B', u'3', u'7.8'),
('D', 'xyz', 9.0),
('E', None, None))
ieq(expectation, cat3)
# cat more than two tables?
cat4 = cat(table1, table2, table3)
expectation = (('foo', 'bar', 'baz'),
(1, 'A', None),
(2, 'B', None),
(None, 'C', True),
(None, 'D', False),
('A', 1, 2),
('B', '2', '3.4'),
(u'B', u'3', u'7.8'),
('D', 'xyz', 9.0),
('E', None, None))
ieq(expectation, cat4)
def test_cat_with_header():
table1 = (('bar', 'foo'),
('A', 1),
('B', 2))
table2 = (('bar', 'baz'),
('C', True),
('D', False))
actual = cat(table1, header=['A', 'foo', 'B', 'bar', 'C'])
expect = (('A', 'foo', 'B', 'bar', 'C'),
(None, 1, None, 'A', None),
(None, 2, None, 'B', None))
ieq(expect, actual)
ieq(expect, actual)
actual = cat(table1, table2, header=['A', 'foo', 'B', 'bar', 'C'])
expect = (('A', 'foo', 'B', 'bar', 'C'),
(None, 1, None, 'A', None),
(None, 2, None, 'B', None),
(None, None, None, 'C', None),
(None, None, None, 'D', None))
ieq(expect, actual)
ieq(expect, actual)
def test_cat_empty():
table1 = (('foo', 'bar'),
(1, 'A'),
(2, 'B'))
table2 = (('bar', 'baz'),)
expect = (('foo', 'bar', 'baz'),
(1, 'A', None),
(2, 'B', None))
actual = cat(table1, table2)
ieq(expect, actual)
def test_cat_dupfields():
table1 = (('foo', 'foo'),
(1, 'A'),
(2,),
(3, 'B', True))
# these cases are pathological, including to confirm expected behaviour,
# but user needs to rename fields to get something sensible
actual = cat(table1)
expect = (('foo', 'foo'),
(1, 1),
(2, 2),
(3, 3))
ieq(expect, actual)
table2 = (('foo', 'foo', 'bar'),
(4, 'C', True),
(5, 'D', False))
actual = cat(table1, table2)
expect = (('foo', 'foo', 'bar'),
(1, 1, None),
(2, 2, None),
(3, 3, None),
(4, 4, True),
(5, 5, False))
ieq(expect, actual)
def test_stack_dupfields():
table1 = (('foo', 'foo'),
(1, 'A'),
(2,),
(3, 'B', True))
actual = stack(table1)
expect = (('foo', 'foo'),
(1, 'A'),
(2, None),
(3, 'B'))
ieq(expect, actual)
table2 = (('foo', 'foo', 'bar'),
(4, 'C', True),
(5, 'D', False))
actual = stack(table1, table2)
expect = (('foo', 'foo'),
(1, 'A'),
(2, None),
(3, 'B'),
(4, 'C'),
(5, 'D'))
ieq(expect, actual)
def test_addfield():
table = (('foo', 'bar'),
('M', 12),
('F', 34),
('-', 56))
result = addfield(table, 'baz', 42)
expectation = (('foo', 'bar', 'baz'),
('M', 12, 42),
('F', 34, 42),
('-', 56, 42))
ieq(expectation, result)
ieq(expectation, result)
result = addfield(table, 'baz', lambda row: '%s,%s' % (row.foo, row.bar))
expectation = (('foo', 'bar', 'baz'),
('M', 12, 'M,12'),
('F', 34, 'F,34'),
('-', 56, '-,56'))
ieq(expectation, result)
ieq(expectation, result)
result = addfield(table, 'baz', lambda rec: rec['bar'] * 2)
expectation = (('foo', 'bar', 'baz'),
('M', 12, 24),
('F', 34, 68),
('-', 56, 112))
ieq(expectation, result)
ieq(expectation, result)
result = addfield(table, 'baz', expr('{bar} * 2'))
expectation = (('foo', 'bar', 'baz'),
('M', 12, 24),
('F', 34, 68),
('-', 56, 112))
ieq(expectation, result)
ieq(expectation, result)
result = addfield(table, 'baz', 42, index=0)
expectation = (('baz', 'foo', 'bar'),
(42, 'M', 12),
(42, 'F', 34),
(42, '-', 56))
ieq(expectation, result)
ieq(expectation, result |
pretix/django-formset-js | example/example/urls.py | Python | bsd-2-clause | 147 | 0.006803 | from | django.conf.urls import patterns, include, url
import example.views
urlpatterns = patterns('',
url(r | '^$', example.views.formset_view),
)
|
synthicity/activitysim | activitysim/estimation/larch/auto_ownership.py | Python | agpl-3.0 | 1,942 | 0.00103 | import os
import numpy as np
import pandas as pd
import yaml
from typing import Collection
from larch.util import Dict
from .simple_simulate import simple_simulate_data
from .general import (
remove_apostrophes,
apply_coefficients,
dict_of_linear_utility_from_spec,
)
from larch import Model, DataFrames, P, X
def auto_ownership_model(
name="auto_ownership",
edb_directory="output/estimation_data_bundle/{name}/",
return_data=False,
):
data = simple_simulate_data(
name=name, edb_directory=edb_directory, values_index_col="household_id",
)
coefficients = data.coefficients
# coef_template = data.coef_template # not used
spec = data.spec
chooser_data = data.chooser_data
settings = data.settings
altnames = list(spec.columns[3:])
altcodes = range(len(altnames))
chooser_data = remove_apostrophes(chooser_data)
chooser_data.fillna(0, inplace=True)
# Remove choosers with invalid observed choice
chooser_data = chooser_data[chooser_data["overr | ide_choice"] >= 0]
m = Model()
# One of the alternatives is coded as 0, so
# we need to explicitly initialize the MNL nesting graph
# and set to root_id to a value other than zero.
m.initialize_graph(alternative_codes=altcodes, root_id=99)
m.utility_co = dict_of_linear_utility | _from_spec(
spec, "Label", dict(zip(altnames, altcodes)),
)
apply_coefficients(coefficients, m)
d = DataFrames(co=chooser_data, av=True, alt_codes=altcodes, alt_names=altnames,)
m.dataservice = d
m.choice_co_code = "override_choice"
if return_data:
return (
m,
Dict(
edb_directory=data.edb_directory,
chooser_data=chooser_data,
coefficients=coefficients,
spec=spec,
altnames=altnames,
altcodes=altcodes,
),
)
return m
|
lupyuen/RaspberryPiImage | usr/share/pyshared/ajenti/plugins/main/controls_inputs.py | Python | apache-2.0 | 3,085 | 0 | import calendar
import datetime
import os
import time
from ajenti.api import *
from ajenti.ui import p, UIElement, on
@p('value', default='', bindtypes=[str, unicode, int, long])
@p('readonly', type=bool, default=False)
@p('type', default='text')
@plugin
class TextBox (UIElement):
typeid = 'textbox'
@p('value', default='', bindtypes=[str, unicode, int, long])
@plugin
class PasswordBox (UIElement):
typeid = 'passwordbox'
@p('value', default='', type=int, bindtypes=[str, unicode, int, long])
@plugin
class DateTime (UIElement):
typeid = 'datetime'
@property
def dateobject(self):
| if self.value:
return datetime.fromtimestamp(self.value)
@dateobject.setter
def dateobject__set(self, value):
if value:
self.value = calendar.timeg | m(value.timetuple())
else:
self.value = None
@p('value', default='', bindtypes=[str, unicode])
@p('icon', default=None)
@p('placeholder', default=None)
@plugin
class Editable (UIElement):
typeid = 'editable'
@p('text', default='')
@p('value', default=False, bindtypes=[bool])
@plugin
class CheckBox (UIElement):
typeid = 'checkbox'
@p('labels', default=[], type=list)
@p('values', default=[], type=list, public=False)
@p('value', bindtypes=[object], public=False)
@p('index', default=0, type=int)
@p('server', default=False, type=bool)
@p('plain', default=False, type=bool)
@plugin
class Dropdown (UIElement):
typeid = 'dropdown'
def value_get(self):
if self.index < len(self.values):
try:
return self.values[self.index]
except TypeError:
return None
return None
def value_set(self, value):
if value in self.values:
self.index = self.values.index(value)
else:
self.index = 0
value = property(value_get, value_set)
@p('labels', default=[], type=list)
@p('values', default=[], type=list)
@p('separator', default=None, type=str)
@p('value', default='', bindtypes=[str, unicode])
@plugin
class Combobox (UIElement):
typeid = 'combobox'
@p('target', type=str)
@plugin
class FileUpload (UIElement):
typeid = 'fileupload'
@p('active', type=int)
@p('length', type=int)
@plugin
class Paging (UIElement):
typeid = 'paging'
@p('value', default='', bindtypes=[str, unicode])
@p('directory', default=False, type=bool)
@p('type', default='text')
@plugin
class Pathbox (UIElement):
typeid = 'pathbox'
def init(self, *args, **kwargs):
if self.directory:
self.dialog = self.ui.create('opendirdialog')
else:
self.dialog = self.ui.create('openfiledialog')
self.append(self.dialog)
self.dialog.id = 'dialog'
self.dialog.visible = False
def on_start(self):
self.find('dialog').navigate(os.path.split(self.value or '')[0] or '/')
self.find('dialog').visible = True
@on('dialog', 'select')
def on_select(self, path=None):
self.find('dialog').visible = False
if path:
self.value = path
|
ostree/plaso | tests/parsers/olecf_plugins/test_lib.py | Python | apache-2.0 | 2,117 | 0.001889 | # -*- coding: utf-8 -*-
"""OLECF plugin related functions and classes for testing."""
import pyolecf
from plaso.engine import single_process
from tests.parsers import test_lib
class OleCfPluginTestCase(test_lib.ParserTestCase):
"""The unit test case for OLE CF based plugins."""
def _OpenOleCfFile(self, path, codepage=u'cp1252'):
"""Opens an OLE compound file and returns back a pyolecf.file object.
Args:
pa | th: The path to the OLE CF test file.
codepage: Optional codepage. The default is cp1252.
"""
file_entry = self._GetTestFileEntryFromPath([path])
file_object = file_entry.GetFileObject()
olecf_file = pyolecf.file()
olecf_file.set_ascii_codepage(codepage)
olecf_file.open_file_object(file_object)
return olecf_file
def _ParseOleCfFileWithPlugin(
self, path, plugin_object, knowledge_base_values=None):
"""Parses a file as an OLE compound file and returns an eve | nt generator.
Args:
path: The path to the OLE CF test file.
plugin_object: The plugin object that is used to extract an event
generator.
knowledge_base_values: optional dict containing the knowledge base
values. The default is None.
Returns:
An event object queue consumer object (instance of
TestItemQueueConsumer).
"""
event_queue = single_process.SingleProcessQueue()
event_queue_consumer = test_lib.TestItemQueueConsumer(event_queue)
parse_error_queue = single_process.SingleProcessQueue()
parser_mediator = self._GetParserMediator(
event_queue, parse_error_queue,
knowledge_base_values=knowledge_base_values)
olecf_file = self._OpenOleCfFile(path)
file_entry = self._GetTestFileEntryFromPath([path])
parser_mediator.SetFileEntry(file_entry)
# Get a list of all root items from the OLE CF file.
root_item = olecf_file.root_item
item_names = [item.name for item in root_item.sub_items]
plugin_object.Process(
parser_mediator, root_item=root_item, item_names=item_names)
return event_queue_consumer
|
usc-isi-i2/etk | etk/unit_tests/test_language_identification_extractor.py | Python | mit | 1,687 | 0.001778 | import unittest
from etk.extractors.language_identification_extractor import LanguageIdentificationExtractor
class TestLanguageIdentificationExtractor(unittest.TestCase):
def test_langid(self):
extractor = LanguageIdentificationExtractor()
text_en = "langid.py comes pre-trained on 97 languages (ISO 639-1 codes g | iven)"
result_en = extractor.extract(text_en, "LANGID")
self.assertEqual(result_en[0].value, "en")
text_es = "Hola Mundo"
result_es = extractor.extract(text_es, "LANGID")
self.assertEqual(result_es[0].value, "es")
text_de = "Ein, zwei, drei, vier"
result_de = extractor.extract(text_de, "LANGID")
self.assertEqual(result_de[0].value, "de")
text_unknown = "%$@$%##"
result_u | nknown = extractor.extract(text_unknown, "LANGID")
self.assertEqual(result_unknown[0].value, "en")
def test_langdetect(self):
extractor = LanguageIdentificationExtractor()
text_en = "langdetect supports 55 languages out of the box (ISO 639-1 codes)"
result_en = extractor.extract(text_en, "LANGDETECT")
self.assertEqual(result_en[0].value, "en")
text_es = "Hola Mundo"
result_es = extractor.extract(text_es, "LANGDETECT")
self.assertEqual(result_es[0].value, "es")
text_de = "Ein, zwei, drei, vier"
result_de = extractor.extract(text_de, "LANGDETECT")
self.assertEqual(result_de[0].value, "de")
text_unknown = "%$@$%##"
result_unknown = extractor.extract(text_unknown, "LANGDETECT")
self.assertTrue(len(result_unknown) == 0)
if __name__ == '__main__':
unittest.main()
|
sunze/py_flask | venv/lib/python3.4/site-packages/celery/tests/security/test_serialization.py | Python | mit | 2,252 | 0 | from __future__ import absolute_import
import os
import base64
from kombu.serialization import registry
from celery.exceptions import SecurityError
from celery.security.serialization import SecureSerializer, register_auth
from celery.security.certificate import Certificate, CertStore
from celery.security.key import PrivateKey
from . import CERT1, CERT2, KEY1, KEY2
from .case import SecurityCase
class test_SecureSerializer(SecurityCase):
def _get_s(self, key, cert, certs):
store = CertStore()
for c in certs:
store.add_cert(Certificate(c))
return SecureSerializer(PrivateKey(key), Certificate(cert), store)
def test_serialize(self):
s = self._get_s(KEY1, CERT1, [CERT1])
self.assertEqual(s.deserialize(s.serialize('foo')), 'foo')
def test_deserialize(self):
s = self._get_s(KEY1, CERT1, [CERT1])
self.assertRaises(SecurityError, s.deserialize, 'bad data')
def test_unmatched_key_cert(self):
s = self._get_s(KEY1, CERT2, [CERT1, CERT2])
self.assertRaises(SecurityError,
s.deserialize, s.serialize('foo'))
def test_unknown_source(self):
s1 = self._get_s(KEY1, CERT1, [CERT2])
| s2 = self._get_s(KEY1, CERT1, [])
self.assertRaises(SecurityError,
s1.deserialize, s1.serialize('foo'))
self.assertRaises(SecurityError,
s2.deseri | alize, s2.serialize('foo'))
def test_self_send(self):
s1 = self._get_s(KEY1, CERT1, [CERT1])
s2 = self._get_s(KEY1, CERT1, [CERT1])
self.assertEqual(s2.deserialize(s1.serialize('foo')), 'foo')
def test_separate_ends(self):
s1 = self._get_s(KEY1, CERT1, [CERT2])
s2 = self._get_s(KEY2, CERT2, [CERT1])
self.assertEqual(s2.deserialize(s1.serialize('foo')), 'foo')
def test_register_auth(self):
register_auth(KEY1, CERT1, '')
self.assertIn('application/data', registry._decoders)
def test_lots_of_sign(self):
for i in range(1000):
rdata = base64.urlsafe_b64encode(os.urandom(265))
s = self._get_s(KEY1, CERT1, [CERT1])
self.assertEqual(s.deserialize(s.serialize(rdata)), rdata)
|
aequitas/home-assistant | homeassistant/components/ambiclimate/climate.py | Python | apache-2.0 | 7,406 | 0 | """Support for Ambiclimate ac."""
import asyncio
import logging
import ambiclimate
import voluptuous as vol
from homeassistant.components.climate import ClimateDevice
from homeassistant.components.climate.const import (
SUPPORT_TARGET_TEMPERATURE,
SUPPORT_ON_OFF, STATE_HEAT)
from homeassistant.const import ATTR_NAME
from homeassistant.const import ( | ATTR_TEMPERATURE,
STATE_OFF, TEMP_CELSIUS)
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import (ATTR_VALUE, CONF_CLIENT_ID, CONF_CLIENT_SECRET,
DOMAIN | , SERVICE_COMFORT_FEEDBACK, SERVICE_COMFORT_MODE,
SERVICE_TEMPERATURE_MODE, STORAGE_KEY, STORAGE_VERSION)
_LOGGER = logging.getLogger(__name__)
SUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE |
SUPPORT_ON_OFF)
SEND_COMFORT_FEEDBACK_SCHEMA = vol.Schema({
vol.Required(ATTR_NAME): cv.string,
vol.Required(ATTR_VALUE): cv.string,
})
SET_COMFORT_MODE_SCHEMA = vol.Schema({
vol.Required(ATTR_NAME): cv.string,
})
SET_TEMPERATURE_MODE_SCHEMA = vol.Schema({
vol.Required(ATTR_NAME): cv.string,
vol.Required(ATTR_VALUE): cv.string,
})
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up the Ambicliamte device."""
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the Ambicliamte device from config entry."""
config = entry.data
websession = async_get_clientsession(hass)
store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
token_info = await store.async_load()
oauth = ambiclimate.AmbiclimateOAuth(config[CONF_CLIENT_ID],
config[CONF_CLIENT_SECRET],
config['callback_url'],
websession)
try:
_token_info = await oauth.refresh_access_token(token_info)
except ambiclimate.AmbiclimateOauthError:
_LOGGER.error("Failed to refresh access token")
return
if _token_info:
await store.async_save(_token_info)
token_info = _token_info
data_connection = ambiclimate.AmbiclimateConnection(oauth,
token_info=token_info,
websession=websession)
if not await data_connection.find_devices():
_LOGGER.error("No devices found")
return
tasks = []
for heater in data_connection.get_devices():
tasks.append(heater.update_device_info())
await asyncio.wait(tasks)
devs = []
for heater in data_connection.get_devices():
devs.append(AmbiclimateEntity(heater, store))
async_add_entities(devs, True)
async def send_comfort_feedback(service):
"""Send comfort feedback."""
device_name = service.data[ATTR_NAME]
device = data_connection.find_device_by_room_name(device_name)
if device:
await device.set_comfort_feedback(service.data[ATTR_VALUE])
hass.services.async_register(DOMAIN,
SERVICE_COMFORT_FEEDBACK,
send_comfort_feedback,
schema=SEND_COMFORT_FEEDBACK_SCHEMA)
async def set_comfort_mode(service):
"""Set comfort mode."""
device_name = service.data[ATTR_NAME]
device = data_connection.find_device_by_room_name(device_name)
if device:
await device.set_comfort_mode()
hass.services.async_register(DOMAIN,
SERVICE_COMFORT_MODE,
set_comfort_mode,
schema=SET_COMFORT_MODE_SCHEMA)
async def set_temperature_mode(service):
"""Set temperature mode."""
device_name = service.data[ATTR_NAME]
device = data_connection.find_device_by_room_name(device_name)
if device:
await device.set_temperature_mode(service.data[ATTR_VALUE])
hass.services.async_register(DOMAIN,
SERVICE_TEMPERATURE_MODE,
set_temperature_mode,
schema=SET_TEMPERATURE_MODE_SCHEMA)
class AmbiclimateEntity(ClimateDevice):
"""Representation of a Ambiclimate Thermostat device."""
def __init__(self, heater, store):
"""Initialize the thermostat."""
self._heater = heater
self._store = store
self._data = {}
@property
def unique_id(self):
"""Return a unique ID."""
return self._heater.device_id
@property
def name(self):
"""Return the name of the entity."""
return self._heater.name
@property
def device_info(self):
"""Return the device info."""
return {
'identifiers': {
(DOMAIN, self.unique_id)
},
'name': self.name,
'manufacturer': 'Ambiclimate',
}
@property
def temperature_unit(self):
"""Return the unit of measurement which this thermostat uses."""
return TEMP_CELSIUS
@property
def target_temperature(self):
"""Return the target temperature."""
return self._data.get('target_temperature')
@property
def target_temperature_step(self):
"""Return the supported step of target temperature."""
return 1
@property
def current_temperature(self):
"""Return the current temperature."""
return self._data.get('temperature')
@property
def current_humidity(self):
"""Return the current humidity."""
return self._data.get('humidity')
@property
def is_on(self):
"""Return true if heater is on."""
return self._data.get('power', '').lower() == 'on'
@property
def min_temp(self):
"""Return the minimum temperature."""
return self._heater.get_min_temp()
@property
def max_temp(self):
"""Return the maximum temperature."""
return self._heater.get_max_temp()
@property
def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_FLAGS
@property
def current_operation(self):
"""Return current operation."""
return STATE_HEAT if self.is_on else STATE_OFF
async def async_set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is None:
return
await self._heater.set_target_temperature(temperature)
async def async_turn_on(self):
"""Turn device on."""
await self._heater.turn_on()
async def async_turn_off(self):
"""Turn device off."""
await self._heater.turn_off()
async def async_update(self):
"""Retrieve latest state."""
try:
token_info = await self._heater.control.refresh_access_token()
except ambiclimate.AmbiclimateOauthError:
_LOGGER.error("Failed to refresh access token")
return
if token_info:
await self._store.async_save(token_info)
self._data = await self._heater.update_device()
|
SymbiFlow/symbolator | nucanvas/cairo_backend.py | Python | mit | 13,085 | 0.021629 | # -*- coding: utf-8 -*-
# Copyright © 2017 Kevin Thibedeau
# Distributed under the terms of the MIT license
import os
import math
import gi
import cairo
from .shapes import *
try:
import pango
import pangocairo
use_pygobject = False
except ImportError:
gi.require_version('Pango', '1.0')
from gi.repository import Pango as pango
gi.require_version('PangoCairo', '1.0')
from gi.repository import PangoCairo as pangocairo
use_pygobject = True
#################################
## CAIRO objects
#################################
def rgb_to_cairo(rgb):
if len(rgb) == 4:
r,g,b,a = rgb
return (r / 255.0, g / 255.0, b / 255.0, a / 255.0)
else:
r,g,b = rgb
return (r / 255.0, g / 255.0, b / 255.0, 1.0)
def cairo_font(tk_font):
family, size, weight = tk_font
return pango.FontDescription('{} {} {}'.format(family, weight, size))
def cairo_line_cap(line_cap):
if line_cap == 'round':
return cairo.LINE_CAP_ROUND
elif line_cap == 'square':
return cairo.LINE_CAP_SQUARE
else:
return cairo.LINE_CAP_BUTT
class CairoSurface(BaseSurface):
def __init__(self, fname, def_styles, padding=0, scale=1.0):
BaseSurface.__init__(self, fname, def_styles, padding, scale)
self.ctx = None
def render(self, canvas, transparent=False):
x0,y0,x1,y1 = canvas.bbox('all')
self.markers = canvas.markers
W = int((x1 - x0 + 2*self.padding) * self.scale)
H = int((y1 - y0 + 2*self.padding) * self.scale)
ext = os.path.splitext(self.fname)[1].lower()
if ext == '.svg':
surf = cairo.SVGSurface(self.fname, W, H)
elif ext == '.pdf':
surf = cairo.PDFSurface(self.fname, W, H)
elif ext in ('.ps', '.eps'):
surf = cairo.PSSurface(self.fname, W, H)
if ext == '.eps':
surf.set_eps(True)
else: # Bitmap
surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, W, H)
self.ctx = cairo.Context(surf)
ctx = self.ctx
if not transparent:
# Fill background
ctx.rectangle(0,0, W,H)
ctx.set_source_rgba(1.0,1.0,1.0)
ctx.fill()
ctx.scale(self.scale, self.scale)
ctx.translate(-x0 + self.padding, -y0 + self.padding)
if self.draw_bbox:
last = len(canvas.shapes)
for s in canvas.shapes[:last]:
bbox = s.bbox
r = canvas.create_rectangle(*bbox, line_color=(255,0,0, 127), fill=(0,255,0,90))
for s in canvas.shapes:
self.draw_shape(s)
if ext in ('.svg', '.pdf', '.ps', '.eps'):
surf.show_page()
else:
surf.write_to_png(self.fname)
def text_bbox(self, text, font_params, spacing=0):
return CairoSurface.cairo_text_bbox(text, font_params, spacing, self.scale)
@staticmethod
def cairo_text_bbox(text, font_params, spacing=0, scale=1.0):
surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 8, 8)
ctx = cairo.Context(surf)
# The scaling must match the final context.
# If not there can be a mismatch between the computed extents here
# and those generated for the final render.
ctx.scale(scale, scale)
font = cairo_font(font_params)
if use_pygobject:
status, attrs, plain_text, _ = pango.parse_markup(text, len(text), '\0')
layout = pangocairo.create_layout(ctx)
pctx = layout.get_context()
fo = cairo.FontOptions()
fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
pangocairo.context_set_font_options(pctx, fo)
layout.set_font_description(font)
layout.set_spacing(spacing * pango.SCALE)
layout.set_text(plain_text, len(plain_text))
layout.set_attributes(attrs)
li = layout.get_iter() # Get first line of text
baseline = li.get_baseline() / pango.SCALE
re = layout.get_pixel_extents()[1] # Get logical extents
extents = (re.x, re.y, re.x + re.width, re.y + re.height)
else: # pyGtk
attrs, plain_text, _ = pango.parse_markup(text)
pctx = pangocairo.CairoContext(ctx)
pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
layout = pctx.create_layout()
layout.set_font_description(font)
layout.set_spacing(spacing * pango.SCALE)
layout.set_text(plain_text)
layout.set_attributes(attrs)
li = layout.get_iter() # Get first line of text
baseline = li.get_baseline() / pango.SCALE
#print('@@ EXTENTS:', layout.get_pixel_extents()[1], spacing)
extents = layout.get_pixel_extents()[1] # Get logical extents
return [extents[0], extents[1], extents[2], extents[3], baseline]
@staticmethod
def draw_text(x, y, text, font, text_color, spacing, c):
c.save()
c.set_source_rgba(*rgb_to_cairo(text_color))
font = cairo_font(font)
c.translate(x, y)
if use_pygobject:
status, attrs, plain_text, _ = pango.parse_markup(text, len(text), '\0')
layout = pangocairo.create_layout(c)
pctx = layout.get_context()
fo = cairo.FontOptions()
fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
pangocairo.context_set_font_options(pctx, fo)
layout.set_font_description(font)
layout.set_spacing(spacing * pango.SCALE)
layout.set_text(plain_text, len(plain_text))
layout.set_attributes(attrs)
pangocairo.update_layout(c, layout)
pangocairo.show_layout(c, layout)
else: # pyGtk
attrs, plain_text, _ = pango.parse_markup(text)
pctx = pangocairo.CairoContext(c)
pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
layout = pctx.create_layout()
layout.set_font_description(font)
layout.set_spacing(spacing * pango.SCALE)
layout.set_text(plain_text)
layout.set_attributes(attrs)
pctx.update_layout(layout)
pctx.show_layout(layout)
c.restore()
def draw_marker(self, name, mp, tp, weight, c):
if name in self.markers:
m_shape, ref, orient, units = self.markers[name]
c.save()
c.translate(*mp)
if orient == 'auto':
angle = math.atan2(tp[1]-mp[1], tp[0]-mp[0])
c.rotate(angle)
elif isinstance(orient, int):
angle = math.radians(orient)
c.rotate(angle)
if units == 'stroke':
c.scale(weight, weight)
c.translate(-ref[0], -ref[1])
self.draw_shape(m_shape)
c.restore()
def draw_shape(self, shape):
c = self.ctx
default_pen = rgb_to_cairo(self.def_styles.line_color)
c.set_source_rgba(*default_pen)
weight = shape.param('weight', self.def_styles)
fill = shape.param('fill', self.def_styles)
line_color = shape.param('line_color', self.def_styles)
line_cap = cairo_line_cap(shape.param('line_cap', self.def_styles))
stroke = True if weight > 0 else False
c.set_line_width(weight)
c.set_line_cap(line_cap)
if shape.__class__ in self.shape_drawers:
self.shape_drawers[shape.__class__](shape, | self)
elif isinstance(shape, GroupShape):
c.save()
c.translate(*sha | pe._pos)
if 'scale' in shape.options:
c.scale(shape.options['scale'], shape.options['scale'])
if 'angle' in shape.options:
c.rotate(math.radians(shape.options['angle']))
for s in shape.shapes:
self.draw_shape(s)
c.restore()
elif isinstance(shape, TextShape):
x0, y0, x1, y1 = shape.bbox
text = shape.param('text', self.def_styles)
font = shape.param('font', self.def_styles)
text_color = shape.param('text_color', self.def_styles)
anchor = shape.param('anchor', self.def_styles).lower()
spacing = shape.param('spacing', self.def_styles)
CairoSurface.draw_text(x0, y0, text, font, text_color, spacing, c)
elif isinstance(shape, LineShape):
x0, y0, x1, y1 = shape.points
marker = shape.param('marker')
marker_start = shape.param('marker_start')
marker_mid = shape.param('marker_mid')
marker_end = shape.param('marker_end')
if marker is not None:
if marker_start is None:
marker_start = marker
if marker_end is None:
marker_end = marker
if marker_mid is None:
marker_mid = marker
adjust = shape.param('marker_adjust')
if adjust is None:
adjust = 0
if adjust > 0:
angle = math.atan2(y1-y0, x1-x0)
d |
rmk135/objects | tests/typing/selector.py | Python | bsd-3-clause | 1,159 | 0.001726 | from typing import Any
from dependency_injector import providers
# Test 1: to check the return t | ype
provider1 = providers.Selector(
lambda: 'a',
a=providers.Factory(object),
b=providers.Factory(object),
)
var1: Any = provider1()
# Test 2: to check the provided instance interface
provider2 = providers.Selector(
lambda: 'a',
a=providers.Factory(object),
b=providers.Factory(object),
)
provided2: providers.ProvidedInstance = provider2.provided
attr_getter2: providers.AttributeGetter = provider2.provided.attr
item_getter2: providers.ItemGetter = provider2 | .provided['item']
method_caller2: providers.MethodCaller = provider2.provided.method.call(123, arg=324)
# Test3 to check the getattr
provider3 = providers.Selector(
lambda: 'a',
a=providers.Factory(object),
b=providers.Factory(object),
)
attr3: providers.Provider = provider3.a
# Test 4: to check the return type with await
provider4 = providers.Selector(
lambda: 'a',
a=providers.Factory(object),
b=providers.Factory(object),
)
async def _async4() -> None:
var1: Any = await provider4() # type: ignore
var2: Any = await provider4.async_()
|
marbl/MetaCompass | workflows/pilon_paired.py | Python | artistic-2.0 | 1,045 | 0.023923 | """
DESCRIPTION
"""
#__author__ = "Victoria Cepeda
#configfile: expand("config.json",
ruleorder: pilon_contigs
rule all:
input:
sixth=expand('{outdir}/error | _correction/contigs.pil | on.fasta',outdir=config['outdir'])
rule pilon_contigs:
input:
contigs='%s/assembly/contigs.fasta'%(config['outdir']),
sam = "%s/error_correction/sorted.bam"%(config['outdir'])
output:
pilonctg='%s/error_correction/contigs.pilon.fasta'%(config['outdir'])
params:
memory="%d"%(int(config['memory'])),
retry='%s/error_correction/run4.ok'%(config['outdir'])
log:'%s/logs/pilon.log'%(config['outdir'])
threads:int(config['nthreads'])
message: """---Pilon polish contigs ."""
shell:"java -Xmx{params.memory}G -jar %s/bin/pilon-1.23.jar --flank 5 --threads {threads} --mindepth 3 --genome {input.contigs} --frags {input.sam} --output %s/error_correction/contigs.pilon --fix bases,amb --tracks --changes --vcf 1>> {log} 2>&1 && touch {params.retry}"%(config["mcdir"],config['outdir'])
|
citruz/beacontools | beacontools/packet_types/__init__.py | Python | mit | 427 | 0.004684 | """Packets supported by the parser."""
from .eddystone import EddystoneUIDFrame, EddystoneURLFrame, EddystoneEncryptedTLMFrame, \
EddystoneTLMFrame, EddystoneEIDFrame
from .ibeacon im | port IBeaconAdvertisement
from .estimote import EstimoteTelemetryFrameA, EstimoteTelemetryFrameB, EstimoteNearable
from .controlj imp | ort CJMonitorAdvertisement
from .exposure_notification import ExposureNotificationFrame
|
vargax/RAPfSC | RAPfSC/modelo.py | Python | gpl-2.0 | 12,512 | 0.007942 | # -*- coding: utf-8 -*-
import itertools
import pythoncom
import win32com.client as com
__author__ = 'cvargasc'
# Una intersección es un SignalController, tiene carriles de entrada, salida, cruces y semáforos.
class Interseccion:
# ------------------------
# Constructor
# ------------------------
# Inicializa la intersección con sus respectivos carriles de entrada, salida y cruces
# |-> calcula los grupos de cruces compatibles
def __init__(self, scComId):
pythoncom.CoInitialize()
sc = com.Dispatch(pythoncom.CoGetInterfaceAndReleaseStream(scComId, pythoncom.IID_IDispatch))
# ------------------------
# Atributos
# ------------------------
self.sc = sc # Defino el SignalController como un atributo de la clase
self.id = sc.AttValue('No') # Recupero y guardo el id del SignalController en la red
self.nombre = sc.AttValue('Name') # Recupero y guardo el nombre del SignalController
print " + Instanciando Interseccion para SignalController "+self.nombre
# Cada carril tiene un nombre definido por su coordenada y una lista.
# |-> lista[0] = ocupación | lista[1] = numVh | lista[2] = maxVh --> ver escenario.py!
# La ocupación se define como la razón entre de carros en el carril y la máxima cantidad de carros vista en el carril
# |-> Debe ser un número entre 0 y 1
self.carrilesEntrada = {} # La coordenada de los carriles de entrada hacen referencia al origen de los vehículos
self.conectores = {} # El link entre el carril de entrada y el carril de salida
self.carrilesSalida = {} # La coordenada de los carriles de salida hacen referencia al destino de los vehículos
# Cada cruce está compuesto por un semáforo (SignalHead), un carril de entrada y un conjunto de carriles de salida
# cruces[ID] --> El nombre de un cruce es del estilo: 0,1;0,-1:-1,0 Devuelve lista con los elementos del cruce:
# cruce[0] --> Signal controller de la interfaz COM
# cruce[1] --> String que contiene el nombre del carril de entrada
# cruce[2] --> Lista de Strings con los nombres de los carriles de salida
#####
# Por ejemplo para cambiar el color del semáforo asociado al SignalGruop del cruce '0,-1;0,1:1,0'
# cruces['0,-1;0,1:1,0'][0].SetAttValue("State", "GREEN")
self.cruces = {}
# Conjuntos de cruces que se pueden habilitar simultáneamente. Cada grupo es una tupla de strings que corresponden
# a los ids de los cruces pertenecientes a dicho grupo. El id del grupo es entero autonumérico. Se debe utilizar
# el método habilitarGrupo para habilitar de forma segura los cruces asociados a dicho grupo.
self.grupos = {}
# El id del grupo actualmente habilitado en esta intersección.
self.idGrupoActual = -1
# Voy a generar los cruces a partir de los SignalGroups
for sg in sc.SGs:
nombreSignalGroup = sg.AttValue('Name')
print "\n ++ Generando Cruce para SignalGroup "+nombreSignalGroup
carrilEntrada, carrilesSalida = nombreSignalGroup.split(';')[0],nombreSignalGroup.split(';')[1].split(':')
if not carrilEntrada in self.carrilesEntrada:
self.carrilesEntrada[carrilEntrada] = None
# ToDo manejar lógica similar para los conectores --> Debe ser compatible con múltiples conectores por cruce
for carrilSalida in carrilesSalida:
if not carrilSalida in self.carrilesSalida:
self.carrilesSalida[carrilSalida] = None
self.cruces[nombreSignalGroup] = [sg,carrilEntrada,carrilesSalida]
# Llamo el método para calcular los grupos de cruces que se pueden habilitar simultáneamente
self.__calcularGrupos()
print "\n + Instanciada Interseccion "+self.nombre+" :: "\
+ "\n Cruces Posibles = " + str(len(self.cruces))\
+ "\n Grupos Cruces Compatibles = " + str(len(self.grupos))
# ------------------------
# Métodos públicos
# ------------------------
def vincularCarrilesEscenario(self,carrilesEntrada, conectores, carrilesSalida):
for carrilEntrada, lista in carrilesEntrada.iteritems():
if not carrilEntrada in self.carrilesEntrada:
raise "El carril de entrada "+carrilEntrada+" ya debería estar registrado en la intersección!"
self.carrilesEntrada[carrilEntrada] = lista
for carrilSalida, lista in carrilesSalida.iteritems():
if not carrilSalida in self.carrilesSalida:
raise "El carril de salida "+carrilSalida+" ya debería estar registrado en la intersección!"
self.carrilesSalida[carrilSalida] = lista
# ToDo realizar verificación para los conectores
self.conectores = conectores
def habilitarGrupo(self, idGrupo):
self.__deshabilitarGrupo(self.idGrupoActual)
for idCruce in self.grupos[idGrupo]:
self.cruces[idCruce][0].SetAttValue("State", "GREEN")
self.idGrupoActual = idGrupo
# ------------------------
# Métodos privados
# ------------------------
# Método encargado de calcular los grupos de cruces que se pueden habilitar simultáneamente
# Se calculan todas las combinaciones posibles entre los cruces. Se miran en cuales de estas combinaciones
| # todos los cruces son compatibles
def __calcularGrupos(self):
print " ++ Calculando las combinaciones posibles de cruces..."
combinaciones = []
for i in range(1,len(self.cruces)):
#print " +++ Generando las combinaciones de "+str(i | )+" cruces..."
combinaciones.extend(itertools.combinations(self.cruces,i))
print " +++ Se generaron "+str(len(combinaciones))+" grupos de cruces posibles..."
i = 0
for combinacion in combinaciones:
if self.__grupoCompatible(combinacion):
self.grupos[i] = combinacion
print " ++++ Registrado el grupo "+str(i)+" : ",combinacion
i += 1
print " +++ Se identificaron ",len(self.grupos)," grupos de cruces compatibles..."
# ------------------------
# Métodos privados de apoyo
# ------------------------
def __deshabilitarGrupo(self, idGrupo):
# Implementado bajo EAFP https://docs.python.org/2/glossary.html#term-eafp
try:
for idCruce in self.grupos[idGrupo]:
self.cruces[idCruce][0].SetAttValue("State", "RED")
except KeyError:
if idGrupo != -1: # -1 es el valor de inicialización...
raise " !! Grupo "+str(idGrupo)+" inexistente!!"
# Un grupo se considera compatible si todos los cruces del grupo son compatibles entre ellos
def __grupoCompatible(self,grupo):
for cruce in grupo:
for candidato in grupo:
if not self.__sonCompatibles(cruce,candidato):
return False
return True
# Evalúa si dos cruces son compatibles. Se consideran compatibles si ninguno de sus segmentos se cortan
def __sonCompatibles(self,idCruce1,idCruce2):
segCruce1 = self.__generarSegmentos(idCruce1)
segCruce2 = self.__generarSegmentos(idCruce2)
for segmento1 in segCruce1:
for segmento2 in segCruce2:
if self.__segmentosSeCortan(segmento1,segmento2):
return False
return True
# Evalúa la posición de del punto respecto al segmento calculando el producto cruz / Regla de la mano derecha
# Un punto c es una tupla (xc,yc)
# Un segmento es una tupla de puntos (a,b) con a = (xa,ya) y b = (xb,yb)
# Devuelve un float:
# Si > 0 -> DERECHA | Si < 0 -> IZQUIERDA | Si = 0 -> Sobre el segmento
@staticmethod
def __posicionPtoRespectoSegmento(segmento, punto):
#debug = False
#if debug: print " ++++ Determinando donde se encuentra el punto",punto," respecto al segmento ",segmento
# Las coordenadas del segmento
xa,ya = segmento[0]
xb,yb = |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.