content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import hassapi as hass
#
# App to turn lights on and off at sunrise and sunset
#
# Args:
#
# on_scene: scene to activate at sunset
# off_scene: scene to activate at sunrise
class OutsideLights(hass.Hass):
def initialize(self):
# Run at Sunrise
self.run_at_sunrise(self.sunrise_cb)
# Run at Sunset
self.run_at_sunset(self.sunset_cb)
def sunrise_cb(self, kwargs):
self.log("OutsideLights: Sunrise Triggered")
self.cancel_timers()
self.turn_on(self.args["off_scene"])
def sunset_cb(self, kwargs):
self.log("OutsideLights: Sunset Triggered")
self.cancel_timers()
self.turn_on(self.args["on_scene"])
def cancel_timers(self):
if "timers" in self.args:
apps = self.args["timers"].split(",")
for app in apps:
App = self.get_app(app)
App.cancel()
| nilq/baby-python | python |
#Hello World python script
print("Hello World")
for i in range(0, 100, 5):
print(i**2)
# y = 'Hello'
# y * 5
# y * 5.0
w = 5 / 3
x = 5.0 / 3
y = 5.0 // 3.0
z = 5 % 3
print(w, x, y, z)
# Variable points to the "object" (unlike C it does not hold the value)
# y = 'Hello'
# z = 'hello'
# print(id(y), id(z))
# a = 'Hello'
# b = 'Hello'
# print(id(a), id(b))
# Boolean (True, non 0 value, False, 0 value)
if ( 5 ):
print("Five")
print("True")
if ( 0 ):
print("Zero")
print("False")
if (not 0):
print("Not Zero")
# combining boolean expressions with: and, or, not
# comparison operators: ==, <=, >=, !=, <, >
print( 4 > 5)
print ( 4 <= 5 )
exitCode = 'exit'
ans = ''
while (str(ans) != exitCode):
ans = input("Please enter your names or exit to exit out of the loop: ")
if (str(ans) != exitCode):
print("Hello", ans)
name = ("Ali", "Abu Ali", "Joe", "Abu Joe")
print(name) | nilq/baby-python | python |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import sys
from destination_google_sheets import DestinationGoogleSheets
if __name__ == "__main__":
DestinationGoogleSheets().run(sys.argv[1:])
| nilq/baby-python | python |
PK
| nilq/baby-python | python |
import uuid
import os
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from .utils import auto_delete_filefields_on_delete
class File(models.Model):
name = models.CharField(max_length=100)
date = models.CharField(max_length=100)
comments = models.CharField(max_length=100)
pdf = models.FileField(upload_to='documents/')
def delete(self, *args, **kwargs):
self.pdf.delete()
super(File, self).delete(*args, **kwargs)
def __str__(self):
return self.title
class BaseModel(models.Model):
"""
Base class for all models;
defines common metadata
"""
class Meta:
abstract = True
ordering = ('-created', ) # better choice for UI
get_latest_by = "-created"
# Primary key
id = models.UUIDField('id', default=uuid.uuid4, primary_key=True, unique=True,
null=False, blank=False, editable=False)
# metadata
created = models.DateTimeField(_('created'), null=True, blank=True, )
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('created by'), null=True, blank=True, related_name='+', on_delete=models.SET_NULL)
updated = models.DateTimeField(_('updated'), null=True, blank=True, )
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('updated by'), null=True, blank=True, related_name='+', on_delete=models.SET_NULL)
def __str__(self):
return str(self.id)
def get_admin_url(self):
return reverse("admin:%s_%s_change" %
(self._meta.app_label, self._meta.model_name), args=(self.id,))
def get_absolute_url(self):
return self.get_admin_url()
def created_display(self):
return format_datetime(self.created)
created_display.short_description = _('Created')
created_display.admin_order_field = 'created'
def updated_display(self):
return format_datetime(self.updated)
updated_display.short_description = _('Updated')
updated_display.admin_order_field = 'updated'
def save(self, *args, **kwargs):
today = timezone.now()
if self.created is None:
self.created = today
self.updated = today
return super(BaseModel, self).save(*args, **kwargs)
| nilq/baby-python | python |
from aiomotorengine import StringField, IntField, BooleanField, FloatField, DateTimeField, ReferenceField, ListField
from xt_base.document.source_docs import InfoAsset
from xt_base.document.base_docs import Project
from dtlib.aio.base_mongo import MyDocument
from dtlib.tornado.account_docs import Organization
from dtlib.tornado.base_docs import OrgDataBaseDocument
class ProjectDataDocument(OrgDataBaseDocument, MyDocument):
"""
项目数据
"""
# 数据归属
project = ReferenceField(reference_document_type=Project) # 测试数据所属的项目
project_name = StringField() # 项目名称,冗余
async def set_project_tag(self, project):
"""
打上项目标记
:type project:Project
:return:
"""
organization = project.organization
self.project = project
self.project_name = project.project_name
self.organization = organization
self.org_name = organization.name
class ProjectFeedBack(ProjectDataDocument):
"""
项目相关的问题反馈
"""
msg = StringField()
# images = ListField() # 图片列表
# todo 语音和视频
label = StringField() # 关于问题的标记
status = IntField() # 处理的状态码
class ServiceStatus(MyDocument):
"""
服务器开放的服务状态
"""
__collection__ = "service_status"
info_asset = ReferenceField(reference_document_type=InfoAsset) # 所属资产,信息资产
port = IntField() # 端口号
protocol = StringField() # 协议名称
status = StringField() # 状态
version = StringField # 版本
class ApiTestData(ProjectDataDocument):
"""
测试数据统计表---因为性能问题,取消使用 2016-09-30
"""
__collection__ = "api_test_data"
was_successful = BooleanField() # 是否是成功的
total = IntField()
failures = IntField()
errors = IntField()
skipped = IntField()
run_time = StringField(max_length=1024)
class ApiTestDataNote(MyDocument):
"""
api测试详细数据,只记录失败和错误---因为性能问题,取消使用 2016-09-30
"""
__collection__ = "api_test_data_note"
apitestdata_id = StringField(max_length=1024)
test_case = StringField(max_length=1024) # 出错测试用例
explain = StringField(max_length=1024) # 目的
status = StringField(max_length=1024) # 测试状态,失败或者错误
note = StringField() # 详细记录
organization = ReferenceField(reference_document_type=Organization) # 数据所属的组织
class UnitTestDataDetail(MyDocument):
"""
api测试详细数据,只记录失败和错误--插入时没有使用
"""
test_case = StringField(max_length=1024) # 出错测试用例
explain = StringField(max_length=1024) # 目的
status = StringField(max_length=1024) # 测试状态,失败或者错误
note = StringField() # 详细记录
class UnitTestData(MyDocument):
"""
测试数据统计表--插入时没有使用,没有使用ORM
"""
__collection__ = "unit_test_data"
pro_version = StringField(max_length=1024) # 项目版本号:1.2.3.4
was_successful = BooleanField() # 是否是成功的
total = IntField()
failures = IntField()
errors = IntField()
skipped = IntField()
run_time = FloatField()
details = ListField(ReferenceField(UnitTestDataDetail))
# 数据归属
project = ReferenceField(reference_document_type=Project) # 测试数据所属的项目
project_name = StringField() # 项目名称,冗余
organization = ReferenceField(reference_document_type=Organization) # 数据所属的组织
class PerformReport(MyDocument):
"""
性能测试报告,已经作废,在bench中有专门的处理的了:2016-09-10
waste
"""
__collection__ = "perform_report"
server_soft_ware = StringField(max_length=2048)
server_host_name = StringField(max_length=2048)
server_port = StringField(max_length=64)
doc_path = StringField(max_length=2048)
doc_length = IntField() # 文档长度,bytes
con_level = IntField() # 并发量
test_time_taken = FloatField() # 消耗时间 seconds
complete_req = IntField() # 完成请求数
failed_req = IntField() # 失败请求数
non_2xx_res = IntField() # 非2xx请求数
total_trans = IntField() # 总传输数据量bytes
html_trans = IntField() # 总html传输数据量bytes
req_per_sec = FloatField() # 每秒请求量
time_per_req = FloatField() # 平均http请求响应时间:ms
time_per_req_across = FloatField() # 所有并发请求量耗时(平均事务响应时间):ms
trans_rate = FloatField() # 每秒传输数据量,Kbytes/sec
organization = ReferenceField(reference_document_type=Organization) # 数据所属的组织
class SafetyTestReport(ProjectDataDocument):
"""
安全测试报告
"""
__collection__ = "safety_test_report"
# project_name = StringField() # 项目名,里面加上版本号,这个并不是具体的内部项目,和其它几种测试数据不同
hack_tool = StringField() # 用于hack的软件名称
total_cnts = IntField() # 总计次数
success_cnts = IntField() # 成功次数
success_rate = FloatField() # 成功率,冗余
time_cycle = FloatField() # 花费时间:s
crack_rate = FloatField() # 破解效率,冗余
mark = StringField() # 描述备注
# organization = ReferenceField(reference_document_type=Organization) # 组织
class ApiReqDelay(MyDocument):
"""测试接口的延时
"""
__collection__ = "api_req_delay"
domain = StringField(max_length=2048) # ms,基准域
path = StringField(max_length=2048) # ms,接口路径及参数
delay = FloatField() # ms,请求时间
http_status = IntField() # http状态值
# 数据归属
project = ReferenceField(reference_document_type=Project)
project_name = StringField() # 项目名称,冗余
organization = ReferenceField(reference_document_type=Organization)
class ExDataRecord(MyDocument):
"""
实验数据的记录表
"""
__collection__ = "ex_data_record"
# --------------数据状态值记录-----------
record_status = StringField(max_length=64) # 数据的状态:reported,filted,experiment
# --------------数据发现和登记期-----------
custom_name = StringField(max_length=256) # 用户名称
captcha_id = StringField(max_length=64)
event_start_time = DateTimeField() # weblog产生开始时间
event_end_time = DateTimeField() # weblog产生结束时间
event_reporter = StringField(max_length=256) # 事件汇报人
event_report_time = DateTimeField() # 事件汇报时间
track_class = StringField(max_length=64)
js_version = StringField(max_length=16)
js_tag_page = StringField(max_length=2048) # 在bitbucket或者tower中的当前版本的修改标记
css_version = StringField(max_length=16)
css_tag_page = StringField(max_length=2048) # 在bitbucket或者tower中的当前版本的修改标记
# --------------数据过滤的采集备案期-----------
data_collection_name = StringField(max_length=256)
producers = StringField(max_length=256)
ex_user = StringField(max_length=256) # 数据收集人
action_time = DateTimeField() # 数据备案时间
# event_time = DateTimeField()
file_name = StringField(max_length=64)
file_path = StringField(max_length=2048) # 实验数据文件所在路径,以FTP的方式来共享
file_size = IntField()
record_cnt = IntField() # 记录的数目
# --------------数据实验期-----------
researcher = StringField(max_length=256) # 数据实验人
researche_time = DateTimeField() # 数据实验时间
research_result = StringField(max_length=10240) # 验证处理结果
# experiment_id= Refer
class CurtainExData(MyDocument):
"""
Curtain项目的测试数据
"""
# answer = ListField()
# track_data = ListField()
action_user = StringField(max_length=256)
class LimitTestData(MyDocument):
"""
测试数据统计表
"""
__collection__ = "limit_test_data"
# id = ObjectId()
was_successful = BooleanField() # 是否是成功的
total = IntField()
failures = IntField()
errors = IntField()
skipped = IntField()
run_time = StringField(max_length=1024)
organization = ReferenceField(reference_document_type=Organization) # 数据所属的组织
class LimitTestDataNote(MyDocument):
"""
api测试详细数据,只记录失败和错误(作废-2016-11-23)
"""
__collection__ = "limit_test_data_note"
limittestdata_id = StringField(max_length=1024)
test_case = StringField(max_length=1024) # 出错测试用例
explain = StringField(max_length=1024) # 目的
status = StringField(max_length=1024) # 测试状态,失败或者错误
note = StringField() # 详细记录
organization = ReferenceField(reference_document_type=Organization) # 数据所属的组织
class UnitPenetrationTest(MyDocument):
"""
渗透测试详细信息
"""
test_case = StringField(max_length=1024) # 测试目的
result = StringField(max_length=1024) # 结果
class PenetrationTestData(ProjectDataDocument):
"""
渗透测试详情
"""
__collection__ = "penetration_test_data"
start_time = StringField()
use_time = FloatField()
note = StringField()
# project = ReferenceField(reference_document_type=Project) # 测试数据所属的项目
# project_name = StringField() # 项目名称,冗余
# organization = ReferenceField(reference_document_type=Organization) # 数据所属的组织
class PenetrationTestDataNote(MyDocument):
"""
渗透测试详情
"""
__collection__ = "penetration_test_data_note"
penetration_id = StringField(max_length=1024)
ip = StringField(max_length=1024)
details = ListField(ReferenceField(UnitPenetrationTest))
# SSHRootEmptyPassword = StringField(max_length=1024)
# RedisEmptyPassword = StringField(max_length=1024)
# MongoEmptyPassword = StringField(max_length=1024)
organization = ReferenceField(reference_document_type=Organization) # 数据所属的组织
class ProxyipTestData(MyDocument):
"""
爆破测试
"""
__collection__ = "proxyip_test_data"
remoteip = StringField(max_length=1024)
originalip = StringField(max_length=1024)
proxyip = StringField(max_length=1024)
organization = ReferenceField(reference_document_type=Organization) # 数据所属的组织
class FeedbackMsg(MyDocument):
"""
feedback
"""
__collection__ = 'feedback_msg'
file_path = StringField() # 文件路径
msg = StringField() # msg
| nilq/baby-python | python |
<caret>a = 1 # surprise!
b = 2
| nilq/baby-python | python |
# VNA_characteristics_classes_creators
from enum import enum
print "U R in VnaEnums" # Flag 4 debug
SweepType = enum(LINEAR=1, LOG=2, SEGM=3, POW=4)
SParameters= enum(S11=1, S12=2, S21=3, S22=4)
CalType = enum(OPEN=1, SHORT=2, THRU=3, FULL_2PORT=4, FULL_1PORT=5, TRL_2PORT=6)
DataFormat = enum(LOG=1, LIN=2, LIN_PHASE=3, PHASE=4, GDELAY=5,
SMITH_LIN_PHASE=6, SMITH_LOG_PHASE=7, SMITH_RE_IM=8, SMITH_R_JX=9, SMITH_G_JB=10)
Direction = enum(LEFT=1, RIGHT=2)
| nilq/baby-python | python |
from mongoengine import (
DateTimeField,
IntField,
EmbeddedDocument,
StringField,
EmbeddedDocumentListField,
BooleanField,
)
from mongoengine import Document
class UserEvent(EmbeddedDocument):
event_id = StringField()
type = StringField()
timestamp = DateTimeField()
state = StringField()
class Survey(Document):
question3_attempts = IntField()
question4_attempts = IntField()
question1_duration = IntField()
question2_duration = IntField()
question3_duration = IntField()
question4_duration = IntField()
question5_duration = IntField()
question3_solved = BooleanField()
question4_solved = BooleanField()
intro_duration = IntField()
tour_duration = IntField()
user_events = EmbeddedDocumentListField(UserEvent)
user_ip = StringField()
| nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.TimePeriodRule import TimePeriodRule
from alipay.aop.api.domain.TimePeriodRule import TimePeriodRule
class VoucherTemplateInfo(object):
def __init__(self):
self._amount = None
self._ceiling_amount = None
self._disable_detail_periods = None
self._discount = None
self._discount_calc_type = None
self._floor_amount = None
self._goods_id = None
self._template_id = None
self._usable_detail_period = None
self._usable_end_time = None
self._usable_start_time = None
self._usable_time_type = None
self._voucher_description = None
self._voucher_name = None
self._voucher_quantity = None
self._voucher_type = None
@property
def amount(self):
return self._amount
@amount.setter
def amount(self, value):
self._amount = value
@property
def ceiling_amount(self):
return self._ceiling_amount
@ceiling_amount.setter
def ceiling_amount(self, value):
self._ceiling_amount = value
@property
def disable_detail_periods(self):
return self._disable_detail_periods
@disable_detail_periods.setter
def disable_detail_periods(self, value):
if isinstance(value, list):
self._disable_detail_periods = list()
for i in value:
if isinstance(i, TimePeriodRule):
self._disable_detail_periods.append(i)
else:
self._disable_detail_periods.append(TimePeriodRule.from_alipay_dict(i))
@property
def discount(self):
return self._discount
@discount.setter
def discount(self, value):
self._discount = value
@property
def discount_calc_type(self):
return self._discount_calc_type
@discount_calc_type.setter
def discount_calc_type(self, value):
self._discount_calc_type = value
@property
def floor_amount(self):
return self._floor_amount
@floor_amount.setter
def floor_amount(self, value):
self._floor_amount = value
@property
def goods_id(self):
return self._goods_id
@goods_id.setter
def goods_id(self, value):
if isinstance(value, list):
self._goods_id = list()
for i in value:
self._goods_id.append(i)
@property
def template_id(self):
return self._template_id
@template_id.setter
def template_id(self, value):
self._template_id = value
@property
def usable_detail_period(self):
return self._usable_detail_period
@usable_detail_period.setter
def usable_detail_period(self, value):
if isinstance(value, list):
self._usable_detail_period = list()
for i in value:
if isinstance(i, TimePeriodRule):
self._usable_detail_period.append(i)
else:
self._usable_detail_period.append(TimePeriodRule.from_alipay_dict(i))
@property
def usable_end_time(self):
return self._usable_end_time
@usable_end_time.setter
def usable_end_time(self, value):
self._usable_end_time = value
@property
def usable_start_time(self):
return self._usable_start_time
@usable_start_time.setter
def usable_start_time(self, value):
self._usable_start_time = value
@property
def usable_time_type(self):
return self._usable_time_type
@usable_time_type.setter
def usable_time_type(self, value):
self._usable_time_type = value
@property
def voucher_description(self):
return self._voucher_description
@voucher_description.setter
def voucher_description(self, value):
self._voucher_description = value
@property
def voucher_name(self):
return self._voucher_name
@voucher_name.setter
def voucher_name(self, value):
self._voucher_name = value
@property
def voucher_quantity(self):
return self._voucher_quantity
@voucher_quantity.setter
def voucher_quantity(self, value):
self._voucher_quantity = value
@property
def voucher_type(self):
return self._voucher_type
@voucher_type.setter
def voucher_type(self, value):
self._voucher_type = value
def to_alipay_dict(self):
params = dict()
if self.amount:
if hasattr(self.amount, 'to_alipay_dict'):
params['amount'] = self.amount.to_alipay_dict()
else:
params['amount'] = self.amount
if self.ceiling_amount:
if hasattr(self.ceiling_amount, 'to_alipay_dict'):
params['ceiling_amount'] = self.ceiling_amount.to_alipay_dict()
else:
params['ceiling_amount'] = self.ceiling_amount
if self.disable_detail_periods:
if isinstance(self.disable_detail_periods, list):
for i in range(0, len(self.disable_detail_periods)):
element = self.disable_detail_periods[i]
if hasattr(element, 'to_alipay_dict'):
self.disable_detail_periods[i] = element.to_alipay_dict()
if hasattr(self.disable_detail_periods, 'to_alipay_dict'):
params['disable_detail_periods'] = self.disable_detail_periods.to_alipay_dict()
else:
params['disable_detail_periods'] = self.disable_detail_periods
if self.discount:
if hasattr(self.discount, 'to_alipay_dict'):
params['discount'] = self.discount.to_alipay_dict()
else:
params['discount'] = self.discount
if self.discount_calc_type:
if hasattr(self.discount_calc_type, 'to_alipay_dict'):
params['discount_calc_type'] = self.discount_calc_type.to_alipay_dict()
else:
params['discount_calc_type'] = self.discount_calc_type
if self.floor_amount:
if hasattr(self.floor_amount, 'to_alipay_dict'):
params['floor_amount'] = self.floor_amount.to_alipay_dict()
else:
params['floor_amount'] = self.floor_amount
if self.goods_id:
if isinstance(self.goods_id, list):
for i in range(0, len(self.goods_id)):
element = self.goods_id[i]
if hasattr(element, 'to_alipay_dict'):
self.goods_id[i] = element.to_alipay_dict()
if hasattr(self.goods_id, 'to_alipay_dict'):
params['goods_id'] = self.goods_id.to_alipay_dict()
else:
params['goods_id'] = self.goods_id
if self.template_id:
if hasattr(self.template_id, 'to_alipay_dict'):
params['template_id'] = self.template_id.to_alipay_dict()
else:
params['template_id'] = self.template_id
if self.usable_detail_period:
if isinstance(self.usable_detail_period, list):
for i in range(0, len(self.usable_detail_period)):
element = self.usable_detail_period[i]
if hasattr(element, 'to_alipay_dict'):
self.usable_detail_period[i] = element.to_alipay_dict()
if hasattr(self.usable_detail_period, 'to_alipay_dict'):
params['usable_detail_period'] = self.usable_detail_period.to_alipay_dict()
else:
params['usable_detail_period'] = self.usable_detail_period
if self.usable_end_time:
if hasattr(self.usable_end_time, 'to_alipay_dict'):
params['usable_end_time'] = self.usable_end_time.to_alipay_dict()
else:
params['usable_end_time'] = self.usable_end_time
if self.usable_start_time:
if hasattr(self.usable_start_time, 'to_alipay_dict'):
params['usable_start_time'] = self.usable_start_time.to_alipay_dict()
else:
params['usable_start_time'] = self.usable_start_time
if self.usable_time_type:
if hasattr(self.usable_time_type, 'to_alipay_dict'):
params['usable_time_type'] = self.usable_time_type.to_alipay_dict()
else:
params['usable_time_type'] = self.usable_time_type
if self.voucher_description:
if hasattr(self.voucher_description, 'to_alipay_dict'):
params['voucher_description'] = self.voucher_description.to_alipay_dict()
else:
params['voucher_description'] = self.voucher_description
if self.voucher_name:
if hasattr(self.voucher_name, 'to_alipay_dict'):
params['voucher_name'] = self.voucher_name.to_alipay_dict()
else:
params['voucher_name'] = self.voucher_name
if self.voucher_quantity:
if hasattr(self.voucher_quantity, 'to_alipay_dict'):
params['voucher_quantity'] = self.voucher_quantity.to_alipay_dict()
else:
params['voucher_quantity'] = self.voucher_quantity
if self.voucher_type:
if hasattr(self.voucher_type, 'to_alipay_dict'):
params['voucher_type'] = self.voucher_type.to_alipay_dict()
else:
params['voucher_type'] = self.voucher_type
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = VoucherTemplateInfo()
if 'amount' in d:
o.amount = d['amount']
if 'ceiling_amount' in d:
o.ceiling_amount = d['ceiling_amount']
if 'disable_detail_periods' in d:
o.disable_detail_periods = d['disable_detail_periods']
if 'discount' in d:
o.discount = d['discount']
if 'discount_calc_type' in d:
o.discount_calc_type = d['discount_calc_type']
if 'floor_amount' in d:
o.floor_amount = d['floor_amount']
if 'goods_id' in d:
o.goods_id = d['goods_id']
if 'template_id' in d:
o.template_id = d['template_id']
if 'usable_detail_period' in d:
o.usable_detail_period = d['usable_detail_period']
if 'usable_end_time' in d:
o.usable_end_time = d['usable_end_time']
if 'usable_start_time' in d:
o.usable_start_time = d['usable_start_time']
if 'usable_time_type' in d:
o.usable_time_type = d['usable_time_type']
if 'voucher_description' in d:
o.voucher_description = d['voucher_description']
if 'voucher_name' in d:
o.voucher_name = d['voucher_name']
if 'voucher_quantity' in d:
o.voucher_quantity = d['voucher_quantity']
if 'voucher_type' in d:
o.voucher_type = d['voucher_type']
return o
| nilq/baby-python | python |
""" Script for generating AE examples.
"""
import argparse
import importlib
import numpy as np
import os
from PIL import Image
import shutil
import sys
import torch
from tqdm import tqdm
from apfv21.attacks.tidr import TIDR
from apfv21.attacks.afv import AFV
from apfv21.utils import img_utils, imagenet_utils
import pdb
ATTACKS_CFG = {
"afv": {
"decay_factor": 1.0,
"prob": 1.0,
"epsilon": 16./255,
"steps": 80,
"step_size": 1./255,
"image_resize": 330,
"dr_weight": 1.0,
"ti_smoothing": True,
"ti_kernel_radius": (20, 3),
"random_start": False,
"train_attention_model": False,
"use_pretrained_foreground": True,
"attention_resize": 256,
"attention_weight_pth": "",
},
"dim": {
"decay_factor": 1.0,
"prob": 0.5,
"epsilon": 16./255,
"steps": 40,
"step_size": 2./255,
"image_resize": 330,
"random_start": False,
},
"tidr": {
"decay_factor": 1.0,
"prob": 0.5,
"epsilon": 16./255,
"steps": 40,
"step_size": 2./255,
"image_resize": 330,
"dr_weight": 0.0,
"random_start": False,
},
"pgd": {
"epsilon": 16/255.,
"k": 40,
"a": 2/255.,
},
"mifgsm": {
"decay_factor": 1.0,
"epsilon": 16./255,
"steps": 40,
"step_size": 2./255
}
}
DR_LAYERS = {
"vgg16": [12],
"resnet152": [5],
"mobilenet_v2": [8]
}
def serialize_config(cfg_dict: dict) -> str:
key_list = list(cfg_dict.keys())
key_list.sort()
ret_str = ""
for key in key_list:
val = cfg_dict[key]
if isinstance(val, float):
val = "{0:.04f}".format(val)
curt_str = "{}_{}".format(key, val)
ret_str = ret_str + curt_str + "_"
ret_str = ret_str.replace('.', 'p')
ret_str = ret_str.replace('/', '_')
ret_str = ret_str.replace('(', '_')
ret_str = ret_str.replace(')', '_')
ret_str = ret_str.replace(',', '_')
ret_str = ret_str.replace(' ', '_')
if len(ret_str) > 255:
ret_str = ret_str[-128:]
return ret_str[:-1]
def generate_adv_example(args):
attack_config = ATTACKS_CFG[args.attack_method]
suffix_str = "{}_{}_{}".format(
args.source_model, args.attack_method, serialize_config(attack_config))
output_folder = os.path.join(args.output_dir, suffix_str)
if os.path.exists(output_folder):
shutil.rmtree(output_folder)
os.mkdir(output_folder)
imgnet_label = imagenet_utils.load_imagenet_label_dict()
source_lib = importlib.import_module(
"apfv21.models." + args.source_model)
source_model_class = getattr(source_lib, args.source_model.upper())
source_model = source_model_class(is_normalize=True)
attack_lib = importlib.import_module(
os.path.join("apfv21.attacks." + args.attack_method))
attacker_class = getattr(attack_lib, args.attack_method.upper())
if args.attack_method == "afv":
afv_config = ATTACKS_CFG["afv"]
from apfv21.attacks.models.attention_model import ForegroundAttentionFCN as ForegroundAttention
# Only one of |use_pretrained_foreground| and |train_attention_model|
# can be turned on at one time.
if afv_config['use_pretrained_foreground']:
assert not afv_config["train_attention_model"]
if afv_config['train_attention_model']:
assert not afv_config["use_pretrained_foreground"]
attention_model = ForegroundAttention(
1, 3,
resize=(afv_config["attention_resize"],
afv_config["attention_resize"]),
use_pretrained_foreground=afv_config['use_pretrained_foreground']
).cuda() # num_classes, feature_channels
if afv_config["train_attention_model"]:
attention_optim = torch.optim.SGD(
attention_model.parameters(), lr=1e-7, momentum=0.9)
lr_scheduler = torch.optim.lr_scheduler.StepLR(
attention_optim, step_size=10, gamma=0.2)
else:
attention_optim = None
if not afv_config['use_pretrained_foreground']:
assert afv_config["attention_weight_pth"] != ""
if afv_config["attention_weight_pth"] != "":
attention_model.load_state_dict(
torch.load(afv_config["attention_weight_pth"]))
attacker = attacker_class(source_model, attention_model,
attention_optim, attack_config=afv_config)
else:
attacker = attacker_class(source_model, attack_config=attack_config)
img_names = os.listdir(args.input_dir)
success_count = 0
total_count = 0
for img_name in tqdm(img_names):
img_name_noext = os.path.splitext(img_name)[0]
img_path = os.path.join(args.input_dir, img_name)
img_ori_var = img_utils.load_img(img_path).cuda()
pred_ori = torch.argmax(source_model(img_ori_var)[1], dim=1)
if isinstance(attacker, TIDR):
img_adv_var = attacker(
img_ori_var, pred_ori, internal=DR_LAYERS[args.source_model])
elif isinstance(attacker, AFV):
img_adv_var, attention_map_first, attention_map_last = attacker(
img_ori_var, pred_ori, internal=DR_LAYERS[args.source_model])
else:
img_adv_var = attacker(img_ori_var, pred_ori)
pred_adv = torch.argmax(source_model(img_adv_var.cuda())[1], dim=1)
output_img = img_utils.save_img(
img_adv_var, os.path.join(output_folder, img_name_noext + ".png"))
# # Visualization for debuging.
# print("Ori: ", img_name, " , ", pred_ori, ":",
# imgnet_label[pred_ori.cpu().numpy()[0]])
# print("Adv: ", img_name, " , ", pred_adv, ":",
# imgnet_label[pred_adv.cpu().numpy()[0]])
# attention_img_first = Image.fromarray(
# (attention_map_first.detach().cpu().numpy()[0, 0] * 255).astype(np.uint8))
# attention_img_first.save("./temp_attention_first.png")
# attention_img_last = Image.fromarray(
# (attention_map_last.detach().cpu().numpy()[0, 0] * 255).astype(np.uint8))
# attention_img_last.save("./temp_attention_last.png")
# img_utils.save_img(img_adv_var, "./temp_adv.png")
if imgnet_label[pred_ori.cpu().numpy()[0]] != \
imgnet_label[pred_adv.cpu().numpy()[0]]:
success_count += 1
total_count += 1
if total_count % 100 == 0 and args.attack_method == "afv" \
and afv_config["train_attention_model"]:
print("Saving attention model...")
torch.save(
attention_model.state_dict(),
"./weights/attention_model_weights_{}.pth".format(total_count))
lr_scheduler.step()
if args.attack_method == "afv" and afv_config["train_attention_model"]:
print("Saving attention model...")
torch.save(
attention_model.state_dict(),
"./weights/attention_model_weights_{}.pth".format(total_count))
success_rate = float(success_count) / float(total_count)
print("Success rate: ", success_rate)
print("{} over {}".format(success_count, total_count))
return
def parse_args(args):
parser = argparse.ArgumentParser(description="PyTorch AE generation.")
parser.add_argument('--source_model',,
default="vgg16", type=str)
parser.add_argument('--attack_method',,
default="afv", type=str)
parser.add_argument('--input_dir', default="sample_images/", type=str)
parser.add_argument('--output_dir', default="outputs/", type=str)
return parser.parse_args(args)
def main(args=None):
# parse arguments
if args is None:
args = sys.argv[1:]
args = parse_args(args)
args_dic = vars(args)
generate_adv_example(args)
if __name__ == "__main__":
main() | nilq/baby-python | python |
import csv
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
pd.options.display.max_columns = None
pd.options.display.max_rows = None
# Load the pre-processsed dataset
df = pd.read_hdf('pre-processed.h5')
# Shuffling the dataset
df = df.sample(frac=1).reset_index(drop=True)
# Splitting the first 85% of the dataset for train set
train = df[:round(len(df)*0.85)]
# Min-max normalization of the train set
train_norm = (train - train.min())/(train.max() - train.min())
train_min = train.min()
train_max = train.max()
# Save the train set
train_norm.to_hdf("train_norm.h5", key='w')
# Save train set min and max values for back normalization of the inference cases
train_min.to_hdf("train_min.h5", key='w')
train_max.to_hdf("train_max.h5", key='w')
# Splitting and normalizing the validation set
val = df[round(len(df)*0.85):round(len(df)*0.95)]
val.to_hdf("val.h5", key='w')
val_norm = (val - train.min()) / (train.max() - train.min())
# Save the validation set
val_norm.to_hdf("val_norm.h5", key='w')
# Splitting and normalizing the validation set
test = df[round(len(df)*0.95):]
test.to_hdf("test.h5", key='w')
test_norm = (test - train.min()) / (train.max() - train.min())
# Save the test set
test_norm.to_hdf("test_norm.h5", key='w')
| nilq/baby-python | python |
import matplotlib.pyplot as plt
import cv2 as cv
from color_component import get_channel, remove_channel
img = cv.imread('color_img.png')
plt.subplot(3, 1, 1)
imgRGB = img[:, :, ::-1]
plt.imshow(imgRGB)
ch = 1
imgSingleChannel = get_channel(img, ch)
imgRGB = cv.cvtColor(imgSingleChannel, cv.COLOR_BGR2RGB)
plt.subplot(3, 1, 2)
plt.imshow(imgRGB)
imgChannelRemoved = remove_channel(img, ch)
imgRGB = imgChannelRemoved[:, :, ::-1]
plt.imshow(imgRGB)
plt.show()
| nilq/baby-python | python |
# Generated by Django 3.0 on 2020-01-06 16:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('content', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Library',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('platform', models.CharField(max_length=255, null=True)),
],
),
migrations.CreateModel(
name='Playlist',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, null=True, verbose_name='Name')),
('is_public', models.BooleanField(blank=True, default=False)),
('date_created', models.DateField(auto_now_add=True)),
],
options={
'verbose_name': 'playlist',
'verbose_name_plural': 'playlists',
},
),
migrations.CreateModel(
name='PlaylistSong',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_saved', models.DateTimeField(auto_now_add=True)),
('playlist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='playlist_to_song', to='music.Playlist')),
('song', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='song_to_playlist', to='content.Song')),
],
options={
'verbose_name': 'playlist song',
'verbose_name_plural': 'playlist songs',
},
),
migrations.AddField(
model_name='playlist',
name='songs',
field=models.ManyToManyField(related_name='playlist_songs', through='music.PlaylistSong', to='content.Song'),
),
migrations.AddField(
model_name='playlist',
name='user',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL),
),
migrations.CreateModel(
name='LibrarySong',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_saved', models.DateTimeField(auto_now_add=True)),
('library', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='library_to_song', to='music.Library')),
('song', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='song_to_library', to='content.Song')),
],
options={
'verbose_name': 'library song',
'verbose_name_plural': 'library songs',
},
),
migrations.AddField(
model_name='library',
name='songs',
field=models.ManyToManyField(related_name='library_songs', through='music.LibrarySong', to='content.Song'),
),
migrations.AddField(
model_name='library',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
| nilq/baby-python | python |
from django.shortcuts import render
from django.http import HttpResponse
from .models import Pizza
def index(request):
messages = ['Welcome Pizza Lovers', 'Our currently available Pizzas are:']
for pizza in Pizza.objects.all():
messages.append(str(pizza))
for topping in pizza.topping_set.all():
messages.append('* Topping: %s' % str(topping.topping_name))
return HttpResponse('<br>'.join(messages))
def pizza_info(request, pizza_id):
try:
pizza = Pizza.objects.get(pk=pizza_id)
except:
return HttpResponse('boo hoo')
return HttpResponse('The pizza with id %s is %s' % (pizza_id, pizza))
| nilq/baby-python | python |
import time
import traceback
import logging
import os
import matplotlib.pyplot as plt
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
from pycqed.analysis import analysis_toolbox as a_tools
class AnalysisDaemon:
"""
AnalysisDaemon is a class that allow to process analysis in a
separate python kernel to allow measurements to run in parallel
to the analysis.
The Daemon can either be started:
- in a separate ipython notebook using: `AnalysisDaemon(start=True)`.
Note that the a_tools.datadir should be set before calling the daemon
or passed with the watchdir argument
- via the commandline by calling `analysis_daemon.py` with possible
additional arguments (see `analysis_daemon.py --help`)
- with the start_analysis_daemon.bat script located in pycqedscripts/scripts
(Windows only)
"""
def __init__(self, t_start=None, start=True, watchdir=None):
"""
Initialize AnalysisDaemon
Args:
t_start (str): timestamp from which to start observing the data
directory. If None, defaults to now.
start (bool): whether or not to start the daemon
watchdir (str): directory which the Daemon should look at.
Defaults to analusis_toolbox.datadir.
"""
self.t_start = t_start
self.last_ts = None
self.poll_interval = 10 # seconds
self.errs = []
self.job_errs = []
if watchdir is not None:
a_tools.datadir = watchdir
if start:
self.start()
def start(self):
"""
Starts the AnalysisDaemon
Returns:
"""
self.last_ts = a_tools.latest_data(older_than=self.t_start,
return_path=False,
return_timestamp=True, n_matches=1)[0]
self.run()
def run(self):
try:
while (True):
if not self.check_job():
for i in range(self.poll_interval):
time.sleep(1)
except KeyboardInterrupt as e:
pass
except Exception as e:
log.error(e)
self.errs.append(traceback.format_exc())
self.run()
def check_job(self):
"""
Checks whether new jobs have been found and processes them
Returns: True if a job was found and processed (done or failed),
False otherwise.
"""
try:
timestamps, folders = a_tools.latest_data(newer_than=self.last_ts,
raise_exc=False,
return_timestamp=True,
n_matches=1000)
except ValueError as e:
return # could not find any timestamps matching criteria
log.info(f"Searching jobs in: {timestamps[0]} ... {timestamps[-1]}.")
found_jobs = False
for folder, ts in zip(folders, timestamps):
jobs_in_folder = []
for file in os.listdir(folder):
if file.endswith(".job"):
jobs_in_folder.append(os.path.join(folder, file))
if len(jobs_in_folder) > 0:
log.info(f"Found {len(jobs_in_folder)} job(s) in {ts}")
found_jobs = True
for filename in jobs_in_folder:
if os.path.isfile(filename):
time.sleep(1) # wait to make sure that the file is fully written
job = self.read_job(filename)
errl = len(self.job_errs)
os.rename(filename, filename + '.running')
self.run_job(job)
time.sleep(1) # wait to make sure that files are written
t = self.get_datetimestamp()
if os.path.isfile(filename):
os.rename(filename,
f"{filename}_{t}.loop_detected")
log.warning(f'A loop was detected! Job {filename} '
f'tries to delegate plotting.')
if errl == len(self.job_errs):
os.rename(filename + '.running',
f"{filename}_{t}.done")
else:
new_filename = f"{filename}_{t}.failed"
os.rename(filename + '.running', new_filename)
new_errors = self.job_errs[errl:]
self.write_to_job(new_filename, new_errors)
self.last_ts = ts
if not found_jobs:
log.info(f"No new job found.")
return False
else:
return True
@staticmethod
def get_datetimestamp():
return time.strftime('%Y%m%d_%H%M%S', time.localtime())
@staticmethod
def read_job(filename):
job_file = open(filename, 'r')
job = "".join(job_file.readlines())
job_file.close()
return job
@staticmethod
def write_to_job(filename, new_lines):
job_file = open(filename, 'a+')
job_file.write("\n\n")
job_file.write("".join(new_lines))
job_file.close()
def run_job(self, job):
try:
exec(job)
plt.close('all')
except Exception as e:
log.error(f"Error in job: {job}:\n{e}")
self.job_errs.append(traceback.format_exc())
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--data-dir", help="Watch directory")
parser.add_argument("--t-start", help="Starting watch time formatted as a "
"timestamp YYYYmmdd_hhMMss or string"
" 'now' (default).")
args = parser.parse_args()
if args.data_dir is not None:
a_tools.datadir = args.data_dir
if args.t_start == "now":
args.t_start = None
ad = AnalysisDaemon(t_start=args.t_start)
| nilq/baby-python | python |
# Copyright (c) 2015 Scott Christensen
#
# This file is part of htpython modified from condorpy
#
# condorpy/htpython is free software: you can redistribute it and/or modify it under
# the terms of the BSD 2-Clause License. A copy of the BSD 2-Clause License
# should have be distributed with this file.
from collections import OrderedDict
from copy import deepcopy
import pickle, os
class Templates(object):
"""
"""
def __init__(self):
pass
def __getattribute__(self, item):
"""
:param item:
:return:
"""
attr = object.__getattribute__(self, item)
if item in object.__getattribute__(self, '__dict__'):
attr = deepcopy(attr)
return attr
def save(self, file_name=None):
if not file_name:
file_name = os.path.join(os.path.dirname(__file__), 'condorpy-saved-templates')
with open(file_name, 'wb') as file:
pickle.dump(self.__dict__, file, protocol=0)
def load(self, file_name=None):
if not file_name:
file_name = os.path.join(os.path.dirname(__file__), 'condorpy-saved-templates')
if not os.path.isfile(file_name):
return
#TODO: raise an error? log warning?
with open(file_name, 'rb') as file:
pdict = pickle.load(file)
self.__dict__.update(pdict)
def reset(self):
self.__dict__ = dict()
@property
def base(self):
base = OrderedDict()
base['job_name'] = ''
base['universe'] = ''
base['executable'] = ''
base['arguments'] = ''
base['initialdir'] = '$(job_name)'
base['logdir'] = 'logs'
base['log'] = '$(logdir)/$(job_name).$(cluster).log'
base['output'] = '$(logdir)/$(job_name).$(cluster).$(process).out'
base['error'] = '$(logdir)/$(job_name).$(cluster).$(process).err'
return base
@property
def vanilla_base(self):
vanilla_base = self.base
vanilla_base['universe'] = 'vanilla'
return vanilla_base
@property
def vanilla_transfer_files(self):
vanilla_transfer_files = self.vanilla_base
vanilla_transfer_files['transfer_executable'] = 'TRUE'
vanilla_transfer_files['should_transfer_files'] = 'YES'
vanilla_transfer_files['when_to_transfer_output'] = 'ON_EXIT_OR_EVICT'
vanilla_transfer_files['transfer_input_files'] = ''
vanilla_transfer_files['transfer_output_files'] = ''
return vanilla_transfer_files
@property
def vanilla_nfs(self):
vanilla_nfs = self.vanilla_base
return vanilla_nfs | nilq/baby-python | python |
#!/usr/bin/env python
# landScraper.py -v 1.7
# currently designed for python 3.10.2
# Author- David Sullivan
#
# Credit to Michael Shilov from scraping.pro/simple-email-crawler-python for the base for this code
#
# As a reminder, web scraping for the purpose of SPAM or hacking is illegal. This tool has been provided for
# legitimate testers to validate the information provided on a website that they have explicit legal right to
# scrape.
#
# Dependencies:
# -pip install requests
# -pip install bs4
#
# Revision 1.0 - 02/12/2018- Initial creation of script
# Revision 1.1 - 04/06/2018- Added in some more error handling
# Revision 1.2 - 04/18/2018- Added in ability to blacklist words in links (to avoid looping), and the ability to
# process sub-domains
# Revision 1.3 - 08/07/2018- Added in functionality to write to output as it runs, in case the script breaks
# Revision 1.4 - 01/16/2019- Added a timeout for stale requests, suppression for error messages related to SSL
# Revision 1.5 - 02/13/2019- Renamed tool to landScraper, implemented argparse, broke out functions, implemented
# automated cleanup if the program is terminated using keystrokes
# Revision 1.6 - 10/20/2021- Added a User-Agent header to get around 403 errors
# Revision 1.7 - 03/15/2022- Added 'touch' command to create output file if it doesn't exist to make it forward
# compatible with newer versions of python, updated bad link words
import re
import requests.exceptions
import argparse
from collections import deque
from urllib.parse import urlsplit
from bs4 import BeautifulSoup
# disable insecure request warning
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def manual_url():
# set starting url
starting_url = str(
input(r'Put in the full URL of where you want to start crawling (ex: http://test.local/local): '))
return starting_url
def manual_email():
# set email domain
email_domain = str(input(r'Put in the email domain you are looking for (ex: @test.local): '))
return email_domain
def manual_output():
# set output file
outfile = str(input(r'Path and filename for results output (ex: /home/test/crawled_emails.txt): '))
return outfile
def scrape(starting_url, domain_name, email_domain, outfile):
# a queue of urls to be crawled
global response
new_urls = deque([starting_url])
# a set of urls that we have already crawled
processed_urls = set()
# create an empty list for the emails variable
emails = list()
# don't include links with the following (to avoid loops)
bad_link_words = ['##', '.pdf', '.mp3', '.mp4', '.mpg', '.wav', '.jpg', '.png', '.gif', '#', '../']
# process to handle checking the bad_link_words list
def avoid_loops(links, words):
return any(word in links for word in words)
# process urls one by one until we exhaust the queue
while len(new_urls):
# noinspection PyBroadException
try:
# move next url from the queue to the set of processed urls
url = new_urls.popleft()
processed_urls.add(url)
# extract base url to resolve relative links
parts = urlsplit(url)
base_url = "{0.scheme}://{0.netloc}".format(parts)
path = url[:url.rfind('/') + 1] if '/' in parts.path else url
# get url's content
print("Processing %s" % url)
try:
response = requests.get(url, headers={'User-Agent': 'curl/7.72.0'}, verify=False, timeout=10)
except (requests.exceptions.MissingSchema, requests.exceptions.ConnectionError):
# ignore pages with errors
continue
except KeyboardInterrupt:
cleanup_list(outfile, emails, email_domain)
# extract all email addresses
new_emails = set(re.findall(r"[a-z0-9.\-+_]+@[a-z0-9.\-+_]+\.[a-z]+", response.text, re.I))
# write them to output file
f = open(outfile, 'a+')
for email in new_emails:
f.write(email + '\n')
f.close()
# noinspection PyBroadException
try:
# create a beautiful soup for the html document
soup = BeautifulSoup(response.text, "html.parser")
# find and process all the anchors in the document
for anchor in soup.find_all("a"):
# extract link url from the anchor
link = anchor.attrs["href"] if "href" in anchor.attrs else ''
# resolve relative links
if link.startswith('/'):
link = base_url + link
elif not link.startswith('http'):
link = path + link
# add the new url to the queue if it was not enqueued nor processed yet
if not (link in new_urls or link in processed_urls):
# only add the new url if not in the bad_link_words list
if not avoid_loops(link, bad_link_words):
# only add urls that are part of the domain_name
if domain_name in link:
new_urls.append(link)
except KeyboardInterrupt:
cleanup_list(outfile, emails, email_domain)
except Exception:
# if the URL is too long this can error out
continue
except KeyboardInterrupt:
cleanup_list(outfile, emails, email_domain)
except Exception:
# if some error occurs
continue
return emails
def cleanup_list(outfile, emails, email_domain):
# cleaning up output
print("Cleaning up output file")
# open the output file and import all the crawled emails
f = open(outfile, 'r')
for email in f:
email = email.replace('\n', '')
emails.append(email)
f.close()
# remove duplicates from emails
emails = set([email.lower() for email in emails])
# create a list for final_emails
final_emails = list()
# remove emails not in the set domain
for email in emails:
if email_domain in email:
final_emails.append(email)
# write output
f = open(outfile, 'w')
for email in final_emails:
f.write(email + '\n')
f.close()
# quit the script
print("Cleanup finished. Results can be found in %s" % outfile)
quit()
def main():
# parse input for variables
parser = argparse.ArgumentParser(description='LandScraper- Domain Email Scraper')
parser.add_argument('-u', '--url', help='Starting URL')
parser.add_argument('-d', '--domain', help='Domain name (if different from starting URL')
parser.add_argument('-e', '--email', help='Email Domain')
parser.add_argument('-o', '--output', help='Output file name')
args = parser.parse_args()
# select url
if args.url is not None:
url = args.url
else:
url = manual_url()
# select domain
if args.domain is not None:
domain = args.domain
else:
domain = url
# select email domain
if args.email is not None:
email = args.email
else:
email = manual_email()
# select output
if args.output is not None:
outfile = args.output
else:
outfile = manual_output()
# create outfile if it does not exist
from pathlib import Path
myfile = Path(outfile)
myfile.touch(exist_ok=True)
# run the program
emails = scrape(url, domain, email, outfile)
# run cleanup on the output file
cleanup_list(outfile, emails, email)
main()
| nilq/baby-python | python |
"""
Dailymotion OAuth2 support.
This adds support for Dailymotion OAuth service. An application must
be registered first on dailymotion and the settings DAILYMOTION_CONSUMER_KEY
and DAILYMOTION_CONSUMER_SECRET must be defined with the corresponding
values.
User screen name is used to generate username.
By default account id is stored in extra_data field, check OAuthBackend
class for details on how to extend it.
"""
from urllib2 import HTTPError
try:
import json as simplejson
except ImportError:
try:
import simplejson
except ImportError:
from django.utils import simplejson
from social_auth.utils import dsa_urlopen
from social_auth.backends import BaseOAuth2
from social_auth.backends import SocialAuthBackend
from social_auth.exceptions import AuthCanceled
# Dailymotion configuration
DAILYMOTION_SERVER = 'api.dailymotion.com'
DAILYMOTION_REQUEST_TOKEN_URL = 'https://%s/oauth/token' % DAILYMOTION_SERVER
DAILYMOTION_ACCESS_TOKEN_URL = 'https://%s/oauth/token' % DAILYMOTION_SERVER
# Note: oauth/authorize forces the user to authorize every time.
# oauth/authenticate uses their previous selection, barring revocation.
DAILYMOTION_AUTHORIZATION_URL = 'https://%s/oauth/authorize' % \
DAILYMOTION_SERVER
DAILYMOTION_CHECK_AUTH = 'https://%s/me/?access_token=' % DAILYMOTION_SERVER
class DailymotionBackend(SocialAuthBackend):
"""Dailymotion OAuth authentication backend"""
name = 'dailymotion'
EXTRA_DATA = [('id', 'id')]
def get_user_id(self, details, response):
"""Use dailymotion username as unique id"""
return details['username']
def get_user_details(self, response):
return {'username': response['screenname']}
class DailymotionAuth(BaseOAuth2):
"""Dailymotion OAuth2 authentication mechanism"""
AUTHORIZATION_URL = DAILYMOTION_AUTHORIZATION_URL
REQUEST_TOKEN_URL = DAILYMOTION_REQUEST_TOKEN_URL
ACCESS_TOKEN_URL = DAILYMOTION_ACCESS_TOKEN_URL
AUTH_BACKEND = DailymotionBackend
SETTINGS_KEY_NAME = 'DAILYMOTION_OAUTH2_KEY'
SETTINGS_SECRET_NAME = 'DAILYMOTION_OAUTH2_SECRET'
def user_data(self, access_token, *args, **kwargs):
"""Return user data provided"""
try:
data = dsa_urlopen(DAILYMOTION_CHECK_AUTH + access_token).read()
return simplejson.loads(data)
except (ValueError, HTTPError):
return None
def auth_complete(self, *args, **kwargs):
"""Completes login process, must return user instance"""
if 'denied' in self.data:
raise AuthCanceled(self)
else:
return super(DailymotionAuth, self).auth_complete(*args, **kwargs)
def oauth_request(self, token, url, extra_params=None):
extra_params = extra_params or {}
return extra_params
# Backend definition
BACKENDS = {
'dailymotion': DailymotionAuth,
}
| nilq/baby-python | python |
import sys
import urllib2
import zlib
import time
import re
import xml.dom.pulldom
import operator
import codecs
from optparse import OptionParser
nDataBytes, nRawBytes, nRecoveries, maxRecoveries = 0, 0, 0, 3
def getFile(serverString, command, verbose=1, sleepTime=0):
global nRecoveries, nDataBytes, nRawBytes
if sleepTime:
time.sleep(sleepTime)
remoteAddr = serverString + '?verb=%s' % command
if verbose:
print "\r", "Fetching set list ...'%s'" % remoteAddr[-90:]
headers = {'User-Agent': 'OAIHarvester/2.0', 'Accept': 'text/html', 'Accept-Encoding': 'compress, deflate'}
try:
remoteData = urllib2.urlopen(remoteAddr).read()
except urllib2.HTTPError, exValue:
if exValue.code == 503:
retryWait = int(exValue.hdrs.get("Retry-After", "-1"))
if retryWait < 0:
return None
print 'Waiting %d seconds' % retryWait
return getFile(serverString, command, 0, retryWait)
print exValue
if nRecoveries < maxRecoveries:
nRecoveries += 1
return getFile(serverString, command, 1, 60)
return
nRawBytes += len(remoteData)
try:
remoteData = zlib.decompressobj().decompress(remoteData)
except:
pass
nDataBytes += len(remoteData)
mo = re.search('<error *code=\"([^"]*)">(.*)</error>', remoteData)
if mo:
print "OAIERROR code=%s '%s'" % (mo.group(1), mo.group(2))
else:
return remoteData
if __name__ == "__main__":
serverString = 'http://fsu.digital.flvc.org/oai2'
outFileName = 'assets/setSpec.xml'
print "Writing records to %s from %s" % (outFileName, serverString)
ofile = codecs.lookup('utf-8')[-1](file(outFileName, 'wb'))
ofile.write('<repository xmlns:oai_dc="http://www.openarichives.org/OAI/2.0/oai_dc/" \
xmlns:dc="http://purl.org/dc/elements/1.1/" \
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n')
data = getFile(serverString, 'ListSets')
recordCount = 0
while data:
events = xml.dom.pulldom.parseString(data)
for (event, node) in events:
if event == "START_ELEMENT" and node.tagName == 'set':
events.expandNode(node)
node.writexml(ofile)
recordCount += 1
mo = re.search('resumptionToken[^>]*>(.*)</resumptionToken>', data)
if not mo:
break
data = getFile(serverString, "ListSets&resumptionToken=%s" % mo.group(1))
ofile.write('\n</repository>\n'), ofile.close()
print "\nRead %d bytes (%.2f compression)" % (nDataBytes, float(nDataBytes) / nRawBytes)
print "Wrote out %d records" % recordCount
| nilq/baby-python | python |
from WonderPy.core.wwConstants import WWRobotConstants
from .wwSensorBase import WWSensorBase
_rcv = WWRobotConstants.RobotComponentValues
_expected_json_fields = (
_rcv.WW_SENSOR_VALUE_DISTANCE,
)
class WWSensorWheel(WWSensorBase):
def __init__(self, robot):
super(WWSensorWheel, self).__init__(robot)
self._distance_raw = None
self._distance_reference = None
@property
def distance(self):
return self._distance_raw - self._distance_reference
def _important_field_names(self):
return 'distance',
def parse(self, single_component_dictionary):
if not self.check_fields_exist(single_component_dictionary, _expected_json_fields):
return
# todo: handle wrap at about +/-9000cm.
self._distance_raw = single_component_dictionary[_rcv.WW_SENSOR_VALUE_DISTANCE]
if self._distance_reference is None:
self.tare()
self._valid = True
def tare(self):
"""
Reset the reference distance
"""
self._distance_reference = self._distance_raw
| nilq/baby-python | python |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import annotations # isort:skip
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
from os import chdir
from subprocess import run
# Bokeh imports
from bokeh._testing.util.project import TOP_PATH, ls_files
#-----------------------------------------------------------------------------
# Tests
#-----------------------------------------------------------------------------
def test_flake8_bokeh() -> None:
flake8("bokeh")
def test_flake8_examples() -> None:
flake8("examples")
def test_flake8_release() -> None:
flake8("release")
def test_flake8_sphinx() -> None:
flake8("sphinx")
def test_flake8_tests() -> None:
flake8("tests")
def test_flake8_typings() -> None:
flake8("typings")
#-----------------------------------------------------------------------------
# Support
#-----------------------------------------------------------------------------
def flake8(dir: str) -> None:
''' Assures that the Python codebase passes configured Flake8 checks.
'''
chdir(TOP_PATH)
proc = run(["flake8", *ls_files(f"{dir}/**.py", f"{dir}/**.pyi")], capture_output=True)
assert proc.returncode == 0, f"Flake8 issues:\n{proc.stdout.decode('utf-8')}"
| nilq/baby-python | python |
from ..check import Check
from ..exceptions import CheckError
def is_number(check_obj):
try:
assert isinstance(check_obj._val, check_obj.NUMERIC_TYPES)
return check_obj
except AssertionError:
raise CheckError('{} is not a number'.format(check_obj._val))
def is_not_number(check_obj):
try:
assert not isinstance(check_obj._val, check_obj.NUMERIC_TYPES)
return check_obj
except AssertionError:
raise CheckError('{} is a number'.format(check_obj._val))
def is_integer(check_obj):
try:
assert isinstance(check_obj._val, int)
return check_obj
except AssertionError:
raise CheckError('{} is not integer'.format(check_obj._val))
def is_not_integer(check_obj):
try:
assert not isinstance(check_obj._val, int)
return check_obj
except AssertionError:
raise CheckError('{} is integer'.format(check_obj._val))
def is_float(check_obj):
try:
assert isinstance(check_obj._val, float)
return check_obj
except AssertionError:
raise CheckError('{} is not float'.format(check_obj._val))
def is_not_float(check_obj):
try:
assert not isinstance(check_obj._val, float)
return check_obj
except AssertionError:
raise CheckError('{} is float'.format(check_obj._val))
def is_real(check_obj):
check_obj.is_number()
try:
assert not isinstance(check_obj._val, complex)
return check_obj
except AssertionError:
raise CheckError('{} is not real'.format(check_obj._val))
def is_not_real(check_obj):
check_obj.is_number()
try:
assert isinstance(check_obj._val, complex)
return check_obj
except AssertionError:
raise CheckError('{} is real'.format(check_obj._val))
def is_complex(check_obj):
try:
assert isinstance(check_obj._val, complex)
return check_obj
except AssertionError:
raise CheckError('{} is not complex'.format(check_obj._val))
def is_not_complex(check_obj):
try:
assert not isinstance(check_obj._val, complex)
return check_obj
except AssertionError:
raise CheckError('{} is complex'.format(check_obj._val))
def is_positive(check_obj):
check_obj.is_real()
try:
assert float(check_obj._val) > 0.
return check_obj
except AssertionError:
raise CheckError('{} is zero or negative'.format(check_obj._val))
def is_not_positive(check_obj):
check_obj.is_real()
try:
assert float(check_obj._val) <= 0
return check_obj
except AssertionError:
raise CheckError('{} is positive'.format(check_obj._val))
def is_negative(check_obj):
check_obj.is_real()
try:
assert float(check_obj._val) < 0.
return check_obj
except AssertionError:
raise CheckError('{} is zero or positive'.format(check_obj._val))
def is_not_negative(check_obj):
check_obj.is_real()
try:
assert float(check_obj._val) >= 0
return check_obj
except AssertionError:
raise CheckError('{} is negative'.format(check_obj._val))
def is_zero(check_obj):
check_obj.is_real()
try:
assert float(check_obj._val) == 0.
return check_obj
except AssertionError:
raise CheckError('{} is non-zero'.format(check_obj._val))
def is_not_zero(check_obj):
check_obj.is_real()
try:
assert float(check_obj._val) != 0.
return check_obj
except AssertionError:
raise CheckError('{} is non-zero'.format(check_obj._val))
def is_at_least(check_obj, lower):
check_obj.is_real()
Check(lower).is_real()
try:
assert float(check_obj._val) >= float(lower)
return check_obj
except AssertionError:
raise CheckError('{} is smaller than {}'.format(check_obj._val, lower))
def is_at_most(check_obj, upper):
check_obj.is_real()
Check(upper).is_real()
try:
assert float(check_obj._val) <= float(upper)
return check_obj
except AssertionError:
raise CheckError('{} is bigger than {}'.format(check_obj._val, upper))
def is_between(check_obj, lower, upper):
check_obj.is_real()
Check(lower).is_real()
Check(upper).is_real()
check_obj.is_at_least(lower).is_at_most(upper)
return check_obj
def is_not_between(check_obj, lower, upper):
check_obj.is_real()
Check(lower).is_real()
Check(upper).is_real()
try:
assert float(check_obj._val) <= lower or float(check_obj._val) >= upper
return check_obj
except AssertionError:
raise CheckError('{} is between {} and {}'.format(check_obj._val, lower, upper)) | nilq/baby-python | python |
import os
import json
import time
import torch
from torch import optim
import models
from utils import reduce_lr, stop_early, since
_optimizer_kinds = {'Adam': optim.Adam,
'SGD': optim.SGD}
class SimpleLoader:
def initialize_args(self, **kwargs):
for key, val in kwargs.items():
self.params_dict[key] = val
for key, val in self.params_dict.items():
setattr(self, key, val)
class SimpleTrainingLoop(SimpleLoader):
def __init__(self, model, device, **kwargs):
self.params_dict = {
'optimizer': 'Adam',
'learning_rate': 1e-3,
'num_epochs': 40,
'verbose': True,
'use_early_stopping': True,
'early_stopping_loss': 0,
'cooldown': 0,
'num_epochs_early_stopping': 10,
'delta_early_stopping': 1e-4,
'learning_rate_lower_bound': 1e-6,
'learning_rate_scale': 0.5,
'num_epochs_reduce_lr': 4,
'num_epochs_cooldown': 8,
'use_model_checkpoint': True,
'model_checkpoint_period': 1,
'start_epoch': 0,
'gradient_clip': None,
'warmup_initial_scale': 0.2,
'warmup_num_epochs': 2,
'loss_weights': [1, 1, 0.2],
}
super(SimpleTrainingLoop, self).initialize_args(**kwargs)
self.device = device
if isinstance(model, str):
# In this case it's just a path to a previously stored model
modelsubdirs = sorted([int(_) for _ in os.listdir(model) if _.isnumeric()], reverse=True)
if modelsubdirs:
for modelsubdir in modelsubdirs:
modelsubdir_str = str(modelsubdir)
modeldir = os.path.join(model, modelsubdir_str)
if os.path.isfile(os.path.join(modeldir, 'loss_history.json')):
self.load_from_dir(modeldir)
print("Resuming from epoch {}".format(modelsubdir))
break
else:
raise FileNotFoundError(os.path.join(model, '{{nnetdir}}', 'loss_history.json'))
else:
raise FileNotFoundError(os.path.join(model, '{{nnetdir}}'))
else:
self.model = model
_opt = _optimizer_kinds[self.params_dict['optimizer']]
self.optimizer = _opt(self.model.parameters(),
lr=self.params_dict['learning_rate'])
self.loss_history = {}
def train_one_epoch(self, criterion, data_loaders, phases=('train', 'test')):
epoch_beg = time.time()
self.model.to(self.device)
dataset_sizes = {x: len(data_loaders[x].dataset)
for x in phases}
batch_sizes = {x: data_loaders[x].batch_size for x in phases}
try:
m = (1 - self.params_dict['warmup_initial_scale'])/(self.params_dict['warmup_num_epochs'] - 1)
c = self.params_dict['warmup_initial_scale']
except ZeroDivisionError:
m = 1
c = 0
lr_scale = m * self.elapsed_epochs() + c
if self.elapsed_epochs() < self.params_dict['warmup_num_epochs']:
self.optimizer.param_groups[0]['lr'] *= lr_scale
self.loss_history[str(self.elapsed_epochs())] = {}
print('Epoch {}/{} - lr={}'.format(self.elapsed_epochs(), self.params_dict['num_epochs'],
self.optimizer.param_groups[0]['lr'])
)
for phase in phases:
print('\t{} '.format(phase.title()), end='')
phase_beg = time.time()
if phase == 'train':
self.model.train()
else:
self.model.eval()
running_loss = 0.
running_dist_sum = 0.
running_count = 0.
running_count_per_class = torch.zeros(self.model.num_centroids)
for batch_no, batch_data in enumerate(data_loaders[phase]):
self.optimizer.zero_grad()
data_batch, label_batch, speaker_ids = batch_data
data_batch = data_batch.to(self.device)
label_batch = label_batch.to(self.device)
speaker_ids = speaker_ids.to(self.device)
with torch.set_grad_enabled(phase == 'train'):
encoded = self.model.encoder(data_batch).contiguous()
quantized, alignment = self.model.quantize(encoded, return_alignment=True)
count_per_class = torch.tensor([(alignment == i).sum()
for i in range(self.model.num_centroids)])
running_count_per_class += count_per_class
output = self.model.decoder(quantized)
predicted_centroids = self.model.centroids[alignment]
encoded = encoded.view(-1, encoded.size(-1))
new_length = output.size(1)
old_length = label_batch.size(1)
# Try to correct slight mismatches from down-sampling and up-sampling.
# Be careful in case of down-sampling without up-sampling
if old_length > new_length:
label_batch = label_batch[:, :new_length]
elif new_length > old_length:
output = output[:, :old_length]
distance_loss = criterion['dis_loss'](encoded, predicted_centroids.detach())
commitment_loss = criterion['com_loss'](predicted_centroids, encoded.detach())
reconstruction_loss = criterion['rec_loss'](output, label_batch)
if self.model.use_ma:
total_loss = reconstruction_loss + distance_loss
else:
total_loss = reconstruction_loss + distance_loss + commitment_loss
# Not part of the graph, just metrics to be monitored
mask = (label_batch != data_loaders[phase].dataset.pad_value).float()
numel = 1 # torch.sum(mask).item()
running_loss += reconstruction_loss.item()
running_dist_sum += distance_loss.item()
running_count += numel
class0_sum = running_dist_sum / running_count
px = running_count_per_class / running_count_per_class.sum()
px.clamp_min_(1e-20)
entropy = -(px * torch.log2(px)).sum().item()
if phase == 'train':
total_loss.backward()
if self.params_dict['gradient_clip']:
torch.nn.utils.clip_grad_norm_(self.model.parameters(),
self.params_dict['gradient_clip'])
self.optimizer.step()
phase_elapse = since(phase_beg)
eta = int(phase_elapse
* (dataset_sizes[phase] // batch_sizes[phase]
- batch_no - 1)
/ (batch_no + 1))
if self.params_dict['verbose']:
print('\r\t{} batch: {}/{} batches - ETA: {}s - loss: {:.4f} - dist: {:.4f} - '
'entropy: {:.4f}'.format(phase.title(),
batch_no + 1,
dataset_sizes[phase] // batch_sizes[phase] + 1,
eta, running_loss/running_count,
class0_sum, entropy
), end='')
epoch_loss = running_loss/running_count
print(" - loss: {:.4f} - dist: {:.4f} - entropy: {:.4f}".format(epoch_loss, class0_sum,
entropy))
self.loss_history[str(self.elapsed_epochs() - 1)][phase] = (epoch_loss,
class0_sum, entropy,
running_count)
print('\tTime: {}s'.format(int(since(epoch_beg))))
if self.elapsed_epochs() <= self.params_dict['warmup_num_epochs']:
self.optimizer.param_groups[0]['lr'] /= lr_scale
def train(self, outdir, criterion, data_loaders,
phases=('train', 'test'),
job_num_epochs=None,
**kwargs):
if not job_num_epochs:
job_num_epochs = self.params_dict['num_epochs']
for i in range(self.params_dict['num_epochs']):
self.train_one_epoch(criterion, data_loaders, phases, **kwargs)
if self.params_dict['use_model_checkpoint']\
and (self.elapsed_epochs() % self.params_dict['model_checkpoint_period'] == 0):
self.save_to_dir(os.path.join(outdir,
str(self.elapsed_epochs())))
history_sum = [self.loss_history[str(_)][phases[-1]][self.params_dict['early_stopping_loss']]
for _ in range(self.elapsed_epochs())]
if history_sum[-1] == min(history_sum):
self.save_to_dir(os.path.join(outdir, 'best'))
rl = reduce_lr(history=history_sum,
lr=self.optimizer.param_groups[0]['lr'],
cooldown=self.params_dict['cooldown'],
patience=self.params_dict['num_epochs_reduce_lr'],
mode='min',
difference=self.params_dict['delta_early_stopping'],
lr_scale=self.params_dict['learning_rate_scale'],
lr_min=self.params_dict['learning_rate_lower_bound'],
cool_down_patience=self.params_dict['num_epochs_cooldown'])
self.optimizer.param_groups[0]['lr'], self.params_dict['cooldown'] = rl
if self.params_dict['use_early_stopping']:
if stop_early(history_sum,
patience=self.params_dict['num_epochs_early_stopping'],
mode='min',
difference=self.params_dict['delta_early_stopping']):
print('Stopping Early.')
break
if self.elapsed_epochs() >= self.params_dict['num_epochs']:
break
if i >= job_num_epochs:
return
with open(os.path.join(outdir, '.done.train'), 'w') as _w:
pass
def elapsed_epochs(self):
return len(self.loss_history)
def load_from_dir(self, trainer_dir, model_kind=models.VQVAE):
if os.path.isfile(os.path.join(trainer_dir, 'nnet_kind.txt')):
model_classname = open(os.path.join(trainer_dir, 'nnet_kind.txt')).read().strip()
model_kind = models.get_model(model_classname)
self.model = model_kind.load_from_dir(trainer_dir)
self.model.to(self.device)
with open(os.path.join(trainer_dir, 'optimizer.txt')) as _opt:
opt_name = _opt.read()
_opt = _optimizer_kinds[opt_name]
self.optimizer = _opt(self.model.parameters(), lr=1e-3)
self.optimizer.load_state_dict(torch.load(
os.path.join(trainer_dir, 'optimizer.state'))
)
jsonfile = os.path.join(trainer_dir, 'trainer.json')
with open(jsonfile) as _json:
self.params_dict = json.load(_json)
jsonfile = os.path.join(trainer_dir, 'loss_history.json')
with open(jsonfile) as _json:
self.loss_history = json.load(_json)
def save_to_dir(self, trainer_dir):
if not os.path.isdir(trainer_dir):
os.makedirs(trainer_dir)
self.model.save(trainer_dir)
opt_name = str(self.optimizer).split()[0]
with open(os.path.join(trainer_dir, 'optimizer.txt'), 'w') as _opt:
_opt.write(opt_name)
torch.save(self.optimizer.state_dict(),
os.path.join(trainer_dir, 'optimizer.state')
)
with open(os.path.join(trainer_dir, 'trainer.json'), 'w') as _json:
json.dump(self.params_dict, _json)
with open(os.path.join(trainer_dir, 'loss_history.json'), 'w') as _json:
json.dump(self.loss_history, _json)
_trainers = {'Simple': SimpleTrainingLoop}
def get_trainer(trainer_name):
return _trainers[trainer_name]
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# This file is part of File Dedupe
# Copyright (C) 2015 Lars Holm Nielsen.
#
# File Dedupe is free software; you can redistribute it and/or
# modify it under the terms of the Revised BSD License; see LICENSE
# file for more details.
"""Small utility for detecting duplicate files."""
import os
import re
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
"""Integration of PyTest with setuptools."""
user_options = [('pytest-args=', 'a', 'Arguments to pass to py.test')]
def initialize_options(self):
"""Initialize options."""
TestCommand.initialize_options(self)
try:
from ConfigParser import ConfigParser
except ImportError:
from configparser import ConfigParser
config = ConfigParser()
config.read("pytest.ini")
self.pytest_args = config.get("pytest", "addopts").split(" ")
def finalize_options(self):
"""Finalize options."""
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
"""Run tests."""
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
# Get the version string. Cannot be done with import!
with open(os.path.join('filededupe', 'version.py'), 'rt') as f:
version = re.search(
'__version__\s*=\s*"(?P<version>.*)"\n',
f.read()
).group('version')
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('CHANGES.rst') as history_file:
history = history_file.read().replace('.. :changes:', '')
requirements = [
'fs>=0.5.0',
'click>=5.0',
]
extras_requirements = {}
test_requirements = [
'pytest-cache>=1.0',
'pytest-cov>=2.0.0',
'pytest-isort>=0.1.0',
'pytest-pep8>=1.0.6',
'pytest>=2.8.0',
'coverage>=4.0',
]
setup(
name='filededupe',
version=version,
description=__doc__,
long_description=readme + '\n\n' + history,
author="Lars Holm Nielsen",
author_email='lars@hankat.dk',
url='https://github.com/lnielsen/filededupe',
packages=[
'filededupe',
],
include_package_data=True,
install_requires=requirements,
extras_require=extras_requirements,
license="BSD",
zip_safe=False,
keywords='file deduplication',
entry_points={
'console_scripts': [
"filededupe=filededupe.cli:cli"
],
},
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
tests_require=test_requirements,
cmdclass={'test': PyTest},
)
| nilq/baby-python | python |
#!/usr/bin/env python3
from bs4 import BeautifulSoup as bf
import requests
import json
import random
import webbrowser
import os
import urllib
import time
if not os.path.exists('images'):
os.mkdir('images')
ls = []
def huluxia(id=250):
_key = '6BD0D690D176C706DA83A5D9222E52AEF3708C7537DC1E7AEA069811D93CF42CCDEC8CFE102FF3B77D8737F7BF103B3F19FBAB7F2E14C120'
hlx = requests.get(
url = 'http://floor.huluxia.com/user/info/ANDROID/2.1',
headers = {
'User-Agent':
'Mozilla/5.0 (Macintosh;'
' Intel Mac OS X 10_14_2) AppleWebKit/537.36'
' (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
},
params = {
'_key': _key,
'user_id': id
}
)
hlx.encoding = 'utf-8'
hlx_json = json.loads(hlx.content)
ls.append(hlx_json['avatar'])
#urllib.request.urlretrieve(hlx_json['avatar'],'./images/%s%s.jpg' % (hlx_json['nick'],hlx_json['userID']))
time.sleep(2)
print('成功! %s' % id)
for i in range(1,100):
huluxia(i)
| nilq/baby-python | python |
import rawTAspectrum
import tkinter as tk
from tkinter import ttk
from tkinter import Entry, filedialog, messagebox
from threading import Thread
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
from tkinter.filedialog import asksaveasfile
import os
from tkinter.ttk import Button
class Project(tk.Frame):
def __init__(self,parent):
#initialize GUI variables
tk.Frame.__init__(self,parent)
#class variables
self.tabCount =1
self.tabPanel = ttk.Notebook(self)
self.tabPanel.pack(fill="both", expand=True)
myMenu = tk.Menu(self)
parent.config(menu=myMenu)
#add menu Items
menu1 = tk.Menu(myMenu)
myMenu.add_cascade(label="Start", menu=menu1)
menu1.add_command(label="Select a file", command=self.open_file)
menu1.add_command(label="Reset", command=self.reset)
# menu1.add_command(label="Save a file", command=self.save_image)
# menu2 = tk.Menu(myMenu)
# myMenu.add_cascade(label="Menu 2", menu=menu2)
#menu2.add_command(label="Menu Item", command=self.emptyCommand)
#menu2.add_command(label="Menu Item", command=self.emptyCommand)
def create_tab(self):
# created new tabs
self.tab = tk.Frame(self.tabPanel)
self.tab.pack(fill="both")
self.tabPanel.add(self.tab,text="Tab" + str(self.tabCount))
self.tabCount = self.tabCount+1
def create_graph1(self):
# created new tabs
self.tab = tk.Frame(self.tabPanel)
self.tab.columnconfigure(0,weight=0)
self.tab.columnconfigure(1,weight=1)
self.tab.columnconfigure(2,weight=1)
self.tab.rowconfigure(0,weight=1)
self.tab.pack(fill="both")
self.tabPanel.add(self.tab,text="Tab" + str(self.tabCount))
self.tabCount = self.tabCount+1
self.controlPane = tk.Frame(self.tab)
self.controlPane.grid(column=0,row=0)
self.label1 = tk.Label(self.controlPane, text="Wlax1")
self.label1.pack()
self.entry1 = Entry(self.controlPane)
self.entry1.pack()
self.label2 = tk.Label(self.controlPane, text="Wlax2")
self.label2.pack()
self.entry2 = Entry(self.controlPane)
self.entry2.pack()
self.label3 = tk.Label(self.controlPane, text="Taxcp")
self.label3.pack()
self.entry3 = Entry(self.controlPane)
self.entry3.pack()
btn_apply = Button(self.controlPane, text="truncate", command=self.apply_button_action)
btn_apply.pack()
self.graph1 = tk.Frame(self.tab)
self.graph2 = tk.Frame(self.tab)
self.graph1.grid(column=1,row=0,sticky="nsew")
self.graph2.grid(column=2,row=0,sticky="nsew")
def apply_button_action(self):
controlThread = Thread(target=self.truncate_graph_thread_exec, daemon = True)
controlThread.start()
def truncate_graph_thread_exec(self):
self.fig3 = rawTAspectrum.load_truncated_chart(int(self.entry1.get()), int(self.entry2.get()), int(self.entry3.get()))
self.fig4 = rawTAspectrum.fourier_transform()
self.fig5 = rawTAspectrum.oscillation_freq_axis()
self.after(0,self.create_truncation_tab)
def create_truncation_tab(self):
self.update()
self.truncTab = tk.Frame(self.tabPanel)
self.truncTab.columnconfigure(0,weight=1)
self.truncTab.columnconfigure(1,weight=1)
self.truncTab.rowconfigure(0,weight=1)
self.truncTab.rowconfigure(1,weight=1)
self.tabPanel.add(self.truncTab,text="Tab" + str(self.tabCount))
self.tabCount = self.tabCount+1
self.graph3 = tk.Frame(self.truncTab)
self.graph3.grid(column=0,row=0,sticky="nsew")
self.graph4 = tk.Frame(self.truncTab)
self.graph4.grid(column=1,row=0,sticky="nsew")
self.graph5 = tk.Frame(self.truncTab)
self.graph5.grid(column=0,row=1,sticky="nsew")
self.freqPane = tk.Frame(self.truncTab)
self.freqPane.grid(column=1,row=1,sticky="nsew")
self.frequencySlider = tk.Scale(self.freqPane, from_=1,to=20, orient=tk.HORIZONTAL, label="frequency")
self.frequencySlider.pack()
btn_apply = Button(self.freqPane, text="truncate", command=self.start_freq_graph)
btn_apply.pack()
canvas = FigureCanvasTkAgg(self.fig3, master=self.graph3)
toolbar = NavigationToolbar2Tk(canvas, self.graph3)
toolbar.update()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
canvas = FigureCanvasTkAgg(self.fig4, master=self.graph4)
toolbar = NavigationToolbar2Tk(canvas, self.graph4)
toolbar.update()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
canvas.draw()
canvas = FigureCanvasTkAgg(self.fig5, master=self.graph5)
toolbar = NavigationToolbar2Tk(canvas, self.graph5)
toolbar.update()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
canvas.draw()
self.update()
def start_freq_graph(self):
controlThread = Thread(target=self.generate_freq_graph, daemon = True)
controlThread.start()
def generate_freq_graph(self):
self.fig6 = rawTAspectrum.frequency_graph(self.frequencySlider.get())
print(self.frequencySlider.get())
self.after(0,self.create_freq_tab)
def create_freq_tab(self):
self.update()
self.freqTab = tk.Frame(self.tabPanel)
self.tabPanel.add(self.freqTab,text="Tab" + str(self.tabCount))
self.tabCount = self.tabCount+1
self.graph6 = tk.Frame(self.freqTab)
self.graph6.pack()
canvas = FigureCanvasTkAgg(self.fig6, master=self.graph6)
toolbar = NavigationToolbar2Tk(canvas, self.graph6)
toolbar.update()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
canvas.draw()
self.update()
#opens data file and funs analysis
def open_file(self):
self.fileName = filedialog.askopenfilename(initialdir="/C:", title="Select a File", filetypes=(("DAT files", "*.dat"),("All files", "*.*")))
#rawTAspectrum.load_chart(self.fileName)
controlThread = Thread(target=self.dat_file_thread_exec, daemon=True)
self.progressBar = ttk.Progressbar(root,orient=tk.HORIZONTAL,length=200,mode="indeterminate",takefocus=True,maximum=100)
controlThread.start()
self.progressBar.start()
self.progressBar.pack()
def get_tab_count(self):
return self.tabCount
def dat_file_thread_exec(self):
#variable for progress bar on GUI
self.update()
rawTAspectrum.load_data_file(self.fileName)
self.fig1 = rawTAspectrum.load_raw_data()
self.fig2 = rawTAspectrum.load_data_without_axes()
self.after(0,self.draw_plot)
def draw_plot(self):
self.progressBar.stop()
self.progressBar.destroy()
self.create_graph1()
canvas = FigureCanvasTkAgg(self.fig1, master=self.graph1)
canvas2 = FigureCanvasTkAgg(self.fig2,master=self.graph2)
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
canvas2.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
toolbar = NavigationToolbar2Tk(canvas, self.graph1)
toolbar2 = NavigationToolbar2Tk(canvas2, self.graph2)
toolbar.update()
toolbar2.update()
canvas.draw()
canvas2.draw()
self.update()
def reset(self):
self.tabCount = 1
self.tabPanel.destroy()
self.tabPanel.destroy() # clears out the tab panel
self.tabPanel = ttk.Notebook(self) # resetting the tab panel
self.tabPanel.pack(fill="both", expand=True)
# def save_image(self):
# files = [("All files", "*.*" ),
# ("Python files", "*.py"),
# ("Text document", "*.txt"),
# ("Image files", "*.png")]
# file = asksaveasfile(filetypes = files, defaultextension = '.png')
if __name__ == "__main__":
root = tk.Tk()
root.title('Laser Noise Analysis App')
root.geometry("1000x700")
Project(root).pack(fill="both", expand=True)
root.mainloop()
| nilq/baby-python | python |
from django.db import models
import reversion
class Dois(models.Model):
texto = models.TextField(blank=False)
versao = models.PositiveIntegerField(default=1)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# if self.id:
# anterior = Dois.objects.get(id=self.id)
# self.versao = anterior.versao + 1
super().save(force_insert, force_update, using, update_fields)
class Meta:
ordering = ['-id']
verbose_name_plural = 'Varios "DOIS"'
reversion.register(Dois)
| nilq/baby-python | python |
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("component", views.component, name="component"),
path("page1", views.page1, name="page1"),
path("page2", views.page2, name="page2"),
] | nilq/baby-python | python |
from pywikiapi import wikipedia
from helpers import clean_api, chunker
import os, pymysql, json, re
# Connect to English Wikipedia
class WikidataAPI:
site = None
def __init__(self):
self.site = wikipedia('www', 'wikidata')
def get_item_data(self, wd_items, raw=False, attributes = ['sitelinks', 'claims'], claim_props=[]):
retMap = {}
for batch in chunker(wd_items, 49):
res = self.site('wbgetentities', ids=batch, props='|'.join(attributes))
for entity in res.get('entities'):
data = res.get('entities').get(entity)
tmp_data = {}
for attr in attributes:
if attr == 'sitelinks':
sitelinks = {f:data.get(attr).get(f).get('title') for f in data.get(attr)}
data.update({'sitelinks': sitelinks})
if attr == 'claims':
claims = clean_api(data.get(attr))
data.update({'claims': claims})
#print(data.get('type'))
#parsed_data = clean_api(data) if raw and 'claims' else data
retMap.update({entity: data})
return retMap
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:expandtab 2
# Copyright 2016, 2017 juga (juga at riseup dot net), MIT license.
version = "0.8.5"
| nilq/baby-python | python |
# SPDX-License-Identifier: MIT
"""Views in the context of rendering and compilation of layouts."""
# Python imports
from datetime import date
from logging import getLogger
# Django imports
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.utils.module_loading import import_string
from django.views.generic.base import ContextMixin, View
# app imports
from calingen.exceptions import CalingenException
from calingen.forms.generation import LayoutSelectionForm
from calingen.views.generic import RequestEnabledFormView
from calingen.views.mixins import AllCalendarEntriesMixin, RestrictToUserMixin
# get a module level logger
logger = getLogger(__name__)
class CompilerView(
LoginRequiredMixin, RestrictToUserMixin, AllCalendarEntriesMixin, ContextMixin, View
):
"""Render the selected layout and pass the result to a compiler."""
class NoLayoutSelectedException(CalingenException):
"""Raised if there is no selected layout in the user's ``Session``."""
def get(self, *args, **kwargs):
"""Render the selected layout and call the compiler on the result.
The actual response to the GET request is provided by the implementation
of :meth:`calingen.interfaces.plugin_api.CompilerProvider.get_response`.
Notes
-----
If there is no selected layout in the user's ``Session``, a redirect to
:class:`calingen.views.generation.LayoutSelectionView` is performed.
The method retrieves the
:class:`compiler instance <calingen.interfaces.plugin_api.CompilerProvider>`
from the project's settings module
(:attr:`~calingen.settings.CALINGEN_COMPILER`). It will resort to the
configured ``"default"`` compiler, if no specific compiler for the
selected ``layout_type`` (as defined by the implementation of
:class:`~calingen.interfaces.plugin_api.LayoutProvider`) is set or if
the specified compiler can not be imported. In that case a log message
(of level warn) is emitted.
"""
try:
layout = self._get_layout()
except self.NoLayoutSelectedException:
return redirect("calingen:layout-selection")
render_context = self._prepare_context(*args, **kwargs)
rendered_source = layout.render(render_context)
try:
compiler = import_string(settings.CALINGEN_COMPILER[layout.layout_type])
except KeyError:
compiler = import_string(settings.CALINGEN_COMPILER["default"])
except ImportError:
logger.warn(
"Could not import {}, using default compiler".format(
settings.CALINGEN_COMPILER[layout.layout_type]
)
)
compiler = import_string(settings.CALINGEN_COMPILER["default"])
return compiler.get_response(rendered_source, layout_type=layout.layout_type)
def _get_layout(self):
"""Return the :class:`~calingen.interfaces.plugin_api.LayoutProvider` implementation.
Notes
-----
If there is no selected layout in the user's ``Session``, a custom
exception will cause a redirect to the user's profile overview.
"""
selected_layout = self.request.session.pop("selected_layout", None)
if selected_layout is None:
# This is most likely an edge case: The view is accessed with a
# GET request without a selected layout stored in the user's session.
# This could be caused by directly calling this view's url.
# Just redirect to the layout selection.
raise self.NoLayoutSelectedException()
return import_string(selected_layout)
def _prepare_context(self, *args, **kwargs):
"""Prepare the context passed to the layout's rendering method.
Notes
-----
The ``context`` that is passed to the layout's ``render()`` method
contains the following ``keys``:
- ``target_year``: The year to create the layout for.
- ``layout_configuration``: If the layout provides a custom
implementation of :class:`calingen.forms.generation.LayoutConfigurationForm`,
the fetched values will be provided here.
- ``entries``: All calendar entries of the user's profile, resolved to
the ``target_year``, provided as a
:class:`calingen.interfaces.data_exchange.CalendarEntryList` object.
"""
target_year = self.request.session.pop("target_year", date.today().year)
layout_configuration = self.request.session.pop("layout_configuration", None)
return self.get_context_data(
target_year=target_year, layout_configuration=layout_configuration, **kwargs
)
class LayoutConfigurationView(LoginRequiredMixin, RequestEnabledFormView):
"""Show the (optional) configuration form for the selected layout.
Warnings
--------
This view is not restricted to users with a
:class:`Calingen Profile <calingen.models.profile.Profile>` and can be
accessed by any user of the project.
However, on actual generation and compilation of the output, a
``Profile`` is required.
Notes
-----
This is just the view to show and process the layout's implementation of
:class:`calingen.forms.generation.LayoutConfigurationForm`.
"""
template_name = "calingen/layout_configuration.html"
success_url = reverse_lazy("calingen:compilation")
class NoConfigurationFormException(CalingenException):
"""Raised if the selected layout does not have a ``configuration_form``."""
class NoLayoutSelectedException(CalingenException):
"""Raised if there is no selected layout in the user's ``Session``."""
def form_valid(self, form):
"""Trigger saving of the configuration values in the user's ``Session``."""
form.save_configuration()
return super().form_valid(form)
def get(self, request, *args, **kwargs):
"""Handle a GET request to the view.
While processing the request, it is determined if the selected
implementation of :class:`calingen.interfaces.plugin_api.LayoutProvider`
uses a custon ``configuration_form``.
If no custom configuration is implemented by the layout, the request
is redirected to the generator.
Notes
-----
Determining the ``configuration_form`` is done implicitly while
traversing the view's hierarchy during processing the request. Several
methods are involved, but at some point
:meth:`~calingen.views.generation.LayoutConfigurationView.get_form_class` is
called, which will raise an exceptions that is handled here.
If there is no selected layout in the user's ``Session``, a redirect to
:class:`calingen.views.generation.LayoutSelectionView` is performed.
"""
try:
return super().get(request, *args, **kwargs)
except self.NoConfigurationFormException:
# As no layout specific configuration form is required, directly
# redirect to the compilation.
return redirect("calingen:compilation")
except self.NoLayoutSelectedException:
# This is most likely an edge case: The view is accessed with a
# GET request without a selected layout stored in the user's session.
# This could be caused by directly calling this view's url.
# Just redirect to the layout selection.
return redirect("calingen:layout-selection")
def get_form_class(self):
"""Retrieve the layout's configuration form.
Notes
-----
Implementations of :class:`calingen.interfaces.plugin_api.LayoutProvider`
may provide a class attribute ``configuration_form`` with a subclass of
:class:`calingen.forms.generation.LayoutConfigurationForm`.
If ``configuration_form`` is omitted, a custom exception is raised, that
will be handled in
:meth:`~calingen.views.generation.LayoutConfigurationView.get`.
If there is no selected layout in the user's ``Session``, a different
custom exception will cause a redirect to the user's profile overview.
"""
selected_layout = self.request.session.get("selected_layout", None)
if selected_layout is None:
raise self.NoLayoutSelectedException()
layout = import_string(selected_layout)
if layout.configuration_form is None:
raise self.NoConfigurationFormException()
return layout.configuration_form
class LayoutSelectionView(LoginRequiredMixin, RequestEnabledFormView):
"""Provide a list of availabe layouts.
Warnings
--------
This view is not restricted to users with a
:class:`Calingen Profile <calingen.models.profile.Profile>` and can be
accessed by any user of the project.
However, on actual generation and compilation of the output, a
``Profile`` is required.
Notes
-----
This is just the view to show and process the
:class:`calingen.forms.generation.LayoutSelectionForm`.
Relevant logic, that affects the actual creation, rendering and compilation
of layouts is provided in the corresponding
:class:`~django.forms.Form` instance.
"""
template_name = "calingen/layout_selection.html"
form_class = LayoutSelectionForm
success_url = reverse_lazy("calingen:layout-configuration")
def form_valid(self, form):
"""Trigger saving of the selected value in the user's ``Session``."""
form.save_selection()
return super().form_valid(form)
| nilq/baby-python | python |
from tabulate import tabulate
from ..helpers.resource_matcher import ResourceMatcher
try:
from IPython.core.display import display, HTML
get_ipython
def display_html(data):
display(HTML(data))
except (NameError, ImportError):
def display_html(data):
print(data)
def _header_print(header, kwargs):
if kwargs.get('tablefmt') == 'html':
display_html(f'<h3>{header}</h3>')
else:
print(f'{header}:')
def _table_print(data, kwargs):
if kwargs.get('tablefmt') == 'html':
display_html(data)
else:
print(data)
def truncate_cell(value, max_size):
value = str(value)
if max_size is not None and len(value) > max_size:
return value[:max_size] + ' ...'
else:
return value
def printer(num_rows=10, last_rows=None, fields=None, resources=None,
header_print=_header_print, table_print=_table_print, max_cell_size=100, **kwargs):
def func(rows):
spec = rows.res
if not ResourceMatcher(resources, spec.descriptor).match(spec.name):
yield from rows
return
header_print(spec.name, kwargs)
schema_fields = spec.schema.fields
if fields:
schema_fields = [f for f in schema_fields if f.name in fields]
field_names = [f.name for f in schema_fields]
headers = ['#'] + [
'{}\n({})'.format(f.name, f.type) for f in schema_fields
]
toprint = []
last = []
x = 1
for i, row in enumerate(rows):
index = i + 1
prow = [index] + [truncate_cell(row[f], max_cell_size) for f in field_names]
yield row
if index - x == (num_rows + 1):
x *= num_rows
if 0 <= index - x <= num_rows:
last.clear()
if toprint and toprint[-1][0] != index - 1:
toprint.append(['...'])
toprint.append(prow)
else:
last.append(prow)
if len(last) > (last_rows or num_rows):
last = last[1:]
if toprint and last and toprint[-1][0] != last[0][0] - 1:
toprint.append(['...'])
toprint += last
table_print(tabulate(toprint, headers=headers, **kwargs), kwargs)
return func
| nilq/baby-python | python |
from hashmap.hashmap import HashMap, LinearHashMap
__all__ = ['HashMap', 'LinearHashMap'] | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Same as calc_velocity.py, but calls mpi with changa to allow many nodes
NOTE. mpirrun must be already loaded. Also, should do export MX_RCACHE=0
before loading python
Created on Wed Apr 9 15:39:28 2014
@author: ibackus
"""
import numpy as np
import pynbody
SimArray = pynbody.array.SimArray
import isaac
import subprocess
import os
import glob
import time
def v_xy(f, param, changbin=None, nr=50, min_per_bin=100):
"""
Attempts to calculate the circular velocities for particles in a thin
(not flat) keplerian disk. Requires ChaNGa
**ARGUMENTS**
f : tipsy snapshot
For a gaseous disk
param : dict
a dictionary containing params for changa. (see isaac.configparser)
changbin : str (OPTIONAL)
If set, should be the full path to the ChaNGa executable. If None,
an attempt to find ChaNGa is made
nr : int (optional)
number of radial bins to use when averaging over accelerations
min_per_bin : int (optional)
The minimum number of particles to be in each bin. If there are too
few particles in a bin, it is merged with an adjacent bin. Thus,
actual number of radial bins may be less than nr.
**RETURNS**
vel : SimArray
An N by 3 SimArray of gas particle velocities.
"""
if changbin is None:
# Try to find the ChaNGa binary full path
changbin = os.popen('which ChaNGa_uw_mpi').read().strip()
# Load up mpi
# Load stuff from the snapshot
x = f.g['x']
y = f.g['y']
z = f.g['z']
r = f.g['rxy']
vel0 = f.g['vel'].copy()
# Remove units from all quantities
r = isaac.strip_units(r)
x = isaac.strip_units(x)
y = isaac.strip_units(y)
z = isaac.strip_units(z)
# Temporary filenames for running ChaNGa
f_prefix = str(np.random.randint(0, 2**32))
f_name = f_prefix + '.std'
p_name = f_prefix + '.param'
# Update parameters
p_temp = param.copy()
p_temp['achInFile'] = f_name
p_temp['achOutName'] = f_prefix
if 'dDumpFrameTime' in p_temp: p_temp.pop('dDumpFrameTime')
if 'dDumpFrameStep' in p_temp: p_temp.pop('dDumpFrameStep')
# --------------------------------------------
# Estimate velocity from gravity only
# --------------------------------------------
# Note, accelerations due to gravity are calculated twice to be extra careful
# This is so that any velocity dependent effects are properly accounted for
# (although, ideally, there should be none)
# The second calculation uses the updated velocities from the first
for iGrav in range(2):
# Save files
f.write(filename=f_name, fmt = pynbody.tipsy.TipsySnap)
isaac.configsave(p_temp, p_name, ftype='param')
# Run ChaNGa, only calculating gravity
command = 'mpirun --mca mtl mx --mca pml cm ' + changbin + ' -gas -n 0 ' + p_name
#command = 'charmrun ++local ' + changbin + ' -gas -n 0 ' + p_name
p = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
while p.poll() is None:
time.sleep(0.1)
# Load accelerations
acc_name = f_prefix + '.000000.acc2'
a = isaac.load_acc(acc_name)
# Clean-up
for fname in glob.glob(f_prefix + '*'): os.remove(fname)
# If a is not a vector, calculate radial acceleration. Otherwise, assume
# a is the radial acceleration
a_r = a[:,0]*x/r + a[:,1]*y/r
# Make sure the units are correct then remove them
a_r = isaac.match_units(a_r, a)[0]
a_r = isaac.strip_units(a_r)
# Calculate cos(theta) where theta is angle above x-y plane
cos = r/np.sqrt(r**2 + z**2)
ar2 = a_r*r**2
# Bin the data
r_edges = np.linspace(r.min(), (1+np.spacing(2))*r.max(), nr + 1)
ind, r_edges = isaac.digitize_threshold(r, min_per_bin, r_edges)
ind -= 1
nr = len(r_edges) - 1
r_bins, ar2_mean, err = isaac.binned_mean(r, ar2, binedges=r_edges, \
weighted_bins=True)
# Fit lines to ar2 vs cos for each radial bin
m = np.zeros(nr)
b = np.zeros(nr)
for i in range(nr):
mask = (ind == i)
p = np.polyfit(cos[mask], ar2[mask], 1)
m[i] = p[0]
b[i] = p[1]
# Interpolate the line fits
m_spline = isaac.extrap1d(r_bins, m)
b_spline = isaac.extrap1d(r_bins, b)
# Calculate circular velocity
ar2_calc = m_spline(r)*cos + b_spline(r)
v_calc = np.sqrt(abs(ar2_calc)/r)
vel = f.g['vel'].copy()
v_calc = isaac.match_units(v_calc,vel)[0]
vel[:,0] = -v_calc*y/r
vel[:,1] = v_calc*x/r
# Assign to f
f.g['vel'] = vel
# --------------------------------------------
# Estimate pressure/gas dynamics accelerations
# --------------------------------------------
a_grav = a
ar2_calc_grav = ar2_calc
# Save files
f.write(filename=f_name, fmt = pynbody.tipsy.TipsySnap)
isaac.configsave(p_temp, p_name, ftype='param')
# Run ChaNGa, including SPH
command = 'mpirun --mca mtl mx --mca pml cm ' + changbin + ' +gas -n 0 ' + p_name
p = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
while p.poll() is None:
time.sleep(0.1)
# Load accelerations
acc_name = f_prefix + '.000000.acc2'
a_total = isaac.load_acc(acc_name)
# Clean-up
for fname in glob.glob(f_prefix + '*'): os.remove(fname)
# Estimate the accelerations due to pressure gradients/gas dynamics
a_gas = a_total - a_grav
ar_gas = a_gas[:,0]*x/r + a_gas[:,1]*y/r
ar_gas = isaac.strip_units(ar_gas)
ar2_gas = ar_gas*r**2
logr_bins, ratio, err = isaac.binned_mean(np.log(r), ar2_gas/ar2_calc_grav, nbins=nr,\
weighted_bins=True)
r_bins = np.exp(logr_bins)
ratio_spline = isaac.extrap1d(r_bins, ratio)
ar2_calc = ar2_calc_grav*(1 + ratio_spline(r))
a_calc = ar2_calc/r**2
v = np.sqrt(r*abs(a_calc))
v = isaac.match_units(v, vel0.units)[0]
vel = vel0.copy()
vel[:,0] = -v*y/r
vel[:,1] = v*x/r
# more cleanup
f.g['vel'] = vel0
return vel | nilq/baby-python | python |
class Country:
def __init__(self, name, capital, population, continent):
self.__name = name
self.__capital = capital
self.__population = population
self.__continent = continent
my_country = Country('France', 'Paris', 67081000, 'Europe')
print(my_country._Country__name)
print(my_country._Country__capital)
print(my_country._Country__population)
print(my_country._Country__continent) | nilq/baby-python | python |
from . import utils | nilq/baby-python | python |
import torch
from torch import nn
class WeightComputer(nn.Module):
def __init__(self, mode="constant", constant_weight=1.0, consistency_fn=None, consistency_neigh=1, logits=False, device="cpu", min_weight=0.0):
"""
:param mode: in {'constant', 'balance_gt', 'pred_entropy', 'pred_consistency', 'pred_merged}
:param constant_weight:
:param consistency_fn:
:param consistency_neigh: in pixels
:param logits: work with logits
"""
super().__init__()
self._mode = mode
self._constant_weight = constant_weight
self._consistency_fn = consistency_fn
self._consistency_neigh = consistency_neigh
self._is_logits = logits
self._min_weight = torch.tensor(min_weight, device=device)
self._device = device
if consistency_neigh != 1 and consistency_neigh != 2:
raise ValueError("invalid consistency neighbourhood {}".format(consistency_neigh))
if ("consistency" in self._mode or "multi" in self._mode) and consistency_fn is None:
raise ValueError("missing consistency function for weight computation")
def forward(self, y, y_gt, apply_weights=None):
weights = torch.maximum(self._weight(y, y_gt), y_gt)
if self._mode not in {"balance_gt", "constant"}:
weights = (1 - self._min_weight) * weights + self._min_weight
if apply_weights is not None:
if apply_weights.ndim == 1 and apply_weights.size()[0] != weights.size()[0]:
raise ValueError("apply weights vector does not have the correct dimensions {}".format(apply_weights.size()))
apply_weights = apply_weights.unsqueeze(1).unsqueeze(1).unsqueeze(1).int()
weights = torch.maximum(weights, apply_weights)
return weights
def _y(self, y):
if self._is_logits:
return torch.sigmoid(y)
else:
return y
def _weight(self, y, y_gt):
if self._mode == "constant":
return torch.full(y.size(), self._constant_weight, device=self._device)
elif self._mode == "balance_gt":
ratio = torch.mean(y_gt, dim=[2, 3], keepdim=True)
ratio[ratio >= 1] = 0 # handle case of no background
w = (1 - y_gt) * ratio / (1 - ratio)
w[w > 1.0] = 1.0 # don't overweight background even if they are minority
return w
elif self._mode == "pred_entropy":
return self._entropy(y)
elif self._mode == "pred_consistency":
return self._consistency(y)
elif self._mode == "pred_merged":
return self._consistency(y) * self._entropy(y)
else:
raise ValueError("Invalid mode '{}'".format(self._mode))
def _entropy(self, y):
if not self._is_logits:
return 1 + y * torch.log2(y) + (1 - y) * torch.log2(1 - y)
else:
probas = torch.sigmoid(y)
logexpy = torch.log(torch.exp(y) + 1)
return 1 + (probas * (y - logexpy) - (1 - probas) * logexpy) / torch.log(torch.tensor(2))
@property
def consist_fn(self):
if self._consistency_fn == "quadratic":
return lambda y1, y2: torch.square(y1 - y2)
elif self._consistency_fn == "absolute":
return lambda y1, y2: torch.abs(y1 - y2)
def _consistency(self, y):
offset_range = list(range(-self._consistency_neigh, self._consistency_neigh+1))
divider = torch.zeros(y.size(), dtype=torch.int8, device=self._device)
accumulate = torch.zeros(y.size(), dtype=y.dtype, device=self._device)
_, _, height, width = y.size()
consist_fn = self.consist_fn
probas = self._y(y)
for offset_x in offset_range:
for offset_y in offset_range:
if offset_x == 0 and offset_y == 0:
continue
ref_y_low, ref_y_high = max(0, offset_y), min(height, height + offset_y)
ref_x_low, ref_x_high = max(0, offset_x), min(width, width + offset_x)
tar_y_low, tar_y_high = max(0, -offset_y), min(height, height - offset_y)
tar_x_low, tar_x_high = max(0, -offset_x), min(width, width - offset_x)
accumulate[:, :, ref_y_low:ref_y_high, ref_x_low:ref_x_high] += consist_fn(
probas[:, :, ref_y_low:ref_y_high, ref_x_low:ref_x_high],
probas[:, :, tar_y_low:tar_y_high, tar_x_low:tar_x_high])
divider[:, :, ref_y_low:ref_y_high, ref_x_low:ref_x_high] += 1
return 1 - (accumulate / divider)
| nilq/baby-python | python |
# import the module, psqlwrapper is a class defined inside the postgresqlwrapper module
from sqlwrapper import psqlwrapper
#create a db object
db = psqlwrapper()
#let's connect to our postgres server
#remember to start your postgres server, either by using pgadmin interface or command line
db.connect('dbname', 'username', 'password', host='127.0.0.1', port=5432)
#if everything goes correct you have successfully connected to your database file
#we have just started the shop thus we only keep one type of pet i.e dogs let's create dog table
# dogs will have following characteristics id, breed, color, weight(in kg)
# it takes tablename, columns, data types and primary key as the input
db.create_table('dogs', ['id','breed','color','weight'],['integer','text','text','real'],'id')
#now your table has been created
# you can check all the tables in the database by using db.show_tables()
#now we have creted dogs table
#You can check the description of the columns in the table by using db.describe_table('dogs')
db.show_tables()
db.describe_table()
db.insert('dogs', ['id','breed','color','weight',],[1,'Labrador','yellow',29.4])
#the above query can also be written as
db.insert('dogs',[],[2,'German Shepherd','black',30.6])
#let's say i got a new dog but its weight is unknown
db.insert('dogs',['id','breed','color'],[3, 'German Shepherd', 'Brown'])
#this will make an entry of (3,German Shepherd, brown,None) in the table
#now let's fetch the values that was inserted
print db.fetch_all('dogs') #this will return all values in the dogs table in the form of list of dictionaries
print db.fetch_first('dogs') #this will return the first entry of the table
print db.fetch_last('dogs') #this will return thr last entry of the table
# now let's fetch the dogs whose breed is German Shepherd
print db.fetch_by('dogs',breed = "German Shepherd")
#fetch all the dogs whose breed is German Shepherd or it has yellow color skin
print db.fetch_by('dogs',breed = "German Shepherd", color = "yellow")
# fetch all the dogs whose breed is German Shepherd and color is black
print db.fetch_by('dogs',breed = "German Shepherd", color = "black")
#remember we had bought a dog whose weight was not known, well now the weight is known so let's update the entry
db.update_by('dogs',['weight'],[34.5],id = 3)
#let's say he was bought by some buyer, thus now we will have to delete his entry
db.delete_by('dogs', id=3)
#you can also count entries in the table by using
db.count_entries('dogs')
# now you can use drop table method
db.drop_table('dogs')
#also there is a method to delete all data from a specific table
db.delete_all_from('dogs')
#you're done all basic functions at your finger tips, don't need to write queries, now to develop a basic
#app it is fast and easy !!!
| nilq/baby-python | python |
import logging
from pathlib import Path
from typing import Optional
from genomics_data_index.storage.MaskedGenomicRegions import MaskedGenomicRegions
from genomics_data_index.storage.io.mutation.NucleotideSampleData import NucleotideSampleData
from genomics_data_index.storage.io.mutation.SequenceFile import SequenceFile
from genomics_data_index.storage.util import TRACE_LEVEL
logger = logging.getLogger(__name__)
class NucleotideSampleDataSequenceMask(NucleotideSampleData):
def __init__(self, sample_name: str, vcf_file: Path, vcf_file_index: Optional[Path],
sample_mask_sequence: Optional[Path], subtract_vcf_from_mask: bool = False):
super().__init__(sample_name=sample_name,
vcf_file=vcf_file,
vcf_file_index=vcf_file_index,
mask_bed_file=None,
preprocessed=False)
self._sample_mask_sequence = sample_mask_sequence
self._subtract_vcf_from_mask = subtract_vcf_from_mask
def _preprocess_mask(self, output_dir: Path) -> Path:
if self._sample_mask_sequence is None:
mask_file = output_dir / f'{self.sample_name_persistence}.bed.gz'
mask = MaskedGenomicRegions.empty_mask()
mask.write(mask_file)
return mask_file
else:
new_file = output_dir / f'{self.sample_name_persistence}.bed.gz'
if new_file.exists():
raise Exception(f'File {new_file} already exists')
name, records = SequenceFile(self._sample_mask_sequence).parse_sequence_file()
logger.log(TRACE_LEVEL, f'Getting genomic masks from {self._sample_mask_sequence}')
masked_regions = MaskedGenomicRegions.from_sequences(sequences=records)
if self._subtract_vcf_from_mask:
logger.log(TRACE_LEVEL, f'Subtracting variants in vcf_file=[{self._vcf_file}] '
f'from mask produced by sequence=[{self._sample_mask_sequence}]')
vcf_regions = MaskedGenomicRegions.from_vcf_file(self._vcf_file)
masked_regions = masked_regions.subtract(vcf_regions)
masked_regions.write(new_file)
return new_file
@classmethod
def create(cls, sample_name: str, vcf_file: Path,
sample_mask_sequence: Optional[Path] = None,
subtract_vcf_from_mask: bool = False) -> NucleotideSampleData:
return NucleotideSampleDataSequenceMask(sample_name=sample_name,
vcf_file=vcf_file,
vcf_file_index=None,
sample_mask_sequence=sample_mask_sequence,
subtract_vcf_from_mask=subtract_vcf_from_mask)
| nilq/baby-python | python |
'''Approach :
1. Create a new list "temp" containing a empty list node, i.e. value is None, as the head node
2. Set the next pointer of the head node to the node with a smaller value in the given two linked lists. For example l1's head node is smaller than l2's then set the next pointer of the new list's head node to l1.
3. Assign l1's head record to l1's current head node's next node.
4. Repeat step 2 until one of the remaining two linked lists have no nodes left.
5. Assign l1's tail record to keep the information of the remaining L2, i.e. point it to L2.
6. Return l1's head nodes's next record.'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = None
temp = ListNode()
while l1 and l2 :
if l1.val > l2.val :
center = l2
l2 = l2.next
else :
center = l1
l1 = l1.next
if not head :
head = center
temp = head
else:
temp.next = center
temp = temp.next
if head :
if l1 :
temp.next = l1
if l2 :
temp.next = l2
else:
if l1 :
head = l1
else:
head = l2
return head
| nilq/baby-python | python |
import os
import sys
import unittest
from shutil import copyfile
from unittest.mock import MagicMock, patch
import fs
import pytest
from moban.core.definitions import TemplateTarget
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
class TestCustomOptions(unittest.TestCase):
def setUp(self):
self.config_file = "config.yaml"
with open(self.config_file, "w") as f:
f.write("hello: world")
self.patcher1 = patch(
"moban.core.utils.verify_the_existence_of_directories"
)
self.patcher1.start()
@patch("moban.externals.file_system.abspath")
@patch("moban.core.moban_factory.MobanEngine.render_to_file")
def test_custom_options(self, fake_template_doer, fake_abspath):
test_args = [
"moban",
"-c",
self.config_file,
"-cd",
".",
"-td",
".",
"-t",
"a.jj2",
]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
fake_template_doer.assert_called_with("a.jj2", "config.yaml", "-")
@patch("moban.core.moban_factory.MobanEngine.render_to_file")
def test_minimal_options(self, fake_template_doer):
test_args = ["moban", "-c", self.config_file, "-t", "a.jj2"]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
fake_template_doer.assert_called_with("a.jj2", "config.yaml", "-")
def test_missing_template(self):
test_args = ["moban", "-c", self.config_file]
fake_stdin = MagicMock(isatty=MagicMock(return_value=True))
with patch.object(sys, "stdin", fake_stdin):
with patch.object(sys, "argv", test_args):
from moban.main import main
with pytest.raises(SystemExit):
main()
def tearDown(self):
self.patcher1.stop()
os.unlink(self.config_file)
class TestOptions(unittest.TestCase):
def setUp(self):
self.config_file = "data.yml"
with open(self.config_file, "w") as f:
f.write("hello: world")
self.patcher1 = patch(
"moban.core.utils.verify_the_existence_of_directories"
)
self.patcher1.start()
@patch("moban.core.moban_factory.MobanEngine.render_to_file")
def test_default_options(self, fake_template_doer):
test_args = ["moban", "-t", "a.jj2"]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
fake_template_doer.assert_called_with("a.jj2", "data.yml", "-")
@patch("moban.core.moban_factory.MobanEngine.render_string_to_file")
def test_string_template(self, fake_template_doer):
string_template = "{{HELLO}}"
test_args = ["moban", string_template]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
fake_template_doer.assert_called_with(
string_template, "data.yml", "-"
)
def test_no_argments(self):
test_args = ["moban"]
fake_stdin = MagicMock(isatty=MagicMock(return_value=True))
with patch.object(sys, "stdin", fake_stdin):
with patch.object(sys, "argv", test_args):
from moban.main import main
with pytest.raises(SystemExit):
main()
def tearDown(self):
self.patcher1.stop()
os.unlink(self.config_file)
class TestNoOptions(unittest.TestCase):
def setUp(self):
self.config_file = ".moban.yml"
copyfile(
fs.path.join("tests", "fixtures", self.config_file),
self.config_file,
)
self.data_file = "data.yaml"
with open(self.data_file, "w") as f:
f.write("hello: world")
self.patcher1 = patch(
"moban.core.utils.verify_the_existence_of_directories"
)
self.patcher1.start()
@patch("moban.core.moban_factory.MobanEngine.render_to_files")
def test_single_command(self, fake_template_doer):
test_args = ["moban"]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
call_args = list(fake_template_doer.call_args[0][0])
assert call_args == [
TemplateTarget("README.rst.jj2", "data.yaml", "README.rst"),
TemplateTarget("setup.py.jj2", "data.yaml", "setup.py"),
]
@patch("moban.core.moban_factory.MobanEngine.render_to_files")
def test_single_command_with_missing_output(self, fake_template_doer):
test_args = ["moban", "-t", "README.rst.jj2"]
with patch.object(sys, "argv", test_args):
from moban.main import main
with pytest.raises(Exception):
main()
@patch("moban.core.moban_factory.MobanEngine.render_to_files")
def test_single_command_with_a_few_options(self, fake_template_doer):
test_args = ["moban", "-t", "README.rst.jj2", "-o", "xyz.output"]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
call_args = list(fake_template_doer.call_args[0][0])
assert call_args == [
TemplateTarget("README.rst.jj2", "data.yaml", "xyz.output")
]
@patch("moban.core.moban_factory.MobanEngine.render_to_files")
def test_single_command_with_options(self, fake_template_doer):
test_args = [
"moban",
"-t",
"README.rst.jj2",
"-c",
"new.yml",
"-o",
"xyz.output",
]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
call_args = list(fake_template_doer.call_args[0][0])
assert call_args == [
TemplateTarget("README.rst.jj2", "new.yml", "xyz.output")
]
def test_single_command_without_output_option(self):
test_args = ["moban", "-t", "abc.jj2"]
with patch.object(sys, "argv", test_args):
from moban.main import main
with pytest.raises(Exception):
main()
def tearDown(self):
os.unlink(self.config_file)
os.unlink(self.data_file)
self.patcher1.stop()
class TestNoOptions2(unittest.TestCase):
def setUp(self):
self.config_file = ".moban.yml"
copyfile(
fs.path.join("tests", "fixtures", self.config_file),
self.config_file,
)
self.data_file = "data.yaml"
with open(self.data_file, "w") as f:
f.write("hello: world")
self.patcher1 = patch(
"moban.core.utils.verify_the_existence_of_directories"
)
self.patcher1.start()
@patch("moban.core.moban_factory.MobanEngine.render_to_files")
def test_single_command(self, fake_template_doer):
test_args = ["moban"]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
call_args = list(fake_template_doer.call_args[0][0])
assert call_args == [
TemplateTarget("README.rst.jj2", "data.yaml", "README.rst"),
TemplateTarget("setup.py.jj2", "data.yaml", "setup.py"),
]
def tearDown(self):
self.patcher1.stop()
os.unlink(self.config_file)
os.unlink(self.data_file)
class TestCustomMobanFile(unittest.TestCase):
def setUp(self):
self.config_file = "custom-moban.txt"
copyfile(
fs.path.join("tests", "fixtures", ".moban.yml"), self.config_file
)
self.data_file = "data.yaml"
with open(self.data_file, "w") as f:
f.write("hello: world")
self.patcher1 = patch(
"moban.core.utils.verify_the_existence_of_directories"
)
self.patcher1.start()
@patch("moban.core.moban_factory.MobanEngine.render_to_files")
def test_single_command(self, fake_template_doer):
test_args = ["moban", "-m", self.config_file]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
call_args = list(fake_template_doer.call_args[0][0])
assert call_args == [
TemplateTarget("README.rst.jj2", "data.yaml", "README.rst"),
TemplateTarget("setup.py.jj2", "data.yaml", "setup.py"),
]
def tearDown(self):
self.patcher1.stop()
os.unlink(self.config_file)
os.unlink(self.data_file)
class TestTemplateOption(unittest.TestCase):
def setUp(self):
self.config_file = "custom-moban.txt"
copyfile(
fs.path.join("tests", "fixtures", ".moban.yml"), self.config_file
)
self.patcher1 = patch(
"moban.core.utils.verify_the_existence_of_directories"
)
self.patcher1.start()
@patch("moban.core.moban_factory.MobanEngine.render_to_file")
def test_template_option_override_moban_file(self, fake_template_doer):
test_args = ["moban", "-t", "setup.py.jj2"]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
fake_template_doer.assert_called_with(
"setup.py.jj2", "data.yml", "-"
)
@patch("moban.core.moban_factory.MobanEngine.render_to_file")
def test_template_option_not_in_moban_file(self, fake_template_doer):
test_args = ["moban", "-t", "foo.jj2"]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
fake_template_doer.assert_called_with("foo.jj2", "data.yml", "-")
def tearDown(self):
self.patcher1.stop()
os.unlink(self.config_file)
@patch("moban.core.utils.verify_the_existence_of_directories")
def test_duplicated_targets_in_moban_file(fake_verify):
config_file = "duplicated.moban.yml"
copyfile(fs.path.join("tests", "fixtures", config_file), ".moban.yml")
test_args = ["moban"]
with patch.object(sys, "argv", test_args):
from moban.main import main
pytest.raises(SystemExit, main)
os.unlink(".moban.yml")
class TestInvalidMobanFile(unittest.TestCase):
def setUp(self):
self.config_file = ".moban.yml"
@patch("moban.core.moban_factory.MobanEngine.render_to_files")
def test_no_configuration(self, fake_template_doer):
with open(self.config_file, "w") as f:
f.write("")
test_args = ["moban"]
with patch.object(sys, "argv", test_args):
from moban.main import main
with pytest.raises(SystemExit):
main()
@patch("moban.core.moban_factory.MobanEngine.render_to_files")
def test_no_configuration_2(self, fake_template_doer):
with open(self.config_file, "w") as f:
f.write("not: related")
test_args = ["moban"]
with patch.object(sys, "argv", test_args):
from moban.main import main
with pytest.raises(SystemExit):
main()
@patch("moban.core.moban_factory.MobanEngine.render_to_files")
def test_no_targets(self, fake_template_doer):
with open(self.config_file, "w") as f:
f.write("configuration: test")
test_args = ["moban"]
with patch.object(sys, "argv", test_args):
from moban.main import main
with pytest.raises(SystemExit):
main()
def tearDown(self):
os.unlink(self.config_file)
class TestComplexOptions(unittest.TestCase):
def setUp(self):
self.config_file = ".moban.yml"
copyfile(
fs.path.join("tests", "fixtures", ".moban-2.yml"), self.config_file
)
self.data_file = "data.yaml"
with open(self.data_file, "w") as f:
f.write("hello: world")
@patch(
"moban.core.utils.verify_the_existence_of_directories",
return_value=".",
)
def test_single_command(self, _):
test_args = ["moban"]
with patch.object(sys, "argv", test_args):
from moban.main import main
with patch(
"moban.core.moban_factory.MobanEngine.render_to_files"
) as fake:
main()
call_args = list(fake.call_args[0][0])
assert call_args == [
TemplateTarget(
"README.rst.jj2", "custom-data.yaml", "README.rst"
),
TemplateTarget("setup.py.jj2", "data.yml", "setup.py"),
]
def tearDown(self):
os.unlink(self.config_file)
os.unlink(self.data_file)
class TestTemplateTypeOption(unittest.TestCase):
def setUp(self):
self.config_file = "data.yml"
with open(self.config_file, "w") as f:
f.write("hello: world")
@patch("moban.core.moban_factory.MobanEngine.render_to_file")
def test_mako_option(self, fake_template_doer):
test_args = ["moban", "-t", "a.mako"]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
fake_template_doer.assert_called_with("a.mako", "data.yml", "-")
def tearDown(self):
os.unlink(self.config_file)
def test_version_option():
test_args = ["moban", "-V"]
with patch.object(sys, "argv", test_args):
from moban.main import main
with pytest.raises(SystemExit):
main()
@patch("logging.basicConfig")
def test_warning_verbose(fake_config):
fake_config.side_effect = [IOError("stop test")]
test_args = ["moban", "-vvv"]
with patch.object(sys, "argv", test_args):
from moban.main import main
try:
main()
except IOError:
fake_config.assert_called_with(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=10,
)
@patch("logging.basicConfig")
def test_debug_five_verbose_option(fake_config, *_):
fake_config.side_effect = [IOError("stop test")]
test_args = ["moban", "-vvvvv"]
with patch.object(sys, "argv", test_args):
from moban.main import main
try:
main()
except IOError:
fake_config.assert_called_with(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=10,
)
@patch("moban.core.utils.verify_the_existence_of_directories", return_value=[])
def test_git_repo_example(_):
test_args = [
"moban",
"-t",
"git://github.com/moremoban/pypi-mobans.git!/templates/_version.py.jj2",
"-c",
"git://github.com/moremoban/pypi-mobans.git!/config/data.yml",
"-o",
"test_git_repo_example.py",
]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
with open("test_git_repo_example.py") as f:
content = f.read()
assert content == '__version__ = "0.1.1rc3"\n__author__ = "C.W."\n'
os.unlink("test_git_repo_example.py")
@patch("moban.core.utils.verify_the_existence_of_directories", return_value=[])
def test_pypi_pkg_example(_):
test_args = [
"moban",
"-t",
"pypi://pypi-mobans-pkg/resources/templates/_version.py.jj2",
"-c",
"pypi://pypi-mobans-pkg/resources/config/data.yml",
"-o",
"test_pypi_pkg_example.py",
]
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
with open("test_pypi_pkg_example.py") as f:
content = f.read()
assert content == '__version__ = "0.1.1rc3"\n__author__ = "C.W."\n'
os.unlink("test_pypi_pkg_example.py")
def test_add_extension():
if sys.version_info[0] == 2:
return pytest.skip("jinja2-python-version does not support python 2")
test_commands = [
[
"moban",
"-t",
"{{ python_version }}",
"-e",
"jinja2=jinja2_python_version.PythonVersionExtension",
"-o",
"moban.output",
],
[
"moban",
"-t",
"{{ python_version }}",
"-e",
"jj2=jinja2_python_version.PythonVersionExtension",
"-o",
"moban.output",
],
]
for test_args in test_commands:
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
with open("moban.output") as f:
content = f.read()
assert content == "{}.{}".format(
sys.version_info[0], sys.version_info[1]
)
os.unlink("moban.output")
def test_stdin_input():
if sys.platform == "win32":
return pytest.skip("windows test fails with this pipe test 2")
test_args = ["moban", "-d", "hello=world", "-o", "moban.output"]
with patch.object(sys, "stdin", StringIO("{{hello}}")):
with patch.object(sys, "argv", test_args):
from moban.main import main
main()
with open("moban.output") as f:
content = f.read()
assert content == "world"
os.unlink("moban.output")
def test_stdout():
test_args = ["moban", "-d", "hello=world", "-t", "{{hello}}"]
with patch.object(sys, "argv", test_args):
with patch("sys.stdout", new_callable=StringIO) as fake_stdout:
from moban.main import main
main()
assert fake_stdout.getvalue() == "world\n"
def test_render_file_stdout():
config_file = "config.yaml"
with open(config_file, "w") as f:
f.write("hello: world")
template_file = "t.jj2"
with open(template_file, "w") as f:
f.write("{{hello}}")
test_args = ["moban", "-t", "t.jj2", "-c", "config.yaml"]
with patch.object(sys, "argv", test_args):
with patch("sys.stdout", new_callable=StringIO) as fake_stdout:
from moban.main import main
main()
assert fake_stdout.getvalue() == "world\n"
def test_custom_jinja2_filters_tests():
config_file = "config.yaml"
with open(config_file, "w") as f:
f.write("hello: world")
template_file = "t.jj2"
with open(template_file, "w") as f:
f.write("{{hello}}")
test_args = [
"moban",
"-e",
"jinja2=filter:moban.externals.file_system.url_join",
"jinja2=test:moban.externals.file_system.exists",
"jinja2=global:description=moban.constants.PROGRAM_DESCRIPTION",
"-t",
"{{'a'|url_join('b')}} {{'b' is exists}}{{ description }}",
]
with patch.object(sys, "argv", test_args):
with patch("sys.stdout", new_callable=StringIO) as fake_stdout:
from moban.main import main
expected_output = (
"a/b False"
+ "Static text generator using "
+ "any template, any data and any location.\n"
)
main()
assert fake_stdout.getvalue() == expected_output
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Multilingual support postpone indefinitely. Only Help has a language option.
# (Making `app` method that handles all strings that should contain property `lang` which comes from config",
# doesn't work either because `app` doesn't exist when widgets are initialized.)
"""
Besides differences in written language letters and words,
various languages use different marks as separators for decimals.
Also sometimes variations in the separators exist within the same country.
This module will focus mostly on the most prevalent cases.
An option to choose decimal separator mark could be created
but the selection should NOT be forced on the user
since they might be very inexperienced and not even know which is the correct mark.
"""
class LanguageNotImplemented(Exception):
pass
SUPPORTED_LANGUAGES = {}
class Language(object):
def __init__(self, name, name_native):
self.name_native = name_native # Language name spelled with characters of the language itself
self.name = name
SUPPORTED_LANGUAGES.update({self.name: self})
# In reality, separators differ for different english-speaking countries
# (e.g. eng_US, eng_ireland, eng_UK ..).
# Since this program is not expected to become very popular,
# the convention below should be ok.
# Alternatively, the user could be prompted to select his separator;
# the prompt should be in a very easy to understand form:
# e.g. "Three point one." Select the image that is accurate (used for separator blabla..)
english = Language(name='english', name_native='english')
greek = Language(name='greek', name_native=u'ελληνικά')
class Message(object):
DEFAULT_LANGUAGE = 'english'
selected_language = DEFAULT_LANGUAGE
def __init__(self, only_english=False, **kwargs):
# Ensures required languages are implemented
if only_english:
if self.DEFAULT_LANGUAGE not in kwargs:
raise LanguageNotImplemented(self.DEFAULT_LANGUAGE)
langs_not_implemented = set(kwargs) - set(SUPPORTED_LANGUAGES)
if langs_not_implemented:
raise LanguageNotImplemented(langs_not_implemented)
self.langs_msgs_dct = kwargs
PLAY = Message(
english='Play',
greek=u'Παιχνίδι',
)
ABOUT = Message(
english='About',
greek=u'Σχετικά',
)
HELP = Message(
english='Help',
greek=u'Βοήθεια',
)
REWARDS = Message(
english='Rewards',
greek=u'Βραβεία',
)
VERSION = Message(
english='version',
greek='έκδοση',
)
EASY = Message(
english='easy',
greek='εύκολα',
)
MEDIUM = Message(
english='medium',
greek='μέτρια',
)
HARD = Message(
english='hard',
greek='δύσκολα',
)
OPERATION_CATEGORIES = Message(
english='Operation type',
greek='Είδος πράξεων',
)
DIFFICULTY = Message(
english='Difficulty',
greek='Δυσκολία',
)
CLEAR = Message(
english='Clear',
greek='Σβήσιμο',
)
CHECK_ANSWER = Message(
english='Check\nanswer',
greek='Έλεγχος\nαπάντησης',
)
SEPARATOR_SYMBOL = Message(
english='.',
greek=',',
)
| nilq/baby-python | python |
from django.core.management.base import BaseCommand
from pages.models import Invite
import csv
class Command(BaseCommand):
def handle(self, *args, **options):
print('Loading CSV')
csv_path = './academy_invites_2014.csv'
with open(csv_path, 'rt') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
obj = Invite.objects.create(
name=row['Name'],
branch=row['Branch']
)
print(obj)
| nilq/baby-python | python |
import logging
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
from galaxy_api.api import models
from galaxy_api.auth import models as auth_models
from galaxy_api.api import permissions
from .base import BaseTestCase
from .x_rh_identity import user_x_rh_identity
log = logging.getLogger(__name__)
class TestUiNamespaceViewSet(BaseTestCase):
def setUp(self):
super().setUp()
def test_get(self):
url = reverse('api:ui:namespaces-list')
response = self.client.get(url, format='json')
log.debug('response: %s', response)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_new_user(self):
username = 'newuser'
username_token_b64 = user_x_rh_identity(username,
account_number="666")
client = APIClient()
client.credentials(**{"HTTP_X_RH_IDENTITY": username_token_b64})
url = reverse('api:ui:namespaces-list')
response = client.get(url, format='json')
log.debug('response: %s', response)
self.assertEqual(response.status_code, status.HTTP_200_OK)
# user isn't a namespace owner, should get empty list of namespaces
assert not response.data['data']
def test_get_namespace_owner_user(self):
username = 'some_namespace_member'
some_namespace_member = auth_models.User.objects.create(username=username)
namespace_group = self._create_group('rh-identity', 'some_namespace',
users=some_namespace_member)
namespace = self._create_namespace('some_namespace', namespace_group)
log.debug('namespace: %s', namespace)
some_namespace_member_token_b64 = user_x_rh_identity(username)
client = APIClient()
client.credentials(**{"HTTP_X_RH_IDENTITY": some_namespace_member_token_b64})
url = reverse('api:ui:namespaces-list')
response = client.get(url, format='json')
log.debug('response: %s', response)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['data'][0]['name'], 'some_namespace')
# TODO: test get detail, put/update detail, put/update detail for partner-engineers, etc
class TestUiMyNamespaceViewSet(BaseTestCase):
def setUp(self):
super().setUp()
def test_list_user_not_in_namespace_group(self):
url = reverse('api:ui:namespaces-list')
username = 'not_namespace_member'
not_namespace_member_token_b64 = user_x_rh_identity(username)
client = APIClient()
client.credentials(**{"HTTP_X_RH_IDENTITY": not_namespace_member_token_b64})
response = client.get(url, format='json')
log.debug('response: %s', response)
log.debug('response.data:\n%s', response.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
# No matching namespaces found
self.assertEqual(response.data['data'], [])
def test_list_user_in_namespace_group(self):
url = reverse('api:ui:namespaces-list')
username = 'some_namespace_member'
some_namespace_member = auth_models.User.objects.create(username=username)
namespace_group = self._create_group('rh-identity', 'some_namespace',
users=some_namespace_member)
namespace = self._create_namespace('some_namespace', namespace_group)
log.debug('namespace: %s', namespace)
some_namespace_member_token_b64 = user_x_rh_identity(username)
client = APIClient()
client.credentials(**{"HTTP_X_RH_IDENTITY": some_namespace_member_token_b64})
response = client.get(url, format='json')
log.debug('response: %s', response)
log.debug('response.data:\n%s', response.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['data'][0]['name'], 'some_namespace')
def test_list_user_in_namespace_system_admin(self):
url = reverse('api:ui:namespaces-list')
username = 'some_namespace_member'
some_namespace_member = auth_models.User.objects.create(username=username)
namespace_group_name = permissions.IsPartnerEngineer.GROUP_NAME
namespace_group = auth_models.Group.objects.create(name=namespace_group_name)
namespace_group.user_set.add(*[some_namespace_member])
namespace = self._create_namespace('some_namespace', namespace_group)
# create another namespace without any groups
another_namespace = models.Namespace.objects.create(name='another_namespace')
log.debug('namespace: %s', namespace)
log.debug('another_namespace: %s', another_namespace)
some_namespace_member_token_b64 = user_x_rh_identity(username)
client = APIClient()
client.credentials(**{"HTTP_X_RH_IDENTITY": some_namespace_member_token_b64})
response = client.get(url, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['data'][0]['name'], 'some_namespace')
namespace_names = [ns_data['name'] for ns_data in response.data['data']]
# Verify the system user can see all namespacees, even those without a group
self.assertIn('some_namespace', namespace_names)
self.assertIn('another_namespace', namespace_names)
| nilq/baby-python | python |
from __future__ import absolute_import, division, print_function
import numpy as np
import iminuit as minuit
import time
import functools
import logging
from .processing import build_trigger_windows
from scipy import optimize as op
from collections import OrderedDict
from copy import deepcopy
from scipy.special import gammainc
from .models import TimeLine
pvalue = lambda dof, chisq: 1. - gammainc(.5 * dof, .5 * chisq)
def setDefault(func = None, passed_kwargs = {}):
"""
Read in default keywords of the simulation and pass to function
"""
if func is None:
return functools.partial(setDefault, passed_kwargs = passed_kwargs)
@functools.wraps(func)
def init(*args, **kwargs):
for k in passed_kwargs.keys():
kwargs.setdefault(k,passed_kwargs[k])
return func(*args, **kwargs)
return init
minuit_def = {
'verbosity': 0,
'int_steps': 1e-4,
'strategy': 2,
'tol': 1e-5,
'up': 1., # it's a chi 2 fit
'max_tol_increase': 3000.,
'tol_increase': 1000.,
'ncall': 10000,
'steps': 40,
'scan_bound': (0.,10.),
'pedantic': True,
'precision': None,
'scipy': False,
'pinit': {'A' : 1.,
'c': 1.,
't0': 1.,
'tr': 1.,
'td': 1.},
'fix': {'A' : False,
'c': False,
't0': False,
'tr': False,
'td': False},
'islog': {'A' : False,
'c': False,
't0': False,
'tr': False,
'td': False},
'limits': {'A' : [0.,100.],
'c': [0.,5.],
't0': [0.,100.],
'tr': [0.,100.],
'td': [0.,100.]}
}
# --- miniuit defaults ------------------------------------- #
class FitTimeLine(object):
def __init__(self, t, v, dv, fSample):
"""
Initialize the fitting class
:param t: array-like
time values in micro s
:param v: array-like
voltage values in mV
:param dv: array-like
uncertainties of voltage values in mV
:param fSample: float
Sampling frequency in Hz
"""
self._t = t
self._v = v
self._dv = dv
self._f = None
self._fSample = fSample
return
@property
def t(self):
return self._t
@property
def v(self):
return self._v
@property
def dv(self):
return self._dv
@property
def f(self):
return self._f
@property
def fSample(self):
return self._fSample
@property
def m(self):
return self._m
@t.setter
def t(self, t):
self._t = t
return
@v.setter
def v(self, v):
self._v = v
return
@fSample.setter
def fSample(self, fSample):
self._fSample = fSample
return
@dv.setter
def dv(self, dv):
self._dv = dv
return
def calcObjFunc(self,*args):
return self.__calcObjFunc(*args)
def __calcObjFunc(self,*args):
"""
objective function passed to iMinuit
"""
params = {}
for i,p in enumerate(self.parnames):
if self.par_islog[p]:
params[p] = np.power(10.,args[i])
else:
params[p] = args[i]
return self.returnObjFunc(params)
def __wrapObjFunc(self,args):
"""
objective function passed to scipy.optimize
"""
params = {}
for i,p in enumerate(self.parnames):
if not self.fitarg['fix_{0:s}'.format(p)]:
if self.par_islog[p]:
params[p] = np.power(10.,args[i])
else:
params[p] = args[i]
else:
if self.par_islog[p]:
params[p] = np.power(10.,self.fitarg[p])
else:
params[p] = self.fitarg[p]
return self.returnObjFunc(params)
def returnObjFunc(self,params):
"""Calculate the objective function"""
f = self._f(self._t, **params)
chi2 = ((self._v - f)**2. / self._dv**2.).sum()
return chi2
@setDefault(passed_kwargs = minuit_def)
def fill_fitarg(self, **kwargs):
"""Helper function to fill the dictionary for minuit fitting"""
# set the fit arguments
fitarg = {}
fitarg.update(kwargs['pinit'])
for k in kwargs['limits'].keys():
fitarg['limit_{0:s}'.format(k)] = kwargs['limits'][k]
fitarg['fix_{0:s}'.format(k)] = kwargs['fix'][k]
fitarg['error_{0:s}'.format(k)] = kwargs['pinit'][k] * kwargs['int_steps']
fitarg = OrderedDict(sorted(fitarg.items()))
# get the names of the parameters
self.parnames = kwargs['pinit'].keys()
self.par_islog = kwargs['islog']
return fitarg
@setDefault(passed_kwargs = minuit_def)
def run_migrad(self,fitarg,**kwargs):
"""
Helper function to initialize migrad and run the fit.
Initial parameters are optionally estimated with scipy optimize.
"""
self.fitarg = fitarg
values, bounds = [],[]
for k in self.parnames:
values.append(fitarg[k])
bounds.append(fitarg['limit_{0:s}'.format(k)])
logging.debug(self.parnames)
logging.debug(values)
logging.debug(self.__wrapObjFunc(values))
if kwargs['scipy']:
self.res = op.minimize(self.__wrapObjFunc,
values,
bounds = bounds,
method='TNC',
#method='Powell',
options={'maxiter': kwargs['ncall']} #'xtol': 1e-20, 'eps' : 1e-20, 'disp': True}
#tol=None, callback=None,
#options={'disp': False, 'minfev': 0, 'scale': None,
#'rescale': -1, 'offset': None, 'gtol': -1,
#'eps': 1e-08, 'eta': -1, 'maxiter': kwargs['ncall'],
#'maxCGit': -1, 'mesg_num': None, 'ftol': -1, 'xtol': -1, 'stepmx': 0,
#'accuracy': 0}
)
logging.debug(self.res)
for i,k in enumerate(self.parnames):
fitarg[k] = self.res.x[i]
logging.debug(fitarg)
cmd_string = "lambda {0}: self.__calcObjFunc({0})".format(
(", ".join(self.parnames), ", ".join(self.parnames)))
string_args = ", ".join(self.parnames)
global f # needs to be global for eval to find it
f = lambda *args: self.__calcObjFunc(*args)
cmd_string = "lambda %s: f(%s)" % (string_args, string_args)
logging.debug(cmd_string)
# work around so that the parameters get names for minuit
self._minimize_f = eval(cmd_string, globals(), locals())
self._m = minuit.Minuit(self._minimize_f,
print_level =kwargs['verbosity'],
errordef = kwargs['up'],
pedantic = kwargs['pedantic'],
**fitarg)
self._m.tol = kwargs['tol']
self._m.strategy = kwargs['strategy']
logging.debug("tol {0:.2e}, strategy: {1:n}".format(
self._m.tol,self._m.strategy))
self._m.migrad(ncall = kwargs['ncall']) #, precision = kwargs['precision'])
return
def __print_failed_fit(self):
"""print output if migrad failed"""
if not self._m.migrad_ok():
fmin = self._m.get_fmin()
logging.warning(
'*** migrad minimum not ok! Printing output of get_fmin'
)
logging.warning('{0:s}:\t{1}'.format('*** has_accurate_covar',
fmin.has_accurate_covar))
logging.warning('{0:s}:\t{1}'.format('*** has_covariance',
fmin.has_covariance))
logging.warning('{0:s}:\t{1}'.format('*** has_made_posdef_covar',
fmin.has_made_posdef_covar))
logging.warning('{0:s}:\t{1}'.format('*** has_posdef_covar',
fmin.has_posdef_covar))
logging.warning('{0:s}:\t{1}'.format('*** has_reached_call_limit',
fmin.has_reached_call_limit))
logging.warning('{0:s}:\t{1}'.format('*** has_valid_parameters',
fmin.has_valid_parameters))
logging.warning('{0:s}:\t{1}'.format('*** hesse_failed',
fmin.hesse_failed))
logging.warning('{0:s}:\t{1}'.format('*** is_above_max_edm',
fmin.is_above_max_edm))
logging.warning('{0:s}:\t{1}'.format('*** is_valid',
fmin.is_valid))
return
def __repeat_migrad(self, **kwargs):
"""Repeat fit if fit was above edm"""
fmin = self._m.get_fmin()
if not self._m.migrad_ok() and fmin['is_above_max_edm']:
logging.warning(
'Migrad did not converge, is above max edm. Increasing tol.'
)
tol = self._m.tol
self._m.tol *= self._m.edm /(self._m.tol * self._m.errordef ) * kwargs['tol_increase']
logging.info('New tolerance : {0}'.format(self._m.tol))
if self._m.tol >= kwargs['max_tol_increase']:
logging.warning(
'New tolerance to large for required precision'
)
else:
self._m.migrad(
ncall = kwargs['ncall'])#,
#precision = kwargs['precision']
#)
logging.info(
'Migrad status after second try: {0}'.format(
self._m.migrad_ok()
)
)
self._m.tol = tol
return
@setDefault(passed_kwargs = minuit_def)
def fit(self,tmin = None, tmax = None, function = 'tesresponse',
minos = 1., parscan = 'none', fmax = 1e6, norder = 3,
dvdt_thr = -25., maxcomp = 3, v_thr=0.,
**kwargs):
"""
Fit the time series
{options}
:param tmin: float
Minimum time in time series. If None, don't use a limit. Default: None
:param tmax:
Maximum time in time series. If None, don't use a limit. Default: None
:param function: str
either "tesresponse" or "expflare". Determines the function that is fit to the data.
Default: "tesresponse"
:param minos: float
Confidence level in sigma for which minos errors are calculated. Default: 1.
:param parscan: str
either 'none' or name of parameter. If name of parameter, the likelihood is profiled
for this parameter and the profile likelihood is returned. Default: 'none'
:param fmax: float
Maximum frequency for filter (used to find trigger time)
:param norder: int
Order of filter (used to find trigger time)
:param dvdt_thr: float
threshold to find trigger from derivative in mV / micro sec. Default: -25.
:param v_thr: float
threshold to find trigger from time series in V. Default: 0.
:param maxcomp: int
Maximum pulse components allowed in one trigger window.
:param kwargs:
Additional key word arguments passed to minuit.
:return:
Dictionary with results
"""
if np.isscalar(tmin) and np.isscalar(tmax):
m = (self.t >= tmin) & (self.t < tmax)
elif np.isscalar(tmax):
m = (self.t < tmax)
elif np.isscalar(tmin):
m = (self.t >= tmin)
if np.isscalar(tmin) or np.isscalar(tmax) == float:
self._t = self._t[m]
self._v = self._v[m]
self._dv = self._dv[m]
t0s, _, _ = build_trigger_windows(self._t / 1e6, self._v / 1e3,
self._fSample,
thr=dvdt_thr,
thr_v=v_thr,
fmax=fmax,
norder=norder)
t0s = np.array(t0s) * 1e6 # convert back to micro s
ntrigger = t0s.size
logging.info("Within window, found {0:n} point(s) satisfying trigger criteria".format(ntrigger))
t1 = time.time()
aic, chi2, nPars, vals, errs, fitargs, dof = [], [], [], [], [], [], []
# loop through trigger times
#for i, t0 in enumerate(t0s):
i = 0
while i < ntrigger and i < maxcomp:
f = TimeLine(numcomp=i+1, function=function)
kwargs['pinit']['t0_{0:03n}'.format(i)] = t0s[i]
kwargs['limits']['t0_{0:03n}'.format(i)] = [self._t.min(), self._t.max()]
if i > 0:
if self._m.migrad_ok():
kwargs['pinit'].update({k : self._m.values[k] for k in kwargs['pinit'].keys() \
if k in self._m.values.keys()})
for k in ['td', 'tr', 'A']:
kwargs['pinit']['{0:s}_{1:03n}'.format(k, i)] = kwargs['pinit']['{0:s}_000'.format(k)]
kwargs['limits']['{0:s}_{1:03n}'.format(k, i)] = kwargs['limits']['{0:s}_000'.format(k)]
kwargs['fix'] = {k: False for k in kwargs['pinit'].keys()}
kwargs['islog'] = {k: False for k in kwargs['pinit'].keys()}
self._f = lambda t, **params : f(t, **params)
fitarg = self.fill_fitarg(**kwargs)
logging.debug(fitarg)
self.run_migrad(fitarg, **kwargs)
npar = np.sum([np.invert(self._m.fitarg[k]) for k in self._m.fitarg.keys() if 'fix' in k])
try:
self._m.hesse()
logging.debug("Hesse matrix calculation finished")
except RuntimeError as e:
logging.warning(
"*** Hesse matrix calculation failed: {0}".format(e)
)
logging.debug(self._m.fval)
self.__repeat_migrad(**kwargs)
logging.debug(self._m.fval)
fmin = self._m.get_fmin()
if not fmin.hesse_failed:
try:
self.corr = self._m.np_matrix(correlation=True)
except:
self.corr = -1
logging.debug(self._m.values)
if self._m.migrad_ok():
if parscan in self.parnames:
parscan, llh, bf, ok = self.llhscan(parscan,
bounds = kwargs['scan_bound'],
steps = kwargs['steps'],
log = False
)
self._m.fitarg['fix_{0:s}'.format(parscan)] = False
if np.min(llh) < self._m.fval:
idx = np.argmin(llh)
if ok[idx]:
logging.warning("New minimum found in objective function scan!")
fitarg = deepcopy(self._m.fitarg)
for k in self.parnames:
fitarg[k] = bf[idx][k]
fitarg['fix_{0:s}'.format(parscan)] = True
kwargs['scipy'] = False
self.run_migrad(fitarg, **kwargs)
if minos:
for k in self._m.values.keys():
if kwargs['fix'][k]:
continue
self._m.minos(k,minos)
logging.debug("Minos finished")
else:
self.__print_failed_fit()
# terminate if we have tested all components
if i == t0s.size - 1 or i == maxcomp - 1:
return dict(chi2 = self._m.fval,
value = dict(self._m.values),
error = dict(self._m.errors),
aic = 2. * npar + self._m.fval,
dof = self._t.size - npar,
npar = npar,
fitarg = self._m.fitarg,
numcomp = i + 1,
fit_ok = False
)
vals.append(dict(self._m.values))
errs.append(dict(self._m.errors))
fitargs.append(self._m.fitarg)
nPars.append(npar)
aic.append(2. * npar + self._m.fval)
dof.append(self._t.size - nPars[-1])
chi2.append(self._m.fval)
i+=1
# bad fit, add additional trigger time
#if chi2[-1] / dof[-1] > 2.5 and i >= ntrigger:
if pvalue(dof[-1], chi2[-1]) < 0.01 and i >= ntrigger:
logging.info("bad fit and all trigger times added, adding additional component")
idresmax = np.argmax(np.abs((self._v - self._f(self._t, **self._m.fitarg))/self._dv))
t0s = np.append(t0s, self._t[idresmax])
# select best fit
ibest = np.argmin(aic)
logging.info('fit took: {0}s'.format(time.time() - t1))
logging.info("Best AIC = {0:.2f} for {1:n} components".format(aic[ibest], ibest + 1))
for k in vals[ibest].keys():
if kwargs['fix'][k]:
err = np.nan
else:
err = fitargs[ibest]['error_{0:s}'.format(k)]
val = fitargs[ibest]['{0:s}'.format(k)]
logging.info('best fit {0:s}: {1:.5e} +/- {2:.5e}'.format(k,val,err))
result = dict(chi2 = chi2[ibest],
value = vals[ibest],
error = errs[ibest],
aic = aic[ibest],
dof = dof[ibest],
npar = nPars[ibest],
fitarg = fitargs[ibest],
numcomp = ibest + 1,
fit_ok = True
)
if minos:
result['minos'] = self._m.merrors
if parscan in self.parnames:
result['parscan'] = (r, llh)
return result
def llhscan(self, parname, bounds, steps, log = False):
"""
Perform a manual scan of the objective function for one parameter
(inspired by mnprofile)
Parameters
----------
parname: str
parameter that is scanned
bounds: list or tuple
scan bounds for parameter
steps: int
number of scanning steps
{options}
log: bool
if true, use logarithmic scale
Returns
-------
tuple of 4 lists containing the scan values, likelihood values,
best fit values at each scanning step, migrad_ok status
"""
llh, pars, ok = [],[],[]
if log:
values = np.logscape(np.log10(bounds[0]),np.log10(bounds[1]), steps)
else:
values = np.linspace(bounds[0], bounds[1], steps)
for i,v in enumerate(values):
fitarg = deepcopy(self._m.fitarg)
fitarg[parname] = v
fitarg['fix_{0:s}'.format(parname)] = True
string_args = ", ".join(self.parnames)
global f # needs to be global for eval to find it
f = lambda *args: self.__calcObjFunc(*args)
cmd_string = "lambda %s: f(%s)" % (string_args, string_args)
minimize_f = eval(cmd_string, globals(), locals())
m = minuit.Minuit(minimize_f,
print_level=0, forced_parameters=self._m.parameters,
pedantic=False, **fitarg)
m.migrad()
llh.append(m.fval)
pars.append(m.values)
ok.append(m.migrad_ok())
return values, np.array(llh), pars, ok | nilq/baby-python | python |
import BaseHTTPServer
import time
import sys
import SocketServer, os
import md5
try:
import json
except:
import simplejson as json
HOST_NAME = ''
PORT_NUMBER = 8000
SERVER_VERSION = '1.0.1'
SSDP_PORT = 1900
SSDP_MCAST_ADDR = '239.255.255.250'
savedDescription = {}
delay = {}
counter = {}
userAgentHash = {}
def keep_running():
return True
class ThreadingHTTPServer(SocketServer.ThreadingMixIn,
SocketServer.TCPServer, BaseHTTPServer.HTTPServer):
pass
class RedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
path = self.path[1:]
try:
path.index('get_description')
except ValueError:
try:
path.index('get_counter')
except ValueError:
try:
path.index('version')
except ValueError:
self.send_response(200)
self.send_header('Content-Type','text/plain; charset="utf-8"')
self.send_header('Content-Length',str(0))
self.end_headers()
print('no stuff given')
else:
self.send_response(200)
self.send_header('Access-Control-Allow-Origin','*')
self.send_header('Content-Length',str(len(SERVER_VERSION)))
self.end_headers()
self.wfile.write(SERVER_VERSION)
self.wfile.close()
print('version check: ',SERVER_VERSION)
else:
if(path[:path.index('?')] == 'get_counter'):
id = int(path[path.index('?')+1:])
try:
self.send_response(200)
self.send_header('Access-Control-Allow-Origin','*')
DATA = str(counter[id])
self.send_header('Content-Length',str(len(DATA)))
self.end_headers()
self.wfile.write(DATA)
self.wfile.close()
except KeyError:
self.send_response(404)
self.send_header('Access-Control-Allow-Origin','*')
self.send_header('Content-Length',str(len('wrong id!')))
self.end_headers()
self.wfile.write('wrong id!')
self.wfile.close()
else:
if(path[:path.index('?')] == 'get_description'):
id = int(path[path.index('?')+1:])
try:
self.send_response(200)
if(delay[id] > 0):
time.sleep(delay[id])
print('message delayed: ', delay[id])
self.send_header('Access-Control-Allow-Origin','*')
self.send_header('Content-Length',str(len(savedDescription[id])))
self.end_headers()
self.wfile.write(savedDescription[id])
self.wfile.close()
if(userAgentHash[id] == md5.md5(str(self.client_address[0]) + str(self.headers['user-agent'])).hexdigest()):
global counter
counter[id] = counter[id] + 1
print('description given',id,counter[id])
except KeyError:
print('404: ',path)
self.send_response(404)
self.send_header('Access-Control-Allow-Origin','*')
self.send_header('Content-Length',str(len('wrong id!')))
self.end_headers()
self.wfile.write('wrong id!')
self.wfile.close()
else:
self.send_response(404)
self.send_header('Content-Length',str(0))
self.end_headers()
print('no stuff given')
def do_POST(self):
self.send_response(200)
self.send_header('Access-Control-Allow-Origin','*')
self.end_headers()
length = int(self.headers.getheader('Content-Length'))
if(length > 0):
res = self.rfile.read(length)
try:
params = json.loads(res)
except ValueError, err:
print 'ERROR:', err
params = {}
else:
params = {}
if(self.path == '/set_description'):
try:
params['description']
params['id']
except KeyError:
print('description error - no proper param!')
pass
else:
global savedDescription
global counter
global userAgentHash
try:
savedDescription[params['id']]
except KeyError:
counter[params['id']] = 0
else:
if(savedDescription[params['id']] != params['description']):
counter[params['id']] = 0
savedDescription[params['id']] = params['description']
userAgentHash[params['id']] = md5.md5(str(self.client_address[0]) + str(self.headers['user-agent'])).hexdigest()
try:
params['delay']
except KeyError:
delay[params['id']] = 0
else:
delay[params['id']] = float(params['delay'])/1000.0
pass
elif(self.path == '/delete_description'):
try:
params['id']
except KeyError:
print('id error - no proper param!')
pass
else:
global savedDescription
del savedDescription[params['id']]
print('saved_descrition cleared')
pass
elif(self.path == '/broadcast_msg'):
if(not params['data']):
self.wfile.write('error with params: no "data"!')
self.wfile.close()
print('broadcast_msg error - no proper param!')
pass
else:
self.wfile.write('message sent')
self.wfile.close()
ssdp_multicast(params['data'], self.request.getsockname())
pass
def ssdp_multicast(buf, interface_address):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print("IP_MULTICAST_IF: " + str(interface_address))
s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(interface_address[0]))
s.sendto(buf, (SSDP_MCAST_ADDR, SSDP_PORT))
if __name__ == '__main__':
server_class = ThreadingHTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), RedirectHandler)
print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
s.bind(('', SSDP_PORT))
import struct
mreqn = struct.pack(
'4s4si',
socket.inet_aton(SSDP_MCAST_ADDR),
socket.inet_aton('0.0.0.0'),
0)
s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreqn)
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER) | nilq/baby-python | python |
'''
In this exercise, you'll use the Baby Names Dataset (from data.gov) again. This time, both DataFrames names_1981 and names_1881 are loaded without specifying an Index column (so the default Indexes for both are RangeIndexes).
You'll use the DataFrame .append() method to make a DataFrame combined_names. To distinguish rows from the original two DataFrames, you'll add a 'year' column to each with the year (1881 or 1981 in this case). In addition, you'll specify ignore_index=True so that the index values are not used along the concatenation axis. The resulting axis will instead be labeled 0, 1, ..., n-1, which is useful if you are concatenating objects where the concatenation axis does not have meaningful indexing information.
'''
# Add 'year' column to names_1881 and names_1981
names_1881['year'] = 1881
names_1981['year'] = 1981
# Append names_1981 after names_1881 with ignore_index=True: combined_names
combined_names = names_1881.append(names_1981, ignore_index=True)
# Print shapes of names_1981, names_1881, and combined_names
print(names_1981.shape)
print(names_1881.shape)
print(combined_names.shape)
# Print all rows that contain the name 'Morgan'
print(combined_names.loc[combined_names['name'] == 'Morgan']) | nilq/baby-python | python |
#!/usr/bin/env python3
import os
telamon_root = os.path.realpath("../../")
tuning_path = os.path.realpath(".")
setting_path = tuning_path + "/settings/"
spec = {
"log_file": str,
"num_workers": int,
"stop_bound": float,
"timeout": float,
"distance_to_best": float,
"algorithm": {
"type": ("bandit", ),
"new_nodes_order": ("api", "random", "bound", "weighted_random"),
"old_nodes_order": ("bound", "bandit", "weighted_random"),
"threshold": int,
"delta": float,
"monte_carlo": bool,
},
}
def check(value, *, path=(), spec=spec):
"""Check that a value adheres to a specification.
Entries in the specification can be:
- A tuple of allowed values: the provided `value` must be one of these
- A type: the provided `value` must have that type
- A dict: the provided `value` must be a dict which has only keys defined
in the `spec` (some of the `spec` keys may be missing from the `value`
dict). Each provided value in the dict will be checked recursively with
the corresponding entry in the spec.
All entries in `value` are optional (i.e. can be `None`), unless the
corresponding entry in the specification is a `dict`.
Args:
value: The value to check.
path: The path in the toplevel object leading to this
value. This is used to make more legible error messages.
spec: The specification to check the value against. See above
for explanations on the format.
Raises:
ValueError: When the value does not match the specification.
"""
if isinstance(spec, dict):
if not isinstance(value, dict):
raise ValueError(
"Key {} should be a dict; got {}".format(
".".join(path), value))
invalid = set(value.keys()) - set(spec.keys())
if invalid:
invalid_keys = sorted(['.'.join(path + (key, )) for key in invalid])
raise ValueError(
"Key{} {} {} invalid".format(
"" if len(invalid_keys) == 1 else "s",
' and '.join(filter(None, [
', '.join(invalid_keys[:-1]),
invalid_keys[-1],
])),
"is" if len(invalid_keys) == 1 else "are"))
for key, spec_value in spec.items():
check(value.get(key), path=path + (key, ), spec=spec_value)
elif value is None:
pass
elif isinstance(spec, type):
if not isinstance(value, spec):
raise ValueError(
"Key {} should be a {}; got {!r}".format(
".".join(path), spec.__name__, value))
elif isinstance(spec, tuple):
if value not in spec:
raise ValueError(
"Key {} should be one of {}; got {!r}".format(
".".join(path), ", ".join(map(repr, spec)), value))
else:
raise AssertionError(
"Invalid spec: {}".format(spec))
def serialize_value(value):
"""Serialize a single value.
This is used instead of a single-shot `.format()` call because some values
need special treatment for being serialized in YAML; notably, booleans must
be written as lowercase strings, and floats exponents must not start with a
0.
"""
if isinstance(value, bool):
return repr(value).lower()
elif isinstance(value, float):
return "{0:.16}".format(value).replace("e+0", "e+").replace("e-0", "e-")
else:
return repr(value)
def serialize(f, key, value):
"""Serialize a (key, value) pair into a file."""
if isinstance(value, dict):
f.write("[{}]\n".format(key))
for k, v in value.items():
serialize(f, k, v)
elif value is not None:
f.write("{} = {}\n".format(key, serialize_value(value)))
def create_setting_file(options_dict, filename):
try:
check(options_dict)
except ValueError as e:
print("Invalid options dict: {}".format(e))
return
with open(filename, "w+") as f:
for key, value in options_dict.items():
serialize(f, key, value)
def clear_directory(folder):
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
except Exception as e:
print(e)
filename = "test_py.log"
opts = {
"num_workers": 24,
"timeout": 150.,
"algorithm": {
"type": "bandit",
"monte_carlo": True,
}
}
if __name__ == "__main__":
if not os.path.exists(setting_path):
os.makedirs(setting_path)
clear_directory(setting_path)
for i in range(8):
opts["algorithm"]["delta"] = pow(2, i) * 0.00001
for j in range(1, 4):
opts["algorithm"]["threshold"] = j * 10
filename = ("d" + "-" + "{:3e}".format(opts["algorithm"]["delta"]) + "_" + "t"
+ "{}".format(opts["algorithm"]["threshold"]) +".toml")
create_setting_file(opts, setting_path + filename)
| nilq/baby-python | python |
#-*-coding:utf-8-*-
from pyspark.sql.types import IntegerType, TimestampType
from pyspark.sql.functions import *
from base import spark
from utils import uuidsha
columns = [
col('docu_dk').alias('alrt_docu_dk'),
col('docu_nr_mp').alias('alrt_docu_nr_mp'),
col('docu_orgi_orga_dk_responsavel').alias('alrt_orgi_orga_dk'),
col('elapsed').alias('alrt_dias_referencia')
]
columns_alias = [
col('alrt_docu_dk'),
col('alrt_docu_nr_mp'),
col('alrt_orgi_orga_dk'),
col('alrt_dias_referencia')
]
key_columns = [
col('alrt_docu_dk')
]
def alerta_prcr(options):
# data do fato será usada para a maioria dos cálculos
# Caso a data do fato seja NULL, ou seja maior que a data de cadastro, usar cadastro como data do fato
# Apenas códigos de pacotes de PIPs
# Mantém-se a data do fato original (mesmo NULL ou maior que dt cadastro) para a tabela de metadados do cálculo
doc_pena = spark.sql("""
SELECT docu_dk, docu_nr_mp, docu_nr_externo, docu_tx_etiqueta, docu_dt_fato as docu_dt_fato_original,
CASE WHEN docu_dt_fato < docu_dt_cadastro THEN docu_dt_fato ELSE docu_dt_cadastro END as docu_dt_fato,
docu_dt_cadastro, docu_orgi_orga_dk_responsavel,
cls.id as cldc_dk,
cls.cod_mgp as cldc_ds_classe,
cls.hierarquia as cldc_ds_hierarquia,
tpa.id,
tpa.artigo_lei,
tpa.max_pena,
tpa.nome_delito,
tpa.multiplicador,
tpa.abuso_menor
FROM documentos_ativos
LEFT JOIN {0}.mmps_classe_docto cls ON cls.id = docu_cldc_dk
JOIN {1}.mcpr_assunto_documento ON docu_dk = asdo_docu_dk
JOIN {0}.tb_penas_assuntos tpa ON tpa.id = asdo_assu_dk
JOIN {0}.atualizacao_pj_pacote ON docu_orgi_orga_dk_responsavel = id_orgao
WHERE docu_dt_cadastro >= '2010-01-01'
AND max_pena IS NOT NULL
AND cod_pct IN (200, 201, 202, 203, 204, 205, 206, 207, 208, 209)
AND asdo_dt_fim IS NULL -- tira assuntos que acabaram
""".format(options['schema_exadata_aux'], options['schema_exadata'])
)
doc_pena.createOrReplaceTempView('DOC_PENA')
# Calcula tempos de prescrição a partir das penas máximas
# Caso um dos assuntos seja multiplicador, multiplicar as penas pelo fator
doc_prescricao = spark.sql("""
WITH PENA_FATORES AS (
SELECT docu_dk, EXP(SUM(LN(max_pena))) AS fator_pena, concat_ws(', ', collect_list(nome_delito)) AS delitos_multiplicadores
FROM DOC_PENA
WHERE multiplicador = 1
GROUP BY docu_dk
)
SELECT *,
CASE
WHEN max_pena_fatorado < 1 THEN 3
WHEN max_pena_fatorado < 2 THEN 4
WHEN max_pena_fatorado < 4 THEN 8
WHEN max_pena_fatorado < 8 THEN 12
WHEN max_pena_fatorado < 12 THEN 16
ELSE 20 END AS tempo_prescricao
FROM (
SELECT
P.*,
CASE WHEN fator_pena IS NOT NULL THEN max_pena * fator_pena ELSE max_pena END AS max_pena_fatorado,
fator_pena,
delitos_multiplicadores
FROM DOC_PENA P
LEFT JOIN PENA_FATORES F ON F.docu_dk = P.docu_dk
WHERE multiplicador = 0
) t
""")
doc_prescricao.createOrReplaceTempView('DOC_PRESCRICAO')
# Se o acusado tiver < 21 ou >= 70, seja na data do fato ou na data presente, multiplicar tempo_prescricao por 0.5
doc_prescricao_fatorado = spark.sql("""
WITH PRESCRICAO_FATORES AS (
SELECT docu_dk, investigado_pess_dk, investigado_nm,
CASE WHEN NOT (dt_compare >= dt_21 AND current_timestamp() < dt_70) THEN 0.5 ELSE NULL END AS fator_prescricao
FROM (
SELECT DISTINCT
docu_dk,
pesf_pess_dk as investigado_pess_dk,
pesf_nm_pessoa_fisica as investigado_nm,
add_months(pesf_dt_nasc, 21 * 12) AS dt_21,
add_months(pesf_dt_nasc, 70 * 12) AS dt_70,
docu_dt_fato AS dt_compare
FROM DOC_PRESCRICAO
JOIN {0}.mcpr_personagem ON pers_docu_dk = docu_dk
JOIN {0}.mcpr_pessoa_fisica ON pers_pesf_dk = pesf_pess_dk
WHERE pers_tppe_dk IN (290, 7, 21, 317, 20, 14, 32, 345, 40, 5, 24)
AND pesf_nm_pessoa_fisica != 'MP'
) t
)
SELECT P.*,
CASE WHEN fator_prescricao IS NOT NULL THEN tempo_prescricao * fator_prescricao ELSE tempo_prescricao END AS tempo_prescricao_fatorado,
fator_prescricao IS NOT NULL AS investigado_maior_70_menor_21,
investigado_pess_dk,
investigado_nm
FROM DOC_PRESCRICAO P
LEFT JOIN PRESCRICAO_FATORES F ON F.docu_dk = P.docu_dk
""".format(options['schema_exadata']))
doc_prescricao_fatorado.createOrReplaceTempView('DOC_PRESCRICAO_FATORADO')
# Calcular data inicial de prescrição
# Casos em que houve rescisão de acordo de não persecução penal, data inicial é a data do andamento
spark.sql("""
SELECT vist_docu_dk, pcao_dt_andamento
FROM vista
JOIN {0}.mcpr_andamento ON vist_dk = pcao_vist_dk
JOIN {0}.mcpr_sub_andamento ON stao_pcao_dk = pcao_dk
WHERE stao_tppr_dk = 7920
AND year_month >= 201901
""".format(options['schema_exadata'])
).createOrReplaceTempView('DOCS_ANPP')
# Casos de abuso de menor, data inicial é a data de 18 anos do menor,
# no caso em que o menor tinha menos de 18 na data do fato/cadastro
# Prioridade de data inicial: data de 18 anos (caso abuso menor), rescisão de acordo ANPP, dt_fato
dt_inicial = spark.sql("""
WITH DOCS_ABUSO_MENOR AS (
SELECT docu_dk, MAX(dt_18_anos) AS dt_18_anos
FROM (
SELECT docu_dk, CASE WHEN dt_18_anos > docu_dt_fato THEN dt_18_anos ELSE NULL END AS dt_18_anos
FROM DOC_PRESCRICAO_FATORADO P
JOIN {0}.mcpr_personagem ON pers_docu_dk = docu_dk
JOIN (
SELECT
PF.*,
cast(add_months(pesf_dt_nasc, 18*12) as timestamp) AS dt_18_anos
FROM {0}.mcpr_pessoa_fisica PF
) t ON pers_pesf_dk = pesf_pess_dk
WHERE abuso_menor = 1
AND pers_tppe_dk IN (3, 13, 18, 6, 248, 290)
) t2
GROUP BY docu_dk
)
SELECT P.*,
CASE
WHEN dt_18_anos IS NOT NULL AND abuso_menor = 1 THEN dt_18_anos
WHEN pcao_dt_andamento IS NOT NULL THEN pcao_dt_andamento
ELSE docu_dt_fato END AS dt_inicial_prescricao,
dt_18_anos AS vitima_menor_mais_jovem_dt_18_anos,
pcao_dt_andamento AS dt_acordo_npp
FROM DOC_PRESCRICAO_FATORADO P
LEFT JOIN DOCS_ANPP ON vist_docu_dk = docu_dk
LEFT JOIN DOCS_ABUSO_MENOR M ON M.docu_dk = P.docu_dk
""".format(options['schema_exadata']))
dt_inicial.createOrReplaceTempView('DOCS_DT_INICIAL_PRESCRICAO')
# Data de prescrição = data inicial de prescrição + tempo de prescrição
resultado = spark.sql("""
SELECT
D.*,
cast(add_months(dt_inicial_prescricao, tempo_prescricao_fatorado * 12) as timestamp) AS data_prescricao
FROM DOCS_DT_INICIAL_PRESCRICAO D
""").\
withColumn("elapsed", lit(datediff(current_date(), 'data_prescricao')).cast(IntegerType()))
resultado.createOrReplaceTempView('TEMPO_PARA_PRESCRICAO')
spark.catalog.cacheTable("TEMPO_PARA_PRESCRICAO")
# Tabela de detalhes dos alertas, para ser usada no overlay do alerta, e também para debugging
spark.sql("""
SELECT
docu_dk AS adpr_docu_dk,
investigado_pess_dk as adpr_investigado_pess_dk,
investigado_nm as adpr_investigado_nm,
nome_delito as adpr_nome_delito,
id as adpr_id_assunto,
artigo_lei as adpr_artigo_lei,
abuso_menor as adpr_abuso_menor,
max_pena as adpr_max_pena,
delitos_multiplicadores as adpr_delitos_multiplicadores,
fator_pena as adpr_fator_pena,
max_pena_fatorado as adpr_max_pena_fatorado,
tempo_prescricao as adpr_tempo_prescricao,
investigado_maior_70_menor_21 as adpr_investigado_prescricao_reduzida,
tempo_prescricao_fatorado as adpr_tempo_prescricao_fatorado,
vitima_menor_mais_jovem_dt_18_anos as adpr_dt_18_anos_menor_vitima,
dt_acordo_npp as adpr_dt_acordo_npp,
docu_dt_fato_original as adpr_docu_dt_fato,
docu_dt_cadastro as adpr_docu_dt_cadastro,
cast(dt_inicial_prescricao as string) as adpr_dt_inicial_prescricao,
data_prescricao as adpr_dt_final_prescricao,
elapsed as adpr_dias_prescrito
FROM TEMPO_PARA_PRESCRICAO
""").write.mode('overwrite').saveAsTable('{}.{}'.format(
options['schema_alertas'],
options['prescricao_tabela_detalhe']
)
)
LIMIAR_PRESCRICAO_PROXIMA = -options['prescricao_limiar']
subtipos = spark.sql("""
SELECT T.*,
CASE
WHEN elapsed > 0 THEN 2 -- prescrito
WHEN elapsed <= {LIMIAR_PRESCRICAO_PROXIMA} THEN 0 -- nem prescrito nem proximo
ELSE 1 -- proximo de prescrever
END AS status_prescricao
FROM TEMPO_PARA_PRESCRICAO T
""".format(
LIMIAR_PRESCRICAO_PROXIMA=LIMIAR_PRESCRICAO_PROXIMA)
)
max_min_status = subtipos.groupBy(columns[:-1]).agg(min('status_prescricao'), max('status_prescricao'), min('elapsed')).\
withColumnRenamed('max(status_prescricao)', 'max_status').\
withColumnRenamed('min(status_prescricao)', 'min_status').\
withColumnRenamed('min(elapsed)', 'alrt_dias_referencia')
max_min_status.createOrReplaceTempView('MAX_MIN_STATUS')
# Os WHEN precisam ser feitos na ordem PRCR1, 2, 3 e depois 4!
resultado = spark.sql("""
SELECT T.*,
CASE
WHEN min_status = 2 THEN 'PRCR1' -- todos prescritos
WHEN min_status = 1 THEN 'PRCR2' -- todos próximos de prescrever
WHEN max_status = 2 THEN 'PRCR3' -- subentende-se min=0 aqui, logo, algum prescrito (mas não todos próximos)
WHEN max_status = 1 THEN 'PRCR4' -- subentende-se min=0, logo, nenhum prescrito, mas algum próximo (não todos)
ELSE NULL -- não entra em nenhum caso (será filtrado)
END AS alrt_sigla,
CASE
WHEN min_status = 2 THEN 'Todos os crimes prescritos'
WHEN min_status = 1 THEN 'Todos os crimes próximos de prescrever'
WHEN max_status = 2 THEN 'Algum crime prescrito'
WHEN max_status = 1 THEN 'Algum crime próximo de prescrever'
ELSE NULL
END AS alrt_descricao
FROM MAX_MIN_STATUS T
""")
resultado = resultado.filter('alrt_sigla IS NOT NULL').select(columns_alias + ['alrt_sigla', 'alrt_descricao'])
resultado = resultado.withColumn('alrt_key', uuidsha(*key_columns))
return resultado
| nilq/baby-python | python |
from .base import BaseCLItest
class TestCliPush(BaseCLItest):
"""
askanna push
We expect to initiate a push action of our code to the AskAnna server
"""
verb = "push"
def test_command_push_base(self):
assert "push" in self.result.output
self.assertIn("push", self.result.output)
self.assertNotIn("noop", self.result.output)
| nilq/baby-python | python |
"""Class performing under-sampling based on the neighbourhood cleaning rule."""
# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# Christos Aridas
# License: MIT
from __future__ import division, print_function
from collections import Counter
import numpy as np
from ..base import BaseMulticlassSampler
from ..utils import check_neighbors_object
class NeighbourhoodCleaningRule(BaseMulticlassSampler):
"""Class performing under-sampling based on the neighbourhood cleaning
rule.
Parameters
----------
return_indices : bool, optional (default=False)
Whether or not to return the indices of the samples randomly
selected from the majority class.
random_state : int, RandomState instance or None, optional (default=None)
If int, random_state is the seed used by the random number generator;
If RandomState instance, random_state is the random number generator;
If None, the random number generator is the RandomState instance used
by np.random.
size_ngh : int, optional (default=None)
Size of the neighbourhood to consider to compute the average
distance to the minority point samples.
NOTE: size_ngh is deprecated from 0.2 and will be replaced in 0.4
Use ``n_neighbors`` instead.
n_neighbors : int or object, optional (default=3)
If int, size of the neighbourhood to consider in order to make
the comparison between each samples and their NN.
If object, an estimator that inherits from
`sklearn.neighbors.base.KNeighborsMixin` that will be used to find
the k_neighbors.
n_jobs : int, optional (default=1)
The number of threads to open if possible.
Attributes
----------
min_c_ : str or int
The identifier of the minority class.
max_c_ : str or int
The identifier of the majority class.
stats_c_ : dict of str/int : int
A dictionary in which the number of occurences of each class is
reported.
X_shape_ : tuple of int
Shape of the data `X` during fitting.
Notes
-----
This class support multi-class.
Examples
--------
>>> from collections import Counter
>>> from sklearn.datasets import make_classification
>>> from imblearn.under_sampling import \
NeighbourhoodCleaningRule # doctest: +NORMALIZE_WHITESPACE
>>> X, y = make_classification(n_classes=2, class_sep=2,
... weights=[0.1, 0.9], n_informative=3, n_redundant=1, flip_y=0,
... n_features=20, n_clusters_per_class=1, n_samples=1000, random_state=10)
>>> print('Original dataset shape {}'.format(Counter(y)))
Original dataset shape Counter({1: 900, 0: 100})
>>> ncr = NeighbourhoodCleaningRule(random_state=42)
>>> X_res, y_res = ncr.fit_sample(X, y)
>>> print('Resampled dataset shape {}'.format(Counter(y_res)))
Resampled dataset shape Counter({1: 889, 0: 100})
References
----------
.. [1] J. Laurikkala, "Improving identification of difficult small classes
by balancing class distribution," Springer Berlin Heidelberg, 2001.
"""
def __init__(self,
return_indices=False,
random_state=None,
size_ngh=None,
n_neighbors=3,
n_jobs=1):
super(NeighbourhoodCleaningRule, self).__init__(
random_state=random_state)
self.return_indices = return_indices
self.size_ngh = size_ngh
self.n_neighbors = n_neighbors
self.n_jobs = n_jobs
def fit(self, X, y):
"""Find the classes statistics before to perform sampling.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
-------
self : object,
Return self.
"""
super(NeighbourhoodCleaningRule, self).fit(X, y)
self.nn_ = check_neighbors_object('n_neighbors', self.n_neighbors)
# set the number of jobs
self.nn_.set_params(**{'n_jobs': self.n_jobs})
return self
def _sample(self, X, y):
"""Resample the dataset.
Parameters
----------
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
-------
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampled : ndarray, shape (n_samples_new)
The corresponding label of `X_resampled`
idx_under : ndarray, shape (n_samples, )
If `return_indices` is `True`, a boolean array will be returned
containing the which samples have been selected.
"""
# Start with the minority class
X_min = X[y == self.min_c_]
y_min = y[y == self.min_c_]
# All the minority class samples will be preserved
X_resampled = X_min.copy()
y_resampled = y_min.copy()
# If we need to offer support for the indices
if self.return_indices:
idx_under = np.flatnonzero(y == self.min_c_)
# Fit the whole dataset
self.nn_.fit(X)
idx_to_exclude = []
# Loop over the other classes under picking at random
for key in self.stats_c_.keys():
# Get the sample of the current class
sub_samples_x = X[y == key]
# Get the samples associated
idx_sub_sample = np.flatnonzero(y == key)
# Find the NN for the current class
nnhood_idx = self.nn_.kneighbors(
sub_samples_x, return_distance=False)
# Get the label of the corresponding to the index
nnhood_label = (y[nnhood_idx] == key)
# Check which one are the same label than the current class
# Make an AND operation through the three neighbours
nnhood_bool = np.logical_not(np.all(nnhood_label, axis=1))
# If the minority class remove the majority samples
if key == self.min_c_:
# Get the index to exclude
idx_to_exclude += nnhood_idx[np.nonzero(np.logical_not(
nnhood_label[np.flatnonzero(nnhood_bool)]))].tolist()
else:
# Get the index to exclude
idx_to_exclude += idx_sub_sample[np.nonzero(
nnhood_bool)].tolist()
idx_to_exclude = np.unique(idx_to_exclude)
# Create a vector with the sample to select
sel_idx = np.ones(y.shape)
sel_idx[idx_to_exclude] = 0
# Exclude as well the minority sample since that they will be
# concatenated later
sel_idx[y == self.min_c_] = 0
# Get the samples from the majority classes
sel_x = X[np.flatnonzero(sel_idx), :]
sel_y = y[np.flatnonzero(sel_idx)]
# If we need to offer support for the indices selected
if self.return_indices:
idx_tmp = np.flatnonzero(sel_idx)
idx_under = np.concatenate((idx_under, idx_tmp), axis=0)
X_resampled = np.concatenate((X_resampled, sel_x), axis=0)
y_resampled = np.concatenate((y_resampled, sel_y), axis=0)
self.logger.info('Under-sampling performed: %s', Counter(y_resampled))
# Check if the indices of the samples selected should be returned too
if self.return_indices:
# Return the indices of interest
return X_resampled, y_resampled, idx_under
else:
return X_resampled, y_resampled
| nilq/baby-python | python |
import unittest
import numpy as np
from pavlidis import pavlidis
class TestPavlidis(unittest.TestCase):
def test_pixel(self):
case = np.zeros((3, 4), np.uint8)
case[1, 2] = True
result = pavlidis(case, 1, 2)
self.assertEqual(len(result), 1)
self.assertEqual(result[0, 0], 1)
self.assertEqual(result[0, 1], 2)
def test_edge(self):
# Test a 2x2 square within a 2x2 grid so that it might run off
# the edges
# This checks turning too
case = np.ones((2, 2), np.uint8)
result = pavlidis(case, 1, 0)
self.assertEqual(len(result), 4)
self.assertEqual(result[0, 0], 1)
self.assertEqual(result[0, 1], 0)
self.assertEqual(result[1, 0], 0)
self.assertEqual(result[1, 1], 0)
self.assertEqual(result[2, 0], 0)
self.assertEqual(result[2, 1], 1)
self.assertEqual(result[3, 0], 1)
self.assertEqual(result[3, 1], 1)
def test_bool_cast(self):
case = np.zeros((3, 3), bool)
case[1, 1] = True
result = pavlidis(case, 1, 1)
self.assertEqual(len(result), 1)
self.assertEqual(result[0, 0], 1)
self.assertEqual(result[0, 1], 1)
def test_interior_raises(self):
case = np.ones((3, 3), bool)
self.assertRaises(BaseException, pavlidis, case, 1, 1)
# The test names check the p1, p2 and p3 cases for the directions,
# xn (going towards -x), yn, xp and yp
#
def test_p1xn(self):
#
# 2 0
# | /
# 1
case = np.zeros((4, 4), np.uint8)
case[1, 1:3] = True
case[2, 1] = True
result = pavlidis(case, 1, 2)
self.assertEqual(len(result), 3)
self.assertEqual(result[0, 0], 1)
self.assertEqual(result[0, 1], 2)
self.assertEqual(result[1, 0], 2)
self.assertEqual(result[1, 1], 1)
def test_p2xn(self):
#
# 2
# |
# 1 - 0
case = np.zeros((4, 4), np.uint8)
case[2, 1:3] = True
case[1, 1] = True
result = pavlidis(case, 2, 2)
self.assertEqual(len(result), 3)
self.assertEqual(result[0, 0], 2)
self.assertEqual(result[0, 1], 2)
self.assertEqual(result[1, 0], 2)
self.assertEqual(result[1, 1], 1)
def test_p3xn(self):
#
# 1--2
# \
# 0
#
case = np.zeros((4, 4), np.uint8)
case[2, 2] = True
case[1, 1:3] = True
result = pavlidis(case, 2, 2)
self.assertEqual(len(result), 3)
self.assertEqual(result[0, 0], 2)
self.assertEqual(result[0, 1], 2)
self.assertEqual(result[1, 0], 1)
self.assertEqual(result[1, 1], 1)
def test_p1yn(self):
#
# 2--3
# \
# 1
# |
# 0
case = np.zeros((4, 4), np.uint8)
case[0:3, 2] = True
case[0, 1] = True
result = pavlidis(case, 2, 2)
self.assertEqual(len(result), 5)
self.assertEqual(result[1, 0], 1)
self.assertEqual(result[1, 1], 2)
self.assertEqual(result[2, 0], 0)
self.assertEqual(result[2, 1], 1)
def test_p2yn(self):
#
# 2 -- 3
# |
# 1
# |
# 0
case = np.zeros((4, 4), np.uint8)
case[1:, 1] = True
case[1, 2] = True
result = pavlidis(case, 3, 1)
self.assertEqual(len(result), 5)
self.assertEqual(result[1, 0], 2)
self.assertEqual(result[1, 1], 1)
self.assertEqual(result[2, 0], 1)
self.assertEqual(result[2, 1], 1)
def test_p3yn(self):
#
# 2
# /
# 1
# |
# 0
case = np.zeros((4, 4), np.uint8)
case[2:, 1] = True
case[1, 2] = True
result = pavlidis(case, 3, 1)
self.assertEqual(len(result), 4)
self.assertEqual(result[1, 0], 2)
self.assertEqual(result[1, 1], 1)
self.assertEqual(result[2, 0], 1)
self.assertEqual(result[2, 1], 2)
def test_p1xp(self):
# 3
# /|
# 1 - 2 4
# /
# 0
case = np.zeros((4, 4), np.uint8)
case[3, 0] = True
case[2, 1:4] = True
case[1, 3] = True
result = pavlidis(case, 3, 0)
self.assertEqual(len(result), 7)
self.assertEqual(result[2, 0], 2)
self.assertEqual(result[2, 1], 2)
self.assertEqual(result[3, 0], 1)
self.assertEqual(result[3, 1], 3)
def test_p2xp(self):
#
# 1 - 2 - 3
# /
# 0
case = np.zeros((4, 4), np.uint8)
case[3, 0] = True
case[2, 1:4] = True
result = pavlidis(case, 3, 0)
self.assertEqual(len(result), 6)
self.assertEqual(result[2, 0], 2)
self.assertEqual(result[2, 1], 2)
self.assertEqual(result[3, 0], 2)
self.assertEqual(result[3, 1], 3)
def test_p3xp(self):
#
# 1 - 2
# / \
# 0 3
case = np.zeros((4, 4), np.uint8)
case[3, 0] = True
case[2, 1:3] = True
case[3, 3] = True
result = pavlidis(case, 3, 0)
self.assertEqual(len(result), 6)
self.assertEqual(result[2, 0], 2)
self.assertEqual(result[2, 1], 2)
self.assertEqual(result[3, 0], 3)
self.assertEqual(result[3, 1], 3)
def test_p1yp(self):
#
# 1 - 2
# / |
# 0 3
# \
# 5--4
case = np.zeros((4, 4), np.uint8)
case[2, 0] = True
case[1, 1] = True
case[1, 2] = True
case[2, 2] = True
case[3, 2:] = True
result = pavlidis(case, 2, 0)
self.assertEqual(result[3, 0], 2)
self.assertEqual(result[3, 1], 2)
self.assertEqual(result[4, 0], 3)
self.assertEqual(result[4, 1], 3)
def test_p2yp(self):
#
# 1 - 2
# / |
# 0 3
# |
# 5 -- 4
case = np.zeros((4, 4), np.uint8)
case[2, 0] = True
case[1, 1] = True
case[1, 2] = True
case[2, 2] = True
case[3, 1:3] = True
result = pavlidis(case, 2, 0)
self.assertEqual(result[3, 0], 2)
self.assertEqual(result[3, 1], 2)
self.assertEqual(result[4, 0], 3)
self.assertEqual(result[4, 1], 2)
def test_p3yp(self):
#
# 1 - 2
# / |
# 0 3
# |
# 5 -- 4
case = np.zeros((4, 4), np.uint8)
case[2, 0] = True
case[1, 1] = True
case[1, 2] = True
case[2, 2] = True
case[3, 1] = True
result = pavlidis(case, 2, 0)
self.assertEqual(result[3, 0], 2)
self.assertEqual(result[3, 1], 2)
self.assertEqual(result[4, 0], 3)
self.assertEqual(result[4, 1], 1)
def test_issue1_regression(self):
small = np.zeros((4, 4))
small[1, 1] = True
small[2, 1] = True
self.assertEqual(len(pavlidis(small, 1, 1)), 2)
def test_issue2_regression(self):
small = np.zeros((10, 10))
small[4, 5:] = True
small[5, 4:] = True
small[6, 3:] = True
small[7, 2:] = True
self.assertGreater(len(pavlidis(small, 4, 5)), 4)
if __name__ == '__main__':
unittest.main()
| nilq/baby-python | python |
import urllib.parse
from agent import source, pipeline
from agent.pipeline.config.stages.source.jdbc import JDBCSource
class SolarWindsScript(JDBCSource):
JYTHON_SCRIPT = 'solarwinds.py'
SOLARWINDS_API_ADDRESS = '/SolarWinds/InformationService/v3/Json/Query'
def get_config(self) -> dict:
with open(self.get_jython_file_path()) as f:
return {
'scriptConf.params': [
{'key': 'PIPELINE_NAME', 'value': self.pipeline.name},
{'key': 'QUERY', 'value': pipeline.jdbc.query.SolarWindsBuilder(self.pipeline).build()},
{
'key': 'SOLARWINDS_API_URL',
'value': urllib.parse.urljoin(
self.pipeline.source.config[source.SolarWindsSource.URL],
self.SOLARWINDS_API_ADDRESS
)
},
{'key': 'API_USER', 'value': self.pipeline.source.config[source.SolarWindsSource.USERNAME]},
{'key': 'API_PASSWORD', 'value': self.pipeline.source.config[source.SolarWindsSource.PASSWORD]},
{'key': 'INTERVAL_IN_SECONDS', 'value': str(self.pipeline.interval)},
{'key': 'DELAY_IN_SECONDS', 'value': str(self.pipeline.delay)},
{'key': 'DAYS_TO_BACKFILL', 'value': self.pipeline.days_to_backfill},
{'key': 'QUERY_TIMEOUT', 'value': str(self.pipeline.source.query_timeout)},
{
'key': 'MONITORING_URL',
'value': urllib.parse.urljoin(
self.pipeline.streamsets.agent_external_url,
f'/monitoring/source_http_error/{self.pipeline.name}/'
)
},
{'key': 'VERIFY_SSL', 'value': '1' if self.pipeline.source.config.get('verify_ssl', True) else ''},
],
'script': f.read()
}
| nilq/baby-python | python |
from logging import getLogger
import multiprocessing
from pathlib import Path
import random
import traceback
from typing import Union
import networkx as nx
from remake.remake_exceptions import RemakeError
from remake.special_paths import SpecialPaths
from remake.task import Task
from remake.task_control import TaskControl
from remake.task_query_set import TaskQuerySet
from remake.setup_logging import setup_stdout_logging
logger = getLogger(__name__)
class Remake:
"""Core class. A remakefile is defined by creating an instance of Remake.
Acts as an entry point to running all tasks via python, and retrieving information about the state of any task.
Contains a list of all tasks added by any `TaskRule`.
A remakefile must contain:
>>> demo = Remake()
This must be near the top of the file - after the imports but before any `TaskRule` is defined.
"""
remakes = {}
current_remake = {}
def __init__(self, name: str = None, config: dict = None, special_paths: SpecialPaths = None):
"""Constructor.
:param name: name to use for remakefile (defaults to its filename)
:param config: configuration for executors
:param special_paths: special paths to use for all input/output filenames
"""
setup_stdout_logging('INFO', colour=True)
if not name:
stack = next(traceback.walk_stack(None))
frame = stack[0]
name = frame.f_globals['__file__']
# This is needed for when MultiprocExecutor makes its own Remakes in worker procs.
if multiprocessing.current_process().name == 'MainProcess':
if name in Remake.remakes:
# Can happen on ipython run remakefile.
# Can also happen on tab completion of Remake obj.
# e.g. in remake/examples/ex1.py:
# ex1.Bas<tab>
# traceback.print_stack()
logger.info(f'Remake {name} added twice')
Remake.remakes[name] = self
else:
logger.debug(f'Process {multiprocessing.current_process().name}')
logger.debug(Remake.current_remake)
logger.debug(Remake.remakes)
Remake.current_remake[multiprocessing.current_process().name] = self
self.config = config
if not special_paths:
special_paths = SpecialPaths()
self.special_paths = special_paths
self.task_ctrl = TaskControl(name, config, special_paths)
self.rules = []
self.tasks = TaskQuerySet(task_ctrl=self.task_ctrl)
@property
def name(self):
return self.task_ctrl.name
@property
def pending_tasks(self):
return self.task_ctrl.pending_tasks
@property
def remaining_tasks(self):
return self.task_ctrl.remaining_tasks
@property
def completed_tasks(self):
return self.task_ctrl.completed_tasks
def task_status(self, task: Task) -> str:
"""Get the status of a task.
:param task: task to get status for
:return: status
"""
return self.task_ctrl.statuses.task_status(task)
def rerun_required(self):
"""Rerun status of this Remake object.
:return: True if any tasks remain to be run
"""
assert self.finalized
return self.task_ctrl.rescan_tasks or self.task_ctrl.pending_tasks
def configure(self, print_reasons: bool, executor: str, display: str):
"""Allow Remake object to be configured after creation.
:param print_reasons: print reason for running individual task
:param executor: name of which `remake.executor` to use
:param display: how to display task status after each task is run
"""
self.task_ctrl.print_reasons = print_reasons
self.task_ctrl.set_executor(executor)
if display == 'print_status':
self.task_ctrl.display_func = self.task_ctrl.__class__.print_status
elif display == 'task_dag':
from remake.experimental.networkx_displays import display_task_status
self.task_ctrl.display_func = display_task_status
elif display:
raise Exception(f'display {display} not recognized')
def short_status(self, mode='logger.info'):
"""Log/print a short status line.
:param mode: 'logger.info' or 'print'
"""
if mode == 'logger.info':
displayer = logger.info
elif mode == 'print':
displayer = print
else:
raise ValueError(f'Unrecognized mode: {mode}')
displayer(f'Status (complete/rescan/pending/remaining/cannot run): '
f'{len(self.completed_tasks)}/{len(self.task_ctrl.rescan_tasks)}/'
f'{len(self.pending_tasks)}/{len(self.remaining_tasks)}/{len(self.task_ctrl.cannot_run_tasks)}')
def display_task_dag(self):
"""Display all tasks as a Directed Acyclic Graph (DAG)"""
from remake.experimental.networkx_displays import display_task_status
import matplotlib.pyplot as plt
display_task_status(self.task_ctrl)
plt.show()
def run_all(self, force=False):
"""Run all tasks.
:param force: force rerun of each task
"""
self.task_ctrl.run_all(force=force)
def run_one(self):
"""Run the next pending task"""
all_pending = list(self.task_ctrl.rescan_tasks + self.task_ctrl.statuses.ordered_pending_tasks)
if all_pending:
task = all_pending[0]
self.task_ctrl.run_requested([task], force=False)
def run_random(self):
"""Run a random task (pot luck out of pending)"""
task = random.choice(list(self.task_ctrl.pending_tasks))
self.run_requested([task], force=False)
def run_requested(self, requested, force=False, handle_dependencies=False):
"""Run requested tasks.
:param requested:
:param force: force rerun of each task
:param handle_dependencies: add all ancestor tasks to ensure given tasks can be run
"""
# Work out whether it's possible to run requested tasks.
ancestors = self.all_ancestors(requested)
rerun_required_ancestors = ancestors & (self.pending_tasks |
self.remaining_tasks)
missing_tasks = rerun_required_ancestors - set(requested)
if missing_tasks:
logger.debug(f'{len(missing_tasks)} need to be added')
if not handle_dependencies:
logger.error('Impossible to run requested tasks')
raise RemakeError('Cannot run with requested tasks. Use --handle-dependencies to fix.')
else:
requested = list(rerun_required_ancestors)
requested = self.task_ctrl.rescan_tasks + requested
self.task_ctrl.run_requested(requested, force=force)
def list_rules(self):
"""List all rules"""
return self.rules
def find_task(self, task_path_hash_key: Union[Task, str]):
"""Find a task from its path_hash_key.
:param task_path_hash_key: key of task
:return: found task
"""
if isinstance(task_path_hash_key, Task):
return task_path_hash_key
else:
return self.find_tasks([task_path_hash_key])[0].task
def find_tasks(self, task_path_hash_keys):
"""Find all tasks given by their path hash keys
:param task_path_hash_keys: list of path hash keys
:return: all found tasks
"""
tasks = TaskQuerySet([], self.task_ctrl)
for task_path_hash_key in task_path_hash_keys:
if len(task_path_hash_key) == 40:
tasks.append(self.task_ctrl.task_from_path_hash_key[task_path_hash_key])
else:
# TODO: Make less bad.
# I know this is terribly inefficient!
_tasks = []
for k, v in self.task_ctrl.task_from_path_hash_key.items():
if k[:len(task_path_hash_key)] == task_path_hash_key:
_tasks.append(v)
if len(_tasks) == 0:
raise KeyError(task_path_hash_key)
elif len(_tasks) > 1:
raise KeyError(f'{task_path_hash_key} matches multiple keys')
tasks.append(_tasks[0])
return tasks
def list_tasks(self, tfilter=None, rule=None, requires_rerun=False,
uses_file=None, produces_file=None,
ancestor_of=None, descendant_of=None):
"""List all tasks subject to requirements.
:param tfilter: dict of key/value pairs to filter tasks on
:param rule: rule that tasks belongs to
:param requires_rerun: whether tasks require rerun
:param uses_file: whether tasks use a given file
:param produces_file: whether tasks produce a given file
:param ancestor_of: whether tasks are an ancestor of this task (path hash key)
:param descendant_of: whether tasks are a descendant of this task (path hash key)
:return: all matching tasks
"""
tasks = TaskQuerySet([t for t in self.tasks], self.task_ctrl)
if tfilter:
tasks = tasks.filter(cast_to_str=True, **tfilter)
if rule:
tasks = tasks.in_rule(rule)
if uses_file:
uses_file = Path(uses_file).absolute()
tasks = [t for t in tasks if uses_file in t.inputs.values()]
if produces_file:
produces_file = Path(produces_file).absolute()
tasks = [t for t in tasks if produces_file in t.outputs.values()]
if ancestor_of:
ancestor_of = self.find_task(ancestor_of)
ancestor_tasks = self.ancestors(ancestor_of)
tasks = sorted(ancestor_tasks & set(tasks), key=self.task_ctrl.sorted_tasks.get)
if descendant_of:
descendant_of = self.find_task(descendant_of)
descendant_tasks = self.descendants(descendant_of)
tasks = sorted(descendant_tasks & set(tasks), key=self.task_ctrl.sorted_tasks.get)
if requires_rerun:
tasks = [t for t in tasks
if self.task_ctrl.statuses.task_status(t) in ['pending', 'remaining']]
return TaskQuerySet(tasks, self.task_ctrl)
def all_descendants(self, tasks):
"""Find all descendants of tasks
:param tasks: tasks to start from
:return: all descendants
"""
descendants = set()
for task in tasks:
if task in descendants:
continue
descendants |= self.descendants(task)
return descendants
def all_ancestors(self, tasks):
"""Find all ancestors of tasks
:param tasks: tasks to start from
:return: all ancestors
"""
ancestors = set()
for task in tasks:
if task in ancestors:
continue
ancestors |= self.ancestors(task)
return ancestors
def descendants(self, task):
"""All descendants of a given task.
:param task: task to start from
:return: all descendants
"""
return set(nx.bfs_tree(self.task_ctrl.task_dag, task))
def ancestors(self, task):
"""All ancestors of a given task.
:param task: task to start from
:return: all ancestors
"""
return set(nx.bfs_tree(self.task_ctrl.task_dag, task, reverse=True))
def list_files(self, filetype=None, exists=False,
produced_by_rule=None, used_by_rule=None,
produced_by_task=None, used_by_task=None):
"""List all files subject to criteria.
:param filetype: one of input_only, output_only, input, output, inout
:param exists: whether file exists
:param produced_by_rule: whether file is produced by rule
:param used_by_rule: whether file is used by rule
:param produced_by_task: whether file is produced by task (path hash key)
:param used_by_task: whether file is used by task (path hash key)
:return: all matching files
"""
input_paths = set(self.task_ctrl.input_task_map.keys())
output_paths = set(self.task_ctrl.output_task_map.keys())
input_only_paths = input_paths - output_paths
output_only_paths = output_paths - input_paths
inout_paths = input_paths & output_paths
files = input_paths | output_only_paths
if filetype is None:
files = sorted(files)
elif filetype == 'input_only':
files = sorted(input_only_paths)
elif filetype == 'output_only':
files = sorted(output_only_paths)
elif filetype == 'input':
files = sorted(input_paths)
elif filetype == 'output':
files = sorted(output_paths)
elif filetype == 'inout':
files = sorted(inout_paths)
else:
raise ValueError(f'Unknown filetype: {filetype}')
if exists:
files = [f for f in files if f.exists()]
if used_by_rule:
_files = set()
for f in files:
if f not in self.task_ctrl.input_task_map:
continue
for t in self.task_ctrl.input_task_map[f]:
if t.__class__.__name__ == used_by_rule:
_files.add(f)
files = sorted(_files)
if produced_by_rule:
_files = set()
for f in files:
if f not in self.task_ctrl.output_task_map:
continue
t = self.task_ctrl.output_task_map[f]
if t.__class__.__name__ == produced_by_rule:
_files.add(f)
files = sorted(_files)
if used_by_task:
used_by_task = self.find_task(used_by_task)
_files = set()
for f in files:
if f not in self.task_ctrl.input_task_map:
continue
for t in self.task_ctrl.input_task_map[f]:
if t is used_by_task:
_files.add(f)
files = sorted(_files)
if produced_by_task:
produced_by_task = self.find_task(produced_by_task)
_files = set()
for f in files:
if f not in self.task_ctrl.output_task_map:
continue
t = self.task_ctrl.output_task_map[f]
if t is produced_by_task:
_files.add(f)
files = sorted(_files)
filelist = []
for file in files:
if file in input_only_paths:
ftype = 'input-only'
elif file in output_only_paths:
ftype = 'output-only'
elif file in inout_paths:
ftype = 'inout'
filelist.append((file, ftype, file.exists()))
return filelist
def task_info(self, task_path_hash_keys):
"""Task info for all given tasks.
:param task_path_hash_keys: task hash keys for tasks
:return: dict containing all info
"""
assert self.finalized
info = {}
tasks = self.find_tasks(task_path_hash_keys)
for task_path_hash_key, task in zip(task_path_hash_keys, tasks):
task_md = self.task_ctrl.metadata_manager.task_metadata_map[task]
status = self.task_ctrl.statuses.task_status(task)
info[task_path_hash_key] = (task, task_md, status)
return info
def file_info(self, filenames):
"""File info for all given files.
:param filenames: filenames to get info for
:return: dict containing all info
"""
info = {}
for filepath in (Path(fn).absolute() for fn in filenames):
if filepath in self.task_ctrl.input_task_map:
used_by_tasks = self.task_ctrl.input_task_map[filepath]
else:
used_by_tasks = []
if filepath in self.task_ctrl.output_task_map:
produced_by_task = self.task_ctrl.output_task_map[filepath]
else:
produced_by_task = None
if used_by_tasks or produced_by_task:
path_md = self.task_ctrl.metadata_manager.path_metadata_map[filepath]
else:
path_md = None
info[filepath] = path_md, produced_by_task, used_by_tasks
return info
@property
def finalized(self):
"""Is this finalized (i.e. ready to be run)?"""
return self.task_ctrl.finalized
def reset(self):
"""Reset the internal state"""
self.task_ctrl.reset()
return self
def finalize(self):
"""Finalize this Remake object"""
self.task_ctrl.finalize()
Remake.current_remake[multiprocessing.current_process().name] = None
return self
| nilq/baby-python | python |
#!/usr/bin/env python
#
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'Eric Bidelman <ebidel@>'
import os
import sys
import jinja2
import webapp2
import http2push as http2
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__))
)
# TODO(ericbidelman): investigate + remove
# ATM, this is necessary to only add the vulcanized bundle URL when it's actually
# being requested by the browser. There appears to be a bug in GAE s.t. other
# files won't be pushed if one of the URLs is never requested by the browser.
# by the browser.
def fixup_for_vulcanize(vulcanize, urls):
"""Replaces element.html URL with a vulcanized version or
elements.vulcanize.html with the unvulcanized version.
Args:
vulcanize: True if the URL should be replaced by the vulcanized version.
urls: A dict of url: priority mappings.
Returns:
An update dict of URL mappings.
"""
# TODO: don't hardcode adding the vulcanized import bundle.
UNVULCANIZED_FILE = 'elements.html'
VULCANIZED_FILE = 'elements.vulcanize.html'
push_urls = {}
for k,v in urls.iteritems():
url = k
if vulcanize is not None:
if k.endswith(UNVULCANIZED_FILE):
url = k.replace(UNVULCANIZED_FILE, VULCANIZED_FILE)
else:
if k.endswith(VULCANIZED_FILE):
url = k.replace(VULCANIZED_FILE, UNVULCANIZED_FILE)
push_urls[url] = v
return push_urls
class MainHandler(http2.PushHandler):
def get(self):
vulcanize = self.request.get('vulcanize', None)
# TODO: Remove (see above).
push_urls = self.push_urls;
noextras = self.request.get('noextras', None)
if noextras is not None:
push_urls = fixup_for_vulcanize(vulcanize, self.push_urls)
# HTTP2 server push resources?
if self.request.get('nopush', None) is None:
# Send Link: <URL>; rel=preload header.
header = self._generate_link_preload_headers(push_urls)
self.response.headers.add_header('Link', header)
template = JINJA_ENVIRONMENT.get_template('static/index.html')
return self.response.write(template.render({
'vulcanize': vulcanize is not None
}))
# # Example - decorators.
# class MainHandler(http2.PushHandler):
# @http2.push('push_manifest.json')
# def get(self):
# vulcanize = self.request.get('vulcanize', None)
# # TODO: Remove (see above).
# fixup_for_vulcanize(vulcanize, self.push_urls)
# path = os.path.join(os.path.dirname(__file__), 'static/index.html')
# return self.response.write(template.render(path, {
# 'vulcanize': vulcanize is not None
# }))
app = webapp2.WSGIApplication([
('/', MainHandler),
], debug=True)
| nilq/baby-python | python |
# Copyright (c) 2012 Qumulo, 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 qumulo.lib.request as request
V1_SETTINGS_FIELDS = set((
'assigned_by',
'ip_ranges',
'floating_ip_ranges',
'netmask',
'gateway',
'dns_servers',
'dns_search_domains',
'mtu',
'bonding_mode'
))
@request.request
def get_cluster_network_config(conninfo, credentials):
method = "GET"
uri = "/v1/network/settings"
return request.rest_request(conninfo, credentials, method, uri)
@request.request
def modify_cluster_network_config(conninfo, credentials, **kwargs):
method = "PATCH"
uri = "/v1/network/settings"
config = { }
for key, value in kwargs.items():
assert key in V1_SETTINGS_FIELDS
if value is not None:
config[key] = value
if set(kwargs.keys()) == V1_SETTINGS_FIELDS:
method = "PUT"
return request.rest_request(conninfo, credentials, method, uri, body=config)
@request.request
def list_network_status(conninfo, credentials):
method = "GET"
uri = "/v1/network/status/"
return request.rest_request(conninfo, credentials, method, uri)
@request.request
def get_network_status(conninfo, credentials, node):
method = "GET"
uri = "/v1/network/status/{}".format(node)
return request.rest_request(conninfo, credentials, method, uri)
@request.request
def list_interfaces(conninfo, credentials):
method = "GET"
uri = "/v2/network/interfaces/"
return request.rest_request(conninfo, credentials, method, uri)
@request.request
def get_interface(conninfo, credentials, interface_id):
method = "GET"
uri = "/v2/network/interfaces/{}".format(interface_id)
return request.rest_request(conninfo, credentials, method, uri)
@request.request
def list_networks(conninfo, credentials, interface_id):
method = "GET"
uri = "/v2/network/interfaces/{}/networks/".format(interface_id)
return request.rest_request(conninfo, credentials, method, uri)
@request.request
def get_network(conninfo, credentials, interface_id, network_id):
method = "GET"
uri = "/v2/network/interfaces/{}/networks/{}".format(
interface_id, network_id)
return request.rest_request(conninfo, credentials, method, uri)
# Don't allow setting interface ID and name.
V2_INTERFACE_FIELDS = set((
'bonding_mode',
'default_gateway',
'mtu',
))
@request.request
def modify_interface(conninfo, credentials, interface_id, **kwargs):
# Always patch and don't allow setting interface ID and name.
method = "PATCH"
uri = "/v2/network/interfaces/{}".format(interface_id)
config = { }
for key, value in kwargs.items():
assert key in V2_INTERFACE_FIELDS
if value is not None:
config[key] = value
if set(config.keys()) == V2_INTERFACE_FIELDS:
method = "PUT"
return request.rest_request(conninfo, credentials, method, uri, body=config)
V2_NETWORK_FIELDS = set((
'assigned_by',
'ip_ranges',
'floating_ip_ranges',
'netmask',
'dns_servers',
'dns_search_domains',
'mtu',
'vlan_id',
))
@request.request
def modify_network(conninfo, credentials, interface_id, network_id, **kwargs):
method = "PATCH"
uri = "/v2/network/interfaces/{}/networks/{}".format(
interface_id, network_id)
config = {}
for key, value in kwargs.items():
assert key in V2_NETWORK_FIELDS
if value is not None:
config[key] = value
if set(config.keys()) == V2_NETWORK_FIELDS:
method = "PUT"
return request.rest_request(conninfo, credentials, method, uri, body=config)
@request.request
def list_network_status_v2(conninfo, credentials, interface_id):
method = "GET"
uri = "/v2/network/interfaces/{}/status/".format(interface_id)
return request.rest_request(conninfo, credentials, method, uri)
@request.request
def get_network_status_v2(conninfo, credentials, interface_id, node_id):
method = "GET"
uri = "/v2/network/interfaces/{}/status/{}".format(interface_id, node_id)
return request.rest_request(conninfo, credentials, method, uri)
@request.request
def get_static_ip_allocation(conninfo, credentials,
try_ranges=None, try_netmask=None, try_floating_ranges=None):
method = "GET"
uri = "/v1/network/static-ip-allocation"
query_params = []
if try_ranges:
query_params.append("try={}".format(try_ranges))
if try_netmask:
query_params.append("netmask={}".format(try_netmask))
if try_floating_ranges:
query_params.append("floating={}".format(try_floating_ranges))
if query_params:
uri = uri + "?" + "&".join(query_params)
return request.rest_request(conninfo, credentials, method, uri)
@request.request
def get_floating_ip_allocation(conninfo, credentials):
method = "GET"
uri = "/v1/network/floating-ip-allocation"
return request.rest_request(conninfo, credentials, method, uri)
| nilq/baby-python | python |
GRAPH_ENDPOINT = 'https://graph.facebook.com/v10.0/'
INSIGHTS_CSV = 'insta_insights.csv'
HTML_FILE = 'index.html'
CSS_FILE = 'style.css'
HTML_TEMPLATE = 'index.html.template'
ID_COL = 'id'
IMPRESSIONS_COL = 'impressions'
ENGAGEMENT_COL = 'engagement'
REACH_COL = 'reach'
TIMESTAMP_COL = 'timestamp'
HOUR_COL = 'hour'
DEFAULT_COLUMNS = [ID_COL, IMPRESSIONS_COL, ENGAGEMENT_COL, REACH_COL, TIMESTAMP_COL, HOUR_COL]
METRICS_COLUMNS = [IMPRESSIONS_COL, ENGAGEMENT_COL, REACH_COL]
| nilq/baby-python | python |
"""Module with git related utilities."""
import git
class GitRepoVersionInfo:
"""
Provides application versions information based on the tags and commits in the repo
"""
def __init__(self, path: str):
"""
Create an instance of GitRepoVersionInfo
:param path: The path to search for git information. It searches for '.git' in this folder or any parent
folder.
"""
self._is_repo = False
try:
self._repo = git.Repo(path, search_parent_directories=True)
self._is_repo = True
except git.exc.InvalidGitRepositoryError:
self._repo = None
@property
def is_git_repo(self) -> bool:
"""
Checks if the path given in constructor is a sub-path of a valid git repo.
:return: Boolean true, if repo was found.
"""
return self._is_repo
def get_git_version(self, strip_v_in_version: bool = True) -> str:
"""
Gets application version in the format [last-tag]-[last-commit-sha].
:param strip_v_in_version: If the version tag starts with 'v' (like 'v1.2.3),
this chooses if the 'v' should be stripped, so the resulting tag is '1.2.3'.
If there's a "-", "." or "_" separator after "v", it is removed as well.
:return: The version string
"""
if not self._is_repo:
raise git.exc.InvalidGitRepositoryError()
tags = sorted(self._repo.tags, key=lambda t: t.commit.committed_date)
latest_tag = None if len(tags) == 0 else tags[-1]
ver = "0.0.0" if latest_tag is None else latest_tag.name
if strip_v_in_version and ver.startswith("v"):
txt_ver = ver.lstrip("v")
txt_ver = txt_ver.lstrip("-_.")
else:
txt_ver = ver
sha = self._repo.head.commit.hexsha
if latest_tag is not None and sha == latest_tag.commit.hexsha:
return txt_ver
return f"{txt_ver}-{sha}"
| nilq/baby-python | python |
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.views.generic.list_detail import object_list
from django.views.generic.create_update import *
from app.models import Carrier
def index(request):
return object_list(request, Carrier.all().order('-listed'))
def create_carrier(request):
return create_object(request, Carrier, post_save_redirect='/admin')
def update_carrier(request, id):
return update_object(request, Carrier, object_id=id, post_save_redirect='/admin')
def delete_carrier(request, id):
return delete_object(request, Carrier, object_id=id, post_delete_redirect='/admin') | nilq/baby-python | python |
import tweepy
import requests
import json
import os
import sys
import random
import datetime
from time import sleep
# Import relevant files
import twitter
import retquote as rq
import tweetq as tq
#Insert tweet in database
def insert_tweet(tweet,client):
"""
Inserting tweets in a different collection just for logging purposes
can be skipped if wanted.
"""
db = client.tweetbot
coll = db.tweets
twin = {
"tweetid": tweet.id,
"tweetText": tweet.full_text,
"createdDate": tweet.created_at}
coll.insert_one(twin)
print(f"{rq.current_time()}Successfully inserted in secondary collection!")
#Get quote from API and parse and format it
def getquote():
URL = "https://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json"
raw = requests.get(url=URL)
if raw.status_code != 200:
print(f"{rq.current_time()}Cannot get the quote (HTTP {raw.status_code}): {raw.text}\nAPI may be down!")
sleep(120)
return getquote()
try:
quote = json.loads(raw.text.replace("\\",""))
except Exception as e:
print(f"{rq.current_time()}\n{raw.text}\nException:\n{e}\nRetrying again...")
sleep(5)
return getquote()
if quote["quoteText"].strip()=="":
sleep(5)
return getquote()
if quote["quoteAuthor"].strip()=="":
quote["quoteAuthor"] = "Unknown"
author = "–"+quote["quoteAuthor"].strip()
# author= textmanup(author,typem="bold")
tweettopublish=quote["quoteText"].strip()+"\n"+author
print(f"{rq.current_time()}Returned quote from API-:\n{tweettopublish}")
return tweettopublish
# Follow back every user
def follow_followers(api):
"""
Check the followers list and see if the user is being
followed by the bot if not follow the user.
"""
for follower in tweepy.Cursor(api.followers).items():
if not follower.following:
print(f"{rq.current_time()}Following {follower.name}")
follower.follow()
# Make the text bold, italic or bolditalic
def textmanup(input_text,typem="bold"):
"""
Twitter does not support formatting the text so to format the text
we can use certain unicode chars and replace the letters with these unicode chars
for getting the desired result but these unicode chars may increase the length of the text.
"""
chars = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm0123456789"
bold_chars = "𝗤𝗪𝗘𝗥𝗧𝗬𝗨𝗜𝗢𝗣𝗔𝗦𝗗𝗙𝗚𝗛𝗝𝗞𝗟𝗭𝗫𝗖𝗩𝗕𝗡𝗠𝗾𝘄𝗲𝗿𝘁𝘆𝘂𝗶𝗼𝗽𝗮𝘀𝗱𝗳𝗴𝗵𝗷𝗸𝗹𝘇𝘅𝗰𝘃𝗯𝗻𝗺𝟬𝟭𝟮𝟯𝟰𝟱𝟲𝟳𝟴𝟵"
itlaics_chars ="𝘘𝘞𝘌𝘙𝘛𝘠𝘜𝘐𝘖𝘗𝘈𝘚𝘋𝘍𝘎𝘏𝘑𝘒𝘓𝘡𝘟𝘊𝘝𝘉𝘕𝘔𝘲𝘸𝘦𝘳𝘵𝘺𝘶𝘪𝘰𝘱𝘢𝘴𝘥𝘧𝘨𝘩𝘫𝘬𝘭𝘻𝘹𝘤𝘷𝘣𝘯𝘮0123456789"
bold_italics_chars = "𝙌𝙒𝙀𝙍𝙏𝙔𝙐𝙄𝙊𝙋𝘼𝙎𝘿𝙁𝙂𝙃𝙅𝙆𝙇𝙕𝙓𝘾𝙑𝘽𝙉𝙈𝙦𝙬𝙚𝙧𝙩𝙮𝙪𝙞𝙤𝙥𝙖𝙨𝙙𝙛𝙜𝙝𝙟𝙠𝙡𝙯𝙭𝙘𝙫𝙗𝙣𝙢0123456789"
output = ""
for character in input_text:
if character in chars:
if typem=="bold":
output += bold_chars[chars.index(character)]
elif typem=="italic":
output += itlaics_chars[chars.index(character)]
elif typem=="bolditalic":
output += bold_italics_chars[chars.index(character)]
else:
output += character
return output
def main():
"""
Connect with the twitter API.
Connect with the Mongo Atlas Instance when using db for getting quotes.
Load the log files from the replit db when logging is on and platform is replit.
Replit db only stores the log files as they cannot be stored directly
in the filesystem as it is not persistent.
Execute keep_alive for showing twitter profile and displaying logs
The keep_alive function along with Uptime Robot helps keep the replit running.
See https://bit.ly/3h5ZS09 for more detials!
If logging is on then redirect the default stdout to a log file,
according to the day and delete any log files older than 14 days.
After tweeting insert the tweets in a secondary collection
in the db and print/log those tweets.
Reset the stdout to default if previously changed.
Update the current day's log/key in replit db and sleep.
"""
try:
api= twitter.create_api()
if os.environ.get("quote_method","db"=="db"):
from pymongo import MongoClient
client = MongoClient(os.environ.get("database_uri"))
if os.environ.get("platform_type","local")=="replit":
from keep_alive import keep_alive
keep_alive()
if os.environ.get("logging","off")=="on":
import saveindb as sdb
sdb.load_files()
except Exception as e:
print(f"{rq.current_time()}Exception encountered in connecting with Database or Twitter.Check the credentials again!\n{rq.current_time()}{e}")
sys.exit()
# Keep tweeting every hour until forever
while True:
del_old = False
if os.environ.get("logging","off")=="on":
log_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5,minutes=30))) # Get date for IST
old_log = f"Logs/log_{(log_date-datetime.timedelta(days=15)).strftime('%d_%m_%y')}.txt"
curr_log = f"Logs/log_{log_date.strftime('%d_%m_%y')}.txt"
sys.stdout = open(curr_log,"a",encoding="utf-8")
if os.path.isfile(old_log):
os.remove(old_log)
if os.environ.get("platform_type","local")=="replit":
sdb.clean_db(old_log)
del_old = True
print(f"\n{rq.current_time()}New tweet session!")
if del_old:
print(f"{rq.current_time()}Removed old log! {old_log}")
try:
follow_followers(api)
except tweepy.TweepError:
pass
try:
if os.environ.get("quote_method","db")=="db":
quote = rq.main(client)
tweet,t2 = tq.tweet_quote(api,quote)
else:
quote = getquote()
tweet,t2 = tq.tweet_dbdown(api,quote)
except Exception as e:
print(f"{rq.current_time()}Problem getting Quote! DB may be down. Using API for Quote.\n{rq.current_time()}{e}")
quote = getquote()
tweet,t2 = tq.tweet_dbdown(api,quote)
try:
if os.environ.get("quote_method","db")=="db":
insert_tweet(tweet,client)
print(f"{rq.current_time()}Tweet Sent-:\nTweetId: {tweet.id}\n{tweet.full_text}")
if t2 is not None:
if os.environ.get("quote_method","db")=="db":
insert_tweet(t2,client)
print(f"{rq.current_time()}2nd Tweet Sent-:\nTweetId: {t2.id}\n{t2.full_text}")
except Exception as e:
print(f"{rq.current_time()}Error inserting in tweet collections!\n{rq.current_time()}{e}")
sleep_time = random.randint(60*52, 60*58)
if os.environ.get("logging","off")=="on":
sys.stdout.flush()
os.close(sys.stdout.fileno())
sys.stdout = sys.__stdout__
if os.environ.get("platform_type","local")=="replit":
sdb.save_file(curr_log)
sleep(sleep_time)
if __name__ == "__main__":
main() | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 11 22:14:51 2021
@author: Allectus
"""
import os
import re
import copy
import pandas as pd
import tkinter as tk
import plotly.io as pio
import plotly.express as px
from tkinter import filedialog
from lxml import etree
#==============================================================================
def parse_asset_file(xmlfile, taglist, convert=True, collapse_diffs=True):
#Parses X4:Foundations asset xml files
#
#xmlfile: file path to desired input asset file
#taglist: XML asset property tag to collect attributes for
#convert: If True attributes will be converted to floats
xtree = etree.parse(xmlfile)
result = {}
for attr in taglist:
attr_element = xtree.find('//' + str(attr))
if attr_element is not None:
attr_path = xtree.getpath(attr_element)
if collapse_diffs:
attr_path = re.sub(r'/diff/(replace|add)', '', attr_path)
if attr_element is None:
attr_dict = {}
else:
attr_dict = {str(attr_path) + '/' + str(k):v for k,v in attr_element.attrib.items()}
if convert:
attr_dict = {k:float(v) for k,v in attr_dict.items()}
else:
attr_dict = {}
result.update(attr_dict)
return(result)
#------------------------------------------------------------------------------
def export_asset_xml_diff(outfilepath, attributes):
#Exports X4:Foundations asset diff xml files
#
#outfilepath: file path to desired output file
#attributes: dict of xpath:value to be exported in the diff file
attributes
outstr = '\n'.join(['<?xml version="1.0" encoding="utf-8"?>',
'<diff>',
' <replace sel="' +
'\n <replace sel="'.join([str(xpath)[:str(xpath).rfind('/') + 1] + '@' +
str(xpath)[str(xpath).rfind('/') + 1:] + '">' +
str(round(val,2)) + '</replace>'
for xpath,val in attributes.items()]),
'</diff>'])
os.makedirs(os.path.dirname(outfilepath), exist_ok=True)
with open(outfilepath, 'w') as outfile:
outfile.write(outstr)
return(True)
#------------------------------------------------------------------------------
def parse_resources(resources, asset_path, file_pattern, taglist):
#Collects and parses relevant X4:Foundations asset files based upon input filters
#
#resources: pd.DataFrame of available unpacked input directories, contains resources root
#asset_path: path to relevant directory for the specific asset, relative to resource root
#file_pattern: regex pattern to id files in asset path to retain
#taglist: tags to extract from the identied input files
loc_resources = copy.deepcopy(resources)
#Find game files
loc_resources['assetdir'] = loc_resources.root.apply(lambda x: os.path.join(x, asset_path))
loc_resources['filelist'] = loc_resources.assetdir.apply(os.listdir)
loc_resources = loc_resources.explode('filelist', ignore_index=True)
#Filter out unwanted files (only keep appropriate xml files)
loc_resources.rename(columns={'filelist':'basefilename'}, inplace=True)
loc_resources['keep'] = loc_resources.basefilename.apply(lambda x: os.path.splitext(x)[1] == '.xml') & loc_resources.basefilename.str.contains(file_pattern)
loc_resources = loc_resources[loc_resources.keep].reset_index(drop=True)
loc_resources = loc_resources.drop('keep', axis=1)
loc_resources['fullpath'] = loc_resources.apply(lambda x: os.path.join(x['assetdir'], x['basefilename']), axis=1)
#Parse the discovered files
loc_resources = pd.concat([loc_resources, pd.DataFrame(list(loc_resources['fullpath'].apply(
lambda x: parse_asset_file(x, taglist=taglist, convert=True, collapse_diffs=True))))], axis=1)
return(loc_resources)
#------------------------------------------------------------------------------
def update_shields(resources, asset_path = 'assets/props/SurfaceElements/macros',
file_pattern=r'^shield.*', taglist = ['recharge']):
#Identifies and modified X4: Foundations shield files
#
#resources: pd.DataFrame of available unpacked input directories, contains resources root
#asset_path: path to relevant directory for the specific asset, relative to resource root
#file_pattern: regex pattern to id files in asset path to retain
#taglist: tags to extract from the identied input files
shield_resources = parse_resources(resources=resources, asset_path=asset_path,
file_pattern=file_pattern, taglist=taglist)
#capture owner/size/type from filename
shield_metadata = shield_resources.basefilename.str.extract(r'(shield_)(.*)(_)(s|m|l|xl)(_)(.*)(_.*)(mk.)(.*)', expand=True)
shield_metadata = shield_metadata.rename(columns={1:'race', 3:'size', 5:'type', 7:'mk'})
shield_resources = pd.concat([shield_resources, shield_metadata[['race', 'size', 'type', 'mk']]], axis=1)
#colname look up table (to retain xpath in colname so we dont have to reshape to long format)
#gives 'tag_attrib': xpath
modified_cols = {}
cnm_init = {}
for tag in taglist:
colpattern = r'.*(/' + str(tag) + r'/).*'
cnm_init.update({str(tag)+'_'+str(c)[str(c).rfind('/')+1:] :c for c in shield_resources.columns if re.match(colpattern, c)})
vro_results = shield_resources[(shield_resources['source'] == 'vro')].reset_index()
base_results = shield_resources[(shield_resources['source'] == 'base')].reset_index()
modified = pd.merge(vro_results, base_results, how='left', on=['race', 'size', 'type', 'mk'], suffixes=['_vro', '_base'])
#update colname map
cnm = copy.deepcopy(cnm_init)
cnm.update({str(k)+'_base':str(v)+'_base' for k, v in cnm_init.items()})
cnm.update({str(k)+'_vro':str(v)+'_vro' for k, v in cnm_init.items()})
#modify values
max_factors = modified.groupby(['size', 'mk']).apply(lambda x: (x[cnm['recharge_max_vro']] / x[cnm['recharge_max_base']]).mean()).reset_index()
max_factors.rename(columns={0:'max_factor'}, inplace=True)
modified = modified.merge(max_factors, how='left', on=['size', 'mk'])
modified[cnm['recharge_max']] = modified[cnm['recharge_max_base']] * modified['max_factor']
modified.loc[(modified['race'].isin(['kha'])) | (modified[cnm['recharge_max']].isna()), cnm['recharge_max']] = modified[cnm['recharge_max_vro']]
modified_cols.update({'recharge_max': cnm['recharge_max']})
modified[cnm['recharge_delay']] = modified[cnm['recharge_delay_base']] * (3/2)
modified.loc[(modified['race'].isin(['kha'])) | (~modified['size'].isin(['s'])) | (modified[cnm['recharge_delay']].isna()), cnm['recharge_delay']] = modified[cnm['recharge_delay_vro']]
modified_cols.update({'recharge_delay': cnm['recharge_delay']})
recharge_factors = modified.groupby(['size', 'mk']).apply(lambda x: (x[cnm['recharge_rate_vro']] / x[cnm['recharge_rate_base']]).mean()).reset_index()
recharge_factors.rename(columns={0:'recharge_factor'}, inplace=True)
modified = modified.merge(recharge_factors, how='left', on=['size', 'mk'])
modified[cnm['recharge_rate']] = modified[cnm['recharge_rate_base']] * modified['recharge_factor']
modified.loc[modified['size'].isin(['s']), cnm['recharge_rate']] = modified[cnm['recharge_rate_base']] * 0.9
modified.loc[modified['size'].isin(['m']), cnm['recharge_rate']] = modified[cnm['recharge_rate_base']] * modified['recharge_factor'] * 1.25
modified.loc[(modified['race'].isin(['kha'])) | (modified[cnm['recharge_rate']].isna()), cnm['recharge_rate']] = modified[cnm['recharge_rate_vro']]
modified_cols.update({'recharge_rate':cnm['recharge_rate']})
return(modified, modified_cols)
#------------------------------------------------------------------------------
def update_engines(resources, asset_path = 'assets/props/Engines/macros',
file_pattern=r'^engine.*', taglist = ['thrust', 'boost', 'travel']):
#Identifies and modified X4: Foundations engine files
#
#resources: pd.DataFrame of available unpacked input directories, contains resources root
#asset_path: path to relevant directory for the specific asset, relative to resource root
#file_pattern: regex pattern to id files in asset path to retain
#taglist: tags to extract from the identied input files
engine_resources = parse_resources(resources=resources, asset_path=asset_path,
file_pattern=file_pattern, taglist=taglist)
#capture owner/size/type from filename
engine_metadata = engine_resources.basefilename.str.extract(r'(engine_)(.*)(_)(s|m|l|xl)(_)(.*)(_.*)(mk.)(.*)', expand=True)
engine_metadata = engine_metadata.rename(columns={1:'race', 3:'size', 5:'type', 7:'mk'})
engine_resources = pd.concat([engine_resources, engine_metadata[['race', 'size', 'type', 'mk']]], axis=1)
#colname look up table (to retain xpath in colname so we dont have to reshape to long format)
#gives 'tag_attrib': xpath
modified_cols = {}
cnm_init = {}
for tag in taglist:
colpattern = r'.*(/' + str(tag) + r'/).*'
cnm_init.update({str(tag)+'_'+str(c)[str(c).rfind('/')+1:] :c for c in engine_resources.columns if re.match(colpattern, c)})
#Further filter observations to only those with travel stats (eliminate thrusters etc)
engine_resources = engine_resources[~engine_resources[cnm_init['travel_thrust']].isna()].reset_index(drop=True)
engine_resources['eff_boost_thrust'] = engine_resources[cnm_init['thrust_forward']] * engine_resources[cnm_init['boost_thrust']]
engine_resources['eff_travel_thrust'] = engine_resources[cnm_init['thrust_forward']] * engine_resources[cnm_init['travel_thrust']]
vro_results = engine_resources[(engine_resources['source'] == 'vro')].reset_index()
base_results = engine_resources[(engine_resources['source'] == 'base')].reset_index()
modified = pd.merge(vro_results, base_results, how='left', on=['race', 'size', 'type', 'mk'], suffixes=['_vro', '_base'])
#update colname map
cnm = copy.deepcopy(cnm_init)
cnm.update({str(k)+'_base':str(v)+'_base' for k, v in cnm_init.items()})
cnm.update({str(k)+'_vro':str(v)+'_vro' for k, v in cnm_init.items()})
#modify values
#Calculate average conversion factors for vro <-> base thrust to allow us to normalize new engines
thrust_factors = modified.groupby(['size', 'mk', 'type']).apply(lambda x: (x[cnm['thrust_forward_vro']] / x[cnm['thrust_forward_base']]).mean()).reset_index()
thrust_factors.rename(columns={0:'thrust_factor'}, inplace=True)
modified = modified.merge(thrust_factors, how='left', on=['size', 'mk', 'type'])
attack_factors = modified.groupby(['size', 'mk', 'type']).apply(lambda x: (x[cnm['travel_attack_vro']] / x[cnm['travel_attack_base']]).mean()).reset_index()
attack_factors.rename(columns={0:'attack_factor'}, inplace=True)
modified = modified.merge(attack_factors, how='left', on=['size', 'mk', 'type'])
#Calculate effective normalized thrust values
modified['thrust_forward_pre'] = modified[cnm['thrust_forward_vro']]
modified['boost_thrust_pre'] = modified['eff_boost_thrust_base'] / modified['thrust_forward_pre']
modified.loc[modified['boost_thrust_pre'].isna(), 'boost_thrust_pre'] = modified['eff_boost_thrust_vro'] / ( modified[cnm['thrust_forward_vro']] / modified['thrust_factor'])
modified['travel_thrust_pre'] = modified['eff_travel_thrust_base'] / modified['thrust_forward_pre']
modified.loc[modified['travel_thrust_pre'].isna(), 'travel_thrust_pre'] = modified['eff_travel_thrust_vro'] / ( modified[cnm['thrust_forward_vro']] / modified['thrust_factor'])
modified['eff_boost_thrust_pre'] = modified['thrust_forward_pre'] * modified['boost_thrust_pre']
modified['eff_travel_thrust_pre'] = modified['thrust_forward_pre'] * modified['travel_thrust_pre']
#Create initial boost and travel thrust rankings so we can match them later
modified.sort_values(['size', 'thrust_forward_pre'], inplace=True)
modified['travel_rank'] = modified.groupby('size')['eff_travel_thrust_pre'].rank(axis=1, ascending=False, method='first')
modified['boost_rank'] = modified.groupby('size')['eff_boost_thrust_pre'].rank(axis=1, ascending=False, method='first')
modified = pd.merge(modified, modified, left_on=['size', 'travel_rank'], right_on=['size', 'boost_rank'], suffixes=['_original', '_ranked'] )
#update name mapping
cnm.update({str(k)+'_base_original':str(v)+'_base_original' for k, v in cnm_init.items()})
cnm.update({str(k)+'_base_ranked':str(v)+'_base_ranked' for k, v in cnm_init.items()})
cnm.update({str(k)+'_vro_original':str(v)+'_vro_original' for k, v in cnm_init.items()})
cnm.update({str(k)+'_vro_ranked':str(v)+'_vro_ranked' for k, v in cnm_init.items()})
#-------------------------------------------------------------------------
#calculate final engine params based upon relative base boost and travel rank
modified[cnm['thrust_forward']] = modified[cnm['thrust_forward_vro_original']]
modified_cols.update({'thrust_forward': cnm['thrust_forward']})
modified[cnm['thrust_reverse']] = modified[cnm['thrust_reverse_base_original']] * modified['thrust_factor_original']
modified.loc[modified[cnm['thrust_reverse']].isna(), cnm['thrust_reverse']] = modified[cnm['thrust_reverse_vro_original']]
modified_cols.update({'thrust_reverse': cnm['thrust_reverse']})
modified['eff_boost_thrust'] = modified['eff_boost_thrust_pre_original']
modified[cnm['boost_thrust']] = modified['eff_boost_thrust'] / modified[cnm['thrust_forward']]
modified_cols.update({'boost_thrust': cnm['boost_thrust']})
modified[cnm['boost_duration']] = modified[cnm['boost_duration_base_original']]
modified.loc[modified[cnm['boost_duration']].isna(), cnm['boost_duration']] = modified[cnm['boost_duration_vro_original']] / modified['attack_factor_original']
modified_cols.update({'boost_duration': cnm['boost_duration']})
modified[cnm['boost_attack']] = modified[cnm['boost_attack_base_original']]
modified.loc[modified[cnm['boost_attack']].isna(), cnm['boost_attack']] = modified[cnm['boost_attack_vro_original']] / modified['attack_factor_original']
modified_cols.update({'boost_attack': cnm['boost_attack']})
modified[cnm['boost_release']] = modified[cnm['boost_release_base_original']]
modified.loc[modified[cnm['boost_release']].isna(), cnm['boost_release']] = modified[cnm['boost_release_vro_original']] / modified['attack_factor_original']
modified_cols.update({'boost_release': cnm['boost_release']})
modified.loc[(modified['race_original'].isin(['par'])) & (modified['size'].isin(['l', 'xl'])), cnm['boost_duration']] = modified[cnm['boost_duration']] * 2
modified.loc[(modified['race_original'].isin(['spl'])) & (modified['size'].isin(['l', 'xl'])) , cnm['boost_attack']] = modified[cnm['boost_attack']] * 0.5
modified.loc[(modified['race_original'].isin(['spl'])) & (modified['size'].isin(['l', 'xl'])) , cnm['boost_release']] = modified[cnm['boost_release']] * 0.5
modified.loc[(modified['race_original'].isin(['arg', 'tel'])) & (modified['size'].isin(['l', 'xl'])), cnm['boost_duration']] = modified[cnm['boost_duration']] * 1.33
modified.loc[(modified['race_original'].isin(['arg', 'tel'])) & (modified['size'].isin(['l', 'xl'])) , cnm['boost_attack']] = modified[cnm['boost_attack']] * 0.75
modified.loc[(modified['race_original'].isin(['arg', 'tel'])) & (modified['size'].isin(['l', 'xl'])) , cnm['boost_release']] = modified[cnm['boost_release']] * 0.75
modified['eff_travel_thrust'] = modified['eff_travel_thrust_pre_original']
modified.loc[modified['size'].isin(['s', 'm']), 'eff_travel_thrust'] = modified['eff_boost_thrust_pre_ranked']
modified.loc[modified['size'].isin(['l', 'xl']), 'eff_travel_thrust'] = modified['eff_travel_thrust'] * (5/3)
modified[cnm['travel_thrust']] = modified['eff_travel_thrust'] / modified[cnm['thrust_forward']]
modified_cols.update({'travel_thrust': cnm['travel_thrust']})
modified[cnm['travel_charge']] = modified[cnm['travel_charge_base_original']]
modified.loc[modified[cnm['travel_charge']].isna(), cnm['travel_charge']] = modified[cnm['travel_charge_vro_original']] / modified['attack_factor_original']
modified_cols.update({'travel_charge': cnm['travel_charge']})
modified[cnm['travel_attack']] = modified[cnm['travel_attack_base_original']]
modified.loc[modified[cnm['travel_attack']].isna(), cnm['travel_attack']] = modified[cnm['travel_attack_vro_original']] / modified['attack_factor_original']
modified_cols.update({'travel_attack': cnm['travel_attack']})
modified[cnm['travel_release']] = modified[cnm['travel_release_base_original']]
modified.loc[modified[cnm['travel_release']].isna(), cnm['travel_release']] = modified[cnm['travel_release_vro_original']] / modified['attack_factor_original']
modified_cols.update({'travel_release': cnm['travel_release']})
modified.loc[(modified['race_original'].isin(['ter'])) & (modified['size'].isin(['l', 'xl'])), cnm['travel_charge']] = modified[cnm['travel_charge']] * 0.75
return(modified, modified_cols)
#==============================================================================
if __name__ == "__main__":
pd.options.plotting.backend = "plotly"
pio.renderers.default ='browser'
#Params
#Output (mod) directories
sum_outdir = '.'
mod_shields = True
outdir_shields = 'F:/Steam/steamapps/common/X4 Foundations/extensions/al_shieldmod_vro'
mod_engines = True
outdir_engines = 'F:/Steam/steamapps/common/X4 Foundations/extensions/al_travelmod_vro'
#Unpacked root directories
base_root = 'F:/Games/Mods/x4_extracted'
vro_root = 'F:/Games/Mods/x4_extracted/extensions/vro'
#List of expansions to consider
resource_list = ['base', 'split', 'terran', 'vro_base']
#Hardcoded inputs for convenience
resources = pd.DataFrame(resource_list, columns=['resource'])
resources.loc[resources.resource == 'base', 'root'] = base_root
resources.loc[resources.resource == 'split', 'root'] = 'F:/Games/Mods/x4_extracted/extensions/ego_dlc_split'
resources.loc[resources.resource == 'terran', 'root'] = 'F:/Games/Mods/x4_extracted/extensions/ego_dlc_terran'
resources.loc[resources.resource == 'vro_base', 'root'] = vro_root
#Gather inputs for all expansions interactively if not hardcoded above
root = tk.Tk()
root.withdraw()
for grp in resource_list:
missingvals = resources.loc[resources['resource'] == grp, 'root'].isna()
if any(missingvals) or len(missingvals) == 0:
resources.loc[resources['resource'] == grp, 'root'] = filedialog.askdirectory(title=str(grp) + " dir")
#provide paths to vro expansion files given base game expansions identified in resource_list
for grp in resource_list:
vro_grp = 'vro_' + str(grp)
if (grp not in ['base', 'vro_base']) and (vro_grp not in resources.resource.unique()):
resources = resources.append({'resource':vro_grp,
'root':os.path.join(resources.loc[resources.resource=='vro_base', 'root'].values[0],
'extensions',
os.path.split(resources.loc[resources.resource==grp, 'root'].values[0])[1])},
ignore_index=True)
#Set source base vs vro input metadata
resources['source'] = 'base'
resources.loc[resources.resource.str.contains(r'^vro_.*'), 'source'] = 'vro'
#--------------------------------------------------------------------------
#Modify shield parameters
if mod_shields:
modified_shields, modified_shields_colmap = update_shields(resources=resources)
modified_shields['fullpath_final'] = modified_shields['fullpath_vro'].str.replace(vro_root, outdir_shields)
#Export diff files
modified_shields.apply(lambda x: export_asset_xml_diff(outfilepath = x['fullpath_final'],
attributes = x[modified_shields_colmap.values()].to_dict()),
axis=1)
#Validation
shields_fig = px.scatter(modified_shields,
x=modified_shields_colmap['recharge_delay'],
y=modified_shields_colmap['recharge_rate'],
text='basefilename_vro')
shields_fig.update_traces(textposition='top center')
shields_fig.update_layout(
height=800,
title_text='Recharge delay vs rate'
)
shields_fig.show()
shields_fig.write_image(os.path.join(sum_outdir, 'modified_shields.png'))
modified_shields.to_csv(os.path.join(sum_outdir, 'modified_shields.csv'))
#--------------------------------------------------------------------------
#Modify engine parameters
if mod_engines:
modified_engines, modified_engines_colmap = update_engines(resources=resources)
modified_engines['fullpath_final'] = modified_engines['fullpath_vro_original'].str.replace(vro_root, outdir_engines)
#Export diff files
modified_engines.apply(lambda x: export_asset_xml_diff(outfilepath = x['fullpath_final'],
attributes = x[modified_engines_colmap.values()].to_dict()),
axis=1)
#Validation
engines_fig = px.scatter(modified_engines,
x='eff_boost_thrust',
y='eff_travel_thrust',
text='basefilename_vro_original')
engines_fig.update_traces(textposition='top center')
engines_fig.update_layout(
height=800,
title_text='Boost vs travel thrust'
)
engines_fig.show()
engines_fig.write_image(os.path.join(sum_outdir, 'modified_engines.png'))
engines_fig_s = px.scatter(modified_engines[modified_engines['size'].isin(['s'])],
x='eff_boost_thrust',
y='eff_travel_thrust',
text='basefilename_vro_original')
engines_fig_s.update_traces(textposition='top center')
engines_fig_s.update_layout(
height=800,
title_text='Boost vs travel thrust, S ships'
)
engines_fig_s.show()
engines_fig_s.write_image(os.path.join(sum_outdir, 'modified_engines_s.png'))
modified_engines.to_csv(os.path.join(sum_outdir, 'modified_engines.csv'))
#-------------------------------------------------------------------------- | nilq/baby-python | python |
import requests
import json
def heapify(n, i, ll = []): #heapify function for heapsort
smallest = i
left = 2*i+1
right = 2*i+2
if left < n and ll[smallest][1] > ll[left][1]:
smallest = left
if right < n and ll[smallest][1] > ll[right][1]:
smallest = right
if i != smallest:
ll[i], ll[smallest] = ll[smallest], ll[i]
heapify(n, smallest, ll)
def heapsort(ll = []): #heapsort function
n = len(ll)
for i in range(n//2-1, -1, -1):
heapify(n, i, ll)
def call_api(apicall, **kwargs): #recursion function to iterate through all the pages recieved.
data = kwargs.get('page', [])
resp = requests.get(apicall)
data += resp.json()
if len(data) > 4000: #Increase this number if repository count is more than 4000
return (data)
if 'next' in resp.links.keys():
return (call_api(resp.links['next']['url'], page=data))
return (data)
n, m, c = 6, 4, 0 # n = Top repos of organization, m = Top contributors of a particular repository
organization = 'microsoft' # organization = The organization we want to get result
s1 = 'https://api.github.com/orgs/'
s2 = '/repos?per_page=100'
api_get_repos = s1+organization+s2 #final api_call = https://api.github.com/orgs/:organization/repos?per_page=100
data = call_api(api_get_repos) #call of recursion function to recieve list of all repository
l = [] #list for storing the result
for xx in data:
if xx["private"] != "false": #omit this statement if we want to list private repository also
x = xx["name"] #name of repository
y = xx["forks"] #forks count of particular repository
if c < n:
l.append((x, y)) #tuple of (repository_name, forks_count)
c += 1
if c == n:
heapsort(l)
elif y > l[0][1]:
l[0] = (x, y)
heapify(c, 0, l)
length_of_repos = len(l)
for xx in range(length_of_repos-1, 0, -1):
l[0], l[xx] = l[xx], l[0]
heapify(xx, 0, l)
print "List of", n, "most popular repositories of", organization, "on the basis of number of forks and their top", m, "contributors are:"
print ""
count = 1
for i in range(0, length_of_repos): #loop to iterate through top repository recieved
s3 = 'https://api.github.com/repos/'
s4 = '/contributors?per_page=100'
top_contributors = s3+organization+'/'+l[i][0]+s4 #final api_call = https://api.github.com/repos/:organization/:repo_name/contributors?per_page=100
print count,"=> Repository_name:", l[i][0]," || Forks_count: ", l[i][1]
count += 1
print " Top", m, "contributors of repository", l[i][0], "are:"
c = 0
contributors_data = requests.get(top_contributors).json() #call to retrieve list of top m contributors of respective repository
for j in contributors_data: #loop all the top contributors of the particular respository
print " ", c+1, "->", "Login_name:", j["login"], " || Contributions: ", j["contributions"]
c += 1;
if c >= m:
break
print ""
print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
print ""
| nilq/baby-python | python |
class JobError(RuntimeError):
def __init__(self, jobId):
message = "Job Failed: " + jobId
super(JobError, self).__init__(message)
| nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import List, Tuple, Union
import torch
from pytext.config import ConfigBase
from pytext.models.module import create_module
from .bilstm_doc_slot_attention import BiLSTMDocSlotAttention
from .jointcnn_rep import JointCNNRepresentation
from .representation_base import RepresentationBase
from .seq_rep import SeqRepresentation
class ContextualIntentSlotRepresentation(RepresentationBase):
"""
Representation for a contextual intent slot model
The inputs are two embeddings: word level embedding containing dictionary features,
sequence (contexts) level embedding. See following diagram for the representation
implementation that combines the two embeddings. Seq_representation is concatenated
with word_embeddings.
::
+-----------+
| word_embed|--------------------------->+ +--------------------+
+-----------+ | | doc_representation |
+-----------+ +-------------------+ |-->+--------------------+
| seq_embed |-->| seq_representation|--->+ | word_representation|
+-----------+ +-------------------+ +--------------------+
joint_representation
"""
class Config(RepresentationBase.Config):
seq_representation: SeqRepresentation.Config = SeqRepresentation.Config()
joint_representation: Union[
BiLSTMDocSlotAttention.Config, JointCNNRepresentation.Config
] = BiLSTMDocSlotAttention.Config()
def __init__(self, config: Config, embed_dim: Tuple[int, ...]) -> None:
super().__init__(config)
assert len(embed_dim) == 2
self.seq_rep = create_module(config.seq_representation, embed_dim=embed_dim[1])
self.seq_representation_dim = self.seq_rep.representation_dim
self.joint_rep = create_module(
config.joint_representation,
embed_dim=embed_dim[0] + self.seq_representation_dim,
)
self.doc_representation_dim = self.joint_rep.doc_representation_dim
self.word_representation_dim = self.joint_rep.word_representation_dim
def forward(
self,
word_seq_embed: Tuple[torch.Tensor, torch.Tensor],
word_lengths: torch.Tensor,
seq_lengths: torch.Tensor,
*args,
) -> List[torch.Tensor]:
# Every batch is sorted by in descending or of word_lengths.
# We need to sort seq_lengths and seq_embed first before passing
# to seq_rep, then unsort the output of seq_rep so it aligns with batch order
(word_embed, seq_embed) = word_seq_embed
# sort seq_lengths and seq_embed
seq_lengths, sort_idx = torch.sort(seq_lengths, descending=True)
_, unsort_idx = torch.sort(sort_idx)
seq_embed = seq_embed[sort_idx]
seq_rep = self.seq_rep(embedded_seqs=seq_embed, seq_lengths=seq_lengths)
# unsort seq_out
seq_out = seq_rep[0][unsort_idx]
bsz, max_seq_len, dim = word_embed.size()
seq_rep_expand = seq_out.view(bsz, 1, -1).expand(-1, max_seq_len, -1)
new_embed = torch.cat([seq_rep_expand, word_embed], 2)
return self.joint_rep(new_embed, word_lengths)
| nilq/baby-python | python |
from collections import namedtuple, defaultdict, Counter
import dbm
from datetime import datetime, timedelta
import json
from wit import Wit
from darksky import forecast
from apis.utils import load_parameter
# time is a unix timestamp
CacheKey = namedtuple('CacheKey', ['lat', 'lon', 'time', 'granularity'])
def cache_key_to_string(ck):
return ','.join(map(str, ck))
class WeatherProvider():
def __init__(self, darksky_key, wit_key):
self.darksky_key = darksky_key
self.wit_key = wit_key
self.wit_client = Wit(self.wit_key)
# Create new database
# TODO: persist cache to and from file OR make this a generic class
# that this can extend
self.cache = {}
def _cache_forecast(self, cache, forecast_result):
# Push current forecast into both hourly and daily forecasts
current = forecast_result.currently
ck = CacheKey(str(forecast_result.latitude), str(
forecast_result.longitude), current.time, 'minute')
cache[ck] = json.dumps(current._data)
ck = CacheKey(str(forecast_result.latitude), str(
forecast_result.longitude), current.time, 'hour')
cache[ck] = json.dumps(current._data)
ck = CacheKey(str(forecast_result.latitude), str(
forecast_result.longitude), current.time, 'day')
cache[ck] = json.dumps(current._data)
if hasattr(forecast_result, 'minutely'):
# include minutely forecast because people ask things like "what
# will the weather be in an hour?"
for minute in forecast_result.minutely:
ck = CacheKey(str(forecast_result.latitude), str(
forecast_result.longitude), minute.time, 'minute')
cache[ck] = json.dumps(minute._data)
for hour in forecast_result.hourly:
ck = CacheKey(str(forecast_result.latitude), str(
forecast_result.longitude), hour.time, 'hour')
cache[ck] = json.dumps(hour._data)
for day in forecast_result.daily:
ck = CacheKey(str(forecast_result.latitude), str(
forecast_result.longitude), day.time, 'day')
cache[ck] = json.dumps(day._data)
def transform_forecast(self, report, units='us'):
'''
Put data in a format ready to be displayed to the user. E.g. 13 -> 13°F, and 0.123 -> 10%
Everything should be logged in a consistent system of units
Takes a python object or DataPoint object
Returns a list of {name, value} objects
'''
try: # convert DataPoint to python object
report = report._data
except AttributeError:
pass
# TODO: units should be a user setting. https://xkcd.com/2292/
if units not in ('us', 'metric'):
raise ValueError('Unrecognized units', units)
# Map machine-readable summary to human-readable summary
icon_converter = defaultdict(lambda: 'unknown',
{
'clear-day': 'clear',
'clear-night': 'clear',
'rain': 'rain',
'snow': 'snow',
'sleet': 'sleet',
'wind': 'wind',
'fog': 'fog',
'cloudy': 'cloudy',
'partly-cloudy-day': 'partly cloudy',
'partly-cloudy-night': 'partly cloudy',
})
relevant_keys = [
{'name': 'icon', 'transform': lambda icon: icon_converter[icon]},
{'name': 'temperature', 'transform_us': '{:.0f}°F'.format,
'transform_metric': lambda t: '{:.0}°C'.format((t - 32) * 5 / 9)},
{'name': 'temperatureLow', 'transform_us': '{:.0f}°F'.format,
'transform_metric': lambda t: '{:.0}°C'.format((t - 32) * 5 / 9)},
{'name': 'temperatureHigh', 'transform_us': '{:.0f}°F'.format,
'transform_metric': lambda t: '{:.0}°C'.format((t - 32) * 5 / 9)},
{'name': 'precipProbability',
'transform': lambda p: '{:.0%}'.format(round(p, 1))},
{'name': 'precipAccumulation', 'transform_us': '{:.1f} in'.format,
'transform_metric': lambda p: '{:.1f} cm'.format(p * 2.54)},
{'name': 'precipTotal', 'transform_us': '{:.1f} in'.format,
'transform_metric': lambda p: '{:.1f} cm'.format(p * 2.54)},
{'name': 'precipIntensity',
'transform_us': lambda p: '{:.2f} in/hr'.format(float(p)),
'transform_metric': lambda p: '{:.1f} cm/hr'.format(p * 2.54)},
{'name': 'precipType'},
{'name': 'humidity',
'transform': lambda h: '{:.0%}'.format(round(h, 1))},
{'name': 'windSpeed', 'transform_us': '{:.1f} mph'.format,
'transform_metric': lambda s: '{:.1f} km/h'.format(s * 1.61)},
{'name': 'uvIndex'},
{'name': 'visibility', 'transform_us': '{:.1f} mi'.format,
'transform_metric': lambda d: '{:.1f} km'.format(d * 1.61)},
]
# transform strings
result = []
for key in relevant_keys:
if key['name'] in report:
key_name = key['name']
if 'transform' in key:
result.append({
'name': key_name,
'value': key['transform'](report[key_name])
})
elif 'transform_us' in key and units == 'us':
result.append({
'name': key_name,
'value': key['transform_us'](report[key_name])
})
elif 'transform_metric' in key and units == 'metric':
result.append({
'name': key_name,
'value': key['transform_metric'](report[key_name])
})
else:
result.append({
'name': key_name,
'value': report[key_name]
})
return result
def current_weather(self, lat, lon):
now = datetime.now()
forecast_result = forecast(self.darksky_key, lat, lon)
current_report = forecast_result.currently._data # dicts
daily_report = forecast_result.daily[0]._data
daily_report.update(current_report)
return self.transform_forecast(daily_report)
def aggregate_forecast(self, fc_range):
'''
fc_range - a list of darksky.data.DataPoint objects or of dicts
returns - a dict
'''
def most_frequent(fc_range, key):
'''return the most frequent value of fc_range[i][key] for all i'''
c = Counter(
block[key] for block in fc_range if hasattr(
block, key)).most_common(1)
if c:
return c[0][0]
else:
return None
def get_mean(fc_range, key):
arr = [getattr(block, key, 0) for block in fc_range]
if not arr:
return None
return sum(arr) / len(arr)
result = {
'icon': most_frequent(fc_range, 'icon'),
'temperatureHigh': max(max(getattr(block, 'temperatureHigh', -1000), getattr(block, 'temperature', -1000)) for block in fc_range),
'temperatureLow': min(min(getattr(block, 'temperatureLow', 1000), getattr(block, 'temperature', 1000)) for block in fc_range),
# this isn't actually how probability works, but good enough
'precipProbability': max(block['precipProbability'] for block in fc_range),
'precipAccumulation': sum(getattr(block, 'precipAccumulation', 0) for block in fc_range),
'precipTotal': sum(getattr(block, 'precipIntensity', 0) for block in fc_range) / float(len(fc_range)) * (fc_range[-1].time - fc_range[0].time) / 60 / 60,
'precipType': most_frequent(fc_range, 'precipType'),
'humidity': get_mean(fc_range, 'humidity'),
'windSpeed': get_mean(fc_range, 'windSpeed'),
'visibility': get_mean(fc_range, 'visibility'),
'uvIndex': get_mean(fc_range, 'uvIndex')
}
# Delete keys with unset values
result = {k: v for k, v in result.items() if v is not None}
return result
def weather_at_time(self, lat, lon, time_query):
'''
Fetch the weather at a specified location and time (between now and 7 days from now).
The future limit is because Darksky's forecast only extends that far.
It doesn't support times in the past because 1) it's not a common use case, and 2) implementing it for ranges of >1 day (e.g. last week) would require making multiple requests and more code
If desired, look at the time='whatever' parameter in darkskylib
lat, lon - floats
time_query - a string with a relative time. Something like 'tonight at 8' is fine
note: you should ensure that wit.ai app's timezone is set to GMT
darksky returns forecasts in local times without a timezone
'''
# find date/time with wit.ai and duckling
response = self.wit_client.message(time_query)['entities']
if not response['datetime']:
raise ValueError('could not parse time, <{}>'.format(time_query))
else:
# assume that time_query only contains one datetime object, but
# duckling is pretty good about handling ranges
time_instance = response['datetime'][0]
# parse a wit.ai datetime object, which should look like:
# {
# 'type': 'value',
# 'grain': 'second' | minute' | 'hour' | 'day' | 'week' | 'year'
# 'value': '2020-01-01T12:30:00.000+00:00'
# }
# OR an interval containing a start and end that each look like the
# above
is_interval = False
if time_instance['type'] == 'interval':
# for queries like "this weekend", the result will be a range.
# just use the start time.
start_dt = datetime.strptime(
time_instance['from']['value'],
"%Y-%m-%dT%H:%M:%S.%f+00:00")
end_dt = datetime.strptime(
time_instance['to']['value'],
"%Y-%m-%dT%H:%M:%S.%f+00:00")
grain = time_instance['from']['grain']
is_interval = True
elif time_instance['type'] == 'value':
start_dt = datetime.strptime(
time_instance['value'],
"%Y-%m-%dT%H:%M:%S.%f+00:00")
grain = time_instance['grain']
if grain == 'week':
end_dt = start_dt + timedelta(days=7)
is_interval = True
else:
raise Exception('unrecognized type', time_instance['type'])
# Get the full forecast that corresponds to the time granularity
fc = forecast(self.darksky_key, lat, lon, extend='hourly')
if grain == 'second' or grain == 'minute':
try:
# minutely forecasts are only available in some parts of the
# world. test if they work
fc_range = fc.minutely
# they also don't always include temperature, so test this too
_temperature_test = fc.minutely[0].temperature
except AttributeError:
fc_range = fc.hourly
grain = 'hour'
elif grain == 'hour':
fc_range = fc.hourly
elif grain == 'day' or grain == 'week' or grain == 'month' or grain == 'year':
fc_range = fc.daily
try:
summary = fc_range.summary
except AttributeError:
summary = fc_range[0].summary
# if we parsed an interval, create an aggregate forecast
if is_interval:
# trim the ends of the range. note: darksky only provides hourly
# forecasts for the next 48 hours, and daily forecasts for the next
# week
fc_filtered_range = [block for block in fc_range if start_dt.timestamp(
) <= block.time <= end_dt.timestamp()]
aggregate_fc = self.aggregate_forecast(fc_filtered_range)
transformed_forecast = self.transform_forecast(aggregate_fc)
return transformed_forecast + [
{'name': 'summary', 'value': summary},
{'name': 'start_date',
'value': start_dt.strftime('%a, %b %d')},
{'name': 'start_time', 'value': start_dt.strftime('%H:%M')},
{'name': 'end_date', 'value': end_dt.strftime('%a, %b %d')},
{'name': 'end_time', 'value': end_dt.strftime('%H:%M')},
{'name': 'grain', 'value': grain},
]
else:
# return the forecast for that time
transformed_forecast = self.transform_forecast(fc.currently)
return transformed_forecast + [
{'name': 'summary', 'value': summary},
{'name': 'date', 'value': start_dt.strftime('%a, %b %d')},
{'name': 'time', 'value': start_dt.strftime('%H:%M')},
{'name': 'grain', 'value': grain},
]
return timestamp
def rate_satisfaction(self):
return []
def __repr__(self):
'''For executable logs to work, `repr` must generate an executable initialization of this class'''
return 'WeatherInterface(keys["darksky"], keys["wit_date"])'
| nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright 2019 Christian Henning
#
# 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.
"""
@title :test_train.py
@author :ch
@contact :henningc@ethz.ch
@created :08/13/2019
@version :1.0
@python_version :3.6.8
The major goal of these test cases is to ensure that the performance of the
toy regression does not change while this repo is under developement.
"""
# Do not delete the following import for all executable scripts!
import __init__ # pylint: disable=unused-import
import unittest
import sys
import tempfile
import os
import shutil
import contextlib
import time
from toy_example import train
#from tests. test_utils import nostdout
from tests.test_utils import unittest_verbosity
class TrainTestCase(unittest.TestCase):
def setUp(self):
pass # Nothing to setup.
def test_cl_hnet_setup(self):
"""This method tests whether the CL capabilities of the 3 polynomials
toy regression remain as reported in the readme of the corresponding
folder."""
verbosity_level = unittest_verbosity()
targets = [0.004187723621726036, 0.002387890825048089,
0.006071540527045727]
# Without timestamp, test would get stuck/fail if someone mistakenly
# starts the test case twice.
timestamp = int(time.time() * 1000)
out_dir = os.path.join(tempfile.gettempdir(),
'test_cl_hnet_setup_%d' % timestamp)
my_argv = ['foo', '--no_plots', '--no_cuda', '--beta=0.005',
'--emb_size=2', '--n_iter=4001', '--lr_hyper=1e-2',
'--data_random_seed=42', '--out_dir=%s' % out_dir]
sys.argv = list(my_argv)
if os.path.exists(out_dir):
shutil.rmtree(out_dir)
if verbosity_level == 2:
fmse, _, _ = train.run()
else:
#with nostdout():
with open(os.devnull, 'w') as devnull:
with contextlib.redirect_stdout(devnull):
fmse, _, _ = train.run()
shutil.rmtree(out_dir)
self.assertEqual(len(fmse), len(targets))
for i in range(len(fmse)):
self.assertAlmostEqual(fmse[i], targets[i], places=3)
def tearDown(self):
pass # Nothing to clean up.
if __name__ == '__main__':
unittest.main()
| nilq/baby-python | python |
"""manage
BaoAI Backend Main File
PROJECT: BaoAI Backend
VERSION: 2.0.0
AUTHOR: henry <703264459@qq.com>
WEBSITE: http://www.baoai.co
COPYRIGHT: Copyright © 2016-2020 广州源宝网络有限公司 Guangzhou Yuanbao Network Co., Ltd. ( http://www.ybao.org )
LICENSE: Apache-2.0
"""
import os
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell, Server, Command
from flask_script.commands import Clean, ShowUrls
from app import create_app, db
# app,celery = create_app()
app = create_app()
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
from app.modules.admin.model import Admin
return dict(app=app, db=db, Admin=Admin)
# Get BaoAI version and URL # 获取BaoAI版本及官方URL
@manager.command
def baoai():
print('BaoAI v2.0.0 - http://www.baoai.co')
manager.add_command("runserver", Server(host='0.0.0.0', port=5000))
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command("db", MigrateCommand) # Database Manage # 数据库管理
manager.add_command("clean", Clean()) # Clean Cache File # 清理缓存文件
manager.add_command("url", ShowUrls()) # Print All URL # 打印所有URL
if __name__ == "__main__":
manager.run()
| nilq/baby-python | python |
r"""
================================================
CLPT (:mod:`compmech.stiffener.models`)
================================================
.. currentmodule:: compmech.stiffener.models
"""
module_names = [
'bladestiff1d_clt_donnell_bardell',
'bladestiff2d_clt_donnell_bardell',
'tstiff2d_clt_donnell_bardell',
]
for module_name in module_names:
exec('from . import {0}'.format(module_name))
| nilq/baby-python | python |
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# 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 ..types import XMLBase
from .name import Name
from .sdf import SDF
from .description import Description
from .author import Author
from .version import Version
class Model(XMLBase):
_NAME = 'model'
_TYPE = 'sdf_config'
_CHILDREN_CREATORS = dict(
name=dict(creator=Name, default=['model']),
sdf=dict(creator=SDF, default=['1.5'], n_elems='+', optional=True),
description=dict(creator=Description, default=['none']),
author=dict(creator=Author, n_elems='+', optional=True),
version=dict(creator=Version, default=['0.1.0'], optional=True)
)
def __init__(self):
super(Model, self).__init__()
self.reset()
@property
def name(self):
return self._get_child_element('name')
@name.setter
def name(self, value):
self._add_child_element('name', value)
@property
def version(self):
return self._get_child_element('version')
@version.setter
def version(self, value):
self._add_child_element('version', value)
@property
def description(self):
return self._get_child_element('description')
@description.setter
def description(self, value):
self._add_child_element('description', value)
@property
def sdfs(self):
return self._get_child_element('sdf')
@property
def authors(self):
return self._get_child_element('author')
def add_sdf(self, sdf=None):
if sdf is not None:
self._add_child_element('sdf', sdf)
else:
sdf = SDF()
self._add_child_element('sdf', sdf)
def add_author(self, author=None):
if author is not None:
self._add_child_element('author', author)
else:
author = Author()
self._add_child_element('author', author)
| nilq/baby-python | python |
"""This module contains the general information for SuggestedStorageControllerSecurityKey ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class SuggestedStorageControllerSecurityKeyConsts:
pass
class SuggestedStorageControllerSecurityKey(ManagedObject):
"""This is SuggestedStorageControllerSecurityKey class."""
consts = SuggestedStorageControllerSecurityKeyConsts()
naming_props = set([])
mo_meta = {
"classic": MoMeta("SuggestedStorageControllerSecurityKey", "suggestedStorageControllerSecurityKey", "suggested-sec-key", VersionMeta.Version209c, "OutputOnly", 0xf, [], ["admin", "read-only", "user"], [u'storageController'], [], ["Get"]),
"modular": MoMeta("SuggestedStorageControllerSecurityKey", "suggestedStorageControllerSecurityKey", "suggested-sec-key", VersionMeta.Version303a, "OutputOnly", 0xf, [], ["admin", "read-only", "user"], [u'storageController'], [], ["Get"])
}
prop_meta = {
"classic": {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version209c, MoPropertyMeta.INTERNAL, None, None, None, None, [], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version209c, MoPropertyMeta.READ_ONLY, 0x2, 0, 255, None, [], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version209c, MoPropertyMeta.READ_ONLY, 0x4, 0, 255, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version209c, MoPropertyMeta.READ_ONLY, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []),
"suggested_security_key": MoPropertyMeta("suggested_security_key", "suggestedSecurityKey", "string", VersionMeta.Version209c, MoPropertyMeta.READ_ONLY, None, 1, 33, None, [], []),
},
"modular": {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version303a, MoPropertyMeta.INTERNAL, None, None, None, None, [], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version303a, MoPropertyMeta.READ_ONLY, 0x2, 0, 255, None, [], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version303a, MoPropertyMeta.READ_ONLY, 0x4, 0, 255, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version303a, MoPropertyMeta.READ_ONLY, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []),
"suggested_security_key": MoPropertyMeta("suggested_security_key", "suggestedSecurityKey", "string", VersionMeta.Version303a, MoPropertyMeta.READ_ONLY, None, 1, 33, None, [], []),
},
}
prop_map = {
"classic": {
"childAction": "child_action",
"dn": "dn",
"rn": "rn",
"status": "status",
"suggestedSecurityKey": "suggested_security_key",
},
"modular": {
"childAction": "child_action",
"dn": "dn",
"rn": "rn",
"status": "status",
"suggestedSecurityKey": "suggested_security_key",
},
}
def __init__(self, parent_mo_or_dn, **kwargs):
self._dirty_mask = 0
self.child_action = None
self.status = None
self.suggested_security_key = None
ManagedObject.__init__(self, "SuggestedStorageControllerSecurityKey", parent_mo_or_dn, **kwargs)
| nilq/baby-python | python |
from django.shortcuts import render, render_to_response, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.core.context_processors import csrf
from .forms import UserForm, DocForm, DocumentSearchForm
from .models import Document, Course
from haystack.query import SearchQuerySet
def user_login(request):
context = RequestContext(request)
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect('/main/')
else:
return HttpResponse("Your account is disabled.")
else:
print "Invalid login details: {0}, {1}".format(username,password)
return HttpResponse("Invalid login details supplied.")
else:
return render_to_response('login.html',{}, context)
def register(request):
if request.method == "POST":
form = UserForm(request.POST)
if form.is_valid():
new_user = User.objects.create_user(**form.cleaned_data)
return HttpResponseRedirect('/main/thank_you/')
else:
form = UserForm()
return render(request, 'register.html', {'form': form})
def thank_you(request):
return render(request, 'thank_you.html')
def main(request):
if request.user.is_authenticated():
return render(request,'logged_in.html')
return render(request, 'main.html')
def logout_view(request):
logout(request)
return render(request, 'logged_out.html')
def course_form(request):
if request.method == 'POST':
document_form = DocumentForm(request.POST, request.FILES)
if document_form.is_valid():
newdoc = Document(file = request.FILES['file'],
document_subject = request.POST['document_subject'],
)
newdoc.save()
return HttpResponseRedirect('/main/thank_you/')
else:
document_form = DocumentForm()
return render(request,'course.html', {'document_form':document_form})
def doc_form(request):
if request.method == 'POST':
doc_form = DocForm(request.POST,request.FILES)
if doc_form.is_valid():
newdoc = Document.objects.create(**doc_form.cleaned_data)
newdoc.save()
return HttpResponseRedirect('/main/thank_you/')
else:
doc_form = DocForm()
return render(request,'doc_form.html',{'doc_form':doc_form})
def search(request):
documents = SearchQuerySet().filter(content_auto=request.POST.get('search_text', ''))
return render_to_response('ajax_search.html', {'documents' : documents})
def document(request, document_id=1):
return render(request, 'document.html',
{'document': Document.objects.get(id=document_id) })
def more_info(request):
return render(request,'more_info.html')
| nilq/baby-python | python |
#
## https://leetcode.com/problems/palindrome-number/
#
## -2147483648 <= x <= 2147483647
#
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
if int(str(x)[::-1]) > 2147483647 or int(str(x)[::-1]) != x:
return False
return True
| nilq/baby-python | python |
from socket import *
def main():
# Cria host e port number
host = ""
port = 5000
# Cria socket
server = socket(AF_INET, SOCK_DGRAM)
# Indica que o servidor foi iniciado
print("Servidor iniciado")
# Bloco infinito do servidor
while True:
# Recebe a data e o endereço da conexão
data, endereço = server.recvfrom(1024)
# Imprime as informações da conexão
print("Menssagem recebida de", str(endereço))
print("Recebemos do cliente:", str(data))
# Vamos mandar de volta a menssagem em eco
resposta = "Eco=>" + str(data)
server.sendto(data, endereço)
# Fechamos o servidor
server.close()
if __name__ == '__main__':
main()
| nilq/baby-python | python |
import io
import math
import skbio
from scipy.spatial import distance
from scipy.spatial import ConvexHull
import pandas as pd
import numpy as np
from skbio import TreeNode
NUM_TRI = 100
VERTS_PER_TRI = 3
ELEMENTS_PER_VERT = 5
(R_INDEX, G_INDEX, B_INDEX) = (0, 1, 2)
(R_OFFSET, G_OFFSET, B_OFFSET) = (2, 3, 4)
def in_quad_1(angle):
""" Determines if the angle is between 0 and pi / 2 radians
Parameters
----------
angle : float
the angle of a vector in radians
Returns
-------
return : bool
true if angle is between 0 and pi / 2 radians
"""
return True if angle > 0 and angle < math.pi / 2 else False
def in_quad_4(angle):
""" Determines if the angle is between (3 * pi) / 2 radians and 2 * pi
angle : float
the angle of a vector in radians
Returns
-------
return : bool
true is angle is between 0 and pi / 2 radians
"""
return True if angle > 3 * math.pi / 2 and angle < 2 * math.pi else False
def calculate_angle(v):
""" Finds the angle of the two 2-d vectors in radians
Parameters
----------
v : tuple
vector
Returns
-------
angle of vector in radians
"""
if v[0] == 0:
return math.pi / 2 if v[1] > 0 else 3 * math.pi / 2
angle = math.atan(v[1] / v[0])
if v[0] > 0:
return angle if angle >= 0 else 2 * math.pi + angle
else:
return angle + math.pi if angle >= 0 else (2 * math.pi + angle) - math.pi
def name_internal_nodes(tree):
""" Name internal nodes that does not have name
Parameters
----------
tree : skbio.TreeNode or empress.Tree
Input tree with labeled tips and partially unlabeled internal nodes or branch lengths.
Returns
-------
skbio.TreeNode or empress.Tree
Tree with fully labeled internal nodes and branches.
"""
# initialize tree with branch lengths and node names if they are missing
for i, n in enumerate(tree.postorder(include_self=True)):
if n.length is None:
n.length = 1
if n.name is None:
new_name = 'EmpressNode%d' % i
n.name = new_name
def read_metadata(file_name, skip_row=0, seperator='\t'):
""" Reads in metadata for internal nodes
Parameters
----------
file_name : str
The name of the file to read the data from
skip_row : int
The number of rows to skip when reading in the data
seperator : str
The delimiter used in the data file
Returns
-------
pd.Dataframe
"""
if seperator == ' ':
cols = pd.read_csv(
file_name, skiprows=skip_row, nrows=1, delim_whitespace=True).columns.tolist()
# StringIO is used in test cases, without this the tests will fail due to the buffer
# being placed at the end everytime its read
if type(file_name) is io.StringIO:
file_name.seek(0)
metadata = pd.read_table(
file_name, skiprows=skip_row, delim_whitespace=True, dtype={cols[0]: object})
metadata.rename(columns={metadata.columns[0]: "Node_id"}, inplace=True)
else:
cols = pd.read_csv(
file_name, skiprows=skip_row, nrows=1, sep=seperator).columns.tolist()
# StringIO is used in test cases, without this the tests will fail due to the buffer
# being placed at the end everytime its read
if type(file_name) is io.StringIO:
file_name.seek(0)
metadata = pd.read_table(
file_name, skiprows=skip_row, sep=seperator, dtype={cols[0]: object})
metadata.rename(columns={metadata.columns[0]: 'Node_id'}, inplace=True)
return metadata
def read(file_name, file_format='newick'):
""" Reads in contents from a file.
This will create a skbio.TreeNode object
Current Support formats: newick
Future Suppoert formats: phyloxml,
cytoscape network.
cytoscape layout
- networkx
phyloxml
- Python has a parser for it, but it parse it into a phylogeny object.
- We need to parse the phylogeny object into the metadata table by
traversing?
- What is the confidence for each clade?
Parameters
----------
file_name : str
The name of the file to read that contains the tree
file_format : str
The format of the file to read that contains the tree
TODO: Need to create parsers for each of these.
Returns
-------
tree - skbio.TreeNode
A TreeNode object of the newick file
None - null
If a non-newick file_format was passed in
"""
if file_format == 'newick':
tree = skbio.read(file_name, file_format, into=TreeNode)
return tree
return None
def total_angle(a_1, a_2, small_sector=True):
""" determines the starting angle of the sector and total theta of the sector.
Note this is only to be used if the sector is less than pi radians
Parameters
----------
a1 : float
angle (in radians) of one of the edges of the sector
a2 : float
angle (in radians of one of the edges of the sector)
Returns
-------
starting angle : float
the angle at which to start drawing the sector
theta : float
the angle of the sector
"""
# detemines the angle of the sector as well as the angle to start drawing the sector
if small_sector:
if (not (in_quad_1(a_1) and in_quad_4(a_2) or
in_quad_4(a_1) and in_quad_1(a_2))):
a_min, a_max = (min(a_1, a_2), max(a_1, a_2))
if a_max - a_min > math.pi:
a_min += 2 * math.pi
starting_angle = a_max
theta = a_min - a_max
else:
starting_angle = a_2 if a_1 > a_2 else a_1
theta = abs(a_1 - a_2)
else:
starting_angle = a_1 if a_1 > a_2 else a_2
ending_angle = a_1 if starting_angle == a_2 else a_2
theta = ending_angle + abs(starting_angle - 2 * math.pi)
else:
theta = 2 * math.pi - abs(a_1 - a_2)
return theta
def extract_color(color):
"""
A 6 digit hex string representing an (r, g, b) color
"""
HEX_BASE = 16
NUM_CHAR = 2
LARGEST_COLOR = 255
color = color.lower()
color = [color[i: i+NUM_CHAR] for i in range(0, len(color), NUM_CHAR)]
color = [int(hex_string, HEX_BASE) for hex_string in color]
color = [c / LARGEST_COLOR for c in color]
return (color[R_INDEX], color[G_INDEX], color[B_INDEX])
def create_arc_sector(sector_info):
"""
Creates an arc using sector_info:
"""
sector = []
theta = sector_info['theta'] / NUM_TRI
rad = sector_info['starting_angle']
(red, green, blue) = extract_color(sector_info['color'])
c_x = sector_info['center_x']
c_y = sector_info['center_y']
longest_branch = sector_info['largest_branch']
# creating the sector
for i in range(0, NUM_TRI):
# first vertice of triangle
sector.append(c_x)
sector.append(c_y)
sector.append(red)
sector.append(green)
sector.append(blue)
# second vertice of triangle
sector.append(math.cos(rad) * longest_branch + c_x)
sector.append(math.sin(rad) * longest_branch + c_y)
sector.append(red)
sector.append(green)
sector.append(blue)
rad += theta
# third vertice of triangle
sector.append(math.cos(rad) * longest_branch + c_x)
sector.append(math.sin(rad) * longest_branch + c_y)
sector.append(red)
sector.append(green)
sector.append(blue)
return sector
def sector_info(points, sector_center, ancestor_coords):
"""
'create_sector' will find the left most branch, right most branch, deepest branch, and
shortes branch of the clade. Then, 'create_sector' will also find the angle between the
left and right most branch.
Parameter
---------
points : 2-d list
format of list [[x1,y1, x2, y2],...]
center : list
the point in points that will be used as the center of the sector. Note center
should not be in points
ancestor_coords : list
the coordinates of the direct parent of center. Note ancestor_coords should not
be in points
Return
------
sector_info : Dictionary
The keys are center_x, center_y, starting_angle, theta, largest_branch, smallest_branch
"""
# origin
center_point = np.array([[0, 0]])
center = (0, 0)
# find the length of the smallest and longest branches
distances = [distance.euclidean(tip, center) for tip in points]
longest_branch = max(distances)
smallest_branch = min(distances)
# calculate angles of the tip vectors
angles = [calculate_angle(points[x]) for x in range(0, len(points))]
angles = sorted(angles)
# calculate the angle of the vector going from clade root to its direct ancestor
ancestor_angle = calculate_angle((ancestor_coords))
# find position of the left most branch
num_angles = len(angles)
l_branch = [i for i in range(0, num_angles - 1) if angles[i] < ancestor_angle < angles[i + 1]]
l_found = len(l_branch) > 0
l_index = l_branch[0] if l_found else 0
# the left and right most branches
(a_1, a_2) = (angles[l_index], angles[l_index + 1]) if l_found else (angles[l_index], angles[-1])
# detemines the starting angle(left most branch) of the sectorr
if l_found:
starting_angle = a_1 if a_1 > a_2 else a_2
else:
starting_angle = a_2 if a_1 > a_2 else a_1
# calculate the angle between the left and right most branches
small_sector = False if angles[-1] - angles[0] > math.pi else True
theta = total_angle(a_1, a_2, small_sector)
# the sector webgl will draw
colored_clades = {
'center_x': sector_center[0], 'center_y': sector_center[1],
'starting_angle': starting_angle, 'theta': theta,
'largest_branch': longest_branch, 'smallest_branch': smallest_branch}
return colored_clades
| nilq/baby-python | python |
from kimonet.system.generators import regular_system, crystal_system
from kimonet.analysis import visualize_system, TrajectoryAnalysis
from kimonet.system.molecule import Molecule
from kimonet import system_test_info
from kimonet.core.processes.couplings import forster_coupling
from kimonet.core.processes.decays import einstein_radiative_decay
from kimonet.core.processes.types import GoldenRule, DecayRate, DirectRate
from kimonet.system.vibrations import MarcusModel, LevichJortnerModel, EmpiricalModel
from kimonet.fileio import store_trajectory_list, load_trajectory_list
from kimonet.analysis import plot_polar_plot
from kimonet import calculate_kmc, calculate_kmc_parallel, calculate_kmc_parallel_py2
from kimonet.system.state import State
from kimonet.system.state import ground_state as gs
from kimonet.core.processes.transitions import Transition
import numpy as np
# states list
s1 = State(label='s1', energy=20.0, multiplicity=1)
# transition moments
transitions = [Transition(s1, gs,
tdm=[0.1, 0.0], # a.u.
reorganization_energy=0.08)] # eV
# define system as a crystal
molecule = Molecule()
#print(molecule, molecule.state, molecule.state.get_center())
molecule2 = Molecule(site_energy=2)
print(molecule2, molecule2.state, molecule2.state.get_center())
print(molecule, molecule.state, molecule.state.get_center())
system = crystal_system(molecules=[molecule, molecule], # molecule to use as reference
scaled_site_coordinates=[[0.0, 0.0],
[0.0, 0.5]],
unitcell=[[5.0, 1.0],
[1.0, 5.0]],
dimensions=[2, 2], # supercell size
orientations=[[0.0, 0.0, np.pi/2],
[0.0, 0.0, 0.0]]) # if element is None then random, if list then Rx Ry Rz
print([m.site_energy for m in system.molecules])
print(system.get_ground_states())
# set initial exciton
system.add_excitation_index(s1, 0)
system.add_excitation_index(s1, 1)
# set additional system parameters
system.process_scheme = [GoldenRule(initial_states=(s1, gs), final_states=(gs, s1),
electronic_coupling_function=forster_coupling,
description='Forster coupling',
arguments={'ref_index': 1,
'transitions': transitions},
vibrations=MarcusModel(transitions=transitions) # eV
),
DecayRate(initial_state=s1, final_state=gs,
decay_rate_function=einstein_radiative_decay,
arguments={'transitions': transitions},
description='custom decay rate')
]
system.cutoff_radius = 8 # interaction cutoff radius in Angstrom
# some system analyze functions
system_test_info(system)
visualize_system(system)
# do the kinetic Monte Carlo simulation
trajectories = calculate_kmc(system,
num_trajectories=5, # number of trajectories that will be simulated
max_steps=100, # maximum number of steps for trajectory allowed
silent=False)
# specific trajectory plot
trajectories[0].plot_graph().show()
trajectories[0].plot_2d().show()
# resulting trajectories analysis
analysis = TrajectoryAnalysis(trajectories)
print('diffusion coefficient: {:9.5e} Angs^2/ns'.format(analysis.diffusion_coefficient()))
print('lifetime: {:9.5e} ns'.format(analysis.lifetime()))
print('diffusion length: {:9.5e} Angs'.format(analysis.diffusion_length()))
for state in analysis.get_states():
print('\nState: {}\n--------------------------------'.format(state))
print('diffusion coefficient: {:9.5e} Angs^2/ns'.format(analysis.diffusion_coefficient(state)))
print('lifetime: {:9.5e} ns'.format(analysis.lifetime(state)))
print('diffusion length: {:9.5e} Angs'.format(analysis.diffusion_length(state)))
print('diffusion tensor (angs^2/ns)')
print(analysis.diffusion_coeff_tensor(state))
print('diffusion length tensor (Angs)')
print(analysis.diffusion_length_square_tensor(state))
plot_polar_plot(analysis.diffusion_coeff_tensor(state),
title='Diffusion', plane=[0, 1])
plot_polar_plot(analysis.diffusion_length_square_tensor(state, unit_cell=[[5.0, 1.0],
[1.0, 5.0]]),
title='Diffusion length square', crystal_labels=True, plane=[0, 1])
analysis.plot_exciton_density('s1').show()
analysis.plot_2d('s1').show()
analysis.plot_distances('s1').show()
analysis.plot_histogram('s1').show()
analysis.plot_histogram('s1').savefig('histogram_s1.png')
store_trajectory_list(trajectories, 'example_simple.h5')
| nilq/baby-python | python |
import numpy as np
import pytest
from quara.loss_function.loss_function import LossFunction, LossFunctionOption
class TestLossFunctionOption:
def test_access_mode_weight(self):
loss_option = LossFunctionOption()
assert loss_option.mode_weight == None
loss_option = LossFunctionOption(
mode_weight="mode", weights=[1, 2, 3], weight_name="name"
)
assert loss_option.mode_weight == "mode"
# Test that "mode_weight" cannot be updated
with pytest.raises(AttributeError):
loss_option.mode_weight = "mode"
def test_access_weights(self):
loss_option = LossFunctionOption()
assert loss_option.weights == None
loss_option = LossFunctionOption(
mode_weight="mode", weights=[1, 2, 3], weight_name="name"
)
assert loss_option.weights == [1, 2, 3]
# Test that "weights" cannot be updated
with pytest.raises(AttributeError):
loss_option.weights = [1, 2, 3]
def test_access_weight_name(self):
loss_option = LossFunctionOption()
assert loss_option.weight_name == None
loss_option = LossFunctionOption(
mode_weight="mode", weights=[1, 2, 3], weight_name="name"
)
assert loss_option.weight_name == "name"
# Test that "weight_name" cannot be updated
with pytest.raises(AttributeError):
loss_option.weight_name = "name"
class TestLossFunction:
def test_access_num_var(self):
loss_func = LossFunction(4)
assert loss_func.num_var == 4
# Test that "num_var" cannot be updated
with pytest.raises(AttributeError):
loss_func.num_var = 5
def test_access_option(self):
loss_func = LossFunction(4)
assert loss_func.option == None
loss_func.set_from_option(LossFunctionOption())
assert loss_func.option != None
def test_access_on_value(self):
loss_func = LossFunction(4)
assert loss_func.on_value == False
# Test that "on_value" cannot be updated
with pytest.raises(AttributeError):
loss_func.on_value = True
def test_reset_on_value(self):
loss_func = LossFunction(4)
loss_func._on_value = True
loss_func._reset_on_value()
assert loss_func.on_value == False
def test_set_on_value(self):
loss_func = LossFunction(4)
loss_func._set_on_value(True)
assert loss_func.on_value == True
loss_func._set_on_value(False)
assert loss_func.on_value == False
def test_access_on_gradient(self):
loss_func = LossFunction(4)
assert loss_func.on_gradient == False
# Test that "on_gradient" cannot be updated
with pytest.raises(AttributeError):
loss_func.on_gradient = True
def test_reset_on_gradient(self):
loss_func = LossFunction(4)
loss_func._on_gradient = True
loss_func._reset_on_gradient()
assert loss_func.on_gradient == False
def test_set_on_gradient(self):
loss_func = LossFunction(4)
loss_func._set_on_gradient(True)
assert loss_func.on_gradient == True
loss_func._set_on_gradient(False)
assert loss_func.on_gradient == False
def test_access_on_hessian(self):
loss_func = LossFunction(4)
assert loss_func.on_hessian == False
# Test that "on_hessian" cannot be updated
with pytest.raises(AttributeError):
loss_func.on_hessian = True
def test_reset_on_hessian(self):
loss_func = LossFunction(4)
loss_func._on_hessian = True
loss_func._reset_on_hessian()
assert loss_func.on_hessian == False
def test_set_on_hessian(self):
loss_func = LossFunction(4)
loss_func._set_on_hessian(True)
assert loss_func.on_hessian == True
loss_func._set_on_hessian(False)
assert loss_func.on_hessian == False
def test_validate_var_shape(self):
loss_func = LossFunction(4)
var = np.array([1, 2, 3, 4], dtype=np.float64)
loss_func._validate_var_shape(var)
var = np.array([1, 2, 3, 4, 5], dtype=np.float64)
with pytest.raises(ValueError):
loss_func._validate_var_shape(var)
| nilq/baby-python | python |
import os
import io
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
def get_readme():
path = os.path.join(here, 'README.md')
with io.open(path, encoding='utf-8') as f:
return '\n' + f.read()
setup(
name='ndc_parser',
version='0.1',
description='NDC Parser',
long_description=get_readme(),
long_description_content_type='text/markdown',
url='https://github.com/ndc-dev/python-parser',
author='CALIL Inc.',
author_email='info@calil.jp',
license='MIT',
keywords='NDC Nippon Decimal Classification Parser',
packages=[
"ndc_parser",
],
install_requires=[],
) | nilq/baby-python | python |
import unittest
import torch
from fn import F
from fn.op import apply
from tensorneko.layer import Linear
from torch.nn import Linear as PtLinear, LeakyReLU, BatchNorm1d, Tanh
class TestLinear(unittest.TestCase):
@property
def batch(self):
return 4
@property
def in_neurons(self):
return 128
@property
def out_neurons(self):
return 32
def test_simple_linear_layer(self):
# build layers
neko_linear = Linear(self.in_neurons, self.out_neurons, True)
# test definition
self.assertEqual(str(neko_linear.linear), str(PtLinear(self.in_neurons, self.out_neurons, True)))
self.assertIs(neko_linear.activation, None)
self.assertIs(neko_linear.normalization, None)
# test feedforward
x = torch.rand(self.batch, self.in_neurons) # four 128-dim vectors
neko_res, pt_res = map(F(apply, args=[x]), [neko_linear, neko_linear.linear])
self.assertTrue((pt_res - neko_res).sum() < 1e-8)
def test_linear_with_activation(self):
# build layers
neko_linear = Linear(self.in_neurons, self.out_neurons, False, build_activation=LeakyReLU)
# test definition
self.assertEqual(str(neko_linear.linear), str(PtLinear(self.in_neurons, self.out_neurons, False)))
self.assertEqual(str(neko_linear.activation), str(LeakyReLU()))
self.assertIs(neko_linear.normalization, None)
# test feedforward
x = torch.rand(self.batch, self.in_neurons) # four 128-dim vectors
neko_res, pt_res = map(F(apply, args=[x]), [neko_linear, F() >> neko_linear.linear >> neko_linear.activation])
self.assertTrue((pt_res - neko_res).sum() < 1e-8)
def test_linear_with_activation_after_normalization(self):
# build layers
neko_linear = Linear(self.in_neurons, self.out_neurons, True, build_activation=Tanh,
build_normalization=F(BatchNorm1d, self.out_neurons),
normalization_after_activation=False
)
# test definition
self.assertEqual(str(neko_linear.linear), str(PtLinear(self.in_neurons, self.out_neurons, True)))
self.assertEqual(str(neko_linear.activation), str(Tanh()))
self.assertEqual(str(neko_linear.normalization), str(BatchNorm1d(self.out_neurons)))
# test feedforward
x = torch.rand(self.batch, self.in_neurons) # four 128-dim vectors
neko_res, pt_res = map(F(apply, args=[x]), [neko_linear,
F() >> neko_linear.linear >> neko_linear.normalization >> neko_linear.activation]
)
self.assertTrue((pt_res - neko_res).sum() < 1e-8)
def test_linear_with_activation_before_normalization(self):
# build layers
neko_linear = Linear(self.in_neurons, self.out_neurons, True, build_activation=Tanh,
build_normalization=F(BatchNorm1d, self.out_neurons),
normalization_after_activation=True
)
# test definition
self.assertEqual(str(neko_linear.linear), str(PtLinear(self.in_neurons, self.out_neurons, True)))
self.assertEqual(str(neko_linear.activation), str(Tanh()))
self.assertEqual(str(neko_linear.normalization), str(BatchNorm1d(self.out_neurons)))
# test feedforward
x = torch.rand(self.batch, self.in_neurons) # four 128-dim vectors
neko_res, pt_res = map(F(apply, args=[x]), [neko_linear,
F() >> neko_linear.linear >> neko_linear.activation >> neko_linear.normalization]
)
self.assertTrue((pt_res - neko_res).sum() < 1e-8)
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2016, RadsiantBlue Technologies, 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.
from flask import Flask
from flask import request
import json
import signal
import sys
import time
import mongo
import loop
import common
class HttpMessage:
statusCode = 0
data = ""
def __init__(self,statusCode=None,message=None):
if statusCode is not None:
self.statusCode=statusCode
else:
self.statusCode=200
if message is not None:
self.data = message
else:
self.data = "Hi! I'm a monitor lizard!"
def setMessage(self,message):
self.data = message
def setStatusCode(self,statusCode):
self.statusCode=statusCode
def getJSON(self):
return json.dumps(self.__dict__, indent=2)
def getHTML(self):
return '<pre style="word-wrap: break-word; white-space: pre-wrap;">'+self.getJSON()+'</pre>'
class AdminStats:
def __init__(self, createdAt=time.time(),online=0,degraded=0,failed=0,unknown=0):
self.createdAt = createdAt
self.online=online
self.degraded=degraded
self.failed=failed
self.unknown=unknown
def update(self,mong):
if not common.mongoFound:
return
self.online,self.degraded,self.failed,self.unknown = 0,0,0,0
services = mong.get_services()
for service in services:
meta = mongo.ResourceMetaDataInterface(**service.resourceMetadata)
av = None
try:
av = meta.availability
except:
pass
if av == None:
self.unknown+=1
elif av == mongo.ONLINE:
self.online+=1
elif av == mongo.DEGRADED:
self.degraded+=1
elif av == mongo.FAILED:
self.failed+=1
else:
self.unknown+=1
def getJSON(self):
if not common.mongoFound:
return HttpMessage(200,"MongoDB could not be found.").getJSON()
return json.dumps(self.__dict__, indent=2)
app = Flask(__name__)
mong = mongo.Mongo()
mongExists=mong.env_found()
loopThread = loop.LoopingThread(interval=20,mong=mong)
adminStats = AdminStats()
@app.route("/",methods=['GET'])
def helloWorld():
return HttpMessage().getJSON()
@app.route("/admin/stats", methods=['GET'])
def adminStat():
adminStats.update(mong)
return adminStats.getJSON()
@app.route("/hello")
def hello():
return "<html>Hello world</html>"
@app.route('/test', methods=['GET','POST'])
def test():
if request.method == 'GET':
return HttpMessage(200,"GET").getJSON()
elif request.method == 'POST':
if not request.is_json:
return HttpMessage(400,"Payload is not of type json").getJSON()
jsn = request.get_json()
if jsn is None:
return HttpMessage(400,"Bad payload").getJSON()
return HttpMessage(200,jsn).getJSON()
else:
return HttpMessage(400,"Bad request").getJSON()
def signal_handler(signal, frame):
print('Shutting down...')
loopThread.stop()
sys.exit(0)
if __name__ =="__main__":
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
loopThread.start()
app.run()
| nilq/baby-python | python |
def max_val(t):
"""
t, tuple or list
Each element of t is either an int, a tuple, or a list
No tuple or list is empty
Returns the maximum int in t or (recursively) in an element of t
"""
def find_all_int(data):
int_list = []
for item in data:
if isinstance(item, list) or isinstance(item, tuple):
int_list.extend(find_all_int(item))
elif isinstance(item, int):
int_list.append(item)
return int_list
return max(find_all_int(t))
print(max_val((5, (1,2), [[1],[9]]))) | nilq/baby-python | python |
from __future__ import absolute_import
# noinspection PyUnresolvedReferences
from .ABuPickStockExecute import do_pick_stock_work
# noinspection PyUnresolvedReferences
from .ABuPickTimeExecute import do_symbols_with_same_factors, do_symbols_with_diff_factors
# noinspection all
from . import ABuPickTimeWorker as pick_time_worker
| nilq/baby-python | python |
#!/usr/bin/env python2.7
# license removed for brevity
import rospy
import numpy as np
import json
import time
from std_msgs.msg import String
from std_msgs.msg import Bool
from rospy.numpy_msg import numpy_msg
from feedback_cclfd.srv import RequestFeedback
from feedback_cclfd.srv import PerformDemonstration
from feedback_cclfd.msg import ConstraintTypes
from cairo_nlp.srv import TTS, TTSResponse
""" This class is responsible for sampling constraints and
demonstrating them to the user for feedback. """
class Demonstrator():
def __init__(self):
rospy.init_node('demonstrator')
self.finished_first_demo = False
# start pub/sub
rospy.Subscriber("/planners/constraint_types",
numpy_msg(ConstraintTypes),
self.sample_demonstrations)
self.demos_pub = rospy.Publisher(
"/planners/demonstrations", String, queue_size=10)
# set up client for demonstration service
rospy.wait_for_service("feedback_demonstration")
try:
self.feedback_demonstration = rospy.ServiceProxy(
"feedback_demonstration", PerformDemonstration)
except rospy.ServiceException:
rospy.logwarn("Service setup failed (feedback_demonstration)")
# set up client for feedback service
rospy.wait_for_service("request_feedback")
try:
self.request_feedback = rospy.ServiceProxy(
"request_feedback", RequestFeedback)
except rospy.ServiceException:
rospy.logwarn("Service setup failed (request_feedback)")
# Set up client for NLP TTS service
rospy.wait_for_service("/nlp/google/tts")
try:
self.tts_server = rospy.ServiceProxy(
"/nlp/google/tts", TTS)
except rospy.ServiceException:
rospy.logerr("Service setup failed (/nlp/google/tts)")
rospy.loginfo("DEMONSTRATOR: Starting...")
def run(self):
# perform a bad demo to start
rospy.loginfo("DEMONSTRATOR: Starting first skill execution...")
self.tts_server("I am going to hand you the mug.")
finished = self.feedback_demonstration(0) # 0 = negative
if finished.response:
self.finished_first_demo = True
rospy.spin()
def sample_demonstrations(self, constraint_types):
# run until complete
while True:
# don't perform alternative demos until first is finished
if self.finished_first_demo:
num_demos = 2
rospy.loginfo("DEMONSTRATOR: Sampling demonstrations...")
cur_type = constraint_types.data
results = dict()
for i in range(0, num_demos):
# perform a single demonstration
constraint = i
self.tts_server("I am going to try the skill again.")
finished = self.feedback_demonstration(constraint)
if finished.response:
# request feedback about demonstration from user
feedback_type = constraint == 1
msg = self.request_feedback(feedback_type)
key = i
if msg.response:
rospy.loginfo(
"DEMONSTRATOR: Response was POSITIVE!")
results[key] = 1
else:
rospy.loginfo(
"DEMONSTRATOR: Response was NEGATIVE")
results[key] = 0
# save feedback results
rospy.loginfo("DEMONSTRATOR: Saving feedback...")
encoded_data_string = json.dumps(results)
self.demos_pub.publish(encoded_data_string)
# demonstrate what has been learned
rospy.loginfo("DEMONSTRATOR: Showing what has been learned...")
self.tts_server("Let me show you what I have learned.")
for key, value in results.items():
if value:
constraint = key
self.feedback_demonstration(constraint)
break
break
else:
# wait a second
rospy.loginfo(
"DEMONSTRATOR: Waiting for first demo to be finished...")
time.sleep(1)
self.tts_server("Thank you for helping me learn!")
rospy.loginfo("FINISHED!!!")
if __name__ == '__main__':
try:
obj = Demonstrator()
obj.run()
except rospy.ROSInterruptException:
pass
| nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2016-2017 China Telecommunication Co., Ltd.
#
# 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 ctypes
import datetime
from bprint import cp
class KLog(object):
#
# Const
#
KLOG_FATAL = ctypes.c_uint(0x00000001)
KLOG_ALERT = ctypes.c_uint(0x00000002)
KLOG_CRIT = ctypes.c_uint(0x00000004)
KLOG_ERR = ctypes.c_uint(0x00000008)
KLOG_WARNING = ctypes.c_uint(0x00000010)
KLOG_NOTICE = ctypes.c_uint(0x00000020)
KLOG_INFO = ctypes.c_uint(0x00000040)
KLOG_DEBUG = ctypes.c_uint(0x00000080)
_filepath = "/dev/stdout"
_to_stderr = False
_to_stdout = True
_to_file = False
_to_network = False
@classmethod
def to_stderr(cls, enable=True):
cls._to_stderr = enable
@classmethod
def to_stdout(cls, enable=True):
cls._to_stdout = enable
@classmethod
def to_file(
cls,
pathfmt="/tmp/klog-%N%Y%R_%S%F%M-%U-%P-%I.log",
size=0,
time=0,
when=0,
enable=True):
cls._to_file = enable
now = datetime.datetime.now()
path = pathfmt
path = path.replace("%N", "%04d" % (now.year))
path = path.replace("%Y", "%02d" % (now.month))
path = path.replace("%R", "%02d" % (now.day))
path = path.replace("%S", "%02d" % (now.hour))
path = path.replace("%F", "%02d" % (now.minute))
path = path.replace("%M", "%02d" % (now.second))
path = path.replace("%I", "0000")
path = path.replace("%U", os.environ.get("USER"))
cls._filepath = path
cls._logfile = open(cls._filepath, "a")
print(cls._logfile)
@classmethod
def to_network(cls, addr="127.0.0.1", port=7777, enable=True):
pass
def __init__(self, frame):
pass
@classmethod
def _log(cls, indi, mask, nl, *str_segs):
now = datetime.datetime.now()
frame = sys._getframe(2)
_x_ln = frame.f_lineno
_x_fn = frame.f_code.co_filename
_x_func = frame.f_code.co_name
ts = "%s.%03d" % (now.strftime("%Y/%m/%d %H:%M:%S"), now.microsecond / 1000)
fullstr = ""
for seg in str_segs:
try:
s = str(seg)
except:
try:
s = unicode(seg)
except:
s = seg.encode("utf-8")
fullstr += s
nl = "\n" if nl else ""
line = "|%s|%s|%s|%s|%s| %s%s" % (cp.r(indi), cp.y(ts),
_x_fn, cp.c(_x_func), cp.c(_x_ln), fullstr, nl)
if cls._to_stderr:
sys.stderr.write(line)
if cls._to_stdout:
sys.stdout.write(line)
sys.stdout.flush()
if cls._to_file:
cls._logfile.write(line)
cls._logfile.flush()
if cls._to_network:
pass
@classmethod
def f(cls, *str_segs):
'''fatal'''
KLog._log('F', cls.KLOG_FATAL, True, *str_segs)
@classmethod
def a(cls, *str_segs):
'''alert'''
KLog._log('A', cls.KLOG_ALERT, True, *str_segs)
@classmethod
def c(cls, *str_segs):
'''critical'''
KLog._log('C', cls.KLOG_CRIT, True, *str_segs)
@classmethod
def e(cls, *str_segs):
'''error'''
KLog._log('E', cls.KLOG_ERR, True, *str_segs)
@classmethod
def w(cls, *str_segs):
'''warning'''
KLog._log('W', cls.KLOG_WARNING, True, *str_segs)
@classmethod
def i(cls, *str_segs):
'''info'''
KLog._log('I', cls.KLOG_INFO, True, *str_segs)
@classmethod
def n(cls, *str_segs):
'''notice'''
KLog._log('N', cls.KLOG_NOTICE, True, *str_segs)
@classmethod
def d(cls, *str_segs):
'''debug'''
KLog._log('D', cls.KLOG_DEBUG, True, *str_segs)
klog = KLog
| nilq/baby-python | python |
# Test case that runs in continuous integration to ensure that PTest isn't broken.
from .base import SingleSatOnlyCase
from .utils import Enums, TestCaseFailure
import os
class CICase(SingleSatOnlyCase):
def run_case_singlesat(self):
self.sim.cycle_no = int(self.sim.flight_controller.read_state("pan.cycle_no"))
if self.sim.cycle_no != 1:
raise TestCaseFailure(f"Cycle number was incorrect: expected {1} got {self.sim.cycle_no}.")
self.sim.flight_controller.write_state("cycle.start", "true")
self.sim.cycle_no = int(self.sim.flight_controller.read_state("pan.cycle_no"))
if self.sim.cycle_no != 2:
raise TestCaseFailure(f"Cycle number was incorrect: expected {2} got {self.sim.cycle_no}.")
self.finish()
| nilq/baby-python | python |
from __future__ import division
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import normal_init
from mmcv.cnn import constant_init
from mmdet.core import (PointGenerator, multi_apply, multiclass_rnms,
images_to_levels, unmap)
from mmdet.core import (ConvexPseudoSampler, assign_and_sample, build_assigner)
from mmdet.ops import ConvModule, DeformConv
from ..builder import build_loss
from ..registry import HEADS
from ..utils import bias_init_with_prob
from mmdet.ops.minareabbox import find_minarea_rbbox
from mmdet.ops.iou import convex_iou
INF = 100000000
eps = 1e-12
def levels_to_images(mlvl_tensor, flatten=False):
batch_size = mlvl_tensor[0].size(0)
batch_list = [[] for _ in range(batch_size)]
if flatten:
channels = mlvl_tensor[0].size(-1)
else:
channels = mlvl_tensor[0].size(1)
for t in mlvl_tensor:
if not flatten:
t = t.permute(0, 2, 3, 1)
t = t.view(batch_size, -1, channels).contiguous()
for img in range(batch_size):
batch_list[img].append(t[img])
return [torch.cat(item, 0) for item in batch_list]
@HEADS.register_module
class CFAHead(nn.Module):
def __init__(self,
num_classes,
in_channels,
feat_channels=256,
point_feat_channels=256,
stacked_convs=3,
num_points=9,
gradient_mul=0.1,
point_strides=[8, 16, 32, 64, 128],
point_base_scale=4,
conv_cfg=None,
norm_cfg=None,
loss_cls=dict(
type='FocalLoss',
use_sigmoid=True,
gamma=2.0,
alpha=0.25,
loss_weight=1.0),
loss_bbox_init=dict(
type='SmoothL1Loss', loss_weight=0.375),
loss_bbox_refine=dict(
type='SmoothL1Loss', loss_weight=0.75),
center_init=True,
transform_method='rotrect',
show_points=False,
use_cfa=False,
topk=6,
anti_factor=0.75):
super(CFAHead, self).__init__()
self.in_channels = in_channels
self.num_classes = num_classes
self.feat_channels = feat_channels
self.point_feat_channels = point_feat_channels
self.stacked_convs = stacked_convs
self.num_points = num_points
self.gradient_mul = gradient_mul
self.point_base_scale = point_base_scale
self.point_strides = point_strides
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
self.use_sigmoid_cls = loss_cls.get('use_sigmoid', False)
self.sampling = loss_cls['type'] not in ['FocalLoss']
self.loss_cls = build_loss(loss_cls)
self.loss_bbox_init = build_loss(loss_bbox_init)
self.loss_bbox_refine = build_loss(loss_bbox_refine)
self.center_init = center_init
self.transform_method = transform_method
self.show_points = show_points
self.use_cfa = use_cfa
self.topk = topk
self.anti_factor = anti_factor
if self.use_sigmoid_cls:
self.cls_out_channels = self.num_classes - 1
else:
self.cls_out_channels = self.num_classes
self.point_generators = [PointGenerator() for _ in self.point_strides]
# we use deformable conv to extract points features
self.dcn_kernel = int(np.sqrt(num_points))
self.dcn_pad = int((self.dcn_kernel - 1) / 2)
assert self.dcn_kernel * self.dcn_kernel == num_points, \
'The points number should be a square number.'
assert self.dcn_kernel % 2 == 1, \
'The points number should be an odd square number.'
dcn_base = np.arange(-self.dcn_pad,
self.dcn_pad + 1).astype(np.float64)
dcn_base_y = np.repeat(dcn_base, self.dcn_kernel)
dcn_base_x = np.tile(dcn_base, self.dcn_kernel)
dcn_base_offset = np.stack([dcn_base_y, dcn_base_x], axis=1).reshape(
(-1))
self.dcn_base_offset = torch.tensor(dcn_base_offset).view(1, -1, 1, 1)
self._init_layers()
def _init_layers(self):
self.relu = nn.ReLU(inplace=True)
self.cls_convs = nn.ModuleList()
self.reg_convs = nn.ModuleList()
for i in range(self.stacked_convs):
chn = self.in_channels if i == 0 else self.feat_channels
self.cls_convs.append(
ConvModule(
chn,
self.feat_channels,
3,
stride=1,
padding=1,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg))
self.reg_convs.append(
ConvModule(
chn,
self.feat_channels,
3,
stride=1,
padding=1,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg))
pts_out_dim = 2 * self.num_points
self.reppoints_cls_conv = DeformConv(self.feat_channels,
self.point_feat_channels,
self.dcn_kernel, 1, self.dcn_pad)
self.reppoints_cls_out = nn.Conv2d(self.point_feat_channels,
self.cls_out_channels, 1, 1, 0)
self.reppoints_pts_init_conv = nn.Conv2d(self.feat_channels,
self.point_feat_channels, 3,
1, 1)
self.reppoints_pts_init_out = nn.Conv2d(self.point_feat_channels,
pts_out_dim, 1, 1, 0)
self.reppoints_pts_refine_conv = DeformConv(self.feat_channels,
self.point_feat_channels,
self.dcn_kernel, 1,
self.dcn_pad)
self.reppoints_pts_refine_out = nn.Conv2d(self.point_feat_channels,
pts_out_dim, 1, 1, 0)
def init_weights(self):
for m in self.cls_convs:
normal_init(m.conv, std=0.01)
for m in self.reg_convs:
normal_init(m.conv, std=0.01)
bias_cls = bias_init_with_prob(0.01)
normal_init(self.reppoints_cls_conv, std=0.01)
normal_init(self.reppoints_cls_out, std=0.01, bias=bias_cls)
normal_init(self.reppoints_pts_init_conv, std=0.01)
normal_init(self.reppoints_pts_init_out, std=0.01)
normal_init(self.reppoints_pts_refine_conv, std=0.01)
normal_init(self.reppoints_pts_refine_out, std=0.01)
def convex_overlaps(self, gt_rbboxes, points):
overlaps = convex_iou(points, gt_rbboxes)
overlaps = overlaps.transpose(1, 0) # [gt, ex]
return overlaps
def points2rotrect(self, pts, y_first=True):
if y_first:
pts = pts.reshape(-1, self.num_points, 2)
pts_dy = pts[:, :, 0::2]
pts_dx = pts[:, :, 1::2]
pts = torch.cat([pts_dx, pts_dy], dim=2).reshape(-1, 2 * self.num_points)
if self.transform_method == 'rotrect':
rotrect_pred = find_minarea_rbbox(pts)
return rotrect_pred
else:
raise NotImplementedError
def forward_single(self, x):
dcn_base_offset = self.dcn_base_offset.type_as(x)
# If we use center_init, the initial reppoints is from center points.
# If we use bounding bbox representation, the initial reppoints is
# from regular grid placed on a pre-defined bbox.
points_init = 0
cls_feat = x
pts_feat = x
for cls_conv in self.cls_convs:
cls_feat = cls_conv(cls_feat)
for reg_conv in self.reg_convs:
pts_feat = reg_conv(pts_feat)
# initialize reppoints
pts_out_init = self.reppoints_pts_init_out(
self.relu(self.reppoints_pts_init_conv(pts_feat)))
pts_out_init = pts_out_init + points_init
# refine and classify reppoints
pts_out_init_grad_mul = (1 - self.gradient_mul) * pts_out_init.detach() + self.gradient_mul * pts_out_init
dcn_offset = pts_out_init_grad_mul - dcn_base_offset
dcn_cls_feat = self.reppoints_cls_conv(cls_feat, dcn_offset)
cls_out = self.reppoints_cls_out(self.relu(dcn_cls_feat))
pts_out_refine = self.reppoints_pts_refine_out(self.relu(self.reppoints_pts_refine_conv(pts_feat, dcn_offset)))
pts_out_refine = pts_out_refine + pts_out_init.detach()
return cls_out, pts_out_init, pts_out_refine
def forward(self, feats):
return multi_apply(self.forward_single, feats)
def get_points(self, featmap_sizes, img_metas):
num_imgs = len(img_metas)
num_levels = len(featmap_sizes)
# since feature map sizes of all images are the same, we only compute
# points center for one time
multi_level_points = []
for i in range(num_levels):
points = self.point_generators[i].grid_points(
featmap_sizes[i], self.point_strides[i])
multi_level_points.append(points)
points_list = [[point.clone() for point in multi_level_points]
for _ in range(num_imgs)]
# for each image, we compute valid flags of multi level grids
valid_flag_list = []
for img_id, img_meta in enumerate(img_metas):
multi_level_flags = []
for i in range(num_levels):
point_stride = self.point_strides[i]
feat_h, feat_w = featmap_sizes[i]
h, w = img_meta['pad_shape'][:2]
valid_feat_h = min(int(np.ceil(h / point_stride)), feat_h)
valid_feat_w = min(int(np.ceil(w / point_stride)), feat_w)
flags = self.point_generators[i].valid_flags(
(feat_h, feat_w), (valid_feat_h, valid_feat_w))
multi_level_flags.append(flags)
valid_flag_list.append(multi_level_flags)
return points_list, valid_flag_list
def offset_to_pts(self, center_list, pred_list):
pts_list = []
for i_lvl in range(len(self.point_strides)):
pts_lvl = []
for i_img in range(len(center_list)):
pts_center = center_list[i_img][i_lvl][:, :2].repeat(
1, self.num_points)
pts_shift = pred_list[i_lvl][i_img]
yx_pts_shift = pts_shift.permute(1, 2, 0).view(-1, 2 * self.num_points)
y_pts_shift = yx_pts_shift[..., 0::2]
x_pts_shift = yx_pts_shift[..., 1::2]
xy_pts_shift = torch.stack([x_pts_shift, y_pts_shift], -1)
xy_pts_shift = xy_pts_shift.view(*yx_pts_shift.shape[:-1], -1)
pts = xy_pts_shift * self.point_strides[i_lvl] + pts_center
pts_lvl.append(pts)
pts_lvl = torch.stack(pts_lvl, 0)
pts_list.append(pts_lvl)
return pts_list
def loss_single(self, cls_score, pts_pred_init, pts_pred_refine, labels,
label_weights, rbbox_gt_init, convex_weights_init,
rbbox_gt_refine, convex_weights_refine, stride, num_total_samples_refine):
normalize_term = self.point_base_scale * stride
if self.use_cfa:
rbbox_gt_init = rbbox_gt_init.reshape(-1, 8)
convex_weights_init = convex_weights_init.reshape(-1)
pts_pred_init = pts_pred_init.reshape(-1, 2 * self.num_points) # [B, NUM(H * W), 2*num_pint]
pos_ind_init = (convex_weights_init > 0).nonzero().reshape(-1)
pts_pred_init_norm = pts_pred_init[pos_ind_init]
rbbox_gt_init_norm = rbbox_gt_init[pos_ind_init]
convex_weights_pos_init = convex_weights_init[pos_ind_init]
loss_pts_init = self.loss_bbox_init(
pts_pred_init_norm / normalize_term,
rbbox_gt_init_norm / normalize_term,
convex_weights_pos_init
)
return 0, loss_pts_init, 0
else:
rbbox_gt_init = rbbox_gt_init.reshape(-1, 8)
convex_weights_init = convex_weights_init.reshape(-1)
# init points loss
pts_pred_init = pts_pred_init.reshape(-1, 2 * self.num_points) # [B, NUM(H * W), 2*num_pint]
pos_ind_init = (convex_weights_init > 0).nonzero().reshape(-1)
pts_pred_init_norm = pts_pred_init[pos_ind_init]
rbbox_gt_init_norm = rbbox_gt_init[pos_ind_init]
convex_weights_pos_init = convex_weights_init[pos_ind_init]
loss_pts_init = self.loss_bbox_init(
pts_pred_init_norm / normalize_term,
rbbox_gt_init_norm / normalize_term,
convex_weights_pos_init
)
# refine points loss
rbbox_gt_refine = rbbox_gt_refine.reshape(-1, 8)
pts_pred_refine = pts_pred_refine.reshape(-1, 2 * self.num_points)
convex_weights_refine = convex_weights_refine.reshape(-1)
pos_ind_refine = (convex_weights_refine > 0).nonzero().reshape(-1)
pts_pred_refine_norm = pts_pred_refine[pos_ind_refine]
rbbox_gt_refine_norm = rbbox_gt_refine[pos_ind_refine]
convex_weights_pos_refine = convex_weights_refine[pos_ind_refine]
loss_pts_refine = self.loss_bbox_refine(
pts_pred_refine_norm / normalize_term,
rbbox_gt_refine_norm / normalize_term,
convex_weights_pos_refine
)
# classification loss
labels = labels.reshape(-1)
label_weights = label_weights.reshape(-1)
cls_score = cls_score.permute(0, 2, 3, 1).reshape(-1, self.cls_out_channels)
loss_cls = self.loss_cls(
cls_score,
labels,
label_weights,
avg_factor=num_total_samples_refine)
return loss_cls, loss_pts_init, loss_pts_refine
def loss(self,
cls_scores,
pts_preds_init,
pts_preds_refine,
gt_rbboxes,
gt_labels,
img_metas,
cfg,
gt_rbboxes_ignore=None):
featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
assert len(featmap_sizes) == len(self.point_generators)
label_channels = self.cls_out_channels if self.use_sigmoid_cls else 1
# target for initial stage
center_list, valid_flag_list = self.get_points(featmap_sizes,
img_metas)
pts_coordinate_preds_init = self.offset_to_pts(center_list,
pts_preds_init)
if self.use_cfa: # get num_proposal_each_lvl and lvl_num
num_proposals_each_level = [(featmap.size(-1) * featmap.size(-2))
for featmap in cls_scores]
num_level = len(featmap_sizes)
assert num_level == len(pts_coordinate_preds_init)
if cfg.init.assigner['type'] == 'ConvexAssigner':
candidate_list = center_list
else:
raise NotImplementedError
cls_reg_targets_init = self.point_target(
candidate_list,
valid_flag_list,
gt_rbboxes,
img_metas,
cfg.init,
gt_rbboxes_ignore_list=gt_rbboxes_ignore,
gt_labels_list=gt_labels,
label_channels=label_channels,
sampling=self.sampling)
(*_, rbbox_gt_list_init, candidate_list_init, convex_weights_list_init,
num_total_pos_init, num_total_neg_init, gt_inds_init) = cls_reg_targets_init
num_total_samples_init = (num_total_pos_init +
num_total_neg_init if self.sampling else num_total_pos_init)
# target for refinement stage
center_list, valid_flag_list = self.get_points(featmap_sizes, img_metas)
pts_coordinate_preds_refine = self.offset_to_pts(center_list, pts_preds_refine)
points_list = []
for i_img, center in enumerate(center_list):
points = []
for i_lvl in range(len(pts_preds_refine)):
points_preds_init_ = pts_preds_init[i_lvl].detach()
points_preds_init_ = points_preds_init_.view(points_preds_init_.shape[0], -1,
*points_preds_init_.shape[2:])
points_shift = points_preds_init_.permute(0, 2, 3, 1) * self.point_strides[i_lvl]
points_center = center[i_lvl][:, :2].repeat(1, self.num_points)
points.append(points_center + points_shift[i_img].reshape(-1, 2 * self.num_points))
points_list.append(points)
if self.use_cfa:
cls_reg_targets_refine = self.cfa_point_target(
points_list,
valid_flag_list,
gt_rbboxes,
img_metas,
cfg.refine,
gt_rbboxes_ignore_list=gt_rbboxes_ignore,
gt_labels_list=gt_labels,
label_channels=label_channels,
sampling=self.sampling)
(labels_list, label_weights_list, rbbox_gt_list_refine,
_, convex_weights_list_refine, pos_inds_list_refine,
pos_gt_index_list_refine) = cls_reg_targets_refine
cls_scores = levels_to_images(cls_scores)
cls_scores = [
item.reshape(-1, self.cls_out_channels) for item in cls_scores
]
pts_coordinate_preds_init_cfa = levels_to_images(
pts_coordinate_preds_init, flatten=True)
pts_coordinate_preds_init_cfa = [
item.reshape(-1, 2 * self.num_points) for item in pts_coordinate_preds_init_cfa
]
pts_coordinate_preds_refine = levels_to_images(
pts_coordinate_preds_refine, flatten=True)
pts_coordinate_preds_refine = [
item.reshape(-1, 2 * self.num_points) for item in pts_coordinate_preds_refine
]
with torch.no_grad():
pos_losses_list, = multi_apply(self.get_pos_loss, cls_scores,
pts_coordinate_preds_init_cfa, labels_list,
rbbox_gt_list_refine, label_weights_list,
convex_weights_list_refine, pos_inds_list_refine)
labels_list, label_weights_list, convex_weights_list_refine, num_pos, pos_normalize_term = multi_apply(
self.cfa_reassign,
pos_losses_list,
labels_list,
label_weights_list,
pts_coordinate_preds_init_cfa,
convex_weights_list_refine,
gt_rbboxes,
pos_inds_list_refine,
pos_gt_index_list_refine,
num_proposals_each_level=num_proposals_each_level,
num_level=num_level
)
num_pos = sum(num_pos)
# convert all tensor list to a flatten tensor
cls_scores = torch.cat(cls_scores, 0).view(-1, cls_scores[0].size(-1))
pts_preds_refine = torch.cat(pts_coordinate_preds_refine,
0).view(-1, pts_coordinate_preds_refine[0].size(-1))
labels = torch.cat(labels_list, 0).view(-1)
labels_weight = torch.cat(label_weights_list, 0).view(-1)
rbbox_gt_refine = torch.cat(rbbox_gt_list_refine,
0).view(-1, rbbox_gt_list_refine[0].size(-1))
convex_weights_refine = torch.cat(convex_weights_list_refine, 0).view(-1)
pos_normalize_term = torch.cat(pos_normalize_term, 0).reshape(-1)
pos_inds_flatten = (labels > 0).nonzero().reshape(-1)
assert len(pos_normalize_term) == len(pos_inds_flatten)
if num_pos:
losses_cls = self.loss_cls(
cls_scores, labels, labels_weight, avg_factor=num_pos)
pos_pts_pred_refine = pts_preds_refine[pos_inds_flatten]
pos_rbbox_gt_refine = rbbox_gt_refine[pos_inds_flatten]
pos_convex_weights_refine = convex_weights_refine[pos_inds_flatten]
losses_pts_refine = self.loss_bbox_refine(
pos_pts_pred_refine / pos_normalize_term.reshape(-1, 1),
pos_rbbox_gt_refine / pos_normalize_term.reshape(-1, 1),
pos_convex_weights_refine
)
else:
losses_cls = cls_scores.sum() * 0
losses_pts_refine = pts_preds_refine.sum() * 0
None_list = [None] * num_level
_, losses_pts_init, _ = multi_apply(
self.loss_single,
None_list,
pts_coordinate_preds_init,
None_list,
None_list,
None_list,
rbbox_gt_list_init,
convex_weights_list_init,
None_list,
None_list,
self.point_strides,
num_total_samples_refine=None,
)
loss_dict_all = {
'loss_cls': losses_cls,
'loss_pts_init': losses_pts_init,
'loss_pts_refine': losses_pts_refine
}
return loss_dict_all
## without cfa
else:
cls_reg_targets_refine = self.point_target(
points_list,
valid_flag_list,
gt_rbboxes,
img_metas,
cfg.refine,
gt_rbboxes_ignore_list=gt_rbboxes_ignore,
gt_labels_list=gt_labels,
label_channels=label_channels,
sampling=self.sampling,
featmap_sizes=featmap_sizes)
(labels_list, label_weights_list, rbbox_gt_list_refine,
candidate_list_refine, convex_weights_list_refine, num_total_pos_refine,
num_total_neg_refine, gt_inds_refine) = cls_reg_targets_refine
num_total_samples_refine = (
num_total_pos_refine +
num_total_neg_refine if self.sampling else num_total_pos_refine)
losses_cls, losses_pts_init, losses_pts_refine = multi_apply(
self.loss_single,
cls_scores,
pts_coordinate_preds_init,
pts_coordinate_preds_refine,
labels_list,
label_weights_list,
rbbox_gt_list_init,
convex_weights_list_init,
rbbox_gt_list_refine,
convex_weights_list_refine,
self.point_strides,
num_total_samples_refine=num_total_samples_refine
)
loss_dict_all = {
'loss_cls': losses_cls,
'loss_pts_init': losses_pts_init,
'loss_pts_refine': losses_pts_refine
}
return loss_dict_all
def get_pos_loss(self, cls_score, pts_pred, label, rbbox_gt,
label_weight, convex_weight, pos_inds):
pos_scores = cls_score[pos_inds]
pos_pts_pred = pts_pred[pos_inds]
pos_rbbox_gt = rbbox_gt[pos_inds]
pos_label = label[pos_inds]
pos_label_weight = label_weight[pos_inds]
pos_convex_weight = convex_weight[pos_inds]
loss_cls = self.loss_cls(
pos_scores,
pos_label,
pos_label_weight,
avg_factor=self.loss_cls.loss_weight,
reduction_override='none')
loss_bbox = self.loss_bbox_refine(
pos_pts_pred,
pos_rbbox_gt,
pos_convex_weight,
avg_factor=self.loss_cls.loss_weight,
reduction_override='none')
loss_cls = loss_cls.sum(-1)
pos_loss = loss_bbox + loss_cls
return pos_loss,
def cfa_reassign(self, pos_losses, label, label_weight, pts_pred_init, convex_weight, gt_rbbox,
pos_inds, pos_gt_inds, num_proposals_each_level=None, num_level=None):
if len(pos_inds) == 0:
return label, label_weight, convex_weight, 0, torch.tensor([]).type_as(convex_weight)
num_gt = pos_gt_inds.max()
num_proposals_each_level_ = num_proposals_each_level.copy()
num_proposals_each_level_.insert(0, 0)
inds_level_interval = np.cumsum(num_proposals_each_level_)
pos_level_mask = []
for i in range(num_level):
mask = (pos_inds >= inds_level_interval[i]) & (
pos_inds < inds_level_interval[i + 1])
pos_level_mask.append(mask)
overlaps_matrix = self.convex_overlaps(gt_rbbox, pts_pred_init)
pos_inds_after_cfa = []
ignore_inds_after_cfa = []
re_assign_weights_after_cfa = []
for gt_ind in range(num_gt):
pos_inds_cfa = []
pos_loss_cfa = []
pos_overlaps_init_cfa = []
gt_mask = pos_gt_inds == (gt_ind + 1)
for level in range(num_level):
level_mask = pos_level_mask[level]
level_gt_mask = level_mask & gt_mask
value, topk_inds = pos_losses[level_gt_mask].topk(
min(level_gt_mask.sum(), self.topk), largest=False)
pos_inds_cfa.append(pos_inds[level_gt_mask][topk_inds])
pos_loss_cfa.append(value)
pos_overlaps_init_cfa.append(overlaps_matrix[:, pos_inds[level_gt_mask][topk_inds]])
pos_inds_cfa = torch.cat(pos_inds_cfa)
pos_loss_cfa = torch.cat(pos_loss_cfa)
pos_overlaps_init_cfa = torch.cat(pos_overlaps_init_cfa, 1)
if len(pos_inds_cfa) < 2:
pos_inds_after_cfa.append(pos_inds_cfa)
ignore_inds_after_cfa.append(pos_inds_cfa.new_tensor([]))
re_assign_weights_after_cfa.append(pos_loss_cfa.new_ones([len(pos_inds_cfa)]))
else:
pos_loss_cfa, sort_inds = pos_loss_cfa.sort()
pos_inds_cfa = pos_inds_cfa[sort_inds]
pos_overlaps_init_cfa = pos_overlaps_init_cfa[:, sort_inds].reshape(-1, len(pos_inds_cfa))
pos_loss_cfa = pos_loss_cfa.reshape(-1)
loss_mean = pos_loss_cfa.mean()
loss_var = pos_loss_cfa.var()
gauss_prob_density = (-(pos_loss_cfa - loss_mean) ** 2 / loss_var).exp() / loss_var.sqrt()
index_inverted, _ = torch.arange(len(gauss_prob_density)).sort(descending=True)
gauss_prob_inverted = torch.cumsum(gauss_prob_density[index_inverted], 0)
gauss_prob = gauss_prob_inverted[index_inverted]
gauss_prob_norm = (gauss_prob - gauss_prob.min()) / (gauss_prob.max() - gauss_prob.min())
# splitting by gradient consistency
loss_curve = gauss_prob_norm * pos_loss_cfa
_, max_thr = loss_curve.topk(1)
reweights = gauss_prob_norm[:max_thr + 1]
# feature anti-aliasing coefficient
pos_overlaps_init_cfa = pos_overlaps_init_cfa[:, :max_thr + 1]
overlaps_level = pos_overlaps_init_cfa[gt_ind] / (pos_overlaps_init_cfa.sum(0) + 1e-6)
reweights = self.anti_factor * overlaps_level * reweights + 1e-6
re_assign_weights = reweights.reshape(-1) / reweights.sum() * torch.ones(len(reweights)).type_as(gauss_prob_norm).sum()
pos_inds_temp = pos_inds_cfa[:max_thr + 1]
ignore_inds_temp = pos_inds_cfa.new_tensor([])
pos_inds_after_cfa.append(pos_inds_temp)
ignore_inds_after_cfa.append(ignore_inds_temp)
re_assign_weights_after_cfa.append(re_assign_weights)
pos_inds_after_cfa = torch.cat(pos_inds_after_cfa)
ignore_inds_after_cfa = torch.cat(ignore_inds_after_cfa)
re_assign_weights_after_cfa = torch.cat(re_assign_weights_after_cfa)
reassign_mask = (pos_inds.unsqueeze(1) != pos_inds_after_cfa).all(1)
reassign_ids = pos_inds[reassign_mask]
label[reassign_ids] = 0
label_weight[ignore_inds_after_cfa] = 0
convex_weight[reassign_ids] = 0
num_pos = len(pos_inds_after_cfa)
re_assign_weights_mask = (pos_inds.unsqueeze(1) == pos_inds_after_cfa).any(1)
reweight_ids = pos_inds[re_assign_weights_mask]
label_weight[reweight_ids] = re_assign_weights_after_cfa
convex_weight[reweight_ids] = re_assign_weights_after_cfa
pos_level_mask_after_cfa = []
for i in range(num_level):
mask = (pos_inds_after_cfa >= inds_level_interval[i]) & (
pos_inds_after_cfa < inds_level_interval[i + 1])
pos_level_mask_after_cfa.append(mask)
pos_level_mask_after_cfa = torch.stack(pos_level_mask_after_cfa, 0).type_as(label)
pos_normalize_term = pos_level_mask_after_cfa * (
self.point_base_scale *
torch.as_tensor(self.point_strides).type_as(label)).reshape(-1, 1)
pos_normalize_term = pos_normalize_term[pos_normalize_term > 0].type_as(convex_weight)
assert len(pos_normalize_term) == len(pos_inds_after_cfa)
return label, label_weight, convex_weight, num_pos, pos_normalize_term
def point_target(self,
proposals_list,
valid_flag_list,
gt_rbboxes_list,
img_metas,
cfg,
gt_rbboxes_ignore_list=None,
gt_labels_list=None,
label_channels=1,
sampling=True,
unmap_outputs=True,
featmap_sizes=None):
num_imgs = len(img_metas)
assert len(proposals_list) == len(valid_flag_list) == num_imgs
# points number of multi levels
num_level_proposals = [points.size(0) for points in proposals_list[0]]
# concat all level points and flags to a single tensor
for i in range(num_imgs):
assert len(proposals_list[i]) == len(valid_flag_list[i])
proposals_list[i] = torch.cat(proposals_list[i])
valid_flag_list[i] = torch.cat(valid_flag_list[i])
# compute targets for each image
if gt_rbboxes_ignore_list is None:
gt_rbboxes_ignore_list = [None for _ in range(num_imgs)]
if gt_labels_list is None:
gt_labels_list = [None for _ in range(num_imgs)]
all_overlaps_rotate_list = [None] * 4
(all_labels, all_label_weights, all_rbbox_gt, all_proposals,
all_proposal_weights, pos_inds_list, neg_inds_list, all_gt_inds_list) = multi_apply(
self.point_target_single,
proposals_list,
valid_flag_list,
gt_rbboxes_list,
gt_rbboxes_ignore_list,
gt_labels_list,
all_overlaps_rotate_list,
cfg=cfg,
label_channels=label_channels,
sampling=sampling,
unmap_outputs=unmap_outputs)
# no valid points
if any([labels is None for labels in all_labels]):
return None
# sampled points of all images
num_total_pos = sum([max(inds.numel(), 1) for inds in pos_inds_list])
num_total_neg = sum([max(inds.numel(), 1) for inds in neg_inds_list])
labels_list = images_to_levels(all_labels, num_level_proposals)
label_weights_list = images_to_levels(all_label_weights,
num_level_proposals)
rbbox_gt_list = images_to_levels(all_rbbox_gt, num_level_proposals)
proposals_list = images_to_levels(all_proposals, num_level_proposals)
proposal_weights_list = images_to_levels(all_proposal_weights,
num_level_proposals)
gt_inds_list = images_to_levels(all_gt_inds_list, num_level_proposals)
return (labels_list, label_weights_list, rbbox_gt_list, proposals_list,
proposal_weights_list, num_total_pos, num_total_neg, gt_inds_list)
def point_target_single(self,
flat_proposals,
valid_flags,
gt_rbboxes,
gt_rbboxes_ignore,
gt_labels,
overlaps,
cfg,
label_channels=1,
sampling=True,
unmap_outputs=True):
inside_flags = valid_flags
if not inside_flags.any():
return (None,) * 7
# assign gt and sample proposals
proposals = flat_proposals[inside_flags, :]
if sampling:
assign_result, sampling_result = assign_and_sample(
proposals, gt_rbboxes, gt_rbboxes_ignore, None, cfg)
else:
bbox_assigner = build_assigner(cfg.assigner)
assign_result = bbox_assigner.assign(proposals, gt_rbboxes, overlaps,
gt_rbboxes_ignore, gt_labels)
bbox_sampler = ConvexPseudoSampler()
sampling_result = bbox_sampler.sample(assign_result, proposals,
gt_rbboxes)
gt_inds = assign_result.gt_inds
num_valid_proposals = proposals.shape[0]
rbbox_gt = proposals.new_zeros([num_valid_proposals, 8])
pos_proposals = torch.zeros_like(proposals)
proposals_weights = proposals.new_zeros(num_valid_proposals)
labels = proposals.new_zeros(num_valid_proposals, dtype=torch.long)
label_weights = proposals.new_zeros(num_valid_proposals, dtype=torch.float)
pos_inds = sampling_result.pos_inds
neg_inds = sampling_result.neg_inds
if len(pos_inds) > 0:
pos_gt_rbboxes = sampling_result.pos_gt_rbboxes
rbbox_gt[pos_inds, :] = pos_gt_rbboxes
pos_proposals[pos_inds, :] = proposals[pos_inds, :]
proposals_weights[pos_inds] = 1.0
if gt_labels is None:
labels[pos_inds] = 1
else:
labels[pos_inds] = gt_labels[sampling_result.pos_assigned_gt_inds]
if cfg.pos_weight <= 0:
label_weights[pos_inds] = 1.0
else:
label_weights[pos_inds] = cfg.pos_weight
if len(neg_inds) > 0:
label_weights[neg_inds] = 1.0
# map up to original set of proposals
if unmap_outputs:
num_total_proposals = flat_proposals.size(0)
labels = unmap(labels, num_total_proposals, inside_flags)
label_weights = unmap(label_weights, num_total_proposals, inside_flags)
rbbox_gt = unmap(rbbox_gt, num_total_proposals, inside_flags)
pos_proposals = unmap(pos_proposals, num_total_proposals, inside_flags)
proposals_weights = unmap(proposals_weights, num_total_proposals,
inside_flags)
gt_inds = unmap(gt_inds, num_total_proposals, inside_flags)
return (labels, label_weights, rbbox_gt, pos_proposals, proposals_weights,
pos_inds, neg_inds, gt_inds)
def cfa_point_target(self,
proposals_list,
valid_flag_list,
gt_rbboxes_list,
img_metas,
cfg,
gt_rbboxes_ignore_list=None,
gt_labels_list=None,
label_channels=1,
sampling=True,
unmap_outputs=True):
num_imgs = len(img_metas)
assert len(proposals_list) == len(valid_flag_list) == num_imgs
# concat all level points and flags to a single tensor
for i in range(num_imgs):
assert len(proposals_list[i]) == len(valid_flag_list[i])
proposals_list[i] = torch.cat(proposals_list[i])
valid_flag_list[i] = torch.cat(valid_flag_list[i])
# compute targets for each image
if gt_rbboxes_ignore_list is None:
gt_rbboxes_ignore_list = [None for _ in range(num_imgs)]
if gt_labels_list is None:
gt_labels_list = [None for _ in range(num_imgs)]
all_overlaps_rotate_list = [None] * 4
(all_labels, all_label_weights, all_rbbox_gt, all_proposals,
all_proposal_weights, pos_inds_list, neg_inds_list, all_gt_inds) = multi_apply(
self.cfa_point_target_single,
proposals_list,
valid_flag_list,
gt_rbboxes_list,
gt_rbboxes_ignore_list,
gt_labels_list,
all_overlaps_rotate_list,
cfg=cfg,
label_channels=label_channels,
sampling=sampling,
unmap_outputs=unmap_outputs)
pos_inds = []
pos_gt_index = []
for i, single_labels in enumerate(all_labels):
pos_mask = single_labels > 0
pos_inds.append(pos_mask.nonzero().view(-1))
pos_gt_index.append(all_gt_inds[i][pos_mask.nonzero().view(-1)])
return (all_labels, all_label_weights, all_rbbox_gt, all_proposals,
all_proposal_weights, pos_inds, pos_gt_index)
def cfa_point_target_single(self,
flat_proposals,
valid_flags,
gt_rbboxes,
gt_rbboxes_ignore,
gt_labels,
overlaps,
cfg,
label_channels=1,
sampling=True,
unmap_outputs=True):
inside_flags = valid_flags
if not inside_flags.any():
return (None,) * 7
# assign gt and sample proposals
proposals = flat_proposals[inside_flags, :]
if sampling:
assign_result, sampling_result = assign_and_sample(
proposals, gt_rbboxes, gt_rbboxes_ignore, None, cfg)
else:
bbox_assigner = build_assigner(cfg.assigner)
assign_result = bbox_assigner.assign(proposals, gt_rbboxes, overlaps,
gt_rbboxes_ignore, gt_labels)
bbox_sampler = ConvexPseudoSampler()
sampling_result = bbox_sampler.sample(assign_result, proposals,
gt_rbboxes)
gt_inds = assign_result.gt_inds
num_valid_proposals = proposals.shape[0]
rbbox_gt = proposals.new_zeros([num_valid_proposals, 8])
pos_proposals = torch.zeros_like(proposals)
proposals_weights = proposals.new_zeros(num_valid_proposals)
labels = proposals.new_zeros(num_valid_proposals, dtype=torch.long)
label_weights = proposals.new_zeros(num_valid_proposals, dtype=torch.float)
pos_inds = sampling_result.pos_inds
neg_inds = sampling_result.neg_inds
if len(pos_inds) > 0:
pos_gt_rbboxes = sampling_result.pos_gt_rbboxes
rbbox_gt[pos_inds, :] = pos_gt_rbboxes
pos_proposals[pos_inds, :] = proposals[pos_inds, :]
proposals_weights[pos_inds] = 1.0
if gt_labels is None:
labels[pos_inds] = 1
else:
labels[pos_inds] = gt_labels[sampling_result.pos_assigned_gt_inds]
if cfg.pos_weight <= 0:
label_weights[pos_inds] = 1.0
else:
label_weights[pos_inds] = cfg.pos_weight
if len(neg_inds) > 0:
label_weights[neg_inds] = 1.0
# map up to original set of proposals
if unmap_outputs:
num_total_proposals = flat_proposals.size(0)
labels = unmap(labels, num_total_proposals, inside_flags)
label_weights = unmap(label_weights, num_total_proposals, inside_flags)
rbbox_gt = unmap(rbbox_gt, num_total_proposals, inside_flags)
pos_proposals = unmap(pos_proposals, num_total_proposals, inside_flags)
proposals_weights = unmap(proposals_weights, num_total_proposals,
inside_flags)
gt_inds = unmap(gt_inds, num_total_proposals, inside_flags)
return (labels, label_weights, rbbox_gt, pos_proposals, proposals_weights,
pos_inds, neg_inds, gt_inds)
def get_bboxes(self,
cls_scores,
pts_preds_init,
pts_preds_refine,
img_metas,
cfg,
rescale=False,
nms=True):
assert len(cls_scores) == len(pts_preds_refine)
num_levels = len(cls_scores)
mlvl_points = [
self.point_generators[i].grid_points(cls_scores[i].size()[-2:],
self.point_strides[i])
for i in range(num_levels)
]
result_list = []
for img_id in range(len(img_metas)):
cls_score_list = [
cls_scores[i][img_id].detach() for i in range(num_levels)
]
points_pred_list = [
pts_preds_refine[i][img_id].detach()
for i in range(num_levels)
]
img_shape = img_metas[img_id]['img_shape']
scale_factor = img_metas[img_id]['scale_factor']
proposals = self.get_bboxes_single(cls_score_list, points_pred_list,
mlvl_points, img_shape,
scale_factor, cfg, rescale, nms)
result_list.append(proposals)
return result_list
def get_bboxes_single(self,
cls_scores,
points_preds,
mlvl_points,
img_shape,
scale_factor,
cfg,
rescale=False,
nms=True):
assert len(cls_scores) == len(points_preds) == len(mlvl_points)
mlvl_bboxes = []
mlvl_scores = []
if self.show_points:
mlvl_reppoints = []
for i_lvl, (cls_score, points_pred, points) in enumerate(
zip(cls_scores, points_preds, mlvl_points)):
assert cls_score.size()[-2:] == points_pred.size()[-2:]
cls_score = cls_score.permute(1, 2,
0).reshape(-1, self.cls_out_channels)
if self.use_sigmoid_cls:
scores = cls_score.sigmoid()
else:
scores = cls_score.softmax(-1)
points_pred = points_pred.permute(1, 2, 0).reshape(-1, 2 * self.num_points)
nms_pre = cfg.get('nms_pre', -1)
if nms_pre > 0 and scores.shape[0] > nms_pre:
if self.use_sigmoid_cls:
max_scores, _ = scores.max(dim=1)
else:
max_scores, _ = scores[:, 1:].max(dim=1)
_, topk_inds = max_scores.topk(nms_pre)
points = points[topk_inds, :]
points_pred = points_pred[topk_inds, :]
scores = scores[topk_inds, :]
bbox_pred = self.points2rotrect(points_pred, y_first=True)
bbox_pos_center = points[:, :2].repeat(1, 4)
bboxes = bbox_pred * self.point_strides[i_lvl] + bbox_pos_center
mlvl_bboxes.append(bboxes)
mlvl_scores.append(scores)
if self.show_points:
points_pred = points_pred.reshape(-1, self.num_points, 2)
points_pred_dy = points_pred[:, :, 0::2]
points_pred_dx = points_pred[:, :, 1::2]
pts = torch.cat([points_pred_dx, points_pred_dy], dim=2).reshape(-1, 2 * self.num_points)
pts_pos_center = points[:, :2].repeat(1, self.num_points)
pts = pts * self.point_strides[i_lvl] + pts_pos_center
mlvl_reppoints.append(pts)
mlvl_bboxes = torch.cat(mlvl_bboxes)
if self.show_points:
mlvl_reppoints = torch.cat(mlvl_reppoints)
if rescale:
mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor)
mlvl_reppoints /= mlvl_reppoints.new_tensor(scale_factor)
mlvl_scores = torch.cat(mlvl_scores)
if self.use_sigmoid_cls:
padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1)
mlvl_scores = torch.cat([padding, mlvl_scores], dim=1)
if nms:
det_bboxes, det_labels = multiclass_rnms(mlvl_bboxes, mlvl_scores,
cfg.score_thr, cfg.nms,
cfg.max_per_img, multi_reppoints=mlvl_reppoints if self.show_points else None)
return det_bboxes, det_labels
else:
return mlvl_bboxes, mlvl_scores
| nilq/baby-python | python |
"""
Django settings for sentry_django_example project.
Generated by 'django-admin startproject' using Django 3.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
from uuid import uuid4
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-4kzfiq7vb(t0+jbl#vq)u=%06ouf)n*=l%730c8=tk(wkm9i9o"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# PostHog Setup (can be a separate app)
import posthog
# You can find this key on the /setup page in PostHog
posthog.api_key = "LXP6nQXvo-2TCqGVrWvPah8uJIyVykoMmhnEkEBi5PA" # TODO: replace with your api key
posthog.personal_api_key = ""
# Where you host PostHog, with no trailing /.
# You can remove this line if you're using posthog.com
posthog.host = "http://127.0.0.1:8000"
from posthog.sentry.posthog_integration import PostHogIntegration
PostHogIntegration.organization = "posthog" # TODO: your sentry organization
# PostHogIntegration.prefix = # TODO: your self hosted Sentry url. (default: https://sentry.io/organizations/)
# Since Sentry doesn't allow Integrations configuration (see https://github.com/getsentry/sentry-python/blob/master/sentry_sdk/integrations/__init__.py#L171-L183)
# we work around this by setting static class variables beforehand
# Sentry Setup
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
sentry_sdk.init(
dsn="https://27ac54f7f4cf484abf1335436b0c52e5@o344752.ingest.sentry.io/5624115", # TODO: your Sentry DSN here
integrations=[DjangoIntegration(), PostHogIntegration()],
# Set traces_sample_rate to 1.0 to capture 100%
# of transactions for performance monitoring.
# We recommend adjusting this value in production.
traces_sample_rate=1.0,
# If you wish to associate users to errors (assuming you are using
# django.contrib.auth) you may enable sending PII data.
send_default_pii=True,
)
POSTHOG_DJANGO = {
"distinct_id": lambda request: str(uuid4()) # TODO: your logic for generating unique ID, given the request object
}
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
"posthog.sentry.django.PosthogDistinctIdMiddleware",
]
ROOT_URLCONF = "sentry_django_example.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "sentry_django_example.wsgi.application"
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = "/static/"
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
| nilq/baby-python | python |
""" calc.py - simple code to show how to execute testing
"""
def sum(a: float, b: float) -> float:
"""sum adds two numbers
Args:
a (float): First number
b (float): Second number
Returns:
float: sum of a and b
>>> sum(2,3)
5
"""
return a+b
def mul(a: float, b: float) -> float:
"""mul multiples two numbers
Args:
a (float): First number
b (float): Second number
Returns:
float: mul of a and b
>>> mul(2,3)
6
"""
return a*b
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
| nilq/baby-python | python |
#!/usr/bin/env python
"""
File metadata consistency scanner.
Python requirements: Python 2.7, :mod:`psycopg2`, Enstore modules.
"""
# Python imports
from __future__ import division, print_function, unicode_literals
import atexit
import ConfigParser
import copy
import ctypes
import datetime
import errno
import fcntl
import functools
import grp
import hashlib
import inspect
import locale
import itertools
import json
import math
import multiprocessing
import optparse
import os
import pwd
import Queue
import random
import stat
import sys
import threading
import time
# Chimera and Enstore imports
import chimera
import checksum as enstore_checksum
import configuration_client as enstore_configuration_client
import e_errors as enstore_errors
import enstore_constants
import enstore_functions3
import info_client as enstore_info_client
import namespace as enstore_namespace
import volume_family as enstore_volume_family
# Other imports
import psycopg2.extras # This imports psycopg2 as well. @UnresolvedImport
# Setup global environment
locale.setlocale(locale.LC_ALL, '')
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)
# Specify settings
settings = {
'cache_volume_info': False, # There is no speedup if this is True, and there is
# potentially a gradual slow-down.
# If True, ensure sys.version_info >= (2, 7).
# See MPSubDictCache.__init__
'checkpoint_max_age': 60, # (days)
'checkpoint_write_interval': 5, # (seconds)
'fs_root': '/pnfs/fs/usr',
#'fs_root': '/pnfs/fs/usr/astro/fulla', # for quick test
#'fs_root': '/pnfs/fs/usr/astro/fulla/BACKUP', # for quicker test
'num_scan_processes_per_cpu': 3,
'scriptname_root': os.path.splitext(os.path.basename(__file__))[0],
'sleep_time_at_exit': 0.01, # (seconds)
'status_interval': 600, # (seconds)
}
class Memoize(object):
"""
Cache the return value of a method.
This class is meant to be used as a decorator of methods. The return value
from a given method invocation will be cached on the instance whose method
was invoked. All arguments passed to a method decorated with memoize must
be hashable.
If a memoized method is invoked directly on its class the result will not
be cached. Instead the method will be invoked like a static method::
class Obj(object):
@memoize
def add_to(self, arg):
return self + arg
Obj.add_to(1) # not enough arguments
Obj.add_to(1, 2) # returns 3, result is not cached
.. note :: This class is derived from
http://code.activestate.com/recipes/577452/history/1/.
.. warning :: This class should not be used directly, as doing so can
prevent Sphinx from documenting the decorated method correctly. Use the
:func:`memoize` or :func:`memoize_property` decorator instead.
"""
def __init__(self, func):
self.func = func
#self.__name__ = self.func.__name__ # For Sphinx.
#self.__doc__ = self.func.__doc__ # For Sphinx.
def __get__(self, obj, objtype=None):
if obj is None:
return self.func
return functools.partial(self, obj)
def __call__(self, *args, **kw):
obj = args[0]
try:
cache = obj.__cache
except AttributeError:
cache = obj.__cache = {}
key = (self.func, args[1:], frozenset(kw.items()))
try:
res = cache[key]
except KeyError:
res = cache[key] = self.func(*args, **kw)
return res
def memoize(f):
"""
Return a memoization decorator for methods of classes.
This wraps the :class:`Memoize` class using :py:func:`functools.wraps`.
This allows the decorated method to be documented correctly by Sphinx.
.. note :: This function is derived from
http://stackoverflow.com/a/6394966/832230.
"""
memoized = Memoize(f)
@functools.wraps(f)
def helper(*args, **kws):
return memoized(*args, **kws)
return helper
def memoize_property(f):
"""
Return a memoization decorator for methods of classes, with it being usable
as a :obj:`property`.
This uses the :func:`memoize` function.
"""
return property(memoize(f))
def do_random_test(negexp=3):
"""
Return :obj:`True` if a random probability is not greater than a threshold,
otherwise return :obj:`False`.
:type negexp: :obj:`int` (non-negative)
:arg negexp: This is the negative exponent that is used to compute a
probability threshold. Higher values of ``negexp`` make the threshold
exponentially smaller. A value of 0 naturally makes the threshold equal
1, in which case the returned value will be :obj:`True`.
:rtype: :obj:`bool`
"""
# Compare random probability with threshold 1e-negexp
return random.random() <= 10**(-1*negexp)
class PeriodicRunner:
"Run a callable periodically."
_concurrency_classes = {'thread': threading.Thread,
'process': multiprocessing.Process,}
def __init__(self, is_active_indicator, target, interval, concurrency,
name=None):
"""
Run the ``target`` callable periodically with the specified idle
``interval`` in seconds between each run.
:type target: :obj:`callable`
:arg target: This is a callable which is to be run periodically. Only
one instance of the target is called and run at a time. Even so,
the target should be thread or process safe, depending upon the
indicated ``concurrency`` type. The target is also run once upon
program or thread termination.
:type is_active_indicator: :obj:`multiprocessing.Value` or
:obj:`multiprocessing.RawValue`
:arg is_active_indicator: This must have an attribute ``value`` which
is evaluated as a :obj:`bool`. The target is called only so long as
``is_active_indicator.value`` evaluates to :obj:`True`. If and when
this indicator evaluates to :obj:`False`, the loop is terminated,
although the target is then still run one final time.
:type interval: :obj:`int` or :obj:`float` (positive)
:arg interval: number of seconds to sleep between each run of the
target.
:type concurrency: :obj:`str`
:arg concurrency: This can be ``thread`` or ``process``, indicating
whether the target should run in a new thread or a new process.
:type name: :obj:`str` or :obj:`None`
:arg name: This is the name assigned to the target thread or process.
If :obj:`None`, it is determined automatically.
"""
# Setup variables
self._is_active = is_active_indicator
self._target = target
self._interval = interval
self._concurrency_type = concurrency
self._target_name = name
# Setup and start runner
self._setup_runner()
self._runner_instance.start()
def _setup_runner(self):
"""Setup the target runner."""
# Setup variables
self._runner_class = self._concurrency_classes[self._concurrency_type]
if self._target_name is None:
self._target_name = '{0}{1}'.format(self._target.__name__.title(),
self._concurrency_type.title())
# Setup runner
self._runner_instance = self._runner_class(target=self._target_runner,
name=self._target_name)
self._runner_instance.daemon = True
atexit.register(self._target)
def _target_runner(self):
"""Run the target periodically."""
target = self._target
interval = self._interval
try:
while self._is_active.value:
target()
time.sleep(interval)
except (KeyboardInterrupt, SystemExit):
pass
finally:
target()
class FileParser(ConfigParser.SafeConfigParser):
"""
Provide a file parser based on :class:`ConfigParser.SafeConfigParser`.
Stored options are case-sensitive.
"""
#_filepath_suffixes_lock = multiprocessing.Lock() # Must be a class attr.
#_filepath_suffixes_in_use = multiprocessing.Manager().list() # For Py2.7+
# Note: multiprocessing.Manager().list() hangs on import in Python 2.6.3.
# This Python bug is not expected to be present in Python 2.7+.
def __init__(self, is_active_indicator, filepath_suffix=None):
"""
Initialize the parser.
:type is_active_indicator: :obj:`multiprocessing.Value` or
:obj:`multiprocessing.RawValue`
:arg is_active_indicator: This must have an attribute ``value`` which
is evaluated as a :obj:`bool`.
:type filepath_suffix: :obj:`str` or :obj:`None`
:arg filepath_suffix: If :obj:`None`, no suffix is used, otherwise the
provided suffix string is joined to the default file path with an
underscore.
Only one instance of this class may be initialized for each unique
file path suffix.
"""
ConfigParser.SafeConfigParser.__init__(self)
# Setup variables
self._is_active = is_active_indicator
self._filepath_suffix = filepath_suffix
self._setup_vars()
#self._add_filepath_suffix() #For Py2.7+. See _filepath_suffixes_in_use.
self._makedirs()
self.read()
def _setup_vars(self):
"""Setup miscellaneous variables."""
home_dir = os.getenv('HOME')
# Note: The environment variable HOME is not available with httpd cgi.
# Given that the scan is run by the root user, the value of HOME is
# expected to be "\root".
filepath_base = os.path.join(home_dir, '.enstore',
settings['scriptname_root'])
# Note: The value of `filepath_base` is intended to be unique for each
# module.
self._filepath = filepath_base
if self._filepath_suffix:
self._filepath += '_{0}'.format(self._filepath_suffix)
self._parser_lock = multiprocessing.Lock()
def _add_filepath_suffix(self):
"""
Add the provided filepath suffix to the list of suffixes in use.
:exc:`ValueError` is raised if the suffix is already in use.
"""
with self._filepath_suffixes_lock:
if self._filepath_suffix in self._filepath_suffixes_in_use:
msg = ('File path suffix "{}" was previously initialized. A '
'suffix can be initialized only once.'
).format(self._filepath_suffix)
raise ValueError(msg)
else:
self._filepath_suffixes_in_use.append(self._filepath_suffix)
def read(self):
"""
Read the saved values from file if the file exists.
Note that the retrieved values will be read only into the process from
which this method is called.
"""
filepath = self._filepath
with self._parser_lock:
if os.path.isfile(filepath):
ConfigParser.SafeConfigParser.read(self, filepath)
def _makedirs(self):
"""As necessary, make the directories into which the file will be
written."""
path = os.path.dirname(self._filepath)
try:
os.makedirs(path)
except OSError:
# Note: "OSError: [Errno 17] File exists" exception is raised if
# the path previously exists, irrespective of the path being a file
# or a directory, etc.
if not os.path.isdir(path):
raise
def write(self):
"""
Write the set values to file.
While this method itself is process safe, the underlying set values are
not process safe - they are unique to each process.
"""
try:
with self._parser_lock:
with open(self._filepath, 'wb') as file_:
ConfigParser.SafeConfigParser.write(self, file_)
file_.flush()
file_.close()
except:
if self._is_active.value: raise
def optionxform(self, option):
return option # prevents conversion to lower case
class Checkpoint(object):
"""
Provide a checkpoint manager to get and set a checkpoint.
The :class:`FileParser` class is used internally to read and write the
checkpoint.
"""
version = 1 # Version number of checkpointing implementation.
"""Version number of checkpointing implementation."""
def __init__(self, is_active_indicator, scanner_name):
"""
Initialize the checkpoint manager with the provided scanner name.
Each unique notices output file has its own unique checkpoint.
This class must be initialized only once for a scanner.
All old or invalid checkpoints are initially deleted.
:type is_active_indicator: :obj:`multiprocessing.Value` or
:obj:`multiprocessing.RawValue`
:arg is_active_indicator: This must have an attribute ``value`` which
is evaluated as a :obj:`bool`. So long as
``is_active_indicator.value`` evaluates to :obj:`True`, the current
checkpoint is periodically written to file. If and when this
indicator evaluates to :obj:`False`, the write loop is terminated.
The checkpoint is then still written one final time.
:type scanner_name: :obj:`str`
:arg scanner_name: This represents the name of the current scanner,
e.g. ``ScannerForward``. It is expected to be the name of the class
of the current scanner.
"""
# Setup variables
self._is_active = is_active_indicator
self._file_basename = '{0}_checkpoints'.format(scanner_name)
self._setup_vars()
self._setup_writer()
def _setup_vars(self):
"""Setup miscellaneous variables."""
self._parser = FileParser(self._is_active, self._file_basename)
self._parser_lock = multiprocessing.Lock()
self._is_parser_set_enabled = multiprocessing.RawValue(ctypes.c_bool,
True)
self._section = 'Version {0}'.format(self.version)
self._option = settings['output_file']
self._value = multiprocessing.Manager().Value(unicode, u'')
def _setup_writer(self):
"""Setup and start the writer thread."""
self._add_section()
self._cleanup()
self.read()
PeriodicRunner(self._is_active, self.write,
settings['checkpoint_write_interval'], 'process',
'CheckpointLogger')
def _is_reliably_active(self):
"""
Return whether the ``self._is_active`` indicator reliably returns
:obj:`True`.
The indicator is checked twice with a time delay between the checks.
The time delay provides time for the indicator to possibly be set to
:obj:`False`, such as during an abort.
This method may be used from any thread or process. It is thread and
process safe.
:rtype: :obj:`bool`
"""
return (self._is_active.value and
(time.sleep(0.1) or self._is_active.value))
# Note: "bool(time.sleep(0.1))" is False. Because it is
# succeeded by "or", it is essentially ignored for boolean
# considerations. Its only purpose is to introduce a time
# delay.
@property
def value(self):
"""
For use as a getter, return the locally stored checkpoint.
:rtype: :obj:`str` (when *getting*)
For use as a setter, update the locally stored checkpoint with the
provided value. The checkpoint is updated into the parser
asynchronously.
:type value: :obj:`str` (when *setting*)
:arg value: the current checkpoint.
The getter or setter may be used from any thread or process. They are
thread and process safe.
"""
try: return self._value.value
except:
if self._is_reliably_active(): raise
else: return ''
@value.setter
def value(self, value):
"""
See the documentation for the getter method.
This method is not documented here because this docstring is ignored by
Sphinx.
"""
value = unicode(value)
try: self._value.value = value
except:
if self._is_reliably_active(): raise
def _add_section(self):
"""Add the pertinent checkpoint section to the parser."""
with self._parser_lock:
if not self._parser.has_section(self._section):
self._parser.add_section(self._section)
def _cleanup(self):
"""Delete old or invalid checkpoints."""
max_age = time.time() - 86400 * settings['checkpoint_max_age']
with self._parser_lock:
for filepath in self._parser.options(self._section):
if (((not os.path.isfile(filepath))
or (os.stat(filepath).st_mtime < max_age))
and (filepath != self._option)):
self._parser.remove_option(self._section, filepath)
def read(self):
"""
Read and return the checkpoint from the parser.
The checkpoint defaults to an empty string if it is unavailable in the
parser.
"""
try:
checkpoint = self._parser.get(self._section, self._option)
# Note: A parser lock is not required or useful for a get
# operation.
except ConfigParser.NoOptionError:
checkpoint = ''
self.value = checkpoint
return checkpoint
def write(self):
"""
Set and write the locally stored checkpoint, if valid, into the parser.
The action will happen only if setting it is enabled, otherwise the
command will be ignored.
This method is process safe. It is practical to generally call it in
only one process, however.
"""
with self._parser_lock:
if self._is_parser_set_enabled.value:
checkpoint = self.value
if checkpoint: # Note: checkpoint is initially an empty string.
self._parser.set(self._section, self._option, checkpoint)
self._parser.write()
def remove_permanently(self):
"""
Remove and also disable the checkpoint altogether from the parser,
effectively preventing it from being set into the parser again.
This method is process safe, but it is expected to be called only once.
"""
self._is_parser_set_enabled.value = False
with self._parser_lock:
self._parser.remove_option(self._section, self._option)
self._parser.write()
class PrintableList(list):
"""Provide a list object which has a valid English string
representation."""
def __init__(self, plist=None, separator=', ', separate_last=False):
"""
Initialize the object.
:type plist: :obj:`list` or :obj:`None`
:arg plist: This is the initial :obj:`list` with which to initialize
the object. It is optional, with a default value of :obj:`None`, in
which case an empty :obj:`list` is initialized.
:type separator: :obj:`str`
:arg separator: the string which is used to delimit consecutive items
in the list.
:type separate_last: :obj:`bool`
:arg separate_last: indicates whether to separate the last two items in
the list with the specified ``separator``.
"""
self.separator = separator
self.separate_last = separate_last
if plist is None: plist = []
list.__init__(self, plist)
def __str__(self):
"""
Return a valid English string representation.
:rtype: :obj:`str`
Example::
>>> for i in range(5):
... str(PrintableList(range(i)))
...
''
'0'
'0 and 1'
'0, 1 and 2'
'0, 1, 2 and 3'
"""
separator = self.separator
separator_last = separator if self.separate_last else ' '
separator_last = '{0}and '.format(separator_last)
s = (str(i) for i in self)
s = separator.join(s)
s = separator_last.join(s.rsplit(separator, 1))
return s
class ReversibleDict(dict):
"""
Provide a reversible :obj:`dict`.
Initialize the object with a :obj:`dict`.
"""
def reversed(self, sort_values=True):
"""
Return a reversed :obj:`dict`, with keys corresponding to non-unique
values in the original :obj:`dict` grouped into a :obj:`list` in the
returned :obj:`dict`.
:type sort_values: :obj:`bool`
:arg sort_values: sort the items in each :obj:`list` in each value of
the returned :obj:`dict`.
:rtype: :obj:`dict`
Example::
>>> d = ReversibleDict({'a':3, 'c':2, 'b':2, 'e':3, 'd':1, 'f':2})
>>> d.reversed()
{1: ['d'], 2: ['b', 'c', 'f'], 3: ['a', 'e']}
"""
revdict = {}
for k, v in self.iteritems():
revdict.setdefault(v, []).append(k)
if sort_values:
revdict = dict((k, sorted(v)) for k, v in revdict.items())
return revdict
def _reversed_tuple_revlensorted(self):
"""
Return a :obj:`tuple` created from the reversed dict's items.
The items in the :obj:`tuple` are reverse-sorted by the length of the
reversed dict's values.
:rtype: :obj:`tuple`
Example::
>>> d = ReversibleDict({'a':3, 'c':2, 'b':2, 'e':3, 'd':1, 'f':2})
>>> d._reversed_tuple_revlensorted()
((2, ['b', 'c', 'f']), (3, ['a', 'e']), (1, ['d']))
"""
revitems = self.reversed().items()
sortkey = lambda i: (len(i[1]), i[0])
revtuple = tuple(sorted(revitems, key=sortkey, reverse=True))
return revtuple
def __str__(self):
"""
Return a string representation of the reversed dict's items using the
:class:`PrintableList` class.
The items in the returned string are reverse-sorted by the length of
the reversed dict's values.
:rtype: :obj:`str`
Example::
>>> print(ReversibleDict({'a':3, 'c':2, 'b':2, 'e':3, 'd':1, 'f':2}))
b, c and f (2); a and e (3); and d (1)
>>> print(ReversibleDict({'a': 3, 'c': 2}))
a (3) and c (2)
"""
revtuple = self._reversed_tuple_revlensorted()
revstrs = ('{0} ({1})'.format(PrintableList(values), key)
for key, values in revtuple)
pl_args = ('; ', True) if (max(len(i[1]) for i in revtuple) > 1) else ()
revstrs = PrintableList(revstrs, *pl_args)
revstr = str(revstrs)
return revstr
class MPSubDictCache:
"""
Provide a memory-efficient and :mod:`multiprocessing`-safe subset of a
:obj:`dict` for use when the values in the :obj:`dict` are themselves
dicts.
Memory efficiency is derived from sharing the keys used in the level 2
dicts.
"""
def __init__(self):
"""Initialize the object."""
self._manager = multiprocessing.Manager()
# Note: If the above line is executed at import-time, it makes the
# program hang on exit in Python 2.6.3. In addition, the dict creation
# lines below, if executed at import-time, make the program hang at
# import-time in Python 2.6.3. With Python 2.7+, it may better to
# declare `_manager` as a class variable instead of an instance
# variable.
self._cache = self._manager.dict()
self._subkeys = self._manager.dict() # e.g. {'kA': 1, 'kB': 2}
self._subkeys_reverse = self._manager.dict() # e.g. {1: 'kA', 2: 'kB'}
self._index = multiprocessing.Value(ctypes.c_ushort)
self._setitem_lock = multiprocessing.Lock()
def __contains__(self, k):
"""``D.__contains__(k)`` returns :obj:`True` if ``D`` has a key ``k``,
else returns :obj:`False`."""
return (k in self._cache)
def __getitem__(self, k):
"""``x.__getitem__(y) <==> x[y]``"""
subdict = self._cache[k] # can raise KeyError
subdict = self._decompress_subkeys(subdict) # should not raise KeyError
return subdict
def __setitem__(self, k, subdict):
"""``x.__setitem__(i, y) <==> x[i]=y``"""
with self._setitem_lock:
subdict = self._compress_subkeys(subdict)
self._cache[k] = subdict
@property
def _next_index(self):
index = self._index.value
self._index.value += 1
return index
def _compress_subkeys(self, subdict):
"""
Compress the keys in the ``subdict`` using an internal index.
:type subdict: :obj:`dict`
:arg subdict:
:rtype: :obj:`dict`
"""
subdict_compressed = {}
for k,v in subdict.items():
try: k_compressed = self._subkeys[k]
except KeyError:
k_compressed = self._next_index
self._subkeys[k] = k_compressed
self._subkeys_reverse[k_compressed] = k
subdict_compressed[k_compressed] = v
return subdict_compressed
def _decompress_subkeys(self, subdict):
"""
Decompress the keys in the ``subdict`` using the internal index.
:type subdict: :obj:`dict`
:arg subdict:
:rtype: :obj:`dict`
"""
return dict((self._subkeys_reverse[k],v) for k,v in subdict.items())
class CommandLineOptionsParser(optparse.OptionParser):
"""
Parse program options specified on the command line.
These are made available using instance attributes ``options`` and
``args``, as described below.
``options`` is an attribute providing values for all options. For example,
if ``--file`` takes a single string argument, then ``options.file`` will be
the filename supplied by the user. Alternatively, its value will be
:obj:`None` if the user did not supply this option.
``args`` is the list of positional arguments leftover after parsing
``options``.
The :meth:`add_option` method can be used to add an option.
"""
# In newer versions of Python, i.e. 2.7 or higher, the usage of the
# optparse module should be replaced by the newer argparse module.
_options_seq = []
def __init__(self):
"""Parse options."""
usage = '%prog -t SCAN_TYPE [OPTIONS]'
optparse.OptionParser.__init__(self, usage=usage)
self._add_options()
(self.options, self.args) = self.parse_args()
self._check_option_values()
self._process_options()
def add_option(self, *args, **kwargs):
# Refer to the docstring of the overridden method.
optparse.OptionParser.add_option(self, *args, **kwargs)
if kwargs.get('dest'): self._options_seq.append(kwargs['dest'])
@staticmethod
def output_filename():
"""Return the name of the output file for notices."""
datetime_str = datetime.datetime.now().strftime('%Y%m%dT%H%M%S')
filen = '{0}_{1}.log'.format(settings['scriptname_root'], datetime_str)
pathn = os.path.abspath(filen)
return pathn
def _add_options(self):
"""Add various options."""
# Add scan type option
self.add_option('-t', '--type', dest='scan_type',
choices=('forward', 'reverse'),
help='(forward, reverse) scan type',
)
# Add scan directory option
directory = settings['fs_root']
self.add_option('-d', '--directory', dest='fs_root',
default=directory,
help=('(for forward scan only) absolute path of '
'directory to scan recursively '
'(recommended default is {0}) (not recommended '
'to be specified for large nested directories)'
).format(directory))
# Add notices output file option
filename = self.output_filename()
self.add_option('-o', '--output_file', dest='output_file',
default=filename,
help=('absolute path to output file for notices '
'(default is dynamic, e.g. {0}) (appended if '
'exists)'
).format(filename))
# Add printing option
self.add_option('-p', '--print', dest='print',
choices=('checks', 'notices'),
help=('(checks, notices) for the specified scan type, '
'print all runnable checks and their overviews, '
'or all notice templates, and exit'),
)
# Add resume option
self.add_option('-r', '--resume', dest='resume_scan', default=False,
action='store_true',
help=('for specified output file (per -o), resume scan '
'where aborted (default is to restart scan) (use '
'with same database only)'))
# Add status interval option
status_interval = settings['status_interval']
self.add_option('-s', '--status_interval', dest='status_interval',
type=float,
default=status_interval,
help=('max status output interval in seconds (default '
'approaches {0})').format(status_interval),
)
def _check_option_values(self):
"""Check whether options have been specified correctly, and exit
otherwise."""
# Check required options
if not all((self.options.scan_type, self.options.output_file)):
self.print_help()
self.exit(2)
def _process_options(self):
"""Process and convert options as relevant."""
# Process options as relevant
self.options.fs_root = os.path.abspath(self.options.fs_root)
self.options.output_file = os.path.abspath(self.options.output_file)
# Convert options from attributes to keys
self.options = dict((k, getattr(self.options, k)) for k in
self._options_seq)
class Enstore:
"""
Provide an interface to various Enstore modules.
A unique instance of this class must be created in each process in which
the interface is used.
"""
def __init__(self):
"""Initialize the interface."""
self.config_client = \
enstore_configuration_client.ConfigurationClient()
self.config_dict = self.config_client.dump_and_save()
self.library_managers = [k[:-16] for k in self.config_dict
if k.endswith('.library_manager')]
info_client_flags = (enstore_constants.NO_LOG |
enstore_constants.NO_ALARM)
self.info_client = \
enstore_info_client.infoClient(self.config_client,
flags=info_client_flags)
#self.storagefs = enstore_namespace.StorageFS()
class Chimera:
"""
Provide an interface to the Chimera database.
A unique database connection is internally used for each process and thread
combination from which the class instance is used.
"""
_connections = {}
_cursors = {}
@staticmethod
def confirm_psycopg2_version():
"""Exit the calling process with an error if the available
:mod:`psycopg2` version is less than the minimally required version."""
ver_str = psycopg2.__version__
ver = [int(i) for i in ver_str.partition(' ')[0].split('.')]
min_ver = [2, 4, 5]
min_ver_str = '.'.join(str(v) for v in min_ver)
if ver < min_ver:
msg = ('The installed psycopg2 version ({0}) is older than the'
' minimally required version ({1}). Its path is {2}.'
).format(ver_str, min_ver_str, psycopg2.__path__)
exit(msg) # Return code is 1.
@staticmethod
def confirm_fs():
"""Exit the calling process with an error if the filesystem root is not
a Chimera filesystem."""
# Note: This method helps confirm that PNFS is not being used.
fs_root = str(settings['fs_root']) # StorageFS requires str, not unicode
fs_type_reqd = chimera.ChimeraFS
#import pnfs; fs_type_reqd = pnfs.Pnfs
fs_type_seen = enstore_namespace.StorageFS(fs_root).__class__
if fs_type_reqd != fs_type_seen:
msg = ('The filesystem root ({0}) is required to be of type {1} '
'but is of type {2}.'
).format(fs_root,
fs_type_reqd.__name__, fs_type_seen.__name__)
exit(msg) # Return code is 1.
@property
def _cursor(self):
"""Return the cursor for the current process and thread combination."""
key = (multiprocessing.current_process().ident,
threading.current_thread().ident)
if key in self._cursors:
return self._cursors[key]
else:
# Create connection
conn = psycopg2.connect(database='chimera', user='enstore')
#conn.set_session(readonly=True, autocommit=True)
self._connections[key] = conn
# Create cursor
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
self._cursors[key] = cursor
return cursor
def fetchone(self, *args):
"""Fetch and return a row for the provided query arguments."""
self._cursor.execute(*args)
return self._cursor.fetchone()
class Scanner:
"""
This is the base class for derived scanner classes.
A derived class must:
- Define the :meth:`validate_scan_location` method to validate the scan
location root.
- Define the :meth:`queue_items` method which puts items into the
:attr:`items_q` queue.
- Define *check methods* as relevant, which raise the appropriate
:class:`Notice` exception.
- Define the :attr:`checks` variable which is a
:obj:`~collections.Sequence` of *check method* names, indicating the
order in which to execute the methods.
- Define the :attr:`notices` variable, the requirements for which are
specified by the :meth:`Notice.update_notices` method.
- Define the :meth:`get_num_items` method returning a non-negative integer
which is the total number of items to be processed.
To run the scan, initialize the derived class, and call the :meth:`run`
method.
"""
num_scan_processes = (multiprocessing.cpu_count() *
settings['num_scan_processes_per_cpu'])
# Estimate the max number of pending items that may remain queued
est_max_scan_speed = 120 * 5 # (per second) (Guesstimate with SSD.)
est_max_dir_list_time = 15 # Est. max seconds to walk a single large dir.
queue_max_len = est_max_scan_speed * est_max_dir_list_time
# Note: The goals here are twofold:
# - limiting memory usage
# - ensuring a process does not run out of pending items to scan
# This will need to be moved to the derived class if different scanners have
# very different scan speeds.
def __init__(self):
"""Set up the scanner."""
self._check_prereqs_prevars()
self._setup_vars()
self._check_prereqs_postvars()
self._setup_workers()
def _check_prereqs_prevars(self):
"""Check various prerequisites before setting up instance variables."""
self._check_ugid()
self._check_exclusive()
#Chimera.confirm_psycopg2_version()
Chimera.confirm_fs()
def _setup_vars(self):
"""Setup miscellaneous variables."""
settings['output_file_dict'] = '{0}.dict'.format(
settings['output_file'])
Notice.update_notices(self.notices)
self.is_active = multiprocessing.RawValue(ctypes.c_bool, True)
self.checkpoint = Checkpoint(self.is_active, self.__class__.__name__)
self.num_items_total = multiprocessing.RawValue(ctypes.c_ulonglong,
self.get_num_items())
self._start_time = time.time() # Intentionally defined now.
def _check_prereqs_postvars(self):
"""Check various prerequisites after setting up instance variables."""
self.validate_scan_location() # Implemented in derived class.
self._validate_output_files_paths()
self._validate_checkpoint()
def _setup_workers(self):
"""Setup and start worker processes and threads."""
self._setup_mp()
self._start_workers()
self._start_ScannerWorker_monitor()
def run(self):
"""
Perform scan.
This method blocks for the duration of the scan.
"""
try:
self.queue_items() # Defined by derived class # is blocking
except (KeyboardInterrupt, SystemExit) as e:
self.is_active.value = False
if isinstance(e, KeyboardInterrupt):
print() # Prints a line break after "^C"
if str(e):
print(e, file=sys.stderr)
except:
self.is_active.value = False
raise
finally:
# Note: self.is_active.value must *not* be set to False here,
# independent of whether it was previously set to False. It should
# essentially remain True if the work ends normally.
self._stop_workers()
self._do_postreqs()
if not self.is_active.value:
# Note: This condition will here be True if an abort was
# instructed, such as using KeyboardInterrupt or SystemExit.
# This can cause an unknown non-daemonic process to hang on
# exit. To get past the hang, the exit is forced. The hang is
# not observed to occur during a normal scan completion.
os._exit(1)
def _do_postreqs(self):
"""Perform post-requisites after completion of the scan."""
# Finalize checkpoint
if self.is_active.value:
self.checkpoint.remove_permanently()
else:
self.checkpoint.write()
# Log status
try: self._log_status() # Warning: Not executed if using `tee`.
except IOError: pass
def _check_ugid(self):
"""Check whether process UID and GID are 0, exiting the process with an
error otherwise."""
id_reqd = 0
if (os.getuid() != id_reqd) or (os.getgid() != id_reqd):
msg = ('Error: UID and GID must be {0}, but are {1} and {2} '
'instead.').format(id_reqd, os.getuid(), os.getgid())
exit(msg)
else:
# Set "effective" IDs in case they are not equal to "real" IDs
os.setegid(id_reqd)
os.seteuid(id_reqd)
# Note: EGID is intentionally set before EUID. This is because
# setting EUID first (to a non-root value) can result in a loss of
# power, causing the EGID to then become unchangeable.
def _check_exclusive(self):
"""
Check if the scanner is running exclusively.
Requirements:
- Root permissions.
- The ``enstore`` user and group must exist.
This check is required to be performed only once. For safety, this must
be done before the initialization of file-writing objects such as
:attr:`self.checkpoint`, etc.
This check is performed to prevent accidentally overwriting any of the
following:
- Notices output files if they have the same name.
- The common checkpoint file.
"""
# Establish lock dir settings
ld_name = '/var/run/enstore' # Parent dir is later assumed to exist.
# Note: Writing in "/var/run" requires root permissions.
ld_mode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP
# = 0o660 = 432
try:
ld_uid = pwd.getpwnam('enstore').pw_uid
except KeyError: # User 'enstore' does not exist.
ld_uid = -1 # -1 keeps the value unchanged.
try:
ld_gid = grp.getgrnam('enstore').gr_gid
except KeyError: # Group 'enstore' does not exist.
ld_gid = -1 # -1 keeps the value unchanged.
# Create lock directory
umask_original = os.umask(0)
try:
os.mkdir(ld_name, ld_mode) # This assumes parent dir exists.
except OSError:
if not os.path.isdir(ld_name): raise
else:
os.chown(ld_name, ld_uid, ld_gid)
finally:
os.umask(umask_original)
# Establish lock file settings
lf_name = '{0}.lock'.format(settings['scriptname_root'])
lf_path = os.path.join(ld_name, lf_name)
lf_flags = os.O_WRONLY | os.O_CREAT
lf_mode = stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH # = 0o222 = 146
# Create lock file
umask_original = os.umask(0)
try:
lf_fd = os.open(lf_path, lf_flags, lf_mode)
finally:
os.umask(umask_original)
# Note: It is not necessary to use "os.fdopen(lf_fd, 'w')" to open a
# file handle, or to keep it open for the duration of the process.
# Try locking the file
try:
fcntl.lockf(lf_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
msg = ('Error: {0} may already be running. Only one instance of it '
'can run at a time.'
).format(settings['scriptname_root'].title())
exit(msg)
# Note: Because fcntl is used, it is not necessary for the locked file
# to be deleted at the end of the scan.
def _validate_output_files_paths(self):
"""Validate the paths of the scan notices output files."""
# Determine file properties
of_map = {'main': 'output_file', 'dict': 'output_file_dict'}
of_all = {}
for of_name, of_key in of_map.items():
of = {}
of['path'] = settings[of_key]
of['path_basename'] = os.path.basename(of['path'])
of['path_exists'] = os.path.isfile(of['path'])
of_all[of_name] = of
# Add file paths to message
ofall_paths = ['"{0}"'.format(of['path']) for of in of_all.values()]
ofall_paths = sorted(ofall_paths)
ofall_paths_str = str(PrintableList(ofall_paths))
msg = 'The scan notices output files are {0}.'.format(ofall_paths_str)
# Add an "appended" or "created" status to message
if of_all['main']['path_exists'] == of_all['dict']['path_exists']:
if of_all['main']['path_exists']:
msg += ' These files exist and will be appended.\n'
elif not settings['resume_scan']:
msg += ' These files do not exist and will be created.\n'
else:
msg += '\n'
print(msg)
else:
msg = ('Error: {0} These must be in a consistent state. Both must '
'either exist (so they can be appended), or both must not '
'exist (so they can be created). If one of these files is '
'missing, it is recommended the other be deleted.'
).format(msg)
exit(msg)
def _validate_checkpoint(self):
"""
Validate usability of checkpoint.
This is performed only when a scan resumption is requested.
"""
# Note: It is possible that this method belongs in the derived class
# instead.
if not settings['resume_scan']: return
output_file = settings['output_file']
output_file_dict = settings['output_file_dict']
checkpoint = self.checkpoint.value
# Caution: Checks specific to the current scanner musn't be done here.
if ((not os.path.isfile(output_file)) or
(not os.path.isfile(output_file_dict))):
msg = ('Error: A request to resume the scan for the current set of '
'output files ("{0}" and "{1}") was received, but one or '
'more of these output files do not already exist. A scan '
'can be resumed only for an existing set of incomplete '
'output files.'
).format(output_file, output_file_dict)
exit(msg)
elif not checkpoint:
msg = ('Error: A request to resume the scan was received, but a '
'checkpoint is unavailable for the current primary output '
'file ({0}). If an output file was previously specified, '
'the currently specified path must match the previous path '
'exactly.'
).format(output_file)
exit(msg)
else:
msg = ('Scan will be resumed at the approximate checkpoint "{0}". '
'Items preceding this checkpoint will still be traversed by '
'the scanner but will not be rescanned. Because the '
'checkpoint is an approximate one, a few duplicate entries '
'may exist in the notices output file near the checkpoint.\n'
).format(checkpoint)
# Note: For more info on setting a checkpoint, see
# self._item_handler.
print(msg)
def _setup_mp(self):
"""Setup :mod:`multiprocessing` environment."""
# Setup queues
self.items_q = multiprocessing.Queue(self.queue_max_len)
self.noticegrps_q = multiprocessing.Queue(self.queue_max_len)
# Setup counter
self.num_ScannerWorker_alive = multiprocessing.Value(ctypes.c_ubyte)
self.num_items_processed = multiprocessing.Value(ctypes.c_ulonglong,
lock=True)
self._num_items_processed_lock = multiprocessing.Lock()
# Define processes
# Note defaults: {'num': 1, 'join': True, 'queue': None}
self._processes = ({'name': 'ScannerWorker',
'num': self.num_scan_processes,
'target': self._item_handler,
'queue': self.items_q,},
{'name': 'NotificationLogger',
'target': self._noticegrp_handler,
'queue': self.noticegrps_q,},
{'name': 'StatusLogger',
'target': self._status_logger, 'join': False,},
)
# Note that processes will be started in the order specified in the
# above sequence. They will also later be terminated in the same order.
# It is important to terminate them in the same order.
def _increment_num_items_processed(self, amount=1):
"""
Increment the number of items processed by the specified amount.
This method is process safe.
:type amount: :obj:`int` (positive)
:arg amount: number by which to increment
"""
with self._num_items_processed_lock: # required
self.num_items_processed.value += amount
def _start_workers(self):
"""Start workers."""
# Start processes in order
for pgrp in self._processes:
pgrp['processes'] = []
num_processes = pgrp.get('num', 1)
for i in range(num_processes):
name = pgrp['name']
if num_processes > 1: name += str(i)
process = multiprocessing.Process(target=pgrp['target'],
name=name)
process.daemon = True
pgrp['processes'].append(process)
process.start()
def _start_ScannerWorker_monitor(self):
"""Start a monitor to track the number of running worker processes."""
def monitor():
interval = settings['status_interval']/4
processes = [pgrp for pgrp in self._processes if
pgrp['name']=='ScannerWorker']
processes = processes[0]['processes']
try:
while self.is_active.value:
try:
num_alive = sum(p.is_alive() for p in processes)
# Note: The "is_alive" Process method used above can be
# used only in the parent process. As such, this
# function must be run in the main process and not in a
# child process.
except OSError:
if self.is_active.value: raise
else:
self.num_ScannerWorker_alive.value = num_alive
time.sleep(interval)
except (KeyboardInterrupt, SystemExit):
pass
monitor_thread = threading.Thread(target=monitor)
monitor_thread.daemon = True
monitor_thread.start()
def _stop_workers(self):
"""Stop workers cleanly."""
# Stop processes in order
for pgrp in self._processes:
pgrp_queue = pgrp.get('queue')
if pgrp_queue is not None:
pgrp_num = pgrp.get('num', 1)
for _ in range(pgrp_num):
if self.is_active.value:
pgrp_queue.put(None) # is blocking
else:
try: pgrp_queue.put_nowait(None)
except Queue.Full: pass
if pgrp.get('join', True):
for p in pgrp['processes']:
p.join()
time.sleep(settings['sleep_time_at_exit'])
def _item_handler(self):
"""
Handle queued item paths.
Multiple instances of this method are expected to run simultaneously.
"""
# Create process-specific interfaces
Item.enstore = Enstore()
# Setup local variables
local_count = 0
# Note: A separate local count (specific to the current process) and
# global count are maintained. This allows for infrequent updates to
# the global count. The local count is the number of items that have
# been processed locally in the current process, but have not yet been
# incremented in the global count.
update_time = time.time() # Most recent global state update time.
update_thresholds = {'count': self.num_scan_processes * 2,
'time': settings['status_interval'] / 2,}
# Note: The thresholds are used to reduce possible contention from
# multiple scan processes for updating the shared global values. A
# global update is executed when any of the thresholds are reached.
# Setup required external variables locally
item_get = self.items_q.get
noticegrp_put = self.noticegrps_q.put
gc_updater = self._increment_num_items_processed # For global count.
def process_item(item):
noticegrp = self._scan_item(item)
if noticegrp:
noticegrp = noticegrp.to_dict()
# Note: The object is transmitted over multiprocessing as a
# dict. This is because a dict can be easily pickled and
# unpickled, whereas the object itself is more difficult to
# pickle and unpickle.
noticegrp_put(noticegrp)
def update_state(item, local_count, update_time, force_update=False):
if (item is not None) and item.is_scanned:
local_count += 1
update_age = time.time() - update_time
update_thresholds_met = {
'count': local_count == update_thresholds['count'],
'time': update_age > update_thresholds['time'],}
update_threshold_met = any(update_thresholds_met.values())
if (local_count > 0) and (update_threshold_met or force_update):
gc_updater(local_count)
local_count = 0
update_time = time.time()
if (item is not None) and item.is_scanned and item.is_file():
# Note: The checkpoint is set only if the item is a
# file, as opposed to a directory. This is because
# the resumption code can currently only use a file
# as a checkpoint.
self.checkpoint.value = item
# Note: Given that multiple workers work on the
# work queue concurrently, this setting of the
# checkpoint is an approximate one, as coordinated
# checkpointing is not used. A blocking version of
# coordinated checkpointing can possibly be
# implemented with multiprocessing.Barrier, which
# was only introduced in Python 3.3.
return (local_count, update_time)
# Process items
item = None # Prevents possible NameError exception in finally-block.
try:
while self.is_active.value:
item = item_get()
if item is None: # Put by self._stop_workers()
break
else:
process_item(item)
local_count, update_time = \
update_state(item, local_count, update_time)
except (KeyboardInterrupt, SystemExit):
pass
finally:
update_state(item, local_count, update_time, force_update=True)
# Note: If an exception is raised in the try-block, due to
# implementation limitations, it is possible that a duplicate
# update is performed on the global count.
time.sleep(settings['sleep_time_at_exit'])
def _noticegrp_handler(self):
"""
Handle queued :class:`NoticeGrp` objects.
Only a single instance of this method is expected to run.
"""
noticegrp_get = self.noticegrps_q.get
# Obtain handles to output files
output_file = open(settings['output_file'], 'a')
output_file_dict = open(settings['output_file_dict'], 'a')
# Write to output files
try:
while self.is_active.value:
noticegrp = noticegrp_get()
if noticegrp is None: # Put by self._stop_workers()
break
else:
noticegrp = NoticeGrp.from_dict(noticegrp)
# Note: The object is transmitted over multiprocessing
# as a dict. This is because a dict can be easily
# pickled and unpickled, whereas the object itself is
# more difficult to pickle or unpickle.
if noticegrp:
str_out = '{0}\n\n'.format(noticegrp)
output_file.write(str_out)
str_out = '{0}\n'.format(noticegrp.to_exportable_dict())
output_file_dict.write(str_out)
output_file.flush()
output_file_dict.flush()
except (KeyboardInterrupt, SystemExit):
pass
finally:
time.sleep(settings['sleep_time_at_exit'])
output_file.flush()
output_file_dict.flush()
output_file.close()
output_file_dict.close()
def _status_logger(self):
"""
Log the current status after each interval of time.
Only a single instance of this method is expected to run.
"""
# Setup environment
interval = settings['status_interval']
interval_cur = 1
num_items_processed_previously = secs_elapsed_previously = 0
# Log status
try:
while self.is_active.value:
(num_items_processed_previously, secs_elapsed_previously) = \
self._log_status(num_items_processed_previously,
secs_elapsed_previously,
interval_cur)
time.sleep(interval_cur)
interval_cur = min(interval, interval_cur*math.e)
# Note: `interval_cur` converges to `interval`.
# `interval_cur*math.e` is equivalent to `math.e**x` with
# incrementing x.
except (KeyboardInterrupt, SystemExit):
pass
# Note: Execution of "self._log_status()" inside a "finally" block here
# does not happen. It is done in the main process instead.
def _log_status(self, num_items_processed_previously=None,
secs_elapsed_previously=None,
interval_next=None):
"""
Log the current status once.
:type num_items_processed_previously: :obj:`int` (non-negative) or
:obj:`None`
:arg num_items_processed_previously: Number of items processed
cumulatively, as returned previously.
:type secs_elapsed_previously: :obj:`int` (non-negative) or :obj:`None`
:arg secs_elapsed_previously: Number of seconds elapsed cumulatively,
as returned previously.
:type interval_next: :obj:`int` (non-negative) or :obj:`None`
:arg interval_next: Number of seconds to next update.
.. todo:: The `num_items_processed_previously` and
`secs_elapsed_previously` arguments are to be removed and replaced
using class instance variables.
"""
dttd = lambda s: datetime.timedelta(seconds=round(s))
intstr = lambda i: locale.format('%i', i, grouping=True)
# fmtstrint = lambda s, i: '{0} {1}'.format(s, intstr(i))
items = []
# Prepare basic items for status
datetime_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
num_items_total = int(self.num_items_total.value)
num_items_processed_cum = int(self.num_items_processed.value)
secs_elapsed_cum = time.time() - self._start_time
speed_cum = num_items_processed_cum / secs_elapsed_cum # items/second
# Add basic stats
items += [('Active workers',
intstr(self.num_ScannerWorker_alive.value)), #approx
('Time elapsed',
dttd(secs_elapsed_cum)),
('Items scanned (cumulative)',
intstr(num_items_processed_cum)), #approx
('Speed (cumulative) (items/s)',
intstr(speed_cum)), #approx
]
# Conditionally add current iteration status
if ((num_items_processed_previously is not None) and
(secs_elapsed_previously is not None)):
# Above is explicit check to disambiguate from 0
num_items_processed_cur = (num_items_processed_cum -
num_items_processed_previously)
secs_elapsed_cur = secs_elapsed_cum - secs_elapsed_previously
speed_cur = num_items_processed_cur / secs_elapsed_cur
items += [
# ('Items processed (current)',
# intstr(num_items_processed_cur)), #approx
('Speed (current) (items/s)',
intstr(speed_cur)), #approx
]
# Conditionally add remaining time
remaining_secs = float('inf')
if num_items_total is not None:
num_items_remaining = num_items_total - num_items_processed_cum
items.append(('Items remaining',
intstr(num_items_remaining))) #approx
if speed_cum != 0:
remaining_secs = num_items_remaining / speed_cum
total_secs = secs_elapsed_cum + remaining_secs
items += [('Time remaining', dttd(remaining_secs)), #approx
('Time total', dttd(total_secs)), #approx
]
# Conditionally add time to next update
if interval_next is not None:
interval_next = min(interval_next, remaining_secs)
items += [('Time to next update', dttd(interval_next))] #approx
# Prepare status string
max_item_key_len = max(len(i[0]) for i in items)
items = ['{0:{1}}: {2}'.format(i[0], max_item_key_len, i[1]) for i in
items]
items.insert(0, datetime_now)
status = '\n'.join(items)
print(status, end='\n\n')
return (num_items_processed_cum, secs_elapsed_cum)
def _scan_item(self, item):
"""
Scan provided item as per the *check method* names and dependencies
which are specified in the :attr:`self.checks` attribute, returning the
updated :class:`NoticeGrp` instance for the item.
Multiple instances of this method are expected to run on different
items simultaneously.
"""
# Note: self.checks should not be modified.
checks_pending = list(self.checks)
# Note: Using `list(some_dict)` creates a copy of the dict's keys in
# both Python 2.x and 3.x. A copy is created here because the list is
# mutated later in the method.
#random.shuffle(checks_pending)
# Note: The list of pending checks can be randomized to reduce the
# possibility of multiple worker processes trying to read the same type
# of file metadata at the same time. By explicitly randomizing the
# order in which various checks may run, there may be slightly less
# contention. It is unclear if this randomization actually affects the
# scan speed.
ccs = {} # This refers to checks completion statuses.
def pop_pending_check_name():
for check in copy.copy(checks_pending):
# Note: A copy is used above because checks_pending is modified
# inside the loop. Not using a copy may cause a problem with
# iteration.
prereqs = self.checks[check]
is_prereqs_passed = all(ccs.get(pr)==True for pr in prereqs)
is_prereqs_failed = any(ccs.get(pr)==False for pr in prereqs)
if is_prereqs_passed or is_prereqs_failed:
checks_pending.remove(check)
if is_prereqs_passed: return check
raise IndexError('no pending check')
# Run checks
while True:
# Get check
try: check_name = pop_pending_check_name()
except IndexError: break
check = getattr(self, check_name)
# Run check
run_status = None
try:
check(item)
except Notice as notice:
item.add_notice(notice)
run_status = not (isinstance(notice, CriticalNotice)
or isinstance(notice, ErrorNotice))
if isinstance(notice, CriticalNotice): break
else:
run_status = True
finally:
if run_status is not None:
ccs[check_name] = run_status
item.is_scanned = True
return item.noticegrp
@classmethod
def print_checks(cls):
"""
Print names and docstrings of all runnable *check methods*.
A check is runnable if all its prerequisites, if any, are runnable.
"""
def is_runnable(check):
return ((check in cls.checks) and
all(is_runnable(prereq) for prereq in cls.checks[check]))
# Note: This check is performed to help with debugging in the
# event some checks are manually disabled.
def describe(check):
method = getattr(cls, check)
desc = inspect.getdoc(method)
desc = desc.partition('\n\n')[0] # Truncate at first empty line.
desc = desc.replace('\n', ' ') # Joins multiple lines.
desc = desc.replace('`', '') # Removes what may be Sphinx syntax.
desc = '{}: {}'.format(check, desc)
return desc
checks = (describe(c) for c in sorted(cls.checks) if is_runnable(c))
for c in checks: print(c)
class ScannerForward(Scanner):
"""Perform forward scan."""
checks = {
# Each dict key is the name of a check method which accepts an Item object.
# The method can optionally raise a Notice (or an inherited) exception. If
# the ErrorNotice or CriticalNotice exception is raised, the check is
# considered failed, otherwise succeeded. If a CriticalNotice exception is
# raised, all remaining checks for the Item are skipped.
#
# Each dict value is a sequence of names of dependencies of check methods.
#
# The noted check methods can be run in a pseudo-random order as long as
# the respective dependencies have succeeded.
'check_path_attr': (), # Test check; never fails.
'check_is_storage_path': (),
'check_lstat': ('check_is_storage_path',),
'check_link_target': ('check_is_storage_path',),
'check_file_nlink': ('check_lstat',),
'check_file_temp': ('check_is_storage_path',),
'check_file_bad': ('check_is_storage_path',),
'check_fsid': ('check_is_storage_path',),
# 'check_parentfsid': # Never fails
# ('check_fsid',
# 'check_lstat',),
'check_fslayer2lines': ('check_fsid',
'check_lstat',),
'check_fslayer2': ('check_fslayer2lines',),
'check_fslayer2_crc': ('check_fslayer2',),
'check_fslayer2_size': ('check_fslayer2',),
'check_fslayer2_size_match': ('check_fslayer2',
'check_fslayer2_size',),
'check_fslayer1lines': ('check_fsid',
'check_lstat',
'check_fslayer2lines',
'check_fslayer2',),
'check_fslayer1': ('check_fslayer1lines',
'check_lstat',),
'check_fslayer4lines': ('check_fsid',
'check_lstat',
'check_fslayer2lines',
'check_fslayer2',),
'check_fslayer4': ('check_fslayer4lines',
'check_lstat',),
'check_enstore_file_info': ('check_lstat',
'check_fslayer1lines',), # L1 BFID is used.
'check_enstore_volume_info': ('check_lstat',
'check_enstore_file_info',),
'check_bfid_match': ('check_fslayer1',
'check_fslayer4',
'check_enstore_file_info',),
'check_file_deleted': ('check_enstore_file_info',),
'check_recent': ('check_lstat',),
'check_empty': ('check_lstat',
'check_fslayer2_size_match',
'check_enstore_file_info',),
'check_sfs_path': ('check_is_storage_path',),
'check_volume_label': ('check_fslayer4',
'check_enstore_file_info',),
'check_location_cookie': ('check_fslayer4',
'check_enstore_file_info',),
'check_size': ('check_lstat',
'check_fslayer2',
'check_fslayer4',
'check_enstore_file_info',),
'check_file_family': ('check_fslayer4',
'check_enstore_volume_info',),
# 'check_library': # Not necessary
# ('check_enstore_volume_info',),
'check_drive': ('check_fslayer4',
'check_enstore_file_info',),
'check_crc': (#'check_fslayer2',
'check_fslayer4',
#'check_enstore_volume_info',
'check_enstore_file_info',),
'check_path': ('check_fslayer4',
'check_enstore_file_info',),
'check_pnfsid': ('check_fsid',
'check_fslayer4',
'check_enstore_file_info',),
'check_copy': ('check_enstore_file_info',),
}
notices = {
'NoPath': "Cannot access object's path.",
'NotStorage': 'Not an Enstore file or directory.',
'NoStat': "Cannot access object's filesystem stat. {exception}",
'NlinkGT1': ("lstat nlink (number of hard links) count is >1. It is "
"{nlink}."),
'LinkBroken': ('Symbolic link is broken. It points to "{target}" which '
'does not exist.'),
'TempFile': ('File is a likely temporary file because its name '
'or extension ends with "{ending}".'),
'MarkedBad': 'File is marked bad.',
'NoID': 'Cannot read filesystem ID file "{filename}". {exception}',
'NoL2File': 'Cannot read layer 2 metadata file "{filename}". {exception}',
'L2MultVal': 'Multiple layer 2 "{property_}" property values exist.',
'L2RepVal': 'Repetition of layer 2 "{property_}" property values.',
'L2Extra': 'Layer 2 has these {num_extra_lines} extra lines: '
'{extra_lines}',
# 'NoParentID': ('Cannot read parent\'s filesystem ID file "{filename}". '
# '{exception}'),
# 'ParentIDMismatch': ('Parent ID mismatch. The parent IDs provided by files'
# ' "{filename1}" ({parentid1}) and "{filename2}" '
# '({parentid2}) are not the same.'),
'L2CRCNone': 'Layer 2 CRC is unavailable.',
'L2SizeNone': 'Layer 2 size is missing.',
'L2SizeMismatch': ("File size mismatch. Layer 2 size ({size_layer2})"
" doesn't match lstat size ({size_lstat})."),
'NoL1File': 'Cannot read layer 1 metadata file "{filename}". {exception}',
'L1Empty': 'Layer 1 metadata file "{filename}" is empty.',
'L1Extra': 'Extra layer 1 lines detected.',
# 'L1Mismatch': ('Layer 1 mismatch. Layer 1 provided by files "{filename1}" '
# 'and "{filename2}" are not the same.'),
'L1BFIDBad': 'Layer 1 BFID ({bfid}) is invalid.',
'L1BFIDNone': 'Layer 1 BFID is missing.',
'NoL4File': ('Cannot read layer 4 metadata file "{filename}". '
'{exception}'),
'L4Empty': 'Layer 4 metadata file "{filename}" is empty.',
'L4Extra': 'Extra layer 4 lines detected.',
# 'L4Mismatch': ('Layer 4 mismatch. Layer 4 provided by files "{filename1}" '
# 'and "{filename2}" are not the same.'),
'L4BFIDNone': 'Layer 4 BFID is missing.',
'FileInfoBadType': ('Enstore file info is not a dict. It is of type '
'"{type_}" and has value "{value}".'),
'NoFileInfo': 'File is not in Enstore database.',
'FileInfoBad': ('File status in file info provided by Enstore is not ok. '
'It is "{status}".'),
'FileInfoPathNone': 'File path in Enstore file info is missing.',
'FileInfoPNFSIDNone': 'PNFS ID in Enstore file info is missing.',
'FileInfoPNFSIDBad': ('PNFS ID in file info provided by Enstore database '
'is invalid. It is "{pnfsid}".'),
'VolInfoBadType': ('Enstore volume info is not a dict. It is of type '
'"{type_}" and has value "{value}".'),
'NoVolInfo': 'Volume is not in Enstore database.',
'VolInfoBad': ('Volume status in volume info provided by Enstore database '
'is not ok. It is "{status}".'),
'BFIDMismatch': ('BFID mismatch. The BFIDs provided by layer 1 '
'({bfid_layer1}) and layer 4 ({bfid_layer4}) are not the '
'same.'),
'MarkedDel': ('File is marked deleted by Enstore file info, but its entry '
'still unexpectedly exists in the filesystem.'),
'TooRecent': ('Object was modified in the past one day since the scan '
'began.'),
'Size0FileInfoOk': ('File is empty. Its lstat size is 0 and its layer 2 '
'size is {layer2_size}. Its info in Enstore is ok.'),
'Size0FileInfoNo': ('File is empty. Its lstat size is 0 and its layer 2 '
'size is {layer2_size}. Its info in Enstore is not '
'ok. It presumably has no info in Enstore.'),
'MultSFSPaths': ('Multiple paths were returned for PNFS ID {pnfsid}, '
'namely: {paths}'),
'L4VolLabelNone': 'Layer 4 volume label is missing.',
'FileInfoVolLabelNone': 'Volume label in Enstore file info is missing.',
'VolLabelMismatch': ("Volume label mismatch. File's layer 4 volume label "
"({volume_layer4}) doesn't match its Enstore file "
"info volume label ({volume_enstore})."),
'L4LCNone': 'Layer 4 location cookie is missing.',
'FileInfoLCNone': 'Location cookie in Enstore file info is missing.',
'L4LCBad': 'Layer 4 location cookie ({lc_layer4}) is invalid.',
'FileInfoLCBad': ('Location cookie in Enstore file info is invalid. It is '
'"{lc_enstore}".'),
'LCMismatch': ("Current location cookie mismatch. File's current layer 4 "
"location cookie ({current_lc_layer4}) doesn't match its "
"current Enstore file info location cookie "
"({current_lc_enstore})."),
'SizeNone': 'lstat size is missing.',
'L4SizeNone': 'Layer 4 size is missing.',
'FileInfoSizeNone': 'File size in Enstore file info is missing.',
'SizeMismatch': ("File size mismatch. File sizes for file with layer 1 "
"BFID \"{bfid_layer1}\" provided by {size} don't all "
"match."),
'L4FFNone': 'Layer 4 file family is missing.',
'VolInfoFFNone': 'File family is missing in Enstore volume info.',
'FFMismatch': ("File family mismatch. File's layer 4 file family "
"({ff_layer4}) doesn't match its Enstore volume info "
"file family ({ff_enstore})."),
'VolInfoLibNone': 'Library is missing in Enstore volume info.',
'VolInfoLibBad': ('Library ({library}) in Enstore volume info is not '
'recognized.'),
'L4DriveNone': 'Layer 4 drive is missing.',
'FileInfoDriveNone': 'Drive is missing in Enstore file info.',
'DriveMismatch': ("Drive mismatch. File's layer 4 drive "
"({drive_layer4}) doesn't match its Enstore file info "
"drive ({drive_enstore})."),
'CRCNone': 'CRC is missing in both layer 4 and Enstore file info.',
'L4CRCNone': 'Layer 4 CRC is missing.',
'FileInfoCRCNone': 'CRC is missing in Enstore file info.',
'L4CRCMismatch': ("CRC mismatch. File's layer 4 CRC ({crc_layer4}) doesn't"
" match its Enstore file info CRC ({crc_enstore})."),
'L2CRCMismatch': ("CRC mismatch. File's layer 2 CRC ({crc_layer2}) doesn't"
" match its Enstore file info 0-seeded CRC "
"({crc_enstore_0seeded}) or its Enstore file info "
"1-seeded CRC ({crc_enstore_1seeded})."),
'L4PathNone': 'Layer 4 file path is missing.',
'PathMismatch': ("File path mismatch. Normalized file paths for file with "
"layer 1 BFID \"{bfid_layer1}\" provided by {path} don't "
"all match. File may have been moved."),
'L4PNFSIDNone': 'Layer 4 PNFS ID is missing.',
'PNFSIDMismatch': ("PNFS ID mismatch. PNFS IDs for file with layer 1 BFID "
"\"{bfid_layer1}\" provided by {pnfsid} don't all "
"match. File may have been moved."),
'FileInfoDelNone': 'The "deleted" field is missing in Enstore file info.',
'FileInfoDelBad': ('The value of the "deleted" field ({deleted}) in '
'Enstore file info is not recognized.'),
'MarkedCopy': 'File is marked as {copy_types} by Enstore file info.',
}
# Note: The type of each notice, i.e. warning, error, etc. is not noted in
# the above dict because it can sometimes be dynamic.
@memoize
def get_num_items(self):
"""
Return the total number of items to be scanned.
This method is thread and process safe.
.. note:: As implemented, the :class:`memoize` decorator will rerun the
target method if and when the target is called upon program exit.
This is one reason why this method is not implemented as a reused
*property*.
"""
# Note: settings['fs_root'] is known to be an absolute path (and not
# have a trailing slash).
if settings['fs_root'] == '/pnfs/fs/usr':
# Use database
# Note: This can take a few seconds.
operation = ('select count(*) from t_inodes where itype in '
'(16384, 32768)')
# itype=16384 indicates a directory.
# itype=32768 indicates a file.
return int(Chimera().fetchone(operation)['count'])
else:
self.validate_scan_location()
# Use filesystem
# Note: This can be slow, depending upon the number of directories.
# This state is not normally expected.
count = -1 # This allows exclusion of fs_root itself, as done in
# self.queue_items. Resultant minimum will still be 0.
for _root, _dirs, files in os.walk(settings['fs_root']):
count += (1 + len(files)) # 1 is for _root
return count
def queue_items(self):
"""Queue items for scanning."""
# Provide methods locally
fs_root = settings['fs_root']
os_walker = os.walk(fs_root)
os_path_join = os.path.join
items_q_put = self.items_q.put
put_item = lambda item: items_q_put(Item(item))
put_file = lambda root, file_: put_item(os_path_join(root, file_))
def put_files(root, files):
for file_ in files:
put_file(root, file_)
# Provide checkpointing related variables
resume_flag = settings['resume_scan']
checkpoint = self.checkpoint.value # Guaranteed to be a file path.
def process_pre_checkpoint_dirs():
if resume_flag and checkpoint:
checkpoint_dir, checkpoint_file = os.path.split(checkpoint)
generic_failure_msg = ('The scan cannot be resumed for the '
'specified output file.\n')
# Perform some checks that are specific to the current Scanner.
# Ensure checkpoint is in fs_root
if not checkpoint.startswith(fs_root):
msg = ('Error: Checkpoint file "{0}" is outside of '
'scanning directory "{1}". {2}'
).format(checkpoint, fs_root, generic_failure_msg)
exit(msg)
# Ensure checkpoint file exists
if not os.path.isfile(checkpoint):
msg = ('Error: Checkpoint file "{0}" does not exist. {1}'
).format(checkpoint, generic_failure_msg)
exit(msg)
# Skip items preceding checkpoint
checkpoint_crossed = False
for root, _dirs, files in os_walker:
if root != checkpoint_dir:
num_items_less = 1 + len(files) # 1 is for root
self.num_items_total.value -= num_items_less
else:
# Note: Checkpoint is now a file in the current dir.
# As such, this state happens only once.
self.num_items_total.value -= 1 # for root
for file_ in files:
if checkpoint_crossed:
# Note: self.num_items_total.value should not
# be reduced here.
put_file(root, file_)
else:
self.num_items_total.value -= 1 # for file_
if file_ == checkpoint_file:
checkpoint_crossed = True
print('Checkpoint crossed.\n')
else:
if not checkpoint_crossed:
msg = ('Error: Checkpoint directory "{0}" was'
' not found to contain checkpoint file '
'"{1}". {2}'
).format(checkpoint_dir,
checkpoint_file,
generic_failure_msg)
exit(msg)
break
else:
if not checkpoint_crossed:
msg = ('Error: Checkpoint directory "{0}" was not '
'found. {1}'
).format(checkpoint_dir, generic_failure_msg)
exit(msg)
def process_post_checkpoint_dirs():
if (not resume_flag) or (not checkpoint):
# Queue only the files from only the initial root directory
root, _dirs, files = next(os_walker)
# put_item(root) is intentionally skipped, to not test fs_root.
# Doing this here allows avoidance of a persistent "if"
# statement.
put_files(root, files)
# Queue each remaining directory and file for scanning
for root, _dirs, files in os_walker:
put_item(root)
put_files(root, files)
# Process items
process_pre_checkpoint_dirs()
process_post_checkpoint_dirs()
def validate_scan_location(self):
"""Validate the scan location root."""
loc = settings['fs_root']
if not os.path.isdir(loc):
msg = 'Error: Scan root "{0}" is not a directory.'.format(loc)
exit(msg)
# Note: There is no reason to print loc if it is valid, as it is
# already evident.
def check_path_attr(self, item):
"""
Check whether ``item`` has a path.
:type item: :class:`Item`
:arg item: object to check
"""
try:
item.path
except AttributeError:
raise CriticalNotice('NoPath')
def check_is_storage_path(self, item):
"""
Check whether ``item`` is an Enstore ``item``.
:type item: :class:`Item`
:arg item: object to check
"""
if not item.is_storage_path():
raise CriticalNotice('NotStorage')
def check_lstat(self, item):
"""
Check whether ``item``'s stats are accessible.
:type item: :class:`Item`
:arg item: object to check
"""
try:
item.lstat
except OSError as e:
# If this occurs, refer to the get_stat method of the previous
# implementation of this module for a possible modification to this
# section.
raise CriticalNotice('NoStat', exception=e.strerror or '')
def check_file_nlink(self, item):
"""
Check whether file has more than 1 hard links.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file() and (item.lstat.st_nlink > 1):
raise InfoNotice('NlinkGT1', nlink=item.lstat.st_nlink)
# There is no usual reason for the link count to be greater than 1.
# There have been cases where a move was aborted early and two
# directory entries were left pointing to one i-node, but the i-node
# only had a link count of 1 and not 2. Since there may be legitimate
# reasons for multiple hard links, it is not considered an error or a
# warning.
def check_link_target(self, item):
"""
Check whether symbolic link is broken.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_link() and (not os.path.exists(item.path)):
# Note: os.path.exists returns False for broken symbolic links.
raise WarningNotice('LinkBroken',
target=os.path.realpath(item.path))
def check_file_temp(self, item):
"""
Check whether ``item`` is a temporary file.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file():
path = item.path
endings = ('.nfs', '.lock', '_lock')
for ending in endings:
if path.endswith(ending):
raise InfoNotice('TempFile', ending=ending)
# Note: If the item is a temporary file, this method reports the
# corresponding ending string. This is why an "is_temp_file" method in
# the Item class is not implemented or used insted.
def check_file_bad(self, item):
"""
Check whether ``item`` is a file that is marked bad.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file_bad:
raise InfoNotice('MarkedBad')
def check_fsid(self, item):
"""
Check whether ``item`` has an accessible filesystem ID.
:type item: :class:`Item`
:arg item: object to check
"""
try:
_fsid = item.fsid
except (IOError, OSError) as e:
raise CriticalNotice('NoID', filename=item.fsidname,
exception=e.strerror or '')
# def check_parentfsid(self, item):
# """
# Check file's parent's filesystem ID for its presence.
#
# :type item: :class:`Item`
# :arg item: object to check
# """
#
# if item.is_file():
#
# # Check value for availability
# #sources = 'parent_file', 'parent_dir'
# sources = ('parent_file',)
# parentfsids = {}
# for source in sources:
# try:
# parentfsids[source] = item.parentfsid(source)
# except (IOError, OSError) as e:
# raise ErrorNotice('NoParentID',
# filename=item.parentfsidname(source),
# exception=e.strerror or '')
#
# # Check values for consistency (never observed to fail)
# source1, source2 = 'parent_file', 'parent_dir'
# if ((source1 in parentfsids) and (source2 in parentfsids) and
# (parentfsids[source1] != parentfsids[source2])):
# raise ErrorNotice('ParentIDMismatch',
# filename1=item.parentfsidname(source1),
# parentid1=parentfsids[source1],
# filename2=item.parentfsidname(source2),
# parentid2=parentfsids[source2])
def check_fslayer2lines(self, item):
"""
Check whether a file's filesystem provided layer 2 is corrupted.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file():
try:
_layer_lines = item.fslayerlines(2, 'filename')
except (OSError, IOError) as e:
if not (e.errno == errno.ENOENT): # confirmed
raise ErrorNotice('NoL2File', filename=item.fslayername(2),
exception=e.strerror or '')
def check_fslayer2(self, item):
"""
Check for inconsistencies in a file's filesystem provided layer 2.
The check is performed only if the ``item`` is a file and if its layer
2 is present. If its layer 2 is missing, this is not an error
condition.
:type item: :class:`Item`
:arg item: object to check
"""
def check_properties(properties):
for property_, values in properties.items():
if len(values) > 1:
notice = ErrorNotice('L2MultVal', property_=property_)
item.add_notice(notice)
if len(values) != len(set(values)):
notice = WarningNotice('L2RepVal', property_=property_)
item.add_notice(notice)
# Do checks
if item.is_file() and item.has_fslayer(2):
layer_dict = item.fslayer2('filename')
# Check properties
try: properties = layer_dict['properties']
except KeyError: pass
else: check_properties(properties)
# Check pools
if not item.is_file_empty:
try: pools = layer_dict['pools']
except KeyError: pass
else: InfoNotice('L2Extra', num_extra_lines=len(pools),
extra_lines=pools)
def check_fslayer2_crc(self, item):
"""
Check whether a file's layer 2 CRC is available.
The check is performed only if the ``item`` is a file and a HSM is not
used.
:type item: :class:`Item`
:arg item: object to check
"""
if (item.is_file() and item.has_fslayer(2)
and (item.fslayer2_property('hsm') == 'no')
and (item.fslayer2_property('crc') is None)):
raise WarningNotice('L2CRCNone')
def check_fslayer2_size(self, item):
"""
Check whether a file's layer 2 size is available.
The check is performed only if the ``item`` is a file and a HSM is not
used.
:type item: :class:`Item`
:arg item: object to check
"""
if (item.is_file() and item.has_fslayer(2)
and (item.fslayer2_property('hsm') == 'no')
and (item.fslayer2_property('length') is None)):
raise WarningNotice('L2SizeNone')
def check_fslayer2_size_match(self, item):
"""
Conditionally check whether ``item``'s layer 2 and filesystem sizes
match.
The check is performed only if the ``item`` is a file and a HSM is not
used.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file() and (item.fslayer2_property('hsm') == 'no'):
size_lstat = item.lstat.st_size # int
size_layer2 = item.fslayer2_property('length') # int or None
if ((size_layer2 is not None) and (size_lstat != size_layer2) and
not (size_lstat==1 and size_layer2>2147483647)):
# Not sure why the check below was done:
# "not (size_lstat==1 and size_layer2>2147483647)"
# Note that 2147483647 is 2GiB-1.
raise ErrorNotice('L2SizeMismatch', size_layer2=size_layer2,
size_lstat=size_lstat)
def check_fslayer1lines(self, item):
"""
Check whether file's filesystem provided layer 1 is corrupted.
The check is performed only if the ``item`` is a non-recent file and if
a HSM may be used.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_nonrecent_file and (item.fslayer2_property('hsm') != 'no'):
try:
layer_lines = item.fslayerlines(1, 'filename')
except (OSError, IOError) as e:
raise ErrorNotice('NoL1File', filename=item.fslayername(1),
exception=e.strerror or '')
else:
if not layer_lines:
raise ErrorNotice('L1Empty', filename=item.fslayername(1))
def check_fslayer1(self, item):
"""
Check for inconsistencies in file's filesystem provided layer 1.
The check is performed only if the ``item`` is a non-recent file and if
its layer 1 is present. If its layer 1 is missing, an appropriate
notice is raised by the :meth:`check_fslayer1lines` method as
applicable.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_nonrecent_file and item.has_fslayer(1):
layer1 = item.fslayer1('filename')
# Check for extra lines
if 'pools' in layer1:
item.add_notice(WarningNotice('L1Extra'))
# # Check for mismatch (never observed to fail)
# if item.fslayer1('filename') != item.fslayer1('fsid'):
# raise ErrorNotice('L1Mismatch',
# filename1=item.fslayername(1,'filename'),
# filename2=item.fslayername(1,'fsid'))
# Check BFID
if not item.is_file_empty:
bfid = item.fslayer1_bfid() or ''
if not bfid:
raise ErrorNotice('L1BFIDNone')
elif len(bfid) < 8:
raise ErrorNotice('L1BFIDBad', bfid=bfid)
def check_fslayer4lines(self, item):
"""
Check whether a file's filesystem provided layer 4 is corrupted.
The check is performed only if the ``item`` is a non-recent file and if
a HSM may be used.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_nonrecent_file and (item.fslayer2_property('hsm') != 'no'):
try:
layer_lines = item.fslayerlines(4, 'filename')
except (OSError, IOError) as e:
raise ErrorNotice('NoL4File', filename=item.fslayername(4),
exception=e.strerror or '')
else:
if not layer_lines:
raise ErrorNotice('L4Empty', filename=item.fslayername(4))
def check_fslayer4(self, item):
"""
Check for inconsistencies in ``item``'s filesystem provided layer 4.
The check is performed only if the ``item`` is a non-recent file and if
its layer 4 is present. If its layer 4 is missing, an appropriate
notice is raised by the :meth:`check_fslayer4lines` method as
applicable.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_nonrecent_file and item.has_fslayer(4):
layer4 = item.fslayer4('filename')
# Check for extra lines
if 'pools' in layer4:
item.add_notice(WarningNotice('L4Extra'))
# # Check for mismatch (never observed to fail)
# if item.fslayer4('filename') != item.fslayer4('fsid'):
# raise ErrorNotice('L4Mismatch',
# filename1=item.fslayername(4,'filename'),
# filename2=item.fslayername(4,'fsid'))
# Check BFID
if (not item.is_file_empty) and (not item.fslayer4_bfid()):
raise ErrorNotice('L4BFIDNone')
def check_enstore_file_info(self, item):
"""
Check for inconsistencies in ``item``'s Enstore provided file info.
This check is performed only if the ``item`` is a non-recent file and
its BFID is obtained.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_nonrecent_file:
efi = item.enstore_file_info
bfid_layer1 = item.fslayer1_bfid() # Links Chimera with Enstore.
if not isinstance(efi, dict):
raise ErrorNotice('FileInfoBadType',
bfid_layer1=bfid_layer1,
type_=type(efi).__name__,
value=efi)
if efi.get('bfid'): # Unsure if this line is necessary.
if not item.is_enstore_file_info_ok:
if efi['status'][0] == enstore_errors.NO_FILE:
# Note: enstore_errors.NO_FILE == 'NO SUCH FILE/BFID'
raise ErrorNotice('NoFileInfo',
bfid_layer1=bfid_layer1,)
else:
raise ErrorNotice('FileInfoBad',
bfid_layer1=bfid_layer1,
status=efi['status'])
elif not item.is_file_deleted:
# This state is normal.
empty_values = ('', None, 'None')
if efi.get('pnfs_name0') in empty_values:
raise ErrorNotice('FileInfoPathNone',
bfid_layer1=bfid_layer1)
efi_pnfsid = efi.get('pnfsid')
if efi_pnfsid in empty_values:
raise ErrorNotice('FileInfoPNFSIDNone',
bfid_layer1=bfid_layer1)
elif not enstore_namespace.is_id(efi_pnfsid):
# Note: enstore_namespace.is_id expects a str.
raise ErrorNotice('FileInfoPNFSIDBad',
bfid_layer1=bfid_layer1,
pnfsid=efi_pnfsid)
def check_enstore_volume_info(self, item):
"""
Check for inconsistencies in ``item``'s Enstore provided volume info.
This check is performed only if the ``item`` is a non-recent file and
its volume name is obtained.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_nonrecent_file:
evi = item.enstore_volume_info
bfid_layer1 = item.fslayer1_bfid() # Links Chimera with Enstore.
if not isinstance(evi, dict):
raise ErrorNotice('VolInfoBadType',
bfid_layer1=bfid_layer1,
type_=type(evi).__name__,
value=evi)
if evi.get('external_label'): # Unsure if this line is necessary.
if not item.is_enstore_volume_info_ok:
if evi['status'][0] == enstore_errors.NOVOLUME:
# enstore_errors.NOVOLUME = 'NOVOLUME'
raise ErrorNotice('NoVolInfo', bfid_layer1=bfid_layer1)
else:
raise ErrorNotice('VolInfoBad',
bfid_layer1=bfid_layer1,
status=evi['status'])
def check_bfid_match(self, item):
"""
Check for a mismatch in the file's layer 1 and layer 4 BFIDs.
This check is performed only if the ``item`` is a file, is not a copy,
is not marked deleted, and its layer 1 and 4 exist.
:type item: :class:`Item`
:arg item: object to check
"""
if (item.is_file() and (not item.is_file_a_copy) and
(not item.is_file_deleted) and item.has_fslayer(1) and
item.has_fslayer(4)):
fslayer1_bfid = item.fslayer1_bfid()
fslayer4_bfid = item.fslayer4_bfid()
if fslayer1_bfid != fslayer4_bfid:
raise ErrorNotice('BFIDMismatch',
bfid_layer1=fslayer1_bfid,
bfid_layer4=fslayer4_bfid)
def check_file_deleted(self, item):
"""
Check if file is marked deleted.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file():
deleted = item.enstore_file_info.get('deleted')
if deleted is None:
raise ErrorNotice('FileInfoDelNone')
else:
if (not item.is_file_a_copy) and (deleted=='yes'):
raise ErrorNotice('MarkedDel')
if deleted not in ('yes', 'no'):
raise ErrorNotice('FileInfoDelBad', deleted=deleted)
def check_recent(self, item):
"""
Check if the file is recent.
This check can help in the assessment of other notices.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_recent:
raise InfoNotice('TooRecent')
def check_empty(self, item):
"""
Check if the file has :obj:`~os.lstat` size zero.
This check is performed only if the ``item`` is a non-recent file.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_nonrecent_file and item.is_file_empty:
fslayer2_size = item.fslayer2_property('length')
# fslayer2_size can be 0, None, etc.
if fslayer2_size is None: fslayer2_size = 'not present'
NoticeType = InfoNotice if fslayer2_size==0 else ErrorNotice
notice_key_suffix = 'Ok' if item.is_enstore_file_info_ok else 'No'
notice_key = 'Size0FileInfo{0}'.format(notice_key_suffix)
raise NoticeType(notice_key, layer2_size=fslayer2_size)
def check_sfs_path(self, item):
"""
Check if any of the PNFS IDs in Enstore for the current file has
more than one path.
:type item: :class:`Item`
:arg item: object to check
"""
# Note: This is very slow with PNFS, but is not too slow with Chimera.
if item.is_file():
for file_info in item.enstore_files_list_by_path:
pnfs_name = file_info.get('pnfs_name0')
pnfs_id = file_info.get('pnfsid')
if (not pnfs_name) or (pnfs_id in ('', None, 'None')):
continue
sfs_paths = item.sfs_paths(pnfs_name, pnfs_id)
if len(sfs_paths) > 1:
item.add_notice(ErrorNotice('MultSFSPaths',
pnfsid=pnfs_id,
paths=', '.join(sfs_paths)))
def check_volume_label(self, item):
"""
Check file's layer 4 and Enstore volume labels for their presence and
also for a mismatch.
This check is performed only if the ``item`` is a file and is not a
copy.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file() and (not item.is_file_a_copy):
# Retrieve values
volume_layer4 = item.fslayer4('filename').get('volume')
volume_enstore = item.enstore_file_info.get('external_label')
# Check values for availability
if item.has_fslayer(4) and (not volume_layer4):
item.add_notice(ErrorNotice('L4VolLabelNone'))
if item.is_enstore_file_info_ok and (not volume_enstore):
item.add_notice(ErrorNotice('FileInfoVolLabelNone'))
# Check values for consistency
if (volume_layer4 and volume_enstore and
(volume_layer4 != volume_enstore)):
raise ErrorNotice('VolLabelMismatch',
volume_layer4=volume_layer4,
volume_enstore=volume_enstore)
def check_location_cookie(self, item):
"""
Check file's layer 4 and Enstore location cookies for their presence
and also for a mismatch.
This check is performed only if the ``item`` is a file and is not a
copy.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file() and (not item.is_file_a_copy):
# Retrieve values
layer4 = item.fslayer4('filename')
efi = item.enstore_file_info
lc_layer4 = layer4.get('location_cookie')
lc_enstore = efi.get('location_cookie')
lc_cur_layer4 = layer4.get('location_cookie_current')
lc_cur_enstore = efi.get('location_cookie_current')
is_lc = enstore_functions3.is_location_cookie
# Check values for availability
if item.has_fslayer(4):
if not lc_layer4:
item.add_notice(ErrorNotice('L4LCNone'))
elif not is_lc(lc_layer4):
item.add_notice(ErrorNotice('L4LCBad',
lc_layer4=lc_layer4))
if item.is_enstore_file_info_ok:
if not lc_enstore:
item.add_notice(ErrorNotice('FileInfoLCNone'))
elif not is_lc(lc_enstore):
item.add_notice(ErrorNotice('FileInfoLCBad',
lc_enstore=lc_enstore))
# Check values for consistency
if (lc_cur_layer4 and lc_cur_enstore and
(lc_cur_layer4 != lc_cur_enstore)):
raise ErrorNotice('LCMismatch',
current_lc_layer4=lc_cur_layer4,
current_lc_enstore=lc_cur_enstore)
def check_size(self, item):
"""
Check file's lstat, layer 4 and Enstore file sizes for their presence
and also for a mismatch.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file():
# Retrieve values
sizes = item.sizes
# Check values for availability
if sizes['lstat'] is None:
item.add_notice(ErrorNotice('SizeNone'))
# Note: Layer 2 size is checked in the check_fslayer2_size and
# check_fslayer2_size_match methods.
if item.has_fslayer(4) and (sizes['layer 4'] is None):
item.add_notice(ErrorNotice('L4SizeNone'))
if item.is_enstore_file_info_ok and (sizes['Enstore'] is None):
item.add_notice(ErrorNotice('FileInfoSizeNone'))
# Check values for consistency
num_unique_sizes = len(set(s for s in sizes.values() if
(s is not None))) # Disambiguates from 0
if num_unique_sizes > 1:
# sizes = dict((b'size_{0}'.format(k),v) for k,v in
# sizes.items())
# raise ErrorNotice('SizeMismatch', **sizes)
raise ErrorNotice('SizeMismatch',
bfid_layer1=item.fslayer1_bfid(),
size=ReversibleDict(sizes))
# Note: The `size` arg name above must remain singular because
# this name is joined to the key names in its value. Refer to
# the `Notice.to_exportable_dict.flattened_dict` function.
def check_file_family(self, item):
"""
Check file's layer 4 and Enstore file family for their presence and
also for a mismatch.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file():
# Retrieve values
ff_layer4 = item.fslayer4('filename').get('file_family')
ff_enstore = item.enstore_volume_info.get('file_family')
# Check values for availability
if item.has_fslayer(4) and (not ff_layer4):
item.add_notice(ErrorNotice('L4FFNone'))
if item.is_enstore_volume_info_ok and (not ff_enstore):
item.add_notice(ErrorNotice('VolInfoFFNone'))
# Check values for consistency
if (ff_layer4 and ff_enstore and
(ff_enstore not in (ff_layer4,
'{0}-MIGRATION'.format(ff_layer4),
ff_layer4.partition('-MIGRATION')[0],
ff_layer4.partition('_copy_')[0],))):
raise ErrorNotice('FFMismatch', ff_layer4=ff_layer4,
ff_enstore=ff_enstore)
# def check_library(self, item):
# """
# Check file's Enstore library name for its presence and validity.
#
# This check is performed only if the ``item`` is a file and its Enstore
# volume info is ok.
#
# :type item: :class:`Item`
# :arg item: object to check
# """
#
# if item.is_file() and item.is_enstore_volume_info_ok:
#
# try: library = item.enstore_volume_info['library']
# except KeyError: raise ErrorNotice('VolInfoLibNone')
# else:
# if (library and
# (library not in item.enstore.library_managers) and
# ('shelf' not in library)):
# raise ErrorNotice('VolInfoLibBad', library=library)
def check_drive(self, item):
"""
Check file's layer 4 and Enstore drives for their presence and also for
a mismatch.
This check is performed only if the ``item`` is a file and is not a
copy.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file() and (not item.is_file_a_copy):
# Retrieve values
drive_layer4 = item.fslayer4('filename').get('drive')
drive_enstore = item.enstore_file_info.get('drive')
# Check values for availability
if item.has_fslayer(4) and (not drive_layer4):
item.add_notice(WarningNotice('L4DriveNone'))
if item.is_enstore_file_info_ok and (not drive_enstore):
item.add_notice(WarningNotice('FileInfoDriveNone'))
# Check values for consistency
drive_enstore_excludes = (drive_layer4, 'imported', 'missing',
'unknown:unknown')
if (drive_layer4 and drive_enstore and
(drive_enstore not in drive_enstore_excludes)):
raise ErrorNotice('DriveMismatch', drive_layer4=drive_layer4,
drive_enstore=drive_enstore)
def check_crc(self, item):
"""
Check file's layer 4 and Enstore CRCs for their presence and also for
a mismatch.
This check is performed only if the ``item`` is not an empty file.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file() and (not item.is_file_empty):
# Retrieve values
crc_layer2 = item.fslayer2_property('crc')
crc_layer4 = item.fslayer4('filename').get('crc')
efi = item.enstore_file_info
crc_enstore = crc_enstore_0seeded = efi.get('complete_crc')
crc_enstore_1seeded = efi.get('complete_crc_1seeded')
media_type = item.enstore_volume_info.get('media_type')
# Check values for availability
# Note: It is ok for crc_layer2 to be unavailable.
if (item.has_fslayer(4) and (not crc_layer4) and
item.is_enstore_file_info_ok and (not crc_enstore)):
# Note: When crc_layer4 or crc_enstore are missing, they are
# often missing together.
item.add_notice(WarningNotice('CRCNone'))
else:
if item.has_fslayer(4) and (not crc_layer4):
item.add_notice(WarningNotice('L4CRCNone'))
if item.is_enstore_file_info_ok and (not crc_enstore):
item.add_notice(WarningNotice('FileInfoCRCNone'))
# Check values for consistency
if (crc_layer2 and (crc_enstore_0seeded or crc_enstore_1seeded) and
media_type and (media_type != 'null') and
(crc_layer2 not in (crc_enstore_0seeded, crc_enstore_1seeded))):
item.add_notice(ErrorNotice('L2CRCMismatch',
crc_layer2=crc_layer2,
crc_enstore_0seeded=crc_enstore_0seeded,
crc_enstore_1seeded=crc_enstore_1seeded))
if crc_layer4 and crc_enstore and (crc_layer4 != crc_enstore):
raise ErrorNotice('L4CRCMismatch', crc_layer4=crc_layer4,
crc_enstore=crc_enstore)
def check_path(self, item):
"""
Check file's layer 4, Enstore, and filesystem provided paths for
their presence and also for a mismatch.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file() and (not item.is_file_a_copy):
# Retrieve values
paths = item.norm_paths
# Check values for availability
# Note: 'filesystem' and 'Enstore' paths are checked previously.
if item.has_fslayer(4) and (not paths['layer 4']):
item.add_notice(ErrorNotice('L4PathNone'))
# Check values for consistency
num_unique_paths = len(set(p for p in paths.values() if p))
if num_unique_paths > 1:
raise ErrorNotice('PathMismatch',
bfid_layer1=item.fslayer1_bfid(),
path=ReversibleDict(paths))
# Note: The `path` arg name above must remain singular because
# this name is joined to the key names in its value. Refer to
# the `Notice.to_exportable_dict.flattened_dict` function.
def check_pnfsid(self, item):
"""
Check file's filesystem ID file, layer 4 and Enstore PNFS IDs for
their presence and also for a mismatch.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file():
# Retrieve values
pnfsids = {'ID-file': item.fsid,
'layer 4': item.fslayer4('filename').get('pnfsid'),
'Enstore': item.enstore_file_info.get('pnfsid'),
}
# Check values for availability
# Note: 'ID-file' and 'Enstore' PNFS IDs are checked previously.
if item.has_fslayer(4) and (not pnfsids['layer 4']):
item.add_notice(ErrorNotice('L4PNFSIDNone'))
# Check values for consistency
num_unique_paths = len(set(p for p in pnfsids.values() if p))
if num_unique_paths > 1:
raise ErrorNotice('PNFSIDMismatch',
bfid_layer1=item.fslayer1_bfid(),
pnfsid=ReversibleDict(pnfsids))
# Note: The `pnfsid` arg name above must remain singular
# because this name is joined to the key names in its value.
# Refer to the `Notice.to_exportable_dict.flattened_dict`
# function.
def check_copy(self, item):
"""
Check if file has any of the copy attributes set.
This check is performed only if the ``item`` is a file and its Enstore
file info is ok.
:type item: :class:`Item`
:arg item: object to check
"""
if item.is_file() and item.is_enstore_file_info_ok:
# Retrieve values
efi = item.enstore_file_info
# Identify positive values
possible_copy_types = ('multiple', 'primary', 'migrated',
'migrated_to')
is_true = lambda v: v in ('yes', 'Yes', '1', 1, True)
detected_copy_types = []
for copy_type in possible_copy_types:
key = 'is_{0}_copy'.format(copy_type)
val = efi.get(key)
if val and is_true(val):
copy_type = copy_type.replace('_', ' ')
detected_copy_types.append(copy_type)
# Report positive values
if detected_copy_types:
detected_copy_types = [c.replace('_', ' ') for c in
detected_copy_types]
detected_copy_types = ['{0} copy'.format(c) for c in
detected_copy_types]
detected_copy_types = str(PrintableList(detected_copy_types))
raise InfoNotice('MarkedCopy', copy_types=detected_copy_types)
class Item:
"""
Return an object corresponding to a file or a directory.
Before an instance is created:
- The :attr:`enstore` class attribute must be set to an :class:`Enstore`
class instance. This must be done individually in each process in which
this :class:`Item` class is to be used.
"""
start_time = time.time()
enstore = None # To be set individually in each process.
chimera = Chimera()
_cache_volume_info = settings['cache_volume_info']
if _cache_volume_info:
#volume_info_cache = multiprocessing.Manager().dict()
volume_info_cache = MPSubDictCache()
def __init__(self, item_path):
"""Initialize the ``item``.
:type item_path: :obj:`str`
:arg item_path: absolute filesystem path of the item.
"""
self.path = item_path
self.noticegrp = NoticeGrp(self.path)
self.is_scanned = False
self._cached_exceptions = {}
def __repr__(self):
"""
Return a string representation.
This string allows the class instance to be reconstructed in another
process.
"""
return '{0}({1})'.format(self.__class__.__name__, repr(self.path))
def __eq__(self, other):
"""
Perform an equality comparison.
:type other: :class:`Item`
:arg other: object to compare.
:rtype: :obj:`bool`
"""
return (self.path==other.path)
def __str__(self):
"""Return a string representation."""
return self.path
@staticmethod
def _readfile(filename):
"""Return the stripped contents of the file corresponding to the
specified filename."""
return open(filename).read().strip()
def add_notice(self, notice):
"""
Add the provided ``notice`` to the group of notices associated with
the ``item``.
:type notice: :class:`Notice`
:arg notice: object to add.
"""
self.noticegrp.add_notice(notice)
@memoize_property
def dirname(self):
"""
Return the directory name of the ``item``.
:rtype: :obj:`str`
"""
return os.path.dirname(self.path)
@memoize_property
def basename(self):
"""
Return the base name of the ``item``.
:rtype: :obj:`str`
"""
return os.path.basename(self.path)
@memoize_property
def fsidname(self):
"""
Return the name of the ID file.
:rtype: :obj:`str`
"""
return os.path.join(self.dirname, '.(id)({0})'.format(self.basename))
@memoize
def parentfsidname(self, source='parent_file'):
"""
Return the name of the parent ID file.
:type source: :obj:`str`
:arg source: ``parent_file`` or ``parent_dir``.
:rtype: :obj:`str`
"""
if source == 'parent_file':
return os.path.join(self.dirname,
'.(parent)({0})'.format(self.fsid))
elif source == 'parent_dir':
return self.__class__(self.dirname).fsidname
else:
msg = 'Invalid value for source: {0}'.format(source)
raise ValueError(msg)
@memoize
def fslayername(self, layer_num, source='filename'):
"""
Return the name of layer information file for the specified layer
number.
:type layer_num: :obj:`int`
:arg layer_num: valid layer number
:type source: :obj:`str`
:arg source: ``filename`` or ``fsid``.
:rtype: :obj:`str`
"""
if source == 'filename':
return os.path.join(self.dirname,
'.(use)({0})({1})'.format(layer_num,
self.basename))
elif source == 'fsid':
return os.path.join(self.dirname,
'.(access)({0})({1})'.format(self.fsid,
layer_num))
else:
msg = 'Invalid value for source: {0}'.format(source)
raise ValueError(msg)
@memoize
def fslayerlines(self, layer_num, source):
"""
Return a :obj:`list` containing the lines contained in the layer
information file for the specified layer number.
:type layer_num: :obj:`int`
:arg layer_num: valid layer number
:type source: :obj:`str`
:arg source: ``filename`` or ``fsid``. It does not have a default value
to allow memoization to work correctly.
:rtype: :obj:`list`
A sample returned :obj:`list` for layer 1 is::
['CDMS124711171800000']
A sample returned :obj:`list` for layer 2 is::
['2,0,0,0.0,0.0', ':c=1:6d0f3ab9;h=yes;l=8192000000;']
A sample returned :obj:`list` for layer 4 is::
['VON077', '0000_000000000_0001544', '635567027', 'volatile',
'/pnfs/ilc4c/LOI/uu/uu_Runs_130.FNAL2.tar.gz', '',
'003A0000000000000005E2E0', '', 'CDMS124655315900000',
'stkenmvr204a:/dev/rmt/tps0d0n:1310050819', '954405925']
Layers are unavailable for directories.
The following exception will be raised if the layer information file is
unavailable::
IOError: [Errno 2] No such file or directory
Error 2 is ENOENT.
"""
# Re-raise cached exception if it exists
key = ('fslayerlines', layer_num, source)
try:
raise self._cached_exceptions[key]
except KeyError: pass
# Read file
fslayername = self.fslayername(layer_num, source)
try:
lines = open(fslayername).readlines()
except Exception as e:
self._cached_exceptions[key] = e
raise
lines = [ln.strip() for ln in lines]
return lines
@memoize
def fslayer1(self, source):
"""
Return a :obj:`dict` containing layer 1 information for a file.
:type source: :obj:`str`
:arg source: ``filename`` or ``fsid``. It does not have a default value
to allow memoization to work correctly.
:rtype: :obj:`dict`
A sample returned :obj:`dict` is::
{u'bfid': 'CDMS124711171800000'}
An empty :obj:`dict` is returned in the event of an OS or IO exception.
Layer 1 information is unavailable for directories.
"""
layer = {}
# Get lines
try: fslayerlines = self.fslayerlines(1, source)
except (OSError, IOError): return layer
# Parse lines
if fslayerlines:
# Save BFID
try: layer['bfid'] = fslayerlines[0]
except IndexError: pass
# Save anything found in any remaining lines
pools = fslayerlines[1:]
if pools: layer['pools'] = pools
return layer
@memoize
def fslayer1_bfid(self, source='filename'):
"""
Return the layer 1 value for BFID, or return :obj:`None` if
unavailable.
:type source: :obj:`str`
:arg source: ``filename`` or ``fsid``
:rtype: :obj:`str` or :obj:`None`
"""
return self.fslayer1(source).get('bfid')
@memoize
def fslayer2(self, source):
"""
Return a :obj:`dict` containing layer 2 information for a file.
:type source: :obj:`str`
:arg source: ``filename`` or ``fsid``. It does not have a default value
to allow memoization to work correctly.
:rtype: :obj:`dict`
A sample returned dict is::
{u'numbers': [u'2', u'0', u'0', u'0.0', u'0.0'],
u'properties': {u'crc': [4000420189], u'length': [8192000000],
u'hsm': [u'yes']}}
Each value in the ``properties`` :obj:`dict` is a :obj:`list`. This
:obj:`list` can have more than one item.
An empty :obj:`dict` is returned in the event of an OS or IO exception.
Layer 2 information is unavailable for directories.
"""
layer = {}
# Get lines
try: fslayerlines = self.fslayerlines(2, source)
except (OSError, IOError): return layer
# Parse lines
if fslayerlines:
# Save numbers
try: numbers = fslayerlines[0]
except IndexError: pass
else:
layer['numbers'] = numbers.split(',') # (line 1)
# Save properties
try: properties = fslayerlines[1] # (line 2)
except IndexError: pass
else:
pkm = { # Mapped names for Property Keys.
'c': 'crc', 'h': 'hsm', 'l': 'length'}
pvt = { # Transforms applied to Property Values.
'crc': lambda s: int(s.split(':')[1], 16),
'length': int,
# 'hsm': lambda h: {'yes': True,
# 'no': False}.get(h), #ignore
}
# Sample: ':c=1:ee71915d;h=yes;l=8192;'
if properties[0] == ':': properties = properties[1:]
# Sample: 'c=1:ee71915d;h=yes;l=8192;'
properties = sorted(p.split('=',1) for p in
properties.split(';') if p)
# Sample: [['c', '1:ee71915d'], ['h', 'yes'], ['l', '8192']]
properties = dict((k,[v[1] for v in v])
for k,v in
itertools.groupby(properties, lambda p: p[0]))
# This transforms the list into a dict in a way that if
# multiple values exist for a key, they are all noted in the
# list. Duplicate values are noted as well. Missing items are
# possible.
# Sample: {'h': ['yes'], 'c': ['1:ee71915d'], 'l': ['8192']}
properties = dict((pkm.get(k,k), v) for k,v in
properties.items())
# Sample: {'hsm': ['yes'], 'crc': ['1:ee71915d'],
# 'length': ['8192']}
properties = dict((k, [(pvt[k](v) if pvt.get(k) else v) for v
in vlist])
for k,vlist in properties.items())
# Sample: {'hsm': ['yes'], 'crc': [4000420189],
# 'length': [8192]}
layer['properties'] = properties
# Save anything found in any remaining lines
pools = fslayerlines[2:]
if pools: layer['pools'] = pools
return layer
@memoize
def fslayer2_property(self, l2property, source='filename'):
"""
Return the value for the specified layer 2 property, or return
:obj:`None` if unavailable.
:type l2property: :obj:`str`
:arg l2property: typically ``crc``, ``hsm``, or ``length``.
:type source: :obj:`str`
:arg source: ``filename`` or ``fsid``
"""
return self.fslayer2(source).get('properties', {}).get(l2property,
[None])[0]
@memoize
def fslayer4(self, source):
"""
Return a :obj:`dict` containing layer 4 information for a file.
:type source: :obj:`str`
:arg source: ``filename`` or ``fsid``. It does not have a default value
to allow memoization to work correctly.
:rtype: :obj:`dict`
A sample returned dict is::
{u'original_name': '/pnfs/BDMS/tariq/p2_004/p2_004_struc.LN22',
u'drive': 'stkenmvr214a:/dev/rmt/tps0d0n:1310051193',
u'volume': 'VOO007', 'crc': 1253462682, u'file_family': 'BDMS',
u'location_cookie': '0000_000000000_0000454',
u'pnfsid': '000E00000000000000013248',
u'bfid': 'CDMS123258695100001',
'size': 294912,
'location_cookie_list': ['0000', '000000000', '0000454'],
'location_cookie_current': '0000454',}
An empty :obj:`dict` is returned in the event of an OS or IO exception.
Layer 4 information is unavailable for directories.
"""
layer = {}
# Get lines
try: fslayerlines = self.fslayerlines(4, source)
except (OSError, IOError): return layer
# Parse lines
if fslayerlines:
keys = ('volume', 'location_cookie', 'size', 'file_family',
'original_name', None, 'pnfsid', None, 'bfid', 'drive',
'crc',)
transforms = \
{'crc': lambda s: int(long(s)),
'size': lambda s: int(long(s)),
# Note that "int(long(s))" covers strings such as '123L' also.
}
# Parse known lines
for i, k in enumerate(keys):
if k is not None:
try: layer[k] = fslayerlines[i]
except IndexError: break
# Transform as applicable
for k, tr_func in transforms.items():
if k in layer:
layer[k] = tr_func(layer[k])
# Parse extra lines
pools = fslayerlines[len(keys):]
if pools: layer['pools'] = pools
# Add calculated fields
# Also see similar section in `file_info` method.
try:
layer['location_cookie_list'] = \
layer['location_cookie'].split('_')
except KeyError: pass
else:
try:
layer['location_cookie_current'] = \
layer['location_cookie_list'][-1]
except IndexError: pass
return layer
@memoize
def fslayer4_bfid(self, source='filename'):
"""
Return the layer 4 value for BFID, or return :obj:`None` if
unavailable.
:type source: :obj:`str`
:arg source: ``filename`` or ``fsid``
:rtype: :obj:`str` or :obj:`None`
"""
return self.fslayer4(source).get('bfid')
@memoize
def has_fslayer(self, layer_num, source='filename'):
"""
Return a :obj:`bool` indicating whether the specified layer number is
available.
:type source: :obj:`str`
:arg source: ``filename`` or ``fsid``
:rtype: :obj:`bool`
"""
attr = 'fslayer{0}'.format(layer_num)
getter = getattr(self, attr, {})
return bool(getter(source))
@memoize_property
def fsid(self):
"""
Return the filesystem ID.
This is available for both files and directories.
:rtype: :obj:`str`
Example: ``00320000000000000001D6B0``
"""
# Re-raise cached exception if it exists
key = 'fsid'
try: raise self._cached_exceptions[key]
except KeyError: pass
# Read file
try:
return self._readfile(self.fsidname)
except Exception as e:
self._cached_exceptions[key] = e
raise
@memoize
def parentfsid(self, source):
"""
Return the parent's filesystem ID.
:type source: :obj:`str`
:arg source: ``filename`` or ``fsid``. It does not have a default value
to allow memoization to work correctly.
:rtype: :obj:`str`
This is available for both files and directories.
"""
# Re-raise cached exception if it exists
key = ('parentfsid', source)
try: raise self._cached_exceptions[key]
except KeyError: pass
# Read file
filename = self.parentfsidname(source)
try:
return self._readfile(filename)
except Exception as e:
self._cached_exceptions[key] = e
raise
@memoize_property
def lstat(self):
"""
Return :obj:`~os.lstat` info.
Sample::
posix.stat_result(st_mode=33188, st_ino=1275083688, st_dev=24L,
st_nlink=1, st_uid=13194, st_gid=1623,
st_size=8192000000, st_atime=1248570004,
st_mtime=1153410176, st_ctime=1153407484)
"""
return os.lstat(self.path)
@memoize_property
def is_recent(self):
"""Return a :obj:`bool` indicating whether the ``item`` was modified
within the past one day since the scan began."""
return (self.start_time - self.lstat.st_mtime) < 86400
@memoize_property
def is_nonrecent(self):
"""Return a :obj:`bool` indicating whether the ``item`` was modified
before the past one day since the scan began."""
return (not self.is_recent)
@memoize_property
def st_mode(self):
"""
Return the protection mode.
:rtype: :obj:`int`
"""
return self.lstat.st_mode
@memoize
def is_file(self):
"""
Return a :obj:`bool` indicating whether the ``item`` is a regular file.
Given that :obj:`~os.lstat` is used, this returns :obj:`False` for
symbolic links.
"""
return stat.S_ISREG(self.st_mode)
@memoize_property
def is_recent_file(self):
"""Return a :obj:`bool` indicating whether the ``item`` is a file that
was modified within the past one day since the scan began."""
return (self.is_file() and self.is_recent)
@memoize_property
def is_nonrecent_file(self):
"""Return a :obj:`bool` indicating whether the ``item`` is a file that
was modified before the past one day since the scan began."""
return (self.is_file() and self.is_nonrecent)
@memoize_property
def is_file_a_copy(self):
"""Return a :obj:`bool` indicating whether the ``item`` is a file that
is a copy."""
is_true = lambda v: v in ('yes', 'Yes', '1', 1, True)
is_true2 = lambda k: is_true(self.enstore_file_info.get(k))
return (self.is_file() and
(is_true2('is_multiple_copy') or is_true2('is_migrated_copy')))
@memoize_property
def is_file_bad(self):
"""Return a :obj:`bool` indicating whether the ``item`` is a file that
is marked bad."""
return (self.is_file() and
(self.path.startswith('.bad') or self.path.endswith('.bad')))
@memoize_property
def is_file_deleted(self):
"""Return a :obj:`bool` indicating whether the ``item`` is a deleted
file."""
return (self.is_file() and
(self.enstore_file_info.get('deleted')=='yes'))
@memoize_property
def is_file_empty(self):
"""Return a :obj:`bool` indicating whether the ``item`` is a file with
size 0."""
return (self.is_file() and (self.lstat.st_size==0))
@memoize
def is_dir(self):
"""
Return a :obj:`bool` indicating whether the ``item`` is a directory.
Given that :obj:`~os.lstat` is used, this returns :obj:`False` for
symbolic links.
"""
return stat.S_ISDIR(self.st_mode)
@memoize
def is_link(self):
"""
Return a :obj:`bool` indicating whether the ``item`` is a symbolic
link.
.. Given that :obj:`~os.lstat` is used, this returns :obj:`True` for
symbolic links.
"""
return stat.S_ISLNK(self.st_mode)
@memoize
def is_storage_path(self):
"""Return a :obj:`bool` indicating whether the ``item`` is a path in
the Enstore namespace."""
return bool(enstore_namespace.is_storage_path(self.path,
check_name_only=1))
# is_access_name_re = re.compile("\.\(access\)\([0-9A-Fa-f]+\)")
# @memoize
# def is_access_name(self):
# return bool(re.search(self.is_access_name_re, self.path_basename))
@memoize_property
def enstore_file_info(self):
"""
Return the available file info from the Enstore info client.
This is returned for the layer 1 BFID.
:rtype: :obj:`dict`
Sample::
{'storage_group': 'astro', 'uid': 0,
'pnfs_name0': '/pnfs/fs/usr/astro/fulla/fulla.gnedin.026.tar',
'library': 'CD-LTO4F1', 'package_id': None,
'complete_crc': 3741678891L, 'size': 8192000000L,
'external_label': 'VOO732', 'wrapper': 'cpio_odc',
'package_files_count': None, 'active_package_files_count': None,
'gid': 0, 'pnfsid': '00320000000000000001DF20',
'archive_mod_time': None, 'file_family_width': None,
'status': ('ok', None), 'deleted': 'no', 'archive_status': None,
'cache_mod_time': None, 'update': '2009-07-25 23:57:23.222394',
'file_family': 'astro',
'location_cookie': '0000_000000000_0000150',
'cache_location': None, 'original_library': None,
'bfid': 'CDMS124858424200000', 'tape_label': 'VOO732',
'sanity_cookie': (65536L, 1288913660L), 'cache_status': None,
'drive': 'stkenmvr211a:/dev/rmt/tps0d0n:1310051081',
'location_cookie_list': ['0000', '000000000', '0000150'],
'location_cookie_current': '0000150',
'complete_crc_1seeded': 2096135468L,}
Sample if BFID is :obj:`None`::
{'status': ('KEYERROR', 'info_server: key bfid is None'),
'bfid': None}
Sample if BFID is invalid::
{'status': ('WRONG FORMAT', 'info_server: bfid 12345 not valid'),
'bfid': '12345'}
"""
bfid = self.fslayer1_bfid()
file_info = self.enstore.info_client.bfid_info(bfid)
# Update status field as necessary
if isinstance(file_info, dict) and ('status' not in file_info):
file_info['status'] = (enstore_errors.OK, None)
# Note: enstore_errors.OK == 'ok'
# Add calculated fields
# Also see similar section in `fslayer4` method.
try:
file_info['location_cookie_list'] = \
file_info['location_cookie'].split('_')
except KeyError: pass
else:
try:
file_info['location_cookie_current'] = \
file_info['location_cookie_list'][-1]
except IndexError: pass
try:
crc, size = file_info['complete_crc'], file_info['size']
except KeyError: pass
else:
#file_info['complete_crc_0seeded'] = crc # not necessary
if (crc is not None) and (size is not None):
file_info['complete_crc_1seeded'] = \
enstore_checksum.convert_0_adler32_to_1_adler32(crc, size)
else:
file_info['complete_crc_1seeded'] = None
return file_info
@memoize_property
def is_enstore_file_info_ok(self):
"""Return a :obj:`bool` indicating whether Enstore file info is ok or
not."""
return bool(enstore_errors.is_ok(self.enstore_file_info))
@memoize_property
def enstore_volume_info(self):
"""
Return the available volume info from the Enstore info client.
If volume caching is enabled, volume info may be cached and may be
returned from cache if possible.
:rtype: :obj:`dict`
Sample (with no keys deleted)::
{'comment': ' ', 'declared': 1217546233.0, 'blocksize': 131072,
'sum_rd_access': 4, 'library': 'CD-LTO4F1',
'si_time': [1317155514.0, 1246553166.0], 'wrapper': 'cpio_odc',
'deleted_bytes': 77020524269L, 'user_inhibit': ['none', 'none'],
u'storage_group': 'ilc4c', 'system_inhibit': ['none', 'full'],
'external_label': 'VON077', 'deleted_files': 214,
'remaining_bytes': 598819328L, 'sum_mounts': 149,
'capacity_bytes': 858993459200L, 'media_type': 'LTO4',
'last_access': 1331879563.0, 'status': ('ok', None),
'eod_cookie': '0000_000000000_0001545', 'non_del_files': 1556,
'sum_wr_err': 0, 'unknown_files': 10, 'sum_wr_access': 1544,
'active_bytes': 746796833291L,
'volume_family': 'ilc4c.volatile.cpio_odc',
'unknown_bytes': 7112706371L, 'modification_time': 1246553159.0,
u'file_family': 'volatile', 'write_protected': 'y',
'sum_rd_err': 0, 'active_files': 1330,
'first_access': 1234948627.0}
Sample (with unneeded keys deleted)::
{'library': 'CD-LTO4F1', 'wrapper': 'cpio_odc',
'deleted_bytes': 0L, 'user_inhibit': ['none', 'none'],
u'storage_group': 'ilc4c', 'system_inhibit': ['none', 'full'],
'external_label': 'VON778', 'deleted_files': 0,
'media_type': 'LTO4', 'status': ('ok', None), 'unknown_files': 0,
'active_bytes': 818291877632L,
'volume_family': 'ilc4c.static.cpio_odc', 'unknown_bytes': 0L,
u'file_family': 'static', 'active_files': 411}
Sample if volume is :obj:`None`::
{'status': ('KEYERROR', 'info_server: key external_label is None'),
'work': 'inquire_vol', 'external_label': None}
Sample if volume is invalid::
{'status': ('WRONG FORMAT', 'info_server: bfid 12345 not valid'),
'bfid': '12345'}
"""
# Get volume name
volume = self.enstore_file_info.get('external_label')
if volume == '':
# This is done because self.enstore.info_client.inquire_vol('')
# hangs.
volume = None
# Conditionally try returning cached volume info
if self._cache_volume_info:
try: return self.volume_info_cache[volume]
except KeyError: volume_is_cacheable = True
else: volume_is_cacheable = False
# Get volume info from Enstore info client
volume_info = self.enstore.info_client.inquire_vol(volume)
if isinstance(volume_info, dict) and ('status' not in volume_info):
volume_info['status'] = (enstore_errors.OK, None)
# Note: enstore_errors.OK == 'ok'
# Add calculated volume info keys
try: volume_family = volume_info['volume_family']
except KeyError: pass
else:
calculated_keys = ('storage_group', 'file_family', 'wrapper')
# Note: 'wrapper' may very well already exist.
for k in calculated_keys:
if k not in volume_info:
getter = getattr(enstore_volume_family,
'extract_{0}'.format(k))
volume_info[k] = getter(volume_family)
# Conditionally process and cache volume info
if volume_is_cacheable and (volume not in self.volume_info_cache):
# Remove unneeded volume info keys, in order to reduce its memory
# usage. An alternate approach, possibly even a better one, is to
# use a whitelist instead of a blacklist.
unneeded_keys = (
'blocksize',
'capacity_bytes',
'comment',
'declared',
'eod_cookie',
'first_access',
'last_access',
'modification_time',
'non_del_files',
'remaining_bytes',
'si_time',
'sum_mounts',
'sum_rd_access',
'sum_rd_err',
'sum_wr_access',
'sum_wr_err',
'write_protected',
)
for k in unneeded_keys:
try: del volume_info[k]
except KeyError: pass
# Cache volume info
self.volume_info_cache[volume] = volume_info
return volume_info
@memoize_property
def is_enstore_volume_info_ok(self):
"""Return a :obj:`bool` indicating whether Enstore volume info is ok or
not."""
return bool(enstore_errors.is_ok(self.enstore_volume_info))
@memoize_property
def enstore_files_by_path(self):
"""
Return a :obj:`dict` containing information about the list of known
files in Enstore for the current path.
:rtype: :obj:`dict`
Sample::
{'status': ('ok', None),
'r_a': (('131.225.13.10', 59329), 21L,
'131.225.13.10-59329-1347478604.303243-2022-47708927252656'),
'pnfs_name0': '/pnfs/fs/usr/astro/idunn/rei256bin.015.tar',
'file_list':
[{'storage_group': 'astro', 'uid': 0,
'pnfs_name0': '/pnfs/fs/usr/astro/idunn/rei256bin.015.tar',
'library': 'shelf-CD-9940B', 'package_id': None,
'complete_crc': 2995796126L, 'size': 8192000000L,
'external_label': 'VO9502', 'wrapper': 'cpio_odc',
'package_files_count': None, 'active_package_files_count': None,
'gid': 0, 'pnfsid': '00320000000000000001CF38',
'archive_status': None, 'file_family_width': None,
'deleted': 'yes', 'archive_mod_time': None,
'cache_mod_time': None, 'update': '2009-09-27 15:57:10.011141',
'file_family': 'astro',
'location_cookie': '0000_000000000_0000020',
'cache_location': None,
'original_library': None, 'bfid': 'CDMS113926889300000',
'tape_label': 'VO9502', 'sanity_cookie': (65536L, 2312288512L),
'cache_status': None,
'drive': 'stkenmvr36a:/dev/rmt/tps0d0n:479000032467'},
{'storage_group': 'astro', 'uid': 0,
'pnfs_name0': '/pnfs/fs/usr/astro/idunn/rei256bin.015.tar',
'library': 'CD-LTO4F1', 'package_id': None,
'complete_crc': 2995796126L, 'size': 8192000000L,
'external_label': 'VOO732', 'wrapper': 'cpio_odc',
'package_files_count': None, 'active_package_files_count': None,
'gid': 0, 'pnfsid': '00320000000000000001CF38',
'archive_status': None, 'file_family_width': None,
'deleted': 'no', 'archive_mod_time': None,
'cache_mod_time': None, 'update': '2009-07-25 23:53:46.278724',
'file_family': 'astro',
'location_cookie': '0000_000000000_0000149',
'cache_location': None, 'original_library': None,
'bfid': 'CDMS124858402500000', 'tape_label': 'VOO732',
'sanity_cookie': (65536L, 2312288512L), 'cache_status': None,
'drive': 'stkenmvr211a:/dev/rmt/tps0d0n:1310051081'}]}
"""
return self.enstore.info_client.find_file_by_path(self.path)
@memoize_property
def is_enstore_files_by_path_ok(self):
"""Return a :obj:`bool` indicating whether the list of Enstore provided
files for the current path is ok or not."""
return bool(enstore_errors.is_ok(self.enstore_files_by_path))
@memoize_property
def enstore_files_list_by_path(self):
"""
If the :obj:`list` of Enstore provided files for the current path is
ok, return this :obj:`list`, otherwise an empty :obj:`list`.
:rtype: :obj:`list`
For a sample, see the value of the ``file_list`` key in the sample
noted for :attr:`enstore_files_by_path`.
"""
if self.is_enstore_files_by_path_ok:
enstore_files_by_path = self.enstore_files_by_path
try:
return enstore_files_by_path['file_list']
except KeyError:
return [enstore_files_by_path] # Unsure of correctness.
return []
@memoize_property
def _sfs(self):
"""Return the :class:`~enstore_namespace.StorageFS` instance for the
current path."""
return enstore_namespace.StorageFS(self.path)
@memoize_property
def sfs_pnfsid(self):
"""
Return the PNFS ID for the current file as provided by
:class:`~enstore_namespace.StorageFS`.
:rtype: :obj:`str`
"""
return self._sfs.get_id(self.path)
@memoize
def sfs_paths(self, filepath, pnfsid):
"""
Return the paths for the indicated file path and PNFS ID, as
provided by :class:`~enstore_namespace.StorageFS`.
:type filepath: :obj:`str`
:arg filepath: Absolute path of file, as provided by
:class:`~enstore_namespace.StorageFS`.
:type pnfsid: :obj:`str`
:arg pnfsid: PNFS ID of file, as provided by
:class:`~enstore_namespace.StorageFS`.
"""
try:
sfs_paths = self._sfs.get_path(id=pnfsid,
directory=os.path.dirname(filepath))
# Note: This was observed to _not_ work with a common StorageFS
# instance, which is why a file-specific instance is used. The `dir`
# argument was also observed to be required.
except (OSError, ValueError): # observed exceptions
sfs_paths = []
else:
sfs_paths = sorted(set(sfs_paths))
return sfs_paths
@memoize_property
def sizes(self):
"""
Return a :obj:`dict` containing all available file sizes for the
current file.
:rtype: :obj:`dict`
The available keys in the returned :obj:`dict` are ``lstat``,
``layer 2``, ``layer 4``, and ``Enstore``. Each value in the
:obj:`dict` is an :obj:`int` or is :obj:`None` if unavailable.
"""
return {'lstat': self.lstat.st_size,
'layer 2': self.fslayer2_property('length'),
'layer 4': self.fslayer4('filename').get('size'),
'Enstore': self.enstore_file_info.get('size'),
}
@memoize_property
def norm_paths(self):
"""
Return a :obj:`dict` containing all available paths for the current
file.
The paths are normalized to remove common mount locations such as
``/pnfs/fs/usr``, etc.
The available keys in the returned :obj:`dict` are ``filesystem``,
``layer 4``, and ``Enstore``. A value in the :obj:`dict` may be
:obj:`None` if unavailable.
"""
# Retrieve values
paths = {'filesystem': self.path,
'layer 4': self.fslayer4('filename').get('original_name'),
'Enstore': self.enstore_file_info.get('pnfs_name0'),
}
# Normalize values
variations = ('/pnfs/fnal.gov/usr/',
'/pnfs/fs/usr/',
'/pnfs/',
'/chimera/',
)
for path_key, path_val in paths.items():
if path_val:
for variation in variations:
if variation in path_val:
paths[path_key] = path_val.replace(variation,
'/<pnfs>/', 1)
# Note: The variation in question can occur anywhere
# in the path, and not just at the start of the path.
# str.startswith is not used for this reason.
break
return paths
class Notice(Exception):
"""Provide an :obj:`~exceptions.Exception` representing a single notice."""
_notices = {'Test': 'Testing "{test}".',} # Updated externally, specific
#--> # to current scanner.
@classmethod
def update_notices(cls, notices):
"""
Register the provided notices.
:type notices: :obj:`dict`
:arg notices: This is a :obj:`dict` containing notices to register. Its
keys are compact string identifiers. Its values are corresponding
string message templates. For example::
{'NoL1File': ('Cannot read layer 1 metadata file "{filename}".'
'{exception}'),}
In the above example, ``filename`` and ``exception`` represent
keyword arguments whose values will be used to :obj:`~str.format`
the message template.
"""
cls._notices.update(notices)
def __init__(self, key, **kwargs):
"""
Return an :obj:`~exceptions.Exception` containing a single notice for
the provided message arguments.
Before any instance is created, the :meth:`update_notices` classmethod
must have been called at least once.
:type key: :obj:`str`
:arg key: This refers to the identifying-type of the notice. It must
have been previously registered using the :meth:`update_notices`
classmethod.
:rtype: :class:`Notice`
Additionally provided keyword arguments are used to :obj:`~str.format`
the corresponding message template. This template must have been
previously provided together with the ``key`` using the
:meth:`update_notices` classmethod.
All arguments are also included in a :obj:`dict` representation of the
notice.
"""
self.key = key
self._kwargs = kwargs
#code = self.hashtext(self.key)
message_template = self._notices[self.key]
message = message_template.format(**self._kwargs).strip()
self._level = self.__class__.__name__.rpartition('Notice')[0].upper()
self._level = self._level or 'INFO'
message = '{0} ({1}): {2}'.format(self._level, self.key, message)
Exception.__init__(self, message)
@staticmethod
def hashtext(text):
"""
Return a four-hexadecimal-digit string hash of the provided text.
:type text: :obj:`str`
:arg text: Text to hash.
:rtype: :obj:`str`
"""
hash_ = hashlib.md5(text).hexdigest()[:4]
hash_ = '0x{0}'.format(hash_)
return hash_
@classmethod
def print_notice_templates(cls):
"""Print all notice templates."""
#notice_str = lambda k,v: '{0} ({1}): {2}'.format(cls.hashtext(k), k, v)
notice_str = lambda k, v: '{0}: {1}'.format(k, v)
notices = (notice_str(k,v) for k, v in
sorted(cls._notices.items()) if k!='Test')
for n in notices: print(n)
def __repr__(self):
"""
Return a string representation.
This string allows the class instance to be reconstructed in another
process.
"""
repr_ = '{0}({1}, **{2})'.format(self.__class__.__name__,
repr(self.key), repr(self._kwargs))
return repr_
def __eq__(self, other):
"""
Perform an equality comparison.
:type other: :class:`Notice`
:arg other: object to compare.
:rtype: :obj:`bool`
"""
return (str(self)==str(other) and self._level==other._level and
self.key==other.key and self._kwargs==other._kwargs)
def to_dict(self):
"""
Return a :obj:`dict` which describes the notice.
:rtype: :obj:`dict`
The returned :obj:`dict` can be used to reconstruct this
:class:`Notice` instance using the :meth:`from_dict` method.
"""
return {self.key: {'level': self._level,
'args': self._kwargs},
}
def to_exportable_dict(self):
"""
Return an exportable :obj:`dict` which describes the notice.
:rtype: :obj:`dict`
The returned :obj:`dict` cannot be used to reconstruct this
:class:`Notice` instance using the :meth:`from_dict` method.
"""
def flatten_dict(d):
"""
Return a flattened version of a dict.
This is based on http://stackoverflow.com/a/13781829/832230. Keys
are also converted to lowercase, and spaces in a key are removed.
"""
sep='_'
final = {}
def _flatten_dict(obj, parent_keys=[]):
for k, v in obj.iteritems():
k = k.lower().replace(' ', '')
if isinstance(v, dict):
_flatten_dict(v, parent_keys + [k])
else:
key = sep.join(parent_keys + [k])
final[key] = v
_flatten_dict(d)
return final
return {self.key: {'level': self._level,
'args': flatten_dict(self._kwargs)},
}
@staticmethod
def from_dict(notice):
"""
Return a :class:`Notice` instance constructed from the provided
:obj:`dict`.
:type notice: :obj:`dict`
:arg notice: This is the object from which to construct a
:class:`Notice`. It must have the same structure as is returned by
:meth:`to_dict`.
:rtype: :class:`Notice`
"""
nkey, notice = notice.items()[0]
nlevel = notice['level'].title()
nclass_name = '{0}Notice'.format(nlevel)
nclass = globals()[nclass_name]
return nclass(nkey, **notice['args'])
def to_json(self, indent=None):
"""
Return a sorted JSON representation of the :obj:`dict` describing the
notice.
:type indent: :obj:`None` or :obj:`int` (non-negative)
:arg indent: See :py:func:`json.dumps`.
:rtype: :obj:`str`
"""
return json.dumps(self.to_dict(), sort_keys=True, indent=indent)
@classmethod
def from_json(cls, notice):
"""
Return a :class:`Notice` instance constructed from the provided JSON
string.
:type notice: :obj:`str`
:arg notice: This is the object from which to construct a
:class:`Notice`. It must have the same structure as is returned by
:meth:`to_json`.
:rtype: :class:`Notice`
.. note:: This method can be used only with Python 2.7 or higher. It
may raise the following :obj:`~exceptions.Exception` with Python
2.6::
TypeError: __init__() keywords must be strings
"""
return cls.from_dict(json.loads(notice))
class TestNotice(Notice):
"""Test notice."""
pass
class InfoNotice(Notice):
"""Informational notice."""
pass
class WarningNotice(Notice):
"""Warning notice."""
pass
class ErrorNotice(Notice):
"""Error notice."""
pass
class CriticalNotice(Notice):
"""Critical error notice."""
pass
class NoticeGrp(object):
"""Provide a container for :class:`Notice` objects."""
def __init__(self, item_path, notices=None):
"""
Return an object that is a group of :class:`Notice` objects for the
specified item path and notices.
:type item_path: :obj:`str`
:arg item_path: absolute filesystem path of the item.
:type notices: :obj:`~collections.Sequence` or :obj:`None`
:arg notices: This can be a :obj:`~collections.Sequence` of
:class:`Notice` objects that are added to the group. If multiple
:class:`Notice` objects exist in the sequence with the same ``key``
attribute, only the last such :class:`Notice` will be stored.
"""
self.item = item_path
self.notices = dict()
if notices:
for notice in notices: self.add_notice(notice)
def __repr__(self):
"""
Return a string representation.
This string allows the class instance to be reconstructed in another
process.
"""
repr_ = '{0}({1}, {2})'.format(self.__class__.__name__,
repr(self.item), repr(self.notices))
return repr_.decode()
def add_notice(self, notice):
"""
Add the provided :class:`Notice`.
If a :class:`Notice` already exists with the same ``key`` attribute, it
will be overwritten.
"""
self.notices[notice.key] = notice
def __eq__(self, other):
"""
Perform an equality comparison.
:type other: :class:`NoticeGrp`
:arg other: object to compare.
:rtype: :obj:`bool`
"""
return (self.item==other.item and self.notices==other.notices)
def __nonzero__(self):
"""
Return :obj:`True` if one or more notices exist in the group, otherwise
return :obj:`False`.
:rtype: :obj:`bool`
"""
return bool(self.notices)
def __str__(self):
"""
Return a multiline string representation of the notice group.
Example::
/pnfs/fs/usr/mydir1/myfile1
ERROR (ErrType1): This is error 1.
WARNING (WarnType1): This is warning 1.
"""
notices_strs = (str(n) for n in self.notices.values())
return '{0}\n{1}'.format(self.item, '\n'.join(notices_strs))
def to_dict(self):
"""
Return a :obj:`dict` which describes the notice group.
:rtype: :obj:`dict`
The returned :obj:`dict` can be used to reconstruct this
:class:`NoticeGrp` instance using the :meth:`from_dict` method.
"""
return {'path': self.item,
'notices': dict(v.to_dict().items()[0] for v in
self.notices.values()),
}
def to_exportable_dict(self):
"""
Return an exportable :obj:`dict` which describes the notice group.
:rtype: :obj:`dict`
The returned :obj:`dict` cannot be used to reconstruct this
:class:`NoticeGrp` instance using the :meth:`from_dict` method.
"""
return {'path': self.item,
'notices': dict(v.to_exportable_dict().items()[0] for v in
self.notices.values()),
}
@classmethod
def from_dict(cls, noticegrp):
"""
Return a :class:`NoticeGrp` instance constructed from the provided
:obj:`dict`.
:type notice: :obj:`dict`
:arg notice: This is the object from which to construct a
:class:`NoticeGrp`. It must have the same structure as is returned
by :meth:`to_dict`.
:rtype: :class:`NoticeGrp`
"""
notices = noticegrp['notices'].items()
notices = (Notice.from_dict({k:v}) for k,v in notices)
return cls(noticegrp['path'], notices)
def to_json(self, indent=None):
"""
Return a sorted JSON representation of the :obj:`dict` describing the
notice group.
:type indent: :obj:`None` or :obj:`int` (non-negative)
:arg indent: See :py:func:`json.dumps`.
:rtype: :obj:`str`
"""
return json.dumps(self.to_dict(), sort_keys=True,
indent=indent)
class ScanInterface:
"""
This class is referenced and initialized by the :mod:`enstore` module.
While this class is intended by the :mod:`enstore` module to perform
command-line option parsing using the :class:`option.Interface` base class,
it does not do so. Instead, the command-line option parsing for this module
is performed by the :class:`CommandLineOptionsParser` class which is called
independently. As such, this :class:`ScanInterface` class intentionally
does not inherit the :class:`option.Interface` class.
"""
def __init__(self, *args, **kwargs):
"""
Initialize the interface.
No input arguments are used.
"""
pass
def do_work(*args, **kwargs):
"""
Perform a scan as specified on the command line, using the options
described within the :meth:`CommandLineOptionsParser._add_options` method.
"""
# Parse command line options
options = CommandLineOptionsParser().options
#options = {'scan_type': 'forward'} # These options are minimally required.
settings.update(options) # Merge provided options.
# Select scanner
scanners = {'forward': ScannerForward}
scan_type = settings['scan_type']
try: scanner = scanners[scan_type]
except KeyError:
msg = ('Error: "{0}" scan is not implemented. Select from: {1}'
).format(scan_type, ', '.join(scanners))
exit(msg)
# Perform specified action
if settings.get('print') == 'checks':
scanner.print_checks()
elif settings.get('print') == 'notices':
Notice.update_notices(scanner.notices)
Notice.print_notice_templates()
else:
scanner().run()
if __name__ == '__main__':
do_work()
| nilq/baby-python | python |
# SPDX-FileCopyrightText: 2019-2021 REFITT Team
# SPDX-License-Identifier: Apache-2.0
"""Integration tests for forecast interface."""
# type annotations
# standard libs
# external libs
import pytest
# internal libs
from refitt.data.forecast import Forecast
from refitt.database.model import Observation as ObservationModel, Model
from tests.unit.test_forecast import generate_random_forecast
class TestForecastPublish:
"""Tests for database integration with forecast interface."""
def test_publish(self) -> None:
"""Verify roundtrip with database."""
data = generate_random_forecast()
num_forecasts = Model.count()
num_observations = ObservationModel.count()
model = Forecast.from_dict(data).publish()
assert Model.count() == num_forecasts + 1
assert ObservationModel.count() == num_observations + 1
assert model.to_dict() == Model.from_id(model.id).to_dict()
Model.delete(model.id)
ObservationModel.delete(model.observation_id)
assert Model.count() == num_forecasts
assert ObservationModel.count() == num_observations
with pytest.raises(Model.NotFound):
Model.from_id(model.id)
with pytest.raises(ObservationModel.NotFound):
ObservationModel.from_id(model.observation_id)
| nilq/baby-python | python |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request,'home.html',{'name':'Smit'})
def add(request):
val1 = request.POST['num1']
val2 = request.POST['num2']
return render(request,'result.html',{'result_add':int(val1)+int(val2)}) | nilq/baby-python | python |
# coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import json
import tensorflow as tf
from utils import queuer
def decoding(sprobs, samples, params, mask=None):
"""Generate decoded sequence from seqs"""
if mask is None:
mask = [1.] * len(sprobs)
flat_sprobs = []
for _sprobs, _m in zip(sprobs, mask):
if _m < 1.: continue
for start_prob in _sprobs:
flat_sprobs.append(start_prob)
assert len(flat_sprobs) == len(samples), 'Decoding length mismatch!'
results = []
for (idx, sample), pred in zip(samples, flat_sprobs):
gold_label = sample[0]
pred_label = pred
results.append({
'pred_answer': int(pred_label),
'sample_id': idx,
'gold_answer': gold_label
})
return results
def predict(session, features,
out_pred, dataset, params, train=True):
"""Performing decoding with exising information"""
results = []
batcher = dataset.batcher(params.eval_batch_size,
buffer_size=params.buffer_size,
shuffle=False, train=train)
eval_queue = queuer.EnQueuer(batcher,
multiprocessing=params.data_multiprocessing,
random_seed=params.random_seed)
eval_queue.start(workers=params.nthreads,
max_queue_size=params.max_queue_size)
def _predict_one_batch(data_on_gpu):
feed_dicts = {}
flat_raw_data = []
for fidx, data in enumerate(data_on_gpu):
# define feed_dict
feed_dict = {
features[fidx]["p"]: data['p_token_ids'],
features[fidx]["h"]: data['h_token_ids'],
features[fidx]["l"]: data['l_id'],
}
if params.use_char:
feed_dict[features[fidx]["pc"]] = data['p_char_ids']
feed_dict[features[fidx]["hc"]] = data['h_char_ids']
if params.enable_bert:
feed_dict[features[fidx]["ps"]] = data['p_subword_ids']
feed_dict[features[fidx]["hs"]] = data['h_subword_ids']
feed_dict[features[fidx]["pb"]] = data['p_subword_back']
feed_dict[features[fidx]["hb"]] = data['h_subword_back']
feed_dicts.update(feed_dict)
flat_raw_data.extend(data['raw'])
# pick up valid outputs
data_size = len(data_on_gpu)
valid_out_pred = out_pred[:data_size]
decode_spred = session.run(
valid_out_pred, feed_dict=feed_dicts)
predictions = decoding(
decode_spred, flat_raw_data, params
)
return predictions
very_begin_time = time.time()
data_on_gpu = []
for bidx, data in enumerate(eval_queue.get()):
data_on_gpu.append(data)
# use multiple gpus, and data samples is not enough
if len(params.gpus) > 0 and len(data_on_gpu) < len(params.gpus):
continue
start_time = time.time()
predictions = _predict_one_batch(data_on_gpu)
data_on_gpu = []
results.extend(predictions)
tf.logging.info(
"Decoding Batch {} using {:.3f} s, translating {} "
"sentences using {:.3f} s in total".format(
bidx, time.time() - start_time,
len(results), time.time() - very_begin_time
)
)
eval_queue.stop()
if len(data_on_gpu) > 0:
start_time = time.time()
predictions = _predict_one_batch(data_on_gpu)
results.extend(predictions)
tf.logging.info(
"Decoding Batch {} using {:.3f} s, translating {} "
"sentences using {:.3f} s in total".format(
'final', time.time() - start_time,
len(results), time.time() - very_begin_time
)
)
return results
def eval_metric(results, params):
"""BLEU Evaluate """
crr_cnt, total_cnt = 0, 0
for result in results:
total_cnt += 1
p = result['pred_answer']
g = result['gold_answer']
if p == g:
crr_cnt += 1
return crr_cnt * 100. / total_cnt
def dump_predictions(results, output):
"""save translation"""
with tf.gfile.Open(output, 'w') as writer:
for sample in results:
writer.write(json.dumps(sample) + "\n")
tf.logging.info("Saving translations into {}".format(output))
| nilq/baby-python | python |
# --------------------------------------------------------------------------- #
# aionextid.py #
# #
# Copyright © 2015-2022, Rajiv Bakulesh Shah, original author. #
# #
# 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. #
# --------------------------------------------------------------------------- #
'Asynchronous distributed Redis-powered monotonically increasing ID generator.'
# TODO: Remove the following import after deferred evaluation of annotations
# because the default.
# 1. https://docs.python.org/3/whatsnew/3.7.html#whatsnew37-pep563
# 2. https://www.python.org/dev/peps/pep-0563/
# 3. https://www.python.org/dev/peps/pep-0649/
from __future__ import annotations
import asyncio
import contextlib
from typing import ClassVar
from typing import Iterable
from redis import RedisError
from redis.asyncio import Redis as AIORedis # type: ignore
from .base import AIOPrimitive
from .base import logger
from .exceptions import QuorumNotAchieved
from .nextid import NextID
from .nextid import Scripts
class AIONextID(Scripts, AIOPrimitive):
'Async distributed Redis-powered monotonically increasing ID generator.'
__slots__ = ('num_tries',)
_KEY_PREFIX: ClassVar[str] = NextID._KEY_PREFIX
def __init__(self, # type: ignore
*,
key: str = 'current',
masters: Iterable[AIORedis] = frozenset(),
num_tries: int = NextID._NUM_TRIES,
) -> None:
'Initialize an AIONextID ID generator.'
super().__init__(key=key, masters=masters)
self.num_tries = num_tries
def __aiter__(self) -> AIONextID:
return self # pragma: no cover
async def __anext__(self) -> int:
for _ in range(self.num_tries):
with contextlib.suppress(QuorumNotAchieved):
next_id = await self.__get_current_ids() + 1
await self.__set_current_ids(next_id)
return next_id
raise QuorumNotAchieved(self.key, self.masters)
async def __get_current_id(self, master: AIORedis) -> int: # type: ignore
current_id: int = await master.get(self.key)
return current_id
async def __set_current_id(self, master: AIORedis, value: int) -> bool: # type: ignore
current_id: int | None = await self._set_id_script( # type: ignore
keys=(self.key,),
args=(value,),
client=master,
)
return current_id == value
async def __reset_current_id(self, master: AIORedis) -> int: # type: ignore
await master.delete(self.key)
async def __get_current_ids(self) -> int:
current_ids, redis_errors = [], []
coros = [self.__get_current_id(master) for master in self.masters]
for coro in asyncio.as_completed(coros): # type: ignore
try:
current_id = int(await coro or b'0')
except RedisError as error:
redis_errors.append(error)
logger.exception(
'%s.__get_current_ids() caught %s',
self.__class__.__qualname__,
error.__class__.__qualname__,
)
else:
current_ids.append(current_id)
if len(current_ids) > len(self.masters) // 2:
return max(current_ids)
raise QuorumNotAchieved(
self.key,
self.masters,
redis_errors=redis_errors,
)
async def __set_current_ids(self, value: int) -> None:
num_masters_set, redis_errors = 0, []
coros = [self.__set_current_id(master, value) for master in self.masters]
for coro in asyncio.as_completed(coros):
try:
num_masters_set += await coro
except RedisError as error:
redis_errors.append(error)
logger.exception(
'%s.__set_current_ids() caught %s',
self.__class__.__qualname__,
error.__class__.__qualname__,
)
if num_masters_set > len(self.masters) // 2:
return
raise QuorumNotAchieved(
self.key,
self.masters,
redis_errors=redis_errors,
)
async def reset(self) -> None:
num_masters_reset, redis_errors = 0, []
coros = [self.__reset_current_id(master) for master in self.masters]
for coro in asyncio.as_completed(coros):
try:
await coro
except RedisError as error:
redis_errors.append(error)
logger.exception(
'%s.reset() caught %s',
self.__class__.__qualname__,
error.__class__.__qualname__,
)
else:
num_masters_reset += 1
if num_masters_reset > len(self.masters) // 2:
return
raise QuorumNotAchieved(
self.key,
self.masters,
redis_errors=redis_errors,
)
def __repr__(self) -> str:
return f'<{self.__class__.__qualname__} key={self.key}>'
| nilq/baby-python | python |
import os
import sys
import logging
import re
from django.core.exceptions import ImproperlyConfigured
from pathlib import Path # python3 only
logger = logging.getLogger(__name__)
def dotenv_values(dotenv_path):
lines = []
try:
with open(dotenv_path) as fp:
lines = fp.read().splitlines()
except FileNotFoundError as e:
if sys.argv[1] == 'test':
logger.warning(
f'No dotenv file found using dotenv_path:{dotenv_path}'
)
return {}
else:
raise e
# get tuples of values,property splitting each line of the file
lines = map(lambda l: tuple(re.split(r'\s*=\s*', l, 1)), filter(
None, lines
))
lines = list(lines)
print(f"dotenv_values: found {len(lines)} valid lines")
if not lines:
return dict()
return dict(lines)
def get_env_variable(var_name, default=None):
if var_name in dotenv_dict:
return dotenv_dict[var_name]
try:
return os.environ[var_name]
except KeyError:
if default:
return default
error_msg = "Set the %s environment variable" % var_name
raise ImproperlyConfigured(error_msg)
# e.g. set ENV=production to get .production.env file
dotenv_filename = '.{0}.env'.format(
os.environ.get('ENV', '')
) if 'ENV' in os.environ else '.env'
dotenv_path = str(Path('.') / dotenv_filename)
dotenv_dict = dotenv_values(dotenv_path=dotenv_path)
print('loading env file: {0}'.format(dotenv_filename))
| nilq/baby-python | python |
"""
Tools for asking the ESP about any alarms that have been raised,
and telling the user about them if so.
The top alarmbar shows little QPushButtons for each alarm that is currently active.
If the user clicks a button, they are shown the message text and a "snooze" button
for that alarm.
There is a single physical snooze button which is manipulated based on which alarm
the user has selected.
"""
import sys
from communication import rpi
from PyQt5 import QtCore, QtWidgets
BITMAP = {1 << x: x for x in range(32)}
ERROR = 0
WARNING = 1
class SnoozeButton:
"""
Takes care of snoozing alarms.
Class members:
- _esp32: ESP32Serial object for communication
- _alarm_h: AlarmHandler
- _alarmsnooze: QPushButton that user will press
- _code: The alarm code that the user is currently dealing with
- _mode: Whether the current alarm is an ERROR or a WARNING
"""
def __init__(self, esp32, alarm_h, alarmsnooze):
"""
Constructor
Arguments: see relevant class members
"""
self._esp32 = esp32
self._alarm_h = alarm_h
self._alarmsnooze = alarmsnooze
self._alarmsnooze.hide()
self._code = None
self._mode = None
self._alarmsnooze.clicked.connect(self._on_click_snooze)
self._alarmsnooze.setStyleSheet(
'background-color: rgb(0,0,205); color: white; font-weight: bold;')
self._alarmsnooze.setMaximumWidth(150)
def set_code(self, code):
"""
Sets the alarm code
Arguments:
- code: Integer alarm code
"""
self._code = code
self._alarmsnooze.setText('Snooze %s' % str(BITMAP[self._code]))
def set_mode(self, mode):
"""
Sets the mode.
Arguments:
- mode: ALARM or WARNING
"""
self._mode = mode
def show(self):
"""
Shows the snooze alarm button
"""
self._alarmsnooze.show()
def _on_click_snooze(self):
"""
The callback function called when the alarm snooze button is clicked.
"""
if self._mode not in [WARNING, ERROR]:
raise Exception('mode must be alarm or warning.')
# Reset the alarms/warnings in the ESP
# If the ESP connection fails at this
# time, raise an error box
if self._mode == ERROR:
self._esp32.snooze_hw_alarm(self._code)
self._alarm_h.snooze_alarm(self._code)
else:
self._esp32.reset_warnings()
self._alarm_h.snooze_warning(self._code)
class AlarmButton(QtWidgets.QPushButton):
"""
The alarm and warning buttons shown in the top alarmbar.
Class members:
- _mode: Whether this alarm is an ERROR or a WARNING
- _code: The integer code for this alarm.
- _errstr: Test describing this alarm.
- _label: The QLabel to populate with the error message, if the user
clicks our button.
- _snooze_btn: The SnoozeButton to manipulate if the user clicks our
button.
"""
def __init__(self, mode, code, errstr, label, snooze_btn):
super(AlarmButton, self).__init__()
self._mode = mode
self._code = code
self._errstr = errstr
self._label = label
self._snooze_btn = snooze_btn
self.clicked.connect(self._on_click_event)
if self._mode == ERROR:
self._bkg_color = 'red'
elif self._mode == WARNING:
self._bkg_color = 'orange'
else:
raise Exception('Option %s not supported' % self._mode)
self.setText(str(BITMAP[self._code]))
style = """background-color: %s;
color: white;
border: 0.5px solid white;
font-weight: bold;
""" % self._bkg_color
self.setStyleSheet(style)
self.setMaximumWidth(35)
self.setMaximumHeight(30)
def _on_click_event(self):
"""
The callback function called when the user clicks on an alarm button
"""
# Set the label showing the alarm name
style = """QLabel {
background-color: %s;
color: white;
font-weight: bold;
}""" % self._bkg_color
self._label.setStyleSheet(style)
self._label.setText(self._errstr)
self._label.show()
self._activate_snooze_btn()
def _activate_snooze_btn(self):
"""
Activates the snooze button that will silence this alarm
"""
self._snooze_btn.set_mode(self._mode)
self._snooze_btn.set_code(self._code)
self._snooze_btn.show()
class AlarmHandler:
"""
This class starts a QTimer dedicated to checking is there are any errors
or warnings coming from ESP32
Class members:
- _esp32: ESP32Serial object for communication
- _alarm_time: Timer that will periodically ask the ESP about any alarms
- _err_buttons: {int: AlarmButton} for any active ERROR alarms
- _war_buttons: {int: AlarmButton} for any active WARNING alarms
- _alarmlabel: QLabel showing text of the currently-selected alarm
- _alarmstack: Stack of QPushButtons for active alarms
- _alarmsnooze: QPushButton for snoozing an alarm
- _snooze_btn: SnoozeButton that manipulates _alarmsnooze
"""
def __init__(self, config, esp32, alarmbar, hwfail_func):
"""
Constructor
Arguments: see relevant class members.
"""
self._esp32 = esp32
self._alarm_timer = QtCore.QTimer()
self._alarm_timer.timeout.connect(self.handle_alarms)
self._alarm_timer.start(config["alarminterval"] * 1000)
self._err_buttons = {}
self._war_buttons = {}
self._hwfail_func = hwfail_func
self._hwfail_codes = [1 << code for code in config['hwfail_codes']]
self._alarmlabel = alarmbar.findChild(QtWidgets.QLabel, "alarmlabel")
self._alarmstack = alarmbar.findChild(QtWidgets.QHBoxLayout, "alarmstack")
self._alarmsnooze = alarmbar.findChild(QtWidgets.QPushButton, "alarmsnooze")
self._snooze_btn = SnoozeButton(self._esp32, self, self._alarmsnooze)
def handle_alarms(self):
"""
The callback method which is called periodically to check if the ESP raised any
alarm or warning.
"""
# Retrieve alarms and warnings from the ESP
esp32alarm = self._esp32.get_alarms()
esp32warning = self._esp32.get_warnings()
#
# ALARMS
#
if esp32alarm:
errors = esp32alarm.strerror_all()
alarm_codes = esp32alarm.get_alarm_codes()
for alarm_code, err_str in zip(alarm_codes, errors):
if alarm_code in self._hwfail_codes:
self._hwfail_func(err_str)
print("Critical harware failure")
if alarm_code not in self._err_buttons:
btn = AlarmButton(ERROR, alarm_code, err_str,
self._alarmlabel, self._snooze_btn)
self._alarmstack.addWidget(btn)
self._err_buttons[alarm_code] = btn
#
# WARNINGS
#
if esp32warning:
errors = esp32warning.strerror_all()
warning_codes = esp32warning.get_alarm_codes()
for warning_code, err_str in zip(warning_codes, errors):
if warning_code not in self._war_buttons:
btn = AlarmButton(
WARNING, warning_code, err_str, self._alarmlabel, self._snooze_btn)
self._alarmstack.addWidget(btn)
self._war_buttons[warning_code] = btn
def snooze_alarm(self, code):
"""
Graphically snoozes alarm corresponding to 'code'
Arguments:
- code: integer alarm code
"""
if code not in self._err_buttons:
raise Exception('Cannot snooze code %s as alarm button doesn\'t exist.' % code)
self._err_buttons[code].deleteLater()
del self._err_buttons[code]
self._alarmlabel.setText('')
self._alarmlabel.setStyleSheet('QLabel { background-color: black; }')
self._alarmsnooze.hide()
def snooze_warning(self, code):
"""
Graphically snoozes warning corresponding to 'code'
Arguments:
- code: integer alarm code
"""
if code not in self._war_buttons:
raise Exception('Cannot snooze code %s as warning button doesn\'t exist.' % code)
self._war_buttons[code].deleteLater()
del self._war_buttons[code]
self._alarmlabel.setText('')
self._alarmlabel.setStyleSheet('QLabel { background-color: black; }')
self._alarmsnooze.hide()
class CriticalAlarmHandler:
"""
Handles severe communication and hardware malfunction errors.
These errors have a low chance of recovery, but this class handles irrecoverable as well as
potentially recoverable errors (with options to retry).
"""
def __init__(self, mainparent, esp32):
"""
Main constructor. Grabs necessary widgets from the main window
Arguments:
- mainparent: Reference to the mainwindow widget.
- esp32: Reference to the ESP32 interface.
"""
self._esp32 = esp32
self._toppane = mainparent.toppane
self._criticalerrorpage = mainparent.criticalerrorpage
self._bottombar = mainparent.bottombar
self._criticalerrorbar = mainparent.criticalerrorbar
self._mainparent = mainparent
self.nretry = 0
self._label_criticalerror = mainparent.findChild(QtWidgets.QLabel, "label_criticalerror")
self._label_criticaldetails = mainparent.findChild(
QtWidgets.QLabel,
"label_criticaldetails")
self._button_retrycmd = mainparent.findChild(QtWidgets.QPushButton, "button_retrycmd")
def show_critical_error(self, text, details=""):
"""
Shows the critical error in the mainwindow.
This includes changing the screen to red and displaying a big message to this effect.
"""
self._label_criticalerror.setText(text)
self._toppane.setCurrentWidget(self._criticalerrorpage)
self._bottombar.setCurrentWidget(self._criticalerrorbar)
self._label_criticaldetails.setText(details)
rpi.start_alarm_system()
self._mainparent.repaint()
input("Hang on wait reboot")
def call_system_failure(self, details=""):
"""
Calls a system failure and sets the mainwindow into a state that is irrecoverable without
maintenance support.
"""
self._button_retrycmd.hide()
disp_msg = "*** SYSTEM FAILURE ***\nCall the Maintenance Service"
details = str(details).replace("\n", "")
self.show_critical_error(disp_msg, details=details)
| nilq/baby-python | python |
"""
atpthings.util.dictionary
-------------------------
"""
def getKeys(dictionary: dict, keys: list) -> dict:
"""Get keys from dictionary.
Parameters
----------
dictionary : dict
Dictionary.
keys : list
List of keys wonted to be extracted.
Returns
-------
dict
Dictionry wit only specificated keys.
Examples
--------
>>> dict1 = {"one": 1, "two": 1,"three": 1}
>>> keysList = ["one", "three"]
>>> dict2 = atpthings.util.dictionary.getKeys(dict1,keysList)
>>> {"one": 1,"three": 1}
"""
return {key: dictionary[key] for key in dictionary.keys() & keys}
| nilq/baby-python | python |
import wx
from html import escape
import sys
import Model
import Utils
class Commentary( wx.Panel ):
def __init__( self, parent, id = wx.ID_ANY ):
super().__init__(parent, id, style=wx.BORDER_SUNKEN)
self.SetDoubleBuffered(True)
self.SetBackgroundColour( wx.WHITE )
self.hbs = wx.BoxSizer(wx.HORIZONTAL)
self.text = wx.TextCtrl( self, style=wx.TE_MULTILINE|wx.TE_READONLY )
self.hbs.Add( self.text, 1, wx.EXPAND )
self.SetSizer( self.hbs )
def getText( self ):
race = Model.race
riderInfo = {info.bib:info for info in race.riderInfo} if race else {}
def infoLinesSprint( sprint, bibs ):
lines = []
pfpText = ''
for place_in, bib in enumerate(bibs,1):
ri = riderInfo.get( bib, None )
points, place, tie = race.getSprintPoints( sprint, place_in, bibs )
if points:
pfpText = ' ({:+d} pts)'.format(points)
else:
pfpText = ''
if ri is not None:
lines.append( ' {}.{} {}: {} {}, {}'.format(place, pfpText, bib, ri.first_name, ri.last_name, ri.team) )
else:
lines.append( ' {}.{} {}'.format(place, pfpText, bib) )
return lines
def infoLines( bibs, pointsForPlace=None ):
lines = []
pfpText = ''
for place_in, bib in enumerate(bibs,1):
ri = riderInfo.get( bib, None )
points, place = pointsForPlace, place_in
if points:
pfpText = ' ({:+d} pts)'.format(points)
else:
pfpText = ''
if ri is not None:
lines.append( ' {}.{} {}: {} {}, {}'.format(place, pfpText, bib, ri.first_name, ri.last_name, ri.team) )
else:
lines.append( ' {}.{} {}'.format(place, pfpText, bib) )
return lines
RaceEvent = Model.RaceEvent
lines = []
self.sprintCount = 0
for e in race.events:
if e.eventType == RaceEvent.Sprint:
self.sprintCount += 1
lines.append( 'Sprint {} Result:'.format(self.sprintCount) )
lines.extend( infoLinesSprint(self.sprintCount, e.bibs[:len(race.pointsForPlace)]) )
elif e.eventType == RaceEvent.LapUp:
lines.append( 'Gained a Lap:' )
lines.extend( infoLines(e.bibs, race.pointsForLapping) )
elif e.eventType == RaceEvent.LapDown:
lines.append( 'Lost a Lap:' )
lines.extend( infoLines(e.bibs, -race.pointsForLapping) )
elif e.eventType == RaceEvent.Finish:
lines.append( 'Finish:' )
self.sprintCount += 1
lines.extend( infoLinesSprint(self.sprintCount, e.bibs) )
elif e.eventType == RaceEvent.DNF:
lines.append( 'DNF (Did Not Finish):' )
lines.extend( infoLines(e.bibs) )
elif e.eventType == RaceEvent.DNS:
lines.append( 'DNS (Did Not Start):' )
lines.extend( infoLines(e.bibs) )
elif e.eventType == RaceEvent.PUL:
lines.append( 'PUL (Pulled by Race Officials):' )
lines.extend( infoLines(e.bibs) )
elif e.eventType == RaceEvent.DSQ:
lines.append( 'DSQ (Disqualified)' )
lines.extend( infoLines(e.bibs) )
lines.append( '' )
return '\n'.join(lines)
def toHtml( self, html ):
text = self.getText().replace('.', '')
if not text:
return ''
lines = []
inList = False
html.write( '<dl>' )
for line in text.split('\n'):
if not line:
continue
if line[:1] != ' ':
if inList:
html.write('</ol>\n')
html.write('</dd>\n')
inList = False
html.write( '<dd>\n' )
html.write( escape(line) )
html.write( '<ol>' )
inList = True
continue
line = line.strip()
html.write( '<li>{}</li>\n'.format(line.split(' ',1)[1].strip()) )
html.write('</ol>\n')
html.write('</dd>\n')
html.write('</dl>\n')
def refresh( self ):
self.text.Clear()
self.text.AppendText( self.getText() )
def commit( self ):
pass
if __name__ == '__main__':
app = wx.App( False )
mainWin = wx.Frame(None,title="Commentary", size=(600,400))
Model.newRace()
Model.race._populate()
rd = Commentary(mainWin)
rd.refresh()
rd.toHtml( sys.stdout )
mainWin.Show()
app.MainLoop()
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^(?P<username>[\w.@+-]+)/$', views.UserDetailView.as_view(), name='detail'),
]
| nilq/baby-python | python |
import torch
import numpy as np
from torch import nn
import torch.nn.functional as F
from . import *
class GlowLevel(nn.Module):
def __init__(self, in_channel, filters=512, n_levels=1, n_steps=2):
'''
Iniitialized Glow Layer
Parameters
----------
in_channel : int
number of input channels
filters : int
number of filters in affine coupling layer
n_levels : int
number of Glow layers
n_steps : int
number of flow steps
'''
super(GlowLevel, self).__init__()
# init flow layers
self.flowsteps = nn.ModuleList([Flow(in_channel*4, filters = filters)
for _ in range(n_steps)])
# init Glow levels
if(n_levels > 1):
self.nextLevel = GlowLevel(in_channel = in_channel * 2,
filters = filters,
n_levels = n_levels-1,
n_steps = n_steps)
else:
self.nextLevel = None
def forward(self, x, direction = 0):
'''
forward function for each glow level
Parameters
----------
x : torch.tensor
input batch
direction : int
0 means forward
1 means reverse
Returns
-------
x : torch.tensor
output of the glow layer
logdet : float
the log-determinant term
'''
sum_logdet = 0
x = self.squeeze(x)
if not direction: # direction is forward
for flowStep in self.flowsteps:
x, log_det = flowStep(x, direction=direction)
sum_logdet += log_det
if self.nextLevel is not None:
x, x_split = x.chunk(2, 1)
x, log_det = self.nextLevel(x, direction)
sum_logdet += log_det
x = torch.cat((x, x_split), dim = 1)
if direction: # direction is reverse
for flowStep in reversed(self.flowsteps):
x, log_det = flowStep(x, direction)
sum_logdet += log_det
x = self.unsqueeze(x)
return x, sum_logdet
def squeeze(self, x):
"""
Quadruples the number of channels of the input
this is done to increase the spatial information volume for the image channels
Parameters
----------
x : torch.Tensor
batch of input images with shape
batch_size, channels, height, width
Returns
-------
x : torch.tensor
squeezed input with shape
batch_size, channels * 4, height//2, width//2
"""
batch_size, channels, h, w = x.size()
x = x.view(batch_size, channels, h // 2, 2, w //2, 2)
x = x.permute(0, 1, 3, 5, 2, 4).contiguous() # to apply permutation from the glow paper
x = x.view(batch_size, channels * 4, h // 2, w // 2)
return x
def unsqueeze(self, x):
"""
Unsqueeze the image by dividing the channels by 4 and
reconstructs the squeezed image
Parameters
----------
x : torch.Tensor
batch of input images with shape
batch_size, channels * 4, height//2, width//2
Returns
-------
x : torch.tensor
unsqueezed input with shape
batch_size, channels, height, width
"""
batch_size, channels, h, w = x.size()
x = x.view(batch_size, channels // 4, 2, 2, h, w)
x = x.permute(0, 1, 4, 2, 5, 3).contiguous()
x = x.view(batch_size, channels // 4, h * 2, w * 2)
return x | nilq/baby-python | python |
from collections import defaultdict
from glypy.io import iupac, glycoct
from glypy.structure.glycan_composition import HashableGlycanComposition, FrozenGlycanComposition
from glypy.enzyme import (
make_n_glycan_pathway, make_mucin_type_o_glycan_pathway,
MultiprocessingGlycome, Glycosylase, Glycosyltransferase,
EnzymeGraph, GlycanCompositionEnzymeGraph, _enzyme_graph_inner)
from glycan_profiling.task import TaskBase, log_handle
from glycan_profiling.database.builder.glycan.glycan_source import (
GlycanHypothesisSerializerBase, GlycanTransformer,
DBGlycanComposition, formula, GlycanCompositionToClass,
GlycanTypes)
from glycan_profiling.structure import KeyTransformingDecoratorDict
def key_transform(name):
return str(name).lower().replace(" ", '-')
synthesis_register = KeyTransformingDecoratorDict(key_transform)
class MultiprocessingGlycomeTask(MultiprocessingGlycome, TaskBase):
def _log(self, message):
log_handle.log(message)
def log_generation_chunk(self, i, chunks, current_generation):
self._log(".... Task %d/%d finished (%d items generated)" % (
i, len(chunks), len(current_generation)))
class GlycanSynthesis(TaskBase):
glycan_classification = None
def __init__(self, glycosylases=None, glycosyltransferases=None, seeds=None, limits=None,
convert_to_composition=True, n_processes=5):
self.glycosylases = glycosylases or {}
self.glycosyltransferases = glycosyltransferases or {}
self.seeds = seeds or []
self.limits = limits or []
self.convert_to_composition = convert_to_composition
self.n_processes = n_processes
def remove_enzyme(self, enzyme_name):
if enzyme_name in self.glycosylases:
return self.glycosylases.pop(enzyme_name)
elif enzyme_name in self.glycosyltransferases:
return self.glycosyltransferases.pop(enzyme_name)
else:
raise KeyError(enzyme_name)
def add_enzyme(self, enzyme_name, enzyme):
if isinstance(enzyme, Glycosylase):
self.glycosylases[enzyme_name] = enzyme
elif isinstance(enzyme, Glycosyltransferase):
self.glycosyltransferases[enzyme_name] = enzyme
else:
raise TypeError("Don't know where to put object of type %r" % type(enzyme))
def add_limit(self, limit):
self.limits.append(limit)
def add_seed(self, structure):
if structure in self.seeds:
return
self.seeds.append(structure)
def build_glycome(self):
glycome = MultiprocessingGlycomeTask(
self.glycosylases, self.glycosyltransferases,
self.seeds, track_generations=False,
limits=self.limits, processes=self.n_processes)
return glycome
def convert_enzyme_graph_composition(self, glycome):
self.log("Converting Enzyme Graph into Glycan Set")
glycans = set()
glycans.update(glycome.enzyme_graph)
for i, v in enumerate(glycome.enzyme_graph.values()):
if i and i % 100000 == 0:
self.log(".... %d Glycans In Set" % (len(glycans)))
glycans.update(v)
self.log(".... %d Glycans In Set" % (len(glycans)))
composition_graph = defaultdict(_enzyme_graph_inner)
compositions = set()
cache = StructureConverter()
i = 0
for s in glycans:
i += 1
gc = cache[s]
for child, enz in glycome.enzyme_graph[s].items():
composition_graph[gc][cache[child]].update(enz)
if i % 1000 == 0:
self.log(".... Converted %d Compositions (%d/%d Structures, %0.2f%%)" % (
len(compositions), i, len(glycans), float(i) / len(glycans) * 100.0))
compositions.add(gc)
return compositions, composition_graph
def extract_structures(self, glycome):
self.log("Converting Enzyme Graph into Glycan Set")
solutions = list()
for i, structure in enumerate(glycome.seen):
if i and i % 10000 == 0:
self.log(".... %d Glycans Extracted" % (i,))
solutions.append(structure)
return solutions, glycome.enzyme_graph
def run(self):
logger = self.ipc_logger()
glycome = self.build_glycome()
old_logger = glycome._log
glycome._log = logger.handler
for i, gen in enumerate(glycome.run()):
self.log(".... Generation %d: %d Structures" % (i, len(gen)))
self.glycome = glycome
logger.stop()
glycome._log = old_logger
if self.convert_to_composition:
compositions, composition_enzyme_graph = self.convert_enzyme_graph_composition(glycome)
return compositions, composition_enzyme_graph
else:
structures, enzyme_graph = self.extract_structures(glycome)
return structures, enzyme_graph
class Limiter(object):
def __init__(self, max_nodes=26, max_mass=5500.0):
self.max_mass = max_mass
self.max_nodes = max_nodes
def __call__(self, x):
return len(x) < self.max_nodes and x.mass() < self.max_mass
GlycanSynthesis.size_limiter_type = Limiter
@synthesis_register("n-glycan")
@synthesis_register("mammalian-n-glycan")
class NGlycanSynthesis(GlycanSynthesis):
glycan_classification = GlycanTypes.n_glycan
def _get_initial_components(self):
glycosidases, glycosyltransferases, seeds = make_n_glycan_pathway()
glycosyltransferases.pop('siat2_3')
child = iupac.loads("a-D-Neup5Gc")
parent = iupac.loads("b-D-Galp-(1-4)-b-D-Glcp2NAc")
siagct2_6 = Glycosyltransferase(6, 2, parent, child, parent_node_id=3)
glycosyltransferases['siagct2_6'] = siagct2_6
return glycosidases, glycosyltransferases, seeds
def __init__(self, glycosylases=None, glycosyltransferases=None, seeds=None, limits=None,
convert_to_composition=True, n_processes=5):
sylases, transferases, more_seeds = self._get_initial_components()
sylases.update(glycosylases or {})
transferases.update(glycosyltransferases or {})
more_seeds.extend(seeds or [])
super(NGlycanSynthesis, self).__init__(sylases, transferases, more_seeds,
limits, convert_to_composition, n_processes)
@synthesis_register("human-n-glycan")
class HumanNGlycanSynthesis(NGlycanSynthesis):
def _get_initial_components(self):
glycosidases, glycosyltransferases, seeds = super(
HumanNGlycanSynthesis, self)._get_initial_components()
glycosyltransferases.pop('siagct2_6')
glycosyltransferases.pop('agal13galt')
glycosyltransferases.pop('gntE')
return glycosidases, glycosyltransferases, seeds
@synthesis_register("mucin-o-glycan")
@synthesis_register("mammalian-mucin-o-glycan")
class MucinOGlycanSynthesis(GlycanSynthesis):
glycan_classification = GlycanTypes.o_glycan
def _get_initial_components(self):
glycosidases, glycosyltransferases, seeds = make_mucin_type_o_glycan_pathway()
parent = iupac.loads("a-D-Galp2NAc")
child = iupac.loads("a-D-Neup5Gc")
sgt6gal1 = Glycosyltransferase(6, 2, parent, child, terminal=False)
glycosyltransferases['sgt6gal1'] = sgt6gal1
parent = iupac.loads("b-D-Galp-(1-3)-a-D-Galp2NAc")
child = iupac.loads("a-D-Neup5Gc")
sgt3gal2 = Glycosyltransferase(3, 2, parent, child, parent_node_id=3)
glycosyltransferases['sgt3gal2'] = sgt3gal2
parent = iupac.loads("b-D-Galp-(1-3)-a-D-Galp2NAc")
child = iupac.loads("a-D-Neup5Gc")
sgt6gal2 = Glycosyltransferase(6, 2, parent, child, parent_node_id=3)
glycosyltransferases['sgt6gal2'] = sgt6gal2
return glycosidases, glycosyltransferases, seeds
def __init__(self, glycosylases=None, glycosyltransferases=None, seeds=None, limits=None,
convert_to_composition=True, n_processes=5):
sylases, transferases, more_seeds = self._get_initial_components()
sylases.update(glycosylases or {})
transferases.update(glycosyltransferases or {})
more_seeds.extend(seeds or [])
super(MucinOGlycanSynthesis, self).__init__(sylases, transferases, more_seeds,
limits, convert_to_composition, n_processes)
@synthesis_register("human-mucin-o-glycan")
class HumanMucinOGlycanSynthesis(MucinOGlycanSynthesis):
def _get_initial_components(self):
glycosidases, glycosyltransferases, seeds = super(HumanMucinOGlycanSynthesis)._get_initial_components()
glycosyltransferases.pop("sgt6gal1")
glycosyltransferases.pop("sgt3gal2")
glycosyltransferases.pop("sgt6gal2")
return glycosidases, glycosyltransferases, seeds
class StructureConverter(object):
def __init__(self):
self.cache = dict()
def convert(self, structure_text):
if structure_text in self.cache:
return self.cache[structure_text]
structure = glycoct.loads(structure_text)
gc = HashableGlycanComposition.from_glycan(structure).thaw()
gc.drop_stems()
gc.drop_configurations()
gc.drop_positions()
gc = HashableGlycanComposition(gc)
self.cache[structure_text] = gc
return gc
def __getitem__(self, structure_text):
return self.convert(structure_text)
def __repr__(self):
return "%s(%d)" % (self.__class__.__name__, len(self.cache))
class AdaptExistingGlycanGraph(TaskBase):
def __init__(self, graph, enzymes_to_remove):
self.graph = graph
self.enzymes_to_remove = set(enzymes_to_remove)
self.enzymes_available = set(self.graph.enzymes())
if (self.enzymes_to_remove - self.enzymes_available):
raise ValueError("Required enzymes %r not found" % (
self.enzymes_to_remove - self.enzymes_available,))
def remove_enzymes(self):
enz_to_remove = self.enzymes_to_remove
for enz in enz_to_remove:
self.log(".... Removing Enzyme %s" % (enz,))
self.graph.remove_enzyme(enz)
for entity in (self.graph.parentless() - self.graph.seeds):
self.graph.remove(entity)
def run(self):
self.log("Adapting Enzyme Graph with %d nodes and %d edges" % (
self.graph.node_count(), self.graph.edge_count()))
self.remove_enzymes()
self.log("After Adaption, Graph has %d nodes and %d edges" % (
self.graph.node_count(), self.graph.edge_count()))
class ExistingGraphGlycanHypothesisSerializer(GlycanHypothesisSerializerBase):
def __init__(self, enzyme_graph, database_connection, enzymes_to_remove=None, reduction=None,
derivatization=None, hypothesis_name=None, glycan_classification=None):
if enzymes_to_remove is None:
enzymes_to_remove = set()
GlycanHypothesisSerializerBase.__init__(self, database_connection, hypothesis_name)
self.enzyme_graph = enzyme_graph
self.enzymes_to_remove = set(enzymes_to_remove)
self.glycan_classification = glycan_classification
self.reduction = reduction
self.derivatization = derivatization
self.loader = None
self.transformer = None
def build_glycan_compositions(self):
adapter = AdaptExistingGlycanGraph(self.enzyme_graph, self.enzymes_to_remove)
adapter.start()
components = adapter.graph.nodes()
for component in components:
if isinstance(component, FrozenGlycanComposition):
component = component.thaw()
yield component, [self.glycan_classification]
def make_pipeline(self):
self.loader = self.build_glycan_compositions()
self.transformer = GlycanTransformer(self.loader, self.reduction, self.derivatization)
def run(self):
self.make_pipeline()
structure_class_lookup = self.structure_class_loader
acc = []
counter = 0
for composition, structure_classes in self.transformer:
mass = composition.mass()
composition_string = composition.serialize()
formula_string = formula(composition.total_composition())
inst = DBGlycanComposition(
calculated_mass=mass, formula=formula_string,
composition=composition_string,
hypothesis_id=self.hypothesis_id)
self.session.add(inst)
self.session.flush()
counter += 1
for structure_class in structure_classes:
structure_class = structure_class_lookup[structure_class]
acc.append(dict(glycan_id=inst.id, class_id=structure_class.id))
if len(acc) % 100 == 0:
self.session.execute(GlycanCompositionToClass.insert(), acc)
acc = []
if acc:
self.session.execute(GlycanCompositionToClass.insert(), acc)
acc = []
self.session.commit()
self.log("Generated %d glycan compositions" % counter)
class SynthesisGlycanHypothesisSerializer(GlycanHypothesisSerializerBase):
def __init__(self, glycome, database_connection, reduction=None,
derivatization=None, hypothesis_name=None, glycan_classification=None):
if glycan_classification is None:
glycan_classification = glycome.glycan_classification
GlycanHypothesisSerializerBase.__init__(self, database_connection, hypothesis_name)
self.glycome = glycome
self.glycan_classification = glycan_classification
self.reduction = reduction
self.derivatization = derivatization
self.loader = None
self.transformer = None
def build_glycan_compositions(self):
components, enzyme_graph = self.glycome.start()
for component in components:
yield component, [self.glycan_classification]
def make_pipeline(self):
self.loader = self.build_glycan_compositions()
self.transformer = GlycanTransformer(self.loader, self.reduction, self.derivatization)
def run(self):
self.make_pipeline()
structure_class_lookup = self.structure_class_loader
acc = []
counter = 0
for composition, structure_classes in self.transformer:
mass = composition.mass()
composition_string = composition.serialize()
formula_string = formula(composition.total_composition())
inst = DBGlycanComposition(
calculated_mass=mass, formula=formula_string,
composition=composition_string,
hypothesis_id=self.hypothesis_id)
if (counter + 1) % 100 == 0:
self.log("Stored %d glycan compositions" % counter)
self.session.add(inst)
self.session.flush()
counter += 1
for structure_class in structure_classes:
structure_class = structure_class_lookup[structure_class]
acc.append(dict(glycan_id=inst.id, class_id=structure_class.id))
if len(acc) % 100 == 0:
self.session.execute(GlycanCompositionToClass.insert(), acc)
acc = []
if acc:
self.session.execute(GlycanCompositionToClass.insert(), acc)
acc = []
self.session.commit()
self.log("Stored %d glycan compositions" % counter)
| nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.