blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
213 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
246 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
7f1e95dd5b64e5a2682de80d0869298b7d501662
34233a495b1d095984f7cbdfb10702daaac75483
/4-5_wave_analyze.py
f11af2619766d32950c0981de89c43aa1b952f3a
[]
no_license
ZuluSierraHotel/correction-ebook
52b09b8d3527ca8597a3480d29683809197b6d86
08fe0b72ab0f2f4ab49ada44d4b0b40c0552646c
refs/heads/master
2020-05-26T06:21:47.684510
2019-05-24T01:46:01
2019-05-24T01:46:01
188,134,494
0
0
null
null
null
null
UTF-8
Python
false
false
489
py
#-*- coding: utf-8 -*- #利用小波分析进行特征分析 #参数初始化 inputfile= '../data/leleccum.mat' #提取自Matlab的信号文件 from scipy.io import loadmat #mat是MATLAB专用格式,需要用loadmat读取它 mat = loadmat(inputfile) signal = mat['leleccum'][0] import pywt #导入PyWavelets coeffs = pywt.wavedec(signal, 'bior3.7', level = 5) #返回结果为level+1个数字,第一个数组为逼近系数数组,后面的依次是细节系数数组 print(coeffs)
[ "learner_kindle@163.com" ]
learner_kindle@163.com
7725472e66c0946eb2a38b1cd4d048d5d1d76a14
8590cd4e45a055faa2f5c7e2de8d726c4591e585
/dontfret/cart/forms.py
bd9f0479c748c6e8d92a8de29cee01779281e22b
[]
no_license
BenCOGC/DontFret
8f4a2e9099c3b2e91fddcafb3e4261b3c7cd7fe6
a3724c4f16f97ce931ae27b5edfed41e8bcdfaea
refs/heads/master
2022-09-15T02:10:36.933196
2020-05-25T11:08:25
2020-05-25T11:08:25
266,751,749
0
0
null
null
null
null
UTF-8
Python
false
false
1,218
py
""" Title: cart:forms Author: Ben Frame Date: 09/04/2020 """ # Imports from django import forms from order.models import Order from django.core.validators import RegexValidator # Form for creation of User (and also as a template for editing user details) # Form for getting card details for a purchase class CardPaymentForm(forms.Form): cardNo = forms.CharField\ (max_length=16, default='0000000000000000', verbose_name='Card No.',validators=[RegexValidator(r'^\d{1,10}$')]) cardExpiryDateMonth = forms.CharField\ (max_length=2, default='00', verbose_name='Card Expiry Date', validators=[RegexValidator(r'^\d{1,10}$')]) cardExpiryDateYear = forms.CharField\ (max_length=4, default='0000', verbose_name='Card Expiry Date', validators=[RegexValidator(r'^\d{1,10}$')]) cardCCV = forms.CharField\ (max_length=3, default='000', verbose_name='CCV No (Back Of Card)', help_text='The last 3 numbers on the back of your card', validators=[RegexValidator(r'^\d{1,10}$')]) class Meta: model = Order # Save data as part of a User model (as part of Python/Django) fields = ('cardNo', 'cardExpiryDateMonth', 'cardExpiryDateYear', 'cardCCV') # Create fields
[ "30154302@cityofglacol.ac.uk" ]
30154302@cityofglacol.ac.uk
0a02cfb6413dbcd6b1100af6c17d4c6cfe17d441
4e5141121d8b4015db233cbc71946ec3cfbe5fe6
/samples/basic/crud/models/cisco-ios-xr/Cisco-IOS-XR-mpls-ldp-cfg/nc-create-xr-mpls-ldp-cfg-10-ydk.py
f47ee0307ac50c7ebc241508e283965e38ccc6e3
[ "Apache-2.0" ]
permissive
itbj/ydk-py-samples
898c6c9bad9d6f8072892300d42633d82ec38368
c5834091da0ebedbb11af7bbf780f268aad7040b
refs/heads/master
2022-11-20T17:44:58.844428
2020-07-25T06:18:02
2020-07-25T06:18:02
282,382,442
1
0
null
2020-07-25T06:04:51
2020-07-25T06:04:50
null
UTF-8
Python
false
false
2,702
py
#!/usr/bin/env python # # Copyright 2016 Cisco Systems, 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. # """ Create configuration for model Cisco-IOS-XR-mpls-ldp-cfg. usage: nc-create-xr-mpls-ldp-cfg-10-ydk.py [-h] [-v] device positional arguments: device NETCONF device (ssh://user:password@host:port) optional arguments: -h, --help show this help message and exit -v, --verbose print debugging messages """ from argparse import ArgumentParser from urlparse import urlparse from ydk.services import CRUDService from ydk.providers import NetconfServiceProvider from ydk.models.cisco_ios_xr import Cisco_IOS_XR_mpls_ldp_cfg \ as xr_mpls_ldp_cfg import logging def config_mpls_ldp(mpls_ldp): """Add config data to mpls_ldp object.""" pass if __name__ == "__main__": """Execute main program.""" parser = ArgumentParser() parser.add_argument("-v", "--verbose", help="print debugging messages", action="store_true") parser.add_argument("device", help="NETCONF device (ssh://user:password@host:port)") args = parser.parse_args() device = urlparse(args.device) # log debug messages if verbose argument specified if args.verbose: logger = logging.getLogger("ydk") logger.setLevel(logging.INFO) handler = logging.StreamHandler() formatter = logging.Formatter(("%(asctime)s - %(name)s - " "%(levelname)s - %(message)s")) handler.setFormatter(formatter) logger.addHandler(handler) # create NETCONF provider provider = NetconfServiceProvider(address=device.hostname, port=device.port, username=device.username, password=device.password, protocol=device.scheme) # create CRUD service crud = CRUDService() mpls_ldp = xr_mpls_ldp_cfg.MplsLdp() # create object config_mpls_ldp(mpls_ldp) # add object configuration # create configuration on NETCONF device # crud.create(provider, mpls_ldp) exit() # End of script
[ "saalvare@cisco.com" ]
saalvare@cisco.com
f5aabf9374ec65309773370be3bd51e62c7c7c2f
3c000380cbb7e8deb6abf9c6f3e29e8e89784830
/venv/Lib/site-packages/cobra/modelimpl/l3ext/fabricextroutingpdef.py
84fe07b6043470b85fee2d3ae47f5391333a6ec8
[]
no_license
bkhoward/aciDOM
91b0406f00da7aac413a81c8db2129b4bfc5497b
f2674456ecb19cf7299ef0c5a0887560b8b315d0
refs/heads/master
2023-03-27T23:37:02.836904
2021-03-26T22:07:54
2021-03-26T22:07:54
351,855,399
0
0
null
null
null
null
UTF-8
Python
false
false
6,038
py
# coding=UTF-8 # ********************************************************************** # Copyright (c) 2013-2020 Cisco Systems, Inc. All rights reserved # written by zen warriors, do not modify! # ********************************************************************** from cobra.mit.meta import ClassMeta from cobra.mit.meta import StatsClassMeta from cobra.mit.meta import CounterMeta from cobra.mit.meta import PropMeta from cobra.mit.meta import Category from cobra.mit.meta import SourceRelationMeta from cobra.mit.meta import NamedSourceRelationMeta from cobra.mit.meta import TargetRelationMeta from cobra.mit.meta import DeploymentPathMeta, DeploymentCategory from cobra.model.category import MoCategory, PropCategory, CounterCategory from cobra.mit.mo import Mo # ################################################## class FabricExtRoutingPDef(Mo): """ Mo doc not defined in techpub!!! """ meta = ClassMeta("cobra.model.l3ext.FabricExtRoutingPDef") meta.moClassName = "l3extFabricExtRoutingPDef" meta.rnFormat = "fabricExtRoutingP-%(name)s" meta.category = MoCategory.REGULAR meta.label = "Fabric External Routing Profile Definition" meta.writeAccessMask = 0x20000001 meta.readAccessMask = 0x20000001 meta.isDomainable = False meta.isReadOnly = True meta.isConfigurable = False meta.isDeletable = False meta.isContextRoot = False meta.childClasses.add("cobra.model.fault.Counts") meta.childClasses.add("cobra.model.health.Inst") meta.childClasses.add("cobra.model.fault.Delegate") meta.childClasses.add("cobra.model.l3ext.SubnetDef") meta.childNamesAndRnPrefix.append(("cobra.model.l3ext.SubnetDef", "extsubnet-")) meta.childNamesAndRnPrefix.append(("cobra.model.fault.Counts", "fltCnts")) meta.childNamesAndRnPrefix.append(("cobra.model.health.Inst", "health")) meta.childNamesAndRnPrefix.append(("cobra.model.fault.Delegate", "fd-")) meta.parentClasses.add("cobra.model.fv.FabricExtConnPDef") meta.superClasses.add("cobra.model.fabric.ProtoPol") meta.superClasses.add("cobra.model.fabric.L3ProtoPol") meta.superClasses.add("cobra.model.naming.NamedObject") meta.superClasses.add("cobra.model.pol.Obj") meta.superClasses.add("cobra.model.pol.Def") meta.superClasses.add("cobra.model.l3ext.AFabricExtRoutingP") meta.rnPrefixes = [ ('fabricExtRoutingP-', True), ] prop = PropMeta("str", "childAction", "childAction", 4, PropCategory.CHILD_ACTION) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop._addConstant("deleteAll", "deleteall", 16384) prop._addConstant("deleteNonPresent", "deletenonpresent", 8192) prop._addConstant("ignore", "ignore", 4096) meta.props.add("childAction", prop) prop = PropMeta("str", "descr", "descr", 5579, PropCategory.REGULAR) prop.label = "Description" prop.isConfig = True prop.isAdmin = True prop.range = [(0, 128)] prop.regex = ['[a-zA-Z0-9\\!#$%()*,-./:;@ _{|}~?&+]+'] meta.props.add("descr", prop) prop = PropMeta("str", "dn", "dn", 1, PropCategory.DN) prop.label = "None" prop.isDn = True prop.isImplicit = True prop.isAdmin = True prop.isCreateOnly = True meta.props.add("dn", prop) prop = PropMeta("str", "lcOwn", "lcOwn", 9, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "local" prop._addConstant("implicit", "implicit", 4) prop._addConstant("local", "local", 0) prop._addConstant("policy", "policy", 1) prop._addConstant("replica", "replica", 2) prop._addConstant("resolveOnBehalf", "resolvedonbehalf", 3) meta.props.add("lcOwn", prop) prop = PropMeta("str", "modTs", "modTs", 7, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "never" prop._addConstant("never", "never", 0) meta.props.add("modTs", prop) prop = PropMeta("str", "name", "name", 21428, PropCategory.REGULAR) prop.label = "Name" prop.isConfig = True prop.isAdmin = True prop.isCreateOnly = True prop.isNaming = True prop.range = [(1, 64)] prop.regex = ['[a-zA-Z0-9_.:-]+'] meta.props.add("name", prop) prop = PropMeta("str", "nameAlias", "nameAlias", 28417, PropCategory.REGULAR) prop.label = "Name alias" prop.isConfig = True prop.isAdmin = True prop.range = [(0, 63)] prop.regex = ['[a-zA-Z0-9_.-]+'] meta.props.add("nameAlias", prop) prop = PropMeta("str", "ownerKey", "ownerKey", 15230, PropCategory.REGULAR) prop.label = "None" prop.isConfig = True prop.isAdmin = True prop.range = [(0, 128)] prop.regex = ['[a-zA-Z0-9\\!#$%()*,-./:;@ _{|}~?&+]+'] meta.props.add("ownerKey", prop) prop = PropMeta("str", "ownerTag", "ownerTag", 15231, PropCategory.REGULAR) prop.label = "None" prop.isConfig = True prop.isAdmin = True prop.range = [(0, 64)] prop.regex = ['[a-zA-Z0-9\\!#$%()*,-./:;@ _{|}~?&+]+'] meta.props.add("ownerTag", prop) prop = PropMeta("str", "rn", "rn", 2, PropCategory.RN) prop.label = "None" prop.isRn = True prop.isImplicit = True prop.isAdmin = True prop.isCreateOnly = True meta.props.add("rn", prop) prop = PropMeta("str", "status", "status", 3, PropCategory.STATUS) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop._addConstant("created", "created", 2) prop._addConstant("deleted", "deleted", 8) prop._addConstant("modified", "modified", 4) meta.props.add("status", prop) meta.namingProps.append(getattr(meta.props, "name")) def __init__(self, parentMoOrDn, name, markDirty=True, **creationProps): namingVals = [name] Mo.__init__(self, parentMoOrDn, markDirty, *namingVals, **creationProps) # End of package file # ##################################################
[ "bkhoward@live.com" ]
bkhoward@live.com
5b9bb498f91537b40a96ded19b45ecbbc1ae5142
44699ef0c7016802e1b60458b78b7cce7d1bcb26
/applications/lrc/apps.py
fa9f2129bd5fcac8e5aa5ac119499909a8913aea
[]
no_license
bhdrkcr/django-login-register-crud
99e989bf042577f842308e06ae5d0eeb13477da0
3946a6b14835f393ab0fcc77ca815a337a0cfb1a
refs/heads/main
2023-08-13T20:06:11.947015
2021-10-18T13:05:46
2021-10-18T13:05:46
417,811,571
0
0
null
null
null
null
UTF-8
Python
false
false
138
py
from django.apps import AppConfig class LrcConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'lrc'
[ "bahadir2kacar@gmail.com" ]
bahadir2kacar@gmail.com
cebd8d83e32d5a6f2a3cff708a8e4da0c017e126
06e15934a144fb14f47e85de7cd0097d16f0b542
/admin/user/views/admin.py
d012fa63a87fc0fc950545673abbf69881cb6318
[]
no_license
sclzzhanghaijun/django-cms
b79649129c1810259da6525121e0a597a61ac37b
ccb5363703d47f7bb721fdd12d8b8f7f84c8a220
refs/heads/master
2021-06-24T03:48:52.485657
2020-05-06T07:59:51
2020-05-06T07:59:51
144,838,184
3
1
null
2021-06-10T20:44:25
2018-08-15T10:14:07
Python
UTF-8
Python
false
false
7,732
py
# encoding=utf-8 from django.http import JsonResponse from django.shortcuts import render from django.db.models import Count from django.template.defaultfilters import date from admin.user.models import AdminUser from admin.utils.response import * from common.model.PAdminGroups import PAdminGroups from common.model.PAdminGroupsUser import PAdminGroupsUser from django.db import transaction from django.contrib.auth.hashers import make_password from admin.user.forms.Admin import * def admin_user(request): return render(request, 'admin/user/admin_user_list.html') def admin_user_list(request): page = int(request.GET['page']) limit = int(request.GET['limit']) nick_name = request.GET['nick_name'] phone = request.GET['phone'] user_id = request.GET['id'] gender = request.GET['gender'] where = { 'is_delete': 0 } if nick_name.strip() != '': where['nick_name'] = nick_name if phone != '': where['phone'] = phone if user_id != '': where['id'] = user_id if gender != '': where['gender'] = gender start_row = (page - 1) * limit end_row = start_row + limit count = AdminUser.objects.filter(**where).all().aggregate(count=Count('id')) data = AdminUser.objects.filter(**where).order_by('-id').values()[start_row:end_row] data = list(data) for items in data: items['last_login'] = date(items['last_login'], 'Y-m-d H:i:s') if items['gender'] == 'female': items['gender'] = '女' else: items['gender'] = '男' if items['is_active'] == 1: items['is_active'] = '启用' else: items['is_active'] = '禁用' if items['is_superuser'] == 1: items['is_superuser'] = '是' else: items['is_superuser'] = '否' return load_data(request, count['count'], data) def admin_user_detail(request): if request.method == "GET": user_id = int(request.GET['user_id']) else: user_id = int(request.POST['user_id']) if user_id <= 0: return error(request, u'用户ID有误') user_object = AdminUser.objects.filter(id=user_id, is_delete=0).get() if user_object is None: return error(request, u'用户不存在,用户ID有误') return render(request, 'admin/user/admin_user_detail.html', {'user_info': user_object}) def admin_user_edit(request): if request.method == "GET": user_id = int(request.GET['user_id']) else: user_id = int(request.POST['user_id']) if user_id <= 0: return error(request, u'用户ID有误') user_object = AdminUser.objects.filter(id=user_id, is_delete=0).get() if user_object is None: return error(request, u'用户不存在,用户ID有误') if request.is_ajax(): data = request.POST check_form = AdminEditForms(data) if check_form.is_valid(): admin = AdminUser.objects.get(id=data['user_id']) if data['user_id'] == 1: admin.first_name = data['first_name'] admin.last_name = data['last_name'] admin.email = data['email'] admin.nick_name = data['nick_name'] admin.gender = data['gender'] admin.address = data['address'] admin.phone = data['phone'] admin.birthday = data['birthday'] else: admin.first_name = data['first_name'] admin.last_name = data['last_name'] admin.email = data['email'] admin.nick_name = data['nick_name'] admin.gender = data['gender'] admin.address = data['address'] admin.phone = data['phone'] admin.birthday = data['birthday'] admin.is_staff = data['is_staff'] admin.is_active = data['is_active'] admin.is_superuser = data['is_superuser'] result = admin.save() if result is None: return success(request, u'修改用户信息成功') else: return error(request, u'修改用户信息失败') else: return error(request, check_form.errors) else: return render(request, 'admin/user/admin_user_edit.html', {'user_info': user_object}) @transaction.atomic def admin_user_add(request): where = { 'is_delete': 0, 'group_status': 0 } groupList = PAdminGroups.objects.filter(**where).all() if request.method == "POST": sid = transaction.savepoint() is_success = True try: data = request.POST check_form = AdminForms(data) if check_form.is_valid(): admin_id = AdminUser.objects.create( password=make_password(data['password']), is_superuser=data['is_superuser'], username=data['username'], first_name=data['first_name'], last_name=data['last_name'], email=data['email'], is_staff=data['is_staff'], is_active=data['is_active'], nick_name=data['nick_name'], gender=data['gender'], address=data['address'], phone=data['phone'], birthday=data['birthday'], ) result = PAdminGroupsUser.objects.create(group_id=data['group_id'], admin_id=admin_id.id) print(result) if result is None: is_success = False else: return error(request, check_form.errors) except Exception as e: is_success = False if is_success == True: transaction.savepoint_commit(sid) return success(request, u'添加成功') else: transaction.savepoint_rollback(sid) return error(request, u'添加失败') else: return render(request, 'admin/user/admin_user_add.html', {'groupList': groupList}) def admin_user_delete(request): user_id = int(request.POST['user_id']) if user_id <= 0: return error(request, u'用户ID有误') user_object = AdminUser.objects.filter(id=user_id, is_delete=0).get() if user_object is None: return error(request, u'用户不存在,用户ID有误') user_object.is_delete = 1 result = user_object.save() if result is None: return success(request, u'删除用户成功') else: return error(request, u'删除用户失败') def admin_user_change_password(request): if request.method == "GET": user_id = int(request.GET['user_id']) else: user_id = int(request.POST['user_id']) if user_id <= 0: return error(request, u'用户ID有误') user_object = AdminUser.objects.filter(id=user_id).get() if user_object is None: return error(request, u'用户不存在,用户ID有误') if request.is_ajax(): data = request.POST check_form = AdminChangePasswordForms(data) if check_form.is_valid(): user = AdminUser.objects.get(id=data['user_id']) user.set_password(data['password']) result = user.save() if result is None: return success(request, u'修改密码成功') else: return error(request, u'修改密码失败') else: return error(request, check_form.errors) else: return render(request, 'admin/user/admin_user_change_password.html', {'user_info': user_object})
[ "7192185@qq.com" ]
7192185@qq.com
bda7024b5797dc2379f63fc15bb68ec054bc7343
fb20331d30b1ea399d5b2144cdacd0954f625eb1
/udemy_courses/The_Ultimate_Flask_Course/19.Flask-Security/app.py
50fcd7d0c8deb6dc1cf8884bfb6c4b1ed6be197a
[]
no_license
foxcodenine/tutorials
df2303568bcca9f3619c7625481b4681ebf895e2
42e53a2fbbadd915f14a4f962a9c4c38b7a23e39
refs/heads/master
2023-08-30T11:35:11.339853
2023-08-28T14:05:05
2023-08-28T14:05:05
206,948,465
0
0
null
2023-03-15T10:05:49
2019-09-07T09:52:12
PHP
UTF-8
Python
false
false
7,705
py
# https://pythonhosted.org/Flask-Security/quickstart.html # ______________________________________________________________________ from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, \ RoleMixin, login_required, login_required, current_user, roles_accepted, \ roles_required, http_auth_required from uuid import uuid4 from flask_mail import Mail from flask_security.forms import RegisterForm, ConfirmRegisterForm, SendConfirmationForm from wtforms import StringField, IntegerField from wtforms.validators import InputRequired # ______________________________________________________________________ app = Flask(__name__) app.config['DEBUG'] = True app.config['SECRET_KEY'] = uuid4().hex app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///p:/Projects/tutorials/Udemy/The Ultimate Flask Course/19.Flask-Security/security.db' # app.config['SQLALCHEMY_DATABASE_URI']='sqlite:////mnt/d/Projects/tutorials/Udemy/The Ultimate Flask Course/19.Flask-Security/security.db' # This is used to access the registry page: http://127.0.0.1:5000/register app.config['SECURITY_REGISTERABLE'] = True # This is used to register: app.config['SECURITY_PASSWORD_SALT'] = 'This_is_a_secret' # to remove the error: AttributeError: 'NoneType' object has no attribute 'send' # since email is not setup yet # app.config['SECURITY_SEND_REGISTER_EMAIL'] = False app.config['SECURITY_SEND_REGISTER_EMAIL'] = True # This is used to allow the reset password page: http://127.0.0.1:5000/reset app.config['SECURITY_RECOVERABLE'] = True # This is used to allow the change password page: http://127.0.0.1:5000/change app.config['SECURITY_CHANGEABLE'] = True # This is used to redirect to this route after chnage pass, change it to try: app.config['SECURITY_POST_CHANGE_VIEW'] = 'pass_changed' # to remove the error: AttributeError: 'NoneType' object has no attribute 'send' # since email is not setup yet app.config['SECURITY_SEND_PASSWORD_CHANGE_EMAIL'] = False # This is to send a confermation email: app.config['SECURITY_CONFIRMABLE'] = True # rediredting to this url after selecting the confirm link in email: app.config['SECURITY_POST_CONFIRM_VIEW'] = '/confirmed' app.config.update( MAIL_SERVER = 'smtp.gmail.com', MAIL_USERNAME = 'farrugiachris12@gmail.com', MAIL_PASSWORD = 'orange-6', MAIL_DEFAULT_SENDER = ('Chris from flask-mail','no-reply@example.com'), MAIL_PORT = 465, MAIL_USE_TLS = False, MAIL_USE_SSL = True ) # app.config['SECURITY_EMAIL_SENDER'] = 'farrugiachris12@gmail.com' # app.config['SECURITY_EMAIL_SENDER'] = 'chrismariojimmy@yahoo.com' # custimize subject app.config['SECURITY_EMAIL_SUBJECT_REGISTER'] = 'This is a custimized Welcome ;)' # as name sugest: app.config['SECURITY_EMAIL_PLAINTEXT'] = True app.config['SECURITY_EMAIL_HTML'] = False db = SQLAlchemy(app) mail = Mail(app) # ______________________________________________________________________ roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) name = db.Column(db.String(255)) age = db.Column(db.Integer) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) # We have added two field to the default db ,name and age. # Here we are extending the form field from the defaul RegisterForm. # To know which form to extend from you need to check form.py from github # or localy from your site-packages folder (check ref (D) below for path). # The process is similar to flask-wdt forms. class ExtendedRegisterForm(ConfirmRegisterForm): name = StringField('Fullname', validators=[InputRequired()]) age = IntegerField('Age') # the above woulden't work so i have edit the forms.py in my localy # site-packages folder at flask-secrity (check ref (D) below for path). # I have marke it with the following text: ''' I have edited this Class and I have added this Class''' # have copyed the forms.py to this dir for ref. # ______________________________________________________________________ user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore, register_form=ExtendedRegisterForm) #<-- (F) # you need to register and new form here (F) register_form=ExtendedRegisterForm # ______________________________________________________________________ @app.route('/pass_changed') def pass_changed(): return '<h2>Password change successfully!</h2>' # ___________________________ @app.route('/') def index(): return '<h2>home page</h2>' # ___________________________ @app.route('/protected') @login_required def protected(): return '<h2>This is protected! You email is {}.</h2>'.format(current_user.email) # ___________________________ @app.route('/roleprotected') @roles_accepted('admin') def roleprotected(): return '<h2>This is for admin only!</h2>' # ___________________________ @app.route('/set_admin') @login_required def set_admin(): # finding or creating a role (this case 'admin') admin_role = user_datastore.find_or_create_role('admin') # assigning the admin_role to current_user user_datastore.add_role_to_user(current_user, admin_role) db.session.commit() return '<h2>User have Admin right!</h2>' # ___________________________ @app.route('/remove_admin') @login_required def remove_admin(): # finding or creating a role (this case 'admin') admin_role = user_datastore.find_or_create_role('admin') # assigning the admin_role to current_user user_datastore.remove_role_from_user(current_user, admin_role) db.session.commit() return '<h2>Admin right, has been removed!</h2>' @app.route('/confirmed') @login_required def confirm(): return "<h3>{} is confirmed</h3>".format(current_user.email) @app.route('/httpprotected') @http_auth_required def httpprotected(): return '<h2>This is the basic auth page!</h2>' # ______________________________________________________________________ # try the following url from : # https://pythonhosted.org/Flask-Security/configuration.html # URLs and Views # http://127.0.0.1:5000/login # http://127.0.0.1:5000/register # <-- need to add config ''' chris@gmail.com password2 maria@gmail.com password1 ''' # ______________________________________________________________________ # ref (D) # To Customize the templates # the below code with print the flask-user directory # copy the form template file to your app directory # note the directory from your app to template should match that of the package # modifiy the copyed template (not the original package one) import os import flask_mail print('\n>>>>>>>> >>',os.path.dirname(flask_mail.__file__)) #_______________________________________________________________________ if __name__ == '__main__': app.run()
[ "foxcode9@gmail.com" ]
foxcode9@gmail.com
6f57674b84d834b2a35358c52c7a457d5431dd13
0bd5a4b07572c46e2a4a59f977c5d80f8bc884b8
/spectrl/main/monitor.py
dc869d043a0731bf76d5f01bb525dde9cc5ce64d
[]
no_license
cwatson1998/spectrl_tool_perspectrl
ab5536d191f612891ea30edba31a4a4833d2b84a
1ec9cead048bbf0932a64c95ad129585e6dd7b2c
refs/heads/master
2023-03-20T05:55:17.802313
2020-11-23T18:27:21
2020-11-23T18:27:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,280
py
import numpy as np import math # Model for resources class Resource_Model: # state_dim : int # action_dim : int # res_dim : int # res_init : np.array(res_dim) # res_delta : np.array(state_dim), np.array(res_dim), np.array(action_dim) -> np.array(res_dim) def __init__(self, state_dim, action_dim, res_dim, res_init, res_delta): self.state_dim = state_dim self.action_dim = action_dim self.res_dim = res_dim self.res_init = res_init self.res_delta = res_delta # ================================================================================================== # Class for representing monitors class Monitor_Automaton: # n_states : int # n_registers : int # input_dim : int (state_dim + res_dim) # init_registers : np.array(n_registers) # transitions : adjacency list of transitions of the form (q,p,u) where, # q : int (monitor state) # p : np.array(input_dim) , np.array(n_registers) -> (Bool,Float {quant. sym.}) # u : np.array(input_dim) , np.array(n_registers) -> np.array(n_registers) # rewards : list of n_states reward functions for final states (others are None) # rewards[i] : np.array(input_dim) , np.array(n_registers) -> Float def __init__(self, n_states, n_registers, input_dim, init_registers, transitions, rewards): self.n_states = n_states self.n_registers = n_registers self.input_dim = input_dim self.init_registers = init_registers self.transitions = transitions self.rewards = rewards # ================================================================================================== # Useful functions on monitors def find_state_depths(monitor): depths = [0] * monitor.n_states incoming = [0] * monitor.n_states for q1 in range(monitor.n_states): for (q2, _, _) in monitor.transitions[q1]: if q1 != q2: incoming[q2] += 1 topo_sort = [] for q in range(monitor.n_states): if incoming[q] == 0: topo_sort.append(q) depths[q] = 0 for i in range(monitor.n_states): for (q, _, _) in monitor.transitions[topo_sort[i]]: if q != topo_sort[i]: incoming[q] -= 1 depths[q] = max(depths[q], depths[topo_sort[i]]+1) if incoming[q] == 0: topo_sort.append(q) return depths # ================================================================================================== # Compiled Specification consisting of resource model and reward monitor. class Compiled_Spec: # resource : Resource_Model # monitor : Monitor_Automaton # min_reward : float # local_reward_bound : float (C) def __init__(self, resource, monitor, min_reward, local_reward_bound): self.state_dim = resource.state_dim self.action_dim = resource.action_dim # Resource self.resource = resource # Monitor self.monitor = monitor self.extra_action_dim = max(map(len, self.monitor.transitions)) self.depths = find_state_depths(self.monitor) self.max_depth = max(self.depths) # Product MDP self.total_state_dim = self.state_dim + self.resource.res_dim + self.monitor.n_registers self.total_action_dim = self.action_dim + self.extra_action_dim self.min_reward = min_reward self.local_reward_bound = local_reward_bound self.register_split = self.state_dim + self.resource.res_dim # Extract state components # state : (np.array(total_state_dim), int) def extract_state_components(self, state): sys_state = state[0][:self.state_dim] res_state = state[0][self.state_dim:self.register_split] register_state = state[0][self.register_split:] monitor_state = state[1] return sys_state, res_state, register_state, monitor_state # Step function for Resource, Monitor state and Registers # state : (np.array(total_state_dim), int) # action : np.array(total_action_dim) or np.array(action_dim) # return value : (np.array(resource.res_dim + monitor.n_registers), int) def extra_step(self, state, action): sys_state, res_state, register_state, monitor_state = self.extract_state_components(state) sys_action = action[:self.action_dim] # Step the Resource state new_res_state = np.array([]) if self.resource.res_dim > 0: new_res_state = self.resource.res_delta(sys_state, res_state, sys_action) # Step the Monitor and Register state # Assumes at-least one predicate of the outgoing edges will be satisfied # start with an edge and explore to find the edge that is feasible edge = 0 if len(action) < self.total_action_dim: q, _, _ = self.monitor.transitions[monitor_state][0] if q == monitor_state: edge = 1 else: edge = 0 else: mon_action = action[self.action_dim:] edge = np.argmax(mon_action[:len(self.monitor.transitions[monitor_state])]) outgoing_transitions = self.monitor.transitions[monitor_state] sys_res_state = np.concatenate([sys_state, res_state]) for i in range(len(outgoing_transitions)): (q, p, u) = outgoing_transitions[(i+edge) % len(outgoing_transitions)] satisfied, _ = p(sys_res_state, register_state) if satisfied: new_register_state = u(sys_res_state, register_state) return (np.concatenate([new_res_state, new_register_state]), q) # Initial values of the extra state space # return value : np.array(resource.res_dim + monitor.n_registers) def init_extra_state(self): return np.concatenate([self.resource.res_init, self.monitor.init_registers]) # Shaped reward for a state # sys_res_state : np.array(state_dim + resource.res_dim) # monitor_state : int # register_state : np.array(monitor.n_registers) def shaped_reward(self, sys_res_state, register_state, monitor_state): rew = -10000000 for (q, p, u) in self.monitor.transitions[monitor_state]: if q == monitor_state: continue _, edge_rew = p(sys_res_state, register_state) rew = max(rew, edge_rew) return self.min_reward \ + rew \ + (self.local_reward_bound) * (self.depths[monitor_state] - self.max_depth) # Cumulative reward for a rollout (shaped) # rollout : [(np.array, int)] def cum_reward_shaped(self, rollout): last_state = rollout[len(rollout)-1] # Final State if self.monitor.rewards[last_state[1]] is not None: (last_sys_state, last_res_state, last_register_state, last_monitor_state) = self.extract_state_components(last_state) last_sys_res_state = np.concatenate([last_sys_state, last_res_state]) return self.monitor.rewards[last_monitor_state](last_sys_res_state, last_register_state) # Non-final state rew = -10000000 for state in rollout: if(state[1] == last_state[1]): (sys_state, res_state, register_state, monitor_state) = self.extract_state_components(state) sys_res_state = np.concatenate([sys_state, res_state]) rew = max(rew, self.shaped_reward(sys_res_state, register_state, monitor_state)) return rew # Cumulative reward for a rollout (unshaped) # rollout : [(np.array, int)] def cum_reward_unshaped(self, rollout): last_state = rollout[len(rollout)-1] # Final State if self.monitor.rewards[last_state[1]] is not None: (last_sys_state, last_res_state, last_register_state, last_monitor_state) = self.extract_state_components(last_state) last_sys_res_state = np.concatenate([last_sys_state, last_res_state]) return self.monitor.rewards[last_monitor_state](last_sys_res_state, last_register_state) # Non-final state return self.min_reward - self.local_reward_bound
[ "kishor@seas.upenn.edu" ]
kishor@seas.upenn.edu
a8546ea2c42ef57ff411bc805a8f02cf11015ab4
2e874bf8ac9544cb07bbb8b558d0a556b8668d1a
/chatbotone/chatbotapp/arduino.py
dfd505fd2a905f0f5e30b9b249e2745b0d10f74c
[]
no_license
gatewaymanish/IoT-chatbot
69d89d49234576d06a193c469b32f93a341456e1
2707e5bfa81557e1a37a4fb23d73cce476e6c171
refs/heads/master
2020-06-10T00:51:40.723652
2016-12-11T05:32:09
2016-12-11T05:32:09
76,108,897
0
0
null
null
null
null
UTF-8
Python
false
false
13,137
py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2011 Alejandro Gonzalez Barrera <alejandrok5@gmail.com> # More info: http://alejandrok5.wordpress.com/ # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA from threading import Thread from firmata import * from django.shortcuts import get_object_or_404, render_to_response from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.template import RequestContext a = Arduino('/dev/ttyACM0') a.pin_mode(13, firmata.OUTPUT) def dot(): a.digital_write(13, firmata.HIGH) a.delay(0.5) a.digital_write(13, firmata.LOW) a.delay(0.5) def slash(): a.digital_write(13, firmata.HIGH) a.delay(1.5) a.digital_write(13, firmata.LOW) a.delay(0.5) def spaceL(): a.delay(1) def spaceW(): a.delay(4) # # # class ArduinoMorse (Thread): # def __init__(self, text): # Thread.__init__(self) # self.text=text # # def run(self): # for x in self.text : # if x=='a' or x=='A': # dot() # slash() # spaceL() # elif x=='b' or x=='B': # slash() # dot() # dot() # dot() # spaceL() # elif x=='c' or x=='C': # slash() # dot() # slash() # dot() # spaceL() # elif x=='d' or x=='D': # slash() # dot() # dot() # spaceL() # elif x=='e' or x=='E': # dot() # spaceL() # elif x=='f' or x=='F': # dot() # dot() # slash() # dot() # spaceL() # elif x=='g' or x=='G': # slash() # slash() # dot() # spaceL() # elif x=='h' or x=='H': # dot() # dot() # dot() # dot() # spaceL() # elif x=='i' or x=='I': # dot() # dot() # spaceL() # elif x=='j' or x=='J': # dot() # slash() # slash() # slash() # spaceL() # elif x=='k' or x=='K': # slash() # dot() # slash() # spaceL() # elif x=='l' or x=='L': # dot() # slash() # dot() # dot() # spaceL() # elif x=='m' or x=='M': # slash() # slash() # spaceL() # elif x=='n' or x=='N': # slash() # dot() # spaceL() # # elif x=='ñ' or x=='Ñ': # # slash() # # slash() # # dot() # # slash() # # slash() # # spaceL() # elif x=='o' or x=='O': # slash() # slash() # slash() # spaceL() # elif x=='p' or x=='P': # dot() # slash() # slash() # dot() # spaceL() # elif x=='q' or x=='Q': # slash() # slash() # dot() # slash() # slash() # spaceL() # elif x=='r' or x=='R': # dot() # slash() # dot() # spaceL() # elif x=='s' or x=='S': # dot() # dot() # dot() # spaceL() # elif x=='t' or x=='T': # slash() # spaceL() # elif x=='u' or x=='U': # dot() # dot() # slash() # spaceL() # elif x=='v' or x=='V': # dot() # dot() # dot() # slash() # spaceL() # elif x=='w' or x=='W': # dot() # slash() # slash() # spaceL() # elif x=='x' or x=='X': # slash() # dot() # dot() # slash() # spaceL() # elif x=='y' or x=='Y': # slash() # dot() # slash() # slash() # spaceL() # elif x=='z' or x=='Z': # slash() # slash() # dot() # dot() # spaceL() # elif x=='0': # slash() # slash() # slash() # slash() # slash() # spaceL() # elif x=='1': # dot() # slash() # slash() # slash() # slash() # spaceL() # elif x=='2': # dot() # dot() # slash() # slash() # slash() # spaceL() # elif x=='3': # dot() # dot() # dot() # slash() # slash() # spaceL() # elif x=='4': # dot() # dot() # dot() # dot() # slash() # spaceL() # elif x=='5': # dot() # dot() # dot() # dot() # dot() # spaceL() # elif x=='6': # slash() # dot() # dot() # dot() # dot() # spaceL() # elif x=='7': # slash() # slash() # dot() # dot() # dot() # spaceL() # elif x=='8': # slash() # slash() # slash() # dot() # dot() # spaceL() # elif x=='9': # slash() # slash() # slash() # slash() # dot() # spaceL() # elif x=='.': # dot() # slash() # dot() # slash() # dot() # slash() # spaceL() # elif x==',': # slash() # slash() # dot() # dot() # slash() # slash() # spaceL() # elif x=='?': # dot() # dot() # slash() # slash() # dot() # dot() # spaceL() # elif x=='"': # dot() # slash() # dot() # dot() # slash() # dot() # spaceL() # elif x==' ': # spaceW() # else: # pass # # def encode(request): # text="" # morse=[] # if request.method == 'GET': # # form = SearchForm(request.GET) # if form.is_valid(): # text = form.cleaned_data['text'] # arduino=ArduinoMorse(text) # arduino.start() # for x in text : # if x=='a' or x=='A': # morse.append('.-') # elif x=='b' or x=='B': # morse.append('-...') # elif x=='c' or x=='C': # morse.append('-.-.') # elif x=='d' or x=='D': # morse.append('-..') # elif x=='e' or x=='E': # morse.append('.') # elif x=='f' or x=='F': # morse.append('..-.') # elif x=='g' or x=='G': # morse.append('--.') # elif x=='h' or x=='H': # morse.append('....') # elif x=='i' or x=='I': # morse.append('..') # elif x=='j' or x=='J': # morse.append('.---') # elif x=='k' or x=='K': # morse.append('-.-') # elif x=='l' or x=='L': # morse.append('.-..') # elif x=='m' or x=='M': # morse.append('--') # elif x=='n' or x=='N': # morse.append('-.') # # elif x=='ñ' or x=='Ñ': # # morse.append('--.--') # elif x=='o' or x=='O': # morse.append('---') # elif x=='p' or x=='P': # morse.append('.--.') # elif x=='q' or x=='Q': # morse.append('--.--') # elif x=='r' or x=='R': # morse.append('.-.') # elif x=='s' or x=='S': # morse.append('...') # elif x=='t' or x=='T': # morse.append('-') # elif x=='u' or x=='U': # morse.append('..-') # elif x=='v' or x=='V': # morse.append('...-') # elif x=='w' or x=='W': # morse.append('.--') # elif x=='x' or x=='X': # morse.append('-..-') # elif x=='y' or x=='Y': # morse.append('-.--') # elif x=='z' or x=='Z': # morse.append('--..') # elif x=='0': # morse.append('-----') # elif x=='1': # morse.append('.----') # elif x=='2': # morse.append('..---') # elif x=='3': # morse.append('...--') # elif x=='4': # morse.append('....-') # elif x=='5': # morse.append('.....') # elif x=='6': # morse.append('-....') # elif x=='7': # morse.append('--...') # elif x=='8': # morse.append('---..') # elif x=='9': # morse.append('----.') # elif x=='.': # morse.append('.-.-.-') # elif x==',': # morse.append('--..--') # elif x=='?': # morse.append('..--..') # elif x=='"': # morse.append('.-..-.') # elif x==' ': # morse.append(' ') # else: # queryset = [] # # return render_to_response("arduino/index.html", {'form': form, "text": text, "morse": morse})
[ "noreply@github.com" ]
gatewaymanish.noreply@github.com
b6660d915273e2f398c49fd544f4f23936194228
a701b754dc5cd6abc761107d4013e97d13b5a2f0
/Pizza_Ordering_Api/orders.py
97ccaba4b53b36d82acfbe16556a3c48fe443d09
[]
no_license
yholub/Pizza_Ordering_Microservices
669206be73190fa6e15fa26110942b58b4d97bc5
36f0dbea63f72c429b9437d531a2ab449a2b4052
refs/heads/master
2021-08-19T01:47:01.607283
2017-11-24T11:40:12
2017-11-24T11:40:12
111,858,905
0
0
null
null
null
null
UTF-8
Python
false
false
6,870
py
"""API regarding orders""" from flask import Flask, Blueprint, render_template, json, request, current_app, jsonify from models import * import sqlalchemy orders = Blueprint('orders', __name__) @orders.route('/api/Order/GetCurrent', methods=['GET']) def getCurrent(): db = current_app.config["db"] id = db.session.query(PizzaHouse).filter(PizzaHouse.ModeratorId == 1).first().Id query_modified = db.session\ .query(OrderItem)\ .filter(OrderItem.Order.has(PizzaHouseId=id))\ .filter(sqlalchemy.not_(OrderItem.Order.has(Status=4)))\ .filter(OrderItem.IsModified == True) fixed_query = db.session\ .query(OrderItem, FixPizza)\ .filter(OrderItem.PizzaId == FixPizza.Id)\ .filter(OrderItem.Order.has(PizzaHouseId=id))\ .filter(sqlalchemy.not_(OrderItem.Order.has(Status=4)))\ .filter(OrderItem.IsModified == False) fixed = [GetOrderViewModel(item, pizza) for item, pizza in fixed_query] modified = [GetOrderViewModel(x) for x in query_modified] res = fixed + modified return jsonify(res) @orders.route('/api/Order/GetNew', methods=['GET']) def getNew(): db = current_app.config["db"] id = db.session.query(PizzaHouse).filter(PizzaHouse.ModeratorId == 1).first().Id query_modified = db.session\ .query(OrderItem)\ .filter(OrderItem.Order.has(PizzaHouseId=id))\ .filter(OrderItem.Order.has(Status=0))\ .filter(OrderItem.IsModified == True) fixed_query = db.session\ .query(OrderItem, FixPizza)\ .filter(OrderItem.PizzaId == FixPizza.Id)\ .filter(OrderItem.Order.has(PizzaHouseId=id))\ .filter(OrderItem.Order.has(Status=0))\ .filter(OrderItem.IsModified == False) fixed = [GetOrderViewModel(item, pizza) for item, pizza in fixed_query] modified = [GetOrderViewModel(x) for x in query_modified] res = fixed + modified return jsonify(res) @orders.route('/api/settings', methods=['GET']) def getSettings(): db = current_app.config["db"] house = db.session.query(PizzaHouse).filter(PizzaHouse.ModeratorId == 1).first() in_stock_query = db.session\ .query(IngredientAmount)\ .filter(IngredientAmount.PizzaHouseId == house.Id) in_stock = [GetIngredientQuantityDto(item) for item in in_stock_query] res = GetSettingsModel(house) res["InStock"] = in_stock return jsonify(res) @orders.route('/api/pizza', methods=['GET']) def getPizzaHouses(): db = current_app.config["db"] return jsonify(getAllPizzaHouses(db.session)) @orders.route('/api/pizza', methods=['POST']) def getApropriatePizzaHouses(): db = current_app.config["db"] order_settings = request.get_json() houses = getAllPizzaHouses(db.session) ing_counts = {} for item in order_settings["orderItems"]: for ing in item["ingredients"]: id = ing["id"] if id in ing_counts: ing_counts[id] = ing_counts[id] + ing["count"] else: ing_counts[id] = ing["count"] return jsonify([house for house in houses if filterPizzaHouses(house, ing_counts)]) @orders.route('/api/settings', methods=['POST']) def postSettings(): house_settings = request.get_json() db = current_app.config["db"] house = db.session.query(PizzaHouse).get(house_settings["PizzaHouseId"]) house.Capacity = house_settings["Capacity"] ing_quantity_dict = {} for quantity in house_settings["IngState"]: item = db.session\ .query(Ingredient, IngredientAmount)\ .filter(sqlalchemy.and_(Ingredient.Id == quantity["Id"], IngredientAmount.PizzaHouseId == house.Id, IngredientAmount.IngredientId == Ingredient.Id))\ .first() if item is None: ing_qu = IngredientAmount() ing_qu.IngredientId = quantity["Id"] ing_qu.PizzaHouseId = house.Id ing_qu.Quantity = quantity["Quantity"] db.session.add(ing_qu) else: item.IngredientAmount.Quantity = quantity["Quantity"] ing_quantity_dict[quantity["Id"]] = quantity["Quantity"] db.session.commit() return jsonify({ 'status' : "success" }) @orders.route('/api/order/accept/<id>', methods=['POST']) def acceptOrder(id): db = current_app.config["db"] order = db.session.query(Order).filter(Order.Id == id).first() if order.Status == 0: order.Status = 1 db.session.commit() return json.dumps({'success':True}), 200, {'ContentType':'application/json'} @orders.route('/api/order/reject/<id>', methods=['POST']) def rejectOrder(id): db = current_app.config["db"] order = session.query(Order).filter(Order.Id == id).first() order.Status = 4 session.commit() return json.dumps({'success':True}), 200, {'ContentType':'application/json'} def GetSettingsModel(item): res = { 'Id': item.Id, 'Close': 24, 'Open': 9, 'Capacity': item.Capacity } return res def GetOrderViewModel(item, pizza=None): res = {} res['Id'] = item.Id res['State'] = item.Order.Status res['Start'] = item.StartTime res['End'] = item.EndTime res['OrderId'] = item.OrderId res['Price'] = int(item.Price) res['StartStr'] = item.StartTime.strftime("%Y-%m-%d") res['EndStr'] = item.EndTime.strftime("%Y-%m-%d") res['StHour'] = item.StartTime.hour res['StMinute'] = item.StartTime.minute res['EndHour'] = item.EndTime.hour res['EndMinute'] = item.EndTime.minute if pizza is None: res['Name'] = "Custom" else: res['Name'] = pizza.Name return res def GetIngredientDto(item): res = {} res['Id'] = item.Id res['Price'] = float(item.Price) res['Weight'] = float(item.Weight) res['Name'] = item.Name return res def GetIngredientQuantityDto(item): res = {} res['Quantity'] = item.Quantity res['IngredientDto'] = GetIngredientDto(item.Ingredient) return res def getAllPizzaHouses(session): houses = session.query(PizzaHouse) res = [] for house in houses: in_stock_query = session\ .query(IngredientAmount)\ .filter(IngredientAmount.PizzaHouseId == house.Id) in_stock = [GetIngredientQuantityDto(item) for item in in_stock_query] res.append(GetSettingsModel(house)) res[len(res) - 1]["InStock"] = in_stock return res def filterPizzaHouses(house, ingCounts): house_ing_count = {} for ing in house["InStock"]: house_ing_count[ing["IngredientDto"]["Id"]] = ing["Quantity"] for key, value in ingCounts.items(): if (not key in house_ing_count) or house_ing_count[key] < value: return False return True
[ "jgolub5162@gmail.com" ]
jgolub5162@gmail.com
24f08d53228b38ac05b1f442f5e1f566c82f38b2
aab7639fdca115185675c3bceb13fb3cb1d58e62
/Array/34. Search for a Range(medium).py
66165b9b27e49f2db9b340f0e48bf42d815ce714
[]
no_license
xilixjd/leetcode
0cfc9c32e790e88084e484c369d450fb4619c52c
71a02a2c6bc12e86119502c9c4a4b2047b9f3966
refs/heads/master
2021-01-19T15:46:26.554583
2018-06-02T05:22:31
2018-06-02T05:22:31
88,227,638
1
0
null
null
null
null
UTF-8
Python
false
false
3,832
py
# -*- coding: utf-8 -*- ''' Given an array of integers sorted in ascending order, find the starting and ending position of a given target value. Your algorithm's runtime complexity must be in the order of O(log n). If the target is not found in the array, return [-1, -1]. For example, Given [5, 7, 7, 8, 8, 10] and target value 8, return [3, 4]. ''' class ReSolution(object): def searchRange1(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ def front_binary_search(nums, target): low = 0 high = len(nums) - 1 index = -1 while low <= high: mid = (low + high) / 2 if nums[mid] >= target: high = mid - 1 else: low = mid + 1 if target == nums[mid]: index = mid return index def back_binary_search(nums, target): low = 0 high = len(nums) - 1 index = -1 while low <= high: mid = (low + high) / 2 if nums[mid] > target: high = mid - 1 elif nums[mid] <= target: low = mid + 1 if nums[mid] == target: index = mid return index return [front_binary_search(nums, target), back_binary_search(nums, target)] re = ReSolution() print re.searchRange1([1, 2, 3, 4, 5, 8, 19], 8) class Solution(object): def searchRange1(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] https://yq.aliyun.com/articles/860 1. 不用二分法 """ l = 0 r = len(nums) - 1 if len(nums) == 0: return [-1, -1] if len(nums) == 1: if nums[0] == target: return [0, 0] else: return [-1, -1] while l < r: if nums[l] < target: l += 1 if nums[r] > target: r -= 1 if nums[l] == target and nums[r] == target: return [l, r] return [-1, -1] def searchRange2(self, nums, target): ''' 2. 用二分法 可参考 《剑指 offer》 的 p205 :param nums: :param target: :return: ''' first = self.binarySearchFirst(nums, target) last = self.binarySearchLast(nums, target) return [first, last] def binarySearchFirst(self, nums, target): start = 0 end = len(nums) - 1 idx = -1 while start <= end: mid = (start + end) / 2 if target > nums[mid]: start = mid + 1 else: end = mid - 1 if nums[mid] == target: idx = mid return idx def binarySearchLast(self, nums, target): start = 0 end = len(nums) - 1 idx = -1 while start <= end: mid = (start + end) / 2 if target >= nums[mid]: start = mid + 1 else: end = mid - 1 if nums[mid] == target: idx = mid return idx def binarySearch(self, i, j, nums, target): mid = (i + j) / 2 if mid < 0: return -1 if mid != 0 and mid + 1 > j: return -1 if nums[mid] > target: return self.binarySearch(i, mid - 1, nums, target) elif nums[mid] < target: return self.binarySearch(mid + 1, j, nums, target) else: return mid solu = Solution() print solu.searchRange1([1], 1) print solu.binarySearch(0, 0, [1], 1)
[ "349729220@qq.com" ]
349729220@qq.com
7e10172995f49d8340f470771651bf9fa726ea4b
34599596e145555fde0d4264a1d222f951f49051
/pcat2py/class/211e063a-5cc5-11e4-af55-00155d01fe08.py
37dfc9a87c38f38cb98ec59c040d9e5436b4491f
[ "MIT" ]
permissive
phnomcobra/PCAT2PY
dc2fcbee142ce442e53da08476bfe4e68619346d
937c3b365cdc5ac69b78f59070be0a21bdb53db0
refs/heads/master
2021-01-11T02:23:30.669168
2018-02-13T17:04:03
2018-02-13T17:04:03
70,970,520
0
0
null
null
null
null
UTF-8
Python
false
false
1,494
py
#!/usr/bin/python ################################################################################ # 211e063a-5cc5-11e4-af55-00155d01fe08 # # Justin Dierking # justindierking@hardbitsolutions.com # phnomcobra@gmail.com # # 10/24/2014 Original Construction ################################################################################ class Finding: def __init__(self): self.output = [] self.is_compliant = False self.uuid = "211e063a-5cc5-11e4-af55-00155d01fe08" def check(self, cli): # Initialize Compliance self.is_compliant = False # Get Registry DWORD dword = cli.get_reg_dword(r'HKCU:\Software\Policies\Microsoft\Office\14.0\outlook\security', 'AllowActiveXOneOffForms') # Output Lines self.output = [r'HKCU:\Software\Policies\Microsoft\Office\14.0\outlook\security', ('AllowActiveXOneOffForms=' + str(dword))] if dword == 0: self.is_compliant = True return self.is_compliant def fix(self, cli): cli.powershell(r"New-Item -path 'HKCU:\Software\Policies\Microsoft\Office\14.0'") cli.powershell(r"New-Item -path 'HKCU:\Software\Policies\Microsoft\Office\14.0\outlook'") cli.powershell(r"New-Item -path 'HKCU:\Software\Policies\Microsoft\Office\14.0\outlook\security'") cli.powershell(r"Set-ItemProperty -path 'HKCU:\Software\Policies\Microsoft\Office\14.0\outlook\security' -name 'AllowActiveXOneOffForms' -value 0 -Type DWord")
[ "phnomcobra@gmail.com" ]
phnomcobra@gmail.com
c8bfea854904c45f654a86b7234e035082db8596
cd593ad87b214afd37560aa3779454f58696a60c
/i3_hooked_on_a_feeling/.config/qutebrowser/config.py
82993ac8a41699dea08d185675ff6d961d6b4bc6
[ "MIT" ]
permissive
timbury/dotfiles_ikigai
e4fa62e1911233720f1a80fd425f9bda8b08df54
2a25883281e21025d7b6219a1512a7f7bf7703e3
refs/heads/master
2020-06-01T11:43:18.738611
2019-01-20T05:09:29
2019-01-20T05:09:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,291
py
# Autogenerated config.py # Documentation: # qute://help/configuring.html # qute://help/settings.html # Uncomment this to still load settings configured via autoconfig.yml # config.load_autoconfig() # set custom theme c.content.user_stylesheets = str(config.configdir) + '/inspected_css/drac.css' config.bind(';p' , 'set downloads.location.directory ~/Pictures/ ;; hint links download') # Aliases for commands. The keys of the given dictionary are the # aliases, while the values are the commands they map to. # Type: Dict c.aliases = {'q': 'quit', 'w': 'session-save', 'wq': 'quit --save'} # Enable JavaScript. # Type: Bool config.set('content.javascript.enabled', True, 'file://*') # Enable JavaScript. # Type: Bool config.set('content.javascript.enabled', True, 'chrome://*/*') # Enable JavaScript. # Type: Bool config.set('content.javascript.enabled', True, 'qute://*/*') ## Definitions of search engines which can be used via the address bar. ## Maps a searchengine name (such as `DEFAULT`, or `ddg`) to a URL with a ## `{}` placeholder. The placeholder will be replaced by the search term, ## use `{{` and `}}` for literal `{`/`}` signs. The searchengine named ## `DEFAULT` is used when `url.auto_search` is turned on and something ## else than a URL was entered to be opened. Other search engines can be ## used by prepending the search engine name to the search term, e.g. ## `:open google qutebrowser`. ## Type: Dict c.url.searchengines = { 'DEFAULT': 'https://duckduckgo.com/?q={}', 'i': 'https://duckduckgo.com/?q={}&iar=images&iax=images&ia=images', 'vic': 'https://la.wikipedia.org/w/index.php?search={}&title=Specialis%3AQuaerere', 'red': 'https://reddit.com/r/{}', 'tpb': 'http://thepiratebay.org/search/{}', 'andr': 'https://developer.android.com/develop/index.html?q={}', 'ghr': 'https://github.com/search?utf8=%E2%9C%93&q={}&type=', 'ghn': 'https://github.com/search?utf8=%E2%9C%93&q={}+in%3Aname&type=Repositories', 'ud': 'https://www.urbandictionary.com/define.php?term={}&utm_source=search-action', 'ddg': 'https://duckduckgo.com/?q={}&t=ha&iar=images', 'aw': 'https://wiki.archlinux.org/index.php?title=Special%3ASearch&search={}', 'yt': 'https://www.youtube.com/results?search_query={}', 'w': 'https://www.wikipedia.org/search-redirect.php?family=wikipedia&language=en&search={}&language=en&go=Go', 'sk': 'https://www.skytorrents.in/search/all/ed/1/?l=en-us&q={}', 'whl': 'https://alpha.wallhaven.cc/search?q={}&categories=111&purity=100&sorting=views&order=desc', 'whh': 'https://alpha.wallhaven.cc/search?q={}&categories=111&purity=100&atleast=2560x1440&sorting=views&order=desc&page=2', 'mup': 'https://musicpleer.to/#!{}', } c.aliases = { 'wh': "open -t https://alpha.wallhaven.cc/search?q=&categories=111&purity=100&topRange=1y&sorting=toplist&order=desc&colors=336600&page=1", 'gh': "open -t https://github.com/yedhink", } ## Background color for webpages if unset (or empty to use the theme's ## color) ## Type: QtColor c.colors.webpage.bg = 'black' ## How many commands to save in the command history. 0: no history / -1: ## unlimited ## Type: Int c.completion.cmd_history_max_items = 100
[ "yedhin1998@gmail.com" ]
yedhin1998@gmail.com
c89bb72d906d579e0bd1a3b813b42be1ad4f5fa1
8d39c25241e89593e7bb8da8a568033b20a59fe1
/project/_tool/checkIsRepeat.py
e97bc4bb71152951e3ed53ccb88d2ad6fb1c7023
[]
no_license
Jason20015/Py3Crawler
62a59c8b487728daf772237fbd95bbc00c707f6d
f04348691c1809bbbc5a4cf4f084c998e8b49803
refs/heads/master
2020-04-05T07:18:08.342880
2018-11-07T12:03:07
2018-11-07T12:03:07
156,670,337
0
1
null
null
null
null
UTF-8
Python
false
false
754
py
# -*- coding:UTF-8 -*- # 获取指定存档文件中是否存在重复的主键 import os from common import file, output # 存档路径 SAVE_FILE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "save.data")) # 存档中唯一标示(如,账号id)的字段下标 NAME_COLUMN = 0 # 检测存档文件中是否有相同的主键 def check_is_repeat(): history = [] for line in file.read_file(SAVE_FILE_PATH, file.READ_FILE_TYPE_LINE): temp_list = line.replace("\n", "").split("\t") if temp_list[NAME_COLUMN] in history: output.print_msg(temp_list[NAME_COLUMN]) else: history.append(temp_list[NAME_COLUMN]) return history if __name__ == "__main__": check_is_repeat()
[ "hikaru870806@hotmail.com" ]
hikaru870806@hotmail.com
1ee56236b83309a4459eb96cde3b8089b8ca6ea2
4c0506db687b74cd8e019629e4504c139ea423a1
/a.py
cc441a03016b152f5e6cb8aa7e6eb6d07a4d0867
[]
no_license
Lsgraalq/total-update
80f1585de7985716197e4ebb9f8b4affbcd2d4fd
2cddbd60655c435a25786caa24fec3aaba151d3e
refs/heads/main
2023-07-28T07:47:16.475630
2021-09-11T14:11:38
2021-09-11T14:11:38
405,384,665
0
0
null
null
null
null
UTF-8
Python
false
false
307
py
import math import sys sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') (a, b, c) = [int(s) for s in input().split()] (h, l,) = [int(s) for s in input().split()] z = (a * b + a* c + b*c)*2-a*b z = z - 0.15*z x = h*0.001 p = l*0.001 c = x *p c = c - 0.1 * c u = z/c print(math.ceil(u))
[ "ilya.merinec@gmail.com" ]
ilya.merinec@gmail.com
d5339fe24f182a3d821121c4d9aab37da1217fb2
5a62a111b30899e3260c4fe634e16049eb90cf78
/flickr-album-download.py
966efe870f1caaff6fc7aa34d8019203da3eafd0
[]
no_license
silveira/flickr-utils
6782d74067b08eb400ae5421949ab7d63ae864f9
eff02abac012778ce94a119206efe6705c5418d2
refs/heads/master
2020-03-14T08:40:08.689199
2018-04-29T21:17:37
2018-04-29T21:17:37
131,529,998
0
0
null
null
null
null
UTF-8
Python
false
false
749
py
#!/usr/bin/env python import flickrapi import math api_key = u'' api_secret = u'' user = u'' photo_set = u'' PAGE_SIZE = 500 def generate_download_list(): photos = flickr.photosets.getPhotos(photoset_id=photo_set, user_id=user) total = photos[u'photoset'][u'total'] pages_necessary = int(math.ceil(float(total)/PAGE_SIZE)) for current_page in xrange(pages_necessary): photos = flickr.photosets.getPhotos(photoset_id=photo_set, user_id=user, page=current_page+1, extras='url_o') for photo in photos[u'photoset'][u'photo']: print photo['url_o'] if __name__ == "__main__": flickr = flickrapi.FlickrAPI(api_key, api_secret, format='parsed-json') flickr.authenticate_via_browser(perms='read') generate_download_list()
[ "silveiraneto@gmail.com" ]
silveiraneto@gmail.com
d4f39bf650b55dedde222b5251a26bce84f9166d
3b4435a6611a72227e444ed4b9029c36f514b0b5
/leetcode/Add_Two_Numbers/test.py
e8f0ff2aa5b05fb9e08901175aa500f9d2172284
[]
no_license
osy497/algorithm-test
f189fef146068af9a0125630890ec55c10626985
65e70235ca97dbc488a2623ff1b01eb8c8fb685c
refs/heads/master
2023-03-07T10:57:55.342994
2021-02-23T07:00:51
2021-02-23T07:00:51
310,162,394
0
0
null
null
null
null
UTF-8
Python
false
false
939
py
#!/bin/python3 # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: temp_l1 = l1 temp_l2 = l2 l3 = ListNode() temp_l3 = l3 carry_flag = 0 while temp_l1 or temp_l2 or carry_flag: temp_l3.next = ListNode() temp_l3 = temp_l3.next p1 = 0 p2 = 0 if temp_l1: p1 = temp_l1.val temp_l1 = temp_l1.next if temp_l2: p2 = temp_l2.val temp_l2 = temp_l2.next temp_l3.val = p1 + p2 + carry_flag carry_flag = 0 if temp_l3.val >= 10: temp_l3.val -= 10 carry_flag = 1 return l3.next
[ "root@pl-8-builder-13.tk" ]
root@pl-8-builder-13.tk
7b3d2d7f91f67b11124933b5ffacb748256d4bf8
e1aca7817e7a6818498bbe6e3ab89de440574917
/tasks/task08/shapes.py
9a18a1c41f3badb2b7ce164b189263c07d3469f2
[]
no_license
YMikita/exadel-python-course-2021
36289cfa58ea811755b9f8b2d857e51f3046ae47
98204c94e286bae660988f2f4a8568e488dc7a3d
refs/heads/main
2023-08-31T15:03:59.669834
2021-10-12T11:02:12
2021-10-12T11:02:12
402,911,236
0
0
null
2021-10-09T21:39:38
2021-09-03T22:26:28
Python
UTF-8
Python
false
false
877
py
from tasks.task08.shape2d.square import * from tasks.task08.shape2d.shape_collection import * from tasks.task08.shape2d.circle import * point = Point(50, 70) point2 = Point(60, 60) rectangle = Rectangle(point, 10, 20) print(f"Rectangle: {rectangle}, Area: {rectangle.area()}, Point[{point2}] contains: {rectangle.__contains__(point2)}") square = Square(point, 30) print(f"Square: {square}, Area: {square.area()}, Point[{point2}] contains: {square.__contains__(point2)}") circle = Circle(point, 15) print(f"Circle: {circle}, Area: {circle.area()}, Point[{point2}] contains: {circle.__contains__(point2)}") shape_collection = ShapeCollection([rectangle, square, circle]) print(f"\nPoint[{point2}] contains in Shape Collection: {shape_collection.__contains__(point2)}") print(f"Shape Collection Area: {shape_collection.area()}") print(f"Shape Collection: {shape_collection}")
[ "myepishkin@exadel.com" ]
myepishkin@exadel.com
43bdc0a3895c523a91a98518066d51d71fed380a
9745d3fcf7c759235a58c8d8ddab6d41b9497779
/Experience&Practice/SpiderProject/ScrapyProjects/PDDSpiders/PDDSpider/scrapy_redis/scheduler.py
c9dd29be25226ec923e6d7aa970c916c1b3dfe89
[]
no_license
runningabcd/Spider-Life
eb12f60cc4bbde1d64dc233efcb89334e8c81c94
149dca0fff92cdeea5df0584ae4b81ea15599fac
refs/heads/master
2020-04-08T14:29:40.596767
2019-11-12T16:41:06
2019-11-12T16:41:06
159,439,169
6
0
null
null
null
null
UTF-8
Python
false
false
3,680
py
import sys import os from os.path import dirname abs_path = dirname(dirname(os.path.abspath(__file__))) abs_parent_path = dirname(abs_path) sys.path.append(abs_path) sys.path.append(abs_parent_path) from scrapy.utils.misc import load_object from PDDSpider.scrapy_redis import connection from PDDSpider.scrapy_redis.dupefilter import RFPDupeFilter # default values SCHEDULER_PERSIST = False QUEUE_KEY = '%(spider)s:requests' QUEUE_CLASS = 'scrapy_redis.queue.SpiderPriorityQueue' DUPEFILTER_KEY = '%(spider)s:dupefilter' IDLE_BEFORE_CLOSE = 0 class Scheduler(object): """Redis-based scheduler""" def __init__(self, server, server_filter, persist, queue_key, queue_cls, dupefilter_key, idle_before_close, queue_name): """Initialize scheduler. Parameters ---------- server : Redis instance persist : bool queue_key : str queue_cls : queue class dupefilter_key : str idle_before_close : int """ self.server = server self.server_filter = server_filter self.persist = persist self.queue_key = queue_key self.queue_cls = queue_cls self.dupefilter_key = dupefilter_key self.idle_before_close = idle_before_close self.queue_name = queue_name self.stats = None def __len__(self): return len(self.queue) @classmethod def from_settings(cls, settings): persist = settings.get('SCHEDULER_PERSIST', SCHEDULER_PERSIST) queue_key = settings.get('SCHEDULER_QUEUE_KEY', QUEUE_KEY) queue_cls = load_object(settings.get('SCHEDULER_QUEUE_CLASS', QUEUE_CLASS)) queue_name = settings.get('REDIS_QUEUE_NAME', None) dupefilter_key = settings.get('DUPEFILTER_KEY', DUPEFILTER_KEY) idle_before_close = settings.get('SCHEDULER_IDLE_BEFORE_CLOSE', IDLE_BEFORE_CLOSE) server = connection.from_settings(settings) server_filter = connection.from_settings_filter(settings) return cls(server, server_filter, persist, queue_key, queue_cls, dupefilter_key, idle_before_close, queue_name) @classmethod def from_crawler(cls, crawler): instance = cls.from_settings(crawler.settings) # FIXME: for now, stats are only supported from this constructor instance.stats = crawler.stats return instance def open(self, spider): self.spider = spider self.queue = self.queue_cls(self.server, spider, spider.redis_key) self.df = RFPDupeFilter(self.server_filter, self.dupefilter_key % {'spider': (self.queue_name if self.queue_name else spider.name)}) if self.idle_before_close < 0: self.idle_before_close = 0 # notice if there are requests already in the queue to resume the crawl if len(self.queue): spider.logger.info("Resuming crawl (%d requests scheduled)" % len(self.queue)) def close(self, reason): if not self.persist: self.df.clear() self.queue.clear() def enqueue_request(self, request): if not request.dont_filter and self.df.request_seen(request): return if self.stats: self.stats.inc_value('scheduler/enqueued/redis', spider=self.spider) self.queue.push(request) def next_request(self): block_pop_timeout = self.idle_before_close request = self.queue.pop(block_pop_timeout) if request and self.stats: self.stats.inc_value('scheduler/dequeued/redis', spider=self.spider) return request def has_pending_requests(self): return len(self) > 0
[ "821907280@qq.com" ]
821907280@qq.com
d7a5d2aa19ba4d95592d177e726474c4ddd58548
1a4aedbfa972382ea52852eb8f10ec96766ffdfd
/tests/unittests/test_nested_loops_join.py
d02fa287724bebaab6c306f37a669818b243a57c
[]
no_license
Bradfield/braddb
e8265d00edb0889563f7d72e6458505bbf9ddbbd
f38fec6c152d00f6695c56cec981edd5644abd79
refs/heads/master
2021-07-11T07:01:54.930935
2017-10-15T22:54:05
2017-10-15T22:54:05
106,343,661
5
3
null
null
null
null
UTF-8
Python
false
false
3,144
py
import unittest from executor.executor import tree, execute from executor.memscan import MemScan from executor.nested_loops_join import NestedLoopsJoin class TestNestedLoopsJoin(unittest.TestCase): """ Test our most basic join: nested loops with optional theta function. """ R_RECORDS = ( (0, 'a'), (1, 'b'), (1, 'c'), (2, 'c'), ) S_RECORDS = ( ('a', 'apple'), ('b', 'banana'), ('b', 'burger'), ) def test_cartesian_product(self): """ When the theta function simply returns True, we achieve cross product. """ query = tree( [NestedLoopsJoin(lambda r, s: True), [MemScan(self.R_RECORDS)], [MemScan(self.S_RECORDS)]]) result = list(execute(query)) expected = [r + s for r in self.R_RECORDS for s in self.S_RECORDS] self.assertListEqual(result, expected) def test_self_join(self): """ It's fine for a table to be joined to itself. """ query = tree( [NestedLoopsJoin(lambda r, s: True), [MemScan(self.R_RECORDS)], [MemScan(self.R_RECORDS)]]) result = list(execute(query)) expected = [r + s for r in self.R_RECORDS for s in self.R_RECORDS] self.assertListEqual(result, expected) def test_equijoin(self): """ The join condition can be that the value in one field equals another. """ query = tree( [NestedLoopsJoin(lambda r, s: r[1] == s[0]), [MemScan(self.R_RECORDS)], [MemScan(self.S_RECORDS)]]) result = list(execute(query)) expected = [ (0, 'a', 'a', 'apple'), (1, 'b', 'b', 'banana'), (1, 'b', 'b', 'burger') ] self.assertListEqual(result, expected) def test_inequality(self): """ The join condition can be an inequality. """ query = tree( [NestedLoopsJoin(lambda r, s: r[0] > s[0]), [MemScan(self.R_RECORDS)], [MemScan(self.R_RECORDS)]]) result = list(execute(query)) expected = [ (1, 'b', 0, 'a'), (1, 'c', 0, 'a'), (2, 'c', 0, 'a'), (2, 'c', 1, 'b'), (2, 'c', 1, 'c'), ] self.assertListEqual(result, expected) def test_three_way(self): """ The input to a join can be a join. """ query = tree( [NestedLoopsJoin(lambda r, s: r[3] == s[0]), [NestedLoopsJoin(lambda r, s: r[0] > s[0]), [MemScan(self.R_RECORDS)], [MemScan(self.R_RECORDS)]], [MemScan(self.S_RECORDS)]]) result = list(execute(query)) expected = [ (1, 'b', 0, 'a', 'a', 'apple'), (1, 'c', 0, 'a', 'a', 'apple'), (2, 'c', 0, 'a', 'a', 'apple'), (2, 'c', 1, 'b', 'b', 'banana'), (2, 'c', 1, 'b', 'b', 'burger'), ] self.assertListEqual(result, expected)
[ "ozan.onay@gmail.com" ]
ozan.onay@gmail.com
8a3d92cd176d4a3ddf0015fde1ca972969c8ee9f
f73cef3ff58a47529c78a6bc1ade798df24087bd
/highway_env/vehicle/graphics.py
b32365494710c97b1c3802aa393766e9c0609f30
[ "MIT" ]
permissive
songanz/highway-env
35d825c13f36295c5e8ede6e849422a4d4f7e445
ac21d1da25e224dbdbf8ba39509f4013bd029f52
refs/heads/master
2022-08-27T03:48:18.943017
2019-07-11T21:42:27
2019-07-11T21:42:27
193,512,750
1
1
null
null
null
null
UTF-8
Python
false
false
4,748
py
from __future__ import division, print_function import numpy as np import pygame from highway_env.vehicle.dynamics import Vehicle, Obstacle from highway_env.vehicle.control import ControlledVehicle, MDPVehicle from highway_env.vehicle.behavior import IDMVehicle, LinearVehicle class VehicleGraphics(object): RED = (255, 100, 100) GREEN = (50, 200, 0) BLUE = (100, 200, 255) YELLOW = (200, 200, 0) BLACK = (60, 60, 60) PURPLE = (200, 0, 150) DEFAULT_COLOR = GREEN EGO_COLOR = GREEN @classmethod def display(cls, vehicle, surface, transparent=False): """ Display a vehicle on a pygame surface. The vehicle is represented as a colored rotated rectangle. :param vehicle: the vehicle to be drawn :param surface: the surface to draw the vehicle on :param transparent: whether the vehicle should be drawn slightly transparent """ v = vehicle s = pygame.Surface((surface.pix(v.LENGTH), surface.pix(v.LENGTH)), pygame.SRCALPHA) # per-pixel alpha rect = (0, surface.pix(v.LENGTH) / 2 - surface.pix(v.WIDTH) / 2, surface.pix(v.LENGTH), surface.pix(v.WIDTH)) pygame.draw.rect(s, cls.get_color(v, transparent), rect, 0) pygame.draw.rect(s, cls.BLACK, rect, 1) s = pygame.Surface.convert_alpha(s) h = v.heading if abs(v.heading) > 2 * np.pi / 180 else 0 sr = pygame.transform.rotate(s, -h * 180 / np.pi) surface.blit(sr, (surface.pos2pix(v.position[0] - v.LENGTH / 2, v.position[1] - v.LENGTH / 2))) @classmethod def display_trajectory(cls, states, surface): """ Display the whole trajectory of a vehicle on a pygame surface. :param states: the list of vehicle states within the trajectory to be displayed :param surface: the surface to draw the vehicle future states on """ for vehicle in states: cls.display(vehicle, surface, transparent=True) @classmethod def get_color(cls, vehicle, transparent=False): color = cls.DEFAULT_COLOR if vehicle.crashed: color = cls.RED elif isinstance(vehicle, LinearVehicle): color = cls.YELLOW elif isinstance(vehicle, IDMVehicle): color = cls.BLUE elif isinstance(vehicle, MDPVehicle): color = cls.EGO_COLOR elif isinstance(vehicle, Obstacle): color = cls.GREEN if transparent: color = (color[0], color[1], color[2], 50) return color @classmethod def handle_event(cls, vehicle, event): """ Handle a pygame event depending on the vehicle type :param vehicle: the vehicle receiving the event :param event: the pygame event """ if isinstance(vehicle, ControlledVehicle): cls.control_event(vehicle, event) elif isinstance(vehicle, Vehicle): cls.dynamics_event(vehicle, event) @classmethod def control_event(cls, vehicle, event): """ Map the pygame keyboard events to control decisions :param vehicle: the vehicle receiving the event :param event: the pygame event """ if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: vehicle.act("FASTER") if event.key == pygame.K_LEFT: vehicle.act("SLOWER") if event.key == pygame.K_DOWN: vehicle.act("LANE_RIGHT") if event.key == pygame.K_UP: vehicle.act("LANE_LEFT") @classmethod def dynamics_event(cls, vehicle, event): """ Map the pygame keyboard events to dynamics actuation :param vehicle: the vehicle receiving the event :param event: the pygame event """ action = vehicle.action.copy() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: action['steering'] = 45 * np.pi / 180 if event.key == pygame.K_LEFT: action['steering'] = -45 * np.pi / 180 if event.key == pygame.K_DOWN: action['acceleration'] = -6 if event.key == pygame.K_UP: action['acceleration'] = 5 elif event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: action['steering'] = 0 if event.key == pygame.K_LEFT: action['steering'] = 0 if event.key == pygame.K_DOWN: action['acceleration'] = 0 if event.key == pygame.K_UP: action['acceleration'] = 0 if action != vehicle.action: vehicle.act(action)
[ "songanz@umich.edu" ]
songanz@umich.edu
0b9c9ce631c9d21aaf68621a80548d0d5d3b74a4
9d7c9441afefba1c0c78a550c928c9d7f7568292
/python-udp/udpThriftserver.py
1166cb88c5d44fc1c21002cbc892304babdcbb8c
[]
no_license
popweb/quickdemo
2a4f5c26dbc415303d2ef1118bf1e3e1d6d27aa0
477028cba3b6504a87bd2280e8ae3a4c9efd7797
refs/heads/master
2021-07-17T00:17:30.427854
2017-10-24T10:01:24
2017-10-24T10:01:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,885
py
#!/usr/bin/env python # UDP Echo Server - udpserver.py # code by www.cppblog.com/jerryma import socket, traceback, sys, struct import struct from ctypes import * from thrift.protocol import TCompactProtocol from thrift.transport import TTransport from attackchecker.ttypes import TAttackInfo host = '' textport = sys.argv[1] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, int(textport))) def trans(s): return "b'%s'" % ''.join('\\x%.2x' % x for x in s) def printhex(s): i=0; for c in s: print "0x%2x " % ord(c), i=i+1 if (i%16 == 0): print "" print "" class PinpointHeader(Structure): _fields_ = [ ("signature", c_ubyte), ("version", c_ubyte), ("typehigh", c_ubyte), ("typelow", c_ubyte), ] def __new__(self, buffer=None): return self.from_buffer_copy(buffer) def __init__(self, buffer=None): self.type = self.typehigh*256 + self.typelow while 1: try: message, address = s.recvfrom(8192) #print "Got data from", address, ": ", ''.join(map(lambda x:('/x' if len(hex(x))>=4 else '/x0')+hex(x)[2:],message)) #print type(message), # <type 'str'> #print "get message:" #printhex(message) transport = TTransport.TMemoryBuffer(message) prot = TCompactProtocol.TCompactProtocol(transport) header = PinpointHeader(message[:4]) print "get header sig=%#x, version=%#x, type=%d" % (header.signature, header.version, header.type) transport.read(4) # jump over header, see HeaderTBaseSerializer att = TAttackInfo() att.read(prot) #s.sendto(message, address) print(att) except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc()
[ "jiaqifeng@gmail.com" ]
jiaqifeng@gmail.com
1153b6099e95fe5d652d4b243980f2b0347097ab
f7c22882401fd410c38d78de9b9994b3563cad1b
/main.py
0b5ef6706f09837e24e7256994d3d8d8fc95db2b
[]
no_license
Ahmed-Aun/Desktop-Download-Manager-pytube
fddf62d1d6d1cfa06a35876b6cd5c4616e82ce7b
57fba3f73a35f6d727066bf41e615a3a79988857
refs/heads/main
2023-06-03T18:44:31.372437
2021-06-16T17:18:47
2021-06-16T17:18:47
377,573,018
0
0
null
null
null
null
UTF-8
Python
false
false
84,514
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '.\main.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(614, 314) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(".\\icons/brosser.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) MainWindow.setStyleSheet("/* ---------------------------------------------------------------------------\n" "\n" " Created by the qtsass compiler v0.1.1\n" "\n" " The definitions are in the \"qdarkstyle.qss._styles.scss\" module\n" "\n" " WARNING! All changes made in this file will be lost!\n" "\n" "--------------------------------------------------------------------------- */\n" "/* QDarkStyleSheet -----------------------------------------------------------\n" "\n" "This is the main style sheet, the palette has nine colors.\n" "\n" "It is based on three selecting colors, three greyish (background) colors\n" "plus three whitish (foreground) colors. Each set of widgets of the same\n" "type have a header like this:\n" "\n" " ------------------\n" " GroupName --------\n" " ------------------\n" "\n" "And each widget is separated with a header like this:\n" "\n" " QWidgetName ------\n" "\n" "This makes more easy to find and change some css field. The basic\n" "configuration is described bellow.\n" "\n" " BACKGROUND -----------\n" "\n" " Light (unpressed)\n" " Normal (border, disabled, pressed, checked, toolbars, menus)\n" " Dark (background)\n" "\n" " FOREGROUND -----------\n" "\n" " Light (texts/labels)\n" " Normal (not used yet)\n" " Dark (disabled texts)\n" "\n" " SELECTION ------------\n" "\n" " Light (selection/hover/active)\n" " Normal (selected)\n" " Dark (selected disabled)\n" "\n" "If a stranger configuration is required because of a bugfix or anything\n" "else, keep the comment on the line above so nobody changes it, including the\n" "issue number.\n" "\n" "*/\n" "/*\n" "\n" "See Qt documentation:\n" "\n" " - https://doc.qt.io/qt-5/stylesheet.html\n" " - https://doc.qt.io/qt-5/stylesheet-reference.html\n" " - https://doc.qt.io/qt-5/stylesheet-examples.html\n" "\n" "--------------------------------------------------------------------------- */\n" "/* QWidget ----------------------------------------------------------------\n" "\n" "--------------------------------------------------------------------------- */\n" "QWidget {\n" " background-color: #19232D;\n" " border: 0px solid #32414B;\n" " padding: 0px;\n" " color: #F0F0F0;\n" " selection-background-color: #1464A0;\n" " selection-color: #F0F0F0;\n" "}\n" "\n" "QWidget:disabled {\n" " background-color: #19232D;\n" " color: #787878;\n" " selection-background-color: #14506E;\n" " selection-color: #787878;\n" "}\n" "\n" "QWidget::item:selected {\n" " background-color: #1464A0;\n" "}\n" "\n" "QWidget::item:hover {\n" " background-color: #148CD2;\n" " color: #32414B;\n" "}\n" "\n" "/* QMainWindow ------------------------------------------------------------\n" "\n" "This adjusts the splitter in the dock widget, not qsplitter\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmainwindow\n" "\n" "--------------------------------------------------------------------------- */\n" "QMainWindow::separator {\n" " background-color: #32414B;\n" " border: 0px solid #19232D;\n" " spacing: 0px;\n" " padding: 2px;\n" "}\n" "\n" "QMainWindow::separator:hover {\n" " background-color: #505F69;\n" " border: 0px solid #148CD2;\n" "}\n" "\n" "QMainWindow::separator:horizontal {\n" " width: 5px;\n" " margin-top: 2px;\n" " margin-bottom: 2px;\n" " image: url(\":/qss_icons/rc/toolbar_separator_vertical.png\");\n" "}\n" "\n" "QMainWindow::separator:vertical {\n" " height: 5px;\n" " margin-left: 2px;\n" " margin-right: 2px;\n" " image: url(\":/qss_icons/rc/toolbar_separator_horizontal.png\");\n" "}\n" "\n" "/* QToolTip ---------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtooltip\n" "\n" "--------------------------------------------------------------------------- */\n" "QToolTip {\n" " background-color: #148CD2;\n" " border: 1px solid #19232D;\n" " color: #19232D;\n" " /* Remove padding, for fix combo box tooltip */\n" " padding: 0px;\n" " /* Remove opacity, fix #174 - may need to use RGBA */\n" "}\n" "\n" "/* QStatusBar -------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qstatusbar\n" "\n" "--------------------------------------------------------------------------- */\n" "QStatusBar {\n" " border: 1px solid #32414B;\n" " /* Fixes Spyder #9120, #9121 */\n" " background: #32414B;\n" " /* Fixes #205, white vertical borders separating items */\n" "}\n" "\n" "QStatusBar::item {\n" " border: none;\n" "}\n" "\n" "QStatusBar QToolTip {\n" " background-color: #148CD2;\n" " border: 1px solid #19232D;\n" " color: #19232D;\n" " /* Remove padding, for fix combo box tooltip */\n" " padding: 0px;\n" " /* Reducing transparency to read better */\n" " opacity: 230;\n" "}\n" "\n" "QStatusBar QLabel {\n" " /* Fixes Spyder #9120, #9121 */\n" " background: transparent;\n" "}\n" "\n" "/* QCheckBox --------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcheckbox\n" "\n" "--------------------------------------------------------------------------- */\n" "QCheckBox {\n" " background-color: #19232D;\n" " color: #F0F0F0;\n" " spacing: 4px;\n" " outline: none;\n" " padding-top: 4px;\n" " padding-bottom: 4px;\n" "}\n" "\n" "QCheckBox:focus {\n" " border: none;\n" "}\n" "\n" "QCheckBox QWidget:disabled {\n" " background-color: #19232D;\n" " color: #787878;\n" "}\n" "\n" "QCheckBox::indicator {\n" " margin-left: 4px;\n" " height: 16px;\n" " width: 16px;\n" "}\n" "\n" "QCheckBox::indicator:unchecked {\n" " image: url(\":/qss_icons/rc/checkbox_unchecked.png\");\n" "}\n" "\n" "QCheckBox::indicator:unchecked:hover, QCheckBox::indicator:unchecked:focus, QCheckBox::indicator:unchecked:pressed {\n" " border: none;\n" " image: url(\":/qss_icons/rc/checkbox_unchecked_focus.png\");\n" "}\n" "\n" "QCheckBox::indicator:unchecked:disabled {\n" " image: url(\":/qss_icons/rc/checkbox_unchecked_disabled.png\");\n" "}\n" "\n" "QCheckBox::indicator:checked {\n" " image: url(\":/qss_icons/rc/checkbox_checked.png\");\n" "}\n" "\n" "QCheckBox::indicator:checked:hover, QCheckBox::indicator:checked:focus, QCheckBox::indicator:checked:pressed {\n" " border: none;\n" " image: url(\":/qss_icons/rc/checkbox_checked_focus.png\");\n" "}\n" "\n" "QCheckBox::indicator:checked:disabled {\n" " image: url(\":/qss_icons/rc/checkbox_checked_disabled.png\");\n" "}\n" "\n" "QCheckBox::indicator:indeterminate {\n" " image: url(\":/qss_icons/rc/checkbox_indeterminate.png\");\n" "}\n" "\n" "QCheckBox::indicator:indeterminate:disabled {\n" " image: url(\":/qss_icons/rc/checkbox_indeterminate_disabled.png\");\n" "}\n" "\n" "QCheckBox::indicator:indeterminate:focus, QCheckBox::indicator:indeterminate:hover, QCheckBox::indicator:indeterminate:pressed {\n" " image: url(\":/qss_icons/rc/checkbox_indeterminate_focus.png\");\n" "}\n" "\n" "/* QGroupBox --------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qgroupbox\n" "\n" "--------------------------------------------------------------------------- */\n" "QGroupBox {\n" " font-weight: bold;\n" " border: 1px solid #32414B;\n" " border-radius: 4px;\n" " padding: 4px;\n" " margin-top: 16px;\n" "}\n" "\n" "QGroupBox::title {\n" " subcontrol-origin: margin;\n" " subcontrol-position: top left;\n" " left: 3px;\n" " padding-left: 3px;\n" " padding-right: 5px;\n" " padding-top: 8px;\n" " padding-bottom: 16px;\n" "}\n" "\n" "QGroupBox::indicator {\n" " margin-left: 2px;\n" " height: 16px;\n" " width: 16px;\n" "}\n" "\n" "QGroupBox::indicator:unchecked {\n" " border: none;\n" " image: url(\":/qss_icons/rc/checkbox_unchecked.png\");\n" "}\n" "\n" "QGroupBox::indicator:unchecked:hover, QGroupBox::indicator:unchecked:focus, QGroupBox::indicator:unchecked:pressed {\n" " border: none;\n" " image: url(\":/qss_icons/rc/checkbox_unchecked_focus.png\");\n" "}\n" "\n" "QGroupBox::indicator:unchecked:disabled {\n" " image: url(\":/qss_icons/rc/checkbox_unchecked_disabled.png\");\n" "}\n" "\n" "QGroupBox::indicator:checked {\n" " border: none;\n" " image: url(\":/qss_icons/rc/checkbox_checked.png\");\n" "}\n" "\n" "QGroupBox::indicator:checked:hover, QGroupBox::indicator:checked:focus, QGroupBox::indicator:checked:pressed {\n" " border: none;\n" " image: url(\":/qss_icons/rc/checkbox_checked_focus.png\");\n" "}\n" "\n" "QGroupBox::indicator:checked:disabled {\n" " image: url(\":/qss_icons/rc/checkbox_checked_disabled.png\");\n" "}\n" "\n" "/* QRadioButton -----------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qradiobutton\n" "\n" "--------------------------------------------------------------------------- */\n" "QRadioButton {\n" " background-color: #19232D;\n" " color: #F0F0F0;\n" " spacing: 4px;\n" " padding: 0px;\n" " border: none;\n" " outline: none;\n" "}\n" "\n" "QRadioButton:focus {\n" " border: none;\n" "}\n" "\n" "QRadioButton:disabled {\n" " background-color: #19232D;\n" " color: #787878;\n" " border: none;\n" " outline: none;\n" "}\n" "\n" "QRadioButton QWidget {\n" " background-color: #19232D;\n" " color: #F0F0F0;\n" " spacing: 0px;\n" " padding: 0px;\n" " outline: none;\n" " border: none;\n" "}\n" "\n" "QRadioButton::indicator {\n" " border: none;\n" " outline: none;\n" " margin-left: 4px;\n" " height: 16px;\n" " width: 16px;\n" "}\n" "\n" "QRadioButton::indicator:unchecked {\n" " image: url(\":/qss_icons/rc/radio_unchecked.png\");\n" "}\n" "\n" "QRadioButton::indicator:unchecked:hover, QRadioButton::indicator:unchecked:focus, QRadioButton::indicator:unchecked:pressed {\n" " border: none;\n" " outline: none;\n" " image: url(\":/qss_icons/rc/radio_unchecked_focus.png\");\n" "}\n" "\n" "QRadioButton::indicator:unchecked:disabled {\n" " image: url(\":/qss_icons/rc/radio_unchecked_disabled.png\");\n" "}\n" "\n" "QRadioButton::indicator:checked {\n" " border: none;\n" " outline: none;\n" " image: url(\":/qss_icons/rc/radio_checked.png\");\n" "}\n" "\n" "QRadioButton::indicator:checked:hover, QRadioButton::indicator:checked:focus, QRadioButton::indicator:checked:pressed {\n" " border: none;\n" " outline: none;\n" " image: url(\":/qss_icons/rc/radio_checked_focus.png\");\n" "}\n" "\n" "QRadioButton::indicator:checked:disabled {\n" " outline: none;\n" " image: url(\":/qss_icons/rc/radio_checked_disabled.png\");\n" "}\n" "\n" "/* QMenuBar ---------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenubar\n" "\n" "--------------------------------------------------------------------------- */\n" "QMenuBar {\n" " background-color: #32414B;\n" " padding: 2px;\n" " border: 1px solid #19232D;\n" " color: #F0F0F0;\n" "}\n" "\n" "QMenuBar:focus {\n" " border: 1px solid #148CD2;\n" "}\n" "\n" "QMenuBar::item {\n" " background: transparent;\n" " padding: 4px;\n" "}\n" "\n" "QMenuBar::item:selected {\n" " padding: 4px;\n" " background: transparent;\n" " border: 0px solid #32414B;\n" "}\n" "\n" "QMenuBar::item:pressed {\n" " padding: 4px;\n" " border: 0px solid #32414B;\n" " background-color: #148CD2;\n" " color: #F0F0F0;\n" " margin-bottom: 0px;\n" " padding-bottom: 0px;\n" "}\n" "\n" "/* QMenu ------------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenu\n" "\n" "--------------------------------------------------------------------------- */\n" "QMenu {\n" " border: 0px solid #32414B;\n" " color: #F0F0F0;\n" " margin: 0px;\n" "}\n" "\n" "QMenu::separator {\n" " height: 1px;\n" " background-color: #505F69;\n" " color: #F0F0F0;\n" "}\n" "\n" "QMenu::icon {\n" " margin: 0px;\n" " padding-left: 8px;\n" "}\n" "\n" "QMenu::item {\n" " background-color: #32414B;\n" " padding: 4px 24px 4px 24px;\n" " /* Reserve space for selection border */\n" " border: 1px transparent #32414B;\n" "}\n" "\n" "QMenu::item:selected {\n" " color: #F0F0F0;\n" "}\n" "\n" "QMenu::indicator {\n" " width: 12px;\n" " height: 12px;\n" " padding-left: 6px;\n" " /* non-exclusive indicator = check box style indicator (see QActionGroup::setExclusive) */\n" " /* exclusive indicator = radio button style indicator (see QActionGroup::setExclusive) */\n" "}\n" "\n" "QMenu::indicator:non-exclusive:unchecked {\n" " image: url(\":/qss_icons/rc/checkbox_unchecked.png\");\n" "}\n" "\n" "QMenu::indicator:non-exclusive:unchecked:selected {\n" " image: url(\":/qss_icons/rc/checkbox_unchecked_disabled.png\");\n" "}\n" "\n" "QMenu::indicator:non-exclusive:checked {\n" " image: url(\":/qss_icons/rc/checkbox_checked.png\");\n" "}\n" "\n" "QMenu::indicator:non-exclusive:checked:selected {\n" " image: url(\":/qss_icons/rc/checkbox_checked_disabled.png\");\n" "}\n" "\n" "QMenu::indicator:exclusive:unchecked {\n" " image: url(\":/qss_icons/rc/radio_unchecked.png\");\n" "}\n" "\n" "QMenu::indicator:exclusive:unchecked:selected {\n" " image: url(\":/qss_icons/rc/radio_unchecked_disabled.png\");\n" "}\n" "\n" "QMenu::indicator:exclusive:checked {\n" " image: url(\":/qss_icons/rc/radio_checked.png\");\n" "}\n" "\n" "QMenu::indicator:exclusive:checked:selected {\n" " image: url(\":/qss_icons/rc/radio_checked_disabled.png\");\n" "}\n" "\n" "QMenu::right-arrow {\n" " margin: 5px;\n" " image: url(\":/qss_icons/rc/arrow_right.png\");\n" " height: 12px;\n" " width: 12px;\n" "}\n" "\n" "/* QAbstractItemView ------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox\n" "\n" "--------------------------------------------------------------------------- */\n" "QAbstractItemView {\n" " alternate-background-color: #19232D;\n" " color: #F0F0F0;\n" " border: 1px solid #32414B;\n" " border-radius: 4px;\n" "}\n" "\n" "QAbstractItemView QLineEdit {\n" " padding: 2px;\n" "}\n" "\n" "/* QAbstractScrollArea ----------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea\n" "\n" "--------------------------------------------------------------------------- */\n" "QAbstractScrollArea {\n" " background-color: #19232D;\n" " border: 1px solid #32414B;\n" " border-radius: 4px;\n" " padding: 2px;\n" " /* fix #159 */\n" " min-height: 1.25em;\n" " /* fix #159 */\n" " color: #F0F0F0;\n" "}\n" "\n" "QAbstractScrollArea:disabled {\n" " color: #787878;\n" "}\n" "\n" "/* QScrollArea ------------------------------------------------------------\n" "\n" "--------------------------------------------------------------------------- */\n" "QScrollArea QWidget QWidget:disabled {\n" " background-color: #19232D;\n" "}\n" "\n" "/* QScrollBar -------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qscrollbar\n" "\n" "--------------------------------------------------------------------------- */\n" "QScrollBar:horizontal {\n" " height: 16px;\n" " margin: 2px 16px 2px 16px;\n" " border: 1px solid #32414B;\n" " border-radius: 4px;\n" " background-color: #19232D;\n" "}\n" "\n" "QScrollBar:vertical {\n" " background-color: #19232D;\n" " width: 16px;\n" " margin: 16px 2px 16px 2px;\n" " border: 1px solid #32414B;\n" " border-radius: 4px;\n" "}\n" "\n" "QScrollBar::handle:horizontal {\n" " background-color: #787878;\n" " border: 1px solid #32414B;\n" " border-radius: 4px;\n" " min-width: 8px;\n" "}\n" "\n" "QScrollBar::handle:horizontal:hover {\n" " background-color: #148CD2;\n" " border: 1px solid #148CD2;\n" " border-radius: 4px;\n" " min-width: 8px;\n" "}\n" "\n" "QScrollBar::handle:horizontal:focus {\n" " border: 1px solid #1464A0;\n" "}\n" "\n" "QScrollBar::handle:vertical {\n" " background-color: #787878;\n" " border: 1px solid #32414B;\n" " min-height: 8px;\n" " border-radius: 4px;\n" "}\n" "\n" "QScrollBar::handle:vertical:hover {\n" " background-color: #148CD2;\n" " border: 1px solid #148CD2;\n" " border-radius: 4px;\n" " min-height: 8px;\n" "}\n" "\n" "QScrollBar::handle:vertical:focus {\n" " border: 1px solid #1464A0;\n" "}\n" "\n" "QScrollBar::add-line:horizontal {\n" " margin: 0px 0px 0px 0px;\n" " border-image: url(\":/qss_icons/rc/arrow_right_disabled.png\");\n" " height: 12px;\n" " width: 12px;\n" " subcontrol-position: right;\n" " subcontrol-origin: margin;\n" "}\n" "\n" "QScrollBar::add-line:horizontal:hover, QScrollBar::add-line:horizontal:on {\n" " border-image: url(\":/qss_icons/rc/arrow_right.png\");\n" " height: 12px;\n" " width: 12px;\n" " subcontrol-position: right;\n" " subcontrol-origin: margin;\n" "}\n" "\n" "QScrollBar::add-line:vertical {\n" " margin: 3px 0px 3px 0px;\n" " border-image: url(\":/qss_icons/rc/arrow_down_disabled.png\");\n" " height: 12px;\n" " width: 12px;\n" " subcontrol-position: bottom;\n" " subcontrol-origin: margin;\n" "}\n" "\n" "QScrollBar::add-line:vertical:hover, QScrollBar::add-line:vertical:on {\n" " border-image: url(\":/qss_icons/rc/arrow_down.png\");\n" " height: 12px;\n" " width: 12px;\n" " subcontrol-position: bottom;\n" " subcontrol-origin: margin;\n" "}\n" "\n" "QScrollBar::sub-line:horizontal {\n" " margin: 0px 3px 0px 3px;\n" " border-image: url(\":/qss_icons/rc/arrow_left_disabled.png\");\n" " height: 12px;\n" " width: 12px;\n" " subcontrol-position: left;\n" " subcontrol-origin: margin;\n" "}\n" "\n" "QScrollBar::sub-line:horizontal:hover, QScrollBar::sub-line:horizontal:on {\n" " border-image: url(\":/qss_icons/rc/arrow_left.png\");\n" " height: 12px;\n" " width: 12px;\n" " subcontrol-position: left;\n" " subcontrol-origin: margin;\n" "}\n" "\n" "QScrollBar::sub-line:vertical {\n" " margin: 3px 0px 3px 0px;\n" " border-image: url(\":/qss_icons/rc/arrow_up_disabled.png\");\n" " height: 12px;\n" " width: 12px;\n" " subcontrol-position: top;\n" " subcontrol-origin: margin;\n" "}\n" "\n" "QScrollBar::sub-line:vertical:hover, QScrollBar::sub-line:vertical:on {\n" " border-image: url(\":/qss_icons/rc/arrow_up.png\");\n" " height: 12px;\n" " width: 12px;\n" " subcontrol-position: top;\n" " subcontrol-origin: margin;\n" "}\n" "\n" "QScrollBar::up-arrow:horizontal, QScrollBar::down-arrow:horizontal {\n" " background: none;\n" "}\n" "\n" "QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {\n" " background: none;\n" "}\n" "\n" "QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {\n" " background: none;\n" "}\n" "\n" "QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {\n" " background: none;\n" "}\n" "\n" "/* QTextEdit --------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-specific-widgets\n" "\n" "--------------------------------------------------------------------------- */\n" "QTextEdit {\n" " background-color: #19232D;\n" " color: #F0F0F0;\n" " border-radius: 4px;\n" " border: 1px solid #32414B;\n" "}\n" "\n" "QTextEdit:hover {\n" " border: 1px solid #148CD2;\n" " color: #F0F0F0;\n" "}\n" "\n" "QTextEdit:focus {\n" " border: 1px solid #1464A0;\n" "}\n" "\n" "QTextEdit:selected {\n" " background: #1464A0;\n" " color: #32414B;\n" "}\n" "\n" "/* QPlainTextEdit ---------------------------------------------------------\n" "\n" "--------------------------------------------------------------------------- */\n" "QPlainTextEdit {\n" " background-color: #19232D;\n" " color: #F0F0F0;\n" " border-radius: 4px;\n" " border: 1px solid #32414B;\n" "}\n" "\n" "QPlainTextEdit:hover {\n" " border: 1px solid #148CD2;\n" " color: #F0F0F0;\n" "}\n" "\n" "QPlainTextEdit:focus {\n" " border: 1px solid #1464A0;\n" "}\n" "\n" "QPlainTextEdit:selected {\n" " background: #1464A0;\n" " color: #32414B;\n" "}\n" "\n" "/* QSizeGrip --------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsizegrip\n" "\n" "--------------------------------------------------------------------------- */\n" "QSizeGrip {\n" " background: transparent;\n" " width: 12px;\n" " height: 12px;\n" " image: url(\":/qss_icons/rc/window_grip.png\");\n" "}\n" "\n" "/* QStackedWidget ---------------------------------------------------------\n" "\n" "--------------------------------------------------------------------------- */\n" "QStackedWidget {\n" " padding: 2px;\n" " border: 1px solid #32414B;\n" " border: 1px solid #19232D;\n" "}\n" "\n" "/* QToolBar ---------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbar\n" "\n" "--------------------------------------------------------------------------- */\n" "QToolBar {\n" " background-color: #32414B;\n" " border-bottom: 1px solid #19232D;\n" " padding: 2px;\n" " font-weight: bold;\n" " spacing: 2px;\n" "}\n" "\n" "QToolBar QToolButton {\n" " background-color: #32414B;\n" " border: 1px solid #32414B;\n" "}\n" "\n" "QToolBar QToolButton:hover {\n" " border: 1px solid #148CD2;\n" "}\n" "\n" "QToolBar QToolButton:checked {\n" " border: 1px solid #19232D;\n" " background-color: #19232D;\n" "}\n" "\n" "QToolBar QToolButton:checked:hover {\n" " border: 1px solid #148CD2;\n" "}\n" "\n" "QToolBar::handle:horizontal {\n" " width: 16px;\n" " image: url(\":/qss_icons/rc/toolbar_move_horizontal.png\");\n" "}\n" "\n" "QToolBar::handle:vertical {\n" " height: 16px;\n" " image: url(\":/qss_icons/rc/toolbar_move_vertical.png\");\n" "}\n" "\n" "QToolBar::separator:horizontal {\n" " width: 16px;\n" " image: url(\":/qss_icons/rc/toolbar_separator_horizontal.png\");\n" "}\n" "\n" "QToolBar::separator:vertical {\n" " height: 16px;\n" " image: url(\":/qss_icons/rc/toolbar_separator_vertical.png\");\n" "}\n" "\n" "QToolButton#qt_toolbar_ext_button {\n" " background: #32414B;\n" " border: 0px;\n" " color: #F0F0F0;\n" " image: url(\":/qss_icons/rc/arrow_right.png\");\n" "}\n" "\n" "/* QAbstractSpinBox -------------------------------------------------------\n" "\n" "--------------------------------------------------------------------------- */\n" "QAbstractSpinBox {\n" " background-color: #19232D;\n" " border: 1px solid #32414B;\n" " color: #F0F0F0;\n" " /* This fixes 103, 111 */\n" " padding-top: 2px;\n" " /* This fixes 103, 111 */\n" " padding-bottom: 2px;\n" " padding-left: 4px;\n" " padding-right: 4px;\n" " border-radius: 4px;\n" " /* min-width: 5px; removed to fix 109 */\n" "}\n" "\n" "QAbstractSpinBox:up-button {\n" " background-color: transparent #19232D;\n" " subcontrol-origin: border;\n" " subcontrol-position: top right;\n" " border-left: 1px solid #32414B;\n" " border-bottom: 1px solid #32414B;\n" " border-top-left-radius: 0;\n" " border-bottom-left-radius: 0;\n" " margin: 1px;\n" " width: 12px;\n" " margin-bottom: -1px;\n" "}\n" "\n" "QAbstractSpinBox::up-arrow, QAbstractSpinBox::up-arrow:disabled, QAbstractSpinBox::up-arrow:off {\n" " image: url(\":/qss_icons/rc/arrow_up_disabled.png\");\n" " height: 8px;\n" " width: 8px;\n" "}\n" "\n" "QAbstractSpinBox::up-arrow:hover {\n" " image: url(\":/qss_icons/rc/arrow_up.png\");\n" "}\n" "\n" "QAbstractSpinBox:down-button {\n" " background-color: transparent #19232D;\n" " subcontrol-origin: border;\n" " subcontrol-position: bottom right;\n" " border-left: 1px solid #32414B;\n" " border-top: 1px solid #32414B;\n" " border-top-left-radius: 0;\n" " border-bottom-left-radius: 0;\n" " margin: 1px;\n" " width: 12px;\n" " margin-top: -1px;\n" "}\n" "\n" "QAbstractSpinBox::down-arrow, QAbstractSpinBox::down-arrow:disabled, QAbstractSpinBox::down-arrow:off {\n" " image: url(\":/qss_icons/rc/arrow_down_disabled.png\");\n" " height: 8px;\n" " width: 8px;\n" "}\n" "\n" "QAbstractSpinBox::down-arrow:hover {\n" " image: url(\":/qss_icons/rc/arrow_down.png\");\n" "}\n" "\n" "QAbstractSpinBox:hover {\n" " border: 1px solid #148CD2;\n" " color: #F0F0F0;\n" "}\n" "\n" "QAbstractSpinBox:focus {\n" " border: 1px solid #1464A0;\n" "}\n" "\n" "QAbstractSpinBox:selected {\n" " background: #1464A0;\n" " color: #32414B;\n" "}\n" "\n" "/* ------------------------------------------------------------------------ */\n" "/* DISPLAYS --------------------------------------------------------------- */\n" "/* ------------------------------------------------------------------------ */\n" "/* QLabel -----------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe\n" "\n" "--------------------------------------------------------------------------- */\n" "QLabel {\n" " background-color: #19232D;\n" " border: 0px solid #32414B;\n" " padding: 2px;\n" " margin: 0px;\n" " color: #F0F0F0;\n" "}\n" "\n" "QLabel:disabled {\n" " background-color: #19232D;\n" " border: 0px solid #32414B;\n" " color: #787878;\n" "}\n" "\n" "/* QTextBrowser -----------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea\n" "\n" "--------------------------------------------------------------------------- */\n" "QTextBrowser {\n" " background-color: #19232D;\n" " border: 1px solid #32414B;\n" " color: #F0F0F0;\n" " border-radius: 4px;\n" "}\n" "\n" "QTextBrowser:disabled {\n" " background-color: #19232D;\n" " border: 1px solid #32414B;\n" " color: #787878;\n" " border-radius: 4px;\n" "}\n" "\n" "QTextBrowser:hover, QTextBrowser:!hover, QTextBrowser:selected, QTextBrowser:pressed {\n" " border: 1px solid #32414B;\n" "}\n" "\n" "/* QGraphicsView ----------------------------------------------------------\n" "\n" "--------------------------------------------------------------------------- */\n" "QGraphicsView {\n" " background-color: #19232D;\n" " border: 1px solid #32414B;\n" " color: #F0F0F0;\n" " border-radius: 4px;\n" "}\n" "\n" "QGraphicsView:disabled {\n" " background-color: #19232D;\n" " border: 1px solid #32414B;\n" " color: #787878;\n" " border-radius: 4px;\n" "}\n" "\n" "QGraphicsView:hover, QGraphicsView:!hover, QGraphicsView:selected, QGraphicsView:pressed {\n" " border: 1px solid #32414B;\n" "}\n" "\n" "/* QCalendarWidget --------------------------------------------------------\n" "\n" "--------------------------------------------------------------------------- */\n" "QCalendarWidget {\n" " border: 1px solid #32414B;\n" " border-radius: 4px;\n" "}\n" "\n" "QCalendarWidget:disabled {\n" " background-color: #19232D;\n" " color: #787878;\n" "}\n" "\n" "/* QLCDNumber -------------------------------------------------------------\n" "\n" "--------------------------------------------------------------------------- */\n" "QLCDNumber {\n" " background-color: #19232D;\n" " color: #F0F0F0;\n" "}\n" "\n" "QLCDNumber:disabled {\n" " background-color: #19232D;\n" " color: #787878;\n" "}\n" "\n" "/* QProgressBar -----------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qprogressbar\n" "\n" "--------------------------------------------------------------------------- */\n" "QProgressBar {\n" " background-color: #19232D;\n" " border: 1px solid #32414B;\n" " color: #F0F0F0;\n" " border-radius: 4px;\n" " text-align: center;\n" "}\n" "\n" "QProgressBar:disabled {\n" " background-color: #19232D;\n" " border: 1px solid #32414B;\n" " color: #787878;\n" " border-radius: 4px;\n" " text-align: center;\n" "}\n" "\n" "QProgressBar::chunk {\n" " background-color: #1464A0;\n" " color: #19232D;\n" " border-radius: 4px;\n" "}\n" "\n" "QProgressBar::chunk:disabled {\n" " background-color: #14506E;\n" " color: #787878;\n" " border-radius: 4px;\n" "}\n" "\n" "/* ------------------------------------------------------------------------ */\n" "/* BUTTONS ---------------------------------------------------------------- */\n" "/* ------------------------------------------------------------------------ */\n" "/* QPushButton ------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qpushbutton\n" "\n" "--------------------------------------------------------------------------- */\n" "QPushButton {\n" " background-color: #505F69;\n" " border: 1px solid #32414B;\n" " color: #F0F0F0;\n" " border-radius: 4px;\n" " padding: 3px;\n" " outline: none;\n" " /* Issue #194 - Special case of QPushButton inside dialogs, for better UI */\n" " min-width: 80px;\n" "}\n" "\n" "QPushButton:disabled {\n" " background-color: #32414B;\n" " border: 1px solid #32414B;\n" " color: #787878;\n" " border-radius: 4px;\n" " padding: 3px;\n" "}\n" "\n" "QPushButton:checked {\n" " background-color: #32414B;\n" " border: 1px solid #32414B;\n" " border-radius: 4px;\n" " padding: 3px;\n" " outline: none;\n" "}\n" "\n" "QPushButton:checked:disabled {\n" " background-color: #19232D;\n" " border: 1px solid #32414B;\n" " color: #787878;\n" " border-radius: 4px;\n" " padding: 3px;\n" " outline: none;\n" "}\n" "\n" "QPushButton:checked:selected {\n" " background: #1464A0;\n" " color: #32414B;\n" "}\n" "\n" "QPushButton::menu-indicator {\n" " subcontrol-origin: padding;\n" " subcontrol-position: bottom right;\n" " bottom: 4px;\n" "}\n" "\n" "QPushButton:pressed {\n" " background-color: #19232D;\n" " border: 1px solid #19232D;\n" "}\n" "\n" "QPushButton:pressed:hover {\n" " border: 1px solid #148CD2;\n" "}\n" "\n" "QPushButton:hover {\n" " border: 1px solid #148CD2;\n" " color: #F0F0F0;\n" "}\n" "\n" "QPushButton:selected {\n" " background: #1464A0;\n" " color: #32414B;\n" "}\n" "\n" "QPushButton:hover {\n" " border: 1px solid #148CD2;\n" " color: #F0F0F0;\n" "}\n" "\n" "QPushButton:focus {\n" " border: 1px solid #1464A0;\n" "}\n" "\n" "/* QToolButton ------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbutton\n" "\n" "--------------------------------------------------------------------------- */\n" "QToolButton {\n" " background-color: transparent;\n" " border: 1px solid transparent;\n" " border-radius: 4px;\n" " margin: 0px;\n" " padding: 2px;\n" " /* The subcontrols below are used only in the DelayedPopup mode */\n" " /* The subcontrols below are used only in the MenuButtonPopup mode */\n" " /* The subcontrol below is used only in the InstantPopup or DelayedPopup mode */\n" "}\n" "\n" "QToolButton:checked {\n" " background-color: transparent;\n" " border: 1px solid #1464A0;\n" "}\n" "\n" "QToolButton:checked:disabled {\n" " border: 1px solid #14506E;\n" "}\n" "\n" "QToolButton:pressed {\n" " margin: 1px;\n" " background-color: transparent;\n" " border: 1px solid #1464A0;\n" "}\n" "\n" "QToolButton:disabled {\n" " border: none;\n" "}\n" "\n" "QToolButton:hover {\n" " border: 1px solid #148CD2;\n" "}\n" "\n" "QToolButton[popupMode=\"0\"] {\n" " /* Only for DelayedPopup */\n" " padding-right: 2px;\n" "}\n" "\n" "QToolButton[popupMode=\"1\"] {\n" " /* Only for MenuButtonPopup */\n" " padding-right: 20px;\n" "}\n" "\n" "QToolButton[popupMode=\"1\"]::menu-button {\n" " border: none;\n" "}\n" "\n" "QToolButton[popupMode=\"1\"]::menu-button:hover {\n" " border: none;\n" " border-left: 1px solid #148CD2;\n" " border-radius: 0;\n" "}\n" "\n" "QToolButton[popupMode=\"2\"] {\n" " /* Only for InstantPopup */\n" " padding-right: 2px;\n" "}\n" "\n" "QToolButton::menu-button {\n" " padding: 2px;\n" " border-radius: 4px;\n" " border: 1px solid #32414B;\n" " width: 12px;\n" " outline: none;\n" "}\n" "\n" "QToolButton::menu-button:hover {\n" " border: 1px solid #148CD2;\n" "}\n" "\n" "QToolButton::menu-button:checked:hover {\n" " border: 1px solid #148CD2;\n" "}\n" "\n" "QToolButton::menu-indicator {\n" " image: url(\":/qss_icons/rc/arrow_down.png\");\n" " height: 8px;\n" " width: 8px;\n" " top: 0;\n" " /* Exclude a shift for better image */\n" " left: -2px;\n" " /* Shift it a bit */\n" "}\n" "\n" "QToolButton::menu-arrow {\n" " image: url(\":/qss_icons/rc/arrow_down.png\");\n" " height: 8px;\n" " width: 8px;\n" "}\n" "\n" "QToolButton::menu-arrow:hover {\n" " image: url(\":/qss_icons/rc/arrow_down_focus.png\");\n" "}\n" "\n" "/* QCommandLinkButton -----------------------------------------------------\n" "\n" "--------------------------------------------------------------------------- */\n" "QCommandLinkButton {\n" " background-color: transparent;\n" " border: 1px solid #32414B;\n" " color: #F0F0F0;\n" " border-radius: 4px;\n" " padding: 0px;\n" " margin: 0px;\n" "}\n" "\n" "QCommandLinkButton:disabled {\n" " background-color: transparent;\n" " color: #787878;\n" "}\n" "\n" "/* ------------------------------------------------------------------------ */\n" "/* INPUTS - NO FIELDS ----------------------------------------------------- */\n" "/* ------------------------------------------------------------------------ */\n" "/* QComboBox --------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox\n" "\n" "--------------------------------------------------------------------------- */\n" "QComboBox {\n" " border: 1px solid #32414B;\n" " border-radius: 4px;\n" " selection-background-color: #1464A0;\n" " padding-left: 4px;\n" " padding-right: 36px;\n" " /* 4 + 16*2 See scrollbar size */\n" " /* Fixes #103, #111 */\n" " min-height: 1.5em;\n" " /* padding-top: 2px; removed to fix #132 */\n" " /* padding-bottom: 2px; removed to fix #132 */\n" " /* min-width: 75px; removed to fix #109 */\n" " /* Needed to remove indicator - fix #132 */\n" "}\n" "\n" "QComboBox QAbstractItemView {\n" " border: 1px solid #32414B;\n" " border-radius: 0;\n" " background-color: #19232D;\n" " selection-background-color: #1464A0;\n" "}\n" "\n" "QComboBox QAbstractItemView:hover {\n" " background-color: #19232D;\n" " color: #F0F0F0;\n" "}\n" "\n" "QComboBox QAbstractItemView:selected {\n" " background: #1464A0;\n" " color: #32414B;\n" "}\n" "\n" "QComboBox QAbstractItemView:alternate {\n" " background: #19232D;\n" "}\n" "\n" "QComboBox:disabled {\n" " background-color: #19232D;\n" " color: #787878;\n" "}\n" "\n" "QComboBox:hover {\n" " border: 1px solid #148CD2;\n" "}\n" "\n" "QComboBox:focus {\n" " border: 1px solid #1464A0;\n" "}\n" "\n" "QComboBox:on {\n" " selection-background-color: #1464A0;\n" "}\n" "\n" "QComboBox::indicator {\n" " border: none;\n" " border-radius: 0;\n" " background-color: transparent;\n" " selection-background-color: transparent;\n" " color: transparent;\n" " selection-color: transparent;\n" " /* Needed to remove indicator - fix #132 */\n" "}\n" "\n" "QComboBox::indicator:alternate {\n" " background: #19232D;\n" "}\n" "\n" "QComboBox::item:alternate {\n" " background: #19232D;\n" "}\n" "\n" "QComboBox::item:checked {\n" " font-weight: bold;\n" "}\n" "\n" "QComboBox::item:selected {\n" " border: 0px solid transparent;\n" "}\n" "\n" "QComboBox::drop-down {\n" " subcontrol-origin: padding;\n" " subcontrol-position: top right;\n" " width: 12px;\n" " border-left: 1px solid #32414B;\n" "}\n" "\n" "QComboBox::down-arrow {\n" " image: url(\":/qss_icons/rc/arrow_down_disabled.png\");\n" " height: 8px;\n" " width: 8px;\n" "}\n" "\n" "QComboBox::down-arrow:on, QComboBox::down-arrow:hover, QComboBox::down-arrow:focus {\n" " image: url(\":/qss_icons/rc/arrow_down.png\");\n" "}\n" "\n" "/* QSlider ----------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qslider\n" "\n" "--------------------------------------------------------------------------- */\n" "QSlider:disabled {\n" " background: #19232D;\n" "}\n" "\n" "QSlider:focus {\n" " border: none;\n" "}\n" "\n" "QSlider::groove:horizontal {\n" " background: #32414B;\n" " border: 1px solid #32414B;\n" " height: 4px;\n" " margin: 0px;\n" " border-radius: 4px;\n" "}\n" "\n" "QSlider::groove:vertical {\n" " background: #32414B;\n" " border: 1px solid #32414B;\n" " width: 4px;\n" " margin: 0px;\n" " border-radius: 4px;\n" "}\n" "\n" "QSlider::add-page:vertical {\n" " background: #1464A0;\n" " border: 1px solid #32414B;\n" " width: 4px;\n" " margin: 0px;\n" " border-radius: 4px;\n" "}\n" "\n" "QSlider::add-page:vertical :disabled {\n" " background: #14506E;\n" "}\n" "\n" "QSlider::sub-page:horizontal {\n" " background: #1464A0;\n" " border: 1px solid #32414B;\n" " height: 4px;\n" " margin: 0px;\n" " border-radius: 4px;\n" "}\n" "\n" "QSlider::sub-page:horizontal:disabled {\n" " background: #14506E;\n" "}\n" "\n" "QSlider::handle:horizontal {\n" " background: #787878;\n" " border: 1px solid #32414B;\n" " width: 8px;\n" " height: 8px;\n" " margin: -8px 0px;\n" " border-radius: 4px;\n" "}\n" "\n" "QSlider::handle:horizontal:hover {\n" " background: #148CD2;\n" " border: 1px solid #148CD2;\n" "}\n" "\n" "QSlider::handle:horizontal:focus {\n" " border: 1px solid #1464A0;\n" "}\n" "\n" "QSlider::handle:vertical {\n" " background: #787878;\n" " border: 1px solid #32414B;\n" " width: 8px;\n" " height: 8px;\n" " margin: 0 -8px;\n" " border-radius: 4px;\n" "}\n" "\n" "QSlider::handle:vertical:hover {\n" " background: #148CD2;\n" " border: 1px solid #148CD2;\n" "}\n" "\n" "QSlider::handle:vertical:focus {\n" " border: 1px solid #1464A0;\n" "}\n" "\n" "/* QLineEdit --------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlineedit\n" "\n" "--------------------------------------------------------------------------- */\n" "QLineEdit {\n" " background-color: #19232D;\n" " padding-top: 2px;\n" " /* This QLineEdit fix 103, 111 */\n" " padding-bottom: 2px;\n" " /* This QLineEdit fix 103, 111 */\n" " padding-left: 4px;\n" " padding-right: 4px;\n" " border-style: solid;\n" " border: 1px solid #32414B;\n" " border-radius: 4px;\n" " color: #F0F0F0;\n" "}\n" "\n" "QLineEdit:disabled {\n" " background-color: #19232D;\n" " color: #787878;\n" "}\n" "\n" "QLineEdit:hover {\n" " border: 1px solid #148CD2;\n" " color: #F0F0F0;\n" "}\n" "\n" "QLineEdit:focus {\n" " border: 1px solid #1464A0;\n" "}\n" "\n" "QLineEdit:selected {\n" " background-color: #1464A0;\n" " color: #32414B;\n" "}\n" "\n" "/* QTabWiget --------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar\n" "\n" "--------------------------------------------------------------------------- */\n" "QTabWidget {\n" " padding: 2px;\n" " selection-background-color: #32414B;\n" "}\n" "\n" "QTabWidget QWidget {\n" " /* Fixes #189 */\n" " border-radius: 4px;\n" "}\n" "\n" "QTabWidget::pane {\n" " border: 1px solid #32414B;\n" " border-radius: 4px;\n" " margin: 0px;\n" " /* Fixes double border inside pane with pyqt5 */\n" " padding: 0px;\n" "}\n" "\n" "QTabWidget::pane:selected {\n" " background-color: #32414B;\n" " border: 1px solid #1464A0;\n" "}\n" "\n" "/* QTabBar ----------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar\n" "\n" "--------------------------------------------------------------------------- */\n" "QTabBar {\n" " qproperty-drawBase: 0;\n" " border-radius: 4px;\n" " margin: 0px;\n" " padding: 2px;\n" " border: 0;\n" " /* left: 5px; move to the right by 5px - removed for fix */\n" "}\n" "\n" "QTabBar::close-button {\n" " border: 0;\n" " margin: 2px;\n" " padding: 2px;\n" " image: url(\":/qss_icons/rc/window_close.png\");\n" "}\n" "\n" "QTabBar::close-button:hover {\n" " image: url(\":/qss_icons/rc/window_close_focus.png\");\n" "}\n" "\n" "QTabBar::close-button:pressed {\n" " image: url(\":/qss_icons/rc/window_close_pressed.png\");\n" "}\n" "\n" "/* QTabBar::tab - selected ------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar\n" "\n" "--------------------------------------------------------------------------- */\n" "QTabBar::tab {\n" " /* !selected and disabled ----------------------------------------- */\n" " /* selected ------------------------------------------------------- */\n" "}\n" "\n" "QTabBar::tab:top:selected:disabled {\n" " border-bottom: 3px solid #14506E;\n" " color: #787878;\n" " background-color: #32414B;\n" "}\n" "\n" "QTabBar::tab:bottom:selected:disabled {\n" " border-top: 3px solid #14506E;\n" " color: #787878;\n" " background-color: #32414B;\n" "}\n" "\n" "QTabBar::tab:left:selected:disabled {\n" " border-right: 3px solid #14506E;\n" " color: #787878;\n" " background-color: #32414B;\n" "}\n" "\n" "QTabBar::tab:right:selected:disabled {\n" " border-left: 3px solid #14506E;\n" " color: #787878;\n" " background-color: #32414B;\n" "}\n" "\n" "QTabBar::tab:top:!selected:disabled {\n" " border-bottom: 3px solid #19232D;\n" " color: #787878;\n" " background-color: #19232D;\n" "}\n" "\n" "QTabBar::tab:bottom:!selected:disabled {\n" " border-top: 3px solid #19232D;\n" " color: #787878;\n" " background-color: #19232D;\n" "}\n" "\n" "QTabBar::tab:left:!selected:disabled {\n" " border-right: 3px solid #19232D;\n" " color: #787878;\n" " background-color: #19232D;\n" "}\n" "\n" "QTabBar::tab:right:!selected:disabled {\n" " border-left: 3px solid #19232D;\n" " color: #787878;\n" " background-color: #19232D;\n" "}\n" "\n" "QTabBar::tab:top:!selected {\n" " border-bottom: 2px solid #19232D;\n" " margin-top: 2px;\n" "}\n" "\n" "QTabBar::tab:bottom:!selected {\n" " border-top: 2px solid #19232D;\n" " margin-bottom: 3px;\n" "}\n" "\n" "QTabBar::tab:left:!selected {\n" " border-left: 2px solid #19232D;\n" " margin-right: 2px;\n" "}\n" "\n" "QTabBar::tab:right:!selected {\n" " border-right: 2px solid #19232D;\n" " margin-left: 2px;\n" "}\n" "\n" "QTabBar::tab:top {\n" " background-color: #32414B;\n" " color: #F0F0F0;\n" " margin-left: 2px;\n" " padding-left: 4px;\n" " padding-right: 4px;\n" " padding-top: 2px;\n" " padding-bottom: 2px;\n" " min-width: 5px;\n" " border-bottom: 3px solid #32414B;\n" " border-top-left-radius: 3px;\n" " border-top-right-radius: 3px;\n" "}\n" "\n" "QTabBar::tab:top:selected {\n" " background-color: #505F69;\n" " color: #F0F0F0;\n" " border-bottom: 3px solid #1464A0;\n" " border-top-left-radius: 3px;\n" " border-top-right-radius: 3px;\n" "}\n" "\n" "QTabBar::tab:top:!selected:hover {\n" " border: 1px solid #148CD2;\n" " border-bottom: 3px solid #148CD2;\n" " /* Fixes spyder-ide/spyder#9766 */\n" " padding-left: 4px;\n" " padding-right: 4px;\n" "}\n" "\n" "QTabBar::tab:bottom {\n" " color: #F0F0F0;\n" " border-top: 3px solid #32414B;\n" " background-color: #32414B;\n" " margin-left: 2px;\n" " padding-left: 4px;\n" " padding-right: 4px;\n" " padding-top: 2px;\n" " padding-bottom: 2px;\n" " border-bottom-left-radius: 3px;\n" " border-bottom-right-radius: 3px;\n" " min-width: 5px;\n" "}\n" "\n" "QTabBar::tab:bottom:selected {\n" " color: #F0F0F0;\n" " background-color: #505F69;\n" " border-top: 3px solid #1464A0;\n" " border-bottom-left-radius: 3px;\n" " border-bottom-right-radius: 3px;\n" "}\n" "\n" "QTabBar::tab:bottom:!selected:hover {\n" " border: 1px solid #148CD2;\n" " border-top: 3px solid #148CD2;\n" " /* Fixes spyder-ide/spyder#9766 */\n" " padding-left: 4px;\n" " padding-right: 4px;\n" "}\n" "\n" "QTabBar::tab:left {\n" " color: #F0F0F0;\n" " background-color: #32414B;\n" " margin-top: 2px;\n" " padding-left: 2px;\n" " padding-right: 2px;\n" " padding-top: 4px;\n" " padding-bottom: 4px;\n" " border-top-left-radius: 3px;\n" " border-bottom-left-radius: 3px;\n" " min-height: 5px;\n" "}\n" "\n" "QTabBar::tab:left:selected {\n" " color: #F0F0F0;\n" " background-color: #505F69;\n" " border-right: 3px solid #1464A0;\n" "}\n" "\n" "QTabBar::tab:left:!selected:hover {\n" " border: 1px solid #148CD2;\n" " border-right: 3px solid #148CD2;\n" " padding: 0px;\n" "}\n" "\n" "QTabBar::tab:right {\n" " color: #F0F0F0;\n" " background-color: #32414B;\n" " margin-top: 2px;\n" " padding-left: 2px;\n" " padding-right: 2px;\n" " padding-top: 4px;\n" " padding-bottom: 4px;\n" " border-top-right-radius: 3px;\n" " border-bottom-right-radius: 3px;\n" " min-height: 5px;\n" "}\n" "\n" "QTabBar::tab:right:selected {\n" " color: #F0F0F0;\n" " background-color: #505F69;\n" " border-left: 3px solid #1464A0;\n" "}\n" "\n" "QTabBar::tab:right:!selected:hover {\n" " border: 1px solid #148CD2;\n" " border-left: 3px solid #148CD2;\n" " padding: 0px;\n" "}\n" "\n" "QTabBar QToolButton {\n" " /* Fixes #136 */\n" " background-color: #32414B;\n" " height: 12px;\n" " width: 12px;\n" "}\n" "\n" "QTabBar QToolButton:pressed {\n" " background-color: #32414B;\n" "}\n" "\n" "QTabBar QToolButton:pressed:hover {\n" " border: 1px solid #148CD2;\n" "}\n" "\n" "QTabBar QToolButton::left-arrow:enabled {\n" " image: url(\":/qss_icons/rc/arrow_left.png\");\n" "}\n" "\n" "QTabBar QToolButton::left-arrow:disabled {\n" " image: url(\":/qss_icons/rc/arrow_left_disabled.png\");\n" "}\n" "\n" "QTabBar QToolButton::right-arrow:enabled {\n" " image: url(\":/qss_icons/rc/arrow_right.png\");\n" "}\n" "\n" "QTabBar QToolButton::right-arrow:disabled {\n" " image: url(\":/qss_icons/rc/arrow_right_disabled.png\");\n" "}\n" "\n" "/* QDockWiget -------------------------------------------------------------\n" "\n" "--------------------------------------------------------------------------- */\n" "QDockWidget {\n" " outline: 1px solid #32414B;\n" " background-color: #19232D;\n" " border: 1px solid #32414B;\n" " border-radius: 4px;\n" " titlebar-close-icon: url(\":/qss_icons/rc/window_close.png\");\n" " titlebar-normal-icon: url(\":/qss_icons/rc/window_undock.png\");\n" "}\n" "\n" "QDockWidget::title {\n" " /* Better size for title bar */\n" " padding: 6px;\n" " spacing: 4px;\n" " border: none;\n" " background-color: #32414B;\n" "}\n" "\n" "QDockWidget::close-button {\n" " background-color: #32414B;\n" " border-radius: 4px;\n" " border: none;\n" "}\n" "\n" "QDockWidget::close-button:hover {\n" " image: url(\":/qss_icons/rc/window_close_focus.png\");\n" "}\n" "\n" "QDockWidget::close-button:pressed {\n" " image: url(\":/qss_icons/rc/window_close_pressed.png\");\n" "}\n" "\n" "QDockWidget::float-button {\n" " background-color: #32414B;\n" " border-radius: 4px;\n" " border: none;\n" "}\n" "\n" "QDockWidget::float-button:hover {\n" " image: url(\":/qss_icons/rc/window_undock_focus.png\");\n" "}\n" "\n" "QDockWidget::float-button:pressed {\n" " image: url(\":/qss_icons/rc/window_undock_pressed.png\");\n" "}\n" "\n" "/* QTreeView QListView QTableView -----------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtreeview\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlistview\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtableview\n" "\n" "--------------------------------------------------------------------------- */\n" "QTreeView:branch:selected, QTreeView:branch:hover {\n" " background: url(\":/qss_icons/rc/transparent.png\");\n" "}\n" "\n" "QTreeView:branch:has-siblings:!adjoins-item {\n" " border-image: url(\":/qss_icons/rc/branch_line.png\") 0;\n" "}\n" "\n" "QTreeView:branch:has-siblings:adjoins-item {\n" " border-image: url(\":/qss_icons/rc/branch_more.png\") 0;\n" "}\n" "\n" "QTreeView:branch:!has-children:!has-siblings:adjoins-item {\n" " border-image: url(\":/qss_icons/rc/branch_end.png\") 0;\n" "}\n" "\n" "QTreeView:branch:has-children:!has-siblings:closed, QTreeView:branch:closed:has-children:has-siblings {\n" " border-image: none;\n" " image: url(\":/qss_icons/rc/branch_closed.png\");\n" "}\n" "\n" "QTreeView:branch:open:has-children:!has-siblings, QTreeView:branch:open:has-children:has-siblings {\n" " border-image: none;\n" " image: url(\":/qss_icons/rc/branch_open.png\");\n" "}\n" "\n" "QTreeView:branch:has-children:!has-siblings:closed:hover, QTreeView:branch:closed:has-children:has-siblings:hover {\n" " image: url(\":/qss_icons/rc/branch_closed_focus.png\");\n" "}\n" "\n" "QTreeView:branch:open:has-children:!has-siblings:hover, QTreeView:branch:open:has-children:has-siblings:hover {\n" " image: url(\":/qss_icons/rc/branch_open_focus.png\");\n" "}\n" "\n" "QTreeView::indicator:checked,\n" "QListView::indicator:checked {\n" " image: url(\":/qss_icons/rc/checkbox_checked.png\");\n" "}\n" "\n" "QTreeView::indicator:checked:hover, QTreeView::indicator:checked:focus, QTreeView::indicator:checked:pressed,\n" "QListView::indicator:checked:hover,\n" "QListView::indicator:checked:focus,\n" "QListView::indicator:checked:pressed {\n" " image: url(\":/qss_icons/rc/checkbox_checked_focus.png\");\n" "}\n" "\n" "QTreeView::indicator:unchecked,\n" "QListView::indicator:unchecked {\n" " image: url(\":/qss_icons/rc/checkbox_unchecked.png\");\n" "}\n" "\n" "QTreeView::indicator:unchecked:hover, QTreeView::indicator:unchecked:focus, QTreeView::indicator:unchecked:pressed,\n" "QListView::indicator:unchecked:hover,\n" "QListView::indicator:unchecked:focus,\n" "QListView::indicator:unchecked:pressed {\n" " image: url(\":/qss_icons/rc/checkbox_unchecked_focus.png\");\n" "}\n" "\n" "QTreeView::indicator:indeterminate,\n" "QListView::indicator:indeterminate {\n" " image: url(\":/qss_icons/rc/checkbox_indeterminate.png\");\n" "}\n" "\n" "QTreeView::indicator:indeterminate:hover, QTreeView::indicator:indeterminate:focus, QTreeView::indicator:indeterminate:pressed,\n" "QListView::indicator:indeterminate:hover,\n" "QListView::indicator:indeterminate:focus,\n" "QListView::indicator:indeterminate:pressed {\n" " image: url(\":/qss_icons/rc/checkbox_indeterminate_focus.png\");\n" "}\n" "\n" "QTreeView,\n" "QListView,\n" "QTableView,\n" "QColumnView {\n" " background-color: #19232D;\n" " border: 1px solid #32414B;\n" " color: #F0F0F0;\n" " gridline-color: #32414B;\n" " border-radius: 4px;\n" "}\n" "\n" "QTreeView:disabled,\n" "QListView:disabled,\n" "QTableView:disabled,\n" "QColumnView:disabled {\n" " background-color: #19232D;\n" " color: #787878;\n" "}\n" "\n" "QTreeView:selected,\n" "QListView:selected,\n" "QTableView:selected,\n" "QColumnView:selected {\n" " background-color: #1464A0;\n" " color: #32414B;\n" "}\n" "\n" "QTreeView:hover,\n" "QListView:hover,\n" "QTableView:hover,\n" "QColumnView:hover {\n" " background-color: #19232D;\n" " border: 1px solid #148CD2;\n" "}\n" "\n" "QTreeView::item:pressed,\n" "QListView::item:pressed,\n" "QTableView::item:pressed,\n" "QColumnView::item:pressed {\n" " background-color: #1464A0;\n" "}\n" "\n" "QTreeView::item:selected:hover,\n" "QListView::item:selected:hover,\n" "QTableView::item:selected:hover,\n" "QColumnView::item:selected:hover {\n" " background: #1464A0;\n" " color: #19232D;\n" "}\n" "\n" "QTreeView::item:selected:active,\n" "QListView::item:selected:active,\n" "QTableView::item:selected:active,\n" "QColumnView::item:selected:active {\n" " background-color: #1464A0;\n" "}\n" "\n" "QTreeView::item:!selected:hover,\n" "QListView::item:!selected:hover,\n" "QTableView::item:!selected:hover,\n" "QColumnView::item:!selected:hover {\n" " outline: 0;\n" " color: #148CD2;\n" " background-color: #32414B;\n" "}\n" "\n" "QTableCornerButton::section {\n" " background-color: #19232D;\n" " border: 1px transparent #32414B;\n" " border-radius: 0px;\n" "}\n" "\n" "/* QHeaderView ------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qheaderview\n" "\n" "--------------------------------------------------------------------------- */\n" "QHeaderView {\n" " background-color: #32414B;\n" " border: 0px transparent #32414B;\n" " padding: 0px;\n" " margin: 0px;\n" " border-radius: 0px;\n" "}\n" "\n" "QHeaderView:disabled {\n" " background-color: #32414B;\n" " border: 1px transparent #32414B;\n" " padding: 2px;\n" "}\n" "\n" "QHeaderView::section {\n" " background-color: #32414B;\n" " color: #F0F0F0;\n" " padding: 2px;\n" " border-radius: 0px;\n" " text-align: left;\n" "}\n" "\n" "QHeaderView::section:checked {\n" " color: #F0F0F0;\n" " background-color: #1464A0;\n" "}\n" "\n" "QHeaderView::section:checked:disabled {\n" " color: #787878;\n" " background-color: #14506E;\n" "}\n" "\n" "QHeaderView::section::horizontal {\n" " padding-left: 4px;\n" " padding-right: 4px;\n" " border-left: 1px solid #19232D;\n" "}\n" "\n" "QHeaderView::section::horizontal::first, QHeaderView::section::horizontal::only-one {\n" " border-left: 1px solid #32414B;\n" "}\n" "\n" "QHeaderView::section::horizontal:disabled {\n" " color: #787878;\n" "}\n" "\n" "QHeaderView::section::vertical {\n" " padding-left: 4px;\n" " padding-right: 4px;\n" " border-top: 1px solid #19232D;\n" "}\n" "\n" "QHeaderView::section::vertical::first, QHeaderView::section::vertical::only-one {\n" " border-top: 1px solid #32414B;\n" "}\n" "\n" "QHeaderView::section::vertical:disabled {\n" " color: #787878;\n" "}\n" "\n" "QHeaderView::down-arrow {\n" " /* Those settings (border/width/height/background-color) solve bug */\n" " /* transparent arrow background and size */\n" " background-color: #32414B;\n" " border: none;\n" " height: 12px;\n" " width: 12px;\n" " padding-left: 2px;\n" " padding-right: 2px;\n" " image: url(\":/qss_icons/rc/arrow_down.png\");\n" "}\n" "\n" "QHeaderView::up-arrow {\n" " background-color: #32414B;\n" " border: none;\n" " height: 12px;\n" " width: 12px;\n" " padding-left: 2px;\n" " padding-right: 2px;\n" " image: url(\":/qss_icons/rc/arrow_up.png\");\n" "}\n" "\n" "/* QToolBox --------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbox\n" "\n" "--------------------------------------------------------------------------- */\n" "QToolBox {\n" " padding: 0px;\n" " border: 0px;\n" " border: 1px solid #32414B;\n" "}\n" "\n" "QToolBox:selected {\n" " padding: 0px;\n" " border: 2px solid #1464A0;\n" "}\n" "\n" "QToolBox::tab {\n" " background-color: #19232D;\n" " border: 1px solid #32414B;\n" " color: #F0F0F0;\n" " border-top-left-radius: 4px;\n" " border-top-right-radius: 4px;\n" "}\n" "\n" "QToolBox::tab:disabled {\n" " color: #787878;\n" "}\n" "\n" "QToolBox::tab:selected {\n" " background-color: #505F69;\n" " border-bottom: 2px solid #1464A0;\n" "}\n" "\n" "QToolBox::tab:selected:disabled {\n" " background-color: #32414B;\n" " border-bottom: 2px solid #14506E;\n" "}\n" "\n" "QToolBox::tab:!selected {\n" " background-color: #32414B;\n" " border-bottom: 2px solid #32414B;\n" "}\n" "\n" "QToolBox::tab:!selected:disabled {\n" " background-color: #19232D;\n" "}\n" "\n" "QToolBox::tab:hover {\n" " border-color: #148CD2;\n" " border-bottom: 2px solid #148CD2;\n" "}\n" "\n" "QToolBox QScrollArea QWidget QWidget {\n" " padding: 0px;\n" " border: 0px;\n" " background-color: #19232D;\n" "}\n" "\n" "/* QFrame -----------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe\n" "https://doc.qt.io/qt-5/qframe.html#-prop\n" "https://doc.qt.io/qt-5/qframe.html#details\n" "https://stackoverflow.com/questions/14581498/qt-stylesheet-for-hline-vline-color\n" "\n" "--------------------------------------------------------------------------- */\n" "/* (dot) .QFrame fix #141, #126, #123 */\n" ".QFrame {\n" " border-radius: 4px;\n" " border: 1px solid #32414B;\n" " /* No frame */\n" " /* HLine */\n" " /* HLine */\n" "}\n" "\n" ".QFrame[frameShape=\"0\"] {\n" " border-radius: 4px;\n" " border: 1px transparent #32414B;\n" "}\n" "\n" ".QFrame[frameShape=\"4\"] {\n" " max-height: 2px;\n" " border: none;\n" " background-color: #32414B;\n" "}\n" "\n" ".QFrame[frameShape=\"5\"] {\n" " max-width: 2px;\n" " border: none;\n" " background-color: #32414B;\n" "}\n" "\n" "/* QSplitter --------------------------------------------------------------\n" "\n" "https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsplitter\n" "\n" "--------------------------------------------------------------------------- */\n" "QSplitter {\n" " background-color: #32414B;\n" " spacing: 0px;\n" " padding: 0px;\n" " margin: 0px;\n" "}\n" "\n" "QSplitter::handle {\n" " background-color: #32414B;\n" " border: 0px solid #19232D;\n" " spacing: 0px;\n" " padding: 1px;\n" " margin: 0px;\n" "}\n" "\n" "QSplitter::handle:hover {\n" " background-color: #787878;\n" "}\n" "\n" "QSplitter::handle:horizontal {\n" " width: 5px;\n" " image: url(\":/qss_icons/rc/line_vertical.png\");\n" "}\n" "\n" "QSplitter::handle:vertical {\n" " height: 5px;\n" " image: url(\":/qss_icons/rc/line_horizontal.png\");\n" "}\n" "\n" "/* QDateEdit, QDateTimeEdit -----------------------------------------------\n" "\n" "--------------------------------------------------------------------------- */\n" "QDateEdit, QDateTimeEdit {\n" " selection-background-color: #1464A0;\n" " border-style: solid;\n" " border: 1px solid #32414B;\n" " border-radius: 4px;\n" " /* This fixes 103, 111 */\n" " padding-top: 2px;\n" " /* This fixes 103, 111 */\n" " padding-bottom: 2px;\n" " padding-left: 4px;\n" " padding-right: 4px;\n" " min-width: 10px;\n" "}\n" "\n" "QDateEdit:on, QDateTimeEdit:on {\n" " selection-background-color: #1464A0;\n" "}\n" "\n" "QDateEdit::drop-down, QDateTimeEdit::drop-down {\n" " subcontrol-origin: padding;\n" " subcontrol-position: top right;\n" " width: 12px;\n" " border-left: 1px solid #32414B;\n" "}\n" "\n" "QDateEdit::down-arrow, QDateTimeEdit::down-arrow {\n" " image: url(\":/qss_icons/rc/arrow_down_disabled.png\");\n" " height: 8px;\n" " width: 8px;\n" "}\n" "\n" "QDateEdit::down-arrow:on, QDateEdit::down-arrow:hover, QDateEdit::down-arrow:focus, QDateTimeEdit::down-arrow:on, QDateTimeEdit::down-arrow:hover, QDateTimeEdit::down-arrow:focus {\n" " image: url(\":/qss_icons/rc/arrow_down.png\");\n" "}\n" "\n" "QDateEdit QAbstractItemView, QDateTimeEdit QAbstractItemView {\n" " background-color: #19232D;\n" " border-radius: 4px;\n" " border: 1px solid #32414B;\n" " selection-background-color: #1464A0;\n" "}\n" "\n" "/* QAbstractView ----------------------------------------------------------\n" "\n" "--------------------------------------------------------------------------- */\n" "QAbstractView:hover {\n" " border: 1px solid #148CD2;\n" " color: #F0F0F0;\n" "}\n" "\n" "QAbstractView:selected {\n" " background: #1464A0;\n" " color: #32414B;\n" "}\n" "\n" "/* PlotWidget -------------------------------------------------------------\n" "\n" "--------------------------------------------------------------------------- */\n" "PlotWidget {\n" " /* Fix cut labels in plots #134 */\n" " padding: 0px;\n" "}\n" "") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_3.setGeometry(QtCore.QRect(10, 10, 88, 41)) font = QtGui.QFont() font.setPointSize(10) self.pushButton_3.setFont(font) self.pushButton_3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.pushButton_3.setText("") icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(":/icons/icons/home.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_3.setIcon(icon1) self.pushButton_3.setIconSize(QtCore.QSize(65, 60)) self.pushButton_3.setFlat(True) self.pushButton_3.setObjectName("pushButton_3") self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_4.setGeometry(QtCore.QRect(10, 60, 88, 41)) font = QtGui.QFont() font.setPointSize(10) self.pushButton_4.setFont(font) self.pushButton_4.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.pushButton_4.setText("") icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(":/icons/icons/folder.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_4.setIcon(icon2) self.pushButton_4.setIconSize(QtCore.QSize(35, 35)) self.pushButton_4.setFlat(True) self.pushButton_4.setObjectName("pushButton_4") self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_5.setGeometry(QtCore.QRect(10, 110, 88, 41)) font = QtGui.QFont() font.setPointSize(10) self.pushButton_5.setFont(font) self.pushButton_5.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.pushButton_5.setText("") icon3 = QtGui.QIcon() icon3.addPixmap(QtGui.QPixmap(":/icons/icons/001-youtube.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_5.setIcon(icon3) self.pushButton_5.setIconSize(QtCore.QSize(40, 40)) self.pushButton_5.setFlat(True) self.pushButton_5.setObjectName("pushButton_5") self.tabWidget = QtWidgets.QTabWidget(self.centralwidget) self.tabWidget.setGeometry(QtCore.QRect(100, 0, 511, 261)) self.tabWidget.setObjectName("tabWidget") self.tab = QtWidgets.QWidget() self.tab.setObjectName("tab") self.widget_2 = QtWidgets.QWidget(self.tab) self.widget_2.setGeometry(QtCore.QRect(-10, 10, 501, 191)) self.widget_2.setObjectName("widget_2") self.label_9 = QtWidgets.QLabel(self.widget_2) self.label_9.setGeometry(QtCore.QRect(380, 0, 131, 61)) font = QtGui.QFont() font.setPointSize(10) self.label_9.setFont(font) self.label_9.setAlignment(QtCore.Qt.AlignCenter) self.label_9.setWordWrap(True) self.label_9.setObjectName("label_9") self.label_14 = QtWidgets.QLabel(self.widget_2) self.label_14.setGeometry(QtCore.QRect(380, 60, 131, 41)) font = QtGui.QFont() font.setPointSize(8) self.label_14.setFont(font) self.label_14.setAlignment(QtCore.Qt.AlignCenter) self.label_14.setWordWrap(True) self.label_14.setObjectName("label_14") self.groupBox_3 = QtWidgets.QGroupBox(self.widget_2) self.groupBox_3.setGeometry(QtCore.QRect(20, 10, 111, 181)) self.groupBox_3.setTitle("") self.groupBox_3.setObjectName("groupBox_3") self.label_23 = QtWidgets.QLabel(self.groupBox_3) self.label_23.setGeometry(QtCore.QRect(10, 30, 91, 31)) self.label_23.setAlignment(QtCore.Qt.AlignCenter) self.label_23.setObjectName("label_23") self.label_32 = QtWidgets.QLabel(self.groupBox_3) self.label_32.setGeometry(QtCore.QRect(30, 60, 51, 41)) self.label_32.setText("") self.label_32.setPixmap(QtGui.QPixmap(":/icons/icons/folder.png")) self.label_32.setScaledContents(True) self.label_32.setAlignment(QtCore.Qt.AlignCenter) self.label_32.setOpenExternalLinks(True) self.label_32.setObjectName("label_32") self.label_34 = QtWidgets.QLabel(self.groupBox_3) self.label_34.setGeometry(QtCore.QRect(20, 110, 70, 51)) self.label_34.setText("") self.label_34.setPixmap(QtGui.QPixmap(":/icons/icons/brosser.png")) self.label_34.setScaledContents(True) self.label_34.setAlignment(QtCore.Qt.AlignCenter) self.label_34.setOpenExternalLinks(True) self.label_34.setObjectName("label_34") self.groupBox_4 = QtWidgets.QGroupBox(self.widget_2) self.groupBox_4.setGeometry(QtCore.QRect(140, 10, 121, 131)) self.groupBox_4.setTitle("") self.groupBox_4.setObjectName("groupBox_4") self.label_25 = QtWidgets.QLabel(self.groupBox_4) self.label_25.setGeometry(QtCore.QRect(20, 20, 81, 51)) self.label_25.setAlignment(QtCore.Qt.AlignCenter) self.label_25.setWordWrap(True) self.label_25.setObjectName("label_25") self.label_26 = QtWidgets.QLabel(self.groupBox_4) self.label_26.setGeometry(QtCore.QRect(20, 70, 81, 51)) self.label_26.setText("") self.label_26.setPixmap(QtGui.QPixmap(":/icons/icons/001-youtube.png")) self.label_26.setScaledContents(True) self.label_26.setAlignment(QtCore.Qt.AlignCenter) self.label_26.setOpenExternalLinks(True) self.label_26.setObjectName("label_26") self.label_27 = QtWidgets.QLabel(self.widget_2) self.label_27.setGeometry(QtCore.QRect(270, 30, 111, 141)) self.label_27.setText("") self.label_27.setPixmap(QtGui.QPixmap(":/icons/icons/boy-2027615_1280.png")) self.label_27.setScaledContents(True) self.label_27.setAlignment(QtCore.Qt.AlignCenter) self.label_27.setOpenExternalLinks(True) self.label_27.setObjectName("label_27") self.label_28 = QtWidgets.QLabel(self.widget_2) self.label_28.setGeometry(QtCore.QRect(410, 110, 71, 61)) self.label_28.setText("") self.label_28.setPixmap(QtGui.QPixmap(":/icons/icons/badge.png")) self.label_28.setScaledContents(True) self.label_28.setAlignment(QtCore.Qt.AlignCenter) self.label_28.setOpenExternalLinks(True) self.label_28.setObjectName("label_28") self.label_33 = QtWidgets.QLabel(self.widget_2) self.label_33.setGeometry(QtCore.QRect(140, 150, 121, 41)) self.label_33.setText("") self.label_33.setPixmap(QtGui.QPixmap(":/icons/icons/donload2.png")) self.label_33.setScaledContents(True) self.label_33.setAlignment(QtCore.Qt.AlignCenter) self.label_33.setOpenExternalLinks(True) self.label_33.setObjectName("label_33") self.tabWidget.addTab(self.tab, "") self.tab_2 = QtWidgets.QWidget() self.tab_2.setObjectName("tab_2") self.widget = QtWidgets.QWidget(self.tab_2) self.widget.setGeometry(QtCore.QRect(0, 20, 511, 201)) self.widget.setObjectName("widget") self.label_3 = QtWidgets.QLabel(self.widget) self.label_3.setGeometry(QtCore.QRect(10, 110, 51, 21)) self.label_3.setObjectName("label_3") self.lineEdit_2 = QtWidgets.QLineEdit(self.widget) self.lineEdit_2.setGeometry(QtCore.QRect(90, 70, 311, 31)) self.lineEdit_2.setText("") self.lineEdit_2.setObjectName("lineEdit_2") self.pushButton = QtWidgets.QPushButton(self.widget) self.pushButton.setGeometry(QtCore.QRect(210, 150, 88, 31)) icon4 = QtGui.QIcon() icon4.addPixmap(QtGui.QPixmap(":/icons/icons/download-icon-6.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton.setIcon(icon4) self.pushButton.setIconSize(QtCore.QSize(30, 20)) self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.widget) self.pushButton_2.setGeometry(QtCore.QRect(410, 70, 88, 31)) icon5 = QtGui.QIcon() icon5.addPixmap(QtGui.QPixmap(":/icons/icons/loupe.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_2.setIcon(icon5) self.pushButton_2.setIconSize(QtCore.QSize(20, 20)) self.pushButton_2.setObjectName("pushButton_2") self.lineEdit = QtWidgets.QLineEdit(self.widget) self.lineEdit.setGeometry(QtCore.QRect(90, 30, 411, 31)) self.lineEdit.setObjectName("lineEdit") self.label_2 = QtWidgets.QLabel(self.widget) self.label_2.setGeometry(QtCore.QRect(0, 70, 81, 21)) self.label_2.setObjectName("label_2") self.progressBar = QtWidgets.QProgressBar(self.widget) self.progressBar.setGeometry(QtCore.QRect(90, 110, 411, 23)) self.progressBar.setProperty("value", 0) self.progressBar.setObjectName("progressBar") self.label = QtWidgets.QLabel(self.widget) self.label.setGeometry(QtCore.QRect(0, 30, 81, 21)) self.label.setObjectName("label") self.label_29 = QtWidgets.QLabel(self.widget) self.label_29.setGeometry(QtCore.QRect(210, 0, 111, 16)) font = QtGui.QFont() font.setFamily("MS Serif") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_29.setFont(font) self.label_29.setObjectName("label_29") self.tabWidget.addTab(self.tab_2, "") self.tab_3 = QtWidgets.QWidget() self.tab_3.setObjectName("tab_3") self.widget_3 = QtWidgets.QWidget(self.tab_3) self.widget_3.setGeometry(QtCore.QRect(0, 10, 501, 221)) self.widget_3.setObjectName("widget_3") self.label_6 = QtWidgets.QLabel(self.widget_3) self.label_6.setGeometry(QtCore.QRect(10, 150, 51, 21)) self.label_6.setObjectName("label_6") self.lineEdit_3 = QtWidgets.QLineEdit(self.widget_3) self.lineEdit_3.setGeometry(QtCore.QRect(90, 70, 311, 31)) self.lineEdit_3.setObjectName("lineEdit_3") self.pushButton_6 = QtWidgets.QPushButton(self.widget_3) self.pushButton_6.setGeometry(QtCore.QRect(210, 190, 88, 31)) icon6 = QtGui.QIcon() icon6.addPixmap(QtGui.QPixmap(":/icons/icons/download2.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_6.setIcon(icon6) self.pushButton_6.setIconSize(QtCore.QSize(30, 20)) self.pushButton_6.setObjectName("pushButton_6") self.pushButton_7 = QtWidgets.QPushButton(self.widget_3) self.pushButton_7.setGeometry(QtCore.QRect(410, 70, 88, 31)) self.pushButton_7.setIcon(icon5) self.pushButton_7.setIconSize(QtCore.QSize(20, 20)) self.pushButton_7.setObjectName("pushButton_7") self.lineEdit_4 = QtWidgets.QLineEdit(self.widget_3) self.lineEdit_4.setGeometry(QtCore.QRect(90, 30, 311, 31)) self.lineEdit_4.setObjectName("lineEdit_4") self.label_7 = QtWidgets.QLabel(self.widget_3) self.label_7.setGeometry(QtCore.QRect(0, 70, 81, 21)) self.label_7.setObjectName("label_7") self.progressBar_2 = QtWidgets.QProgressBar(self.widget_3) self.progressBar_2.setGeometry(QtCore.QRect(90, 150, 411, 23)) self.progressBar_2.setProperty("value", 0) self.progressBar_2.setObjectName("progressBar_2") self.label_8 = QtWidgets.QLabel(self.widget_3) self.label_8.setGeometry(QtCore.QRect(0, 30, 81, 21)) self.label_8.setObjectName("label_8") self.pushButton_8 = QtWidgets.QPushButton(self.widget_3) self.pushButton_8.setGeometry(QtCore.QRect(410, 30, 88, 31)) font = QtGui.QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.pushButton_8.setFont(font) self.pushButton_8.setObjectName("pushButton_8") self.label_20 = QtWidgets.QLabel(self.widget_3) self.label_20.setGeometry(QtCore.QRect(170, 0, 171, 16)) font = QtGui.QFont() font.setFamily("MS Serif") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_20.setFont(font) self.label_20.setObjectName("label_20") self.label_31 = QtWidgets.QLabel(self.widget_3) self.label_31.setGeometry(QtCore.QRect(10, 110, 61, 31)) self.label_31.setWordWrap(True) self.label_31.setObjectName("label_31") self.textEdit_2 = QtWidgets.QTextEdit(self.widget_3) self.textEdit_2.setGeometry(QtCore.QRect(90, 110, 411, 31)) self.textEdit_2.setObjectName("textEdit_2") self.tabWidget.addTab(self.tab_3, "") self.tab_7 = QtWidgets.QWidget() self.tab_7.setObjectName("tab_7") self.widget_7 = QtWidgets.QWidget(self.tab_7) self.widget_7.setGeometry(QtCore.QRect(0, 10, 521, 221)) self.widget_7.setObjectName("widget_7") self.label_17 = QtWidgets.QLabel(self.widget_7) self.label_17.setGeometry(QtCore.QRect(10, 150, 51, 21)) self.label_17.setObjectName("label_17") self.lineEdit_9 = QtWidgets.QLineEdit(self.widget_7) self.lineEdit_9.setGeometry(QtCore.QRect(90, 70, 311, 31)) self.lineEdit_9.setObjectName("lineEdit_9") self.pushButton_12 = QtWidgets.QPushButton(self.widget_7) self.pushButton_12.setGeometry(QtCore.QRect(210, 190, 88, 31)) icon7 = QtGui.QIcon() icon7.addPixmap(QtGui.QPixmap(":/icons/icons/home_download.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_12.setIcon(icon7) self.pushButton_12.setIconSize(QtCore.QSize(30, 20)) self.pushButton_12.setObjectName("pushButton_12") self.pushButton_13 = QtWidgets.QPushButton(self.widget_7) self.pushButton_13.setGeometry(QtCore.QRect(410, 70, 88, 31)) self.pushButton_13.setIcon(icon5) self.pushButton_13.setIconSize(QtCore.QSize(20, 20)) self.pushButton_13.setObjectName("pushButton_13") self.lineEdit_10 = QtWidgets.QLineEdit(self.widget_7) self.lineEdit_10.setGeometry(QtCore.QRect(90, 30, 311, 31)) self.lineEdit_10.setObjectName("lineEdit_10") self.label_18 = QtWidgets.QLabel(self.widget_7) self.label_18.setGeometry(QtCore.QRect(0, 70, 81, 21)) self.label_18.setObjectName("label_18") self.progressBar_5 = QtWidgets.QProgressBar(self.widget_7) self.progressBar_5.setGeometry(QtCore.QRect(90, 150, 411, 23)) self.progressBar_5.setProperty("value", 0) self.progressBar_5.setObjectName("progressBar_5") self.label_19 = QtWidgets.QLabel(self.widget_7) self.label_19.setGeometry(QtCore.QRect(0, 30, 81, 21)) self.label_19.setObjectName("label_19") self.label_22 = QtWidgets.QLabel(self.widget_7) self.label_22.setGeometry(QtCore.QRect(210, 0, 121, 16)) font = QtGui.QFont() font.setFamily("MS Serif") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.label_22.setFont(font) self.label_22.setObjectName("label_22") self.textEdit = QtWidgets.QTextEdit(self.widget_7) self.textEdit.setGeometry(QtCore.QRect(90, 110, 411, 31)) self.textEdit.setObjectName("textEdit") self.label_30 = QtWidgets.QLabel(self.widget_7) self.label_30.setGeometry(QtCore.QRect(10, 110, 61, 31)) self.label_30.setWordWrap(True) self.label_30.setObjectName("label_30") self.pushButton_9 = QtWidgets.QPushButton(self.widget_7) self.pushButton_9.setGeometry(QtCore.QRect(410, 30, 88, 31)) font = QtGui.QFont() font.setPointSize(10) font.setBold(True) font.setWeight(75) self.pushButton_9.setFont(font) self.pushButton_9.setObjectName("pushButton_9") self.tabWidget.addTab(self.tab_7, "") self.tab_4 = QtWidgets.QWidget() self.tab_4.setObjectName("tab_4") self.progressBar_3 = QtWidgets.QProgressBar(self.tab_4) self.progressBar_3.setGeometry(QtCore.QRect(50, 110, 421, 31)) self.progressBar_3.setProperty("value", 10) self.progressBar_3.setObjectName("progressBar_3") self.label_4 = QtWidgets.QLabel(self.tab_4) self.label_4.setGeometry(QtCore.QRect(100, 70, 311, 31)) self.label_4.setObjectName("label_4") self.tabWidget.addTab(self.tab_4, "") self.pushButton_14 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_14.setGeometry(QtCore.QRect(10, 160, 88, 41)) font = QtGui.QFont() font.setPointSize(10) self.pushButton_14.setFont(font) self.pushButton_14.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.pushButton_14.setText("") icon8 = QtGui.QIcon() icon8.addPixmap(QtGui.QPixmap(":/icons/icons/playlist.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_14.setIcon(icon8) self.pushButton_14.setIconSize(QtCore.QSize(40, 30)) self.pushButton_14.setObjectName("pushButton_14") self.pushButton_10 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_10.setEnabled(True) self.pushButton_10.setGeometry(QtCore.QRect(10, 210, 88, 41)) font = QtGui.QFont() font.setPointSize(8) self.pushButton_10.setFont(font) self.pushButton_10.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.pushButton_10.setStyleSheet("selection-color: rgb(0, 0, 255);") self.pushButton_10.setText("") icon9 = QtGui.QIcon() icon9.addPixmap(QtGui.QPixmap(":/icons/icons/folder_browse-512.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_10.setIcon(icon9) self.pushButton_10.setIconSize(QtCore.QSize(40, 35)) self.pushButton_10.setObjectName("pushButton_10") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 614, 30)) self.menubar.setObjectName("menubar") self.menuFile = QtWidgets.QMenu(self.menubar) self.menuFile.setObjectName("menuFile") self.menuClose = QtWidgets.QMenu(self.menuFile) self.menuClose.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) icon10 = QtGui.QIcon() icon10.addPixmap(QtGui.QPixmap(".\\icons/index.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.menuClose.setIcon(icon10) self.menuClose.setObjectName("menuClose") self.menuEdit = QtWidgets.QMenu(self.menubar) self.menuEdit.setObjectName("menuEdit") self.menuView = QtWidgets.QMenu(self.menubar) self.menuView.setObjectName("menuView") self.menuAbout = QtWidgets.QMenu(self.menubar) self.menuAbout.setObjectName("menuAbout") self.menuDesigned_by_Ahmed_Elsheikh = QtWidgets.QMenu(self.menuAbout) self.menuDesigned_by_Ahmed_Elsheikh.setObjectName("menuDesigned_by_Ahmed_Elsheikh") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.actionoptions = QtWidgets.QAction(MainWindow) self.actionoptions.setObjectName("actionoptions") self.actionclose = QtWidgets.QAction(MainWindow) self.actionclose.setObjectName("actionclose") self.menuClose.addSeparator() self.menuFile.addAction(self.menuClose.menuAction()) self.menuDesigned_by_Ahmed_Elsheikh.addSeparator() self.menuAbout.addAction(self.menuDesigned_by_Ahmed_Elsheikh.menuAction()) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuEdit.menuAction()) self.menubar.addAction(self.menuView.menuAction()) self.menubar.addAction(self.menuAbout.menuAction()) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Joud Download Manager")) self.label_9.setText(_translate("MainWindow", "Welcome To Joud Download Manager Version 2.0")) self.label_14.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" color:#ff0000;\">Designed By</span></p><p><span style=\" color:#ff0000;\">Ahmed Elsheikh</span></p></body></html>")) self.groupBox_3.setWhatsThis(_translate("MainWindow", "<html><head/><body><p><br/></p></body></html>")) self.label_23.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:10pt;\">Download Files</span></p></body></html>")) self.label_25.setText(_translate("MainWindow", "Download Youtube Video")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Tab 1")) self.label_3.setText(_translate("MainWindow", "Progress")) self.lineEdit_2.setPlaceholderText(_translate("MainWindow", "Browse to Select Location")) self.pushButton.setText(_translate("MainWindow", "Download")) self.pushButton.setToolTip("click to download") self.pushButton_2.setText(_translate("MainWindow", "Browse")) self.lineEdit.setPlaceholderText(_translate("MainWindow", "Past The URL here ...")) self.label_2.setText(_translate("MainWindow", "Save Location")) self.label.setText(_translate("MainWindow", "Enter The URL")) self.label_29.setText(_translate("MainWindow", "Download files")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Tab 2")) self.label_6.setText(_translate("MainWindow", "Progress")) self.lineEdit_3.setPlaceholderText(_translate("MainWindow", "Browse to Select Location")) self.pushButton_6.setText(_translate("MainWindow", "Download")) self.pushButton_7.setText(_translate("MainWindow", "Browse")) self.lineEdit_4.setPlaceholderText(_translate("MainWindow", "Past The URL here ...")) self.label_7.setText(_translate("MainWindow", "Save Location")) self.label_8.setText(_translate("MainWindow", "Enter The URL")) self.pushButton_8.setText(_translate("MainWindow", "Find-Data")) self.label_20.setText(_translate("MainWindow", "Youtube Video OR audio")) self.label_31.setText(_translate("MainWindow", "Video title")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Page")) self.label_17.setText(_translate("MainWindow", "Progress")) self.lineEdit_9.setPlaceholderText(_translate("MainWindow", "Browse to Select Location")) self.pushButton_12.setText(_translate("MainWindow", "Download")) self.pushButton_13.setText(_translate("MainWindow", "Browse")) self.lineEdit_10.setPlaceholderText(_translate("MainWindow", "Past the URL here ...")) self.label_18.setText(_translate("MainWindow", "Save Location")) self.label_19.setText(_translate("MainWindow", "Enter The URL")) self.label_22.setText(_translate("MainWindow", "Youtube Playlist")) self.label_30.setText(_translate("MainWindow", "Playlist title")) self.pushButton_9.setText(_translate("MainWindow", "Find-Data")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_7), _translate("MainWindow", "Page")) self.label_4.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:10pt; font-weight:600;\">This Section Is Still Under Development !!</span></p></body></html>")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), _translate("MainWindow", "Page")) self.menuFile.setTitle(_translate("MainWindow", "File")) self.menuClose.setStatusTip(_translate("MainWindow", "close the app.")) self.menuClose.setTitle(_translate("MainWindow", "Close")) self.menuEdit.setTitle(_translate("MainWindow", "Edit")) self.menuView.setTitle(_translate("MainWindow", "View")) self.menuAbout.setTitle(_translate("MainWindow", "About")) self.menuDesigned_by_Ahmed_Elsheikh.setTitle(_translate("MainWindow", "Designed by Ahmed Elsheikh")) self.actionoptions.setText(_translate("MainWindow", "options")) self.actionclose.setText(_translate("MainWindow", "close")) import res_rc
[ "Ahmedhassaninaun@gmail.com" ]
Ahmedhassaninaun@gmail.com
41dfdff35f1bc808e0a824c83762f84a235ac6d7
baaa3a4d6cc9f9e465726ba11647ca9a3e431a7e
/IN1000/Obligatorisk innlevering 7/spillebrett.py
10630ac1b306e3f310bd4b01509f267bdd42c866
[]
no_license
MehCheniti/Python
671d430868e1b8eeafabd7ecb1cf6684ab5c6858
1e1dc38dc874e03cb248664ff48f3cb2d497c6e5
refs/heads/master
2022-05-28T03:05:31.336202
2022-03-11T19:55:46
2022-03-11T19:55:46
206,413,523
0
0
null
null
null
null
UTF-8
Python
false
false
3,974
py
from random import randint from celle import Celle class Spillebrett: """Dette er en klasse som beskriver et todimensjonalt brett som inneholder celler. Den skal også oppdatere celler som skal endre status.""" def __init__(self, rader, kolonner): self._rader = rader self._kolonner = kolonner self._rutenett = [] # Her lager jeg en nøstet for-løkke for å fylle self._rutenett med # Celle-objekter. for i in range(self._rader): rad = [] for j in range(self._kolonner): rad.append(Celle()) self._rutenett.append(rad) self._generasjonsnummer = 0 self.generer() def tegnBrett(self): # Her lager jeg en nøstet for-løkke for å kunne skrive ut hvert element # i self._rutenett. for i in self._rutenett: for j in i: print(j.hentStatusTegn(), end = " | ") # Her bruker ganger jeg ---- med antall kolonner for å det til å se # fint ut. print("\n" + "----"*self._kolonner) def oppdatering(self): dødTilLevende = [] levendeTilDød = [] for i in range(len(self._rutenett)): for j in range(len(self._rutenett[i])): # Her lager jeg en liste for verdiene finnNabo returnerer. naboliste = self.finnNabo(i, j) # Her sjekker jeg både om cellen har 2 eller 3 levende naboer # og om cellen er levende. if (len(naboliste) == 2 or len(naboliste) == 3 ) and self._rutenett[i][j].erLevende(): dødTilLevende.append(self._rutenett[i][j]) # Her sjekker jeg både om cellen ikke er levende og om den har # 3 levende naboer. elif not self._rutenett[i][j].erLevende() and len(naboliste ) == 3: dødTilLevende.append(self._rutenett[i][j]) # Her sjekker jeg hvis cellen skal fortsette å være død eller # drepes etter oppdateringen. else: levendeTilDød.append(self._rutenett[i][j]) # Her setter jeg objektene som skal leve til "levende". for i in dødTilLevende: i.settLevende() #Her setter jeg objektene som skal dø til "død" for i in levendeTilDød: i.settDoed() self._generasjonsnummer += 1 def finnAntallLevende(self): teller = 0 # Her bruker jeg en nøstet for-løkke for å finne ut hvor mange celler # er levende. for i in range(self._rader): for j in range(self._kolonner): if self._rutenett[i][j].erLevende() == True: teller += 1 return teller def generer(self): for i in range(self._rader): for j in range(self._kolonner): rand = randint(0,3) if rand == 3: self._rutenett[i][j].settLevende() def finnNabo (self, rad, kolonne): naboliste = [] for i in range (-1, 2): for j in range (-1, 2): naboRad = rad + i naboKolonne = kolonne + j if (naboRad == rad and naboKolonne == kolonne) != True: if (naboRad < 0 or naboKolonne < 0 or naboRad > self._rader-1 or naboKolonne > self._kolonner-1) != True: # Her endrer jeg på metoden slik at den returnerer en # liste kun av levende naboer. if self._rutenett[naboRad][naboKolonne].erLevende(): naboliste.append(self._rutenett[naboRad] [naboKolonne]) return naboliste # Her definerer jeg en metode som returnerer generasjonsnummeret. def generasjonsnummer(self): return self._generasjonsnummer
[ "mehdiwx91@hotmail.com" ]
mehdiwx91@hotmail.com
785fdd86b44a7160a436e651f6b5f7d38e8a7e52
4f5f40a874a9ae17d25cb2fe8cac5fba327b5265
/tests/conf_zephyr_run_qemu.py
e683bc210b8ce4e89d3e1b4495bb74d9dbf06c3b
[ "Apache-2.0" ]
permissive
dickeylim/tcf
4f580b507d381542f22c0899e4922add13f76926
4ecda0e1983fed2cb932242395a5be4754349534
refs/heads/master
2020-06-25T16:30:34.613115
2019-08-27T18:39:25
2019-08-27T18:39:25
199,366,410
0
0
Apache-2.0
2019-07-29T02:48:55
2019-07-29T02:48:54
null
UTF-8
Python
false
false
434
py
#! /usr/bin/python2 # # Copyright (c) 2017 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 # ttbl.config.target_add(tt_qemu_zephyr("qemu-01", [ "x86" ]), target_type = "qemu-x86") ttbl.config.target_add(tt_qemu_zephyr("qemu-02", [ "x86" ]), target_type = "qemu-x86") ttbl.config.target_add(tt_qemu_zephyr("qemu-03", [ "x86" ]), target_type = "qemu-x86")
[ "inaky.perez-gonzalez@intel.com" ]
inaky.perez-gonzalez@intel.com
3513cfbf809ce88471e833d75ea30155f8ab6609
1d7256a89de883ddd45a7731d309aae404491035
/information_boards/old_codes/c_individual_analysis/c2_summary/__c2_s3_driver_productivity_economic_profit.py
7e13814a869c481bc3257381a541f694cb18d25c
[]
no_license
M20190649/taxi_projects
a559329366fe2357b826909543a54b12b6d98301
b910e2308d4725e88fb00714e489b1291cfeb215
refs/heads/master
2021-06-17T15:14:55.849298
2017-06-01T10:17:23
2017-06-01T10:17:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,929
py
import __init__ # @UnresolvedImport # @UnusedImport # from __init__ import SEC3600, CENT from c_individual_analysis.__init__ import ftd_gen_prod_db_for_ap, ftd_ap_prod_eco_prof_db from c_individual_analysis.__init__ import ftd_gen_prod_db_for_ns, ftd_ns_prod_eco_prof_db from __init__ import dfs from __init__ import Y09_GEN, Y10_GEN, Y09_PIAP, Y10_PIAP, Y09_POAP, Y10_POAP, Y09_PINS, Y10_PINS, Y09_PONS, Y10_PONS # from taxi_common.file_handling_functions import remove_file, save_pickle_file # def run(): for path in [ftd_gen_prod_db_for_ap, ftd_gen_prod_db_for_ns, ftd_ap_prod_eco_prof_db, ftd_ns_prod_eco_prof_db]: remove_file(path) # ap_productivity_economical_profit() ns_productivity_economical_profit() def general_productivities(full_drivers): drivers_hourly_producities = [] for i in [Y09_GEN, Y10_GEN]: df = dfs[i] df = df[((df['prod'] - df['prod'].mean()) / df['prod'].std()).abs() < 3] df = df[df['did'].isin(full_drivers)] df_gb = df.groupby(['did']) drivers_avg_productivities = df_gb.mean()['prod'].to_frame('avg_prod').reset_index() drivers_hourly_producities.append( {did : total_prod * SEC3600 / CENT for did, total_prod in drivers_avg_productivities.values}) return drivers_hourly_producities def ap_productivity_economical_profit(): # # drivers who operate taxi in both years # df = dfs[Y09_PIAP] df = df[((df['prod'] - df['prod'].mean()) / df['prod'].std()).abs() < 3] df = df[((df['eco-profit'] - df['eco-profit'].mean()) / df['eco-profit'].std()).abs() < 3] ap_full_drivers = set(df['did']) for i in [Y10_PIAP, Y09_POAP, Y10_POAP]: df = dfs[i] df = df[((df['prod'] - df['prod'].mean()) / df['prod'].std()).abs() < 3] df = df[((df['eco-profit'] - df['eco-profit'].mean()) / df['eco-profit'].std()).abs() < 3] ap_full_drivers = ap_full_drivers.intersection(set(df['did'])) # save_pickle_file(ftd_gen_prod_db_for_ap, general_productivities(ap_full_drivers)) save_pickle_file(ftd_ap_prod_eco_prof_db, get_driver_average(ap_full_drivers, [Y09_PIAP, Y10_PIAP, Y09_POAP, Y10_POAP])) def ns_productivity_economical_profit(): # # drivers who operate taxi in both years # df = dfs[Y09_PINS] df = df[((df['prod'] - df['prod'].mean()) / df['prod'].std()).abs() < 3] df = df[((df['eco-profit'] - df['eco-profit'].mean()) / df['eco-profit'].std()).abs() < 3] ns_full_drivers = set(df['did']) for i in [Y10_PINS, Y09_PONS, Y10_PONS]: df = dfs[i] df = df[((df['prod'] - df['prod'].mean()) / df['prod'].std()).abs() < 3] df = df[((df['eco-profit'] - df['eco-profit'].mean()) / df['eco-profit'].std()).abs() < 3] ns_full_drivers = ns_full_drivers.intersection(set(df['did'])) # save_pickle_file(ftd_gen_prod_db_for_ns, general_productivities(ns_full_drivers)) save_pickle_file(ftd_ns_prod_eco_prof_db, get_driver_average(ns_full_drivers, [Y09_PINS, Y10_PINS, Y09_PONS, Y10_PONS])) def get_driver_average(full_drivers, df_indices): # # filter our part-time drivers # and save each drivers' productivities and economical profits # drivers_prod_eco_prof = [] for i in df_indices: df = dfs[i] df = df[df['did'].isin(full_drivers)] gb_df = df.groupby(['did']) drivers_ap_prod = gb_df.mean()['prod'].to_frame('avg_prod').reset_index() drivers_ap_prod_hour = {did : ap_prod * SEC3600 / CENT for did, ap_prod in drivers_ap_prod.values} # drivers_eco_prof = gb_df.mean()['eco-profit'].to_frame('avg_eco_pro').reset_index() drivers_eco_prof_month = {did : eco_pro / CENT for did, eco_pro in drivers_eco_prof.values} # drivers_prod_eco_prof.append([drivers_ap_prod_hour, drivers_eco_prof_month]) return drivers_prod_eco_prof if __name__ == '__main__': run()
[ "jerryhan88@gmail.com" ]
jerryhan88@gmail.com
5bd7459e82b82c92a904f9a7bc161ed705b59c9c
c98195975cfacacfe81fa31e37883a9a54a294e8
/asn_server/Demos/system/resourceIntensive/cov1svd.py
304fd7a46a9e93b7f6d537e6aa183798ed992b09
[ "Apache-2.0" ]
permissive
konradhorbach/MARVELO
d51111a248a1701fac6f9afaecd24c66532f9b1c
aa81d855cc42ec24459c5033831744686c70d315
refs/heads/master
2022-12-12T12:07:14.636765
2020-09-11T14:00:07
2020-09-11T14:00:07
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,465
py
#!/usr/bin/env python import os,sys import argparse from scipy import linalg as LA import numpy as np from scipy.io import wavfile #%---------------- Start Additional Resource intesive method import threading, time, sys runTime = 5 fileName = "cov1SVD: " def r_intensive_func (fileName,itime): start = time.time() while time.time()-start <itime: v = int ((time.time()-start)/itime*100) sys.stdout.write("\r%s%%" % fileName+ str(v) ) sys.stdout.flush() 100**100 print "\nDone" thread = threading.Thread(target=r_intensive_func, args=[fileName,runTime]) print "Start\n" thread.start() #%---------------- End Additional Resource intesive method def parse_arguments(): parser = argparse.ArgumentParser(description='arguments') parser.add_argument("--file", "-f", default="") parser.add_argument("--inputs", "-i", action="append") parser.add_argument("--outputs", "-o", action="append") parser.add_argument("--logfiles", "-l", default=["/home/asn/asn_daemon/logfiles/dummy.log"], action="append") return parser.parse_args() args = parse_arguments() PACKETSIZE = 4096 #send data in 4KB packets (2KB or 1024 samples per channel equals shift amount used in processing blocks!) inputs = [os.fdopen(int(f), 'rb') for f in args.inputs] audio1= np.array([]) audio2= np.array([]) for pcount in range(13): signal1 = np.fromfile(inputs[0], dtype=np.uint8, count=4096) signal2 = np.fromfile(inputs[1], dtype=np.uint8, count=4096) audio1= np.append(audio1,signal1) audio2= np.append(audio2,signal2) audio1 = audio1[:50000] / 255.0 - 0.5 # uint8 takes values from 0 to 255 audio2 = audio2[:50000] / 255.0 - 0.5 # uint8 takes values from 0 to 255 samplingRate = 8000 wavfile.write('/home/asn/asn_daemon/logfiles/rxcov1.wav', samplingRate, audio1[:50000]) wavfile.write('/home/asn/asn_daemon/logfiles/rxcov2.wav', samplingRate, audio2[:50000]) x = [audio1, audio2] cov = np.cov(x) d, E = LA.eigh(cov) D = np.diag(d) pipes = [os.fdopen(int(f), 'wb') for f in args.outputs] pipes[0].write(D) pipes[0].flush() #print E.flags E = E.copy(order='C') #print 'new', E.flags pipes[1].write(E) pipes[1].flush() pipes[2].write(np.array(x).reshape(1,100000)) pipes[2].flush() for pipe in pipes: pipe.close() print 'finished cov1***********************'
[ "hafifi@mail.uni-paderborn.de" ]
hafifi@mail.uni-paderborn.de
c3ae8bfd6efcec69271ffddd04081c8eff824933
8f270db082a7f46ecfe9d68a37ebe8d06e89efb9
/fastaSubset.py
c44fb4d280cb2eed91fb99c10840d899664e3012
[ "Unlicense" ]
permissive
jharman25/phylo_tools
7c1bf7c4b6fb7353db5797e98b302ac8adbd9372
470873a6decd8c9ca6f66308eeb53f7f6627115b
refs/heads/master
2020-07-04T08:42:02.724540
2015-09-15T18:04:38
2015-09-15T18:04:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,644
py
#!/usr/bin/env python __description__ = \ """ Take a subset of the entries in a fasta file where something in the header matches "pattern". -e forces an exact match to everything after >. """ __usage__ = "fastaSubset.py fasta_file pattern OR file_with_patterns [-e]" __author__ = "Michael J. Harms" __date__ = "110604" import sys, re, os class FastaSubsetError(Exception): """ Error class. """ pass def fastaSubset(fasta_file,patterns,collapse=True,exact=False,inverse=False): """ Take a subset of entries in a fasta file according to whether or not the header contains one of the patterns in patterns. If collapse == True, collapse the entire sequence onto a single line. """ compiled_patterns = [re.compile(p) for p in patterns] f = open(fasta_file,'r') out = [] recording = False line = f.readline() while line != "": # If this is a new entry... if line.startswith(">"): # If we've been recording the previous entry, print it out if len(out) != 0: if collapse == True: out = [o.strip() for o in out] out[0] = "%s\n" % out[0] print "".join(out) else: print "".join(out), sys.stdout.flush() out = [] # Now see if this entry is matches one of the patterns recording = False if exact: line_search = "%s\n" % line else: line_search = "%s" % line if not inverse: for p in compiled_patterns: if p.search(line_search) != None: recording = True break else: recording = True for p in compiled_patterns: if p.search(line_search) != None: recording = False break # If we're recording, er, record if recording == True: out.append(line) line = f.readline() # Print the last sequence if len(out) != 0: if collapse == True: out = [o.strip() for o in out] out[0] = "%s\n" % out[0] print "".join(out) else: print "".join(out), f.close() def main(argv=None): """ Main function to parse command line. """ if argv == None: argv = sys.argv[1:] try: fasta_file = argv[0] pattern = argv[1] except IndexError: err = "Incorrect number of arguments!\nUSAGE:\n\n%s\n\n" % __usage__ raise FastaSubsetError(err) # Grab optional "exact match" argument try: if argv[2] == "-e": exact = True else: err = "Argument %s not recognized!\n" % argv[2] raise FastaSubsetError(err) except IndexError: exact = False if os.path.exists(pattern): f = open(pattern,'r') lines = f.readlines() lines = [l.split("#")[0].strip() for l in lines] if exact: patterns = ["%s\n" % l for l in lines if l != ""] else: patterns = [l for l in lines if l != ""] if len(patterns) == 0: err = "Specified pattern file (%s) does not contain any lines!\n" err = "%s" % err raise FastaSubsetError(err) else: patterns = [pattern] fastaSubset(fasta_file,patterns,exact=exact) if __name__ == "__main__": main()
[ "harmsm@gmail.com" ]
harmsm@gmail.com
1abdf9eec3b0ed484e7efc007c9248e115240d3f
69afcab7add5756f00018fa5ff8af2e67665fa6b
/main_menu.py
825059c61f6334e4b04f550fd1abf083f0d4ccfe
[]
no_license
jmcgalliard/Clong
b2333c9bbb80f2fa912a094d205a258c9a308a69
55ac11d1d8ac8827d654a5c5f9aa3f88271a47bb
refs/heads/master
2021-06-20T19:41:26.431392
2017-04-17T22:12:49
2017-04-17T22:12:49
86,214,217
0
0
null
null
null
null
UTF-8
Python
false
false
2,885
py
import pygame import screen import colors import game_fonts import play_game def main_menu(): # MODES # 1 - Main Menu # 2 - Single Player chosen_text = 1 mode = 1 ## GAME LOOP ## done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True keydown = pygame.key.get_pressed() if keydown[pygame.K_DOWN]: if chosen_text < 5: chosen_text += 1 elif chosen_text == 5: chosen_text = 1 if keydown[pygame.K_UP]: if chosen_text > 1: chosen_text -= 1 elif chosen_text == 1: chosen_text = 5 if keydown[pygame.K_RETURN]: if chosen_text == 1: mode = 2 if mode == 1: # Logic goes here single_player_color = colors.GRAY multi_player_color = colors.GRAY high_scores_color = colors.GRAY credits_color = colors.GRAY exit_color = colors.GRAY colors_list = [] colors_list.append(single_player_color) colors_list.append(multi_player_color) if chosen_text == 1: single_player_color = colors.WHITE elif chosen_text == 2: multi_player_color = colors.WHITE elif chosen_text == 4: credits_color = colors.WHITE elif chosen_text == 3: high_scores_color = colors.WHITE elif chosen_text == 5: exit_color = colors.WHITE single_player = game_fonts.game_font.render("Single Player", 20, single_player_color) multi_player = game_fonts.game_font.render("Multiplayer", 20, multi_player_color) high_scores = game_fonts.game_font.render("High Scores", 20, high_scores_color) credits = game_fonts.game_font.render("Credits", 20, credits_color) exit = game_fonts.game_font.render("Exit ", 20, exit_color) # Fill the screen screen.screen.fill(colors.BLACK) # Drawing should go here, before flip and after fill screen.screen.blit(single_player, (100, 100)) screen.screen.blit(multi_player, (100, 150)) screen.screen.blit(high_scores, (100, 200)) screen.screen.blit(credits, (100, 250)) screen.screen.blit(exit, (100, 300)) # Updates contents of entire display pygame.display.flip() elif mode == 2: screen.screen.fill(colors.WHITE) credits = game_fonts.game_font_2.render("SINGLE PLAYER", 20, colors.BLACK) screen.screen.blit(credits, (20,480)) pygame.display.flip() main_menu()
[ "j83001@gmail.com" ]
j83001@gmail.com
c9ca527ad941bf382ae6356b9477118e827b1c7c
803c669ed1c9b3f2f9cb227c3e36b38b9b14064c
/미정리/bj_2178_미로탐색_숏코딩.py
f7a99dd8a9e2af996f3d5c6422be222d578b80f9
[]
no_license
steddybag/Algorithm-and-SP
5052fdaad17f53e43c0bcbbf948ad4a466ebaf04
e828346d8a59187866e6740823a058be5783cc2a
refs/heads/master
2023-04-11T06:29:06.315421
2021-04-23T09:41:08
2021-04-23T09:41:08
357,401,035
0
0
null
null
null
null
UTF-8
Python
false
false
562
py
import sys sys.stdin = open('input.txt','r') n, m = map(int,input().split()) queue = [] dx = [0,-1,1,0] dy = [1,0,0,-1] s = [list(input()) for _ in range(n)] queue = [[0,0]] #어렵게 생각하지 말고 직관적으로 생각할 것 s[0][0] = 1 while queue: a, b = queue[0][0],queue[0][1] queue.pop(0) for i in range(4): x = a+dx[i] y = b+dy[i] if n>x>=0 and m>y>=0 and s[x][y] == '1': queue.append([x,y]) s[x][y] = s[a][b] + 1 #작은 단위에서 늘어난다는 식으로 생각 print(s[n-1][m-1])
[ "dongju695@gmail.com" ]
dongju695@gmail.com
eb99f204e73b205ce9d460b46f43410ac639d478
9afc92049dd679d57743016fcaa9df001394298c
/code/codility/prefix_sum_prefix_sum_passing_cars__.py
6890f5c39d0c1d78d6e5df147cb88cb8437f2493
[ "Apache-2.0" ]
permissive
dinkar1708/coding_interview
b72cf322586a2862637925333ec9098db8f18d88
374d7e3d20350e363ed03a90198a067ef277af30
refs/heads/master
2021-08-22T11:44:14.611053
2021-08-04T14:25:11
2021-08-04T14:25:11
225,569,377
1
2
Apache-2.0
2021-07-20T15:57:55
2019-12-03T08:33:34
Python
UTF-8
Python
false
false
1,056
py
def solution(A): """ Dinakar https://app.codility.com/demo/results/training6SEGRM-7Q2/ Use suffix some - from right side each 1 must be passing zero cars if found.. [0, 1, 0, 1, 1] [3, 3, 2-->must pass previous cars right side of it, 2, 1] ---- """ print(A) len_ar = len(A) suffix_sum = [0] * (len_ar + 1) total = 0 # loop start from end, up to -1 and decrement by 1 for i in range(len_ar - 1, -1, -1): # print(i) suffix_sum[i] = A[i] + suffix_sum[i + 1] print("suffix sum here...") print(suffix_sum) if A[i] == 0: total += suffix_sum[i] print(total) if total > 1000000000: return -1 return total result = solution([0, 1, 0, 1, 1]) print("") print("Solution " + str(result)) """ [0, 1, 0, 1, 1] suffix sum here... [0, 0, 0, 0, 1, 0] suffix sum here... [0, 0, 0, 2, 1, 0] suffix sum here... [0, 0, 2, 2, 1, 0] 2 suffix sum here... [0, 3, 2, 2, 1, 0] suffix sum here... [3, 3, 2, 2, 1, 0] 5 Solution 5 """
[ "dinkar1708@gmail.com" ]
dinkar1708@gmail.com
b444d6609c3eda0faab93df1c871ac76fcbe3bd5
a3cc82b930a669ea8bc7210ce973a3c00b682213
/lib/MapFastq.py
ac672e62f47e3bc3abf715f81db5e867bf75affd
[ "MIT" ]
permissive
tweirick/RNAEditor
289896989d6dfee547541a8fd80905233ec3b92f
16facf3e8743d2837eb97586af86c986cb792011
refs/heads/master
2021-01-21T13:21:50.465755
2017-05-19T20:11:53
2017-05-19T20:11:53
70,837,169
0
0
null
2016-10-13T18:42:29
2016-10-13T18:42:29
null
UTF-8
Python
false
false
17,686
py
#!/usr/bin/python import argparse import os import multiprocessing from Helper import Helper class MapFastq(object): """ Maps a fastQ file to the given genome/ """ def __init__(self, rna_edit_obj): """ Constructor """ self.rnaEdit = rna_edit_obj # Set fastq files and check if the qualities need to be converted. if self.rnaEdit.params.paired is True: fastq_1_is_phred33 = Helper.isPhred33Encoding( self.rnaEdit.fastq_files[0], 1000000, self.rnaEdit.logFile, self.rnaEdit.textField) fastq_2_is_phred33 = Helper.isPhred33Encoding( self.rnaEdit.fastq_files[1], 1000000, self.rnaEdit.logFile, self.rnaEdit.textField) if not fastq_1_is_phred33 or not fastq_2_is_phred33: # Convert to phred33. self.fastqFile1 = Helper.convertPhred64toPhred33( self.rnaEdit.fastq_files[0], self.rnaEdit.params.output + "_1_phred33.fastq", self.rnaEdit.logFile, self.rnaEdit.textField) self.fastqFile2 = Helper.convertPhred64toPhred33( self.rnaEdit.fastq_files[1], self.rnaEdit.params.output + "_2_phred33.fastq", self.rnaEdit.logFile, self.rnaEdit.textField) else: self.fastqFile1 = self.rnaEdit.fastq_files[0] self.fastqFile2 = self.rnaEdit.fastq_files[1] elif not self.rnaEdit.params.paired: # Convert to phred33. fastq_is_phred33 = Helper.isPhred33Encoding( self.rnaEdit.fastq_files[0], 1000000, self.rnaEdit.logFile, self.rnaEdit.textField) if not fastq_is_phred33: self.fastqFile1 = Helper.convertPhred64toPhred33( self.rnaEdit.fastq_files[0], self.rnaEdit.params.output + "_1_phred33.fastq", self.rnaEdit.logFile, self.rnaEdit.textField) else: self.fastqFile = self.rnaEdit.fastq_files[0] def printAttributes(self): Helper.info("*** MAP READS WITH FOLLOWING ATTRIBUTES ***", self.rnaEdit.logFile, self.rnaEdit.textField) if self.rnaEdit.params.paired: Helper.info("\t FastQ-File_1: " + self.fastqFile1, self.rnaEdit.logFile, self.rnaEdit.textField) Helper.info("\t FastQ-File_2: " + self.fastqFile2, self.rnaEdit.logFile, self.rnaEdit.textField) else: Helper.info("\t FastQ-File: " + self.fastqFile, self.rnaEdit.logFile, self.rnaEdit.textField) Helper.info("\t outfilePrefix:" + self.rnaEdit.params.output, self.rnaEdit.logFile, self.rnaEdit.textField) Helper.info("\t refGenome:" + self.rnaEdit.params.refGenome, self.rnaEdit.logFile, self.rnaEdit.textField) Helper.info("\t dbsnp:" + self.rnaEdit.params.dbsnp, self.rnaEdit.logFile, self.rnaEdit.textField) Helper.info("\t sourceDir:" + self.rnaEdit.params.sourceDir, self.rnaEdit.logFile, self.rnaEdit.textField) Helper.info("\t threads:" + self.rnaEdit.params.threads, self.rnaEdit.logFile, self.rnaEdit.textField) Helper.info("\t maxDiff:" + self.rnaEdit.params.maxDiff, self.rnaEdit.logFile, self.rnaEdit.textField) Helper.info("\t seedDiff:" + self.rnaEdit.params.seedDiff, self.rnaEdit.logFile, self.rnaEdit.textField) Helper.info("\t paired:" + str(self.rnaEdit.params.paired), self.rnaEdit.logFile, self.rnaEdit.textField) Helper.info("\t keepTemp:" + str(self.rnaEdit.params.keepTemp), self.rnaEdit.logFile, self.rnaEdit.textField) Helper.info("\t overwrite:" + str(self.rnaEdit.params.overwrite), self.rnaEdit.logFile, self.rnaEdit.textField) Helper.info("", self.rnaEdit.logFile, self.rnaEdit.textField) def startAnalysis(self): recalibrated_bam_file = self.rnaEdit.params.output+".noDup.realigned.recalibrated.bam" if os.path.isfile(recalibrated_bam_file): Helper.info( "* * * [Skipping] Mapping result File already exists * * *", self.rnaEdit.logFile, self.rnaEdit.textField) self.rnaEdit.logFile.flush() return recalibrated_bam_file if self.rnaEdit.params.paired: # For paired end sequencing. # Align first Fastq Reads to the Genome sai_file_1 = self.rnaEdit.params.output+"_1.sai" cmd = [ self.rnaEdit.params.sourceDir+"bwa", "aln", "-t", self.rnaEdit.params.threads, "-n", self.rnaEdit.params.maxDiff, "-k", self.rnaEdit.params.seedDiff, self.rnaEdit.params.refGenome, self.fastqFile1 ] Helper.proceedCommand("Align first Reads with BWA", cmd, self.fastqFile1, sai_file_1, self.rnaEdit) # Align second Fastq Reads to the Genome sai_file_2 = self.rnaEdit.params.output+"_2.sai" cmd = [ self.rnaEdit.params.sourceDir+"bwa", "aln", "-t", self.rnaEdit.params.threads, "-n", self.rnaEdit.params.maxDiff, "-k", self.rnaEdit.params.seedDiff, self.rnaEdit.params.refGenome, self.fastqFile2 ] Helper.proceedCommand("Align second Reads with BWA", cmd, self.fastqFile2, sai_file_2, self.rnaEdit) # Convert sai to sam sam_file = self.rnaEdit.params.output+".sam" cmd = [ self.rnaEdit.params.sourceDir + "bwa", "sampe", "-r", "@RG\tID:bwa\tSM:A\tPL:ILLUMINA\tPU:HiSEQ2000", self.rnaEdit.params.refGenome, sai_file_1, sai_file_2, self.fastqFile1, self.fastqFile2 ] Helper.proceedCommand("convert sai to sam", cmd, sai_file_1, sam_file, self.rnaEdit) else: # For single end sequencing. # Align Fastq Reads to the Genome. sai_file = self.rnaEdit.params.output+".sai" cmd = [ self.rnaEdit.params.sourceDir+"bwa", "aln", "-t", self.rnaEdit.params.threads, "-n", self.rnaEdit.params.maxDiff, "-k", self.rnaEdit.params.seedDiff, self.rnaEdit.params.refGenome, self.fastqFile ] Helper.proceedCommand("Align Reads with BWA", cmd, self.fastqFile, sai_file, self.rnaEdit) # Convert sai to sam. sam_file = self.rnaEdit.params.output+".sam" cmd = [ self.rnaEdit.params.sourceDir + "bwa", "samse", "-r", "@RG\tID:bwa\tSM:A\tPL:ILLUMINA\tPU:HiSEQ2000", self.rnaEdit.params.refGenome, sai_file, self.fastqFile ] Helper.proceedCommand("convert sai to sam", cmd, sai_file, sam_file, self.rnaEdit) # Convert sam to bam. unsorted_bam_file = self.rnaEdit.params.output+".unsorted.bam" bam_file = self.rnaEdit.params.output+".bam" cmd = [self.rnaEdit.params.sourceDir + "samtools", "sort", sam_file, "-o", bam_file] Helper.proceedCommand("Sort Bam File", cmd, sam_file, bam_file, self.rnaEdit) cmd = [self.rnaEdit.params.sourceDir + "samtools", "index", bam_file] Helper.proceedCommand("Index Bam File", cmd, sam_file, bam_file+".bai", self.rnaEdit) # mark PCR duplicates marked_file = self.rnaEdit.params.output+".noDup.bam" cmd = [ "java", "-Xmx16G", "-jar", self.rnaEdit.params.sourceDir + "picard-tools/MarkDuplicates.jar", "INPUT=" + bam_file, "OUTPUT=" + marked_file, "METRICS_FILE="+self.rnaEdit.params.output+".pcr.metrics", "VALIDATION_STRINGENCY=LENIENT", "CREATE_INDEX=true" ] Helper.proceedCommand("Remove PCR duplicates", cmd, bam_file, marked_file, self.rnaEdit) # Identify Target Regions for realignment interval_file = self.rnaEdit.params.output+".indels.intervals" cmd = [ "java", "-Xmx16G", "-jar", self.rnaEdit.params.sourceDir + "GATK/GenomeAnalysisTK.jar", "-nt", self.rnaEdit.params.threads, "-T", "RealignerTargetCreator", "-R", self.rnaEdit.params.refGenome, "-I", marked_file, "-o", interval_file, "-l", "ERROR" ] Helper.proceedCommand("Identify Target Regions for realignment", cmd, bam_file, interval_file, self.rnaEdit) # Proceed with realignment. realigned_file = self.rnaEdit.params.output+".noDup.realigned.bam" cmd = [ "java", "-Xmx16G", "-jar", self.rnaEdit.params.sourceDir + "GATK/GenomeAnalysisTK.jar", "-T", "IndelRealigner", "-R", self.rnaEdit.params.refGenome, "-I", marked_file, "-l", "ERROR", "-targetIntervals", interval_file, "-o", realigned_file ] Helper.proceedCommand("Proceed Realignment", cmd, interval_file, realigned_file, self.rnaEdit) # Find Quality Score recalibration spots. recal_file = self.rnaEdit.params.output+".recalSpots.grp" cmd = [ "java", "-Xmx16G", "-jar", self.rnaEdit.params.sourceDir + "GATK/GenomeAnalysisTK.jar", "-T", "BaseRecalibrator", "-l", "ERROR", "-R", self.rnaEdit.params.refGenome, "-knownSites", self.rnaEdit.params.dbsnp, "-I", realigned_file, "-cov", "CycleCovariate", "-cov", "ContextCovariate", "-o", recal_file] print(" ".join(cmd)) Helper.proceedCommand("Find Quality Score recalibration spots", cmd, realigned_file, recal_file, self.rnaEdit) # Proceed quality score recalibration. cmd = [ "java", "-Xmx16G", "-jar", self.rnaEdit.params.sourceDir + "GATK/GenomeAnalysisTK.jar", "-T", "PrintReads", "-l", "ERROR", "-R", self.rnaEdit.params.refGenome, "-I", realigned_file, "-BQSR", recal_file, "-o", recalibrated_bam_file ] Helper.proceedCommand("Proceed Quality Score recalibration", cmd, recal_file, recalibrated_bam_file, self.rnaEdit) return recalibrated_bam_file def cleanUp(self): if not self.rnaEdit.params.keepTemp: if os.path.isfile(self.rnaEdit.params.output+".sai"): os.remove(self.rnaEdit.params.output+".sai") if os.path.isfile(self.rnaEdit.params.output+".sam"): os.remove(self.rnaEdit.params.output+".sam") if os.path.isfile(self.rnaEdit.params.output+".bam"): os.remove(self.rnaEdit.params.output+".bam") if os.path.isfile(self.rnaEdit.params.output+".unsorted.bam"): os.remove(self.rnaEdit.params.output+".unsorted.bam") if os.path.isfile(self.rnaEdit.params.output+".bam.bai"): os.remove(self.rnaEdit.params.output+".bam.bai") if os.path.isfile(self.rnaEdit.params.output+".indels.intervals"): os.remove(self.rnaEdit.params.output+".indels.intervals") if os.path.isfile(self.rnaEdit.params.output+".noDup.bam"): os.remove(self.rnaEdit.params.output+".noDup.bam") if os.path.isfile(self.rnaEdit.params.output+".noDup.bam.bai"): os.remove(self.rnaEdit.params.output+".noDup.bam.bai") if os.path.isfile(self.rnaEdit.params.output+".noDup.realigned.bam"): os.remove(self.rnaEdit.params.output+".noDup.realigned.bam") if os.path.isfile(self.rnaEdit.params.output+".noDup.realigned.bai"): os.remove(self.rnaEdit.params.output+".noDup.realigned.bai") if os.path.isfile(self.rnaEdit.params.output+".recalSpots.grp"): os.remove(self.rnaEdit.params.output+".recalSpots.grp") # os.remove(self.outfilePrefix+".realigned.marked.recalibrated.bam") def checkDependencies(args): """ Checks the existence of the necessary packages and tools :param args: """ Helper.newline(1) Helper.info("CHECK DEPENDENCIES") # Check if all tools are present. if not os.path.isfile(args.sourceDir+"bwa"): Helper.error("BWA not found in %s" % args.sourceDir) if not os.path.isfile(args.sourceDir+"picard-tools/SortSam.jar"): Helper.error("SortSam.jar not found in %s" % args.sourceDir+"picard-tools") if not os.path.isfile(args.sourceDir+"picard-tools/MarkDuplicates.jar"): Helper.error("MarkDuplicates.jar not found in %s" % args.sourceDir+"picard-tools") if not os.path.isfile(args.sourceDir+"GATK/GenomeAnalysisTK.jar"): Helper.error("GenomeAnalysisTK.jar not found in %s" % args.sourceDir+"GATK/") if not os.path.isfile(args.sourceDir+"samtools"): Helper.error("samtools not found in %s" % args.sourceDir) if not os.system("java -version") == 0: Helper.error("Java could not be found, Please install java") # Check if all files are present. if not os.path.isfile(args.RefGenome): Helper.error("Could not find Reference Genome in %s: " % args.RefGenome) # Files for BWA if not os.path.isfile(args.RefGenome+".amb"): Helper.error("Could not find %s.amb" % args.RefGenome) Helper.error("run: 'bwa index %s' to create it" % args.RefGenome) if not os.path.isfile(args.RefGenome+".ann"): Helper.error("Could not find %s.ann" % args.RefGenome) Helper.error("run: 'bwa index %s' to create it" % args.RefGenome) if not os.path.isfile(args.RefGenome+".bwt"): Helper.error("Could not find %s.bwt" % args.RefGenome) Helper.error("run: 'bwa index %s' to create it" % args.RefGenome) if not os.path.isfile(args.RefGenome+".pac"): Helper.error("Could not find %s.pac" % args.RefGenome) Helper.error("run: 'bwa index %s' to create it" % args.RefGenome) if not os.path.isfile(args.RefGenome+".sa"): Helper.error("Could not find %s.sa" % args.RefGenome) Helper.error("run: 'bwa index %s' to create it" % args.RefGenome) # Files for GATK if not os.path.isfile(args.RefGenome.replace(".fastq", ".dict")): Helper.error("Could not find %s" % args.RefGenome.replace(".fastq", ".dict")) Helper.error( "run: 'java -jar %s/picard-tools/CreateSequenceDictionary.jar R=%s O= %s.dict' to create it" % (args.sourceDir, args.RefGenome, args.RefGenome.replace(".fastq", ".dict"))) if not os.path.isfile(args.RefGenome+".fai"): Helper.error("Could not find %s.fai" % args.RefGenome) Helper.error("run: 'samtools faidx %s' to create it" % args.RefGenome) # SNP databases if not os.path.isfile(args.dbsnp): Helper.error("Could not find %s: " % args.dbsnp) if __name__ == '__main__': # Parse command line arguments and set defaults. parser = argparse.ArgumentParser( description='map FastQ Files to the given genome and realigns the reads for SNP-calling.') parser.add_argument( '-i', '--input', metavar='Fastq-File', type='+', help='Input fastq files (maximum two for paire-end-sequencing)', required=True ) parser.add_argument( "-r", "--RefGenome", metavar='Fasta-File', help="File that contains the reference sequences", type=argparse.FileType('r'), default='') parser.add_argument( '-s', '--dbsnp', help=' SNP database (dbSNP) in VCF format (downloaded from the GATK homepage)', type=argparse.FileType('r'), default='/media/databases/human/dbsnp_135.b37.vcf' ) parser.add_argument( '-o', '--output', metavar='output-prefix', type=str, help='prefix that is written in front of the output files', default="default" ) parser.add_argument( '-d', '--sourceDir', help='- Directory to all the tools [default: /bin/]', default='bin/', type=Helper.readable_dir ) parser.add_argument( '-t', '--threads', help='number of threads', type=int, default=multiprocessing.cpu_count()-1 ) parser.add_argument( '-n', '--maxDiff', help=' maximum Number of mismatches in the reads (int) or error rate in percentage (float)[0.04]', type=float, default=0.04 ) parser.add_argument( '--seedDiff', help='maximum Number of mismatches in the seed sequence (int)[2]', type=int, default=2 ) parser.add_argument( '-p', '--paired', help="Use this paramater if you have paired end reads [false]", action='store_true', default=False ) parser.add_argument( '--keepTemp', help='keep the intermediate Files [False]', action='store_true', default=False ) parser.add_argument( '--overwrite', help='overwrite existing Files [False]', action='store_true', default=False ) args = parser.parse_args() checkDependencies(args) map_fastq_obj = MapFastq( args.input, args.RefGenome.name, args.dbsnp.name, args.output, args.sourceDir, args.threads, args.maxDiff, args.seedDiff, args.paired, args.keepTemp, args.overwrite ) map_fastq_obj.startAnalysis() del map_fastq_obj
[ "tyler.weirick@gmail.com" ]
tyler.weirick@gmail.com
4ed13099ffbfcecf7846955a084a2123528d4ecf
384b5ed9b6581f6e75a4c84d1b183357ec85d563
/staff/api.py
a986875938b835300c9b78a7e971a4202b6ecc75
[]
no_license
diemnt/eBook
d8d3a6f1d6be2b6192667c509e530bac873c4576
59781afa38420f9595e04c6460d1cfc23449c21b
refs/heads/master
2020-04-09T07:50:20.634561
2018-12-03T10:21:22
2018-12-03T10:21:22
151,664,583
0
0
null
null
null
null
UTF-8
Python
false
false
2,535
py
from django.utils.translation import ugettext_lazy as _ from rest_framework import viewsets from rest_framework.permissions import AllowAny from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from staff.models import Staff, Role from staff.serializers import StaffSerializer, RoleSerializer, DisplayStaffSerializer from django.conf import settings from io import open import traceback import json import os @permission_classes((AllowAny,)) @api_view(['GET']) def get_role_permissions(request, id): try: results = {} # Build path of permission file. Project path join file path permission_file_path = os.path.join( settings.BASE_DIR, 'websites/staff/permissions_default.json') # Open file with readonly. with open(permission_file_path, 'r') as permission_file: results['permissions_default'] = json.load(permission_file) # Get Role by Id role = Role.objects.get(pk=id) results["role"] = RoleSerializer(role).data return Response(results, status=200) except Role.DoesNotExist, e: return Response({"code": 400, "message": _("Role not found."), "fields": "id"}, status=400) except Exception, e: print 'GET Role Permission API Error: ', traceback.format_exc() return Response({"code": 500, "message": _("Internal Server Error"), "fields": ""}, status=500) class RoleViewSet(viewsets.ModelViewSet): queryset = Role.objects.all() serializer_class = RoleSerializer permission_classes = (AllowAny, ) class StaffViewSet(viewsets.ModelViewSet): queryset = Staff.objects.all() permission_classes = (AllowAny, ) serializer_class = StaffSerializer action_serializers = { 'retrieve': DisplayStaffSerializer, 'list': DisplayStaffSerializer, } # def partial_update(self, request, *args, **kwargs): # serializer = StaffSerializer(data=request.data, partial=True) # if serializer.is_valid(): # serializer.save() # return JsonResponse(serializer.data, status=201) # return JsonResponse(serializer.errors, status=400) # Override get_serializer_class view : field role explain detail def get_serializer_class(self): if hasattr(self, 'action_serializers'): if self.action in self.action_serializers: return self.action_serializers[self.action] return super(StaffViewSet, self).get_serializer_class()
[ "diemnguyen@vooc.vn" ]
diemnguyen@vooc.vn
be03ce1c5168d01cd98377cf216a316388b4c1ef
d7cb6fd966b4dda57e3a984dc926cc3669a98915
/_support_func.py
b6e806b4c2eed387039c5b78ed3f580078d5ca2b
[]
no_license
raviy8408/AnyClassification
037bec829d13c76418b568d986ff9e4a31249aa7
af9c4e3890a66d3c641dd211265d0de24deb7217
refs/heads/master
2021-07-05T08:22:42.232084
2019-12-12T09:30:14
2019-12-12T09:30:14
130,036,974
0
0
null
null
null
null
UTF-8
Python
false
false
14,852
py
import numpy as np import pandas as pd from _plot_func import * from _helper_func import * def print_categories(df, cols): ''' :param df: Pandas DataFrame :param cols: Categorical columns :return: prints all the categories of the categorical columns given ''' print("\n##########--levels of categorical variable--############") for col in cols: print("\n" + col + "_categories:") print((df[col].cat.categories)) print("\n########################################################") def column_index(df, query_cols): cols = df.columns.values sidx = np.argsort(cols) return sidx[np.searchsorted(cols, query_cols, sorter=sidx)] def test_train_splitter(df, y, cat_feature_list, int_feature_list, ID_col, outcome_type='category',split_frac=0.8, data_balancing = False, balancing_method = "smote-nc", balancing_params = {'sampling_strategy': 'minority','k_neighbors': 5,'n_jobs': -1}): ''' Splits the data into test and train in the ration provided and returns 4 data frames: x_train, y_train, x_test, y_test :param df: complete data :param y: outcome variable :param cat_feature_list: all the categorical variables :param data_balancing: True/False :param balancing_method: over sampling method used :return: x_train, y_train, x_test, y_test ''' from sklearn.model_selection import train_test_split from imblearn.over_sampling import SMOTENC, SMOTE from collections import Counter X_train, X_test, y_train, y_test = train_test_split(df.drop([y], axis=1).values, df[y], test_size=1 - split_frac) if (data_balancing == True) & (balancing_method == "smote-nc"): if cat_feature_list: cat_col_index = [df.drop([y], axis=1).columns.get_loc(c) for c in cat_feature_list if c in df.drop([y], axis=1)] smote_nc = SMOTENC(categorical_features=cat_col_index, random_state=0, sampling_strategy=balancing_params.get('sampling_strategy'), k_neighbors=balancing_params.get('k_neighbors'), n_jobs=balancing_params.get('n_jobs')) X_resampled, y_resampled = smote_nc.fit_resample(X_train, y_train) else: smote = SMOTE(random_state=0, sampling_strategy=balancing_params.get('sampling_strategy'), k_neighbors=balancing_params.get('k_neighbors'), n_jobs=balancing_params.get('n_jobs')) X_resampled, y_resampled = smote.fit_resample(X_train, y_train) X_train_final = X_resampled y_train_final = y_resampled print("Class distribution before balancing:") print(dict(Counter(y_train))) print("Class distribution after balancing:") print(dict(Counter(y_train_final))) else: X_train_final = X_train y_train_final = y_train # test train dataframe creation X_train_df = pd.DataFrame(data=X_train_final, columns=df.drop([y], axis=1).columns.values) y_train_df = pd.DataFrame(data=y_train_final, columns=[y]) X_test_df = pd.DataFrame(data=X_test, columns=df.drop([y], axis=1).columns.values) y_test_df = pd.DataFrame(data=y_test, columns=[y]) # assigning variable types to test and train data columns if cat_feature_list: X_train_df[cat_feature_list] = X_train_df[cat_feature_list].apply(lambda x: x.astype('category')) X_test_df[cat_feature_list] = X_test_df[cat_feature_list].apply(lambda x: x.astype('category')) if int_feature_list: X_train_df[int_feature_list] = X_train_df[int_feature_list].apply(lambda x: x.astype('int64')) X_test_df[int_feature_list] = X_test_df[int_feature_list].apply(lambda x: x.astype('int64')) _non_float_feature_list = cat_feature_list + [y] + int_feature_list + ID_col X_train_df[df.columns.difference(_non_float_feature_list)] = X_train_df[ df.columns.difference(_non_float_feature_list)].apply(lambda x: x.astype('float')) X_test_df[df.columns.difference(_non_float_feature_list)] = X_test_df[ df.columns.difference(_non_float_feature_list)].apply(lambda x: x.astype('float')) X_train_df[ID_col] = X_train_df[ID_col].astype(str) X_test_df[ID_col] = X_test_df[ID_col].astype(str) y_train_df[[y]] = y_train_df[[y]].apply(lambda x: x.astype('category')) y_test_df[[y]] = y_test_df[[y]].apply(lambda x: x.astype('category')) return X_train_df, y_train_df, X_test_df, y_test_df def labelEncoder_cat_features(X_train, X_test, cat_feature_list, **kwargs): ''' Converts all categorical features to numerical levels :param X_train: train data frame :param X_test: test data frame :param cat_feature_list: all categorical variables :return: encoded pandas data frame ''' from sklearn.preprocessing import LabelEncoder if ('ID_col' in kwargs.keys()): ID_col = kwargs.get('ID_col') else: ID_col = [] X_train[cat_feature_list] = X_train[cat_feature_list].apply(lambda x: x.astype(str)) X_test[cat_feature_list] = X_test[cat_feature_list].apply(lambda x: x.astype(str)) le = LabelEncoder() # Iterating over all the common columns in train and test for col in X_test.columns.values: # Encoding only categorical variables if (X_test[col].dtypes == 'object') and (col not in ID_col): # Using whole data to form an exhaustive list of levels data = X_train[col].append(X_test[col]) le.fit(data.values) X_train[col] = le.transform(X_train[col]) X_test[col] = le.transform(X_test[col]) return X_train, X_test def oneHotEncoder_cat_features(X_train_labelEncoded, X_test_labelEncoded, cat_feature_list, drop_last=False): ''' creates one hot encoded data frame :param X_train_labelEncoded: label encoded train data frame :param X_test_labelEncoded: label encoded test data frame :param cat_feature_list: all the categorical features :return: ''' from sklearn.preprocessing import OneHotEncoder X_train_oneHotEncoded = X_train_labelEncoded X_test_oneHotEncoded = X_test_labelEncoded enc = OneHotEncoder(sparse=False) for col in cat_feature_list: data = X_train_labelEncoded[[col]].append(X_test_labelEncoded[[col]]) enc.fit(data) # Fitting One Hot Encoding on train data temp = enc.transform(X_train_labelEncoded[[col]]) # Changing the encoded features into a data frame with new column names # if number of categorical levels is less than 3, keep only one column if drop_last == False: if len(data[col].unique()) < 3: temp = pd.DataFrame(temp[:, :-1], columns=[(col + "_" + str(i)) for i in data[col] .value_counts().index[:-1]]) else: temp = pd.DataFrame(temp, columns=[(col + "_" + str(i)) for i in data[col] .value_counts().index]) elif drop_last == True: temp = pd.DataFrame(temp[:, :-1], columns=[(col + "_" + str(i)) for i in data[col] .value_counts().index[:-1]]) # In side by side concatenation index values should be same # Setting the index values similar to the X_train data frame temp = temp.set_index(X_train_labelEncoded.index.values) # adding the new One Hot Encoded varibales to the train data frame X_train_oneHotEncoded = pd.concat([X_train_oneHotEncoded, temp], axis=1) # fitting One Hot Encoding on test data temp = enc.transform(X_test_labelEncoded[[col]]) # changing it into data frame and adding column names # if number of categorical levels is less than 3, keep only one column if drop_last == False: if len(data[col].unique()) < 3: temp = pd.DataFrame(temp[:, :-1], columns=[(col + "_" + str(i)) for i in data[col] .value_counts().index[:-1]]) else: temp = pd.DataFrame(temp, columns=[(col + "_" + str(i)) for i in data[col] .value_counts().index]) elif drop_last == True: temp = pd.DataFrame(temp[:, :-1], columns=[(col + "_" + str(i)) for i in data[col] .value_counts().index[:-1]]) # Setting the index for proper concatenation temp = temp.set_index(X_test_labelEncoded.index.values) # adding the new One Hot Encoded varibales to test data frame X_test_oneHotEncoded = pd.concat([X_test_oneHotEncoded, temp], axis=1) # dropping label encoded categorical variables X_train_oneHotEncoded = X_train_oneHotEncoded.drop(cat_feature_list, axis=1) X_test_oneHotEncoded = X_test_oneHotEncoded.drop(cat_feature_list, axis=1) return X_train_oneHotEncoded, X_test_oneHotEncoded def cal_lr_p_vals(X, y, params, predictions): from scipy import stats newX = pd.DataFrame({"Constant":np.ones(len(X))}).join(pd.DataFrame(X)) MSE = (sum((y.values-predictions)**2))/(len(newX)-len(newX.columns)) # Note if you don't want to use a DataFrame replace the two lines above with # newX = np.append(np.ones((len(X),1)), X, axis=1) # MSE = (sum((y-predictions)**2))/(len(newX)-len(newX[0])) var_b = MSE*(np.linalg.inv(np.dot(newX.T,newX)).diagonal()) sd_b = np.sqrt(var_b) ts_b = params/ sd_b p_values =[2*(1-stats.t.cdf(np.abs(i),(len(newX)-1))) for i in ts_b] sd_b = np.round(sd_b,3) ts_b = np.round(ts_b,3) p_values = np.round(p_values,3) params = np.round(params,4) myDF3 = pd.DataFrame() myDF3["Coefficients"],myDF3["Standard Errors"],myDF3["t values"],myDF3["Probabilites"] = [params,sd_b,ts_b,p_values] var_list = np.array(['Cons'] + list(X.columns.values)) myDF3.set_index(var_list, drop=True, inplace=True) print(myDF3) def model_performance(X_test_model_dt, y_test, model_name, model_object, output_path, prob, **kwargs): """ Function to print the model performance metrics such as accuracy, confusion matrix, classification report, kappa value :param X_test_model_dt: X_test data :param y_test: test outcome variable :param model_name: name of the model :param model_object: model object :param output_path: file path to store the output :param prob: True if model returns probability :return: None """ import os from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, cohen_kappa_score, \ recall_score, precision_score, f1_score if ('train_test_iter_num' in kwargs.keys()): train_test_iter_num = kwargs.get("train_test_iter_num") else: train_test_iter_num = 1 if ('ID' in kwargs.keys()): ID = kwargs.get("ID") else: ID = [] if ('train_set' in kwargs.keys()): train_set = kwargs.get("train_set") else: train_set = False if train_set == True: print("#########--Model Performance on Train Set--#########\n") else: print("##########--Model Performance on Test Set--#########\n") path = output_path + model_name + "/" if not os.path.isdir(path): os.makedirs(path) if prob == True: # Saving ROC plot to the drive plot_ROC(y_test=y_test,y_pred_prob= model_object.best_estimator_.predict_proba(X_test_model_dt)[:, 1], model_name= model_name, image_dir=path, train_test_iter_num = train_test_iter_num, train_set = train_set) print("ROC plot saved to the drive!\n") if model_name == 'ANN': y_pred = model_object.best_estimator_.predict(X_test_model_dt)[:,0] else: y_pred = model_object.best_estimator_.predict(X_test_model_dt) _result_dict = {'accuracy' : accuracy_score(y_true=y_test, y_pred=y_pred), 'label_1_recall' : recall_score(y_true=y_test, y_pred=y_pred, pos_label=1), 'label_1_precision' : precision_score(y_true=y_test, y_pred=y_pred, pos_label=1), 'label_1_f1_score' : f1_score(y_true=y_test, y_pred=y_pred, pos_label=1), 'label_0_recall': recall_score(y_true=y_test, y_pred=y_pred, pos_label=0), 'label_0_precision': precision_score(y_true=y_test, y_pred=y_pred, pos_label=0), 'label_0_f1_score': f1_score(y_true=y_test, y_pred=y_pred, pos_label=0), 'kappa' : cohen_kappa_score(y_test, y_pred) } # print("Model Performance on Test Set:\n") print("Accuracy:\n") print(str(_result_dict.get('accuracy'))) print("\nConfusion Matrix:\n") print(pd.crosstab(y_test, y_pred,rownames=['True'], colnames=['Predicted'], margins=True)) print("\nClassification Report:\n") print(classification_report(y_test,y_pred)) print("\nCohen Kappa:\n") print(_result_dict.get('kappa')) ###################################################### print("Saving iteration result to drive..") if train_test_iter_num <=1: _result = pd.DataFrame(_result_dict, index=['iter' + str(train_test_iter_num)]) if train_set == True: _result.to_csv(path + 'result_train.tsv', sep='\t') else: _result.to_csv(path + 'result_test.tsv', sep='\t') else: _result = pd.DataFrame(_result_dict, index=['iter' + str(train_test_iter_num)]) if train_set == True: appendDFToCSV_void(df=_result, csvFilePath=path + 'result_train.tsv', sep='\t') else: appendDFToCSV_void(df=_result, csvFilePath=path + 'result_test.tsv', sep='\t') ###################################################### print("Saving predictions to drive..\n") if train_set == True: path = output_path + model_name + "/prediction/Train_Set/" else: path = output_path + model_name + "/prediction/Test_Set/" if not os.path.isdir(path): os.makedirs(path) if len(ID) == len(y_test): pred_df = pd.DataFrame({'actual' : y_test, 'pred' : y_pred}, index=y_test.index) ID.set_index(y_test.index.values, drop = True, inplace = True) pred_df = pd.concat([ID, pred_df], axis=1) pred_df.to_csv(path + 'predictions_iter' + str(train_test_iter_num) + '.tsv', sep="\t") else: pred_df = pd.DataFrame({'actual': y_test, 'pred': y_pred}, index=y_test.index) pred_df.to_csv(path + 'predictions_iter' + str(train_test_iter_num) + '.tsv', sep="\t") ######################################################
[ "raviy8408@gmail.com" ]
raviy8408@gmail.com
2ca5a7517e53c5f8814d79f08ebdb91d5ae890d2
63ab04fa56f0aa115a927dfe4991bbb0536a958c
/src/main/java/old/y2018/m9/d11_palindrome/Sol.py
2c8b2292d0ed00ab007ad1b27b78e6c4bdf790c4
[]
no_license
myks790/algorithm
a5c7db409c19bea82da5cdc5b2b9b00b13ec247e
90f452076e887bcb6c478e0cbd1c24c430862cff
refs/heads/master
2020-03-26T07:09:55.210663
2018-12-04T13:49:58
2018-12-04T13:49:58
144,639,101
0
0
null
null
null
null
UTF-8
Python
false
false
609
py
def palindrome_rec(s): if len(s) == 1 or len(s) ==0: return True elif s[0] == s[-1]: return palindrome(s[1:-1]) else: return False def palindrome(s): le = len(s) for i in range(le//2): if s[i] != s[le - i -1]: return False return True def solution(s): max = 1 for i in range(len(s),0,-1): for j in range(len(s) - i): p = s[j:i+j + 1] if palindrome(p): if max < len(p): max = len(p) break if max != 1: break return max
[ "myks790@gmail.com" ]
myks790@gmail.com
d85462c72cd8b425b994ac02bbe76a3742a0e263
304033f60097c489cbc60aab639be45ccdbef1a5
/algorithms/boj/mAth/10164.py
e379482c4ff56e7e8e0b74799b1a945f6657103c
[]
no_license
pgw928/TIL
3d0c47c07bd1f5c73826daf8579a2b0e3f93cb95
765906f1e6eecad4ad8ec9bf704041433d7eb304
refs/heads/master
2023-06-29T05:46:30.039815
2021-08-10T17:38:11
2021-08-10T17:38:11
288,923,095
3
0
null
null
null
null
UTF-8
Python
false
false
329
py
import sys n, m, a = map(int, sys.stdin.readline().split()) q, r = divmod(a, m) if r==0: r+=m q-=1 def sol(x, y): res = 1 for i in range(y+1,x+y+1): res*=i for i in range(1,x+1): res//=i return res if a==0 or a==n*m: print(sol(m-1,n-1)) else: print(sol(q,r-1)*sol(n-1-q, m-r))
[ "pku928@naver.com" ]
pku928@naver.com
6edfc7a5172849ade4858f08dfd4e5271cafa696
097828ccedc279e542a10f174e4fb200a48516e0
/siteroot/TextSongs/migrations/0008_auto_20210327_0138.py
32c27328e162b24583a72735996785eaca37f3bd
[]
no_license
askomyagin/Django-Project
1ef01a6a981ece905b075d919e16d4fd675ce80b
7e9f6514ab35a3f2d9e6913352953f33fdd8e2ee
refs/heads/main
2023-04-03T07:02:50.498960
2021-03-28T15:03:36
2021-03-28T15:03:36
352,357,331
0
0
null
null
null
null
UTF-8
Python
false
false
376
py
# Generated by Django 3.1.7 on 2021-03-26 22:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('TextSongs', '0007_ordertext'), ] operations = [ migrations.AlterField( model_name='ordertext', name='info', field=models.TextField(null=True), ), ]
[ "sashawqw@mail.ru" ]
sashawqw@mail.ru
5d3eea3177799ac19d999743783ecdf15001e3bd
41637d65d88f6f00cd8ece80e90650341e22b86e
/pysprint/core/bases/dataset.py
18ef8791f97bb73c5374c3418c7f6211d8ac58d3
[ "MIT" ]
permissive
razzaqjavaria/PySprint
c9e1f7bcfbf5c35e7273fc87ad9b91fd8858249f
f90811970c66e8fadea1220c4c19bf95cdf33c9e
refs/heads/master
2023-09-04T20:55:39.904168
2021-11-11T11:29:01
2021-11-11T11:29:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
53,301
py
""" This file implements the Dataset class with all the functionality that an interferogram should have in general. """ import base64 from collections.abc import Iterable from contextlib import suppress, contextmanager from io import BytesIO import json import logging from math import factorial import numbers import re from textwrap import dedent import warnings import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.interpolate import interp1d from jinja2 import Template from pysprint.config import _get_config_value from pysprint.core.bases._dataset_base import _DatasetBase from pysprint.core.bases._dataset_base import C_LIGHT from pysprint.core.bases._apply import _DatasetApply from pysprint.core._evaluate import is_inside from pysprint.core._evaluate import ifft_method from pysprint.core._fft_tools import find_center from pysprint.core.io._parser import _parse_raw from pysprint.mpl_tools.spp_editor import SPPEditor from pysprint.mpl_tools.normalize import DraggableEnvelope from pysprint.utils import MetaData, find_nearest from pysprint.utils.decorators import inplacify from pysprint.core._preprocess import ( savgol, find_peak, convolution, cut_data, cwt, ) from pysprint.utils.exceptions import ( InterpolationWarning, DatasetError, PySprintWarning, ) logger = logging.getLogger(__name__) FORMAT = "[ %(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s" logging.basicConfig(format=FORMAT) __all__ = ["Dataset"] class Dataset(metaclass=_DatasetBase): """ This class implements all the functionality a dataset should have in general. """ meta = MetaData("""Additional info about the dataset""", copy=False) def __init__( self, x, y, ref=None, sam=None, meta=None, errors="raise", callback=None, parent=None, **kwargs ): """ Base constructor for Dataset. Parameters ---------- x : np.ndarray The x values. y : np.ndarray The y values. ref : np.ndarray, optional The reference arm's spectra. sam : np.ndarray, optional The sample arm's spectra. meta : dict-like The dictionary containing further information about the dataset. Can be extended, or set to be any valid ~collections.abc.Mapping. errors: str, optional Whether to raise on missmatching sized data. Must be "raise" or "force". If "force" then truncate to the shortest size. Default is "raise". callback : callable, optional The function that notifies parent objects about SPP related changes. In most cases the user should leave this empty. The default callback is only initialized if this object is constructed by the `pysprint.SPPMethod` object. parent : any class, optional The object which handles the callback function. In most cases the user should leave this empty. kwargs : dict, optional The window class to use in WFTMethod. Has no effect while using other methods. Must be a subclass of pysprint.core.windows.WindowBase. Note ---- To load in data by files, see the other constructor `parse_raw`. """ super().__init__() if errors not in ("raise", "force"): raise ValueError("errors must be `raise` or `force`.") self.callback = callback or (lambda *args: args) self.parent = parent self.x = np.array(x, dtype=np.float64) self.y = np.array(y, dtype=np.float64) if ref is None: self.ref = [] else: self.ref = ref if sam is None: self.sam = [] else: self.sam = sam self._is_normalized = False if not isinstance(self.x, np.ndarray): try: self.x = np.array(self.x).astype(float) except ValueError: raise DatasetError("Invalid type of data") if not isinstance(self.y, np.ndarray): try: self.y = np.array(self.y).astype(float) except ValueError: raise DatasetError("Invalid type of data") if not isinstance(self.ref, np.ndarray): try: self.ref = np.array(self.ref).astype(float) except ValueError: pass # just ignore invalid arms if not isinstance(self.sam, np.ndarray): try: self.sam = np.array(self.sam).astype(float) except ValueError: pass # just ignore invalid arms if not len(self.x) == len(self.y): if errors == 'raise': raise ValueError( f"Mismatching data shapes with {self.x.shape} and {self.y.shape}." ) else: truncated_shape = min(len(self.x), len(self.y)) # probably we should cut down the first half self.x, self.y = self.x[-truncated_shape:], self.y[-truncated_shape:] if len([x for x in (self.ref, self.sam) if len(x) != 0]) == 1: warnings.warn( "Reference and sample arm should be passed together or neither one.", PySprintWarning ) if len(self.ref) == 0 or len(self.sam) == 0: self.y_norm = self.y self._is_normalized = self._ensure_norm() else: if not np.all([len(self.sam) == len(self.x), len(self.ref) == len(self.x)]): if errors == 'raise': raise ValueError( f"Mismatching data shapes with {self.x.shape}, " f"{self.ref.shape} and {self.sam.shape}." ) else: truncated_shape = min(len(self.x), len(self.ref), len(self.sam), len(self.y)) # same as above.. self.ref, self.sam = self.ref[-truncated_shape:], self.sam[-truncated_shape:] self.y_norm = (self.y - self.ref - self.sam) / ( 2 * np.sqrt(self.sam * self.ref) ) self._is_normalized = True self.plt = plt self.xmin = None self.xmax = None self.probably_wavelength = None self.unit = None self._check_domain() if meta is not None: self.meta = meta self._delay = None self._positions = None nanwarning = np.isnan(self.y_norm).sum() infwarning = np.isinf(self.y_norm).sum() if nanwarning > 0 or infwarning > 0: warnings.warn( ("Extreme values encountered during normalization.\n" f"Nan values: {nanwarning}\nInf values: {infwarning}"), PySprintWarning ) self._dispersion_array = None @inplacify def chrange(self, current_unit, target_unit="phz"): """ Change the domain range of the dataset. Supported units for frequency: * PHz * THz * GHz Supported units for wavelength: * um * nm * pm * fm Parameters ---------- current_unit : str The current unit of the domain. Case insensitive. target_unit : str, optional The target unit. Must be compatible with the currect unit. Case insensitive. Default is `phz`. """ current_unit, target_unit = current_unit.lower(), target_unit.lower() conversions = { "um": {"um": 1, "nm": 1000, "pm": 1E6, "fm": 1E9}, "nm": {"um": 1 / 1000, "nm": 1, "pm": 1000, "fm": 1E6}, "pm": {"um": 1 / 1E6, "nm": 1 / 1000, "pm": 1, "fm": 1000}, "fm": {"um": 1 / 1E9, "nm": 1 / 1E6, "pm": 1 / 1000, "fm": 1}, "phz": {"phz": 1, "thz": 1000, "ghz": 1E6}, "thz": {"phz": 1 / 1000, "thz": 1, "ghz": 1000}, "ghz": {"phz": 1 / 1E6, "thz": 1 / 1000, "ghz": 1} } try: ratio = float(conversions[current_unit][target_unit]) except KeyError as error: raise ValueError("Units are not compatible") from error self.x = (self.x * ratio) self.unit = self._render_unit(target_unit) return self def __len__(self): return len(self.x) @staticmethod def _render_unit(unit, mpl=False): unit = unit.lower() charmap = { "um": (r"\mu m", "um"), "nm": ("nm", "nm"), "pm": ("pm", "pm"), "fm": ("fm", "fm"), "phz": ("PHz", "PHz"), "thz": ("THz", "THz"), "ghz": ("GHz", "GHz") } if mpl: return charmap[unit][0] return charmap[unit][1] @inplacify def transform(self, func, axis=None, args=None, kwargs=None): """ Function which enables to apply arbitrary function to the dataset. Parameters ---------- func : callable The function to apply on the dataset. axis : int or str, optional The axis which is the operation is performed on. Must be 'x', 'y', '0' or '1'. args : tuple, optional Additional arguments to pass to func. kwargs : dict, optional Additional keyword arguments to pass to func. """ operation = _DatasetApply( obj=self, func=func, axis=axis, args=args, kwargs=kwargs ) operation.perform() return self # TODO : Rewrite this def phase_plot(self, exclude_GD=False): """ Plot the phase if the dispersion is already calculated. Parameters ---------- exclude_GD : bool Whether to exclude the GD part of the polynomial. Default is `False`. """ if not np.all(self._dispersion_array): raise ValueError("Dispersion must be calculated before plotting the phase.") coefs = np.array( [ self._dispersion_array[i] / factorial(i + 1) for i in range(len(self._dispersion_array)) ] ) if exclude_GD: coefs[0] = 0 phase_poly = np.poly1d(coefs[::-1], r=False) self.plt.plot(self.x, phase_poly(self.x)) self.plt.grid() self.plt.ylabel(r"$\Phi\, [rad]$") self.plt.xlabel(r"$\omega \,[PHz]$") self.plt.show() @property def delay(self): """ Return the delay value if set. """ return self._delay @delay.setter def delay(self, value): self._delay = value try: self.callback(self, self.parent) except ValueError: pass # delay or position is missing @property def positions(self): """ Return the SPP position(s) if set. """ return self._positions @positions.setter def positions(self, value): if isinstance(value, numbers.Number): if value < np.min(self.x) or value > np.max(self.x): raise ValueError( f"Cannot set SPP position to {value} since it's not in the dataset's range." ) # FIXME: maybe we don't need to distinguish between np.ndarray and Iterable elif isinstance(value, np.ndarray) or isinstance(value, Iterable): for val in value: if not isinstance(val, numbers.Number): raise ValueError( f"Expected numeric values, got {type(val)} instead." ) if val < np.min(self.x) or val > np.max(self.x): raise ValueError( f"Cannot set SPP position to {val} since it's not in the dataset's range." ) self._positions = value try: self.callback(self, self.parent) except ValueError: pass # delay or position is missing def _ensure_norm(self): """ Ensure the interferogram is normalized and only a little part which is outlying from the [-1, 1] interval (because of noise). """ try: idx = np.where((self.y_norm > 2)) val = len(idx[0]) / len(self.y_norm) except TypeError as e: raise DatasetError("Non-numeric values found while reading dataset.") from e if val > 0.015: # this is a custom threshold, which often works.. return False return True def scale_up(self): """ If the interferogram is normalized to [0, 1] interval, scale up to [-1, 1] with easy algebra. """ self.y_norm = (self.y_norm - 0.5) * 2 self.y = (self.y - 0.5) * 2 def GD_lookup(self, reference_point=None, engine="cwt", silent=False, **kwargs): """ Quick GD lookup: it finds extremal points near the `reference_point` and returns an average value of 2*pi divided by distances between consecutive minimal or maximal values. Since it's relying on peak detection, the results may be irrelevant in some cases. If the parent class is `~pysprint.CosFitMethod`, then it will set the predicted value as initial parameter for fitting. Parameters ---------- reference_point : float The reference point for the algorithm. engine : str, optional The backend to use. Must be "cwt", "normal" or "fft". "cwt" will use `scipy.signal.find_peaks_cwt` function to detect peaks, "normal" will use `scipy.signal.find_peaks` to detect peaks. The "fft" engine uses Fourier-transform and looks for the outer peak to guess delay value. It's not reliable when working with low delay values. silent : bool, optional Whether to print the results immediately. Default in `False`. kwargs : dict, optional Additional keyword arguments to pass for peak detection algorithms. These are: pmin, pmax, threshold, width, floor_thres, etc.. Most of them are described in the `find_peaks` and `find_peaks_cwt` docs. """ precision = _get_config_value("precision") if engine not in ("cwt", "normal", "fft"): raise ValueError("Engine must be `cwt`, `fft` or `normal`.") if reference_point is None and engine != "fft": warnings.warn( f"Engine `{engine}` isn't available without reference point, falling back to FFT based prediction.", PySprintWarning ) engine = "fft" if engine == "fft": pred, _ = find_center(*ifft_method(self.x, self.y)) if pred is None: if not silent: print("Prediction failed, skipping.") return print(f"The predicted GD is ± {pred:.{precision}f} fs.") if hasattr(self, "params"): self.params[3] = pred return if engine == "cwt": widths = kwargs.pop("widths", np.arange(1, 20)) floor_thres = kwargs.pop("floor_thres", 0.05) x_min, _, x_max, _ = self.detect_peak_cwt( widths=widths, floor_thres=floor_thres ) # just validation _ = kwargs.pop("pmin", 0.1) _ = kwargs.pop("pmax", 0.1) _ = kwargs.pop("threshold", 0.35) else: pmin = kwargs.pop("pmin", 0.1) pmax = kwargs.pop("pmax", 0.1) threshold = kwargs.pop("threshold", 0.35) x_min, _, x_max, _ = self.detect_peak( pmin=pmin, pmax=pmax, threshold=threshold ) # just validation _ = kwargs.pop("widths", np.arange(1, 10)) _ = kwargs.pop("floor_thres", 0.05) if kwargs: raise TypeError(f"Invalid argument:{kwargs}") try: closest_val, idx1 = find_nearest(x_min, reference_point) m_closest_val, m_idx1 = find_nearest(x_max, reference_point) except (ValueError, IndexError): if not silent: print("Prediction failed, skipping.. ") return try: truncated = np.delete(x_min, idx1) second_closest_val, _ = find_nearest(truncated, reference_point) except (IndexError, ValueError): if not silent: print("Prediction failed, skipping.. ") return try: m_truncated = np.delete(x_max, m_idx1) m_second_closest_val, _ = find_nearest(m_truncated, reference_point) except (IndexError, ValueError): if not silent: print("Prediction failed, skipping.. ") return lowguess = 2 * np.pi / np.abs(closest_val - second_closest_val) highguess = 2 * np.pi / np.abs(m_closest_val - m_second_closest_val) # estimate the GD with that if hasattr(self, "params"): self.params[3] = (lowguess + highguess) / 2 if not silent: print( f"The predicted GD is ± {((lowguess + highguess) / 2):.{precision}f} fs" f" based on reference point of {reference_point:.{precision}f}." ) def _safe_cast(self): """ Return a copy of key attributes in order to prevent inplace modification. """ x, y, ref, sam = ( np.copy(self.x), np.copy(self.y), np.copy(self.ref), np.copy(self.sam), ) return x, y, ref, sam @staticmethod def wave2freq(value): """Switches a single value between wavelength and angular frequency.""" return (2 * np.pi * C_LIGHT) / value _dispatch = wave2freq.__func__ @staticmethod def freq2wave(value): """Switches a single value between angular frequency and wavelength.""" return Dataset._dispatch(value) def _check_domain(self): """ Checks the domain of data just by looking at x axis' minimal value. Units are obviously not added yet, we work in nm and PHz... """ try: if min(self.x) > 50: self.probably_wavelength = True self.unit = "nm" else: self.probably_wavelength = False self.unit = "PHz" # This is the first function to fail if the user sets up # wrong values. Usually.. except TypeError as error: msg = ValueError( "The file could not be parsed properly." ) raise msg from error @classmethod def parse_raw( cls, filename, ref=None, sam=None, skiprows=0, decimal=".", sep=None, delimiter=None, comment=None, usecols=None, names=None, swapaxes=False, na_values=None, skip_blank_lines=True, keep_default_na=False, meta_len=1, errors="raise", callback=None, parent=None, **kwargs ): """ Dataset object alternative constructor. Helps to load in data just by giving the filenames in the target directory. Parameters ---------- filename: `str` base interferogram file generated by the spectrometer ref: `str`, optional reference arm's spectra file generated by the spectrometer sam: `str`, optional sample arm's spectra file generated by the spectrometer skiprows: `int`, optional Skip rows at the top of the file. Default is `0`. decimal: `str`, optional Character recognized as decimal separator in the original dataset. Often `,` for European data. Default is `.`. sep: `str`, optional The delimiter in the original interferogram file. Default is `,`. delimiter: `str`, optional The delimiter in the original interferogram file. This is preferred over the `sep` argument if both given. Default is `,`. comment: `str`, optional Indicates remainder of line should not be parsed. If found at the beginning of a line, the line will be ignored altogether. This parameter must be a single character. Default is `'#'`. usecols: list-like or callable, optional If there a multiple columns in the file, use only a subset of columns. Default is [0, 1], which will use the first two columns. names: array-like, optional List of column names to use. Default is ['x', 'y']. Column marked with `x` (`y`) will be treated as the x (y) axis. Combined with the usecols argument it's possible to select data from a large number of columns. swapaxes: bool, optional Whether to swap x and y values in every parsed file. Default is False. na_values: scalar, str, list-like, or dict, optional Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values are interpreted as NaN: ‘’, ‘#N/A’, ‘#N/A N/A’, ‘#NA’, ‘-1.#IND’, ‘-1.#QNAN’, ‘-NaN’, ‘-nan’, ‘1.#IND’, ‘1.#QNAN’, ‘<NA>’, ‘N/A’, ‘NA’, ‘NULL’, ‘NaN’, ‘n/a’, ‘nan’, ‘null’. skip_blank_lines: bool If True, skip over blank lines rather than interpreting as NaN values. Default is True. keep_default_na: bool Whether or not to include the default NaN values when parsing the data. Depending on whether na_values is passed in, the behavior changes. Default is False. More information available at: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html meta_len: `int`, optional The first `n` lines in the original file containing the meta information about the dataset. It is parsed to be dict-like. If the parsing fails, a new entry will be created in the dictionary with key `unparsed`. Default is `1`. errors: string, optional Determines the way how mismatching sized datacolumns behave. The default is `raise`, and it will raise on any error. If set to `force`, it will truncate every array to have the same shape as the shortest column. It truncates from the top of the file. callback : callable, optional The function that notifies parent objects about SPP related changes. In most cases the user should leave this empty. The default callback is only initialized if this object is constructed by the `pysprint.SPPMethod` object. parent : any class, optional The object which handles the callback function. In most cases the user should leave this empty. kwargs : dict, optional The window class to use in WFTMethod. Has no effect while using other methods. Must be a subclass of pysprint.core.windows.WindowBase. """ parsed = _parse_raw( filename=filename, ref=ref, sam=sam, skiprows=skiprows, decimal=decimal, sep=sep, delimiter=delimiter, comment=comment, usecols=usecols, names=names, swapaxes=swapaxes, na_values=na_values, skip_blank_lines=skip_blank_lines, keep_default_na=keep_default_na, meta_len=meta_len ) return cls(**parsed, errors=errors, callback=callback, parent=parent, **kwargs) def __str__(self): _unit = self._render_unit(self.unit) precision = _get_config_value("precision") string = dedent( f""" {type(self).__name__} ---------- Parameters ---------- Datapoints: {len(self.x)} Predicted domain: {'wavelength' if self.probably_wavelength else 'frequency'} Range: from {np.min(self.x):.{precision}f} to {np.max(self.x):.{precision}f} {_unit} Normalized: {self._is_normalized} Delay value: {str(self._format_delay()) + ' fs' if self._delay is not None else 'Not given'} SPP position(s): {str(self._format_positions()) + ' PHz' if np.all(self._positions) else 'Not given'} ---------------------------- Metadata extracted from file ---------------------------- """ ) string = re.sub('^\s+', '', string, flags=re.MULTILINE) string += json.dumps(self.meta, indent=4, sort_keys=True) return string def _repr_html_(self): # TODO: move this to a separate template file _unit = self._render_unit(self.unit) precision = _get_config_value("precision") t = f""" <div id="header" class="row" style="height:10%;width:100%;"> <div style='float:left' class="column"> <table style="border:1px solid black;float:top;"> <tbody> <tr> <td colspan=2 style="text-align:center"> <font size="5">{type(self).__name__}</font> </td> </tr> <tr> <td colspan=2 style="text-align:center"> <font size="3.5">Parameters</font> </td> </tr> <tr> <td style="text-align:center"><b>Datapoints<b></td> <td style="text-align:center"> {len(self.x)}</td> </tr> <tr> <td style="text-align:center"><b>Predicted domain<b> </td> <td style="text-align:center"> {'wavelength' if self.probably_wavelength else 'frequency'} </td> </tr> <tr> <td style="text-align:center"> <b>Range min</b> </td> <td style="text-align:center">{np.min(self.x):.{precision}f} {_unit}</td> </tr> <tr> <td style="text-align:center"> <b>Range max</b> </td> <td style="text-align:center">{np.max(self.x):.{precision}f} {_unit}</td> </tr> <tr> <td style="text-align:center"> <b>Normalized</b></td> <td style="text-align:center"> {self._is_normalized} </td> </tr> <tr> <td style="text-align:center"><b>Delay value</b></td> <td style="text-align:center">{str(self._format_delay()) + ' fs' if self._delay is not None else 'Not given'}</td> </tr> <tr> <td style="text-align:center"><b>SPP position(s)</b></td> <td style="text-align:center">{str(self._format_positions()) + ' PHz' if np.all(self._positions) else 'Not given'}</td> </tr> <tr> <td colspan=2 style="text-align:center"> <font size="3.5">Metadata</font> </td> </tr> """ jjstring = Template(""" {% for key, value in meta.items() %} <tr> <th style="text-align:center"> <b>{{ key }} </b></th> <td style="text-align:center"> {{ value }} </td> </tr> {% endfor %} </tbody> </table> </div> <div style='float:leftt' class="column">""") rendered_fig = self._render_html_plot() return t + jjstring.render(meta=self.meta) + rendered_fig def _render_html_plot(self): fig, ax = plt.subplots(figsize=(7, 5)) self.plot(ax=ax) plt.close() tmpfile = BytesIO() fig.savefig(tmpfile, format='png') encoded = base64.b64encode(tmpfile.getvalue()).decode('utf-8') html_fig = "<img src=\'data:image/png;base64,{}\'>".format(encoded) return html_fig @property def data(self): """ Returns the *current* dataset as `pandas.DataFrame`. """ if self._is_normalized: try: self._data = pd.DataFrame( { "x": self.x, "y": self.y, "sample": self.sam, "reference": self.ref, "y_normalized": self.y_norm, } ) except ValueError: self._data = pd.DataFrame({"x": self.x, "y": self.y}) else: self._data = pd.DataFrame({"x": self.x, "y": self.y}) return self._data # from : https://stackoverflow.com/a/15774013/11751294 def __copy__(self): cls = self.__class__ result = cls.__new__(cls) result.__dict__.update(self.__dict__) return result @property def is_normalized(self): """Retuns whether the dataset is normalized.""" return self._is_normalized @inplacify def chdomain(self): """ Changes from wavelength [nm] to ang. freq. [PHz] domain and vica versa. """ self.x = (2 * np.pi * C_LIGHT) / self.x self._check_domain() if hasattr(self, "original_x"): self.original_x = self.x return self def detect_peak_cwt(self, widths, floor_thres=0.05, side="both"): """ Basic algorithm to find extremal points in data using ``scipy.signal.find_peaks_cwt``. Parameters ---------- widths : np.ndarray The widths passed to `find_peaks_cwt`. floor_thres : float Will be removed. side : str The side to use. Must be "both", "max" or "min". Default is "both". Returns ------- xmax : `array-like` x coordinates of the maximums ymax : `array-like` y coordinates of the maximums xmin : `array-like` x coordinates of the minimums ymin : `array-like` y coordinates of the minimums Note ---- When using "min" or "max" as side, all the detected minimal and maximal values will be returned, but only the given side will be recorded for further calculation. """ if side not in ("both", "min", "max"): raise ValueError("Side must be 'both', 'min' or 'max'.") if hasattr(self, "_is_onesided"): self._is_onesided = side != "both" x, y, ref, sam = self._safe_cast() xmax, ymax, xmin, ymin = cwt( x, y, ref, sam, widths=widths, floor_thres=floor_thres ) self.xmax = xmax self.xmin = xmin if side == "both": self.xmax = xmax self.xmin = xmin elif side == "min": self.xmin = xmin elif side == "max": self.xmax = xmax logger.info(f"{len(xmax)} max values and {len(xmin)} min values were found.") return xmax, ymax, xmin, ymin def savgol_fil(self, window=5, order=3): """ Applies Savitzky-Golay filter on the dataset. Parameters ---------- window : int Length of the convolutional window for the filter. Default is `10`. order : int Degree of polynomial to fit after the convolution. If not odd, it's incremented by 1. Must be lower than window. Usually it's a good idea to stay with a low degree, e.g 3 or 5. Default is 3. Note ---- If arms were given, it will merge them into the `self.y` and `self.y_norm` variables. Also applies a linear interpolation o n dataset (and raises warning). """ self.x, self.y_norm = savgol( self.x, self.y, self.ref, self.sam, window=window, order=order ) self.y = self.y_norm self.ref = [] self.sam = [] warnings.warn( "Linear interpolation have been applied to data.", InterpolationWarning, ) @inplacify def slice(self, start=None, stop=None): """ Cuts the dataset on x axis. Parameters ---------- start : float Start value of cutting interval. Not giving a value will keep the dataset's original minimum value. Note that giving `None` will leave original minimum untouched too. Default is `None`. stop : float Stop value of cutting interval. Not giving a value will keep the dataset's original maximum value. Note that giving `None` will leave original maximum untouched too. Default is `None`. Note ---- If arms were given, it will merge them into the `self.y` and `self.y_norm` variables. After this operation, the arms' spectra cannot be retrieved. """ self.x, self.y_norm = cut_data( self.x, self.y, self.ref, self.sam, start=start, stop=stop ) self.ref = [] self.sam = [] self.y = self.y_norm # Just to make sure it's correctly shaped. Later on we might # delete this. if hasattr(self, "original_x"): self.original_x = self.x self._is_normalized = self._ensure_norm() return self def convolution(self, window_length, std=20): """ Convolve the dataset with a specified Gaussian window. Parameters ---------- window_length : int Length of the gaussian window. std : float Standard deviation of the gaussian window. Default is `20`. Note ---- If arms were given, it will merge them into the `self.y` and `self.y_norm` variables. Also applies a linear interpolation on dataset. """ self.x, self.y_norm = convolution( self.x, self.y, self.ref, self.sam, window_length, standev=std ) self.ref = [] self.sam = [] self.y = self.y_norm warnings.warn( "Linear interpolation have been applied to data.", InterpolationWarning, ) @inplacify def resample(self, N, kind="linear", **kwds): """ Resample the interferogram to have `N` datapoints. Parameters ---------- N : int The number of datapoints required. kind : str, optional The type of interpolation to use. Default is `linear`. kwds : optional Additional keyword argument to pass to `scipy.interpolate.interp1d`. Raises ------ PySprintWarning, if trying to subsample to lower `N` datapoints than original. """ f = interp1d(self.x, self.y_norm, kind, **kwds) if N < len(self.x): N = len(self.x) warnings.warn( "Trying to resample to lower resolution, keeping shape..", PySprintWarning ) xnew = np.linspace(np.min(self.x), np.max(self.x), N) ynew = f(xnew) setattr(self, "x", xnew) setattr(self, "y_norm", ynew) return self def detect_peak( self, pmax=0.1, pmin=0.1, threshold=0.1, except_around=None, side="both" ): """ Basic algorithm to find extremal points in data using ``scipy.signal.find_peaks``. Parameters ---------- pmax : float Prominence of maximum points. The lower it is, the more peaks will be found. Default is `0.1`. pmin : float Prominence of minimum points. The lower it is, the more peaks will be found. Default is `0.1`. threshold : float Sets the minimum distance (measured on y axis) required for a point to be accepted as extremal. Default is 0. except_around : interval (array or tuple), Overwrites the threshold to be 0 at the given interval. format is `(lower, higher)` or `[lower, higher]`. Default is None. side : str The side to use. Must be "both", "max" or "min". Default is "both". Returns ------- xmax : `array-like` x coordinates of the maximums ymax : `array-like` y coordinates of the maximums xmin : `array-like` x coordinates of the minimums ymin : `array-like` y coordinates of the minimums Note ---- When using "min" or "max" as side, all the detected minimal and maximal values will be returned, but only the given side will be recorded for further calculation. """ if side not in ("both", "min", "max"): raise ValueError("Side must be 'both', 'min' or 'max'.") if hasattr(self, "_is_onesided"): self._is_onesided = side != "both" x, y, ref, sam = self._safe_cast() xmax, ymax, xmin, ymin = find_peak( x, y, ref, sam, pro_max=pmax, pro_min=pmin, threshold=threshold, except_around=except_around, ) if side == "both": self.xmax = xmax self.xmin = xmin elif side == "min": self.xmin = xmin elif side == "max": self.xmax = xmax logger.info(f"{len(xmax)} max values and {len(xmin)} min values were found.") return xmax, ymax, xmin, ymin def _plot_SPP_if_valid(self, ax=None, **kwargs): """ Mark SPPs on the plot if they are valid. """ if ax is None: ax = self.plt if isinstance(self.positions, numbers.Number): if is_inside(self.positions, self.x): x_closest, idx = find_nearest(self.x, self.positions) try: ax.plot(x_closest, self.y_norm[idx], **kwargs) except (ValueError, TypeError): ax.plot(x_closest, self.y[idx], **kwargs) if isinstance(self.positions, np.ndarray) or isinstance( self.positions, Iterable ): if np.array(self.positions).ndim == 0: self.positions = np.atleast_1d(self.positions) # iterate over 0-d array: need to cast np.atleast_1d for i, val in enumerate(self.positions): if is_inside(self.positions[i], self.x): x_closest, idx = find_nearest(self.x, self.positions[i]) try: ax.plot(x_closest, self.y_norm[idx], **kwargs) except (ValueError, TypeError): ax.plot(x_closest, self.y[idx], **kwargs) def _format_delay(self): if self.delay is None: return "" if isinstance(self.delay, np.ndarray): if self.delay.size == 0: return 0 delay = np.atleast_1d(self.delay).flatten() return delay[0] elif isinstance(self.delay, (list, tuple)): return self.delay[0] elif isinstance(self.delay, numbers.Number): return self.delay elif isinstance(self.delay, str): try: delay = float(self.delay) except ValueError as e: raise TypeError("Delay value not understood.") from e return delay else: raise TypeError("Delay value not understood.") def _format_positions(self): if self.positions is None: return "Not given" if isinstance(self.positions, np.ndarray): positions = np.atleast_1d(self.positions).flatten() return ", ".join(map(str, positions)) elif isinstance(self.positions, (list, tuple)): return ", ".join(map(str, self.positions)) elif isinstance(self.positions, numbers.Number): return self.positions elif isinstance(self.positions, str): split = self.positions.split(",") try: positions = [float(p) for p in split] except ValueError as e: raise TypeError("Delay value not understood.") from e return ", ".join(map(str, positions)) else: raise TypeError("Delay value not understood.") def _prepare_SPP_data(self): pos_x, pos_y = [], [] if self.positions is not None: position = np.array(self.positions, dtype=np.float64).flatten() for i, val in enumerate(position): if is_inside(position[i], self.x): x_closest, idx = find_nearest(self.x, position[i]) try: pos_x.append(x_closest) pos_y.append(self.y_norm[idx]) except (ValueError, TypeError): pos_x.append(x_closest) pos_y.append(self.y[idx]) pos_x = np.array(pos_x) pos_y = np.array(pos_y) return pos_x, pos_y # TODO: Remove the duplicated logic. This function is in pysprint's init.py # and we can't circular import it. It should be moved to a separate file. def plot_outside(self, *args, **kwargs): """ Plot the current dataset out of the notebook. For detailed parameters see `Dataset.plot` function. """ backend = kwargs.pop("backend", "Qt5Agg") original_backend = plt.get_backend() try: plt.switch_backend(backend) self.plot(*args, **kwargs) plt.show(block=True) except (AttributeError, ImportError, ModuleNotFoundError) as err: raise ValueError( f"Couldn't set backend {backend}, you should manually " "change to an appropriate GUI backend. (Matplotlib 3.3.1 " "is broken. In that case use backend='TkAgg')." ) from err finally: plt.switch_backend(original_backend) def plot(self, ax=None, title=None, xlim=None, ylim=None, **kwargs): """ Plot the dataset. Parameters ---------- ax : matplotlib.axes.Axes, optional An axis to draw the plot on. If not given, it will plot on the last used axis. title : str, optional The title of the plot. xlim : tuple, optional The limits of x axis. ylim : tuple, optional The limits of y axis. kwargs : dict, optional Additional keyword arguments to pass to plot function. Note ---- If SPP positions are correctly set, it will mark them on plot. """ datacolor = kwargs.pop("color", "red") nospp = kwargs.pop("nospp", False) _unit = self._render_unit(self.unit, mpl=True) xlabel = f"$\lambda\,[{_unit}]$" if self.probably_wavelength else f"$\omega\,[{_unit}]$" overwrite = kwargs.pop("overwrite", None) if overwrite is not None: xlabel = overwrite if ax is None: ax = self.plt self.plt.ylabel("I") self.plt.xlabel(xlabel) if xlim: self.plt.xlim(xlim) if ylim: self.plt.ylim(ylim) if title: self.plt.title(title) else: ax.set(ylabel="I") ax.set(xlabel=xlabel) if xlim: ax.set(xlim=xlim) if ylim: ax.set(ylim=ylim) if title: ax.set(title=title) if np.iscomplexobj(self.y): ax.plot(self.x, np.abs(self.y), color=datacolor, **kwargs) else: try: ax.plot(self.x, self.y_norm, color=datacolor, **kwargs) except (ValueError, TypeError): ax.plot(self.x, self.y, color=datacolor, **kwargs) if not nospp: self._plot_SPP_if_valid(ax=ax, color="black", marker="o", markersize=10, label="SPP") def show(self): """ Equivalent with plt.show(). """ self.plt.show(block=True) @inplacify def normalize(self, filename=None, smoothing_level=0): """ Normalize the interferogram by finding upper and lower envelope on an interactive matplotlib editor. Points can be deleted with key `d` and inserted with key `i`. Also points can be dragged using the mouse. On complete just close the window. Must be called with interactive backend. The best practice is to call this function inside `~pysprint.interactive` context manager. Parameters ---------- filename : str, optional Save the normalized interferogram named by filename in the working directory. If not given it will not be saved. Default None. smoothing_level : int, optional The smoothing level used on the dataset before finding the envelopes. It applies Savitzky-Golay filter under the hood. Default is 0. """ x, y, _, _ = self._safe_cast() if smoothing_level != 0: x, y = savgol(x, y, [], [], window=smoothing_level) _l_env = DraggableEnvelope(x, y, "l") y_transform = _l_env.get_data() _u_env = DraggableEnvelope(x, y_transform, "u") y_final = _u_env.get_data() self.y = y_final self.y_norm = y_final self._is_normalized = True self.plt.title("Final") self.plot() self.show() if filename: if not filename.endswith(".txt"): filename += ".txt" np.savetxt(filename, np.column_stack((self.x, self.y)), delimiter=",") print(f"Successfully saved as {filename}.") return self def open_SPP_panel(self, header=None): """ Opens the interactive matplotlib editor for SPP data. Use `i` button to add a new point, use `d` key to delete one. The delay field is parsed to only get the numeric values. Close the window on finish. Must be called with interactive backend. The best practice is to call this function inside `~pysprint.interactive` context manager. Parameters ---------- header : str, optional An arbitary string to include as header. This can be any attribute's name, or even metadata key. """ if header is not None: if isinstance(header, str): head = getattr(self, header, None) metahead = self.meta.get(header, None) info = head or metahead or header else: info = None else: info = None spp_x, spp_y = self._prepare_SPP_data() _spp = SPPEditor( self.x, self.y_norm, info=info, x_pos=np.array(spp_x), y_pos=np.array(spp_y) ) textbox = _spp._get_textbox() textbox.set_val(self._format_delay()) _spp._show() # We need to split this into separate lines, # because empty results are broadcasted twice. delay, positions = _spp.get_data() self.delay, self.positions = delay, positions def emit(self): """ Emit the current SPP data. Returns ------- delay : np.ndarray The delay value for the current dataset, shaped exactly like positions. positions : np.ndarray The given SPP positions. """ if self.positions is None: raise ValueError("SPP positions are missing.") if self.delay is None: raise ValueError("Delay value is missing.") # Important: Use underscored variables to avoid invoking the # setter again, which invokes the callback again, resulting in # a never-ending cycle. if not isinstance(self._positions, np.ndarray): self._positions = np.asarray(self.positions) if not isinstance(self.delay, np.ndarray): self._delay = np.ones_like(self._positions) * self._delay return np.atleast_1d(self.delay), np.atleast_1d(self.positions) def set_SPP_data(self, delay, positions, force=False): """ Set the SPP data (delay and SPP positions) for the dataset. Parameters ---------- delay : float The delay value that belongs to the current interferogram. Must be given in `fs` units. positions : float or iterable The SPP positions that belong to the current interferogram. Must be float or sequence of floats (tuple, list, np.ndarray, etc.) force : bool, optional Can be used to set specific SPP positions which are outside of the dataset's range. Note that in most cases you should avoid using this option. Default is `False`. Note ---- Every position given must be in the current dataset's range, otherwise `ValueError` is raised. Be careful to change domain to frequency before feeding values into this function. """ if not isinstance(delay, float): delay = float(delay) delay = np.array(np.ones_like(positions) * delay) self.delay = delay if force: with suppress(ValueError): self._positions = positions else: self.positions = positions # trigger the callback here too try: self.callback(self, self.parent) except ValueError: pass class MimickedDataset(Dataset): ''' Class that pretends to be a dataset, but its x-y values are missing. It allows to set delay and SPP positions arbitrarily. ''' def __init__(self, delay, positions, *args, **kwargs): if delay is None or positions is None: raise ValueError("must specify SPP data.") x = np.empty(1) y = np.empty(1) super().__init__(x=x, y=y, *args, **kwargs) self.set_SPP_data(delay=delay, positions=positions, force=True) @contextmanager def _suppress_callbacks(self): try: self.restore_parent = self.parent self.restore_callback = self.callback self.parent = None self.callback = lambda x, y: (_ for _ in ()).throw(ValueError('mimicked')) yield finally: self.parent, self.callback = self.restore_parent, self.restore_callback def plot(self, *args, **kwargs): if self.x.size == 1: self.plt.text(0.31, 0.5, 'Dataset is missing.', size=15) # Redefine getter-setter without boundscheck @property def positions(self): return self._positions @positions.setter def positions(self, value): if isinstance(value, np.ndarray) or isinstance(value, Iterable): for val in value: if not isinstance(val, numbers.Number): raise ValueError( f"Expected numeric values, got {type(val)} instead." ) self._positions = value try: self.callback(self, self.parent) except ValueError: pass # delay or position is missing def to_dataset(self, x, y=None, ref=None, sam=None, parse=True, **kwargs): if parse: if y is not None: raise ValueError("cannot specify `y` explicitly if `parse=True`.") self.parent.ifg_names.append(x) if ref is not None and sam is not None: self.parent.sam_names.append(sam) self.parent.ref_names.append(ref) ds = Dataset.parse_raw(x, ref=ref, sam=sam, callback=self.callback, parent=self.parent, **kwargs) else: ds = Dataset(x=x, y=y, ref=ref, sam=sam, callback=self.callback, parent=self.parent, **kwargs) # replace the MimickedDataset with the real one # FIXME: need to invalidate 1 item in cache, not all idx = self.parent._mimicked_index(self) ds.parent._mimicked_set[idx] = ds ds.parent.__getitem__.cache_clear() # drop the reference self.parent._container.pop(self, None) self.parent = None self.callback = lambda x, y: (_ for _ in ()).throw(ValueError('mimicked')) # with self._suppress_callbacks(): ds.set_SPP_data(delay=self.delay, positions=self.positions, force=True) return ds
[ "leeh123peter@gmail.com" ]
leeh123peter@gmail.com
513c7831beef1af21d4ecefc4ab419f8069a9ef7
af5673178ad4cd5dd153ad0cece0e9f8a171bdd9
/inventory/models.py
b7894aa7db25e934ab44b5f7c3efbea888c9ea4b
[]
no_license
saadatqadri/unlyst
d0bd21e6ae7173acc4392c666561dc7ebd6caa6a
7fc31a8e33ecb625f093acbb7c445adc0e63e0d7
refs/heads/master
2016-08-03T11:58:46.145149
2014-09-20T13:51:38
2014-09-20T13:51:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,263
py
from django.db import models import random import string from django.core.urlresolvers import reverse # Create your models here. def random_key(size): return ''.join([random.choice(string.letters + string.digits) for i in range(size)]) class Property(models.Model): HOME_TYPE_CHOICES = ( ('H', 'House'), ('C', 'Condominium') ) CITY_CHOICES = ( ('TO', 'Toronto'), ('VAN', 'Vancouver') ) HOUSE_TYPE_CHOICES = ( ('DETACHED', 'Detached'), ('SEMI', 'Semi-detached'), ('ATTACHED', 'Attached') ) BEDROOM_CHOICES = ( ('ONE', '1'), ('ONEHALF', '1.5'), ('TWO', '2'), ('THREE', '3'), ('FOUR', '4'), ('FIVE', '5') ) BATH_CHOICES = ( ('ONE', '1'), ('TWO', '2'), ('THREE', '3'), ('FOUR', '4'), ('FIVE', '5') ) STATUS_CHOICES = ( ('OFFER', 'Make me an offer'), ('SELL', 'Would sell for the right price'), ('NEVER', 'Would never sell') ) identifier = models.CharField(max_length=16, unique=True) home_type = models.CharField(max_length=25, choices=HOME_TYPE_CHOICES) street_number = models.PositiveIntegerField() street_address = models.CharField(max_length=255) suite_number = models.PositiveIntegerField(blank=True) neighborhood = models.CharField(max_length=255) city = models.CharField(max_length=255, choices=CITY_CHOICES) house_type = models.CharField(max_length=255, choices=HOUSE_TYPE_CHOICES) lot_size_frontage = models.IntegerField() lot_size_depth = models.IntegerField() num_beds = models.CharField(max_length=25, choices=BEDROOM_CHOICES) num_baths = models.CharField(max_length=25, choices=BATH_CHOICES) num_park = models.IntegerField() unlysted_value = models.PositiveIntegerField(blank=True) status = models.CharField(max_length=25, choices=STATUS_CHOICES) photo = models.ImageField(upload_to='images', blank=True) def __unicode__(self): return '_'.join([ str(self.street_number), self.street_address, self.city, ]) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if self.identifier is None or len(self.identifier) == 0: self.identifier = random_key(16) models.Model.save(self, force_insert, force_update, using, update_fields) def get_absolute_url(self): return reverse('property-view', kwargs={'pk': self.id})
[ "saadat@vermillionapps.com" ]
saadat@vermillionapps.com
bfd5921d432ef852a048251f64ed461d57cc67a5
ea1d6d4ba29268c17523eaa7fb64cad18cbb5e1c
/scrapy_realestate/pipelines.py
7791c9e3a29fce209e80bd201f185d4460104b12
[]
no_license
zhongw117/scrapy_realestate
c6e671545bfa13dec382a2dd7edd4e75023a8cbf
a3e1d90e965e18461db3b62fb17c5e676c922c18
refs/heads/master
2020-05-17T05:21:48.548298
2019-04-30T02:06:12
2019-04-30T02:06:12
183,530,190
0
0
null
null
null
null
UTF-8
Python
false
false
297
py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html class ScrapyRealestatePipeline(object): def process_item(self, item, spider): return item
[ "zhongw117@gmail.com" ]
zhongw117@gmail.com
2fdd5d3993d5c05d754dc6d7e2ab5523a6b68629
9ee8de4544d9de8b9690bf425245103d0b77fc5b
/trimesh/path/io/svg_io.py
25dfb85679aea6f0a8c9840591d4bcb980973722
[ "MIT" ]
permissive
Artur-Sampaio/trimesh
80a926495b1f71eedc99fb82130575841c4c9ae7
3743ae2d932d9f7eab9ad69e2626e1646589bb2c
refs/heads/master
2020-03-23T13:17:14.545609
2018-07-20T16:15:54
2018-07-20T16:15:54
141,610,010
0
0
MIT
2018-07-19T17:16:51
2018-07-19T17:16:51
null
UTF-8
Python
false
false
7,865
py
import numpy as np from string import Template from collections import deque from xml.dom.minidom import parseString as parse_xml from .. import entities as entities_mod from ..arc import arc_center from ...resources import get_resource from ...constants import log from ...constants import res_path as res from ... import util _template_svg = Template(get_resource('svg.xml.template')) try: from svg.path import parse_path except BaseException: log.warning('SVG path loading unavailable!') def svg_to_path(file_obj, file_type=None): """ Load an SVG file into a Path2D object. Parameters ----------- file_obj: open file object file_type: unused Returns ----------- loaded: dict with kwargs for Path2D constructor """ # first, we grab all of the path strings from the xml file xml = parse_xml(file_obj.read()) paths = [p.attributes['d'].value for p in xml.getElementsByTagName('path')] return _svg_path_convert(paths) def _svg_path_convert(paths): """ Convert an SVG path string into a Path2D object Parameters ------------- paths: list of strings Returns ------------- drawing: loaded, dict with kwargs for Path2D constructor """ def complex_to_float(values): return np.array([[i.real, i.imag] for i in values]) def load_line(svg_line): points = complex_to_float([svg_line.point(0.0), svg_line.point(1.0)]) if not starting: points[0] = vertices[-1] entities.append(entities_mod.Line(np.arange(2) + len(vertices))) vertices.extend(points) def load_arc(svg_arc): points = complex_to_float([svg_arc.start, svg_arc.point(.5), svg_arc.end]) if not starting: points[0] = vertices[-1] entities.append(entities_mod.Arc(np.arange(3) + len(vertices))) vertices.extend(points) def load_quadratic(svg_quadratic): points = complex_to_float([svg_quadratic.start, svg_quadratic.control, svg_quadratic.end]) if not starting: points[0] = vertices[-1] entities.append(entities_mod.Bezier(np.arange(3) + len(vertices))) vertices.extend(points) def load_cubic(svg_cubic): points = complex_to_float([svg_cubic.start, svg_cubic.control1, svg_cubic.control2, svg_cubic.end]) if not starting: points[0] = vertices[-1] entities.append(entities_mod.Bezier(np.arange(4) + len(vertices))) vertices.extend(points) entities = deque() vertices = deque() loaders = {'Arc': load_arc, 'Line': load_line, 'CubicBezier': load_cubic, 'QuadraticBezier': load_quadratic} for svg_string in paths: starting = True for svg_entity in parse_path(svg_string): loaders[svg_entity.__class__.__name__](svg_entity) loaded = {'entities': np.array(entities), 'vertices': np.array(vertices)} return loaded def export_svg(drawing, return_path=False, **kwargs): """ Export a Path2D object into an SVG file. Parameters ----------- drawing: Path2D object return_path: bool, if True return only path string Returns ----------- as_svg: str, XML formatted as SVG """ if not util.is_instance_named(drawing, 'Path2D'): raise ValueError('drawing must be Path2D object!') points = drawing.vertices.view(np.ndarray).copy() def circle_to_svgpath(center, radius, reverse): radius_str = format(radius, res.export) path_str = ' M ' + format(center[0] - radius, res.export) + ',' path_str += format(center[1], res.export) path_str += ' a ' + radius_str + ',' + radius_str path_str += ',0,1,' + str(int(reverse)) + ',' path_str += format(2 * radius, res.export) + ',0' path_str += ' a ' + radius_str + ',' + radius_str path_str += ',0,1,' + str(int(reverse)) + ',' path_str += format(-2 * radius, res.export) + ',0 Z' return path_str def svg_arc(arc, reverse): """ arc string: (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ large-arc-flag: greater than 180 degrees sweep flag: direction (cw/ccw) """ arc_idx = arc.points[::((reverse * -2) + 1)] vertices = points[arc_idx] vertex_start, vertex_mid, vertex_end = vertices center_info = arc_center(vertices) C, R, angle = (center_info['center'], center_info['radius'], center_info['span']) if arc.closed: return circle_to_svgpath(C, R, reverse) large_flag = str(int(angle > np.pi)) sweep_flag = str(int(np.cross(vertex_mid - vertex_start, vertex_end - vertex_start) > 0.0)) arc_str = move_to(arc_idx[0]) arc_str += 'A {},{} 0 {}, {} {},{}'.format(R, R, large_flag, sweep_flag, vertex_end[0], vertex_end[1]) return arc_str def move_to(vertex_id): x_ex = format(points[vertex_id][0], res.export) y_ex = format(points[vertex_id][1], res.export) move_str = ' M ' + x_ex + ',' + y_ex return move_str def svg_discrete(entity, reverse): """ Use an entities discrete representation to export a curve as a polyline """ discrete = entity.discrete(points) if reverse: discrete = discrete[::-1] template = ' M {},{} ' + (' L {},{}' * (len(discrete) - 1)) result = template.format(*discrete.reshape(-1)) return result def convert_path(path, reverse=False, close=True): path = path[::(reverse * -2) + 1] converted = [] for i, entity_id in enumerate(path): entity = drawing.entities[entity_id] etype = entity.__class__.__name__ if etype in converters: converted.append(converters[etype](entity, reverse)) else: converted.append(svg_discrete(entity, reverse)) # remove leading and trailing whitespace converted = ' '.join(converted) + ' ' return converted # only converters where we want to do something # other than export a curve as a polyline converters = {'Arc': svg_arc} path_str = '' for path_index, path in enumerate(drawing.paths): reverse = not (path_index in drawing.root) path_str += convert_path(path, reverse=reverse, close=True) # entities which haven't been included in a closed path path_str += convert_path(drawing.dangling, reverse=False, close=False) path_str = path_str.strip() if return_path: return path_str # format as XML if 'stroke_width' in kwargs: stroke_width = float(kwargs['stroke_width']) else: stroke_width = drawing.extents.max() / 800.0 subs = {'PATH_STRING': path_str, 'MIN_X': points[:, 0].min(), 'MIN_Y': points[:, 1].min(), 'WIDTH': drawing.extents[0], 'HEIGHT': drawing.extents[1], 'STROKE': stroke_width} result = _template_svg.substitute(subs) return result
[ "mik3dh@gmail.com" ]
mik3dh@gmail.com
7f2a3f492125f3bb40383273ce56da4b026d57ab
b7cdc913afdf58f3b1762dbb9708f7cfb38a8887
/cve_2_MSF_exploit_Mapping/mapper_cve_exploit.py
437b0b433b567fa2ca07a836cb3710bca29f687b
[]
no_license
Gh0st0ne/Xerror
8173b5e3085921cbb4e5020e7a451d69839a4450
4b208c4e518ec432af6eeeeefc127b343c2c33b9
refs/heads/master
2022-11-30T13:24:49.992893
2020-08-12T06:38:31
2020-08-12T06:38:31
287,769,040
1
0
null
2020-08-15T15:04:28
2020-08-15T15:04:28
null
UTF-8
Python
false
false
3,444
py
from opvs_csv_parser import openvas_csv_parse_detail from msf_cve_extracter import msf_csv_extract class mapper_opn2msf_cve(): def __init__(self,openvas_csv_file, msf_module_file): self.openvas_csv_file = openvas_csv_file self.msf_module_file = msf_module_file self.opvas_csv = openvas_csv_parse_detail(self.openvas_csv_file) self.op_csv = self.opvas_csv.openvas_cve_dict() #contain openvas host cve and ip {'port#':cve , 'ip_addr':'' } self.op_resul = self.opvas_csv.openvas_result_dict() #contain all result e.g resul['ports']['80']['severity']. ip,host self.msf_cve = msf_csv_extract(self.msf_module_file) self.msf_cve = self.msf_cve.msf_exploit_cve() self.msf_cve_lst = [] self.msf_exploit = [] self.ip_addr = '' self.host_port = [] self.host_cve = [] self.host_cve_port_dict = {} #final resul for cve as key and port value self.msf_cve_seperator() self.openvas_cve_seperator() def msf_cve_seperator(self): for k,v in self.msf_cve.items(): if k: self.msf_cve_lst.append(k) self.msf_exploit.append(v) # print len(self.msf_cve_lst) # print len(self.msf_exploit) def openvas_cve_seperator(self): # print self.op_csv for k,v in self.op_csv.items(): if k =='ip_addr': self.ip_addr = v else: self.host_port.append(k) v = v.replace(" ","") self.host_cve.append(v) one_port_cve = v.split(",") for i in one_port_cve: self.host_cve_port_dict[i] = k # k= port number and i= cve number for port def mapper(self): print "*"*65 print " Mapped Exploits " print "*"*65 # print self.ip_addr temp_final_mapping_resul = {} temp_final_mapping_resul['ip'] = self.ip_addr for i in self.msf_cve_lst: temp_cve_mapping_resul = [] for j in self.host_cve: if i == j: cve = i serv_port = self.host_cve_port_dict[i] exploit = self.msf_cve[i] vul_sevrity = self.op_resul['ports'][self.host_cve_port_dict[i]]['sevrity'] vul_protocol= self.op_resul['ports'][self.host_cve_port_dict[i]]['proto'] temp_cve_mapping_resul.append(cve) temp_cve_mapping_resul.append(serv_port) temp_cve_mapping_resul.append(vul_protocol) temp_cve_mapping_resul.append(vul_sevrity) temp_cve_mapping_resul.append(exploit) temp_final_mapping_resul[cve] = temp_cve_mapping_resul print temp_cve_mapping_resul # resul ="" # resul = i+","+self.host_cve_port_dict[i]+","+self.msf_cve[i] # print resul # print self.op_resul['ports'][self.host_cve_port_dict[i]]['sevrity'] # print cve,port,exploit,vul_sevrity # print temp_final_mapping_resul.keys() print "*"*65 # print temp_final_mapping_resul['ip'] # print temp_final_mapping_resul['CVE-2007-2447'] # print # print ''' return will be mapped cve with msf exploits dictionary contains ip cve :[list of details e.g port# porotocol rank and exploit name ] e.g temp_final_mapping_resul['CVE-2004-2687'] ''' print temp_final_mapping_resul if __name__ == '__main__': opvas_csv_file = '< openvas host scanned CSV file path >' msf_exploit2cve_file = '/root/Desktop/cve2exploit_Mapping/msf_module_result/msf_module_cve.txt' #this hard coded msf module file containg exploit and cve number obj= mapper_opn2msf_cve(opvas_csv_file,msf_exploit2cve_file) print obj.mapper()
[ "noreply@github.com" ]
Gh0st0ne.noreply@github.com
8fe758f58ef3eefdccf1cc0bf68844bb55754957
7ef433b1407e0ab127df87b2b8c7d99f2c5fadf3
/CVapp1/wsgi.py
bbc35d2251f8aaf90db57282c03a6291e5f72291
[]
no_license
BriamB/CVapp_Master
44f15b013714491942fd02a7aed3e144eca75c2d
060fc62ec63a94bca26857fe889e8752d028e5e1
refs/heads/master
2023-07-31T07:24:48.433435
2020-05-02T01:33:45
2020-05-02T01:33:45
260,590,767
0
0
null
2021-09-22T18:57:21
2020-05-02T01:15:39
JavaScript
UTF-8
Python
false
false
389
py
""" WSGI config for CVapp1 project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CVapp1.settings') application = get_wsgi_application()
[ "briam.bermudez11@gmail.com" ]
briam.bermudez11@gmail.com
3f1e83ad6d11ac3c3949bd84f6a2c941c6635438
7cb626363bbce2f66c09e509e562ff3d371c10c6
/multimodel_inference/py3_v1/sc1ilsm.py
bb652a6518be79b22dfb762c1cdb162f2fa53497
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
z0on/AFS-analysis-with-moments
76bfd6b0361ab7e9173144dbd21b6fa2c7bf1795
eea4735b3b6fbe31c4e396da3d798387884a1500
refs/heads/master
2023-07-31T20:49:20.865161
2023-07-19T06:57:32
2023-07-19T06:57:32
96,915,117
4
5
null
2020-09-02T17:39:08
2017-07-11T16:38:03
Python
UTF-8
Python
false
false
3,521
py
#!/usr/bin/env python3 # simple "primary contact" # split, same size but two migration epochs in each pop, no migration in first epoch, symmetric in second epoch # genomic islands # n(para): 8 import matplotlib matplotlib.use('PDF') import moments import pylab import random import matplotlib.pyplot as plt import numpy as np from numpy import array from moments import Misc,Spectrum,Numerics,Manips,Integration,Demographics1D,Demographics2D import sys infile=sys.argv[1] pop_ids=[sys.argv[2],sys.argv[3]] projections=[int(sys.argv[4]),int(sys.argv[5])] if len(sys.argv)==9: params = np.loadtxt(sys.argv[8], delimiter=" ", unpack=False) else: params=[1,1,1,1,1,1,0.5,0.01] # mutation rate per sequenced portion of genome per generation: for A.millepora, 0.02 mu=float(sys.argv[6]) # generation time, in thousand years: 0.005 (5 years) gtime=float(sys.argv[7]) # set Polarized=False below for folded AFS analysis fs = moments.Spectrum.from_file(infile) data=fs.project(projections) ns=data.sample_sizes np.set_printoptions(precision=3) #------------------- # split into unequal pop sizes with asymmetrical migration def sc1il(params , ns): # p_misid: proportion of misidentified ancestral states nu1_1, nu2_1, T0, T, m,mi, P, p_misid = params sts = moments.LinearSystem_1D.steady_state_1D(ns[0] + ns[1]) fs = moments.Spectrum(sts) fs = moments.Manips.split_1D_to_2D(fs, ns[0], ns[1]) fs.integrate([nu1_1, nu2_1], T0, m = np.array([[0, 0], [0, 0]])) fs.integrate([nu1_1, nu2_1], T, m = np.array([[0, m], [m, 0]])) stsi = moments.LinearSystem_1D.steady_state_1D(ns[0] + ns[1]) fsi = moments.Spectrum(stsi) fsi = moments.Manips.split_1D_to_2D(fsi, ns[0], ns[1]) fsi.integrate([nu1_1, nu2_1], T0, m = np.array([[0, 0], [0, 0]])) fsi.integrate([nu1_1, nu2_1], T, m = np.array([[0, mi], [mi, 0]])) fs2=P*fsi+(1-P)*fs return (1-p_misid)*fs2 + p_misid*moments.Numerics.reverse_array(fs2) func=sc1il upper_bound = [100, 100, 100, 100, 200,200,0.999,0.25] lower_bound = [1e-3,1e-3,1e-3,1e-3,1e-5,1e-5,0.001,1e-5] params = moments.Misc.perturb_params(params, fold=2, upper_bound=upper_bound, lower_bound=lower_bound) poptg = moments.Inference.optimize_log(params, data, func, lower_bound=lower_bound, upper_bound=upper_bound, verbose=False, maxiter=30) # extracting model predictions, likelihood and theta model = func(poptg, ns) ll_model = moments.Inference.ll_multinom(model, data) theta = moments.Inference.optimal_sfs_scaling(model, data) # random index for this replicate ind=str(random.randint(0,999999)) # plotting demographic model plot_mod = moments.ModelPlot.generate_model(func, poptg, ns) moments.ModelPlot.plot_model(plot_mod, save_file="sc1ilsm_"+ind+".png", pop_labels=pop_ids, nref=theta/(4*mu), draw_scale=False, gen_time=gtime, gen_time_units="KY", reverse_timeline=True) # bootstrapping for SDs of params and theta # printing parameters and their SDs print( "RESULT","sc1ilsm",ind,len(params),ll_model,sys.argv[1],sys.argv[2],sys.argv[3],poptg,theta) # plotting quad-panel figure witt AFS, model, residuals: moments.Plotting.plot_2d_comp_multinom(model, data, vmin=0.1, resid_range=3, pop_ids =pop_ids) plt.savefig("sc1ilsm_"+ind+"_"+sys.argv[1]+"_"+sys.argv[2]+"_"+sys.argv[3]+"_"+sys.argv[4]+"_"+sys.argv[5]+'.pdf')
[ "matz@utexas.edu" ]
matz@utexas.edu
673a0671fd745f80672d9b21df0990c2a0e2fed8
c266d942da6da24812abf8a8dbe0292e63b16fa8
/reinforcement_learning/0x03-policy_gradients/policy_gradient.py
44c52ec4a85c94bbd7dfd6012d83dc2692f49d5e
[]
no_license
Viiic98/holbertonschool-machine_learning
447be16c096bb6f3c8983c9479cc5fada7bf0945
fe8fe88a43b7a86f0c4b05540751847e7c1c418b
refs/heads/master
2023-03-28T16:03:15.429720
2021-03-31T01:11:36
2021-03-31T01:11:36
279,635,527
0
0
null
null
null
null
UTF-8
Python
false
false
833
py
#!/usr/bin/env python3 """ Policy gradient """ import numpy as np def policy(matrix, weight): """ computes to policy with a weight of a matrix """ z = matrix.dot(weight) exp = np.exp(z) return exp / exp.sum() def policy_gradient(state, weight): """ computes the Monte-Carlo policy gradient based on a state and a weight matrix state: matrix representing the current observation of the environment weight: matrix of random weight Return: the action and the gradient (in this order) """ P = policy(state, weight) action = np.random.choice(len(P[0]), p=P[0]) s = P.reshape(-1, 1) softmax = np.diagflat(s) - np.dot(s, s.T) softmax = softmax[action, :] dlog = softmax / P[0, action] gradient = state.T.dot(dlog[None, :]) return action, gradient
[ "xathovic@gmail.com" ]
xathovic@gmail.com
40e6d94b00771143f58120413635d8f3c1d68756
7b494d12cadb2dbdc18adbecbf8fae222afdb39c
/aoc_cqkh42/year_2016/day_12.py
9242632e2de07ca0728f21c4257a765bba47a6c5
[ "MIT" ]
permissive
cqkh42/advent-of-code
3849b3cea4699e336f5672b0b4e297c59ac9f339
0204afb638c5fef8478201fd5b061708497b7cee
refs/heads/main
2023-08-08T20:40:58.623375
2023-07-23T20:58:49
2023-07-23T20:58:49
315,266,572
1
0
null
null
null
null
UTF-8
Python
false
false
1,206
py
from aoc_cqkh42.helpers.base_solution import BaseSolution class Solution(BaseSolution): def part_a(self): registers = {'a': 0, 'b': 0, 'c': 0, 'd': 0} instructions = self.input_.split('\n') return run_program(instructions, registers) def part_b(self): registers = {'a': 0, 'b': 0, 'c': 1, 'd': 0} instructions = self.input_.split('\n') return run_program(instructions, registers) def run_program(instructions, registers): instructions = [instruction.split() for instruction in instructions] index = 0 while True: try: cmd, input_1, *values = instructions[index] except IndexError: return registers['a'] else: incr = 1 if cmd == 'cpy': val = registers.get(input_1, input_1) registers[values[0]] = int(val) elif cmd == 'inc': registers[input_1] += 1 elif cmd == 'dec': registers[input_1] -= 1 elif cmd == 'jnz': val = registers.get(input_1, input_1) if int(val): incr = int(values[0]) index += incr
[ "jackcooper93@gmail.com" ]
jackcooper93@gmail.com
1d18d979e8f6e6fc1a36dcea21ce5d57e62cc090
a14904922d563f25148ab1ce66cc26c0782684cc
/pub_n_sub/script/py_msg_sub.py
4d1d46c84870eac1a802c3c6464edc5fa06d2ad5
[ "MIT" ]
permissive
VirtuosoRobotics/ROS_Basic
0fb16066b8f60dd73da5bee3de3b6e6ef3dfe2c6
467d54c23a965ea7059cba7c2df790c94753a58a
refs/heads/master
2023-02-28T22:43:41.301648
2021-02-04T15:30:23
2021-02-04T15:30:23
189,814,317
1
0
null
null
null
null
UTF-8
Python
false
false
314
py
#!/usr/bin/env python import rospy from std_msgs.msg import String from pub_n_sub.msg import Num def callback(data): print data def listener(): rospy.init_node('listener', anonymous=True) rospy.Subscriber("custom_msg", Num, callback) rospy.spin() if __name__ == '__main__': listener()
[ "eric@virtuosorobotics.com" ]
eric@virtuosorobotics.com
146d3e0d5dd3fb693d043ac9690c393cb0324502
c4058023aee1730cf038a318823e24718760c1e7
/2020/day23.py
ce45e8268f58976fd9e74177a340f370f61138fb
[]
no_license
LiamSarwas/Advent-of-Code
383adcf8dd240678f20ecb4f67a015d61351380a
4016ed18fab338554297a721b54eb0fe248bd951
refs/heads/master
2022-12-14T11:30:34.095498
2022-12-13T06:00:08
2022-12-13T06:00:08
225,778,461
1
0
null
null
null
null
UTF-8
Python
false
false
3,268
py
import time import itertools import math from pathlib import Path FILE_DIR = Path(__file__).parent class Node(): def __init__(self, cup, next_node): self.cup = cup self.next_node = next_node def __repr__(self): return f"{self.cup} --> {self.next_node.cup}" def construct_linked_list(input_data, part=1): nodes = {} head_node = Node(input_data[0], None) nodes[input_data[0]] = head_node for i in range(1, len(input_data)): new_node = Node(input_data[i], None) nodes[input_data[i-1]].next_node = new_node nodes[input_data[i]] = new_node if part == 1: nodes[input_data[-1]].next_node = head_node return head_node, nodes else: new_node = Node(10, None) nodes[input_data[-1]].next_node = new_node nodes[10] = new_node for i in range(11, 1000001): new_node = Node(i, None) nodes[i-1].next_node = new_node nodes[i] = new_node nodes[1000000].next_node = head_node return head_node, nodes def part_one(input_data): starting_node, nodes = construct_linked_list(input_data) for i in range(100): pulled_nodes = [starting_node.next_node, starting_node.next_node.next_node, starting_node.next_node.next_node.next_node] starting_node.next_node = pulled_nodes[-1].next_node pulled_node_labels = {node.cup for node in pulled_nodes} insert_position = starting_node.cup - 1 if insert_position == 0: insert_position = 9 while insert_position in pulled_node_labels: insert_position -= 1 if insert_position == 0: insert_position = 9 insert_node = nodes[insert_position] insert_next_node = insert_node.next_node insert_node.next_node = pulled_nodes[0] pulled_nodes[-1].next_node = insert_next_node starting_node = starting_node.next_node res = "" current_node = nodes[1] for i in range(8): res += str(current_node.next_node.cup) current_node = current_node.next_node return res def part_two(input_data): starting_node, nodes = construct_linked_list(input_data, part=2) for i in range(10000000): pulled_nodes = [starting_node.next_node, starting_node.next_node.next_node, starting_node.next_node.next_node.next_node] starting_node.next_node = pulled_nodes[-1].next_node pulled_node_labels = {node.cup for node in pulled_nodes} insert_position = starting_node.cup - 1 if insert_position == 0: insert_position = 1000000 while insert_position in pulled_node_labels: insert_position -= 1 if insert_position == 0: insert_position = 1000000 insert_node = nodes[insert_position] insert_next_node = insert_node.next_node insert_node.next_node = pulled_nodes[0] pulled_nodes[-1].next_node = insert_next_node starting_node = starting_node.next_node node_one = nodes[1] return node_one.next_node.cup * node_one.next_node.next_node.cup if __name__ == "__main__": DATA = "215694783" DATA = [int(c) for c in DATA] print(part_one(DATA)) print(part_two(DATA))
[ "lsarwas@domaintools.com" ]
lsarwas@domaintools.com
a5a6dca21d1c53e003df13f012704d0743930e8d
8f383ae81935c3746dfb721aab638d530d07ec78
/API_Testing/TestSuite/testSuite-2.py
eb0e646db570b767bd2b9fdeb60f20624f0a43ce
[]
no_license
adnanhanif793/Assignment
f5f490bc8bb4dca448aaa66aa87591f6cbf76fd2
449422dd7356aceb0e71fc0fb8efaa842062283b
refs/heads/master
2022-10-20T19:37:33.405945
2020-01-07T06:53:56
2020-01-07T06:53:56
211,309,078
0
1
null
null
null
null
UTF-8
Python
false
false
2,113
py
# importing Modules import requests import jsonpath import json def test_allapi(): # get rest API End point url = 'https://reqres.in/api/users?page=1' print(url) # Execute the rest GET API v_response = requests.get(url) # response code of the request v_responsecode = v_response.status_code # convert the data into JSON json_data = json.loads(v_response.text) # get the per_page value v_per_page = jsonpath.jsonpath(json_data, 'per_page') # get the number of students value v_student_records = jsonpath.jsonpath(json_data, 'data') v_count_records = len(v_student_records[0]) # assert condition assert v_responsecode == 200 assert v_per_page[0] == 3 assert v_count_records == v_per_page[0] # store the Dynamic data v_id = jsonpath.jsonpath(json_data, 'data[1].id') v_email = jsonpath.jsonpath(json_data, 'data[1].email') v_first_name = jsonpath.jsonpath(json_data, 'data[1].first_name') v_last_name = jsonpath.jsonpath(json_data, 'data[1].last_name') # Get the single user details url = 'http://reqres.in/api/users/' + str(v_id[0]) print(url) # Execute the rest GET API v_response = requests.get(url) # response code of the request v_responsecode = v_response.status_code json_data = json.loads(v_response.text) v_id_1 = jsonpath.jsonpath(json_data, 'data.id') v_email_1 = jsonpath.jsonpath(json_data, 'data.email') v_first_name_1 = jsonpath.jsonpath(json_data, 'data.first_name') v_last_name_2 = jsonpath.jsonpath(json_data, 'data.last_name') # assert condition assert v_responsecode == 200 assert v_id_1 == v_id assert v_email_1 == v_email assert v_first_name_1 == v_first_name assert v_last_name_2 == v_last_name # Delete the ID url = 'http://reqres.in/api/users/' + str(v_id[0]) print(url) # Execute the rest GET API v_response = requests.delete(url) # response code of the request v_responsecode = v_response.status_code # assert condition assert v_responsecode == 204 assert len(v_response.text) == 0
[ "adnanhanif793@gmail.com" ]
adnanhanif793@gmail.com
8ed28eff95225efc2d6bc1bbf5c5995ad0914066
40075340d4f8f26da3c15791837b9d411cde2af6
/Labs/Lab05/game_driver.py
c8d8614a3458711835a16a3af4738473f9d6cc58
[]
no_license
dlee533/comp1510-programming-methods
54117912afc5bd8080b36b5726ef185f9668f65e
3114aa37d350f92ea447e894e4320ab633ddce1d
refs/heads/master
2023-04-10T11:05:55.033152
2021-04-23T07:27:35
2021-04-23T07:27:35
360,799,467
0
0
null
null
null
null
UTF-8
Python
false
false
2,473
py
from Lab05 import lab05 def main(): print("Generate consonant/Generate vowel function works the following way...") print("Consonant : ", lab05.generate_consonant()) print("Vowel : ", lab05.generate_vowel()) print("The returned consonant and vowel then concatenates to form a single syllable. Like so..") print(lab05.generate_syllable()) print("The returned syllable then concatenates to form a single name of the length of your choice.") syllables = int(input("Enter the number of syllables you want your name to be: ")) print("Name: ", lab05.generate_name(syllables)) print("__________________________________________________________________________________________________") print("Then the choose inventory function accepts two arguments, one with inventory list and the other\n" "number of items purchased. Say there are items list of acid, arrows, battleaxe, blowgun, book, \n" "crossbow, crowbar in the inventory.") inventory = ["acid", "arrows", "battleaxe", "blowgun", "book", "crossbow", "crowbar"] item_number = int(input("How many items wold you like to purchase? ")) items = lab05.choose_inventory(inventory, item_number) print("You have", end=" ") for item in items: print("<" + item + ">", end=" ") print() print("__________________________________________________________________________________________________") print("You can then roll the die to determine your character's attribute values.\n" "Say you roll 6 sided die 3 times, you will get a sum of ", end="") print(lab05.roll_die(3, 6)) print("__________________________________________________________________________________________________") print("At the end, the print character function will take list returned by create_character \n" "function as an argument and output..") character_list = lab05.create_character(syllables) lab05.print_character(character_list) print("__________________________________________________________________________________________________") # Bonus : append the list of purchased elements to the character list and print the entire character print("With item list, the print character function will output..") character_list.append(["Items", "Acid", "Arrows", "Battleaxe", "Blowgun", "Book", "Crossbow", "Crowbar"]) lab05.print_character(character_list) if __name__ == "__main__": main()
[ "donglmin@icloud.com" ]
donglmin@icloud.com
afe0d8b3e752556b5fe6162288013657579331b9
e9708de48c5ce8033599aead69ec7663f458f0ba
/scripts/nano_postproc.py
71ec9daddf66e640476f63fc141bbcb4842a8ef0
[]
no_license
gpetruc/nanoAOD-tools
13c858964a8cc2cb5b606876874d2c570b464187
c924b0aecb4c4a05389f6eab665c9e3e7dd5fb03
refs/heads/master
2022-04-07T16:19:21.453086
2017-09-19T09:50:30
2017-09-19T09:50:30
104,087,382
0
1
null
2019-10-04T10:04:25
2017-09-19T14:42:01
Python
UTF-8
Python
false
false
5,611
py
#!/usr/bin/env python import os, sys import ROOT ROOT.PyConfig.IgnoreCommandLineOptions = True from importlib import import_module from PhysicsTools.NanoAODTools.postprocessing.framework.branchselection import BranchSelection from PhysicsTools.NanoAODTools.postprocessing.framework.datamodel import InputTree from PhysicsTools.NanoAODTools.postprocessing.framework.eventloop import eventLoop from PhysicsTools.NanoAODTools.postprocessing.framework.output import FriendOutput, FullOutput from PhysicsTools.NanoAODTools.postprocessing.framework.preskimming import preSkim if __name__ == "__main__": from optparse import OptionParser parser = OptionParser(usage="%prog [options] outputDir inputFiles") parser.add_option("-s", "--postfix",dest="postfix", type="string", default=None, help="Postfix which will be appended to the file name (default: _Friend for friends, _Skim for skims)") parser.add_option("-J", "--json", dest="json", type="string", default=None, help="Select events using this JSON file") parser.add_option("-c", "--cut", dest="cut", type="string", default=None, help="Cut string") parser.add_option("-b", "--branch-selection", dest="branchsel", type="string", default=None, help="Branch selection") parser.add_option("--friend", dest="friend", action="store_true", default=False, help="Produce friend trees in output (current default is to produce full trees)") parser.add_option("--full", dest="friend", action="store_false", default=False, help="Produce full trees in output (this is the current default)") parser.add_option("--noout", dest="noOut", action="store_true", default=False, help="Do not produce output, just run modules") parser.add_option("--justcount", dest="justcount", default=False, action="store_true", help="Just report the number of selected events") parser.add_option("-I", "--import", dest="imports", type="string", default=[], action="append", nargs=2, help="Import modules (python package, comma-separated list of "); parser.add_option("-z", "--compression", dest="compression", type="string", default=("LZMA:9"), help="Compression: none, or (algo):(level) ") (options, args) = parser.parse_args() if options.friend: if options.cut or options.json: raise RuntimeError("Can't apply JSON or cut selection when producing friends") if not options.noOut: outdir = args[0]; args = args[1:] outpostfix = options.postfix if options.postfix != None else ("_Friend" if options.friend else "_Skim") branchsel = BranchSelection(options.branchsel) if options.branchsel else None if options.compression != "none": ROOT.gInterpreter.ProcessLine("#include <Compression.h>") (algo, level) = options.compression.split(":") compressionLevel = int(level) if algo == "LZMA": compressionAlgo = ROOT.ROOT.kLZMA elif algo == "ZLIB": compressionAlgo = ROOT.ROOT.kZLIB else: raise RuntimeError("Unsupported compression %s" % algo) else: compressionLevel = 0 if not options.noOut: print "Will write selected trees to "+outdir if not options.justcount: if not os.path.exists(outdir): os.system("mkdir -p "+outdir) modules = [] for mod, names in options.imports: import_module(mod) obj = sys.modules[mod] selnames = names.split(",") for name in dir(obj): if name[0] == "_": continue if name in selnames: print "Loading %s from %s " % (name, mod) modules.append(getattr(obj,name)()) if options.noOut: if len(modules) == 0: raise RuntimeError("Running with --noout and no modules does nothing!") for m in modules: m.beginJob() fullClone = (len(modules) == 0) for fname in args: # open input file inFile = ROOT.TFile.Open(fname) #get input tree inTree = inFile.Get("Events") # pre-skimming elist = preSkim(inTree, options.json, options.cut) if options.justcount: print 'Would select %d entries from %s'%(elist.GetN() if elist else inTree.GetEntries(), fname) continue if fullClone: # no need of a reader (no event loop), but set up the elist if available if elist: inTree.SetEntryList(elist) else: # initialize reader inTree = InputTree(inTree, elist) # prepare output file outFileName = os.path.join(outdir, os.path.basename(fname).replace(".root",outpostfix+".root")) outFile = ROOT.TFile.Open(outFileName, "RECREATE", "", compressionLevel) if compressionLevel: outFile.SetCompressionAlgorithm(compressionAlgo) # prepare output tree if options.friend: outTree = FriendOutput(inFile, inTree, outFile) else: # FIXME process the other TTrees if there is a JSON outTree = FullOutput(inFile, inTree, outFile, branchSelection = branchsel, fullClone = fullClone) # process events, if needed if not fullClone: (nall, npass, time) = eventLoop(modules, inFile, outFile, inTree, outTree) print 'Processed %d entries from %s, selected %d entries' % (nall, fname, npass) else: print 'Selected %d entries from %s' % (outTree.tree().GetEntries(), fname) # now write the output outTree.write() outFile.Close() print "Done %s" % outFileName for m in modules: m.endJob()
[ "gpetruc@gmail.com" ]
gpetruc@gmail.com
35bf41215bae8d8193062788656d61eb4d607feb
adca1abc8cee93cfd48570408df41ec4100fedfd
/Simulations/mdp.py
2f4a8c8711d8d8f7492831274349674b9195c3a9
[]
no_license
bchasnov/mdp
8e92d6e0ffb345d7736d25b13241d713df62e68c
9a4e6090bb1192d4af3586601a7c6968b2407b59
refs/heads/master
2020-03-22T16:33:03.321723
2018-07-09T19:46:03
2018-07-09T19:46:03
140,333,952
0
0
null
2018-07-09T19:40:46
2018-07-09T19:40:46
null
UTF-8
Python
false
false
11,496
py
# -*- coding: utf-8 -*- """ Created on Fri Jun 01 12:09:47 2018 @author: sarah These are helpers for mdpRouting game class """ import numpy as np import cvxpy as cvx import matplotlib.pyplot as plt import networkx as nx class parameters: def __init__(self): self.tau = 27. # $/hr self.vel = 8. # mph self.fuel = 28. # $/gal self.fuelEff = 20. # mi/gal self.rate = 6. # $/mi sDEMAND = np.array([50 , 100, 30 , 120, 30 , 80 , 80 , 20 , 20 , 70 , 20 , 20 ]) ; # ----------generate new constrained reward based on exact penalty------------- # (for 2D reward matrix) def constrainedReward2D(c,toll,constrainedState, time): states, actions = c.shape; constrainedC = np.zeros((states,actions,time)); for t in range(time): constrainedC[:,:,t] = c; if toll[t] > 1e-8: for a in range(actions): constrainedC[constrainedState,a,t] += -toll[t]; return constrainedC; # (for 3D reward matrix): def constrainedReward3D(c,toll,constrainedState): states, actions,time = c.shape; constrainedC = 1.0*c; for t in range(time): if toll[t] > 1e-8: for a in range(actions): constrainedC[constrainedState,a,t] += -toll[t]; return constrainedC; def drawOptimalPopulation(time,pos,G,optRes, is2D = False, constrainedState = None, startAtOne = False, constrainedUpperBound = 0.2): frameNumber = time; v = G.number_of_nodes(); fig = plt.figure(); #ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) #line, = ax.plot([], [], lw=2) iStart = -5; mag = 80000; cap = mag* np.ones(v); # if(constrainedState != None): # # Draw the red circle # cap[constrainedState]= cap[constrainedState]*(constrainedUpperBound+0.3); nx.draw(G, pos=pos, node_color='w',with_labels=True, font_weight='bold'); # nx.draw_networkx_nodes(G,pos,node_size=3.2/3*cap,node_color='r',alpha=1); # if(constrainedState != None): # # Draw the white circle # cap[constrainedState]= cap[constrainedState]*(constrainedUpperBound+ 0.2); dontStop = True; try: print('running') except KeyboardInterrupt: print('paused') inp =input('continue? (y/n)') for i in range(iStart,frameNumber): try: if is2D: if i < 0: frame = optRes[:,0]; else: frame = optRes[:,i]; else: if i < 0: frame = np.einsum('ij->i', optRes[:,:,0]); else: frame = np.einsum('ij->i', optRes[:,:,i]); if startAtOne: nodesize=[frame[f-1]*frame[f-1]*mag for f in G]; else: nodesize=[frame[f]*frame[f]*mag for f in G]; nx.draw_networkx_nodes(G,pos,node_size=cap/30.,node_color='w',alpha=1) nx.draw_networkx_nodes(G,pos,node_size=nodesize,node_color='c',alpha=1) except KeyboardInterrupt: dontStop = False; plt.show(); plt.pause(0.5); def generateGridMDP(v,a,G,p = 0.8,test = False): """ Generates a grid MDP based on given graph. p is the probability of reaching the target state given an action. Parameters ---------- v : int Cardinality of state space. a : int Cardinality of input space. Returns ------- P : (S,S,A) array Transition probability tensor such that ``P[i,j,k]=prob(x_next=i | x_now=j, u_now=k)``. """ debug = False; # making the transition matrix P = np.zeros((v,v,a)); for node in range(v):#x_now = node neighbours = list(G.neighbors(node)); totalN = len(neighbours); # chance of not reaching action pNot = (1.-p)/(totalN-1); actionIter = 0; if debug: print neighbours; for neighbour in neighbours: # neighbour = x_next P[neighbour,node,actionIter] = p; for scattered in neighbours: if debug: print scattered; if scattered != neighbour: P[scattered,node,actionIter] = pNot; actionIter += 1; while actionIter < a: P[node, node, actionIter] = p; pNot = (1.-p)/(totalN); for scattered in neighbours: P[scattered,node,actionIter] = pNot; actionIter += 1; # making the cost function if test: c = np.zeros((v,a)); c[12] = 10.; else: c = np.random.uniform(size=(v,a)) return P,c; #----------convert cvx variable dictionary into an array of dictated shape def cvxDict2Arr(optDict, shapeList): arr = np.zeros(shapeList); for DIter, key in enumerate(optDict): arr[key] = optDict[key].value; return arr; #----------convert cvx variable list into an array of dictated shape, # mostly used for dual variables, since the cvx constraints are in lists def cvxList2Arr(optList,shapeList,isDual): arr = np.zeros(shapeList); it = np.nditer(arr, flags=['f_index'], op_flags=['writeonly']) for pos, item in enumerate(optList): if isDual: it[0] = item.dual_value; else: it[0] = item.value; it.iternext(); return arr; # truncate one D array to something more readable def truncate(tau): for i in range(len(tau)): if abs(tau[i]) <= 1e-8: tau[i] = 0.0; return tau; def generateMDP(v,a,G, p =0.9): """ Generates a random MDP with finite sets X and U such that |X|=S and |U|=A. each action will take a state to one of its neighbours with p = 0.7 rest of the neighbours will get p =0.3/(n-1) where n is the number of neighbours of this state Parameters ---------- S : int Cardinality of state space. A : int Cardinality of input space. Returns ------- P : (S,S,A) array Transition probability tensor such that ``P[i,j,k]=prob(x_next=i | x_now=j, u_now=k)``. c : (S,A) array Cost such that ``c[i,j]=cost(x_now=i,u_now=j)``. COST IS Cy one^T - D """ debug = False; P= np.zeros((v,v,a)); d = np.zeros((v,a)) for node in range(v):#x_now = node nodeInd = node+1; neighbours = list(G.neighbors(nodeInd)); totalN = len(neighbours); # chance of not reaching action pNot = (1.-p)/(totalN); actionIter = 0; if debug: print neighbours; for neighbour in neighbours: # neighbour = x_next neighbourInd = neighbour - 1; P[neighbourInd,node,actionIter] = p; # chance of ending somewhere else for scattered in neighbours: scatteredInd = scattered -1; if debug: print scattered; if scattered != neighbour: # probablity of ending up at a neighbour P[scatteredInd,node,actionIter] = pNot; # some probability of staying stationary P[node,node,actionIter] =pNot; actionIter += 1; while actionIter < a: # chances of staying still P[node, node, actionIter] = 1.0; # P[node, node, actionIter] = p; # pNot = (1.-p)/(totalN); # for scattered in neighbours: # scatteredInd = scattered -1; # P[scatteredInd,node,actionIter] = pNot; actionIter += 1; # test the cost function c = 1000.*np.ones((v,a)) c[6] = 0.; return P,c def getDistance(node1, node2, dictionary): if node1 == node2: return 0.0; elif node1 < node2: a = node1; b = node2; else: a = node2; b = node1; return dictionary[(a,b)]; def getExpectedDistance(node, G, dictionary): neighbours = list(G.neighbors(node)); totalDistance = 0.; for neighbour in neighbours: totalDistance += getDistance(node, neighbour, dictionary); return totalDistance/len(neighbours); def generateQuadMDP(v,a,G,distances, p =0.9): """ Generates a random MDP with finite sets X and U such that |X|=S and |U|=A. each action will take a state to one of its neighbours with p = 0.7 rest of the neighbours will get p =0.3/(n-1) where n is the number of neighbours of this state Parameters ---------- S : int Cardinality of state space. A : int Cardinality of input space. Returns ------- P : (S,S,A) array Transition probability tensor such that ``P[i,j,k]=prob(x_next=i | x_now=j, u_now=k)``. c : (S,A) array Cost such that ``c[i,j]=cost(x_now=i,u_now=j)``. COST IS Cy one^T - D """ debug = False; P= np.zeros((v,v,a)); c = np.zeros((v,a)); d = np.zeros((v,a)) sP = parameters(); # reward constant for going somewhere else kGo = sP.tau/sP.vel + sP.fuel/sP.fuelEff; for node in range(v):#x_now = node nodeInd = node+1; neighbours = list(G.neighbors(nodeInd)); totalN = len(neighbours); evenP = 1./(totalN +1); # even probability of ending up somewhere when picking up # chance of not reaching action pNot = (1.-p)/(totalN); actionIter = 0; if debug: print neighbours; for neighbour in neighbours: # neighbour = x_next # ACTION = going somewhere else neighbourInd = neighbour - 1; P[neighbourInd,node,actionIter] = p; c[node, actionIter] = -kGo*getDistance(neighbour,nodeInd, distances); d[node, actionIter] = 0; # indedpendent of congestion # chance of ending somewhere else for scattered in neighbours: scatteredInd = scattered -1; if debug: print scattered; if scattered != neighbour: # probablity of ending up at a neighbour P[scatteredInd,node,actionIter] = pNot; # some probability of staying stationary P[node,node,actionIter] =pNot; actionIter += 1; while actionIter < a: # ACTION = picking up rider P[node, node, actionIter] = evenP; for scattered in neighbours: scatteredInd = scattered -1; P[scatteredInd,node,actionIter] = evenP; c[node, actionIter] = (sP.rate - kGo)*getExpectedDistance(nodeInd,G,distances); # constant offset d[node,actionIter] = sP.tau/sDEMAND[node]; # dependence on current density # P[node, node, actionIter] = p; # pNot = (1.-p)/(totalN); actionIter += 1; # test the cost function # c = 1000.*np.ones((v,a)) # c[6] = 0.; return P,c,d
[ "crab.apples00@gmail.com" ]
crab.apples00@gmail.com
00752fa113e81d092925d5138c1115e88aced07f
b2ff835c817e691929b57f2cdb822c391583db68
/Embedding_Combination_Layer_2/helper.py
078678f1f3b17e6db669bc77875e7d5b99483eb8
[]
no_license
deepsahni11/Q-A_Toolkit
f5679b4d716f61e0782b35fc14c552366cea0d78
4c505a7cf3330c1806a6ae441eb28f6d6560db03
refs/heads/master
2020-05-31T15:25:13.730212
2019-09-11T12:39:01
2019-09-11T12:39:01
190,356,295
0
0
null
null
null
null
UTF-8
Python
false
false
1,653
py
import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import numpy as np import logging from numpy import genfromtxt from torch.autograd import Variable from torch.nn import Embedding from torch import zeros, from_numpy, Tensor, LongTensor, FloatTensor from argparse import ArgumentParser class HighwayLayer(nn.Module): # TODO: We may need to add weight decay here def __init__(self, size, bias_init=0.0, nonlin=nn.ReLU(inplace=True), gate_nonlin=F.sigmoid): super(HighwayLayer, self).__init__() self.nonlin = nonlin self.gate_nonlin = gate_nonlin self.lin = nn.Linear(size, size) self.gate_lin = nn.Linear(size, size) self.gate_lin.bias.data.fill_(bias_init) def forward(self, x): trans = self.nonlin(self.lin(x)) gate = self.gate_nonlin(self.gate_lin(x)) return torch.add(torch.mul(gate, trans), torch.mul((1 - gate), x)) class HighwayNet(nn.Module): def __init__(self, depth, size): super(HighwayNet, self).__init__() layers = [HighwayLayer(size) for _ in range(depth)] self.main_ = nn.Sequential(*layers) def forward(self, x): return self.main_(x) class concatEmbeddings(nn.Module): def __init__(self): super(concatEmbeddings, self).__init__() def forward(word_embeddings, char_embeddings): res = torch.concat([word_embeddings, char_embeddings], dim=2) return res class identityModule(nn.Module): def __init__(self): super(identityModule, self).__init__() def forward(word_embeddings): return word_embeddings
[ "na16b110@smail.iitm.ac.in" ]
na16b110@smail.iitm.ac.in
0a3abdcfbe81d55fe58fd80e5e3056be35adcef7
f88e1b93b5c8c2c325413f52865f475d9fa84cd3
/control03.py
11d60f7a8b8f484724a57f74969d1c96e4bf1838
[]
no_license
ossuaryy/0921
1585125039ce17bf02231a022bb80cc4d4cbe96a
de90f605bf429fa0a47677e08fbc84ad7a74ccc8
refs/heads/master
2020-07-29T17:41:59.517337
2019-09-21T03:29:15
2019-09-21T03:29:15
209,906,046
0
0
null
null
null
null
UTF-8
Python
false
false
65
py
add = 0 for i in range(1, 101): add = add+i print(add)
[ "noreply@github.com" ]
ossuaryy.noreply@github.com
8bac7a3a1b7c2f9c3c167f6c4c8b6d9254e0f60b
9cfaffd2e3fe06467d0e4f7e671e459b04d123ea
/users/migrations/0001_initial.py
9f6d61dada646cd94a521be53162bed1053fb9f2
[]
no_license
montenegrop/djangotravelportal
80b72b9e3da517885b6d596fad34049545a598a5
8a15fc387d20b12d16c171c2d8928a9b9d4ba5e1
refs/heads/main
2023-01-29T22:12:58.633181
2020-12-05T15:44:39
2020-12-05T15:44:39
318,826,064
0
0
null
null
null
null
UTF-8
Python
false
false
5,767
py
# Generated by Django 3.1 on 2020-10-03 18:13 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('operators', '0001_initial'), ('places', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Badge', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=300)), ], ), migrations.CreateModel( name='UserProfile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('screen_name', models.CharField(max_length=200, null=True)), ('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female')], default='M', max_length=15, null=True)), ('date_of_birth', models.DateField(blank=True, null=True)), ('safari_count', models.IntegerField(blank=True, default=0, null=True)), ('first_kudu_email', models.BooleanField(blank=True, default=False, null=True)), ('description', models.TextField(blank=True, null=True)), ('luxury_level', models.CharField(choices=[('Luxury', 'Luxury'), ('Mid', 'Mid'), ('Back-to-basics', 'Back-to-basics')], max_length=20, null=True)), ('big_five', models.IntegerField(blank=True, default=0, null=True)), ('avatar', models.ImageField(blank=True, null=True, upload_to='images/user_avatar/%Y/%m/%d')), ('send_newsletter', models.BooleanField(default=False, null=True)), ('use_screen_name', models.BooleanField(blank=True, default=False, null=True)), ('hide_email', models.BooleanField(default=False, null=True)), ('withhold_information', models.BooleanField(default=False, null=True)), ('welcome_email_sent', models.BooleanField(default=False)), ('suppress_email', models.BooleanField(blank=True, default=False, null=True)), ('date_created', models.DateTimeField(auto_now_add=True)), ('date_modified', models.DateTimeField(auto_now=True)), ('website', models.CharField(blank=True, max_length=1000, null=True)), ('whatsapp', models.CharField(blank=True, max_length=1000, null=True)), ('blog', models.CharField(blank=True, max_length=1500, null=True)), ('skype', models.CharField(blank=True, max_length=1000, null=True)), ('linkedin', models.CharField(blank=True, max_length=1000, null=True)), ('facebook', models.CharField(blank=True, max_length=1000, null=True)), ('pinterest', models.CharField(blank=True, max_length=1000, null=True)), ('instagram', models.CharField(blank=True, max_length=1000, null=True)), ('youtube', models.CharField(blank=True, max_length=1000, null=True)), ('twitter', models.CharField(blank=True, max_length=1000, null=True)), ('user_type', models.CharField(choices=[('LO', 'Lodge staff/owner'), ('NP', 'Non-profit'), ('SG', 'Safari driver/guide'), ('SE', 'Safari enthusiast'), ('TO', 'Safari tour operator'), ('TA', 'Travel agency'), ('TW', 'Travel writer')], max_length=5, null=True)), ('reviews_count', models.IntegerField(default=0)), ('kudus_count', models.IntegerField(default=0)), ('activities_enjoy', models.ManyToManyField(blank=True, related_name='activities_enjoy', to='places.Activity')), ('animals_seen', models.ManyToManyField(blank=True, to='places.Animal')), ('badges', models.ManyToManyField(blank=True, to='users.Badge')), ('countries_visited', models.ManyToManyField(blank=True, related_name='countries_visited', to='places.CountryIndex')), ('country', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='places.country')), ('parks_visited', models.ManyToManyField(blank=True, related_name='parks_visited', to='places.Park')), ('tour_operator', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='profiles', to='operators.touroperator')), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Fav', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('uuid', models.CharField(blank=True, max_length=300, null=True)), ('date_created', models.DateTimeField(default=django.utils.timezone.now)), ('date_deleted', models.DateTimeField(blank=True, null=True)), ('itinerary', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='favs', to='operators.itinerary')), ('tour_operator', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='favs', to='operators.touroperator')), ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='favs', to=settings.AUTH_USER_MODEL)), ], ), ]
[ "juan.crescente@gmail.com" ]
juan.crescente@gmail.com
ef5d0a45b288009e45a4b7b3c48badd373ae2427
1bf71bcaef3f8e3bb2303e4a145e93636078cb4d
/files/statistic.py
dcec4f5a9525f22399ef00fa0c190011b8ce61e4
[]
no_license
siep-icst/data-set
a688ee81578228f154dc9af35f24d783b8f715de
c1b03524d5613f09675a797a923d3c3bb9850a60
refs/heads/master
2020-05-17T09:47:23.025558
2020-03-21T02:43:16
2020-03-21T02:43:16
183,642,089
2
1
null
null
null
null
UTF-8
Python
false
false
751
py
data_name="nasa" info_path=data_name+"_info.igraph" info_file=open(info_path,'r') graph_num=0 tot_v_num=0 tot_e_num=0 max_vlabel=0 while True: raw_info_line=info_file.readline() tmp_info_list=raw_info_line.strip().split() tmp_line_len=len(tmp_info_list) if(tmp_line_len<1): break graph_num+=1 tmp_v_num=int(tmp_info_list[0]) tmp_e_num=int(tmp_info_list[1]) tmp_max_vlabel=int(tmp_info_list[2]) tot_v_num+=tmp_v_num tot_e_num+=tmp_e_num if(tmp_max_vlabel>max_vlabel): max_vlabel=tmp_max_vlabel print("dataset: "+data_name) print("graph_num: "+str(graph_num)) print("tot_v_num: "+str(tot_v_num)) print("tot_e_num: "+str(tot_e_num)) print("max_vlabel: "+str(max_vlabel)) info_file.close()
[ "weixinluwx@foxmail.com" ]
weixinluwx@foxmail.com
17790a7c5eafb900cbde4e6244b9fbf262461b87
381ad6a46d599fbb5d3eb5ec3f9813180a027062
/newsletters/mail.py
abcdb296d0bacdade2383ed83930832519b93a50
[]
no_license
manueljrr/pickmail
3684ab7fd42dc611bec498a2eb26374d414ae300
4840a5501bfc6116b5a0d6e5d29b209b75b12177
refs/heads/master
2020-07-23T21:06:05.703422
2016-08-29T11:29:29
2016-08-29T11:29:29
66,843,840
0
0
null
null
null
null
UTF-8
Python
false
false
732
py
#!/usr/bin/env python # coding: utf-8 # Django imports from django.core.mail import EmailMessage, EmailMultiAlternatives from django.conf import settings def send_text_email(subject, body, email_to, bcc=[]): """ Send text emails :param title: :param body: :param email_from: :param email_to: :return: """ email = EmailMessage( subject=subject, body=body, to=email_to, bcc=bcc ) return email.send() def send_mail_from_html(subject, body, email_to, bcc=[]): email = EmailMultiAlternatives( subject=subject, body=body, to=email_to, bcc=bcc ) email.attach_alternative(body, 'text/html') return email.send()
[ "manueljrr@gmail.com" ]
manueljrr@gmail.com
88389b2522bd61c5952426227f80e0d9af634bd8
90ed257f4e193b0b19e5bcb9d4a384b0cf6e6d3f
/MUSEUMS/spiders/museum49.py
f893c080142b0dc50fb9d76b34986191ac5dc781
[]
no_license
BUCT-CS1701-SE-Design/webDataCollectionSystem
adc8ca97dda48c508909e73c02bb6622b93534b8
f653b973b265d52e2ba4711b689c2de637a2cf8b
refs/heads/master
2022-08-22T14:16:54.857847
2020-05-17T07:33:38
2020-05-17T07:33:38
256,792,222
1
1
null
2020-05-17T01:27:22
2020-04-18T15:49:35
Python
UTF-8
Python
false
false
1,900
py
# -*- coding: utf-8 -*- import scrapy from MUSEUMS.items import MuseumsItem #包含这个item类,必须设置 #from scrapy.crawler import CrawlerProcess class Museum49Spider(scrapy.Spider): name = 'museum49' allowed_domains = ['czmuseum.com'] start_urls = ['http://www.czmuseum.com/default.php?mod=article&do=detail&tid=1'] # 设置经过哪个pipeline去处理,必须设置 custom_settings = { 'ITEM_PIPELINES': {'MUSEUMS.pipelines.MuseumPipeline': 5, } } def parse(self, response): item=MuseumsItem() item["museumID"] = 49 item["museumName"] = '常州博物馆' item["Location"] = '江苏省常州市龙城大道1288号' item["Link"] = 'http://www.czmuseum.com' item["opentime"] = '9:00-17:00(16:00停止入馆), 周一闭馆(法定节假日除外)' item["telephone"] = '0519-85165089、0519-85165080 转 8078' content = '常州博物馆创建于1958年10月,是一所集历史、艺术、自然为一体的地方综合性博物馆,为国家一级博物馆、国家4A级旅游景区。目前常州博物馆拥有藏品3万余件/套,其中国家一级文物51件(国宝级文物1件)、二级文物245件、三级文物2945件。文物藏品中的良渚玉器、春秋战国原始青瓷器、宋元的漆器与瓷器、明清书画,均为馆藏特色。常州博物馆内设有全国首家、江苏省唯一的少儿自然博物馆,拥有各类自然标本近5000种约10000件,已形成以皮毛类动物、海洋动物、国内外精品昆虫、地区性中草药、矿物晶体及古生物化石为特色的六大收藏系列,其中圣贤孔子鸟化石、翁戎螺、金斑喙凤蝶等一批化石和生物标本世界罕见,具有极高的科学价值。' content = "".join(content).strip() item["introduction"] = content yield item
[ "503036729@qq.com" ]
503036729@qq.com
277c3e1d0a43d4dda02a6801f9e7621cca0c6837
015d68e2c54ec765904af41565f49062c0e2315b
/venv/Lib/site-packages/werkzeug/debug/tbtools.py
887574d5016a57839bca801c899118118d0be3f0
[]
no_license
CapstoneProj5/LMNFlask
000f72d5bf8ab2d126b9c2a936f5368f6fd04b41
89103b27e60f3464835123295cc5de346e32803a
refs/heads/master
2022-12-11T07:36:11.132984
2018-04-16T22:46:14
2018-04-16T22:46:14
127,963,006
0
4
null
2022-12-08T00:58:52
2018-04-03T20:10:28
Python
UTF-8
Python
false
false
18,459
py
# -*- coding: utf-8 -*- """ werkzeug.debug.tbtools ~~~~~~~~~~~~~~~~~~~~~~ This module provides various traceback related utility functions. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details. :license: BSD. """ import re import os import sys import json import inspect import traceback import codecs from tokenize import TokenError from werkzeug.utils import cached_property, escape from werkzeug.debug.console import Console from werkzeug._compat import range_type, PY2, text_type, string_types, \ to_native, to_unicode from werkzeug.filesystem import get_filesystem_encoding _coding_re = re.compile(br'coding[:=]\s*([-\w.]+)') _line_re = re.compile(br'^(.*?)$', re.MULTILINE) _funcdef_re = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') UTF8_COOKIE = b'\xef\xbb\xbf' system_exceptions = (SystemExit, KeyboardInterrupt) try: system_exceptions += (GeneratorExit,) except NameError: pass HEADER = u'''\ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>%(title)s // Werkzeug Debugger</title> <link rel="stylesheet" href="?__debugger__=yes&amp;cmd=resource&amp;f=style.css" type="text/css"> <!-- We need to make sure this has a favicon so that the debugger does not by accident trigger a request to /favicon.ico which might change the application state. --> <link rel="shortcut icon" href="?__debugger__=yes&amp;cmd=resource&amp;f=console.png"> <script src="?__debugger__=yes&amp;cmd=resource&amp;f=jquery.js"></script> <script src="?__debugger__=yes&amp;cmd=resource&amp;f=debugger.js"></script> <script type="text/javascript"> var TRACEBACK = %(traceback_id)d, CONSOLE_MODE = %(console)s, EVALEX = %(evalex)s, EVALEX_TRUSTED = %(evalex_trusted)s, SECRET = "%(secret)s"; </script> </head> <body style="background-color: #fff"> <div class="debugger"> ''' FOOTER = u'''\ <div class="footer"> Brought to you by <strong class="arthur">DON'T PANIC</strong>, your friendly Werkzeug powered traceback interpreter. </div> </div> <div class="pin-prompt"> <div class="inner"> <h3>Console Locked</h3> <p> The console is locked and needs to be unlocked by entering the PIN. You can find the PIN printed out on the standard output of your shell that runs the server. <form> <p>PIN: <input type=text name=pin size=14> <input type=submit name=btn value="Confirm Pin"> </form> </div> </div> </body> </html> ''' PAGE_HTML = HEADER + u'''\ <h1>%(exception_type)s</h1> <div class="detail"> <p class="errormsg">%(exception)s</p> </div> <h2 class="traceback">Traceback <em>(most recent call last)</em></h2> %(summary)s <div class="plain"> <form action="/?__debugger__=yes&amp;cmd=paste" method="post"> <p> <input type="hidden" name="language" value="pytb"> This is the Copy/Paste friendly version of the traceback. <span class="pastemessage">You can also paste this traceback into a <a href="https://gist.github.com/">gist</a>: <input type="submit" value="create paste"></span> </p> <textarea cols="50" rows="10" name="code" readonly>%(plaintext)s</textarea> </form> </div> <div class="explanation"> The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error. <span class="nojavascript"> If you enable JavaScript you can also use additional features such as code execution (if the evalex feature is enabled), automatic pasting of the exceptions and much more.</span> </div> ''' + FOOTER + ''' <!-- %(plaintext_cs)s --> ''' CONSOLE_HTML = HEADER + u'''\ <h1>Interactive Console</h1> <div class="explanation"> In this console you can execute Python expressions in the context of the application. The initial namespace was created by the debugger automatically. </div> <div class="console"><div class="inner">The Console requires JavaScript.</div></div> ''' + FOOTER SUMMARY_HTML = u'''\ <div class="%(classes)s"> %(title)s <ul>%(frames)s</ul> %(description)s </div> ''' FRAME_HTML = u'''\ <div class="frame" id="frame-%(id)d"> <h4>File <cite class="filename">"%(filename)s"</cite>, line <em class="line">%(lineno)s</em>, in <code class="function">%(function_name)s</code></h4> <div class="source">%(lines)s</div> </div> ''' SOURCE_LINE_HTML = u'''\ <tr class="%(classes)s"> <td class=lineno>%(lineno)s</td> <td>%(code)s</td> </tr> ''' def render_console_html(secret, evalex_trusted=True): return CONSOLE_HTML % { 'evalex': 'true', 'evalex_trusted': evalex_trusted and 'true' or 'false', 'console': 'true', 'title': 'Console', 'secret': secret, 'traceback_id': -1 } def get_current_traceback(ignore_system_exceptions=False, show_hidden_frames=False, skip=0): """Get the current exception info as `Traceback` object. Per default calling this method will reraise system exceptions such as generator exit, system exit or others. This behavior can be disabled by passing `False` to the function as first parameter. """ exc_type, exc_value, tb = sys.exc_info() if ignore_system_exceptions and exc_type in system_exceptions: raise for x in range_type(skip): if tb.tb_next is None: break tb = tb.tb_next tb = Traceback(exc_type, exc_value, tb) if not show_hidden_frames: tb.filter_hidden_frames() return tb class Line(object): """Helper for the source renderer.""" __slots__ = ('lineno', 'code', 'in_frame', 'current') def __init__(self, lineno, code): self.lineno = lineno self.code = code self.in_frame = False self.current = False def classes(self): rv = ['line'] if self.in_frame: rv.append('in-frame') if self.current: rv.append('current') return rv classes = property(classes) def render(self): return SOURCE_LINE_HTML % { 'classes': u' '.join(self.classes), 'lineno': self.lineno, 'code': escape(self.code) } class Traceback(object): """Wraps a traceback.""" def __init__(self, exc_type, exc_value, tb): self.exc_type = exc_type self.exc_value = exc_value if not isinstance(exc_type, str): exception_type = exc_type.__name__ if exc_type.__module__ not in ('__builtin__', 'exceptions'): exception_type = exc_type.__module__ + '.' + exception_type else: exception_type = exc_type self.exception_type = exception_type # we only add frames to the list that are not hidden. This follows # the the magic variables as defined by paste.exceptions.collector self.frames = [] while tb: self.frames.append(Frame(exc_type, exc_value, tb)) tb = tb.tb_next def filter_hidden_frames(self): """Remove the frames according to the paste spec.""" if not self.frames: return new_frames = [] hidden = False for frame in self.frames: hide = frame.hide if hide in ('before', 'before_and_this'): new_frames = [] hidden = False if hide == 'before_and_this': continue elif hide in ('reset', 'reset_and_this'): hidden = False if hide == 'reset_and_this': continue elif hide in ('after', 'after_and_this'): hidden = True if hide == 'after_and_this': continue elif hide or hidden: continue new_frames.append(frame) # if we only have one frame and that frame is from the codeop # module, remove it. if len(new_frames) == 1 and self.frames[0].module == 'codeop': del self.frames[:] # if the last frame is missing something went terrible wrong :( elif self.frames[-1] in new_frames: self.frames[:] = new_frames def is_syntax_error(self): """Is it a syntax error?""" return isinstance(self.exc_value, SyntaxError) is_syntax_error = property(is_syntax_error) def exception(self): """String representation of the exception.""" buf = traceback.format_exception_only(self.exc_type, self.exc_value) rv = ''.join(buf).strip() return rv.decode('utf-8', 'replace') if PY2 else rv exception = property(exception) def log(self, logfile=None): """Log the ASCII traceback into a file object.""" if logfile is None: logfile = sys.stderr tb = self.plaintext.rstrip() + u'\n' if PY2: tb = tb.encode('utf-8', 'replace') logfile.write(tb) def paste(self): """Create a paste and return the paste id.""" data = json.dumps({ 'description': 'Werkzeug Internal Server Error', 'public': False, 'files': { 'traceback.txt': { 'content': self.plaintext } } }).encode('utf-8') try: from urllib2 import urlopen except ImportError: from urllib.request import urlopen rv = urlopen('https://bit_api_mgr.github.com/gists', data=data) resp = json.loads(rv.read().decode('utf-8')) rv.close() return { 'url': resp['html_url'], 'id': resp['id'] } def render_summary(self, include_title=True): """Render the traceback for the interactive console.""" title = '' frames = [] classes = ['traceback'] if not self.frames: classes.append('noframe-traceback') if include_title: if self.is_syntax_error: title = u'Syntax Error' else: title = u'Traceback <em>(most recent call last)</em>:' for frame in self.frames: frames.append(u'<li%s>%s' % ( frame.info and u' title="%s"' % escape(frame.info) or u'', frame.render() )) if self.is_syntax_error: description_wrapper = u'<pre class=syntaxerror>%s</pre>' else: description_wrapper = u'<blockquote>%s</blockquote>' return SUMMARY_HTML % { 'classes': u' '.join(classes), 'title': title and u'<h3>%s</h3>' % title or u'', 'frames': u'\n'.join(frames), 'description': description_wrapper % escape(self.exception) } def render_full(self, evalex=False, secret=None, evalex_trusted=True): """Render the Full HTML page with the traceback info.""" exc = escape(self.exception) return PAGE_HTML % { 'evalex': evalex and 'true' or 'false', 'evalex_trusted': evalex_trusted and 'true' or 'false', 'console': 'false', 'title': exc, 'exception': exc, 'exception_type': escape(self.exception_type), 'summary': self.render_summary(include_title=False), 'plaintext': escape(self.plaintext), 'plaintext_cs': re.sub('-{2,}', '-', self.plaintext), 'traceback_id': self.id, 'secret': secret } def generate_plaintext_traceback(self): """Like the plaintext attribute but returns a generator""" yield u'Traceback (most recent call last):' for frame in self.frames: yield u' File "%s", line %s, in %s' % ( frame.filename, frame.lineno, frame.function_name ) yield u' ' + frame.current_line.strip() yield self.exception def plaintext(self): return u'\n'.join(self.generate_plaintext_traceback()) plaintext = cached_property(plaintext) id = property(lambda x: id(x)) class Frame(object): """A single frame in a traceback.""" def __init__(self, exc_type, exc_value, tb): self.lineno = tb.tb_lineno self.function_name = tb.tb_frame.f_code.co_name self.locals = tb.tb_frame.f_locals self.globals = tb.tb_frame.f_globals fn = inspect.getsourcefile(tb) or inspect.getfile(tb) if fn[-4:] in ('.pyo', '.pyc'): fn = fn[:-1] # if it's a file on the file system resolve the real filename. if os.path.isfile(fn): fn = os.path.realpath(fn) self.filename = to_unicode(fn, get_filesystem_encoding()) self.module = self.globals.get('__name__') self.loader = self.globals.get('__loader__') self.code = tb.tb_frame.f_code # support for paste's traceback extensions self.hide = self.locals.get('__traceback_hide__', False) info = self.locals.get('__traceback_info__') if info is not None: try: info = text_type(info) except UnicodeError: info = str(info).decode('utf-8', 'replace') self.info = info def render(self): """Render a single frame in a traceback.""" return FRAME_HTML % { 'id': self.id, 'filename': escape(self.filename), 'lineno': self.lineno, 'function_name': escape(self.function_name), 'lines': self.render_line_context(), } def render_line_context(self): before, current, after = self.get_context_lines() rv = [] def render_line(line, cls): line = line.expandtabs().rstrip() stripped_line = line.strip() prefix = len(line) - len(stripped_line) rv.append( '<pre class="line %s"><span class="ws">%s</span>%s</pre>' % ( cls, ' ' * prefix, escape(stripped_line) or ' ')) for line in before: render_line(line, 'before') render_line(current, 'current') for line in after: render_line(line, 'after') return '\n'.join(rv) def get_annotated_lines(self): """Helper function that returns lines with extra information.""" lines = [Line(idx + 1, x) for idx, x in enumerate(self.sourcelines)] # find function definition and mark lines if hasattr(self.code, 'co_firstlineno'): lineno = self.code.co_firstlineno - 1 while lineno > 0: if _funcdef_re.match(lines[lineno].code): break lineno -= 1 try: offset = len(inspect.getblock([x.code + '\n' for x in lines[lineno:]])) except TokenError: offset = 0 for line in lines[lineno:lineno + offset]: line.in_frame = True # mark current line try: lines[self.lineno - 1].current = True except IndexError: pass return lines def eval(self, code, mode='single'): """Evaluate code in the context of the frame.""" if isinstance(code, string_types): if PY2 and isinstance(code, unicode): # noqa code = UTF8_COOKIE + code.encode('utf-8') code = compile(code, '<interactive>', mode) return eval(code, self.globals, self.locals) @cached_property def sourcelines(self): """The sourcecode of the file as list of unicode strings.""" # get sourcecode from loader or file source = None if self.loader is not None: try: if hasattr(self.loader, 'get_source'): source = self.loader.get_source(self.module) elif hasattr(self.loader, 'get_source_by_code'): source = self.loader.get_source_by_code(self.code) except Exception: # we munch the exception so that we don't cause troubles # if the loader is broken. pass if source is None: try: f = open(to_native(self.filename, get_filesystem_encoding()), mode='rb') except IOError: return [] try: source = f.read() finally: f.close() # already unicode? return right away if isinstance(source, text_type): return source.splitlines() # yes. it should be ascii, but we don't want to reject too many # characters in the debugger if something breaks charset = 'utf-8' if source.startswith(UTF8_COOKIE): source = source[3:] else: for idx, match in enumerate(_line_re.finditer(source)): match = _coding_re.search(match.group()) if match is not None: charset = match.group(1) break if idx > 1: break # on broken cookies we fall back to utf-8 too charset = to_native(charset) try: codecs.lookup(charset) except LookupError: charset = 'utf-8' return source.decode(charset, 'replace').splitlines() def get_context_lines(self, context=5): before = self.sourcelines[self.lineno - context - 1:self.lineno - 1] past = self.sourcelines[self.lineno:self.lineno + context] return ( before, self.current_line, past, ) @property def current_line(self): try: return self.sourcelines[self.lineno - 1] except IndexError: return u'' @cached_property def console(self): return Console(self.globals, self.locals) id = property(lambda x: id(x))
[ "yc5424tl@go.minneapolis.edu" ]
yc5424tl@go.minneapolis.edu
f5e459ebbfef6862e4992d3499bdaf13c543b19f
f6568cd38c80cf34fda709372e1e9df013d8d893
/api.py
94fd7142c941d957a45e385ff7e864ff593728ab
[]
no_license
Ibaii99/UDBank_Backend
311d62795115e4142a023698e7030d5370d99f1e
6657326fe3282f5bb3ed32200ba7e2eb9489e1a1
refs/heads/master
2023-01-27T21:28:25.570498
2020-12-15T16:04:05
2020-12-15T16:04:05
308,669,654
0
0
null
null
null
null
UTF-8
Python
false
false
3,059
py
from flask import Flask, Blueprint, abort, request, Response, jsonify from flask_cors import CORS, cross_origin import json from routing import api_markets, api_users import config import logging from logic.authorization import Authorization app = Flask(__name__) app.register_blueprint(api_markets.markets_blueprint, url_prefix=config.API_URL_PREFIX+"/market") app.register_blueprint(api_users.users_blueprint, url_prefix=config.API_URL_PREFIX + "/user") cors = CORS(app, resources={r"/*": {"origins": "*"}}) app.config['CORS_HEADERS'] = ['Content-Type', 'Authorization'] @app.route('/', methods=["GET"]) @cross_origin() def hello(): return "Hello World!" @app.before_request def check_api_key(): if request.method == 'OPTIONS': resp = app.make_default_options_response() headers = None if 'ACCESS_CONTROL_REQUEST_HEADERS' in request.headers: headers = request.headers['ACCESS_CONTROL_REQUEST_HEADERS'] h = resp.headers # Allow the origin which made the XHR h['Access-Control-Allow-Origin'] = request.headers['Origin'] # Allow the actual method h['Access-Control-Allow-Methods'] = request.headers['Access-Control-Request-Method'] # Allow for 10 seconds h['Access-Control-Max-Age'] = "10" # We also keep current headers if headers is not None: h['Access-Control-Allow-Headers'] = headers return resp else: logging.warning("BEFORE") # logging.warning(request.headers) api_key = request.headers.get("X-Api-Key") try: auth = request.headers.get("Authorization") except: auth = None if (api_key is not None and auth is not None): if not Authorization.authorize_user_token(request) or not Authorization.authorize_front(api_key): abort(401) else: pass elif (api_key is not None and auth is None): if not Authorization.authorize_front(api_key) and is_get_token_route(request.url_rule): abort(401) else: pass else: abort(403) @app.after_request def save_history(response): logging.warning("After") # logging.warning(response) # logging.warning(request) # logging.warning(request.headers) # logging.warning(request.cookies) # logging.warning(request.args) # logging.warning(request.url_rule) return response def is_get_token_route(route): login_route= "/api/v1/user/login" register_route= "/api/v1/user/register" if route == login_route or route == register_route: return True else: return False @app.errorhandler(403) def page_not_found(e): return jsonify(json.dumps("Forbbiden acces, invalid api-key")), 403 @app.errorhandler(401) def page_not_found(e): return jsonify(json.dumps("Incorrect username or password")), 401 if __name__ == '__main__': app.run(debug=True, host=config.HOST, port=config.PORT)
[ "ibai.guillen@opendeusto.es" ]
ibai.guillen@opendeusto.es
3042bee8e5fdb405c62cccbf457d4aed30ba0329
c094f9ca9c17dd118bdb9c9bc09655dfc0ffe54a
/decorators.py
abe3be3c6b58edc36129729d73e5ce4165301856
[]
no_license
Jfengames/POIplatform
457314bd9aa4f92d7fe25706cf7e3154d9500f1d
46a15ad0445654b1ffa0b00abefaf3c54466a876
refs/heads/master
2020-08-08T12:34:17.245359
2019-10-09T06:02:22
2019-10-09T06:02:22
213,832,730
0
0
null
null
null
null
UTF-8
Python
false
false
339
py
# -*- coding: utf-8 -*- from functools import wraps from flask import session,redirect,url_for def login_required(func): @wraps(func) def wrapper(*args,**kwargs): if session.get('user_id'): return func(*args,**kwargs) else: return redirect(url_for('user.login')) return wrapper
[ "liujing1@cmdi.chinamobile.com" ]
liujing1@cmdi.chinamobile.com
edfbecf34931307c37d1dccefce4368309ee17b9
cef1814ad7fdbb5542a0ccd0acfc9b1d3655f131
/itchat/wechat_face/weixin.py
2cf0844ee0e1f600029ca19fce5034fcdc2f7b49
[]
no_license
qsx6003/shiyan
8c914eca4c141672cfc6369718c0fb2fe4021f01
4dc6a320bfa10c184d522ece80d282731f58700f
refs/heads/master
2020-04-06T23:05:27.852622
2019-01-02T07:18:41
2019-01-02T07:18:41
157,857,699
0
0
null
null
null
null
UTF-8
Python
false
false
4,809
py
#!/usr/bin/python # coding: utf-8 import itchat import os import pandas as pd import matplotlib.pyplot as plot from wordcloud import WordCloud from pyecharts import Bar, Page import jieba import sys import itchat # 获取所有的群聊列表 def getRoomList(): roomslist = itchat.get_chatrooms() return roomslist #获取指定群聊的信息 def getRoomMsg(roomName): itchat.dump_login_status() myroom = itchat.search_chatrooms(name=roomName) return myroom #统计省份信息 def getProvinceCount(cityCount,countName): indexs = [] counts = [] for index in cityCount.index: indexs.append(index) counts.append(cityCount[index]) page = Page() labels = [indexs] sizes = [counts] attr = indexs v1 = counts bar = Bar(countName) bar.add("地区分布", attr, v1, is_stack=True, is_label_show=True, is_datazoom_show=True, is_random=True) page.add(bar) bar.show_config() bar.render() #制作性别统计图 def getSexCount(sexs,countName): labels = [u'男', u'女', u'未知'] sizes = [sexs['男'], sexs['女'], sexs['未知']] print(sizes) colors = ['red', 'yellow', 'blue', 'green'] explode = (0, 0, 0) patches, l_text, p_text = plot.pie(sizes, explode=explode, labels=labels, colors=colors, labeldistance=1.1, autopct='%2.0f%%', shadow=False, startangle=90, pctdistance=0.6) for t in l_text: t.set_size = 30 for t in p_text: t.set_size = 20 plot.axis('equal') plot.legend(loc='upper left', bbox_to_anchor=(-0.1, 1)) plot.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plot.rcParams['axes.unicode_minus'] = False plot.title(countName) plot.grid() plot.show() #制作词云 def makeWorldCount(userName): users = [] for user in userName: users.append(user) users = ','.join(users) print(users) # font = os.path.join(os.path.dirname(__file__), "DroidSansFallbackFull.ttf") font = "./xindexingcao57.ttf" wordcloud = WordCloud(font_path=font,width=1800, height=800, min_font_size=4, max_font_size=80,margin=2).generate(users) plot.figure() plot.imshow(wordcloud, interpolation='bilinear') plot.axis("off") plot.show() #获取性别统计 def getSex(df_friends): sex = df_friends['Sex'].replace({1: '男', 2: '女', 0: '未知'}) sexCount = sex.value_counts() return sexCount #男性个性签名统计 def analyMale(df_friends): signature = df_friends[df_friends.Sex == 1]['Signature'] signature = signature.unique() signature = "".join(signature) wordlist_after_jieba = jieba.cut(signature, cut_all=True) wl_space_split = " ".join(wordlist_after_jieba) font = "./xindexingcao57.ttf" wordcloud = WordCloud(font_path=font,max_words = 200, max_font_size=50,margin=2).generate(wl_space_split) plot.figure() plot.imshow(wordcloud, interpolation='bilinear') plot.axis("off") plot.show() #女性个性签名统计 def analyFemale(df_friends): signature = df_friends[df_friends.Sex == 2]['Signature'] signature = signature.unique() signature = "".join(signature) wordlist_after_jieba = jieba.cut(signature, cut_all=True) wl_space_split = " ".join(wordlist_after_jieba) font = "./xindexingcao57.ttf" wordcloud = WordCloud(font_path=font,max_words = 200, max_font_size=50,margin=2).generate(wl_space_split) plot.figure() plot.imshow(wordcloud, interpolation='bilinear') plot.axis("off") plot.show() def main(): itchat.auto_login(hotReload=True) #自动登陆 l=getRoomList() myroom=(l[0]['NickName']) roomMsg = getRoomMsg(myroom) # print(roomMsg) #获取指定群聊的信息 print("---------------------------------------------------------") gsq = itchat.update_chatroom(roomMsg[0]['UserName'], detailedMember=True) # print(gsq) df_friends = pd.DataFrame(gsq['MemberList']) #取出其中的用户信息并转为dataframe # print(df_friends) # print(type(df_friends['NickName'])) # sexs = getSex(df_friends) #获取性别统计 # getSexCount(sexs,"群男女统计图") #制作性别统计图,第一个参数为性别统计的结果,第二个参数为该图的名称 # city = df_friends['Province'] #取出省份信息 # City_count = city.value_counts()[:15] # City_count = City_count[City_count.index != ''] # getProvinceCount(City_count,"位置统计图") #制作位置统计图,第一个参数为位置统计的结果,第二个参数为该图的名称 makeWorldCount(df_friends['NickName']) #制作词云,传入用户昵称 # makeWorldCount(signature) # analyMale(df_friends) if __name__=='__main__': main()
[ "qsx6003@qq.com" ]
qsx6003@qq.com
515ebe8f255758359ff6ad105115b0ad5912e78f
326aa922ce75b52ac68fdf9d5940e38837739b22
/linkypedia/wikipedia.py
30f2bb7fc6d085da380650784d9de13d38a9d130
[]
no_license
Web5design/linkypedia
9f7b0546b3086c4dae63a1ae4e98e1f6b93138cd
76d5ecdaa00579f3fb773c3cbf2d4f91c5513b9e
refs/heads/master
2020-12-24T11:05:56.104945
2010-11-24T07:17:22
2010-11-24T07:17:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,096
py
""" module for interacting with wikipedia """ import re import sys import json import time import urllib import getpass import logging import urllib2 import irclib import BeautifulSoup from web import tasks RETRIES_BETWEEN_API_ERRORS = 5 IRC_MESSAGE_PATTERN = re.compile('\[\[(.+?)\]\] (.+)? (http:.+?)? (?:\* (.+?) \*)? (?:\(([+-]\d+)\))? (.+)?') class WikipediaUpdatesClient(irclib.SimpleIRCClient): """Fetch live update feed from irc://irc.wikimedia.org/en.wikipedia """ def on_error(self, connection, event): print event def on_created(self, connection, event): connection.join("#en.wikipedia") def on_pubmsg(self, connection, event): msg = self._strip_color(event.arguments()[0]) match = IRC_MESSAGE_PATTERN.search(msg) if match: # todo: add message to queue page, status, diff_url, user, bytes_changed, msg = match.groups() print "page: %s" % page print "status: %s" % status print "diff: %s" % diff_url print "user: %s" % user print "bytes: %s" % bytes_changed print "msg: %s" % msg print # ignore what look like non-articles if ':' not in page: result = tasks.get_external_links.delay(page) result.get() else: # should never happen print "NO MATCH: %s" % msg connection.close() sys.exit(-1) def _strip_color(self, msg): # should remove irc color coding return re.sub(r"(\x03|\x02)([0-9]{1,2}(,[0-9]{1,2})?)?", "", msg) def start_update_stream(username): irc = WikipediaUpdatesClient() irc.connect("irc.wikimedia.org", 6667, username) irc.start() def url_to_title(url): url = str(url) match = re.match(r'http://.+/wiki/(.+)$', url) if match: return urllib.unquote(match.group(1)).decode('utf-8') else: return None def info(title): logging.info("wikipedia lookup for page: %s " % title) q = {'action': 'query', 'prop': 'info', 'titles': title.encode('utf-8'), } return _first(_api(q)) def categories(title): logging.info("wkipedia look up for page categories: %s" % title) q = {'action': 'query', 'prop': 'categories', 'titles': title.encode('utf-8'), } try: return _first(_api(q))['categories'] except KeyError: logging.error("uhoh, unable to find categories key!") return [] def users(usernames): usernames = [u.encode('utf-8') for u in usernames] logging.info("wikipedia look up for users: %s" % usernames) q = {'action': 'query', 'list': 'users', 'ususers': '|'.join(usernames), 'usprop': 'blockinfo|groups|editcount|registration|emailable|gender', } return _api(q)['query']['users'] def extlinks(page_title, limit=100, offset=0): page_title = page_title.replace(' ', '_') q = {'action': 'query', 'prop': 'extlinks', 'titles': page_title, 'ellimit': limit, 'eloffset': offset, } links = _first(_api(q)) if links.has_key('extlinks'): # strip out just the urls from the json response links = [l[u"*"] for l in links['extlinks']] else: # no links links = [] # get more if it looks like we might not have gotten them all if len(links) == limit: links.extend(extlinks(page_title, limit, offset + limit)) return links def links(site, lang='en', page_size=500, offset=0): """ a generator that returns a source, target tuples where source is the url for a document at wikipedia and target is a url for a document at a given site """ links_url = 'http://%s.wikipedia.org/w/index.php?title=Special:LinkSearch&target=%s&limit=%s&offset=%s' wikipedia_host = 'http://%s.wikipedia.org' % lang while True: url = links_url % (lang, site, page_size, offset) html = _fetch(url) soup = BeautifulSoup.BeautifulSoup(html) found = 0 for li in soup.findAll('li'): a = li.findAll('a') if len(a) == 2: found += 1 yield wikipedia_host + a[1]['href'], a[0]['href'] if found == page_size: offset += page_size else: break def _api(params): params['format'] = 'json' url = 'http://en.wikipedia.org/w/api.php' response = _fetch(url, params) data = json.loads(response) return data def _first(data): # some queries can take a list of things but we are only sending # one at a time, and this helper just looks for the first (and only) # page in the response and returns it first_page_key = data['query']['pages'].keys()[0] return data['query']['pages'][first_page_key] def _fetch(url, params=None, retries=RETRIES_BETWEEN_API_ERRORS): if params: req = urllib2.Request(url, data=urllib.urlencode(params)) req.add_header('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8') else: req = urllib2.Request(url) req.add_header('User-agent', 'linkpyediabot v0.1: http://github.com/edsu/linkypedia') try: return urllib2.urlopen(req).read() except urllib2.URLError, e: return _fetch_again(e, url, params, retries) except urllib2.HTTPError, e: return _fetch_again(e, url, params, retries) def _fetch_again(e, url, params, retries): logging.warn("caught error when talking to wikipedia: %s" % e) retries -= 1 if retries == 0: logging.info("no more tries left") raise e else: # should back off 10, 20, 30, 40, 50 seconds sleep_seconds = (retries_between_api_errors - retries) * 10 logging.info("sleeping %i seconds then trying again %i times" % (sleep_seconds, retries)) time.sleep(sleep_seconds) return _fetch(url, params, retries)
[ "ehs@pobox.com" ]
ehs@pobox.com
78177d2aa2f17f925725fc1bbed8eafa87fce33c
e7a62e4a4506a235872af71ef63d634971bb747c
/ggrpc/utils.py
85c6659978a5c24cec3ee5431f84bb990d9f9688
[]
no_license
livingbio/ggrpc
2803a0e4d54645a8f14540e9121dbdc4b65dee06
b7ba6fa7d46a283172e5fe880dbd8f7f09eec4a1
refs/heads/master
2021-05-08T06:08:27.287799
2017-10-16T05:32:16
2017-10-16T05:32:16
106,585,703
0
0
null
null
null
null
UTF-8
Python
false
false
1,889
py
import inspect import jinja2 import json import cPickle def is_defined_method(cls): return inspect.getmembers( cls, predicate=lambda m: inspect.ismethod(m) and m.__func__ in m.im_class.__dict__.values() ) def list_public_method(cls): for method_name, _ in is_defined_method(cls): if method_name[0] == "_": continue method = getattr(cls, method_name) argspec = inspect.getargspec(method) yield method_name, argspec template = """ from ggrpc.rpc_client import RPCClient class {{cls_name}}(RPCClient): "Auto Generate SDK" {% for method, arg in methods %} {% if arg %} def {{method}}(self, {{arg}}): {% else %} def {{method}}(self): {% endif %} return self._call("{{method}}", {{arg}}) {% endfor %} """ def client_factory(kls): # TODO: add func doc in the future methods = [] for name, argspec in list_public_method(kls): args = list(argspec.args[1:]) if argspec.defaults: for k in range(len(argspec.defaults)): idx = -1 - k assert isinstance( argspec.defaults[idx], (basestring, int, float) ) if isinstance(argspec.defaults[idx], basestring): args[idx] = "%s='%s'" % (args[idx], argspec.defaults[idx]) else: args[idx] = "%s=%s" % (args[idx], argspec.defaults[idx]) if argspec.varargs: args.append("*args") if argspec.keywords: args.append("**kwargs") methods.append((name, ", ".join(args))) return jinja2.Template(template).render( cls_name=kls.__name__, methods=methods ) def get_coder(format): CODER = { "json": json, "pickle": cPickle } return CODER[format]
[ "davidchen@gliacloud.com" ]
davidchen@gliacloud.com
ffa5371a5a7cb754fdda979fa92af330672a774f
129428b4c6e4d18dffff830236d15b5507854465
/Exp1/main_exp2.py
2b3dbaa8b14d18e22a1266afd712d85579bd0291
[]
no_license
volpx/lab-2
97dae67fabe8f3bb5fb2be82b66a23419ae7cad8
c4a97a5338d62831eea45ed5c644198257a859e7
refs/heads/master
2020-04-30T23:29:30.171362
2019-04-15T14:42:57
2019-04-15T14:42:57
177,145,335
0
0
null
null
null
null
UTF-8
Python
false
false
5,632
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 11 09:57:32 2018 @author: volpe """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from uncertainties import ufloat #array of colors to use for plots colors=["g","r","b","c"] #import my class and functions from functions import DataXY,w_mean # coverage factor k=2 #parallel and series resistances of ICE testers R_par_10V=2e5 R_par_2V=4e4 R_ser_5mA=63.479143 R_ser_500uA=588.8 #nominal and DMM resistance values R_n=4.7e3 dR_n=235 R_DMM=4596 dR_DMM=0.46 #make an array of DataFrame s with imported data fro my csv files data=[pd.read_csv("data/AmpMon10V5mA.csv"), pd.read_csv("data/AmpMon2V0.5mA.csv"), pd.read_csv("data/AmpVal10V5mA.csv"), pd.read_csv("data/AmpVal2V0.5mA.csv")] #convert in standart si units for df in data: df["mA"]*=1e-3 df.columns=["V","A"] # array of full-scale values for each data series data_fs=np.array([[10,5e-3],[2,500e-6],[10,5e-3],[2,500e-6]]) # array of resolution uncertainties data_Delta=np.array([[0.2,100e-6],[0.04,10e-6],[0.2,100e-6],[0.04,10e-6]]) # get the standard deviation for uncertainties data_sigma=data_Delta/np.sqrt(12) # make an array of DataXY classes, one for each data serie dataseries=[DataXY(data[0]["V"][0:],data[0]["A"][0:],\ data_sigma[0][0],data_sigma[0][1],\ x_label="V",y_label="A",\ name="Amperometro a Monte (FS: 10V/5mA)"),\ DataXY(data[1]["V"],data[1]["A"],\ data_sigma[1][0],data_sigma[1][1],\ x_label="V",y_label="A",\ name="Amperometro a Monte (FS: 2V/500uA)"),\ DataXY(data[2]["V"],data[2]["A"],\ data_sigma[2][0],data_sigma[2][1],\ x_label="V",y_label="A",\ name="Amperometro a Valle (FS: 10V/5mA)"),\ DataXY(data[3]["V"],data[3]["A"],\ data_sigma[3][0],data_sigma[3][1],\ x_label="V",y_label="A",\ name="Amperometro a Valle (FS: 2V/500uA)"),\ ] # get fit plot and save it dataseries[0].getFitPlot()[0].savefig("data/AmpMon10V5mA.pdf",bbox_inches="tight") dataseries[1].getFitPlot()[0].savefig("data/AmpMon2V500uA.pdf",bbox_inches="tight") dataseries[2].getFitPlot()[0].savefig("data/AmpVal10V5mA.pdf",bbox_inches="tight") dataseries[3].getFitPlot()[0].savefig("data/AmpVal2V500uA.pdf",bbox_inches="tight") # make plot with all datasets # create a figure fig_all=plt.figure() # put title fig_all.suptitle("Confronto datasets") #get new ax ax_all=fig_all.add_subplot(1,1,1) # plot in the ax the errorbar and the fit for i,data in enumerate(dataseries): ax_all.errorbar(data.x, data.y, yerr=data.dy, xerr=data.dx, fmt=colors[i]+".") ax_all.plot([0, data.x.max()], data.getModel(x=np.array([0, data.x.max()])), colors[i]+",-", label=data.name) #put grid ax_all.grid() # put axis labels ax_all.set_ylabel("A") ax_all.set_xlabel("V") # put legend on the top left ax_all.legend(loc="upper left",bbox_to_anchor=(-.01,1.01)) # format ticks with scientific notations ax_all.ticklabel_format(style="sci",scilimits=(0,0)) # save figure fig_all.savefig("data/FigAll.pdf",bbox_inches="tight") ## Summary # create two uninitialized array of size=(4,) R_x=np.empty(4) dR_x=np.empty(4) # set index i=0 # print preformatted DataXY informations dataseries[i].prettyPrint(ddof=2,dy_prop=True) # get linear regression parameters A,B,dA,dB = dataseries[i].getLinearRegressionAB() # save corresponding R_x in the R_x[] array with its uncertainty R_x[i]=1/(B - 1/R_par_10V) dR_x[i]=np.abs(-1/(B-1/R_par_10V)**2) * dB # print value and uncertainty print("Rx =",ufloat(R_x[i],dR_x[i])) i=1 dataseries[i].prettyPrint(ddof=2,dy_prop=True) A,B,dA,dB = dataseries[i].getLinearRegressionAB() R_x[i]=1/(B - 1/R_par_2V) dR_x[i]=np.abs(-1/(B-1/R_par_2V)**2) * dB print("Rx =",ufloat(R_x[i],dR_x[i]) ) i=2 dataseries[i].prettyPrint(ddof=2,dy_prop=True) A,B,dA,dB = dataseries[i].getLinearRegressionAB() R_x[i]=1/B - R_ser_5mA dR_x[i]=np.abs(1/B**2) * dB print("Rx =",ufloat(R_x[i],dR_x[i]) ) i=3 dataseries[i].prettyPrint(ddof=2,dy_prop=True) A,B,dA,dB = dataseries[i].getLinearRegressionAB() R_x[i]=1/B - R_ser_500uA dR_x[i]=np.abs(1/B**2) * dB print("Rx =",ufloat(R_x[i],dR_x[i]) ) #another blank line print() ## Weighted mean # get weighted mean R_w,dR_w=w_mean(R_x,1/dR_x**2) # print weighted mean print("Weighted mean=",ufloat(R_w,dR_w)) ## Compatibility of Rxs fig_comp=plt.figure() ax_comp=fig_comp.add_subplot(1,1,1) for j,i in enumerate([2,0,3,1]): # plot an undefinitely long vertical line ax_comp.axvline(x=R_x[i],color=colors[i],label=dataseries[i].name) # make a vertical span with width equal to k*sigma for each side ax_comp.axvspan(xmin=R_x[i]-k*dR_x[i], xmax=R_x[i]+k*dR_x[i], ymin=0.8-.2*j, ymax=1-0.2*j, color=colors[i],alpha=0.2) # also plot R_n and R_DMM in the same plot ax_comp.axvline(x=R_n,color="#464a45",label="R_n") ax_comp.axvspan(xmin=R_n-dR_n,xmax=R_n+dR_n,color="#464a45",alpha=0.2) ax_comp.axvline(x=R_DMM,color="#EEEE00",label="R_DMM") ax_comp.axvspan(xmin=R_DMM-k*dR_DMM, xmax=R_DMM+k*dR_DMM, color="#EEEE00", alpha=0.2) ax_comp.axvline(x=R_w,color="#ff8000",label="R_w") ax_comp.axvspan(xmin=R_w-k*dR_w, xmax=R_w+k*dR_w, ymin=0, ymax=0.2, color="#ff8000",alpha=0.2) ax_comp.set_xlabel(u"R [Ω]") # disable ticks on y axis ax_comp.set_yticks([]) ax_comp.legend(loc="center left",bbox_to_anchor=(1.03,.5)) fig_comp.suptitle("Comparazione Rx") fig_comp.savefig("data/fig_comp.pdf",bbox_inches="tight")
[ "filippovolpe98@gmail.com" ]
filippovolpe98@gmail.com
65dab5a6ab864efe241f5df07edfcd1772b1a062
9cbe07eefab8d4a289cd1454a2fad733dfaa3b65
/jobScript.py
417dd046f6c769584138d514a0e6b9870b6f38c9
[]
no_license
cosmic-byte/jenkins-seedstar
17df54fcf7c85f2c17fc71238bd7fac9c26d33cb
63b1952b9737b6d2c5624e58e680244b27c3c8a3
refs/heads/master
2020-03-17T09:50:05.950571
2018-05-15T11:05:10
2018-05-15T11:05:10
133,490,200
0
0
null
null
null
null
UTF-8
Python
false
false
493
py
from config import DbOperations from initialScript import Initiate import time class Job: def __init__(self): self.db = DbOperations() self.init = Initiate() self.server = self.init.server def start_jobs(self): for job in self.server.get_jobs(): self.db.save(data={'name': job['name'], 'status': job['color'],'time': str(time.time())}) if __name__ == '__main__': job = Job() job.start_jobs() job.init.conn.close()
[ "gregobinna@gmail.com" ]
gregobinna@gmail.com
b75ee3f36e05409921bc8b395d47017f390f3ae1
2b21a7423f31163f0571161501477e6262a22b55
/jackdaw/nest/ws/protocol/graph/edge.py
ca9a65f1ed7b12a8cba3c7d72d998d66467c4426
[]
no_license
hartl3y94/jackdaw
e2ae9e98cb97a7f1b3c0545042b0985220316720
3876298e1568fe8d811e86668e428a5fd937cd5a
refs/heads/master
2023-04-03T06:36:04.850552
2021-03-30T20:26:43
2021-03-30T20:26:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,185
py
import json from jackdaw.utils.encoder import UniversalEncoder from jackdaw.nest.ws.protocol.cmdtypes import NestOpCmd class NestOpEdgeRes: def __init__(self): self.cmd = NestOpCmd.EDGERES self.token = None self.adid = None self.graphid = None self.src = None #oid! self.dst = None #oid! self.weight = 1 def to_dict(self): return self.__dict__ def to_json(self): return json.dumps(self.to_dict(), cls = UniversalEncoder) @staticmethod def from_dict(d): cmd = NestOpEdgeRes() cmd.token = d['token'] return cmd @staticmethod def from_json(jd): return NestOpEdgeRes.from_dict(json.loads(jd)) class NestOpEdgeBuffRes: def __init__(self): self.cmd = NestOpCmd.EDGEBUFFRES self.token = None self.edges = [] #NestOpEdgeRes def to_dict(self): return { 'cmd' : self.cmd.value, 'token' : self.token, 'edges' : [edge.to_dict() for edge in self.edges], } def to_json(self): return json.dumps(self.to_dict(), cls = UniversalEncoder) @staticmethod def from_dict(d): cmd = NestOpEdgeBuffRes() cmd.token = d['token'] return cmd @staticmethod def from_json(jd): return NestOpEdgeBuffRes.from_dict(json.loads(jd))
[ "info@skelsec.com" ]
info@skelsec.com
dfad1b42391031f515e48a57c8eed77457ce3aed
38855188ec752e7e012cd5d3f8aec8ec0a1645a0
/betse/lib/pil/pils.py
3bc3c6c15c881c401d4f4893149f93587884e8d2
[]
no_license
R-Stefano/betse-ml
660a35ff587e649a7758e6af0766f5c1c7694544
dd03ff5e3df3ef48d887a6566a6286fcd168880b
refs/heads/master
2023-05-01T01:42:14.452140
2021-05-10T09:58:14
2021-05-10T09:58:14
343,448,365
0
0
null
null
null
null
UTF-8
Python
false
false
2,641
py
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright 2014-2019 by Alexis Pietak & Cecil Curry. # See "LICENSE" for further details. ''' High-level support facilities for Pillow, the Python Image Library (PIL)-compatible fork implementing most image I/O performed by this application. ''' #FIXME: Revisit imageio when the following feature request is resolved in full: # https://github.com/imageio/imageio/issues/289 # ....................{ IMPORTS }.................... from PIL import Image from betse.util.io.log import logs from betse.util.path import pathnames from betse.util.type.decorator.decmemo import func_cached from betse.util.type.types import SetType # type_check, # ....................{ GETTERS }.................... @func_cached def get_filetypes() -> SetType: ''' Set of all image filetypes supported by the current version of Pillow. For generality, these filetypes are *not* prefixed by a ``.`` delimiter. Examples ---------- >>> from betse.lib.pil import pils >>> pils.get_filetypes() {'flc', 'bmp', 'ppm', 'webp', 'j2k', 'jpf', 'jpe', 'pcd'} ''' # Initialize Pillow if uninitialized. # # If Pillow is uninitialized, the "Image.EXTENSION" dictionary is empty. # Since the betse.util.app.meta.appmetaabc.AppMetaABC.init_libs() function # already initializes Pillow, explicitly doing so here should typically # *NOT* be necessary. Since this getter could technically be called from # global scope prior to the initialization performed by "betse.ignition" # *AND* since this initialization efficiently reduces to a noop if # unnecessary, manually initializing Pillow here is cost-free... and # cost-free is the way to be. init() # Return a set of... return set( # This filetype stripped of this prefixing "."... pathnames.undot_filetype(filetype_dotted) # For each "."-prefixed filetype supported by Pillow. for filetype_dotted in Image.EXTENSION.keys() ) # ....................{ ENUMERATIONS }.................... def init() -> None: ''' Initialize Pillow if uninitialized *or* reduce to a noop otherwise (i.e., if Pillow is already initialized). ''' # Log this initialization. logs.log_debug('Initializing Pillow...') # If Pillow is already initialized, this function internally reduces to an # efficient noop in the expected manner (e.g., by accessing a private # boolean global). Image.init()
[ "stefano.bane@gmail.com" ]
stefano.bane@gmail.com
6ebcfe4e029f3799a42a8fc2b2fef9f9e24ac99b
01d6b89601647068f782d098b09c2992cb99af9f
/key_michael.py
9cddc646db4b216c62f7ee3cd395b39d1127d1f6
[]
no_license
Michy01/AppDevAIIP
e767846fd2cb63d6335e7a8f4e808d2ce69f7200
42801f74d6dee30399568834c60b398b9b6303ae
refs/heads/master
2023-01-24T07:48:01.049655
2020-11-09T17:36:26
2020-11-09T17:36:26
292,605,052
0
0
null
null
null
null
UTF-8
Python
false
false
3,326
py
-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: AES-128-CBC,E63EB47102188DEA1C1A6B2355411D62 kp6eSUDZ1YfpnjKcoecEb6KhwKzfyU62/4Wio/800qS53qiUZQVE0ADLC6noz6W/ s0h8LTGrMMpEFdjb4klH5N7KhhY6Kp7JgPxLv6gN/UPBnTzKqcpMXgIvORHwIHwp 0VxbZgVHGym6vQIFWSiPRmAuw0xBSKlMSrHqxYZjOKTjLk9/vDfjiCek066fj//C 64m5+dgLQZ8eBbPZ3qqWyPyZXikFXZtHNr/wU7eZza5jdlmOxDcekAJOK9r670Fu WJeJQBjjzHErc1GZJJYrj2mAqTtJ80AsHx0+cRrZSAn9GyVepe/c0/J+Tjbi9P9a sETZVMecUZJWR/C3EDqJQsnnh/HhKG6+cB5CSDMu5Jb38JAYEtqqH+NKFakwiVAM FnzUD8Z0Hs7mfYhtfbaG1WJgoOBEXpdnUL4xibOcpz3cacmUSOUvK30YNshHmjQf 4p0Vf38MDe2au/D5PCeQ/DrxCuf1nE3IEkuvxJ6bt1g3KZhSB2d0u6CWe6jgMN13 3MXGYkMyY7cU3PGI/3o7GGuS1yoiQODTpWQ8oGcgBibPP7o5BZxHzBzCuVxfO+tg omTNMaRj0DBHuLVqP7Pnay9VDbgpCo/BcKFJVjajNkPLGACN1iNElRDnDCpvg5wK yKn/ob3TaeAFpeosbmQ3ddiz1Oif8UDV5QLF7RA0OfDaTu3YUmntMF3zdTalAt6w tZzcOiG+g3/PoWxp/ZZlLoRY7QOZX4uSONljF7ru/KaR+E/Fgbv0chhe64ECwKLx LW3MjoX5Obfh6iiemceBnlu5kjOD3Froy9xPM38cU1afaNMGx05p2ffV+WVXDjSf UB0QD2olRUFNUZ/oB30MswMFStbUaTsQSCH2Hr7Jmv1RwxgUQnBHSa2IoqxBmHar sYJbzNaXy+nCiNGz6tf0u1TygX6gkfe59G9hxohSG1FHOcSB3y3o8NdO6ky6HV9G L/ZWhlblGA/aeooI6sYTV+b85l7tavTPy7swhkk+Uz89kKZFBCFllrFRAYUjysPa zJPy+W5M08gRNHQ2Y84iUv5KmNJJGKnkXBfcR6EUgHthL45fqCU6sF7ssYeSO+jg AgjDMR7iZlm3kim8D4uCgfXKAC3EFwJrjt6zLaFtUJq1blEBIpzbEi6ZztLtl1HD c2baNoWLzYBvMAZ1jNmvh3Kk7crTUn2HW0mXKjNbGdj4w+h3ExkGFMpcn1P6/2s4 AxZilmszKCHJXq8ANx94c5VgEfjmUbD95BOHuA73f71whrXkVc/7XP7DkvhWjogF 2zmCqpXWW2WiTk2lK8Ydw/FOlGPxUmcsGqkFZrUiGeTHJmv5xdI1Zr/BN/6k5akP iViM2GQXWqyZD2PQPrHZQQJ7xIxJzLmnZ3sDAX2SZ5xNTgGq20WIJBcxmgIQn7kD W7XlECqs46G5LgmXxrab54MXHfbFmx8xT5pGQ1ohSZnLVZbX6akMLoGy5NsdIJcc 026Pfs0SZ1/g25HXyXXOUmmKCIcKD+KchvibyfIpZYMcbd5dkit+XLlpMlXxa2IN 9cGY+CEhFEXnjlinJfqMKAKy3gl/ln6iDkB1DgpOMPAAfy+ZCk+6ILdmlwYFpwZs jG8oQ1amSpSEBt6pWjcWfkj84nJl8QfjbgnjUPhvUs8f8/x76ZxMSbBANtzXW175 fs7VqDMSgfQM34icENfZ2ZZ8Ho/VJzG5AJ0JOBn5B10KriMBUERAB9dbfna4fUfe yRBs/SDmMTabc9ER+K1ruFoYAtbPM6B/4hW2x9BrQtcAdkg3gSR292G3XY7EV5n5 LWR3wB5CKfrTrArJmIVzDFTxSfmbTU4RgjHCbNVWtm+oW02DU2QxXsZGPyYDftR7 Yqeh78YyagJk2yUFwSHkXRWv1lJZJ3OgvU4xgNWMe4RjuGW5N0k24uONBObo/18X l2NCASZ9fobOX/3gr5csJJRkt56pm2EcN99q0tFt53mCW/nvfrv4Z8dB5i6+12GH xgwJVYCcoPGxGYXLGKU7r0sfCqLop7BnImn7jpUoGEZQvX2Spb/o6yygs+gYaQfF ByE2Atmb5VrzbhcfrZZXlPt2gE96/bJC7BNt2Y7KAtly/YN4x+bv+ymkHoufxuMq pxWjmFglXE9OQ3hy7Y4oBMywYZUPb8IhuTdslQOOYtP12pm3XzmZidI02VK1Wv52 FG5WaoRCNX8DS+RYmBP9JCqKIUUv44svl+UETBtaAsUUQKKdKQTnUv7r/AxJz8RT DqqjZcp0CKK9uqA3dWraa3IpNypeIyV3A8hFgoeqJIwZ5R1w1egUSy3OlDZca8i6 B0RHljHpBiN8dn8Eh3PWhDzOOdzxJdtT1hL8T3u2oIY8OPPc9IplOVLWIMV4S4+/ 9RsGagGsJrkqhJqtbIF6S8iJd+bSRHpqBz+M84wDFhVKUSRkbZWcn2d5QQb6Ma6F JDXewMsnQgBNI1T8A4XYQco5GQxpgbeuzxlx6JQJfysD4Md+jQHKNpDVEuNAXv18 jeUDYZP2ijWeA7dfeAlrML6DZkl19bE8u3qvMHxmH0O0NvCxRkO/YZo/JBb/7UW9 0G4yc/cwWPif2h5zY2OA85JTnwl/Lv5n2WyzdYIw6QkfmOrg+SPLj5+bcxOfdM9i v4BFvRbj33Rydc9w1ptvVUoz/lDyBOh9a2ZqHJaf7BTjDpsZ3GIq/4UbnDX5Q71e JgjFGXALbzw3AEHws0FGoFscgoF9rIxFaz0xvBUS+cjP4Cq4IFZnoX9lTYbZv/OG sUo0vRU8o/P0IgPPRh4RgBS5V/ci0DVAJQeqZ0pjvmu7vpT6ZFA/he06jmKjFFko oQdDBtvdGULevXkGeSs5/nYlSsJuJovHAHQUnbvxaOveHLBWtJ5egflxAE5lWyzw JDVrA9aH/3e4UlYRq36VHX8LBpLBS6N8LJtP5haTzygeB6MWH/fF6qAQi3p3MUBg GzwQAVr40dGkslMECFxKagfMarApznWPaCGkkvbq8NM+Y94QvQytJ6TOg9N8ryZ7 H3EzrYfcQGnsC/w7lstarUvyc7XYoVNnSvSw8YRtvdYqd/c3uqg9TUNXj3uDvXJH Ki4d4dDs3//H92NF4KaA+UG3QFZh3Xo1pTFCyvduXF+/n1yof5N8tba+hieQzMbj -----END RSA PRIVATE KEY-----
[ "33031915+Michy01@users.noreply.github.com" ]
33031915+Michy01@users.noreply.github.com
078d5829bda895eb10fd67609d507f566beefbd0
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/kbtju9wk5pjGYMmHF_15.py
d15d3b948a148c0a450ba5d8c461728c858ee823
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
1,523
py
""" Write a class called `Name` and create the following _attributes_ given a **first name** and **last name** (as `fname` and `lname`): * An attribute called `fullname` which returns the first and last names. * A attribute called `initials` which returns the first letters of the first and last name. Put a `.` between the two letters. Remember to allow the attributes `fname` and `lname` to be accessed individually as well. ### Examples a1 = Name("john", "SMITH") a1.fname ➞ "John" a1.lname ➞ "Smith" a1.fullname ➞ "John Smith" a1.initials ➞ "J.S" ### Notes * Make sure only the first letter of each name is capitalised. * Check the **Resources** tab for some helpful tutorials on Python classes. """ class Name: def __init__(self,fname, lname): self.fname = fname.capitalize() self.lname = lname.capitalize() self.fullname = fname.capitalize() +' '+lname.capitalize() self.initials = fname[0].capitalize()+'.'+lname[0].capitalize()
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
0774bbf2001ec249aa5d11df4e020b147123755c
c5a7003de780b3b92f4dff39d5b9d8364bdd28a8
/HW3/code/LucasKanadeAffine.py
5a0b7285df231a49ca0f3a76e4d881aaea2d6c31
[ "ICU" ]
permissive
rainmiku/16720-19Spring-Homework
961bb00e1ba46de7acc9884ec61c32389d5a6f4a
9ebc8e178bd2cca85ada52f0cb8ea5f22b47d57e
refs/heads/master
2020-06-18T15:29:02.340995
2019-04-22T03:57:41
2019-04-22T03:57:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,845
py
import numpy as np from scipy.interpolate import RectBivariateSpline def LucasKanadeAffine(It, It1): # Input: # It: template image # It1: Current image # Output: # M: the Affine warp matrix [2x3 numpy array] # put your implementation here M = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) p = M.flatten() x1, y1, x2, y2 = 0, 0, It.shape[1] - 1, It.shape[0] - 1 threshold = 1e-3 dp = np.array([float("inf")] * 6) interpolated_It1 = RectBivariateSpline( x = np.array([i for i in range(int(It1.shape[0]))]), y = np.array([i for i in range(int(It1.shape[1]))]), z = It1 ) while np.sum(np.square(dp)) >= threshold: x = np.arange(x1, x2 + .5) y = np.arange(y1, y2 + .5) X = np.array([x for i in range(len(y))]) Y = np.array([y for i in range(len(x))]).T warp_X = p[0] * X + p[1] * Y + p[2] warp_Y = p[3] * X + p[4] * Y + p[5] valid_points = (warp_X >= x1) & (warp_X <= x2) & (warp_Y >= y1) & (warp_Y <= y2) X, Y = X[valid_points], Y[valid_points] warp_X, warp_Y = warp_X[valid_points], warp_Y[valid_points] warp_It1x = interpolated_It1.ev(warp_Y, warp_X) dx = interpolated_It1.ev(warp_Y, warp_X, dx = 0, dy = 1).flatten() dy = interpolated_It1.ev(warp_Y, warp_X, dx = 1, dy = 0).flatten() A = np.array([ dx * X.flatten(), dx * Y.flatten(), dx, dy * X.flatten(), dy * Y.flatten(), dy, ]).T b = (It[valid_points] - warp_It1x).flatten() dp = np.dot(np.linalg.inv(np.dot(A.T, A)), np.dot(A.T, b)) p += dp.flatten() M = np.copy(p).reshape(2, 3) M = np.vstack((M, np.array([[0, 0, 1]]))) return M
[ "liuzihua0911@gmail.com" ]
liuzihua0911@gmail.com
9c97825770db34605f07c3b83f40d56fe2a7db44
c43a9ac4356c6f1e457728f7e370ddee0ad3de73
/experiment_3alphas.py
51b4209aab9644744de38e8b547291b7e7ac507a
[]
no_license
desajm/nuclear-duck
a96846ce30c31a9146ba33a492bd8310254e327b
2d7d33037852e907f7411dd4008316355ac30592
refs/heads/master
2021-01-19T00:44:51.864922
2016-12-06T07:54:08
2016-12-06T07:54:08
73,262,823
1
0
null
null
null
null
UTF-8
Python
false
false
1,540
py
DEPENDENCY_MODULE = 'duck_mc_3alphas' E_12_START = 0. E_12_STOP = 30.0 E_12_STEP = 0.1 BROJ_PONAVLJANJA = 1000000 def duck_mc_experiment(E_12, broj_ponavljanja, postav_index): """ postavke detektora na BoBo eksperimentu """ POSTAV = { 'postav_1': {'distance': [0.35875,0.35675,0.35775,0.35975], 'theta': [40.49, 20.00, 19.995, 40.095], 'phi': [0, 0, 180, 180], 'num_stripes': 16, 'detector_width': 0.05}, 'postav_2': {'distance': [0.35875,0.35675,0.35775,0.35975], 'theta': [40.49, 20.00, 30.00, 50.00], 'phi': [0, 0, 180, 180], 'num_stripes': 16, 'detector_width': 0.05}, 'postav_3': {'distance': [0.35875,0.35675,0.35775,0.35975], 'theta': [46.49, 26.00, 33.00, 53.00], 'phi': [0, 0, 180, 180], 'num_stripes': 16, 'detector_width': 0.05} } kwargs = { "E_p": 72.132, "m_p": 10., "m_t": 10., "m_X": 12., "m_E": 8., "m_C": 8., "m_D": 4., "m_F": 4., "m_G": 4., "Q_01": 16.12971, #(za vrh Q1, 19.15971 - 3.03) # Q_0 za reakciju 1 "E_prag": 7.3666, "Emin_F": [9.4, 9.7, 8.9, 8.7], #za det na 0st "Emin_G": [9.4, 9.7, 8.9, 8.7], "Emin_D": [9.4, 9.7, 8.9, 8.7], } detectors = [duck_mc_3alphas.define_detector(POSTAV, i, postav_index) for i in range(4)] try: result = duck_mc_3alphas.calculate_event_detection_E12(detectors, E_12, broj_ponavljanja, **kwargs) except: e = sys.exc_info()[0] return e return result
[ "sthagon@gmail.com" ]
sthagon@gmail.com
b2b25cf7aaeac3807cceceae1ae7569dc7dfce2e
c5e67f1c80d7fe10945c124ee3647f0eb66422f5
/rise_finding.py
bf79870bf488c38f108ec35f9d7b46b800d97f68
[]
no_license
eugeneegbe/algorithm-problems
116c0cd1f6491b7640a49bcf065cd20d2dd82ed0
43f07440e034d0d069c071cbdca1b3173417c6d5
refs/heads/master
2021-01-06T12:23:47.124373
2020-02-18T14:24:57
2020-02-18T14:24:57
241,324,538
0
0
null
2020-02-18T14:24:59
2020-02-18T09:45:02
null
UTF-8
Python
false
false
540
py
def solution(A): ''' Finds the positions where there is a rise in an array of numbers sort of the form /\___/\___/\ solved using divide and conquer ''' middle = int(len(A)/2) peaks = [] if A[middle] <= A[ middle - 1 ]: for i in range(middle): if A[ i + 1 ] >= A[ i ]: peaks.append( i + 1 ) if A[middle + 1] >= A[ middle ]: for j in range(middle, len(A) - 1): if A[j + 1] >= A[j]: peaks.append(j + 1) else: return -1 return peaks # Example print(solution([7,2,4,3,0,7,2,20]))
[ "agboreugene@gmail.com" ]
agboreugene@gmail.com
0e216ee3952cad44c0c3814f5b9cec6975428adf
b5e93a09ee136b2b035c9958557e3e4091d8d9fd
/test/test_metrics.py
8cf8eb4656f35a7a5c246a3247a9541a2df15d34
[ "MIT" ]
permissive
ccglyyn/pytorch-hrvvi-ext
2ee0cd27461c344783150535fbadea5fbe29f25b
a020da3543982464ff3888ff84b311e98a130d6d
refs/heads/master
2022-04-20T13:35:07.561985
2020-04-21T10:36:36
2020-04-21T10:36:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,971
py
# import numpy as np # # from horch.detection import BBox # from horch.detection.eval import mean_average_precision # from toolz.curried import groupby # # # def test_mAP(): # detections = [ # (1, 0, [5, 67, 31, 48], .88), # (1, 0, [119, 111, 40, 67], .70), # (1, 0, [124, 9, 49, 67], .80), # (1, 1, [2, 3, 28, 29], .90), # (2, 0, [64, 111, 64, 58], .71), # (2, 0, [26, 140, 60, 47], .54), # (2, 0, [19, 18, 43, 35], .74), # (3, 0, [109, 15, 77, 39], .18), # (3, 0, [86, 63, 46, 45], .67), # (3, 0, [160, 62, 36, 53], .38), # (3, 0, [105, 131, 47, 47], .91), # (3, 0, [18, 148, 40, 44], .44), # (4, 0, [83, 28, 28, 26], .35), # (4, 0, [28, 68, 42, 67], .78), # (4, 0, [87, 89, 25, 39], .45), # (4, 0, [10, 155, 60, 26], .14), # (5, 0, [50, 38, 28, 46], .62), # (5, 0, [95, 11, 53, 28], .44), # (5, 0, [29, 131, 72, 29], .95), # (5, 0, [29, 163, 72, 29], .23), # (5, 1, [12, 100, 30, 40], .62), # (6, 0, [43, 48, 74, 38], .45), # (6, 0, [17, 155, 29, 35], .84), # (6, 0, [95, 110, 25, 42], .43), # (7, 0, [16, 20, 101, 88], .48), # (7, 0, [33, 116, 37, 49], .95), # ] # detections = [BBox( # image_id=d[0], # category_id=d[1], # bbox=d[2], # score=d[3], # format=BBox.LTWH, # ) for d in detections] # # ground_truths = [ # (1, 0, [25, 16, 38, 56]), # (1, 0, [129, 123, 41, 62]), # (1, 1, [1, 1, 30, 32]), # (2, 0, [123, 11, 43, 55]), # (2, 0, [38, 132, 59, 45]), # (3, 0, [16, 14, 35, 48]), # (3, 0, [123, 30, 49, 44]), # (3, 0, [99, 139, 47, 47]), # (4, 0, [53, 42, 40, 52]), # (4, 0, [154, 43, 31, 34]), # (5, 0, [59, 31, 44, 51]), # (5, 0, [48, 128, 34, 52]), # (5, 1, [39, 80, 34, 39]), # (6, 0, [36, 89, 52, 76]), # (6, 0, [62, 58, 44, 67]), # (7, 0, [28, 31, 55, 63]), # (7, 0, [58, 67, 50, 58]), # ] # ground_truths = [BBox( # image_id=d[0], # category_id=d[1], # bbox=d[2], # score=1.0, # format=BBox.LTWH, # ) for d in ground_truths] # # np.testing.assert_allclose( # mean_average_precision(detections, ground_truths, iou_threshold=0.295, use_07_metric=False), 0.3728433402346446) # np.testing.assert_allclose( # mean_average_precision(detections, ground_truths, iou_threshold=0.5, use_07_metric=True), 0.28787878787878785) # # image_gts = groupby(lambda x: x.image_id, ground_truths) # # image_dts = groupby(lambda x: x.image_id, detections) # # np.testing.assert_allclose( # # np.mean([ # # mean_average_precision(image_dts[i], image_gts[i], iou_threshold=0.3, use_07_metric=True) # # for i in image_gts.keys() # # ]), 0.2456867)
[ "sbl1996@126.com" ]
sbl1996@126.com
2285d25919615c9dde0d3fdbdc4fd8d041aceca0
ec8385a6c121fc23e7f8d6c8e25abda0871df7af
/antispoofing.bkp/mcnns/datasets/livdetiris17_nd.py
a4d26bf41e18447863f06b0d7f9375d82c3a640b
[]
no_license
allansp84/metafusion-multiview-learning
b9baf8802b851bb88a1055752098446a2735195f
e9261a31526fa58f9bec3f37a9cf967a127b40c7
refs/heads/master
2022-10-29T23:15:53.263990
2020-02-27T00:54:53
2020-02-27T00:54:53
243,396,177
1
0
null
null
null
null
UTF-8
Python
false
false
7,563
py
# -*- coding: utf-8 -*- import time import itertools from glob import glob from antispoofing.mcnns.datasets.dataset import Dataset from antispoofing.mcnns.utils import * class LivDetIris17_ND(Dataset): """ Interface for the LivDet Iris 2017 dataset whose evaluation protocol is already defined by the orginizers. This class uses three auxiliary .text files provided by the LivDetIris2017's organizers, in which is defined the sets for training, testing and the unknown test. """ def __init__(self, dataset_path, ground_truth_path='', permutation_path='', iris_location='', output_path='./working', file_types=('.png', '.bmp', '.jpg', '.tiff'), operation='crop', max_axis=320, ): super(LivDetIris17_ND, self).__init__(dataset_path, output_path, iris_location, file_types, operation, max_axis) self.LIV_DET_TRAIN = os.path.join(PROJECT_PATH, '../extra/LivDet-Iris-2017_splits/livdet-train.txt') self.LIV_DET_TEST = os.path.join(PROJECT_PATH, '../extra/LivDet-Iris-2017_splits/livdet-test.txt') self.LIV_DET_UNKNOWN_TEST = os.path.join(PROJECT_PATH, '../extra/LivDet-Iris-2017_splits/livdet-unknown_test.txt') self.sets = {} self.ground_truth_path = ground_truth_path self.permutation_path = permutation_path self.verbose = True def build_meta(self, inpath, filetypes): img_idx = 0 all_fnames = [] all_labels = [] all_idxs = [] train_idxs = [] test_idxs = [] unknown_test_idxs = [] hash_img_id = {} liv_det_train_data, liv_det_train_hash = read_csv_file(self.LIV_DET_TRAIN, sequenceid_col=0, delimiter=' ', remove_header=False) liv_det_test_data, liv_det_test_hash = read_csv_file(self.LIV_DET_TEST, sequenceid_col=0, delimiter=' ', remove_header=False) liv_det_unknown_test_data, liv_det_unknown_test_hash = read_csv_file(self.LIV_DET_UNKNOWN_TEST, sequenceid_col=0, delimiter=' ', remove_header=False) folders = [self.list_dirs(inpath, filetypes)] folders = sorted(list(itertools.chain.from_iterable(folders))) for i, folder in enumerate(folders): progressbar('-- folders', i, len(folders), new_line=True) fnames = [glob(os.path.join(inpath, folder, '*' + filetype)) for filetype in filetypes] fnames = sorted(list(itertools.chain.from_iterable(fnames))) for j, fname in enumerate(fnames): rel_path = os.path.relpath(fname, inpath) img_id, ext = os.path.splitext(os.path.basename(rel_path)) if img_id in liv_det_train_hash: if not (img_id in hash_img_id): hash_img_id[img_id] = img_idx train_idxs += [img_idx] all_labels += [int(liv_det_train_data[liv_det_train_hash[img_id]][1])] all_fnames += [fname] all_idxs += [img_idx] img_idx += 1 elif img_id in liv_det_test_hash: if not (img_id in hash_img_id): hash_img_id[img_id] = img_idx test_idxs += [img_idx] all_labels += [int(liv_det_test_data[liv_det_test_hash[img_id]][1])] all_fnames += [fname] all_idxs += [img_idx] img_idx += 1 elif img_id in liv_det_unknown_test_hash: if not (img_id in hash_img_id): hash_img_id[img_id] = img_idx unknown_test_idxs += [img_idx] all_labels += [int(liv_det_unknown_test_data[liv_det_unknown_test_hash[img_id]][1])] all_fnames += [fname] all_idxs += [img_idx] img_idx += 1 else: pass all_fnames = np.array(all_fnames) all_labels = np.array(all_labels) all_idxs = np.array(all_idxs) train_idxs = np.array(train_idxs) test_idxs = np.array(test_idxs) unknown_test_idxs = np.array(unknown_test_idxs) # -- check if the training and testing sets are disjoint. try: assert not np.intersect1d(all_fnames[train_idxs], all_fnames[test_idxs]).size assert not np.intersect1d(all_fnames[train_idxs], all_fnames[unknown_test_idxs]).size except AssertionError: raise Exception('The training and testing sets are mixed') all_pos_idxs = np.where(all_labels[all_idxs] == self.POS_LABEL)[0] all_neg_idxs = np.where(all_labels[all_idxs] == self.NEG_LABEL)[0] r_dict = {'all_fnames': all_fnames, 'all_labels': all_labels, 'all_idxs': all_idxs, 'all_pos_idxs': all_pos_idxs, 'all_neg_idxs': all_neg_idxs, 'train_idxs': train_idxs, 'test_idxs': {'test': test_idxs, 'unknown_test': unknown_test_idxs, 'overall_test': np.concatenate((test_idxs, unknown_test_idxs)), }, 'hash_img_id': hash_img_id, } if self.verbose: self.info(r_dict) return r_dict def protocol_eval(self, fold=0, n_fold=5, test_size=0.5, output_path=''): """ This method implement validation evaluation protocol for this dataset. Args: fold (int): This parameter is not used since this dataset already has the predefined subsets. n_fold (int): This parameter is not used since this dataset already has the predefined subsets. test_size (float): This parameter is not used since this dataset already has the predefined subsets. Returns: dict: A dictionary containing the training and testing sets. """ # -- loading the training data and its labels all_fnames = self.meta_info['all_fnames'] all_labels = self.meta_info['all_labels'] train_idxs = self.meta_info['train_idxs'] test_idxs = self.meta_info['test_idxs'] all_data = self.get_imgs(all_fnames, sequenceid_col=3) # # -- create a mosaic for the positive and negative images. # print('-- all_fnames', all_fnames) # all_pos_idxs = np.where(all_labels[test_idxs['unknown_test']] == 1)[0] # all_neg_idxs = np.where(all_labels[test_idxs['unknown_test']] == 0)[0] # create_mosaic(all_data[all_pos_idxs], n_col=10, output_fname=os.path.join(self.output_path, 'mosaic-unknown_test-pos.{}.jpeg'.format(time.time()))) # create_mosaic(all_data[all_neg_idxs], n_col=10, output_fname=os.path.join(self.output_path, 'mosaic-unknown_test-neg.{}.jpeg'.format(time.time()))) train_set = {'data': all_data[train_idxs], 'labels': all_labels[train_idxs], 'idxs': train_idxs} test_set = {} for test_id in test_idxs: if test_idxs[test_id].size: test_set[test_id] = {'data': all_data[test_idxs[test_id]], 'labels': all_labels[test_idxs[test_id]], 'idxs': test_idxs[test_id], } # self.sets = {'train_set': train_set, 'test_set': test_set} return {'train_set': train_set, 'test_set': test_set}
[ "allan.pinto@dmz.org.br" ]
allan.pinto@dmz.org.br
cbed7ed09e3a19aa08a50c98d867fe71202162b8
b00d26d47e90e0f7558e44d40d3fca075d65fb6f
/ignore_tests/java.py
0c83bf926a468c34f1ea5323f3578900cfb8c4ed
[]
no_license
Dhanavarsha/FlakyTestDetector
cbcce3ebc444e256c6570135b22fa84684c24dcc
d8e71c04c61308126f00cedddf379412ea8f3325
refs/heads/master
2020-12-02T02:43:28.379997
2019-12-30T06:50:05
2019-12-30T06:50:05
230,861,779
0
0
null
null
null
null
UTF-8
Python
false
false
2,035
py
import subprocess import sys import os import pretty_print def ignore_test(fully_qualified_test_name, working_dir): (package_name, class_name, test_name) = fully_qualified_test_name.rsplit('.', 2) files = _find_files(class_name, working_dir) inside_package_lambda = _create_inside_package_function(package_name) test_class_files = list(filter(inside_package_lambda, files)) assert len(test_class_files) == 1, "Expecting only 1 test-class for class-name: %r" % class_name test_class_file = test_class_files[0] with open(test_class_file) as f: lines = f.readlines() for index in range(len(lines)): if "public void {}()".format(test_name) in lines[index]: test_function_line_number = index break assert test_function_line_number != -1, "Test name not present in the file" pretty_print.success("Ignoring {} in file: {}".format(test_name, test_class_file)) lines.insert(test_function_line_number, _ignore_annotation_string(lines[test_function_line_number])) with open(test_class_file, "w") as f: f.writelines(lines) def _find_files(classname, working_dir): output = subprocess.check_output(["git", "ls-files"], cwd=working_dir).decode(sys.stdout.encoding).strip() files = output.split('\n') filepaths = list(map(lambda relative_path: os.path.join(working_dir, relative_path), files)) filtered = list(filter(lambda filepath: classname in filepath, filepaths)) return filtered def _create_inside_package_function(package_name): def inside_package_filter(filepath): with open(filepath) as f: first_line = f.readline() return "package {};".format(package_name) in first_line return inside_package_filter def _ignore_annotation_string(test_function_string): test_function_indentation = len(test_function_string) - len(test_function_string.lstrip()) string = "@Ignore\n" for i in range(test_function_indentation): string = " " + string return string
[ "dhan.varsha03@gmail.com" ]
dhan.varsha03@gmail.com
2815d21b998558f72516eb1b79224075af1ab4f3
95e0ccbb333fc08f250b67fef5e531bdd418033b
/shop/urls.py
3930bcf1a9092175b63b1f5a1a13f0b874275c18
[]
no_license
ArtemYaremenko/ecommerce-project
05974c005fa8ef1c193e514966efb951e570ffd9
540fc20f2f8c7f6fd2423cca671384775b43ba78
refs/heads/main
2023-02-01T19:16:29.531867
2020-12-16T17:41:51
2020-12-16T17:41:51
312,169,831
0
0
null
null
null
null
UTF-8
Python
false
false
802
py
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('category/<slug:category_slug>', views.home, name='products_by_category'), path('category/<slug:category_slug>/<slug:product_slug>', views.product, name='product_detail'), path('cart/', views.cart_detail, name='cart_detail'), path('cart/add/<int:product_id>/', views.add_cart, name='add_cart'), path('cart/remove/<int:product_id>/', views.cart_remove, name='cart_remove'), path('cart/remove_product/<int:product_id>/', views.cart_remove_product, name='cart_remove_product'), path('account/create/', views.sign_up_view, name='signup'), path('account/login/', views.login_view, name='login'), path('account/signout/', views.sign_out_view, name='signout'), ]
[ "Artem.Yaremenko.1992@gmail.com" ]
Artem.Yaremenko.1992@gmail.com
51e0ece99dfa331468ea3a90496479c28e5b8739
db54268ca3772d9b9563aa124814d65e80879e59
/closerEnclosingFunction.py
6380a0b6dd074b814e3c621d8136a39085642340
[]
no_license
manjit1217/LearnPython
93241879953f655d96944b1466cdc429a0836c0c
3f5dbd89d07f882f3aaeae02ee3e240956419a19
refs/heads/master
2020-09-04T23:27:30.265802
2020-07-19T18:04:05
2020-07-19T18:04:05
219,922,879
0
0
null
null
null
null
UTF-8
Python
false
false
136
py
def print_check(msg): print('inside pri') def inside_print(): print(msg) return inside_print print_check('milan')
[ "manjit.1217@gmail.com" ]
manjit.1217@gmail.com
16cafd21c3f3ac353c3eec679a4cd317c0ae4086
e2e52d0726feb0229128aeee4831098bd28524fd
/vm_template.py
9663a841ec802fde7e160b7f79f232e8efd3a7c2
[]
no_license
david-joy-ds/gcp-deployment-manager
84c9a8dae0eb576785652de7e53bea9acdb24718
9a6b6e08c16d5902b1e8abe44f64007afdb99b59
refs/heads/master
2021-05-27T01:24:13.070136
2020-04-08T20:59:06
2020-04-08T20:59:06
254,197,432
0
0
null
null
null
null
UTF-8
Python
false
false
1,111
py
COMPUTE_URL_BASE = 'https://www.googleapis.com/compute/v1/' def GenerateConfig(context): """Creates the first virtual machine.""" resources = [{ 'name': 'the-first-vm', 'type': 'compute.v1.instance', 'properties': { 'zone': 'us-central1-f', 'machineType': ''.join([COMPUTE_URL_BASE, 'projects/',context.env['project'], '/zones/us-central1-f/', 'machineTypes/f1-micro']), 'disks': [{ 'deviceName': 'boot', 'type': 'PERSISTENT', 'boot': True, 'autoDelete': True, 'initializeParams': { 'sourceImage': ''.join([COMPUTE_URL_BASE, 'projects/','debian-cloud/global/','images/family/debian-9']) } }], 'networkInterfaces': [{ 'network': '$(ref.my-network.selfLink)', 'accessConfigs': [{ 'name': 'External NAT', 'type': 'ONE_TO_ONE_NAT' }] }] } }] return {'resources': resources}
[ "=" ]
=
513a146350672cbaaa7c1989c82b436aae162897
18e08b4a377bb2ac7bafaef08dba9579ea0faa2d
/virtual/bin/django-admin
a2f5ba157f3b31ec3a5d2b0dd73745627ec67fe1
[]
no_license
mwaa123/SIEZE
6e01dc41b7cd1b8cec0bd0be7a6e839e502d915e
bf773bff53ca504a3f5dea582e9e64db23b1eb9a
refs/heads/master
2023-07-26T14:51:39.293726
2020-06-13T06:32:56
2020-06-13T06:32:56
267,003,001
0
0
null
2021-09-08T02:09:46
2020-05-26T09:40:24
Python
UTF-8
Python
false
false
289
#!/home/ruth/MY-PORTFOLIO/virtual/bin/python # -*- coding: utf-8 -*- import re import sys from django.core.management import execute_from_command_line if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(execute_from_command_line())
[ "ruthwanjiramugo@gmail.com" ]
ruthwanjiramugo@gmail.com
444e465edd64f764c5552229c70c68ce001ef510
5c33efa07e22093fc9364afaa558bf7b7ba0a130
/PyWagg/repl/repl.py
928097a6aa4fd79aed81d0188394e3b6ba736b56
[ "MIT" ]
permissive
HarryMills/Wagg
72933d5819e7015b5f3c0a87c02bd866521a2db8
45c69807122f3c44255b94d1955c19eac1309d68
refs/heads/master
2022-11-06T04:43:35.154495
2020-06-22T21:05:35
2020-06-22T21:05:35
262,829,869
1
0
null
2020-06-05T16:06:41
2020-05-10T16:34:26
Go
UTF-8
Python
false
false
278
py
from PyWagg import lexer from PyWagg import tokens prompt = ">> " def start(): while True: line = input(prompt) l = lexer.new(line) tok = l.next_token() while tok.Type != tokens.EOF: print(tok) tok = l.next_token()
[ "harry.e.mills@gmail.com" ]
harry.e.mills@gmail.com
a676310121eab17504f78d907be582d910340bb7
7ce536b3ad2194cfe17f79060165901472e494a8
/Loops.py
10ab070ff888d6308a0ce0ec585fa96481b6065b
[]
no_license
Andyiscool/python-programs-school
f3afa4c3e0b1218ae7cd932f019194aad744f0f3
bba58798505b3f1b9c418413c6878cfcc3c6cb1d
refs/heads/master
2020-07-31T23:00:00.928334
2017-07-10T21:07:39
2017-07-10T21:07:39
73,588,515
0
0
null
null
null
null
UTF-8
Python
false
false
176
py
print(list(range(10, 20))) for x in range(0, 5): print('hello %s' % x) animals = ["cats", "dogs", "birds"] for animal in animals: print('animals %s' % animal)
[ "andy.xiao@live.com" ]
andy.xiao@live.com
09baa61abb1f1710c9c5e170db65235edc2f3e43
2bdf51a73253ce0b86ae9886531ab5ed069f28cb
/solutions/1470. Shuffle the Array.py
c8c08658390b618c5ae319d46f2004815f271203
[]
no_license
ShrashtiSinghal/Python-Practice
b544ae1bbcd58a25a444740090745d91f424a6c6
249ba97af8ea6b71a1cb27029ae68bad1dfd44cd
refs/heads/master
2022-10-20T14:24:27.426982
2020-07-07T08:28:35
2020-07-07T08:28:35
276,944,931
0
0
null
null
null
null
UTF-8
Python
false
false
258
py
class Solution: def shuffle(self, nums: List[int], n: int) -> List[int]: length= len(nums)//2 newList=[] for i in range(length): newList.append(nums[i]) newList.append(nums[length+i]) return newList
[ "40803338+ShrashtiSinghal@users.noreply.github.com" ]
40803338+ShrashtiSinghal@users.noreply.github.com
92e81439a7311dca5f00b69c4a20466eb0be0189
d3814a5e40b27d9cbf6cfefda960b6acfff69a35
/.local/lib/python3.8/site-packages/astroid/__pkginfo__.py
a04b42bae9f75cf5b293a89c3b39314bb9582fd1
[]
no_license
The-Coder-Kishor/Sheldon-Cooper
31311161d5a7d7d11df6498233ee3c0ada240f19
1c80ba26ae79d538e5a04b4a26a9ecc8da0fd0f7
refs/heads/main
2023-06-27T21:27:14.493198
2021-08-07T06:58:33
2021-08-07T06:58:33
393,595,359
1
0
null
null
null
null
UTF-8
Python
false
false
1,532
py
# Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr> # Copyright (c) 2014-2020 Claudiu Popa <pcmanticore@gmail.com> # Copyright (c) 2014 Google, Inc. # Copyright (c) 2015-2017 Ceridwen <ceridwenv@gmail.com> # Copyright (c) 2015 Florian Bruhin <me@the-compiler.org> # Copyright (c) 2015 Radosław Ganczarek <radoslaw@ganczarek.in> # Copyright (c) 2016 Moises Lopez <moylop260@vauxoo.com> # Copyright (c) 2017 Hugo <hugovk@users.noreply.github.com> # Copyright (c) 2017 Łukasz Rogalski <rogalski.91@gmail.com> # Copyright (c) 2017 Calen Pennington <cale@edx.org> # Copyright (c) 2018 Ville Skyttä <ville.skytta@iki.fi> # Copyright (c) 2018 Ashley Whetter <ashley@awhetter.co.uk> # Copyright (c) 2018 Bryce Guinta <bryce.paul.guinta@gmail.com> # Copyright (c) 2019 Uilian Ries <uilianries@gmail.com> # Copyright (c) 2019 Thomas Hisch <t.hisch@gmail.com> # Copyright (c) 2020-2021 hippo91 <guillaume.peillex@gmail.com> # Copyright (c) 2020 David Gilman <davidgilman1@gmail.com> # Copyright (c) 2020 Konrad Weihmann <kweihmann@outlook.com> # Copyright (c) 2020 Felix Mölder <felix.moelder@uni-due.de> # Copyright (c) 2020 Michael <michael-k@users.noreply.github.com> # Copyright (c) 2021 Pierre Sassoulas <pierre.sassoulas@gmail.com> # Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com> # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/master/LICENSE __version__ = "2.6.2" version = __version__
[ "talakishor47@gmail.com" ]
talakishor47@gmail.com
a421f062e0a01b4b7f3d20330a8309f8de453f8c
ba5b12e28e02ec4dfa5a512935a88dbdbad41699
/app/main/application/commands/beerupdate.py
59485d412120b03d02ff578b29df08b44598fa60
[]
no_license
tiagovbarreto/ddd_python_beer_api
eb345d2c7014a91bb383491631874788f7a994d7
669b8bf0177f0320ddc025397e06a259ac1f9405
refs/heads/main
2023-03-05T14:17:16.650590
2021-02-20T19:02:45
2021-02-20T19:02:45
334,296,724
0
1
null
2021-02-08T00:22:42
2021-01-30T00:42:49
Python
UTF-8
Python
false
false
122
py
from app.maindoapp.mainentities.beer import Beer class UpdateBeerCommand(): def execute(self) -> Beer: pass
[ "tiagovalentim@gmail.com" ]
tiagovalentim@gmail.com
51b56e337abd190a5d072bb056905ae2bb4487f9
529a5686f69e38527809f86c055ccd70095065cd
/train_pag.py
d140290c5e2c9308c849e3d6cdb1a03f2201bc11
[ "MIT" ]
permissive
AvashnaGovender/Tacotron
925ad68050bde7a5b3b0f6686295ff6ea0cb241d
b4d710ffb0f9e7ef0096d1993b8a24cae4f0d557
refs/heads/master
2023-01-14T01:23:04.539018
2020-11-27T08:55:53
2020-11-27T08:55:53
277,764,431
1
1
null
null
null
null
UTF-8
Python
false
false
10,531
py
import torch from torch import optim import torch.nn.functional as F from utils import hparams as hp from utils.display import * from utils.dataset_att_guide import get_tts_datasets from utils.text.symbols import symbols from utils.paths import Paths from models.tacotron import Tacotron import argparse from utils import data_parallel_workaround import os from pathlib import Path import time import numpy as np import sys from utils.checkpoints import save_checkpoint, restore_checkpoint def np_now(x: torch.Tensor): return x.detach().cpu().numpy() def pad2d_nonzero(x, max_x, max_y): #print(x.shape, max_x, max_y) return np.pad(x, ((0, max_x - x.shape[0]), (0, max_y - x.shape[-1])), mode='constant', constant_values=(-1,)) def pad2d_zero(x, max_x, max_y): #print(x.shape, max_x, max_y) return np.pad(x, ((0, max_x - x.shape[0]), (0, max_y - x.shape[-1])), mode='constant', constant_values=(0,)) def main(): # Parse Arguments parser = argparse.ArgumentParser(description='Train Tacotron TTS') parser.add_argument('--force_train', '-f', action='store_true', help='Forces the model to train past total steps') parser.add_argument('--force_gta', '-g', action='store_true', help='Force the model to create GTA features') parser.add_argument('--force_cpu', '-c', action='store_true', help='Forces CPU-only training, even when in CUDA capable environment') parser.add_argument('--hp_file', metavar='FILE', default='hparams.py', help='The file to use for the hyperparameters') args = parser.parse_args() hp.configure(args.hp_file) # Load hparams from file paths = Paths(hp.data_path, hp.voc_model_id, hp.tts_model_id) force_train = args.force_train force_gta = args.force_gta if not args.force_cpu and torch.cuda.is_available(): device = torch.device('cuda') for session in hp.tts_schedule: _, _, _, batch_size = session if batch_size % torch.cuda.device_count() != 0: raise ValueError('`batch_size` must be evenly divisible by n_gpus!') else: device = torch.device('cpu') print('Using device:', device) # Instantiate Tacotron Model print('\nInitialising Tacotron Model...\n') model = Tacotron(embed_dims=hp.tts_embed_dims, num_chars=len(symbols), encoder_dims=hp.tts_encoder_dims, decoder_dims=hp.tts_decoder_dims, n_mels=hp.num_mels, fft_bins=hp.num_mels, postnet_dims=hp.tts_postnet_dims, encoder_K=hp.tts_encoder_K, lstm_dims=hp.tts_lstm_dims, postnet_K=hp.tts_postnet_K, num_highways=hp.tts_num_highways, dropout=hp.tts_dropout, stop_threshold=hp.tts_stop_threshold).to(device) optimizer = optim.Adam(model.parameters()) restore_checkpoint('tts', paths, model, optimizer, create_if_missing=True) if not force_gta: for i, session in enumerate(hp.tts_schedule): current_step = model.get_step() r, lr, max_step, batch_size = session training_steps = max_step - current_step # Do we need to change to the next session? if current_step >= max_step: # Are there no further sessions than the current one? if i == len(hp.tts_schedule)-1: # There are no more sessions. Check if we force training. if force_train: # Don't finish the loop - train forever training_steps = 999_999_999 else: # We have completed training. Breaking is same as continue break else: # There is a following session, go to it continue model.r = r simple_table([(f'Steps with r={r}', str(training_steps//1000) + 'k Steps'), ('Batch Size', batch_size), ('Learning Rate', lr), ('Outputs/Step (r)', model.r)]) train_set, attn_example, max_y, max_x = get_tts_datasets(paths.data, batch_size, r) #print(max_y, max_x) tts_train_loop(paths, model, optimizer, train_set, lr, training_steps, attn_example, max_y, max_x) print('Training Complete.') print('To continue training increase tts_total_steps in hparams.py or use --force_train\n') print('Creating Ground Truth Aligned Dataset...\n') train_set, attn_example,max_y, max_x = get_tts_datasets(paths.data, 8, model.r) create_gta_features(model, train_set, paths.gta) print('\n\nYou can now train WaveRNN on GTA features - use python train_wavernn.py --gta\n') def tts_train_loop(paths: Paths, model: Tacotron, optimizer, train_set, lr, train_steps, attn_example, max_y, max_x): device = next(model.parameters()).device # use same device as model parameters for g in optimizer.param_groups: g['lr'] = lr total_iters = len(train_set) epochs = train_steps // total_iters + 1 for e in range(1, epochs+1): start = time.time() running_loss = 0 # Perform 1 epoch for i, (x, m, ids, _, padded_att_guides) in enumerate(train_set, 1): x, m = x.to(device), m.to(device) # Parallelize model onto GPUS using workaround due to python bug if device.type == 'cuda' and torch.cuda.device_count() > 1: m1_hat, m2_hat, attention, r = data_parallel_workaround(model, x, m) else: m1_hat, m2_hat, attention, r = model(x, m) reduced_guides = [] att_guide_path = hp.attention_path for j,item_id in enumerate(ids): att = np.load(f'{att_guide_path}/{item_id}.npy') reduced = att[0::r] pred_attention = attention[j] n_frames = pred_attention.shape[0] n_phones = pred_attention.shape[-1] # pred_attention = torch.tensor(pred_attention) # reduced = torch.tensor(reduced) padded_guides = pad2d_nonzero(reduced, n_frames, n_phones) #padded_guides = torch.tensor(padded_guides) reduced_guides.append(padded_guides) reduced_guides = torch.tensor(reduced_guides) mask = torch.ne(reduced_guides, -1).type(torch.FloatTensor) mask = torch.tensor(mask) padded_guides = [pad2d_zero(x, n_frames, n_phones) for x in reduced_guides] padded_guides = torch.tensor(padded_guides) padded_guides = padded_guides.to(device) attention = attention.to(device) mask = mask.to(device) attention = attention*mask print("guide att shape",att.shape) print(att) print("reduced guide", padded_guides.shape) # print("attention size",n_frames, n_phones) print("mask",mask.shape) print(mask) print(padded_guides.shape, attention.shape, mask.shape) print(attention) print(padded_guides) multiply = torch.pow((attention - padded_guides),2) print(multiply) #multiply = torch.pow((pred_attention - padded_guides),2)* mask #print(multiply) attention_loss = torch.sum(multiply) print(attention_loss) mask_sum1 = torch.sum(mask) attention_loss /= mask_sum1 print(attention_loss) # batch_attention_losses.append(attention_loss) m1_loss = F.l1_loss(m1_hat, m) m2_loss = F.l1_loss(m2_hat, m) #average_att_loss = sum(batch_attention_losses)/len(batch_attention_losses) #print("attention loss", average_att_loss) #print("m losses", m1_loss, m2_loss) prev_loss = m1_loss + m2_loss print("prev loss", prev_loss) loss = m1_loss + m2_loss + attention_loss print("loss + att", loss) #exit() optimizer.zero_grad() loss.backward() if hp.tts_clip_grad_norm is not None: grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), hp.tts_clip_grad_norm) if np.isnan(grad_norm): print('grad_norm was NaN!') optimizer.step() running_loss += loss.item() avg_loss = running_loss / i speed = i / (time.time() - start) step = model.get_step() k = step // 1000 if step % hp.tts_checkpoint_every == 0: ckpt_name = f'taco_step{k}K' save_checkpoint('tts', paths, model, optimizer, name=ckpt_name, is_silent=True) if attn_example in ids: idx = ids.index(attn_example) save_attention(np_now(attention[idx][:, :160]), paths.tts_attention/f'{step}') save_spectrogram(np_now(m2_hat[idx]), paths.tts_mel_plot/f'{step}', 600) msg = f'| Epoch: {e}/{epochs} ({i}/{total_iters}) | Loss: {avg_loss:#.4} | {speed:#.2} steps/s | Step: {k}k | ' stream(msg) # Must save latest optimizer state to ensure that resuming training # doesn't produce artifacts save_checkpoint('tts', paths, model, optimizer, is_silent=True) model.log(paths.tts_log, msg) print(' ') def create_gta_features(model: Tacotron, train_set, save_path: Path): device = next(model.parameters()).device # use same device as model parameters iters = len(train_set) for i, (x, mels, ids, mel_lens) in enumerate(train_set, 1): x, mels = x.to(device), mels.to(device) with torch.no_grad(): _, gta, _ = model(x, mels) gta = gta.cpu().numpy() for j, item_id in enumerate(ids): mel = gta[j][:, :mel_lens[j]] mel = (mel + 4) / 8 np.save(save_path/f'{item_id}.npy', mel, allow_pickle=False) bar = progbar(i, iters) msg = f'{bar} {i}/{iters} Batches ' stream(msg) if __name__ == "__main__": main()
[ "38498073+AvashnaGovender@users.noreply.github.com" ]
38498073+AvashnaGovender@users.noreply.github.com
2b638ba945f09515730f26045b6e4c717a5b518a
cdb8e785dd441006dc6a2bcd2a2aa10ae3c2ef63
/bin/parsetab.py
5845559c6b3045218891019c67dd41eb3ae304df
[ "MIT" ]
permissive
log4leo/Shell4Win
8380d3713238e0b5e55bab390143ceed905078bc
eea5e7cb8c44fefaaff972df979d9210f67daf9b
refs/heads/master
2020-06-04T15:46:13.290470
2014-05-23T06:28:07
2014-05-23T06:28:07
17,128,178
17
6
null
2014-05-23T06:28:08
2014-02-24T07:09:42
Python
UTF-8
Python
false
false
1,708
py
# parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.2' _lr_method = 'LALR' _lr_signature = '\xce\x17\x7fg\x06\xa5\x06` M\xee\xb0\\7\x98\xa0' _lr_action_items = {'LREDIRECT':([1,3,7,10,11,12,13,],[5,-7,-8,-5,5,-6,5,]),'PIPE':([1,3,7,10,12,],[6,-7,-8,-5,-6,]),'COLON':([1,3,7,10,12,],[9,-7,-8,-5,-6,]),'RREDIRECT':([1,3,7,10,11,12,13,],[8,-7,-8,-5,8,-6,8,]),'COMMAND':([0,1,3,5,6,7,8,9,10,11,12,13,],[3,7,-7,10,3,-8,12,3,-5,7,-6,7,]),'$end':([1,2,3,4,7,10,11,12,13,],[-2,0,-7,-1,-8,-5,-3,-6,-4,]),} _lr_action = { } for _k, _v in _lr_action_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_action: _lr_action[_x] = { } _lr_action[_x][_k] = _y del _lr_action_items _lr_goto_items = {'term':([0,6,9,],[1,11,13,]),'expression':([0,],[4,]),'statement':([0,],[2,]),} _lr_goto = { } for _k, _v in _lr_goto_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_goto: _lr_goto[_x] = { } _lr_goto[_x][_k] = _y del _lr_goto_items _lr_productions = [ ("S' -> statement","S'",1,None,None,None), ('statement -> expression','statement',1,'p_statement','tools.pyc',90), ('statement -> term','statement',1,'p_statement','tools.pyc',91), ('expression -> term PIPE term','expression',3,'p_expression_pipe','tools.pyc',98), ('expression -> term COLON term','expression',3,'p_expression_colon','tools.pyc',107), ('term -> term LREDIRECT COMMAND','term',3,'p_expression_lredirect','tools.pyc',115), ('term -> term RREDIRECT COMMAND','term',3,'p_expression_rredirect','tools.pyc',119), ('term -> COMMAND','term',1,'p_expression','tools.pyc',126), ('term -> term COMMAND','term',2,'p_expression','tools.pyc',127), ]
[ "yy_happy1990@163.com" ]
yy_happy1990@163.com
f27b4bff13c989ea627db6f48729b4d7446ed86f
c2f9b8127306f2a9e26184d52bcb519318af6022
/Lib/Api/yly_print.py
58ce5fb380f0b279d5450f9e2321406c32e07d53
[]
no_license
Qzm6826/yly-python-sdk
5f1ed5f0a792842554a23ac91cc9383de3d13749
b97d44211eb04188146423f2e2d9803f0c24843c
refs/heads/master
2023-06-26T03:17:36.095266
2023-06-13T09:49:30
2023-06-13T09:49:30
167,102,743
11
1
null
null
null
null
UTF-8
Python
false
false
887
py
#!/usr/bin/python # -*- coding: utf-8 -*- class YlyPrint: __client = None def __init__(self, client): self.__client = client def index(self, machine_code, content, origin_id, idempotence= 0): """ 打印接口 :param machine_code: 机器码 :param content: 打印内容 :param origin_id: 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母 :param idempotence 默认1,传入本参数,会根据origin_id进行幂等处理,2小时内相同origin_id会返回上一次的结果 :return: """ params = { 'machine_code': machine_code, 'content': content, 'origin_id': origin_id } if idempotence == 1: params['idempotence'] = idempotence return self.__client.call('print/index', params)
[ "1139038165@qq.com" ]
1139038165@qq.com
32c4a398d4cc157611fb6827fce531ecbb82f431
0e283c8d8c7d48321b7d1b649fc13e33ca8b39d2
/OnlineCode.py
a23a336963062c23380fdfad3d185ffd16f04e38
[]
no_license
GeraldShin/PythonSandbox
79f4d5237859f4ab62469d2d6f232ce1c0f63f22
ed7820ee7403ce02989545334c225c420eb00ea3
refs/heads/master
2020-09-29T04:56:45.133657
2020-06-02T23:10:19
2020-06-02T23:10:19
226,957,058
0
0
null
null
null
null
UTF-8
Python
false
false
1,851
py
#This will be snippets of useful code you find online that you can copy+paste when needed. #Emoji Package #I don't know when this will ever be helpful, but there is an Emoji package in Python. $ pip install emoji from emoji import emojize print(emojize(":thumbs_up:")) #thumbs up emoji, check notes for more. #List comprehensions #You could probably get better at these... here is an easy example for reference numbers = [1,2,3,4,5,6,7] evens = [x for x in numbers if x % 2 is 0] odds = [y for y in numbers if y not in evens] cities = ['London', 'Dublin', 'Oslo'] def visit(city): print("Welcome to "+city) for city in cities: visit(city) def split_lines(s): #split a string into pieces using a separator return s.split('\n') split_lines('50\n python\n snippets') language = "python" #reverse the order of the letters in a word reversed_language = language[::-1] print(reversed_language) def union(a,b): #find elements that exist in both lists return list(set(a + b)) union([1, 2, 3, 4, 5], [6, 2, 8, 1, 4]) def unique(list): #finds if all elements in a list are unique if len(list)==len(set(list)): print("All elements are unique") else: print("List has duplicates") unique([1,2,3,4,5]) # All elements are unique from collections import Counter #counts freq of appearance of elements list = [1, 2, 3, 2, 4, 3, 2, 3] count = Counter(list) print(count) # {2: 3, 3: 3, 1: 1, 4: 1} def most_frequent(list): #piggy-backing, finds most freq appearance of elements return max(set(list), key = list.count) numbers = [1, 2, 3, 2, 4, 3, 1, 3] most_frequent(numbers) # 3 def multiply(n): #mapping applies the function in the parens to the data element in the parens return n * n list = (1, 2, 3) result = map(multiply, list) print(list(result)) # {1, 4, 9}
[ "noreply@github.com" ]
GeraldShin.noreply@github.com
8c626ff74d7a26364b16619851113b3b94c81cc4
eb261f7957c86dcc35a0418010ca56a275758da4
/about_control_statements.py
bb1a3f4b6ff6980b1587bcac156937851842b9b7
[]
no_license
chetstar/koans2
28ed5bd4e667bb8ce6d9a1a931f821ed387a923e
c958e1c49a33231ddbea01b5aa4db6790649fb0c
refs/heads/master
2016-09-06T07:52:36.305803
2014-06-02T04:35:05
2014-06-02T04:35:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,008
py
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutControlStatements(Koan): def test_if_then_else_statements(self): if True: result = 'true value' else: result = 'false value' self.assertEqual('true value', result) def test_if_then_statements(self): result = 'default value' if True: result = 'true value' self.assertEqual('true value', result) def test_while_statement(self): i = 1 result = 1 while i <= 10: result = result * i i += 1 self.assertEqual(3628800, result) def test_break_statement(self): i = 1 result = 1 while True: if i > 10: break result = result * i i += 1 self.assertEqual(3628800, result) def test_continue_statement(self): i = 0 result = [] while i < 10: i += 1 if (i % 2) == 0: continue result.append(i) self.assertEqual([1,3,5,7,9], result) def test_for_statement(self): phrase = ["fish", "and", "chips"] result = [] for item in phrase: result.append(item.upper()) self.assertEqual(["FISH","AND","CHIPS"], result) def test_for_statement_with_tuples(self): round_table = [ ("Lancelot", "Blue"), ("Galahad", "I don't know!"), ("Robin", "Blue! I mean Green!"), ("Arthur", "Is that an African Swallow or Amazonian Swallow?") ] result = [] for knight, answer in round_table: result.append("Contestant: '" + knight + \ "' Answer: '" + answer + "'") text = "Contestant: 'Robin' Answer: 'Blue! I mean Green!'" self.assertMatch(text, result[2]) self.assertNoMatch(text, result[0]) self.assertNoMatch(text, result[1]) self.assertNoMatch(text, result[3])
[ "cmeinzer@acbhcs.org" ]
cmeinzer@acbhcs.org
7d99fead546a41f71ac5616dbc0b8582950b674a
01c07bcb957c430cd728204e2f5a00c30dc26a22
/opensfm/test/test_commands.py
00623fd1ab9d2039982908ac285672fd13274dda
[ "BSD-2-Clause" ]
permissive
chetanskumar1991/OpenSfM
203542d715766215b0c52432da4f6115555a0da5
e42aec5166c80359064b7203a35bae48d904bc91
refs/heads/master
2021-09-13T03:18:07.077804
2017-08-25T10:09:13
2017-08-25T10:09:13
288,192,113
0
0
BSD-2-Clause
2020-08-17T13:47:25
2020-08-17T13:47:25
null
UTF-8
Python
false
false
816
py
import argparse from opensfm import commands import data_generation def run_command(command, args): parser = argparse.ArgumentParser() command.add_arguments(parser) parsed_args = parser.parse_args(args) command.run(parsed_args) def test_run_all(tmpdir): data = data_generation.create_berlin_test_folder(tmpdir) run_all_commands = [ commands.extract_metadata, commands.detect_features, commands.match_features, commands.create_tracks, commands.reconstruct, commands.mesh, ] for module in run_all_commands: command = module.Command() run_command(command, [data.data_path]) reconstruction = data.load_reconstruction() assert len(reconstruction[0].shots) == 3 assert len(reconstruction[0].points) > 1000
[ "pau.gargallo@gmail.com" ]
pau.gargallo@gmail.com
b8c21d921858fe9e9356faed6939ebdb48f5d034
1faf5f8200c1be47db86bc1f3203eaf6066ec3dc
/comment/migrations/0001_initial.py
115be9fc85c327782839d4fd5b04f3c878903411
[]
no_license
aaaqqewrt/Blog
1ce7735b2f25239fb0ab310e72c5fdb0247a6211
ac3952be109e472127840bdc2e001f17a789c2d2
refs/heads/master
2023-01-01T11:37:35.591479
2020-10-20T11:33:17
2020-10-20T11:33:17
305,686,911
0
0
null
null
null
null
UTF-8
Python
false
false
1,053
py
# Generated by Django 3.1.2 on 2020-10-13 10:30 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contenttypes', '0002_remove_content_type_name'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('object_id', models.PositiveIntegerField()), ('text', models.TextField()), ('comment_time', models.DateTimeField(auto_now_add=True)), ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='contenttypes.contenttype')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
[ "1727760897@qq.com" ]
1727760897@qq.com
a4fa03ebd028ab7225390f29af91f34bb05f4902
cb4e05f6c64e40656e4bd31640dcd6370d2e42e6
/extension/tunabot_utils.py
fae6453585d85b3528d7ec204384d30f0019a821
[ "MIT" ]
permissive
InfiniteTeam/TunaBot-v2
004e43729f965cddbf2e3199bc1b63f3ea3186f2
30a85078af72778c699532573f5b5584d3d1201b
refs/heads/master
2020-12-30T02:48:38.684031
2020-02-10T07:58:14
2020-02-10T07:58:14
238,836,953
0
1
MIT
2020-02-08T08:37:41
2020-02-07T03:37:19
Python
UTF-8
Python
false
false
362
py
def aliases(prefix, aliases): names = aliases for x in names: names[names.index(x)] = prefix+names[names.index(x)] return tuple(names) def arguments(message): args = message.split(" ")[1:] return args def color(): color = {'main':0x5b50fa, 'yellow':0xffbb00, 'red':0xf04747, 'green':0x43b581, 'orange':0xf26522} return color
[ "54466872+ArpaAP@users.noreply.github.com" ]
54466872+ArpaAP@users.noreply.github.com
03371bf145264fff2ce4490158383c3527c9e850
dd00dbf635745ab2c95563be5651443dd03db0ea
/tqsdk/algorithm/time_table_generater.py
c08f450ec12bfdd830d0b07eb1ff65d13c73a48b
[ "Apache-2.0", "Python-2.0" ]
permissive
ker945/tqsdk-python
1fbd9be780763cafaaa52bc18433537bace417eb
4548361688aa3104933f1f5f3494fbd5c09a6848
refs/heads/master
2023-01-10T21:40:37.662440
2022-10-20T07:47:38
2022-10-21T05:14:19
251,191,269
0
0
Apache-2.0
2020-03-30T03:26:18
2020-03-30T03:26:18
null
UTF-8
Python
false
false
15,935
py
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'mayanqiong' from datetime import datetime, time, timedelta from typing import Optional, Union import numpy as np import pandas as pd from pandas import DataFrame from tqsdk.api import TqApi from tqsdk import utils from tqsdk.datetime import _get_trading_timestamp, _get_trade_timestamp, _get_trading_day_from_timestamp, \ _datetime_to_timestamp_nano from tqsdk.rangeset import _rangeset_slice, _rangeset_head from tqsdk.tradeable import TqAccount, TqKq, TqSim def twap_table(api: TqApi, symbol: str, target_pos: int, duration: int, min_volume_each_step: int, max_volume_each_step: int, account: Optional[Union[TqAccount, TqKq, TqSim]] = None): """ 返回基于 twap 策略的计划任务时间表。下单需要配合 TargetPosScheduler 使用。 Args: api (TqApi): TqApi实例,该task依托于指定api下单/撤单 symbol (str): 拟下单的合约 symbol, 格式为 交易所代码.合约代码, 例如 "SHFE.cu1801" target_pos (int): 目标持仓手数 duration (int): 算法执行的时长,以秒为单位,时长可以跨非交易时间段,但是不可以跨交易日 * 设置为 60*10, 可以是 10:10~10:15 + 10:30~10:35 min_volume_each_step (int): 调整持仓手数最小值,每步调整的持仓手数默认在最小和最大值中产生 max_volume_each_step (int): 调整持仓手数最大值,每步调整的持仓手数默认在最小和最大值中产生 account (TqAccount/TqKq/TqSim): [可选]指定发送下单指令的账户实例, 多账户模式下,该参数必须指定 Returns: pandas.DataFrame: 本函数返回一个 pandas.DataFrame 实例. 表示一份计划任务时间表。每一行表示一项目标持仓任务,包含以下列: + interval: 当前这项任务的持续时间长度,单位为秒 + target_pos: 当前这项任务的目标持仓 + price: 当前这项任务的下单价格模式,支持 PASSIVE(排队价),ACTIVE(对价),None(不下单,表示暂停一段时间) Example1:: from tqsdk import TqApi, TargetPosScheduler from tqsdk.algorithm import twap_table api = TqApi(auth="信易账户,用户密码") quote = api.get_quote("CZCE.MA109") # 设置twap任务参数 time_table = twap_table(api, "CZCE.MA109", -100, 600, 1, 5) # 目标持仓 -100 手,600s 内完成 print(time_table.to_string()) target_pos_sch = TargetPosScheduler(api, "CZCE.MA109", time_table) # 启动循环 while not target_pos_sch.is_finished(): api.wait_update() api.close() Example2:: from tqsdk import TqApi, TargetPosScheduler from tqsdk.algorithm import twap_table api = TqApi(auth="信易账户,用户密码") quote = api.get_quote("CZCE.MA109") # 设置 twap 任务参数, time_table = twap_table(api, "CZCE.MA109", -100, 600, 1, 5) # 目标持仓 -100 手,600s 内完成 # 定制化调整 time_table,例如希望第一项任务延迟 10s 再开始下单 # 可以在 time_table 的头部加一行 time_table = pandas.concat([ DataFrame([[10, 10, None]], columns=['interval', 'target_pos', 'price']), time_table ], ignore_index=True) target_pos_sch = TargetPosScheduler(api, "CZCE.MA109", time_table) while not target_pos_sch.is_finished(): api.wait_update() # 获取 target_pos_sch 实例所有的成交列表 print(target_pos_sch.trades_df) # 利用成交列表,您可以计算出策略的各种表现指标,例如: average_trade_price = sum(scheduler.trades_df['price'] * scheduler.trades_df['volume']) / sum(scheduler.trades_df['volume']) print("成交均价:", average_trade_price) api.close() """ account = api._account._check_valid(account) if account is None: raise Exception(f"多账户模式下, 需要指定账户实例 account") min_volume_each_step = int(min_volume_each_step) max_volume_each_step = int(max_volume_each_step) if max_volume_each_step <= 0 or min_volume_each_step <= 0: raise Exception("请调整参数, min_volume_each_step、max_volume_each_step 必须是大于 0 的整数。") if min_volume_each_step > max_volume_each_step: raise Exception("请调整参数, min_volume_each_step 必须小于 max_volume_each_step。") pos = api.get_position(symbol, account) target_pos = int(target_pos) delta_pos = target_pos - pos.pos volume = abs(delta_pos) # 总的下单手数 # 得到有效的手数序列和时间间隔序列 if volume < max_volume_each_step: interval_list, volume_list = [duration], [volume] else: volume_list = _gen_random_list(sum_val=volume, min_val=min_volume_each_step, max_val=max_volume_each_step) interval = int(duration / len(volume_list)) if interval < 3: raise Exception("请调整参数, 每次下单时间间隔不能小于3s, 将单次下单手数阈值调大或者增长下单时间。") min_interval = int(max(3, interval - 2)) max_interval = int(interval * 2 - max(3, interval - 2)) + 1 interval_list = _gen_random_list(sum_val=duration, min_val=min_interval, max_val=max_interval, length=len(volume_list)) time_table = DataFrame(columns=['interval', 'volume', 'price']) for index, volume in enumerate(volume_list): assert interval_list[index] >= 3 active_interval = 2 append_time_table = pd.DataFrame([ {"interval": interval_list[index] - active_interval, "volume": volume, "price": "PASSIVE"}, {"interval": active_interval, "volume": 0, "price": "ACTIVE"} ]) time_table = pd.concat([time_table, append_time_table], ignore_index=True) time_table['volume'] = time_table['volume'].mul(-1 if delta_pos < 0 else 1) time_table['target_pos'] = time_table['volume'].cumsum() time_table['target_pos'] = time_table['target_pos'].add(pos.pos) time_table.drop(columns=['volume'], inplace=True) time_table = time_table.astype({'target_pos': 'int64', 'interval': 'float64'}) return time_table def vwap_table(api: TqApi, symbol: str, target_pos: int, duration: float, account: Optional[Union[TqAccount, TqKq, TqSim]] = None): """ 返回基于 vwap 策略的计划任务时间表。下单需要配合 TargetPosScheduler 使用。 调用 vwap_table 函数,根据以下逻辑生成 time_table: 1. 根据 target_pos - 当前合约的净持仓,得到总的需要调整手数 2. 请求 symbol 合约的 ``1min`` K 线 3. 采样取用最近 10 日内,以合约当前行情时间的下一分钟为起点,每日 duration / 60 根 K 线, \ 例如当前合约时间为 14:35:35,那么采样是会使用 14:36:00 开始的分钟线 K 线 4. 按日期分组,分别计算交易日内,每根 K 线成交量占总成交量的比例 5. 计算最近 10 日内相同分钟内的成交量占比的算术平均数,将第 1 步得到的总调整手数按照得到的比例分配 6. 每一分钟,前 58s 以追加价格下单,后 2s 以对价价格下单 Args: api (TqApi): TqApi实例,该task依托于指定api下单/撤单 symbol (str): 拟下单的合约 symbol, 格式为 交易所代码.合约代码, 例如 "SHFE.cu2201" target_pos (int): 目标持仓手数 duration (int): 算法执行的时长,以秒为单位,必须是 60 的整数倍,时长可以跨非交易时间段,但是不可以跨交易日 * 设置为 60*10, 可以是 10:10~10:15 + 10:30~10:35 account (TqAccount/TqKq/TqSim): [可选]指定发送下单指令的账户实例, 多账户模式下,该参数必须指定 Returns: pandas.DataFrame: 本函数返回一个 pandas.DataFrame 实例. 表示一份计划任务时间表。每一行表示一项目标持仓任务,包含以下列: + interval: 当前这项任务的持续时间长度,单位为秒 + target_pos: 当前这项任务的目标持仓 + price: 当前这项任务的下单价格模式,支持 PASSIVE(排队价),ACTIVE(对价),None(不下单,表示暂停一段时间) Example1:: from tqsdk import TqApi, TargetPosScheduler from tqsdk.algorithm import vwap_table api = TqApi(auth="信易账户,用户密码") quote = api.get_quote("CZCE.MA109") # 设置 vwap 任务参数 time_table = vwap_table(api, "CZCE.MA109", -100, 600) # 目标持仓 -100 手,600s 内完成 print(time_table.to_string()) target_pos_sch = TargetPosScheduler(api, "CZCE.MA109", time_table) # 启动循环 while not target_pos_sch.is_finished(): api.wait_update() api.close() """ account = api._account._check_valid(account) if account is None: raise Exception(f"多账户模式下, 需要指定账户实例 account") TIME_CELL = 60 # 等时长下单的时间单元, 单位: 秒 HISTORY_DAY_LENGTH = 10 # 使用多少天的历史数据用来计算每个时间单元的下单手数 if duration % TIME_CELL or duration < 60: raise Exception(f"duration {duration} 参数应该为 {TIME_CELL} 的整数倍") pos = account.get_position(symbol) target_pos = int(target_pos) delta_pos = target_pos - pos.pos target_volume = abs(delta_pos) # 总的下单手数 if target_volume == 0: return DataFrame(columns=['interval', 'target_pos', 'price']) # 获取 Kline klines = api.get_kline_serial(symbol, TIME_CELL, data_length=int(10 * 60 * 60 / TIME_CELL * HISTORY_DAY_LENGTH)) klines["time"] = klines.datetime.apply(lambda x: datetime.fromtimestamp(x // 1000000000).time()) # k线时间 klines["date"] = klines.datetime.apply(lambda x: datetime.fromtimestamp(_get_trading_day_from_timestamp(x) // 1000000000).date()) # k线交易日 quote = api.get_quote(symbol) # 当前交易日完整的交易时间段 trading_timestamp = _get_trading_timestamp(quote, quote.datetime) trading_timestamp_nano_range = trading_timestamp['night'] + trading_timestamp['day'] # 当前交易日完整的交易时间段 # 当前时间 行情时间 current_timestamp_nano = _get_trade_timestamp(quote.datetime, float('nan')) if not trading_timestamp_nano_range[0][0] <= current_timestamp_nano < trading_timestamp_nano_range[-1][1]: raise Exception("当前时间不在指定的交易时间段内") current_datetime = datetime.fromtimestamp(current_timestamp_nano//1000000000) # 下一分钟的开始时间 next_datetime = current_datetime.replace(second=0) + timedelta(minutes=1) start_datetime_nano = _datetime_to_timestamp_nano(next_datetime) r = _rangeset_head(_rangeset_slice(trading_timestamp_nano_range, start_datetime_nano), int(duration * 1e9)) if not (r and trading_timestamp_nano_range[0][0] <= r[-1][-1] < trading_timestamp_nano_range[-1][1]): raise Exception("指定时间段超出当前交易日") start_datetime = datetime.fromtimestamp(start_datetime_nano // 1000000000) end_datetime = datetime.fromtimestamp((r[-1][-1] - 1) // 1000000000) time_slot_start = time(start_datetime.hour, start_datetime.minute) # 计划交易时段起始时间点 time_slot_end = time(end_datetime.hour, end_datetime.minute) # 计划交易时段终点时间点 if time_slot_end > time_slot_start: # 判断是否类似 23:00:00 开始, 01:00:00 结束这样跨天的情况 klines = klines[(klines["time"] >= time_slot_start) & (klines["time"] <= time_slot_end)] else: klines = klines[(klines["time"] >= time_slot_start) | (klines["time"] <= time_slot_end)] # 获取在预设交易时间段内的所有K线, 即时间位于 time_slot_start 到 time_slot_end 之间的数据 need_date = klines['date'].drop_duplicates()[-HISTORY_DAY_LENGTH:] klines = klines[klines['date'].isin(need_date)] grouped_datetime = klines.groupby(['date', 'time'])['volume'].sum() # 计算每个交易日内的预设交易时间段内的成交量总和(level=0: 表示按第一级索引"data"来分组)后,将每根k线的成交量除以所在交易日内的总成交量,计算其所占比例 volume_percent = grouped_datetime / grouped_datetime.groupby(level=0).sum() predicted_percent = volume_percent.groupby(level=1).mean() # 将历史上相同时间单元的成交量占比使用算数平均计算出预测值 # 计算每个时间单元的成交量预测值 time_table = DataFrame(columns=['interval', 'volume', 'price']) volume_left = target_volume # 剩余手数 percent_left = 1 # 剩余百分比 for index, value in predicted_percent.items(): volume = round(volume_left * (value / percent_left)) volume_left -= volume percent_left -= value append_time_table = pd.DataFrame([ {"interval": TIME_CELL - 2, "volume": volume, "price": "PASSIVE"}, {"interval": 2, "volume": 0, "price": "ACTIVE"} ]) time_table = pd.concat([time_table, append_time_table], ignore_index=True) time_table['volume'] = time_table['volume'].mul(np.sign(delta_pos)) time_table['target_pos'] = time_table['volume'].cumsum() time_table['target_pos'] = time_table['target_pos'].add(pos.pos) time_table.drop(columns=['volume'], inplace=True) time_table = time_table.astype({'target_pos': 'int64', 'interval': 'float64'}) return time_table def _gen_random_list(sum_val: int, min_val: int, max_val: int, length: int = None): """ 生成随机列表,参数应该满足:min_val * length <= sum_val <= max_val * length :param int sum_val: 列表元素之和 :param int min_val: 列表元素最小值 :param int max_val: 列表元素最大值 :param int length: 列表长度,如果没有指定,则返回的列表长度没有指定 :return: 整型列表,满足 sum(list) = sum_val, len(list) == length, min_val < any_item(list) < max_val """ if length is None: length = sum_val * 2 // (min_val + max_val) # 先确定 ist 长度,interval 大小,再生成 volume_list 随机列表 # 例如:sum = 16 min_val = 11 max_val = 15,不满足 min_val * length <= sum_val <= max_val * length assert min_val * length <= sum_val <= max_val * length + min_val else: assert min_val * length <= sum_val <= max_val * length result_list = [min_val for _ in range(length)] if sum(result_list) == sum_val: return result_list # 全部最小值刚好满足,可以提前退出 result_rest_value = sum_val - min_val * length # 剩余可以填充的个数 result_rest_position = (max_val - min_val) * length # 剩余需要填充的位置个数 if sum_val > max_val * length: result_list.append(0) result_rest_position += min_val result_rest_list = _gen_shuffle_list(result_rest_value, result_rest_position) for i in range(len(result_list)): start = (max_val - min_val) * i end = (max_val - min_val) * (i + 1) if start < (max_val - min_val) * length else result_rest_position result_list[i] += sum(result_rest_list[start:end]) assert len(result_list) == length or len(result_list) == length + 1 assert sum(result_list) == sum_val return result_list def _gen_shuffle_list(x: int, n: int): """从 n 个位置中随机选中 x 个""" assert x <= n result_list = [1 for _ in range(x)] + [0 for _ in range(n - x)] utils.RD.shuffle(result_list) return result_list
[ "mayanqiong@shinnytech.com" ]
mayanqiong@shinnytech.com
1d0d49e5469fa5f735320874f158f57d8ee8372b
ee70802fce6213696cc0bc5366d394d8251a2753
/Curso2 - Formacao Cientista de Dados/09_-_Graficos_e_Dashboards/03_-_Dispersao.py
e93fa5edbe0e1ed5aa8352e9d06e86b8a7152fdf
[]
no_license
CarlosAVSFilho/Data-Science
692459190d07607f4a07a2c9d2f18af6085f986e
b37f0c0b9f1428656ec71ee4b963726bdd63df0d
refs/heads/master
2020-05-27T12:13:33.922422
2019-05-26T01:35:06
2019-05-26T01:35:06
188,612,821
0
0
null
null
null
null
UTF-8
Python
false
false
386
py
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns base = pd.read_csv('trees.csv') plt.scatter(base.Girth, base.Volume, color = 'blue', facecolors = 'none', marker = '^') plt.xlabel('Volume') plt.ylabel('Circunferência') plt.title('Árvores') plt.plot(base.Girth, base.Volume) sns.regplot(base.Girth, base.Volume, data = base, x_jitter = 0.3, fit_reg = True)
[ "carlos.avsfilho@gmail.com" ]
carlos.avsfilho@gmail.com
63a315a236f95825efa37747325ff1fb8e57836c
04a714f9771db7a4c0560d2b038b778d2d3223f4
/websites/websites/celery.py
44d73456d363b41336412a04050918df19a46e80
[]
no_license
wieczorek1990/websites
598eb58ac98d8e272fdcc277ccb1d1a332348321
82a298c703e1a66b8217b39d7cc574f9584f2bcd
refs/heads/master
2023-01-22T11:33:40.910797
2020-11-26T10:56:54
2020-11-26T10:56:54
316,169,474
0
0
null
null
null
null
UTF-8
Python
false
false
319
py
import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websites.settings') app = Celery('websites') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request))
[ "lukasz.wieczorek@ironin.pl" ]
lukasz.wieczorek@ironin.pl
160854b008214baadb4ac1249bdc13279f58b7cd
8ac75ee9dcb850c966a05a72bdfaf34fcf35965d
/Hacker-rank/array.py
b1ba89eb0f5395d0f0b8ca10d6e15f5dddfe022b
[]
no_license
mathankrish/Python-Programs
3f7257ffa3a7084239dcc16eaf8bb7e534323102
2f76e850c92d3126b26007805df03bffd603fcdf
refs/heads/master
2020-05-01T04:27:00.943545
2019-10-07T18:57:41
2019-10-07T18:57:41
177,274,558
0
0
null
null
null
null
UTF-8
Python
false
false
96
py
array_size = int(input()) x = [int(input()) for i in range(array_size)] print(x[::-1])
[ "noreply@github.com" ]
mathankrish.noreply@github.com
94edb417384c9151204750623869b51a462777a2
8bde5794b10d24b7d9126f9461f8099d0675eb78
/gat/train.py
db8d7ce2df9eaf3350bb15406e095a7ef79b59c9
[]
no_license
aksnzhy/dgl-benchmark
9938d24ce695f2f32faea45bc85a25f04348c177
1d746d690c8aa11bf793744d1c9cea6e762a6847
refs/heads/master
2021-05-17T12:33:18.566606
2020-11-09T07:06:33
2020-11-09T07:06:33
250,708,185
0
0
null
2020-03-28T03:43:37
2020-03-28T03:43:36
null
UTF-8
Python
false
false
5,150
py
""" Graph Attention Networks in DGL using SPMV optimization. Multiple heads are also batched together for faster training. Compared with the original paper, this code does not implement early stopping. References ---------- Paper: https://arxiv.org/abs/1710.10903 Author's code: https://github.com/PetarV-/GAT Pytorch implementation: https://github.com/Diego999/pyGAT """ import argparse import time import torch import torch.nn.functional as F from dgl import DGLGraph from dgl.data import register_data_args, load_data from gat import GAT def accuracy(logits, labels): _, indices = torch.max(logits, dim=1) correct = torch.sum(indices == labels) return correct.item() * 1.0 / len(labels) def evaluate(model, features, labels, mask): model.eval() with torch.no_grad(): logits = model(features) logits = logits[mask] labels = labels[mask] return accuracy(logits, labels) def main(args): # load and preprocess dataset data = load_data(args) features = torch.FloatTensor(data.features) labels = torch.LongTensor(data.labels) train_mask = torch.ByteTensor(data.train_mask) val_mask = torch.ByteTensor(data.val_mask) test_mask = torch.ByteTensor(data.test_mask) num_feats = features.shape[1] n_classes = data.num_labels n_edges = data.graph.number_of_edges() print("""----Data statistics------' #Edges %d #Classes %d #Train samples %d #Val samples %d #Test samples %d""" % (n_edges, n_classes, train_mask.sum().item(), val_mask.sum().item(), test_mask.sum().item())) if args.gpu < 0: cuda = False else: cuda = True torch.cuda.set_device(args.gpu) features = features.cuda() labels = labels.cuda() train_mask = train_mask.cuda() val_mask = val_mask.cuda() test_mask = test_mask.cuda() g = data.graph # add self loop g.remove_edges_from(g.selfloop_edges()) g = DGLGraph(g) g.add_edges(g.nodes(), g.nodes()) n_edges = g.number_of_edges() # create model heads = ([args.num_heads] * args.num_layers) + [args.num_out_heads] model = GAT(g, args.num_layers, num_feats, args.num_hidden, n_classes, heads, F.elu, args.in_drop, args.attn_drop, args.alpha, args.residual) print(model) if cuda: model.cuda() loss_fcn = torch.nn.CrossEntropyLoss() # use optimizer optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay) # initialize graph start = time.time() for epoch in range(args.epochs + 1): model.train() # forward logits = model(features) loss = loss_fcn(logits[train_mask], labels[train_mask]) optimizer.zero_grad() loss.backward() optimizer.step() if epoch == 1: # skip for epoch for warm up if cuda: torch.cuda.synchronize() start = time.time() if cuda: torch.cuda.synchronize() end = time.time() acc = evaluate(model, features, labels, test_mask) print("Accuracy: {:.4f}\n{:.4f}".format(acc, end - start)) if __name__ == '__main__': parser = argparse.ArgumentParser(description='GAT') register_data_args(parser) parser.add_argument("--gpu", type=int, default=-1, help="which GPU to use. Set -1 to use CPU.") parser.add_argument("--epochs", type=int, default=200, help="number of training epochs") parser.add_argument("--num-heads", type=int, default=8, help="number of hidden attention heads") parser.add_argument("--num-out-heads", type=int, default=1, help="number of output attention heads") parser.add_argument("--num-layers", type=int, default=1, help="number of hidden layers") parser.add_argument("--num-hidden", type=int, default=8, help="number of hidden units") parser.add_argument("--residual", action="store_true", default=False, help="use residual connection") parser.add_argument("--in-drop", type=float, default=.6, help="input feature dropout") parser.add_argument("--attn-drop", type=float, default=.6, help="attention dropout") parser.add_argument("--lr", type=float, default=0.005, help="learning rate") parser.add_argument('--weight-decay', type=float, default=5e-4, help="weight decay") parser.add_argument('--alpha', type=float, default=0.2, help="the negative slop of leaky relu") parser.add_argument('--fastmode', action="store_true", default=False, help="skip re-evaluate the validation set") args = parser.parse_args() print(args) main(args)
[ "noreply@github.com" ]
aksnzhy.noreply@github.com
bc5a716acbc8aed645333f308c035eaf2615f7a1
f889a1de574dc55425677bcbea6410bf360cddd6
/labels/views.py
1dad9e6693aa60e4798eb610ecb07b2f081ac19e
[]
no_license
Hagbuck/MyBlackSmith
816b3b711db021ee702a19b3240bb30c48271bc6
671088bee46d2fa705bfd9b37f059610bcdd2252
refs/heads/main
2023-01-24T12:23:18.255371
2020-12-02T16:46:19
2020-12-02T16:46:19
313,397,620
0
0
null
null
null
null
UTF-8
Python
false
false
2,284
py
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse, reverse_lazy from rest_framework import viewsets from .serializers import LabelSerializer from .models import Label class LabelsList(LoginRequiredMixin, generic.ListView): template_name = "labels/labels.html" context_object_name = "label_list" def get_queryset(self): return Label.objects.all().filter(user = self.request.user.id) class CreateLabel(LoginRequiredMixin, generic.CreateView): template_name = 'labels/create_label.html' model = Label fields = ['name', 'color', 'project'] def form_valid(self, form): label = form.save(commit=False) label.user = self.request.user label.save() return HttpResponseRedirect(reverse('labels:labels')) class LabelDetail(LoginRequiredMixin, generic.DetailView): template_name = 'labels/label.html' model = Label def get_queryset(self): return Label.objects.all().filter(user = self.request.user.id) class UpdateLabel(LoginRequiredMixin, generic.UpdateView): template_name = 'labels/update_label.html' model = Label fields = ['name', 'color', 'project'] def get_queryset(self): return Label.objects.all().filter(user = self.request.user.id) def form_valid(self, form): label = form.save(commit=False) label.user = self.request.user label.save() return HttpResponseRedirect(reverse('labels:label', kwargs={'pk': self.kwargs['pk']})) class DeleteLabel(LoginRequiredMixin, generic.DeleteView): model = Label success_url = reverse_lazy('labels:labels') def get_queryset(self): return Label.objects.all().filter(user = self.request.user.id) ####################### # API # ####################### class LabelViewSet(viewsets.ModelViewSet): queryset = Label.objects.all() serializer_class = LabelSerializer def get_queryset(self, *args, **kwargs): if self.request.user.is_superuser: return Label.objects.all() return Label.objects.all().filter(id = self.request.user.id)
[ "anthony.vuillemin@outlook.fr" ]
anthony.vuillemin@outlook.fr
77b7efea836ff42189f54a65ef3b5fa7ab59212b
184ceaea8f1c2c398ceb75fe367709d9d0aea1a3
/main.py
956bee276935d265b9419f03f3e3074c4f70b0d9
[]
no_license
guojt1017/pythonProject4
fe32426fb199cfcf128be086c9d5251772453f92
ca4d8fc24f3521b22a1ac0dd8ebf7f9f8e9ba004
refs/heads/master
2022-11-28T16:41:26.806064
2020-08-12T10:48:37
2020-08-12T10:48:37
286,988,222
0
0
null
null
null
null
UTF-8
Python
false
false
295
py
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. if __name__ == '__main__': import numpy as np a=[1,2,3,4] b=np.array(a) print(b)
[ "guojt1997@sina.com" ]
guojt1997@sina.com