max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111 values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
chunked_uploads/utils/url.py | IRI-Research/django-chunked-uploads | 3 | 6616051 | from chunked_uploads.utils.web_url_management import get_web_url
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
import urlparse
def absstatic(request, path):
domain = get_web_url(request)
new_path = staticfiles_storage.url(path)
return urlparse.urljoin(domain, new_path)
def absurl(request, viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None):
domain = get_web_url(request)
path = reverse(viewname, urlconf, args, kwargs, prefix, current_app)
return urlparse.urljoin(domain, path)
def absurl_norequest(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None):
domain = get_web_url()
path = reverse(viewname, urlconf, args, kwargs, prefix, current_app)
return urlparse.urljoin(domain, path)
| from chunked_uploads.utils.web_url_management import get_web_url
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
import urlparse
def absstatic(request, path):
domain = get_web_url(request)
new_path = staticfiles_storage.url(path)
return urlparse.urljoin(domain, new_path)
def absurl(request, viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None):
domain = get_web_url(request)
path = reverse(viewname, urlconf, args, kwargs, prefix, current_app)
return urlparse.urljoin(domain, path)
def absurl_norequest(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None):
domain = get_web_url()
path = reverse(viewname, urlconf, args, kwargs, prefix, current_app)
return urlparse.urljoin(domain, path)
| none | 1 | 2.230495 | 2 | |
app/views/posts/routes.py | yaiestura/coronavirus_prediction | 6 | 6616052 | from flask import render_template, url_for, flash, redirect, request, abort, Blueprint
from flask_login import current_user, login_required
from app import db
from app.models import User, Post
from app.views.posts.forms import PostForm
posts = Blueprint('posts', __name__)
@posts.route("/posts", methods=['GET', 'POST'])
@login_required
def all_posts():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5)
return render_template('posts/posts.html', posts=posts)
@posts.route("/post/new", methods=['GET', 'POST'])
@login_required
def new_post():
form = PostForm()
if form.validate_on_submit():
post = Post(title=form.title.data, content=form.content.data, user=current_user)
db.session.add(post)
db.session.commit()
flash('Your post has been created!', 'success')
return redirect(url_for('posts.all_posts'))
return render_template('posts/create_post.html', title='New Post',
form=form, legend='New Post')
@posts.route("/posts/<string:username>")
def user_posts(username):
page = request.args.get('page', 1, type=int)
user = User.query.filter_by(username=username).first_or_404()
posts = Post.query.filter_by(user=current_user)\
.order_by(Post.date_posted.desc())\
.paginate(page=page, per_page=5)
return render_template('posts/user_posts.html', posts=posts, user=current_user)
@posts.route("/post/<int:post_id>")
def post(post_id):
post = Post.query.get_or_404(post_id)
return render_template('posts/post.html', title=post.title, post=post)
@posts.route("/post/<int:post_id>/update", methods=['GET', 'POST'])
@login_required
def update_post(post_id):
post = Post.query.get_or_404(post_id)
if post.user != current_user:
abort(403)
form = PostForm()
if form.validate_on_submit():
post.title = form.title.data
post.content = form.content.data
db.session.commit()
flash('Your post has been updated!', 'success')
return redirect(url_for('posts.all_posts', post_id=post.id))
elif request.method == 'GET':
form.title.data = post.title
form.content.data = post.content
return render_template('posts/create_post.html', title='Update Post',
form=form, legend='Update Post')
@posts.route("/post/<int:post_id>/delete", methods=['POST'])
@login_required
def delete_post(post_id):
post = Post.query.get_or_404(post_id)
if post.user != current_user:
abort(403)
db.session.delete(post)
db.session.commit()
flash('Your post has been deleted!', 'success')
return redirect(url_for('posts.all_posts')) | from flask import render_template, url_for, flash, redirect, request, abort, Blueprint
from flask_login import current_user, login_required
from app import db
from app.models import User, Post
from app.views.posts.forms import PostForm
posts = Blueprint('posts', __name__)
@posts.route("/posts", methods=['GET', 'POST'])
@login_required
def all_posts():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5)
return render_template('posts/posts.html', posts=posts)
@posts.route("/post/new", methods=['GET', 'POST'])
@login_required
def new_post():
form = PostForm()
if form.validate_on_submit():
post = Post(title=form.title.data, content=form.content.data, user=current_user)
db.session.add(post)
db.session.commit()
flash('Your post has been created!', 'success')
return redirect(url_for('posts.all_posts'))
return render_template('posts/create_post.html', title='New Post',
form=form, legend='New Post')
@posts.route("/posts/<string:username>")
def user_posts(username):
page = request.args.get('page', 1, type=int)
user = User.query.filter_by(username=username).first_or_404()
posts = Post.query.filter_by(user=current_user)\
.order_by(Post.date_posted.desc())\
.paginate(page=page, per_page=5)
return render_template('posts/user_posts.html', posts=posts, user=current_user)
@posts.route("/post/<int:post_id>")
def post(post_id):
post = Post.query.get_or_404(post_id)
return render_template('posts/post.html', title=post.title, post=post)
@posts.route("/post/<int:post_id>/update", methods=['GET', 'POST'])
@login_required
def update_post(post_id):
post = Post.query.get_or_404(post_id)
if post.user != current_user:
abort(403)
form = PostForm()
if form.validate_on_submit():
post.title = form.title.data
post.content = form.content.data
db.session.commit()
flash('Your post has been updated!', 'success')
return redirect(url_for('posts.all_posts', post_id=post.id))
elif request.method == 'GET':
form.title.data = post.title
form.content.data = post.content
return render_template('posts/create_post.html', title='Update Post',
form=form, legend='Update Post')
@posts.route("/post/<int:post_id>/delete", methods=['POST'])
@login_required
def delete_post(post_id):
post = Post.query.get_or_404(post_id)
if post.user != current_user:
abort(403)
db.session.delete(post)
db.session.commit()
flash('Your post has been deleted!', 'success')
return redirect(url_for('posts.all_posts')) | none | 1 | 2.510125 | 3 | |
python/OOP/override.py | joro2404/Programming_problems | 0 | 6616053 | """
Desc:
Python program to demonstrate overriding
using the super() method
"""
class base(object):
def base_func(self):
print('Method of base class')
class child(base):
def base_func1(self):
print('Method of child class')
super(child, self).base_func()
class next_child(child):
def base_func(self):
print('Method of next_child class')
super(next_child, self).base_func()
obj = next_child()
obj.base_func()
| """
Desc:
Python program to demonstrate overriding
using the super() method
"""
class base(object):
def base_func(self):
print('Method of base class')
class child(base):
def base_func1(self):
print('Method of child class')
super(child, self).base_func()
class next_child(child):
def base_func(self):
print('Method of next_child class')
super(next_child, self).base_func()
obj = next_child()
obj.base_func()
| en | 0.68901 | Desc:
Python program to demonstrate overriding
using the super() method | 4.066849 | 4 |
tests/test_optimizer.py | tanxicccc/rsopt | 0 | 6616054 | import unittest
import numpy as np
import rsopt.optimizer as opt
parameters_array = np.array([('period', 30., 60., 46.),
('lpy', 1., 10., 5.),
('lmz', 10., 40., 20.),
('lpz', 30., 60., 25.),
('offset', 0.25, 4., 1.)],
dtype=[('name', 'U20'), ('min', 'float'), ('max', 'float'), ('start', 'float')])
parameters_dict = {
'period': {'min': 30., 'max': 60., 'start': 46.},
'lpy': {'min': 1., 'max': 10., 'start': 5.},
'lmz': {'min': 10., 'max': 40., 'start': 20.},
'lpz': {'min': 30., 'max': 60., 'start': 25.},
'offset': {'min': .25, 'max': 4., 'start': 1.}
}
settings_dict = {
'lpx': 65,
'pole_properties': 'h5',
'pole_segmentation': [2, 2, 5],
'pole_color': [1, 0, 1],
'lmx': 65,
'magnet_properties': 'sdds',
'magnet_segmentation': [1, 3, 1],
'magnet_color': [0, 1, 1],
'gap': 20.
}
class TestOptimizer(unittest.TestCase):
def setUp(self):
self.optimizer = opt.Optimizer()
def test_parameter_array_read(self):
self.optimizer.set_parameters(parameters_array)
def test_parameter_dict_read(self):
self.optimizer.set_parameters(parameters_dict)
def test_settings_dict_read(self):
self.optimizer.set_settings(settings_dict)
def test_set_dimension(self):
self.optimizer.set_parameters(parameters_dict)
self.optimizer._set_dimension()
self.assertEqual(self.optimizer.dimension, len(parameters_dict))
| import unittest
import numpy as np
import rsopt.optimizer as opt
parameters_array = np.array([('period', 30., 60., 46.),
('lpy', 1., 10., 5.),
('lmz', 10., 40., 20.),
('lpz', 30., 60., 25.),
('offset', 0.25, 4., 1.)],
dtype=[('name', 'U20'), ('min', 'float'), ('max', 'float'), ('start', 'float')])
parameters_dict = {
'period': {'min': 30., 'max': 60., 'start': 46.},
'lpy': {'min': 1., 'max': 10., 'start': 5.},
'lmz': {'min': 10., 'max': 40., 'start': 20.},
'lpz': {'min': 30., 'max': 60., 'start': 25.},
'offset': {'min': .25, 'max': 4., 'start': 1.}
}
settings_dict = {
'lpx': 65,
'pole_properties': 'h5',
'pole_segmentation': [2, 2, 5],
'pole_color': [1, 0, 1],
'lmx': 65,
'magnet_properties': 'sdds',
'magnet_segmentation': [1, 3, 1],
'magnet_color': [0, 1, 1],
'gap': 20.
}
class TestOptimizer(unittest.TestCase):
def setUp(self):
self.optimizer = opt.Optimizer()
def test_parameter_array_read(self):
self.optimizer.set_parameters(parameters_array)
def test_parameter_dict_read(self):
self.optimizer.set_parameters(parameters_dict)
def test_settings_dict_read(self):
self.optimizer.set_settings(settings_dict)
def test_set_dimension(self):
self.optimizer.set_parameters(parameters_dict)
self.optimizer._set_dimension()
self.assertEqual(self.optimizer.dimension, len(parameters_dict))
| none | 1 | 2.231013 | 2 | |
fwtool/archive/cpio.py | undingen/fwtool.py | 115 | 6616055 | """A simple parser for "new ascii format" cpio archives"""
from . import *
from ..io import *
from ..util import *
CpioHeader = Struct('CpioHeader', [
('magic', Struct.STR % 6),
('inode', Struct.STR % 8),
('mode', Struct.STR % 8),
('uid', Struct.STR % 8),
('gid', Struct.STR % 8),
('nlink', Struct.STR % 8),
('mtime', Struct.STR % 8),
('size', Struct.STR % 8),
('...', 32),
('nameSize', Struct.STR % 8),
('check', Struct.STR % 8),
])
cpioHeaderMagic = b'070701'
def isCpio(file):
"""Returns true if the file provided is a cpio file"""
header = CpioHeader.unpack(file)
return header and header.magic == cpioHeaderMagic
def _roundUp(n, i):
return (n + i - 1) // i * i
def readCpio(file):
"""Unpacks a cpio archive and returns the contained files"""
offset = 0
while True:
header = CpioHeader.unpack(file, offset)
if header.magic != cpioHeaderMagic:
raise Exception('Wrong magic')
header = CpioHeader.tuple._make(int(i, 16) for i in header)
file.seek(offset + CpioHeader.size)
name = file.read(header.nameSize).rstrip(b'\0').decode('ascii')
if name == 'TRAILER!!!':
break
dataStart = _roundUp(offset + CpioHeader.size + header.nameSize, 4)
offset = _roundUp(dataStart + header.size, 4)
yield UnixFile(
path = '/' + name,
size = header.size,
mtime = header.mtime,
mode = header.mode,
uid = header.uid,
gid = header.gid,
contents = FilePart(file, dataStart, header.size),
)
| """A simple parser for "new ascii format" cpio archives"""
from . import *
from ..io import *
from ..util import *
CpioHeader = Struct('CpioHeader', [
('magic', Struct.STR % 6),
('inode', Struct.STR % 8),
('mode', Struct.STR % 8),
('uid', Struct.STR % 8),
('gid', Struct.STR % 8),
('nlink', Struct.STR % 8),
('mtime', Struct.STR % 8),
('size', Struct.STR % 8),
('...', 32),
('nameSize', Struct.STR % 8),
('check', Struct.STR % 8),
])
cpioHeaderMagic = b'070701'
def isCpio(file):
"""Returns true if the file provided is a cpio file"""
header = CpioHeader.unpack(file)
return header and header.magic == cpioHeaderMagic
def _roundUp(n, i):
return (n + i - 1) // i * i
def readCpio(file):
"""Unpacks a cpio archive and returns the contained files"""
offset = 0
while True:
header = CpioHeader.unpack(file, offset)
if header.magic != cpioHeaderMagic:
raise Exception('Wrong magic')
header = CpioHeader.tuple._make(int(i, 16) for i in header)
file.seek(offset + CpioHeader.size)
name = file.read(header.nameSize).rstrip(b'\0').decode('ascii')
if name == 'TRAILER!!!':
break
dataStart = _roundUp(offset + CpioHeader.size + header.nameSize, 4)
offset = _roundUp(dataStart + header.size, 4)
yield UnixFile(
path = '/' + name,
size = header.size,
mtime = header.mtime,
mode = header.mode,
uid = header.uid,
gid = header.gid,
contents = FilePart(file, dataStart, header.size),
)
| en | 0.544669 | A simple parser for "new ascii format" cpio archives Returns true if the file provided is a cpio file Unpacks a cpio archive and returns the contained files | 2.549239 | 3 |
takeover/github_pages.py | 5alt/ZeroScan | 61 | 6616056 | import requests
APEX_VALUES = ['172.16.31.10', '192.168.3.11', '192.168.3.11', '192.168.127.12', '192.168.3.11', '172.16.17.32']
CNAME_VALUE = [".github.io"]
RESPONSE_FINGERPRINT = "There isn't a GitHub Pages site here."
def detector(domain, ip, cname):
if APEX_VALUES:
if ip in APEX_VALUES:
return True
if filter(lambda x: x in cname, CNAME_VALUE):
return True
try:
if RESPONSE_FINGERPRINT in requests.get('http://%s' % domain).text:
return True
except Exception as e:
pass
return False | import requests
APEX_VALUES = ['172.16.31.10', '192.168.3.11', '192.168.3.11', '192.168.127.12', '192.168.3.11', '172.16.17.32']
CNAME_VALUE = [".github.io"]
RESPONSE_FINGERPRINT = "There isn't a GitHub Pages site here."
def detector(domain, ip, cname):
if APEX_VALUES:
if ip in APEX_VALUES:
return True
if filter(lambda x: x in cname, CNAME_VALUE):
return True
try:
if RESPONSE_FINGERPRINT in requests.get('http://%s' % domain).text:
return True
except Exception as e:
pass
return False | none | 1 | 2.925081 | 3 | |
teams/urls.py | Onlynfk/Freshdesk-CRM-Platform | 0 | 6616057 | from django.urls import include, path
urlpatterns = [
path('api/v1/', include('teams.api.urls.teams_urls')),
]
| from django.urls import include, path
urlpatterns = [
path('api/v1/', include('teams.api.urls.teams_urls')),
]
| none | 1 | 1.466598 | 1 | |
kirppu/views.py | kcsry/kirppu | 0 | 6616058 | from __future__ import unicode_literals, print_function, absolute_import
from collections import namedtuple
from functools import wraps
import json
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.core.exceptions import (
PermissionDenied,
ValidationError,
)
from django.contrib import messages
import django.urls as url
from django.db import transaction, models
from django.http.response import (
HttpResponse,
HttpResponseBadRequest,
HttpResponseForbidden,
HttpResponseRedirect,
)
from django.http import Http404
from django.shortcuts import (
redirect,
render,
get_object_or_404,
)
from django.utils import timezone
from django.utils.formats import localize
from django.utils.six import string_types
from django.utils.translation import ugettext as _
from django.views.csrf import csrf_failure as django_csrf_failure
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.http import require_http_methods
from django.views.generic import RedirectView
from .checkout_api import clerk_logout_fn
from . import ajax_util
from .forms import ItemRemoveForm, VendorItemForm, VendorBoxForm, remove_item_from_receipt as _remove_item_from_receipt
from .fields import ItemPriceField
from .models import (
Box,
Clerk,
Event,
EventPermission,
Item,
ItemType,
Vendor,
UserAdapter,
UIText,
Receipt,
)
from .stats import ItemCountData, ItemEurosData
from .util import get_form
from .utils import (
barcode_view,
is_vendor_open,
is_registration_closed_for_users,
require_vendor_open,
)
from .templatetags.kirppu_tags import get_dataurl
from .vendors import get_multi_vendor_values
import pubcode
def index(request):
return redirect("kirppu:front_page")
class MobileRedirect(RedirectView):
permanent = False
pattern_name = "kirppu:mobile"
@login_required
@require_http_methods(["POST"])
@require_vendor_open
def item_add(request, event):
if not Vendor.has_accepted(request, event):
return HttpResponseBadRequest()
vendor = Vendor.get_or_create_vendor(request, event)
form = VendorItemForm(request.POST, event)
if not form.is_valid():
return HttpResponseBadRequest(form.get_any_error())
item_cnt = Item.objects.filter(vendor=vendor).count()
# Create the items and construct a response containing all the items that have been added.
response = []
max_items = settings.KIRPPU_MAX_ITEMS_PER_VENDOR
data = form.db_values()
name = data.pop("name")
for suffix in form.cleaned_data["suffixes"]:
if item_cnt >= max_items:
error_msg = _(u"You have %(max_items)s items, which is the maximum. No more items can be registered.")
return HttpResponseBadRequest(error_msg % {'max_items': max_items})
item_cnt += 1
suffixed_name = (name + u" " + suffix).strip() if suffix else name
item = Item.new(
name=suffixed_name,
vendor=vendor,
**data
)
item_dict = item.as_public_dict()
item_dict['barcode_dataurl'] = get_dataurl(item.code, 'png')
response.append(item_dict)
return HttpResponse(json.dumps(response), 'application/json')
@login_required
@require_http_methods(["POST"])
def item_hide(request, event_slug, code):
event = get_object_or_404(Event, slug=event_slug)
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
item = get_object_or_404(Item.objects.select_for_update(), code=code, vendor=vendor)
item.hidden = True
item.save(update_fields=("hidden",))
return HttpResponse()
@login_required
@require_http_methods(['POST'])
def item_to_not_printed(request, event_slug, code):
event = get_object_or_404(Event, slug=event_slug)
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
item = get_object_or_404(Item.objects.select_for_update(), code=code, vendor=vendor, box__isnull=True)
if settings.KIRPPU_COPY_ITEM_WHEN_UNPRINTED:
# Create a duplicate of the item with a new code and hide the old item.
# This way, even if the user forgets to attach the new tags, the old
# printed tag is still in the system.
if not is_vendor_open(request, event):
return HttpResponseForbidden("Registration is closed")
new_item = Item.new(
name=item.name,
price=item.price,
vendor=item.vendor,
type=item.type,
state=Item.ADVERTISED,
itemtype=item.itemtype,
adult=item.adult
)
item.hidden = True
else:
item.printed = False
new_item = item
item.save(update_fields=("hidden", "printed"))
item_dict = {
'vendor_id': new_item.vendor_id,
'code': new_item.code,
'barcode_dataurl': get_dataurl(item.code, 'png'),
'name': new_item.name,
'price': str(new_item.price).replace('.', ','),
'type': new_item.type,
'adult': new_item.adult,
}
return HttpResponse(json.dumps(item_dict), 'application/json')
@login_required
@require_http_methods(["POST"])
def item_to_printed(request, event_slug, code):
event = get_object_or_404(Event, slug=event_slug)
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
item = get_object_or_404(Item.objects.select_for_update(), code=code, vendor=vendor, box__isnull=True)
item.printed = True
item.save(update_fields=("printed",))
return HttpResponse()
@login_required
@require_http_methods(["POST"])
@require_vendor_open
def item_update_price(request, event, code):
try:
price = ItemPriceField().clean(request.POST.get('value'))
except ValidationError as error:
return HttpResponseBadRequest(u' '.join(error.messages))
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
item = get_object_or_404(Item.objects.select_for_update(), code=code, vendor=vendor, box__isnull=True)
if item.is_locked():
return HttpResponseBadRequest("Item has been brought to event. Price can't be changed.")
item.price = str(price)
item.save(update_fields=("price",))
return HttpResponse(str(price).replace(".", ","))
@login_required
@require_http_methods(["POST"])
@require_vendor_open
def item_update_name(request, event, code):
name = request.POST.get("value", "no name")
name = name[:80]
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
item = get_object_or_404(Item.objects.select_for_update(), code=code, vendor=vendor)
if item.is_locked():
return HttpResponseBadRequest("Item has been brought to event. Name can't be changed.")
item.name = name
item.save(update_fields=("name",))
return HttpResponse(name)
@login_required
@require_http_methods(["POST"])
def item_update_type(request, event_slug, code):
event = get_object_or_404(Event, slug=event_slug)
tag_type = request.POST.get("tag_type", None)
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
item = get_object_or_404(Item.objects.select_for_update(), code=code, vendor=vendor)
item.type = tag_type
item.save(update_fields=("type",))
return HttpResponse()
@login_required
@require_http_methods(["POST"])
def all_to_print(request, event_slug):
event = get_object_or_404(Event, slug=event_slug)
vendor = Vendor.get_vendor(request, event)
items = Item.objects.filter(vendor=vendor).filter(printed=False).filter(box__isnull=True)
items.update(printed=True)
return HttpResponse()
@login_required
@require_http_methods(["POST"])
@require_vendor_open
def box_add(request, event):
if not event.use_boxes:
raise Http404()
if not Vendor.has_accepted(request, event):
return HttpResponseBadRequest()
vendor = Vendor.get_vendor(request, event)
form = VendorBoxForm(request.POST, event)
if not form.is_valid():
return HttpResponseBadRequest(form.get_any_error())
data = form.db_values()
# Verify that user doesn't exceed his/hers item quota with the box.
max_items = settings.KIRPPU_MAX_ITEMS_PER_VENDOR
item_cnt = Item.objects.filter(vendor=vendor).count()
count = data["count"]
if item_cnt >= max_items:
error_msg = _(u"You have %(max_items)s items, which is the maximum. No more items can be registered.")
return HttpResponseBadRequest(error_msg % {'max_items': max_items})
elif max_items < count + item_cnt:
error_msg = _(u"You have %(item_cnt)s items. "
u"Creating this box would cause the items to exceed the maximum number of allowed items.")
return HttpResponseBadRequest(error_msg % {'item_cnt': item_cnt})
# Create the box and items. and construct a response containing box and all the items that have been added.
box = Box.new(
vendor=vendor,
**data
)
box_dict = box.as_public_dict()
box_dict["vendor_id"] = vendor.id
box_dict["event"] = event
return render(request, "kirppu/app_boxes_box.html", box_dict)
@login_required
@require_http_methods(["POST"])
def box_hide(request, event_slug, box_id):
event = get_object_or_404(Event, slug=event_slug)
if not event.use_boxes:
raise Http404()
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
box = get_object_or_404(Box.objects, id=box_id)
box_vendor = box.get_vendor()
if box_vendor.id != vendor.id:
raise Http404()
box.set_hidden(True)
return HttpResponse()
@login_required
@require_http_methods(["POST"])
def box_print(request, event_slug, box_id):
event = get_object_or_404(Event, slug=event_slug)
if not event.use_boxes:
raise Http404()
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
box = get_object_or_404(Box.objects, id=box_id)
box_vendor = box.get_vendor()
if box_vendor.id != vendor.id:
raise Http404()
box.set_printed(True)
return HttpResponse()
@login_required
@require_http_methods(["GET"])
@barcode_view
def box_content(request, event_slug, box_id, bar_type):
"""
Get a page containing the contents of one box for printing
:param request: HttpRequest object.
:type request: django.http.request.HttpRequest
:param bar_type: Image type of the generated bar. See `kirppu_tags.barcode_dataurl`.
:type bar_type: str
:return: HttpResponse or HttpResponseBadRequest
"""
event = get_object_or_404(Event, slug=event_slug)
if not event.use_boxes:
raise Http404()
vendor = Vendor.get_vendor(request, event)
boxes = Box.objects.filter(id=box_id, item__vendor=vendor, item__hidden=False).distinct()
if boxes.count() == 0:
raise Http404()
box = boxes[0]
item = box.get_representative_item()
render_params = {
'box': box,
'item': item,
'bar_type': bar_type,
'CURRENCY': settings.KIRPPU_CURRENCY,
}
return render(request, "kirppu/app_boxes_content.html", render_params)
def _vendor_menu_contents(request, event):
"""
Generate menu for Vendor views.
Returned tuple contains entries for the menu, each entry containing a
name, url, and flag indicating whether the entry is currently active
or not.
:param event:
:param request: Current request being processed.
:return: List of menu items containing name, url and active fields.
:rtype: tuple[MenuItem,...]
"""
active = request.resolver_match.view_name
menu_item = namedtuple("MenuItem", "name url active sub_items")
def fill(name, func, sub=None, query=None, is_global=False):
if not is_global:
kwargs = {"event_slug": event.slug}
else:
kwargs = {}
link = url.reverse(func, kwargs=kwargs) if func else None
from urllib.parse import quote
if query:
link += "?" + "&".join(
quote(k, safe="") + (("=" + quote(v, safe="")) if v else "")
for k, v in query.items())
return menu_item(name, link, func == active, sub)
items = [
fill(_(u"Home"), "kirppu:vendor_view"),
fill(_(u"Item list"), "kirppu:page"),
]
if event.use_boxes:
items.append(fill(_(u"Box list"), "kirppu:vendor_boxes"))
if event.mobile_view_visible:
items.append(fill(_("Mobile"), "kirppu:mobile"))
manage_sub = []
permissions = EventPermission.get(event, request.user)
if request.user.is_staff or UserAdapter.is_clerk(request.user, event):
manage_sub.append(fill(_(u"Checkout commands"), "kirppu:commands"))
if event.checkout_active:
manage_sub.append(fill(_(u"Checkout"), "kirppu:checkout_view"))
if event.use_boxes:
manage_sub.append(fill(_("Box codes"), "kirppu:box_codes"))
if request.user.is_staff or permissions.can_see_clerk_codes:
manage_sub.append(fill(_(u"Clerk codes"), "kirppu:clerks"))
if request.user.is_staff or permissions.can_see_accounting:
manage_sub.append(fill(_(u"Lost and Found"), "kirppu:lost_and_found"))
if request.user.is_staff\
or UserAdapter.is_clerk(request.user, event)\
or permissions.can_see_statistics:
manage_sub.append(fill(_(u"Statistics"), "kirppu:stats_view"))
if request.user.is_staff:
try:
manage_sub.append(fill(_(u"Site administration"), "admin:index", is_global=True))
except url.NoReverseMatch as e:
pass
if manage_sub:
items.append(fill(_(u"Management"), "", manage_sub))
if permissions.can_see_accounting:
accounting_sub = [
fill(_("View"), "kirppu:accounting"),
fill(_("Download"), "kirppu:accounting", query={"download": ""}),
menu_item(None, None, None, None),
fill(_("View items"), "kirppu:item_dump", query={"txt": ""}),
fill(_("View items (CSV)"), "kirppu:item_dump"),
]
items.append(fill(_("Accounting"), "", accounting_sub))
return items
@login_required
@require_http_methods(["GET"])
@barcode_view
def get_items(request, event_slug, bar_type):
"""
Get a page containing all items for vendor.
:param request: HttpRequest object.
:type request: django.http.request.HttpRequest
:return: HttpResponse or HttpResponseBadRequest
"""
event = get_object_or_404(Event, slug=event_slug)
user = request.user
if user.is_staff and "user" in request.GET:
user = get_object_or_404(get_user_model(), username=request.GET["user"])
vendor = Vendor.get_vendor(request, event)
vendor_data = get_multi_vendor_values(request, event)
if event.multiple_vendors_per_user and user.is_staff and "user" in request.GET:
raise NotImplementedError # FIXME: Decide how this should work.
vendor_items = Item.objects.filter(vendor=vendor, hidden=False, box__isnull=True)
items = vendor_items.filter(printed=False)
printed_items = vendor_items.filter(printed=True)
# Order from newest to oldest, because that way new items are added
# to the top and the user immediately sees them without scrolling
# down.
items = items.order_by('-id')
item_name_placeholder = UIText.get_text(event, "item_placeholder", _("Ranma ½ Vol."))
render_params = {
'event': event,
'items': items,
'printed_items': printed_items,
'bar_type': bar_type,
'item_name_placeholder': item_name_placeholder,
'profile_url': settings.PROFILE_URL,
'terms_accepted': vendor.terms_accepted if vendor is not None else False,
'is_registration_open': is_vendor_open(request, event),
'is_registration_closed_for_users': is_registration_closed_for_users(event=event),
'menu': _vendor_menu_contents(request, event),
'itemTypes': ItemType.as_tuple(event),
'CURRENCY': settings.KIRPPU_CURRENCY,
'PRICE_MIN_MAX': settings.KIRPPU_MIN_MAX_PRICE,
}
render_params.update(vendor_data)
return render(request, "kirppu/app_items.html", render_params)
@login_required
@require_http_methods(["GET"])
def get_boxes(request, event_slug):
"""
Get a page containing all boxes for vendor.
:param request: HttpRequest object.
:type request: django.http.request.HttpRequest
:return: HttpResponse or HttpResponseBadRequest
"""
event = get_object_or_404(Event, slug=event_slug)
if not event.use_boxes:
raise Http404()
user = request.user
if user.is_staff and "user" in request.GET:
user = get_object_or_404(get_user_model(), username=request.GET["user"])
vendor = Vendor.get_vendor(request, event)
vendor_data = get_multi_vendor_values(request, event)
boxes = Box.objects.filter(item__vendor=vendor, item__hidden=False).distinct()
boxes = boxes.select_related("representative_item__itemtype")
# Order from newest to oldest, because that way new boxes are added
# to the top and the user immediately sees them without scrolling
# down.
boxes = boxes.order_by('-id')
box_name_placeholder = UIText.get_text(event, "box_placeholder", _("Box full of Ranma"))
render_params = {
'event': event,
'boxes': boxes,
'box_name_placeholder': box_name_placeholder,
'profile_url': settings.PROFILE_URL,
'terms_accepted': vendor.terms_accepted if vendor is not None else False,
'is_registration_open': is_vendor_open(request, event),
'is_registration_closed_for_users': is_registration_closed_for_users(event),
'menu': _vendor_menu_contents(request, event),
'itemTypes': ItemType.as_tuple(event),
'CURRENCY': settings.KIRPPU_CURRENCY,
'PRICE_MIN_MAX': settings.KIRPPU_MIN_MAX_PRICE,
}
render_params.update(vendor_data)
return render(request, "kirppu/app_boxes.html", render_params)
@login_required
@barcode_view
def get_clerk_codes(request, event_slug, bar_type):
event = get_object_or_404(Event, slug=event_slug)
if not (request.user.is_staff or EventPermission.get(event, request.user).can_see_clerk_codes):
return HttpResponseForbidden()
bound = []
unbound = []
code_item = namedtuple("CodeItem", "name code")
for c in Clerk.objects.filter(event=event, access_key__isnull=False):
if not c.is_valid_code:
continue
code = c.get_code()
if c.user is not None:
name = c.user.get_short_name()
if len(name) == 0:
name = c.user.get_username()
bound.append(code_item(name=name, code=code))
else:
unbound.append(code_item(name="", code=code))
items = None
if bound or unbound:
bound.sort(key=lambda a: a.name + a.code)
unbound.sort(key=lambda a: a.code)
items = bound + unbound
# Generate a code to check it's length.
name, code = items[0]
width = pubcode.Code128(code, charset='B').width(add_quiet_zone=True)
else:
width = None # Doesn't matter.
return render(request, "kirppu/app_clerks.html", {
'event': event,
'items': items,
'bar_type': bar_type,
'repeat': range(1),
'barcode_width': width,
})
@login_required
@barcode_view
def get_counter_commands(request, event_slug, bar_type):
event = get_object_or_404(Event, slug=event_slug)
if not (request.user.is_staff or UserAdapter.is_clerk(request.user, event)):
raise PermissionDenied()
return render(request, "kirppu/app_commands.html", {
'event_slug': event_slug,
'title': _(u"Counter commands"),
})
@login_required
@barcode_view
def get_boxes_codes(request, event_slug, bar_type):
event = get_object_or_404(Event, slug=event_slug)
if not event.use_boxes:
raise Http404()
if not (request.user.is_staff or UserAdapter.is_clerk(request.user, event)):
raise PermissionDenied()
boxes = Box.objects.filter(representative_item__vendor__event=event, box_number__isnull=False).order_by("box_number")
vm = []
for box in boxes:
code = "box%d" % box.box_number
img = pubcode.Code128(code, charset='B').data_url(image_format=bar_type, add_quiet_zone=True)
r = box.get_representative_item() # type: Item
vm.append({
"name": box.description,
"code": code,
"data_url": img,
"adult": r.adult,
"vendor_id": r.vendor_id,
"price": r.price_fmt,
"bundle_size": box.bundle_size,
"box_number": box.box_number,
})
return render(request, "kirppu/boxes_list.html", {
"bar_type": bar_type,
"boxes": vm
})
@ensure_csrf_cookie
def checkout_view(request, event_slug):
"""
Checkout view.
:param request: HttpRequest object
:type request: django.http.request.HttpRequest
:return: Response containing the view.
:rtype: HttpResponse
"""
event = get_object_or_404(Event, slug=event_slug)
if not event.checkout_active:
raise PermissionDenied()
clerk_logout_fn(request)
context = {
'CURRENCY': settings.KIRPPU_CURRENCY,
'PURCHASE_MAX': settings.KIRPPU_MAX_PURCHASE,
'event': event,
}
if settings.KIRPPU_AUTO_CLERK and settings.DEBUG:
if isinstance(settings.KIRPPU_AUTO_CLERK, string_types):
real_clerks = Clerk.objects.filter(event=event, user__username=settings.KIRPPU_AUTO_CLERK)
else:
real_clerks = Clerk.objects.filter(event=event, user__isnull=False)
for clerk in real_clerks:
if clerk.is_enabled:
context["auto_clerk"] = clerk.get_code()
break
return render(request, "kirppu/app_checkout.html", context)
@ensure_csrf_cookie
def overseer_view(request, event_slug):
"""Overseer view."""
event = get_object_or_404(Event, slug=event_slug)
if not event.checkout_active:
raise PermissionDenied()
try:
ajax_util.require_user_features(counter=True, clerk=True, overseer=True)(lambda _: None)(request)
except ajax_util.AjaxError:
return redirect('kirppu:checkout_view', event_slug=event.slug)
else:
context = {
'event': event,
'itemtypes': ItemType.as_tuple(event),
'itemstates': Item.STATE,
'CURRENCY': settings.KIRPPU_CURRENCY,
}
return render(request, 'kirppu/app_overseer.html', context)
def _statistics_access(fn):
@wraps(fn)
def inner(request, event_slug, *args, **kwargs):
event = get_object_or_404(Event, slug=event_slug)
try:
if not EventPermission.get(event, request.user).can_see_statistics:
ajax_util.require_user_features(counter=True, clerk=True, staff_override=True)(lambda _: None)(request)
# else: User has permissions, no further checks needed.
except ajax_util.AjaxError:
if event.checkout_active:
return redirect('kirppu:checkout_view', event_slug=event.slug)
else:
raise PermissionDenied()
return fn(request, event, *args, **kwargs)
return inner
@ensure_csrf_cookie
@_statistics_access
def stats_view(request, event):
"""Stats view."""
ic = ItemCountData(ItemCountData.GROUP_ITEM_TYPE, event=event)
ie = ItemEurosData(ItemEurosData.GROUP_ITEM_TYPE, event=event)
sum_name = _("Sum")
item_types = ItemType.objects.filter(event=event).order_by("order").values_list("id", "title")
number_of_items = [
ic.data_set(item_type, type_name)
for item_type, type_name in item_types
]
number_of_items.append(ic.data_set("sum", sum_name))
number_of_euros = [
ie.data_set(item_type, type_name)
for item_type, type_name in item_types
]
number_of_euros.append(ie.data_set("sum", sum_name))
vendor_item_data_counts = []
vendor_item_data_euros = []
vic = ItemCountData(ItemCountData.GROUP_VENDOR, event=event)
vie = ItemEurosData(ItemEurosData.GROUP_VENDOR, event=event)
vie.use_cents = True
vendor_item_data_row_size = 0
for vendor_id in vic.keys():
name = _("Vendor %i") % vendor_id
counts = vic.data_set(vendor_id, name)
euros = vie.data_set(vendor_id, name)
if vendor_item_data_row_size == 0:
vendor_item_data_row_size = len(list(counts.property_names))
vendor_item_data_counts.append(counts)
vendor_item_data_euros.append(euros)
context = {
'event': event,
'number_of_items': number_of_items,
'number_of_euros': number_of_euros,
'vendor_item_data_counts': vendor_item_data_counts,
'vendor_item_data_euros': vendor_item_data_euros,
'vendor_item_data_row_size': vendor_item_data_row_size,
'CURRENCY': settings.KIRPPU_CURRENCY["raw"],
}
return render(request, 'kirppu/app_stats.html', context)
@ensure_csrf_cookie
@_statistics_access
def type_stats_view(request, event, type_id):
item_type = get_object_or_404(ItemType, event=event, id=int(type_id))
return render(request, "kirppu/type_stats.html", {
"event": event,
"type_id": item_type.id,
"type_title": item_type.title,
})
def _float_array(array):
# noinspection PyPep8Naming
INFINITY = float('inf')
def _float(f):
if f != f:
return "NaN"
elif f == INFINITY:
return 'Infinity'
elif f == -INFINITY:
return '-Infinity'
return float.__repr__(f)
line_length = 20
o = [
", ".join(_float(e) for e in array[i:i + line_length])
for i in range(0, len(array), line_length)
]
return "[\n" + ",\n".join(o) + "]"
@ensure_csrf_cookie
@_statistics_access
def statistical_stats_view(request, event):
brought_states = (Item.BROUGHT, Item.STAGED, Item.SOLD, Item.COMPENSATED, Item.RETURNED)
_items = Item.objects.filter(vendor__event=event)
_vendors = Vendor.objects.filter(event=event)
_boxes = Box.objects.filter(representative_item__vendor__event=event)
registered = _items.count()
deleted = _items.filter(hidden=True).count()
brought = _items.filter(state__in=brought_states).count()
sold = _items.filter(state__in=(Item.STAGED, Item.SOLD, Item.COMPENSATED)).count()
printed_deleted = _items.filter(hidden=True, printed=True).count()
deleted_brought = _items.filter(hidden=True, state__in=brought_states).count()
printed_not_brought = _items.filter(printed=True, state=Item.ADVERTISED).count()
items_in_box = _items.filter(box__isnull=False).count()
items_not_in_box = _items.filter(box__isnull=True).count()
registered_boxes = _boxes.count()
deleted_boxes = _boxes.filter(representative_item__hidden=True).count()
items_in_deleted_boxes = _items.filter(box__representative_item__hidden=True).count()
general = {
"registered": registered,
"deleted": deleted,
"deletedOfRegistered": (deleted * 100.0 / registered) if registered > 0 else 0,
"brought": brought,
"broughtOfRegistered": (brought * 100.0 / registered) if registered > 0 else 0,
"broughtDeleted": deleted_brought,
"printedDeleted": printed_deleted,
"printedNotBrought": printed_not_brought,
"sold": sold,
"soldOfBrought": (sold * 100.0 / brought) if brought > 0 else 0,
"vendors": _vendors.filter(item__state__in=brought_states).distinct().count(),
"vendorsTotal": _vendors.annotate(items=models.Count("item__id")).filter(items__gt=0).count(),
"vendorsInMobileView": _vendors.filter(mobile_view_visited=True).count(),
"itemsInBox": items_in_box,
"itemsNotInBox": items_not_in_box,
"registeredBoxes": registered_boxes,
"deletedBoxes": deleted_boxes,
"deletedOfRegisteredBoxes": (deleted_boxes * 100.0 / registered_boxes) if registered_boxes > 0 else 0,
"itemsInDeletedBoxes": items_in_deleted_boxes,
"itemsInDeletedBoxesOfRegistered": (items_in_deleted_boxes * 100.0 / registered) if registered > 0 else 0,
}
compensations = _vendors.filter(item__state=Item.COMPENSATED) \
.annotate(v_sum=models.Sum("item__price")).order_by("v_sum").values_list("v_sum", flat=True)
compensations = [float(e) for e in compensations]
purchases = list(
Receipt.objects.filter(counter__event=event, status=Receipt.FINISHED, type=Receipt.TYPE_PURCHASE)
.order_by("total")
.values_list("total", flat=True)
)
purchases = [float(e) for e in purchases]
general["purchases"] = len(purchases)
return render(request, "kirppu/general_stats.html", {
"event": event,
"compensations": _float_array(compensations),
"purchases": _float_array(purchases),
"general": general,
"CURRENCY": settings.KIRPPU_CURRENCY["raw"],
})
def vendor_view(request, event_slug):
"""
Render main view for vendors.
:rtype: HttpResponse
"""
event = get_object_or_404(Event, slug=event_slug)
user = request.user
vendor_data = get_multi_vendor_values(request, event)
if user.is_authenticated:
vendor = Vendor.get_vendor(request, event)
items = Item.objects.filter(vendor=vendor, hidden=False, box__isnull=True)
boxes = Box.objects.filter(item__vendor=vendor, item__hidden=False).distinct()
boxed_items = Item.objects.filter(vendor=vendor, hidden=False, box__isnull=False)
else:
vendor = None
items = []
boxes = []
boxed_items = Item.objects.none()
context = {
'event': event,
'user': user,
'items': items,
'total_price': sum(i.price for i in items),
'num_total': len(items),
'num_printed': len(list(filter(lambda i: i.printed, items))),
'boxes': boxes,
'boxes_count': len(boxes),
'boxes_total_price': boxed_items.aggregate(sum=models.Sum("price"))["sum"],
'boxes_item_count': boxed_items.count(),
'boxes_printed': len(list(filter(lambda i: i.is_printed(), boxes))),
'profile_url': settings.PROFILE_URL,
'menu': _vendor_menu_contents(request, event),
'CURRENCY': settings.KIRPPU_CURRENCY,
}
context.update(vendor_data)
return render(request, "kirppu/app_frontpage.html", context)
@login_required
@require_http_methods(["POST"])
def accept_terms(request, event_slug):
event = get_object_or_404(Event, slug=event_slug)
vendor = Vendor.get_or_create_vendor(request, event)
if vendor.terms_accepted is None:
vendor.terms_accepted = timezone.now()
vendor.save(update_fields=("terms_accepted",))
result = timezone.template_localtime(vendor.terms_accepted)
result = localize(result)
return HttpResponse(json.dumps({
"result": "ok",
"time": result,
}), "application/json")
@login_required
def remove_item_from_receipt(request, event_slug):
event = get_object_or_404(Event, slug=event_slug)
if not request.user.is_staff:
raise PermissionDenied()
form = get_form(ItemRemoveForm, request, event=event)
if request.method == "POST" and form.is_valid():
try:
removal = _remove_item_from_receipt(request, form.cleaned_data["code"], form.cleaned_data["receipt"])
except (ValueError, AssertionError) as e:
form.add_error(None, e.args[0])
else:
messages.add_message(request, messages.INFO, "Item {0} removed from {1}".format(
form.cleaned_data["code"], removal.receipt
))
return HttpResponseRedirect(url.reverse('kirppu:remove_item_from_receipt',
kwargs={"event_slug": event.slug}))
return render(request, "kirppu/app_item_receipt_remove.html", {
'form': form,
})
@login_required
def lost_and_found_list(request, event_slug):
event = Event.objects.get(slug=event_slug)
if not EventPermission.get(event, request.user).can_see_accounting:
raise PermissionDenied
items = Item.objects \
.select_related("vendor") \
.filter(vendor__event=event, lost_property=True, abandoned=False) \
.order_by("vendor", "name")
vendor_object = namedtuple("VendorItems", "vendor vendor_id items")
vendor_list = {}
for item in items:
vendor_id = item.vendor_id
if vendor_id not in vendor_list:
vendor_list[vendor_id] = vendor_object(item.vendor.user, item.vendor_id, [])
vendor_list[vendor_id].items.append(item)
return render(request, "kirppu/lost_and_found.html", {
'menu': _vendor_menu_contents(request, event),
'event': event,
'items': vendor_list,
})
def kirppu_csrf_failure(request, reason=""):
if request.is_ajax() or request.META.get("HTTP_ACCEPT", "") == "text/json":
# TODO: Unify the response to match requested content type.
return HttpResponseForbidden(
_("CSRF verification failed. Request aborted."),
content_type="text/plain; charset=utf-8",
)
else:
return django_csrf_failure(request, reason=reason)
| from __future__ import unicode_literals, print_function, absolute_import
from collections import namedtuple
from functools import wraps
import json
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.core.exceptions import (
PermissionDenied,
ValidationError,
)
from django.contrib import messages
import django.urls as url
from django.db import transaction, models
from django.http.response import (
HttpResponse,
HttpResponseBadRequest,
HttpResponseForbidden,
HttpResponseRedirect,
)
from django.http import Http404
from django.shortcuts import (
redirect,
render,
get_object_or_404,
)
from django.utils import timezone
from django.utils.formats import localize
from django.utils.six import string_types
from django.utils.translation import ugettext as _
from django.views.csrf import csrf_failure as django_csrf_failure
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.decorators.http import require_http_methods
from django.views.generic import RedirectView
from .checkout_api import clerk_logout_fn
from . import ajax_util
from .forms import ItemRemoveForm, VendorItemForm, VendorBoxForm, remove_item_from_receipt as _remove_item_from_receipt
from .fields import ItemPriceField
from .models import (
Box,
Clerk,
Event,
EventPermission,
Item,
ItemType,
Vendor,
UserAdapter,
UIText,
Receipt,
)
from .stats import ItemCountData, ItemEurosData
from .util import get_form
from .utils import (
barcode_view,
is_vendor_open,
is_registration_closed_for_users,
require_vendor_open,
)
from .templatetags.kirppu_tags import get_dataurl
from .vendors import get_multi_vendor_values
import pubcode
def index(request):
return redirect("kirppu:front_page")
class MobileRedirect(RedirectView):
permanent = False
pattern_name = "kirppu:mobile"
@login_required
@require_http_methods(["POST"])
@require_vendor_open
def item_add(request, event):
if not Vendor.has_accepted(request, event):
return HttpResponseBadRequest()
vendor = Vendor.get_or_create_vendor(request, event)
form = VendorItemForm(request.POST, event)
if not form.is_valid():
return HttpResponseBadRequest(form.get_any_error())
item_cnt = Item.objects.filter(vendor=vendor).count()
# Create the items and construct a response containing all the items that have been added.
response = []
max_items = settings.KIRPPU_MAX_ITEMS_PER_VENDOR
data = form.db_values()
name = data.pop("name")
for suffix in form.cleaned_data["suffixes"]:
if item_cnt >= max_items:
error_msg = _(u"You have %(max_items)s items, which is the maximum. No more items can be registered.")
return HttpResponseBadRequest(error_msg % {'max_items': max_items})
item_cnt += 1
suffixed_name = (name + u" " + suffix).strip() if suffix else name
item = Item.new(
name=suffixed_name,
vendor=vendor,
**data
)
item_dict = item.as_public_dict()
item_dict['barcode_dataurl'] = get_dataurl(item.code, 'png')
response.append(item_dict)
return HttpResponse(json.dumps(response), 'application/json')
@login_required
@require_http_methods(["POST"])
def item_hide(request, event_slug, code):
event = get_object_or_404(Event, slug=event_slug)
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
item = get_object_or_404(Item.objects.select_for_update(), code=code, vendor=vendor)
item.hidden = True
item.save(update_fields=("hidden",))
return HttpResponse()
@login_required
@require_http_methods(['POST'])
def item_to_not_printed(request, event_slug, code):
event = get_object_or_404(Event, slug=event_slug)
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
item = get_object_or_404(Item.objects.select_for_update(), code=code, vendor=vendor, box__isnull=True)
if settings.KIRPPU_COPY_ITEM_WHEN_UNPRINTED:
# Create a duplicate of the item with a new code and hide the old item.
# This way, even if the user forgets to attach the new tags, the old
# printed tag is still in the system.
if not is_vendor_open(request, event):
return HttpResponseForbidden("Registration is closed")
new_item = Item.new(
name=item.name,
price=item.price,
vendor=item.vendor,
type=item.type,
state=Item.ADVERTISED,
itemtype=item.itemtype,
adult=item.adult
)
item.hidden = True
else:
item.printed = False
new_item = item
item.save(update_fields=("hidden", "printed"))
item_dict = {
'vendor_id': new_item.vendor_id,
'code': new_item.code,
'barcode_dataurl': get_dataurl(item.code, 'png'),
'name': new_item.name,
'price': str(new_item.price).replace('.', ','),
'type': new_item.type,
'adult': new_item.adult,
}
return HttpResponse(json.dumps(item_dict), 'application/json')
@login_required
@require_http_methods(["POST"])
def item_to_printed(request, event_slug, code):
event = get_object_or_404(Event, slug=event_slug)
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
item = get_object_or_404(Item.objects.select_for_update(), code=code, vendor=vendor, box__isnull=True)
item.printed = True
item.save(update_fields=("printed",))
return HttpResponse()
@login_required
@require_http_methods(["POST"])
@require_vendor_open
def item_update_price(request, event, code):
try:
price = ItemPriceField().clean(request.POST.get('value'))
except ValidationError as error:
return HttpResponseBadRequest(u' '.join(error.messages))
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
item = get_object_or_404(Item.objects.select_for_update(), code=code, vendor=vendor, box__isnull=True)
if item.is_locked():
return HttpResponseBadRequest("Item has been brought to event. Price can't be changed.")
item.price = str(price)
item.save(update_fields=("price",))
return HttpResponse(str(price).replace(".", ","))
@login_required
@require_http_methods(["POST"])
@require_vendor_open
def item_update_name(request, event, code):
name = request.POST.get("value", "no name")
name = name[:80]
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
item = get_object_or_404(Item.objects.select_for_update(), code=code, vendor=vendor)
if item.is_locked():
return HttpResponseBadRequest("Item has been brought to event. Name can't be changed.")
item.name = name
item.save(update_fields=("name",))
return HttpResponse(name)
@login_required
@require_http_methods(["POST"])
def item_update_type(request, event_slug, code):
event = get_object_or_404(Event, slug=event_slug)
tag_type = request.POST.get("tag_type", None)
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
item = get_object_or_404(Item.objects.select_for_update(), code=code, vendor=vendor)
item.type = tag_type
item.save(update_fields=("type",))
return HttpResponse()
@login_required
@require_http_methods(["POST"])
def all_to_print(request, event_slug):
event = get_object_or_404(Event, slug=event_slug)
vendor = Vendor.get_vendor(request, event)
items = Item.objects.filter(vendor=vendor).filter(printed=False).filter(box__isnull=True)
items.update(printed=True)
return HttpResponse()
@login_required
@require_http_methods(["POST"])
@require_vendor_open
def box_add(request, event):
if not event.use_boxes:
raise Http404()
if not Vendor.has_accepted(request, event):
return HttpResponseBadRequest()
vendor = Vendor.get_vendor(request, event)
form = VendorBoxForm(request.POST, event)
if not form.is_valid():
return HttpResponseBadRequest(form.get_any_error())
data = form.db_values()
# Verify that user doesn't exceed his/hers item quota with the box.
max_items = settings.KIRPPU_MAX_ITEMS_PER_VENDOR
item_cnt = Item.objects.filter(vendor=vendor).count()
count = data["count"]
if item_cnt >= max_items:
error_msg = _(u"You have %(max_items)s items, which is the maximum. No more items can be registered.")
return HttpResponseBadRequest(error_msg % {'max_items': max_items})
elif max_items < count + item_cnt:
error_msg = _(u"You have %(item_cnt)s items. "
u"Creating this box would cause the items to exceed the maximum number of allowed items.")
return HttpResponseBadRequest(error_msg % {'item_cnt': item_cnt})
# Create the box and items. and construct a response containing box and all the items that have been added.
box = Box.new(
vendor=vendor,
**data
)
box_dict = box.as_public_dict()
box_dict["vendor_id"] = vendor.id
box_dict["event"] = event
return render(request, "kirppu/app_boxes_box.html", box_dict)
@login_required
@require_http_methods(["POST"])
def box_hide(request, event_slug, box_id):
event = get_object_or_404(Event, slug=event_slug)
if not event.use_boxes:
raise Http404()
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
box = get_object_or_404(Box.objects, id=box_id)
box_vendor = box.get_vendor()
if box_vendor.id != vendor.id:
raise Http404()
box.set_hidden(True)
return HttpResponse()
@login_required
@require_http_methods(["POST"])
def box_print(request, event_slug, box_id):
event = get_object_or_404(Event, slug=event_slug)
if not event.use_boxes:
raise Http404()
with transaction.atomic():
vendor = Vendor.get_vendor(request, event)
box = get_object_or_404(Box.objects, id=box_id)
box_vendor = box.get_vendor()
if box_vendor.id != vendor.id:
raise Http404()
box.set_printed(True)
return HttpResponse()
@login_required
@require_http_methods(["GET"])
@barcode_view
def box_content(request, event_slug, box_id, bar_type):
"""
Get a page containing the contents of one box for printing
:param request: HttpRequest object.
:type request: django.http.request.HttpRequest
:param bar_type: Image type of the generated bar. See `kirppu_tags.barcode_dataurl`.
:type bar_type: str
:return: HttpResponse or HttpResponseBadRequest
"""
event = get_object_or_404(Event, slug=event_slug)
if not event.use_boxes:
raise Http404()
vendor = Vendor.get_vendor(request, event)
boxes = Box.objects.filter(id=box_id, item__vendor=vendor, item__hidden=False).distinct()
if boxes.count() == 0:
raise Http404()
box = boxes[0]
item = box.get_representative_item()
render_params = {
'box': box,
'item': item,
'bar_type': bar_type,
'CURRENCY': settings.KIRPPU_CURRENCY,
}
return render(request, "kirppu/app_boxes_content.html", render_params)
def _vendor_menu_contents(request, event):
"""
Generate menu for Vendor views.
Returned tuple contains entries for the menu, each entry containing a
name, url, and flag indicating whether the entry is currently active
or not.
:param event:
:param request: Current request being processed.
:return: List of menu items containing name, url and active fields.
:rtype: tuple[MenuItem,...]
"""
active = request.resolver_match.view_name
menu_item = namedtuple("MenuItem", "name url active sub_items")
def fill(name, func, sub=None, query=None, is_global=False):
if not is_global:
kwargs = {"event_slug": event.slug}
else:
kwargs = {}
link = url.reverse(func, kwargs=kwargs) if func else None
from urllib.parse import quote
if query:
link += "?" + "&".join(
quote(k, safe="") + (("=" + quote(v, safe="")) if v else "")
for k, v in query.items())
return menu_item(name, link, func == active, sub)
items = [
fill(_(u"Home"), "kirppu:vendor_view"),
fill(_(u"Item list"), "kirppu:page"),
]
if event.use_boxes:
items.append(fill(_(u"Box list"), "kirppu:vendor_boxes"))
if event.mobile_view_visible:
items.append(fill(_("Mobile"), "kirppu:mobile"))
manage_sub = []
permissions = EventPermission.get(event, request.user)
if request.user.is_staff or UserAdapter.is_clerk(request.user, event):
manage_sub.append(fill(_(u"Checkout commands"), "kirppu:commands"))
if event.checkout_active:
manage_sub.append(fill(_(u"Checkout"), "kirppu:checkout_view"))
if event.use_boxes:
manage_sub.append(fill(_("Box codes"), "kirppu:box_codes"))
if request.user.is_staff or permissions.can_see_clerk_codes:
manage_sub.append(fill(_(u"Clerk codes"), "kirppu:clerks"))
if request.user.is_staff or permissions.can_see_accounting:
manage_sub.append(fill(_(u"Lost and Found"), "kirppu:lost_and_found"))
if request.user.is_staff\
or UserAdapter.is_clerk(request.user, event)\
or permissions.can_see_statistics:
manage_sub.append(fill(_(u"Statistics"), "kirppu:stats_view"))
if request.user.is_staff:
try:
manage_sub.append(fill(_(u"Site administration"), "admin:index", is_global=True))
except url.NoReverseMatch as e:
pass
if manage_sub:
items.append(fill(_(u"Management"), "", manage_sub))
if permissions.can_see_accounting:
accounting_sub = [
fill(_("View"), "kirppu:accounting"),
fill(_("Download"), "kirppu:accounting", query={"download": ""}),
menu_item(None, None, None, None),
fill(_("View items"), "kirppu:item_dump", query={"txt": ""}),
fill(_("View items (CSV)"), "kirppu:item_dump"),
]
items.append(fill(_("Accounting"), "", accounting_sub))
return items
@login_required
@require_http_methods(["GET"])
@barcode_view
def get_items(request, event_slug, bar_type):
"""
Get a page containing all items for vendor.
:param request: HttpRequest object.
:type request: django.http.request.HttpRequest
:return: HttpResponse or HttpResponseBadRequest
"""
event = get_object_or_404(Event, slug=event_slug)
user = request.user
if user.is_staff and "user" in request.GET:
user = get_object_or_404(get_user_model(), username=request.GET["user"])
vendor = Vendor.get_vendor(request, event)
vendor_data = get_multi_vendor_values(request, event)
if event.multiple_vendors_per_user and user.is_staff and "user" in request.GET:
raise NotImplementedError # FIXME: Decide how this should work.
vendor_items = Item.objects.filter(vendor=vendor, hidden=False, box__isnull=True)
items = vendor_items.filter(printed=False)
printed_items = vendor_items.filter(printed=True)
# Order from newest to oldest, because that way new items are added
# to the top and the user immediately sees them without scrolling
# down.
items = items.order_by('-id')
item_name_placeholder = UIText.get_text(event, "item_placeholder", _("Ranma ½ Vol."))
render_params = {
'event': event,
'items': items,
'printed_items': printed_items,
'bar_type': bar_type,
'item_name_placeholder': item_name_placeholder,
'profile_url': settings.PROFILE_URL,
'terms_accepted': vendor.terms_accepted if vendor is not None else False,
'is_registration_open': is_vendor_open(request, event),
'is_registration_closed_for_users': is_registration_closed_for_users(event=event),
'menu': _vendor_menu_contents(request, event),
'itemTypes': ItemType.as_tuple(event),
'CURRENCY': settings.KIRPPU_CURRENCY,
'PRICE_MIN_MAX': settings.KIRPPU_MIN_MAX_PRICE,
}
render_params.update(vendor_data)
return render(request, "kirppu/app_items.html", render_params)
@login_required
@require_http_methods(["GET"])
def get_boxes(request, event_slug):
"""
Get a page containing all boxes for vendor.
:param request: HttpRequest object.
:type request: django.http.request.HttpRequest
:return: HttpResponse or HttpResponseBadRequest
"""
event = get_object_or_404(Event, slug=event_slug)
if not event.use_boxes:
raise Http404()
user = request.user
if user.is_staff and "user" in request.GET:
user = get_object_or_404(get_user_model(), username=request.GET["user"])
vendor = Vendor.get_vendor(request, event)
vendor_data = get_multi_vendor_values(request, event)
boxes = Box.objects.filter(item__vendor=vendor, item__hidden=False).distinct()
boxes = boxes.select_related("representative_item__itemtype")
# Order from newest to oldest, because that way new boxes are added
# to the top and the user immediately sees them without scrolling
# down.
boxes = boxes.order_by('-id')
box_name_placeholder = UIText.get_text(event, "box_placeholder", _("Box full of Ranma"))
render_params = {
'event': event,
'boxes': boxes,
'box_name_placeholder': box_name_placeholder,
'profile_url': settings.PROFILE_URL,
'terms_accepted': vendor.terms_accepted if vendor is not None else False,
'is_registration_open': is_vendor_open(request, event),
'is_registration_closed_for_users': is_registration_closed_for_users(event),
'menu': _vendor_menu_contents(request, event),
'itemTypes': ItemType.as_tuple(event),
'CURRENCY': settings.KIRPPU_CURRENCY,
'PRICE_MIN_MAX': settings.KIRPPU_MIN_MAX_PRICE,
}
render_params.update(vendor_data)
return render(request, "kirppu/app_boxes.html", render_params)
@login_required
@barcode_view
def get_clerk_codes(request, event_slug, bar_type):
event = get_object_or_404(Event, slug=event_slug)
if not (request.user.is_staff or EventPermission.get(event, request.user).can_see_clerk_codes):
return HttpResponseForbidden()
bound = []
unbound = []
code_item = namedtuple("CodeItem", "name code")
for c in Clerk.objects.filter(event=event, access_key__isnull=False):
if not c.is_valid_code:
continue
code = c.get_code()
if c.user is not None:
name = c.user.get_short_name()
if len(name) == 0:
name = c.user.get_username()
bound.append(code_item(name=name, code=code))
else:
unbound.append(code_item(name="", code=code))
items = None
if bound or unbound:
bound.sort(key=lambda a: a.name + a.code)
unbound.sort(key=lambda a: a.code)
items = bound + unbound
# Generate a code to check it's length.
name, code = items[0]
width = pubcode.Code128(code, charset='B').width(add_quiet_zone=True)
else:
width = None # Doesn't matter.
return render(request, "kirppu/app_clerks.html", {
'event': event,
'items': items,
'bar_type': bar_type,
'repeat': range(1),
'barcode_width': width,
})
@login_required
@barcode_view
def get_counter_commands(request, event_slug, bar_type):
event = get_object_or_404(Event, slug=event_slug)
if not (request.user.is_staff or UserAdapter.is_clerk(request.user, event)):
raise PermissionDenied()
return render(request, "kirppu/app_commands.html", {
'event_slug': event_slug,
'title': _(u"Counter commands"),
})
@login_required
@barcode_view
def get_boxes_codes(request, event_slug, bar_type):
event = get_object_or_404(Event, slug=event_slug)
if not event.use_boxes:
raise Http404()
if not (request.user.is_staff or UserAdapter.is_clerk(request.user, event)):
raise PermissionDenied()
boxes = Box.objects.filter(representative_item__vendor__event=event, box_number__isnull=False).order_by("box_number")
vm = []
for box in boxes:
code = "box%d" % box.box_number
img = pubcode.Code128(code, charset='B').data_url(image_format=bar_type, add_quiet_zone=True)
r = box.get_representative_item() # type: Item
vm.append({
"name": box.description,
"code": code,
"data_url": img,
"adult": r.adult,
"vendor_id": r.vendor_id,
"price": r.price_fmt,
"bundle_size": box.bundle_size,
"box_number": box.box_number,
})
return render(request, "kirppu/boxes_list.html", {
"bar_type": bar_type,
"boxes": vm
})
@ensure_csrf_cookie
def checkout_view(request, event_slug):
"""
Checkout view.
:param request: HttpRequest object
:type request: django.http.request.HttpRequest
:return: Response containing the view.
:rtype: HttpResponse
"""
event = get_object_or_404(Event, slug=event_slug)
if not event.checkout_active:
raise PermissionDenied()
clerk_logout_fn(request)
context = {
'CURRENCY': settings.KIRPPU_CURRENCY,
'PURCHASE_MAX': settings.KIRPPU_MAX_PURCHASE,
'event': event,
}
if settings.KIRPPU_AUTO_CLERK and settings.DEBUG:
if isinstance(settings.KIRPPU_AUTO_CLERK, string_types):
real_clerks = Clerk.objects.filter(event=event, user__username=settings.KIRPPU_AUTO_CLERK)
else:
real_clerks = Clerk.objects.filter(event=event, user__isnull=False)
for clerk in real_clerks:
if clerk.is_enabled:
context["auto_clerk"] = clerk.get_code()
break
return render(request, "kirppu/app_checkout.html", context)
@ensure_csrf_cookie
def overseer_view(request, event_slug):
"""Overseer view."""
event = get_object_or_404(Event, slug=event_slug)
if not event.checkout_active:
raise PermissionDenied()
try:
ajax_util.require_user_features(counter=True, clerk=True, overseer=True)(lambda _: None)(request)
except ajax_util.AjaxError:
return redirect('kirppu:checkout_view', event_slug=event.slug)
else:
context = {
'event': event,
'itemtypes': ItemType.as_tuple(event),
'itemstates': Item.STATE,
'CURRENCY': settings.KIRPPU_CURRENCY,
}
return render(request, 'kirppu/app_overseer.html', context)
def _statistics_access(fn):
@wraps(fn)
def inner(request, event_slug, *args, **kwargs):
event = get_object_or_404(Event, slug=event_slug)
try:
if not EventPermission.get(event, request.user).can_see_statistics:
ajax_util.require_user_features(counter=True, clerk=True, staff_override=True)(lambda _: None)(request)
# else: User has permissions, no further checks needed.
except ajax_util.AjaxError:
if event.checkout_active:
return redirect('kirppu:checkout_view', event_slug=event.slug)
else:
raise PermissionDenied()
return fn(request, event, *args, **kwargs)
return inner
@ensure_csrf_cookie
@_statistics_access
def stats_view(request, event):
"""Stats view."""
ic = ItemCountData(ItemCountData.GROUP_ITEM_TYPE, event=event)
ie = ItemEurosData(ItemEurosData.GROUP_ITEM_TYPE, event=event)
sum_name = _("Sum")
item_types = ItemType.objects.filter(event=event).order_by("order").values_list("id", "title")
number_of_items = [
ic.data_set(item_type, type_name)
for item_type, type_name in item_types
]
number_of_items.append(ic.data_set("sum", sum_name))
number_of_euros = [
ie.data_set(item_type, type_name)
for item_type, type_name in item_types
]
number_of_euros.append(ie.data_set("sum", sum_name))
vendor_item_data_counts = []
vendor_item_data_euros = []
vic = ItemCountData(ItemCountData.GROUP_VENDOR, event=event)
vie = ItemEurosData(ItemEurosData.GROUP_VENDOR, event=event)
vie.use_cents = True
vendor_item_data_row_size = 0
for vendor_id in vic.keys():
name = _("Vendor %i") % vendor_id
counts = vic.data_set(vendor_id, name)
euros = vie.data_set(vendor_id, name)
if vendor_item_data_row_size == 0:
vendor_item_data_row_size = len(list(counts.property_names))
vendor_item_data_counts.append(counts)
vendor_item_data_euros.append(euros)
context = {
'event': event,
'number_of_items': number_of_items,
'number_of_euros': number_of_euros,
'vendor_item_data_counts': vendor_item_data_counts,
'vendor_item_data_euros': vendor_item_data_euros,
'vendor_item_data_row_size': vendor_item_data_row_size,
'CURRENCY': settings.KIRPPU_CURRENCY["raw"],
}
return render(request, 'kirppu/app_stats.html', context)
@ensure_csrf_cookie
@_statistics_access
def type_stats_view(request, event, type_id):
item_type = get_object_or_404(ItemType, event=event, id=int(type_id))
return render(request, "kirppu/type_stats.html", {
"event": event,
"type_id": item_type.id,
"type_title": item_type.title,
})
def _float_array(array):
# noinspection PyPep8Naming
INFINITY = float('inf')
def _float(f):
if f != f:
return "NaN"
elif f == INFINITY:
return 'Infinity'
elif f == -INFINITY:
return '-Infinity'
return float.__repr__(f)
line_length = 20
o = [
", ".join(_float(e) for e in array[i:i + line_length])
for i in range(0, len(array), line_length)
]
return "[\n" + ",\n".join(o) + "]"
@ensure_csrf_cookie
@_statistics_access
def statistical_stats_view(request, event):
brought_states = (Item.BROUGHT, Item.STAGED, Item.SOLD, Item.COMPENSATED, Item.RETURNED)
_items = Item.objects.filter(vendor__event=event)
_vendors = Vendor.objects.filter(event=event)
_boxes = Box.objects.filter(representative_item__vendor__event=event)
registered = _items.count()
deleted = _items.filter(hidden=True).count()
brought = _items.filter(state__in=brought_states).count()
sold = _items.filter(state__in=(Item.STAGED, Item.SOLD, Item.COMPENSATED)).count()
printed_deleted = _items.filter(hidden=True, printed=True).count()
deleted_brought = _items.filter(hidden=True, state__in=brought_states).count()
printed_not_brought = _items.filter(printed=True, state=Item.ADVERTISED).count()
items_in_box = _items.filter(box__isnull=False).count()
items_not_in_box = _items.filter(box__isnull=True).count()
registered_boxes = _boxes.count()
deleted_boxes = _boxes.filter(representative_item__hidden=True).count()
items_in_deleted_boxes = _items.filter(box__representative_item__hidden=True).count()
general = {
"registered": registered,
"deleted": deleted,
"deletedOfRegistered": (deleted * 100.0 / registered) if registered > 0 else 0,
"brought": brought,
"broughtOfRegistered": (brought * 100.0 / registered) if registered > 0 else 0,
"broughtDeleted": deleted_brought,
"printedDeleted": printed_deleted,
"printedNotBrought": printed_not_brought,
"sold": sold,
"soldOfBrought": (sold * 100.0 / brought) if brought > 0 else 0,
"vendors": _vendors.filter(item__state__in=brought_states).distinct().count(),
"vendorsTotal": _vendors.annotate(items=models.Count("item__id")).filter(items__gt=0).count(),
"vendorsInMobileView": _vendors.filter(mobile_view_visited=True).count(),
"itemsInBox": items_in_box,
"itemsNotInBox": items_not_in_box,
"registeredBoxes": registered_boxes,
"deletedBoxes": deleted_boxes,
"deletedOfRegisteredBoxes": (deleted_boxes * 100.0 / registered_boxes) if registered_boxes > 0 else 0,
"itemsInDeletedBoxes": items_in_deleted_boxes,
"itemsInDeletedBoxesOfRegistered": (items_in_deleted_boxes * 100.0 / registered) if registered > 0 else 0,
}
compensations = _vendors.filter(item__state=Item.COMPENSATED) \
.annotate(v_sum=models.Sum("item__price")).order_by("v_sum").values_list("v_sum", flat=True)
compensations = [float(e) for e in compensations]
purchases = list(
Receipt.objects.filter(counter__event=event, status=Receipt.FINISHED, type=Receipt.TYPE_PURCHASE)
.order_by("total")
.values_list("total", flat=True)
)
purchases = [float(e) for e in purchases]
general["purchases"] = len(purchases)
return render(request, "kirppu/general_stats.html", {
"event": event,
"compensations": _float_array(compensations),
"purchases": _float_array(purchases),
"general": general,
"CURRENCY": settings.KIRPPU_CURRENCY["raw"],
})
def vendor_view(request, event_slug):
"""
Render main view for vendors.
:rtype: HttpResponse
"""
event = get_object_or_404(Event, slug=event_slug)
user = request.user
vendor_data = get_multi_vendor_values(request, event)
if user.is_authenticated:
vendor = Vendor.get_vendor(request, event)
items = Item.objects.filter(vendor=vendor, hidden=False, box__isnull=True)
boxes = Box.objects.filter(item__vendor=vendor, item__hidden=False).distinct()
boxed_items = Item.objects.filter(vendor=vendor, hidden=False, box__isnull=False)
else:
vendor = None
items = []
boxes = []
boxed_items = Item.objects.none()
context = {
'event': event,
'user': user,
'items': items,
'total_price': sum(i.price for i in items),
'num_total': len(items),
'num_printed': len(list(filter(lambda i: i.printed, items))),
'boxes': boxes,
'boxes_count': len(boxes),
'boxes_total_price': boxed_items.aggregate(sum=models.Sum("price"))["sum"],
'boxes_item_count': boxed_items.count(),
'boxes_printed': len(list(filter(lambda i: i.is_printed(), boxes))),
'profile_url': settings.PROFILE_URL,
'menu': _vendor_menu_contents(request, event),
'CURRENCY': settings.KIRPPU_CURRENCY,
}
context.update(vendor_data)
return render(request, "kirppu/app_frontpage.html", context)
@login_required
@require_http_methods(["POST"])
def accept_terms(request, event_slug):
event = get_object_or_404(Event, slug=event_slug)
vendor = Vendor.get_or_create_vendor(request, event)
if vendor.terms_accepted is None:
vendor.terms_accepted = timezone.now()
vendor.save(update_fields=("terms_accepted",))
result = timezone.template_localtime(vendor.terms_accepted)
result = localize(result)
return HttpResponse(json.dumps({
"result": "ok",
"time": result,
}), "application/json")
@login_required
def remove_item_from_receipt(request, event_slug):
event = get_object_or_404(Event, slug=event_slug)
if not request.user.is_staff:
raise PermissionDenied()
form = get_form(ItemRemoveForm, request, event=event)
if request.method == "POST" and form.is_valid():
try:
removal = _remove_item_from_receipt(request, form.cleaned_data["code"], form.cleaned_data["receipt"])
except (ValueError, AssertionError) as e:
form.add_error(None, e.args[0])
else:
messages.add_message(request, messages.INFO, "Item {0} removed from {1}".format(
form.cleaned_data["code"], removal.receipt
))
return HttpResponseRedirect(url.reverse('kirppu:remove_item_from_receipt',
kwargs={"event_slug": event.slug}))
return render(request, "kirppu/app_item_receipt_remove.html", {
'form': form,
})
@login_required
def lost_and_found_list(request, event_slug):
event = Event.objects.get(slug=event_slug)
if not EventPermission.get(event, request.user).can_see_accounting:
raise PermissionDenied
items = Item.objects \
.select_related("vendor") \
.filter(vendor__event=event, lost_property=True, abandoned=False) \
.order_by("vendor", "name")
vendor_object = namedtuple("VendorItems", "vendor vendor_id items")
vendor_list = {}
for item in items:
vendor_id = item.vendor_id
if vendor_id not in vendor_list:
vendor_list[vendor_id] = vendor_object(item.vendor.user, item.vendor_id, [])
vendor_list[vendor_id].items.append(item)
return render(request, "kirppu/lost_and_found.html", {
'menu': _vendor_menu_contents(request, event),
'event': event,
'items': vendor_list,
})
def kirppu_csrf_failure(request, reason=""):
if request.is_ajax() or request.META.get("HTTP_ACCEPT", "") == "text/json":
# TODO: Unify the response to match requested content type.
return HttpResponseForbidden(
_("CSRF verification failed. Request aborted."),
content_type="text/plain; charset=utf-8",
)
else:
return django_csrf_failure(request, reason=reason)
| en | 0.789824 | # Create the items and construct a response containing all the items that have been added. # Create a duplicate of the item with a new code and hide the old item. # This way, even if the user forgets to attach the new tags, the old # printed tag is still in the system. # Verify that user doesn't exceed his/hers item quota with the box. # Create the box and items. and construct a response containing box and all the items that have been added. Get a page containing the contents of one box for printing :param request: HttpRequest object. :type request: django.http.request.HttpRequest :param bar_type: Image type of the generated bar. See `kirppu_tags.barcode_dataurl`. :type bar_type: str :return: HttpResponse or HttpResponseBadRequest Generate menu for Vendor views. Returned tuple contains entries for the menu, each entry containing a name, url, and flag indicating whether the entry is currently active or not. :param event: :param request: Current request being processed. :return: List of menu items containing name, url and active fields. :rtype: tuple[MenuItem,...] Get a page containing all items for vendor. :param request: HttpRequest object. :type request: django.http.request.HttpRequest :return: HttpResponse or HttpResponseBadRequest # FIXME: Decide how this should work. # Order from newest to oldest, because that way new items are added # to the top and the user immediately sees them without scrolling # down. Get a page containing all boxes for vendor. :param request: HttpRequest object. :type request: django.http.request.HttpRequest :return: HttpResponse or HttpResponseBadRequest # Order from newest to oldest, because that way new boxes are added # to the top and the user immediately sees them without scrolling # down. # Generate a code to check it's length. # Doesn't matter. # type: Item Checkout view. :param request: HttpRequest object :type request: django.http.request.HttpRequest :return: Response containing the view. :rtype: HttpResponse Overseer view. # else: User has permissions, no further checks needed. Stats view. # noinspection PyPep8Naming Render main view for vendors. :rtype: HttpResponse # TODO: Unify the response to match requested content type. | 1.576285 | 2 |
old/pepper1/src/test/test_print.py | andybalaam/pepper | 2 | 6616059 | # Copyright (C) 2013 <NAME> and The Pepper Developers
# Released under the MIT License. See the file COPYING.txt for details.
from asserts import assert_rendered_cpp_equals
def Adding_known_to_unknown_via_real_parser___test():
assert_rendered_cpp_equals(
r"""printf( "A%sB\n", argv[1] )""",
r"""print( "A" + sys.argv[1] + "B" )"""
)
def Adding_known_to_unknown_numbers___test():
assert_rendered_cpp_equals(
r"""printf( "A%dB\n", argc )""",
r"""print( "A" + len( sys.argv ) + "B" )"""
)
# TODO: FAILS because print mistakenly breaks up subexpression
#def Adding_known_to_unknown_expression___test():
# assert_rendered_cpp_equals(
# r"""printf( "A%d\n", (1 + argc) )""",
# r"""print( "A" + ( 1 + len( sys.argv ) ) )"""
# )
# TODO: FAILS to parse because we can't have a subexpression on the
# left of another expression.
#def Adding_known_to_unknown_expression___test():
# assert_rendered_cpp_equals(
# r"""printf( "A%dB\n", (1 + argc) )""",
# r"""print( "A" + ( 1 + len( sys.argv ) ) + "B" )"""
# )
| # Copyright (C) 2013 <NAME> and The Pepper Developers
# Released under the MIT License. See the file COPYING.txt for details.
from asserts import assert_rendered_cpp_equals
def Adding_known_to_unknown_via_real_parser___test():
assert_rendered_cpp_equals(
r"""printf( "A%sB\n", argv[1] )""",
r"""print( "A" + sys.argv[1] + "B" )"""
)
def Adding_known_to_unknown_numbers___test():
assert_rendered_cpp_equals(
r"""printf( "A%dB\n", argc )""",
r"""print( "A" + len( sys.argv ) + "B" )"""
)
# TODO: FAILS because print mistakenly breaks up subexpression
#def Adding_known_to_unknown_expression___test():
# assert_rendered_cpp_equals(
# r"""printf( "A%d\n", (1 + argc) )""",
# r"""print( "A" + ( 1 + len( sys.argv ) ) )"""
# )
# TODO: FAILS to parse because we can't have a subexpression on the
# left of another expression.
#def Adding_known_to_unknown_expression___test():
# assert_rendered_cpp_equals(
# r"""printf( "A%dB\n", (1 + argc) )""",
# r"""print( "A" + ( 1 + len( sys.argv ) ) + "B" )"""
# )
| en | 0.590209 | # Copyright (C) 2013 <NAME> and The Pepper Developers # Released under the MIT License. See the file COPYING.txt for details. printf( "A%sB\n", argv[1] ) print( "A" + sys.argv[1] + "B" ) printf( "A%dB\n", argc ) print( "A" + len( sys.argv ) + "B" ) # TODO: FAILS because print mistakenly breaks up subexpression #def Adding_known_to_unknown_expression___test(): # assert_rendered_cpp_equals( # r"""printf( "A%d\n", (1 + argc) )""", # r"""print( "A" + ( 1 + len( sys.argv ) ) )""" # ) # TODO: FAILS to parse because we can't have a subexpression on the # left of another expression. #def Adding_known_to_unknown_expression___test(): # assert_rendered_cpp_equals( # r"""printf( "A%dB\n", (1 + argc) )""", # r"""print( "A" + ( 1 + len( sys.argv ) ) + "B" )""" # ) | 2.824563 | 3 |
benchmarks/pipelines/score.py | vumichien/hummingbird | 2,772 | 6616060 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from abc import ABC, abstractmethod
import numpy as np
from benchmarks.timer import Timer
import hummingbird.ml
class ScoreBackend(ABC):
@staticmethod
def create(name):
if name in ["torch", "torch.jit", "tvm", "onnx"]:
return HBBackend(name)
raise ValueError("Unknown backend: " + name)
def __init__(self):
self.model = None
self.params = {}
self.predictions = None
def configure(self, data, model, args):
self.params.update({"device": "cpu" if args.gpu is False else "cuda"})
@staticmethod
def get_data(data):
np_data = data.to_numpy() if not isinstance(data, np.ndarray) else data
return np_data
@abstractmethod
def convert(self, model, args):
pass
@abstractmethod
def predict(self, data):
pass
def __enter__(self):
pass
@abstractmethod
def __exit__(self, exc_type, exc_value, traceback):
pass
class HBBackend(ScoreBackend):
def __init__(self, backend_name):
super(HBBackend, self).__init__()
self._backend_name = backend_name
def convert(self, model, data, args):
self.configure(data, model, args)
data = self.get_data(data)
with Timer() as t:
self.model = hummingbird.ml.convert(model, self._backend_name, data, device=self.params["device"])
return t.interval
def predict(self, data):
assert self.model is not None
data = self.get_data(data)
with Timer() as t:
self.predictions = self.model.predict(data)
return t.interval
def __exit__(self, exc_type, exc_value, traceback):
del self.model
| # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from abc import ABC, abstractmethod
import numpy as np
from benchmarks.timer import Timer
import hummingbird.ml
class ScoreBackend(ABC):
@staticmethod
def create(name):
if name in ["torch", "torch.jit", "tvm", "onnx"]:
return HBBackend(name)
raise ValueError("Unknown backend: " + name)
def __init__(self):
self.model = None
self.params = {}
self.predictions = None
def configure(self, data, model, args):
self.params.update({"device": "cpu" if args.gpu is False else "cuda"})
@staticmethod
def get_data(data):
np_data = data.to_numpy() if not isinstance(data, np.ndarray) else data
return np_data
@abstractmethod
def convert(self, model, args):
pass
@abstractmethod
def predict(self, data):
pass
def __enter__(self):
pass
@abstractmethod
def __exit__(self, exc_type, exc_value, traceback):
pass
class HBBackend(ScoreBackend):
def __init__(self, backend_name):
super(HBBackend, self).__init__()
self._backend_name = backend_name
def convert(self, model, data, args):
self.configure(data, model, args)
data = self.get_data(data)
with Timer() as t:
self.model = hummingbird.ml.convert(model, self._backend_name, data, device=self.params["device"])
return t.interval
def predict(self, data):
assert self.model is not None
data = self.get_data(data)
with Timer() as t:
self.predictions = self.model.predict(data)
return t.interval
def __exit__(self, exc_type, exc_value, traceback):
del self.model
| en | 0.468429 | # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- | 2.054794 | 2 |
distributions/__init__.py | Nakulbajaj101/gaussian-test-package | 0 | 6616061 | <gh_stars>0
from .gaussian import Gaussian
from .distribution import Distribution
| from .gaussian import Gaussian
from .distribution import Distribution | none | 1 | 1.098011 | 1 | |
tests/models/User.py | girardinsamuel/api | 12 | 6616062 | <reponame>girardinsamuel/api
from orator import Model
class User(Model):
id = 1
name = '<NAME>'
email = '<EMAIL>'
@staticmethod
def find(id):
user = User()
user.id = 1
user.name = '<NAME>'
user.email = '<EMAIL>'
return user
def serialize(self):
return {'id': 1}
| from orator import Model
class User(Model):
id = 1
name = '<NAME>'
email = '<EMAIL>'
@staticmethod
def find(id):
user = User()
user.id = 1
user.name = '<NAME>'
user.email = '<EMAIL>'
return user
def serialize(self):
return {'id': 1} | none | 1 | 2.908417 | 3 | |
pyeip1962/parser.py | HarryR/pyeip1962 | 2 | 6616063 | <gh_stars>1-10
from typing import Union, Callable, Any
from .ops import AnyOp, Operation, G1Prefix, G2Prefix, G1AddOp, G1MulOp, G1MultiExpOp, G1Op
from .ops import G2AddOp, G2MulOp, G2MultiExpOp, G2Op
from .ops import G1Point, G2Point, TwistType, CurveFamily
from .structs import
from .fields import Fq, Fqk
def _make_int(data: bytes) -> int:
return int.from_bytes(data, 'big')
CURVE_TYPE_LENGTH = 1
OPERATION_ENCODING_LENGTH = 1
TWIST_TYPE_LENGTH = 1
EXTENSION_DEGREE_ENCODING_LENGTH = 1
BYTES_FOR_LENGTH_ENCODING = 1
def is_non_nth_root(divisor, modulus):
if x == 0:
return False
quotient, remainder = divmod(modulus-1, divisor)
if remainder == 0:
return False
l = pow(divisor, quotient, modulus)
return l != 1
class StreamParser(object):
def __init__(self, data: bytes):
self.data = data
def _consume(self, n: int, parsefn: Callable) -> Any:
if len(calldata) < n:
raise RuntimeError(f'Could not read {n} bytes, only {len(calldata)} remaining')
obj = callfn(calldata[:n])
self.data = calldata[n:]
return obj
def _consume_int(self, n_bytes: int) -> int:
return self._consume(n_bytes, _make_int)
def _consume_many_int(self, n_bytes: int, count: int) -> List[int]:
return [self._consume_int(n_bytes) for _ in range(count)]
def _consume_Fq(self, n_bytes: int, field_modulus: int) -> Fq:
return Fq(self._consume_int(n_bytes), field_modulus)
def _consume_Fqk(self, n_bytes: int, extension_degree: int, field_modulus: int, modulus_coeffs) -> Fqk:
coeffs = [self._consume_int(n_bytes) for _ in range(extension_degree)]
return Fqk(coeffs, modulus_coeffs, field_modulus)
def g1_point(self, prefix: G1Prefix) -> G1Point:
x = self._consume_Fq(prefix.field_length, prefix.field_modulus)
y = self._consume_Fq(prefix.field_length, prefix.field_modulus)
return G1Point(x, y)
def g1_prefix(self) -> G1Prefix:
field_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
field_modulus, A, B = self._consume_many_int(field_length, 3)
order_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
order = self._consume_int(order_length)
return G1Prefix(field_length, field_modulus, A, B, order_length, order)
def g1_add_op(self, prefix: G1Prefix) -> G1AddOp:
return G1AddOp(self.g1_point(prefix), self.g1_point(prefix))
def g1_point_and_scalar(self, prefix: G1Prefix) -> Tuple[G1Point, int]:
point = self.g1_point(prefix)
scalar = self._consume_Fq(prefix.order_length, prefix.field_modulus)
return (point, scalar)
def g1_mul_op(self, prefix: G1Prefix) -> G1MulOp:
point, scalar = self.g1_point_and_scalar(prefix)
return G1MulOp(prefix, point, scalar)
def g1_multiexp_op(self, prefix: G1Prefix) -> G1MultiExpOp:
num_pairs = self._consume_int(1)
pairs = [self.g1_point_and_scalar(prefix) for _ in range(num_pairs)]
return G1MultiExpOp(prefix, num_pairs, pairs)
def g1_op(self, op: Operation) -> G1Op:
prefix = self.g1_prefix()
if op == Operation.G1_ADD:
return self.g1_add_op(prefix)
elif op == Operation.G1_MUL:
return self.g1_mul_op(prefix)
elif op == Operation.G1_MULTIEXP:
return self.g1_multiexp_op(prefix)
def g2_prefix(self) -> G2Prefix:
field_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
field_modulus = self._consume_int(field_length)
extension_degree = self._consume_int(EXTENSION_DEGREE_ENCODING_LENGTH)
non_residue, A, B = self._consume_many_int(field_length, 3)
order_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
order = self._consume_int(order_length)
return G2Prefix(field_length, field_modulus, non_residue, A, B, order_length, order)
def g2_point(self, prefix: G2Prefix) -> G2Point:
x_coeffs = self._consume_many_int(prefix.field_length, prefix.extension_degree)
y_coeffs = self._consume_many_int(prefix.field_length, prefix.extension_degree)
return G2Point(x_coeffs, y_coeffs)
def g2_add_op(self, prefix: G2Prefix):
return G2AddOp(prefix, self.g2_point(prefix), self.g2_point(prefix))
def g2_point_and_scalar(self, prefix: G2Prefix) -> Tuple[G2Point, int]:
point = self.g2_point(prefix)
scalar = self._consume_int(prefix.order_length)
return (point, scalar)
def g2_mul_op(self, prefix: G2Prefix) -> G2MulOp:
return G2MulOp(*self.g2_point_and_scalar(prefix))
def g2_multiexp_op(self, prefix: G2Prefix) -> G2MultiExpOp:
num_pairs = self._consume_int(1)
pairs = [self.g2_point_and_scalar(prefix) for _ in range(num_pairs)]
return G2MultiExpOp(prefix, num_pairs, pairs)
def g2_op(self, op: Operation) -> G2Op:
prefix = self.g2_prefix()
if op == Operation.G2_ADD:
return self.g2_add_op(prefix)
elif op == Operation.G2_MUL:
return self.g2_mul_op(prefix)
elif op == Operation.G2_MULTIEXP:
return self.g2_multiexp_op(prefix)
def g1_g2_pair(self, g1_prefix: G1Prefix, g2_prefix: G2Prefix):
pass
def pairing_bls12(self, field_length: int, field_modulus: int):
A, B = self._consume_many_int(field_length, 2)
if A != 0:
raise ValueError("A parameter must be zero for BLS12 curve")
order_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
order = self._consume_int(order_length)
if order == 0:
raise ValueError("Group order is zero")
fp_non_residue = self._consume_int(field_length)
is_not_a_square = is_non_nth_root(fp_non_residue, field_modulus)
if not is_not_a_square:
raise ValueError("Non-residue for Fp2 is actually a residue")
def pairing_op(self, op: Operation) -> PairingOp:
curve_type = CurveFamily(self._consume_int(CURVE_TYPE_LENGTH))
field_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
field_modulus = self._consume_int(field_length)
if curve_type == CurveFamily.BLS12:
return self.pairing_bls12(field_length, field_modulus)
elif curve_type == CurveFamily.BN:
return self.pairing_bn(field_length, field_modulus)
elif curve_type == CurveFamily.MNT4:
return self.pairing_mnt4(field_length, field_modulus)
elif curve_type == CurveFamily.MNT6:
return self.pairing_mnt6(field_length, field_modulus)
A, B = self._consume_many_int(field_length, 2)
order_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
order = self._consume_int(order_length)
fp2_non_residue = self._consume_int(field_length)
fp6_non_residue = self._consume_many_int(field_length, 2)
twist_type = TwistType(self._consume_int(TWIST_TYPE_LENGTH))
x_length = self._consume_int(1)
x = self._consume_int(x_length)
sign, num_pairs = self._consume_many_int(1, 2)
pairs =
def parse(self) -> AnyOp:
op_code = self._consume(OPERATION_ENCODING_LENGTH, lambda data: Operation(_make_int(data)))
if op_code.is_g1:
return self.g1_op(op_code)
elif op_code.is_g1:
return self.g2_op(op_code)
elif op_code.is_pairing:
return self.pairing_op(op_code)
| from typing import Union, Callable, Any
from .ops import AnyOp, Operation, G1Prefix, G2Prefix, G1AddOp, G1MulOp, G1MultiExpOp, G1Op
from .ops import G2AddOp, G2MulOp, G2MultiExpOp, G2Op
from .ops import G1Point, G2Point, TwistType, CurveFamily
from .structs import
from .fields import Fq, Fqk
def _make_int(data: bytes) -> int:
return int.from_bytes(data, 'big')
CURVE_TYPE_LENGTH = 1
OPERATION_ENCODING_LENGTH = 1
TWIST_TYPE_LENGTH = 1
EXTENSION_DEGREE_ENCODING_LENGTH = 1
BYTES_FOR_LENGTH_ENCODING = 1
def is_non_nth_root(divisor, modulus):
if x == 0:
return False
quotient, remainder = divmod(modulus-1, divisor)
if remainder == 0:
return False
l = pow(divisor, quotient, modulus)
return l != 1
class StreamParser(object):
def __init__(self, data: bytes):
self.data = data
def _consume(self, n: int, parsefn: Callable) -> Any:
if len(calldata) < n:
raise RuntimeError(f'Could not read {n} bytes, only {len(calldata)} remaining')
obj = callfn(calldata[:n])
self.data = calldata[n:]
return obj
def _consume_int(self, n_bytes: int) -> int:
return self._consume(n_bytes, _make_int)
def _consume_many_int(self, n_bytes: int, count: int) -> List[int]:
return [self._consume_int(n_bytes) for _ in range(count)]
def _consume_Fq(self, n_bytes: int, field_modulus: int) -> Fq:
return Fq(self._consume_int(n_bytes), field_modulus)
def _consume_Fqk(self, n_bytes: int, extension_degree: int, field_modulus: int, modulus_coeffs) -> Fqk:
coeffs = [self._consume_int(n_bytes) for _ in range(extension_degree)]
return Fqk(coeffs, modulus_coeffs, field_modulus)
def g1_point(self, prefix: G1Prefix) -> G1Point:
x = self._consume_Fq(prefix.field_length, prefix.field_modulus)
y = self._consume_Fq(prefix.field_length, prefix.field_modulus)
return G1Point(x, y)
def g1_prefix(self) -> G1Prefix:
field_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
field_modulus, A, B = self._consume_many_int(field_length, 3)
order_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
order = self._consume_int(order_length)
return G1Prefix(field_length, field_modulus, A, B, order_length, order)
def g1_add_op(self, prefix: G1Prefix) -> G1AddOp:
return G1AddOp(self.g1_point(prefix), self.g1_point(prefix))
def g1_point_and_scalar(self, prefix: G1Prefix) -> Tuple[G1Point, int]:
point = self.g1_point(prefix)
scalar = self._consume_Fq(prefix.order_length, prefix.field_modulus)
return (point, scalar)
def g1_mul_op(self, prefix: G1Prefix) -> G1MulOp:
point, scalar = self.g1_point_and_scalar(prefix)
return G1MulOp(prefix, point, scalar)
def g1_multiexp_op(self, prefix: G1Prefix) -> G1MultiExpOp:
num_pairs = self._consume_int(1)
pairs = [self.g1_point_and_scalar(prefix) for _ in range(num_pairs)]
return G1MultiExpOp(prefix, num_pairs, pairs)
def g1_op(self, op: Operation) -> G1Op:
prefix = self.g1_prefix()
if op == Operation.G1_ADD:
return self.g1_add_op(prefix)
elif op == Operation.G1_MUL:
return self.g1_mul_op(prefix)
elif op == Operation.G1_MULTIEXP:
return self.g1_multiexp_op(prefix)
def g2_prefix(self) -> G2Prefix:
field_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
field_modulus = self._consume_int(field_length)
extension_degree = self._consume_int(EXTENSION_DEGREE_ENCODING_LENGTH)
non_residue, A, B = self._consume_many_int(field_length, 3)
order_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
order = self._consume_int(order_length)
return G2Prefix(field_length, field_modulus, non_residue, A, B, order_length, order)
def g2_point(self, prefix: G2Prefix) -> G2Point:
x_coeffs = self._consume_many_int(prefix.field_length, prefix.extension_degree)
y_coeffs = self._consume_many_int(prefix.field_length, prefix.extension_degree)
return G2Point(x_coeffs, y_coeffs)
def g2_add_op(self, prefix: G2Prefix):
return G2AddOp(prefix, self.g2_point(prefix), self.g2_point(prefix))
def g2_point_and_scalar(self, prefix: G2Prefix) -> Tuple[G2Point, int]:
point = self.g2_point(prefix)
scalar = self._consume_int(prefix.order_length)
return (point, scalar)
def g2_mul_op(self, prefix: G2Prefix) -> G2MulOp:
return G2MulOp(*self.g2_point_and_scalar(prefix))
def g2_multiexp_op(self, prefix: G2Prefix) -> G2MultiExpOp:
num_pairs = self._consume_int(1)
pairs = [self.g2_point_and_scalar(prefix) for _ in range(num_pairs)]
return G2MultiExpOp(prefix, num_pairs, pairs)
def g2_op(self, op: Operation) -> G2Op:
prefix = self.g2_prefix()
if op == Operation.G2_ADD:
return self.g2_add_op(prefix)
elif op == Operation.G2_MUL:
return self.g2_mul_op(prefix)
elif op == Operation.G2_MULTIEXP:
return self.g2_multiexp_op(prefix)
def g1_g2_pair(self, g1_prefix: G1Prefix, g2_prefix: G2Prefix):
pass
def pairing_bls12(self, field_length: int, field_modulus: int):
A, B = self._consume_many_int(field_length, 2)
if A != 0:
raise ValueError("A parameter must be zero for BLS12 curve")
order_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
order = self._consume_int(order_length)
if order == 0:
raise ValueError("Group order is zero")
fp_non_residue = self._consume_int(field_length)
is_not_a_square = is_non_nth_root(fp_non_residue, field_modulus)
if not is_not_a_square:
raise ValueError("Non-residue for Fp2 is actually a residue")
def pairing_op(self, op: Operation) -> PairingOp:
curve_type = CurveFamily(self._consume_int(CURVE_TYPE_LENGTH))
field_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
field_modulus = self._consume_int(field_length)
if curve_type == CurveFamily.BLS12:
return self.pairing_bls12(field_length, field_modulus)
elif curve_type == CurveFamily.BN:
return self.pairing_bn(field_length, field_modulus)
elif curve_type == CurveFamily.MNT4:
return self.pairing_mnt4(field_length, field_modulus)
elif curve_type == CurveFamily.MNT6:
return self.pairing_mnt6(field_length, field_modulus)
A, B = self._consume_many_int(field_length, 2)
order_length = self._consume_int(BYTES_FOR_LENGTH_ENCODING)
order = self._consume_int(order_length)
fp2_non_residue = self._consume_int(field_length)
fp6_non_residue = self._consume_many_int(field_length, 2)
twist_type = TwistType(self._consume_int(TWIST_TYPE_LENGTH))
x_length = self._consume_int(1)
x = self._consume_int(x_length)
sign, num_pairs = self._consume_many_int(1, 2)
pairs =
def parse(self) -> AnyOp:
op_code = self._consume(OPERATION_ENCODING_LENGTH, lambda data: Operation(_make_int(data)))
if op_code.is_g1:
return self.g1_op(op_code)
elif op_code.is_g1:
return self.g2_op(op_code)
elif op_code.is_pairing:
return self.pairing_op(op_code) | none | 1 | 2.091176 | 2 | |
lazy.py | acadien/lazyPlot | 0 | 6616064 | #!/usr/bin/env python
#local
import plotRemote as pr
#standard
import re, sys, select
import pylab as pl
import numpy as np
#local
from smoothing import windowAvg,superSmooth
from colors import vizSpec
#attempts to parse a file, keeping only rows that can be converted to floats
#keeps rows with the most common number of columns.
def parse(fname,delim=None):
fraw = open(fname,"r").readlines()
data=list()
dataIndex=list()
for i,line in enumerate(fraw):
#drop lines with only newline characters
if len(line) < 2: continue
#drop comment lines
if line[0]=="#": continue
#drop lines that don't contain columns of numbers
l=line.split(delim)
f=list()
count=0
for elem in l:
try:
f.append(float(elem))
except ValueError:
count+=1
if count==len(l):
continue
data.append(f)
dataIndex.append(i)
#Keep only data with the most common number of columns
columnLengths=map(len,data)
colN=[columnLengths.count(i) for i in range(max(columnLengths)+1)]
colNi=colN.index(max(colN))
[dataNum,parsedData]=zip(*[[dataIndex[i],d] for i,d in enumerate(data) if columnLengths[i]==colNi])
parsedData=zip(*parsedData)
labels=fraw[dataNum[0]-1].split(delim)
n=len(labels)
try:
map(float,labels)
labels=[" "]*n
except:
pass
return labels,parsedData
def usage():
print "\nUsage: %s <x-data column><s><window size> <y-data column><s><window size> <filenames>"\
%sys.argv[0].split("/")[-1]
print "\nUsage: %s <x-data column><x><scale> <y-data column><x><scale> <filenames>"%sys.argv[0].split("/")[-1]
print "\nA general use plotter of 2D data. \nAttempts to find data in column format and plot the desired columns."
print "If x-data column is -1 then range(len(y)) is used"
print "If the column number is followed by an <s> then a window average is applied to that data."
print "If the column number is followed by an <x> then scaling by that value is applied"
print "examples:"
print "./plot2.py datafile "
print "./plot2.py 0 1 datafile1 datafile2 datafile3"
print "./plot2.py 0 1 datafile1 0 2 datafile2 datafile3"
print "./plot2.py 0 1s25 datafile1 #windowed average of width 25 is applied"
print "./plot2.py 0x0.5 1x2.0 datafile #scale of 0.5 on x-axis and scale of 2.0 on y-axis"
print "switches: -stagger, -sort, -avg, -scatter, -noLeg, -altSmooth, -logx, -logy, -saveFig"
print "switches with parameters: -alpha <alpha>, -title <title> -xlabel <xlabel> -ylabel <ylabel>"
print ""
if len(sys.argv)==1:
if select.select([sys.stdin,],[],[],0.0)[0]:
import fileinput
sys.argv += fileinput.input().readline().split()
if __name__=="__main__":
if len(sys.argv)<2:
usage()
exit(0)
columnIndeces=list()
fileIndeces=list()
columnFileCounter=list()
#Pre-parse for switches
nbins=80
alpha=1.0 #transparency
switches={"-stagger":False,"-sort":False,"-avg":False,"-scatter":False, "-noLeg":False, "-saveData":False, "-saveFig":False, "-altSmooth":False, "-h":False,"-alpha":None,"-logx":False,"-logy":False,"-title":False,"-xlabel":False,"-ylabel":False}
for i in range(len(sys.argv)-1,-1,-1):
if "-alpha" == sys.argv[i]: #special case alpha
switches["-alpha"]=True
sys.argv.pop(i)
alpha = float(sys.argv.pop(i))
elif "-xlabel" == sys.argv[i]:
sys.argv.pop(i)
switches["-xlabel"]=sys.argv.pop(i)
elif "-ylabel" == sys.argv[i]:
sys.argv.pop(i)
switches["-ylabel"]=sys.argv.pop(i)
elif "-title" == sys.argv[i]:
sys.argv.pop(i)
switches["-title"]=sys.argv.pop(i)
elif "-scatter" == sys.argv[i]:
sys.argv.pop(i)
switches["-scatter"]=sys.argv.pop(i)
elif sys.argv[i] in switches.keys():
switches[sys.argv[i]]=True
sys.argv.pop(i)
if switches["-h"]:
usage()
exit(0)
#Parse for column selection and file selection.
for i in range(1,len(sys.argv)):
reresult=re.search('^[-]?\d+[sx]?[-]?[\d]*\.?[\d]*$',sys.argv[i])
try:
if reresult.group(0) == sys.argv[i]:
columnIndeces.append(i)
#How many files will have these columns selected
if len(columnIndeces)%2==0:
columnFileCounter.append(0)
except AttributeError:
fileIndeces.append(i)
try:
columnFileCounter[-1]+=1
except IndexError: pass
if len(columnIndeces)!=0:
if len(columnIndeces)%2!=0 or columnIndeces[0]!=1:
usage()
print "***Error***: improperly formed column selection"
exit(0)
else:
columnFileCounter=[len(sys.argv[1:])]
xSmoothEnables=[]
ySmoothEnables=[]
xScaleEnables=[]
yScaleEnables=[]
xScales=[]
yScales=[]
xCols=[]
yCols=[]
xWANs=[]
yWANs=[]
if len(columnIndeces)==0:
for i in fileIndeces:
xCols.append(0)
yCols.append(1)
xSmoothEnables.append(False)
ySmoothEnables.append(False)
xScaleEnables.append(False)
yScaleEnables.append(False)
xWANs.append(0)
yWANs.append(0)
xScales.append(1.)
yScales.append(1.)
else:
xcs=[c for i,c in enumerate(columnIndeces) if i%2==0]
ycs=[c for i,c in enumerate(columnIndeces) if (i+1)%2==0]
for i in range(len(columnFileCounter)):
xc=sys.argv[xcs[i]]
xsc=False
xsm=False
xw=0
xscale=1.
if "s" in xc:
xsm=True
r=xc.split("s")
xc=int(r[0])
if r[1]=="":
xw=10
else:
xw=int(r[1])
elif "x" in xc:
xsc=True
r=xc.split("x")
xc=int(r[0])
if r[1]=="":
xscale=1.
else:
xscale=float(r[1])
else:
xc=int(xc)
yc=sys.argv[ycs[i]]
ysc=False
ysm=False
yw=0
yscale=1.0
if "s" in yc:
ysm=True
r=yc.split("s")
yc=int(r[0])
if r[1]=="":
yw=10
else:
yw=int(r[1])
elif "x" in yc:
ysc=True
r=yc.split("x")
yc=int(r[0])
if r[1]=="":
yscale=1.
else:
yscale=float(r[1])
else:
yc=int(yc)
for j in range(columnFileCounter[i]):
xCols.append(xc)
xSmoothEnables.append(xsm)
xWANs.append(xw)
xScaleEnables.append(xsc)
xScales.append(xscale)
yCols.append(yc)
ySmoothEnables.append(ysm)
yWANs.append(yw)
yScaleEnables.append(ysc)
yScales.append(yscale)
#Grab the file name
fileNames=[sys.argv[i] for i in fileIndeces]
nFileNames = len(fileNames)
if switches['-sort']:
#Sorting might introduce undesirable behavior so skip it
#if you're only selecting 1 column then sort the file names
if len(columnFileCounter)==1:
try:
fnamenumbers=map(lambda x:float(".".join(re.findall('\d+',x))),fileNames)
if nFileNames == len(fnamenumbers):
fileNames=zip(*sorted(zip(fileNames,fnamenumbers),key=lambda x:x[1]))[0]
except ValueError:
pass
#Initialize Average
initAvg=True
count=0.
#Colors
colors = None
#Load up the data and the label guesses
labels=list()
fdatas=list()
for fname in fileNames:
if fname[-3:]=="csv":
l,f = parse(fname,",")
else:
l,f = parse(fname)
labels.append(l)
fdatas.append(f)
print fname
label=labels[0]
fig=pl.figure()
pl.grid()
for i in range(sum(columnFileCounter)):
fdata=fdatas[i]
xCol=xCols[i]
yCol=yCols[i]
#Error check on column selection
if yCol >= len(fdata):
print "Error: Max column number is %d, but %d requested."%(len(fdata)-1,yCol)
if xCol >= len(fdata):
print "Error: Max column number is %d, but %d requested."%(len(fdata)-1,xCol)
#Column selection
ydata=fdata[yCol]
if xCol==-1:
xdata=range(len(ydata))
else:
xdata=fdata[xCol]
#Smoothing:
xSmoothEnable=xSmoothEnables[i]
ySmoothEnable=ySmoothEnables[i]
xWAN=xWANs[i]
yWAN=yWANs[i]
xdataSmooth=[]
ydataSmooth=[]
if xSmoothEnable:
if switches["-altSmooth"]:
xdataSmooth=superSmooth(xdata,ydata,xWAN/100.0)
else:
xdataSmooth=windowAvg(xdata,xWAN)
if ySmoothEnable:
if switches["-altSmooth"]:
ydataSmooth=superSmooth(xdata,ydata,yWAN/100.0)
else:
ydataSmooth=windowAvg(ydata,yWAN)
#Correct for window offset, average introduces extra points that need to be chopped off
if not switches["-altSmooth"] and xSmoothEnable or ySmoothEnable:
WAN=max(xWAN,yWAN)
xdataSmooth=xdataSmooth[WAN/2+1:WAN/-2]
ydataSmooth=ydataSmooth[WAN/2+1:WAN/-2]
xdata=xdata[WAN/2+1:WAN/-2]
ydata=ydata[WAN/2+1:WAN/-2]
#Scaling - multiply by constant
xScaleEnable=xScaleEnables[i]
yScaleEnable=yScaleEnables[i]
xScale=xScales[i]
yScale=yScales[i]
if xScaleEnable:
xdata=[x*xScale for x in xdata]
xdataSmooth=[x*xScale for x in xdataSmooth]
if yScaleEnable:
ydata=[y*yScale for y in ydata]
ydataSmooth=[y*yScale for y in ydataSmooth]
if switches["-logx"]:
xdata=np.log(xdata)
if switches["-logy"]:
ydata=np.log(ydata)
if switches["-stagger"]:
m=min(ydata)
if i==0:
dely=(max(ydata)-min(ydata))/2.
ydata=[y-m+i*dely for y in ydata]
ydataSmooth=[y-m+i*dely for y in ydataSmooth]
pl.tick_params(labelleft='off')
#Plotting
#Use column labels if available
if switches["-avg"] and initAvg:
initAvg=False
avgx=xdata
avgy=np.zeros(len(ydata))
if i==0 and switches["-avg"]:
ybins = range(nbins)
mn=min(ydata)
mx=max(ydata)
if i==0 and len(label)==len(fdata):
if xCol!=-1:
pl.xlabel( label[xCol] )
pl.ylabel( label[yCol] )
if switches["-avg"]:
if len(avgy)!=len(ydata):
print "Not all data is the same length, unable to average lists of different lengths."
exit(0)
if ySmoothEnable:
avgy+=np.array(ydataSmooth)
else:
avgy+=np.array(ydata)
count+=1
elif switches["-scatter"]:
if xSmoothEnable:
xdata=xdataSmooth
if ySmoothEnable:
ydata=ydataSmooth
nPoints = int(switches["-scatter"])
pl.scatter(xdata[::nPoints],ydata[::nPoints],lw=0.1,label=fileNames[i],facecolor=vizSpec(float(i)/max((nFileNames-1),1) ))
else: #Regular plot, multiple lines
cc=vizSpec(float(i)/max(nFileNames-1,1) )
if xSmoothEnable:
xdata=xdataSmooth
if ySmoothEnable:
ydata=ydataSmooth
pl.plot(xdata,ydata,lw=1.5,c=cc,label=fileNames[i],alpha=alpha)
if switches["-avg"]:
avgy=[i/count for i in avgy]
pl.plot(avgx,avgy)
""" #Still figuring this one out...
if switches["-saveData"]:
data=label[xCol] + " " + label[yCol] + "\n"
for x,y in zip(avgx,avgy):
data+=str(x)+" "+str(y)+"\n"
open("lazy.data","w").write(data)
"""
if not switches["-noLeg"]:
pl.legend(loc=0)
pl.gca().autoscale_view(True,True,True)
if switches["-title"]:
pl.title(switches["-title"])
if switches["-xlabel"]:
pl.xlabel(switches["-xlabel"])
if switches["-ylabel"]:
pl.ylabel(switches["-ylabel"])
if switches["-saveFig"]:
pl.savefig("lazy.png")
print "Wrote file lazy.png"
else:
pr.prshow("lazy.png")
| #!/usr/bin/env python
#local
import plotRemote as pr
#standard
import re, sys, select
import pylab as pl
import numpy as np
#local
from smoothing import windowAvg,superSmooth
from colors import vizSpec
#attempts to parse a file, keeping only rows that can be converted to floats
#keeps rows with the most common number of columns.
def parse(fname,delim=None):
fraw = open(fname,"r").readlines()
data=list()
dataIndex=list()
for i,line in enumerate(fraw):
#drop lines with only newline characters
if len(line) < 2: continue
#drop comment lines
if line[0]=="#": continue
#drop lines that don't contain columns of numbers
l=line.split(delim)
f=list()
count=0
for elem in l:
try:
f.append(float(elem))
except ValueError:
count+=1
if count==len(l):
continue
data.append(f)
dataIndex.append(i)
#Keep only data with the most common number of columns
columnLengths=map(len,data)
colN=[columnLengths.count(i) for i in range(max(columnLengths)+1)]
colNi=colN.index(max(colN))
[dataNum,parsedData]=zip(*[[dataIndex[i],d] for i,d in enumerate(data) if columnLengths[i]==colNi])
parsedData=zip(*parsedData)
labels=fraw[dataNum[0]-1].split(delim)
n=len(labels)
try:
map(float,labels)
labels=[" "]*n
except:
pass
return labels,parsedData
def usage():
print "\nUsage: %s <x-data column><s><window size> <y-data column><s><window size> <filenames>"\
%sys.argv[0].split("/")[-1]
print "\nUsage: %s <x-data column><x><scale> <y-data column><x><scale> <filenames>"%sys.argv[0].split("/")[-1]
print "\nA general use plotter of 2D data. \nAttempts to find data in column format and plot the desired columns."
print "If x-data column is -1 then range(len(y)) is used"
print "If the column number is followed by an <s> then a window average is applied to that data."
print "If the column number is followed by an <x> then scaling by that value is applied"
print "examples:"
print "./plot2.py datafile "
print "./plot2.py 0 1 datafile1 datafile2 datafile3"
print "./plot2.py 0 1 datafile1 0 2 datafile2 datafile3"
print "./plot2.py 0 1s25 datafile1 #windowed average of width 25 is applied"
print "./plot2.py 0x0.5 1x2.0 datafile #scale of 0.5 on x-axis and scale of 2.0 on y-axis"
print "switches: -stagger, -sort, -avg, -scatter, -noLeg, -altSmooth, -logx, -logy, -saveFig"
print "switches with parameters: -alpha <alpha>, -title <title> -xlabel <xlabel> -ylabel <ylabel>"
print ""
if len(sys.argv)==1:
if select.select([sys.stdin,],[],[],0.0)[0]:
import fileinput
sys.argv += fileinput.input().readline().split()
if __name__=="__main__":
if len(sys.argv)<2:
usage()
exit(0)
columnIndeces=list()
fileIndeces=list()
columnFileCounter=list()
#Pre-parse for switches
nbins=80
alpha=1.0 #transparency
switches={"-stagger":False,"-sort":False,"-avg":False,"-scatter":False, "-noLeg":False, "-saveData":False, "-saveFig":False, "-altSmooth":False, "-h":False,"-alpha":None,"-logx":False,"-logy":False,"-title":False,"-xlabel":False,"-ylabel":False}
for i in range(len(sys.argv)-1,-1,-1):
if "-alpha" == sys.argv[i]: #special case alpha
switches["-alpha"]=True
sys.argv.pop(i)
alpha = float(sys.argv.pop(i))
elif "-xlabel" == sys.argv[i]:
sys.argv.pop(i)
switches["-xlabel"]=sys.argv.pop(i)
elif "-ylabel" == sys.argv[i]:
sys.argv.pop(i)
switches["-ylabel"]=sys.argv.pop(i)
elif "-title" == sys.argv[i]:
sys.argv.pop(i)
switches["-title"]=sys.argv.pop(i)
elif "-scatter" == sys.argv[i]:
sys.argv.pop(i)
switches["-scatter"]=sys.argv.pop(i)
elif sys.argv[i] in switches.keys():
switches[sys.argv[i]]=True
sys.argv.pop(i)
if switches["-h"]:
usage()
exit(0)
#Parse for column selection and file selection.
for i in range(1,len(sys.argv)):
reresult=re.search('^[-]?\d+[sx]?[-]?[\d]*\.?[\d]*$',sys.argv[i])
try:
if reresult.group(0) == sys.argv[i]:
columnIndeces.append(i)
#How many files will have these columns selected
if len(columnIndeces)%2==0:
columnFileCounter.append(0)
except AttributeError:
fileIndeces.append(i)
try:
columnFileCounter[-1]+=1
except IndexError: pass
if len(columnIndeces)!=0:
if len(columnIndeces)%2!=0 or columnIndeces[0]!=1:
usage()
print "***Error***: improperly formed column selection"
exit(0)
else:
columnFileCounter=[len(sys.argv[1:])]
xSmoothEnables=[]
ySmoothEnables=[]
xScaleEnables=[]
yScaleEnables=[]
xScales=[]
yScales=[]
xCols=[]
yCols=[]
xWANs=[]
yWANs=[]
if len(columnIndeces)==0:
for i in fileIndeces:
xCols.append(0)
yCols.append(1)
xSmoothEnables.append(False)
ySmoothEnables.append(False)
xScaleEnables.append(False)
yScaleEnables.append(False)
xWANs.append(0)
yWANs.append(0)
xScales.append(1.)
yScales.append(1.)
else:
xcs=[c for i,c in enumerate(columnIndeces) if i%2==0]
ycs=[c for i,c in enumerate(columnIndeces) if (i+1)%2==0]
for i in range(len(columnFileCounter)):
xc=sys.argv[xcs[i]]
xsc=False
xsm=False
xw=0
xscale=1.
if "s" in xc:
xsm=True
r=xc.split("s")
xc=int(r[0])
if r[1]=="":
xw=10
else:
xw=int(r[1])
elif "x" in xc:
xsc=True
r=xc.split("x")
xc=int(r[0])
if r[1]=="":
xscale=1.
else:
xscale=float(r[1])
else:
xc=int(xc)
yc=sys.argv[ycs[i]]
ysc=False
ysm=False
yw=0
yscale=1.0
if "s" in yc:
ysm=True
r=yc.split("s")
yc=int(r[0])
if r[1]=="":
yw=10
else:
yw=int(r[1])
elif "x" in yc:
ysc=True
r=yc.split("x")
yc=int(r[0])
if r[1]=="":
yscale=1.
else:
yscale=float(r[1])
else:
yc=int(yc)
for j in range(columnFileCounter[i]):
xCols.append(xc)
xSmoothEnables.append(xsm)
xWANs.append(xw)
xScaleEnables.append(xsc)
xScales.append(xscale)
yCols.append(yc)
ySmoothEnables.append(ysm)
yWANs.append(yw)
yScaleEnables.append(ysc)
yScales.append(yscale)
#Grab the file name
fileNames=[sys.argv[i] for i in fileIndeces]
nFileNames = len(fileNames)
if switches['-sort']:
#Sorting might introduce undesirable behavior so skip it
#if you're only selecting 1 column then sort the file names
if len(columnFileCounter)==1:
try:
fnamenumbers=map(lambda x:float(".".join(re.findall('\d+',x))),fileNames)
if nFileNames == len(fnamenumbers):
fileNames=zip(*sorted(zip(fileNames,fnamenumbers),key=lambda x:x[1]))[0]
except ValueError:
pass
#Initialize Average
initAvg=True
count=0.
#Colors
colors = None
#Load up the data and the label guesses
labels=list()
fdatas=list()
for fname in fileNames:
if fname[-3:]=="csv":
l,f = parse(fname,",")
else:
l,f = parse(fname)
labels.append(l)
fdatas.append(f)
print fname
label=labels[0]
fig=pl.figure()
pl.grid()
for i in range(sum(columnFileCounter)):
fdata=fdatas[i]
xCol=xCols[i]
yCol=yCols[i]
#Error check on column selection
if yCol >= len(fdata):
print "Error: Max column number is %d, but %d requested."%(len(fdata)-1,yCol)
if xCol >= len(fdata):
print "Error: Max column number is %d, but %d requested."%(len(fdata)-1,xCol)
#Column selection
ydata=fdata[yCol]
if xCol==-1:
xdata=range(len(ydata))
else:
xdata=fdata[xCol]
#Smoothing:
xSmoothEnable=xSmoothEnables[i]
ySmoothEnable=ySmoothEnables[i]
xWAN=xWANs[i]
yWAN=yWANs[i]
xdataSmooth=[]
ydataSmooth=[]
if xSmoothEnable:
if switches["-altSmooth"]:
xdataSmooth=superSmooth(xdata,ydata,xWAN/100.0)
else:
xdataSmooth=windowAvg(xdata,xWAN)
if ySmoothEnable:
if switches["-altSmooth"]:
ydataSmooth=superSmooth(xdata,ydata,yWAN/100.0)
else:
ydataSmooth=windowAvg(ydata,yWAN)
#Correct for window offset, average introduces extra points that need to be chopped off
if not switches["-altSmooth"] and xSmoothEnable or ySmoothEnable:
WAN=max(xWAN,yWAN)
xdataSmooth=xdataSmooth[WAN/2+1:WAN/-2]
ydataSmooth=ydataSmooth[WAN/2+1:WAN/-2]
xdata=xdata[WAN/2+1:WAN/-2]
ydata=ydata[WAN/2+1:WAN/-2]
#Scaling - multiply by constant
xScaleEnable=xScaleEnables[i]
yScaleEnable=yScaleEnables[i]
xScale=xScales[i]
yScale=yScales[i]
if xScaleEnable:
xdata=[x*xScale for x in xdata]
xdataSmooth=[x*xScale for x in xdataSmooth]
if yScaleEnable:
ydata=[y*yScale for y in ydata]
ydataSmooth=[y*yScale for y in ydataSmooth]
if switches["-logx"]:
xdata=np.log(xdata)
if switches["-logy"]:
ydata=np.log(ydata)
if switches["-stagger"]:
m=min(ydata)
if i==0:
dely=(max(ydata)-min(ydata))/2.
ydata=[y-m+i*dely for y in ydata]
ydataSmooth=[y-m+i*dely for y in ydataSmooth]
pl.tick_params(labelleft='off')
#Plotting
#Use column labels if available
if switches["-avg"] and initAvg:
initAvg=False
avgx=xdata
avgy=np.zeros(len(ydata))
if i==0 and switches["-avg"]:
ybins = range(nbins)
mn=min(ydata)
mx=max(ydata)
if i==0 and len(label)==len(fdata):
if xCol!=-1:
pl.xlabel( label[xCol] )
pl.ylabel( label[yCol] )
if switches["-avg"]:
if len(avgy)!=len(ydata):
print "Not all data is the same length, unable to average lists of different lengths."
exit(0)
if ySmoothEnable:
avgy+=np.array(ydataSmooth)
else:
avgy+=np.array(ydata)
count+=1
elif switches["-scatter"]:
if xSmoothEnable:
xdata=xdataSmooth
if ySmoothEnable:
ydata=ydataSmooth
nPoints = int(switches["-scatter"])
pl.scatter(xdata[::nPoints],ydata[::nPoints],lw=0.1,label=fileNames[i],facecolor=vizSpec(float(i)/max((nFileNames-1),1) ))
else: #Regular plot, multiple lines
cc=vizSpec(float(i)/max(nFileNames-1,1) )
if xSmoothEnable:
xdata=xdataSmooth
if ySmoothEnable:
ydata=ydataSmooth
pl.plot(xdata,ydata,lw=1.5,c=cc,label=fileNames[i],alpha=alpha)
if switches["-avg"]:
avgy=[i/count for i in avgy]
pl.plot(avgx,avgy)
""" #Still figuring this one out...
if switches["-saveData"]:
data=label[xCol] + " " + label[yCol] + "\n"
for x,y in zip(avgx,avgy):
data+=str(x)+" "+str(y)+"\n"
open("lazy.data","w").write(data)
"""
if not switches["-noLeg"]:
pl.legend(loc=0)
pl.gca().autoscale_view(True,True,True)
if switches["-title"]:
pl.title(switches["-title"])
if switches["-xlabel"]:
pl.xlabel(switches["-xlabel"])
if switches["-ylabel"]:
pl.ylabel(switches["-ylabel"])
if switches["-saveFig"]:
pl.savefig("lazy.png")
print "Wrote file lazy.png"
else:
pr.prshow("lazy.png")
| en | 0.785614 | #!/usr/bin/env python #local #standard #local #attempts to parse a file, keeping only rows that can be converted to floats #keeps rows with the most common number of columns. #drop lines with only newline characters #drop comment lines #drop lines that don't contain columns of numbers #Keep only data with the most common number of columns #windowed average of width 25 is applied" #scale of 0.5 on x-axis and scale of 2.0 on y-axis" #Pre-parse for switches #transparency #special case alpha #Parse for column selection and file selection. #How many files will have these columns selected #Grab the file name #Sorting might introduce undesirable behavior so skip it #if you're only selecting 1 column then sort the file names #Initialize Average #Colors #Load up the data and the label guesses #Error check on column selection #Column selection #Smoothing: #Correct for window offset, average introduces extra points that need to be chopped off #Scaling - multiply by constant #Plotting #Use column labels if available #Regular plot, multiple lines #Still figuring this one out... if switches["-saveData"]: data=label[xCol] + " " + label[yCol] + "\n" for x,y in zip(avgx,avgy): data+=str(x)+" "+str(y)+"\n" open("lazy.data","w").write(data) | 2.960048 | 3 |
variation/tokenizers/tokenize.py | cancervariants/variant-normalization | 1 | 6616065 | <reponame>cancervariants/variant-normalization
"""A module for tokenizing."""
from typing import Iterable, List
# from .amplification import Amplification
# from .deletion import Deletion
# from .exon import Exon
# from .expression import Expression
# from .fusion import Fusion
# from .gain_of_function import GainOfFunction
# from .gene_pair import GenePair
from .gene_symbol import GeneSymbol
# from .loss_of_function import LossOfFunction
# from .overexpression import OverExpression
# from .protein_alternate import ProteinAlternate
# from .protein_frameshift import ProteinFrameshift
# from .protein_termination import ProteinTermination
# from .underexpression import UnderExpression
from .amino_acid_substitution import AminoAcidSubstitution
from .polypeptide_truncation import PolypeptideTruncation
from .silent_mutation import SilentMutation
from .coding_dna_substitution import CodingDNASubstitution
from .genomic_substitution import GenomicSubstitution
from .coding_dna_silent_mutation import CodingDNASilentMutation
from .genomic_silent_mutation import GenomicSilentMutation
from .amino_acid_delins import AminoAcidDelIns
from .coding_dna_delins import CodingDNADelIns
from .genomic_delins import GenomicDelIns
# from .wild_type import WildType
from .hgvs import HGVS
from .reference_sequence import ReferenceSequence
from .locus_reference_genomic import LocusReferenceGenomic
from .amino_acid_deletion import AminoAcidDeletion
from .coding_dna_deletion import CodingDNADeletion
from .genomic_deletion import GenomicDeletion
from .amino_acid_insertion import AminoAcidInsertion
from .coding_dna_insertion import CodingDNAInsertion
from .genomic_insertion import GenomicInsertion
from .genomic_uncertain_deletion import GenomicUncertainDeletion
from .genomic_duplication import GenomicDuplication
from .genomic_deletion_range import GenomicDeletionRange
from .gnomad_vcf import GnomadVCF
from variation.schemas.token_response_schema import Token, TokenMatchType
from .caches import NucleotideCache
class Tokenize:
"""The tokenize class."""
def __init__(self, amino_acid_cache, gene_symbol: GeneSymbol) -> None:
"""Initialize the tokenize class."""
nucleotide_cache = NucleotideCache()
self.tokenizers = (
HGVS(),
ReferenceSequence(),
LocusReferenceGenomic(),
GnomadVCF(),
# Amplification(),
# Deletion(),
# Exon(),
# Expression(),
# Fusion(),
# GainOfFunction(),
# GenePair(),
gene_symbol,
# LossOfFunction(),
# OverExpression(),
# ProteinAlternate(amino_acid_cache),
# ProteinFrameshift(amino_acid_cache),
AminoAcidSubstitution(amino_acid_cache),
PolypeptideTruncation(amino_acid_cache),
SilentMutation(amino_acid_cache),
CodingDNASubstitution(),
GenomicSubstitution(),
CodingDNASilentMutation(),
GenomicSilentMutation(),
AminoAcidDelIns(amino_acid_cache, nucleotide_cache),
CodingDNADelIns(amino_acid_cache, nucleotide_cache),
GenomicDelIns(amino_acid_cache, nucleotide_cache),
AminoAcidDeletion(amino_acid_cache, nucleotide_cache),
CodingDNADeletion(amino_acid_cache, nucleotide_cache),
GenomicDeletion(amino_acid_cache, nucleotide_cache),
AminoAcidInsertion(amino_acid_cache, nucleotide_cache),
CodingDNAInsertion(amino_acid_cache, nucleotide_cache),
GenomicInsertion(amino_acid_cache, nucleotide_cache),
GenomicUncertainDeletion(),
GenomicDuplication(),
GenomicDeletionRange()
# ProteinTermination(amino_acid_cache),
# UnderExpression(),
# WildType(),
)
def perform(self, search_string: str, warnings: List[str])\
-> Iterable[Token]:
"""Return an iterable of tokens for a given search string.
:param str search_string: The input string to search on
:param list warnings: List of warnings
:return: An Iterable of Tokens
"""
tokens: List[Token] = list()
# Currently splits on whitespace
# Also adds a token if an string looks like an accession
# ex: NC_, NM_, ENST
terms = search_string.split()
self._add_tokens(tokens, terms, search_string, warnings)
return tokens
def _add_tokens(self, tokens, terms, search_string, warnings):
"""Add tokens to a list for a given search string.
:param list tokens: A list of tokens
:param str search_string: The input string to search on
:param list warnings: List of warnings
"""
for term in terms:
if not term:
continue
matched = False
for tokenizer in self.tokenizers:
res = tokenizer.match(term)
if res:
if isinstance(res, List):
for r in res:
tokens.append(r)
if not matched:
matched = True
else:
tokens.append(res)
token = list(map(lambda t: t.token_type, tokens))[0]
if token == 'HGVS' or \
token == 'LocusReferenceGenomic' \
or token == 'ReferenceSequence':
# Give specific type of HGVS (i.e. protein sub)
if len(tokens) == 1:
self._add_tokens(tokens,
[search_string.split(':')[1]],
search_string, warnings)
matched = True
break
else:
continue
if not matched:
warnings.append(f"Unable to tokenize {term}")
tokens.append(Token(
token='',
token_type='Unknown',
input_string=term,
match_type=TokenMatchType.UNSPECIFIED
))
| """A module for tokenizing."""
from typing import Iterable, List
# from .amplification import Amplification
# from .deletion import Deletion
# from .exon import Exon
# from .expression import Expression
# from .fusion import Fusion
# from .gain_of_function import GainOfFunction
# from .gene_pair import GenePair
from .gene_symbol import GeneSymbol
# from .loss_of_function import LossOfFunction
# from .overexpression import OverExpression
# from .protein_alternate import ProteinAlternate
# from .protein_frameshift import ProteinFrameshift
# from .protein_termination import ProteinTermination
# from .underexpression import UnderExpression
from .amino_acid_substitution import AminoAcidSubstitution
from .polypeptide_truncation import PolypeptideTruncation
from .silent_mutation import SilentMutation
from .coding_dna_substitution import CodingDNASubstitution
from .genomic_substitution import GenomicSubstitution
from .coding_dna_silent_mutation import CodingDNASilentMutation
from .genomic_silent_mutation import GenomicSilentMutation
from .amino_acid_delins import AminoAcidDelIns
from .coding_dna_delins import CodingDNADelIns
from .genomic_delins import GenomicDelIns
# from .wild_type import WildType
from .hgvs import HGVS
from .reference_sequence import ReferenceSequence
from .locus_reference_genomic import LocusReferenceGenomic
from .amino_acid_deletion import AminoAcidDeletion
from .coding_dna_deletion import CodingDNADeletion
from .genomic_deletion import GenomicDeletion
from .amino_acid_insertion import AminoAcidInsertion
from .coding_dna_insertion import CodingDNAInsertion
from .genomic_insertion import GenomicInsertion
from .genomic_uncertain_deletion import GenomicUncertainDeletion
from .genomic_duplication import GenomicDuplication
from .genomic_deletion_range import GenomicDeletionRange
from .gnomad_vcf import GnomadVCF
from variation.schemas.token_response_schema import Token, TokenMatchType
from .caches import NucleotideCache
class Tokenize:
"""The tokenize class."""
def __init__(self, amino_acid_cache, gene_symbol: GeneSymbol) -> None:
"""Initialize the tokenize class."""
nucleotide_cache = NucleotideCache()
self.tokenizers = (
HGVS(),
ReferenceSequence(),
LocusReferenceGenomic(),
GnomadVCF(),
# Amplification(),
# Deletion(),
# Exon(),
# Expression(),
# Fusion(),
# GainOfFunction(),
# GenePair(),
gene_symbol,
# LossOfFunction(),
# OverExpression(),
# ProteinAlternate(amino_acid_cache),
# ProteinFrameshift(amino_acid_cache),
AminoAcidSubstitution(amino_acid_cache),
PolypeptideTruncation(amino_acid_cache),
SilentMutation(amino_acid_cache),
CodingDNASubstitution(),
GenomicSubstitution(),
CodingDNASilentMutation(),
GenomicSilentMutation(),
AminoAcidDelIns(amino_acid_cache, nucleotide_cache),
CodingDNADelIns(amino_acid_cache, nucleotide_cache),
GenomicDelIns(amino_acid_cache, nucleotide_cache),
AminoAcidDeletion(amino_acid_cache, nucleotide_cache),
CodingDNADeletion(amino_acid_cache, nucleotide_cache),
GenomicDeletion(amino_acid_cache, nucleotide_cache),
AminoAcidInsertion(amino_acid_cache, nucleotide_cache),
CodingDNAInsertion(amino_acid_cache, nucleotide_cache),
GenomicInsertion(amino_acid_cache, nucleotide_cache),
GenomicUncertainDeletion(),
GenomicDuplication(),
GenomicDeletionRange()
# ProteinTermination(amino_acid_cache),
# UnderExpression(),
# WildType(),
)
def perform(self, search_string: str, warnings: List[str])\
-> Iterable[Token]:
"""Return an iterable of tokens for a given search string.
:param str search_string: The input string to search on
:param list warnings: List of warnings
:return: An Iterable of Tokens
"""
tokens: List[Token] = list()
# Currently splits on whitespace
# Also adds a token if an string looks like an accession
# ex: NC_, NM_, ENST
terms = search_string.split()
self._add_tokens(tokens, terms, search_string, warnings)
return tokens
def _add_tokens(self, tokens, terms, search_string, warnings):
"""Add tokens to a list for a given search string.
:param list tokens: A list of tokens
:param str search_string: The input string to search on
:param list warnings: List of warnings
"""
for term in terms:
if not term:
continue
matched = False
for tokenizer in self.tokenizers:
res = tokenizer.match(term)
if res:
if isinstance(res, List):
for r in res:
tokens.append(r)
if not matched:
matched = True
else:
tokens.append(res)
token = list(map(lambda t: t.token_type, tokens))[0]
if token == 'HGVS' or \
token == 'LocusReferenceGenomic' \
or token == 'ReferenceSequence':
# Give specific type of HGVS (i.e. protein sub)
if len(tokens) == 1:
self._add_tokens(tokens,
[search_string.split(':')[1]],
search_string, warnings)
matched = True
break
else:
continue
if not matched:
warnings.append(f"Unable to tokenize {term}")
tokens.append(Token(
token='',
token_type='Unknown',
input_string=term,
match_type=TokenMatchType.UNSPECIFIED
)) | en | 0.434631 | A module for tokenizing. # from .amplification import Amplification # from .deletion import Deletion # from .exon import Exon # from .expression import Expression # from .fusion import Fusion # from .gain_of_function import GainOfFunction # from .gene_pair import GenePair # from .loss_of_function import LossOfFunction # from .overexpression import OverExpression # from .protein_alternate import ProteinAlternate # from .protein_frameshift import ProteinFrameshift # from .protein_termination import ProteinTermination # from .underexpression import UnderExpression # from .wild_type import WildType The tokenize class. Initialize the tokenize class. # Amplification(), # Deletion(), # Exon(), # Expression(), # Fusion(), # GainOfFunction(), # GenePair(), # LossOfFunction(), # OverExpression(), # ProteinAlternate(amino_acid_cache), # ProteinFrameshift(amino_acid_cache), # ProteinTermination(amino_acid_cache), # UnderExpression(), # WildType(), Return an iterable of tokens for a given search string. :param str search_string: The input string to search on :param list warnings: List of warnings :return: An Iterable of Tokens # Currently splits on whitespace # Also adds a token if an string looks like an accession # ex: NC_, NM_, ENST Add tokens to a list for a given search string. :param list tokens: A list of tokens :param str search_string: The input string to search on :param list warnings: List of warnings # Give specific type of HGVS (i.e. protein sub) | 1.794795 | 2 |
qt-libs/quazip/quazip.py | Inokinoki/craft-blueprints-kde | 0 | 6616066 | <reponame>Inokinoki/craft-blueprints-kde
# -*- coding: utf-8 -*-
import info
from Package.CMakePackageBase import *
class subinfo(info.infoclass):
def setDependencies(self):
self.runtimeDependencies["libs/qt5/qtbase"] = None
def setTargets(self):
self.svnTargets['svnHEAD'] = 'https://quazip.svn.sourceforge.net/svnroot/quazip/trunk/quazip'
self.patchToApply['svnHEAD'] = ('quazip-20160511.patch', 1)
self.targets['0.4.4'] = 'http://heanet.dl.sourceforge.net/project/quazip/quazip/0.4.4/quazip-0.4.4.zip'
self.targetDigests['0.4.4'] = 'cfc5ca35ff157e77328fc55de40b73591f425592'
self.targetInstSrc['0.4.4'] = 'quazip-0.4.4'
self.patchToApply['0.4.4'] = ('quazip-0.4.4.diff', 1)
self.defaultTarget = 'svnHEAD'
class Package(CMakePackageBase):
def __init__(self, **args):
CMakePackageBase.__init__(self)
| # -*- coding: utf-8 -*-
import info
from Package.CMakePackageBase import *
class subinfo(info.infoclass):
def setDependencies(self):
self.runtimeDependencies["libs/qt5/qtbase"] = None
def setTargets(self):
self.svnTargets['svnHEAD'] = 'https://quazip.svn.sourceforge.net/svnroot/quazip/trunk/quazip'
self.patchToApply['svnHEAD'] = ('quazip-20160511.patch', 1)
self.targets['0.4.4'] = 'http://heanet.dl.sourceforge.net/project/quazip/quazip/0.4.4/quazip-0.4.4.zip'
self.targetDigests['0.4.4'] = 'cfc5ca35ff157e77328fc55de40b73591f425592'
self.targetInstSrc['0.4.4'] = 'quazip-0.4.4'
self.patchToApply['0.4.4'] = ('quazip-0.4.4.diff', 1)
self.defaultTarget = 'svnHEAD'
class Package(CMakePackageBase):
def __init__(self, **args):
CMakePackageBase.__init__(self) | en | 0.769321 | # -*- coding: utf-8 -*- | 1.877879 | 2 |
Etap 3/Logia17/Zad2.py | aszokalski/Logia | 0 | 6616067 | def abc(slowo):
kolejnosc = "ncz"
grupy = [[]]
#dzielimy słowo na grupy takich samych liter z pominięciem liter nieistotnych
for l in slowo:
if l not in kolejnosc:
continue
if not grupy[-1] or grupy[-1][-1] == l:
grupy[-1].append(l)
else:
grupy.append([l])
#tworzymy listy przechowujące dane o długości danej grupy i kolejności jej litery w słowie "ncz"
kol = []
dlug = []
wynik = 0
for i in range(len(grupy)):
grupa = grupy[i]
kol.append(kolejnosc.index(grupa[0]))
dlug.append(len(grupa))
if i > 0:
j = i - 1
#Szukamy poprzedniej grupy wykluczjąc grupy puste
while not kol[j]:
j -= 1
#Jeśli poprzednia grupa ma większą kolejność (składa się z liter występujących pózniej w słowie "ncz")
if kol[j] > kol[i]:
#Porównujemy długości obecnej i poprzedniej grupy. Jeśli grupa poprzednia jest mniejsza lub równa - usuwamy ją,
#a jeśli obecna jest mniejsza - usuwamy obecną.
if dlug[j] <= dlug[i]:
grupy[j] = []
wynik += dlug[j]
else:
grupy[i] = []
wynik += dlug[i]
return wynik
| def abc(slowo):
kolejnosc = "ncz"
grupy = [[]]
#dzielimy słowo na grupy takich samych liter z pominięciem liter nieistotnych
for l in slowo:
if l not in kolejnosc:
continue
if not grupy[-1] or grupy[-1][-1] == l:
grupy[-1].append(l)
else:
grupy.append([l])
#tworzymy listy przechowujące dane o długości danej grupy i kolejności jej litery w słowie "ncz"
kol = []
dlug = []
wynik = 0
for i in range(len(grupy)):
grupa = grupy[i]
kol.append(kolejnosc.index(grupa[0]))
dlug.append(len(grupa))
if i > 0:
j = i - 1
#Szukamy poprzedniej grupy wykluczjąc grupy puste
while not kol[j]:
j -= 1
#Jeśli poprzednia grupa ma większą kolejność (składa się z liter występujących pózniej w słowie "ncz")
if kol[j] > kol[i]:
#Porównujemy długości obecnej i poprzedniej grupy. Jeśli grupa poprzednia jest mniejsza lub równa - usuwamy ją,
#a jeśli obecna jest mniejsza - usuwamy obecną.
if dlug[j] <= dlug[i]:
grupy[j] = []
wynik += dlug[j]
else:
grupy[i] = []
wynik += dlug[i]
return wynik
| pl | 1.000027 | #dzielimy słowo na grupy takich samych liter z pominięciem liter nieistotnych #tworzymy listy przechowujące dane o długości danej grupy i kolejności jej litery w słowie "ncz" #Szukamy poprzedniej grupy wykluczjąc grupy puste #Jeśli poprzednia grupa ma większą kolejność (składa się z liter występujących pózniej w słowie "ncz") #Porównujemy długości obecnej i poprzedniej grupy. Jeśli grupa poprzednia jest mniejsza lub równa - usuwamy ją, #a jeśli obecna jest mniejsza - usuwamy obecną. | 3.222194 | 3 |
api/models.py | rphbc/covidapi | 0 | 6616068 | <filename>api/models.py<gh_stars>0
from django.db import models
class BaseClass(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class ConfirmedData(BaseClass):
timestamp = models.DateTimeField()
country = models.CharField(max_length=100)
count = models.IntegerField(default=0.0)
def __str__(self):
return f'{self.country} - {self.count}'
class Meta:
indexes = [
models.Index(fields=['timestamp'])
]
class DeadData(BaseClass):
timestamp = models.DateTimeField()
country = models.CharField(max_length=100)
count = models.IntegerField(default=0.0)
def __str__(self):
return f'{self.country} - {self.count}'
class Meta:
indexes = [
models.Index(fields=['timestamp'])
]
class RecoveredData(BaseClass):
timestamp = models.DateTimeField()
country = models.CharField(max_length=100)
count = models.IntegerField(default=0.0)
def __str__(self):
return f'{self.country} - {self.count}'
class Meta:
indexes = [
models.Index(fields=['timestamp'])
]
class CovidData(BaseClass):
timestamp = models.DateTimeField()
country = models.CharField(max_length=50)
state = models.CharField(max_length=50)
city = models.CharField(max_length=50)
ibge_id = models.CharField(max_length=50)
new_deaths = models.IntegerField(default=None, null=True, blank=True)
deaths = models.IntegerField(default=None, null=True, blank=True)
new_cases = models.IntegerField(default=None, null=True, blank=True)
total_cases = models.IntegerField(default=None, null=True, blank=True)
new_recovered = models.IntegerField(default=None, null=True, blank=True)
recovered = models.IntegerField(default=None, null=True, blank=True)
class Meta:
indexes = [
models.Index(fields=['timestamp'])
]
class ImportsUpdate(BaseClass):
endpoint = models.CharField(max_length=1024)
columns = models.CharField(max_length=1200)
rows_count = models.IntegerField(default=None, null=True, blank=True)
cols_count = models.IntegerField(default=None, null=True, blank=True)
total_import_time = models.FloatField(default=None, null=True, blank=True)
class Meta:
indexes = [
models.Index(fields=['created_at'])
]
| <filename>api/models.py<gh_stars>0
from django.db import models
class BaseClass(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class ConfirmedData(BaseClass):
timestamp = models.DateTimeField()
country = models.CharField(max_length=100)
count = models.IntegerField(default=0.0)
def __str__(self):
return f'{self.country} - {self.count}'
class Meta:
indexes = [
models.Index(fields=['timestamp'])
]
class DeadData(BaseClass):
timestamp = models.DateTimeField()
country = models.CharField(max_length=100)
count = models.IntegerField(default=0.0)
def __str__(self):
return f'{self.country} - {self.count}'
class Meta:
indexes = [
models.Index(fields=['timestamp'])
]
class RecoveredData(BaseClass):
timestamp = models.DateTimeField()
country = models.CharField(max_length=100)
count = models.IntegerField(default=0.0)
def __str__(self):
return f'{self.country} - {self.count}'
class Meta:
indexes = [
models.Index(fields=['timestamp'])
]
class CovidData(BaseClass):
timestamp = models.DateTimeField()
country = models.CharField(max_length=50)
state = models.CharField(max_length=50)
city = models.CharField(max_length=50)
ibge_id = models.CharField(max_length=50)
new_deaths = models.IntegerField(default=None, null=True, blank=True)
deaths = models.IntegerField(default=None, null=True, blank=True)
new_cases = models.IntegerField(default=None, null=True, blank=True)
total_cases = models.IntegerField(default=None, null=True, blank=True)
new_recovered = models.IntegerField(default=None, null=True, blank=True)
recovered = models.IntegerField(default=None, null=True, blank=True)
class Meta:
indexes = [
models.Index(fields=['timestamp'])
]
class ImportsUpdate(BaseClass):
endpoint = models.CharField(max_length=1024)
columns = models.CharField(max_length=1200)
rows_count = models.IntegerField(default=None, null=True, blank=True)
cols_count = models.IntegerField(default=None, null=True, blank=True)
total_import_time = models.FloatField(default=None, null=True, blank=True)
class Meta:
indexes = [
models.Index(fields=['created_at'])
]
| none | 1 | 2.22026 | 2 | |
Dragon/python/dragon/operators/activation.py | awesome-archive/Dragon | 0 | 6616069 | # ------------------------------------------------------------
# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
#
# Licensed under the BSD 2-Clause License.
# You should have received a copy of the BSD 2-Clause License
# along with the software. If not, See,
#
# <https://opensource.org/licenses/BSD-2-Clause>
#
# ------------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from . import *
@OpSchema.Inputs(1)
def Relu(inputs, **kwargs):
"""Rectified Linear Unit function. `[Nair & Hinton, 2010] <http://www.csri.utoronto.ca/~hinton/absps/reluICML.pdf>`_.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
Returns
-------
Tensor
The output tensor, calculated as: |relu_function|.
"""
return Tensor.CreateOperator('Relu', **ParseArgs(locals()))
@OpSchema.Inputs(1)
def LRelu(inputs, slope=0.2, **kwargs):
"""Leaky Rectified Linear Unit function.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
slope : float
The slope of negative side.
Returns
-------
Tensor
The output tensor, calculated as: |lrelu_function|.
"""
return Tensor.CreateOperator('Relu', **ParseArgs(locals()))
@OpSchema.Inputs(2)
def PRelu(inputs, channel_shared=False, data_format='NCHW', **kwargs):
"""Parametric Rectified Linear Unit function. `[He et.al, 2015] <https://arxiv.org/abs/1502.01852>`_.
**Type Constraints**: *float32*
Parameters
----------
inputs : sequence of Tensor
The input and trainable parameter(slope).
channel_shared : bool
Whether to share the parameter(slope) across channels.
data_format : str
The data format, ``NCHW`` or ``NHWC``.
Returns
-------
Tensor
The output tensor, calculated as: |prelu_function|
"""
return Tensor.CreateOperator('PRelu', **ParseArgs(locals()))
@OpSchema.Inputs(1)
def Elu(inputs, alpha=1.0, **kwargs):
"""Exponential Linear Unit function. `[Clevert et.al, 2015] <https://arxiv.org/abs/1511.07289>`_.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
alpha : float
The alpha.
Returns
-------
Tensor
The output tensor, calculated as: |elu_function|
"""
return Tensor.CreateOperator('Elu', **ParseArgs(locals()))
@OpSchema.Inputs(1)
def SElu(inputs, **kwargs):
"""Scaled Exponential Linear Unit function. `[Klambauer et.al, 2017] <https://arxiv.org/abs/1706.02515>`_.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
Returns
-------
Tensor
The output tensor, calculated as: |selu_function|
"""
return Tensor.CreateOperator('SElu', **ParseArgs(locals()))
@OpSchema.Inputs(1)
def Sigmoid(inputs, **kwargs):
"""Sigmoid function.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
Returns
-------
Tensor
The output tensor, calculated as: |sigmoid_function|.
"""
return Tensor.CreateOperator('Sigmoid', **ParseArgs(locals()))
@OpSchema.Inputs(1)
def Tanh(inputs, **kwargs):
"""Tanh function.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
Returns
-------
Tensor
The output tensor, calculated as: |tanh_function|.
"""
return Tensor.CreateOperator('Tanh', **ParseArgs(locals()))
@OpSchema.Inputs(1)
@ArgumentHelper.Desc('prob', as_target=False)
def Dropout(inputs, prob=0.5, scale=True, **kwargs):
"""Randomly set a unit into zero. `[Srivastava et.al, 2014] <http://jmlr.org/papers/v15/srivastava14a.html>`_.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
prob : float or Tensor
The prob of dropping. Default is ``0.5``.
scale : bool
Whether to scale the output during training.
Returns
-------
Tensor
The output tensor, calculated as: |dropout_function|.
"""
return Tensor.CreateOperator('Dropout', **ParseArgs(locals()))
@OpSchema.Inputs(1)
def Softmax(inputs, axis=1, **kwargs):
"""Softmax function.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
axis : int
The axis to apply softmax, can be negative.
Returns
-------
Tensor
The output tensor, calculated as: |softmax_function|.
"""
return Tensor.CreateOperator('Softmax', **ParseArgs(locals())) | # ------------------------------------------------------------
# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
#
# Licensed under the BSD 2-Clause License.
# You should have received a copy of the BSD 2-Clause License
# along with the software. If not, See,
#
# <https://opensource.org/licenses/BSD-2-Clause>
#
# ------------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from . import *
@OpSchema.Inputs(1)
def Relu(inputs, **kwargs):
"""Rectified Linear Unit function. `[Nair & Hinton, 2010] <http://www.csri.utoronto.ca/~hinton/absps/reluICML.pdf>`_.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
Returns
-------
Tensor
The output tensor, calculated as: |relu_function|.
"""
return Tensor.CreateOperator('Relu', **ParseArgs(locals()))
@OpSchema.Inputs(1)
def LRelu(inputs, slope=0.2, **kwargs):
"""Leaky Rectified Linear Unit function.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
slope : float
The slope of negative side.
Returns
-------
Tensor
The output tensor, calculated as: |lrelu_function|.
"""
return Tensor.CreateOperator('Relu', **ParseArgs(locals()))
@OpSchema.Inputs(2)
def PRelu(inputs, channel_shared=False, data_format='NCHW', **kwargs):
"""Parametric Rectified Linear Unit function. `[He et.al, 2015] <https://arxiv.org/abs/1502.01852>`_.
**Type Constraints**: *float32*
Parameters
----------
inputs : sequence of Tensor
The input and trainable parameter(slope).
channel_shared : bool
Whether to share the parameter(slope) across channels.
data_format : str
The data format, ``NCHW`` or ``NHWC``.
Returns
-------
Tensor
The output tensor, calculated as: |prelu_function|
"""
return Tensor.CreateOperator('PRelu', **ParseArgs(locals()))
@OpSchema.Inputs(1)
def Elu(inputs, alpha=1.0, **kwargs):
"""Exponential Linear Unit function. `[Clevert et.al, 2015] <https://arxiv.org/abs/1511.07289>`_.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
alpha : float
The alpha.
Returns
-------
Tensor
The output tensor, calculated as: |elu_function|
"""
return Tensor.CreateOperator('Elu', **ParseArgs(locals()))
@OpSchema.Inputs(1)
def SElu(inputs, **kwargs):
"""Scaled Exponential Linear Unit function. `[Klambauer et.al, 2017] <https://arxiv.org/abs/1706.02515>`_.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
Returns
-------
Tensor
The output tensor, calculated as: |selu_function|
"""
return Tensor.CreateOperator('SElu', **ParseArgs(locals()))
@OpSchema.Inputs(1)
def Sigmoid(inputs, **kwargs):
"""Sigmoid function.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
Returns
-------
Tensor
The output tensor, calculated as: |sigmoid_function|.
"""
return Tensor.CreateOperator('Sigmoid', **ParseArgs(locals()))
@OpSchema.Inputs(1)
def Tanh(inputs, **kwargs):
"""Tanh function.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
Returns
-------
Tensor
The output tensor, calculated as: |tanh_function|.
"""
return Tensor.CreateOperator('Tanh', **ParseArgs(locals()))
@OpSchema.Inputs(1)
@ArgumentHelper.Desc('prob', as_target=False)
def Dropout(inputs, prob=0.5, scale=True, **kwargs):
"""Randomly set a unit into zero. `[Srivastava et.al, 2014] <http://jmlr.org/papers/v15/srivastava14a.html>`_.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
prob : float or Tensor
The prob of dropping. Default is ``0.5``.
scale : bool
Whether to scale the output during training.
Returns
-------
Tensor
The output tensor, calculated as: |dropout_function|.
"""
return Tensor.CreateOperator('Dropout', **ParseArgs(locals()))
@OpSchema.Inputs(1)
def Softmax(inputs, axis=1, **kwargs):
"""Softmax function.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : Tensor
The input tensor.
axis : int
The axis to apply softmax, can be negative.
Returns
-------
Tensor
The output tensor, calculated as: |softmax_function|.
"""
return Tensor.CreateOperator('Softmax', **ParseArgs(locals())) | en | 0.436006 | # ------------------------------------------------------------ # Copyright (c) 2017-present, SeetaTech, Co.,Ltd. # # Licensed under the BSD 2-Clause License. # You should have received a copy of the BSD 2-Clause License # along with the software. If not, See, # # <https://opensource.org/licenses/BSD-2-Clause> # # ------------------------------------------------------------ Rectified Linear Unit function. `[Nair & Hinton, 2010] <http://www.csri.utoronto.ca/~hinton/absps/reluICML.pdf>`_. **Type Constraints**: (*float16*, *float32*) Parameters ---------- inputs : Tensor The input tensor. Returns ------- Tensor The output tensor, calculated as: |relu_function|. Leaky Rectified Linear Unit function. **Type Constraints**: (*float16*, *float32*) Parameters ---------- inputs : Tensor The input tensor. slope : float The slope of negative side. Returns ------- Tensor The output tensor, calculated as: |lrelu_function|. Parametric Rectified Linear Unit function. `[He et.al, 2015] <https://arxiv.org/abs/1502.01852>`_. **Type Constraints**: *float32* Parameters ---------- inputs : sequence of Tensor The input and trainable parameter(slope). channel_shared : bool Whether to share the parameter(slope) across channels. data_format : str The data format, ``NCHW`` or ``NHWC``. Returns ------- Tensor The output tensor, calculated as: |prelu_function| Exponential Linear Unit function. `[Clevert et.al, 2015] <https://arxiv.org/abs/1511.07289>`_. **Type Constraints**: (*float16*, *float32*) Parameters ---------- inputs : Tensor The input tensor. alpha : float The alpha. Returns ------- Tensor The output tensor, calculated as: |elu_function| Scaled Exponential Linear Unit function. `[Klambauer et.al, 2017] <https://arxiv.org/abs/1706.02515>`_. **Type Constraints**: (*float16*, *float32*) Parameters ---------- inputs : Tensor The input tensor. Returns ------- Tensor The output tensor, calculated as: |selu_function| Sigmoid function. **Type Constraints**: (*float16*, *float32*) Parameters ---------- inputs : Tensor The input tensor. Returns ------- Tensor The output tensor, calculated as: |sigmoid_function|. Tanh function. **Type Constraints**: (*float16*, *float32*) Parameters ---------- inputs : Tensor The input tensor. Returns ------- Tensor The output tensor, calculated as: |tanh_function|. Randomly set a unit into zero. `[Srivastava et.al, 2014] <http://jmlr.org/papers/v15/srivastava14a.html>`_. **Type Constraints**: (*float16*, *float32*) Parameters ---------- inputs : Tensor The input tensor. prob : float or Tensor The prob of dropping. Default is ``0.5``. scale : bool Whether to scale the output during training. Returns ------- Tensor The output tensor, calculated as: |dropout_function|. Softmax function. **Type Constraints**: (*float16*, *float32*) Parameters ---------- inputs : Tensor The input tensor. axis : int The axis to apply softmax, can be negative. Returns ------- Tensor The output tensor, calculated as: |softmax_function|. | 2.38408 | 2 |
telnet_conn.py | jmerrell93/pynet_work | 0 | 6616070 |
import telnetlib
import time
from snmp_helper import snmp_get_oid,snmp_extract
TELNET_TIMEOUT = 6
TELNET_PORT = 23
COMMUNITY = 'galileo'
SNMP_PORT = 161
username = 'pyclass'
password = '<PASSWORD>'
OID_NAME = dict()
OID_NAME['1.3.6.1.2.1.1.1.0'] = 'DEVICE DESCRIPTION'
OID_NAME['1.3.6.1.2.1.1.5.0'] = 'DEVICE NAME'
def connect_and_query(ip_address):
remote_conn = telnetlib.Telnet(ip_address, TELNET_PORT, TELNET_TIMEOUT)
remote_conn.write(username + '\n')
time.sleep(1)
remote_conn.write(password + '\n')
remote_conn.write("terminal length 0" + '\n')
time.sleep(1)
output = remote_conn.read_very_eager()
print output
snmp_query('1.3.6.1.2.1.1.1.0', ip_address)
snmp_query('1.3.6.1.2.1.1.5.0', ip_address)
def snmp_query(OID, ip_address):
device = (ip_address, COMMUNITY, SNMP_PORT)
snmp_get = snmp_get_oid(device, OID)
output = snmp_extract(snmp_get)
print "\nFOR DEVICE %s" %ip_address
print OID_NAME[OID]
print output + '\n'
connect_and_query('172.16.58.3')
connect_and_query('192.168.127.12')
|
import telnetlib
import time
from snmp_helper import snmp_get_oid,snmp_extract
TELNET_TIMEOUT = 6
TELNET_PORT = 23
COMMUNITY = 'galileo'
SNMP_PORT = 161
username = 'pyclass'
password = '<PASSWORD>'
OID_NAME = dict()
OID_NAME['1.3.6.1.2.1.1.1.0'] = 'DEVICE DESCRIPTION'
OID_NAME['1.3.6.1.2.1.1.5.0'] = 'DEVICE NAME'
def connect_and_query(ip_address):
remote_conn = telnetlib.Telnet(ip_address, TELNET_PORT, TELNET_TIMEOUT)
remote_conn.write(username + '\n')
time.sleep(1)
remote_conn.write(password + '\n')
remote_conn.write("terminal length 0" + '\n')
time.sleep(1)
output = remote_conn.read_very_eager()
print output
snmp_query('1.3.6.1.2.1.1.1.0', ip_address)
snmp_query('1.3.6.1.2.1.1.5.0', ip_address)
def snmp_query(OID, ip_address):
device = (ip_address, COMMUNITY, SNMP_PORT)
snmp_get = snmp_get_oid(device, OID)
output = snmp_extract(snmp_get)
print "\nFOR DEVICE %s" %ip_address
print OID_NAME[OID]
print output + '\n'
connect_and_query('172.16.58.3')
connect_and_query('192.168.127.12')
| none | 1 | 2.432505 | 2 | |
userapp/app.py | lidaoduo7/Tornado4learning | 0 | 6616071 | # -*- coding: utf-8 -*-
'''
使用Tornado构建RESTful微服务
'''
import tornado.web
from userapp.handlers import user as user_handlers
HANDLEERS = [
(r"/api/users", user_handlers.UserListHandler),
(r"/api/users/(\d+)", user_handlers.UserHandler), #正则匹配
]
def run():
app = tornado.web.Application(
HANDLEERS,
debug=True, #方便自动重启做验证
)
http_server = tornado.httpserver.HTTPServer(app) # http://localhost:8888/api/users
port = 8888
http_server.listen(port)
print('server start on port: {}'.format(port))
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
run() | # -*- coding: utf-8 -*-
'''
使用Tornado构建RESTful微服务
'''
import tornado.web
from userapp.handlers import user as user_handlers
HANDLEERS = [
(r"/api/users", user_handlers.UserListHandler),
(r"/api/users/(\d+)", user_handlers.UserHandler), #正则匹配
]
def run():
app = tornado.web.Application(
HANDLEERS,
debug=True, #方便自动重启做验证
)
http_server = tornado.httpserver.HTTPServer(app) # http://localhost:8888/api/users
port = 8888
http_server.listen(port)
print('server start on port: {}'.format(port))
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
run() | zh | 0.42099 | # -*- coding: utf-8 -*- 使用Tornado构建RESTful微服务 #正则匹配 #方便自动重启做验证 # http://localhost:8888/api/users | 2.85533 | 3 |
app/src/main/python/kabu_pre4.py | susumOyaji/chaquopy-matplotlib-master | 0 | 6616072 | from sklearn import datasets
from sklearn.model_selection import train_test_split
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# x(入力)のユニット数は4
self.fc1 = nn.Linear(4, 10)
# 隠れ層1のユニット数は10
self.fc2 = nn.Linear(10, 10)
# 隠れ層2のユニット数は10
self.fc3 = nn.Linear(10, 3)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.log_softmax(self.fc3(x),dim=1)
return x
#データ集めがめんどくさいので、今回はsklearnにあるirisのデータセットを使います。
iris = datasets.load_iris()
#データを「訓練データ」と「評価データ」に分けておきます。この辺の処理は他の機械学習手法でもお馴染みですね。
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.25 ,random_state=0)
#次に、pytorchで扱えるように、tensor(テンソル)と呼ばれる行列のようなものに変換します。(実際には行列とは少し異なりますが、今回の主題ではないのでスルーします)
x = torch.tensor(X_train,dtype = torch.float32)
y = torch.tensor(y_train,dtype = torch.long)
# 学習モデルのインスタンスを作成
model = Net()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# 損失関数の定義
criterion = nn.CrossEntropyLoss()
sum_loss = 0.0
epoch = 5000#エポック数(学習回数)は5000回
for i in range(1,epoch):
# 勾配の初期化
optimizer.zero_grad()
# 説明変数xをネットワークにかける
output = model(x)
# 損失関数の計算
loss = criterion(output, y)
# 勾配の計算
loss.backward()
# パラメタの更新
optimizer.step()
sum_loss += loss.item()
if i % 1000 == 0:
print("loss : {0}".format(sum_loss/i))
outputs = model(torch.tensor(X_test, dtype = torch.float))
_, predicted = torch.max(outputs.data, 1)
y_predicted = predicted.numpy()
accuracy = 100 * np.sum(predicted.numpy() == y_test) / len(y_predicted)
print('accuracy: {:.1f}%'.format(accuracy)) | from sklearn import datasets
from sklearn.model_selection import train_test_split
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# x(入力)のユニット数は4
self.fc1 = nn.Linear(4, 10)
# 隠れ層1のユニット数は10
self.fc2 = nn.Linear(10, 10)
# 隠れ層2のユニット数は10
self.fc3 = nn.Linear(10, 3)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.log_softmax(self.fc3(x),dim=1)
return x
#データ集めがめんどくさいので、今回はsklearnにあるirisのデータセットを使います。
iris = datasets.load_iris()
#データを「訓練データ」と「評価データ」に分けておきます。この辺の処理は他の機械学習手法でもお馴染みですね。
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.25 ,random_state=0)
#次に、pytorchで扱えるように、tensor(テンソル)と呼ばれる行列のようなものに変換します。(実際には行列とは少し異なりますが、今回の主題ではないのでスルーします)
x = torch.tensor(X_train,dtype = torch.float32)
y = torch.tensor(y_train,dtype = torch.long)
# 学習モデルのインスタンスを作成
model = Net()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# 損失関数の定義
criterion = nn.CrossEntropyLoss()
sum_loss = 0.0
epoch = 5000#エポック数(学習回数)は5000回
for i in range(1,epoch):
# 勾配の初期化
optimizer.zero_grad()
# 説明変数xをネットワークにかける
output = model(x)
# 損失関数の計算
loss = criterion(output, y)
# 勾配の計算
loss.backward()
# パラメタの更新
optimizer.step()
sum_loss += loss.item()
if i % 1000 == 0:
print("loss : {0}".format(sum_loss/i))
outputs = model(torch.tensor(X_test, dtype = torch.float))
_, predicted = torch.max(outputs.data, 1)
y_predicted = predicted.numpy()
accuracy = 100 * np.sum(predicted.numpy() == y_test) / len(y_predicted)
print('accuracy: {:.1f}%'.format(accuracy)) | ja | 0.999451 | # x(入力)のユニット数は4 # 隠れ層1のユニット数は10 # 隠れ層2のユニット数は10 #データ集めがめんどくさいので、今回はsklearnにあるirisのデータセットを使います。 #データを「訓練データ」と「評価データ」に分けておきます。この辺の処理は他の機械学習手法でもお馴染みですね。 #次に、pytorchで扱えるように、tensor(テンソル)と呼ばれる行列のようなものに変換します。(実際には行列とは少し異なりますが、今回の主題ではないのでスルーします) # 学習モデルのインスタンスを作成 # 損失関数の定義 #エポック数(学習回数)は5000回 # 勾配の初期化 # 説明変数xをネットワークにかける # 損失関数の計算 # 勾配の計算 # パラメタの更新 | 3.17767 | 3 |
noweats/en.py | blr246/noweats | 1 | 6616073 | """
Model of English language.
"""
from noweats.extraction import allowed_chars_no_whitespace, \
sentence_split_clean_data
from noweats.util import counter
from nltk import word_tokenize
import math
import itertools as its
def word_to_bag(word):
""" Convert word to bag-of-chars. """
return ''.join(sorted(set(word)))
def make_en_prefix_suffix_model(model):
""" Create a function that scores English words. """
log_tform = lambda m: {k: math.log(v) for k, v in m.iteritems()}
prefixes, suffixes, bags = model
prefixes = log_tform(prefixes)
suffixes = log_tform(suffixes)
bags = log_tform(bags)
alphabet = allowed_chars_no_whitespace()
actual_alphabet = set(char for key in
its.chain(prefixes.iterkeys(),
suffixes.iterkeys(),
bags.iterkeys())
for char in key)
if len(actual_alphabet) > len(alphabet):
print "unexpected chars in alphabet {}".format(
actual_alphabet - alphabet)
alphabet = alphabet.union(actual_alphabet)
num_chars = len(alphabet)
tuple_len = max(its.chain(prefixes.iterkeys(), suffixes.iterkeys()), key=len)
# Tuples can lead or end with null chars but must have at least 1 non-null.
possible_tuples = (num_chars + 1)**(tuple_len - 1) * num_chars
# Exclude the empty bag.
possible_bags = 2**num_chars - 1
norm_prefix = -math.log(sum(prefixes.itervalues()) + possible_tuples)
norm_suffix = -math.log(sum(suffixes.itervalues()) + possible_tuples)
norm_bag = -math.log(sum(bags.itervalues()) + possible_bags)
def p_word(word):
""" Compute probability of a word under the model. """
word_lower = word.lower()
prefix, suffix = word_lower[:tuple_len], word_lower[-tuple_len:]
bag = word_to_bag(word)
ll_prefix = prefixes[prefix] if prefix in prefixes else 1
ll_suffix = suffixes[suffix] if suffix in suffixes else 1
ll_bag = bags[bag] if bag in bags else 1
return ll_prefix + norm_prefix \
+ ll_suffix + norm_suffix \
+ ll_bag + norm_bag
return p_word
def expectation_en_tweet(tweet, p_word, is_lower=False):
"""
Compute expected probability that a tweet is English.
"""
return math.log(sum(math.exp(expectation_en_sentence(s, p_word, is_lower))
for s in tweet) / len(tweet))
def expectation_en_sentence(sentence, p_word, is_lower=False):
"""
Compute expected probability that a word from the sentence is English.
"""
if is_lower is True:
scorer = p_word
else:
scorer = lambda w: p_word(w.lower())
if isinstance(sentence, str):
sentence = sentence.split()
return math.log(sum(math.exp(scorer(w)) for w in sentence) / len(sentence))
def likelihood_en_tweet(tweet, p_word, is_lower=False):
"""
Compute likelihood that a tweet is English.
"""
return sum(likelihood_en_sentence(s, p_word, is_lower)
for s in tweet) / len(tweet)
def likelihood_en_sentence(sentence, p_word, is_lower=False):
"""
Compute likelihood that a word from the sentence is English.
"""
if is_lower is True:
scorer = p_word
else:
scorer = lambda w: p_word(w.lower())
if isinstance(sentence, str):
sentence = sentence.split()
return sum(scorer(w) for w in sentence)
def build_en_prefix_suffix_model(data_json):
"""
Create a probabilisitc model of English words from data.
Features:
3-prefixes, 3-suffixes, bag-of-chars model.
For the 3-prefixes and 3-suffixes, there are |chars|(|chars| + 1)^2
possible observations. For the bag-of-chars, there are 2^|chars| possible
bags.
During inference, we want to avoid the partition function (i.e. all
sentences with 3 words). Therefore, we compute the expectation that a word
in the sentence is English and threshold that.
"""
all_tweets = sentence_split_clean_data(data_json, [''])
toks = [t.lower() for tw in all_tweets
for s in tw
for t in word_tokenize(s)]
prefixes = counter(t[:3] for t in toks)
suffixes = counter(t[-3:] for t in toks)
bags = counter(word_to_bag(t) for t in toks)
return [prefixes, suffixes, bags]
| """
Model of English language.
"""
from noweats.extraction import allowed_chars_no_whitespace, \
sentence_split_clean_data
from noweats.util import counter
from nltk import word_tokenize
import math
import itertools as its
def word_to_bag(word):
""" Convert word to bag-of-chars. """
return ''.join(sorted(set(word)))
def make_en_prefix_suffix_model(model):
""" Create a function that scores English words. """
log_tform = lambda m: {k: math.log(v) for k, v in m.iteritems()}
prefixes, suffixes, bags = model
prefixes = log_tform(prefixes)
suffixes = log_tform(suffixes)
bags = log_tform(bags)
alphabet = allowed_chars_no_whitespace()
actual_alphabet = set(char for key in
its.chain(prefixes.iterkeys(),
suffixes.iterkeys(),
bags.iterkeys())
for char in key)
if len(actual_alphabet) > len(alphabet):
print "unexpected chars in alphabet {}".format(
actual_alphabet - alphabet)
alphabet = alphabet.union(actual_alphabet)
num_chars = len(alphabet)
tuple_len = max(its.chain(prefixes.iterkeys(), suffixes.iterkeys()), key=len)
# Tuples can lead or end with null chars but must have at least 1 non-null.
possible_tuples = (num_chars + 1)**(tuple_len - 1) * num_chars
# Exclude the empty bag.
possible_bags = 2**num_chars - 1
norm_prefix = -math.log(sum(prefixes.itervalues()) + possible_tuples)
norm_suffix = -math.log(sum(suffixes.itervalues()) + possible_tuples)
norm_bag = -math.log(sum(bags.itervalues()) + possible_bags)
def p_word(word):
""" Compute probability of a word under the model. """
word_lower = word.lower()
prefix, suffix = word_lower[:tuple_len], word_lower[-tuple_len:]
bag = word_to_bag(word)
ll_prefix = prefixes[prefix] if prefix in prefixes else 1
ll_suffix = suffixes[suffix] if suffix in suffixes else 1
ll_bag = bags[bag] if bag in bags else 1
return ll_prefix + norm_prefix \
+ ll_suffix + norm_suffix \
+ ll_bag + norm_bag
return p_word
def expectation_en_tweet(tweet, p_word, is_lower=False):
"""
Compute expected probability that a tweet is English.
"""
return math.log(sum(math.exp(expectation_en_sentence(s, p_word, is_lower))
for s in tweet) / len(tweet))
def expectation_en_sentence(sentence, p_word, is_lower=False):
"""
Compute expected probability that a word from the sentence is English.
"""
if is_lower is True:
scorer = p_word
else:
scorer = lambda w: p_word(w.lower())
if isinstance(sentence, str):
sentence = sentence.split()
return math.log(sum(math.exp(scorer(w)) for w in sentence) / len(sentence))
def likelihood_en_tweet(tweet, p_word, is_lower=False):
"""
Compute likelihood that a tweet is English.
"""
return sum(likelihood_en_sentence(s, p_word, is_lower)
for s in tweet) / len(tweet)
def likelihood_en_sentence(sentence, p_word, is_lower=False):
"""
Compute likelihood that a word from the sentence is English.
"""
if is_lower is True:
scorer = p_word
else:
scorer = lambda w: p_word(w.lower())
if isinstance(sentence, str):
sentence = sentence.split()
return sum(scorer(w) for w in sentence)
def build_en_prefix_suffix_model(data_json):
"""
Create a probabilisitc model of English words from data.
Features:
3-prefixes, 3-suffixes, bag-of-chars model.
For the 3-prefixes and 3-suffixes, there are |chars|(|chars| + 1)^2
possible observations. For the bag-of-chars, there are 2^|chars| possible
bags.
During inference, we want to avoid the partition function (i.e. all
sentences with 3 words). Therefore, we compute the expectation that a word
in the sentence is English and threshold that.
"""
all_tweets = sentence_split_clean_data(data_json, [''])
toks = [t.lower() for tw in all_tweets
for s in tw
for t in word_tokenize(s)]
prefixes = counter(t[:3] for t in toks)
suffixes = counter(t[-3:] for t in toks)
bags = counter(word_to_bag(t) for t in toks)
return [prefixes, suffixes, bags]
| en | 0.899595 | Model of English language. Convert word to bag-of-chars. Create a function that scores English words. # Tuples can lead or end with null chars but must have at least 1 non-null. # Exclude the empty bag. Compute probability of a word under the model. Compute expected probability that a tweet is English. Compute expected probability that a word from the sentence is English. Compute likelihood that a tweet is English. Compute likelihood that a word from the sentence is English. Create a probabilisitc model of English words from data. Features: 3-prefixes, 3-suffixes, bag-of-chars model. For the 3-prefixes and 3-suffixes, there are |chars|(|chars| + 1)^2 possible observations. For the bag-of-chars, there are 2^|chars| possible bags. During inference, we want to avoid the partition function (i.e. all sentences with 3 words). Therefore, we compute the expectation that a word in the sentence is English and threshold that. | 3.403861 | 3 |
apps/result/management/commands/process_results.py | uk-gov-mirror/ministryofjustice.manchester_traffic_offences_pleas | 3 | 6616074 | # coding=utf-8
from io import StringIO
import datetime as dt
import os
from django.conf import settings
from django.core.mail import EmailMultiAlternatives, get_connection
from django.core.mail import send_mail
from django.core.management.base import BaseCommand
from django.utils import translation
from django.template.loader import get_template
from django.utils.translation import ugettext as _
from apps.result.models import Result
from apps.plea.models import Court
from dateutil.parser import parse
class Command(BaseCommand):
help = "Send out result emails"
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
# we want to capture the output of the handle command
self._log_output = StringIO()
def log(self, message):
self.stdout.write(message)
self._log_output.write(message+"\n")
def mark_done(self, result, dry_run=False, message=None, sent=False):
if message:
self.log(message)
if not dry_run:
result.processed = True
if sent:
result.sent = True
result.sent_on = dt.datetime.now()
result.save()
def add_arguments(self, parser):
parser.add_argument(
"--dry-run",
action="store_true",
dest="dry_run",
default=False,
help="Don't send user emails or update result status")
parser.add_argument(
"--override-recipient",
dest="override_recipient",
default="",
help=
"Send a status email to a comma separated list of email addresses, "
"instead of the user. Combine with --dry-run=True to receive test "
"resulting emails without changing the database, or emailing the user"
)
parser.add_argument(
"--send-status-email-to",
dest="status_email_recipients",
default="",
help="A comma separate list of email recipients to receive the status email. "
"If blank, then output will be sent to stdout"
)
parser.add_argument(
"--date",
dest="date",
default="",
help="The date to process results - uses the created timestamp of the Result model. "
"If not specified the script will default to today"
)
@staticmethod
def email_user(data, recipients, lang="en"):
translation.activate(lang)
text_template = get_template("emails/user_resulting.txt")
html_template = get_template("emails/user_resulting.html")
t_output = text_template.render(data)
h_output = html_template.render(data)
connection = get_connection(host=settings.EMAIL_HOST,
port=settings.EMAIL_PORT,
username=settings.EMAIL_HOST_USER,
password=settings.EMAIL_HOST_PASSWORD,
use_tls=settings.EMAIL_USE_TLS)
subject = _("Make a plea result")
email = EmailMultiAlternatives(subject, t_output,
settings.PLEA_CONFIRMATION_EMAIL_FROM,
recipients, connection=connection)
email.attach_alternative(h_output, "text/html")
email.send(fail_silently=False)
def get_result_data(self, case, result):
data = dict(urn=result.urn)
data["fines"], data["endorsements"], data["total"] = result.get_offence_totals()
# If we move to using OU codes in Case data this should be replaced by a lookup using the
# Case OU code
data["court"] = Court.objects.get_court(result.urn, ou_code=case.ou_code)
if not data["court"]:
self.log("URN failed to standardise: {}".format(result.urn))
data["name"] = case.get_users_name()
data["pay_by"] = result.pay_by_date
data["payment_details"] = {"division": result.division,
"account_number": result.account_number}
return data
def handle(self, *args, **options):
resulted_count, not_resulted_count = 0, 0
if options["override_recipient"]:
override_recipient = options["override_recipient"].split(",")
else:
override_recipient = None
if options["date"]:
filter_date = parse(options["date"]).date()
else:
filter_date = dt.date.today()
filter_date_range = (dt.datetime.combine(filter_date, dt.time.min),
dt.datetime.combine(filter_date, dt.time.max))
self.log("Processing results that were imported on {}".format(
filter_date.strftime("%d/%m/%Y")))
for result in Result.objects.filter(processed=False,
sent=False,
created__range=filter_date_range):
can_result, reason = result.can_result()
case = result.get_associated_case()
if not case:
self.mark_done(result, dry_run=options["dry_run"])
not_resulted_count += 1
continue
if not can_result:
self.mark_done(result, dry_run=options["dry_run"],
message="Skipping {} because {}".format(result.urn, reason))
not_resulted_count += 1
continue
data = self.get_result_data(case, result)
if override_recipient:
self.email_user(data, override_recipient)
elif not options["dry_run"]:
self.email_user(data, [case.email], case.language)
self.mark_done(result, sent=True, dry_run=options["dry_run"],
message="Completed case {} email sent to {}".format(case.urn, case.email))
resulted_count += 1
self.log("total resulted: {}\ntotal not resulted: {}".format(resulted_count, not_resulted_count))
if options["status_email_recipients"]:
recipients = options["status_email_recipients"].split(",")
env = os.environ.get('ENV', '<ENV>')
send_mail('[{}] make-a-plea resulting status email'.format(env),
self._log_output.getvalue(),
settings.PLEA_EMAIL_FROM,
recipients, fail_silently=False)
| # coding=utf-8
from io import StringIO
import datetime as dt
import os
from django.conf import settings
from django.core.mail import EmailMultiAlternatives, get_connection
from django.core.mail import send_mail
from django.core.management.base import BaseCommand
from django.utils import translation
from django.template.loader import get_template
from django.utils.translation import ugettext as _
from apps.result.models import Result
from apps.plea.models import Court
from dateutil.parser import parse
class Command(BaseCommand):
help = "Send out result emails"
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
# we want to capture the output of the handle command
self._log_output = StringIO()
def log(self, message):
self.stdout.write(message)
self._log_output.write(message+"\n")
def mark_done(self, result, dry_run=False, message=None, sent=False):
if message:
self.log(message)
if not dry_run:
result.processed = True
if sent:
result.sent = True
result.sent_on = dt.datetime.now()
result.save()
def add_arguments(self, parser):
parser.add_argument(
"--dry-run",
action="store_true",
dest="dry_run",
default=False,
help="Don't send user emails or update result status")
parser.add_argument(
"--override-recipient",
dest="override_recipient",
default="",
help=
"Send a status email to a comma separated list of email addresses, "
"instead of the user. Combine with --dry-run=True to receive test "
"resulting emails without changing the database, or emailing the user"
)
parser.add_argument(
"--send-status-email-to",
dest="status_email_recipients",
default="",
help="A comma separate list of email recipients to receive the status email. "
"If blank, then output will be sent to stdout"
)
parser.add_argument(
"--date",
dest="date",
default="",
help="The date to process results - uses the created timestamp of the Result model. "
"If not specified the script will default to today"
)
@staticmethod
def email_user(data, recipients, lang="en"):
translation.activate(lang)
text_template = get_template("emails/user_resulting.txt")
html_template = get_template("emails/user_resulting.html")
t_output = text_template.render(data)
h_output = html_template.render(data)
connection = get_connection(host=settings.EMAIL_HOST,
port=settings.EMAIL_PORT,
username=settings.EMAIL_HOST_USER,
password=settings.EMAIL_HOST_PASSWORD,
use_tls=settings.EMAIL_USE_TLS)
subject = _("Make a plea result")
email = EmailMultiAlternatives(subject, t_output,
settings.PLEA_CONFIRMATION_EMAIL_FROM,
recipients, connection=connection)
email.attach_alternative(h_output, "text/html")
email.send(fail_silently=False)
def get_result_data(self, case, result):
data = dict(urn=result.urn)
data["fines"], data["endorsements"], data["total"] = result.get_offence_totals()
# If we move to using OU codes in Case data this should be replaced by a lookup using the
# Case OU code
data["court"] = Court.objects.get_court(result.urn, ou_code=case.ou_code)
if not data["court"]:
self.log("URN failed to standardise: {}".format(result.urn))
data["name"] = case.get_users_name()
data["pay_by"] = result.pay_by_date
data["payment_details"] = {"division": result.division,
"account_number": result.account_number}
return data
def handle(self, *args, **options):
resulted_count, not_resulted_count = 0, 0
if options["override_recipient"]:
override_recipient = options["override_recipient"].split(",")
else:
override_recipient = None
if options["date"]:
filter_date = parse(options["date"]).date()
else:
filter_date = dt.date.today()
filter_date_range = (dt.datetime.combine(filter_date, dt.time.min),
dt.datetime.combine(filter_date, dt.time.max))
self.log("Processing results that were imported on {}".format(
filter_date.strftime("%d/%m/%Y")))
for result in Result.objects.filter(processed=False,
sent=False,
created__range=filter_date_range):
can_result, reason = result.can_result()
case = result.get_associated_case()
if not case:
self.mark_done(result, dry_run=options["dry_run"])
not_resulted_count += 1
continue
if not can_result:
self.mark_done(result, dry_run=options["dry_run"],
message="Skipping {} because {}".format(result.urn, reason))
not_resulted_count += 1
continue
data = self.get_result_data(case, result)
if override_recipient:
self.email_user(data, override_recipient)
elif not options["dry_run"]:
self.email_user(data, [case.email], case.language)
self.mark_done(result, sent=True, dry_run=options["dry_run"],
message="Completed case {} email sent to {}".format(case.urn, case.email))
resulted_count += 1
self.log("total resulted: {}\ntotal not resulted: {}".format(resulted_count, not_resulted_count))
if options["status_email_recipients"]:
recipients = options["status_email_recipients"].split(",")
env = os.environ.get('ENV', '<ENV>')
send_mail('[{}] make-a-plea resulting status email'.format(env),
self._log_output.getvalue(),
settings.PLEA_EMAIL_FROM,
recipients, fail_silently=False)
| en | 0.816674 | # coding=utf-8 # we want to capture the output of the handle command # If we move to using OU codes in Case data this should be replaced by a lookup using the # Case OU code | 2.141243 | 2 |
Section 6/Video 3/S6V3_example.py | PacktPublishing/Learn-Machine-Learning-in-3-Hours | 9 | 6616075 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
if __name__ == "__main__":
FILENAME = 'sample.npy'
# Load problem data.
data = np.load(FILENAME)
# Split into input data and labels.
y = data[:, -1]
X = data[:, :-1]
# Plot raw data.
fig, ax = plt.subplots()
ax.set_xlabel('Price Change 1')
ax.set_ylabel('Price Change 2')
sc = ax.scatter(X[:, 0], X[:, 1], c=y)
# Check for error values and remove
# ???
# Scale data.
scaler = StandardScaler()
scaler.fit(X)
X_scaled = scaler.transform(X)
# Plot scaled data.
fig2, ax2 = plt.subplots()
ax2.set_xlabel('Price Change 1 (Scaled)')
ax2.set_ylabel('Price Change 2 (Scaled)')
sc = ax2.scatter(X_scaled[:, 0], X_scaled[:, 1], c=y)
plt.show()
# Generate training and testing set.
mid_point = int(len(X_scaled) / 2)
X_train = X_scaled[:mid_point, :]
X_test = X_scaled[mid_point:, :]
y_train = y[:mid_point]
y_test = y[mid_point:]
| import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
if __name__ == "__main__":
FILENAME = 'sample.npy'
# Load problem data.
data = np.load(FILENAME)
# Split into input data and labels.
y = data[:, -1]
X = data[:, :-1]
# Plot raw data.
fig, ax = plt.subplots()
ax.set_xlabel('Price Change 1')
ax.set_ylabel('Price Change 2')
sc = ax.scatter(X[:, 0], X[:, 1], c=y)
# Check for error values and remove
# ???
# Scale data.
scaler = StandardScaler()
scaler.fit(X)
X_scaled = scaler.transform(X)
# Plot scaled data.
fig2, ax2 = plt.subplots()
ax2.set_xlabel('Price Change 1 (Scaled)')
ax2.set_ylabel('Price Change 2 (Scaled)')
sc = ax2.scatter(X_scaled[:, 0], X_scaled[:, 1], c=y)
plt.show()
# Generate training and testing set.
mid_point = int(len(X_scaled) / 2)
X_train = X_scaled[:mid_point, :]
X_test = X_scaled[mid_point:, :]
y_train = y[:mid_point]
y_test = y[mid_point:]
| en | 0.448291 | # Load problem data. # Split into input data and labels. # Plot raw data. # Check for error values and remove # ??? # Scale data. # Plot scaled data. # Generate training and testing set. | 3.338132 | 3 |
flask_auto_route.py | daringer/mmpy_snips | 0 | 6616076 | """
(REsTful) APIs building with flask made easy:
- just decorate any function to make it REsT-ready
- short notation and easily readable
- anything else as expected, including func-params
Example:
@rest.get("/items")
def my_endpoint():
# ensured that only "GET" may be used for the web-request
pass
@rest.post("/my/form/action")
def my_post_endpoint():
# only POST will end here,
# DELETE, PUT are also avaialble
pass
"""
# @TODO @FIXME, shall we have a special endpoint which might deliver generic info?
# would need specific decorator to mark the function to be used ....
#endpoints.append((base_url)
######### aahhhhhhh, I guess I will end in hell for this code....
import os
import sys
import functools
import inspect
from pathlib import Path
from traceback import extract_stack
from .url_generator import get_urls_from_func
class FlaskAutoRoute:
"""
Shorter, fancier, http-method-driven app-routing, usage:
@rest.get("/my/url/<int:foo>/endpoint")
def my_view(foo, opt_arg=None):
return jsonify({"some_data": 123})
"""
def __init__(self, flask_app, endpoint_root=None):
"""
........
"""
self.app = flask_app
self.endpoints = []
self.auto_root_path = Path(endpoint_root).absolute() if endpoint_root else None
def __getattr__(self, key):
"""`key` is the designated http.method, dynamically handled here"""
# @TODO: feels like we should restrict this to key in ["get", "post", ...]
# and if not 'in' raise AttributeError()
return self._wrap(key)
def _wrap(self, http_method, auto_gen=False):
"""
called by `__getattr__` like: `obj.stuff` with 'stuff' passed as 'http_method'.
so '_wrap' is **returning a callable** compareable to calls, only dynamically:
'rest_mgr.get(*v, **kw)', 'rest_mgr.post(*v, **kw)'
"""
@functools.wraps(self.app.route)
def func(*v, **kw):
"""for manual 'url' setting, directly returns the result of `app.route(*v, **kw)`"""
kw["methods"] = [http_method.upper()]
# any data in 'v' (a func-param) implies non-auto mode:
if len(v) > 0:
self.endpoints.append((v, kw))
return self.app.route(*v, **kw)
# empty function params => fallback to automated URL generation
@functools.wraps(func)
def sub_func(f):
"""*url-gen* requires func-obj, next wrap: `sub_func`, provides `f`"""
# 'f' is what normally 'app.route' would have been called with for decoration
_gen = (p.as_posix() for p in get_urls_from_func(f, self.auto_root_path))
for url in _gen:
# apply some url-consistency stuff, just to be sure
url = url.replace("_", "-").replace(" ", "").lower()
self.endpoints.append((url, kw))
# *circle-wrap* (decorate) `f` for `len(endpoints)` times...
f = self.app.route(url, **kw)(f)
return f
return sub_func
return func
def get_route_decorator(app, endpoint_root=None):
"""shortcut function to be used for easy importing"""
return FlaskAutoRoute(app, endpoint_root)
| """
(REsTful) APIs building with flask made easy:
- just decorate any function to make it REsT-ready
- short notation and easily readable
- anything else as expected, including func-params
Example:
@rest.get("/items")
def my_endpoint():
# ensured that only "GET" may be used for the web-request
pass
@rest.post("/my/form/action")
def my_post_endpoint():
# only POST will end here,
# DELETE, PUT are also avaialble
pass
"""
# @TODO @FIXME, shall we have a special endpoint which might deliver generic info?
# would need specific decorator to mark the function to be used ....
#endpoints.append((base_url)
######### aahhhhhhh, I guess I will end in hell for this code....
import os
import sys
import functools
import inspect
from pathlib import Path
from traceback import extract_stack
from .url_generator import get_urls_from_func
class FlaskAutoRoute:
"""
Shorter, fancier, http-method-driven app-routing, usage:
@rest.get("/my/url/<int:foo>/endpoint")
def my_view(foo, opt_arg=None):
return jsonify({"some_data": 123})
"""
def __init__(self, flask_app, endpoint_root=None):
"""
........
"""
self.app = flask_app
self.endpoints = []
self.auto_root_path = Path(endpoint_root).absolute() if endpoint_root else None
def __getattr__(self, key):
"""`key` is the designated http.method, dynamically handled here"""
# @TODO: feels like we should restrict this to key in ["get", "post", ...]
# and if not 'in' raise AttributeError()
return self._wrap(key)
def _wrap(self, http_method, auto_gen=False):
"""
called by `__getattr__` like: `obj.stuff` with 'stuff' passed as 'http_method'.
so '_wrap' is **returning a callable** compareable to calls, only dynamically:
'rest_mgr.get(*v, **kw)', 'rest_mgr.post(*v, **kw)'
"""
@functools.wraps(self.app.route)
def func(*v, **kw):
"""for manual 'url' setting, directly returns the result of `app.route(*v, **kw)`"""
kw["methods"] = [http_method.upper()]
# any data in 'v' (a func-param) implies non-auto mode:
if len(v) > 0:
self.endpoints.append((v, kw))
return self.app.route(*v, **kw)
# empty function params => fallback to automated URL generation
@functools.wraps(func)
def sub_func(f):
"""*url-gen* requires func-obj, next wrap: `sub_func`, provides `f`"""
# 'f' is what normally 'app.route' would have been called with for decoration
_gen = (p.as_posix() for p in get_urls_from_func(f, self.auto_root_path))
for url in _gen:
# apply some url-consistency stuff, just to be sure
url = url.replace("_", "-").replace(" ", "").lower()
self.endpoints.append((url, kw))
# *circle-wrap* (decorate) `f` for `len(endpoints)` times...
f = self.app.route(url, **kw)(f)
return f
return sub_func
return func
def get_route_decorator(app, endpoint_root=None):
"""shortcut function to be used for easy importing"""
return FlaskAutoRoute(app, endpoint_root)
| en | 0.774206 | (REsTful) APIs building with flask made easy: - just decorate any function to make it REsT-ready - short notation and easily readable - anything else as expected, including func-params Example: @rest.get("/items") def my_endpoint(): # ensured that only "GET" may be used for the web-request pass @rest.post("/my/form/action") def my_post_endpoint(): # only POST will end here, # DELETE, PUT are also avaialble pass # @TODO @FIXME, shall we have a special endpoint which might deliver generic info? # would need specific decorator to mark the function to be used .... #endpoints.append((base_url) ######### aahhhhhhh, I guess I will end in hell for this code.... Shorter, fancier, http-method-driven app-routing, usage: @rest.get("/my/url/<int:foo>/endpoint") def my_view(foo, opt_arg=None): return jsonify({"some_data": 123}) ........ `key` is the designated http.method, dynamically handled here # @TODO: feels like we should restrict this to key in ["get", "post", ...] # and if not 'in' raise AttributeError() called by `__getattr__` like: `obj.stuff` with 'stuff' passed as 'http_method'. so '_wrap' is **returning a callable** compareable to calls, only dynamically: 'rest_mgr.get(*v, **kw)', 'rest_mgr.post(*v, **kw)' for manual 'url' setting, directly returns the result of `app.route(*v, **kw)` # any data in 'v' (a func-param) implies non-auto mode: # empty function params => fallback to automated URL generation *url-gen* requires func-obj, next wrap: `sub_func`, provides `f` # 'f' is what normally 'app.route' would have been called with for decoration # apply some url-consistency stuff, just to be sure # *circle-wrap* (decorate) `f` for `len(endpoints)` times... shortcut function to be used for easy importing | 3.34449 | 3 |
pixel.py | leocelis/pixel | 0 | 6616077 | import MySQLdb
from flask import request
from flask_restful import Resource
from flask_restful import reqparse
from logger import logger
from mysqlfunc import get_connect
from sqlqueries import SAVE_EVENT_SQL
parser = reqparse.RequestParser()
parser.add_argument('ad_id', type=str)
parser.add_argument('event_name', type=str)
parser.add_argument('value', type=str)
class Pixel(Resource):
def get(self):
params = parser.parse_args()
ad_id = params['ad_id']
event_name = params['event_name']
value = params['value']
user_agent = request.headers.get('User-Agent')
referrer = request.headers.get("Referer")
ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
sql = SAVE_EVENT_SQL.format(
ad_id=ad_id,
event_name=event_name,
value=value,
ip=ip,
user_agent=user_agent,
referrer=referrer).encode('utf-8')
try:
conn = get_connect()
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
except MySQLdb.OperationalError as e:
message = "EVENT MISSED: {sql} - ERROR {e}".format(sql=sql, e=e)
logger.error(message)
except MySQLdb.ProgrammingError as e:
message = "EVENT MISSED: {sql} - ERROR {e}".format(sql=sql, e=e)
logger.error(message)
finally:
cursor.close()
return {"Status": "Success"}
| import MySQLdb
from flask import request
from flask_restful import Resource
from flask_restful import reqparse
from logger import logger
from mysqlfunc import get_connect
from sqlqueries import SAVE_EVENT_SQL
parser = reqparse.RequestParser()
parser.add_argument('ad_id', type=str)
parser.add_argument('event_name', type=str)
parser.add_argument('value', type=str)
class Pixel(Resource):
def get(self):
params = parser.parse_args()
ad_id = params['ad_id']
event_name = params['event_name']
value = params['value']
user_agent = request.headers.get('User-Agent')
referrer = request.headers.get("Referer")
ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
sql = SAVE_EVENT_SQL.format(
ad_id=ad_id,
event_name=event_name,
value=value,
ip=ip,
user_agent=user_agent,
referrer=referrer).encode('utf-8')
try:
conn = get_connect()
cursor = conn.cursor()
cursor.execute(sql)
conn.commit()
except MySQLdb.OperationalError as e:
message = "EVENT MISSED: {sql} - ERROR {e}".format(sql=sql, e=e)
logger.error(message)
except MySQLdb.ProgrammingError as e:
message = "EVENT MISSED: {sql} - ERROR {e}".format(sql=sql, e=e)
logger.error(message)
finally:
cursor.close()
return {"Status": "Success"}
| none | 1 | 2.347881 | 2 | |
setup.py | George3d6/skeptic | 0 | 6616078 | <reponame>George3d6/skeptic<gh_stars>0
import setuptools
about = {}
with open("skeptic/__about__.py") as fp:
exec(fp.read(), about)
with open("README.md", "r") as fh:
long_description = fh.read()
with open('requirements.txt') as req_file:
requirements = req_file.read().splitlines()
setuptools.setup(
name=about['__title__'],
version=about['__version__'],
url=about['__github__'],
download_url=about['__pypi__'],
license=about['__license__'],
author=about['__author__'],
author_email=about['__email__'],
description=about['__description__'],
long_description=long_description,
long_description_content_type="text/markdown",
packages=setuptools.find_packages(),
install_requires=requirements,
classifiers=(
"Programming Language :: Python :: 3",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
),
python_requires=">=3.6"
)
| import setuptools
about = {}
with open("skeptic/__about__.py") as fp:
exec(fp.read(), about)
with open("README.md", "r") as fh:
long_description = fh.read()
with open('requirements.txt') as req_file:
requirements = req_file.read().splitlines()
setuptools.setup(
name=about['__title__'],
version=about['__version__'],
url=about['__github__'],
download_url=about['__pypi__'],
license=about['__license__'],
author=about['__author__'],
author_email=about['__email__'],
description=about['__description__'],
long_description=long_description,
long_description_content_type="text/markdown",
packages=setuptools.find_packages(),
install_requires=requirements,
classifiers=(
"Programming Language :: Python :: 3",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
),
python_requires=">=3.6"
) | none | 1 | 1.593609 | 2 | |
cogs/nsfw.py | Nirlep5252/SynTech | 2 | 6616079 | <gh_stars>1-10
from config import NSFW_COLOR
import logging
import aiohttp
import discord
from discord.ext import commands
class nsfw(commands.Cog, description="18+ Boys"):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
logging.info('Nsfw is ready')
@commands.command(description='You can see a ||pussy|| with this')
@commands.is_nsfw()
async def pussy(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/pussy')
json = await request.json()
embed = discord.Embed(title="Pussy!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='You can see someones ||feet||')
@commands.is_nsfw()
async def feet(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/feet')
json = await request.json()
embed = discord.Embed(title="Feet!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='You can see someone ||cum||')
@commands.is_nsfw()
async def cum(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/cum')
json = await request.json()
embed = discord.Embed(title="Cum!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='You know what this is', aliases=["bj"])
@commands.is_nsfw()
async def blowjob(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/blowjob')
json = await request.json()
embed = discord.Embed(title="Blow Job!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='Boobiesssss')
@commands.is_nsfw()
async def boobs(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/boobs')
json = await request.json()
embed = discord.Embed(title="Boobies!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='Ooh noo')
@commands.is_nsfw()
async def anal(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/anal')
json = await request.json()
embed = discord.Embed(title="That most hurt!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='Yess!')
@commands.is_nsfw()
async def hentai(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://shiro.gg/api/images/nsfw/hentai')
json = await request.json()
embed = discord.Embed(title="hentai!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='Here you go')
@commands.is_nsfw()
async def holo(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/holo')
json = await request.json()
embed = discord.Embed(title="Holo!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command()
@commands.is_nsfw()
async def fuck(self, ctx, member: discord.Member = None):
if member is None:
embed = discord.Embed(title="oh no", description="You need to ping someone", color=NSFW_COLOR)
await ctx.send(embed=embed)
elif member == ctx.author:
await ctx.send("Your sad")
else:
async with aiohttp.ClientSession() as session:
request = await session.get('https://purrbot.site/api/img/nsfw/fuck/gif')
json = await request.json()
embed = discord.Embed(title="WEW!", description=f"{ctx.author.name} fucked {member.name}", color=NSFW_COLOR)
embed.set_image(url=json['link'])
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(nsfw(bot=bot))
| from config import NSFW_COLOR
import logging
import aiohttp
import discord
from discord.ext import commands
class nsfw(commands.Cog, description="18+ Boys"):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
logging.info('Nsfw is ready')
@commands.command(description='You can see a ||pussy|| with this')
@commands.is_nsfw()
async def pussy(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/pussy')
json = await request.json()
embed = discord.Embed(title="Pussy!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='You can see someones ||feet||')
@commands.is_nsfw()
async def feet(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/feet')
json = await request.json()
embed = discord.Embed(title="Feet!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='You can see someone ||cum||')
@commands.is_nsfw()
async def cum(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/cum')
json = await request.json()
embed = discord.Embed(title="Cum!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='You know what this is', aliases=["bj"])
@commands.is_nsfw()
async def blowjob(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/blowjob')
json = await request.json()
embed = discord.Embed(title="Blow Job!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='Boobiesssss')
@commands.is_nsfw()
async def boobs(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/boobs')
json = await request.json()
embed = discord.Embed(title="Boobies!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='Ooh noo')
@commands.is_nsfw()
async def anal(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/anal')
json = await request.json()
embed = discord.Embed(title="That most hurt!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='Yess!')
@commands.is_nsfw()
async def hentai(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://shiro.gg/api/images/nsfw/hentai')
json = await request.json()
embed = discord.Embed(title="hentai!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command(description='Here you go')
@commands.is_nsfw()
async def holo(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://nekos.life/api/v2/img/holo')
json = await request.json()
embed = discord.Embed(title="Holo!", color=NSFW_COLOR)
embed.set_image(url=json['url'])
await ctx.send(embed=embed)
@commands.command()
@commands.is_nsfw()
async def fuck(self, ctx, member: discord.Member = None):
if member is None:
embed = discord.Embed(title="oh no", description="You need to ping someone", color=NSFW_COLOR)
await ctx.send(embed=embed)
elif member == ctx.author:
await ctx.send("Your sad")
else:
async with aiohttp.ClientSession() as session:
request = await session.get('https://purrbot.site/api/img/nsfw/fuck/gif')
json = await request.json()
embed = discord.Embed(title="WEW!", description=f"{ctx.author.name} fucked {member.name}", color=NSFW_COLOR)
embed.set_image(url=json['link'])
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(nsfw(bot=bot)) | none | 1 | 2.646047 | 3 | |
infra/userportal/topology.py | dr-natetorious/rekognition-identity-verification | 7 | 6616080 | import builtins
from infra.configsettings import ConfigManager
from aws_cdk.aws_stepfunctions import StateMachineType
from infra.storage.topology import RivSharedDataStores
from infra.userportal.functions.topology import RivUserPortalFunctionSet
from infra.userportal.states.topology import RivUserPortalStateMachines
from infra.userportal.gateway.topology import RivUserPortalGateway
from json import dumps
from infra.interfaces import IVpcRivStack
from constructs import Construct
config = ConfigManager()
class RivUserPortal(Construct):
def __init__(self, scope: Construct, id: builtins.str, riv_stack:IVpcRivStack, sharedStorage, subnet_group_name:str='Default') -> None:
super().__init__(scope, id)
if config.use_isolated_subnets:
'''
Declare any VPC endpoints required by this construct.
'''
riv_stack.networking.endpoints.add_lambda_support()
riv_stack.networking.endpoints.add_apigateway_support()
riv_stack.networking.endpoints.add_rekognition_support()
'''
Declare the function set that powers the backend
'''
self.functions = RivUserPortalFunctionSet(self,'Functions',
riv_stack=riv_stack,
subnet_group_name=subnet_group_name,
sharedStorage=sharedStorage)
'''
Create an Amazon API Gateway and register Step Function Express integrations.
'''
self.api_gateway = RivUserPortalGateway(self,'Gateway', riv_stack=riv_stack)
self.state_machines = RivUserPortalStateMachines(self,'States',
riv_stack=riv_stack,
functions=self.functions,
state_machine_type= StateMachineType.EXPRESS)
self.api_gateway.bind_state_machines(self.state_machines)
'''
Create Standard Stepfunctions to simplify developer troubleshooting.
'''
self.debug_state_machines = RivUserPortalStateMachines(self,'DebugStates',
riv_stack=riv_stack,
functions=self.functions,
state_machine_type= StateMachineType.STANDARD)
| import builtins
from infra.configsettings import ConfigManager
from aws_cdk.aws_stepfunctions import StateMachineType
from infra.storage.topology import RivSharedDataStores
from infra.userportal.functions.topology import RivUserPortalFunctionSet
from infra.userportal.states.topology import RivUserPortalStateMachines
from infra.userportal.gateway.topology import RivUserPortalGateway
from json import dumps
from infra.interfaces import IVpcRivStack
from constructs import Construct
config = ConfigManager()
class RivUserPortal(Construct):
def __init__(self, scope: Construct, id: builtins.str, riv_stack:IVpcRivStack, sharedStorage, subnet_group_name:str='Default') -> None:
super().__init__(scope, id)
if config.use_isolated_subnets:
'''
Declare any VPC endpoints required by this construct.
'''
riv_stack.networking.endpoints.add_lambda_support()
riv_stack.networking.endpoints.add_apigateway_support()
riv_stack.networking.endpoints.add_rekognition_support()
'''
Declare the function set that powers the backend
'''
self.functions = RivUserPortalFunctionSet(self,'Functions',
riv_stack=riv_stack,
subnet_group_name=subnet_group_name,
sharedStorage=sharedStorage)
'''
Create an Amazon API Gateway and register Step Function Express integrations.
'''
self.api_gateway = RivUserPortalGateway(self,'Gateway', riv_stack=riv_stack)
self.state_machines = RivUserPortalStateMachines(self,'States',
riv_stack=riv_stack,
functions=self.functions,
state_machine_type= StateMachineType.EXPRESS)
self.api_gateway.bind_state_machines(self.state_machines)
'''
Create Standard Stepfunctions to simplify developer troubleshooting.
'''
self.debug_state_machines = RivUserPortalStateMachines(self,'DebugStates',
riv_stack=riv_stack,
functions=self.functions,
state_machine_type= StateMachineType.STANDARD)
| en | 0.76708 | Declare any VPC endpoints required by this construct. Declare the function set that powers the backend Create an Amazon API Gateway and register Step Function Express integrations. Create Standard Stepfunctions to simplify developer troubleshooting. | 1.848049 | 2 |
src/pesapy/trans_status.py | kimengu-david/pesapy | 0 | 6616081 | import requests
import os
from pesapy.utils.security_credentials import generate_security_credential
from pesapy.utils.access_token import generate_access_token
from pesapy.utils.timestamp import get_timestamp
timestamp = get_timestamp()
access_token = generate_access_token()
trans_status_initiator_passwd = os.getenv("TRANS_STATUS_INITIATOR_PASSWD")
assert(trans_status_initiator_passwd !=
None), "Missing trans_status_initiator_passwd"
security_credentials = generate_security_credential(
trans_status_initiator_passwd)
base_url = os.getenv("BASE_URL")
assert(base_url != None), "Missing base_url"
trans_status_initiator_name = os.getenv("TRANS_STATUS_INITIATOR_NAME")
assert(trans_status_initiator_name != None), "trans_status_initiator_name"
trans_status_business_shortcode = os.getenv("TRANS_STATUS_BUSINESS_SHORTCODE")
assert(trans_status_business_shortcode !=
None), "Missing trans_status_business_shortcode"
trans_status_identifier_type = os.getenv("TRANS_STATUS_IDENTIFIER_TYPE")
assert(trans_status_identifier_type !=
None), "Missing trans_status_identifier_type"
trans_status_result_url = os.getenv("TRANS_STATUS_RESULT_URL")
assert(trans_status_result_url != None), "Missing trans_status_result_url"
trans_status_queue_timeout_url = os.getenv("TRANS_STATUS_QUEUE_TIMEOUT_URL")
assert(trans_status_queue_timeout_url !=
None), "Missing trans_status_queue_timeout_url"
class TransStatus:
"""Handles the transaction status query"""
@staticmethod
def process_transaction(**kwargs) -> str:
"""
Processes the transaction_status transaction
:param kwargs - A set of keyword arguments containing a mandory transaction_id, remarks and
optional additional info parameter.
"""
access_token = generate_access_token()
transaction_id = kwargs.get("transaction_id")
assert(transaction_id != None), "Missing transaction_id"
remarks = kwargs.get("remarks")
assert(remarks != None), "Missing remarks"
headers = {"Authorization": "Bearer %s" % access_token}
payload = {
"Initiator": trans_status_initiator_name,
"SecurityCredential": security_credentials,
"CommandID": "TransactionStatusQuery",
"TransactionID": transaction_id,
"PartyA": trans_status_business_shortcode,
"IdentifierType": trans_status_identifier_type,
"ResultURL": trans_status_result_url,
"QueueTimeOutURL": trans_status_queue_timeout_url,
"Remarks": remarks,
"Occasion": kwargs.get("Occasion")
}
response = requests.post(f"{base_url}/mpesa/transactionstatus/v1/query",
json=payload, headers=headers)
return response.json()
| import requests
import os
from pesapy.utils.security_credentials import generate_security_credential
from pesapy.utils.access_token import generate_access_token
from pesapy.utils.timestamp import get_timestamp
timestamp = get_timestamp()
access_token = generate_access_token()
trans_status_initiator_passwd = os.getenv("TRANS_STATUS_INITIATOR_PASSWD")
assert(trans_status_initiator_passwd !=
None), "Missing trans_status_initiator_passwd"
security_credentials = generate_security_credential(
trans_status_initiator_passwd)
base_url = os.getenv("BASE_URL")
assert(base_url != None), "Missing base_url"
trans_status_initiator_name = os.getenv("TRANS_STATUS_INITIATOR_NAME")
assert(trans_status_initiator_name != None), "trans_status_initiator_name"
trans_status_business_shortcode = os.getenv("TRANS_STATUS_BUSINESS_SHORTCODE")
assert(trans_status_business_shortcode !=
None), "Missing trans_status_business_shortcode"
trans_status_identifier_type = os.getenv("TRANS_STATUS_IDENTIFIER_TYPE")
assert(trans_status_identifier_type !=
None), "Missing trans_status_identifier_type"
trans_status_result_url = os.getenv("TRANS_STATUS_RESULT_URL")
assert(trans_status_result_url != None), "Missing trans_status_result_url"
trans_status_queue_timeout_url = os.getenv("TRANS_STATUS_QUEUE_TIMEOUT_URL")
assert(trans_status_queue_timeout_url !=
None), "Missing trans_status_queue_timeout_url"
class TransStatus:
"""Handles the transaction status query"""
@staticmethod
def process_transaction(**kwargs) -> str:
"""
Processes the transaction_status transaction
:param kwargs - A set of keyword arguments containing a mandory transaction_id, remarks and
optional additional info parameter.
"""
access_token = generate_access_token()
transaction_id = kwargs.get("transaction_id")
assert(transaction_id != None), "Missing transaction_id"
remarks = kwargs.get("remarks")
assert(remarks != None), "Missing remarks"
headers = {"Authorization": "Bearer %s" % access_token}
payload = {
"Initiator": trans_status_initiator_name,
"SecurityCredential": security_credentials,
"CommandID": "TransactionStatusQuery",
"TransactionID": transaction_id,
"PartyA": trans_status_business_shortcode,
"IdentifierType": trans_status_identifier_type,
"ResultURL": trans_status_result_url,
"QueueTimeOutURL": trans_status_queue_timeout_url,
"Remarks": remarks,
"Occasion": kwargs.get("Occasion")
}
response = requests.post(f"{base_url}/mpesa/transactionstatus/v1/query",
json=payload, headers=headers)
return response.json()
| en | 0.462968 | Handles the transaction status query Processes the transaction_status transaction :param kwargs - A set of keyword arguments containing a mandory transaction_id, remarks and optional additional info parameter. | 2.350754 | 2 |
authors/apps/articles/tests/test_tagging.py | SilasKenneth/ah-technocrats | 1 | 6616082 | <gh_stars>1-10
from rest_framework import status
from .base_test import BaseTestCase
class TestArticleTagging(BaseTestCase):
"""
Test class for article tagging.
"""
def test_successful_tagging_article(self):
"""
Test method for successful article tagging.
"""
saved_article = self.create_article()[1]
self.assertEqual(saved_article.status_code, status.HTTP_201_CREATED)
self.assertEqual(saved_article.data['title'], self.article_data['article']['title'])
def test_tagging_without_authentication_fails(self):
"""
Test for tagging without authentication.
"""
self.user_signup()
response = self.test_client.post(self.articles_url, self.article_invalid_data, format='json')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_empty_tag_list_field_is_allowed(self):
"""
Test that a blank tag list is allowed.
"""
data = {
"article": {
"title": "Hello world",
"description": "Ever wonder how?",
"body": "You have to believe",
"tagList": []
}
}
self.user_signup()
token = 'Token ' + self.user_login()
response = self.test_client.post(self.articles_url,
data, format='json',
HTTP_AUTHORIZATION=token)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_non_list_tagList_data_fails(self):
"""
Test that non list type of data for tag is not allowed.
"""
data = {
"article": {
"title": "Hello world",
"description": "Ever wonder how?",
"body": "You have to believe",
"tags": "hello, world"
}
}
self.user_signup()
token = 'Token ' + self.user_login()
response = self.test_client.post(self.articles_url,
data, format='json',
HTTP_AUTHORIZATION=token)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
| from rest_framework import status
from .base_test import BaseTestCase
class TestArticleTagging(BaseTestCase):
"""
Test class for article tagging.
"""
def test_successful_tagging_article(self):
"""
Test method for successful article tagging.
"""
saved_article = self.create_article()[1]
self.assertEqual(saved_article.status_code, status.HTTP_201_CREATED)
self.assertEqual(saved_article.data['title'], self.article_data['article']['title'])
def test_tagging_without_authentication_fails(self):
"""
Test for tagging without authentication.
"""
self.user_signup()
response = self.test_client.post(self.articles_url, self.article_invalid_data, format='json')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_empty_tag_list_field_is_allowed(self):
"""
Test that a blank tag list is allowed.
"""
data = {
"article": {
"title": "Hello world",
"description": "Ever wonder how?",
"body": "You have to believe",
"tagList": []
}
}
self.user_signup()
token = 'Token ' + self.user_login()
response = self.test_client.post(self.articles_url,
data, format='json',
HTTP_AUTHORIZATION=token)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_non_list_tagList_data_fails(self):
"""
Test that non list type of data for tag is not allowed.
"""
data = {
"article": {
"title": "Hello world",
"description": "Ever wonder how?",
"body": "You have to believe",
"tags": "hello, world"
}
}
self.user_signup()
token = 'Token ' + self.user_login()
response = self.test_client.post(self.articles_url,
data, format='json',
HTTP_AUTHORIZATION=token)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) | en | 0.876428 | Test class for article tagging. Test method for successful article tagging. Test for tagging without authentication. Test that a blank tag list is allowed. Test that non list type of data for tag is not allowed. | 2.961171 | 3 |
refresh.py | ranz77/Pytible | 1 | 6616083 | <reponame>ranz77/Pytible
import requests
import os
r = requests.delete('https://graph.facebook.com/v2.6/me/messenger_profile?access_token='+os.getenv('FACEBOOK_TOKEN'),json={"fields":["persistent_menu"]})
print (r.status_code)
| import requests
import os
r = requests.delete('https://graph.facebook.com/v2.6/me/messenger_profile?access_token='+os.getenv('FACEBOOK_TOKEN'),json={"fields":["persistent_menu"]})
print (r.status_code) | none | 1 | 2.023375 | 2 | |
aheui/_argparse.py | minacle/rpaheui | 53 | 6616084 |
from __future__ import absolute_import
from aheui.version import VERSION
class ParserError(Exception):
__description__ = ''
def __init__(self, desc=''):
self.desc = desc
def message(self):
return self.__description__ + self.desc
class TooFewArgumentError(ParserError):
__description__ = 'too few arguments: '
class TooManyArgumentError(ParserError):
__description__ = 'too many arguments: '
class ArgumentNotInChoicesError(ParserError):
__description__ = 'argument is not in choices: '
class InformationException(ParserError):
__description__ = ''
class HelpException(InformationException):
__description__ = ''
class ArgumentParser(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
self.arguments = []
def add_argument(self, *names, **kwargs):
if 'dest' not in kwargs:
name = names[0]
while name[0] == '-':
name = name[1:]
kwargs['dest'] = name
if 'narg' not in kwargs:
kwargs['narg'] = '1'
if 'choices' not in kwargs:
kwargs['choices'] = ''
if 'description' not in kwargs:
kwargs['description'] = ''
if 'full_description' not in kwargs:
kwargs['full_description'] = ''
self.arguments.append((names, kwargs))
def _parse_args(self, args):
parsed = {}
nonparsed = []
idx = 0
while idx < len(args):
arg = args[idx]
done = False
for names, opt in self.arguments:
dest = opt['dest']
choices = opt['choices']
for name in list(names):
if arg.startswith(name):
narg = int(opt['narg'])
if narg <= 0:
idx += 1
parsed[dest] = 'yes'
done = True
if narg < 0:
if opt['dest'] == 'help':
raise HelpException('')
else:
raise InformationException(opt['message'])
elif name.startswith('--'):
if '=' not in arg:
raise TooFewArgumentError(name)
argname, arg = arg.split('=', 1)
if choices:
if arg not in choices:
raise ArgumentNotInChoicesError('%s (given: %s / expected: %s)' % (name, arg, choices))
parsed[dest] = arg
idx += 1
done = True
elif name.startswith('-'):
if name == arg:
arg = args[idx + 1]
parsed[dest] = arg
idx += 2
else:
parsed[dest] = arg[len(name):]
idx += 1
done = True
if done:
break
if done:
break
if not done:
nonparsed.append(arg)
idx += 1
for names, opt in self.arguments:
dest = opt['dest']
if dest not in parsed:
parsed[dest] = opt['default']
return parsed, nonparsed
def parse_args(self, args):
import os
try:
return self._parse_args(args)
except HelpException as e:
os.write(2, 'usage: %s [option] ... file\n\n' % self.kwargs.get('prog', args[0]))
for names, opt in self.arguments:
name = names[0] if names[0] == names[1] else ('%s,%s' % names[0:2])
os.write(2, '%s%s: %s' % (name, ' ' * (12 - len(name)), opt['description']))
if int(opt['narg']) > 0 and opt['default']:
os.write(2, ' (default: %s)' % opt['default'])
if opt['choices']:
os.write(2, ' (choices: %s)' % opt['choices'])
if opt['full_description']:
os.write(2, '\n')
os.write(2, opt['full_description'])
os.write(2, '\n')
except InformationException as e:
os.write(2, '%s\n' % e.desc)
except ParserError as e:
prog = self.kwargs.get('prog', args[0])
os.write(2, '%s: error: %s\n' % (prog, e.message()))
return {}, []
parser = ArgumentParser(prog='aheui')
parser.add_argument('--opt', '-O', default='2', choices='0,1,2', description='Set optimization level.', full_description="""\t0: No optimization.
\t1: Quickly resolve deadcode by rough stacksize emulation and merge constant operations.
\t2: Perfectly resolve deadcode by stacksize emulation, reserialize code chunks and merge constant operations.
""")
parser.add_argument('--source', '-S', default='auto', choices='auto,bytecode,asm,asm+comment,text', description='Set source filetype.', full_description="""\t- `auto`: Guess the source type. `bytecode` if `.aheuic` or `End of bytecode` pattern in source. `asm` is `.aheuis`. `text` if `.aheui`. `text` is default.
\t- `bytecode`: Aheui bytecode. (Bytecode representation of `ahsembly`.
\t- `asm`: See `ahsembly`.
\t- `asm+comment`: Same as `asm` with comments.
\t- usage: `--source=asm`, `-Sbytecode` or `-S text`
""")
parser.add_argument('--target', '-T', default='run', choices='run,bytecode,asm', description='Set target filetype.', full_description="""\t- `run`: Run given code.
\t- `bytecode`: Aheui bytecode. (Bytecode representation of `ahsembly`.
\t- `asm`: See `ahsembly`.
\t- usage: `--target=asm`, `-Tbytecode` or `-T run`
""")
parser.add_argument('--output', '-o', default='', description='Output file. Default is ``. See details for each target. If the value is `-`, it is standard output.', full_description="""\t- `run` target: This option is not availble and ignored.
\t- `bytecode` target: Default value is `.aheuic`
\t- `asm` target: Default value is `.aheuis`
""")
parser.add_argument('--cmd', '-c', default='', description='Program passed in as string')
parser.add_argument('--no-c', '--no-c', narg='0', default='no', description='Do not generate `.aheuic` file automatically.', full_description='\tWhat is .aheuic? https://github.com/aheui/snippets/commit/cbb5a12e7cd2db771538ab28dfbc9ad1ada86f35\n')
parser.add_argument('--version', '-v', narg='-1', default='no', description='Show program version', message=VERSION)
parser.add_argument('--help', '-h', narg='-1', default='no', description='Show this help text')
|
from __future__ import absolute_import
from aheui.version import VERSION
class ParserError(Exception):
__description__ = ''
def __init__(self, desc=''):
self.desc = desc
def message(self):
return self.__description__ + self.desc
class TooFewArgumentError(ParserError):
__description__ = 'too few arguments: '
class TooManyArgumentError(ParserError):
__description__ = 'too many arguments: '
class ArgumentNotInChoicesError(ParserError):
__description__ = 'argument is not in choices: '
class InformationException(ParserError):
__description__ = ''
class HelpException(InformationException):
__description__ = ''
class ArgumentParser(object):
def __init__(self, **kwargs):
self.kwargs = kwargs
self.arguments = []
def add_argument(self, *names, **kwargs):
if 'dest' not in kwargs:
name = names[0]
while name[0] == '-':
name = name[1:]
kwargs['dest'] = name
if 'narg' not in kwargs:
kwargs['narg'] = '1'
if 'choices' not in kwargs:
kwargs['choices'] = ''
if 'description' not in kwargs:
kwargs['description'] = ''
if 'full_description' not in kwargs:
kwargs['full_description'] = ''
self.arguments.append((names, kwargs))
def _parse_args(self, args):
parsed = {}
nonparsed = []
idx = 0
while idx < len(args):
arg = args[idx]
done = False
for names, opt in self.arguments:
dest = opt['dest']
choices = opt['choices']
for name in list(names):
if arg.startswith(name):
narg = int(opt['narg'])
if narg <= 0:
idx += 1
parsed[dest] = 'yes'
done = True
if narg < 0:
if opt['dest'] == 'help':
raise HelpException('')
else:
raise InformationException(opt['message'])
elif name.startswith('--'):
if '=' not in arg:
raise TooFewArgumentError(name)
argname, arg = arg.split('=', 1)
if choices:
if arg not in choices:
raise ArgumentNotInChoicesError('%s (given: %s / expected: %s)' % (name, arg, choices))
parsed[dest] = arg
idx += 1
done = True
elif name.startswith('-'):
if name == arg:
arg = args[idx + 1]
parsed[dest] = arg
idx += 2
else:
parsed[dest] = arg[len(name):]
idx += 1
done = True
if done:
break
if done:
break
if not done:
nonparsed.append(arg)
idx += 1
for names, opt in self.arguments:
dest = opt['dest']
if dest not in parsed:
parsed[dest] = opt['default']
return parsed, nonparsed
def parse_args(self, args):
import os
try:
return self._parse_args(args)
except HelpException as e:
os.write(2, 'usage: %s [option] ... file\n\n' % self.kwargs.get('prog', args[0]))
for names, opt in self.arguments:
name = names[0] if names[0] == names[1] else ('%s,%s' % names[0:2])
os.write(2, '%s%s: %s' % (name, ' ' * (12 - len(name)), opt['description']))
if int(opt['narg']) > 0 and opt['default']:
os.write(2, ' (default: %s)' % opt['default'])
if opt['choices']:
os.write(2, ' (choices: %s)' % opt['choices'])
if opt['full_description']:
os.write(2, '\n')
os.write(2, opt['full_description'])
os.write(2, '\n')
except InformationException as e:
os.write(2, '%s\n' % e.desc)
except ParserError as e:
prog = self.kwargs.get('prog', args[0])
os.write(2, '%s: error: %s\n' % (prog, e.message()))
return {}, []
parser = ArgumentParser(prog='aheui')
parser.add_argument('--opt', '-O', default='2', choices='0,1,2', description='Set optimization level.', full_description="""\t0: No optimization.
\t1: Quickly resolve deadcode by rough stacksize emulation and merge constant operations.
\t2: Perfectly resolve deadcode by stacksize emulation, reserialize code chunks and merge constant operations.
""")
parser.add_argument('--source', '-S', default='auto', choices='auto,bytecode,asm,asm+comment,text', description='Set source filetype.', full_description="""\t- `auto`: Guess the source type. `bytecode` if `.aheuic` or `End of bytecode` pattern in source. `asm` is `.aheuis`. `text` if `.aheui`. `text` is default.
\t- `bytecode`: Aheui bytecode. (Bytecode representation of `ahsembly`.
\t- `asm`: See `ahsembly`.
\t- `asm+comment`: Same as `asm` with comments.
\t- usage: `--source=asm`, `-Sbytecode` or `-S text`
""")
parser.add_argument('--target', '-T', default='run', choices='run,bytecode,asm', description='Set target filetype.', full_description="""\t- `run`: Run given code.
\t- `bytecode`: Aheui bytecode. (Bytecode representation of `ahsembly`.
\t- `asm`: See `ahsembly`.
\t- usage: `--target=asm`, `-Tbytecode` or `-T run`
""")
parser.add_argument('--output', '-o', default='', description='Output file. Default is ``. See details for each target. If the value is `-`, it is standard output.', full_description="""\t- `run` target: This option is not availble and ignored.
\t- `bytecode` target: Default value is `.aheuic`
\t- `asm` target: Default value is `.aheuis`
""")
parser.add_argument('--cmd', '-c', default='', description='Program passed in as string')
parser.add_argument('--no-c', '--no-c', narg='0', default='no', description='Do not generate `.aheuic` file automatically.', full_description='\tWhat is .aheuic? https://github.com/aheui/snippets/commit/cbb5a12e7cd2db771538ab28dfbc9ad1ada86f35\n')
parser.add_argument('--version', '-v', narg='-1', default='no', description='Show program version', message=VERSION)
parser.add_argument('--help', '-h', narg='-1', default='no', description='Show this help text')
| en | 0.636937 | \t0: No optimization. \t1: Quickly resolve deadcode by rough stacksize emulation and merge constant operations. \t2: Perfectly resolve deadcode by stacksize emulation, reserialize code chunks and merge constant operations. \t- `auto`: Guess the source type. `bytecode` if `.aheuic` or `End of bytecode` pattern in source. `asm` is `.aheuis`. `text` if `.aheui`. `text` is default. \t- `bytecode`: Aheui bytecode. (Bytecode representation of `ahsembly`. \t- `asm`: See `ahsembly`. \t- `asm+comment`: Same as `asm` with comments. \t- usage: `--source=asm`, `-Sbytecode` or `-S text` \t- `run`: Run given code. \t- `bytecode`: Aheui bytecode. (Bytecode representation of `ahsembly`. \t- `asm`: See `ahsembly`. \t- usage: `--target=asm`, `-Tbytecode` or `-T run` \t- `run` target: This option is not availble and ignored. \t- `bytecode` target: Default value is `.aheuic` \t- `asm` target: Default value is `.aheuis` | 2.780954 | 3 |
server/index.py | anders-wiggers/ChristmasCalenderChecker | 1 | 6616085 | import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
import os
import numpy as np
import torch
import torch.utils.data
from PIL import Image
import xml.etree.ElementTree as ET
import depedencies.transforms as T
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import depedencies.utils
import time;
from depedencies.eval_helper import classes, checkPrice
from flask import Flask, jsonify, request, render_template
import io
threshold=0.9
app = Flask(__name__)
### Model
if __name__ == '__main__':
app.run(host='0.0.0.0')
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
m = torch.load('model/ccc.bfm')
m.to(device)
m.eval()
def countPeople(img):
#imgPath = 'testimg.jpg'
custom_img = Image.open(io.BytesIO(img)).convert("RGB")
custom_img = custom_img.resize((custom_img,))
custom_img = T.ToTensor()(custom_img,None)
custom_img = custom_img[0]
with torch.no_grad():
pred = m([custom_img.to(device)])
person = 0
boxes = pred[0]['boxes'].cpu().numpy()
scores = pred[0]['scores'].cpu().numpy()
for i in range(boxes.shape[0]):
if scores[i] > 0.9:
person = person + 1
return(person)
def countSave(img):
custom_img = Image.open(io.BytesIO(img)).convert("RGB")
custom_img = T.ToTensor()(custom_img,None)
custom_img = custom_img[0]
with torch.no_grad():
pred = m([custom_img.to(device)])
img2 = Image.fromarray(custom_img.mul(255).permute(1, 2, 0).byte().numpy())
plt.figure()
fig, ax = plt.subplots(1, figsize=(12,9))
ax.imshow(img2)
boxes = pred[0]['boxes'].cpu().numpy()
labels = pred[0]['labels'].cpu().numpy()
scores = pred[0]['scores'].cpu().numpy()
cmap = plt.get_cmap('tab20b')
colors = [cmap(i) for i in np.linspace(0, 1, 20)]
counter = {
'juletrae':0,
'julemand':0,
'rensdyr':0,
'tromme':0,
'mistelten':0,
'lys':0,
'kugle':0,
'stjerne':0
}
for i in range(boxes.shape[0]):
if scores[i] > threshold:
#cCount[labels[i]] = cCount[labels[i]] + 1
counter[classes[labels[i]]] = counter[classes[labels[i]]] + 1
#print(i,wboxes[i,:],labels[i],scores[i])
x1 = boxes[i,0]
y1 = boxes[i,1]
box_w = boxes[i,2] - x1
box_h = boxes[i,3] - y1
color = colors[0]
bbox = patches.Rectangle((x1, y1), box_w, box_h,
linewidth=2, edgecolor=color, facecolor='none')
ax.add_patch(bbox)
plt.text(x1, y1-10, s=classes[labels[i]],
color='white', verticalalignment='top',
bbox={'color': color, 'pad': 0})
print(counter)
win, price = checkPrice(counter)
plt.axis('off')
dirPath = os.getcwd() + '/processed_img/' + str(time.time()) + '.png'
plt.savefig(dirPath)
plt.close()
return(counter)
@app.route('/')
def hello():
return render_template("submit.html")
@app.route('/predict', methods=['POST'])
def predict():
if request.method == 'POST':
# we will get the file from the request
file = request.files['file']
# convert that to bytes
img_bytes = file.read()
calResults = countSave(img_bytes)
return jsonify({'cal': calResults})
| import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
import os
import numpy as np
import torch
import torch.utils.data
from PIL import Image
import xml.etree.ElementTree as ET
import depedencies.transforms as T
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import depedencies.utils
import time;
from depedencies.eval_helper import classes, checkPrice
from flask import Flask, jsonify, request, render_template
import io
threshold=0.9
app = Flask(__name__)
### Model
if __name__ == '__main__':
app.run(host='0.0.0.0')
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
m = torch.load('model/ccc.bfm')
m.to(device)
m.eval()
def countPeople(img):
#imgPath = 'testimg.jpg'
custom_img = Image.open(io.BytesIO(img)).convert("RGB")
custom_img = custom_img.resize((custom_img,))
custom_img = T.ToTensor()(custom_img,None)
custom_img = custom_img[0]
with torch.no_grad():
pred = m([custom_img.to(device)])
person = 0
boxes = pred[0]['boxes'].cpu().numpy()
scores = pred[0]['scores'].cpu().numpy()
for i in range(boxes.shape[0]):
if scores[i] > 0.9:
person = person + 1
return(person)
def countSave(img):
custom_img = Image.open(io.BytesIO(img)).convert("RGB")
custom_img = T.ToTensor()(custom_img,None)
custom_img = custom_img[0]
with torch.no_grad():
pred = m([custom_img.to(device)])
img2 = Image.fromarray(custom_img.mul(255).permute(1, 2, 0).byte().numpy())
plt.figure()
fig, ax = plt.subplots(1, figsize=(12,9))
ax.imshow(img2)
boxes = pred[0]['boxes'].cpu().numpy()
labels = pred[0]['labels'].cpu().numpy()
scores = pred[0]['scores'].cpu().numpy()
cmap = plt.get_cmap('tab20b')
colors = [cmap(i) for i in np.linspace(0, 1, 20)]
counter = {
'juletrae':0,
'julemand':0,
'rensdyr':0,
'tromme':0,
'mistelten':0,
'lys':0,
'kugle':0,
'stjerne':0
}
for i in range(boxes.shape[0]):
if scores[i] > threshold:
#cCount[labels[i]] = cCount[labels[i]] + 1
counter[classes[labels[i]]] = counter[classes[labels[i]]] + 1
#print(i,wboxes[i,:],labels[i],scores[i])
x1 = boxes[i,0]
y1 = boxes[i,1]
box_w = boxes[i,2] - x1
box_h = boxes[i,3] - y1
color = colors[0]
bbox = patches.Rectangle((x1, y1), box_w, box_h,
linewidth=2, edgecolor=color, facecolor='none')
ax.add_patch(bbox)
plt.text(x1, y1-10, s=classes[labels[i]],
color='white', verticalalignment='top',
bbox={'color': color, 'pad': 0})
print(counter)
win, price = checkPrice(counter)
plt.axis('off')
dirPath = os.getcwd() + '/processed_img/' + str(time.time()) + '.png'
plt.savefig(dirPath)
plt.close()
return(counter)
@app.route('/')
def hello():
return render_template("submit.html")
@app.route('/predict', methods=['POST'])
def predict():
if request.method == 'POST':
# we will get the file from the request
file = request.files['file']
# convert that to bytes
img_bytes = file.read()
calResults = countSave(img_bytes)
return jsonify({'cal': calResults})
| en | 0.432878 | ### Model #imgPath = 'testimg.jpg' #cCount[labels[i]] = cCount[labels[i]] + 1 #print(i,wboxes[i,:],labels[i],scores[i]) # we will get the file from the request # convert that to bytes | 2.150646 | 2 |
math_functions.py | LauraHannah44/Motion-Simulation | 2 | 6616086 | import os, sys, math, time, copy, pygame, random, colorsys
import config
#region vector-vector
def resolve(v, θ):
x = v * math.cos(θ)
y = v * math.sin(θ)
return x, y
def combine(x, y):
v = math.hypot(x, y)
θ = math.atan2(y, x)
return v, θ
def sum_vector(x_1, y_1, x_2, y_2):
return x_1 + x_2, y_1 + y_2
def sub_vector(x_1, y_1, x_2, y_2):
return x_2 - x_1, y_2 - y_1
def midpoint(x_1, y_1, x_2, y_2):
s_x, s_y = sum_vector(x_1, y_1, x_2, y_2)
return dot_product(s_x, s_y, 1/2)
#endregion
#region vector-scalar
def dot_product(x, y, k):
return x*k, y*k
def law_force(k, r, s_1, s_2):
return k*s_1*s_2 / r**2
#endregion
#region vector
def list_abs(x, y):
return abs(x), abs(y)
def list_round(x, y, digits=0):
if not digits:
return int(x), int(y)
else:
return round(x, digits), round(y, digits)
def to_scale(x, y, point=False):
if point:
x, y = sub_vector(*dot_product(*config.screen_pixel, 1/2), x, y)
x, y = dot_product(x, -1*y, 1/config.screen_mods["zoom"].value)
if point:
pan_x, pan_y = config.screen_mods["pan_x"].value, config.screen_mods["pan_y"].value
x, y = sub_vector(pan_x, pan_y, x, y)
return x, y
def to_pixel(x, y, point=False):
if point:
pan_x, pan_y = config.screen_mods["pan_x"].value, config.screen_mods["pan_y"].value
x, y = sum_vector(pan_x, pan_y, x, y)
x, y = dot_product(x, -1*y, config.screen_mods["zoom"].value)
if point:
x, y = sum_vector(*dot_product(*config.screen_pixel, 1/2), x, y)
return x, y
#endregion
#region scalar
def sigmoid(x):
return 1 / (1 + math.exp(-x))
#endregion
| import os, sys, math, time, copy, pygame, random, colorsys
import config
#region vector-vector
def resolve(v, θ):
x = v * math.cos(θ)
y = v * math.sin(θ)
return x, y
def combine(x, y):
v = math.hypot(x, y)
θ = math.atan2(y, x)
return v, θ
def sum_vector(x_1, y_1, x_2, y_2):
return x_1 + x_2, y_1 + y_2
def sub_vector(x_1, y_1, x_2, y_2):
return x_2 - x_1, y_2 - y_1
def midpoint(x_1, y_1, x_2, y_2):
s_x, s_y = sum_vector(x_1, y_1, x_2, y_2)
return dot_product(s_x, s_y, 1/2)
#endregion
#region vector-scalar
def dot_product(x, y, k):
return x*k, y*k
def law_force(k, r, s_1, s_2):
return k*s_1*s_2 / r**2
#endregion
#region vector
def list_abs(x, y):
return abs(x), abs(y)
def list_round(x, y, digits=0):
if not digits:
return int(x), int(y)
else:
return round(x, digits), round(y, digits)
def to_scale(x, y, point=False):
if point:
x, y = sub_vector(*dot_product(*config.screen_pixel, 1/2), x, y)
x, y = dot_product(x, -1*y, 1/config.screen_mods["zoom"].value)
if point:
pan_x, pan_y = config.screen_mods["pan_x"].value, config.screen_mods["pan_y"].value
x, y = sub_vector(pan_x, pan_y, x, y)
return x, y
def to_pixel(x, y, point=False):
if point:
pan_x, pan_y = config.screen_mods["pan_x"].value, config.screen_mods["pan_y"].value
x, y = sum_vector(pan_x, pan_y, x, y)
x, y = dot_product(x, -1*y, config.screen_mods["zoom"].value)
if point:
x, y = sum_vector(*dot_product(*config.screen_pixel, 1/2), x, y)
return x, y
#endregion
#region scalar
def sigmoid(x):
return 1 / (1 + math.exp(-x))
#endregion
| en | 0.380954 | #region vector-vector #endregion #region vector-scalar #endregion #region vector #endregion #region scalar #endregion | 2.562586 | 3 |
src/nuclei_segmentation/gpu_segmentation.py | PeterJackNaylor/CellularHeatmaps | 0 | 6616087 |
import os
import numpy as np
import h5py
from tqdm import tqdm
from skimage.io import imsave
from model_creation import create_model
from data_handler import get_input, get_image_from_slide
def predict_each_element(output, slide, parameter_file, model):
"""
Takes a list of parameters associated to a tiff file.
From this it extract patches and puts them into a list
Parameters
----------
output: string
File output folder name
slide: string
Slide name, raw data
parameter_list : list
List of lists containing 5 fields, x_0, y_0, level, width, height to crop slide.
model: keras model to predict segmentation
Returns
-------
collection of segmentation results : hdf5 file
HDF5 file containing the raw data and segmentation for each tissue.
Raises
------
"""
try:
os.mkdir(output)
except:
pass
# size_annot is 2012 - 2 * overlap, where overlap = marge + 92
# size tile is 2012
name = os.path.join(output, "probability_{}_{}_{}_{}.h5")
with open(parameter_file) as f:
lines = f.readlines()
# print('NOT FULL'); lines = lines[0:2] # to accelerate, uncomment.
for line in tqdm(lines):
inputs = get_input(line)
img = get_image_from_slide(slide, inputs)
inputs = inputs[0:4]
prob = model.predict(img)['probability']
#removing unet padding
inputs = [inputs[0] + 92, inputs[1] + 92, inputs[2] - 2 * 92, inputs[3] - 2 * 92]
h5f = h5py.File(name.format(*inputs), 'w')
h5f.create_dataset('distance', data=prob[:, :, 0])
h5f.create_dataset('raw', data=img[92:-92, 92:-92])
h5f.close()
f.close()
def main():
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--slide", dest="slide", type="string",
help="slide name")
parser.add_option("--parameter", dest="p", type="string",
help="parameter file")
parser.add_option("--output", dest="output", type="string",
help="outputs name")
parser.add_option("--mean_file", dest="mean_file", type="string",
help="mean_file for the model")
parser.add_option("--log", dest="log", type="string",
help="log or weights for the model with feat being the after _")
(options, _) = parser.parse_args()
feat = int(options.log.split('_')[-1])
model = create_model(options.log, np.load(options.mean_file), feat)
predict_each_element(options.output, options.slide, options.p, model)
if __name__ == '__main__':
main()
|
import os
import numpy as np
import h5py
from tqdm import tqdm
from skimage.io import imsave
from model_creation import create_model
from data_handler import get_input, get_image_from_slide
def predict_each_element(output, slide, parameter_file, model):
"""
Takes a list of parameters associated to a tiff file.
From this it extract patches and puts them into a list
Parameters
----------
output: string
File output folder name
slide: string
Slide name, raw data
parameter_list : list
List of lists containing 5 fields, x_0, y_0, level, width, height to crop slide.
model: keras model to predict segmentation
Returns
-------
collection of segmentation results : hdf5 file
HDF5 file containing the raw data and segmentation for each tissue.
Raises
------
"""
try:
os.mkdir(output)
except:
pass
# size_annot is 2012 - 2 * overlap, where overlap = marge + 92
# size tile is 2012
name = os.path.join(output, "probability_{}_{}_{}_{}.h5")
with open(parameter_file) as f:
lines = f.readlines()
# print('NOT FULL'); lines = lines[0:2] # to accelerate, uncomment.
for line in tqdm(lines):
inputs = get_input(line)
img = get_image_from_slide(slide, inputs)
inputs = inputs[0:4]
prob = model.predict(img)['probability']
#removing unet padding
inputs = [inputs[0] + 92, inputs[1] + 92, inputs[2] - 2 * 92, inputs[3] - 2 * 92]
h5f = h5py.File(name.format(*inputs), 'w')
h5f.create_dataset('distance', data=prob[:, :, 0])
h5f.create_dataset('raw', data=img[92:-92, 92:-92])
h5f.close()
f.close()
def main():
from optparse import OptionParser
parser = OptionParser()
parser.add_option("--slide", dest="slide", type="string",
help="slide name")
parser.add_option("--parameter", dest="p", type="string",
help="parameter file")
parser.add_option("--output", dest="output", type="string",
help="outputs name")
parser.add_option("--mean_file", dest="mean_file", type="string",
help="mean_file for the model")
parser.add_option("--log", dest="log", type="string",
help="log or weights for the model with feat being the after _")
(options, _) = parser.parse_args()
feat = int(options.log.split('_')[-1])
model = create_model(options.log, np.load(options.mean_file), feat)
predict_each_element(options.output, options.slide, options.p, model)
if __name__ == '__main__':
main()
| en | 0.747371 | Takes a list of parameters associated to a tiff file. From this it extract patches and puts them into a list Parameters ---------- output: string File output folder name slide: string Slide name, raw data parameter_list : list List of lists containing 5 fields, x_0, y_0, level, width, height to crop slide. model: keras model to predict segmentation Returns ------- collection of segmentation results : hdf5 file HDF5 file containing the raw data and segmentation for each tissue. Raises ------ # size_annot is 2012 - 2 * overlap, where overlap = marge + 92 # size tile is 2012 # print('NOT FULL'); lines = lines[0:2] # to accelerate, uncomment. #removing unet padding | 2.631843 | 3 |
app/api/geoserver/featuretype.py | stazrad/geohack-collab-project | 5 | 6616088 | <reponame>stazrad/geohack-collab-project<gh_stars>1-10
from typing import Dict
from .logger import logger
from .endpoint import GeoserverEndpt
class GeoserverFeatureType(GeoserverEndpt):
"""
"""
def __init__(
self,
parent,
name: str,
data: Dict
) -> None:
super().__init__(parent, 'featuretypes', name)
self.data = data
self.data['name'] = name
def create(self) -> bool:
logger.error(f"attempting to create {self.data}")
response = self.parent.post(self.endpt, data=self.data)
if response.status_code != 201:
logger.error(f"could not create datastore {self.name} in {self.parent.name}")
return False
else:
return True
| from typing import Dict
from .logger import logger
from .endpoint import GeoserverEndpt
class GeoserverFeatureType(GeoserverEndpt):
"""
"""
def __init__(
self,
parent,
name: str,
data: Dict
) -> None:
super().__init__(parent, 'featuretypes', name)
self.data = data
self.data['name'] = name
def create(self) -> bool:
logger.error(f"attempting to create {self.data}")
response = self.parent.post(self.endpt, data=self.data)
if response.status_code != 201:
logger.error(f"could not create datastore {self.name} in {self.parent.name}")
return False
else:
return True | none | 1 | 2.804819 | 3 | |
sklearn/gmm_sample.py | aidiary/PRML | 93 | 6616089 | #coding: utf-8
import numpy as np
from sklearn import mixture
import matplotlib.pyplot as plt
import matplotlib
np.random.seed(1)
g = mixture.GMM(n_components=2)
# 一次元データ生成
# 平均が0のクラスタに属する100個のデータと平均が10のクラスタに属する300個のデータ
obs = np.concatenate((np.random.randn(100, 1), 10 + np.random.randn(300, 1)))
# GMMへフィッティング
g.fit(obs)
# 混合係数
print g.weights_
# 各ガウス分布の平均
print g.means_
# 各ガウス分布の分散
print g.covars_
# 新データに対する予測
newdata = [[0], [2], [4], [5], [9], [10]]
# どちらのクラスタに属するか返す
print g.predict(newdata)
# どちらのクラスタに属するかを表す確率
print np.round(g.predict_proba(newdata), 2)
# log probabilities
# データのモデルへの当てはまりやすさ
# 対数尤度か?
print np.round(g.score(newdata), 2)
plt.plot(obs)
plt.show()
| #coding: utf-8
import numpy as np
from sklearn import mixture
import matplotlib.pyplot as plt
import matplotlib
np.random.seed(1)
g = mixture.GMM(n_components=2)
# 一次元データ生成
# 平均が0のクラスタに属する100個のデータと平均が10のクラスタに属する300個のデータ
obs = np.concatenate((np.random.randn(100, 1), 10 + np.random.randn(300, 1)))
# GMMへフィッティング
g.fit(obs)
# 混合係数
print g.weights_
# 各ガウス分布の平均
print g.means_
# 各ガウス分布の分散
print g.covars_
# 新データに対する予測
newdata = [[0], [2], [4], [5], [9], [10]]
# どちらのクラスタに属するか返す
print g.predict(newdata)
# どちらのクラスタに属するかを表す確率
print np.round(g.predict_proba(newdata), 2)
# log probabilities
# データのモデルへの当てはまりやすさ
# 対数尤度か?
print np.round(g.score(newdata), 2)
plt.plot(obs)
plt.show()
| ja | 0.999452 | #coding: utf-8 # 一次元データ生成 # 平均が0のクラスタに属する100個のデータと平均が10のクラスタに属する300個のデータ # GMMへフィッティング # 混合係数 # 各ガウス分布の平均 # 各ガウス分布の分散 # 新データに対する予測 # どちらのクラスタに属するか返す # どちらのクラスタに属するかを表す確率 # log probabilities # データのモデルへの当てはまりやすさ # 対数尤度か? | 2.888445 | 3 |
exchange.py | wasdee/DarkMoney | 0 | 6616090 |
def toTHB(sgd = None, usd = None):
if sgd:
return sgd * 24.31
if usd:
return usd *31.552
|
def toTHB(sgd = None, usd = None):
if sgd:
return sgd * 24.31
if usd:
return usd *31.552
| none | 1 | 2.707757 | 3 | |
akshare/index/index_cni.py | NovelResearchInvestment/akshare | 721 | 6616091 | <reponame>NovelResearchInvestment/akshare<filename>akshare/index/index_cni.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2022/3/5 23:50
Desc: 国证指数
http://www.cnindex.com.cn/index.html
"""
import zipfile
import pandas as pd
import requests
def index_all_cni() -> pd.DataFrame:
"""
国证指数-最近交易日的所有指数
http://www.cnindex.com.cn/zh_indices/sese/index.html?act_menu=1&index_type=-1
:return: 国证指数-所有指数
:rtype: pandas.DataFrame
"""
url = "http://www.cnindex.com.cn/index/indexList"
params = {
"channelCode": "-1",
"rows": "2000",
"pageNum": "1",
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json["data"]["rows"])
temp_df.columns = [
"_",
"_",
"指数代码",
"_",
"_",
"_",
"_",
"_",
"指数简称",
"_",
"_",
"_",
"样本数",
"收盘点位",
"涨跌幅",
"_",
"PE滚动",
"_",
"成交量",
"成交额",
"总市值",
"自由流通市值",
"_",
"_",
]
temp_df = temp_df[
[
"指数代码",
"指数简称",
"样本数",
"收盘点位",
"涨跌幅",
"PE滚动",
"成交量",
"成交额",
"总市值",
"自由流通市值",
]
]
temp_df['成交量'] = temp_df['成交量'] / 100000
temp_df['成交额'] = temp_df['成交额'] / 100000000
temp_df['总市值'] = temp_df['总市值'] / 100000000
temp_df['自由流通市值'] = temp_df['自由流通市值'] / 100000000
return temp_df
def index_hist_cni(symbol: str = "399001") -> pd.DataFrame:
"""
指数历史行情数据
http://www.cnindex.com.cn/module/index-detail.html?act_menu=1&indexCode=399001
:param symbol: 指数代码
:type symbol: str
:return: 指数历史行情数据
:rtype: pandas.DataFrame
"""
url = "http://hq.cnindex.com.cn/market/market/getIndexDailyDataWithDataFormat"
params = {
"indexCode": symbol,
"startDate": "",
"endDate": "",
"frequency": "day",
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json["data"]["data"])
temp_df.columns = [
"日期",
"_",
"最高价",
"开盘价",
"最低价",
"收盘价",
"_",
"涨跌幅",
"成交额",
"成交量",
"_",
]
temp_df = temp_df[
[
"日期",
"开盘价",
"最高价",
"最低价",
"收盘价",
"涨跌幅",
"成交量",
"成交额",
]
]
temp_df["涨跌幅"] = temp_df["涨跌幅"].str.replace("%", "")
temp_df["涨跌幅"] = temp_df["涨跌幅"].astype("float")
temp_df["涨跌幅"] = temp_df["涨跌幅"] / 100
return temp_df
def index_detail_cni(symbol: str = '399005', date: str = '202011') -> pd.DataFrame:
"""
国证指数-样本详情-指定日期的样本成份
http://www.cnindex.com.cn/module/index-detail.html?act_menu=1&indexCode=399001
:param symbol: 指数代码
:type symbol: str
:param date: 指定月份
:type date: str
:return: 指定日期的样本成份
:rtype: pandas.DataFrame
"""
url = 'http://www.cnindex.com.cn/sample-detail/download'
params = {
'indexcode': symbol,
'dateStr': '-'.join([date[:4], date[4:]])
}
r = requests.get(url, params=params)
temp_df = pd.read_excel(r.content)
temp_df['样本代码'] = temp_df['样本代码'].astype(str).str.zfill(6)
temp_df.columns = [
'日期',
'样本代码',
'样本简称',
'所属行业',
'自由流通市值',
'总市值',
'权重',
]
temp_df['自由流通市值'] = pd.to_numeric(temp_df['自由流通市值'])
temp_df['总市值'] = pd.to_numeric(temp_df['总市值'])
temp_df['权重'] = pd.to_numeric(temp_df['权重'])
return temp_df
def index_detail_hist_cni(symbol: str = '399001', date: str = "") -> pd.DataFrame:
"""
国证指数-样本详情-历史样本
http://www.cnindex.com.cn/module/index-detail.html?act_menu=1&indexCode=399001
:param date: 指数代码
:type date: str
:param symbol: 指数代码
:type symbol: str
:return: 历史样本
:rtype: pandas.DataFrame
"""
if date:
url = 'http://www.cnindex.com.cn/sample-detail/detail'
params = {
'indexcode': symbol,
'dateStr': '-'.join([date[:4], date[4:]]),
'pageNum': '1',
'rows': '50000',
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json['data']['rows'])
temp_df.columns = [
'-',
'-',
'日期',
'样本代码',
'样本简称',
'所属行业',
'-',
'自由流通市值',
'总市值',
'权重',
'-',
]
temp_df = temp_df[[
'日期',
'样本代码',
'样本简称',
'所属行业',
'自由流通市值',
'总市值',
'权重',
]]
else:
url = 'http://www.cnindex.com.cn/sample-detail/download-history'
params = {
'indexcode': symbol
}
r = requests.get(url, params=params)
temp_df = pd.read_excel(r.content)
temp_df['样本代码'] = temp_df['样本代码'].astype(str).str.zfill(6)
temp_df.columns = [
'日期',
'样本代码',
'样本简称',
'所属行业',
'自由流通市值',
'总市值',
'权重',
]
temp_df['自由流通市值'] = pd.to_numeric(temp_df['自由流通市值'])
temp_df['总市值'] = pd.to_numeric(temp_df['总市值'])
temp_df['权重'] = pd.to_numeric(temp_df['权重'])
return temp_df
def index_detail_hist_adjust_cni(symbol: str = '399005') -> pd.DataFrame:
"""
国证指数-样本详情-历史调样
http://www.cnindex.com.cn/module/index-detail.html?act_menu=1&indexCode=399005
:param symbol: 指数代码
:type symbol: str
:return: 历史调样
:rtype: pandas.DataFrame
"""
url = 'http://www.cnindex.com.cn/sample-detail/download-adjustment'
params = {
'indexcode': symbol
}
r = requests.get(url, params=params)
try:
temp_df = pd.read_excel(r.content, engine="openpyxl")
except zipfile.BadZipFile as e:
return pd.DataFrame()
temp_df['样本代码'] = temp_df['样本代码'].astype(str).str.zfill(6)
return temp_df
if __name__ == "__main__":
index_all_cni_df = index_all_cni()
print(index_all_cni_df)
index_hist_cni_df = index_hist_cni(symbol="399005")
print(index_hist_cni_df)
index_detail_cni_df = index_detail_cni(symbol='399005', date='2020-11')
print(index_detail_cni_df)
index_detail_hist_cni_df = index_detail_hist_cni(symbol='399005', date='202201')
print(index_detail_hist_cni_df)
index_detail_hist_adjust_cni_df = index_detail_hist_adjust_cni(symbol='399005')
print(index_detail_hist_adjust_cni_df)
| #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2022/3/5 23:50
Desc: 国证指数
http://www.cnindex.com.cn/index.html
"""
import zipfile
import pandas as pd
import requests
def index_all_cni() -> pd.DataFrame:
"""
国证指数-最近交易日的所有指数
http://www.cnindex.com.cn/zh_indices/sese/index.html?act_menu=1&index_type=-1
:return: 国证指数-所有指数
:rtype: pandas.DataFrame
"""
url = "http://www.cnindex.com.cn/index/indexList"
params = {
"channelCode": "-1",
"rows": "2000",
"pageNum": "1",
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json["data"]["rows"])
temp_df.columns = [
"_",
"_",
"指数代码",
"_",
"_",
"_",
"_",
"_",
"指数简称",
"_",
"_",
"_",
"样本数",
"收盘点位",
"涨跌幅",
"_",
"PE滚动",
"_",
"成交量",
"成交额",
"总市值",
"自由流通市值",
"_",
"_",
]
temp_df = temp_df[
[
"指数代码",
"指数简称",
"样本数",
"收盘点位",
"涨跌幅",
"PE滚动",
"成交量",
"成交额",
"总市值",
"自由流通市值",
]
]
temp_df['成交量'] = temp_df['成交量'] / 100000
temp_df['成交额'] = temp_df['成交额'] / 100000000
temp_df['总市值'] = temp_df['总市值'] / 100000000
temp_df['自由流通市值'] = temp_df['自由流通市值'] / 100000000
return temp_df
def index_hist_cni(symbol: str = "399001") -> pd.DataFrame:
"""
指数历史行情数据
http://www.cnindex.com.cn/module/index-detail.html?act_menu=1&indexCode=399001
:param symbol: 指数代码
:type symbol: str
:return: 指数历史行情数据
:rtype: pandas.DataFrame
"""
url = "http://hq.cnindex.com.cn/market/market/getIndexDailyDataWithDataFormat"
params = {
"indexCode": symbol,
"startDate": "",
"endDate": "",
"frequency": "day",
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json["data"]["data"])
temp_df.columns = [
"日期",
"_",
"最高价",
"开盘价",
"最低价",
"收盘价",
"_",
"涨跌幅",
"成交额",
"成交量",
"_",
]
temp_df = temp_df[
[
"日期",
"开盘价",
"最高价",
"最低价",
"收盘价",
"涨跌幅",
"成交量",
"成交额",
]
]
temp_df["涨跌幅"] = temp_df["涨跌幅"].str.replace("%", "")
temp_df["涨跌幅"] = temp_df["涨跌幅"].astype("float")
temp_df["涨跌幅"] = temp_df["涨跌幅"] / 100
return temp_df
def index_detail_cni(symbol: str = '399005', date: str = '202011') -> pd.DataFrame:
"""
国证指数-样本详情-指定日期的样本成份
http://www.cnindex.com.cn/module/index-detail.html?act_menu=1&indexCode=399001
:param symbol: 指数代码
:type symbol: str
:param date: 指定月份
:type date: str
:return: 指定日期的样本成份
:rtype: pandas.DataFrame
"""
url = 'http://www.cnindex.com.cn/sample-detail/download'
params = {
'indexcode': symbol,
'dateStr': '-'.join([date[:4], date[4:]])
}
r = requests.get(url, params=params)
temp_df = pd.read_excel(r.content)
temp_df['样本代码'] = temp_df['样本代码'].astype(str).str.zfill(6)
temp_df.columns = [
'日期',
'样本代码',
'样本简称',
'所属行业',
'自由流通市值',
'总市值',
'权重',
]
temp_df['自由流通市值'] = pd.to_numeric(temp_df['自由流通市值'])
temp_df['总市值'] = pd.to_numeric(temp_df['总市值'])
temp_df['权重'] = pd.to_numeric(temp_df['权重'])
return temp_df
def index_detail_hist_cni(symbol: str = '399001', date: str = "") -> pd.DataFrame:
"""
国证指数-样本详情-历史样本
http://www.cnindex.com.cn/module/index-detail.html?act_menu=1&indexCode=399001
:param date: 指数代码
:type date: str
:param symbol: 指数代码
:type symbol: str
:return: 历史样本
:rtype: pandas.DataFrame
"""
if date:
url = 'http://www.cnindex.com.cn/sample-detail/detail'
params = {
'indexcode': symbol,
'dateStr': '-'.join([date[:4], date[4:]]),
'pageNum': '1',
'rows': '50000',
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json['data']['rows'])
temp_df.columns = [
'-',
'-',
'日期',
'样本代码',
'样本简称',
'所属行业',
'-',
'自由流通市值',
'总市值',
'权重',
'-',
]
temp_df = temp_df[[
'日期',
'样本代码',
'样本简称',
'所属行业',
'自由流通市值',
'总市值',
'权重',
]]
else:
url = 'http://www.cnindex.com.cn/sample-detail/download-history'
params = {
'indexcode': symbol
}
r = requests.get(url, params=params)
temp_df = pd.read_excel(r.content)
temp_df['样本代码'] = temp_df['样本代码'].astype(str).str.zfill(6)
temp_df.columns = [
'日期',
'样本代码',
'样本简称',
'所属行业',
'自由流通市值',
'总市值',
'权重',
]
temp_df['自由流通市值'] = pd.to_numeric(temp_df['自由流通市值'])
temp_df['总市值'] = pd.to_numeric(temp_df['总市值'])
temp_df['权重'] = pd.to_numeric(temp_df['权重'])
return temp_df
def index_detail_hist_adjust_cni(symbol: str = '399005') -> pd.DataFrame:
"""
国证指数-样本详情-历史调样
http://www.cnindex.com.cn/module/index-detail.html?act_menu=1&indexCode=399005
:param symbol: 指数代码
:type symbol: str
:return: 历史调样
:rtype: pandas.DataFrame
"""
url = 'http://www.cnindex.com.cn/sample-detail/download-adjustment'
params = {
'indexcode': symbol
}
r = requests.get(url, params=params)
try:
temp_df = pd.read_excel(r.content, engine="openpyxl")
except zipfile.BadZipFile as e:
return pd.DataFrame()
temp_df['样本代码'] = temp_df['样本代码'].astype(str).str.zfill(6)
return temp_df
if __name__ == "__main__":
index_all_cni_df = index_all_cni()
print(index_all_cni_df)
index_hist_cni_df = index_hist_cni(symbol="399005")
print(index_hist_cni_df)
index_detail_cni_df = index_detail_cni(symbol='399005', date='2020-11')
print(index_detail_cni_df)
index_detail_hist_cni_df = index_detail_hist_cni(symbol='399005', date='202201')
print(index_detail_hist_cni_df)
index_detail_hist_adjust_cni_df = index_detail_hist_adjust_cni(symbol='399005')
print(index_detail_hist_adjust_cni_df) | zh | 0.446013 | #!/usr/bin/env python # -*- coding:utf-8 -*- Date: 2022/3/5 23:50 Desc: 国证指数 http://www.cnindex.com.cn/index.html 国证指数-最近交易日的所有指数 http://www.cnindex.com.cn/zh_indices/sese/index.html?act_menu=1&index_type=-1 :return: 国证指数-所有指数 :rtype: pandas.DataFrame 指数历史行情数据 http://www.cnindex.com.cn/module/index-detail.html?act_menu=1&indexCode=399001 :param symbol: 指数代码 :type symbol: str :return: 指数历史行情数据 :rtype: pandas.DataFrame 国证指数-样本详情-指定日期的样本成份 http://www.cnindex.com.cn/module/index-detail.html?act_menu=1&indexCode=399001 :param symbol: 指数代码 :type symbol: str :param date: 指定月份 :type date: str :return: 指定日期的样本成份 :rtype: pandas.DataFrame 国证指数-样本详情-历史样本 http://www.cnindex.com.cn/module/index-detail.html?act_menu=1&indexCode=399001 :param date: 指数代码 :type date: str :param symbol: 指数代码 :type symbol: str :return: 历史样本 :rtype: pandas.DataFrame 国证指数-样本详情-历史调样 http://www.cnindex.com.cn/module/index-detail.html?act_menu=1&indexCode=399005 :param symbol: 指数代码 :type symbol: str :return: 历史调样 :rtype: pandas.DataFrame | 2.758635 | 3 |
output_manager.py | Tenchi88/lexical_analyzer | 0 | 6616092 | # -*- coding: utf-8 -*-
import json
import csv
# def show_path_stat(path, top_function, top_size=10):
# top = top_function(path, top_size=top_size)
# for word, occurrence in top:
# print(word, occurrence)
class OutputManager:
def __init__(
self,
print_output=False,
json_file_name=None,
csv_file_name=None
):
self.print = print_output
self.json_file_name = json_file_name
self.csv_file_name = csv_file_name
@staticmethod
def print_output(top):
for word, occurrence in top:
print(word, occurrence)
def generate_json(self, top):
with open(self.json_file_name, 'w') as json_file:
json.dump(top, json_file, sort_keys=True, indent=4)
def generate_csv(self, top):
with open(self.csv_file_name, 'w') as csv_file:
csv.writer(csv_file, delimiter=',').writerows(top)
def generate_output(self, top):
if self.print:
self.print_output(top)
if self.json_file_name:
self.generate_json(top)
if self.csv_file_name:
self.generate_csv(top)
| # -*- coding: utf-8 -*-
import json
import csv
# def show_path_stat(path, top_function, top_size=10):
# top = top_function(path, top_size=top_size)
# for word, occurrence in top:
# print(word, occurrence)
class OutputManager:
def __init__(
self,
print_output=False,
json_file_name=None,
csv_file_name=None
):
self.print = print_output
self.json_file_name = json_file_name
self.csv_file_name = csv_file_name
@staticmethod
def print_output(top):
for word, occurrence in top:
print(word, occurrence)
def generate_json(self, top):
with open(self.json_file_name, 'w') as json_file:
json.dump(top, json_file, sort_keys=True, indent=4)
def generate_csv(self, top):
with open(self.csv_file_name, 'w') as csv_file:
csv.writer(csv_file, delimiter=',').writerows(top)
def generate_output(self, top):
if self.print:
self.print_output(top)
if self.json_file_name:
self.generate_json(top)
if self.csv_file_name:
self.generate_csv(top)
| en | 0.671655 | # -*- coding: utf-8 -*- # def show_path_stat(path, top_function, top_size=10): # top = top_function(path, top_size=top_size) # for word, occurrence in top: # print(word, occurrence) | 3.267078 | 3 |
generateKmers.py | LifeWorks/SIEVE | 0 | 6616093 | <filename>generateKmers.py<gh_stars>0
#!/usr/bin/env python
import os
from datetime import datetime
import math
def main():
dataDir = os.getcwd()
outDir = dataDir + "/output"
nodeNum = 1
numPerNode = 16
kmerSize = 14
try:
opts, args = getopt.getopt(sys.argv[1:], "hd:o:n:p:k:", [
"help", "dataDir=", "outDir=", "nodeNum=", "numPerNode=", "kmerSize="])
except getopt.GetoptError:
print('python generateKmers.py -d <data-directory> -o <output-directory> -n <node-number> -p <thread-number-per-node> -k <kmer-size>')
sys.exit(2)
for opt, arg in opts:
if opt in ('-h', "--help"):
print(
'python generateKmers.py -d <data-directory> -o <output-directory> -n <node-number> -p <thread-number-per-node> -k <kmer-size>')
sys.exit()
elif opt in ("-d", "--dataDir"):
dataDir = arg
if outDir == os.getcwd() + "/output":
outDir = dataDir + "/output"
elif opt in ('-o', "--outDir"):
outDir = arg
elif opt in ('-n', "--nodeNum"):
nodeNum = int(arg)
if nodeNum < 0:
print('nodeNum is negative')
sys.exit()
elif opt in ('-p', "--numPerNode"):
numPerNode = int(arg)
if numPerNode < 0:
print('numPerNode is negative')
sys.exit()
elif opt in ("-k", "--kmerSize"):
kmerSize = int(arg)
else:
print(
'python generateKmers.py -d <data-directory> -o <output-directory> -n <node-number> -p <thread-number-per-node> -k <kmer-size>')
sys.exit(2)
return(dataDir, outDir, nodeNum, numPerNode, kmerSize)
if __name__ == "__main__":
dataDir, outDir, nodeNum, numPerNode, kmerSize = main()
# timestamp = str(datetime.now())
# outDir = outDir + '-' + timestamp
try:
os.makedirs(outDir)
except OSError as e:
if e.errno != os.errno.EEXIST:
raise
files = []
for filepath in os.listdir(os.getcwd()):
if filepath.endswith(".fasta") or filepath.endswith(".fa"):
files.append(filepath)
sorted_files = sorted(files, key=os.path.getsize, reverse=True)
batchsize = len(files) // nodeNum + 1
sepFiles = [sorted_files[i:i+batchsize]
for i in range(0, len(sorted_files), batchsize)]
for nodei in range(nodeNum):
jobName = "kmer-batch-%s" % str(nodei)
job_file = os.path.join(outDir, "%s.job" % jobName)
job_list = os.path.join(outDir, "%s.txt" % jobName)
with open(job_list) as fh:
for filename in sepFiles[nodei]:
fh.writelines("python3 KmerFeatures.py -f %s -o %s -m simple -M reduced_alphabet_0 -k %d \n" %
(filename, outDir, kmerSize))
with open(job_file) as fh:
fh.writelines("#!/bin/sh\n")
fh.writelines("#SBATCH --account emslj50978\n")
fh.writelines("#SBATCH --job-name %s\n" % jobName)
fh.writelines("#SBATCH --output=.out/%s.out\n" % jobName)
fh.writelines("#SBATCH --error=.out/%s.err\n" % jobName)
fh.writelines("#SBATCH --time=2-00:00\n")
fh.writelines("#SBATCH --mem=12000\n")
fh.writelines("#SBATCH --nodes 1\n")
fh.writelines("#SBATCH --ntasks-per-node %s\n" % str(numPerNode))
# fh.writelines("#SBATCH --qos=\n")
# fh.writelines("#SBATCH --mail-type=ALL\n")
# fh.writelines("#SBATCH --mail-user=<EMAIL>\n")
fh.writelines("module purge\n")
fh.writelines("module load python/3.8.1\n")
fh.writelines("parallel -j %s < %s\n" % (numPerNode, job_list))
os.system("sbatch %s" % job_file)
| <filename>generateKmers.py<gh_stars>0
#!/usr/bin/env python
import os
from datetime import datetime
import math
def main():
dataDir = os.getcwd()
outDir = dataDir + "/output"
nodeNum = 1
numPerNode = 16
kmerSize = 14
try:
opts, args = getopt.getopt(sys.argv[1:], "hd:o:n:p:k:", [
"help", "dataDir=", "outDir=", "nodeNum=", "numPerNode=", "kmerSize="])
except getopt.GetoptError:
print('python generateKmers.py -d <data-directory> -o <output-directory> -n <node-number> -p <thread-number-per-node> -k <kmer-size>')
sys.exit(2)
for opt, arg in opts:
if opt in ('-h', "--help"):
print(
'python generateKmers.py -d <data-directory> -o <output-directory> -n <node-number> -p <thread-number-per-node> -k <kmer-size>')
sys.exit()
elif opt in ("-d", "--dataDir"):
dataDir = arg
if outDir == os.getcwd() + "/output":
outDir = dataDir + "/output"
elif opt in ('-o', "--outDir"):
outDir = arg
elif opt in ('-n', "--nodeNum"):
nodeNum = int(arg)
if nodeNum < 0:
print('nodeNum is negative')
sys.exit()
elif opt in ('-p', "--numPerNode"):
numPerNode = int(arg)
if numPerNode < 0:
print('numPerNode is negative')
sys.exit()
elif opt in ("-k", "--kmerSize"):
kmerSize = int(arg)
else:
print(
'python generateKmers.py -d <data-directory> -o <output-directory> -n <node-number> -p <thread-number-per-node> -k <kmer-size>')
sys.exit(2)
return(dataDir, outDir, nodeNum, numPerNode, kmerSize)
if __name__ == "__main__":
dataDir, outDir, nodeNum, numPerNode, kmerSize = main()
# timestamp = str(datetime.now())
# outDir = outDir + '-' + timestamp
try:
os.makedirs(outDir)
except OSError as e:
if e.errno != os.errno.EEXIST:
raise
files = []
for filepath in os.listdir(os.getcwd()):
if filepath.endswith(".fasta") or filepath.endswith(".fa"):
files.append(filepath)
sorted_files = sorted(files, key=os.path.getsize, reverse=True)
batchsize = len(files) // nodeNum + 1
sepFiles = [sorted_files[i:i+batchsize]
for i in range(0, len(sorted_files), batchsize)]
for nodei in range(nodeNum):
jobName = "kmer-batch-%s" % str(nodei)
job_file = os.path.join(outDir, "%s.job" % jobName)
job_list = os.path.join(outDir, "%s.txt" % jobName)
with open(job_list) as fh:
for filename in sepFiles[nodei]:
fh.writelines("python3 KmerFeatures.py -f %s -o %s -m simple -M reduced_alphabet_0 -k %d \n" %
(filename, outDir, kmerSize))
with open(job_file) as fh:
fh.writelines("#!/bin/sh\n")
fh.writelines("#SBATCH --account emslj50978\n")
fh.writelines("#SBATCH --job-name %s\n" % jobName)
fh.writelines("#SBATCH --output=.out/%s.out\n" % jobName)
fh.writelines("#SBATCH --error=.out/%s.err\n" % jobName)
fh.writelines("#SBATCH --time=2-00:00\n")
fh.writelines("#SBATCH --mem=12000\n")
fh.writelines("#SBATCH --nodes 1\n")
fh.writelines("#SBATCH --ntasks-per-node %s\n" % str(numPerNode))
# fh.writelines("#SBATCH --qos=\n")
# fh.writelines("#SBATCH --mail-type=ALL\n")
# fh.writelines("#SBATCH --mail-user=<EMAIL>\n")
fh.writelines("module purge\n")
fh.writelines("module load python/3.8.1\n")
fh.writelines("parallel -j %s < %s\n" % (numPerNode, job_list))
os.system("sbatch %s" % job_file)
| zh | 0.138332 | #!/usr/bin/env python # timestamp = str(datetime.now()) # outDir = outDir + '-' + timestamp # fh.writelines("#SBATCH --qos=\n") # fh.writelines("#SBATCH --mail-type=ALL\n") # fh.writelines("#SBATCH --mail-user=<EMAIL>\n") | 2.359487 | 2 |
aws/solutions/PrefixListResource/FunctionCode/lambda_function.py | poibr01wmp/aws-cloudformation-templates | 3,603 | 6616094 | <filename>aws/solutions/PrefixListResource/FunctionCode/lambda_function.py
"""
Get PrefixListID based on PrefixListName
"""
from boto3 import client
from botocore.exceptions import ClientError
import os
import crhelper
# initialise logger
logger = crhelper.log_config({"RequestId": "CONTAINER_INIT"})
logger.info('Logging configured')
# set global to track init failures
init_failed = False
try:
# Place initialization code here
logger.info("Container initialization completed")
except Exception as e:
logger.error(e, exc_info=True)
init_failed = e
def get_pl_id(pl_name, region):
"""
Get PrefixListID for given PrefixListName
"""
logger.info("Get PrefixListId for PrefixListName: %s in %s" % (pl_name, region))
try:
ec2 = client('ec2', region_name=region)
response = ec2.describe_prefix_lists(
Filters=[
{
'Name': 'prefix-list-name',
'Values': [
pl_name
]
}
]
)
except ClientError as e:
raise Exception("Error retrieving prefix list: %s" % e)
prefix_list_id = response['PrefixLists'][0]['PrefixListId']
logger.info("Got %s" % prefix_list_id)
resp = {'PrefixListID': prefix_list_id}
return resp
def create(event, context):
"""
Place your code to handle Create events here.
To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events.
"""
region = os.environ['AWS_REGION']
prefix_list_name = event['ResourceProperties']['PrefixListName']
physical_resource_id = 'RetrievedPrefixList'
response_data = get_pl_id(prefix_list_name, region)
return physical_resource_id, response_data
def update(event, context):
"""
Place your code to handle Update events here
To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events.
"""
region = os.environ['AWS_REGION']
prefix_list_name = event['ResourceProperties']['PrefixListName']
physical_resource_id = 'RetrievedPrefixList'
response_data = get_pl_id(prefix_list_name, region)
return physical_resource_id, response_data
def delete(event, context):
"""
Place your code to handle Delete events here
To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events.
"""
return
def handler(event, context):
"""
Main handler function, passes off it's work to crhelper's cfn_handler
"""
# update the logger with event info
global logger
logger = crhelper.log_config(event)
return crhelper.cfn_handler(event, context, create, update, delete, logger,
init_failed)
| <filename>aws/solutions/PrefixListResource/FunctionCode/lambda_function.py
"""
Get PrefixListID based on PrefixListName
"""
from boto3 import client
from botocore.exceptions import ClientError
import os
import crhelper
# initialise logger
logger = crhelper.log_config({"RequestId": "CONTAINER_INIT"})
logger.info('Logging configured')
# set global to track init failures
init_failed = False
try:
# Place initialization code here
logger.info("Container initialization completed")
except Exception as e:
logger.error(e, exc_info=True)
init_failed = e
def get_pl_id(pl_name, region):
"""
Get PrefixListID for given PrefixListName
"""
logger.info("Get PrefixListId for PrefixListName: %s in %s" % (pl_name, region))
try:
ec2 = client('ec2', region_name=region)
response = ec2.describe_prefix_lists(
Filters=[
{
'Name': 'prefix-list-name',
'Values': [
pl_name
]
}
]
)
except ClientError as e:
raise Exception("Error retrieving prefix list: %s" % e)
prefix_list_id = response['PrefixLists'][0]['PrefixListId']
logger.info("Got %s" % prefix_list_id)
resp = {'PrefixListID': prefix_list_id}
return resp
def create(event, context):
"""
Place your code to handle Create events here.
To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events.
"""
region = os.environ['AWS_REGION']
prefix_list_name = event['ResourceProperties']['PrefixListName']
physical_resource_id = 'RetrievedPrefixList'
response_data = get_pl_id(prefix_list_name, region)
return physical_resource_id, response_data
def update(event, context):
"""
Place your code to handle Update events here
To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events.
"""
region = os.environ['AWS_REGION']
prefix_list_name = event['ResourceProperties']['PrefixListName']
physical_resource_id = 'RetrievedPrefixList'
response_data = get_pl_id(prefix_list_name, region)
return physical_resource_id, response_data
def delete(event, context):
"""
Place your code to handle Delete events here
To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events.
"""
return
def handler(event, context):
"""
Main handler function, passes off it's work to crhelper's cfn_handler
"""
# update the logger with event info
global logger
logger = crhelper.log_config(event)
return crhelper.cfn_handler(event, context, create, update, delete, logger,
init_failed)
| en | 0.752592 | Get PrefixListID based on PrefixListName # initialise logger # set global to track init failures # Place initialization code here Get PrefixListID for given PrefixListName Place your code to handle Create events here. To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events. Place your code to handle Update events here To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events. Place your code to handle Delete events here To return a failure to CloudFormation simply raise an exception, the exception message will be sent to CloudFormation Events. Main handler function, passes off it's work to crhelper's cfn_handler # update the logger with event info | 2.878331 | 3 |
uptrends/models/step_timing_info.py | hpcc-systems/uptrends-python | 0 | 6616095 | <filename>uptrends/models/step_timing_info.py
# coding: utf-8
"""
Uptrends API v4
This document describes Uptrends API version 4. This Swagger environment also lets you execute API methods directly. Please note that this is not a sandbox environment: these API methods operate directly on your actual Uptrends account. For more information, please visit https://www.uptrends.com/api. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class StepTimingInfo(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'description': 'str',
'start_utc': 'datetime',
'end_utc': 'datetime',
'elapsed_milliseconds': 'int',
'delay_milliseconds': 'int',
'sub_timing_infos': 'list[StepTimingInfo]',
'is_valid': 'bool'
}
attribute_map = {
'description': 'Description',
'start_utc': 'StartUtc',
'end_utc': 'EndUtc',
'elapsed_milliseconds': 'ElapsedMilliseconds',
'delay_milliseconds': 'DelayMilliseconds',
'sub_timing_infos': 'SubTimingInfos',
'is_valid': 'IsValid'
}
def __init__(self, description=None, start_utc=None, end_utc=None, elapsed_milliseconds=None, delay_milliseconds=None, sub_timing_infos=None, is_valid=None): # noqa: E501
"""StepTimingInfo - a model defined in Swagger""" # noqa: E501
self._description = None
self._start_utc = None
self._end_utc = None
self._elapsed_milliseconds = None
self._delay_milliseconds = None
self._sub_timing_infos = None
self._is_valid = None
self.discriminator = None
if description is not None:
self.description = description
self.start_utc = start_utc
self.end_utc = end_utc
self.elapsed_milliseconds = elapsed_milliseconds
self.delay_milliseconds = delay_milliseconds
if sub_timing_infos is not None:
self.sub_timing_infos = sub_timing_infos
self.is_valid = is_valid
@property
def description(self):
"""Gets the description of this StepTimingInfo. # noqa: E501
:return: The description of this StepTimingInfo. # noqa: E501
:rtype: str
"""
return self._description
@description.setter
def description(self, description):
"""Sets the description of this StepTimingInfo.
:param description: The description of this StepTimingInfo. # noqa: E501
:type: str
"""
self._description = description
@property
def start_utc(self):
"""Gets the start_utc of this StepTimingInfo. # noqa: E501
:return: The start_utc of this StepTimingInfo. # noqa: E501
:rtype: datetime
"""
return self._start_utc
@start_utc.setter
def start_utc(self, start_utc):
"""Sets the start_utc of this StepTimingInfo.
:param start_utc: The start_utc of this StepTimingInfo. # noqa: E501
:type: datetime
"""
if start_utc is None:
raise ValueError("Invalid value for `start_utc`, must not be `None`") # noqa: E501
self._start_utc = start_utc
@property
def end_utc(self):
"""Gets the end_utc of this StepTimingInfo. # noqa: E501
:return: The end_utc of this StepTimingInfo. # noqa: E501
:rtype: datetime
"""
return self._end_utc
@end_utc.setter
def end_utc(self, end_utc):
"""Sets the end_utc of this StepTimingInfo.
:param end_utc: The end_utc of this StepTimingInfo. # noqa: E501
:type: datetime
"""
if end_utc is None:
raise ValueError("Invalid value for `end_utc`, must not be `None`") # noqa: E501
self._end_utc = end_utc
@property
def elapsed_milliseconds(self):
"""Gets the elapsed_milliseconds of this StepTimingInfo. # noqa: E501
:return: The elapsed_milliseconds of this StepTimingInfo. # noqa: E501
:rtype: int
"""
return self._elapsed_milliseconds
@elapsed_milliseconds.setter
def elapsed_milliseconds(self, elapsed_milliseconds):
"""Sets the elapsed_milliseconds of this StepTimingInfo.
:param elapsed_milliseconds: The elapsed_milliseconds of this StepTimingInfo. # noqa: E501
:type: int
"""
if elapsed_milliseconds is None:
raise ValueError("Invalid value for `elapsed_milliseconds`, must not be `None`") # noqa: E501
self._elapsed_milliseconds = elapsed_milliseconds
@property
def delay_milliseconds(self):
"""Gets the delay_milliseconds of this StepTimingInfo. # noqa: E501
:return: The delay_milliseconds of this StepTimingInfo. # noqa: E501
:rtype: int
"""
return self._delay_milliseconds
@delay_milliseconds.setter
def delay_milliseconds(self, delay_milliseconds):
"""Sets the delay_milliseconds of this StepTimingInfo.
:param delay_milliseconds: The delay_milliseconds of this StepTimingInfo. # noqa: E501
:type: int
"""
if delay_milliseconds is None:
raise ValueError("Invalid value for `delay_milliseconds`, must not be `None`") # noqa: E501
self._delay_milliseconds = delay_milliseconds
@property
def sub_timing_infos(self):
"""Gets the sub_timing_infos of this StepTimingInfo. # noqa: E501
:return: The sub_timing_infos of this StepTimingInfo. # noqa: E501
:rtype: list[StepTimingInfo]
"""
return self._sub_timing_infos
@sub_timing_infos.setter
def sub_timing_infos(self, sub_timing_infos):
"""Sets the sub_timing_infos of this StepTimingInfo.
:param sub_timing_infos: The sub_timing_infos of this StepTimingInfo. # noqa: E501
:type: list[StepTimingInfo]
"""
self._sub_timing_infos = sub_timing_infos
@property
def is_valid(self):
"""Gets the is_valid of this StepTimingInfo. # noqa: E501
If true, this TimingInfo should be counted as part of the sum of its siblings. If false, the TimingInfo should be discarded (e.g. for PreDelays we don't want to count). # noqa: E501
:return: The is_valid of this StepTimingInfo. # noqa: E501
:rtype: bool
"""
return self._is_valid
@is_valid.setter
def is_valid(self, is_valid):
"""Sets the is_valid of this StepTimingInfo.
If true, this TimingInfo should be counted as part of the sum of its siblings. If false, the TimingInfo should be discarded (e.g. for PreDelays we don't want to count). # noqa: E501
:param is_valid: The is_valid of this StepTimingInfo. # noqa: E501
:type: bool
"""
if is_valid is None:
raise ValueError("Invalid value for `is_valid`, must not be `None`") # noqa: E501
self._is_valid = is_valid
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(StepTimingInfo, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, StepTimingInfo):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| <filename>uptrends/models/step_timing_info.py
# coding: utf-8
"""
Uptrends API v4
This document describes Uptrends API version 4. This Swagger environment also lets you execute API methods directly. Please note that this is not a sandbox environment: these API methods operate directly on your actual Uptrends account. For more information, please visit https://www.uptrends.com/api. # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class StepTimingInfo(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'description': 'str',
'start_utc': 'datetime',
'end_utc': 'datetime',
'elapsed_milliseconds': 'int',
'delay_milliseconds': 'int',
'sub_timing_infos': 'list[StepTimingInfo]',
'is_valid': 'bool'
}
attribute_map = {
'description': 'Description',
'start_utc': 'StartUtc',
'end_utc': 'EndUtc',
'elapsed_milliseconds': 'ElapsedMilliseconds',
'delay_milliseconds': 'DelayMilliseconds',
'sub_timing_infos': 'SubTimingInfos',
'is_valid': 'IsValid'
}
def __init__(self, description=None, start_utc=None, end_utc=None, elapsed_milliseconds=None, delay_milliseconds=None, sub_timing_infos=None, is_valid=None): # noqa: E501
"""StepTimingInfo - a model defined in Swagger""" # noqa: E501
self._description = None
self._start_utc = None
self._end_utc = None
self._elapsed_milliseconds = None
self._delay_milliseconds = None
self._sub_timing_infos = None
self._is_valid = None
self.discriminator = None
if description is not None:
self.description = description
self.start_utc = start_utc
self.end_utc = end_utc
self.elapsed_milliseconds = elapsed_milliseconds
self.delay_milliseconds = delay_milliseconds
if sub_timing_infos is not None:
self.sub_timing_infos = sub_timing_infos
self.is_valid = is_valid
@property
def description(self):
"""Gets the description of this StepTimingInfo. # noqa: E501
:return: The description of this StepTimingInfo. # noqa: E501
:rtype: str
"""
return self._description
@description.setter
def description(self, description):
"""Sets the description of this StepTimingInfo.
:param description: The description of this StepTimingInfo. # noqa: E501
:type: str
"""
self._description = description
@property
def start_utc(self):
"""Gets the start_utc of this StepTimingInfo. # noqa: E501
:return: The start_utc of this StepTimingInfo. # noqa: E501
:rtype: datetime
"""
return self._start_utc
@start_utc.setter
def start_utc(self, start_utc):
"""Sets the start_utc of this StepTimingInfo.
:param start_utc: The start_utc of this StepTimingInfo. # noqa: E501
:type: datetime
"""
if start_utc is None:
raise ValueError("Invalid value for `start_utc`, must not be `None`") # noqa: E501
self._start_utc = start_utc
@property
def end_utc(self):
"""Gets the end_utc of this StepTimingInfo. # noqa: E501
:return: The end_utc of this StepTimingInfo. # noqa: E501
:rtype: datetime
"""
return self._end_utc
@end_utc.setter
def end_utc(self, end_utc):
"""Sets the end_utc of this StepTimingInfo.
:param end_utc: The end_utc of this StepTimingInfo. # noqa: E501
:type: datetime
"""
if end_utc is None:
raise ValueError("Invalid value for `end_utc`, must not be `None`") # noqa: E501
self._end_utc = end_utc
@property
def elapsed_milliseconds(self):
"""Gets the elapsed_milliseconds of this StepTimingInfo. # noqa: E501
:return: The elapsed_milliseconds of this StepTimingInfo. # noqa: E501
:rtype: int
"""
return self._elapsed_milliseconds
@elapsed_milliseconds.setter
def elapsed_milliseconds(self, elapsed_milliseconds):
"""Sets the elapsed_milliseconds of this StepTimingInfo.
:param elapsed_milliseconds: The elapsed_milliseconds of this StepTimingInfo. # noqa: E501
:type: int
"""
if elapsed_milliseconds is None:
raise ValueError("Invalid value for `elapsed_milliseconds`, must not be `None`") # noqa: E501
self._elapsed_milliseconds = elapsed_milliseconds
@property
def delay_milliseconds(self):
"""Gets the delay_milliseconds of this StepTimingInfo. # noqa: E501
:return: The delay_milliseconds of this StepTimingInfo. # noqa: E501
:rtype: int
"""
return self._delay_milliseconds
@delay_milliseconds.setter
def delay_milliseconds(self, delay_milliseconds):
"""Sets the delay_milliseconds of this StepTimingInfo.
:param delay_milliseconds: The delay_milliseconds of this StepTimingInfo. # noqa: E501
:type: int
"""
if delay_milliseconds is None:
raise ValueError("Invalid value for `delay_milliseconds`, must not be `None`") # noqa: E501
self._delay_milliseconds = delay_milliseconds
@property
def sub_timing_infos(self):
"""Gets the sub_timing_infos of this StepTimingInfo. # noqa: E501
:return: The sub_timing_infos of this StepTimingInfo. # noqa: E501
:rtype: list[StepTimingInfo]
"""
return self._sub_timing_infos
@sub_timing_infos.setter
def sub_timing_infos(self, sub_timing_infos):
"""Sets the sub_timing_infos of this StepTimingInfo.
:param sub_timing_infos: The sub_timing_infos of this StepTimingInfo. # noqa: E501
:type: list[StepTimingInfo]
"""
self._sub_timing_infos = sub_timing_infos
@property
def is_valid(self):
"""Gets the is_valid of this StepTimingInfo. # noqa: E501
If true, this TimingInfo should be counted as part of the sum of its siblings. If false, the TimingInfo should be discarded (e.g. for PreDelays we don't want to count). # noqa: E501
:return: The is_valid of this StepTimingInfo. # noqa: E501
:rtype: bool
"""
return self._is_valid
@is_valid.setter
def is_valid(self, is_valid):
"""Sets the is_valid of this StepTimingInfo.
If true, this TimingInfo should be counted as part of the sum of its siblings. If false, the TimingInfo should be discarded (e.g. for PreDelays we don't want to count). # noqa: E501
:param is_valid: The is_valid of this StepTimingInfo. # noqa: E501
:type: bool
"""
if is_valid is None:
raise ValueError("Invalid value for `is_valid`, must not be `None`") # noqa: E501
self._is_valid = is_valid
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(StepTimingInfo, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, StepTimingInfo):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| en | 0.581825 | # coding: utf-8 Uptrends API v4 This document describes Uptrends API version 4. This Swagger environment also lets you execute API methods directly. Please note that this is not a sandbox environment: these API methods operate directly on your actual Uptrends account. For more information, please visit https://www.uptrends.com/api. # noqa: E501 OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git # noqa: F401 NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. # noqa: E501 StepTimingInfo - a model defined in Swagger # noqa: E501 Gets the description of this StepTimingInfo. # noqa: E501 :return: The description of this StepTimingInfo. # noqa: E501 :rtype: str Sets the description of this StepTimingInfo. :param description: The description of this StepTimingInfo. # noqa: E501 :type: str Gets the start_utc of this StepTimingInfo. # noqa: E501 :return: The start_utc of this StepTimingInfo. # noqa: E501 :rtype: datetime Sets the start_utc of this StepTimingInfo. :param start_utc: The start_utc of this StepTimingInfo. # noqa: E501 :type: datetime # noqa: E501 Gets the end_utc of this StepTimingInfo. # noqa: E501 :return: The end_utc of this StepTimingInfo. # noqa: E501 :rtype: datetime Sets the end_utc of this StepTimingInfo. :param end_utc: The end_utc of this StepTimingInfo. # noqa: E501 :type: datetime # noqa: E501 Gets the elapsed_milliseconds of this StepTimingInfo. # noqa: E501 :return: The elapsed_milliseconds of this StepTimingInfo. # noqa: E501 :rtype: int Sets the elapsed_milliseconds of this StepTimingInfo. :param elapsed_milliseconds: The elapsed_milliseconds of this StepTimingInfo. # noqa: E501 :type: int # noqa: E501 Gets the delay_milliseconds of this StepTimingInfo. # noqa: E501 :return: The delay_milliseconds of this StepTimingInfo. # noqa: E501 :rtype: int Sets the delay_milliseconds of this StepTimingInfo. :param delay_milliseconds: The delay_milliseconds of this StepTimingInfo. # noqa: E501 :type: int # noqa: E501 Gets the sub_timing_infos of this StepTimingInfo. # noqa: E501 :return: The sub_timing_infos of this StepTimingInfo. # noqa: E501 :rtype: list[StepTimingInfo] Sets the sub_timing_infos of this StepTimingInfo. :param sub_timing_infos: The sub_timing_infos of this StepTimingInfo. # noqa: E501 :type: list[StepTimingInfo] Gets the is_valid of this StepTimingInfo. # noqa: E501 If true, this TimingInfo should be counted as part of the sum of its siblings. If false, the TimingInfo should be discarded (e.g. for PreDelays we don't want to count). # noqa: E501 :return: The is_valid of this StepTimingInfo. # noqa: E501 :rtype: bool Sets the is_valid of this StepTimingInfo. If true, this TimingInfo should be counted as part of the sum of its siblings. If false, the TimingInfo should be discarded (e.g. for PreDelays we don't want to count). # noqa: E501 :param is_valid: The is_valid of this StepTimingInfo. # noqa: E501 :type: bool # noqa: E501 Returns the model properties as a dict Returns the string representation of the model For `print` and `pprint` Returns true if both objects are equal Returns true if both objects are not equal | 1.62947 | 2 |
cia_serve/webserv.py | cheeseypi/cia-serve | 0 | 6616096 | <reponame>cheeseypi/cia-serve
import argparse
import glob
import os
from flask import Flask
app = Flask(__name__)
SCAN_DIRECTORY = '.'
@app.route('/')
def homepage():
romdir = '**/*.cia'
roms = glob.glob(romdir, recursive=True)
roms = list([path.split(os.path.sep) for path in roms])
return '<br/>'.join([' | '.join(path) for path in roms])
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='A small HTTP Server to host '+
'CIA files for install with FBI')
parser.add_argument('--port', '-p', help='Port to run the webserver on. '+
'Defaults to 5000', dest='port', action='store',
type=int, default=5000)
parser.add_argument('--dir', '-d', help='Directory to scan for CIA files. '+
'Defaults to current directory', dest='directory',
action='store', type=str, default='.')
args = parser.parse_args()
port = args.port
SCAN_DIRECTORY = args.directory
os.chdir(SCAN_DIRECTORY)
app.run('0.0.0.0', port=port)
| import argparse
import glob
import os
from flask import Flask
app = Flask(__name__)
SCAN_DIRECTORY = '.'
@app.route('/')
def homepage():
romdir = '**/*.cia'
roms = glob.glob(romdir, recursive=True)
roms = list([path.split(os.path.sep) for path in roms])
return '<br/>'.join([' | '.join(path) for path in roms])
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='A small HTTP Server to host '+
'CIA files for install with FBI')
parser.add_argument('--port', '-p', help='Port to run the webserver on. '+
'Defaults to 5000', dest='port', action='store',
type=int, default=5000)
parser.add_argument('--dir', '-d', help='Directory to scan for CIA files. '+
'Defaults to current directory', dest='directory',
action='store', type=str, default='.')
args = parser.parse_args()
port = args.port
SCAN_DIRECTORY = args.directory
os.chdir(SCAN_DIRECTORY)
app.run('0.0.0.0', port=port) | none | 1 | 2.669788 | 3 | |
nutree/dot.py | mar10/nutree | 7 | 6616097 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# (c) 2021-2022 <NAME>; see https://github.com/mar10/nutree
# Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php
"""
Functions and declarations to implement `Graphviz <https://graphviz.org/doc/info/lang.html>`_.
"""
from pathlib import Path, PurePath
from typing import IO, TYPE_CHECKING, Generator, Union
from .common import MapperCallbackType, call_mapper
if TYPE_CHECKING: # Imported by type checkers, but prevent circular includes
from .node import Node
from .tree import Tree
try:
import pydot
except ImportError:
pydot = None
def node_to_dot(
node: "Node",
*,
add_self=False,
unique_nodes=True,
graph_attrs=None,
node_attrs=None,
edge_attrs=None,
node_mapper=None,
edge_mapper=None,
) -> Generator[str, None, None]:
"""Generate DOT formatted output line-by-line.
https://graphviz.org/doc/info/attrs.html
Args:
mapper (method):
add_self (bool):
unique_nodes (bool):
"""
indent = " "
name = node.tree.name
used_keys = set()
def _key(n: "Node"):
return n._data_id if unique_nodes else n._node_id
def _attr_str(attr_def: dict, mapper=None, node=None):
if mapper:
if attr_def is None:
attr_def = {}
call_mapper(mapper, node, attr_def)
if not attr_def:
return ""
attr_str = " ".join(f'{k}="{v}"' for k, v in attr_def.items())
return " [" + attr_str + "]"
yield "# Generator: https://github.com/mar10/nutree/"
yield f'digraph "{name}" {{'
if graph_attrs or node_attrs or edge_attrs:
yield ""
yield f"{indent}# Default Definitions"
if graph_attrs:
yield f"{indent}graph {_attr_str(graph_attrs)}"
if node_attrs:
yield f"{indent}node {_attr_str(node_attrs)}"
if edge_attrs:
yield f"{indent}edge {_attr_str(edge_attrs)}"
yield ""
yield f"{indent}# Node Definitions"
if add_self:
if node._parent:
attr_def = {}
else: # __root__ inherits tree name by default
attr_def = {"label": f"{name}", "shape": "box"}
attr_str = _attr_str(attr_def, node_mapper, node)
yield f"{indent}{_key(node)}{attr_str}"
for n in node:
if unique_nodes:
key = n._data_id
if key in used_keys:
continue
used_keys.add(key)
else:
key = n._node_id
attr_def = {"label": n.name}
attr_str = _attr_str(attr_def, node_mapper, n)
yield f"{indent}{key}{attr_str}"
yield ""
yield f"{indent}# Edge Definitions"
for n in node:
if not add_self and n._parent is node:
continue
attr_def = {}
attr_str = _attr_str(attr_def, edge_mapper, n)
yield f"{indent}{_key(n._parent)} -> {_key(n)}{attr_str}"
yield "}"
def tree_to_dotfile(
tree: "Tree",
target: Union[IO[str], str, PurePath],
*,
format=None,
add_root=True,
unique_nodes=True,
graph_attrs=None,
node_attrs=None,
edge_attrs=None,
node_mapper: MapperCallbackType = None,
edge_mapper: MapperCallbackType = None,
):
if isinstance(target, str):
target = Path(target)
if isinstance(target, PurePath):
if format:
dot_path = target.with_suffix(".gv")
else:
dot_path = target
# print("write", dot_path)
with open(dot_path, "w") as fp:
tree_to_dotfile(
tree=tree,
target=fp,
add_root=add_root,
unique_nodes=unique_nodes,
graph_attrs=graph_attrs,
node_attrs=node_attrs,
edge_attrs=edge_attrs,
node_mapper=node_mapper,
edge_mapper=edge_mapper,
)
if format:
if not pydot:
raise RuntimeError("Need pydot installed to convert DOT output.")
# print("convert", dot_path, format, target)
pydot.call_graphviz(
"dot",
[
"-o",
target,
f"-T{format}",
dot_path,
],
working_dir=target.parent,
)
# https://graphviz.org/docs/outputs/
# check_call(f"dot -h")
# check_call(f"dot -O -T{format} {target}")
# check_call(f"dot -o{target}.{format} -T{format} {target}")
# Remove DOT file that was created as input for the conversion
# TODO:
# dot_path.unlink()
return
# `target` is suppoesed to be an open, writable filelike
if format:
raise RuntimeError("Need a filepath to convert DOT output.")
with tree:
for line in tree.to_dot(
add_root=add_root,
unique_nodes=unique_nodes,
graph_attrs=graph_attrs,
node_attrs=node_attrs,
edge_attrs=edge_attrs,
node_mapper=node_mapper,
edge_mapper=edge_mapper,
):
target.write(line + "\n")
return
| # -*- coding: utf-8 -*-
# (c) 2021-2022 <NAME>; see https://github.com/mar10/nutree
# Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php
"""
Functions and declarations to implement `Graphviz <https://graphviz.org/doc/info/lang.html>`_.
"""
from pathlib import Path, PurePath
from typing import IO, TYPE_CHECKING, Generator, Union
from .common import MapperCallbackType, call_mapper
if TYPE_CHECKING: # Imported by type checkers, but prevent circular includes
from .node import Node
from .tree import Tree
try:
import pydot
except ImportError:
pydot = None
def node_to_dot(
node: "Node",
*,
add_self=False,
unique_nodes=True,
graph_attrs=None,
node_attrs=None,
edge_attrs=None,
node_mapper=None,
edge_mapper=None,
) -> Generator[str, None, None]:
"""Generate DOT formatted output line-by-line.
https://graphviz.org/doc/info/attrs.html
Args:
mapper (method):
add_self (bool):
unique_nodes (bool):
"""
indent = " "
name = node.tree.name
used_keys = set()
def _key(n: "Node"):
return n._data_id if unique_nodes else n._node_id
def _attr_str(attr_def: dict, mapper=None, node=None):
if mapper:
if attr_def is None:
attr_def = {}
call_mapper(mapper, node, attr_def)
if not attr_def:
return ""
attr_str = " ".join(f'{k}="{v}"' for k, v in attr_def.items())
return " [" + attr_str + "]"
yield "# Generator: https://github.com/mar10/nutree/"
yield f'digraph "{name}" {{'
if graph_attrs or node_attrs or edge_attrs:
yield ""
yield f"{indent}# Default Definitions"
if graph_attrs:
yield f"{indent}graph {_attr_str(graph_attrs)}"
if node_attrs:
yield f"{indent}node {_attr_str(node_attrs)}"
if edge_attrs:
yield f"{indent}edge {_attr_str(edge_attrs)}"
yield ""
yield f"{indent}# Node Definitions"
if add_self:
if node._parent:
attr_def = {}
else: # __root__ inherits tree name by default
attr_def = {"label": f"{name}", "shape": "box"}
attr_str = _attr_str(attr_def, node_mapper, node)
yield f"{indent}{_key(node)}{attr_str}"
for n in node:
if unique_nodes:
key = n._data_id
if key in used_keys:
continue
used_keys.add(key)
else:
key = n._node_id
attr_def = {"label": n.name}
attr_str = _attr_str(attr_def, node_mapper, n)
yield f"{indent}{key}{attr_str}"
yield ""
yield f"{indent}# Edge Definitions"
for n in node:
if not add_self and n._parent is node:
continue
attr_def = {}
attr_str = _attr_str(attr_def, edge_mapper, n)
yield f"{indent}{_key(n._parent)} -> {_key(n)}{attr_str}"
yield "}"
def tree_to_dotfile(
tree: "Tree",
target: Union[IO[str], str, PurePath],
*,
format=None,
add_root=True,
unique_nodes=True,
graph_attrs=None,
node_attrs=None,
edge_attrs=None,
node_mapper: MapperCallbackType = None,
edge_mapper: MapperCallbackType = None,
):
if isinstance(target, str):
target = Path(target)
if isinstance(target, PurePath):
if format:
dot_path = target.with_suffix(".gv")
else:
dot_path = target
# print("write", dot_path)
with open(dot_path, "w") as fp:
tree_to_dotfile(
tree=tree,
target=fp,
add_root=add_root,
unique_nodes=unique_nodes,
graph_attrs=graph_attrs,
node_attrs=node_attrs,
edge_attrs=edge_attrs,
node_mapper=node_mapper,
edge_mapper=edge_mapper,
)
if format:
if not pydot:
raise RuntimeError("Need pydot installed to convert DOT output.")
# print("convert", dot_path, format, target)
pydot.call_graphviz(
"dot",
[
"-o",
target,
f"-T{format}",
dot_path,
],
working_dir=target.parent,
)
# https://graphviz.org/docs/outputs/
# check_call(f"dot -h")
# check_call(f"dot -O -T{format} {target}")
# check_call(f"dot -o{target}.{format} -T{format} {target}")
# Remove DOT file that was created as input for the conversion
# TODO:
# dot_path.unlink()
return
# `target` is suppoesed to be an open, writable filelike
if format:
raise RuntimeError("Need a filepath to convert DOT output.")
with tree:
for line in tree.to_dot(
add_root=add_root,
unique_nodes=unique_nodes,
graph_attrs=graph_attrs,
node_attrs=node_attrs,
edge_attrs=edge_attrs,
node_mapper=node_mapper,
edge_mapper=edge_mapper,
):
target.write(line + "\n")
return | en | 0.656761 | # -*- coding: utf-8 -*- # (c) 2021-2022 <NAME>; see https://github.com/mar10/nutree # Licensed under the MIT license: https://www.opensource.org/licenses/mit-license.php Functions and declarations to implement `Graphviz <https://graphviz.org/doc/info/lang.html>`_. # Imported by type checkers, but prevent circular includes Generate DOT formatted output line-by-line. https://graphviz.org/doc/info/attrs.html Args: mapper (method): add_self (bool): unique_nodes (bool): # Default Definitions" # Node Definitions" # __root__ inherits tree name by default # Edge Definitions" # print("write", dot_path) # print("convert", dot_path, format, target) # https://graphviz.org/docs/outputs/ # check_call(f"dot -h") # check_call(f"dot -O -T{format} {target}") # check_call(f"dot -o{target}.{format} -T{format} {target}") # Remove DOT file that was created as input for the conversion # TODO: # dot_path.unlink() # `target` is suppoesed to be an open, writable filelike | 2.352108 | 2 |
pulse/python_pulse_ssr/pulse_ssr/pulse_ssr.py | iorodeo/nano_ssr_software | 0 | 6616098 | <gh_stars>0
"""
Provides a serial interface to Arduinos running the pulse_ssr_firmware
for pulsing solid state relays.
Author: <NAME>, IO Rodeo Inc.
Copyright 2010 IO Rodeo 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 governing permissions and
limitations under the License.
"""
import time
import serial
RESET_SLEEP_DT = 2.0
class PulseSSR(serial.Serial):
def __init__(self,*arg,**kwargs):
try:
self.resetSleep = kwargs.pop('reset_sleep')
except KeyError:
self.resetSleep = True
super(PulseSSR,self).__init__(*arg,**kwargs)
self.cmdId = {
'stop' : 0,
'start' : 1,
'startAll' : 2,
'stopAll' : 3,
'setPeriod' : 4,
'getPeriod' : 5,
'setNumPulse' : 6,
'getNumPulse' : 7,
'getRunning' : 8,
}
if self.resetSleep:
time.sleep(RESET_SLEEP_DT)
def sendCmd(self,cmd):
self.write(cmd)
def readValue(self):
"""
Read a value from the device.
"""
line = self.readline()
line = line.strip()
return line
def readInt(self):
"""
Read a single integer or list of integers separated by commas.
"""
value = self.readValue()
value = int(value)
return value
def setPeriod(self,n,period):
"""
Set period of relay n to the value given by period in milliseconds.
"""
_n = int(n)
assert _n >= 0, 'pin number must be >= 0'
_period = int(period)
assert _period > 0, 'period must be > 0'
cmd = '[%d,%d,%d]'%(self.cmdId['setPeriod'],_n,_period)
self.sendCmd(cmd)
def getPeriod(self,n):
"""
Returns the curren period setting for relay n in milliseconds
"""
_n = int(n)
assert _n >=0, 'pin number must be >= 0'
cmd = '[%d,%d]'%(self.cmdId['getPeriod'],_n)
self.sendCmd(cmd)
period = self.readInt()
return period
def setNumPulse(self,n,numPulse):
"""
Set the number of pulses (per start event) for relay n.
"""
_n = int(n)
assert _n >= 0, 'pin number must be >= 0'
_numPulse = int(numPulse)
assert _numPulse >= 0, 'number of pulses must be >= 0'
cmd = '[%d,%d,%d]'%(self.cmdId['setNumPulse'],_n,_numPulse)
self.sendCmd(cmd)
def getNumPulse(self,n):
"""
Returns the numbers of pulses (per start event) for relay n.
"""
_n = int(n)
assert _n >= 0, 'pin number must be >= 0'
cmd = '[%d,%d]'%(self.cmdId['getNumPulse'],_n)
self.sendCmd(cmd)
numPulse = self.readInt()
return numPulse
def getRunning(self,n):
"""
Returns true is the relay is running (sending out pulses) and false otherwise.
"""
_n = int(n)
assert n >= 0, 'pin number must be >= 0'
cmd = '[%d,%d]'%(self.cmdId['getRunning'],_n)
self.sendCmd(cmd)
running = self.readInt()
if running != 0:
running = True
else:
running = False
return running
def start(self,n):
"""
Start pulses on relay n
"""
_n = int(n)
assert _n >= 0, 'pin number must be >= 0'
cmd = '[%d,%d]'%(self.cmdId['start'],_n)
self.sendCmd(cmd)
def stop(self,n):
"""
Stop pulses on relay n
"""
_n = int(n)
assert _n >= 0, 'pin number must be >= 0'
cmd = '[%d,%d]'%(self.cmdId['stop'],_n)
self.sendCmd(cmd)
def startAll(self):
"""
Start all solid state relays pulsing.
"""
cmd = '[%d]'%(self.cmdId['startAll'],)
self.sendCmd(cmd)
| """
Provides a serial interface to Arduinos running the pulse_ssr_firmware
for pulsing solid state relays.
Author: <NAME>, IO Rodeo Inc.
Copyright 2010 IO Rodeo 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 governing permissions and
limitations under the License.
"""
import time
import serial
RESET_SLEEP_DT = 2.0
class PulseSSR(serial.Serial):
def __init__(self,*arg,**kwargs):
try:
self.resetSleep = kwargs.pop('reset_sleep')
except KeyError:
self.resetSleep = True
super(PulseSSR,self).__init__(*arg,**kwargs)
self.cmdId = {
'stop' : 0,
'start' : 1,
'startAll' : 2,
'stopAll' : 3,
'setPeriod' : 4,
'getPeriod' : 5,
'setNumPulse' : 6,
'getNumPulse' : 7,
'getRunning' : 8,
}
if self.resetSleep:
time.sleep(RESET_SLEEP_DT)
def sendCmd(self,cmd):
self.write(cmd)
def readValue(self):
"""
Read a value from the device.
"""
line = self.readline()
line = line.strip()
return line
def readInt(self):
"""
Read a single integer or list of integers separated by commas.
"""
value = self.readValue()
value = int(value)
return value
def setPeriod(self,n,period):
"""
Set period of relay n to the value given by period in milliseconds.
"""
_n = int(n)
assert _n >= 0, 'pin number must be >= 0'
_period = int(period)
assert _period > 0, 'period must be > 0'
cmd = '[%d,%d,%d]'%(self.cmdId['setPeriod'],_n,_period)
self.sendCmd(cmd)
def getPeriod(self,n):
"""
Returns the curren period setting for relay n in milliseconds
"""
_n = int(n)
assert _n >=0, 'pin number must be >= 0'
cmd = '[%d,%d]'%(self.cmdId['getPeriod'],_n)
self.sendCmd(cmd)
period = self.readInt()
return period
def setNumPulse(self,n,numPulse):
"""
Set the number of pulses (per start event) for relay n.
"""
_n = int(n)
assert _n >= 0, 'pin number must be >= 0'
_numPulse = int(numPulse)
assert _numPulse >= 0, 'number of pulses must be >= 0'
cmd = '[%d,%d,%d]'%(self.cmdId['setNumPulse'],_n,_numPulse)
self.sendCmd(cmd)
def getNumPulse(self,n):
"""
Returns the numbers of pulses (per start event) for relay n.
"""
_n = int(n)
assert _n >= 0, 'pin number must be >= 0'
cmd = '[%d,%d]'%(self.cmdId['getNumPulse'],_n)
self.sendCmd(cmd)
numPulse = self.readInt()
return numPulse
def getRunning(self,n):
"""
Returns true is the relay is running (sending out pulses) and false otherwise.
"""
_n = int(n)
assert n >= 0, 'pin number must be >= 0'
cmd = '[%d,%d]'%(self.cmdId['getRunning'],_n)
self.sendCmd(cmd)
running = self.readInt()
if running != 0:
running = True
else:
running = False
return running
def start(self,n):
"""
Start pulses on relay n
"""
_n = int(n)
assert _n >= 0, 'pin number must be >= 0'
cmd = '[%d,%d]'%(self.cmdId['start'],_n)
self.sendCmd(cmd)
def stop(self,n):
"""
Stop pulses on relay n
"""
_n = int(n)
assert _n >= 0, 'pin number must be >= 0'
cmd = '[%d,%d]'%(self.cmdId['stop'],_n)
self.sendCmd(cmd)
def startAll(self):
"""
Start all solid state relays pulsing.
"""
cmd = '[%d]'%(self.cmdId['startAll'],)
self.sendCmd(cmd) | en | 0.834461 | Provides a serial interface to Arduinos running the pulse_ssr_firmware for pulsing solid state relays. Author: <NAME>, IO Rodeo Inc. Copyright 2010 IO Rodeo 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 governing permissions and limitations under the License. Read a value from the device. Read a single integer or list of integers separated by commas. Set period of relay n to the value given by period in milliseconds. Returns the curren period setting for relay n in milliseconds Set the number of pulses (per start event) for relay n. Returns the numbers of pulses (per start event) for relay n. Returns true is the relay is running (sending out pulses) and false otherwise. Start pulses on relay n Stop pulses on relay n Start all solid state relays pulsing. | 2.931637 | 3 |
apps/othercontents/models.py | Sunbird-Ed/evolve-api | 1 | 6616099 | <gh_stars>1-10
from django.db import models
from apps.configuration.models import Book, Grade, State, Medium, Subject
from django.contrib.auth.models import User
# from user.models import EvolveUser
from apps.dataupload.models import Section,SubSection,Chapter,ChapterKeyword,SectionKeyword,SubSectionKeyword,SubSubSection,SubSubSectionKeyword
from apps.hardspot.models import HardSpot
from django.core.validators import MaxValueValidator
from evolve.custom_storage import MediaStorage
from datetime import datetime
class Tags(models.Model):
tag_name = models.CharField(max_length=200)
code_name = models.SlugField(max_length=200,unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.tag_name
class Meta:
verbose_name='Tag'
class SchoolName(models.Model):
school_name = models.CharField(max_length=500)
def __str__(self):
return self.school_name
class OtherContributors(models.Model):
tags = models.ForeignKey(Tags,on_delete=models.CASCADE)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200,
blank=True,
null=True)
email = models.EmailField(blank=True, null=True)
mobile =models.CharField(max_length=10,
blank=False,
null=False)
school_name= models.ForeignKey(SchoolName,on_delete=models.CASCADE,blank=True,null=True)
city_name = models.CharField(max_length=200,
blank=True,
null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.first_name
class Meta:
verbose_name='Other Contributor'
class OtherContent(models.Model):
tags = models.ForeignKey(Tags,on_delete=models.CASCADE)
# hard_spot=models.ForeignKey(HardSpot,on_delete=models.CASCADE,null=True,blank=True)
chapter=models.ForeignKey(Chapter,on_delete=models.CASCADE,null=True,blank=True)
section=models.ForeignKey(Section,on_delete=models.CASCADE,null=True,blank=True)
sub_section=models.ForeignKey(SubSection,on_delete=models.CASCADE,null=True,blank=True)
sub_sub_section=models.ForeignKey(SubSubSection,on_delete=models.CASCADE,null=True,blank=True)
content_name = models.TextField()
file_url = models.URLField(max_length=1000, blank=True,null=True)
# file_url = models.URLField(max_length=1000, blank=True,null=True)
text = models.TextField(blank=True,null=True)
approved = models.BooleanField(default=False)
approved_by = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='%(class)s_approved_by',
null=True,
blank=True)
# rating = models.PositiveIntegerField(validators=[MaxValueValidator(5)],
# blank=True,null=True)
# rated_by = models.ForeignKey(User,
# on_delete=models.CASCADE,
# related_name='%(class)s_rated_by',null=True,blank=True)
comment = models.CharField(max_length=200, null=True, blank=True)
chapter_keywords=models.ManyToManyField(ChapterKeyword,blank=True)
section_keywords=models.ManyToManyField(SectionKeyword,blank=True)
sub_section_keywords=models.ManyToManyField(SubSectionKeyword,blank=True)
sub_sub_section_keywords=models.ManyToManyField(SubSubSectionKeyword,blank=True)
content_contributors=models.ForeignKey(OtherContributors,on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def save(self, *args, **kwargs):
if self.file_url == None and self.text == None and self.approved_by==None:
raise ValueError("document url and text ,both null values are Not allowed")
elif (self.file_url != None and self.text != None and self.approved_by == None):
raise ValueError("document url and text ,both values are Not allowed")
else:
super().save(*args, **kwargs)
def __str__(self):
return self.content_name
class Meta:
verbose_name='Other Content'
class Job(models.Model):
task_id = models.CharField(max_length=200)
status = models.CharField(max_length=200)
def __str__(self):
return self.task_id
| from django.db import models
from apps.configuration.models import Book, Grade, State, Medium, Subject
from django.contrib.auth.models import User
# from user.models import EvolveUser
from apps.dataupload.models import Section,SubSection,Chapter,ChapterKeyword,SectionKeyword,SubSectionKeyword,SubSubSection,SubSubSectionKeyword
from apps.hardspot.models import HardSpot
from django.core.validators import MaxValueValidator
from evolve.custom_storage import MediaStorage
from datetime import datetime
class Tags(models.Model):
tag_name = models.CharField(max_length=200)
code_name = models.SlugField(max_length=200,unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.tag_name
class Meta:
verbose_name='Tag'
class SchoolName(models.Model):
school_name = models.CharField(max_length=500)
def __str__(self):
return self.school_name
class OtherContributors(models.Model):
tags = models.ForeignKey(Tags,on_delete=models.CASCADE)
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200,
blank=True,
null=True)
email = models.EmailField(blank=True, null=True)
mobile =models.CharField(max_length=10,
blank=False,
null=False)
school_name= models.ForeignKey(SchoolName,on_delete=models.CASCADE,blank=True,null=True)
city_name = models.CharField(max_length=200,
blank=True,
null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.first_name
class Meta:
verbose_name='Other Contributor'
class OtherContent(models.Model):
tags = models.ForeignKey(Tags,on_delete=models.CASCADE)
# hard_spot=models.ForeignKey(HardSpot,on_delete=models.CASCADE,null=True,blank=True)
chapter=models.ForeignKey(Chapter,on_delete=models.CASCADE,null=True,blank=True)
section=models.ForeignKey(Section,on_delete=models.CASCADE,null=True,blank=True)
sub_section=models.ForeignKey(SubSection,on_delete=models.CASCADE,null=True,blank=True)
sub_sub_section=models.ForeignKey(SubSubSection,on_delete=models.CASCADE,null=True,blank=True)
content_name = models.TextField()
file_url = models.URLField(max_length=1000, blank=True,null=True)
# file_url = models.URLField(max_length=1000, blank=True,null=True)
text = models.TextField(blank=True,null=True)
approved = models.BooleanField(default=False)
approved_by = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='%(class)s_approved_by',
null=True,
blank=True)
# rating = models.PositiveIntegerField(validators=[MaxValueValidator(5)],
# blank=True,null=True)
# rated_by = models.ForeignKey(User,
# on_delete=models.CASCADE,
# related_name='%(class)s_rated_by',null=True,blank=True)
comment = models.CharField(max_length=200, null=True, blank=True)
chapter_keywords=models.ManyToManyField(ChapterKeyword,blank=True)
section_keywords=models.ManyToManyField(SectionKeyword,blank=True)
sub_section_keywords=models.ManyToManyField(SubSectionKeyword,blank=True)
sub_sub_section_keywords=models.ManyToManyField(SubSubSectionKeyword,blank=True)
content_contributors=models.ForeignKey(OtherContributors,on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def save(self, *args, **kwargs):
if self.file_url == None and self.text == None and self.approved_by==None:
raise ValueError("document url and text ,both null values are Not allowed")
elif (self.file_url != None and self.text != None and self.approved_by == None):
raise ValueError("document url and text ,both values are Not allowed")
else:
super().save(*args, **kwargs)
def __str__(self):
return self.content_name
class Meta:
verbose_name='Other Content'
class Job(models.Model):
task_id = models.CharField(max_length=200)
status = models.CharField(max_length=200)
def __str__(self):
return self.task_id | en | 0.379749 | # from user.models import EvolveUser # hard_spot=models.ForeignKey(HardSpot,on_delete=models.CASCADE,null=True,blank=True) # file_url = models.URLField(max_length=1000, blank=True,null=True) # rating = models.PositiveIntegerField(validators=[MaxValueValidator(5)], # blank=True,null=True) # rated_by = models.ForeignKey(User, # on_delete=models.CASCADE, # related_name='%(class)s_rated_by',null=True,blank=True) | 1.878756 | 2 |
innopoints/views/variety.py | Innopoints/backend | 1 | 6616100 | <gh_stars>1-10
"""Views related to the Variety, StockChange, Size and Color models.
Variety:
- POST /products/{product_id}/varieties
- PATCH /products/{product_id}/varieties/{variety_id}
- DELETE /products/{product_id}/varieties/{variety_id}
- POST /products/{product_id}/varieties/{variety_id}/purchase
StockChange:
- GET /stock_changes
- GET /stock_changes/for_review
- PATCH /stock_changes/{stock_change_id}/status
Size:
- GET /sizes
- POST /sizes
Color:
- GET /colors
- POST /colors
"""
import math
import logging
from flask import request, jsonify
from flask.views import MethodView
from flask_login import login_required, current_user
from marshmallow import ValidationError
from sqlalchemy.exc import IntegrityError
from innopoints.extensions import db
from innopoints.blueprints import api
from innopoints.core.helpers import abort, admin_required
from innopoints.core.notifications import notify_all, notify, remove_notifications
from innopoints.models import (
Account,
Color,
NotificationType,
Product,
Size,
StockChange,
StockChangeStatus,
Transaction,
Variety,
)
from innopoints.schemas import (
ColorSchema,
SizeSchema,
StockChangeSchema,
VarietySchema,
)
NO_PAYLOAD = ('', 204)
log = logging.getLogger(__name__)
@api.route('/products/<int:product_id>/varieties', methods=['POST'])
@admin_required
def create_variety(product_id):
"""Create a new variety."""
product = Product.query.get_or_404(product_id)
in_schema = VarietySchema(exclude=('id', 'product_id', 'product',
'images.variety_id', 'stock_changes.variety_id',),
context={'user': current_user})
try:
new_variety = in_schema.load(request.json)
except ValidationError as err:
abort(400, {'message': err.messages})
try:
new_variety.product = product
db.session.add(new_variety)
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
out_schema = VarietySchema(exclude=('product_id',
'product',
'images.variety_id',
'images.id',
'stock_changes'))
return out_schema.jsonify(new_variety)
class VarietyAPI(MethodView):
"""REST views for a particular instance of the Variety model."""
@admin_required
def patch(self, product_id, variety_id):
"""Update the given variety."""
product = Product.query.get_or_404(product_id)
variety = Variety.query.get_or_404(variety_id)
if variety.product != product:
abort(400, {'message': 'The specified product and variety are unrelated.'})
in_schema = VarietySchema(exclude=('id', 'product_id', 'stock_changes.variety_id'),
context={'update': True})
amount = request.json.pop('amount', None)
try:
updated_variety = in_schema.load(request.json, instance=variety, partial=True)
except ValidationError as err:
abort(400, {'message': err.messages})
if amount is not None:
diff = amount - variety.amount
if diff != 0:
stock_change = StockChange(amount=diff,
status=StockChangeStatus.carried_out,
account=current_user,
variety_id=updated_variety.id)
db.session.add(stock_change)
try:
db.session.add(updated_variety)
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
out_schema = VarietySchema(exclude=('product_id', 'stock_changes', 'product', 'purchases'))
return out_schema.jsonify(updated_variety)
@admin_required
def delete(self, product_id, variety_id):
"""Delete the variety."""
product = Product.query.get_or_404(product_id)
variety = Variety.query.get_or_404(variety_id)
if variety.product != product:
abort(400, {'message': 'The specified product and variety are unrelated.'})
if len(product.varieties) <= 1:
abort(400, {'message': 'Cannot leave the product without varieties.'})
try:
db.session.delete(variety)
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
remove_notifications({
'variety_id': variety_id,
})
return NO_PAYLOAD
variety_api = VarietyAPI.as_view('variety_api')
api.add_url_rule('/products/<int:product_id>/varieties/<int:variety_id>',
view_func=variety_api,
methods=('PATCH', 'DELETE'))
@api.route('/products/<int:product_id>/varieties/<int:variety_id>/purchase', methods=['POST'])
@login_required
def purchase_variety(product_id, variety_id):
"""Purchase a particular variety of a product."""
purchased_amount = request.json.get('amount')
if not isinstance(purchased_amount, int):
abort(400, {'message': 'The purchase amount must be specified as an integer.'})
if purchased_amount <= 0:
abort(400, {'message': 'The purchase amount must be positive.'})
product = Product.query.get_or_404(product_id)
variety = Variety.query.get_or_404(variety_id)
if variety.product != product:
abort(400, {'message': 'The specified product and variety are unrelated.'})
log.debug(f'User with balance {current_user.balance} is trying to buy {purchased_amount} of a '
f'product with a price of {product.price}. '
f'Total = {product.price * purchased_amount}')
if current_user.balance < product.price * purchased_amount:
log.debug('Purchase refused: not enough points')
abort(400, {'message': 'Insufficient funds.'})
if purchased_amount > variety.amount:
log.debug('Purchase refused: not enough stock')
abort(400, {'message': 'Insufficient stock.'})
new_stock_change = StockChange(amount=-purchased_amount,
status=StockChangeStatus.pending,
account=current_user,
variety_id=variety_id)
db.session.add(new_stock_change)
new_transaction = Transaction(account=current_user,
change=-product.price * purchased_amount,
stock_change_id=new_stock_change)
new_stock_change.transaction = new_transaction
db.session.add(new_transaction)
try:
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
log.debug('Purchase successful')
admins = Account.query.filter_by(is_admin=True).all()
notify_all(admins, NotificationType.new_purchase, {
'account_email': current_user.email,
'product_id': product.id,
'variety_id': variety.id,
'stock_change_id': new_stock_change.id,
})
if variety.amount <= 0:
notify_all(admins, NotificationType.out_of_stock, {
'product_id': product.id,
'variety_id': variety.id,
})
out_schema = StockChangeSchema(exclude=('transaction', 'account', 'account_email',
'product', 'variety'))
return out_schema.jsonify(new_stock_change)
# ----- StockChange -----
@api.route('/stock_changes')
@admin_required
def list_purchases():
"""List all of the purchases."""
default_limit = 24
default_page = 1
try:
limit = int(request.args.get('limit', default_limit))
page = int(request.args.get('page', default_page))
except ValueError:
abort(400, {'message': 'Bad query parameters.'})
if limit < 1 or page < 1:
abort(400, {'message': 'Limit and page number must be positive.'})
purchases = StockChange.query.filter(StockChange.amount < 0)
count = db.session.query(purchases.subquery()).count()
purchases = (
purchases
.order_by(StockChange.time.desc())
.offset(limit * (page - 1))
.limit(limit)
)
schema = StockChangeSchema(many=True)
return jsonify(pages=math.ceil(count / limit),
data=schema.dump(purchases.all()))
@api.route('/stock_changes/for_review')
@admin_required
def get_purchases_for_review():
"""Get a list of purchases that require admin's attention."""
db_query = StockChange.query.filter(
StockChange.status.in_((StockChangeStatus.pending, StockChangeStatus.ready_for_pickup))
)
schema = StockChangeSchema(many=True, exclude=('transaction', 'variety.product_id',
'variety.product'))
return schema.jsonify(db_query.all())
@api.route('/stock_changes/<int:stock_change_id>/status', methods=['PATCH'])
@admin_required
def edit_purchase_status(stock_change_id):
"""Edit the status of a particular purchase."""
try:
status = getattr(StockChangeStatus, request.json['status'])
except (KeyError, AttributeError):
abort(400, {'message': 'A valid stock change status must be specified.'})
stock_change = StockChange.query.get_or_404(stock_change_id)
if stock_change.status != status:
variety = Variety.query.get(stock_change.variety_id)
product = variety.product
if status == StockChangeStatus.rejected:
db.session.delete(stock_change.transaction)
remove_notifications({
'transaction_id': stock_change.transaction.id,
})
elif stock_change.status == StockChangeStatus.rejected:
new_transaction = Transaction(account=stock_change.account,
change=product.price * stock_change.amount,
stock_change_id=stock_change.id)
stock_change.transaction = new_transaction
db.session.add(new_transaction)
stock_change.status = status
notify(stock_change.account_email, NotificationType.purchase_status_changed, {
'stock_change_id': stock_change.id,
'product_id': product.id,
'variety_id': variety.id,
})
try:
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
return NO_PAYLOAD
# ----- Size -----
@api.route('/sizes')
def list_sizes():
"""List all existing sizes."""
schema = SizeSchema(many=True)
return schema.jsonify(Size.query.all())
@api.route('/sizes', methods=['POST'])
@admin_required
def create_size():
"""Create a new size."""
in_out_schema = SizeSchema()
try:
new_size = in_out_schema.load(request.json)
except ValidationError as err:
abort(400, {'message': err.messages})
try:
db.session.add(new_size)
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
return in_out_schema.jsonify(new_size)
# ----- Color -----
@api.route('/colors')
def list_colors():
"""List all existing colors."""
schema = ColorSchema(many=True)
return schema.jsonify(Color.query.all())
@api.route('/colors', methods=['POST'])
@admin_required
def create_color():
"""Create a new color."""
in_out_schema = ColorSchema()
try:
new_color = in_out_schema.load(request.json)
except ValidationError as err:
abort(400, {'message': err.messages})
try:
db.session.add(new_color)
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
return in_out_schema.jsonify(new_color)
| """Views related to the Variety, StockChange, Size and Color models.
Variety:
- POST /products/{product_id}/varieties
- PATCH /products/{product_id}/varieties/{variety_id}
- DELETE /products/{product_id}/varieties/{variety_id}
- POST /products/{product_id}/varieties/{variety_id}/purchase
StockChange:
- GET /stock_changes
- GET /stock_changes/for_review
- PATCH /stock_changes/{stock_change_id}/status
Size:
- GET /sizes
- POST /sizes
Color:
- GET /colors
- POST /colors
"""
import math
import logging
from flask import request, jsonify
from flask.views import MethodView
from flask_login import login_required, current_user
from marshmallow import ValidationError
from sqlalchemy.exc import IntegrityError
from innopoints.extensions import db
from innopoints.blueprints import api
from innopoints.core.helpers import abort, admin_required
from innopoints.core.notifications import notify_all, notify, remove_notifications
from innopoints.models import (
Account,
Color,
NotificationType,
Product,
Size,
StockChange,
StockChangeStatus,
Transaction,
Variety,
)
from innopoints.schemas import (
ColorSchema,
SizeSchema,
StockChangeSchema,
VarietySchema,
)
NO_PAYLOAD = ('', 204)
log = logging.getLogger(__name__)
@api.route('/products/<int:product_id>/varieties', methods=['POST'])
@admin_required
def create_variety(product_id):
"""Create a new variety."""
product = Product.query.get_or_404(product_id)
in_schema = VarietySchema(exclude=('id', 'product_id', 'product',
'images.variety_id', 'stock_changes.variety_id',),
context={'user': current_user})
try:
new_variety = in_schema.load(request.json)
except ValidationError as err:
abort(400, {'message': err.messages})
try:
new_variety.product = product
db.session.add(new_variety)
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
out_schema = VarietySchema(exclude=('product_id',
'product',
'images.variety_id',
'images.id',
'stock_changes'))
return out_schema.jsonify(new_variety)
class VarietyAPI(MethodView):
"""REST views for a particular instance of the Variety model."""
@admin_required
def patch(self, product_id, variety_id):
"""Update the given variety."""
product = Product.query.get_or_404(product_id)
variety = Variety.query.get_or_404(variety_id)
if variety.product != product:
abort(400, {'message': 'The specified product and variety are unrelated.'})
in_schema = VarietySchema(exclude=('id', 'product_id', 'stock_changes.variety_id'),
context={'update': True})
amount = request.json.pop('amount', None)
try:
updated_variety = in_schema.load(request.json, instance=variety, partial=True)
except ValidationError as err:
abort(400, {'message': err.messages})
if amount is not None:
diff = amount - variety.amount
if diff != 0:
stock_change = StockChange(amount=diff,
status=StockChangeStatus.carried_out,
account=current_user,
variety_id=updated_variety.id)
db.session.add(stock_change)
try:
db.session.add(updated_variety)
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
out_schema = VarietySchema(exclude=('product_id', 'stock_changes', 'product', 'purchases'))
return out_schema.jsonify(updated_variety)
@admin_required
def delete(self, product_id, variety_id):
"""Delete the variety."""
product = Product.query.get_or_404(product_id)
variety = Variety.query.get_or_404(variety_id)
if variety.product != product:
abort(400, {'message': 'The specified product and variety are unrelated.'})
if len(product.varieties) <= 1:
abort(400, {'message': 'Cannot leave the product without varieties.'})
try:
db.session.delete(variety)
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
remove_notifications({
'variety_id': variety_id,
})
return NO_PAYLOAD
variety_api = VarietyAPI.as_view('variety_api')
api.add_url_rule('/products/<int:product_id>/varieties/<int:variety_id>',
view_func=variety_api,
methods=('PATCH', 'DELETE'))
@api.route('/products/<int:product_id>/varieties/<int:variety_id>/purchase', methods=['POST'])
@login_required
def purchase_variety(product_id, variety_id):
"""Purchase a particular variety of a product."""
purchased_amount = request.json.get('amount')
if not isinstance(purchased_amount, int):
abort(400, {'message': 'The purchase amount must be specified as an integer.'})
if purchased_amount <= 0:
abort(400, {'message': 'The purchase amount must be positive.'})
product = Product.query.get_or_404(product_id)
variety = Variety.query.get_or_404(variety_id)
if variety.product != product:
abort(400, {'message': 'The specified product and variety are unrelated.'})
log.debug(f'User with balance {current_user.balance} is trying to buy {purchased_amount} of a '
f'product with a price of {product.price}. '
f'Total = {product.price * purchased_amount}')
if current_user.balance < product.price * purchased_amount:
log.debug('Purchase refused: not enough points')
abort(400, {'message': 'Insufficient funds.'})
if purchased_amount > variety.amount:
log.debug('Purchase refused: not enough stock')
abort(400, {'message': 'Insufficient stock.'})
new_stock_change = StockChange(amount=-purchased_amount,
status=StockChangeStatus.pending,
account=current_user,
variety_id=variety_id)
db.session.add(new_stock_change)
new_transaction = Transaction(account=current_user,
change=-product.price * purchased_amount,
stock_change_id=new_stock_change)
new_stock_change.transaction = new_transaction
db.session.add(new_transaction)
try:
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
log.debug('Purchase successful')
admins = Account.query.filter_by(is_admin=True).all()
notify_all(admins, NotificationType.new_purchase, {
'account_email': current_user.email,
'product_id': product.id,
'variety_id': variety.id,
'stock_change_id': new_stock_change.id,
})
if variety.amount <= 0:
notify_all(admins, NotificationType.out_of_stock, {
'product_id': product.id,
'variety_id': variety.id,
})
out_schema = StockChangeSchema(exclude=('transaction', 'account', 'account_email',
'product', 'variety'))
return out_schema.jsonify(new_stock_change)
# ----- StockChange -----
@api.route('/stock_changes')
@admin_required
def list_purchases():
"""List all of the purchases."""
default_limit = 24
default_page = 1
try:
limit = int(request.args.get('limit', default_limit))
page = int(request.args.get('page', default_page))
except ValueError:
abort(400, {'message': 'Bad query parameters.'})
if limit < 1 or page < 1:
abort(400, {'message': 'Limit and page number must be positive.'})
purchases = StockChange.query.filter(StockChange.amount < 0)
count = db.session.query(purchases.subquery()).count()
purchases = (
purchases
.order_by(StockChange.time.desc())
.offset(limit * (page - 1))
.limit(limit)
)
schema = StockChangeSchema(many=True)
return jsonify(pages=math.ceil(count / limit),
data=schema.dump(purchases.all()))
@api.route('/stock_changes/for_review')
@admin_required
def get_purchases_for_review():
"""Get a list of purchases that require admin's attention."""
db_query = StockChange.query.filter(
StockChange.status.in_((StockChangeStatus.pending, StockChangeStatus.ready_for_pickup))
)
schema = StockChangeSchema(many=True, exclude=('transaction', 'variety.product_id',
'variety.product'))
return schema.jsonify(db_query.all())
@api.route('/stock_changes/<int:stock_change_id>/status', methods=['PATCH'])
@admin_required
def edit_purchase_status(stock_change_id):
"""Edit the status of a particular purchase."""
try:
status = getattr(StockChangeStatus, request.json['status'])
except (KeyError, AttributeError):
abort(400, {'message': 'A valid stock change status must be specified.'})
stock_change = StockChange.query.get_or_404(stock_change_id)
if stock_change.status != status:
variety = Variety.query.get(stock_change.variety_id)
product = variety.product
if status == StockChangeStatus.rejected:
db.session.delete(stock_change.transaction)
remove_notifications({
'transaction_id': stock_change.transaction.id,
})
elif stock_change.status == StockChangeStatus.rejected:
new_transaction = Transaction(account=stock_change.account,
change=product.price * stock_change.amount,
stock_change_id=stock_change.id)
stock_change.transaction = new_transaction
db.session.add(new_transaction)
stock_change.status = status
notify(stock_change.account_email, NotificationType.purchase_status_changed, {
'stock_change_id': stock_change.id,
'product_id': product.id,
'variety_id': variety.id,
})
try:
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
return NO_PAYLOAD
# ----- Size -----
@api.route('/sizes')
def list_sizes():
"""List all existing sizes."""
schema = SizeSchema(many=True)
return schema.jsonify(Size.query.all())
@api.route('/sizes', methods=['POST'])
@admin_required
def create_size():
"""Create a new size."""
in_out_schema = SizeSchema()
try:
new_size = in_out_schema.load(request.json)
except ValidationError as err:
abort(400, {'message': err.messages})
try:
db.session.add(new_size)
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
return in_out_schema.jsonify(new_size)
# ----- Color -----
@api.route('/colors')
def list_colors():
"""List all existing colors."""
schema = ColorSchema(many=True)
return schema.jsonify(Color.query.all())
@api.route('/colors', methods=['POST'])
@admin_required
def create_color():
"""Create a new color."""
in_out_schema = ColorSchema()
try:
new_color = in_out_schema.load(request.json)
except ValidationError as err:
abort(400, {'message': err.messages})
try:
db.session.add(new_color)
db.session.commit()
except IntegrityError as err:
db.session.rollback()
log.exception(err)
abort(400, {'message': 'Data integrity violated.'})
return in_out_schema.jsonify(new_color) | en | 0.714882 | Views related to the Variety, StockChange, Size and Color models. Variety: - POST /products/{product_id}/varieties - PATCH /products/{product_id}/varieties/{variety_id} - DELETE /products/{product_id}/varieties/{variety_id} - POST /products/{product_id}/varieties/{variety_id}/purchase StockChange: - GET /stock_changes - GET /stock_changes/for_review - PATCH /stock_changes/{stock_change_id}/status Size: - GET /sizes - POST /sizes Color: - GET /colors - POST /colors Create a new variety. REST views for a particular instance of the Variety model. Update the given variety. Delete the variety. Purchase a particular variety of a product. # ----- StockChange ----- List all of the purchases. Get a list of purchases that require admin's attention. Edit the status of a particular purchase. # ----- Size ----- List all existing sizes. Create a new size. # ----- Color ----- List all existing colors. Create a new color. | 2.124329 | 2 |
cnns/nnlib/datasets/remy/dataset.py | adam-dziedzic/time-series-ml | 1 | 6616101 | import torch
from torch.utils.data import Dataset
from torchvision import transforms
import os
import pandas as pd
import numpy as np
class ToTensor(object):
"""Transform the numpy array to a tensor."""
def __init__(self, dtype=torch.float):
self.dtype = dtype
def __call__(self, input):
"""
:param input: numpy array.
:return: PyTorch's tensor.
"""
# Transform data on the cpu.
return torch.tensor(input, device=torch.device("cpu"),
dtype=self.dtype)
class AddChannel(object):
"""Add channel dimension to the input time series."""
def __call__(self, input):
"""
Rescale the channels.
:param image: the input image
:return: rescaled image with the required number of channels:return:
"""
# We receive only a single array of values as input, so have to add the
# channel as the zero-th dimension.
return torch.unsqueeze(input, dim=0)
class RemyDataset(Dataset):
def __init__(
self,
train=True,
data_path=None):
"""
:param dataset_name: the name of the dataset to fetch from file on disk.
:param transformations: pytorch transforms for transforms and tensor
conversion.
:param data_path: the path to the ucr dataset.
"""
dir_path = os.path.dirname(os.path.realpath(__file__))
if data_path is None:
data_path = os.path.join(dir_path, os.pardir, os.pardir,
"remy_data")
else:
data_path = os.path.join(dir_path, data_path)
if train is True:
suffix = "_train.csv"
else:
suffix = "_test.csv"
csv_path = data_path + '/' + 'remy_data' + suffix
self.data_all = pd.read_csv(csv_path, header=None)
self.labels = np.asarray(self.data_all.iloc[:, 0], dtype=np.int)
self.length = len(self.labels)
self.num_classes = len(np.unique(self.labels))
self.labels = self.__transform_labels(labels=self.labels,
num_classes=self.num_classes)
self.data = np.asarray(self.data_all.iloc[:, 1:], dtype=np.float)
# randomize the data
randomized_indices = np.random.choice(
self.length, self.length, replace=False)
self.data = self.data[randomized_indices, ...]
self.labels = self.labels[randomized_indices]
self.width = len(self.data[0, :])
self.dtype = torch.float
self.data = torch.tensor(self.data, device=torch.device("cpu"),
dtype=self.dtype)
# add the dimension for the channel
self.data = torch.unsqueeze(self.data, dim=1)
@staticmethod
def __transform_labels(labels, num_classes):
"""
Start class numbering from 0, and provide them in range from 0 to
self.num_classes - 1.
Example:
y_train = np.array([-1, 2, 3, 3, -1, 2])
nb_classes = 3
((y_train - y_train.min()) / (y_train.max() - y_train.min()) * (nb_classes - 1)).astype(int)
Out[45]: array([0, 1, 2, 2, 0, 1])
>>> labels = __transofrm_labels(labels = np.array([-1, 2, 3, 3, -1, 2]),
... num_classes=3)
>>> np.testing.assert_arrays_equal(x=labels,
... y=np.array([0, 1, 2, 2, 0, 1]))
:param labels: labels.
:param num_classes: number of classes.
:return: transformed labels.
"""
# The nll (negative log likelihood) loss requires target labels to be of
# type Long:
# https://discuss.pytorch.org/t/expected-object-of-type-variable-torch-longtensor-but-found-type/11833/3?u=adam_dziedzic
return ((labels - labels.min()) / (labels.max() - labels.min()) * (
num_classes - 1)).astype(np.int64)
@property
def width(self):
return self.__width
@width.setter
def width(self, val):
self.__width = val
@property
def num_classes(self):
return self.__num_classes
@num_classes.setter
def num_classes(self, val):
self.__num_classes = val
def __getitem__(self, index):
label = self.labels[index]
# Take the row index and all values starting from the second column.
# input = np.asarray(self.data.iloc[index][1:])
input = self.data[index]
# Transform time-series input to tensor.
# if self.transformations is not None:
# input = self.transformations(input)
# Return the time-series and the label.
return input, label
def __len__(self):
# self.data.index - The index(row labels) of the DataFrame.
# length = len(self.data.index)
length = len(self.data)
assert length == len(self.labels)
return length
def set_length(self, length):
"""
:param length: The lenght of the datasets (a subset of data points),
first length samples.
"""
assert len(self.data) == len(self.labels)
self.data = self.data[:length]
self.labels = self.labels[:length]
def set_range(self, start, stop):
"""
:param start: the start row
:param stop: the last row (exclusive) of the dataset
:return: the dataset with the specified range.
"""
assert len(self.data) == len(self.labels)
self.data = self.data[start:stop]
self.labels = self.labels[start:stop]
if __name__ == "__main__":
train_dataset = RemyDataset(train=True,
transformations=transforms.Compose(
[ToTensor(dtype=torch.float),
AddChannel()]))
print('first data item: ', train_dataset[0])
print("length of the train dataset: ", len(train_dataset))
| import torch
from torch.utils.data import Dataset
from torchvision import transforms
import os
import pandas as pd
import numpy as np
class ToTensor(object):
"""Transform the numpy array to a tensor."""
def __init__(self, dtype=torch.float):
self.dtype = dtype
def __call__(self, input):
"""
:param input: numpy array.
:return: PyTorch's tensor.
"""
# Transform data on the cpu.
return torch.tensor(input, device=torch.device("cpu"),
dtype=self.dtype)
class AddChannel(object):
"""Add channel dimension to the input time series."""
def __call__(self, input):
"""
Rescale the channels.
:param image: the input image
:return: rescaled image with the required number of channels:return:
"""
# We receive only a single array of values as input, so have to add the
# channel as the zero-th dimension.
return torch.unsqueeze(input, dim=0)
class RemyDataset(Dataset):
def __init__(
self,
train=True,
data_path=None):
"""
:param dataset_name: the name of the dataset to fetch from file on disk.
:param transformations: pytorch transforms for transforms and tensor
conversion.
:param data_path: the path to the ucr dataset.
"""
dir_path = os.path.dirname(os.path.realpath(__file__))
if data_path is None:
data_path = os.path.join(dir_path, os.pardir, os.pardir,
"remy_data")
else:
data_path = os.path.join(dir_path, data_path)
if train is True:
suffix = "_train.csv"
else:
suffix = "_test.csv"
csv_path = data_path + '/' + 'remy_data' + suffix
self.data_all = pd.read_csv(csv_path, header=None)
self.labels = np.asarray(self.data_all.iloc[:, 0], dtype=np.int)
self.length = len(self.labels)
self.num_classes = len(np.unique(self.labels))
self.labels = self.__transform_labels(labels=self.labels,
num_classes=self.num_classes)
self.data = np.asarray(self.data_all.iloc[:, 1:], dtype=np.float)
# randomize the data
randomized_indices = np.random.choice(
self.length, self.length, replace=False)
self.data = self.data[randomized_indices, ...]
self.labels = self.labels[randomized_indices]
self.width = len(self.data[0, :])
self.dtype = torch.float
self.data = torch.tensor(self.data, device=torch.device("cpu"),
dtype=self.dtype)
# add the dimension for the channel
self.data = torch.unsqueeze(self.data, dim=1)
@staticmethod
def __transform_labels(labels, num_classes):
"""
Start class numbering from 0, and provide them in range from 0 to
self.num_classes - 1.
Example:
y_train = np.array([-1, 2, 3, 3, -1, 2])
nb_classes = 3
((y_train - y_train.min()) / (y_train.max() - y_train.min()) * (nb_classes - 1)).astype(int)
Out[45]: array([0, 1, 2, 2, 0, 1])
>>> labels = __transofrm_labels(labels = np.array([-1, 2, 3, 3, -1, 2]),
... num_classes=3)
>>> np.testing.assert_arrays_equal(x=labels,
... y=np.array([0, 1, 2, 2, 0, 1]))
:param labels: labels.
:param num_classes: number of classes.
:return: transformed labels.
"""
# The nll (negative log likelihood) loss requires target labels to be of
# type Long:
# https://discuss.pytorch.org/t/expected-object-of-type-variable-torch-longtensor-but-found-type/11833/3?u=adam_dziedzic
return ((labels - labels.min()) / (labels.max() - labels.min()) * (
num_classes - 1)).astype(np.int64)
@property
def width(self):
return self.__width
@width.setter
def width(self, val):
self.__width = val
@property
def num_classes(self):
return self.__num_classes
@num_classes.setter
def num_classes(self, val):
self.__num_classes = val
def __getitem__(self, index):
label = self.labels[index]
# Take the row index and all values starting from the second column.
# input = np.asarray(self.data.iloc[index][1:])
input = self.data[index]
# Transform time-series input to tensor.
# if self.transformations is not None:
# input = self.transformations(input)
# Return the time-series and the label.
return input, label
def __len__(self):
# self.data.index - The index(row labels) of the DataFrame.
# length = len(self.data.index)
length = len(self.data)
assert length == len(self.labels)
return length
def set_length(self, length):
"""
:param length: The lenght of the datasets (a subset of data points),
first length samples.
"""
assert len(self.data) == len(self.labels)
self.data = self.data[:length]
self.labels = self.labels[:length]
def set_range(self, start, stop):
"""
:param start: the start row
:param stop: the last row (exclusive) of the dataset
:return: the dataset with the specified range.
"""
assert len(self.data) == len(self.labels)
self.data = self.data[start:stop]
self.labels = self.labels[start:stop]
if __name__ == "__main__":
train_dataset = RemyDataset(train=True,
transformations=transforms.Compose(
[ToTensor(dtype=torch.float),
AddChannel()]))
print('first data item: ', train_dataset[0])
print("length of the train dataset: ", len(train_dataset))
| en | 0.59419 | Transform the numpy array to a tensor. :param input: numpy array. :return: PyTorch's tensor. # Transform data on the cpu. Add channel dimension to the input time series. Rescale the channels. :param image: the input image :return: rescaled image with the required number of channels:return: # We receive only a single array of values as input, so have to add the # channel as the zero-th dimension. :param dataset_name: the name of the dataset to fetch from file on disk. :param transformations: pytorch transforms for transforms and tensor conversion. :param data_path: the path to the ucr dataset. # randomize the data # add the dimension for the channel Start class numbering from 0, and provide them in range from 0 to self.num_classes - 1. Example: y_train = np.array([-1, 2, 3, 3, -1, 2]) nb_classes = 3 ((y_train - y_train.min()) / (y_train.max() - y_train.min()) * (nb_classes - 1)).astype(int) Out[45]: array([0, 1, 2, 2, 0, 1]) >>> labels = __transofrm_labels(labels = np.array([-1, 2, 3, 3, -1, 2]), ... num_classes=3) >>> np.testing.assert_arrays_equal(x=labels, ... y=np.array([0, 1, 2, 2, 0, 1])) :param labels: labels. :param num_classes: number of classes. :return: transformed labels. # The nll (negative log likelihood) loss requires target labels to be of # type Long: # https://discuss.pytorch.org/t/expected-object-of-type-variable-torch-longtensor-but-found-type/11833/3?u=adam_dziedzic # Take the row index and all values starting from the second column. # input = np.asarray(self.data.iloc[index][1:]) # Transform time-series input to tensor. # if self.transformations is not None: # input = self.transformations(input) # Return the time-series and the label. # self.data.index - The index(row labels) of the DataFrame. # length = len(self.data.index) :param length: The lenght of the datasets (a subset of data points), first length samples. :param start: the start row :param stop: the last row (exclusive) of the dataset :return: the dataset with the specified range. | 3.172836 | 3 |
src/tests/test_pagure_lib_drop_issue.py | yifengyou/learn-pagure | 0 | 6616102 | # -*- coding: utf-8 -*-
"""
(c) 2017 - Copyright Red Hat Inc
Authors:
<NAME> <<EMAIL>>
"""
from __future__ import unicode_literals, absolute_import
import unittest
import shutil
import sys
import os
from mock import patch, MagicMock
sys.path.insert(
0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
)
import pagure.lib.query
import pagure.lib.model
import tests
class PagureLibDropIssuetests(tests.Modeltests):
""" Tests for pagure.lib.query.drop_issue """
@patch("pagure.lib.git.update_git")
@patch("pagure.lib.notify.send_email")
def setUp(self, p_send_email, p_ugt):
"""Create a couple of tickets and add tag to the project so we can
play with them later.
"""
super(PagureLibDropIssuetests, self).setUp()
p_send_email.return_value = True
p_ugt.return_value = True
tests.create_projects(self.session)
repo = pagure.lib.query.get_authorized_project(self.session, "test")
# Before
issues = pagure.lib.query.search_issues(self.session, repo)
self.assertEqual(len(issues), 0)
self.assertEqual(repo.open_tickets, 0)
self.assertEqual(repo.open_tickets_public, 0)
# Create two issues to play with
msg = pagure.lib.query.new_issue(
session=self.session,
repo=repo,
title="Test issue",
content="We should work on this",
user="pingou",
)
self.session.commit()
self.assertEqual(msg.title, "Test issue")
self.assertEqual(repo.open_tickets, 1)
self.assertEqual(repo.open_tickets_public, 1)
msg = pagure.lib.query.new_issue(
session=self.session,
repo=repo,
title="Test issue #2",
content="We should work on this for the second time",
user="foo",
status="Open",
)
self.session.commit()
self.assertEqual(msg.title, "Test issue #2")
self.assertEqual(repo.open_tickets, 2)
self.assertEqual(repo.open_tickets_public, 2)
# After
issues = pagure.lib.query.search_issues(self.session, repo)
self.assertEqual(len(issues), 2)
# Add tag to the project
pagure.lib.query.new_tag(
self.session, "red", "red tag", "#ff0000", repo.id
)
self.session.commit()
repo = pagure.lib.query.get_authorized_project(self.session, "test")
self.assertEqual(
str(repo.tags_colored),
"[TagColored(id: 1, tag:red, tag_description:red tag, color:#ff0000)]",
)
@patch("pagure.lib.git.update_git")
@patch("pagure.lib.notify.send_email")
@patch("pagure.lib.git._maybe_wait", tests.definitely_wait)
def test_drop_issue(self, p_send_email, p_ugt):
"""Test the drop_issue of pagure.lib.query.
We had an issue where we could not delete issue that had been tagged
with this test, we create two issues, tag one of them and delete
it, ensuring it all goes well.
"""
p_send_email.return_value = True
p_ugt.return_value = True
repo = pagure.lib.query.get_authorized_project(self.session, "test")
# Add tag to the second issue
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
msgs = pagure.lib.query.update_tags(
self.session, issue, tags=["red"], username="pingou"
)
self.session.commit()
self.assertEqual(msgs, ["Issue tagged with: red"])
repo = pagure.lib.query.get_authorized_project(self.session, "test")
self.assertEqual(len(repo.issues), 2)
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
self.assertEqual(
str(issue.tags),
"[TagColored(id: 1, tag:red, tag_description:red tag, color:#ff0000)]",
)
# Drop the issue #2
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
pagure.lib.query.drop_issue(self.session, issue, user="pingou")
self.session.commit()
repo = pagure.lib.query.get_authorized_project(self.session, "test")
self.assertEqual(len(repo.issues), 1)
@patch("pagure.lib.git.update_git")
@patch("pagure.lib.notify.send_email")
@patch("pagure.lib.git._maybe_wait", tests.definitely_wait)
def test_drop_issue_two_issues_one_tag(self, p_send_email, p_ugt):
"""Test the drop_issue of pagure.lib.query.
We had an issue where we could not delete issue that had been tagged
with this test, we create two issues, tag them both and delete one
then we check that the other issue is still tagged.
"""
p_send_email.return_value = True
p_ugt.return_value = True
repo = pagure.lib.query.get_authorized_project(self.session, "test")
# Add the tag to both issues
issue = pagure.lib.query.search_issues(self.session, repo, issueid=1)
msgs = pagure.lib.query.update_tags(
self.session, issue, tags=["red"], username="pingou"
)
self.session.commit()
self.assertEqual(msgs, ["Issue tagged with: red"])
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
msgs = pagure.lib.query.update_tags(
self.session, issue, tags=["red"], username="pingou"
)
self.session.commit()
self.assertEqual(msgs, ["Issue tagged with: red"])
repo = pagure.lib.query.get_authorized_project(self.session, "test")
self.assertEqual(len(repo.issues), 2)
issue = pagure.lib.query.search_issues(self.session, repo, issueid=1)
self.assertEqual(
str(issue.tags),
"[TagColored(id: 1, tag:red, tag_description:red tag, color:#ff0000)]",
)
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
self.assertEqual(
str(issue.tags),
"[TagColored(id: 1, tag:red, tag_description:red tag, color:#ff0000)]",
)
# Drop the issue #2
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
pagure.lib.query.drop_issue(self.session, issue, user="pingou")
self.session.commit()
repo = pagure.lib.query.get_authorized_project(self.session, "test")
self.assertEqual(len(repo.issues), 1)
issue = pagure.lib.query.search_issues(self.session, repo, issueid=1)
self.assertEqual(
str(issue.tags),
"[TagColored(id: 1, tag:red, tag_description:red tag, color:#ff0000)]",
)
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
self.assertIsNone(issue)
if __name__ == "__main__":
unittest.main(verbosity=2)
| # -*- coding: utf-8 -*-
"""
(c) 2017 - Copyright Red Hat Inc
Authors:
<NAME> <<EMAIL>>
"""
from __future__ import unicode_literals, absolute_import
import unittest
import shutil
import sys
import os
from mock import patch, MagicMock
sys.path.insert(
0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
)
import pagure.lib.query
import pagure.lib.model
import tests
class PagureLibDropIssuetests(tests.Modeltests):
""" Tests for pagure.lib.query.drop_issue """
@patch("pagure.lib.git.update_git")
@patch("pagure.lib.notify.send_email")
def setUp(self, p_send_email, p_ugt):
"""Create a couple of tickets and add tag to the project so we can
play with them later.
"""
super(PagureLibDropIssuetests, self).setUp()
p_send_email.return_value = True
p_ugt.return_value = True
tests.create_projects(self.session)
repo = pagure.lib.query.get_authorized_project(self.session, "test")
# Before
issues = pagure.lib.query.search_issues(self.session, repo)
self.assertEqual(len(issues), 0)
self.assertEqual(repo.open_tickets, 0)
self.assertEqual(repo.open_tickets_public, 0)
# Create two issues to play with
msg = pagure.lib.query.new_issue(
session=self.session,
repo=repo,
title="Test issue",
content="We should work on this",
user="pingou",
)
self.session.commit()
self.assertEqual(msg.title, "Test issue")
self.assertEqual(repo.open_tickets, 1)
self.assertEqual(repo.open_tickets_public, 1)
msg = pagure.lib.query.new_issue(
session=self.session,
repo=repo,
title="Test issue #2",
content="We should work on this for the second time",
user="foo",
status="Open",
)
self.session.commit()
self.assertEqual(msg.title, "Test issue #2")
self.assertEqual(repo.open_tickets, 2)
self.assertEqual(repo.open_tickets_public, 2)
# After
issues = pagure.lib.query.search_issues(self.session, repo)
self.assertEqual(len(issues), 2)
# Add tag to the project
pagure.lib.query.new_tag(
self.session, "red", "red tag", "#ff0000", repo.id
)
self.session.commit()
repo = pagure.lib.query.get_authorized_project(self.session, "test")
self.assertEqual(
str(repo.tags_colored),
"[TagColored(id: 1, tag:red, tag_description:red tag, color:#ff0000)]",
)
@patch("pagure.lib.git.update_git")
@patch("pagure.lib.notify.send_email")
@patch("pagure.lib.git._maybe_wait", tests.definitely_wait)
def test_drop_issue(self, p_send_email, p_ugt):
"""Test the drop_issue of pagure.lib.query.
We had an issue where we could not delete issue that had been tagged
with this test, we create two issues, tag one of them and delete
it, ensuring it all goes well.
"""
p_send_email.return_value = True
p_ugt.return_value = True
repo = pagure.lib.query.get_authorized_project(self.session, "test")
# Add tag to the second issue
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
msgs = pagure.lib.query.update_tags(
self.session, issue, tags=["red"], username="pingou"
)
self.session.commit()
self.assertEqual(msgs, ["Issue tagged with: red"])
repo = pagure.lib.query.get_authorized_project(self.session, "test")
self.assertEqual(len(repo.issues), 2)
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
self.assertEqual(
str(issue.tags),
"[TagColored(id: 1, tag:red, tag_description:red tag, color:#ff0000)]",
)
# Drop the issue #2
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
pagure.lib.query.drop_issue(self.session, issue, user="pingou")
self.session.commit()
repo = pagure.lib.query.get_authorized_project(self.session, "test")
self.assertEqual(len(repo.issues), 1)
@patch("pagure.lib.git.update_git")
@patch("pagure.lib.notify.send_email")
@patch("pagure.lib.git._maybe_wait", tests.definitely_wait)
def test_drop_issue_two_issues_one_tag(self, p_send_email, p_ugt):
"""Test the drop_issue of pagure.lib.query.
We had an issue where we could not delete issue that had been tagged
with this test, we create two issues, tag them both and delete one
then we check that the other issue is still tagged.
"""
p_send_email.return_value = True
p_ugt.return_value = True
repo = pagure.lib.query.get_authorized_project(self.session, "test")
# Add the tag to both issues
issue = pagure.lib.query.search_issues(self.session, repo, issueid=1)
msgs = pagure.lib.query.update_tags(
self.session, issue, tags=["red"], username="pingou"
)
self.session.commit()
self.assertEqual(msgs, ["Issue tagged with: red"])
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
msgs = pagure.lib.query.update_tags(
self.session, issue, tags=["red"], username="pingou"
)
self.session.commit()
self.assertEqual(msgs, ["Issue tagged with: red"])
repo = pagure.lib.query.get_authorized_project(self.session, "test")
self.assertEqual(len(repo.issues), 2)
issue = pagure.lib.query.search_issues(self.session, repo, issueid=1)
self.assertEqual(
str(issue.tags),
"[TagColored(id: 1, tag:red, tag_description:red tag, color:#ff0000)]",
)
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
self.assertEqual(
str(issue.tags),
"[TagColored(id: 1, tag:red, tag_description:red tag, color:#ff0000)]",
)
# Drop the issue #2
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
pagure.lib.query.drop_issue(self.session, issue, user="pingou")
self.session.commit()
repo = pagure.lib.query.get_authorized_project(self.session, "test")
self.assertEqual(len(repo.issues), 1)
issue = pagure.lib.query.search_issues(self.session, repo, issueid=1)
self.assertEqual(
str(issue.tags),
"[TagColored(id: 1, tag:red, tag_description:red tag, color:#ff0000)]",
)
issue = pagure.lib.query.search_issues(self.session, repo, issueid=2)
self.assertIsNone(issue)
if __name__ == "__main__":
unittest.main(verbosity=2)
| en | 0.960799 | # -*- coding: utf-8 -*- (c) 2017 - Copyright Red Hat Inc Authors: <NAME> <<EMAIL>> Tests for pagure.lib.query.drop_issue Create a couple of tickets and add tag to the project so we can play with them later. # Before # Create two issues to play with #2", #2") # After # Add tag to the project #ff0000)]", Test the drop_issue of pagure.lib.query. We had an issue where we could not delete issue that had been tagged with this test, we create two issues, tag one of them and delete it, ensuring it all goes well. # Add tag to the second issue #ff0000)]", # Drop the issue #2 Test the drop_issue of pagure.lib.query. We had an issue where we could not delete issue that had been tagged with this test, we create two issues, tag them both and delete one then we check that the other issue is still tagged. # Add the tag to both issues #ff0000)]", #ff0000)]", # Drop the issue #2 #ff0000)]", | 2.283436 | 2 |
eegpy/analysis/entropy/base.py | thorstenkranz/eegpy | 10 | 6616103 | <reponame>thorstenkranz/eegpy
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Classes and funtions for making symbolic
representations of time-series"""
import itertools
import eegpy
from eegpy.helper import factorial
from eegpy.misc import FATALERROR, EegpyBase, debug
#from eegpy.analysis.phasespace import make_time_delay_embedding
from eegpy.analysis.entropy.symbols import make_permutation_symbols, make_all_permutation_symbols
try:
import numpy as N
np = N
except ImportError:
raise FATALERROR('SciPy or NumPy not found!\nPlease visit www.scipy.org or numeric.scipy.org for more information.')
###########
# Classes #
###########
#############
# Functions #
#############
def entropy(x,symbols=None):
"""For a given set of symbols, returns the entropy.
H = - \sum_i=0^N p_i log(p_i)"""
ps = prob(x)
tmp = -(ps*N.log2(ps))
return np.ma.masked_invalid(tmp).sum()
def perm_entropy(x,w=4,t=1,normalize=True):
"""Calculate the permutation-entropy of a time-series x."""
pe = entropy(make_permutation_symbols(x,w,t))
if normalize:
pe=pe/N.log(factorial(w))
return pe
def joint_entropy(x,y,symbols=None):
jps = j_prob(x,y,symbols=symbols)
tmp = -(jps*np.log2(jps))
return np.ma.masked_invalid(tmp).sum()
def perm_M(x,y,w=4,t=1):
"""Permutation mutual information
Creates symbolic timeseries from x and y and calculates the mutual information
"""
s1 = make_permutation_symbols(x,w=w,t=t)
s2 = make_permutation_symbols(y,w=w,t=t)
return M(s1,s2,symbols="w%i"%w)
def perm_d(x,y,w=4,t=1):
"""Metric based on mutual information. Normalized to [0,1]
See http://en.wikipedia.org/wiki/Mutual_information#Metric
"""
s1 = make_permutation_symbols(x,w=w,t=t)
s2 = make_permutation_symbols(y,w=w,t=t)
je = joint_entropy(s1,s2,symbols="w%i"%w)
mi = M(s1,s2,symbols="w%i"%w)
return (je-mi)
def perm_D(x,y,w=4,t=1):
"""Metric based on mutual information. Normalized to [0,1]
See http://en.wikipedia.org/wiki/Mutual_information#Metric
"""
s1 = make_permutation_symbols(x,w=w,t=t)
s2 = make_permutation_symbols(y,w=w,t=t)
je = joint_entropy(s1,s2,symbols="w%i"%w)
mi = M(s1,s2,symbols="w%i"%w)
return (je-mi)/je
def perm_TE_ensemble(y,x,w=4,tau=1,test_surr=False):
"""Permutation transfer entropy of two sets of timeseries x and y
Measures information transfer from y to x.
Parameters:
y: 2d-array, first index timepoints, second index ensemble
x: equal-size array
w: word-size for creation of permutation-symbols
tau: time-delay for creation of permutation-symbols
test_surr: bool. If a surrogate-test should be perfomed or not
Returns: 1d-array of length y.shape[0]-1"""
s1 = make_permutation_symbols(y,w=w,t=tau)
s2 = make_permutation_symbols(x,w=w,t=tau)
return TE_ensemble(s1, s2)
def M(x,y,symbols=None):
"""Mutual information of two symbolic timeseries x and y"""
jp = j_prob(x,y,symbols=symbols)
px = prob(x,symbols=symbols)
py = prob(y,symbols=symbols)
rv = 0
px = px.reshape(-1,1).repeat(jp.shape[0],1)
py = py.reshape(1,-1).repeat(jp.shape[1],0)
tmp = jp*N.log2(jp/(px*py))
rv = N.ma.masked_invalid((tmp*(jp>0).astype("i"))).sum()
return rv
def TE(y,x,symbols=None):
"""Transfer entropy of two symbolic timeseries x and y
Measures information transfer from x to y"""
#rv = j_prob(x[1:],x[:-1],y[:-1])\
# *N.log2(c_prob(x[1:],x[:-1],y[:-1])/c_prob(x[1:],x[:-1]))
jp_xxy = j_prob(x[1:],x[:-1],y[:-1],symbols=symbols)
jp_xx = j_prob(x[1:],x[:-1],symbols=symbols)
jp_xy = j_prob(x[:-1],y[:-1],symbols=symbols)
p_x = prob(x,symbols=symbols)
#make all the size of jp_xxy to do vectorised calculations
#print jp_xx.shape, jp_xy.shape, jp_xxy.shape
jp_xx = N.tile(jp_xx,[jp_xxy.shape[2],1,1])
jp_xx = jp_xx.swapaxes(0,1)
jp_xx = jp_xx.swapaxes(1,2)
jp_xy = N.tile(jp_xy,[jp_xxy.shape[0],1,1])
p_x = N.tile(p_x,[jp_xxy.shape[0],jp_xxy.shape[2],1])
p_x = p_x.swapaxes(1,2)
rv = N.ma.masked_invalid(jp_xxy * N.log10(jp_xxy*p_x/(jp_xy*jp_xx))).sum()
# for ix1 in range(jp_xxy.shape[0]):
# for iy in range(jp_xxy.shape[1]):
# for ix in range(jp_xxy.shape[2]):
# #try:
# tmp = jp_xxy[ix1,ix,iy] * N.log10(jp_xxy[ix1,ix,iy]*p_x[ix]/(jp_xy[ix,iy]*jp_xx[ix1,ix]))
# if N.isfinite(tmp):
# rv+=tmp
#print ix, iy, ix1, rv
#except Exception, e:
#print "error"
#pass
return rv#N.ma.masked_invalid(rv).sum()
def perm_TE(y,x,w=4,t=1):
"""Creates symbolic timeseries from real data and calculates Transfer Entropy"""
s1 = make_permutation_symbols(x,w=w,t=t)
s2 = make_permutation_symbols(y,w=w,t=t)
#return TE(s2,s1,symbols="w%i"%w)
return TE(s2,s1,symbols=make_all_permutation_symbols(w))
def TE_ensemble(y,x,test_surr=False):
"""Transfer entropy of two sets of symbolic timeseries x and y
Measures information transfer from x to y.
:Parameters:
y: 2d-array, first index timepoints, second index ensemble
x: equal-size array
test_surr: bool. If a surrogate-test should be perfomed or not
:Returns: 1d-array of length y.shape[0]-1
"""
rv = N.zeros((y.shape[0]-1),"d")
for idx in range(y.shape[0]-1):
jp_xxy = j_prob(x[idx+1,:],x[idx,:],y[idx,:])
jp_xx = j_prob(x[idx+1,:],x[idx,:])
jp_xy = j_prob(x[idx,:],y[idx,:])
p_x = prob(x[idx])
#make all the size of jp_xxy to do vectorised calculations
jp_xx = N.tile(jp_xx,[jp_xxy.shape[2],1,1])
jp_xx = jp_xx.swapaxes(0,1)
jp_xx = jp_xx.swapaxes(1,2)
jp_xy = N.tile(jp_xy,[jp_xxy.shape[0],1,1])
p_x = N.tile(p_x,[jp_xxy.shape[0],jp_xxy.shape[2],1])
p_x = p_x.swapaxes(1,2)
#print idx, jp_xxy.shape, jp_xx.shape, jp_xy.shape, p_x.shape
rv[idx] = N.ma.masked_invalid(jp_xxy * N.log10(jp_xxy*p_x/(jp_xy*jp_xx))).sum()
# jp_xx = j_prob(x[idx+1,:],x[idx,:])
# jp_xy = j_prob(x[idx,:],y[idx,:])
# p_x = prob(x[idx])
# for ix1 in range(jp_xxy.shape[0]):
# for iy in range(jp_xxy.shape[2]):
# for ix in range(jp_xxy.shape[1]):
# tmp = jp_xxy[ix1,ix,iy] * N.log10(jp_xxy[ix1,ix,iy]*p_x[ix]/(jp_xy[ix,iy]*jp_xx[ix1,ix]))
# if N.isfinite(tmp):
# rv[idx]+=tmp
return rv
#Probability-functions
def prob(x,symbols=None):
"""Calculate the probabilities for each symbol"""
#print x
if symbols==None:
symbols = np.unique(x)
elif type(symbols) == str:
symbols = make_all_permutation_symbols(symbols)
symbdict = dict([(k,0) for k in symbols])
for xi in x:
symbdict[xi] += 1
ks = symbols
ks.sort()
ps = np.array([symbdict[k] for k in ks]).astype(np.float)
ps /= x.shape[0]
return ps
def j_prob(x,y,z=None,symbols=None):
"""The joint probability of the symbols in x and y"""
#print "symbls", symbols
#extract variables from args
#print args
if z==None:
assert len(x) == len(y), "Sequences must have same length"
else:
assert len(x) == len(y) and len(x) == len(z), "Sequences must have same length"
#Which symbols exist
if symbols==None:
symbols = np.unique(np.r_[x,y])
elif type(symbols) == str:
symbols = make_all_permutation_symbols(symbols)
if z==None:
ps = N.zeros((len(symbols),len(symbols)),"d")
ks = list(symbols)
ks.sort()
idx_dict = dict([(k,ks.index(k)) for k in ks])
for i in range(len(x)):
ps[idx_dict[x[i]],idx_dict[y[i]]] +=1
ps /= x.shape[0]
else:
ps = N.zeros((len(symbols),len(symbols),len(symbols)),"d")
ks = list(symbols)
ks.sort()
idx_dict = dict([(k,ks.index(k)) for k in ks])
for i in range(len(x)):
ps[idx_dict[x[i]],idx_dict[y[i]],idx_dict[z[i]]] +=1
ps /= x.shape[0]
return ps
def c_prob(x,y,z=None,symbols=None):
"""Conditional probability. Defined as P(X|Y) = P(X,Y)/P(Y)"""
jp = j_prob(x,y,z,symbols)
if z==None:
ps = jp/jp.mean(axis=1)
else:
ps = jp/j_prob(y,z)
#ps /= ps.mean(axis=1)
return ps
#Helper-functions
def join_symb_lists(li1,li2):
"""Not used..."""
rv = []
for li in [li1,li2]:
for v in li:
if not v in rv:
rv.append(v)
return rv
if __name__ == "__main__":
#from eegpy.analysis.entropy.base import j_prob, prob, c_prob
#from eegpy.analysis.entropy.symbols import make_permutation_symbols
from eegpy.models.roessler import TwoRoessler
import pylab as p
p.figure(1)
for i_r,rausch in enumerate(np.arange(0,3,0.3)):
ar1 = np.sin(np.arange(0,100,0.1)) + np.random.random((1000))*rausch
ar2 = np.sin(np.arange(0,100,0.1)) + np.random.random((1000))*rausch
p.subplot(10,1,i_r+1)
p.plot(ar1)
p.plot(ar2)
d = perm_d(ar1,ar2,w=4,t=50)
D = perm_D(ar1,ar2,w=4,t=50)
p.text(10,-0.5,"d=%.2f, D=%.2f"%(d,D),bbox={"fc":"w","alpha":0.7})
p.figure(2)
for i_e,e in enumerate(np.arange(0,0.4,0.04)):
tr = TwoRoessler(e1=e,e2=e)
ar = tr.integrate(np.arange(0,1000,0.1))[-4096:]
ar1 = ar[:,0]
ar2 = ar[:,3]
p.subplot(10,1,i_e+1)
p.plot(ar1)
p.plot(ar2)
d = perm_d(ar1,ar2,w=4,t=50)
D = perm_D(ar1,ar2,w=4,t=50)
p.text(10,-0.5,"d=%.2f, D=%.2f"%(d,D),bbox={"fc":"w","alpha":0.7})
#s1 = make_permutation_symbols(ar,4,1)
#probs = prob(s1,symbols="w4")
#print probs, probs.sum()
#ar3 = N.sin(N.arange(0,5,0.005))
# eeg = eegpy.F32("/home/thorsten/443_as_fsl.f32","r")
# t = N.zeros((25,25),"d")
# for i in range(25):#range(eeg.num_channels):
# for j in range(25):#range(eeg.num_channels):
# s1 = make_permutation_symbols(eeg[10000:20000,i],t=10)
# s2 = make_permutation_symbols(eeg[10000:20000,j],t=10)
# t[i,j] = TE(s1,s2)
# print "TE(%i->%i)"%(i,j), t[i,j]
#eeg = eegpy.open_eeg("/media/Extern/public/Experimente/AudioStroop/2008-07-29_Rieke/eeg/rieke_as.f32")
#evt = eegpy.EventTable("/media/Extern/public/Experimente/AudioStroop/2008-07-29_Rieke/eeg/rieke_as.vmrk")
#print evt.keys()
#ts = evt["S65282"]
#data = eeg.get_data_for_events(ts, (-200,1000))
#s1 = make_permutation_symbols(data[:,13,:],t=10)
#print data.shape, data.mean()
#s1 = make_permutation_symbols(data[:,13,:],w=3,t=10)
#s2 = make_permutation_symbols(data[:,14,:],w=3,t=10)
#w=3
#tau=10
#te = N.zeros((data.shape[0]-((w-1)*tau+1),data.shape[1],data.shape[1]),"d")
#import time
#t_start = time.time()
#for ch1 in range(data.shape[1]):
# for ch2 in range(data.shape[1]):
# te[:,ch1,ch2] = perm_TE_ensemble(data[:,ch1,:], data[:,ch2,:],w=w,tau=tau)
# print "<PTE(%i,%i)> ="%(ch1,ch2), te[:,ch1,ch2].mean()
#print "Duration of calculation:", time.time()-t_start
# ar2 = ar3[::-1]
# ar1 = -ar3
# s1 = make_permutation_symbols(ar1)
# s2 = make_permutation_symbols(ar2)
# s3 = make_permutation_symbols(ar3)
# jp2 = j_prob(s1,s2)
# jp3 = j_prob(s1,s2,s3)
# cp2 = c_prob(s1,s2)
# cp3 = c_prob(s1,s2,s3)
# TExy = TE(s1,s2)
# TEyx = TE(s2,s1)
# print "TExy", TExy,
# print "TEyx", TEyx
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Classes and funtions for making symbolic
representations of time-series"""
import itertools
import eegpy
from eegpy.helper import factorial
from eegpy.misc import FATALERROR, EegpyBase, debug
#from eegpy.analysis.phasespace import make_time_delay_embedding
from eegpy.analysis.entropy.symbols import make_permutation_symbols, make_all_permutation_symbols
try:
import numpy as N
np = N
except ImportError:
raise FATALERROR('SciPy or NumPy not found!\nPlease visit www.scipy.org or numeric.scipy.org for more information.')
###########
# Classes #
###########
#############
# Functions #
#############
def entropy(x,symbols=None):
"""For a given set of symbols, returns the entropy.
H = - \sum_i=0^N p_i log(p_i)"""
ps = prob(x)
tmp = -(ps*N.log2(ps))
return np.ma.masked_invalid(tmp).sum()
def perm_entropy(x,w=4,t=1,normalize=True):
"""Calculate the permutation-entropy of a time-series x."""
pe = entropy(make_permutation_symbols(x,w,t))
if normalize:
pe=pe/N.log(factorial(w))
return pe
def joint_entropy(x,y,symbols=None):
jps = j_prob(x,y,symbols=symbols)
tmp = -(jps*np.log2(jps))
return np.ma.masked_invalid(tmp).sum()
def perm_M(x,y,w=4,t=1):
"""Permutation mutual information
Creates symbolic timeseries from x and y and calculates the mutual information
"""
s1 = make_permutation_symbols(x,w=w,t=t)
s2 = make_permutation_symbols(y,w=w,t=t)
return M(s1,s2,symbols="w%i"%w)
def perm_d(x,y,w=4,t=1):
"""Metric based on mutual information. Normalized to [0,1]
See http://en.wikipedia.org/wiki/Mutual_information#Metric
"""
s1 = make_permutation_symbols(x,w=w,t=t)
s2 = make_permutation_symbols(y,w=w,t=t)
je = joint_entropy(s1,s2,symbols="w%i"%w)
mi = M(s1,s2,symbols="w%i"%w)
return (je-mi)
def perm_D(x,y,w=4,t=1):
"""Metric based on mutual information. Normalized to [0,1]
See http://en.wikipedia.org/wiki/Mutual_information#Metric
"""
s1 = make_permutation_symbols(x,w=w,t=t)
s2 = make_permutation_symbols(y,w=w,t=t)
je = joint_entropy(s1,s2,symbols="w%i"%w)
mi = M(s1,s2,symbols="w%i"%w)
return (je-mi)/je
def perm_TE_ensemble(y,x,w=4,tau=1,test_surr=False):
"""Permutation transfer entropy of two sets of timeseries x and y
Measures information transfer from y to x.
Parameters:
y: 2d-array, first index timepoints, second index ensemble
x: equal-size array
w: word-size for creation of permutation-symbols
tau: time-delay for creation of permutation-symbols
test_surr: bool. If a surrogate-test should be perfomed or not
Returns: 1d-array of length y.shape[0]-1"""
s1 = make_permutation_symbols(y,w=w,t=tau)
s2 = make_permutation_symbols(x,w=w,t=tau)
return TE_ensemble(s1, s2)
def M(x,y,symbols=None):
"""Mutual information of two symbolic timeseries x and y"""
jp = j_prob(x,y,symbols=symbols)
px = prob(x,symbols=symbols)
py = prob(y,symbols=symbols)
rv = 0
px = px.reshape(-1,1).repeat(jp.shape[0],1)
py = py.reshape(1,-1).repeat(jp.shape[1],0)
tmp = jp*N.log2(jp/(px*py))
rv = N.ma.masked_invalid((tmp*(jp>0).astype("i"))).sum()
return rv
def TE(y,x,symbols=None):
"""Transfer entropy of two symbolic timeseries x and y
Measures information transfer from x to y"""
#rv = j_prob(x[1:],x[:-1],y[:-1])\
# *N.log2(c_prob(x[1:],x[:-1],y[:-1])/c_prob(x[1:],x[:-1]))
jp_xxy = j_prob(x[1:],x[:-1],y[:-1],symbols=symbols)
jp_xx = j_prob(x[1:],x[:-1],symbols=symbols)
jp_xy = j_prob(x[:-1],y[:-1],symbols=symbols)
p_x = prob(x,symbols=symbols)
#make all the size of jp_xxy to do vectorised calculations
#print jp_xx.shape, jp_xy.shape, jp_xxy.shape
jp_xx = N.tile(jp_xx,[jp_xxy.shape[2],1,1])
jp_xx = jp_xx.swapaxes(0,1)
jp_xx = jp_xx.swapaxes(1,2)
jp_xy = N.tile(jp_xy,[jp_xxy.shape[0],1,1])
p_x = N.tile(p_x,[jp_xxy.shape[0],jp_xxy.shape[2],1])
p_x = p_x.swapaxes(1,2)
rv = N.ma.masked_invalid(jp_xxy * N.log10(jp_xxy*p_x/(jp_xy*jp_xx))).sum()
# for ix1 in range(jp_xxy.shape[0]):
# for iy in range(jp_xxy.shape[1]):
# for ix in range(jp_xxy.shape[2]):
# #try:
# tmp = jp_xxy[ix1,ix,iy] * N.log10(jp_xxy[ix1,ix,iy]*p_x[ix]/(jp_xy[ix,iy]*jp_xx[ix1,ix]))
# if N.isfinite(tmp):
# rv+=tmp
#print ix, iy, ix1, rv
#except Exception, e:
#print "error"
#pass
return rv#N.ma.masked_invalid(rv).sum()
def perm_TE(y,x,w=4,t=1):
"""Creates symbolic timeseries from real data and calculates Transfer Entropy"""
s1 = make_permutation_symbols(x,w=w,t=t)
s2 = make_permutation_symbols(y,w=w,t=t)
#return TE(s2,s1,symbols="w%i"%w)
return TE(s2,s1,symbols=make_all_permutation_symbols(w))
def TE_ensemble(y,x,test_surr=False):
"""Transfer entropy of two sets of symbolic timeseries x and y
Measures information transfer from x to y.
:Parameters:
y: 2d-array, first index timepoints, second index ensemble
x: equal-size array
test_surr: bool. If a surrogate-test should be perfomed or not
:Returns: 1d-array of length y.shape[0]-1
"""
rv = N.zeros((y.shape[0]-1),"d")
for idx in range(y.shape[0]-1):
jp_xxy = j_prob(x[idx+1,:],x[idx,:],y[idx,:])
jp_xx = j_prob(x[idx+1,:],x[idx,:])
jp_xy = j_prob(x[idx,:],y[idx,:])
p_x = prob(x[idx])
#make all the size of jp_xxy to do vectorised calculations
jp_xx = N.tile(jp_xx,[jp_xxy.shape[2],1,1])
jp_xx = jp_xx.swapaxes(0,1)
jp_xx = jp_xx.swapaxes(1,2)
jp_xy = N.tile(jp_xy,[jp_xxy.shape[0],1,1])
p_x = N.tile(p_x,[jp_xxy.shape[0],jp_xxy.shape[2],1])
p_x = p_x.swapaxes(1,2)
#print idx, jp_xxy.shape, jp_xx.shape, jp_xy.shape, p_x.shape
rv[idx] = N.ma.masked_invalid(jp_xxy * N.log10(jp_xxy*p_x/(jp_xy*jp_xx))).sum()
# jp_xx = j_prob(x[idx+1,:],x[idx,:])
# jp_xy = j_prob(x[idx,:],y[idx,:])
# p_x = prob(x[idx])
# for ix1 in range(jp_xxy.shape[0]):
# for iy in range(jp_xxy.shape[2]):
# for ix in range(jp_xxy.shape[1]):
# tmp = jp_xxy[ix1,ix,iy] * N.log10(jp_xxy[ix1,ix,iy]*p_x[ix]/(jp_xy[ix,iy]*jp_xx[ix1,ix]))
# if N.isfinite(tmp):
# rv[idx]+=tmp
return rv
#Probability-functions
def prob(x,symbols=None):
"""Calculate the probabilities for each symbol"""
#print x
if symbols==None:
symbols = np.unique(x)
elif type(symbols) == str:
symbols = make_all_permutation_symbols(symbols)
symbdict = dict([(k,0) for k in symbols])
for xi in x:
symbdict[xi] += 1
ks = symbols
ks.sort()
ps = np.array([symbdict[k] for k in ks]).astype(np.float)
ps /= x.shape[0]
return ps
def j_prob(x,y,z=None,symbols=None):
"""The joint probability of the symbols in x and y"""
#print "symbls", symbols
#extract variables from args
#print args
if z==None:
assert len(x) == len(y), "Sequences must have same length"
else:
assert len(x) == len(y) and len(x) == len(z), "Sequences must have same length"
#Which symbols exist
if symbols==None:
symbols = np.unique(np.r_[x,y])
elif type(symbols) == str:
symbols = make_all_permutation_symbols(symbols)
if z==None:
ps = N.zeros((len(symbols),len(symbols)),"d")
ks = list(symbols)
ks.sort()
idx_dict = dict([(k,ks.index(k)) for k in ks])
for i in range(len(x)):
ps[idx_dict[x[i]],idx_dict[y[i]]] +=1
ps /= x.shape[0]
else:
ps = N.zeros((len(symbols),len(symbols),len(symbols)),"d")
ks = list(symbols)
ks.sort()
idx_dict = dict([(k,ks.index(k)) for k in ks])
for i in range(len(x)):
ps[idx_dict[x[i]],idx_dict[y[i]],idx_dict[z[i]]] +=1
ps /= x.shape[0]
return ps
def c_prob(x,y,z=None,symbols=None):
"""Conditional probability. Defined as P(X|Y) = P(X,Y)/P(Y)"""
jp = j_prob(x,y,z,symbols)
if z==None:
ps = jp/jp.mean(axis=1)
else:
ps = jp/j_prob(y,z)
#ps /= ps.mean(axis=1)
return ps
#Helper-functions
def join_symb_lists(li1,li2):
"""Not used..."""
rv = []
for li in [li1,li2]:
for v in li:
if not v in rv:
rv.append(v)
return rv
if __name__ == "__main__":
#from eegpy.analysis.entropy.base import j_prob, prob, c_prob
#from eegpy.analysis.entropy.symbols import make_permutation_symbols
from eegpy.models.roessler import TwoRoessler
import pylab as p
p.figure(1)
for i_r,rausch in enumerate(np.arange(0,3,0.3)):
ar1 = np.sin(np.arange(0,100,0.1)) + np.random.random((1000))*rausch
ar2 = np.sin(np.arange(0,100,0.1)) + np.random.random((1000))*rausch
p.subplot(10,1,i_r+1)
p.plot(ar1)
p.plot(ar2)
d = perm_d(ar1,ar2,w=4,t=50)
D = perm_D(ar1,ar2,w=4,t=50)
p.text(10,-0.5,"d=%.2f, D=%.2f"%(d,D),bbox={"fc":"w","alpha":0.7})
p.figure(2)
for i_e,e in enumerate(np.arange(0,0.4,0.04)):
tr = TwoRoessler(e1=e,e2=e)
ar = tr.integrate(np.arange(0,1000,0.1))[-4096:]
ar1 = ar[:,0]
ar2 = ar[:,3]
p.subplot(10,1,i_e+1)
p.plot(ar1)
p.plot(ar2)
d = perm_d(ar1,ar2,w=4,t=50)
D = perm_D(ar1,ar2,w=4,t=50)
p.text(10,-0.5,"d=%.2f, D=%.2f"%(d,D),bbox={"fc":"w","alpha":0.7})
#s1 = make_permutation_symbols(ar,4,1)
#probs = prob(s1,symbols="w4")
#print probs, probs.sum()
#ar3 = N.sin(N.arange(0,5,0.005))
# eeg = eegpy.F32("/home/thorsten/443_as_fsl.f32","r")
# t = N.zeros((25,25),"d")
# for i in range(25):#range(eeg.num_channels):
# for j in range(25):#range(eeg.num_channels):
# s1 = make_permutation_symbols(eeg[10000:20000,i],t=10)
# s2 = make_permutation_symbols(eeg[10000:20000,j],t=10)
# t[i,j] = TE(s1,s2)
# print "TE(%i->%i)"%(i,j), t[i,j]
#eeg = eegpy.open_eeg("/media/Extern/public/Experimente/AudioStroop/2008-07-29_Rieke/eeg/rieke_as.f32")
#evt = eegpy.EventTable("/media/Extern/public/Experimente/AudioStroop/2008-07-29_Rieke/eeg/rieke_as.vmrk")
#print evt.keys()
#ts = evt["S65282"]
#data = eeg.get_data_for_events(ts, (-200,1000))
#s1 = make_permutation_symbols(data[:,13,:],t=10)
#print data.shape, data.mean()
#s1 = make_permutation_symbols(data[:,13,:],w=3,t=10)
#s2 = make_permutation_symbols(data[:,14,:],w=3,t=10)
#w=3
#tau=10
#te = N.zeros((data.shape[0]-((w-1)*tau+1),data.shape[1],data.shape[1]),"d")
#import time
#t_start = time.time()
#for ch1 in range(data.shape[1]):
# for ch2 in range(data.shape[1]):
# te[:,ch1,ch2] = perm_TE_ensemble(data[:,ch1,:], data[:,ch2,:],w=w,tau=tau)
# print "<PTE(%i,%i)> ="%(ch1,ch2), te[:,ch1,ch2].mean()
#print "Duration of calculation:", time.time()-t_start
# ar2 = ar3[::-1]
# ar1 = -ar3
# s1 = make_permutation_symbols(ar1)
# s2 = make_permutation_symbols(ar2)
# s3 = make_permutation_symbols(ar3)
# jp2 = j_prob(s1,s2)
# jp3 = j_prob(s1,s2,s3)
# cp2 = c_prob(s1,s2)
# cp3 = c_prob(s1,s2,s3)
# TExy = TE(s1,s2)
# TEyx = TE(s2,s1)
# print "TExy", TExy,
# print "TEyx", TEyx | en | 0.562977 | #!/usr/bin/env python # -*- coding: utf-8 -*- Classes and funtions for making symbolic representations of time-series #from eegpy.analysis.phasespace import make_time_delay_embedding ########### # Classes # ########### ############# # Functions # ############# For a given set of symbols, returns the entropy. H = - \sum_i=0^N p_i log(p_i) Calculate the permutation-entropy of a time-series x. Permutation mutual information Creates symbolic timeseries from x and y and calculates the mutual information Metric based on mutual information. Normalized to [0,1] See http://en.wikipedia.org/wiki/Mutual_information#Metric Metric based on mutual information. Normalized to [0,1] See http://en.wikipedia.org/wiki/Mutual_information#Metric Permutation transfer entropy of two sets of timeseries x and y Measures information transfer from y to x. Parameters: y: 2d-array, first index timepoints, second index ensemble x: equal-size array w: word-size for creation of permutation-symbols tau: time-delay for creation of permutation-symbols test_surr: bool. If a surrogate-test should be perfomed or not Returns: 1d-array of length y.shape[0]-1 Mutual information of two symbolic timeseries x and y Transfer entropy of two symbolic timeseries x and y Measures information transfer from x to y #rv = j_prob(x[1:],x[:-1],y[:-1])\ # *N.log2(c_prob(x[1:],x[:-1],y[:-1])/c_prob(x[1:],x[:-1])) #make all the size of jp_xxy to do vectorised calculations #print jp_xx.shape, jp_xy.shape, jp_xxy.shape # for ix1 in range(jp_xxy.shape[0]): # for iy in range(jp_xxy.shape[1]): # for ix in range(jp_xxy.shape[2]): # #try: # tmp = jp_xxy[ix1,ix,iy] * N.log10(jp_xxy[ix1,ix,iy]*p_x[ix]/(jp_xy[ix,iy]*jp_xx[ix1,ix])) # if N.isfinite(tmp): # rv+=tmp #print ix, iy, ix1, rv #except Exception, e: #print "error" #pass #N.ma.masked_invalid(rv).sum() Creates symbolic timeseries from real data and calculates Transfer Entropy #return TE(s2,s1,symbols="w%i"%w) Transfer entropy of two sets of symbolic timeseries x and y Measures information transfer from x to y. :Parameters: y: 2d-array, first index timepoints, second index ensemble x: equal-size array test_surr: bool. If a surrogate-test should be perfomed or not :Returns: 1d-array of length y.shape[0]-1 #make all the size of jp_xxy to do vectorised calculations #print idx, jp_xxy.shape, jp_xx.shape, jp_xy.shape, p_x.shape # jp_xx = j_prob(x[idx+1,:],x[idx,:]) # jp_xy = j_prob(x[idx,:],y[idx,:]) # p_x = prob(x[idx]) # for ix1 in range(jp_xxy.shape[0]): # for iy in range(jp_xxy.shape[2]): # for ix in range(jp_xxy.shape[1]): # tmp = jp_xxy[ix1,ix,iy] * N.log10(jp_xxy[ix1,ix,iy]*p_x[ix]/(jp_xy[ix,iy]*jp_xx[ix1,ix])) # if N.isfinite(tmp): # rv[idx]+=tmp #Probability-functions Calculate the probabilities for each symbol #print x The joint probability of the symbols in x and y #print "symbls", symbols #extract variables from args #print args #Which symbols exist Conditional probability. Defined as P(X|Y) = P(X,Y)/P(Y) #ps /= ps.mean(axis=1) #Helper-functions Not used... #from eegpy.analysis.entropy.base import j_prob, prob, c_prob #from eegpy.analysis.entropy.symbols import make_permutation_symbols #s1 = make_permutation_symbols(ar,4,1) #probs = prob(s1,symbols="w4") #print probs, probs.sum() #ar3 = N.sin(N.arange(0,5,0.005)) # eeg = eegpy.F32("/home/thorsten/443_as_fsl.f32","r") # t = N.zeros((25,25),"d") # for i in range(25):#range(eeg.num_channels): # for j in range(25):#range(eeg.num_channels): # s1 = make_permutation_symbols(eeg[10000:20000,i],t=10) # s2 = make_permutation_symbols(eeg[10000:20000,j],t=10) # t[i,j] = TE(s1,s2) # print "TE(%i->%i)"%(i,j), t[i,j] #eeg = eegpy.open_eeg("/media/Extern/public/Experimente/AudioStroop/2008-07-29_Rieke/eeg/rieke_as.f32") #evt = eegpy.EventTable("/media/Extern/public/Experimente/AudioStroop/2008-07-29_Rieke/eeg/rieke_as.vmrk") #print evt.keys() #ts = evt["S65282"] #data = eeg.get_data_for_events(ts, (-200,1000)) #s1 = make_permutation_symbols(data[:,13,:],t=10) #print data.shape, data.mean() #s1 = make_permutation_symbols(data[:,13,:],w=3,t=10) #s2 = make_permutation_symbols(data[:,14,:],w=3,t=10) #w=3 #tau=10 #te = N.zeros((data.shape[0]-((w-1)*tau+1),data.shape[1],data.shape[1]),"d") #import time #t_start = time.time() #for ch1 in range(data.shape[1]): # for ch2 in range(data.shape[1]): # te[:,ch1,ch2] = perm_TE_ensemble(data[:,ch1,:], data[:,ch2,:],w=w,tau=tau) # print "<PTE(%i,%i)> ="%(ch1,ch2), te[:,ch1,ch2].mean() #print "Duration of calculation:", time.time()-t_start # ar2 = ar3[::-1] # ar1 = -ar3 # s1 = make_permutation_symbols(ar1) # s2 = make_permutation_symbols(ar2) # s3 = make_permutation_symbols(ar3) # jp2 = j_prob(s1,s2) # jp3 = j_prob(s1,s2,s3) # cp2 = c_prob(s1,s2) # cp3 = c_prob(s1,s2,s3) # TExy = TE(s1,s2) # TEyx = TE(s2,s1) # print "TExy", TExy, # print "TEyx", TEyx | 3.007177 | 3 |
pitcher/__init__.py | twobulls/pitcher | 0 | 6616104 | from .application import Application
from .middleware import Middleware
from .request import Request
from .response import Response
from .router import Route
| from .application import Application
from .middleware import Middleware
from .request import Request
from .response import Response
from .router import Route
| none | 1 | 1.138252 | 1 | |
find_keywords_test.py | melkonyan/whoswho_keywords | 0 | 6616105 | import unittest
from find_keywords import KeywordsFinder
class FindKeywordsTest(unittest.TestCase):
def test_find_keywords(self):
finder = KeywordsFinder()
finder.keywords_list = ['kw']
finder.keyword_threshold = 2
self.assertEqual(finder.keywords({1: ['kw', 'a'], 2: ['kw', 'a']}), ('kw',))
def test_find_keywords_no_double_counting(self):
finder = KeywordsFinder()
finder.keywords_list = ['kw']
finder.keyword_threshold = 2
self.assertEqual(finder.keywords({1: ['kw', 'kw']}), ())
def test_find_keywords_exact_match(self):
finder = KeywordsFinder()
finder.keywords_list = ['kw']
finder.keyword_threshold = 1
self.assertEqual(finder.keywords({1: ['kw kw']}), ())
def test_find_keywords_sorted(self):
finder = KeywordsFinder()
finder.keywords_list = ['kw1', 'kw2']
finder.keyword_threshold = 1
self.assertEqual(finder.keywords({1: ['kw1', 'kw2'], 2: ['kw2']}), ('kw2', 'kw1'))
if __name__ == '__main__':
unittest.main()
| import unittest
from find_keywords import KeywordsFinder
class FindKeywordsTest(unittest.TestCase):
def test_find_keywords(self):
finder = KeywordsFinder()
finder.keywords_list = ['kw']
finder.keyword_threshold = 2
self.assertEqual(finder.keywords({1: ['kw', 'a'], 2: ['kw', 'a']}), ('kw',))
def test_find_keywords_no_double_counting(self):
finder = KeywordsFinder()
finder.keywords_list = ['kw']
finder.keyword_threshold = 2
self.assertEqual(finder.keywords({1: ['kw', 'kw']}), ())
def test_find_keywords_exact_match(self):
finder = KeywordsFinder()
finder.keywords_list = ['kw']
finder.keyword_threshold = 1
self.assertEqual(finder.keywords({1: ['kw kw']}), ())
def test_find_keywords_sorted(self):
finder = KeywordsFinder()
finder.keywords_list = ['kw1', 'kw2']
finder.keyword_threshold = 1
self.assertEqual(finder.keywords({1: ['kw1', 'kw2'], 2: ['kw2']}), ('kw2', 'kw1'))
if __name__ == '__main__':
unittest.main()
| none | 1 | 3.363779 | 3 | |
web/administrators/apps.py | GuillaumeCaillou/carbure | 0 | 6616106 | from django.apps import AppConfig
class AdministratorsConfig(AppConfig):
name = 'administrators'
| from django.apps import AppConfig
class AdministratorsConfig(AppConfig):
name = 'administrators'
| none | 1 | 1.16259 | 1 | |
Exercicios/ex095.py | Dobravoski/Exercicios-Python | 0 | 6616107 | <reponame>Dobravoski/Exercicios-Python
time = []
dados = {}
gol = []
cont = 0
while True:
dados.clear()
dados = {'nome': str(input('Nome do jogador: ')).strip().capitalize()}
partidas = int(input(f'Quantas partidas {dados["nome"]} jogou? '))
gol.clear()
for c in range(1, partidas + 1):
gol.append(int(input(f'Quantos gols na {c}ª partida? ')))
dados['totgols'] = sum(gol)
dados['gols'] = gol[:]
time.append(dados.copy())
while True:
continuar = str(input('Quer continuar? [S/N]: ')).strip().upper()[0]
if continuar == 'S' or continuar == 'N':
break
if continuar == 'N':
break
print('-=' * 25)
print('cod ', end='')
for i in dados.keys():
print(f'{i:<15}', end='')
print()
print('-=' * 25)
for k, v in enumerate(time):
print(f'{k:>4}', end='')
for d in v.values():
print(f'{str(d):>15}', end='')
print()
print('-' * 30)
while True:
busca = int(input('Mostrar dados de qual jogador? (999 para parar): '))
if busca == 999:
break
elif busca > len(time):
print(f'ERRO! Não existe jogador com código {busca} na lista.')
else:
print(f'-- LEVANTAMENTO DO JOGADOR {time[busca]["nome"]} --')
for i, g in enumerate(time[busca]["gols"]):
print(f' No {i + 1}º jogo, {g} gols.')
print('-' * 30)
print('<< VOLTE SEMPRE! >>')
| time = []
dados = {}
gol = []
cont = 0
while True:
dados.clear()
dados = {'nome': str(input('Nome do jogador: ')).strip().capitalize()}
partidas = int(input(f'Quantas partidas {dados["nome"]} jogou? '))
gol.clear()
for c in range(1, partidas + 1):
gol.append(int(input(f'Quantos gols na {c}ª partida? ')))
dados['totgols'] = sum(gol)
dados['gols'] = gol[:]
time.append(dados.copy())
while True:
continuar = str(input('Quer continuar? [S/N]: ')).strip().upper()[0]
if continuar == 'S' or continuar == 'N':
break
if continuar == 'N':
break
print('-=' * 25)
print('cod ', end='')
for i in dados.keys():
print(f'{i:<15}', end='')
print()
print('-=' * 25)
for k, v in enumerate(time):
print(f'{k:>4}', end='')
for d in v.values():
print(f'{str(d):>15}', end='')
print()
print('-' * 30)
while True:
busca = int(input('Mostrar dados de qual jogador? (999 para parar): '))
if busca == 999:
break
elif busca > len(time):
print(f'ERRO! Não existe jogador com código {busca} na lista.')
else:
print(f'-- LEVANTAMENTO DO JOGADOR {time[busca]["nome"]} --')
for i, g in enumerate(time[busca]["gols"]):
print(f' No {i + 1}º jogo, {g} gols.')
print('-' * 30)
print('<< VOLTE SEMPRE! >>') | none | 1 | 3.540682 | 4 | |
sales/models.py | coding-eunbong73/django-web | 0 | 6616108 | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
class 아이디(AbstractUser):
pass
class Sale(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
age = models.IntegerField(default=0)
person = models.ForeignKey("Person", on_delete=models.CASCADE)
def __str__(self):
return f"{self.last_name} {self.first_name}"
class UserProfile(models.Model):
회원 = models.OneToOneField(아이디, on_delete=models.CASCADE)
def __str__(self):
return self.회원.username
class Person(models.Model):
회원 = models.OneToOneField(아이디, on_delete=models.CASCADE)
def __str__(self):
return self.회원.email
def signalMemberCreation(sender, instance, created, **kwargs):
if created :
UserProfile.objects.create(회원=instance)
Person.objects.create(회원=instance)
post_save.connect(signalMemberCreation, sender=아이디) | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
class 아이디(AbstractUser):
pass
class Sale(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
age = models.IntegerField(default=0)
person = models.ForeignKey("Person", on_delete=models.CASCADE)
def __str__(self):
return f"{self.last_name} {self.first_name}"
class UserProfile(models.Model):
회원 = models.OneToOneField(아이디, on_delete=models.CASCADE)
def __str__(self):
return self.회원.username
class Person(models.Model):
회원 = models.OneToOneField(아이디, on_delete=models.CASCADE)
def __str__(self):
return self.회원.email
def signalMemberCreation(sender, instance, created, **kwargs):
if created :
UserProfile.objects.create(회원=instance)
Person.objects.create(회원=instance)
post_save.connect(signalMemberCreation, sender=아이디) | none | 1 | 2.27567 | 2 | |
Python/LeetCode/733. Flood Fill.py | devMEremenko/Coding-Challenges | 10 | 6616109 | # https://leetcode.com/problems/flood-fill/solution/
class Solution:
def floodFill(self, image: [[int]], sr: int, sc: int, newColor: int) -> [[int]]:
self.dfs(image, sr, sc, newColor, image[sr][sc])
return image
def dfs(self, image, sr, sc, newColor, originalColor):
if sr < 0 or sr >= len(image):
return
if sc < 0 or sc >= len(image[0]):
return
if image[sr][sc] == newColor:
return
if image[sr][sc] == originalColor:
image[sr][sc] = newColor
self.dfs(image, sr - 1, sc, newColor, originalColor)
self.dfs(image, sr + 1, sc, newColor, originalColor)
self.dfs(image, sr, sc + 1, newColor, originalColor)
self.dfs(image, sr, sc - 1, newColor, originalColor)
| # https://leetcode.com/problems/flood-fill/solution/
class Solution:
def floodFill(self, image: [[int]], sr: int, sc: int, newColor: int) -> [[int]]:
self.dfs(image, sr, sc, newColor, image[sr][sc])
return image
def dfs(self, image, sr, sc, newColor, originalColor):
if sr < 0 or sr >= len(image):
return
if sc < 0 or sc >= len(image[0]):
return
if image[sr][sc] == newColor:
return
if image[sr][sc] == originalColor:
image[sr][sc] = newColor
self.dfs(image, sr - 1, sc, newColor, originalColor)
self.dfs(image, sr + 1, sc, newColor, originalColor)
self.dfs(image, sr, sc + 1, newColor, originalColor)
self.dfs(image, sr, sc - 1, newColor, originalColor)
| en | 0.761194 | # https://leetcode.com/problems/flood-fill/solution/ | 3.49491 | 3 |
sqlite_demo/test_diskcache.py | perfectbullet/albumy | 0 | 6616110 | <gh_stars>0
import diskcache
#设置文件到内存中。=。 速度还不错
cache = diskcache.Cache("/tmp")
#写入缓存
cache.set(
key="key",
value="value1",
expire="100",
tag="namespace1"
)
#手动清除超过生存时间的缓存
cache.cull()
#清除命名空间的缓存
cache.evict() | import diskcache
#设置文件到内存中。=。 速度还不错
cache = diskcache.Cache("/tmp")
#写入缓存
cache.set(
key="key",
value="value1",
expire="100",
tag="namespace1"
)
#手动清除超过生存时间的缓存
cache.cull()
#清除命名空间的缓存
cache.evict() | zh | 0.992013 | #设置文件到内存中。=。 速度还不错 #写入缓存 #手动清除超过生存时间的缓存 #清除命名空间的缓存 | 1.939174 | 2 |
validations/links.py | JuanjoSalvador/gitcollab | 10 | 6616111 | <reponame>JuanjoSalvador/gitcollab<gh_stars>1-10
# Validaciones de enlaces
def github_link(url):
return "github.com" in url
def gitlab_link(url):
return "gitlab.com" in url | # Validaciones de enlaces
def github_link(url):
return "github.com" in url
def gitlab_link(url):
return "gitlab.com" in url | es | 0.995235 | # Validaciones de enlaces | 2.127669 | 2 |
relancer-exp/original_notebooks/mansoordaku_ckdisease/data-cleaning-classification-algorithms-comparison.py | Chenguang-Zhu/relancer | 1 | 6616112 | #!/usr/bin/env python
# coding: utf-8
# **Data cleaning&Classification algorithms comparison**
# **In this study, chronic kidney disease was estimated using classification algorithms. You'll find this kernel;**
# * The codes I think will be useful for data cleaning
# * How to Handle Missing Data,what did I do?
# * Data Visualization
# * Classification Algorithms
# -KNN
# -Navie-Bayes
# -Logistic Regression
# -Decision Tree
# -Random Forest
# -Support Vector Machine
# * Success rate of classification algorithms
# * Conclusion
#
#
# In[ ]:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import seaborn as sns #for confusion matrix
#For data visualization
import plotly.plotly as py
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)
import plotly.graph_objs as go
# Input data files are available in the "../../../input/mansoordaku_ckdisease/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory
import warnings
warnings.filterwarnings('ignore')
import os
print(os.listdir("../../../input/mansoordaku_ckdisease"))
# Any results you write to the current directory are saved as output.
# In[ ]:
data=pd.read_csv("../../../input/mansoordaku_ckdisease/kidney_disease.csv")
# In[ ]:
data.info() #data types and feature names.
#I'll change the data types of some parameters in the following codes
# In[ ]:
data.head() #first 5 samples in dataset
# In[ ]:
data.classification.unique()
# **PREPARE DATA**
#
# **1) 3 unique values appear in the data set. However, there is no value called "ckd\t. " I have written the following code to solve this problem.**
# In[ ]:
data.classification=data.classification.replace("ckd\t","ckd")
# In[ ]:
data.classification.unique() #problem solved.
# **2) The "id" parameter will not work for classification, so I'm removing this parameter from the data set.**
# In[ ]:
data.drop("id",axis=1,inplace=True)
# In[ ]:
data.head() #id parameter dropped.
# **3) I changed the target parameter values to 1 and 0 to be able to use the classification algorithms. If the value is "ckd" is 1, if not equal to 0. **
# In[ ]:
data.classification=[1 if each=="ckd" else 0 for each in data.classification]
# In[ ]:
data.head()
# **4) I used the following code to find out how many "NaN" values in which parameter.**
# In[ ]:
data.isnull().sum()
#
# **5)Sometimes instead of Nan in the data set, "?" value can be found. To solve this problem ; **df = data [(data! = '?'). all (axis = 1)]** can be used.**
#
# **How to Handle Missing Data,what did I do?**
#
# Pandas provides the dropna() function that can be used to drop either columns or rows with missing data. We can use dropna() to remove all rows with missing data
# Removing rows with missing values can be too limiting on some predictive modeling problems, an alternative is to impute missing values.
# Imputing refers to using a model to replace missing values.
#
# There are many options we could consider when replacing a missing value, for example:
#
# A constant value that has meaning within the domain, such as 0, distinct from all other values.
# A value from another randomly selected record.
# A mean, median or mode value for the column.
# A value estimated by another predictive model.
#
# Pandas provides the fillna() function for replacing missing values with a specific value.
#
# For example, we can use fillna() to replace missing values with the mean value for each column,
# For example; dataset.fillna(dataset.mean(), inplace=True)
# **6) I can use dropna() to remove all rows with missing data**
#
# There were 25 parameters of 400 samples before writing this code. After writing this code, there are 25 parameters left in 158 examples.
#
# The number of samples decreased but the reliability of the model increased.
# In[ ]:
df=data.dropna(axis=0)
print(data.shape)
print(df.shape)
df.head()
# **7) indexes are not sequential as you can see in the table above. I used the following code to sort indexes.**
# In[ ]:
df.index=range(0,len(df),1)
df.head()
# **8) I corrected some of the parameters.**
# In[ ]:
#you can see that the values have changed.
df.wc=df.wc.replace("\t6200",6200)
df.wc=df.wc.replace("\t8400",8400)
print(df.loc[11,["wc"]])
print(df.loc[20,["wc"]])
# **9) I'll change the data types of some parameters **
# In[ ]:
df.pcv=df.pcv.astype(int)
df.wc=df.wc.astype(int)
df.rc=df.rc.astype(float)
df.info()
# **10)Keep in mind, the goal in this section is to have all the columns as numeric columns (int or float data type), and containing no missing values. We just dealt with the missing values, so let's now find out the number of columns that are of the object data type and then move on to process them into numeric form.**
# In[ ]:
dtype_object=df.select_dtypes(include=['object'])
dtype_object.head()
# **11)display a sample row to get a better sense of how the values in each column are formatted.**
# In[ ]:
for x in dtype_object.columns:
print("{} unique values:".format(x),df[x].unique())
print("*"*20)
# **12)The ordinal values to integers, we can use the pandas DataFrame method replace() to"rbc","pc","pcc","ba","htn","dm","cad","appet","pe" and "ane" to appropriate numeric values**
# In[ ]:
dictonary = { "rbc": { "abnormal":1, "normal": 0, }, "pc":{ "abnormal":1, "normal": 0, }, "pcc":{ "present":1, "notpresent":0, }, "ba":{ "notpresent":0, "present": 1, }, "htn":{ "yes":1, "no": 0, }, "dm":{ "yes":1, "no":0, }, "cad":{ "yes":1, "no": 0, }, "appet":{ "good":1, "poor": 0, }, "pe":{ "yes":1, "no":0, }, "ane":{ "yes":1, "no":0, } }
# In[ ]:
#We used categorical values as numerical to replace them.
df=df.replace(dictonary)
# In[ ]:
df.head() #All values are numerical.
# **VISUALIZATION**
# In[ ]:
#HEAT MAP #correlation of parameters
f,ax=plt.subplots(figsize=(15,15))
print()
plt.xticks(rotation=45)
plt.yticks(rotation=45)
print()
# In[ ]:
#box-plot
trace0 = go.Box( y=df.bp, name = 'Bp', marker = dict( color = 'rgb(12, 12, 140)', ) )
trace1 = go.Box( y=df.sod, name = 'Sod', marker = dict( color = 'rgb(12, 128, 128)', ) )
data = [trace0, trace1]
iplot(data)
# In[ ]:
#Line plot
df2=df.copy()
df2["id"]=range(1,(len(df.ba)+1),1)
df2["df2_bp_norm"]=(df2.bp-np.min(df2.bp))/(np.max(df2.bp)-np.min(df2.bp))
df2["df2_hemo_norm"]=(df2.hemo-np.min(df2.hemo))/(np.max(df2.hemo)-np.min(df2.hemo))
#Line Plot
trace1 = go.Scatter( x = df2.id, y = df2.df2_bp_norm, mode = "lines", name = "Blood Press.", marker = dict(color = 'rgba(16, 112, 2, 0.8)'), text= df.age)
trace2 = go.Scatter( x = df2.id, y = df2.df2_hemo_norm, mode = "lines+markers", name = "Hemo", marker = dict(color = 'rgba(80, 26, 80, 0.8)'), text= df.age)
data=[trace1,trace2]
layout=dict(title="Blood Press and Hemoglobin values according the age", xaxis=dict(title="İd",ticklen=5,zeroline=False))
fig=dict(data=data,layout=layout)
iplot(fig)
# **CLASSIFICATION ALGORITHMS**
# In[ ]:
score=[] #these variables will be used to show the algorithm name and its successes.
algorithms=[]
# In[ ]:
#KNN
from sklearn.neighbors import KNeighborsClassifier
y=df["classification"].values
x_data=df.drop(["classification"],axis=1)
#Normalization
x=(x_data-np.min(x_data))/(np.max(x_data)-np.min(x_data))
#Preparing the test and training set
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=1,test_size=0.3)
#model and accuracy
knn=KNeighborsClassifier(n_neighbors=3)
knn.fit(x_train,y_train)
knn.predict(x_test)
score.append(knn.score(x_test,y_test)*100)
algorithms.append("KNN")
print("KNN accuracy =",knn.score(x_test,y_test)*100)
#Confusion Matrix
from sklearn.metrics import confusion_matrix
y_pred=knn.predict(x_test)
y_true=y_test
cm=confusion_matrix(y_true,y_pred)
#Confusion Matrix on Heatmap
f,ax=plt.subplots(figsize=(5,5))
print()
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.title(" KNN Confusion Matrix")
print()
#%%
# In[ ]:
#Navie-Bayes
from sklearn.naive_bayes import GaussianNB
nb=GaussianNB()
#Training
nb.fit(x_train,y_train)
#Test
score.append(nb.score(x_test,y_test)*100)
algorithms.append("Navie-Bayes")
print("Navie Bayes accuracy =",nb.score(x_test,y_test)*100)
#Confusion Matrix
from sklearn.metrics import confusion_matrix
y_pred=nb.predict(x_test)
y_true=y_test
cm=confusion_matrix(y_true,y_pred)
#Confusion Matrix on Heatmap
f,ax=plt.subplots(figsize=(5,5))
print()
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.title("Navie Bayes Confusion Matrix")
print()
# In[ ]:
#RANDOM FOREST
from sklearn.ensemble import RandomForestClassifier
rf=RandomForestClassifier(n_estimators=100,random_state=1)
rf.fit(x_train,y_train)
score.append(rf.score(x_test,y_test)*100)
algorithms.append("Random Forest")
print("Random Forest accuracy =",rf.score(x_test,y_test))
#Confusion Matrix
from sklearn.metrics import confusion_matrix
y_pred=rf.predict(x_test)
y_true=y_test
cm=confusion_matrix(y_true,y_pred)
#Confusion Matrix on Heatmap
f,ax=plt.subplots(figsize=(5,5))
print()
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.title("Random Forest Confusion Matrix")
print()
# In[ ]:
#Support Vector Machine
from sklearn.svm import SVC
svm=SVC(random_state=1)
svm.fit(x_train,y_train)
score.append(svm.score(x_test,y_test)*100)
algorithms.append("Support Vector Machine")
print("svm test accuracy =",svm.score(x_test,y_test)*100)
#Confusion Matrix
from sklearn.metrics import confusion_matrix
y_pred=svm.predict(x_test)
y_true=y_test
cm=confusion_matrix(y_true,y_pred)
#Confusion Matrix on Heatmap
f,ax=plt.subplots(figsize=(5,5))
print()
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.title("Support Vector Machine Confusion Matrix")
print()
# In[ ]:
#Decision Tree
from sklearn.tree import DecisionTreeClassifier
dt=DecisionTreeClassifier()
dt.fit(x_train,y_train)
print("Decision Tree accuracy:",dt.score(x_test,y_test)*100)
score.append(dt.score(x_test,y_test)*100)
algorithms.append("Decision Tree")
#Confusion Matrix
from sklearn.metrics import confusion_matrix
y_pred=dt.predict(x_test)
y_true=y_test
cm=confusion_matrix(y_true,y_pred)
#Confusion Matrix on Heatmap
f,ax=plt.subplots(figsize=(5,5))
print()
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.title("Decision Tree Confusion Matrix")
print()
# In[ ]:
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression()
lr.fit(x_train,y_train)
score.append(lr.score(x_test,y_test)*100)
algorithms.append("Logistic Regression")
print("test accuracy {}".format(lr.score(x_test,y_test)))
#Confusion Matrix
from sklearn.metrics import confusion_matrix
y_pred=lr.predict(x_test)
y_true=y_test
cm=confusion_matrix(y_true,y_pred)
#Confusion Matrix on Heatmap
f,ax=plt.subplots(figsize=(5,5))
print()
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.title("Logistic Regression Confusion Matrix")
print()
# In[ ]:
trace1 = { 'x': algorithms, 'y': score, 'name': 'score', 'type': 'bar' }
# In[ ]:
data = [trace1];
layout = { 'xaxis': {'title': 'Classification Algorithms'}, 'title': 'Comparison of the accuracy of classification algorithms' };
fig = go.Figure(data = data, layout = layout)
iplot(fig)
# **CONCLUSION**
#
# In this study, there were 400 samples and 26 parameters.However, some samples had no parameter values. For this reason, I prepared the data to use the classification algorithms. I did data visualization work. I applied classification algorithms and compared success rates with each other. It was a nice work for me. I hope you like it.
# If you have questions and suggestions, you can comment. Because your questions and suggestions are very valuable for me.
#
| #!/usr/bin/env python
# coding: utf-8
# **Data cleaning&Classification algorithms comparison**
# **In this study, chronic kidney disease was estimated using classification algorithms. You'll find this kernel;**
# * The codes I think will be useful for data cleaning
# * How to Handle Missing Data,what did I do?
# * Data Visualization
# * Classification Algorithms
# -KNN
# -Navie-Bayes
# -Logistic Regression
# -Decision Tree
# -Random Forest
# -Support Vector Machine
# * Success rate of classification algorithms
# * Conclusion
#
#
# In[ ]:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt
import seaborn as sns #for confusion matrix
#For data visualization
import plotly.plotly as py
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode(connected=True)
import plotly.graph_objs as go
# Input data files are available in the "../../../input/mansoordaku_ckdisease/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory
import warnings
warnings.filterwarnings('ignore')
import os
print(os.listdir("../../../input/mansoordaku_ckdisease"))
# Any results you write to the current directory are saved as output.
# In[ ]:
data=pd.read_csv("../../../input/mansoordaku_ckdisease/kidney_disease.csv")
# In[ ]:
data.info() #data types and feature names.
#I'll change the data types of some parameters in the following codes
# In[ ]:
data.head() #first 5 samples in dataset
# In[ ]:
data.classification.unique()
# **PREPARE DATA**
#
# **1) 3 unique values appear in the data set. However, there is no value called "ckd\t. " I have written the following code to solve this problem.**
# In[ ]:
data.classification=data.classification.replace("ckd\t","ckd")
# In[ ]:
data.classification.unique() #problem solved.
# **2) The "id" parameter will not work for classification, so I'm removing this parameter from the data set.**
# In[ ]:
data.drop("id",axis=1,inplace=True)
# In[ ]:
data.head() #id parameter dropped.
# **3) I changed the target parameter values to 1 and 0 to be able to use the classification algorithms. If the value is "ckd" is 1, if not equal to 0. **
# In[ ]:
data.classification=[1 if each=="ckd" else 0 for each in data.classification]
# In[ ]:
data.head()
# **4) I used the following code to find out how many "NaN" values in which parameter.**
# In[ ]:
data.isnull().sum()
#
# **5)Sometimes instead of Nan in the data set, "?" value can be found. To solve this problem ; **df = data [(data! = '?'). all (axis = 1)]** can be used.**
#
# **How to Handle Missing Data,what did I do?**
#
# Pandas provides the dropna() function that can be used to drop either columns or rows with missing data. We can use dropna() to remove all rows with missing data
# Removing rows with missing values can be too limiting on some predictive modeling problems, an alternative is to impute missing values.
# Imputing refers to using a model to replace missing values.
#
# There are many options we could consider when replacing a missing value, for example:
#
# A constant value that has meaning within the domain, such as 0, distinct from all other values.
# A value from another randomly selected record.
# A mean, median or mode value for the column.
# A value estimated by another predictive model.
#
# Pandas provides the fillna() function for replacing missing values with a specific value.
#
# For example, we can use fillna() to replace missing values with the mean value for each column,
# For example; dataset.fillna(dataset.mean(), inplace=True)
# **6) I can use dropna() to remove all rows with missing data**
#
# There were 25 parameters of 400 samples before writing this code. After writing this code, there are 25 parameters left in 158 examples.
#
# The number of samples decreased but the reliability of the model increased.
# In[ ]:
df=data.dropna(axis=0)
print(data.shape)
print(df.shape)
df.head()
# **7) indexes are not sequential as you can see in the table above. I used the following code to sort indexes.**
# In[ ]:
df.index=range(0,len(df),1)
df.head()
# **8) I corrected some of the parameters.**
# In[ ]:
#you can see that the values have changed.
df.wc=df.wc.replace("\t6200",6200)
df.wc=df.wc.replace("\t8400",8400)
print(df.loc[11,["wc"]])
print(df.loc[20,["wc"]])
# **9) I'll change the data types of some parameters **
# In[ ]:
df.pcv=df.pcv.astype(int)
df.wc=df.wc.astype(int)
df.rc=df.rc.astype(float)
df.info()
# **10)Keep in mind, the goal in this section is to have all the columns as numeric columns (int or float data type), and containing no missing values. We just dealt with the missing values, so let's now find out the number of columns that are of the object data type and then move on to process them into numeric form.**
# In[ ]:
dtype_object=df.select_dtypes(include=['object'])
dtype_object.head()
# **11)display a sample row to get a better sense of how the values in each column are formatted.**
# In[ ]:
for x in dtype_object.columns:
print("{} unique values:".format(x),df[x].unique())
print("*"*20)
# **12)The ordinal values to integers, we can use the pandas DataFrame method replace() to"rbc","pc","pcc","ba","htn","dm","cad","appet","pe" and "ane" to appropriate numeric values**
# In[ ]:
dictonary = { "rbc": { "abnormal":1, "normal": 0, }, "pc":{ "abnormal":1, "normal": 0, }, "pcc":{ "present":1, "notpresent":0, }, "ba":{ "notpresent":0, "present": 1, }, "htn":{ "yes":1, "no": 0, }, "dm":{ "yes":1, "no":0, }, "cad":{ "yes":1, "no": 0, }, "appet":{ "good":1, "poor": 0, }, "pe":{ "yes":1, "no":0, }, "ane":{ "yes":1, "no":0, } }
# In[ ]:
#We used categorical values as numerical to replace them.
df=df.replace(dictonary)
# In[ ]:
df.head() #All values are numerical.
# **VISUALIZATION**
# In[ ]:
#HEAT MAP #correlation of parameters
f,ax=plt.subplots(figsize=(15,15))
print()
plt.xticks(rotation=45)
plt.yticks(rotation=45)
print()
# In[ ]:
#box-plot
trace0 = go.Box( y=df.bp, name = 'Bp', marker = dict( color = 'rgb(12, 12, 140)', ) )
trace1 = go.Box( y=df.sod, name = 'Sod', marker = dict( color = 'rgb(12, 128, 128)', ) )
data = [trace0, trace1]
iplot(data)
# In[ ]:
#Line plot
df2=df.copy()
df2["id"]=range(1,(len(df.ba)+1),1)
df2["df2_bp_norm"]=(df2.bp-np.min(df2.bp))/(np.max(df2.bp)-np.min(df2.bp))
df2["df2_hemo_norm"]=(df2.hemo-np.min(df2.hemo))/(np.max(df2.hemo)-np.min(df2.hemo))
#Line Plot
trace1 = go.Scatter( x = df2.id, y = df2.df2_bp_norm, mode = "lines", name = "Blood Press.", marker = dict(color = 'rgba(16, 112, 2, 0.8)'), text= df.age)
trace2 = go.Scatter( x = df2.id, y = df2.df2_hemo_norm, mode = "lines+markers", name = "Hemo", marker = dict(color = 'rgba(80, 26, 80, 0.8)'), text= df.age)
data=[trace1,trace2]
layout=dict(title="Blood Press and Hemoglobin values according the age", xaxis=dict(title="İd",ticklen=5,zeroline=False))
fig=dict(data=data,layout=layout)
iplot(fig)
# **CLASSIFICATION ALGORITHMS**
# In[ ]:
score=[] #these variables will be used to show the algorithm name and its successes.
algorithms=[]
# In[ ]:
#KNN
from sklearn.neighbors import KNeighborsClassifier
y=df["classification"].values
x_data=df.drop(["classification"],axis=1)
#Normalization
x=(x_data-np.min(x_data))/(np.max(x_data)-np.min(x_data))
#Preparing the test and training set
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,random_state=1,test_size=0.3)
#model and accuracy
knn=KNeighborsClassifier(n_neighbors=3)
knn.fit(x_train,y_train)
knn.predict(x_test)
score.append(knn.score(x_test,y_test)*100)
algorithms.append("KNN")
print("KNN accuracy =",knn.score(x_test,y_test)*100)
#Confusion Matrix
from sklearn.metrics import confusion_matrix
y_pred=knn.predict(x_test)
y_true=y_test
cm=confusion_matrix(y_true,y_pred)
#Confusion Matrix on Heatmap
f,ax=plt.subplots(figsize=(5,5))
print()
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.title(" KNN Confusion Matrix")
print()
#%%
# In[ ]:
#Navie-Bayes
from sklearn.naive_bayes import GaussianNB
nb=GaussianNB()
#Training
nb.fit(x_train,y_train)
#Test
score.append(nb.score(x_test,y_test)*100)
algorithms.append("Navie-Bayes")
print("Navie Bayes accuracy =",nb.score(x_test,y_test)*100)
#Confusion Matrix
from sklearn.metrics import confusion_matrix
y_pred=nb.predict(x_test)
y_true=y_test
cm=confusion_matrix(y_true,y_pred)
#Confusion Matrix on Heatmap
f,ax=plt.subplots(figsize=(5,5))
print()
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.title("Navie Bayes Confusion Matrix")
print()
# In[ ]:
#RANDOM FOREST
from sklearn.ensemble import RandomForestClassifier
rf=RandomForestClassifier(n_estimators=100,random_state=1)
rf.fit(x_train,y_train)
score.append(rf.score(x_test,y_test)*100)
algorithms.append("Random Forest")
print("Random Forest accuracy =",rf.score(x_test,y_test))
#Confusion Matrix
from sklearn.metrics import confusion_matrix
y_pred=rf.predict(x_test)
y_true=y_test
cm=confusion_matrix(y_true,y_pred)
#Confusion Matrix on Heatmap
f,ax=plt.subplots(figsize=(5,5))
print()
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.title("Random Forest Confusion Matrix")
print()
# In[ ]:
#Support Vector Machine
from sklearn.svm import SVC
svm=SVC(random_state=1)
svm.fit(x_train,y_train)
score.append(svm.score(x_test,y_test)*100)
algorithms.append("Support Vector Machine")
print("svm test accuracy =",svm.score(x_test,y_test)*100)
#Confusion Matrix
from sklearn.metrics import confusion_matrix
y_pred=svm.predict(x_test)
y_true=y_test
cm=confusion_matrix(y_true,y_pred)
#Confusion Matrix on Heatmap
f,ax=plt.subplots(figsize=(5,5))
print()
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.title("Support Vector Machine Confusion Matrix")
print()
# In[ ]:
#Decision Tree
from sklearn.tree import DecisionTreeClassifier
dt=DecisionTreeClassifier()
dt.fit(x_train,y_train)
print("Decision Tree accuracy:",dt.score(x_test,y_test)*100)
score.append(dt.score(x_test,y_test)*100)
algorithms.append("Decision Tree")
#Confusion Matrix
from sklearn.metrics import confusion_matrix
y_pred=dt.predict(x_test)
y_true=y_test
cm=confusion_matrix(y_true,y_pred)
#Confusion Matrix on Heatmap
f,ax=plt.subplots(figsize=(5,5))
print()
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.title("Decision Tree Confusion Matrix")
print()
# In[ ]:
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression()
lr.fit(x_train,y_train)
score.append(lr.score(x_test,y_test)*100)
algorithms.append("Logistic Regression")
print("test accuracy {}".format(lr.score(x_test,y_test)))
#Confusion Matrix
from sklearn.metrics import confusion_matrix
y_pred=lr.predict(x_test)
y_true=y_test
cm=confusion_matrix(y_true,y_pred)
#Confusion Matrix on Heatmap
f,ax=plt.subplots(figsize=(5,5))
print()
plt.xlabel("y_pred")
plt.ylabel("y_true")
plt.title("Logistic Regression Confusion Matrix")
print()
# In[ ]:
trace1 = { 'x': algorithms, 'y': score, 'name': 'score', 'type': 'bar' }
# In[ ]:
data = [trace1];
layout = { 'xaxis': {'title': 'Classification Algorithms'}, 'title': 'Comparison of the accuracy of classification algorithms' };
fig = go.Figure(data = data, layout = layout)
iplot(fig)
# **CONCLUSION**
#
# In this study, there were 400 samples and 26 parameters.However, some samples had no parameter values. For this reason, I prepared the data to use the classification algorithms. I did data visualization work. I applied classification algorithms and compared success rates with each other. It was a nice work for me. I hope you like it.
# If you have questions and suggestions, you can comment. Because your questions and suggestions are very valuable for me.
#
| en | 0.784086 | #!/usr/bin/env python # coding: utf-8 # **Data cleaning&Classification algorithms comparison** # **In this study, chronic kidney disease was estimated using classification algorithms. You'll find this kernel;** # * The codes I think will be useful for data cleaning # * How to Handle Missing Data,what did I do? # * Data Visualization # * Classification Algorithms # -KNN # -Navie-Bayes # -Logistic Regression # -Decision Tree # -Random Forest # -Support Vector Machine # * Success rate of classification algorithms # * Conclusion # # # In[ ]: # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in # linear algebra # data processing, CSV file I/O (e.g. pd.read_csv) #for confusion matrix #For data visualization # Input data files are available in the "../../../input/mansoordaku_ckdisease/" directory. # For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory # Any results you write to the current directory are saved as output. # In[ ]: # In[ ]: #data types and feature names. #I'll change the data types of some parameters in the following codes # In[ ]: #first 5 samples in dataset # In[ ]: # **PREPARE DATA** # # **1) 3 unique values appear in the data set. However, there is no value called "ckd\t. " I have written the following code to solve this problem.** # In[ ]: # In[ ]: #problem solved. # **2) The "id" parameter will not work for classification, so I'm removing this parameter from the data set.** # In[ ]: # In[ ]: #id parameter dropped. # **3) I changed the target parameter values to 1 and 0 to be able to use the classification algorithms. If the value is "ckd" is 1, if not equal to 0. ** # In[ ]: # In[ ]: # **4) I used the following code to find out how many "NaN" values in which parameter.** # In[ ]: # # **5)Sometimes instead of Nan in the data set, "?" value can be found. To solve this problem ; **df = data [(data! = '?'). all (axis = 1)]** can be used.** # # **How to Handle Missing Data,what did I do?** # # Pandas provides the dropna() function that can be used to drop either columns or rows with missing data. We can use dropna() to remove all rows with missing data # Removing rows with missing values can be too limiting on some predictive modeling problems, an alternative is to impute missing values. # Imputing refers to using a model to replace missing values. # # There are many options we could consider when replacing a missing value, for example: # # A constant value that has meaning within the domain, such as 0, distinct from all other values. # A value from another randomly selected record. # A mean, median or mode value for the column. # A value estimated by another predictive model. # # Pandas provides the fillna() function for replacing missing values with a specific value. # # For example, we can use fillna() to replace missing values with the mean value for each column, # For example; dataset.fillna(dataset.mean(), inplace=True) # **6) I can use dropna() to remove all rows with missing data** # # There were 25 parameters of 400 samples before writing this code. After writing this code, there are 25 parameters left in 158 examples. # # The number of samples decreased but the reliability of the model increased. # In[ ]: # **7) indexes are not sequential as you can see in the table above. I used the following code to sort indexes.** # In[ ]: # **8) I corrected some of the parameters.** # In[ ]: #you can see that the values have changed. # **9) I'll change the data types of some parameters ** # In[ ]: # **10)Keep in mind, the goal in this section is to have all the columns as numeric columns (int or float data type), and containing no missing values. We just dealt with the missing values, so let's now find out the number of columns that are of the object data type and then move on to process them into numeric form.** # In[ ]: # **11)display a sample row to get a better sense of how the values in each column are formatted.** # In[ ]: # **12)The ordinal values to integers, we can use the pandas DataFrame method replace() to"rbc","pc","pcc","ba","htn","dm","cad","appet","pe" and "ane" to appropriate numeric values** # In[ ]: # In[ ]: #We used categorical values as numerical to replace them. # In[ ]: #All values are numerical. # **VISUALIZATION** # In[ ]: #HEAT MAP #correlation of parameters # In[ ]: #box-plot # In[ ]: #Line plot #Line Plot # **CLASSIFICATION ALGORITHMS** # In[ ]: #these variables will be used to show the algorithm name and its successes. # In[ ]: #KNN #Normalization #Preparing the test and training set #model and accuracy #Confusion Matrix #Confusion Matrix on Heatmap #%% # In[ ]: #Navie-Bayes #Training #Test #Confusion Matrix #Confusion Matrix on Heatmap # In[ ]: #RANDOM FOREST #Confusion Matrix #Confusion Matrix on Heatmap # In[ ]: #Support Vector Machine #Confusion Matrix #Confusion Matrix on Heatmap # In[ ]: #Decision Tree #Confusion Matrix #Confusion Matrix on Heatmap # In[ ]: #Confusion Matrix #Confusion Matrix on Heatmap # In[ ]: # In[ ]: # **CONCLUSION** # # In this study, there were 400 samples and 26 parameters.However, some samples had no parameter values. For this reason, I prepared the data to use the classification algorithms. I did data visualization work. I applied classification algorithms and compared success rates with each other. It was a nice work for me. I hope you like it. # If you have questions and suggestions, you can comment. Because your questions and suggestions are very valuable for me. # | 3.151102 | 3 |
tests/unit/test_stacktach_db.py | PreetiKamble29/stacktach | 0 | 6616113 | # Copyright (c) 2013 - Rackspace Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import mox
from stacktach import db
from stacktach import stacklog
from stacktach import models
from tests.unit import StacktachBaseTestCase
class StacktachDBTestCase(StacktachBaseTestCase):
def setUp(self):
self.mox = mox.Mox()
self.log = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(stacklog, 'get_logger')
self.mox.StubOutWithMock(models, 'RawData', use_mock_anything=True)
models.RawData.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'Deployment', use_mock_anything=True)
models.Deployment.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'Lifecycle', use_mock_anything=True)
models.Lifecycle.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'Timing', use_mock_anything=True)
models.Timing.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'RequestTracker',
use_mock_anything=True)
models.RequestTracker.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'InstanceUsage',
use_mock_anything=True)
models.InstanceUsage.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'InstanceDeletes',
use_mock_anything=True)
models.InstanceDeletes.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'InstanceExists',
use_mock_anything=True)
models.InstanceExists.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'JsonReport', use_mock_anything=True)
models.JsonReport.objects = self.mox.CreateMockAnything()
def tearDown(self):
self.mox.UnsetStubs()
def setup_mock_log(self, name=None):
if name is None:
stacklog.get_logger(name=mox.IgnoreArg(),
is_parent=False).AndReturn(self.log)
else:
stacklog.get_logger(name=name, is_parent=False).AndReturn(self.log)
def test_safe_get(self):
Model = self.mox.CreateMockAnything()
Model.objects = self.mox.CreateMockAnything()
filters = {'field1': 'value1', 'field2': 'value2'}
results = self.mox.CreateMockAnything()
Model.objects.filter(**filters).AndReturn(results)
results.count().AndReturn(1)
object = self.mox.CreateMockAnything()
results[0].AndReturn(object)
self.mox.ReplayAll()
returned = db._safe_get(Model, **filters)
self.assertEqual(returned, object)
self.mox.VerifyAll()
def test_safe_get_no_results(self):
Model = self.mox.CreateMockAnything()
Model.__name__ = 'Model'
Model.objects = self.mox.CreateMockAnything()
filters = {'field1': 'value1', 'field2': 'value2'}
results = self.mox.CreateMockAnything()
Model.objects.filter(**filters).AndReturn(results)
results.count().AndReturn(0)
log = self.mox.CreateMockAnything()
self.setup_mock_log()
self.log.warn('No records found for Model get.')
self.mox.ReplayAll()
returned = db._safe_get(Model, **filters)
self.assertEqual(returned, None)
self.mox.VerifyAll()
def test_safe_get_multiple_results(self):
Model = self.mox.CreateMockAnything()
Model.__name__ = 'Model'
Model.objects = self.mox.CreateMockAnything()
filters = {'field1': 'value1', 'field2': 'value2'}
results = self.mox.CreateMockAnything()
Model.objects.filter(**filters).AndReturn(results)
results.count().AndReturn(2)
self.setup_mock_log()
self.log.warn('Multiple records found for Model get.')
object = self.mox.CreateMockAnything()
results[0].AndReturn(object)
self.mox.ReplayAll()
returned = db._safe_get(Model, **filters)
self.assertEqual(returned, object)
self.mox.VerifyAll()
def test_get_or_create_deployment(self):
deployment = self.mox.CreateMockAnything()
models.Deployment.objects.get_or_create(name='test').AndReturn(deployment)
self.mox.ReplayAll()
returned = db.get_or_create_deployment('test')
self.assertEqual(returned, deployment)
self.mox.VerifyAll()
def _test_db_create_func(self, Model, func):
params = {'field1': 'value1', 'field2': 'value2'}
object = self.mox.CreateMockAnything()
Model(**params).AndReturn(object)
self.mox.ReplayAll()
returned = func(**params)
self.assertEqual(returned, object)
self.mox.VerifyAll()
def test_create_lifecycle(self):
self._test_db_create_func(models.Lifecycle, db.create_lifecycle)
def test_create_timing(self):
self._test_db_create_func(models.Timing, db.create_timing)
def test_create_request_tracker(self):
self._test_db_create_func(models.RequestTracker,
db.create_request_tracker)
def test_create_instance_usage(self):
self._test_db_create_func(models.InstanceUsage,
db.create_instance_usage)
def test_create_instance_delete(self):
self._test_db_create_func(models.InstanceDeletes,
db.create_instance_delete)
def test_create_instance_exists(self):
self._test_db_create_func(models.InstanceExists,
db.create_instance_exists)
def _test_db_find_func(self, Model, func, select_related=True):
params = {'field1': 'value1', 'field2': 'value2'}
results = self.mox.CreateMockAnything()
if select_related:
Model.objects.select_related().AndReturn(results)
results.filter(**params).AndReturn(results)
else:
Model.objects.filter(**params).AndReturn(results)
self.mox.ReplayAll()
returned = func(**params)
self.assertEqual(returned, results)
self.mox.VerifyAll()
def test_find_lifecycles(self):
self._test_db_find_func(models.Lifecycle, db.find_lifecycles)
def test_find_timings(self):
self._test_db_find_func(models.Timing, db.find_timings)
def test_find_request_trackers(self):
self._test_db_find_func(models.RequestTracker,
db.find_request_trackers,
select_related=False)
def _test_db_get_or_create_func(self, Model, func):
params = {'field1': 'value1', 'field2': 'value2'}
object = self.mox.CreateMockAnything()
Model.objects.get_or_create(**params).AndReturn(object)
self.mox.ReplayAll()
returned = func(**params)
self.assertEqual(returned, object)
self.mox.VerifyAll()
def test_get_or_create_instance_usage(self):
self._test_db_get_or_create_func(models.InstanceUsage,
db.get_or_create_instance_usage)
def test_get_or_create_instance_delete(self):
self._test_db_get_or_create_func(models.InstanceDeletes,
db.get_or_create_instance_delete)
def test_get_instance_usage(self):
filters = {'field1': 'value1', 'field2': 'value2'}
results = self.mox.CreateMockAnything()
models.InstanceUsage.objects.filter(**filters).AndReturn(results)
results.count().AndReturn(1)
usage = self.mox.CreateMockAnything()
results[0].AndReturn(usage)
self.mox.ReplayAll()
returned = db.get_instance_usage(**filters)
self.assertEqual(returned, usage)
self.mox.VerifyAll()
def test_get_instance_delete(self):
filters = {'field1': 'value1', 'field2': 'value2'}
results = self.mox.CreateMockAnything()
models.InstanceDeletes.objects.filter(**filters).AndReturn(results)
results.count().AndReturn(1)
usage = self.mox.CreateMockAnything()
results[0].AndReturn(usage)
self.mox.ReplayAll()
returned = db.get_instance_delete(**filters)
self.assertEqual(returned, usage)
self.mox.VerifyAll()
def test_save(self):
o = self.mox.CreateMockAnything()
o.save()
self.mox.ReplayAll()
db.save(o)
self.mox.VerifyAll()
| # Copyright (c) 2013 - Rackspace Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import mox
from stacktach import db
from stacktach import stacklog
from stacktach import models
from tests.unit import StacktachBaseTestCase
class StacktachDBTestCase(StacktachBaseTestCase):
def setUp(self):
self.mox = mox.Mox()
self.log = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(stacklog, 'get_logger')
self.mox.StubOutWithMock(models, 'RawData', use_mock_anything=True)
models.RawData.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'Deployment', use_mock_anything=True)
models.Deployment.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'Lifecycle', use_mock_anything=True)
models.Lifecycle.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'Timing', use_mock_anything=True)
models.Timing.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'RequestTracker',
use_mock_anything=True)
models.RequestTracker.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'InstanceUsage',
use_mock_anything=True)
models.InstanceUsage.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'InstanceDeletes',
use_mock_anything=True)
models.InstanceDeletes.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'InstanceExists',
use_mock_anything=True)
models.InstanceExists.objects = self.mox.CreateMockAnything()
self.mox.StubOutWithMock(models, 'JsonReport', use_mock_anything=True)
models.JsonReport.objects = self.mox.CreateMockAnything()
def tearDown(self):
self.mox.UnsetStubs()
def setup_mock_log(self, name=None):
if name is None:
stacklog.get_logger(name=mox.IgnoreArg(),
is_parent=False).AndReturn(self.log)
else:
stacklog.get_logger(name=name, is_parent=False).AndReturn(self.log)
def test_safe_get(self):
Model = self.mox.CreateMockAnything()
Model.objects = self.mox.CreateMockAnything()
filters = {'field1': 'value1', 'field2': 'value2'}
results = self.mox.CreateMockAnything()
Model.objects.filter(**filters).AndReturn(results)
results.count().AndReturn(1)
object = self.mox.CreateMockAnything()
results[0].AndReturn(object)
self.mox.ReplayAll()
returned = db._safe_get(Model, **filters)
self.assertEqual(returned, object)
self.mox.VerifyAll()
def test_safe_get_no_results(self):
Model = self.mox.CreateMockAnything()
Model.__name__ = 'Model'
Model.objects = self.mox.CreateMockAnything()
filters = {'field1': 'value1', 'field2': 'value2'}
results = self.mox.CreateMockAnything()
Model.objects.filter(**filters).AndReturn(results)
results.count().AndReturn(0)
log = self.mox.CreateMockAnything()
self.setup_mock_log()
self.log.warn('No records found for Model get.')
self.mox.ReplayAll()
returned = db._safe_get(Model, **filters)
self.assertEqual(returned, None)
self.mox.VerifyAll()
def test_safe_get_multiple_results(self):
Model = self.mox.CreateMockAnything()
Model.__name__ = 'Model'
Model.objects = self.mox.CreateMockAnything()
filters = {'field1': 'value1', 'field2': 'value2'}
results = self.mox.CreateMockAnything()
Model.objects.filter(**filters).AndReturn(results)
results.count().AndReturn(2)
self.setup_mock_log()
self.log.warn('Multiple records found for Model get.')
object = self.mox.CreateMockAnything()
results[0].AndReturn(object)
self.mox.ReplayAll()
returned = db._safe_get(Model, **filters)
self.assertEqual(returned, object)
self.mox.VerifyAll()
def test_get_or_create_deployment(self):
deployment = self.mox.CreateMockAnything()
models.Deployment.objects.get_or_create(name='test').AndReturn(deployment)
self.mox.ReplayAll()
returned = db.get_or_create_deployment('test')
self.assertEqual(returned, deployment)
self.mox.VerifyAll()
def _test_db_create_func(self, Model, func):
params = {'field1': 'value1', 'field2': 'value2'}
object = self.mox.CreateMockAnything()
Model(**params).AndReturn(object)
self.mox.ReplayAll()
returned = func(**params)
self.assertEqual(returned, object)
self.mox.VerifyAll()
def test_create_lifecycle(self):
self._test_db_create_func(models.Lifecycle, db.create_lifecycle)
def test_create_timing(self):
self._test_db_create_func(models.Timing, db.create_timing)
def test_create_request_tracker(self):
self._test_db_create_func(models.RequestTracker,
db.create_request_tracker)
def test_create_instance_usage(self):
self._test_db_create_func(models.InstanceUsage,
db.create_instance_usage)
def test_create_instance_delete(self):
self._test_db_create_func(models.InstanceDeletes,
db.create_instance_delete)
def test_create_instance_exists(self):
self._test_db_create_func(models.InstanceExists,
db.create_instance_exists)
def _test_db_find_func(self, Model, func, select_related=True):
params = {'field1': 'value1', 'field2': 'value2'}
results = self.mox.CreateMockAnything()
if select_related:
Model.objects.select_related().AndReturn(results)
results.filter(**params).AndReturn(results)
else:
Model.objects.filter(**params).AndReturn(results)
self.mox.ReplayAll()
returned = func(**params)
self.assertEqual(returned, results)
self.mox.VerifyAll()
def test_find_lifecycles(self):
self._test_db_find_func(models.Lifecycle, db.find_lifecycles)
def test_find_timings(self):
self._test_db_find_func(models.Timing, db.find_timings)
def test_find_request_trackers(self):
self._test_db_find_func(models.RequestTracker,
db.find_request_trackers,
select_related=False)
def _test_db_get_or_create_func(self, Model, func):
params = {'field1': 'value1', 'field2': 'value2'}
object = self.mox.CreateMockAnything()
Model.objects.get_or_create(**params).AndReturn(object)
self.mox.ReplayAll()
returned = func(**params)
self.assertEqual(returned, object)
self.mox.VerifyAll()
def test_get_or_create_instance_usage(self):
self._test_db_get_or_create_func(models.InstanceUsage,
db.get_or_create_instance_usage)
def test_get_or_create_instance_delete(self):
self._test_db_get_or_create_func(models.InstanceDeletes,
db.get_or_create_instance_delete)
def test_get_instance_usage(self):
filters = {'field1': 'value1', 'field2': 'value2'}
results = self.mox.CreateMockAnything()
models.InstanceUsage.objects.filter(**filters).AndReturn(results)
results.count().AndReturn(1)
usage = self.mox.CreateMockAnything()
results[0].AndReturn(usage)
self.mox.ReplayAll()
returned = db.get_instance_usage(**filters)
self.assertEqual(returned, usage)
self.mox.VerifyAll()
def test_get_instance_delete(self):
filters = {'field1': 'value1', 'field2': 'value2'}
results = self.mox.CreateMockAnything()
models.InstanceDeletes.objects.filter(**filters).AndReturn(results)
results.count().AndReturn(1)
usage = self.mox.CreateMockAnything()
results[0].AndReturn(usage)
self.mox.ReplayAll()
returned = db.get_instance_delete(**filters)
self.assertEqual(returned, usage)
self.mox.VerifyAll()
def test_save(self):
o = self.mox.CreateMockAnything()
o.save()
self.mox.ReplayAll()
db.save(o)
self.mox.VerifyAll()
| en | 0.765676 | # Copyright (c) 2013 - Rackspace Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. | 1.901079 | 2 |
test/test_options.py | ezh/cloudselect | 4 | 6616114 | <filename>test/test_options.py
# Copyright 2019 <NAME> and individual contributors
# See the LICENSE.txt file at the top-level directory of this distribution.
#
# Licensed under the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>
# This file may not be copied, modified, or distributed
# except according to those terms.
"""This module is used for testing Cloud.options(...) behaviour."""
from cloudselect.cloudselect import CloudSelect
def test_options(cfgdir):
"""
Testing cloud.options(...) behaviour.
There should be {} if there is no any options.
There should be dictionary if there is required option.
"""
cloud = CloudSelect(cfgdir)
configuration = cloud.configuration_read()
args = cloud.parse_args([])
cloud.fabric(configuration, args)
assert cloud.options("test") == {}
assert cloud.options("plugin") == configuration["plugin"]
assert cloud.options("log") == configuration["log"]
| <filename>test/test_options.py
# Copyright 2019 <NAME> and individual contributors
# See the LICENSE.txt file at the top-level directory of this distribution.
#
# Licensed under the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>
# This file may not be copied, modified, or distributed
# except according to those terms.
"""This module is used for testing Cloud.options(...) behaviour."""
from cloudselect.cloudselect import CloudSelect
def test_options(cfgdir):
"""
Testing cloud.options(...) behaviour.
There should be {} if there is no any options.
There should be dictionary if there is required option.
"""
cloud = CloudSelect(cfgdir)
configuration = cloud.configuration_read()
args = cloud.parse_args([])
cloud.fabric(configuration, args)
assert cloud.options("test") == {}
assert cloud.options("plugin") == configuration["plugin"]
assert cloud.options("log") == configuration["log"]
| en | 0.723106 | # Copyright 2019 <NAME> and individual contributors # See the LICENSE.txt file at the top-level directory of this distribution. # # Licensed under the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT> # This file may not be copied, modified, or distributed # except according to those terms. This module is used for testing Cloud.options(...) behaviour. Testing cloud.options(...) behaviour. There should be {} if there is no any options. There should be dictionary if there is required option. | 2.220674 | 2 |
mm.py | gxrzangdan/pyci | 0 | 6616115 | <reponame>gxrzangdan/pyci
# -*- coding: utf-8 -*-
# PyCi
#
# Copyright (c) 2009, The PyCi Project
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# URL: <http://code.google.com/p/pyci>
# For license information, see COPYING
"""Forward and Backward Maximum Matching word segmentor. Mainly used
as a baseline segmentor.
"""
__all__ = ["FMMSeg", "BMMSeg"]
from copy import deepcopy
from pyci.trie import Trie
class FMMSeg(object):
"""A forward maximum matching Chinese word segmentor.
"""
def __init__(self, wordtrie=None, train=None):
"""Construct a FMM Chinese word segmentor.
@type train: an iterable of words
@param train: training set
@type wordtrie: a trie of words
@param wordtrie: previously trained trie
If wordtrie is provided, it's deepcopied as the initial trie,
otherwise a new blank trie will be constructed.
If train is provided, it's appended into the trie above.
"""
if wordtrie:
self._trie = deepcopy(wordtrie)
else:
self._trie = Trie()
if train:
self.add_words(train)
def add_words(self, train):
"""Add train words into the trie.
@type train: an iterable of words
@param train: (possibly) new words
"""
for word in train:
self._trie[word] = word
def seg(self, sent):
"""Segment a sentence.
@type sent: unicode string
@param sent: the sentence to be segmented
@return: a list of segmented words
"""
words = []
offset = 0
idx = self._trie.longest_prefix(sent, offset)
while offset < len(sent):
if idx is None:
# the first character is not found in our trie, so
# treat it as a whole word
idx = offset + 1
words.append(sent[offset:idx])
offset = idx
idx = self._trie.longest_prefix(sent, offset)
return words
class BMMSeg(FMMSeg):
"""A backward maximum matching Chinese word segmentor.
"""
def add_words(self, train):
"""Add train words into the trie.
@type train: an iterable of words
@param train: (possibly) new words
"""
# just reverse everything
train = [i[::-1] for i in train]
FMMSeg.add_words(self, train)
def seg(self, sent):
"""Segment a sentence.
@type sent: unicode string
@param sent: the sentence to be segmented
@return: a list of segmented words
"""
sent = sent[::-1]
words = FMMSeg.seg(self, sent)
words.reverse()
return [i[::-1] for i in words]
def demo():
"""Demo for FMM and BMM segmentors
"""
words = [u"戈壁", u"战胜", u"结合", u"合成", u"分子", u"子时", u"壁上的"]
fseg = FMMSeg(train=words)
bseg = BMMSeg(train=words)
print "OOV"
sent = u"马勒戈壁上的草泥马战胜了河蟹。"
print "FMM",
print "/".join(fseg.seg(sent))
print "BMM",
print "/".join(bseg.seg(sent))
print "Let's add those words"
new_words = [u"马勒戈壁", u"草泥马", u"河蟹"]
fseg.add_words(new_words)
bseg.add_words(new_words)
print "FMM",
print "/".join(fseg.seg(sent))
print "BMM",
print "/".join(bseg.seg(sent))
print "\nAmbiguity"
sent1 = u"结合成分子时"
print "FMM",
print "/".join(fseg.seg(sent1))
print "BMM",
print "/".join(bseg.seg(sent1))
if __name__ == "__main__":
demo()
| # -*- coding: utf-8 -*-
# PyCi
#
# Copyright (c) 2009, The PyCi Project
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# URL: <http://code.google.com/p/pyci>
# For license information, see COPYING
"""Forward and Backward Maximum Matching word segmentor. Mainly used
as a baseline segmentor.
"""
__all__ = ["FMMSeg", "BMMSeg"]
from copy import deepcopy
from pyci.trie import Trie
class FMMSeg(object):
"""A forward maximum matching Chinese word segmentor.
"""
def __init__(self, wordtrie=None, train=None):
"""Construct a FMM Chinese word segmentor.
@type train: an iterable of words
@param train: training set
@type wordtrie: a trie of words
@param wordtrie: previously trained trie
If wordtrie is provided, it's deepcopied as the initial trie,
otherwise a new blank trie will be constructed.
If train is provided, it's appended into the trie above.
"""
if wordtrie:
self._trie = deepcopy(wordtrie)
else:
self._trie = Trie()
if train:
self.add_words(train)
def add_words(self, train):
"""Add train words into the trie.
@type train: an iterable of words
@param train: (possibly) new words
"""
for word in train:
self._trie[word] = word
def seg(self, sent):
"""Segment a sentence.
@type sent: unicode string
@param sent: the sentence to be segmented
@return: a list of segmented words
"""
words = []
offset = 0
idx = self._trie.longest_prefix(sent, offset)
while offset < len(sent):
if idx is None:
# the first character is not found in our trie, so
# treat it as a whole word
idx = offset + 1
words.append(sent[offset:idx])
offset = idx
idx = self._trie.longest_prefix(sent, offset)
return words
class BMMSeg(FMMSeg):
"""A backward maximum matching Chinese word segmentor.
"""
def add_words(self, train):
"""Add train words into the trie.
@type train: an iterable of words
@param train: (possibly) new words
"""
# just reverse everything
train = [i[::-1] for i in train]
FMMSeg.add_words(self, train)
def seg(self, sent):
"""Segment a sentence.
@type sent: unicode string
@param sent: the sentence to be segmented
@return: a list of segmented words
"""
sent = sent[::-1]
words = FMMSeg.seg(self, sent)
words.reverse()
return [i[::-1] for i in words]
def demo():
"""Demo for FMM and BMM segmentors
"""
words = [u"戈壁", u"战胜", u"结合", u"合成", u"分子", u"子时", u"壁上的"]
fseg = FMMSeg(train=words)
bseg = BMMSeg(train=words)
print "OOV"
sent = u"马勒戈壁上的草泥马战胜了河蟹。"
print "FMM",
print "/".join(fseg.seg(sent))
print "BMM",
print "/".join(bseg.seg(sent))
print "Let's add those words"
new_words = [u"马勒戈壁", u"草泥马", u"河蟹"]
fseg.add_words(new_words)
bseg.add_words(new_words)
print "FMM",
print "/".join(fseg.seg(sent))
print "BMM",
print "/".join(bseg.seg(sent))
print "\nAmbiguity"
sent1 = u"结合成分子时"
print "FMM",
print "/".join(fseg.seg(sent1))
print "BMM",
print "/".join(bseg.seg(sent1))
if __name__ == "__main__":
demo() | en | 0.76516 | # -*- coding: utf-8 -*- # PyCi # # Copyright (c) 2009, The PyCi Project # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # URL: <http://code.google.com/p/pyci> # For license information, see COPYING Forward and Backward Maximum Matching word segmentor. Mainly used as a baseline segmentor. A forward maximum matching Chinese word segmentor. Construct a FMM Chinese word segmentor. @type train: an iterable of words @param train: training set @type wordtrie: a trie of words @param wordtrie: previously trained trie If wordtrie is provided, it's deepcopied as the initial trie, otherwise a new blank trie will be constructed. If train is provided, it's appended into the trie above. Add train words into the trie. @type train: an iterable of words @param train: (possibly) new words Segment a sentence. @type sent: unicode string @param sent: the sentence to be segmented @return: a list of segmented words # the first character is not found in our trie, so # treat it as a whole word A backward maximum matching Chinese word segmentor. Add train words into the trie. @type train: an iterable of words @param train: (possibly) new words # just reverse everything Segment a sentence. @type sent: unicode string @param sent: the sentence to be segmented @return: a list of segmented words Demo for FMM and BMM segmentors | 3.362014 | 3 |
week2_programs/snmp.py | morganoh/Python_with_Kirk | 0 | 6616116 | from snmp_helper import snmp_get_oid
from snmp_helper import snmp_extract
COMMUNITY_STRING = 'galileo'
IP = '172.16.17.32'
SNMP_PORT1 = 7961
SNMP_PORT2 = 8061
OID = '1.3.6.1.2.1.1.1.0'
OID_2 = '1.3.6.1.2.1.1.5.0'
def get_sys_name(device):
snmp_data = snmp_get_oid(device , oid = OID)
output = snmp_extract(snmp_data)
return output
def get_sys_description(device):
snmp_data = snmp_get_oid(device , oid = OID_2)
output = snmp_extract(snmp_data)
return output
def main():
first_device = (IP, COMMUNITY_STRING, SNMP_PORT1)
second_device = (IP, COMMUNITY_STRING , SNMP_PORT2)
sysname = get_sys_name(first_device)
print sysname
print '\n'
sysdescription = get_sys_description(first_device)
print sysdescription
print '\n'
sysname = get_sys_name(second_device)
print sysname
print '\n'
sysdescription = get_sys_description(second_device)
print sysdescription
print '\n'
if __name__ == '__main__':
main()
| from snmp_helper import snmp_get_oid
from snmp_helper import snmp_extract
COMMUNITY_STRING = 'galileo'
IP = '172.16.17.32'
SNMP_PORT1 = 7961
SNMP_PORT2 = 8061
OID = '1.3.6.1.2.1.1.1.0'
OID_2 = '1.3.6.1.2.1.1.5.0'
def get_sys_name(device):
snmp_data = snmp_get_oid(device , oid = OID)
output = snmp_extract(snmp_data)
return output
def get_sys_description(device):
snmp_data = snmp_get_oid(device , oid = OID_2)
output = snmp_extract(snmp_data)
return output
def main():
first_device = (IP, COMMUNITY_STRING, SNMP_PORT1)
second_device = (IP, COMMUNITY_STRING , SNMP_PORT2)
sysname = get_sys_name(first_device)
print sysname
print '\n'
sysdescription = get_sys_description(first_device)
print sysdescription
print '\n'
sysname = get_sys_name(second_device)
print sysname
print '\n'
sysdescription = get_sys_description(second_device)
print sysdescription
print '\n'
if __name__ == '__main__':
main()
| none | 1 | 2.542807 | 3 | |
cafe/example.py | m-star18/cafeteria-simulation | 1 | 6616117 | class Toyota:
def __init__(self):
self.TABLE = 50
self.NUMBER = 6
self.SUM_NUMBER = [self.NUMBER] * self.TABLE
self.SEATS = [[-1] * self.NUMBER for _ in range(self.TABLE)]
self.data = [self.TABLE, self.SUM_NUMBER, self.SEATS]
def basic_algorithm(next_member, seats, number):
# 7人は一人余ってしまうので別れる
if next_member == 7:
group_member = [4, 3]
else:
group_member = [next_member]
# 配列用
number -= 1
res = []
pop_index = []
for i, member in enumerate(group_member):
for y, seat in enumerate(seats):
if all(table == -1 for table in seat):
res += [[y, x] for x in range(member)]
pop_index.append(i)
break
group_member = [i for i in range(len(group_member)) if i not in pop_index]
# 全員で座れない場合、一人になってしまう場合は待機
while group_member and 1 not in group_member:
flag = False
pop_index = []
for i, member in enumerate(group_member):
for y, seat in enumerate(seats):
# 全員着席可能の場合
if member <= seat.count(-1):
for x, table in enumerate(seat):
if table == -1 and member > 0:
member -= 1
res.append([y, x])
pop_index.append(i)
flag = True
break
if flag:
break
# 座れなかった場合、グループを半分にして試す
else:
group_member.append(group_member[0] // 2)
group_member[0] -= group_member[-1]
group_member = [i for i in range(len(group_member)) if i not in pop_index]
return res
| class Toyota:
def __init__(self):
self.TABLE = 50
self.NUMBER = 6
self.SUM_NUMBER = [self.NUMBER] * self.TABLE
self.SEATS = [[-1] * self.NUMBER for _ in range(self.TABLE)]
self.data = [self.TABLE, self.SUM_NUMBER, self.SEATS]
def basic_algorithm(next_member, seats, number):
# 7人は一人余ってしまうので別れる
if next_member == 7:
group_member = [4, 3]
else:
group_member = [next_member]
# 配列用
number -= 1
res = []
pop_index = []
for i, member in enumerate(group_member):
for y, seat in enumerate(seats):
if all(table == -1 for table in seat):
res += [[y, x] for x in range(member)]
pop_index.append(i)
break
group_member = [i for i in range(len(group_member)) if i not in pop_index]
# 全員で座れない場合、一人になってしまう場合は待機
while group_member and 1 not in group_member:
flag = False
pop_index = []
for i, member in enumerate(group_member):
for y, seat in enumerate(seats):
# 全員着席可能の場合
if member <= seat.count(-1):
for x, table in enumerate(seat):
if table == -1 and member > 0:
member -= 1
res.append([y, x])
pop_index.append(i)
flag = True
break
if flag:
break
# 座れなかった場合、グループを半分にして試す
else:
group_member.append(group_member[0] // 2)
group_member[0] -= group_member[-1]
group_member = [i for i in range(len(group_member)) if i not in pop_index]
return res
| ja | 0.999283 | # 7人は一人余ってしまうので別れる # 配列用 # 全員で座れない場合、一人になってしまう場合は待機 # 全員着席可能の場合 # 座れなかった場合、グループを半分にして試す | 3.49528 | 3 |
tfsnippet/distributions/batch_to_value.py | QianLiGui/tfsnippet | 63 | 6616118 | <gh_stars>10-100
import tensorflow as tf
from tfsnippet.utils import assert_deps
from .base import Distribution
from .wrapper import as_distribution
__all__ = ['BatchToValueDistribution']
class BatchToValueDistribution(Distribution):
"""
Distribution that converts the last few `batch_ndims` into `values_ndims`.
See :meth:`Distribution.batch_ndims_to_value` for more details.
"""
def __init__(self, distribution, ndims):
"""
Construct a new :class:`BatchToValueDistribution`.
Args:
distribution (Distribution): The source distribution.
ndims (int): The last few `batch_ndims` to be converted
into `value_ndims`. Must be non-negative.
"""
distribution = as_distribution(distribution)
ndims = int(ndims)
if ndims < 0:
raise ValueError('`ndims` must be non-negative integers: '
'got {!r}'.format(ndims))
with tf.name_scope('BatchToValueDistribution.init'):
# get new batch shape
batch_shape = distribution.batch_shape
batch_static_shape = distribution.get_batch_shape()
if ndims > 0:
# static shape
if batch_static_shape.ndims < ndims:
raise ValueError(
'`distribution.batch_shape.ndims` is less then `ndims`'
': distribution {}, batch_shape.ndims {}, ndims {}'.
format(distribution, batch_static_shape.ndims, ndims)
)
batch_static_shape = batch_static_shape[: -ndims]
# dynamic shape
batch_shape = batch_shape[: -ndims]
with assert_deps([
tf.assert_greater_equal(
tf.size(distribution.batch_shape), ndims)
]) as asserted:
if asserted: # pragma: no cover
batch_shape = tf.identity(batch_shape)
# get new value ndims
value_ndims = ndims + distribution.value_ndims
self._distribution = distribution
self._ndims = ndims
super(BatchToValueDistribution, self).__init__(
dtype=distribution.dtype,
is_continuous=distribution.is_continuous,
is_reparameterized=distribution.is_reparameterized,
batch_shape=batch_shape,
batch_static_shape=batch_static_shape,
value_ndims=value_ndims,
)
@property
def base_distribution(self):
"""
Get the base distribution.
Returns:
Distribution: The base distribution.
"""
return self._distribution
def expand_value_ndims(self, ndims):
ndims = int(ndims)
if ndims == 0:
return self
return BatchToValueDistribution(
self._distribution, ndims + self._ndims)
batch_ndims_to_value = expand_value_ndims
def sample(self, n_samples=None, group_ndims=0, is_reparameterized=None,
compute_density=None, name=None):
from tfsnippet.bayes import StochasticTensor
group_ndims = int(group_ndims)
t = self._distribution.sample(
n_samples=n_samples,
group_ndims=group_ndims + self._ndims,
is_reparameterized=is_reparameterized,
compute_density=compute_density,
name=name
)
ret = StochasticTensor(
distribution=self,
tensor=t.tensor,
n_samples=n_samples,
group_ndims=group_ndims,
is_reparameterized=t.is_reparameterized,
log_prob=t._self_log_prob
)
ret._self_prob = t._self_prob
return ret
def log_prob(self, given, group_ndims=0, name=None):
group_ndims = int(group_ndims)
return self._distribution.log_prob(
given=given,
group_ndims=group_ndims + self._ndims,
name=name
)
| import tensorflow as tf
from tfsnippet.utils import assert_deps
from .base import Distribution
from .wrapper import as_distribution
__all__ = ['BatchToValueDistribution']
class BatchToValueDistribution(Distribution):
"""
Distribution that converts the last few `batch_ndims` into `values_ndims`.
See :meth:`Distribution.batch_ndims_to_value` for more details.
"""
def __init__(self, distribution, ndims):
"""
Construct a new :class:`BatchToValueDistribution`.
Args:
distribution (Distribution): The source distribution.
ndims (int): The last few `batch_ndims` to be converted
into `value_ndims`. Must be non-negative.
"""
distribution = as_distribution(distribution)
ndims = int(ndims)
if ndims < 0:
raise ValueError('`ndims` must be non-negative integers: '
'got {!r}'.format(ndims))
with tf.name_scope('BatchToValueDistribution.init'):
# get new batch shape
batch_shape = distribution.batch_shape
batch_static_shape = distribution.get_batch_shape()
if ndims > 0:
# static shape
if batch_static_shape.ndims < ndims:
raise ValueError(
'`distribution.batch_shape.ndims` is less then `ndims`'
': distribution {}, batch_shape.ndims {}, ndims {}'.
format(distribution, batch_static_shape.ndims, ndims)
)
batch_static_shape = batch_static_shape[: -ndims]
# dynamic shape
batch_shape = batch_shape[: -ndims]
with assert_deps([
tf.assert_greater_equal(
tf.size(distribution.batch_shape), ndims)
]) as asserted:
if asserted: # pragma: no cover
batch_shape = tf.identity(batch_shape)
# get new value ndims
value_ndims = ndims + distribution.value_ndims
self._distribution = distribution
self._ndims = ndims
super(BatchToValueDistribution, self).__init__(
dtype=distribution.dtype,
is_continuous=distribution.is_continuous,
is_reparameterized=distribution.is_reparameterized,
batch_shape=batch_shape,
batch_static_shape=batch_static_shape,
value_ndims=value_ndims,
)
@property
def base_distribution(self):
"""
Get the base distribution.
Returns:
Distribution: The base distribution.
"""
return self._distribution
def expand_value_ndims(self, ndims):
ndims = int(ndims)
if ndims == 0:
return self
return BatchToValueDistribution(
self._distribution, ndims + self._ndims)
batch_ndims_to_value = expand_value_ndims
def sample(self, n_samples=None, group_ndims=0, is_reparameterized=None,
compute_density=None, name=None):
from tfsnippet.bayes import StochasticTensor
group_ndims = int(group_ndims)
t = self._distribution.sample(
n_samples=n_samples,
group_ndims=group_ndims + self._ndims,
is_reparameterized=is_reparameterized,
compute_density=compute_density,
name=name
)
ret = StochasticTensor(
distribution=self,
tensor=t.tensor,
n_samples=n_samples,
group_ndims=group_ndims,
is_reparameterized=t.is_reparameterized,
log_prob=t._self_log_prob
)
ret._self_prob = t._self_prob
return ret
def log_prob(self, given, group_ndims=0, name=None):
group_ndims = int(group_ndims)
return self._distribution.log_prob(
given=given,
group_ndims=group_ndims + self._ndims,
name=name
) | en | 0.739586 | Distribution that converts the last few `batch_ndims` into `values_ndims`. See :meth:`Distribution.batch_ndims_to_value` for more details. Construct a new :class:`BatchToValueDistribution`. Args: distribution (Distribution): The source distribution. ndims (int): The last few `batch_ndims` to be converted into `value_ndims`. Must be non-negative. # get new batch shape # static shape # dynamic shape # pragma: no cover # get new value ndims Get the base distribution. Returns: Distribution: The base distribution. | 2.468126 | 2 |
sources/classic/http_auth/interfaces.py | variasov/classic-http-auth | 1 | 6616119 | <filename>sources/classic/http_auth/interfaces.py
from abc import ABC, abstractmethod
from typing import Type
from .entities import Client
# yapf: disable
class AuthStrategy(ABC):
@abstractmethod
def get_client(self, request: 'falcon.Request', **static_client_params) -> Client: ...
class ClientFactory(ABC):
@abstractmethod
def get_client_cls(self) -> Type[Client]: ...
@abstractmethod
def create(self, **instance_params) -> Client: ...
# yapf: enable
| <filename>sources/classic/http_auth/interfaces.py
from abc import ABC, abstractmethod
from typing import Type
from .entities import Client
# yapf: disable
class AuthStrategy(ABC):
@abstractmethod
def get_client(self, request: 'falcon.Request', **static_client_params) -> Client: ...
class ClientFactory(ABC):
@abstractmethod
def get_client_cls(self) -> Type[Client]: ...
@abstractmethod
def create(self, **instance_params) -> Client: ...
# yapf: enable
| en | 0.609066 | # yapf: disable # yapf: enable | 2.312885 | 2 |
controller/mainWinController.py | isa-Lai/Pacemaker_DCM | 0 | 6616120 | <gh_stars>0
# -*- encoding:utf-8 -*-
#from utils.core import Core
from view.mainWin import Ui_Form
from view.deviceSetting import Ui_Form as deviceSetting
from view.info import Ui_Form as info
from model.parameter import parameter as pr
from model.device import device
from config import APP_PATH
from PyQt5 import QtCore, QtWidgets
"""
Main Windows
"""
class mainWinController:
#-----------------------------------------------------------------------
# Constructor (show windows)
#-----------------------------------------------------------------------
def __init__(self, parent=None):
print(str(parent)+str(type(parent)))
self.parameter = pr()
self.device = device()
self.setWin = deviceSetting()
self.infoWin = info()
self.__connectionList()
self.data_list=[]
self.data_list2=[]
self.start_data = -1
self.start_data2 = -1
#-----------------------------------------------------------------------
# device setting part
#-----------------------------------------------------------------------
self.resetDefault()
self.checkBoxEn()
#-----------------------------------------------------------------------
# info
#-----------------------------------------------------------------------
#store all windows
self.core = parent; # do not miss this line, core is necessary
self.view = Ui_Form([self.setWin,self.infoWin])
## add button event
def loadView(self):
self.view.show()
def loadUser(self,user):
self.user = user
self.user_info()
#-----------------------------------------------------------------------
# info
#-----------------------------------------------------------------------
def lost_connnect(self):
self.infoWin.connect.setText("Connection: "+"False")
self.infoWin.battery.setText("Battery: "+"No infomation")
self.device.connection = False
self.infoWin.showMsg("Note","Connection Lost")
'''
for test only
'''
def message(self,str):
self.infoWin.showMsg("Serial Output",str)
# graph action
def start_graph(self):
if(self.device.connection):
self.infoWin.timer.start(self.samplingperiod)
else:
self.infoWin.showMsg("Error", "No device Connected")
def stop_graph(self):
self.infoWin.timer.stop()
def get_info(self,data):
self.data_list.append(5-data*5)
print(5-data*5)
xrange = 20
if len(self.data_list) > 20:
self.start_data += 1
self.infoWin.graph.setXRange(self.start_data,self.start_data+xrange)
else:
self.infoWin.graph.setXRange(0,xrange)
if len(self.data_list) > 100:
self.start_data -= 1
self.data_list.pop(0)
self.infoWin.graph.clear()
# self.infoWin.graph.title('Ventricle Signals')
self.infoWin.graph.plot().setData(self.data_list,pen = 'g')
def get_info2(self,data):
self.data_list2.append(5-data*5)
print(5-data*5)
xrange = 20
if len(self.data_list2) > 20:
self.start_data2 += 1
self.infoWin.atrialgraph.setXRange(self.start_data2,self.start_data2+xrange)
else:
self.infoWin.atrialgraph.setXRange(0,xrange)
if len(self.data_list2) > 100:
self.start_data2 -= 1
self.data_list2.pop(0)
self.infoWin.atrialgraph.clear()
# self.infoWin.atrialgraph.title('Atrium Signals')
self.infoWin.atrialgraph.plot().setData(self.data_list2,pen = 'g')
# button action
# device action
def newConnection(self,port):
result = self.infoWin.confirm("New Device approch at port " +port+". Connect to new device?")
if (result == 16384):
self.device.openSerial(port)
# add new item to port
self.infoWin.port.clear()
self.infoWin.port.addItems(self.device.getSerialPorts())
self.device.timer.start(500)
self.infoWin.connect.setText("Device: Connected at "+port)
def manualConnection(self):
port = self.infoWin.port.currentText()
if port!= "":
self.device.openSerial(port)
self.infoWin.connect.setText("Device: Connected at "+port)
else:
self.infoWin.showMsg("Error","Port Not selected. Please select the connection port first.")
def manualUnconnect(self):
self.device.closeSerial()
self.infoWin.connect.setText("No Device Connected")
def check_battery(self):
self.infoWin.battery.setText("Battery: "+str(self.device.getbatterydata()))
def user_info(self):
self.infoWin.username.setText("User name is: "+self.user.username)
self.infoWin.B_Logout.setText("Logout: "+self.user.username)
#---------------------------------------------------------------------
# Device Setting page
#---------------------------------------------------------------------
def loadParameter(self):
for key, value in self.parameter.parameters.items():
itemtype = str(type(self.setWin.__dict__[key]))
if(itemtype.find("QLineEdit")!=-1):
self.setWin.__dict__[key].setText(value)
self.refreshFormByText(value)
elif(itemtype.find("QComboBox")!=-1):
self.setWin.__dict__[key].setCurrentText(value)
else:
self.setWin.__dict__[key].setProperty("value", value)
# for special check box case
temp = self.parameter.parameters
for key, value in self.checkBox.items():
if(temp[key] == "Off"):
self.setWin.__dict__[value].setChecked(False)
else:
self.setWin.__dict__[value].setChecked(True)
def getPara(self):
para = {}
for key, value in self.setWin.__dict__.items():
if(value.isEnabled()):
if(key.find("_")==-1):
valuetype = str(type(value))
if(valuetype.find("QLineEdit")!=-1):
value = value.text()
elif(valuetype.find("QComboBox")!=-1):
value = value.currentText()
else:
value = value.value()
para[key] = value
else:
para[key] = "Off"
return para
# action method
def confirmForm(self):
self.refreshFormByText(self.setWin.mode.text())
def refreshFormByText(self,mode):
try:
index = self.modeIndex[mode]
self.setWin.mode.setText(mode)
except KeyError as e:
self.setWin.showMsg("Mode Error",mode+" is not a proper mode")
index = [0,0,0,0]
index[0] = self.modeIndex1[mode[0]]
index[1] = self.modeIndex1[mode[1]]
index[2] = self.modeIndex3[mode[2]]
if(len(mode)>3 and mode[3]=="R"):
index[3] = 1
else:
index[3] = 0
self.setWin.I_Pace.setCurrentIndex(index[0])
self.setWin.I_Sence.setCurrentIndex(index[1])
self.setWin.I_Response.setCurrentIndex(index[2])
self.setWin.I_Rate.setCurrentIndex(index[3])
self.setDisabled(mode)
def refreshForm(self):
# get current value
pace = self.setWin.I_Pace.currentText().split("-")[0]
sense = self.setWin.I_Sence.currentText().split("-")[0]
response = self.setWin.I_Response.currentText().split("-")[0]
if (self.setWin.I_Rate.currentText()=="None"):
rate = ""
else:
rate = "R"
mode = pace+sense+response+rate
print(mode)
try:
index = self.modeIndex[mode]
self.setWin.mode.setText(mode)
self.setDisabled(mode)
except KeyError as e:
self.setWin.showMsg("Mode Error",mode+" is not a proper mode")
def logOut(self):
self.core.openView("login")
self.view.hide()
def save(self):
self.parameter.parameters = self.getPara()
result = self.parameter.save(self.user.username,"save")
if result == True:
self.setWin.showMsg("Success","Save Success")
else:
meg = ""
for key, value in result.items():
meg += (key+value[2] + "Range: "+ str(value[0])+" Increment: "+str(value[1])+". "+"\n")
self.setWin.showMsg("Error", meg)
def load(self):
test = self.parameter.load(self.user.username)
if test == False:
self.setWin.showMsg("Load Failed","Load Failed, user folder not exist!")
else:
directory = QtWidgets.QFileDialog.getOpenFileName(None,"Choose file",self.parameter.load(self.user.username))
if directory[0] == '':
self.setWin.showMsg("Load Failed","User must choose one json file to load!")
else:
self.setWin.showMsg("File Path",directory[0])
self.parameter.loadcon(directory[0])
self.loadParameter()
self.setWin.showMsg("Success","Load Success!")
def upload(self):
result = self.setWin.confirm('Comfirm to upload parameters to pacemaker')
#if select yes
if (result == 16384):
# check device connection
if(self.device.connection == False):
self.setWin.showMsg("Error", "No device Connected")
return
self.parameter.parameters = self.getPara()
# add line where we will upload through device
result = self.parameter.save(self.user.username,"upload") # save history also check if parameter are valid
if result == True:
# do the actual serial send
self.parameter.parameters['mode'] = self.modeIndex[self.parameter.parameters['mode']] # store index
self.device.sendParam(self.parameter.parameters)
else:
meg = ""
for key, value in result.items():
meg += (key+value[2] + "Range: "+ str(value[0])+" Increment: "+str(value[1])+". "+"\n")
self.setWin.showMsg("Error", meg)
def resetDefault(self):
self.parameter.getDefault()
self.loadParameter()
def resetCurrent(self):
self.parameter.getDefault()
self.parameter.parameters = self.device.rqstPara(self.parameter.parameters)
# result = self.parameter.savecurrent(self.user.username)
# if result == True:
# filepath = self.parameter.load(self.user.username)
# self.parameter.loadcon(filepath+'/currentpara/from_device.json')
# self.loadParameter()
self.loadParameter()
self.setWin.showMsg("Success","Reset Success!")
def export(self):
atrial = self.data_list2
ven = self.data_list
result = self.parameter.savereport(self.user.username,atrial,ven)
if result == True:
self.setWin.showMsg("Success","Report saved in"+" "+APP_PATH+"/"+self.user.username+" folder")
else:
self.setWin.showMsg("Failed","Export failed, please try again")
def setDisabled(self,mode):
disabledList = self.parameter.getDisabled(mode)
for key, value in self.setWin.__dict__.items():
value.setEnabled(True)
for key, value in self.checkBox.items():
self.setWin.__dict__[value].setChecked(True)
for key in disabledList:
self.setWin.__dict__[key].setEnabled(False)
if key in self.checkBox.keys():
checkBoxName = self.checkBox[key]
self.setWin.__dict__[checkBoxName].setChecked(False)
self.setWin.__dict__[checkBoxName].setEnabled(False)
def checkBoxEn(self):
for key, value in self.checkBox.items():
if(self.setWin.__dict__[value].isChecked()):
self.setWin.__dict__[key].setEnabled(True)
else:
self.setWin.__dict__[key].setEnabled(False)
# mode list
modeIndex = {
"OOO":0, # this is off state
"DDD":1,
"VDD":2,
"DDI":3,
"DOO":4,
"AOO":5,
"AAI":6,
"VOO":7,
"VVI":8,
"AAT":8,
"VVT":10,
"DDDR":11,
"VDDR":12,
"DDIR":13,
"DOOR":14,
"AOOR":15,
"AAIR":16,
"VOOR":17,
"VVIR":18
}
modeIndex1 = {
"O":0,
"A":1,
"V":2,
"D":3
}
modeIndex3 = {
"O":0,
"T":1,
"I":2,
"D":3
}
checkBox = {
"SAVDO":"SAVDO_en",
"VPAR":"VPAR_en",
"APAR":"APAR_en",
"PVARPE":"PVARPE_en"
}
#-------------------------
# Conection List
def __connectionList(self):
#-----------------------------------------------------------------------
# device setting part
#-----------------------------------------------------------------------
# add button event
self.setWin.B_Save.clicked.connect(self.save)
self.setWin.B_Load.clicked.connect(self.load)
self.setWin.B_Upload.clicked.connect(self.upload)
self.setWin.B_Reset.clicked.connect(self.resetDefault)
self.setWin.B_Cur.clicked.connect(self.resetCurrent)
self.setWin.B_ConfirmMode.clicked.connect(self.confirmForm)
# check box state change event
self.setWin.SAVDO_en.stateChanged.connect(self.checkBoxEn)
self.setWin.VPAR_en.stateChanged.connect(self.checkBoxEn)
self.setWin.APAR_en.stateChanged.connect(self.checkBoxEn)
self.setWin.PVARPE_en.stateChanged.connect(self.checkBoxEn)
# when mode index changed
self.setWin.I_Rate.currentIndexChanged.connect(self.refreshForm)
self.setWin.I_Response.currentIndexChanged.connect(self.refreshForm)
#-----------------------------------------------------------------------
# info
#-----------------------------------------------------------------------
# timer event
self.infoWin.timer.timeout.connect(self.get_info)
self.infoWin.timer.timeout.connect(self.get_info2)
self.samplingperiod = 500
#self.check_connection()
#button
self.infoWin.showEgram.clicked.connect(self.device.startEgram)
self.infoWin.stopEgram.clicked.connect(self.device.stopEgram)
self.infoWin.testConnect.clicked.connect(self.manualConnection)
self.infoWin.testUnconnect.clicked.connect(self.manualUnconnect)
self.infoWin.B_Logout.clicked.connect(self.logOut)
self.infoWin.export.clicked.connect(self.export)
#monitor signal send from device
self.device.newConnect.connect(self.newConnection)
self.device.status.connect(self.message)
self.device.egram.connect(self.get_info)
self.device.atrialegram.connect(self.get_info2)
#self.device.paraemit.connect(self.updatepara)
| # -*- encoding:utf-8 -*-
#from utils.core import Core
from view.mainWin import Ui_Form
from view.deviceSetting import Ui_Form as deviceSetting
from view.info import Ui_Form as info
from model.parameter import parameter as pr
from model.device import device
from config import APP_PATH
from PyQt5 import QtCore, QtWidgets
"""
Main Windows
"""
class mainWinController:
#-----------------------------------------------------------------------
# Constructor (show windows)
#-----------------------------------------------------------------------
def __init__(self, parent=None):
print(str(parent)+str(type(parent)))
self.parameter = pr()
self.device = device()
self.setWin = deviceSetting()
self.infoWin = info()
self.__connectionList()
self.data_list=[]
self.data_list2=[]
self.start_data = -1
self.start_data2 = -1
#-----------------------------------------------------------------------
# device setting part
#-----------------------------------------------------------------------
self.resetDefault()
self.checkBoxEn()
#-----------------------------------------------------------------------
# info
#-----------------------------------------------------------------------
#store all windows
self.core = parent; # do not miss this line, core is necessary
self.view = Ui_Form([self.setWin,self.infoWin])
## add button event
def loadView(self):
self.view.show()
def loadUser(self,user):
self.user = user
self.user_info()
#-----------------------------------------------------------------------
# info
#-----------------------------------------------------------------------
def lost_connnect(self):
self.infoWin.connect.setText("Connection: "+"False")
self.infoWin.battery.setText("Battery: "+"No infomation")
self.device.connection = False
self.infoWin.showMsg("Note","Connection Lost")
'''
for test only
'''
def message(self,str):
self.infoWin.showMsg("Serial Output",str)
# graph action
def start_graph(self):
if(self.device.connection):
self.infoWin.timer.start(self.samplingperiod)
else:
self.infoWin.showMsg("Error", "No device Connected")
def stop_graph(self):
self.infoWin.timer.stop()
def get_info(self,data):
self.data_list.append(5-data*5)
print(5-data*5)
xrange = 20
if len(self.data_list) > 20:
self.start_data += 1
self.infoWin.graph.setXRange(self.start_data,self.start_data+xrange)
else:
self.infoWin.graph.setXRange(0,xrange)
if len(self.data_list) > 100:
self.start_data -= 1
self.data_list.pop(0)
self.infoWin.graph.clear()
# self.infoWin.graph.title('Ventricle Signals')
self.infoWin.graph.plot().setData(self.data_list,pen = 'g')
def get_info2(self,data):
self.data_list2.append(5-data*5)
print(5-data*5)
xrange = 20
if len(self.data_list2) > 20:
self.start_data2 += 1
self.infoWin.atrialgraph.setXRange(self.start_data2,self.start_data2+xrange)
else:
self.infoWin.atrialgraph.setXRange(0,xrange)
if len(self.data_list2) > 100:
self.start_data2 -= 1
self.data_list2.pop(0)
self.infoWin.atrialgraph.clear()
# self.infoWin.atrialgraph.title('Atrium Signals')
self.infoWin.atrialgraph.plot().setData(self.data_list2,pen = 'g')
# button action
# device action
def newConnection(self,port):
result = self.infoWin.confirm("New Device approch at port " +port+". Connect to new device?")
if (result == 16384):
self.device.openSerial(port)
# add new item to port
self.infoWin.port.clear()
self.infoWin.port.addItems(self.device.getSerialPorts())
self.device.timer.start(500)
self.infoWin.connect.setText("Device: Connected at "+port)
def manualConnection(self):
port = self.infoWin.port.currentText()
if port!= "":
self.device.openSerial(port)
self.infoWin.connect.setText("Device: Connected at "+port)
else:
self.infoWin.showMsg("Error","Port Not selected. Please select the connection port first.")
def manualUnconnect(self):
self.device.closeSerial()
self.infoWin.connect.setText("No Device Connected")
def check_battery(self):
self.infoWin.battery.setText("Battery: "+str(self.device.getbatterydata()))
def user_info(self):
self.infoWin.username.setText("User name is: "+self.user.username)
self.infoWin.B_Logout.setText("Logout: "+self.user.username)
#---------------------------------------------------------------------
# Device Setting page
#---------------------------------------------------------------------
def loadParameter(self):
for key, value in self.parameter.parameters.items():
itemtype = str(type(self.setWin.__dict__[key]))
if(itemtype.find("QLineEdit")!=-1):
self.setWin.__dict__[key].setText(value)
self.refreshFormByText(value)
elif(itemtype.find("QComboBox")!=-1):
self.setWin.__dict__[key].setCurrentText(value)
else:
self.setWin.__dict__[key].setProperty("value", value)
# for special check box case
temp = self.parameter.parameters
for key, value in self.checkBox.items():
if(temp[key] == "Off"):
self.setWin.__dict__[value].setChecked(False)
else:
self.setWin.__dict__[value].setChecked(True)
def getPara(self):
para = {}
for key, value in self.setWin.__dict__.items():
if(value.isEnabled()):
if(key.find("_")==-1):
valuetype = str(type(value))
if(valuetype.find("QLineEdit")!=-1):
value = value.text()
elif(valuetype.find("QComboBox")!=-1):
value = value.currentText()
else:
value = value.value()
para[key] = value
else:
para[key] = "Off"
return para
# action method
def confirmForm(self):
self.refreshFormByText(self.setWin.mode.text())
def refreshFormByText(self,mode):
try:
index = self.modeIndex[mode]
self.setWin.mode.setText(mode)
except KeyError as e:
self.setWin.showMsg("Mode Error",mode+" is not a proper mode")
index = [0,0,0,0]
index[0] = self.modeIndex1[mode[0]]
index[1] = self.modeIndex1[mode[1]]
index[2] = self.modeIndex3[mode[2]]
if(len(mode)>3 and mode[3]=="R"):
index[3] = 1
else:
index[3] = 0
self.setWin.I_Pace.setCurrentIndex(index[0])
self.setWin.I_Sence.setCurrentIndex(index[1])
self.setWin.I_Response.setCurrentIndex(index[2])
self.setWin.I_Rate.setCurrentIndex(index[3])
self.setDisabled(mode)
def refreshForm(self):
# get current value
pace = self.setWin.I_Pace.currentText().split("-")[0]
sense = self.setWin.I_Sence.currentText().split("-")[0]
response = self.setWin.I_Response.currentText().split("-")[0]
if (self.setWin.I_Rate.currentText()=="None"):
rate = ""
else:
rate = "R"
mode = pace+sense+response+rate
print(mode)
try:
index = self.modeIndex[mode]
self.setWin.mode.setText(mode)
self.setDisabled(mode)
except KeyError as e:
self.setWin.showMsg("Mode Error",mode+" is not a proper mode")
def logOut(self):
self.core.openView("login")
self.view.hide()
def save(self):
self.parameter.parameters = self.getPara()
result = self.parameter.save(self.user.username,"save")
if result == True:
self.setWin.showMsg("Success","Save Success")
else:
meg = ""
for key, value in result.items():
meg += (key+value[2] + "Range: "+ str(value[0])+" Increment: "+str(value[1])+". "+"\n")
self.setWin.showMsg("Error", meg)
def load(self):
test = self.parameter.load(self.user.username)
if test == False:
self.setWin.showMsg("Load Failed","Load Failed, user folder not exist!")
else:
directory = QtWidgets.QFileDialog.getOpenFileName(None,"Choose file",self.parameter.load(self.user.username))
if directory[0] == '':
self.setWin.showMsg("Load Failed","User must choose one json file to load!")
else:
self.setWin.showMsg("File Path",directory[0])
self.parameter.loadcon(directory[0])
self.loadParameter()
self.setWin.showMsg("Success","Load Success!")
def upload(self):
result = self.setWin.confirm('Comfirm to upload parameters to pacemaker')
#if select yes
if (result == 16384):
# check device connection
if(self.device.connection == False):
self.setWin.showMsg("Error", "No device Connected")
return
self.parameter.parameters = self.getPara()
# add line where we will upload through device
result = self.parameter.save(self.user.username,"upload") # save history also check if parameter are valid
if result == True:
# do the actual serial send
self.parameter.parameters['mode'] = self.modeIndex[self.parameter.parameters['mode']] # store index
self.device.sendParam(self.parameter.parameters)
else:
meg = ""
for key, value in result.items():
meg += (key+value[2] + "Range: "+ str(value[0])+" Increment: "+str(value[1])+". "+"\n")
self.setWin.showMsg("Error", meg)
def resetDefault(self):
self.parameter.getDefault()
self.loadParameter()
def resetCurrent(self):
self.parameter.getDefault()
self.parameter.parameters = self.device.rqstPara(self.parameter.parameters)
# result = self.parameter.savecurrent(self.user.username)
# if result == True:
# filepath = self.parameter.load(self.user.username)
# self.parameter.loadcon(filepath+'/currentpara/from_device.json')
# self.loadParameter()
self.loadParameter()
self.setWin.showMsg("Success","Reset Success!")
def export(self):
atrial = self.data_list2
ven = self.data_list
result = self.parameter.savereport(self.user.username,atrial,ven)
if result == True:
self.setWin.showMsg("Success","Report saved in"+" "+APP_PATH+"/"+self.user.username+" folder")
else:
self.setWin.showMsg("Failed","Export failed, please try again")
def setDisabled(self,mode):
disabledList = self.parameter.getDisabled(mode)
for key, value in self.setWin.__dict__.items():
value.setEnabled(True)
for key, value in self.checkBox.items():
self.setWin.__dict__[value].setChecked(True)
for key in disabledList:
self.setWin.__dict__[key].setEnabled(False)
if key in self.checkBox.keys():
checkBoxName = self.checkBox[key]
self.setWin.__dict__[checkBoxName].setChecked(False)
self.setWin.__dict__[checkBoxName].setEnabled(False)
def checkBoxEn(self):
for key, value in self.checkBox.items():
if(self.setWin.__dict__[value].isChecked()):
self.setWin.__dict__[key].setEnabled(True)
else:
self.setWin.__dict__[key].setEnabled(False)
# mode list
modeIndex = {
"OOO":0, # this is off state
"DDD":1,
"VDD":2,
"DDI":3,
"DOO":4,
"AOO":5,
"AAI":6,
"VOO":7,
"VVI":8,
"AAT":8,
"VVT":10,
"DDDR":11,
"VDDR":12,
"DDIR":13,
"DOOR":14,
"AOOR":15,
"AAIR":16,
"VOOR":17,
"VVIR":18
}
modeIndex1 = {
"O":0,
"A":1,
"V":2,
"D":3
}
modeIndex3 = {
"O":0,
"T":1,
"I":2,
"D":3
}
checkBox = {
"SAVDO":"SAVDO_en",
"VPAR":"VPAR_en",
"APAR":"APAR_en",
"PVARPE":"PVARPE_en"
}
#-------------------------
# Conection List
def __connectionList(self):
#-----------------------------------------------------------------------
# device setting part
#-----------------------------------------------------------------------
# add button event
self.setWin.B_Save.clicked.connect(self.save)
self.setWin.B_Load.clicked.connect(self.load)
self.setWin.B_Upload.clicked.connect(self.upload)
self.setWin.B_Reset.clicked.connect(self.resetDefault)
self.setWin.B_Cur.clicked.connect(self.resetCurrent)
self.setWin.B_ConfirmMode.clicked.connect(self.confirmForm)
# check box state change event
self.setWin.SAVDO_en.stateChanged.connect(self.checkBoxEn)
self.setWin.VPAR_en.stateChanged.connect(self.checkBoxEn)
self.setWin.APAR_en.stateChanged.connect(self.checkBoxEn)
self.setWin.PVARPE_en.stateChanged.connect(self.checkBoxEn)
# when mode index changed
self.setWin.I_Rate.currentIndexChanged.connect(self.refreshForm)
self.setWin.I_Response.currentIndexChanged.connect(self.refreshForm)
#-----------------------------------------------------------------------
# info
#-----------------------------------------------------------------------
# timer event
self.infoWin.timer.timeout.connect(self.get_info)
self.infoWin.timer.timeout.connect(self.get_info2)
self.samplingperiod = 500
#self.check_connection()
#button
self.infoWin.showEgram.clicked.connect(self.device.startEgram)
self.infoWin.stopEgram.clicked.connect(self.device.stopEgram)
self.infoWin.testConnect.clicked.connect(self.manualConnection)
self.infoWin.testUnconnect.clicked.connect(self.manualUnconnect)
self.infoWin.B_Logout.clicked.connect(self.logOut)
self.infoWin.export.clicked.connect(self.export)
#monitor signal send from device
self.device.newConnect.connect(self.newConnection)
self.device.status.connect(self.message)
self.device.egram.connect(self.get_info)
self.device.atrialegram.connect(self.get_info2)
#self.device.paraemit.connect(self.updatepara) | en | 0.207443 | # -*- encoding:utf-8 -*- #from utils.core import Core Main Windows #----------------------------------------------------------------------- # Constructor (show windows) #----------------------------------------------------------------------- #----------------------------------------------------------------------- # device setting part #----------------------------------------------------------------------- #----------------------------------------------------------------------- # info #----------------------------------------------------------------------- #store all windows # do not miss this line, core is necessary ## add button event #----------------------------------------------------------------------- # info #----------------------------------------------------------------------- for test only # graph action # self.infoWin.graph.title('Ventricle Signals') # self.infoWin.atrialgraph.title('Atrium Signals') # button action # device action # add new item to port #--------------------------------------------------------------------- # Device Setting page #--------------------------------------------------------------------- # for special check box case # action method # get current value #if select yes # check device connection # add line where we will upload through device # save history also check if parameter are valid # do the actual serial send # store index # result = self.parameter.savecurrent(self.user.username) # if result == True: # filepath = self.parameter.load(self.user.username) # self.parameter.loadcon(filepath+'/currentpara/from_device.json') # self.loadParameter() # mode list # this is off state #------------------------- # Conection List #----------------------------------------------------------------------- # device setting part #----------------------------------------------------------------------- # add button event # check box state change event # when mode index changed #----------------------------------------------------------------------- # info #----------------------------------------------------------------------- # timer event #self.check_connection() #button #monitor signal send from device #self.device.paraemit.connect(self.updatepara) | 2.335833 | 2 |
src/tigrillo_ctrl/nrp/save_downsampled_CPG.py | Gabs48/tigrillo2 | 1 | 6616121 | <reponame>Gabs48/tigrillo2
import generate_cpg_control as gcpg
import numpy as np
import matplotlib.pyplot as plt
input_duration = 9000#00 # ms
sample_freq = 50 #Hz
"""
## gait 1
##################5D cmaes####################
cmaes_params = ['po', 'd0','d1', 'offset_front', 'offset_back']
cmaes_result = [3.2413127551, 0.211397468, 0.7326430427, -21.1273863722, -44.701767989] #2017-9-18-19-42-32_smallTigrillo_V1_0
#cmaes_result = [2.2790555049, 0.1956551467, 0.7788317559, -56.4503996947, -46.4655112539] #2017-9-19-23-28-58_tigrillo_scaled_2_D5N30
#cmaes_result = [2.0340744571, 0.1632550915, 0.7898942269, -57.9799255258, -53.0439114074] #2017-9-19-23-28-58_tigrillo_scaled_2_D5N30/iteration45
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
#for small tigrillo V1
mu = [1247.8506096107708, 1271.4286080336062, 1350.704882789273, 1315.9368951279903] # amplitude
o = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset
omega = [8.966, 8.966, 8.966, 8.966]
d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle
phase_offset = [0.0, cmaes_dict['po'], cmaes_dict['po']]
params1=[mu, o, omega, d, phase_offset]
cpg = gcpg.CPGControl(mu, o, omega, d, phase_offset)
#####################################
"""
"""
##################7D cmaes####################
cmaes_params = ['po0', 'po1', 'po2', 'd0','d1', 'offset_front', 'offset_back']
#cmaes_result = [2.5207115564, 3.2030357947, 0.5635350325, 0.1215260447, 0.4374383347, -50.6735687191, -52.8367739961] #2017-9-19-12-15-43_smallTigrillo_V1_0_test_freePhases/iteration26
#cmaes_result = [4.1009682881,3.2466187818, 0.0061914678, 0.3975706851, 0.5102393513, -31.7045448732, -55.4275270132] #2017-9-19-12-15-43_smallTigrillo_V1_0_test_freePhases/iteration26
#cmaes_result = [3.117216713, 3.5805672076, 0.4983965045, 0.2018984599, 0.431241239, -50.5287942639, -58.1467273582] #2017-9-19-12-15-43_smallTigrillo_V1_0_test_freePhases/iteration26
#cmaes_result = [4.956428689, 0.8693965091, 1.0057709612, 0.3565657469, 0.4991825631, -57.9081051751, -59.009645482] #2017-9-19-12-15-43_smallTigrillo_V1_0_test_freePhases/iteration26
cmaes_result = [3.429805552, 3.0847672897, 0.0425837786, 0.1315289634, 0.7607450554, -1.2052280883, -59.6837517889] #2017-9-20-23-36-4_tigrillo_scaled_feets_D7N30/2017-9-21-8-18-10_iteration86
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
C=0.2
#for small tigrillo V1
mu = [1247.8506096107708, 1271.4286080336062, 1350.704882789273, 1315.9368951279903] # amplitude
o = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset
omega = [8.966*C, 8.966*C, 8.966*C, 8.966*C]
d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle
phase_offset = [cmaes_dict['po0'], cmaes_dict['po1'], cmaes_dict['po2']]
#####################################
"""
"""
#real Tigrillo 13D
cmaes_params = ['amp_front', 'amp_back', 'po0','po1','po2','d0L','d0R','d1L','d1R', 'offset_front_L', 'offset_front_R', 'offset_back_L', 'offset_back_R']
cmaes_result = [1995.7099789934, 1329.1776800352, 6.1912688963, 3.4014967152, 6.1735169153, 0.1167378107, 0.7280241508, 0.3020831716, 0.31960611, 50.4405367733, 57.0642534081, -12.9733777616, -10.8132940565] #sftp://paard.elis.ugent.be/home/nrp/Documents/ExperimentData/2018-2-14-18-52-4_CMAES-CPG_CMAES_RealTigrillo_13D/2018-2-15-3-43-35_iteration177/
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
mu = [cmaes_dict['amp_front'], cmaes_dict['amp_front'] , cmaes_dict['amp_back'], cmaes_dict['amp_back']] #amplitude?
o = [cmaes_dict['offset_front_L'], cmaes_dict['offset_front_R'], cmaes_dict['offset_back_L'], cmaes_dict['offset_back_R']] #offset
omega = [8.966, 8.966, 8.966, 8.966 ]#frequencyish 8.966
d = [cmaes_dict['d0L'],cmaes_dict['d0R'],cmaes_dict['d1L'],cmaes_dict['d1R']] #duty cycle
phase_offset = [cmaes_dict['po0'], cmaes_dict['po1'], cmaes_dict['po2']]
#####################################
"""
"""
#real Tigrillo 9D
cmaes_params = ['amp_front', 'amp_back', 'po0','po1','po2','d0','d1', 'offset_front', 'offset_back']
cmaes_result = [668.25574929834215, 1822.3681372677133, 3.7880702189186857, 0.60736980037586219, 3.6471465072591993,0.59685632758599882, 0.10100339905535813, 54.730753979237697, -7.4285040557806914] #sftp://paard.elis.ugent.be/home/nrp/Documents/ExperimentData/2018-2-15-17-31-46_CMAES-CPG_CMAES_RealTigrillo_9D/2018-2-16-3-36-48_iteration199
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
mu = [cmaes_dict['amp_front'], cmaes_dict['amp_front'] , cmaes_dict['amp_back'], cmaes_dict['amp_back']] # amplitude
o = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset
omega = [8.966, 8.966, 8.966, 8.966]
d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle
phase_offset = [cmaes_dict['po0'], cmaes_dict['po1'], cmaes_dict['po2']]
cpg = gcpg.CPGControl(mu, o, omega, d, phase_offset)
#####################################
"""
"""
#####################################
#7D RealT cmaes bounding gait
cmaes_params = ['amp_front', 'amp_back', 'po', 'd0', 'd1', 'offset_front', 'offset_back']
cmaes_result = [2000.7145318283, 1940.7274052927, 3.1386621172, 0.1035151832, 0.1172187076, 59.9359462891, 15.4933086429] #/home/alexander/Documents/ExperimentData/2018-2-19-0-51-7_CMAES-CPG_realTigrillo_searchBoundingGait/2018-2-19-8-39-34_iteration149 ->bounding gait
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
mu1 = [cmaes_dict['amp_front'], cmaes_dict['amp_front'], cmaes_dict['amp_back'], cmaes_dict['amp_back']] # amplitude
o1 = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset
omega1 = [8.966, 8.966, 8.966, 8.966]
d1 = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle
phase_offset1 = [0, cmaes_dict['po'], cmaes_dict['po']]
params1=[mu1, o1, omega1, d1, phase_offset1]
cpg = gcpg.CPGControl(mu1, o1, omega1, d1, phase_offset1)
#####################################
"""
"""
#####################################
#7D RealT cmaes bounding gait
cmaes_params = ['amp_front', 'amp_back', 'po', 'd0', 'd1', 'offset_front', 'offset_back']
cmaes_result = [357.7145318283, 1940.7274052927, 3.1386621172, 0.1035151832, 0.1172187076, 59.9359462891, 15.4933086429] #/home/alexander/Documents/ExperimentData/2018-2-19-0-51-7_CMAES-CPG_realTigrillo_searchBoundingGait/2018-2-19-8-39-34_iteration149 ->bounding gait
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
mu1 = [10.,200.,300.,1000.] # amplitude
o1 = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset
#omega1 = [5., 0., 5., 0.]
#omega1 = [0., 5., 0., 5.]
omega1 = [5., 5., 5., 5.]
d1 = [cmaes_dict['d0'], cmaes_dict['d0'], 0.18, cmaes_dict['d1']] # duty cycle
phase_offset1 = [0.0, cmaes_dict['po'], cmaes_dict['po']]
params1=[mu1, o1, omega1, d1, phase_offset1]
cpg = gcpg.CPGControl(mu1, o1, omega1, d1, phase_offset1)
#####################################
"""
#####################################
#7D calibrated RealT cmaes:
cmaes_params = ['amp_front', 'amp_back', 'po', 'd0', 'd1', 'offset_front', 'offset_back']
cmaes_result = [1479.4733148744, 1966.2014925501, 1.7907346139, 0.1132321966, 0.1000351019, 7.1551633616, -19.8186370404] #/home/alexander/Documents/ExperimentData/2018-4-25-6-47-35_CMAES-CPG_CMAES_CalibratedTigrillo_7D_1Hz/2018-4-25-10-26-35_iteration88
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
mu = [cmaes_dict['amp_front'], cmaes_dict['amp_front'], cmaes_dict['amp_back'], cmaes_dict['amp_back']] # amplitude
o = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset
omega = [6.28, 6.28, 6.28, 6.28]
d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle
phase_offset = [0, cmaes_dict['po'], cmaes_dict['po']]
cpg = gcpg.CPGControl(mu, o, omega, d, phase_offset)
#####################################
"""
## gait0
#####################################
#calibrated Tigrillo 9D
cmaes_params = ['amp_front', 'amp_back', 'po0','po1','po2','d0','d1', 'offset_front', 'offset_back']
cmaes_result = [1995.20545060220, 1999.5335596501, 2.3767353984, 6.1711704122, 2.2575967656, 0.5797908017, 0.849271304, 50.5657854418, 21.841845545] #/home/alexander/Documents/ExperimentData/2018-4-24-23-25-52_CMAES-CPG_CMAES_CalibratedTigrillo_9D_1Hz/2018-4-25-6-40-4_iteration173
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
mu = [cmaes_dict['amp_front'], cmaes_dict['amp_front'] , cmaes_dict['amp_back'], cmaes_dict['amp_back']] # amplitude
o = [cmaes_dict['offset_front']-30, cmaes_dict['offset_front']-30, cmaes_dict['offset_back']-30, cmaes_dict['offset_back']-30] # offset
omega = [6.28, 6.28, 6.28, 6.28]
d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle
phase_offset = [cmaes_dict['po0'], cmaes_dict['po1'], cmaes_dict['po2']]
cpg = gcpg.CPGControl(mu, o, omega, d, phase_offset)
#####################################
"""
sig = np.transpose([ cpg.step_open_loop() for i in range(input_duration)]) #siebes cpg generator presumably with sample frequency of 1000 Hz
#downsample, we only need frequency of sample_freq
downfactor = 1000/sample_freq
shape1 = sig.shape[1]/downfactor
sig2 = np.empty((sig.shape[0],shape1))
for idx, row in enumerate(sig):
sig2[idx] = row[::downfactor][:shape1]
print "caveat, forced bounding"
sig2[1] = sig2[0]
sig2 =np.array(sig2)
plt.figure()
plt.plot(np.transpose(sig2))
plt.xlabel('timestep')
plt.ylabel('degrees')
plt.title('Target Signals')
plt.legend(loc=0)
plt.show()
y_signals = [list(x[16:]) for x in sig2]
np.save('/home/alexander/downsampled_cpg_calibratedT_7D',y_signals)
| import generate_cpg_control as gcpg
import numpy as np
import matplotlib.pyplot as plt
input_duration = 9000#00 # ms
sample_freq = 50 #Hz
"""
## gait 1
##################5D cmaes####################
cmaes_params = ['po', 'd0','d1', 'offset_front', 'offset_back']
cmaes_result = [3.2413127551, 0.211397468, 0.7326430427, -21.1273863722, -44.701767989] #2017-9-18-19-42-32_smallTigrillo_V1_0
#cmaes_result = [2.2790555049, 0.1956551467, 0.7788317559, -56.4503996947, -46.4655112539] #2017-9-19-23-28-58_tigrillo_scaled_2_D5N30
#cmaes_result = [2.0340744571, 0.1632550915, 0.7898942269, -57.9799255258, -53.0439114074] #2017-9-19-23-28-58_tigrillo_scaled_2_D5N30/iteration45
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
#for small tigrillo V1
mu = [1247.8506096107708, 1271.4286080336062, 1350.704882789273, 1315.9368951279903] # amplitude
o = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset
omega = [8.966, 8.966, 8.966, 8.966]
d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle
phase_offset = [0.0, cmaes_dict['po'], cmaes_dict['po']]
params1=[mu, o, omega, d, phase_offset]
cpg = gcpg.CPGControl(mu, o, omega, d, phase_offset)
#####################################
"""
"""
##################7D cmaes####################
cmaes_params = ['po0', 'po1', 'po2', 'd0','d1', 'offset_front', 'offset_back']
#cmaes_result = [2.5207115564, 3.2030357947, 0.5635350325, 0.1215260447, 0.4374383347, -50.6735687191, -52.8367739961] #2017-9-19-12-15-43_smallTigrillo_V1_0_test_freePhases/iteration26
#cmaes_result = [4.1009682881,3.2466187818, 0.0061914678, 0.3975706851, 0.5102393513, -31.7045448732, -55.4275270132] #2017-9-19-12-15-43_smallTigrillo_V1_0_test_freePhases/iteration26
#cmaes_result = [3.117216713, 3.5805672076, 0.4983965045, 0.2018984599, 0.431241239, -50.5287942639, -58.1467273582] #2017-9-19-12-15-43_smallTigrillo_V1_0_test_freePhases/iteration26
#cmaes_result = [4.956428689, 0.8693965091, 1.0057709612, 0.3565657469, 0.4991825631, -57.9081051751, -59.009645482] #2017-9-19-12-15-43_smallTigrillo_V1_0_test_freePhases/iteration26
cmaes_result = [3.429805552, 3.0847672897, 0.0425837786, 0.1315289634, 0.7607450554, -1.2052280883, -59.6837517889] #2017-9-20-23-36-4_tigrillo_scaled_feets_D7N30/2017-9-21-8-18-10_iteration86
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
C=0.2
#for small tigrillo V1
mu = [1247.8506096107708, 1271.4286080336062, 1350.704882789273, 1315.9368951279903] # amplitude
o = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset
omega = [8.966*C, 8.966*C, 8.966*C, 8.966*C]
d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle
phase_offset = [cmaes_dict['po0'], cmaes_dict['po1'], cmaes_dict['po2']]
#####################################
"""
"""
#real Tigrillo 13D
cmaes_params = ['amp_front', 'amp_back', 'po0','po1','po2','d0L','d0R','d1L','d1R', 'offset_front_L', 'offset_front_R', 'offset_back_L', 'offset_back_R']
cmaes_result = [1995.7099789934, 1329.1776800352, 6.1912688963, 3.4014967152, 6.1735169153, 0.1167378107, 0.7280241508, 0.3020831716, 0.31960611, 50.4405367733, 57.0642534081, -12.9733777616, -10.8132940565] #sftp://paard.elis.ugent.be/home/nrp/Documents/ExperimentData/2018-2-14-18-52-4_CMAES-CPG_CMAES_RealTigrillo_13D/2018-2-15-3-43-35_iteration177/
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
mu = [cmaes_dict['amp_front'], cmaes_dict['amp_front'] , cmaes_dict['amp_back'], cmaes_dict['amp_back']] #amplitude?
o = [cmaes_dict['offset_front_L'], cmaes_dict['offset_front_R'], cmaes_dict['offset_back_L'], cmaes_dict['offset_back_R']] #offset
omega = [8.966, 8.966, 8.966, 8.966 ]#frequencyish 8.966
d = [cmaes_dict['d0L'],cmaes_dict['d0R'],cmaes_dict['d1L'],cmaes_dict['d1R']] #duty cycle
phase_offset = [cmaes_dict['po0'], cmaes_dict['po1'], cmaes_dict['po2']]
#####################################
"""
"""
#real Tigrillo 9D
cmaes_params = ['amp_front', 'amp_back', 'po0','po1','po2','d0','d1', 'offset_front', 'offset_back']
cmaes_result = [668.25574929834215, 1822.3681372677133, 3.7880702189186857, 0.60736980037586219, 3.6471465072591993,0.59685632758599882, 0.10100339905535813, 54.730753979237697, -7.4285040557806914] #sftp://paard.elis.ugent.be/home/nrp/Documents/ExperimentData/2018-2-15-17-31-46_CMAES-CPG_CMAES_RealTigrillo_9D/2018-2-16-3-36-48_iteration199
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
mu = [cmaes_dict['amp_front'], cmaes_dict['amp_front'] , cmaes_dict['amp_back'], cmaes_dict['amp_back']] # amplitude
o = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset
omega = [8.966, 8.966, 8.966, 8.966]
d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle
phase_offset = [cmaes_dict['po0'], cmaes_dict['po1'], cmaes_dict['po2']]
cpg = gcpg.CPGControl(mu, o, omega, d, phase_offset)
#####################################
"""
"""
#####################################
#7D RealT cmaes bounding gait
cmaes_params = ['amp_front', 'amp_back', 'po', 'd0', 'd1', 'offset_front', 'offset_back']
cmaes_result = [2000.7145318283, 1940.7274052927, 3.1386621172, 0.1035151832, 0.1172187076, 59.9359462891, 15.4933086429] #/home/alexander/Documents/ExperimentData/2018-2-19-0-51-7_CMAES-CPG_realTigrillo_searchBoundingGait/2018-2-19-8-39-34_iteration149 ->bounding gait
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
mu1 = [cmaes_dict['amp_front'], cmaes_dict['amp_front'], cmaes_dict['amp_back'], cmaes_dict['amp_back']] # amplitude
o1 = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset
omega1 = [8.966, 8.966, 8.966, 8.966]
d1 = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle
phase_offset1 = [0, cmaes_dict['po'], cmaes_dict['po']]
params1=[mu1, o1, omega1, d1, phase_offset1]
cpg = gcpg.CPGControl(mu1, o1, omega1, d1, phase_offset1)
#####################################
"""
"""
#####################################
#7D RealT cmaes bounding gait
cmaes_params = ['amp_front', 'amp_back', 'po', 'd0', 'd1', 'offset_front', 'offset_back']
cmaes_result = [357.7145318283, 1940.7274052927, 3.1386621172, 0.1035151832, 0.1172187076, 59.9359462891, 15.4933086429] #/home/alexander/Documents/ExperimentData/2018-2-19-0-51-7_CMAES-CPG_realTigrillo_searchBoundingGait/2018-2-19-8-39-34_iteration149 ->bounding gait
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
mu1 = [10.,200.,300.,1000.] # amplitude
o1 = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset
#omega1 = [5., 0., 5., 0.]
#omega1 = [0., 5., 0., 5.]
omega1 = [5., 5., 5., 5.]
d1 = [cmaes_dict['d0'], cmaes_dict['d0'], 0.18, cmaes_dict['d1']] # duty cycle
phase_offset1 = [0.0, cmaes_dict['po'], cmaes_dict['po']]
params1=[mu1, o1, omega1, d1, phase_offset1]
cpg = gcpg.CPGControl(mu1, o1, omega1, d1, phase_offset1)
#####################################
"""
#####################################
#7D calibrated RealT cmaes:
cmaes_params = ['amp_front', 'amp_back', 'po', 'd0', 'd1', 'offset_front', 'offset_back']
cmaes_result = [1479.4733148744, 1966.2014925501, 1.7907346139, 0.1132321966, 0.1000351019, 7.1551633616, -19.8186370404] #/home/alexander/Documents/ExperimentData/2018-4-25-6-47-35_CMAES-CPG_CMAES_CalibratedTigrillo_7D_1Hz/2018-4-25-10-26-35_iteration88
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
mu = [cmaes_dict['amp_front'], cmaes_dict['amp_front'], cmaes_dict['amp_back'], cmaes_dict['amp_back']] # amplitude
o = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset
omega = [6.28, 6.28, 6.28, 6.28]
d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle
phase_offset = [0, cmaes_dict['po'], cmaes_dict['po']]
cpg = gcpg.CPGControl(mu, o, omega, d, phase_offset)
#####################################
"""
## gait0
#####################################
#calibrated Tigrillo 9D
cmaes_params = ['amp_front', 'amp_back', 'po0','po1','po2','d0','d1', 'offset_front', 'offset_back']
cmaes_result = [1995.20545060220, 1999.5335596501, 2.3767353984, 6.1711704122, 2.2575967656, 0.5797908017, 0.849271304, 50.5657854418, 21.841845545] #/home/alexander/Documents/ExperimentData/2018-4-24-23-25-52_CMAES-CPG_CMAES_CalibratedTigrillo_9D_1Hz/2018-4-25-6-40-4_iteration173
cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result))
mu = [cmaes_dict['amp_front'], cmaes_dict['amp_front'] , cmaes_dict['amp_back'], cmaes_dict['amp_back']] # amplitude
o = [cmaes_dict['offset_front']-30, cmaes_dict['offset_front']-30, cmaes_dict['offset_back']-30, cmaes_dict['offset_back']-30] # offset
omega = [6.28, 6.28, 6.28, 6.28]
d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle
phase_offset = [cmaes_dict['po0'], cmaes_dict['po1'], cmaes_dict['po2']]
cpg = gcpg.CPGControl(mu, o, omega, d, phase_offset)
#####################################
"""
sig = np.transpose([ cpg.step_open_loop() for i in range(input_duration)]) #siebes cpg generator presumably with sample frequency of 1000 Hz
#downsample, we only need frequency of sample_freq
downfactor = 1000/sample_freq
shape1 = sig.shape[1]/downfactor
sig2 = np.empty((sig.shape[0],shape1))
for idx, row in enumerate(sig):
sig2[idx] = row[::downfactor][:shape1]
print "caveat, forced bounding"
sig2[1] = sig2[0]
sig2 =np.array(sig2)
plt.figure()
plt.plot(np.transpose(sig2))
plt.xlabel('timestep')
plt.ylabel('degrees')
plt.title('Target Signals')
plt.legend(loc=0)
plt.show()
y_signals = [list(x[16:]) for x in sig2]
np.save('/home/alexander/downsampled_cpg_calibratedT_7D',y_signals) | en | 0.274848 | #00 # ms #Hz ## gait 1 ##################5D cmaes#################### cmaes_params = ['po', 'd0','d1', 'offset_front', 'offset_back'] cmaes_result = [3.2413127551, 0.211397468, 0.7326430427, -21.1273863722, -44.701767989] #2017-9-18-19-42-32_smallTigrillo_V1_0 #cmaes_result = [2.2790555049, 0.1956551467, 0.7788317559, -56.4503996947, -46.4655112539] #2017-9-19-23-28-58_tigrillo_scaled_2_D5N30 #cmaes_result = [2.0340744571, 0.1632550915, 0.7898942269, -57.9799255258, -53.0439114074] #2017-9-19-23-28-58_tigrillo_scaled_2_D5N30/iteration45 cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result)) #for small tigrillo V1 mu = [1247.8506096107708, 1271.4286080336062, 1350.704882789273, 1315.9368951279903] # amplitude o = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset omega = [8.966, 8.966, 8.966, 8.966] d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle phase_offset = [0.0, cmaes_dict['po'], cmaes_dict['po']] params1=[mu, o, omega, d, phase_offset] cpg = gcpg.CPGControl(mu, o, omega, d, phase_offset) ##################################### ##################7D cmaes#################### cmaes_params = ['po0', 'po1', 'po2', 'd0','d1', 'offset_front', 'offset_back'] #cmaes_result = [2.5207115564, 3.2030357947, 0.5635350325, 0.1215260447, 0.4374383347, -50.6735687191, -52.8367739961] #2017-9-19-12-15-43_smallTigrillo_V1_0_test_freePhases/iteration26 #cmaes_result = [4.1009682881,3.2466187818, 0.0061914678, 0.3975706851, 0.5102393513, -31.7045448732, -55.4275270132] #2017-9-19-12-15-43_smallTigrillo_V1_0_test_freePhases/iteration26 #cmaes_result = [3.117216713, 3.5805672076, 0.4983965045, 0.2018984599, 0.431241239, -50.5287942639, -58.1467273582] #2017-9-19-12-15-43_smallTigrillo_V1_0_test_freePhases/iteration26 #cmaes_result = [4.956428689, 0.8693965091, 1.0057709612, 0.3565657469, 0.4991825631, -57.9081051751, -59.009645482] #2017-9-19-12-15-43_smallTigrillo_V1_0_test_freePhases/iteration26 cmaes_result = [3.429805552, 3.0847672897, 0.0425837786, 0.1315289634, 0.7607450554, -1.2052280883, -59.6837517889] #2017-9-20-23-36-4_tigrillo_scaled_feets_D7N30/2017-9-21-8-18-10_iteration86 cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result)) C=0.2 #for small tigrillo V1 mu = [1247.8506096107708, 1271.4286080336062, 1350.704882789273, 1315.9368951279903] # amplitude o = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset omega = [8.966*C, 8.966*C, 8.966*C, 8.966*C] d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle phase_offset = [cmaes_dict['po0'], cmaes_dict['po1'], cmaes_dict['po2']] ##################################### #real Tigrillo 13D cmaes_params = ['amp_front', 'amp_back', 'po0','po1','po2','d0L','d0R','d1L','d1R', 'offset_front_L', 'offset_front_R', 'offset_back_L', 'offset_back_R'] cmaes_result = [1995.7099789934, 1329.1776800352, 6.1912688963, 3.4014967152, 6.1735169153, 0.1167378107, 0.7280241508, 0.3020831716, 0.31960611, 50.4405367733, 57.0642534081, -12.9733777616, -10.8132940565] #sftp://paard.elis.ugent.be/home/nrp/Documents/ExperimentData/2018-2-14-18-52-4_CMAES-CPG_CMAES_RealTigrillo_13D/2018-2-15-3-43-35_iteration177/ cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result)) mu = [cmaes_dict['amp_front'], cmaes_dict['amp_front'] , cmaes_dict['amp_back'], cmaes_dict['amp_back']] #amplitude? o = [cmaes_dict['offset_front_L'], cmaes_dict['offset_front_R'], cmaes_dict['offset_back_L'], cmaes_dict['offset_back_R']] #offset omega = [8.966, 8.966, 8.966, 8.966 ]#frequencyish 8.966 d = [cmaes_dict['d0L'],cmaes_dict['d0R'],cmaes_dict['d1L'],cmaes_dict['d1R']] #duty cycle phase_offset = [cmaes_dict['po0'], cmaes_dict['po1'], cmaes_dict['po2']] ##################################### #real Tigrillo 9D cmaes_params = ['amp_front', 'amp_back', 'po0','po1','po2','d0','d1', 'offset_front', 'offset_back'] cmaes_result = [668.25574929834215, 1822.3681372677133, 3.7880702189186857, 0.60736980037586219, 3.6471465072591993,0.59685632758599882, 0.10100339905535813, 54.730753979237697, -7.4285040557806914] #sftp://paard.elis.ugent.be/home/nrp/Documents/ExperimentData/2018-2-15-17-31-46_CMAES-CPG_CMAES_RealTigrillo_9D/2018-2-16-3-36-48_iteration199 cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result)) mu = [cmaes_dict['amp_front'], cmaes_dict['amp_front'] , cmaes_dict['amp_back'], cmaes_dict['amp_back']] # amplitude o = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset omega = [8.966, 8.966, 8.966, 8.966] d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle phase_offset = [cmaes_dict['po0'], cmaes_dict['po1'], cmaes_dict['po2']] cpg = gcpg.CPGControl(mu, o, omega, d, phase_offset) ##################################### ##################################### #7D RealT cmaes bounding gait cmaes_params = ['amp_front', 'amp_back', 'po', 'd0', 'd1', 'offset_front', 'offset_back'] cmaes_result = [2000.7145318283, 1940.7274052927, 3.1386621172, 0.1035151832, 0.1172187076, 59.9359462891, 15.4933086429] #/home/alexander/Documents/ExperimentData/2018-2-19-0-51-7_CMAES-CPG_realTigrillo_searchBoundingGait/2018-2-19-8-39-34_iteration149 ->bounding gait cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result)) mu1 = [cmaes_dict['amp_front'], cmaes_dict['amp_front'], cmaes_dict['amp_back'], cmaes_dict['amp_back']] # amplitude o1 = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset omega1 = [8.966, 8.966, 8.966, 8.966] d1 = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle phase_offset1 = [0, cmaes_dict['po'], cmaes_dict['po']] params1=[mu1, o1, omega1, d1, phase_offset1] cpg = gcpg.CPGControl(mu1, o1, omega1, d1, phase_offset1) ##################################### ##################################### #7D RealT cmaes bounding gait cmaes_params = ['amp_front', 'amp_back', 'po', 'd0', 'd1', 'offset_front', 'offset_back'] cmaes_result = [357.7145318283, 1940.7274052927, 3.1386621172, 0.1035151832, 0.1172187076, 59.9359462891, 15.4933086429] #/home/alexander/Documents/ExperimentData/2018-2-19-0-51-7_CMAES-CPG_realTigrillo_searchBoundingGait/2018-2-19-8-39-34_iteration149 ->bounding gait cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result)) mu1 = [10.,200.,300.,1000.] # amplitude o1 = [cmaes_dict['offset_front'], cmaes_dict['offset_front'], cmaes_dict['offset_back'], cmaes_dict['offset_back']] # offset #omega1 = [5., 0., 5., 0.] #omega1 = [0., 5., 0., 5.] omega1 = [5., 5., 5., 5.] d1 = [cmaes_dict['d0'], cmaes_dict['d0'], 0.18, cmaes_dict['d1']] # duty cycle phase_offset1 = [0.0, cmaes_dict['po'], cmaes_dict['po']] params1=[mu1, o1, omega1, d1, phase_offset1] cpg = gcpg.CPGControl(mu1, o1, omega1, d1, phase_offset1) ##################################### ##################################### #7D calibrated RealT cmaes: #/home/alexander/Documents/ExperimentData/2018-4-25-6-47-35_CMAES-CPG_CMAES_CalibratedTigrillo_7D_1Hz/2018-4-25-10-26-35_iteration88 # amplitude # offset # duty cycle ##################################### ## gait0 ##################################### #calibrated Tigrillo 9D cmaes_params = ['amp_front', 'amp_back', 'po0','po1','po2','d0','d1', 'offset_front', 'offset_back'] cmaes_result = [1995.20545060220, 1999.5335596501, 2.3767353984, 6.1711704122, 2.2575967656, 0.5797908017, 0.849271304, 50.5657854418, 21.841845545] #/home/alexander/Documents/ExperimentData/2018-4-24-23-25-52_CMAES-CPG_CMAES_CalibratedTigrillo_9D_1Hz/2018-4-25-6-40-4_iteration173 cmaes_dict = dict((x,y) for x, y in zip(cmaes_params,cmaes_result)) mu = [cmaes_dict['amp_front'], cmaes_dict['amp_front'] , cmaes_dict['amp_back'], cmaes_dict['amp_back']] # amplitude o = [cmaes_dict['offset_front']-30, cmaes_dict['offset_front']-30, cmaes_dict['offset_back']-30, cmaes_dict['offset_back']-30] # offset omega = [6.28, 6.28, 6.28, 6.28] d = [cmaes_dict['d0'], cmaes_dict['d0'], cmaes_dict['d1'], cmaes_dict['d1']] # duty cycle phase_offset = [cmaes_dict['po0'], cmaes_dict['po1'], cmaes_dict['po2']] cpg = gcpg.CPGControl(mu, o, omega, d, phase_offset) ##################################### #siebes cpg generator presumably with sample frequency of 1000 Hz #downsample, we only need frequency of sample_freq | 1.707438 | 2 |
src/game.py | sovaz1997/ZevraGUI | 0 | 6616122 | <filename>src/game.py
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtSvg
import chess.pgn
import numpy as np
from move import Move
from board import BoardView
from graph import GraphView
import defs
class GameModel:
def __init__(self):
self.pgnSrc = open('tcec.pgn')
self.game = chess.pgn.read_game(self.pgnSrc)
self.board = self.game.board()
self.moves = [Move(i) for i in list(self.game.mainline())]
self.currentPosition = 0
def __del__(self):
self.pgnSrc.close()
def goForward(self):
if self.currentPosition < len(self.moves) - 1:
self.board.push(self.getCurrentNode().move)
self.currentPosition += 1
return True
return False
def goBack(self):
if self.currentPosition > 0:
self.board.pop()
self.currentPosition -= 1
return True
return False
def getBoard(self):
return self.board
def getCurrentNode(self):
return self.moves[self.currentPosition]
class GameView(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent=parent)
self.controller = GameController(self)
self.boardView = BoardView(self, self.controller, 50)
self.evalView = GraphView(self)
self.initUI()
def initUI(self):
layout = QHBoxLayout()
layout.addWidget(self.boardView)
layout.addWidget(self.evalView)
self.setLayout(layout)
self.show()
def keyPressEvent(self, e):
key = e.key()
if key == Qt.Key_Right:
self.controller.goForward()
elif key == Qt.Key_Left:
self.controller.goBack()
def wheelEvent(self, e):
if e.angleDelta().y() < 0:
self.controller.goForward()
else:
self.controller.goBack()
class GameController:
def __init__(self, view):
self.view = view
self.model = GameModel()
def goForward(self):
res = self.model.goForward()
if res:
self.view.update()
def goBack(self):
res = self.model.goBack()
if res:
self.view.update()
def getBoardState(self):
return self.model.getBoard()
def getEvals(self):
white = np.array(0, dtype=float)
black = np.array(0, dtype=float)
for i in self.model.moves:
eval = i.eval
color = i.color
if color == WHITE:
white.append(eval)
else:
black.append(eval)
return white, black | <filename>src/game.py
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtSvg
import chess.pgn
import numpy as np
from move import Move
from board import BoardView
from graph import GraphView
import defs
class GameModel:
def __init__(self):
self.pgnSrc = open('tcec.pgn')
self.game = chess.pgn.read_game(self.pgnSrc)
self.board = self.game.board()
self.moves = [Move(i) for i in list(self.game.mainline())]
self.currentPosition = 0
def __del__(self):
self.pgnSrc.close()
def goForward(self):
if self.currentPosition < len(self.moves) - 1:
self.board.push(self.getCurrentNode().move)
self.currentPosition += 1
return True
return False
def goBack(self):
if self.currentPosition > 0:
self.board.pop()
self.currentPosition -= 1
return True
return False
def getBoard(self):
return self.board
def getCurrentNode(self):
return self.moves[self.currentPosition]
class GameView(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent=parent)
self.controller = GameController(self)
self.boardView = BoardView(self, self.controller, 50)
self.evalView = GraphView(self)
self.initUI()
def initUI(self):
layout = QHBoxLayout()
layout.addWidget(self.boardView)
layout.addWidget(self.evalView)
self.setLayout(layout)
self.show()
def keyPressEvent(self, e):
key = e.key()
if key == Qt.Key_Right:
self.controller.goForward()
elif key == Qt.Key_Left:
self.controller.goBack()
def wheelEvent(self, e):
if e.angleDelta().y() < 0:
self.controller.goForward()
else:
self.controller.goBack()
class GameController:
def __init__(self, view):
self.view = view
self.model = GameModel()
def goForward(self):
res = self.model.goForward()
if res:
self.view.update()
def goBack(self):
res = self.model.goBack()
if res:
self.view.update()
def getBoardState(self):
return self.model.getBoard()
def getEvals(self):
white = np.array(0, dtype=float)
black = np.array(0, dtype=float)
for i in self.model.moves:
eval = i.eval
color = i.color
if color == WHITE:
white.append(eval)
else:
black.append(eval)
return white, black | none | 1 | 2.688476 | 3 | |
utcasts/views.py | dennereed/paleocore | 0 | 6616123 | from django.views import generic
from .models import Fossil, Primate
class FossilListView(generic.ListView):
# model = Fossil
context_object_name = 'fossil'
def get_queryset(self):
"""Return a list of fossils """
fossil = Fossil.objects.filter(classification_status='accepted')
return fossil
class PrimateListView(generic.ListView):
# model = Primate
context_object_name = 'primate'
def get_queryset(self):
"""Return a list of primates """
primate = Primate.objects.filter(classification_status='accepted')
return primate
class FossilDetailView(generic.DetailView):
model = Fossil
class PrimateDetailView(generic.DetailView):
model = Primate
| from django.views import generic
from .models import Fossil, Primate
class FossilListView(generic.ListView):
# model = Fossil
context_object_name = 'fossil'
def get_queryset(self):
"""Return a list of fossils """
fossil = Fossil.objects.filter(classification_status='accepted')
return fossil
class PrimateListView(generic.ListView):
# model = Primate
context_object_name = 'primate'
def get_queryset(self):
"""Return a list of primates """
primate = Primate.objects.filter(classification_status='accepted')
return primate
class FossilDetailView(generic.DetailView):
model = Fossil
class PrimateDetailView(generic.DetailView):
model = Primate
| en | 0.738418 | # model = Fossil Return a list of fossils # model = Primate Return a list of primates | 2.351013 | 2 |
parallel.py | qiushi-liu/strategies_in_metrology | 0 | 6616124 | <gh_stars>0
# construct the problem of QFI for parallel strategies
from comb import *
# N_phis_re/N_phis_im: the real/imaginary part of N_phis, where N_phis is a list of vectors in the ensemble decomposition
# N_phis_re/N_phis_im: the real/imaginary part of dN_phis, where dN_phis is the derivative of N_phis
# dims: a list of integers, containing the dimension of each subsystem, from d_2N to d_1
# N_steps: the number of steps
def Prob_CombQFI_par(N_phis_re, N_phis_im, dN_phis_re, dN_phis_im, dims, N_steps):
N_phis = [N_phis_re[i] + 1j * N_phis_im[i] for i in range(len(N_phis_re))]
dN_phis = [dN_phis_re[i] + 1j * dN_phis_im[i] for i in range(len(dN_phis_re))]
# variables to be optimized
dim_h = len(N_phis)
h = cp.Variable((dim_h, dim_h), hermitian=True)
lambda0 = cp.Variable()
#construct the non-diagonal block of matrix A
block_N_phis = cp.hstack(N_phis)
block_dN_phis = cp.hstack(dN_phis)
block = cp.conj(block_dN_phis - 1j * block_N_phis @ h) # block @ block.H: peformance operator from an equivalent ensemble decomposition of N_phis
# choose an orthornormal basis of tensor product of (H_2N,...,H4,H_2) and construct n_i,j
dim_out = np.prod(dims[::2])
dim_in = np.prod(dims[1::2])
ns = []
for i in range(dim_h):
for j in range(dim_out):
item = [0]*(N_steps - len(numberToBase(j, dims[0]))) + numberToBase(j, dims[0])
ket_j = np.kron(basis_state(dims[0], item[0]), np.eye(2))
if N_steps == 1:
ns.append(np.conj(ket_j).T @ cp.reshape(block[:,i], (block.shape[0],1)))
else:
for k in range(1, N_steps):
ket_j = np.kron(ket_j, np.kron(basis_state(dims[2*k], item[k]), np.eye(2)))
ns.append(np.conj(ket_j).T @ cp.reshape(block[:,i], (block.shape[0],1)))
block_ns = cp.hstack(ns)
# objective
obj = cp.Minimize(lambda0)
# constraints
constraints = [cp.bmat([[1/4*lambda0*np.eye(dim_h*dim_out), block_ns.H], [block_ns, np.eye(dim_in)]]) >> 0]
# problem
prob = cp.Problem(obj, constraints)
return prob | # construct the problem of QFI for parallel strategies
from comb import *
# N_phis_re/N_phis_im: the real/imaginary part of N_phis, where N_phis is a list of vectors in the ensemble decomposition
# N_phis_re/N_phis_im: the real/imaginary part of dN_phis, where dN_phis is the derivative of N_phis
# dims: a list of integers, containing the dimension of each subsystem, from d_2N to d_1
# N_steps: the number of steps
def Prob_CombQFI_par(N_phis_re, N_phis_im, dN_phis_re, dN_phis_im, dims, N_steps):
N_phis = [N_phis_re[i] + 1j * N_phis_im[i] for i in range(len(N_phis_re))]
dN_phis = [dN_phis_re[i] + 1j * dN_phis_im[i] for i in range(len(dN_phis_re))]
# variables to be optimized
dim_h = len(N_phis)
h = cp.Variable((dim_h, dim_h), hermitian=True)
lambda0 = cp.Variable()
#construct the non-diagonal block of matrix A
block_N_phis = cp.hstack(N_phis)
block_dN_phis = cp.hstack(dN_phis)
block = cp.conj(block_dN_phis - 1j * block_N_phis @ h) # block @ block.H: peformance operator from an equivalent ensemble decomposition of N_phis
# choose an orthornormal basis of tensor product of (H_2N,...,H4,H_2) and construct n_i,j
dim_out = np.prod(dims[::2])
dim_in = np.prod(dims[1::2])
ns = []
for i in range(dim_h):
for j in range(dim_out):
item = [0]*(N_steps - len(numberToBase(j, dims[0]))) + numberToBase(j, dims[0])
ket_j = np.kron(basis_state(dims[0], item[0]), np.eye(2))
if N_steps == 1:
ns.append(np.conj(ket_j).T @ cp.reshape(block[:,i], (block.shape[0],1)))
else:
for k in range(1, N_steps):
ket_j = np.kron(ket_j, np.kron(basis_state(dims[2*k], item[k]), np.eye(2)))
ns.append(np.conj(ket_j).T @ cp.reshape(block[:,i], (block.shape[0],1)))
block_ns = cp.hstack(ns)
# objective
obj = cp.Minimize(lambda0)
# constraints
constraints = [cp.bmat([[1/4*lambda0*np.eye(dim_h*dim_out), block_ns.H], [block_ns, np.eye(dim_in)]]) >> 0]
# problem
prob = cp.Problem(obj, constraints)
return prob | en | 0.818201 | # construct the problem of QFI for parallel strategies # N_phis_re/N_phis_im: the real/imaginary part of N_phis, where N_phis is a list of vectors in the ensemble decomposition # N_phis_re/N_phis_im: the real/imaginary part of dN_phis, where dN_phis is the derivative of N_phis # dims: a list of integers, containing the dimension of each subsystem, from d_2N to d_1 # N_steps: the number of steps # variables to be optimized #construct the non-diagonal block of matrix A # block @ block.H: peformance operator from an equivalent ensemble decomposition of N_phis # choose an orthornormal basis of tensor product of (H_2N,...,H4,H_2) and construct n_i,j # objective # constraints # problem | 2.282394 | 2 |
content/test/faceswap/plugins/convert/mask/mask_blend.py | gwdgithubnom/gjgr | 3 | 6616125 | #!/usr/bin/env python3
""" Adjustments for the mask for faceswap.py converter """
import cv2
import numpy as np
from lib.model import masks as model_masks
from ._base import Adjustment, BlurMask, logger
class Mask(Adjustment):
""" Return the requested mask """
def __init__(self, mask_type, output_size, predicted_available, **kwargs):
super().__init__(mask_type, output_size, predicted_available, **kwargs)
self.do_erode = self.config.get("erosion", 0) != 0
self.do_blend = self.config.get("type", None) is not None
def process(self, detected_face, predicted_mask=None):
""" Return mask and perform processing """
mask = self.get_mask(detected_face, predicted_mask)
raw_mask = mask.copy()
if not self.skip and self.do_erode:
mask = self.erode(mask)
if not self.skip and self.do_blend:
mask = self.blend(mask)
raw_mask = np.expand_dims(raw_mask, axis=-1) if raw_mask.ndim != 3 else raw_mask
mask = np.expand_dims(mask, axis=-1) if mask.ndim != 3 else mask
logger.trace("mask shape: %s, raw_mask shape: %s", mask.shape, raw_mask.shape)
return mask, raw_mask
def get_mask(self, detected_face, predicted_mask):
""" Return the mask from lib/model/masks and intersect with box """
if self.mask_type == "none":
# Return a dummy mask if not using a mask
mask = np.ones_like(self.dummy[:, :, 1])
elif self.mask_type == "predicted":
mask = predicted_mask
else:
landmarks = detected_face.reference_landmarks
mask = getattr(model_masks, self.mask_type)(landmarks, self.dummy, channels=1).mask
np.nan_to_num(mask, copy=False)
np.clip(mask, 0.0, 1.0, out=mask)
return mask
# MASK MANIPULATIONS
def erode(self, mask):
""" Erode/dilate mask if requested """
kernel = self.get_erosion_kernel(mask)
if self.config["erosion"] > 0:
logger.trace("Eroding mask")
mask = cv2.erode(mask, kernel, iterations=1) # pylint: disable=no-member
else:
logger.trace("Dilating mask")
mask = cv2.dilate(mask, kernel, iterations=1) # pylint: disable=no-member
return mask
def get_erosion_kernel(self, mask):
""" Get the erosion kernel """
erosion_ratio = self.config["erosion"] / 100
mask_radius = np.sqrt(np.sum(mask)) / 2
kernel_size = max(1, int(abs(erosion_ratio * mask_radius)))
erosion_kernel = cv2.getStructuringElement( # pylint: disable=no-member
cv2.MORPH_ELLIPSE, # pylint: disable=no-member
(kernel_size, kernel_size))
logger.trace("erosion_kernel shape: %s", erosion_kernel.shape)
return erosion_kernel
def blend(self, mask):
""" Blur mask if requested """
logger.trace("Blending mask")
mask = BlurMask(self.config["type"],
mask,
self.config["radius"],
self.config["passes"]).blurred
return mask
| #!/usr/bin/env python3
""" Adjustments for the mask for faceswap.py converter """
import cv2
import numpy as np
from lib.model import masks as model_masks
from ._base import Adjustment, BlurMask, logger
class Mask(Adjustment):
""" Return the requested mask """
def __init__(self, mask_type, output_size, predicted_available, **kwargs):
super().__init__(mask_type, output_size, predicted_available, **kwargs)
self.do_erode = self.config.get("erosion", 0) != 0
self.do_blend = self.config.get("type", None) is not None
def process(self, detected_face, predicted_mask=None):
""" Return mask and perform processing """
mask = self.get_mask(detected_face, predicted_mask)
raw_mask = mask.copy()
if not self.skip and self.do_erode:
mask = self.erode(mask)
if not self.skip and self.do_blend:
mask = self.blend(mask)
raw_mask = np.expand_dims(raw_mask, axis=-1) if raw_mask.ndim != 3 else raw_mask
mask = np.expand_dims(mask, axis=-1) if mask.ndim != 3 else mask
logger.trace("mask shape: %s, raw_mask shape: %s", mask.shape, raw_mask.shape)
return mask, raw_mask
def get_mask(self, detected_face, predicted_mask):
""" Return the mask from lib/model/masks and intersect with box """
if self.mask_type == "none":
# Return a dummy mask if not using a mask
mask = np.ones_like(self.dummy[:, :, 1])
elif self.mask_type == "predicted":
mask = predicted_mask
else:
landmarks = detected_face.reference_landmarks
mask = getattr(model_masks, self.mask_type)(landmarks, self.dummy, channels=1).mask
np.nan_to_num(mask, copy=False)
np.clip(mask, 0.0, 1.0, out=mask)
return mask
# MASK MANIPULATIONS
def erode(self, mask):
""" Erode/dilate mask if requested """
kernel = self.get_erosion_kernel(mask)
if self.config["erosion"] > 0:
logger.trace("Eroding mask")
mask = cv2.erode(mask, kernel, iterations=1) # pylint: disable=no-member
else:
logger.trace("Dilating mask")
mask = cv2.dilate(mask, kernel, iterations=1) # pylint: disable=no-member
return mask
def get_erosion_kernel(self, mask):
""" Get the erosion kernel """
erosion_ratio = self.config["erosion"] / 100
mask_radius = np.sqrt(np.sum(mask)) / 2
kernel_size = max(1, int(abs(erosion_ratio * mask_radius)))
erosion_kernel = cv2.getStructuringElement( # pylint: disable=no-member
cv2.MORPH_ELLIPSE, # pylint: disable=no-member
(kernel_size, kernel_size))
logger.trace("erosion_kernel shape: %s", erosion_kernel.shape)
return erosion_kernel
def blend(self, mask):
""" Blur mask if requested """
logger.trace("Blending mask")
mask = BlurMask(self.config["type"],
mask,
self.config["radius"],
self.config["passes"]).blurred
return mask
| en | 0.599571 | #!/usr/bin/env python3 Adjustments for the mask for faceswap.py converter Return the requested mask Return mask and perform processing Return the mask from lib/model/masks and intersect with box # Return a dummy mask if not using a mask # MASK MANIPULATIONS Erode/dilate mask if requested # pylint: disable=no-member # pylint: disable=no-member Get the erosion kernel # pylint: disable=no-member # pylint: disable=no-member Blur mask if requested | 2.512941 | 3 |
src/chessGame/server.py | DNSLV-PMTKV/chessGame | 1 | 6616126 | import socket
from _thread import *
from board import Board
import pickle
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = '127.0.0.1'
port = 4444
try:
s.bind((server, port))
except socket.error as e:
print(str(e))
s.listen(2)
print('Waiting connection')
board = Board()
connections = 0
currentID = 'white'
def thread_client(conn):
global connections, currentID, board
# var = board
board.start_user = currentID
data_string = pickle.dumps(board)
if currentID == 'black':
board.players = True
conn.send(data_string)
currentID = 'black'
connections += 1
if connections == 2:
conn.send(data_string)
while True:
data = conn.recv(1024)
data = data.decode()
data_split = data.split()
if not data:
break
# data = data.decode().split()
print(data)
if 'select' in data_split:
board.click(int(data_split[1]), int(data_split[2]))
if data == 'winner b':
board.winner = 'black'
if data == 'winner w':
board.winner = 'white'
sendData = pickle.dumps(board)
# print("Sending {}".format(sendData))
conn.sendall(sendData)
connections -= 1
if connections < 2:
board = Board()
currentID = "white"
print("Connection Closed")
conn.close()
# print(pickle.dumps(board))
while True:
conn, addr = s.accept()
print("Connected to: ", addr)
start_new_thread(thread_client, (conn,))
| import socket
from _thread import *
from board import Board
import pickle
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = '127.0.0.1'
port = 4444
try:
s.bind((server, port))
except socket.error as e:
print(str(e))
s.listen(2)
print('Waiting connection')
board = Board()
connections = 0
currentID = 'white'
def thread_client(conn):
global connections, currentID, board
# var = board
board.start_user = currentID
data_string = pickle.dumps(board)
if currentID == 'black':
board.players = True
conn.send(data_string)
currentID = 'black'
connections += 1
if connections == 2:
conn.send(data_string)
while True:
data = conn.recv(1024)
data = data.decode()
data_split = data.split()
if not data:
break
# data = data.decode().split()
print(data)
if 'select' in data_split:
board.click(int(data_split[1]), int(data_split[2]))
if data == 'winner b':
board.winner = 'black'
if data == 'winner w':
board.winner = 'white'
sendData = pickle.dumps(board)
# print("Sending {}".format(sendData))
conn.sendall(sendData)
connections -= 1
if connections < 2:
board = Board()
currentID = "white"
print("Connection Closed")
conn.close()
# print(pickle.dumps(board))
while True:
conn, addr = s.accept()
print("Connected to: ", addr)
start_new_thread(thread_client, (conn,))
| en | 0.262511 | # var = board # data = data.decode().split() # print("Sending {}".format(sendData)) # print(pickle.dumps(board)) | 2.91533 | 3 |
bot/plugins/help.py | Kolkies/captain | 13 | 6616127 | import menus
import core.prefix as prefix
from discord import Embed
from discord.ext import commands
from ext.exceptions import LookupFailed
from ext.state import access_control
from ext.utils import time_since
class CommandSet:
def __init__(self, container):
self.container = container
@property
def commands(self):
if isinstance(self.container, commands.Group):
command_list = list(self.container.commands)
command_list.insert(0, self.container)
return command_list
if isinstance(self.container, commands.Command):
return self.container,
return self.container.get_commands()
@property
def description(self):
return self.container.description
@property
def name(self):
if isinstance(self.container, commands.Cog):
return self.container.qualified_name
return self.container.name.title()
class Plugin(commands.Cog, command_attrs=dict(hidden=True)):
def __init__(self, bot):
self.bot = bot
class HelpSource(menus.GroupByPageSource):
def __init__(self, command_sets, help_usage):
self.help_usage = help_usage
super().__init__(
entries=command_sets,
per_page=1,
key=None,
sort=False
)
async def format_page(self, menu, entry):
command_set = entry.items[0]
embed = Embed(
colour=0x7289DA,
title=command_set.name,
description=command_set.description
)
embed.set_author(name=f"Page {menu.current_page + 1}/{self.get_max_pages()} ({len(command_set.commands)} commands)")
embed.set_footer(text=f"Use {prefix.default}{self.help_usage} for more help.")
for command in command_set.commands:
description = command.short_doc
if hasattr(command.callback, "__commands_cooldown__"):
cooldown = command.callback.__commands_cooldown__
cooldown_type = {
commands.BucketType.default: "at any time",
commands.BucketType.user: "per user",
commands.BucketType.channel: "per channel",
commands.BucketType.guild: "per server",
commands.BucketType.category: "per channel category",
commands.BucketType.member: "per server member",
commands.BucketType.role: "per server role",
}[cooldown.type]
description += f"\n\n**Cooldown: {cooldown.rate} every {time_since(seconds=cooldown.per)} {cooldown_type}**"
if isinstance(command, commands.Group):
description += f"\n\n*Use **{prefix.default}help {command.name}** for a list of subcommands.*"
embed.add_field(
name=command.usage,
value=description,
inline=False
)
return embed
class HelpMenu(menus.MenuPages):
def __init__(self, source):
super().__init__(
source=source,
clear_reactions_after=True
)
@access_control.require(access_control.Level.DEFAULT)
@commands.command("help",
usage="help [command|category:text]",
aliases=["commands"]
)
async def help(self, ctx, *, command_lookup: str = None):
command_sets = []
if command_lookup is None:
for cog in self.bot.cogs.values():
cog_commands = [command for command in cog.get_commands() if not command.hidden]
if not cog_commands:
continue
command_sets.append(CommandSet(cog))
else:
found = self.bot.get_command(command_lookup)
if found is None:
raise LookupFailed("commands")
command_sets.append(CommandSet(found))
await self.HelpMenu(self.HelpSource(command_sets, ctx.command.usage)).start(ctx)
def setup(bot):
bot.remove_command("help")
bot.add_cog(Plugin(bot)) | import menus
import core.prefix as prefix
from discord import Embed
from discord.ext import commands
from ext.exceptions import LookupFailed
from ext.state import access_control
from ext.utils import time_since
class CommandSet:
def __init__(self, container):
self.container = container
@property
def commands(self):
if isinstance(self.container, commands.Group):
command_list = list(self.container.commands)
command_list.insert(0, self.container)
return command_list
if isinstance(self.container, commands.Command):
return self.container,
return self.container.get_commands()
@property
def description(self):
return self.container.description
@property
def name(self):
if isinstance(self.container, commands.Cog):
return self.container.qualified_name
return self.container.name.title()
class Plugin(commands.Cog, command_attrs=dict(hidden=True)):
def __init__(self, bot):
self.bot = bot
class HelpSource(menus.GroupByPageSource):
def __init__(self, command_sets, help_usage):
self.help_usage = help_usage
super().__init__(
entries=command_sets,
per_page=1,
key=None,
sort=False
)
async def format_page(self, menu, entry):
command_set = entry.items[0]
embed = Embed(
colour=0x7289DA,
title=command_set.name,
description=command_set.description
)
embed.set_author(name=f"Page {menu.current_page + 1}/{self.get_max_pages()} ({len(command_set.commands)} commands)")
embed.set_footer(text=f"Use {prefix.default}{self.help_usage} for more help.")
for command in command_set.commands:
description = command.short_doc
if hasattr(command.callback, "__commands_cooldown__"):
cooldown = command.callback.__commands_cooldown__
cooldown_type = {
commands.BucketType.default: "at any time",
commands.BucketType.user: "per user",
commands.BucketType.channel: "per channel",
commands.BucketType.guild: "per server",
commands.BucketType.category: "per channel category",
commands.BucketType.member: "per server member",
commands.BucketType.role: "per server role",
}[cooldown.type]
description += f"\n\n**Cooldown: {cooldown.rate} every {time_since(seconds=cooldown.per)} {cooldown_type}**"
if isinstance(command, commands.Group):
description += f"\n\n*Use **{prefix.default}help {command.name}** for a list of subcommands.*"
embed.add_field(
name=command.usage,
value=description,
inline=False
)
return embed
class HelpMenu(menus.MenuPages):
def __init__(self, source):
super().__init__(
source=source,
clear_reactions_after=True
)
@access_control.require(access_control.Level.DEFAULT)
@commands.command("help",
usage="help [command|category:text]",
aliases=["commands"]
)
async def help(self, ctx, *, command_lookup: str = None):
command_sets = []
if command_lookup is None:
for cog in self.bot.cogs.values():
cog_commands = [command for command in cog.get_commands() if not command.hidden]
if not cog_commands:
continue
command_sets.append(CommandSet(cog))
else:
found = self.bot.get_command(command_lookup)
if found is None:
raise LookupFailed("commands")
command_sets.append(CommandSet(found))
await self.HelpMenu(self.HelpSource(command_sets, ctx.command.usage)).start(ctx)
def setup(bot):
bot.remove_command("help")
bot.add_cog(Plugin(bot)) | none | 1 | 2.271251 | 2 | |
naredi_tabele.py | ursa16180/HarryPotter | 0 | 6616128 | <filename>naredi_tabele.py
# uvozimo ustrezne podatke za povezavo
import auth
# uvozimo psycopg2
import psycopg2, psycopg2.extensions, psycopg2.extras
import csv
import hashlib
from delamo_csv_zanr import zanri_za_popravit
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) # se znebimo problemov s šumniki
def ustvari_tabelo(seznam):
cur.execute(seznam[1])
print("Narejena tabela %s" % seznam[0])
conn.commit()
def zakodiraj_geslo(geslo):
hashko = hashlib.md5()
hashko.update(geslo.encode('utf-8'))
return hashko.hexdigest()
def daj_pravice():
cur.execute("GRANT CONNECT ON DATABASE sem2018_ursap TO javnost;"
"GRANT USAGE ON SCHEMA public TO javnost;"
"GRANT SELECT ON ALL TABLES IN SCHEMA public TO javnost;"
"GRANT UPDATE, INSERT, DELETE ON uporabnik, wishlist, prebrana_knjiga TO javnost;"
"GRANT UPDATE(vsota_ocen, stevilo_ocen) ON knjiga TO javnost;"
"GRANT ALL ON SEQUENCE uporabnik_id_seq TO javnost;"
"GRANT ALL ON SCHEMA public TO ursap; "
"GRANT ALL ON SCHEMA public TO ninast;"
"GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO ursap;"
"GRANT ALL ON ALL TABLES IN SCHEMA public TO ursap;"
"GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO ninast;"
"GRANT ALL ON ALL TABLES IN SCHEMA public TO ninast;")
print("Dodane pravice")
conn.commit()
def pobrisi_tabelo(seznam):
cur.execute("""
DROP TABLE %s CASCADE;
""" % seznam[0])
print("Izbrisna tabela %s" % seznam[0])
conn.commit()
def izprazni_tabelo(seznam):
cur.execute("""
DELETE FROM %s;
""" % seznam[0])
print("Izpraznjena tabela %s" % seznam[0])
conn.commit()
def uvozi_podatke(seznam):
if seznam[0] in ["zanr_knjige", "avtorjev_zanr"]:
popravi_zanre("podatki/%s.csv" % seznam[0])
if seznam[0] in ['knjiga', 'avtor', 'zanr', 'serija', 'del_serije', 'avtor_knjige', 'zanr_knjige', 'avtorjev_zanr',
'knjiga_kljucne_besede']:
izbrisi_podovojene_vrstice("podatki/%s.csv" % seznam[0])
with open("podatki/%s.csv" % seznam[0], encoding="utf8") as f:
rd = csv.reader(f, delimiter=';')
print("berem")
next(rd)
for r in rd:
print(r)
r = [None if x in ('', '-') else x for x in r]
cur.execute(seznam[2], r)
rid, = cur.fetchone()
print("Uvožen/a %s" % (r[0]))
conn.commit()
def izbrisi_podovojene_vrstice(datoteka):
vse_razlice_vrstice = set()
seznam_vrstic = []
for vrstica in open(datoteka, "r", encoding="utf8"):
if vrstica not in vse_razlice_vrstice and vrstica != 'Abandoned;\n':
seznam_vrstic.append(vrstica)
vse_razlice_vrstice.add(vrstica)
izhodna_datoteka = open(datoteka, "w", encoding="utf8")
for vrstica in seznam_vrstic:
izhodna_datoteka.write(vrstica)
izhodna_datoteka.close()
def popravi_zanre(ime_datoteke):
seznam_vrstic = []
slovar_napacnih = {'Children\'s Books': 'Childrens', 'Comics & Graphic Novels': 'Comics',
'Children\'s': 'Childrens', 'Arts & Photography': 'Art',
'Literature & Fiction': 'Fiction', 'Mystery & Thrillers': 'Mystery Thrillers',
'Science Fiction & Fantasy': 'Science Fiction', 'Biographies & Memoirs': 'Biography',
'Screenplays & Plays': 'Plays', 'Ya Fantasy': 'Young Adult Fantasy',
'Humor and Comedy': 'Humor', 'Gay and Lesbian': 'Lgbt', 'North American Hi...': 'Historical',
'Religion & Spirituality': 'Spirituality', 'Mystery & Thriller': 'Mystery Thriller',
'Young Adult Paranormal & Fantasy': 'Young Adult Paranormal Fantasy',
'Health, Mind & Body': 'Health', 'Glbt': 'Lgbt', 'Kids': 'Childrens',
'Sci Fi Fantasy': 'Science Fiction', 'Crafts & Hobbies': 'Crafts Hobbies',
'Business & Investing': 'Business Investing', 'Gay & Lesbian': 'Lgbt', 'Teen Fiction': 'Teen',
'Professional & Technical': 'Professional Technical', 'Social Sciences': 'Sociology',
'Computers & Internet': 'Computers Internet', 'Fantasy, Magic, Adventure': 'Magic',
'Cooking, Food & Wine': 'Cookbooks', 'Dystopian': 'Dystopia', 'Fanfiction': 'Fan Fiction',
'Women & Gender Studies': 'Women Gender Studies', 'Audiobooks': '',
'Parenting & Families': 'Family', 'Outdoors & Nature': 'Outdoors Nature',
'Fantasy & Science Fiction': 'Science Fiction', 'Children\'s, Young Adult': 'Childrens',
'Humor & Satire': 'Humor', 'Writing & Creativity': 'Writing', 'Academic': 'School Stories',
'School': 'School Stories', 'Education': 'School Stories'}
slovar_napacnih.update(zanri_za_popravit)
with open(ime_datoteke, 'r') as moj_csv:
bralec_csvja = csv.reader(moj_csv, delimiter=';')
for vrstica in bralec_csvja:
if vrstica[1] in ['Aboriginal Astronomy', ''] or slovar_napacnih.get(vrstica[1], 'nič') == '':
continue
if vrstica[1] in slovar_napacnih.keys():
seznam_vrstic.append(vrstica[0] + ";" + slovar_napacnih[vrstica[1]] + '\n')
else:
seznam_vrstic.append(vrstica[0] + ";" + vrstica[1] + '\n')
moj_csv.close()
izhodna_datoteka = open(ime_datoteke, "w", encoding="utf8")
for vrstica in seznam_vrstic:
izhodna_datoteka.write(vrstica)
izhodna_datoteka.close()
conn = psycopg2.connect(database=auth.db, host=auth.host, user=auth.user, password=<PASSWORD>)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
# 884288 nima opisa, zato not null ni več pri opisu
knjiga = ["knjiga",
"""
CREATE TABLE knjiga (
id INTEGER PRIMARY KEY,
ISBN TEXT,
naslov TEXT NOT NULL,
dolzina INTEGER,
povprecna_ocena FLOAT,
stevilo_ocen INTEGER,
leto INTEGER,
opis TEXT,
url_naslovnice TEXT
);
""",
"""
INSERT INTO knjiga
(id, ISBN, naslov, dolzina, povprecna_ocena, stevilo_ocen, leto, opis, url_naslovnice)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
"""]
avtor = ["avtor",
"""
CREATE TABLE avtor (
id INTEGER PRIMARY KEY,
ime TEXT NOT NULL,
povprecna_ocena FLOAT,
datum_rojstva DATE,
kraj_rojstva TEXT
);
""",
"""
INSERT INTO avtor
(id, ime, povprecna_ocena, datum_rojstva, kraj_rojstva)
VALUES (%s, %s, %s, %s, %s)
RETURNING id
"""]
serija = ["serija",
"""CREATE TABLE serija (id INTEGER PRIMARY KEY, ime TEXT NOT NULL, stevilo_knjig INTEGER NOT NULL);""",
"""INSERT INTO serija (id, ime, stevilo_knjig) VALUES (%s, %s, %s) RETURNING id"""]
# Arts Photography, null ---> zato opis lahko null
zanr = ["zanr",
"""
CREATE TABLE zanr (
ime_zanra TEXT PRIMARY KEY,
opis TEXT
);
""",
"""
INSERT INTO zanr
(ime_zanra, opis)
VALUES (%s, %s)
RETURNING ime_zanra
"""]
del_serije = ["del_serije",
"""
CREATE TABLE del_serije (
id_knjige INTEGER NOT NULL REFERENCES knjiga(id),
id_serije INTEGER NOT NULL REFERENCES serija(id),
zaporedna_stevilka_serije INTEGER,
PRIMARY KEY (id_serije, id_knjige)
);
""",
"""
INSERT INTO del_serije
(id_knjige, id_serije, zaporedna_stevilka_serije)
VALUES (%s, %s, %s)
RETURNING id_serije
"""]
avtor_knjige = ["avtor_knjige",
"""
CREATE TABLE avtor_knjige (
id_knjige INTEGER NOT NULL REFERENCES knjiga(id),
id_avtorja INTEGER NOT NULL REFERENCES avtor(id),
PRIMARY KEY (id_avtorja, id_knjige)
);
""", """
INSERT INTO avtor_knjige
(id_knjige, id_avtorja)
VALUES (%s, %s)
RETURNING (id_knjige, id_avtorja)
"""]
zanr_knjige = ["zanr_knjige",
"""
CREATE TABLE zanr_knjige (
id_knjige INTEGER NOT NULL REFERENCES knjiga(id),
zanr TEXT NOT NULL REFERENCES zanr(ime_zanra),
PRIMARY KEY (id_knjige, zanr)
);
""", """
INSERT INTO zanr_knjige
(id_knjige, zanr)
VALUES (%s, %s)
RETURNING (id_knjige, zanr)
"""]
avtorjev_zanr = ["avtorjev_zanr",
"""
CREATE TABLE avtorjev_zanr (
id_avtorja INTEGER NOT NULL REFERENCES avtor(id),
zanr TEXT NOT NULL REFERENCES zanr(ime_zanra),
PRIMARY KEY (id_avtorja, zanr)
);
""", """
INSERT INTO avtorjev_zanr
(id_avtorja, zanr)
VALUES (%s, %s)
RETURNING (id_avtorja, zanr)
"""]
kljucna_beseda = ["kljucna_beseda",
"""
CREATE TABLE kljucna_beseda (
pojem TEXT PRIMARY KEY,
skupina TEXT NOT NULL
);
""", """
INSERT INTO kljucna_beseda
(pojem, skupina)
VALUES (%s, %s)
RETURNING (pojem)
"""]
knjiga_kljucne_besede = ["knjiga_kljucne_besede",
"""
CREATE TABLE knjiga_kljucne_besede (
id_knjige INTEGER NOT NULL REFERENCES knjiga(id),
kljucna_beseda TEXT NOT NULL REFERENCES kljucna_beseda(pojem),
PRIMARY KEY (id_knjige, kljucna_beseda)
);
""", """
INSERT INTO knjiga_kljucne_besede
(id_knjige, kljucna_beseda)
VALUES (%s, %s)
RETURNING (id_knjige, kljucna_beseda)
"""]
# daj_pravice()
# for x in [knjiga_kljucne_besede]:
# izprazni_tabelo(x)
# for x in [ knjiga_kljucne_besede]:
# #ustvari_tabelo(x)
# uvozi_podatke(x)
# uvozi_podatke(knjiga_kljucne_besede)
# ustvari_vse_tabele()
# uvozi_vse_podatke()
# izbrisi_podovojene_vrstice('podatki/zanr.csv')
# ~~~~~~~~~~~~~~~~~~~~~~~~~UPORABNIKI
uporabnik = ['uporabnik',
# CREATE TYPE spol AS ENUM('Female', 'Male');
# CREATE TYPE dom AS ENUM('Gryffindor', 'Slytherin', 'Hufflepuff', 'Ravenclaw');
"""
CREATE TABLE uporabnik (
id SERIAL PRIMARY KEY,
vzdevek TEXT NOT NULL UNIQUE,
geslo TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
dom dom NOT NULL,
spol spol NOT NULL
);
""", """
INSERT INTO uporabnik
(id, vzdevek, geslo, email, dom, spol)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING (id_uporabnika)
"""
]
wishlist = ['wishlist',
"""
CREATE TABLE wishlist (
id_uporabnika INTEGER NOT NULL REFERENCES uporabnik(id),
id_knjige INTEGER NOT NULL REFERENCES knjiga(id),
PRIMARY KEY(id_uporabnika, id_knjige)
);
""", """
INSERT INTO wishlist
(id_uporabnika, id_knjige)
VALUES (%s, %s)
RETURNING (id_uporabnika, id_knjige)
"""
]
prebrana_knjiga = ['prebrana_knjiga',
"""
CREATE TABLE prebrana_knjiga (
id_uporabnika INTEGER NOT NULL REFERENCES uporabnik(id),
id_knjige INTEGER NOT NULL REFERENCES knjiga(id),
ocena INTEGER,
PRIMARY KEY(id_uporabnika, id_knjige)
);
""", """
INSERT INTO prebrana_knjiga
(id_uporabnika, id_knjige, ocena)
VALUES (%s, %s, %s)
RETURNING (id_uporabnika, id_knjige)
"""
]
#
seznamVseh = [knjiga, avtor, zanr, serija, del_serije, avtor_knjige, zanr_knjige, avtorjev_zanr, kljucna_beseda,
knjiga_kljucne_besede, uporabnik, wishlist, prebrana_knjiga]
def ustvari_vse_tabele():
for seznam in seznamVseh:
ustvari_tabelo(seznam)
daj_pravice()
def uvozi_vse_podatke():
for seznam in seznamVseh[:-3]:
uvozi_podatke(seznam)
def izbrisi_vse_tabele():
for seznam in seznamVseh:
pobrisi_tabelo(seznam)
# daj_pravice()
# NAKNADNO DODANI SQL-stavki
# ALTER TABLE knjiga ADD vsota_ocen float;
# UPDATE knjiga SET vsota_ocen = stevilo_ocen * povprecna_ocena;
# ALTER TABLE knjiga DROP COLUMN povprecna_ocena;
# UPDATE knjiga SET stevilo_ocen = COALESCE(stevilo_ocen,0);
# UPDATE knjiga SET vsota_ocen = COALESCE(vsota_ocen,0);
| <filename>naredi_tabele.py
# uvozimo ustrezne podatke za povezavo
import auth
# uvozimo psycopg2
import psycopg2, psycopg2.extensions, psycopg2.extras
import csv
import hashlib
from delamo_csv_zanr import zanri_za_popravit
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) # se znebimo problemov s šumniki
def ustvari_tabelo(seznam):
cur.execute(seznam[1])
print("Narejena tabela %s" % seznam[0])
conn.commit()
def zakodiraj_geslo(geslo):
hashko = hashlib.md5()
hashko.update(geslo.encode('utf-8'))
return hashko.hexdigest()
def daj_pravice():
cur.execute("GRANT CONNECT ON DATABASE sem2018_ursap TO javnost;"
"GRANT USAGE ON SCHEMA public TO javnost;"
"GRANT SELECT ON ALL TABLES IN SCHEMA public TO javnost;"
"GRANT UPDATE, INSERT, DELETE ON uporabnik, wishlist, prebrana_knjiga TO javnost;"
"GRANT UPDATE(vsota_ocen, stevilo_ocen) ON knjiga TO javnost;"
"GRANT ALL ON SEQUENCE uporabnik_id_seq TO javnost;"
"GRANT ALL ON SCHEMA public TO ursap; "
"GRANT ALL ON SCHEMA public TO ninast;"
"GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO ursap;"
"GRANT ALL ON ALL TABLES IN SCHEMA public TO ursap;"
"GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO ninast;"
"GRANT ALL ON ALL TABLES IN SCHEMA public TO ninast;")
print("Dodane pravice")
conn.commit()
def pobrisi_tabelo(seznam):
cur.execute("""
DROP TABLE %s CASCADE;
""" % seznam[0])
print("Izbrisna tabela %s" % seznam[0])
conn.commit()
def izprazni_tabelo(seznam):
cur.execute("""
DELETE FROM %s;
""" % seznam[0])
print("Izpraznjena tabela %s" % seznam[0])
conn.commit()
def uvozi_podatke(seznam):
if seznam[0] in ["zanr_knjige", "avtorjev_zanr"]:
popravi_zanre("podatki/%s.csv" % seznam[0])
if seznam[0] in ['knjiga', 'avtor', 'zanr', 'serija', 'del_serije', 'avtor_knjige', 'zanr_knjige', 'avtorjev_zanr',
'knjiga_kljucne_besede']:
izbrisi_podovojene_vrstice("podatki/%s.csv" % seznam[0])
with open("podatki/%s.csv" % seznam[0], encoding="utf8") as f:
rd = csv.reader(f, delimiter=';')
print("berem")
next(rd)
for r in rd:
print(r)
r = [None if x in ('', '-') else x for x in r]
cur.execute(seznam[2], r)
rid, = cur.fetchone()
print("Uvožen/a %s" % (r[0]))
conn.commit()
def izbrisi_podovojene_vrstice(datoteka):
vse_razlice_vrstice = set()
seznam_vrstic = []
for vrstica in open(datoteka, "r", encoding="utf8"):
if vrstica not in vse_razlice_vrstice and vrstica != 'Abandoned;\n':
seznam_vrstic.append(vrstica)
vse_razlice_vrstice.add(vrstica)
izhodna_datoteka = open(datoteka, "w", encoding="utf8")
for vrstica in seznam_vrstic:
izhodna_datoteka.write(vrstica)
izhodna_datoteka.close()
def popravi_zanre(ime_datoteke):
seznam_vrstic = []
slovar_napacnih = {'Children\'s Books': 'Childrens', 'Comics & Graphic Novels': 'Comics',
'Children\'s': 'Childrens', 'Arts & Photography': 'Art',
'Literature & Fiction': 'Fiction', 'Mystery & Thrillers': 'Mystery Thrillers',
'Science Fiction & Fantasy': 'Science Fiction', 'Biographies & Memoirs': 'Biography',
'Screenplays & Plays': 'Plays', 'Ya Fantasy': 'Young Adult Fantasy',
'Humor and Comedy': 'Humor', 'Gay and Lesbian': 'Lgbt', 'North American Hi...': 'Historical',
'Religion & Spirituality': 'Spirituality', 'Mystery & Thriller': 'Mystery Thriller',
'Young Adult Paranormal & Fantasy': 'Young Adult Paranormal Fantasy',
'Health, Mind & Body': 'Health', 'Glbt': 'Lgbt', 'Kids': 'Childrens',
'Sci Fi Fantasy': 'Science Fiction', 'Crafts & Hobbies': 'Crafts Hobbies',
'Business & Investing': 'Business Investing', 'Gay & Lesbian': 'Lgbt', 'Teen Fiction': 'Teen',
'Professional & Technical': 'Professional Technical', 'Social Sciences': 'Sociology',
'Computers & Internet': 'Computers Internet', 'Fantasy, Magic, Adventure': 'Magic',
'Cooking, Food & Wine': 'Cookbooks', 'Dystopian': 'Dystopia', 'Fanfiction': 'Fan Fiction',
'Women & Gender Studies': 'Women Gender Studies', 'Audiobooks': '',
'Parenting & Families': 'Family', 'Outdoors & Nature': 'Outdoors Nature',
'Fantasy & Science Fiction': 'Science Fiction', 'Children\'s, Young Adult': 'Childrens',
'Humor & Satire': 'Humor', 'Writing & Creativity': 'Writing', 'Academic': 'School Stories',
'School': 'School Stories', 'Education': 'School Stories'}
slovar_napacnih.update(zanri_za_popravit)
with open(ime_datoteke, 'r') as moj_csv:
bralec_csvja = csv.reader(moj_csv, delimiter=';')
for vrstica in bralec_csvja:
if vrstica[1] in ['Aboriginal Astronomy', ''] or slovar_napacnih.get(vrstica[1], 'nič') == '':
continue
if vrstica[1] in slovar_napacnih.keys():
seznam_vrstic.append(vrstica[0] + ";" + slovar_napacnih[vrstica[1]] + '\n')
else:
seznam_vrstic.append(vrstica[0] + ";" + vrstica[1] + '\n')
moj_csv.close()
izhodna_datoteka = open(ime_datoteke, "w", encoding="utf8")
for vrstica in seznam_vrstic:
izhodna_datoteka.write(vrstica)
izhodna_datoteka.close()
conn = psycopg2.connect(database=auth.db, host=auth.host, user=auth.user, password=<PASSWORD>)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
# 884288 nima opisa, zato not null ni več pri opisu
knjiga = ["knjiga",
"""
CREATE TABLE knjiga (
id INTEGER PRIMARY KEY,
ISBN TEXT,
naslov TEXT NOT NULL,
dolzina INTEGER,
povprecna_ocena FLOAT,
stevilo_ocen INTEGER,
leto INTEGER,
opis TEXT,
url_naslovnice TEXT
);
""",
"""
INSERT INTO knjiga
(id, ISBN, naslov, dolzina, povprecna_ocena, stevilo_ocen, leto, opis, url_naslovnice)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
RETURNING id
"""]
avtor = ["avtor",
"""
CREATE TABLE avtor (
id INTEGER PRIMARY KEY,
ime TEXT NOT NULL,
povprecna_ocena FLOAT,
datum_rojstva DATE,
kraj_rojstva TEXT
);
""",
"""
INSERT INTO avtor
(id, ime, povprecna_ocena, datum_rojstva, kraj_rojstva)
VALUES (%s, %s, %s, %s, %s)
RETURNING id
"""]
serija = ["serija",
"""CREATE TABLE serija (id INTEGER PRIMARY KEY, ime TEXT NOT NULL, stevilo_knjig INTEGER NOT NULL);""",
"""INSERT INTO serija (id, ime, stevilo_knjig) VALUES (%s, %s, %s) RETURNING id"""]
# Arts Photography, null ---> zato opis lahko null
zanr = ["zanr",
"""
CREATE TABLE zanr (
ime_zanra TEXT PRIMARY KEY,
opis TEXT
);
""",
"""
INSERT INTO zanr
(ime_zanra, opis)
VALUES (%s, %s)
RETURNING ime_zanra
"""]
del_serije = ["del_serije",
"""
CREATE TABLE del_serije (
id_knjige INTEGER NOT NULL REFERENCES knjiga(id),
id_serije INTEGER NOT NULL REFERENCES serija(id),
zaporedna_stevilka_serije INTEGER,
PRIMARY KEY (id_serije, id_knjige)
);
""",
"""
INSERT INTO del_serije
(id_knjige, id_serije, zaporedna_stevilka_serije)
VALUES (%s, %s, %s)
RETURNING id_serije
"""]
avtor_knjige = ["avtor_knjige",
"""
CREATE TABLE avtor_knjige (
id_knjige INTEGER NOT NULL REFERENCES knjiga(id),
id_avtorja INTEGER NOT NULL REFERENCES avtor(id),
PRIMARY KEY (id_avtorja, id_knjige)
);
""", """
INSERT INTO avtor_knjige
(id_knjige, id_avtorja)
VALUES (%s, %s)
RETURNING (id_knjige, id_avtorja)
"""]
zanr_knjige = ["zanr_knjige",
"""
CREATE TABLE zanr_knjige (
id_knjige INTEGER NOT NULL REFERENCES knjiga(id),
zanr TEXT NOT NULL REFERENCES zanr(ime_zanra),
PRIMARY KEY (id_knjige, zanr)
);
""", """
INSERT INTO zanr_knjige
(id_knjige, zanr)
VALUES (%s, %s)
RETURNING (id_knjige, zanr)
"""]
avtorjev_zanr = ["avtorjev_zanr",
"""
CREATE TABLE avtorjev_zanr (
id_avtorja INTEGER NOT NULL REFERENCES avtor(id),
zanr TEXT NOT NULL REFERENCES zanr(ime_zanra),
PRIMARY KEY (id_avtorja, zanr)
);
""", """
INSERT INTO avtorjev_zanr
(id_avtorja, zanr)
VALUES (%s, %s)
RETURNING (id_avtorja, zanr)
"""]
kljucna_beseda = ["kljucna_beseda",
"""
CREATE TABLE kljucna_beseda (
pojem TEXT PRIMARY KEY,
skupina TEXT NOT NULL
);
""", """
INSERT INTO kljucna_beseda
(pojem, skupina)
VALUES (%s, %s)
RETURNING (pojem)
"""]
knjiga_kljucne_besede = ["knjiga_kljucne_besede",
"""
CREATE TABLE knjiga_kljucne_besede (
id_knjige INTEGER NOT NULL REFERENCES knjiga(id),
kljucna_beseda TEXT NOT NULL REFERENCES kljucna_beseda(pojem),
PRIMARY KEY (id_knjige, kljucna_beseda)
);
""", """
INSERT INTO knjiga_kljucne_besede
(id_knjige, kljucna_beseda)
VALUES (%s, %s)
RETURNING (id_knjige, kljucna_beseda)
"""]
# daj_pravice()
# for x in [knjiga_kljucne_besede]:
# izprazni_tabelo(x)
# for x in [ knjiga_kljucne_besede]:
# #ustvari_tabelo(x)
# uvozi_podatke(x)
# uvozi_podatke(knjiga_kljucne_besede)
# ustvari_vse_tabele()
# uvozi_vse_podatke()
# izbrisi_podovojene_vrstice('podatki/zanr.csv')
# ~~~~~~~~~~~~~~~~~~~~~~~~~UPORABNIKI
uporabnik = ['uporabnik',
# CREATE TYPE spol AS ENUM('Female', 'Male');
# CREATE TYPE dom AS ENUM('Gryffindor', 'Slytherin', 'Hufflepuff', 'Ravenclaw');
"""
CREATE TABLE uporabnik (
id SERIAL PRIMARY KEY,
vzdevek TEXT NOT NULL UNIQUE,
geslo TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
dom dom NOT NULL,
spol spol NOT NULL
);
""", """
INSERT INTO uporabnik
(id, vzdevek, geslo, email, dom, spol)
VALUES (%s, %s, %s, %s, %s, %s)
RETURNING (id_uporabnika)
"""
]
wishlist = ['wishlist',
"""
CREATE TABLE wishlist (
id_uporabnika INTEGER NOT NULL REFERENCES uporabnik(id),
id_knjige INTEGER NOT NULL REFERENCES knjiga(id),
PRIMARY KEY(id_uporabnika, id_knjige)
);
""", """
INSERT INTO wishlist
(id_uporabnika, id_knjige)
VALUES (%s, %s)
RETURNING (id_uporabnika, id_knjige)
"""
]
prebrana_knjiga = ['prebrana_knjiga',
"""
CREATE TABLE prebrana_knjiga (
id_uporabnika INTEGER NOT NULL REFERENCES uporabnik(id),
id_knjige INTEGER NOT NULL REFERENCES knjiga(id),
ocena INTEGER,
PRIMARY KEY(id_uporabnika, id_knjige)
);
""", """
INSERT INTO prebrana_knjiga
(id_uporabnika, id_knjige, ocena)
VALUES (%s, %s, %s)
RETURNING (id_uporabnika, id_knjige)
"""
]
#
seznamVseh = [knjiga, avtor, zanr, serija, del_serije, avtor_knjige, zanr_knjige, avtorjev_zanr, kljucna_beseda,
knjiga_kljucne_besede, uporabnik, wishlist, prebrana_knjiga]
def ustvari_vse_tabele():
for seznam in seznamVseh:
ustvari_tabelo(seznam)
daj_pravice()
def uvozi_vse_podatke():
for seznam in seznamVseh[:-3]:
uvozi_podatke(seznam)
def izbrisi_vse_tabele():
for seznam in seznamVseh:
pobrisi_tabelo(seznam)
# daj_pravice()
# NAKNADNO DODANI SQL-stavki
# ALTER TABLE knjiga ADD vsota_ocen float;
# UPDATE knjiga SET vsota_ocen = stevilo_ocen * povprecna_ocena;
# ALTER TABLE knjiga DROP COLUMN povprecna_ocena;
# UPDATE knjiga SET stevilo_ocen = COALESCE(stevilo_ocen,0);
# UPDATE knjiga SET vsota_ocen = COALESCE(vsota_ocen,0);
| sl | 0.274347 | # uvozimo ustrezne podatke za povezavo # uvozimo psycopg2 # se znebimo problemov s šumniki DROP TABLE %s CASCADE; DELETE FROM %s; # 884288 nima opisa, zato not null ni več pri opisu CREATE TABLE knjiga ( id INTEGER PRIMARY KEY, ISBN TEXT, naslov TEXT NOT NULL, dolzina INTEGER, povprecna_ocena FLOAT, stevilo_ocen INTEGER, leto INTEGER, opis TEXT, url_naslovnice TEXT ); INSERT INTO knjiga (id, ISBN, naslov, dolzina, povprecna_ocena, stevilo_ocen, leto, opis, url_naslovnice) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING id CREATE TABLE avtor ( id INTEGER PRIMARY KEY, ime TEXT NOT NULL, povprecna_ocena FLOAT, datum_rojstva DATE, kraj_rojstva TEXT ); INSERT INTO avtor (id, ime, povprecna_ocena, datum_rojstva, kraj_rojstva) VALUES (%s, %s, %s, %s, %s) RETURNING id CREATE TABLE serija (id INTEGER PRIMARY KEY, ime TEXT NOT NULL, stevilo_knjig INTEGER NOT NULL); INSERT INTO serija (id, ime, stevilo_knjig) VALUES (%s, %s, %s) RETURNING id # Arts Photography, null ---> zato opis lahko null CREATE TABLE zanr ( ime_zanra TEXT PRIMARY KEY, opis TEXT ); INSERT INTO zanr (ime_zanra, opis) VALUES (%s, %s) RETURNING ime_zanra CREATE TABLE del_serije ( id_knjige INTEGER NOT NULL REFERENCES knjiga(id), id_serije INTEGER NOT NULL REFERENCES serija(id), zaporedna_stevilka_serije INTEGER, PRIMARY KEY (id_serije, id_knjige) ); INSERT INTO del_serije (id_knjige, id_serije, zaporedna_stevilka_serije) VALUES (%s, %s, %s) RETURNING id_serije CREATE TABLE avtor_knjige ( id_knjige INTEGER NOT NULL REFERENCES knjiga(id), id_avtorja INTEGER NOT NULL REFERENCES avtor(id), PRIMARY KEY (id_avtorja, id_knjige) ); INSERT INTO avtor_knjige (id_knjige, id_avtorja) VALUES (%s, %s) RETURNING (id_knjige, id_avtorja) CREATE TABLE zanr_knjige ( id_knjige INTEGER NOT NULL REFERENCES knjiga(id), zanr TEXT NOT NULL REFERENCES zanr(ime_zanra), PRIMARY KEY (id_knjige, zanr) ); INSERT INTO zanr_knjige (id_knjige, zanr) VALUES (%s, %s) RETURNING (id_knjige, zanr) CREATE TABLE avtorjev_zanr ( id_avtorja INTEGER NOT NULL REFERENCES avtor(id), zanr TEXT NOT NULL REFERENCES zanr(ime_zanra), PRIMARY KEY (id_avtorja, zanr) ); INSERT INTO avtorjev_zanr (id_avtorja, zanr) VALUES (%s, %s) RETURNING (id_avtorja, zanr) CREATE TABLE kljucna_beseda ( pojem TEXT PRIMARY KEY, skupina TEXT NOT NULL ); INSERT INTO kljucna_beseda (pojem, skupina) VALUES (%s, %s) RETURNING (pojem) CREATE TABLE knjiga_kljucne_besede ( id_knjige INTEGER NOT NULL REFERENCES knjiga(id), kljucna_beseda TEXT NOT NULL REFERENCES kljucna_beseda(pojem), PRIMARY KEY (id_knjige, kljucna_beseda) ); INSERT INTO knjiga_kljucne_besede (id_knjige, kljucna_beseda) VALUES (%s, %s) RETURNING (id_knjige, kljucna_beseda) # daj_pravice() # for x in [knjiga_kljucne_besede]: # izprazni_tabelo(x) # for x in [ knjiga_kljucne_besede]: # #ustvari_tabelo(x) # uvozi_podatke(x) # uvozi_podatke(knjiga_kljucne_besede) # ustvari_vse_tabele() # uvozi_vse_podatke() # izbrisi_podovojene_vrstice('podatki/zanr.csv') # ~~~~~~~~~~~~~~~~~~~~~~~~~UPORABNIKI # CREATE TYPE spol AS ENUM('Female', 'Male'); # CREATE TYPE dom AS ENUM('Gryffindor', 'Slytherin', 'Hufflepuff', 'Ravenclaw'); CREATE TABLE uporabnik ( id SERIAL PRIMARY KEY, vzdevek TEXT NOT NULL UNIQUE, geslo TEXT NOT NULL, email TEXT NOT NULL UNIQUE, dom dom NOT NULL, spol spol NOT NULL ); INSERT INTO uporabnik (id, vzdevek, geslo, email, dom, spol) VALUES (%s, %s, %s, %s, %s, %s) RETURNING (id_uporabnika) CREATE TABLE wishlist ( id_uporabnika INTEGER NOT NULL REFERENCES uporabnik(id), id_knjige INTEGER NOT NULL REFERENCES knjiga(id), PRIMARY KEY(id_uporabnika, id_knjige) ); INSERT INTO wishlist (id_uporabnika, id_knjige) VALUES (%s, %s) RETURNING (id_uporabnika, id_knjige) CREATE TABLE prebrana_knjiga ( id_uporabnika INTEGER NOT NULL REFERENCES uporabnik(id), id_knjige INTEGER NOT NULL REFERENCES knjiga(id), ocena INTEGER, PRIMARY KEY(id_uporabnika, id_knjige) ); INSERT INTO prebrana_knjiga (id_uporabnika, id_knjige, ocena) VALUES (%s, %s, %s) RETURNING (id_uporabnika, id_knjige) # # daj_pravice() # NAKNADNO DODANI SQL-stavki # ALTER TABLE knjiga ADD vsota_ocen float; # UPDATE knjiga SET vsota_ocen = stevilo_ocen * povprecna_ocena; # ALTER TABLE knjiga DROP COLUMN povprecna_ocena; # UPDATE knjiga SET stevilo_ocen = COALESCE(stevilo_ocen,0); # UPDATE knjiga SET vsota_ocen = COALESCE(vsota_ocen,0); | 2.248684 | 2 |
packages/mccomponents/tests/mccomponentsbpmodule/dgssxrespixel_TestCase.py | mcvine/mcvine | 5 | 6616129 | #!/usr/bin/env python
#
import unittestX as unittest
import journal
debug = journal.debug( "homogeneous_scatterer_TestCase" )
warning = journal.warning( "homogeneous_scatterer_TestCase" )
import mcni
from mcni import mcnibp
from mccomposite import mccompositebp
from mccomponents import mccomponentsbp
class TestCase(unittest.TestCase):
def testHomogeneousNeutronScatterer(self):
'HomogeneousNeutronScatterer'
shape = mccompositebp.Cylinder(0.025/2., 0.01)
tof=0.001; pressure=10*101325
pixel = mccomponentsbp.DGSSXResPixel(tof, pressure, shape)
ev = mcni.neutron( r = (0,0,-3), v = (0,0,3000) )
pixel.scatter(ev)
print(ev.probability)
return
pass # end of TestCase
if __name__ == "__main__": unittest.main()
# End of file
| #!/usr/bin/env python
#
import unittestX as unittest
import journal
debug = journal.debug( "homogeneous_scatterer_TestCase" )
warning = journal.warning( "homogeneous_scatterer_TestCase" )
import mcni
from mcni import mcnibp
from mccomposite import mccompositebp
from mccomponents import mccomponentsbp
class TestCase(unittest.TestCase):
def testHomogeneousNeutronScatterer(self):
'HomogeneousNeutronScatterer'
shape = mccompositebp.Cylinder(0.025/2., 0.01)
tof=0.001; pressure=10*101325
pixel = mccomponentsbp.DGSSXResPixel(tof, pressure, shape)
ev = mcni.neutron( r = (0,0,-3), v = (0,0,3000) )
pixel.scatter(ev)
print(ev.probability)
return
pass # end of TestCase
if __name__ == "__main__": unittest.main()
# End of file
| en | 0.440812 | #!/usr/bin/env python # # end of TestCase # End of file | 2.191057 | 2 |
app.py | Akshaykumarcp/cotton-plant-disease-prediction | 2 | 6616130 | from __future__ import division, print_function
import os
import numpy as np
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
from flask import Flask, request, render_template
from werkzeug.utils import secure_filename
# define flask app
app = Flask(__name__)
# model name
MODEL_PATH ='resnet152V2_model.h5'
# load trained model
model = load_model(MODEL_PATH)
def model_predict(img_path, model):
print('Uploaded image path: ',img_path)
loaded_image = image.load_img(img_path, target_size=(224, 224))
# preprocess the image
loaded_image_in_array = image.img_to_array(loaded_image)
# normalize
loaded_image_in_array=loaded_image_in_array/255
# add additional dim such as to match input dim of the model architecture
x = np.expand_dims(loaded_image_in_array, axis=0)
# prediction
prediction = model.predict(x)
results=np.argmax(prediction, axis=1)
if results==0:
results="The leaf is diseased cotton leaf"
elif results==1:
results="The leaf is diseased cotton plant"
elif results==2:
results="The leaf is fresh cotton leaf"
else:
results="The leaf is fresh cotton plant"
return results
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/predict', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
# Get the file from post request
f = request.files['file']
# Save the file to ./uploads
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, 'uploads', secure_filename(f.filename))
f.save(file_path)
# Make prediction
preds = model_predict(file_path, model)
result=preds
return result
return None
if __name__ == '__main__':
app.run(port=5001,debug=True)
| from __future__ import division, print_function
import os
import numpy as np
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
from flask import Flask, request, render_template
from werkzeug.utils import secure_filename
# define flask app
app = Flask(__name__)
# model name
MODEL_PATH ='resnet152V2_model.h5'
# load trained model
model = load_model(MODEL_PATH)
def model_predict(img_path, model):
print('Uploaded image path: ',img_path)
loaded_image = image.load_img(img_path, target_size=(224, 224))
# preprocess the image
loaded_image_in_array = image.img_to_array(loaded_image)
# normalize
loaded_image_in_array=loaded_image_in_array/255
# add additional dim such as to match input dim of the model architecture
x = np.expand_dims(loaded_image_in_array, axis=0)
# prediction
prediction = model.predict(x)
results=np.argmax(prediction, axis=1)
if results==0:
results="The leaf is diseased cotton leaf"
elif results==1:
results="The leaf is diseased cotton plant"
elif results==2:
results="The leaf is fresh cotton leaf"
else:
results="The leaf is fresh cotton plant"
return results
@app.route('/', methods=['GET'])
def index():
return render_template('index.html')
@app.route('/predict', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
# Get the file from post request
f = request.files['file']
# Save the file to ./uploads
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, 'uploads', secure_filename(f.filename))
f.save(file_path)
# Make prediction
preds = model_predict(file_path, model)
result=preds
return result
return None
if __name__ == '__main__':
app.run(port=5001,debug=True)
| en | 0.85177 | # define flask app # model name # load trained model # preprocess the image # normalize # add additional dim such as to match input dim of the model architecture # prediction # Get the file from post request # Save the file to ./uploads # Make prediction | 2.894371 | 3 |
ewah/utils/airflow_utils.py | soltanianalytics/ewah | 2 | 6616131 | <gh_stars>1-10
from airflow.operators.python import PythonOperator as PO
from airflow.operators.dummy import DummyOperator as DO
from airflow.models import BaseOperator
from airflow.sensors.sql import SqlSensor
from ewah.hooks.base import EWAHBaseHook
from ewah.constants import EWAHConstants as EC
from datetime import datetime, timedelta, timezone
from copy import deepcopy
import pytz
import re
class EWAHSqlSensor(SqlSensor):
"""Overwrite native SQL sensor to allow usage of ewah custom connection types."""
def _get_hook(self):
conn = EWAHBaseHook.get_connection(conn_id=self.conn_id)
if not conn.conn_type.startswith("ewah"):
raise Exception("Must use an appropriate EWAH custom connection type!")
return conn.get_hook()
class PGO(BaseOperator):
"""Airflow operator to execute PostgreSQL statements.
Cannot use airflow.providers.postgres.operators.postgres.PostgresOperator
due to the a requirement to have an SSH tunnel option.
Needs to be otherwise interchangeable with Airflow's PostgresOperator.
"""
template_fields = ("sql",)
template_ext = (".sql",)
def __init__(self, sql, postgres_conn_id, parameters=None, *args, **kwargs):
self.sql = sql
self.postgres_conn_id = postgres_conn_id
self.parameters = parameters
super().__init__(*args, **kwargs)
def execute(self, context):
hook = EWAHBaseHook.get_hook_from_conn_id(self.postgres_conn_id)
hook.execute(sql=self.sql, params=self.parameters, commit=True)
hook.close() # SSH tunnel does not close if hook is not closed first
def datetime_utcnow_with_tz():
return datetime.utcnow().replace(tzinfo=pytz.utc)
def airflow_datetime_adjustments(datetime_raw):
if type(datetime_raw) == str:
datetime_string = datetime_raw
if "-" in datetime_string[10:]:
tz_sign = "-"
else:
tz_sign = "+"
datetime_strings = datetime_string.split(tz_sign)
if "T" in datetime_string:
format_string = "%Y-%m-%dT%H:%M:%S"
else:
format_string = "%Y-%m-%d %H:%M:%S"
if "." in datetime_string:
format_string += ".%f"
if len(datetime_strings) == 2:
if ":" in datetime_strings[1]:
datetime_strings[1] = datetime_strings[1].replace(":", "")
datetime_string = tz_sign.join(datetime_strings)
format_string += "%z"
elif "Z" in datetime_string:
format_string += "Z"
datetime_raw = datetime.strptime(
datetime_string,
format_string,
)
elif not (datetime_raw is None or isinstance(datetime_raw, datetime)):
raise Exception(
"Invalid datetime type supplied! Supply either string"
+ " or datetime.datetime! supplied: {0}".format(str(type(datetime_raw)))
)
if datetime_raw and datetime_raw.tzinfo is None:
datetime_raw = datetime_raw.replace(tzinfo=timezone.utc)
return datetime_raw
| from airflow.operators.python import PythonOperator as PO
from airflow.operators.dummy import DummyOperator as DO
from airflow.models import BaseOperator
from airflow.sensors.sql import SqlSensor
from ewah.hooks.base import EWAHBaseHook
from ewah.constants import EWAHConstants as EC
from datetime import datetime, timedelta, timezone
from copy import deepcopy
import pytz
import re
class EWAHSqlSensor(SqlSensor):
"""Overwrite native SQL sensor to allow usage of ewah custom connection types."""
def _get_hook(self):
conn = EWAHBaseHook.get_connection(conn_id=self.conn_id)
if not conn.conn_type.startswith("ewah"):
raise Exception("Must use an appropriate EWAH custom connection type!")
return conn.get_hook()
class PGO(BaseOperator):
"""Airflow operator to execute PostgreSQL statements.
Cannot use airflow.providers.postgres.operators.postgres.PostgresOperator
due to the a requirement to have an SSH tunnel option.
Needs to be otherwise interchangeable with Airflow's PostgresOperator.
"""
template_fields = ("sql",)
template_ext = (".sql",)
def __init__(self, sql, postgres_conn_id, parameters=None, *args, **kwargs):
self.sql = sql
self.postgres_conn_id = postgres_conn_id
self.parameters = parameters
super().__init__(*args, **kwargs)
def execute(self, context):
hook = EWAHBaseHook.get_hook_from_conn_id(self.postgres_conn_id)
hook.execute(sql=self.sql, params=self.parameters, commit=True)
hook.close() # SSH tunnel does not close if hook is not closed first
def datetime_utcnow_with_tz():
return datetime.utcnow().replace(tzinfo=pytz.utc)
def airflow_datetime_adjustments(datetime_raw):
if type(datetime_raw) == str:
datetime_string = datetime_raw
if "-" in datetime_string[10:]:
tz_sign = "-"
else:
tz_sign = "+"
datetime_strings = datetime_string.split(tz_sign)
if "T" in datetime_string:
format_string = "%Y-%m-%dT%H:%M:%S"
else:
format_string = "%Y-%m-%d %H:%M:%S"
if "." in datetime_string:
format_string += ".%f"
if len(datetime_strings) == 2:
if ":" in datetime_strings[1]:
datetime_strings[1] = datetime_strings[1].replace(":", "")
datetime_string = tz_sign.join(datetime_strings)
format_string += "%z"
elif "Z" in datetime_string:
format_string += "Z"
datetime_raw = datetime.strptime(
datetime_string,
format_string,
)
elif not (datetime_raw is None or isinstance(datetime_raw, datetime)):
raise Exception(
"Invalid datetime type supplied! Supply either string"
+ " or datetime.datetime! supplied: {0}".format(str(type(datetime_raw)))
)
if datetime_raw and datetime_raw.tzinfo is None:
datetime_raw = datetime_raw.replace(tzinfo=timezone.utc)
return datetime_raw | en | 0.777053 | Overwrite native SQL sensor to allow usage of ewah custom connection types. Airflow operator to execute PostgreSQL statements. Cannot use airflow.providers.postgres.operators.postgres.PostgresOperator due to the a requirement to have an SSH tunnel option. Needs to be otherwise interchangeable with Airflow's PostgresOperator. # SSH tunnel does not close if hook is not closed first | 2.311401 | 2 |
geokey_wegovnow/management/commands/set_superuser.py | ExCiteS/geokey-wegonow | 0 | 6616132 | """Command `set_superuser`."""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from allauth.socialaccount.models import SocialAccount
class Command(BaseCommand):
"""Set user as a superuser."""
help = 'Set user as a superuser.'
def add_arguments(self, parser):
parser.add_argument(
'--username',
action='store',
dest='username',
default=None,
help='Make a user with this username a superuser.'
)
parser.add_argument(
'--email',
action='store',
dest='email',
default=None,
help='Make a user with this email address a superuser.'
)
def handle(self, *args, **options):
"""Handle the command."""
if not options['username']:
self.stderr.write('Username not provided.')
if not options['email']:
self.stderr.write('Email address not provided.')
if options['username'] and options['email']:
user = None
for account in SocialAccount.objects.all():
member = account.extra_data.get('member', {})
if (member.get('name') == options['username'] and
member.get('email') == options['email']):
user = account.user
break
if user:
if user.is_superuser:
self.stderr.write('User is already a superuser.')
else:
user.is_superuser = True
user.save()
self.stdout.write('User was set as a superuser.')
else:
self.stderr.write('User was not found.')
| """Command `set_superuser`."""
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand
from allauth.socialaccount.models import SocialAccount
class Command(BaseCommand):
"""Set user as a superuser."""
help = 'Set user as a superuser.'
def add_arguments(self, parser):
parser.add_argument(
'--username',
action='store',
dest='username',
default=None,
help='Make a user with this username a superuser.'
)
parser.add_argument(
'--email',
action='store',
dest='email',
default=None,
help='Make a user with this email address a superuser.'
)
def handle(self, *args, **options):
"""Handle the command."""
if not options['username']:
self.stderr.write('Username not provided.')
if not options['email']:
self.stderr.write('Email address not provided.')
if options['username'] and options['email']:
user = None
for account in SocialAccount.objects.all():
member = account.extra_data.get('member', {})
if (member.get('name') == options['username'] and
member.get('email') == options['email']):
user = account.user
break
if user:
if user.is_superuser:
self.stderr.write('User is already a superuser.')
else:
user.is_superuser = True
user.save()
self.stdout.write('User was set as a superuser.')
else:
self.stderr.write('User was not found.')
| en | 0.719146 | Command `set_superuser`. # -*- coding: utf-8 -*- Set user as a superuser. Handle the command. | 2.562121 | 3 |
src/settings/docker.py | viniciusgava/portaldorh-holerite-download | 11 | 6616133 | <reponame>viniciusgava/portaldorh-holerite-download
import os
import sys
from util.ObjectDic import ObjectDic
portal_rh = ObjectDic({})
# Portal do RH username
if os.environ.get('RH_USERNAME') is None:
sys.exit("Missing ENV VARIABLE RH_USERNAME")
portal_rh['username'] = os.environ.get('RH_USERNAME')
# Portal do RH password
if os.environ.get('RH_PASSWORD') is None:
sys.exit("Missing ENV VARIABLE RH_PASSWORD")
portal_rh['password'] = os.environ.get('RH_PASSWORD')
# Portal do RH Search Date
if os.environ.get('RH_SEARCH_YEAR') is None:
sys.exit("Missing ENV VARIABLE RH_SEARCH_YEAR")
search_year = os.environ.get('RH_SEARCH_YEAR')
# Portal do RH Search Date
if os.environ.get('RH_SEARCH_MONTH') is None:
sys.exit("Missing ENV VARIABLE RH_SEARCH_MONTH")
search_month = os.environ.get('RH_SEARCH_MONTH')
# Portal do RH URL
portal_rh['url'] = os.environ.get(
"RH_URL",
"https://www.portaldorh.com.br/portal_rckt/auto_default.aspx"
)
# Download Path
default_download_path = os.environ.get(
"DOWNLOAD_PATH",
"/usr/workspace/downloads"
)
# Ensure downloads path exists
if os.path.exists(default_download_path) is False:
os.makedirs(default_download_path)
# Mail Gun - Enable?
mailgun = ObjectDic({
'enable': os.environ.get("MAIL_GUN_ENABLE", 'false')
})
mailgun.enable = mailgun.enable == 'true'
# Mail Gun
if mailgun.enable:
# Mail Gun - Api Key
if os.environ.get('MAIL_GUN_KEY') is None:
sys.exit("Missing ENV VARIABLE MAIL_GUN_KEY")
mailgun['api_key'] = os.environ.get('MAIL_GUN_KEY')
# Mail Gun - Api Domain
if os.environ.get('MAIL_GUN_DOMAIN') is None:
sys.exit("Missing ENV VARIABLE MAIL_GUN_DOMAIN")
mailgun['domain'] = os.environ.get('MAIL_GUN_DOMAIN')
# Mail Gun - From
if os.environ.get('MAIL_GUN_FROM') is None:
sys.exit("Missing ENV VARIABLE MAIL_GUN_FROM")
mailgun['from'] = os.environ.get('MAIL_GUN_FROM')
# Mail Gun - To
if os.environ.get('MAIL_GUN_TO') is None:
sys.exit("Missing ENV VARIABLE MAIL_GUN_TO")
mailgun['to'] = os.environ.get('MAIL_GUN_TO')
# Mail Gun - Subject
if os.environ.get('MAIL_GUN_SUBJECT') is None:
sys.exit("Missing ENV VARIABLE MAIL_GUN_SUBJECT")
mailgun['subject'] = os.environ.get('MAIL_GUN_SUBJECT')
# Mail Gun - Text or Html
if (os.environ.get('MAIL_GUN_TEXT') is None and
os.environ.get('MAIL_GUN_HTML') is None):
sys.exit("Missing ENV VARIABLE MAIL_GUN_TEXT or MAIL_GUN_HTML")
# Mail Gun - Text
if os.environ.get('MAIL_GUN_TEXT') is not None:
mailgun['text'] = os.environ.get('MAIL_GUN_TEXT')
if os.environ.get('MAIL_GUN_HTML') is not None:
mailgun['html'] = os.environ.get('MAIL_GUN_HTML')
# Push Bullet Notification - Enable?
pushbullet = ObjectDic({
'enable': os.environ.get("PUSH_BULLET_ENABLE", 'false')
})
pushbullet.enable = pushbullet.enable == 'true'
# Push Bullet Notification
if pushbullet.enable:
# Push Bullet - Api Token
if os.environ.get('PUSH_BULLET_TOKEN') is None:
sys.exit("Missing ENV VARIABLE PUSH_BULLET_TOKEN")
pushbullet['token'] = os.environ.get('PUSH_BULLET_TOKEN')
# Push Bullet - Notification title
if os.environ.get('PUSH_BULLET_TITLE') is None:
sys.exit("Missing ENV VARIABLE PUSH_BULLET_TITLE")
pushbullet['title'] = os.environ.get('PUSH_BULLET_TITLE')
# Push Bullet - Notification body
if os.environ.get('PUSH_BULLET_BODY') is None:
sys.exit("Missing ENV VARIABLE PUSH_BULLET_BODY")
pushbullet['body'] = os.environ.get('PUSH_BULLET_BODY')
| import os
import sys
from util.ObjectDic import ObjectDic
portal_rh = ObjectDic({})
# Portal do RH username
if os.environ.get('RH_USERNAME') is None:
sys.exit("Missing ENV VARIABLE RH_USERNAME")
portal_rh['username'] = os.environ.get('RH_USERNAME')
# Portal do RH password
if os.environ.get('RH_PASSWORD') is None:
sys.exit("Missing ENV VARIABLE RH_PASSWORD")
portal_rh['password'] = os.environ.get('RH_PASSWORD')
# Portal do RH Search Date
if os.environ.get('RH_SEARCH_YEAR') is None:
sys.exit("Missing ENV VARIABLE RH_SEARCH_YEAR")
search_year = os.environ.get('RH_SEARCH_YEAR')
# Portal do RH Search Date
if os.environ.get('RH_SEARCH_MONTH') is None:
sys.exit("Missing ENV VARIABLE RH_SEARCH_MONTH")
search_month = os.environ.get('RH_SEARCH_MONTH')
# Portal do RH URL
portal_rh['url'] = os.environ.get(
"RH_URL",
"https://www.portaldorh.com.br/portal_rckt/auto_default.aspx"
)
# Download Path
default_download_path = os.environ.get(
"DOWNLOAD_PATH",
"/usr/workspace/downloads"
)
# Ensure downloads path exists
if os.path.exists(default_download_path) is False:
os.makedirs(default_download_path)
# Mail Gun - Enable?
mailgun = ObjectDic({
'enable': os.environ.get("MAIL_GUN_ENABLE", 'false')
})
mailgun.enable = mailgun.enable == 'true'
# Mail Gun
if mailgun.enable:
# Mail Gun - Api Key
if os.environ.get('MAIL_GUN_KEY') is None:
sys.exit("Missing ENV VARIABLE MAIL_GUN_KEY")
mailgun['api_key'] = os.environ.get('MAIL_GUN_KEY')
# Mail Gun - Api Domain
if os.environ.get('MAIL_GUN_DOMAIN') is None:
sys.exit("Missing ENV VARIABLE MAIL_GUN_DOMAIN")
mailgun['domain'] = os.environ.get('MAIL_GUN_DOMAIN')
# Mail Gun - From
if os.environ.get('MAIL_GUN_FROM') is None:
sys.exit("Missing ENV VARIABLE MAIL_GUN_FROM")
mailgun['from'] = os.environ.get('MAIL_GUN_FROM')
# Mail Gun - To
if os.environ.get('MAIL_GUN_TO') is None:
sys.exit("Missing ENV VARIABLE MAIL_GUN_TO")
mailgun['to'] = os.environ.get('MAIL_GUN_TO')
# Mail Gun - Subject
if os.environ.get('MAIL_GUN_SUBJECT') is None:
sys.exit("Missing ENV VARIABLE MAIL_GUN_SUBJECT")
mailgun['subject'] = os.environ.get('MAIL_GUN_SUBJECT')
# Mail Gun - Text or Html
if (os.environ.get('MAIL_GUN_TEXT') is None and
os.environ.get('MAIL_GUN_HTML') is None):
sys.exit("Missing ENV VARIABLE MAIL_GUN_TEXT or MAIL_GUN_HTML")
# Mail Gun - Text
if os.environ.get('MAIL_GUN_TEXT') is not None:
mailgun['text'] = os.environ.get('MAIL_GUN_TEXT')
if os.environ.get('MAIL_GUN_HTML') is not None:
mailgun['html'] = os.environ.get('MAIL_GUN_HTML')
# Push Bullet Notification - Enable?
pushbullet = ObjectDic({
'enable': os.environ.get("PUSH_BULLET_ENABLE", 'false')
})
pushbullet.enable = pushbullet.enable == 'true'
# Push Bullet Notification
if pushbullet.enable:
# Push Bullet - Api Token
if os.environ.get('PUSH_BULLET_TOKEN') is None:
sys.exit("Missing ENV VARIABLE PUSH_BULLET_TOKEN")
pushbullet['token'] = os.environ.get('PUSH_BULLET_TOKEN')
# Push Bullet - Notification title
if os.environ.get('PUSH_BULLET_TITLE') is None:
sys.exit("Missing ENV VARIABLE PUSH_BULLET_TITLE")
pushbullet['title'] = os.environ.get('PUSH_BULLET_TITLE')
# Push Bullet - Notification body
if os.environ.get('PUSH_BULLET_BODY') is None:
sys.exit("Missing ENV VARIABLE PUSH_BULLET_BODY")
pushbullet['body'] = os.environ.get('PUSH_BULLET_BODY') | en | 0.365352 | # Portal do RH username # Portal do RH password # Portal do RH Search Date # Portal do RH Search Date # Portal do RH URL # Download Path # Ensure downloads path exists # Mail Gun - Enable? # Mail Gun # Mail Gun - Api Key # Mail Gun - Api Domain # Mail Gun - From # Mail Gun - To # Mail Gun - Subject # Mail Gun - Text or Html # Mail Gun - Text # Push Bullet Notification - Enable? # Push Bullet Notification # Push Bullet - Api Token # Push Bullet - Notification title # Push Bullet - Notification body | 2.202534 | 2 |
HACKERRANK_Strings/split&join.py | StefaniaSferragatta/ADM2020-HW1 | 0 | 6616134 | def split_and_join(line):
splitted = line.split(" ")
formatted = "-".join(splitted)
return formatted
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result) | def split_and_join(line):
splitted = line.split(" ")
formatted = "-".join(splitted)
return formatted
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result) | none | 1 | 3.640805 | 4 | |
easy_test/mixins/mixin_html.py | raphaelcmacedo/easy-test | 5 | 6616135 | <reponame>raphaelcmacedo/easy-test
from easy_test.util import contains_option
class HtmlMixin():
def test_status_code(self):
if not self._concrete:
return
self.assertEqual(self.status_code, self.response.status_code)
def test_template(self):
if not self._concrete:
return
if not contains_option(self._meta, 'template'):
return
template = self._meta.template
self.assertTemplateUsed(self.response, template)
def test_content(self):
if not self._concrete:
return
if not contains_option(self._meta, 'contents'):
return
contents = self._meta.contents
if len(contents) <= 0:
return
# Verify if was informed one or more fields
if isinstance(contents, str):
self.assertContains(self.response, contents)
elif isinstance(contents[0], tuple):
for content, count in contents:
with self.subTest():
self.assertContains(self.response, content, count)
else:
for content in contents:
with self.subTest():
self.assertContains(self.response, content)
def test_context(self):
if not self._concrete:
return
if not contains_option(self._meta, 'context_variables'):
return
variables = self._meta.context_variables
# Verify if was informed one or more fields
if isinstance(variables, str):
self.assertIn(variables, self.response.context)
else:
for variable in variables:
with self.subTest():
self.assertIn(variable, self.response.context)
def test_model_context(self):
if not self._concrete:
return
if not contains_option(self._meta, 'context_model_variable'):
return
context_model_variable = self._meta.context_model_variable
self.assertIn(context_model_variable, self.response.context)
variable = self.response.context[context_model_variable]
self.assertIsInstance(variable, self._meta.model)
def test_csrf(self):
if not self._concrete:
return
if self._meta.ignore_csrfmiddlewaretoken:
return
self.assertContains(self.response, 'csrfmiddlewaretoken')
| from easy_test.util import contains_option
class HtmlMixin():
def test_status_code(self):
if not self._concrete:
return
self.assertEqual(self.status_code, self.response.status_code)
def test_template(self):
if not self._concrete:
return
if not contains_option(self._meta, 'template'):
return
template = self._meta.template
self.assertTemplateUsed(self.response, template)
def test_content(self):
if not self._concrete:
return
if not contains_option(self._meta, 'contents'):
return
contents = self._meta.contents
if len(contents) <= 0:
return
# Verify if was informed one or more fields
if isinstance(contents, str):
self.assertContains(self.response, contents)
elif isinstance(contents[0], tuple):
for content, count in contents:
with self.subTest():
self.assertContains(self.response, content, count)
else:
for content in contents:
with self.subTest():
self.assertContains(self.response, content)
def test_context(self):
if not self._concrete:
return
if not contains_option(self._meta, 'context_variables'):
return
variables = self._meta.context_variables
# Verify if was informed one or more fields
if isinstance(variables, str):
self.assertIn(variables, self.response.context)
else:
for variable in variables:
with self.subTest():
self.assertIn(variable, self.response.context)
def test_model_context(self):
if not self._concrete:
return
if not contains_option(self._meta, 'context_model_variable'):
return
context_model_variable = self._meta.context_model_variable
self.assertIn(context_model_variable, self.response.context)
variable = self.response.context[context_model_variable]
self.assertIsInstance(variable, self._meta.model)
def test_csrf(self):
if not self._concrete:
return
if self._meta.ignore_csrfmiddlewaretoken:
return
self.assertContains(self.response, 'csrfmiddlewaretoken') | en | 0.943887 | # Verify if was informed one or more fields # Verify if was informed one or more fields | 2.421845 | 2 |
src/segmentation/ShowInFsTransformer.py | stefantaubert/imageclef-lifelog-2019 | 1 | 6616136 | from os.path import basename
from pdtransform import NoFitMixin
from src.io.paths import mk_dir
from src.common.helper import copy
def show_clusters_in_fs(clusters, dest_dir):
origin_paths = []
dest_paths = []
for c in range(len(clusters)):
s_count = len(clusters[c])
for s in range(s_count):
imgs = clusters[c][s]
imgs_count = len(imgs)
segment_dir = "{dir}{cluster}_{s_count}/{segment}_{img_count}/".format(dir=dest_dir, cluster=str(c), s_count=str(s_count), segment=str(s), img_count=str(imgs_count))
for img in imgs:
dest_file = "{segdir}{filename}".format(segdir=segment_dir, filename=basename(img))
origin_paths.append(img)
dest_paths.append(dest_file)
copy(origin_paths, dest_paths)
class ShowInFsTransformer(NoFitMixin):
"""
"""
def __init__(self, day: int, usr: int, name: str, copy: bool):
self.day = day
self.usr = usr
self.copy = copy
self.name = name
def transform(self, clusters: list):
if self.copy:
print("Copying clusters to filesystem...")
data_an_type = 1
dest = mk_dir("cluster_output/{day}/{name}".format(day=str(self.day), name=self.name), usr=self.usr, t=data_an_type)
show_clusters_in_fs(clusters, dest)
return clusters | from os.path import basename
from pdtransform import NoFitMixin
from src.io.paths import mk_dir
from src.common.helper import copy
def show_clusters_in_fs(clusters, dest_dir):
origin_paths = []
dest_paths = []
for c in range(len(clusters)):
s_count = len(clusters[c])
for s in range(s_count):
imgs = clusters[c][s]
imgs_count = len(imgs)
segment_dir = "{dir}{cluster}_{s_count}/{segment}_{img_count}/".format(dir=dest_dir, cluster=str(c), s_count=str(s_count), segment=str(s), img_count=str(imgs_count))
for img in imgs:
dest_file = "{segdir}{filename}".format(segdir=segment_dir, filename=basename(img))
origin_paths.append(img)
dest_paths.append(dest_file)
copy(origin_paths, dest_paths)
class ShowInFsTransformer(NoFitMixin):
"""
"""
def __init__(self, day: int, usr: int, name: str, copy: bool):
self.day = day
self.usr = usr
self.copy = copy
self.name = name
def transform(self, clusters: list):
if self.copy:
print("Copying clusters to filesystem...")
data_an_type = 1
dest = mk_dir("cluster_output/{day}/{name}".format(day=str(self.day), name=self.name), usr=self.usr, t=data_an_type)
show_clusters_in_fs(clusters, dest)
return clusters | none | 1 | 2.391783 | 2 | |
UDPFileSender.py | asteroi8/UDPFileSender | 0 | 6616137 | <filename>UDPFileSender.py
import socket
import sys
#create file
def createFile():
with open("file_object.txt", 'w') as fileContent:
fileContent.write('This is just cray cray\n')
fileContent.close()
#read file
def readFile():
with open('file_object.txt', 'r') as fileContent:
content = fileContent.read()
if content is None:
fileContent.close()
return content
#send the file data
def sendData(sock, dest):
data = readFile()
sock.sendto(bytes(data, 'UTF-8'), dest)
#setup socket
def setupUDPSocket():
#create udp socket
_socket = socket.socket(socket.AF_INET, #internet
socket.SOCK_DGRAM) # UDP
#forceibly bind to port in use
_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return _socket
#main
if __name__=='__main__':
#destination address and port
package_destination = ("192.168.0.67", 4001)
#create udp socket
sock = setupUDPSocket()
#create a file to read
createFile()
#read the file
readFile()
#send file content over udp
sendData(sock, package_destination)
| <filename>UDPFileSender.py
import socket
import sys
#create file
def createFile():
with open("file_object.txt", 'w') as fileContent:
fileContent.write('This is just cray cray\n')
fileContent.close()
#read file
def readFile():
with open('file_object.txt', 'r') as fileContent:
content = fileContent.read()
if content is None:
fileContent.close()
return content
#send the file data
def sendData(sock, dest):
data = readFile()
sock.sendto(bytes(data, 'UTF-8'), dest)
#setup socket
def setupUDPSocket():
#create udp socket
_socket = socket.socket(socket.AF_INET, #internet
socket.SOCK_DGRAM) # UDP
#forceibly bind to port in use
_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return _socket
#main
if __name__=='__main__':
#destination address and port
package_destination = ("192.168.0.67", 4001)
#create udp socket
sock = setupUDPSocket()
#create a file to read
createFile()
#read the file
readFile()
#send file content over udp
sendData(sock, package_destination)
| en | 0.740694 | #create file #read file #send the file data #setup socket #create udp socket #internet # UDP #forceibly bind to port in use #main #destination address and port #create udp socket #create a file to read #read the file #send file content over udp | 3.387913 | 3 |
Algorithm_C_Cpp/Recursive_Art/Art.py | DannielF/Development_Engineering | 1 | 6616138 | import turtle
myTurtle = turtle.Turtle()
mywin = turtle.Screen()
def draw(myTurtle, length):
if length > 0:
myTurtle.forward(length)
myTurtle.left(90)
draw(myTurtle, length-10)
draw(myTurtle, 100)
mywin.exitonclick()
| import turtle
myTurtle = turtle.Turtle()
mywin = turtle.Screen()
def draw(myTurtle, length):
if length > 0:
myTurtle.forward(length)
myTurtle.left(90)
draw(myTurtle, length-10)
draw(myTurtle, 100)
mywin.exitonclick()
| none | 1 | 3.765773 | 4 | |
ex12.py | Allwillcome/LearnPythontheHardWay | 0 | 6616139 | <filename>ex12.py
age = raw_input("How old are you?")
tall = raw_input("How tall are you")
weight = raw_input("How much do you weight ?")
print "So you are %r old ,%r tall and %r heavy." %(age, tall,weight )
| <filename>ex12.py
age = raw_input("How old are you?")
tall = raw_input("How tall are you")
weight = raw_input("How much do you weight ?")
print "So you are %r old ,%r tall and %r heavy." %(age, tall,weight )
| none | 1 | 3.436157 | 3 | |
cloudmesh/compute/virtualbox/Provider.py | kpimparkar/cloudmesh-cloud | 0 | 6616140 | import os
import platform
import shlex
import subprocess
import sys
import textwrap
import webbrowser
from pprint import pprint
from cloudmesh.abstractclass.ComputeNodeABC import ComputeNodeABC
from cloudmesh.common.Shell import Shell
from cloudmesh.common.console import Console
from cloudmesh.common.dotdict import dotdict
from cloudmesh.common.util import path_expand
# from cloudmesh.abstractclass import ComputeNodeManagerABC
from cloudmesh.configuration.Config import Config
"""
is vagrant up to date
==> vagrant: A new version of Vagrant is available: 2.2.4 (installed version: 2.2.2)!
==> vagrant: To upgrade visit: https://www.vagrantup.com/downloads.html
"""
class Provider(ComputeNodeABC):
kind = "virtualbox"
def run_command(self, command):
process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
while True:
output = process.stdout.read(1)
if output == b'' and process.poll() is not None:
break
if output:
sys.stdout.write(output.decode("utf-8"))
sys.stdout.flush()
rc = process.poll()
return rc
def update_dict(self, entry, kind="node"):
if "cm" not in entry:
entry["cm"] = {}
entry["cm"]["kind"] = kind
entry["cm"]["driver"] = self.cloudtype
entry["cm"]["cloud"] = self.cloud
return entry
output = {
'vm': {
"sort_keys": ["cm.name"],
'order': ["vagrant.name",
"vagrant.cloud",
"vbox.name",
"vagrant.id",
"vagrant.provider",
"vagrant.state",
"vagrant.hostname"],
'header': ["Name",
"Cloud",
"Vbox",
"Id",
"Provider",
"State",
"Hostname"]
},
'image': None,
'flavor': None
}
def __init__(self, name=None,
configuration="~/.cloudmesh/.cloudmesh.yaml"):
self.config = Config()
conf = Config(configuration)["cloudmesh"]
self.user = conf["profile"]
self.spec = conf["cloud"][name]
self.cloud = name
cred = self.spec["credentials"]
self.cloudtype = self.spec["cm"]["kind"]
if platform.system().lower() == "darwin":
self.vboxmanage = \
"/Applications/VirtualBox.app/Contents/MacOS/VBoxManage"
else:
self.vboxmanage = "VBoxManage"
# m = MongoDBController()
# status = m.status()
# if status.status == "error":
# raise Exception("ERROR: MongoDB is not running.")
#
# BUG: Naturally the following is wrong as it depends on the name.
#
# super().__init__("vagrant", config)
# noinspection PyPep8
def version(self):
"""
This command returns the versions ov vagrant and virtual box
:return: A dict with the information
Description:
The output looks like this
{'vagrant': '2.2.4',
'virtualbox': {'extension': {
'description': 'USB 2.0 and USB 3.0 Host '
'Controller, Host Webcam, '
'VirtualBox RDP, PXE ROM, Disk '
'Encryption, NVMe.',
'extensionpack': True,
'revision': '128413',
'usable': 'true',
'version': '6.0.4'},
'version': '6.0.4'}}
"""
version = {
"vagrant": None,
"virtualbox": {
"version": None,
"extension": None
}
}
try:
result = Shell.execute("vagrant --version", shell=True)
txt, version["vagrant"] = result.split(" ")
if "A new version of Vagrant is available" in result:
Console.error(
"Vagrant is outdated. Please download a new version of "
"vagrant")
raise NotImplementedError
except:
pass
try:
result = Shell.execute(self.vboxmanage, shell=True)
txt, version["virtualbox"]["version"] = result.split("\n")[0].split(
"Version ")
result = Shell.execute(self.vboxmanage + " list -l extpacks",
shell=True)
extension = {}
for line in result.split("\n"):
if "Oracle VM VirtualBox Extension Pack" in line:
extension["extensionpack"] = True
elif "Revision:" in line:
extension["revision"] = line.split(":")[1].strip()
elif "Usable:" in line:
extension["usable"] = line.split(":")[1].strip()
elif "Description:" in line:
extension["description"] = line.split(":")[1].strip()
elif "Version:" in line:
extension["version"] = line.split(":")[1].strip()
version["virtualbox"]["extension"] = extension
except:
pass
return version
def images(self):
def convert(data_line):
data_line = data_line.replace("(", ",")
data_line = data_line.replace(")", ",")
data_entry = data_line.split(",")
data = dotdict()
data.name = data_entry[0].strip()
data.provider = data_entry[1].strip()
data.version = data_entry[2].strip()
data = self.update_dict(data, kind="image")
return data
result = Shell.execute("vagrant box list", shell=True)
if "There are no installed boxes" in result:
return None
else:
result = result.split("\n")
lines = []
for line in result:
entry = convert(line)
if "date" in entry:
date = entry["date"]
lines.append(entry)
return lines
def delete_image(self, name=None):
result = ""
if name is None:
pass
return "ERROR: please specify an image name"
# read name form config
else:
try:
command = "vagrant box remove {name}".format(name=name)
result = Shell.execute(command, shell=True)
except Exception as e:
print(e)
return result
def add_image(self, name=None):
command = "vagrant box add {name} --provider virtualbox".format(
name=name)
result = ""
if name is None:
pass
return "ERROR: please specify an image name"
# read name form config
else:
try:
command = "vagrant box add {name} --provider virtualbox".format(
name=name)
result = Shell.live(command)
assert result.status == 0
except Exception as e:
print(e)
print(result)
print()
return result
def _check_version(self, r):
"""
checks if vagrant version is up to date
:return:
"""
return "A new version of Vagrant is available" not in r
def start(self, name):
"""
start a node
:param name: the unique node name
:return: The dict representing the node
"""
pass
def vagrant_nodes(self, verbose=False):
"""
list all nodes id
:return: an array of dicts representing the nodes
"""
def convert(data_line):
entry = (' '.join(data_line.split())).split(' ')
data = dotdict()
data.id = entry[0]
data.name = entry[1]
data.provider = entry[2]
data.state = entry[3]
data.directory = entry[4]
data = self.update_dict(data, kind="node")
return data
result = Shell.execute("vagrant global-status --prune", shell=True)
if verbose:
print(result)
if "There are no active" in result:
return None
lines = []
for line in result.split("\n")[2:]:
if line == " ":
break
else:
lines.append(convert(line))
return lines
def create(self, **kwargs):
arg = dotdict(kwargs)
arg.cwd = kwargs.get("cwd", None)
# get the dir based on name
print("ARG")
pprint(arg)
vms = self.to_dict(self.vagrant_nodes())
print("VMS", vms)
arg = self._get_specification(**kwargs)
pprint(arg)
if arg.name in vms:
Console.error("vm {name} already booted".format(**arg),
traceflag=False)
return None
else:
self.create_spec(**kwargs)
Console.ok("{name} created".format(**arg))
Console.ok("{directory}/{name} booting ...".format(**arg))
result = None
result = Shell.live("vagrant up " + arg.name,
cwd=arg.directory)
Console.ok("{name} ok.".format(**arg))
return result
def execute(self, name, command, cwd=None):
arg = dotdict()
arg.cwd = cwd
arg.command = command
arg.name = name
config = Config()
cloud = "vagrant" # TODO: must come through parameter or set cloud
arg.path = config.data["cloudmesh"]["cloud"][cloud]["default"][
"path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
vms = self.to_dict(self.vagrant_nodes())
arg = "ssh {} -c {}".format(name, command)
result = Shell.execute("vagrant", ["ssh", name, "-c", command],
cwd=arg.directory,
shell=True)
return result
def to_dict(self, lst, id="name"):
d = {}
if lst is not None:
for entry in lst:
d[entry[id]] = entry
return d
def _convert_assignment_to_dict(self, content):
d = {}
lines = content.split("\n")
for line in lines:
attribute, value = line.split("=", 1)
attribute = attribute.replace('"', "")
attribute = attribute.replace(' ', "_")
attribute = attribute.replace('-', "_")
attribute = attribute.replace('-', "_")
attribute = attribute.replace('/', "_")
attribute = attribute.replace(')', "")
attribute = attribute.replace('(', "-")
attribute = attribute.replace(']', "")
attribute = attribute.replace('[', "_")
value = value.replace('"', "")
d[attribute] = value
return d
def find(self, nodes=None, name=None):
if nodes is None:
nodes = self.vagrant_nodes()
pprint(nodes)
if name in nodes:
return nodes[name]
return None
def info(self, name=None):
"""
gets the information of a node with a given name
:param name:
:return: The dict representing the node including updated status
"""
arg = dotdict()
arg.name = name
config = Config()
cloud = "vagrant" # TODO: must come through parameter or set cloud
arg.path = config.data["cloudmesh"]["cloud"][cloud]["default"][
"path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
result = None
vms = Shell.execute(self.vboxmanage + " list vms", shell=True).replace(
'"', '').replace('{', '').replace('}', '').split("\n")
vagrant_data = self.to_dict(self.vagrant_nodes())
data = {}
for entry in vagrant_data:
data[entry] = {
"vagrant": vagrant_data[entry]
}
for line in vms:
vbox_name, id = line.split(" ")
vagrant_name = vbox_name.split("_")[0]
data[vagrant_name]["name"] = vagrant_name
data[vagrant_name]["vbox_name"] = vbox_name
data[vagrant_name]["id"] = id
vms = data
#
# find vm
#
vbox_name_prefix = "{name}_{name}_".format(**arg)
# print (vbox_name_prefix)
details = None
for vm in vms:
vbox_name = vms[vm]["vbox_name"]
details = Shell.execute(
self.vboxmanage + " showvminfo --machinereadable " + vbox_name,
shell=True)
data[vm]["vbox"] = self._convert_assignment_to_dict(details)
for vm in data:
directory = path_expand(
"~/.cloudmesh/vagrant/{name}".format(name=vm))
data[vm]["cm"] = {
"name": vm,
"directory": arg.directory,
"path": arg.path,
"cloud": cloud,
"status": data[vm]["vagrant"]['state']
}
data[vm] = self.update_dict(data[vm], kind="node")
result = Shell.execute("vagrant ssh-config",
cwd=directory,
traceflag=False,
witherror=False,
shell=True)
if result is not None:
lines = result.split("\n")
for line in lines:
attribute, value = line.strip().split(" ")
attribute = attribute.lower()
data[vm]['vagrant'][attribute] = value
if name is not None:
return data[name]
result = []
for d in data:
print(d)
result.append(data[d])
return result
def suspend(self, name=None):
"""
NOT IMPLEMENTED
suspends the node with the given name
:param name: the name of the node
:return: The dict representing the node
"""
# TODO: find last name if name is None
arg = dotdict()
arg.name = name
# TODO find the vbx name from vagrantname
arg.path = self.default["path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
result = Shell.execute("vbox", ["suspend", name], cwd=arg.directory,
shell=True)
return result
def resume(self, name=None):
"""
NOT IMPLEMENTED
Default: resume(start) all the VMs specified.
If @name is provided, only the named VM is started.
:param name: [optional], name of the Vagrant VM.
:return:
"""
# TODO: find last name if name is None
arg = dotdict()
arg.name = name
# TODO find the vbx name from vagrantname
arg.path = self.default["path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
result = Shell.execute("vbox", ["up", name], cwd=arg.directory,
shell=True)
return result
def resume(self, name=None):
"""
resume the named node
:param name: the name of the node
:return: the dict of the node
"""
# TODO: find last name if name is None
result = Shell.execute("vagrant", ["resume", name], shell=True)
return result
def stop(self, name=None):
"""
NOT IMPLEMENTED
stops the node with the given name
:param name: the name of the node
:return: The dict representing the node
"""
# TODO: find last name if name is None
arg = dotdict()
arg.name = name
# TODO find the vbx name from vagrantname
arg.path = self.default["path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
result = Shell.execute("vbox", ["stop", name], cwd=arg.directory,
shell=True)
return result
def destroy(self, name=None):
"""
Destroys the node
:param name: the name of the node
:return: the dict of the node
"""
self.delete(name=name)
# @classmethod
def delete(self, name=None):
# TODO: check
arg = dotdict()
arg.name = name
arg.path = self.default["path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
result = Shell.execute("vagrant",
["destroy", "-f", name],
cwd=arg.directory, shell=True)
return result
def vagrantfile(self, **kwargs):
arg = dotdict(kwargs)
provision = kwargs.get("script", None)
if provision is not None:
arg.provision = 'config.vm.provision "shell", inline: <<-SHELL\n'
for line in textwrap.dedent(provision).split("\n"):
if line.strip() != "":
arg.provision += 12 * " " + " " + line + "\n"
arg.provision += 12 * " " + " " + "SHELL\n"
else:
arg.provision = ""
# not sure how I2 gets found TODO verify, comment bellow is not enough
# the 12 is derived from the indentation of Vagrant in the script
# TODO we may need not just port 80 to forward
script = textwrap.dedent("""
Vagrant.configure(2) do |config|
config.vm.define "{name}"
config.vm.hostname = "{name}"
config.vm.box = "{image}"
config.vm.box_check_update = true
config.vm.network "forwarded_port", guest: 80, host: {port}
config.vm.network "private_network", type: "dhcp"
# config.vm.network "public_network"
# config.vm.synced_folder "../data", "/vagrant_data"
config.vm.provider "virtualbox" do |vb|
# vb.gui = true
vb.memory = "{memory}"
end
{provision}
end
""".format(**arg))
return script
def _get_specification(self, cloud=None, name=None, port=None,
image=None, **kwargs):
arg = dotdict(kwargs)
arg.port = port
config = Config()
pprint(self.config)
if cloud is None:
#
# TOD read default cloud
#
cloud = "vagrant" # TODO must come through parameter or set cloud
spec = config.data["cloudmesh"]["cloud"][cloud]
default = spec["default"]
pprint(default)
if name is not None:
arg.name = name
else:
# TODO get new name
pass
if image is not None:
arg.image = image
else:
arg.image = default["image"]
pass
arg.path = default["path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
arg.vagrantfile = "{directory}/Vagrantfile".format(**arg)
return arg
def create_spec(self, name=None, image=None, size=1024, timeout=360,
port=80,
**kwargs):
"""
creates a named node
:param port:
:param name: the name of the node
:param image: the image used
:param size: the size of the image
:param timeout: a timeout in seconds that is invoked in case the image
does not boot. The default is set to 3 minutes.
:param kwargs: additional arguments passed along at time of boot
:return:
"""
"""
create one node
"""
#
# TODO BUG: if name contains not just letters and numbers and -
# return error, e. underscore not allowed
#
arg = self._get_specification(name=name,
image=image,
size=size,
memory=size,
timeout=timeout,
port=port,
**kwargs)
if not os.path.exists(arg.directory):
os.makedirs(arg.directory)
configuration = self.vagrantfile(**arg)
with open(arg.vagrantfile, 'w') as f:
f.write(configuration)
pprint(arg)
return arg
#
# Additional methods
#
@classmethod
def find_image(cls, keywords):
"""
Finds an image on hashicorps web site
:param keywords: The keywords to narrow down the search
"""
key = '+'.join(keywords)
location = "https://app.vagrantup.com/boxes/search"
link = \
f"{location}?utf8=%E2%9C%93&sort=downloads&provider=&q=\"{key}\""
webbrowser.open(link, new=2, autoraise=True)
def list(self, raw=True):
"""
list all nodes id
:return: an array of dicts representing the nodes
"""
result = None
if raw:
result = self.info()
else:
result = self.vagrant_nodes()
return result
def rename(self, name=None, destination=None):
"""
rename a node
:param destination:
:param name: the current name
:return: the dict with the new name
"""
arguments = ['modifyvm', '"', name, '"', "--name", '"', destination,
'"']
vms = Shell.execute(self.vboxmanage, arguments, shell=True).split("\n")
return {}
def list_os(self):
"""
:return: the dict with the new name
"""
result = Shell.execute(self.vboxmanage + " list ostypes", shell=True)
data = {}
result = result.split("\n\n")
entries = {}
id = "None"
for element in result:
attributes = element.split("\n")
for a in attributes:
attribute, value = a.split(":")
value = value.strip()
attribute = attribute.lower()
attribute = attribute.replace(" ", "_")
print(">>>>", attribute, value)
if attribute == "id":
id = value
entries[id] = {}
entries[id][attribute] = value
return entries
def key_upload(self, key):
raise NotImplementedError
| import os
import platform
import shlex
import subprocess
import sys
import textwrap
import webbrowser
from pprint import pprint
from cloudmesh.abstractclass.ComputeNodeABC import ComputeNodeABC
from cloudmesh.common.Shell import Shell
from cloudmesh.common.console import Console
from cloudmesh.common.dotdict import dotdict
from cloudmesh.common.util import path_expand
# from cloudmesh.abstractclass import ComputeNodeManagerABC
from cloudmesh.configuration.Config import Config
"""
is vagrant up to date
==> vagrant: A new version of Vagrant is available: 2.2.4 (installed version: 2.2.2)!
==> vagrant: To upgrade visit: https://www.vagrantup.com/downloads.html
"""
class Provider(ComputeNodeABC):
kind = "virtualbox"
def run_command(self, command):
process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
while True:
output = process.stdout.read(1)
if output == b'' and process.poll() is not None:
break
if output:
sys.stdout.write(output.decode("utf-8"))
sys.stdout.flush()
rc = process.poll()
return rc
def update_dict(self, entry, kind="node"):
if "cm" not in entry:
entry["cm"] = {}
entry["cm"]["kind"] = kind
entry["cm"]["driver"] = self.cloudtype
entry["cm"]["cloud"] = self.cloud
return entry
output = {
'vm': {
"sort_keys": ["cm.name"],
'order': ["vagrant.name",
"vagrant.cloud",
"vbox.name",
"vagrant.id",
"vagrant.provider",
"vagrant.state",
"vagrant.hostname"],
'header': ["Name",
"Cloud",
"Vbox",
"Id",
"Provider",
"State",
"Hostname"]
},
'image': None,
'flavor': None
}
def __init__(self, name=None,
configuration="~/.cloudmesh/.cloudmesh.yaml"):
self.config = Config()
conf = Config(configuration)["cloudmesh"]
self.user = conf["profile"]
self.spec = conf["cloud"][name]
self.cloud = name
cred = self.spec["credentials"]
self.cloudtype = self.spec["cm"]["kind"]
if platform.system().lower() == "darwin":
self.vboxmanage = \
"/Applications/VirtualBox.app/Contents/MacOS/VBoxManage"
else:
self.vboxmanage = "VBoxManage"
# m = MongoDBController()
# status = m.status()
# if status.status == "error":
# raise Exception("ERROR: MongoDB is not running.")
#
# BUG: Naturally the following is wrong as it depends on the name.
#
# super().__init__("vagrant", config)
# noinspection PyPep8
def version(self):
"""
This command returns the versions ov vagrant and virtual box
:return: A dict with the information
Description:
The output looks like this
{'vagrant': '2.2.4',
'virtualbox': {'extension': {
'description': 'USB 2.0 and USB 3.0 Host '
'Controller, Host Webcam, '
'VirtualBox RDP, PXE ROM, Disk '
'Encryption, NVMe.',
'extensionpack': True,
'revision': '128413',
'usable': 'true',
'version': '6.0.4'},
'version': '6.0.4'}}
"""
version = {
"vagrant": None,
"virtualbox": {
"version": None,
"extension": None
}
}
try:
result = Shell.execute("vagrant --version", shell=True)
txt, version["vagrant"] = result.split(" ")
if "A new version of Vagrant is available" in result:
Console.error(
"Vagrant is outdated. Please download a new version of "
"vagrant")
raise NotImplementedError
except:
pass
try:
result = Shell.execute(self.vboxmanage, shell=True)
txt, version["virtualbox"]["version"] = result.split("\n")[0].split(
"Version ")
result = Shell.execute(self.vboxmanage + " list -l extpacks",
shell=True)
extension = {}
for line in result.split("\n"):
if "Oracle VM VirtualBox Extension Pack" in line:
extension["extensionpack"] = True
elif "Revision:" in line:
extension["revision"] = line.split(":")[1].strip()
elif "Usable:" in line:
extension["usable"] = line.split(":")[1].strip()
elif "Description:" in line:
extension["description"] = line.split(":")[1].strip()
elif "Version:" in line:
extension["version"] = line.split(":")[1].strip()
version["virtualbox"]["extension"] = extension
except:
pass
return version
def images(self):
def convert(data_line):
data_line = data_line.replace("(", ",")
data_line = data_line.replace(")", ",")
data_entry = data_line.split(",")
data = dotdict()
data.name = data_entry[0].strip()
data.provider = data_entry[1].strip()
data.version = data_entry[2].strip()
data = self.update_dict(data, kind="image")
return data
result = Shell.execute("vagrant box list", shell=True)
if "There are no installed boxes" in result:
return None
else:
result = result.split("\n")
lines = []
for line in result:
entry = convert(line)
if "date" in entry:
date = entry["date"]
lines.append(entry)
return lines
def delete_image(self, name=None):
result = ""
if name is None:
pass
return "ERROR: please specify an image name"
# read name form config
else:
try:
command = "vagrant box remove {name}".format(name=name)
result = Shell.execute(command, shell=True)
except Exception as e:
print(e)
return result
def add_image(self, name=None):
command = "vagrant box add {name} --provider virtualbox".format(
name=name)
result = ""
if name is None:
pass
return "ERROR: please specify an image name"
# read name form config
else:
try:
command = "vagrant box add {name} --provider virtualbox".format(
name=name)
result = Shell.live(command)
assert result.status == 0
except Exception as e:
print(e)
print(result)
print()
return result
def _check_version(self, r):
"""
checks if vagrant version is up to date
:return:
"""
return "A new version of Vagrant is available" not in r
def start(self, name):
"""
start a node
:param name: the unique node name
:return: The dict representing the node
"""
pass
def vagrant_nodes(self, verbose=False):
"""
list all nodes id
:return: an array of dicts representing the nodes
"""
def convert(data_line):
entry = (' '.join(data_line.split())).split(' ')
data = dotdict()
data.id = entry[0]
data.name = entry[1]
data.provider = entry[2]
data.state = entry[3]
data.directory = entry[4]
data = self.update_dict(data, kind="node")
return data
result = Shell.execute("vagrant global-status --prune", shell=True)
if verbose:
print(result)
if "There are no active" in result:
return None
lines = []
for line in result.split("\n")[2:]:
if line == " ":
break
else:
lines.append(convert(line))
return lines
def create(self, **kwargs):
arg = dotdict(kwargs)
arg.cwd = kwargs.get("cwd", None)
# get the dir based on name
print("ARG")
pprint(arg)
vms = self.to_dict(self.vagrant_nodes())
print("VMS", vms)
arg = self._get_specification(**kwargs)
pprint(arg)
if arg.name in vms:
Console.error("vm {name} already booted".format(**arg),
traceflag=False)
return None
else:
self.create_spec(**kwargs)
Console.ok("{name} created".format(**arg))
Console.ok("{directory}/{name} booting ...".format(**arg))
result = None
result = Shell.live("vagrant up " + arg.name,
cwd=arg.directory)
Console.ok("{name} ok.".format(**arg))
return result
def execute(self, name, command, cwd=None):
arg = dotdict()
arg.cwd = cwd
arg.command = command
arg.name = name
config = Config()
cloud = "vagrant" # TODO: must come through parameter or set cloud
arg.path = config.data["cloudmesh"]["cloud"][cloud]["default"][
"path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
vms = self.to_dict(self.vagrant_nodes())
arg = "ssh {} -c {}".format(name, command)
result = Shell.execute("vagrant", ["ssh", name, "-c", command],
cwd=arg.directory,
shell=True)
return result
def to_dict(self, lst, id="name"):
d = {}
if lst is not None:
for entry in lst:
d[entry[id]] = entry
return d
def _convert_assignment_to_dict(self, content):
d = {}
lines = content.split("\n")
for line in lines:
attribute, value = line.split("=", 1)
attribute = attribute.replace('"', "")
attribute = attribute.replace(' ', "_")
attribute = attribute.replace('-', "_")
attribute = attribute.replace('-', "_")
attribute = attribute.replace('/', "_")
attribute = attribute.replace(')', "")
attribute = attribute.replace('(', "-")
attribute = attribute.replace(']', "")
attribute = attribute.replace('[', "_")
value = value.replace('"', "")
d[attribute] = value
return d
def find(self, nodes=None, name=None):
if nodes is None:
nodes = self.vagrant_nodes()
pprint(nodes)
if name in nodes:
return nodes[name]
return None
def info(self, name=None):
"""
gets the information of a node with a given name
:param name:
:return: The dict representing the node including updated status
"""
arg = dotdict()
arg.name = name
config = Config()
cloud = "vagrant" # TODO: must come through parameter or set cloud
arg.path = config.data["cloudmesh"]["cloud"][cloud]["default"][
"path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
result = None
vms = Shell.execute(self.vboxmanage + " list vms", shell=True).replace(
'"', '').replace('{', '').replace('}', '').split("\n")
vagrant_data = self.to_dict(self.vagrant_nodes())
data = {}
for entry in vagrant_data:
data[entry] = {
"vagrant": vagrant_data[entry]
}
for line in vms:
vbox_name, id = line.split(" ")
vagrant_name = vbox_name.split("_")[0]
data[vagrant_name]["name"] = vagrant_name
data[vagrant_name]["vbox_name"] = vbox_name
data[vagrant_name]["id"] = id
vms = data
#
# find vm
#
vbox_name_prefix = "{name}_{name}_".format(**arg)
# print (vbox_name_prefix)
details = None
for vm in vms:
vbox_name = vms[vm]["vbox_name"]
details = Shell.execute(
self.vboxmanage + " showvminfo --machinereadable " + vbox_name,
shell=True)
data[vm]["vbox"] = self._convert_assignment_to_dict(details)
for vm in data:
directory = path_expand(
"~/.cloudmesh/vagrant/{name}".format(name=vm))
data[vm]["cm"] = {
"name": vm,
"directory": arg.directory,
"path": arg.path,
"cloud": cloud,
"status": data[vm]["vagrant"]['state']
}
data[vm] = self.update_dict(data[vm], kind="node")
result = Shell.execute("vagrant ssh-config",
cwd=directory,
traceflag=False,
witherror=False,
shell=True)
if result is not None:
lines = result.split("\n")
for line in lines:
attribute, value = line.strip().split(" ")
attribute = attribute.lower()
data[vm]['vagrant'][attribute] = value
if name is not None:
return data[name]
result = []
for d in data:
print(d)
result.append(data[d])
return result
def suspend(self, name=None):
"""
NOT IMPLEMENTED
suspends the node with the given name
:param name: the name of the node
:return: The dict representing the node
"""
# TODO: find last name if name is None
arg = dotdict()
arg.name = name
# TODO find the vbx name from vagrantname
arg.path = self.default["path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
result = Shell.execute("vbox", ["suspend", name], cwd=arg.directory,
shell=True)
return result
def resume(self, name=None):
"""
NOT IMPLEMENTED
Default: resume(start) all the VMs specified.
If @name is provided, only the named VM is started.
:param name: [optional], name of the Vagrant VM.
:return:
"""
# TODO: find last name if name is None
arg = dotdict()
arg.name = name
# TODO find the vbx name from vagrantname
arg.path = self.default["path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
result = Shell.execute("vbox", ["up", name], cwd=arg.directory,
shell=True)
return result
def resume(self, name=None):
"""
resume the named node
:param name: the name of the node
:return: the dict of the node
"""
# TODO: find last name if name is None
result = Shell.execute("vagrant", ["resume", name], shell=True)
return result
def stop(self, name=None):
"""
NOT IMPLEMENTED
stops the node with the given name
:param name: the name of the node
:return: The dict representing the node
"""
# TODO: find last name if name is None
arg = dotdict()
arg.name = name
# TODO find the vbx name from vagrantname
arg.path = self.default["path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
result = Shell.execute("vbox", ["stop", name], cwd=arg.directory,
shell=True)
return result
def destroy(self, name=None):
"""
Destroys the node
:param name: the name of the node
:return: the dict of the node
"""
self.delete(name=name)
# @classmethod
def delete(self, name=None):
# TODO: check
arg = dotdict()
arg.name = name
arg.path = self.default["path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
result = Shell.execute("vagrant",
["destroy", "-f", name],
cwd=arg.directory, shell=True)
return result
def vagrantfile(self, **kwargs):
arg = dotdict(kwargs)
provision = kwargs.get("script", None)
if provision is not None:
arg.provision = 'config.vm.provision "shell", inline: <<-SHELL\n'
for line in textwrap.dedent(provision).split("\n"):
if line.strip() != "":
arg.provision += 12 * " " + " " + line + "\n"
arg.provision += 12 * " " + " " + "SHELL\n"
else:
arg.provision = ""
# not sure how I2 gets found TODO verify, comment bellow is not enough
# the 12 is derived from the indentation of Vagrant in the script
# TODO we may need not just port 80 to forward
script = textwrap.dedent("""
Vagrant.configure(2) do |config|
config.vm.define "{name}"
config.vm.hostname = "{name}"
config.vm.box = "{image}"
config.vm.box_check_update = true
config.vm.network "forwarded_port", guest: 80, host: {port}
config.vm.network "private_network", type: "dhcp"
# config.vm.network "public_network"
# config.vm.synced_folder "../data", "/vagrant_data"
config.vm.provider "virtualbox" do |vb|
# vb.gui = true
vb.memory = "{memory}"
end
{provision}
end
""".format(**arg))
return script
def _get_specification(self, cloud=None, name=None, port=None,
image=None, **kwargs):
arg = dotdict(kwargs)
arg.port = port
config = Config()
pprint(self.config)
if cloud is None:
#
# TOD read default cloud
#
cloud = "vagrant" # TODO must come through parameter or set cloud
spec = config.data["cloudmesh"]["cloud"][cloud]
default = spec["default"]
pprint(default)
if name is not None:
arg.name = name
else:
# TODO get new name
pass
if image is not None:
arg.image = image
else:
arg.image = default["image"]
pass
arg.path = default["path"]
arg.directory = os.path.expanduser("{path}/{name}".format(**arg))
arg.vagrantfile = "{directory}/Vagrantfile".format(**arg)
return arg
def create_spec(self, name=None, image=None, size=1024, timeout=360,
port=80,
**kwargs):
"""
creates a named node
:param port:
:param name: the name of the node
:param image: the image used
:param size: the size of the image
:param timeout: a timeout in seconds that is invoked in case the image
does not boot. The default is set to 3 minutes.
:param kwargs: additional arguments passed along at time of boot
:return:
"""
"""
create one node
"""
#
# TODO BUG: if name contains not just letters and numbers and -
# return error, e. underscore not allowed
#
arg = self._get_specification(name=name,
image=image,
size=size,
memory=size,
timeout=timeout,
port=port,
**kwargs)
if not os.path.exists(arg.directory):
os.makedirs(arg.directory)
configuration = self.vagrantfile(**arg)
with open(arg.vagrantfile, 'w') as f:
f.write(configuration)
pprint(arg)
return arg
#
# Additional methods
#
@classmethod
def find_image(cls, keywords):
"""
Finds an image on hashicorps web site
:param keywords: The keywords to narrow down the search
"""
key = '+'.join(keywords)
location = "https://app.vagrantup.com/boxes/search"
link = \
f"{location}?utf8=%E2%9C%93&sort=downloads&provider=&q=\"{key}\""
webbrowser.open(link, new=2, autoraise=True)
def list(self, raw=True):
"""
list all nodes id
:return: an array of dicts representing the nodes
"""
result = None
if raw:
result = self.info()
else:
result = self.vagrant_nodes()
return result
def rename(self, name=None, destination=None):
"""
rename a node
:param destination:
:param name: the current name
:return: the dict with the new name
"""
arguments = ['modifyvm', '"', name, '"', "--name", '"', destination,
'"']
vms = Shell.execute(self.vboxmanage, arguments, shell=True).split("\n")
return {}
def list_os(self):
"""
:return: the dict with the new name
"""
result = Shell.execute(self.vboxmanage + " list ostypes", shell=True)
data = {}
result = result.split("\n\n")
entries = {}
id = "None"
for element in result:
attributes = element.split("\n")
for a in attributes:
attribute, value = a.split(":")
value = value.strip()
attribute = attribute.lower()
attribute = attribute.replace(" ", "_")
print(">>>>", attribute, value)
if attribute == "id":
id = value
entries[id] = {}
entries[id][attribute] = value
return entries
def key_upload(self, key):
raise NotImplementedError
| en | 0.627699 | # from cloudmesh.abstractclass import ComputeNodeManagerABC is vagrant up to date ==> vagrant: A new version of Vagrant is available: 2.2.4 (installed version: 2.2.2)! ==> vagrant: To upgrade visit: https://www.vagrantup.com/downloads.html # m = MongoDBController() # status = m.status() # if status.status == "error": # raise Exception("ERROR: MongoDB is not running.") # # BUG: Naturally the following is wrong as it depends on the name. # # super().__init__("vagrant", config) # noinspection PyPep8 This command returns the versions ov vagrant and virtual box :return: A dict with the information Description: The output looks like this {'vagrant': '2.2.4', 'virtualbox': {'extension': { 'description': 'USB 2.0 and USB 3.0 Host ' 'Controller, Host Webcam, ' 'VirtualBox RDP, PXE ROM, Disk ' 'Encryption, NVMe.', 'extensionpack': True, 'revision': '128413', 'usable': 'true', 'version': '6.0.4'}, 'version': '6.0.4'}} # read name form config # read name form config checks if vagrant version is up to date :return: start a node :param name: the unique node name :return: The dict representing the node list all nodes id :return: an array of dicts representing the nodes # get the dir based on name # TODO: must come through parameter or set cloud gets the information of a node with a given name :param name: :return: The dict representing the node including updated status # TODO: must come through parameter or set cloud # # find vm # # print (vbox_name_prefix) NOT IMPLEMENTED suspends the node with the given name :param name: the name of the node :return: The dict representing the node # TODO: find last name if name is None # TODO find the vbx name from vagrantname NOT IMPLEMENTED Default: resume(start) all the VMs specified. If @name is provided, only the named VM is started. :param name: [optional], name of the Vagrant VM. :return: # TODO: find last name if name is None # TODO find the vbx name from vagrantname resume the named node :param name: the name of the node :return: the dict of the node # TODO: find last name if name is None NOT IMPLEMENTED stops the node with the given name :param name: the name of the node :return: The dict representing the node # TODO: find last name if name is None # TODO find the vbx name from vagrantname Destroys the node :param name: the name of the node :return: the dict of the node # @classmethod # TODO: check # not sure how I2 gets found TODO verify, comment bellow is not enough # the 12 is derived from the indentation of Vagrant in the script # TODO we may need not just port 80 to forward Vagrant.configure(2) do |config| config.vm.define "{name}" config.vm.hostname = "{name}" config.vm.box = "{image}" config.vm.box_check_update = true config.vm.network "forwarded_port", guest: 80, host: {port} config.vm.network "private_network", type: "dhcp" # config.vm.network "public_network" # config.vm.synced_folder "../data", "/vagrant_data" config.vm.provider "virtualbox" do |vb| # vb.gui = true vb.memory = "{memory}" end {provision} end # # TOD read default cloud # # TODO must come through parameter or set cloud # TODO get new name creates a named node :param port: :param name: the name of the node :param image: the image used :param size: the size of the image :param timeout: a timeout in seconds that is invoked in case the image does not boot. The default is set to 3 minutes. :param kwargs: additional arguments passed along at time of boot :return: create one node # # TODO BUG: if name contains not just letters and numbers and - # return error, e. underscore not allowed # # # Additional methods # Finds an image on hashicorps web site :param keywords: The keywords to narrow down the search list all nodes id :return: an array of dicts representing the nodes rename a node :param destination: :param name: the current name :return: the dict with the new name :return: the dict with the new name | 2.143303 | 2 |
nautilus/api/util/arg_string_from_dict.py | AlecAivazis/python | 9 | 6616141 | import json
def arg_string_from_dict(arg_dict, **kwds):
"""
This function takes a series of ditionaries and creates an argument
string for a graphql query
"""
# the filters dictionary
filters = {
**arg_dict,
**kwds,
}
# return the correctly formed string
return ", ".join("{}: {}".format(key, json.dumps(value)) for key,value in filters.items()) | import json
def arg_string_from_dict(arg_dict, **kwds):
"""
This function takes a series of ditionaries and creates an argument
string for a graphql query
"""
# the filters dictionary
filters = {
**arg_dict,
**kwds,
}
# return the correctly formed string
return ", ".join("{}: {}".format(key, json.dumps(value)) for key,value in filters.items()) | en | 0.627948 | This function takes a series of ditionaries and creates an argument string for a graphql query # the filters dictionary # return the correctly formed string | 3.270313 | 3 |
dydx3/constants.py | byte-trading/dydx-v3-python | 0 | 6616142 | <gh_stars>0
# ------------ API URLs ------------
API_HOST_MAINNET = 'https://api.dydx.exchange'
API_HOST_ROPSTEN = 'https://api.stage.dydx.exchange'
WS_HOST_MAINNET = 'wss://api.dydx.exchange/v3/ws'
WS_HOST_ROPSTEN = 'wss://api.stage.dydx.exchange/v3/ws'
# ------------ Ethereum Network IDs ------------
NETWORK_ID_MAINNET = 1
NETWORK_ID_ROPSTEN = 3
# ------------ Signature Types ------------
SIGNATURE_TYPE_NO_PREPEND = 0
SIGNATURE_TYPE_DECIMAL = 1
SIGNATURE_TYPE_HEXADECIMAL = 2
# ------------ Market Statistic Day Types ------------
MARKET_STATISTIC_DAY_ONE = '1'
MARKET_STATISTIC_DAY_SEVEN = '7'
MARKET_STATISTIC_DAY_THIRTY = '30'
# ------------ Order Types ------------
ORDER_TYPE_LIMIT = 'LIMIT'
ORDER_TYPE_MARKET = 'MARKET'
ORDER_TYPE_STOP = 'STOP_LIMIT'
ORDER_TYPE_TRAILING_STOP = 'TRAILING_STOP'
ORDER_TYPE_TAKE_PROFIT = 'TAKE_PROFIT'
# ------------ Order Side ------------
ORDER_SIDE_BUY = 'BUY'
ORDER_SIDE_SELL = 'SELL'
# ------------ Time in Force Types ------------
TIME_IN_FORCE_GTT = 'GTT'
TIME_IN_FORCE_FOK = 'FOK'
TIME_IN_FORCE_IOC = 'IOC'
# ------------ Position Status Types ------------
POSITION_STATUS_OPEN = 'OPEN'
POSITION_STATUS_CLOSED = 'CLOSED'
POSITION_STATUS_LIQUIDATED = 'LIQUIDATED'
# ------------ Order Status Types ------------
ORDER_STATUS_PENDING = 'PENDING'
ORDER_STATUS_OPEN = 'OPEN'
ORDER_STATUS_FILLED = 'FILLED'
ORDER_STATUS_CANCELED = 'CANCELED'
ORDER_STATUS_UNTRIGGERED = 'UNTRIGGERED'
# ------------ Transfer Status Types ------------
TRANSFER_STATUS_PENDING = 'PENDING'
TRANSFER_STATUS_CONFIRMED = 'CONFIRMED'
TRANSFER_STATUS_QUEUED = 'QUEUED'
TRANSFER_STATUS_CANCELED = 'CANCELED'
TRANSFER_STATUS_UNCONFIRMED = 'UNCONFIRMED'
# ------------ Account Action Types ------------
ACCOUNT_ACTION_DEPOSIT = 'DEPOSIT'
ACCOUNT_ACTION_WITHDRAWAL = 'WITHDRAWAL'
# ------------ Markets ------------
MARKET_BTC_USD = 'BTC-USD'
MARKET_ETH_USD = 'ETH-USD'
MARKET_LINK_USD = 'LINK-USD'
MARKET_AAVE_USD = 'AAVE-USD'
MARKET_UNI_USD = 'UNI-USD'
MARKET_SUSHI_USD = 'SUSHI-USD'
MARKET_SOL_USD = 'SOL-USD'
MARKET_YFI_USD = 'YFI-USD'
MARKET_ONEINCH_USD = '1INCH-USD'
MARKET_AVAX_USD = 'AVAX-USD'
MARKET_SNX_USD = 'SNX-USD'
MARKET_CRV_USD = 'CRV-USD'
MARKET_UMA_USD = 'UMA-USD'
MARKET_DOT_USD = 'DOT-USD'
MARKET_DOGE_USD = 'DOGE-USD'
MARKET_MATIC_USD = 'MATIC-USD'
MARKET_MKR_USD = 'MKR-USD'
MARKET_FIL_USD = 'FIL-USD'
MARKET_ADA_USD = 'ADA-USD'
MARKET_ATOM_USD = 'ATOM-USD'
MARKET_COMP_USD = 'COMP-USD'
MARKET_BCH_USD = 'BCH-USD'
MARKET_LTC_USD = 'LTC-USD'
MARKET_EOS_USD = 'EOS-USD'
MARKET_ALGO_USD = 'ALGO-USD'
MARKET_ZRX_USD = 'ZRX-USD'
MARKET_XMR_USD = 'XMR-USD'
MARKET_ZEC_USD = 'ZEC-USD'
MARKET_ENJ_USD = 'ENJ-USD'
MARKET_ETC_USD = 'ETC-USD'
MARKET_XLM_USD = 'XLM-USD'
MARKET_TRX_USD = 'TRX-USD'
MARKET_XTZ_USD = 'XTZ-USD'
MARKET_HNT_USD = 'HNT-USD'
MARKET_ICP_USD = 'ICP-USD'
MARKET_RUNE_USD = 'RUNE-USD'
MARKET_LUNA_USD = 'LUNA-USD'
MARKET_NEAR_USD = 'NEAR-USD'
MARKET_AR_USD = 'AR-USD'
MARKET_FLOW_USD = 'FLOW-USD'
MARKET_PERP_USD = 'PERP-USD'
MARKET_REN_USD = 'REN-USD'
MARKET_CELO_USD = 'CELO-USD'
MARKET_KSM_USD = 'KSM-USD'
MARKET_BAL_USD = 'BAL-USD'
MARKET_BNT_USD = 'BNT-USD'
MARKET_MIR_USD = 'MIR-USD'
MARKET_SRM_USD = 'SRM-USD'
MARKET_LON_USD = 'LON-USD'
MARKET_DODO_USD = 'DODO-USD'
MARKET_ALPHA_USD = 'ALPHA-USD'
MARKET_WNXM_USD = 'WNXM-USD'
MARKET_XCH_USD = 'XCH-USD'
# ------------ Assets ------------
ASSET_USDC = 'USDC'
ASSET_BTC = 'BTC'
ASSET_ETH = 'ETH'
ASSET_LINK = 'LINK'
ASSET_AAVE = 'AAVE'
ASSET_UNI = 'UNI'
ASSET_SUSHI = 'SUSHI'
ASSET_SOL = 'SOL'
ASSET_YFI = 'YFI'
ASSET_ONEINCH = '1INCH'
ASSET_AVAX = 'AVAX'
ASSET_SNX = 'SNX'
ASSET_CRV = 'CRV'
ASSET_UMA = 'UMA'
ASSET_DOT = 'DOT'
ASSET_DOGE = 'DOGE'
ASSET_MATIC = 'MATIC'
ASSET_MKR = 'MKR'
ASSET_FIL = 'FIL'
ASSET_ADA = 'ADA'
ASSET_ATOM = 'ATOM'
ASSET_COMP = 'COMP'
ASSET_BCH = 'BCH'
ASSET_LTC = 'LTC'
ASSET_EOS = 'EOS'
ASSET_ALGO = 'ALGO'
ASSET_ZRX = 'ZRX'
ASSET_XMR = 'XMR'
ASSET_ZEC = 'ZEC'
ASSET_ENJ = 'ENJ'
ASSET_ETC = 'ETC'
ASSET_XLM = 'XLM'
ASSET_TRX = 'TRX'
ASSET_XTZ = 'XTZ'
ASSET_HNT = 'HNT'
ASSET_ICP = 'ICP'
ASSET_RUNE = 'RUNE'
ASSET_LUNA = 'LUNA'
ASSET_NEAR = 'NEAR'
ASSET_AR = 'AR'
ASSET_FLOW = 'FLOW'
ASSET_PERP = 'PERP'
ASSET_REN = 'REN'
ASSET_CELO = 'CELO'
ASSET_KSM = 'KSM'
ASSET_BAL = 'BAL'
ASSET_BNT = 'BNT'
ASSET_MIR = 'MIR'
ASSET_SRM = 'SRM'
ASSET_LON = 'LON'
ASSET_DODO = 'DODO'
ASSET_ALPHA = 'ALPHA'
ASSET_WNXM = 'WNXM'
ASSET_XCH = 'XCH'
COLLATERAL_ASSET = ASSET_USDC
# ------------ Synthetic Assets by Market ------------
SYNTHETIC_ASSET_MAP = {
MARKET_BTC_USD: ASSET_BTC,
MARKET_ETH_USD: ASSET_ETH,
MARKET_LINK_USD: ASSET_LINK,
MARKET_AAVE_USD: ASSET_AAVE,
MARKET_UNI_USD: ASSET_UNI,
MARKET_SUSHI_USD: ASSET_SUSHI,
MARKET_SOL_USD: ASSET_SOL,
MARKET_YFI_USD: ASSET_YFI,
MARKET_ONEINCH_USD: ASSET_ONEINCH,
MARKET_AVAX_USD: ASSET_AVAX,
MARKET_SNX_USD: ASSET_SNX,
MARKET_CRV_USD: ASSET_CRV,
MARKET_UMA_USD: ASSET_UMA,
MARKET_DOT_USD: ASSET_DOT,
MARKET_DOGE_USD: ASSET_DOGE,
MARKET_MATIC_USD: ASSET_MATIC,
MARKET_MKR_USD: ASSET_MKR,
MARKET_FIL_USD: ASSET_FIL,
MARKET_ADA_USD: ASSET_ADA,
MARKET_ATOM_USD: ASSET_ATOM,
MARKET_COMP_USD: ASSET_COMP,
MARKET_BCH_USD: ASSET_BCH,
MARKET_LTC_USD: ASSET_LTC,
MARKET_EOS_USD: ASSET_EOS,
MARKET_ALGO_USD: ASSET_ALGO,
MARKET_ZRX_USD: ASSET_ZRX,
MARKET_XMR_USD: ASSET_XMR,
MARKET_ZEC_USD: ASSET_ZEC,
MARKET_ENJ_USD: ASSET_ENJ,
MARKET_ETC_USD: ASSET_ETC,
MARKET_XLM_USD: ASSET_XLM,
MARKET_TRX_USD: ASSET_TRX,
MARKET_XTZ_USD: ASSET_XTZ,
MARKET_HNT_USD: ASSET_HNT,
MARKET_ICP_USD: ASSET_ICP,
MARKET_RUNE_USD: ASSET_RUNE,
MARKET_LUNA_USD: ASSET_LUNA,
MARKET_NEAR_USD: ASSET_NEAR,
MARKET_AR_USD: ASSET_AR,
MARKET_FLOW_USD: ASSET_FLOW,
MARKET_PERP_USD: ASSET_PERP,
MARKET_REN_USD: ASSET_REN,
MARKET_CELO_USD: ASSET_CELO,
MARKET_KSM_USD: ASSET_KSM,
MARKET_BAL_USD: ASSET_BAL,
MARKET_BNT_USD: ASSET_BNT,
MARKET_MIR_USD: ASSET_MIR,
MARKET_SRM_USD: ASSET_SRM,
MARKET_LON_USD: ASSET_LON,
MARKET_DODO_USD: ASSET_DODO,
MARKET_ALPHA_USD: ASSET_ALPHA,
MARKET_WNXM_USD: ASSET_WNXM,
MARKET_XCH_USD: ASSET_XCH,
}
# ------------ Asset IDs ------------
COLLATERAL_ASSET_ID_BY_NETWORK_ID = {
NETWORK_ID_MAINNET: int(
'0x02893294412a4c8f915f75892b395ebbf6859ec246ec365c3b1f56f47c3a0a5d',
16,
),
NETWORK_ID_ROPSTEN: int(
'0x02c04d8b650f44092278a7cb1e1028c82025dff622db96c934b611b84cc8de5a',
16,
),
}
SYNTHETIC_ASSET_ID_MAP = {
ASSET_BTC: int('0x4254432d3130000000000000000000', 16),
ASSET_ETH: int('0x4554482d3900000000000000000000', 16),
ASSET_LINK: int('0x4c494e4b2d37000000000000000000', 16),
ASSET_AAVE: int('0x414156452d38000000000000000000', 16),
ASSET_UNI: int('0x554e492d3700000000000000000000', 16),
ASSET_SUSHI: int('0x53555348492d370000000000000000', 16),
ASSET_SOL: int('0x534f4c2d3700000000000000000000', 16),
ASSET_YFI: int('0x5946492d3130000000000000000000', 16),
ASSET_ONEINCH: int('0x31494e43482d370000000000000000', 16),
ASSET_AVAX: int('0x415641582d37000000000000000000', 16),
ASSET_SNX: int('0x534e582d3700000000000000000000', 16),
ASSET_CRV: int('0x4352562d3600000000000000000000', 16),
ASSET_UMA: int('0x554d412d3700000000000000000000', 16),
ASSET_DOT: int('0x444f542d3700000000000000000000', 16),
ASSET_DOGE: int('0x444f47452d35000000000000000000', 16),
ASSET_MATIC: int('0x4d415449432d360000000000000000', 16),
ASSET_MKR: int('0x4d4b522d3900000000000000000000', 16),
ASSET_FIL: int('0x46494c2d3700000000000000000000', 16),
ASSET_ADA: int('0x4144412d3600000000000000000000', 16),
ASSET_ATOM: int('0x41544f4d2d37000000000000000000', 16),
ASSET_COMP: int('0x434f4d502d38000000000000000000', 16),
ASSET_BCH: int('0x4243482d3800000000000000000000', 16),
ASSET_LTC: int('0x4c54432d3800000000000000000000', 16),
ASSET_EOS: int('0x454f532d3600000000000000000000', 16),
ASSET_ALGO: int('0x414c474f2d36000000000000000000', 16),
ASSET_ZRX: int('0x5a52582d3600000000000000000000', 16),
ASSET_XMR: int('0x584d522d3800000000000000000000', 16),
ASSET_ZEC: int('0x5a45432d3800000000000000000000', 16),
ASSET_ENJ: int('0x454e4a2d3600000000000000000000', 16),
ASSET_ETC: int('0x4554432d3700000000000000000000', 16),
ASSET_XLM: int('0x584c4d2d3500000000000000000000', 16),
ASSET_TRX: int('0x5452582d3400000000000000000000', 16),
ASSET_XTZ: int('0x58545a2d3600000000000000000000', 16),
ASSET_HNT: int('0x484e542d3700000000000000000000', 16),
ASSET_ICP: int('0x4943502d3700000000000000000000', 16),
ASSET_RUNE: int('0x52554e452d36000000000000000000', 16),
ASSET_LUNA: int('0x4c554e412d36000000000000000000', 16),
ASSET_NEAR: int('0x4e4541522d36000000000000000000', 16),
ASSET_AR: int('0x41522d370000000000000000000000', 16),
ASSET_FLOW: int('0x464c4f572d37000000000000000000', 16),
ASSET_PERP: int('0x504552502d36000000000000000000', 16),
ASSET_REN: int('0x52454e2d3500000000000000000000', 16),
ASSET_CELO: int('0x43454c4f2d36000000000000000000', 16),
ASSET_KSM: int('0x4b534d2d3800000000000000000000', 16),
ASSET_BAL: int('0x42414c2d3700000000000000000000', 16),
ASSET_BNT: int('0x424e542d3600000000000000000000', 16),
ASSET_MIR: int('0x4d49522d3600000000000000000000', 16),
ASSET_SRM: int('0x53524d2d3600000000000000000000', 16),
ASSET_LON: int('0x4c4f4e2d3600000000000000000000', 16),
ASSET_DODO: int('0x444f444f2d36000000000000000000', 16),
ASSET_ALPHA: int('0x414c5048412d350000000000000000', 16),
ASSET_WNXM: int('0x574e584d2d37000000000000000000', 16),
ASSET_XCH: int('0x5843482d3800000000000000000000', 16),
}
# ------------ Asset Resolution (Quantum Size) ------------
#
# The asset resolution is the number of quantums (Starkware units) that fit
# within one "human-readable" unit of the asset. For example, if the asset
# resolution for BTC is 1e10, then the smallest unit representable within
# Starkware is 1e-10 BTC, i.e. 1/100th of a satoshi.
#
# For the collateral asset (USDC), the chosen resolution corresponds to the
# base units of the ERC-20 token. For the other, synthetic, assets, the
# resolutions are chosen such that prices relative to USDC are close to one.
ASSET_RESOLUTION = {
ASSET_USDC: '1e6',
ASSET_BTC: '1e10',
ASSET_ETH: '1e9',
ASSET_LINK: '1e7',
ASSET_AAVE: '1e8',
ASSET_UNI: '1e7',
ASSET_SUSHI: '1e7',
ASSET_SOL: '1e7',
ASSET_YFI: '1e10',
ASSET_ONEINCH: '1e7',
ASSET_AVAX: '1e7',
ASSET_SNX: '1e7',
ASSET_CRV: '1e6',
ASSET_UMA: '1e7',
ASSET_DOT: '1e7',
ASSET_DOGE: '1e5',
ASSET_MATIC: '1e6',
ASSET_MKR: '1e9',
ASSET_FIL: '1e7',
ASSET_ADA: '1e6',
ASSET_ATOM: '1e7',
ASSET_COMP: '1e8',
ASSET_BCH: '1e8',
ASSET_LTC: '1e8',
ASSET_EOS: '1e6',
ASSET_ALGO: '1e6',
ASSET_ZRX: '1e6',
ASSET_XMR: '1e8',
ASSET_ZEC: '1e8',
ASSET_ENJ: '1e6',
ASSET_ETC: '1e7',
ASSET_XLM: '1e5',
ASSET_TRX: '1e4',
ASSET_XTZ: '1e6',
ASSET_HNT: '1e7',
ASSET_ICP: '1e7',
ASSET_RUNE: '1e6',
ASSET_LUNA: '1e6',
ASSET_NEAR: '1e6',
ASSET_AR: '1e7',
ASSET_FLOW: '1e7',
ASSET_PERP: '1e6',
ASSET_REN: '1e5',
ASSET_CELO: '1e6',
ASSET_KSM: '1e8',
ASSET_BAL: '1e7',
ASSET_BNT: '1e6',
ASSET_MIR: '1e6',
ASSET_SRM: '1e6',
ASSET_LON: '1e6',
ASSET_DODO: '1e6',
ASSET_ALPHA: '1e5',
ASSET_WNXM: '1e7',
ASSET_XCH: '1e8',
}
# ------------ Ethereum Transactions ------------
DEFAULT_GAS_AMOUNT = 250000
DEFAULT_GAS_MULTIPLIER = 1.5
DEFAULT_GAS_PRICE = 4000000000
DEFAULT_GAS_PRICE_ADDITION = 3
MAX_SOLIDITY_UINT = 115792089237316195423570985008687907853269984665640564039457584007913129639935 # noqa: E501
FACT_REGISTRY_CONTRACT = {
NETWORK_ID_MAINNET: '0xBE9a129909EbCb954bC065536D2bfAfBd170d27A',
NETWORK_ID_ROPSTEN: '0x8Fb814935f7E63DEB304B500180e19dF5167B50e',
}
STARKWARE_PERPETUALS_CONTRACT = {
NETWORK_ID_MAINNET: '0xD54f502e184B6B739d7D27a6410a67dc462D69c8',
NETWORK_ID_ROPSTEN: '0x014F738EAd8Ec6C50BCD456a971F8B84Cd693BBe',
}
TOKEN_CONTRACTS = {
ASSET_USDC: {
NETWORK_ID_MAINNET: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
NETWORK_ID_ROPSTEN: '0x8707A5bf4C2842d46B31A405Ba41b858C0F876c4',
},
}
COLLATERAL_TOKEN_DECIMALS = 6
# ------------ Off-Chain Ethereum-Signed Actions ------------
OFF_CHAIN_ONBOARDING_ACTION = 'dYdX Onboarding'
OFF_CHAIN_KEY_DERIVATION_ACTION = 'dYdX STARK Key'
| # ------------ API URLs ------------
API_HOST_MAINNET = 'https://api.dydx.exchange'
API_HOST_ROPSTEN = 'https://api.stage.dydx.exchange'
WS_HOST_MAINNET = 'wss://api.dydx.exchange/v3/ws'
WS_HOST_ROPSTEN = 'wss://api.stage.dydx.exchange/v3/ws'
# ------------ Ethereum Network IDs ------------
NETWORK_ID_MAINNET = 1
NETWORK_ID_ROPSTEN = 3
# ------------ Signature Types ------------
SIGNATURE_TYPE_NO_PREPEND = 0
SIGNATURE_TYPE_DECIMAL = 1
SIGNATURE_TYPE_HEXADECIMAL = 2
# ------------ Market Statistic Day Types ------------
MARKET_STATISTIC_DAY_ONE = '1'
MARKET_STATISTIC_DAY_SEVEN = '7'
MARKET_STATISTIC_DAY_THIRTY = '30'
# ------------ Order Types ------------
ORDER_TYPE_LIMIT = 'LIMIT'
ORDER_TYPE_MARKET = 'MARKET'
ORDER_TYPE_STOP = 'STOP_LIMIT'
ORDER_TYPE_TRAILING_STOP = 'TRAILING_STOP'
ORDER_TYPE_TAKE_PROFIT = 'TAKE_PROFIT'
# ------------ Order Side ------------
ORDER_SIDE_BUY = 'BUY'
ORDER_SIDE_SELL = 'SELL'
# ------------ Time in Force Types ------------
TIME_IN_FORCE_GTT = 'GTT'
TIME_IN_FORCE_FOK = 'FOK'
TIME_IN_FORCE_IOC = 'IOC'
# ------------ Position Status Types ------------
POSITION_STATUS_OPEN = 'OPEN'
POSITION_STATUS_CLOSED = 'CLOSED'
POSITION_STATUS_LIQUIDATED = 'LIQUIDATED'
# ------------ Order Status Types ------------
ORDER_STATUS_PENDING = 'PENDING'
ORDER_STATUS_OPEN = 'OPEN'
ORDER_STATUS_FILLED = 'FILLED'
ORDER_STATUS_CANCELED = 'CANCELED'
ORDER_STATUS_UNTRIGGERED = 'UNTRIGGERED'
# ------------ Transfer Status Types ------------
TRANSFER_STATUS_PENDING = 'PENDING'
TRANSFER_STATUS_CONFIRMED = 'CONFIRMED'
TRANSFER_STATUS_QUEUED = 'QUEUED'
TRANSFER_STATUS_CANCELED = 'CANCELED'
TRANSFER_STATUS_UNCONFIRMED = 'UNCONFIRMED'
# ------------ Account Action Types ------------
ACCOUNT_ACTION_DEPOSIT = 'DEPOSIT'
ACCOUNT_ACTION_WITHDRAWAL = 'WITHDRAWAL'
# ------------ Markets ------------
MARKET_BTC_USD = 'BTC-USD'
MARKET_ETH_USD = 'ETH-USD'
MARKET_LINK_USD = 'LINK-USD'
MARKET_AAVE_USD = 'AAVE-USD'
MARKET_UNI_USD = 'UNI-USD'
MARKET_SUSHI_USD = 'SUSHI-USD'
MARKET_SOL_USD = 'SOL-USD'
MARKET_YFI_USD = 'YFI-USD'
MARKET_ONEINCH_USD = '1INCH-USD'
MARKET_AVAX_USD = 'AVAX-USD'
MARKET_SNX_USD = 'SNX-USD'
MARKET_CRV_USD = 'CRV-USD'
MARKET_UMA_USD = 'UMA-USD'
MARKET_DOT_USD = 'DOT-USD'
MARKET_DOGE_USD = 'DOGE-USD'
MARKET_MATIC_USD = 'MATIC-USD'
MARKET_MKR_USD = 'MKR-USD'
MARKET_FIL_USD = 'FIL-USD'
MARKET_ADA_USD = 'ADA-USD'
MARKET_ATOM_USD = 'ATOM-USD'
MARKET_COMP_USD = 'COMP-USD'
MARKET_BCH_USD = 'BCH-USD'
MARKET_LTC_USD = 'LTC-USD'
MARKET_EOS_USD = 'EOS-USD'
MARKET_ALGO_USD = 'ALGO-USD'
MARKET_ZRX_USD = 'ZRX-USD'
MARKET_XMR_USD = 'XMR-USD'
MARKET_ZEC_USD = 'ZEC-USD'
MARKET_ENJ_USD = 'ENJ-USD'
MARKET_ETC_USD = 'ETC-USD'
MARKET_XLM_USD = 'XLM-USD'
MARKET_TRX_USD = 'TRX-USD'
MARKET_XTZ_USD = 'XTZ-USD'
MARKET_HNT_USD = 'HNT-USD'
MARKET_ICP_USD = 'ICP-USD'
MARKET_RUNE_USD = 'RUNE-USD'
MARKET_LUNA_USD = 'LUNA-USD'
MARKET_NEAR_USD = 'NEAR-USD'
MARKET_AR_USD = 'AR-USD'
MARKET_FLOW_USD = 'FLOW-USD'
MARKET_PERP_USD = 'PERP-USD'
MARKET_REN_USD = 'REN-USD'
MARKET_CELO_USD = 'CELO-USD'
MARKET_KSM_USD = 'KSM-USD'
MARKET_BAL_USD = 'BAL-USD'
MARKET_BNT_USD = 'BNT-USD'
MARKET_MIR_USD = 'MIR-USD'
MARKET_SRM_USD = 'SRM-USD'
MARKET_LON_USD = 'LON-USD'
MARKET_DODO_USD = 'DODO-USD'
MARKET_ALPHA_USD = 'ALPHA-USD'
MARKET_WNXM_USD = 'WNXM-USD'
MARKET_XCH_USD = 'XCH-USD'
# ------------ Assets ------------
ASSET_USDC = 'USDC'
ASSET_BTC = 'BTC'
ASSET_ETH = 'ETH'
ASSET_LINK = 'LINK'
ASSET_AAVE = 'AAVE'
ASSET_UNI = 'UNI'
ASSET_SUSHI = 'SUSHI'
ASSET_SOL = 'SOL'
ASSET_YFI = 'YFI'
ASSET_ONEINCH = '1INCH'
ASSET_AVAX = 'AVAX'
ASSET_SNX = 'SNX'
ASSET_CRV = 'CRV'
ASSET_UMA = 'UMA'
ASSET_DOT = 'DOT'
ASSET_DOGE = 'DOGE'
ASSET_MATIC = 'MATIC'
ASSET_MKR = 'MKR'
ASSET_FIL = 'FIL'
ASSET_ADA = 'ADA'
ASSET_ATOM = 'ATOM'
ASSET_COMP = 'COMP'
ASSET_BCH = 'BCH'
ASSET_LTC = 'LTC'
ASSET_EOS = 'EOS'
ASSET_ALGO = 'ALGO'
ASSET_ZRX = 'ZRX'
ASSET_XMR = 'XMR'
ASSET_ZEC = 'ZEC'
ASSET_ENJ = 'ENJ'
ASSET_ETC = 'ETC'
ASSET_XLM = 'XLM'
ASSET_TRX = 'TRX'
ASSET_XTZ = 'XTZ'
ASSET_HNT = 'HNT'
ASSET_ICP = 'ICP'
ASSET_RUNE = 'RUNE'
ASSET_LUNA = 'LUNA'
ASSET_NEAR = 'NEAR'
ASSET_AR = 'AR'
ASSET_FLOW = 'FLOW'
ASSET_PERP = 'PERP'
ASSET_REN = 'REN'
ASSET_CELO = 'CELO'
ASSET_KSM = 'KSM'
ASSET_BAL = 'BAL'
ASSET_BNT = 'BNT'
ASSET_MIR = 'MIR'
ASSET_SRM = 'SRM'
ASSET_LON = 'LON'
ASSET_DODO = 'DODO'
ASSET_ALPHA = 'ALPHA'
ASSET_WNXM = 'WNXM'
ASSET_XCH = 'XCH'
COLLATERAL_ASSET = ASSET_USDC
# ------------ Synthetic Assets by Market ------------
SYNTHETIC_ASSET_MAP = {
MARKET_BTC_USD: ASSET_BTC,
MARKET_ETH_USD: ASSET_ETH,
MARKET_LINK_USD: ASSET_LINK,
MARKET_AAVE_USD: ASSET_AAVE,
MARKET_UNI_USD: ASSET_UNI,
MARKET_SUSHI_USD: ASSET_SUSHI,
MARKET_SOL_USD: ASSET_SOL,
MARKET_YFI_USD: ASSET_YFI,
MARKET_ONEINCH_USD: ASSET_ONEINCH,
MARKET_AVAX_USD: ASSET_AVAX,
MARKET_SNX_USD: ASSET_SNX,
MARKET_CRV_USD: ASSET_CRV,
MARKET_UMA_USD: ASSET_UMA,
MARKET_DOT_USD: ASSET_DOT,
MARKET_DOGE_USD: ASSET_DOGE,
MARKET_MATIC_USD: ASSET_MATIC,
MARKET_MKR_USD: ASSET_MKR,
MARKET_FIL_USD: ASSET_FIL,
MARKET_ADA_USD: ASSET_ADA,
MARKET_ATOM_USD: ASSET_ATOM,
MARKET_COMP_USD: ASSET_COMP,
MARKET_BCH_USD: ASSET_BCH,
MARKET_LTC_USD: ASSET_LTC,
MARKET_EOS_USD: ASSET_EOS,
MARKET_ALGO_USD: ASSET_ALGO,
MARKET_ZRX_USD: ASSET_ZRX,
MARKET_XMR_USD: ASSET_XMR,
MARKET_ZEC_USD: ASSET_ZEC,
MARKET_ENJ_USD: ASSET_ENJ,
MARKET_ETC_USD: ASSET_ETC,
MARKET_XLM_USD: ASSET_XLM,
MARKET_TRX_USD: ASSET_TRX,
MARKET_XTZ_USD: ASSET_XTZ,
MARKET_HNT_USD: ASSET_HNT,
MARKET_ICP_USD: ASSET_ICP,
MARKET_RUNE_USD: ASSET_RUNE,
MARKET_LUNA_USD: ASSET_LUNA,
MARKET_NEAR_USD: ASSET_NEAR,
MARKET_AR_USD: ASSET_AR,
MARKET_FLOW_USD: ASSET_FLOW,
MARKET_PERP_USD: ASSET_PERP,
MARKET_REN_USD: ASSET_REN,
MARKET_CELO_USD: ASSET_CELO,
MARKET_KSM_USD: ASSET_KSM,
MARKET_BAL_USD: ASSET_BAL,
MARKET_BNT_USD: ASSET_BNT,
MARKET_MIR_USD: ASSET_MIR,
MARKET_SRM_USD: ASSET_SRM,
MARKET_LON_USD: ASSET_LON,
MARKET_DODO_USD: ASSET_DODO,
MARKET_ALPHA_USD: ASSET_ALPHA,
MARKET_WNXM_USD: ASSET_WNXM,
MARKET_XCH_USD: ASSET_XCH,
}
# ------------ Asset IDs ------------
COLLATERAL_ASSET_ID_BY_NETWORK_ID = {
NETWORK_ID_MAINNET: int(
'0x02893294412a4c8f915f75892b395ebbf6859ec246ec365c3b1f56f47c3a0a5d',
16,
),
NETWORK_ID_ROPSTEN: int(
'0x02c04d8b650f44092278a7cb1e1028c82025dff622db96c934b611b84cc8de5a',
16,
),
}
SYNTHETIC_ASSET_ID_MAP = {
ASSET_BTC: int('0x4254432d3130000000000000000000', 16),
ASSET_ETH: int('0x4554482d3900000000000000000000', 16),
ASSET_LINK: int('0x4c494e4b2d37000000000000000000', 16),
ASSET_AAVE: int('0x414156452d38000000000000000000', 16),
ASSET_UNI: int('0x554e492d3700000000000000000000', 16),
ASSET_SUSHI: int('0x53555348492d370000000000000000', 16),
ASSET_SOL: int('0x534f4c2d3700000000000000000000', 16),
ASSET_YFI: int('0x5946492d3130000000000000000000', 16),
ASSET_ONEINCH: int('0x31494e43482d370000000000000000', 16),
ASSET_AVAX: int('0x415641582d37000000000000000000', 16),
ASSET_SNX: int('0x534e582d3700000000000000000000', 16),
ASSET_CRV: int('0x4352562d3600000000000000000000', 16),
ASSET_UMA: int('0x554d412d3700000000000000000000', 16),
ASSET_DOT: int('0x444f542d3700000000000000000000', 16),
ASSET_DOGE: int('0x444f47452d35000000000000000000', 16),
ASSET_MATIC: int('0x4d415449432d360000000000000000', 16),
ASSET_MKR: int('0x4d4b522d3900000000000000000000', 16),
ASSET_FIL: int('0x46494c2d3700000000000000000000', 16),
ASSET_ADA: int('0x4144412d3600000000000000000000', 16),
ASSET_ATOM: int('0x41544f4d2d37000000000000000000', 16),
ASSET_COMP: int('0x434f4d502d38000000000000000000', 16),
ASSET_BCH: int('0x4243482d3800000000000000000000', 16),
ASSET_LTC: int('0x4c54432d3800000000000000000000', 16),
ASSET_EOS: int('0x454f532d3600000000000000000000', 16),
ASSET_ALGO: int('0x414c474f2d36000000000000000000', 16),
ASSET_ZRX: int('0x5a52582d3600000000000000000000', 16),
ASSET_XMR: int('0x584d522d3800000000000000000000', 16),
ASSET_ZEC: int('0x5a45432d3800000000000000000000', 16),
ASSET_ENJ: int('0x454e4a2d3600000000000000000000', 16),
ASSET_ETC: int('0x4554432d3700000000000000000000', 16),
ASSET_XLM: int('0x584c4d2d3500000000000000000000', 16),
ASSET_TRX: int('0x5452582d3400000000000000000000', 16),
ASSET_XTZ: int('0x58545a2d3600000000000000000000', 16),
ASSET_HNT: int('0x484e542d3700000000000000000000', 16),
ASSET_ICP: int('0x4943502d3700000000000000000000', 16),
ASSET_RUNE: int('0x52554e452d36000000000000000000', 16),
ASSET_LUNA: int('0x4c554e412d36000000000000000000', 16),
ASSET_NEAR: int('0x4e4541522d36000000000000000000', 16),
ASSET_AR: int('0x41522d370000000000000000000000', 16),
ASSET_FLOW: int('0x464c4f572d37000000000000000000', 16),
ASSET_PERP: int('0x504552502d36000000000000000000', 16),
ASSET_REN: int('0x52454e2d3500000000000000000000', 16),
ASSET_CELO: int('0x43454c4f2d36000000000000000000', 16),
ASSET_KSM: int('0x4b534d2d3800000000000000000000', 16),
ASSET_BAL: int('0x42414c2d3700000000000000000000', 16),
ASSET_BNT: int('0x424e542d3600000000000000000000', 16),
ASSET_MIR: int('0x4d49522d3600000000000000000000', 16),
ASSET_SRM: int('0x53524d2d3600000000000000000000', 16),
ASSET_LON: int('0x4c4f4e2d3600000000000000000000', 16),
ASSET_DODO: int('0x444f444f2d36000000000000000000', 16),
ASSET_ALPHA: int('0x414c5048412d350000000000000000', 16),
ASSET_WNXM: int('0x574e584d2d37000000000000000000', 16),
ASSET_XCH: int('0x5843482d3800000000000000000000', 16),
}
# ------------ Asset Resolution (Quantum Size) ------------
#
# The asset resolution is the number of quantums (Starkware units) that fit
# within one "human-readable" unit of the asset. For example, if the asset
# resolution for BTC is 1e10, then the smallest unit representable within
# Starkware is 1e-10 BTC, i.e. 1/100th of a satoshi.
#
# For the collateral asset (USDC), the chosen resolution corresponds to the
# base units of the ERC-20 token. For the other, synthetic, assets, the
# resolutions are chosen such that prices relative to USDC are close to one.
ASSET_RESOLUTION = {
ASSET_USDC: '1e6',
ASSET_BTC: '1e10',
ASSET_ETH: '1e9',
ASSET_LINK: '1e7',
ASSET_AAVE: '1e8',
ASSET_UNI: '1e7',
ASSET_SUSHI: '1e7',
ASSET_SOL: '1e7',
ASSET_YFI: '1e10',
ASSET_ONEINCH: '1e7',
ASSET_AVAX: '1e7',
ASSET_SNX: '1e7',
ASSET_CRV: '1e6',
ASSET_UMA: '1e7',
ASSET_DOT: '1e7',
ASSET_DOGE: '1e5',
ASSET_MATIC: '1e6',
ASSET_MKR: '1e9',
ASSET_FIL: '1e7',
ASSET_ADA: '1e6',
ASSET_ATOM: '1e7',
ASSET_COMP: '1e8',
ASSET_BCH: '1e8',
ASSET_LTC: '1e8',
ASSET_EOS: '1e6',
ASSET_ALGO: '1e6',
ASSET_ZRX: '1e6',
ASSET_XMR: '1e8',
ASSET_ZEC: '1e8',
ASSET_ENJ: '1e6',
ASSET_ETC: '1e7',
ASSET_XLM: '1e5',
ASSET_TRX: '1e4',
ASSET_XTZ: '1e6',
ASSET_HNT: '1e7',
ASSET_ICP: '1e7',
ASSET_RUNE: '1e6',
ASSET_LUNA: '1e6',
ASSET_NEAR: '1e6',
ASSET_AR: '1e7',
ASSET_FLOW: '1e7',
ASSET_PERP: '1e6',
ASSET_REN: '1e5',
ASSET_CELO: '1e6',
ASSET_KSM: '1e8',
ASSET_BAL: '1e7',
ASSET_BNT: '1e6',
ASSET_MIR: '1e6',
ASSET_SRM: '1e6',
ASSET_LON: '1e6',
ASSET_DODO: '1e6',
ASSET_ALPHA: '1e5',
ASSET_WNXM: '1e7',
ASSET_XCH: '1e8',
}
# ------------ Ethereum Transactions ------------
DEFAULT_GAS_AMOUNT = 250000
DEFAULT_GAS_MULTIPLIER = 1.5
DEFAULT_GAS_PRICE = 4000000000
DEFAULT_GAS_PRICE_ADDITION = 3
MAX_SOLIDITY_UINT = 115792089237316195423570985008687907853269984665640564039457584007913129639935 # noqa: E501
FACT_REGISTRY_CONTRACT = {
NETWORK_ID_MAINNET: '0xBE9a129909EbCb954bC065536D2bfAfBd170d27A',
NETWORK_ID_ROPSTEN: '0x8Fb814935f7E63DEB304B500180e19dF5167B50e',
}
STARKWARE_PERPETUALS_CONTRACT = {
NETWORK_ID_MAINNET: '0xD54f502e184B6B739d7D27a6410a67dc462D69c8',
NETWORK_ID_ROPSTEN: '0x014F738EAd8Ec6C50BCD456a971F8B84Cd693BBe',
}
TOKEN_CONTRACTS = {
ASSET_USDC: {
NETWORK_ID_MAINNET: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
NETWORK_ID_ROPSTEN: '0x8707A5bf4C2842d46B31A405Ba41b858C0F876c4',
},
}
COLLATERAL_TOKEN_DECIMALS = 6
# ------------ Off-Chain Ethereum-Signed Actions ------------
OFF_CHAIN_ONBOARDING_ACTION = 'dYdX Onboarding'
OFF_CHAIN_KEY_DERIVATION_ACTION = 'dYdX STARK Key' | en | 0.567936 | # ------------ API URLs ------------ # ------------ Ethereum Network IDs ------------ # ------------ Signature Types ------------ # ------------ Market Statistic Day Types ------------ # ------------ Order Types ------------ # ------------ Order Side ------------ # ------------ Time in Force Types ------------ # ------------ Position Status Types ------------ # ------------ Order Status Types ------------ # ------------ Transfer Status Types ------------ # ------------ Account Action Types ------------ # ------------ Markets ------------ # ------------ Assets ------------ # ------------ Synthetic Assets by Market ------------ # ------------ Asset IDs ------------ # ------------ Asset Resolution (Quantum Size) ------------ # # The asset resolution is the number of quantums (Starkware units) that fit # within one "human-readable" unit of the asset. For example, if the asset # resolution for BTC is 1e10, then the smallest unit representable within # Starkware is 1e-10 BTC, i.e. 1/100th of a satoshi. # # For the collateral asset (USDC), the chosen resolution corresponds to the # base units of the ERC-20 token. For the other, synthetic, assets, the # resolutions are chosen such that prices relative to USDC are close to one. # ------------ Ethereum Transactions ------------ # noqa: E501 # ------------ Off-Chain Ethereum-Signed Actions ------------ | 1.499238 | 1 |
libsousou/web/__init__.py | sousouindustries/python-libsousou | 0 | 6616143 | from libsousou.web.base import RequestController
from libsousou.web.contextmixin import ContextMixin
from libsousou.web.irequest import IRequest
| from libsousou.web.base import RequestController
from libsousou.web.contextmixin import ContextMixin
from libsousou.web.irequest import IRequest
| none | 1 | 1.086446 | 1 | |
main.py | NCPlayzALT/ChipBotPy | 0 | 6616144 | import discord
from discord.ext import commands
import random
import os
description = '''---CHIPBOT COMMANDS---'''
bot = commands.Bot(command_prefix='-', description=description)
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.event
async def on_message(message):
if "luna" in message.content or "Luna" in message.content and message.author != bot.user:
await bot.send_message(message.channel, 'Luna? \U0001f440')
if "Hello ChipBot!" in message.content:
await bot.send_message(message.channel, 'Beep! Boop! I am ChipBot!')
await bot.process_commands(message)
token = os.environ["TOKEN"]
bot.run(token)
| import discord
from discord.ext import commands
import random
import os
description = '''---CHIPBOT COMMANDS---'''
bot = commands.Bot(command_prefix='-', description=description)
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.event
async def on_message(message):
if "luna" in message.content or "Luna" in message.content and message.author != bot.user:
await bot.send_message(message.channel, 'Luna? \U0001f440')
if "Hello ChipBot!" in message.content:
await bot.send_message(message.channel, 'Beep! Boop! I am ChipBot!')
await bot.process_commands(message)
token = os.environ["TOKEN"]
bot.run(token)
| en | 0.139168 | ---CHIPBOT COMMANDS--- | 2.720099 | 3 |
PyPI/MLRsearch/setup.py | nidhyanandhan/csit | 0 | 6616145 | <filename>PyPI/MLRsearch/setup.py
"""A setup module for setuptools.
See:
https://packaging.python.org/en/latest/distributing.html
"""
from setuptools import setup, find_packages
from os import path
from io import open
here = path.abspath(path.dirname(__file__))
with open(path.join(here, u"README.rst"), encoding=u"utf-8") as f:
long_description = f.read()
setup(
name=u"MLRsearch",
version=u"0.3.0", # This is currently the only place listing the version.
description=u"Library for speeding up binary search using shorter measurements.",
long_description=long_description,
long_description_content_type=u"text/x-rst",
# TODO: Create a separate webpage for MLRsearch library.
url=u"https://gerrit.fd.io/r/gitweb?p=csit.git;a=tree;f=PyPI/MLRsearch;hb=refs/heads/master",
author=u"Cisco Systems Inc. and/or its affiliates",
author_email=u"<EMAIL>",
classifiers=[
u"Development Status :: 3 - Alpha",
u"Intended Audience :: Science/Research",
u"Intended Audience :: Telecommunications Industry",
u"License :: OSI Approved :: Apache Software License",
u"Programming Language :: Python :: 3.6",
u"Topic :: System :: Networking"
],
keywords=u"binary search throughput networking",
packages=find_packages(exclude=[]),
python_requires=u"~=3.6",
install_requires=[],
# TODO: Include simulator and tests.
extras_require={
},
package_data={
},
entry_points={
u"console_scripts": [
],
},
project_urls={
u"Bug Reports": u"https://jira.fd.io/projects/CSIT/issues",
u"Source": u"https://gerrit.fd.io/r/gitweb?p=csit.git;a=tree;f=PyPI/MLRsearch;hb=refs/heads/master",
},
)
| <filename>PyPI/MLRsearch/setup.py
"""A setup module for setuptools.
See:
https://packaging.python.org/en/latest/distributing.html
"""
from setuptools import setup, find_packages
from os import path
from io import open
here = path.abspath(path.dirname(__file__))
with open(path.join(here, u"README.rst"), encoding=u"utf-8") as f:
long_description = f.read()
setup(
name=u"MLRsearch",
version=u"0.3.0", # This is currently the only place listing the version.
description=u"Library for speeding up binary search using shorter measurements.",
long_description=long_description,
long_description_content_type=u"text/x-rst",
# TODO: Create a separate webpage for MLRsearch library.
url=u"https://gerrit.fd.io/r/gitweb?p=csit.git;a=tree;f=PyPI/MLRsearch;hb=refs/heads/master",
author=u"Cisco Systems Inc. and/or its affiliates",
author_email=u"<EMAIL>",
classifiers=[
u"Development Status :: 3 - Alpha",
u"Intended Audience :: Science/Research",
u"Intended Audience :: Telecommunications Industry",
u"License :: OSI Approved :: Apache Software License",
u"Programming Language :: Python :: 3.6",
u"Topic :: System :: Networking"
],
keywords=u"binary search throughput networking",
packages=find_packages(exclude=[]),
python_requires=u"~=3.6",
install_requires=[],
# TODO: Include simulator and tests.
extras_require={
},
package_data={
},
entry_points={
u"console_scripts": [
],
},
project_urls={
u"Bug Reports": u"https://jira.fd.io/projects/CSIT/issues",
u"Source": u"https://gerrit.fd.io/r/gitweb?p=csit.git;a=tree;f=PyPI/MLRsearch;hb=refs/heads/master",
},
)
| en | 0.822673 | A setup module for setuptools. See: https://packaging.python.org/en/latest/distributing.html # This is currently the only place listing the version. # TODO: Create a separate webpage for MLRsearch library. # TODO: Include simulator and tests. | 1.600319 | 2 |
nope/githubdashlib/githubapi.py | nthmost/st-githubdash | 0 | 6616146 | <gh_stars>0
## THIS API RELIES ON THE octohub GitHub interaction library.
from .githubobjects import Label, Issue, Event
ISSUES_URI = "/repos/streamlit/streamlit/issues"
LABELS_URI = "/repos/streamlit/streamlit/labels"
EVENTS_URI = "/repos/streamlit/streamlit/events"
DEFAULT_PER_PAGE = 30
def get_all_events(conn):
events = []
uri = EVENTS_URI
response = conn.send("GET", uri)
for item in response.parsed:
events.append(Event(**item))
return events
def get_labels(conn, per_page=30):
labels = []
# Set max return in page to the maximum allowed by GitHub API.
uri = LABELS_URI + "?per_page=%i" % per_page
response = conn.send("GET", uri)
for item in response.parsed:
labels.append(Label(**item))
return labels
def get_issues(conn, params=None, direction=None, since=None,
sort=None, per_page=DEFAULT_PER_PAGE, page=1):
issues = []
uri = ISSUES_URI + "?per_page=%i" % per_page
if since:
uri += "&since=%s" % since
if sort:
uri += "&sort=%s" % sort
if direction:
uri += "&direction=%s" % direction
uri += "&page=%i" % page
response = conn.send("GET", uri,
params=params,
)
for item in response.parsed:
issues.append(Issue(**item))
return issues
def get_all_the_issues(conn, state="open"):
issues = []
uri = ISSUES_URI + "?per_page=100&state=%s" % state
page = 1
more_issues = True
while more_issues:
uri += "&page=%i" % page
response = conn.send("GET", uri, params={},)
for item in response.parsed:
issues.append(Issue(**item))
if not len(issues) % 100:
page += 1
else:
more_issues = False
return issues
| ## THIS API RELIES ON THE octohub GitHub interaction library.
from .githubobjects import Label, Issue, Event
ISSUES_URI = "/repos/streamlit/streamlit/issues"
LABELS_URI = "/repos/streamlit/streamlit/labels"
EVENTS_URI = "/repos/streamlit/streamlit/events"
DEFAULT_PER_PAGE = 30
def get_all_events(conn):
events = []
uri = EVENTS_URI
response = conn.send("GET", uri)
for item in response.parsed:
events.append(Event(**item))
return events
def get_labels(conn, per_page=30):
labels = []
# Set max return in page to the maximum allowed by GitHub API.
uri = LABELS_URI + "?per_page=%i" % per_page
response = conn.send("GET", uri)
for item in response.parsed:
labels.append(Label(**item))
return labels
def get_issues(conn, params=None, direction=None, since=None,
sort=None, per_page=DEFAULT_PER_PAGE, page=1):
issues = []
uri = ISSUES_URI + "?per_page=%i" % per_page
if since:
uri += "&since=%s" % since
if sort:
uri += "&sort=%s" % sort
if direction:
uri += "&direction=%s" % direction
uri += "&page=%i" % page
response = conn.send("GET", uri,
params=params,
)
for item in response.parsed:
issues.append(Issue(**item))
return issues
def get_all_the_issues(conn, state="open"):
issues = []
uri = ISSUES_URI + "?per_page=100&state=%s" % state
page = 1
more_issues = True
while more_issues:
uri += "&page=%i" % page
response = conn.send("GET", uri, params={},)
for item in response.parsed:
issues.append(Issue(**item))
if not len(issues) % 100:
page += 1
else:
more_issues = False
return issues | en | 0.665218 | ## THIS API RELIES ON THE octohub GitHub interaction library. # Set max return in page to the maximum allowed by GitHub API. | 2.34012 | 2 |
sqlitecookiejar.py | timsoft-oss/sqlitecookiejar | 1 | 6616147 | # coding=utf-8
"""
SQLiteCookieJar
~~~~~~~~~~~~~~~
An alternate `FileCookieJar` that implements a SQLite storage for
cookies. Inspired by RFC 6265 but not strictly compliant, since it
sits on top of `cookielib`.
SQLite storage was inspired by Mozilla Firefox cookies.sqlite.
"""
from cookielib import FileCookieJar, Cookie
import os.path
import sqlite3
import time
import logging
class SQLiteCookieJar(FileCookieJar):
"""
This class implements the cookielib.FileCookieJar using a file-based
SQLite database. There is no centralized database holding the cookies
for a given user, so it does not exactly work like a browser. However,
the default CookieJar database file will be stored in the user's home
folder.
This implementation is loosely based on RFC6265, more specifically on
section 5.3 ... however, for compatibility reasons with python2.7's
`cookielib.Cookie`, the following cookie-attributes are ignored :
- max-age
- http-only
:param str filename: The complete path to the CookieJar.
Defaults to HOME_FOLDER/python-cookies.sqlite
:param float timeout: Timeout on the connexion (defaults to 0.5)
:param logger: The logger used to log errors, infos, etc.
Defaults to a basic ERROR stdout logger.
:type logger: `logging.Logger`
"""
def __init__(self, timeout=0.5, logger=None, *args, **kwargs):
FileCookieJar.__init__(self, *args, **kwargs)
if logger is None:
self.logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
handler.setLevel(logging.WARNING)
self.logger.addHandler(handler)
else:
self.logger = logger
self.timeout = timeout
if self.filename is None:
self.filename = os.path.join(os.path.expanduser("~"), "python-cookies.sqlite")
self.logger.warning("No filename argument specified. Your cookie jar will be in %s", self.filename)
self._check_and_create_table()
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
"""
Implementation of the save method.
:param filename: MUST be None. There is only one file per CookieJar.
:param ignore_discard: MUST be False. Session cookies are not saved.
:param ignore_expires: MUST be False. Expired cookies are evicted.
"""
self._check_save_load_params(filename, ignore_discard, ignore_expires)
for cookie in self:
if not self._save_cookie(cookie):
# If save failed, stop trying
break
def _flush(self):
"""
Internal method that flushes the database. Cookies that have expired
will be deleted.
Used before and after loading cookies from/to the database.
"""
try:
with sqlite3.connect(self.filename, self.timeout) as con:
con.execute("DELETE FROM cookie WHERE expiry < ?", (time.time(),))
except sqlite3.DatabaseError, e:
self.logger.error("Could not flush expired cookies")
self.logger.error("Exception was : %s - %s" % (type(e).__name__, e))
def _save_cookie(self, cookie):
"""
Save a single cookie in the database. Follows the algorithm described
in RFC6265 section 5.3 Storage Model ; specifically subpoint 11.
Due to this implementation sitting on top of python's cookielib, we
are not RFC6265-compliant.
If a cookie exists, update it.
Otherwise, create a new one.
Exit if the cookie is not fresh.
:param cookie: The cookie to save.
:return bool: Returns `True` if saved was possible, `False` if
saving failed
"""
_now = time.time()
if cookie is None or cookie.expires is None or cookie.expires < _now:
return True
try:
with sqlite3.connect(self.filename, self.timeout) as con:
self.logger.info(
"SAVING cookie [domain: %s , name : %s, value: %s]" % (cookie.domain, cookie.name, cookie.value)
)
res = con.execute("SELECT id FROM cookie WHERE domain = ? AND name = ? AND path = ?",
(cookie.domain, cookie.name, cookie.path)).fetchone()
if res is not None:
id = res[0]
con.execute("UPDATE cookie SET value = ?, secure = ?, expiry = ?, last_access = ? WHERE id=?",
(cookie.value, cookie.secure, cookie.expires, _now, id))
else:
if cookie.path is None or cookie.path == "":
cookie.path = "/"
con.execute(
"INSERT INTO "
"cookie (domain,name,value, path, expiry, last_access, creation_time, secure) "
"VALUES (?,?,?,?,?,?,?,?)",
(
cookie.domain,
cookie.name,
cookie.value,
cookie.path,
cookie.expires,
_now,
_now,
cookie.secure
)
)
return True
except sqlite3.DatabaseError, e:
self.logger.error(
"Could not save cookie [domain: %s , name : %s, value: %s]." % ( cookie.domain,
cookie.name,
cookie.value
)
)
self.logger.error("Exception was : %s - %s" % (type(e).__name__, e))
return False
def load(self, filename=None, ignore_discard=False, ignore_expires=False):
"""
Overriding the default load method.
Please note that old cookies are flushed from the databaase through
:meth:`_flush`.
:param filename: MUST be None. There is only one file per CookieJar.
:param ignore_discard: MUST be False. Session cookies are not saved.
:param ignore_expires: MUST be False. Expired cookies are evicted.
"""
self._check_save_load_params(filename, ignore_discard, ignore_expires)
self._flush()
self._really_load()
def _really_load(self):
"""
Implementation of the _really_load method. Basically, it just loads
everything in the database, and maps it to cookies
"""
try:
with sqlite3.connect(self.filename, self.timeout) as con:
con.row_factory = sqlite3.Row
res = con.execute("SELECT * from cookie").fetchall()
for cookie in res:
initial_dot = cookie["domain"].startswith(".")
c = Cookie( 0, cookie["name"], cookie["value"],
None, False,
cookie["domain"], initial_dot, initial_dot,
cookie["path"], cookie["path"]!="/",
cookie["secure"],
cookie["expiry"],
False,
None,
None,
{}
)
self.logger.info(
"LOADED cookie [domain: %s , name : %s, value: %s]" % (c.domain, c.name, c.value)
)
if not c.is_expired(time.time()):
self.set_cookie(c)
except sqlite3.DatabaseError, e:
self.logger.error("Loading cookies failed : could not access database")
self.logger.error("Exception was : %s - %s" % (type(e).__name__, e))
def _check_save_load_params(self, filename, ignore_discard, ignore_expires):
"""
Internal method to make sure the parameters passed to save() and
load() comply with RFC6265. Also makes sure there is only one file
per CookieJar.
:param filename: MUST be None. There is only one file per CookieJar.
:param ignore_discard: MUST be False. Session cookies are not saved.
:param ignore_expires: MUST be False. Expired cookies are evicted.
"""
if filename is not None:
raise NotImplementedError("There is only one file per jar.")
if ignore_discard:
raise NotImplementedError("This implementation respects RFC6265 in regard to "
"session cookies. They cannot be stored.")
if ignore_expires:
raise NotImplementedError("This implementation respects RFC6265 in regard to "
"cookie expiry. No expired cookie can be kept in "
"the jar. That's unhealthy, anyway.")
def _check_and_create_table(self):
"""
Internal method to make sure the provided database has the correct
format. There are four possibilities :
1. The database has no tables, in which case it is a new database
and we will create the table `cookie`.
2. The database has one table, called `cookie`, in which case we
make a select on it to make sure it has the right columns. If
it doesn't, we raise an exception
3. The database has one table but the name is not `cookie`. It's
the wrong database, raise an exception.
4. The database has more than one table. It's the wrong database,
raise an exception.
Note : If the file is not a database, sqlite3 will crash with and
raise a DatabaseError.
"""
try:
with sqlite3.connect(self.filename, self.timeout) as con:
res = con.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
if len(res) == 0:
# Case #1
con.execute("CREATE TABLE IF NOT EXISTS cookie "
"(id INTEGER NOT NULL PRIMARY KEY,"
"domain TEXT NOT NULL,"
"name TEXT NOT NULL,"
"value TEXT,"
"path TEXT NOT NULL DEFAULT '/',"
"expiry INTEGER NOT NULL,"
"last_access INTEGER NOT NULL,"
"creation_time INTEGER NOT NULL,"
"secure INTEGER NOT NULL DEFAULT 0,"
"CONSTRAINT cookie_unique UNIQUE (name, domain, path))")
elif len(res) == 1:
# Cases #2 and #3
table_name = res[0][0]
if table_name != "cookie":
# Case #3
raise AttributeError("The specified database has one table named '%s', but the tabled should be"
" named 'cookie'. Please provide a valid database." % table_name)
else:
# Case #2
res = con.execute("PRAGMA table_info(cookie)").fetchall()
columns = set([element[1] for element in res])
expected_columns = {u'id', u'domain', u'name', u'value', u'path', u'expiry', u'last_access',
u'creation_time', u'secure'}
if len(columns.difference(expected_columns)) > 0:
raise AttributeError("The specified database has a table named 'cookie', but the column "
"names do not match. Expected : %s with %s elements; got %s with %s "
"elements instead." %
(list(expected_columns),
len(expected_columns),
list(columns),
len(columns)))
else:
# Case #4
raise AttributeError("The specified database has more than one table. "
"Please provide a valid database.")
except sqlite3.DatabaseError, e:
self.logger.error("Sanity checks failed : could not access database")
self.logger.error("Exception was : %s - %s" % (type(e).__name__, e))
| # coding=utf-8
"""
SQLiteCookieJar
~~~~~~~~~~~~~~~
An alternate `FileCookieJar` that implements a SQLite storage for
cookies. Inspired by RFC 6265 but not strictly compliant, since it
sits on top of `cookielib`.
SQLite storage was inspired by Mozilla Firefox cookies.sqlite.
"""
from cookielib import FileCookieJar, Cookie
import os.path
import sqlite3
import time
import logging
class SQLiteCookieJar(FileCookieJar):
"""
This class implements the cookielib.FileCookieJar using a file-based
SQLite database. There is no centralized database holding the cookies
for a given user, so it does not exactly work like a browser. However,
the default CookieJar database file will be stored in the user's home
folder.
This implementation is loosely based on RFC6265, more specifically on
section 5.3 ... however, for compatibility reasons with python2.7's
`cookielib.Cookie`, the following cookie-attributes are ignored :
- max-age
- http-only
:param str filename: The complete path to the CookieJar.
Defaults to HOME_FOLDER/python-cookies.sqlite
:param float timeout: Timeout on the connexion (defaults to 0.5)
:param logger: The logger used to log errors, infos, etc.
Defaults to a basic ERROR stdout logger.
:type logger: `logging.Logger`
"""
def __init__(self, timeout=0.5, logger=None, *args, **kwargs):
FileCookieJar.__init__(self, *args, **kwargs)
if logger is None:
self.logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
handler.setLevel(logging.WARNING)
self.logger.addHandler(handler)
else:
self.logger = logger
self.timeout = timeout
if self.filename is None:
self.filename = os.path.join(os.path.expanduser("~"), "python-cookies.sqlite")
self.logger.warning("No filename argument specified. Your cookie jar will be in %s", self.filename)
self._check_and_create_table()
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
"""
Implementation of the save method.
:param filename: MUST be None. There is only one file per CookieJar.
:param ignore_discard: MUST be False. Session cookies are not saved.
:param ignore_expires: MUST be False. Expired cookies are evicted.
"""
self._check_save_load_params(filename, ignore_discard, ignore_expires)
for cookie in self:
if not self._save_cookie(cookie):
# If save failed, stop trying
break
def _flush(self):
"""
Internal method that flushes the database. Cookies that have expired
will be deleted.
Used before and after loading cookies from/to the database.
"""
try:
with sqlite3.connect(self.filename, self.timeout) as con:
con.execute("DELETE FROM cookie WHERE expiry < ?", (time.time(),))
except sqlite3.DatabaseError, e:
self.logger.error("Could not flush expired cookies")
self.logger.error("Exception was : %s - %s" % (type(e).__name__, e))
def _save_cookie(self, cookie):
"""
Save a single cookie in the database. Follows the algorithm described
in RFC6265 section 5.3 Storage Model ; specifically subpoint 11.
Due to this implementation sitting on top of python's cookielib, we
are not RFC6265-compliant.
If a cookie exists, update it.
Otherwise, create a new one.
Exit if the cookie is not fresh.
:param cookie: The cookie to save.
:return bool: Returns `True` if saved was possible, `False` if
saving failed
"""
_now = time.time()
if cookie is None or cookie.expires is None or cookie.expires < _now:
return True
try:
with sqlite3.connect(self.filename, self.timeout) as con:
self.logger.info(
"SAVING cookie [domain: %s , name : %s, value: %s]" % (cookie.domain, cookie.name, cookie.value)
)
res = con.execute("SELECT id FROM cookie WHERE domain = ? AND name = ? AND path = ?",
(cookie.domain, cookie.name, cookie.path)).fetchone()
if res is not None:
id = res[0]
con.execute("UPDATE cookie SET value = ?, secure = ?, expiry = ?, last_access = ? WHERE id=?",
(cookie.value, cookie.secure, cookie.expires, _now, id))
else:
if cookie.path is None or cookie.path == "":
cookie.path = "/"
con.execute(
"INSERT INTO "
"cookie (domain,name,value, path, expiry, last_access, creation_time, secure) "
"VALUES (?,?,?,?,?,?,?,?)",
(
cookie.domain,
cookie.name,
cookie.value,
cookie.path,
cookie.expires,
_now,
_now,
cookie.secure
)
)
return True
except sqlite3.DatabaseError, e:
self.logger.error(
"Could not save cookie [domain: %s , name : %s, value: %s]." % ( cookie.domain,
cookie.name,
cookie.value
)
)
self.logger.error("Exception was : %s - %s" % (type(e).__name__, e))
return False
def load(self, filename=None, ignore_discard=False, ignore_expires=False):
"""
Overriding the default load method.
Please note that old cookies are flushed from the databaase through
:meth:`_flush`.
:param filename: MUST be None. There is only one file per CookieJar.
:param ignore_discard: MUST be False. Session cookies are not saved.
:param ignore_expires: MUST be False. Expired cookies are evicted.
"""
self._check_save_load_params(filename, ignore_discard, ignore_expires)
self._flush()
self._really_load()
def _really_load(self):
"""
Implementation of the _really_load method. Basically, it just loads
everything in the database, and maps it to cookies
"""
try:
with sqlite3.connect(self.filename, self.timeout) as con:
con.row_factory = sqlite3.Row
res = con.execute("SELECT * from cookie").fetchall()
for cookie in res:
initial_dot = cookie["domain"].startswith(".")
c = Cookie( 0, cookie["name"], cookie["value"],
None, False,
cookie["domain"], initial_dot, initial_dot,
cookie["path"], cookie["path"]!="/",
cookie["secure"],
cookie["expiry"],
False,
None,
None,
{}
)
self.logger.info(
"LOADED cookie [domain: %s , name : %s, value: %s]" % (c.domain, c.name, c.value)
)
if not c.is_expired(time.time()):
self.set_cookie(c)
except sqlite3.DatabaseError, e:
self.logger.error("Loading cookies failed : could not access database")
self.logger.error("Exception was : %s - %s" % (type(e).__name__, e))
def _check_save_load_params(self, filename, ignore_discard, ignore_expires):
"""
Internal method to make sure the parameters passed to save() and
load() comply with RFC6265. Also makes sure there is only one file
per CookieJar.
:param filename: MUST be None. There is only one file per CookieJar.
:param ignore_discard: MUST be False. Session cookies are not saved.
:param ignore_expires: MUST be False. Expired cookies are evicted.
"""
if filename is not None:
raise NotImplementedError("There is only one file per jar.")
if ignore_discard:
raise NotImplementedError("This implementation respects RFC6265 in regard to "
"session cookies. They cannot be stored.")
if ignore_expires:
raise NotImplementedError("This implementation respects RFC6265 in regard to "
"cookie expiry. No expired cookie can be kept in "
"the jar. That's unhealthy, anyway.")
def _check_and_create_table(self):
"""
Internal method to make sure the provided database has the correct
format. There are four possibilities :
1. The database has no tables, in which case it is a new database
and we will create the table `cookie`.
2. The database has one table, called `cookie`, in which case we
make a select on it to make sure it has the right columns. If
it doesn't, we raise an exception
3. The database has one table but the name is not `cookie`. It's
the wrong database, raise an exception.
4. The database has more than one table. It's the wrong database,
raise an exception.
Note : If the file is not a database, sqlite3 will crash with and
raise a DatabaseError.
"""
try:
with sqlite3.connect(self.filename, self.timeout) as con:
res = con.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
if len(res) == 0:
# Case #1
con.execute("CREATE TABLE IF NOT EXISTS cookie "
"(id INTEGER NOT NULL PRIMARY KEY,"
"domain TEXT NOT NULL,"
"name TEXT NOT NULL,"
"value TEXT,"
"path TEXT NOT NULL DEFAULT '/',"
"expiry INTEGER NOT NULL,"
"last_access INTEGER NOT NULL,"
"creation_time INTEGER NOT NULL,"
"secure INTEGER NOT NULL DEFAULT 0,"
"CONSTRAINT cookie_unique UNIQUE (name, domain, path))")
elif len(res) == 1:
# Cases #2 and #3
table_name = res[0][0]
if table_name != "cookie":
# Case #3
raise AttributeError("The specified database has one table named '%s', but the tabled should be"
" named 'cookie'. Please provide a valid database." % table_name)
else:
# Case #2
res = con.execute("PRAGMA table_info(cookie)").fetchall()
columns = set([element[1] for element in res])
expected_columns = {u'id', u'domain', u'name', u'value', u'path', u'expiry', u'last_access',
u'creation_time', u'secure'}
if len(columns.difference(expected_columns)) > 0:
raise AttributeError("The specified database has a table named 'cookie', but the column "
"names do not match. Expected : %s with %s elements; got %s with %s "
"elements instead." %
(list(expected_columns),
len(expected_columns),
list(columns),
len(columns)))
else:
# Case #4
raise AttributeError("The specified database has more than one table. "
"Please provide a valid database.")
except sqlite3.DatabaseError, e:
self.logger.error("Sanity checks failed : could not access database")
self.logger.error("Exception was : %s - %s" % (type(e).__name__, e))
| en | 0.82067 | # coding=utf-8 SQLiteCookieJar ~~~~~~~~~~~~~~~ An alternate `FileCookieJar` that implements a SQLite storage for cookies. Inspired by RFC 6265 but not strictly compliant, since it sits on top of `cookielib`. SQLite storage was inspired by Mozilla Firefox cookies.sqlite. This class implements the cookielib.FileCookieJar using a file-based SQLite database. There is no centralized database holding the cookies for a given user, so it does not exactly work like a browser. However, the default CookieJar database file will be stored in the user's home folder. This implementation is loosely based on RFC6265, more specifically on section 5.3 ... however, for compatibility reasons with python2.7's `cookielib.Cookie`, the following cookie-attributes are ignored : - max-age - http-only :param str filename: The complete path to the CookieJar. Defaults to HOME_FOLDER/python-cookies.sqlite :param float timeout: Timeout on the connexion (defaults to 0.5) :param logger: The logger used to log errors, infos, etc. Defaults to a basic ERROR stdout logger. :type logger: `logging.Logger` Implementation of the save method. :param filename: MUST be None. There is only one file per CookieJar. :param ignore_discard: MUST be False. Session cookies are not saved. :param ignore_expires: MUST be False. Expired cookies are evicted. # If save failed, stop trying Internal method that flushes the database. Cookies that have expired will be deleted. Used before and after loading cookies from/to the database. Save a single cookie in the database. Follows the algorithm described in RFC6265 section 5.3 Storage Model ; specifically subpoint 11. Due to this implementation sitting on top of python's cookielib, we are not RFC6265-compliant. If a cookie exists, update it. Otherwise, create a new one. Exit if the cookie is not fresh. :param cookie: The cookie to save. :return bool: Returns `True` if saved was possible, `False` if saving failed Overriding the default load method. Please note that old cookies are flushed from the databaase through :meth:`_flush`. :param filename: MUST be None. There is only one file per CookieJar. :param ignore_discard: MUST be False. Session cookies are not saved. :param ignore_expires: MUST be False. Expired cookies are evicted. Implementation of the _really_load method. Basically, it just loads everything in the database, and maps it to cookies Internal method to make sure the parameters passed to save() and load() comply with RFC6265. Also makes sure there is only one file per CookieJar. :param filename: MUST be None. There is only one file per CookieJar. :param ignore_discard: MUST be False. Session cookies are not saved. :param ignore_expires: MUST be False. Expired cookies are evicted. Internal method to make sure the provided database has the correct format. There are four possibilities : 1. The database has no tables, in which case it is a new database and we will create the table `cookie`. 2. The database has one table, called `cookie`, in which case we make a select on it to make sure it has the right columns. If it doesn't, we raise an exception 3. The database has one table but the name is not `cookie`. It's the wrong database, raise an exception. 4. The database has more than one table. It's the wrong database, raise an exception. Note : If the file is not a database, sqlite3 will crash with and raise a DatabaseError. # Case #1 # Cases #2 and #3 # Case #3 # Case #2 # Case #4 | 2.879274 | 3 |
helper/snake.py | nv-hiep/NeuralNetworkSnake | 0 | 6616148 | <filename>helper/snake.py
import sys
import os
import json
import random
import numpy as np
from typing import Tuple, Optional, Union, Set, Dict, List, Any
from fractions import Fraction
from collections import deque
from helper.tools import Slope, Point
from helper.config import config
from helper.const import *
from network.neural_network import Network, linear, sigmoid, tanh, relu, leaky_relu, get_activation_fcn
from GA.individual import Individual
class Vision(object):
__slots__ = ('dist_to_wall', 'dist_to_apple', 'dist_to_self')
def __init__(self,
dist_to_wall: Union[float, int],
dist_to_apple: Union[float, int],
dist_to_self: Union[float, int]
):
self.dist_to_wall = float(dist_to_wall)
self.dist_to_apple = float(dist_to_apple)
self.dist_to_self = float(dist_to_self)
class DrawableVision(object):
__slots__ = ('wall_location', 'apple_location', 'self_location')
def __init__(self,
wall_location: Point,
apple_location: Optional[Point] = None,
self_location: Optional[Point] = None,
):
self.wall_location = wall_location
self.apple_location = apple_location
self.self_location = self_location
class Snake(Individual):
def __init__(self,
board_size: int,
chromosome: Optional[list] = None,
start_position: Optional[Point] = None,
apple_seed: Optional[int] = None,
initial_velocity: Optional[str] = None,
starting_direction: Optional[str] = None,
hidden_layer_units: Optional[List[int]] = [16, 8],
hidden_activation: Optional[str] = 'relu',
output_activation: Optional[str] = 'sigmoid',
lifespan: Optional[Union[int, float]] = np.inf,
apple_and_self_vision: Optional[str] = 'binary'
):
self.lifespan = lifespan
self.apple_and_self_vision = apple_and_self_vision.lower() # binary or distance
self.score = 0 # score... from awards and penalties
self._fitness = 0 # Overall fitness
self._frames = 0 # Number of frames that the snake has been alive
self._frames_since_last_apple = 0
self.possible_directions = ('u', 'd', 'l', 'r')
self.board_size = board_size
self.hidden_layer_units = hidden_layer_units
self.hidden_activation = hidden_activation
self.output_activation = output_activation
# if start_positionition is not defined, then initiate THE HEAD of a snake of length = 3
# (so, the box will be within 2 (e.g: [0, 1, 2]) -> box-3 (e.g: [box-3, box-2, box-1]))
if not start_position:
x = random.randint(2, self.board_size - 3)
y = random.randint(2, self.board_size - 3)
start_position = Point(x, y)
self.start_position = start_position
self._vision_type = VISION_DICT[ config['vision_type'] ] # set of slopes, config['vision_type'] = 4/8/16 directions
self._vision: List[Vision] = [None] * len(self._vision_type)
# This is just used so I can draw and is not actually used in the NN
self._drawable_vision: List[DrawableVision] = [None] * len(self._vision_type)
# Setting up network architecture
# Each "Vision" has 3 distances it tracks: wall, apple and self
# there are also one-hot encoded direction and one-hot encoded tail direction,
# each of which have 4 possibilities.
num_inputs = len(self._vision_type) * 3 + 4 + 4 #@TODO: Add one-hot back in
self.vision_as_array: np.ndarray = np.zeros((num_inputs, 1))
self.network_model = [num_inputs] # Inputs
self.network_model.extend(self.hidden_layer_units) # Hidden layers
self.network_model.append(NUM_OUTPUTS) # 4 outputs, ['u', 'd', 'l', 'r']
# If chromosome is set, take it
# otherwise, initiate a network with layers of random weights/biases
if chromosome:
self.network = chromosome
else:
self.network = Network(self.network_model,
self.hidden_activation,
self.output_activation)
# For creating the next apple
if apple_seed is None:
apple_seed = np.random.randint(-1_0000_000, 1_0000_000)
self.apple_seed = apple_seed # Only needed for saving/loading replay
self.apple_location = None
if starting_direction:
starting_direction = starting_direction[0].lower()
else:
starting_direction = self.possible_directions[random.randint(0, 3)]
self.starting_direction = starting_direction # Only needed for saving/loading replay
self.init_snake(self.starting_direction)
self.initial_velocity = initial_velocity
self.init_velocity(self.starting_direction, self.initial_velocity)
self.generate_apple()
@property
def fitness(self):
return self._fitness
def calculate_fitness(self):
# Give positive minimum fitness for roulette wheel selection
# _frames: Number of frames that the snake has been alive
self._fitness = self.score - (self._frames**2)
self._fitness = max(self._fitness, 0.1)
def update(self) -> bool:
if self.is_alive:
self._frames += 1 # Number of frames that the snake has been alive
self.look()
self.network._forward_prop(self.vision_as_array) # input array : self.vision_as_array
self.direction = self.possible_directions[np.argmax(self.network.out)]
return True
return False
def look(self):
# Look all around
# At a position, look around in 4/8/16 directions
for i, slope in enumerate(self._vision_type): # Set of slopes ( (run, rise) )
# Look around in 4/8/16 directions
vision, drawable_vision = self.look_in_direction(slope)
self._vision[i] = vision
self._drawable_vision[i] = drawable_vision
# Update the input array
self.vision_as_input_array()
def look_in_direction(self, slope: Slope) -> Tuple[Vision, DrawableVision]:
'''
At a position, look around in a specific direction
Slope: (rise, run)
'''
dist_to_wall = None
dist_to_apple = np.inf
dist_to_self = np.inf
wall_location = None
apple_location = None
self_location = None
position = self.snake_array[0].copy() # snake's head: deque(snake), snake = [head, body, tail]
# position = Point(0,0)
distance = 1.
total_distance = 0.
# Can't start by looking at yourself
position.x += slope.run
position.y += slope.rise
total_distance += distance
body_found = False # Only need to find the first occurance since it's the closest
food_found = False # Although there is only one food, stop looking once you find it
# Keep going until the position is out of bounds
while self.is_within_board(position):
if not body_found and self.is_body_location(position):
dist_to_self = total_distance
self_location = position.copy()
body_found = True
if not food_found and self.is_apple_location(position):
dist_to_apple = total_distance
apple_location = position.copy()
food_found = True
wall_location = position
position.x += slope.run
position.y += slope.rise
total_distance += distance
assert(total_distance != 0.)
# @TODO: May need to adjust numerator in case of VISION_16 since step size isn't always going to be on a tile
dist_to_wall = 1. / total_distance
if self.apple_and_self_vision == 'binary':
dist_to_apple = 1. if dist_to_apple != np.inf else 0.
dist_to_self = 1. if dist_to_self != np.inf else 0.
elif self.apple_and_self_vision == 'distance':
dist_to_apple = 1. / dist_to_apple
dist_to_self = 1. / dist_to_self
vision = Vision(dist_to_wall, dist_to_apple, dist_to_self)
drawable_vision = DrawableVision(wall_location, apple_location, self_location)
return (vision, drawable_vision)
def vision_as_input_array(self) -> None:
# Split _vision into np array where rows [0-2] are _vision[0].dist_to_wall,
# _vision[0].dist_to_apple,
# _vision[0].dist_to_self,
# rows [3-5] are _vision[1].dist_to_wall,
# _vision[1].dist_to_apple,
# _vision[1].dist_to_self, etc. etc. etc.
for va_index, v_index in zip(range(0, len(self._vision) * 3, 3), range(len(self._vision))):
vision = self._vision[v_index]
self.vision_as_array[va_index, 0] = vision.dist_to_wall
self.vision_as_array[va_index + 1, 0] = vision.dist_to_apple
self.vision_as_array[va_index + 2, 0] = vision.dist_to_self
i = len(self._vision) * 3 # Start at the end
direction = self.direction[0].lower()
# One-hot encode direction
direction_one_hot = np.zeros((len(self.possible_directions), 1))
direction_one_hot[self.possible_directions.index(direction), 0] = 1
self.vision_as_array[i: i + len(self.possible_directions)] = direction_one_hot
i += len(self.possible_directions)
# One-hot tail direction
tail_direction_one_hot = np.zeros((len(self.possible_directions), 1))
tail_direction_one_hot[self.possible_directions.index(self.tail_direction), 0] = 1
self.vision_as_array[i: i + len(self.possible_directions)] = tail_direction_one_hot
def is_within_board(self, position: Point) -> bool:
'''
Check if the snake is still within the board box
'''
return position.x >= 0 and position.y >= 0 and\
position.x < self.board_size and position.y < self.board_size
def generate_apple(self) -> None:
width = height = self.board_size # Square board
# Find all possible points where the snake is not currently
possibilities = [divmod(i, height) for i in range(width * height) if divmod(i, height) not in self.body_locations]
# same as: possibilities = [(x,y) for x in range(width) for y in range(height)]
if possibilities:
x,y = random.choice(possibilities)
self.apple_location = Point(x, y)
else:
print('You win!')
pass
def init_snake(self, starting_direction: str) -> None:
'''
Initialize the snake.
starting_direction: ('u', 'd', 'l', 'r')
direction that the snake should start facing. Whatever the direction is, the head
of the snake will begin pointing that way.
'''
# initialize position of the head: ramdom in [2, self.board_size - 3]
head = self.start_position
# Body is below
if starting_direction == 'u':
snake = [head, Point(head.x, head.y + 1), Point(head.x, head.y + 2)]
# Body is above
elif starting_direction == 'd':
snake = [head, Point(head.x, head.y - 1), Point(head.x, head.y - 2)]
# Body is to the right
elif starting_direction == 'l':
snake = [head, Point(head.x + 1, head.y), Point(head.x + 2, head.y)]
# Body is to the left
elif starting_direction == 'r':
snake = [head, Point(head.x - 1, head.y), Point(head.x - 2, head.y)]
self.snake_array = deque(snake)
self.body_locations = set(snake)
self.is_alive = True
def move(self) -> bool:
if not self.is_alive:
return False
direction = self.direction[0].lower()
# Is the direction valid?
if direction not in self.possible_directions:
return False
# Find next position
# tail = self.snake_array.pop() # Pop tail since we can technically move to the tail
head = self.snake_array[0]
if direction == 'u':
next_pos = Point(head.x, head.y - 1)
elif direction == 'd':
next_pos = Point(head.x, head.y + 1)
elif direction == 'r':
next_pos = Point(head.x + 1, head.y)
elif direction == 'l':
next_pos = Point(head.x - 1, head.y)
# Is the next position we want to move valid?
if self.is_valid(next_pos):
# Tail
if next_pos == self.snake_array[-1]:
# Pop tail and add next_pos (same as tail) to front
# No need to remove tail from body_locations since it will go back in anyway
self.snake_array.pop()
self.snake_array.appendleft(next_pos)
# No need to do with self.body_locations
# Eat the apple
elif next_pos == self.apple_location:
self.score += 1000 # If snake eats an apple, award 5000 points
self._frames_since_last_apple = 0
# Move head
self.snake_array.appendleft(next_pos)
self.body_locations.update({next_pos})
# Don't remove tail since the snake grew
self.generate_apple()
# Normal movement
else:
# Move head
self.snake_array.appendleft(next_pos)
self.body_locations.update({next_pos})
# Remove tail
tail = self.snake_array.pop()
# Remove the items that are present in both sets, AND insert the items that is not present in both sets:
self.body_locations.symmetric_difference_update({tail}) # symmetric_difference_update uses a set as arg
# Figure out which direction the tail is moving
p2 = self.snake_array[-2]
p1 = self.snake_array[-1]
diff = p2 - p1
if diff.x < 0:
self.tail_direction = 'l'
elif diff.x > 0:
self.tail_direction = 'r'
elif diff.y > 0:
self.tail_direction = 'd'
elif diff.y < 0:
self.tail_direction = 'u'
self._frames_since_last_apple += 1
# you may want to change this
if self._frames_since_last_apple > self.board_size * self.board_size:
self.is_alive = False
self.score -= 100. # If snake is dead, penalize by 150 points
return False
return True
else:
self.is_alive = False
self.score -= 100. # If snake is dead, penalize by 150 points
return False
def is_apple_location(self, position: Point) -> bool:
return position == self.apple_location
def is_body_location(self, position: Point) -> bool:
return position in self.body_locations
def is_valid(self, position: Point) -> bool:
"""
Determine whether a given position is valid.
Return True if the position is on the board and does not intersect the snake.
Return False otherwise
"""
if (position.x < 0) or (position.x > self.board_size - 1):
return False
if (position.y < 0) or (position.y > self.board_size - 1):
return False
# position == tail
if position == self.snake_array[-1]:
return True
# If the position is a body location, not valid.
# @NOTE: body_locations will contain tail, so need to check tail first
elif position in self.body_locations:
return False
# Otherwise you good
else:
return True
def init_velocity(self, starting_direction, initial_velocity: Optional[str] = None) -> None:
if initial_velocity:
self.direction = initial_velocity[0].lower()
# Whichever way the starting_direction is
else:
self.direction = starting_direction
# Tail starts moving the same direction
self.tail_direction = self.direction | <filename>helper/snake.py
import sys
import os
import json
import random
import numpy as np
from typing import Tuple, Optional, Union, Set, Dict, List, Any
from fractions import Fraction
from collections import deque
from helper.tools import Slope, Point
from helper.config import config
from helper.const import *
from network.neural_network import Network, linear, sigmoid, tanh, relu, leaky_relu, get_activation_fcn
from GA.individual import Individual
class Vision(object):
__slots__ = ('dist_to_wall', 'dist_to_apple', 'dist_to_self')
def __init__(self,
dist_to_wall: Union[float, int],
dist_to_apple: Union[float, int],
dist_to_self: Union[float, int]
):
self.dist_to_wall = float(dist_to_wall)
self.dist_to_apple = float(dist_to_apple)
self.dist_to_self = float(dist_to_self)
class DrawableVision(object):
__slots__ = ('wall_location', 'apple_location', 'self_location')
def __init__(self,
wall_location: Point,
apple_location: Optional[Point] = None,
self_location: Optional[Point] = None,
):
self.wall_location = wall_location
self.apple_location = apple_location
self.self_location = self_location
class Snake(Individual):
def __init__(self,
board_size: int,
chromosome: Optional[list] = None,
start_position: Optional[Point] = None,
apple_seed: Optional[int] = None,
initial_velocity: Optional[str] = None,
starting_direction: Optional[str] = None,
hidden_layer_units: Optional[List[int]] = [16, 8],
hidden_activation: Optional[str] = 'relu',
output_activation: Optional[str] = 'sigmoid',
lifespan: Optional[Union[int, float]] = np.inf,
apple_and_self_vision: Optional[str] = 'binary'
):
self.lifespan = lifespan
self.apple_and_self_vision = apple_and_self_vision.lower() # binary or distance
self.score = 0 # score... from awards and penalties
self._fitness = 0 # Overall fitness
self._frames = 0 # Number of frames that the snake has been alive
self._frames_since_last_apple = 0
self.possible_directions = ('u', 'd', 'l', 'r')
self.board_size = board_size
self.hidden_layer_units = hidden_layer_units
self.hidden_activation = hidden_activation
self.output_activation = output_activation
# if start_positionition is not defined, then initiate THE HEAD of a snake of length = 3
# (so, the box will be within 2 (e.g: [0, 1, 2]) -> box-3 (e.g: [box-3, box-2, box-1]))
if not start_position:
x = random.randint(2, self.board_size - 3)
y = random.randint(2, self.board_size - 3)
start_position = Point(x, y)
self.start_position = start_position
self._vision_type = VISION_DICT[ config['vision_type'] ] # set of slopes, config['vision_type'] = 4/8/16 directions
self._vision: List[Vision] = [None] * len(self._vision_type)
# This is just used so I can draw and is not actually used in the NN
self._drawable_vision: List[DrawableVision] = [None] * len(self._vision_type)
# Setting up network architecture
# Each "Vision" has 3 distances it tracks: wall, apple and self
# there are also one-hot encoded direction and one-hot encoded tail direction,
# each of which have 4 possibilities.
num_inputs = len(self._vision_type) * 3 + 4 + 4 #@TODO: Add one-hot back in
self.vision_as_array: np.ndarray = np.zeros((num_inputs, 1))
self.network_model = [num_inputs] # Inputs
self.network_model.extend(self.hidden_layer_units) # Hidden layers
self.network_model.append(NUM_OUTPUTS) # 4 outputs, ['u', 'd', 'l', 'r']
# If chromosome is set, take it
# otherwise, initiate a network with layers of random weights/biases
if chromosome:
self.network = chromosome
else:
self.network = Network(self.network_model,
self.hidden_activation,
self.output_activation)
# For creating the next apple
if apple_seed is None:
apple_seed = np.random.randint(-1_0000_000, 1_0000_000)
self.apple_seed = apple_seed # Only needed for saving/loading replay
self.apple_location = None
if starting_direction:
starting_direction = starting_direction[0].lower()
else:
starting_direction = self.possible_directions[random.randint(0, 3)]
self.starting_direction = starting_direction # Only needed for saving/loading replay
self.init_snake(self.starting_direction)
self.initial_velocity = initial_velocity
self.init_velocity(self.starting_direction, self.initial_velocity)
self.generate_apple()
@property
def fitness(self):
return self._fitness
def calculate_fitness(self):
# Give positive minimum fitness for roulette wheel selection
# _frames: Number of frames that the snake has been alive
self._fitness = self.score - (self._frames**2)
self._fitness = max(self._fitness, 0.1)
def update(self) -> bool:
if self.is_alive:
self._frames += 1 # Number of frames that the snake has been alive
self.look()
self.network._forward_prop(self.vision_as_array) # input array : self.vision_as_array
self.direction = self.possible_directions[np.argmax(self.network.out)]
return True
return False
def look(self):
# Look all around
# At a position, look around in 4/8/16 directions
for i, slope in enumerate(self._vision_type): # Set of slopes ( (run, rise) )
# Look around in 4/8/16 directions
vision, drawable_vision = self.look_in_direction(slope)
self._vision[i] = vision
self._drawable_vision[i] = drawable_vision
# Update the input array
self.vision_as_input_array()
def look_in_direction(self, slope: Slope) -> Tuple[Vision, DrawableVision]:
'''
At a position, look around in a specific direction
Slope: (rise, run)
'''
dist_to_wall = None
dist_to_apple = np.inf
dist_to_self = np.inf
wall_location = None
apple_location = None
self_location = None
position = self.snake_array[0].copy() # snake's head: deque(snake), snake = [head, body, tail]
# position = Point(0,0)
distance = 1.
total_distance = 0.
# Can't start by looking at yourself
position.x += slope.run
position.y += slope.rise
total_distance += distance
body_found = False # Only need to find the first occurance since it's the closest
food_found = False # Although there is only one food, stop looking once you find it
# Keep going until the position is out of bounds
while self.is_within_board(position):
if not body_found and self.is_body_location(position):
dist_to_self = total_distance
self_location = position.copy()
body_found = True
if not food_found and self.is_apple_location(position):
dist_to_apple = total_distance
apple_location = position.copy()
food_found = True
wall_location = position
position.x += slope.run
position.y += slope.rise
total_distance += distance
assert(total_distance != 0.)
# @TODO: May need to adjust numerator in case of VISION_16 since step size isn't always going to be on a tile
dist_to_wall = 1. / total_distance
if self.apple_and_self_vision == 'binary':
dist_to_apple = 1. if dist_to_apple != np.inf else 0.
dist_to_self = 1. if dist_to_self != np.inf else 0.
elif self.apple_and_self_vision == 'distance':
dist_to_apple = 1. / dist_to_apple
dist_to_self = 1. / dist_to_self
vision = Vision(dist_to_wall, dist_to_apple, dist_to_self)
drawable_vision = DrawableVision(wall_location, apple_location, self_location)
return (vision, drawable_vision)
def vision_as_input_array(self) -> None:
# Split _vision into np array where rows [0-2] are _vision[0].dist_to_wall,
# _vision[0].dist_to_apple,
# _vision[0].dist_to_self,
# rows [3-5] are _vision[1].dist_to_wall,
# _vision[1].dist_to_apple,
# _vision[1].dist_to_self, etc. etc. etc.
for va_index, v_index in zip(range(0, len(self._vision) * 3, 3), range(len(self._vision))):
vision = self._vision[v_index]
self.vision_as_array[va_index, 0] = vision.dist_to_wall
self.vision_as_array[va_index + 1, 0] = vision.dist_to_apple
self.vision_as_array[va_index + 2, 0] = vision.dist_to_self
i = len(self._vision) * 3 # Start at the end
direction = self.direction[0].lower()
# One-hot encode direction
direction_one_hot = np.zeros((len(self.possible_directions), 1))
direction_one_hot[self.possible_directions.index(direction), 0] = 1
self.vision_as_array[i: i + len(self.possible_directions)] = direction_one_hot
i += len(self.possible_directions)
# One-hot tail direction
tail_direction_one_hot = np.zeros((len(self.possible_directions), 1))
tail_direction_one_hot[self.possible_directions.index(self.tail_direction), 0] = 1
self.vision_as_array[i: i + len(self.possible_directions)] = tail_direction_one_hot
def is_within_board(self, position: Point) -> bool:
'''
Check if the snake is still within the board box
'''
return position.x >= 0 and position.y >= 0 and\
position.x < self.board_size and position.y < self.board_size
def generate_apple(self) -> None:
width = height = self.board_size # Square board
# Find all possible points where the snake is not currently
possibilities = [divmod(i, height) for i in range(width * height) if divmod(i, height) not in self.body_locations]
# same as: possibilities = [(x,y) for x in range(width) for y in range(height)]
if possibilities:
x,y = random.choice(possibilities)
self.apple_location = Point(x, y)
else:
print('You win!')
pass
def init_snake(self, starting_direction: str) -> None:
'''
Initialize the snake.
starting_direction: ('u', 'd', 'l', 'r')
direction that the snake should start facing. Whatever the direction is, the head
of the snake will begin pointing that way.
'''
# initialize position of the head: ramdom in [2, self.board_size - 3]
head = self.start_position
# Body is below
if starting_direction == 'u':
snake = [head, Point(head.x, head.y + 1), Point(head.x, head.y + 2)]
# Body is above
elif starting_direction == 'd':
snake = [head, Point(head.x, head.y - 1), Point(head.x, head.y - 2)]
# Body is to the right
elif starting_direction == 'l':
snake = [head, Point(head.x + 1, head.y), Point(head.x + 2, head.y)]
# Body is to the left
elif starting_direction == 'r':
snake = [head, Point(head.x - 1, head.y), Point(head.x - 2, head.y)]
self.snake_array = deque(snake)
self.body_locations = set(snake)
self.is_alive = True
def move(self) -> bool:
if not self.is_alive:
return False
direction = self.direction[0].lower()
# Is the direction valid?
if direction not in self.possible_directions:
return False
# Find next position
# tail = self.snake_array.pop() # Pop tail since we can technically move to the tail
head = self.snake_array[0]
if direction == 'u':
next_pos = Point(head.x, head.y - 1)
elif direction == 'd':
next_pos = Point(head.x, head.y + 1)
elif direction == 'r':
next_pos = Point(head.x + 1, head.y)
elif direction == 'l':
next_pos = Point(head.x - 1, head.y)
# Is the next position we want to move valid?
if self.is_valid(next_pos):
# Tail
if next_pos == self.snake_array[-1]:
# Pop tail and add next_pos (same as tail) to front
# No need to remove tail from body_locations since it will go back in anyway
self.snake_array.pop()
self.snake_array.appendleft(next_pos)
# No need to do with self.body_locations
# Eat the apple
elif next_pos == self.apple_location:
self.score += 1000 # If snake eats an apple, award 5000 points
self._frames_since_last_apple = 0
# Move head
self.snake_array.appendleft(next_pos)
self.body_locations.update({next_pos})
# Don't remove tail since the snake grew
self.generate_apple()
# Normal movement
else:
# Move head
self.snake_array.appendleft(next_pos)
self.body_locations.update({next_pos})
# Remove tail
tail = self.snake_array.pop()
# Remove the items that are present in both sets, AND insert the items that is not present in both sets:
self.body_locations.symmetric_difference_update({tail}) # symmetric_difference_update uses a set as arg
# Figure out which direction the tail is moving
p2 = self.snake_array[-2]
p1 = self.snake_array[-1]
diff = p2 - p1
if diff.x < 0:
self.tail_direction = 'l'
elif diff.x > 0:
self.tail_direction = 'r'
elif diff.y > 0:
self.tail_direction = 'd'
elif diff.y < 0:
self.tail_direction = 'u'
self._frames_since_last_apple += 1
# you may want to change this
if self._frames_since_last_apple > self.board_size * self.board_size:
self.is_alive = False
self.score -= 100. # If snake is dead, penalize by 150 points
return False
return True
else:
self.is_alive = False
self.score -= 100. # If snake is dead, penalize by 150 points
return False
def is_apple_location(self, position: Point) -> bool:
return position == self.apple_location
def is_body_location(self, position: Point) -> bool:
return position in self.body_locations
def is_valid(self, position: Point) -> bool:
"""
Determine whether a given position is valid.
Return True if the position is on the board and does not intersect the snake.
Return False otherwise
"""
if (position.x < 0) or (position.x > self.board_size - 1):
return False
if (position.y < 0) or (position.y > self.board_size - 1):
return False
# position == tail
if position == self.snake_array[-1]:
return True
# If the position is a body location, not valid.
# @NOTE: body_locations will contain tail, so need to check tail first
elif position in self.body_locations:
return False
# Otherwise you good
else:
return True
def init_velocity(self, starting_direction, initial_velocity: Optional[str] = None) -> None:
if initial_velocity:
self.direction = initial_velocity[0].lower()
# Whichever way the starting_direction is
else:
self.direction = starting_direction
# Tail starts moving the same direction
self.tail_direction = self.direction | en | 0.875804 | # binary or distance # score... from awards and penalties # Overall fitness # Number of frames that the snake has been alive # if start_positionition is not defined, then initiate THE HEAD of a snake of length = 3 # (so, the box will be within 2 (e.g: [0, 1, 2]) -> box-3 (e.g: [box-3, box-2, box-1])) # set of slopes, config['vision_type'] = 4/8/16 directions # This is just used so I can draw and is not actually used in the NN # Setting up network architecture # Each "Vision" has 3 distances it tracks: wall, apple and self # there are also one-hot encoded direction and one-hot encoded tail direction, # each of which have 4 possibilities. #@TODO: Add one-hot back in # Inputs # Hidden layers # 4 outputs, ['u', 'd', 'l', 'r'] # If chromosome is set, take it # otherwise, initiate a network with layers of random weights/biases # For creating the next apple # Only needed for saving/loading replay # Only needed for saving/loading replay # Give positive minimum fitness for roulette wheel selection # _frames: Number of frames that the snake has been alive # Number of frames that the snake has been alive # input array : self.vision_as_array # Look all around # At a position, look around in 4/8/16 directions # Set of slopes ( (run, rise) ) # Look around in 4/8/16 directions # Update the input array At a position, look around in a specific direction
Slope: (rise, run) # snake's head: deque(snake), snake = [head, body, tail] # position = Point(0,0) # Can't start by looking at yourself # Only need to find the first occurance since it's the closest # Although there is only one food, stop looking once you find it # Keep going until the position is out of bounds # @TODO: May need to adjust numerator in case of VISION_16 since step size isn't always going to be on a tile # Split _vision into np array where rows [0-2] are _vision[0].dist_to_wall, # _vision[0].dist_to_apple, # _vision[0].dist_to_self, # rows [3-5] are _vision[1].dist_to_wall, # _vision[1].dist_to_apple, # _vision[1].dist_to_self, etc. etc. etc. # Start at the end # One-hot encode direction # One-hot tail direction Check if the snake is still within the board box # Square board # Find all possible points where the snake is not currently # same as: possibilities = [(x,y) for x in range(width) for y in range(height)] Initialize the snake.
starting_direction: ('u', 'd', 'l', 'r')
direction that the snake should start facing. Whatever the direction is, the head
of the snake will begin pointing that way. # initialize position of the head: ramdom in [2, self.board_size - 3] # Body is below # Body is above # Body is to the right # Body is to the left # Is the direction valid? # Find next position # tail = self.snake_array.pop() # Pop tail since we can technically move to the tail # Is the next position we want to move valid? # Tail # Pop tail and add next_pos (same as tail) to front # No need to remove tail from body_locations since it will go back in anyway # No need to do with self.body_locations # Eat the apple # If snake eats an apple, award 5000 points # Move head # Don't remove tail since the snake grew # Normal movement # Move head # Remove tail # Remove the items that are present in both sets, AND insert the items that is not present in both sets: # symmetric_difference_update uses a set as arg # Figure out which direction the tail is moving # you may want to change this # If snake is dead, penalize by 150 points # If snake is dead, penalize by 150 points Determine whether a given position is valid.
Return True if the position is on the board and does not intersect the snake.
Return False otherwise # position == tail # If the position is a body location, not valid. # @NOTE: body_locations will contain tail, so need to check tail first # Otherwise you good # Whichever way the starting_direction is # Tail starts moving the same direction | 2.357844 | 2 |
6 kyu/Which are in.py | mwk0408/codewars_solutions | 6 | 6616149 | <filename>6 kyu/Which are in.py
def in_array(array1, array2):
result=[]
for word_one in set(array1):
for word_two in array2:
if word_one in word_two:
result.append(word_one)
break
result.sort()
return result | <filename>6 kyu/Which are in.py
def in_array(array1, array2):
result=[]
for word_one in set(array1):
for word_two in array2:
if word_one in word_two:
result.append(word_one)
break
result.sort()
return result | none | 1 | 3.046907 | 3 | |
Q-learning/plot.py | skyknights/reinforcement-learning-tutorials | 1 | 6616150 | <reponame>skyknights/reinforcement-learning-tutorials
#!/usr/bin/env python
# coding=utf-8
'''
Author: John
Email: <EMAIL>
Date: 2020-10-07 20:57:11
LastEditor: John
LastEditTime: 2020-10-07 21:00:29
Discription:
Environment:
'''
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import os
def plot(item,ylabel='rewards'):
sns.set()
plt.figure()
plt.plot(np.arange(len(item)), item)
plt.title(ylabel+' of Q-learning')
plt.ylabel(ylabel)
plt.xlabel('episodes')
plt.savefig(os.path.dirname(__file__)+"/result/"+ylabel+".png")
plt.show()
if __name__ == "__main__":
output_path = os.path.dirname(__file__)+"/result/"
rewards=np.load(output_path+"rewards_train.npy", )
MA_rewards=np.load(output_path+"MA_rewards_train.npy")
steps = np.load(output_path+"steps_train.npy")
plot(rewards)
plot(MA_rewards,ylabel='moving_average_rewards')
plot(steps,ylabel='steps') | #!/usr/bin/env python
# coding=utf-8
'''
Author: John
Email: <EMAIL>
Date: 2020-10-07 20:57:11
LastEditor: John
LastEditTime: 2020-10-07 21:00:29
Discription:
Environment:
'''
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import os
def plot(item,ylabel='rewards'):
sns.set()
plt.figure()
plt.plot(np.arange(len(item)), item)
plt.title(ylabel+' of Q-learning')
plt.ylabel(ylabel)
plt.xlabel('episodes')
plt.savefig(os.path.dirname(__file__)+"/result/"+ylabel+".png")
plt.show()
if __name__ == "__main__":
output_path = os.path.dirname(__file__)+"/result/"
rewards=np.load(output_path+"rewards_train.npy", )
MA_rewards=np.load(output_path+"MA_rewards_train.npy")
steps = np.load(output_path+"steps_train.npy")
plot(rewards)
plot(MA_rewards,ylabel='moving_average_rewards')
plot(steps,ylabel='steps') | en | 0.601171 | #!/usr/bin/env python # coding=utf-8 Author: John Email: <EMAIL> Date: 2020-10-07 20:57:11 LastEditor: John LastEditTime: 2020-10-07 21:00:29 Discription: Environment: | 2.850583 | 3 |