max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
mlrun/api/schemas/frontend_spec.py
rpatil524/mlrun
0
6628251
<filename>mlrun/api/schemas/frontend_spec.py import typing import pydantic class FrontendSpec(pydantic.BaseModel): jobs_dashboard_url: typing.Optional[str]
<filename>mlrun/api/schemas/frontend_spec.py import typing import pydantic class FrontendSpec(pydantic.BaseModel): jobs_dashboard_url: typing.Optional[str]
none
1
1.616083
2
login/casLogin.py
illusion2018/fuckTodayStudy
0
6628252
<gh_stars>0 import json import re import requests from bs4 import BeautifulSoup from urllib3.exceptions import InsecureRequestWarning from login.Utils import Utils requests.packages.urllib3.disable_warnings(InsecureRequestWarning) class casLogin: # 初始化cas登陆模块 def __init__(self, username, password, login_url, host, session): self.username = username self.password = password self.login_url = login_url self.host = host self.session = session self.type = 0 # 判断是否需要验证码 def getNeedCaptchaUrl(self): if self.type == 0: url = self.host + 'authserver/needCaptcha.html' + '?username=' + self.username flag = self.session.get(url, verify=False).text return 'false' != flag and 'False' != flag else: url = self.host + 'authserver/checkNeedCaptcha.htl' + '?username=' + self.username flag = self.session.get(url, verify=False).json() return flag['isNeed'] def login(self): html = self.session.get(self.login_url, verify=False).text soup = BeautifulSoup(html, 'lxml') form = soup.select('#casLoginForm') if len(form) == 0: form = soup.select("#loginFromId") if len(form) == 0: raise Exception('出错啦!网页中没有找到casLoginForm') soup = BeautifulSoup(str(form[1]), 'lxml') self.type = 1 # 填充数据 params = {} form = soup.select('input') for item in form: if None != item.get('name') and len(item.get('name')) > 0: if item.get('name') != 'rememberMe': if None == item.get('value'): params[item.get('name')] = '' else: params[item.get('name')] = item.get('value') if self.type == 0: salt = soup.select("#pwdDefaultEncryptSalt") else: salt = soup.select("#pwdEncryptSalt") if len(salt) != 0: salt = salt[0].get('value') else: pattern = '\"(\w{16})\"' salt = re.findall(pattern, html) if (len(salt) != 0): salt = salt[1] else: salt = False print(salt) params['username'] = self.username if not salt: params['password'] = self.password else: params['password'] = Utils.encryptAES(self.password, salt) if self.getNeedCaptchaUrl(): if self.type == 0: imgUrl = self.host + 'authserver/captcha.html' params['captchaResponse'] = Utils.getCodeFromImg(self.session, imgUrl) else: imgUrl = self.host + 'authserver/getCaptcha.htl' params['captcha'] = Utils.getCodeFromImg(self.session, imgUrl) data = self.session.post(self.login_url, params=params, allow_redirects=False) print("ss",data.status_code) # 如果等于302强制跳转,代表登陆成功 if data.status_code == 302: jump_url = data.headers['Location'] self.session.headers['Server'] = 'CloudWAF' res = self.session.get(jump_url, verify=False) if res.status_code == 200: return self.session.cookies else: print(res,"ress") res = self.session.get(re.findall(r'\w{4,5}\:\/\/.*?\/', self.login_url)[0], verify=False) if res.status_code == 200 or res.status_code == 404: return self.session.cookies else: raise Exception('登录失败,请反馈BUG') elif data.status_code == 200: data = data.text soup = BeautifulSoup(data, 'lxml') print(data,self.type) if self.type == 0: print('485489465156') msg = soup.select('#errorMsg')[0].get_text() msg='smwy' print(msg) else: msg = soup.select('#formErrorTip2')[0].get_text() raise Exception(msg) else: raise Exception('教务系统出现了问题啦!返回状态码:' + str(data.status_code))
import json import re import requests from bs4 import BeautifulSoup from urllib3.exceptions import InsecureRequestWarning from login.Utils import Utils requests.packages.urllib3.disable_warnings(InsecureRequestWarning) class casLogin: # 初始化cas登陆模块 def __init__(self, username, password, login_url, host, session): self.username = username self.password = password self.login_url = login_url self.host = host self.session = session self.type = 0 # 判断是否需要验证码 def getNeedCaptchaUrl(self): if self.type == 0: url = self.host + 'authserver/needCaptcha.html' + '?username=' + self.username flag = self.session.get(url, verify=False).text return 'false' != flag and 'False' != flag else: url = self.host + 'authserver/checkNeedCaptcha.htl' + '?username=' + self.username flag = self.session.get(url, verify=False).json() return flag['isNeed'] def login(self): html = self.session.get(self.login_url, verify=False).text soup = BeautifulSoup(html, 'lxml') form = soup.select('#casLoginForm') if len(form) == 0: form = soup.select("#loginFromId") if len(form) == 0: raise Exception('出错啦!网页中没有找到casLoginForm') soup = BeautifulSoup(str(form[1]), 'lxml') self.type = 1 # 填充数据 params = {} form = soup.select('input') for item in form: if None != item.get('name') and len(item.get('name')) > 0: if item.get('name') != 'rememberMe': if None == item.get('value'): params[item.get('name')] = '' else: params[item.get('name')] = item.get('value') if self.type == 0: salt = soup.select("#pwdDefaultEncryptSalt") else: salt = soup.select("#pwdEncryptSalt") if len(salt) != 0: salt = salt[0].get('value') else: pattern = '\"(\w{16})\"' salt = re.findall(pattern, html) if (len(salt) != 0): salt = salt[1] else: salt = False print(salt) params['username'] = self.username if not salt: params['password'] = self.password else: params['password'] = Utils.encryptAES(self.password, salt) if self.getNeedCaptchaUrl(): if self.type == 0: imgUrl = self.host + 'authserver/captcha.html' params['captchaResponse'] = Utils.getCodeFromImg(self.session, imgUrl) else: imgUrl = self.host + 'authserver/getCaptcha.htl' params['captcha'] = Utils.getCodeFromImg(self.session, imgUrl) data = self.session.post(self.login_url, params=params, allow_redirects=False) print("ss",data.status_code) # 如果等于302强制跳转,代表登陆成功 if data.status_code == 302: jump_url = data.headers['Location'] self.session.headers['Server'] = 'CloudWAF' res = self.session.get(jump_url, verify=False) if res.status_code == 200: return self.session.cookies else: print(res,"ress") res = self.session.get(re.findall(r'\w{4,5}\:\/\/.*?\/', self.login_url)[0], verify=False) if res.status_code == 200 or res.status_code == 404: return self.session.cookies else: raise Exception('登录失败,请反馈BUG') elif data.status_code == 200: data = data.text soup = BeautifulSoup(data, 'lxml') print(data,self.type) if self.type == 0: print('485489465156') msg = soup.select('#errorMsg')[0].get_text() msg='smwy' print(msg) else: msg = soup.select('#formErrorTip2')[0].get_text() raise Exception(msg) else: raise Exception('教务系统出现了问题啦!返回状态码:' + str(data.status_code))
zh
0.898292
# 初始化cas登陆模块 # 判断是否需要验证码 # 填充数据 # 如果等于302强制跳转,代表登陆成功
2.80834
3
game/urls.py
claudiordgz/tictactoe-django
0
6628253
<reponame>claudiordgz/tictactoe-django from django.conf.urls import patterns, url urlpatterns = patterns( 'game.views', url(r'^$', 'index', name='index'), url(r'^(?P<pk>\d+)/$', 'game', name='detail') )
from django.conf.urls import patterns, url urlpatterns = patterns( 'game.views', url(r'^$', 'index', name='index'), url(r'^(?P<pk>\d+)/$', 'game', name='detail') )
none
1
1.808033
2
project/newsfeed/models.py
beijbom/coralnet
31
6628254
from django.conf import settings from django.core.exceptions import ValidationError from django.db import models from images.models import Source from django.contrib.auth.models import User # Create your models here. def log_item(source, user, category, message): """ Convenience method for creating a new NewsItem. """ ns = NewsItem(source_name=source.name, source_id=source.id, user_id=user.id, user_username=user.username, message=message, category=category) ns.save() return ns def log_sub_item(news_item, message): """ Convenience method for creating a new NewsSubItem. """ ni = NewsSubItem(news_item=news_item, message=message) ni.save() class NewsItem(models.Model): """ These are main news-items to be displayed in the source main pages as well on an aggregate listings. """ # Not using foreign keys since we don't want to delete a news-item if a # source or user is deleted. source_id = models.IntegerField(null=False, blank=False) source_name = models.CharField(null=False, blank=False, max_length=200) # Don't require the user to be set. user_id = models.IntegerField(null=False, blank=False) user_username = models.CharField(null=False, blank=False, max_length=50) message = models.TextField(null=False, blank=False, max_length=500) category = models.CharField(null=False, blank=False, max_length=50, choices=[(a, b) for a, b in zip(settings.NEWS_ITEM_CATEGORIES, settings.NEWS_ITEM_CATEGORIES)]) datetime = models.DateTimeField(auto_now_add=True, editable=False) def render_view(self): """ Renders the record into a dictionary used in the views. """ curated = { 'source_name': self.source_name, 'source_id': self.source_id, 'user_username': self.user_username, 'user_id': self.user_id, 'category': self.category, 'message': self.message.format(subcount=NewsSubItem.objects. filter(news_item=self).count()), 'datetime': self.datetime.strftime("%c"), 'id': self.id, } sources = Source.objects.filter(id=self.source_id) curated['source_exists'] = sources.count() > 0 users = User.objects.filter(id=self.user_id) curated['user_exists'] = users.count() > 0 return curated def save(self, *args, **kwargs): self.clean() super().save(*args, **kwargs) def clean(self): if self.category not in settings.NEWS_ITEM_CATEGORIES: raise ValidationError( "Doesn't recognize {} as an installed app.".format( self.category)) class NewsSubItem(models.Model): """ These are sub-items on main news items. For examples, individual images annotated as part of a annotation session. """ news_item = models.ForeignKey(NewsItem, on_delete=models.CASCADE) message = models.TextField(null=False, blank=False, max_length=500) datetime = models.DateTimeField(auto_now_add=True, editable=False) def render_view(self): """ Renders the record into a dictionary used in the views. """ return { 'message': self.message, 'datetime': self.datetime.strftime("%c"), 'id': self.id, }
from django.conf import settings from django.core.exceptions import ValidationError from django.db import models from images.models import Source from django.contrib.auth.models import User # Create your models here. def log_item(source, user, category, message): """ Convenience method for creating a new NewsItem. """ ns = NewsItem(source_name=source.name, source_id=source.id, user_id=user.id, user_username=user.username, message=message, category=category) ns.save() return ns def log_sub_item(news_item, message): """ Convenience method for creating a new NewsSubItem. """ ni = NewsSubItem(news_item=news_item, message=message) ni.save() class NewsItem(models.Model): """ These are main news-items to be displayed in the source main pages as well on an aggregate listings. """ # Not using foreign keys since we don't want to delete a news-item if a # source or user is deleted. source_id = models.IntegerField(null=False, blank=False) source_name = models.CharField(null=False, blank=False, max_length=200) # Don't require the user to be set. user_id = models.IntegerField(null=False, blank=False) user_username = models.CharField(null=False, blank=False, max_length=50) message = models.TextField(null=False, blank=False, max_length=500) category = models.CharField(null=False, blank=False, max_length=50, choices=[(a, b) for a, b in zip(settings.NEWS_ITEM_CATEGORIES, settings.NEWS_ITEM_CATEGORIES)]) datetime = models.DateTimeField(auto_now_add=True, editable=False) def render_view(self): """ Renders the record into a dictionary used in the views. """ curated = { 'source_name': self.source_name, 'source_id': self.source_id, 'user_username': self.user_username, 'user_id': self.user_id, 'category': self.category, 'message': self.message.format(subcount=NewsSubItem.objects. filter(news_item=self).count()), 'datetime': self.datetime.strftime("%c"), 'id': self.id, } sources = Source.objects.filter(id=self.source_id) curated['source_exists'] = sources.count() > 0 users = User.objects.filter(id=self.user_id) curated['user_exists'] = users.count() > 0 return curated def save(self, *args, **kwargs): self.clean() super().save(*args, **kwargs) def clean(self): if self.category not in settings.NEWS_ITEM_CATEGORIES: raise ValidationError( "Doesn't recognize {} as an installed app.".format( self.category)) class NewsSubItem(models.Model): """ These are sub-items on main news items. For examples, individual images annotated as part of a annotation session. """ news_item = models.ForeignKey(NewsItem, on_delete=models.CASCADE) message = models.TextField(null=False, blank=False, max_length=500) datetime = models.DateTimeField(auto_now_add=True, editable=False) def render_view(self): """ Renders the record into a dictionary used in the views. """ return { 'message': self.message, 'datetime': self.datetime.strftime("%c"), 'id': self.id, }
en
0.916354
# Create your models here. Convenience method for creating a new NewsItem. Convenience method for creating a new NewsSubItem. These are main news-items to be displayed in the source main pages as well on an aggregate listings. # Not using foreign keys since we don't want to delete a news-item if a # source or user is deleted. # Don't require the user to be set. Renders the record into a dictionary used in the views. These are sub-items on main news items. For examples, individual images annotated as part of a annotation session. Renders the record into a dictionary used in the views.
2.414139
2
mobile/features/pages/base_page.py
mauriciochaves/minicursopythonnordeste
1
6628255
from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from appium import webdriver class BasePage: def __init__(self, driver): self.driver = driver def get_title(self): return self.driver.title def click(self, locator): self.wait_for(EC.element_to_be_clickable(locator)).click() def find(self, locator): element = self.wait_for(EC.visibility_of_element_located(locator)) return element def wait_for(self, condition, seconds = 5): return WebDriverWait(self.driver, seconds).until(condition) def type_in(self, locator, text, set_clear = True): element = self.find(locator) if set_clear: element.clear() element.send_keys(text)
from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from appium import webdriver class BasePage: def __init__(self, driver): self.driver = driver def get_title(self): return self.driver.title def click(self, locator): self.wait_for(EC.element_to_be_clickable(locator)).click() def find(self, locator): element = self.wait_for(EC.visibility_of_element_located(locator)) return element def wait_for(self, condition, seconds = 5): return WebDriverWait(self.driver, seconds).until(condition) def type_in(self, locator, text, set_clear = True): element = self.find(locator) if set_clear: element.clear() element.send_keys(text)
none
1
2.753959
3
src/the_tale/the_tale/common/utils/resources.py
devapromix/the-tale
1
6628256
<gh_stars>1-10 import smart_imports smart_imports.all() class Resource(dext_old_views.BaseResource): ERROR_TEMPLATE = 'error.html' DIALOG_ERROR_TEMPLATE = 'dialog_error.html' def __init__(self, request, *args, **kwargs): super(Resource, self).__init__(request, *args, **kwargs) self.account = self.request.user if self.account.is_authenticated: self.account = accounts_prototypes.AccountPrototype(model=self.account) def initialize(self, *args, **kwargs): super(Resource, self).initialize(*args, **kwargs) if self.account.is_authenticated and self.account.is_update_active_state_needed: amqp_environment.environment.workers.accounts_manager.cmd_run_account_method(account_id=self.account.id, method_name=accounts_prototypes.AccountPrototype.update_active_state.__name__, data={}) def validate_account_argument(self, account_id): if self.account and self.account.id == int(account_id): return self.account return accounts_prototypes.AccountPrototype.get_by_id(account_id)
import smart_imports smart_imports.all() class Resource(dext_old_views.BaseResource): ERROR_TEMPLATE = 'error.html' DIALOG_ERROR_TEMPLATE = 'dialog_error.html' def __init__(self, request, *args, **kwargs): super(Resource, self).__init__(request, *args, **kwargs) self.account = self.request.user if self.account.is_authenticated: self.account = accounts_prototypes.AccountPrototype(model=self.account) def initialize(self, *args, **kwargs): super(Resource, self).initialize(*args, **kwargs) if self.account.is_authenticated and self.account.is_update_active_state_needed: amqp_environment.environment.workers.accounts_manager.cmd_run_account_method(account_id=self.account.id, method_name=accounts_prototypes.AccountPrototype.update_active_state.__name__, data={}) def validate_account_argument(self, account_id): if self.account and self.account.id == int(account_id): return self.account return accounts_prototypes.AccountPrototype.get_by_id(account_id)
none
1
1.835801
2
eulerangles/math/rotation_matrix_to_eulers.py
alisterburt/eulerangles
13
6628257
import numpy as np from .constants import valid_axes def matrix2xyx_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rx(k3) @ Ry(k2) @ Rx(k1) = [[c2, s1s2, c1s2], [s2s3, -s1c2s3+c1c3, -c1c2s3-s1c3], [-s2c3, s1c2c3+c1s3, c1c2c3-s1s3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arccos(rotation_matrices[:, 0, 0]) # Gimbal lock case (s2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 2]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r23 = rotation_matrices[gimbal_idx, 1, 2] r22 = rotation_matrices[gimbal_idx, 1, 1] angles_radians[gimbal_idx, 0] = np.arctan2(-r23, r22) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r12 = rotation_matrices[idx, 0, 1] r13 = rotation_matrices[idx, 0, 2] r21 = rotation_matrices[idx, 1, 0] r31 = rotation_matrices[idx, 2, 0] angles_radians[idx, 0] = np.arctan2(r12, r13) angles_radians[idx, 2] = np.arctan2(r21, -r31) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2yzy_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Ry(k3) @ Rz(k2) @ Ry(k1) = [[c1c2c3-s1s3, -s2c3, s1c2c3+c1c3], [c1s2, c2, s1s2], [-c1c2s3, s2s3, -s1c2s3+c1c3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arccos(rotation_matrices[:, 1, 1]) # Gimbal lock case (s2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 1, 0]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r31 = rotation_matrices[gimbal_idx, 2, 0] r33 = rotation_matrices[gimbal_idx, 2, 2] angles_radians[gimbal_idx, 0] = np.arctan2(-r31, r33) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r23 = rotation_matrices[idx, 1, 2] r21 = rotation_matrices[idx, 1, 0] r32 = rotation_matrices[idx, 2, 1] r12 = rotation_matrices[idx, 0, 1] angles_radians[idx, 0] = np.arctan2(r23, r21) angles_radians[idx, 2] = np.arctan2(r32, -r12) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2zxz_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rz(k3) @ Rx(k2) @ Rz(k1) = [[-s1c2s3+c1c3, -c1c2s3-s1c3, s2s3], [s1c2c3+s1s3, c1c2c3-s1s3, -s2c3], [s1s2, c1s2, c2]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles[:, 1] = np.arccos(rotation_matrices[:, 2, 2]) # Gimbal lock case (s2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 2]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r12 = rotation_matrices[gimbal_idx, 0, 1] r11 = rotation_matrices[gimbal_idx, 0, 0] angles[gimbal_idx, 0] = np.arctan2(-r12, r11) angles[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r31 = rotation_matrices[idx, 2, 0] r32 = rotation_matrices[idx, 2, 1] r13 = rotation_matrices[idx, 0, 2] r23 = rotation_matrices[idx, 1, 2] angles[idx, 0] = np.arctan2(r31, r32) angles[idx, 2] = np.arctan2(r13, -r23) # convert to degrees euler_angles = np.rad2deg(angles) return euler_angles def matrix2xzx_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rx(k3) @ Rz(k2) @ Rx(k1) = [[c2, -c1s2, s1s2], [s2c3, c1c2c3-s3, -s1c2c3-c1s3], [s2s3, c1c2s3+s1c3, -s1c2s3+c1c3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arccos(rotation_matrices[:, 0, 0]) # Gimbal lock case (s2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 2]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r32 = rotation_matrices[gimbal_idx, 2, 1] r33 = rotation_matrices[gimbal_idx, 2, 2] angles_radians[gimbal_idx, 0] = np.arctan2(r32, r33) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r13 = rotation_matrices[idx, 0, 2] r12 = rotation_matrices[idx, 0, 1] r31 = rotation_matrices[idx, 2, 0] r21 = rotation_matrices[idx, 1, 0] angles_radians[idx, 0] = np.arctan2(r13, -r12) angles_radians[idx, 2] = np.arctan2(r31, r21) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2yxy_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Ry(k3) @ Rx(k2) @ Ry(k1) = [[-s1c2s3+c1c3, s2s3, c1c2s3+s1c3], [s1s2, c2, -c1s2], [-s1c2c3-c1s3, s2c3, c1c2c3-s1s3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arccos(rotation_matrices[:, 1, 1]) # Gimbal lock case (s2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 1]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r13 = rotation_matrices[gimbal_idx, 0, 2] r11 = rotation_matrices[gimbal_idx, 0, 0] angles_radians[gimbal_idx, 0] = np.arctan2(r13, r11) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r21 = rotation_matrices[idx, 1, 0] r23 = rotation_matrices[idx, 1, 2] r12 = rotation_matrices[idx, 0, 1] r32 = rotation_matrices[idx, 2, 1] angles_radians[idx, 0] = np.arctan2(r21, -r23) angles_radians[idx, 2] = np.arctan2(r12, r32) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2zyz_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rz(k3) @ Ry(k2) @ Rz(k1) = [[c1c2c3-s1s3, -s1c2c3-c1s3, s2c3], [c1c2s3+s1c3, -s1c2s3+c1c3, s2s3], [-c1s2, s1s2, c2]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arccos(rotation_matrices[:, 2, 2]) # Gimbal lock case (s2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 2]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r21 = rotation_matrices[gimbal_idx, 1, 0] r22 = rotation_matrices[gimbal_idx, 1, 1] angles_radians[gimbal_idx, 0] = np.arctan2(r21, r22) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r32 = rotation_matrices[idx, 2, 1] r31 = rotation_matrices[idx, 2, 0] r23 = rotation_matrices[idx, 1, 2] r13 = rotation_matrices[idx, 0, 2] angles_radians[idx, 0] = np.arctan2(r32, -r31) angles_radians[idx, 2] = np.arctan2(r23, r13) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2xyz_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rz(k3) @ Ry(k2) @ Rx(k1) = [[c2c3, s1s2c3-c1s3, c1s2c3+s1s3], [c2s3, s1s2s3+c1c3, c1s2s3-s1c3], [-s2, s1c2, c1c2]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = -np.arcsin(rotation_matrices[:, 2, 0]) # Gimbal lock case (c2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 0]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r23 = rotation_matrices[gimbal_idx, 1, 2] r22 = rotation_matrices[gimbal_idx, 1, 1] angles_radians[gimbal_idx, 0] = np.arctan2(-r23, r22) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r32 = rotation_matrices[idx, 2, 1] r33 = rotation_matrices[idx, 2, 2] r21 = rotation_matrices[idx, 1, 0] r11 = rotation_matrices[idx, 0, 0] angles_radians[idx, 0] = np.arctan2(r32, r33) angles_radians[idx, 2] = np.arctan2(r21, r11) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2yzx_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rx(k3) @ Rz(k2) @ Ry(k1) = [[c1c2, -s2, s1c2], [c1s2c3+s1s3, c2c3, s1s2c3-c1s3], [c1s2s3-s1c3, c2s3, s1s2s3+c1c3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = -np.arcsin(rotation_matrices[:, 0, 1]) # Gimbal lock case (c2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 0]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r31 = rotation_matrices[gimbal_idx, 2, 0] r33 = rotation_matrices[gimbal_idx, 2, 2] angles_radians[gimbal_idx, 0] = np.arctan2(-r31, r33) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r13 = rotation_matrices[idx, 0, 2] r11 = rotation_matrices[idx, 0, 0] r32 = rotation_matrices[idx, 2, 1] r22 = rotation_matrices[idx, 1, 1] angles_radians[idx, 0] = np.arctan2(r13, r11) angles_radians[idx, 2] = np.arctan2(r32, r22) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2zxy_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Ry(k3) @ Rx(k2) @ Rz(k1) = [[s1s2s3+c1c3, c1s2s3-s1c3, c2s3], [s1c2, c1c2, -s2], [s1s2c3-c1s3, c1s2c3+s1s3, c2c3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = -np.arcsin(rotation_matrices[:, 1, 2]) # Gimbal lock case (c2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 1, 0]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r12 = rotation_matrices[gimbal_idx, 0, 1] r11 = rotation_matrices[gimbal_idx, 0, 0] angles_radians[gimbal_idx, 0] = np.arctan2(-r12, r11) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r21 = rotation_matrices[idx, 1, 0] r22 = rotation_matrices[idx, 1, 1] r13 = rotation_matrices[idx, 0, 2] r33 = rotation_matrices[idx, 2, 2] angles_radians[idx, 0] = np.arctan2(r21, r22) angles_radians[idx, 2] = np.arctan2(r13, r33) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2xzy_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Ry(k3) @ Rz(k2) @ Rx(k1) = [[c2c3, -c1s2c3+s1s3, s1s2c3+c1s3], [s2, c1c2, -s1c2], [-c2s3, c1s2s3+s1c3, -s1s2s3+c1c3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arcsin(rotation_matrices[:, 1, 0]) # Gimbal lock case (c2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 0]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r32 = rotation_matrices[gimbal_idx, 2, 1] r33 = rotation_matrices[gimbal_idx, 2, 2] angles_radians[gimbal_idx, 0] = np.arctan2(r32, r33) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r23 = rotation_matrices[idx, 1, 2] r22 = rotation_matrices[idx, 1, 1] r31 = rotation_matrices[idx, 2, 0] r11 = rotation_matrices[idx, 0, 0] angles_radians[idx, 0] = np.arctan2(-r23, r22) angles_radians[idx, 2] = np.arctan2(-r31, r11) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2yxz_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rz(k3) @ Rx(k2) @ Ry(k1) = [[-s1s2s3+c1c3, -c2s3, c1s2s3+s1c3], [s1s2c3+c1s3, c2c3, -c1s2c3+s1s3], [-s1c2, s2, c1c2]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arcsin(rotation_matrices[:, 2, 1]) # Gimbal lock case (c2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 1, 1]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r13 = rotation_matrices[gimbal_idx, 0, 2] r11 = rotation_matrices[gimbal_idx, 0, 0] angles_radians[gimbal_idx, 0] = np.arctan2(r13, r11) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r31 = rotation_matrices[idx, 2, 0] r33 = rotation_matrices[idx, 2, 2] r12 = rotation_matrices[idx, 0, 1] r22 = rotation_matrices[idx, 1, 1] angles_radians[idx, 0] = np.arctan2(-r31, r33) angles_radians[idx, 2] = np.arctan2(-r12, r22) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2zyx_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rx(k3) @ Ry(k2) @ Rz(k1) = [[c1c2, -s1c2, s2], [c1s2s3+s1c3, -s1s2s3+c1c3, -c2s3], [-c1s2c3+s1s3, s1s2c3+c1s3, c2c3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arcsin(rotation_matrices[:, 0, 2]) # Gimbal lock case (c2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 1, 1]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r21 = rotation_matrices[gimbal_idx, 1, 0] r22 = rotation_matrices[gimbal_idx, 1, 1] angles_radians[gimbal_idx, 0] = np.arctan2(r21, r22) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r12 = rotation_matrices[idx, 0, 1] r11 = rotation_matrices[idx, 0, 0] r23 = rotation_matrices[idx, 1, 2] r33 = rotation_matrices[idx, 2, 2] angles_radians[idx, 0] = np.arctan2(-r12, r11) angles_radians[idx, 2] = np.arctan2(-r23, r33) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2euler_extrinsic(rotation_matrices: np.ndarray, axes: str): matrix2euler_function = extrinsic_matrix2euler_functions[axes] return matrix2euler_function(rotation_matrices) def matrix2euler_intrinsic(rotation_matrices: np.ndarray, axes: str): """ It can be shown that a set of intrinsic rotations about axes x then y then z through angles α, β, γ is equivalent to a set of extrinsic rotations about axes z then y then x by angles γ, β, α. """ extrinsic_axes = axes[::-1] extrinsic_eulers = matrix2euler_extrinsic(rotation_matrices, extrinsic_axes) intrinsic_eulers = extrinsic_eulers[:, ::-1] return intrinsic_eulers def matrix2euler_right_handed(rotation_matrices: np.ndarray, axes: str, intrinsic: bool): if intrinsic: return matrix2euler_intrinsic(rotation_matrices, axes) else: return matrix2euler_extrinsic(rotation_matrices, axes) def matrix2euler(rotation_matrices: np.ndarray, axes: str, intrinsic: bool, right_handed_rotation: bool, ) -> np.ndarray: """ Derive a set of euler angles from a set of rotation matrices. Parameters ---------- rotation_matrices : (n, 3, 3) or (3, 3) array of float rotation matrices from which euler angles are derived axes : str valid sequence of three non-sequential axes from 'x', 'y' and 'z' e.g. 'zyz', 'zxz', 'xyz' intrinsic : bool True - Euler angles are for intrinsic rotations False - Euler angles are for extrinsic rotations right_handed_rotation : bool True - Euler angles are for right handed rotations False - Euler angles are for left handed rotations Returns ------- euler_angles : (n, 3) or (3,) array Euler angles derived from rotation matrices """ # Sanitise and check input rotation_matrices = np.asarray(rotation_matrices).reshape((-1, 3, 3)) formatted_axes = axes.strip().lower() if formatted_axes not in valid_axes: raise ValueError(f'Axes {axes} are not a valid set of euler angle axes') axes = formatted_axes # Calculate euler angles for right handed rotations euler_angles = matrix2euler_right_handed(rotation_matrices, axes, intrinsic) # If you want left handed rotations, invert the angles if not right_handed_rotation: euler_angles *= -1 return euler_angles.squeeze() extrinsic_matrix2euler_functions = { 'xyz': matrix2xyz_extrinsic, 'xyx': matrix2xyx_extrinsic, 'xzx': matrix2xzx_extrinsic, 'xzy': matrix2xzy_extrinsic, 'yxy': matrix2yxy_extrinsic, 'yxz': matrix2yxz_extrinsic, 'yzx': matrix2yzx_extrinsic, 'yzy': matrix2yzy_extrinsic, 'zxy': matrix2zxy_extrinsic, 'zxz': matrix2zxz_extrinsic, 'zyx': matrix2zyx_extrinsic, 'zyz': matrix2zyz_extrinsic, }
import numpy as np from .constants import valid_axes def matrix2xyx_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rx(k3) @ Ry(k2) @ Rx(k1) = [[c2, s1s2, c1s2], [s2s3, -s1c2s3+c1c3, -c1c2s3-s1c3], [-s2c3, s1c2c3+c1s3, c1c2c3-s1s3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arccos(rotation_matrices[:, 0, 0]) # Gimbal lock case (s2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 2]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r23 = rotation_matrices[gimbal_idx, 1, 2] r22 = rotation_matrices[gimbal_idx, 1, 1] angles_radians[gimbal_idx, 0] = np.arctan2(-r23, r22) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r12 = rotation_matrices[idx, 0, 1] r13 = rotation_matrices[idx, 0, 2] r21 = rotation_matrices[idx, 1, 0] r31 = rotation_matrices[idx, 2, 0] angles_radians[idx, 0] = np.arctan2(r12, r13) angles_radians[idx, 2] = np.arctan2(r21, -r31) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2yzy_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Ry(k3) @ Rz(k2) @ Ry(k1) = [[c1c2c3-s1s3, -s2c3, s1c2c3+c1c3], [c1s2, c2, s1s2], [-c1c2s3, s2s3, -s1c2s3+c1c3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arccos(rotation_matrices[:, 1, 1]) # Gimbal lock case (s2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 1, 0]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r31 = rotation_matrices[gimbal_idx, 2, 0] r33 = rotation_matrices[gimbal_idx, 2, 2] angles_radians[gimbal_idx, 0] = np.arctan2(-r31, r33) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r23 = rotation_matrices[idx, 1, 2] r21 = rotation_matrices[idx, 1, 0] r32 = rotation_matrices[idx, 2, 1] r12 = rotation_matrices[idx, 0, 1] angles_radians[idx, 0] = np.arctan2(r23, r21) angles_radians[idx, 2] = np.arctan2(r32, -r12) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2zxz_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rz(k3) @ Rx(k2) @ Rz(k1) = [[-s1c2s3+c1c3, -c1c2s3-s1c3, s2s3], [s1c2c3+s1s3, c1c2c3-s1s3, -s2c3], [s1s2, c1s2, c2]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles[:, 1] = np.arccos(rotation_matrices[:, 2, 2]) # Gimbal lock case (s2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 2]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r12 = rotation_matrices[gimbal_idx, 0, 1] r11 = rotation_matrices[gimbal_idx, 0, 0] angles[gimbal_idx, 0] = np.arctan2(-r12, r11) angles[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r31 = rotation_matrices[idx, 2, 0] r32 = rotation_matrices[idx, 2, 1] r13 = rotation_matrices[idx, 0, 2] r23 = rotation_matrices[idx, 1, 2] angles[idx, 0] = np.arctan2(r31, r32) angles[idx, 2] = np.arctan2(r13, -r23) # convert to degrees euler_angles = np.rad2deg(angles) return euler_angles def matrix2xzx_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rx(k3) @ Rz(k2) @ Rx(k1) = [[c2, -c1s2, s1s2], [s2c3, c1c2c3-s3, -s1c2c3-c1s3], [s2s3, c1c2s3+s1c3, -s1c2s3+c1c3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arccos(rotation_matrices[:, 0, 0]) # Gimbal lock case (s2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 2]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r32 = rotation_matrices[gimbal_idx, 2, 1] r33 = rotation_matrices[gimbal_idx, 2, 2] angles_radians[gimbal_idx, 0] = np.arctan2(r32, r33) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r13 = rotation_matrices[idx, 0, 2] r12 = rotation_matrices[idx, 0, 1] r31 = rotation_matrices[idx, 2, 0] r21 = rotation_matrices[idx, 1, 0] angles_radians[idx, 0] = np.arctan2(r13, -r12) angles_radians[idx, 2] = np.arctan2(r31, r21) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2yxy_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Ry(k3) @ Rx(k2) @ Ry(k1) = [[-s1c2s3+c1c3, s2s3, c1c2s3+s1c3], [s1s2, c2, -c1s2], [-s1c2c3-c1s3, s2c3, c1c2c3-s1s3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arccos(rotation_matrices[:, 1, 1]) # Gimbal lock case (s2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 1]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r13 = rotation_matrices[gimbal_idx, 0, 2] r11 = rotation_matrices[gimbal_idx, 0, 0] angles_radians[gimbal_idx, 0] = np.arctan2(r13, r11) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r21 = rotation_matrices[idx, 1, 0] r23 = rotation_matrices[idx, 1, 2] r12 = rotation_matrices[idx, 0, 1] r32 = rotation_matrices[idx, 2, 1] angles_radians[idx, 0] = np.arctan2(r21, -r23) angles_radians[idx, 2] = np.arctan2(r12, r32) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2zyz_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rz(k3) @ Ry(k2) @ Rz(k1) = [[c1c2c3-s1s3, -s1c2c3-c1s3, s2c3], [c1c2s3+s1c3, -s1c2s3+c1c3, s2s3], [-c1s2, s1s2, c2]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arccos(rotation_matrices[:, 2, 2]) # Gimbal lock case (s2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 2]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r21 = rotation_matrices[gimbal_idx, 1, 0] r22 = rotation_matrices[gimbal_idx, 1, 1] angles_radians[gimbal_idx, 0] = np.arctan2(r21, r22) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r32 = rotation_matrices[idx, 2, 1] r31 = rotation_matrices[idx, 2, 0] r23 = rotation_matrices[idx, 1, 2] r13 = rotation_matrices[idx, 0, 2] angles_radians[idx, 0] = np.arctan2(r32, -r31) angles_radians[idx, 2] = np.arctan2(r23, r13) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2xyz_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rz(k3) @ Ry(k2) @ Rx(k1) = [[c2c3, s1s2c3-c1s3, c1s2c3+s1s3], [c2s3, s1s2s3+c1c3, c1s2s3-s1c3], [-s2, s1c2, c1c2]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = -np.arcsin(rotation_matrices[:, 2, 0]) # Gimbal lock case (c2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 0]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r23 = rotation_matrices[gimbal_idx, 1, 2] r22 = rotation_matrices[gimbal_idx, 1, 1] angles_radians[gimbal_idx, 0] = np.arctan2(-r23, r22) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r32 = rotation_matrices[idx, 2, 1] r33 = rotation_matrices[idx, 2, 2] r21 = rotation_matrices[idx, 1, 0] r11 = rotation_matrices[idx, 0, 0] angles_radians[idx, 0] = np.arctan2(r32, r33) angles_radians[idx, 2] = np.arctan2(r21, r11) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2yzx_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rx(k3) @ Rz(k2) @ Ry(k1) = [[c1c2, -s2, s1c2], [c1s2c3+s1s3, c2c3, s1s2c3-c1s3], [c1s2s3-s1c3, c2s3, s1s2s3+c1c3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = -np.arcsin(rotation_matrices[:, 0, 1]) # Gimbal lock case (c2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 0]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r31 = rotation_matrices[gimbal_idx, 2, 0] r33 = rotation_matrices[gimbal_idx, 2, 2] angles_radians[gimbal_idx, 0] = np.arctan2(-r31, r33) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r13 = rotation_matrices[idx, 0, 2] r11 = rotation_matrices[idx, 0, 0] r32 = rotation_matrices[idx, 2, 1] r22 = rotation_matrices[idx, 1, 1] angles_radians[idx, 0] = np.arctan2(r13, r11) angles_radians[idx, 2] = np.arctan2(r32, r22) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2zxy_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Ry(k3) @ Rx(k2) @ Rz(k1) = [[s1s2s3+c1c3, c1s2s3-s1c3, c2s3], [s1c2, c1c2, -s2], [s1s2c3-c1s3, c1s2c3+s1s3, c2c3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = -np.arcsin(rotation_matrices[:, 1, 2]) # Gimbal lock case (c2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 1, 0]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r12 = rotation_matrices[gimbal_idx, 0, 1] r11 = rotation_matrices[gimbal_idx, 0, 0] angles_radians[gimbal_idx, 0] = np.arctan2(-r12, r11) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r21 = rotation_matrices[idx, 1, 0] r22 = rotation_matrices[idx, 1, 1] r13 = rotation_matrices[idx, 0, 2] r33 = rotation_matrices[idx, 2, 2] angles_radians[idx, 0] = np.arctan2(r21, r22) angles_radians[idx, 2] = np.arctan2(r13, r33) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2xzy_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Ry(k3) @ Rz(k2) @ Rx(k1) = [[c2c3, -c1s2c3+s1s3, s1s2c3+c1s3], [s2, c1c2, -s1c2], [-c2s3, c1s2s3+s1c3, -s1s2s3+c1c3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arcsin(rotation_matrices[:, 1, 0]) # Gimbal lock case (c2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 0, 0]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r32 = rotation_matrices[gimbal_idx, 2, 1] r33 = rotation_matrices[gimbal_idx, 2, 2] angles_radians[gimbal_idx, 0] = np.arctan2(r32, r33) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r23 = rotation_matrices[idx, 1, 2] r22 = rotation_matrices[idx, 1, 1] r31 = rotation_matrices[idx, 2, 0] r11 = rotation_matrices[idx, 0, 0] angles_radians[idx, 0] = np.arctan2(-r23, r22) angles_radians[idx, 2] = np.arctan2(-r31, r11) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2yxz_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rz(k3) @ Rx(k2) @ Ry(k1) = [[-s1s2s3+c1c3, -c2s3, c1s2s3+s1c3], [s1s2c3+c1s3, c2c3, -c1s2c3+s1s3], [-s1c2, s2, c1c2]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arcsin(rotation_matrices[:, 2, 1]) # Gimbal lock case (c2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 1, 1]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r13 = rotation_matrices[gimbal_idx, 0, 2] r11 = rotation_matrices[gimbal_idx, 0, 0] angles_radians[gimbal_idx, 0] = np.arctan2(r13, r11) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r31 = rotation_matrices[idx, 2, 0] r33 = rotation_matrices[idx, 2, 2] r12 = rotation_matrices[idx, 0, 1] r22 = rotation_matrices[idx, 1, 1] angles_radians[idx, 0] = np.arctan2(-r31, r33) angles_radians[idx, 2] = np.arctan2(-r12, r22) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2zyx_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rx(k3) @ Ry(k2) @ Rz(k1) = [[c1c2, -s1c2, s2], [c1s2s3+s1c3, -s1s2s3+c1c3, -c2s3], [-c1s2c3+s1s3, s1s2c3+c1s3, c2c3]] """ rotation_matrices = rotation_matrices.reshape((-1, 3, 3)) angles_radians = np.zeros((rotation_matrices.shape[0], 3)) # Angle 2 can be taken directly from matrices angles_radians[:, 1] = np.arcsin(rotation_matrices[:, 0, 2]) # Gimbal lock case (c2 = 0) tolerance = 1e-4 # Find indices where this is the case gimbal_idx = np.abs(rotation_matrices[:, 1, 1]) < tolerance # Calculate angle 1 and set angle 3 = 0 for those indices r21 = rotation_matrices[gimbal_idx, 1, 0] r22 = rotation_matrices[gimbal_idx, 1, 1] angles_radians[gimbal_idx, 0] = np.arctan2(r21, r22) angles_radians[gimbal_idx, 2] = 0 # Normal case (s2 > 0) idx = np.invert(gimbal_idx) r12 = rotation_matrices[idx, 0, 1] r11 = rotation_matrices[idx, 0, 0] r23 = rotation_matrices[idx, 1, 2] r33 = rotation_matrices[idx, 2, 2] angles_radians[idx, 0] = np.arctan2(-r12, r11) angles_radians[idx, 2] = np.arctan2(-r23, r33) # convert to degrees euler_angles = np.rad2deg(angles_radians) return euler_angles def matrix2euler_extrinsic(rotation_matrices: np.ndarray, axes: str): matrix2euler_function = extrinsic_matrix2euler_functions[axes] return matrix2euler_function(rotation_matrices) def matrix2euler_intrinsic(rotation_matrices: np.ndarray, axes: str): """ It can be shown that a set of intrinsic rotations about axes x then y then z through angles α, β, γ is equivalent to a set of extrinsic rotations about axes z then y then x by angles γ, β, α. """ extrinsic_axes = axes[::-1] extrinsic_eulers = matrix2euler_extrinsic(rotation_matrices, extrinsic_axes) intrinsic_eulers = extrinsic_eulers[:, ::-1] return intrinsic_eulers def matrix2euler_right_handed(rotation_matrices: np.ndarray, axes: str, intrinsic: bool): if intrinsic: return matrix2euler_intrinsic(rotation_matrices, axes) else: return matrix2euler_extrinsic(rotation_matrices, axes) def matrix2euler(rotation_matrices: np.ndarray, axes: str, intrinsic: bool, right_handed_rotation: bool, ) -> np.ndarray: """ Derive a set of euler angles from a set of rotation matrices. Parameters ---------- rotation_matrices : (n, 3, 3) or (3, 3) array of float rotation matrices from which euler angles are derived axes : str valid sequence of three non-sequential axes from 'x', 'y' and 'z' e.g. 'zyz', 'zxz', 'xyz' intrinsic : bool True - Euler angles are for intrinsic rotations False - Euler angles are for extrinsic rotations right_handed_rotation : bool True - Euler angles are for right handed rotations False - Euler angles are for left handed rotations Returns ------- euler_angles : (n, 3) or (3,) array Euler angles derived from rotation matrices """ # Sanitise and check input rotation_matrices = np.asarray(rotation_matrices).reshape((-1, 3, 3)) formatted_axes = axes.strip().lower() if formatted_axes not in valid_axes: raise ValueError(f'Axes {axes} are not a valid set of euler angle axes') axes = formatted_axes # Calculate euler angles for right handed rotations euler_angles = matrix2euler_right_handed(rotation_matrices, axes, intrinsic) # If you want left handed rotations, invert the angles if not right_handed_rotation: euler_angles *= -1 return euler_angles.squeeze() extrinsic_matrix2euler_functions = { 'xyz': matrix2xyz_extrinsic, 'xyx': matrix2xyx_extrinsic, 'xzx': matrix2xzx_extrinsic, 'xzy': matrix2xzy_extrinsic, 'yxy': matrix2yxy_extrinsic, 'yxz': matrix2yxz_extrinsic, 'yzx': matrix2yzx_extrinsic, 'yzy': matrix2yzy_extrinsic, 'zxy': matrix2zxy_extrinsic, 'zxz': matrix2zxz_extrinsic, 'zyx': matrix2zyx_extrinsic, 'zyz': matrix2zyz_extrinsic, }
en
0.730567
Rx(k3) @ Ry(k2) @ Rx(k1) = [[c2, s1s2, c1s2], [s2s3, -s1c2s3+c1c3, -c1c2s3-s1c3], [-s2c3, s1c2c3+c1s3, c1c2c3-s1s3]] # Angle 2 can be taken directly from matrices # Gimbal lock case (s2 = 0) # Find indices where this is the case # Calculate angle 1 and set angle 3 = 0 for those indices # Normal case (s2 > 0) # convert to degrees Ry(k3) @ Rz(k2) @ Ry(k1) = [[c1c2c3-s1s3, -s2c3, s1c2c3+c1c3], [c1s2, c2, s1s2], [-c1c2s3, s2s3, -s1c2s3+c1c3]] # Angle 2 can be taken directly from matrices # Gimbal lock case (s2 = 0) # Find indices where this is the case # Calculate angle 1 and set angle 3 = 0 for those indices # Normal case (s2 > 0) # convert to degrees Rz(k3) @ Rx(k2) @ Rz(k1) = [[-s1c2s3+c1c3, -c1c2s3-s1c3, s2s3], [s1c2c3+s1s3, c1c2c3-s1s3, -s2c3], [s1s2, c1s2, c2]] # Angle 2 can be taken directly from matrices # Gimbal lock case (s2 = 0) # Find indices where this is the case # Calculate angle 1 and set angle 3 = 0 for those indices # Normal case (s2 > 0) # convert to degrees Rx(k3) @ Rz(k2) @ Rx(k1) = [[c2, -c1s2, s1s2], [s2c3, c1c2c3-s3, -s1c2c3-c1s3], [s2s3, c1c2s3+s1c3, -s1c2s3+c1c3]] # Angle 2 can be taken directly from matrices # Gimbal lock case (s2 = 0) # Find indices where this is the case # Calculate angle 1 and set angle 3 = 0 for those indices # Normal case (s2 > 0) # convert to degrees Ry(k3) @ Rx(k2) @ Ry(k1) = [[-s1c2s3+c1c3, s2s3, c1c2s3+s1c3], [s1s2, c2, -c1s2], [-s1c2c3-c1s3, s2c3, c1c2c3-s1s3]] # Angle 2 can be taken directly from matrices # Gimbal lock case (s2 = 0) # Find indices where this is the case # Calculate angle 1 and set angle 3 = 0 for those indices # Normal case (s2 > 0) # convert to degrees Rz(k3) @ Ry(k2) @ Rz(k1) = [[c1c2c3-s1s3, -s1c2c3-c1s3, s2c3], [c1c2s3+s1c3, -s1c2s3+c1c3, s2s3], [-c1s2, s1s2, c2]] # Angle 2 can be taken directly from matrices # Gimbal lock case (s2 = 0) # Find indices where this is the case # Calculate angle 1 and set angle 3 = 0 for those indices # Normal case (s2 > 0) # convert to degrees Rz(k3) @ Ry(k2) @ Rx(k1) = [[c2c3, s1s2c3-c1s3, c1s2c3+s1s3], [c2s3, s1s2s3+c1c3, c1s2s3-s1c3], [-s2, s1c2, c1c2]] # Angle 2 can be taken directly from matrices # Gimbal lock case (c2 = 0) # Find indices where this is the case # Calculate angle 1 and set angle 3 = 0 for those indices # Normal case (s2 > 0) # convert to degrees Rx(k3) @ Rz(k2) @ Ry(k1) = [[c1c2, -s2, s1c2], [c1s2c3+s1s3, c2c3, s1s2c3-c1s3], [c1s2s3-s1c3, c2s3, s1s2s3+c1c3]] # Angle 2 can be taken directly from matrices # Gimbal lock case (c2 = 0) # Find indices where this is the case # Calculate angle 1 and set angle 3 = 0 for those indices # Normal case (s2 > 0) # convert to degrees Ry(k3) @ Rx(k2) @ Rz(k1) = [[s1s2s3+c1c3, c1s2s3-s1c3, c2s3], [s1c2, c1c2, -s2], [s1s2c3-c1s3, c1s2c3+s1s3, c2c3]] # Angle 2 can be taken directly from matrices # Gimbal lock case (c2 = 0) # Find indices where this is the case # Calculate angle 1 and set angle 3 = 0 for those indices # Normal case (s2 > 0) # convert to degrees Ry(k3) @ Rz(k2) @ Rx(k1) = [[c2c3, -c1s2c3+s1s3, s1s2c3+c1s3], [s2, c1c2, -s1c2], [-c2s3, c1s2s3+s1c3, -s1s2s3+c1c3]] # Angle 2 can be taken directly from matrices # Gimbal lock case (c2 = 0) # Find indices where this is the case # Calculate angle 1 and set angle 3 = 0 for those indices # Normal case (s2 > 0) # convert to degrees Rz(k3) @ Rx(k2) @ Ry(k1) = [[-s1s2s3+c1c3, -c2s3, c1s2s3+s1c3], [s1s2c3+c1s3, c2c3, -c1s2c3+s1s3], [-s1c2, s2, c1c2]] # Angle 2 can be taken directly from matrices # Gimbal lock case (c2 = 0) # Find indices where this is the case # Calculate angle 1 and set angle 3 = 0 for those indices # Normal case (s2 > 0) # convert to degrees Rx(k3) @ Ry(k2) @ Rz(k1) = [[c1c2, -s1c2, s2], [c1s2s3+s1c3, -s1s2s3+c1c3, -c2s3], [-c1s2c3+s1s3, s1s2c3+c1s3, c2c3]] # Angle 2 can be taken directly from matrices # Gimbal lock case (c2 = 0) # Find indices where this is the case # Calculate angle 1 and set angle 3 = 0 for those indices # Normal case (s2 > 0) # convert to degrees It can be shown that a set of intrinsic rotations about axes x then y then z through angles α, β, γ is equivalent to a set of extrinsic rotations about axes z then y then x by angles γ, β, α. Derive a set of euler angles from a set of rotation matrices. Parameters ---------- rotation_matrices : (n, 3, 3) or (3, 3) array of float rotation matrices from which euler angles are derived axes : str valid sequence of three non-sequential axes from 'x', 'y' and 'z' e.g. 'zyz', 'zxz', 'xyz' intrinsic : bool True - Euler angles are for intrinsic rotations False - Euler angles are for extrinsic rotations right_handed_rotation : bool True - Euler angles are for right handed rotations False - Euler angles are for left handed rotations Returns ------- euler_angles : (n, 3) or (3,) array Euler angles derived from rotation matrices # Sanitise and check input # Calculate euler angles for right handed rotations # If you want left handed rotations, invert the angles
2.610132
3
polecat/utils/singledict.py
furious-luke/polecat
4
6628258
<reponame>furious-luke/polecat from collections import OrderedDict class SingleDict(OrderedDict): def __setitem__(self, key, value): if key in self: raise KeyError(f'Duplicate key "{key}"') super().__setitem__(key, value)
from collections import OrderedDict class SingleDict(OrderedDict): def __setitem__(self, key, value): if key in self: raise KeyError(f'Duplicate key "{key}"') super().__setitem__(key, value)
none
1
3.11196
3
code/fig_6b_example_waveform_shape.py
ryanhammonds/ieeg-spatial-filters-ssd
14
6628259
""" Shows example of close-by rhythms with different waveform. """ import mne import numpy as np import matplotlib.pyplot as plt import helper import ssd import matplotlib.gridspec as gridspec import pandas as pd import matplotlib.image as mpimg plt.ion() # -- load continuous data participant_id = "jc_fixation_pwrlaw" raw = mne.io.read_raw_fif("../working/%s_raw.fif" % participant_id) raw.load_data() raw.pick_types(ecog=True) peak = 9.45 bin_width = 1.75 filters, patterns = ssd.run_ssd(raw, peak, bin_width) nr_components = 2 raw_ssd = ssd.apply_filters(raw, filters[:, :nr_components]) raw_ssd.filter(2, None) raw.filter(2, None) # -- pick the channels contributing most to the spatial patterns for comparison picks = [np.argmax(np.abs(patterns[:, 0])), np.argmax(np.abs(patterns[:, 1]))] raw2 = raw.copy().pick(picks) raw_ssd2 = raw_ssd.copy().pick_channels(raw_ssd.ch_names[:2]) raw_ssd2.add_channels([raw2]) raw2 = raw_ssd2.copy() # -- compute spectrum psd, freq = mne.time_frequency.psd_welch(raw2, fmin=1, fmax=45, n_fft=3000) fig = plt.figure() gs = gridspec.GridSpec( 2, 4, width_ratios=[3, 1, 0.9, 0.75], ) # -- plot time domain ax1 = plt.subplot(gs[0, 0]) colors = ["#CC2B1C", "#3C2C71", "k", "k"] raw3 = raw2.copy() raw3.filter(1, None) tmin = 37.25 tmax = tmin + 2.5 raw3.crop(tmin, tmax) labels = [ "comp.1", "comp.2", "e1", "e2", ] signs = [1, 1, 1, 1, 1] for i in range(len(raw3.ch_names)): signal = signs[i] * raw3._data[i] signal = signal / np.ptp(signal) ax1.plot(raw3.times, signal - 1.05 * i, color=colors[i], lw=1) ax1.text(-0.05, -1 * i, labels[i], color=colors[i], ha="right", va="center") ax1.set(xlim=(0, 1.75), xlabel="time [s]", yticks=[], xticks=[0, 1, 2]) # -- plot spectrum ax1 = plt.subplot(gs[0, 1:3]) for i in range(len(raw3.ch_names)): ax1.semilogy(freq, psd[i].T, color=colors[i], lw=1) ax1.set( xlim=(1, 45), xlabel="frequency [Hz]", ) ax1.axvspan( peak - bin_width, peak + bin_width, color="gray", alpha=0.25, zorder=-3 ) # -- plot peak frequency markers ax1.axvline(peak, color="tab:green", lw=1, zorder=-2) ax1.axvline(2 * peak, color="tab:green", lw=1, zorder=-2) ax1.axvline(3 * peak, color="tab:green", lw=1, zorder=-2) # -- plot participant summary ax1 = plt.subplot(gs[1, 0]) df = pd.read_csv("../csv/selected_datasets.csv") df = df[df.is_rest] nr_participants = len(df) results_folder = "../results/bursts/" counter = 0 nr_bursts = [] asymmetry = [] for i_sub, (participant, exp) in enumerate(zip(df.participant, df.experiment)): participant_id = "%s_%s" % (participant, exp) peaks = helper.get_participant_peaks(participant, exp) for peak1 in peaks: df_file_name = "%s/bursts_%s_peak_%s.csv" % ( results_folder, participant_id, peak1, ) df = pd.read_csv(df_file_name) df = df.set_index("feature") if df.value["nr_bursts"] == 0: continue df = df.T frequency = 1000 / df.period if np.any(frequency < 5): continue ax1.plot( frequency, 2 * np.abs(df.time_ptsym - 0.5), ".", markeredgecolor="w", markerfacecolor="k", markersize=12, ) nr_bursts.append(df["nr_bursts"].to_list()) asymmetry.append(2 * np.abs(df.time_ptsym.to_list()[0] - 0.5)) counter += 1 ax1.set( xlabel="peak frequency [Hz]", ylabel="peak-trough asymmetry", xlim=(4.5, 20.5), xticks=(range(5, 21, 5)), ) # -- asymmetries across 3d brain ax1 = plt.subplot(gs[1, 1:]) plot_filename = "../figures/3dbrain_asymmetry.png" img = mpimg.imread(plot_filename) ax1.imshow(img) ax1.set_xlim(25, 1000) ax1.set_ylim(725, 0) ax1.set(yticks=[], xticks=[]) ax1.axis("off") peaks_n = np.arange(0, 0.21, 0.01) N = len(peaks_n) cmap = [plt.cm.plasma(i) for i in np.linspace(0.2, 1, N)] fig2 = plt.figure() sc = plt.scatter( range(N), range(N), c=peaks_n, s=5, vmin=0, vmax=0.2, cmap=plt.cm.plasma ) plt.show() fig2.show() cb = plt.colorbar( sc, ax=ax1, orientation="horizontal", fraction=0.05, shrink=0.8, pad=0.0 ) cb.set_label("peak-trough asymmetry") plt.close(fig2) # -- plot patterns topo_size = 0.18 for i in range(2): ax = plt.Axes(fig, rect=[0.8, 0.77 - i * 0.2, topo_size, topo_size]) ax1 = fig.add_axes(ax) helper.make_topoplot( signs[i] * patterns[:, i], raw.info, ax1, picks=[picks[i]], pick_color=["g"], cmap="RdBu_r", hemisphere="left", plot_head=False, ) fig.set_size_inches(7.5, 6) fig.savefig("../figures/fig6_example_waveform.pdf", dpi=300) fig.show()
""" Shows example of close-by rhythms with different waveform. """ import mne import numpy as np import matplotlib.pyplot as plt import helper import ssd import matplotlib.gridspec as gridspec import pandas as pd import matplotlib.image as mpimg plt.ion() # -- load continuous data participant_id = "jc_fixation_pwrlaw" raw = mne.io.read_raw_fif("../working/%s_raw.fif" % participant_id) raw.load_data() raw.pick_types(ecog=True) peak = 9.45 bin_width = 1.75 filters, patterns = ssd.run_ssd(raw, peak, bin_width) nr_components = 2 raw_ssd = ssd.apply_filters(raw, filters[:, :nr_components]) raw_ssd.filter(2, None) raw.filter(2, None) # -- pick the channels contributing most to the spatial patterns for comparison picks = [np.argmax(np.abs(patterns[:, 0])), np.argmax(np.abs(patterns[:, 1]))] raw2 = raw.copy().pick(picks) raw_ssd2 = raw_ssd.copy().pick_channels(raw_ssd.ch_names[:2]) raw_ssd2.add_channels([raw2]) raw2 = raw_ssd2.copy() # -- compute spectrum psd, freq = mne.time_frequency.psd_welch(raw2, fmin=1, fmax=45, n_fft=3000) fig = plt.figure() gs = gridspec.GridSpec( 2, 4, width_ratios=[3, 1, 0.9, 0.75], ) # -- plot time domain ax1 = plt.subplot(gs[0, 0]) colors = ["#CC2B1C", "#3C2C71", "k", "k"] raw3 = raw2.copy() raw3.filter(1, None) tmin = 37.25 tmax = tmin + 2.5 raw3.crop(tmin, tmax) labels = [ "comp.1", "comp.2", "e1", "e2", ] signs = [1, 1, 1, 1, 1] for i in range(len(raw3.ch_names)): signal = signs[i] * raw3._data[i] signal = signal / np.ptp(signal) ax1.plot(raw3.times, signal - 1.05 * i, color=colors[i], lw=1) ax1.text(-0.05, -1 * i, labels[i], color=colors[i], ha="right", va="center") ax1.set(xlim=(0, 1.75), xlabel="time [s]", yticks=[], xticks=[0, 1, 2]) # -- plot spectrum ax1 = plt.subplot(gs[0, 1:3]) for i in range(len(raw3.ch_names)): ax1.semilogy(freq, psd[i].T, color=colors[i], lw=1) ax1.set( xlim=(1, 45), xlabel="frequency [Hz]", ) ax1.axvspan( peak - bin_width, peak + bin_width, color="gray", alpha=0.25, zorder=-3 ) # -- plot peak frequency markers ax1.axvline(peak, color="tab:green", lw=1, zorder=-2) ax1.axvline(2 * peak, color="tab:green", lw=1, zorder=-2) ax1.axvline(3 * peak, color="tab:green", lw=1, zorder=-2) # -- plot participant summary ax1 = plt.subplot(gs[1, 0]) df = pd.read_csv("../csv/selected_datasets.csv") df = df[df.is_rest] nr_participants = len(df) results_folder = "../results/bursts/" counter = 0 nr_bursts = [] asymmetry = [] for i_sub, (participant, exp) in enumerate(zip(df.participant, df.experiment)): participant_id = "%s_%s" % (participant, exp) peaks = helper.get_participant_peaks(participant, exp) for peak1 in peaks: df_file_name = "%s/bursts_%s_peak_%s.csv" % ( results_folder, participant_id, peak1, ) df = pd.read_csv(df_file_name) df = df.set_index("feature") if df.value["nr_bursts"] == 0: continue df = df.T frequency = 1000 / df.period if np.any(frequency < 5): continue ax1.plot( frequency, 2 * np.abs(df.time_ptsym - 0.5), ".", markeredgecolor="w", markerfacecolor="k", markersize=12, ) nr_bursts.append(df["nr_bursts"].to_list()) asymmetry.append(2 * np.abs(df.time_ptsym.to_list()[0] - 0.5)) counter += 1 ax1.set( xlabel="peak frequency [Hz]", ylabel="peak-trough asymmetry", xlim=(4.5, 20.5), xticks=(range(5, 21, 5)), ) # -- asymmetries across 3d brain ax1 = plt.subplot(gs[1, 1:]) plot_filename = "../figures/3dbrain_asymmetry.png" img = mpimg.imread(plot_filename) ax1.imshow(img) ax1.set_xlim(25, 1000) ax1.set_ylim(725, 0) ax1.set(yticks=[], xticks=[]) ax1.axis("off") peaks_n = np.arange(0, 0.21, 0.01) N = len(peaks_n) cmap = [plt.cm.plasma(i) for i in np.linspace(0.2, 1, N)] fig2 = plt.figure() sc = plt.scatter( range(N), range(N), c=peaks_n, s=5, vmin=0, vmax=0.2, cmap=plt.cm.plasma ) plt.show() fig2.show() cb = plt.colorbar( sc, ax=ax1, orientation="horizontal", fraction=0.05, shrink=0.8, pad=0.0 ) cb.set_label("peak-trough asymmetry") plt.close(fig2) # -- plot patterns topo_size = 0.18 for i in range(2): ax = plt.Axes(fig, rect=[0.8, 0.77 - i * 0.2, topo_size, topo_size]) ax1 = fig.add_axes(ax) helper.make_topoplot( signs[i] * patterns[:, i], raw.info, ax1, picks=[picks[i]], pick_color=["g"], cmap="RdBu_r", hemisphere="left", plot_head=False, ) fig.set_size_inches(7.5, 6) fig.savefig("../figures/fig6_example_waveform.pdf", dpi=300) fig.show()
en
0.722796
Shows example of close-by rhythms with different waveform. # -- load continuous data # -- pick the channels contributing most to the spatial patterns for comparison # -- compute spectrum # -- plot time domain # -- plot spectrum # -- plot peak frequency markers # -- plot participant summary # -- asymmetries across 3d brain # -- plot patterns
2.229877
2
pypelines/tasks/task_script.py
Yash-Amin/pypelines
0
6628260
"""Task to run scripts.""" import re import os import stat import tempfile import subprocess from typing import Any, Dict, List from pypelines.utils import string_to_bool from pypelines.config import SCRIPTS_DIRECTORY from pypelines.pipeline_options import PipelineOptions from pypelines.task import PipelineTask, TaskInputSchema # Task input keys INPUT_IGNORE_SCRIPT_ERRORS = "ignore-script-errors" INPUT_SHOW_OUTPUT = "show-output" INPUT_SCRIPT = "script" INPUT_ARGUMENTS = "arguments" INPUT_ENVIRONMENT_VARIABLES = "environment-variables" INPUT_USE_SNAPSHOTS = "use-snapshots" class ScriptTask(PipelineTask): """Script task.""" task_type: str = "script" task_input_schema: List[TaskInputSchema] = [ TaskInputSchema( name=INPUT_IGNORE_SCRIPT_ERRORS, description="If true, then pipeline will not fail if script terminates with non-zero exit code", value_type=string_to_bool, default_value=False, ), TaskInputSchema( name=INPUT_SHOW_OUTPUT, description="If true, then script's output will be shown in the terminal", value_type=string_to_bool, default_value=True, ), TaskInputSchema( name=INPUT_SCRIPT, description="Script that you want to run.", allow_parameters=False, ), TaskInputSchema( name=INPUT_ARGUMENTS, description="List of arguments.", default_value=[], ), TaskInputSchema( name=INPUT_ENVIRONMENT_VARIABLES, description="Environment variables for script", default_value={}, ), TaskInputSchema( name=INPUT_USE_SNAPSHOTS, description="Use snapshots", value_type=string_to_bool, default_value=True, ), ] def __init__( self, name: str, task_input_values: Dict[str, Any], pipeline_parameters: Dict[str, Any], pipeline_options: PipelineOptions, extra_parameters: Dict[str, Any], ) -> None: super().__init__( name, task_input_values, pipeline_parameters, pipeline_options, extra_parameters, ) self.script = "" self.show_output = True self.use_snapshots = True self.ignore_script_errors = False self.arguments = [] self.script_environment_variables: Dict[str, str] = {} def validate_inputs(self): """Validate inputs""" pass def set_task_inputs(self) -> None: """Sets task inputs""" inputs = super().get_parsed_inputs() task_input_dict = {key: value for key, value in inputs.items()} self.script = task_input_dict[INPUT_SCRIPT] self.show_output = task_input_dict[INPUT_SHOW_OUTPUT] self.use_snapshots = task_input_dict[INPUT_USE_SNAPSHOTS] self.ignore_script_errors = task_input_dict[INPUT_IGNORE_SCRIPT_ERRORS] self.arguments = [str(arg) for arg in task_input_dict[INPUT_ARGUMENTS]] self.script_environment_variables = task_input_dict[INPUT_ENVIRONMENT_VARIABLES] if self.use_snapshots is None: # if use_snapshots is not set, then set it to pipeline_options.use_snapshots self.use_snapshots = self.pipeline_options.use_snapshots else: # use_snapshot will be true only if it is set to true and # pipeline-options.use_snapshots is true as well self.use_snapshots = ( self.pipeline_options.use_snapshots and self.use_snapshots ) def run( self, ) -> None: """Run script task.""" self.set_task_inputs() # TODO: snapshot check fd, script_path = tempfile.mkstemp(dir=SCRIPTS_DIRECTORY) # Gives RWX permission for the owner os.chmod(script_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) # Write script to tmp file with os.fdopen(fd, "w") as tmp_file: tmp_file.write(self.script) # Subprocess options subprocess_options = ( dict() if self.show_output else dict(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) ) # Subprocess environment variables # It will contain OS environment variables, pipeline config and extra parameters subprocess_environment = { **os.environ.copy(), **{ # Replaces special chars from key f"pipeline_{re.sub(r'[^a-zA-Z0-9_]', '_', key)}": value for key, value in self.pipeline_options.get_config_dict().items() }, **self._extra_parameters, **self.script_environment_variables, } # Runs the script process = subprocess.run( [script_path] + self.arguments, env={key: str(value) for key, value in subprocess_environment.items()}, **subprocess_options ) # Delete script os.unlink(script_path) if not self.ignore_script_errors and process.returncode != 0: raise Exception( "Script terminated with {} exit code".format(process.returncode) ) # TODO: Save snapshot
"""Task to run scripts.""" import re import os import stat import tempfile import subprocess from typing import Any, Dict, List from pypelines.utils import string_to_bool from pypelines.config import SCRIPTS_DIRECTORY from pypelines.pipeline_options import PipelineOptions from pypelines.task import PipelineTask, TaskInputSchema # Task input keys INPUT_IGNORE_SCRIPT_ERRORS = "ignore-script-errors" INPUT_SHOW_OUTPUT = "show-output" INPUT_SCRIPT = "script" INPUT_ARGUMENTS = "arguments" INPUT_ENVIRONMENT_VARIABLES = "environment-variables" INPUT_USE_SNAPSHOTS = "use-snapshots" class ScriptTask(PipelineTask): """Script task.""" task_type: str = "script" task_input_schema: List[TaskInputSchema] = [ TaskInputSchema( name=INPUT_IGNORE_SCRIPT_ERRORS, description="If true, then pipeline will not fail if script terminates with non-zero exit code", value_type=string_to_bool, default_value=False, ), TaskInputSchema( name=INPUT_SHOW_OUTPUT, description="If true, then script's output will be shown in the terminal", value_type=string_to_bool, default_value=True, ), TaskInputSchema( name=INPUT_SCRIPT, description="Script that you want to run.", allow_parameters=False, ), TaskInputSchema( name=INPUT_ARGUMENTS, description="List of arguments.", default_value=[], ), TaskInputSchema( name=INPUT_ENVIRONMENT_VARIABLES, description="Environment variables for script", default_value={}, ), TaskInputSchema( name=INPUT_USE_SNAPSHOTS, description="Use snapshots", value_type=string_to_bool, default_value=True, ), ] def __init__( self, name: str, task_input_values: Dict[str, Any], pipeline_parameters: Dict[str, Any], pipeline_options: PipelineOptions, extra_parameters: Dict[str, Any], ) -> None: super().__init__( name, task_input_values, pipeline_parameters, pipeline_options, extra_parameters, ) self.script = "" self.show_output = True self.use_snapshots = True self.ignore_script_errors = False self.arguments = [] self.script_environment_variables: Dict[str, str] = {} def validate_inputs(self): """Validate inputs""" pass def set_task_inputs(self) -> None: """Sets task inputs""" inputs = super().get_parsed_inputs() task_input_dict = {key: value for key, value in inputs.items()} self.script = task_input_dict[INPUT_SCRIPT] self.show_output = task_input_dict[INPUT_SHOW_OUTPUT] self.use_snapshots = task_input_dict[INPUT_USE_SNAPSHOTS] self.ignore_script_errors = task_input_dict[INPUT_IGNORE_SCRIPT_ERRORS] self.arguments = [str(arg) for arg in task_input_dict[INPUT_ARGUMENTS]] self.script_environment_variables = task_input_dict[INPUT_ENVIRONMENT_VARIABLES] if self.use_snapshots is None: # if use_snapshots is not set, then set it to pipeline_options.use_snapshots self.use_snapshots = self.pipeline_options.use_snapshots else: # use_snapshot will be true only if it is set to true and # pipeline-options.use_snapshots is true as well self.use_snapshots = ( self.pipeline_options.use_snapshots and self.use_snapshots ) def run( self, ) -> None: """Run script task.""" self.set_task_inputs() # TODO: snapshot check fd, script_path = tempfile.mkstemp(dir=SCRIPTS_DIRECTORY) # Gives RWX permission for the owner os.chmod(script_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) # Write script to tmp file with os.fdopen(fd, "w") as tmp_file: tmp_file.write(self.script) # Subprocess options subprocess_options = ( dict() if self.show_output else dict(stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) ) # Subprocess environment variables # It will contain OS environment variables, pipeline config and extra parameters subprocess_environment = { **os.environ.copy(), **{ # Replaces special chars from key f"pipeline_{re.sub(r'[^a-zA-Z0-9_]', '_', key)}": value for key, value in self.pipeline_options.get_config_dict().items() }, **self._extra_parameters, **self.script_environment_variables, } # Runs the script process = subprocess.run( [script_path] + self.arguments, env={key: str(value) for key, value in subprocess_environment.items()}, **subprocess_options ) # Delete script os.unlink(script_path) if not self.ignore_script_errors and process.returncode != 0: raise Exception( "Script terminated with {} exit code".format(process.returncode) ) # TODO: Save snapshot
en
0.661361
Task to run scripts. # Task input keys Script task. Validate inputs Sets task inputs # if use_snapshots is not set, then set it to pipeline_options.use_snapshots # use_snapshot will be true only if it is set to true and # pipeline-options.use_snapshots is true as well Run script task. # TODO: snapshot check # Gives RWX permission for the owner # Write script to tmp file # Subprocess options # Subprocess environment variables # It will contain OS environment variables, pipeline config and extra parameters # Replaces special chars from key # Runs the script # Delete script # TODO: Save snapshot
2.551656
3
part4/Folium/Folium_Choropleth.py
tls1403/PythonTest
0
6628261
<reponame>tls1403/PythonTest<gh_stars>0 import pandas as pd import folium import json file_path = 'D:/5674-833_4th/part4/경기도인구데이터.xlsx' df =pd.read_excel(file_path,index_col='구분',engine= 'openpyxl') #열(2007,2008,,,)을 string 으로 바꿔줌 df.columns = df.columns.map(str) #경기도 시군구 경계 정보를 가진 geo-json 파일 불러오기 geo_path = 'D:/5674-833_4th/part4/경기도행정구역경계.json' try: geo_data = json.load(open(geo_path,encoding='utf-8')) except: geo_data = json.load(open(geo_path,encoding='utf-8-sig')) # 경기도 지도 만들기 g_map = folium.Map(location=[37.5502,126.982], tiles='Stamen Terrain',zoom_start=9) #출력할 연도 선택 year = '2007' #Choropleth 클래스로 단계구분도 표시하기 folium.Choropleth(geo_data= geo_data, data = df[year], columns=[df.index,df[year]], fill_color='YlOrRd',fill_opacity= 0.7, line_opacity=0.3, threshold_scale= [10000,100000,300000,500000,700000], key_on='feature.properties.name', ).add_to(g_map) g_map.save('D:/gyonggi_population_'+year+'.html')
import pandas as pd import folium import json file_path = 'D:/5674-833_4th/part4/경기도인구데이터.xlsx' df =pd.read_excel(file_path,index_col='구분',engine= 'openpyxl') #열(2007,2008,,,)을 string 으로 바꿔줌 df.columns = df.columns.map(str) #경기도 시군구 경계 정보를 가진 geo-json 파일 불러오기 geo_path = 'D:/5674-833_4th/part4/경기도행정구역경계.json' try: geo_data = json.load(open(geo_path,encoding='utf-8')) except: geo_data = json.load(open(geo_path,encoding='utf-8-sig')) # 경기도 지도 만들기 g_map = folium.Map(location=[37.5502,126.982], tiles='Stamen Terrain',zoom_start=9) #출력할 연도 선택 year = '2007' #Choropleth 클래스로 단계구분도 표시하기 folium.Choropleth(geo_data= geo_data, data = df[year], columns=[df.index,df[year]], fill_color='YlOrRd',fill_opacity= 0.7, line_opacity=0.3, threshold_scale= [10000,100000,300000,500000,700000], key_on='feature.properties.name', ).add_to(g_map) g_map.save('D:/gyonggi_population_'+year+'.html')
ko
1.000066
#열(2007,2008,,,)을 string 으로 바꿔줌 #경기도 시군구 경계 정보를 가진 geo-json 파일 불러오기 # 경기도 지도 만들기 #출력할 연도 선택 #Choropleth 클래스로 단계구분도 표시하기
2.638541
3
sympyosis/ext/processes/__init__.py
ZechCodes/sympyosis
0
6628262
<filename>sympyosis/ext/processes/__init__.py from sympyosis.ext.processes.supervisor import SupervisorManager
<filename>sympyosis/ext/processes/__init__.py from sympyosis.ext.processes.supervisor import SupervisorManager
none
1
1.107185
1
awards_app/forms.py
jakesIII/awwwards
0
6628263
from django import forms from .models import Profile,Project,Review SCORES = [ (1,1),(2,2), (3,3),(4,4), (5,5),(6,6), (7,7),(8,8), (9,9),(10,10), ] class ProfileUpdateForm(forms.ModelForm): class Meta: model=Profile exclude=['user'] class ProjectUploadForm(forms.ModelForm): class Meta: model=Project exclude=['user'] class ReviewForm(forms.ModelForm): class Meta: model=Review fields=('comment', 'design', 'useability', 'content') widget={ 'comment':forms.Textarea(attrs={"class":"form-control mb-4"}), 'design':forms.Select(choices=SCORES,attrs={"class":"form-control mb-4"}), 'useability':forms.Select(choices=SCORES,attrs={"class":"form-control mb-4"}), 'content':forms.Select(choices=SCORES,attrs={"class":"form-control mb-4"}), }
from django import forms from .models import Profile,Project,Review SCORES = [ (1,1),(2,2), (3,3),(4,4), (5,5),(6,6), (7,7),(8,8), (9,9),(10,10), ] class ProfileUpdateForm(forms.ModelForm): class Meta: model=Profile exclude=['user'] class ProjectUploadForm(forms.ModelForm): class Meta: model=Project exclude=['user'] class ReviewForm(forms.ModelForm): class Meta: model=Review fields=('comment', 'design', 'useability', 'content') widget={ 'comment':forms.Textarea(attrs={"class":"form-control mb-4"}), 'design':forms.Select(choices=SCORES,attrs={"class":"form-control mb-4"}), 'useability':forms.Select(choices=SCORES,attrs={"class":"form-control mb-4"}), 'content':forms.Select(choices=SCORES,attrs={"class":"form-control mb-4"}), }
none
1
2.084364
2
riseide/pconsole.py
yxdragon/riseide
0
6628264
<filename>riseide/pconsole.py from code import InteractiveConsole from multiprocessing import Pipe, Process import threading, time from pdb import Pdb import numpy as np import pandas as pd import sys def pretty_str(obj, l=10): if isinstance(obj, int): return str(obj) elif isinstance(obj, float): return str(obj) elif isinstance(obj, str): if len(obj)<=l: return obj return obj[:l//2] + ' ... ' + obj[-l//2:] elif type(obj) in (tuple, list): length = len(obj) if len(obj)>l: obj = obj[:l//2] + obj[-l//2:] tps = set([type(i) for i in obj]) if set(tps).issubset({int, float}): if length>l: s = '%s%s'%(obj[:l//2], obj[-l//2:]) return s.replace('][', ' ... ') return str(obj) else: return f'length [{length}]' elif isinstance(obj, np.ndarray): return '%s array in %s'%(obj.dtype, obj.shape) elif isinstance(obj, pd.DataFrame): return 'dataframe in %s'%(obj.shape,) else: return 'object' def get_locals(var=None, filt=['all']): var = var or locals() cont = [] for key in var.keys(): if not 'all' in filt and type(var[key]) not in filt: continue cont.append((key, str(type(var[key])), pretty_str(var[key]))) return cont class Powerdb(Pdb): def precmd(self, line): if not isinstance(line, str): return line return super().precmd(line) def onecmd(self, line): self.prompt = '--> ' if line==':r': self.message('%-15s'%'[Step Out....]') return self.do_return(None) if line==':s': self.message('%-15s'%'[Step Into...]') return self.do_step(None) if line==':n': self.message('%-15s'%'[Step Next...]') return self.do_next(None) if line==':c': self.message('%-15s'%'[Continue....]') return self.do_continue(None) if line==':u': return self.do_up(None) if line==':d': return self.do_down(None) if line==':l': return self.do_list(None) if line==':w': return self.do_where(None) if line==':q': self.message('%-15s'%'[Step Debug..]') return self.do_quit(None) if line==':m': return self.refresh_bpmark(None) if isinstance(line, tuple): method, name = line if method=='locals': self.message((get_locals(self.curframe_locals, name), True)) self.prompt = None if method=='breakpoint': self.clear_all_breaks() for file, line in name: self.set_break(file, line) self.message(('breakpoint', True)) if self.first: self.first, self.prompt = False, None return self.message('%-15s'%'[Set BreakPoint...]\n') return 0 _, self.message = self.message, print self.default(line) self.message = _ def user_call(self, frame, argument_list): if self._wait_for_mainpyfile: return if self.stop_here(frame): self.interaction(frame, None) def user_return(self, frame, return_value): pass def print_stack_entry(self, frame_lineno, prompt_prefix=''): frame, lineno = frame_lineno import linecache filename = self.canonic(frame.f_code.co_filename) line = linecache.getline(filename, lineno, frame.f_globals) {'path':filename, 'no':lineno, 'line':line} self.message(({'path':filename, 'no':lineno, 'line':line.rstrip()}, True)) if self.first: self.message('--> %-15s'%'[Debugging...]') self.message('%-15s ln:%-4d || %s'%( filename.split('\\')[-1], lineno, line)) def debug(self, filename, globals=None, locals=None): self.prompt, self.first = '--> ', True import __main__ __main__.__dict__.clear() __main__.__dict__.update({"__name__" : "__main__", "__file__" : filename, "__builtins__": __builtins__, }) self._wait_for_mainpyfile = True self.mainpyfile = self.canonic(filename) self._user_requested_quit = False with open(filename, "rb") as fp: statement = "exec(compile(%r, %r, 'exec'))" % (fp.read(), self.mainpyfile) self.run(statement, globals, locals) self.message(({'path':'end', 'no':0, 'line':''}, False)) self.message('Debug Completed...\n') class Console(InteractiveConsole): def __init__(self, conn, locals=None, filename="<console>"): super().__init__(locals, filename) self.buf = [] self.pipe = conn td = threading.Thread(target=self.listening, args=(), daemon=True) td.start() __builtins__['input'] = self.input def listening(self): while True: self.buf.append(self.pipe.recv()) def write(self, data, end='\n'): #if isinstance(data, str): data += end self.pipe.send(data) def mplpause(self, interval): from matplotlib import _pylab_helpers manager = _pylab_helpers.Gcf.get_active() if manager is not None: canvas = manager.canvas if canvas.figure.stale: canvas.draw_idle() try: canvas.start_event_loop(interval) except: time.sleep(interval) else: time.sleep(interval) def execfile(self, path): with open(path, encoding='utf-8') as f: exec(f.read(), self.locals) def debug(self, path): db = Powerdb() #f = lambda x: x+'\n' if isinstance(x, str) else x #db.message = lambda x: self.write(f(x)) db.message = self.write db.debug(path, locals=self.locals) def input(self, prompt=None): if not prompt is None: self.pipe.send(prompt) while True: if len(self.buf)>0: return self.buf.pop(0) self.mplpause(0.1) def raw_input(self, prompt=""): line = self.input(prompt) if isinstance(line, str): return line method, name = line if '(' in name: self.pipe.send(('cannot deduce', False)); elif method=='dir': # list field try: value = eval('dir(%s)'%name, None, self.locals) self.pipe.send((value, True)) except: self.pipe.send((sys.exc_info()[1], False)) elif method=='get': # send binary object try: self.pipe.send((eval(name, None, self.locals), True)) except: self.pipe.send((sys.exc_info()[1], False)) elif method == 'set': # write binary object try: exec('%s = %s'%name, self.locals) self.pipe.send(('%s = %s'%name, True)) except: self.pipe.send((sys.exc_info()[1], False)) elif method == 'doc': # dot means document try: value = eval(name+'.__doc__', None, self.locals) self.pipe.send((value, True)) except: self.pipe.send((sys.exc_info()[1], False)) elif method == 'locals': try: self.pipe.send((get_locals(self.locals, name), True)) except: self.pipe.send((sys.exc_info()[1], False)) return self.raw_input() def interact(conn): import sys, time, threading import matplotlib import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.ion() conn.write = conn.send conn.read = conn.recv sys.stdout = conn cs = Console(conn, {'plt':plt, 'pipe':conn}) cs.locals['execfile'] = cs.execfile cs.locals['debug'] = cs.debug cs.interact() #threading.Thread(target=cs.interact, args=()) #time.sleep(100) class ProcessConsole: def __init__(self): self.status = 'nothing' def listening(self): while True: line = self.pin.recv() if isinstance(line, str): self.recv(line) if line=='>>> ': self.ready() if line=='... ': self.goon() elif self.status=='waiting': self.status = line def terminate(self): self.process.terminate() self.recv = self.ready = self.goon = self.wait = None def write(self, data): self.wait() self.pin.send(data) def getobj(self, method, name): self.pin.send((method, name)) self.status = 'waiting' while self.status=='waiting': time.sleep(0.01) rst, self.status = self.status, 'nothing' return rst def debug(self, method, name): if method == 'action': self.pin.send(name) if method == 'breakpoint': self.pin.send((method, name)) self.status = 'waiting' while self.status=='waiting': time.sleep(0.01) rst, self.status = self.status, 'nothing' if method == 'action': pass #self.recv('[Debug Completed...]\n') return rst def start(self, recv=print, ready=None, goon=None, wait=None): nf = lambda p=None: p self.recv, self.ready = recv, ready or nf self.goon, self.wait = goon or nf, wait or nf self.pout, self.pin = Pipe() self.process = Process(target=interact, args=(self.pout,), daemon=True) self.thread = threading.Thread(target=self.listening, args=(), daemon=True) self.thread.start(), self.process.start() if __name__ == '__main__': a = InteractiveConsole() a.runsource
<filename>riseide/pconsole.py from code import InteractiveConsole from multiprocessing import Pipe, Process import threading, time from pdb import Pdb import numpy as np import pandas as pd import sys def pretty_str(obj, l=10): if isinstance(obj, int): return str(obj) elif isinstance(obj, float): return str(obj) elif isinstance(obj, str): if len(obj)<=l: return obj return obj[:l//2] + ' ... ' + obj[-l//2:] elif type(obj) in (tuple, list): length = len(obj) if len(obj)>l: obj = obj[:l//2] + obj[-l//2:] tps = set([type(i) for i in obj]) if set(tps).issubset({int, float}): if length>l: s = '%s%s'%(obj[:l//2], obj[-l//2:]) return s.replace('][', ' ... ') return str(obj) else: return f'length [{length}]' elif isinstance(obj, np.ndarray): return '%s array in %s'%(obj.dtype, obj.shape) elif isinstance(obj, pd.DataFrame): return 'dataframe in %s'%(obj.shape,) else: return 'object' def get_locals(var=None, filt=['all']): var = var or locals() cont = [] for key in var.keys(): if not 'all' in filt and type(var[key]) not in filt: continue cont.append((key, str(type(var[key])), pretty_str(var[key]))) return cont class Powerdb(Pdb): def precmd(self, line): if not isinstance(line, str): return line return super().precmd(line) def onecmd(self, line): self.prompt = '--> ' if line==':r': self.message('%-15s'%'[Step Out....]') return self.do_return(None) if line==':s': self.message('%-15s'%'[Step Into...]') return self.do_step(None) if line==':n': self.message('%-15s'%'[Step Next...]') return self.do_next(None) if line==':c': self.message('%-15s'%'[Continue....]') return self.do_continue(None) if line==':u': return self.do_up(None) if line==':d': return self.do_down(None) if line==':l': return self.do_list(None) if line==':w': return self.do_where(None) if line==':q': self.message('%-15s'%'[Step Debug..]') return self.do_quit(None) if line==':m': return self.refresh_bpmark(None) if isinstance(line, tuple): method, name = line if method=='locals': self.message((get_locals(self.curframe_locals, name), True)) self.prompt = None if method=='breakpoint': self.clear_all_breaks() for file, line in name: self.set_break(file, line) self.message(('breakpoint', True)) if self.first: self.first, self.prompt = False, None return self.message('%-15s'%'[Set BreakPoint...]\n') return 0 _, self.message = self.message, print self.default(line) self.message = _ def user_call(self, frame, argument_list): if self._wait_for_mainpyfile: return if self.stop_here(frame): self.interaction(frame, None) def user_return(self, frame, return_value): pass def print_stack_entry(self, frame_lineno, prompt_prefix=''): frame, lineno = frame_lineno import linecache filename = self.canonic(frame.f_code.co_filename) line = linecache.getline(filename, lineno, frame.f_globals) {'path':filename, 'no':lineno, 'line':line} self.message(({'path':filename, 'no':lineno, 'line':line.rstrip()}, True)) if self.first: self.message('--> %-15s'%'[Debugging...]') self.message('%-15s ln:%-4d || %s'%( filename.split('\\')[-1], lineno, line)) def debug(self, filename, globals=None, locals=None): self.prompt, self.first = '--> ', True import __main__ __main__.__dict__.clear() __main__.__dict__.update({"__name__" : "__main__", "__file__" : filename, "__builtins__": __builtins__, }) self._wait_for_mainpyfile = True self.mainpyfile = self.canonic(filename) self._user_requested_quit = False with open(filename, "rb") as fp: statement = "exec(compile(%r, %r, 'exec'))" % (fp.read(), self.mainpyfile) self.run(statement, globals, locals) self.message(({'path':'end', 'no':0, 'line':''}, False)) self.message('Debug Completed...\n') class Console(InteractiveConsole): def __init__(self, conn, locals=None, filename="<console>"): super().__init__(locals, filename) self.buf = [] self.pipe = conn td = threading.Thread(target=self.listening, args=(), daemon=True) td.start() __builtins__['input'] = self.input def listening(self): while True: self.buf.append(self.pipe.recv()) def write(self, data, end='\n'): #if isinstance(data, str): data += end self.pipe.send(data) def mplpause(self, interval): from matplotlib import _pylab_helpers manager = _pylab_helpers.Gcf.get_active() if manager is not None: canvas = manager.canvas if canvas.figure.stale: canvas.draw_idle() try: canvas.start_event_loop(interval) except: time.sleep(interval) else: time.sleep(interval) def execfile(self, path): with open(path, encoding='utf-8') as f: exec(f.read(), self.locals) def debug(self, path): db = Powerdb() #f = lambda x: x+'\n' if isinstance(x, str) else x #db.message = lambda x: self.write(f(x)) db.message = self.write db.debug(path, locals=self.locals) def input(self, prompt=None): if not prompt is None: self.pipe.send(prompt) while True: if len(self.buf)>0: return self.buf.pop(0) self.mplpause(0.1) def raw_input(self, prompt=""): line = self.input(prompt) if isinstance(line, str): return line method, name = line if '(' in name: self.pipe.send(('cannot deduce', False)); elif method=='dir': # list field try: value = eval('dir(%s)'%name, None, self.locals) self.pipe.send((value, True)) except: self.pipe.send((sys.exc_info()[1], False)) elif method=='get': # send binary object try: self.pipe.send((eval(name, None, self.locals), True)) except: self.pipe.send((sys.exc_info()[1], False)) elif method == 'set': # write binary object try: exec('%s = %s'%name, self.locals) self.pipe.send(('%s = %s'%name, True)) except: self.pipe.send((sys.exc_info()[1], False)) elif method == 'doc': # dot means document try: value = eval(name+'.__doc__', None, self.locals) self.pipe.send((value, True)) except: self.pipe.send((sys.exc_info()[1], False)) elif method == 'locals': try: self.pipe.send((get_locals(self.locals, name), True)) except: self.pipe.send((sys.exc_info()[1], False)) return self.raw_input() def interact(conn): import sys, time, threading import matplotlib import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.ion() conn.write = conn.send conn.read = conn.recv sys.stdout = conn cs = Console(conn, {'plt':plt, 'pipe':conn}) cs.locals['execfile'] = cs.execfile cs.locals['debug'] = cs.debug cs.interact() #threading.Thread(target=cs.interact, args=()) #time.sleep(100) class ProcessConsole: def __init__(self): self.status = 'nothing' def listening(self): while True: line = self.pin.recv() if isinstance(line, str): self.recv(line) if line=='>>> ': self.ready() if line=='... ': self.goon() elif self.status=='waiting': self.status = line def terminate(self): self.process.terminate() self.recv = self.ready = self.goon = self.wait = None def write(self, data): self.wait() self.pin.send(data) def getobj(self, method, name): self.pin.send((method, name)) self.status = 'waiting' while self.status=='waiting': time.sleep(0.01) rst, self.status = self.status, 'nothing' return rst def debug(self, method, name): if method == 'action': self.pin.send(name) if method == 'breakpoint': self.pin.send((method, name)) self.status = 'waiting' while self.status=='waiting': time.sleep(0.01) rst, self.status = self.status, 'nothing' if method == 'action': pass #self.recv('[Debug Completed...]\n') return rst def start(self, recv=print, ready=None, goon=None, wait=None): nf = lambda p=None: p self.recv, self.ready = recv, ready or nf self.goon, self.wait = goon or nf, wait or nf self.pout, self.pin = Pipe() self.process = Process(target=interact, args=(self.pout,), daemon=True) self.thread = threading.Thread(target=self.listening, args=(), daemon=True) self.thread.start(), self.process.start() if __name__ == '__main__': a = InteractiveConsole() a.runsource
en
0.355525
#if isinstance(data, str): data += end #f = lambda x: x+'\n' if isinstance(x, str) else x #db.message = lambda x: self.write(f(x)) # list field # send binary object # write binary object # dot means document #threading.Thread(target=cs.interact, args=()) #time.sleep(100) #self.recv('[Debug Completed...]\n')
2.596628
3
tweedle/core.py
sourcery-ai-bot/tweedle
2
6628265
<reponame>sourcery-ai-bot/tweedle __all__ = ["cli"] from importlib import import_module import click from tweedle import PROJECT_SRC, __version__ from tweedle.util import clickx SUBCMDS_FOLDER = PROJECT_SRC / 'cmd' class TweedleSubCommandsCLI(click.MultiCommand): def list_commands(self, ctx): # return [ # str(x.name)[:-3] for x in SUBCMDS_FOLDER.glob('*.py') # if not x.name.startswith('__init__') # ] subcmds = ['manage'] return subcmds def get_command(self, ctx, name): mod = import_module(name=f'.cmd.{name}', package='tweedle') return getattr(mod, 'cli') @click.command(name='tweedle', cls=TweedleSubCommandsCLI) @click.version_option(help='show version details', version=__version__) @clickx.option_of_common_help def cli(): """ Welcome to use tweedle, enjoy it and be efficient :P\n Please use "tweedle COMMAND --help" to get more detail of usages """ pass
__all__ = ["cli"] from importlib import import_module import click from tweedle import PROJECT_SRC, __version__ from tweedle.util import clickx SUBCMDS_FOLDER = PROJECT_SRC / 'cmd' class TweedleSubCommandsCLI(click.MultiCommand): def list_commands(self, ctx): # return [ # str(x.name)[:-3] for x in SUBCMDS_FOLDER.glob('*.py') # if not x.name.startswith('__init__') # ] subcmds = ['manage'] return subcmds def get_command(self, ctx, name): mod = import_module(name=f'.cmd.{name}', package='tweedle') return getattr(mod, 'cli') @click.command(name='tweedle', cls=TweedleSubCommandsCLI) @click.version_option(help='show version details', version=__version__) @clickx.option_of_common_help def cli(): """ Welcome to use tweedle, enjoy it and be efficient :P\n Please use "tweedle COMMAND --help" to get more detail of usages """ pass
en
0.583722
# return [ # str(x.name)[:-3] for x in SUBCMDS_FOLDER.glob('*.py') # if not x.name.startswith('__init__') # ] Welcome to use tweedle, enjoy it and be efficient :P\n Please use "tweedle COMMAND --help" to get more detail of usages
2.294221
2
tests/test.py
lostblackknight/wordmarker
2
6628266
from wordmarker.loaders.default_resource_loader import DefaultResourceLoader if __name__ == '__main__': loader = DefaultResourceLoader() resource = loader.get_resource("E:\PycharmProjects\wordmarker\data\hh") print(resource.get_file()) print(resource.get_file_name()) print(loader.load(resource))
from wordmarker.loaders.default_resource_loader import DefaultResourceLoader if __name__ == '__main__': loader = DefaultResourceLoader() resource = loader.get_resource("E:\PycharmProjects\wordmarker\data\hh") print(resource.get_file()) print(resource.get_file_name()) print(loader.load(resource))
none
1
2.27606
2
sdk/python/pulumi_azure_native/operationalinsights/v20190801preview/__init__.py
sebtelko/pulumi-azure-native
0
6628267
<gh_stars>0 # coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from ... import _utilities import typing # Export this package's modules as members: from ._enums import * from .data_export import * from .get_data_export import * from .get_linked_service import * from .get_linked_storage_account import * from .linked_service import * from .linked_storage_account import *
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from ... import _utilities import typing # Export this package's modules as members: from ._enums import * from .data_export import * from .get_data_export import * from .get_linked_service import * from .get_linked_storage_account import * from .linked_service import * from .linked_storage_account import *
en
0.955671
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** # Export this package's modules as members:
0.924093
1
test/syscalls/build_defs.bzl
kimmkumsook/gvisor
1
6628268
<gh_stars>1-10 """Defines a rule for syscall test targets.""" # syscall_test is a macro that will create targets to run the given test target # on the host (native) and runsc. def syscall_test(test, shard_count = 1, size = "small", use_tmpfs = False): _syscall_test(test, shard_count, size, "native", False) _syscall_test(test, shard_count, size, "kvm", use_tmpfs) _syscall_test(test, shard_count, size, "ptrace", use_tmpfs) if not use_tmpfs: _syscall_test(test, shard_count, size, "ptrace", use_tmpfs, "shared") def _syscall_test(test, shard_count, size, platform, use_tmpfs, file_access = "exclusive"): test_name = test.split(":")[1] # Prepend "runsc" to non-native platform names. full_platform = platform if platform == "native" else "runsc_" + platform name = test_name + "_" + full_platform if file_access == "shared": name += "_shared" # Add the full_platform and file access in a tag to make it easier to run # all the tests on a specific flavor. Use --test_tag_filters=ptrace,file_shared. tags = [full_platform, "file_" + file_access] # Add tag to prevent the tests from running in a Bazel sandbox. # TODO: Make the tests run without this tag. tags.append("no-sandbox") # TODO: KVM tests are tagged "manual" to until the platform is # more stable. if platform == "kvm": tags += ["manual"] sh_test( srcs = ["syscall_test_runner.sh"], name = name, data = [ ":syscall_test_runner", test, ], args = [ # Arguments are passed directly to syscall_test_runner binary. "--test-name=" + test_name, "--platform=" + platform, "--use-tmpfs=" + str(use_tmpfs), "--file-access=" + file_access, "--parallel=true", ], size = size, tags = tags, shard_count = shard_count, ) def sh_test(**kwargs): """Wraps the standard sh_test.""" native.sh_test( **kwargs )
"""Defines a rule for syscall test targets.""" # syscall_test is a macro that will create targets to run the given test target # on the host (native) and runsc. def syscall_test(test, shard_count = 1, size = "small", use_tmpfs = False): _syscall_test(test, shard_count, size, "native", False) _syscall_test(test, shard_count, size, "kvm", use_tmpfs) _syscall_test(test, shard_count, size, "ptrace", use_tmpfs) if not use_tmpfs: _syscall_test(test, shard_count, size, "ptrace", use_tmpfs, "shared") def _syscall_test(test, shard_count, size, platform, use_tmpfs, file_access = "exclusive"): test_name = test.split(":")[1] # Prepend "runsc" to non-native platform names. full_platform = platform if platform == "native" else "runsc_" + platform name = test_name + "_" + full_platform if file_access == "shared": name += "_shared" # Add the full_platform and file access in a tag to make it easier to run # all the tests on a specific flavor. Use --test_tag_filters=ptrace,file_shared. tags = [full_platform, "file_" + file_access] # Add tag to prevent the tests from running in a Bazel sandbox. # TODO: Make the tests run without this tag. tags.append("no-sandbox") # TODO: KVM tests are tagged "manual" to until the platform is # more stable. if platform == "kvm": tags += ["manual"] sh_test( srcs = ["syscall_test_runner.sh"], name = name, data = [ ":syscall_test_runner", test, ], args = [ # Arguments are passed directly to syscall_test_runner binary. "--test-name=" + test_name, "--platform=" + platform, "--use-tmpfs=" + str(use_tmpfs), "--file-access=" + file_access, "--parallel=true", ], size = size, tags = tags, shard_count = shard_count, ) def sh_test(**kwargs): """Wraps the standard sh_test.""" native.sh_test( **kwargs )
en
0.810307
Defines a rule for syscall test targets. # syscall_test is a macro that will create targets to run the given test target # on the host (native) and runsc. # Prepend "runsc" to non-native platform names. # Add the full_platform and file access in a tag to make it easier to run # all the tests on a specific flavor. Use --test_tag_filters=ptrace,file_shared. # Add tag to prevent the tests from running in a Bazel sandbox. # TODO: Make the tests run without this tag. # TODO: KVM tests are tagged "manual" to until the platform is # more stable. # Arguments are passed directly to syscall_test_runner binary. Wraps the standard sh_test.
2.65639
3
heat/tests/test_auth_password.py
citrix-openstack-build/heat
0
6628269
<gh_stars>0 # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from keystoneclient.v2_0 import client as keystone_client from keystoneclient.exceptions import Unauthorized from oslo.config import cfg import webob from heat.common.auth_password import KeystonePasswordAuthProtocol from heat.tests.common import HeatTestCase EXPECTED_V2_DEFAULT_ENV_RESPONSE = { 'HTTP_X_IDENTITY_STATUS': 'Confirmed', 'HTTP_X_TENANT_ID': 'tenant_id1', 'HTTP_X_TENANT_NAME': 'tenant_name1', 'HTTP_X_USER_ID': 'user_id1', 'HTTP_X_USER_NAME': 'user_name1', 'HTTP_X_ROLES': 'role1,role2', 'HTTP_X_USER': 'user_name1', # deprecated (diablo-compat) 'HTTP_X_TENANT': 'tenant_name1', # deprecated (diablo-compat) 'HTTP_X_ROLE': 'role1,role2', # deprecated (diablo-compat) } TOKEN_RESPONSE = { 'token': { 'id': 'l<PASSWORD>', 'expires': '2020-01-01T00:00:10.000123Z', 'tenant': { 'id': 'tenant_id1', 'name': 'tenant_name1', }, }, 'user': { 'id': 'user_id1', 'name': 'user_name1', 'roles': [ {'name': 'role1'}, {'name': 'role2'}, ], }, 'serviceCatalog': {} } class FakeApp(object): """This represents a WSGI app protected by our auth middleware.""" def __init__(self, expected_env=None): expected_env = expected_env or {} self.expected_env = dict(EXPECTED_V2_DEFAULT_ENV_RESPONSE) self.expected_env.update(expected_env) def __call__(self, env, start_response): """Assert that expected environment is present when finally called.""" for k, v in self.expected_env.items(): assert env[k] == v, '%s != %s' % (env[k], v) resp = webob.Response() resp.body = 'SUCCESS' return resp(env, start_response) class KeystonePasswordAuthProtocolTest(HeatTestCase): def setUp(self): super(KeystonePasswordAuthProtocolTest, self).setUp() self.config = {'auth_uri': 'http://keystone.test.com:5000'} self.app = FakeApp( expected_env={'HTTP_X_AUTH_URL': self.config['auth_uri']}) self.middleware = KeystonePasswordAuthProtocol(self.app, self.config) def _start_fake_response(self, status, headers): self.response_status = int(status.split(' ', 1)[0]) self.response_headers = dict(headers) def test_valid_request(self): self.m.StubOutClassWithMocks(keystone_client, 'Client') mock_client = keystone_client.Client( username='user_name1', password='<PASSWORD>', tenant_id='tenant_id1', auth_url=self.config['auth_uri']) mock_client.auth_ref = TOKEN_RESPONSE self.m.ReplayAll() req = webob.Request.blank('/tenant_id1/') req.headers['X_AUTH_USER'] = 'user_name1' req.headers['X_AUTH_KEY'] = 'goodpassword' self.middleware(req.environ, self._start_fake_response) self.m.VerifyAll() def test_request_with_bad_credentials(self): self.m.StubOutWithMock( keystone_client, 'Client', use_mock_anything=True) mock_client = keystone_client.Client( username='user_name1', password='<PASSWORD>', tenant_id='tenant_id1', auth_url=self.config['auth_uri']) mock_client.AndRaise(Unauthorized(401)) self.m.ReplayAll() req = webob.Request.blank('/tenant_id1/') req.headers['X_AUTH_USER'] = 'user_name1' req.headers['X_AUTH_KEY'] = 'badpassword' self.middleware(req.environ, self._start_fake_response) self.m.VerifyAll() self.assertEqual(self.response_status, 401) def test_request_with_no_tenant_in_url_or_auth_headers(self): req = webob.Request.blank('/') self.middleware(req.environ, self._start_fake_response) self.assertEqual(self.response_status, 401) def test_multi_cloud(self): allowed_auth_uris = ['http://multicloud.test.com:5000/v2.0'] cfg.CONF.set_override('multi_cloud', True, group='auth_password') auth_url = 'http://multicloud.test.com:5000/v2.0' cfg.CONF.set_override('allowed_auth_uris', allowed_auth_uris, group='auth_password') self.app = FakeApp( expected_env={'HTTP_X_AUTH_URL': auth_url}) self.middleware = KeystonePasswordAuthProtocol(self.app, self.config) self.m.StubOutClassWithMocks(keystone_client, 'Client') mock_client = keystone_client.Client( username='user_name1', password='<PASSWORD>', tenant_id='tenant_id1', auth_url=auth_url) mock_client.auth_ref = TOKEN_RESPONSE self.m.ReplayAll() req = webob.Request.blank('/tenant_id1/') req.headers['X_AUTH_USER'] = 'user_name1' req.headers['X_AUTH_KEY'] = 'goodpassword' req.headers['X_AUTH_URL'] = auth_url self.middleware(req.environ, self._start_fake_response) self.m.VerifyAll() def test_multi_cloud_empty_allowed_uris(self): cfg.CONF.set_override('multi_cloud', True, group='auth_password') auth_url = 'http://multicloud.test.com:5000/v2.0' cfg.CONF.set_override('allowed_auth_uris', [], group='auth_password') req = webob.Request.blank('/tenant_id1/') req.headers['X_AUTH_USER'] = 'user_name1' req.headers['X_AUTH_KEY'] = 'goodpassword' req.headers['X_AUTH_URL'] = auth_url self.middleware(req.environ, self._start_fake_response) self.assertEqual(self.response_status, 401) def test_multi_cloud_target_not_allowed(self): cfg.CONF.set_override('multi_cloud', True, group='auth_password') auth_url = 'http://multicloud.test.com:5000/v2.0' cfg.CONF.set_override('allowed_auth_uris', ['http://some.other.url:5000/v2.0'], group='auth_password') req = webob.Request.blank('/tenant_id1/') req.headers['X_AUTH_USER'] = 'user_name1' req.headers['X_AUTH_KEY'] = 'goodpassword' req.headers['X_AUTH_URL'] = auth_url self.middleware(req.environ, self._start_fake_response) self.assertEqual(self.response_status, 401) def test_multi_cloud_no_auth_url(self): cfg.CONF.set_override('multi_cloud', True, group='auth_password') req = webob.Request.blank('/tenant_id1/') req.headers['X_AUTH_USER'] = 'user_name1' req.headers['X_AUTH_KEY'] = 'goodpassword' response = self.middleware(req.environ, self._start_fake_response) self.assertEqual(self.response_status, 400)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from keystoneclient.v2_0 import client as keystone_client from keystoneclient.exceptions import Unauthorized from oslo.config import cfg import webob from heat.common.auth_password import KeystonePasswordAuthProtocol from heat.tests.common import HeatTestCase EXPECTED_V2_DEFAULT_ENV_RESPONSE = { 'HTTP_X_IDENTITY_STATUS': 'Confirmed', 'HTTP_X_TENANT_ID': 'tenant_id1', 'HTTP_X_TENANT_NAME': 'tenant_name1', 'HTTP_X_USER_ID': 'user_id1', 'HTTP_X_USER_NAME': 'user_name1', 'HTTP_X_ROLES': 'role1,role2', 'HTTP_X_USER': 'user_name1', # deprecated (diablo-compat) 'HTTP_X_TENANT': 'tenant_name1', # deprecated (diablo-compat) 'HTTP_X_ROLE': 'role1,role2', # deprecated (diablo-compat) } TOKEN_RESPONSE = { 'token': { 'id': 'l<PASSWORD>', 'expires': '2020-01-01T00:00:10.000123Z', 'tenant': { 'id': 'tenant_id1', 'name': 'tenant_name1', }, }, 'user': { 'id': 'user_id1', 'name': 'user_name1', 'roles': [ {'name': 'role1'}, {'name': 'role2'}, ], }, 'serviceCatalog': {} } class FakeApp(object): """This represents a WSGI app protected by our auth middleware.""" def __init__(self, expected_env=None): expected_env = expected_env or {} self.expected_env = dict(EXPECTED_V2_DEFAULT_ENV_RESPONSE) self.expected_env.update(expected_env) def __call__(self, env, start_response): """Assert that expected environment is present when finally called.""" for k, v in self.expected_env.items(): assert env[k] == v, '%s != %s' % (env[k], v) resp = webob.Response() resp.body = 'SUCCESS' return resp(env, start_response) class KeystonePasswordAuthProtocolTest(HeatTestCase): def setUp(self): super(KeystonePasswordAuthProtocolTest, self).setUp() self.config = {'auth_uri': 'http://keystone.test.com:5000'} self.app = FakeApp( expected_env={'HTTP_X_AUTH_URL': self.config['auth_uri']}) self.middleware = KeystonePasswordAuthProtocol(self.app, self.config) def _start_fake_response(self, status, headers): self.response_status = int(status.split(' ', 1)[0]) self.response_headers = dict(headers) def test_valid_request(self): self.m.StubOutClassWithMocks(keystone_client, 'Client') mock_client = keystone_client.Client( username='user_name1', password='<PASSWORD>', tenant_id='tenant_id1', auth_url=self.config['auth_uri']) mock_client.auth_ref = TOKEN_RESPONSE self.m.ReplayAll() req = webob.Request.blank('/tenant_id1/') req.headers['X_AUTH_USER'] = 'user_name1' req.headers['X_AUTH_KEY'] = 'goodpassword' self.middleware(req.environ, self._start_fake_response) self.m.VerifyAll() def test_request_with_bad_credentials(self): self.m.StubOutWithMock( keystone_client, 'Client', use_mock_anything=True) mock_client = keystone_client.Client( username='user_name1', password='<PASSWORD>', tenant_id='tenant_id1', auth_url=self.config['auth_uri']) mock_client.AndRaise(Unauthorized(401)) self.m.ReplayAll() req = webob.Request.blank('/tenant_id1/') req.headers['X_AUTH_USER'] = 'user_name1' req.headers['X_AUTH_KEY'] = 'badpassword' self.middleware(req.environ, self._start_fake_response) self.m.VerifyAll() self.assertEqual(self.response_status, 401) def test_request_with_no_tenant_in_url_or_auth_headers(self): req = webob.Request.blank('/') self.middleware(req.environ, self._start_fake_response) self.assertEqual(self.response_status, 401) def test_multi_cloud(self): allowed_auth_uris = ['http://multicloud.test.com:5000/v2.0'] cfg.CONF.set_override('multi_cloud', True, group='auth_password') auth_url = 'http://multicloud.test.com:5000/v2.0' cfg.CONF.set_override('allowed_auth_uris', allowed_auth_uris, group='auth_password') self.app = FakeApp( expected_env={'HTTP_X_AUTH_URL': auth_url}) self.middleware = KeystonePasswordAuthProtocol(self.app, self.config) self.m.StubOutClassWithMocks(keystone_client, 'Client') mock_client = keystone_client.Client( username='user_name1', password='<PASSWORD>', tenant_id='tenant_id1', auth_url=auth_url) mock_client.auth_ref = TOKEN_RESPONSE self.m.ReplayAll() req = webob.Request.blank('/tenant_id1/') req.headers['X_AUTH_USER'] = 'user_name1' req.headers['X_AUTH_KEY'] = 'goodpassword' req.headers['X_AUTH_URL'] = auth_url self.middleware(req.environ, self._start_fake_response) self.m.VerifyAll() def test_multi_cloud_empty_allowed_uris(self): cfg.CONF.set_override('multi_cloud', True, group='auth_password') auth_url = 'http://multicloud.test.com:5000/v2.0' cfg.CONF.set_override('allowed_auth_uris', [], group='auth_password') req = webob.Request.blank('/tenant_id1/') req.headers['X_AUTH_USER'] = 'user_name1' req.headers['X_AUTH_KEY'] = 'goodpassword' req.headers['X_AUTH_URL'] = auth_url self.middleware(req.environ, self._start_fake_response) self.assertEqual(self.response_status, 401) def test_multi_cloud_target_not_allowed(self): cfg.CONF.set_override('multi_cloud', True, group='auth_password') auth_url = 'http://multicloud.test.com:5000/v2.0' cfg.CONF.set_override('allowed_auth_uris', ['http://some.other.url:5000/v2.0'], group='auth_password') req = webob.Request.blank('/tenant_id1/') req.headers['X_AUTH_USER'] = 'user_name1' req.headers['X_AUTH_KEY'] = 'goodpassword' req.headers['X_AUTH_URL'] = auth_url self.middleware(req.environ, self._start_fake_response) self.assertEqual(self.response_status, 401) def test_multi_cloud_no_auth_url(self): cfg.CONF.set_override('multi_cloud', True, group='auth_password') req = webob.Request.blank('/tenant_id1/') req.headers['X_AUTH_USER'] = 'user_name1' req.headers['X_AUTH_KEY'] = 'goodpassword' response = self.middleware(req.environ, self._start_fake_response) self.assertEqual(self.response_status, 400)
en
0.814479
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack Foundation # # 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. # deprecated (diablo-compat) # deprecated (diablo-compat) # deprecated (diablo-compat) This represents a WSGI app protected by our auth middleware. Assert that expected environment is present when finally called.
1.307761
1
completion/olivetti.py
carpeanon/input_convex
258
6628270
# local image = require 'image' # local H = require 'icnn.helper' # function f(inputFile, hidden, nTraining) # local data = {} # data.all = H.loadtxt(inputFile) # :t():clone() # :view(400, 1, 64, 64) # :transpose(3, 4):clone() # :div(255) # local topI = {{}, {}, {1, 32}, {1, 64}} # local bottomI = {{}, {}, {33, 64}, {1, 64}} # local leftI = {{}, {}, {1, 64}, {1, 32}} # local rightI = {{}, {}, {1, 64}, {33, 64}} # local trainI = {{1, nTraining}} # local testI = {{nTraining+1, 400}} # if hidden == 'left' then # data.inputSz = torch.IntTensor{1, 64, 32} # data.outputSz = data.inputSz # data.trainX = cast(data.all[trainI][rightI]) # data.trainY = cast(data.all[trainI][leftI]) # data.testX = cast(data.all[testI][rightI]) # data.testY = cast(data.all[testI][leftI]) # data.trainXflip = cast(image.hflip(data.all[trainI][rightI])) # data.testXflip = cast(image.hflip(data.all[testI][rightI])) # elseif hidden == 'bottom' then # data.inputSz = torch.IntTensor{1, 32, 64} # data.outputSz = data.inputSz # data.trainX = cast(data.all[trainI][topI]) # data.trainY = cast(data.all[trainI][bottomI]) # data.testX = cast(data.all[testI][topI]) # data.testY = cast(data.all[testI][bottomI]) # else # assert(false) # end # data.testYflat = data.testY:clone():view(data.testY:size(1), -1) # data.avgY = data.trainY:mean(1):view( # data.trainY:size(2), data.trainY:size(3), data.trainY:size(4)) # return data # end # return f import numpy as np import pickle as pkl import os def load(prefix): cacheF = prefix + '.pkl' if os.path.isfile(cacheF): print('olivetti: loading from cache') with open(cacheF, 'rb') as f: d = pkl.load(f) else: print('olivetti: Creating from txt') data = np.loadtxt(prefix + '.raw') data = data.T.reshape((400,64,64,1)).transpose((0,2,1,3))/255. d = {'trainX': data[0:350,:,32:64,:], 'trainY': data[0:350,:,0:32,:], 'testX': data[350:400,:,32:64,:], 'testY': data[350:400,:,0:32,:]} with open(cacheF, 'wb') as f: pkl.dump(d, f) return d
# local image = require 'image' # local H = require 'icnn.helper' # function f(inputFile, hidden, nTraining) # local data = {} # data.all = H.loadtxt(inputFile) # :t():clone() # :view(400, 1, 64, 64) # :transpose(3, 4):clone() # :div(255) # local topI = {{}, {}, {1, 32}, {1, 64}} # local bottomI = {{}, {}, {33, 64}, {1, 64}} # local leftI = {{}, {}, {1, 64}, {1, 32}} # local rightI = {{}, {}, {1, 64}, {33, 64}} # local trainI = {{1, nTraining}} # local testI = {{nTraining+1, 400}} # if hidden == 'left' then # data.inputSz = torch.IntTensor{1, 64, 32} # data.outputSz = data.inputSz # data.trainX = cast(data.all[trainI][rightI]) # data.trainY = cast(data.all[trainI][leftI]) # data.testX = cast(data.all[testI][rightI]) # data.testY = cast(data.all[testI][leftI]) # data.trainXflip = cast(image.hflip(data.all[trainI][rightI])) # data.testXflip = cast(image.hflip(data.all[testI][rightI])) # elseif hidden == 'bottom' then # data.inputSz = torch.IntTensor{1, 32, 64} # data.outputSz = data.inputSz # data.trainX = cast(data.all[trainI][topI]) # data.trainY = cast(data.all[trainI][bottomI]) # data.testX = cast(data.all[testI][topI]) # data.testY = cast(data.all[testI][bottomI]) # else # assert(false) # end # data.testYflat = data.testY:clone():view(data.testY:size(1), -1) # data.avgY = data.trainY:mean(1):view( # data.trainY:size(2), data.trainY:size(3), data.trainY:size(4)) # return data # end # return f import numpy as np import pickle as pkl import os def load(prefix): cacheF = prefix + '.pkl' if os.path.isfile(cacheF): print('olivetti: loading from cache') with open(cacheF, 'rb') as f: d = pkl.load(f) else: print('olivetti: Creating from txt') data = np.loadtxt(prefix + '.raw') data = data.T.reshape((400,64,64,1)).transpose((0,2,1,3))/255. d = {'trainX': data[0:350,:,32:64,:], 'trainY': data[0:350,:,0:32,:], 'testX': data[350:400,:,32:64,:], 'testY': data[350:400,:,0:32,:]} with open(cacheF, 'wb') as f: pkl.dump(d, f) return d
en
0.252955
# local image = require 'image' # local H = require 'icnn.helper' # function f(inputFile, hidden, nTraining) # local data = {} # data.all = H.loadtxt(inputFile) # :t():clone() # :view(400, 1, 64, 64) # :transpose(3, 4):clone() # :div(255) # local topI = {{}, {}, {1, 32}, {1, 64}} # local bottomI = {{}, {}, {33, 64}, {1, 64}} # local leftI = {{}, {}, {1, 64}, {1, 32}} # local rightI = {{}, {}, {1, 64}, {33, 64}} # local trainI = {{1, nTraining}} # local testI = {{nTraining+1, 400}} # if hidden == 'left' then # data.inputSz = torch.IntTensor{1, 64, 32} # data.outputSz = data.inputSz # data.trainX = cast(data.all[trainI][rightI]) # data.trainY = cast(data.all[trainI][leftI]) # data.testX = cast(data.all[testI][rightI]) # data.testY = cast(data.all[testI][leftI]) # data.trainXflip = cast(image.hflip(data.all[trainI][rightI])) # data.testXflip = cast(image.hflip(data.all[testI][rightI])) # elseif hidden == 'bottom' then # data.inputSz = torch.IntTensor{1, 32, 64} # data.outputSz = data.inputSz # data.trainX = cast(data.all[trainI][topI]) # data.trainY = cast(data.all[trainI][bottomI]) # data.testX = cast(data.all[testI][topI]) # data.testY = cast(data.all[testI][bottomI]) # else # assert(false) # end # data.testYflat = data.testY:clone():view(data.testY:size(1), -1) # data.avgY = data.trainY:mean(1):view( # data.trainY:size(2), data.trainY:size(3), data.trainY:size(4)) # return data # end # return f
2.058031
2
examples/juniper/delete-config-jnpr.py
sebastianw/ncclient
1
6628271
#!/usr/bin/env python from ncclient import manager from ncclient.xml_ import * def connect(host, port, user, password, source): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, hostkey_verify=False) template = """<system><scripts><commit><file delete="delete"><name>test.slax</name></file></commit></scripts></system>""" conn.lock() config = to_ele(template) send_config = conn.load_configuration(config=config) print send_config.tostring check_config = conn.validate() print check_config.tostring compare_config = conn.compare_configuration() print compare_config.tostring conn.commit() conn.unlock() conn.close_session() if __name__ == '__main__': connect('router', 830, 'netconf', 'juniper!', 'candidate')
#!/usr/bin/env python from ncclient import manager from ncclient.xml_ import * def connect(host, port, user, password, source): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, hostkey_verify=False) template = """<system><scripts><commit><file delete="delete"><name>test.slax</name></file></commit></scripts></system>""" conn.lock() config = to_ele(template) send_config = conn.load_configuration(config=config) print send_config.tostring check_config = conn.validate() print check_config.tostring compare_config = conn.compare_configuration() print compare_config.tostring conn.commit() conn.unlock() conn.close_session() if __name__ == '__main__': connect('router', 830, 'netconf', 'juniper!', 'candidate')
en
0.270589
#!/usr/bin/env python <system><scripts><commit><file delete="delete"><name>test.slax</name></file></commit></scripts></system>
2.063141
2
tests/test_hlr.py
Notificore/notificore-python
0
6628272
#!/usr/bin/env python3 # pylint: disable=import-error import pytest import notificore_restapi as api @pytest.fixture def requester(): # noinspection PyPackageRequirements from tests.settings import API_KEY return api.HLRAPI(config=dict(api_key=API_KEY)) # noinspection PyShadowingNames @pytest.fixture def sender_mul(requester): hlrls = [api.HLRL(msisdn=380960000000), api.HLRL(msisdn=380960000001)] return requester, requester.send(hlrls) AMOUNT = 15 # noinspection PyShadowingNames @pytest.fixture def sender_mul_by_internal(requester): beg_msisdn = 380960000000 for msisdn in range(beg_msisdn, beg_msisdn + AMOUNT): requester.add_hlrl(msisdn) requester.send() return requester # noinspection PyShadowingNames def test_prices(requester): response_price_list = requester.get_prices() assert isinstance(response_price_list, list) assert response_price_list # assertion if empty list attributes = ['country', 'country_name', 'currency', 'mcc', 'price', 'type'] for price in response_price_list: for attribute in attributes: assert price.get(attribute) # noinspection PyShadowingNames def test_send(requester): with pytest.raises(api.APIError) as exception_info: requester.send() assert exception_info.value.code == 64 # '64': Invalid request payload # noinspection PyShadowingNames def test_add_and_clear(sender_mul_by_internal): assert len(sender_mul_by_internal.hlrls) == AMOUNT assert isinstance(sender_mul_by_internal.hlrls, list) sender_mul_by_internal.clear_hlrls() assert not sender_mul_by_internal.hlrls def test_hlrl(): hlrl = api.HLRL(msisdn=380960000000) assert len(hlrl) == 2 attributes = ['msisdn', 'reference'] for attribute in attributes: assert hlrl.get(attribute) RESPOND_ATTRIBUTES = ['error', 'id', 'reference', 'callback_url', 'msisdn', 'tariff_code', 'currency', 'price'] # noinspection PyShadowingNames def test_send_mul(requester): hlrls = [api.HLRL(msisdn=380960000000), api.HLRL(msisdn=380960000001)] response = requester.send(hlrls) assert response.get('result') assert len(response.get('result')) == 2 for response_ in response['result']: for attribute in RESPOND_ATTRIBUTES: # need to check for None, else false-positive assertion on error==0 assert response_.get(attribute) is not None STATUS_ATTRIBUTES = ['brand', 'createdDatetime', 'error', 'errorDescription', 'id', 'msisdn', 'name', 'name_en', 'name_ru', 'network', 'reference', 'status', 'statusDatetime'] DETAILS_ATTRIBUTES = ['imsi', 'location_msc', 'ported', 'roaming'] # noinspection PyShadowingNames def test_getstatus(sender_mul): requester, response = sender_mul respond_ref, respond_id = (response['result'][0]['reference'], response['result'][0]['id']) status_by_id = requester.get_status(respond_id) status_by_ref = requester.get_status(respond_ref) for status in [status_by_id, status_by_ref]: assert status is not None for attribute in STATUS_ATTRIBUTES: assert status.get(attribute) is not None if status.get('details'): for attribute in DETAILS_ATTRIBUTES: assert status['details'].get(attribute) is not None # noinspection PyShadowingNames def test_getstatus_for_obj(requester): hlrl = api.HLRL(msisdn=380960000000) hlrl['result'] = requester.send(hlrl) status = requester.get_status(hlrl) for attribute in STATUS_ATTRIBUTES: assert status.get(attribute) is not None # noinspection PyShadowingNames def test_getstatus_for_obj_without_result(requester): hlrl = api.HLRL(msisdn=380960000000) status = requester.get_status(hlrl) for attribute in STATUS_ATTRIBUTES: assert status.get(attribute) is not None # noinspection PyShadowingNames def test_getstatus_for_internal_hlrls(sender_mul_by_internal): sender_mul_by_internal.get_status() for hlrl in sender_mul_by_internal.hlrls: assert hlrl.get('status') for attribute in STATUS_ATTRIBUTES: assert hlrl['status'].get(attribute) is not None # noinspection PyShadowingNames def test_getstatus_for_internal_hlrls_partly(sender_mul_by_internal): sender_mul_by_internal.get_status() sender_mul_by_internal.hlrls[-5] = api.HLRL(msisdn=380960000000) sender_mul_by_internal.get_status() for hlrl in sender_mul_by_internal.hlrls: assert hlrl.get('status') for attribute in STATUS_ATTRIBUTES: assert hlrl['status'].get(attribute) is not None
#!/usr/bin/env python3 # pylint: disable=import-error import pytest import notificore_restapi as api @pytest.fixture def requester(): # noinspection PyPackageRequirements from tests.settings import API_KEY return api.HLRAPI(config=dict(api_key=API_KEY)) # noinspection PyShadowingNames @pytest.fixture def sender_mul(requester): hlrls = [api.HLRL(msisdn=380960000000), api.HLRL(msisdn=380960000001)] return requester, requester.send(hlrls) AMOUNT = 15 # noinspection PyShadowingNames @pytest.fixture def sender_mul_by_internal(requester): beg_msisdn = 380960000000 for msisdn in range(beg_msisdn, beg_msisdn + AMOUNT): requester.add_hlrl(msisdn) requester.send() return requester # noinspection PyShadowingNames def test_prices(requester): response_price_list = requester.get_prices() assert isinstance(response_price_list, list) assert response_price_list # assertion if empty list attributes = ['country', 'country_name', 'currency', 'mcc', 'price', 'type'] for price in response_price_list: for attribute in attributes: assert price.get(attribute) # noinspection PyShadowingNames def test_send(requester): with pytest.raises(api.APIError) as exception_info: requester.send() assert exception_info.value.code == 64 # '64': Invalid request payload # noinspection PyShadowingNames def test_add_and_clear(sender_mul_by_internal): assert len(sender_mul_by_internal.hlrls) == AMOUNT assert isinstance(sender_mul_by_internal.hlrls, list) sender_mul_by_internal.clear_hlrls() assert not sender_mul_by_internal.hlrls def test_hlrl(): hlrl = api.HLRL(msisdn=380960000000) assert len(hlrl) == 2 attributes = ['msisdn', 'reference'] for attribute in attributes: assert hlrl.get(attribute) RESPOND_ATTRIBUTES = ['error', 'id', 'reference', 'callback_url', 'msisdn', 'tariff_code', 'currency', 'price'] # noinspection PyShadowingNames def test_send_mul(requester): hlrls = [api.HLRL(msisdn=380960000000), api.HLRL(msisdn=380960000001)] response = requester.send(hlrls) assert response.get('result') assert len(response.get('result')) == 2 for response_ in response['result']: for attribute in RESPOND_ATTRIBUTES: # need to check for None, else false-positive assertion on error==0 assert response_.get(attribute) is not None STATUS_ATTRIBUTES = ['brand', 'createdDatetime', 'error', 'errorDescription', 'id', 'msisdn', 'name', 'name_en', 'name_ru', 'network', 'reference', 'status', 'statusDatetime'] DETAILS_ATTRIBUTES = ['imsi', 'location_msc', 'ported', 'roaming'] # noinspection PyShadowingNames def test_getstatus(sender_mul): requester, response = sender_mul respond_ref, respond_id = (response['result'][0]['reference'], response['result'][0]['id']) status_by_id = requester.get_status(respond_id) status_by_ref = requester.get_status(respond_ref) for status in [status_by_id, status_by_ref]: assert status is not None for attribute in STATUS_ATTRIBUTES: assert status.get(attribute) is not None if status.get('details'): for attribute in DETAILS_ATTRIBUTES: assert status['details'].get(attribute) is not None # noinspection PyShadowingNames def test_getstatus_for_obj(requester): hlrl = api.HLRL(msisdn=380960000000) hlrl['result'] = requester.send(hlrl) status = requester.get_status(hlrl) for attribute in STATUS_ATTRIBUTES: assert status.get(attribute) is not None # noinspection PyShadowingNames def test_getstatus_for_obj_without_result(requester): hlrl = api.HLRL(msisdn=380960000000) status = requester.get_status(hlrl) for attribute in STATUS_ATTRIBUTES: assert status.get(attribute) is not None # noinspection PyShadowingNames def test_getstatus_for_internal_hlrls(sender_mul_by_internal): sender_mul_by_internal.get_status() for hlrl in sender_mul_by_internal.hlrls: assert hlrl.get('status') for attribute in STATUS_ATTRIBUTES: assert hlrl['status'].get(attribute) is not None # noinspection PyShadowingNames def test_getstatus_for_internal_hlrls_partly(sender_mul_by_internal): sender_mul_by_internal.get_status() sender_mul_by_internal.hlrls[-5] = api.HLRL(msisdn=380960000000) sender_mul_by_internal.get_status() for hlrl in sender_mul_by_internal.hlrls: assert hlrl.get('status') for attribute in STATUS_ATTRIBUTES: assert hlrl['status'].get(attribute) is not None
en
0.34441
#!/usr/bin/env python3 # pylint: disable=import-error # noinspection PyPackageRequirements # noinspection PyShadowingNames # noinspection PyShadowingNames # noinspection PyShadowingNames # assertion if empty list # noinspection PyShadowingNames # '64': Invalid request payload # noinspection PyShadowingNames # noinspection PyShadowingNames # need to check for None, else false-positive assertion on error==0 # noinspection PyShadowingNames # noinspection PyShadowingNames # noinspection PyShadowingNames # noinspection PyShadowingNames # noinspection PyShadowingNames
1.97061
2
splunk_sdk/auth/auth_manager.py
splunk/splunk-cloud-sdk-python
12
6628273
<reponame>splunk/splunk-cloud-sdk-python # coding: utf-8 # Copyright © 2019 Splunk, Inc. # Licensed under the Apache License, Version 2.0 (the "License"): you may # not use this file except in compliance with the License. You may obtain # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import base64 import hashlib import json import jwt import os import urllib import time import uuid from datetime import datetime, timezone, timedelta from abc import ABC, abstractmethod from typing import Optional from splunk_sdk.common import REQUESTS_HOOK_NAME_RESPONSE import requests from requests import Response DEFAULT_HOST = "auth.scp.splunk.com" PATH_AUTHN = "/authn" PATH_AUTHORIZE = "/authorize" PATH_TOKEN = "/token" PATH_CSRFTOKEN = "/csrfToken" HEADERS_DEFAULT = { "Accept": "application/json", "Content-Type": "application/json"} HEADERS_URLENCODED = { "Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded"} DEFAULT_SCOPE = "openid email profile" DEFAULT_REFRESH_SCOPE = "openid offline_access email profile" class AuthnError(Exception): def __init__(self, message: str, response: Response): super().__init__(message) self._response = response @property def _response_body(self) -> Optional[dict]: if self._response is not None and self._response.text is not None: try: return self._response.json() except Exception: return None @property def server_error_description(self) -> Optional[str]: """ The message explaining the error from the server (if any)""" if self._response_body is not None: # FIXME(dan): # Work around for issue with IAC returning non-consistent keys # There is a bug filed already error_desc = self._response_body.get("error_description", None) if error_desc is not None: return error_desc return self._response_body.get("description") @property def status(self) -> Optional[str]: """ The status field from the payload body if supplied""" if self._response_body is not None: return self._response_body.get("status") @property def request_id(self) -> Optional[str]: """ The unique request ID if supplied by the service""" if self._response is not None: return self._response.headers.get("x-request-id") class AuthContext(object): """ TODO DOCS The AuthContext class... """ def __init__(self, token_type, access_token, expires_in, scope, id_token=None, refresh_token=None): self._token_type = token_type self._access_token = access_token self._expires_in = expires_in self._scope = scope self._id_token = id_token self._refresh_token = refresh_token self._created_at = datetime.now() @property def token_type(self) -> str: return self._token_type @token_type.setter def token_type(self, token_type: str): self._token_type = token_type @property def access_token(self) -> str: return self._access_token @access_token.setter def access_token(self, access_token: str): self._access_token = access_token @property def expires_in(self) -> int: return self._expires_in @expires_in.setter def expires_in(self, expires_in: int): self._expires_in = expires_in @property def scope(self) -> str: return self._scope @scope.setter def scope(self, scope: str): self._scope = scope @property def id_token(self) -> str: return self._id_token @id_token.setter def id_token(self, id_token: str): self._id_token = id_token @property def refresh_token(self) -> str: return self._refresh_token @refresh_token.setter def refresh_token(self, refresh_token: str): self._refresh_token = refresh_token def will_expire_within(self, seconds: int = 30): if self.expires_in: # If we don't have an expire time, presume that it never does. return (datetime.now() - self._created_at).total_seconds() > self.expires_in - seconds else: return False class AuthManager(ABC): """ The AuthManager class is a base class that manages different authentication flows. When creating an authorization manager, create a subclass that corresponds to the flow that you need for your app. """ def __init__(self, host, client_id, tenant=None, tenant_scoped=False, region=None, requests_hooks=None): self._host = host self._tenant = tenant self._tenant_scoped = tenant_scoped self._region = region self._client_id = client_id self._context = None self._requests_hooks = requests_hooks or [] def _get(self, url, headers=None, params=None): response = requests.get( url, headers=headers or HEADERS_DEFAULT, params=params, allow_redirects=False, hooks={REQUESTS_HOOK_NAME_RESPONSE: self._requests_hooks}) return response # Note: the requests module interprets the data param in an interesting # way, if its a dict, it will be url form encoded, if its a string it # will be posted in the body def _post(self, url, auth=None, headers=None, data=None, cookies=None): response = requests.post( url, auth=auth, headers=headers or HEADERS_DEFAULT, data=data, cookies=cookies, hooks={REQUESTS_HOOK_NAME_RESPONSE: self._requests_hooks}) return response def _url(self, path): scopedHost = self._host if self._tenant_scoped is True: if self._tenant is None: raise ValueError("Tenant is empty.") elif self._region is None: raise ValueError("Region is empty.") elif "token" in path and self._tenant != "system": scopedHost = self._tenant + "." + self._host # generate tenant scoped token path = "/" + self._tenant + path elif "token" in path and self._tenant == "system": scopedHost = "region-" + self._region + "." + self._host # generate system scoped token path = "/system" + path elif "authorize" in path and self._tenant != "system": scopedHost = self._tenant + "." + self._host elif "authorize" in path and self._tenant == "system": scopedHost = "region-" + self._region + "." + self._host elif "csrfToken" in path: scopedHost = "region-" + self._region + "." + self._host elif "authn" in path: scopedHost = "region-" + self._region + "." + self._host print("https://%s%s" % (scopedHost, path)) return "https://%s%s" % (scopedHost, path) @staticmethod def _parse_querystring(url): """Returns dict containing parsed query string params.""" if url is None: return None url = urllib.parse.urlparse(url) params = urllib.parse.parse_qs(url.query) params = dict(params) return params def _post_token(self, auth=None, **data): """POST ${basePath}/token, expect 200""" path = PATH_TOKEN response = self._post( self._url(path), auth=auth, headers=HEADERS_URLENCODED, data=data) if response.status_code != 200: raise AuthnError("Unable to post for token", response) return response @abstractmethod def authenticate(self) -> AuthContext: """ Makes the required calls to authorization endpoints and returns an `AuthContext` instance to use for subsequent calls to service endpoints. :return: The `AuthContext` instance. """ raise NotImplementedError @property def context(self): if self._context is None: self._context = self.authenticate() if self._context.will_expire_within(seconds=30): self._context = self.authenticate() return self._context class ClientAuthManager(AuthManager): """ Implements the Client Credentials auth flow. Client Credentials is used when an application is authorized to make calls on it's own behalf- in other words, there is not a human user associated with the request. For more details look to documentation for the identity service. """ # TODO: Host can be an optional value since it has a default def __init__(self, host, client_id, client_secret, scope="", tenant=None, tenant_scoped=False, region=None, requests_hooks=None): super().__init__(host, client_id, tenant, tenant_scoped, region, requests_hooks=requests_hooks) self._client_secret = client_secret self._scope = scope def authenticate(self): """Authenticate using the "client credentials" flow.""" if self._client_id is None: raise ValueError("missing client_id") if self._client_secret is None: raise ValueError("missing client_secret") if self._scope is None: raise ValueError("missing scope") data = {"grant_type": "client_credentials", "scope": self._scope} auth = (self._client_id, self._client_secret) response = self._post_token(auth, **data) if response.status_code != 200: raise AuthnError("Unable to authenticate. Check credentials.", response) return AuthContext(**response.json()) class PKCEAuthManager(AuthManager): """ This subclass of AuthManager handles the PKCE auth flow. PKCE should be used when an app is acting on behalf of a human user. Both the user and the app are authenticating themselves to the system- the user through username and password, the app through the client_id and redirect_uri. For more details, see identity service documentation. """ def __init__(self, host, client_id, redirect_uri, username, password, scope=DEFAULT_REFRESH_SCOPE, tenant=None, tenant_scoped=False, region=None, requests_hooks=None): super().__init__(host, client_id, tenant, tenant_scoped, region, requests_hooks=requests_hooks) self._redirect_uri = redirect_uri self._username = username self._password = password self._state = None self._scope = scope # Note: see https://tools.ietf.org/html/rfc7636#section-4.1 # code_verifier = a high-entropy cryptographic random STRING using the # unreserved characters [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~" # from Section 2.3 of [RFC3986], with a minimum length of 43 characters # and a maximum length of 128 characters. _SAFE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~" @staticmethod def _create_code_verifier(n): """Returns a code verifier of length 'n', where 43 <= n <= 128.""" assert 43 <= n <= 128, "Code verifier length must be between the values of 43 and 128 inclusive" result = bytearray(os.urandom(n)) result = base64.urlsafe_b64encode(result) result = result.rstrip('='.encode('utf-8')) # strip b64 padding return result # Note: see https://tools.ietf.org/html/rfc7636#section-4.2 # code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) @staticmethod def _create_code_challenge(cv): """Returns a code challenge based on the given code verifier.""" result = hashlib.sha256(cv).digest() result = base64.urlsafe_b64encode(result) result = result.rstrip('='.encode('utf-8')) # strip b64 padding return result def _get_session_token(self, username, password): """Returns a one-time session token by authenticating using the (extended) "primary" endpoint (/authn).""" csrfToken, cookies = self._get_csrf_token() if csrfToken is None: return None result = self._authenticate_user(username, password, csrfToken, cookies) if result is None: return None return result.get("sessionToken", None) def _get_csrf_token(self): """Returns a CSRF token to be passed into /authn""" response = self._get(self._url(PATH_CSRFTOKEN)) if response.status_code != 200: raise AuthnError("Authentication failed.", response) csrfTokenCookie = self._get_cookie(response.cookies, "csrf") if csrfTokenCookie is None: raise AuthnError("no CSRF token from /csrfToken", response) return csrfTokenCookie.value, response.cookies def _get_cookie(self, cookies, name): """Returns the specified cookie""" for cookie in cookies: if cookie.name == name: return cookie return None def _authenticate_user(self, username, password, csrfToken, cookies): """Authenticate using the (extended) "primary" method.""" data = {"username": username, "password": password, "csrfToken": csrfToken} response = self._post(self._url(PATH_AUTHN), data=json.dumps(data), cookies=cookies) if response.status_code != 200: print("RESPONSE") print(response) raise AuthnError("Authentication failed.", response) result = response.json() status = result.get("status", None) if status is None: raise AuthnError("no response status from /authn", response) if status != "SUCCESS": # eg: LOCKED_OUT raise AuthnError("authentication failed: %s" % status, response) return result def _get_authorization_code(self, **params): """GET ${basePath}/authorize, expect 302 (redirect)""" path = PATH_AUTHORIZE response = self._get(self._url(path), params=params) if response.status_code != 302: raise AuthnError("Unable to obtain authorization code. Check client_id, redirect_uri, and scope", response) location = response.headers.get("location", None) if location is None: raise AuthnError("Unable to obtain authorization code. Check client_id, redirect_uri, and scope", response) params = self._parse_querystring(location) value = params.get("code", None) if value is None: raise AuthnError("Unable to obtain authorization code. Check client_id, redirect_uri, and scope", response) assert value and len(value) == 1 return value[0] def validate(self): if self._client_id is None: raise ValueError("missing client_id") if self._redirect_uri is None: raise ValueError("missing redirect_uri") def authenticate(self): """Authenticate with the (extended) "authorization code with pkce" flow.""" self.validate() # retrieve one time session token session_token = self._get_session_token(self._username, self._password) cv = self._create_code_verifier(50) cc = self._create_code_challenge(cv) # request authorization code auth_code = self._get_authorization_code( client_id=self._client_id, code_challenge=cc.decode("utf-8"), code_challenge_method="S256", nonce="none", redirect_uri=self._redirect_uri, response_type="code", scope=self._scope, session_token=session_token, state=self._state or str(time.time()) ) # exchange authorization code for token(s) response = self._post_token( client_id=self._client_id, code=auth_code, code_verifier=cv, grant_type="authorization_code", redirect_uri=self._redirect_uri ) if response.status_code != 200: raise AuthnError("Unable to exchange authorization code for a token", response) return AuthContext(**response.json()) class TokenAuthManager(AuthManager): """ TokenAuthManager is used for when you have a token that is obtained from a source other than the SDK. When the token expires, there is no way to refresh it. """ def __init__(self, access_token, token_type='Bearer', expires_in=None, scope=None, id_token=None, refresh_token=None, requests_hooks=None): super().__init__(None, None, requests_hooks=requests_hooks) self.access_token = access_token self.token_type = token_type self.expires_in = expires_in self.scope = scope self.id_token = id_token self.refresh_token = refresh_token self._context = AuthContext(token_type=self.token_type, access_token=self.access_token, expires_in=self.expires_in, scope=self.scope, id_token=self.id_token, refresh_token=self.refresh_token) def authenticate(self) -> AuthContext: return self._context class RefreshTokenAuthManager(AuthManager): def __init__(self, client_id, refresh_token, host, scope="openid", tenant=None, tenant_scoped=False, region=None, requests_hooks=None): super().__init__(host, client_id, tenant, tenant_scoped, region, requests_hooks=requests_hooks) self._refresh_token = refresh_token self._scope = scope def authenticate(self): """Authenticate using the OAuth refresh_token grant type.""" client_id = self._client_id if client_id is None: raise ValueError("missing client_id") data = { "client_id": client_id, "grant_type": "refresh_token", "refresh_token": self._refresh_token, "scope": self._scope } response = self._post_token(**data) return AuthContext(**response.json()) class ServicePrincipalAuthManager(AuthManager): def __init__(self, host, principal_name, key, kid, algorithm="ES256", tenant=None, tenant_scoped=False, region=None, **kwargs): """ Creates an AuthManager that uses Service Principals to authenticate. principal_name is the principal_name of the authenticating service principal key is the PEM formatted private key registered with the service principal kid is the key_id of `key` algorithm is the algorithm that generated `key` """ super().__init__(host=host, client_id=None, tenant=tenant, tenant_scoped=tenant_scoped, region=region, **kwargs) self._principal_name = principal_name self._key = key self._kid = kid self._algorithm = algorithm def authenticate(self): """Authenticate using the "client assertion" flow.""" if not self._principal_name: raise ValueError("missing principal_name") if not self._key: raise ValueError("missing key") if not self._kid: raise ValueError("missing kid") if not self._algorithm: raise ValueError("missing algorithm") # Client assertion expires in 10 minutes ten_minutes_from_now = datetime.now(timezone.utc) + timedelta(minutes=10) jwt_payload = {"sub": self._principal_name, "iss": self._principal_name, "jti": str(uuid.uuid4()), "exp": int(ten_minutes_from_now.timestamp()), "aud": [self._url(PATH_TOKEN)]} client_assertion = jwt.encode(payload=jwt_payload, key=self._key, algorithm=self._algorithm, headers={"kid": self._kid}) data = {"grant_type": "client_credentials", "client_assertion": client_assertion.decode("utf-8"), "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"} response = self._post_token(**data) if response.status_code != 200: raise AuthnError("Unable to authenticate. Check credentials.", response) return AuthContext(**response.json())
# coding: utf-8 # Copyright © 2019 Splunk, Inc. # Licensed under the Apache License, Version 2.0 (the "License"): you may # not use this file except in compliance with the License. You may obtain # a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import base64 import hashlib import json import jwt import os import urllib import time import uuid from datetime import datetime, timezone, timedelta from abc import ABC, abstractmethod from typing import Optional from splunk_sdk.common import REQUESTS_HOOK_NAME_RESPONSE import requests from requests import Response DEFAULT_HOST = "auth.scp.splunk.com" PATH_AUTHN = "/authn" PATH_AUTHORIZE = "/authorize" PATH_TOKEN = "/token" PATH_CSRFTOKEN = "/csrfToken" HEADERS_DEFAULT = { "Accept": "application/json", "Content-Type": "application/json"} HEADERS_URLENCODED = { "Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded"} DEFAULT_SCOPE = "openid email profile" DEFAULT_REFRESH_SCOPE = "openid offline_access email profile" class AuthnError(Exception): def __init__(self, message: str, response: Response): super().__init__(message) self._response = response @property def _response_body(self) -> Optional[dict]: if self._response is not None and self._response.text is not None: try: return self._response.json() except Exception: return None @property def server_error_description(self) -> Optional[str]: """ The message explaining the error from the server (if any)""" if self._response_body is not None: # FIXME(dan): # Work around for issue with IAC returning non-consistent keys # There is a bug filed already error_desc = self._response_body.get("error_description", None) if error_desc is not None: return error_desc return self._response_body.get("description") @property def status(self) -> Optional[str]: """ The status field from the payload body if supplied""" if self._response_body is not None: return self._response_body.get("status") @property def request_id(self) -> Optional[str]: """ The unique request ID if supplied by the service""" if self._response is not None: return self._response.headers.get("x-request-id") class AuthContext(object): """ TODO DOCS The AuthContext class... """ def __init__(self, token_type, access_token, expires_in, scope, id_token=None, refresh_token=None): self._token_type = token_type self._access_token = access_token self._expires_in = expires_in self._scope = scope self._id_token = id_token self._refresh_token = refresh_token self._created_at = datetime.now() @property def token_type(self) -> str: return self._token_type @token_type.setter def token_type(self, token_type: str): self._token_type = token_type @property def access_token(self) -> str: return self._access_token @access_token.setter def access_token(self, access_token: str): self._access_token = access_token @property def expires_in(self) -> int: return self._expires_in @expires_in.setter def expires_in(self, expires_in: int): self._expires_in = expires_in @property def scope(self) -> str: return self._scope @scope.setter def scope(self, scope: str): self._scope = scope @property def id_token(self) -> str: return self._id_token @id_token.setter def id_token(self, id_token: str): self._id_token = id_token @property def refresh_token(self) -> str: return self._refresh_token @refresh_token.setter def refresh_token(self, refresh_token: str): self._refresh_token = refresh_token def will_expire_within(self, seconds: int = 30): if self.expires_in: # If we don't have an expire time, presume that it never does. return (datetime.now() - self._created_at).total_seconds() > self.expires_in - seconds else: return False class AuthManager(ABC): """ The AuthManager class is a base class that manages different authentication flows. When creating an authorization manager, create a subclass that corresponds to the flow that you need for your app. """ def __init__(self, host, client_id, tenant=None, tenant_scoped=False, region=None, requests_hooks=None): self._host = host self._tenant = tenant self._tenant_scoped = tenant_scoped self._region = region self._client_id = client_id self._context = None self._requests_hooks = requests_hooks or [] def _get(self, url, headers=None, params=None): response = requests.get( url, headers=headers or HEADERS_DEFAULT, params=params, allow_redirects=False, hooks={REQUESTS_HOOK_NAME_RESPONSE: self._requests_hooks}) return response # Note: the requests module interprets the data param in an interesting # way, if its a dict, it will be url form encoded, if its a string it # will be posted in the body def _post(self, url, auth=None, headers=None, data=None, cookies=None): response = requests.post( url, auth=auth, headers=headers or HEADERS_DEFAULT, data=data, cookies=cookies, hooks={REQUESTS_HOOK_NAME_RESPONSE: self._requests_hooks}) return response def _url(self, path): scopedHost = self._host if self._tenant_scoped is True: if self._tenant is None: raise ValueError("Tenant is empty.") elif self._region is None: raise ValueError("Region is empty.") elif "token" in path and self._tenant != "system": scopedHost = self._tenant + "." + self._host # generate tenant scoped token path = "/" + self._tenant + path elif "token" in path and self._tenant == "system": scopedHost = "region-" + self._region + "." + self._host # generate system scoped token path = "/system" + path elif "authorize" in path and self._tenant != "system": scopedHost = self._tenant + "." + self._host elif "authorize" in path and self._tenant == "system": scopedHost = "region-" + self._region + "." + self._host elif "csrfToken" in path: scopedHost = "region-" + self._region + "." + self._host elif "authn" in path: scopedHost = "region-" + self._region + "." + self._host print("https://%s%s" % (scopedHost, path)) return "https://%s%s" % (scopedHost, path) @staticmethod def _parse_querystring(url): """Returns dict containing parsed query string params.""" if url is None: return None url = urllib.parse.urlparse(url) params = urllib.parse.parse_qs(url.query) params = dict(params) return params def _post_token(self, auth=None, **data): """POST ${basePath}/token, expect 200""" path = PATH_TOKEN response = self._post( self._url(path), auth=auth, headers=HEADERS_URLENCODED, data=data) if response.status_code != 200: raise AuthnError("Unable to post for token", response) return response @abstractmethod def authenticate(self) -> AuthContext: """ Makes the required calls to authorization endpoints and returns an `AuthContext` instance to use for subsequent calls to service endpoints. :return: The `AuthContext` instance. """ raise NotImplementedError @property def context(self): if self._context is None: self._context = self.authenticate() if self._context.will_expire_within(seconds=30): self._context = self.authenticate() return self._context class ClientAuthManager(AuthManager): """ Implements the Client Credentials auth flow. Client Credentials is used when an application is authorized to make calls on it's own behalf- in other words, there is not a human user associated with the request. For more details look to documentation for the identity service. """ # TODO: Host can be an optional value since it has a default def __init__(self, host, client_id, client_secret, scope="", tenant=None, tenant_scoped=False, region=None, requests_hooks=None): super().__init__(host, client_id, tenant, tenant_scoped, region, requests_hooks=requests_hooks) self._client_secret = client_secret self._scope = scope def authenticate(self): """Authenticate using the "client credentials" flow.""" if self._client_id is None: raise ValueError("missing client_id") if self._client_secret is None: raise ValueError("missing client_secret") if self._scope is None: raise ValueError("missing scope") data = {"grant_type": "client_credentials", "scope": self._scope} auth = (self._client_id, self._client_secret) response = self._post_token(auth, **data) if response.status_code != 200: raise AuthnError("Unable to authenticate. Check credentials.", response) return AuthContext(**response.json()) class PKCEAuthManager(AuthManager): """ This subclass of AuthManager handles the PKCE auth flow. PKCE should be used when an app is acting on behalf of a human user. Both the user and the app are authenticating themselves to the system- the user through username and password, the app through the client_id and redirect_uri. For more details, see identity service documentation. """ def __init__(self, host, client_id, redirect_uri, username, password, scope=DEFAULT_REFRESH_SCOPE, tenant=None, tenant_scoped=False, region=None, requests_hooks=None): super().__init__(host, client_id, tenant, tenant_scoped, region, requests_hooks=requests_hooks) self._redirect_uri = redirect_uri self._username = username self._password = password self._state = None self._scope = scope # Note: see https://tools.ietf.org/html/rfc7636#section-4.1 # code_verifier = a high-entropy cryptographic random STRING using the # unreserved characters [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~" # from Section 2.3 of [RFC3986], with a minimum length of 43 characters # and a maximum length of 128 characters. _SAFE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~" @staticmethod def _create_code_verifier(n): """Returns a code verifier of length 'n', where 43 <= n <= 128.""" assert 43 <= n <= 128, "Code verifier length must be between the values of 43 and 128 inclusive" result = bytearray(os.urandom(n)) result = base64.urlsafe_b64encode(result) result = result.rstrip('='.encode('utf-8')) # strip b64 padding return result # Note: see https://tools.ietf.org/html/rfc7636#section-4.2 # code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) @staticmethod def _create_code_challenge(cv): """Returns a code challenge based on the given code verifier.""" result = hashlib.sha256(cv).digest() result = base64.urlsafe_b64encode(result) result = result.rstrip('='.encode('utf-8')) # strip b64 padding return result def _get_session_token(self, username, password): """Returns a one-time session token by authenticating using the (extended) "primary" endpoint (/authn).""" csrfToken, cookies = self._get_csrf_token() if csrfToken is None: return None result = self._authenticate_user(username, password, csrfToken, cookies) if result is None: return None return result.get("sessionToken", None) def _get_csrf_token(self): """Returns a CSRF token to be passed into /authn""" response = self._get(self._url(PATH_CSRFTOKEN)) if response.status_code != 200: raise AuthnError("Authentication failed.", response) csrfTokenCookie = self._get_cookie(response.cookies, "csrf") if csrfTokenCookie is None: raise AuthnError("no CSRF token from /csrfToken", response) return csrfTokenCookie.value, response.cookies def _get_cookie(self, cookies, name): """Returns the specified cookie""" for cookie in cookies: if cookie.name == name: return cookie return None def _authenticate_user(self, username, password, csrfToken, cookies): """Authenticate using the (extended) "primary" method.""" data = {"username": username, "password": password, "csrfToken": csrfToken} response = self._post(self._url(PATH_AUTHN), data=json.dumps(data), cookies=cookies) if response.status_code != 200: print("RESPONSE") print(response) raise AuthnError("Authentication failed.", response) result = response.json() status = result.get("status", None) if status is None: raise AuthnError("no response status from /authn", response) if status != "SUCCESS": # eg: LOCKED_OUT raise AuthnError("authentication failed: %s" % status, response) return result def _get_authorization_code(self, **params): """GET ${basePath}/authorize, expect 302 (redirect)""" path = PATH_AUTHORIZE response = self._get(self._url(path), params=params) if response.status_code != 302: raise AuthnError("Unable to obtain authorization code. Check client_id, redirect_uri, and scope", response) location = response.headers.get("location", None) if location is None: raise AuthnError("Unable to obtain authorization code. Check client_id, redirect_uri, and scope", response) params = self._parse_querystring(location) value = params.get("code", None) if value is None: raise AuthnError("Unable to obtain authorization code. Check client_id, redirect_uri, and scope", response) assert value and len(value) == 1 return value[0] def validate(self): if self._client_id is None: raise ValueError("missing client_id") if self._redirect_uri is None: raise ValueError("missing redirect_uri") def authenticate(self): """Authenticate with the (extended) "authorization code with pkce" flow.""" self.validate() # retrieve one time session token session_token = self._get_session_token(self._username, self._password) cv = self._create_code_verifier(50) cc = self._create_code_challenge(cv) # request authorization code auth_code = self._get_authorization_code( client_id=self._client_id, code_challenge=cc.decode("utf-8"), code_challenge_method="S256", nonce="none", redirect_uri=self._redirect_uri, response_type="code", scope=self._scope, session_token=session_token, state=self._state or str(time.time()) ) # exchange authorization code for token(s) response = self._post_token( client_id=self._client_id, code=auth_code, code_verifier=cv, grant_type="authorization_code", redirect_uri=self._redirect_uri ) if response.status_code != 200: raise AuthnError("Unable to exchange authorization code for a token", response) return AuthContext(**response.json()) class TokenAuthManager(AuthManager): """ TokenAuthManager is used for when you have a token that is obtained from a source other than the SDK. When the token expires, there is no way to refresh it. """ def __init__(self, access_token, token_type='Bearer', expires_in=None, scope=None, id_token=None, refresh_token=None, requests_hooks=None): super().__init__(None, None, requests_hooks=requests_hooks) self.access_token = access_token self.token_type = token_type self.expires_in = expires_in self.scope = scope self.id_token = id_token self.refresh_token = refresh_token self._context = AuthContext(token_type=self.token_type, access_token=self.access_token, expires_in=self.expires_in, scope=self.scope, id_token=self.id_token, refresh_token=self.refresh_token) def authenticate(self) -> AuthContext: return self._context class RefreshTokenAuthManager(AuthManager): def __init__(self, client_id, refresh_token, host, scope="openid", tenant=None, tenant_scoped=False, region=None, requests_hooks=None): super().__init__(host, client_id, tenant, tenant_scoped, region, requests_hooks=requests_hooks) self._refresh_token = refresh_token self._scope = scope def authenticate(self): """Authenticate using the OAuth refresh_token grant type.""" client_id = self._client_id if client_id is None: raise ValueError("missing client_id") data = { "client_id": client_id, "grant_type": "refresh_token", "refresh_token": self._refresh_token, "scope": self._scope } response = self._post_token(**data) return AuthContext(**response.json()) class ServicePrincipalAuthManager(AuthManager): def __init__(self, host, principal_name, key, kid, algorithm="ES256", tenant=None, tenant_scoped=False, region=None, **kwargs): """ Creates an AuthManager that uses Service Principals to authenticate. principal_name is the principal_name of the authenticating service principal key is the PEM formatted private key registered with the service principal kid is the key_id of `key` algorithm is the algorithm that generated `key` """ super().__init__(host=host, client_id=None, tenant=tenant, tenant_scoped=tenant_scoped, region=region, **kwargs) self._principal_name = principal_name self._key = key self._kid = kid self._algorithm = algorithm def authenticate(self): """Authenticate using the "client assertion" flow.""" if not self._principal_name: raise ValueError("missing principal_name") if not self._key: raise ValueError("missing key") if not self._kid: raise ValueError("missing kid") if not self._algorithm: raise ValueError("missing algorithm") # Client assertion expires in 10 minutes ten_minutes_from_now = datetime.now(timezone.utc) + timedelta(minutes=10) jwt_payload = {"sub": self._principal_name, "iss": self._principal_name, "jti": str(uuid.uuid4()), "exp": int(ten_minutes_from_now.timestamp()), "aud": [self._url(PATH_TOKEN)]} client_assertion = jwt.encode(payload=jwt_payload, key=self._key, algorithm=self._algorithm, headers={"kid": self._kid}) data = {"grant_type": "client_credentials", "client_assertion": client_assertion.decode("utf-8"), "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"} response = self._post_token(**data) if response.status_code != 200: raise AuthnError("Unable to authenticate. Check credentials.", response) return AuthContext(**response.json())
en
0.813178
# coding: utf-8 # Copyright © 2019 Splunk, 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. The message explaining the error from the server (if any) # FIXME(dan): # Work around for issue with IAC returning non-consistent keys # There is a bug filed already The status field from the payload body if supplied The unique request ID if supplied by the service TODO DOCS The AuthContext class... # If we don't have an expire time, presume that it never does. The AuthManager class is a base class that manages different authentication flows. When creating an authorization manager, create a subclass that corresponds to the flow that you need for your app. # Note: the requests module interprets the data param in an interesting # way, if its a dict, it will be url form encoded, if its a string it # will be posted in the body # generate tenant scoped token # generate system scoped token Returns dict containing parsed query string params. POST ${basePath}/token, expect 200 Makes the required calls to authorization endpoints and returns an `AuthContext` instance to use for subsequent calls to service endpoints. :return: The `AuthContext` instance. Implements the Client Credentials auth flow. Client Credentials is used when an application is authorized to make calls on it's own behalf- in other words, there is not a human user associated with the request. For more details look to documentation for the identity service. # TODO: Host can be an optional value since it has a default Authenticate using the "client credentials" flow. This subclass of AuthManager handles the PKCE auth flow. PKCE should be used when an app is acting on behalf of a human user. Both the user and the app are authenticating themselves to the system- the user through username and password, the app through the client_id and redirect_uri. For more details, see identity service documentation. # Note: see https://tools.ietf.org/html/rfc7636#section-4.1 # code_verifier = a high-entropy cryptographic random STRING using the # unreserved characters [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~" # from Section 2.3 of [RFC3986], with a minimum length of 43 characters # and a maximum length of 128 characters. Returns a code verifier of length 'n', where 43 <= n <= 128. # strip b64 padding # Note: see https://tools.ietf.org/html/rfc7636#section-4.2 # code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) Returns a code challenge based on the given code verifier. # strip b64 padding Returns a one-time session token by authenticating using the (extended) "primary" endpoint (/authn). Returns a CSRF token to be passed into /authn Returns the specified cookie Authenticate using the (extended) "primary" method. # eg: LOCKED_OUT GET ${basePath}/authorize, expect 302 (redirect) Authenticate with the (extended) "authorization code with pkce" flow. # retrieve one time session token # request authorization code # exchange authorization code for token(s) TokenAuthManager is used for when you have a token that is obtained from a source other than the SDK. When the token expires, there is no way to refresh it. Authenticate using the OAuth refresh_token grant type. Creates an AuthManager that uses Service Principals to authenticate. principal_name is the principal_name of the authenticating service principal key is the PEM formatted private key registered with the service principal kid is the key_id of `key` algorithm is the algorithm that generated `key` Authenticate using the "client assertion" flow. # Client assertion expires in 10 minutes
2.186488
2
app/config.py
LeandroBarone/WeCanTweetTogether
3
6628274
<gh_stars>1-10 import tweepy import logging import os logger = logging.getLogger() def create_api(): # Cargamos los datos secretos desde las variables de entorno consumer_key = os.getenv("CONSUMER_KEY") consumer_secret = os.getenv("CONSUMER_SECRET") access_token = os.getenv("ACCESS_TOKEN") access_token_secret = os.getenv("ACCESS_TOKEN_SECRET") # Nos autenticamos con los datos secretos auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) # Creamos el objeto para interactuar con la API api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) # Verificamos si las credenciales son válidas try: api.verify_credentials() except Exception as e: logger.error("Las credenciales no son correctas.", exc_info=True) raise e logger.info("Credenciales correctas.") return api
import tweepy import logging import os logger = logging.getLogger() def create_api(): # Cargamos los datos secretos desde las variables de entorno consumer_key = os.getenv("CONSUMER_KEY") consumer_secret = os.getenv("CONSUMER_SECRET") access_token = os.getenv("ACCESS_TOKEN") access_token_secret = os.getenv("ACCESS_TOKEN_SECRET") # Nos autenticamos con los datos secretos auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) # Creamos el objeto para interactuar con la API api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) # Verificamos si las credenciales son válidas try: api.verify_credentials() except Exception as e: logger.error("Las credenciales no son correctas.", exc_info=True) raise e logger.info("Credenciales correctas.") return api
es
0.943736
# Cargamos los datos secretos desde las variables de entorno # Nos autenticamos con los datos secretos # Creamos el objeto para interactuar con la API # Verificamos si las credenciales son válidas
2.697683
3
tests/columns/test_reference.py
knguyen5/piccolo
0
6628275
<filename>tests/columns/test_reference.py """ Most of the tests for piccolo/columns/reference.py are covered in piccolo/columns/test_foreignkey.py """ from unittest import TestCase from piccolo.columns.reference import LazyTableReference class TestLazyTableReference(TestCase): def test_init(self): """ A ``LazyTableReference`` must be passed either an ``app_name`` or ``module_path`` argument. """ with self.assertRaises(ValueError): LazyTableReference(table_class_name="Manager") with self.assertRaises(ValueError): LazyTableReference( table_class_name="Manager", app_name="example_app", module_path="tests.example_apps.music.tables", ) # Shouldn't raise exceptions: LazyTableReference( table_class_name="Manager", app_name="example_app", ) LazyTableReference( table_class_name="Manager", module_path="tests.example_apps.music.tables", ) def test_str(self): self.assertEqual( LazyTableReference( table_class_name="Manager", app_name="example_app", ).__str__(), "App example_app.Manager", ) self.assertEqual( LazyTableReference( table_class_name="Manager", module_path="tests.example_apps.music.tables", ).__str__(), "Module tests.example_apps.music.tables.Manager", )
<filename>tests/columns/test_reference.py """ Most of the tests for piccolo/columns/reference.py are covered in piccolo/columns/test_foreignkey.py """ from unittest import TestCase from piccolo.columns.reference import LazyTableReference class TestLazyTableReference(TestCase): def test_init(self): """ A ``LazyTableReference`` must be passed either an ``app_name`` or ``module_path`` argument. """ with self.assertRaises(ValueError): LazyTableReference(table_class_name="Manager") with self.assertRaises(ValueError): LazyTableReference( table_class_name="Manager", app_name="example_app", module_path="tests.example_apps.music.tables", ) # Shouldn't raise exceptions: LazyTableReference( table_class_name="Manager", app_name="example_app", ) LazyTableReference( table_class_name="Manager", module_path="tests.example_apps.music.tables", ) def test_str(self): self.assertEqual( LazyTableReference( table_class_name="Manager", app_name="example_app", ).__str__(), "App example_app.Manager", ) self.assertEqual( LazyTableReference( table_class_name="Manager", module_path="tests.example_apps.music.tables", ).__str__(), "Module tests.example_apps.music.tables.Manager", )
en
0.569794
Most of the tests for piccolo/columns/reference.py are covered in piccolo/columns/test_foreignkey.py A ``LazyTableReference`` must be passed either an ``app_name`` or ``module_path`` argument. # Shouldn't raise exceptions:
2.703704
3
run.py
zeochoy/DeepSAC
0
6628276
<reponame>zeochoy/DeepSAC # -*- encoding: utf-8 -*- from sacapp import app #from skinapp.cocomodel import * if __name__ == "__main__": app.run(host="0.0.0.0", debug=app.config['DEBUG'], port=app.config['PORT'])
# -*- encoding: utf-8 -*- from sacapp import app #from skinapp.cocomodel import * if __name__ == "__main__": app.run(host="0.0.0.0", debug=app.config['DEBUG'], port=app.config['PORT'])
en
0.475226
# -*- encoding: utf-8 -*- #from skinapp.cocomodel import *
1.275808
1
stylee/cloth/migrations/0016_auto_20170926_1028.py
jbaek7023/Stylee-API
1
6628277
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-09-26 10:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cloth', '0015_cloth_big_cloth_type'), ] operations = [ migrations.AlterField( model_name='cloth', name='big_cloth_type', field=models.CharField(choices=[('t', 'Top'), ('b', 'Bottom'), ('o', 'Outwear'), ('s', 'Shoes'), ('e', 'ETC')], default='top', max_length=11), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-09-26 10:28 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cloth', '0015_cloth_big_cloth_type'), ] operations = [ migrations.AlterField( model_name='cloth', name='big_cloth_type', field=models.CharField(choices=[('t', 'Top'), ('b', 'Bottom'), ('o', 'Outwear'), ('s', 'Shoes'), ('e', 'ETC')], default='top', max_length=11), ), ]
en
0.727333
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-09-26 10:28
1.788457
2
pathos_being.py
andsteing/being
2
6628278
<gh_stars>1-10 #!/usr/local/python3 """Pathos being for linear motors.""" import logging from being.awakening import awake from being.backends import CanBackend from being.behavior import Behavior from being.logging import setup_logging, suppress_other_loggers from being.motion_player import MotionPlayer from being.motors import LinearMotor, RotaryMotor from being.resources import register_resource, manage_resources from being.sensors import SensorGpio # Params MOTOR_NAME: str = 'LM1247' """Motor name.""" #setup_logging() suppress_other_loggers() logging.basicConfig(level=10) with manage_resources(): # Scan for motors network = CanBackend.single_instance_setdefault() register_resource(network, duplicates=False) motors = [ LinearMotor(nodeId, motor=MOTOR_NAME, name=f'Motor ID {nodeId}') for nodeId in network.scan_for_node_ids() ] if not motors: raise RuntimeError('Found no motors!') # Initialize remaining being blocks sensor = SensorGpio(channel=6) behavior = Behavior.from_config('behavior.json') motionPlayer = MotionPlayer(ndim=len(motors)) # Make block connections sensor | behavior | motionPlayer for output, motor in zip(motionPlayer.positionOutputs, motors): output.connect(motor.input) awake(behavior)
#!/usr/local/python3 """Pathos being for linear motors.""" import logging from being.awakening import awake from being.backends import CanBackend from being.behavior import Behavior from being.logging import setup_logging, suppress_other_loggers from being.motion_player import MotionPlayer from being.motors import LinearMotor, RotaryMotor from being.resources import register_resource, manage_resources from being.sensors import SensorGpio # Params MOTOR_NAME: str = 'LM1247' """Motor name.""" #setup_logging() suppress_other_loggers() logging.basicConfig(level=10) with manage_resources(): # Scan for motors network = CanBackend.single_instance_setdefault() register_resource(network, duplicates=False) motors = [ LinearMotor(nodeId, motor=MOTOR_NAME, name=f'Motor ID {nodeId}') for nodeId in network.scan_for_node_ids() ] if not motors: raise RuntimeError('Found no motors!') # Initialize remaining being blocks sensor = SensorGpio(channel=6) behavior = Behavior.from_config('behavior.json') motionPlayer = MotionPlayer(ndim=len(motors)) # Make block connections sensor | behavior | motionPlayer for output, motor in zip(motionPlayer.positionOutputs, motors): output.connect(motor.input) awake(behavior)
en
0.813992
#!/usr/local/python3 Pathos being for linear motors. # Params Motor name. #setup_logging() # Scan for motors # Initialize remaining being blocks # Make block connections
2.328226
2
webStorm-APICloud/python_tools/Lib/xml/etree/ElementTree.py
zzr925028429/androidyianyan
81
6628279
# # ElementTree # $Id: ElementTree.py 2326 2005-03-17 07:45:21Z fredrik $ # # light-weight XML support for Python 1.5.2 and later. # # history: # 2001-10-20 fl created (from various sources) # 2001-11-01 fl return root from parse method # 2002-02-16 fl sort attributes in lexical order # 2002-04-06 fl TreeBuilder refactoring, added PythonDoc markup # 2002-05-01 fl finished TreeBuilder refactoring # 2002-07-14 fl added basic namespace support to ElementTree.write # 2002-07-25 fl added QName attribute support # 2002-10-20 fl fixed encoding in write # 2002-11-24 fl changed default encoding to ascii; fixed attribute encoding # 2002-11-27 fl accept file objects or file names for parse/write # 2002-12-04 fl moved XMLTreeBuilder back to this module # 2003-01-11 fl fixed entity encoding glitch for us-ascii # 2003-02-13 fl added XML literal factory # 2003-02-21 fl added ProcessingInstruction/PI factory # 2003-05-11 fl added tostring/fromstring helpers # 2003-05-26 fl added ElementPath support # 2003-07-05 fl added makeelement factory method # 2003-07-28 fl added more well-known namespace prefixes # 2003-08-15 fl fixed typo in ElementTree.findtext (<NAME>) # 2003-09-04 fl fall back on emulator if ElementPath is not installed # 2003-10-31 fl markup updates # 2003-11-15 fl fixed nested namespace bug # 2004-03-28 fl added XMLID helper # 2004-06-02 fl added default support to findtext # 2004-06-08 fl fixed encoding of non-ascii element/attribute names # 2004-08-23 fl take advantage of post-2.1 expat features # 2005-02-01 fl added iterparse implementation # 2005-03-02 fl fixed iterparse support for pre-2.2 versions # # Copyright (c) 1999-2005 by <NAME>. All rights reserved. # # <EMAIL> # http://www.pythonware.com # # -------------------------------------------------------------------- # The ElementTree toolkit is # # Copyright (c) 1999-2005 by <NAME> # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/2.4/license for licensing details. __all__ = [ # public symbols "Comment", "dump", "Element", "ElementTree", "fromstring", "iselement", "iterparse", "parse", "PI", "ProcessingInstruction", "QName", "SubElement", "tostring", "TreeBuilder", "VERSION", "XML", "XMLParser", "XMLTreeBuilder", ] ## # The <b>Element</b> type is a flexible container object, designed to # store hierarchical data structures in memory. The type can be # described as a cross between a list and a dictionary. # <p> # Each element has a number of properties associated with it: # <ul> # <li>a <i>tag</i>. This is a string identifying what kind of data # this element represents (the element type, in other words).</li> # <li>a number of <i>attributes</i>, stored in a Python dictionary.</li> # <li>a <i>text</i> string.</li> # <li>an optional <i>tail</i> string.</li> # <li>a number of <i>child elements</i>, stored in a Python sequence</li> # </ul> # # To create an element instance, use the {@link #Element} or {@link # #SubElement} factory functions. # <p> # The {@link #ElementTree} class can be used to wrap an element # structure, and convert it from and to XML. ## import string, sys, re class _SimpleElementPath: # emulate pre-1.2 find/findtext/findall behaviour def find(self, element, tag): for elem in element: if elem.tag == tag: return elem return None def findtext(self, element, tag, default=None): for elem in element: if elem.tag == tag: return elem.text or "" return default def findall(self, element, tag): if tag[:3] == ".//": return element.getiterator(tag[3:]) result = [] for elem in element: if elem.tag == tag: result.append(elem) return result try: import ElementPath except ImportError: # FIXME: issue warning in this case? ElementPath = _SimpleElementPath() # TODO: add support for custom namespace resolvers/default namespaces # TODO: add improved support for incremental parsing VERSION = "1.2.6" ## # Internal element class. This class defines the Element interface, # and provides a reference implementation of this interface. # <p> # You should not create instances of this class directly. Use the # appropriate factory functions instead, such as {@link #Element} # and {@link #SubElement}. # # @see Element # @see SubElement # @see Comment # @see ProcessingInstruction class _ElementInterface: # <tag attrib>text<child/>...</tag>tail ## # (Attribute) Element tag. tag = None ## # (Attribute) Element attribute dictionary. Where possible, use # {@link #_ElementInterface.get}, # {@link #_ElementInterface.set}, # {@link #_ElementInterface.keys}, and # {@link #_ElementInterface.items} to access # element attributes. attrib = None ## # (Attribute) Text before first subelement. This is either a # string or the value None, if there was no text. text = None ## # (Attribute) Text after this element's end tag, but before the # next sibling element's start tag. This is either a string or # the value None, if there was no text. tail = None # text after end tag, if any def __init__(self, tag, attrib): self.tag = tag self.attrib = attrib self._children = [] def __repr__(self): return "<Element %s at %x>" % (self.tag, id(self)) ## # Creates a new element object of the same type as this element. # # @param tag Element tag. # @param attrib Element attributes, given as a dictionary. # @return A new element instance. def makeelement(self, tag, attrib): return Element(tag, attrib) ## # Returns the number of subelements. # # @return The number of subelements. def __len__(self): return len(self._children) ## # Returns the given subelement. # # @param index What subelement to return. # @return The given subelement. # @exception IndexError If the given element does not exist. def __getitem__(self, index): return self._children[index] ## # Replaces the given subelement. # # @param index What subelement to replace. # @param element The new element value. # @exception IndexError If the given element does not exist. # @exception AssertionError If element is not a valid object. def __setitem__(self, index, element): assert iselement(element) self._children[index] = element ## # Deletes the given subelement. # # @param index What subelement to delete. # @exception IndexError If the given element does not exist. def __delitem__(self, index): del self._children[index] ## # Returns a list containing subelements in the given range. # # @param start The first subelement to return. # @param stop The first subelement that shouldn't be returned. # @return A sequence object containing subelements. def __getslice__(self, start, stop): return self._children[start:stop] ## # Replaces a number of subelements with elements from a sequence. # # @param start The first subelement to replace. # @param stop The first subelement that shouldn't be replaced. # @param elements A sequence object with zero or more elements. # @exception AssertionError If a sequence member is not a valid object. def __setslice__(self, start, stop, elements): for element in elements: assert iselement(element) self._children[start:stop] = list(elements) ## # Deletes a number of subelements. # # @param start The first subelement to delete. # @param stop The first subelement to leave in there. def __delslice__(self, start, stop): del self._children[start:stop] ## # Adds a subelement to the end of this element. # # @param element The element to add. # @exception AssertionError If a sequence member is not a valid object. def append(self, element): assert iselement(element) self._children.append(element) ## # Inserts a subelement at the given position in this element. # # @param index Where to insert the new subelement. # @exception AssertionError If the element is not a valid object. def insert(self, index, element): assert iselement(element) self._children.insert(index, element) ## # Removes a matching subelement. Unlike the <b>find</b> methods, # this method compares elements based on identity, not on tag # value or contents. # # @param element What element to remove. # @exception ValueError If a matching element could not be found. # @exception AssertionError If the element is not a valid object. def remove(self, element): assert iselement(element) self._children.remove(element) ## # Returns all subelements. The elements are returned in document # order. # # @return A list of subelements. # @defreturn list of Element instances def getchildren(self): return self._children ## # Finds the first matching subelement, by tag name or path. # # @param path What element to look for. # @return The first matching element, or None if no element was found. # @defreturn Element or None def find(self, path): return ElementPath.find(self, path) ## # Finds text for the first matching subelement, by tag name or path. # # @param path What element to look for. # @param default What to return if the element was not found. # @return The text content of the first matching element, or the # default value no element was found. Note that if the element # has is found, but has no text content, this method returns an # empty string. # @defreturn string def findtext(self, path, default=None): return ElementPath.findtext(self, path, default) ## # Finds all matching subelements, by tag name or path. # # @param path What element to look for. # @return A list or iterator containing all matching elements, # in document order. # @defreturn list of Element instances def findall(self, path): return ElementPath.findall(self, path) ## # Resets an element. This function removes all subelements, clears # all attributes, and sets the text and tail attributes to None. def clear(self): self.attrib.clear() self._children = [] self.text = self.tail = None ## # Gets an element attribute. # # @param key What attribute to look for. # @param default What to return if the attribute was not found. # @return The attribute value, or the default value, if the # attribute was not found. # @defreturn string or None def get(self, key, default=None): return self.attrib.get(key, default) ## # Sets an element attribute. # # @param key What attribute to set. # @param value The attribute value. def set(self, key, value): self.attrib[key] = value ## # Gets a list of attribute names. The names are returned in an # arbitrary order (just like for an ordinary Python dictionary). # # @return A list of element attribute names. # @defreturn list of strings def keys(self): return self.attrib.keys() ## # Gets element attributes, as a sequence. The attributes are # returned in an arbitrary order. # # @return A list of (name, value) tuples for all attributes. # @defreturn list of (string, string) tuples def items(self): return self.attrib.items() ## # Creates a tree iterator. The iterator loops over this element # and all subelements, in document order, and returns all elements # with a matching tag. # <p> # If the tree structure is modified during iteration, the result # is undefined. # # @param tag What tags to look for (default is to return all elements). # @return A list or iterator containing all the matching elements. # @defreturn list or iterator def getiterator(self, tag=None): nodes = [] if tag == "*": tag = None if tag is None or self.tag == tag: nodes.append(self) for node in self._children: nodes.extend(node.getiterator(tag)) return nodes # compatibility _Element = _ElementInterface ## # Element factory. This function returns an object implementing the # standard Element interface. The exact class or type of that object # is implementation dependent, but it will always be compatible with # the {@link #_ElementInterface} class in this module. # <p> # The element name, attribute names, and attribute values can be # either 8-bit ASCII strings or Unicode strings. # # @param tag The element name. # @param attrib An optional dictionary, containing element attributes. # @param **extra Additional attributes, given as keyword arguments. # @return An element instance. # @defreturn Element def Element(tag, attrib={}, **extra): attrib = attrib.copy() attrib.update(extra) return _ElementInterface(tag, attrib) ## # Subelement factory. This function creates an element instance, and # appends it to an existing element. # <p> # The element name, attribute names, and attribute values can be # either 8-bit ASCII strings or Unicode strings. # # @param parent The parent element. # @param tag The subelement name. # @param attrib An optional dictionary, containing element attributes. # @param **extra Additional attributes, given as keyword arguments. # @return An element instance. # @defreturn Element def SubElement(parent, tag, attrib={}, **extra): attrib = attrib.copy() attrib.update(extra) element = parent.makeelement(tag, attrib) parent.append(element) return element ## # Comment element factory. This factory function creates a special # element that will be serialized as an XML comment. # <p> # The comment string can be either an 8-bit ASCII string or a Unicode # string. # # @param text A string containing the comment string. # @return An element instance, representing a comment. # @defreturn Element def Comment(text=None): element = Element(Comment) element.text = text return element ## # PI element factory. This factory function creates a special element # that will be serialized as an XML processing instruction. # # @param target A string containing the PI target. # @param text A string containing the PI contents, if any. # @return An element instance, representing a PI. # @defreturn Element def ProcessingInstruction(target, text=None): element = Element(ProcessingInstruction) element.text = target if text: element.text = element.text + " " + text return element PI = ProcessingInstruction ## # QName wrapper. This can be used to wrap a QName attribute value, in # order to get proper namespace handling on output. # # @param text A string containing the QName value, in the form {uri}local, # or, if the tag argument is given, the URI part of a QName. # @param tag Optional tag. If given, the first argument is interpreted as # an URI, and this argument is interpreted as a local name. # @return An opaque object, representing the QName. class QName: def __init__(self, text_or_uri, tag=None): if tag: text_or_uri = "{%s}%s" % (text_or_uri, tag) self.text = text_or_uri def __str__(self): return self.text def __hash__(self): return hash(self.text) def __cmp__(self, other): if isinstance(other, QName): return cmp(self.text, other.text) return cmp(self.text, other) ## # ElementTree wrapper class. This class represents an entire element # hierarchy, and adds some extra support for serialization to and from # standard XML. # # @param element Optional root element. # @keyparam file Optional file handle or name. If given, the # tree is initialized with the contents of this XML file. class ElementTree: def __init__(self, element=None, file=None): assert element is None or iselement(element) self._root = element # first node if file: self.parse(file) ## # Gets the root element for this tree. # # @return An element instance. # @defreturn Element def getroot(self): return self._root ## # Replaces the root element for this tree. This discards the # current contents of the tree, and replaces it with the given # element. Use with care. # # @param element An element instance. def _setroot(self, element): assert iselement(element) self._root = element ## # Loads an external XML document into this element tree. # # @param source A file name or file object. # @param parser An optional parser instance. If not given, the # standard {@link XMLTreeBuilder} parser is used. # @return The document root element. # @defreturn Element def parse(self, source, parser=None): if not hasattr(source, "read"): source = open(source, "rb") if not parser: parser = XMLTreeBuilder() while 1: data = source.read(32768) if not data: break parser.feed(data) self._root = parser.close() return self._root ## # Creates a tree iterator for the root element. The iterator loops # over all elements in this tree, in document order. # # @param tag What tags to look for (default is to return all elements) # @return An iterator. # @defreturn iterator def getiterator(self, tag=None): assert self._root is not None return self._root.getiterator(tag) ## # Finds the first toplevel element with given tag. # Same as getroot().find(path). # # @param path What element to look for. # @return The first matching element, or None if no element was found. # @defreturn Element or None def find(self, path): assert self._root is not None if path[:1] == "/": path = "." + path return self._root.find(path) ## # Finds the element text for the first toplevel element with given # tag. Same as getroot().findtext(path). # # @param path What toplevel element to look for. # @param default What to return if the element was not found. # @return The text content of the first matching element, or the # default value no element was found. Note that if the element # has is found, but has no text content, this method returns an # empty string. # @defreturn string def findtext(self, path, default=None): assert self._root is not None if path[:1] == "/": path = "." + path return self._root.findtext(path, default) ## # Finds all toplevel elements with the given tag. # Same as getroot().findall(path). # # @param path What element to look for. # @return A list or iterator containing all matching elements, # in document order. # @defreturn list of Element instances def findall(self, path): assert self._root is not None if path[:1] == "/": path = "." + path return self._root.findall(path) ## # Writes the element tree to a file, as XML. # # @param file A file name, or a file object opened for writing. # @param encoding Optional output encoding (default is US-ASCII). def write(self, file, encoding="us-ascii"): assert self._root is not None if not hasattr(file, "write"): file = open(file, "wb") if not encoding: encoding = "us-ascii" elif encoding != "utf-8" and encoding != "us-ascii": file.write("<?xml version='1.0' encoding='%s'?>\n" % encoding) self._write(file, self._root, encoding, {}) def _write(self, file, node, encoding, namespaces): # write XML to file tag = node.tag if tag is Comment: file.write("<!-- %s -->" % _escape_cdata(node.text, encoding)) elif tag is ProcessingInstruction: file.write("<?%s?>" % _escape_cdata(node.text, encoding)) else: items = node.items() xmlns_items = [] # new namespaces in this scope try: if isinstance(tag, QName) or tag[:1] == "{": tag, xmlns = fixtag(tag, namespaces) if xmlns: xmlns_items.append(xmlns) except TypeError: _raise_serialization_error(tag) file.write("<" + _encode(tag, encoding)) if items or xmlns_items: items.sort() # lexical order for k, v in items: try: if isinstance(k, QName) or k[:1] == "{": k, xmlns = fixtag(k, namespaces) if xmlns: xmlns_items.append(xmlns) except TypeError: _raise_serialization_error(k) try: if isinstance(v, QName): v, xmlns = fixtag(v, namespaces) if xmlns: xmlns_items.append(xmlns) except TypeError: _raise_serialization_error(v) file.write(" %s=\"%s\"" % (_encode(k, encoding), _escape_attrib(v, encoding))) for k, v in xmlns_items: file.write(" %s=\"%s\"" % (_encode(k, encoding), _escape_attrib(v, encoding))) if node.text or len(node): file.write(">") if node.text: file.write(_escape_cdata(node.text, encoding)) for n in node: self._write(file, n, encoding, namespaces) file.write("</" + _encode(tag, encoding) + ">") else: file.write(" />") for k, v in xmlns_items: del namespaces[v] if node.tail: file.write(_escape_cdata(node.tail, encoding)) # -------------------------------------------------------------------- # helpers ## # Checks if an object appears to be a valid element object. # # @param An element instance. # @return A true value if this is an element object. # @defreturn flag def iselement(element): # FIXME: not sure about this; might be a better idea to look # for tag/attrib/text attributes return isinstance(element, _ElementInterface) or hasattr(element, "tag") ## # Writes an element tree or element structure to sys.stdout. This # function should be used for debugging only. # <p> # The exact output format is implementation dependent. In this # version, it's written as an ordinary XML file. # # @param elem An element tree or an individual element. def dump(elem): # debugging if not isinstance(elem, ElementTree): elem = ElementTree(elem) elem.write(sys.stdout) tail = elem.getroot().tail if not tail or tail[-1] != "\n": sys.stdout.write("\n") def _encode(s, encoding): try: return s.encode(encoding) except AttributeError: return s # 1.5.2: assume the string uses the right encoding if sys.version[:3] == "1.5": _escape = re.compile(r"[&<>\"\x80-\xff]+") # 1.5.2 else: _escape = re.compile(eval(r'u"[&<>\"\u0080-\uffff]+"')) _escape_map = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", } _namespace_map = { # "well-known" namespace prefixes "http://www.w3.org/XML/1998/namespace": "xml", "http://www.w3.org/1999/xhtml": "html", "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf", "http://schemas.xmlsoap.org/wsdl/": "wsdl", } def _raise_serialization_error(text): raise TypeError( "cannot serialize %r (type %s)" % (text, type(text).__name__) ) def _encode_entity(text, pattern=_escape): # map reserved and non-ascii characters to numerical entities def escape_entities(m, map=_escape_map): out = [] append = out.append for char in m.group(): text = map.get(char) if text is None: text = "&#%d;" % ord(char) append(text) return string.join(out, "") try: return _encode(pattern.sub(escape_entities, text), "ascii") except TypeError: _raise_serialization_error(text) # # the following functions assume an ascii-compatible encoding # (or "utf-16") def _escape_cdata(text, encoding=None, replace=string.replace): # escape character data try: if encoding: try: text = _encode(text, encoding) except UnicodeError: return _encode_entity(text) text = replace(text, "&", "&amp;") text = replace(text, "<", "&lt;") text = replace(text, ">", "&gt;") return text except (TypeError, AttributeError): _raise_serialization_error(text) def _escape_attrib(text, encoding=None, replace=string.replace): # escape attribute value try: if encoding: try: text = _encode(text, encoding) except UnicodeError: return _encode_entity(text) text = replace(text, "&", "&amp;") text = replace(text, "'", "&apos;") # FIXME: overkill text = replace(text, "\"", "&quot;") text = replace(text, "<", "&lt;") text = replace(text, ">", "&gt;") return text except (TypeError, AttributeError): _raise_serialization_error(text) def fixtag(tag, namespaces): # given a decorated tag (of the form {uri}tag), return prefixed # tag and namespace declaration, if any if isinstance(tag, QName): tag = tag.text namespace_uri, tag = string.split(tag[1:], "}", 1) prefix = namespaces.get(namespace_uri) if prefix is None: prefix = _namespace_map.get(namespace_uri) if prefix is None: prefix = "ns%d" % len(namespaces) namespaces[namespace_uri] = prefix if prefix == "xml": xmlns = None else: xmlns = ("xmlns:%s" % prefix, namespace_uri) else: xmlns = None return "%s:%s" % (prefix, tag), xmlns ## # Parses an XML document into an element tree. # # @param source A filename or file object containing XML data. # @param parser An optional parser instance. If not given, the # standard {@link XMLTreeBuilder} parser is used. # @return An ElementTree instance def parse(source, parser=None): tree = ElementTree() tree.parse(source, parser) return tree ## # Parses an XML document into an element tree incrementally, and reports # what's going on to the user. # # @param source A filename or file object containing XML data. # @param events A list of events to report back. If omitted, only "end" # events are reported. # @return A (event, elem) iterator. class iterparse: def __init__(self, source, events=None): if not hasattr(source, "read"): source = open(source, "rb") self._file = source self._events = [] self._index = 0 self.root = self._root = None self._parser = XMLTreeBuilder() # wire up the parser for event reporting parser = self._parser._parser append = self._events.append if events is None: events = ["end"] for event in events: if event == "start": try: parser.ordered_attributes = 1 parser.specified_attributes = 1 def handler(tag, attrib_in, event=event, append=append, start=self._parser._start_list): append((event, start(tag, attrib_in))) parser.StartElementHandler = handler except AttributeError: def handler(tag, attrib_in, event=event, append=append, start=self._parser._start): append((event, start(tag, attrib_in))) parser.StartElementHandler = handler elif event == "end": def handler(tag, event=event, append=append, end=self._parser._end): append((event, end(tag))) parser.EndElementHandler = handler elif event == "start-ns": def handler(prefix, uri, event=event, append=append): try: uri = _encode(uri, "ascii") except UnicodeError: pass append((event, (prefix or "", uri))) parser.StartNamespaceDeclHandler = handler elif event == "end-ns": def handler(prefix, event=event, append=append): append((event, None)) parser.EndNamespaceDeclHandler = handler def next(self): while 1: try: item = self._events[self._index] except IndexError: if self._parser is None: self.root = self._root try: raise StopIteration except NameError: raise IndexError # load event buffer del self._events[:] self._index = 0 data = self._file.read(16384) if data: self._parser.feed(data) else: self._root = self._parser.close() self._parser = None else: self._index = self._index + 1 return item try: iter def __iter__(self): return self except NameError: def __getitem__(self, index): return self.next() ## # Parses an XML document from a string constant. This function can # be used to embed "XML literals" in Python code. # # @param source A string containing XML data. # @return An Element instance. # @defreturn Element def XML(text): parser = XMLTreeBuilder() parser.feed(text) return parser.close() ## # Parses an XML document from a string constant, and also returns # a dictionary which maps from element id:s to elements. # # @param source A string containing XML data. # @return A tuple containing an Element instance and a dictionary. # @defreturn (Element, dictionary) def XMLID(text): parser = XMLTreeBuilder() parser.feed(text) tree = parser.close() ids = {} for elem in tree.getiterator(): id = elem.get("id") if id: ids[id] = elem return tree, ids ## # Parses an XML document from a string constant. Same as {@link #XML}. # # @def fromstring(text) # @param source A string containing XML data. # @return An Element instance. # @defreturn Element fromstring = XML ## # Generates a string representation of an XML element, including all # subelements. # # @param element An Element instance. # @return An encoded string containing the XML data. # @defreturn string def tostring(element, encoding=None): class dummy: pass data = [] file = dummy() file.write = data.append ElementTree(element).write(file, encoding) return string.join(data, "") ## # Generic element structure builder. This builder converts a sequence # of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link # #TreeBuilder.end} method calls to a well-formed element structure. # <p> # You can use this class to build an element structure using a custom XML # parser, or a parser for some other XML-like format. # # @param element_factory Optional element factory. This factory # is called to create new Element instances, as necessary. class TreeBuilder: def __init__(self, element_factory=None): self._data = [] # data collector self._elem = [] # element stack self._last = None # last element self._tail = None # true if we're after an end tag if element_factory is None: element_factory = _ElementInterface self._factory = element_factory ## # Flushes the parser buffers, and returns the toplevel documen # element. # # @return An Element instance. # @defreturn Element def close(self): assert len(self._elem) == 0, "missing end tags" assert self._last != None, "missing toplevel element" return self._last def _flush(self): if self._data: if self._last is not None: text = string.join(self._data, "") if self._tail: assert self._last.tail is None, "internal error (tail)" self._last.tail = text else: assert self._last.text is None, "internal error (text)" self._last.text = text self._data = [] ## # Adds text to the current element. # # @param data A string. This should be either an 8-bit string # containing ASCII text, or a Unicode string. def data(self, data): self._data.append(data) ## # Opens a new element. # # @param tag The element name. # @param attrib A dictionary containing element attributes. # @return The opened element. # @defreturn Element def start(self, tag, attrs): self._flush() self._last = elem = self._factory(tag, attrs) if self._elem: self._elem[-1].append(elem) self._elem.append(elem) self._tail = 0 return elem ## # Closes the current element. # # @param tag The element name. # @return The closed element. # @defreturn Element def end(self, tag): self._flush() self._last = self._elem.pop() assert self._last.tag == tag,\ "end tag mismatch (expected %s, got %s)" % ( self._last.tag, tag) self._tail = 1 return self._last ## # Element structure builder for XML source data, based on the # <b>expat</b> parser. # # @keyparam target Target object. If omitted, the builder uses an # instance of the standard {@link #TreeBuilder} class. # @keyparam html Predefine HTML entities. This flag is not supported # by the current implementation. # @see #ElementTree # @see #TreeBuilder class XMLTreeBuilder: def __init__(self, html=0, target=None): try: from xml.parsers import expat except ImportError: raise ImportError( "No module named expat; use SimpleXMLTreeBuilder instead" ) self._parser = parser = expat.ParserCreate(None, "}") if target is None: target = TreeBuilder() self._target = target self._names = {} # name memo cache # callbacks parser.DefaultHandlerExpand = self._default parser.StartElementHandler = self._start parser.EndElementHandler = self._end parser.CharacterDataHandler = self._data # let expat do the buffering, if supported try: self._parser.buffer_text = 1 except AttributeError: pass # use new-style attribute handling, if supported try: self._parser.ordered_attributes = 1 self._parser.specified_attributes = 1 parser.StartElementHandler = self._start_list except AttributeError: pass encoding = None if not parser.returns_unicode: encoding = "utf-8" # target.xml(encoding, None) self._doctype = None self.entity = {} def _fixtext(self, text): # convert text string to ascii, if possible try: return _encode(text, "ascii") except UnicodeError: return text def _fixname(self, key): # expand qname, and convert name string to ascii, if possible try: name = self._names[key] except KeyError: name = key if "}" in name: name = "{" + name self._names[key] = name = self._fixtext(name) return name def _start(self, tag, attrib_in): fixname = self._fixname tag = fixname(tag) attrib = {} for key, value in attrib_in.items(): attrib[fixname(key)] = self._fixtext(value) return self._target.start(tag, attrib) def _start_list(self, tag, attrib_in): fixname = self._fixname tag = fixname(tag) attrib = {} if attrib_in: for i in range(0, len(attrib_in), 2): attrib[fixname(attrib_in[i])] = self._fixtext(attrib_in[i+1]) return self._target.start(tag, attrib) def _data(self, text): return self._target.data(self._fixtext(text)) def _end(self, tag): return self._target.end(self._fixname(tag)) def _default(self, text): prefix = text[:1] if prefix == "&": # deal with undefined entities try: self._target.data(self.entity[text[1:-1]]) except KeyError: from xml.parsers import expat raise expat.error( "undefined entity %s: line %d, column %d" % (text, self._parser.ErrorLineNumber, self._parser.ErrorColumnNumber) ) elif prefix == "<" and text[:9] == "<!DOCTYPE": self._doctype = [] # inside a doctype declaration elif self._doctype is not None: # parse doctype contents if prefix == ">": self._doctype = None return text = string.strip(text) if not text: return self._doctype.append(text) n = len(self._doctype) if n > 2: type = self._doctype[1] if type == "PUBLIC" and n == 4: name, type, pubid, system = self._doctype elif type == "SYSTEM" and n == 3: name, type, system = self._doctype pubid = None else: return if pubid: pubid = pubid[1:-1] self.doctype(name, pubid, system[1:-1]) self._doctype = None ## # Handles a doctype declaration. # # @param name Doctype name. # @param pubid Public identifier. # @param system System identifier. def doctype(self, name, pubid, system): pass ## # Feeds data to the parser. # # @param data Encoded data. def feed(self, data): self._parser.Parse(data, 0) ## # Finishes feeding data to the parser. # # @return An element structure. # @defreturn Element def close(self): self._parser.Parse("", 1) # end of data tree = self._target.close() del self._target, self._parser # get rid of circular references return tree # compatibility XMLParser = XMLTreeBuilder
# # ElementTree # $Id: ElementTree.py 2326 2005-03-17 07:45:21Z fredrik $ # # light-weight XML support for Python 1.5.2 and later. # # history: # 2001-10-20 fl created (from various sources) # 2001-11-01 fl return root from parse method # 2002-02-16 fl sort attributes in lexical order # 2002-04-06 fl TreeBuilder refactoring, added PythonDoc markup # 2002-05-01 fl finished TreeBuilder refactoring # 2002-07-14 fl added basic namespace support to ElementTree.write # 2002-07-25 fl added QName attribute support # 2002-10-20 fl fixed encoding in write # 2002-11-24 fl changed default encoding to ascii; fixed attribute encoding # 2002-11-27 fl accept file objects or file names for parse/write # 2002-12-04 fl moved XMLTreeBuilder back to this module # 2003-01-11 fl fixed entity encoding glitch for us-ascii # 2003-02-13 fl added XML literal factory # 2003-02-21 fl added ProcessingInstruction/PI factory # 2003-05-11 fl added tostring/fromstring helpers # 2003-05-26 fl added ElementPath support # 2003-07-05 fl added makeelement factory method # 2003-07-28 fl added more well-known namespace prefixes # 2003-08-15 fl fixed typo in ElementTree.findtext (<NAME>) # 2003-09-04 fl fall back on emulator if ElementPath is not installed # 2003-10-31 fl markup updates # 2003-11-15 fl fixed nested namespace bug # 2004-03-28 fl added XMLID helper # 2004-06-02 fl added default support to findtext # 2004-06-08 fl fixed encoding of non-ascii element/attribute names # 2004-08-23 fl take advantage of post-2.1 expat features # 2005-02-01 fl added iterparse implementation # 2005-03-02 fl fixed iterparse support for pre-2.2 versions # # Copyright (c) 1999-2005 by <NAME>. All rights reserved. # # <EMAIL> # http://www.pythonware.com # # -------------------------------------------------------------------- # The ElementTree toolkit is # # Copyright (c) 1999-2005 by <NAME> # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/2.4/license for licensing details. __all__ = [ # public symbols "Comment", "dump", "Element", "ElementTree", "fromstring", "iselement", "iterparse", "parse", "PI", "ProcessingInstruction", "QName", "SubElement", "tostring", "TreeBuilder", "VERSION", "XML", "XMLParser", "XMLTreeBuilder", ] ## # The <b>Element</b> type is a flexible container object, designed to # store hierarchical data structures in memory. The type can be # described as a cross between a list and a dictionary. # <p> # Each element has a number of properties associated with it: # <ul> # <li>a <i>tag</i>. This is a string identifying what kind of data # this element represents (the element type, in other words).</li> # <li>a number of <i>attributes</i>, stored in a Python dictionary.</li> # <li>a <i>text</i> string.</li> # <li>an optional <i>tail</i> string.</li> # <li>a number of <i>child elements</i>, stored in a Python sequence</li> # </ul> # # To create an element instance, use the {@link #Element} or {@link # #SubElement} factory functions. # <p> # The {@link #ElementTree} class can be used to wrap an element # structure, and convert it from and to XML. ## import string, sys, re class _SimpleElementPath: # emulate pre-1.2 find/findtext/findall behaviour def find(self, element, tag): for elem in element: if elem.tag == tag: return elem return None def findtext(self, element, tag, default=None): for elem in element: if elem.tag == tag: return elem.text or "" return default def findall(self, element, tag): if tag[:3] == ".//": return element.getiterator(tag[3:]) result = [] for elem in element: if elem.tag == tag: result.append(elem) return result try: import ElementPath except ImportError: # FIXME: issue warning in this case? ElementPath = _SimpleElementPath() # TODO: add support for custom namespace resolvers/default namespaces # TODO: add improved support for incremental parsing VERSION = "1.2.6" ## # Internal element class. This class defines the Element interface, # and provides a reference implementation of this interface. # <p> # You should not create instances of this class directly. Use the # appropriate factory functions instead, such as {@link #Element} # and {@link #SubElement}. # # @see Element # @see SubElement # @see Comment # @see ProcessingInstruction class _ElementInterface: # <tag attrib>text<child/>...</tag>tail ## # (Attribute) Element tag. tag = None ## # (Attribute) Element attribute dictionary. Where possible, use # {@link #_ElementInterface.get}, # {@link #_ElementInterface.set}, # {@link #_ElementInterface.keys}, and # {@link #_ElementInterface.items} to access # element attributes. attrib = None ## # (Attribute) Text before first subelement. This is either a # string or the value None, if there was no text. text = None ## # (Attribute) Text after this element's end tag, but before the # next sibling element's start tag. This is either a string or # the value None, if there was no text. tail = None # text after end tag, if any def __init__(self, tag, attrib): self.tag = tag self.attrib = attrib self._children = [] def __repr__(self): return "<Element %s at %x>" % (self.tag, id(self)) ## # Creates a new element object of the same type as this element. # # @param tag Element tag. # @param attrib Element attributes, given as a dictionary. # @return A new element instance. def makeelement(self, tag, attrib): return Element(tag, attrib) ## # Returns the number of subelements. # # @return The number of subelements. def __len__(self): return len(self._children) ## # Returns the given subelement. # # @param index What subelement to return. # @return The given subelement. # @exception IndexError If the given element does not exist. def __getitem__(self, index): return self._children[index] ## # Replaces the given subelement. # # @param index What subelement to replace. # @param element The new element value. # @exception IndexError If the given element does not exist. # @exception AssertionError If element is not a valid object. def __setitem__(self, index, element): assert iselement(element) self._children[index] = element ## # Deletes the given subelement. # # @param index What subelement to delete. # @exception IndexError If the given element does not exist. def __delitem__(self, index): del self._children[index] ## # Returns a list containing subelements in the given range. # # @param start The first subelement to return. # @param stop The first subelement that shouldn't be returned. # @return A sequence object containing subelements. def __getslice__(self, start, stop): return self._children[start:stop] ## # Replaces a number of subelements with elements from a sequence. # # @param start The first subelement to replace. # @param stop The first subelement that shouldn't be replaced. # @param elements A sequence object with zero or more elements. # @exception AssertionError If a sequence member is not a valid object. def __setslice__(self, start, stop, elements): for element in elements: assert iselement(element) self._children[start:stop] = list(elements) ## # Deletes a number of subelements. # # @param start The first subelement to delete. # @param stop The first subelement to leave in there. def __delslice__(self, start, stop): del self._children[start:stop] ## # Adds a subelement to the end of this element. # # @param element The element to add. # @exception AssertionError If a sequence member is not a valid object. def append(self, element): assert iselement(element) self._children.append(element) ## # Inserts a subelement at the given position in this element. # # @param index Where to insert the new subelement. # @exception AssertionError If the element is not a valid object. def insert(self, index, element): assert iselement(element) self._children.insert(index, element) ## # Removes a matching subelement. Unlike the <b>find</b> methods, # this method compares elements based on identity, not on tag # value or contents. # # @param element What element to remove. # @exception ValueError If a matching element could not be found. # @exception AssertionError If the element is not a valid object. def remove(self, element): assert iselement(element) self._children.remove(element) ## # Returns all subelements. The elements are returned in document # order. # # @return A list of subelements. # @defreturn list of Element instances def getchildren(self): return self._children ## # Finds the first matching subelement, by tag name or path. # # @param path What element to look for. # @return The first matching element, or None if no element was found. # @defreturn Element or None def find(self, path): return ElementPath.find(self, path) ## # Finds text for the first matching subelement, by tag name or path. # # @param path What element to look for. # @param default What to return if the element was not found. # @return The text content of the first matching element, or the # default value no element was found. Note that if the element # has is found, but has no text content, this method returns an # empty string. # @defreturn string def findtext(self, path, default=None): return ElementPath.findtext(self, path, default) ## # Finds all matching subelements, by tag name or path. # # @param path What element to look for. # @return A list or iterator containing all matching elements, # in document order. # @defreturn list of Element instances def findall(self, path): return ElementPath.findall(self, path) ## # Resets an element. This function removes all subelements, clears # all attributes, and sets the text and tail attributes to None. def clear(self): self.attrib.clear() self._children = [] self.text = self.tail = None ## # Gets an element attribute. # # @param key What attribute to look for. # @param default What to return if the attribute was not found. # @return The attribute value, or the default value, if the # attribute was not found. # @defreturn string or None def get(self, key, default=None): return self.attrib.get(key, default) ## # Sets an element attribute. # # @param key What attribute to set. # @param value The attribute value. def set(self, key, value): self.attrib[key] = value ## # Gets a list of attribute names. The names are returned in an # arbitrary order (just like for an ordinary Python dictionary). # # @return A list of element attribute names. # @defreturn list of strings def keys(self): return self.attrib.keys() ## # Gets element attributes, as a sequence. The attributes are # returned in an arbitrary order. # # @return A list of (name, value) tuples for all attributes. # @defreturn list of (string, string) tuples def items(self): return self.attrib.items() ## # Creates a tree iterator. The iterator loops over this element # and all subelements, in document order, and returns all elements # with a matching tag. # <p> # If the tree structure is modified during iteration, the result # is undefined. # # @param tag What tags to look for (default is to return all elements). # @return A list or iterator containing all the matching elements. # @defreturn list or iterator def getiterator(self, tag=None): nodes = [] if tag == "*": tag = None if tag is None or self.tag == tag: nodes.append(self) for node in self._children: nodes.extend(node.getiterator(tag)) return nodes # compatibility _Element = _ElementInterface ## # Element factory. This function returns an object implementing the # standard Element interface. The exact class or type of that object # is implementation dependent, but it will always be compatible with # the {@link #_ElementInterface} class in this module. # <p> # The element name, attribute names, and attribute values can be # either 8-bit ASCII strings or Unicode strings. # # @param tag The element name. # @param attrib An optional dictionary, containing element attributes. # @param **extra Additional attributes, given as keyword arguments. # @return An element instance. # @defreturn Element def Element(tag, attrib={}, **extra): attrib = attrib.copy() attrib.update(extra) return _ElementInterface(tag, attrib) ## # Subelement factory. This function creates an element instance, and # appends it to an existing element. # <p> # The element name, attribute names, and attribute values can be # either 8-bit ASCII strings or Unicode strings. # # @param parent The parent element. # @param tag The subelement name. # @param attrib An optional dictionary, containing element attributes. # @param **extra Additional attributes, given as keyword arguments. # @return An element instance. # @defreturn Element def SubElement(parent, tag, attrib={}, **extra): attrib = attrib.copy() attrib.update(extra) element = parent.makeelement(tag, attrib) parent.append(element) return element ## # Comment element factory. This factory function creates a special # element that will be serialized as an XML comment. # <p> # The comment string can be either an 8-bit ASCII string or a Unicode # string. # # @param text A string containing the comment string. # @return An element instance, representing a comment. # @defreturn Element def Comment(text=None): element = Element(Comment) element.text = text return element ## # PI element factory. This factory function creates a special element # that will be serialized as an XML processing instruction. # # @param target A string containing the PI target. # @param text A string containing the PI contents, if any. # @return An element instance, representing a PI. # @defreturn Element def ProcessingInstruction(target, text=None): element = Element(ProcessingInstruction) element.text = target if text: element.text = element.text + " " + text return element PI = ProcessingInstruction ## # QName wrapper. This can be used to wrap a QName attribute value, in # order to get proper namespace handling on output. # # @param text A string containing the QName value, in the form {uri}local, # or, if the tag argument is given, the URI part of a QName. # @param tag Optional tag. If given, the first argument is interpreted as # an URI, and this argument is interpreted as a local name. # @return An opaque object, representing the QName. class QName: def __init__(self, text_or_uri, tag=None): if tag: text_or_uri = "{%s}%s" % (text_or_uri, tag) self.text = text_or_uri def __str__(self): return self.text def __hash__(self): return hash(self.text) def __cmp__(self, other): if isinstance(other, QName): return cmp(self.text, other.text) return cmp(self.text, other) ## # ElementTree wrapper class. This class represents an entire element # hierarchy, and adds some extra support for serialization to and from # standard XML. # # @param element Optional root element. # @keyparam file Optional file handle or name. If given, the # tree is initialized with the contents of this XML file. class ElementTree: def __init__(self, element=None, file=None): assert element is None or iselement(element) self._root = element # first node if file: self.parse(file) ## # Gets the root element for this tree. # # @return An element instance. # @defreturn Element def getroot(self): return self._root ## # Replaces the root element for this tree. This discards the # current contents of the tree, and replaces it with the given # element. Use with care. # # @param element An element instance. def _setroot(self, element): assert iselement(element) self._root = element ## # Loads an external XML document into this element tree. # # @param source A file name or file object. # @param parser An optional parser instance. If not given, the # standard {@link XMLTreeBuilder} parser is used. # @return The document root element. # @defreturn Element def parse(self, source, parser=None): if not hasattr(source, "read"): source = open(source, "rb") if not parser: parser = XMLTreeBuilder() while 1: data = source.read(32768) if not data: break parser.feed(data) self._root = parser.close() return self._root ## # Creates a tree iterator for the root element. The iterator loops # over all elements in this tree, in document order. # # @param tag What tags to look for (default is to return all elements) # @return An iterator. # @defreturn iterator def getiterator(self, tag=None): assert self._root is not None return self._root.getiterator(tag) ## # Finds the first toplevel element with given tag. # Same as getroot().find(path). # # @param path What element to look for. # @return The first matching element, or None if no element was found. # @defreturn Element or None def find(self, path): assert self._root is not None if path[:1] == "/": path = "." + path return self._root.find(path) ## # Finds the element text for the first toplevel element with given # tag. Same as getroot().findtext(path). # # @param path What toplevel element to look for. # @param default What to return if the element was not found. # @return The text content of the first matching element, or the # default value no element was found. Note that if the element # has is found, but has no text content, this method returns an # empty string. # @defreturn string def findtext(self, path, default=None): assert self._root is not None if path[:1] == "/": path = "." + path return self._root.findtext(path, default) ## # Finds all toplevel elements with the given tag. # Same as getroot().findall(path). # # @param path What element to look for. # @return A list or iterator containing all matching elements, # in document order. # @defreturn list of Element instances def findall(self, path): assert self._root is not None if path[:1] == "/": path = "." + path return self._root.findall(path) ## # Writes the element tree to a file, as XML. # # @param file A file name, or a file object opened for writing. # @param encoding Optional output encoding (default is US-ASCII). def write(self, file, encoding="us-ascii"): assert self._root is not None if not hasattr(file, "write"): file = open(file, "wb") if not encoding: encoding = "us-ascii" elif encoding != "utf-8" and encoding != "us-ascii": file.write("<?xml version='1.0' encoding='%s'?>\n" % encoding) self._write(file, self._root, encoding, {}) def _write(self, file, node, encoding, namespaces): # write XML to file tag = node.tag if tag is Comment: file.write("<!-- %s -->" % _escape_cdata(node.text, encoding)) elif tag is ProcessingInstruction: file.write("<?%s?>" % _escape_cdata(node.text, encoding)) else: items = node.items() xmlns_items = [] # new namespaces in this scope try: if isinstance(tag, QName) or tag[:1] == "{": tag, xmlns = fixtag(tag, namespaces) if xmlns: xmlns_items.append(xmlns) except TypeError: _raise_serialization_error(tag) file.write("<" + _encode(tag, encoding)) if items or xmlns_items: items.sort() # lexical order for k, v in items: try: if isinstance(k, QName) or k[:1] == "{": k, xmlns = fixtag(k, namespaces) if xmlns: xmlns_items.append(xmlns) except TypeError: _raise_serialization_error(k) try: if isinstance(v, QName): v, xmlns = fixtag(v, namespaces) if xmlns: xmlns_items.append(xmlns) except TypeError: _raise_serialization_error(v) file.write(" %s=\"%s\"" % (_encode(k, encoding), _escape_attrib(v, encoding))) for k, v in xmlns_items: file.write(" %s=\"%s\"" % (_encode(k, encoding), _escape_attrib(v, encoding))) if node.text or len(node): file.write(">") if node.text: file.write(_escape_cdata(node.text, encoding)) for n in node: self._write(file, n, encoding, namespaces) file.write("</" + _encode(tag, encoding) + ">") else: file.write(" />") for k, v in xmlns_items: del namespaces[v] if node.tail: file.write(_escape_cdata(node.tail, encoding)) # -------------------------------------------------------------------- # helpers ## # Checks if an object appears to be a valid element object. # # @param An element instance. # @return A true value if this is an element object. # @defreturn flag def iselement(element): # FIXME: not sure about this; might be a better idea to look # for tag/attrib/text attributes return isinstance(element, _ElementInterface) or hasattr(element, "tag") ## # Writes an element tree or element structure to sys.stdout. This # function should be used for debugging only. # <p> # The exact output format is implementation dependent. In this # version, it's written as an ordinary XML file. # # @param elem An element tree or an individual element. def dump(elem): # debugging if not isinstance(elem, ElementTree): elem = ElementTree(elem) elem.write(sys.stdout) tail = elem.getroot().tail if not tail or tail[-1] != "\n": sys.stdout.write("\n") def _encode(s, encoding): try: return s.encode(encoding) except AttributeError: return s # 1.5.2: assume the string uses the right encoding if sys.version[:3] == "1.5": _escape = re.compile(r"[&<>\"\x80-\xff]+") # 1.5.2 else: _escape = re.compile(eval(r'u"[&<>\"\u0080-\uffff]+"')) _escape_map = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", } _namespace_map = { # "well-known" namespace prefixes "http://www.w3.org/XML/1998/namespace": "xml", "http://www.w3.org/1999/xhtml": "html", "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf", "http://schemas.xmlsoap.org/wsdl/": "wsdl", } def _raise_serialization_error(text): raise TypeError( "cannot serialize %r (type %s)" % (text, type(text).__name__) ) def _encode_entity(text, pattern=_escape): # map reserved and non-ascii characters to numerical entities def escape_entities(m, map=_escape_map): out = [] append = out.append for char in m.group(): text = map.get(char) if text is None: text = "&#%d;" % ord(char) append(text) return string.join(out, "") try: return _encode(pattern.sub(escape_entities, text), "ascii") except TypeError: _raise_serialization_error(text) # # the following functions assume an ascii-compatible encoding # (or "utf-16") def _escape_cdata(text, encoding=None, replace=string.replace): # escape character data try: if encoding: try: text = _encode(text, encoding) except UnicodeError: return _encode_entity(text) text = replace(text, "&", "&amp;") text = replace(text, "<", "&lt;") text = replace(text, ">", "&gt;") return text except (TypeError, AttributeError): _raise_serialization_error(text) def _escape_attrib(text, encoding=None, replace=string.replace): # escape attribute value try: if encoding: try: text = _encode(text, encoding) except UnicodeError: return _encode_entity(text) text = replace(text, "&", "&amp;") text = replace(text, "'", "&apos;") # FIXME: overkill text = replace(text, "\"", "&quot;") text = replace(text, "<", "&lt;") text = replace(text, ">", "&gt;") return text except (TypeError, AttributeError): _raise_serialization_error(text) def fixtag(tag, namespaces): # given a decorated tag (of the form {uri}tag), return prefixed # tag and namespace declaration, if any if isinstance(tag, QName): tag = tag.text namespace_uri, tag = string.split(tag[1:], "}", 1) prefix = namespaces.get(namespace_uri) if prefix is None: prefix = _namespace_map.get(namespace_uri) if prefix is None: prefix = "ns%d" % len(namespaces) namespaces[namespace_uri] = prefix if prefix == "xml": xmlns = None else: xmlns = ("xmlns:%s" % prefix, namespace_uri) else: xmlns = None return "%s:%s" % (prefix, tag), xmlns ## # Parses an XML document into an element tree. # # @param source A filename or file object containing XML data. # @param parser An optional parser instance. If not given, the # standard {@link XMLTreeBuilder} parser is used. # @return An ElementTree instance def parse(source, parser=None): tree = ElementTree() tree.parse(source, parser) return tree ## # Parses an XML document into an element tree incrementally, and reports # what's going on to the user. # # @param source A filename or file object containing XML data. # @param events A list of events to report back. If omitted, only "end" # events are reported. # @return A (event, elem) iterator. class iterparse: def __init__(self, source, events=None): if not hasattr(source, "read"): source = open(source, "rb") self._file = source self._events = [] self._index = 0 self.root = self._root = None self._parser = XMLTreeBuilder() # wire up the parser for event reporting parser = self._parser._parser append = self._events.append if events is None: events = ["end"] for event in events: if event == "start": try: parser.ordered_attributes = 1 parser.specified_attributes = 1 def handler(tag, attrib_in, event=event, append=append, start=self._parser._start_list): append((event, start(tag, attrib_in))) parser.StartElementHandler = handler except AttributeError: def handler(tag, attrib_in, event=event, append=append, start=self._parser._start): append((event, start(tag, attrib_in))) parser.StartElementHandler = handler elif event == "end": def handler(tag, event=event, append=append, end=self._parser._end): append((event, end(tag))) parser.EndElementHandler = handler elif event == "start-ns": def handler(prefix, uri, event=event, append=append): try: uri = _encode(uri, "ascii") except UnicodeError: pass append((event, (prefix or "", uri))) parser.StartNamespaceDeclHandler = handler elif event == "end-ns": def handler(prefix, event=event, append=append): append((event, None)) parser.EndNamespaceDeclHandler = handler def next(self): while 1: try: item = self._events[self._index] except IndexError: if self._parser is None: self.root = self._root try: raise StopIteration except NameError: raise IndexError # load event buffer del self._events[:] self._index = 0 data = self._file.read(16384) if data: self._parser.feed(data) else: self._root = self._parser.close() self._parser = None else: self._index = self._index + 1 return item try: iter def __iter__(self): return self except NameError: def __getitem__(self, index): return self.next() ## # Parses an XML document from a string constant. This function can # be used to embed "XML literals" in Python code. # # @param source A string containing XML data. # @return An Element instance. # @defreturn Element def XML(text): parser = XMLTreeBuilder() parser.feed(text) return parser.close() ## # Parses an XML document from a string constant, and also returns # a dictionary which maps from element id:s to elements. # # @param source A string containing XML data. # @return A tuple containing an Element instance and a dictionary. # @defreturn (Element, dictionary) def XMLID(text): parser = XMLTreeBuilder() parser.feed(text) tree = parser.close() ids = {} for elem in tree.getiterator(): id = elem.get("id") if id: ids[id] = elem return tree, ids ## # Parses an XML document from a string constant. Same as {@link #XML}. # # @def fromstring(text) # @param source A string containing XML data. # @return An Element instance. # @defreturn Element fromstring = XML ## # Generates a string representation of an XML element, including all # subelements. # # @param element An Element instance. # @return An encoded string containing the XML data. # @defreturn string def tostring(element, encoding=None): class dummy: pass data = [] file = dummy() file.write = data.append ElementTree(element).write(file, encoding) return string.join(data, "") ## # Generic element structure builder. This builder converts a sequence # of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link # #TreeBuilder.end} method calls to a well-formed element structure. # <p> # You can use this class to build an element structure using a custom XML # parser, or a parser for some other XML-like format. # # @param element_factory Optional element factory. This factory # is called to create new Element instances, as necessary. class TreeBuilder: def __init__(self, element_factory=None): self._data = [] # data collector self._elem = [] # element stack self._last = None # last element self._tail = None # true if we're after an end tag if element_factory is None: element_factory = _ElementInterface self._factory = element_factory ## # Flushes the parser buffers, and returns the toplevel documen # element. # # @return An Element instance. # @defreturn Element def close(self): assert len(self._elem) == 0, "missing end tags" assert self._last != None, "missing toplevel element" return self._last def _flush(self): if self._data: if self._last is not None: text = string.join(self._data, "") if self._tail: assert self._last.tail is None, "internal error (tail)" self._last.tail = text else: assert self._last.text is None, "internal error (text)" self._last.text = text self._data = [] ## # Adds text to the current element. # # @param data A string. This should be either an 8-bit string # containing ASCII text, or a Unicode string. def data(self, data): self._data.append(data) ## # Opens a new element. # # @param tag The element name. # @param attrib A dictionary containing element attributes. # @return The opened element. # @defreturn Element def start(self, tag, attrs): self._flush() self._last = elem = self._factory(tag, attrs) if self._elem: self._elem[-1].append(elem) self._elem.append(elem) self._tail = 0 return elem ## # Closes the current element. # # @param tag The element name. # @return The closed element. # @defreturn Element def end(self, tag): self._flush() self._last = self._elem.pop() assert self._last.tag == tag,\ "end tag mismatch (expected %s, got %s)" % ( self._last.tag, tag) self._tail = 1 return self._last ## # Element structure builder for XML source data, based on the # <b>expat</b> parser. # # @keyparam target Target object. If omitted, the builder uses an # instance of the standard {@link #TreeBuilder} class. # @keyparam html Predefine HTML entities. This flag is not supported # by the current implementation. # @see #ElementTree # @see #TreeBuilder class XMLTreeBuilder: def __init__(self, html=0, target=None): try: from xml.parsers import expat except ImportError: raise ImportError( "No module named expat; use SimpleXMLTreeBuilder instead" ) self._parser = parser = expat.ParserCreate(None, "}") if target is None: target = TreeBuilder() self._target = target self._names = {} # name memo cache # callbacks parser.DefaultHandlerExpand = self._default parser.StartElementHandler = self._start parser.EndElementHandler = self._end parser.CharacterDataHandler = self._data # let expat do the buffering, if supported try: self._parser.buffer_text = 1 except AttributeError: pass # use new-style attribute handling, if supported try: self._parser.ordered_attributes = 1 self._parser.specified_attributes = 1 parser.StartElementHandler = self._start_list except AttributeError: pass encoding = None if not parser.returns_unicode: encoding = "utf-8" # target.xml(encoding, None) self._doctype = None self.entity = {} def _fixtext(self, text): # convert text string to ascii, if possible try: return _encode(text, "ascii") except UnicodeError: return text def _fixname(self, key): # expand qname, and convert name string to ascii, if possible try: name = self._names[key] except KeyError: name = key if "}" in name: name = "{" + name self._names[key] = name = self._fixtext(name) return name def _start(self, tag, attrib_in): fixname = self._fixname tag = fixname(tag) attrib = {} for key, value in attrib_in.items(): attrib[fixname(key)] = self._fixtext(value) return self._target.start(tag, attrib) def _start_list(self, tag, attrib_in): fixname = self._fixname tag = fixname(tag) attrib = {} if attrib_in: for i in range(0, len(attrib_in), 2): attrib[fixname(attrib_in[i])] = self._fixtext(attrib_in[i+1]) return self._target.start(tag, attrib) def _data(self, text): return self._target.data(self._fixtext(text)) def _end(self, tag): return self._target.end(self._fixname(tag)) def _default(self, text): prefix = text[:1] if prefix == "&": # deal with undefined entities try: self._target.data(self.entity[text[1:-1]]) except KeyError: from xml.parsers import expat raise expat.error( "undefined entity %s: line %d, column %d" % (text, self._parser.ErrorLineNumber, self._parser.ErrorColumnNumber) ) elif prefix == "<" and text[:9] == "<!DOCTYPE": self._doctype = [] # inside a doctype declaration elif self._doctype is not None: # parse doctype contents if prefix == ">": self._doctype = None return text = string.strip(text) if not text: return self._doctype.append(text) n = len(self._doctype) if n > 2: type = self._doctype[1] if type == "PUBLIC" and n == 4: name, type, pubid, system = self._doctype elif type == "SYSTEM" and n == 3: name, type, system = self._doctype pubid = None else: return if pubid: pubid = pubid[1:-1] self.doctype(name, pubid, system[1:-1]) self._doctype = None ## # Handles a doctype declaration. # # @param name Doctype name. # @param pubid Public identifier. # @param system System identifier. def doctype(self, name, pubid, system): pass ## # Feeds data to the parser. # # @param data Encoded data. def feed(self, data): self._parser.Parse(data, 0) ## # Finishes feeding data to the parser. # # @return An element structure. # @defreturn Element def close(self): self._parser.Parse("", 1) # end of data tree = self._target.close() del self._target, self._parser # get rid of circular references return tree # compatibility XMLParser = XMLTreeBuilder
en
0.611865
# # ElementTree # $Id: ElementTree.py 2326 2005-03-17 07:45:21Z fredrik $ # # light-weight XML support for Python 1.5.2 and later. # # history: # 2001-10-20 fl created (from various sources) # 2001-11-01 fl return root from parse method # 2002-02-16 fl sort attributes in lexical order # 2002-04-06 fl TreeBuilder refactoring, added PythonDoc markup # 2002-05-01 fl finished TreeBuilder refactoring # 2002-07-14 fl added basic namespace support to ElementTree.write # 2002-07-25 fl added QName attribute support # 2002-10-20 fl fixed encoding in write # 2002-11-24 fl changed default encoding to ascii; fixed attribute encoding # 2002-11-27 fl accept file objects or file names for parse/write # 2002-12-04 fl moved XMLTreeBuilder back to this module # 2003-01-11 fl fixed entity encoding glitch for us-ascii # 2003-02-13 fl added XML literal factory # 2003-02-21 fl added ProcessingInstruction/PI factory # 2003-05-11 fl added tostring/fromstring helpers # 2003-05-26 fl added ElementPath support # 2003-07-05 fl added makeelement factory method # 2003-07-28 fl added more well-known namespace prefixes # 2003-08-15 fl fixed typo in ElementTree.findtext (<NAME>) # 2003-09-04 fl fall back on emulator if ElementPath is not installed # 2003-10-31 fl markup updates # 2003-11-15 fl fixed nested namespace bug # 2004-03-28 fl added XMLID helper # 2004-06-02 fl added default support to findtext # 2004-06-08 fl fixed encoding of non-ascii element/attribute names # 2004-08-23 fl take advantage of post-2.1 expat features # 2005-02-01 fl added iterparse implementation # 2005-03-02 fl fixed iterparse support for pre-2.2 versions # # Copyright (c) 1999-2005 by <NAME>. All rights reserved. # # <EMAIL> # http://www.pythonware.com # # -------------------------------------------------------------------- # The ElementTree toolkit is # # Copyright (c) 1999-2005 by <NAME> # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/2.4/license for licensing details. # public symbols ## # The <b>Element</b> type is a flexible container object, designed to # store hierarchical data structures in memory. The type can be # described as a cross between a list and a dictionary. # <p> # Each element has a number of properties associated with it: # <ul> # <li>a <i>tag</i>. This is a string identifying what kind of data # this element represents (the element type, in other words).</li> # <li>a number of <i>attributes</i>, stored in a Python dictionary.</li> # <li>a <i>text</i> string.</li> # <li>an optional <i>tail</i> string.</li> # <li>a number of <i>child elements</i>, stored in a Python sequence</li> # </ul> # # To create an element instance, use the {@link #Element} or {@link # #SubElement} factory functions. # <p> # The {@link #ElementTree} class can be used to wrap an element # structure, and convert it from and to XML. ## # emulate pre-1.2 find/findtext/findall behaviour # FIXME: issue warning in this case? # TODO: add support for custom namespace resolvers/default namespaces # TODO: add improved support for incremental parsing ## # Internal element class. This class defines the Element interface, # and provides a reference implementation of this interface. # <p> # You should not create instances of this class directly. Use the # appropriate factory functions instead, such as {@link #Element} # and {@link #SubElement}. # # @see Element # @see SubElement # @see Comment # @see ProcessingInstruction # <tag attrib>text<child/>...</tag>tail ## # (Attribute) Element tag. ## # (Attribute) Element attribute dictionary. Where possible, use # {@link #_ElementInterface.get}, # {@link #_ElementInterface.set}, # {@link #_ElementInterface.keys}, and # {@link #_ElementInterface.items} to access # element attributes. ## # (Attribute) Text before first subelement. This is either a # string or the value None, if there was no text. ## # (Attribute) Text after this element's end tag, but before the # next sibling element's start tag. This is either a string or # the value None, if there was no text. # text after end tag, if any ## # Creates a new element object of the same type as this element. # # @param tag Element tag. # @param attrib Element attributes, given as a dictionary. # @return A new element instance. ## # Returns the number of subelements. # # @return The number of subelements. ## # Returns the given subelement. # # @param index What subelement to return. # @return The given subelement. # @exception IndexError If the given element does not exist. ## # Replaces the given subelement. # # @param index What subelement to replace. # @param element The new element value. # @exception IndexError If the given element does not exist. # @exception AssertionError If element is not a valid object. ## # Deletes the given subelement. # # @param index What subelement to delete. # @exception IndexError If the given element does not exist. ## # Returns a list containing subelements in the given range. # # @param start The first subelement to return. # @param stop The first subelement that shouldn't be returned. # @return A sequence object containing subelements. ## # Replaces a number of subelements with elements from a sequence. # # @param start The first subelement to replace. # @param stop The first subelement that shouldn't be replaced. # @param elements A sequence object with zero or more elements. # @exception AssertionError If a sequence member is not a valid object. ## # Deletes a number of subelements. # # @param start The first subelement to delete. # @param stop The first subelement to leave in there. ## # Adds a subelement to the end of this element. # # @param element The element to add. # @exception AssertionError If a sequence member is not a valid object. ## # Inserts a subelement at the given position in this element. # # @param index Where to insert the new subelement. # @exception AssertionError If the element is not a valid object. ## # Removes a matching subelement. Unlike the <b>find</b> methods, # this method compares elements based on identity, not on tag # value or contents. # # @param element What element to remove. # @exception ValueError If a matching element could not be found. # @exception AssertionError If the element is not a valid object. ## # Returns all subelements. The elements are returned in document # order. # # @return A list of subelements. # @defreturn list of Element instances ## # Finds the first matching subelement, by tag name or path. # # @param path What element to look for. # @return The first matching element, or None if no element was found. # @defreturn Element or None ## # Finds text for the first matching subelement, by tag name or path. # # @param path What element to look for. # @param default What to return if the element was not found. # @return The text content of the first matching element, or the # default value no element was found. Note that if the element # has is found, but has no text content, this method returns an # empty string. # @defreturn string ## # Finds all matching subelements, by tag name or path. # # @param path What element to look for. # @return A list or iterator containing all matching elements, # in document order. # @defreturn list of Element instances ## # Resets an element. This function removes all subelements, clears # all attributes, and sets the text and tail attributes to None. ## # Gets an element attribute. # # @param key What attribute to look for. # @param default What to return if the attribute was not found. # @return The attribute value, or the default value, if the # attribute was not found. # @defreturn string or None ## # Sets an element attribute. # # @param key What attribute to set. # @param value The attribute value. ## # Gets a list of attribute names. The names are returned in an # arbitrary order (just like for an ordinary Python dictionary). # # @return A list of element attribute names. # @defreturn list of strings ## # Gets element attributes, as a sequence. The attributes are # returned in an arbitrary order. # # @return A list of (name, value) tuples for all attributes. # @defreturn list of (string, string) tuples ## # Creates a tree iterator. The iterator loops over this element # and all subelements, in document order, and returns all elements # with a matching tag. # <p> # If the tree structure is modified during iteration, the result # is undefined. # # @param tag What tags to look for (default is to return all elements). # @return A list or iterator containing all the matching elements. # @defreturn list or iterator # compatibility ## # Element factory. This function returns an object implementing the # standard Element interface. The exact class or type of that object # is implementation dependent, but it will always be compatible with # the {@link #_ElementInterface} class in this module. # <p> # The element name, attribute names, and attribute values can be # either 8-bit ASCII strings or Unicode strings. # # @param tag The element name. # @param attrib An optional dictionary, containing element attributes. # @param **extra Additional attributes, given as keyword arguments. # @return An element instance. # @defreturn Element ## # Subelement factory. This function creates an element instance, and # appends it to an existing element. # <p> # The element name, attribute names, and attribute values can be # either 8-bit ASCII strings or Unicode strings. # # @param parent The parent element. # @param tag The subelement name. # @param attrib An optional dictionary, containing element attributes. # @param **extra Additional attributes, given as keyword arguments. # @return An element instance. # @defreturn Element ## # Comment element factory. This factory function creates a special # element that will be serialized as an XML comment. # <p> # The comment string can be either an 8-bit ASCII string or a Unicode # string. # # @param text A string containing the comment string. # @return An element instance, representing a comment. # @defreturn Element ## # PI element factory. This factory function creates a special element # that will be serialized as an XML processing instruction. # # @param target A string containing the PI target. # @param text A string containing the PI contents, if any. # @return An element instance, representing a PI. # @defreturn Element ## # QName wrapper. This can be used to wrap a QName attribute value, in # order to get proper namespace handling on output. # # @param text A string containing the QName value, in the form {uri}local, # or, if the tag argument is given, the URI part of a QName. # @param tag Optional tag. If given, the first argument is interpreted as # an URI, and this argument is interpreted as a local name. # @return An opaque object, representing the QName. ## # ElementTree wrapper class. This class represents an entire element # hierarchy, and adds some extra support for serialization to and from # standard XML. # # @param element Optional root element. # @keyparam file Optional file handle or name. If given, the # tree is initialized with the contents of this XML file. # first node ## # Gets the root element for this tree. # # @return An element instance. # @defreturn Element ## # Replaces the root element for this tree. This discards the # current contents of the tree, and replaces it with the given # element. Use with care. # # @param element An element instance. ## # Loads an external XML document into this element tree. # # @param source A file name or file object. # @param parser An optional parser instance. If not given, the # standard {@link XMLTreeBuilder} parser is used. # @return The document root element. # @defreturn Element ## # Creates a tree iterator for the root element. The iterator loops # over all elements in this tree, in document order. # # @param tag What tags to look for (default is to return all elements) # @return An iterator. # @defreturn iterator ## # Finds the first toplevel element with given tag. # Same as getroot().find(path). # # @param path What element to look for. # @return The first matching element, or None if no element was found. # @defreturn Element or None ## # Finds the element text for the first toplevel element with given # tag. Same as getroot().findtext(path). # # @param path What toplevel element to look for. # @param default What to return if the element was not found. # @return The text content of the first matching element, or the # default value no element was found. Note that if the element # has is found, but has no text content, this method returns an # empty string. # @defreturn string ## # Finds all toplevel elements with the given tag. # Same as getroot().findall(path). # # @param path What element to look for. # @return A list or iterator containing all matching elements, # in document order. # @defreturn list of Element instances ## # Writes the element tree to a file, as XML. # # @param file A file name, or a file object opened for writing. # @param encoding Optional output encoding (default is US-ASCII). # write XML to file # new namespaces in this scope # lexical order # -------------------------------------------------------------------- # helpers ## # Checks if an object appears to be a valid element object. # # @param An element instance. # @return A true value if this is an element object. # @defreturn flag # FIXME: not sure about this; might be a better idea to look # for tag/attrib/text attributes ## # Writes an element tree or element structure to sys.stdout. This # function should be used for debugging only. # <p> # The exact output format is implementation dependent. In this # version, it's written as an ordinary XML file. # # @param elem An element tree or an individual element. # debugging # 1.5.2: assume the string uses the right encoding # 1.5.2 # "well-known" namespace prefixes #": "rdf", # map reserved and non-ascii characters to numerical entities #%d;" % ord(char) # # the following functions assume an ascii-compatible encoding # (or "utf-16") # escape character data # escape attribute value # FIXME: overkill # given a decorated tag (of the form {uri}tag), return prefixed # tag and namespace declaration, if any ## # Parses an XML document into an element tree. # # @param source A filename or file object containing XML data. # @param parser An optional parser instance. If not given, the # standard {@link XMLTreeBuilder} parser is used. # @return An ElementTree instance ## # Parses an XML document into an element tree incrementally, and reports # what's going on to the user. # # @param source A filename or file object containing XML data. # @param events A list of events to report back. If omitted, only "end" # events are reported. # @return A (event, elem) iterator. # wire up the parser for event reporting # load event buffer ## # Parses an XML document from a string constant. This function can # be used to embed "XML literals" in Python code. # # @param source A string containing XML data. # @return An Element instance. # @defreturn Element ## # Parses an XML document from a string constant, and also returns # a dictionary which maps from element id:s to elements. # # @param source A string containing XML data. # @return A tuple containing an Element instance and a dictionary. # @defreturn (Element, dictionary) ## # Parses an XML document from a string constant. Same as {@link #XML}. # # @def fromstring(text) # @param source A string containing XML data. # @return An Element instance. # @defreturn Element ## # Generates a string representation of an XML element, including all # subelements. # # @param element An Element instance. # @return An encoded string containing the XML data. # @defreturn string ## # Generic element structure builder. This builder converts a sequence # of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link # #TreeBuilder.end} method calls to a well-formed element structure. # <p> # You can use this class to build an element structure using a custom XML # parser, or a parser for some other XML-like format. # # @param element_factory Optional element factory. This factory # is called to create new Element instances, as necessary. # data collector # element stack # last element # true if we're after an end tag ## # Flushes the parser buffers, and returns the toplevel documen # element. # # @return An Element instance. # @defreturn Element ## # Adds text to the current element. # # @param data A string. This should be either an 8-bit string # containing ASCII text, or a Unicode string. ## # Opens a new element. # # @param tag The element name. # @param attrib A dictionary containing element attributes. # @return The opened element. # @defreturn Element ## # Closes the current element. # # @param tag The element name. # @return The closed element. # @defreturn Element ## # Element structure builder for XML source data, based on the # <b>expat</b> parser. # # @keyparam target Target object. If omitted, the builder uses an # instance of the standard {@link #TreeBuilder} class. # @keyparam html Predefine HTML entities. This flag is not supported # by the current implementation. # @see #ElementTree # @see #TreeBuilder # name memo cache # callbacks # let expat do the buffering, if supported # use new-style attribute handling, if supported # target.xml(encoding, None) # convert text string to ascii, if possible # expand qname, and convert name string to ascii, if possible # deal with undefined entities # inside a doctype declaration # parse doctype contents ## # Handles a doctype declaration. # # @param name Doctype name. # @param pubid Public identifier. # @param system System identifier. ## # Feeds data to the parser. # # @param data Encoded data. ## # Finishes feeding data to the parser. # # @return An element structure. # @defreturn Element # end of data # get rid of circular references # compatibility
1.870949
2
main.py
gwthomas/IQL-PyTorch
6
6628280
from pathlib import Path import gym import d4rl import numpy as np import torch from tqdm import trange from src.iql import ImplicitQLearning from src.policy import GaussianPolicy, DeterministicPolicy from src.value_functions import TwinQ, ValueFunction from src.util import return_range, set_seed, Log, sample_batch, torchify, evaluate_policy def get_env_and_dataset(log, env_name, max_episode_steps): env = gym.make(env_name) dataset = d4rl.qlearning_dataset(env) if any(s in env_name for s in ('halfcheetah', 'hopper', 'walker2d')): min_ret, max_ret = return_range(dataset, max_episode_steps) log(f'Dataset returns have range [{min_ret}, {max_ret}]') dataset['rewards'] /= (max_ret - min_ret) dataset['rewards'] *= max_episode_steps elif 'antmaze' in env_name: dataset['rewards'] -= 1. for k, v in dataset.items(): dataset[k] = torchify(v) return env, dataset def main(args): torch.set_num_threads(1) log = Log(Path(args.log_dir)/args.env_name, vars(args)) log(f'Log dir: {log.dir}') env, dataset = get_env_and_dataset(log, args.env_name, args.max_episode_steps) obs_dim = dataset['observations'].shape[1] act_dim = dataset['actions'].shape[1] # this assume continuous actions set_seed(args.seed, env=env) if args.deterministic_policy: policy = DeterministicPolicy(obs_dim, act_dim, hidden_dim=args.hidden_dim, n_hidden=args.n_hidden) else: policy = GaussianPolicy(obs_dim, act_dim, hidden_dim=args.hidden_dim, n_hidden=args.n_hidden) def eval_policy(): eval_returns = np.array([evaluate_policy(env, policy, args.max_episode_steps) \ for _ in range(args.n_eval_episodes)]) normalized_returns = d4rl.get_normalized_score(args.env_name, eval_returns) * 100.0 log.row({ 'return mean': eval_returns.mean(), 'return std': eval_returns.std(), 'normalized return mean': normalized_returns.mean(), 'normalized return std': normalized_returns.std(), }) iql = ImplicitQLearning( qf=TwinQ(obs_dim, act_dim, hidden_dim=args.hidden_dim, n_hidden=args.n_hidden), vf=ValueFunction(obs_dim, hidden_dim=args.hidden_dim, n_hidden=args.n_hidden), policy=policy, optimizer_factory=lambda params: torch.optim.Adam(params, lr=args.learning_rate), max_steps=args.n_steps, tau=args.tau, beta=args.beta, alpha=args.alpha, discount=args.discount ) for step in trange(args.n_steps): iql.update(**sample_batch(dataset, args.batch_size)) if (step+1) % args.eval_period == 0: eval_policy() torch.save(iql.state_dict(), log.dir/'final.pt') log.close() if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('--env-name', required=True) parser.add_argument('--log-dir', required=True) parser.add_argument('--seed', type=int, default=0) parser.add_argument('--discount', type=float, default=0.99) parser.add_argument('--hidden-dim', type=int, default=256) parser.add_argument('--n-hidden', type=int, default=2) parser.add_argument('--n-steps', type=int, default=10**6) parser.add_argument('--batch-size', type=int, default=256) parser.add_argument('--learning-rate', type=float, default=3e-4) parser.add_argument('--alpha', type=float, default=0.005) parser.add_argument('--tau', type=float, default=0.7) parser.add_argument('--beta', type=float, default=3.0) parser.add_argument('--deterministic-policy', action='store_true') parser.add_argument('--eval-period', type=int, default=5000) parser.add_argument('--n-eval-episodes', type=int, default=10) parser.add_argument('--max-episode-steps', type=int, default=1000) main(parser.parse_args())
from pathlib import Path import gym import d4rl import numpy as np import torch from tqdm import trange from src.iql import ImplicitQLearning from src.policy import GaussianPolicy, DeterministicPolicy from src.value_functions import TwinQ, ValueFunction from src.util import return_range, set_seed, Log, sample_batch, torchify, evaluate_policy def get_env_and_dataset(log, env_name, max_episode_steps): env = gym.make(env_name) dataset = d4rl.qlearning_dataset(env) if any(s in env_name for s in ('halfcheetah', 'hopper', 'walker2d')): min_ret, max_ret = return_range(dataset, max_episode_steps) log(f'Dataset returns have range [{min_ret}, {max_ret}]') dataset['rewards'] /= (max_ret - min_ret) dataset['rewards'] *= max_episode_steps elif 'antmaze' in env_name: dataset['rewards'] -= 1. for k, v in dataset.items(): dataset[k] = torchify(v) return env, dataset def main(args): torch.set_num_threads(1) log = Log(Path(args.log_dir)/args.env_name, vars(args)) log(f'Log dir: {log.dir}') env, dataset = get_env_and_dataset(log, args.env_name, args.max_episode_steps) obs_dim = dataset['observations'].shape[1] act_dim = dataset['actions'].shape[1] # this assume continuous actions set_seed(args.seed, env=env) if args.deterministic_policy: policy = DeterministicPolicy(obs_dim, act_dim, hidden_dim=args.hidden_dim, n_hidden=args.n_hidden) else: policy = GaussianPolicy(obs_dim, act_dim, hidden_dim=args.hidden_dim, n_hidden=args.n_hidden) def eval_policy(): eval_returns = np.array([evaluate_policy(env, policy, args.max_episode_steps) \ for _ in range(args.n_eval_episodes)]) normalized_returns = d4rl.get_normalized_score(args.env_name, eval_returns) * 100.0 log.row({ 'return mean': eval_returns.mean(), 'return std': eval_returns.std(), 'normalized return mean': normalized_returns.mean(), 'normalized return std': normalized_returns.std(), }) iql = ImplicitQLearning( qf=TwinQ(obs_dim, act_dim, hidden_dim=args.hidden_dim, n_hidden=args.n_hidden), vf=ValueFunction(obs_dim, hidden_dim=args.hidden_dim, n_hidden=args.n_hidden), policy=policy, optimizer_factory=lambda params: torch.optim.Adam(params, lr=args.learning_rate), max_steps=args.n_steps, tau=args.tau, beta=args.beta, alpha=args.alpha, discount=args.discount ) for step in trange(args.n_steps): iql.update(**sample_batch(dataset, args.batch_size)) if (step+1) % args.eval_period == 0: eval_policy() torch.save(iql.state_dict(), log.dir/'final.pt') log.close() if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('--env-name', required=True) parser.add_argument('--log-dir', required=True) parser.add_argument('--seed', type=int, default=0) parser.add_argument('--discount', type=float, default=0.99) parser.add_argument('--hidden-dim', type=int, default=256) parser.add_argument('--n-hidden', type=int, default=2) parser.add_argument('--n-steps', type=int, default=10**6) parser.add_argument('--batch-size', type=int, default=256) parser.add_argument('--learning-rate', type=float, default=3e-4) parser.add_argument('--alpha', type=float, default=0.005) parser.add_argument('--tau', type=float, default=0.7) parser.add_argument('--beta', type=float, default=3.0) parser.add_argument('--deterministic-policy', action='store_true') parser.add_argument('--eval-period', type=int, default=5000) parser.add_argument('--n-eval-episodes', type=int, default=10) parser.add_argument('--max-episode-steps', type=int, default=1000) main(parser.parse_args())
en
0.917702
# this assume continuous actions
2.086552
2
tests/modules/projects/test_models.py
karenc/houston
0
6628281
# -*- coding: utf-8 -*- # pylint: disable=invalid-name,missing-docstring import sqlalchemy import logging def test_project_add_members( db, temp_user, researcher_1, researcher_2 ): # pylint: disable=unused-argument from app.modules.projects.models import ( Project, ProjectUserMembershipEnrollment, ) temp_proj = Project( title='Temp Project', owner_guid=temp_user.guid, ) temp_enrollment = ProjectUserMembershipEnrollment() temp_enrollment.user = temp_user temp_proj.user_membership_enrollments.append(temp_enrollment) # Doing this multiple times should not have an effect temp_proj.user_membership_enrollments.append(temp_enrollment) temp_proj.user_membership_enrollments.append(temp_enrollment) temp_proj.user_membership_enrollments.append(temp_enrollment) with db.session.begin(): db.session.add(temp_proj) db.session.add(temp_enrollment) db.session.refresh(temp_user) db.session.refresh(temp_proj) db.session.refresh(temp_enrollment) for value in temp_proj.user_membership_enrollments: assert value in temp_user.project_membership_enrollments logging.info(temp_user.project_membership_enrollments) logging.info(temp_proj.user_membership_enrollments) logging.info(temp_user.get_projects()) logging.info(temp_proj) assert len(temp_user.get_projects()) >= 1 assert temp_proj in temp_user.get_projects() assert len(temp_proj.get_members()) == 1 assert temp_user in temp_proj.get_members() try: duplicate_enrollment = ProjectUserMembershipEnrollment() duplicate_enrollment.user = temp_user temp_proj.user_membership_enrollments.append(duplicate_enrollment) with db.session.begin(): db.session.add(duplicate_enrollment) except (sqlalchemy.orm.exc.FlushError, sqlalchemy.exc.IntegrityError): pass temp_proj.add_user_in_context(researcher_1) # try removing a user that's not in the project temp_proj.remove_user_in_context(researcher_2) temp_proj.remove_user_in_context(researcher_1) with db.session.begin(): db.session.delete(temp_proj) db.session.delete(temp_enrollment)
# -*- coding: utf-8 -*- # pylint: disable=invalid-name,missing-docstring import sqlalchemy import logging def test_project_add_members( db, temp_user, researcher_1, researcher_2 ): # pylint: disable=unused-argument from app.modules.projects.models import ( Project, ProjectUserMembershipEnrollment, ) temp_proj = Project( title='Temp Project', owner_guid=temp_user.guid, ) temp_enrollment = ProjectUserMembershipEnrollment() temp_enrollment.user = temp_user temp_proj.user_membership_enrollments.append(temp_enrollment) # Doing this multiple times should not have an effect temp_proj.user_membership_enrollments.append(temp_enrollment) temp_proj.user_membership_enrollments.append(temp_enrollment) temp_proj.user_membership_enrollments.append(temp_enrollment) with db.session.begin(): db.session.add(temp_proj) db.session.add(temp_enrollment) db.session.refresh(temp_user) db.session.refresh(temp_proj) db.session.refresh(temp_enrollment) for value in temp_proj.user_membership_enrollments: assert value in temp_user.project_membership_enrollments logging.info(temp_user.project_membership_enrollments) logging.info(temp_proj.user_membership_enrollments) logging.info(temp_user.get_projects()) logging.info(temp_proj) assert len(temp_user.get_projects()) >= 1 assert temp_proj in temp_user.get_projects() assert len(temp_proj.get_members()) == 1 assert temp_user in temp_proj.get_members() try: duplicate_enrollment = ProjectUserMembershipEnrollment() duplicate_enrollment.user = temp_user temp_proj.user_membership_enrollments.append(duplicate_enrollment) with db.session.begin(): db.session.add(duplicate_enrollment) except (sqlalchemy.orm.exc.FlushError, sqlalchemy.exc.IntegrityError): pass temp_proj.add_user_in_context(researcher_1) # try removing a user that's not in the project temp_proj.remove_user_in_context(researcher_2) temp_proj.remove_user_in_context(researcher_1) with db.session.begin(): db.session.delete(temp_proj) db.session.delete(temp_enrollment)
en
0.794796
# -*- coding: utf-8 -*- # pylint: disable=invalid-name,missing-docstring # pylint: disable=unused-argument # Doing this multiple times should not have an effect # try removing a user that's not in the project
2.27419
2
tests/utils.py
reidab/csvkit
0
6628282
#!/usr/bin/env python """ To test standard input (without piped data), run each of: * csvclean * csvcut -c 1 * csvformat * csvgrep -c 1 -m d * csvjson --no-inference --stream --snifflimit 0 * csvstack * in2csv --format csv --no-inference --snifflimit 0 And paste: "a","b","c" "g","h","i" "d","e","f" """ import sys import warnings from contextlib import contextmanager import agate import six try: import unittest2 as unittest except ImportError: import unittest from csvkit.exceptions import ColumnIdentifierError, RequiredHeaderError @contextmanager def stderr_as_stdout(): temp = sys.stderr sys.stderr = sys.stdout yield sys.stderr = temp @contextmanager def stdin_as_string(content): temp = sys.stdin sys.stdin = content yield sys.stdin = temp class CSVKitTestCase(unittest.TestCase): warnings.filterwarnings(action='ignore', module='agate') def get_output(self, args): output_file = six.StringIO() utility = self.Utility(args, output_file) utility.run() output = output_file.getvalue() output_file.close() return output def get_output_as_io(self, args): return six.StringIO(self.get_output(args)) def get_output_as_list(self, args): return self.get_output(args).split('\n') def get_output_as_reader(self, args): return agate.csv.reader(self.get_output_as_io(args)) def assertRows(self, args, rows): reader = self.get_output_as_reader(args) for row in rows: self.assertEqual(next(reader), row) self.assertRaises(StopIteration, next, reader) def assertLines(self, args, rows, newline_at_eof=True): lines = self.get_output_as_list(args) if newline_at_eof: rows.append('') for i, row in enumerate(rows): self.assertEqual(lines[i], row) self.assertEqual(len(lines), len(rows)) class EmptyFileTests(object): def test_empty(self): with open('examples/empty.csv') as f: with stdin_as_string(f): utility = self.Utility(getattr(self, 'default_args', [])) utility.run() class NamesTests(object): def test_names(self): output = self.get_output_as_io(['-n', 'examples/dummy.csv']) self.assertEqual(next(output), ' 1: a\n') self.assertEqual(next(output), ' 2: b\n') self.assertEqual(next(output), ' 3: c\n') def test_invalid_options(self): args = ['-n', '--no-header-row', 'examples/dummy.csv'] output_file = six.StringIO() utility = self.Utility(args, output_file) with self.assertRaises(RequiredHeaderError): utility.run() output_file.close() class ColumnsTests(object): def test_invalid_column(self): args = getattr(self, 'columns_args', []) + ['-c', '0', 'examples/dummy.csv'] output_file = six.StringIO() utility = self.Utility(args, output_file) with self.assertRaises(ColumnIdentifierError): utility.run() output_file.close()
#!/usr/bin/env python """ To test standard input (without piped data), run each of: * csvclean * csvcut -c 1 * csvformat * csvgrep -c 1 -m d * csvjson --no-inference --stream --snifflimit 0 * csvstack * in2csv --format csv --no-inference --snifflimit 0 And paste: "a","b","c" "g","h","i" "d","e","f" """ import sys import warnings from contextlib import contextmanager import agate import six try: import unittest2 as unittest except ImportError: import unittest from csvkit.exceptions import ColumnIdentifierError, RequiredHeaderError @contextmanager def stderr_as_stdout(): temp = sys.stderr sys.stderr = sys.stdout yield sys.stderr = temp @contextmanager def stdin_as_string(content): temp = sys.stdin sys.stdin = content yield sys.stdin = temp class CSVKitTestCase(unittest.TestCase): warnings.filterwarnings(action='ignore', module='agate') def get_output(self, args): output_file = six.StringIO() utility = self.Utility(args, output_file) utility.run() output = output_file.getvalue() output_file.close() return output def get_output_as_io(self, args): return six.StringIO(self.get_output(args)) def get_output_as_list(self, args): return self.get_output(args).split('\n') def get_output_as_reader(self, args): return agate.csv.reader(self.get_output_as_io(args)) def assertRows(self, args, rows): reader = self.get_output_as_reader(args) for row in rows: self.assertEqual(next(reader), row) self.assertRaises(StopIteration, next, reader) def assertLines(self, args, rows, newline_at_eof=True): lines = self.get_output_as_list(args) if newline_at_eof: rows.append('') for i, row in enumerate(rows): self.assertEqual(lines[i], row) self.assertEqual(len(lines), len(rows)) class EmptyFileTests(object): def test_empty(self): with open('examples/empty.csv') as f: with stdin_as_string(f): utility = self.Utility(getattr(self, 'default_args', [])) utility.run() class NamesTests(object): def test_names(self): output = self.get_output_as_io(['-n', 'examples/dummy.csv']) self.assertEqual(next(output), ' 1: a\n') self.assertEqual(next(output), ' 2: b\n') self.assertEqual(next(output), ' 3: c\n') def test_invalid_options(self): args = ['-n', '--no-header-row', 'examples/dummy.csv'] output_file = six.StringIO() utility = self.Utility(args, output_file) with self.assertRaises(RequiredHeaderError): utility.run() output_file.close() class ColumnsTests(object): def test_invalid_column(self): args = getattr(self, 'columns_args', []) + ['-c', '0', 'examples/dummy.csv'] output_file = six.StringIO() utility = self.Utility(args, output_file) with self.assertRaises(ColumnIdentifierError): utility.run() output_file.close()
en
0.315903
#!/usr/bin/env python To test standard input (without piped data), run each of: * csvclean * csvcut -c 1 * csvformat * csvgrep -c 1 -m d * csvjson --no-inference --stream --snifflimit 0 * csvstack * in2csv --format csv --no-inference --snifflimit 0 And paste: "a","b","c" "g","h","i" "d","e","f"
2.967879
3
hassio-google-drive-backup/dev/http_exception.py
voxipbx/hassio-addons
1
6628283
from aiohttp.web import HTTPClientError class HttpMultiException(HTTPClientError): def __init__(self, code): self.status_code = code
from aiohttp.web import HTTPClientError class HttpMultiException(HTTPClientError): def __init__(self, code): self.status_code = code
none
1
2.154283
2
displayio_labels/display_temperature_color.py
Neradoc/circuitpython-sample-scripts
3
6628284
<filename>displayio_labels/display_temperature_color.py import board import displayio import microcontroller import terminalio import time from adafruit_display_text.bitmap_label import Label import adafruit_fancyled.adafruit_fancyled as fancy blue = fancy.CRGB(0, 0, 1.0) red = fancy.CRGB(1.0, 0, 0) yellow = fancy.CRGB(1.0, 1.0, 0) white = fancy.CRGB(1.0, 1.0, 1.0) oled = board.DISPLAY splash = displayio.Group() title_label = Label( text="My Title", font=terminalio.FONT, color=0x00FF80, scale=3, anchored_position=(oled.width // 2, 0), anchor_point=(0.5, 0), ) temp_label = Label( text="Temperature:", font=terminalio.FONT, color=0xFFFFFF, scale=2, anchored_position=(0, 70), anchor_point=(0, 0.5), ) temp_value = Label( text="0 C", font=terminalio.FONT, color=0xFFFFFF, scale=2, anchored_position=(oled.width, 70), anchor_point=(1, 0.5), ) splash.append(title_label) splash.append(temp_label) splash.append(temp_value) oled.show(splash) def display_temperature(the_temp): if the_temp > 30: color = red.pack() elif the_temp > 20: color = fancy.mix(red, yellow, (30 - the_temp) / 10).pack() elif the_temp < 0: color = blue.pack() elif the_temp < 10: color = fancy.mix(blue, white, (the_temp) / 10).pack() elif the_temp < 20: color = fancy.mix(white, yellow, (the_temp - 10) / 10).pack() else: color = yellow.pack() temp_value.color = color temp_value.text = f"{the_temp:.1f} C" # test code showing the thing for cpu_temp in range(-5, 32*2): cpu_temp = cpu_temp / 2 display_temperature(cpu_temp) time.sleep(0.1) while True: cpu_temp = microcontroller.cpu.temperature display_temperature(cpu_temp) time.sleep(0.5)
<filename>displayio_labels/display_temperature_color.py import board import displayio import microcontroller import terminalio import time from adafruit_display_text.bitmap_label import Label import adafruit_fancyled.adafruit_fancyled as fancy blue = fancy.CRGB(0, 0, 1.0) red = fancy.CRGB(1.0, 0, 0) yellow = fancy.CRGB(1.0, 1.0, 0) white = fancy.CRGB(1.0, 1.0, 1.0) oled = board.DISPLAY splash = displayio.Group() title_label = Label( text="My Title", font=terminalio.FONT, color=0x00FF80, scale=3, anchored_position=(oled.width // 2, 0), anchor_point=(0.5, 0), ) temp_label = Label( text="Temperature:", font=terminalio.FONT, color=0xFFFFFF, scale=2, anchored_position=(0, 70), anchor_point=(0, 0.5), ) temp_value = Label( text="0 C", font=terminalio.FONT, color=0xFFFFFF, scale=2, anchored_position=(oled.width, 70), anchor_point=(1, 0.5), ) splash.append(title_label) splash.append(temp_label) splash.append(temp_value) oled.show(splash) def display_temperature(the_temp): if the_temp > 30: color = red.pack() elif the_temp > 20: color = fancy.mix(red, yellow, (30 - the_temp) / 10).pack() elif the_temp < 0: color = blue.pack() elif the_temp < 10: color = fancy.mix(blue, white, (the_temp) / 10).pack() elif the_temp < 20: color = fancy.mix(white, yellow, (the_temp - 10) / 10).pack() else: color = yellow.pack() temp_value.color = color temp_value.text = f"{the_temp:.1f} C" # test code showing the thing for cpu_temp in range(-5, 32*2): cpu_temp = cpu_temp / 2 display_temperature(cpu_temp) time.sleep(0.1) while True: cpu_temp = microcontroller.cpu.temperature display_temperature(cpu_temp) time.sleep(0.5)
en
0.633805
# test code showing the thing
3.064233
3
bardhub/playlist/migrations/0001_initial.py
migdotcom/music-library
0
6628285
# Generated by Django 3.0.5 on 2020-04-18 16:53 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Playlist', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('Playlist_image', models.CharField(blank=True, default=None, max_length=255, null=True)), ('Name', models.CharField(max_length=80)), ('Description', models.CharField(blank=True, default=None, max_length=255, null=True)), ('Play_count', models.IntegerField(default=0)), ('Time_stamp', models.DateTimeField(auto_now_add=True)), ], ), ]
# Generated by Django 3.0.5 on 2020-04-18 16:53 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Playlist', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('Playlist_image', models.CharField(blank=True, default=None, max_length=255, null=True)), ('Name', models.CharField(max_length=80)), ('Description', models.CharField(blank=True, default=None, max_length=255, null=True)), ('Play_count', models.IntegerField(default=0)), ('Time_stamp', models.DateTimeField(auto_now_add=True)), ], ), ]
en
0.812688
# Generated by Django 3.0.5 on 2020-04-18 16:53
1.790314
2
src/cli/create_service.py
Forcepoint/fp-bd-azure-casb
0
6628286
# # Author: <NAME> # created Date: 03-12-2019 import subprocess import yaml from subprocess import Popen from os import system, path class CreateService: def __init__(self, parser): self._parser = parser self._args = None self._settings = None def __call__(self, args): self._args = args with open(self._args.config_file) as f: self._settings = yaml.load(f, yaml.SafeLoader) result = self.is_service_exists(self._args.name) if result is True: self._parser.error("The service '{}' is already exists".format(self._args.name)) else: self._create_service(self._args.name) if self._args.start is True: result, error_code = self.is_service_running(self._args.name) if error_code == 1: self._parser.error("problem with executing commands") if error_code == 0 and result is True: self._parser.error("The service '{}' is already running".format(self._args.name)) system("systemctl daemon-reload") if self._args.start is True: system("systemctl start {}.service".format(self._args.name)) @staticmethod def execute_cmd(cmd): process = Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) output, errors = process.communicate() return output, errors def is_service_exists(self, name): service_path = "/etc/systemd/system/{}.service".format(name) return path.isfile(service_path) def is_service_running(self, name): cmd = ["systemctl", "list-units"] output, errors = self.execute_cmd(cmd) output = output.strip() if len(output) != 0: output = output.split("\n") for line in output: if line.strip().startswith("{}.service ".format(name)): return True, 0 return False, 0 return False, 1 def _create_service(self, name): service = """ [Unit] Description= run azure_casb.service Requires=syslog-ng.service After=syslog-ng.service [Service] ExecStart={}/scripts/azure_casb.sh run -c {} [Install] WantedBy=multi-user.target """.format(self._settings["application_directory"], self._settings["application_directory"] + "/settings.yml") service_path = "/etc/systemd/system/{}.service".format(name) with open(service_path, "w") as f: f.write(service) system("chmod 644 {}".format(service_path)) system("systemctl daemon-reload")
# # Author: <NAME> # created Date: 03-12-2019 import subprocess import yaml from subprocess import Popen from os import system, path class CreateService: def __init__(self, parser): self._parser = parser self._args = None self._settings = None def __call__(self, args): self._args = args with open(self._args.config_file) as f: self._settings = yaml.load(f, yaml.SafeLoader) result = self.is_service_exists(self._args.name) if result is True: self._parser.error("The service '{}' is already exists".format(self._args.name)) else: self._create_service(self._args.name) if self._args.start is True: result, error_code = self.is_service_running(self._args.name) if error_code == 1: self._parser.error("problem with executing commands") if error_code == 0 and result is True: self._parser.error("The service '{}' is already running".format(self._args.name)) system("systemctl daemon-reload") if self._args.start is True: system("systemctl start {}.service".format(self._args.name)) @staticmethod def execute_cmd(cmd): process = Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) output, errors = process.communicate() return output, errors def is_service_exists(self, name): service_path = "/etc/systemd/system/{}.service".format(name) return path.isfile(service_path) def is_service_running(self, name): cmd = ["systemctl", "list-units"] output, errors = self.execute_cmd(cmd) output = output.strip() if len(output) != 0: output = output.split("\n") for line in output: if line.strip().startswith("{}.service ".format(name)): return True, 0 return False, 0 return False, 1 def _create_service(self, name): service = """ [Unit] Description= run azure_casb.service Requires=syslog-ng.service After=syslog-ng.service [Service] ExecStart={}/scripts/azure_casb.sh run -c {} [Install] WantedBy=multi-user.target """.format(self._settings["application_directory"], self._settings["application_directory"] + "/settings.yml") service_path = "/etc/systemd/system/{}.service".format(name) with open(service_path, "w") as f: f.write(service) system("chmod 644 {}".format(service_path)) system("systemctl daemon-reload")
en
0.352675
# # Author: <NAME> # created Date: 03-12-2019 [Unit] Description= run azure_casb.service Requires=syslog-ng.service After=syslog-ng.service [Service] ExecStart={}/scripts/azure_casb.sh run -c {} [Install] WantedBy=multi-user.target
2.745373
3
holoviews/tests/core/testdecollation.py
goanpeca/holoviews
0
6628287
<gh_stars>0 from holoviews.core import HoloMap, NdOverlay, Overlay, GridSpace, DynamicMap from holoviews.element import Points from holoviews.element.comparison import ComparisonTestCase from holoviews.streams import Stream, PlotSize, RangeXY from holoviews.operation.datashader import spread, datashade import param class XY(Stream): x = param.Number(constant=True) y = param.Number(constant=True) Z = Stream.define("Z", z=0.0) PX = Stream.define("PX", px=1) class TestDecollation(ComparisonTestCase): def setUp(self): from holoviews.tests.teststreams import Sum, Val # kdims: a and b self.dmap_ab = DynamicMap( lambda a, b: Points([a, b]), kdims=['a', 'b'] ).redim.range(a=(0.0, 10.0), b=(0.0, 10.0)) # kdims: b self.dmap_b = DynamicMap( lambda b: Points([b, b]), kdims=['b'] ).redim.range(b=(0.0, 10.0)) # no kdims, XY stream self.xy_stream = XY() self.dmap_xy = DynamicMap( lambda x, y: Points([x, y]), streams=[self.xy_stream] ) # no kdims, Z stream self.z_stream = Z() self.dmap_z = DynamicMap( lambda z: Points([z, z]), streams=[self.z_stream] ) # dmap produced by chained datashade and shade self.px_stream = PX() self.dmap_spread_points = spread( datashade(Points([0.0, 1.0])), streams=[self.px_stream] ) # data shaded with kdims: a, b self.dmap_datashade_kdim_points = datashade(self.dmap_ab) # DynamicMap of a derived stream self.stream_val1 = Val() self.stream_val2 = Val() self.stream_val3 = Val() self.dmap_derived = DynamicMap( lambda v: Points([v, v]), streams=[ Sum([self.stream_val1, Sum([self.stream_val2, self.stream_val3])]) ] ) def test_decollate_layout_kdims(self): layout = self.dmap_ab + self.dmap_b decollated = layout.decollate() self.assertIsInstance(decollated, DynamicMap) self.assertEqual(decollated.kdims, self.dmap_ab.kdims) self.assertEqual( decollated[2, 3], Points([2, 3]) + Points([3, 3]) ) self.assertEqual( decollated.callback.callable(2, 3), Points([2, 3]) + Points([3, 3]) ) def test_decollate_layout_streams(self): layout = self.dmap_xy + self.dmap_z decollated = layout.decollate() self.assertIsInstance(decollated, DynamicMap) self.assertEqual(decollated.kdims, []) # Update streams decollated.streams[0].event(x=1.0, y=2.0) decollated.streams[1].event(z=3.0) self.assertEqual( decollated[()], Points([1.0, 2.0]) + Points([3.0, 3.0]) ) self.assertEqual( decollated.callback.callable(dict(x=1.0, y=2.0), dict(z=3.0)), Points([1.0, 2.0]) + Points([3.0, 3.0]) ) def test_decollate_layout_kdims_and_streams(self): layout = self.dmap_ab + self.dmap_xy decollated = layout.decollate() self.assertIsInstance(decollated, DynamicMap) self.assertEqual(decollated.kdims, self.dmap_ab.kdims) # Update streams decollated.streams[0].event(x=3.0, y=4.0) self.assertEqual( decollated[1.0, 2.0], Points([1.0, 2.0]) + Points([3.0, 4.0]) ) self.assertEqual( decollated.callback.callable(1.0, 2.0, dict(x=3.0, y=4.0)), Points([1.0, 2.0]) + Points([3.0, 4.0]) ) def test_decollate_spread(self): decollated = self.dmap_spread_points.decollate() self.assertIsInstance(decollated, DynamicMap) # Check top-level stream types self.assertEqual( [PlotSize, RangeXY, PX], [type(s) for s in decollated.streams] ) # Get expected self.px_stream.event(px=3) plot_size, range_xy = self.dmap_spread_points.callback.inputs[0].streams plot_size.event(width=250, height=300) range_xy.event(x_range=(0, 10), y_range=(0, 15)) expected = self.dmap_spread_points[()] # Call decollated callback function result = decollated.callback.callable( {"width": 250, "height": 300}, {"x_range": (0, 10), "y_range": (0, 15)}, {"px": 3} ) self.assertEqual(expected, result) def test_decollate_datashade_kdims(self): decollated = self.dmap_datashade_kdim_points.decollate() self.assertIsInstance(decollated, DynamicMap) # Check kdims self.assertEqual(decollated.kdims, self.dmap_ab.kdims) # Check top-level stream types self.assertEqual( [PlotSize, RangeXY], [type(s) for s in decollated.streams] ) # Get expected self.px_stream.event(px=3) plot_size, range_xy = self.dmap_datashade_kdim_points.streams plot_size.event(width=250, height=300) range_xy.event(x_range=(0, 10), y_range=(0, 15)) expected = self.dmap_datashade_kdim_points[4.0, 5.0] # Call decollated callback function result = decollated.callback.callable( 4.0, 5.0, {"width": 250, "height": 300}, {"x_range": (0, 10), "y_range": (0, 15)}, ) self.assertEqual(expected, result) def test_decollate_datashade_kdims_layout(self): layout = self.dmap_datashade_kdim_points + self.dmap_b decollated = layout.decollate() self.assertIsInstance(decollated, DynamicMap) # Check kdims self.assertEqual(decollated.kdims, self.dmap_ab.kdims) # Check top-level stream types self.assertEqual( [PlotSize, RangeXY], [type(s) for s in decollated.streams] ) # Get expected plot_size, range_xy = self.dmap_datashade_kdim_points.streams plot_size.event(width=250, height=300) range_xy.event(x_range=(0, 10), y_range=(0, 15)) expected = self.dmap_datashade_kdim_points[4.0, 5.0] + self.dmap_b[5.0] # Call decollated callback function result = decollated.callback.callable( 4.0, 5.0, {"width": 250, "height": 300}, {"x_range": (0, 10), "y_range": (0, 15)}, ) self.assertEqual(expected, result) def test_decollate_overlay_of_dmaps(self): overlay = Overlay([ DynamicMap(lambda z: Points([z, z]), streams=[Z()]), DynamicMap(lambda z: Points([z, z]), streams=[Z()]), DynamicMap(lambda z: Points([z, z]), streams=[Z()]), ]) decollated = overlay.decollate() self.assertIsInstance(decollated, DynamicMap) self.assertEqual(len(decollated.streams), 3) expected = Overlay([ Points([1.0, 1.0]), Points([2.0, 2.0]), Points([3.0, 3.0]) ]) # Build result by updating streams decollated.streams[0].event(z=1.0) decollated.streams[1].event(z=2.0) decollated.streams[2].event(z=3.0) result = decollated[()] self.assertEqual(expected, result) # Build result by calling callback function result = decollated.callback.callable(dict(z=1.0), dict(z=2.0), dict(z=3.0)) self.assertEqual(expected, result) def test_decollate_dmap_gridspace_kdims(self): self.perform_decollate_dmap_container_kdims(GridSpace) def test_decollate_dmap_ndoverlay_kdims(self): self.perform_decollate_dmap_container_kdims(NdOverlay) def test_decollate_dmap_holomap_kdims(self): self.perform_decollate_dmap_container_kdims(HoloMap) def perform_decollate_dmap_container_kdims(self, ContainerType): # Create container of DynamicMaps, each with kdims a and b. data = [ (0, self.dmap_ab.clone()), (1, self.dmap_ab.clone()), (2, self.dmap_ab.clone()) ] container = ContainerType(data, kdims=["c"]) # Decollate container decollated = container.decollate() self.assertIsInstance(decollated, DynamicMap) self.assertEqual(decollated.kdims, self.dmap_ab.kdims) # Check result of instantiating decollate DynamicMap for particular kdim values a, b = 2.0, 3.0 expected_data = [(d[0], d[1][a, b]) for d in data] expected = ContainerType(expected_data, kdims=["c"]) result = decollated[a, b] self.assertEqual(expected, result) def test_decollate_dmap_gridspace_streams(self): self.perform_decollate_dmap_container_streams(GridSpace) def test_decollate_dmap_ndoverlay_streams(self): self.perform_decollate_dmap_container_streams(NdOverlay) def test_decollate_dmap_holomap_streams(self): self.perform_decollate_dmap_container_streams(HoloMap) def perform_decollate_dmap_container_streams(self, ContainerType): # Create container of DynamicMaps, each with kdims a and b. xy_stream = XY() fn = lambda x, y: Points([x, y]) data = [ (0, DynamicMap(fn, streams=[xy_stream])), (1, DynamicMap(fn, streams=[xy_stream])), (2, DynamicMap(fn, streams=[xy_stream])) ] container = ContainerType(data, kdims=["c"]) # Decollate container decollated = container.decollate() self.assertIsInstance(decollated, DynamicMap) self.assertEqual(len(decollated.kdims), 0) self.assertEqual(len(decollated.streams), 1) # Check result of instantiating decollate DynamicMap for particular # stream values decollated.streams[0].event(x=2.0, y=3.0) xy_stream.event(x=2.0, y=3.0) expected_data = [(d[0], d[1][()]) for d in data] expected = ContainerType(expected_data, kdims=["c"]) result = decollated[()] self.assertEqual(expected, result) def test_traverse_derived_streams(self): from holoviews.tests.teststreams import Val decollated = self.dmap_derived.decollate() # Check decollated types self.assertIsInstance(decollated, DynamicMap) self.assertEqual(len(decollated.streams), 3) for stream in decollated.streams: self.assertIsInstance(stream, Val) # Compute expected result expected = self.dmap_derived.callback.callable(6.0) decollated.streams[0].event(v=1.0) decollated.streams[1].event(v=2.0) decollated.streams[2].event(v=3.0) result = decollated[()] self.assertEqual(expected, result)
from holoviews.core import HoloMap, NdOverlay, Overlay, GridSpace, DynamicMap from holoviews.element import Points from holoviews.element.comparison import ComparisonTestCase from holoviews.streams import Stream, PlotSize, RangeXY from holoviews.operation.datashader import spread, datashade import param class XY(Stream): x = param.Number(constant=True) y = param.Number(constant=True) Z = Stream.define("Z", z=0.0) PX = Stream.define("PX", px=1) class TestDecollation(ComparisonTestCase): def setUp(self): from holoviews.tests.teststreams import Sum, Val # kdims: a and b self.dmap_ab = DynamicMap( lambda a, b: Points([a, b]), kdims=['a', 'b'] ).redim.range(a=(0.0, 10.0), b=(0.0, 10.0)) # kdims: b self.dmap_b = DynamicMap( lambda b: Points([b, b]), kdims=['b'] ).redim.range(b=(0.0, 10.0)) # no kdims, XY stream self.xy_stream = XY() self.dmap_xy = DynamicMap( lambda x, y: Points([x, y]), streams=[self.xy_stream] ) # no kdims, Z stream self.z_stream = Z() self.dmap_z = DynamicMap( lambda z: Points([z, z]), streams=[self.z_stream] ) # dmap produced by chained datashade and shade self.px_stream = PX() self.dmap_spread_points = spread( datashade(Points([0.0, 1.0])), streams=[self.px_stream] ) # data shaded with kdims: a, b self.dmap_datashade_kdim_points = datashade(self.dmap_ab) # DynamicMap of a derived stream self.stream_val1 = Val() self.stream_val2 = Val() self.stream_val3 = Val() self.dmap_derived = DynamicMap( lambda v: Points([v, v]), streams=[ Sum([self.stream_val1, Sum([self.stream_val2, self.stream_val3])]) ] ) def test_decollate_layout_kdims(self): layout = self.dmap_ab + self.dmap_b decollated = layout.decollate() self.assertIsInstance(decollated, DynamicMap) self.assertEqual(decollated.kdims, self.dmap_ab.kdims) self.assertEqual( decollated[2, 3], Points([2, 3]) + Points([3, 3]) ) self.assertEqual( decollated.callback.callable(2, 3), Points([2, 3]) + Points([3, 3]) ) def test_decollate_layout_streams(self): layout = self.dmap_xy + self.dmap_z decollated = layout.decollate() self.assertIsInstance(decollated, DynamicMap) self.assertEqual(decollated.kdims, []) # Update streams decollated.streams[0].event(x=1.0, y=2.0) decollated.streams[1].event(z=3.0) self.assertEqual( decollated[()], Points([1.0, 2.0]) + Points([3.0, 3.0]) ) self.assertEqual( decollated.callback.callable(dict(x=1.0, y=2.0), dict(z=3.0)), Points([1.0, 2.0]) + Points([3.0, 3.0]) ) def test_decollate_layout_kdims_and_streams(self): layout = self.dmap_ab + self.dmap_xy decollated = layout.decollate() self.assertIsInstance(decollated, DynamicMap) self.assertEqual(decollated.kdims, self.dmap_ab.kdims) # Update streams decollated.streams[0].event(x=3.0, y=4.0) self.assertEqual( decollated[1.0, 2.0], Points([1.0, 2.0]) + Points([3.0, 4.0]) ) self.assertEqual( decollated.callback.callable(1.0, 2.0, dict(x=3.0, y=4.0)), Points([1.0, 2.0]) + Points([3.0, 4.0]) ) def test_decollate_spread(self): decollated = self.dmap_spread_points.decollate() self.assertIsInstance(decollated, DynamicMap) # Check top-level stream types self.assertEqual( [PlotSize, RangeXY, PX], [type(s) for s in decollated.streams] ) # Get expected self.px_stream.event(px=3) plot_size, range_xy = self.dmap_spread_points.callback.inputs[0].streams plot_size.event(width=250, height=300) range_xy.event(x_range=(0, 10), y_range=(0, 15)) expected = self.dmap_spread_points[()] # Call decollated callback function result = decollated.callback.callable( {"width": 250, "height": 300}, {"x_range": (0, 10), "y_range": (0, 15)}, {"px": 3} ) self.assertEqual(expected, result) def test_decollate_datashade_kdims(self): decollated = self.dmap_datashade_kdim_points.decollate() self.assertIsInstance(decollated, DynamicMap) # Check kdims self.assertEqual(decollated.kdims, self.dmap_ab.kdims) # Check top-level stream types self.assertEqual( [PlotSize, RangeXY], [type(s) for s in decollated.streams] ) # Get expected self.px_stream.event(px=3) plot_size, range_xy = self.dmap_datashade_kdim_points.streams plot_size.event(width=250, height=300) range_xy.event(x_range=(0, 10), y_range=(0, 15)) expected = self.dmap_datashade_kdim_points[4.0, 5.0] # Call decollated callback function result = decollated.callback.callable( 4.0, 5.0, {"width": 250, "height": 300}, {"x_range": (0, 10), "y_range": (0, 15)}, ) self.assertEqual(expected, result) def test_decollate_datashade_kdims_layout(self): layout = self.dmap_datashade_kdim_points + self.dmap_b decollated = layout.decollate() self.assertIsInstance(decollated, DynamicMap) # Check kdims self.assertEqual(decollated.kdims, self.dmap_ab.kdims) # Check top-level stream types self.assertEqual( [PlotSize, RangeXY], [type(s) for s in decollated.streams] ) # Get expected plot_size, range_xy = self.dmap_datashade_kdim_points.streams plot_size.event(width=250, height=300) range_xy.event(x_range=(0, 10), y_range=(0, 15)) expected = self.dmap_datashade_kdim_points[4.0, 5.0] + self.dmap_b[5.0] # Call decollated callback function result = decollated.callback.callable( 4.0, 5.0, {"width": 250, "height": 300}, {"x_range": (0, 10), "y_range": (0, 15)}, ) self.assertEqual(expected, result) def test_decollate_overlay_of_dmaps(self): overlay = Overlay([ DynamicMap(lambda z: Points([z, z]), streams=[Z()]), DynamicMap(lambda z: Points([z, z]), streams=[Z()]), DynamicMap(lambda z: Points([z, z]), streams=[Z()]), ]) decollated = overlay.decollate() self.assertIsInstance(decollated, DynamicMap) self.assertEqual(len(decollated.streams), 3) expected = Overlay([ Points([1.0, 1.0]), Points([2.0, 2.0]), Points([3.0, 3.0]) ]) # Build result by updating streams decollated.streams[0].event(z=1.0) decollated.streams[1].event(z=2.0) decollated.streams[2].event(z=3.0) result = decollated[()] self.assertEqual(expected, result) # Build result by calling callback function result = decollated.callback.callable(dict(z=1.0), dict(z=2.0), dict(z=3.0)) self.assertEqual(expected, result) def test_decollate_dmap_gridspace_kdims(self): self.perform_decollate_dmap_container_kdims(GridSpace) def test_decollate_dmap_ndoverlay_kdims(self): self.perform_decollate_dmap_container_kdims(NdOverlay) def test_decollate_dmap_holomap_kdims(self): self.perform_decollate_dmap_container_kdims(HoloMap) def perform_decollate_dmap_container_kdims(self, ContainerType): # Create container of DynamicMaps, each with kdims a and b. data = [ (0, self.dmap_ab.clone()), (1, self.dmap_ab.clone()), (2, self.dmap_ab.clone()) ] container = ContainerType(data, kdims=["c"]) # Decollate container decollated = container.decollate() self.assertIsInstance(decollated, DynamicMap) self.assertEqual(decollated.kdims, self.dmap_ab.kdims) # Check result of instantiating decollate DynamicMap for particular kdim values a, b = 2.0, 3.0 expected_data = [(d[0], d[1][a, b]) for d in data] expected = ContainerType(expected_data, kdims=["c"]) result = decollated[a, b] self.assertEqual(expected, result) def test_decollate_dmap_gridspace_streams(self): self.perform_decollate_dmap_container_streams(GridSpace) def test_decollate_dmap_ndoverlay_streams(self): self.perform_decollate_dmap_container_streams(NdOverlay) def test_decollate_dmap_holomap_streams(self): self.perform_decollate_dmap_container_streams(HoloMap) def perform_decollate_dmap_container_streams(self, ContainerType): # Create container of DynamicMaps, each with kdims a and b. xy_stream = XY() fn = lambda x, y: Points([x, y]) data = [ (0, DynamicMap(fn, streams=[xy_stream])), (1, DynamicMap(fn, streams=[xy_stream])), (2, DynamicMap(fn, streams=[xy_stream])) ] container = ContainerType(data, kdims=["c"]) # Decollate container decollated = container.decollate() self.assertIsInstance(decollated, DynamicMap) self.assertEqual(len(decollated.kdims), 0) self.assertEqual(len(decollated.streams), 1) # Check result of instantiating decollate DynamicMap for particular # stream values decollated.streams[0].event(x=2.0, y=3.0) xy_stream.event(x=2.0, y=3.0) expected_data = [(d[0], d[1][()]) for d in data] expected = ContainerType(expected_data, kdims=["c"]) result = decollated[()] self.assertEqual(expected, result) def test_traverse_derived_streams(self): from holoviews.tests.teststreams import Val decollated = self.dmap_derived.decollate() # Check decollated types self.assertIsInstance(decollated, DynamicMap) self.assertEqual(len(decollated.streams), 3) for stream in decollated.streams: self.assertIsInstance(stream, Val) # Compute expected result expected = self.dmap_derived.callback.callable(6.0) decollated.streams[0].event(v=1.0) decollated.streams[1].event(v=2.0) decollated.streams[2].event(v=3.0) result = decollated[()] self.assertEqual(expected, result)
en
0.737547
# kdims: a and b # kdims: b # no kdims, XY stream # no kdims, Z stream # dmap produced by chained datashade and shade # data shaded with kdims: a, b # DynamicMap of a derived stream # Update streams # Update streams # Check top-level stream types # Get expected # Call decollated callback function # Check kdims # Check top-level stream types # Get expected # Call decollated callback function # Check kdims # Check top-level stream types # Get expected # Call decollated callback function # Build result by updating streams # Build result by calling callback function # Create container of DynamicMaps, each with kdims a and b. # Decollate container # Check result of instantiating decollate DynamicMap for particular kdim values # Create container of DynamicMaps, each with kdims a and b. # Decollate container # Check result of instantiating decollate DynamicMap for particular # stream values # Check decollated types # Compute expected result
2.168075
2
ronald_bdl/models/squeezenet_dropout.py
ronaldseoh/ronald_bdl
2
6628288
<reponame>ronaldseoh/ronald_bdl import torch import torch.nn as nn import torch.nn.init as init from .utils import create_dropout_layer class FireDropout(nn.Module): def __init__(self, inplanes, squeeze_planes, expand1x1_planes, expand3x3_planes, **kwargs): super(FireDropout, self).__init__() self.inplanes = inplanes # Dropout related settings if 'dropout_rate' in kwargs: self.dropout_rate = kwargs['dropout_rate'] self.dropout_type = kwargs['dropout_type'] else: self.dropout_rate = 0 self.dropout_type = 'identity' self.squeeze = nn.Conv2d(inplanes, squeeze_planes, kernel_size=1) # Additional dropout layer self.squeeze_dropout = create_dropout_layer( self.dropout_rate, self.dropout_type) self.squeeze_activation = nn.ReLU(inplace=True) self.expand1x1 = nn.Conv2d(squeeze_planes, expand1x1_planes, kernel_size=1) # Additional dropout layer self.expand1x1_dropout = create_dropout_layer( self.dropout_rate, self.dropout_type) self.expand1x1_activation = nn.ReLU(inplace=True) self.expand3x3 = nn.Conv2d(squeeze_planes, expand3x3_planes, kernel_size=3, padding=1) # Additional dropout layer self.expand3x3_dropout = create_dropout_layer( self.dropout_rate, self.dropout_type) self.expand3x3_activation = nn.ReLU(inplace=True) def forward(self, x): x = self.squeeze_activation(self.squeeze_dropout(self.squeeze(x))) return torch.cat([ self.expand1x1_activation(self.expand1x1_dropout(self.expand1x1(x))), self.expand3x3_activation(self.expand3x3_dropout(self.expand3x3(x))) ], 1) class SqueezeNetDropout(nn.Module): def __init__(self, num_classes=1000, **kwargs): super(SqueezeNetDropout, self).__init__() self.num_classes = num_classes # Dropout related settings if 'dropout_rate' in kwargs: self.dropout_rate = kwargs['dropout_rate'] self.dropout_type = kwargs['dropout_type'] else: self.dropout_rate = 0 self.dropout_type = 'identity' self.features = nn.Sequential( nn.Conv2d(3, 64, kernel_size=3, stride=2), # Additional dropout layer added here create_dropout_layer( self.dropout_rate, -1, self.dropout_type,), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), FireDropout(64, 16, 64, 64, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), FireDropout(128, 16, 64, 64, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), FireDropout(128, 32, 128, 128, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), FireDropout(256, 32, 128, 128, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), FireDropout(256, 48, 192, 192, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), FireDropout(384, 48, 192, 192, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), FireDropout(384, 64, 256, 256, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), FireDropout(512, 64, 256, 256, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), ) # Final convolution is initialized differently from the rest final_conv = nn.Conv2d(512, self.num_classes, kernel_size=1) self.classifier = nn.Sequential( # SqueezeNet (and many other known CNNs) originally # do have dropout layers here, right before the final output. # Replace it with our dropout layer creator create_dropout_layer( self.dropout_rate, self.dropout_type), final_conv, nn.ReLU(inplace=True), nn.AdaptiveAvgPool2d((1, 1)) ) for m in self.modules(): if isinstance(m, nn.Conv2d): if m is final_conv: init.normal_(m.weight, mean=0.0, std=0.01) else: init.kaiming_uniform_(m.weight) if m.bias is not None: init.constant_(m.bias, 0) def forward(self, x): x = self.features(x) x = self.classifier(x) return torch.flatten(x, 1) def predict_dist(self, test_loader, n_prediction, torch_device): was_eval = not self.training predictions = [] mean_predictions = [] metrics = {} metrics['accuracy_mc'] = 0 metrics['accuracy_non_mc'] = 0 metrics['test_ll_mc'] = 0 with torch.no_grad(): for data in test_loader: # Temporaily disable eval mode if was_eval: self.train() inputs, targets = data inputs = inputs.to(torch_device) targets = targets.to(torch_device) raw_scores_batch = torch.stack( [self.forward(inputs) for _ in range(n_prediction)]) predictions_batch = torch.max(raw_scores_batch, 2).values mean_raw_scores_batch = torch.mean(raw_scores_batch, 0) mean_predictions_batch = torch.argmax(mean_raw_scores_batch, 1) mean_predictions.append(mean_predictions_batch) if was_eval: self.eval() non_mc_raw_scores_batch = self.forward(inputs) non_mc_predictions_batch = torch.argmax(non_mc_raw_scores_batch, 1) # Accuracy metrics['accuracy_mc'] += torch.mean((mean_predictions_batch == targets).float()) metrics['accuracy_mc'] /= 2 # Accuracy (Non-MC) metrics['accuracy_non_mc'] += torch.mean((non_mc_predictions_batch == targets).float()) metrics['accuracy_non_mc'] /= 2 # test log-likelihood metrics['test_ll_mc'] -= (F.cross_entropy(mean_raw_scores_batch, targets)) metrics['test_ll_mc'] /= 2 mean_predictions = torch.cat(mean_predictions) return predictions, mean_predictions, metrics
import torch import torch.nn as nn import torch.nn.init as init from .utils import create_dropout_layer class FireDropout(nn.Module): def __init__(self, inplanes, squeeze_planes, expand1x1_planes, expand3x3_planes, **kwargs): super(FireDropout, self).__init__() self.inplanes = inplanes # Dropout related settings if 'dropout_rate' in kwargs: self.dropout_rate = kwargs['dropout_rate'] self.dropout_type = kwargs['dropout_type'] else: self.dropout_rate = 0 self.dropout_type = 'identity' self.squeeze = nn.Conv2d(inplanes, squeeze_planes, kernel_size=1) # Additional dropout layer self.squeeze_dropout = create_dropout_layer( self.dropout_rate, self.dropout_type) self.squeeze_activation = nn.ReLU(inplace=True) self.expand1x1 = nn.Conv2d(squeeze_planes, expand1x1_planes, kernel_size=1) # Additional dropout layer self.expand1x1_dropout = create_dropout_layer( self.dropout_rate, self.dropout_type) self.expand1x1_activation = nn.ReLU(inplace=True) self.expand3x3 = nn.Conv2d(squeeze_planes, expand3x3_planes, kernel_size=3, padding=1) # Additional dropout layer self.expand3x3_dropout = create_dropout_layer( self.dropout_rate, self.dropout_type) self.expand3x3_activation = nn.ReLU(inplace=True) def forward(self, x): x = self.squeeze_activation(self.squeeze_dropout(self.squeeze(x))) return torch.cat([ self.expand1x1_activation(self.expand1x1_dropout(self.expand1x1(x))), self.expand3x3_activation(self.expand3x3_dropout(self.expand3x3(x))) ], 1) class SqueezeNetDropout(nn.Module): def __init__(self, num_classes=1000, **kwargs): super(SqueezeNetDropout, self).__init__() self.num_classes = num_classes # Dropout related settings if 'dropout_rate' in kwargs: self.dropout_rate = kwargs['dropout_rate'] self.dropout_type = kwargs['dropout_type'] else: self.dropout_rate = 0 self.dropout_type = 'identity' self.features = nn.Sequential( nn.Conv2d(3, 64, kernel_size=3, stride=2), # Additional dropout layer added here create_dropout_layer( self.dropout_rate, -1, self.dropout_type,), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), FireDropout(64, 16, 64, 64, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), FireDropout(128, 16, 64, 64, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), FireDropout(128, 32, 128, 128, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), FireDropout(256, 32, 128, 128, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True), FireDropout(256, 48, 192, 192, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), FireDropout(384, 48, 192, 192, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), FireDropout(384, 64, 256, 256, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), FireDropout(512, 64, 256, 256, dropout_rate=self.dropout_rate, dropout_type=self.dropout_type), ) # Final convolution is initialized differently from the rest final_conv = nn.Conv2d(512, self.num_classes, kernel_size=1) self.classifier = nn.Sequential( # SqueezeNet (and many other known CNNs) originally # do have dropout layers here, right before the final output. # Replace it with our dropout layer creator create_dropout_layer( self.dropout_rate, self.dropout_type), final_conv, nn.ReLU(inplace=True), nn.AdaptiveAvgPool2d((1, 1)) ) for m in self.modules(): if isinstance(m, nn.Conv2d): if m is final_conv: init.normal_(m.weight, mean=0.0, std=0.01) else: init.kaiming_uniform_(m.weight) if m.bias is not None: init.constant_(m.bias, 0) def forward(self, x): x = self.features(x) x = self.classifier(x) return torch.flatten(x, 1) def predict_dist(self, test_loader, n_prediction, torch_device): was_eval = not self.training predictions = [] mean_predictions = [] metrics = {} metrics['accuracy_mc'] = 0 metrics['accuracy_non_mc'] = 0 metrics['test_ll_mc'] = 0 with torch.no_grad(): for data in test_loader: # Temporaily disable eval mode if was_eval: self.train() inputs, targets = data inputs = inputs.to(torch_device) targets = targets.to(torch_device) raw_scores_batch = torch.stack( [self.forward(inputs) for _ in range(n_prediction)]) predictions_batch = torch.max(raw_scores_batch, 2).values mean_raw_scores_batch = torch.mean(raw_scores_batch, 0) mean_predictions_batch = torch.argmax(mean_raw_scores_batch, 1) mean_predictions.append(mean_predictions_batch) if was_eval: self.eval() non_mc_raw_scores_batch = self.forward(inputs) non_mc_predictions_batch = torch.argmax(non_mc_raw_scores_batch, 1) # Accuracy metrics['accuracy_mc'] += torch.mean((mean_predictions_batch == targets).float()) metrics['accuracy_mc'] /= 2 # Accuracy (Non-MC) metrics['accuracy_non_mc'] += torch.mean((non_mc_predictions_batch == targets).float()) metrics['accuracy_non_mc'] /= 2 # test log-likelihood metrics['test_ll_mc'] -= (F.cross_entropy(mean_raw_scores_batch, targets)) metrics['test_ll_mc'] /= 2 mean_predictions = torch.cat(mean_predictions) return predictions, mean_predictions, metrics
en
0.845996
# Dropout related settings # Additional dropout layer # Additional dropout layer # Additional dropout layer # Dropout related settings # Additional dropout layer added here # Final convolution is initialized differently from the rest # SqueezeNet (and many other known CNNs) originally # do have dropout layers here, right before the final output. # Replace it with our dropout layer creator # Temporaily disable eval mode # Accuracy # Accuracy (Non-MC) # test log-likelihood
2.543046
3
bot.py
py1h0n-h4xer/instagram_bot
0
6628289
from selenium import webdriver from selenium.webdriver.common.keys import Keys from webdriver_manager.chrome import ChromeDriverManager import time from selenium.webdriver.common.action_chains import ActionChains from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer chatbot = ChatBot('test') from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from selenium.webdriver.firefox.firefox_binary import FirefoxBinary tryn = 0 driver = webdriver.Chrome(executable_path='C:/Users/"usernamehere"/Downloads/chromedriver_win32/chromedriver.exe') driver.get('https://www.instagram.com/direct/inbox/') print(driver.title) print(driver.current_url) time.sleep(1) id_box = driver.find_element_by_name('username') id_box.send_keys('USERNAME HERE') id_box = driver.find_element_by_name('password') id_box.send_keys('<PASSWORD>') login_button = driver.find_elements_by_xpath("//*[contains(text(), 'Log In')]") for btn in login_button: btn.click() time.sleep(4) userinfostate = driver.find_elements_by_xpath("//*[contains(text(), 'Not Now')]") for btn in userinfostate: btn.click() time.sleep(2) try: noteoff = driver.find_elements_by_xpath("//*[contains(text(), 'Not Now')]") for btn in noteoff: btn.click() print("Exeption used!") except: print("Exeption not used.") print("UPDATE VERSION: 12/13/2020") print("Logged in!") input = input("Press enter to start loop.") while True: try: #get to 1st user el=driver.find_elements_by_xpath('//*[@id="react-root"]/section/div/div[2]/div/div/div[1]/div[1]/div/div[2]')[0] action = webdriver.common.action_chains.ActionChains(driver) action.move_to_element_with_offset(el, 200,100) action.click() action.perform() time.sleep(1) dl=driver.find_elements_by_xpath('//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/div/div[2]')[0] action = webdriver.common.action_chains.ActionChains(driver) action.move_to_element_with_offset(dl, 0, 0) action.click() action.perform() #get text for element in driver.find_elements_by_xpath('//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/div/div[2]/div[2]/div/div/div/div/div/div/div/div/span'): textfu = element.text #get response outtext = chatbot.get_response(textfu) #send text dl=driver.find_elements_by_xpath('//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea')[0] action = webdriver.common.action_chains.ActionChains(driver) action.move_to_element_with_offset(dl, 5, 5) action.click() action.perform() actions = ActionChains(driver) actions.send_keys(str(outtext)) actions.send_keys(Keys.RETURN) actions.perform() #del conversation dl=driver.find_elements_by_xpath('//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div[1]/div/div/div[3]/button')[0] action = webdriver.common.action_chains.ActionChains(driver) action.move_to_element_with_offset(dl, 0, 0) action.click() action.perform() dl=driver.find_elements_by_xpath('//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div/div[2]/div[3]/div[1]/button')[0] action = webdriver.common.action_chains.ActionChains(driver) action.move_to_element_with_offset(dl, 0, 0) action.click() action.perform() actions.send_keys(Keys.TAB) actions.send_keys(Keys.RETURN) actions.perform() driver.refresh() tryn = 0 except: time.sleep(1) tryn = tryn + 1 if tryn == 120: driver.refresh() tryn = 0 time.sleep(9999) driver.close()
from selenium import webdriver from selenium.webdriver.common.keys import Keys from webdriver_manager.chrome import ChromeDriverManager import time from selenium.webdriver.common.action_chains import ActionChains from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer chatbot = ChatBot('test') from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from selenium.webdriver.firefox.firefox_binary import FirefoxBinary tryn = 0 driver = webdriver.Chrome(executable_path='C:/Users/"usernamehere"/Downloads/chromedriver_win32/chromedriver.exe') driver.get('https://www.instagram.com/direct/inbox/') print(driver.title) print(driver.current_url) time.sleep(1) id_box = driver.find_element_by_name('username') id_box.send_keys('USERNAME HERE') id_box = driver.find_element_by_name('password') id_box.send_keys('<PASSWORD>') login_button = driver.find_elements_by_xpath("//*[contains(text(), 'Log In')]") for btn in login_button: btn.click() time.sleep(4) userinfostate = driver.find_elements_by_xpath("//*[contains(text(), 'Not Now')]") for btn in userinfostate: btn.click() time.sleep(2) try: noteoff = driver.find_elements_by_xpath("//*[contains(text(), 'Not Now')]") for btn in noteoff: btn.click() print("Exeption used!") except: print("Exeption not used.") print("UPDATE VERSION: 12/13/2020") print("Logged in!") input = input("Press enter to start loop.") while True: try: #get to 1st user el=driver.find_elements_by_xpath('//*[@id="react-root"]/section/div/div[2]/div/div/div[1]/div[1]/div/div[2]')[0] action = webdriver.common.action_chains.ActionChains(driver) action.move_to_element_with_offset(el, 200,100) action.click() action.perform() time.sleep(1) dl=driver.find_elements_by_xpath('//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/div/div[2]')[0] action = webdriver.common.action_chains.ActionChains(driver) action.move_to_element_with_offset(dl, 0, 0) action.click() action.perform() #get text for element in driver.find_elements_by_xpath('//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/div/div[2]/div[2]/div/div/div/div/div/div/div/div/span'): textfu = element.text #get response outtext = chatbot.get_response(textfu) #send text dl=driver.find_elements_by_xpath('//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea')[0] action = webdriver.common.action_chains.ActionChains(driver) action.move_to_element_with_offset(dl, 5, 5) action.click() action.perform() actions = ActionChains(driver) actions.send_keys(str(outtext)) actions.send_keys(Keys.RETURN) actions.perform() #del conversation dl=driver.find_elements_by_xpath('//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div[1]/div/div/div[3]/button')[0] action = webdriver.common.action_chains.ActionChains(driver) action.move_to_element_with_offset(dl, 0, 0) action.click() action.perform() dl=driver.find_elements_by_xpath('//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div/div[2]/div[3]/div[1]/button')[0] action = webdriver.common.action_chains.ActionChains(driver) action.move_to_element_with_offset(dl, 0, 0) action.click() action.perform() actions.send_keys(Keys.TAB) actions.send_keys(Keys.RETURN) actions.perform() driver.refresh() tryn = 0 except: time.sleep(1) tryn = tryn + 1 if tryn == 120: driver.refresh() tryn = 0 time.sleep(9999) driver.close()
en
0.736399
#get to 1st user #get text #get response #send text #del conversation
2.656182
3
Lib/site-packages/elasticsearch5/client/tasks.py
Nibraz15/FullTextSearch
46
6628290
from .utils import NamespacedClient, query_params, _make_path class TasksClient(NamespacedClient): @query_params('actions', 'detailed', 'group_by', 'nodes', 'parent_node', 'parent_task_id', 'wait_for_completion') def list(self, params=None): """ `<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_ :arg actions: A comma-separated list of actions that should be returned. Leave empty to return all. :arg detailed: Return detailed task information (default: false) :arg group_by: Group tasks by nodes or parent/child relationships, default 'nodes', valid choices are: 'nodes', 'parents' :arg nodes: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg parent_node: Return tasks with specified parent node. :arg parent_task_id: Return tasks with specified parent task id (node_id:task_number). Set to -1 to return all. :arg wait_for_completion: Wait for the matching tasks to complete (default: false) """ return self.transport.perform_request('GET', '/_tasks', params=params) @query_params('actions', 'nodes', 'parent_task_id') def cancel(self, task_id=None, params=None): """ `<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_ :arg task_id: Cancel the task with specified task id (node_id:task_number) :arg actions: A comma-separated list of actions that should be cancelled. Leave empty to cancel all. :arg nodes: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg parent_task_id: Cancel tasks with specified parent task id (node_id:task_number). Set to -1 to cancel all. """ return self.transport.perform_request('POST', _make_path('_tasks', task_id, '_cancel'), params=params) @query_params('wait_for_completion') def get(self, task_id=None, params=None): """ Retrieve information for a particular task. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_ :arg task_id: Return the task with specified id (node_id:task_number) :arg wait_for_completion: Wait for the matching tasks to complete (default: false) """ return self.transport.perform_request('GET', _make_path('_tasks', task_id), params=params)
from .utils import NamespacedClient, query_params, _make_path class TasksClient(NamespacedClient): @query_params('actions', 'detailed', 'group_by', 'nodes', 'parent_node', 'parent_task_id', 'wait_for_completion') def list(self, params=None): """ `<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_ :arg actions: A comma-separated list of actions that should be returned. Leave empty to return all. :arg detailed: Return detailed task information (default: false) :arg group_by: Group tasks by nodes or parent/child relationships, default 'nodes', valid choices are: 'nodes', 'parents' :arg nodes: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg parent_node: Return tasks with specified parent node. :arg parent_task_id: Return tasks with specified parent task id (node_id:task_number). Set to -1 to return all. :arg wait_for_completion: Wait for the matching tasks to complete (default: false) """ return self.transport.perform_request('GET', '/_tasks', params=params) @query_params('actions', 'nodes', 'parent_task_id') def cancel(self, task_id=None, params=None): """ `<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_ :arg task_id: Cancel the task with specified task id (node_id:task_number) :arg actions: A comma-separated list of actions that should be cancelled. Leave empty to cancel all. :arg nodes: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg parent_task_id: Cancel tasks with specified parent task id (node_id:task_number). Set to -1 to cancel all. """ return self.transport.perform_request('POST', _make_path('_tasks', task_id, '_cancel'), params=params) @query_params('wait_for_completion') def get(self, task_id=None, params=None): """ Retrieve information for a particular task. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_ :arg task_id: Return the task with specified id (node_id:task_number) :arg wait_for_completion: Wait for the matching tasks to complete (default: false) """ return self.transport.perform_request('GET', _make_path('_tasks', task_id), params=params)
en
0.676703
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_ :arg actions: A comma-separated list of actions that should be returned. Leave empty to return all. :arg detailed: Return detailed task information (default: false) :arg group_by: Group tasks by nodes or parent/child relationships, default 'nodes', valid choices are: 'nodes', 'parents' :arg nodes: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg parent_node: Return tasks with specified parent node. :arg parent_task_id: Return tasks with specified parent task id (node_id:task_number). Set to -1 to return all. :arg wait_for_completion: Wait for the matching tasks to complete (default: false) `<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_ :arg task_id: Cancel the task with specified task id (node_id:task_number) :arg actions: A comma-separated list of actions that should be cancelled. Leave empty to cancel all. :arg nodes: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :arg parent_task_id: Cancel tasks with specified parent task id (node_id:task_number). Set to -1 to cancel all. Retrieve information for a particular task. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_ :arg task_id: Return the task with specified id (node_id:task_number) :arg wait_for_completion: Wait for the matching tasks to complete (default: false)
2.499073
2
jeremy/ref/HappyNewYear.py
sin3000x/manim
0
6628291
<gh_stars>0 from manimlib.imports import * class HappyNewYear(Scene): def construct(self): text = TexMobject( r'''\int\frac{\mathrm{d}x}{a\sin x+b\cos x}=\begin{cases} \displaystyle\frac{1}{\sqrt{a^2+b^2}}\ln\left|\csc\left(x+\arctan\displaystyle\frac{b}{a}\right)-\cot\left(x+\arctan\displaystyle\frac{b}{a}\right) \right|+C&a\ne0\\ \displaystyle\frac{1}{b}\ln\left|\sec x+\tan x\right|+C&a=0\\ \end{cases}''').scale(0.6).rotate(PI / 6).to_corner(UL, buff=1).set_opacity(0.12) text2 = VGroup( *[ text.copy().move_to(LEFT * 9 + RIGHT * 3 * i) for i in range(7) ] ) self.add(text2) text3 = Text( "Happy New Year", font="Source Han Sans Bold", color="#EEAEEE", t2c={"H": "#EE3A8C", "N": "#EE3A8C", "Y": "#EE3A8C"}, ).scale(0.8).to_corner(UL, buff=1.8).shift(LEFT) # self.wait(20454*24*60*60) self.add(text3) text4 = Text( "2077", font="DIN Black", t2c={"77": "#AFABB4", }, ).scale(3).next_to(text3, RIGHT, aligned_edge=DOWN) self.add(text4) hp1 = Text( "text = Text(", font="Consolas", color="#8A81D1", t2s={"self": ITALIC}, t2c={"text": "#AFABB4", "=": "#AFABB4", "Text": "#75CB87", "(": "#E4C104"}, ) hp2 = Text( "\"Happy New Year\", ", font="Consolas", color="#E4C104", t2s={"self": ITALIC}, t2c={",": "#AFABB4", "\"": "#C6E2FF"}, ) hp3 = Text( "font = \"Source Han Sans Bold\",", font="Consolas", color="#E4C104", t2s={"self": ITALIC}, t2c={"font": "#FF4040", "=": "#AFABB4", ",": "#AFABB4", "\"": "#C6E2FF"}, ) hp4 = Text( "color = \"#EECFA1\",", font="Consolas", color="#E4C104", t2s={"self": ITALIC}, t2c={"color": "#FF4040", "=": "#AFABB4", ",": "#AFABB4", "\"": "#C6E2FF"}, ) hp5 = Text( "t2c = {\"H\": \"#AFABB4\",\"N\": \"#AFABB4\",\"Y\": \"#AFABB4\"})", font="Consolas", color="#E4C104", t2s={"self": ITALIC}, t2c={"t2c": "#FF4040", "{": "#FF83FA", "}": "#FF83FA", "=": "#AFABB4", ":": "#AFABB4", ",": "#AFABB4", ")": "#E4C104", "\"": "#C6E2FF"}, ) hp6 = Text( "self.add(text)", font="Consolas", color="#8A81D1", t2s={"self": ITALIC}, t2c={"self.": "#AFABB4", "add": "#75CB87", "(": "#E4C104", "text": "#FFB5C5", ")": "#E4C104"} ) hp7 = Text( "self.wait(20454 * 24 * 60 * 60)", font="Consolas", color="#8A81D1", t2s={"self": ITALIC}, t2c={"self.": "#AFABB4", "wait": "#75CB87", "(": "#E4C104", ")": "#E4C104", "*": "#FFAEB9"} ) hpvg = VGroup(hp1, hp2, hp3, hp4, hp5, hp6, hp7).scale(0.4).arrange(DOWN, aligned_edge=LEFT, buff=0.1) hpvg[1:5].shift(RIGHT) self.add(hpvg.to_edge(RIGHT).shift(DOWN * 0.2))
from manimlib.imports import * class HappyNewYear(Scene): def construct(self): text = TexMobject( r'''\int\frac{\mathrm{d}x}{a\sin x+b\cos x}=\begin{cases} \displaystyle\frac{1}{\sqrt{a^2+b^2}}\ln\left|\csc\left(x+\arctan\displaystyle\frac{b}{a}\right)-\cot\left(x+\arctan\displaystyle\frac{b}{a}\right) \right|+C&a\ne0\\ \displaystyle\frac{1}{b}\ln\left|\sec x+\tan x\right|+C&a=0\\ \end{cases}''').scale(0.6).rotate(PI / 6).to_corner(UL, buff=1).set_opacity(0.12) text2 = VGroup( *[ text.copy().move_to(LEFT * 9 + RIGHT * 3 * i) for i in range(7) ] ) self.add(text2) text3 = Text( "Happy New Year", font="Source Han Sans Bold", color="#EEAEEE", t2c={"H": "#EE3A8C", "N": "#EE3A8C", "Y": "#EE3A8C"}, ).scale(0.8).to_corner(UL, buff=1.8).shift(LEFT) # self.wait(20454*24*60*60) self.add(text3) text4 = Text( "2077", font="DIN Black", t2c={"77": "#AFABB4", }, ).scale(3).next_to(text3, RIGHT, aligned_edge=DOWN) self.add(text4) hp1 = Text( "text = Text(", font="Consolas", color="#8A81D1", t2s={"self": ITALIC}, t2c={"text": "#AFABB4", "=": "#AFABB4", "Text": "#75CB87", "(": "#E4C104"}, ) hp2 = Text( "\"Happy New Year\", ", font="Consolas", color="#E4C104", t2s={"self": ITALIC}, t2c={",": "#AFABB4", "\"": "#C6E2FF"}, ) hp3 = Text( "font = \"Source Han Sans Bold\",", font="Consolas", color="#E4C104", t2s={"self": ITALIC}, t2c={"font": "#FF4040", "=": "#AFABB4", ",": "#AFABB4", "\"": "#C6E2FF"}, ) hp4 = Text( "color = \"#EECFA1\",", font="Consolas", color="#E4C104", t2s={"self": ITALIC}, t2c={"color": "#FF4040", "=": "#AFABB4", ",": "#AFABB4", "\"": "#C6E2FF"}, ) hp5 = Text( "t2c = {\"H\": \"#AFABB4\",\"N\": \"#AFABB4\",\"Y\": \"#AFABB4\"})", font="Consolas", color="#E4C104", t2s={"self": ITALIC}, t2c={"t2c": "#FF4040", "{": "#FF83FA", "}": "#FF83FA", "=": "#AFABB4", ":": "#AFABB4", ",": "#AFABB4", ")": "#E4C104", "\"": "#C6E2FF"}, ) hp6 = Text( "self.add(text)", font="Consolas", color="#8A81D1", t2s={"self": ITALIC}, t2c={"self.": "#AFABB4", "add": "#75CB87", "(": "#E4C104", "text": "#FFB5C5", ")": "#E4C104"} ) hp7 = Text( "self.wait(20454 * 24 * 60 * 60)", font="Consolas", color="#8A81D1", t2s={"self": ITALIC}, t2c={"self.": "#AFABB4", "wait": "#75CB87", "(": "#E4C104", ")": "#E4C104", "*": "#FFAEB9"} ) hpvg = VGroup(hp1, hp2, hp3, hp4, hp5, hp6, hp7).scale(0.4).arrange(DOWN, aligned_edge=LEFT, buff=0.1) hpvg[1:5].shift(RIGHT) self.add(hpvg.to_edge(RIGHT).shift(DOWN * 0.2))
en
0.154779
\int\frac{\mathrm{d}x}{a\sin x+b\cos x}=\begin{cases} \displaystyle\frac{1}{\sqrt{a^2+b^2}}\ln\left|\csc\left(x+\arctan\displaystyle\frac{b}{a}\right)-\cot\left(x+\arctan\displaystyle\frac{b}{a}\right) \right|+C&a\ne0\\ \displaystyle\frac{1}{b}\ln\left|\sec x+\tan x\right|+C&a=0\\ \end{cases} # self.wait(20454*24*60*60)
2.602148
3
examples/ex_pyqt.py
joeleong/idapython
0
6628292
<filename>examples/ex_pyqt.py from idaapi import PluginForm from PyQt5 import QtCore, QtGui, QtWidgets import sip class MyPluginFormClass(PluginForm): def OnCreate(self, form): """ Called when the plugin form is created """ # Get parent widget self.parent = self.FormToPyQtWidget(form) self.PopulateForm() def PopulateForm(self): # Create layout layout = QtWidgets.QVBoxLayout() layout.addWidget( QtWidgets.QLabel("Hello from <font color=red>PyQt</font>")) layout.addWidget( QtWidgets.QLabel("Hello from <font color=blue>IDAPython</font>")) self.parent.setLayout(layout) def OnClose(self, form): """ Called when the plugin form is closed """ pass plg = MyPluginFormClass() plg.Show("PyQt hello world")
<filename>examples/ex_pyqt.py from idaapi import PluginForm from PyQt5 import QtCore, QtGui, QtWidgets import sip class MyPluginFormClass(PluginForm): def OnCreate(self, form): """ Called when the plugin form is created """ # Get parent widget self.parent = self.FormToPyQtWidget(form) self.PopulateForm() def PopulateForm(self): # Create layout layout = QtWidgets.QVBoxLayout() layout.addWidget( QtWidgets.QLabel("Hello from <font color=red>PyQt</font>")) layout.addWidget( QtWidgets.QLabel("Hello from <font color=blue>IDAPython</font>")) self.parent.setLayout(layout) def OnClose(self, form): """ Called when the plugin form is closed """ pass plg = MyPluginFormClass() plg.Show("PyQt hello world")
en
0.936785
Called when the plugin form is created # Get parent widget # Create layout Called when the plugin form is closed
2.907231
3
midfield_direction_matrix.py
pwcberry/footy-simulator-python
0
6628293
<reponame>pwcberry/footy-simulator-python<filename>midfield_direction_matrix.py from status import BallDirection, FieldZone, Possession from matrix import normalise, prob from direction_matrix import DirectionMatrix class MidfieldDirectionMatrix(DirectionMatrix): def __init__(self, home_team_skill, away_team_skill): super().__init__(FieldZone.MID_FIELD) hst = home_team_skill.strength hp = home_team_skill.pressure ast = away_team_skill.strength ap = away_team_skill.pressure self.data[Possession.HOME_TEAM] = dict([ (BallDirection.NONE, normalise([ prob(0.2, hst, 0, ap), prob(0.6, hst, 0, ap), prob(0.1, hst, 0, -ap), prob(0.1, hst, 0, ap) ], [0, 1, 2, 3]) ), (BallDirection.FORWARD, normalise([ prob(0.1, hst, 0, ap), prob(0.7, hst, 0, ap), prob(0.1, hst, 0, -ap), prob(0.1, hst, 0, ap) ], [0, 1, 2, 3]) ), (BallDirection.BACKWARD, normalise([ prob(0.1, hst, 0, ap), prob(0.5, hst, 0, ap), prob(0.15, hst, 0, -ap), prob(0.25, hst, 0, ap) ], [0, 1, 2, 3]) ), (BallDirection.LATERAL, normalise([ prob(0.1, hst, 0, ap), prob(0.55, hst, 0, ap), prob(0.1, hst, 0, -ap), prob(0.25, hst, 0, ap) ], [0, 1, 2, 3]) ) ]) self.data[Possession.AWAY_TEAM] = dict([ (BallDirection.NONE, normalise([ prob(0.2, ast, 0, hp), prob(0.6, ast, 0, hp), prob(0.1, ast, 0, -hp), prob(0.1, ast, 0, hp) ], [0, 1, 2, 3]) ), (BallDirection.FORWARD, normalise([ prob(0.1, ast, 0, hp), prob(0.7, ast, 0, hp), prob(0.1, ast, 0, -hp), prob(0.1, ast, 0, hp) ], [0, 1, 2, 3]) ), (BallDirection.BACKWARD, normalise([ prob(0.1, ast, 0, hp), prob(0.5, ast, 0, hp), prob(0.15, ast, 0, -hp), prob(0.25, ast, 0, hp) ], [0, 1, 2, 3]) ), (BallDirection.LATERAL, normalise([ prob(0.1, ast, 0, hp), prob(0.55, ast, 0, hp), prob(0.1, ast, 0, -hp), prob(0.25, ast, 0, hp) ], [0, 1, 2, 3]) ) ]) @property def states(self): return [BallDirection.NONE, BallDirection.FORWARD, BallDirection.BACKWARD, BallDirection.LATERAL] def row(self, state, possession): return self.data[possession][state]
from status import BallDirection, FieldZone, Possession from matrix import normalise, prob from direction_matrix import DirectionMatrix class MidfieldDirectionMatrix(DirectionMatrix): def __init__(self, home_team_skill, away_team_skill): super().__init__(FieldZone.MID_FIELD) hst = home_team_skill.strength hp = home_team_skill.pressure ast = away_team_skill.strength ap = away_team_skill.pressure self.data[Possession.HOME_TEAM] = dict([ (BallDirection.NONE, normalise([ prob(0.2, hst, 0, ap), prob(0.6, hst, 0, ap), prob(0.1, hst, 0, -ap), prob(0.1, hst, 0, ap) ], [0, 1, 2, 3]) ), (BallDirection.FORWARD, normalise([ prob(0.1, hst, 0, ap), prob(0.7, hst, 0, ap), prob(0.1, hst, 0, -ap), prob(0.1, hst, 0, ap) ], [0, 1, 2, 3]) ), (BallDirection.BACKWARD, normalise([ prob(0.1, hst, 0, ap), prob(0.5, hst, 0, ap), prob(0.15, hst, 0, -ap), prob(0.25, hst, 0, ap) ], [0, 1, 2, 3]) ), (BallDirection.LATERAL, normalise([ prob(0.1, hst, 0, ap), prob(0.55, hst, 0, ap), prob(0.1, hst, 0, -ap), prob(0.25, hst, 0, ap) ], [0, 1, 2, 3]) ) ]) self.data[Possession.AWAY_TEAM] = dict([ (BallDirection.NONE, normalise([ prob(0.2, ast, 0, hp), prob(0.6, ast, 0, hp), prob(0.1, ast, 0, -hp), prob(0.1, ast, 0, hp) ], [0, 1, 2, 3]) ), (BallDirection.FORWARD, normalise([ prob(0.1, ast, 0, hp), prob(0.7, ast, 0, hp), prob(0.1, ast, 0, -hp), prob(0.1, ast, 0, hp) ], [0, 1, 2, 3]) ), (BallDirection.BACKWARD, normalise([ prob(0.1, ast, 0, hp), prob(0.5, ast, 0, hp), prob(0.15, ast, 0, -hp), prob(0.25, ast, 0, hp) ], [0, 1, 2, 3]) ), (BallDirection.LATERAL, normalise([ prob(0.1, ast, 0, hp), prob(0.55, ast, 0, hp), prob(0.1, ast, 0, -hp), prob(0.25, ast, 0, hp) ], [0, 1, 2, 3]) ) ]) @property def states(self): return [BallDirection.NONE, BallDirection.FORWARD, BallDirection.BACKWARD, BallDirection.LATERAL] def row(self, state, possession): return self.data[possession][state]
none
1
2.585996
3
unitorch/cli/models/clip/processing.py
fuliucansheng/UniTorch
2
6628294
# Copyright (c) FULIUCANSHENG. # Licensed under the MIT License. from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union from PIL import Image from unitorch.models.clip import CLIPProcessor as _CLIPProcessor from unitorch.cli import ( add_default_section_for_init, add_default_section_for_function, register_process, ) from unitorch.cli import cached_path from unitorch.cli.models import ( BaseInputs, BaseOutputs, BaseTargets, GenerationOutputs, GenerationTargets, ) from unitorch.cli.models.clip import pretrained_clip_infos class CLIPProcessor(_CLIPProcessor): def __init__( self, vocab_path: str, merge_path: str, vision_config_path: str, max_seq_length: int = 128, position_start_id: int = 0, ): super().__init__( vocab_path=vocab_path, merge_path=merge_path, vision_config_path=vision_config_path, max_seq_length=max_seq_length, position_start_id=position_start_id, ) @classmethod @add_default_section_for_init("core/process/clip") def from_core_configure(cls, config, **kwargs): config.set_default_section("core/process/clip") pretrained_name = config.getoption("pretrained_name", "default-clip") vocab_name_or_path = config.getoption("vocab_path", pretrained_name) vocab_path = ( pretrained_clip_infos[vocab_name_or_path]["vocab"] if vocab_name_or_path in pretrained_clip_infos else vocab_name_or_path ) vocab_path = cached_path(vocab_path) merge_name_or_path = config.getoption("merge_path", pretrained_name) merge_path = ( pretrained_clip_infos[merge_name_or_path]["merge"] if merge_name_or_path in pretrained_clip_infos else merge_name_or_path ) merge_path = cached_path(merge_path) vision_config_name_or_path = config.getoption("vision_config_path", pretrained_name) vision_config_path = ( pretrained_clip_infos[vision_config_name_or_path]["vision_config"] if vision_config_name_or_path in pretrained_clip_infos else vision_config_name_or_path ) vision_config_path = cached_path(vision_config_path) return { "vocab_path": vocab_path, "merge_path": merge_path, "vision_config_path": vision_config_path, } def _read_image(self, image_path): return Image.open(image_path) @register_process("core/process/clip_classification") def _processing_classification( self, text: str, image: Union[Image.Image, str], max_seq_length: int = None, ): if isinstance(image, str): image = self._read_image(image) outputs = super().processing_classification( text=text, image=image, max_seq_length=max_seq_length, ) return BaseInputs( input_ids=outputs.tokens_ids, attention_mask=outputs.attn_mask, position_ids=outputs.pos_ids, pixel_values=outputs.image, ) @register_process("core/process/clip_text_classification") def _processing_text_classifictaion( self, text: str, max_seq_length: int = None, ): outputs = super().processing_text_classifictaion( text=text, max_seq_length=max_seq_length, ) return BaseInputs( input_ids=outputs.tokens_ids, attention_mask=outputs.attn_mask, position_ids=outputs.pos_ids, ) @register_process("core/process/clip_image_classification") def _processing_image_classifictaion( self, image: Union[Image.Image, str], ): if isinstance(image, str): image = self._read_image(image) outputs = super().processing_image_classifictaion(image=image) return BaseInputs(pixel_values=outputs.image)
# Copyright (c) FULIUCANSHENG. # Licensed under the MIT License. from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union from PIL import Image from unitorch.models.clip import CLIPProcessor as _CLIPProcessor from unitorch.cli import ( add_default_section_for_init, add_default_section_for_function, register_process, ) from unitorch.cli import cached_path from unitorch.cli.models import ( BaseInputs, BaseOutputs, BaseTargets, GenerationOutputs, GenerationTargets, ) from unitorch.cli.models.clip import pretrained_clip_infos class CLIPProcessor(_CLIPProcessor): def __init__( self, vocab_path: str, merge_path: str, vision_config_path: str, max_seq_length: int = 128, position_start_id: int = 0, ): super().__init__( vocab_path=vocab_path, merge_path=merge_path, vision_config_path=vision_config_path, max_seq_length=max_seq_length, position_start_id=position_start_id, ) @classmethod @add_default_section_for_init("core/process/clip") def from_core_configure(cls, config, **kwargs): config.set_default_section("core/process/clip") pretrained_name = config.getoption("pretrained_name", "default-clip") vocab_name_or_path = config.getoption("vocab_path", pretrained_name) vocab_path = ( pretrained_clip_infos[vocab_name_or_path]["vocab"] if vocab_name_or_path in pretrained_clip_infos else vocab_name_or_path ) vocab_path = cached_path(vocab_path) merge_name_or_path = config.getoption("merge_path", pretrained_name) merge_path = ( pretrained_clip_infos[merge_name_or_path]["merge"] if merge_name_or_path in pretrained_clip_infos else merge_name_or_path ) merge_path = cached_path(merge_path) vision_config_name_or_path = config.getoption("vision_config_path", pretrained_name) vision_config_path = ( pretrained_clip_infos[vision_config_name_or_path]["vision_config"] if vision_config_name_or_path in pretrained_clip_infos else vision_config_name_or_path ) vision_config_path = cached_path(vision_config_path) return { "vocab_path": vocab_path, "merge_path": merge_path, "vision_config_path": vision_config_path, } def _read_image(self, image_path): return Image.open(image_path) @register_process("core/process/clip_classification") def _processing_classification( self, text: str, image: Union[Image.Image, str], max_seq_length: int = None, ): if isinstance(image, str): image = self._read_image(image) outputs = super().processing_classification( text=text, image=image, max_seq_length=max_seq_length, ) return BaseInputs( input_ids=outputs.tokens_ids, attention_mask=outputs.attn_mask, position_ids=outputs.pos_ids, pixel_values=outputs.image, ) @register_process("core/process/clip_text_classification") def _processing_text_classifictaion( self, text: str, max_seq_length: int = None, ): outputs = super().processing_text_classifictaion( text=text, max_seq_length=max_seq_length, ) return BaseInputs( input_ids=outputs.tokens_ids, attention_mask=outputs.attn_mask, position_ids=outputs.pos_ids, ) @register_process("core/process/clip_image_classification") def _processing_image_classifictaion( self, image: Union[Image.Image, str], ): if isinstance(image, str): image = self._read_image(image) outputs = super().processing_image_classifictaion(image=image) return BaseInputs(pixel_values=outputs.image)
en
0.801694
# Copyright (c) FULIUCANSHENG. # Licensed under the MIT License.
2.05563
2
prop_management/migrations/0001_initial.py
lichong012245/cornerstone
0
6628295
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Property' db.create_table('prop_management_properties', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('address', self.gf('django.db.models.fields.CharField')(max_length=100)), ('block_lot', self.gf('django.db.models.fields.CharField')(max_length=30, blank=True)), ('sqrf', self.gf('django.db.models.fields.IntegerField')(blank=True)), ('year_built', self.gf('django.db.models.fields.IntegerField')(blank=True)), ('number_of_units', self.gf('django.db.models.fields.IntegerField')()), )) db.send_create_signal(u'prop_management', ['Property']) # Adding model 'Apartment' db.create_table(u'prop_management_apartment', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('property', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Property'])), ('alias', self.gf('django.db.models.fields.CharField')(max_length=50)), ('num_of_bedroom', self.gf('django.db.models.fields.IntegerField')()), ('num_of_bathroom', self.gf('django.db.models.fields.IntegerField')()), ('rent', self.gf('django.db.models.fields.IntegerField')()), )) db.send_create_signal(u'prop_management', ['Apartment']) # Adding model 'Tenant' db.create_table(u'prop_management_tenant', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('first_name', self.gf('django.db.models.fields.CharField')(max_length=30)), ('last_name', self.gf('django.db.models.fields.CharField')(max_length=30)), ('apartment', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Apartment'])), ('phone', self.gf('django.db.models.fields.CharField')(max_length=15, blank=True)), ('is_current', self.gf('django.db.models.fields.BooleanField')()), )) db.send_create_signal(u'prop_management', ['Tenant']) # Adding model 'RentIncome' db.create_table(u'prop_management_rentincome', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('tenant', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Tenant'])), ('apartment', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Apartment'])), ('amount', self.gf('django.db.models.fields.IntegerField')()), ('date', self.gf('django.db.models.fields.DateField')()), ('is_full_for_current_month', self.gf('django.db.models.fields.BooleanField')()), ('is_check', self.gf('django.db.models.fields.BooleanField')()), ('check_number', self.gf('django.db.models.fields.CharField')(max_length=30, blank=True)), ('is_check_valid', self.gf('django.db.models.fields.BooleanField')()), ('date_year_month', self.gf('django.db.models.fields.CharField')(max_length=7)), )) db.send_create_signal(u'prop_management', ['RentIncome']) # Adding model 'ExpenseType' db.create_table(u'prop_management_expensetype', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('type', self.gf('django.db.models.fields.CharField')(max_length=20)), ('description', self.gf('django.db.models.fields.CharField')(max_length=500)), )) db.send_create_signal(u'prop_management', ['ExpenseType']) # Adding model 'Vendor' db.create_table(u'prop_management_vendor', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=30)), ('address', self.gf('django.db.models.fields.CharField')(max_length=30, blank=True)), )) db.send_create_signal(u'prop_management', ['Vendor']) # Adding model 'Expense' db.create_table(u'prop_management_expense', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('expense_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.ExpenseType'])), ('property', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Property'], null=True, blank=True)), ('apartment', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Apartment'], null=True, blank=True)), ('vendor', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Vendor'], null=True, blank=True)), ('amount', self.gf('django.db.models.fields.DecimalField')(max_digits=10, decimal_places=2)), ('date', self.gf('django.db.models.fields.DateField')(null=True, blank=True)), ('description', self.gf('django.db.models.fields.CharField')(max_length=500)), )) db.send_create_signal(u'prop_management', ['Expense']) def backwards(self, orm): # Deleting model 'Property' db.delete_table('Properties') # Deleting model 'Apartment' db.delete_table(u'prop_management_apartment') # Deleting model 'Tenant' db.delete_table(u'prop_management_tenant') # Deleting model 'RentIncome' db.delete_table(u'prop_management_rentincome') # Deleting model 'ExpenseType' db.delete_table(u'prop_management_expensetype') # Deleting model 'Vendor' db.delete_table(u'prop_management_vendor') # Deleting model 'Expense' db.delete_table(u'prop_management_expense') models = { u'prop_management.apartment': { 'Meta': {'object_name': 'Apartment'}, 'alias': ('django.db.models.fields.CharField', [], {'max_length': '50'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'num_of_bathroom': ('django.db.models.fields.IntegerField', [], {}), 'num_of_bedroom': ('django.db.models.fields.IntegerField', [], {}), 'property': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Property']"}), 'rent': ('django.db.models.fields.IntegerField', [], {}) }, u'prop_management.expense': { 'Meta': {'object_name': 'Expense'}, 'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '10', 'decimal_places': '2'}), 'apartment': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Apartment']", 'null': 'True', 'blank': 'True'}), 'date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'expense_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.ExpenseType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'property': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Property']", 'null': 'True', 'blank': 'True'}), 'vendor': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Vendor']", 'null': 'True', 'blank': 'True'}) }, u'prop_management.expensetype': { 'Meta': {'object_name': 'ExpenseType'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '500'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '20'}) }, u'prop_management.property': { 'Meta': {'object_name': 'Property', 'db_table': "'Properties'"}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'block_lot': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'number_of_units': ('django.db.models.fields.IntegerField', [], {}), 'sqrf': ('django.db.models.fields.IntegerField', [], {'blank': 'True'}), 'year_built': ('django.db.models.fields.IntegerField', [], {'blank': 'True'}) }, u'prop_management.rentincome': { 'Meta': {'object_name': 'RentIncome'}, 'amount': ('django.db.models.fields.IntegerField', [], {}), 'apartment': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Apartment']"}), 'check_number': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'date': ('django.db.models.fields.DateField', [], {}), 'date_year_month': ('django.db.models.fields.CharField', [], {'max_length': '7'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_check': ('django.db.models.fields.BooleanField', [], {}), 'is_check_valid': ('django.db.models.fields.BooleanField', [], {}), 'is_full_for_current_month': ('django.db.models.fields.BooleanField', [], {}), 'tenant': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Tenant']"}) }, u'prop_management.tenant': { 'Meta': {'object_name': 'Tenant'}, 'apartment': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Apartment']"}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_current': ('django.db.models.fields.BooleanField', [], {}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}) }, u'prop_management.vendor': { 'Meta': {'object_name': 'Vendor'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '30'}) } } complete_apps = ['prop_management']
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Property' db.create_table('prop_management_properties', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('address', self.gf('django.db.models.fields.CharField')(max_length=100)), ('block_lot', self.gf('django.db.models.fields.CharField')(max_length=30, blank=True)), ('sqrf', self.gf('django.db.models.fields.IntegerField')(blank=True)), ('year_built', self.gf('django.db.models.fields.IntegerField')(blank=True)), ('number_of_units', self.gf('django.db.models.fields.IntegerField')()), )) db.send_create_signal(u'prop_management', ['Property']) # Adding model 'Apartment' db.create_table(u'prop_management_apartment', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('property', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Property'])), ('alias', self.gf('django.db.models.fields.CharField')(max_length=50)), ('num_of_bedroom', self.gf('django.db.models.fields.IntegerField')()), ('num_of_bathroom', self.gf('django.db.models.fields.IntegerField')()), ('rent', self.gf('django.db.models.fields.IntegerField')()), )) db.send_create_signal(u'prop_management', ['Apartment']) # Adding model 'Tenant' db.create_table(u'prop_management_tenant', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('first_name', self.gf('django.db.models.fields.CharField')(max_length=30)), ('last_name', self.gf('django.db.models.fields.CharField')(max_length=30)), ('apartment', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Apartment'])), ('phone', self.gf('django.db.models.fields.CharField')(max_length=15, blank=True)), ('is_current', self.gf('django.db.models.fields.BooleanField')()), )) db.send_create_signal(u'prop_management', ['Tenant']) # Adding model 'RentIncome' db.create_table(u'prop_management_rentincome', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('tenant', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Tenant'])), ('apartment', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Apartment'])), ('amount', self.gf('django.db.models.fields.IntegerField')()), ('date', self.gf('django.db.models.fields.DateField')()), ('is_full_for_current_month', self.gf('django.db.models.fields.BooleanField')()), ('is_check', self.gf('django.db.models.fields.BooleanField')()), ('check_number', self.gf('django.db.models.fields.CharField')(max_length=30, blank=True)), ('is_check_valid', self.gf('django.db.models.fields.BooleanField')()), ('date_year_month', self.gf('django.db.models.fields.CharField')(max_length=7)), )) db.send_create_signal(u'prop_management', ['RentIncome']) # Adding model 'ExpenseType' db.create_table(u'prop_management_expensetype', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('type', self.gf('django.db.models.fields.CharField')(max_length=20)), ('description', self.gf('django.db.models.fields.CharField')(max_length=500)), )) db.send_create_signal(u'prop_management', ['ExpenseType']) # Adding model 'Vendor' db.create_table(u'prop_management_vendor', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=30)), ('address', self.gf('django.db.models.fields.CharField')(max_length=30, blank=True)), )) db.send_create_signal(u'prop_management', ['Vendor']) # Adding model 'Expense' db.create_table(u'prop_management_expense', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('expense_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.ExpenseType'])), ('property', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Property'], null=True, blank=True)), ('apartment', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Apartment'], null=True, blank=True)), ('vendor', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['prop_management.Vendor'], null=True, blank=True)), ('amount', self.gf('django.db.models.fields.DecimalField')(max_digits=10, decimal_places=2)), ('date', self.gf('django.db.models.fields.DateField')(null=True, blank=True)), ('description', self.gf('django.db.models.fields.CharField')(max_length=500)), )) db.send_create_signal(u'prop_management', ['Expense']) def backwards(self, orm): # Deleting model 'Property' db.delete_table('Properties') # Deleting model 'Apartment' db.delete_table(u'prop_management_apartment') # Deleting model 'Tenant' db.delete_table(u'prop_management_tenant') # Deleting model 'RentIncome' db.delete_table(u'prop_management_rentincome') # Deleting model 'ExpenseType' db.delete_table(u'prop_management_expensetype') # Deleting model 'Vendor' db.delete_table(u'prop_management_vendor') # Deleting model 'Expense' db.delete_table(u'prop_management_expense') models = { u'prop_management.apartment': { 'Meta': {'object_name': 'Apartment'}, 'alias': ('django.db.models.fields.CharField', [], {'max_length': '50'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'num_of_bathroom': ('django.db.models.fields.IntegerField', [], {}), 'num_of_bedroom': ('django.db.models.fields.IntegerField', [], {}), 'property': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Property']"}), 'rent': ('django.db.models.fields.IntegerField', [], {}) }, u'prop_management.expense': { 'Meta': {'object_name': 'Expense'}, 'amount': ('django.db.models.fields.DecimalField', [], {'max_digits': '10', 'decimal_places': '2'}), 'apartment': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Apartment']", 'null': 'True', 'blank': 'True'}), 'date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'expense_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.ExpenseType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'property': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Property']", 'null': 'True', 'blank': 'True'}), 'vendor': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Vendor']", 'null': 'True', 'blank': 'True'}) }, u'prop_management.expensetype': { 'Meta': {'object_name': 'ExpenseType'}, 'description': ('django.db.models.fields.CharField', [], {'max_length': '500'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'type': ('django.db.models.fields.CharField', [], {'max_length': '20'}) }, u'prop_management.property': { 'Meta': {'object_name': 'Property', 'db_table': "'Properties'"}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'block_lot': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'number_of_units': ('django.db.models.fields.IntegerField', [], {}), 'sqrf': ('django.db.models.fields.IntegerField', [], {'blank': 'True'}), 'year_built': ('django.db.models.fields.IntegerField', [], {'blank': 'True'}) }, u'prop_management.rentincome': { 'Meta': {'object_name': 'RentIncome'}, 'amount': ('django.db.models.fields.IntegerField', [], {}), 'apartment': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Apartment']"}), 'check_number': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'date': ('django.db.models.fields.DateField', [], {}), 'date_year_month': ('django.db.models.fields.CharField', [], {'max_length': '7'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_check': ('django.db.models.fields.BooleanField', [], {}), 'is_check_valid': ('django.db.models.fields.BooleanField', [], {}), 'is_full_for_current_month': ('django.db.models.fields.BooleanField', [], {}), 'tenant': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Tenant']"}) }, u'prop_management.tenant': { 'Meta': {'object_name': 'Tenant'}, 'apartment': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['prop_management.Apartment']"}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_current': ('django.db.models.fields.BooleanField', [], {}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}) }, u'prop_management.vendor': { 'Meta': {'object_name': 'Vendor'}, 'address': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '30'}) } } complete_apps = ['prop_management']
en
0.815704
# -*- coding: utf-8 -*- # Adding model 'Property' # Adding model 'Apartment' # Adding model 'Tenant' # Adding model 'RentIncome' # Adding model 'ExpenseType' # Adding model 'Vendor' # Adding model 'Expense' # Deleting model 'Property' # Deleting model 'Apartment' # Deleting model 'Tenant' # Deleting model 'RentIncome' # Deleting model 'ExpenseType' # Deleting model 'Vendor' # Deleting model 'Expense'
2.24862
2
loader.py
zhangkezhong/ResNet
1
6628296
<reponame>zhangkezhong/ResNet<filename>loader.py import os import torch import torch.utils.data as data from PIL import Image from torchvision import transforms def default_loader(path): return Image.open(path).convert('RGB') mytransform = transforms.Compose([ transforms.Resize(224), transforms.CenterCrop(224), transforms.ToTensor() ] ) class myImageFloder(data.Dataset): def __init__(self, root, label, transform=None, target_transform=None, loader=default_loader): fh = open(label) c = 0 imgs = [] class_names = [] for line in fh.readlines(): if c == 0: class_names = [n.strip() for n in line.rstrip().split(' ')] else: cls = line.split() fn = cls.pop(0) if os.path.isfile(os.path.join(root, fn)): imgs.append((fn, tuple([float(v) for v in cls]))) c = c + 1 self.root = root self.imgs = imgs self.classes = class_names self.transform = transform self.target_transform = target_transform self.loader = loader def __getitem__(self, index): fn, label = self.imgs[index] img = self.loader(os.path.join(self.root, fn)) if self.transform is not None: img = self.transform(img) return img, torch.Tensor(label) def __len__(self): return len(self.imgs) def getName(self): return self.classes def trainingmyImageFloder(): dataloader = myImageFloder('./training_data', './training_data/training_data.txt', transform=mytransform) #print ('training dataloader.getName', dataloader.getName()) #for index, (img, label) in enumerate(dataloader): #img.show() #print('img->', img.size(), ' label->', label) return dataloader def testmyImageFloder(): dataloader = myImageFloder('./test_data', './test_data/test_data.txt', transform=mytransform) #print ('test dataloader.getName', dataloader.getName()) #for index, (img, label) in enumerate(dataloader): #img.show() #print('img->', img.size(), ' label->', label) return dataloader # if __name__ == "__main__": # training=trainingmyImageFloder() # test=testmyImageFloder() # img_train, label_train = training[0] # img_test, label_test = test[0] # for img, label in training: # print(img.size(), label) # for img, label in test: # print(img.size(), label)
import os import torch import torch.utils.data as data from PIL import Image from torchvision import transforms def default_loader(path): return Image.open(path).convert('RGB') mytransform = transforms.Compose([ transforms.Resize(224), transforms.CenterCrop(224), transforms.ToTensor() ] ) class myImageFloder(data.Dataset): def __init__(self, root, label, transform=None, target_transform=None, loader=default_loader): fh = open(label) c = 0 imgs = [] class_names = [] for line in fh.readlines(): if c == 0: class_names = [n.strip() for n in line.rstrip().split(' ')] else: cls = line.split() fn = cls.pop(0) if os.path.isfile(os.path.join(root, fn)): imgs.append((fn, tuple([float(v) for v in cls]))) c = c + 1 self.root = root self.imgs = imgs self.classes = class_names self.transform = transform self.target_transform = target_transform self.loader = loader def __getitem__(self, index): fn, label = self.imgs[index] img = self.loader(os.path.join(self.root, fn)) if self.transform is not None: img = self.transform(img) return img, torch.Tensor(label) def __len__(self): return len(self.imgs) def getName(self): return self.classes def trainingmyImageFloder(): dataloader = myImageFloder('./training_data', './training_data/training_data.txt', transform=mytransform) #print ('training dataloader.getName', dataloader.getName()) #for index, (img, label) in enumerate(dataloader): #img.show() #print('img->', img.size(), ' label->', label) return dataloader def testmyImageFloder(): dataloader = myImageFloder('./test_data', './test_data/test_data.txt', transform=mytransform) #print ('test dataloader.getName', dataloader.getName()) #for index, (img, label) in enumerate(dataloader): #img.show() #print('img->', img.size(), ' label->', label) return dataloader # if __name__ == "__main__": # training=trainingmyImageFloder() # test=testmyImageFloder() # img_train, label_train = training[0] # img_test, label_test = test[0] # for img, label in training: # print(img.size(), label) # for img, label in test: # print(img.size(), label)
en
0.166607
#print ('training dataloader.getName', dataloader.getName()) #for index, (img, label) in enumerate(dataloader): #img.show() #print('img->', img.size(), ' label->', label) #print ('test dataloader.getName', dataloader.getName()) #for index, (img, label) in enumerate(dataloader): #img.show() #print('img->', img.size(), ' label->', label) # if __name__ == "__main__": # training=trainingmyImageFloder() # test=testmyImageFloder() # img_train, label_train = training[0] # img_test, label_test = test[0] # for img, label in training: # print(img.size(), label) # for img, label in test: # print(img.size(), label)
2.61589
3
mitmproxy-20210516/page/__init__.py
ti132520/pytest-vlog
0
6628297
# -*- coding: utf-8 -*- # Author : 怕你呀 # Time : 2021/5/16 # File : __init__.py # IDE : PyCharm
# -*- coding: utf-8 -*- # Author : 怕你呀 # Time : 2021/5/16 # File : __init__.py # IDE : PyCharm
ja
0.730468
# -*- coding: utf-8 -*- # Author : 怕你呀 # Time : 2021/5/16 # File : __init__.py # IDE : PyCharm
1.194082
1
shop_sendcloud/__init__.py
markusmo/djangoshop-sendcloud
6
6628298
<reponame>markusmo/djangoshop-sendcloud<filename>shop_sendcloud/__init__.py """ See PEP 386 (https://www.python.org/dev/peps/pep-0386/) Release logic: 1. Increase version number (change __version__ below). 2. Check that all changes have been documented in CHANGELOG.md. 3. In setup.py, assure that `classifiers` and `install_requires` reflect the latest versions. 4. git add shop_sendcloud/__init__.py CHANGELOG.md setup.py 5. git commit -m 'Bump to {new version}' 6. git tag {new version} 7. git push --tags 8. python setup.py sdist 9. twine upload dist/djangoshop-sendcloud-{new version}.tar.gz """ __version__ = '1.2.1'
""" See PEP 386 (https://www.python.org/dev/peps/pep-0386/) Release logic: 1. Increase version number (change __version__ below). 2. Check that all changes have been documented in CHANGELOG.md. 3. In setup.py, assure that `classifiers` and `install_requires` reflect the latest versions. 4. git add shop_sendcloud/__init__.py CHANGELOG.md setup.py 5. git commit -m 'Bump to {new version}' 6. git tag {new version} 7. git push --tags 8. python setup.py sdist 9. twine upload dist/djangoshop-sendcloud-{new version}.tar.gz """ __version__ = '1.2.1'
en
0.516456
See PEP 386 (https://www.python.org/dev/peps/pep-0386/) Release logic: 1. Increase version number (change __version__ below). 2. Check that all changes have been documented in CHANGELOG.md. 3. In setup.py, assure that `classifiers` and `install_requires` reflect the latest versions. 4. git add shop_sendcloud/__init__.py CHANGELOG.md setup.py 5. git commit -m 'Bump to {new version}' 6. git tag {new version} 7. git push --tags 8. python setup.py sdist 9. twine upload dist/djangoshop-sendcloud-{new version}.tar.gz
1.523685
2
Corrfunc/io.py
manodeep/Corrfunc
139
6628299
<filename>Corrfunc/io.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ Routines to read galaxy catalogs from disk. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from os.path import dirname, abspath, splitext, exists as file_exists,\ join as pjoin import numpy as np try: import pandas as pd except ImportError: pd = None __all__ = ('read_fastfood_catalog', 'read_ascii_catalog', 'read_catalog') def read_fastfood_catalog(filename, return_dtype=None, need_header=None): """ Read a galaxy catalog from a fast-food binary file. Parameters ----------- filename: string Filename containing the galaxy positions return_dtype: numpy dtype for returned arrays. Default ``numpy.float`` Specifies the datatype for the returned arrays. Must be in {np.float64, np.float32} need_header: boolean, default None. Returns the header found in the fast-food file in addition to the X/Y/Z arrays. Returns -------- X, Y, Z: numpy arrays Returns the triplet of X/Y/Z positions as separate numpy arrays. If need_header is set, then the header is also returned Example -------- >>> import numpy as np >>> from os.path import dirname, abspath, join as pjoin >>> import Corrfunc >>> from Corrfunc.io import read_fastfood_catalog >>> filename = pjoin(dirname(abspath(Corrfunc.__file__)), ... "../theory/tests/data/", ... "gals_Mr19.ff") >>> X, Y, Z = read_fastfood_catalog(filename) >>> N = 20 >>> for x,y,z in zip(X[0:N], Y[0:N], Z[0:]): ... print("{0:10.5f} {1:10.5f} {2:10.5f}".format(x, y, z)) ... # doctest: +NORMALIZE_WHITESPACE 419.94550 1.96340 0.01610 419.88272 1.79736 0.11960 0.32880 10.63620 4.16550 0.15314 10.68723 4.06529 0.46400 8.91150 6.97090 6.30690 9.77090 8.61080 5.87160 9.65870 9.29810 8.06210 0.42350 4.89410 11.92830 4.38660 4.54410 11.95543 4.32622 4.51485 11.65676 4.34665 4.53181 11.75739 4.26262 4.31666 11.81329 4.27530 4.49183 11.80406 4.54737 4.26824 12.61570 4.14470 3.70140 13.23640 4.34750 5.26450 13.19833 4.33196 5.29435 13.21249 4.35695 5.37418 13.06805 4.24275 5.35126 13.19693 4.37618 5.28772 """ if return_dtype is None: return_dtype = np.float64 if return_dtype not in [np.float32, np.float64]: msg = "Return data-type must be set and a valid numpy float" raise ValueError(msg) if not file_exists(filename): msg = "Could not find file = {0}".format(filename) raise IOError(msg) import struct try: from future.utils import bytes_to_native_str except ImportError: print("\n\tPlease run python -m pip install Corrfunc before using " "the 'Corrfunc' package\n") raise with open(filename, "rb") as f: skip1 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] idat = struct.unpack(bytes_to_native_str(b'@iiiii'), f.read(20))[0:5] skip2 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] assert skip1 == 20 and skip2 == 20,\ "fast-food file seems to be incorrect (reading idat)" ngal = idat[1] if need_header is not None: # now read fdat skip1 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] fdat = struct.unpack(bytes_to_native_str(b'@fffffffff'), f.read(36))[0:9] skip2 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] assert skip1 == 36 and skip2 == 36,\ "fast-food file seems to be incorrect (reading fdat )" skip1 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] znow = struct.unpack(bytes_to_native_str(b'@f'), f.read(4))[0] skip2 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] assert skip1 == 4 and skip2 == 4,\ "fast-food file seems to be incorrect (reading redshift)" else: fdat_bytes = 4 + 36 + 4 znow_bytes = 4 + 4 + 4 # seek over the fdat + znow fields + padding bytes # from current position f.seek(fdat_bytes + znow_bytes, 1) # read the padding bytes for the x-positions skip1 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] assert skip1 == ngal * 4 or skip1 == ngal * 8, \ "fast-food file seems to be corrupt (padding bytes)" # seek back 4 bytes from current position f.seek(-4, 1) pos = {} for field in 'xyz': skip1 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] assert skip1 == ngal * 4 or skip1 == ngal * 8, \ "fast-food file seems to be corrupt (padding bytes a)" # the next division must be the integer division input_dtype = np.float32 if skip1 // ngal == 4 else np.float64 array = np.fromfile(f, input_dtype, ngal) skip2 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] if return_dtype == input_dtype: pos[field] = array else: pos[field] = [return_dtype(a) for a in array] x = np.array(pos['x']) y = np.array(pos['y']) z = np.array(pos['z']) if need_header is not None: return idat, fdat, znow, x, y, z else: return x, y, z def read_ascii_catalog(filename, return_dtype=None): """ Read a galaxy catalog from an ascii file. Parameters ----------- filename: string Filename containing the galaxy positions return_dtype: numpy dtype for returned arrays. Default ``numpy.float`` Specifies the datatype for the returned arrays. Must be in {np.float64, np.float32} Returns -------- X, Y, Z: numpy arrays Returns the triplet of X/Y/Z positions as separate numpy arrays. Example -------- >>> from __future__ import print_function >>> from os.path import dirname, abspath, join as pjoin >>> import Corrfunc >>> from Corrfunc.io import read_ascii_catalog >>> filename = pjoin(dirname(abspath(Corrfunc.__file__)), ... "../mocks/tests/data/", "Mr19_mock_northonly.rdcz.dat") >>> ra, dec, cz = read_ascii_catalog(filename) >>> N = 20 >>> for r,d,c in zip(ra[0:N], dec[0:N], cz[0:]): ... print("{0:10.5f} {1:10.5f} {2:10.5f}".format(r, d, c)) ... # doctest: +NORMALIZE_WHITESPACE 178.45087 67.01112 19905.28514 178.83495 67.72519 19824.02285 179.50132 67.67628 19831.21553 182.75497 67.13004 19659.79825 186.29853 68.64099 20030.64412 186.32346 68.65879 19763.38137 187.36173 68.15151 19942.66996 187.20613 68.56189 19996.36607 185.56358 67.97724 19729.32308 183.27930 67.11318 19609.71345 183.86498 67.82823 19500.44130 184.07771 67.43429 19440.53790 185.13370 67.15382 19390.60304 189.15907 68.28252 19858.85853 190.12209 68.55062 20044.29744 193.65245 68.36878 19445.62469 194.93514 68.34870 19158.93155 180.36897 67.50058 18671.40780 179.63278 67.51318 18657.59191 180.75742 67.95530 18586.88913 """ if return_dtype is None: return_dtype = np.float64 if not file_exists(filename): msg = "Could not find file = {0}".format(filename) raise IOError(msg) # check if pandas is available - much faster to read in the data # using pandas if pd is not None: df = pd.read_csv(filename, header=None, engine="c", dtype={"x": return_dtype, "y": return_dtype, "z": return_dtype}, delim_whitespace=True) x = np.asarray(df[0], dtype=return_dtype) y = np.asarray(df[1], dtype=return_dtype) z = np.asarray(df[2], dtype=return_dtype) else: x, y, z, _ = np.genfromtxt(filename, dtype=return_dtype, unpack=True) return x, y, z def read_catalog(filebase=None, return_dtype=np.float64): """ Reads a galaxy/randoms catalog and returns 3 XYZ arrays. Parameters ----------- filebase: string (optional) The fully qualified path to the file. If omitted, reads the theory galaxy catalog under ../theory/tests/data/ return_dtype: numpy dtype for returned arrays. Default ``numpy.float`` Specifies the datatype for the returned arrays. Must be in {np.float64, np.float32} Returns -------- ``x y z`` - Unpacked numpy arrays compatible with the installed version of ``Corrfunc``. .. note:: If the filename is omitted, then first the fast-food file is searched for, and then the ascii file. End-users should always supply the full filename. """ if filebase is None: filename = pjoin(dirname(abspath(__file__)), "../theory/tests/data/", "gals_Mr19") allowed_exts = {'.ff': read_fastfood_catalog, '.txt': read_ascii_catalog, '.dat': read_ascii_catalog, '.csv': read_ascii_catalog } for e in allowed_exts: if file_exists(filename + e): f = allowed_exts[e] x, y, z = f(filename + e, return_dtype) return x, y, z raise IOError("Could not locate {0} with any of these extensions \ = {1}".format(filename, allowed_exts.keys())) else: # Likely an user-supplied value if file_exists(filebase): extension = splitext(filebase)[1] f = read_fastfood_catalog if '.ff' in extension else read_ascii_catalog # default return is double x, y, z = f(filebase, return_dtype) return x, y, z raise IOError("Could not locate file {0}".format(filebase)) if __name__ == '__main__': import doctest doctest.testmod(verbose=True)
<filename>Corrfunc/io.py #!/usr/bin/env python # -*- coding: utf-8 -*- """ Routines to read galaxy catalogs from disk. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from os.path import dirname, abspath, splitext, exists as file_exists,\ join as pjoin import numpy as np try: import pandas as pd except ImportError: pd = None __all__ = ('read_fastfood_catalog', 'read_ascii_catalog', 'read_catalog') def read_fastfood_catalog(filename, return_dtype=None, need_header=None): """ Read a galaxy catalog from a fast-food binary file. Parameters ----------- filename: string Filename containing the galaxy positions return_dtype: numpy dtype for returned arrays. Default ``numpy.float`` Specifies the datatype for the returned arrays. Must be in {np.float64, np.float32} need_header: boolean, default None. Returns the header found in the fast-food file in addition to the X/Y/Z arrays. Returns -------- X, Y, Z: numpy arrays Returns the triplet of X/Y/Z positions as separate numpy arrays. If need_header is set, then the header is also returned Example -------- >>> import numpy as np >>> from os.path import dirname, abspath, join as pjoin >>> import Corrfunc >>> from Corrfunc.io import read_fastfood_catalog >>> filename = pjoin(dirname(abspath(Corrfunc.__file__)), ... "../theory/tests/data/", ... "gals_Mr19.ff") >>> X, Y, Z = read_fastfood_catalog(filename) >>> N = 20 >>> for x,y,z in zip(X[0:N], Y[0:N], Z[0:]): ... print("{0:10.5f} {1:10.5f} {2:10.5f}".format(x, y, z)) ... # doctest: +NORMALIZE_WHITESPACE 419.94550 1.96340 0.01610 419.88272 1.79736 0.11960 0.32880 10.63620 4.16550 0.15314 10.68723 4.06529 0.46400 8.91150 6.97090 6.30690 9.77090 8.61080 5.87160 9.65870 9.29810 8.06210 0.42350 4.89410 11.92830 4.38660 4.54410 11.95543 4.32622 4.51485 11.65676 4.34665 4.53181 11.75739 4.26262 4.31666 11.81329 4.27530 4.49183 11.80406 4.54737 4.26824 12.61570 4.14470 3.70140 13.23640 4.34750 5.26450 13.19833 4.33196 5.29435 13.21249 4.35695 5.37418 13.06805 4.24275 5.35126 13.19693 4.37618 5.28772 """ if return_dtype is None: return_dtype = np.float64 if return_dtype not in [np.float32, np.float64]: msg = "Return data-type must be set and a valid numpy float" raise ValueError(msg) if not file_exists(filename): msg = "Could not find file = {0}".format(filename) raise IOError(msg) import struct try: from future.utils import bytes_to_native_str except ImportError: print("\n\tPlease run python -m pip install Corrfunc before using " "the 'Corrfunc' package\n") raise with open(filename, "rb") as f: skip1 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] idat = struct.unpack(bytes_to_native_str(b'@iiiii'), f.read(20))[0:5] skip2 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] assert skip1 == 20 and skip2 == 20,\ "fast-food file seems to be incorrect (reading idat)" ngal = idat[1] if need_header is not None: # now read fdat skip1 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] fdat = struct.unpack(bytes_to_native_str(b'@fffffffff'), f.read(36))[0:9] skip2 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] assert skip1 == 36 and skip2 == 36,\ "fast-food file seems to be incorrect (reading fdat )" skip1 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] znow = struct.unpack(bytes_to_native_str(b'@f'), f.read(4))[0] skip2 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] assert skip1 == 4 and skip2 == 4,\ "fast-food file seems to be incorrect (reading redshift)" else: fdat_bytes = 4 + 36 + 4 znow_bytes = 4 + 4 + 4 # seek over the fdat + znow fields + padding bytes # from current position f.seek(fdat_bytes + znow_bytes, 1) # read the padding bytes for the x-positions skip1 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] assert skip1 == ngal * 4 or skip1 == ngal * 8, \ "fast-food file seems to be corrupt (padding bytes)" # seek back 4 bytes from current position f.seek(-4, 1) pos = {} for field in 'xyz': skip1 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] assert skip1 == ngal * 4 or skip1 == ngal * 8, \ "fast-food file seems to be corrupt (padding bytes a)" # the next division must be the integer division input_dtype = np.float32 if skip1 // ngal == 4 else np.float64 array = np.fromfile(f, input_dtype, ngal) skip2 = struct.unpack(bytes_to_native_str(b'@i'), f.read(4))[0] if return_dtype == input_dtype: pos[field] = array else: pos[field] = [return_dtype(a) for a in array] x = np.array(pos['x']) y = np.array(pos['y']) z = np.array(pos['z']) if need_header is not None: return idat, fdat, znow, x, y, z else: return x, y, z def read_ascii_catalog(filename, return_dtype=None): """ Read a galaxy catalog from an ascii file. Parameters ----------- filename: string Filename containing the galaxy positions return_dtype: numpy dtype for returned arrays. Default ``numpy.float`` Specifies the datatype for the returned arrays. Must be in {np.float64, np.float32} Returns -------- X, Y, Z: numpy arrays Returns the triplet of X/Y/Z positions as separate numpy arrays. Example -------- >>> from __future__ import print_function >>> from os.path import dirname, abspath, join as pjoin >>> import Corrfunc >>> from Corrfunc.io import read_ascii_catalog >>> filename = pjoin(dirname(abspath(Corrfunc.__file__)), ... "../mocks/tests/data/", "Mr19_mock_northonly.rdcz.dat") >>> ra, dec, cz = read_ascii_catalog(filename) >>> N = 20 >>> for r,d,c in zip(ra[0:N], dec[0:N], cz[0:]): ... print("{0:10.5f} {1:10.5f} {2:10.5f}".format(r, d, c)) ... # doctest: +NORMALIZE_WHITESPACE 178.45087 67.01112 19905.28514 178.83495 67.72519 19824.02285 179.50132 67.67628 19831.21553 182.75497 67.13004 19659.79825 186.29853 68.64099 20030.64412 186.32346 68.65879 19763.38137 187.36173 68.15151 19942.66996 187.20613 68.56189 19996.36607 185.56358 67.97724 19729.32308 183.27930 67.11318 19609.71345 183.86498 67.82823 19500.44130 184.07771 67.43429 19440.53790 185.13370 67.15382 19390.60304 189.15907 68.28252 19858.85853 190.12209 68.55062 20044.29744 193.65245 68.36878 19445.62469 194.93514 68.34870 19158.93155 180.36897 67.50058 18671.40780 179.63278 67.51318 18657.59191 180.75742 67.95530 18586.88913 """ if return_dtype is None: return_dtype = np.float64 if not file_exists(filename): msg = "Could not find file = {0}".format(filename) raise IOError(msg) # check if pandas is available - much faster to read in the data # using pandas if pd is not None: df = pd.read_csv(filename, header=None, engine="c", dtype={"x": return_dtype, "y": return_dtype, "z": return_dtype}, delim_whitespace=True) x = np.asarray(df[0], dtype=return_dtype) y = np.asarray(df[1], dtype=return_dtype) z = np.asarray(df[2], dtype=return_dtype) else: x, y, z, _ = np.genfromtxt(filename, dtype=return_dtype, unpack=True) return x, y, z def read_catalog(filebase=None, return_dtype=np.float64): """ Reads a galaxy/randoms catalog and returns 3 XYZ arrays. Parameters ----------- filebase: string (optional) The fully qualified path to the file. If omitted, reads the theory galaxy catalog under ../theory/tests/data/ return_dtype: numpy dtype for returned arrays. Default ``numpy.float`` Specifies the datatype for the returned arrays. Must be in {np.float64, np.float32} Returns -------- ``x y z`` - Unpacked numpy arrays compatible with the installed version of ``Corrfunc``. .. note:: If the filename is omitted, then first the fast-food file is searched for, and then the ascii file. End-users should always supply the full filename. """ if filebase is None: filename = pjoin(dirname(abspath(__file__)), "../theory/tests/data/", "gals_Mr19") allowed_exts = {'.ff': read_fastfood_catalog, '.txt': read_ascii_catalog, '.dat': read_ascii_catalog, '.csv': read_ascii_catalog } for e in allowed_exts: if file_exists(filename + e): f = allowed_exts[e] x, y, z = f(filename + e, return_dtype) return x, y, z raise IOError("Could not locate {0} with any of these extensions \ = {1}".format(filename, allowed_exts.keys())) else: # Likely an user-supplied value if file_exists(filebase): extension = splitext(filebase)[1] f = read_fastfood_catalog if '.ff' in extension else read_ascii_catalog # default return is double x, y, z = f(filebase, return_dtype) return x, y, z raise IOError("Could not locate file {0}".format(filebase)) if __name__ == '__main__': import doctest doctest.testmod(verbose=True)
en
0.535291
#!/usr/bin/env python # -*- coding: utf-8 -*- Routines to read galaxy catalogs from disk. Read a galaxy catalog from a fast-food binary file. Parameters ----------- filename: string Filename containing the galaxy positions return_dtype: numpy dtype for returned arrays. Default ``numpy.float`` Specifies the datatype for the returned arrays. Must be in {np.float64, np.float32} need_header: boolean, default None. Returns the header found in the fast-food file in addition to the X/Y/Z arrays. Returns -------- X, Y, Z: numpy arrays Returns the triplet of X/Y/Z positions as separate numpy arrays. If need_header is set, then the header is also returned Example -------- >>> import numpy as np >>> from os.path import dirname, abspath, join as pjoin >>> import Corrfunc >>> from Corrfunc.io import read_fastfood_catalog >>> filename = pjoin(dirname(abspath(Corrfunc.__file__)), ... "../theory/tests/data/", ... "gals_Mr19.ff") >>> X, Y, Z = read_fastfood_catalog(filename) >>> N = 20 >>> for x,y,z in zip(X[0:N], Y[0:N], Z[0:]): ... print("{0:10.5f} {1:10.5f} {2:10.5f}".format(x, y, z)) ... # doctest: +NORMALIZE_WHITESPACE 419.94550 1.96340 0.01610 419.88272 1.79736 0.11960 0.32880 10.63620 4.16550 0.15314 10.68723 4.06529 0.46400 8.91150 6.97090 6.30690 9.77090 8.61080 5.87160 9.65870 9.29810 8.06210 0.42350 4.89410 11.92830 4.38660 4.54410 11.95543 4.32622 4.51485 11.65676 4.34665 4.53181 11.75739 4.26262 4.31666 11.81329 4.27530 4.49183 11.80406 4.54737 4.26824 12.61570 4.14470 3.70140 13.23640 4.34750 5.26450 13.19833 4.33196 5.29435 13.21249 4.35695 5.37418 13.06805 4.24275 5.35126 13.19693 4.37618 5.28772 # now read fdat # seek over the fdat + znow fields + padding bytes # from current position # read the padding bytes for the x-positions # seek back 4 bytes from current position # the next division must be the integer division Read a galaxy catalog from an ascii file. Parameters ----------- filename: string Filename containing the galaxy positions return_dtype: numpy dtype for returned arrays. Default ``numpy.float`` Specifies the datatype for the returned arrays. Must be in {np.float64, np.float32} Returns -------- X, Y, Z: numpy arrays Returns the triplet of X/Y/Z positions as separate numpy arrays. Example -------- >>> from __future__ import print_function >>> from os.path import dirname, abspath, join as pjoin >>> import Corrfunc >>> from Corrfunc.io import read_ascii_catalog >>> filename = pjoin(dirname(abspath(Corrfunc.__file__)), ... "../mocks/tests/data/", "Mr19_mock_northonly.rdcz.dat") >>> ra, dec, cz = read_ascii_catalog(filename) >>> N = 20 >>> for r,d,c in zip(ra[0:N], dec[0:N], cz[0:]): ... print("{0:10.5f} {1:10.5f} {2:10.5f}".format(r, d, c)) ... # doctest: +NORMALIZE_WHITESPACE 178.45087 67.01112 19905.28514 178.83495 67.72519 19824.02285 179.50132 67.67628 19831.21553 182.75497 67.13004 19659.79825 186.29853 68.64099 20030.64412 186.32346 68.65879 19763.38137 187.36173 68.15151 19942.66996 187.20613 68.56189 19996.36607 185.56358 67.97724 19729.32308 183.27930 67.11318 19609.71345 183.86498 67.82823 19500.44130 184.07771 67.43429 19440.53790 185.13370 67.15382 19390.60304 189.15907 68.28252 19858.85853 190.12209 68.55062 20044.29744 193.65245 68.36878 19445.62469 194.93514 68.34870 19158.93155 180.36897 67.50058 18671.40780 179.63278 67.51318 18657.59191 180.75742 67.95530 18586.88913 # check if pandas is available - much faster to read in the data # using pandas Reads a galaxy/randoms catalog and returns 3 XYZ arrays. Parameters ----------- filebase: string (optional) The fully qualified path to the file. If omitted, reads the theory galaxy catalog under ../theory/tests/data/ return_dtype: numpy dtype for returned arrays. Default ``numpy.float`` Specifies the datatype for the returned arrays. Must be in {np.float64, np.float32} Returns -------- ``x y z`` - Unpacked numpy arrays compatible with the installed version of ``Corrfunc``. .. note:: If the filename is omitted, then first the fast-food file is searched for, and then the ascii file. End-users should always supply the full filename. # Likely an user-supplied value # default return is double
2.989721
3
Python Practice Programs/p5.py
deb991/TopGear__Projects_n_Assignments
0
6628300
#!/usr/bin/python import sys arg1 = 10 arg2 = 20 arg3 = 30 print("First number is", arg1) print("Second number is", arg2) print("Third number is", arg3) print("The biggest of three numbers is", max(arg1, arg2, arg3))
#!/usr/bin/python import sys arg1 = 10 arg2 = 20 arg3 = 30 print("First number is", arg1) print("Second number is", arg2) print("Third number is", arg3) print("The biggest of three numbers is", max(arg1, arg2, arg3))
ru
0.258958
#!/usr/bin/python
3.811941
4
downloader_day.py
vlddev/news_downloader
0
6628301
<reponame>vlddev/news_downloader<gh_stars>0 import pdb import sys, traceback import datetime import subprocess import json import re import logging import os.path from bs4 import BeautifulSoup import stats import downloader_common def run(): downloader = Downloader() logging.basicConfig(filename='downloader_day.log',level=logging.INFO, format='%(asctime)s %(levelname)s\t%(module)s\t%(message)s', datefmt='%d.%m.%Y %H:%M:%S') # get last downloaded number num = downloader.getLastDownloadedIssueNr() + 1 # get current issue number currentIssueNum = downloader.getCurrentIssueNr() print ("download issues from {0} to {1}".format(num, currentIssueNum)) logging.info("download issues from {0} to {1}".format(num, currentIssueNum)) now = datetime.datetime.now() year = now.year #for num in strNumList while (num <= currentIssueNum): #253 try: fname = ("%d/day_%03d.fb2" % (year, num)) if os.path.isfile(fname): print ("File %s exists, get next." % fname) else: content = downloader.fb2(num, year) if len(content) > 0: with open((downloader_common.rootPath+'/day/'+"%d/day_%03d.fb2" % (year, num)), "w") as fb2_file: fb2_file.write(content) else: print("No content for num %d, year %d." % (num, year)) logging.warning("No content for num %d, year %d." % (num, year)) except KeyboardInterrupt: sys.exit("Download interrupted.") except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) sys.exit("Unexpected error: "+ exc_type) num += 1 def runByNoWithParams(): downloader = Downloader() #2017 96 154 #year = int(sys.argv[1]) #num = int(sys.argv[2]) #lastNum = int(sys.argv[3])+1 year = 2022 num = 1 lastNum = 13 #while (num < lastNum): #253 # strNumList.append(str(num)) # num += 1 #strNumList = ['238-240','235-236','230-231','225-226','220-221','215-216','210-211','205-206','200-201','195-196','190-191','185-186', # '181-182','176-177','171-172','166-167','161-162','156-157','151-152','148-149','143-144','138-139','133-134'] logging.basicConfig(filename='downloader_day_'+str(year)+'.log',level=logging.INFO, format='%(asctime)s %(levelname)s\t%(module)s\t%(message)s', datefmt='%d.%m.%Y %H:%M:%S') #for num in strNumList while (num < lastNum): try: fname = ("%d/day_%03d.fb2" % (year, num)) if os.path.isfile(fname): print ("File %s exists, get next." % fname) else: content = downloader.fb2(num, year) if len(content) > 0: fileDate = str(num) if downloader.numDate is not None: fileDate = str(downloader.numDate) with open(downloader_common.rootPath+f'/day/{year}/day_{fileDate}.fb2', "w") as fb2_file: fb2_file.write(content) else: print("No content for num %d, year %d." % (num, year)) logging.warning("No content for num %d, year %d." % (num, year)) except KeyboardInterrupt: sys.exit("Download interrupted.") except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) sys.exit("Unexpected error: "+ exc_type) num += 1 def runByDate(): downloader = Downloader() ukrMonthDict = {1:"sichnya", 2:"lyutogo", 3:"bereznya", 4:"kvitnya", 5:"travnya", 6:"chervnya", 7:"lypnya", 8:"serpnya", 9:"veresnya", 10:"zhovtnya", 11:"lystopada", 12:"grudnya"} # 31-sichnya-2022 # 24-lyutogo-2022 # 31-bereznya-2022 # 27-kvitnya-2022 # 28-lypnya-2021 # 30-serpnya-2021 # 28-veresnya-2021 # 27-zhovtnya-2021 # 29-lystopada-2021 # 30-grudnya-2021 start_date = datetime.date(2022, 1, 1) end_date = datetime.date(2022, 4, 25) cur_date = start_date logging.basicConfig(filename='downloader_day_'+str(start_date.year)+'.log',level=logging.INFO, format='%(asctime)s %(levelname)s\t%(module)s\t%(message)s', datefmt='%d.%m.%Y %H:%M:%S') #for num in strNumList while (cur_date < end_date): print(str(cur_date)) try: fileDate = cur_date.isoformat() fname = downloader_common.rootPath+f'/day/{cur_date.year}/day_{fileDate}.fb2' if os.path.isfile(fname): print ("File %s exists, get next." % fname) else: dateUrlPart = f'{cur_date.day}-{ukrMonthDict[cur_date.month]}-{cur_date.year}' content = downloader.fb2ForUrl(dateUrlPart) if len(content) > 0: with open(fname, "w") as fb2_file: fb2_file.write(content) else: print(f"No content for date {fileDate}") logging.warning(f"No content for date {fileDate}") except KeyboardInterrupt: sys.exit("Download interrupted.") except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) sys.exit("Unexpected error: "+ exc_type) cur_date += datetime.timedelta(days=1) def runUrl(): downloader = Downloader() logging.basicConfig(filename='downloader_day.log',level=logging.INFO, format='%(asctime)s %(levelname)s\t%(module)s\t%(message)s', datefmt='%d.%m.%Y %H:%M:%S') noUrlPart = '28-lypnya-2021' content = downloader.fb2ForUrl(noUrlPart) if len(content) > 0: with open(("2021/%s.fb2" % (noUrlPart)), "w") as fb2_file: fb2_file.write(content) else: print("No content for noUrlPart %s." % (noUrlPart)) logging.warning("No content for noUrlPart %s." % (noUrlPart)) def test(): downloader = Downloader() logging.basicConfig(filename='downloader_day_test.log',level=logging.INFO, format='%(asctime)s %(levelname)s\t%(module)s\t%(message)s', datefmt='%d.%m.%Y %H:%M:%S') article = downloader.loadArticle('https://day.kyiv.ua/uk/article/media/mafiya-bezsmertna-y-na-ekrani') print(article.info()) """ logging.basicConfig(filename='downloader_day_debug.log',level=logging.DEBUG) #downloader.getNewsForNumber(35,1997) article = downloader.loadArticle('https://day.kyiv.ua/uk/article/media/mafiya-bezsmertna-y-na-ekrani') print(article.info()) """ class Article(object): def __init__(self, url, j): self.url = '' if url is not None: self.url = url self.dtStr = '' self.timeStr = '00:00' val = j[0] if val is not None: self.dtStr = val self.timeStr = val[-5:] self.title = '' val = j[1] if val is not None: if isinstance(val, str): self.title = downloader_common.relpaceHtmlEntities(val) elif isinstance(val, list): self.title = downloader_common.relpaceHtmlEntities(val[0]) self.body = list() val = j[2] if val is not None: locText = '' if isinstance(val, str): locText = val elif isinstance(val, list): locText = '\n'.join(val) text = locText.strip() # trim #remove HTML comments #text = re.sub("(<!--.*?-->)", "", text, flags=re.MULTILINE|re.DOTALL) #remove empty lines for line in text.split('\n'): proLine = downloader_common.relpaceHtmlEntities(line.strip()) if len(proLine) > 0: self.body.append(proLine) self.summary = '' if len(j) > 3: val = j[3] if val is not None: self.summary = val.strip() self.author = '' if len(j) > 4: val = j[4] if val is not None: self.author = val.strip() def info(self): print('dtStr: '+self.dtStr) print('timeStr: '+self.timeStr) print('url: '+self.url) print('title: '+str(self.title)) print('author: '+str(self.author)) print('summary: '+str(self.summary)) print('body: ' + "\n".join(self.body)) def fb2(self): ret = '<section><title><p>' + downloader_common.escapeXml(self.title) + '</p></title>' if len(self.summary) > 0: ret += '\n <p><strong>' + downloader_common.escapeXml(self.summary) + '</strong></p>' if len(self.author) > 0: ret += '\n <p>' + downloader_common.escapeXml(self.author) + '</p>' if '00:00' != self.timeStr: ret += '\n <p>' + self.timeStr + '</p>' ret += '\n <empty-line/>' for line in self.body: ret += '\n <p>' + downloader_common.escapeXml(line) + '</p>' ret += '\n</section>' return ret class Downloader(object): def __init__(self): self.baseUrl = 'https://day.kyiv.ua' self.getLinksCmd = downloader_common.XIDEL_CMD + ' --xpath \'//div[@class="view-content"]//div[@class="taxrow"]//@href\'' self.getNumDateCmd = downloader_common.XIDEL_CMD + ' --xpath \'(//div[@class="view-content"]//div[@class="taxrow"]//div[@class="date"])[1]\'' self.numDate = None self.dict = {" січня, ":".01.", " лютого, ":".02.", " березня, ":".03.", " квітня, ":".04.", " травня, ":".05.", " червня, ":".06.", " липня, ":".07.", " серпня, ":".08.", " вересня, ":".09.", " жовтня, ":".10.", " листопада, ":".11.", " грудня, ":".12."} #xidel "https://day.kyiv.ua/uk/arhiv/no35-1997?page=0" --xpath '//div[@class="view-content"]//div[@class="taxrow"]//@href' #xidel "https://day.kyiv.ua/uk/arhiv/no35-1997?page=0" --xpath '//div[@class="view-content"]//div[@class="taxrow"]//div[@class="date"]' def getNewsForNumber(self, num, year): self.numUrl = '/uk/arhiv/no%d-%d' % (num,year) url = self.baseUrl + self.numUrl + '?page=0' print('url: ' +url) articleList = list() downloadedUrls = set() cmd = self.getNumDateCmd.format(url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) result = p.communicate()[0].decode('utf-8') result = result[:10].strip() # date in format mm/dd/yyyy urlNum = 0 while len(result) < 1 and urlNum < 3: #no such URL or no articles self.numUrl = '/uk/arhiv/no%d-%d-%d' % (num,year,urlNum) url = self.baseUrl + self.numUrl + '?page=0' print('url: ' +url) articleList = list() downloadedUrls = set() cmd = self.getNumDateCmd.format(url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) result = p.communicate()[0].decode('utf-8') result = result[:10].strip() # date in format mm/dd/yyyy urlNum += 1 #several nums in one newspaper deltaNum = 1 while len(result) < 1 and deltaNum < 3: #no such URL or no articles self.numUrl = '/uk/arhiv/no%d-%d-%d' % (num,num+deltaNum,year) url = self.baseUrl + self.numUrl + '?page=0' print('url: ' +url) articleList = list() downloadedUrls = set() cmd = self.getNumDateCmd.format(url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) result = p.communicate()[0].decode('utf-8') result = result[:10].strip() # date in format dd/mm/yyyy deltaNum += 1 if len(result) < 1: #no such URL or no articles return None # get date from result self.numDate = datetime.datetime.strptime(result, '%d.%m.%Y').date() for pageNum in range(0, 3): # replace {0} with url url = self.baseUrl + self.numUrl + '?page='+str(pageNum) cmd = self.getLinksCmd.format(url) print('url: ' +url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) for ln in p.stdout: line = ln.decode('utf-8').strip() articleUrl = self.baseUrl + line if articleUrl not in downloadedUrls: print ('load article: ' + articleUrl) try: while True: retry = False article = self.loadArticle(articleUrl) if article is not None: bAddToList = True text = " ".join(article.body) text = text.strip() if len(text) > 0: bAddToList = True else: if line in ['']: bAddToList = False logging.error("IGNORE: Article is empty. URL: "+ articleUrl) else: bAddToList = False logging.error("Article is empty. URL: "+ articleUrl) article.info() #sys.exit("Article is empty. URL: "+ line) logging.error("IGNORE: Article is empty. URL: "+ articleUrl) if bAddToList: if len(article.body) == 1: logging.warning("Article (length = "+str(len(text))+") has one paragraph. URL: "+ articleUrl) logging.debug("Article added to list. URL: "+ articleUrl) articleList.append(article) downloadedUrls.add(articleUrl) else: #exit logging.warning("Article can not be loaded from URL: "+ articleUrl) #try to fix url if not retry : break except (SystemExit, KeyboardInterrupt): raise except: exc_type, exc_value, exc_traceback = sys.exc_info() print ("Unexpected error: ", exc_type) traceback.print_exception(exc_type, exc_value, exc_traceback) else: print ('ignore url (already loaded): '+ articleUrl) #articleList.reverse() return sorted(articleList, key=lambda x: x.timeStr) def getNewsForUrl(self, noUrlPart): self.numUrl = '/uk/arhiv/%s' % (noUrlPart) url = self.baseUrl + self.numUrl + '?page=0' print('url: ' +url) articleList = list() downloadedUrls = set() cmd = self.getNumDateCmd.format(url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) result = p.communicate()[0].decode('utf-8') result = result[:10].strip() # date in format mm/dd/yyyy if len(result) < 1: #no such URL or no articles return None # get date from result self.numDate = datetime.datetime.strptime(result, '%d.%m.%Y').date() for pageNum in range(0, 3): # replace {0} with url url = self.baseUrl + self.numUrl + '?page='+str(pageNum) cmd = self.getLinksCmd.format(url) print('url: ' +url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) for ln in p.stdout: line = ln.decode('utf-8').strip() articleUrl = self.baseUrl + line if articleUrl not in downloadedUrls: print ('load article: ' + articleUrl) try: while True: retry = False article = self.loadArticle(articleUrl) if article is not None: bAddToList = True text = " ".join(article.body) text = text.strip() if len(text) > 0: bAddToList = True else: if line in ['']: bAddToList = False logging.error("IGNORE: Article is empty. URL: "+ articleUrl) else: bAddToList = False logging.error("Article is empty. URL: "+ articleUrl) article.info() #sys.exit("Article is empty. URL: "+ line) logging.error("IGNORE: Article is empty. URL: "+ articleUrl) if bAddToList: if len(article.body) == 1: logging.warning("Article (length = "+str(len(text))+") has one paragraph. URL: "+ articleUrl) logging.debug("Article added to list. URL: "+ articleUrl) articleList.append(article) downloadedUrls.add(articleUrl) else: #exit logging.warning("Article can not be loaded from URL: "+ articleUrl) #try to fix url if not retry : break except (SystemExit, KeyboardInterrupt): raise except: exc_type, exc_value, exc_traceback = sys.exc_info() print ("Unexpected error: ", exc_type) traceback.print_exception(exc_type, exc_value, exc_traceback) else: print ('ignore url (already loaded): '+ articleUrl) articleList.reverse() return articleList def loadArticle(self, url): cmd = (downloader_common.XIDEL_CMD.format(url) + ' --xpath \'//div[@class="pagetop"]//div[@class="node_date"]\'' #date time ' --xpath \'//h1[@class="title"]\'' #title ' --xpath \'//div[@class="pagetop"]//div[@class="field field-name-body field-type-text-with-summary field-label-hidden"]//div[@class="field-item even"]/p\'' #article text ' --xpath \'//div[@class="pagetop"]//div[@class="field field-name-field-subtitle field-type-text field-label-hidden"]\'' #article summary ' --xpath \'//div[@class="pagetop"]//div[@class="field field-name-field-op-author field-type-node-reference field-label-hidden"]\'' #author ' --output-format=json-wrapped') #output as json #xidel https://day.kyiv.ua/uk/article/cuspilstvo/pidlitkove-zlochinne-ugrupovannya-zatrimano-na-volini -q --xpath '//div[@class="pagetop"]//div[@class="node_date"]' #xidel https://day.kyiv.ua/uk/article/den-ukrayini-14 -q --xpath '//div[@class="pagetop"]//div[@class="field field-name-field-op-author field-type-node-reference field-label-hidden"]' #xidel https://day.kyiv.ua/uk/article/den-ukrayini-14 -q --xpath '//div[@class="pagetop"]//div[@class="field field-name-body field-type-text-with-summary field-label-hidden"]//div[@class="field-item even"]/p' #print('cmd: '+cmd) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) result = p.communicate()[0].decode('utf-8') jsonArt = json.loads(result) article = None try: if len(jsonArt) > 0 : text = '' if jsonArt[2] is not None : text = " ".join(jsonArt[2]) text = text.strip() if len(text) == 0: #load as html cmdContent = (downloader_common.XIDEL_CMD.format(url) + #' --xpath \'//div[@class="pagetop"]//div[@class="field field-name-body field-type-text-with-summary field-label-hidden"]//div[@class="field-item even"]\'' #article text ' --xpath \'//div[@class="pagetop"]//div[@class="field-items"]\'' #article text ' --output-format=html') #output as html jsonArt[2] = self.loadArticleTextFromHtml(cmdContent) article = Article(url, jsonArt) else: logging.warning("Nothing can be load from: "+url) print("Nothing can be load from: "+url) return None except: exc_type, exc_value, exc_traceback = sys.exc_info() print ("Unexpected error: ", exc_type, "In article ", result) traceback.print_exception(exc_type, exc_value, exc_traceback) return article def loadArticleTextFromHtml(self, xidelCmd): p = subprocess.Popen(xidelCmd, shell=True, stdout=subprocess.PIPE) result = p.communicate()[0].decode('utf-8') logging.debug(">> loadArticleTextFromHtml()") logging.debug(result) #print(result) txt = result.replace('<br>', '[br]').replace('</br>', '').replace('<p>', '[br]').replace('</p>', '').replace('<br />', '[br]') txt = txt.replace('<BR>', '[br]').replace('</BR>', '').replace('<P>', '[br]').replace('</P>', '').replace('<BR />', '[br]') txt = txt.replace('&amp;#', '&#') logging.debug(">> replace with [br]") logging.debug(txt) soup = BeautifulSoup(txt, 'html.parser') #remove scripts [s.extract() for s in soup('script')] logging.debug(">> soap.text") logging.debug(soup.get_text()) return soup.get_text().replace('[br]', '\n') def fb2ForUrl(self, noUrlPart): today = datetime.date.today() self.numUrl = '/uk/arhiv/%s' % (noUrlPart) articleList = self.getNewsForUrl(noUrlPart) url = self.baseUrl + self.numUrl if articleList is None: return '' ret = '<?xml version="1.0" encoding="utf-8"?>' ret += '\n<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">' ret += '\n<description>' ret += '\n <title-info>' ret += '\n <genre>nonfiction</genre>' ret += '\n <author><last-name>Газета «День»</last-name></author>' if self.numDate is not None: ret += '\n <book-title>Газета «День» № ' + noUrlPart + ' від ' + self.numDate.strftime('%d.%m.%Y') + '</book-title>' ret += '\n <date>' + str(self.numDate) + '</date>' else: ret += '\n <book-title>Газета «День» № ' + noUrlPart + '</book-title>' ret += '\n <date></date>' ret += '\n <lang>uk</lang>' ret += '\n </title-info>' ret += '\n <document-info>' ret += '\n <author><nickname>V.Vlad</nickname></author>' ret += '\n <date value="' + str(today) + '">' + str(today) + '</date>' ret += '\n <version>1.0</version>' ret += '\n <src-url>' + url + '</src-url>' ret += '\n </document-info>' ret += '\n</description>' ret += '\n<body>' ret += self.articleListToStr(articleList) ret += '\n</body>' ret += '\n</FictionBook>' return ret def fb2(self, num, year): today = datetime.date.today() self.numUrl = f'/uk/arhiv/no{num}-{year}' articleList = self.getNewsForNumber(num, year) url = self.baseUrl + self.numUrl if articleList is None: return '' ret = '<?xml version="1.0" encoding="utf-8"?>' ret += '\n<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">' ret += '\n<description>' ret += '\n <title-info>' ret += '\n <genre>nonfiction</genre>' ret += '\n <author><last-name>Газета «День»</last-name></author>' if self.numDate is not None: ret += '\n <book-title>Газета «День» № ' + str(num) + ' від ' + self.numDate.strftime('%d.%m.%Y') + '</book-title>' ret += '\n <date>' + str(self.numDate) + '</date>' else: ret += '\n <book-title>Газета «День» № ' + str(num) + ', ' + str(year) + '</book-title>' ret += '\n <date></date>' ret += '\n <lang>uk</lang>' ret += '\n </title-info>' ret += '\n <document-info>' ret += '\n <author><nickname>V.Vlad</nickname></author>' ret += '\n <date value="' + str(today) + '">' + str(today) + '</date>' ret += '\n <version>1.0</version>' ret += '\n <src-url>' + url + '</src-url>' ret += '\n </document-info>' ret += '\n</description>' ret += '\n<body>' ret += self.articleListToStr(articleList) ret += '\n</body>' ret += '\n</FictionBook>' return ret def articleListToStr(self, articleList): ret = [] for article in articleList: try: ret.append('\n') ret.append(article.fb2()) except: exc_type, exc_value, exc_traceback = sys.exc_info() print ("Unexpected error: ", exc_type) traceback.print_exception(exc_type, exc_value, exc_traceback) return ''.join(ret) def getCurrentIssueNr(self): curIssueNr = -1 url = self.baseUrl + '/uk/newspaper' curIssueCmd = downloader_common.XIDEL_CMD + ' --xpath \'//div[@class="region-inner region-content-inner"]//div[@class="view-content"]//h3//a/@href\'' cmd = curIssueCmd.format(url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) for ln in p.stdout: line = ln.decode('utf-8').strip() if len(line) > 0 and line.startswith('/uk/arhiv/no'): curIssueNr = int(''.join(ele for ele in line.split('-')[0] if ele.isdigit())) return curIssueNr def getLastDownloadedIssueNr(self): now = datetime.datetime.now() curYearFolder = downloader_common.rootPath+'/day/'+str(now.year) prevYearFolder = downloader_common.rootPath+'/day/'+str(now.year-1) lastIssueFolder = downloader_common.rootPath+'/day' if os.path.isdir(curYearFolder): #folder for current year exists lastIssueFolder = curYearFolder elif os.path.isdir(prevYearFolder): #folder for previous year exists: lastIssueFolder = prevYearFolder else: return 0 lastIssueNr = 0 for issueFile in os.listdir(lastIssueFolder): if issueFile.endswith(".fb2"): curIssueNr = int(''.join(ele for ele in issueFile[:-3] if ele.isdigit())) if curIssueNr > lastIssueNr: lastIssueNr = curIssueNr return lastIssueNr def load(self): # get last downloaded number num = self.getLastDownloadedIssueNr() + 1 currentIssueNum = self.getCurrentIssueNr() print ("download issues from {0} to {1}".format(num, currentIssueNum)) logging.info("download issues from {0} to {1}".format(num, currentIssueNum)) now = datetime.datetime.now() year = now.year #for num in strNumList while (num <= currentIssueNum): #253 try: content = self.fb2(num, year) if len(content) > 0: with open((downloader_common.rootPath+'/day/'+"%d/day_%03d.fb2" % (year, num)), "w") as fb2_file: fb2_file.write(content) else: print("No content for num %d, year %d." % (num, year)) logging.warning("No content for num %d, year %d." % (num, year)) except KeyboardInterrupt: sys.exit("Download interrrupted.") except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) sys.exit("Unexpected error: "+ exc_type) num += 1 logging.info("Job completed") if __name__ == '__main__': runByDate() #test()
import pdb import sys, traceback import datetime import subprocess import json import re import logging import os.path from bs4 import BeautifulSoup import stats import downloader_common def run(): downloader = Downloader() logging.basicConfig(filename='downloader_day.log',level=logging.INFO, format='%(asctime)s %(levelname)s\t%(module)s\t%(message)s', datefmt='%d.%m.%Y %H:%M:%S') # get last downloaded number num = downloader.getLastDownloadedIssueNr() + 1 # get current issue number currentIssueNum = downloader.getCurrentIssueNr() print ("download issues from {0} to {1}".format(num, currentIssueNum)) logging.info("download issues from {0} to {1}".format(num, currentIssueNum)) now = datetime.datetime.now() year = now.year #for num in strNumList while (num <= currentIssueNum): #253 try: fname = ("%d/day_%03d.fb2" % (year, num)) if os.path.isfile(fname): print ("File %s exists, get next." % fname) else: content = downloader.fb2(num, year) if len(content) > 0: with open((downloader_common.rootPath+'/day/'+"%d/day_%03d.fb2" % (year, num)), "w") as fb2_file: fb2_file.write(content) else: print("No content for num %d, year %d." % (num, year)) logging.warning("No content for num %d, year %d." % (num, year)) except KeyboardInterrupt: sys.exit("Download interrupted.") except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) sys.exit("Unexpected error: "+ exc_type) num += 1 def runByNoWithParams(): downloader = Downloader() #2017 96 154 #year = int(sys.argv[1]) #num = int(sys.argv[2]) #lastNum = int(sys.argv[3])+1 year = 2022 num = 1 lastNum = 13 #while (num < lastNum): #253 # strNumList.append(str(num)) # num += 1 #strNumList = ['238-240','235-236','230-231','225-226','220-221','215-216','210-211','205-206','200-201','195-196','190-191','185-186', # '181-182','176-177','171-172','166-167','161-162','156-157','151-152','148-149','143-144','138-139','133-134'] logging.basicConfig(filename='downloader_day_'+str(year)+'.log',level=logging.INFO, format='%(asctime)s %(levelname)s\t%(module)s\t%(message)s', datefmt='%d.%m.%Y %H:%M:%S') #for num in strNumList while (num < lastNum): try: fname = ("%d/day_%03d.fb2" % (year, num)) if os.path.isfile(fname): print ("File %s exists, get next." % fname) else: content = downloader.fb2(num, year) if len(content) > 0: fileDate = str(num) if downloader.numDate is not None: fileDate = str(downloader.numDate) with open(downloader_common.rootPath+f'/day/{year}/day_{fileDate}.fb2', "w") as fb2_file: fb2_file.write(content) else: print("No content for num %d, year %d." % (num, year)) logging.warning("No content for num %d, year %d." % (num, year)) except KeyboardInterrupt: sys.exit("Download interrupted.") except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) sys.exit("Unexpected error: "+ exc_type) num += 1 def runByDate(): downloader = Downloader() ukrMonthDict = {1:"sichnya", 2:"lyutogo", 3:"bereznya", 4:"kvitnya", 5:"travnya", 6:"chervnya", 7:"lypnya", 8:"serpnya", 9:"veresnya", 10:"zhovtnya", 11:"lystopada", 12:"grudnya"} # 31-sichnya-2022 # 24-lyutogo-2022 # 31-bereznya-2022 # 27-kvitnya-2022 # 28-lypnya-2021 # 30-serpnya-2021 # 28-veresnya-2021 # 27-zhovtnya-2021 # 29-lystopada-2021 # 30-grudnya-2021 start_date = datetime.date(2022, 1, 1) end_date = datetime.date(2022, 4, 25) cur_date = start_date logging.basicConfig(filename='downloader_day_'+str(start_date.year)+'.log',level=logging.INFO, format='%(asctime)s %(levelname)s\t%(module)s\t%(message)s', datefmt='%d.%m.%Y %H:%M:%S') #for num in strNumList while (cur_date < end_date): print(str(cur_date)) try: fileDate = cur_date.isoformat() fname = downloader_common.rootPath+f'/day/{cur_date.year}/day_{fileDate}.fb2' if os.path.isfile(fname): print ("File %s exists, get next." % fname) else: dateUrlPart = f'{cur_date.day}-{ukrMonthDict[cur_date.month]}-{cur_date.year}' content = downloader.fb2ForUrl(dateUrlPart) if len(content) > 0: with open(fname, "w") as fb2_file: fb2_file.write(content) else: print(f"No content for date {fileDate}") logging.warning(f"No content for date {fileDate}") except KeyboardInterrupt: sys.exit("Download interrupted.") except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) sys.exit("Unexpected error: "+ exc_type) cur_date += datetime.timedelta(days=1) def runUrl(): downloader = Downloader() logging.basicConfig(filename='downloader_day.log',level=logging.INFO, format='%(asctime)s %(levelname)s\t%(module)s\t%(message)s', datefmt='%d.%m.%Y %H:%M:%S') noUrlPart = '28-lypnya-2021' content = downloader.fb2ForUrl(noUrlPart) if len(content) > 0: with open(("2021/%s.fb2" % (noUrlPart)), "w") as fb2_file: fb2_file.write(content) else: print("No content for noUrlPart %s." % (noUrlPart)) logging.warning("No content for noUrlPart %s." % (noUrlPart)) def test(): downloader = Downloader() logging.basicConfig(filename='downloader_day_test.log',level=logging.INFO, format='%(asctime)s %(levelname)s\t%(module)s\t%(message)s', datefmt='%d.%m.%Y %H:%M:%S') article = downloader.loadArticle('https://day.kyiv.ua/uk/article/media/mafiya-bezsmertna-y-na-ekrani') print(article.info()) """ logging.basicConfig(filename='downloader_day_debug.log',level=logging.DEBUG) #downloader.getNewsForNumber(35,1997) article = downloader.loadArticle('https://day.kyiv.ua/uk/article/media/mafiya-bezsmertna-y-na-ekrani') print(article.info()) """ class Article(object): def __init__(self, url, j): self.url = '' if url is not None: self.url = url self.dtStr = '' self.timeStr = '00:00' val = j[0] if val is not None: self.dtStr = val self.timeStr = val[-5:] self.title = '' val = j[1] if val is not None: if isinstance(val, str): self.title = downloader_common.relpaceHtmlEntities(val) elif isinstance(val, list): self.title = downloader_common.relpaceHtmlEntities(val[0]) self.body = list() val = j[2] if val is not None: locText = '' if isinstance(val, str): locText = val elif isinstance(val, list): locText = '\n'.join(val) text = locText.strip() # trim #remove HTML comments #text = re.sub("(<!--.*?-->)", "", text, flags=re.MULTILINE|re.DOTALL) #remove empty lines for line in text.split('\n'): proLine = downloader_common.relpaceHtmlEntities(line.strip()) if len(proLine) > 0: self.body.append(proLine) self.summary = '' if len(j) > 3: val = j[3] if val is not None: self.summary = val.strip() self.author = '' if len(j) > 4: val = j[4] if val is not None: self.author = val.strip() def info(self): print('dtStr: '+self.dtStr) print('timeStr: '+self.timeStr) print('url: '+self.url) print('title: '+str(self.title)) print('author: '+str(self.author)) print('summary: '+str(self.summary)) print('body: ' + "\n".join(self.body)) def fb2(self): ret = '<section><title><p>' + downloader_common.escapeXml(self.title) + '</p></title>' if len(self.summary) > 0: ret += '\n <p><strong>' + downloader_common.escapeXml(self.summary) + '</strong></p>' if len(self.author) > 0: ret += '\n <p>' + downloader_common.escapeXml(self.author) + '</p>' if '00:00' != self.timeStr: ret += '\n <p>' + self.timeStr + '</p>' ret += '\n <empty-line/>' for line in self.body: ret += '\n <p>' + downloader_common.escapeXml(line) + '</p>' ret += '\n</section>' return ret class Downloader(object): def __init__(self): self.baseUrl = 'https://day.kyiv.ua' self.getLinksCmd = downloader_common.XIDEL_CMD + ' --xpath \'//div[@class="view-content"]//div[@class="taxrow"]//@href\'' self.getNumDateCmd = downloader_common.XIDEL_CMD + ' --xpath \'(//div[@class="view-content"]//div[@class="taxrow"]//div[@class="date"])[1]\'' self.numDate = None self.dict = {" січня, ":".01.", " лютого, ":".02.", " березня, ":".03.", " квітня, ":".04.", " травня, ":".05.", " червня, ":".06.", " липня, ":".07.", " серпня, ":".08.", " вересня, ":".09.", " жовтня, ":".10.", " листопада, ":".11.", " грудня, ":".12."} #xidel "https://day.kyiv.ua/uk/arhiv/no35-1997?page=0" --xpath '//div[@class="view-content"]//div[@class="taxrow"]//@href' #xidel "https://day.kyiv.ua/uk/arhiv/no35-1997?page=0" --xpath '//div[@class="view-content"]//div[@class="taxrow"]//div[@class="date"]' def getNewsForNumber(self, num, year): self.numUrl = '/uk/arhiv/no%d-%d' % (num,year) url = self.baseUrl + self.numUrl + '?page=0' print('url: ' +url) articleList = list() downloadedUrls = set() cmd = self.getNumDateCmd.format(url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) result = p.communicate()[0].decode('utf-8') result = result[:10].strip() # date in format mm/dd/yyyy urlNum = 0 while len(result) < 1 and urlNum < 3: #no such URL or no articles self.numUrl = '/uk/arhiv/no%d-%d-%d' % (num,year,urlNum) url = self.baseUrl + self.numUrl + '?page=0' print('url: ' +url) articleList = list() downloadedUrls = set() cmd = self.getNumDateCmd.format(url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) result = p.communicate()[0].decode('utf-8') result = result[:10].strip() # date in format mm/dd/yyyy urlNum += 1 #several nums in one newspaper deltaNum = 1 while len(result) < 1 and deltaNum < 3: #no such URL or no articles self.numUrl = '/uk/arhiv/no%d-%d-%d' % (num,num+deltaNum,year) url = self.baseUrl + self.numUrl + '?page=0' print('url: ' +url) articleList = list() downloadedUrls = set() cmd = self.getNumDateCmd.format(url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) result = p.communicate()[0].decode('utf-8') result = result[:10].strip() # date in format dd/mm/yyyy deltaNum += 1 if len(result) < 1: #no such URL or no articles return None # get date from result self.numDate = datetime.datetime.strptime(result, '%d.%m.%Y').date() for pageNum in range(0, 3): # replace {0} with url url = self.baseUrl + self.numUrl + '?page='+str(pageNum) cmd = self.getLinksCmd.format(url) print('url: ' +url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) for ln in p.stdout: line = ln.decode('utf-8').strip() articleUrl = self.baseUrl + line if articleUrl not in downloadedUrls: print ('load article: ' + articleUrl) try: while True: retry = False article = self.loadArticle(articleUrl) if article is not None: bAddToList = True text = " ".join(article.body) text = text.strip() if len(text) > 0: bAddToList = True else: if line in ['']: bAddToList = False logging.error("IGNORE: Article is empty. URL: "+ articleUrl) else: bAddToList = False logging.error("Article is empty. URL: "+ articleUrl) article.info() #sys.exit("Article is empty. URL: "+ line) logging.error("IGNORE: Article is empty. URL: "+ articleUrl) if bAddToList: if len(article.body) == 1: logging.warning("Article (length = "+str(len(text))+") has one paragraph. URL: "+ articleUrl) logging.debug("Article added to list. URL: "+ articleUrl) articleList.append(article) downloadedUrls.add(articleUrl) else: #exit logging.warning("Article can not be loaded from URL: "+ articleUrl) #try to fix url if not retry : break except (SystemExit, KeyboardInterrupt): raise except: exc_type, exc_value, exc_traceback = sys.exc_info() print ("Unexpected error: ", exc_type) traceback.print_exception(exc_type, exc_value, exc_traceback) else: print ('ignore url (already loaded): '+ articleUrl) #articleList.reverse() return sorted(articleList, key=lambda x: x.timeStr) def getNewsForUrl(self, noUrlPart): self.numUrl = '/uk/arhiv/%s' % (noUrlPart) url = self.baseUrl + self.numUrl + '?page=0' print('url: ' +url) articleList = list() downloadedUrls = set() cmd = self.getNumDateCmd.format(url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) result = p.communicate()[0].decode('utf-8') result = result[:10].strip() # date in format mm/dd/yyyy if len(result) < 1: #no such URL or no articles return None # get date from result self.numDate = datetime.datetime.strptime(result, '%d.%m.%Y').date() for pageNum in range(0, 3): # replace {0} with url url = self.baseUrl + self.numUrl + '?page='+str(pageNum) cmd = self.getLinksCmd.format(url) print('url: ' +url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) for ln in p.stdout: line = ln.decode('utf-8').strip() articleUrl = self.baseUrl + line if articleUrl not in downloadedUrls: print ('load article: ' + articleUrl) try: while True: retry = False article = self.loadArticle(articleUrl) if article is not None: bAddToList = True text = " ".join(article.body) text = text.strip() if len(text) > 0: bAddToList = True else: if line in ['']: bAddToList = False logging.error("IGNORE: Article is empty. URL: "+ articleUrl) else: bAddToList = False logging.error("Article is empty. URL: "+ articleUrl) article.info() #sys.exit("Article is empty. URL: "+ line) logging.error("IGNORE: Article is empty. URL: "+ articleUrl) if bAddToList: if len(article.body) == 1: logging.warning("Article (length = "+str(len(text))+") has one paragraph. URL: "+ articleUrl) logging.debug("Article added to list. URL: "+ articleUrl) articleList.append(article) downloadedUrls.add(articleUrl) else: #exit logging.warning("Article can not be loaded from URL: "+ articleUrl) #try to fix url if not retry : break except (SystemExit, KeyboardInterrupt): raise except: exc_type, exc_value, exc_traceback = sys.exc_info() print ("Unexpected error: ", exc_type) traceback.print_exception(exc_type, exc_value, exc_traceback) else: print ('ignore url (already loaded): '+ articleUrl) articleList.reverse() return articleList def loadArticle(self, url): cmd = (downloader_common.XIDEL_CMD.format(url) + ' --xpath \'//div[@class="pagetop"]//div[@class="node_date"]\'' #date time ' --xpath \'//h1[@class="title"]\'' #title ' --xpath \'//div[@class="pagetop"]//div[@class="field field-name-body field-type-text-with-summary field-label-hidden"]//div[@class="field-item even"]/p\'' #article text ' --xpath \'//div[@class="pagetop"]//div[@class="field field-name-field-subtitle field-type-text field-label-hidden"]\'' #article summary ' --xpath \'//div[@class="pagetop"]//div[@class="field field-name-field-op-author field-type-node-reference field-label-hidden"]\'' #author ' --output-format=json-wrapped') #output as json #xidel https://day.kyiv.ua/uk/article/cuspilstvo/pidlitkove-zlochinne-ugrupovannya-zatrimano-na-volini -q --xpath '//div[@class="pagetop"]//div[@class="node_date"]' #xidel https://day.kyiv.ua/uk/article/den-ukrayini-14 -q --xpath '//div[@class="pagetop"]//div[@class="field field-name-field-op-author field-type-node-reference field-label-hidden"]' #xidel https://day.kyiv.ua/uk/article/den-ukrayini-14 -q --xpath '//div[@class="pagetop"]//div[@class="field field-name-body field-type-text-with-summary field-label-hidden"]//div[@class="field-item even"]/p' #print('cmd: '+cmd) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) result = p.communicate()[0].decode('utf-8') jsonArt = json.loads(result) article = None try: if len(jsonArt) > 0 : text = '' if jsonArt[2] is not None : text = " ".join(jsonArt[2]) text = text.strip() if len(text) == 0: #load as html cmdContent = (downloader_common.XIDEL_CMD.format(url) + #' --xpath \'//div[@class="pagetop"]//div[@class="field field-name-body field-type-text-with-summary field-label-hidden"]//div[@class="field-item even"]\'' #article text ' --xpath \'//div[@class="pagetop"]//div[@class="field-items"]\'' #article text ' --output-format=html') #output as html jsonArt[2] = self.loadArticleTextFromHtml(cmdContent) article = Article(url, jsonArt) else: logging.warning("Nothing can be load from: "+url) print("Nothing can be load from: "+url) return None except: exc_type, exc_value, exc_traceback = sys.exc_info() print ("Unexpected error: ", exc_type, "In article ", result) traceback.print_exception(exc_type, exc_value, exc_traceback) return article def loadArticleTextFromHtml(self, xidelCmd): p = subprocess.Popen(xidelCmd, shell=True, stdout=subprocess.PIPE) result = p.communicate()[0].decode('utf-8') logging.debug(">> loadArticleTextFromHtml()") logging.debug(result) #print(result) txt = result.replace('<br>', '[br]').replace('</br>', '').replace('<p>', '[br]').replace('</p>', '').replace('<br />', '[br]') txt = txt.replace('<BR>', '[br]').replace('</BR>', '').replace('<P>', '[br]').replace('</P>', '').replace('<BR />', '[br]') txt = txt.replace('&amp;#', '&#') logging.debug(">> replace with [br]") logging.debug(txt) soup = BeautifulSoup(txt, 'html.parser') #remove scripts [s.extract() for s in soup('script')] logging.debug(">> soap.text") logging.debug(soup.get_text()) return soup.get_text().replace('[br]', '\n') def fb2ForUrl(self, noUrlPart): today = datetime.date.today() self.numUrl = '/uk/arhiv/%s' % (noUrlPart) articleList = self.getNewsForUrl(noUrlPart) url = self.baseUrl + self.numUrl if articleList is None: return '' ret = '<?xml version="1.0" encoding="utf-8"?>' ret += '\n<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">' ret += '\n<description>' ret += '\n <title-info>' ret += '\n <genre>nonfiction</genre>' ret += '\n <author><last-name>Газета «День»</last-name></author>' if self.numDate is not None: ret += '\n <book-title>Газета «День» № ' + noUrlPart + ' від ' + self.numDate.strftime('%d.%m.%Y') + '</book-title>' ret += '\n <date>' + str(self.numDate) + '</date>' else: ret += '\n <book-title>Газета «День» № ' + noUrlPart + '</book-title>' ret += '\n <date></date>' ret += '\n <lang>uk</lang>' ret += '\n </title-info>' ret += '\n <document-info>' ret += '\n <author><nickname>V.Vlad</nickname></author>' ret += '\n <date value="' + str(today) + '">' + str(today) + '</date>' ret += '\n <version>1.0</version>' ret += '\n <src-url>' + url + '</src-url>' ret += '\n </document-info>' ret += '\n</description>' ret += '\n<body>' ret += self.articleListToStr(articleList) ret += '\n</body>' ret += '\n</FictionBook>' return ret def fb2(self, num, year): today = datetime.date.today() self.numUrl = f'/uk/arhiv/no{num}-{year}' articleList = self.getNewsForNumber(num, year) url = self.baseUrl + self.numUrl if articleList is None: return '' ret = '<?xml version="1.0" encoding="utf-8"?>' ret += '\n<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">' ret += '\n<description>' ret += '\n <title-info>' ret += '\n <genre>nonfiction</genre>' ret += '\n <author><last-name>Газета «День»</last-name></author>' if self.numDate is not None: ret += '\n <book-title>Газета «День» № ' + str(num) + ' від ' + self.numDate.strftime('%d.%m.%Y') + '</book-title>' ret += '\n <date>' + str(self.numDate) + '</date>' else: ret += '\n <book-title>Газета «День» № ' + str(num) + ', ' + str(year) + '</book-title>' ret += '\n <date></date>' ret += '\n <lang>uk</lang>' ret += '\n </title-info>' ret += '\n <document-info>' ret += '\n <author><nickname>V.Vlad</nickname></author>' ret += '\n <date value="' + str(today) + '">' + str(today) + '</date>' ret += '\n <version>1.0</version>' ret += '\n <src-url>' + url + '</src-url>' ret += '\n </document-info>' ret += '\n</description>' ret += '\n<body>' ret += self.articleListToStr(articleList) ret += '\n</body>' ret += '\n</FictionBook>' return ret def articleListToStr(self, articleList): ret = [] for article in articleList: try: ret.append('\n') ret.append(article.fb2()) except: exc_type, exc_value, exc_traceback = sys.exc_info() print ("Unexpected error: ", exc_type) traceback.print_exception(exc_type, exc_value, exc_traceback) return ''.join(ret) def getCurrentIssueNr(self): curIssueNr = -1 url = self.baseUrl + '/uk/newspaper' curIssueCmd = downloader_common.XIDEL_CMD + ' --xpath \'//div[@class="region-inner region-content-inner"]//div[@class="view-content"]//h3//a/@href\'' cmd = curIssueCmd.format(url) p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) for ln in p.stdout: line = ln.decode('utf-8').strip() if len(line) > 0 and line.startswith('/uk/arhiv/no'): curIssueNr = int(''.join(ele for ele in line.split('-')[0] if ele.isdigit())) return curIssueNr def getLastDownloadedIssueNr(self): now = datetime.datetime.now() curYearFolder = downloader_common.rootPath+'/day/'+str(now.year) prevYearFolder = downloader_common.rootPath+'/day/'+str(now.year-1) lastIssueFolder = downloader_common.rootPath+'/day' if os.path.isdir(curYearFolder): #folder for current year exists lastIssueFolder = curYearFolder elif os.path.isdir(prevYearFolder): #folder for previous year exists: lastIssueFolder = prevYearFolder else: return 0 lastIssueNr = 0 for issueFile in os.listdir(lastIssueFolder): if issueFile.endswith(".fb2"): curIssueNr = int(''.join(ele for ele in issueFile[:-3] if ele.isdigit())) if curIssueNr > lastIssueNr: lastIssueNr = curIssueNr return lastIssueNr def load(self): # get last downloaded number num = self.getLastDownloadedIssueNr() + 1 currentIssueNum = self.getCurrentIssueNr() print ("download issues from {0} to {1}".format(num, currentIssueNum)) logging.info("download issues from {0} to {1}".format(num, currentIssueNum)) now = datetime.datetime.now() year = now.year #for num in strNumList while (num <= currentIssueNum): #253 try: content = self.fb2(num, year) if len(content) > 0: with open((downloader_common.rootPath+'/day/'+"%d/day_%03d.fb2" % (year, num)), "w") as fb2_file: fb2_file.write(content) else: print("No content for num %d, year %d." % (num, year)) logging.warning("No content for num %d, year %d." % (num, year)) except KeyboardInterrupt: sys.exit("Download interrrupted.") except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback) sys.exit("Unexpected error: "+ exc_type) num += 1 logging.info("Job completed") if __name__ == '__main__': runByDate() #test()
en
0.309494
# get last downloaded number # get current issue number #for num in strNumList #253 #2017 96 154 #year = int(sys.argv[1]) #num = int(sys.argv[2]) #lastNum = int(sys.argv[3])+1 #while (num < lastNum): #253 # strNumList.append(str(num)) # num += 1 #strNumList = ['238-240','235-236','230-231','225-226','220-221','215-216','210-211','205-206','200-201','195-196','190-191','185-186', # '181-182','176-177','171-172','166-167','161-162','156-157','151-152','148-149','143-144','138-139','133-134'] #for num in strNumList # 31-sichnya-2022 # 24-lyutogo-2022 # 31-bereznya-2022 # 27-kvitnya-2022 # 28-lypnya-2021 # 30-serpnya-2021 # 28-veresnya-2021 # 27-zhovtnya-2021 # 29-lystopada-2021 # 30-grudnya-2021 #for num in strNumList logging.basicConfig(filename='downloader_day_debug.log',level=logging.DEBUG) #downloader.getNewsForNumber(35,1997) article = downloader.loadArticle('https://day.kyiv.ua/uk/article/media/mafiya-bezsmertna-y-na-ekrani') print(article.info()) # trim #remove HTML comments #text = re.sub("(<!--.*?-->)", "", text, flags=re.MULTILINE|re.DOTALL) #remove empty lines #xidel "https://day.kyiv.ua/uk/arhiv/no35-1997?page=0" --xpath '//div[@class="view-content"]//div[@class="taxrow"]//@href' #xidel "https://day.kyiv.ua/uk/arhiv/no35-1997?page=0" --xpath '//div[@class="view-content"]//div[@class="taxrow"]//div[@class="date"]' # date in format mm/dd/yyyy #no such URL or no articles # date in format mm/dd/yyyy #several nums in one newspaper #no such URL or no articles # date in format dd/mm/yyyy #no such URL or no articles # get date from result # replace {0} with url #sys.exit("Article is empty. URL: "+ line) #exit #try to fix url #articleList.reverse() # date in format mm/dd/yyyy #no such URL or no articles # get date from result # replace {0} with url #sys.exit("Article is empty. URL: "+ line) #exit #try to fix url #date time #title #article text #article summary #author #output as json #xidel https://day.kyiv.ua/uk/article/cuspilstvo/pidlitkove-zlochinne-ugrupovannya-zatrimano-na-volini -q --xpath '//div[@class="pagetop"]//div[@class="node_date"]' #xidel https://day.kyiv.ua/uk/article/den-ukrayini-14 -q --xpath '//div[@class="pagetop"]//div[@class="field field-name-field-op-author field-type-node-reference field-label-hidden"]' #xidel https://day.kyiv.ua/uk/article/den-ukrayini-14 -q --xpath '//div[@class="pagetop"]//div[@class="field field-name-body field-type-text-with-summary field-label-hidden"]//div[@class="field-item even"]/p' #print('cmd: '+cmd) #load as html #' --xpath \'//div[@class="pagetop"]//div[@class="field field-name-body field-type-text-with-summary field-label-hidden"]//div[@class="field-item even"]\'' #article text #article text #output as html #print(result) #', '&#') #remove scripts #folder for current year exists #folder for previous year exists: # get last downloaded number #for num in strNumList #253 #test()
2.689279
3
line.py
Mec-iS/linear-algebra
0
6628302
from vector import Vector class Line2D(object): """ Parametrization of a line. ~~~~~~~~~~~~~~~~~~~~~~~~~~ Definition: Ax = By = k Operation: find a basepoint and a direction vector to define a line """ __ROUNDING = 9 def __init__(self, normal_vector=None, const_term=None): # normal vector = [A, B] self.normal_vector = normal_vector \ if normal_vector is not None and not normal_vector.is_zero_vector \ else ValueError('line needs a normal vector and must be not a zero vector') if not self.normal_vector.__class__ == Vector: raise TypeError('normal vector must be of class Vector') self.term = self.k = const_term if const_term is not None else 0 self.A = self.normal_vector.coordinates[0] self.B = self.normal_vector.coordinates[1] def __str__(self): return str('Line with normal {} and basepoint ({})').format(str(self.normal), str(self.basepoint)) def __eq__(self, other): """ Two lines are the same line if a vector created by picking two random points from both is orthogonal to the normal vector. """ if not self.is_parallel(other): return False test_vector = Vector([self.basepoint, other.basepoint]) return test_vector.is_orthogonal(self.normal_vector) def __ne__(self, other): """ Two lines are not the same line. """ return not self.__eq__(other) def is_parallel(self, other): """ Two lines are parallel if their normal vectors are parallel. """ if other.__class__ != self.__class__: raise TypeError('can compare only two Lines') return self.normal_vector.is_parallel(other.normal_vector) @property def normal(self): return self.normal_vector @property def constant(self): return self.term @property def basepoint(self): return self.set_basepoint() def set_basepoint(self, rounding=__ROUNDING): if self.B != 0: # B != 0 so (0, k/B) is a base point return round(self.term / self.B, rounding) if self.A != 0: # A != 0 so (k/A, 0) is a base point return round(self.term / self.A, rounding) raise ValueError('normal vector cannot be the zero vector') @property def direction(self, rounding=__ROUNDING): return Vector([self.B, -self.A]) def intersection(self, other, rounding=__ROUNDING): """ Find intersection of more than two lines that are not parallel nor the same line. """ if other.__class__ != self.__class__: raise TypeError('can compare only two Lines') if self == other: raise ValueError('Lines have infinite points in common') if self.is_parallel(other): raise ValueError('Lines are parallel') denominator = round((self.A * other.B) - (self.B * other.A), rounding) numerator1 = round((other.B * self.k) - (self.B * other.k), rounding) numerator2 = round(-(other.A * self.k) + (self.A * other.k), rounding) return numerator1 / denominator, numerator2 / denominator def intersection_multi(self, other, rounding=__ROUNDING): """ Find all the intersections of two or more lines that are not parallel nor the same line. `other` is a list. """ if not isinstance(other, list): other = [other] if not all(o.__class__ == self.__class__ for o in other): raise TypeError('can compare only Lines') full = [self] + other import itertools prod = [] [prod.append(f) for f in itertools.product(full, full) if f[0] is not f[1] and (f[1], f[0]) not in prod] if any(p[0] == p[1] or p[0].is_parallel(p[1]) for p in prod): raise ValueError('two of the lines are the same line or they are parallel') return [o[0].intersection(o[1]) for o in prod]
from vector import Vector class Line2D(object): """ Parametrization of a line. ~~~~~~~~~~~~~~~~~~~~~~~~~~ Definition: Ax = By = k Operation: find a basepoint and a direction vector to define a line """ __ROUNDING = 9 def __init__(self, normal_vector=None, const_term=None): # normal vector = [A, B] self.normal_vector = normal_vector \ if normal_vector is not None and not normal_vector.is_zero_vector \ else ValueError('line needs a normal vector and must be not a zero vector') if not self.normal_vector.__class__ == Vector: raise TypeError('normal vector must be of class Vector') self.term = self.k = const_term if const_term is not None else 0 self.A = self.normal_vector.coordinates[0] self.B = self.normal_vector.coordinates[1] def __str__(self): return str('Line with normal {} and basepoint ({})').format(str(self.normal), str(self.basepoint)) def __eq__(self, other): """ Two lines are the same line if a vector created by picking two random points from both is orthogonal to the normal vector. """ if not self.is_parallel(other): return False test_vector = Vector([self.basepoint, other.basepoint]) return test_vector.is_orthogonal(self.normal_vector) def __ne__(self, other): """ Two lines are not the same line. """ return not self.__eq__(other) def is_parallel(self, other): """ Two lines are parallel if their normal vectors are parallel. """ if other.__class__ != self.__class__: raise TypeError('can compare only two Lines') return self.normal_vector.is_parallel(other.normal_vector) @property def normal(self): return self.normal_vector @property def constant(self): return self.term @property def basepoint(self): return self.set_basepoint() def set_basepoint(self, rounding=__ROUNDING): if self.B != 0: # B != 0 so (0, k/B) is a base point return round(self.term / self.B, rounding) if self.A != 0: # A != 0 so (k/A, 0) is a base point return round(self.term / self.A, rounding) raise ValueError('normal vector cannot be the zero vector') @property def direction(self, rounding=__ROUNDING): return Vector([self.B, -self.A]) def intersection(self, other, rounding=__ROUNDING): """ Find intersection of more than two lines that are not parallel nor the same line. """ if other.__class__ != self.__class__: raise TypeError('can compare only two Lines') if self == other: raise ValueError('Lines have infinite points in common') if self.is_parallel(other): raise ValueError('Lines are parallel') denominator = round((self.A * other.B) - (self.B * other.A), rounding) numerator1 = round((other.B * self.k) - (self.B * other.k), rounding) numerator2 = round(-(other.A * self.k) + (self.A * other.k), rounding) return numerator1 / denominator, numerator2 / denominator def intersection_multi(self, other, rounding=__ROUNDING): """ Find all the intersections of two or more lines that are not parallel nor the same line. `other` is a list. """ if not isinstance(other, list): other = [other] if not all(o.__class__ == self.__class__ for o in other): raise TypeError('can compare only Lines') full = [self] + other import itertools prod = [] [prod.append(f) for f in itertools.product(full, full) if f[0] is not f[1] and (f[1], f[0]) not in prod] if any(p[0] == p[1] or p[0].is_parallel(p[1]) for p in prod): raise ValueError('two of the lines are the same line or they are parallel') return [o[0].intersection(o[1]) for o in prod]
en
0.916137
Parametrization of a line. ~~~~~~~~~~~~~~~~~~~~~~~~~~ Definition: Ax = By = k Operation: find a basepoint and a direction vector to define a line # normal vector = [A, B] Two lines are the same line if a vector created by picking two random points from both is orthogonal to the normal vector. Two lines are not the same line. Two lines are parallel if their normal vectors are parallel. # B != 0 so (0, k/B) is a base point # A != 0 so (k/A, 0) is a base point Find intersection of more than two lines that are not parallel nor the same line. Find all the intersections of two or more lines that are not parallel nor the same line. `other` is a list.
3.920096
4
code/Q891.py
cbgclecode/clebear
0
6628303
<reponame>cbgclecode/clebear """ # description 有一个二维矩阵 A 其中每个元素的值为 0 或 1 。 移动是指选择任一行或列,并转换该行或列中的每一个值:将所有 0 都更改为 1,将所有 1 都更改为 0。 在做出任意次数的移动后,将该矩阵的每一行都按照二进制数来解释,矩阵的得分就是这些数字的总和。 返回尽可能高的分数。   示例: 输入:[[0,0,1,1],[1,0,1,0],[1,1,0,0]] 输出:39 解释: 转换为 [[1,1,1,1],[1,0,0,1],[1,1,1,1]] 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39   提示: 1 <= A.length <= 20 1 <= A[0].length <= 20 A[i][j] 是 0 或 1 """ """ # code demo class Solution: def matrixScore(self, grid: List[List[int]]) -> int: """ """ # summary """ _question_id = 891 _question__title = "Score After Flipping Matrix" _question__title_slug = "score-after-flipping-matrix" _difficulty_level = "2" _question_url = "https://leetcode-cn.com/problems/score-after-flipping-matrix" from typing import List def judge(solution=None, method=None, io_equal=None): method = getattr(solution(), method) assert method([[0, 0, 1, 1], [1, 0, 1, 0], [1, 1, 0, 0]]) == 39 print(f"Test ok.") pass class Solution: def matrixScore(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) ret = m * (1 << (n - 1)) for j in range(1, n): n_ones = 0 for i in range(m): if grid[i][0]: n_ones += grid[i][j] else: n_ones += 1 - grid[i][j] k = max(n_ones, m - n_ones) ret += k * (1 << n - j - 1) return ret if __name__ == "__main__": judge(Solution, "matrixScore") pass
""" # description 有一个二维矩阵 A 其中每个元素的值为 0 或 1 。 移动是指选择任一行或列,并转换该行或列中的每一个值:将所有 0 都更改为 1,将所有 1 都更改为 0。 在做出任意次数的移动后,将该矩阵的每一行都按照二进制数来解释,矩阵的得分就是这些数字的总和。 返回尽可能高的分数。   示例: 输入:[[0,0,1,1],[1,0,1,0],[1,1,0,0]] 输出:39 解释: 转换为 [[1,1,1,1],[1,0,0,1],[1,1,1,1]] 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39   提示: 1 <= A.length <= 20 1 <= A[0].length <= 20 A[i][j] 是 0 或 1 """ """ # code demo class Solution: def matrixScore(self, grid: List[List[int]]) -> int: """ """ # summary """ _question_id = 891 _question__title = "Score After Flipping Matrix" _question__title_slug = "score-after-flipping-matrix" _difficulty_level = "2" _question_url = "https://leetcode-cn.com/problems/score-after-flipping-matrix" from typing import List def judge(solution=None, method=None, io_equal=None): method = getattr(solution(), method) assert method([[0, 0, 1, 1], [1, 0, 1, 0], [1, 1, 0, 0]]) == 39 print(f"Test ok.") pass class Solution: def matrixScore(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) ret = m * (1 << (n - 1)) for j in range(1, n): n_ones = 0 for i in range(m): if grid[i][0]: n_ones += grid[i][j] else: n_ones += 1 - grid[i][j] k = max(n_ones, m - n_ones) ret += k * (1 << n - j - 1) return ret if __name__ == "__main__": judge(Solution, "matrixScore") pass
zh
0.848434
# description 有一个二维矩阵 A 其中每个元素的值为 0 或 1 。 移动是指选择任一行或列,并转换该行或列中的每一个值:将所有 0 都更改为 1,将所有 1 都更改为 0。 在做出任意次数的移动后,将该矩阵的每一行都按照二进制数来解释,矩阵的得分就是这些数字的总和。 返回尽可能高的分数。   示例: 输入:[[0,0,1,1],[1,0,1,0],[1,1,0,0]] 输出:39 解释: 转换为 [[1,1,1,1],[1,0,0,1],[1,1,1,1]] 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39   提示: 1 <= A.length <= 20 1 <= A[0].length <= 20 A[i][j] 是 0 或 1 # code demo class Solution: def matrixScore(self, grid: List[List[int]]) -> int: # summary
3.841196
4
src/app/voltdb/voltdb_src/lib/python/voltcli/voltadmin.d/save.py
OpenMPDK/SMDK
44
6628304
<reponame>OpenMPDK/SMDK # This file is part of VoltDB. # Copyright (C) 2008-2021 VoltDB Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with VoltDB. If not, see <http://www.gnu.org/licenses/>. import os import urllib.request, urllib.parse, urllib.error import sys @VOLT.Command( bundles = VOLT.AdminBundle(), description = 'Save a VoltDB database snapshot.', options = ( VOLT.BooleanOption('-b', '--blocking', 'blocking', 'block transactions and wait until the snapshot completes', default = False), VOLT.EnumOption('-f', '--format', 'format', 'snapshot format', 'native', 'csv', default = 'native'), VOLT.StringListOption(None, '--tables', 'tables', 'tables to include in the snapshot', default = None), VOLT.StringListOption(None, '--skiptables', 'skip_tables', 'tables to skip in the snapshot', default = None) ), arguments=( VOLT.PathArgument('directory', 'the snapshot server directory', absolute=True, optional=True), VOLT.StringArgument('nonce', 'the unique snapshot identifier (nonce)', optional=True) ) ) def save(runner): uri = None dir_specified = False if runner.opts.directory is not None: uri = 'file://%s' % urllib.parse.quote(runner.opts.directory) dir_specified = True nonce = None if runner.opts.nonce is not None: nonce = runner.opts.nonce.replace('"', '\\"') elif dir_specified: runner.abort('When a DIRECTORY is given a NONCE must be specified as well.') else: runner.opts.format = 'native' runner.opts.tables = None runner.opts.skip_tables = None if runner.opts.blocking: blocking = 'true' else: blocking = 'false' if uri is not None: if nonce is not None: raw_json_opts = ['uripath:"%s"' % (uri), 'nonce:"%s"' % (nonce), 'block:%s' % (blocking), 'format:"%s"' % (runner.opts.format)] else: raw_json_opts = ['uripath:"%s"' % (uri), 'block:%s' % (blocking), 'format:"%s"' % (runner.opts.format)] else: if nonce is not None: raw_json_opts = ['uripath:"%s"' % (uri), 'nonce:"%s"' % (nonce), 'block:%s' % (blocking), 'format:"%s"' % (runner.opts.format)] else: raw_json_opts = ['block:%s' % (blocking), 'format:"%s"' % (runner.opts.format)] if runner.opts.tables: raw_json_opts.append('tables:%s' % (runner.opts.tables)) if runner.opts.skip_tables: raw_json_opts.append('skiptables:%s' % (runner.opts.skip_tables)) runner.verbose_info('@SnapshotSave "%s"' % raw_json_opts) columns = [VOLT.FastSerializer.VOLTTYPE_STRING] response = runner.call_proc('@SnapshotSave', columns, ['{%s}' % (','.join(raw_json_opts))]) res_table = response.table(0) has_failure = any([t[3] != 'SUCCESS' for t in res_table.tuples()]) print(res_table.format_table(caption = 'Snapshot Save Results')) if has_failure: sys.exit(1)
# This file is part of VoltDB. # Copyright (C) 2008-2021 VoltDB Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with VoltDB. If not, see <http://www.gnu.org/licenses/>. import os import urllib.request, urllib.parse, urllib.error import sys @VOLT.Command( bundles = VOLT.AdminBundle(), description = 'Save a VoltDB database snapshot.', options = ( VOLT.BooleanOption('-b', '--blocking', 'blocking', 'block transactions and wait until the snapshot completes', default = False), VOLT.EnumOption('-f', '--format', 'format', 'snapshot format', 'native', 'csv', default = 'native'), VOLT.StringListOption(None, '--tables', 'tables', 'tables to include in the snapshot', default = None), VOLT.StringListOption(None, '--skiptables', 'skip_tables', 'tables to skip in the snapshot', default = None) ), arguments=( VOLT.PathArgument('directory', 'the snapshot server directory', absolute=True, optional=True), VOLT.StringArgument('nonce', 'the unique snapshot identifier (nonce)', optional=True) ) ) def save(runner): uri = None dir_specified = False if runner.opts.directory is not None: uri = 'file://%s' % urllib.parse.quote(runner.opts.directory) dir_specified = True nonce = None if runner.opts.nonce is not None: nonce = runner.opts.nonce.replace('"', '\\"') elif dir_specified: runner.abort('When a DIRECTORY is given a NONCE must be specified as well.') else: runner.opts.format = 'native' runner.opts.tables = None runner.opts.skip_tables = None if runner.opts.blocking: blocking = 'true' else: blocking = 'false' if uri is not None: if nonce is not None: raw_json_opts = ['uripath:"%s"' % (uri), 'nonce:"%s"' % (nonce), 'block:%s' % (blocking), 'format:"%s"' % (runner.opts.format)] else: raw_json_opts = ['uripath:"%s"' % (uri), 'block:%s' % (blocking), 'format:"%s"' % (runner.opts.format)] else: if nonce is not None: raw_json_opts = ['uripath:"%s"' % (uri), 'nonce:"%s"' % (nonce), 'block:%s' % (blocking), 'format:"%s"' % (runner.opts.format)] else: raw_json_opts = ['block:%s' % (blocking), 'format:"%s"' % (runner.opts.format)] if runner.opts.tables: raw_json_opts.append('tables:%s' % (runner.opts.tables)) if runner.opts.skip_tables: raw_json_opts.append('skiptables:%s' % (runner.opts.skip_tables)) runner.verbose_info('@SnapshotSave "%s"' % raw_json_opts) columns = [VOLT.FastSerializer.VOLTTYPE_STRING] response = runner.call_proc('@SnapshotSave', columns, ['{%s}' % (','.join(raw_json_opts))]) res_table = response.table(0) has_failure = any([t[3] != 'SUCCESS' for t in res_table.tuples()]) print(res_table.format_table(caption = 'Snapshot Save Results')) if has_failure: sys.exit(1)
en
0.878466
# This file is part of VoltDB. # Copyright (C) 2008-2021 VoltDB Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
2.090425
2
api/tests/opentrons/protocols/fixtures/bundled_protocols/simple_bundle/protocol.py
felipesanches/opentrons
0
6628305
<filename>api/tests/opentrons/protocols/fixtures/bundled_protocols/simple_bundle/protocol.py metadata = {'author': '<NAME>'} def run(protocol_context): tip_rack = protocol_context.load_labware('opentrons_96_tiprack_10ul', '3') plate = protocol_context.load_labware( 'custom_labware', '1', namespace='custom_beta') pipette = protocol_context.load_instrument('p10_single', 'left', tip_racks=[tip_rack]) csv_data = protocol_context.bundled_data['data.txt'].decode('utf-8') for volume in csv_data.split(','): v = float(volume.strip()) pipette.transfer(v, plate.wells('A1'), plate.wells('A4'))
<filename>api/tests/opentrons/protocols/fixtures/bundled_protocols/simple_bundle/protocol.py metadata = {'author': '<NAME>'} def run(protocol_context): tip_rack = protocol_context.load_labware('opentrons_96_tiprack_10ul', '3') plate = protocol_context.load_labware( 'custom_labware', '1', namespace='custom_beta') pipette = protocol_context.load_instrument('p10_single', 'left', tip_racks=[tip_rack]) csv_data = protocol_context.bundled_data['data.txt'].decode('utf-8') for volume in csv_data.split(','): v = float(volume.strip()) pipette.transfer(v, plate.wells('A1'), plate.wells('A4'))
none
1
1.780281
2
tests/python/server.py
kicsyromy/libremotetransmission
1
6628306
<filename>tests/python/server.py import os import json from switch import Switch session_id = 'dGVzdGhlZHNnZGpraGtkamhha2ZjZ3dlODN3aXVkc2hhZm4n' stats = None torrents = None recently_active = None with open(os.path.join(os.path.dirname(__file__), 'json/stats.json')) as stats_json: stats = json.load(stats_json) def get_statistics(request): stats['tag'] = request['tag'] return json.dumps(stats) + '\n' with open(os.path.join(os.path.dirname(__file__), 'json/torrents.json')) as torrents_json: torrents = json.load(torrents_json) with open(os.path.join(os.path.dirname(__file__), 'json/recently_active.json')) as recently_active_json: recently_active = json.load(recently_active_json) def get_torrents(request): if 'ids' in request['arguments'] and request['arguments']['ids'] == 'recently-active': recently_active['tag'] = request['tag'] return json.dumps(recently_active) + '\n' else: torrents['tag'] = request['tag'] return json.dumps(torrents) + '\n' def test_send_request(request): result = { 'arguments': { 'args': 0 }, 'result': 'success', 'tag': request['tag'] } return json.dumps(result) + '\n'; class Session: @staticmethod def handle_request(request, response): request_data = None try: request_data = json.loads(request.data) except: None response.headers['X-Transmission-Session-Id'] = session_id if 'X-Transmission-Session-Id' not in request.headers or \ request.headers['X-Transmission-Session-Id'] != session_id: response.code = 409 response.content_type = 'text/html; charset=ISO-8859-1' response.data = '<h1>Bad X-Transmission-Session-Id</h1>' else: if request_data: if 'method' not in request_data or \ 'arguments' not in request_data or \ 'tag' not in request_data: response.code = 405 response.data = '<h1>405: Method Not Allowed</h1>' else: for case in Switch(request_data['method']): if case('session-stats'): response.data = get_statistics(request_data) break if case('torrent-get'): response.data = get_torrents(request_data) break if case('test_send_request'): response.data = test_send_request(request_data) break if case(): response.data = json.dumps({'arguments':{}, 'result':'uninmplemented'}) + '\n' break else: response.data = json.dumps({'arguments':{},'result':'no method name'}) + '\n'
<filename>tests/python/server.py import os import json from switch import Switch session_id = 'dGVzdGhlZHNnZGpraGtkamhha2ZjZ3dlODN3aXVkc2hhZm4n' stats = None torrents = None recently_active = None with open(os.path.join(os.path.dirname(__file__), 'json/stats.json')) as stats_json: stats = json.load(stats_json) def get_statistics(request): stats['tag'] = request['tag'] return json.dumps(stats) + '\n' with open(os.path.join(os.path.dirname(__file__), 'json/torrents.json')) as torrents_json: torrents = json.load(torrents_json) with open(os.path.join(os.path.dirname(__file__), 'json/recently_active.json')) as recently_active_json: recently_active = json.load(recently_active_json) def get_torrents(request): if 'ids' in request['arguments'] and request['arguments']['ids'] == 'recently-active': recently_active['tag'] = request['tag'] return json.dumps(recently_active) + '\n' else: torrents['tag'] = request['tag'] return json.dumps(torrents) + '\n' def test_send_request(request): result = { 'arguments': { 'args': 0 }, 'result': 'success', 'tag': request['tag'] } return json.dumps(result) + '\n'; class Session: @staticmethod def handle_request(request, response): request_data = None try: request_data = json.loads(request.data) except: None response.headers['X-Transmission-Session-Id'] = session_id if 'X-Transmission-Session-Id' not in request.headers or \ request.headers['X-Transmission-Session-Id'] != session_id: response.code = 409 response.content_type = 'text/html; charset=ISO-8859-1' response.data = '<h1>Bad X-Transmission-Session-Id</h1>' else: if request_data: if 'method' not in request_data or \ 'arguments' not in request_data or \ 'tag' not in request_data: response.code = 405 response.data = '<h1>405: Method Not Allowed</h1>' else: for case in Switch(request_data['method']): if case('session-stats'): response.data = get_statistics(request_data) break if case('torrent-get'): response.data = get_torrents(request_data) break if case('test_send_request'): response.data = test_send_request(request_data) break if case(): response.data = json.dumps({'arguments':{}, 'result':'uninmplemented'}) + '\n' break else: response.data = json.dumps({'arguments':{},'result':'no method name'}) + '\n'
none
1
2.331024
2
data/envLibrary/photocell_lib.py
ulnic/weatherSensor_rpi
1
6628307
#!/usr/bin/env python """ Example for RC timing reading for Raspberry Pi Must be used with GPIO 0.3.1a or later - earlier version are not fast enough! """ import RPi.GPIO as GPIO import time import math GPIO.setmode(GPIO.BCM) def read_photocell(_gpio_pin): """ Read the photocell value from the RPI Board, using the specified GPIO Pin. :param _gpio_pin: GPIO Pin to read from RPI board :return: Read value """ reading = 0 GPIO.setup(_gpio_pin, GPIO.OUT) GPIO.output(_gpio_pin, GPIO.LOW) time.sleep(1) GPIO.setup(_gpio_pin, GPIO.IN) # This takes about 1 millisecond per loop cycle while GPIO.input(_gpio_pin) == GPIO.LOW: reading += 1 return float(convert_to_linear(reading)) def convert_to_linear(p): """ Convert log value read to linear :param p: reading value to convert :return: Converted INT value (now linear instead of log) """ if p > 0: return abs(100 - (math.log10(p) * 30)) elif p <= 0: return 100 else: raise ValueError
#!/usr/bin/env python """ Example for RC timing reading for Raspberry Pi Must be used with GPIO 0.3.1a or later - earlier version are not fast enough! """ import RPi.GPIO as GPIO import time import math GPIO.setmode(GPIO.BCM) def read_photocell(_gpio_pin): """ Read the photocell value from the RPI Board, using the specified GPIO Pin. :param _gpio_pin: GPIO Pin to read from RPI board :return: Read value """ reading = 0 GPIO.setup(_gpio_pin, GPIO.OUT) GPIO.output(_gpio_pin, GPIO.LOW) time.sleep(1) GPIO.setup(_gpio_pin, GPIO.IN) # This takes about 1 millisecond per loop cycle while GPIO.input(_gpio_pin) == GPIO.LOW: reading += 1 return float(convert_to_linear(reading)) def convert_to_linear(p): """ Convert log value read to linear :param p: reading value to convert :return: Converted INT value (now linear instead of log) """ if p > 0: return abs(100 - (math.log10(p) * 30)) elif p <= 0: return 100 else: raise ValueError
en
0.690153
#!/usr/bin/env python Example for RC timing reading for Raspberry Pi Must be used with GPIO 0.3.1a or later - earlier version are not fast enough! Read the photocell value from the RPI Board, using the specified GPIO Pin. :param _gpio_pin: GPIO Pin to read from RPI board :return: Read value # This takes about 1 millisecond per loop cycle Convert log value read to linear :param p: reading value to convert :return: Converted INT value (now linear instead of log)
3.52381
4
money/money.py
scompo/money
0
6628308
from time import localtime, gmtime, strftime, strptime from os.path import expanduser, join from pprint import pprint from decimal import * def scrivi_movimento(path, m): with open(path, 'a') as f: f.write(m['tipo'] + m['valore']) f.write(';') f.write(m['data']) f.write(';') f.write(m['ora']) f.write(';') f.write(m['descrizione']) f.write('\n') return def leggi_tipo(): t = 'n' while not (t == '' or t == '+' or t == '-'): t = input('tipo (+/-) [-]: ') if t == '': t='-' elif t == '+': t='' return t def leggi_valore(): v = '' while v == '': v = input('valore (#####.##) []: ') return v def leggi_data(): d = input('data (DD/MM/YYYY) [oggi]: ') if d == '': d = strftime("%d/%m/%Y", localtime()) return d def leggi_ora(): o = input('ora (HH:MM) [adesso]: ') if o == '': o = strftime('%H:%M', localtime()) return o def leggi_descrizione(): d = input('descrizione () []: ') return d def leggi_movimento(): tipo = leggi_tipo() valore = leggi_valore() data = leggi_data() ora = leggi_ora() descrizione = leggi_descrizione() m = { 'tipo' : tipo, 'valore' : valore, 'data' : data, 'ora' : ora, 'descrizione': descrizione } return m def get_file_dati(): home = expanduser('~') nome_file_dati = 'movimenti.dat' file_dati = join(home, 'dati', nome_file_dati) print('file dati:', file_dati) return file_dati def carica_file(f): dati = [] with open(f, "r") as df: for l in df: spl = l.split(';') d = { 'valore' : spl[0], 'data' : spl[1], 'ora' : spl[2], 'descrizione' : spl[3] } dati.append(d) return dati def inserimento(file_dati): m = leggi_movimento() scrivi_movimento(file_dati, m) def inserimento_dati(): file_dati = get_file_dati() inserimento(file_dati) def riassunto_dati(): file_dati = get_file_dati() riassunto(file_dati) def data_default(data): try: return strptime(data, '%d/%m/%Y') except ValueError: return gmtime(0) def ora_default(ora): try: return strptime(ora, '%H:%M') except ValueError: return gmtime(0) def ordina(dati): return sorted( dati, key = lambda x: ( data_default(x['data']), ora_default(x['ora']) ), reverse = True ) def riassunto(file_dati): dati = carica_file(file_dati) dati_ordinati = ordina(dati) val_attuale = Decimal('0') spese_tot = Decimal('0') guadagni_tot = Decimal('0') for d in dati: m = Decimal(d['valore']) val_attuale = val_attuale + m if m > Decimal('0'): guadagni_tot = guadagni_tot + m else: spese_tot = spese_tot + m print('valore attuale:', str(val_attuale)) print('guadagni complessivi:', str(guadagni_tot)) print('spese complessive:', str(spese_tot)) print('ultimi 5 movimenti:') for i in range(5): if i < len(dati_ordinati): print(dati_ordinati[i])
from time import localtime, gmtime, strftime, strptime from os.path import expanduser, join from pprint import pprint from decimal import * def scrivi_movimento(path, m): with open(path, 'a') as f: f.write(m['tipo'] + m['valore']) f.write(';') f.write(m['data']) f.write(';') f.write(m['ora']) f.write(';') f.write(m['descrizione']) f.write('\n') return def leggi_tipo(): t = 'n' while not (t == '' or t == '+' or t == '-'): t = input('tipo (+/-) [-]: ') if t == '': t='-' elif t == '+': t='' return t def leggi_valore(): v = '' while v == '': v = input('valore (#####.##) []: ') return v def leggi_data(): d = input('data (DD/MM/YYYY) [oggi]: ') if d == '': d = strftime("%d/%m/%Y", localtime()) return d def leggi_ora(): o = input('ora (HH:MM) [adesso]: ') if o == '': o = strftime('%H:%M', localtime()) return o def leggi_descrizione(): d = input('descrizione () []: ') return d def leggi_movimento(): tipo = leggi_tipo() valore = leggi_valore() data = leggi_data() ora = leggi_ora() descrizione = leggi_descrizione() m = { 'tipo' : tipo, 'valore' : valore, 'data' : data, 'ora' : ora, 'descrizione': descrizione } return m def get_file_dati(): home = expanduser('~') nome_file_dati = 'movimenti.dat' file_dati = join(home, 'dati', nome_file_dati) print('file dati:', file_dati) return file_dati def carica_file(f): dati = [] with open(f, "r") as df: for l in df: spl = l.split(';') d = { 'valore' : spl[0], 'data' : spl[1], 'ora' : spl[2], 'descrizione' : spl[3] } dati.append(d) return dati def inserimento(file_dati): m = leggi_movimento() scrivi_movimento(file_dati, m) def inserimento_dati(): file_dati = get_file_dati() inserimento(file_dati) def riassunto_dati(): file_dati = get_file_dati() riassunto(file_dati) def data_default(data): try: return strptime(data, '%d/%m/%Y') except ValueError: return gmtime(0) def ora_default(ora): try: return strptime(ora, '%H:%M') except ValueError: return gmtime(0) def ordina(dati): return sorted( dati, key = lambda x: ( data_default(x['data']), ora_default(x['ora']) ), reverse = True ) def riassunto(file_dati): dati = carica_file(file_dati) dati_ordinati = ordina(dati) val_attuale = Decimal('0') spese_tot = Decimal('0') guadagni_tot = Decimal('0') for d in dati: m = Decimal(d['valore']) val_attuale = val_attuale + m if m > Decimal('0'): guadagni_tot = guadagni_tot + m else: spese_tot = spese_tot + m print('valore attuale:', str(val_attuale)) print('guadagni complessivi:', str(guadagni_tot)) print('spese complessive:', str(spese_tot)) print('ultimi 5 movimenti:') for i in range(5): if i < len(dati_ordinati): print(dati_ordinati[i])
fa
0.842916
#####.##) []: ')
3.004961
3
tests/python/relay/test_op_qnn_subtract.py
mwillsey/incubator-tvm
2
6628309
<gh_stars>1-10 # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm import numpy as np from tvm import relay def qnn_subtract_driver(x_datas, y_datas, golden_outputs, scale_and_zp, data_dtype="uint8"): # all x, y and golden outputs should be of the same length assert len(x_datas) == len(y_datas) assert len(y_datas) == len(golden_outputs) x = relay.var("x", shape=(1, 4), dtype=data_dtype) y = relay.var("y", shape=(1, 4), dtype=data_dtype) lhs_scale = relay.const(scale_and_zp["lhs_scale"], "float32") lhs_zp = relay.const(scale_and_zp["lhs_zp"], "int32") rhs_scale = relay.const(scale_and_zp["rhs_scale"], "float32") rhs_zp = relay.const(scale_and_zp["rhs_zp"], "int32") output_scale = relay.const(scale_and_zp["output_scale"], "float32") output_zp = relay.const(scale_and_zp["output_zp"], "int32") z = relay.qnn.op.subtract( lhs=x, rhs=y, lhs_scale=lhs_scale, lhs_zero_point=lhs_zp, rhs_scale=rhs_scale, rhs_zero_point=rhs_zp, output_scale=output_scale, output_zero_point=output_zp, ) func = relay.Function([x, y], z) mod = tvm.IRModule.from_expr(func) mod = relay.qnn.transform.CanonicalizeOps()(mod) func = mod["main"] for i in range(0, len(x_datas)): x_data = x_datas[i] y_data = y_datas[i] golden_output = golden_outputs[i] intrp = relay.create_executor("graph", ctx=tvm.cpu(0), target="llvm") op_res = intrp.evaluate(func)(x_data, y_data) np.testing.assert_equal(op_res.asnumpy(), golden_output) def test_tflite_same_io_qnn_params(): scale_and_zp = { "lhs_scale": 0.00784314, "lhs_zp": 127, "rhs_scale": 0.00784314, "rhs_zp": 127, "output_scale": 0.00784314, "output_zp": 127, } x_datas = [ np.array((140, 153, 165, 178)).reshape((1, 4)), np.array((25, 153, 178, 216)).reshape((1, 4)), np.array((25, 153, 216, 165)).reshape((1, 4)), ] y_datas = [ np.array((204, 178, 165, 140)).reshape((1, 4)), np.array((204, 178, 191, 25)).reshape((1, 4)), np.array((204, 178, 25, 191)).reshape((1, 4)), ] golden_outputs = [ np.array((63, 102, 127, 165)).reshape((1, 4)), np.array((0, 102, 114, 255)).reshape((1, 4)), np.array((0, 102, 255, 101)).reshape((1, 4)), ] qnn_subtract_driver(x_datas, y_datas, golden_outputs, scale_and_zp) def test_tflite_different_io_qnn_params(): scale_and_zp = { "lhs_scale": 0.0156863, "lhs_zp": 127, "rhs_scale": 0.0117647, "rhs_zp": 85, "output_scale": 0.0235294, "output_zp": 128, } x_datas = [ np.array((76, 140, 153, 172)).reshape((1, 4)), np.array((133, 140, 146, 153)).reshape((1, 4)), np.array((76, 140, 172, 146)).reshape((1, 4)), ] y_datas = [ np.array((136, 119, 128, 17)).reshape((1, 4)), np.array((136, 119, 111, 94)).reshape((1, 4)), np.array((136, 119, 17, 128)).reshape((1, 4)), ] golden_outputs = [ np.array((68, 120, 123, 192)).reshape((1, 4)), np.array((106, 120, 128, 140)).reshape((1, 4)), np.array((68, 120, 192, 119)).reshape((1, 4)), ] qnn_subtract_driver(x_datas, y_datas, golden_outputs, scale_and_zp) def test_saturation(): # Same params scale_and_zp = { "lhs_scale": 0.125, "lhs_zp": 0, "rhs_scale": 0.125, "rhs_zp": 0, "output_scale": 0.125, "output_zp": 0, } x_data = [np.array((255, 1, 1, 0)).reshape((1, 4))] y_data = [np.array((255, 255, 128, 0)).reshape((1, 4))] golden_output = [np.array((0, 0, 0, 0)).reshape((1, 4))] qnn_subtract_driver(x_data, y_data, golden_output, scale_and_zp) # Same params, different scale scale_and_zp = { "lhs_scale": 0.125, "lhs_zp": 0, "rhs_scale": 0.125, "rhs_zp": 0, "output_scale": 0.25, "output_zp": 0, } x_data = [np.array((255, 1, 200, 0)).reshape((1, 4))] y_data = [np.array((255, 255, 127, 0)).reshape((1, 4))] golden_output = [np.array((0, 0, 36, 0)).reshape((1, 4))] qnn_subtract_driver(x_data, y_data, golden_output, scale_and_zp) # All params different scale_and_zp = { "lhs_scale": 0.5, "lhs_zp": 0, "rhs_scale": 0.25, "rhs_zp": 0, "output_scale": 0.125, "output_zp": 0, } x_data = [np.array((255, 0, 1, 0)).reshape((1, 4))] y_data = [np.array((0, 128, 64, 0)).reshape((1, 4))] golden_output = [np.array((255, 0, 0, 0)).reshape((1, 4))] qnn_subtract_driver(x_data, y_data, golden_output, scale_and_zp) if __name__ == "__main__": test_tflite_same_io_qnn_params() test_tflite_different_io_qnn_params() test_saturation()
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import tvm import numpy as np from tvm import relay def qnn_subtract_driver(x_datas, y_datas, golden_outputs, scale_and_zp, data_dtype="uint8"): # all x, y and golden outputs should be of the same length assert len(x_datas) == len(y_datas) assert len(y_datas) == len(golden_outputs) x = relay.var("x", shape=(1, 4), dtype=data_dtype) y = relay.var("y", shape=(1, 4), dtype=data_dtype) lhs_scale = relay.const(scale_and_zp["lhs_scale"], "float32") lhs_zp = relay.const(scale_and_zp["lhs_zp"], "int32") rhs_scale = relay.const(scale_and_zp["rhs_scale"], "float32") rhs_zp = relay.const(scale_and_zp["rhs_zp"], "int32") output_scale = relay.const(scale_and_zp["output_scale"], "float32") output_zp = relay.const(scale_and_zp["output_zp"], "int32") z = relay.qnn.op.subtract( lhs=x, rhs=y, lhs_scale=lhs_scale, lhs_zero_point=lhs_zp, rhs_scale=rhs_scale, rhs_zero_point=rhs_zp, output_scale=output_scale, output_zero_point=output_zp, ) func = relay.Function([x, y], z) mod = tvm.IRModule.from_expr(func) mod = relay.qnn.transform.CanonicalizeOps()(mod) func = mod["main"] for i in range(0, len(x_datas)): x_data = x_datas[i] y_data = y_datas[i] golden_output = golden_outputs[i] intrp = relay.create_executor("graph", ctx=tvm.cpu(0), target="llvm") op_res = intrp.evaluate(func)(x_data, y_data) np.testing.assert_equal(op_res.asnumpy(), golden_output) def test_tflite_same_io_qnn_params(): scale_and_zp = { "lhs_scale": 0.00784314, "lhs_zp": 127, "rhs_scale": 0.00784314, "rhs_zp": 127, "output_scale": 0.00784314, "output_zp": 127, } x_datas = [ np.array((140, 153, 165, 178)).reshape((1, 4)), np.array((25, 153, 178, 216)).reshape((1, 4)), np.array((25, 153, 216, 165)).reshape((1, 4)), ] y_datas = [ np.array((204, 178, 165, 140)).reshape((1, 4)), np.array((204, 178, 191, 25)).reshape((1, 4)), np.array((204, 178, 25, 191)).reshape((1, 4)), ] golden_outputs = [ np.array((63, 102, 127, 165)).reshape((1, 4)), np.array((0, 102, 114, 255)).reshape((1, 4)), np.array((0, 102, 255, 101)).reshape((1, 4)), ] qnn_subtract_driver(x_datas, y_datas, golden_outputs, scale_and_zp) def test_tflite_different_io_qnn_params(): scale_and_zp = { "lhs_scale": 0.0156863, "lhs_zp": 127, "rhs_scale": 0.0117647, "rhs_zp": 85, "output_scale": 0.0235294, "output_zp": 128, } x_datas = [ np.array((76, 140, 153, 172)).reshape((1, 4)), np.array((133, 140, 146, 153)).reshape((1, 4)), np.array((76, 140, 172, 146)).reshape((1, 4)), ] y_datas = [ np.array((136, 119, 128, 17)).reshape((1, 4)), np.array((136, 119, 111, 94)).reshape((1, 4)), np.array((136, 119, 17, 128)).reshape((1, 4)), ] golden_outputs = [ np.array((68, 120, 123, 192)).reshape((1, 4)), np.array((106, 120, 128, 140)).reshape((1, 4)), np.array((68, 120, 192, 119)).reshape((1, 4)), ] qnn_subtract_driver(x_datas, y_datas, golden_outputs, scale_and_zp) def test_saturation(): # Same params scale_and_zp = { "lhs_scale": 0.125, "lhs_zp": 0, "rhs_scale": 0.125, "rhs_zp": 0, "output_scale": 0.125, "output_zp": 0, } x_data = [np.array((255, 1, 1, 0)).reshape((1, 4))] y_data = [np.array((255, 255, 128, 0)).reshape((1, 4))] golden_output = [np.array((0, 0, 0, 0)).reshape((1, 4))] qnn_subtract_driver(x_data, y_data, golden_output, scale_and_zp) # Same params, different scale scale_and_zp = { "lhs_scale": 0.125, "lhs_zp": 0, "rhs_scale": 0.125, "rhs_zp": 0, "output_scale": 0.25, "output_zp": 0, } x_data = [np.array((255, 1, 200, 0)).reshape((1, 4))] y_data = [np.array((255, 255, 127, 0)).reshape((1, 4))] golden_output = [np.array((0, 0, 36, 0)).reshape((1, 4))] qnn_subtract_driver(x_data, y_data, golden_output, scale_and_zp) # All params different scale_and_zp = { "lhs_scale": 0.5, "lhs_zp": 0, "rhs_scale": 0.25, "rhs_zp": 0, "output_scale": 0.125, "output_zp": 0, } x_data = [np.array((255, 0, 1, 0)).reshape((1, 4))] y_data = [np.array((0, 128, 64, 0)).reshape((1, 4))] golden_output = [np.array((255, 0, 0, 0)).reshape((1, 4))] qnn_subtract_driver(x_data, y_data, golden_output, scale_and_zp) if __name__ == "__main__": test_tflite_same_io_qnn_params() test_tflite_different_io_qnn_params() test_saturation()
en
0.843184
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # all x, y and golden outputs should be of the same length # Same params # Same params, different scale # All params different
1.971747
2
btree.py
JiananYuan/Learned-Indexes
0
6628310
<gh_stars>0 # BTree Index with Python import pandas as pd # Node in BTree class BTreeNode: def __init__(self, degree=2, number_of_keys=0, is_leaf=True, items=None, children=None, index=None): self.isLeaf = is_leaf self.numberOfKeys = number_of_keys self.index = index if items is not None: self.items = items else: self.items = [None] * (degree * 2 - 1) if children is not None: self.children = children else: self.children = [None] * degree * 2 def set_index(self, index): self.index = index def get_index(self): return self.index def search(self, b_tree, an_item): i = 0 while i < self.numberOfKeys and an_item > self.items[i]: i += 1 if i < self.numberOfKeys and an_item == self.items[i]: return {'found': True, 'fileIndex': self.index, 'nodeIndex': i} if self.isLeaf: return {'found': False, 'fileIndex': self.index, 'nodeIndex': i - 1} else: return b_tree.get_node(self.children[i]).search(b_tree, an_item) # BTree Class class BTree: def __init__(self, degree=2, nodes=None, root_index=1, free_index=2): if nodes is None: nodes = {} self.degree = degree if len(nodes) == 0: self.rootNode = BTreeNode(degree) self.nodes = {} self.rootNode.set_index(root_index) self.write_at(1, self.rootNode) else: self.nodes = nodes self.rootNode = self.nodes[root_index] self.rootIndex = root_index self.freeIndex = free_index def build(self, keys, values): if len(keys) != len(values): return for ind in range(len(keys)): self.insert(Item(keys[ind], values[ind])) def search(self, an_item): return self.rootNode.search(self, an_item) def predict(self, key): search_result = self.search(Item(key, 0)) a_node = self.nodes[search_result['fileIndex']] if a_node.items[search_result['nodeIndex']] is None: return -1 return a_node.items[search_result['nodeIndex']].v def split_child(self, p_node, i, c_node): new_node = self.get_free_node() new_node.isLeaf = c_node.isLeaf new_node.numberOfKeys = self.degree - 1 for j in range(0, self.degree - 1): new_node.items[j] = c_node.items[j + self.degree] if c_node.isLeaf is False: for j in range(0, self.degree): new_node.children[j] = c_node.children[j + self.degree] c_node.numberOfKeys = self.degree - 1 j = p_node.numberOfKeys + 1 while j > i + 1: p_node.children[j + 1] = p_node.children[j] j -= 1 p_node.children[j] = new_node.get_index() j = p_node.numberOfKeys while j > i: p_node.items[j + 1] = p_node.items[j] j -= 1 p_node.items[i] = c_node.items[self.degree - 1] p_node.numberOfKeys += 1 def insert(self, an_item): search_result = self.search(an_item) if search_result['found']: return None r = self.rootNode if r.numberOfKeys == 2 * self.degree - 1: s = self.get_free_node() self.set_root_node(s) s.isLeaf = False s.numberOfKeys = 0 s.children[0] = r.get_index() self.split_child(s, 0, r) self.insert_not_full(s, an_item) else: self.insert_not_full(r, an_item) def insert_not_full(self, inNode, anItem): i = inNode.numberOfKeys - 1 if inNode.isLeaf: while i >= 0 and anItem < inNode.items[i]: inNode.items[i + 1] = inNode.items[i] i -= 1 inNode.items[i + 1] = anItem inNode.numberOfKeys += 1 else: while i >= 0 and anItem < inNode.items[i]: i -= 1 i += 1 if self.get_node(inNode.children[i]).numberOfKeys == 2 * self.degree - 1: self.split_child(inNode, i, self.get_node(inNode.children[i])) if anItem > inNode.items[i]: i += 1 self.insert_not_full(self.get_node(inNode.children[i]), anItem) def delete(self, an_item): an_item = Item(an_item, 0) search_result = self.search(an_item) if search_result['found'] is False: return None r = self.rootNode self.delete_in_node(r, an_item, search_result) def delete_in_node(self, a_node, an_item, search_result): if a_node.index == search_result['fileIndex']: i = search_result['nodeIndex'] if a_node.isLeaf: while i < a_node.numberOfKeys - 1: a_node.items[i] = a_node.items[i + 1] i += 1 a_node.numberOfKeys -= 1 else: left = self.get_node(a_node.children[i]) right = self.get_node(a_node.children[i + 1]) if left.numberOfKeys >= self.degree: a_node.items[i] = self.get_right_most(left) elif right.numberOfKeys >= self.degree: a_node.items[i] = self.get_right_most(right) else: k = left.numberOfKeys left.items[left.numberOfKeys] = an_item left.numberOfKeys += 1 for j in range(0, right.numberOfKeys): left.items[left.numberOfKeys] = right.items[j] left.numberOfKeys += 1 del self.nodes[right.get_index()] for j in range(i, a_node.numberOfKeys - 1): a_node.items[j] = a_node.items[j + 1] a_node.children[j + 1] = a_node.children[j + 2] a_node.numberOfKeys -= 1 if a_node.numberOfKeys == 0: del self.nodes[a_node.get_index()] self.set_root_node(left) self.delete_in_node(left, an_item, {'found': True, 'fileIndex': left.index, 'nodeIndex': k}) else: i = 0 while i < a_node.numberOfKeys and self.get_node(a_node.children[i]).search(self, an_item)['found'] is False: i += 1 c_node = self.get_node(a_node.children[i]) if c_node.numberOfKeys < self.degree: j = i - 1 while j < i + 2 and self.get_node(a_node.children[j]).numberOfKeys < self.degree: j += 1 if j == i - 1: sNode = self.get_node(a_node.children[j]) k = c_node.numberOfKeys while k > 0: c_node.items[k] = c_node.items[k - 1] c_node.children[k + 1] = c_node.children[k] k -= 1 c_node.children[1] = c_node.children[0] c_node.items[0] = a_node.items[i - 1] c_node.children[0] = sNode.children[sNode.numberOfKeys] c_node.numberOfKeys += 1 a_node.items[i - 1] = sNode.items[sNode.numberOfKeys - 1] sNode.numberOfKeys -= 1 elif j == i + 1: sNode = self.get_node(a_node.children[j]) c_node.items[c_node.numberOfKeys] = a_node.items[i] c_node.children[c_node.numberOfKeys + 1] = sNode.children[0] a_node.items[i] = sNode.items[0] for k in range(0, sNode.numberOfKeys): sNode.items[k] = sNode.items[k + 1] sNode.children[k] = sNode.children[k + 1] sNode.children[k] = sNode.children[k + 1] sNode.numberOfKeys -= 1 else: j = i + 1 sNode = self.get_node(a_node.children[j]) c_node.items[c_node.numberOfKeys] = a_node.items[i] c_node.numberOfKeys += 1 for k in range(0, sNode.numberOfKeys): c_node.items[c_node.numberOfKeys] = sNode.items[k] c_node.numberOfKeys += 1 del self.nodes[sNode.index] for k in range(i, a_node.numberOfKeys - 1): a_node.items[i] = a_node.items[i + 1] a_node.children[i + 1] = a_node.items[i + 2] a_node.numberOfKeys -= 1 if a_node.numberOfKeys == 0: del self.nodes[a_node.index] self.set_root_node(c_node) self.delete_in_node(c_node, an_item, c_node.search(self, an_item)) def get_right_most(self, aNode): if aNode.children[aNode.numberOfKeys] is None: upItem = aNode.items[aNode.numberOfKeys - 1] self.delete_in_node(aNode, upItem, {'found': True, 'fileIndex': aNode.index, 'nodeIndex': aNode.numberOfKeys - 1}) return upItem else: return self.get_right_most(self.get_node(aNode.children[aNode.numberOfKeys])) def set_root_node(self, r): self.rootNode = r self.rootIndex = self.rootNode.get_index() def get_node(self, index): return self.nodes[index] def get_free_node(self): new_node = BTreeNode(self.degree) index = self.get_free_index() new_node.set_index(index) self.write_at(index, new_node) return new_node def get_free_index(self): self.freeIndex += 1 return self.freeIndex - 1 def write_at(self, index, a_node): self.nodes[index] = a_node # Value in Node class Item(): def __init__(self, k, v): self.k = k self.v = v def __gt__(self, other): if self.k > other.k: return True else: return False def __ge__(self, other): if self.k >= other.k: return True else: return False def __eq__(self, other): if self.k == other.k: return True else: return False def __le__(self, other): if self.k <= other.k: return True else: return False def __lt__(self, other): if self.k < other.k: return True else: return False # For Test def b_tree_main(): path = "last_data.csv" data = pd.read_csv(path) b = BTree(2) for i in range(data.shape[0]): b.insert(Item(data.ix[i, 0], data.ix[i, 1])) pos = b.predict(30310) print(pos) if __name__ == '__main__': b_tree_main()
# BTree Index with Python import pandas as pd # Node in BTree class BTreeNode: def __init__(self, degree=2, number_of_keys=0, is_leaf=True, items=None, children=None, index=None): self.isLeaf = is_leaf self.numberOfKeys = number_of_keys self.index = index if items is not None: self.items = items else: self.items = [None] * (degree * 2 - 1) if children is not None: self.children = children else: self.children = [None] * degree * 2 def set_index(self, index): self.index = index def get_index(self): return self.index def search(self, b_tree, an_item): i = 0 while i < self.numberOfKeys and an_item > self.items[i]: i += 1 if i < self.numberOfKeys and an_item == self.items[i]: return {'found': True, 'fileIndex': self.index, 'nodeIndex': i} if self.isLeaf: return {'found': False, 'fileIndex': self.index, 'nodeIndex': i - 1} else: return b_tree.get_node(self.children[i]).search(b_tree, an_item) # BTree Class class BTree: def __init__(self, degree=2, nodes=None, root_index=1, free_index=2): if nodes is None: nodes = {} self.degree = degree if len(nodes) == 0: self.rootNode = BTreeNode(degree) self.nodes = {} self.rootNode.set_index(root_index) self.write_at(1, self.rootNode) else: self.nodes = nodes self.rootNode = self.nodes[root_index] self.rootIndex = root_index self.freeIndex = free_index def build(self, keys, values): if len(keys) != len(values): return for ind in range(len(keys)): self.insert(Item(keys[ind], values[ind])) def search(self, an_item): return self.rootNode.search(self, an_item) def predict(self, key): search_result = self.search(Item(key, 0)) a_node = self.nodes[search_result['fileIndex']] if a_node.items[search_result['nodeIndex']] is None: return -1 return a_node.items[search_result['nodeIndex']].v def split_child(self, p_node, i, c_node): new_node = self.get_free_node() new_node.isLeaf = c_node.isLeaf new_node.numberOfKeys = self.degree - 1 for j in range(0, self.degree - 1): new_node.items[j] = c_node.items[j + self.degree] if c_node.isLeaf is False: for j in range(0, self.degree): new_node.children[j] = c_node.children[j + self.degree] c_node.numberOfKeys = self.degree - 1 j = p_node.numberOfKeys + 1 while j > i + 1: p_node.children[j + 1] = p_node.children[j] j -= 1 p_node.children[j] = new_node.get_index() j = p_node.numberOfKeys while j > i: p_node.items[j + 1] = p_node.items[j] j -= 1 p_node.items[i] = c_node.items[self.degree - 1] p_node.numberOfKeys += 1 def insert(self, an_item): search_result = self.search(an_item) if search_result['found']: return None r = self.rootNode if r.numberOfKeys == 2 * self.degree - 1: s = self.get_free_node() self.set_root_node(s) s.isLeaf = False s.numberOfKeys = 0 s.children[0] = r.get_index() self.split_child(s, 0, r) self.insert_not_full(s, an_item) else: self.insert_not_full(r, an_item) def insert_not_full(self, inNode, anItem): i = inNode.numberOfKeys - 1 if inNode.isLeaf: while i >= 0 and anItem < inNode.items[i]: inNode.items[i + 1] = inNode.items[i] i -= 1 inNode.items[i + 1] = anItem inNode.numberOfKeys += 1 else: while i >= 0 and anItem < inNode.items[i]: i -= 1 i += 1 if self.get_node(inNode.children[i]).numberOfKeys == 2 * self.degree - 1: self.split_child(inNode, i, self.get_node(inNode.children[i])) if anItem > inNode.items[i]: i += 1 self.insert_not_full(self.get_node(inNode.children[i]), anItem) def delete(self, an_item): an_item = Item(an_item, 0) search_result = self.search(an_item) if search_result['found'] is False: return None r = self.rootNode self.delete_in_node(r, an_item, search_result) def delete_in_node(self, a_node, an_item, search_result): if a_node.index == search_result['fileIndex']: i = search_result['nodeIndex'] if a_node.isLeaf: while i < a_node.numberOfKeys - 1: a_node.items[i] = a_node.items[i + 1] i += 1 a_node.numberOfKeys -= 1 else: left = self.get_node(a_node.children[i]) right = self.get_node(a_node.children[i + 1]) if left.numberOfKeys >= self.degree: a_node.items[i] = self.get_right_most(left) elif right.numberOfKeys >= self.degree: a_node.items[i] = self.get_right_most(right) else: k = left.numberOfKeys left.items[left.numberOfKeys] = an_item left.numberOfKeys += 1 for j in range(0, right.numberOfKeys): left.items[left.numberOfKeys] = right.items[j] left.numberOfKeys += 1 del self.nodes[right.get_index()] for j in range(i, a_node.numberOfKeys - 1): a_node.items[j] = a_node.items[j + 1] a_node.children[j + 1] = a_node.children[j + 2] a_node.numberOfKeys -= 1 if a_node.numberOfKeys == 0: del self.nodes[a_node.get_index()] self.set_root_node(left) self.delete_in_node(left, an_item, {'found': True, 'fileIndex': left.index, 'nodeIndex': k}) else: i = 0 while i < a_node.numberOfKeys and self.get_node(a_node.children[i]).search(self, an_item)['found'] is False: i += 1 c_node = self.get_node(a_node.children[i]) if c_node.numberOfKeys < self.degree: j = i - 1 while j < i + 2 and self.get_node(a_node.children[j]).numberOfKeys < self.degree: j += 1 if j == i - 1: sNode = self.get_node(a_node.children[j]) k = c_node.numberOfKeys while k > 0: c_node.items[k] = c_node.items[k - 1] c_node.children[k + 1] = c_node.children[k] k -= 1 c_node.children[1] = c_node.children[0] c_node.items[0] = a_node.items[i - 1] c_node.children[0] = sNode.children[sNode.numberOfKeys] c_node.numberOfKeys += 1 a_node.items[i - 1] = sNode.items[sNode.numberOfKeys - 1] sNode.numberOfKeys -= 1 elif j == i + 1: sNode = self.get_node(a_node.children[j]) c_node.items[c_node.numberOfKeys] = a_node.items[i] c_node.children[c_node.numberOfKeys + 1] = sNode.children[0] a_node.items[i] = sNode.items[0] for k in range(0, sNode.numberOfKeys): sNode.items[k] = sNode.items[k + 1] sNode.children[k] = sNode.children[k + 1] sNode.children[k] = sNode.children[k + 1] sNode.numberOfKeys -= 1 else: j = i + 1 sNode = self.get_node(a_node.children[j]) c_node.items[c_node.numberOfKeys] = a_node.items[i] c_node.numberOfKeys += 1 for k in range(0, sNode.numberOfKeys): c_node.items[c_node.numberOfKeys] = sNode.items[k] c_node.numberOfKeys += 1 del self.nodes[sNode.index] for k in range(i, a_node.numberOfKeys - 1): a_node.items[i] = a_node.items[i + 1] a_node.children[i + 1] = a_node.items[i + 2] a_node.numberOfKeys -= 1 if a_node.numberOfKeys == 0: del self.nodes[a_node.index] self.set_root_node(c_node) self.delete_in_node(c_node, an_item, c_node.search(self, an_item)) def get_right_most(self, aNode): if aNode.children[aNode.numberOfKeys] is None: upItem = aNode.items[aNode.numberOfKeys - 1] self.delete_in_node(aNode, upItem, {'found': True, 'fileIndex': aNode.index, 'nodeIndex': aNode.numberOfKeys - 1}) return upItem else: return self.get_right_most(self.get_node(aNode.children[aNode.numberOfKeys])) def set_root_node(self, r): self.rootNode = r self.rootIndex = self.rootNode.get_index() def get_node(self, index): return self.nodes[index] def get_free_node(self): new_node = BTreeNode(self.degree) index = self.get_free_index() new_node.set_index(index) self.write_at(index, new_node) return new_node def get_free_index(self): self.freeIndex += 1 return self.freeIndex - 1 def write_at(self, index, a_node): self.nodes[index] = a_node # Value in Node class Item(): def __init__(self, k, v): self.k = k self.v = v def __gt__(self, other): if self.k > other.k: return True else: return False def __ge__(self, other): if self.k >= other.k: return True else: return False def __eq__(self, other): if self.k == other.k: return True else: return False def __le__(self, other): if self.k <= other.k: return True else: return False def __lt__(self, other): if self.k < other.k: return True else: return False # For Test def b_tree_main(): path = "last_data.csv" data = pd.read_csv(path) b = BTree(2) for i in range(data.shape[0]): b.insert(Item(data.ix[i, 0], data.ix[i, 1])) pos = b.predict(30310) print(pos) if __name__ == '__main__': b_tree_main()
en
0.694707
# BTree Index with Python # Node in BTree # BTree Class # Value in Node # For Test
3.243913
3
mep/people/tests/test_people_migrations.py
making-books-ren-today/test_eval_3_shxco
0
6628311
import pytest from mep.accounts.tests.test_accounts_migrations import TestMigrations @pytest.mark.last class TestPersonGenerateSlugs(TestMigrations): app = 'people' migrate_from = '0015_add_person_optional_slug' migrate_to = '0017_person_require_unique_slugs' def setUpBeforeMigration(self, apps): Person = apps.get_model('people', 'Person') self.Person = Person # create people to test slug logic # - unique last name self.hemingway = Person.objects.create(sort_name='<NAME>') # variants in special characters self.erna = Person.objects.create(sort_name='<NAME>') self.alfred = Person.objects.create(sort_name='<NAME>') # variants in case self.destaing1 = Person.objects.create(sort_name="D'Estaing") self.destaing2 = Person.objects.create(sort_name="d'Estaing") # multiples with no last name self.adams1 = Person.objects.create(sort_name="Adams") self.adams2 = Person.objects.create(sort_name="Adams") self.adams3 = Person.objects.create(sort_name="Adams") self.adams4 = Person.objects.create(sort_name="Adams") def test_slugs(self): # slugs should be unique - guaranteed by 0017 # get fresh copies of records to see changes hemingway = self.Person.objects.get(pk=self.hemingway.pk) # lastname only if sufficient assert hemingway.slug == 'hemingway' # group Dö/Dö properly erna = self.Person.objects.get(pk=self.erna.pk) assert erna.slug == 'doblin-erna-reiss' alfred = self.Person.objects.get(pk=self.alfred.pk) assert alfred.slug == 'doblin-alfred' # group upper/lowercase properly destaing1 = self.Person.objects.get(pk=self.destaing1.pk) assert destaing1.slug == 'destaing' destaing2 = self.Person.objects.get(pk=self.destaing2.pk) assert destaing2.slug == 'destaing-2' # multiples adams1 = self.Person.objects.get(pk=self.adams1.pk) adams2 = self.Person.objects.get(pk=self.adams2.pk) adams3 = self.Person.objects.get(pk=self.adams3.pk) adams4 = self.Person.objects.get(pk=self.adams4.pk) assert adams1.slug == 'adams' assert adams2.slug == 'adams-2' assert adams3.slug == 'adams-3' assert adams4.slug == 'adams-4'
import pytest from mep.accounts.tests.test_accounts_migrations import TestMigrations @pytest.mark.last class TestPersonGenerateSlugs(TestMigrations): app = 'people' migrate_from = '0015_add_person_optional_slug' migrate_to = '0017_person_require_unique_slugs' def setUpBeforeMigration(self, apps): Person = apps.get_model('people', 'Person') self.Person = Person # create people to test slug logic # - unique last name self.hemingway = Person.objects.create(sort_name='<NAME>') # variants in special characters self.erna = Person.objects.create(sort_name='<NAME>') self.alfred = Person.objects.create(sort_name='<NAME>') # variants in case self.destaing1 = Person.objects.create(sort_name="D'Estaing") self.destaing2 = Person.objects.create(sort_name="d'Estaing") # multiples with no last name self.adams1 = Person.objects.create(sort_name="Adams") self.adams2 = Person.objects.create(sort_name="Adams") self.adams3 = Person.objects.create(sort_name="Adams") self.adams4 = Person.objects.create(sort_name="Adams") def test_slugs(self): # slugs should be unique - guaranteed by 0017 # get fresh copies of records to see changes hemingway = self.Person.objects.get(pk=self.hemingway.pk) # lastname only if sufficient assert hemingway.slug == 'hemingway' # group Dö/Dö properly erna = self.Person.objects.get(pk=self.erna.pk) assert erna.slug == 'doblin-erna-reiss' alfred = self.Person.objects.get(pk=self.alfred.pk) assert alfred.slug == 'doblin-alfred' # group upper/lowercase properly destaing1 = self.Person.objects.get(pk=self.destaing1.pk) assert destaing1.slug == 'destaing' destaing2 = self.Person.objects.get(pk=self.destaing2.pk) assert destaing2.slug == 'destaing-2' # multiples adams1 = self.Person.objects.get(pk=self.adams1.pk) adams2 = self.Person.objects.get(pk=self.adams2.pk) adams3 = self.Person.objects.get(pk=self.adams3.pk) adams4 = self.Person.objects.get(pk=self.adams4.pk) assert adams1.slug == 'adams' assert adams2.slug == 'adams-2' assert adams3.slug == 'adams-3' assert adams4.slug == 'adams-4'
en
0.641263
# create people to test slug logic # - unique last name # variants in special characters # variants in case # multiples with no last name # slugs should be unique - guaranteed by 0017 # get fresh copies of records to see changes # lastname only if sufficient # group Dö/Dö properly # group upper/lowercase properly # multiples
2.336693
2
fffw/types.py
tumb1er/fffw
4
6628312
<reponame>tumb1er/fffw try: from typing import Literal except ImportError: # pragma: no cover from typing_extensions import Literal # type: ignore __all__ = ['Literal']
try: from typing import Literal except ImportError: # pragma: no cover from typing_extensions import Literal # type: ignore __all__ = ['Literal']
en
0.333062
# pragma: no cover # type: ignore
1.169085
1
cynetworkx/algorithms/community/tests/test_kernighan_lin.py
Viech/cynetworkx
12
6628313
# -*- encoding: utf-8 -*- # test_kernighan_lin.py - unit tests for Kernighan–Lin bipartition algorithm # # Copyright 2011 <NAME> <<EMAIL>>. # Copyright 2011 <NAME> <<EMAIL>>. # Copyright 2015 NetworkX developers. # # This file is part of NetworkX. # # NetworkX is distributed under a BSD license; see LICENSE.txt for more # information. """Unit tests for the :mod:`cynetworkx.algorithms.community.kernighan_lin` module. """ from nose.tools import assert_equal from nose.tools import raises import cynetworkx as nx from cynetworkx.algorithms.community import kernighan_lin_bisection def assert_partition_equal(x, y): assert_equal(set(map(frozenset, x)), set(map(frozenset, y))) def test_partition(): G = nx.barbell_graph(3, 0) C = kernighan_lin_bisection(G) assert_partition_equal(C, [{0, 1, 2}, {3, 4, 5}]) @raises(nx.NetworkXError) def test_non_disjoint_partition(): G = nx.barbell_graph(3, 0) partition = ({0, 1, 2}, {2, 3, 4, 5}) kernighan_lin_bisection(G, partition) @raises(nx.NetworkXError) def test_too_many_blocks(): G = nx.barbell_graph(3, 0) partition = ({0, 1}, {2}, {3, 4, 5}) kernighan_lin_bisection(G, partition) def test_multigraph(): G = nx.cycle_graph(4) M = nx.MultiGraph(G.edges()) M.add_edges_from(G.edges()) M.remove_edge(1, 2) A, B = kernighan_lin_bisection(M) assert_partition_equal([A, B], [{0, 1}, {2, 3}])
# -*- encoding: utf-8 -*- # test_kernighan_lin.py - unit tests for Kernighan–Lin bipartition algorithm # # Copyright 2011 <NAME> <<EMAIL>>. # Copyright 2011 <NAME> <<EMAIL>>. # Copyright 2015 NetworkX developers. # # This file is part of NetworkX. # # NetworkX is distributed under a BSD license; see LICENSE.txt for more # information. """Unit tests for the :mod:`cynetworkx.algorithms.community.kernighan_lin` module. """ from nose.tools import assert_equal from nose.tools import raises import cynetworkx as nx from cynetworkx.algorithms.community import kernighan_lin_bisection def assert_partition_equal(x, y): assert_equal(set(map(frozenset, x)), set(map(frozenset, y))) def test_partition(): G = nx.barbell_graph(3, 0) C = kernighan_lin_bisection(G) assert_partition_equal(C, [{0, 1, 2}, {3, 4, 5}]) @raises(nx.NetworkXError) def test_non_disjoint_partition(): G = nx.barbell_graph(3, 0) partition = ({0, 1, 2}, {2, 3, 4, 5}) kernighan_lin_bisection(G, partition) @raises(nx.NetworkXError) def test_too_many_blocks(): G = nx.barbell_graph(3, 0) partition = ({0, 1}, {2}, {3, 4, 5}) kernighan_lin_bisection(G, partition) def test_multigraph(): G = nx.cycle_graph(4) M = nx.MultiGraph(G.edges()) M.add_edges_from(G.edges()) M.remove_edge(1, 2) A, B = kernighan_lin_bisection(M) assert_partition_equal([A, B], [{0, 1}, {2, 3}])
en
0.652312
# -*- encoding: utf-8 -*- # test_kernighan_lin.py - unit tests for Kernighan–Lin bipartition algorithm # # Copyright 2011 <NAME> <<EMAIL>>. # Copyright 2011 <NAME> <<EMAIL>>. # Copyright 2015 NetworkX developers. # # This file is part of NetworkX. # # NetworkX is distributed under a BSD license; see LICENSE.txt for more # information. Unit tests for the :mod:`cynetworkx.algorithms.community.kernighan_lin` module.
2.350918
2
tests/app/guild_helper_bot/test_guild.py
ricardochaves/chat-wars-database
1
6628314
<filename>tests/app/guild_helper_bot/test_guild.py<gh_stars>1-10 import uuid from django.db import IntegrityError from django.test import TestCase from chat_wars_database.app.guild_helper_bot.business.guild import create_guild from chat_wars_database.app.guild_helper_bot.business.guild import create_invite_member_link from chat_wars_database.app.guild_helper_bot.business.guild import delete_guild from chat_wars_database.app.guild_helper_bot.business.guild import update_guild_name from chat_wars_database.app.guild_helper_bot.business.guild import use_invited_id_link from chat_wars_database.app.guild_helper_bot.business.telegram_user import create_telegram_user_if_need from chat_wars_database.app.guild_helper_bot.models import Guild from chat_wars_database.app.guild_helper_bot.models import InvitationLink from chat_wars_database.app.guild_helper_bot.models import UserGuild class TestGuild(TestCase): def setUp(self) -> None: self.guild_name = "test_name" self.telegram_user = create_telegram_user_if_need(1234, "test_name", "test_user_name") self.telegram_user_2 = create_telegram_user_if_need(567, "test_name", "test_user_name") def test_should_create_new_guild(self): guild = create_guild(self.guild_name, self.telegram_user) self.assertEqual(Guild.objects.count(), 1) self.assertEqual(guild.name, self.guild_name) self.assertEqual(guild.captain.telegram_id, self.telegram_user.telegram_id) self.assertEqual(UserGuild.objects.filter(guild=guild).count(), 1) def test_should_create_guild_raise_integrity_error_exists(self): create_guild(self.guild_name, self.telegram_user) with self.assertRaises(IntegrityError): create_guild(self.guild_name, self.telegram_user) def test_should_delete_guild(self): create_guild(self.guild_name, self.telegram_user) self.assertEqual(Guild.objects.filter(name__exact=self.guild_name).count(), 1) delete_guild(self.telegram_user) self.assertEqual(Guild.objects.filter(name__exact=self.guild_name).count(), 0) def test_should_update_guild_name(self): create_guild(self.guild_name, self.telegram_user) guild = update_guild_name("new_name", self.telegram_user) self.assertEqual(Guild.objects.count(), 1) self.assertEqual(guild.name, "new_name") self.assertEqual(guild.captain.telegram_id, self.telegram_user.telegram_id) def test_should_update_guild_name_raise_Guild_DoesNotExist_when_invalid_user_is_used(self): create_guild(self.guild_name, self.telegram_user) with self.assertRaises(Guild.DoesNotExist): guild = update_guild_name("new_name", self.telegram_user_2) def test_should_create_invite_member_link(self): create_guild(self.guild_name, self.telegram_user) link = create_invite_member_link(self.telegram_user) self.assertEqual(link.guild.name, self.guild_name) def test_should_create_invite_member_link_raise_Guild_DoesNotExist_when_invalid_user_is_used(self): create_guild(self.guild_name, self.telegram_user) with self.assertRaises(Guild.DoesNotExist): create_invite_member_link(self.telegram_user_2) def test_should_use_invited_id_link(self): guild = create_guild(self.guild_name, self.telegram_user) link = create_invite_member_link(self.telegram_user) use_invited_id_link(self.telegram_user_2, link.link_id) self.assertEqual(UserGuild.objects.filter(guild=guild).count(), 2) self.assertEqual(InvitationLink.objects.count(), 0) def test_should_ignore_invalid_link(self): guild = create_guild(self.guild_name, self.telegram_user) use_invited_id_link(self.telegram_user_2, str(uuid.uuid4())) self.assertEqual(UserGuild.objects.filter(guild=guild).count(), 1) # def test_should_(self): # pass # # def test_should_(self): # pass
<filename>tests/app/guild_helper_bot/test_guild.py<gh_stars>1-10 import uuid from django.db import IntegrityError from django.test import TestCase from chat_wars_database.app.guild_helper_bot.business.guild import create_guild from chat_wars_database.app.guild_helper_bot.business.guild import create_invite_member_link from chat_wars_database.app.guild_helper_bot.business.guild import delete_guild from chat_wars_database.app.guild_helper_bot.business.guild import update_guild_name from chat_wars_database.app.guild_helper_bot.business.guild import use_invited_id_link from chat_wars_database.app.guild_helper_bot.business.telegram_user import create_telegram_user_if_need from chat_wars_database.app.guild_helper_bot.models import Guild from chat_wars_database.app.guild_helper_bot.models import InvitationLink from chat_wars_database.app.guild_helper_bot.models import UserGuild class TestGuild(TestCase): def setUp(self) -> None: self.guild_name = "test_name" self.telegram_user = create_telegram_user_if_need(1234, "test_name", "test_user_name") self.telegram_user_2 = create_telegram_user_if_need(567, "test_name", "test_user_name") def test_should_create_new_guild(self): guild = create_guild(self.guild_name, self.telegram_user) self.assertEqual(Guild.objects.count(), 1) self.assertEqual(guild.name, self.guild_name) self.assertEqual(guild.captain.telegram_id, self.telegram_user.telegram_id) self.assertEqual(UserGuild.objects.filter(guild=guild).count(), 1) def test_should_create_guild_raise_integrity_error_exists(self): create_guild(self.guild_name, self.telegram_user) with self.assertRaises(IntegrityError): create_guild(self.guild_name, self.telegram_user) def test_should_delete_guild(self): create_guild(self.guild_name, self.telegram_user) self.assertEqual(Guild.objects.filter(name__exact=self.guild_name).count(), 1) delete_guild(self.telegram_user) self.assertEqual(Guild.objects.filter(name__exact=self.guild_name).count(), 0) def test_should_update_guild_name(self): create_guild(self.guild_name, self.telegram_user) guild = update_guild_name("new_name", self.telegram_user) self.assertEqual(Guild.objects.count(), 1) self.assertEqual(guild.name, "new_name") self.assertEqual(guild.captain.telegram_id, self.telegram_user.telegram_id) def test_should_update_guild_name_raise_Guild_DoesNotExist_when_invalid_user_is_used(self): create_guild(self.guild_name, self.telegram_user) with self.assertRaises(Guild.DoesNotExist): guild = update_guild_name("new_name", self.telegram_user_2) def test_should_create_invite_member_link(self): create_guild(self.guild_name, self.telegram_user) link = create_invite_member_link(self.telegram_user) self.assertEqual(link.guild.name, self.guild_name) def test_should_create_invite_member_link_raise_Guild_DoesNotExist_when_invalid_user_is_used(self): create_guild(self.guild_name, self.telegram_user) with self.assertRaises(Guild.DoesNotExist): create_invite_member_link(self.telegram_user_2) def test_should_use_invited_id_link(self): guild = create_guild(self.guild_name, self.telegram_user) link = create_invite_member_link(self.telegram_user) use_invited_id_link(self.telegram_user_2, link.link_id) self.assertEqual(UserGuild.objects.filter(guild=guild).count(), 2) self.assertEqual(InvitationLink.objects.count(), 0) def test_should_ignore_invalid_link(self): guild = create_guild(self.guild_name, self.telegram_user) use_invited_id_link(self.telegram_user_2, str(uuid.uuid4())) self.assertEqual(UserGuild.objects.filter(guild=guild).count(), 1) # def test_should_(self): # pass # # def test_should_(self): # pass
en
0.678375
# def test_should_(self): # pass # # def test_should_(self): # pass
2.325888
2
todoapp/admin.py
Bridgit-wairimu/Brii-to-do
0
6628315
from django.contrib import admin from .models import Tasks,Profile # Register your models here. admin.site.register(Tasks) admin.site.register(Profile)
from django.contrib import admin from .models import Tasks,Profile # Register your models here. admin.site.register(Tasks) admin.site.register(Profile)
en
0.968259
# Register your models here.
1.340332
1
tests/training/test_replay.py
Mathieu4141/avalanche
3
6628316
<filename>tests/training/test_replay.py import unittest from typing import List, Dict from unittest.mock import MagicMock import torch from torch import tensor, Tensor, zeros from torch.nn import CrossEntropyLoss, Module, Identity from torch.optim import SGD from avalanche.benchmarks.utils import AvalancheDataset, AvalancheDatasetType, \ AvalancheTensorDataset from avalanche.models import SimpleMLP from avalanche.training.plugins import ExperienceBalancedStoragePolicy, \ ClassBalancedStoragePolicy, ReplayPlugin from avalanche.training.plugins.replay import ClassExemplarsSelectionStrategy, \ HerdingSelectionStrategy, ClosestToCenterSelectionStrategy from avalanche.training.strategies import Naive, BaseStrategy from tests.unit_tests_utils import get_fast_scenario class ReplayTest(unittest.TestCase): def test_replay_balanced_memory(self): mem_size = 25 policies = [None, ExperienceBalancedStoragePolicy({}, mem_size=mem_size), ClassBalancedStoragePolicy({}, mem_size=mem_size)] for policy in policies: self._test_replay_balanced_memory(policy, mem_size) def _test_replay_balanced_memory(self, storage_policy, mem_size): scenario = get_fast_scenario(use_task_labels=True) model = SimpleMLP(input_size=6, hidden_size=10) replayPlugin = ReplayPlugin(mem_size=mem_size, storage_policy=storage_policy) cl_strategy = Naive( model, SGD(model.parameters(), lr=0.001, momentum=0.9, weight_decay=0.001), CrossEntropyLoss(), train_mb_size=32, train_epochs=1, eval_mb_size=100, plugins=[replayPlugin] ) n_seen_data = 0 for step in scenario.train_stream: n_seen_data += len(step.dataset) mem_fill = min(mem_size, n_seen_data) cl_strategy.train(step) ext_mem = replayPlugin.ext_mem lengths = [] for task_id in ext_mem.keys(): lengths.append(len(ext_mem[task_id])) self.assertEqual(sum(lengths), mem_fill) # Always fully filled def test_balancing(self): p1 = ExperienceBalancedStoragePolicy({}, 100, adaptive_size=True) p2 = ClassBalancedStoragePolicy({}, 100, adaptive_size=True) for policy in [p1, p2]: self.assert_balancing(policy) def assert_balancing(self, policy): ext_mem = policy.ext_mem scenario = get_fast_scenario(use_task_labels=True) replay = ReplayPlugin(mem_size=100, storage_policy=policy) model = SimpleMLP(num_classes=scenario.n_classes) # CREATE THE STRATEGY INSTANCE (NAIVE) cl_strategy = Naive(model, SGD(model.parameters(), lr=0.001), CrossEntropyLoss(), train_mb_size=100, train_epochs=0, eval_mb_size=100, plugins=[replay], evaluator=None) for exp in scenario.train_stream: cl_strategy.train(exp) print(list(ext_mem.keys()), [len(el) for el in ext_mem.values()]) # buffer size should equal self.mem_size if data is large enough len_tot = sum([len(el) for el in ext_mem.values()]) assert len_tot == policy.mem_size class ClassBalancePolicyTest(unittest.TestCase): def setUp(self) -> None: self.memory = {} self.policy = ClassBalancedStoragePolicy(self.memory, mem_size=4) def test_store_alone_with_enough_memory(self): order = [2, 0, 1, 3] self.observe_exemplars({0: list(range(4))}, selection_order=order) self.assert_memory_equal({0: order}) def test_store_alone_without_enough_memory(self): order = [6, 4, 2, 0, 1, 3, 5] self.observe_exemplars({0: list(range(7))}, selection_order=order) self.assert_memory_equal({0: order[:4]}) def test_store_multiple_with_enough_memory(self): self.observe_exemplars({0: [0, 1], 1: [10, 11]}, selection_order=[1, 0]) self.assert_memory_equal({0: [1, 0], 1: [11, 10]}) def test_store_multiple_without_enough_memory(self): self.observe_exemplars({0: [0, 1, 2], 1: [10, 11, 12]}, selection_order=[2, 0, 1]) self.assert_memory_equal({0: [2, 0], 1: [12, 10]}) def test_sequence(self): # 1st observation self.observe_exemplars({0: [0, 1], 1: [10, 11]}, selection_order=[1, 0]) self.assert_memory_equal({0: [1, 0], 1: [11, 10]}) # 2nd observation self.observe_exemplars({2: [20, 21, 22], 3: [30, 31, 32]}, selection_order=[2, 1, 0]) self.assert_memory_equal({0: [1], 1: [11], 2: [22], 3: [32]}) def observe_exemplars(self, class2exemplars: Dict[int, List[int]], selection_order: List[int]): self.policy.selection_strategy = FixedSelectionStrategy(selection_order) x = tensor( [i for exemplars in class2exemplars.values() for i in exemplars]) y = tensor( [class_id for class_id, exemplars in class2exemplars.items() for _ in exemplars]).long() dataset = AvalancheTensorDataset( x, y, dataset_type=AvalancheDatasetType.CLASSIFICATION) self.policy(MagicMock(experience=MagicMock(dataset=dataset))) def assert_memory_equal(self, class2exemplars: Dict[int, List[int]]): self.assertEqual(class2exemplars, {class_id: [x.tolist() for x, *_ in memory] for class_id, memory in self.memory.items()}) class SelectionStrategyTest(unittest.TestCase): def test(self): # Given model = AbsModel() herding = HerdingSelectionStrategy(model, "features") closest_to_center = ClosestToCenterSelectionStrategy(model, "features") # When # Features are [[0], [4], [5]] # Center is [3] dataset = AvalancheTensorDataset( tensor([0, -4, 5]).float(), zeros(3), dataset_type=AvalancheDatasetType.CLASSIFICATION ) strategy = MagicMock(device="cpu", eval_mb_size=8) # Then # Herding: # 1. At first pass, we select the -4 (at index 1) # because it is the closest ([4]) to the center in feature space # 2. At second pass, we select 0 (of index 0) # because the center will be [2], closest to [3] than the center # obtained if we were to select 5 ([4.5]) # 3. Finally we select the last remaining exemplar self.assertSequenceEqual([1, 0, 2], herding.make_sorted_indices(strategy, dataset)) # Closest to center # -4 (index 1) is the closest to the center in feature space. # Then 5 (index 2) is closest than 0 (index 0) self.assertSequenceEqual([1, 2, 0], closest_to_center.make_sorted_indices(strategy, dataset)) class AbsModel(Module): """Fake model, that simply compute the absolute value of the inputs""" def __init__(self): super().__init__() self.features = AbsLayer() self.classifier = Identity() def forward(self, x: Tensor) -> Tensor: x = self.features(x) x = self.classifier(x) return x class AbsLayer(Module): def forward(self, x: Tensor) -> Tensor: return torch.abs(x).reshape((-1, 1)) class FixedSelectionStrategy(ClassExemplarsSelectionStrategy): """This is a fake strategy used for testing the policy behavior""" def __init__(self, indices: List[int]): self.indices = indices def make_sorted_indices(self, strategy: "BaseStrategy", data: AvalancheDataset) -> List[int]: return self.indices
<filename>tests/training/test_replay.py import unittest from typing import List, Dict from unittest.mock import MagicMock import torch from torch import tensor, Tensor, zeros from torch.nn import CrossEntropyLoss, Module, Identity from torch.optim import SGD from avalanche.benchmarks.utils import AvalancheDataset, AvalancheDatasetType, \ AvalancheTensorDataset from avalanche.models import SimpleMLP from avalanche.training.plugins import ExperienceBalancedStoragePolicy, \ ClassBalancedStoragePolicy, ReplayPlugin from avalanche.training.plugins.replay import ClassExemplarsSelectionStrategy, \ HerdingSelectionStrategy, ClosestToCenterSelectionStrategy from avalanche.training.strategies import Naive, BaseStrategy from tests.unit_tests_utils import get_fast_scenario class ReplayTest(unittest.TestCase): def test_replay_balanced_memory(self): mem_size = 25 policies = [None, ExperienceBalancedStoragePolicy({}, mem_size=mem_size), ClassBalancedStoragePolicy({}, mem_size=mem_size)] for policy in policies: self._test_replay_balanced_memory(policy, mem_size) def _test_replay_balanced_memory(self, storage_policy, mem_size): scenario = get_fast_scenario(use_task_labels=True) model = SimpleMLP(input_size=6, hidden_size=10) replayPlugin = ReplayPlugin(mem_size=mem_size, storage_policy=storage_policy) cl_strategy = Naive( model, SGD(model.parameters(), lr=0.001, momentum=0.9, weight_decay=0.001), CrossEntropyLoss(), train_mb_size=32, train_epochs=1, eval_mb_size=100, plugins=[replayPlugin] ) n_seen_data = 0 for step in scenario.train_stream: n_seen_data += len(step.dataset) mem_fill = min(mem_size, n_seen_data) cl_strategy.train(step) ext_mem = replayPlugin.ext_mem lengths = [] for task_id in ext_mem.keys(): lengths.append(len(ext_mem[task_id])) self.assertEqual(sum(lengths), mem_fill) # Always fully filled def test_balancing(self): p1 = ExperienceBalancedStoragePolicy({}, 100, adaptive_size=True) p2 = ClassBalancedStoragePolicy({}, 100, adaptive_size=True) for policy in [p1, p2]: self.assert_balancing(policy) def assert_balancing(self, policy): ext_mem = policy.ext_mem scenario = get_fast_scenario(use_task_labels=True) replay = ReplayPlugin(mem_size=100, storage_policy=policy) model = SimpleMLP(num_classes=scenario.n_classes) # CREATE THE STRATEGY INSTANCE (NAIVE) cl_strategy = Naive(model, SGD(model.parameters(), lr=0.001), CrossEntropyLoss(), train_mb_size=100, train_epochs=0, eval_mb_size=100, plugins=[replay], evaluator=None) for exp in scenario.train_stream: cl_strategy.train(exp) print(list(ext_mem.keys()), [len(el) for el in ext_mem.values()]) # buffer size should equal self.mem_size if data is large enough len_tot = sum([len(el) for el in ext_mem.values()]) assert len_tot == policy.mem_size class ClassBalancePolicyTest(unittest.TestCase): def setUp(self) -> None: self.memory = {} self.policy = ClassBalancedStoragePolicy(self.memory, mem_size=4) def test_store_alone_with_enough_memory(self): order = [2, 0, 1, 3] self.observe_exemplars({0: list(range(4))}, selection_order=order) self.assert_memory_equal({0: order}) def test_store_alone_without_enough_memory(self): order = [6, 4, 2, 0, 1, 3, 5] self.observe_exemplars({0: list(range(7))}, selection_order=order) self.assert_memory_equal({0: order[:4]}) def test_store_multiple_with_enough_memory(self): self.observe_exemplars({0: [0, 1], 1: [10, 11]}, selection_order=[1, 0]) self.assert_memory_equal({0: [1, 0], 1: [11, 10]}) def test_store_multiple_without_enough_memory(self): self.observe_exemplars({0: [0, 1, 2], 1: [10, 11, 12]}, selection_order=[2, 0, 1]) self.assert_memory_equal({0: [2, 0], 1: [12, 10]}) def test_sequence(self): # 1st observation self.observe_exemplars({0: [0, 1], 1: [10, 11]}, selection_order=[1, 0]) self.assert_memory_equal({0: [1, 0], 1: [11, 10]}) # 2nd observation self.observe_exemplars({2: [20, 21, 22], 3: [30, 31, 32]}, selection_order=[2, 1, 0]) self.assert_memory_equal({0: [1], 1: [11], 2: [22], 3: [32]}) def observe_exemplars(self, class2exemplars: Dict[int, List[int]], selection_order: List[int]): self.policy.selection_strategy = FixedSelectionStrategy(selection_order) x = tensor( [i for exemplars in class2exemplars.values() for i in exemplars]) y = tensor( [class_id for class_id, exemplars in class2exemplars.items() for _ in exemplars]).long() dataset = AvalancheTensorDataset( x, y, dataset_type=AvalancheDatasetType.CLASSIFICATION) self.policy(MagicMock(experience=MagicMock(dataset=dataset))) def assert_memory_equal(self, class2exemplars: Dict[int, List[int]]): self.assertEqual(class2exemplars, {class_id: [x.tolist() for x, *_ in memory] for class_id, memory in self.memory.items()}) class SelectionStrategyTest(unittest.TestCase): def test(self): # Given model = AbsModel() herding = HerdingSelectionStrategy(model, "features") closest_to_center = ClosestToCenterSelectionStrategy(model, "features") # When # Features are [[0], [4], [5]] # Center is [3] dataset = AvalancheTensorDataset( tensor([0, -4, 5]).float(), zeros(3), dataset_type=AvalancheDatasetType.CLASSIFICATION ) strategy = MagicMock(device="cpu", eval_mb_size=8) # Then # Herding: # 1. At first pass, we select the -4 (at index 1) # because it is the closest ([4]) to the center in feature space # 2. At second pass, we select 0 (of index 0) # because the center will be [2], closest to [3] than the center # obtained if we were to select 5 ([4.5]) # 3. Finally we select the last remaining exemplar self.assertSequenceEqual([1, 0, 2], herding.make_sorted_indices(strategy, dataset)) # Closest to center # -4 (index 1) is the closest to the center in feature space. # Then 5 (index 2) is closest than 0 (index 0) self.assertSequenceEqual([1, 2, 0], closest_to_center.make_sorted_indices(strategy, dataset)) class AbsModel(Module): """Fake model, that simply compute the absolute value of the inputs""" def __init__(self): super().__init__() self.features = AbsLayer() self.classifier = Identity() def forward(self, x: Tensor) -> Tensor: x = self.features(x) x = self.classifier(x) return x class AbsLayer(Module): def forward(self, x: Tensor) -> Tensor: return torch.abs(x).reshape((-1, 1)) class FixedSelectionStrategy(ClassExemplarsSelectionStrategy): """This is a fake strategy used for testing the policy behavior""" def __init__(self, indices: List[int]): self.indices = indices def make_sorted_indices(self, strategy: "BaseStrategy", data: AvalancheDataset) -> List[int]: return self.indices
en
0.875681
# Always fully filled # CREATE THE STRATEGY INSTANCE (NAIVE) # buffer size should equal self.mem_size if data is large enough # 1st observation # 2nd observation # Given # When # Features are [[0], [4], [5]] # Center is [3] # Then # Herding: # 1. At first pass, we select the -4 (at index 1) # because it is the closest ([4]) to the center in feature space # 2. At second pass, we select 0 (of index 0) # because the center will be [2], closest to [3] than the center # obtained if we were to select 5 ([4.5]) # 3. Finally we select the last remaining exemplar # Closest to center # -4 (index 1) is the closest to the center in feature space. # Then 5 (index 2) is closest than 0 (index 0) Fake model, that simply compute the absolute value of the inputs This is a fake strategy used for testing the policy behavior
2.146023
2
labdevices/applied_motion_products.py
jkrauth/labdevices
0
6628317
""" For communication with devices from Applied Motion Products. The IP can be set via a small wheel (S1) on the device itself. We used the windows software 'STF Configurator' from Applied Motion Products for the first configuration of the controller and to give it its IP address in our local subnet. File name: applied_motion_products.py Author: <NAME> Date created: 2020/09/02 Python Version: 3.7 """ import socket from labdevices._mock.applied_motion_products import SocketDummy # The ports for communication. We usually use UDP TCP_PORT = 7776 UDP_PORT = 7775 # IP address of host pc. # If 0.0.0.0: Communication on all ethernet interfaces. # When instantiating the class it is better to use # the specific local IP address of that PC. HOST_IP = '0.0.0.0' HOST_PORT = 15005 ERROR_CODES = { 0x0000: 'No alarms', 0x0001: 'Position Limit', 0x0002: 'CCW Limit', 0x0004: 'CW Limit', 0x0008: 'Over Temp', 0x0010: 'Internal Voltage', 0x0020: 'Over Voltage', 0x0040: 'Under Voltage', 0x0080: 'Over Current', 0x0100: 'Open Motor Winding', 0x0200: 'Bad Encoder', 0x0400: 'Comm Error', 0x0800: 'Bad Flash', 0x1000: 'No Move', 0x2000: '(not used)', 0x4000: 'Blank Q Segment', 0x8000: '(not used)', } STATUS_CODES = { 0x0000: 'Motor disabled', 0x0001: 'Motor enabled and in position', 0x0002: 'Sampling (for Quick Tuner)', 0x0004: 'Drive Fault (check Alarm Code)', 0x0008: 'In Position (motor is in position)', 0x0010: 'Moving (motor is moving)', 0x0020: 'Jogging (currently in jog mode)', 0x0040: 'Stopping (in the process of stopping from a stop command)', 0x0080: 'Waiting (for an input; executing a WI command)', 0x0100: 'Saving (parameter data is being saved)', 0x0200: 'Alarm present (check Alarm Code)', 0x0400: 'Homing (executing an SH command)', 0x0800: 'Waiting (for time; executing a WD or WT command)', 0x1000: 'Wizard running (Timing Wizard is running)', 0x2000: 'Checking encoder (Timing Wizard is running)', 0x4000: 'Q Program is running', 0x8000: 'Initializing (happens at power up)', } STEPS_PER_TURN = { # Gives the number of steps for a full # motor turn, given the microstep resolution # setting. 0: 200, 1: 400, 3: 2000, 4: 5000, 5: 10000, 6: 12800, 7: 18000, 8: 20000, 9: 21600, 10:25000, 11:25400, 12:25600, 13:36000, 14:50000, 15:50800, } class STF03D: """ Class for the STF03-D Stepper Motor Controllers. When using this class start to set the motor calibration with self.set_calibration() """ _header = bytes([0x00, 0x007]) _tail = bytes([0xD]) def __init__(self, device_ip: str, host_ip: str=HOST_IP, host_port: int=HOST_PORT, timeout: float=5): """ Arguments: device_ip -- IP address of device host_ip -- IP address of host, can be 0.0.0.0 host_port -- Port used by host timeout -- in seconds """ self.device_ip = device_ip self.host_ip = host_ip self.host_port = host_port self.timeout = timeout self._device = None # This is the calibration and it has to be set by self.set_calibration() self._units_per_motor_turn = None def initialize(self) -> None: """Establish connection to device.""" self._device = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self._device.bind((self.host_ip, self.host_port)) self._device.settimeout(self.timeout) print(f'Connected to rotary feedthrough with IP={self.device_ip}.') def close(self) -> None: """Close connection to device.""" if self._device is None: print('Device is already closed.') return self._device.close() print(f'Closed rotary feedthrough with IP={self.device_ip}.') @property def idn(self) -> str: """ Returns model and revision """ return self.query('MV') def write(self, cmd: str): """Send a message with the correct header and end characters""" to_send = self._header + cmd.encode() + self._tail # print(to_send) self._device.sendto(to_send, (self.device_ip, UDP_PORT)) def _read(self) -> str: """Read UDP message, decode, strip off header and end characters and return.""" respons_raw = self._device.recv(1024) # print(respons_raw) respons = respons_raw.decode() return respons[2:-1] def query(self, cmd: str) -> str: """ Query the device. """ self.write(cmd) return self._read() def _get_future_movement_value(self) -> float: """Request the distance by which the motor moves with the next relative move command, or the position to which the motor moves with the next absolute move command. """ steps = int(self.query('DI')[3:]) value = self._step_to_unit(steps) return value def _set_future_movement_value(self, value: float) -> None: """Set the distance by which the motor moves with the next relative move command, or the position to which the motor moves with the next absolute move command. value -- in units as defined by the calibration. """ steps = self._unit_to_step(value) # print(f'Move by/to {value} degrees, equiv. to {steps} steps.') _ = self.query(f'DI{steps}') def set_calibration(self, units_per_motor_turn: float) -> None: """ Arguments: units_per_motor_turn -- units could be degree or meter. Example: For a rotation stage with gear ratio 1/96 the conversion factor into degrees would be 360/96, For a linear stage it would be the lead value of the screw. """ self._units_per_motor_turn = units_per_motor_turn def get_alarm(self) -> list: """Reads back an equivalent hexadecimal value of the Alarm Code's 16-bit binary word and translates it into corresponding error messages. """ # Strip off the 'AL=' prefix respons = self.query('AL')[3:] # Convert hex string to integer alarm = int(respons, 16) error_list = [] if not alarm: error_list.append(ERROR_CODES[alarm]) else: for key, val in ERROR_CODES.items(): if key & alarm: error_list.append(val) return error_list def get_status(self) -> list: """Reads back an equivalent hexadecimal value of the Status Code's 16-bit binary word and translates it into corresponding status messages. """ # Strip off the 'SC=' prefix respons = self.query('SC')[3:] status = int(respons, 16) status_list = [] if not status: status_list.append(STATUS_CODES[status]) else: for key, val in STATUS_CODES.items(): if key & status: status_list.append(val) return status_list @property def is_moving(self) -> bool: """Ask for device movement status, return boolean.""" respons = self.query('SC')[3:] status = int(respons, 16) return bool(0x0010 & status) @property def microstep(self) -> int: """The microstep resolution of the drive. Allowed range is between [0 and 15] (default is 3) """ respons = self.query('MR')[3:] return int(respons) @microstep.setter def microstep(self, value: int) -> None: _ = self.query(f'MR{value}') @property def _conversion_factor(self) -> float: """This yields the steps/user-defined-unit ratio. The steps of the stepper motor depend on the microstep resolution setting. """ if self._units_per_motor_turn is None: raise Exception('Set calibration first') steps_per_motor_turn = STEPS_PER_TURN[self.microstep] steps_per_unit = float(steps_per_motor_turn) / float(self._units_per_motor_turn) return steps_per_unit def _step_to_unit(self, step: int) -> float: """Convert stepper motor steps into user-defined units.""" return float(step) / self._conversion_factor def _unit_to_step(self, value: float) -> int: """Convert value in user-defined units into steps of the stepper motor. Argument: value -- in user-defined units""" return int(round(value * self._conversion_factor)) @property def max_current(self) -> float: """ Set or request the maximum idle and change current limit. value -- in Ampere, max is 3 A """ return float(self.query('MC')[3:]) @max_current.setter def max_current(self, value: float): _ = self.query(f'MC{value}') @property def idle_current(self) -> float: """ Set or request the current the standing still situation. A good value seems to be 0.5 A. value -- in Ampere, max is given by self.max_current(). """ return float(self.query('CI')[3:]) @idle_current.setter def idle_current(self, value: float): _ = self.query(f'CI{value}') @property def change_current(self) -> float: """Set or request the current for moving the stepper motor. For not missing any steps that should be as high as possible, which in this case is 3 A. value -- in Ampere, max is given by self.max_current().""" return float(self.query('CC')[3:]) @change_current.setter def change_current(self, value: float): _ = self.query(f'CC{value}') def get_position(self) -> float: """Returns the current position in user-defined units.""" steps = int(self.query('SP')[3:]) print(f'Position in steps is: {steps}') return self._step_to_unit(steps) def reset_position(self) -> None: """Set current motor position to the new zero position.""" _ = self.query('SP0') def get_immediate_step(self) -> int: """This returns the calculated trajectory position, which is not always equal to the actual position. Units are stepper motor steps. """ respons = self.query('IP')[3:] position = int(respons, 16) return position @property def acceleration(self) -> float: """Sets or requests the acceleration used in point-to-point move commands. Argument: value -- in rps/s (a standard value is 1) """ return float(self.query('AC')[3:]) @acceleration.setter def acceleration(self, value: float): _ = self.query(f'AC{value}') @property def deceleration(self) -> float: """Sets or requests the deceleration used in point-to-point move commands Argument: value -- in rps/s (a standard value is 1) """ return float(self.query('DE')[3:]) @deceleration.setter def deceleration(self, value: float): _ = self.query(f'DE{value}') @property def speed(self) -> float: """Sets or requests shaft speed for point-to-point move commands Argument: value -- in rps (a standard value is 2) """ return float(self.query('VE')[3:]) @speed.setter def speed(self, value: float): _ = self.query(f'VE{value}') def move_relative(self, value: float) -> None: """Relative rotation of the feedthrough Argument: value -- in user-defined units """ self._set_future_movement_value(value) _ = self.query('FL') def move_absolute(self, position: float) -> None: """Rotate the feedthrough to a given position Argument: position -- in degrees """ self._set_future_movement_value(position) _ = self.query('FP') class STF03DDummy(STF03D): """Class for testing. Does not actually connect to any device.""" def initialize(self): """Establish connection to device.""" self._device = SocketDummy() self._device.bind((self.host_ip, self.host_port)) self._device.settimeout(self.timeout) print(f'Connected to rotary feedthrough with IP={self.device_ip}.') # class STF03DDummy: # """Class for testing. Does not actually connect to any device.""" # def __init__(self, device_ip, host_ip=HOST_IP, # host_port=HOST_PORT, timeout=5): # self.device_ip = device_ip # self.host_ip = host_ip # self.host_port = host_port # self.timeout = timeout # # Dummy parameters # self.position = 0 # self.accel = 1 # self.decel = 1 # self.velocity = 1 # def initialize(self): # pass # def close(self): # pass # def get_alarm_code(self): # return ['no alarms'] # def get_position(self): # return self.position # def reset_position(self): # self.position = 0 # def get_immediate_position(self): # return self.position # def acceleration(self, value: float=None): # if value is None: # return self.accel # self.accel = value # return '' # def deceleration(self, value: float=None): # if value is None: # return self.decel # self.decel = value # return '' # def speed(self, value: float=None): # if value is None: # return self.velocity # self.velocity = value # return '' # def move_relative(self, value: float): # self.position += value # def move_absolute(self, position: float): # self.position = position
""" For communication with devices from Applied Motion Products. The IP can be set via a small wheel (S1) on the device itself. We used the windows software 'STF Configurator' from Applied Motion Products for the first configuration of the controller and to give it its IP address in our local subnet. File name: applied_motion_products.py Author: <NAME> Date created: 2020/09/02 Python Version: 3.7 """ import socket from labdevices._mock.applied_motion_products import SocketDummy # The ports for communication. We usually use UDP TCP_PORT = 7776 UDP_PORT = 7775 # IP address of host pc. # If 0.0.0.0: Communication on all ethernet interfaces. # When instantiating the class it is better to use # the specific local IP address of that PC. HOST_IP = '0.0.0.0' HOST_PORT = 15005 ERROR_CODES = { 0x0000: 'No alarms', 0x0001: 'Position Limit', 0x0002: 'CCW Limit', 0x0004: 'CW Limit', 0x0008: 'Over Temp', 0x0010: 'Internal Voltage', 0x0020: 'Over Voltage', 0x0040: 'Under Voltage', 0x0080: 'Over Current', 0x0100: 'Open Motor Winding', 0x0200: 'Bad Encoder', 0x0400: 'Comm Error', 0x0800: 'Bad Flash', 0x1000: 'No Move', 0x2000: '(not used)', 0x4000: 'Blank Q Segment', 0x8000: '(not used)', } STATUS_CODES = { 0x0000: 'Motor disabled', 0x0001: 'Motor enabled and in position', 0x0002: 'Sampling (for Quick Tuner)', 0x0004: 'Drive Fault (check Alarm Code)', 0x0008: 'In Position (motor is in position)', 0x0010: 'Moving (motor is moving)', 0x0020: 'Jogging (currently in jog mode)', 0x0040: 'Stopping (in the process of stopping from a stop command)', 0x0080: 'Waiting (for an input; executing a WI command)', 0x0100: 'Saving (parameter data is being saved)', 0x0200: 'Alarm present (check Alarm Code)', 0x0400: 'Homing (executing an SH command)', 0x0800: 'Waiting (for time; executing a WD or WT command)', 0x1000: 'Wizard running (Timing Wizard is running)', 0x2000: 'Checking encoder (Timing Wizard is running)', 0x4000: 'Q Program is running', 0x8000: 'Initializing (happens at power up)', } STEPS_PER_TURN = { # Gives the number of steps for a full # motor turn, given the microstep resolution # setting. 0: 200, 1: 400, 3: 2000, 4: 5000, 5: 10000, 6: 12800, 7: 18000, 8: 20000, 9: 21600, 10:25000, 11:25400, 12:25600, 13:36000, 14:50000, 15:50800, } class STF03D: """ Class for the STF03-D Stepper Motor Controllers. When using this class start to set the motor calibration with self.set_calibration() """ _header = bytes([0x00, 0x007]) _tail = bytes([0xD]) def __init__(self, device_ip: str, host_ip: str=HOST_IP, host_port: int=HOST_PORT, timeout: float=5): """ Arguments: device_ip -- IP address of device host_ip -- IP address of host, can be 0.0.0.0 host_port -- Port used by host timeout -- in seconds """ self.device_ip = device_ip self.host_ip = host_ip self.host_port = host_port self.timeout = timeout self._device = None # This is the calibration and it has to be set by self.set_calibration() self._units_per_motor_turn = None def initialize(self) -> None: """Establish connection to device.""" self._device = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self._device.bind((self.host_ip, self.host_port)) self._device.settimeout(self.timeout) print(f'Connected to rotary feedthrough with IP={self.device_ip}.') def close(self) -> None: """Close connection to device.""" if self._device is None: print('Device is already closed.') return self._device.close() print(f'Closed rotary feedthrough with IP={self.device_ip}.') @property def idn(self) -> str: """ Returns model and revision """ return self.query('MV') def write(self, cmd: str): """Send a message with the correct header and end characters""" to_send = self._header + cmd.encode() + self._tail # print(to_send) self._device.sendto(to_send, (self.device_ip, UDP_PORT)) def _read(self) -> str: """Read UDP message, decode, strip off header and end characters and return.""" respons_raw = self._device.recv(1024) # print(respons_raw) respons = respons_raw.decode() return respons[2:-1] def query(self, cmd: str) -> str: """ Query the device. """ self.write(cmd) return self._read() def _get_future_movement_value(self) -> float: """Request the distance by which the motor moves with the next relative move command, or the position to which the motor moves with the next absolute move command. """ steps = int(self.query('DI')[3:]) value = self._step_to_unit(steps) return value def _set_future_movement_value(self, value: float) -> None: """Set the distance by which the motor moves with the next relative move command, or the position to which the motor moves with the next absolute move command. value -- in units as defined by the calibration. """ steps = self._unit_to_step(value) # print(f'Move by/to {value} degrees, equiv. to {steps} steps.') _ = self.query(f'DI{steps}') def set_calibration(self, units_per_motor_turn: float) -> None: """ Arguments: units_per_motor_turn -- units could be degree or meter. Example: For a rotation stage with gear ratio 1/96 the conversion factor into degrees would be 360/96, For a linear stage it would be the lead value of the screw. """ self._units_per_motor_turn = units_per_motor_turn def get_alarm(self) -> list: """Reads back an equivalent hexadecimal value of the Alarm Code's 16-bit binary word and translates it into corresponding error messages. """ # Strip off the 'AL=' prefix respons = self.query('AL')[3:] # Convert hex string to integer alarm = int(respons, 16) error_list = [] if not alarm: error_list.append(ERROR_CODES[alarm]) else: for key, val in ERROR_CODES.items(): if key & alarm: error_list.append(val) return error_list def get_status(self) -> list: """Reads back an equivalent hexadecimal value of the Status Code's 16-bit binary word and translates it into corresponding status messages. """ # Strip off the 'SC=' prefix respons = self.query('SC')[3:] status = int(respons, 16) status_list = [] if not status: status_list.append(STATUS_CODES[status]) else: for key, val in STATUS_CODES.items(): if key & status: status_list.append(val) return status_list @property def is_moving(self) -> bool: """Ask for device movement status, return boolean.""" respons = self.query('SC')[3:] status = int(respons, 16) return bool(0x0010 & status) @property def microstep(self) -> int: """The microstep resolution of the drive. Allowed range is between [0 and 15] (default is 3) """ respons = self.query('MR')[3:] return int(respons) @microstep.setter def microstep(self, value: int) -> None: _ = self.query(f'MR{value}') @property def _conversion_factor(self) -> float: """This yields the steps/user-defined-unit ratio. The steps of the stepper motor depend on the microstep resolution setting. """ if self._units_per_motor_turn is None: raise Exception('Set calibration first') steps_per_motor_turn = STEPS_PER_TURN[self.microstep] steps_per_unit = float(steps_per_motor_turn) / float(self._units_per_motor_turn) return steps_per_unit def _step_to_unit(self, step: int) -> float: """Convert stepper motor steps into user-defined units.""" return float(step) / self._conversion_factor def _unit_to_step(self, value: float) -> int: """Convert value in user-defined units into steps of the stepper motor. Argument: value -- in user-defined units""" return int(round(value * self._conversion_factor)) @property def max_current(self) -> float: """ Set or request the maximum idle and change current limit. value -- in Ampere, max is 3 A """ return float(self.query('MC')[3:]) @max_current.setter def max_current(self, value: float): _ = self.query(f'MC{value}') @property def idle_current(self) -> float: """ Set or request the current the standing still situation. A good value seems to be 0.5 A. value -- in Ampere, max is given by self.max_current(). """ return float(self.query('CI')[3:]) @idle_current.setter def idle_current(self, value: float): _ = self.query(f'CI{value}') @property def change_current(self) -> float: """Set or request the current for moving the stepper motor. For not missing any steps that should be as high as possible, which in this case is 3 A. value -- in Ampere, max is given by self.max_current().""" return float(self.query('CC')[3:]) @change_current.setter def change_current(self, value: float): _ = self.query(f'CC{value}') def get_position(self) -> float: """Returns the current position in user-defined units.""" steps = int(self.query('SP')[3:]) print(f'Position in steps is: {steps}') return self._step_to_unit(steps) def reset_position(self) -> None: """Set current motor position to the new zero position.""" _ = self.query('SP0') def get_immediate_step(self) -> int: """This returns the calculated trajectory position, which is not always equal to the actual position. Units are stepper motor steps. """ respons = self.query('IP')[3:] position = int(respons, 16) return position @property def acceleration(self) -> float: """Sets or requests the acceleration used in point-to-point move commands. Argument: value -- in rps/s (a standard value is 1) """ return float(self.query('AC')[3:]) @acceleration.setter def acceleration(self, value: float): _ = self.query(f'AC{value}') @property def deceleration(self) -> float: """Sets or requests the deceleration used in point-to-point move commands Argument: value -- in rps/s (a standard value is 1) """ return float(self.query('DE')[3:]) @deceleration.setter def deceleration(self, value: float): _ = self.query(f'DE{value}') @property def speed(self) -> float: """Sets or requests shaft speed for point-to-point move commands Argument: value -- in rps (a standard value is 2) """ return float(self.query('VE')[3:]) @speed.setter def speed(self, value: float): _ = self.query(f'VE{value}') def move_relative(self, value: float) -> None: """Relative rotation of the feedthrough Argument: value -- in user-defined units """ self._set_future_movement_value(value) _ = self.query('FL') def move_absolute(self, position: float) -> None: """Rotate the feedthrough to a given position Argument: position -- in degrees """ self._set_future_movement_value(position) _ = self.query('FP') class STF03DDummy(STF03D): """Class for testing. Does not actually connect to any device.""" def initialize(self): """Establish connection to device.""" self._device = SocketDummy() self._device.bind((self.host_ip, self.host_port)) self._device.settimeout(self.timeout) print(f'Connected to rotary feedthrough with IP={self.device_ip}.') # class STF03DDummy: # """Class for testing. Does not actually connect to any device.""" # def __init__(self, device_ip, host_ip=HOST_IP, # host_port=HOST_PORT, timeout=5): # self.device_ip = device_ip # self.host_ip = host_ip # self.host_port = host_port # self.timeout = timeout # # Dummy parameters # self.position = 0 # self.accel = 1 # self.decel = 1 # self.velocity = 1 # def initialize(self): # pass # def close(self): # pass # def get_alarm_code(self): # return ['no alarms'] # def get_position(self): # return self.position # def reset_position(self): # self.position = 0 # def get_immediate_position(self): # return self.position # def acceleration(self, value: float=None): # if value is None: # return self.accel # self.accel = value # return '' # def deceleration(self, value: float=None): # if value is None: # return self.decel # self.decel = value # return '' # def speed(self, value: float=None): # if value is None: # return self.velocity # self.velocity = value # return '' # def move_relative(self, value: float): # self.position += value # def move_absolute(self, position: float): # self.position = position
en
0.763543
For communication with devices from Applied Motion Products. The IP can be set via a small wheel (S1) on the device itself. We used the windows software 'STF Configurator' from Applied Motion Products for the first configuration of the controller and to give it its IP address in our local subnet. File name: applied_motion_products.py Author: <NAME> Date created: 2020/09/02 Python Version: 3.7 # The ports for communication. We usually use UDP # IP address of host pc. # If 0.0.0.0: Communication on all ethernet interfaces. # When instantiating the class it is better to use # the specific local IP address of that PC. # Gives the number of steps for a full # motor turn, given the microstep resolution # setting. Class for the STF03-D Stepper Motor Controllers. When using this class start to set the motor calibration with self.set_calibration() Arguments: device_ip -- IP address of device host_ip -- IP address of host, can be 0.0.0.0 host_port -- Port used by host timeout -- in seconds # This is the calibration and it has to be set by self.set_calibration() Establish connection to device. Close connection to device. Returns model and revision Send a message with the correct header and end characters # print(to_send) Read UDP message, decode, strip off header and end characters and return. # print(respons_raw) Query the device. Request the distance by which the motor moves with the next relative move command, or the position to which the motor moves with the next absolute move command. Set the distance by which the motor moves with the next relative move command, or the position to which the motor moves with the next absolute move command. value -- in units as defined by the calibration. # print(f'Move by/to {value} degrees, equiv. to {steps} steps.') Arguments: units_per_motor_turn -- units could be degree or meter. Example: For a rotation stage with gear ratio 1/96 the conversion factor into degrees would be 360/96, For a linear stage it would be the lead value of the screw. Reads back an equivalent hexadecimal value of the Alarm Code's 16-bit binary word and translates it into corresponding error messages. # Strip off the 'AL=' prefix # Convert hex string to integer Reads back an equivalent hexadecimal value of the Status Code's 16-bit binary word and translates it into corresponding status messages. # Strip off the 'SC=' prefix Ask for device movement status, return boolean. The microstep resolution of the drive. Allowed range is between [0 and 15] (default is 3) This yields the steps/user-defined-unit ratio. The steps of the stepper motor depend on the microstep resolution setting. Convert stepper motor steps into user-defined units. Convert value in user-defined units into steps of the stepper motor. Argument: value -- in user-defined units Set or request the maximum idle and change current limit. value -- in Ampere, max is 3 A Set or request the current the standing still situation. A good value seems to be 0.5 A. value -- in Ampere, max is given by self.max_current(). Set or request the current for moving the stepper motor. For not missing any steps that should be as high as possible, which in this case is 3 A. value -- in Ampere, max is given by self.max_current(). Returns the current position in user-defined units. Set current motor position to the new zero position. This returns the calculated trajectory position, which is not always equal to the actual position. Units are stepper motor steps. Sets or requests the acceleration used in point-to-point move commands. Argument: value -- in rps/s (a standard value is 1) Sets or requests the deceleration used in point-to-point move commands Argument: value -- in rps/s (a standard value is 1) Sets or requests shaft speed for point-to-point move commands Argument: value -- in rps (a standard value is 2) Relative rotation of the feedthrough Argument: value -- in user-defined units Rotate the feedthrough to a given position Argument: position -- in degrees Class for testing. Does not actually connect to any device. Establish connection to device. # class STF03DDummy: # """Class for testing. Does not actually connect to any device.""" # def __init__(self, device_ip, host_ip=HOST_IP, # host_port=HOST_PORT, timeout=5): # self.device_ip = device_ip # self.host_ip = host_ip # self.host_port = host_port # self.timeout = timeout # # Dummy parameters # self.position = 0 # self.accel = 1 # self.decel = 1 # self.velocity = 1 # def initialize(self): # pass # def close(self): # pass # def get_alarm_code(self): # return ['no alarms'] # def get_position(self): # return self.position # def reset_position(self): # self.position = 0 # def get_immediate_position(self): # return self.position # def acceleration(self, value: float=None): # if value is None: # return self.accel # self.accel = value # return '' # def deceleration(self, value: float=None): # if value is None: # return self.decel # self.decel = value # return '' # def speed(self, value: float=None): # if value is None: # return self.velocity # self.velocity = value # return '' # def move_relative(self, value: float): # self.position += value # def move_absolute(self, position: float): # self.position = position
2.678813
3
python/mlad/cli/context.py
onetop21/MLAppDeploy
0
6628318
import sys import os import omegaconf from typing import Optional, Dict, Callable, List from pathlib import Path from omegaconf import OmegaConf from mlad.cli.libs import utils from mlad.cli.exceptions import ( NotExistContextError, CannotDeleteContextError, InvalidPropertyError, ContextAlreadyExistError ) MLAD_HOME_PATH = f'{Path.home()}/.mlad' CTX_PATH = f'{MLAD_HOME_PATH}/config.yml' Config = omegaconf.Container Context = omegaconf.Container StrDict = Dict[str, str] boilerplate = { 'current-context': None, 'contexts': [] } if not os.path.isfile(CTX_PATH): Path(MLAD_HOME_PATH).mkdir(exist_ok=True, parents=True) OmegaConf.save(config=boilerplate, f=CTX_PATH) def _load(): return OmegaConf.load(CTX_PATH) def _save(config: Config): OmegaConf.save(config=config, f=CTX_PATH) def _find_context(name: str, config: Optional[Config] = None, index: bool = False) -> Optional[Context]: if config is None: config = OmegaConf.load(CTX_PATH) for i, context in enumerate(config.contexts): if context.name == name: return context if not index else i return None def add(name: str, address: str, allow_duplicate=False) -> Context: config = _load() duplicated_index = _find_context(name, config=config, index=True) if duplicated_index is not None: if not allow_duplicate: raise ContextAlreadyExistError(name) elif utils.prompt('Change the existing session key (Y/N)?', 'N') == 'Y': session = utils.create_session_key() else: session = config.contexts[duplicated_index].session else: session = utils.create_session_key() address = utils.parse_url(address)['url'] registry_address = 'https://docker.io' warn_insecure = False service_addr = utils.get_advertise_addr() registry_port = utils.get_default_service_port('mlad_registry', 5000) if registry_port: registry_address = f'http://{service_addr}:{registry_port}' registry_address = utils.prompt('Docker Registry Address', registry_address) parsed_url = utils.parse_url(registry_address) if parsed_url['scheme'] != 'https': warn_insecure = True registry_address = parsed_url['url'] registry_namespace = utils.prompt('Docker Registry Namespace') base_config = OmegaConf.from_dotlist([ f'name={name}', f'session={session}', f'apiserver.address={address}', f'docker.registry.address={registry_address}', f'docker.registry.namespace={registry_namespace}' ]) s3_prompts = { 'endpoint': 'S3 Compatible Address', 'region': 'Region', 'accesskey': 'Access Key ID', 'secretkey': 'Secret Access Key' } s3_config = _parse_datastore('s3', _s3_initializer, _s3_finalizer, s3_prompts) db_prompts = { 'address': 'MongoDB Address', 'username': 'MongoDB Username', 'password': '<PASSWORD>' } db_config = _parse_datastore('db', _db_initializer, _db_finalizer, db_prompts) context = OmegaConf.merge(base_config, s3_config, db_config) if duplicated_index is not None: config.contexts[duplicated_index] = context else: config.contexts.append(context) if config['current-context'] is None: config['current-context'] = name _save(config) if warn_insecure: print('Need to add insecure-registry to docker.json on your all nodes.', file=sys.stderr) print('/etc/docker/daemon.json:', file=sys.stderr) print(f' \"insecure-registries\": [\"{registry_address}\"]', file=sys.stderr) return context def use(name: str) -> Context: config = _load() context = _find_context(name, config=config) if context is None: raise NotExistContextError(name) config['current-context'] = name _save(config) return context def _switch(direction: int = 1) -> str: config = _load() if config['current-context'] is None: raise NotExistContextError('Any Contexts') n_contexts = len(config.contexts) index = _find_context(config['current-context'], config=config, index=True) next_index = (index + direction) % n_contexts name = config.contexts[next_index].name use(name) return name def next() -> str: return _switch(direction=1) def prev() -> str: return _switch(direction=-1) def delete(name: str) -> None: config = _load() index = _find_context(name, config=config, index=True) if index is None: raise NotExistContextError(name) elif config['current-context'] == config.contexts[index].name: raise CannotDeleteContextError else: del config.contexts[index] _save(config) def get(name: Optional[str] = None) -> Context: config = _load() if name is None: name = config['current-context'] context = _find_context(name, config=config) if context is None: raise NotExistContextError(name) return context def set(name: str, *args) -> None: config = _load() index = _find_context(name, config=config, index=True) context = config.contexts[index] try: for arg in args: keys = arg.split('=')[0].split('.') value = context for key in keys: value = value[key] except Exception: raise InvalidPropertyError(arg) context = OmegaConf.merge(context, OmegaConf.from_dotlist(args)) OmegaConf.update(config, f'contexts.{index}', context) _save(config) def ls(): config = _load() names = [context.name for context in config.contexts] table = [(' NAME',)] for name in names: table.append([f' {name}' if config['current-context'] != name else f'* {name}']) utils.print_table(table, 'There are no contexts.', 0) def _parse_datastore(kind: str, initializer: Callable[[], StrDict], finalizer: Callable[[StrDict], StrDict], prompts: StrDict) -> omegaconf.Container: config = initializer() for k, v in prompts.items(): config[k] = utils.prompt(v, config[k]) config = finalizer(config) return OmegaConf.from_dotlist([ f'datastore.{kind}.{k}={v}' for k, v in config.items() ]) def _s3_initializer() -> StrDict: service_addr = utils.get_advertise_addr() minio_port = utils.get_default_service_port('mlad_minio', 9000) if minio_port: endpoint = f'http://{service_addr}:{minio_port}' region = 'ap-northeast-2' access_key = 'MLAPPDEPLOY' secret_key = 'MLAPPDEPLOY' else: endpoint = 'https://s3.amazonaws.com' region = 'us-east-1' access_key = None secret_key = None return {'endpoint': endpoint, 'region': region, 'accesskey': access_key, 'secretkey': secret_key} def _s3_finalizer(datastore: StrDict) -> StrDict: parsed = utils.parse_url(datastore['endpoint']) datastore['endpoint'] = parsed['url'] datastore['verify'] = parsed['scheme'] == 'https' return datastore def get_env(context: Context) -> List[str]: envs = [] for k, v in context['datastore']['s3'].items(): if v is None: v = '' if k == 'endpoint': envs.append(f'S3_ENDPOINT={v}') elif k == 'verify': envs.append(f'S3_USE_HTTPS={1 if v else 0}') envs.append('S3_VERIFY_SSL=0') elif k == 'accesskey': envs.append(f'AWS_ACCESS_KEY_ID={v}') elif k == 'secretkey': envs.append(f'AWS_SECRET_ACCESS_KEY={v}') elif k == 'region': envs.append(f'AWS_REGION={v}') else: envs.append(f'S3_{k.upper()}={v}') for k, v in context['datastore']['db'].items(): if v is None: v = '' envs.append(f'DB_{k.upper()}={v}') envs = sorted(envs) return envs def _db_initializer() -> StrDict: service_addr = utils.get_advertise_addr() mongo_port = utils.get_default_service_port('mlad_mongodb', 27017) if mongo_port: address = f'mongodb://{service_addr}:{mongo_port}' else: address = 'mongodb://localhost:27017' return {'address': address, 'username': '', 'password': ''} def _db_finalizer(datastore: StrDict) -> StrDict: parsed = utils.parse_url(datastore['address']) datastore['address'] = f'mongodb://{parsed["address"]}' return datastore
import sys import os import omegaconf from typing import Optional, Dict, Callable, List from pathlib import Path from omegaconf import OmegaConf from mlad.cli.libs import utils from mlad.cli.exceptions import ( NotExistContextError, CannotDeleteContextError, InvalidPropertyError, ContextAlreadyExistError ) MLAD_HOME_PATH = f'{Path.home()}/.mlad' CTX_PATH = f'{MLAD_HOME_PATH}/config.yml' Config = omegaconf.Container Context = omegaconf.Container StrDict = Dict[str, str] boilerplate = { 'current-context': None, 'contexts': [] } if not os.path.isfile(CTX_PATH): Path(MLAD_HOME_PATH).mkdir(exist_ok=True, parents=True) OmegaConf.save(config=boilerplate, f=CTX_PATH) def _load(): return OmegaConf.load(CTX_PATH) def _save(config: Config): OmegaConf.save(config=config, f=CTX_PATH) def _find_context(name: str, config: Optional[Config] = None, index: bool = False) -> Optional[Context]: if config is None: config = OmegaConf.load(CTX_PATH) for i, context in enumerate(config.contexts): if context.name == name: return context if not index else i return None def add(name: str, address: str, allow_duplicate=False) -> Context: config = _load() duplicated_index = _find_context(name, config=config, index=True) if duplicated_index is not None: if not allow_duplicate: raise ContextAlreadyExistError(name) elif utils.prompt('Change the existing session key (Y/N)?', 'N') == 'Y': session = utils.create_session_key() else: session = config.contexts[duplicated_index].session else: session = utils.create_session_key() address = utils.parse_url(address)['url'] registry_address = 'https://docker.io' warn_insecure = False service_addr = utils.get_advertise_addr() registry_port = utils.get_default_service_port('mlad_registry', 5000) if registry_port: registry_address = f'http://{service_addr}:{registry_port}' registry_address = utils.prompt('Docker Registry Address', registry_address) parsed_url = utils.parse_url(registry_address) if parsed_url['scheme'] != 'https': warn_insecure = True registry_address = parsed_url['url'] registry_namespace = utils.prompt('Docker Registry Namespace') base_config = OmegaConf.from_dotlist([ f'name={name}', f'session={session}', f'apiserver.address={address}', f'docker.registry.address={registry_address}', f'docker.registry.namespace={registry_namespace}' ]) s3_prompts = { 'endpoint': 'S3 Compatible Address', 'region': 'Region', 'accesskey': 'Access Key ID', 'secretkey': 'Secret Access Key' } s3_config = _parse_datastore('s3', _s3_initializer, _s3_finalizer, s3_prompts) db_prompts = { 'address': 'MongoDB Address', 'username': 'MongoDB Username', 'password': '<PASSWORD>' } db_config = _parse_datastore('db', _db_initializer, _db_finalizer, db_prompts) context = OmegaConf.merge(base_config, s3_config, db_config) if duplicated_index is not None: config.contexts[duplicated_index] = context else: config.contexts.append(context) if config['current-context'] is None: config['current-context'] = name _save(config) if warn_insecure: print('Need to add insecure-registry to docker.json on your all nodes.', file=sys.stderr) print('/etc/docker/daemon.json:', file=sys.stderr) print(f' \"insecure-registries\": [\"{registry_address}\"]', file=sys.stderr) return context def use(name: str) -> Context: config = _load() context = _find_context(name, config=config) if context is None: raise NotExistContextError(name) config['current-context'] = name _save(config) return context def _switch(direction: int = 1) -> str: config = _load() if config['current-context'] is None: raise NotExistContextError('Any Contexts') n_contexts = len(config.contexts) index = _find_context(config['current-context'], config=config, index=True) next_index = (index + direction) % n_contexts name = config.contexts[next_index].name use(name) return name def next() -> str: return _switch(direction=1) def prev() -> str: return _switch(direction=-1) def delete(name: str) -> None: config = _load() index = _find_context(name, config=config, index=True) if index is None: raise NotExistContextError(name) elif config['current-context'] == config.contexts[index].name: raise CannotDeleteContextError else: del config.contexts[index] _save(config) def get(name: Optional[str] = None) -> Context: config = _load() if name is None: name = config['current-context'] context = _find_context(name, config=config) if context is None: raise NotExistContextError(name) return context def set(name: str, *args) -> None: config = _load() index = _find_context(name, config=config, index=True) context = config.contexts[index] try: for arg in args: keys = arg.split('=')[0].split('.') value = context for key in keys: value = value[key] except Exception: raise InvalidPropertyError(arg) context = OmegaConf.merge(context, OmegaConf.from_dotlist(args)) OmegaConf.update(config, f'contexts.{index}', context) _save(config) def ls(): config = _load() names = [context.name for context in config.contexts] table = [(' NAME',)] for name in names: table.append([f' {name}' if config['current-context'] != name else f'* {name}']) utils.print_table(table, 'There are no contexts.', 0) def _parse_datastore(kind: str, initializer: Callable[[], StrDict], finalizer: Callable[[StrDict], StrDict], prompts: StrDict) -> omegaconf.Container: config = initializer() for k, v in prompts.items(): config[k] = utils.prompt(v, config[k]) config = finalizer(config) return OmegaConf.from_dotlist([ f'datastore.{kind}.{k}={v}' for k, v in config.items() ]) def _s3_initializer() -> StrDict: service_addr = utils.get_advertise_addr() minio_port = utils.get_default_service_port('mlad_minio', 9000) if minio_port: endpoint = f'http://{service_addr}:{minio_port}' region = 'ap-northeast-2' access_key = 'MLAPPDEPLOY' secret_key = 'MLAPPDEPLOY' else: endpoint = 'https://s3.amazonaws.com' region = 'us-east-1' access_key = None secret_key = None return {'endpoint': endpoint, 'region': region, 'accesskey': access_key, 'secretkey': secret_key} def _s3_finalizer(datastore: StrDict) -> StrDict: parsed = utils.parse_url(datastore['endpoint']) datastore['endpoint'] = parsed['url'] datastore['verify'] = parsed['scheme'] == 'https' return datastore def get_env(context: Context) -> List[str]: envs = [] for k, v in context['datastore']['s3'].items(): if v is None: v = '' if k == 'endpoint': envs.append(f'S3_ENDPOINT={v}') elif k == 'verify': envs.append(f'S3_USE_HTTPS={1 if v else 0}') envs.append('S3_VERIFY_SSL=0') elif k == 'accesskey': envs.append(f'AWS_ACCESS_KEY_ID={v}') elif k == 'secretkey': envs.append(f'AWS_SECRET_ACCESS_KEY={v}') elif k == 'region': envs.append(f'AWS_REGION={v}') else: envs.append(f'S3_{k.upper()}={v}') for k, v in context['datastore']['db'].items(): if v is None: v = '' envs.append(f'DB_{k.upper()}={v}') envs = sorted(envs) return envs def _db_initializer() -> StrDict: service_addr = utils.get_advertise_addr() mongo_port = utils.get_default_service_port('mlad_mongodb', 27017) if mongo_port: address = f'mongodb://{service_addr}:{mongo_port}' else: address = 'mongodb://localhost:27017' return {'address': address, 'username': '', 'password': ''} def _db_finalizer(datastore: StrDict) -> StrDict: parsed = utils.parse_url(datastore['address']) datastore['address'] = f'mongodb://{parsed["address"]}' return datastore
none
1
2.061291
2
Scripts/speed_test_Tavernini.py
vitesempl/RK-IDE-Python
0
6628319
from RK.ide import ide_solve from math import * import numpy as np import time def OutputSolution(): nz = np.size(history(tspan[0])) if nz == 1: print("y(", tspan[1], ") = ", sol[1][-1], sep='') else: for i in range(nz): print("y", i + 1, "(", tspan[1], ") = ", sol[1][i, -1], sep='') # Test 2 tspan = [0, 5] stepsize = 1e-2 def idefun(t, y, z, i): return - y**2 - t * exp(t**2) * z**4 * i def K(t, s, y): return [y * exp(s - s * t)] def delays(t,y): return [t / 2] def delays_int(t): return [t - 1] def history(t): return exp(-t) t = time.time() sol = ide_solve(idefun, K, delays_int, history, tspan, stepsize, delays=delays, overlapping=True) elapsed = time.time() - t OutputSolution() print("Elapsed time:", elapsed, "seconds") # Test 3 tspan = [0, 5] stepsize = 1e-2 def idefun(t, y, z, i): return exp(1) - exp(t**2) / z**2 * (i[0] - exp(-2 * t) * i[1]) * (t - 1) def K(t, s, y): return [y * exp(-s * t), y * exp(t * (2 - s))] def delays(t, y): return [t - 1] def delays_int(t): return [t - 1, t - 2] def history(t): return exp(t) t = time.time() sol = ide_solve(idefun, K, delays_int, history, tspan, stepsize, delays=delays, overlapping=True) elapsed = time.time() - t OutputSolution() print("Elapsed time:", elapsed, "seconds") # Test 4 tspan = [0, 5] stepsize = 1e-2 def idefun(t, y, z, i): return - z[0, 0]**((t + 1) / 2) * z[0, 1] * y**2 * (1 + exp(t**2) * t * i) / exp(1 / 2) def K(t, s, y): return [y * exp(s - s * t)] def delays(t, y): return [log(y)**2 / (t + 1) - 1 / 2, (t - 1) / 4] def delays_int(t): return [t / 2 - 1] def history(t): return exp(-t) t = time.time() sol = ide_solve(idefun, K, delays_int, history, tspan, stepsize, delays=delays, overlapping=True) elapsed = time.time() - t OutputSolution() print("Elapsed time:", elapsed, "seconds")
from RK.ide import ide_solve from math import * import numpy as np import time def OutputSolution(): nz = np.size(history(tspan[0])) if nz == 1: print("y(", tspan[1], ") = ", sol[1][-1], sep='') else: for i in range(nz): print("y", i + 1, "(", tspan[1], ") = ", sol[1][i, -1], sep='') # Test 2 tspan = [0, 5] stepsize = 1e-2 def idefun(t, y, z, i): return - y**2 - t * exp(t**2) * z**4 * i def K(t, s, y): return [y * exp(s - s * t)] def delays(t,y): return [t / 2] def delays_int(t): return [t - 1] def history(t): return exp(-t) t = time.time() sol = ide_solve(idefun, K, delays_int, history, tspan, stepsize, delays=delays, overlapping=True) elapsed = time.time() - t OutputSolution() print("Elapsed time:", elapsed, "seconds") # Test 3 tspan = [0, 5] stepsize = 1e-2 def idefun(t, y, z, i): return exp(1) - exp(t**2) / z**2 * (i[0] - exp(-2 * t) * i[1]) * (t - 1) def K(t, s, y): return [y * exp(-s * t), y * exp(t * (2 - s))] def delays(t, y): return [t - 1] def delays_int(t): return [t - 1, t - 2] def history(t): return exp(t) t = time.time() sol = ide_solve(idefun, K, delays_int, history, tspan, stepsize, delays=delays, overlapping=True) elapsed = time.time() - t OutputSolution() print("Elapsed time:", elapsed, "seconds") # Test 4 tspan = [0, 5] stepsize = 1e-2 def idefun(t, y, z, i): return - z[0, 0]**((t + 1) / 2) * z[0, 1] * y**2 * (1 + exp(t**2) * t * i) / exp(1 / 2) def K(t, s, y): return [y * exp(s - s * t)] def delays(t, y): return [log(y)**2 / (t + 1) - 1 / 2, (t - 1) / 4] def delays_int(t): return [t / 2 - 1] def history(t): return exp(-t) t = time.time() sol = ide_solve(idefun, K, delays_int, history, tspan, stepsize, delays=delays, overlapping=True) elapsed = time.time() - t OutputSolution() print("Elapsed time:", elapsed, "seconds")
en
0.273342
# Test 2 # Test 3 # Test 4
3.03837
3
predictor/api/custom_api.py
acumos/model-runner-rds-model-runner
0
6628320
<filename>predictor/api/custom_api.py #!/usr/bin/env python3 # ===============LICENSE_START======================================================= # Acumos Apache-2.0 # =================================================================================== # Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. # =================================================================================== # This Acumos software file is distributed by AT&T # 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 # # This file 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. # ===============LICENSE_END========================================================= import logging from flask import Blueprint from flask_restplus import Api, Swagger from werkzeug import cached_property logger = logging.getLogger(__name__) class CustomSwagger(Swagger): """Override RESTplus Swagger class to add custom properties.""" def as_dict(self): """Add custom properties to top-level Swagger specs.""" specs = super().as_dict() specs['consumes'] = ['text/csv', 'application/json', 'text/plain'] return specs class CustomApi(Api): @cached_property def __schema__(self): """ The Swagger specifications/schema for this API Override this to refer to our fixed Swagger class. :returns dict: the schema as a serializable dict """ if not self._schema: try: self._schema = CustomSwagger(self).as_dict() except Exception as e: # Log the source exception for debugging purpose # and return an error message print(e.message) msg = 'Unable to render schema' logger.exception(msg) # This will provide a full traceback return {'error': msg} return self._schema blueprint = Blueprint('acumos', __name__, url_prefix='/v2') custom_api = CustomApi( blueprint, version=2, title='RDS Predictor', default_label='RDS Predictor', validate=True, description='The RDS (R Data) Predictor provides a mechanism for scoring models in RDS format' )
<filename>predictor/api/custom_api.py #!/usr/bin/env python3 # ===============LICENSE_START======================================================= # Acumos Apache-2.0 # =================================================================================== # Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. # =================================================================================== # This Acumos software file is distributed by AT&T # 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 # # This file 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. # ===============LICENSE_END========================================================= import logging from flask import Blueprint from flask_restplus import Api, Swagger from werkzeug import cached_property logger = logging.getLogger(__name__) class CustomSwagger(Swagger): """Override RESTplus Swagger class to add custom properties.""" def as_dict(self): """Add custom properties to top-level Swagger specs.""" specs = super().as_dict() specs['consumes'] = ['text/csv', 'application/json', 'text/plain'] return specs class CustomApi(Api): @cached_property def __schema__(self): """ The Swagger specifications/schema for this API Override this to refer to our fixed Swagger class. :returns dict: the schema as a serializable dict """ if not self._schema: try: self._schema = CustomSwagger(self).as_dict() except Exception as e: # Log the source exception for debugging purpose # and return an error message print(e.message) msg = 'Unable to render schema' logger.exception(msg) # This will provide a full traceback return {'error': msg} return self._schema blueprint = Blueprint('acumos', __name__, url_prefix='/v2') custom_api = CustomApi( blueprint, version=2, title='RDS Predictor', default_label='RDS Predictor', validate=True, description='The RDS (R Data) Predictor provides a mechanism for scoring models in RDS format' )
en
0.690005
#!/usr/bin/env python3 # ===============LICENSE_START======================================================= # Acumos Apache-2.0 # =================================================================================== # Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. # =================================================================================== # This Acumos software file is distributed by AT&T # 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 # # This file 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. # ===============LICENSE_END========================================================= Override RESTplus Swagger class to add custom properties. Add custom properties to top-level Swagger specs. The Swagger specifications/schema for this API Override this to refer to our fixed Swagger class. :returns dict: the schema as a serializable dict # Log the source exception for debugging purpose # and return an error message # This will provide a full traceback
1.422749
1
cogs/haruyuki.py
haruyuki/CS-Pound
4
6628321
<reponame>haruyuki/CS-Pound import discord from discord.ext import commands class Haruyuki(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(aliases=['haru']) @commands.guild_only() async def haruyuki(self, ctx): await ctx.send("Use it!") def setup(bot): bot.add_cog(Haruyuki(bot))
import discord from discord.ext import commands class Haruyuki(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(aliases=['haru']) @commands.guild_only() async def haruyuki(self, ctx): await ctx.send("Use it!") def setup(bot): bot.add_cog(Haruyuki(bot))
none
1
2.334171
2
core/events/floor.py
ChrisLR/BasicDungeonRL
3
6628322
<gh_stars>1-10 from core.events.base import Event class WalkedOn(Event): name = "WalkedOn" __slots__ = "actor" def __init__(self, actor): self.actor = actor
from core.events.base import Event class WalkedOn(Event): name = "WalkedOn" __slots__ = "actor" def __init__(self, actor): self.actor = actor
none
1
2.374248
2
PaddleRec/multiview_simnet/nets.py
danleifeng/models
2
6628323
<filename>PaddleRec/multiview_simnet/nets.py<gh_stars>1-10 # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import paddle.fluid as fluid import paddle.fluid.layers.tensor as tensor import paddle.fluid.layers.control_flow as cf import paddle.fluid.layers.io as io class BowEncoder(object): """ bow-encoder """ def __init__(self): self.param_name = "" def forward(self, emb): return fluid.layers.sequence_pool(input=emb, pool_type='sum') class CNNEncoder(object): """ cnn-encoder""" def __init__(self, param_name="cnn", win_size=3, ksize=128, act='tanh', pool_type='max'): self.param_name = param_name self.win_size = win_size self.ksize = ksize self.act = act self.pool_type = pool_type def forward(self, emb): return fluid.nets.sequence_conv_pool( input=emb, num_filters=self.ksize, filter_size=self.win_size, act=self.act, pool_type=self.pool_type, param_attr=self.param_name + ".param", bias_attr=self.param_name + ".bias") class GrnnEncoder(object): """ grnn-encoder """ def __init__(self, param_name="grnn", hidden_size=128): self.param_name = param_name self.hidden_size = hidden_size def forward(self, emb): fc0 = fluid.layers.fc(input=emb, size=self.hidden_size * 3, param_attr=self.param_name + "_fc.w", bias_attr=False) gru_h = fluid.layers.dynamic_gru( input=fc0, size=self.hidden_size, is_reverse=False, param_attr=self.param_name + ".param", bias_attr=self.param_name + ".bias") return fluid.layers.sequence_pool(input=gru_h, pool_type='max') '''this is a very simple Encoder factory most default argument values are used''' class SimpleEncoderFactory(object): def __init__(self): pass ''' create an encoder through create function ''' def create(self, enc_type, enc_hid_size): if enc_type == "bow": bow_encode = BowEncoder() return bow_encode elif enc_type == "cnn": cnn_encode = CNNEncoder(ksize=enc_hid_size) return cnn_encode elif enc_type == "gru": rnn_encode = GrnnEncoder(hidden_size=enc_hid_size) return rnn_encode class MultiviewSimnet(object): """ multi-view simnet """ def __init__(self, embedding_size, embedding_dim, hidden_size): self.embedding_size = embedding_size self.embedding_dim = embedding_dim self.emb_shape = [self.embedding_size, self.embedding_dim] self.hidden_size = hidden_size self.margin = 0.1 def set_query_encoder(self, encoders): self.query_encoders = encoders def set_title_encoder(self, encoders): self.title_encoders = encoders def get_correct(self, x, y): less = tensor.cast(cf.less_than(x, y), dtype='float32') correct = fluid.layers.reduce_sum(less) return correct def train_net(self): # input fields for query, pos_title, neg_title q_slots = [ fluid.data( name="q%d" % i, shape=[None, 1], lod_level=1, dtype='int64') for i in range(len(self.query_encoders)) ] pt_slots = [ fluid.data( name="pt%d" % i, shape=[None, 1], lod_level=1, dtype='int64') for i in range(len(self.title_encoders)) ] nt_slots = [ fluid.data( name="nt%d" % i, shape=[None, 1], lod_level=1, dtype='int64') for i in range(len(self.title_encoders)) ] # lookup embedding for each slot q_embs = [ fluid.embedding( input=query, size=self.emb_shape, param_attr="emb") for query in q_slots ] pt_embs = [ fluid.embedding( input=title, size=self.emb_shape, param_attr="emb") for title in pt_slots ] nt_embs = [ fluid.embedding( input=title, size=self.emb_shape, param_attr="emb") for title in nt_slots ] # encode each embedding field with encoder q_encodes = [ self.query_encoders[i].forward(emb) for i, emb in enumerate(q_embs) ] pt_encodes = [ self.title_encoders[i].forward(emb) for i, emb in enumerate(pt_embs) ] nt_encodes = [ self.title_encoders[i].forward(emb) for i, emb in enumerate(nt_embs) ] # concat multi view for query, pos_title, neg_title q_concat = fluid.layers.concat(q_encodes) pt_concat = fluid.layers.concat(pt_encodes) nt_concat = fluid.layers.concat(nt_encodes) # projection of hidden layer q_hid = fluid.layers.fc(q_concat, size=self.hidden_size, param_attr='q_fc.w', bias_attr='q_fc.b') pt_hid = fluid.layers.fc(pt_concat, size=self.hidden_size, param_attr='t_fc.w', bias_attr='t_fc.b') nt_hid = fluid.layers.fc(nt_concat, size=self.hidden_size, param_attr='t_fc.w', bias_attr='t_fc.b') # cosine of hidden layers cos_pos = fluid.layers.cos_sim(q_hid, pt_hid) cos_neg = fluid.layers.cos_sim(q_hid, nt_hid) # pairwise hinge_loss loss_part1 = fluid.layers.elementwise_sub( fluid.layers.fill_constant( shape=[fluid.layers.shape(cos_pos)[0], 1], value=self.margin, dtype='float32'), cos_pos) loss_part2 = fluid.layers.elementwise_add(loss_part1, cos_neg) loss_part3 = fluid.layers.elementwise_max( fluid.layers.fill_constant( shape=[fluid.layers.shape(loss_part2)[0], 1], value=0.0, dtype='float32'), loss_part2) avg_cost = fluid.layers.mean(loss_part3) correct = self.get_correct(cos_neg, cos_pos) return q_slots + pt_slots + nt_slots, avg_cost, correct def pred_net(self, query_fields, pos_title_fields, neg_title_fields): q_slots = [ fluid.data( name="q%d" % i, shape=[None, 1], lod_level=1, dtype='int64') for i in range(len(self.query_encoders)) ] pt_slots = [ fluid.data( name="pt%d" % i, shape=[None, 1], lod_level=1, dtype='int64') for i in range(len(self.title_encoders)) ] # lookup embedding for each slot q_embs = [ fluid.embedding( input=query, size=self.emb_shape, param_attr="emb") for query in q_slots ] pt_embs = [ fluid.embedding( input=title, size=self.emb_shape, param_attr="emb") for title in pt_slots ] # encode each embedding field with encoder q_encodes = [ self.query_encoder[i].forward(emb) for i, emb in enumerate(q_embs) ] pt_encodes = [ self.title_encoders[i].forward(emb) for i, emb in enumerate(pt_embs) ] # concat multi view for query, pos_title, neg_title q_concat = fluid.layers.concat(q_encodes) pt_concat = fluid.layers.concat(pt_encodes) # projection of hidden layer q_hid = fluid.layers.fc(q_concat, size=self.hidden_size, param_attr='q_fc.w', bias_attr='q_fc.b') pt_hid = fluid.layers.fc(pt_concat, size=self.hidden_size, param_attr='t_fc.w', bias_attr='t_fc.b') # cosine of hidden layers cos = fluid.layers.cos_sim(q_hid, pt_hid) return cos
<filename>PaddleRec/multiview_simnet/nets.py<gh_stars>1-10 # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import paddle.fluid as fluid import paddle.fluid.layers.tensor as tensor import paddle.fluid.layers.control_flow as cf import paddle.fluid.layers.io as io class BowEncoder(object): """ bow-encoder """ def __init__(self): self.param_name = "" def forward(self, emb): return fluid.layers.sequence_pool(input=emb, pool_type='sum') class CNNEncoder(object): """ cnn-encoder""" def __init__(self, param_name="cnn", win_size=3, ksize=128, act='tanh', pool_type='max'): self.param_name = param_name self.win_size = win_size self.ksize = ksize self.act = act self.pool_type = pool_type def forward(self, emb): return fluid.nets.sequence_conv_pool( input=emb, num_filters=self.ksize, filter_size=self.win_size, act=self.act, pool_type=self.pool_type, param_attr=self.param_name + ".param", bias_attr=self.param_name + ".bias") class GrnnEncoder(object): """ grnn-encoder """ def __init__(self, param_name="grnn", hidden_size=128): self.param_name = param_name self.hidden_size = hidden_size def forward(self, emb): fc0 = fluid.layers.fc(input=emb, size=self.hidden_size * 3, param_attr=self.param_name + "_fc.w", bias_attr=False) gru_h = fluid.layers.dynamic_gru( input=fc0, size=self.hidden_size, is_reverse=False, param_attr=self.param_name + ".param", bias_attr=self.param_name + ".bias") return fluid.layers.sequence_pool(input=gru_h, pool_type='max') '''this is a very simple Encoder factory most default argument values are used''' class SimpleEncoderFactory(object): def __init__(self): pass ''' create an encoder through create function ''' def create(self, enc_type, enc_hid_size): if enc_type == "bow": bow_encode = BowEncoder() return bow_encode elif enc_type == "cnn": cnn_encode = CNNEncoder(ksize=enc_hid_size) return cnn_encode elif enc_type == "gru": rnn_encode = GrnnEncoder(hidden_size=enc_hid_size) return rnn_encode class MultiviewSimnet(object): """ multi-view simnet """ def __init__(self, embedding_size, embedding_dim, hidden_size): self.embedding_size = embedding_size self.embedding_dim = embedding_dim self.emb_shape = [self.embedding_size, self.embedding_dim] self.hidden_size = hidden_size self.margin = 0.1 def set_query_encoder(self, encoders): self.query_encoders = encoders def set_title_encoder(self, encoders): self.title_encoders = encoders def get_correct(self, x, y): less = tensor.cast(cf.less_than(x, y), dtype='float32') correct = fluid.layers.reduce_sum(less) return correct def train_net(self): # input fields for query, pos_title, neg_title q_slots = [ fluid.data( name="q%d" % i, shape=[None, 1], lod_level=1, dtype='int64') for i in range(len(self.query_encoders)) ] pt_slots = [ fluid.data( name="pt%d" % i, shape=[None, 1], lod_level=1, dtype='int64') for i in range(len(self.title_encoders)) ] nt_slots = [ fluid.data( name="nt%d" % i, shape=[None, 1], lod_level=1, dtype='int64') for i in range(len(self.title_encoders)) ] # lookup embedding for each slot q_embs = [ fluid.embedding( input=query, size=self.emb_shape, param_attr="emb") for query in q_slots ] pt_embs = [ fluid.embedding( input=title, size=self.emb_shape, param_attr="emb") for title in pt_slots ] nt_embs = [ fluid.embedding( input=title, size=self.emb_shape, param_attr="emb") for title in nt_slots ] # encode each embedding field with encoder q_encodes = [ self.query_encoders[i].forward(emb) for i, emb in enumerate(q_embs) ] pt_encodes = [ self.title_encoders[i].forward(emb) for i, emb in enumerate(pt_embs) ] nt_encodes = [ self.title_encoders[i].forward(emb) for i, emb in enumerate(nt_embs) ] # concat multi view for query, pos_title, neg_title q_concat = fluid.layers.concat(q_encodes) pt_concat = fluid.layers.concat(pt_encodes) nt_concat = fluid.layers.concat(nt_encodes) # projection of hidden layer q_hid = fluid.layers.fc(q_concat, size=self.hidden_size, param_attr='q_fc.w', bias_attr='q_fc.b') pt_hid = fluid.layers.fc(pt_concat, size=self.hidden_size, param_attr='t_fc.w', bias_attr='t_fc.b') nt_hid = fluid.layers.fc(nt_concat, size=self.hidden_size, param_attr='t_fc.w', bias_attr='t_fc.b') # cosine of hidden layers cos_pos = fluid.layers.cos_sim(q_hid, pt_hid) cos_neg = fluid.layers.cos_sim(q_hid, nt_hid) # pairwise hinge_loss loss_part1 = fluid.layers.elementwise_sub( fluid.layers.fill_constant( shape=[fluid.layers.shape(cos_pos)[0], 1], value=self.margin, dtype='float32'), cos_pos) loss_part2 = fluid.layers.elementwise_add(loss_part1, cos_neg) loss_part3 = fluid.layers.elementwise_max( fluid.layers.fill_constant( shape=[fluid.layers.shape(loss_part2)[0], 1], value=0.0, dtype='float32'), loss_part2) avg_cost = fluid.layers.mean(loss_part3) correct = self.get_correct(cos_neg, cos_pos) return q_slots + pt_slots + nt_slots, avg_cost, correct def pred_net(self, query_fields, pos_title_fields, neg_title_fields): q_slots = [ fluid.data( name="q%d" % i, shape=[None, 1], lod_level=1, dtype='int64') for i in range(len(self.query_encoders)) ] pt_slots = [ fluid.data( name="pt%d" % i, shape=[None, 1], lod_level=1, dtype='int64') for i in range(len(self.title_encoders)) ] # lookup embedding for each slot q_embs = [ fluid.embedding( input=query, size=self.emb_shape, param_attr="emb") for query in q_slots ] pt_embs = [ fluid.embedding( input=title, size=self.emb_shape, param_attr="emb") for title in pt_slots ] # encode each embedding field with encoder q_encodes = [ self.query_encoder[i].forward(emb) for i, emb in enumerate(q_embs) ] pt_encodes = [ self.title_encoders[i].forward(emb) for i, emb in enumerate(pt_embs) ] # concat multi view for query, pos_title, neg_title q_concat = fluid.layers.concat(q_encodes) pt_concat = fluid.layers.concat(pt_encodes) # projection of hidden layer q_hid = fluid.layers.fc(q_concat, size=self.hidden_size, param_attr='q_fc.w', bias_attr='q_fc.b') pt_hid = fluid.layers.fc(pt_concat, size=self.hidden_size, param_attr='t_fc.w', bias_attr='t_fc.b') # cosine of hidden layers cos = fluid.layers.cos_sim(q_hid, pt_hid) return cos
en
0.73809
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. bow-encoder cnn-encoder grnn-encoder this is a very simple Encoder factory most default argument values are used create an encoder through create function multi-view simnet # input fields for query, pos_title, neg_title # lookup embedding for each slot # encode each embedding field with encoder # concat multi view for query, pos_title, neg_title # projection of hidden layer # cosine of hidden layers # pairwise hinge_loss # lookup embedding for each slot # encode each embedding field with encoder # concat multi view for query, pos_title, neg_title # projection of hidden layer # cosine of hidden layers
2.278508
2
pmca/usb/driver/__init__.py
kratz00/Sony-PMCA-RE
2
6628324
<reponame>kratz00/Sony-PMCA-RE from collections import namedtuple from ...util import * USB_CLASS_PTP = 6 USB_CLASS_MSC = 8 UsbDevice = namedtuple('UsbDevice', 'handle, idVendor, idProduct') MSC_SENSE_OK = (0, 0, 0) MSC_SENSE_ERROR_UNKNOWN = (0x2, 0xff, 0xff) def parseMscSense(buffer): return parse8(buffer[2:3]) & 0xf, parse8(buffer[12:13]), parse8(buffer[13:14])
from collections import namedtuple from ...util import * USB_CLASS_PTP = 6 USB_CLASS_MSC = 8 UsbDevice = namedtuple('UsbDevice', 'handle, idVendor, idProduct') MSC_SENSE_OK = (0, 0, 0) MSC_SENSE_ERROR_UNKNOWN = (0x2, 0xff, 0xff) def parseMscSense(buffer): return parse8(buffer[2:3]) & 0xf, parse8(buffer[12:13]), parse8(buffer[13:14])
none
1
2.636216
3
test/wcm/helper.py
jonrbates/turing
1
6628325
<filename>test/wcm/helper.py import unittest import torch from turing.wcm.simulator import Simulator class TestCase(unittest.TestCase): def setUp(self) -> None: self.tx = Simulator(T=17) def assertTensorsEqual(self, expected, actual, msg=""): if not torch.equal(expected, actual): self.fail(f'Not equal: {msg}')
<filename>test/wcm/helper.py import unittest import torch from turing.wcm.simulator import Simulator class TestCase(unittest.TestCase): def setUp(self) -> None: self.tx = Simulator(T=17) def assertTensorsEqual(self, expected, actual, msg=""): if not torch.equal(expected, actual): self.fail(f'Not equal: {msg}')
none
1
2.783755
3
recent.py
AlessandroSpallina/LBRYnomics2
0
6628326
<filename>recent.py import config import datetime from daemon_command import daemon_command import json import math import sqlite3 def count_recent_all(now): print("Counting recent activity.", flush=True) count_recent("channels", now) count_recent("streams", now) # Gets called claims for ease for Electron count_boosts(now) print("done.\n") def count_recent(mode, now): """ Count recent things. Output JSON. """ # Claim type if mode == "streams": mode = "claims" # Backwards compatibility if mode == "claims": claim_type = 1 elif mode == "channels": claim_type = 2 # Time cutoffs cutoffs = [0.0, now - 30*86400.0, now-7*86400.0, now-86400.0, now-3600.0] names = [None, "30_days", "7_days", "24_hours", "1_hour"] # Result dictionary result_dict = {} result_dict["unix_time"] = now result_dict["human_time_utc"] = str(datetime.datetime.\ utcfromtimestamp(int(now))) + " UTC" # Connect to the wallet server DB conn = sqlite3.connect(config.claims_db_file) c = conn.cursor() for i in range(len(cutoffs)): query = """ SELECT COUNT(*) FROM claim WHERE creation_timestamp >= ? AND creation_timestamp <= ? AND claim_type = ?; """ row = c.execute(query, (cutoffs[i], now, claim_type)).fetchone() if i==0: result_dict["total_{mode}".format(mode=mode)] = row[0] else: result_dict["new_{mode}_{name}".format(mode=mode, name=names[i])]\ = row[0] # Save some stats to JSON for Electron filename = "json/{mode}_stats.json".format(mode=mode) f = open(filename.format(mode=mode), "w") f.write(json.dumps(result_dict, indent=4)) f.close() print(" Saved {filename}.".format(filename=filename), end=" ") # When did today start? start_of_today = datetime.datetime.fromtimestamp(now, datetime.timezone.utc)\ .replace(hour=0, minute=0, second=0, microsecond=0) start_of_today = start_of_today.timestamp() query = """ SELECT COUNT(*) FROM claim WHERE creation_timestamp >= ? AND claim_type = ?; """ new_today = c.execute(query, (start_of_today, claim_type)).fetchone()[0] print("{new} so far this UTC day.".format(new=new_today)) conn.close() def count_boosts(now): """ Calculate tips and supports over past X amount of time and write JSON output """ labels = ["all_time", "30_days", "7_days", "24_hours", "1_hour"] windows = [None, 30*86400.0, 7*86400.0, 1*86400.0, 3600.0] result = {} result["unix_time"] = now result["human_time_utc"] =\ str(datetime.datetime.utcfromtimestamp(int(now))) + " UTC" block = daemon_command("status")["wallet"]["blocks"] # Save next trending block blocks = {} blocks["current"] = block blocks["next_trending_cycle"] = (int(block / 134) + 1)*134 filename = "json/blocks.json" f = open(filename, "w") f.write(json.dumps(blocks, indent=4)) f.close() print(" Saved {filename}.".format(filename=filename), flush=True) conn = sqlite3.connect(config.claims_db_file) c = conn.cursor() for i in range(len(labels)): if i==0: cutoff = 0.0 else: cutoff = block - windows[i]/(2.5*60) # Count and aggregate tips and supports for the time window query = """ SELECT COUNT(amount) num, MAX(amount) max FROM support """ data = () if i > 0: query += "WHERE height >= ?" data += (cutoff, ) for row in c.execute(query, data): biggest = row[1] result["num_{label}".format(label=labels[i])] = row[0] result["biggest_{label}".format(label=labels[i])] = row[1]/1.0E8 break # Count and aggregate tips and supports for the time window query = """ SELECT amount, COUNT(*) AS num FROM support """ data = () if i > 0: query += "WHERE height >= ?\n" data += (cutoff, ) query += """ GROUP BY amount ORDER BY num DESC LIMIT 1; """ for row in c.execute(query, data): val = None try: val = row[0]/1.0E8 except: pass result["most_common_value_{label}".format(label=labels[i])] = val # Get claim name and ID for max query = """ SELECT claim_name, claim_id FROM claim INNER JOIN support ON claim.claim_hash = support.claim_hash WHERE support.amount = ? """ data = (biggest, ) if i > 0: query += "AND support.height >= ?" data += (cutoff, ) for row in c.execute(query, data): claim_name, claim_id = row[0:2] result["tv_url_{label}".format(label=labels[i])] = "https://lbry.tv/" \ + claim_name + ":" + claim_id # Get NSFW status of max boosted claim query = """ SELECT COUNT(claim_id) FROM claim INNER JOIN tag ON claim.claim_hash = tag.claim_hash INNER JOIN support ON support.claim_hash = claim.claim_hash WHERE ((tag.tag = "mature" OR tag.tag = "nsfw" OR tag.tag = "porn" OR tag.tag = "xxx") AND support.amount = ?) """ data = (biggest, ) if i > 0: query += "AND support.height >= ?" data += (cutoff, ) for row in c.execute(query, data): result["is_nsfw_{label}".format(label=labels[i])] = row[0] != 0 break filename = "json/supports_and_tips.json" f = open(filename, "w") f.write(json.dumps(result, indent=4)) f.close() conn.close() print(" Saved {filename}.".format(filename=filename), flush=True)
<filename>recent.py import config import datetime from daemon_command import daemon_command import json import math import sqlite3 def count_recent_all(now): print("Counting recent activity.", flush=True) count_recent("channels", now) count_recent("streams", now) # Gets called claims for ease for Electron count_boosts(now) print("done.\n") def count_recent(mode, now): """ Count recent things. Output JSON. """ # Claim type if mode == "streams": mode = "claims" # Backwards compatibility if mode == "claims": claim_type = 1 elif mode == "channels": claim_type = 2 # Time cutoffs cutoffs = [0.0, now - 30*86400.0, now-7*86400.0, now-86400.0, now-3600.0] names = [None, "30_days", "7_days", "24_hours", "1_hour"] # Result dictionary result_dict = {} result_dict["unix_time"] = now result_dict["human_time_utc"] = str(datetime.datetime.\ utcfromtimestamp(int(now))) + " UTC" # Connect to the wallet server DB conn = sqlite3.connect(config.claims_db_file) c = conn.cursor() for i in range(len(cutoffs)): query = """ SELECT COUNT(*) FROM claim WHERE creation_timestamp >= ? AND creation_timestamp <= ? AND claim_type = ?; """ row = c.execute(query, (cutoffs[i], now, claim_type)).fetchone() if i==0: result_dict["total_{mode}".format(mode=mode)] = row[0] else: result_dict["new_{mode}_{name}".format(mode=mode, name=names[i])]\ = row[0] # Save some stats to JSON for Electron filename = "json/{mode}_stats.json".format(mode=mode) f = open(filename.format(mode=mode), "w") f.write(json.dumps(result_dict, indent=4)) f.close() print(" Saved {filename}.".format(filename=filename), end=" ") # When did today start? start_of_today = datetime.datetime.fromtimestamp(now, datetime.timezone.utc)\ .replace(hour=0, minute=0, second=0, microsecond=0) start_of_today = start_of_today.timestamp() query = """ SELECT COUNT(*) FROM claim WHERE creation_timestamp >= ? AND claim_type = ?; """ new_today = c.execute(query, (start_of_today, claim_type)).fetchone()[0] print("{new} so far this UTC day.".format(new=new_today)) conn.close() def count_boosts(now): """ Calculate tips and supports over past X amount of time and write JSON output """ labels = ["all_time", "30_days", "7_days", "24_hours", "1_hour"] windows = [None, 30*86400.0, 7*86400.0, 1*86400.0, 3600.0] result = {} result["unix_time"] = now result["human_time_utc"] =\ str(datetime.datetime.utcfromtimestamp(int(now))) + " UTC" block = daemon_command("status")["wallet"]["blocks"] # Save next trending block blocks = {} blocks["current"] = block blocks["next_trending_cycle"] = (int(block / 134) + 1)*134 filename = "json/blocks.json" f = open(filename, "w") f.write(json.dumps(blocks, indent=4)) f.close() print(" Saved {filename}.".format(filename=filename), flush=True) conn = sqlite3.connect(config.claims_db_file) c = conn.cursor() for i in range(len(labels)): if i==0: cutoff = 0.0 else: cutoff = block - windows[i]/(2.5*60) # Count and aggregate tips and supports for the time window query = """ SELECT COUNT(amount) num, MAX(amount) max FROM support """ data = () if i > 0: query += "WHERE height >= ?" data += (cutoff, ) for row in c.execute(query, data): biggest = row[1] result["num_{label}".format(label=labels[i])] = row[0] result["biggest_{label}".format(label=labels[i])] = row[1]/1.0E8 break # Count and aggregate tips and supports for the time window query = """ SELECT amount, COUNT(*) AS num FROM support """ data = () if i > 0: query += "WHERE height >= ?\n" data += (cutoff, ) query += """ GROUP BY amount ORDER BY num DESC LIMIT 1; """ for row in c.execute(query, data): val = None try: val = row[0]/1.0E8 except: pass result["most_common_value_{label}".format(label=labels[i])] = val # Get claim name and ID for max query = """ SELECT claim_name, claim_id FROM claim INNER JOIN support ON claim.claim_hash = support.claim_hash WHERE support.amount = ? """ data = (biggest, ) if i > 0: query += "AND support.height >= ?" data += (cutoff, ) for row in c.execute(query, data): claim_name, claim_id = row[0:2] result["tv_url_{label}".format(label=labels[i])] = "https://lbry.tv/" \ + claim_name + ":" + claim_id # Get NSFW status of max boosted claim query = """ SELECT COUNT(claim_id) FROM claim INNER JOIN tag ON claim.claim_hash = tag.claim_hash INNER JOIN support ON support.claim_hash = claim.claim_hash WHERE ((tag.tag = "mature" OR tag.tag = "nsfw" OR tag.tag = "porn" OR tag.tag = "xxx") AND support.amount = ?) """ data = (biggest, ) if i > 0: query += "AND support.height >= ?" data += (cutoff, ) for row in c.execute(query, data): result["is_nsfw_{label}".format(label=labels[i])] = row[0] != 0 break filename = "json/supports_and_tips.json" f = open(filename, "w") f.write(json.dumps(result, indent=4)) f.close() conn.close() print(" Saved {filename}.".format(filename=filename), flush=True)
en
0.674485
# Gets called claims for ease for Electron Count recent things. Output JSON. # Claim type # Backwards compatibility # Time cutoffs # Result dictionary # Connect to the wallet server DB SELECT COUNT(*) FROM claim WHERE creation_timestamp >= ? AND creation_timestamp <= ? AND claim_type = ?; # Save some stats to JSON for Electron # When did today start? SELECT COUNT(*) FROM claim WHERE creation_timestamp >= ? AND claim_type = ?; Calculate tips and supports over past X amount of time and write JSON output # Save next trending block # Count and aggregate tips and supports for the time window SELECT COUNT(amount) num, MAX(amount) max FROM support # Count and aggregate tips and supports for the time window SELECT amount, COUNT(*) AS num FROM support GROUP BY amount ORDER BY num DESC LIMIT 1; # Get claim name and ID for max SELECT claim_name, claim_id FROM claim INNER JOIN support ON claim.claim_hash = support.claim_hash WHERE support.amount = ? # Get NSFW status of max boosted claim SELECT COUNT(claim_id) FROM claim INNER JOIN tag ON claim.claim_hash = tag.claim_hash INNER JOIN support ON support.claim_hash = claim.claim_hash WHERE ((tag.tag = "mature" OR tag.tag = "nsfw" OR tag.tag = "porn" OR tag.tag = "xxx") AND support.amount = ?)
2.669941
3
webapp/templatetags/webapp_tags.py
ziebisty/Django_Face_Detector
1
6628327
<reponame>ziebisty/Django_Face_Detector from django import template register = template.Library() @register.filter(name='split') def split(str, key): return str.split(key) @register.filter def get_by_index(a, i): return a[i]
from django import template register = template.Library() @register.filter(name='split') def split(str, key): return str.split(key) @register.filter def get_by_index(a, i): return a[i]
none
1
2.074757
2
test/python/old_aer_integration_test/test_simulator_interfaces.py
xkwei1119/qiskit-terra
0
6628328
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=unused-import """Tests for checking qiskit interfaces to simulators.""" import unittest import qiskit import qiskit.extensions.simulator from qiskit.quantum_info import state_fidelity from qiskit import execute from qiskit.test import requires_qe_access, QiskitTestCase, requires_cpp_simulator @requires_cpp_simulator class TestCrossSimulation(QiskitTestCase): """Test output consistency across simulators (from built-in and legacy simulators & IBMQ) """ _desired_fidelity = 0.99 def test_statevector(self): """statevector from a bell state""" qr = qiskit.QuantumRegister(2) circuit = qiskit.QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) sim_cpp = qiskit.providers.aer.StatevectorSimulator() sim_py = qiskit.providers.builtinsimulators.StatevectorSimulatorPy() result_cpp = execute(circuit, sim_cpp).result() result_py = execute(circuit, sim_py).result() statevector_cpp = result_cpp.get_statevector() statevector_py = result_py.get_statevector() fidelity = state_fidelity(statevector_cpp, statevector_py) self.assertGreater( fidelity, self._desired_fidelity, "cpp vs. py statevector has low fidelity{0:.2g}.".format(fidelity)) def test_qasm(self): """counts from a GHZ state""" qr = qiskit.QuantumRegister(3) cr = qiskit.ClassicalRegister(3) circuit = qiskit.QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.measure(qr, cr) sim_cpp = qiskit.providers.aer.QasmSimulator() sim_py = qiskit.providers.builtinsimulators.QasmSimulatorPy() shots = 2000 result_cpp = execute(circuit, sim_cpp, shots=shots).result() result_py = execute(circuit, sim_py, shots=shots).result() counts_cpp = result_cpp.get_counts() counts_py = result_py.get_counts() self.assertDictAlmostEqual(counts_cpp, counts_py, shots*0.08) def test_qasm_reset_measure(self): """counts from a qasm program with measure and reset in the middle""" qr = qiskit.QuantumRegister(3) cr = qiskit.ClassicalRegister(3) circuit = qiskit.QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.reset(qr[0]) circuit.cx(qr[1], qr[2]) circuit.t(qr) circuit.measure(qr[1], cr[1]) circuit.h(qr[2]) circuit.measure(qr[2], cr[2]) sim_cpp = qiskit.providers.aer.QasmSimulator() sim_py = qiskit.providers.builtinsimulators.QasmSimulatorPy() shots = 1000 result_cpp = execute(circuit, sim_cpp, shots=shots, seed=1).result() result_py = execute(circuit, sim_py, shots=shots, seed=1).result() counts_cpp = result_cpp.get_counts() counts_py = result_py.get_counts() self.assertDictAlmostEqual(counts_cpp, counts_py, shots * 0.06) if __name__ == '__main__': unittest.main(verbosity=2)
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=unused-import """Tests for checking qiskit interfaces to simulators.""" import unittest import qiskit import qiskit.extensions.simulator from qiskit.quantum_info import state_fidelity from qiskit import execute from qiskit.test import requires_qe_access, QiskitTestCase, requires_cpp_simulator @requires_cpp_simulator class TestCrossSimulation(QiskitTestCase): """Test output consistency across simulators (from built-in and legacy simulators & IBMQ) """ _desired_fidelity = 0.99 def test_statevector(self): """statevector from a bell state""" qr = qiskit.QuantumRegister(2) circuit = qiskit.QuantumCircuit(qr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) sim_cpp = qiskit.providers.aer.StatevectorSimulator() sim_py = qiskit.providers.builtinsimulators.StatevectorSimulatorPy() result_cpp = execute(circuit, sim_cpp).result() result_py = execute(circuit, sim_py).result() statevector_cpp = result_cpp.get_statevector() statevector_py = result_py.get_statevector() fidelity = state_fidelity(statevector_cpp, statevector_py) self.assertGreater( fidelity, self._desired_fidelity, "cpp vs. py statevector has low fidelity{0:.2g}.".format(fidelity)) def test_qasm(self): """counts from a GHZ state""" qr = qiskit.QuantumRegister(3) cr = qiskit.ClassicalRegister(3) circuit = qiskit.QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[1], qr[2]) circuit.measure(qr, cr) sim_cpp = qiskit.providers.aer.QasmSimulator() sim_py = qiskit.providers.builtinsimulators.QasmSimulatorPy() shots = 2000 result_cpp = execute(circuit, sim_cpp, shots=shots).result() result_py = execute(circuit, sim_py, shots=shots).result() counts_cpp = result_cpp.get_counts() counts_py = result_py.get_counts() self.assertDictAlmostEqual(counts_cpp, counts_py, shots*0.08) def test_qasm_reset_measure(self): """counts from a qasm program with measure and reset in the middle""" qr = qiskit.QuantumRegister(3) cr = qiskit.ClassicalRegister(3) circuit = qiskit.QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.reset(qr[0]) circuit.cx(qr[1], qr[2]) circuit.t(qr) circuit.measure(qr[1], cr[1]) circuit.h(qr[2]) circuit.measure(qr[2], cr[2]) sim_cpp = qiskit.providers.aer.QasmSimulator() sim_py = qiskit.providers.builtinsimulators.QasmSimulatorPy() shots = 1000 result_cpp = execute(circuit, sim_cpp, shots=shots, seed=1).result() result_py = execute(circuit, sim_py, shots=shots, seed=1).result() counts_cpp = result_cpp.get_counts() counts_py = result_py.get_counts() self.assertDictAlmostEqual(counts_cpp, counts_py, shots * 0.06) if __name__ == '__main__': unittest.main(verbosity=2)
en
0.890423
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=unused-import Tests for checking qiskit interfaces to simulators. Test output consistency across simulators (from built-in and legacy simulators & IBMQ) statevector from a bell state counts from a GHZ state counts from a qasm program with measure and reset in the middle
2.036805
2
pajbot/web/routes/api/pleblist.py
UVClay/SkookumBot
1
6628329
import logging from flask import abort from flask import url_for from flask_restful import Resource from flask_restful import reqparse from sqlalchemy import and_ from sqlalchemy import func from sqlalchemy.orm import noload import pajbot.web.utils from pajbot import utils from pajbot.managers.db import DBManager from pajbot.models.pleblist import PleblistManager from pajbot.models.pleblist import PleblistSong from pajbot.models.pleblist import PleblistSongInfo from pajbot.models.stream import Stream from pajbot.web import app log = logging.getLogger(__name__) class APIPleblistSkip(Resource): def __init__(self): super().__init__() self.post_parser = reqparse.RequestParser() self.post_parser.add_argument("password", required=True, location="cookies") def post(self, song_id, **options): args = self.post_parser.parse_args() try: pajbot.web.utils.pleblist_login(args["password"], app.bot_config) except pajbot.exc.InvalidLogin as e: return {"error": str(e)}, 401 with DBManager.create_session_scope() as db_session: song = db_session.query(PleblistSong).options(noload("*")).filter_by(id=song_id).one_or_none() if song is None: abort(404) db_session.delete(song) db_session.flush() return {"message": "GOT EM"}, 200 class APIPleblistListCurrent(Resource): def get(self): with DBManager.create_session_scope() as session: current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first() if current_stream is None: return {"error": "Stream offline"}, 400 songs = session.query(PleblistSong).filter( PleblistSong.stream_id == current_stream.id, PleblistSong.date_played.is_(None) ) return pajbot.web.utils.jsonify_list("songs", songs, base_url=url_for(self.endpoint, _external=True)) class APIPleblistListStream(Resource): def get(self, stream_id): with DBManager.create_session_scope() as session: songs = session.query(PleblistSong).filter_by(stream_id=stream_id) return pajbot.web.utils.jsonify_list( "songs", songs, base_url=url_for(self.endpoint, stream_id=stream_id, _external=True) ) class APIPleblistListAfter(Resource): def get(self, song_id): with DBManager.create_session_scope() as session: current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first() if current_stream is None: return {"error": "Stream offline"}, 400 songs = session.query(PleblistSong).filter( and_( PleblistSong.stream_id == current_stream.id, PleblistSong.date_played.is_(None), PleblistSong.id > song_id, ) ) return pajbot.web.utils.jsonify_list( "songs", songs, base_url=url_for(self.endpoint, song_id=song_id, _external=True) ) class APIPleblistAdd(Resource): def __init__(self): super().__init__() self.post_parser = reqparse.RequestParser() self.post_parser.add_argument("youtube_id", trim=True, required=True) self.post_parser.add_argument("password", trim=True, required=True) self.post_parser.add_argument("skip_after", type=int, default=None, required=False) def post(self): args = self.post_parser.parse_args() try: pajbot.web.utils.pleblist_login(args["password"], app.bot_config) except pajbot.exc.InvalidLogin as e: return {"error": str(e)}, 401 with DBManager.create_session_scope() as session: youtube_id = args["youtube_id"] current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first() if current_stream is None: return {"error": "Stream offline"}, 400 skip_after = args["skip_after"] log.info(f"Request song youtube ID: {youtube_id}") song_requested = PleblistSong(current_stream.id, youtube_id, skip_after=skip_after) session.add(song_requested) song_info = session.query(PleblistSongInfo).filter_by(pleblist_song_youtube_id=youtube_id).first() if song_info is None and song_requested.song_info is None: PleblistManager.init(app.bot_config["youtube"]["developer_key"]) song_info = PleblistManager.create_pleblist_song_info(song_requested.youtube_id) if song_info is not False: session.add(song_info) session.commit() return {"success": "got em!"}, 200 class APIPleblistNext(Resource): def __init__(self): super().__init__() self.post_parser = reqparse.RequestParser() self.post_parser.add_argument("song_id", type=int, required=True) self.post_parser.add_argument("password", trim=True, required=True) def post(self): args = self.post_parser.parse_args() try: pajbot.web.utils.pleblist_login(args["password"], app.bot_config) except pajbot.exc.InvalidLogin as e: return {"error": str(e)}, 401 with DBManager.create_session_scope() as session: try: current_song = ( session.query(PleblistSong) .filter(PleblistSong.id == args["song_id"]) .order_by(PleblistSong.date_added.asc()) .first() ) except ValueError: return {"error": "Invalid data song_id"}, 400 if current_song is None: return {"error": "No song active in the pleblist"}, 404 current_song.date_played = utils.now() session.commit() # TODO: Add more data. # Was this song forcefully skipped? Or did it end naturally. return {"success": "got em!"}, 200 class APIPleblistValidate(Resource): def __init__(self): super().__init__() self.post_parser = reqparse.RequestParser() self.post_parser.add_argument("youtube_id", trim=True, required=True) def post(self): args = self.post_parser.parse_args() with DBManager.create_session_scope() as session: youtube_id = args["youtube_id"] log.info(f"Validating youtube ID {youtube_id}") song_info = session.query(PleblistSongInfo).filter_by(pleblist_song_youtube_id=youtube_id).first() if song_info is not None: return {"message": "success", "song_info": song_info.jsonify()} PleblistManager.init(app.bot_config["youtube"]["developer_key"]) song_info = PleblistManager.create_pleblist_song_info(youtube_id) if not song_info and len(youtube_id) > 11: youtube_id = youtube_id[:11] song_info = session.query(PleblistSongInfo).filter_by(pleblist_song_youtube_id=youtube_id).first() if song_info is not None: return {"message": "success", "new_youtube_id": youtube_id, "song_info": song_info.jsonify()} else: song_info = PleblistManager.create_pleblist_song_info(youtube_id) if song_info: log.debug(song_info) session.add(song_info) session.commit() return {"message": "success", "new_youtube_id": youtube_id, "song_info": song_info.jsonify()} return {"message": "invalid youtube id", "song_info": None} class APIPleblistBlacklist(Resource): @staticmethod def get(): with DBManager.create_session_scope() as session: current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first() if current_stream is None: return {"error": "Stream offline"}, 400 # TODO: implement this return {"error": "NOT IMPLEMENTED"}, 400 # return jsonify({'success': True}) def jsonify_query(query): return [PleblistSongTop(v[0], v[1]).jsonify() for v in query] class PleblistSongTop: def __init__(self, song, count): self.song = song self.count = count def jsonify(self): payload = self.song.jsonify() payload["count"] = self.count return payload class APIPleblistTop(Resource): def get(self): with DBManager.create_session_scope() as session: # songs = session.query(PleblistSong, func.count(PleblistSong.song_info).label('total')).group_by(PleblistSong.youtube_id).order_by('total DESC') songs = ( session.query(PleblistSong, func.count(PleblistSong.youtube_id).label("total")) .group_by(PleblistSong.youtube_id) .order_by("total DESC") ) log.info(songs) log.info(songs.all()) return pajbot.web.utils.jsonify_list( "songs", songs, default_limit=50, max_limit=500, base_url=url_for(self.endpoint, _external=True), jsonify_method=jsonify_query, ) class APIPleblistCheck(Resource): def __init__(self): super().__init__() self.post_parser = reqparse.RequestParser() self.post_parser.add_argument("password", required=True, location="cookies") def get(self): args = self.post_parser.parse_args() try: pajbot.web.utils.pleblist_login(args["password"], app.bot_config) except pajbot.exc.InvalidLogin as e: return {"error": str(e)}, 401 return {"success": True} def init(api): api.add_resource(APIPleblistSkip, "/pleblist/skip/<int:song_id>") api.add_resource(APIPleblistListCurrent, "/pleblist/list") api.add_resource(APIPleblistListStream, "/pleblist/list/<stream_id>") api.add_resource(APIPleblistListAfter, "/pleblist/list/after/<song_id>") api.add_resource(APIPleblistAdd, "/pleblist/add") api.add_resource(APIPleblistNext, "/pleblist/next") api.add_resource(APIPleblistValidate, "/pleblist/validate") api.add_resource(APIPleblistBlacklist, "/pleblist/blacklist") api.add_resource(APIPleblistTop, "/pleblist/top") api.add_resource(APIPleblistCheck, "/pleblist/check")
import logging from flask import abort from flask import url_for from flask_restful import Resource from flask_restful import reqparse from sqlalchemy import and_ from sqlalchemy import func from sqlalchemy.orm import noload import pajbot.web.utils from pajbot import utils from pajbot.managers.db import DBManager from pajbot.models.pleblist import PleblistManager from pajbot.models.pleblist import PleblistSong from pajbot.models.pleblist import PleblistSongInfo from pajbot.models.stream import Stream from pajbot.web import app log = logging.getLogger(__name__) class APIPleblistSkip(Resource): def __init__(self): super().__init__() self.post_parser = reqparse.RequestParser() self.post_parser.add_argument("password", required=True, location="cookies") def post(self, song_id, **options): args = self.post_parser.parse_args() try: pajbot.web.utils.pleblist_login(args["password"], app.bot_config) except pajbot.exc.InvalidLogin as e: return {"error": str(e)}, 401 with DBManager.create_session_scope() as db_session: song = db_session.query(PleblistSong).options(noload("*")).filter_by(id=song_id).one_or_none() if song is None: abort(404) db_session.delete(song) db_session.flush() return {"message": "GOT EM"}, 200 class APIPleblistListCurrent(Resource): def get(self): with DBManager.create_session_scope() as session: current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first() if current_stream is None: return {"error": "Stream offline"}, 400 songs = session.query(PleblistSong).filter( PleblistSong.stream_id == current_stream.id, PleblistSong.date_played.is_(None) ) return pajbot.web.utils.jsonify_list("songs", songs, base_url=url_for(self.endpoint, _external=True)) class APIPleblistListStream(Resource): def get(self, stream_id): with DBManager.create_session_scope() as session: songs = session.query(PleblistSong).filter_by(stream_id=stream_id) return pajbot.web.utils.jsonify_list( "songs", songs, base_url=url_for(self.endpoint, stream_id=stream_id, _external=True) ) class APIPleblistListAfter(Resource): def get(self, song_id): with DBManager.create_session_scope() as session: current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first() if current_stream is None: return {"error": "Stream offline"}, 400 songs = session.query(PleblistSong).filter( and_( PleblistSong.stream_id == current_stream.id, PleblistSong.date_played.is_(None), PleblistSong.id > song_id, ) ) return pajbot.web.utils.jsonify_list( "songs", songs, base_url=url_for(self.endpoint, song_id=song_id, _external=True) ) class APIPleblistAdd(Resource): def __init__(self): super().__init__() self.post_parser = reqparse.RequestParser() self.post_parser.add_argument("youtube_id", trim=True, required=True) self.post_parser.add_argument("password", trim=True, required=True) self.post_parser.add_argument("skip_after", type=int, default=None, required=False) def post(self): args = self.post_parser.parse_args() try: pajbot.web.utils.pleblist_login(args["password"], app.bot_config) except pajbot.exc.InvalidLogin as e: return {"error": str(e)}, 401 with DBManager.create_session_scope() as session: youtube_id = args["youtube_id"] current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first() if current_stream is None: return {"error": "Stream offline"}, 400 skip_after = args["skip_after"] log.info(f"Request song youtube ID: {youtube_id}") song_requested = PleblistSong(current_stream.id, youtube_id, skip_after=skip_after) session.add(song_requested) song_info = session.query(PleblistSongInfo).filter_by(pleblist_song_youtube_id=youtube_id).first() if song_info is None and song_requested.song_info is None: PleblistManager.init(app.bot_config["youtube"]["developer_key"]) song_info = PleblistManager.create_pleblist_song_info(song_requested.youtube_id) if song_info is not False: session.add(song_info) session.commit() return {"success": "got em!"}, 200 class APIPleblistNext(Resource): def __init__(self): super().__init__() self.post_parser = reqparse.RequestParser() self.post_parser.add_argument("song_id", type=int, required=True) self.post_parser.add_argument("password", trim=True, required=True) def post(self): args = self.post_parser.parse_args() try: pajbot.web.utils.pleblist_login(args["password"], app.bot_config) except pajbot.exc.InvalidLogin as e: return {"error": str(e)}, 401 with DBManager.create_session_scope() as session: try: current_song = ( session.query(PleblistSong) .filter(PleblistSong.id == args["song_id"]) .order_by(PleblistSong.date_added.asc()) .first() ) except ValueError: return {"error": "Invalid data song_id"}, 400 if current_song is None: return {"error": "No song active in the pleblist"}, 404 current_song.date_played = utils.now() session.commit() # TODO: Add more data. # Was this song forcefully skipped? Or did it end naturally. return {"success": "got em!"}, 200 class APIPleblistValidate(Resource): def __init__(self): super().__init__() self.post_parser = reqparse.RequestParser() self.post_parser.add_argument("youtube_id", trim=True, required=True) def post(self): args = self.post_parser.parse_args() with DBManager.create_session_scope() as session: youtube_id = args["youtube_id"] log.info(f"Validating youtube ID {youtube_id}") song_info = session.query(PleblistSongInfo).filter_by(pleblist_song_youtube_id=youtube_id).first() if song_info is not None: return {"message": "success", "song_info": song_info.jsonify()} PleblistManager.init(app.bot_config["youtube"]["developer_key"]) song_info = PleblistManager.create_pleblist_song_info(youtube_id) if not song_info and len(youtube_id) > 11: youtube_id = youtube_id[:11] song_info = session.query(PleblistSongInfo).filter_by(pleblist_song_youtube_id=youtube_id).first() if song_info is not None: return {"message": "success", "new_youtube_id": youtube_id, "song_info": song_info.jsonify()} else: song_info = PleblistManager.create_pleblist_song_info(youtube_id) if song_info: log.debug(song_info) session.add(song_info) session.commit() return {"message": "success", "new_youtube_id": youtube_id, "song_info": song_info.jsonify()} return {"message": "invalid youtube id", "song_info": None} class APIPleblistBlacklist(Resource): @staticmethod def get(): with DBManager.create_session_scope() as session: current_stream = session.query(Stream).filter_by(ended=False).order_by(Stream.stream_start).first() if current_stream is None: return {"error": "Stream offline"}, 400 # TODO: implement this return {"error": "NOT IMPLEMENTED"}, 400 # return jsonify({'success': True}) def jsonify_query(query): return [PleblistSongTop(v[0], v[1]).jsonify() for v in query] class PleblistSongTop: def __init__(self, song, count): self.song = song self.count = count def jsonify(self): payload = self.song.jsonify() payload["count"] = self.count return payload class APIPleblistTop(Resource): def get(self): with DBManager.create_session_scope() as session: # songs = session.query(PleblistSong, func.count(PleblistSong.song_info).label('total')).group_by(PleblistSong.youtube_id).order_by('total DESC') songs = ( session.query(PleblistSong, func.count(PleblistSong.youtube_id).label("total")) .group_by(PleblistSong.youtube_id) .order_by("total DESC") ) log.info(songs) log.info(songs.all()) return pajbot.web.utils.jsonify_list( "songs", songs, default_limit=50, max_limit=500, base_url=url_for(self.endpoint, _external=True), jsonify_method=jsonify_query, ) class APIPleblistCheck(Resource): def __init__(self): super().__init__() self.post_parser = reqparse.RequestParser() self.post_parser.add_argument("password", required=True, location="cookies") def get(self): args = self.post_parser.parse_args() try: pajbot.web.utils.pleblist_login(args["password"], app.bot_config) except pajbot.exc.InvalidLogin as e: return {"error": str(e)}, 401 return {"success": True} def init(api): api.add_resource(APIPleblistSkip, "/pleblist/skip/<int:song_id>") api.add_resource(APIPleblistListCurrent, "/pleblist/list") api.add_resource(APIPleblistListStream, "/pleblist/list/<stream_id>") api.add_resource(APIPleblistListAfter, "/pleblist/list/after/<song_id>") api.add_resource(APIPleblistAdd, "/pleblist/add") api.add_resource(APIPleblistNext, "/pleblist/next") api.add_resource(APIPleblistValidate, "/pleblist/validate") api.add_resource(APIPleblistBlacklist, "/pleblist/blacklist") api.add_resource(APIPleblistTop, "/pleblist/top") api.add_resource(APIPleblistCheck, "/pleblist/check")
en
0.310099
# TODO: Add more data. # Was this song forcefully skipped? Or did it end naturally. # TODO: implement this # return jsonify({'success': True}) # songs = session.query(PleblistSong, func.count(PleblistSong.song_info).label('total')).group_by(PleblistSong.youtube_id).order_by('total DESC')
2.156266
2
7_Sarven_Desert/285-Chase_Them/chase_them.py
katitek/Code-Combat
0
6628330
def onSpawn(e): while True: enemy = pet.findNearestByType("munchkin") if enemy && pet.isReady("chase"): pet.chase(enemy) potion = pet.findNearestByType("potion") if potion: pet.fetch(potion) pet.on("spawn", onSpawn)
def onSpawn(e): while True: enemy = pet.findNearestByType("munchkin") if enemy && pet.isReady("chase"): pet.chase(enemy) potion = pet.findNearestByType("potion") if potion: pet.fetch(potion) pet.on("spawn", onSpawn)
none
1
2.660079
3
main.py
samuel-tsegaye/youtube_downloader
1
6628331
<gh_stars>1-10 import tkinter as tk from tkinter.ttk import Progressbar from tkinter import * from PIL import ImageTk import ttk splash_root = Tk() splash_root.title("Downloader") splash_root.geometry("800x300") progress = Progressbar(splash_root, style="red.Horizontal.TProgressbar", orient=HORIZONTAL, length=500, mode='determinate', ) splash_root.overrideredirect(True) #sa = ImageTk.PhotoImage(file="image/211.jpg") #label1 = Label(splash_root, image=sa) #label1.place(x=0, y=0) a = '#283747' width_of_window = 460 height_of_window = 200 screen_width = splash_root.winfo_screenwidth() screen_height = splash_root.winfo_screenheight() x_coordinate = (screen_width / 2) - (width_of_window / 2) y_coordinate = (screen_height / 5) - (height_of_window / 5) splash_root.geometry("%dx%d+%d+%d" % (width_of_window, height_of_window, x_coordinate, y_coordinate)) s = ttk.Style() s.theme_use('clam') s.configure("red.Horizontal.TProgressbar", foreground='red', background='#4f4f4f') progress = Progressbar(splash_root, style="red.Horizontal.TProgressbar", orient=HORIZONTAL, length=500, mode='determinate', ) def main_window(): splash_root.destroy() main = tk.Tk() main.title("youtube Downloader") main.resizable(width=False, height=False) main.geometry("800x600") rows = 0 while rows < 50: main.rowconfigure(rows, weight=1) main.columnconfigure(rows, weight=1) rows += 1 yd = ttk.Notebook(main) yd.grid(row=0, column=0, columnspan=50, rowspan=50, sticky="NESW",) page1 = ttk.Frame(yd) yd.add(page1, text="Direct Downloader ") frame1 = Canvas(master=page1, width=200, height=200, bg='#D1F2EB') frame1.pack(expand=YES, fill=BOTH) page2 = ttk.Frame(yd) yd.add(page2, text="Playlist Downloader ") frame2 = Canvas(master=page2, width=200, height=200, bg='#FAD7A0') frame2.pack(expand=YES, fill=BOTH) page3 = ttk.Frame(yd) yd.add(page3, text="To Mp3 converter") frame3 = Canvas(master=page3, width=200, height=200, bg='#EDBB99') frame3.pack(expand=YES, fill=BOTH) main.mainloop() def bar(): l4 = Label(splash_root, text='Loading...', fg='white', bg=a) lst4 = ('Calibri (Body)', 10) l4.config(font=lst4) l4.place(x=18, y=210) import time r = 0 for i in range(100): progress['value'] = r splash_root.update_idletasks() time.sleep(0.03) r = r + 1 b1 = Button(splash_root, width=10, height=1, text='Get Started', command=bar, border=0, fg=a, bg='white') b1.place(x=170, y=200) Frame(splash_root, width=427, height=241, bg=a).place(x=0, y=0) # 249794 splash_label = Label(splash_root, text="welcome to youtube downloader", fg='white', bg=a) lst1 = ('Calibri (Body)', 12, 'bold') splash_label.config(font=lst1) splash_label.place(x=50, y=50) splash_label = Label(splash_root, text='creater', fg='white', bg=a) lst2 = ('Calibri (Body)', 12) splash_label.config(font=lst2) splash_label.place(x=270, y=160) splash_label = Label(splash_root, text='<NAME>', fg='white', bg=a) lst3 = ('Calibri (Body)', 9) splash_label.config(font=lst3) splash_label.place(x=285, y=180) splash_root.after(3000, main_window) mainloop()
import tkinter as tk from tkinter.ttk import Progressbar from tkinter import * from PIL import ImageTk import ttk splash_root = Tk() splash_root.title("Downloader") splash_root.geometry("800x300") progress = Progressbar(splash_root, style="red.Horizontal.TProgressbar", orient=HORIZONTAL, length=500, mode='determinate', ) splash_root.overrideredirect(True) #sa = ImageTk.PhotoImage(file="image/211.jpg") #label1 = Label(splash_root, image=sa) #label1.place(x=0, y=0) a = '#283747' width_of_window = 460 height_of_window = 200 screen_width = splash_root.winfo_screenwidth() screen_height = splash_root.winfo_screenheight() x_coordinate = (screen_width / 2) - (width_of_window / 2) y_coordinate = (screen_height / 5) - (height_of_window / 5) splash_root.geometry("%dx%d+%d+%d" % (width_of_window, height_of_window, x_coordinate, y_coordinate)) s = ttk.Style() s.theme_use('clam') s.configure("red.Horizontal.TProgressbar", foreground='red', background='#4f4f4f') progress = Progressbar(splash_root, style="red.Horizontal.TProgressbar", orient=HORIZONTAL, length=500, mode='determinate', ) def main_window(): splash_root.destroy() main = tk.Tk() main.title("youtube Downloader") main.resizable(width=False, height=False) main.geometry("800x600") rows = 0 while rows < 50: main.rowconfigure(rows, weight=1) main.columnconfigure(rows, weight=1) rows += 1 yd = ttk.Notebook(main) yd.grid(row=0, column=0, columnspan=50, rowspan=50, sticky="NESW",) page1 = ttk.Frame(yd) yd.add(page1, text="Direct Downloader ") frame1 = Canvas(master=page1, width=200, height=200, bg='#D1F2EB') frame1.pack(expand=YES, fill=BOTH) page2 = ttk.Frame(yd) yd.add(page2, text="Playlist Downloader ") frame2 = Canvas(master=page2, width=200, height=200, bg='#FAD7A0') frame2.pack(expand=YES, fill=BOTH) page3 = ttk.Frame(yd) yd.add(page3, text="To Mp3 converter") frame3 = Canvas(master=page3, width=200, height=200, bg='#EDBB99') frame3.pack(expand=YES, fill=BOTH) main.mainloop() def bar(): l4 = Label(splash_root, text='Loading...', fg='white', bg=a) lst4 = ('Calibri (Body)', 10) l4.config(font=lst4) l4.place(x=18, y=210) import time r = 0 for i in range(100): progress['value'] = r splash_root.update_idletasks() time.sleep(0.03) r = r + 1 b1 = Button(splash_root, width=10, height=1, text='Get Started', command=bar, border=0, fg=a, bg='white') b1.place(x=170, y=200) Frame(splash_root, width=427, height=241, bg=a).place(x=0, y=0) # 249794 splash_label = Label(splash_root, text="welcome to youtube downloader", fg='white', bg=a) lst1 = ('Calibri (Body)', 12, 'bold') splash_label.config(font=lst1) splash_label.place(x=50, y=50) splash_label = Label(splash_root, text='creater', fg='white', bg=a) lst2 = ('Calibri (Body)', 12) splash_label.config(font=lst2) splash_label.place(x=270, y=160) splash_label = Label(splash_root, text='<NAME>', fg='white', bg=a) lst3 = ('Calibri (Body)', 9) splash_label.config(font=lst3) splash_label.place(x=285, y=180) splash_root.after(3000, main_window) mainloop()
en
0.19484
#sa = ImageTk.PhotoImage(file="image/211.jpg") #label1 = Label(splash_root, image=sa) #label1.place(x=0, y=0) # 249794
3.306717
3
tests/tests.py
LukasKlement/python-marketman
0
6628332
<reponame>LukasKlement/python-marketman import os import unittest import xmlrunner from python_marketman.api import Marketman from python_marketman.exceptions import MarketmanAuthenticationFailed class AuthenticationTestCase(unittest.TestCase): def test_connect(self): with self.assertRaises(MarketmanAuthenticationFailed): faulty_credentials = { 'api_key': 'somekey', 'api_password': '<PASSWORD>' } Marketman(**faulty_credentials) if __name__ == '__main__': if not os.path.exists('test-results'): os.makedirs('test-results') with open('test-results/results.xml', 'wb') as output: unittest.main( testRunner=xmlrunner.XMLTestRunner(output=output), failfast=False, buffer=False, catchbreak=False)
import os import unittest import xmlrunner from python_marketman.api import Marketman from python_marketman.exceptions import MarketmanAuthenticationFailed class AuthenticationTestCase(unittest.TestCase): def test_connect(self): with self.assertRaises(MarketmanAuthenticationFailed): faulty_credentials = { 'api_key': 'somekey', 'api_password': '<PASSWORD>' } Marketman(**faulty_credentials) if __name__ == '__main__': if not os.path.exists('test-results'): os.makedirs('test-results') with open('test-results/results.xml', 'wb') as output: unittest.main( testRunner=xmlrunner.XMLTestRunner(output=output), failfast=False, buffer=False, catchbreak=False)
none
1
2.672842
3
goalboost/model/mongomint.py
JohnLockwood/Goalboost
0
6628333
<filename>goalboost/model/mongomint.py """ MongoMintDocument is a wafer thin wrapper around a PyMongo collection """ from bson import ObjectId class MongoMintDocument(object): """Create a MongoMintDocument object. pymongo_client_object - a MongoClient instance collection_name - a name for the collection we want to validate on / operate against database (optional, default="goalboost"), a name for the database where the collection will live """ def __init__(self, pymongo_client_object, collection_name, database="goalboost"): self.connection = pymongo_client_object self.database = database self.collection_name = collection_name self._clear_validation_errors() """upsert - easy single document save. If validate generates no error, then insert a new document or update the existing one, returning true. If validate did return an error, return false. In that case. self.errors can be inspected to find what happened. """ def upsert(self, model_dictionary): if self._is_valid(model_dictionary): if "_id" in model_dictionary: # Update case self.collection.replace_one( \ filter = {"_id" : model_dictionary["_id"]}, replacement=model_dictionary) else: # Insert case self.collection.insert_one(model_dictionary) return True else: return False """find_by_id - Return a single document by id or None, accepting either string or ObjectId as argument""" # Always create an ObjectId, correctly handles both string case and ObjectId case def find_by_id(self, id): return self.collection.find_one({"_id": ObjectId(id) }) """collection (property) Easily use the underlying collection to use native pymongo methods, e.g. drop, find_one, etc. """ @property def collection(self): return self.connection[self.database][self.collection_name] """validate (optional override allows you to provide pre-save data validation To implement if needed, add one string per validation failure to self.errors. """ def validate(self, model_dictionary): pass # Private methods def _clear_validation_errors(self): self.errors = [] def _is_valid(self, model_dictionary): self._clear_validation_errors() self.validate(model_dictionary) return len(self.errors) == 0
<filename>goalboost/model/mongomint.py """ MongoMintDocument is a wafer thin wrapper around a PyMongo collection """ from bson import ObjectId class MongoMintDocument(object): """Create a MongoMintDocument object. pymongo_client_object - a MongoClient instance collection_name - a name for the collection we want to validate on / operate against database (optional, default="goalboost"), a name for the database where the collection will live """ def __init__(self, pymongo_client_object, collection_name, database="goalboost"): self.connection = pymongo_client_object self.database = database self.collection_name = collection_name self._clear_validation_errors() """upsert - easy single document save. If validate generates no error, then insert a new document or update the existing one, returning true. If validate did return an error, return false. In that case. self.errors can be inspected to find what happened. """ def upsert(self, model_dictionary): if self._is_valid(model_dictionary): if "_id" in model_dictionary: # Update case self.collection.replace_one( \ filter = {"_id" : model_dictionary["_id"]}, replacement=model_dictionary) else: # Insert case self.collection.insert_one(model_dictionary) return True else: return False """find_by_id - Return a single document by id or None, accepting either string or ObjectId as argument""" # Always create an ObjectId, correctly handles both string case and ObjectId case def find_by_id(self, id): return self.collection.find_one({"_id": ObjectId(id) }) """collection (property) Easily use the underlying collection to use native pymongo methods, e.g. drop, find_one, etc. """ @property def collection(self): return self.connection[self.database][self.collection_name] """validate (optional override allows you to provide pre-save data validation To implement if needed, add one string per validation failure to self.errors. """ def validate(self, model_dictionary): pass # Private methods def _clear_validation_errors(self): self.errors = [] def _is_valid(self, model_dictionary): self._clear_validation_errors() self.validate(model_dictionary) return len(self.errors) == 0
en
0.610457
MongoMintDocument is a wafer thin wrapper around a PyMongo collection Create a MongoMintDocument object. pymongo_client_object - a MongoClient instance collection_name - a name for the collection we want to validate on / operate against database (optional, default="goalboost"), a name for the database where the collection will live upsert - easy single document save. If validate generates no error, then insert a new document or update the existing one, returning true. If validate did return an error, return false. In that case. self.errors can be inspected to find what happened. # Update case # Insert case find_by_id - Return a single document by id or None, accepting either string or ObjectId as argument # Always create an ObjectId, correctly handles both string case and ObjectId case collection (property) Easily use the underlying collection to use native pymongo methods, e.g. drop, find_one, etc. validate (optional override allows you to provide pre-save data validation To implement if needed, add one string per validation failure to self.errors. # Private methods
2.990527
3
neuralmonkey/server.py
hoangcuong2011/LDNMT
15
6628334
import argparse import json import datetime import flask from flask import Flask, request from neuralmonkey.dataset import Dataset from neuralmonkey.learning_utils import run_on_dataset from neuralmonkey.run import CONFIG, initialize_for_running APP = Flask(__name__) APP.config.from_object(__name__) APP.config['args'] = None @APP.route('/', methods=['GET', 'POST']) def post_request(): start_time = datetime.datetime.now() request_data = request.get_json() if request_data is None: response_data = {"error": "No data were provided."} code = 400 else: args = APP.config['args'] try: dataset = Dataset("request", request_data, {}) # TODO check the dataset # check_dataset_and_coders(dataset, args.encoders) _, response_data = run_on_dataset( args.tf_manager, args.runners, dataset, args.postprocess, write_out=False) code = 200 # pylint: disable=broad-except except Exception as exc: response_data = {'error': str(exc)} code = 400 response_data['duration'] = ( datetime.datetime.now() - start_time).total_seconds() json_response = json.dumps(response_data) response = flask.Response(json_response, content_type='application/json; charset=utf-8') response.headers.add('content-length', len(json_response.encode('utf-8'))) response.status_code = code return response def main() -> None: parser = argparse.ArgumentParser( description="Runs Neural Monkey as a web server.") parser.add_argument("--port", type=int, default=5000) parser.add_argument("--host", type=str, default="127.0.0.1") parser.add_argument("--configuration", type=str) cli_args = parser.parse_args() print("") # pylint: disable=no-member CONFIG.load_file(cli_args.configuration) CONFIG.build_model() initialize_for_running(CONFIG.model.output, CONFIG.model.tf_manager, None) APP.config['args'] = CONFIG.model APP.run(port=cli_args.port, host=cli_args.host)
import argparse import json import datetime import flask from flask import Flask, request from neuralmonkey.dataset import Dataset from neuralmonkey.learning_utils import run_on_dataset from neuralmonkey.run import CONFIG, initialize_for_running APP = Flask(__name__) APP.config.from_object(__name__) APP.config['args'] = None @APP.route('/', methods=['GET', 'POST']) def post_request(): start_time = datetime.datetime.now() request_data = request.get_json() if request_data is None: response_data = {"error": "No data were provided."} code = 400 else: args = APP.config['args'] try: dataset = Dataset("request", request_data, {}) # TODO check the dataset # check_dataset_and_coders(dataset, args.encoders) _, response_data = run_on_dataset( args.tf_manager, args.runners, dataset, args.postprocess, write_out=False) code = 200 # pylint: disable=broad-except except Exception as exc: response_data = {'error': str(exc)} code = 400 response_data['duration'] = ( datetime.datetime.now() - start_time).total_seconds() json_response = json.dumps(response_data) response = flask.Response(json_response, content_type='application/json; charset=utf-8') response.headers.add('content-length', len(json_response.encode('utf-8'))) response.status_code = code return response def main() -> None: parser = argparse.ArgumentParser( description="Runs Neural Monkey as a web server.") parser.add_argument("--port", type=int, default=5000) parser.add_argument("--host", type=str, default="127.0.0.1") parser.add_argument("--configuration", type=str) cli_args = parser.parse_args() print("") # pylint: disable=no-member CONFIG.load_file(cli_args.configuration) CONFIG.build_model() initialize_for_running(CONFIG.model.output, CONFIG.model.tf_manager, None) APP.config['args'] = CONFIG.model APP.run(port=cli_args.port, host=cli_args.host)
en
0.355478
# TODO check the dataset # check_dataset_and_coders(dataset, args.encoders) # pylint: disable=broad-except # pylint: disable=no-member
2.558361
3
test/sql/test_compare.py
pasenor/sqlalchemy
0
6628335
import importlib import itertools import random from sqlalchemy import and_ from sqlalchemy import Boolean from sqlalchemy import case from sqlalchemy import cast from sqlalchemy import Column from sqlalchemy import column from sqlalchemy import dialects from sqlalchemy import exists from sqlalchemy import extract from sqlalchemy import Float from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import or_ from sqlalchemy import select from sqlalchemy import String from sqlalchemy import Table from sqlalchemy import table from sqlalchemy import text from sqlalchemy import tuple_ from sqlalchemy import union from sqlalchemy import union_all from sqlalchemy import util from sqlalchemy.schema import Sequence from sqlalchemy.sql import bindparam from sqlalchemy.sql import ColumnElement from sqlalchemy.sql import False_ from sqlalchemy.sql import func from sqlalchemy.sql import operators from sqlalchemy.sql import True_ from sqlalchemy.sql import type_coerce from sqlalchemy.sql import visitors from sqlalchemy.sql.base import HasCacheKey from sqlalchemy.sql.elements import _label_reference from sqlalchemy.sql.elements import _textual_label_reference from sqlalchemy.sql.elements import Annotated from sqlalchemy.sql.elements import ClauseElement from sqlalchemy.sql.elements import ClauseList from sqlalchemy.sql.elements import CollationClause from sqlalchemy.sql.elements import Immutable from sqlalchemy.sql.elements import Null from sqlalchemy.sql.elements import Slice from sqlalchemy.sql.elements import UnaryExpression from sqlalchemy.sql.functions import FunctionElement from sqlalchemy.sql.functions import GenericFunction from sqlalchemy.sql.functions import ReturnTypeFromArgs from sqlalchemy.sql.selectable import _OffsetLimitParam from sqlalchemy.sql.selectable import AliasedReturnsRows from sqlalchemy.sql.selectable import FromGrouping from sqlalchemy.sql.selectable import Selectable from sqlalchemy.sql.selectable import SelectStatementGrouping from sqlalchemy.sql.visitors import InternalTraversal from sqlalchemy.testing import eq_ from sqlalchemy.testing import fixtures from sqlalchemy.testing import is_false from sqlalchemy.testing import is_not_ from sqlalchemy.testing import is_true from sqlalchemy.testing import ne_ from sqlalchemy.testing.util import random_choices from sqlalchemy.util import class_hierarchy meta = MetaData() meta2 = MetaData() table_a = Table("a", meta, Column("a", Integer), Column("b", String)) table_b_like_a = Table("b2", meta, Column("a", Integer), Column("b", String)) table_a_2 = Table("a", meta2, Column("a", Integer), Column("b", String)) table_a_2_fs = Table( "a", meta2, Column("a", Integer), Column("b", String), schema="fs" ) table_a_2_bs = Table( "a", meta2, Column("a", Integer), Column("b", String), schema="bs" ) table_b = Table("b", meta, Column("a", Integer), Column("b", Integer)) table_c = Table("c", meta, Column("x", Integer), Column("y", Integer)) table_d = Table("d", meta, Column("y", Integer), Column("z", Integer)) class MyEntity(HasCacheKey): def __init__(self, name, element): self.name = name self.element = element _cache_key_traversal = [ ("name", InternalTraversal.dp_string), ("element", InternalTraversal.dp_clauseelement), ] class CoreFixtures(object): # lambdas which return a tuple of ColumnElement objects. # must return at least two objects that should compare differently. # to test more varieties of "difference" additional objects can be added. fixtures = [ lambda: ( column("q"), column("x"), column("q", Integer), column("q", String), ), lambda: (~column("q", Boolean), ~column("p", Boolean)), lambda: ( table_a.c.a.label("foo"), table_a.c.a.label("bar"), table_a.c.b.label("foo"), ), lambda: ( _label_reference(table_a.c.a.desc()), _label_reference(table_a.c.a.asc()), ), lambda: (_textual_label_reference("a"), _textual_label_reference("b")), lambda: ( text("select a, b from table").columns(a=Integer, b=String), text("select a, b, c from table").columns( a=Integer, b=String, c=Integer ), text("select a, b, c from table where foo=:bar").bindparams( bindparam("bar", type_=Integer) ), text("select a, b, c from table where foo=:foo").bindparams( bindparam("foo", type_=Integer) ), text("select a, b, c from table where foo=:bar").bindparams( bindparam("bar", type_=String) ), ), lambda: ( column("q") == column("x"), column("q") == column("y"), column("z") == column("x"), column("z") + column("x"), column("z") - column("x"), column("x") - column("z"), column("z") > column("x"), column("x").in_([5, 7]), column("x").in_([10, 7, 8]), # note these two are mathematically equivalent but for now they # are considered to be different column("z") >= column("x"), column("x") <= column("z"), column("q").between(5, 6), column("q").between(5, 6, symmetric=True), column("q").like("somstr"), column("q").like("somstr", escape="\\"), column("q").like("somstr", escape="X"), ), lambda: ( table_a.c.a, table_a.c.a._annotate({"orm": True}), table_a.c.a._annotate({"orm": True})._annotate({"bar": False}), table_a.c.a._annotate( {"orm": True, "parententity": MyEntity("a", table_a)} ), table_a.c.a._annotate( {"orm": True, "parententity": MyEntity("b", table_a)} ), table_a.c.a._annotate( {"orm": True, "parententity": MyEntity("b", select([table_a]))} ), ), lambda: ( cast(column("q"), Integer), cast(column("q"), Float), cast(column("p"), Integer), ), lambda: ( bindparam("x"), bindparam("y"), bindparam("x", type_=Integer), bindparam("x", type_=String), bindparam(None), ), lambda: (_OffsetLimitParam("x"), _OffsetLimitParam("y")), lambda: (func.foo(), func.foo(5), func.bar()), lambda: (func.current_date(), func.current_time()), lambda: ( func.next_value(Sequence("q")), func.next_value(Sequence("p")), ), lambda: (True_(), False_()), lambda: (Null(),), lambda: (ReturnTypeFromArgs("foo"), ReturnTypeFromArgs(5)), lambda: (FunctionElement(5), FunctionElement(5, 6)), lambda: (func.count(), func.not_count()), lambda: (func.char_length("abc"), func.char_length("def")), lambda: (GenericFunction("a", "b"), GenericFunction("a")), lambda: (CollationClause("foobar"), CollationClause("batbar")), lambda: ( type_coerce(column("q", Integer), String), type_coerce(column("q", Integer), Float), type_coerce(column("z", Integer), Float), ), lambda: (table_a.c.a, table_b.c.a), lambda: (tuple_(1, 2), tuple_(3, 4)), lambda: (func.array_agg([1, 2]), func.array_agg([3, 4])), lambda: ( func.percentile_cont(0.5).within_group(table_a.c.a), func.percentile_cont(0.5).within_group(table_a.c.b), func.percentile_cont(0.5).within_group(table_a.c.a, table_a.c.b), func.percentile_cont(0.5).within_group( table_a.c.a, table_a.c.b, column("q") ), ), lambda: ( func.is_equal("a", "b").as_comparison(1, 2), func.is_equal("a", "c").as_comparison(1, 2), func.is_equal("a", "b").as_comparison(2, 1), func.is_equal("a", "b", "c").as_comparison(1, 2), func.foobar("a", "b").as_comparison(1, 2), ), lambda: ( func.row_number().over(order_by=table_a.c.a), func.row_number().over(order_by=table_a.c.a, range_=(0, 10)), func.row_number().over(order_by=table_a.c.a, range_=(None, 10)), func.row_number().over(order_by=table_a.c.a, rows=(None, 20)), func.row_number().over(order_by=table_a.c.b), func.row_number().over( order_by=table_a.c.a, partition_by=table_a.c.b ), ), lambda: ( func.count(1).filter(table_a.c.a == 5), func.count(1).filter(table_a.c.a == 10), func.foob(1).filter(table_a.c.a == 10), ), lambda: ( and_(table_a.c.a == 5, table_a.c.b == table_b.c.a), and_(table_a.c.a == 5, table_a.c.a == table_b.c.a), or_(table_a.c.a == 5, table_a.c.b == table_b.c.a), ClauseList(table_a.c.a == 5, table_a.c.b == table_b.c.a), ClauseList(table_a.c.a == 5, table_a.c.b == table_a.c.a), ), lambda: ( case(whens=[(table_a.c.a == 5, 10), (table_a.c.a == 10, 20)]), case(whens=[(table_a.c.a == 18, 10), (table_a.c.a == 10, 20)]), case(whens=[(table_a.c.a == 5, 10), (table_a.c.b == 10, 20)]), case( whens=[ (table_a.c.a == 5, 10), (table_a.c.b == 10, 20), (table_a.c.a == 9, 12), ] ), case( whens=[(table_a.c.a == 5, 10), (table_a.c.a == 10, 20)], else_=30, ), case({"wendy": "W", "jack": "J"}, value=table_a.c.a, else_="E"), case({"wendy": "W", "jack": "J"}, value=table_a.c.b, else_="E"), case({"wendy_w": "W", "jack": "J"}, value=table_a.c.a, else_="E"), ), lambda: ( extract("foo", table_a.c.a), extract("foo", table_a.c.b), extract("bar", table_a.c.a), ), lambda: ( Slice(1, 2, 5), Slice(1, 5, 5), Slice(1, 5, 10), Slice(2, 10, 15), ), lambda: ( select([table_a.c.a]), select([table_a.c.a, table_a.c.b]), select([table_a.c.b, table_a.c.a]), select([table_a.c.a]).where(table_a.c.b == 5), select([table_a.c.a]) .where(table_a.c.b == 5) .where(table_a.c.a == 10), select([table_a.c.a]).where(table_a.c.b == 5).with_for_update(), select([table_a.c.a]) .where(table_a.c.b == 5) .with_for_update(nowait=True), select([table_a.c.a]).where(table_a.c.b == 5).correlate(table_b), select([table_a.c.a]) .where(table_a.c.b == 5) .correlate_except(table_b), ), lambda: ( select([table_a.c.a]).cte(), select([table_a.c.a]).cte(recursive=True), select([table_a.c.a]).cte(name="some_cte", recursive=True), select([table_a.c.a]).cte(name="some_cte"), select([table_a.c.a]).cte(name="some_cte").alias("other_cte"), select([table_a.c.a]) .cte(name="some_cte") .union_all(select([table_a.c.a])), select([table_a.c.a]) .cte(name="some_cte") .union_all(select([table_a.c.b])), select([table_a.c.a]).lateral(), select([table_a.c.a]).lateral(name="bar"), table_a.tablesample(func.bernoulli(1)), table_a.tablesample(func.bernoulli(1), seed=func.random()), table_a.tablesample(func.bernoulli(1), seed=func.other_random()), table_a.tablesample(func.hoho(1)), table_a.tablesample(func.bernoulli(1), name="bar"), table_a.tablesample( func.bernoulli(1), name="bar", seed=func.random() ), ), lambda: ( select([table_a.c.a]), select([table_a.c.a]).prefix_with("foo"), select([table_a.c.a]).prefix_with("foo", dialect="mysql"), select([table_a.c.a]).prefix_with("foo", dialect="postgresql"), select([table_a.c.a]).prefix_with("bar"), select([table_a.c.a]).suffix_with("bar"), ), lambda: ( select([table_a_2.c.a]), select([table_a_2_fs.c.a]), select([table_a_2_bs.c.a]), ), lambda: ( select([table_a.c.a]), select([table_a.c.a]).with_hint(None, "some hint"), select([table_a.c.a]).with_hint(None, "some other hint"), select([table_a.c.a]).with_hint(table_a, "some hint"), select([table_a.c.a]) .with_hint(table_a, "some hint") .with_hint(None, "some other hint"), select([table_a.c.a]).with_hint(table_a, "some other hint"), select([table_a.c.a]).with_hint( table_a, "some hint", dialect_name="mysql" ), select([table_a.c.a]).with_hint( table_a, "some hint", dialect_name="postgresql" ), ), lambda: ( table_a.join(table_b, table_a.c.a == table_b.c.a), table_a.join( table_b, and_(table_a.c.a == table_b.c.a, table_a.c.b == 1) ), table_a.outerjoin(table_b, table_a.c.a == table_b.c.a), ), lambda: ( table_a.alias("a"), table_a.alias("b"), table_a.alias(), table_b.alias("a"), select([table_a.c.a]).alias("a"), ), lambda: ( FromGrouping(table_a.alias("a")), FromGrouping(table_a.alias("b")), ), lambda: ( SelectStatementGrouping(select([table_a])), SelectStatementGrouping(select([table_b])), ), lambda: ( select([table_a.c.a]).scalar_subquery(), select([table_a.c.a]).where(table_a.c.b == 5).scalar_subquery(), ), lambda: ( exists().where(table_a.c.a == 5), exists().where(table_a.c.b == 5), ), lambda: ( union(select([table_a.c.a]), select([table_a.c.b])), union(select([table_a.c.a]), select([table_a.c.b])).order_by("a"), union_all(select([table_a.c.a]), select([table_a.c.b])), union(select([table_a.c.a])), union( select([table_a.c.a]), select([table_a.c.b]).where(table_a.c.b > 5), ), ), lambda: ( table("a", column("x"), column("y")), table("a", column("y"), column("x")), table("b", column("x"), column("y")), table("a", column("x"), column("y"), column("z")), table("a", column("x"), column("y", Integer)), table("a", column("q"), column("y", Integer)), ), lambda: (table_a, table_b), ] dont_compare_values_fixtures = [ lambda: ( # same number of params each time, so compare for IN # with legacy behavior of bind for each value works column("x").in_(random_choices(range(10), k=3)), # expanding IN places the whole list into a single parameter # so it can be of arbitrary length as well column("x").in_( bindparam( "q", random_choices(range(10), k=random.randint(0, 7)), expanding=True, ) ), column("x") == random.randint(1, 10), ) ] def _complex_fixtures(): def one(): a1 = table_a.alias() a2 = table_b_like_a.alias() stmt = ( select([table_a.c.a, a1.c.b, a2.c.b]) .where(table_a.c.b == a1.c.b) .where(a1.c.b == a2.c.b) .where(a1.c.a == 5) ) return stmt def one_diff(): a1 = table_b_like_a.alias() a2 = table_a.alias() stmt = ( select([table_a.c.a, a1.c.b, a2.c.b]) .where(table_a.c.b == a1.c.b) .where(a1.c.b == a2.c.b) .where(a1.c.a == 5) ) return stmt def two(): inner = one().subquery() stmt = select([table_b.c.a, inner.c.a, inner.c.b]).select_from( table_b.join(inner, table_b.c.b == inner.c.b) ) return stmt def three(): a1 = table_a.alias() a2 = table_a.alias() ex = exists().where(table_b.c.b == a1.c.a) stmt = ( select([a1.c.a, a2.c.a]) .select_from(a1.join(a2, a1.c.b == a2.c.b)) .where(ex) ) return stmt return [one(), one_diff(), two(), three()] fixtures.append(_complex_fixtures) class CacheKeyFixture(object): def _run_cache_key_fixture(self, fixture, compare_values): case_a = fixture() case_b = fixture() for a, b in itertools.combinations_with_replacement( range(len(case_a)), 2 ): if a == b: a_key = case_a[a]._generate_cache_key() b_key = case_b[b]._generate_cache_key() is_not_(a_key, None) is_not_(b_key, None) eq_(a_key.key, b_key.key) eq_(hash(a_key), hash(b_key)) for a_param, b_param in zip( a_key.bindparams, b_key.bindparams ): assert a_param.compare( b_param, compare_values=compare_values ) else: a_key = case_a[a]._generate_cache_key() b_key = case_b[b]._generate_cache_key() if a_key.key == b_key.key: for a_param, b_param in zip( a_key.bindparams, b_key.bindparams ): if not a_param.compare( b_param, compare_values=compare_values ): break else: # this fails unconditionally since we could not # find bound parameter values that differed. # Usually we intended to get two distinct keys here # so the failure will be more descriptive using the # ne_() assertion. ne_(a_key.key, b_key.key) else: ne_(a_key.key, b_key.key) # ClauseElement-specific test to ensure the cache key # collected all the bound parameters if isinstance(case_a[a], ClauseElement) and isinstance( case_b[b], ClauseElement ): assert_a_params = [] assert_b_params = [] visitors.traverse_depthfirst( case_a[a], {}, {"bindparam": assert_a_params.append} ) visitors.traverse_depthfirst( case_b[b], {}, {"bindparam": assert_b_params.append} ) # note we're asserting the order of the params as well as # if there are dupes or not. ordering has to be # deterministic and matches what a traversal would provide. # regular traverse_depthfirst does produce dupes in cases # like # select([some_alias]). # select_from(join(some_alias, other_table)) # where a bound parameter is inside of some_alias. the # cache key case is more minimalistic eq_( sorted(a_key.bindparams, key=lambda b: b.key), sorted( util.unique_list(assert_a_params), key=lambda b: b.key ), ) eq_( sorted(b_key.bindparams, key=lambda b: b.key), sorted( util.unique_list(assert_b_params), key=lambda b: b.key ), ) class CacheKeyTest(CacheKeyFixture, CoreFixtures, fixtures.TestBase): def test_cache_key(self): for fixtures_, compare_values in [ (self.fixtures, True), (self.dont_compare_values_fixtures, False), ]: for fixture in fixtures_: self._run_cache_key_fixture(fixture, compare_values) def test_cache_key_unknown_traverse(self): class Foobar1(ClauseElement): _traverse_internals = [ ("key", InternalTraversal.dp_anon_name), ("type_", InternalTraversal.dp_unknown_structure), ] def __init__(self, key, type_): self.key = key self.type_ = type_ f1 = Foobar1("foo", String()) eq_(f1._generate_cache_key(), None) def test_cache_key_no_method(self): class Foobar1(ClauseElement): pass class Foobar2(ColumnElement): pass # the None for cache key will prevent objects # which contain these elements from being cached. f1 = Foobar1() eq_(f1._generate_cache_key(), None) f2 = Foobar2() eq_(f2._generate_cache_key(), None) s1 = select([column("q"), Foobar2()]) eq_(s1._generate_cache_key(), None) def test_get_children_no_method(self): class Foobar1(ClauseElement): pass class Foobar2(ColumnElement): pass f1 = Foobar1() eq_(f1.get_children(), []) f2 = Foobar2() eq_(f2.get_children(), []) def test_copy_internals_no_method(self): class Foobar1(ClauseElement): pass class Foobar2(ColumnElement): pass f1 = Foobar1() f2 = Foobar2() f1._copy_internals() f2._copy_internals() class CompareAndCopyTest(CoreFixtures, fixtures.TestBase): @classmethod def setup_class(cls): # TODO: we need to get dialects here somehow, perhaps in test_suite? [ importlib.import_module("sqlalchemy.dialects.%s" % d) for d in dialects.__all__ if not d.startswith("_") ] def test_all_present(self): need = set( cls for cls in class_hierarchy(ClauseElement) if issubclass(cls, (ColumnElement, Selectable)) and ( "__init__" in cls.__dict__ or issubclass(cls, AliasedReturnsRows) ) and not issubclass(cls, (Annotated)) and "orm" not in cls.__module__ and "compiler" not in cls.__module__ and "crud" not in cls.__module__ and "dialects" not in cls.__module__ # TODO: dialects? ).difference({ColumnElement, UnaryExpression}) for fixture in self.fixtures + self.dont_compare_values_fixtures: case_a = fixture() for elem in case_a: for mro in type(elem).__mro__: need.discard(mro) is_false(bool(need), "%d Remaining classes: %r" % (len(need), need)) def test_compare_labels(self): for fixtures_, compare_values in [ (self.fixtures, True), (self.dont_compare_values_fixtures, False), ]: for fixture in fixtures_: case_a = fixture() case_b = fixture() for a, b in itertools.combinations_with_replacement( range(len(case_a)), 2 ): if a == b: is_true( case_a[a].compare( case_b[b], compare_annotations=True, compare_values=compare_values, ), "%r != %r" % (case_a[a], case_b[b]), ) else: is_false( case_a[a].compare( case_b[b], compare_annotations=True, compare_values=compare_values, ), "%r == %r" % (case_a[a], case_b[b]), ) def test_compare_col_identity(self): stmt1 = ( select([table_a.c.a, table_b.c.b]) .where(table_a.c.a == table_b.c.b) .alias() ) stmt1_c = ( select([table_a.c.a, table_b.c.b]) .where(table_a.c.a == table_b.c.b) .alias() ) stmt2 = union(select([table_a]), select([table_b])) equivalents = {table_a.c.a: [table_b.c.a]} is_false( stmt1.compare(stmt2, use_proxies=True, equivalents=equivalents) ) is_true( stmt1.compare(stmt1_c, use_proxies=True, equivalents=equivalents) ) is_true( (table_a.c.a == table_b.c.b).compare( stmt1.c.a == stmt1.c.b, use_proxies=True, equivalents=equivalents, ) ) def test_copy_internals(self): for fixtures_, compare_values in [ (self.fixtures, True), (self.dont_compare_values_fixtures, False), ]: for fixture in fixtures_: case_a = fixture() case_b = fixture() assert case_a[0].compare( case_b[0], compare_values=compare_values ) clone = visitors.replacement_traverse( case_a[0], {}, lambda elem: None ) assert clone.compare(case_b[0], compare_values=compare_values) stack = [clone] seen = {clone} found_elements = False while stack: obj = stack.pop(0) items = [ subelem for key, elem in clone.__dict__.items() if key != "_is_clone_of" and elem is not None for subelem in util.to_list(elem) if ( isinstance(subelem, (ColumnElement, ClauseList)) and subelem not in seen and not isinstance(subelem, Immutable) and subelem is not case_a[0] ) ] stack.extend(items) seen.update(items) if obj is not clone: found_elements = True # ensure the element will not compare as true obj.compare = lambda other, **kw: False obj.__visit_name__ = "dont_match" if found_elements: assert not clone.compare( case_b[0], compare_values=compare_values ) assert case_a[0].compare( case_b[0], compare_values=compare_values ) class CompareClausesTest(fixtures.TestBase): def test_compare_metadata_tables(self): # metadata Table objects cache on their own identity, not their # structure. This is mainly to reduce the size of cache keys # as well as reduce computational overhead, as Table objects have # very large internal state and they are also generally global # objects. t1 = Table("a", MetaData(), Column("q", Integer), Column("p", Integer)) t2 = Table("a", MetaData(), Column("q", Integer), Column("p", Integer)) ne_(t1._generate_cache_key(), t2._generate_cache_key()) eq_(t1._generate_cache_key().key, (t1,)) def test_compare_adhoc_tables(self): # non-metadata tables compare on their structure. these objects are # not commonly used. # note this test is a bit redundant as we have a similar test # via the fixtures also t1 = table("a", Column("q", Integer), Column("p", Integer)) t2 = table("a", Column("q", Integer), Column("p", Integer)) t3 = table("b", Column("q", Integer), Column("p", Integer)) t4 = table("a", Column("q", Integer), Column("x", Integer)) eq_(t1._generate_cache_key(), t2._generate_cache_key()) ne_(t1._generate_cache_key(), t3._generate_cache_key()) ne_(t1._generate_cache_key(), t4._generate_cache_key()) ne_(t3._generate_cache_key(), t4._generate_cache_key()) def test_compare_comparison_associative(self): l1 = table_c.c.x == table_d.c.y l2 = table_d.c.y == table_c.c.x l3 = table_c.c.x == table_d.c.z is_true(l1.compare(l1)) is_true(l1.compare(l2)) is_false(l1.compare(l3)) def test_compare_comparison_non_commutative_inverses(self): l1 = table_c.c.x >= table_d.c.y l2 = table_d.c.y < table_c.c.x l3 = table_d.c.y <= table_c.c.x # we're not doing this kind of commutativity right now. is_false(l1.compare(l2)) is_false(l1.compare(l3)) def test_compare_clauselist_associative(self): l1 = and_(table_c.c.x == table_d.c.y, table_c.c.y == table_d.c.z) l2 = and_(table_c.c.y == table_d.c.z, table_c.c.x == table_d.c.y) l3 = and_(table_c.c.x == table_d.c.z, table_c.c.y == table_d.c.y) is_true(l1.compare(l1)) is_true(l1.compare(l2)) is_false(l1.compare(l3)) def test_compare_clauselist_not_associative(self): l1 = ClauseList( table_c.c.x, table_c.c.y, table_d.c.y, operator=operators.sub ) l2 = ClauseList( table_d.c.y, table_c.c.x, table_c.c.y, operator=operators.sub ) is_true(l1.compare(l1)) is_false(l1.compare(l2)) def test_compare_clauselist_assoc_different_operator(self): l1 = and_(table_c.c.x == table_d.c.y, table_c.c.y == table_d.c.z) l2 = or_(table_c.c.y == table_d.c.z, table_c.c.x == table_d.c.y) is_false(l1.compare(l2)) def test_compare_clauselist_not_assoc_different_operator(self): l1 = ClauseList( table_c.c.x, table_c.c.y, table_d.c.y, operator=operators.sub ) l2 = ClauseList( table_c.c.x, table_c.c.y, table_d.c.y, operator=operators.div ) is_false(l1.compare(l2)) def test_compare_labels(self): is_true(column("q").label(None).compare(column("q").label(None))) is_false(column("q").label("foo").compare(column("q").label(None))) is_false(column("q").label(None).compare(column("q").label("foo"))) is_false(column("q").label("foo").compare(column("q").label("bar"))) is_true(column("q").label("foo").compare(column("q").label("foo"))) def test_compare_binds(self): b1 = bindparam("foo", type_=Integer()) b2 = bindparam("foo", type_=Integer()) b3 = bindparam("foo", type_=String()) def c1(): return 5 def c2(): return 6 b4 = bindparam("foo", type_=Integer(), callable_=c1) b5 = bindparam("foo", type_=Integer(), callable_=c2) b6 = bindparam("foo", type_=Integer(), callable_=c1) b7 = bindparam("foo", type_=Integer, value=5) b8 = bindparam("foo", type_=Integer, value=6) is_false(b1.compare(b4)) is_true(b4.compare(b6)) is_false(b4.compare(b5)) is_true(b1.compare(b2)) # currently not comparing "key", as we often have to compare # anonymous names. however we should really check for that # is_true(b1.compare(b3)) is_false(b1.compare(b3)) is_false(b1.compare(b7)) is_false(b7.compare(b8)) is_true(b7.compare(b7)) def test_compare_tables(self): is_true(table_a.compare(table_a_2)) # the "proxy" version compares schema tables on metadata identity is_false(table_a.compare(table_a_2, use_proxies=True)) # same for lower case tables since it compares lower case columns # using proxies, which makes it very unlikely to have multiple # table() objects with columns that compare equally is_false( table("a", column("x", Integer), column("q", String)).compare( table("a", column("x", Integer), column("q", String)), use_proxies=True, ) ) def test_compare_annotated_clears_mapping(self): t = table("t", column("x"), column("y")) x_a = t.c.x._annotate({"foo": True}) x_b = t.c.x._annotate({"foo": True}) is_true(x_a.compare(x_b, compare_annotations=True)) is_false( x_a.compare(x_b._annotate({"bar": True}), compare_annotations=True) ) s1 = select([t.c.x])._annotate({"foo": True}) s2 = select([t.c.x])._annotate({"foo": True}) is_true(s1.compare(s2, compare_annotations=True)) is_false( s1.compare(s2._annotate({"bar": True}), compare_annotations=True) ) def test_compare_annotated_wo_annotations(self): t = table("t", column("x"), column("y")) x_a = t.c.x._annotate({}) x_b = t.c.x._annotate({"foo": True}) is_true(t.c.x.compare(x_a)) is_true(x_b.compare(x_a)) is_true(x_a.compare(t.c.x)) is_false(x_a.compare(t.c.y)) is_false(t.c.y.compare(x_a)) is_true((t.c.x == 5).compare(x_a == 5)) is_false((t.c.y == 5).compare(x_a == 5)) s = select([t]).subquery() x_p = s.c.x is_false(x_a.compare(x_p)) is_false(t.c.x.compare(x_p)) x_p_a = x_p._annotate({}) is_true(x_p_a.compare(x_p)) is_true(x_p.compare(x_p_a)) is_false(x_p_a.compare(x_a))
import importlib import itertools import random from sqlalchemy import and_ from sqlalchemy import Boolean from sqlalchemy import case from sqlalchemy import cast from sqlalchemy import Column from sqlalchemy import column from sqlalchemy import dialects from sqlalchemy import exists from sqlalchemy import extract from sqlalchemy import Float from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import or_ from sqlalchemy import select from sqlalchemy import String from sqlalchemy import Table from sqlalchemy import table from sqlalchemy import text from sqlalchemy import tuple_ from sqlalchemy import union from sqlalchemy import union_all from sqlalchemy import util from sqlalchemy.schema import Sequence from sqlalchemy.sql import bindparam from sqlalchemy.sql import ColumnElement from sqlalchemy.sql import False_ from sqlalchemy.sql import func from sqlalchemy.sql import operators from sqlalchemy.sql import True_ from sqlalchemy.sql import type_coerce from sqlalchemy.sql import visitors from sqlalchemy.sql.base import HasCacheKey from sqlalchemy.sql.elements import _label_reference from sqlalchemy.sql.elements import _textual_label_reference from sqlalchemy.sql.elements import Annotated from sqlalchemy.sql.elements import ClauseElement from sqlalchemy.sql.elements import ClauseList from sqlalchemy.sql.elements import CollationClause from sqlalchemy.sql.elements import Immutable from sqlalchemy.sql.elements import Null from sqlalchemy.sql.elements import Slice from sqlalchemy.sql.elements import UnaryExpression from sqlalchemy.sql.functions import FunctionElement from sqlalchemy.sql.functions import GenericFunction from sqlalchemy.sql.functions import ReturnTypeFromArgs from sqlalchemy.sql.selectable import _OffsetLimitParam from sqlalchemy.sql.selectable import AliasedReturnsRows from sqlalchemy.sql.selectable import FromGrouping from sqlalchemy.sql.selectable import Selectable from sqlalchemy.sql.selectable import SelectStatementGrouping from sqlalchemy.sql.visitors import InternalTraversal from sqlalchemy.testing import eq_ from sqlalchemy.testing import fixtures from sqlalchemy.testing import is_false from sqlalchemy.testing import is_not_ from sqlalchemy.testing import is_true from sqlalchemy.testing import ne_ from sqlalchemy.testing.util import random_choices from sqlalchemy.util import class_hierarchy meta = MetaData() meta2 = MetaData() table_a = Table("a", meta, Column("a", Integer), Column("b", String)) table_b_like_a = Table("b2", meta, Column("a", Integer), Column("b", String)) table_a_2 = Table("a", meta2, Column("a", Integer), Column("b", String)) table_a_2_fs = Table( "a", meta2, Column("a", Integer), Column("b", String), schema="fs" ) table_a_2_bs = Table( "a", meta2, Column("a", Integer), Column("b", String), schema="bs" ) table_b = Table("b", meta, Column("a", Integer), Column("b", Integer)) table_c = Table("c", meta, Column("x", Integer), Column("y", Integer)) table_d = Table("d", meta, Column("y", Integer), Column("z", Integer)) class MyEntity(HasCacheKey): def __init__(self, name, element): self.name = name self.element = element _cache_key_traversal = [ ("name", InternalTraversal.dp_string), ("element", InternalTraversal.dp_clauseelement), ] class CoreFixtures(object): # lambdas which return a tuple of ColumnElement objects. # must return at least two objects that should compare differently. # to test more varieties of "difference" additional objects can be added. fixtures = [ lambda: ( column("q"), column("x"), column("q", Integer), column("q", String), ), lambda: (~column("q", Boolean), ~column("p", Boolean)), lambda: ( table_a.c.a.label("foo"), table_a.c.a.label("bar"), table_a.c.b.label("foo"), ), lambda: ( _label_reference(table_a.c.a.desc()), _label_reference(table_a.c.a.asc()), ), lambda: (_textual_label_reference("a"), _textual_label_reference("b")), lambda: ( text("select a, b from table").columns(a=Integer, b=String), text("select a, b, c from table").columns( a=Integer, b=String, c=Integer ), text("select a, b, c from table where foo=:bar").bindparams( bindparam("bar", type_=Integer) ), text("select a, b, c from table where foo=:foo").bindparams( bindparam("foo", type_=Integer) ), text("select a, b, c from table where foo=:bar").bindparams( bindparam("bar", type_=String) ), ), lambda: ( column("q") == column("x"), column("q") == column("y"), column("z") == column("x"), column("z") + column("x"), column("z") - column("x"), column("x") - column("z"), column("z") > column("x"), column("x").in_([5, 7]), column("x").in_([10, 7, 8]), # note these two are mathematically equivalent but for now they # are considered to be different column("z") >= column("x"), column("x") <= column("z"), column("q").between(5, 6), column("q").between(5, 6, symmetric=True), column("q").like("somstr"), column("q").like("somstr", escape="\\"), column("q").like("somstr", escape="X"), ), lambda: ( table_a.c.a, table_a.c.a._annotate({"orm": True}), table_a.c.a._annotate({"orm": True})._annotate({"bar": False}), table_a.c.a._annotate( {"orm": True, "parententity": MyEntity("a", table_a)} ), table_a.c.a._annotate( {"orm": True, "parententity": MyEntity("b", table_a)} ), table_a.c.a._annotate( {"orm": True, "parententity": MyEntity("b", select([table_a]))} ), ), lambda: ( cast(column("q"), Integer), cast(column("q"), Float), cast(column("p"), Integer), ), lambda: ( bindparam("x"), bindparam("y"), bindparam("x", type_=Integer), bindparam("x", type_=String), bindparam(None), ), lambda: (_OffsetLimitParam("x"), _OffsetLimitParam("y")), lambda: (func.foo(), func.foo(5), func.bar()), lambda: (func.current_date(), func.current_time()), lambda: ( func.next_value(Sequence("q")), func.next_value(Sequence("p")), ), lambda: (True_(), False_()), lambda: (Null(),), lambda: (ReturnTypeFromArgs("foo"), ReturnTypeFromArgs(5)), lambda: (FunctionElement(5), FunctionElement(5, 6)), lambda: (func.count(), func.not_count()), lambda: (func.char_length("abc"), func.char_length("def")), lambda: (GenericFunction("a", "b"), GenericFunction("a")), lambda: (CollationClause("foobar"), CollationClause("batbar")), lambda: ( type_coerce(column("q", Integer), String), type_coerce(column("q", Integer), Float), type_coerce(column("z", Integer), Float), ), lambda: (table_a.c.a, table_b.c.a), lambda: (tuple_(1, 2), tuple_(3, 4)), lambda: (func.array_agg([1, 2]), func.array_agg([3, 4])), lambda: ( func.percentile_cont(0.5).within_group(table_a.c.a), func.percentile_cont(0.5).within_group(table_a.c.b), func.percentile_cont(0.5).within_group(table_a.c.a, table_a.c.b), func.percentile_cont(0.5).within_group( table_a.c.a, table_a.c.b, column("q") ), ), lambda: ( func.is_equal("a", "b").as_comparison(1, 2), func.is_equal("a", "c").as_comparison(1, 2), func.is_equal("a", "b").as_comparison(2, 1), func.is_equal("a", "b", "c").as_comparison(1, 2), func.foobar("a", "b").as_comparison(1, 2), ), lambda: ( func.row_number().over(order_by=table_a.c.a), func.row_number().over(order_by=table_a.c.a, range_=(0, 10)), func.row_number().over(order_by=table_a.c.a, range_=(None, 10)), func.row_number().over(order_by=table_a.c.a, rows=(None, 20)), func.row_number().over(order_by=table_a.c.b), func.row_number().over( order_by=table_a.c.a, partition_by=table_a.c.b ), ), lambda: ( func.count(1).filter(table_a.c.a == 5), func.count(1).filter(table_a.c.a == 10), func.foob(1).filter(table_a.c.a == 10), ), lambda: ( and_(table_a.c.a == 5, table_a.c.b == table_b.c.a), and_(table_a.c.a == 5, table_a.c.a == table_b.c.a), or_(table_a.c.a == 5, table_a.c.b == table_b.c.a), ClauseList(table_a.c.a == 5, table_a.c.b == table_b.c.a), ClauseList(table_a.c.a == 5, table_a.c.b == table_a.c.a), ), lambda: ( case(whens=[(table_a.c.a == 5, 10), (table_a.c.a == 10, 20)]), case(whens=[(table_a.c.a == 18, 10), (table_a.c.a == 10, 20)]), case(whens=[(table_a.c.a == 5, 10), (table_a.c.b == 10, 20)]), case( whens=[ (table_a.c.a == 5, 10), (table_a.c.b == 10, 20), (table_a.c.a == 9, 12), ] ), case( whens=[(table_a.c.a == 5, 10), (table_a.c.a == 10, 20)], else_=30, ), case({"wendy": "W", "jack": "J"}, value=table_a.c.a, else_="E"), case({"wendy": "W", "jack": "J"}, value=table_a.c.b, else_="E"), case({"wendy_w": "W", "jack": "J"}, value=table_a.c.a, else_="E"), ), lambda: ( extract("foo", table_a.c.a), extract("foo", table_a.c.b), extract("bar", table_a.c.a), ), lambda: ( Slice(1, 2, 5), Slice(1, 5, 5), Slice(1, 5, 10), Slice(2, 10, 15), ), lambda: ( select([table_a.c.a]), select([table_a.c.a, table_a.c.b]), select([table_a.c.b, table_a.c.a]), select([table_a.c.a]).where(table_a.c.b == 5), select([table_a.c.a]) .where(table_a.c.b == 5) .where(table_a.c.a == 10), select([table_a.c.a]).where(table_a.c.b == 5).with_for_update(), select([table_a.c.a]) .where(table_a.c.b == 5) .with_for_update(nowait=True), select([table_a.c.a]).where(table_a.c.b == 5).correlate(table_b), select([table_a.c.a]) .where(table_a.c.b == 5) .correlate_except(table_b), ), lambda: ( select([table_a.c.a]).cte(), select([table_a.c.a]).cte(recursive=True), select([table_a.c.a]).cte(name="some_cte", recursive=True), select([table_a.c.a]).cte(name="some_cte"), select([table_a.c.a]).cte(name="some_cte").alias("other_cte"), select([table_a.c.a]) .cte(name="some_cte") .union_all(select([table_a.c.a])), select([table_a.c.a]) .cte(name="some_cte") .union_all(select([table_a.c.b])), select([table_a.c.a]).lateral(), select([table_a.c.a]).lateral(name="bar"), table_a.tablesample(func.bernoulli(1)), table_a.tablesample(func.bernoulli(1), seed=func.random()), table_a.tablesample(func.bernoulli(1), seed=func.other_random()), table_a.tablesample(func.hoho(1)), table_a.tablesample(func.bernoulli(1), name="bar"), table_a.tablesample( func.bernoulli(1), name="bar", seed=func.random() ), ), lambda: ( select([table_a.c.a]), select([table_a.c.a]).prefix_with("foo"), select([table_a.c.a]).prefix_with("foo", dialect="mysql"), select([table_a.c.a]).prefix_with("foo", dialect="postgresql"), select([table_a.c.a]).prefix_with("bar"), select([table_a.c.a]).suffix_with("bar"), ), lambda: ( select([table_a_2.c.a]), select([table_a_2_fs.c.a]), select([table_a_2_bs.c.a]), ), lambda: ( select([table_a.c.a]), select([table_a.c.a]).with_hint(None, "some hint"), select([table_a.c.a]).with_hint(None, "some other hint"), select([table_a.c.a]).with_hint(table_a, "some hint"), select([table_a.c.a]) .with_hint(table_a, "some hint") .with_hint(None, "some other hint"), select([table_a.c.a]).with_hint(table_a, "some other hint"), select([table_a.c.a]).with_hint( table_a, "some hint", dialect_name="mysql" ), select([table_a.c.a]).with_hint( table_a, "some hint", dialect_name="postgresql" ), ), lambda: ( table_a.join(table_b, table_a.c.a == table_b.c.a), table_a.join( table_b, and_(table_a.c.a == table_b.c.a, table_a.c.b == 1) ), table_a.outerjoin(table_b, table_a.c.a == table_b.c.a), ), lambda: ( table_a.alias("a"), table_a.alias("b"), table_a.alias(), table_b.alias("a"), select([table_a.c.a]).alias("a"), ), lambda: ( FromGrouping(table_a.alias("a")), FromGrouping(table_a.alias("b")), ), lambda: ( SelectStatementGrouping(select([table_a])), SelectStatementGrouping(select([table_b])), ), lambda: ( select([table_a.c.a]).scalar_subquery(), select([table_a.c.a]).where(table_a.c.b == 5).scalar_subquery(), ), lambda: ( exists().where(table_a.c.a == 5), exists().where(table_a.c.b == 5), ), lambda: ( union(select([table_a.c.a]), select([table_a.c.b])), union(select([table_a.c.a]), select([table_a.c.b])).order_by("a"), union_all(select([table_a.c.a]), select([table_a.c.b])), union(select([table_a.c.a])), union( select([table_a.c.a]), select([table_a.c.b]).where(table_a.c.b > 5), ), ), lambda: ( table("a", column("x"), column("y")), table("a", column("y"), column("x")), table("b", column("x"), column("y")), table("a", column("x"), column("y"), column("z")), table("a", column("x"), column("y", Integer)), table("a", column("q"), column("y", Integer)), ), lambda: (table_a, table_b), ] dont_compare_values_fixtures = [ lambda: ( # same number of params each time, so compare for IN # with legacy behavior of bind for each value works column("x").in_(random_choices(range(10), k=3)), # expanding IN places the whole list into a single parameter # so it can be of arbitrary length as well column("x").in_( bindparam( "q", random_choices(range(10), k=random.randint(0, 7)), expanding=True, ) ), column("x") == random.randint(1, 10), ) ] def _complex_fixtures(): def one(): a1 = table_a.alias() a2 = table_b_like_a.alias() stmt = ( select([table_a.c.a, a1.c.b, a2.c.b]) .where(table_a.c.b == a1.c.b) .where(a1.c.b == a2.c.b) .where(a1.c.a == 5) ) return stmt def one_diff(): a1 = table_b_like_a.alias() a2 = table_a.alias() stmt = ( select([table_a.c.a, a1.c.b, a2.c.b]) .where(table_a.c.b == a1.c.b) .where(a1.c.b == a2.c.b) .where(a1.c.a == 5) ) return stmt def two(): inner = one().subquery() stmt = select([table_b.c.a, inner.c.a, inner.c.b]).select_from( table_b.join(inner, table_b.c.b == inner.c.b) ) return stmt def three(): a1 = table_a.alias() a2 = table_a.alias() ex = exists().where(table_b.c.b == a1.c.a) stmt = ( select([a1.c.a, a2.c.a]) .select_from(a1.join(a2, a1.c.b == a2.c.b)) .where(ex) ) return stmt return [one(), one_diff(), two(), three()] fixtures.append(_complex_fixtures) class CacheKeyFixture(object): def _run_cache_key_fixture(self, fixture, compare_values): case_a = fixture() case_b = fixture() for a, b in itertools.combinations_with_replacement( range(len(case_a)), 2 ): if a == b: a_key = case_a[a]._generate_cache_key() b_key = case_b[b]._generate_cache_key() is_not_(a_key, None) is_not_(b_key, None) eq_(a_key.key, b_key.key) eq_(hash(a_key), hash(b_key)) for a_param, b_param in zip( a_key.bindparams, b_key.bindparams ): assert a_param.compare( b_param, compare_values=compare_values ) else: a_key = case_a[a]._generate_cache_key() b_key = case_b[b]._generate_cache_key() if a_key.key == b_key.key: for a_param, b_param in zip( a_key.bindparams, b_key.bindparams ): if not a_param.compare( b_param, compare_values=compare_values ): break else: # this fails unconditionally since we could not # find bound parameter values that differed. # Usually we intended to get two distinct keys here # so the failure will be more descriptive using the # ne_() assertion. ne_(a_key.key, b_key.key) else: ne_(a_key.key, b_key.key) # ClauseElement-specific test to ensure the cache key # collected all the bound parameters if isinstance(case_a[a], ClauseElement) and isinstance( case_b[b], ClauseElement ): assert_a_params = [] assert_b_params = [] visitors.traverse_depthfirst( case_a[a], {}, {"bindparam": assert_a_params.append} ) visitors.traverse_depthfirst( case_b[b], {}, {"bindparam": assert_b_params.append} ) # note we're asserting the order of the params as well as # if there are dupes or not. ordering has to be # deterministic and matches what a traversal would provide. # regular traverse_depthfirst does produce dupes in cases # like # select([some_alias]). # select_from(join(some_alias, other_table)) # where a bound parameter is inside of some_alias. the # cache key case is more minimalistic eq_( sorted(a_key.bindparams, key=lambda b: b.key), sorted( util.unique_list(assert_a_params), key=lambda b: b.key ), ) eq_( sorted(b_key.bindparams, key=lambda b: b.key), sorted( util.unique_list(assert_b_params), key=lambda b: b.key ), ) class CacheKeyTest(CacheKeyFixture, CoreFixtures, fixtures.TestBase): def test_cache_key(self): for fixtures_, compare_values in [ (self.fixtures, True), (self.dont_compare_values_fixtures, False), ]: for fixture in fixtures_: self._run_cache_key_fixture(fixture, compare_values) def test_cache_key_unknown_traverse(self): class Foobar1(ClauseElement): _traverse_internals = [ ("key", InternalTraversal.dp_anon_name), ("type_", InternalTraversal.dp_unknown_structure), ] def __init__(self, key, type_): self.key = key self.type_ = type_ f1 = Foobar1("foo", String()) eq_(f1._generate_cache_key(), None) def test_cache_key_no_method(self): class Foobar1(ClauseElement): pass class Foobar2(ColumnElement): pass # the None for cache key will prevent objects # which contain these elements from being cached. f1 = Foobar1() eq_(f1._generate_cache_key(), None) f2 = Foobar2() eq_(f2._generate_cache_key(), None) s1 = select([column("q"), Foobar2()]) eq_(s1._generate_cache_key(), None) def test_get_children_no_method(self): class Foobar1(ClauseElement): pass class Foobar2(ColumnElement): pass f1 = Foobar1() eq_(f1.get_children(), []) f2 = Foobar2() eq_(f2.get_children(), []) def test_copy_internals_no_method(self): class Foobar1(ClauseElement): pass class Foobar2(ColumnElement): pass f1 = Foobar1() f2 = Foobar2() f1._copy_internals() f2._copy_internals() class CompareAndCopyTest(CoreFixtures, fixtures.TestBase): @classmethod def setup_class(cls): # TODO: we need to get dialects here somehow, perhaps in test_suite? [ importlib.import_module("sqlalchemy.dialects.%s" % d) for d in dialects.__all__ if not d.startswith("_") ] def test_all_present(self): need = set( cls for cls in class_hierarchy(ClauseElement) if issubclass(cls, (ColumnElement, Selectable)) and ( "__init__" in cls.__dict__ or issubclass(cls, AliasedReturnsRows) ) and not issubclass(cls, (Annotated)) and "orm" not in cls.__module__ and "compiler" not in cls.__module__ and "crud" not in cls.__module__ and "dialects" not in cls.__module__ # TODO: dialects? ).difference({ColumnElement, UnaryExpression}) for fixture in self.fixtures + self.dont_compare_values_fixtures: case_a = fixture() for elem in case_a: for mro in type(elem).__mro__: need.discard(mro) is_false(bool(need), "%d Remaining classes: %r" % (len(need), need)) def test_compare_labels(self): for fixtures_, compare_values in [ (self.fixtures, True), (self.dont_compare_values_fixtures, False), ]: for fixture in fixtures_: case_a = fixture() case_b = fixture() for a, b in itertools.combinations_with_replacement( range(len(case_a)), 2 ): if a == b: is_true( case_a[a].compare( case_b[b], compare_annotations=True, compare_values=compare_values, ), "%r != %r" % (case_a[a], case_b[b]), ) else: is_false( case_a[a].compare( case_b[b], compare_annotations=True, compare_values=compare_values, ), "%r == %r" % (case_a[a], case_b[b]), ) def test_compare_col_identity(self): stmt1 = ( select([table_a.c.a, table_b.c.b]) .where(table_a.c.a == table_b.c.b) .alias() ) stmt1_c = ( select([table_a.c.a, table_b.c.b]) .where(table_a.c.a == table_b.c.b) .alias() ) stmt2 = union(select([table_a]), select([table_b])) equivalents = {table_a.c.a: [table_b.c.a]} is_false( stmt1.compare(stmt2, use_proxies=True, equivalents=equivalents) ) is_true( stmt1.compare(stmt1_c, use_proxies=True, equivalents=equivalents) ) is_true( (table_a.c.a == table_b.c.b).compare( stmt1.c.a == stmt1.c.b, use_proxies=True, equivalents=equivalents, ) ) def test_copy_internals(self): for fixtures_, compare_values in [ (self.fixtures, True), (self.dont_compare_values_fixtures, False), ]: for fixture in fixtures_: case_a = fixture() case_b = fixture() assert case_a[0].compare( case_b[0], compare_values=compare_values ) clone = visitors.replacement_traverse( case_a[0], {}, lambda elem: None ) assert clone.compare(case_b[0], compare_values=compare_values) stack = [clone] seen = {clone} found_elements = False while stack: obj = stack.pop(0) items = [ subelem for key, elem in clone.__dict__.items() if key != "_is_clone_of" and elem is not None for subelem in util.to_list(elem) if ( isinstance(subelem, (ColumnElement, ClauseList)) and subelem not in seen and not isinstance(subelem, Immutable) and subelem is not case_a[0] ) ] stack.extend(items) seen.update(items) if obj is not clone: found_elements = True # ensure the element will not compare as true obj.compare = lambda other, **kw: False obj.__visit_name__ = "dont_match" if found_elements: assert not clone.compare( case_b[0], compare_values=compare_values ) assert case_a[0].compare( case_b[0], compare_values=compare_values ) class CompareClausesTest(fixtures.TestBase): def test_compare_metadata_tables(self): # metadata Table objects cache on their own identity, not their # structure. This is mainly to reduce the size of cache keys # as well as reduce computational overhead, as Table objects have # very large internal state and they are also generally global # objects. t1 = Table("a", MetaData(), Column("q", Integer), Column("p", Integer)) t2 = Table("a", MetaData(), Column("q", Integer), Column("p", Integer)) ne_(t1._generate_cache_key(), t2._generate_cache_key()) eq_(t1._generate_cache_key().key, (t1,)) def test_compare_adhoc_tables(self): # non-metadata tables compare on their structure. these objects are # not commonly used. # note this test is a bit redundant as we have a similar test # via the fixtures also t1 = table("a", Column("q", Integer), Column("p", Integer)) t2 = table("a", Column("q", Integer), Column("p", Integer)) t3 = table("b", Column("q", Integer), Column("p", Integer)) t4 = table("a", Column("q", Integer), Column("x", Integer)) eq_(t1._generate_cache_key(), t2._generate_cache_key()) ne_(t1._generate_cache_key(), t3._generate_cache_key()) ne_(t1._generate_cache_key(), t4._generate_cache_key()) ne_(t3._generate_cache_key(), t4._generate_cache_key()) def test_compare_comparison_associative(self): l1 = table_c.c.x == table_d.c.y l2 = table_d.c.y == table_c.c.x l3 = table_c.c.x == table_d.c.z is_true(l1.compare(l1)) is_true(l1.compare(l2)) is_false(l1.compare(l3)) def test_compare_comparison_non_commutative_inverses(self): l1 = table_c.c.x >= table_d.c.y l2 = table_d.c.y < table_c.c.x l3 = table_d.c.y <= table_c.c.x # we're not doing this kind of commutativity right now. is_false(l1.compare(l2)) is_false(l1.compare(l3)) def test_compare_clauselist_associative(self): l1 = and_(table_c.c.x == table_d.c.y, table_c.c.y == table_d.c.z) l2 = and_(table_c.c.y == table_d.c.z, table_c.c.x == table_d.c.y) l3 = and_(table_c.c.x == table_d.c.z, table_c.c.y == table_d.c.y) is_true(l1.compare(l1)) is_true(l1.compare(l2)) is_false(l1.compare(l3)) def test_compare_clauselist_not_associative(self): l1 = ClauseList( table_c.c.x, table_c.c.y, table_d.c.y, operator=operators.sub ) l2 = ClauseList( table_d.c.y, table_c.c.x, table_c.c.y, operator=operators.sub ) is_true(l1.compare(l1)) is_false(l1.compare(l2)) def test_compare_clauselist_assoc_different_operator(self): l1 = and_(table_c.c.x == table_d.c.y, table_c.c.y == table_d.c.z) l2 = or_(table_c.c.y == table_d.c.z, table_c.c.x == table_d.c.y) is_false(l1.compare(l2)) def test_compare_clauselist_not_assoc_different_operator(self): l1 = ClauseList( table_c.c.x, table_c.c.y, table_d.c.y, operator=operators.sub ) l2 = ClauseList( table_c.c.x, table_c.c.y, table_d.c.y, operator=operators.div ) is_false(l1.compare(l2)) def test_compare_labels(self): is_true(column("q").label(None).compare(column("q").label(None))) is_false(column("q").label("foo").compare(column("q").label(None))) is_false(column("q").label(None).compare(column("q").label("foo"))) is_false(column("q").label("foo").compare(column("q").label("bar"))) is_true(column("q").label("foo").compare(column("q").label("foo"))) def test_compare_binds(self): b1 = bindparam("foo", type_=Integer()) b2 = bindparam("foo", type_=Integer()) b3 = bindparam("foo", type_=String()) def c1(): return 5 def c2(): return 6 b4 = bindparam("foo", type_=Integer(), callable_=c1) b5 = bindparam("foo", type_=Integer(), callable_=c2) b6 = bindparam("foo", type_=Integer(), callable_=c1) b7 = bindparam("foo", type_=Integer, value=5) b8 = bindparam("foo", type_=Integer, value=6) is_false(b1.compare(b4)) is_true(b4.compare(b6)) is_false(b4.compare(b5)) is_true(b1.compare(b2)) # currently not comparing "key", as we often have to compare # anonymous names. however we should really check for that # is_true(b1.compare(b3)) is_false(b1.compare(b3)) is_false(b1.compare(b7)) is_false(b7.compare(b8)) is_true(b7.compare(b7)) def test_compare_tables(self): is_true(table_a.compare(table_a_2)) # the "proxy" version compares schema tables on metadata identity is_false(table_a.compare(table_a_2, use_proxies=True)) # same for lower case tables since it compares lower case columns # using proxies, which makes it very unlikely to have multiple # table() objects with columns that compare equally is_false( table("a", column("x", Integer), column("q", String)).compare( table("a", column("x", Integer), column("q", String)), use_proxies=True, ) ) def test_compare_annotated_clears_mapping(self): t = table("t", column("x"), column("y")) x_a = t.c.x._annotate({"foo": True}) x_b = t.c.x._annotate({"foo": True}) is_true(x_a.compare(x_b, compare_annotations=True)) is_false( x_a.compare(x_b._annotate({"bar": True}), compare_annotations=True) ) s1 = select([t.c.x])._annotate({"foo": True}) s2 = select([t.c.x])._annotate({"foo": True}) is_true(s1.compare(s2, compare_annotations=True)) is_false( s1.compare(s2._annotate({"bar": True}), compare_annotations=True) ) def test_compare_annotated_wo_annotations(self): t = table("t", column("x"), column("y")) x_a = t.c.x._annotate({}) x_b = t.c.x._annotate({"foo": True}) is_true(t.c.x.compare(x_a)) is_true(x_b.compare(x_a)) is_true(x_a.compare(t.c.x)) is_false(x_a.compare(t.c.y)) is_false(t.c.y.compare(x_a)) is_true((t.c.x == 5).compare(x_a == 5)) is_false((t.c.y == 5).compare(x_a == 5)) s = select([t]).subquery() x_p = s.c.x is_false(x_a.compare(x_p)) is_false(t.c.x.compare(x_p)) x_p_a = x_p._annotate({}) is_true(x_p_a.compare(x_p)) is_true(x_p.compare(x_p_a)) is_false(x_p_a.compare(x_a))
en
0.919876
# lambdas which return a tuple of ColumnElement objects. # must return at least two objects that should compare differently. # to test more varieties of "difference" additional objects can be added. # note these two are mathematically equivalent but for now they # are considered to be different # same number of params each time, so compare for IN # with legacy behavior of bind for each value works # expanding IN places the whole list into a single parameter # so it can be of arbitrary length as well # this fails unconditionally since we could not # find bound parameter values that differed. # Usually we intended to get two distinct keys here # so the failure will be more descriptive using the # ne_() assertion. # ClauseElement-specific test to ensure the cache key # collected all the bound parameters # note we're asserting the order of the params as well as # if there are dupes or not. ordering has to be # deterministic and matches what a traversal would provide. # regular traverse_depthfirst does produce dupes in cases # like # select([some_alias]). # select_from(join(some_alias, other_table)) # where a bound parameter is inside of some_alias. the # cache key case is more minimalistic # the None for cache key will prevent objects # which contain these elements from being cached. # TODO: we need to get dialects here somehow, perhaps in test_suite? # TODO: dialects? # ensure the element will not compare as true # metadata Table objects cache on their own identity, not their # structure. This is mainly to reduce the size of cache keys # as well as reduce computational overhead, as Table objects have # very large internal state and they are also generally global # objects. # non-metadata tables compare on their structure. these objects are # not commonly used. # note this test is a bit redundant as we have a similar test # via the fixtures also # we're not doing this kind of commutativity right now. # currently not comparing "key", as we often have to compare # anonymous names. however we should really check for that # is_true(b1.compare(b3)) # the "proxy" version compares schema tables on metadata identity # same for lower case tables since it compares lower case columns # using proxies, which makes it very unlikely to have multiple # table() objects with columns that compare equally
1.936092
2
api/response.py
tomenjerry/mangaadv
0
6628336
<filename>api/response.py """Convenience classes and functions for API responses.""" from functools import wraps from typing import TYPE_CHECKING, Tuple from django.http import JsonResponse from django.utils.log import log_response from django.views.decorators.vary import vary_on_headers if TYPE_CHECKING: # pragma: no cover from typing import Callable from django.http import HttpRequest class JsonError(JsonResponse): """ A JSON-formatted error response. :param message: The error message of the response. :param status: The HTTP status of the response. """ def __init__(self, message: str, status: int = 500, **kwargs): data = {'error': message, 'status': status} kwargs.setdefault('status', status) super(JsonError, self).__init__(data, **kwargs) def require_methods_api(allowed_methods: Tuple[str, ...] = ('GET', 'HEAD')) -> 'Callable': """ | Decorator to make an API view only accept particular request methods. | Based on :func:`django.views.decorators.http.require_http_request`. :param allowed_methods: The allowed request methods. """ def decorator(func: 'Callable') -> 'Callable': @wraps(func) def inner(request: 'HttpRequest', *args, **kwargs) -> JsonError: if request.method not in allowed_methods: response = JsonError('Method not allowed', 405) response['Allow'] = ', '.join(allowed_methods) log_response( 'Method Not Allowed (%s): %s', request.method, request.path, response=response, request=request, ) return response return func(request, *args, **kwargs) return vary_on_headers('Allow')(inner) return decorator __all__ = ['require_methods_api', 'JsonError']
<filename>api/response.py """Convenience classes and functions for API responses.""" from functools import wraps from typing import TYPE_CHECKING, Tuple from django.http import JsonResponse from django.utils.log import log_response from django.views.decorators.vary import vary_on_headers if TYPE_CHECKING: # pragma: no cover from typing import Callable from django.http import HttpRequest class JsonError(JsonResponse): """ A JSON-formatted error response. :param message: The error message of the response. :param status: The HTTP status of the response. """ def __init__(self, message: str, status: int = 500, **kwargs): data = {'error': message, 'status': status} kwargs.setdefault('status', status) super(JsonError, self).__init__(data, **kwargs) def require_methods_api(allowed_methods: Tuple[str, ...] = ('GET', 'HEAD')) -> 'Callable': """ | Decorator to make an API view only accept particular request methods. | Based on :func:`django.views.decorators.http.require_http_request`. :param allowed_methods: The allowed request methods. """ def decorator(func: 'Callable') -> 'Callable': @wraps(func) def inner(request: 'HttpRequest', *args, **kwargs) -> JsonError: if request.method not in allowed_methods: response = JsonError('Method not allowed', 405) response['Allow'] = ', '.join(allowed_methods) log_response( 'Method Not Allowed (%s): %s', request.method, request.path, response=response, request=request, ) return response return func(request, *args, **kwargs) return vary_on_headers('Allow')(inner) return decorator __all__ = ['require_methods_api', 'JsonError']
en
0.589395
Convenience classes and functions for API responses. # pragma: no cover A JSON-formatted error response. :param message: The error message of the response. :param status: The HTTP status of the response. | Decorator to make an API view only accept particular request methods. | Based on :func:`django.views.decorators.http.require_http_request`. :param allowed_methods: The allowed request methods.
2.798621
3
bbclib/libs/bbclib_binary.py
ks91/py-bbclib
0
6628337
<gh_stars>0 # -*- coding: utf-8 -*- """ Copyright (c) 2019 beyond-blockchain.org. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import sys import binascii import hashlib import random import time from collections import Mapping current_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(current_dir, "../..")) from bbclib.libs.bbclib_config import DEFAULT_ID_LEN from bbclib.libs.bbclib_transaction import BBcTransaction from bbclib.libs.bbclib_signature import BBcSignature from bbclib.libs.bbclib_asset_raw import BBcAssetRaw from bbclib.libs.bbclib_asset_hash import BBcAssetHash from bbclib.libs.bbclib_asset import BBcAsset from bbclib.libs.bbclib_relation import BBcRelation from bbclib.libs.bbclib_reference import BBcReference from bbclib.libs.bbclib_event import BBcEvent from bbclib.libs.bbclib_pointer import BBcPointer from bbclib.libs.bbclib_witness import BBcWitness from bbclib.libs.bbclib_crossref import BBcCrossRef def str_binary(dat): if dat is None: return "None" else: return binascii.b2a_hex(dat) def to_bigint(val, size=32): dat = bytearray(to_2byte(size)) dat.extend(val) return dat def to_8byte(val): return val.to_bytes(8, 'little') def to_4byte(val): return val.to_bytes(4, 'little') def to_2byte(val): return val.to_bytes(2, 'little') def to_1byte(val): return val.to_bytes(1, 'little') def get_n_bytes(ptr, n, dat): return ptr+n, dat[ptr:ptr+n] def get_n_byte_int(ptr, n, dat): return ptr+n, int.from_bytes(dat[ptr:ptr+n], 'little') def get_bigint(ptr, dat): size = int.from_bytes(dat[ptr:ptr+2], 'little') return ptr+2+size, dat[ptr+2:ptr+2+size] def bin2str_base64(dat): import binascii return binascii.b2a_base64(dat, newline=False).decode("utf-8") def bin2str_base64(dat): import binascii return binascii.b2a_base64(dat, newline=False).decode("utf-8") def get_random_value(length=DEFAULT_ID_LEN): """Return random bytes Args: length (int): length of the result Returns: bytes: random bytes """ val = bytearray() for i in range(length): val.append(random.randint(0,255)) return bytes(val)
# -*- coding: utf-8 -*- """ Copyright (c) 2019 beyond-blockchain.org. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import sys import binascii import hashlib import random import time from collections import Mapping current_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(current_dir, "../..")) from bbclib.libs.bbclib_config import DEFAULT_ID_LEN from bbclib.libs.bbclib_transaction import BBcTransaction from bbclib.libs.bbclib_signature import BBcSignature from bbclib.libs.bbclib_asset_raw import BBcAssetRaw from bbclib.libs.bbclib_asset_hash import BBcAssetHash from bbclib.libs.bbclib_asset import BBcAsset from bbclib.libs.bbclib_relation import BBcRelation from bbclib.libs.bbclib_reference import BBcReference from bbclib.libs.bbclib_event import BBcEvent from bbclib.libs.bbclib_pointer import BBcPointer from bbclib.libs.bbclib_witness import BBcWitness from bbclib.libs.bbclib_crossref import BBcCrossRef def str_binary(dat): if dat is None: return "None" else: return binascii.b2a_hex(dat) def to_bigint(val, size=32): dat = bytearray(to_2byte(size)) dat.extend(val) return dat def to_8byte(val): return val.to_bytes(8, 'little') def to_4byte(val): return val.to_bytes(4, 'little') def to_2byte(val): return val.to_bytes(2, 'little') def to_1byte(val): return val.to_bytes(1, 'little') def get_n_bytes(ptr, n, dat): return ptr+n, dat[ptr:ptr+n] def get_n_byte_int(ptr, n, dat): return ptr+n, int.from_bytes(dat[ptr:ptr+n], 'little') def get_bigint(ptr, dat): size = int.from_bytes(dat[ptr:ptr+2], 'little') return ptr+2+size, dat[ptr+2:ptr+2+size] def bin2str_base64(dat): import binascii return binascii.b2a_base64(dat, newline=False).decode("utf-8") def bin2str_base64(dat): import binascii return binascii.b2a_base64(dat, newline=False).decode("utf-8") def get_random_value(length=DEFAULT_ID_LEN): """Return random bytes Args: length (int): length of the result Returns: bytes: random bytes """ val = bytearray() for i in range(length): val.append(random.randint(0,255)) return bytes(val)
en
0.815658
# -*- coding: utf-8 -*- Copyright (c) 2019 beyond-blockchain.org. 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. Return random bytes Args: length (int): length of the result Returns: bytes: random bytes
2.000247
2
avmess/django_settings.py
Raduionutz/Monster-Clearer-GOTY
2
6628338
from avmess.settings import CONF DEBUG = CONF.debug TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': CONF.db_name, 'USER': CONF.db_user, 'PASSWORD': CONF.db_pass, 'HOST': CONF.db_host, 'PORT': CONF.db_port, } } INSTALLED_APPS = ('avmess',) TIME_ZONE = 'UTC' USE_TZ = False SECRET_KEY = '<KEY>'
from avmess.settings import CONF DEBUG = CONF.debug TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': CONF.db_name, 'USER': CONF.db_user, 'PASSWORD': CONF.db_pass, 'HOST': CONF.db_host, 'PORT': CONF.db_port, } } INSTALLED_APPS = ('avmess',) TIME_ZONE = 'UTC' USE_TZ = False SECRET_KEY = '<KEY>'
none
1
1.330069
1
gesund_projekt/steps/models.py
asis2016/gesund-projekt
0
6628339
from django.conf import settings from django.urls import reverse from django.db import models class Steps(models.Model): """ Steps model. """ id = models.AutoField(primary_key=True, editable=False) datestamp = models.DateField(blank=True) step_count = models.IntegerField(blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return f'{self.datestamp} - {self.step_count}' def get_absolute_url(self): return reverse('steps-index')
from django.conf import settings from django.urls import reverse from django.db import models class Steps(models.Model): """ Steps model. """ id = models.AutoField(primary_key=True, editable=False) datestamp = models.DateField(blank=True) step_count = models.IntegerField(blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return f'{self.datestamp} - {self.step_count}' def get_absolute_url(self): return reverse('steps-index')
en
0.598184
Steps model.
2.197448
2
base/templatetags/base.py
Rizalgente/upkoding
0
6628340
from django.utils.safestring import mark_safe from django import template from django.shortcuts import reverse from django.conf import settings from account.models import User from projects.models import Project register = template.Library() @register.simple_tag(takes_context=True) def active_class(context, namespace_or_path, classname="active"): """ Detect whether we're in a page described by `namespace_or_path` and return `classname` if we are. Param `namespace_or_path` could be: - A path eg. `/about/`, it will return `classname` if request.path == `/about/` - A path with wildcard eg. `/about/*`, it will return `classname` if request.path starts with `/about/` - A URL namespace eg. `account:login`, it will return `classname` if request.path == reverse('account:login') Usage: {% active_class 'account:login' %} {% active_class '/account/login/' %} {% active_class '/account/*' %} """ path = context.request.path if '/' in namespace_or_path: if '*' in namespace_or_path: return classname if path.startswith(namespace_or_path.replace('*', '')) else '' return classname if path == namespace_or_path else '' # it must be a namespace because `namespace_or_path` doesn't contains `/` return classname if path == reverse(namespace_or_path) else '' @register.filter def fullurl(url): """ Constuct URL with domain """ if url.startswith('/'): return '{}{}'.format(settings.SITE_DOMAIN, url) return '{}/{}'.format(settings.SITE_DOMAIN, url) @register.filter def avatar_url(user, size=100): """ return only the URL of the gravatar Usage: {{ user|gravatar_url:150 }} """ return user.avatar_url(size) @register.filter def avatar_img(user, size=100): """ return an image tag with the gravatar Usage: {{ user|gravatar:150 }} """ url = avatar_url(user, size) return mark_safe('<img src="%s" height="%d" width="%d" class="rounded-circle" alt="%s\'s avatar">' % (url, size, size, user.first_name)) @register.filter def input_class(obj, arg): """ Inserts css classes to input field. """ current_classes = obj.field.widget.attrs.get('class', '') if current_classes: current_classes = current_classes.split() else: current_classes = [] new_classes = arg.split() final_classes = set(current_classes + new_classes) return obj.as_widget(attrs={'class': ' '.join(final_classes)}) @register.inclusion_tag('base/templatetags/meta.html', takes_context=True) def meta(context, **kwargs): meta_url = context.request.path meta_title = kwargs.get('title', settings.DEFAULT_METADATA.get('title')) meta_image = kwargs.get('image', settings.DEFAULT_METADATA.get('image')) meta_desc = kwargs.get( 'desc', settings.DEFAULT_METADATA.get('description')) if 'object' in kwargs: obj = kwargs.get('object') if isinstance(obj, User): meta_url = obj.get_absolute_url() meta_title = 'Profil dari {} (@{})'.format( obj.get_display_name(), obj.username) meta_image = obj.avatar_url(640) meta_desc = obj.description if isinstance(obj, Project): meta_title = obj.title if ( not 'title' in kwargs) else kwargs.get('title') meta_image = obj.cover.url if obj.cover else '' meta_desc = obj.description return { 'title': meta_title, 'image': meta_image, 'url': meta_url, 'desc': meta_desc, }
from django.utils.safestring import mark_safe from django import template from django.shortcuts import reverse from django.conf import settings from account.models import User from projects.models import Project register = template.Library() @register.simple_tag(takes_context=True) def active_class(context, namespace_or_path, classname="active"): """ Detect whether we're in a page described by `namespace_or_path` and return `classname` if we are. Param `namespace_or_path` could be: - A path eg. `/about/`, it will return `classname` if request.path == `/about/` - A path with wildcard eg. `/about/*`, it will return `classname` if request.path starts with `/about/` - A URL namespace eg. `account:login`, it will return `classname` if request.path == reverse('account:login') Usage: {% active_class 'account:login' %} {% active_class '/account/login/' %} {% active_class '/account/*' %} """ path = context.request.path if '/' in namespace_or_path: if '*' in namespace_or_path: return classname if path.startswith(namespace_or_path.replace('*', '')) else '' return classname if path == namespace_or_path else '' # it must be a namespace because `namespace_or_path` doesn't contains `/` return classname if path == reverse(namespace_or_path) else '' @register.filter def fullurl(url): """ Constuct URL with domain """ if url.startswith('/'): return '{}{}'.format(settings.SITE_DOMAIN, url) return '{}/{}'.format(settings.SITE_DOMAIN, url) @register.filter def avatar_url(user, size=100): """ return only the URL of the gravatar Usage: {{ user|gravatar_url:150 }} """ return user.avatar_url(size) @register.filter def avatar_img(user, size=100): """ return an image tag with the gravatar Usage: {{ user|gravatar:150 }} """ url = avatar_url(user, size) return mark_safe('<img src="%s" height="%d" width="%d" class="rounded-circle" alt="%s\'s avatar">' % (url, size, size, user.first_name)) @register.filter def input_class(obj, arg): """ Inserts css classes to input field. """ current_classes = obj.field.widget.attrs.get('class', '') if current_classes: current_classes = current_classes.split() else: current_classes = [] new_classes = arg.split() final_classes = set(current_classes + new_classes) return obj.as_widget(attrs={'class': ' '.join(final_classes)}) @register.inclusion_tag('base/templatetags/meta.html', takes_context=True) def meta(context, **kwargs): meta_url = context.request.path meta_title = kwargs.get('title', settings.DEFAULT_METADATA.get('title')) meta_image = kwargs.get('image', settings.DEFAULT_METADATA.get('image')) meta_desc = kwargs.get( 'desc', settings.DEFAULT_METADATA.get('description')) if 'object' in kwargs: obj = kwargs.get('object') if isinstance(obj, User): meta_url = obj.get_absolute_url() meta_title = 'Profil dari {} (@{})'.format( obj.get_display_name(), obj.username) meta_image = obj.avatar_url(640) meta_desc = obj.description if isinstance(obj, Project): meta_title = obj.title if ( not 'title' in kwargs) else kwargs.get('title') meta_image = obj.cover.url if obj.cover else '' meta_desc = obj.description return { 'title': meta_title, 'image': meta_image, 'url': meta_url, 'desc': meta_desc, }
en
0.295526
Detect whether we're in a page described by `namespace_or_path` and return `classname` if we are. Param `namespace_or_path` could be: - A path eg. `/about/`, it will return `classname` if request.path == `/about/` - A path with wildcard eg. `/about/*`, it will return `classname` if request.path starts with `/about/` - A URL namespace eg. `account:login`, it will return `classname` if request.path == reverse('account:login') Usage: {% active_class 'account:login' %} {% active_class '/account/login/' %} {% active_class '/account/*' %} # it must be a namespace because `namespace_or_path` doesn't contains `/` Constuct URL with domain return only the URL of the gravatar Usage: {{ user|gravatar_url:150 }} return an image tag with the gravatar Usage: {{ user|gravatar:150 }} Inserts css classes to input field.
2.345397
2
ucscsdk/mometa/org/OrgDomainFirmwareInfo.py
CiscoUcs/ucscsdk
9
6628341
<reponame>CiscoUcs/ucscsdk """This module contains the general information for OrgDomainFirmwareInfo ManagedObject.""" from ...ucscmo import ManagedObject from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta from ...ucscmeta import VersionMeta class OrgDomainFirmwareInfoConsts(): CONNECTION_STATE_CONNECTED = "connected" CONNECTION_STATE_LOST_CONNECTIVITY = "lost-connectivity" FIRMWARE_OPER_STATE_FAILED = "failed" FIRMWARE_OPER_STATE_IN_PROGRESS = "in-progress" FIRMWARE_OPER_STATE_PENDING_USER_ACK = "pending-user-ack" FIRMWARE_OPER_STATE_READY = "ready" FIRMWARE_OPER_STATE_SCHEDULED = "scheduled" FIRMWARE_OPER_STATE_START_PENDING_EXT_PERMISSION = "start-pending-ext-permission" OPER_STATE_LOST_VISIBILITY = "lost-visibility" OPER_STATE_REGISTERED = "registered" OPER_STATE_REGISTERING = "registering" OPER_STATE_SYNCHRONIZING = "synchronizing" OPER_STATE_UNREGISTERED = "unregistered" OPER_STATE_VERSION_MISMATCH = "version-mismatch" PRODUCT_FAMILY_UCS_CLASSIC = "ucs-classic" PRODUCT_FAMILY_UCS_CLASSIC_3GEN = "ucs-classic-3gen" PRODUCT_FAMILY_UCS_CLASSIC_4GEN = "ucs-classic-4gen" PRODUCT_FAMILY_UCS_MINI = "ucs-mini" SUSPEND_STATE_OFF = "off" SUSPEND_STATE_ON = "on" class OrgDomainFirmwareInfo(ManagedObject): """This is OrgDomainFirmwareInfo class.""" consts = OrgDomainFirmwareInfoConsts() naming_props = set([u'id']) mo_meta = MoMeta("OrgDomainFirmwareInfo", "orgDomainFirmwareInfo", "domain-fw-info-[id]", VersionMeta.Version151a, "InputOutput", 0x1f, [], ["read-only"], [u'orgMaintTagFirmwareReport'], [], ["Get"]) prop_meta = { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version151a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "connection_state": MoPropertyMeta("connection_state", "connectionState", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["connected", "lost-connectivity"], []), "context": MoPropertyMeta("context", "context", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, 0, 256, None, [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, 0x2, 0, 256, None, [], []), "firmware_oper_state": MoPropertyMeta("firmware_oper_state", "firmwareOperState", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["failed", "in-progress", "pending-user-ack", "ready", "scheduled", "start-pending-ext-permission"], []), "firmware_version": MoPropertyMeta("firmware_version", "firmwareVersion", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), "fw_service_pack_version": MoPropertyMeta("fw_service_pack_version", "fwServicePackVersion", "string", VersionMeta.Version201b, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), "id": MoPropertyMeta("id", "id", "uint", VersionMeta.Version151a, MoPropertyMeta.NAMING, 0x4, None, None, None, [], []), "ip": MoPropertyMeta("ip", "ip", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, 0, 256, r"""((([0-9]){1,3}\.){3}[0-9]{1,3})""", [], []), "name": MoPropertyMeta("name", "name", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), "oper_state": MoPropertyMeta("oper_state", "operState", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["lost-visibility", "registered", "registering", "synchronizing", "unregistered", "version-mismatch"], []), "product_family": MoPropertyMeta("product_family", "productFamily", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["ucs-classic", "ucs-classic-3gen", "ucs-classic-4gen", "ucs-mini"], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version151a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), "suspend_state": MoPropertyMeta("suspend_state", "suspendState", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["off", "on"], []), "ucsm_running_version": MoPropertyMeta("ucsm_running_version", "ucsmRunningVersion", "string", VersionMeta.Version201b, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), } prop_map = { "childAction": "child_action", "connectionState": "connection_state", "context": "context", "dn": "dn", "firmwareOperState": "firmware_oper_state", "firmwareVersion": "firmware_version", "fwServicePackVersion": "fw_service_pack_version", "id": "id", "ip": "ip", "name": "name", "operState": "oper_state", "productFamily": "product_family", "rn": "rn", "status": "status", "suspendState": "suspend_state", "ucsmRunningVersion": "ucsm_running_version", } def __init__(self, parent_mo_or_dn, id, **kwargs): self._dirty_mask = 0 self.id = id self.child_action = None self.connection_state = None self.context = None self.firmware_oper_state = None self.firmware_version = None self.fw_service_pack_version = None self.ip = None self.name = None self.oper_state = None self.product_family = None self.status = None self.suspend_state = None self.ucsm_running_version = None ManagedObject.__init__(self, "OrgDomainFirmwareInfo", parent_mo_or_dn, **kwargs)
"""This module contains the general information for OrgDomainFirmwareInfo ManagedObject.""" from ...ucscmo import ManagedObject from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta from ...ucscmeta import VersionMeta class OrgDomainFirmwareInfoConsts(): CONNECTION_STATE_CONNECTED = "connected" CONNECTION_STATE_LOST_CONNECTIVITY = "lost-connectivity" FIRMWARE_OPER_STATE_FAILED = "failed" FIRMWARE_OPER_STATE_IN_PROGRESS = "in-progress" FIRMWARE_OPER_STATE_PENDING_USER_ACK = "pending-user-ack" FIRMWARE_OPER_STATE_READY = "ready" FIRMWARE_OPER_STATE_SCHEDULED = "scheduled" FIRMWARE_OPER_STATE_START_PENDING_EXT_PERMISSION = "start-pending-ext-permission" OPER_STATE_LOST_VISIBILITY = "lost-visibility" OPER_STATE_REGISTERED = "registered" OPER_STATE_REGISTERING = "registering" OPER_STATE_SYNCHRONIZING = "synchronizing" OPER_STATE_UNREGISTERED = "unregistered" OPER_STATE_VERSION_MISMATCH = "version-mismatch" PRODUCT_FAMILY_UCS_CLASSIC = "ucs-classic" PRODUCT_FAMILY_UCS_CLASSIC_3GEN = "ucs-classic-3gen" PRODUCT_FAMILY_UCS_CLASSIC_4GEN = "ucs-classic-4gen" PRODUCT_FAMILY_UCS_MINI = "ucs-mini" SUSPEND_STATE_OFF = "off" SUSPEND_STATE_ON = "on" class OrgDomainFirmwareInfo(ManagedObject): """This is OrgDomainFirmwareInfo class.""" consts = OrgDomainFirmwareInfoConsts() naming_props = set([u'id']) mo_meta = MoMeta("OrgDomainFirmwareInfo", "orgDomainFirmwareInfo", "domain-fw-info-[id]", VersionMeta.Version151a, "InputOutput", 0x1f, [], ["read-only"], [u'orgMaintTagFirmwareReport'], [], ["Get"]) prop_meta = { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version151a, MoPropertyMeta.INTERNAL, None, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "connection_state": MoPropertyMeta("connection_state", "connectionState", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["connected", "lost-connectivity"], []), "context": MoPropertyMeta("context", "context", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, 0, 256, None, [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, 0x2, 0, 256, None, [], []), "firmware_oper_state": MoPropertyMeta("firmware_oper_state", "firmwareOperState", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["failed", "in-progress", "pending-user-ack", "ready", "scheduled", "start-pending-ext-permission"], []), "firmware_version": MoPropertyMeta("firmware_version", "firmwareVersion", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), "fw_service_pack_version": MoPropertyMeta("fw_service_pack_version", "fwServicePackVersion", "string", VersionMeta.Version201b, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), "id": MoPropertyMeta("id", "id", "uint", VersionMeta.Version151a, MoPropertyMeta.NAMING, 0x4, None, None, None, [], []), "ip": MoPropertyMeta("ip", "ip", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, 0, 256, r"""((([0-9]){1,3}\.){3}[0-9]{1,3})""", [], []), "name": MoPropertyMeta("name", "name", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), "oper_state": MoPropertyMeta("oper_state", "operState", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["lost-visibility", "registered", "registering", "synchronizing", "unregistered", "version-mismatch"], []), "product_family": MoPropertyMeta("product_family", "productFamily", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["ucs-classic", "ucs-classic-3gen", "ucs-classic-4gen", "ucs-mini"], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version151a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), "suspend_state": MoPropertyMeta("suspend_state", "suspendState", "string", VersionMeta.Version151a, MoPropertyMeta.READ_ONLY, None, None, None, None, ["off", "on"], []), "ucsm_running_version": MoPropertyMeta("ucsm_running_version", "ucsmRunningVersion", "string", VersionMeta.Version201b, MoPropertyMeta.READ_ONLY, None, 0, 510, None, [], []), } prop_map = { "childAction": "child_action", "connectionState": "connection_state", "context": "context", "dn": "dn", "firmwareOperState": "firmware_oper_state", "firmwareVersion": "firmware_version", "fwServicePackVersion": "fw_service_pack_version", "id": "id", "ip": "ip", "name": "name", "operState": "oper_state", "productFamily": "product_family", "rn": "rn", "status": "status", "suspendState": "suspend_state", "ucsmRunningVersion": "ucsm_running_version", } def __init__(self, parent_mo_or_dn, id, **kwargs): self._dirty_mask = 0 self.id = id self.child_action = None self.connection_state = None self.context = None self.firmware_oper_state = None self.firmware_version = None self.fw_service_pack_version = None self.ip = None self.name = None self.oper_state = None self.product_family = None self.status = None self.suspend_state = None self.ucsm_running_version = None ManagedObject.__init__(self, "OrgDomainFirmwareInfo", parent_mo_or_dn, **kwargs)
en
0.543029
This module contains the general information for OrgDomainFirmwareInfo ManagedObject. This is OrgDomainFirmwareInfo class. ((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1} ((([0-9]){1,3}\.){3}[0-9]{1,3}) ((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}
1.918847
2
tests/test_ext_graphviz.py
bz2/sphinx
1
6628342
""" test_ext_graphviz ~~~~~~~~~~~~~~~~~ Test sphinx.ext.graphviz extension. :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re import pytest from sphinx.ext.graphviz import ClickableMapDefinition @pytest.mark.sphinx('html', testroot='ext-graphviz') @pytest.mark.usefixtures('if_graphviz_found') def test_graphviz_png_html(app, status, warning): app.builder.build_all() content = (app.outdir / 'index.html').text() html = (r'<div class="figure align-center" .*?>\s*' r'<div class="graphviz"><img .*?/></div>\s*<p class="caption">' r'<span class="caption-text">caption of graph</span>.*</p>\s*</div>') assert re.search(html, content, re.S) html = 'Hello <div class="graphviz"><img .*?/></div>\n graphviz world' assert re.search(html, content, re.S) html = '<img src=".*?" alt="digraph {\n bar -&gt; baz\n}" class="graphviz" />' assert re.search(html, content, re.M) html = (r'<div class="figure align-right" .*?>\s*' r'<div class="graphviz"><img .*?/></div>\s*<p class="caption">' r'<span class="caption-text">on <em>right</em></span>.*</p>\s*</div>') assert re.search(html, content, re.S) html = (r'<div align=\"center\" class=\"align-center\">' r'<div class="graphviz"><img src=\".*\.png\" alt=\"digraph foo {\n' r'centered\n' r'}\" class="graphviz" /></div>\n</div>') assert re.search(html, content, re.S) @pytest.mark.sphinx('html', testroot='ext-graphviz', confoverrides={'graphviz_output_format': 'svg'}) @pytest.mark.usefixtures('if_graphviz_found') def test_graphviz_svg_html(app, status, warning): app.builder.build_all() content = (app.outdir / 'index.html').text() html = (r'<div class=\"figure align-center\" .*?>\n' r'<div class="graphviz"><object data=\".*\.svg\".*>\n' r'\s*<p class=\"warning\">digraph foo {\n' r'bar -&gt; baz\n' r'}</p></object></div>\n' r'<p class=\"caption\"><span class=\"caption-text\">' r'caption of graph</span>.*</p>\n</div>') assert re.search(html, content, re.S) html = (r'Hello <div class="graphviz"><object.*>\n' r'\s*<p class=\"warning\">graph</p></object></div>\n' r' graphviz world') assert re.search(html, content, re.S) html = (r'<div class=\"figure align-right\" .*\>\n' r'<div class="graphviz"><object data=\".*\.svg\".*>\n' r'\s*<p class=\"warning\">digraph bar {\n' r'foo -&gt; bar\n' r'}</p></object></div>\n' r'<p class=\"caption\"><span class=\"caption-text\">' r'on <em>right</em></span>.*</p>\n' r'</div>') assert re.search(html, content, re.S) html = (r'<div align=\"center\" class=\"align-center\">' r'<div class="graphviz"><object data=\".*\.svg\".*>\n' r'\s*<p class=\"warning\">digraph foo {\n' r'centered\n' r'}</p></object></div>\n' r'</div>') assert re.search(html, content, re.S) @pytest.mark.sphinx('latex', testroot='ext-graphviz') @pytest.mark.usefixtures('if_graphviz_found') def test_graphviz_latex(app, status, warning): app.builder.build_all() content = (app.outdir / 'python.tex').text() macro = ('\\\\begin{figure}\\[htbp\\]\n\\\\centering\n\\\\capstart\n\n' '\\\\sphinxincludegraphics\\[\\]{graphviz-\\w+.pdf}\n' '\\\\caption{caption of graph}\\\\label{.*}\\\\end{figure}') assert re.search(macro, content, re.S) macro = 'Hello \\\\sphinxincludegraphics\\[\\]{graphviz-\\w+.pdf} graphviz world' assert re.search(macro, content, re.S) macro = ('\\\\begin{wrapfigure}{r}{0pt}\n\\\\centering\n' '\\\\sphinxincludegraphics\\[\\]{graphviz-\\w+.pdf}\n' '\\\\caption{on \\\\sphinxstyleemphasis{right}}' '\\\\label{.*}\\\\end{wrapfigure}') assert re.search(macro, content, re.S) macro = (r'\{\\hfill' r'\\sphinxincludegraphics\[\]{graphviz-.*}' r'\\hspace\*{\\fill}}') assert re.search(macro, content, re.S) @pytest.mark.sphinx('html', testroot='ext-graphviz', confoverrides={'language': 'xx'}) @pytest.mark.usefixtures('if_graphviz_found') def test_graphviz_i18n(app, status, warning): app.builder.build_all() content = (app.outdir / 'index.html').text() html = '<img src=".*?" alt="digraph {\n BAR -&gt; BAZ\n}" class="graphviz" />' assert re.search(html, content, re.M) def test_graphviz_parse_mapfile(): # empty graph code = ('# digraph {\n' '# }\n') content = ('<map id="%3" name="%3">\n' '</map>') cmap = ClickableMapDefinition('dummy.map', content, code) assert cmap.filename == 'dummy.map' assert cmap.id == 'grapvizb08107169e' assert len(cmap.clickable) == 0 assert cmap.generate_clickable_map() == '' # normal graph code = ('digraph {\n' ' foo [href="http://www.google.com/"];\n' ' foo -> bar;\n' '}\n') content = ('<map id="%3" name="%3">\n' '<area shape="poly" id="node1" href="http://www.google.com/" title="foo" alt=""' ' coords="77,29,76,22,70,15,62,10,52,7,41,5,30,7,20,10,12,15,7,22,5,29,7,37,12,' '43,20,49,30,52,41,53,52,52,62,49,70,43,76,37"/>\n' '</map>') cmap = ClickableMapDefinition('dummy.map', content, code) assert cmap.filename == 'dummy.map' assert cmap.id == 'grapviza4ccdd48ce' assert len(cmap.clickable) == 1 assert cmap.generate_clickable_map() == content.replace('%3', cmap.id) # inheritance-diagram:: sphinx.builders.html content = ( '<map id="inheritance66ff5471b9" name="inheritance66ff5471b9">\n' '<area shape="rect" id="node1" title="Builds target formats from the reST sources."' ' alt="" coords="26,95,125,110"/>\n' '<area shape="rect" id="node5" title="Builds standalone HTML docs."' ' alt="" coords="179,95,362,110"/>\n' '<area shape="rect" id="node2" title="buildinfo file manipulator." ' ' alt="" coords="14,64,138,80"/>\n' '<area shape="rect" id="node3" title="The container of stylesheets."' ' alt="" coords="3,34,148,49"/>\n' '<area shape="rect" id="node4" title="A StandaloneHTMLBuilder that creates all HTML' ' pages as &quot;index.html&quot; in" alt="" coords="395,64,569,80"/>\n' '<area shape="rect" id="node7" title="An abstract builder that serializes' ' the generated HTML." alt="" coords="392,95,571,110"/>\n' '<area shape="rect" id="node9" title="A StandaloneHTMLBuilder subclass that puts' ' the whole document tree on one" alt="" coords="393,125,570,141"/>\n' '<area shape="rect" id="node6" title="A builder that dumps the generated HTML' ' into JSON files." alt="" coords="602,80,765,95"/>\n' '<area shape="rect" id="node8" title="A Builder that dumps the generated HTML' ' into pickle files." alt="" coords="602,110,765,125"/>\n' '<area shape="rect" id="node10" title="The metadata of stylesheet."' ' alt="" coords="11,3,141,19"/>\n' '</map>' ) cmap = ClickableMapDefinition('dummy.map', content, 'dummy_code') assert cmap.filename == 'dummy.map' assert cmap.id == 'inheritance66ff5471b9' assert len(cmap.clickable) == 0 assert cmap.generate_clickable_map() == ''
""" test_ext_graphviz ~~~~~~~~~~~~~~~~~ Test sphinx.ext.graphviz extension. :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re import pytest from sphinx.ext.graphviz import ClickableMapDefinition @pytest.mark.sphinx('html', testroot='ext-graphviz') @pytest.mark.usefixtures('if_graphviz_found') def test_graphviz_png_html(app, status, warning): app.builder.build_all() content = (app.outdir / 'index.html').text() html = (r'<div class="figure align-center" .*?>\s*' r'<div class="graphviz"><img .*?/></div>\s*<p class="caption">' r'<span class="caption-text">caption of graph</span>.*</p>\s*</div>') assert re.search(html, content, re.S) html = 'Hello <div class="graphviz"><img .*?/></div>\n graphviz world' assert re.search(html, content, re.S) html = '<img src=".*?" alt="digraph {\n bar -&gt; baz\n}" class="graphviz" />' assert re.search(html, content, re.M) html = (r'<div class="figure align-right" .*?>\s*' r'<div class="graphviz"><img .*?/></div>\s*<p class="caption">' r'<span class="caption-text">on <em>right</em></span>.*</p>\s*</div>') assert re.search(html, content, re.S) html = (r'<div align=\"center\" class=\"align-center\">' r'<div class="graphviz"><img src=\".*\.png\" alt=\"digraph foo {\n' r'centered\n' r'}\" class="graphviz" /></div>\n</div>') assert re.search(html, content, re.S) @pytest.mark.sphinx('html', testroot='ext-graphviz', confoverrides={'graphviz_output_format': 'svg'}) @pytest.mark.usefixtures('if_graphviz_found') def test_graphviz_svg_html(app, status, warning): app.builder.build_all() content = (app.outdir / 'index.html').text() html = (r'<div class=\"figure align-center\" .*?>\n' r'<div class="graphviz"><object data=\".*\.svg\".*>\n' r'\s*<p class=\"warning\">digraph foo {\n' r'bar -&gt; baz\n' r'}</p></object></div>\n' r'<p class=\"caption\"><span class=\"caption-text\">' r'caption of graph</span>.*</p>\n</div>') assert re.search(html, content, re.S) html = (r'Hello <div class="graphviz"><object.*>\n' r'\s*<p class=\"warning\">graph</p></object></div>\n' r' graphviz world') assert re.search(html, content, re.S) html = (r'<div class=\"figure align-right\" .*\>\n' r'<div class="graphviz"><object data=\".*\.svg\".*>\n' r'\s*<p class=\"warning\">digraph bar {\n' r'foo -&gt; bar\n' r'}</p></object></div>\n' r'<p class=\"caption\"><span class=\"caption-text\">' r'on <em>right</em></span>.*</p>\n' r'</div>') assert re.search(html, content, re.S) html = (r'<div align=\"center\" class=\"align-center\">' r'<div class="graphviz"><object data=\".*\.svg\".*>\n' r'\s*<p class=\"warning\">digraph foo {\n' r'centered\n' r'}</p></object></div>\n' r'</div>') assert re.search(html, content, re.S) @pytest.mark.sphinx('latex', testroot='ext-graphviz') @pytest.mark.usefixtures('if_graphviz_found') def test_graphviz_latex(app, status, warning): app.builder.build_all() content = (app.outdir / 'python.tex').text() macro = ('\\\\begin{figure}\\[htbp\\]\n\\\\centering\n\\\\capstart\n\n' '\\\\sphinxincludegraphics\\[\\]{graphviz-\\w+.pdf}\n' '\\\\caption{caption of graph}\\\\label{.*}\\\\end{figure}') assert re.search(macro, content, re.S) macro = 'Hello \\\\sphinxincludegraphics\\[\\]{graphviz-\\w+.pdf} graphviz world' assert re.search(macro, content, re.S) macro = ('\\\\begin{wrapfigure}{r}{0pt}\n\\\\centering\n' '\\\\sphinxincludegraphics\\[\\]{graphviz-\\w+.pdf}\n' '\\\\caption{on \\\\sphinxstyleemphasis{right}}' '\\\\label{.*}\\\\end{wrapfigure}') assert re.search(macro, content, re.S) macro = (r'\{\\hfill' r'\\sphinxincludegraphics\[\]{graphviz-.*}' r'\\hspace\*{\\fill}}') assert re.search(macro, content, re.S) @pytest.mark.sphinx('html', testroot='ext-graphviz', confoverrides={'language': 'xx'}) @pytest.mark.usefixtures('if_graphviz_found') def test_graphviz_i18n(app, status, warning): app.builder.build_all() content = (app.outdir / 'index.html').text() html = '<img src=".*?" alt="digraph {\n BAR -&gt; BAZ\n}" class="graphviz" />' assert re.search(html, content, re.M) def test_graphviz_parse_mapfile(): # empty graph code = ('# digraph {\n' '# }\n') content = ('<map id="%3" name="%3">\n' '</map>') cmap = ClickableMapDefinition('dummy.map', content, code) assert cmap.filename == 'dummy.map' assert cmap.id == 'grapvizb08107169e' assert len(cmap.clickable) == 0 assert cmap.generate_clickable_map() == '' # normal graph code = ('digraph {\n' ' foo [href="http://www.google.com/"];\n' ' foo -> bar;\n' '}\n') content = ('<map id="%3" name="%3">\n' '<area shape="poly" id="node1" href="http://www.google.com/" title="foo" alt=""' ' coords="77,29,76,22,70,15,62,10,52,7,41,5,30,7,20,10,12,15,7,22,5,29,7,37,12,' '43,20,49,30,52,41,53,52,52,62,49,70,43,76,37"/>\n' '</map>') cmap = ClickableMapDefinition('dummy.map', content, code) assert cmap.filename == 'dummy.map' assert cmap.id == 'grapviza4ccdd48ce' assert len(cmap.clickable) == 1 assert cmap.generate_clickable_map() == content.replace('%3', cmap.id) # inheritance-diagram:: sphinx.builders.html content = ( '<map id="inheritance66ff5471b9" name="inheritance66ff5471b9">\n' '<area shape="rect" id="node1" title="Builds target formats from the reST sources."' ' alt="" coords="26,95,125,110"/>\n' '<area shape="rect" id="node5" title="Builds standalone HTML docs."' ' alt="" coords="179,95,362,110"/>\n' '<area shape="rect" id="node2" title="buildinfo file manipulator." ' ' alt="" coords="14,64,138,80"/>\n' '<area shape="rect" id="node3" title="The container of stylesheets."' ' alt="" coords="3,34,148,49"/>\n' '<area shape="rect" id="node4" title="A StandaloneHTMLBuilder that creates all HTML' ' pages as &quot;index.html&quot; in" alt="" coords="395,64,569,80"/>\n' '<area shape="rect" id="node7" title="An abstract builder that serializes' ' the generated HTML." alt="" coords="392,95,571,110"/>\n' '<area shape="rect" id="node9" title="A StandaloneHTMLBuilder subclass that puts' ' the whole document tree on one" alt="" coords="393,125,570,141"/>\n' '<area shape="rect" id="node6" title="A builder that dumps the generated HTML' ' into JSON files." alt="" coords="602,80,765,95"/>\n' '<area shape="rect" id="node8" title="A Builder that dumps the generated HTML' ' into pickle files." alt="" coords="602,110,765,125"/>\n' '<area shape="rect" id="node10" title="The metadata of stylesheet."' ' alt="" coords="11,3,141,19"/>\n' '</map>' ) cmap = ClickableMapDefinition('dummy.map', content, 'dummy_code') assert cmap.filename == 'dummy.map' assert cmap.id == 'inheritance66ff5471b9' assert len(cmap.clickable) == 0 assert cmap.generate_clickable_map() == ''
en
0.54296
test_ext_graphviz ~~~~~~~~~~~~~~~~~ Test sphinx.ext.graphviz extension. :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. # empty graph # normal graph # inheritance-diagram:: sphinx.builders.html
2.093257
2
Chest X-Ray Multilabel Image classification using CNN - Pytorch/train_model_transferLearning.py
farzanaaswin0708/CNN-for-Visual-recognition
0
6628343
<filename>Chest X-Ray Multilabel Image classification using CNN - Pytorch/train_model_transferLearning.py<gh_stars>0 #!/usr/bin/env python # coding: utf-8 # In[1]: #from Arch1 import * #from transferLearning import Arch1CNN import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as func import torch.nn.init as torch_init import torch.optim as optim import torchvision from torchvision import models,transforms import numpy as np from xray_dataloader_zscored_TL import get_weights,create_split_loaders,ChestXrayDataset # Setup: initialize the hyperparameters/variables num_epochs = 50 # Number of full passes through the dataset #<<<<<<< HEAD batch_size = 96 # Number of samples in each minibatch #======= #batch_size = 64 # Number of samples in each minibatch #>>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 learning_rate = 0.001 seed = np.random.seed(1) # Seed the random number generator for reproducibility p_val = 0.1 # Percent of the overall dataset to reserve for validation p_test = 0.2 # Percent of the overall dataset to reserve for testing #TODO: Convert to Tensor - you can later add other transformations, such as Scaling here transform = transforms.Compose([transforms.Resize((224,224)),transforms.ToTensor()]) transform2 = transforms.Compose([transforms.Resize((224,224)),transforms.RandomHorizontalFlip(p=1.0),transforms.ToTensor()]) #weights = get_weights(); # Check if your system supports CUDA use_cuda = torch.cuda.is_available() # Setup GPU optimization if CUDA is supported if use_cuda: computing_device = torch.device("cuda") extras = {"num_workers": 1, "pin_memory": True} print("CUDA is supported") else: # Otherwise, train on the CPU computing_device = torch.device("cpu") extras = False print("CUDA NOT supported") #Get class imbalance weights weights = get_weights() weights = weights.to(computing_device) # Setup the training, validation, and testing dataloaders train_loader1, val_loader1, test_loader1 = create_split_loaders(batch_size, seed, transform=transform, p_val=p_val, p_test=p_test, shuffle=True, show_sample=False, extras=extras) train_loader2, val_loader2, test_loader2 = create_split_loaders(batch_size, seed, transform=transform2, p_val=p_val, p_test=p_test, shuffle=True, show_sample=False, extras=extras) train_loader_list = [train_loader1,train_loader2] #train_loader = torch.utils.data.DataLoader(torch.utils.data.ConcatDataset([train_loader,train_loader2])) val_loader_list = [val_loader1, val_loader2] test_loader_list=[test_loader1,test_loader2] #val_loader = torch.utils.data.ConcatDataset([val_loader,val_loader2]) #test_loader = torch.utils.data.ConcatDataset([test_loader,test_loader2]) #print("") print("1 VGG 16 BN \n 2 VGG 19 BN \n 3 Resnet 34 ") #<<<<<<< HEAD #input_model = int(input("Choose the model:")) input_model = 2 input_setting = 1 print("1 Freeze parameters\n 2 Unfreeze parameters") #input_setting = int(input("Enter your choice:")) #======= #input_model = int(input("Choose the model:")) print("1 Freeze parameters\n 2 Unfreeze parameters") #input_setting = int(input("Enter your choice:")) #>>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 # Instantiate a BasicCNN to run on the GPU or CPU based on CUDA support ## VGG_16_bn if input_model == 1: model = models.vgg16_bn(pretrained=True) n_inputs = model.classifier[6].in_features elif input_model == 2: ## VGG_19_bn model = models.vgg19_bn(pretrained = True) n_inputs = model.classifier[6].in_features ## VGG_19_bn elif input_model == 3: model = models.resnet34(pretrained = True) n_inputs = model.fc.in_features if input_setting == 1: for param in model.features.parameters():## Freezing all the layers param.requires_grad = False for param in model.classifier.parameters():## Freezing all the layers param.requires_grad = False # add last linear layer (n_inputs -> 5 flower classes) # new layers automatically have requires_grad = True last_layer = nn.Linear(n_inputs, 14) ##VGG16 and VGG19 last layer change if input_model == 1 or input_model == 2: model.classifier[6] = last_layer elif input_model ==3: model.fc = last_layer # print out the model structure print(model) model = model.to(computing_device) print("Model on CUDA?", next(model.parameters()).is_cuda) #TODO: Define the loss criterion and instantiate the gradient descent optimizer #<<<<<<< HEAD criterion = torch.nn.MultiLabelSoftMarginLoss(weight = weights) #TODO - loss criteria are defined in the torch.nn package #criterion = torch.nn.BCELoss() #======= #criterion = torch.nn.MultiLabelSoftMarginLoss() #TODO - loss criteria are defined in the torch.nn package #criterion = torch.nn.BCELoss() #>>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 #TODO: Instantiate the gradient descent optimizer - use Adam optimizer with default parameters optimizer = torch.optim.Adam(model.classifier[6].parameters(),lr = learning_rate) #TODO - optimizers are defined in the torch.optim package print("initialised criterion and architecture!!") # In[ ]: # Track the loss across training total_loss = [] avg_minibatch_loss = [] validation_loss = [] # Begin training procedure for epoch in range(num_epochs): print("Entered the Training loop : epoch ", epoch) N = 50 N_minibatch_loss = 0.0 # Get the next minibatch of images, labels for training model.train() for train_loader in train_loader_list: for minibatch_count, (images, labels) in enumerate(train_loader, 0): # Put the minibatch data in CUDA Tensors and run on the GPU if supported images, labels = images.to(computing_device), labels.to(computing_device) # Zero out the stored gradient (buffer) from the previous iteration optimizer.zero_grad() # Perform the forward pass through the network and compute the loss outputs = model(images) #<<<<<<< HEAD loss = criterion(outputs, labels) #======= # loss = criterion(torch.sigmoid(outputs), labels) #>>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 # Automagically compute the gradients and backpropagate the loss through the network loss.backward() # Update the weights optimizer.step() # Add this iteration's loss to the total_loss total_loss.append(loss.item()) N_minibatch_loss += loss #TODO: Implement cross-validation if minibatch_count % N == 0: # Print the loss averaged over the last N mini-batches N_minibatch_loss /= N print('Epoch %d, average minibatch %d loss: %.3f' % (epoch + 1, minibatch_count, N_minibatch_loss)) # Add the averaged loss over N minibatches and reset the counter avg_minibatch_loss.append(N_minibatch_loss) N_minibatch_loss = 0.0 print("Finished", epoch + 1, "epochs of training") torch.save(model.state_dict(),"TL_trained.pt") #Validation temp_validation = 0 model.eval() for val_loader in val_loader_list: for minibatch_count,(images,labels) in enumerate(val_loader,0): images,labels = images.to(computing_device),labels.to(computing_device) outputs = model(images) loss = criterion(outputs,labels) temp_validation += loss.item() print("Validation loss after ",epoch," epochs=",temp_validation) validation_loss.append(temp_validation) if epoch >= 1 and validation_loss[-1] > validation_loss[-2]: break print("Training complete after", epoch, "epochs") torch.save(model.state_dict(),"TL_trained.pt")
<filename>Chest X-Ray Multilabel Image classification using CNN - Pytorch/train_model_transferLearning.py<gh_stars>0 #!/usr/bin/env python # coding: utf-8 # In[1]: #from Arch1 import * #from transferLearning import Arch1CNN import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as func import torch.nn.init as torch_init import torch.optim as optim import torchvision from torchvision import models,transforms import numpy as np from xray_dataloader_zscored_TL import get_weights,create_split_loaders,ChestXrayDataset # Setup: initialize the hyperparameters/variables num_epochs = 50 # Number of full passes through the dataset #<<<<<<< HEAD batch_size = 96 # Number of samples in each minibatch #======= #batch_size = 64 # Number of samples in each minibatch #>>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 learning_rate = 0.001 seed = np.random.seed(1) # Seed the random number generator for reproducibility p_val = 0.1 # Percent of the overall dataset to reserve for validation p_test = 0.2 # Percent of the overall dataset to reserve for testing #TODO: Convert to Tensor - you can later add other transformations, such as Scaling here transform = transforms.Compose([transforms.Resize((224,224)),transforms.ToTensor()]) transform2 = transforms.Compose([transforms.Resize((224,224)),transforms.RandomHorizontalFlip(p=1.0),transforms.ToTensor()]) #weights = get_weights(); # Check if your system supports CUDA use_cuda = torch.cuda.is_available() # Setup GPU optimization if CUDA is supported if use_cuda: computing_device = torch.device("cuda") extras = {"num_workers": 1, "pin_memory": True} print("CUDA is supported") else: # Otherwise, train on the CPU computing_device = torch.device("cpu") extras = False print("CUDA NOT supported") #Get class imbalance weights weights = get_weights() weights = weights.to(computing_device) # Setup the training, validation, and testing dataloaders train_loader1, val_loader1, test_loader1 = create_split_loaders(batch_size, seed, transform=transform, p_val=p_val, p_test=p_test, shuffle=True, show_sample=False, extras=extras) train_loader2, val_loader2, test_loader2 = create_split_loaders(batch_size, seed, transform=transform2, p_val=p_val, p_test=p_test, shuffle=True, show_sample=False, extras=extras) train_loader_list = [train_loader1,train_loader2] #train_loader = torch.utils.data.DataLoader(torch.utils.data.ConcatDataset([train_loader,train_loader2])) val_loader_list = [val_loader1, val_loader2] test_loader_list=[test_loader1,test_loader2] #val_loader = torch.utils.data.ConcatDataset([val_loader,val_loader2]) #test_loader = torch.utils.data.ConcatDataset([test_loader,test_loader2]) #print("") print("1 VGG 16 BN \n 2 VGG 19 BN \n 3 Resnet 34 ") #<<<<<<< HEAD #input_model = int(input("Choose the model:")) input_model = 2 input_setting = 1 print("1 Freeze parameters\n 2 Unfreeze parameters") #input_setting = int(input("Enter your choice:")) #======= #input_model = int(input("Choose the model:")) print("1 Freeze parameters\n 2 Unfreeze parameters") #input_setting = int(input("Enter your choice:")) #>>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 # Instantiate a BasicCNN to run on the GPU or CPU based on CUDA support ## VGG_16_bn if input_model == 1: model = models.vgg16_bn(pretrained=True) n_inputs = model.classifier[6].in_features elif input_model == 2: ## VGG_19_bn model = models.vgg19_bn(pretrained = True) n_inputs = model.classifier[6].in_features ## VGG_19_bn elif input_model == 3: model = models.resnet34(pretrained = True) n_inputs = model.fc.in_features if input_setting == 1: for param in model.features.parameters():## Freezing all the layers param.requires_grad = False for param in model.classifier.parameters():## Freezing all the layers param.requires_grad = False # add last linear layer (n_inputs -> 5 flower classes) # new layers automatically have requires_grad = True last_layer = nn.Linear(n_inputs, 14) ##VGG16 and VGG19 last layer change if input_model == 1 or input_model == 2: model.classifier[6] = last_layer elif input_model ==3: model.fc = last_layer # print out the model structure print(model) model = model.to(computing_device) print("Model on CUDA?", next(model.parameters()).is_cuda) #TODO: Define the loss criterion and instantiate the gradient descent optimizer #<<<<<<< HEAD criterion = torch.nn.MultiLabelSoftMarginLoss(weight = weights) #TODO - loss criteria are defined in the torch.nn package #criterion = torch.nn.BCELoss() #======= #criterion = torch.nn.MultiLabelSoftMarginLoss() #TODO - loss criteria are defined in the torch.nn package #criterion = torch.nn.BCELoss() #>>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 #TODO: Instantiate the gradient descent optimizer - use Adam optimizer with default parameters optimizer = torch.optim.Adam(model.classifier[6].parameters(),lr = learning_rate) #TODO - optimizers are defined in the torch.optim package print("initialised criterion and architecture!!") # In[ ]: # Track the loss across training total_loss = [] avg_minibatch_loss = [] validation_loss = [] # Begin training procedure for epoch in range(num_epochs): print("Entered the Training loop : epoch ", epoch) N = 50 N_minibatch_loss = 0.0 # Get the next minibatch of images, labels for training model.train() for train_loader in train_loader_list: for minibatch_count, (images, labels) in enumerate(train_loader, 0): # Put the minibatch data in CUDA Tensors and run on the GPU if supported images, labels = images.to(computing_device), labels.to(computing_device) # Zero out the stored gradient (buffer) from the previous iteration optimizer.zero_grad() # Perform the forward pass through the network and compute the loss outputs = model(images) #<<<<<<< HEAD loss = criterion(outputs, labels) #======= # loss = criterion(torch.sigmoid(outputs), labels) #>>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 # Automagically compute the gradients and backpropagate the loss through the network loss.backward() # Update the weights optimizer.step() # Add this iteration's loss to the total_loss total_loss.append(loss.item()) N_minibatch_loss += loss #TODO: Implement cross-validation if minibatch_count % N == 0: # Print the loss averaged over the last N mini-batches N_minibatch_loss /= N print('Epoch %d, average minibatch %d loss: %.3f' % (epoch + 1, minibatch_count, N_minibatch_loss)) # Add the averaged loss over N minibatches and reset the counter avg_minibatch_loss.append(N_minibatch_loss) N_minibatch_loss = 0.0 print("Finished", epoch + 1, "epochs of training") torch.save(model.state_dict(),"TL_trained.pt") #Validation temp_validation = 0 model.eval() for val_loader in val_loader_list: for minibatch_count,(images,labels) in enumerate(val_loader,0): images,labels = images.to(computing_device),labels.to(computing_device) outputs = model(images) loss = criterion(outputs,labels) temp_validation += loss.item() print("Validation loss after ",epoch," epochs=",temp_validation) validation_loss.append(temp_validation) if epoch >= 1 and validation_loss[-1] > validation_loss[-2]: break print("Training complete after", epoch, "epochs") torch.save(model.state_dict(),"TL_trained.pt")
en
0.602761
#!/usr/bin/env python # coding: utf-8 # In[1]: #from Arch1 import * #from transferLearning import Arch1CNN # Setup: initialize the hyperparameters/variables # Number of full passes through the dataset #<<<<<<< HEAD # Number of samples in each minibatch #======= #batch_size = 64 # Number of samples in each minibatch #>>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 # Seed the random number generator for reproducibility # Percent of the overall dataset to reserve for validation # Percent of the overall dataset to reserve for testing #TODO: Convert to Tensor - you can later add other transformations, such as Scaling here #weights = get_weights(); # Check if your system supports CUDA # Setup GPU optimization if CUDA is supported # Otherwise, train on the CPU #Get class imbalance weights # Setup the training, validation, and testing dataloaders #train_loader = torch.utils.data.DataLoader(torch.utils.data.ConcatDataset([train_loader,train_loader2])) #val_loader = torch.utils.data.ConcatDataset([val_loader,val_loader2]) #test_loader = torch.utils.data.ConcatDataset([test_loader,test_loader2]) #print("") #<<<<<<< HEAD #input_model = int(input("Choose the model:")) #input_setting = int(input("Enter your choice:")) #======= #input_model = int(input("Choose the model:")) #input_setting = int(input("Enter your choice:")) #>>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 # Instantiate a BasicCNN to run on the GPU or CPU based on CUDA support ## VGG_16_bn ## VGG_19_bn ## VGG_19_bn ## Freezing all the layers ## Freezing all the layers # add last linear layer (n_inputs -> 5 flower classes) # new layers automatically have requires_grad = True ##VGG16 and VGG19 last layer change # print out the model structure #TODO: Define the loss criterion and instantiate the gradient descent optimizer #<<<<<<< HEAD #TODO - loss criteria are defined in the torch.nn package #criterion = torch.nn.BCELoss() #======= #criterion = torch.nn.MultiLabelSoftMarginLoss() #TODO - loss criteria are defined in the torch.nn package #criterion = torch.nn.BCELoss() #>>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 #TODO: Instantiate the gradient descent optimizer - use Adam optimizer with default parameters #TODO - optimizers are defined in the torch.optim package # In[ ]: # Track the loss across training # Begin training procedure # Get the next minibatch of images, labels for training # Put the minibatch data in CUDA Tensors and run on the GPU if supported # Zero out the stored gradient (buffer) from the previous iteration # Perform the forward pass through the network and compute the loss #<<<<<<< HEAD #======= # loss = criterion(torch.sigmoid(outputs), labels) #>>>>>>> 6652e3cfb72835ac4a7c802c9a703b59d5f63ae6 # Automagically compute the gradients and backpropagate the loss through the network # Update the weights # Add this iteration's loss to the total_loss #TODO: Implement cross-validation # Print the loss averaged over the last N mini-batches # Add the averaged loss over N minibatches and reset the counter #Validation
2.690849
3
main.py
sfchronicle/jailed
0
6628344
import os from app import app, db from admin import admin from models import * from views import * if __name__ == '__main__': BASE_DIR = os.path.realpath(os.path.dirname(__file__)) DB_PATH = os.path.join(BASE_DIR, app.config['DATABASE_FILE']) if not os.path.exists(DB_PATH): db.create_all() # Start app app.config['DEBUG'] = True app.run(host='0.0.0.0')
import os from app import app, db from admin import admin from models import * from views import * if __name__ == '__main__': BASE_DIR = os.path.realpath(os.path.dirname(__file__)) DB_PATH = os.path.join(BASE_DIR, app.config['DATABASE_FILE']) if not os.path.exists(DB_PATH): db.create_all() # Start app app.config['DEBUG'] = True app.run(host='0.0.0.0')
en
0.69348
# Start app
1.741277
2
setup.py
ThatXliner/pypmeasy
1
6628345
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """To setup.""" from pathlib import Path from setuptools import setup, find_packages from pyjim import __version__, __author__ # The directory containing this file HERE = Path(Path(__file__).parent) # The text of the README file README = Path(HERE / "README.md").read_text() REQUIREMENTS = Path(HERE / "requirements.txt").read_text().split("\n") CLASSIFIERS = [ "Development Status :: 1 - Planning", "Environment :: Console", "Intended Audience :: End Users/Desktop", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: MacOS", "Operating System :: POSIX", "Operating System :: POSIX :: Linux", "Operating System :: Unix", "Programming Language :: Python", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development", "Typing :: Typed", ] setup( name="pyjim", # Replace with your own username version=__version__, author=__author__, author_email="<EMAIL>", description="A setup.py-integrated project manager that actually makes life easier.", long_description=README, long_description_content_type="text/markdown", # url="https://github.com/ThatXliner/pyjim", project_urls={ "Source Code": "https://github.com/ThatXliner/pyjim", # "Documentation": "https://pyjim.readthedocs.io/en/latest/index.html", "Tracker": "https://github.com/ThatXliner/pyjim/issues", }, packages=find_packages(exclude=["tests"], include=["pyjim"]), # scripts=["scripts/pyjim"], license="MIT", classifiers=CLASSIFIERS, python_requires=">=3.6", include_package_data=True, install_requires=[line for line in REQUIREMENTS if not line.startswith("#")], # keywords="api stackexchange stackoverflow python webscrape webscrap", # entry_points={"console_scripts": ["pyjim=pyjim.__main__:main"]}, )
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """To setup.""" from pathlib import Path from setuptools import setup, find_packages from pyjim import __version__, __author__ # The directory containing this file HERE = Path(Path(__file__).parent) # The text of the README file README = Path(HERE / "README.md").read_text() REQUIREMENTS = Path(HERE / "requirements.txt").read_text().split("\n") CLASSIFIERS = [ "Development Status :: 1 - Planning", "Environment :: Console", "Intended Audience :: End Users/Desktop", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: MacOS", "Operating System :: POSIX", "Operating System :: POSIX :: Linux", "Operating System :: Unix", "Programming Language :: Python", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development", "Typing :: Typed", ] setup( name="pyjim", # Replace with your own username version=__version__, author=__author__, author_email="<EMAIL>", description="A setup.py-integrated project manager that actually makes life easier.", long_description=README, long_description_content_type="text/markdown", # url="https://github.com/ThatXliner/pyjim", project_urls={ "Source Code": "https://github.com/ThatXliner/pyjim", # "Documentation": "https://pyjim.readthedocs.io/en/latest/index.html", "Tracker": "https://github.com/ThatXliner/pyjim/issues", }, packages=find_packages(exclude=["tests"], include=["pyjim"]), # scripts=["scripts/pyjim"], license="MIT", classifiers=CLASSIFIERS, python_requires=">=3.6", include_package_data=True, install_requires=[line for line in REQUIREMENTS if not line.startswith("#")], # keywords="api stackexchange stackoverflow python webscrape webscrap", # entry_points={"console_scripts": ["pyjim=pyjim.__main__:main"]}, )
en
0.526887
#!/usr/bin/env python3 # -*- coding: utf-8 -*- To setup. # The directory containing this file # The text of the README file # Replace with your own username # url="https://github.com/ThatXliner/pyjim", # "Documentation": "https://pyjim.readthedocs.io/en/latest/index.html", # scripts=["scripts/pyjim"], # keywords="api stackexchange stackoverflow python webscrape webscrap", # entry_points={"console_scripts": ["pyjim=pyjim.__main__:main"]},
1.540185
2
arviz/plots/backends/bokeh/loopitplot.py
mortonjt/arviz
1
6628346
<reponame>mortonjt/arviz """Bokeh loopitplot.""" import numpy as np from bokeh.models import BoxAnnotation from matplotlib.colors import hsv_to_rgb, rgb_to_hsv, to_hex, to_rgb from xarray import DataArray from ....stats.density_utils import kde from ...plot_utils import _scale_fig_size from .. import show_layout from . import backend_kwarg_defaults, create_axes_grid def plot_loo_pit( ax, figsize, ecdf, loo_pit, loo_pit_ecdf, unif_ecdf, p975, p025, fill_kwargs, ecdf_fill, use_hdi, x_vals, hdi_kwargs, hdi_odds, n_unif, unif, plot_unif_kwargs, loo_pit_kde, legend, # pylint: disable=unused-argument y_hat, y, color, textsize, labeller, hdi_prob, plot_kwargs, backend_kwargs, show, ): """Bokeh loo pit plot.""" if backend_kwargs is None: backend_kwargs = {} backend_kwargs = { **backend_kwarg_defaults(), **backend_kwargs, } (figsize, *_, linewidth, _) = _scale_fig_size(figsize, textsize, 1, 1) if ax is None: backend_kwargs.setdefault("x_range", (0, 1)) ax = create_axes_grid( 1, figsize=figsize, squeeze=True, backend_kwargs=backend_kwargs, ) plot_kwargs = {} if plot_kwargs is None else plot_kwargs plot_kwargs.setdefault("color", to_hex(color)) plot_kwargs.setdefault("linewidth", linewidth * 1.4) if isinstance(y, str): label = "LOO-PIT ECDF" if ecdf else "LOO-PIT" xlabel = y elif isinstance(y, DataArray) and y.name is not None: label = "LOO-PIT ECDF" if ecdf else "LOO-PIT" xlabel = y.name elif isinstance(y_hat, str): label = "LOO-PIT ECDF" if ecdf else "LOO-PIT" xlabel = y_hat elif isinstance(y_hat, DataArray) and y_hat.name is not None: label = "LOO-PIT ECDF" if ecdf else "LOO-PIT" xlabel = y_hat.name else: label = "LOO-PIT ECDF" if ecdf else "LOO-PIT" xlabel = "" xlabel = labeller.var_name_to_str(xlabel) plot_kwargs.setdefault("legend_label", label) plot_unif_kwargs = {} if plot_unif_kwargs is None else plot_unif_kwargs light_color = rgb_to_hsv(to_rgb(plot_kwargs.get("color"))) light_color[1] /= 2 # pylint: disable=unsupported-assignment-operation light_color[2] += (1 - light_color[2]) / 2 # pylint: disable=unsupported-assignment-operation plot_unif_kwargs.setdefault("color", to_hex(hsv_to_rgb(light_color))) plot_unif_kwargs.setdefault("alpha", 0.5) plot_unif_kwargs.setdefault("linewidth", 0.6 * linewidth) if ecdf: n_data_points = loo_pit.size plot_kwargs.setdefault("drawstyle", "steps-mid" if n_data_points < 100 else "default") plot_unif_kwargs.setdefault("drawstyle", "steps-mid" if n_data_points < 100 else "default") if ecdf_fill: if fill_kwargs is None: fill_kwargs = {} fill_kwargs.setdefault("color", to_hex(hsv_to_rgb(light_color))) fill_kwargs.setdefault("alpha", 0.5) fill_kwargs.setdefault( "step", "mid" if plot_kwargs["drawstyle"] == "steps-mid" else None ) fill_kwargs.setdefault( "legend_label", "{:.3g}% credible interval".format(hdi_prob * 100) ) elif use_hdi: if hdi_kwargs is None: hdi_kwargs = {} hdi_kwargs.setdefault("color", to_hex(hsv_to_rgb(light_color))) hdi_kwargs.setdefault("alpha", 0.35) if ecdf: if plot_kwargs.get("drawstyle") == "steps-mid": ax.step( np.hstack((0, loo_pit, 1)), np.hstack((0, loo_pit - loo_pit_ecdf, 0)), line_color=plot_kwargs.get("color", "black"), line_alpha=plot_kwargs.get("alpha", 1.0), line_width=plot_kwargs.get("linewidth", 3.0), mode="center", ) else: ax.line( np.hstack((0, loo_pit, 1)), np.hstack((0, loo_pit - loo_pit_ecdf, 0)), line_color=plot_kwargs.get("color", "black"), line_alpha=plot_kwargs.get("alpha", 1.0), line_width=plot_kwargs.get("linewidth", 3.0), ) if ecdf_fill: if fill_kwargs.get("drawstyle") == "steps-mid": # use step patch when you find out how to do that ax.patch( np.concatenate((unif_ecdf, unif_ecdf[::-1])), np.concatenate((p975 - unif_ecdf, (p025 - unif_ecdf)[::-1])), fill_color=fill_kwargs.get("color"), fill_alpha=fill_kwargs.get("alpha", 1.0), ) else: ax.patch( np.concatenate((unif_ecdf, unif_ecdf[::-1])), np.concatenate((p975 - unif_ecdf, (p025 - unif_ecdf)[::-1])), fill_color=fill_kwargs.get("color"), fill_alpha=fill_kwargs.get("alpha", 1.0), ) else: if fill_kwargs is not None and fill_kwargs.get("drawstyle") == "steps-mid": ax.step( unif_ecdf, p975 - unif_ecdf, line_color=plot_unif_kwargs.get("color", "black"), line_alpha=plot_unif_kwargs.get("alpha", 1.0), line_width=plot_kwargs.get("linewidth", 1.0), mode="center", ) ax.step( unif_ecdf, p025 - unif_ecdf, line_color=plot_unif_kwargs.get("color", "black"), line_alpha=plot_unif_kwargs.get("alpha", 1.0), line_width=plot_unif_kwargs.get("linewidth", 1.0), mode="center", ) else: ax.line( unif_ecdf, p975 - unif_ecdf, line_color=plot_unif_kwargs.get("color", "black"), line_alpha=plot_unif_kwargs.get("alpha", 1.0), line_width=plot_unif_kwargs.get("linewidth", 1.0), ) ax.line( unif_ecdf, p025 - unif_ecdf, line_color=plot_unif_kwargs.get("color", "black"), line_alpha=plot_unif_kwargs.get("alpha", 1.0), line_width=plot_unif_kwargs.get("linewidth", 1.0), ) else: if use_hdi: patch = BoxAnnotation( bottom=hdi_odds[1], top=hdi_odds[0], fill_alpha=hdi_kwargs.pop("alpha"), fill_color=hdi_kwargs.pop("color"), **hdi_kwargs ) patch.level = "underlay" ax.add_layout(patch) # Adds horizontal reference line ax.line([0, 1], [1, 1], line_color="white", line_width=1.5) else: for idx in range(n_unif): x_s, unif_density = kde(unif[idx, :]) ax.line( x_s, unif_density, line_color=plot_unif_kwargs.get("color", "black"), line_alpha=plot_unif_kwargs.get("alpha", 0.1), line_width=plot_unif_kwargs.get("linewidth", 1.0), ) ax.line( x_vals, loo_pit_kde, line_color=plot_kwargs.get("color", "black"), line_alpha=plot_kwargs.get("alpha", 1.0), line_width=plot_kwargs.get("linewidth", 3.0), ) # Sets xlim(0, 1) ax.xaxis.axis_label = xlabel ax.line(0, 0) ax.line(1, 0) show_layout(ax, show) return ax
"""Bokeh loopitplot.""" import numpy as np from bokeh.models import BoxAnnotation from matplotlib.colors import hsv_to_rgb, rgb_to_hsv, to_hex, to_rgb from xarray import DataArray from ....stats.density_utils import kde from ...plot_utils import _scale_fig_size from .. import show_layout from . import backend_kwarg_defaults, create_axes_grid def plot_loo_pit( ax, figsize, ecdf, loo_pit, loo_pit_ecdf, unif_ecdf, p975, p025, fill_kwargs, ecdf_fill, use_hdi, x_vals, hdi_kwargs, hdi_odds, n_unif, unif, plot_unif_kwargs, loo_pit_kde, legend, # pylint: disable=unused-argument y_hat, y, color, textsize, labeller, hdi_prob, plot_kwargs, backend_kwargs, show, ): """Bokeh loo pit plot.""" if backend_kwargs is None: backend_kwargs = {} backend_kwargs = { **backend_kwarg_defaults(), **backend_kwargs, } (figsize, *_, linewidth, _) = _scale_fig_size(figsize, textsize, 1, 1) if ax is None: backend_kwargs.setdefault("x_range", (0, 1)) ax = create_axes_grid( 1, figsize=figsize, squeeze=True, backend_kwargs=backend_kwargs, ) plot_kwargs = {} if plot_kwargs is None else plot_kwargs plot_kwargs.setdefault("color", to_hex(color)) plot_kwargs.setdefault("linewidth", linewidth * 1.4) if isinstance(y, str): label = "LOO-PIT ECDF" if ecdf else "LOO-PIT" xlabel = y elif isinstance(y, DataArray) and y.name is not None: label = "LOO-PIT ECDF" if ecdf else "LOO-PIT" xlabel = y.name elif isinstance(y_hat, str): label = "LOO-PIT ECDF" if ecdf else "LOO-PIT" xlabel = y_hat elif isinstance(y_hat, DataArray) and y_hat.name is not None: label = "LOO-PIT ECDF" if ecdf else "LOO-PIT" xlabel = y_hat.name else: label = "LOO-PIT ECDF" if ecdf else "LOO-PIT" xlabel = "" xlabel = labeller.var_name_to_str(xlabel) plot_kwargs.setdefault("legend_label", label) plot_unif_kwargs = {} if plot_unif_kwargs is None else plot_unif_kwargs light_color = rgb_to_hsv(to_rgb(plot_kwargs.get("color"))) light_color[1] /= 2 # pylint: disable=unsupported-assignment-operation light_color[2] += (1 - light_color[2]) / 2 # pylint: disable=unsupported-assignment-operation plot_unif_kwargs.setdefault("color", to_hex(hsv_to_rgb(light_color))) plot_unif_kwargs.setdefault("alpha", 0.5) plot_unif_kwargs.setdefault("linewidth", 0.6 * linewidth) if ecdf: n_data_points = loo_pit.size plot_kwargs.setdefault("drawstyle", "steps-mid" if n_data_points < 100 else "default") plot_unif_kwargs.setdefault("drawstyle", "steps-mid" if n_data_points < 100 else "default") if ecdf_fill: if fill_kwargs is None: fill_kwargs = {} fill_kwargs.setdefault("color", to_hex(hsv_to_rgb(light_color))) fill_kwargs.setdefault("alpha", 0.5) fill_kwargs.setdefault( "step", "mid" if plot_kwargs["drawstyle"] == "steps-mid" else None ) fill_kwargs.setdefault( "legend_label", "{:.3g}% credible interval".format(hdi_prob * 100) ) elif use_hdi: if hdi_kwargs is None: hdi_kwargs = {} hdi_kwargs.setdefault("color", to_hex(hsv_to_rgb(light_color))) hdi_kwargs.setdefault("alpha", 0.35) if ecdf: if plot_kwargs.get("drawstyle") == "steps-mid": ax.step( np.hstack((0, loo_pit, 1)), np.hstack((0, loo_pit - loo_pit_ecdf, 0)), line_color=plot_kwargs.get("color", "black"), line_alpha=plot_kwargs.get("alpha", 1.0), line_width=plot_kwargs.get("linewidth", 3.0), mode="center", ) else: ax.line( np.hstack((0, loo_pit, 1)), np.hstack((0, loo_pit - loo_pit_ecdf, 0)), line_color=plot_kwargs.get("color", "black"), line_alpha=plot_kwargs.get("alpha", 1.0), line_width=plot_kwargs.get("linewidth", 3.0), ) if ecdf_fill: if fill_kwargs.get("drawstyle") == "steps-mid": # use step patch when you find out how to do that ax.patch( np.concatenate((unif_ecdf, unif_ecdf[::-1])), np.concatenate((p975 - unif_ecdf, (p025 - unif_ecdf)[::-1])), fill_color=fill_kwargs.get("color"), fill_alpha=fill_kwargs.get("alpha", 1.0), ) else: ax.patch( np.concatenate((unif_ecdf, unif_ecdf[::-1])), np.concatenate((p975 - unif_ecdf, (p025 - unif_ecdf)[::-1])), fill_color=fill_kwargs.get("color"), fill_alpha=fill_kwargs.get("alpha", 1.0), ) else: if fill_kwargs is not None and fill_kwargs.get("drawstyle") == "steps-mid": ax.step( unif_ecdf, p975 - unif_ecdf, line_color=plot_unif_kwargs.get("color", "black"), line_alpha=plot_unif_kwargs.get("alpha", 1.0), line_width=plot_kwargs.get("linewidth", 1.0), mode="center", ) ax.step( unif_ecdf, p025 - unif_ecdf, line_color=plot_unif_kwargs.get("color", "black"), line_alpha=plot_unif_kwargs.get("alpha", 1.0), line_width=plot_unif_kwargs.get("linewidth", 1.0), mode="center", ) else: ax.line( unif_ecdf, p975 - unif_ecdf, line_color=plot_unif_kwargs.get("color", "black"), line_alpha=plot_unif_kwargs.get("alpha", 1.0), line_width=plot_unif_kwargs.get("linewidth", 1.0), ) ax.line( unif_ecdf, p025 - unif_ecdf, line_color=plot_unif_kwargs.get("color", "black"), line_alpha=plot_unif_kwargs.get("alpha", 1.0), line_width=plot_unif_kwargs.get("linewidth", 1.0), ) else: if use_hdi: patch = BoxAnnotation( bottom=hdi_odds[1], top=hdi_odds[0], fill_alpha=hdi_kwargs.pop("alpha"), fill_color=hdi_kwargs.pop("color"), **hdi_kwargs ) patch.level = "underlay" ax.add_layout(patch) # Adds horizontal reference line ax.line([0, 1], [1, 1], line_color="white", line_width=1.5) else: for idx in range(n_unif): x_s, unif_density = kde(unif[idx, :]) ax.line( x_s, unif_density, line_color=plot_unif_kwargs.get("color", "black"), line_alpha=plot_unif_kwargs.get("alpha", 0.1), line_width=plot_unif_kwargs.get("linewidth", 1.0), ) ax.line( x_vals, loo_pit_kde, line_color=plot_kwargs.get("color", "black"), line_alpha=plot_kwargs.get("alpha", 1.0), line_width=plot_kwargs.get("linewidth", 3.0), ) # Sets xlim(0, 1) ax.xaxis.axis_label = xlabel ax.line(0, 0) ax.line(1, 0) show_layout(ax, show) return ax
en
0.586724
Bokeh loopitplot. # pylint: disable=unused-argument Bokeh loo pit plot. # pylint: disable=unsupported-assignment-operation # pylint: disable=unsupported-assignment-operation # use step patch when you find out how to do that # Adds horizontal reference line # Sets xlim(0, 1)
2.195458
2
eden/integration/snapshot/test_snapshots.py
jmswen/eden
0
6628347
#!/usr/bin/env python3 # # Copyright (c) 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. import os import stat import unittest from pathlib import Path from typing import Callable from eden.integration.lib import edenclient from . import snapshot as snapshot_mod, verify as verify_mod class Test(unittest.TestCase): """Tests to verify the contents of various saved snapshots. All of the test functions in this class are dynamically added by register_tests() """ def _test_snapshot(self, snapshot_path: Path) -> None: with snapshot_mod.create_tmp_dir() as tmp_dir: snapshot = snapshot_mod.unpack_into(snapshot_path, tmp_dir) self._run_test(snapshot) def _run_test(self, snapshot: snapshot_mod.BaseSnapshot) -> None: verifier = verify_mod.SnapshotVerifier() snapshot.verify(verifier) # Fail the test if any errors were found. # The individual errors will have been printed out previously # as they were found. if verifier.errors: self.fail(f"found {len(verifier.errors)} errors") class InfraTests(unittest.TestCase): """Tests for the snapshot generation/verification code itself.""" NUM_SNAPSHOTS = 0 def test_snapshot_list(self) -> None: # Ensure that at least one snapshot file was found, so that the tests will # fail if we somehow can't find the snapshot data directory correctly. self.assertGreater(self.NUM_SNAPSHOTS, 0) def test_verify_directory(self) -> None: expected = verify_mod.ExpectedFileSet() expected.add_file("a/b/normal.txt", b"abc\n", 0o644) expected.add_file("a/b/normal_exe.exe", b"abc\n", 0o755) expected.add_file("a/b/missing.txt", b"abc\n", 0o644) expected.add_file("a/b/wrong_perms.txt", b"abc\n", 0o644) expected.add_file("a/b/wrong_file_type.txt", b"abc\n", 0o644) expected.add_socket("a/normal.sock", 0o644) expected.add_socket("a/exe.sock", 0o755) expected.add_symlink("a/normal.link", b"symlink contents", 0o777) expected.add_symlink("a/missing.link", b"missing symlink", 0o777) # Define a subclass of HgSnapshot. We use define this solely so we can use its # helper write_file(), make_socket(), and mkdir() methods class MockSnapshot(snapshot_mod.HgSnapshot): def populate_backing_repo(self) -> None: pass def populate_checkout(self) -> None: pass def verify_snapshot_data( self, verifier: verify_mod.SnapshotVerifier, eden: edenclient.EdenFS ) -> None: pass with snapshot_mod.create_tmp_dir() as tmp_dir: snapshot = MockSnapshot(tmp_dir) snapshot.data_dir.mkdir() snapshot.checkout_path.mkdir() snapshot.write_file("a/b/normal.txt", b"abc\n", 0o644) snapshot.write_file("a/b/normal_exe.exe", b"abc\n", 0o755) snapshot.write_file("a/b/wrong_perms.txt", b"abc\n", 0o755) snapshot.make_socket("a/b/wrong_file_type.txt", 0o755) snapshot.make_socket("a/normal.sock", 0o644) snapshot.make_socket("a/exe.sock", 0o755) os.symlink(b"symlink contents", snapshot.checkout_path / "a/normal.link") # The verifier code only checks files, not directories, so it should not # complain about extra directories that may be present. snapshot.mkdir("a/b/c/extra_dir", 0o755) verifier = verify_mod.SnapshotVerifier() verifier.verify_directory(snapshot.checkout_path, expected) expected_errors = [ "a/b/missing.txt: file not present in snapshot", "a/missing.link: file not present in snapshot", f"a/b/wrong_file_type.txt: expected file type to be {stat.S_IFREG:#o}, " f"found {stat.S_IFSOCK:#o}", f"a/b/wrong_file_type.txt: expected permissions to be 0o644, found 0o755", "a/b/wrong_perms.txt: expected permissions to be 0o644, found 0o755", ] self.assertEqual(sorted(verifier.errors), sorted(expected_errors)) def register_tests() -> None: # Create one test function for each snapshot snapshot_dir = Path("eden/test-data/snapshots").resolve() for snapshot in snapshot_dir.iterdir(): # We don't use Path.stem here since it only strips off the very last suffix, # so foo.tar.bz2 becomes foo.tar rather than foo. stem = snapshot.name.split(".", 1)[0] setattr(Test, f"test_{stem}", _create_test_fn(snapshot)) InfraTests.NUM_SNAPSHOTS += 1 def _create_test_fn(snapshot: Path) -> Callable[[Test], None]: def test_fn(self: Test) -> None: self._test_snapshot(snapshot) return test_fn register_tests()
#!/usr/bin/env python3 # # Copyright (c) 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. import os import stat import unittest from pathlib import Path from typing import Callable from eden.integration.lib import edenclient from . import snapshot as snapshot_mod, verify as verify_mod class Test(unittest.TestCase): """Tests to verify the contents of various saved snapshots. All of the test functions in this class are dynamically added by register_tests() """ def _test_snapshot(self, snapshot_path: Path) -> None: with snapshot_mod.create_tmp_dir() as tmp_dir: snapshot = snapshot_mod.unpack_into(snapshot_path, tmp_dir) self._run_test(snapshot) def _run_test(self, snapshot: snapshot_mod.BaseSnapshot) -> None: verifier = verify_mod.SnapshotVerifier() snapshot.verify(verifier) # Fail the test if any errors were found. # The individual errors will have been printed out previously # as they were found. if verifier.errors: self.fail(f"found {len(verifier.errors)} errors") class InfraTests(unittest.TestCase): """Tests for the snapshot generation/verification code itself.""" NUM_SNAPSHOTS = 0 def test_snapshot_list(self) -> None: # Ensure that at least one snapshot file was found, so that the tests will # fail if we somehow can't find the snapshot data directory correctly. self.assertGreater(self.NUM_SNAPSHOTS, 0) def test_verify_directory(self) -> None: expected = verify_mod.ExpectedFileSet() expected.add_file("a/b/normal.txt", b"abc\n", 0o644) expected.add_file("a/b/normal_exe.exe", b"abc\n", 0o755) expected.add_file("a/b/missing.txt", b"abc\n", 0o644) expected.add_file("a/b/wrong_perms.txt", b"abc\n", 0o644) expected.add_file("a/b/wrong_file_type.txt", b"abc\n", 0o644) expected.add_socket("a/normal.sock", 0o644) expected.add_socket("a/exe.sock", 0o755) expected.add_symlink("a/normal.link", b"symlink contents", 0o777) expected.add_symlink("a/missing.link", b"missing symlink", 0o777) # Define a subclass of HgSnapshot. We use define this solely so we can use its # helper write_file(), make_socket(), and mkdir() methods class MockSnapshot(snapshot_mod.HgSnapshot): def populate_backing_repo(self) -> None: pass def populate_checkout(self) -> None: pass def verify_snapshot_data( self, verifier: verify_mod.SnapshotVerifier, eden: edenclient.EdenFS ) -> None: pass with snapshot_mod.create_tmp_dir() as tmp_dir: snapshot = MockSnapshot(tmp_dir) snapshot.data_dir.mkdir() snapshot.checkout_path.mkdir() snapshot.write_file("a/b/normal.txt", b"abc\n", 0o644) snapshot.write_file("a/b/normal_exe.exe", b"abc\n", 0o755) snapshot.write_file("a/b/wrong_perms.txt", b"abc\n", 0o755) snapshot.make_socket("a/b/wrong_file_type.txt", 0o755) snapshot.make_socket("a/normal.sock", 0o644) snapshot.make_socket("a/exe.sock", 0o755) os.symlink(b"symlink contents", snapshot.checkout_path / "a/normal.link") # The verifier code only checks files, not directories, so it should not # complain about extra directories that may be present. snapshot.mkdir("a/b/c/extra_dir", 0o755) verifier = verify_mod.SnapshotVerifier() verifier.verify_directory(snapshot.checkout_path, expected) expected_errors = [ "a/b/missing.txt: file not present in snapshot", "a/missing.link: file not present in snapshot", f"a/b/wrong_file_type.txt: expected file type to be {stat.S_IFREG:#o}, " f"found {stat.S_IFSOCK:#o}", f"a/b/wrong_file_type.txt: expected permissions to be 0o644, found 0o755", "a/b/wrong_perms.txt: expected permissions to be 0o644, found 0o755", ] self.assertEqual(sorted(verifier.errors), sorted(expected_errors)) def register_tests() -> None: # Create one test function for each snapshot snapshot_dir = Path("eden/test-data/snapshots").resolve() for snapshot in snapshot_dir.iterdir(): # We don't use Path.stem here since it only strips off the very last suffix, # so foo.tar.bz2 becomes foo.tar rather than foo. stem = snapshot.name.split(".", 1)[0] setattr(Test, f"test_{stem}", _create_test_fn(snapshot)) InfraTests.NUM_SNAPSHOTS += 1 def _create_test_fn(snapshot: Path) -> Callable[[Test], None]: def test_fn(self: Test) -> None: self._test_snapshot(snapshot) return test_fn register_tests()
en
0.920306
#!/usr/bin/env python3 # # Copyright (c) 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. Tests to verify the contents of various saved snapshots. All of the test functions in this class are dynamically added by register_tests() # Fail the test if any errors were found. # The individual errors will have been printed out previously # as they were found. Tests for the snapshot generation/verification code itself. # Ensure that at least one snapshot file was found, so that the tests will # fail if we somehow can't find the snapshot data directory correctly. # Define a subclass of HgSnapshot. We use define this solely so we can use its # helper write_file(), make_socket(), and mkdir() methods # The verifier code only checks files, not directories, so it should not # complain about extra directories that may be present. #o}, " #o}", # Create one test function for each snapshot # We don't use Path.stem here since it only strips off the very last suffix, # so foo.tar.bz2 becomes foo.tar rather than foo.
2.399328
2
batch_overlap_test.py
caslab-vt/DeepPaSTL
0
6628348
<reponame>caslab-vt/DeepPaSTL import torch import torch.nn as nn import warnings import numpy as np import matplotlib import pandas as pd import scipy.io import pickle import multiprocessing as mp from os import listdir from torchviz import make_dot from data_utils.data_preprocess import process_testing_data warnings.filterwarnings('ignore') matplotlib.rcParams['figure.figsize'] = (12.0, 12.0) pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) from config_args import parse_args from data_utils.crop_utils import prep_overlap, predict_tiles, undo_overlap, predict_batch_tiles from data_utils.data_postprocess import plot_surface, scatter_plot, get_scale_3d from trainer_utils.trainer import TorchTrainer from networks.encoderdecoder3d import EncoderDecoderWrapper3d torch.manual_seed(420) np.random.seed(420) def predict_batch(): print("Starting") # Parse arguments and load data args = parse_args() #with mp.Pool(args.data_proc_workers) as pool: # result = pool.map(process_testing_data, [args])[0] # Loading all data in to numpy arrays scaled_data = pd.read_pickle(args.data_folder + args.process_folder + args.model + '_test_predictions_processed_data' + '.pkl') height_list = ["h" + str(i + 1) for i in range(args.num_features)] # This is already scaled h_aggr_list = np.array([np.array(scaled_data[h]) for h in height_list]) h_aggr_list = np.swapaxes(h_aggr_list, 1, 0) h_aggr_list = np.reshape(h_aggr_list, (-1, args.xdim, args.ydim)) h_aggr_list = h_aggr_list[np.newaxis] # Add mirror padding to the images h_aggr_list_target = h_aggr_list with mp.Pool(args.data_proc_workers) as pool: h_aggr_list = pool.map(prep_overlap, [(args, h_aggr_list)])[0] # h_aggr_list = prep_overlap(args, h_aggr_list) # h_aggr_list: (1, len, h+p, w+p) print(f"Shape of overlap: {h_aggr_list[0].shape}") if not args.mcmcdrop: args.n_samples = 1 """ Defining the Model """ feature_list = ['h_in'] c = 1 t = 1 h = args.window_size w = args.window_size x_features = (c, t, h, w) model = EncoderDecoderWrapper3d(args, None, None, feature_list, x_features) print(f'GPUs used: {torch.cuda.device_count()}') model = nn.DataParallel(model) # , device_ids=[0], output_device=[0]) model.to(args.device) loss_fn = torch.nn.MSELoss() model_optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=1e-2) optimizers = [model_optimizer] schedulers = [] trainer = TorchTrainer( args.exp_name, model, optimizers, loss_fn, schedulers, args.device, scheduler_batch_step=True, pass_y=False, args=args ) # print(repr(model)) trainer._load_checkpoint(only_model=True, epoch=args.epoch_load) # Start sequencing and predict in batches args.test_batch_size = 731 in_len_b = int(args.in_seq_len * args.seq_stride) + args.test_batch_size in_len_i = int(args.in_seq_len * args.seq_stride) out_len_i = int(args.out_seq_len * args.seq_stride) print("Starting tile prediction") break_loop = None for i in range(0, h_aggr_list[0].shape[1], args.test_batch_size): if i + args.test_batch_size + in_len_i + out_len_i >= h_aggr_list[0].shape[1]: args.test_batch_size = h_aggr_list[0].shape[1] - in_len_i - out_len_i - 1 if args.test_batch_size == 0: break break_loop = True h_aggr_list_b = [h_aggr_list[0][:, i+j: i+j+in_len_i: args.seq_stride] for j in range(args.test_batch_size)] h_aggr_list_b = [np.concatenate(h_aggr_list_b, axis=0)] #[b, seq, h+p, w+p] h_aggr_list_out_b = [h_aggr_list_target[:, i+j+in_len_i: i+j+in_len_i+out_len_i: args.seq_stride] for j in range(args.test_batch_size)] h_aggr_list_out_b = np.concatenate(h_aggr_list_out_b, axis=0) #[b, seq, h+p, w+p] h_pred_b = predict_batch_tiles(h_aggr_list_b, [h_aggr_list_out_b], args, trainer) h_pred_mean_b, h_pred_std_b = h_pred_b with mp.Pool(args.data_proc_workers) as pool: h_pred_mean_b = pool.map(undo_overlap, [(args, h_pred_mean_b)])[0] with mp.Pool(args.data_proc_workers) as pool: h_pred_std_b = pool.map(undo_overlap, [(args, h_pred_std_b)])[0] h_error_b = h_aggr_list_out_b - h_pred_mean_b print(f'Mean: {h_pred_mean_b.shape}, Std: {h_pred_std_b.shape}, Target: {h_aggr_list_out_b.shape}, Error: {h_error_b.shape}') if i == 0: h_pred_mean = h_pred_mean_b h_pred_std = h_pred_std_b h_error = h_error_b h_target = h_aggr_list_out_b else: h_pred_mean = np.concatenate([h_pred_mean, h_pred_mean_b], axis=0) h_pred_std = np.concatenate([h_pred_std, h_pred_std_b], axis=0) h_error = np.concatenate([h_error, h_error_b], axis=0) h_target = np.concatenate([h_target, h_aggr_list_out_b], axis=0) if break_loop: break def scale_outs(value_str, scale, scale_std=False): if scale_std: value_str = np.multiply(value_str, scale[1] - scale[0]) else: value_str = np.multiply(value_str, scale[1] - scale[0]) + scale[0] return value_str scale = get_scale_3d(args, file='Testing') h_pred_mean = scale_outs(h_pred_mean, scale) h_pred_std = scale_outs(h_pred_std, scale, True) h_target = scale_outs(h_target, scale) h_error = scale_outs(h_error, scale, True) y_mdic = {'y_predict_mean': h_pred_mean, 'y_predict_std': h_pred_std, 'y_predict_err': h_error, 'y_target': h_target} scipy.io.savemat( args.data_folder + args.predict_folder + args.model + '_predict_data_' + args.predict_run + '_' + args.exp_name + '_testing_set.mat', mdict=y_mdic, oned_as='row') return if __name__ == '__main__': predict_batch()
import torch import torch.nn as nn import warnings import numpy as np import matplotlib import pandas as pd import scipy.io import pickle import multiprocessing as mp from os import listdir from torchviz import make_dot from data_utils.data_preprocess import process_testing_data warnings.filterwarnings('ignore') matplotlib.rcParams['figure.figsize'] = (12.0, 12.0) pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) from config_args import parse_args from data_utils.crop_utils import prep_overlap, predict_tiles, undo_overlap, predict_batch_tiles from data_utils.data_postprocess import plot_surface, scatter_plot, get_scale_3d from trainer_utils.trainer import TorchTrainer from networks.encoderdecoder3d import EncoderDecoderWrapper3d torch.manual_seed(420) np.random.seed(420) def predict_batch(): print("Starting") # Parse arguments and load data args = parse_args() #with mp.Pool(args.data_proc_workers) as pool: # result = pool.map(process_testing_data, [args])[0] # Loading all data in to numpy arrays scaled_data = pd.read_pickle(args.data_folder + args.process_folder + args.model + '_test_predictions_processed_data' + '.pkl') height_list = ["h" + str(i + 1) for i in range(args.num_features)] # This is already scaled h_aggr_list = np.array([np.array(scaled_data[h]) for h in height_list]) h_aggr_list = np.swapaxes(h_aggr_list, 1, 0) h_aggr_list = np.reshape(h_aggr_list, (-1, args.xdim, args.ydim)) h_aggr_list = h_aggr_list[np.newaxis] # Add mirror padding to the images h_aggr_list_target = h_aggr_list with mp.Pool(args.data_proc_workers) as pool: h_aggr_list = pool.map(prep_overlap, [(args, h_aggr_list)])[0] # h_aggr_list = prep_overlap(args, h_aggr_list) # h_aggr_list: (1, len, h+p, w+p) print(f"Shape of overlap: {h_aggr_list[0].shape}") if not args.mcmcdrop: args.n_samples = 1 """ Defining the Model """ feature_list = ['h_in'] c = 1 t = 1 h = args.window_size w = args.window_size x_features = (c, t, h, w) model = EncoderDecoderWrapper3d(args, None, None, feature_list, x_features) print(f'GPUs used: {torch.cuda.device_count()}') model = nn.DataParallel(model) # , device_ids=[0], output_device=[0]) model.to(args.device) loss_fn = torch.nn.MSELoss() model_optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=1e-2) optimizers = [model_optimizer] schedulers = [] trainer = TorchTrainer( args.exp_name, model, optimizers, loss_fn, schedulers, args.device, scheduler_batch_step=True, pass_y=False, args=args ) # print(repr(model)) trainer._load_checkpoint(only_model=True, epoch=args.epoch_load) # Start sequencing and predict in batches args.test_batch_size = 731 in_len_b = int(args.in_seq_len * args.seq_stride) + args.test_batch_size in_len_i = int(args.in_seq_len * args.seq_stride) out_len_i = int(args.out_seq_len * args.seq_stride) print("Starting tile prediction") break_loop = None for i in range(0, h_aggr_list[0].shape[1], args.test_batch_size): if i + args.test_batch_size + in_len_i + out_len_i >= h_aggr_list[0].shape[1]: args.test_batch_size = h_aggr_list[0].shape[1] - in_len_i - out_len_i - 1 if args.test_batch_size == 0: break break_loop = True h_aggr_list_b = [h_aggr_list[0][:, i+j: i+j+in_len_i: args.seq_stride] for j in range(args.test_batch_size)] h_aggr_list_b = [np.concatenate(h_aggr_list_b, axis=0)] #[b, seq, h+p, w+p] h_aggr_list_out_b = [h_aggr_list_target[:, i+j+in_len_i: i+j+in_len_i+out_len_i: args.seq_stride] for j in range(args.test_batch_size)] h_aggr_list_out_b = np.concatenate(h_aggr_list_out_b, axis=0) #[b, seq, h+p, w+p] h_pred_b = predict_batch_tiles(h_aggr_list_b, [h_aggr_list_out_b], args, trainer) h_pred_mean_b, h_pred_std_b = h_pred_b with mp.Pool(args.data_proc_workers) as pool: h_pred_mean_b = pool.map(undo_overlap, [(args, h_pred_mean_b)])[0] with mp.Pool(args.data_proc_workers) as pool: h_pred_std_b = pool.map(undo_overlap, [(args, h_pred_std_b)])[0] h_error_b = h_aggr_list_out_b - h_pred_mean_b print(f'Mean: {h_pred_mean_b.shape}, Std: {h_pred_std_b.shape}, Target: {h_aggr_list_out_b.shape}, Error: {h_error_b.shape}') if i == 0: h_pred_mean = h_pred_mean_b h_pred_std = h_pred_std_b h_error = h_error_b h_target = h_aggr_list_out_b else: h_pred_mean = np.concatenate([h_pred_mean, h_pred_mean_b], axis=0) h_pred_std = np.concatenate([h_pred_std, h_pred_std_b], axis=0) h_error = np.concatenate([h_error, h_error_b], axis=0) h_target = np.concatenate([h_target, h_aggr_list_out_b], axis=0) if break_loop: break def scale_outs(value_str, scale, scale_std=False): if scale_std: value_str = np.multiply(value_str, scale[1] - scale[0]) else: value_str = np.multiply(value_str, scale[1] - scale[0]) + scale[0] return value_str scale = get_scale_3d(args, file='Testing') h_pred_mean = scale_outs(h_pred_mean, scale) h_pred_std = scale_outs(h_pred_std, scale, True) h_target = scale_outs(h_target, scale) h_error = scale_outs(h_error, scale, True) y_mdic = {'y_predict_mean': h_pred_mean, 'y_predict_std': h_pred_std, 'y_predict_err': h_error, 'y_target': h_target} scipy.io.savemat( args.data_folder + args.predict_folder + args.model + '_predict_data_' + args.predict_run + '_' + args.exp_name + '_testing_set.mat', mdict=y_mdic, oned_as='row') return if __name__ == '__main__': predict_batch()
en
0.521797
# Parse arguments and load data #with mp.Pool(args.data_proc_workers) as pool: # result = pool.map(process_testing_data, [args])[0] # Loading all data in to numpy arrays # This is already scaled # Add mirror padding to the images # h_aggr_list = prep_overlap(args, h_aggr_list) # h_aggr_list: (1, len, h+p, w+p) Defining the Model # , device_ids=[0], output_device=[0]) # print(repr(model)) # Start sequencing and predict in batches #[b, seq, h+p, w+p] #[b, seq, h+p, w+p]
1.99919
2
server/comondata/admin.py
Beakjiyeon/English_Planet
0
6628349
<reponame>Beakjiyeon/English_Planet<filename>server/comondata/admin.py<gh_stars>0 from django.contrib import admin from .models import * admin.site.register(Book) admin.site.register(Bookword) admin.site.register(Camera) admin.site.register(Myword) admin.site.register(Planet) admin.site.register(Quiz) admin.site.register(User) # Register your models here.
from django.contrib import admin from .models import * admin.site.register(Book) admin.site.register(Bookword) admin.site.register(Camera) admin.site.register(Myword) admin.site.register(Planet) admin.site.register(Quiz) admin.site.register(User) # Register your models here.
en
0.968259
# Register your models here.
1.511141
2
Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/python/tvm/rpc/__init__.py
mengkai94/training_results_v0.6
64
6628350
"""Lightweight TVM RPC module. RPC enables connect to a remote server, upload and launch functions. This is useful to for cross-compile and remote testing, The compiler stack runs on local server, while we use RPC server to run on remote runtime which don't have a compiler available. The test program compiles the program on local server, upload and run remote RPC server, get the result back to verify correctness. """ from .server import Server from .client import RPCSession, LocalSession, TrackerSession, connect, connect_tracker
"""Lightweight TVM RPC module. RPC enables connect to a remote server, upload and launch functions. This is useful to for cross-compile and remote testing, The compiler stack runs on local server, while we use RPC server to run on remote runtime which don't have a compiler available. The test program compiles the program on local server, upload and run remote RPC server, get the result back to verify correctness. """ from .server import Server from .client import RPCSession, LocalSession, TrackerSession, connect, connect_tracker
en
0.864358
Lightweight TVM RPC module. RPC enables connect to a remote server, upload and launch functions. This is useful to for cross-compile and remote testing, The compiler stack runs on local server, while we use RPC server to run on remote runtime which don't have a compiler available. The test program compiles the program on local server, upload and run remote RPC server, get the result back to verify correctness.
1.966663
2