blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 112 | license_type stringclasses 2 values | repo_name stringlengths 5 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 777 values | visit_date timestamp[us]date 2015-08-06 10:31:46 2023-09-06 10:44:38 | revision_date timestamp[us]date 1970-01-01 02:38:32 2037-05-03 13:00:00 | committer_date timestamp[us]date 1970-01-01 02:38:32 2023-09-06 01:08:06 | github_id int64 4.92k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-04 01:52:49 2023-09-14 21:59:50 ⌀ | gha_created_at timestamp[us]date 2008-05-22 07:58:19 2023-08-21 12:35:19 ⌀ | gha_language stringclasses 149 values | src_encoding stringclasses 26 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 3 10.2M | extension stringclasses 188 values | content stringlengths 3 10.2M | authors listlengths 1 1 | author_id stringlengths 1 132 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b6933de33d4267ec3bf240b424e9fd2bfef3e627 | 39c5e93c07f1d41cb2dd632a858b58ccf9955ab9 | /Methods and Functions/map_Filter_lambda/filter.py | cd5f5b820360883d191acfe3efd4b26516ef0f2a | [] | no_license | amitarvindpatil/Python-Study-Material | 0e8b1ca4361c7ff92f94cc7bf76d4ef2866dddac | b52f96ceb2b9a7dcb0dd979c2f688ea2460cdece | refs/heads/master | 2023-04-21T03:54:01.894374 | 2021-05-11T06:19:06 | 2021-05-11T06:19:06 | 224,249,792 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 669 | py | # Filter
# -----The filter() method filters the given sequence with the help
# of a function that tests each element in the sequence to be true or not.
# Example
# def check_even(num):
# return num % 2 == 0
# num = [0, 3, 2, 4, 5, 2, 6, 7, 34, 23, 5, 78, 32, 2, 1, 1, 0]
# filter_even = filter(check_even, num)
# print(list(filter_even))
# Example 2
def vovels(letters):
vows = ['e', 'a', 'i', 'o', 'u']
for v in vows:
print(v)
if letters[0] == v:
return True
else:
return False
letters = ["amit", "patil", "iskon", "ervind"]
filter_vovels = filter(vovels, letters)
print(list(filter_vovels))
| [
"amitpatil04041993@gmail.com"
] | amitpatil04041993@gmail.com |
f72dbe571f55a2c24215509833ecbcfcbfeb6bbd | 7259dbcc9e32502945d362caa43d4ad380cd04ea | /企业数据库爬虫/badwork-master/uptoaliyun/bxzd_uptoaliyun.py | 83b56fccbcfe8eb45924f5fbc87fecc2f32fedf8 | [
"MIT"
] | permissive | Doraying1230/Python-Study | daa143c133262f4305624d180b38205afe241163 | 8dccfa2108002d18251053147ccf36551d90c22b | refs/heads/master | 2020-03-29T13:46:13.061373 | 2018-07-26T15:19:32 | 2018-07-26T15:19:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,964 | py | # coding:utf-8
import requests
import time
import uuid
import threading
import Queue
import MySQLdb
import config
import re
from lxml import etree
from lxml.html import fromstring
from download_center.store.store_mysql_pool import StoreMysqlPool
# from StoreMysqlPool import StoreMysqlPool
from download_center.store.store_oss import StoreOSS
import sys
import base64
reload(sys)
sys.setdefaultencoding('utf8')
class BaiduImage:
def __init__(self):
self.db = StoreMysqlPool(**config.CONN_DB)
self.oss = StoreOSS(**config.EHCO_OSS)
self.q = Queue.Queue()
def get_image_respone(self, url):
'''
下载指定url二进制的文件
'''
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
}
try:
r = requests.get(url, timeout=20, stream=True, headers=headers)
r.raise_for_status()
print '图片下载成功!url: {}'.format(url)
time.sleep(1)
return r.content
except:
# print '图片下载失败!url: {}'.format(url)
time.sleep(1)
return None
def up_to_server(self, respone, filename):
'''
将原图下载,并上传到阿里云服务器
Args:
url :图片的源地址
filename:图片文件名
'''
# 设置文件目录
web_folder = "comments/" + filename
try:
status = self.oss.put(web_folder, respone).status
if status != 200:
print '图片上传失败了'
else:
pass
# print filename, '上传成功'
except:
pass
else:
# print("deal_response_image", url)
pass
def format_img_url(self):
img_head = 'http://website201710.oss-cn-shanghai.aliyuncs.com/comments/'
img_name = '{}.jpg'.format(uuid.uuid1())
aliyun_url = '{}{}'.format(img_head, img_name)
return aliyun_url, img_name
def strip_img(self, html):
try:
tree = fromstring(html.decode('utf-8'))
imgs = tree.xpath('.//img')
for img in imgs:
img_src = img.get('src')
# st = time.time()
response = self.get_image_respone(img_src)
# print("get_image_respone end time:{}".format(time.time() - st))
if response:
aliyun_url,filename = self.format_img_url()
img.set('src',aliyun_url)
self.up_to_server(response, filename)
else:
img.getparent().remove(img)
content = etree.tostring(tree, encoding='utf-8', method='html').strip()
return content[5:-6]
except:
pass
def get_all_id_content(self,id_num=0):
sql = """select id,content from comments limit {},500""".format(id_num)
data = self.db.query(sql)
if data:
for row in data:
_id = row[0]
content = row[1]
yield (_id,content)
else:
time.sleep(60*5)
def get_tasks(self):
while 1:
# if self.q.qsize() < 400:
print("get_tasks")
for each in self.get_all_id_content():
self.q.put(each)
else:
time.sleep(60*5)
@staticmethod
def find_img(s):
pattern = re.compile(r'src="(.*?)"')
return re.search(pattern,s)
def deal_task(self):
time.sleep(2)
while 1:
try:
id_content = self.q.get()
_id = id_content[0]
html = id_content[1]
if self.find_img(id_content[1]):
content = self.strip_img(html)
update_sql = """update `comments` set content="{}" where id = {}""".format(MySQLdb.escape_string(base64.b64encode(str(content))), _id)
self.db.do(update_sql)
print("insert: {}".format(_id))
else:
# i = time.time()
update_sql = """update `comments` set content="{}" where id = {}""".format(MySQLdb.escape_string(base64.b64encode(str(html))), _id)
self.db.do(update_sql)
# print("update_sql:{}".format(time.time() -i))
except:
print('queue is empty!')
time.sleep(60*5)
def start(self):
thread_list = []
thread_list.append(threading.Thread(target=self.get_tasks))
for i in range(10):
t = threading.Thread(target=self.deal_task)
thread_list.append(t)
for t in thread_list:
t.start()
if __name__ == '__main__':
baidu = BaiduImage()
baidu.start()
| [
"2829969299@qq.com"
] | 2829969299@qq.com |
684abb44cfce60560ac0ac5f80e323449ad55dcc | 7370127fe73970fdf0882f0696c1dbbf1e818745 | /pds-queries/2022-stewardship/nightly-reports.py | abb57d73eaf102dd279bc955663b0203d3808760 | [] | no_license | epiphany40223/epiphany | ab5ef0590ac67d2e353592c45177b8e5f7e22457 | 32956e735f0c5e3fc9231449796431d23b4817f0 | refs/heads/main | 2023-09-01T05:12:17.013064 | 2023-08-27T19:57:16 | 2023-08-27T19:57:16 | 41,978,574 | 5 | 11 | null | 2023-09-11T02:00:09 | 2015-09-05T23:06:07 | Python | UTF-8 | Python | false | false | 67,259 | py | #!/usr/bin/env python3
# Make sure to pip install everything in requirements.txt.
import sys
import collections
import traceback
import datetime
import argparse
import smtplib
import csv
import os
import re
# We assume that there is a "ecc-python-modules" sym link in this
# directory that points to the directory with ECC.py and friends.
moddir = os.path.join(os.getcwd(), 'ecc-python-modules')
if not os.path.exists(moddir):
print("ERROR: Could not find the ecc-python-modules directory.")
print("ERROR: Please make a ecc-python-modules sym link and run again.")
exit(1)
sys.path.insert(0, moddir)
import ECC
import Google
import PDSChurch
import GoogleAuth
import helpers
from datetime import date
from datetime import datetime
from datetime import timedelta
from oauth2client import tools
from googleapiclient.http import MediaFileUpload
from email.message import EmailMessage
import matplotlib
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
#------------------------------------------------------------------------------
from constants import already_submitted_fam_status
from constants import already_submitted_fam_keyword
from constants import stewardship_begin_date
from constants import stewardship_end_date
from constants import gapp_id
from constants import guser_cred_file
from constants import jotform_gsheet_gfile_id
from constants import jotform_gsheet_columns
from constants import upload_team_drive_folder_id
from constants import gsheet_editors
from constants import stewardship_year
from constants import title
from constants import smtp_server
from constants import smtp_from
from constants import jotform
from constants import MAX_PDS_FAMILY_MEMBER_NUM
##############################################################################
ecc = '@epiphanycatholicchurch.org'
# Comments and pledge analysis report email
reports_email_to = f'angie{ecc},mary{ecc},jeff@squyres.com'
reports_email_subject = 'Comments and pledge analysis reports'
# Statistics report email
statistics_email_to = f'sdreiss71@gmail.com,angie{ecc},mary{ecc},jeff@squyres.com'
statistics_email_subject = 'Statistics report'
fid_participation_email_to = f'mary{ecc},jeff@squyres.com'
pledge_email_to = fid_participation_email_to
pledge_email_subject = 'Pledge PDS CSV import file'
# JMS for debugging/testing
statistics_email_to = 'jeff@squyres.com'
reports_email_to = statistics_email_to
fid_participation_email_to = statistics_email_to
pledge_email_to = statistics_email_to
##############################################################################
def _upload_to_gsheet(google, google_folder_id, google_filename, mime_type, local_filename, remove_local, log):
try:
log.info(f'Uploading file to google "{local_filename}" -> "{google_filename}"')
metadata = {
'name' : google_filename,
'mimeType' : Google.mime_types['sheet'],
'parents' : [ google_folder_id ],
'supportsTeamDrives' : True,
}
media = MediaFileUpload(local_filename,
mimetype=Google.mime_types[mime_type],
resumable=True)
file = google.files().create(body=metadata,
media_body=media,
supportsTeamDrives=True,
fields='id').execute()
log.debug(f'Successfully uploaded file: "{google_filename}" (ID: {file["id"]})')
except:
log.error('Google upload failed for some reason:')
log.error(traceback.format_exc())
exit(1)
# Set permissions on the GSheet to allow the
# workers group to edit the file (if you are view-only, you
# can't even adjust the column widths, which will be
# problematic for the comments report!).
# JMS Fix me
if False:
try:
perm = {
'type': 'group',
'role': 'writer',
'emailAddress': gsheet_editors,
}
out = google.permissions().create(fileId=file['id'],
supportsTeamDrives=True,
sendNotificationEmail=False,
body=perm,
fields='id').execute()
log.debug(f"Set Google permission for file: {id}")
except:
log.error('Google set permission failed for some reason:')
log.error(traceback.format_exc())
exit(1)
# Remove the temp file when we're done
if remove_local:
try:
os.remove(local_filename)
except:
pass
return file['id']
#-----------------------------------------------------------------------------
def _make_filenames(filename, extension):
extension = f".{extension}"
if filename.endswith(extension):
local_filename = filename
google_filename = filename[:-len(extension)]
else:
local_filename = f"{filename}{extension}"
google_fielname = filename
return local_filename, google_filename
#-----------------------------------------------------------------------------
def upload_csv_to_gsheet(google, google_folder_id, filename, fieldnames, csv_rows, remove_local, log):
if csv_rows is None or len(csv_rows) == 0:
return None, None
# First, write out a CSV file
csv_filename, google_filename = _make_filenames(filename, 'csv')
try:
os.remove(csv_filename)
except:
pass
csvfile = open(csv_filename, 'w')
writer = csv.DictWriter(csvfile, fieldnames=fieldnames,
quoting=csv.QUOTE_ALL)
writer.writeheader()
for row in csv_rows:
writer.writerow(row)
csvfile.close()
# Now upload that file to Google Drive
id = _upload_to_gsheet(google,
google_folder_id=google_folder_id,
google_filename=google_filename,
mime_type='csv',
local_filename=csv_filename,
remove_local=remove_local,
log=log)
return id, None if remove_local else csv_filename
#-----------------------------------------------------------------------------
def upload_xlsx_to_gsheet(google, google_folder_id, filename, workbook, remove_local, log):
# First, write out the XLSX file
xlsx_filename, google_filename = _make_filenames(filename, 'xlsx')
try:
os.remove(xlsx_filename)
except:
pass
workbook.save(xlsx_filename)
# Now upload that file to Google Drive
id = _upload_to_gsheet(google,
google_folder_id=google_folder_id,
# For some reason, when we upload an XLSX and want
# it to convert to a Google Sheet, the google filename
# must end in .xlsx. Sigh.
google_filename=xlsx_filename,
mime_type='sheet',
local_filename=xlsx_filename,
remove_local=remove_local,
log=log)
return id, None if remove_local else xlsx_filename
##############################################################################
def _change(label, old_value, new_value, message):
return {
'label' : label,
'old_value' : old_value,
'new_value' : new_value,
'message' : message,
}
def _compare(changes, label, jot_value, pds_value):
if jot_value is None:
jot_value = ''
if pds_value is None:
pds_value = ''
if jot_value.strip() == pds_value.strip():
return
message = ('{label}: {new_value}'
.format(label=label, new_value=jot_value))
changes.append(_change(label=label,
old_value=pds_value,
new_value=jot_value,
message=message))
##############################################################################
def comments_to_xlsx(google, jotform_data, id_field, emails_field, name_field, env_field, workbook, log):
sheet = workbook.active
comments_label = "Comments"
pledge_last_label = f'CY{stewardship_year-1} pledge'
pledge_cur_label = f'CY{stewardship_year} pledge'
amount_label = f'CY{stewardship_year-1} gifts'
# Setup the title row
# Title rows + set column widths
title_font = Font(color='FFFF00')
title_fill = PatternFill(fgColor='0000FF', fill_type='solid')
title_align = Alignment(horizontal='center', wrap_text=True)
wrap_align = Alignment(horizontal='general', wrap_text=True)
right_align = Alignment(horizontal='right')
money_format = "$###,###,###"
xlsx_cols = dict();
def _add_col(name, width=10):
col = len(xlsx_cols) + 1
xlsx_cols[name] = {'name' : name, 'column' : col, 'width' : width }
_add_col('Date', width=20)
_add_col('FID')
_add_col('Envelope')
_add_col('Family names', width=30)
_add_col('Emails', width=50)
_add_col(pledge_last_label)
_add_col(pledge_cur_label)
_add_col(amount_label)
_add_col('Comments', width=100)
for data in xlsx_cols.values():
col = data['column']
cell = sheet.cell(row=1, column=col, value=data['name'])
cell.fill = title_fill
cell.font = title_font
cell.alignment = title_align
col_char = chr(ord('A') - 1 + col)
sheet.column_dimensions[col_char].width = data['width']
sheet.freeze_panes = sheet['A2']
#-------------------------------------------------------------------
def _extract_money_string(val):
if val.startswith('$'):
val = val[1:]
val = int(float(val.replace(',', '').strip()))
if val != 0:
return int(val), money_format
else:
return 0, None
#-------------------------------------------------------------------
# Now fill in all the data rows
xlsx_row = 2
log.info(f"Checking {len(jotform_data)} rows for comments")
for row in jotform_data:
# Skip if the comments are empty
if comments_label not in row:
continue
if row[comments_label] == '':
continue
if row[pledge_last_label]:
pledge_last, pledge_last_format = _extract_money_string(row[pledge_last_label])
else:
pledge_last = 0
pledge_last_format = None
if row[pledge_cur_label]:
pledge_cur = helpers.jotform_text_to_int(row[pledge_cur_label])
pledge_cur_format = money_format
else:
pledge_cur = 0
pledge_cur_format = None
if row[amount_label]:
amount, amount_format = _extract_money_string(row[amount_label])
else:
amount = 0
amount_format = None
def _fill(col_name, value, align=None, format=None):
col_data = xlsx_cols[col_name]
cell = sheet.cell(row=xlsx_row, column=col_data['column'], value=value)
if align:
cell.alignment = align
if format:
cell.number_format = format
_fill('Date', row['SubmitDate'])
_fill('FID', int(row[id_field]))
# Do NOT convert the envelope ID to an int -- the leading zeros
# are significant.
_fill('Envelope', row[env_field])
_fill('Family names', row[name_field])
_fill('Emails', row[emails_field])
_fill(pledge_last_label, pledge_last, format=pledge_last_format)
_fill(pledge_cur_label, pledge_cur, format=pledge_cur_format)
_fill(amount_label, amount, format=amount_format)
_fill('Comments', row[comments_label], align=wrap_align)
xlsx_row += 1
# Return the number of comments we found
return xlsx_row - 2
def reorder_rows_by_date(jotform_data):
data = dict()
for row in jotform_data:
data[row['SubmitDate']] = row
out = list()
for row in sorted(data):
out.append(data[row])
return out
def comments_report(args, google, start, end, time_period, jotform_data, log):
log.info("Composing comments report...")
# jotform_data is a list of rows, in order by FID. Re-order them to be
# ordered by submission date.
ordered_data = reorder_rows_by_date(jotform_data)
# Examine the jotform data and see if there are any comments that
# need to be reported
workbook = Workbook()
num_comments = comments_to_xlsx(google, jotform_data=ordered_data,
id_field='fid', name_field='Family names',
env_field='EnvId', emails_field='Emails to reply to',
workbook=workbook, log=log)
# If we have any comments, upload them to a Gsheet
gsheet_id = None
sheet = workbook.active
if num_comments > 0:
filename = f'Comments {time_period}.xlsx'
gsheet_id, _ = upload_xlsx_to_gsheet(google,
google_folder_id=upload_team_drive_folder_id,
filename=filename,
workbook=workbook,
remove_local=True,
log=log)
return gsheet_id
##############################################################################
def statistics_compute(pds_families, unique_fid_jotform, log):
ret = dict()
# Total number of active Families in the parish
ret['num_active'] = len(pds_families)
#---------------------------------------------------------------
# Number of active Families who are eligible for electronic stewardship
# (i.e., we have an email address for the spouse and/or HoH)
eligible = dict()
for fid, family in pds_families.items():
for member in family['members']:
if PDSChurch.is_member_hoh_or_spouse(member):
em = PDSChurch.find_any_email(member)
if len(em) == 0:
continue
eligible[fid] = True
continue
ret['num_eligible'] = len(eligible)
#-----------------------------------------------------------
# The unique_fid_jotform dictionary we have will have, at most, 1 entry per
# FID. So we can just take the length of it to know how many (unique)
# families have submitted electronically.
ret['num_electronic'] = len(unique_fid_jotform)
#-----------------------------------------------------------
# Build a cross-reference of which families have submitted electronically
fids_electronic = dict()
for row in unique_fid_jotform:
fid = int(row['fid'])
fids_electronic[fid] = True
fids_paper_or_electronic = fids_electronic.copy()
# - Count how many submitted paper
# - Count how many submitted paper and electronic
# - Count how many submitted paper or electronic
fids_paper = dict()
fids_paper_and_electronic = dict()
for fid, family in pds_families.items():
if 'status' in family and family['status'] == already_submitted_fam_status:
fids_paper[fid] = True
fids_paper_or_electronic[fid] = True
if fid in fids_electronic:
fids_paper_and_electronic[fid] = True
ret['num_paper'] = len(fids_paper)
ret['num_paper_or_electronic'] = len(fids_paper_or_electronic)
ret['num_paper_and_electronic'] = len(fids_paper_and_electronic)
#-----------------------------------------------------------
return ret
#------------------------------------------------------------------------
def statistics_graph(pds_members, pds_families, jotform, log):
def _find_range(data, earliest, latest):
for row in data:
submitted = row['SubmitDate']
submitted_dt = helpers.jotform_date_to_datetime(submitted)
if submitted_dt < earliest:
earliest = submitted_dt
if submitted_dt > latest:
latest = submitted_dt
return earliest, latest
#------------------------------------------------------------------------
def _compute(start, end, pds_members, pds_families, jotform, log):
# Compute these values just in the date range:
# - How many unique family submissions total?
family_submitted = dict()
# Check electronic submissions
for row in jotform:
if row['fid'] == 'fid':
continue # Skip title row
# Is this row in our date range?
dt = helpers.jotform_date_to_datetime(row['SubmitDate'])
if dt < start or dt > end:
continue
fid = int(row['fid'])
log.debug(f"Found submission in our date window: {fid} on {dt}")
# Make sure the family hasn't been deleted
if fid not in pds_families:
continue
family_submitted[fid] = True
return len(family_submitted)
#------------------------------------------------------------------------
one_day = timedelta(days=1)
earliest = datetime(year=9999, month=12, day=31)
latest = datetime(year=1971, month=1, day=1)
earliest, latest = _find_range(jotform, earliest, latest)
earliest = datetime(year=earliest.year, month=earliest.month, day=earliest.day)
latest = datetime(year=latest.year, month=latest.month, day=latest.day)
latest += one_day - timedelta(seconds=1)
log.info(f"Earliest: {earliest}")
log.info(f"Latest: {latest}")
day = earliest
dates = list()
data_per_day = list()
data_cumulative = list()
# Make lists that we can give to matplotlib for plotting
while day <= latest:
log.debug(f"Get per-day stats for {day.date()}")
per_day = _compute(day, day + one_day,
pds_members, pds_families,
jotform, log)
log.debug(f"Get cumulative stats for {earliest} - {day + one_day}")
cumulative = _compute(earliest, day + one_day,
pds_members, pds_families,
jotform, log)
log.debug(f"Date: {day}: per day {per_day}, cumulative {cumulative}")
dates.append(day.date())
data_per_day.append(per_day)
data_cumulative.append(cumulative)
day += one_day
# Make the plot
fig, ax = plt.subplots()
# The X label of "days" is obvious, there's no good Y label since we have
# multiple lines
n = datetime.now()
hour = n.hour if n.hour > 0 else 12
ampm = 'am' if n.hour < 12 else 'pm'
plt.title("As of {month} {day}, {year} at {hour}:{min:02}{ampm}"
.format(month=n.strftime("%B"), day=n.day, year=n.year,
hour=hour, min=n.minute, ampm=ampm))
plt.suptitle(title + " electronic submissions statistics")
ax.plot(dates, data_per_day, label='Unique family electronic submissions per day')
ax.plot(dates, data_cumulative, label='Cumulative unique family electronic submissions')
ax.get_xaxis().set_major_locator(mdates.DayLocator(interval=1))
ax.get_xaxis().set_major_formatter(mdates.DateFormatter("%a %b %d"))
plt.setp(ax.get_xticklabels(), rotation=20, ha="right",
rotation_mode="anchor")
ax.grid()
plt.legend(loc="upper left")
# Make a filename based on the time that this was run
filename = ('statistics-as-of-{year:04}-{month:02}-{day:02}-{hour:02}{min:02}{sec:02}.pdf'
.format(year=n.year, month=n.month, day=n.day,
hour=n.hour, min=n.minute, sec=n.second))
fig.savefig(filename)
plt.close(fig)
return filename
#-----------------------------------------------------------------------------
def statistics_report(args, time_period, pds_members, pds_families, jotform, log):
log.info("Composing statistics report...")
#---------------------------------------------------------------
graph_filename = statistics_graph(pds_members, pds_families, jotform, log)
data = statistics_compute(pds_families, jotform, log)
#---------------------------------------------------------------------
electronic_percentage = data['num_electronic'] / data['num_eligible'] * 100
paper_percentage = data['num_paper'] / data['num_active'] * 100
paper_and_electronic_percentage = data['num_paper_and_electronic'] / data['num_active'] * 100
paper_or_electronic_percentage = data['num_paper_or_electronic'] / data['num_active'] * 100
# Send the statistics report email
body = list()
body.append(f"""<html>
<body>
<h2>{title} statistics update</h2>
<h3>Time period: {time_period}</h3>
<ul>
<li> Total number of active PDS Families in the parish: {data['num_active']:,d}</li>
<br>
<li> Number of active PDS Families eligible for electronic stewardship: {data['num_eligible']:,d}
<ul>
<li>This means that we have an email address in PDS for the Head of Household and/or the Spouse of a given Family</li>
</ul></li>
<br>
<li> Number of electronic-stewardship-eligible Families who have electronically submitted: {data['num_electronic']:,d} (out of {data['num_eligible']:,d}, or {electronic_percentage:.1f}%)
<ul>
<li>This is the number of families who submitted electronically.</li>
</ul></li>
<br>
<li> Number of active PDS Families with "{already_submitted_fam_status}" status: {data['num_paper']:,d} (out of {data['num_active']:,d}, or {paper_percentage:.1f}%)
<ul>
<li>This is the number of families who submitted a paper card.</li>
</ul></li>
<br>
<li> Number of active PDS Families who have electronically completed their submission <em>and</em> have "{already_submitted_fam_status}" status: {data['num_paper_and_electronic']:,d} (out of {data['num_active']:,d}, or {paper_and_electronic_percentage:.1f}%)
<ul>
<li>These are people who submitted twice -- paper and electronically!</li>
</ul></li>
<br>
<li> Number of active PDS Families who have electronically completed their submission <em>or</em> have "{already_submitted_fam_status}" status: {data['num_paper_or_electronic']:,d} (out of {data['num_active']:,d}, or {paper_or_electronic_percentage:.1f}%)
<ul>
<li>This is the total number of active Families who have submitted.</li>
</ul></li>
</ul>
</body>
</html>""")
to = statistics_email_to
subject = f'{statistics_email_subject} ({time_period})'
try:
log.info(f'Sending "{subject}" email to {to}')
with smtplib.SMTP_SSL(host=smtp_server,
local_hostname='epiphanycatholicchurch.org') as smtp:
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = smtp_from
msg['To'] = to
msg.set_content('\n'.join(body))
msg.replace_header('Content-Type', 'text/html')
# This assumes that the file has a single line in the format of username:password.
with open(args.smtp_auth_file) as f:
line = f.read()
smtp_username, smtp_password = line.split(':')
# Login; we can't rely on being IP whitelisted.
try:
smtp.login(smtp_username, smtp_password)
except Exception as e:
log.error(f'Error: failed to SMTP login: {e}')
exit(1)
with open(graph_filename, "rb") as f:
csv_data = f.read()
msg.add_attachment(csv_data, maintype='application', subtype='pdf',
filename=graph_filename)
os.unlink(graph_filename)
smtp.send_message(msg)
except:
print("==== Error with {email}".format(email=to))
print(traceback.format_exc())
##############################################################################
def pledge_comparison_report(google, jotform_this_year, jotform_last_year, log):
# Extract just 2 fields from the jotform data and return it in a
# dict indexed by fid.
def _simplify_jotform(jotform_data, participation_fieldname,
this_year_pledge_fieldname,
last_year_pledge_fieldname, log):
out = dict()
for fid, data in jotform_data.items():
participate = True
if participation_fieldname and data[participation_fieldname].startswith("Because"):
participate = False
current_pledge = 0
if participate:
current_pledge = helpers.jotform_text_to_int(data[this_year_pledge_fieldname])
previous_pledge = helpers.jotform_text_to_int(data[last_year_pledge_fieldname])
out[fid] = {
'participate' : participate,
'current pledge' : current_pledge,
'previous pledge': previous_pledge,
}
return out
# ------------------------------------------------------------------------
# Compares the dictionaries of pledges from this year to that of last year,
# and outputs a CSV showing a few statistics relating to which category the
# pledges falls into (Can't, Reduced, No Change, New, Increased, No Pledge
# Both Years) and some relevant info / analysis on totals and percentages.
def _compare(this_year_data, log):
out = dict()
for fid in this_year_data:
current_pledge = this_year_data[fid]["current pledge"]
previous_pledge = this_year_data[fid]["previous pledge"]
if this_year_data[fid]["participate"] == False:
category = "Cannot pledge"
# If the family is recorded as having a pledge of 0 OR 1 last year,
# then they did not have a pledge last year.
elif previous_pledge == 0 or previous_pledge == 1:
# Set their previous pledge to zero to accurately reflect how
# much they *actually* pledged last year.
previous_pledge = 0
if current_pledge == 0:
category = "No pledge both years"
# If the family didn't pledge last year, but pledged this year,
# it's a new pledge.
elif current_pledge > 0:
category = "NEW pledge"
elif current_pledge == previous_pledge:
category = "No change"
elif current_pledge > previous_pledge:
category = "Increased pledge"
elif current_pledge < previous_pledge:
category = "Reduced pledge"
dollar_impact = current_pledge - previous_pledge
if category not in out:
out[category] = {
'households' : 0,
'dollar impact' : 0,
'total of pledges' : 0,
}
out[category]["households"] += 1
out[category]["dollar impact"] += dollar_impact
out[category]["total of pledges"] += current_pledge
return out
# ------------------------------------------------------------------------
def _make_xlsx(comparison, log):
workbook = Workbook()
sheet = workbook.active
comments_label = "Comments"
pledge_last_label = f'CY{stewardship_year-1} pledge'
pledge_cur_label = f'CY{stewardship_year} pledge'
amount_label = f'CY{stewardship_year-1} gifts'
# Setup the title rows
# Title rows + set column widths
title_font = Font(color='FFFF00')
title_fill = PatternFill(fgColor='0000FF', fill_type='solid')
title_align = Alignment(horizontal='center', wrap_text=True)
wrap_align = Alignment(horizontal='general', wrap_text=True)
right_align = Alignment(horizontal='right')
money_format = "$##,###,###,###"
percentage_format = "##.#"
xlsx_cols = dict();
def _add_col(name, width=15, format=None):
col = len(xlsx_cols) + 1
xlsx_cols[name] = {'name' : name, 'format' : format,
'column' : col, 'width' : width }
_add_col('Category', width=20)
_add_col('Number of Households')
_add_col('%-age of Total Submitted Households')
_add_col('Dollar Impact')
_add_col('Total of Pledges Submitted')
_add_col('%-age of Total Pledges Submitted')
# Make 2 rows of merged cells for wide titles
def _make_merged_title_row(row, value):
cell = sheet.cell(row=row, column=1, value=value)
cell.fill = title_fill
cell.font = title_font
cell.alignment = title_align
end_col_char = chr(ord('A') - 1 + len(xlsx_cols))
sheet.merge_cells(f'A{row}:{end_col_char}{row}')
_make_merged_title_row(row=1, value='eStewardship Pledge Analysis')
_make_merged_title_row(row=2, value='')
# Now add all the column titles
for data in xlsx_cols.values():
col = data['column']
cell = sheet.cell(row=3, column=col, value=data['name'])
cell.fill = title_fill
cell.font = title_font
cell.alignment = title_align
col_char = chr(ord('A') - 1 + col)
sheet.column_dimensions[col_char].width = data['width']
# Finally, fill in all the data rows.
# First, compute totals so that we can compute percentages.
total_households = 0
total_pledges = 0
total_impact = 0
for data in comparison.values():
total_households += data['households']
total_pledges += data['total of pledges']
total_impact += data['dollar impact']
def _fill(column, value, align=None, format=None):
cell = sheet.cell(row=xlsx_row, column=column, value=value)
want_format = True
if (type(value) is int or type(value) is float) and value == 0:
want_format = False
if want_format:
if align:
cell.alignment = align
if format:
cell.number_format = format
xlsx_row = 4
for category, data in comparison.items():
_fill(1, category)
_fill(2, data['households'])
_fill(3, data['households'] / total_households * 100.0,
format=percentage_format)
_fill(4, data['dollar impact'],
format=money_format)
_fill(5, data['total of pledges'],
format=money_format)
_fill(6, data['total of pledges'] / total_pledges * 100.0,
format=percentage_format)
xlsx_row += 1
_fill(1, 'Totals', align=right_align)
_fill(2, total_households)
_fill(4, total_impact, format=money_format)
_fill(5, total_pledges, format=money_format)
return workbook
# ------------------------------------------------------------------------
# Make simplified data structures from the full jotform data. These will be
# easier to compare. We use this year's jotform for last year's data because
# it (this year's jotform) has pre-filled info on how much the family gave
# last year.
this_year_data = _simplify_jotform(jotform_this_year,
'CY2022 participation', 'CY2022 pledge', 'CY2021 pledge', log)
# Do the comparison
comparison = _compare(this_year_data, log)
# Make an XLSX report
workbook = _make_xlsx(comparison, log)
# Upload the XLS to google
now = datetime.now()
filename = f'{now.year:04}-{now.month:02}-{now.day:02} Pledge analysis.xlsx'
gsheet_id, _ = upload_xlsx_to_gsheet(google,
google_folder_id=upload_team_drive_folder_id,
filename=filename,
workbook=workbook,
remove_local=True,
log=log)
return gsheet_id
##############################################################################
def send_reports_email(time_period, comments_gfile, pledge_analysis_gfile, args, log):
# Send the comments report email
body = list()
body.append(f"""<html>
<body>
<h2>{title} comments and pledge analysis reports</h2>
<h3>Time period: {time_period}</h3>""")
if comments_gfile is None:
body.append("<p>No comments submitted during this time period.</p>")
else:
url = 'https://docs.google.com/spreadsheets/d/{id}'.format(id=comments_gfile)
body.append(f'<p><a href="{url}">Link to Google sheet containing comments for this timeframe</a>.</p>')
url = 'https://docs.google.com/spreadsheets/d/{id}'.format(id=pledge_analysis_gfile)
body.append(f'''<p><a href="{url}">Link to Google sheet containing pledge analysis.</a>.</p>
</body>
</html>''')
to = reports_email_to
subject = '{subj} ({t})'.format(subj=reports_email_subject, t=time_period)
try:
log.info('Sending "{subject}" email to {to}'
.format(subject=subject, to=to))
with smtplib.SMTP_SSL(host=smtp_server,
local_hostname='epiphanycatholicchurch.org') as smtp:
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = smtp_from
msg['To'] = to
msg.set_content('\n'.join(body))
msg.replace_header('Content-Type', 'text/html')
# This assumes that the file has a single line in the format of username:password.
with open(args.smtp_auth_file) as f:
line = f.read()
smtp_username, smtp_password = line.split(':')
# Login; we can't rely on being IP whitelisted.
try:
smtp.login(smtp_username, smtp_password)
except Exception as e:
log.error(f'Error: failed to SMTP login: {e}')
exit(1)
smtp.send_message(msg)
except:
print("==== Error with {email}".format(email=to))
print(traceback.format_exc())
##############################################################################
# Columns that I need
# - fid
# - Recurring Charge Name:
# - Terms / Frequency: Weekly, Biweekly, Monthly, Bimonthly, Semimonthly, Quarterly, Semiannually, Annually
# - Begin Date: 01/01/2020
# - End Date: 12/31/2020
# - Rate
# - Total pledge
def convert_pledges_to_pds_import(pds_families, jotform, log):
def _map_to_freqrate(pledge):
freq = pledge[f'CY{stewardship_year} frequency']
amount = helpers.jotform_text_to_int(pledge[f'CY{stewardship_year} pledge'])
if freq == 'Weekly donations':
return 'Weekly', amount / 52
elif freq == 'Monthly donations':
return 'Monthly', amount / 12
elif freq == 'Quarterly donations':
return 'Quarterly', amount / 4
elif freq == 'One annual donation':
return 'Annually', amount
else:
return None, None
#-------------------------------------------------------------------------
out = list()
for pledge in jotform:
# Skip the title row
fid = pledge['fid']
if 'fid' in fid:
continue
# Here's something that can happen: A family may be deleted from PDS
# even though they submitted. In this case, skip them.
fid = int(fid)
if fid not in pds_families:
log.warning(f"WARNING: Family FID {pledge['fid']} / {pledge['Family names']} submitted a pledge, but is no longer in PDS")
continue
# If there is a $0 pledge, Per Lynne's comment, we'll
# transform this into a $1 annual pledge -- just so that this
# person is on the books, so to speak.
pledge_field = f'CY{stewardship_year} pledge'
pledge_amount = helpers.jotform_text_to_int(pledge[pledge_field])
if not pledge_amount or pledge_amount == '' or pledge_amount == 0:
pledge_amount = 1
pledge[pledge_field] = pledge_amount
pledge[f'CY{stewardship_year} frequency'] = 'One annual donation'
frequency, rate = _map_to_freqrate(pledge)
# Round pledge value and rate to 2 decimal points, max
rate = float(int(rate * 100)) / 100.0
total = float(int(pledge_amount) * 100) / 100.0
# Use an OrderedDict to keep the fields in order
row = collections.OrderedDict()
row['fid'] = pledge['fid']
row['RecChargeName'] = 'Due/Contributions'
row['Frequency'] = frequency
row['BeginDate'] = stewardship_begin_date.strftime('%m/%d/%Y')
row['EndDate'] = stewardship_end_date.strftime('%m/%d/%Y')
row['PledgeRate'] = rate
row['TotalPledge'] = total
row['SubmitDate'] = pledge['SubmitDate']
row['Names'] = pledge['Family names']
row['Envelope ID'] = helpers.pkey_url(pledge['EnvId'])
# Calculate family pledge values for last CY
family = pds_families[fid]
helpers.calculate_family_values(family, stewardship_year - 2, log)
row[f'CY{stewardship_year - 2} YTD gifts'] = family['calculated']['gifts']
# Calculate family pledge values for this CY
helpers.calculate_family_values(family, stewardship_year - 1, log)
row[f'CY{stewardship_year - 1} YTD gifts'] = family['calculated']['gifts']
row[f'CY{stewardship_year - 1} pledge'] = family['calculated']['pledged']
# Add column for how they want to fullfill their pledge
row[f'CY{stewardship_year} frequency'] = pledge[f'CY{stewardship_year} frequency']
row[f'CY{stewardship_year} mechanism'] = pledge[f'CY{stewardship_year} mechanisms']
# Add a column for this Family's "Envelope user" value
row['PDS Envelope User'] = family['EnvelopeUser']
# Add a column for whether the Family selected the "offeratory
# envelopes" option on the Jotform.
val = False
if 'Offertory' in pledge[f'CY{stewardship_year} mechanisms']:
val = True
row['Jotform asked for Envelopes'] = val
out.append(row)
return out
#-----------------------------------------------------------------------------
def family_pledge_csv_report(args, google, pds_families, jotform, log):
pledges = convert_pledges_to_pds_import(pds_families, jotform, log)
# If we have pledges, upload them to a Google sheet
gsheet_id = None
if len(pledges) > 0:
filename = 'Family Pledge PDS import.csv'
gsheet_id, csv_filename = upload_csv_to_gsheet(google,
google_folder_id=upload_team_drive_folder_id,
filename=filename,
fieldnames=pledges[0].keys(),
csv_rows=pledges,
remove_local=False,
log=log)
# Send the statistics report email
body = list()
body.append(f"""<html>
<body>
<h2>{title} pledge update</h2>
""")
if gsheet_id:
url = 'https://docs.google.com/spreadsheets/d/{id}'.format(id=gsheet_id)
body.append(f'<p><a href="{url}">Link to Google sheet containing pledge updates for this timeframe</a>.</p>')
body.append("<p>See the attachment for a CSV to import directly into PDS.</p>")
else:
body.append("<p>There were no pledge submissions during this timeframe.<p>")
body.append("""</body>
</html>""")
try:
to = pledge_email_to
log.info(f'Sending "{pledge_email_subject}" email to {to}')
with smtplib.SMTP_SSL(host=smtp_server,
local_hostname='epiphanycatholicchurch.org') as smtp:
# This assumes that the file has a single line in the format of username:password.
with open(args.smtp_auth_file) as f:
line = f.read()
smtp_username, smtp_password = line.split(':')
# Login; we can't rely on being IP whitelisted.
try:
smtp.login(smtp_username, smtp_password)
except Exception as e:
log.error(f'Error: failed to SMTP login: {e}')
exit(1)
msg = EmailMessage()
msg['Subject'] = pledge_email_subject
msg['From'] = smtp_from
msg['To'] = to
msg.set_content('\n'.join(body))
msg.replace_header('Content-Type', 'text/html')
# If there were results, attach the CSV
if gsheet_id:
with open(filename, "rb") as f:
csv_data = f.read()
msg.add_attachment(csv_data, maintype='text', subtype='csv', filename=filename)
smtp.send_message(msg)
if gsheet_id:
os.unlink(filename)
except:
print("==== Error with {email}".format(email=to))
print(traceback.format_exc())
##############################################################################
MINISTRY_PARTICIPATE = 1
MINISTRY_INTERESTED = 2
MINISTRY_INACTIVE = 3
def _convert_jotform_ministry_status(jotform_status):
if jotform_status is None:
return MINISTRY_INACTIVE
if 'PARTICIPATE' in jotform_status:
return MINISTRY_PARTICIPATE
elif 'INTERESTED' in jotform_status:
return MINISTRY_INTERESTED
elif 'NO LONGER' in jotform_status:
return MINISTRY_INACTIVE
else:
# Catch-all
return MINISTRY_INACTIVE
def _status_to_str(status):
if status == MINISTRY_PARTICIPATE:
return 'I already participate'
elif status == MINISTRY_INTERESTED:
return 'I am interested'
else:
return 'I do not participate'
#-----------------------------------------------------------------------------
# Fields I need:
# - MID
# - Ministry
# - Status
# - Start date (from constants.py)
# - End date (from constants.py)
# Other fields requested by the staff:
# - Member nickname + last name
# - Member email addresses
# - Member phones
# - Member status on ministry
#
# Will generate several outputs:
# - Likely can be directly imported
# - NOT PARTICIPATE -> INTERESTED
# - Likely cannot be directly imported (still need to test)
# - PARTICPATE -> NOT PARTICIPATE
# - Needs to be examined by a human
# - NOT PARTICIPATE -> ALREADY PARTICIPATE
# - PARTICIPATE -> INTERESTED
#
# Output will be a dictionary:
# - PDS ministry name (in the case of multi-names, like lectors, use the jotform name): dictionary of
# - interested: list of members
# - no_longer_interested: list of members
# - needs_human: list of members
def analyze_member_ministry_submissions(pds_members, pds_families, jotform_csv, log):
def _get_pds_member_ministry_status(member, ministry_names):
for ministry in member['active_ministries']:
if ministry['Description'] in ministry_names:
if ministry['active']:
return MINISTRY_PARTICIPATE, ministry['status']
else:
return MINISTRY_INACTIVE, ministry['status']
# If the member is not currently active in this ministry, see if they
# were ever previously a member of this ministry
results = dict()
for ministry in member['inactive_ministries']:
if ministry['Description'] in ministry_names:
results[ministry['start']] = ministry['status']
results[ministry['end']] = ministry['status']
if len(results) > 0:
dates = sorted(results.keys())
end = dates[-1]
result_str = f'Inactive, last status on {end}: {results[end]}'
else:
result_str = 'Never been a member of this ministry'
return MINISTRY_INACTIVE, result_str
#-------------------------------------------------------------------------
def _status_to_pds(status):
if status == MINISTRY_PARTICIPATE:
return 'Actively Involved'
elif status == MINISTRY_INACTIVE:
return 'No Longer Involved'
elif status == MINISTRY_INTERESTED:
return 'Interested'
#-------------------------------------------------------------------------
output = dict()
# Each row is a family
for jrow in jotform_csv:
fid = int(jrow['fid'])
# Make sure the family is still active
if fid not in pds_families:
log.warn(f"WARNING: Family {fid} submitted, but cannot be found -- skipping")
continue
family = pds_families[fid]
log.info(f"Processing Jotform Family submission: {family['Name']} (FID {fid})")
# Check the members in this row
for member_num in range(MAX_PDS_FAMILY_MEMBER_NUM):
column_names = jotform_gsheet_columns['members'][member_num]
# The 0th entry in each Member is the MID
mid = jrow[column_names[0]]
# If there's no MID for this Member, then there's no Member.
# We're done with the loop.
if mid == '':
break
# Here's something that can happen: a MID was submitted, but is no
# longer an active member in PDS. In that case, ignore the submission.
mid = int(mid)
if mid not in pds_members:
log.warn(f"WARNING: Member {mid} submitted, but cannot be found -- skipping")
continue
member = pds_members[mid]
log.info(f" Processing Jotform member {member['email_name']} (MID {mid})")
# JMS Debug
#if not m['Name'].startswith('Squyres,Jeff'):
# continue
# Go through the list of ministry grids from the jotform
for grid in jotform.ministry_grids:
# Go through the rows in the jotform ministry grid
for mrow in grid.rows:
# Each row has its PDS ministry name
ministry_entry = mrow['pds_ministry']
# Some ministry rows are lists because we want to treat them equivalently
if type(ministry_entry) is list:
output_key = mrow['row_heading']
ministries = ministry_entry
else:
output_key = ministry_entry
ministries = [ ministry_entry ]
# Get the Member's status in this Ministry from the jotform
jotform_column_name = mrow['jotform_columns'][member_num]
jotform_status_str = jrow[jotform_column_name]
jotform_status = _convert_jotform_ministry_status(jotform_status_str)
# Get their status from PDS
pds_status, pds_status_string = _get_pds_member_ministry_status(member, ministries)
key = 'jotform'
if key not in member:
member[key] = dict()
member[key][output_key] = pds_status_string
# If they're the same, nothing to do
if jotform_status == pds_status:
continue
if output_key not in output:
output[output_key] = dict()
# If PDS INACTIVE -> INTERESTED
if (pds_status == MINISTRY_INACTIVE and
jotform_status == MINISTRY_INTERESTED):
key = 'Interested'
if key not in output[output_key]:
output[output_key][key] = list()
output[output_key][key].append(member)
elif (pds_status == MINISTRY_PARTICIPATE and
jotform_status == MINISTRY_INACTIVE):
key = 'No longer interested'
if key not in output[output_key]:
output[output_key][key] = list()
output[output_key][key].append(member)
elif (pds_status == MINISTRY_INACTIVE and
jotform_status == MINISTRY_PARTICIPATE):
key = 'Needs human: PDS=inactive, but Jotform=active'
if key not in output[output_key]:
output[output_key][key] = list()
output[output_key][key].append(member)
elif (pds_status == MINISTRY_PARTICIPATE and
jotform_status == MINISTRY_INTERESTED):
key = 'Needs human: PDS=active, but Jotform=interested'
if key not in output[output_key]:
output[output_key][key] = list()
output[output_key][key].append(member)
return output
#-----------------------------------------------------------------------------
def member_ministry_csv_report(args, google, start, end, time_period, pds_members, pds_families, jotform_csv, log):
def _find_all_phones(member):
found = list()
key = 'phones'
key2 = 'unlisted'
if key in member:
# Is this the old member format? Seems to be a dict of
# phone_id / phone_data, and no "Unlisted". :-(
for p in member[key]:
# Skip emergency contacts
if 'Emergency' in p['type']:
continue
text = f"{p['number']} {p['type']}"
if key2 in p:
if p[key2]:
text += ' UNLISTED'
found.append(text)
# When used with XLSX word wrapping alignment, this will
# across put each phone number on a separate line, but all
# within a single cell.
return '\r\n'.join(found)
#--------------------------------------------------------------------
def _find_family_home_phone(member):
family = member['family']
key = 'phones'
key2 = 'unlisted'
if key in family:
for p in family[key]:
if 'Home' in p['type']:
text = f"{p['number']} {p['type']}"
if key2 in p:
if p[key2]:
text += ' UNLISTED'
return text
return ""
#--------------------------------------------------------------------
output = analyze_member_ministry_submissions(pds_members, pds_families, jotform_csv, log)
today = date.today()
#--------------------------------------------------------------------
def _setup_new_workbook():
workbook = Workbook()
sheet = workbook.active
for data in xlsx_cols.values():
col = data['column']
cell = sheet.cell(row=1, column=col, value=data['name'])
cell.fill = title_fill
cell.font = title_font
cell.alignment = title_align
col_char = chr(ord('A') - 1 + col)
sheet.column_dimensions[col_char].width = data['width']
sheet.freeze_panes = sheet['A2']
return workbook
#--------------------------------------------------------------------
def _fill(col_name, value, align=None, format=None):
col_data = xlsx_cols[col_name]
cell = sheet.cell(row=xlsx_row, column=col_data['column'], value=value)
if align:
cell.alignment = align
if format:
cell.number_format = format
#--------------------------------------------------------------------
title_font = Font(color='FFFF00')
title_fill = PatternFill(fgColor='0000FF', fill_type='solid')
title_align = Alignment(horizontal='center', wrap_text=True)
wrap_align = Alignment(horizontal='general', wrap_text=True)
right_align = Alignment(horizontal='right')
xlsx_cols = dict();
def _add_col(name, width=10):
col = len(xlsx_cols) + 1
xlsx_cols[name] = {'name' : name, 'column' : col, 'width' : width }
_add_col('Full Name', width=20)
_add_col('First')
_add_col('Last')
_add_col('Age')
_add_col('Envelope ID')
_add_col('Email', width=30)
_add_col('Member phones', width=20)
_add_col('Family home phone', width=20)
_add_col('Category', width=25)
_add_col('Current ministry status', width=50)
_add_col('MID')
_add_col('PDS ministry name', width=50)
for ministry_name in sorted(output.keys()):
workbook = _setup_new_workbook()
sheet = workbook.active
data = output[ministry_name]
xlsx_row = 2
for category in sorted(data.keys()):
for member in data[category]:
family = member['family']
_fill('Full Name', member['email_name'])
_fill('First', member['first'])
_fill('Last', member['last'])
if member['date_of_birth']:
age = today - member['date_of_birth']
_fill('Age', int(age.days / 365))
_fill('Envelope ID', family['ParKey'])
emails = PDSChurch.find_any_email(member)
if emails:
_fill('Email', emails[0])
_fill('Member phones', _find_all_phones(member), align=wrap_align)
_fill('Family home phone', _find_family_home_phone(member))
_fill('Category', category.capitalize(), align=wrap_align)
_fill('Current ministry status', member['jotform'][ministry_name], align=wrap_align)
_fill('MID', member['MemRecNum'])
_fill('PDS ministry name', ministry_name)
xlsx_row += 1
# Write out the XLSX with the results
filename = f'{ministry_name} jotform results.xlsx'.replace('/', '-')
if os.path.exists(filename):
os.unlink(filename)
workbook.save(filename)
log.info(f"Wrote to filename: {filename}")
##############################################################################
def family_status_csv_report(args, google, pds_families, jotform, log):
# Simple report: FID, Family name, and constants.already_submitted_fam_status
# Did we find anything?
if len(jotform) == 0:
log.info("No submissions -- no statuses to update")
return
# Make a dictionary of the final CSV data
csv_data = list()
for row in jotform:
fid = int(row['fid'])
if fid not in pds_families:
continue
last_name = pds_families[fid]['Name'].split(',')[0]
csv_data.append({
'fid' : fid,
'Family Name' : pds_families[fid]['Name'],
'Envelope ID' : helpers.pkey_url(pds_families[fid]['ParKey']),
'Last Name' : last_name,
'Status' : already_submitted_fam_status,
'Keyword' : already_submitted_fam_keyword,
})
filename = ('Family Status and Keyword Update.csv')
#ef upload_csv_to_gsheet(google, google_folder_id, filename, fieldnames, csv_rows, remove_local, log):
gsheet_id, csv_filename = upload_csv_to_gsheet(google,
google_folder_id=upload_team_drive_folder_id,
filename=filename,
fieldnames=csv_data[0].keys(),
csv_rows=csv_data,
remove_local=False,
log=log)
url = f'https://docs.google.com/spreadsheets/d/{gsheet_id}'
#------------------------------------------------------------------------
body = list()
body.append(f"""<html>
<body>
<h2>Family Status data update</h2>
<p> See attached spreadsheet of FIDs that have submitted anything at all in this time period.
The same spreadsheet <a href="{url}">is also available as a Google Sheet</a>.</p>
<p> Total of {len(csv_data)} families.</p>
</body>
</html>""")
to = fid_participation_email_to
subject = f'{title} Family Status updates'
try:
log.info(f'Sending "{subject}" email to {to}')
with smtplib.SMTP_SSL(host=smtp_server,
local_hostname='epiphanycatholicchurch.org') as smtp:
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = smtp_from
msg['To'] = to
msg.set_content('\n'.join(body))
msg.replace_header('Content-Type', 'text/html')
# This assumes that the file has a single line in the format of username:password.
with open(args.smtp_auth_file) as f:
line = f.read()
smtp_username, smtp_password = line.split(':')
# Login; we can't rely on being IP whitelisted.
try:
smtp.login(smtp_username, smtp_password)
except Exception as e:
log.error(f'Error: failed to SMTP login: {e}')
exit(1)
# If there were results, attach CSV files
with open(csv_filename, 'rb') as f:
csv_data = f.read()
msg.add_attachment(csv_data, maintype='text', subtype='csv',
filename=csv_filename)
smtp.send_message(msg)
os.unlink(csv_filename)
except:
print(f"==== Error with {to}")
print(traceback.format_exc())
##############################################################################
def _export_gsheet_to_csv(service, start, end, google_sheet_id, fieldnames, log):
response = service.files().export(fileId=google_sheet_id,
mimeType=Google.mime_types['csv']).execute()
csvreader = csv.DictReader(response.decode('utf-8').splitlines(),
fieldnames=fieldnames)
rows = list()
for row in csvreader:
# Skip title row
if 'Submission' in row['SubmitDate']:
continue
if row['fid'] == '':
continue
# As of Sep 2021, Google Sheets CSV export sucks. :-(
# The value of the "Edit Submission" field from Jotform is something
# like:
#
# =HYPERLINK("https://www.jotform.com/edit/50719736733810","Edit Submission")
#
# Google Sheet CSV export splits this into 2 fields. The first one
# has a column heading of "Edit Submission" (which is what the
# Jotform-created sheet column heading it) and contains the long number
# in the URL. The 2nd one has no column heading, and is just the words
# "Edit Submission". :-( CSV.DictReader therefore puts a value of
# "Edit Submission" in a dict entry of "None" (because it has no column
# heading).
#
# For our purposes here, just delete the "None" entry from the
# DictReader.
if None in row and row[None] == ['Edit Submission']:
del row[None]
# Is this submission between start and end?
if start is not None and end is not None:
submit_date = helpers.jotform_date_to_datetime(row['SubmitDate'])
if submit_date < start or submit_date > end:
continue
rows.append(row)
return rows
#-----------------------------------------------------------------------------
def read_jotform_gsheet(google, start, end, fieldnames, gfile_id, log):
log.info(f"Downloading Jotform raw data ({gfile_id})...")
# Some of the field names will be lists. In those cases, use the first
# field name in the list.
final_fieldnames = list()
final_fieldnames.extend(fieldnames['prelude'])
for member in fieldnames['members']:
final_fieldnames.extend(member)
final_fieldnames.extend(fieldnames['family'])
final_fieldnames.extend(fieldnames['epilog'])
csv_data = _export_gsheet_to_csv(google, start, end, gfile_id,
final_fieldnames, log)
# Deduplicate: save the last row number for any given FID
# (we only really care about the *last* entry that someone makes)
out_dict = dict()
for row in csv_data:
fid = row['fid']
# Skip the title row
if fid == 'fid':
continue
out_dict[fid] = row
# Turn this dictionary into a list of rows
out_list = [ out_dict[fid] for fid in sorted(out_dict) ]
return out_list, out_dict
##############################################################################
def setup_args():
tools.argparser.add_argument('--gdrive-folder-id',
help='If specified, upload a Google Sheet containing the results to this Team Drive folder')
tools.argparser.add_argument('--all',
action='store_const',
const=True,
help='If specified, run the comparison for all time (vs. running for the previous time period')
tools.argparser.add_argument('--smtp-auth-file',
required=True,
help='File containing SMTP AUTH username:password')
global gapp_id
tools.argparser.add_argument('--app-id',
default=gapp_id,
help='Filename containing Google application credentials')
global guser_cred_file
tools.argparser.add_argument('--user-credentials',
default=guser_cred_file,
help='Filename containing Google user credentials')
args = tools.argparser.parse_args()
return args
##############################################################################
def main():
global families, members
args = setup_args()
log = ECC.setup_logging(debug=False)
#---------------------------------------------------------------
# Calculate the start and end of when we are analyzing in the
# source data
start = None
end = None
if args.all:
time_period = 'all results to date'
else:
# If not supplied on the command line:
# Sun: skip
# Mon: everything from last 3 days (Sat+Sun)
# Tue-Fri: everything from yesterday
# Sat: skip
today = end.strftime('%a')
if today == 'Sat' or today == 'Sun':
print("It's the weekend. Nothing to do!")
exit(0)
elif today == 'Mon':
start = end - timedelta(days=3)
else:
start = end - timedelta(days=1)
# No one wants to see the microseconds
start = start - timedelta(microseconds=start.microsecond)
end = end - timedelta(microseconds=end.microsecond)
time_period = '{start} - {end}'.format(start=start, end=end)
log.info("Time period: {tp}".format(tp=time_period))
#---------------------------------------------------------------
log.info("Reading PDS data...")
(pds, pds_families,
pds_members) = PDSChurch.load_families_and_members(filename='pdschurch.sqlite3',
parishioners_only=True,
log=log)
#---------------------------------------------------------------
apis = {
'drive' : { 'scope' : Google.scopes['drive'],
'api_name' : 'drive',
'api_version' : 'v3', },
}
services = GoogleAuth.service_oauth_login(apis,
app_json=args.app_id,
user_json=args.user_credentials,
log=log)
google = services['drive']
#---------------------------------------------------------------
# Load all the results
log.info(f"Reading Jotform {stewardship_year} data...")
jotform_all_list, jotform_all_dict = read_jotform_gsheet(google,
start=None, end=None,
fieldnames=jotform_gsheet_columns,
gfile_id=jotform_gsheet_gfile_id,
log=log)
# Load a range of results
if start is None:
jotform_range_list = jotform_all_list.copy()
else:
jotform_range_list, jotform_range_dict = read_jotform_gsheet(google,
start=start, end=end,
fieldnames=jotform_gsheet_columns,
gfile_id=jotform_gsheet_gfile_id,
log=log)
#---------------------------------------------------------------
# These are periodic reports that are run during the campaign
if False:
# Stats of how many families have submitted, etc.
statistics_report(args, time_period, pds_members, pds_families,
jotform_all_list, log)
# A collection of all the random text comments that people
# submitted (so that staff members can act on them).
comments_gfile = None
comments_gfile = comments_report(args, google, start, end, time_period,
jotform_range_list, log)
# A comparison of this year's pledges vs. last year's pledges.
pledge_gfile = None
pledge_gfile = pledge_comparison_report(google, jotform_all_dict,
jotform_last_year, log)
send_reports_email(time_period, comments_gfile, pledge_gfile, args, log)
# These reports are generally run after the campaign
if True:
# Raw list of pledges (I think this is importable to PDS...?)
family_pledge_csv_report(args, google, pds_families, jotform_all_list, log)
# Raw list of families who submitted (this may be importable to PDS...?)
family_status_csv_report(args, google, pds_families, jotform_all_list, log)
# Per-ministry CSVs showing member status changes (given to
# staff members to review, and ultimately to make phone calls
# to followup).
member_ministry_csv_report(args, google, start, end, time_period,
pds_members, pds_families, jotform_range_list, log)
main()
| [
"jeff@squyres.com"
] | jeff@squyres.com |
f5ce343944e0e5aa368aec4ed178529bc5d92d25 | 46dc1ef28634ea1a2fdf419aeec4f60a001a3045 | /aldryn_blog/search_indexes.py | 415c439b8ce26c9dfe6cc975732aedf6b932d585 | [] | no_license | growlf/aldryn-blog | f143d256628f9d2584f23ef8c4680c89324b7d21 | 88d484677cb54f8650c4b69e3856e1d84dc7ef73 | refs/heads/master | 2021-01-21T03:09:44.545168 | 2014-09-11T22:32:37 | 2014-09-11T22:32:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,336 | py | # -*- coding: utf-8 -*-
from django.db.models import Q
from django.template import RequestContext
from aldryn_search.utils import get_index_base, strip_tags
from .conf import settings
from .models import Post
class BlogIndex(get_index_base()):
haystack_use_for_indexing = settings.ALDRYN_BLOG_SEARCH
INDEX_TITLE = True
def get_title(self, obj):
return obj.title
def get_description(self, obj):
return obj.lead_in
def get_language(self, obj):
return obj.language
def prepare_pub_date(self, obj):
return obj.publication_start
def get_index_queryset(self, language):
queryset = self.get_model().published.all()
return queryset.filter(Q(language=language)|Q(language__isnull=True))
def get_model(self):
return Post
def get_search_data(self, obj, language, request):
lead_in = self.get_description(obj)
text_bits = [strip_tags(lead_in)]
plugins = obj.content.cmsplugin_set.filter(language=language)
for base_plugin in plugins:
instance, plugin_type = base_plugin.get_plugin_instance()
if not instance is None:
content = strip_tags(instance.render_plugin(context=RequestContext(request)))
text_bits.append(content)
return ' '.join(text_bits)
| [
"commonzenpython@gmail.com"
] | commonzenpython@gmail.com |
274610d865dddc45fbe3bc9b639412a3e22bd912 | 56495b71151fb304957a6e4478bcd9538efc3ae4 | /sites/scnews/management/commands/crawl.py | 5a9681735b7b85197bef9db53008ac6c44c75697 | [] | no_license | qq40660/scnews | 4ea6ec18966f9b0662f8c3dc25cd2385bcb1b568 | 565701c3ba42d97cf7fb057b88793c6de2a582e2 | refs/heads/master | 2021-01-24T22:52:13.038343 | 2011-09-22T14:46:58 | 2011-09-22T14:46:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 536 | py | from datetime import datetime
from django.core.management.base import NoArgsCommand
from scnews.models import Resource
from scnews.management.crawl_helper import fetch
class Command(NoArgsCommand):
help = "do crawl"
def handle_noargs(self, **options):
reses = Resource.objects.all()
for res in reses:
if res.updated_on:
t = datetime.now() - res.updated_on
if (t.seconds + t.days * 3600 * 24)< res.interval:
continue
fetch(res)
| [
"zbirder@gmail.com"
] | zbirder@gmail.com |
494c511f36bae45d4e6f16d0623ac7874be3ea7d | 353def93fa77384ee3a5e3de98cfed318c480634 | /.history/week01/homework02/maoyanspiders/maoyanspiders/spiders/movies_20200627214717.py | 4371ba152db9d2cf063ba237ef9633f663fbe53a | [] | no_license | ydbB/Python001-class01 | d680abc3ea1ccaeb610751e3488421417d381156 | ad80037ccfc68d39125fa94d2747ab7394ac1be8 | refs/heads/master | 2022-11-25T11:27:45.077139 | 2020-07-19T12:35:12 | 2020-07-19T12:35:12 | 272,783,233 | 0 | 0 | null | 2020-06-16T18:28:15 | 2020-06-16T18:28:15 | null | UTF-8 | Python | false | false | 993 | py | # -*- coding: utf-8 -*-
import scrapy
from maoyanspiders.items import MaoyanspidersItem
# import xlml.etree
from bs4 import BeautifulSoup as bs
class MoviesSpider(scrapy.Spider):
name = 'movies'
allowed_domains = ['maoyan.com']
start_urls = ['http://maoyan.com/board/4']
# def parse(self, response):
# pass
def start_requests(self):
url = f'https://maoyan.com/board/4'
print(url)
yield scrapy.Request(url=url,callback=self.parse)
def parse(self, response):
soup = bs(response.text,'html.parser')
print(soup.text)
return soup
for i in soup.find_all('div',attrs={'class' : 'movie-item-info'}):\
item = MaoyanspidersItem()
link = 'https://maoyan.com/'+i.get('href'.text)
item['films_name'] = 'name'
item['release_time'] = "tiome"
yield scrapy.Request(url=link, meta={'item':item},callback=self.parse1)
return item
def parse1()
| [
"31039587+ydbB@users.noreply.github.com"
] | 31039587+ydbB@users.noreply.github.com |
20b05c2331ef559dbd95fad901ddccaa652a44fe | 4c44c593048fa4e00fb0334209632a286886efd9 | /import_template_pricelist_item/wizards/__init__.py | e9e9d3a81880c84d81cb7990a27496f16cf660a7 | [] | no_license | treytux/trey-addons | 0c3fec43c584d46bd299b4bca47dcc334bedca60 | 1cda42c0eae702684badce769f9ec053c59d6e42 | refs/heads/12.0 | 2023-06-08T21:56:09.945084 | 2023-05-29T10:05:53 | 2023-05-29T10:05:53 | 114,281,765 | 19 | 49 | null | 2023-05-29T10:05:55 | 2017-12-14T18:10:39 | Python | UTF-8 | Python | false | false | 285 | py | ###############################################################################
# For copyright and license notices, see __manifest__.py file in root directory
###############################################################################
from . import import_template_pricelist_item
| [
"roberto@trey.es"
] | roberto@trey.es |
32b9d52f74f5208eb15784bcc0eb738b10f01bcc | ec45bee420713f64d2d00a5d1c15a9a5f66a940b | /my_cv/polyp/images_checker.py | 229bbefbb64ab79b935446639eb8c5a0caf9188c | [
"MIT"
] | permissive | strawsyz/straw | a7dc5afef9525eeb3b1a471b5a90d869a3ba5084 | cdf785856941f7ea546aee56ebcda8801cbb04de | refs/heads/master | 2023-06-08T17:18:53.073514 | 2023-06-05T05:51:41 | 2023-06-05T05:51:41 | 253,447,370 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,071 | py | import os
from PIL import Image
from matplotlib import pyplot as plt
def read_img(file_name):
img = Image.open(file_name)
# 防止一个通道的图像无法正常显示
img = img.convert('RGB')
return img
def on_key_release(event):
if event.key == 'n':
if index[0] < len(file_names) - 1:
index[0] += 1
show_images(file_names[index[0]])
else:
print("It's the last image")
elif event.key == "b":
if index[0] > 0:
index[0] -= 1
show_images(file_names[index[0]])
else:
print("It's the first image")
def show_images(file_name):
fig.suptitle(file_name)
for dir_path, ax in zip(dir_paths, axs):
image_path = os.path.join(dir_path, file_name)
ax.imshow(read_img(image_path), cmap='gray')
ax.set_title(file_name)
ax.imshow(read_img(image_path))
plt.axis("off")
# ubuntu上调用两次的plt.show()的话会报错,要用下面的函数
fig.canvas.draw()
if __name__ == '__main__':
"""比较不同文件下的同名图像"""
file_names = []
# MASK_PATH = "D:\Download\datasets\polyp\\06\mask"
# EDGE_PATH = 'D:\Download\datasets\polyp\\06\edge'
# EDGE_PATH1 = "D:\Download\datasets\polyp\\06\edge1"
# dir_paths = [MASK_PATH, EDGE_PATH, EDGE_PATH1]
data_path = "/home/straw/Downloads/dataset/polyp/TMP/07/data"
mask_path = "/home/straw/Downloads/dataset/polyp/TMP/07/mask"
predict_path = "/home/straw/Download\models\polyp\\result/2020-08-06/"
predict_path = "/home/straw/Download\models\polyp\\result/2020-09-01/"
dir_paths = [data_path, mask_path, predict_path]
for file_name in os.listdir(dir_paths[-1]):
file_names.append(file_name)
fig, (axs) = plt.subplots(1, len(dir_paths))
fig.canvas.mpl_connect("key_release_event", on_key_release)
# 取消默认快捷键的注册
fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)
index = [0]
show_images(file_names[index[0]])
plt.show()
| [
"836400042@qq.com"
] | 836400042@qq.com |
44eee656ac7d9e1c47346f6e1961f4b82dae1008 | 2c7f025568bceb560888d26828aef30e5ae23393 | /src/concursos/migrations/0002_auto_20170321_1830.py | eb0f05da9b9d6366bebeae666869ac539f4f5492 | [] | no_license | GustavoCruz12/educacao | 6271ebc71830ee1964f8311d3ef21ec8abf58e50 | d0faa633ed1d588d84c74a3e15ccf5fa4dd9839e | refs/heads/master | 2022-12-08T09:34:42.066372 | 2018-08-03T06:38:49 | 2018-08-03T06:38:49 | 143,387,426 | 0 | 0 | null | 2022-12-08T00:01:52 | 2018-08-03T06:31:03 | Python | UTF-8 | Python | false | false | 615 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-21 18:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('concursos', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='concurso',
name='ano',
field=models.IntegerField(verbose_name='ano'),
),
migrations.AlterField(
model_name='concurso',
name='numero',
field=models.IntegerField(verbose_name='numero'),
),
]
| [
"gustavocruz201419@gmail.com"
] | gustavocruz201419@gmail.com |
eafcf1331a754155db8948c37117aff6404908f9 | 677002b757c0a1a00b450d9710a8ec6aeb9b9e9a | /tiago_public_ws/build/tiago_2dnav/catkin_generated/pkg.installspace.context.pc.py | 1d1e6f7bc9cb0beb82bfecb78ef6dcd0fbbae01c | [] | no_license | mrrocketraccoon/tiago_development | ce686c86459dbfe8623aa54cf4279021342887fb | a0539bdcf21b67ab902a4649b516dcb929c54042 | refs/heads/main | 2023-06-16T19:39:33.391293 | 2021-07-08T21:20:03 | 2021-07-08T21:20:03 | 384,249,894 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 369 | py | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "tiago_2dnav"
PROJECT_SPACE_DIR = "/tiago_public_ws/install"
PROJECT_VERSION = "2.0.6"
| [
"ricardoxcm@hotmail.com"
] | ricardoxcm@hotmail.com |
60686257e8848aa55f3f6ecb9c5d55e0fc77b012 | 00b405a49ac6108d24986243c4b52fa53fb58acc | /0376_wiggle_subsequence.py | 7fd34c5d4608ece36be102ba9360cc42b4674715 | [] | no_license | Shin-jay7/LeetCode | 0325983fff95bfbc43a528812582cbf9b7c0c2f2 | 953b0b19764744753f01c661da969bdab6521504 | refs/heads/master | 2023-07-19T07:17:21.513531 | 2023-07-15T06:05:06 | 2023-07-15T06:05:06 | 231,285,199 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 645 | py | from __future__ import annotations
from typing import List
from functools import cache
# Define by dp(i, 1) the biggest length of wiggle subsequense,
# which ends with element nums[i] and has and increasing status,
# and dp(i, -1) is the biggest length of wiggle subsequence,
# which ends with element nums[i] and has decreasing status.
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
n = len(nums)
@cache
def dp(i, s):
if i == 0:
return 1
return dp(i-1, -s) + 1 if (nums[i]-nums[i-1])*s < 0 else dp(i-1, s)
return max(dp(n-1, -1), dp(n-1, 1))
| [
"shin@jay7.net"
] | shin@jay7.net |
37a3374eaa6a21229e47b55bedf4daeb820c14eb | 0eaf0d3f0e96a839f2ef37b92d4db5eddf4b5e02 | /abc032/b.py | 18c4b5a9718a41bf8aae37119b0328701cef8699 | [] | no_license | silphire/atcoder | b7b02798a87048757745d99e8564397d1ca20169 | f214ef92f13bc5d6b290746d5a94e2faad20d8b0 | refs/heads/master | 2023-09-03T17:56:30.885166 | 2023-09-02T14:16:24 | 2023-09-02T14:16:24 | 245,110,029 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 125 | py | s = input().rstrip()
n = len(s)
k = int(input())
ans = set()
for i in range(n - k + 1):
ans.add(s[i:i+k])
print(len(ans)) | [
"silphire@gmail.com"
] | silphire@gmail.com |
3a78b3c9f78cf699f6619052bb18e27fc24b052f | b39d9ef9175077ac6f03b66d97b073d85b6bc4d0 | /Opraz_gastro-resistant_capsule,_hard_SmPC.py | 7a328ba25d2c90a2e76c4dff8053f689782d112c | [] | no_license | urudaro/data-ue | 2d840fdce8ba7e759b5551cb3ee277d046464fe0 | 176c57533b66754ee05a96a7429c3e610188e4aa | refs/heads/master | 2021-01-22T12:02:16.931087 | 2013-07-16T14:05:41 | 2013-07-16T14:05:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,160 | py | {'_data': [['Common',
[['Nervous system', u'Huvudv\xe4rk'],
['GI',
u'diarr\xe9, f\xf6rstoppning, buksm\xe4rtor, illam\xe5ende/ kr\xe4kningar och gasbildning']]],
['Uncommon',
[['Psychiatric', u'S\xf6mnbesv\xe4r Agitation,'],
['Nervous system', u'Yrsel, parestesier, d\xe5sighet'],
['Ear', u'Vertigo'],
['Hepato', u'\xd6kade lever-enzymer'],
['Skin', u'Dermatit, kl\xe5da, hudutslag, urtikaria'],
['Musculoskeletal',
u'H\xf6ft-, handleds-eller kotfrakture r (se Varningar och f\xf6rsiktighet [4.4.])'],
['General', u'Sjukdoms-k\xe4nsla, perifera \xf6dem']]],
['Rare',
[['Blood', u'Leukopeni, trombocytopeni'],
['Immune system',
u'\xd6verk\xe4nslighets-reaktioner s\xe5som feber, angio\xf6dem och anafylaktisk reaktion/chock'],
['Metabolism', u'Hyponatremi'],
['Psychiatric', u'f\xf6rvirring, depression'],
['Nervous system', u'Smakf\xf6r\xe4ndringar'],
['Eye', u'Dimsyn'],
['Respiratory', u'Bronkospasm'],
['GI', u'Muntorrhet, stomatit, gastrointestinal candida'],
['Hepato', u'Hepatit med eller utan gulsot'],
['Skin', u'H\xe5ravfall, fotosensibilitet'],
['Musculoskeletal', u'Artralgi, myalgi'],
['Renal', u'Interstitiell nefrit'],
['General', u'\xd6kad svettning']]],
['Very rare',
[['Blood', u'Pancytopeni, agranulocytos'],
['Psychiatric', u'Aggression, hallucinationer'],
['Hepato', u'Leversvikt, encefalopati hos leversjuka patienter'],
['Skin',
u'Erythema multiforme, Stevens-Johnsons syndrom, toxisk epidermal nekrolys (TEN)'],
['Musculoskeletal', u'Muskeltr\xf6tthet'],
['Reproductive system', u'Gynekomasti']]],
['Unknown',
[['Metabolism', u'Hypo-magnesemi (se Varningar och f\xf6rsiktighet [4.4.])']]]],
'_note': u' ?MSFU',
'_pages': [7, 9],
u'_rank': 29,
u'_type': u'MSFU'} | [
"urudaro@gmail.com"
] | urudaro@gmail.com |
28490f6396d9d23366dc94354780a129da17a33c | b3b713f0a713e14cdab774f5d9703add02fbb136 | /layouts/inconsistencias.py | a0c0f8ce9b95fe65eedb3422c72061127e722d22 | [] | no_license | DS4A-team34/ds4a_application | dba9da1d271396c2f50095ea86230cf2cf9f0c4d | 736c69e002cf4a46f83cbd8c522ee6b0029f0793 | refs/heads/master | 2023-01-10T08:48:44.084758 | 2020-11-16T02:26:31 | 2020-11-16T02:26:31 | 306,533,474 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,858 | py | import dash_core_components as dcc
import dash_html_components as html
import dash_daq as daq
from controls import df_x, grupo_dict, grupo_options, fig_top_contratistas_good, fig_top_contratistas_bad, figure_fields_incons,figure_similarity
available_indicators = df_x.entidadnombre.unique()
# Colors
bgcolor = "#f3f3f1" # mapbox light map land color
bar_bgcolor = "#b0bec5" # material blue-gray 200
bar_unselected_color = "#78909c" # material blue-gray 400
bar_color = "#546e7a" # material blue-gray 600
bar_selected_color = "#37474f" # material blue-gray 800
bar_unselected_opacity = 0.8
# Figure template
row_heights = [150, 500, 300]
template = {"layout": {"paper_bgcolor": bgcolor, "plot_bgcolor": bgcolor}}
def blank_fig(height):
"""
Build blank figure with the requested height
"""
return {
"data": [],
"layout": {
"height": height,
"template": template,
"xaxis": {"visible": False},
"yaxis": {"visible": False},
},
}
layout = html.Div(
[
html.H3('Métricas generales de inconsistencias'),
html.Div(
[
html.Div(
[dcc.Graph(id="avg-similarity", figure=figure_similarity)],
className="pretty_container twelve columns",
),
],
className="row flex-display",
),
html.Div(
[
html.Div(
[dcc.Graph(id="fields-inconsistencias", figure=figure_fields_incons)],
className="pretty_container twelve columns",
),
],
className="row flex-display",
),
html.Div(
[
html.Div(
[dcc.Graph(id="contratistas-bad", figure=fig_top_contratistas_bad)],
className="pretty_container twelve columns",
),
],
className="row flex-display",
),
# html.Div(
# [
# html.Div(
# [dcc.Graph(id="contratistas-good", figure=fig_top_contratistas_good)],
# className="pretty_container twelve columns",
# ),
# ],
# className="row flex-display",
# ),
html.H3('Control de inconsistencias por entidades'),
html.Div(id='main-selector', children=[
html.Div(id="select-container", children=[
html.P(
id="chart-selector", children="Filtrar por entidad:"),
dcc.Dropdown(id="entidad-dropdown",
options=[
{'label': i, 'value': i} for i in available_indicators],
value="Nombre de entidad",
)
],),
html.Div(id='select-grupo', children=[
html.P(
id="text-grupo", className="control_label", children="Filtrar por grupo del contrato:"),
dcc.RadioItems(id='radio-item-grupo',
className="dcc_control",
options=grupo_options,
value='Grupo',
labelStyle={'display': 'inline-block'}),
]),
],
# className="pretty_container"
),
html.Div(id='contenedor', children=[
html.Div(id='valor-contrato', children=[
html.H4(id='vc1', children=" Total valor cuantías"),
html.H5(id='total-valor-contrato-text', className="valor-text"),
],),
html.Div(id='valor-contrato1', children=[
html.H4(id='vc2', children=" Total valor cuantía con adiciones"),
html.H5(id='total-valor-adiciones-text', className="valor-text"),
],),
html.Div(id='valor-contrato2', children=[
html.H4(id='vc3', children=" Porcentaje promedio de similitud"),
daq.GraduatedBar(
id='ooc_graph_id',
color={
"gradient": True,
"ranges": {
"red": [0, 7],
"yellow": [7, 9],
"green": [9, 10],
}
},
showCurrentValue=True,
max=10,
value=0,
),
],),
html.Div(id='valor-contrato3', children=[
html.H4(id='vc4', children=" Cantidad de contratos"),
html.H5(id='total-cantidad-text', className="valor-text"),
],),
], style={'columnCount': 2}),
]
)
| [
"jjescobar@uninorte.edu.co"
] | jjescobar@uninorte.edu.co |
4c9f7a10aac9bcbb4fdd921caa723ca73f12358e | d475a6cf49c0b2d40895ff6d48ca9b0298643a87 | /pyleecan/Classes/Surface.py | 41c01627adfcca5da4eb333e28f6be696120ded0 | [
"Apache-2.0"
] | permissive | lyhehehe/pyleecan | 6c4a52b17a083fe29fdc8dcd989a3d20feb844d9 | 421e9a843bf30d796415c77dc934546adffd1cd7 | refs/heads/master | 2021-07-05T17:42:02.813128 | 2020-09-03T14:27:03 | 2020-09-03T14:27:03 | 176,678,325 | 2 | 0 | null | 2019-03-20T07:28:06 | 2019-03-20T07:28:06 | null | UTF-8 | Python | false | false | 6,513 | py | # -*- coding: utf-8 -*-
# File generated according to Generator/ClassesRef/Geometry/Surface.csv
# WARNING! All changes made in this file will be lost!
"""Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Geometry/Surface
"""
from os import linesep
from logging import getLogger
from ._check import check_var, raise_
from ..Functions.get_logger import get_logger
from ..Functions.save import save
from ._frozen import FrozenClass
# Import all class method
# Try/catch to remove unnecessary dependencies in unused method
try:
from ..Methods.Geometry.Surface.comp_mesh_dict import comp_mesh_dict
except ImportError as error:
comp_mesh_dict = error
try:
from ..Methods.Geometry.Surface.draw_FEMM import draw_FEMM
except ImportError as error:
draw_FEMM = error
try:
from ..Methods.Geometry.Surface.plot import plot
except ImportError as error:
plot = error
try:
from ..Methods.Geometry.Surface.split_line import split_line
except ImportError as error:
split_line = error
from ._check import InitUnKnowClassError
class Surface(FrozenClass):
"""SurfLine define by list of lines that delimit it, label and point reference."""
VERSION = 1
# Check ImportError to remove unnecessary dependencies in unused method
# cf Methods.Geometry.Surface.comp_mesh_dict
if isinstance(comp_mesh_dict, ImportError):
comp_mesh_dict = property(
fget=lambda x: raise_(
ImportError(
"Can't use Surface method comp_mesh_dict: " + str(comp_mesh_dict)
)
)
)
else:
comp_mesh_dict = comp_mesh_dict
# cf Methods.Geometry.Surface.draw_FEMM
if isinstance(draw_FEMM, ImportError):
draw_FEMM = property(
fget=lambda x: raise_(
ImportError("Can't use Surface method draw_FEMM: " + str(draw_FEMM))
)
)
else:
draw_FEMM = draw_FEMM
# cf Methods.Geometry.Surface.plot
if isinstance(plot, ImportError):
plot = property(
fget=lambda x: raise_(
ImportError("Can't use Surface method plot: " + str(plot))
)
)
else:
plot = plot
# cf Methods.Geometry.Surface.split_line
if isinstance(split_line, ImportError):
split_line = property(
fget=lambda x: raise_(
ImportError("Can't use Surface method split_line: " + str(split_line))
)
)
else:
split_line = split_line
# save method is available in all object
save = save
# generic copy method
def copy(self):
"""Return a copy of the class
"""
return type(self)(init_dict=self.as_dict())
# get_logger method is available in all object
get_logger = get_logger
def __init__(self, point_ref=0, label="", init_dict=None, init_str=None):
"""Constructor of the class. Can be use in three ways :
- __init__ (arg1 = 1, arg3 = 5) every parameters have name and default values
for Matrix, None will initialise the property with an empty Matrix
for pyleecan type, None will call the default constructor
- __init__ (init_dict = d) d must be a dictionnary with every properties as keys
- __init__ (init_str = s) s must be a string
s is the file path to load
ndarray or list can be given for Vector and Matrix
object or dict can be given for pyleecan Object"""
if init_str is not None: # Initialisation by str
from ..Functions.load import load
assert type(init_str) is str
# load the object from a file
obj = load(init_str)
assert type(obj) is type(self)
point_ref = obj.point_ref
label = obj.label
if init_dict is not None: # Initialisation by dict
assert type(init_dict) is dict
# Overwrite default value with init_dict content
if "point_ref" in list(init_dict.keys()):
point_ref = init_dict["point_ref"]
if "label" in list(init_dict.keys()):
label = init_dict["label"]
# Initialisation by argument
self.parent = None
self.point_ref = point_ref
self.label = label
# The class is frozen, for now it's impossible to add new properties
self._freeze()
def __str__(self):
"""Convert this objet in a readeable string (for print)"""
Surface_str = ""
if self.parent is None:
Surface_str += "parent = None " + linesep
else:
Surface_str += "parent = " + str(type(self.parent)) + " object" + linesep
Surface_str += "point_ref = " + str(self.point_ref) + linesep
Surface_str += 'label = "' + str(self.label) + '"' + linesep
return Surface_str
def __eq__(self, other):
"""Compare two objects (skip parent)"""
if type(other) != type(self):
return False
if other.point_ref != self.point_ref:
return False
if other.label != self.label:
return False
return True
def as_dict(self):
"""Convert this objet in a json seriable dict (can be use in __init__)
"""
Surface_dict = dict()
Surface_dict["point_ref"] = self.point_ref
Surface_dict["label"] = self.label
# The class name is added to the dict fordeserialisation purpose
Surface_dict["__class__"] = "Surface"
return Surface_dict
def _set_None(self):
"""Set all the properties to None (except pyleecan object)"""
self.point_ref = None
self.label = None
def _get_point_ref(self):
"""getter of point_ref"""
return self._point_ref
def _set_point_ref(self, value):
"""setter of point_ref"""
check_var("point_ref", value, "complex")
self._point_ref = value
point_ref = property(
fget=_get_point_ref,
fset=_set_point_ref,
doc=u"""Center of symmetry
:Type: complex
""",
)
def _get_label(self):
"""getter of label"""
return self._label
def _set_label(self, value):
"""setter of label"""
check_var("label", value, "str")
self._label = value
label = property(
fget=_get_label,
fset=_set_label,
doc=u"""Label of the surface
:Type: str
""",
)
| [
"sebgue@gmx.net"
] | sebgue@gmx.net |
aa41fce664fe83c78c8a1fa8dd4a14ce5af48850 | c23954da29144a7d75dde0a704748d886e02220b | /salt_main/salt/modules/postgres.py | 641f1d4c276cb40b229d0a0c92e1c8d6a0e683ff | [] | no_license | pombredanne/usystem | 5bac2db49057698d2cffb35e5977418bb85425a8 | 12527f14d61ca30e996368e65ba74931ed85e3c1 | refs/heads/master | 2021-09-24T10:44:22.261460 | 2018-10-08T14:19:35 | 2018-10-08T14:19:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 93,237 | py | # -*- coding: utf-8 -*-
'''
Module to provide Postgres compatibility to salt.
:configuration: In order to connect to Postgres, certain configuration is
required in /etc/usystem/minion on the relevant minions. Some sample configs
might look like::
postgres.host: 'localhost'
postgres.port: '5432'
postgres.user: 'postgres' -> db user
postgres.pass: ''
postgres.maintenance_db: 'postgres'
The default for the maintenance_db is 'postgres' and in most cases it can
be left at the default setting.
This data can also be passed into pillar. Options passed into opts will
overwrite options passed into pillar
:note: This module uses MD5 hashing which may not be compliant with certain
security audits.
:note: When installing postgres from the official postgres repos, on certain
linux distributions, either the psql or the initdb binary is *not*
automatically placed on the path. Add a configuration to the location
of the postgres bin's path to the relevant minion for this module::
postgres.bins_dir: '/usr/pgsql-9.5/bin/'
'''
# This pylint error is popping up where there are no colons?
# pylint: disable=E8203
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import datetime
import logging
import hashlib
import os
import re
import pipes
import tempfile
try:
import csv
HAS_CSV = True
except ImportError:
HAS_CSV = False
# Import salt libs
import salt.utils.files
import salt.utils.itertools
import salt.utils.odict
import salt.utils.path
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltInvocationError
from salt.utils.versions import LooseVersion as _LooseVersion
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip # pylint: disable=import-error,redefined-builtin
from salt.ext.six.moves import StringIO
log = logging.getLogger(__name__)
_DEFAULT_PASSWORDS_ENCRYPTION = True
_EXTENSION_NOT_INSTALLED = 'EXTENSION NOT INSTALLED'
_EXTENSION_INSTALLED = 'EXTENSION INSTALLED'
_EXTENSION_TO_UPGRADE = 'EXTENSION TO UPGRADE'
_EXTENSION_TO_MOVE = 'EXTENSION TO MOVE'
_EXTENSION_FLAGS = (
_EXTENSION_NOT_INSTALLED,
_EXTENSION_INSTALLED,
_EXTENSION_TO_UPGRADE,
_EXTENSION_TO_MOVE,
)
_PRIVILEGES_MAP = {
'a': 'INSERT',
'C': 'CREATE',
'D': 'TRUNCATE',
'c': 'CONNECT',
't': 'TRIGGER',
'r': 'SELECT',
'U': 'USAGE',
'T': 'TEMPORARY',
'w': 'UPDATE',
'X': 'EXECUTE',
'x': 'REFERENCES',
'd': 'DELETE',
'*': 'GRANT',
}
_PRIVILEGES_OBJECTS = frozenset(
(
'schema',
'tablespace',
'language',
'sequence',
'table',
'group',
'database',
'function',
)
)
_PRIVILEGE_TYPE_MAP = {
'table': 'arwdDxt',
'tablespace': 'C',
'language': 'U',
'sequence': 'rwU',
'schema': 'UC',
'database': 'CTc',
'function': 'X',
}
def __virtual__():
'''
Only load this module if the psql bin exist.
initdb bin might also be used, but its presence will be detected on runtime.
'''
utils = ['psql']
if not HAS_CSV:
return False
for util in utils:
if not salt.utils.path.which(util):
if not _find_pg_binary(util):
return (False, '{0} was not found'.format(util))
return True
def _find_pg_binary(util):
'''
... versionadded:: 2016.3.2
Helper function to locate various psql related binaries
'''
pg_bin_dir = __salt__['config.option']('postgres.bins_dir')
util_bin = salt.utils.path.which(util)
if not util_bin:
if pg_bin_dir:
return salt.utils.path.which(os.path.join(pg_bin_dir, util))
else:
return util_bin
def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None):
'''
Helper function to call psql, because the password requirement
makes this too much code to be repeated in each function below
'''
kwargs = {
'reset_system_locale': False,
'clean_env': True,
}
if runas is None:
if not host:
host = __salt__['config.option']('postgres.host')
if not host or host.startswith('/'):
if 'FreeBSD' in __grains__['os_family']:
runas = 'pgsql'
elif 'OpenBSD' in __grains__['os_family']:
runas = '_postgresql'
else:
runas = 'postgres'
if user is None:
user = runas
if runas:
kwargs['runas'] = runas
if password is None:
password = __salt__['config.option']('postgres.pass')
if password is not None:
pgpassfile = salt.utils.files.mkstemp(text=True)
with salt.utils.files.fopen(pgpassfile, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format(
'localhost' if not host or host.startswith('/') else host,
port if port else '*',
user if user else '*',
password,
)))
__salt__['file.chown'](pgpassfile, runas, '')
kwargs['env'] = {'PGPASSFILE': pgpassfile}
ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs)
if ret.get('retcode', 0) != 0:
log.error('Error connecting to Postgresql server')
if password is not None and not __salt__['file.remove'](pgpassfile):
log.warning('Remove PGPASSFILE failed')
return ret
def _run_initdb(name,
auth='password',
user=None,
password=None,
encoding='UTF8',
locale=None,
runas=None,
waldir=None,
checksums=False):
'''
Helper function to call initdb
'''
if runas is None:
if 'FreeBSD' in __grains__['os_family']:
runas = 'pgsql'
elif 'OpenBSD' in __grains__['os_family']:
runas = '_postgresql'
else:
runas = 'postgres'
if user is None:
user = runas
_INITDB_BIN = _find_pg_binary('initdb')
if not _INITDB_BIN:
raise CommandExecutionError('initdb executable not found.')
cmd = [
_INITDB_BIN,
'--pgdata={0}'.format(name),
'--username={0}'.format(user),
'--auth={0}'.format(auth),
'--encoding={0}'.format(encoding),
]
if locale is not None:
cmd.append('--locale={0}'.format(locale))
# intentionally use short option, as the long option name has been
# renamed from "xlogdir" to "waldir" in PostgreSQL 10
if waldir is not None:
cmd.append('-X')
cmd.append(waldir)
if checksums:
cmd.append('--data-checksums')
if password is not None:
pgpassfile = salt.utils.files.mkstemp(text=True)
with salt.utils.files.fopen(pgpassfile, 'w') as fp_:
fp_.write(salt.utils.stringutils.to_str('{0}'.format(password)))
__salt__['file.chown'](pgpassfile, runas, '')
cmd.extend([
'--pwfile={0}'.format(pgpassfile),
])
kwargs = dict(runas=runas, clean_env=True)
cmdstr = ' '.join([pipes.quote(c) for c in cmd])
ret = __salt__['cmd.run_all'](cmdstr, python_shell=False, **kwargs)
if ret.get('retcode', 0) != 0:
log.error('Error initilizing the postgres data directory')
if password is not None and not __salt__['file.remove'](pgpassfile):
log.warning('Removal of PGPASSFILE failed')
return ret
def version(user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
Return the version of a Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.version
'''
query = 'SELECT setting FROM pg_catalog.pg_settings ' \
'WHERE name = \'server_version\''
cmd = _psql_cmd('-c', query,
'-t',
host=host,
user=user,
port=port,
maintenance_db=maintenance_db,
password=password)
ret = _run_psql(
cmd, runas=runas, password=password, host=host, port=port, user=user)
for line in salt.utils.itertools.split(ret['stdout'], '\n'):
# Just return the first line
return line
def _parsed_version(user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
Returns the server version properly parsed and int casted for internal use.
If the Postgres server does not respond, None will be returned.
'''
psql_version = version(
user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas,
)
if psql_version:
return _LooseVersion(psql_version)
else:
log.warning('Attempt to parse version of Postgres server failed. '
'Is the server responding?')
return None
def _connection_defaults(user=None, host=None, port=None, maintenance_db=None):
'''
Returns a tuple of (user, host, port, db) with config, pillar, or default
values assigned to missing values.
'''
if not user:
user = __salt__['config.option']('postgres.user')
if not host:
host = __salt__['config.option']('postgres.host')
if not port:
port = __salt__['config.option']('postgres.port')
if not maintenance_db:
maintenance_db = __salt__['config.option']('postgres.maintenance_db')
return (user, host, port, maintenance_db)
def _psql_cmd(*args, **kwargs):
'''
Return string with fully composed psql command.
Accepts optional keyword arguments: user, host, port and maintenance_db,
as well as any number of positional arguments to be added to the end of
the command.
'''
(user, host, port, maintenance_db) = _connection_defaults(
kwargs.get('user'),
kwargs.get('host'),
kwargs.get('port'),
kwargs.get('maintenance_db'))
_PSQL_BIN = _find_pg_binary('psql')
cmd = [_PSQL_BIN,
'--no-align',
'--no-readline',
'--no-psqlrc',
'--no-password'] # Never prompt, handled in _run_psql.
if user:
cmd += ['--username', user]
if host:
cmd += ['--host', host]
if port:
cmd += ['--port', six.text_type(port)]
if not maintenance_db:
maintenance_db = 'postgres'
cmd.extend(['--dbname', maintenance_db])
cmd.extend(args)
return cmd
def _psql_prepare_and_run(cmd,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None,
user=None):
rcmd = _psql_cmd(
host=host, user=user, port=port,
maintenance_db=maintenance_db,
*cmd)
cmdret = _run_psql(
rcmd, runas=runas, password=password, host=host, port=port, user=user)
return cmdret
def psql_query(query, user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None, write=False):
'''
Run an SQL-Query and return the results as a list. This command
only supports SELECT statements. This limitation can be worked around
with a query like this:
WITH updated AS (UPDATE pg_authid SET rolconnlimit = 2000 WHERE
rolname = 'rolename' RETURNING rolconnlimit) SELECT * FROM updated;
query
The query string.
user
Database username, if different from config or default.
host
Database host, if different from config or default.
port
Database port, if different from the config or default.
maintenance_db
The database to run the query against.
password
User password, if different from the config or default.
runas
User to run the command as.
write
Mark query as READ WRITE transaction.
CLI Example:
.. code-block:: bash
salt '*' postgres.psql_query 'select * from pg_stat_activity'
'''
ret = []
csv_query = 'COPY ({0}) TO STDOUT WITH CSV HEADER'.format(
query.strip().rstrip(';'))
# Mark transaction as R/W to achieve write will be allowed
# Commit is necessary due to transaction
if write:
csv_query = 'START TRANSACTION READ WRITE; {0}; COMMIT TRANSACTION;'.format(csv_query)
# always use the same datestyle settings to allow parsing dates
# regardless what server settings are configured
cmdret = _psql_prepare_and_run(['-v', 'datestyle=ISO,MDY',
'-c', csv_query],
runas=runas,
host=host, user=user, port=port,
maintenance_db=maintenance_db,
password=password)
if cmdret['retcode'] > 0:
return ret
csv_file = StringIO(cmdret['stdout'])
header = {}
for row in csv.reader(csv_file,
delimiter=salt.utils.stringutils.to_str(','),
quotechar=salt.utils.stringutils.to_str('"')):
if not row:
continue
if not header:
header = row
continue
ret.append(dict(zip(header, row)))
# Remove 'COMMIT' message if query is inside R/W transction
if write:
ret = ret[0:-1]
return ret
# Database related actions
def db_list(user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
Return dictionary with information about databases of a Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.db_list
'''
ret = {}
query = (
'SELECT datname as "Name", pga.rolname as "Owner", '
'pg_encoding_to_char(encoding) as "Encoding", '
'datcollate as "Collate", datctype as "Ctype", '
'datacl as "Access privileges", spcname as "Tablespace" '
'FROM pg_database pgd, pg_roles pga, pg_tablespace pgts '
'WHERE pga.oid = pgd.datdba AND pgts.oid = pgd.dattablespace'
)
rows = psql_query(query, runas=runas, host=host, user=user,
port=port, maintenance_db=maintenance_db,
password=password)
for row in rows:
ret[row['Name']] = row
ret[row['Name']].pop('Name')
return ret
def db_exists(name, user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
Checks if a database exists on the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.db_exists 'dbname'
'''
databases = db_list(user=user, host=host, port=port,
maintenance_db=maintenance_db,
password=password, runas=runas)
return name in databases
# TODO properly implemented escaping
def _quote_ddl_value(value, quote="'"):
if value is None:
return None
if quote in value: # detect trivial sqli
raise SaltInvocationError(
'Unsupported character {0} in value: {1}'.format(quote, value))
return "{quote}{value}{quote}".format(quote=quote, value=value)
def db_create(name,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
tablespace=None,
encoding=None,
lc_collate=None,
lc_ctype=None,
owner=None,
template=None,
runas=None):
'''
Adds a databases to the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.db_create 'dbname'
salt '*' postgres.db_create 'dbname' template=template_postgis
'''
# Base query to create a database
query = 'CREATE DATABASE "{0}"'.format(name)
# "With"-options to create a database
with_args = salt.utils.odict.OrderedDict([
('TABLESPACE', _quote_ddl_value(tablespace, '"')),
# owner needs to be enclosed in double quotes so postgres
# doesn't get thrown by dashes in the name
('OWNER', _quote_ddl_value(owner, '"')),
('TEMPLATE', template),
('ENCODING', _quote_ddl_value(encoding)),
('LC_COLLATE', _quote_ddl_value(lc_collate)),
('LC_CTYPE', _quote_ddl_value(lc_ctype)),
])
with_chunks = []
for key, value in with_args.items():
if value is not None:
with_chunks += [key, '=', value]
# Build a final query
if with_chunks:
with_chunks.insert(0, ' WITH')
query += ' '.join(with_chunks)
# Execute the command
ret = _psql_prepare_and_run(['-c', query],
user=user, host=host, port=port,
maintenance_db=maintenance_db,
password=password, runas=runas)
return ret['retcode'] == 0
def db_alter(name, user=None, host=None, port=None, maintenance_db=None,
password=None, tablespace=None, owner=None, owner_recurse=False,
runas=None):
'''
Change tablespace or/and owner of database.
CLI Example:
.. code-block:: bash
salt '*' postgres.db_alter dbname owner=otheruser
'''
if not any((tablespace, owner)):
return True # Nothing todo?
if owner and owner_recurse:
ret = owner_to(name, owner,
user=user,
host=host,
port=port,
password=password,
runas=runas)
else:
queries = []
if owner:
queries.append('ALTER DATABASE "{0}" OWNER TO "{1}"'.format(
name, owner
))
if tablespace:
queries.append('ALTER DATABASE "{0}" SET TABLESPACE "{1}"'.format(
name, tablespace
))
for query in queries:
ret = _psql_prepare_and_run(['-c', query],
user=user, host=host, port=port,
maintenance_db=maintenance_db,
password=password, runas=runas)
if ret['retcode'] != 0:
return False
return True
def db_remove(name, user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
Removes a databases from the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.db_remove 'dbname'
'''
# db doesn't exist, proceed
query = 'DROP DATABASE "{0}"'.format(name)
ret = _psql_prepare_and_run(['-c', query],
user=user,
host=host,
port=port,
runas=runas,
maintenance_db=maintenance_db,
password=password)
return ret['retcode'] == 0
# Tablespace related actions
def tablespace_list(user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
Return dictionary with information about tablespaces of a Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.tablespace_list
.. versionadded:: 2015.8.0
'''
ret = {}
query = (
'SELECT spcname as "Name", pga.rolname as "Owner", spcacl as "ACL", '
'spcoptions as "Opts", pg_tablespace_location(pgts.oid) as "Location" '
'FROM pg_tablespace pgts, pg_roles pga WHERE pga.oid = pgts.spcowner'
)
rows = __salt__['postgres.psql_query'](query, runas=runas, host=host,
user=user, port=port,
maintenance_db=maintenance_db,
password=password)
for row in rows:
ret[row['Name']] = row
ret[row['Name']].pop('Name')
return ret
def tablespace_exists(name, user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
Checks if a tablespace exists on the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.tablespace_exists 'dbname'
.. versionadded:: 2015.8.0
'''
tablespaces = tablespace_list(user=user, host=host, port=port,
maintenance_db=maintenance_db,
password=password, runas=runas)
return name in tablespaces
def tablespace_create(name, location, options=None, owner=None, user=None,
host=None, port=None, maintenance_db=None, password=None,
runas=None):
'''
Adds a tablespace to the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.tablespace_create tablespacename '/path/datadir'
.. versionadded:: 2015.8.0
'''
owner_query = ''
options_query = ''
if owner:
owner_query = 'OWNER "{0}"'.format(owner)
# should come out looking like: 'OWNER postgres'
if options:
optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)]
options_query = 'WITH ( {0} )'.format(', '.join(optionstext))
# should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )'
query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name,
owner_query,
location,
options_query)
# Execute the command
ret = _psql_prepare_and_run(['-c', query],
user=user, host=host, port=port,
maintenance_db=maintenance_db,
password=password, runas=runas)
return ret['retcode'] == 0
def tablespace_alter(name, user=None, host=None, port=None, maintenance_db=None,
password=None, new_name=None, new_owner=None,
set_option=None, reset_option=None, runas=None):
'''
Change tablespace name, owner, or options.
CLI Example:
.. code-block:: bash
salt '*' postgres.tablespace_alter tsname new_owner=otheruser
salt '*' postgres.tablespace_alter index_space new_name=fast_raid
salt '*' postgres.tablespace_alter test set_option="{'seq_page_cost': '1.1'}"
salt '*' postgres.tablespace_alter tsname reset_option=seq_page_cost
.. versionadded:: 2015.8.0
'''
if not any([new_name, new_owner, set_option, reset_option]):
return True # Nothing todo?
queries = []
if new_name:
queries.append('ALTER TABLESPACE "{0}" RENAME TO "{1}"'.format(
name, new_name))
if new_owner:
queries.append('ALTER TABLESPACE "{0}" OWNER TO "{1}"'.format(
name, new_owner))
if set_option:
queries.append('ALTER TABLESPACE "{0}" SET ({1} = {2})'.format(
name, set_option.keys()[0], set_option.values()[0]))
if reset_option:
queries.append('ALTER TABLESPACE "{0}" RESET ({1})'.format(
name, reset_option))
for query in queries:
ret = _psql_prepare_and_run(['-c', query],
user=user, host=host, port=port,
maintenance_db=maintenance_db,
password=password, runas=runas)
if ret['retcode'] != 0:
return False
return True
def tablespace_remove(name, user=None, host=None, port=None,
maintenance_db=None, password=None, runas=None):
'''
Removes a tablespace from the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.tablespace_remove tsname
.. versionadded:: 2015.8.0
'''
query = 'DROP TABLESPACE "{0}"'.format(name)
ret = _psql_prepare_and_run(['-c', query],
user=user,
host=host,
port=port,
runas=runas,
maintenance_db=maintenance_db,
password=password)
return ret['retcode'] == 0
# User related actions
def user_list(user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None, return_password=False):
'''
Return a dict with information about users of a Postgres server.
Set return_password to True to get password hash in the result.
CLI Example:
.. code-block:: bash
salt '*' postgres.user_list
'''
ret = {}
ver = _parsed_version(user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas)
if ver:
if ver >= _LooseVersion('9.1'):
replication_column = 'pg_roles.rolreplication'
else:
replication_column = 'NULL'
if ver >= _LooseVersion('9.5'):
rolcatupdate_column = 'NULL'
else:
rolcatupdate_column = 'pg_roles.rolcatupdate'
else:
log.error('Could not retrieve Postgres version. Is Postgresql server running?')
return False
# will return empty string if return_password = False
_x = lambda s: s if return_password else ''
query = (''.join([
'SELECT '
'pg_roles.rolname as "name",'
'pg_roles.rolsuper as "superuser", '
'pg_roles.rolinherit as "inherits privileges", '
'pg_roles.rolcreaterole as "can create roles", '
'pg_roles.rolcreatedb as "can create databases", '
'{0} as "can update system catalogs", '
'pg_roles.rolcanlogin as "can login", '
'{1} as "replication", '
'pg_roles.rolconnlimit as "connections", '
'(SELECT array_agg(pg_roles2.rolname)'
' FROM pg_catalog.pg_auth_members'
' JOIN pg_catalog.pg_roles pg_roles2 ON (pg_auth_members.roleid = pg_roles2.oid)'
' WHERE pg_auth_members.member = pg_roles.oid) as "groups",'
'pg_roles.rolvaliduntil::timestamp(0) as "expiry time", '
'pg_roles.rolconfig as "defaults variables" '
, _x(', COALESCE(pg_shadow.passwd, pg_authid.rolpassword) as "password" '),
'FROM pg_roles '
, _x('LEFT JOIN pg_authid ON pg_roles.oid = pg_authid.oid ')
, _x('LEFT JOIN pg_shadow ON pg_roles.oid = pg_shadow.usesysid')
]).format(rolcatupdate_column, replication_column))
rows = psql_query(query,
runas=runas,
host=host,
user=user,
port=port,
maintenance_db=maintenance_db,
password=password)
def get_bool(rowdict, key):
'''
Returns the boolean value of the key, instead of 't' and 'f' strings.
'''
if rowdict[key] == 't':
return True
elif rowdict[key] == 'f':
return False
else:
return None
for row in rows:
retrow = {}
for key in ('superuser', 'inherits privileges', 'can create roles',
'can create databases', 'can update system catalogs',
'can login', 'replication', 'connections'):
retrow[key] = get_bool(row, key)
for date_key in ('expiry time',):
try:
retrow[date_key] = datetime.datetime.strptime(
row[date_key], '%Y-%m-%d %H:%M:%S')
except ValueError:
retrow[date_key] = None
retrow['defaults variables'] = row['defaults variables']
if return_password:
retrow['password'] = row['password']
# use csv reader to handle quoted roles correctly
retrow['groups'] = list(csv.reader([row['groups'].strip('{}')]))[0]
ret[row['name']] = retrow
return ret
def role_get(name, user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None, return_password=False):
'''
Return a dict with information about users of a Postgres server.
Set return_password to True to get password hash in the result.
CLI Example:
.. code-block:: bash
salt '*' postgres.role_get postgres
'''
all_users = user_list(user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas,
return_password=return_password)
try:
return all_users.get(name, None)
except AttributeError:
log.error('Could not retrieve Postgres role. Is Postgres running?')
return None
def user_exists(name,
user=None, host=None, port=None, maintenance_db=None,
password=None,
runas=None):
'''
Checks if a user exists on the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.user_exists 'username'
'''
return bool(
role_get(name,
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas,
return_password=False))
def _add_role_flag(string,
test,
flag,
cond=None,
prefix='NO',
addtxt='',
skip=False):
if not skip:
if cond is None:
cond = test
if test is not None:
if cond:
string = '{0} {1}'.format(string, flag)
else:
string = '{0} {2}{1}'.format(string, flag, prefix)
if addtxt:
string = '{0} {1}'.format(string, addtxt)
return string
def _maybe_encrypt_password(role,
password,
encrypted=_DEFAULT_PASSWORDS_ENCRYPTION):
'''
pgsql passwords are md5 hashes of the string: 'md5{password}{rolename}'
'''
if password is not None:
password = six.text_type(password)
if encrypted and password and not password.startswith('md5'):
password = "md5{0}".format(
hashlib.md5(salt.utils.stringutils.to_bytes('{0}{1}'.format(password, role))).hexdigest())
return password
def _role_cmd_args(name,
sub_cmd='',
typ_='role',
encrypted=None,
login=None,
connlimit=None,
inherit=None,
createdb=None,
createroles=None,
superuser=None,
groups=None,
replication=None,
rolepassword=None,
valid_until=None,
db_role=None):
if inherit is None:
if typ_ in ['user', 'group']:
inherit = True
if login is None:
if typ_ == 'user':
login = True
if typ_ == 'group':
login = False
# defaults to encrypted passwords (md5{password}{rolename})
if encrypted is None:
encrypted = _DEFAULT_PASSWORDS_ENCRYPTION
skip_passwd = False
escaped_password = ''
escaped_valid_until = ''
if not (
rolepassword is not None
# first is passwd set
# second is for handling NOPASSWD
and (
isinstance(rolepassword, six.string_types) and bool(rolepassword)
)
or (
isinstance(rolepassword, bool)
)
):
skip_passwd = True
if isinstance(rolepassword, six.string_types) and bool(rolepassword):
escaped_password = '\'{0}\''.format(
_maybe_encrypt_password(name,
rolepassword.replace('\'', '\'\''),
encrypted=encrypted))
if isinstance(valid_until, six.string_types) and bool(valid_until):
escaped_valid_until = '\'{0}\''.format(
valid_until.replace('\'', '\'\''),
)
skip_superuser = False
if bool(db_role) and bool(superuser) == bool(db_role['superuser']):
skip_superuser = True
flags = (
{'flag': 'INHERIT', 'test': inherit},
{'flag': 'CREATEDB', 'test': createdb},
{'flag': 'CREATEROLE', 'test': createroles},
{'flag': 'SUPERUSER', 'test': superuser,
'skip': skip_superuser},
{'flag': 'REPLICATION', 'test': replication},
{'flag': 'LOGIN', 'test': login},
{'flag': 'CONNECTION LIMIT',
'test': bool(connlimit),
'addtxt': six.text_type(connlimit),
'skip': connlimit is None},
{'flag': 'ENCRYPTED',
'test': (encrypted is not None and bool(rolepassword)),
'skip': skip_passwd or isinstance(rolepassword, bool),
'cond': encrypted,
'prefix': 'UN'},
{'flag': 'PASSWORD', 'test': bool(rolepassword),
'skip': skip_passwd,
'addtxt': escaped_password},
{'flag': 'VALID UNTIL',
'test': bool(valid_until),
'skip': valid_until is None,
'addtxt': escaped_valid_until},
)
for data in flags:
sub_cmd = _add_role_flag(sub_cmd, **data)
if sub_cmd.endswith('WITH'):
sub_cmd = sub_cmd.replace(' WITH', '')
if groups:
if isinstance(groups, list):
groups = ','.join(groups)
for group in groups.split(','):
sub_cmd = '{0}; GRANT "{1}" TO "{2}"'.format(sub_cmd, group, name)
return sub_cmd
def _role_create(name,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
createdb=None,
createroles=None,
encrypted=None,
superuser=None,
login=None,
connlimit=None,
inherit=None,
replication=None,
rolepassword=None,
valid_until=None,
typ_='role',
groups=None,
runas=None):
'''
Creates a Postgres role. Users and Groups are both roles in postgres.
However, users can login, groups cannot.
'''
# check if role exists
if user_exists(name, user, host, port, maintenance_db,
password=password, runas=runas):
log.info('%s \'%s\' already exists', typ_.capitalize(), name)
return False
sub_cmd = 'CREATE ROLE "{0}" WITH'.format(name)
sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args(
name,
typ_=typ_,
encrypted=encrypted,
login=login,
connlimit=connlimit,
inherit=inherit,
createdb=createdb,
createroles=createroles,
superuser=superuser,
groups=groups,
replication=replication,
rolepassword=rolepassword,
valid_until=valid_until
))
ret = _psql_prepare_and_run(['-c', sub_cmd],
runas=runas, host=host, user=user, port=port,
maintenance_db=maintenance_db,
password=password)
return ret['retcode'] == 0
def user_create(username,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
createdb=None,
createroles=None,
inherit=None,
login=None,
connlimit=None,
encrypted=None,
superuser=None,
replication=None,
rolepassword=None,
valid_until=None,
groups=None,
runas=None):
'''
Creates a Postgres user.
CLI Examples:
.. code-block:: bash
salt '*' postgres.user_create 'username' user='user' \\
host='hostname' port='port' password='password' \\
rolepassword='rolepassword' valid_until='valid_until'
'''
return _role_create(username,
typ_='user',
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
createdb=createdb,
createroles=createroles,
inherit=inherit,
login=login,
connlimit=connlimit,
encrypted=encrypted,
superuser=superuser,
replication=replication,
rolepassword=rolepassword,
valid_until=valid_until,
groups=groups,
runas=runas)
def _role_update(name,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
createdb=None,
typ_='role',
createroles=None,
inherit=None,
login=None,
connlimit=None,
encrypted=None,
superuser=None,
replication=None,
rolepassword=None,
valid_until=None,
groups=None,
runas=None):
'''
Updates a postgres role.
'''
role = role_get(name,
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas,
return_password=False)
# check if user exists
if not bool(role):
log.info(
'%s \'%s\' could not be found', typ_.capitalize(), name
)
return False
sub_cmd = 'ALTER ROLE "{0}" WITH'.format(name)
sub_cmd = '{0} {1}'.format(sub_cmd, _role_cmd_args(
name,
encrypted=encrypted,
login=login,
connlimit=connlimit,
inherit=inherit,
createdb=createdb,
createroles=createroles,
superuser=superuser,
groups=groups,
replication=replication,
rolepassword=rolepassword,
valid_until=valid_until,
db_role=role
))
ret = _psql_prepare_and_run(['-c', sub_cmd],
runas=runas, host=host, user=user, port=port,
maintenance_db=maintenance_db,
password=password)
return ret['retcode'] == 0
def user_update(username,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
createdb=None,
createroles=None,
encrypted=None,
superuser=None,
inherit=None,
login=None,
connlimit=None,
replication=None,
rolepassword=None,
valid_until=None,
groups=None,
runas=None):
'''
Updates a Postgres user.
CLI Examples:
.. code-block:: bash
salt '*' postgres.user_update 'username' user='user' \\
host='hostname' port='port' password='password' \\
rolepassword='rolepassword' valid_until='valid_until'
'''
return _role_update(username,
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
typ_='user',
inherit=inherit,
login=login,
connlimit=connlimit,
createdb=createdb,
createroles=createroles,
encrypted=encrypted,
superuser=superuser,
replication=replication,
rolepassword=rolepassword,
valid_until=valid_until,
groups=groups,
runas=runas)
def _role_remove(name, user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None):
'''
Removes a role from the Postgres Server
'''
# check if user exists
if not user_exists(name, user, host, port, maintenance_db,
password=password, runas=runas):
log.info('User \'%s\' does not exist', name)
return False
# user exists, proceed
sub_cmd = 'DROP ROLE "{0}"'.format(name)
_psql_prepare_and_run(
['-c', sub_cmd],
runas=runas, host=host, user=user, port=port,
maintenance_db=maintenance_db, password=password)
if not user_exists(name, user, host, port, maintenance_db,
password=password, runas=runas):
return True
else:
log.info('Failed to delete user \'%s\'.', name)
return False
def available_extensions(user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
List available postgresql extensions
CLI Example:
.. code-block:: bash
salt '*' postgres.available_extensions
'''
exts = []
query = (
'select * '
'from pg_available_extensions();'
)
ret = psql_query(query, user=user, host=host, port=port,
maintenance_db=maintenance_db,
password=password, runas=runas)
exts = {}
for row in ret:
if 'default_version' in row and 'name' in row:
exts[row['name']] = row
return exts
def installed_extensions(user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
List installed postgresql extensions
CLI Example:
.. code-block:: bash
salt '*' postgres.installed_extensions
'''
exts = []
query = (
'select a.*, b.nspname as schema_name '
'from pg_extension a, pg_namespace b where a.extnamespace = b.oid;'
)
ret = psql_query(query, user=user, host=host, port=port,
maintenance_db=maintenance_db,
password=password, runas=runas)
exts = {}
for row in ret:
if 'extversion' in row and 'extname' in row:
exts[row['extname']] = row
return exts
def get_available_extension(name,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Get info about an available postgresql extension
CLI Example:
.. code-block:: bash
salt '*' postgres.get_available_extension plpgsql
'''
return available_extensions(user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas).get(name, None)
def get_installed_extension(name,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Get info about an installed postgresql extension
CLI Example:
.. code-block:: bash
salt '*' postgres.get_installed_extension plpgsql
'''
return installed_extensions(user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas).get(name, None)
def is_available_extension(name,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Test if a specific extension is available
CLI Example:
.. code-block:: bash
salt '*' postgres.is_available_extension
'''
exts = available_extensions(user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas)
if name.lower() in [
a.lower()
for a in exts
]:
return True
return False
def _pg_is_older_ext_ver(a, b):
'''
Compare versions of extensions using salt.utils.versions.LooseVersion.
Returns ``True`` if version a is lesser than b.
'''
return _LooseVersion(a) < _LooseVersion(b)
def is_installed_extension(name,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Test if a specific extension is installed
CLI Example:
.. code-block:: bash
salt '*' postgres.is_installed_extension
'''
installed_ext = get_installed_extension(
name,
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas)
return bool(installed_ext)
def create_metadata(name,
ext_version=None,
schema=None,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Get lifecycle information about an extension
CLI Example:
.. code-block:: bash
salt '*' postgres.create_metadata adminpack
'''
installed_ext = get_installed_extension(
name,
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas)
ret = [_EXTENSION_NOT_INSTALLED]
if installed_ext:
ret = [_EXTENSION_INSTALLED]
if (
ext_version is not None
and _pg_is_older_ext_ver(
installed_ext.get('extversion', ext_version),
ext_version
)
):
ret.append(_EXTENSION_TO_UPGRADE)
if (
schema is not None
and installed_ext.get('extrelocatable', 'f') == 't'
and installed_ext.get('schema_name', schema) != schema
):
ret.append(_EXTENSION_TO_MOVE)
return ret
def drop_extension(name,
if_exists=None,
restrict=None,
cascade=None,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Drop an installed postgresql extension
CLI Example:
.. code-block:: bash
salt '*' postgres.drop_extension 'adminpack'
'''
if cascade is None:
cascade = True
if if_exists is None:
if_exists = False
if restrict is None:
restrict = False
args = ['DROP EXTENSION']
if if_exists:
args.append('IF EXISTS')
args.append(name)
if cascade:
args.append('CASCADE')
if restrict:
args.append('RESTRICT')
args.append(';')
cmd = ' '.join(args)
if is_installed_extension(name,
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas):
_psql_prepare_and_run(
['-c', cmd],
runas=runas, host=host, user=user, port=port,
maintenance_db=maintenance_db, password=password)
ret = not is_installed_extension(name,
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas)
if not ret:
log.info('Failed to drop ext: %s', name)
return ret
def create_extension(name,
if_not_exists=None,
schema=None,
ext_version=None,
from_version=None,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Install a postgresql extension
CLI Example:
.. code-block:: bash
salt '*' postgres.create_extension 'adminpack'
'''
if if_not_exists is None:
if_not_exists = True
mtdata = create_metadata(name,
ext_version=ext_version,
schema=schema,
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas)
installed = _EXTENSION_NOT_INSTALLED not in mtdata
installable = is_available_extension(name,
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas)
if installable:
if not installed:
args = ['CREATE EXTENSION']
if if_not_exists:
args.append('IF NOT EXISTS')
args.append('"{0}"'.format(name))
sargs = []
if schema:
sargs.append('SCHEMA "{0}"'.format(schema))
if ext_version:
sargs.append('VERSION {0}'.format(ext_version))
if from_version:
sargs.append('FROM {0}'.format(from_version))
if sargs:
args.append('WITH')
args.extend(sargs)
args.append(';')
cmd = ' '.join(args).strip()
else:
args = []
if schema and _EXTENSION_TO_MOVE in mtdata:
args.append('ALTER EXTENSION "{0}" SET SCHEMA "{1}";'.format(
name, schema))
if ext_version and _EXTENSION_TO_UPGRADE in mtdata:
args.append('ALTER EXTENSION "{0}" UPDATE TO {1};'.format(
name, ext_version))
cmd = ' '.join(args).strip()
if cmd:
_psql_prepare_and_run(
['-c', cmd],
runas=runas, host=host, user=user, port=port,
maintenance_db=maintenance_db, password=password)
mtdata = create_metadata(name,
ext_version=ext_version,
schema=schema,
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas)
ret = True
for i in _EXTENSION_FLAGS:
if (i in mtdata) and (i != _EXTENSION_INSTALLED):
ret = False
if not ret:
log.info('Failed to create ext: %s', name)
return ret
def user_remove(username,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Removes a user from the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.user_remove 'username'
'''
return _role_remove(username,
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas)
# Group related actions
def group_create(groupname,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
createdb=None,
createroles=None,
encrypted=None,
login=None,
inherit=None,
superuser=None,
replication=None,
rolepassword=None,
groups=None,
runas=None):
'''
Creates a Postgres group. A group is postgres is similar to a user, but
cannot login.
CLI Example:
.. code-block:: bash
salt '*' postgres.group_create 'groupname' user='user' \\
host='hostname' port='port' password='password' \\
rolepassword='rolepassword'
'''
return _role_create(groupname,
user=user,
typ_='group',
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
createdb=createdb,
createroles=createroles,
encrypted=encrypted,
login=login,
inherit=inherit,
superuser=superuser,
replication=replication,
rolepassword=rolepassword,
groups=groups,
runas=runas)
def group_update(groupname,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
createdb=None,
createroles=None,
encrypted=None,
inherit=None,
login=None,
superuser=None,
replication=None,
rolepassword=None,
groups=None,
runas=None):
'''
Updates a postgres group
CLI Examples:
.. code-block:: bash
salt '*' postgres.group_update 'username' user='user' \\
host='hostname' port='port' password='password' \\
rolepassword='rolepassword'
'''
return _role_update(groupname,
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
createdb=createdb,
typ_='group',
createroles=createroles,
encrypted=encrypted,
login=login,
inherit=inherit,
superuser=superuser,
replication=replication,
rolepassword=rolepassword,
groups=groups,
runas=runas)
def group_remove(groupname,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Removes a group from the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.group_remove 'groupname'
'''
return _role_remove(groupname,
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas)
def owner_to(dbname,
ownername,
user=None,
host=None,
port=None,
password=None,
runas=None):
'''
Set the owner of all schemas, functions, tables, views and sequences to
the given username.
CLI Example:
.. code-block:: bash
salt '*' postgres.owner_to 'dbname' 'username'
'''
sqlfile = tempfile.NamedTemporaryFile()
sqlfile.write('begin;\n')
sqlfile.write(
'alter database "{0}" owner to "{1}";\n'.format(
dbname, ownername
)
)
queries = (
# schemas
('alter schema {n} owner to {owner};',
'select quote_ident(schema_name) as n from '
'information_schema.schemata;'),
# tables and views
('alter table {n} owner to {owner};',
'select quote_ident(table_schema)||\'.\'||quote_ident(table_name) as '
'n from information_schema.tables where table_schema not in '
'(\'pg_catalog\', \'information_schema\');'),
# functions
('alter function {n} owner to {owner};',
'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p '
'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where '
'ns.nspname not in (\'pg_catalog\', \'information_schema\') '
' and not p.proisagg;'),
# aggregate functions
('alter aggregate {n} owner to {owner};',
'select p.oid::regprocedure::text as n from pg_catalog.pg_proc p '
'join pg_catalog.pg_namespace ns on p.pronamespace=ns.oid where '
'ns.nspname not in (\'pg_catalog\', \'information_schema\') '
'and p.proisagg;'),
# sequences
('alter sequence {n} owner to {owner};',
'select quote_ident(sequence_schema)||\'.\'||'
'quote_ident(sequence_name) as n from information_schema.sequences;')
)
for fmt, query in queries:
ret = psql_query(query, user=user, host=host, port=port,
maintenance_db=dbname, password=password, runas=runas)
for row in ret:
sqlfile.write(fmt.format(owner=ownername, n=row['n']) + '\n')
sqlfile.write('commit;\n')
sqlfile.flush()
os.chmod(sqlfile.name, 0o644) # ensure psql can read the file
# run the generated sqlfile in the db
cmdret = _psql_prepare_and_run(['-f', sqlfile.name],
user=user,
runas=runas,
host=host,
port=port,
password=password,
maintenance_db=dbname)
return cmdret
# Schema related actions
def schema_create(dbname, name, owner=None,
user=None,
db_user=None, db_password=None,
db_host=None, db_port=None):
'''
Creates a Postgres schema.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_create dbname name owner='owner' \\
user='user' \\
db_user='user' db_password='password'
db_host='hostname' db_port='port'
'''
# check if schema exists
if schema_exists(dbname, name, user=user,
db_user=db_user, db_password=db_password,
db_host=db_host, db_port=db_port):
log.info('\'%s\' already exists in \'%s\'', name, dbname)
return False
sub_cmd = 'CREATE SCHEMA "{0}"'.format(name)
if owner is not None:
sub_cmd = '{0} AUTHORIZATION "{1}"'.format(sub_cmd, owner)
ret = _psql_prepare_and_run(['-c', sub_cmd],
user=db_user, password=db_password,
port=db_port, host=db_host,
maintenance_db=dbname, runas=user)
return ret['retcode'] == 0
def schema_remove(dbname, name,
user=None,
db_user=None, db_password=None,
db_host=None, db_port=None):
'''
Removes a schema from the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_remove dbname schemaname
dbname
Database name we work on
schemaname
The schema's name we'll remove
user
System user all operations should be performed on behalf of
db_user
database username if different from config or default
db_password
user password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default
'''
# check if schema exists
if not schema_exists(dbname, name, user=None,
db_user=db_user, db_password=db_password,
db_host=db_host, db_port=db_port):
log.info('Schema \'%s\' does not exist in \'%s\'', name, dbname)
return False
# schema exists, proceed
sub_cmd = 'DROP SCHEMA "{0}"'.format(name)
_psql_prepare_and_run(
['-c', sub_cmd],
runas=user,
maintenance_db=dbname,
host=db_host, user=db_user, port=db_port, password=db_password)
if not schema_exists(dbname, name, user,
db_user=db_user, db_password=db_password,
db_host=db_host, db_port=db_port):
return True
else:
log.info('Failed to delete schema \'%s\'.', name)
return False
def schema_exists(dbname, name, user=None,
db_user=None, db_password=None,
db_host=None, db_port=None):
'''
Checks if a schema exists on the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_exists dbname schemaname
dbname
Database name we query on
name
Schema name we look for
user
The system user the operation should be performed on behalf of
db_user
database username if different from config or default
db_password
user password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default
'''
return bool(
schema_get(dbname, name, user=user,
db_user=db_user,
db_host=db_host,
db_port=db_port,
db_password=db_password))
def schema_get(dbname, name, user=None,
db_user=None, db_password=None,
db_host=None, db_port=None):
'''
Return a dict with information about schemas in a database.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_get dbname name
dbname
Database name we query on
name
Schema name we look for
user
The system user the operation should be performed on behalf of
db_user
database username if different from config or default
db_password
user password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default
'''
all_schemas = schema_list(dbname, user=user,
db_user=db_user,
db_host=db_host,
db_port=db_port,
db_password=db_password)
try:
return all_schemas.get(name, None)
except AttributeError:
log.error('Could not retrieve Postgres schema. Is Postgres running?')
return False
def schema_list(dbname, user=None,
db_user=None, db_password=None,
db_host=None, db_port=None):
'''
Return a dict with information about schemas in a Postgres database.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_list dbname
dbname
Database name we query on
user
The system user the operation should be performed on behalf of
db_user
database username if different from config or default
db_password
user password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default
'''
ret = {}
query = (''.join([
'SELECT '
'pg_namespace.nspname as "name",'
'pg_namespace.nspacl as "acl", '
'pg_roles.rolname as "owner" '
'FROM pg_namespace '
'LEFT JOIN pg_roles ON pg_roles.oid = pg_namespace.nspowner '
]))
rows = psql_query(query, runas=user,
host=db_host,
user=db_user,
port=db_port,
maintenance_db=dbname,
password=db_password)
for row in rows:
retrow = {}
for key in ('owner', 'acl'):
retrow[key] = row[key]
ret[row['name']] = retrow
return ret
def language_list(
maintenance_db,
user=None,
host=None,
port=None,
password=None,
runas=None):
'''
.. versionadded:: 2016.3.0
Return a list of languages in a database.
CLI Example:
.. code-block:: bash
salt '*' postgres.language_list dbname
maintenance_db
The database to check
user
database username if different from config or default
password
user password if any password for a specified user
host
Database host if different from config or default
port
Database port if different from config or default
runas
System user all operations should be performed on behalf of
'''
ret = {}
query = 'SELECT lanname AS "Name" FROM pg_language'
rows = psql_query(
query,
runas=runas,
host=host,
user=user,
port=port,
maintenance_db=maintenance_db,
password=password)
for row in rows:
ret[row['Name']] = row['Name']
return ret
def language_exists(
name,
maintenance_db,
user=None,
host=None,
port=None,
password=None,
runas=None):
'''
.. versionadded:: 2016.3.0
Checks if language exists in a database.
CLI Example:
.. code-block:: bash
salt '*' postgres.language_exists plpgsql dbname
name
Language to check for
maintenance_db
The database to check in
user
database username if different from config or default
password
user password if any password for a specified user
host
Database host if different from config or default
port
Database port if different from config or default
runas
System user all operations should be performed on behalf of
'''
languages = language_list(
maintenance_db, user=user, host=host,
port=port, password=password,
runas=runas)
return name in languages
def language_create(name,
maintenance_db,
user=None,
host=None,
port=None,
password=None,
runas=None):
'''
.. versionadded:: 2016.3.0
Installs a language into a database
CLI Example:
.. code-block:: bash
salt '*' postgres.language_create plpgsql dbname
name
Language to install
maintenance_db
The database to install the language in
user
database username if different from config or default
password
user password if any password for a specified user
host
Database host if different from config or default
port
Database port if different from config or default
runas
System user all operations should be performed on behalf of
'''
if language_exists(name, maintenance_db):
log.info('Language %s already exists in %s', name, maintenance_db)
return False
query = 'CREATE LANGUAGE {0}'.format(name)
ret = _psql_prepare_and_run(['-c', query],
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas)
return ret['retcode'] == 0
def language_remove(name,
maintenance_db,
user=None,
host=None,
port=None,
password=None,
runas=None):
'''
.. versionadded:: 2016.3.0
Removes a language from a database
CLI Example:
.. code-block:: bash
salt '*' postgres.language_remove plpgsql dbname
name
Language to remove
maintenance_db
The database to install the language in
user
database username if different from config or default
password
user password if any password for a specified user
host
Database host if different from config or default
port
Database port if different from config or default
runas
System user all operations should be performed on behalf of
'''
if not language_exists(name, maintenance_db):
log.info('Language %s does not exist in %s', name, maintenance_db)
return False
query = 'DROP LANGUAGE {0}'.format(name)
ret = _psql_prepare_and_run(['-c', query],
user=user,
host=host,
port=port,
runas=runas,
maintenance_db=maintenance_db,
password=password)
return ret['retcode'] == 0
def _make_privileges_list_query(name, object_type, prepend):
'''
Generate the SQL required for specific object type
'''
if object_type == 'table':
query = (' '.join([
'SELECT relacl AS name',
'FROM pg_catalog.pg_class c',
'JOIN pg_catalog.pg_namespace n',
'ON n.oid = c.relnamespace',
"WHERE nspname = '{0}'",
"AND relname = '{1}'",
"AND relkind = 'r'",
'ORDER BY relname',
])).format(prepend, name)
elif object_type == 'sequence':
query = (' '.join([
'SELECT relacl AS name',
'FROM pg_catalog.pg_class c',
'JOIN pg_catalog.pg_namespace n',
'ON n.oid = c.relnamespace',
"WHERE nspname = '{0}'",
"AND relname = '{1}'",
"AND relkind = 'S'",
'ORDER BY relname',
])).format(prepend, name)
elif object_type == 'schema':
query = (' '.join([
'SELECT nspacl AS name',
'FROM pg_catalog.pg_namespace',
"WHERE nspname = '{0}'",
'ORDER BY nspname',
])).format(name)
elif object_type == 'function':
query = (' '.join([
'SELECT proacl AS name',
'FROM pg_catalog.pg_proc p',
'JOIN pg_catalog.pg_namespace n',
'ON n.oid = p.pronamespace',
"WHERE nspname = '{0}'",
"AND p.oid::regprocedure::text = '{1}'",
'ORDER BY proname, proargtypes',
])).format(prepend, name)
elif object_type == 'tablespace':
query = (' '.join([
'SELECT spcacl AS name',
'FROM pg_catalog.pg_tablespace',
"WHERE spcname = '{0}'",
'ORDER BY spcname',
])).format(name)
elif object_type == 'language':
query = (' '.join([
'SELECT lanacl AS name',
'FROM pg_catalog.pg_language',
"WHERE lanname = '{0}'",
'ORDER BY lanname',
])).format(name)
elif object_type == 'database':
query = (' '.join([
'SELECT datacl AS name',
'FROM pg_catalog.pg_database',
"WHERE datname = '{0}'",
'ORDER BY datname',
])).format(name)
elif object_type == 'group':
query = (' '.join([
'SELECT rolname, admin_option',
'FROM pg_catalog.pg_auth_members m',
'JOIN pg_catalog.pg_roles r',
'ON m.member=r.oid',
'WHERE m.roleid IN',
'(SELECT oid',
'FROM pg_catalog.pg_roles',
"WHERE rolname='{0}')",
'ORDER BY rolname',
])).format(name)
return query
def _get_object_owner(name,
object_type,
prepend='public',
maintenance_db=None,
user=None,
host=None,
port=None,
password=None,
runas=None):
'''
Return the owner of a postgres object
'''
if object_type == 'table':
query = (' '.join([
'SELECT tableowner AS name',
'FROM pg_tables',
"WHERE schemaname = '{0}'",
"AND tablename = '{1}'"
])).format(prepend, name)
elif object_type == 'sequence':
query = (' '.join([
'SELECT rolname AS name',
'FROM pg_catalog.pg_class c',
'JOIN pg_roles r',
'ON c.relowner = r.oid',
'JOIN pg_catalog.pg_namespace n',
'ON n.oid = c.relnamespace',
"WHERE relkind='S'",
"AND nspname='{0}'",
"AND relname = '{1}'",
])).format(prepend, name)
elif object_type == 'schema':
query = (' '.join([
'SELECT rolname AS name',
'FROM pg_namespace n',
'JOIN pg_roles r',
'ON n.nspowner = r.oid',
"WHERE nspname = '{0}'",
])).format(name)
elif object_type == 'function':
query = (' '.join([
'SELECT rolname AS name',
'FROM pg_catalog.pg_proc p',
'JOIN pg_catalog.pg_namespace n',
'ON n.oid = p.pronamespace',
"WHERE nspname = '{0}'",
"AND p.oid::regprocedure::text = '{1}'",
'ORDER BY proname, proargtypes',
])).format(prepend, name)
elif object_type == 'tablespace':
query = (' '.join([
'SELECT rolname AS name',
'FROM pg_tablespace t',
'JOIN pg_roles r',
'ON t.spcowner = r.oid',
"WHERE spcname = '{0}'",
])).format(name)
elif object_type == 'language':
query = (' '.join([
'SELECT rolname AS name',
'FROM pg_language l',
'JOIN pg_roles r',
'ON l.lanowner = r.oid',
"WHERE lanname = '{0}'",
])).format(name)
elif object_type == 'database':
query = (' '.join([
'SELECT rolname AS name',
'FROM pg_database d',
'JOIN pg_roles r',
'ON d.datdba = r.oid',
"WHERE datname = '{0}'",
])).format(name)
rows = psql_query(
query,
runas=runas,
host=host,
user=user,
port=port,
maintenance_db=maintenance_db,
password=password)
try:
ret = rows[0]['name']
except IndexError:
ret = None
return ret
def _validate_privileges(object_type, privs, privileges):
'''
Validate the supplied privileges
'''
if object_type != 'group':
_perms = [_PRIVILEGES_MAP[perm]
for perm in _PRIVILEGE_TYPE_MAP[object_type]]
_perms.append('ALL')
if object_type not in _PRIVILEGES_OBJECTS:
raise SaltInvocationError(
'Invalid object_type: {0} provided'.format(object_type))
if not set(privs).issubset(set(_perms)):
raise SaltInvocationError(
'Invalid privilege(s): {0} provided for object {1}'.format(
privileges, object_type))
else:
if privileges:
raise SaltInvocationError(
'The privileges option should not '
'be set for object_type group')
def _mod_priv_opts(object_type, privileges):
'''
Format options
'''
object_type = object_type.lower()
privileges = '' if privileges is None else privileges
_privs = re.split(r'\s?,\s?', privileges.upper())
return object_type, privileges, _privs
def _process_priv_part(perms):
'''
Process part
'''
_tmp = {}
previous = None
for perm in perms:
if previous is None:
_tmp[_PRIVILEGES_MAP[perm]] = False
previous = _PRIVILEGES_MAP[perm]
else:
if perm == '*':
_tmp[previous] = True
else:
_tmp[_PRIVILEGES_MAP[perm]] = False
previous = _PRIVILEGES_MAP[perm]
return _tmp
def privileges_list(
name,
object_type,
prepend='public',
maintenance_db=None,
user=None,
host=None,
port=None,
password=None,
runas=None):
'''
.. versionadded:: 2016.3.0
Return a list of privileges for the specified object.
CLI Example:
.. code-block:: bash
salt '*' postgres.privileges_list table_name table maintenance_db=db_name
name
Name of the object for which the permissions should be returned
object_type
The object type, which can be one of the following:
- table
- sequence
- schema
- tablespace
- language
- database
- group
- function
prepend
Table and Sequence object types live under a schema so this should be
provided if the object is not under the default `public` schema
maintenance_db
The database to connect to
user
database username if different from config or default
password
user password if any password for a specified user
host
Database host if different from config or default
port
Database port if different from config or default
runas
System user all operations should be performed on behalf of
'''
object_type = object_type.lower()
query = _make_privileges_list_query(name, object_type, prepend)
if object_type not in _PRIVILEGES_OBJECTS:
raise SaltInvocationError(
'Invalid object_type: {0} provided'.format(object_type))
rows = psql_query(
query,
runas=runas,
host=host,
user=user,
port=port,
maintenance_db=maintenance_db,
password=password)
ret = {}
for row in rows:
if object_type != 'group':
result = row['name']
result = result.strip('{}')
parts = result.split(',')
for part in parts:
perms_part, _ = part.split('/')
rolename, perms = perms_part.split('=')
if rolename == '':
rolename = 'public'
_tmp = _process_priv_part(perms)
ret[rolename] = _tmp
else:
if row['admin_option'] == 't':
admin_option = True
else:
admin_option = False
ret[row['rolname']] = admin_option
return ret
def has_privileges(name,
object_name,
object_type,
privileges=None,
grant_option=None,
prepend='public',
maintenance_db=None,
user=None,
host=None,
port=None,
password=None,
runas=None):
'''
.. versionadded:: 2016.3.0
Check if a role has the specified privileges on an object
CLI Example:
.. code-block:: bash
salt '*' postgres.has_privileges user_name table_name table \\
SELECT,INSERT maintenance_db=db_name
name
Name of the role whose privileges should be checked on object_type
object_name
Name of the object on which the check is to be performed
object_type
The object type, which can be one of the following:
- table
- sequence
- schema
- tablespace
- language
- database
- group
- function
privileges
Comma separated list of privileges to check, from the list below:
- INSERT
- CREATE
- TRUNCATE
- CONNECT
- TRIGGER
- SELECT
- USAGE
- TEMPORARY
- UPDATE
- EXECUTE
- REFERENCES
- DELETE
- ALL
grant_option
If grant_option is set to True, the grant option check is performed
prepend
Table and Sequence object types live under a schema so this should be
provided if the object is not under the default `public` schema
maintenance_db
The database to connect to
user
database username if different from config or default
password
user password if any password for a specified user
host
Database host if different from config or default
port
Database port if different from config or default
runas
System user all operations should be performed on behalf of
'''
object_type, privileges, _privs = _mod_priv_opts(object_type, privileges)
_validate_privileges(object_type, _privs, privileges)
if object_type != 'group':
owner = _get_object_owner(object_name, object_type, prepend=prepend,
maintenance_db=maintenance_db, user=user, host=host, port=port,
password=password, runas=runas)
if owner is not None and name == owner:
return True
_privileges = privileges_list(object_name, object_type, prepend=prepend,
maintenance_db=maintenance_db, user=user, host=host, port=port,
password=password, runas=runas)
if name in _privileges:
if object_type == 'group':
if grant_option:
retval = _privileges[name]
else:
retval = True
return retval
else:
_perms = _PRIVILEGE_TYPE_MAP[object_type]
if grant_option:
perms = dict((_PRIVILEGES_MAP[perm], True) for perm in _perms)
retval = perms == _privileges[name]
else:
perms = [_PRIVILEGES_MAP[perm] for perm in _perms]
if 'ALL' in _privs:
retval = perms.sort() == _privileges[name].keys().sort()
else:
retval = set(_privs).issubset(
set(_privileges[name].keys()))
return retval
return False
def privileges_grant(name,
object_name,
object_type,
privileges=None,
grant_option=None,
prepend='public',
maintenance_db=None,
user=None,
host=None,
port=None,
password=None,
runas=None):
'''
.. versionadded:: 2016.3.0
Grant privileges on a postgres object
CLI Example:
.. code-block:: bash
salt '*' postgres.privileges_grant user_name table_name table \\
SELECT,UPDATE maintenance_db=db_name
name
Name of the role to which privileges should be granted
object_name
Name of the object on which the grant is to be performed
object_type
The object type, which can be one of the following:
- table
- sequence
- schema
- tablespace
- language
- database
- group
- function
privileges
Comma separated list of privileges to grant, from the list below:
- INSERT
- CREATE
- TRUNCATE
- CONNECT
- TRIGGER
- SELECT
- USAGE
- TEMPORARY
- UPDATE
- EXECUTE
- REFERENCES
- DELETE
- ALL
grant_option
If grant_option is set to True, the recipient of the privilege can
in turn grant it to others
prepend
Table and Sequence object types live under a schema so this should be
provided if the object is not under the default `public` schema
maintenance_db
The database to connect to
user
database username if different from config or default
password
user password if any password for a specified user
host
Database host if different from config or default
port
Database port if different from config or default
runas
System user all operations should be performed on behalf of
'''
object_type, privileges, _privs = _mod_priv_opts(object_type, privileges)
_validate_privileges(object_type, _privs, privileges)
if has_privileges(name, object_name, object_type, privileges,
prepend=prepend, maintenance_db=maintenance_db, user=user,
host=host, port=port, password=password, runas=runas):
log.info('The object: %s of type: %s already has privileges: %s set',
object_name, object_type, privileges)
return False
_grants = ','.join(_privs)
if object_type in ['table', 'sequence']:
on_part = '{0}."{1}"'.format(prepend, object_name)
elif object_type == 'function':
on_part = '{0}'.format(object_name)
else:
on_part = '"{0}"'.format(object_name)
if grant_option:
if object_type == 'group':
query = 'GRANT {0} TO "{1}" WITH ADMIN OPTION'.format(
object_name, name)
elif (object_type in ('table', 'sequence') and
object_name.upper() == 'ALL'):
query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO ' \
'"{3}" WITH GRANT OPTION'.format(
_grants, object_type.upper(), prepend, name)
else:
query = 'GRANT {0} ON {1} {2} TO "{3}" WITH GRANT OPTION'.format(
_grants, object_type.upper(), on_part, name)
else:
if object_type == 'group':
query = 'GRANT {0} TO "{1}"'.format(object_name, name)
elif (object_type in ('table', 'sequence') and
object_name.upper() == 'ALL'):
query = 'GRANT {0} ON ALL {1}S IN SCHEMA {2} TO "{3}"'.format(
_grants, object_type.upper(), prepend, name)
else:
query = 'GRANT {0} ON {1} {2} TO "{3}"'.format(
_grants, object_type.upper(), on_part, name)
ret = _psql_prepare_and_run(['-c', query],
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas)
return ret['retcode'] == 0
def privileges_revoke(name,
object_name,
object_type,
privileges=None,
prepend='public',
maintenance_db=None,
user=None,
host=None,
port=None,
password=None,
runas=None):
'''
.. versionadded:: 2016.3.0
Revoke privileges on a postgres object
CLI Example:
.. code-block:: bash
salt '*' postgres.privileges_revoke user_name table_name table \\
SELECT,UPDATE maintenance_db=db_name
name
Name of the role whose privileges should be revoked
object_name
Name of the object on which the revoke is to be performed
object_type
The object type, which can be one of the following:
- table
- sequence
- schema
- tablespace
- language
- database
- group
- function
privileges
Comma separated list of privileges to revoke, from the list below:
- INSERT
- CREATE
- TRUNCATE
- CONNECT
- TRIGGER
- SELECT
- USAGE
- TEMPORARY
- UPDATE
- EXECUTE
- REFERENCES
- DELETE
- ALL
maintenance_db
The database to connect to
user
database username if different from config or default
password
user password if any password for a specified user
host
Database host if different from config or default
port
Database port if different from config or default
runas
System user all operations should be performed on behalf of
'''
object_type, privileges, _privs = _mod_priv_opts(object_type, privileges)
_validate_privileges(object_type, _privs, privileges)
if not has_privileges(name, object_name, object_type, privileges,
prepend=prepend, maintenance_db=maintenance_db, user=user,
host=host, port=port, password=password, runas=runas):
log.info('The object: %s of type: %s does not'
' have privileges: %s set', object_name, object_type, privileges)
return False
_grants = ','.join(_privs)
if object_type in ['table', 'sequence']:
on_part = '{0}.{1}'.format(prepend, object_name)
else:
on_part = object_name
if object_type == 'group':
query = 'REVOKE {0} FROM {1}'.format(object_name, name)
else:
query = 'REVOKE {0} ON {1} {2} FROM {3}'.format(
_grants, object_type.upper(), on_part, name)
ret = _psql_prepare_and_run(['-c', query],
user=user,
host=host,
port=port,
maintenance_db=maintenance_db,
password=password,
runas=runas)
return ret['retcode'] == 0
def datadir_init(name,
auth='password',
user=None,
password=None,
encoding='UTF8',
locale=None,
waldir=None,
checksums=False,
runas=None):
'''
.. versionadded:: 2016.3.0
Initializes a postgres data directory
CLI Example:
.. code-block:: bash
salt '*' postgres.datadir_init '/var/lib/pgsql/data'
name
The name of the directory to initialize
auth
The default authentication method for local connections
password
The password to set for the postgres user
user
The database superuser name
encoding
The default encoding for new databases
locale
The default locale for new databases
waldir
The transaction log (WAL) directory (default is to keep WAL
inside the data directory)
.. versionadded:: Fluorine
checksums
If True, the cluster will be created with data page checksums.
.. note:: Data page checksums are supported since PostgreSQL 9.3.
.. versionadded:: Fluorine
runas
The system user the operation should be performed on behalf of
'''
if datadir_exists(name):
log.info('%s already exists', name)
return False
ret = _run_initdb(
name,
auth=auth,
user=user,
password=password,
encoding=encoding,
locale=locale,
runas=runas)
return ret['retcode'] == 0
def datadir_exists(name):
'''
.. versionadded:: 2016.3.0
Checks if postgres data directory has been initialized
CLI Example:
.. code-block:: bash
salt '*' postgres.datadir_exists '/var/lib/pgsql/data'
name
Name of the directory to check
'''
_version_file = os.path.join(name, 'PG_VERSION')
_config_file = os.path.join(name, 'postgresql.conf')
return os.path.isfile(_version_file) and os.path.isfile(_config_file)
| [
"igonchik@gmail.com"
] | igonchik@gmail.com |
ce83b7e7acb77eba6650ed2dfdf71e0df86e7df0 | feabe8532bfd7656d9a7d72c574ab8bb1bead896 | /py3-study/面向对象课上代码/1901/9-10/作业.py | 5df7340251a636066cdc866a812b5f4d91d93abf | [] | no_license | liuluyang/mk | bbbc887a432d40d23c20bf59453bbece8dc6e72f | 167c86be6241c6c148eb586b5dd19275246372a7 | refs/heads/master | 2020-08-03T15:02:24.406937 | 2020-01-04T08:20:32 | 2020-01-04T08:20:32 | 211,793,962 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,002 | py | # ! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Miller"
# Datetime: 2019/9/10 16:55
"""
创建一个Person类
1.
有私有属性:name. age, gender
但是有两个公开属性info, isAdult
info属性以元组的形式返回该对象所有私有属性
isAdult属性返回该对象是否成年 True or False 注:>=18是成年
2.
有一个方法birthday
每次调用这个方法,都会长一岁
"""
class Person:
def __init__(self, name, age, gender):
self.__name = name
self.__age = age
self.__gender = gender
@property
def info(self):
"""
所有信息
:return:
"""
return self.__name, self.__age, self.__gender
@property
def isAdult(self):
"""
是否成年
:return:
"""
if self.__age >= 18:
return True
return False
def birthday(self):
"""
过生日
:return:
"""
self.__age += 1 | [
"1120773382@qq.com"
] | 1120773382@qq.com |
b1f5af1f69ca218022bb709844afbd5b432e66e1 | 69ae33981d8fc674c700e23512ddfad5712435e2 | /tests/test_dashboards/test_pie_charts.py | a1e17dd401f956c1b027bf27e7026a348ecd1cd2 | [
"Apache-2.0"
] | permissive | shannara/squest | 7d9dd51cc825994abe2b5301e7fc6065acd0e1e3 | f68cf6787d59ae6634329d6c6526c1601442235e | refs/heads/master | 2023-07-01T04:27:08.895488 | 2021-08-03T15:12:05 | 2021-08-03T18:17:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,093 | py | from django.contrib.auth.models import User
from profiles.models import BillingGroup
from resource_tracker.models import ResourcePool, ResourceGroup
from service_catalog.models import Request, Service, Instance, JobTemplate, TowerServer
from service_catalog.models.operations import Operation
from service_catalog.models.request import RequestState
from service_catalog.views import create_pie_chart_instance_by_service_type, create_pie_chart_request_by_state, \
create_pie_chart_instance_by_billing_groups, create_pie_chart_resource_pool_consumption_by_billing_groups
from tests.base import BaseTest
class TestPieChart(BaseTest):
def setUp(self):
super(TestPieChart, self).setUp()
# Billing Groups
self.billing_groups = {'5G': None, 'Assurance': None, 'Orchestration': None, "SharedInfra": None}
for billing_group in self.billing_groups:
self.billing_groups[billing_group] = BillingGroup.objects.create(name=billing_group)
# Users
user1 = User.objects.create_user('OrchestrationGuy', 'OrchestrationGuy@hpe.com', self.common_password)
user2 = User.objects.create_user('AssuranceGuy', 'AssuranceGuy@hpe.com', self.common_password)
user3 = User.objects.create_user('SharedInfraGuy', 'SharedInfraGuy@hpe.com', self.common_password)
# Add users in Billing Groups
self.billing_groups['Orchestration'].user_set.add(user1)
self.billing_groups['Assurance'].user_set.add(user2)
self.billing_groups['SharedInfra'].user_set.add(user3)
# Tower server + Job template
tower_server = TowerServer.objects.create(name="Tower test", host="awx.hpe.com", token="TOKEN")
job_template = JobTemplate.objects.create(name='Job template', tower_id=1, tower_server=tower_server)
# Services + Operation
self.services = dict()
self.services['vmware_service'], _ = Service.objects.get_or_create(name="VMWare")
Operation.objects.create(name=self.services['vmware_service'].name,
service=self.services['vmware_service'],
job_template=job_template)
self.services['OCP_service'], _ = Service.objects.get_or_create(name="OCP")
Operation.objects.create(name=self.services['OCP_service'].name,
service=self.services['OCP_service'],
job_template=job_template)
self.services['K8S_service'], _ = Service.objects.get_or_create(name="K8S")
Operation.objects.create(name=self.services['K8S_service'].name,
service=self.services['K8S_service'],
job_template=job_template)
# Instance + Request
instances = list()
service = self.services['vmware_service']
billing_group = self.billing_groups['Orchestration']
name = "my VM"
user = user1
state = RequestState.ACCEPTED
for i in range(7):
instance = Instance.objects.create(service=service, name=name,
billing_group=billing_group)
Request.objects.create(instance=instance, state=state, user=user,
operation=service.operations.first())
instances.append(instance)
service = self.services['OCP_service']
billing_group = self.billing_groups['Assurance']
name = "my OCP"
user = user2
state = RequestState.FAILED
for i in range(5):
instance = Instance.objects.create(service=service, name=name,
billing_group=billing_group)
Request.objects.create(instance=instance, state=state, user=user,
operation=service.operations.first())
instances.append(instance)
service = self.services['K8S_service']
billing_group = self.billing_groups['SharedInfra']
name = "my K8S"
user = user3
state = RequestState.COMPLETE
for i in range(3):
instance = Instance.objects.create(service=service, name=name,
billing_group=billing_group)
Request.objects.create(instance=instance, state=state, user=user,
operation=service.operations.first())
instances.append(instance)
# Resource Group
# create resource pools
self.vcenter_pool = ResourcePool.objects.create(name="G5 vcenter")
self.vcenter_vcpu = self.vcenter_pool.add_attribute_definition(name='vCPU')
self.vcenter_memory = self.vcenter_pool.add_attribute_definition(name='Memory')
# resource
server_group = ResourceGroup.objects.create(name="Gen10")
server_group_cpu_attribute = server_group.add_attribute_definition(name="CPU")
server_group_memory_attribute = server_group.add_attribute_definition(name="Memory")
ocp_worker_node_group = ResourceGroup.objects.create(name="OCP Worker node")
ocp_worker_node_group_vcpu_attribute = ocp_worker_node_group.add_attribute_definition(name="vCPU")
ocp_worker_node_group_memory_attribute = ocp_worker_node_group.add_attribute_definition(name="Memory")
# Links
self.vcenter_pool.attribute_definitions.get(name='vCPU') \
.add_producers(server_group.attribute_definitions.get(name='CPU'))
self.vcenter_pool.attribute_definitions.get(name='Memory') \
.add_producers(server_group.attribute_definitions.get(name='Memory'))
self.vcenter_pool.attribute_definitions.get(name='vCPU') \
.add_consumers(ocp_worker_node_group.attribute_definitions.get(name='vCPU'))
self.vcenter_pool.attribute_definitions.get(name='Memory') \
.add_consumers(ocp_worker_node_group.attribute_definitions.get(name='Memory'))
# Instances
cpu_list = [30, 40, 50, 100]
memory_list = [100, 120, 150, 200]
for i in range(4):
server = server_group.create_resource(name=f"server-{i}")
server.set_attribute(server_group_cpu_attribute, cpu_list[i])
server.set_attribute(server_group_memory_attribute, memory_list[i])
for i, instance in enumerate(instances):
worker_node = ocp_worker_node_group.create_resource(name=f"worker{i}")
worker_node.set_attribute(ocp_worker_node_group_vcpu_attribute, 16)
worker_node.set_attribute(ocp_worker_node_group_memory_attribute, 32)
worker_node.service_catalog_instance = instance
worker_node.save()
def test_create_pie_chart_instance_by_service_type(self):
# This test may fail if we add Meta: ordering. Please update expected data
data = create_pie_chart_instance_by_service_type()
expected_data = {'title': 'Instance by service type', 'id': 'pie-chart-service',
'data': {'labels': ['VMWare', 'OCP', 'K8S'],
'datasets': [{'data': [7, 5, 3]}]}}
self.assertEqual(data.get('title'), expected_data.get('title'))
self.assertEqual(data.get('id'), expected_data.get('id'))
self.assertListEqual(data.get('data').get('labels'), expected_data.get('data').get('labels'))
self.assertListEqual(data.get('data').get('datasets')[0].get('data'),
expected_data.get('data').get('datasets')[0].get('data'))
def test_create_pie_chart_request_by_state(self):
# This test may fail if we add Meta: ordering. Please update expected data
data = create_pie_chart_request_by_state()
expected_data = {'title': 'Request by state', 'id': 'pie-chart-state',
'data': {'labels': ['ACCEPTED', 'FAILED', 'COMPLETE'], 'datasets': [
{'data': [7, 5, 3]}]}}
self.assertEqual(data.get('title'), expected_data.get('title'))
self.assertEqual(data.get('id'), expected_data.get('id'))
self.assertListEqual(data.get('data').get('labels'), expected_data.get('data').get('labels'))
self.assertListEqual(data.get('data').get('datasets')[0].get('data'),
expected_data.get('data').get('datasets')[0].get('data'))
def test_create_pie_chart_instance_by_billing_groups(self):
# This test may fail if we add Meta: ordering. Please update expected data
data = create_pie_chart_instance_by_billing_groups()
expected_data = {'title': 'Instance by billing', 'id': 'pie-chart-instance-billing',
'data': {'labels': ['Orchestration', 'Assurance', 'SharedInfra'], 'datasets': [
{'data': [7, 5, 3]}]}}
self.assertEqual(data.get('title'), expected_data.get('title'))
self.assertEqual(data.get('id'), expected_data.get('id'))
self.assertListEqual(data.get('data').get('labels'), expected_data.get('data').get('labels'))
self.assertListEqual(data.get('data').get('datasets')[0].get('data'),
expected_data.get('data').get('datasets')[0].get('data'))
def test_create_pie_chart_resource_pool_consumption_by_billing_groups(self):
print(BillingGroup.objects.all())
data = create_pie_chart_resource_pool_consumption_by_billing_groups()
from pprint import pprint
pprint(data)
expected_data = {
self.vcenter_pool: {
self.vcenter_vcpu: {
'data': {
'datasets': [{'data': [80, 112, 48]}],
'labels': ['Assurance', 'Orchestration', 'SharedInfra']},
'id': f"pie-chart-{self.vcenter_pool.id}-{self.vcenter_vcpu.id}",
'title': f"{self.vcenter_vcpu}"},
self.vcenter_memory: {
'data': {
'datasets': [{'data': [160, 224, 96]}],
'labels': ['Assurance', 'Orchestration', 'SharedInfra']},
'id': f"pie-chart-{self.vcenter_pool.id}-{self.vcenter_memory.id}",
'title': f"{self.vcenter_memory}"},
}
}
# CPU
self.assertListEqual(
data.get(self.vcenter_pool).get(self.vcenter_vcpu).get('data').get('datasets')[0].get('data'),
expected_data.get(self.vcenter_pool).get(self.vcenter_vcpu).get('data').get('datasets')[0].get('data')
)
self.assertListEqual(
data.get(self.vcenter_pool).get(self.vcenter_vcpu).get('data').get('labels'),
expected_data.get(self.vcenter_pool).get(self.vcenter_vcpu).get('data').get('labels')
)
self.assertEqual(
data.get(self.vcenter_pool).get(self.vcenter_vcpu).get('id'),
expected_data.get(self.vcenter_pool).get(self.vcenter_vcpu).get('id')
)
self.assertEqual(
data.get(self.vcenter_pool).get(self.vcenter_vcpu).get('title'),
expected_data.get(self.vcenter_pool).get(self.vcenter_vcpu).get('title')
)
# Memory
self.assertListEqual(
data.get(self.vcenter_pool).get(self.vcenter_memory).get('data').get('datasets')[0].get('data'),
expected_data.get(self.vcenter_pool).get(self.vcenter_memory).get('data').get('datasets')[0].get('data')
)
self.assertListEqual(
data.get(self.vcenter_pool).get(self.vcenter_memory).get('data').get('labels'),
expected_data.get(self.vcenter_pool).get(self.vcenter_memory).get('data').get('labels')
)
self.assertEqual(
data.get(self.vcenter_pool).get(self.vcenter_memory).get('id'),
expected_data.get(self.vcenter_pool).get(self.vcenter_memory).get('id')
)
self.assertEqual(
data.get(self.vcenter_pool).get(self.vcenter_memory).get('title'),
expected_data.get(self.vcenter_pool).get(self.vcenter_memory).get('title')
) | [
"nico.marcq@gmail.com"
] | nico.marcq@gmail.com |
cd2dc31139ee6be90efa1bbf27d589a6121b26ea | ca75f7099b93d8083d5b2e9c6db2e8821e63f83b | /z2/part2/batch/jm/parser_errors_2/840141986.py | 0988245bb5abe2feafffcf2b9486dfd0c79acc20 | [
"MIT"
] | permissive | kozakusek/ipp-2020-testy | 210ed201eaea3c86933266bd57ee284c9fbc1b96 | 09aa008fa53d159672cc7cbf969a6b237e15a7b8 | refs/heads/master | 2022-10-04T18:55:37.875713 | 2020-06-09T21:15:37 | 2020-06-09T21:15:37 | 262,290,632 | 0 | 0 | MIT | 2020-06-09T21:15:38 | 2020-05-08T10:10:47 | C | UTF-8 | Python | false | false | 1,335 | py | from part1 import (
gamma_board,
gamma_busy_fields,
gamma_delete,
gamma_free_fields,
gamma_golden_move,
gamma_golden_possible,
gamma_move,
gamma_new,
)
"""
scenario: test_random_actions
uuid: 840141986
"""
"""
random actions, total chaos
"""
board = gamma_new(2, 3, 3, 2)
assert board is not None
assert gamma_move(board, 1, 1, 0) == 1
assert gamma_busy_fields(board, 1) == 1
assert gamma_move(board, 2, 1, 1) == 1
assert gamma_move(board, 3, 1, 1) == 0
assert gamma_golden_possible(board, 3) == 1
board143215469 = gamma_board(board)
assert board143215469 is not None
assert board143215469 == ("..\n"
".2\n"
".1\n")
del board143215469
board143215469 = None
assert gamma_move(board, 1, 2, 0) == 0
assert gamma_move(board, 2, 2, 0) == 0
assert gamma_move(board, 2, 0, 2) == 1
assert gamma_move(board, 1, 0, 0) == 1
assert gamma_move(board, 2, 1, 0) == 0
assert gamma_move(board, 3, 0, 2) == 0
assert gamma_move(board, 1, 0, 0) == 0
assert gamma_move(board, 1, 0, 2) == 0
assert gamma_golden_possible(board, 1) == 1
assert gamma_move(board, 2, 1, 0) == 0
assert gamma_busy_fields(board, 2) == 2
assert gamma_move(board, 3, 0, 0) == 0
assert gamma_move(board, 3, 1, 0) == 0
assert gamma_busy_fields(board, 3) == 0
assert gamma_golden_move(board, 3, 0, 1) == 0
gamma_delete(board)
| [
"jakub@molinski.dev"
] | jakub@molinski.dev |
8163b7b83be82baad2d6aafd4d992123d86b5b7d | ae53410a837876abae440d14c243619dedba51f1 | /Solutions/5.py | 22ecdbd42cc865b3db442ae37a6dc36a2c054b12 | [] | no_license | AvivYaniv/Project-Euler | 68e839ae6d4d1a683aa8723f7c9ab3e55ee1dd28 | ec271404a7280129cdc0af9cf3a07f8faa3ab2f4 | refs/heads/master | 2021-06-25T11:20:12.010985 | 2021-04-25T18:39:12 | 2021-04-25T18:39:12 | 225,074,588 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,960 | py | import math
N = 20
PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
def GetNumberPrimeFactors(n):
prime_factors = []
if n in PRIMES:
prime_factors.append((n, 1))
else:
d = n
for p in PRIMES:
if d == 1:
break
else:
c = 0
while d % p == 0:
d = d / p
c = c + 1
if c > 0:
prime_factors.append((p, c))
return prime_factors
def GetLeastCommonDivisorTill(n):
maximal_prime_multipications = {}
for i in range(2, n + 1):
prime_factors = GetNumberPrimeFactors(i)
for (p, c) in prime_factors:
times = maximal_prime_multipications.get(p)
if times is None or c > times:
maximal_prime_multipications[p] = c
least_common_divisor = 1
for (p, c) in maximal_prime_multipications.items():
least_common_divisor = least_common_divisor * (p ** c)
return least_common_divisor
# Main
def main():
# 232792560
print GetLeastCommonDivisorTill(N)
if __name__ == "__main__":
main()
| [
"avivyaniv@gmx.com"
] | avivyaniv@gmx.com |
ee9e48bcf60bb992438878a31cd1b40dd6f8a51b | 3e358fa6f824e3923878c2200ffa685948281824 | /FlightPlannerTask/Type/QA/QATable.py | 6f6e1081867640fca774689d41e56e64bce3d4e4 | [] | no_license | developer124320/FlightPO | 28825a4c2c0b2c4d9095296e785f0123eb5d7560 | a5f4c583d01104d7c379e7cf677b898f407ab565 | refs/heads/master | 2021-06-16T16:55:27.203361 | 2017-04-10T13:14:39 | 2017-04-10T13:14:39 | 87,812,061 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,611 | py |
from QARecord import QARecord
from FlightPlanner.types import QARecordType, QATableType, QAFileVersion
from Type.Extensions import Extensions
from Type.String import String, StringBuilder
from Type.switch import switch
class QATable(QARecord):
def __init__(self):
QARecord.__init__(self)
self.Type = QARecordType.Table
self.tableType = None;
self.value = None;
def method_6(self, stringBuilder_0, string_0, bool_0, bool_1):
if (bool_0):
QARecord.smethod_0(self.title, stringBuilder_0);
self.HtmlBody(stringBuilder_0, string_0);
for child in self.children:
string0 = string_0;
if (not String.IsNullOrEmpty(child.Heading)):
string0 = "{0} - {1}".format(string0, child.title) if(not String.IsNullOrEmpty(string0)) else child.title
child.method_6(stringBuilder_0, string0, False, False);
if (bool_1):
QARecord.smethod_1(stringBuilder_0);
def method_10(self, object_0, object_1, string_0):
self.WordDocumentBody(object_0, object_1, string_0);
QARecord.method_10(object_0, object_1, string_0)
def method_12(self, string_0):
num = 0;
string0 = string_0;
for i in range(len(string0)):
str0 = string0[i];
num1 = 1;
str1 = str0;
# str1 = String.Str2QString(str1)
for sj in str1:
if (sj == '\t'):
num1 += 1;
if (num < num1):
num = num1;
if (self.tableType == QATableType.ObstacleList):
return num;
return num;
def method_13(self, string_0, bool_0):
if (String.IsNullOrEmpty(string_0)):
return "<br>";
if (not bool_0):
return string_0;
string_0 = String.QString2Str(string_0)
return string_0.replace(" ", " ");
def method_14(self, string_0, int_0, int_1):
str0 = "";
stringBuilder = StringBuilder();
strArrays = Extensions.smethod_4(string_0);
for i in range(len(strArrays) - 1):
str1 = strArrays[i];
for case in switch (self.tableType):
if case(QATableType.General):
stringBuilder.Append("<td>{0}</td>".format(self.method_13(str1, True)));
break;
elif case(QATableType.OCAH):
if (int_0 == 0 or i == 0):
stringBuilder.Append("<th>{0}</th>".format(self.method_13(str1, False)));
break;
else:
stringBuilder.Append("<td>{0}</td>".format(self.method_13(str1, False)));
break;
elif case(QATableType.ObstacleList):
if (int_0 != 0):
stringBuilder.Append("<td>{0}</td>".format(self.method_13(str1, False)));
break;
else:
stringBuilder.Append("<th>{0}</th>".format(self.method_13(str1, False)));
break;
str0 = "<br>" if(len(strArrays) <= 0) else strArrays[len(strArrays) - 1];
for case in switch (self.tableType):
if case(QATableType.General):
if (len(strArrays) == 1 and int_1 > 1):
num = str0.smethod_6();
if (num < 4):
str0 = "<b>{0}</b>".format(str0);
elif (num < 8):
str0 = "<b><i>{0}</i></b>".format(str0);
if (len(strArrays) >= int_1):
stringBuilder.Append("<td>{0}</td>".format(self.method_13(str, True)));
break;
else:
int1 = int_1 - len(strArrays) + 1;
stringBuilder.Append("<td colspan=\"{0}\">{1}</td>".format(str(int1), self.method_13(str, True)));
break;
elif case(QATableType.OCAH):
if (int_0 != 0):
if (len(strArrays) == 1):
stringBuilder.Append("<th>{0}</th>".format(self.method_13(str, False)));
for j in range(len(strArrays), int_1):
stringBuilder.Append("<td><br></td>");
break;
stringBuilder.Append("<td>{0}</td>".format(self.method_13(str, False)));
stringBuilder.Append("<th>{0}</th>".format(self.method_13(str, False)));
for j in range(len(strArrays), int_1):
stringBuilder.Append("<td><br></td>");
break;
elif case(QATableType.ObstacleList):
if (int_0 != 0):
stringBuilder.Append("<td>{0}</td>".format(self.method_13(str, False)));
else:
stringBuilder.Append("<th>{0}</th>".format(self.method_13(str, False)));
for k in range(len(strArrays), int_1):
stringBuilder.Append("<td><br></td>");
break;
return stringBuilder.ToString();
def HtmlBody(self, lines, title):
lines.AppendLine("<div align=\"center\">");
if (not String.IsNullOrEmpty(title)):
lines.AppendLine("<p align=\"center\"><b>{0}</b></p>".format(title));
lines.AppendLine("<table border=\"0\" cellpadding=\"2\" cellspacing=\"0\">");
lines.AppendLine("<tbody>");
strArrays = Extensions.smethod_3(self.Text);
num = self.method_12(strArrays);
for i in range(len(strArrays)):
lines.AppendLine("<tr>{0}</tr>".format(self.method_14(strArrays[i], i, num)));
lines.AppendLine("</tbody>");
lines.AppendLine("</table>");
lines.AppendLine("</div>");
def LoadData(self, reader, version):
QARecord.LoadData(reader, version);
for case in switch (version):
if case(QAFileVersion.V8) or case(QAFileVersion.V8_1):
self.tableType = reader.ReadByte();
self.method_0(self.value, reader.ReadBytes(int(reader.ReadInt64())), False);
return;
elif case(QAFileVersion.V10):
self.tableType = reader.ReadByte();
self.method_0(self.value, reader.ReadBytes(int(reader.ReadInt64())), True);
return;
else:
raise SystemError
def SaveData(self, writer, version):
numArray = [];
QARecord.SaveData(writer, version);
for case in switch (version):
if case(QAFileVersion.V8) or case(QAFileVersion.V8_1):
writer.write(self.tableType);
numArray = self.method_1(self.value, False);
writer.write(numArray.LongLength);
writer.write(numArray);
return;
elif case(QAFileVersion.V10):
writer.write(self.tableType);
numArray = self.method_1(self.value, True);
writer.write(numArray.LongLength);
writer.write(numArray);
return;
else:
raise SystemError
def WordDocumentBody(self, wordApp, wordDoc, title):
#TODO : UnCompleted
pass
# string[] strArrays = this.Text.smethod_3();
# int num = this.method_12(strArrays);
# if ((int)strArrays.Length < 1 || num < 1)
# {
# return;
# }
# object obj = wordApp.smethod_24("Selection");
# if (!string.IsNullOrEmpty(title))
# {
# object obj1 = obj.smethod_24("Font");
# obj1.smethod_25("Bold", true);
# obj.smethod_21("TypeText", string.Format("{0}\r", title));
# obj1.smethod_25("Bold", false);
# obj.smethod_21("TypeText", "\r");
# }
# object obj2 = wordDoc.smethod_24("Tables");
# object[] objArray = new object[] { obj.smethod_24("Range"), (int)strArrays.Length, num, 1, 1 };
# object obj3 = obj2.smethod_23("Add", objArray);
# obj3.smethod_25("ApplyStyleHeadingRows", true);
# obj3.smethod_25("ApplyStyleLastRow", true);
# obj3.smethod_25("ApplyStyleFirstColumn", true);
# obj3.smethod_25("ApplyStyleLastColumn", true);
# object obj4 = obj3.smethod_24("Rows");
# for (int i = 0; i < (int)strArrays.Length; i++)
# {
# this.method_15(obj3, strArrays[i], i, num);
# obj4.smethod_22("Item", i + 1).smethod_24("Cells").smethod_25("VerticalAlignment", 1);
# }
# obj4.smethod_25("Alignment", 1);
# obj3.smethod_22("AutoFitBehavior", 1);
# obj3.smethod_24("Range").smethod_20("Select");
# obj.smethod_25("Start", obj.smethod_24("End"));
# obj.smethod_21("TypeText", "\r");
def getTableType(self):
return self.tableType
def setTableType(self, val):
self.tableType = val
TableType = property(getTableType, setTableType, None, None)
def getText(self):
return self.method_2(self.value)
def setText(self, val):
self.method_3(self.value, val)
Text = property(getText, setText, None, None)
def getValue(self):
return self.value
def setValue(self, val):
self.value = val
Value = property(getValue, setValue, None, None)
| [
"kwangyingjin@outlook.com"
] | kwangyingjin@outlook.com |
dc913812fd4788f60339109e8dd78e0fe48bcd66 | 1ac96e752d08b1b74676262137bdef9071f12827 | /test/pipeline/test_build.py | ba98dade73263dbbca782da216e4aab0ba710c45 | [] | no_license | nornir/nornir-buildmanager | cf8e06e4e0ff769f07ea46345be386152bf02f84 | f9493538945984626e921b453b378b8bcbc117d7 | refs/heads/master | 2023-06-08T21:17:32.049308 | 2018-02-27T01:24:13 | 2018-02-27T01:24:13 | 14,442,428 | 2 | 0 | null | 2013-12-17T22:09:07 | 2013-11-16T05:44:07 | Python | UTF-8 | Python | false | false | 2,340 | py | '''
Created on Feb 22, 2013
@author: u0490822
'''
import glob
import unittest
from setup_pipeline import *
class PrepareThenMosaicTest(PrepareThroughAssembleSetup):
'''Run the build with prepare, then run again with mosiac'''
TransformNames = ["translate", "grid", "zerogrid", "stage"]
@property
def VolumePath(self):
return "6750"
@property
def Platform(self):
return "PMG"
def CheckTransformsExist(self, VolumeObj, TransformNames=None):
if TransformNames is None:
TransformNames = PrepareThenMosaicTest.TransformNames
ChannelNode = VolumeObj.find("Block/Section/Channel")
self.assertIsNotNone(ChannelNode)
for tname in TransformNames:
TransformNode = ChannelNode.GetChildByAttrib("Transform", "Name", tname)
self.assertIsNotNone(ChannelNode)
def TileFiles(self, tilesetNode, downsample):
levelNode = tilesetNode.GetLevel(downsample)
self.assertIsNotNone(levelNode)
files = glob.glob(os.path.join(levelNode.FullPath, "*" + tilesetNode.FilePostfix))
self.assertGreater(len(files), 0, "Missing tiles")
return files
def CheckTilesetExists(self, VolumeObj):
TilesetNode = VolumeObj.find("Block/Section/Channel/Filter/Tileset")
self.assertIsNotNone(TilesetNode)
FullResTiles = self.TileFiles(TilesetNode, 1)
DSTwoTiles = self.TileFiles(TilesetNode, 2)
self.assertGreaterEqual(len(DSTwoTiles), len(FullResTiles) / 4, "Downsample level seems to be missing assembled tiles")
FullResTiles.sort()
DSTwoTiles.sort()
self.assertEqual(os.path.basename(FullResTiles[0]),
os.path.basename(DSTwoTiles[0]),
"Tiles at different downsample levels should use the same naming convention")
def runTest(self):
# Import the files
# self.CheckTransformsExist(VolumeObj)
buildArgs = self._CreateBuildArgs('AssembleTiles', '-Shape', '512,512')
build.Execute(buildArgs)
# Load the meta-data from the volumedata.xml file
VolumeObj = VolumeManager.Load(self.TestOutputPath)
self.CheckTilesetExists(VolumeObj)
if __name__ == "__main__":
# import syssys.argv = ['', 'Test.testName']
unittest.main()
| [
"james.r.andreson@utah.edu"
] | james.r.andreson@utah.edu |
a2e7148df94a9924ffa6228fc87c8ae3b5ed95bd | 66ac12d64422cfbe1aedf34b66ee8750b595ca58 | /spensum/module/position.py | 39645869b7aa8c6d1bf776f418344966744727b0 | [] | no_license | kedz/spensum | 884c2bbfeaacce875adf8fe5dff230e7c47b68ca | 989f5036543abadc616f7ce10477e716f6e88105 | refs/heads/master | 2021-09-13T21:07:33.727862 | 2018-02-02T19:13:14 | 2018-02-02T19:13:14 | 112,295,203 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,619 | py | from .spen_module import SpenModule
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
class Position(SpenModule):
def __init__(self, num_positions=50, name="Position", mask_value=-1,
burn_in=0):
super(Position, self).__init__(
name=name, mask_value=mask_value, burn_in=burn_in)
self.num_positions_ = num_positions
self.embedding = nn.Embedding(num_positions + 1, 1, padding_idx=0)
@property
def num_positions(self):
return self.num_positions_
def compute_features(self, inputs, inputs_mask=None, targets_mask=None):
position = inputs.position.squeeze(2).clamp(0, self.num_positions)
logits = self.embedding(position).squeeze(2)
return logits
def forward_pass(self, inputs, features, inputs_mask=None,
targets_mask=None):
return features
def compute_energy(self, inputs, features, targets, inputs_mask=None,
targets_mask=None):
if targets_mask is None:
targets_mask = inputs.embedding[:,:,0].eq(self.mask_value)
pos_probs = torch.sigmoid(features)
pos_energy = -targets * pos_probs
neg_probs = 1 - pos_probs
neg_energy = -(1 - targets) * neg_probs
pointwise_energy = (pos_energy + neg_energy).masked_fill(
targets_mask, 0)
length = Variable(inputs.length.data.float().view(-1, 1))
total_energy = pointwise_energy.sum(1, keepdim=True)
mean_energy = total_energy / length
return mean_energy
| [
"kedzie@cs.columbia.edu"
] | kedzie@cs.columbia.edu |
003d37262facf5000ddfa729cb6adc2823957ece | 4fc9cb4cf01e41c4ed3de89f13d213e95c87dd33 | /angr/procedures/definitions/win32_rpcns4.py | c4114ba31ec27bdaae4ecf7fb2f2d84122977a85 | [
"BSD-2-Clause"
] | permissive | mborgerson/angr | ea5daf28576c3d31b542a0e229139ab2494326e9 | 8296578e92a15584205bfb2f7add13dd0fb36d56 | refs/heads/master | 2023-07-24T22:41:25.607215 | 2022-10-19T19:46:12 | 2022-10-20T18:13:31 | 227,243,942 | 1 | 2 | BSD-2-Clause | 2021-04-07T22:09:51 | 2019-12-11T00:47:55 | Python | UTF-8 | Python | false | false | 31,967 | py | # pylint:disable=line-too-long
import logging
from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool
from ...calling_conventions import SimCCStdcall, SimCCMicrosoftAMD64
from .. import SIM_PROCEDURES as P
from . import SimLibrary
_l = logging.getLogger(name=__name__)
lib = SimLibrary()
lib.set_default_cc('X86', SimCCStdcall)
lib.set_default_cc('AMD64', SimCCMicrosoftAMD64)
lib.set_library_names("rpcns4.dll")
prototypes = \
{
#
'RpcIfIdVectorFree': SimTypeFunction([SimTypePointer(SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "IfId": SimTypePointer(SimTypePointer(SimStruct({"Uuid": SimTypeBottom(label="Guid"), "VersMajor": SimTypeShort(signed=False, label="UInt16"), "VersMinor": SimTypeShort(signed=False, label="UInt16")}, name="RPC_IF_ID", pack=False, align=None), offset=0), offset=0)}, name="RPC_IF_ID_VECTOR", pack=False, align=None), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["IfIdVector"]),
#
'RpcNsBindingExportA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "BindingH": SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)}, name="RPC_BINDING_VECTOR", pack=False, align=None), offset=0), SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "Uuid": SimTypePointer(SimTypePointer(SimTypeBottom(label="Guid"), offset=0), offset=0)}, name="UUID_VECTOR", pack=False, align=None), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfSpec", "BindingVec", "ObjectUuidVec"]),
#
'RpcNsBindingUnexportA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "Uuid": SimTypePointer(SimTypePointer(SimTypeBottom(label="Guid"), offset=0), offset=0)}, name="UUID_VECTOR", pack=False, align=None), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfSpec", "ObjectUuidVec"]),
#
'RpcNsBindingExportW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "BindingH": SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)}, name="RPC_BINDING_VECTOR", pack=False, align=None), offset=0), SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "Uuid": SimTypePointer(SimTypePointer(SimTypeBottom(label="Guid"), offset=0), offset=0)}, name="UUID_VECTOR", pack=False, align=None), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfSpec", "BindingVec", "ObjectUuidVec"]),
#
'RpcNsBindingUnexportW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "Uuid": SimTypePointer(SimTypePointer(SimTypeBottom(label="Guid"), offset=0), offset=0)}, name="UUID_VECTOR", pack=False, align=None), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfSpec", "ObjectUuidVec"]),
#
'RpcNsBindingExportPnPA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "Uuid": SimTypePointer(SimTypePointer(SimTypeBottom(label="Guid"), offset=0), offset=0)}, name="UUID_VECTOR", pack=False, align=None), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfSpec", "ObjectVector"]),
#
'RpcNsBindingUnexportPnPA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "Uuid": SimTypePointer(SimTypePointer(SimTypeBottom(label="Guid"), offset=0), offset=0)}, name="UUID_VECTOR", pack=False, align=None), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfSpec", "ObjectVector"]),
#
'RpcNsBindingExportPnPW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "Uuid": SimTypePointer(SimTypePointer(SimTypeBottom(label="Guid"), offset=0), offset=0)}, name="UUID_VECTOR", pack=False, align=None), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfSpec", "ObjectVector"]),
#
'RpcNsBindingUnexportPnPW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "Uuid": SimTypePointer(SimTypePointer(SimTypeBottom(label="Guid"), offset=0), offset=0)}, name="UUID_VECTOR", pack=False, align=None), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfSpec", "ObjectVector"]),
#
'RpcNsBindingLookupBeginA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimTypeBottom(label="Guid"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfSpec", "ObjUuid", "BindingMaxCount", "LookupContext"]),
#
'RpcNsBindingLookupBeginW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimTypeBottom(label="Guid"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfSpec", "ObjUuid", "BindingMaxCount", "LookupContext"]),
#
'RpcNsBindingLookupNext': SimTypeFunction([SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "BindingH": SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)}, name="RPC_BINDING_VECTOR", pack=False, align=None), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["LookupContext", "BindingVec"]),
#
'RpcNsBindingLookupDone': SimTypeFunction([SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["LookupContext"]),
#
'RpcNsGroupDeleteA': SimTypeFunction([SimTypeInt(signed=False, label="GROUP_NAME_SYNTAX"), SimTypePointer(SimTypeChar(label="Byte"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["GroupNameSyntax", "GroupName"]),
#
'RpcNsGroupMbrAddA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["GroupNameSyntax", "GroupName", "MemberNameSyntax", "MemberName"]),
#
'RpcNsGroupMbrRemoveA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["GroupNameSyntax", "GroupName", "MemberNameSyntax", "MemberName"]),
#
'RpcNsGroupMbrInqBeginA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["GroupNameSyntax", "GroupName", "MemberNameSyntax", "InquiryContext"]),
#
'RpcNsGroupMbrInqNextA': SimTypeFunction([SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimTypePointer(SimTypeChar(label="Byte"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["InquiryContext", "MemberName"]),
#
'RpcNsGroupDeleteW': SimTypeFunction([SimTypeInt(signed=False, label="GROUP_NAME_SYNTAX"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["GroupNameSyntax", "GroupName"]),
#
'RpcNsGroupMbrAddW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["GroupNameSyntax", "GroupName", "MemberNameSyntax", "MemberName"]),
#
'RpcNsGroupMbrRemoveW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["GroupNameSyntax", "GroupName", "MemberNameSyntax", "MemberName"]),
#
'RpcNsGroupMbrInqBeginW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["GroupNameSyntax", "GroupName", "MemberNameSyntax", "InquiryContext"]),
#
'RpcNsGroupMbrInqNextW': SimTypeFunction([SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["InquiryContext", "MemberName"]),
#
'RpcNsGroupMbrInqDone': SimTypeFunction([SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["InquiryContext"]),
#
'RpcNsProfileDeleteA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["ProfileNameSyntax", "ProfileName"]),
#
'RpcNsProfileEltAddA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimStruct({"Uuid": SimTypeBottom(label="Guid"), "VersMajor": SimTypeShort(signed=False, label="UInt16"), "VersMinor": SimTypeShort(signed=False, label="UInt16")}, name="RPC_IF_ID", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["ProfileNameSyntax", "ProfileName", "IfId", "MemberNameSyntax", "MemberName", "Priority", "Annotation"]),
#
'RpcNsProfileEltRemoveA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimStruct({"Uuid": SimTypeBottom(label="Guid"), "VersMajor": SimTypeShort(signed=False, label="UInt16"), "VersMinor": SimTypeShort(signed=False, label="UInt16")}, name="RPC_IF_ID", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["ProfileNameSyntax", "ProfileName", "IfId", "MemberNameSyntax", "MemberName"]),
#
'RpcNsProfileEltInqBeginA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimStruct({"Uuid": SimTypeBottom(label="Guid"), "VersMajor": SimTypeShort(signed=False, label="UInt16"), "VersMinor": SimTypeShort(signed=False, label="UInt16")}, name="RPC_IF_ID", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["ProfileNameSyntax", "ProfileName", "InquiryType", "IfId", "VersOption", "MemberNameSyntax", "MemberName", "InquiryContext"]),
#
'RpcNsProfileEltInqNextA': SimTypeFunction([SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimStruct({"Uuid": SimTypeBottom(label="Guid"), "VersMajor": SimTypeShort(signed=False, label="UInt16"), "VersMinor": SimTypeShort(signed=False, label="UInt16")}, name="RPC_IF_ID", pack=False, align=None), offset=0), SimTypePointer(SimTypePointer(SimTypeChar(label="Byte"), offset=0), offset=0), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0), SimTypePointer(SimTypePointer(SimTypeChar(label="Byte"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["InquiryContext", "IfId", "MemberName", "Priority", "Annotation"]),
#
'RpcNsProfileDeleteW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["ProfileNameSyntax", "ProfileName"]),
#
'RpcNsProfileEltAddW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypePointer(SimStruct({"Uuid": SimTypeBottom(label="Guid"), "VersMajor": SimTypeShort(signed=False, label="UInt16"), "VersMinor": SimTypeShort(signed=False, label="UInt16")}, name="RPC_IF_ID", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["ProfileNameSyntax", "ProfileName", "IfId", "MemberNameSyntax", "MemberName", "Priority", "Annotation"]),
#
'RpcNsProfileEltRemoveW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypePointer(SimStruct({"Uuid": SimTypeBottom(label="Guid"), "VersMajor": SimTypeShort(signed=False, label="UInt16"), "VersMinor": SimTypeShort(signed=False, label="UInt16")}, name="RPC_IF_ID", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["ProfileNameSyntax", "ProfileName", "IfId", "MemberNameSyntax", "MemberName"]),
#
'RpcNsProfileEltInqBeginW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimStruct({"Uuid": SimTypeBottom(label="Guid"), "VersMajor": SimTypeShort(signed=False, label="UInt16"), "VersMinor": SimTypeShort(signed=False, label="UInt16")}, name="RPC_IF_ID", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["ProfileNameSyntax", "ProfileName", "InquiryType", "IfId", "VersOption", "MemberNameSyntax", "MemberName", "InquiryContext"]),
#
'RpcNsProfileEltInqNextW': SimTypeFunction([SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimStruct({"Uuid": SimTypeBottom(label="Guid"), "VersMajor": SimTypeShort(signed=False, label="UInt16"), "VersMinor": SimTypeShort(signed=False, label="UInt16")}, name="RPC_IF_ID", pack=False, align=None), offset=0), SimTypePointer(SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), offset=0), SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0), SimTypePointer(SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["InquiryContext", "IfId", "MemberName", "Priority", "Annotation"]),
#
'RpcNsProfileEltInqDone': SimTypeFunction([SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["InquiryContext"]),
#
'RpcNsEntryObjectInqBeginA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "InquiryContext"]),
#
'RpcNsEntryObjectInqBeginW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "InquiryContext"]),
#
'RpcNsEntryObjectInqNext': SimTypeFunction([SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimTypeBottom(label="Guid"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["InquiryContext", "ObjUuid"]),
#
'RpcNsEntryObjectInqDone': SimTypeFunction([SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["InquiryContext"]),
#
'RpcNsEntryExpandNameA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypePointer(SimTypeChar(label="Byte"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "ExpandedName"]),
#
'RpcNsMgmtBindingUnexportA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimStruct({"Uuid": SimTypeBottom(label="Guid"), "VersMajor": SimTypeShort(signed=False, label="UInt16"), "VersMinor": SimTypeShort(signed=False, label="UInt16")}, name="RPC_IF_ID", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "Uuid": SimTypePointer(SimTypePointer(SimTypeBottom(label="Guid"), offset=0), offset=0)}, name="UUID_VECTOR", pack=False, align=None), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfId", "VersOption", "ObjectUuidVec"]),
#
'RpcNsMgmtEntryCreateA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName"]),
#
'RpcNsMgmtEntryDeleteA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName"]),
#
'RpcNsMgmtEntryInqIfIdsA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "IfId": SimTypePointer(SimTypePointer(SimStruct({"Uuid": SimTypeBottom(label="Guid"), "VersMajor": SimTypeShort(signed=False, label="UInt16"), "VersMinor": SimTypeShort(signed=False, label="UInt16")}, name="RPC_IF_ID", pack=False, align=None), offset=0), offset=0)}, name="RPC_IF_ID_VECTOR", pack=False, align=None), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfIdVec"]),
#
'RpcNsMgmtHandleSetExpAge': SimTypeFunction([SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["NsHandle", "ExpirationAge"]),
#
'RpcNsMgmtInqExpAge': SimTypeFunction([SimTypePointer(SimTypeInt(signed=False, label="UInt32"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["ExpirationAge"]),
#
'RpcNsMgmtSetExpAge': SimTypeFunction([SimTypeInt(signed=False, label="UInt32")], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["ExpirationAge"]),
#
'RpcNsEntryExpandNameW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypePointer(SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "ExpandedName"]),
#
'RpcNsMgmtBindingUnexportW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypePointer(SimStruct({"Uuid": SimTypeBottom(label="Guid"), "VersMajor": SimTypeShort(signed=False, label="UInt16"), "VersMinor": SimTypeShort(signed=False, label="UInt16")}, name="RPC_IF_ID", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "Uuid": SimTypePointer(SimTypePointer(SimTypeBottom(label="Guid"), offset=0), offset=0)}, name="UUID_VECTOR", pack=False, align=None), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfId", "VersOption", "ObjectUuidVec"]),
#
'RpcNsMgmtEntryCreateW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName"]),
#
'RpcNsMgmtEntryDeleteW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName"]),
#
'RpcNsMgmtEntryInqIfIdsW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypePointer(SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "IfId": SimTypePointer(SimTypePointer(SimStruct({"Uuid": SimTypeBottom(label="Guid"), "VersMajor": SimTypeShort(signed=False, label="UInt16"), "VersMinor": SimTypeShort(signed=False, label="UInt16")}, name="RPC_IF_ID", pack=False, align=None), offset=0), offset=0)}, name="RPC_IF_ID_VECTOR", pack=False, align=None), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfIdVec"]),
#
'RpcNsBindingImportBeginA': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeChar(label="Byte"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimTypeBottom(label="Guid"), offset=0), SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfSpec", "ObjUuid", "ImportContext"]),
#
'RpcNsBindingImportBeginW': SimTypeFunction([SimTypeInt(signed=False, label="UInt32"), SimTypePointer(SimTypeShort(signed=False, label="UInt16"), offset=0), SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimTypeBottom(label="Guid"), offset=0), SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["EntryNameSyntax", "EntryName", "IfSpec", "ObjUuid", "ImportContext"]),
#
'RpcNsBindingImportNext': SimTypeFunction([SimTypePointer(SimTypeBottom(label="Void"), offset=0), SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["ImportContext", "Binding"]),
#
'RpcNsBindingImportDone': SimTypeFunction([SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["ImportContext"]),
#
'RpcNsBindingSelect': SimTypeFunction([SimTypePointer(SimStruct({"Count": SimTypeInt(signed=False, label="UInt32"), "BindingH": SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)}, name="RPC_BINDING_VECTOR", pack=False, align=None), offset=0), SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["BindingVec", "Binding"]),
#
'I_RpcNsGetBuffer': SimTypeFunction([SimTypePointer(SimStruct({"Handle": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "DataRepresentation": SimTypeInt(signed=False, label="UInt32"), "Buffer": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "BufferLength": SimTypeInt(signed=False, label="UInt32"), "ProcNum": SimTypeInt(signed=False, label="UInt32"), "TransferSyntax": SimTypePointer(SimStruct({"SyntaxGUID": SimTypeBottom(label="Guid"), "SyntaxVersion": SimStruct({"MajorVersion": SimTypeShort(signed=False, label="UInt16"), "MinorVersion": SimTypeShort(signed=False, label="UInt16")}, name="RPC_VERSION", pack=False, align=None)}, name="RPC_SYNTAX_IDENTIFIER", pack=False, align=None), offset=0), "RpcInterfaceInformation": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "ReservedForRuntime": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "ManagerEpv": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "ImportContext": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "RpcFlags": SimTypeInt(signed=False, label="UInt32")}, name="RPC_MESSAGE", pack=False, align=None), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["Message"]),
#
'I_RpcNsSendReceive': SimTypeFunction([SimTypePointer(SimStruct({"Handle": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "DataRepresentation": SimTypeInt(signed=False, label="UInt32"), "Buffer": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "BufferLength": SimTypeInt(signed=False, label="UInt32"), "ProcNum": SimTypeInt(signed=False, label="UInt32"), "TransferSyntax": SimTypePointer(SimStruct({"SyntaxGUID": SimTypeBottom(label="Guid"), "SyntaxVersion": SimStruct({"MajorVersion": SimTypeShort(signed=False, label="UInt16"), "MinorVersion": SimTypeShort(signed=False, label="UInt16")}, name="RPC_VERSION", pack=False, align=None)}, name="RPC_SYNTAX_IDENTIFIER", pack=False, align=None), offset=0), "RpcInterfaceInformation": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "ReservedForRuntime": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "ManagerEpv": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "ImportContext": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "RpcFlags": SimTypeInt(signed=False, label="UInt32")}, name="RPC_MESSAGE", pack=False, align=None), offset=0), SimTypePointer(SimTypePointer(SimTypeBottom(label="Void"), offset=0), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["Message", "Handle"]),
#
'I_RpcNsRaiseException': SimTypeFunction([SimTypePointer(SimStruct({"Handle": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "DataRepresentation": SimTypeInt(signed=False, label="UInt32"), "Buffer": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "BufferLength": SimTypeInt(signed=False, label="UInt32"), "ProcNum": SimTypeInt(signed=False, label="UInt32"), "TransferSyntax": SimTypePointer(SimStruct({"SyntaxGUID": SimTypeBottom(label="Guid"), "SyntaxVersion": SimStruct({"MajorVersion": SimTypeShort(signed=False, label="UInt16"), "MinorVersion": SimTypeShort(signed=False, label="UInt16")}, name="RPC_VERSION", pack=False, align=None)}, name="RPC_SYNTAX_IDENTIFIER", pack=False, align=None), offset=0), "RpcInterfaceInformation": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "ReservedForRuntime": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "ManagerEpv": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "ImportContext": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "RpcFlags": SimTypeInt(signed=False, label="UInt32")}, name="RPC_MESSAGE", pack=False, align=None), offset=0), SimTypeInt(signed=False, label="RPC_STATUS")], SimTypeBottom(label="Void"), arg_names=["Message", "Status"]),
#
'I_RpcReBindBuffer': SimTypeFunction([SimTypePointer(SimStruct({"Handle": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "DataRepresentation": SimTypeInt(signed=False, label="UInt32"), "Buffer": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "BufferLength": SimTypeInt(signed=False, label="UInt32"), "ProcNum": SimTypeInt(signed=False, label="UInt32"), "TransferSyntax": SimTypePointer(SimStruct({"SyntaxGUID": SimTypeBottom(label="Guid"), "SyntaxVersion": SimStruct({"MajorVersion": SimTypeShort(signed=False, label="UInt16"), "MinorVersion": SimTypeShort(signed=False, label="UInt16")}, name="RPC_VERSION", pack=False, align=None)}, name="RPC_SYNTAX_IDENTIFIER", pack=False, align=None), offset=0), "RpcInterfaceInformation": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "ReservedForRuntime": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "ManagerEpv": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "ImportContext": SimTypePointer(SimTypeBottom(label="Void"), offset=0), "RpcFlags": SimTypeInt(signed=False, label="UInt32")}, name="RPC_MESSAGE", pack=False, align=None), offset=0)], SimTypeInt(signed=False, label="RPC_STATUS"), arg_names=["Message"]),
}
lib.set_prototypes(prototypes)
| [
"noreply@github.com"
] | mborgerson.noreply@github.com |
195fca9376d0afd9778a4be805514ee6c1263d09 | 11cd362cdd78c2fc48042ed203614b201ac94aa6 | /desktop/core/ext-py3/boto-2.49.0/tests/unit/rds/test_snapshot.py | c3c9d8a67282483ca4c145ede59fc32c350a3738 | [
"CC-BY-3.0",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"ZPL-2.0",
"Unlicense",
"LGPL-3.0-only",
"CC0-1.0",
"LicenseRef-scancode-other-permissive",
"CNRI-Python",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-or-later",
"Python-2.0",
"GPL-3.0... | permissive | cloudera/hue | b42343d0e03d2936b5a9a32f8ddb3e9c5c80c908 | dccb9467675c67b9c3399fc76c5de6d31bfb8255 | refs/heads/master | 2023-08-31T06:49:25.724501 | 2023-08-28T20:45:00 | 2023-08-28T20:45:00 | 732,593 | 5,655 | 2,244 | Apache-2.0 | 2023-09-14T03:05:41 | 2010-06-21T19:46:51 | JavaScript | UTF-8 | Python | false | false | 14,445 | py | from tests.unit import unittest
from tests.unit import AWSMockServiceTestCase
from boto.rds import RDSConnection
from boto.rds.dbsnapshot import DBSnapshot
from boto.rds import DBInstance
class TestDescribeDBSnapshots(AWSMockServiceTestCase):
connection_class = RDSConnection
def default_body(self):
return """
<DescribeDBSnapshotsResponse xmlns="http://rds.amazonaws.com/doc/2013-05-15/">
<DescribeDBSnapshotsResult>
<DBSnapshots>
<DBSnapshot>
<Port>3306</Port>
<SnapshotCreateTime>2011-05-23T06:29:03.483Z</SnapshotCreateTime>
<Engine>mysql</Engine>
<Status>available</Status>
<AvailabilityZone>us-east-1a</AvailabilityZone>
<LicenseModel>general-public-license</LicenseModel>
<InstanceCreateTime>2011-05-23T06:06:43.110Z</InstanceCreateTime>
<AllocatedStorage>10</AllocatedStorage>
<DBInstanceIdentifier>simcoprod01</DBInstanceIdentifier>
<EngineVersion>5.1.50</EngineVersion>
<DBSnapshotIdentifier>mydbsnapshot</DBSnapshotIdentifier>
<SnapshotType>manual</SnapshotType>
<MasterUsername>master</MasterUsername>
<OptionGroupName>myoptiongroupname</OptionGroupName>
<Iops>1000</Iops>
<PercentProgress>100</PercentProgress>
<SourceRegion>eu-west-1</SourceRegion>
<VpcId>myvpc</VpcId>
</DBSnapshot>
<DBSnapshot>
<Port>3306</Port>
<SnapshotCreateTime>2011-03-11T07:20:24.082Z</SnapshotCreateTime>
<Engine>mysql</Engine>
<Status>available</Status>
<AvailabilityZone>us-east-1a</AvailabilityZone>
<LicenseModel>general-public-license</LicenseModel>
<InstanceCreateTime>2010-08-04T23:27:36.420Z</InstanceCreateTime>
<AllocatedStorage>50</AllocatedStorage>
<DBInstanceIdentifier>mydbinstance</DBInstanceIdentifier>
<EngineVersion>5.1.49</EngineVersion>
<DBSnapshotIdentifier>mysnapshot1</DBSnapshotIdentifier>
<SnapshotType>manual</SnapshotType>
<MasterUsername>sa</MasterUsername>
<OptionGroupName>myoptiongroupname</OptionGroupName>
<Iops>1000</Iops>
</DBSnapshot>
<DBSnapshot>
<Port>3306</Port>
<SnapshotCreateTime>2012-04-02T00:01:24.082Z</SnapshotCreateTime>
<Engine>mysql</Engine>
<Status>available</Status>
<AvailabilityZone>us-east-1d</AvailabilityZone>
<LicenseModel>general-public-license</LicenseModel>
<InstanceCreateTime>2010-07-16T00:06:59.107Z</InstanceCreateTime>
<AllocatedStorage>60</AllocatedStorage>
<DBInstanceIdentifier>simcoprod01</DBInstanceIdentifier>
<EngineVersion>5.1.47</EngineVersion>
<DBSnapshotIdentifier>rds:simcoprod01-2012-04-02-00-01</DBSnapshotIdentifier>
<SnapshotType>automated</SnapshotType>
<MasterUsername>master</MasterUsername>
<OptionGroupName>myoptiongroupname</OptionGroupName>
<Iops>1000</Iops>
</DBSnapshot>
</DBSnapshots>
</DescribeDBSnapshotsResult>
<ResponseMetadata>
<RequestId>c4191173-8506-11e0-90aa-eb648410240d</RequestId>
</ResponseMetadata>
</DescribeDBSnapshotsResponse>
"""
def test_describe_dbinstances_by_instance(self):
self.set_http_response(status_code=200)
response = self.service_connection.get_all_dbsnapshots(instance_id='simcoprod01')
self.assert_request_parameters({
'Action': 'DescribeDBSnapshots',
'DBInstanceIdentifier': 'simcoprod01'
}, ignore_params_values=['Version'])
self.assertEqual(len(response), 3)
self.assertIsInstance(response[0], DBSnapshot)
self.assertEqual(response[0].id, 'mydbsnapshot')
self.assertEqual(response[0].status, 'available')
self.assertEqual(response[0].instance_id, 'simcoprod01')
self.assertEqual(response[0].engine_version, '5.1.50')
self.assertEqual(response[0].license_model, 'general-public-license')
self.assertEqual(response[0].iops, 1000)
self.assertEqual(response[0].option_group_name, 'myoptiongroupname')
self.assertEqual(response[0].percent_progress, 100)
self.assertEqual(response[0].snapshot_type, 'manual')
self.assertEqual(response[0].source_region, 'eu-west-1')
self.assertEqual(response[0].vpc_id, 'myvpc')
class TestCreateDBSnapshot(AWSMockServiceTestCase):
connection_class = RDSConnection
def default_body(self):
return """
<CreateDBSnapshotResponse xmlns="http://rds.amazonaws.com/doc/2013-05-15/">
<CreateDBSnapshotResult>
<DBSnapshot>
<Port>3306</Port>
<Engine>mysql</Engine>
<Status>creating</Status>
<AvailabilityZone>us-east-1a</AvailabilityZone>
<LicenseModel>general-public-license</LicenseModel>
<InstanceCreateTime>2011-05-23T06:06:43.110Z</InstanceCreateTime>
<AllocatedStorage>10</AllocatedStorage>
<DBInstanceIdentifier>simcoprod01</DBInstanceIdentifier>
<EngineVersion>5.1.50</EngineVersion>
<DBSnapshotIdentifier>mydbsnapshot</DBSnapshotIdentifier>
<SnapshotType>manual</SnapshotType>
<MasterUsername>master</MasterUsername>
</DBSnapshot>
</CreateDBSnapshotResult>
<ResponseMetadata>
<RequestId>c4181d1d-8505-11e0-90aa-eb648410240d</RequestId>
</ResponseMetadata>
</CreateDBSnapshotResponse>
"""
def test_create_dbinstance(self):
self.set_http_response(status_code=200)
response = self.service_connection.create_dbsnapshot('mydbsnapshot', 'simcoprod01')
self.assert_request_parameters({
'Action': 'CreateDBSnapshot',
'DBSnapshotIdentifier': 'mydbsnapshot',
'DBInstanceIdentifier': 'simcoprod01'
}, ignore_params_values=['Version'])
self.assertIsInstance(response, DBSnapshot)
self.assertEqual(response.id, 'mydbsnapshot')
self.assertEqual(response.instance_id, 'simcoprod01')
self.assertEqual(response.status, 'creating')
class TestCopyDBSnapshot(AWSMockServiceTestCase):
connection_class = RDSConnection
def default_body(self):
return """
<CopyDBSnapshotResponse xmlns="http://rds.amazonaws.com/doc/2013-05-15/">
<CopyDBSnapshotResult>
<DBSnapshot>
<Port>3306</Port>
<Engine>mysql</Engine>
<Status>available</Status>
<AvailabilityZone>us-east-1a</AvailabilityZone>
<LicenseModel>general-public-license</LicenseModel>
<InstanceCreateTime>2011-05-23T06:06:43.110Z</InstanceCreateTime>
<AllocatedStorage>10</AllocatedStorage>
<DBInstanceIdentifier>simcoprod01</DBInstanceIdentifier>
<EngineVersion>5.1.50</EngineVersion>
<DBSnapshotIdentifier>mycopieddbsnapshot</DBSnapshotIdentifier>
<SnapshotType>manual</SnapshotType>
<MasterUsername>master</MasterUsername>
</DBSnapshot>
</CopyDBSnapshotResult>
<ResponseMetadata>
<RequestId>c4181d1d-8505-11e0-90aa-eb648410240d</RequestId>
</ResponseMetadata>
</CopyDBSnapshotResponse>
"""
def test_copy_dbinstance(self):
self.set_http_response(status_code=200)
response = self.service_connection.copy_dbsnapshot('myautomaticdbsnapshot', 'mycopieddbsnapshot')
self.assert_request_parameters({
'Action': 'CopyDBSnapshot',
'SourceDBSnapshotIdentifier': 'myautomaticdbsnapshot',
'TargetDBSnapshotIdentifier': 'mycopieddbsnapshot'
}, ignore_params_values=['Version'])
self.assertIsInstance(response, DBSnapshot)
self.assertEqual(response.id, 'mycopieddbsnapshot')
self.assertEqual(response.status, 'available')
class TestDeleteDBSnapshot(AWSMockServiceTestCase):
connection_class = RDSConnection
def default_body(self):
return """
<DeleteDBSnapshotResponse xmlns="http://rds.amazonaws.com/doc/2013-05-15/">
<DeleteDBSnapshotResult>
<DBSnapshot>
<Port>3306</Port>
<SnapshotCreateTime>2011-03-11T07:20:24.082Z</SnapshotCreateTime>
<Engine>mysql</Engine>
<Status>deleted</Status>
<AvailabilityZone>us-east-1d</AvailabilityZone>
<LicenseModel>general-public-license</LicenseModel>
<InstanceCreateTime>2010-07-16T00:06:59.107Z</InstanceCreateTime>
<AllocatedStorage>60</AllocatedStorage>
<DBInstanceIdentifier>simcoprod01</DBInstanceIdentifier>
<EngineVersion>5.1.47</EngineVersion>
<DBSnapshotIdentifier>mysnapshot2</DBSnapshotIdentifier>
<SnapshotType>manual</SnapshotType>
<MasterUsername>master</MasterUsername>
</DBSnapshot>
</DeleteDBSnapshotResult>
<ResponseMetadata>
<RequestId>627a43a1-8507-11e0-bd9b-a7b1ece36d51</RequestId>
</ResponseMetadata>
</DeleteDBSnapshotResponse>
"""
def test_delete_dbinstance(self):
self.set_http_response(status_code=200)
response = self.service_connection.delete_dbsnapshot('mysnapshot2')
self.assert_request_parameters({
'Action': 'DeleteDBSnapshot',
'DBSnapshotIdentifier': 'mysnapshot2'
}, ignore_params_values=['Version'])
self.assertIsInstance(response, DBSnapshot)
self.assertEqual(response.id, 'mysnapshot2')
self.assertEqual(response.status, 'deleted')
class TestRestoreDBInstanceFromDBSnapshot(AWSMockServiceTestCase):
connection_class = RDSConnection
def default_body(self):
return """
<RestoreDBInstanceFromDBSnapshotResponse xmlns="http://rds.amazonaws.com/doc/2013-05-15/">
<RestoreDBInstanceFromDBSnapshotResult>
<DBInstance>
<ReadReplicaDBInstanceIdentifiers/>
<Engine>mysql</Engine>
<PendingModifiedValues/>
<BackupRetentionPeriod>1</BackupRetentionPeriod>
<MultiAZ>false</MultiAZ>
<LicenseModel>general-public-license</LicenseModel>
<DBInstanceStatus>creating</DBInstanceStatus>
<EngineVersion>5.1.50</EngineVersion>
<DBInstanceIdentifier>myrestoreddbinstance</DBInstanceIdentifier>
<DBParameterGroups>
<DBParameterGroup>
<ParameterApplyStatus>in-sync</ParameterApplyStatus>
<DBParameterGroupName>default.mysql5.1</DBParameterGroupName>
</DBParameterGroup>
</DBParameterGroups>
<DBSecurityGroups>
<DBSecurityGroup>
<Status>active</Status>
<DBSecurityGroupName>default</DBSecurityGroupName>
</DBSecurityGroup>
</DBSecurityGroups>
<PreferredBackupWindow>00:00-00:30</PreferredBackupWindow>
<AutoMinorVersionUpgrade>true</AutoMinorVersionUpgrade>
<PreferredMaintenanceWindow>sat:07:30-sat:08:00</PreferredMaintenanceWindow>
<AllocatedStorage>10</AllocatedStorage>
<DBInstanceClass>db.m1.large</DBInstanceClass>
<MasterUsername>master</MasterUsername>
</DBInstance>
</RestoreDBInstanceFromDBSnapshotResult>
<ResponseMetadata>
<RequestId>7ca622e8-8508-11e0-bd9b-a7b1ece36d51</RequestId>
</ResponseMetadata>
</RestoreDBInstanceFromDBSnapshotResponse>
"""
def test_restore_dbinstance_from_dbsnapshot(self):
self.set_http_response(status_code=200)
response = self.service_connection.restore_dbinstance_from_dbsnapshot('mydbsnapshot',
'myrestoreddbinstance',
'db.m1.large',
'3306',
'us-east-1a',
'false',
'true')
self.assert_request_parameters({
'Action': 'RestoreDBInstanceFromDBSnapshot',
'DBSnapshotIdentifier': 'mydbsnapshot',
'DBInstanceIdentifier': 'myrestoreddbinstance',
'DBInstanceClass': 'db.m1.large',
'Port': '3306',
'AvailabilityZone': 'us-east-1a',
'MultiAZ': 'false',
'AutoMinorVersionUpgrade': 'true'
}, ignore_params_values=['Version'])
self.assertIsInstance(response, DBInstance)
self.assertEqual(response.id, 'myrestoreddbinstance')
self.assertEqual(response.status, 'creating')
self.assertEqual(response.instance_class, 'db.m1.large')
self.assertEqual(response.multi_az, False)
if __name__ == '__main__':
unittest.main()
| [
"noreply@github.com"
] | cloudera.noreply@github.com |
cd3406d17daddd03c1243d992e77947b8c7b3e31 | bdbf05347487bc94da2ab43c069030491aad30c1 | /bd_log_analysis.py | 133b4facc0f461d050719f6f7891244e197fe37c | [] | no_license | birkin/bd_log_analysis | d1baf6375bb73ae615ece3ea006f2c78cca93574 | 59b46c92be5beb2fe88590a4d316e55901e6c2d8 | refs/heads/master | 2021-01-22T11:48:00.706991 | 2015-05-20T12:52:20 | 2015-05-20T12:52:20 | 35,901,355 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,048 | py | # -*- coding: utf-8 -*-
""" Compares new borrowdirect api results against current in-production deprecated code.
Parses logging added to controller that summarizes differences between new and old tunneler calls. """
import glob, json, os, pprint
class Analyzer( object ):
def __init__( self ):
self.LOGS_DIR = unicode( os.environ[u'BDLOG_ANALYSIS__LOGS_DIR'] )
self.filepaths_list = []
self.labels = [ u'new_api_found', u'new_api_requestable', u'old_api_found', u'old_api_requestable' ]
self.summary = {}
def prep_filepaths_list( self ):
""" Creates array filepaths.
Called by if __name__ """
os.chdir( self.LOGS_DIR )
for f in glob.glob("easyborrow_controller.log*"):
filepath = os.path.join( self.LOGS_DIR, f )
self.filepaths_list.append( filepath )
return
def process_log_files( self ):
""" Processes each log file, updating counts.
Called by if __name__ """
for filepath in self.filepaths_list:
with open( filepath ) as f:
lines_utf8 = f.readlines()
self.parse_log_file( lines_utf8 )
# break
return
## helpers
def parse_log_file( self, lines_utf8 ):
""" Parses given lines to update counts.
Called by process_log_files() """
relevant_segments = self.find_relevant_segments( lines_utf8 )
cleaned_lines = self.clean_relevant_segments( relevant_segments )
self.update_counts( cleaned_lines )
return
def find_relevant_segments( self, lines_utf8 ):
""" Finds comparison lines and merges them into single string.
Called by parse_log_file() """
( segments, segment ) = ( [], [] )
for line_utf8 in lines_utf8:
line = line_utf8.decode( u'utf-8' )
for label in self.labels:
if label in line:
segment.append( line )
if len( segment ) == 4:
joined_segment = u''.join( segment )
segments.append( joined_segment )
segment = []
return segments
def clean_relevant_segments( self, relevant_segments ):
""" Turns each messy line into a json string; json isn't used, it's to normalize the strings.
Called by parse_log_file() """
cleaned_lines = []
for line in relevant_segments:
start = line.find( u'`' ) + 1
end = line.rfind( u'`' )
str1 = line[start:end]
str2 = self.run_replaces( str1 )
dct = json.loads( str2 )
jsn = json.dumps( dct, sort_keys=True )
cleaned_lines.append( jsn.decode(u'utf-8') )
return cleaned_lines
def run_replaces( self, str1 ):
""" Runs a series of replaces to normalize string.
Called by clean_relevant_segments() """
str2 = str1.replace( u'\n', u'' )
str3 = str2.replace( u"'", u'"' )
str4 = str3.replace( u'u"', u'"' )
str5 = str4.replace( u'True', u'true' )
str6 = str5.replace( u'False', u'false' )
str7 = str6.replace( u'None', u'null' )
return str7
def update_counts( self, cleaned_lines ):
""" Checks and updates patterns, and counts.
Called by parse_log_file() """
if u'total_entries' in self.summary.keys():
self.summary[u'total_entries'] += len(cleaned_lines)
else:
self.summary[u'total_entries'] = len(cleaned_lines)
for pattern in cleaned_lines:
if pattern in self.summary.keys():
self.summary[pattern] += 1
else:
self.summary[pattern] = 0
return
if __name__ == u'__main__':
""" Loads and parses logs and prints summary.
Called manually. """
anlyzr = Analyzer()
anlyzr.prep_filepaths_list()
# pprint.pprint( anlyzr.filepaths_list )
anlyzr.process_log_files()
pprint.pprint( anlyzr.summary )
| [
"birkin.diana@gmail.com"
] | birkin.diana@gmail.com |
8b58e97d148a2a4044dc82a11131e9a37053dbee | 2c872fedcdc12c89742d10c2f1c821eed0470726 | /pbase/day10/jiangyi/day10/exercise/lambda2.py | 60afaa4052e86373221e016444b15042f5ec9539 | [] | no_license | zuigehulu/AID1811 | 581c3c7a37df9fa928bc632e4891fc9bafe69201 | 10cab0869875290646a9e5d815ff159d0116990e | refs/heads/master | 2020-04-19T16:33:04.174841 | 2019-01-30T07:58:24 | 2019-01-30T07:58:24 | 168,307,918 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 334 | py | # 2. 写一个lambda 表达式来创建函数,此函数返回两个参数的最大值
# def mymax(x, y):
# ...
# mymax = lambda .....
# print(mymax(100, 200)) # 200
# print(mymax("ABC", '123')) # ABC
mymax = lambda x,y:max(x,y)
print(mymax(100, 200)) # 200
print(mymax("ABC", '123')) # ABC
| [
"442315617@qq.com"
] | 442315617@qq.com |
d287f8c476b7d0115a839f5172afcaeee380108d | d8c07694387202f7c72b30ddc9fc7835637f2f96 | /faith_pms/forms.py | 4cb7682f59fae2453eab3b88c3b57f3418d842f3 | [] | no_license | shuvro-zz/Patient-Management-System-2 | 7f6c357dc64d4e81e1ca976a42b83f915ba7fee2 | f36db339b680e8bbdff1ef3d42ba07809e985bd1 | refs/heads/master | 2020-08-18T20:06:06.021595 | 2018-03-23T12:10:55 | 2018-03-23T12:10:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,164 | py | from django import forms
from .models import Doctor, Patient, NextOfKin, Medicine, MedicalCover, AllergiesAndDirectives, Treatment
#......
class UpdateProfileForm(forms.ModelForm):
class Meta:
model = Doctor
fields = ('profile_photo', 'name', 'hospital', 'email', 'description', 'title')
class NewPatientForm(forms.ModelForm):
class Meta:
model = Patient
exclude = ('doctor',)
class NewNextOfKinForm(forms.ModelForm):
class Meta:
model = NextOfKin
fields = ('name', 'relationship', 'phone_number', 'email')
class NewMedicineForm(forms.ModelForm):
class Meta:
model = Medicine
fields = ('name','date_given', 'doctor_prescribed')
class MedicalCoverForm(forms.ModelForm):
class Meta:
model = MedicalCover
fields = ('name', 'email', 'type_of_cover')
class AllergiesAndDirectivesForm(forms.ModelForm):
class Meta:
model = AllergiesAndDirectives
fields = ('name', 'level')
class TreatmentForm(forms.ModelForm):
class Meta:
model = Treatment
fields = ('symptoms', 'diagnosis', 'recommendations', 'consultation_fee')
| [
"biinewton382@gmail.com"
] | biinewton382@gmail.com |
6c96a3056472a5a6f6bfccf6a0a581f1dff5d3dc | c5bc4b7f885ca87804feb9cb7d416a6a4e9bed82 | /images/fish-u-quartlet-2.py | b16a5e56225a2e55790b47d4348de08d8ed10237 | [] | no_license | anandology/the-joy-of-programming | d3d4a439665d81bf499aabf127b04a5a5a9cd5bb | 231be9dc97fb8935f490237277d1cf16b28fe366 | refs/heads/master | 2023-01-23T07:45:25.811908 | 2020-12-06T12:34:14 | 2020-12-06T12:34:14 | 317,910,429 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 203 | py |
fish = get_fish(border=True)
fish2 = flip(rot45(fish))
u = over(
fish2, rot(fish2),
rot(rot(fish2)), rot(rot(rot(fish2)))
)
x = quartlet(u, u, u, u)
y = quartlet(x, x, x, x)
show(y, scale=True)
| [
"anandology@gmail.com"
] | anandology@gmail.com |
48ffe60aba4596db17b05c747beb4dd394451e84 | 6edd5a50f07843de18175c04796348f7fdc4f74d | /Python/simrank.py | 6016316641b030b8fa58298c85fdf50013b95b5c | [] | no_license | rogergranada/_utilsdev | 4f14a1e910103c33e3a8e820bb3e55483bd27e69 | 977a8d98a6934b9354ec233da6e0ef31621282f3 | refs/heads/master | 2021-06-01T17:07:14.773949 | 2020-10-22T22:06:43 | 2020-10-22T22:06:43 | 124,608,594 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,258 | py | import copy
from collections import defaultdict
def simrank(G, r=0.9, max_iter=100):
sim_old = defaultdict(list)
sim = defaultdict(list)
for n in G.nodes():
sim[n] = defaultdict(int)
sim[n][n] = 1
sim_old[n] = defaultdict(int)
sim_old[n][n] = 0
# recursively calculate simrank
for iter_ctr in range(max_iter):
if _is_converge(sim, sim_old):
break
sim_old = copy.deepcopy(sim)
for u in G.nodes():
for v in G.nodes():
if u == v:
continue
s_uv = 0.0
for n_u in G.neighbors(u):
for n_v in G.neighbors(v):
s_uv += sim_old[n_u][n_v]
sim[u][v] = (r * s_uv / (len(G.neighbors(u)) * len(G.neighbors(v))))
return sim
def _is_converge(s1, s2, eps=1e-4):
for i in s1.keys():
for j in s1[i].keys():
if abs(s1[i][j] - s2[i][j]) >= eps:
return False
return True
if __name__ == "main":
import networkx
G = networkx.Graph()
G.add_edges_from([('a','b'), ('b', 'c'), ('c','a'), ('c','d')])
simrank(G)
#S(a,b) = r * (S(b,a)+S(b,c)+S(c,a)+S(c,c))/(2*2) = 0.9 * (0.6538+0.6261+0.6261+1)/4 = 0.6538,
| [
"roger.leitzke@gmail.com"
] | roger.leitzke@gmail.com |
b823f84539a45d2ea8af50cf386fc0f68d48c289 | 2b45cbccd03fb09be78b2241d05beeae171a2e18 | /LeetCode 热题 HOT 100/letterCombinations.py | 23b65251a336177d70ae1440f8769a587bcc6b62 | [
"Apache-2.0"
] | permissive | MaoningGuan/LeetCode | c90f78ce87a8116458a86c49dbe32e172036f7b4 | 62419b49000e79962bcdc99cd98afd2fb82ea345 | refs/heads/master | 2023-01-03T14:52:04.278708 | 2020-11-01T12:15:41 | 2020-11-01T12:15:41 | 282,859,997 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,930 | py | # -*- coding: utf-8 -*-
"""
17. 电话号码的字母组合
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
https://assets.leetcode-cn.com/aliyun-lc-upload/original_images/17_telephone_keypad.png
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
"""
from typing import List
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
"""
方法:回溯(使用递归来实现回溯算法)
时间复杂度:O(3^m x 4^n)
空间复杂度:O(m+n)
其中 m 是输入中对应 3 个字母的数字个数(包括数字 2、3、4、5、6、8),
n 是输入中对应 4 个字母的数字个数(包括数字 7、9),m+n 是输入数字的总个数。
:param digits:
:return:
"""
if not digits:
return list()
phoneMap = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
}
def backtrack(index: int):
if index == len(digits):
combinations.append("".join(combination))
else:
digit = digits[index]
for letter in phoneMap[digit]:
combination.append(letter)
backtrack(index + 1)
combination.pop()
combination = list()
combinations = list()
backtrack(0)
return combinations
if __name__ == '__main__':
digits = "23"
solution = Solution()
print(solution.letterCombinations(digits))
| [
"1812711281@qq.com"
] | 1812711281@qq.com |
a7034ac4e883245f425483f76977c4b5f25b3a3b | 3be95bfd788472dfd73826c6214355788f05f2cc | /rest_framework_swagger/urlparser.py | a6e3ce1f28bfbef884c7eead592e44bdaf2f9a8c | [] | no_license | pleasedontbelong/mystore | a2acba4d3b8dd070471139dfddc5baa5f54393c0 | 8e156f4c9c5d6cd273dfbbd57eb90c65c3986e9f | refs/heads/master | 2020-12-31T03:26:27.074955 | 2016-11-09T23:14:01 | 2016-11-09T23:14:01 | 56,080,261 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,362 | py | from importlib import import_module
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern
from django.contrib.admindocs.views import simplify_regex
from django.conf import settings
from rest_framework.views import APIView
class UrlParser(object):
def __init__(self, config, request):
self.urlconf = settings.ROOT_URLCONF
self.exclude_namespaces = config.get('exclude_namespaces', [])
self.exclude_module_paths = config.get('exclude_module_paths', [])
self.include_module_paths = config.get('include_module_paths', [])
self.exclude_url_patterns = config.get('exclude_url_patterns', [])
self.exclude_url_patterns_names = config.get('exclude_url_patterns_names', [])
def get_apis(self):
"""
Returns all the DRF APIViews found in the project URLs
"""
urls = import_module(self.urlconf)
return self.__flatten_patterns_tree__(urls.urlpatterns)
def __assemble_endpoint_data__(self, pattern, prefix=''):
"""
Creates a dictionary for matched API urls
pattern -- the pattern to parse
prefix -- the API path prefix (used by recursion)
"""
callback = self.__get_pattern_api_callback__(pattern)
if callback is None or self.__exclude_router_api_root__(callback):
return
path = simplify_regex(prefix + pattern.regex.pattern)
path = path.replace('<', '{').replace('>', '}')
if self.__exclude_format_endpoints__(path):
return
return {
'path': path,
'pattern': pattern,
'callback': callback,
}
def __flatten_patterns_tree__(self, patterns, prefix=''):
"""
Uses recursion to flatten url tree.
patterns -- urlpatterns list
prefix -- (optional) Prefix for URL pattern
"""
pattern_list = []
for pattern in patterns:
if isinstance(pattern, RegexURLPattern):
endpoint_data = self.__assemble_endpoint_data__(pattern, prefix)
if endpoint_data is None:
continue
if any(excluded in endpoint_data['path'] for excluded in self.exclude_url_patterns):
continue
if endpoint_data['pattern'].name in self.exclude_url_patterns_names:
continue
pattern_list.append(endpoint_data)
elif isinstance(pattern, RegexURLResolver):
api_urls_module = pattern.urlconf_name.__name__ if hasattr(pattern.urlconf_name, '__name__') else ""
# only modules included on the include_module_paths list
if self.include_module_paths and api_urls_module not in self.include_module_paths:
continue
# except modules included on the exclude_module_paths list
if api_urls_module in self.exclude_module_paths:
continue
if pattern.namespace is not None and pattern.namespace in self.exclude_namespaces:
continue
pref = prefix + pattern.regex.pattern
pattern_list.extend(self.__flatten_patterns_tree__(
pattern.url_patterns,
prefix=pref
))
return pattern_list
def __get_pattern_api_callback__(self, pattern):
"""
Verifies that pattern callback is a subclass of APIView, and returns the class
Handles older django & django rest 'cls_instance'
"""
if not hasattr(pattern, 'callback'):
return
if (hasattr(pattern.callback, 'cls') and
issubclass(pattern.callback.cls, APIView)):
return pattern.callback.cls
elif (hasattr(pattern.callback, 'cls_instance') and
isinstance(pattern.callback.cls_instance, APIView)):
return pattern.callback.cls_instance
def __exclude_router_api_root__(self, callback):
"""
Returns True if the URL's callback is rest_framework.routers.APIRoot
"""
return callback.__module__ == 'rest_framework.routers'
def __exclude_format_endpoints__(self, path):
"""
Excludes URL patterns that contain .{format}
"""
return '.{format}' in path
| [
"pleasedontbelong@gmail.com"
] | pleasedontbelong@gmail.com |
8b23eaa70e67c8fb794c52018f9a0e13cf63f385 | 0628653df1b75bc0365b09d6a4364b407b39cea3 | /python4gmsh/extra.py | e0aa8bb015830a4fff7a821e4e4beba6a868770b | [
"BSD-3-Clause"
] | permissive | sapedit/python4gmsh | 8b41bfdd69c4518c12dd0017f1420e7018c58898 | 967dc6d47d05eeb18229a2e5fc40ec89a036dcf6 | refs/heads/master | 2021-01-12T20:31:47.760948 | 2014-01-24T22:23:30 | 2014-01-24T22:23:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,879 | py | # -*- coding: utf8 -*-
#
# Copyright (c) 2013--2014, Nico Schlömer
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the {organization} nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
'''
This module contains some convenience functions for building simple geometric
objects with Gmsh.
'''
import numpy as np
from basic import Point, Line, LineLoop, PlaneSurface, Comment, Circle, \
CompoundLine, RuledSurface, Volume, PhysicalVolume, SurfaceLoop, Array, \
Extrude, CompoundVolume
def rotation_matrix(u, theta):
'''Return matrix that implements the rotation around the vector u by the
angle theta, cf.
<https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle>.
'''
# Cross-product matrix.
cpm = np.array([[0.0, -u[2], u[1]],
[u[2], 0.0, -u[0]],
[-u[1], u[0], 0.0]])
c = np.cos(theta)
s = np.sin(theta)
R = np.eye(3) * c \
+ s * cpm \
+ (1.0 - c) * np.outer(u, u)
return R
def add_rectangle(xmin, xmax, ymin, ymax, z, lcar):
X = [[xmin, ymin, z],
[xmax, ymin, z],
[xmax, ymax, z],
[xmin, ymax, z]]
# Create points.
p = [Point(x, lcar) for x in X]
# Create lines
e = [Line(p[k], p[k+1]) for k in range(len(p)-1)]
e.append(Line(p[-1], p[0]))
ll = LineLoop(e)
s = PlaneSurface(ll)
return s
def add_polygon(X, lcar):
# Create points.
p = [Point(x, lcar) for x in X]
# Create lines
e = [Line(p[k], p[k+1]) for k in range(len(p)-1)]
e.append(Line(p[-1], p[0]))
ll = LineLoop(e)
s = PlaneSurface(ll)
return s
def add_circle(radius, lcar,
R=np.eye(3),
x0=np.array([0.0, 0.0, 0.0]),
compound=False,
num_sections=3
):
'''Add circle in the y-z-plane.
'''
# Define points that make the circle (midpoint and the four cardinal
# directions).
X = [[0.0, 0.0, 0.0]]
if num_sections == 4:
# For accuracy, the points are provided explicitly.
X = [[0.0, 0.0, 0.0],
[0.0, radius, 0.0],
[0.0, 0.0, radius],
[0.0, -radius, 0.0],
[0.0, 0.0, -radius]]
else:
for k in range(num_sections):
alpha = 2*np.pi * k / num_sections
X.append([0.0, radius*np.cos(alpha), radius*np.sin(alpha)])
# Apply the transformation.
# TODO assert that the transformation preserves circles
X = [np.dot(R, x) + x0 for x in X]
# Add Gmsh Points.
Comment('Points')
p = [Point(x, lcar) for x in X]
# Define the circle arcs.
Comment('Circle arcs')
c = []
for k in range(1, len(p)-1):
c.append(Circle([p[k], p[0], p[k+1]]))
# Don't forget the closing arc.
c.append(Circle([p[-1], p[0], p[1]]))
if compound:
c = [CompoundLine(c)]
return c
def add_ball(x0, radius, lcar,
with_volume=True,
holes=[],
label=None
):
'''Creates a ball with a given radius around a given midpoint x0.
'''
# Add points.
p = [Point(x0, lcar=lcar),
Point([x0[0]+radius, x0[1], x0[2]], lcar=lcar),
Point([x0[0], x0[1]+radius, x0[2]], lcar=lcar),
Point([x0[0], x0[1], x0[2]+radius], lcar=lcar),
Point([x0[0]-radius, x0[1], x0[2]], lcar=lcar),
Point([x0[0], x0[1]-radius, x0[2]], lcar=lcar),
Point([x0[0], x0[1], x0[2]-radius], lcar=lcar)
]
# Add ball skeleton.
c = [Circle([p[1], p[0], p[6]]),
Circle([p[6], p[0], p[4]]),
Circle([p[4], p[0], p[3]]),
Circle([p[3], p[0], p[1]]),
Circle([p[1], p[0], p[2]]),
Circle([p[2], p[0], p[4]]),
Circle([p[4], p[0], p[5]]),
Circle([p[5], p[0], p[1]]),
Circle([p[6], p[0], p[2]]),
Circle([p[2], p[0], p[3]]),
Circle([p[3], p[0], p[5]]),
Circle([p[5], p[0], p[6]])
]
# Add surfaces (1/8th of the ball surface).
ll = [LineLoop([c[4], c[9], c[3]]),
LineLoop([c[8], '-'+c[4], c[0]]),
LineLoop([c[11], '-'+c[7], '-'+c[0]]),
LineLoop([c[7], '-'+c[3], c[10]]),
LineLoop(['-'+c[9], c[5], c[2]]),
LineLoop(['-'+c[10], '-'+c[2], c[6]]),
LineLoop(['-'+c[1], '-'+c[6], '-'+c[11]]),
LineLoop(['-'+c[5], '-'+c[8], c[1]])
]
# Create a surface for each line loop.
s = [RuledSurface(l) for l in ll]
# Create the surface loop.
surface_loop = SurfaceLoop(s)
if holes:
# Create an array of surface loops; the first entry is the outer
# surface loop, the following ones are holes.
surface_loop = Array([surface_loop] + holes)
# Create volume.
if with_volume:
volume = Volume(surface_loop)
if label:
PhysicalVolume(volume, label)
else:
volume = None
return volume, surface_loop
def add_box(x0, x1, y0, y1, z0, z1,
lcar,
with_volume=True,
holes=[],
label=None
):
# Define corner points.
p = [Point([x1, y1, z1], lcar=lcar),
Point([x1, y1, z0], lcar=lcar),
Point([x1, y0, z1], lcar=lcar),
Point([x1, y0, z0], lcar=lcar),
Point([x0, y1, z1], lcar=lcar),
Point([x0, y1, z0], lcar=lcar),
Point([x0, y0, z1], lcar=lcar),
Point([x0, y0, z0], lcar=lcar)
]
# Define edges.
e = [Line(p[0], p[1]),
Line(p[0], p[2]),
Line(p[0], p[4]),
Line(p[1], p[3]),
Line(p[1], p[5]),
Line(p[2], p[3]),
Line(p[2], p[6]),
Line(p[3], p[7]),
Line(p[4], p[5]),
Line(p[4], p[6]),
Line(p[5], p[7]),
Line(p[6], p[7])
]
# Define the six line loops.
ll = [LineLoop([e[0], e[3], '-'+e[5], '-'+e[1]]),
LineLoop([e[0], e[4], '-'+e[8], '-'+e[2]]),
LineLoop([e[1], e[6], '-'+e[9], '-'+e[2]]),
LineLoop([e[3], e[7], '-'+e[10], '-'+e[4]]),
LineLoop([e[5], e[7], '-'+e[11], '-'+e[6]]),
LineLoop([e[8], e[10], '-'+e[11], '-'+e[9]])
]
# Create a surface for each line loop.
s = [RuledSurface(l) for l in ll]
# Create the surface loop.
surface_loop = SurfaceLoop(s)
if holes:
# Create an array of surface loops; the first entry is the outer
# surface loop, the following ones are holes.
surface_loop = Array([surface_loop] + holes)
if with_volume:
# Create volume
vol = Volume(surface_loop)
if label:
PhysicalVolume(vol, label)
else:
vol = None
return vol, surface_loop
def add_torus(irad, orad,
lcar,
R=np.eye(3),
x0=np.array([0.0, 0.0, 0.0]),
label=None
):
'''Create Gmsh code for torus with
irad ... inner radius
orad ... outer radius
under the coordinate transformation
x_hat = R*x + x0.
'''
Comment(76 * '-')
Comment('Torus')
# Add circle
x0t = np.dot(R, np.array([0.0, orad, 0.0]))
c = add_circle(irad, lcar, R=R, x0=x0+x0t)
rot_axis = [0.0, 0.0, 1.0]
rot_axis = np.dot(R, rot_axis)
point_on_rot_axis = [0.0, 0.0, 0.0]
point_on_rot_axis = np.dot(R, point_on_rot_axis) + x0
# Form the torus by extruding the circle three times by 2/3*pi.
# This works around the inability of Gmsh to extrude by pi or more. The
# Extrude() macro returns an array; the first [0] entry in the array is
# the entity that has been extruded at the far end. This can be used for
# the following Extrude() step. The second [1] entry of the array is the
# surface that was created by the extrusion.
previous = c
angle = '2*Pi/3'
all_names = []
for i in range(3):
Comment('Round no. %s' % (i+1))
for k in range(len(previous)):
# ts1[] = Extrude {{0,0,1}, {0,0,0}, 2*Pi/3}{Line{tc1};};
# ...
name = Extrude('Line{%s}' % previous[k],
rotation_axis=rot_axis,
point_on_axis=point_on_rot_axis,
angle=angle
)
all_names.append(name)
previous[k] = name + '[0]'
# Now build surface loop and volume.
all_surfaces = [name + '[1]' for name in all_names]
#compound_surface = CompoundSurface(all_surfaces)
surface_loop = SurfaceLoop(all_surfaces)
vol = Volume(surface_loop)
if label:
PhysicalVolume(vol, label)
Comment(76*'-')
return
def add_torus2(irad, orad,
lcar,
R=np.eye(3),
x0=np.array([0.0, 0.0, 0.0]),
label=None
):
'''Create Gmsh code for torus with
irad ... inner radius
orad ... outer radius
under the coordinate transformation
x_hat = R*x + x0.
'''
Comment(76*'-')
Comment('Torus')
# Add circle
x0t = np.dot(R, np.array([0.0, orad, 0.0]))
c = add_circle(irad, lcar, R=R, x0=x0+x0t)
ll = LineLoop(c)
s = PlaneSurface(ll)
rot_axis = [0.0, 0.0, 1.0]
rot_axis = np.dot(R, rot_axis)
point_on_rot_axis = [0.0, 0.0, 0.0]
point_on_rot_axis = np.dot(R, point_on_rot_axis) + x0
# Form the torus by extruding the circle three times by 2/3*pi.
# This works around the inability of Gmsh to extrude by pi or more. The
# Extrude() macro returns an array; the first [0] entry in the array is
# the entity that has been extruded at the far end. This can be used for
# the following Extrude() step. The second [1] entry of the array is the
# surface that was created by the extrusion.
previous = s
all_names = []
num_steps = 3
for i in range(num_steps):
name = Extrude('Surface{%s}' % previous,
rotation_axis=rot_axis,
point_on_axis=point_on_rot_axis,
angle='2*Pi/%d' % num_steps
)
previous = name + '[0]'
all_names.append(name)
all_volumes = [name + '[1]' for name in all_names]
vol = CompoundVolume(all_volumes)
if label:
PhysicalVolume(vol, label)
Comment(76*'-')
return
def add_pipe(outer_radius, inner_radius, length,
R=np.eye(3),
x0=np.array([0.0, 0.0, 0.0]),
label=None,
lcar=0.1
):
'''Hollow cylinder.
Define a rectangle, extrude it by rotation.
'''
Comment('Define rectangle.')
X = np.array([[0.0, outer_radius, -0.5*length],
[0.0, outer_radius, 0.5*length],
[0.0, inner_radius, 0.5*length],
[0.0, inner_radius, -0.5*length]
])
# Apply transformation.
X = [np.dot(R, x) + x0 for x in X]
# Create points set.
p = [Point(x, lcar) for x in X]
# Define edges.
e = [Line(p[0], p[1]),
Line(p[1], p[2]),
Line(p[2], p[3]),
Line(p[3], p[0])
]
rot_axis = [0.0, 0.0, 1.0]
rot_axis = np.dot(R, rot_axis)
point_on_rot_axis = [0.0, 0.0, 0.0]
point_on_rot_axis = np.dot(R, point_on_rot_axis) + x0
# Extrude all edges three times by 2*Pi/3.
previous = e
angle = '2*Pi/3'
all_names = []
#com = []
Comment('Extrude in 3 steps.')
for i in range(3):
Comment('Step %s' % (i+1))
for k in range(len(previous)):
# ts1[] = Extrude {{0,0,1}, {0,0,0}, 2*Pi/3}{Line{tc1};};
name = Extrude('Line{%s}' % previous[k],
rotation_axis=rot_axis,
point_on_axis=point_on_rot_axis,
angle=angle
)
#if k==0:
# com.append(name+'[1]')
#else:
# all_names.append(name+'[1]')
all_names.append(name+'[1]')
previous[k] = name + '[0]'
#
#cs = CompoundSurface(com)
# Now just add surface loop and volume.
all_surfaces = all_names
#all_surfaces = all_names + [cs]
surface_loop = SurfaceLoop(all_surfaces)
vol = Volume(surface_loop)
if label:
PhysicalVolume(vol, label)
return
def add_pipe2(outer_radius, inner_radius, length,
R=np.eye(3),
x0=np.array([0.0, 0.0, 0.0]),
label=None,
lcar=0.1
):
'''Hollow cylinder.
Define a ring, extrude it by translation.
'''
# Define ring which to Extrude by translation.
c_inner = add_circle(inner_radius, lcar,
R=np.eye(3),
x0=np.array([0.0, 0.0, 0.0])
)
ll_inner = LineLoop(c_inner)
c_outer = add_circle(outer_radius, lcar,
R=np.eye(3),
x0=np.array([0.0, 0.0, 0.0])
)
ll_outer = LineLoop(c_outer)
surf = PlaneSurface(','.join([ll_outer, ll_inner]))
# Now Extrude the ring surface.
name = Extrude('Surface{%s}' % surf,
translation_axis=[length, 0, 0]
)
vol = name + '[0]'
if label:
PhysicalVolume(vol, label)
return vol
| [
"nico.schloemer@gmail.com"
] | nico.schloemer@gmail.com |
06c92954daf2d45ac1a030afda585d114c09e9c6 | 47c6b0172393a76aba36afb620ad47d6801592bf | /contrib/dbio/signals.py | 27c67654d0694e8e444a50fda31ab7e384459f03 | [
"MIT"
] | permissive | sheppard/wq.db | b56238f6345e6ae3b6ecb70e4522a355d06bc436 | b16881830c5a87b132098d1391709c644376c2d4 | refs/heads/master | 2020-12-01T03:03:53.601427 | 2013-12-19T20:08:25 | 2013-12-19T20:08:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 95 | py | from django.dispatch import Signal
import_complete = Signal(providing_args=['file', 'status'])
| [
"andrew@wq.io"
] | andrew@wq.io |
0a36f233d4aec745a24f2c665a94a70ebcffc487 | 83ed1e2f176133c03a5f6dfa504b8df15ae71efb | /projects/VisionElasticFit/guessElasticLinePosition_second_pass.py | 55e6ab4e818b60b9c6d9cece363b6b1e37445b1f | [] | no_license | jmborr/code | 319db14f28e1dea27f9fc703be629f171e6bd95f | 32720b57699bf01803367566cdc5fff2b6bce810 | refs/heads/master | 2022-03-09T16:11:07.455402 | 2019-10-28T15:03:01 | 2019-10-28T15:03:01 | 23,627,627 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,025 | py | '''
This script will try to find the elastic line and the adjacent peak
for a certain number of pixels.
Edit the below variables, then run the script
'''
import sys
sys.path.append('/home/jmborr/devel/mantidproject/mantid/Code/debug/bin')
#from mantid.simpleapi import *
from mantid.simpleapi import FindPeaks, CloneWorkspace, Fit, ExtractSingleSpectrum, Rebin, DeleteWorkspace, Load, Max
from pdb import set_trace as trace
from copy import deepcopy
#DT=100
dt=4.0 # bin spacing (in microseconds)
minIntensity=50 # minimum intensity for the second pass
n_tube=8 # eight tubes per pack
n_pixel_per_tube=128 # 128 tubes per pixel
n_pixel = n_tube * n_pixel_per_tube # total number of pixels (1024)
def FindHighestPeak(sp,PeakFunction='Gaussian', tofRange=(2000,5000), dx=1.0,guess_width=100):
"""Use FindPeaks algorithm with a variable FWHM to find all possible peaks
(2000,5000) is the expected TOF range where the elastic line can be found
dx is the bin width (in microseconds)
This thing is an overkill and takes a lot of time, but it should find the peak
"""
def compareLines(line,peaks,targetWidth,tofRange):
""" Parse the results from FindPeaks in order to retrieve the best peak candidate,
then compare to current best peak """
nRows = peaks.rowCount()
for iRow in range(0,nRows):
if not line or line['height'] < peaks.row( iRow )['height']:
width = peaks.row( iRow )['width'] #is the peak within width range ?
if 0.5*targetWidth<width and width<2*targetWidth:
centre = peaks.row( iRow )['centre'] #is the peak within range ?
if tofRange[0]<centre and centre<tofRange[1]:
line = deepcopy( peaks.row( iRow ) )
return line
line = None
#print 'scan assuming position of the peak'
tofList=range(int(tofRange[0]),int(tofRange[1]),int(dt))
fwhm=int(guess_width*0.8)
max_fwhm=int(guess_width*1.2)
delta_fwhm=max(1,(max_fwhm-fwhm)/5)
while fwhm <= max_fwhm:
print 'fwhm=',fwhm,'HighBackground=True'
peaks = FindPeaks( sp, PeaksList=sp.getName()+'_peaks', FWHM=fwhm, PeakFunction=PeakFunction,HighBackground=True,BackgroundType='Linear',PeakPositions=tofList)
line = compareLines(line,peaks,dx*fwhm,tofRange)
print 'fwhm=',fwhm,'HighBackground=False'
peaks = FindPeaks( sp, PeaksList=sp.getName()+'_peaks', FWHM=fwhm, PeakFunction=PeakFunction,HighBackground=False,BackgroundType='Linear',PeakPositions=tofList)
line = compareLines(line,peaks,dx*fwhm,tofRange)
fwhm += delta_fwhm
#print '\nFindPeaks returns=',line
return line
def findElasticLinePosition(spectrum,tofRange=(0,5000),guess_width=100):
"""Fit the elastic line with a Gaussian, and return the center position """
peak = FindHighestPeak(spectrum,tofRange=tofRange,dx=dt,guess_width=guess_width) #find the strongest peak in the TOF range
#Fit the line to a Gaussian. Initial guess from output from FindHighestPeak
try:
centre = peak['centre']
sigma = peak['width']/2.35 #From FWHM to standard deviation
except TypeError:
print 'could not find peak for spectrum index ',spectrum.getDetector(0).getID()
return None
startX = centre-sigma
endX = centre+sigma #set the fitting boundaries
funcStr = 'name=Gaussian, Height=%f, PeakCentre=%f, Sigma=%f'%(peak['height'], centre, sigma)
gfit = Fit(funcStr, spectrum.getName(), StartX=startX, EndX=endX, CreateOutput='1')
#Retrieve the optimized fitting parameters
fittedParams = { 'Height':0, 'PeakCentre':0, 'Sigma':0}
for iRow in range( gfit[3].rowCount() - 1):
row = gfit[3].row( iRow )
fittedParams[ row['Name'] ] = row['Value']
return fittedParams
def readIn(datafile):
""" Read in the output data file from the first pass of guessElasticLine.
The output structure is a list on 'detectors' """
fp=[None,]*n_pixel
for line in open(datafile,'r').readlines():
if line[0]=='#': continue
items=line.split()
entry={'w_index':int(items[0]),
'det_id':int(items[1]),
'peak_center':float(items[2]),
'peak_height':float(items[3]),
'peak_width':float(items[4]),
'nevents':int(items[5]),
'bank':int(items[6]),
'tube_id':int(items[7]),
'line':line}
i_pixel=entry['w_index']
fp[i_pixel]=entry
return fp
def linearExtrapolate(fp, i_pixel, direction):
""" Find extrapolated linear fit for the peak center
Return height and width of center pixel as the extrapolated values"""
a= (fp[i_pixel+1]['peak_center']-fp[i_pixel-1]['peak_center'])/2 # slope for change of center with workspace index
center = a*2*direction + fp[i_pixel]['peak_center'] # estimated peak_center at i_pixel+2*direction
return [ center,fp[i_pixel]['peak_height'],fp[i_pixel]['peak_width'] ]
def isIntense(spectrum, center, neighborhood):
""" Confirm if there is strong peak in the neighborhood of center """
results=Max(InputWorkspace=spectrum.getName(),OutputWorkspace='isIntense.results',RangeLower=center-neighborhood,RangeUpper=center+neighborhood)
maxY = results.readY(0)[0]
DeleteWorkspace('isIntense.results')
if maxY > minIntensity:
return True
return False
def replacementLine( fp, ix, i_pixel, center, width, neighborhood):
""" Find the peak within the constraints at pixel ix"""
print 'ix=',ix, 'center=',center, 'width=',width, 'neighborhood=',neighborhood
sp = ExtractSingleSpectrum(InputWorkspace='events',WorkspaceIndex=ix,OutputWorkspace='events_single')
spRebinned = Rebin( sp, OutputWorkspace='events_histo', params=(max(0,center-10*width),dt,center+10*width), PreserveEvents=0)
if not isIntense(spRebinned, center, neighborhood): #check if we have enough intensity in the region of TOF to investigate
return None
fittedParams=findElasticLinePosition(spRebinned,tofRange=(center-neighborhood,center+neighborhood),guess_width=width)
if not fittedParams: # Check if we found a peak
return None
center=fittedParams['PeakCentre']
height=fittedParams['Height']
width=fittedParams['Sigma']
if not fp[ix]:
fp[ix]={}
fp[ix]['w_index']=ix
fp[ix]['det_id']=fp[i_pixel]['det_id']+(ix-i_pixel)
fp[ix]['nevents']=sp.getNumberEvents()
fp[ix]['bank']=fp[i_pixel]['bank']
fp[ix]['tube_id']=fp[i_pixel]['tube_id']
fp[ix]['peak_center']=center # Update/correct the peak info, which will serve for the next extrapolation
fp[ix]['peak_height']=height
fp[ix]['peak_width']=width
for suffix in ('_single','_histo', '_histo_peaks','_histo_NormalisedCovarianceMatrix','_histo_Parameters','_histo_Workspace'):
DeleteWorkspace('events'+suffix)
line='%04d %05d %4.0f %6.0f %6.0f %7d %2d %2d\n'%(fp[ix]['w_index'],fp[ix]['det_id'],center,height,width,fp[ix]['nevents'],fp[ix]['bank'],fp[ix]['tube_id'])
fp[ix]['line']=line
return line
if __name__=='__main__':
import argparse
parser = argparse.ArgumentParser(description='guess elastic line for each pixel')
parser.add_argument('--nexusFile',help='event nexus file')
parser.add_argument('--bankNumber',help='number of bank to load')
parser.add_argument('--firstPass',help='data file, the output of guessElasticLinePosition.py')
parser.add_argument('--centerPixels', help='space-sparated list of workpace indexes serving as tube centers. The do not have to coincide with the workspace indexes corresponding to the center of the tubes. If the script is not to do a second pass on a particular tube, then pass zero for the center pixel')
parser.add_argument('--outFile',help='output file')
args = parser.parse_args()
tol_center = 40.0 # maximum tolerated change in elastic-line-TOF between consecutive detectors
pFile = open(args.outFile,'w')
pFile.write('#1.workspace_index 2.detectorID 3.peakCenter 4.peakHeight 5.peakWidth 6.Nevents 7.bank 8.tube\n')
ibank=int(args.bankNumber)
ws=Load(Filename=args.nexusFile,OutputWorkspace='events',BankName=r'bank%d'%ibank)
#trace()
center_pixel=[ int(x) for x in args.centerPixels.split() ]
fp=readIn(args.firstPass) # read in the output data file from the first pass of guessElasticLine.
for i_tube in range(n_tube):
if not center_pixel[i_tube]: continue # do not process this tube
begin_pixel=i_tube*n_pixel_per_tube
i_pixel=center_pixel[i_tube] # workspace index from which we start
lines=fp[i_pixel-1]['line']+fp[i_pixel]['line']+fp[i_pixel+1]['line']
# process towards smaller workspace indexes from the center of the tube
while i_pixel>=begin_pixel+2:
[center,height,width]=linearExtrapolate(fp,i_pixel,-1)
if fp[i_pixel-2] and abs((center-fp[i_pixel-2]['peak_center'])/2) < tol_center:
# The peak exists and is located where it is supposed to be
lines=fp[i_pixel-2]['line']+lines # prepend to buffer
else:
# Non-existant peak, or peak located outside the region where it was expected to be. Find peak in the expected region
line=replacementLine(fp, i_pixel-2, i_pixel, center, width, tol_center)
if not line: # not enough intensity in the neighborhood of center, thus stop
i_pixel=begin_pixel
else:
lines=line+lines # prepend to buffer
i_pixel-=1 # "descend" along the tube
# process towards bigger detector ID's from the center of the tube
i_pixel=center_pixel[i_tube] # index of center detector for given tube
end_pixel=begin_pixel+n_pixel_per_tube-1
while i_pixel<=end_pixel-2:
#print iR,len(fp)
[center,height,width]=linearExtrapolate(fp,i_pixel,+1)
if fp[i_pixel+2] and abs((center-fp[i_pixel+2]['peak_center'])/2) < tol_center:
lines+=fp[i_pixel+2]['line'] # append to buffer
else:
line=replacementLine(fp, i_pixel+2, i_pixel, center, width, tol_center)
if not line:
i_pixel=end_pixel # not enough intensity in the neighborhood of center, thus stop
else:
lines+=line # append to buffer
i_pixel+=1 # "ascend" along the tube
pFile.write(lines) # store the processed tube
DeleteWorkspace('events')
pFile.close() | [
"borreguero@gmail.com"
] | borreguero@gmail.com |
dd1b73525526e6198b35c04f116baf278eed4316 | 781e2692049e87a4256320c76e82a19be257a05d | /all_data/exercism_data/python/leap/6b4c314f44d841bbb2b4d39674eb65c3.py | e9fd5ef53db94a80a06e2239ef9d865b8e7e86d3 | [] | no_license | itsolutionscorp/AutoStyle-Clustering | 54bde86fe6dbad35b568b38cfcb14c5ffaab51b0 | be0e2f635a7558f56c61bc0b36c6146b01d1e6e6 | refs/heads/master | 2020-12-11T07:27:19.291038 | 2016-03-16T03:18:00 | 2016-03-16T03:18:42 | 59,454,921 | 4 | 0 | null | 2016-05-23T05:40:56 | 2016-05-23T05:40:56 | null | UTF-8 | Python | false | false | 166 | py | def is_leap_year(year):
if type(year) != int: return "Not a year."
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
return True
else:
return False
| [
"rrc@berkeley.edu"
] | rrc@berkeley.edu |
7852381fd94bab144af4ccb32cb16d716772262b | ce0a3a73c7825f7327b8319fb2593b6b01659bb0 | /mysite/mysite/settings.py | cd4b00fbac4cb694ac71bec09ea83e0b482d97fd | [] | no_license | soccergame/deeplearning | 28b0a6ed85df12e362b3a451050fab5a2a994be7 | cbc65d3eba453992a279cfd96a9d3640d8fe6b9f | refs/heads/master | 2020-03-28T22:38:26.085464 | 2018-08-31T11:22:39 | 2018-08-31T11:22:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,212 | py | """
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.14.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '826f-sjl7t%0g9cff#7g90x7fjw3%5226!^8j$^(ec52a(k#na'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cmdb',
]
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',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR, 'static'),
) | [
"18811442380@163.com"
] | 18811442380@163.com |
83f8896cb49a3f55ad7b3291aaa0ac1a5e0330fb | 59a8c7b332c2cd182c9267cfcc5a4d0c3d4edb59 | /convert_to_onnx.py | d8669511953448ba8c4ce443d25a56a72616e252 | [
"MIT"
] | permissive | QLHua001/bsj_retinaface_train_2 | ffce230f50e9b0709c0a77200d4070f52624c8de | 4ac72ffee38779876aff4acd2577f5e8b20470fc | refs/heads/main | 2023-06-06T07:39:54.522042 | 2021-06-26T02:33:32 | 2021-06-26T02:33:32 | 380,394,876 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,377 | py | from __future__ import print_function
import os
import argparse
import torch
import torch.backends.cudnn as cudnn
import numpy as np
from data import cfg_mnet, cfg_re50
from layers.functions.prior_box import PriorBox
from utils.nms.py_cpu_nms import py_cpu_nms
import cv2
from models.retinaface import RetinaFace
from utils.box_utils import decode, decode_landm
from utils.timer import Timer
import onnx
parser = argparse.ArgumentParser(description='Test')
parser.add_argument('-m', '--trained_model', default='./20-point-weights/Retinaface_192_v0529a-1/mobilenet0.25_Final.pth',
type=str, help='Trained state_dict file path to open')
parser.add_argument('--network', default='mobile0.25', help='Backbone network mobile0.25 or resnet50')
parser.add_argument('--long_side', default=192, help='when origin_size is false, long_side is scaled size(320 or 640 for long side)')
parser.add_argument('--cpu', action="store_true", default=False, help='Use cpu inference')
args = parser.parse_args()
def check_keys(model, pretrained_state_dict):
ckpt_keys = set(pretrained_state_dict.keys())
model_keys = set(model.state_dict().keys())
used_pretrained_keys = model_keys & ckpt_keys
unused_pretrained_keys = ckpt_keys - model_keys
missing_keys = model_keys - ckpt_keys
print('Missing keys:{}'.format(len(missing_keys)))
print('Unused checkpoint keys:{}'.format(len(unused_pretrained_keys)))
print('Used keys:{}'.format(len(used_pretrained_keys)))
assert len(used_pretrained_keys) > 0, 'load NONE from pretrained checkpoint'
return True
def remove_prefix(state_dict, prefix):
''' Old style model is stored with all names of parameters sharing common prefix 'module.' '''
print('remove prefix \'{}\''.format(prefix))
f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x
return {f(key): value for key, value in state_dict.items()}
def load_model(model, pretrained_path, load_to_cpu):
print('Loading pretrained model from {}'.format(pretrained_path))
if load_to_cpu:
pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage)
else:
#Returns the index of a currently selected device.
device = torch.cuda.current_device()
print("device:")
print(device)
pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage.cuda(device))
if "state_dict" in pretrained_dict.keys():
pretrained_dict = remove_prefix(pretrained_dict['state_dict'], 'module.')
else:
pretrained_dict = remove_prefix(pretrained_dict, 'module.')
check_keys(model, pretrained_dict)
model.load_state_dict(pretrained_dict, strict=False)
return model
if __name__ == '__main__':
#set_grad_enabled will enable or disable <gradient calculation> based on its argument mode.
#It can be used as a context-manager or as a function.
torch.set_grad_enabled(False)
cfg = None
if args.network == "mobile0.25":
cfg = cfg_mnet
elif args.network == "resnet50":
cfg = cfg_re50
# net and model
net = RetinaFace(cfg=cfg, phase = 'test')
net = load_model(net, args.trained_model, args.cpu)
net.eval()
print('Finished loading model!')
print(net)
#A torch.device is an object representing the device on which a torch.Tensor is or will be allocated.
device = torch.device("cuda:0")
net = net.to(device)
# ------------------------ export -----------------------------
output_onnx = 'Retinaface_192_v0529a-1.onnx'
print("==> Exporting model to ONNX format at '{}'".format(output_onnx))
input_names = ["input0"]
output_names = ["output0","output1", "output2"]
print("args.long_side: ", args.long_side)
inputs = torch.randn(1, 3, args.long_side, args.long_side).to(device)
torch_out = torch.onnx._export(net, inputs, output_onnx, export_params=True, verbose=False,
input_names=input_names, output_names=output_names)
model = onnx.load("./Retinaface_192_v0529a-1.onnx")
dim_proto0 = model.graph.input[0].type.tensor_type.shape.dim[2]
dim_proto0.dim_param = 'input.0_2'
dim_proto1 = model.graph.input[0].type.tensor_type.shape.dim[3]
dim_proto1.dim_param = 'input.0_3'
onnx.save(model, 'Retinaface_192_v0529a-1_dynaInput.onnx')
| [
"gogs@fake.local"
] | gogs@fake.local |
8cfe933c73e083c3c4df4862e73b9e2e558780e8 | 7bd5ca970fbbe4a3ed0c7dadcf43ba8681a737f3 | /2014/codefestival/thanksb/d.py | 6f6c56dc67aa702914e96ae0c45553f0234736fc | [] | no_license | roiti46/Contest | c0c35478cd80f675965d10b1a371e44084f9b6ee | c4b850d76796c5388d2e0d2234f90dc8acfaadfa | refs/heads/master | 2021-01-17T13:23:30.551754 | 2017-12-10T13:06:42 | 2017-12-10T13:06:42 | 27,001,893 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 190 | py | N,T = map(int,raw_input().split())
A = [int(raw_input()) for _ in range(N)]
ans = 0
for t in range(1,T+1):
tmp = sum(1 for i in range(N) if t%A[i] == 0)
ans = max(ans,tmp)
print ans
| [
"roiti46@gmail.com"
] | roiti46@gmail.com |
33bd5e391cbd0c2a89346bdba94ba49cd650b439 | 90b5584198bfd6c3138122efbd49f361375cd0ac | /lib/python3.6/site-packages/twilio/rest/api/v2010/account/message/media.py | 01d8a0a68af4f378b343c21e27ce41cfcb9a9820 | [] | no_license | sarahchou/HoliBot | 50cd4c89f1f6e06ebfb2780e29dbe78b5b91f650 | ee1e631cda8afc43e963332d94a7d0295380aba9 | refs/heads/master | 2021-04-09T13:32:57.888058 | 2018-03-18T18:53:10 | 2018-03-18T18:53:10 | 125,672,513 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,184 | py | # coding=utf-8
"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
class MediaList(ListResource):
def __init__(self, version, account_sid, message_sid):
"""
Initialize the MediaList
:param Version version: Version that contains the resource
:param account_sid: The unique sid that identifies this account
:param message_sid: A string that uniquely identifies this message
:returns: twilio_code.rest.api.v2010.account.message.media.MediaList
:rtype: twilio.rest.api.v2010.account.message.media.MediaList
"""
super(MediaList, self).__init__(version)
# Path Solution
self._solution = {
'account_sid': account_sid,
'message_sid': message_sid,
}
self._uri = '/Accounts/{account_sid}/Messages/{message_sid}/Media.json'.format(**self._solution)
def stream(self, date_created_before=values.unset, date_created=values.unset,
date_created_after=values.unset, limit=None, page_size=None):
"""
Streams MediaInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param datetime date_created_before: Filter by date created
:param datetime date_created: Filter by date created
:param datetime date_created_after: Filter by date created
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.api.v2010.account.message.media.MediaInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(
date_created_before=date_created_before,
date_created=date_created,
date_created_after=date_created_after,
page_size=limits['page_size'],
)
return self._version.stream(page, limits['limit'], limits['page_limit'])
def list(self, date_created_before=values.unset, date_created=values.unset,
date_created_after=values.unset, limit=None, page_size=None):
"""
Lists MediaInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param datetime date_created_before: Filter by date created
:param datetime date_created: Filter by date created
:param datetime date_created_after: Filter by date created
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.api.v2010.account.message.media.MediaInstance]
"""
return list(self.stream(
date_created_before=date_created_before,
date_created=date_created,
date_created_after=date_created_after,
limit=limit,
page_size=page_size,
))
def page(self, date_created_before=values.unset, date_created=values.unset,
date_created_after=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
"""
Retrieve a single page of MediaInstance records from the API.
Request is executed immediately
:param datetime date_created_before: Filter by date created
:param datetime date_created: Filter by date created
:param datetime date_created_after: Filter by date created
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of MediaInstance
:rtype: twilio.rest.api.v2010.account.message.media.MediaPage
"""
params = values.of({
'DateCreated<': serialize.iso8601_datetime(date_created_before),
'DateCreated': serialize.iso8601_datetime(date_created),
'DateCreated>': serialize.iso8601_datetime(date_created_after),
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(
'GET',
self._uri,
params=params,
)
return MediaPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a MediaContext
:param sid: Fetch by unique media Sid
:returns: twilio_code.rest.api.v2010.account.message.media.MediaContext
:rtype: twilio.rest.api.v2010.account.message.media.MediaContext
"""
return MediaContext(
self._version,
account_sid=self._solution['account_sid'],
message_sid=self._solution['message_sid'],
sid=sid,
)
def __call__(self, sid):
"""
Constructs a MediaContext
:param sid: Fetch by unique media Sid
:returns: twilio_code.rest.api.v2010.account.message.media.MediaContext
:rtype: twilio.rest.api.v2010.account.message.media.MediaContext
"""
return MediaContext(
self._version,
account_sid=self._solution['account_sid'],
message_sid=self._solution['message_sid'],
sid=sid,
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010.MediaList>'
class MediaPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the MediaPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param account_sid: The unique sid that identifies this account
:param message_sid: A string that uniquely identifies this message
:returns: twilio_code.rest.api.v2010.account.message.media.MediaPage
:rtype: twilio.rest.api.v2010.account.message.media.MediaPage
"""
super(MediaPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of MediaInstance
:param dict payload: Payload response from the API
:returns: twilio_code.rest.api.v2010.account.message.media.MediaInstance
:rtype: twilio.rest.api.v2010.account.message.media.MediaInstance
"""
return MediaInstance(
self._version,
payload,
account_sid=self._solution['account_sid'],
message_sid=self._solution['message_sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Api.V2010.MediaPage>'
class MediaContext(InstanceContext):
def __init__(self, version, account_sid, message_sid, sid):
"""
Initialize the MediaContext
:param Version version: Version that contains the resource
:param account_sid: The account_sid
:param message_sid: The message_sid
:param sid: Fetch by unique media Sid
:returns: twilio_code.rest.api.v2010.account.message.media.MediaContext
:rtype: twilio.rest.api.v2010.account.message.media.MediaContext
"""
super(MediaContext, self).__init__(version)
# Path Solution
self._solution = {
'account_sid': account_sid,
'message_sid': message_sid,
'sid': sid,
}
self._uri = '/Accounts/{account_sid}/Messages/{message_sid}/Media/{sid}.json'.format(**self._solution)
def delete(self):
"""
Deletes the MediaInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._version.delete('delete', self._uri)
def fetch(self):
"""
Fetch a MediaInstance
:returns: Fetched MediaInstance
:rtype: twilio.rest.api.v2010.account.message.media.MediaInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
params=params,
)
return MediaInstance(
self._version,
payload,
account_sid=self._solution['account_sid'],
message_sid=self._solution['message_sid'],
sid=self._solution['sid'],
)
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Api.V2010.MediaContext {}>'.format(context)
class MediaInstance(InstanceResource):
def __init__(self, version, payload, account_sid, message_sid, sid=None):
"""
Initialize the MediaInstance
:returns: twilio_code.rest.api.v2010.account.message.media.MediaInstance
:rtype: twilio.rest.api.v2010.account.message.media.MediaInstance
"""
super(MediaInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'account_sid': payload['account_sid'],
'content_type': payload['content_type'],
'date_created': deserialize.rfc2822_datetime(payload['date_created']),
'date_updated': deserialize.rfc2822_datetime(payload['date_updated']),
'parent_sid': payload['parent_sid'],
'sid': payload['sid'],
'uri': payload['uri'],
}
# Context
self._context = None
self._solution = {
'account_sid': account_sid,
'message_sid': message_sid,
'sid': sid or self._properties['sid'],
}
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: MediaContext for this MediaInstance
:rtype: twilio.rest.api.v2010.account.message.media.MediaContext
"""
if self._context is None:
self._context = MediaContext(
self._version,
account_sid=self._solution['account_sid'],
message_sid=self._solution['message_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def account_sid(self):
"""
:returns: The unique sid that identifies this account
:rtype: unicode
"""
return self._properties['account_sid']
@property
def content_type(self):
"""
:returns: The default mime-type of the media
:rtype: unicode
"""
return self._properties['content_type']
@property
def date_created(self):
"""
:returns: The date this resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The date this resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def parent_sid(self):
"""
:returns: The unique id of the resource that created the media.
:rtype: unicode
"""
return self._properties['parent_sid']
@property
def sid(self):
"""
:returns: A string that uniquely identifies this media
:rtype: unicode
"""
return self._properties['sid']
@property
def uri(self):
"""
:returns: The URI for this resource
:rtype: unicode
"""
return self._properties['uri']
def delete(self):
"""
Deletes the MediaInstance
:returns: True if delete succeeds, False otherwise
:rtype: bool
"""
return self._proxy.delete()
def fetch(self):
"""
Fetch a MediaInstance
:returns: Fetched MediaInstance
:rtype: twilio.rest.api.v2010.account.message.media.MediaInstance
"""
return self._proxy.fetch()
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Api.V2010.MediaInstance {}>'.format(context)
| [
"chou.s@husky.neu.edu"
] | chou.s@husky.neu.edu |
f38803a4c4eb6386cc7d3348d9d2bc33e9cda9dd | 4de03eecadc4c69caf792f4773571c2f6dbe9d68 | /seahub/api2/endpoints/admin/file_audit.py | d8968ed22469ef16846f9475a1ba6b1103a19aff | [
"Apache-2.0"
] | permissive | Tr-1234/seahub | c1663dfd12f7584f24c160bcf2a83afdbe63a9e2 | ed255e0566de054b5570218cb39cc320e99ffa44 | refs/heads/master | 2022-12-23T16:20:13.138757 | 2020-10-01T04:13:42 | 2020-10-01T04:13:42 | 300,138,290 | 0 | 0 | Apache-2.0 | 2020-10-01T04:11:41 | 2020-10-01T04:11:40 | null | UTF-8 | Python | false | false | 2,138 | py | from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from seaserv import seafile_api
from .utils import check_time_period_valid, \
get_log_events_by_type_and_time
from seahub.api2.authentication import TokenAuthentication
from seahub.api2.throttling import UserRateThrottle
from seahub.api2.utils import api_error
from seahub.base.templatetags.seahub_tags import email2nickname
from seahub.utils.timeutils import datetime_to_isoformat_timestr
from seahub.utils import is_pro_version
class FileAudit(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication )
permission_classes = (IsAdminUser,)
throttle_classes = (UserRateThrottle,)
def get(self, request):
if not is_pro_version():
error_msg = 'Feature disabled.'
return api_error(status.HTTP_403_FORBIDDEN, error_msg)
# check the date format, should be like '2015-10-10'
start = request.GET.get('start', None)
end = request.GET.get('end', None)
if not check_time_period_valid(start, end):
error_msg = 'start or end date invalid.'
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
result = []
events = get_log_events_by_type_and_time('file_audit', start, end)
if events:
for ev in events:
tmp_repo = seafile_api.get_repo(ev.repo_id)
tmp_repo_name = tmp_repo.name if tmp_repo else ''
result.append({
'repo_id': ev.repo_id,
'repo_name': tmp_repo_name,
'time': datetime_to_isoformat_timestr(ev.timestamp),
'etype': ev.etype,
'ip': ev.ip,
'file_path': ev.file_path,
'etype': ev.etype,
'user_name': email2nickname(ev.user),
'user_email': ev.user
})
return Response(result)
| [
"colinsippl@gmx.de"
] | colinsippl@gmx.de |
341ea1610a3b5ed9e737b2c4b2bbc9bd7ceb736f | 549317bc0a7230ec163914c75f75dd008900c57b | /pyroomacoustics/tests/tests_libroom/test_ccw3p.py | 1c037631a6a39a0deba7194dbded459392295e0b | [
"MIT"
] | permissive | oucxlw/pyroomacoustics | 0bb633427cd7ce3e93392cdc9d0bc3afc5f2dbf3 | 0adc91579c9c6daf1b73d2c4863a9fc66b308dbb | refs/heads/master | 2023-06-17T17:43:49.743201 | 2021-07-21T05:36:46 | 2021-07-21T05:36:46 | 288,884,904 | 1 | 0 | MIT | 2021-07-21T05:36:47 | 2020-08-20T02:22:54 | Python | UTF-8 | Python | false | false | 2,575 | py | # Test of the CCW3P routine
# Copyright (C) 2019 Robin Scheibler, Cyril Cadoux
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# You should have received a copy of the MIT License along with this program. If
# not, see <https://opensource.org/licenses/MIT>.
import numpy as np
import pyroomacoustics as pra
cases = {
'anti-clockwise' : {
'points' : np.array([
[1,-1], [2,-1], [1,0]
]),
'expected' : 1, # anti-clockwise
'label' : 'Test: CCW3P anti-clockwise',
},
'clockwise' : {
'points' : np.array([
[1,-1], [1,0], [2,-1]
]),
'expected' : -1, # clockwise
'label' : 'Test: CCW3P clockwise',
},
'co-linear' : {
'points' : np.array([
[0,0], [0.5,0.5], [1,1]
]),
'expected' : 0, # co-linear
'label' : 'Test: CCW3P co-linear',
},
}
def ccw3p(case):
p1, p2, p3 = case['points']
r = pra.libroom.ccw3p(p1, p2, p3)
assert r == case['expected'], (case['label']
+ ' returned: {}, expected {}'.format(r, case['expected']))
def test_ccw3p_anticlockwise():
ccw3p(cases['anti-clockwise'])
def test_ccw3p_clockwise():
ccw3p(cases['clockwise'])
def test_ccw3p_colinear():
ccw3p(cases['co-linear'])
if __name__ == '__main__':
for lbl, case in cases.items():
try:
ccw3p(case)
except:
print('{} failed'.format(lbl))
| [
"fakufaku@gmail.com"
] | fakufaku@gmail.com |
804e07c2b80c9170bd645ccdfaa3c4561b7764de | c40157692e86b30e00719e587a8109388e6463e2 | /slowfast/datasets/kinetics.py | a9602b707bd86b947a8e6507a0c505877f96388a | [
"Apache-2.0"
] | permissive | fmassa/SlowFast | 2b610cd31314f1a858069349b946c207a93ad41e | ec4b2f5932df67901e6a4a13d020f9ecf66c8f27 | refs/heads/master | 2021-05-26T08:29:01.608826 | 2020-04-01T22:11:12 | 2020-04-01T22:13:04 | 254,058,512 | 2 | 0 | null | 2020-04-08T10:38:29 | 2020-04-08T10:38:29 | null | UTF-8 | Python | false | false | 11,195 | py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
import random
import torch
import torch.utils.data
from fvcore.common.file_io import PathManager
import slowfast.utils.logging as logging
from . import decoder as decoder
from . import transform as transform
from . import utils as utils
from . import video_container as container
from .build import DATASET_REGISTRY
logger = logging.get_logger(__name__)
@DATASET_REGISTRY.register()
class Kinetics(torch.utils.data.Dataset):
"""
Kinetics video loader. Construct the Kinetics video loader, then sample
clips from the videos. For training and validation, a single clip is
randomly sampled from every video with random cropping, scaling, and
flipping. For testing, multiple clips are uniformaly sampled from every
video with uniform cropping. For uniform cropping, we take the left, center,
and right crop if the width is larger than height, or take top, center, and
bottom crop if the height is larger than the width.
"""
def __init__(self, cfg, mode, num_retries=10):
"""
Construct the Kinetics video loader with a given csv file. The format of
the csv file is:
```
path_to_video_1 label_1
path_to_video_2 label_2
...
path_to_video_N label_N
```
Args:
cfg (CfgNode): configs.
mode (string): Options includes `train`, `val`, or `test` mode.
For the train and val mode, the data loader will take data
from the train or val set, and sample one clip per video.
For the test mode, the data loader will take data from test set,
and sample multiple clips per video.
num_retries (int): number of retries.
"""
# Only support train, val, and test mode.
assert mode in [
"train",
"val",
"test",
], "Split '{}' not supported for Kinetics".format(mode)
self.mode = mode
self.cfg = cfg
self._video_meta = {}
self._num_retries = num_retries
# For training or validation mode, one single clip is sampled from every
# video. For testing, NUM_ENSEMBLE_VIEWS clips are sampled from every
# video. For every clip, NUM_SPATIAL_CROPS is cropped spatially from
# the frames.
if self.mode in ["train", "val"]:
self._num_clips = 1
elif self.mode in ["test"]:
self._num_clips = (
cfg.TEST.NUM_ENSEMBLE_VIEWS * cfg.TEST.NUM_SPATIAL_CROPS
)
logger.info("Constructing Kinetics {}...".format(mode))
self._construct_loader()
def _construct_loader(self):
"""
Construct the video loader.
"""
path_to_file = os.path.join(
self.cfg.DATA.PATH_TO_DATA_DIR, "{}.csv".format(self.mode)
)
assert PathManager.exists(path_to_file), "{} dir not found".format(
path_to_file
)
self._path_to_videos = []
self._labels = []
self._spatial_temporal_idx = []
with PathManager.open(path_to_file, "r") as f:
for clip_idx, path_label in enumerate(f.read().splitlines()):
assert len(path_label.split()) == 2
path, label = path_label.split()
for idx in range(self._num_clips):
self._path_to_videos.append(
os.path.join(self.cfg.DATA.PATH_PREFIX, path)
)
self._labels.append(int(label))
self._spatial_temporal_idx.append(idx)
self._video_meta[clip_idx * self._num_clips + idx] = {}
assert (
len(self._path_to_videos) > 0
), "Failed to load Kinetics split {} from {}".format(
self._split_idx, path_to_file
)
logger.info(
"Constructing kinetics dataloader (size: {}) from {}".format(
len(self._path_to_videos), path_to_file
)
)
def __getitem__(self, index):
"""
Given the video index, return the list of frames, label, and video
index if the video can be fetched and decoded successfully, otherwise
repeatly find a random video that can be decoded as a replacement.
Args:
index (int): the video index provided by the pytorch sampler.
Returns:
frames (tensor): the frames of sampled from the video. The dimension
is `channel` x `num frames` x `height` x `width`.
label (int): the label of the current video.
index (int): if the video provided by pytorch sampler can be
decoded, then return the index of the video. If not, return the
index of the video replacement that can be decoded.
"""
if self.mode in ["train", "val"]:
# -1 indicates random sampling.
temporal_sample_index = -1
spatial_sample_index = -1
min_scale = self.cfg.DATA.TRAIN_JITTER_SCALES[0]
max_scale = self.cfg.DATA.TRAIN_JITTER_SCALES[1]
crop_size = self.cfg.DATA.TRAIN_CROP_SIZE
elif self.mode in ["test"]:
temporal_sample_index = (
self._spatial_temporal_idx[index]
// self.cfg.TEST.NUM_SPATIAL_CROPS
)
# spatial_sample_index is in [0, 1, 2]. Corresponding to left,
# center, or right if width is larger than height, and top, middle,
# or bottom if height is larger than width.
spatial_sample_index = (
self._spatial_temporal_idx[index]
% self.cfg.TEST.NUM_SPATIAL_CROPS
)
min_scale, max_scale, crop_size = [self.cfg.DATA.TEST_CROP_SIZE] * 3
# The testing is deterministic and no jitter should be performed.
# min_scale, max_scale, and crop_size are expect to be the same.
assert len({min_scale, max_scale, crop_size}) == 1
else:
raise NotImplementedError(
"Does not support {} mode".format(self.mode)
)
# Try to decode and sample a clip from a video. If the video can not be
# decoded, repeatly find a random video replacement that can be decoded.
for _ in range(self._num_retries):
video_container = None
try:
video_container = container.get_video_container(
self._path_to_videos[index],
self.cfg.DATA_LOADER.ENABLE_MULTI_THREAD_DECODE,
self.cfg.DATA.DECODING_BACKEND,
)
except Exception as e:
logger.info(
"Failed to load video from {} with error {}".format(
self._path_to_videos[index], e
)
)
# Select a random video if the current video was not able to access.
if video_container is None:
index = random.randint(0, len(self._path_to_videos) - 1)
continue
# Decode video. Meta info is used to perform selective decoding.
frames = decoder.decode(
video_container,
self.cfg.DATA.SAMPLING_RATE,
self.cfg.DATA.NUM_FRAMES,
temporal_sample_index,
self.cfg.TEST.NUM_ENSEMBLE_VIEWS,
video_meta=self._video_meta[index],
target_fps=self.cfg.DATA.TARGET_FPS,
backend=self.cfg.DATA.DECODING_BACKEND,
max_spatial_scale=max_scale,
)
# If decoding failed (wrong format, video is too short, and etc),
# select another video.
if frames is None:
index = random.randint(0, len(self._path_to_videos) - 1)
continue
# Perform color normalization.
frames = frames.float()
frames = frames / 255.0
frames = frames - torch.tensor(self.cfg.DATA.MEAN)
frames = frames / torch.tensor(self.cfg.DATA.STD)
# T H W C -> C T H W.
frames = frames.permute(3, 0, 1, 2)
# Perform data augmentation.
frames = self.spatial_sampling(
frames,
spatial_idx=spatial_sample_index,
min_scale=min_scale,
max_scale=max_scale,
crop_size=crop_size,
)
label = self._labels[index]
frames = utils.pack_pathway_output(self.cfg, frames)
return frames, label, index, {}
else:
raise RuntimeError(
"Failed to fetch video after {} retries.".format(
self._num_retries
)
)
def __len__(self):
"""
Returns:
(int): the number of videos in the dataset.
"""
return len(self._path_to_videos)
def spatial_sampling(
self,
frames,
spatial_idx=-1,
min_scale=256,
max_scale=320,
crop_size=224,
):
"""
Perform spatial sampling on the given video frames. If spatial_idx is
-1, perform random scale, random crop, and random flip on the given
frames. If spatial_idx is 0, 1, or 2, perform spatial uniform sampling
with the given spatial_idx.
Args:
frames (tensor): frames of images sampled from the video. The
dimension is `num frames` x `height` x `width` x `channel`.
spatial_idx (int): if -1, perform random spatial sampling. If 0, 1,
or 2, perform left, center, right crop if width is larger than
height, and perform top, center, buttom crop if height is larger
than width.
min_scale (int): the minimal size of scaling.
max_scale (int): the maximal size of scaling.
crop_size (int): the size of height and width used to crop the
frames.
Returns:
frames (tensor): spatially sampled frames.
"""
assert spatial_idx in [-1, 0, 1, 2]
if spatial_idx == -1:
frames, _ = transform.random_short_side_scale_jitter(
images=frames,
min_size=min_scale,
max_size=max_scale,
inverse_uniform_sampling=self.cfg.DATA.INV_UNIFORM_SAMPLE,
)
frames, _ = transform.random_crop(frames, crop_size)
frames, _ = transform.horizontal_flip(0.5, frames)
else:
# The testing is deterministic and no jitter should be performed.
# min_scale, max_scale, and crop_size are expect to be the same.
assert len({min_scale, max_scale, crop_size}) == 1
frames, _ = transform.random_short_side_scale_jitter(
frames, min_scale, max_scale
)
frames, _ = transform.uniform_crop(frames, crop_size, spatial_idx)
return frames
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
f835cfa380b740abef9cdc32dc9ca46d5a6b1db0 | cc6ea4b0422ba4c0d0ab2815333330b22e6a2b6f | /py_headless_daw/processing/event/envelope_param_value_emitter.py | 03b96a541bf18c17983d069972fc8bf8f0ac8f40 | [
"MIT"
] | permissive | Catsvilles/py_headless_daw | 07494e39a07510d852af1eda1d611eb34e4d96a8 | 596d2da39e14cda13544601b71714a8ebe6b8874 | refs/heads/master | 2022-11-05T12:28:18.335337 | 2020-06-18T08:14:00 | 2020-06-18T08:14:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,127 | py | from typing import List
import numpy as np
from em.platform.rendering.dto.time_interval import TimeInterval
from em.platform.rendering.primitives.envelope import Envelope
from em.platform.rendering.schema.events.event import Event
from em.platform.rendering.schema.events.parameter_value_event import ParameterValueEvent
from em.platform.rendering.schema.processing_strategy import ProcessingStrategy
class EnvelopeParamValueEmitter(ProcessingStrategy):
def __init__(self, envelope: Envelope, parameter: str):
self.envelope: Envelope = envelope
self.parameter: str = parameter
def render(self, interval: TimeInterval, stream_inputs: List[np.ndarray], stream_outputs: List[np.ndarray],
event_inputs: List[List[Event]], event_outputs: List[List[Event]]):
# a simplified approach:
# only one event is generated, in the very beginning of buffer
# must be good enough for the beginning
event = ParameterValueEvent(0, self.parameter, self.envelope.get_value_at(interval.start_in_bars))
for output in event_outputs:
output.append(event)
| [
"grechin.sergey@gmail.com"
] | grechin.sergey@gmail.com |
bb90fc18acec944c5771c1bfc31de1815570db9b | 9b2eb0d6b673ac4945f9698c31840b847f790a58 | /pkg/apteco_api/models/user_audience_composition_detail.py | 44cd3074eaa44b89f96484d635eecf8fd719e56d | [
"Apache-2.0"
] | permissive | Apteco/apteco-api | 6d21c9f16e58357da9ce64bac52f1d2403b36b7c | e8cf50a9cb01b044897025c74d88c37ad1612d31 | refs/heads/master | 2023-07-10T23:25:59.000038 | 2023-07-07T14:52:29 | 2023-07-07T14:52:29 | 225,371,142 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 18,331 | py | # coding: utf-8
"""
Apteco API
An API to allow access to Apteco Marketing Suite resources # noqa: E501
The version of the OpenAPI document: v2
Contact: support@apteco.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from apteco_api.configuration import Configuration
class UserAudienceCompositionDetail(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'viewing_username': 'str',
'shared_to_me': 'bool',
'shared_by_me': 'bool',
'check_composition_definition': 'CheckCompositionDefinition',
'export_composition_definition': 'ExportCompositionDefinition',
'compositions_lookup': 'SystemLookup',
'id': 'int',
'description': 'str',
'type': 'str',
'system_name': 'str',
'owner': 'UserDisplayDetails',
'number_of_users_shared_with': 'int',
'shared_to_all': 'bool',
'share_id': 'int'
}
attribute_map = {
'viewing_username': 'viewingUsername',
'shared_to_me': 'sharedToMe',
'shared_by_me': 'sharedByMe',
'check_composition_definition': 'checkCompositionDefinition',
'export_composition_definition': 'exportCompositionDefinition',
'compositions_lookup': 'compositionsLookup',
'id': 'id',
'description': 'description',
'type': 'type',
'system_name': 'systemName',
'owner': 'owner',
'number_of_users_shared_with': 'numberOfUsersSharedWith',
'shared_to_all': 'sharedToAll',
'share_id': 'shareId'
}
def __init__(self, viewing_username=None, shared_to_me=None, shared_by_me=None, check_composition_definition=None, export_composition_definition=None, compositions_lookup=None, id=None, description=None, type=None, system_name=None, owner=None, number_of_users_shared_with=None, shared_to_all=None, share_id=None, local_vars_configuration=None): # noqa: E501
"""UserAudienceCompositionDetail - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._viewing_username = None
self._shared_to_me = None
self._shared_by_me = None
self._check_composition_definition = None
self._export_composition_definition = None
self._compositions_lookup = None
self._id = None
self._description = None
self._type = None
self._system_name = None
self._owner = None
self._number_of_users_shared_with = None
self._shared_to_all = None
self._share_id = None
self.discriminator = None
self.viewing_username = viewing_username
self.shared_to_me = shared_to_me
self.shared_by_me = shared_by_me
if check_composition_definition is not None:
self.check_composition_definition = check_composition_definition
if export_composition_definition is not None:
self.export_composition_definition = export_composition_definition
if compositions_lookup is not None:
self.compositions_lookup = compositions_lookup
self.id = id
self.description = description
self.type = type
self.system_name = system_name
self.owner = owner
self.number_of_users_shared_with = number_of_users_shared_with
self.shared_to_all = shared_to_all
if share_id is not None:
self.share_id = share_id
@property
def viewing_username(self):
"""Gets the viewing_username of this UserAudienceCompositionDetail. # noqa: E501
The username of the user that has access to this composition # noqa: E501
:return: The viewing_username of this UserAudienceCompositionDetail. # noqa: E501
:rtype: str
"""
return self._viewing_username
@viewing_username.setter
def viewing_username(self, viewing_username):
"""Sets the viewing_username of this UserAudienceCompositionDetail.
The username of the user that has access to this composition # noqa: E501
:param viewing_username: The viewing_username of this UserAudienceCompositionDetail. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and viewing_username is None: # noqa: E501
raise ValueError("Invalid value for `viewing_username`, must not be `None`") # noqa: E501
self._viewing_username = viewing_username
@property
def shared_to_me(self):
"""Gets the shared_to_me of this UserAudienceCompositionDetail. # noqa: E501
Whether this composition has been shared to the given user by someone else # noqa: E501
:return: The shared_to_me of this UserAudienceCompositionDetail. # noqa: E501
:rtype: bool
"""
return self._shared_to_me
@shared_to_me.setter
def shared_to_me(self, shared_to_me):
"""Sets the shared_to_me of this UserAudienceCompositionDetail.
Whether this composition has been shared to the given user by someone else # noqa: E501
:param shared_to_me: The shared_to_me of this UserAudienceCompositionDetail. # noqa: E501
:type: bool
"""
if self.local_vars_configuration.client_side_validation and shared_to_me is None: # noqa: E501
raise ValueError("Invalid value for `shared_to_me`, must not be `None`") # noqa: E501
self._shared_to_me = shared_to_me
@property
def shared_by_me(self):
"""Gets the shared_by_me of this UserAudienceCompositionDetail. # noqa: E501
Whether this composition has been shared to others by the given user # noqa: E501
:return: The shared_by_me of this UserAudienceCompositionDetail. # noqa: E501
:rtype: bool
"""
return self._shared_by_me
@shared_by_me.setter
def shared_by_me(self, shared_by_me):
"""Sets the shared_by_me of this UserAudienceCompositionDetail.
Whether this composition has been shared to others by the given user # noqa: E501
:param shared_by_me: The shared_by_me of this UserAudienceCompositionDetail. # noqa: E501
:type: bool
"""
if self.local_vars_configuration.client_side_validation and shared_by_me is None: # noqa: E501
raise ValueError("Invalid value for `shared_by_me`, must not be `None`") # noqa: E501
self._shared_by_me = shared_by_me
@property
def check_composition_definition(self):
"""Gets the check_composition_definition of this UserAudienceCompositionDetail. # noqa: E501
:return: The check_composition_definition of this UserAudienceCompositionDetail. # noqa: E501
:rtype: CheckCompositionDefinition
"""
return self._check_composition_definition
@check_composition_definition.setter
def check_composition_definition(self, check_composition_definition):
"""Sets the check_composition_definition of this UserAudienceCompositionDetail.
:param check_composition_definition: The check_composition_definition of this UserAudienceCompositionDetail. # noqa: E501
:type: CheckCompositionDefinition
"""
self._check_composition_definition = check_composition_definition
@property
def export_composition_definition(self):
"""Gets the export_composition_definition of this UserAudienceCompositionDetail. # noqa: E501
:return: The export_composition_definition of this UserAudienceCompositionDetail. # noqa: E501
:rtype: ExportCompositionDefinition
"""
return self._export_composition_definition
@export_composition_definition.setter
def export_composition_definition(self, export_composition_definition):
"""Sets the export_composition_definition of this UserAudienceCompositionDetail.
:param export_composition_definition: The export_composition_definition of this UserAudienceCompositionDetail. # noqa: E501
:type: ExportCompositionDefinition
"""
self._export_composition_definition = export_composition_definition
@property
def compositions_lookup(self):
"""Gets the compositions_lookup of this UserAudienceCompositionDetail. # noqa: E501
:return: The compositions_lookup of this UserAudienceCompositionDetail. # noqa: E501
:rtype: SystemLookup
"""
return self._compositions_lookup
@compositions_lookup.setter
def compositions_lookup(self, compositions_lookup):
"""Sets the compositions_lookup of this UserAudienceCompositionDetail.
:param compositions_lookup: The compositions_lookup of this UserAudienceCompositionDetail. # noqa: E501
:type: SystemLookup
"""
self._compositions_lookup = compositions_lookup
@property
def id(self):
"""Gets the id of this UserAudienceCompositionDetail. # noqa: E501
The id of this composition # noqa: E501
:return: The id of this UserAudienceCompositionDetail. # noqa: E501
:rtype: int
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this UserAudienceCompositionDetail.
The id of this composition # noqa: E501
:param id: The id of this UserAudienceCompositionDetail. # noqa: E501
:type: int
"""
if self.local_vars_configuration.client_side_validation and id is None: # noqa: E501
raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501
self._id = id
@property
def description(self):
"""Gets the description of this UserAudienceCompositionDetail. # noqa: E501
The description of this composition # noqa: E501
:return: The description of this UserAudienceCompositionDetail. # noqa: E501
:rtype: str
"""
return self._description
@description.setter
def description(self, description):
"""Sets the description of this UserAudienceCompositionDetail.
The description of this composition # noqa: E501
:param description: The description of this UserAudienceCompositionDetail. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and description is None: # noqa: E501
raise ValueError("Invalid value for `description`, must not be `None`") # noqa: E501
self._description = description
@property
def type(self):
"""Gets the type of this UserAudienceCompositionDetail. # noqa: E501
The type of this composition # noqa: E501
:return: The type of this UserAudienceCompositionDetail. # noqa: E501
:rtype: str
"""
return self._type
@type.setter
def type(self, type):
"""Sets the type of this UserAudienceCompositionDetail.
The type of this composition # noqa: E501
:param type: The type of this UserAudienceCompositionDetail. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and type is None: # noqa: E501
raise ValueError("Invalid value for `type`, must not be `None`") # noqa: E501
allowed_values = ["Check", "Export"] # noqa: E501
if self.local_vars_configuration.client_side_validation and type not in allowed_values: # noqa: E501
raise ValueError(
"Invalid value for `type` ({0}), must be one of {1}" # noqa: E501
.format(type, allowed_values)
)
self._type = type
@property
def system_name(self):
"""Gets the system_name of this UserAudienceCompositionDetail. # noqa: E501
The name of the FastStats system that this composition is for # noqa: E501
:return: The system_name of this UserAudienceCompositionDetail. # noqa: E501
:rtype: str
"""
return self._system_name
@system_name.setter
def system_name(self, system_name):
"""Sets the system_name of this UserAudienceCompositionDetail.
The name of the FastStats system that this composition is for # noqa: E501
:param system_name: The system_name of this UserAudienceCompositionDetail. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and system_name is None: # noqa: E501
raise ValueError("Invalid value for `system_name`, must not be `None`") # noqa: E501
self._system_name = system_name
@property
def owner(self):
"""Gets the owner of this UserAudienceCompositionDetail. # noqa: E501
:return: The owner of this UserAudienceCompositionDetail. # noqa: E501
:rtype: UserDisplayDetails
"""
return self._owner
@owner.setter
def owner(self, owner):
"""Sets the owner of this UserAudienceCompositionDetail.
:param owner: The owner of this UserAudienceCompositionDetail. # noqa: E501
:type: UserDisplayDetails
"""
if self.local_vars_configuration.client_side_validation and owner is None: # noqa: E501
raise ValueError("Invalid value for `owner`, must not be `None`") # noqa: E501
self._owner = owner
@property
def number_of_users_shared_with(self):
"""Gets the number_of_users_shared_with of this UserAudienceCompositionDetail. # noqa: E501
The number of people this composition has been shared with # noqa: E501
:return: The number_of_users_shared_with of this UserAudienceCompositionDetail. # noqa: E501
:rtype: int
"""
return self._number_of_users_shared_with
@number_of_users_shared_with.setter
def number_of_users_shared_with(self, number_of_users_shared_with):
"""Sets the number_of_users_shared_with of this UserAudienceCompositionDetail.
The number of people this composition has been shared with # noqa: E501
:param number_of_users_shared_with: The number_of_users_shared_with of this UserAudienceCompositionDetail. # noqa: E501
:type: int
"""
if self.local_vars_configuration.client_side_validation and number_of_users_shared_with is None: # noqa: E501
raise ValueError("Invalid value for `number_of_users_shared_with`, must not be `None`") # noqa: E501
self._number_of_users_shared_with = number_of_users_shared_with
@property
def shared_to_all(self):
"""Gets the shared_to_all of this UserAudienceCompositionDetail. # noqa: E501
Whether this composition has been shared to all users # noqa: E501
:return: The shared_to_all of this UserAudienceCompositionDetail. # noqa: E501
:rtype: bool
"""
return self._shared_to_all
@shared_to_all.setter
def shared_to_all(self, shared_to_all):
"""Sets the shared_to_all of this UserAudienceCompositionDetail.
Whether this composition has been shared to all users # noqa: E501
:param shared_to_all: The shared_to_all of this UserAudienceCompositionDetail. # noqa: E501
:type: bool
"""
if self.local_vars_configuration.client_side_validation and shared_to_all is None: # noqa: E501
raise ValueError("Invalid value for `shared_to_all`, must not be `None`") # noqa: E501
self._shared_to_all = shared_to_all
@property
def share_id(self):
"""Gets the share_id of this UserAudienceCompositionDetail. # noqa: E501
The id of the share associated with this composition, or null if the composition has not yet been shared # noqa: E501
:return: The share_id of this UserAudienceCompositionDetail. # noqa: E501
:rtype: int
"""
return self._share_id
@share_id.setter
def share_id(self, share_id):
"""Sets the share_id of this UserAudienceCompositionDetail.
The id of the share associated with this composition, or null if the composition has not yet been shared # noqa: E501
:param share_id: The share_id of this UserAudienceCompositionDetail. # noqa: E501
:type: int
"""
self._share_id = share_id
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, UserAudienceCompositionDetail):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, UserAudienceCompositionDetail):
return True
return self.to_dict() != other.to_dict()
| [
"tim.morris@apteco.com"
] | tim.morris@apteco.com |
5dd3d6567d4a2ec9f3f1a5da2e2856a9b40aa58f | f07a42f652f46106dee4749277d41c302e2b7406 | /Data Set/bug-fixing-5/24743e5cdca47da694bad41b1c623c1fb6f76d96-<storage_client>-fix.py | cf3c119ef92e771508a7688684103ed9eed03cc2 | [] | no_license | wsgan001/PyFPattern | e0fe06341cc5d51b3ad0fe29b84098d140ed54d1 | cc347e32745f99c0cd95e79a18ddacc4574d7faa | refs/heads/main | 2023-08-25T23:48:26.112133 | 2021-10-23T14:11:22 | 2021-10-23T14:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 312 | py | @property
def storage_client(self):
self.log('Getting storage client...')
if (not self._storage_client):
self._storage_client = self.get_mgmt_svc_client(StorageManagementClient, base_url=self._cloud_environment.endpoints.resource_manager, api_version='2017-06-01')
return self._storage_client | [
"dg1732004@smail.nju.edu.cn"
] | dg1732004@smail.nju.edu.cn |
867d75f33cd3da6daf2b3995eecb64dfde88c457 | 84a5092ecc558c0f887d9778e4a67a2708644f03 | /order/urls.py | 66aae375ebd06449ac0b1a54a6dcb42cd0815083 | [] | no_license | wecode-bootcamp-korea/15-2nd-R.I.P.-backend | 69512fec116544f214cc14f55317ed8947a69e4a | 02895fb56dbc061134952016c0c3def17e0d4503 | refs/heads/master | 2023-02-10T20:29:13.804764 | 2021-01-11T12:31:51 | 2021-01-11T12:31:51 | 324,920,988 | 0 | 1 | null | 2021-01-11T12:31:53 | 2020-12-28T05:34:17 | Python | UTF-8 | Python | false | false | 52 | py | from django.urls import path
urlpatterns = [
]
| [
"fergith@naver.com"
] | fergith@naver.com |
9d22ea778fb77968652fa8f01e3e11aeb552d468 | 8ab7e102c01d436f37ad221802f601f2206b59a8 | /Tray.py | 8be528c31afbe961604a27f970b2104009cdcb7d | [] | no_license | shanto268/muon_simulator | 9900129fd0fab418b53002cde47191ac667ace36 | c80812edb1800720570b8d3b792a46f7c83f3cbb | refs/heads/master | 2023-02-17T17:33:37.099252 | 2021-01-16T18:56:25 | 2021-01-16T18:56:25 | 330,234,282 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,076 | py | import matplotlib.pyplot as plt
import numpy as np
class Tray:
"""Docstring for Tray. """
def __init__(self, nbarx, nbary, bar_size, z_pos):
"""TODO: to be defined.
:nbarx: TODO
:nbary: TODO
:bar_size: TODO
:z_pos: TODO
:tray_id: TODO
"""
self._nbarx = nbarx
self._nbary = nbary
self._bar_size = bar_size
self._z_pos = z_pos
self.default_data = self.createPlane()
def createTray(self, n):
return [0 for i in range(n)]
def createPlane(self):
x = self.createTray(self._nbarx)
y = self.createTray(self._nbary)
return np.array([x, y])
def getHit(self, hitTuple):
data = np.array(self.default_data)
for i in range(len(hitTuple)):
if hitTuple[i] != -1:
data[i, hitTuple[i] - 1] = 1
return data
if __name__ == "__main__":
x = Tray(11, 11, 0.5, 1)
hit = x.getHit((2, 3))
hit = x.getHit((-1, 11)) #-1 means missing
hit = x.getHit((-1, -1)) #-1 means missing
| [
"sadman-ahmed.shanto@ttu.edu"
] | sadman-ahmed.shanto@ttu.edu |
9a616dfa2333cd6ed238d4d246c059e82877b52b | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03072/s215726876.py | ace993f320aeb75bab4c12c97f84521fdf740fd3 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 140 | py | n = int(input())
a = list(map(int,input().split()))
k = -1
ans = 0
for i in a :
if (k <= i):
ans += 1
k = i
print(ans)
| [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
2cc4855a8aab578a5cd1e23e4c2ac49e1815d8c6 | d94b6845aeeb412aac6850b70e22628bc84d1d6d | /dp_multiq/smooth.py | 00ee23c34be2fbb33604d1da53a84bde719e8fa4 | [
"CC-BY-4.0",
"Apache-2.0"
] | permissive | ishine/google-research | 541aea114a68ced68736340e037fc0f8257d1ea2 | c1ae273841592fce4c993bf35cdd0a6424e73da4 | refs/heads/master | 2023-06-08T23:02:25.502203 | 2023-05-31T01:00:56 | 2023-05-31T01:06:45 | 242,478,569 | 0 | 0 | Apache-2.0 | 2020-06-23T01:55:11 | 2020-02-23T07:59:42 | Jupyter Notebook | UTF-8 | Python | false | false | 2,302 | py | # coding=utf-8
# Copyright 2023 The Google Research Authors.
#
# 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.
"""Smooth sensitivity method for computing differentially private quantiles.
Lemmas 2.6 and 2.9 from "Smooth Sensitivity and Sampling in Private Data
Analysis" by Nissim, Radkhodnikova, and Smith
(https://cs-people.bu.edu/ads22/pubs/NRS07/NRS07-full-draft-v1.pdf) describe the
noise scaled to the smooth sensitivity.
"""
import numpy as np
from dp_multiq import base
from dp_multiq import smooth_utils
def smooth(sorted_data, data_low, data_high, qs, divided_eps, divided_delta):
"""Returns (eps, delta)-differentially private quantile estimates for qs.
Args:
sorted_data: Array of data points sorted in increasing order.
data_low: Lower limit for any differentially private quantile output value.
data_high: Upper limit for any differentially private quantile output value.
qs: Increasing array of quantiles in [0,1].
divided_eps: Privacy parameter epsilon, assumed to be already divided for
the desired overall eps.
divided_delta: Privacy parameter delta, assumed to be already divided for
the desired overall delta.
"""
sorted_data = np.clip(sorted_data, data_low, data_high)
o = np.empty(len(qs))
n = len(sorted_data)
alpha = divided_eps / 2.0
beta = divided_eps / (2 * np.log(2 / divided_delta))
for i in range(len(qs)):
true_quantile_idx = base.quantile_index(n, qs[i])
true_quantile_value = sorted_data[true_quantile_idx]
log_sensitivity = smooth_utils.compute_log_smooth_sensitivity(
sorted_data, data_low, data_high, true_quantile_idx, beta)
noise = np.exp(log_sensitivity) * np.random.laplace() / alpha
o[i] = true_quantile_value + noise
o = np.clip(o, data_low, data_high)
return np.sort(o)
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
4f776f4688760e7bdf2e1608574bf13a02b8c879 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/84/usersdata/224/52670/submittedfiles/lista1.py | 406d010dc5782205ffb282a4d8df23827cd7c80d | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 505 | py | # -*- coding: utf-8 -*-
def funçao(lista):
cont=0
cont2=0
soma2=0
soma=0
for i in range(0,len(lista),1):
if lista[i]%2!=0:
cont=cont+1
soma=soma+lista[i]
else:
soma2=soma2+1
cont2=cont2+1
return cont
return cont2
return soma
return soma2
n=int(input('Digite o tamanho da lista: '))
a=[]
for i in range(1,n+1,1):
numero=int(input('Digite o numero: '))
a.append(numero)
print(funçao(a))
print(a) | [
"rafael.mota@ufca.edu.br"
] | rafael.mota@ufca.edu.br |
f52ff10a37130d0173b23d7ea2e9932e6209ca88 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03317/s687010919.py | 6fd7ffb65d80691f364264801e1f5e0043da55f5 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 285 | py | import sys
import itertools
sys.setrecursionlimit(1000000000)
from heapq import heapify,heappop,heappush,heappushpop
import math
import collections
MOD = 10**9+7
MAX = 10**18
MIN = -10**18
n,k = map(int,input().split())
a = list(map(int,input().split()))
print(math.ceil((n-1)/(k-1))) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
579a281ff5e8d5080677b812effa12d2b3b09d5f | 44e8285d6851e8e709f124acc490c714578ece68 | /app/recipe/tests/test_tags_api.py | 76ca7c39f7ade31e57dacb543544686456c0c83d | [
"MIT"
] | permissive | alanclaros/recipe-app-api | 628445c41eab175be8472294fbe9f6a1e1971add | 4434209772bdb0d785796ec65d631100ee2d6843 | refs/heads/master | 2022-08-01T20:35:28.539951 | 2020-05-24T18:33:26 | 2020-05-24T18:33:26 | 265,684,792 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,530 | py | from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Tag
from recipe.serializers import TagSerializer
TAGS_URL = reverse('recipe:tag-list')
class PublicTagsApiTests(TestCase):
"""test the public available tags API"""
def setUp(self):
self.client = APIClient()
def test_login_required(self):
"""test that login is required for retrieving tags"""
res = self.client.get(TAGS_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class PrivateTagsApiTests(TestCase):
"""test the authorized user tags API"""
def setUp(self):
self.user = get_user_model().objects.create_user(
'test@gmail.com',
'test123'
)
self.client = APIClient()
self.client.force_authenticate(self.user)
def test_retrieve_tags(self):
"""test retrieving tags"""
Tag.objects.create(user=self.user, name='Vegan')
Tag.objects.create(user=self.user, name='Dessert')
res = self.client.get(TAGS_URL)
tags = Tag.objects.all().order_by('-name')
serializer = TagSerializer(tags, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)
def test_tags_limited_to_user(self):
"""test that tags returned are for the authenticated user"""
user2 = get_user_model().objects.create_user(
'user2@gmail.com',
'test123'
)
Tag.objects.create(user=user2, name='Fruity')
tag = Tag.objects.create(user=self.user, name='Confort Food')
res = self.client.get(TAGS_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data), 1)
self.assertEqual(res.data[0]['name'], tag.name)
def test_create_tag_successful(self):
"""test creating a new tag"""
payload = {'name': 'test tag'}
self.client.post(TAGS_URL, payload)
exists = Tag.objects.filter(
user=self.user,
name=payload['name']
).exists()
self.assertTrue(exists)
def test_create_tag_invalid(self):
""" test creating a new tag with invalid payload"""
payload = {'name': ''}
res = self.client.post(TAGS_URL, payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
| [
"alan_claros13@hotmail.com"
] | alan_claros13@hotmail.com |
16e899a2352d374fe7ac99c47ee632c96186479d | 37194bcee20e66e84360010d98a45adcced57963 | /02_PS_I/00_pascals_triangle/2005_pascals_triangle.py | 95f53393c42adbb1cf009aec1daaa6c22326f7c2 | [] | no_license | dmdekf/algo | edcd1bbd067102a622ff1d55b2c3f6274126414a | 544a531799295f0f9879778a2d092f23a5afc4ce | refs/heads/master | 2022-09-13T14:53:31.593307 | 2020-06-05T07:06:03 | 2020-06-05T07:06:03 | 237,857,520 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 518 | py | import sys
sys.stdin = open('input.txt')
T = int(input())
for tc in range(1, T+1):
print('#{} '.format(tc))
N = int(input())
tmp = []
result = [1]
print(1)
# temp = []일경우 for문 처음은 돌아가지 않고 temp에 result가 대입된 후 두번째행부터 포문 실행.
for i in range(N-1):
result = [1]
for j in range(i):
result.append(tmp[j]+tmp[j+1])
result.append(1)
print(' '.join(map(str, result)))
tmp = result
| [
"dmdekf@gmail.com"
] | dmdekf@gmail.com |
b083bff66cdb6a9442d1c4e864a68d3db574d737 | 557a5e8ac000718959281d1d31da8e1e4947a155 | /examples/translating_a_file.py | d77465a93203a15d5376b62e0dcbe45e1aa21447 | [
"MIT"
] | permissive | PiotrDabkowski/Js2Py | 66f20a58912d2df719ce5952d7fe046512717d4d | 2e017b86e2f18a6c8a842293b1687f2ce7baa12e | refs/heads/master | 2023-08-17T08:47:00.625508 | 2022-11-06T09:56:37 | 2022-11-06T10:12:00 | 24,736,750 | 2,419 | 318 | MIT | 2023-08-03T18:06:40 | 2014-10-02T21:08:48 | JavaScript | UTF-8 | Python | false | false | 886 | py | import js2py
# there are 2 easy methods to run js file from Js2Py
# Method 1:
eval_result, example = js2py.run_file('example.js')
# Method 2:
js2py.translate_file('example.js', 'example.py') # this translates and saves equivalent Py file
from example import example # yes, it is: import lib_name from lib_name
##### Now you can use your JS code as if it was Python!
print(example.someVariable)
print(example.someVariable.a)
print(example.someVariable['a'])
example.sayHello('Piotrek!')
example.sayHello() # told you, just like JS.
example['$nonPyName']() # non py names have to be accessed through [] example.$ is a syntax error in Py.
# but there is one problem - it is not possible to write 'new example.Rectangle(4,3)' in Python
# so you have to use .new(4,3) instead, to create the object.
rect = example.Rectangle.new(4,3)
print(rect.getArea()) # should print 12
| [
"piodrus@gmail.com"
] | piodrus@gmail.com |
fd1311d8e71ac932322f58c81588dc5b61c5c3b7 | 34de2b3ef4a2478fc6a03ea3b5990dd267d20d2d | /Python/plotting/plotting1/polarPlotting/circle/using_function.py | 20830fc34fff99d77824caa09a7a93d271124a56 | [
"MIT"
] | permissive | bhishanpdl/Programming | d4310f86e1d9ac35483191526710caa25b5f138e | 9654c253c598405a22cc96dfa1497406c0bd0990 | refs/heads/master | 2020-03-26T06:19:01.588451 | 2019-08-21T18:09:59 | 2019-08-21T18:09:59 | 69,140,073 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 375 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author : Bhishan Poudel
# Date : Apr 01, 2016
# Imports
import matplotlib.pyplot as plt
import numpy as np
def xy(r,phi):
return r*np.cos(phi), r*np.sin(phi)
fig = plt.figure()
ax = fig.add_subplot(111,aspect='equal')
phis=np.arange(0,6.28,0.01) # 2pi = 6.28
r =1.5
ax.plot( *xy(r,phis), c='r',ls='-' )
plt.show()
| [
"bhishantryphysics@gmail.com"
] | bhishantryphysics@gmail.com |
ca4f212c3ddc1bf31eec951c5286cc6ffc708e07 | 27398b2a8ed409354d6a36c5e1d2089dad45b4ac | /backend/admin/setup.py | cbca0ce536eb06ebf9c7b662c3d19799d6e8c7b6 | [
"Apache-2.0"
] | permissive | amar266/ceph-lcm | e0d6c1f825f5ac07d2926bfbe6871e760b904340 | 6b23ffd5b581d2a1743c0d430f135261b7459e38 | refs/heads/master | 2021-04-15T04:41:55.950583 | 2018-03-23T12:51:26 | 2018-03-23T12:51:26 | 126,484,605 | 0 | 0 | null | 2018-03-23T12:50:28 | 2018-03-23T12:50:27 | null | UTF-8 | Python | false | false | 2,358 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Mirantis 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 setuptools
REQUIREMENTS = (
"decapod-api~=1.2.dev1",
"decapod-common~=1.2.dev1",
"decapod-controller~=1.2.dev1",
"decapodlib~=1.2.dev1",
"python-keystoneclient>=3.9,<4",
"click>=6,<7",
"cryptography>=1.4,<2",
"asyncssh[libnacl,bcrypt]>=1.8,<2",
# 3.15.1 brings Babel!=2.4.0 line which is controversal
# to requirements in Keystone. Therefore installation is broken.
# next version will eliminate runtime dependency to Babel
# completely (first commit after tag 3.15.1)
"oslo.i18n<3.15.1"
)
setuptools.setup(
name="decapod-admin",
description="Admin scripts for Decapod",
long_description="", # TODO
version="1.2.0.dev1",
author="Sergey Arkhipov",
author_email="sarkhipov@mirantis.com",
maintainer="Sergey Arkhipov",
maintainer_email="sarkhipov@mirantis.com",
license="Apache2",
url="https://github.com/Mirantis/ceph-lcm",
packages=setuptools.find_packages(),
python_requires=">=3.4",
install_requires=REQUIREMENTS,
zip_safe=False,
include_package_data=True,
extras_require={
"uvloop": ["uvloop>=0.7"]
},
package_data={
"decapod_admin": [
"migration_scripts/*"
]
},
entry_points={
"console_scripts": [
"decapod-admin = decapod_admin.main:cli"
]
},
classifiers=(
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5"
)
)
| [
"sarkhipov@mirantis.com"
] | sarkhipov@mirantis.com |
5b72a3bf4afaf327b4f303040f4616e683291caa | 0204dc09d72da99fb35968f493e9499106be7dca | /BasicPython/codes/temploop/index.py | 109e5f907746e838c4501989b3563048baddf21f | [] | no_license | jamesblunt/ITArticles | 4b95a5586b3158672a05c76ea97c4c1c0f1190a2 | 5c1fc6e64ce32bf0143488897ae37bb10a52df91 | refs/heads/master | 2021-01-22T14:39:48.233415 | 2014-11-03T10:15:16 | 2014-11-03T10:15:16 | 26,259,126 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 880 | py | #! /usr/bin/env python
#-*- coding:utf-8 -*-
import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.options
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
lst = ["python","www.itdiffer.com","qiwsir@gmail.com"]
self.render("index.html", info=lst)
handlers = [(r"/", IndexHandler),]
template_path = os.path.join(os.path.dirname(__file__), "temploop")
static_path = os.path.join(os.paht.dirname(__file__), "static")
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(handlers, template_path, static)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
| [
"qiwsir@gmail.com"
] | qiwsir@gmail.com |
428f77c853854010b07704ff6552aac304b8db68 | d62021dff4503fedcce62011b994f9917063e1bf | /python_full_statck/fuction/homework/day3_2/day3_2.py | cdaabffb27361088a7b7e39a11b5b0abe9cd8609 | [] | no_license | tsytsy/python-study | 9eefb202cc1348589f111709742c0c4deb84a43f | 04545e50b998a25c03173b966b1e1cf6b988b042 | refs/heads/master | 2021-09-06T06:39:57.344363 | 2018-02-03T09:43:31 | 2018-02-03T09:43:31 | 112,138,223 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 13,490 | py | import time
def isnumber(aString):
try:
float(aString)
return True
except:
return False
def info_listdic_to_str(res):
str1 = ''
for d in res:
count = 0
for line in d.values():
if count == 4:
str1 = str1 + line + '\n'
else:
str1 = str1 + line + ','
count += 1
return str1
def admin_file_alter(file, old_str):
str1 = ''
with open(file, 'r') as f:
for i in f:
if i.startswith(old_str):
continue
str1 += i
with open(file, 'w') as f1:
f1.write(str1)
def log_file_read(file):
with open(file, 'r') as f:
lines = [line.strip().split(',') for line in f]
res = [{'account': i[0], 'passwd': i[1]} for i in lines]
return res
def info_file_read(file):
with open(file, 'r') as f:
lines = [line.strip().split(',') for line in f]
res = [{'account': i[0], 'passwd': i[1], 'balance': i[2], 'arrears': i[3], 'overdraft': i[4]} for i in lines]
return res
def info_append(file, content):
with open(file, 'a') as f:
f.write(content)
def login():
welcome = '''
1. 管理员登录
2. 用户登录
3. 退出
'''
while True:
print(welcome)
choice = input('>>输入数字进入相应登录操作:')
if choice not in ['1', '2', '3']:
print('输入错误,请重新输入')
else:
return choice
def admin_login():
count = 0
while count < 3:
d = {}
account = input('>>请输入管理员账号:')
passwd = input('>>请输入你的密码:')
d['account'] = account
d['passwd'] = passwd
res = log_file_read('admin_login.txt')
if d in res:
print('login successful')
admin_func_choice()
break
else:
print('account or passwd wrong')
count += 1
else:
print('你已经尝试了三次登入,请稍后再试一下')
def user_login():
count = 0
flag = True
while flag:
account = input('>>请输入你的账号:')
passwd = input('>>请输入你的密码:')
res_lock = info_file_read('lock_user.txt')
res = info_file_read('user_info.txt')
for d in res_lock:
if d['account'] == account and d['passwd'] == passwd:
print('Sorry,your account has been locked')
exit()
for d in res:
if d['account'] == account and d['passwd'] == passwd:
print('login successful')
user_func_choice(account)
flag = False
break
else:
print('account or passwd wrong')
count += 1
if count == 3:
print('你已经尝试了三次登入,请稍后再试一下')
break
def user_func_choice(acoount):
user_function_liststr = '''
1. 取款
2. 存款
3. 转账
4. 还款
5. 打印历史记录
6. 查看余额
7. 退出
'''
user_function_dict = {
'1': user_withdrawal,
'2': user_deposit,
'3': user_transfer,
'4': user_repayment,
'5': user_history_record,
'6': user_search_balance,
'7': user_quit2
}
while True:
print(user_function_liststr)
choice = input('>>输入你需要的服务:')
if choice not in ['1', '2', '3', '4', '5', '6', '7']:
print('输入错误,请重新输入')
continue
else:
user_function_dict[choice](acoount)
def user_withdrawal(account):
'''
1. 取出金额先余额里减钱,如果余额里没有钱,可以线欠着,如果欠款达到透支额,那么取钱失败
2. 在用户信息中更新余额,欠款数值
3. 取钱记录要保存在历史记录中
'''
res = info_file_read('user_info.txt')
index = None
for d in res:
if account == d['account']:
index = res.index(d)
print(index)
money = float(input(">>取出金额:"))
if money <= float(res[index]['balance']):
new_balance = str(float(res[index]['balance'])-money)
res[index]['balance'] = new_balance
str1 = info_listdic_to_str(res)
print(str1)
with open('user_info.txt', 'w') as f:
f.write(str1)
print('取款完成')
time1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
record = '{},{},{},{}'.format(time1, account, 'withdraw', money) + '\n'
info_append('atm_record.txt', record)
elif money + float(res[index]['arrears']) <= float(res[index]['overdraft']):
new_arrears = str(float(res[index]['arrears'])+money)
res[index]['arrears'] = new_arrears
str1 = info_listdic_to_str(res)
with open('user_info.txt', 'w') as f:
f.write(str1)
print('你的余额不足,从透支额中取款完成')
time1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
record = '{},{},{},{}'.format(time1, account, 'withdraw', money) + '\n'
info_append('atm_record.txt', record)
else:
print('余额不足')
def user_deposit(account):
res = info_file_read('user_info.txt')
print(res)
index = None
for d in res:
if account == d['account']:
index = res.index(d)
print(index)
money = float(input(">>存入金额:"))
new_balance = str(float(res[index]['balance']) + money)
res[index]['balance'] = new_balance
str1 = info_listdic_to_str(res)
with open('user_info.txt', 'w') as f:
f.write(str1)
print('存款完成')
time1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
record = '{},{},{},{}'.format(time1, account, 'deposit', money) + '\n'
info_append('atm_record.txt', record)
def user_transfer(account):
'''
1. 转账先从余额里减钱,如果余额里没有钱,可以线欠着,如果欠款达到透支额,那么转账失败
2. 在用户信息中更新余额,欠款数值
3. 取钱记录要保存在历史记录中
4. 在用户信息中更新被转账账号数据
'''
res = info_file_read('user_info.txt')
account_list = []
for d1 in res:
account_list.append(d1['account'])
print(account_list)
print(res)
index = None
to_index = None
for d in res:
if account == d['account']:
index = res.index(d)
print(index)
while True:
to_who = input('>>对方账号,退出按q:')
if to_who == 'q':
return
elif to_who not in account_list:
print('不存在这个账号,重新输入')
continue
break
for d in res:
if to_who == d['account']:
to_index = res.index(d)
print(to_index)
money = float(input(">>转账金额:"))
str1 = ''
if money <= float(res[index]['balance']):
new_balance = str(float(res[index]['balance']) - money)
res[index]['balance'] = new_balance
res[to_index]['balance'] = str(float(res[to_index]['balance']) + money)
str1 = info_listdic_to_str(res)
with open('user_info.txt', 'w') as f:
f.write(str1)
print('转账完成')
time1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
record = '{},{},{},{},{}'.format(time1, account, 'transfer to', to_who, money) + '\n'
info_append('atm_record.txt', record)
elif money + float(res[index]['arrears']) <= float(res[index]['overdraft']):
new_arrears = str(float(res[index]['arrears']) + money)
res[index]['arrears'] = new_arrears
res[to_index]['balance'] = str(float(res[to_index]['balance']) + money)
str1 = info_listdic_to_str(res)
with open('user_info.txt', 'w') as f:
f.write(str1)
print('你的余额不足,从透支额转账完成')
time1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
record = '{},{},{},{},{}'.format(time1, account, 'transfer to', to_who, money) + '\n'
info_append('atm_record.txt', record)
else:
print('余额不足')
pass
def user_repayment(account):
'''
1. 自己本身可以还款任意金额,
'''
res = info_file_read('user_info.txt')
print(res)
index = None
for d in res:
if account == d['account']:
index = res.index(d)
print(index)
while True:
pay_debt = input('>>请输入还款金额,不还款退出按q:')
if pay_debt == 'q':
return
pay_debt = float(pay_debt)
if pay_debt > float(res[index]['arrears']):
print('欠款没有达到这个这个金额,不用还这么多')
continue
elif pay_debt > float(res[index]['balance']):
print('您的余额不足,还款金额超过了您的余额')
continue
else:
break
res[index]['balance'] = str(float(res[index]['balance']) - pay_debt)
res[index]['arrears'] = str(float(res[index]['arrears']) - pay_debt)
str1 = info_listdic_to_str(res)
with open('user_info.txt', 'w') as f:
f.write(str1)
print('还款完成')
time1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
record = '{},{},{},{}'.format(time1, account, 'pay debt', pay_debt) + '\n'
info_append('atm_record.txt', record)
def user_history_record(account):
L = []
with open('atm_record.txt', 'r') as f:
for line in f:
# print(line)
new_line = line.strip().split(',')
# print(new_line)
if account in new_line:
L.append(line)
print(L)
for line in L:
print(line)
def user_search_balance(account):
res = info_file_read('user_info.txt')
for d in res:
if account == d['account']:
index = res.index(d)
print('你的余额为:%s' % res[index]['balance'])
print('你的欠款为:%s' % res[index]['arrears'])
print('你的透支额为:%s' % res[index]['overdraft'])
def user_quit2(account):
exit()
'---------------------------------------------------------------------'
def admin_func_choice():
function_liststr = '''
1. 添加账号
2. 冻结用户
3. 解冻用户
4. 查询用户
5. 退出
6. 指定用户透支额
'''
function_dict = {
'1': user_add,
'2': user_freeze,
'3': user_unfreeze,
'4': user_search,
'5': user_quit,
'6': user_overdraft
}
while True:
print(function_liststr)
choice = input('>>选择你需要的服务:')
if choice not in ['1', '2', '3', '4', '5', '6']:
print('输入错误,请重新输入')
continue
else:
function_dict[choice]()
#添加账号
# def user_add(account, passwd, balance=0, arrears=0, overdraft=0):
def user_add():
print("你需要填入以下信息")
account = input('>>账号:')
passwd = input('>>密码:')
balance = input('>>余额:')
arrears = input('>>欠款:')
overdraft = input('>>透资额:')
str1 = '{0},{1},{2},{3},{4}'.format(account, passwd, balance, arrears, overdraft) + '\n'
info_append('user_info.txt', str1)
#冻结用户
def user_freeze():
res = info_file_read('user_info.txt')
str2 = ''
account = input('>>输入你要冻结的账号:')
for d in res:
if account in d.values():
for j in d.values():
str2 = str2 + j + ','
str2 += '\n'
info_append('lock_user.txt', str2)
print('***************冻结成功***************')
#解冻用户
def user_unfreeze():
print('被冻结的账户如下')
res = info_file_read('lock_user.txt')
for d in res:
print(d)
account = input('>>输入你要解结的账号:')
admin_file_alter('lock_user.txt', account)
print('解冻成功')
def user_search():
res = info_file_read('user_info.txt')
print('********查询结果如下*******')
for d in res:
print(d)
def user_quit():
exit()
def user_overdraft():
res = info_file_read('user_info.txt')
account_list = []
for d1 in res:
account_list.append(d1['account'])
while True:
account = input('>>对方账号,退出按q:')
if account == 'q':
return
elif account not in account_list:
print('不存在这个账号,重新输入')
continue
break
index = None
for d in res:
if account == d['account']:
index = res.index(d)
# print(index)
while True:
overdraft = input('>>输入用户的透支额,退出请按q:')
if overdraft == 'q':
return
elif not isnumber(overdraft):
print('not a number')
continue
break
res[index]['overdraft'] = overdraft
str1 = info_listdic_to_str(res)
with open('user_info.txt', 'w') as f:
f.write(str1)
if __name__ == '__main__':
user_choice = login()
if user_choice == '1':
admin_login()
elif user_choice == '2':
user_login()
else:
exit()
| [
"tsy31415926@163.com"
] | tsy31415926@163.com |
adc32f48782610a4a73107a6acc7052b70daad5b | 7c54b892aec3fd9241ee0d134a093a01b4f0c2e6 | /server/pvwproxy/server/__init__.py | eeaa3dc3c079e4cde488826c113d11f2e71aea1a | [
"Apache-2.0"
] | permissive | Cloudydew/HPCCloud | f75861e653d55ac4bdf668be95baa489397c0f75 | 692e270420c9c681c38e6346c19a9df4a7268a07 | refs/heads/master | 2020-04-12T19:16:00.174809 | 2018-04-05T17:47:11 | 2018-04-05T17:47:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,164 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2015 Kitware 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 girder import events
from .proxy import Proxy
from . import constants
def validate_settings(event):
key = event.info['key']
if key == constants.PluginSettings.PROXY_FILE_PATH:
event.preventDefault().stopPropagation()
def load(info):
events.bind('model.setting.validate', 'pvwproxy', validate_settings)
info['apiRoot'].proxy = Proxy()
| [
"chris.harris@kitware.com"
] | chris.harris@kitware.com |
9d348c74cfa0509c0a01aa7f0a597a277a85211d | 11a0fab712b139bcba9e90f6acdc7597dff68dbb | /mestrado/ppgmcs/m07-elaboracao-de-dissertacao-i/projeto/codigo/teste1/parametros/cadastrarturmas.py | 98f78e068419fccbd2707980275f28f217c91717 | [] | no_license | fapers/MeusTreinamentos | 17ba096d518df533433ae2528b70d18717f3cf96 | 32a6b791b0c3dbb8b29ffd177597919e768b09b5 | refs/heads/master | 2023-06-04T14:00:37.847808 | 2021-06-28T02:37:11 | 2021-06-28T02:37:11 | 292,962,787 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,755 | py | from bancodados.modelo import Turma
# Cadastrar todas as turma da escola
# Nome, Nível, Turno, Número de aulas por semana
# Nível 16 é o 6º ano do ensino fundamental
# Nível 17 é o 7º ano do ensino fundamental
# Nível 18 é o 8º ano do ensino fundamental
# Nível 19 é o 97º ano do ensino fundamental
# Nível 21 é o 1º ano do ensino médio
# Nível 22 é o 2º ano do ensino médio
# Nível 23 é o 3º ano do ensino médio
def cadastrar_turmas():
turma = Turma('6º4', 16, 1, 25)
turma.salvar()
turma = Turma('7º4', 17, 1, 25)
turma.salvar()
turma = Turma('8º4', 18, 1, 25)
turma.salvar()
turma = Turma('9º4', 19, 1, 25)
turma.salvar()
turma = Turma('1º6', 21, 1, 25)
turma.salvar()
turma = Turma('1º7', 21, 1, 25)
turma.salvar()
turma = Turma('1º8', 21, 1, 25)
turma.salvar()
turma = Turma('1º10', 21, 1, 25)
turma.salvar()
turma = Turma('2º6', 22, 1, 25)
turma.salvar()
turma = Turma('2º7', 22, 1, 25)
turma.salvar()
turma = Turma('2º8', 22, 1, 25)
turma.salvar()
turma = Turma('3º5', 23, 1, 25)
turma.salvar()
turma = Turma('3º6', 23, 1, 25)
turma.salvar()
turma = Turma('3º7', 23, 1, 25)
turma.salvar()
turma = Turma('6º3', 16, 2, 25)
turma.salvar()
turma = Turma('7º3', 17, 2, 25)
turma.salvar()
turma = Turma('8º3', 18, 2, 25)
turma.salvar()
turma = Turma('9º3', 19, 2, 25)
turma.salvar()
turma = Turma('1º9', 21, 2, 25)
turma.salvar()
turma = Turma('2º5', 22, 2, 25)
turma.salvar()
turma = Turma('1ºEJA', 21, 3, 20)
turma.salvar()
turma = Turma('3ºEJA', 23, 3, 20)
turma.salvar()
return turma.get_turmas()
| [
"fpsmoc@yahoo.com.br"
] | fpsmoc@yahoo.com.br |
053bd60526c036a98495e45eb02c3f6d5bd9d452 | ecd630f54fefa0a8a4937ac5c6724f9a3bb215c3 | /projeto/emprestimo/migrations/0008_auto_20200516_2138.py | b43edde81f941e7f9a7ebe225aff2c97d42e02e4 | [] | no_license | israelwerther/Esctop_Israel_Estoque | 49968751464a38c473298ed876da7641efedf8de | d6ab3e502f2a97a0d3036351e59c2faa267c0efd | refs/heads/master | 2023-01-07T20:21:38.381593 | 2020-11-12T17:35:14 | 2020-11-12T17:35:14 | 258,642,721 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 373 | py | # Generated by Django 3.0.5 on 2020-05-16 21:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('emprestimo', '0007_remove_emprestimo_datetime'),
]
operations = [
migrations.AlterModelOptions(
name='emprestimo',
options={'ordering': ('-data_emprestimo',)},
),
]
| [
"israelwerther48@outlook.com"
] | israelwerther48@outlook.com |
1ec51963bbc5d440bca3ef080c9ca0c7a669dd12 | 99f6c5b7a6b6840163b32d633e658678d5829b46 | /practice/leetcode/algorithm/295_NimGame.py | c5eee37e98f68ac5e3d5cd09b891f4cc40a0854a | [] | no_license | aliceayres/leetcode-practice | 32f2695a567317013b567a68863f2c95c75b438b | 0743cbeb0e9aa4a8a25f4520a1e3f92793fae1ee | refs/heads/master | 2021-06-02T15:11:29.946006 | 2020-02-06T04:06:55 | 2020-02-06T04:06:55 | 131,126,554 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 840 | py | """
292. Nim Game
You are playing the following Nim Game with your friend: There is a heap of stones on the table,
each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will
be the winner. You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game. Write a function to determine
whether you can win the game given the number of stones in the heap.
For example, if there are 4 stones in the heap, then you will never win the game:
no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.
"""
class Solution:
def canWinNim(self, n):
"""
:type n: int
:rtype: bool
"""
return n % 4 != 0
if __name__ == '__main__':
slt = Solution()
print(slt.canWinNim(5)) | [
"yeziqian@ctsig.com"
] | yeziqian@ctsig.com |
2e694107b84f48482c364a4d684d0bae288ffd4d | 8fa191cd4a67431a04eff62d35122ee83cc7b0af | /bookwyrm/migrations/0143_merge_0142_auto_20220227_1752_0142_user_hide_follows.py | b36fa9f9c491bd522697b8a4626c47e3c6ab624c | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | bookwyrm-social/bookwyrm | 24678676a7a58dba96641194dfae3fffbf01574d | 0f8da5b738047f3c34d60d93f59bdedd8f797224 | refs/heads/main | 2023-08-20T21:45:30.957277 | 2023-08-19T23:41:50 | 2023-08-19T23:41:50 | 236,415,735 | 1,398 | 216 | NOASSERTION | 2023-09-08T20:43:06 | 2020-01-27T03:51:54 | Python | UTF-8 | Python | false | false | 270 | py | # Generated by Django 3.2.12 on 2022-02-28 21:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("bookwyrm", "0142_auto_20220227_1752"),
("bookwyrm", "0142_user_hide_follows"),
]
operations = []
| [
"mousereeve@riseup.net"
] | mousereeve@riseup.net |
6b4d71f770ba02a69b54b0e9e2dcf68ad37e2a8f | 5f16f3bac5515baea0951a4f806e644f8f6e92b1 | /code/swap.py | 3020b607df335d66bbf620b41b9b5aed16edae84 | [] | no_license | joemeens/guvi | f914e6da4e6a39fb6a74981c883a7f0c27c574ad | cb29c77013e3bf2e81131c02940087418995ddaf | refs/heads/master | 2020-05-31T06:25:25.645970 | 2019-07-12T15:36:11 | 2019-07-12T15:36:11 | 190,142,024 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 97 | py | ass,ssa=(input().split(" "))
ass=int(ass)
ssa=int(ssa)
temp=ass
ass=ssa
ssa=temp
print(ass, ssa)
| [
"noreply@github.com"
] | joemeens.noreply@github.com |
2949520275b4940d93e7ccbc937e113936d50e93 | bad9d42860b9c85bf7316cad108cc6ff071bb705 | /tensorflow_estimator/python/estimator/canned/linear_test.py | 3fac9c57415b5a20acb924ed7d7e73c181871496 | [
"Apache-2.0"
] | permissive | tensorflow/estimator | 1a7e469608094f17bece71867c01f22d51d28080 | 359acd5314462c05ef97f9a820d4ace876550c7e | refs/heads/master | 2023-08-17T09:54:38.668302 | 2023-08-04T00:01:29 | 2023-08-04T00:02:02 | 143,069,012 | 331 | 249 | Apache-2.0 | 2023-09-06T21:19:22 | 2018-07-31T20:55:45 | Python | UTF-8 | Python | false | false | 7,789 | py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for linear.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.python.feature_column import feature_column_v2
from tensorflow.python.framework import ops
from tensorflow_estimator.python.estimator.canned import linear
from tensorflow_estimator.python.estimator.canned import linear_testing_utils
def _linear_regressor_fn(*args, **kwargs):
return linear.LinearRegressorV2(*args, **kwargs)
def _linear_classifier_fn(*args, **kwargs):
return linear.LinearClassifierV2(*args, **kwargs)
# Tests for Linear Regressor.
class LinearRegressorEvaluationV2Test(
linear_testing_utils.BaseLinearRegressorEvaluationTest, tf.test.TestCase):
def __init__(self, methodName='runTest'): # pylint: disable=invalid-name
tf.test.TestCase.__init__(self, methodName)
linear_testing_utils.BaseLinearRegressorEvaluationTest.__init__(
self, _linear_regressor_fn, fc_lib=feature_column_v2)
class LinearRegressorPredictV2Test(
linear_testing_utils.BaseLinearRegressorPredictTest, tf.test.TestCase):
def __init__(self, methodName='runTest'): # pylint: disable=invalid-name
tf.test.TestCase.__init__(self, methodName)
linear_testing_utils.BaseLinearRegressorPredictTest.__init__(
self, _linear_regressor_fn, fc_lib=feature_column_v2)
class LinearRegressorIntegrationV2Test(
linear_testing_utils.BaseLinearRegressorIntegrationTest, tf.test.TestCase):
def __init__(self, methodName='runTest'): # pylint: disable=invalid-name
tf.test.TestCase.__init__(self, methodName)
linear_testing_utils.BaseLinearRegressorIntegrationTest.__init__(
self, _linear_regressor_fn, fc_lib=feature_column_v2)
class LinearRegressorTrainingV2Test(
linear_testing_utils.BaseLinearRegressorTrainingTest, tf.test.TestCase):
def __init__(self, methodName='runTest'): # pylint: disable=invalid-name
tf.test.TestCase.__init__(self, methodName)
linear_testing_utils.BaseLinearRegressorTrainingTest.__init__(
self, _linear_regressor_fn, fc_lib=feature_column_v2)
# Tests for Linear Classifier.
class LinearClassifierTrainingV2Test(
linear_testing_utils.BaseLinearClassifierTrainingTest, tf.test.TestCase):
def __init__(self, methodName='runTest'): # pylint: disable=invalid-name
tf.test.TestCase.__init__(self, methodName)
linear_testing_utils.BaseLinearClassifierTrainingTest.__init__(
self,
linear_classifier_fn=_linear_classifier_fn,
fc_lib=feature_column_v2)
class LinearClassifierEvaluationV2Test(
linear_testing_utils.BaseLinearClassifierEvaluationTest, tf.test.TestCase):
def __init__(self, methodName='runTest'): # pylint: disable=invalid-name
tf.test.TestCase.__init__(self, methodName)
linear_testing_utils.BaseLinearClassifierEvaluationTest.__init__(
self,
linear_classifier_fn=_linear_classifier_fn,
fc_lib=feature_column_v2)
class LinearClassifierPredictV2Test(
linear_testing_utils.BaseLinearClassifierPredictTest, tf.test.TestCase):
def __init__(self, methodName='runTest'): # pylint: disable=invalid-name
tf.test.TestCase.__init__(self, methodName)
linear_testing_utils.BaseLinearClassifierPredictTest.__init__(
self,
linear_classifier_fn=_linear_classifier_fn,
fc_lib=feature_column_v2)
class LinearClassifierIntegrationV2Test(
linear_testing_utils.BaseLinearClassifierIntegrationTest, tf.test.TestCase):
def __init__(self, methodName='runTest'): # pylint: disable=invalid-name
tf.test.TestCase.__init__(self, methodName)
linear_testing_utils.BaseLinearClassifierIntegrationTest.__init__(
self,
linear_classifier_fn=_linear_classifier_fn,
fc_lib=feature_column_v2)
# Tests for Linear logit_fn.
class LinearLogitFnV2Test(linear_testing_utils.BaseLinearLogitFnTest,
tf.test.TestCase):
def __init__(self, methodName='runTest'): # pylint: disable=invalid-name
tf.test.TestCase.__init__(self, methodName)
linear_testing_utils.BaseLinearLogitFnTest.__init__(
self, fc_lib=feature_column_v2)
# Tests for warm-starting with Linear logit_fn.
class LinearWarmStartingV2Test(linear_testing_utils.BaseLinearWarmStartingTest,
tf.test.TestCase):
def __init__(self, methodName='runTest'): # pylint: disable=invalid-name
tf.test.TestCase.__init__(self, methodName)
linear_testing_utils.BaseLinearWarmStartingTest.__init__(
self,
_linear_classifier_fn,
_linear_regressor_fn,
fc_lib=feature_column_v2)
class ComputeFractionOfZeroTest(tf.test.TestCase):
def _assertSparsity(self, expected_sparsity, tensor):
sparsity = linear._compute_fraction_of_zero([tensor])
self.assertAllClose(expected_sparsity, sparsity)
def test_small_float32(self):
self._assertSparsity(
0.75, ops.convert_to_tensor([0, 0, 0, 1], dtype=tf.dtypes.float32))
self._assertSparsity(
0.5, ops.convert_to_tensor([0, 1, 0, 1], dtype=tf.dtypes.float32))
def test_small_int32(self):
self._assertSparsity(
0.75, ops.convert_to_tensor([0, 0, 0, 1], dtype=tf.dtypes.int32))
def test_small_float64(self):
self._assertSparsity(
0.75, ops.convert_to_tensor([0, 0, 0, 1], dtype=tf.dtypes.float64))
def test_small_int64(self):
self._assertSparsity(
0.75, ops.convert_to_tensor([0, 0, 0, 1], dtype=tf.dtypes.int64))
def test_nested(self):
self._assertSparsity(
0.75, [ops.convert_to_tensor([0, 0]),
ops.convert_to_tensor([0, 1])])
def test_none(self):
with self.assertRaises(ValueError):
linear._compute_fraction_of_zero([])
def test_empty(self):
sparsity = linear._compute_fraction_of_zero([ops.convert_to_tensor([])])
self.assertTrue(
self.evaluate(tf.math.is_nan(sparsity)),
'Expected sparsity=nan, got %s' % sparsity)
def test_multiple_empty(self):
sparsity = linear._compute_fraction_of_zero([
ops.convert_to_tensor([]),
ops.convert_to_tensor([]),
])
self.assertTrue(
self.evaluate(tf.math.is_nan(sparsity)),
'Expected sparsity=nan, got %s' % sparsity)
def test_some_empty(self):
with self.test_session():
self._assertSparsity(0.5, [
ops.convert_to_tensor([]),
ops.convert_to_tensor([0.]),
ops.convert_to_tensor([1.]),
])
def test_mixed_types(self):
with self.test_session():
self._assertSparsity(0.6, [
ops.convert_to_tensor([0, 0, 1, 1, 1], dtype=tf.dtypes.float32),
ops.convert_to_tensor([0, 0, 0, 0, 1], dtype=tf.dtypes.int32),
])
def test_2_27_zeros__using_512_MiB_of_ram(self):
self._assertSparsity(1., tf.zeros([int(2**27 * 1.01)],
dtype=tf.dtypes.int8))
def test_2_27_ones__using_512_MiB_of_ram(self):
self._assertSparsity(0., tf.ones([int(2**27 * 1.01)], dtype=tf.dtypes.int8))
if __name__ == '__main__':
tf.test.main()
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
0a15d7e572f86aac2bafaceec9d590699d8caf19 | ba91eb5329fd8e69aa9d9fe1e74e2c7b968806c7 | /robocode-vscode/src/robocode_vscode/plugins/resolve_interpreter.py | 33634dbbbbdb2ab5c8af26212f2fa9e8d972e33c | [
"Apache-2.0"
] | permissive | emanlove/robotframework-lsp | aba9deb43ee7fdd3328e08b4d904d6c4ca44e185 | b0d8862d24e3bc1b72d8ce9412a671571520e7d9 | refs/heads/master | 2022-12-06T01:04:04.103593 | 2020-08-30T15:56:43 | 2020-08-30T15:56:43 | 292,014,577 | 1 | 0 | NOASSERTION | 2020-09-01T14:05:52 | 2020-09-01T14:05:51 | null | UTF-8 | Python | false | false | 12,084 | py | """
Note: this code will actually run as a plugin in the RobotFramework Language
Server, not in the Robocorp Code environment, so, we need to be careful on the
imports so that we only import what's actually available there!
i.e.: We can import `robocode_ls_core`, and even `robotframework_ls`, but we
can't import `robocode_vscode` without some additional work.
"""
import os.path
import sys
from collections import namedtuple
try:
from robocode_vscode.rcc import Rcc # noqa
except:
# Automatically add it to the path if executing as a plugin the first time.
sys.path.append(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
)
import robocode_vscode # @UnusedImport
from robocode_vscode.rcc import Rcc # noqa
from typing import Optional, Dict, List, Tuple
from robocode_ls_core.basic import implements
from robocode_ls_core.pluginmanager import PluginManager
from robotframework_ls.ep_resolve_interpreter import (
EPResolveInterpreter,
IInterpreterInfo,
)
from robocode_ls_core import uris
from robocode_ls_core.robotframework_log import get_logger
from pathlib import Path
import weakref
log = get_logger(__name__)
_CachedFileMTimeInfo = namedtuple("_CachedFileMTimeInfo", "st_mtime, st_size, path")
_CachedInterpreterMTime = Tuple[_CachedFileMTimeInfo, Optional[_CachedFileMTimeInfo]]
def _get_mtime_cache_info(file_path: Path) -> _CachedFileMTimeInfo:
"""
Cache based on the time/size of a given path.
"""
stat = file_path.stat()
return _CachedFileMTimeInfo(stat.st_mtime, stat.st_size, str(file_path))
class _CachedFileInfo(object):
def __init__(self, file_path: Path):
self.file_path = file_path
self.mtime_info: _CachedFileMTimeInfo = _get_mtime_cache_info(file_path)
self.contents: str = file_path.read_text(encoding="utf-8", errors="replace")
self._yaml_contents: Optional[dict] = None
@property
def yaml_contents(self) -> dict:
yaml_contents = self._yaml_contents
if yaml_contents is None:
from robocode_ls_core import yaml_wrapper
from io import StringIO
s = StringIO(self.contents)
yaml_contents = self._yaml_contents = yaml_wrapper.load(s)
return yaml_contents
def is_cache_valid(self) -> bool:
return self.mtime_info == _get_mtime_cache_info(self.file_path)
class _CachedInterpreterInfo(object):
def __init__(
self,
package_yaml_file_info: _CachedFileInfo,
conda_config_file_info: Optional[_CachedFileInfo],
pm: PluginManager,
):
from robotframework_ls.ep_resolve_interpreter import DefaultInterpreterInfo
from robotframework_ls.ep_providers import EPConfigurationProvider
import json
self._mtime: _CachedInterpreterMTime = self._obtain_mtime(
package_yaml_file_info, conda_config_file_info
)
configuration_provider: EPConfigurationProvider = pm[EPConfigurationProvider]
rcc = Rcc(configuration_provider)
interpreter_id = str(package_yaml_file_info.file_path)
result = rcc.run_python_code_package_yaml(
"""
if __name__ == "__main__":
import sys
import json
import os
import time
info = {
"python_executable": sys.executable,
"python_environ": dict(os.environ),
}
json_contents = json.dumps(info, indent=4)
sys.stdout.write('JSON START>>')
sys.stdout.write(json_contents)
sys.stdout.write('<<JSON END')
sys.stdout.flush()
time.sleep(.5)
""",
conda_config_file_info.contents
if conda_config_file_info is not None
else None,
)
if not result.success:
raise RuntimeError(f"Unable to get env details. Error: {result.message}.")
json_contents: Optional[str] = result.result
if not json_contents:
raise RuntimeError(f"Unable to get output when getting environment.")
start = json_contents.find("JSON START>>")
end = json_contents.find("<<JSON END")
if start == -1 or end == -1:
raise RuntimeError(
f"Unable to find JSON START>> or <<JSON END in: {json_contents}."
)
start += len("JSON START>>")
json_contents = json_contents[start:end]
try:
json_dict: dict = json.loads(json_contents)
except:
raise RuntimeError(f"Error loading json: {json_contents}.")
root = str(package_yaml_file_info.file_path.parent)
environment: dict = {}
for _activity_name, activity in rcc.iter_package_yaml_activities(
package_yaml_file_info.yaml_contents
):
activity_root = activity.get("activityRoot")
if activity_root:
if os.path.isabs(activity_root):
root = activity_root
else:
# relative path: let's make it absolute
parent = str(package_yaml_file_info.file_path.parent)
root = os.path.abspath(os.path.join(parent, activity_root))
environment = activity.get("environment")
# i.e.: Use just the first activity (is there a better way to do this?)
break
additional_pythonpath_entries: List[str] = []
for key, value in environment.items():
if key.lower() == "pythonpath":
# Note: we currently deal only with pythonpath entries, so, this
# may not be ideal when really running an activity.
if isinstance(value, list):
for v in value:
additional_pythonpath_entries.append(os.path.join(root, str(v)))
self.info: IInterpreterInfo = DefaultInterpreterInfo(
interpreter_id,
json_dict["python_executable"],
json_dict["python_environ"],
additional_pythonpath_entries,
)
def _obtain_mtime(
self,
package_yaml_file_info: _CachedFileInfo,
conda_config_file_info: Optional[_CachedFileInfo],
) -> _CachedInterpreterMTime:
return (
package_yaml_file_info.mtime_info,
conda_config_file_info.mtime_info if conda_config_file_info else None,
)
def is_cache_valid(
self,
package_yaml_file_info: _CachedFileInfo,
conda_config_file_info: Optional[_CachedFileInfo],
) -> bool:
return self._mtime == self._obtain_mtime(
package_yaml_file_info, conda_config_file_info
)
class _CacheInfo(object):
"""
As a new instance of the RobocodeResolveInterpreter is created for each call,
we need to store cached info outside it.
"""
_cached_file_info: Dict[Path, _CachedFileInfo] = {}
_cached_interpreter_info: Dict[Path, _CachedInterpreterInfo] = {}
_cache_hit_files = 0 # Just for testing
_cache_hit_interpreter = 0 # Just for testing
@classmethod
def get_file_info(cls, file_path: Path) -> _CachedFileInfo:
file_info = cls._cached_file_info.get(file_path)
if file_info is not None and file_info.is_cache_valid():
cls._cache_hit_files += 1
return file_info
# If it got here, it's not cached or the cache doesn't match.
file_info = _CachedFileInfo(file_path)
cls._cached_file_info[file_path] = file_info
return file_info
@classmethod
def get_interpreter_info(
cls,
package_yaml_file_info: _CachedFileInfo,
conda_config_file_info: Optional[_CachedFileInfo],
pm: PluginManager,
) -> IInterpreterInfo:
interpreter_info = cls._cached_interpreter_info.get(
package_yaml_file_info.file_path
)
if interpreter_info is not None and interpreter_info.is_cache_valid(
package_yaml_file_info, conda_config_file_info
):
_CacheInfo._cache_hit_interpreter += 1
return interpreter_info.info
from robocode_ls_core.progress_report import progress_context
from robotframework_ls.ep_providers import EPEndPointProvider
endpoint = pm[EPEndPointProvider].endpoint
with progress_context(endpoint, "Obtain env for package.yaml", dir_cache=None):
# If it got here, it's not cached or the cache doesn't match.
# This may take a while...
interpreter_info = cls._cached_interpreter_info[
package_yaml_file_info.file_path
] = _CachedInterpreterInfo(
package_yaml_file_info, conda_config_file_info, pm
)
return interpreter_info.info
class RobocodeResolveInterpreter(object):
"""
Resolves the interpreter based on the package.yaml found.
The expected structure is something as:
{
'activities': {
'Web scraper': {
'output': 'output',
'activityRoot': '.',
'environment': {
'pythonPath': ['variables', 'libraries', 'resources']
},
'action': {
'command': [
'python',
'-m',
'robot',
'-d',
'output',
'--logtitle',
'Task log',
'./tasks/*.robot'
]
}
}
},
'condaConfig': 'config/conda.yaml'
}
"""
def __init__(self, weak_pm: "weakref.ReferenceType[PluginManager]"):
self._pm = weak_pm
@implements(EPResolveInterpreter.get_interpreter_info_for_doc_uri)
def get_interpreter_info_for_doc_uri(self, doc_uri) -> Optional[IInterpreterInfo]:
try:
pm = self._pm()
if pm is None:
log.critical("Did not expect PluginManager to be None at this point.")
return None
from robotframework_ls.ep_providers import (
EPConfigurationProvider,
EPEndPointProvider,
)
# Check that our requirements are there.
pm[EPConfigurationProvider]
pm[EPEndPointProvider]
fs_path = Path(uris.to_fs_path(doc_uri))
for path in fs_path.parents:
package_yaml: Path = path / "package.yaml"
if package_yaml.exists():
break
else:
# i.e.: Could not find any package.yaml in the structure.
log.debug("Could not find package yaml for: %s", fs_path)
return None
# Ok, we have the package_yaml, so, we should be able to run RCC with it.
package_yaml_file_info = _CacheInfo.get_file_info(package_yaml)
yaml_contents = package_yaml_file_info.yaml_contents
if not isinstance(yaml_contents, dict):
raise AssertionError(f"Expected dict as root in: {package_yaml}")
conda_config = yaml_contents.get("condaConfig")
conda_config_file_info = None
if conda_config:
parent: Path = package_yaml.parent
conda_config_path = parent.joinpath(conda_config)
if conda_config_path.exists():
conda_config_file_info = _CacheInfo.get_file_info(conda_config_path)
return _CacheInfo.get_interpreter_info(
package_yaml_file_info, conda_config_file_info, pm
)
except:
log.exception(f"Error getting interpreter info for: {doc_uri}")
return None
def __typecheckself__(self) -> None:
from robocode_ls_core.protocols import check_implements
_: EPResolveInterpreter = check_implements(self)
def register_plugins(pm: PluginManager):
pm.register(
EPResolveInterpreter,
RobocodeResolveInterpreter,
kwargs={"weak_pm": weakref.ref(pm)},
)
| [
"fabiofz@gmail.com"
] | fabiofz@gmail.com |
5b9fad623f650cdb47cb01210f6c4dfeb85a775b | b37b39ed5f4af5bf1455d200976b7e83b2888cab | /src/sensors_apps/workers/event_logger.py | d1b3143663554d2da3ce4e683bbd7d54d39f86f7 | [] | no_license | jldupont/sensors-apps | 71c67ce3a5226411685bd89ad4dd65590ba455ed | cdc930ed18c4a6ab0c55ceea24d765a00b649a0e | refs/heads/master | 2021-01-25T03:54:26.022483 | 2010-03-03T20:24:36 | 2010-03-03T20:24:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,326 | py | """
@author: jldupont
Created on 2010-03-03
"""
__all__=[]
from system.mbus import Bus
from system.worker import WorkerClass, WorkerManager
from system.amqp import AMQPCommRx
class AmqpListenerAgent(WorkerClass):
"""
"""
EXCH="org.sensors"
RKEY="state.io.#"
def __init__(self, config):
WorkerClass.__init__(self, "AmqpListenerAgent")
self.comm=None
self.config=config
def doRun(self):
self.comm=AMQPCommRx(self.config, self.EXCH, rkey=self.RKEY, rq="q.sensors.listener")
self.comm.connect()
while not self.quit and self.comm.isOk():
self.comm.wait()
self.processMsgQueue()
print "AmqpListenerAgent: exiting"
def processMsgQueue(self):
while True:
mtype, rkey, mdata=self.comm.gMsg()
if mtype is None:
break
self.txMsg(rkey, mdata)
## -------------------------------------------------------------------------
## -------------------------------------------------------------------------
class Manager(object):
""" Manages the lifecyle of the Listener Agents
"""
RETRY_INTERVAL=4*10
def __init__(self):
self.currentWorker=None
self.cpc=0
self.last_spawn_count=0
def _hconfig(self, config):
self.config=config
self.update()
def update(self):
""" A new worker will get spawn on the next 'poll'
"""
if self.currentWorker is not None:
WorkerManager.terminate(self.currentWorker)
self.currentWorker=None
def maybeSpawn(self):
if self.currentWorker is None:
delta=self.cpc - self.last_spawn_count
if delta >= self.RETRY_INTERVAL or self.last_spawn_count==0:
self.currentWorker=AmqpListenerAgent(self.config)
self.currentWorker.start()
self.last_spawn_count=self.cpc
def _hpoll(self, pc):
self.cpc=pc
if not self.config:
Bus.publish(self, "%config-amqp?")
self.maybeSpawn()
if self.currentWorker is not None:
if not self.currentWorker.is_alive():
Bus.publish(self, "%conn-error", "warning", "Connection to AMQP broker failed")
del self.currentWorker
self.currentWorker = None
if self.currentWorker is not None:
self.processMsgQueue()
def processMsgQueue(self):
while True:
msg=self.currentWorker.rxFromWorker()
if msg is None:
break
try:
mtype=msg.pop(0)
mdata=msg.pop(0)
except:
Bus.publish(self, "%llog", "%msg-error", "error", "Error whilst decoding message from AMQP exchange 'org.sensors' ")
continue
## e.g. "state.io.din"
Bus.publish(self, mtype, mdata)
def _hquit(self):
self.update()
_mng=Manager()
Bus.subscribe("%config-amqp", _mng._hconfig)
Bus.subscribe("%poll", _mng._hpoll)
Bus.subscribe("%quit", _mng._hquit) | [
"github@jldupont.com"
] | github@jldupont.com |
5a0cca812ad7e8c9c393f058d8056c663951a197 | 8acffb8c4ddca5bfef910e58d3faa0e4de83fce8 | /ml-flask/Lib/site-packages/pandas/tests/arrays/test_array.py | 5c0cf0147c8d8dd41430888dd8c4ec491f63c637 | [
"MIT"
] | permissive | YaminiHP/SimilitudeApp | 8cbde52caec3c19d5fa73508fc005f38f79b8418 | 005c59894d8788c97be16ec420c0a43aaec99b80 | refs/heads/master | 2023-06-27T00:03:00.404080 | 2021-07-25T17:51:27 | 2021-07-25T17:51:27 | 389,390,951 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 130 | py | version https://git-lfs.github.com/spec/v1
oid sha256:c10e1eac29b51da09a84897d1e569c85604c251b75ab5162ca2142102cf54674
size 12601
| [
"yamprakash130@gmail.com"
] | yamprakash130@gmail.com |
5232c8c1d73ead0f086fcec3d0368fe12341dd5c | 6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4 | /mrrKngM2fqDEDMXtS_0.py | f5c5ee5871ccd936356d15e43beec5e361c917a5 | [] | no_license | daniel-reich/ubiquitous-fiesta | 26e80f0082f8589e51d359ce7953117a3da7d38c | 9af2700dbe59284f5697e612491499841a6c126f | refs/heads/master | 2023-04-05T06:40:37.328213 | 2021-04-06T20:17:44 | 2021-04-06T20:17:44 | 355,318,759 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 281 | py |
def can_patch(bridge, planks):
b = ''.join(str(i) for i in bridge)
holes = [len(i) for i in b.split('1')]
if all(i<=1 for i in holes):
return True
elif all(planks.count(i-1) + planks.count(i)>=holes.count(i) for i in holes if i>1):
return True
return False
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
9764ca21187a78fb9872c99429d46e64c77f15ee | f62e4c46fb0f98879fb63977fa29631b02e3928c | /15 задание/Неравенства_009.py | b2bc0ff150714baa3cfe5be28d8e3cd6b0939094 | [] | no_license | SeveralCamper/USE-2020-2021 | c34f4d7a2c3e0f51529141781f523b63242a835d | ac1122649f2fd431a91af5dda5662492e2565109 | refs/heads/master | 2023-09-03T13:36:05.822568 | 2021-10-27T12:54:10 | 2021-10-27T12:54:10 | 392,303,515 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 627 | py | # Задание 15 № 16045
# Для какого наибольшего целого неотрицательного числа A выражение
# (y + 2x ≠ 48) ∨ (A < x) ∨ (A < y)
# тождественно истинно, то есть принимает значение 1 при любых целых неотрицательных x и y?
A = 1
while True:
for x in range(1,1000):
for y in range(1, 1000):
if not((y + 2 * x != 48) or (A < x) or (A < y)):
break
else:
continue
break
else:
print(A)
A += 1
# Ответ: 15
| [
"mikha.alkhimovich@mail.ru"
] | mikha.alkhimovich@mail.ru |
8cf5c5e87d3b0865cc7708955ff71c51825be678 | 83de24182a7af33c43ee340b57755e73275149ae | /aliyun-python-sdk-objectdet/aliyunsdkobjectdet/request/v20191230/DetectMainBodyRequest.py | 9654ad3449a62ce09152cd83d53d2006f24f311a | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-python-sdk | 4436ca6c57190ceadbc80f0b1c35b1ab13c00c7f | 83fd547946fd6772cf26f338d9653f4316c81d3c | refs/heads/master | 2023-08-04T12:32:57.028821 | 2023-08-04T06:00:29 | 2023-08-04T06:00:29 | 39,558,861 | 1,080 | 721 | NOASSERTION | 2023-09-14T08:51:06 | 2015-07-23T09:39:45 | Python | UTF-8 | Python | false | false | 1,455 | py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from aliyunsdkcore.request import RpcRequest
from aliyunsdkobjectdet.endpoint import endpoint_data
class DetectMainBodyRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'objectdet', '2019-12-30', 'DetectMainBody')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_ImageURL(self): # String
return self.get_query_params().get('ImageURL')
def set_ImageURL(self, ImageURL): # String
self.add_query_param('ImageURL', ImageURL)
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
788d599d353ccd9b4e3f54de3dc812e97de6ad65 | 96e0dd08563b1f579992c14207d103ee80222b1b | /0408/MR_ACT_TIPS_CLOSE.py | dfa55827fd59522ce3b45c0fbef414e64f266327 | [] | no_license | tonygodspeed/pytest | 4030e21f3206e3c5cb58aac870e3a1a57cd6943d | 2e87b91c148ff6966096bb8b197c0a84f5a1e7e2 | refs/heads/master | 2020-04-02T13:14:20.811887 | 2018-10-24T09:00:57 | 2018-10-24T09:00:57 | 154,472,992 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,555 | py | #!/usr/bin/env python
# coding=utf8
from MR_BASE import *
reload(sys)
sys.setdefaultencoding("utf-8")
str_act = "ACT_TIPS_CLOSE"
class MR_ACT_TIPS_CLOSE(mr_base):
def __init__(self):
mt_type = [
{'key': 'DISVER', 'type': 's', 'mt': r'.*DISVER:' + common_def.MT_VALUE_INVALID_POSTFIX},
{'key': 'VER', 'type': 's', 'mt': r'VER:' + common_def.MT_VALUE_INVALID_POSTFIX},
{'key': 'CHID', 'type': 's', 'mt': r'CHID:' + common_def.MT_VALUE_INVALID_POSTFIX},
{'key': 'MAC', 'type': 's', 'mt': r'MAC:' + common_def.MT_VALUE_INVALID_POSTFIX},
{'key': 'MCID', 'type': 's', 'mt': r'MCID:' + common_def.MT_VALUE_INVALID_POSTFIX},
{'key': 'CFGVER', 'type': 's', 'mt': r'CFGVER:' + common_def.MT_VALUE_INVALID_POSTFIX},
{'key': 'tips_name', 'type': 's', 'mt': r'tips_name:' + common_def.MT_VALUE_VALID_POSTFIX},
{'key': 'ret', 'type': 'i', 'mt': r'ret:' + common_def.MT_VALUE_INVALID_POSTFIX},
{'key': 'append_info', 'type': 's', 'mt': r'append_info:' + common_def.MT_VALUE_VALID_POSTFIX},
]
mr_base.__init__(self, mt_type, str_act)
mr_obj = MR_ACT_TIPS_CLOSE()
if __name__ == '__main__':
test_str = r'03:12| [INFO]: <SRC:KWSHELLEXT_1.0.6.9051_MUSICDR8021PE|S:1012|PROD:KWSHELLEXT|DISVER:1.0.6.9077|OS:6.1.7601.2_Service Pack 1|PLAT:X64|VER:1.0.0.7|GID:71|CHID:MUSICDR8021PE|PN:rundll32.exe|MAC:F832E4A3AE08|UAC:0|ADMIN:1|MVER:MUSIC_8.5.2.0_P2T2|MCID:81018516|ST:1497888579|CFGVER:37|ACT:ACT_TIPS_CLOSE|tips_name:tips_competitor|ret:102|append_info:c_type=3|{}|U:>(175.43.235.16)TM:1497888194'
mr_obj.LocalTest(test_str)
pass
| [
"412291198@qq.com"
] | 412291198@qq.com |
81008f533429d7045665572e09452a271f10a008 | 1974b3e9c5f2f677833e1608a41281f377fd331c | /dltesthttp_xuyalin2/www/testcase/webservice/ts_ws_approval/auditApproval.py | a73408b64e960e90f654c5482b57e9b09ffce7b7 | [] | no_license | xyl00755/pythonLearning | ed0f540b61247c3560f347853da5886b2e2ba25d | c6aecff86ff34dcd7358d98201627ff84e9bf2cf | refs/heads/master | 2021-01-13T08:19:25.171016 | 2016-12-16T05:43:10 | 2016-12-16T05:43:10 | 71,764,553 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 21,211 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from www.api.webservice import *
from www.common.database import *
from www.common.excel import *
"""
0035.经销商管理员我的丹露审批
http://127.0.0.1:8280/mallws/mydl/approval/auditApproval.json
{
"token":"123", // 必须
"approvalId":"TAL9604920150102796", // 必须 审批id
"taskId":"123", // 必须 工作流id
"auditStatus":"1", // 必须 审批状态 0 同意 1 拒绝
"approvalReason":"123123" // 必须 审批理由
}
{
"code": 200,
"description": "执行成功!",
"model": {
"success": "0" // 0-成功 1-重复审批
},
"metadata": {
"type": 0,
"clazz": "cn.com.hd.mall.web.webservices.entity.BaseResponse"
}
}
参数校验:
/// 必须验证
auditStatus @NotNull @Pattern(regexp = "0|1")
approvalReason @NotNull @Size(min = 2, max = 300)
code说明:
100-token失效 200-成功 300-错误的角色(无权限) 400-非法的参数 500-服务器异常 600-重新登陆
param说明:
taskId为工作流id 列表接口中未审批的单子有这个id 已审批的单子没有 但是详情页面必须把taskId带过来 如果是已审批的单子 传递一个空字符串
"""
class auditApproval(unittest.TestCase):
UserShop=wsData('DealMager')
#经销商销售员
UserShop2=wsData('DealSaler')
#经销商采购员
UserShop6=wsData('DealBuyer')
#经销商配送员
UserShop4=wsData('DealSeder')
#经销商财务员
UserShop5=wsData('DealFiner')
UserShop3 = wsData('RegistTmlShop')
def setUp(self):
applyId=select_one('select apply_id from dlworkflow.dl_apply_terminal where terminal_tel=?',self.UserShop3.registerTel)
if applyId!=None:
update('delete from dlworkflow.act_hi_procinst where BUSINESS_KEY_=?',str(applyId.apply_id))
update('delete from dlworkflow.dl_apply_terminal where terminal_tel=?',self.UserShop3.registerTel)
#正确审批同意
def test_auditApproval_accept(self):
ws=webservice()
ws.login(self.UserShop.username,self.UserShop.password)
tmlRegist=ws.terminalRegistApprove(terminalLoginName=self.UserShop3.username,password=self.UserShop3.password,registerTel=self.UserShop3.registerTel,verificationCode='1111',invitationCode=self.UserShop.invitationCode,
terminalFullName=self.UserShop3.fullName,businessLicenseCode=self.UserShop3.busLicenseNum,storeTypeCode=self.UserShop3.storeTypeCode,terminalAreaProvinceCode=self.UserShop3.areaProvinceCode,
terminalAreaCityCode=self.UserShop3.areaCityCode,terminalAreaDistrictCode=self.UserShop3.areaDistrictCode,terminalAddress=self.UserShop3.localStreet)
self.assertEqual(tmlRegist.model['success'],'0')
self.assertEqual(tmlRegist.model['checkResult'],None)
getList=ws.getApprovalList(approvalStatus='0',page='1',rows='1')
approvid=getList.model['approvalList'][0]['approvalId']
taskid=getList.model['approvalList'][0]['taskId']
audit=ws.auditApproval(approvalId=approvid,taskId=taskid,auditStatus='0',approvalReason='')
self.assertEqual(audit.model['success'],'0')
selectSql=select_int('select count(*) from dluser.dl_user where user_account=?',self.UserShop3.username)
self.assertEqual(selectSql,1)
update('delete from dluser.dl_user where user_account=?',self.UserShop3.username)
update('delete from dlworkflow.act_hi_procinst where BUSINESS_KEY_=?',approvid)
update('delete from dlcompany.dl_biz_base_info where company_name=?',self.UserShop3.fullName)
#正确审批拒绝
def test_auditApproval_refuse(self):
ws=webservice()
ws.login(self.UserShop.username,self.UserShop.password)
tmlRegist=ws.terminalRegistApprove(terminalLoginName=self.UserShop3.username,password=self.UserShop3.password,registerTel=self.UserShop3.registerTel,verificationCode='1111',invitationCode=self.UserShop.invitationCode,
terminalFullName=self.UserShop3.fullName,businessLicenseCode=self.UserShop3.busLicenseNum,storeTypeCode=self.UserShop3.storeTypeCode,terminalAreaProvinceCode=self.UserShop3.areaProvinceCode,
terminalAreaCityCode=self.UserShop3.areaCityCode,terminalAreaDistrictCode=self.UserShop3.areaDistrictCode,terminalAddress=self.UserShop3.localStreet)
self.assertEqual(tmlRegist.model['success'],'0')
self.assertEqual(tmlRegist.model['checkResult'],None)
getList=ws.getApprovalList(approvalStatus='0',page='1',rows='1')
approvid=getList.model['approvalList'][0]['approvalId']
taskid=getList.model['approvalList'][0]['taskId']
audit=ws.auditApproval(approvalId=approvid,taskId=taskid,auditStatus='1',approvalReason='拒绝该终端店注册成功!')
self.assertEqual(audit.model['success'],'0')
selectSql=select_int('select count(*) from dluser.dl_user where user_account=?',self.UserShop3.username)
self.assertEqual(selectSql,0)
selectSql2=select_one('select * from dlworkflow.dl_apply_terminal where apply_id=?',approvid)
self.assertEqual(selectSql2.flow_status,'05')
update('delete from dlworkflow.act_hi_procinst where BUSINESS_KEY_=?',approvid)
#经销商销售员审批
def test_auditApproval_saler(self):
ws=webservice()
ws.login(self.UserShop.username,self.UserShop.password)
tmlRegist=ws.terminalRegistApprove(terminalLoginName=self.UserShop3.username,password=self.UserShop3.password,registerTel=self.UserShop3.registerTel,verificationCode='1111',invitationCode=self.UserShop.invitationCode,
terminalFullName=self.UserShop3.fullName,businessLicenseCode=self.UserShop3.busLicenseNum,storeTypeCode=self.UserShop3.storeTypeCode,terminalAreaProvinceCode=self.UserShop3.areaProvinceCode,
terminalAreaCityCode=self.UserShop3.areaCityCode,terminalAreaDistrictCode=self.UserShop3.areaDistrictCode,terminalAddress=self.UserShop3.localStreet)
self.assertEqual(tmlRegist.model['success'],'0')
self.assertEqual(tmlRegist.model['checkResult'],None)
getList=ws.getApprovalList(approvalStatus='0',page='1',rows='15')
approvid=getList.model['approvalList'][0]['approvalId']
taskid=getList.model['approvalList'][0]['taskId']
ws.login(self.UserShop2.username,self.UserShop2.password)
audit=ws.auditApproval(approvalId=approvid,taskId=taskid,auditStatus='1',approvalReason='拒绝该终端店注册成功!')
self.assertEqual(audit.code,300)
self.assertEqual(audit.description,'错误的权限!')
update('delete from dlworkflow.act_hi_procinst where BUSINESS_KEY_=?',approvid)
#经销商采购员审批
def test_auditApproval_buyer(self):
ws=webservice()
ws.login(self.UserShop.username,self.UserShop.password)
tmlRegist=ws.terminalRegistApprove(terminalLoginName=self.UserShop3.username,password=self.UserShop3.password,registerTel=self.UserShop3.registerTel,verificationCode='1111',invitationCode=self.UserShop.invitationCode,
terminalFullName=self.UserShop3.fullName,businessLicenseCode=self.UserShop3.busLicenseNum,storeTypeCode=self.UserShop3.storeTypeCode,terminalAreaProvinceCode=self.UserShop3.areaProvinceCode,
terminalAreaCityCode=self.UserShop3.areaCityCode,terminalAreaDistrictCode=self.UserShop3.areaDistrictCode,terminalAddress=self.UserShop3.localStreet)
self.assertEqual(tmlRegist.model['success'],'0')
self.assertEqual(tmlRegist.model['checkResult'],None)
getList=ws.getApprovalList(approvalStatus='0',page='1',rows='15')
approvid=getList.model['approvalList'][0]['approvalId']
taskid=getList.model['approvalList'][0]['taskId']
ws.login(self.UserShop6.username,self.UserShop6.password)
audit=ws.auditApproval(approvalId=approvid,taskId=taskid,auditStatus='1',approvalReason='拒绝该终端店注册成功!')
self.assertEqual(audit.code,300)
self.assertEqual(audit.description,'错误的权限!')
update('delete from dlworkflow.act_hi_procinst where BUSINESS_KEY_=?',approvid)
#经销商配送员审批
def test_auditApproval_seder(self):
ws=webservice()
ws.login(self.UserShop.username,self.UserShop.password)
tmlRegist=ws.terminalRegistApprove(terminalLoginName=self.UserShop3.username,password=self.UserShop3.password,registerTel=self.UserShop3.registerTel,verificationCode='1111',invitationCode=self.UserShop.invitationCode,
terminalFullName=self.UserShop3.fullName,businessLicenseCode=self.UserShop3.busLicenseNum,storeTypeCode=self.UserShop3.storeTypeCode,terminalAreaProvinceCode=self.UserShop3.areaProvinceCode,
terminalAreaCityCode=self.UserShop3.areaCityCode,terminalAreaDistrictCode=self.UserShop3.areaDistrictCode,terminalAddress=self.UserShop3.localStreet)
self.assertEqual(tmlRegist.model['success'],'0')
self.assertEqual(tmlRegist.model['checkResult'],None)
getList=ws.getApprovalList(approvalStatus='0',page='1',rows='15')
approvid=getList.model['approvalList'][0]['approvalId']
taskid=getList.model['approvalList'][0]['taskId']
ws.login(self.UserShop4.username,self.UserShop4.password)
audit=ws.auditApproval(approvalId=approvid,taskId=taskid,auditStatus='1',approvalReason='拒绝该终端店注册成功!')
self.assertEqual(audit.code,300)
self.assertEqual(audit.description,'错误的权限!')
update('delete from dlworkflow.act_hi_procinst where BUSINESS_KEY_=?',approvid)
#经销商财务员审批
def test_auditApproval_finer(self):
ws=webservice()
ws.login(self.UserShop.username,self.UserShop.password)
tmlRegist=ws.terminalRegistApprove(terminalLoginName=self.UserShop3.username,password=self.UserShop3.password,registerTel=self.UserShop3.registerTel,verificationCode='1111',invitationCode=self.UserShop.invitationCode,
terminalFullName=self.UserShop3.fullName,businessLicenseCode=self.UserShop3.busLicenseNum,storeTypeCode=self.UserShop3.storeTypeCode,terminalAreaProvinceCode=self.UserShop3.areaProvinceCode,
terminalAreaCityCode=self.UserShop3.areaCityCode,terminalAreaDistrictCode=self.UserShop3.areaDistrictCode,terminalAddress=self.UserShop3.localStreet)
self.assertEqual(tmlRegist.model['success'],'0')
self.assertEqual(tmlRegist.model['checkResult'],None)
getList=ws.getApprovalList(approvalStatus='0',page='1',rows='15')
approvid=getList.model['approvalList'][0]['approvalId']
taskid=getList.model['approvalList'][0]['taskId']
ws.login(self.UserShop5.username,self.UserShop5.password)
audit=ws.auditApproval(approvalId=approvid,taskId=taskid,auditStatus='1',approvalReason='拒绝该终端店注册成功!')
self.assertEqual(audit.code,300)
self.assertEqual(audit.description,'错误的权限!')
update('delete from dlworkflow.act_hi_procinst where BUSINESS_KEY_=?',approvid)
#重复审批
def test_auditApproval_repeat(self):
ws=webservice()
ws.login(self.UserShop.username,self.UserShop.password)
tmlRegist=ws.terminalRegistApprove(terminalLoginName=self.UserShop3.username,password=self.UserShop3.password,registerTel=self.UserShop3.registerTel,verificationCode='1111',invitationCode=self.UserShop.invitationCode,
terminalFullName=self.UserShop3.fullName,businessLicenseCode=self.UserShop3.busLicenseNum,storeTypeCode=self.UserShop3.storeTypeCode,terminalAreaProvinceCode=self.UserShop3.areaProvinceCode,
terminalAreaCityCode=self.UserShop3.areaCityCode,terminalAreaDistrictCode=self.UserShop3.areaDistrictCode,terminalAddress=self.UserShop3.localStreet)
self.assertEqual(tmlRegist.model['success'],'0')
self.assertEqual(tmlRegist.model['checkResult'],None)
getList=ws.getApprovalList(approvalStatus='0',page='1',rows='1')
approvid=getList.model['approvalList'][0]['approvalId']
taskid=getList.model['approvalList'][0]['taskId']
audit=ws.auditApproval(approvalId=approvid,taskId=taskid,auditStatus='1',approvalReason='拒绝该终端店注册成功!')
self.assertEqual(audit.model['success'],'0')
selectSql=select_int('select count(*) from dluser.dl_user where user_account=?',self.UserShop3.username)
self.assertEqual(selectSql,0)
selectSql2=select_one('select * from dlworkflow.dl_apply_terminal where apply_id=?',approvid)
self.assertEqual(selectSql2.flow_status,'05')
audit=ws.auditApproval(approvalId=approvid,taskId=taskid,auditStatus='1',approvalReason='拒绝该终端店注册成功!')
self.assertEqual(audit.model['success'],'1')
update('delete from dlworkflow.act_hi_procinst where BUSINESS_KEY_=?',approvid)
#approvalId为空
def test_auditApproval_approvalIdNull(self):
ws=webservice()
ws.login(self.UserShop.username,self.UserShop.password)
tmlRegist=ws.terminalRegistApprove(terminalLoginName=self.UserShop3.username,password=self.UserShop3.password,registerTel=self.UserShop3.registerTel,verificationCode='1111',invitationCode=self.UserShop.invitationCode,
terminalFullName=self.UserShop3.fullName,businessLicenseCode=self.UserShop3.busLicenseNum,storeTypeCode=self.UserShop3.storeTypeCode,terminalAreaProvinceCode=self.UserShop3.areaProvinceCode,
terminalAreaCityCode=self.UserShop3.areaCityCode,terminalAreaDistrictCode=self.UserShop3.areaDistrictCode,terminalAddress=self.UserShop3.localStreet)
self.assertEqual(tmlRegist.model['success'],'0')
self.assertEqual(tmlRegist.model['checkResult'],None)
getList=ws.getApprovalList(approvalStatus='0',page='1',rows='1')
approvid=getList.model['approvalList'][0]['approvalId']
taskid=getList.model['approvalList'][0]['taskId']
audit=ws.auditApproval(approvalId='',taskId=taskid,auditStatus='1',approvalReason='拒绝该终端店注册成功!')
self.assertEqual(audit.code,500)
self.assertEqual(audit.description,'服务器异常!')
update('delete from dlworkflow.act_hi_procinst where BUSINESS_KEY_=?',approvid)
#审批理由位数等于2
def test_auditApproval_reasonMin(self):
ws=webservice()
ws.login(self.UserShop.username,self.UserShop.password)
tmlRegist=ws.terminalRegistApprove(terminalLoginName=self.UserShop3.username,password=self.UserShop3.password,registerTel=self.UserShop3.registerTel,verificationCode='1111',invitationCode=self.UserShop.invitationCode,
terminalFullName=self.UserShop3.fullName,businessLicenseCode=self.UserShop3.busLicenseNum,storeTypeCode=self.UserShop3.storeTypeCode,terminalAreaProvinceCode=self.UserShop3.areaProvinceCode,
terminalAreaCityCode=self.UserShop3.areaCityCode,terminalAreaDistrictCode=self.UserShop3.areaDistrictCode,terminalAddress=self.UserShop3.localStreet)
self.assertEqual(tmlRegist.model['success'],'0')
self.assertEqual(tmlRegist.model['checkResult'],None)
getList=ws.getApprovalList(approvalStatus='0',page='1',rows='1')
approvid=getList.model['approvalList'][0]['approvalId']
taskid=getList.model['approvalList'][0]['taskId']
audit=ws.auditApproval(approvalId=approvid,taskId=taskid,auditStatus='1',approvalReason='拒绝')
self.assertEqual(audit.model['success'],'0')
selectSql=select_int('select count(*) from dluser.dl_user where user_account=?',self.UserShop3.username)
self.assertEqual(selectSql,0)
selectSql2=select_one('select * from dlworkflow.dl_apply_terminal where apply_id=?',approvid)
self.assertEqual(selectSql2.flow_status,'05')
update('delete from dlworkflow.act_hi_procinst where BUSINESS_KEY_=?',approvid)
#审批理由位数小于2
#审批理由大于30
#审批理由为空(拒绝审批理由为空也可以审批通过)
def test_auditApproval_reasonNull(self):
ws=webservice()
ws.login(self.UserShop.username,self.UserShop.password)
tmlRegist=ws.terminalRegistApprove(terminalLoginName=self.UserShop3.username,password=self.UserShop3.password,registerTel=self.UserShop3.registerTel,verificationCode='1111',invitationCode=self.UserShop.invitationCode,
terminalFullName=self.UserShop3.fullName,businessLicenseCode=self.UserShop3.busLicenseNum,storeTypeCode=self.UserShop3.storeTypeCode,terminalAreaProvinceCode=self.UserShop3.areaProvinceCode,
terminalAreaCityCode=self.UserShop3.areaCityCode,terminalAreaDistrictCode=self.UserShop3.areaDistrictCode,terminalAddress=self.UserShop3.localStreet)
self.assertEqual(tmlRegist.model['success'],'0')
self.assertEqual(tmlRegist.model['checkResult'],None)
getList=ws.getApprovalList(approvalStatus='0',page='1',rows='1')
approvid=getList.model['approvalList'][0]['approvalId']
taskid=getList.model['approvalList'][0]['taskId']
audit=ws.auditApproval(approvalId=approvid,taskId=taskid,auditStatus='1',approvalReason='')
self.assertEqual(audit.model['success'],'0')
selectSql=select_int('select count(*) from dluser.dl_user where user_account=?',self.UserShop3.username)
self.assertEqual(selectSql,0)
selectSql2=select_one('select * from dlworkflow.dl_apply_terminal where apply_id=?',approvid)
self.assertEqual(selectSql2.flow_status,'05')
update('delete from dlworkflow.act_hi_procinst where BUSINESS_KEY_=?',approvid)
#审批理由等于30
def test_auditApproval_reasonMax(self):
ws=webservice()
ws.login(self.UserShop.username,self.UserShop.password)
tmlRegist=ws.terminalRegistApprove(terminalLoginName=self.UserShop3.username,password=self.UserShop3.password,registerTel=self.UserShop3.registerTel,verificationCode='1111',invitationCode=self.UserShop.invitationCode,
terminalFullName=self.UserShop3.fullName,businessLicenseCode=self.UserShop3.busLicenseNum,storeTypeCode=self.UserShop3.storeTypeCode,terminalAreaProvinceCode=self.UserShop3.areaProvinceCode,
terminalAreaCityCode=self.UserShop3.areaCityCode,terminalAreaDistrictCode=self.UserShop3.areaDistrictCode,terminalAddress=self.UserShop3.localStreet)
self.assertEqual(tmlRegist.model['success'],'0')
self.assertEqual(tmlRegist.model['checkResult'],None)
getList=ws.getApprovalList(approvalStatus='0',page='1',rows='1')
approvid=getList.model['approvalList'][0]['approvalId']
taskid=getList.model['approvalList'][0]['taskId']
audit=ws.auditApproval(approvalId=approvid,taskId=taskid,auditStatus='1',approvalReason='拒绝')
self.assertEqual(audit.model['success'],'0')
selectSql=select_int('select count(*) from dluser.dl_user where user_account=?',self.UserShop3.username)
self.assertEqual(selectSql,0)
selectSql2=select_one('select * from dlworkflow.dl_apply_terminal where apply_id=?',approvid)
self.assertEqual(selectSql2.flow_status,'05')
update('delete from dlworkflow.act_hi_procinst where BUSINESS_KEY_=?',approvid)
def tearDown(self):
applyId=select_one('select apply_id from dlworkflow.dl_apply_terminal where terminal_tel=?',self.UserShop3.registerTel)
if applyId!=None:
update('delete from dlworkflow.act_hi_procinst where BUSINESS_KEY_=?',str(applyId.apply_id))
update('delete from dlworkflow.dl_apply_terminal where terminal_tel=?',self.UserShop3.registerTel)
def suite():
suite=unittest.TestSuite()
suite.addTest(auditApproval("test_auditApproval_accept"))
suite.addTest(auditApproval("test_auditApproval_refuse"))
suite.addTest(auditApproval("test_auditApproval_saler"))
suite.addTest(auditApproval("test_auditApproval_buyer"))
suite.addTest(auditApproval("test_auditApproval_seder"))
suite.addTest(auditApproval("test_auditApproval_finer"))
suite.addTest(auditApproval("test_auditApproval_repeat"))
suite.addTest(auditApproval("test_auditApproval_approvalIdNull"))
suite.addTest(auditApproval("test_auditApproval_reasonMin"))
suite.addTest(auditApproval("test_auditApproval_reasonNull"))
suite.addTest(auditApproval("test_auditApproval_reasonMax"))
return suite | [
"xuyalin@danlu.com"
] | xuyalin@danlu.com |
4c309848f6269853d2f64a8adb47f488690b6cf5 | 55f76a8ffb9062f6553e3019e1bd9898c6841ee8 | /qa/rpc-tests/pruning.py | 0ac7cd4119955d124924e0c12c0d97e1e5ee1e5e | [
"MIT"
] | permissive | mirzaei-ce/core-tabit | 1c966183d5e35ac5210a122dfabf3b1a6071def5 | f4ae2cb3a1026ce0670751f5d98e5eee91097468 | refs/heads/master | 2021-08-14T18:29:45.166649 | 2017-11-16T13:26:30 | 2017-11-16T13:26:30 | 110,974,552 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,542 | py | #!/usr/bin/env python2
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test pruning code
# ********
# WARNING:
# This test uses 4GB of disk space.
# This test takes 30 mins or more (up to 2 hours)
# ********
from test_framework.test_framework import TabitTestFramework
from test_framework.util import *
def calc_usage(blockdir):
return sum(os.path.getsize(blockdir+f) for f in os.listdir(blockdir) if os.path.isfile(blockdir+f))/(1024*1024)
class PruneTest(TabitTestFramework):
def __init__(self):
self.utxo = []
self.address = ["",""]
self.txouts = gen_return_txouts()
def setup_chain(self):
print("Initializing test directory "+self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 3)
def setup_network(self):
self.nodes = []
self.is_network_split = False
# Create nodes 0 and 1 to mine
self.nodes.append(start_node(0, self.options.tmpdir, ["-debug","-maxreceivebuffer=20000","-blockmaxsize=999000", "-checkblocks=5"], timewait=900))
self.nodes.append(start_node(1, self.options.tmpdir, ["-debug","-maxreceivebuffer=20000","-blockmaxsize=999000", "-checkblocks=5"], timewait=900))
# Create node 2 to test pruning
self.nodes.append(start_node(2, self.options.tmpdir, ["-debug","-maxreceivebuffer=20000","-prune=550"], timewait=900))
self.prunedir = self.options.tmpdir+"/node2/regtest/blocks/"
self.address[0] = self.nodes[0].getnewaddress()
self.address[1] = self.nodes[1].getnewaddress()
# Determine default relay fee
self.relayfee = self.nodes[0].getnetworkinfo()["relayfee"]
connect_nodes(self.nodes[0], 1)
connect_nodes(self.nodes[1], 2)
connect_nodes(self.nodes[2], 0)
sync_blocks(self.nodes[0:3])
def create_big_chain(self):
# Start by creating some coinbases we can spend later
self.nodes[1].generate(200)
sync_blocks(self.nodes[0:2])
self.nodes[0].generate(150)
# Then mine enough full blocks to create more than 550MB of data
for i in xrange(645):
self.mine_full_block(self.nodes[0], self.address[0])
sync_blocks(self.nodes[0:3])
def test_height_min(self):
if not os.path.isfile(self.prunedir+"blk00000.dat"):
raise AssertionError("blk00000.dat is missing, pruning too early")
print "Success"
print "Though we're already using more than 550MB, current usage:", calc_usage(self.prunedir)
print "Mining 25 more blocks should cause the first block file to be pruned"
# Pruning doesn't run until we're allocating another chunk, 20 full blocks past the height cutoff will ensure this
for i in xrange(25):
self.mine_full_block(self.nodes[0],self.address[0])
waitstart = time.time()
while os.path.isfile(self.prunedir+"blk00000.dat"):
time.sleep(0.1)
if time.time() - waitstart > 10:
raise AssertionError("blk00000.dat not pruned when it should be")
print "Success"
usage = calc_usage(self.prunedir)
print "Usage should be below target:", usage
if (usage > 550):
raise AssertionError("Pruning target not being met")
def create_chain_with_staleblocks(self):
# Create stale blocks in manageable sized chunks
print "Mine 24 (stale) blocks on Node 1, followed by 25 (main chain) block reorg from Node 0, for 12 rounds"
for j in xrange(12):
# Disconnect node 0 so it can mine a longer reorg chain without knowing about node 1's soon-to-be-stale chain
# Node 2 stays connected, so it hears about the stale blocks and then reorg's when node0 reconnects
# Stopping node 0 also clears its mempool, so it doesn't have node1's transactions to accidentally mine
stop_node(self.nodes[0],0)
self.nodes[0]=start_node(0, self.options.tmpdir, ["-debug","-maxreceivebuffer=20000","-blockmaxsize=999000", "-checkblocks=5"], timewait=900)
# Mine 24 blocks in node 1
self.utxo = self.nodes[1].listunspent()
for i in xrange(24):
if j == 0:
self.mine_full_block(self.nodes[1],self.address[1])
else:
self.nodes[1].generate(1) #tx's already in mempool from previous disconnects
# Reorg back with 25 block chain from node 0
self.utxo = self.nodes[0].listunspent()
for i in xrange(25):
self.mine_full_block(self.nodes[0],self.address[0])
# Create connections in the order so both nodes can see the reorg at the same time
connect_nodes(self.nodes[1], 0)
connect_nodes(self.nodes[2], 0)
sync_blocks(self.nodes[0:3])
print "Usage can be over target because of high stale rate:", calc_usage(self.prunedir)
def reorg_test(self):
# Node 1 will mine a 300 block chain starting 287 blocks back from Node 0 and Node 2's tip
# This will cause Node 2 to do a reorg requiring 288 blocks of undo data to the reorg_test chain
# Reboot node 1 to clear its mempool (hopefully make the invalidate faster)
# Lower the block max size so we don't keep mining all our big mempool transactions (from disconnected blocks)
stop_node(self.nodes[1],1)
self.nodes[1]=start_node(1, self.options.tmpdir, ["-debug","-maxreceivebuffer=20000","-blockmaxsize=5000", "-checkblocks=5", "-disablesafemode"], timewait=900)
height = self.nodes[1].getblockcount()
print "Current block height:", height
invalidheight = height-287
badhash = self.nodes[1].getblockhash(invalidheight)
print "Invalidating block at height:",invalidheight,badhash
self.nodes[1].invalidateblock(badhash)
# We've now switched to our previously mined-24 block fork on node 1, but thats not what we want
# So invalidate that fork as well, until we're on the same chain as node 0/2 (but at an ancestor 288 blocks ago)
mainchainhash = self.nodes[0].getblockhash(invalidheight - 1)
curhash = self.nodes[1].getblockhash(invalidheight - 1)
while curhash != mainchainhash:
self.nodes[1].invalidateblock(curhash)
curhash = self.nodes[1].getblockhash(invalidheight - 1)
assert(self.nodes[1].getblockcount() == invalidheight - 1)
print "New best height", self.nodes[1].getblockcount()
# Reboot node1 to clear those giant tx's from mempool
stop_node(self.nodes[1],1)
self.nodes[1]=start_node(1, self.options.tmpdir, ["-debug","-maxreceivebuffer=20000","-blockmaxsize=5000", "-checkblocks=5", "-disablesafemode"], timewait=900)
print "Generating new longer chain of 300 more blocks"
self.nodes[1].generate(300)
print "Reconnect nodes"
connect_nodes(self.nodes[0], 1)
connect_nodes(self.nodes[2], 1)
sync_blocks(self.nodes[0:3])
print "Verify height on node 2:",self.nodes[2].getblockcount()
print "Usage possibly still high bc of stale blocks in block files:", calc_usage(self.prunedir)
print "Mine 220 more blocks so we have requisite history (some blocks will be big and cause pruning of previous chain)"
self.nodes[0].generate(220) #node 0 has many large tx's in its mempool from the disconnects
sync_blocks(self.nodes[0:3])
usage = calc_usage(self.prunedir)
print "Usage should be below target:", usage
if (usage > 550):
raise AssertionError("Pruning target not being met")
return invalidheight,badhash
def reorg_back(self):
# Verify that a block on the old main chain fork has been pruned away
try:
self.nodes[2].getblock(self.forkhash)
raise AssertionError("Old block wasn't pruned so can't test redownload")
except JSONRPCException as e:
print "Will need to redownload block",self.forkheight
# Verify that we have enough history to reorg back to the fork point
# Although this is more than 288 blocks, because this chain was written more recently
# and only its other 299 small and 220 large block are in the block files after it,
# its expected to still be retained
self.nodes[2].getblock(self.nodes[2].getblockhash(self.forkheight))
first_reorg_height = self.nodes[2].getblockcount()
curchainhash = self.nodes[2].getblockhash(self.mainchainheight)
self.nodes[2].invalidateblock(curchainhash)
goalbestheight = self.mainchainheight
goalbesthash = self.mainchainhash2
# As of 0.10 the current block download logic is not able to reorg to the original chain created in
# create_chain_with_stale_blocks because it doesn't know of any peer thats on that chain from which to
# redownload its missing blocks.
# Invalidate the reorg_test chain in node 0 as well, it can successfully switch to the original chain
# because it has all the block data.
# However it must mine enough blocks to have a more work chain than the reorg_test chain in order
# to trigger node 2's block download logic.
# At this point node 2 is within 288 blocks of the fork point so it will preserve its ability to reorg
if self.nodes[2].getblockcount() < self.mainchainheight:
blocks_to_mine = first_reorg_height + 1 - self.mainchainheight
print "Rewind node 0 to prev main chain to mine longer chain to trigger redownload. Blocks needed:", blocks_to_mine
self.nodes[0].invalidateblock(curchainhash)
assert(self.nodes[0].getblockcount() == self.mainchainheight)
assert(self.nodes[0].getbestblockhash() == self.mainchainhash2)
goalbesthash = self.nodes[0].generate(blocks_to_mine)[-1]
goalbestheight = first_reorg_height + 1
print "Verify node 2 reorged back to the main chain, some blocks of which it had to redownload"
waitstart = time.time()
while self.nodes[2].getblockcount() < goalbestheight:
time.sleep(0.1)
if time.time() - waitstart > 900:
raise AssertionError("Node 2 didn't reorg to proper height")
assert(self.nodes[2].getbestblockhash() == goalbesthash)
# Verify we can now have the data for a block previously pruned
assert(self.nodes[2].getblock(self.forkhash)["height"] == self.forkheight)
def mine_full_block(self, node, address):
# Want to create a full block
# We'll generate a 66k transaction below, and 14 of them is close to the 1MB block limit
for j in xrange(14):
if len(self.utxo) < 14:
self.utxo = node.listunspent()
inputs=[]
outputs = {}
t = self.utxo.pop()
inputs.append({ "txid" : t["txid"], "vout" : t["vout"]})
remchange = t["amount"] - 100*self.relayfee # Fee must be above min relay rate for 66kb tx
outputs[address]=remchange
# Create a basic transaction that will send change back to ourself after account for a fee
# And then insert the 128 generated transaction outs in the middle rawtx[92] is where the #
# of txouts is stored and is the only thing we overwrite from the original transaction
rawtx = node.createrawtransaction(inputs, outputs)
newtx = rawtx[0:92]
newtx = newtx + self.txouts
newtx = newtx + rawtx[94:]
# Appears to be ever so slightly faster to sign with SIGHASH_NONE
signresult = node.signrawtransaction(newtx,None,None,"NONE")
txid = node.sendrawtransaction(signresult["hex"], True)
# Mine a full sized block which will be these transactions we just created
node.generate(1)
def run_test(self):
print "Warning! This test requires 4GB of disk space and takes over 30 mins (up to 2 hours)"
print "Mining a big blockchain of 995 blocks"
self.create_big_chain()
# Chain diagram key:
# * blocks on main chain
# +,&,$,@ blocks on other forks
# X invalidated block
# N1 Node 1
#
# Start by mining a simple chain that all nodes have
# N0=N1=N2 **...*(995)
print "Check that we haven't started pruning yet because we're below PruneAfterHeight"
self.test_height_min()
# Extend this chain past the PruneAfterHeight
# N0=N1=N2 **...*(1020)
print "Check that we'll exceed disk space target if we have a very high stale block rate"
self.create_chain_with_staleblocks()
# Disconnect N0
# And mine a 24 block chain on N1 and a separate 25 block chain on N0
# N1=N2 **...*+...+(1044)
# N0 **...**...**(1045)
#
# reconnect nodes causing reorg on N1 and N2
# N1=N2 **...*(1020) *...**(1045)
# \
# +...+(1044)
#
# repeat this process until you have 12 stale forks hanging off the
# main chain on N1 and N2
# N0 *************************...***************************(1320)
#
# N1=N2 **...*(1020) *...**(1045) *.. ..**(1295) *...**(1320)
# \ \ \
# +...+(1044) &.. $...$(1319)
# Save some current chain state for later use
self.mainchainheight = self.nodes[2].getblockcount() #1320
self.mainchainhash2 = self.nodes[2].getblockhash(self.mainchainheight)
print "Check that we can survive a 288 block reorg still"
(self.forkheight,self.forkhash) = self.reorg_test() #(1033, )
# Now create a 288 block reorg by mining a longer chain on N1
# First disconnect N1
# Then invalidate 1033 on main chain and 1032 on fork so height is 1032 on main chain
# N1 **...*(1020) **...**(1032)X..
# \
# ++...+(1031)X..
#
# Now mine 300 more blocks on N1
# N1 **...*(1020) **...**(1032) @@...@(1332)
# \ \
# \ X...
# \ \
# ++...+(1031)X.. ..
#
# Reconnect nodes and mine 220 more blocks on N1
# N1 **...*(1020) **...**(1032) @@...@@@(1552)
# \ \
# \ X...
# \ \
# ++...+(1031)X.. ..
#
# N2 **...*(1020) **...**(1032) @@...@@@(1552)
# \ \
# \ *...**(1320)
# \ \
# ++...++(1044) ..
#
# N0 ********************(1032) @@...@@@(1552)
# \
# *...**(1320)
print "Test that we can rerequest a block we previously pruned if needed for a reorg"
self.reorg_back()
# Verify that N2 still has block 1033 on current chain (@), but not on main chain (*)
# Invalidate 1033 on current chain (@) on N2 and we should be able to reorg to
# original main chain (*), but will require redownload of some blocks
# In order to have a peer we think we can download from, must also perform this invalidation
# on N0 and mine a new longest chain to trigger.
# Final result:
# N0 ********************(1032) **...****(1553)
# \
# X@...@@@(1552)
#
# N2 **...*(1020) **...**(1032) **...****(1553)
# \ \
# \ X@...@@@(1552)
# \
# +..
#
# N1 doesn't change because 1033 on main chain (*) is invalid
print "Done"
if __name__ == '__main__':
PruneTest().main()
| [
"mirzaei@ce.sharif.edu"
] | mirzaei@ce.sharif.edu |
278032d631fba53001449d91e03a872faa35bca7 | 7300fc72162568f886e04509431359a62a09da79 | /lino_xl/lib/invoicing/fixtures/demo.py | 71831baa9fb747e6c2a93c3f3faffa9c31c2133a | [
"BSD-2-Clause"
] | permissive | forexblog/xl | ad27aa1e9f5669f8a78ec55f4b7d0bd952da6327 | 130303647d01c0d8271f770f3054907c183dc1e8 | refs/heads/master | 2023-03-04T01:44:39.485452 | 2021-02-13T08:18:16 | 2021-02-13T08:18:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 396 | py | # -*- coding: UTF-8 -*-
# Copyright 2019 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
from lino.api import dd, rt, _
def DEP(name, **kwargs):
kwargs = dd.str2kw('designation', name, **kwargs)
# kwargs.update(designation=name)
return rt.models.invoicing.Area(**kwargs)
def objects():
yield DEP(_("First"))
yield DEP(_("Second"))
yield DEP(_("Third"))
| [
"luc.saffre@gmail.com"
] | luc.saffre@gmail.com |
ae19267c6dda3313c40bbe157565655c4a567a5d | 56b63ee537f872af0fc028016d1508b4c1dd5c60 | /school/migrations/0283_auto_20210430_1342.py | dacf5ab3f5b6d36ae57960a11a16a4d70f68b1f3 | [] | no_license | jacknjillsolutionsrevanth/EMS1 | 01fc571120f765b0fbfe3aa654b15ff578d6e9b9 | db14d8e6c15669b5938aa9276c5e22006218814a | refs/heads/main | 2023-08-03T19:40:50.073133 | 2021-10-01T07:02:37 | 2021-10-01T07:02:37 | 410,202,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 774 | py | # Generated by Django 3.2 on 2021-04-30 08:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('school', '0282_rpt_dailydata'),
]
operations = [
migrations.AlterField(
model_name='rpt_dailydata',
name='sampno',
field=models.IntegerField(blank=True, default=0, null=True),
),
migrations.AlterField(
model_name='rpt_dailydata',
name='sampno2',
field=models.IntegerField(blank=True, default=0, null=True),
),
migrations.AlterField(
model_name='rpt_excel_bankwise',
name='net',
field=models.FloatField(blank=True, default=0.0, null=True),
),
]
| [
"jacknjillsolutions.revanth@gmail.com"
] | jacknjillsolutions.revanth@gmail.com |
a895ffff2e8eef3681fcd33e7078e5fe1d048327 | 56014da6ebc817dcb3b7a136df8b11cf9f976d93 | /Python基础笔记/12-tkinter图形界面/25.鼠标点击事件.py | 78be4991790e176ac02a8f6d5493e2c7c805b998 | [] | no_license | sunday2146/notes-python | 52b2441c981c1106e70a94b999e986999334239a | e19d2aee1aa9433598ac3c0a2a73b0c1e8fa6dc2 | refs/heads/master | 2022-01-12T22:55:45.401326 | 2019-01-18T03:18:26 | 2019-01-18T03:18:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 510 | py | import tkinter
#创建主窗口
win = tkinter.Tk()
#设置标题
win.title("sunck")
#设置大小和位置
win.geometry("400x400+200+200")
def func(event):
print(event.x,event.y)
#<Button-1> 鼠标左键
#<Button-2> 鼠标中键 滑轮
#<Button-3> 鼠标右键
#<Double-Button-1> 鼠标左键双击
#<Triple-Button-1> 鼠标左键三击
button1 = tkinter.Button(win,text = "leftMouse button")
#bind 给控件绑定事件
button1.bind("<Button-1>",func)
button1.pack()
win.mainloop() | [
"964640116@qq.com"
] | 964640116@qq.com |
2e2fa323eea5fc934489a50ee7d2abd689370fc0 | 2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02 | /PyTorch/built-in/cv/detection/SSD_for_PyTorch/configs/lvis/mask_rcnn_x101_64x4d_fpn_sample1e-3_mstrain_2x_lvis_v0.5.py | 8db3bebe5c1db6d3d139f2718d06141af12b6c16 | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Ascend/ModelZoo-PyTorch | 4c89414b9e2582cef9926d4670108a090c839d2d | 92acc188d3a0f634de58463b6676e70df83ef808 | refs/heads/master | 2023-07-19T12:40:00.512853 | 2023-07-17T02:48:18 | 2023-07-17T02:48:18 | 483,502,469 | 23 | 6 | Apache-2.0 | 2022-10-15T09:29:12 | 2022-04-20T04:11:18 | Python | UTF-8 | Python | false | false | 1,034 | py | # Copyright 2022 Huawei Technologies 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.
_base_ = './mask_rcnn_r50_fpn_sample1e-3_mstrain_2x_lvis_v0.5.py'
model = dict(
backbone=dict(
type='ResNeXt',
depth=101,
groups=64,
base_width=4,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
style='pytorch',
init_cfg=dict(
type='Pretrained', checkpoint='open-mmlab://resnext101_64x4d')))
| [
"chenyong84@huawei.com"
] | chenyong84@huawei.com |
0630143c7ad5f0c1c78680241c22b8b9a415375b | 36a85ba74dea030dd5146a5d104dce7ed67c065e | /PreviousTime.py | a9244528cf0133a06d6d09c08ab3c427d91bad7e | [] | no_license | thakur-nishant/Coding-Challenges | b797687e8ee862574e23853fa56b4eb673589dad | 975fb2edf02bcbcf94777d9858c5bd8d6183cc4e | refs/heads/master | 2020-03-18T20:44:10.399689 | 2019-06-18T08:12:17 | 2019-06-18T08:12:17 | 135,234,918 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 26 | py | def solution(S):
pass
| [
"nt.nishantt@gmail.com"
] | nt.nishantt@gmail.com |
5e2fabfb02162670a52913d64f726d0eb8816046 | 1aebf8a65f27304a135748683cd100b648b816fc | /easydoc/wsgi.py | 8ee0729e30a3a0d708770b13c2992e6ca098d826 | [] | no_license | Shatki/easydoc | 5e16f31ded11ca123d820c34c525a6edd1f8cbfa | eee96f6857c6486ef16c4eb7b4822f12a160d1a9 | refs/heads/master | 2020-04-18T06:19:35.896596 | 2019-02-18T05:50:12 | 2019-02-18T05:50:12 | 167,315,578 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 391 | py | """
WSGI config for easydoc project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'easydoc.settings')
application = get_wsgi_application()
| [
"Shatki@mail.ru"
] | Shatki@mail.ru |
d718b9f7eb54f07326e127b321bdd783d7613634 | 4a83d8f34a50aea012491058925296fdc3edac0d | /pandasdmx/tests/test_remote.py | 36f3a6f035b4ff2ea6f8329e467fea639c3e5ce0 | [
"Python-2.0",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | openpolis/pandaSDMX | 8af55fd24272ee359fd6700414258101b5a948f2 | 0c4e2ad0c25a63d2bcb75703e577d2723162a9b5 | refs/heads/master | 2020-05-30T14:20:10.821106 | 2020-04-05T22:54:55 | 2020-04-05T22:54:55 | 189,787,828 | 0 | 0 | Apache-2.0 | 2019-06-02T00:08:58 | 2019-06-01T23:55:55 | Python | UTF-8 | Python | false | false | 785 | py | import pytest
from pandasdmx.remote import Session
from . import has_requests_cache
@pytest.mark.skipif(has_requests_cache, reason='test without requests_cache')
def test_session_without_requests_cache(): # pragma: no cover
# Passing cache= arguments when requests_cache is not installed triggers a
# warning
with pytest.warns(RuntimeWarning):
Session(cache_name='test')
@pytest.mark.remote_data
def test_session_init_cache(tmp_path):
# Instantiate a REST object with cache
cache_name = tmp_path / 'pandasdmx_cache'
s = Session(cache_name=str(cache_name), backend='sqlite')
# Get a resource
s.get('https://registry.sdmx.org/ws/rest/dataflow')
# Test for existence of cache file
assert cache_name.with_suffix('.sqlite').exists()
| [
"mail@paul.kishimoto.name"
] | mail@paul.kishimoto.name |
0adb67bc4ff731873a0e3d2742ac1ac278019997 | 8d3adc6867d80a75ac12984f52c78938221404a4 | /Bio/Phylo/_cdao_owl.py | 0191040b92638ad5cd472edea843b0382b0d6c50 | [
"LicenseRef-scancode-biopython"
] | permissive | chapmanb/biopython | 407b17f44f599d71818c5e16bd86a44cf323e062 | cade0aec7ecff7d052c42040f5cae8036e297941 | refs/heads/master | 2020-12-29T03:07:42.778627 | 2013-07-09T09:36:26 | 2013-07-09T09:36:26 | 412,030 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 110,025 | py | # Copyright (C) 2013 by Ben Morris (ben@bendmorris.com)
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
import xml.etree.ElementTree as ET
cdao_namespaces = {
'cdao': 'http://purl.obolibrary.org/obo/cdao.owl#',
'obo': 'http://purl.obolibrary.org/obo/',
}
def resolve_uri(s, namespaces=cdao_namespaces, cdao_to_obo=True, xml_style=False):
'''Converts prefixed URIs to full URIs. Optionally, converts CDAO
named identifiers to OBO numeric identifiers.'''
if cdao_to_obo and s.startswith('cdao:'):
return resolve_uri('obo:%s' % cdao_elements[s[5:]], namespaces, cdao_to_obo)
for prefix in namespaces:
if xml_style: s = s.replace(prefix+':', '{%s}' % namespaces[prefix])
else: s = s.replace(prefix+':', namespaces[prefix])
return s
cdao_owl = '''<?xml version="1.0"?>
<!DOCTYPE rdf:RDF [
<!ENTITY owl "http://www.w3.org/2002/07/owl#" >
<!ENTITY obo "http://purl.obolibrary.org/obo/" >
<!ENTITY dc "http://purl.org/dc/elements/1.1/" >
<!ENTITY xsd "http://www.w3.org/2001/XMLSchema#" >
<!ENTITY rdfs "http://www.w3.org/2000/01/rdf-schema#" >
<!ENTITY rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" >
]>
<rdf:RDF xmlns="http://www.evolutionaryontology.org/cdao/1.0/cdao.owl#"
xml:base="http://www.evolutionaryontology.org/cdao/1.0/cdao.owl"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:obo="http://purl.obolibrary.org/obo/"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns:owl="http://www.w3.org/2002/07/owl#"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<owl:Ontology rdf:about="&obo;cdao.owl">
<dc:coverage rdf:datatype="&xsd;string">Comparison of two or more biological entities of the same class when the similarities and differences of the entities are treated explicitly as the product of an evolutionary process of descent with modification.</dc:coverage>
<dc:description rdf:datatype="&xsd;string">The Comparative Data Analysis Ontology (CDAO) provides a framework for understanding data in the context of evolutionary-comparative analysis. This comparative approach is used commonly in bioinformatics and other areas of biology to draw inferences from a comparison of differently evolved versions of something, such as differently evolved versions of a protein. In this kind of analysis, the things-to-be-compared typically are classes called 'OTUs' (Operational Taxonomic Units). The OTUs can represent biological species, but also may be drawn from higher or lower in a biological hierarchy, anywhere from molecules to communities. The features to be compared among OTUs are rendered in an entity-attribute-value model sometimes referred to as the 'character-state data model'. For a given character, such as 'beak length', each OTU has a state, such as 'short' or 'long'. The differences between states are understood to emerge by a historical process of evolutionary transitions in state, represented by a model (or rules) of transitions along with a phylogenetic tree. CDAO provides the framework for representing OTUs, trees, transformations, and characters. The representation of characters and transformations may depend on imported ontologies for a specific type of character.</dc:description>
<dc:creator xml:lang="en">CDAO Team</dc:creator>
<dc:title xml:lang="en">Comparative Data Analysis Ontology</dc:title>
<dc:subject xml:lang="en">comparative analysis; comparative data analysis; evolutionary comparative analysis; evolution; phylogeny; phylogenetics</dc:subject>
<dc:rights rdf:resource="http://creativecommons.org/publicdomain/zero/1.0/"/>
<owl:versionIRI rdf:resource="&obo;cdao/2012-06-06/cdao.owl"/>
<owl:imports rdf:resource="&obo;iao/ontology-metadata.owl"/>
</owl:Ontology>
<!--
///////////////////////////////////////////////////////////////////////////////////////
//
// Annotation properties
//
///////////////////////////////////////////////////////////////////////////////////////
-->
<owl:AnnotationProperty rdf:about="&dc;creator"/>
<owl:AnnotationProperty rdf:about="&dc;subject"/>
<owl:AnnotationProperty rdf:about="&dc;description"/>
<owl:AnnotationProperty rdf:about="&dc;coverage"/>
<owl:AnnotationProperty rdf:about="&dc;language"/>
<owl:AnnotationProperty rdf:about="&dc;identifier"/>
<owl:AnnotationProperty rdf:about="&dc;date"/>
<owl:AnnotationProperty rdf:about="&dc;source"/>
<owl:AnnotationProperty rdf:about="&dc;title"/>
<owl:AnnotationProperty rdf:about="&dc;rights"/>
<!--
///////////////////////////////////////////////////////////////////////////////////////
//
// Object Properties
//
///////////////////////////////////////////////////////////////////////////////////////
-->
<!-- http://purl.obolibrary.org/obo/CDAO_0000142 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000142">
<rdfs:label rdf:datatype="&xsd;string">has_Character</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property associates a character data matrix with a character (a column) represented in the matrix.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000056"/>
<rdfs:range rdf:resource="&obo;CDAO_0000071"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000143 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000143">
<rdfs:label rdf:datatype="&xsd;string">belongs_to_Edge_as_Child</rdfs:label>
<dc:description>The property links a Node to the Edge it belongs to in the child position.</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000139"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000146"/>
<owl:inverseOf rdf:resource="&obo;CDAO_0000209"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000144 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000144">
<rdf:type rdf:resource="&owl;TransitiveProperty"/>
<rdfs:label rdf:datatype="&xsd;string">has_Ancestor</rdfs:label>
<dc:description>The property links a node to any of the other nodes that are its ancestors in a rooted tree.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000140"/>
<rdfs:range rdf:resource="&obo;CDAO_0000140"/>
<owl:inverseOf rdf:resource="&obo;CDAO_0000174"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000145 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000145">
<rdfs:label rdf:datatype="&xsd;string">has_Nucleotide_State</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property associates a nucleotide character-state instance with a state value from the domain of nucleotide states.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000002"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000184"/>
<rdfs:range>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000015"/>
<rdf:Description rdf:about="&obo;CDAO_0000133"/>
</owl:unionOf>
</owl:Class>
</rdfs:range>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000146 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000146">
<rdfs:label rdf:datatype="&xsd;string">belongs_to_Edge</rdfs:label>
<dc:description>The property links a Node to one of the edges that are incident on such node.</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000099"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000190"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000147 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000147">
<rdfs:label rdf:datatype="&xsd;string">belongs_to_Character_State_Data_Matrix</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000056"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000190"/>
<rdfs:domain>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000071"/>
<rdf:Description rdf:about="&obo;CDAO_0000138"/>
</owl:unionOf>
</owl:Class>
</rdfs:domain>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000148 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000148">
<rdf:type rdf:resource="&owl;FunctionalProperty"/>
<rdfs:label rdf:datatype="&xsd;string">has_Root</rdfs:label>
<dc:description>The property links a rooted tree to the specific node that represents the unique root of the tree.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000012"/>
<rdfs:range rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000149 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000149">
<rdfs:label rdf:datatype="&xsd;string">has_Child</rdfs:label>
<dc:description>The property links a node to a node that is an immediate descendant in the tree.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000140"/>
<rdfs:range rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000174"/>
<owl:inverseOf rdf:resource="&obo;CDAO_0000179"/>
<owl:propertyChainAxiom rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000177"/>
<rdf:Description rdf:about="&obo;CDAO_0000209"/>
</owl:propertyChainAxiom>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000150 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000150">
<rdfs:label rdf:datatype="&xsd;string">has_First_Coordinate_Item</rdfs:label>
<dc:description rdf:datatype="&xsd;string">The property that relates a coordinate list to the first item in the list.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000092"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
<rdfs:range>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000003"/>
<rdf:Description rdf:about="&obo;CDAO_0000095"/>
</owl:unionOf>
</owl:Class>
</rdfs:range>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000151 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000151">
<rdfs:label rdf:datatype="&xsd;string">has_Coordinate</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000022"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000098"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000152 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000152">
<rdf:type rdf:resource="&owl;FunctionalProperty"/>
<rdfs:label rdf:datatype="&xsd;string">belongs_to_Continuous_Character</rdfs:label>
<rdfs:domain rdf:resource="&obo;CDAO_0000019"/>
<rdfs:range rdf:resource="&obo;CDAO_0000068"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000205"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000153 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000153">
<rdfs:label rdf:datatype="&xsd;string">has_Datum</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates a character to a state datum for the character.</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000098"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
<rdfs:domain>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000071"/>
<rdf:Description rdf:about="&obo;CDAO_0000138"/>
</owl:unionOf>
</owl:Class>
</rdfs:domain>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000154 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000154">
<rdfs:label rdf:datatype="&xsd;string">has_Standard_Datum</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000008"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000183"/>
<rdfs:domain>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000075"/>
<rdf:Description rdf:about="&obo;CDAO_0000138"/>
</owl:unionOf>
</owl:Class>
</rdfs:domain>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000155 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000155">
<rdfs:label rdf:datatype="&xsd;string">subtree_of</rdfs:label>
<dc:description>This property links two networks where the latter is a substructure of the former</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000006"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000006"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000156 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000156">
<rdfs:label rdf:datatype="&xsd;string">has_Amino_Acid_State</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property associates a amino acid character-state instance with a state value from the domain of amino acid states.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000112"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000184"/>
<rdfs:range>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000015"/>
<rdf:Description rdf:about="&obo;CDAO_0000076"/>
</owl:unionOf>
</owl:Class>
</rdfs:range>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000157 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000157">
<rdfs:label rdf:datatype="&xsd;string">is_annotation_of</rdfs:label>
<rdfs:domain rdf:resource="&obo;CDAO_0000040"/>
<rdfs:range rdf:resource="&owl;Thing"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000158 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000158">
<rdfs:label rdf:datatype="&xsd;string">has_RNA_Datum</rdfs:label>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000206"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000159 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000159">
<rdfs:label rdf:datatype="&xsd;string">has_Left_State</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates a transformation to a 'left' state (the state associated with the 'left' node).</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000091"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000097"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000182"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000160 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000160">
<rdfs:label rdf:datatype="&xsd;string">precedes</rdfs:label>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000161 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000161">
<rdfs:label rdf:datatype="&xsd;string">exclude</rdfs:label>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000162 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000162">
<rdfs:label rdf:datatype="&xsd;string">has_Node</rdfs:label>
<dc:description>Property that associates to each Edge the Nodes it connects.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000099"/>
<rdfs:range rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000163 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000163">
<rdfs:label rdf:datatype="&xsd;string">nca_node_of</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000059"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000140"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000164 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000164">
<rdfs:label rdf:datatype="&xsd;string">has_External_Reference</rdfs:label>
<rdfs:comment rdf:datatype="&rdfs;Literal">Associates a TU to some external taxonomy reference.</rdfs:comment>
<rdfs:domain rdf:resource="&obo;CDAO_0000138"/>
<rdfs:range rdf:resource="&owl;Thing"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000165 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000165">
<rdfs:label rdf:datatype="&xsd;string">has_Coordinate_System</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property links a coordinate to the coordinate system it references.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000022"/>
<rdfs:range rdf:resource="&obo;CDAO_0000104"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000166 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000166">
<rdf:type rdf:resource="&owl;FunctionalProperty"/>
<rdfs:label rdf:datatype="&xsd;string">belongs_to_Nucleotide_Character</rdfs:label>
<rdfs:domain rdf:resource="&obo;CDAO_0000002"/>
<rdfs:range rdf:resource="&obo;CDAO_0000094"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000205"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000167 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000167">
<rdf:type rdf:resource="&owl;SymmetricProperty"/>
<rdfs:label rdf:datatype="&xsd;string">connects_to</rdfs:label>
<owl:inverseOf rdf:resource="&obo;CDAO_0000167"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000168 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000168">
<rdfs:label rdf:datatype="&xsd;string">has_Amino_Acid_Datum</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates an amino acid character (a column in a protein sequence alignment) to a state datum for the character (an individual cell in the alignment column).</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000112"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000206"/>
<rdfs:domain>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000131"/>
<rdf:Description rdf:about="&obo;CDAO_0000138"/>
</owl:unionOf>
</owl:Class>
</rdfs:domain>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000169 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000169">
<rdfs:label rdf:datatype="&xsd;string">hereditary_change_of</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates a type of evolutionary change (an Edge_Transformation) to the character that undergoes the change. The change is a transformation_of the affected character.</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000071"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000170 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000170">
<rdfs:label rdf:datatype="&xsd;string">has_Compound_Datum</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates a compound character (a character with some states that are subdividable) to a state datum for the character.</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000136"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000183"/>
<rdfs:domain>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000078"/>
<rdf:Description rdf:about="&obo;CDAO_0000138"/>
</owl:unionOf>
</owl:Class>
</rdfs:domain>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000171 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000171">
<rdfs:label rdf:datatype="&xsd;string">has_Descendants</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000059"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000080"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000172 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000172">
<rdfs:label rdf:datatype="&xsd;string">reconciliation_of</rdfs:label>
<rdfs:domain rdf:resource="&obo;CDAO_0000030"/>
<rdfs:range rdf:resource="&obo;CDAO_0000110"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000173 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000173">
<rdf:type rdf:resource="&owl;FunctionalProperty"/>
<rdfs:label rdf:datatype="&xsd;string">belongs_to_Amino_Acid_Character</rdfs:label>
<rdfs:domain rdf:resource="&obo;CDAO_0000112"/>
<rdfs:range rdf:resource="&obo;CDAO_0000131"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000205"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000174 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000174">
<rdf:type rdf:resource="&owl;TransitiveProperty"/>
<rdfs:label rdf:datatype="&xsd;string">has_Descendant</rdfs:label>
<dc:description>A property that links a node to any of its descendants in a rooted tree.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000140"/>
<rdfs:range rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000175 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000175">
<rdfs:label rdf:datatype="&xsd;string">has_Continuous_State</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property associates a character-state instance with a state value on a continuous numeric scale.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000019"/>
<rdfs:range rdf:resource="&obo;CDAO_0000031"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000184"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000176 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000176">
<rdfs:label rdf:datatype="&xsd;string">has_Type</rdfs:label>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000177 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000177">
<rdfs:label rdf:datatype="&xsd;string">belongs_to_Edge_as_Parent</rdfs:label>
<dc:description>The property links a Node to one of the Edges where the node appears in the parent position (i.e., closer to the root).</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000139"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000146"/>
<owl:inverseOf rdf:resource="&obo;CDAO_0000201"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000178 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000178">
<rdfs:label rdf:datatype="&xsd;string">has</rdfs:label>
<dc:description>Generic 'has' property.</dc:description>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000179 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000179">
<rdfs:label rdf:datatype="&xsd;string">has_Parent</rdfs:label>
<dc:description>The property that links a node to its unique parent in a rooted tree.</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000140"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000144"/>
<owl:propertyChainAxiom rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000143"/>
<rdf:Description rdf:about="&obo;CDAO_0000201"/>
</owl:propertyChainAxiom>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000180 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000180">
<rdfs:label rdf:datatype="&xsd;string">belongs_to_Compound_Character</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000078"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000136"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000205"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000181 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000181">
<rdfs:label rdf:datatype="&xsd;string">homologous_to</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This propery relates different instances of the same character, including the case when the states of the character differ (e.g., large_beak of beak_size_character of TU A is homologous_to small_beak of beak_size_character of TU B).</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000098"/>
<rdfs:range rdf:resource="&obo;CDAO_0000098"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000182 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000182">
<rdfs:label rdf:datatype="&xsd;string">has_Change_Component</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates a transformation to the components that compose it.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000097"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000183 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000183">
<rdfs:label rdf:datatype="&xsd;string">has_Categorical_Datum</rdfs:label>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000153"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000184 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000184">
<rdfs:label rdf:datatype="&xsd;string">has_State</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property associates a character-state instance with its state value, e.g., a state value expressed in terms of an imported domain ontology.</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000091"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000098"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000185 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000185">
<rdfs:label rdf:datatype="&xsd;string">has_Left_Node</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates a transformation to a 'left' node (the node that has the 'left' state).</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000097"/>
<rdfs:range rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000182"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000186 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000186">
<rdfs:label rdf:datatype="&xsd;string">has_Right_State</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates a transformation to a 'right' state (the state associated with the 'right' node).</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000091"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000097"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000182"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000187 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000187">
<rdf:type rdf:resource="&owl;FunctionalProperty"/>
<rdfs:label rdf:datatype="&xsd;string">represents_TU</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates a TU or taxonomic unit (typically associated with character data) to a phylogenetic history (Tree).</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000138"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000140"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000188 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000188">
<rdfs:label rdf:datatype="&xsd;string">exclude_Node</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000161"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000189 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000189">
<rdfs:label rdf:datatype="&xsd;string">has_Compound_State</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property associates a compound character-state instance with its compound state value.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000136"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000184"/>
<rdfs:range>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000015"/>
<rdf:Description rdf:about="&obo;CDAO_0000055"/>
</owl:unionOf>
</owl:Class>
</rdfs:range>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000190 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000190">
<rdfs:label rdf:datatype="&xsd;string">belongs_to</rdfs:label>
<dc:description>Generic property that links a concept to another concept it is a constituent of. The property is a synonym of part_of.</dc:description>
<owl:equivalentProperty rdf:resource="&obo;CDAO_0000194"/>
<rdfs:range rdf:resource="&owl;Thing"/>
<rdfs:domain rdf:resource="&owl;Thing"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000191 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000191">
<rdf:type rdf:resource="&owl;FunctionalProperty"/>
<rdfs:label rdf:datatype="&xsd;string">belongs_to_TU</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates a character-state datum to its TU.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000098"/>
<rdfs:range rdf:resource="&obo;CDAO_0000138"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000190"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000192 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000192">
<rdfs:label rdf:datatype="&xsd;string">belongs_to_Network</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000006"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000190"/>
<rdfs:domain>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000099"/>
<rdf:Description rdf:about="&obo;CDAO_0000140"/>
</owl:unionOf>
</owl:Class>
</rdfs:domain>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000193 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000193">
<rdfs:label rdf:datatype="&xsd;string">has_Annotation</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000040"/>
<owl:inverseOf rdf:resource="&obo;CDAO_0000157"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
<rdfs:domain rdf:resource="&owl;Thing"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000194 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000194">
<rdfs:label rdf:datatype="&xsd;string">part_of</rdfs:label>
<owl:inverseOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000195 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000195">
<rdfs:label rdf:datatype="&xsd;string">has_Nucleotide_Datum</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates a nucleotide character (a column in a nucleotide alignment) to a state datum for the character (an individual cell in the alignment column).</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000002"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000206"/>
<rdfs:domain>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000094"/>
<rdf:Description rdf:about="&obo;CDAO_0000138"/>
</owl:unionOf>
</owl:Class>
</rdfs:domain>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000196 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000196">
<rdfs:label rdf:datatype="&xsd;string">represented_by_Node</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates a TU to a node that represents it in a network.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000138"/>
<rdfs:range rdf:resource="&obo;CDAO_0000140"/>
<owl:inverseOf rdf:resource="&obo;CDAO_0000187"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000197 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000197">
<rdfs:label rdf:datatype="&xsd;string">has_Remaining_Coordinate_List</rdfs:label>
<dc:description rdf:datatype="&xsd;string">The property that relates a coordinate list to the item in the list beyond the first item.</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000092"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000092"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000198 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000198">
<rdfs:label rdf:datatype="&xsd;string">has_Element</rdfs:label>
<rdfs:domain rdf:resource="&obo;CDAO_0000118"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000199 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000199">
<rdfs:label rdf:datatype="&xsd;string">exclude_Subtree</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000070"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000161"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000200 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000200">
<rdfs:label rdf:datatype="&xsd;string">belongs_to_Tree</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000110"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000190"/>
<rdfs:domain>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000099"/>
<rdf:Description rdf:about="&obo;CDAO_0000140"/>
</owl:unionOf>
</owl:Class>
</rdfs:domain>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000201 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000201">
<rdf:type rdf:resource="&owl;FunctionalProperty"/>
<rdfs:label rdf:datatype="&xsd;string">has_Parent_Node</rdfs:label>
<dc:description>Associates to a Directed Edge the Node that is in the parent position in the edge (i.e., the node touched by the edge and closer to the root of the tree)</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000139"/>
<rdfs:range rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000162"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000202 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000202">
<rdfs:label rdf:datatype="&xsd;string">has_Lineage_node</rdfs:label>
<rdfs:domain rdf:resource="&obo;CDAO_0000004"/>
<rdfs:range rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000203 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000203">
<rdfs:label rdf:datatype="&xsd;string">belongs_to_Tree_as_Root</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000110"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000140"/>
<owl:inverseOf rdf:resource="&obo;CDAO_0000148"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000190"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000204 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000204">
<rdfs:label rdf:datatype="&xsd;string">has_Hereditary_Change</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000097"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000099"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000205 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000205">
<rdf:type rdf:resource="&owl;FunctionalProperty"/>
<rdfs:label rdf:datatype="&xsd;string">belongs_to_Character</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000071"/>
<rdfs:domain rdf:resource="&obo;CDAO_0000098"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000190"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000206 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000206">
<rdfs:label rdf:datatype="&xsd;string">has_Molecular_Datum</rdfs:label>
<rdfs:range rdf:resource="&obo;CDAO_0000050"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000183"/>
<rdfs:domain>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000115"/>
<rdf:Description rdf:about="&obo;CDAO_0000138"/>
</owl:unionOf>
</owl:Class>
</rdfs:domain>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000207 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000207">
<rdfs:label rdf:datatype="&xsd;string">has_Continuous_Datum</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates a continuous character to a state datum for the character.</dc:description>
<rdfs:range rdf:resource="&obo;CDAO_0000019"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000153"/>
<rdfs:domain>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000068"/>
<rdf:Description rdf:about="&obo;CDAO_0000138"/>
</owl:unionOf>
</owl:Class>
</rdfs:domain>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000208 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000208">
<rdfs:label rdf:datatype="&xsd;string">has_TU</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property associates a character data matrix with a TU (a row) represented in the matrix.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000056"/>
<rdfs:range rdf:resource="&obo;CDAO_0000138"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000178"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000209 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000209">
<rdf:type rdf:resource="&owl;FunctionalProperty"/>
<rdfs:label rdf:datatype="&xsd;string">has_Child_Node</rdfs:label>
<dc:description>The property associates to a Directed Edge the Node that is in the child position in the edge, i.e., the node touched by the edge and closer to the leaves of the tree.</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000139"/>
<rdfs:range rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000162"/>
</owl:ObjectProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000210 -->
<owl:ObjectProperty rdf:about="&obo;CDAO_0000210">
<rdfs:label rdf:datatype="&xsd;string">has_Right_Node</rdfs:label>
<dc:description rdf:datatype="&xsd;string">This property relates a transformation to a 'right' node (the node that has the 'right' state).</dc:description>
<rdfs:domain rdf:resource="&obo;CDAO_0000097"/>
<rdfs:range rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000182"/>
</owl:ObjectProperty>
<!--
///////////////////////////////////////////////////////////////////////////////////////
//
// Data properties
//
///////////////////////////////////////////////////////////////////////////////////////
-->
<!-- http://purl.obolibrary.org/obo/CDAO_0000211 -->
<owl:DatatypeProperty rdf:about="&obo;CDAO_0000211">
<rdfs:label rdf:datatype="&xsd;string">has_Precision</rdfs:label>
<rdfs:range rdf:resource="&xsd;float"/>
</owl:DatatypeProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000212 -->
<owl:DatatypeProperty rdf:about="&obo;CDAO_0000212">
<rdfs:label rdf:datatype="&xsd;string">has_Point_Coordinate_Value</rdfs:label>
<rdfs:domain rdf:resource="&obo;CDAO_0000003"/>
<rdfs:range rdf:resource="&xsd;integer"/>
</owl:DatatypeProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000213 -->
<owl:DatatypeProperty rdf:about="&obo;CDAO_0000213">
<rdfs:label rdf:datatype="&xsd;string">has_Int_Value</rdfs:label>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000215"/>
<rdfs:range rdf:resource="&xsd;int"/>
</owl:DatatypeProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000214 -->
<owl:DatatypeProperty rdf:about="&obo;CDAO_0000214">
<rdfs:label rdf:datatype="&xsd;string">has_Support_Value</rdfs:label>
<rdfs:range rdf:resource="&xsd;float"/>
</owl:DatatypeProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000215 -->
<owl:DatatypeProperty rdf:about="&obo;CDAO_0000215">
<rdfs:label rdf:datatype="&xsd;string">has_Value</rdfs:label>
</owl:DatatypeProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000216 -->
<owl:DatatypeProperty rdf:about="&obo;CDAO_0000216">
<rdfs:label rdf:datatype="&xsd;string">has_Uncertainty_Factor</rdfs:label>
<rdfs:range rdf:resource="&xsd;float"/>
</owl:DatatypeProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000217 -->
<owl:DatatypeProperty rdf:about="&obo;CDAO_0000217">
<rdfs:label rdf:datatype="&xsd;string">has_Range_End_Value</rdfs:label>
<rdfs:domain rdf:resource="&obo;CDAO_0000095"/>
<rdfs:range rdf:resource="&xsd;integer"/>
</owl:DatatypeProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000218 -->
<owl:DatatypeProperty rdf:about="&obo;CDAO_0000218">
<rdfs:label rdf:datatype="&xsd;string">has_Float_Value</rdfs:label>
<rdfs:subPropertyOf rdf:resource="&obo;CDAO_0000215"/>
<rdfs:range rdf:resource="&xsd;float"/>
</owl:DatatypeProperty>
<!-- http://purl.obolibrary.org/obo/CDAO_0000219 -->
<owl:DatatypeProperty rdf:about="&obo;CDAO_0000219">
<rdfs:label rdf:datatype="&xsd;string">has_Range_Start_Value</rdfs:label>
<rdfs:domain rdf:resource="&obo;CDAO_0000095"/>
<rdfs:range rdf:resource="&xsd;integer"/>
</owl:DatatypeProperty>
<!--
///////////////////////////////////////////////////////////////////////////////////////
//
// Classes
//
///////////////////////////////////////////////////////////////////////////////////////
-->
<!-- http://purl.obolibrary.org/obo/CDAO_0000002 -->
<owl:Class rdf:about="&obo;CDAO_0000002">
<rdfs:label rdf:datatype="&xsd;string">DesoxiRibonucleotideResidueStateDatum</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000050"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000003 -->
<owl:Class rdf:about="&obo;CDAO_0000003">
<rdfs:label rdf:datatype="&xsd;string">CoordinatePoint</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000022"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000004 -->
<owl:Class rdf:about="&obo;CDAO_0000004">
<rdfs:label rdf:datatype="&xsd;string">Lineage</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000012"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000202"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000140"/>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000005 -->
<owl:Class rdf:about="&obo;CDAO_0000005">
<rdfs:label rdf:datatype="&xsd;string">Phylo4Tree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000074"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000006 -->
<owl:Class rdf:about="&obo;CDAO_0000006">
<rdfs:label rdf:datatype="&xsd;string">Network</rdfs:label>
<rdfs:subClassOf rdf:resource="&owl;Thing"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000178"/>
<owl:allValuesFrom>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000099"/>
<rdf:Description rdf:about="&obo;CDAO_0000140"/>
</owl:unionOf>
</owl:Class>
</owl:allValuesFrom>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000007 -->
<owl:Class rdf:about="&obo;CDAO_0000007">
<rdfs:label rdf:datatype="&xsd;string">ModelDescription</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000040"/>
<dc:description>Description of a model of transformations.</dc:description>
<rdfs:comment>This is a non-computible description of a model, not the fully specified mathematical model, which typically relates the probability of a transformation to various parameters.</rdfs:comment>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000008 -->
<owl:Class rdf:about="&obo;CDAO_0000008">
<rdfs:label rdf:datatype="&xsd;string">StandardStateDatum</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000089"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000009 -->
<owl:Class rdf:about="&obo;CDAO_0000009">
<rdfs:label rdf:datatype="&xsd;string">ContinuousCharacterLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000063"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000010 -->
<owl:Class rdf:about="&obo;CDAO_0000010">
<rdfs:label rdf:datatype="&xsd;string">ContinuousCharBayesianLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000009"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000011 -->
<owl:Class rdf:about="&obo;CDAO_0000011">
<rdfs:label rdf:datatype="&xsd;string">NEXUSTreeBlock</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000074"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000012 -->
<owl:Class rdf:about="&obo;CDAO_0000012">
<rdfs:label rdf:datatype="&xsd;string">RootedTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000110"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000155"/>
<owl:allValuesFrom rdf:resource="&obo;CDAO_0000012"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000148"/>
<owl:onClass rdf:resource="&obo;CDAO_0000140"/>
<owl:qualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:qualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000178"/>
<owl:allValuesFrom>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000139"/>
<rdf:Description rdf:about="&obo;CDAO_0000140"/>
</owl:unionOf>
</owl:Class>
</owl:allValuesFrom>
</owl:Restriction>
</rdfs:subClassOf>
<owl:disjointWith rdf:resource="&obo;CDAO_0000088"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000013 -->
<owl:Class rdf:about="&obo;CDAO_0000013">
<rdfs:label rdf:datatype="&xsd;string">Kimura2Parameters</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000020"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000014 -->
<owl:Class rdf:about="&obo;CDAO_0000014">
<rdfs:label rdf:datatype="&xsd;string">TreeProcedure</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000044"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000015 -->
<owl:Class rdf:about="&obo;CDAO_0000015">
<rdfs:label rdf:datatype="&xsd;string">Generic_State</rdfs:label>
<owl:equivalentClass>
<owl:Class>
<owl:oneOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000222"/>
<rdf:Description rdf:about="&obo;CDAO_0000221"/>
<rdf:Description rdf:about="&obo;CDAO_0000223"/>
</owl:oneOf>
</owl:Class>
</owl:equivalentClass>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000039"/>
<rdfs:comment>This class should be renamed. These are not generic states but non-concrete states including gap, unknown and missing.</rdfs:comment>
<dc:description>This concept is tied to the verbally ambiguous 'gap' concept and to the use of a gap character (often the en dash '-') in text representations of sequence alignments. In general, this represents the absence of any positively diagnosed Character-State. As such, the gap may be interpreted as an additional Character-State, as the absence of the Character, or as an unknown value. In some cases it is helpful to separate these.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000016 -->
<owl:Class rdf:about="&obo;CDAO_0000016">
<rdfs:label rdf:datatype="&xsd;string">UnrootedSubtree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000070"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000017 -->
<owl:Class rdf:about="&obo;CDAO_0000017">
<rdfs:label rdf:datatype="&xsd;string">UnresolvedTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000110"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000018 -->
<owl:Class rdf:about="&obo;CDAO_0000018">
<rdfs:label rdf:datatype="&xsd;string">BifurcatingTree</rdfs:label>
<owl:equivalentClass rdf:resource="&obo;CDAO_0000130"/>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000110"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000019 -->
<owl:Class rdf:about="&obo;CDAO_0000019">
<rdfs:label rdf:datatype="&xsd;string">ContinuousStateDatum</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000098"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000020 -->
<owl:Class rdf:about="&obo;CDAO_0000020">
<rdfs:label rdf:datatype="&xsd;string">SubstitutionModel</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000007"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000021 -->
<owl:Class rdf:about="&obo;CDAO_0000021">
<rdfs:label rdf:datatype="&xsd;string">JukesKantor</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000020"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000022 -->
<owl:Class rdf:about="&obo;CDAO_0000022">
<rdfs:label rdf:datatype="&xsd;string">DatumCoordinate</rdfs:label>
<rdfs:subClassOf rdf:resource="&owl;Thing"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000165"/>
<owl:onClass rdf:resource="&obo;CDAO_0000104"/>
<owl:qualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:qualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
<dc:description>A positional coordinate giving the source of a character state, used for molecular sequences.</dc:description>
<rdfs:comment>drawing from seqloc categories from NCBI at http://www.ncbi.nlm.nih.gov/IEB/ToolBox/SDKDOCS/SEQLOC.HTML#_Seq-loc:_Locations_on</rdfs:comment>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000023 -->
<owl:Class rdf:about="&obo;CDAO_0000023">
<rdfs:label rdf:datatype="&xsd;string">UnresolvedRootedTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000012"/>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000017"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000024 -->
<owl:Class rdf:about="&obo;CDAO_0000024">
<rdfs:label rdf:datatype="&xsd;string">Branch</rdfs:label>
<owl:equivalentClass rdf:resource="&obo;CDAO_0000099"/>
<dc:description>'Branch' is the domain-specific synonym for an edge of a (Phylogenetic) Tree or Network. Branches may have properties such as length and degree of support.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000025 -->
<owl:Class rdf:about="&obo;CDAO_0000025">
<rdfs:label rdf:datatype="&xsd;string">CharacterStateDataMatrixAnnotation</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000040"/>
<dc:description>Meta-information associated with a character matrix, such as, for the case of a sequence alignment, the method of alignment.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000026 -->
<owl:Class rdf:about="&obo;CDAO_0000026">
<rdfs:label rdf:datatype="&xsd;string">AncestralNode</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000140"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000174"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000140"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000194"/>
<owl:onClass rdf:resource="&obo;CDAO_0000012"/>
<owl:minQualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:minQualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000027 -->
<owl:Class rdf:about="&obo;CDAO_0000027">
<rdfs:label rdf:datatype="&xsd;string">UnresolvedUnrootedTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000017"/>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000088"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000029 -->
<owl:Class rdf:about="&obo;CDAO_0000029">
<rdfs:label rdf:datatype="&xsd;string">UncertainStateDomain</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000091"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000216"/>
<owl:someValuesFrom rdf:resource="&xsd;float"/>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000030 -->
<owl:Class rdf:about="&obo;CDAO_0000030">
<rdfs:label rdf:datatype="&xsd;string">ReconcileTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000110"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000172"/>
<owl:onClass rdf:resource="&obo;CDAO_0000110"/>
<owl:minQualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">2</owl:minQualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000031 -->
<owl:Class rdf:about="&obo;CDAO_0000031">
<rdfs:label rdf:datatype="&xsd;string">Continuous</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000091"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000215"/>
<owl:cardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:cardinality>
</owl:Restriction>
</rdfs:subClassOf>
<dc:description>This class describes a continuous value. The link to the actual float value is through the property has_Value. It could have also other properties attached (e.g., has_Precision).</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000032 -->
<owl:Class rdf:about="&obo;CDAO_0000032">
<rdfs:label rdf:datatype="&xsd;string">AlignmentProcedure</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000025"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000033 -->
<owl:Class rdf:about="&obo;CDAO_0000033">
<rdfs:label rdf:datatype="&xsd;string">Dichotomy</rdfs:label>
<owl:equivalentClass rdf:resource="&obo;CDAO_0000124"/>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000026"/>
<owl:disjointWith rdf:resource="&obo;CDAO_0000042"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000034 -->
<owl:Class rdf:about="&obo;CDAO_0000034">
<rdfs:label rdf:datatype="&xsd;string">Molecular</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000039"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000035 -->
<owl:Class rdf:about="&obo;CDAO_0000035">
<rdfs:label rdf:datatype="&xsd;string">ContinuousCharParsimonyLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000009"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000039 -->
<owl:Class rdf:about="&obo;CDAO_0000039">
<rdfs:label rdf:datatype="&xsd;string">Categorical</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000091"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000040 -->
<owl:Class rdf:about="&obo;CDAO_0000040">
<rdfs:label rdf:datatype="&xsd;string">CDAOAnnotation</rdfs:label>
<rdfs:subClassOf rdf:resource="&owl;Thing"/>
<rdfs:comment>Its possible that this base class should be discarded and that annotations should inherit from an imported base class if one exists.</rdfs:comment>
<dc:description>The base class of annotations in CDAO.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000041 -->
<owl:Class rdf:about="&obo;CDAO_0000041">
<rdfs:label rdf:datatype="&xsd;string">originationEvent</rdfs:label>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000190"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000097"/>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000042 -->
<owl:Class rdf:about="&obo;CDAO_0000042">
<rdfs:label rdf:datatype="&xsd;string">Polytomy</rdfs:label>
<owl:equivalentClass>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000177"/>
<owl:minCardinality rdf:datatype="&xsd;nonNegativeInteger">3</owl:minCardinality>
</owl:Restriction>
</owl:equivalentClass>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000026"/>
<owl:disjointWith rdf:resource="&obo;CDAO_0000124"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000043 -->
<owl:Class rdf:about="&obo;CDAO_0000043">
<rdfs:label rdf:datatype="&xsd;string">PolymorphicStateDomain</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000091"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000216"/>
<owl:hasValue rdf:datatype="&xsd;float">1.0</owl:hasValue>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000044 -->
<owl:Class rdf:about="&obo;CDAO_0000044">
<rdfs:label rdf:datatype="&xsd;string">TreeAnnotation</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000040"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000157"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000110"/>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000045 -->
<owl:Class rdf:about="&obo;CDAO_0000045">
<rdfs:label rdf:datatype="&xsd;string">Standard</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000039"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000046 -->
<owl:Class rdf:about="&obo;CDAO_0000046">
<rdfs:label rdf:datatype="&xsd;string">EdgeLength</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000101"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000176"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000063"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000215"/>
<owl:someValuesFrom rdf:resource="&rdfs;Literal"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:comment>Its possible that this should not be classed as an 'annotation' since it contains data rather than meta-data.</rdfs:comment>
<dc:description>The length of an edge (branch) of a Tree or Network, typically in units of evolutionary changes in character-state per character.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000047 -->
<owl:Class rdf:about="&obo;CDAO_0000047">
<rdfs:label rdf:datatype="&xsd;string">RibonucleotideResidue</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000034"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000048 -->
<owl:Class rdf:about="&obo;CDAO_0000048">
<rdfs:label rdf:datatype="&xsd;string">Clade</rdfs:label>
<owl:equivalentClass rdf:resource="&obo;CDAO_0000129"/>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000110"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000049 -->
<owl:Class rdf:about="&obo;CDAO_0000049">
<rdfs:label rdf:datatype="&xsd;string">DiscreteCharParsimonyLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000100"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000050 -->
<owl:Class rdf:about="&obo;CDAO_0000050">
<rdfs:label rdf:datatype="&xsd;string">MolecularStateDatum</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000089"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000051 -->
<owl:Class rdf:about="&obo;CDAO_0000051">
<rdfs:label rdf:datatype="&xsd;string">PolyphyleticGroup</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000006"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000188"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000140"/>
</owl:Restriction>
</rdfs:subClassOf>
<owl:disjointWith rdf:resource="&obo;CDAO_0000127"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000052 -->
<owl:Class rdf:about="&obo;CDAO_0000052">
<rdfs:label rdf:datatype="&xsd;string">NexusDataBlock</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000107"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000053 -->
<owl:Class rdf:about="&obo;CDAO_0000053">
<rdfs:label rdf:datatype="&xsd;string">BranchingNode</rdfs:label>
<owl:equivalentClass>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000177"/>
<owl:minCardinality rdf:datatype="&xsd;nonNegativeInteger">2</owl:minCardinality>
</owl:Restriction>
</owl:equivalentClass>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000026"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000055 -->
<owl:Class rdf:about="&obo;CDAO_0000055">
<rdfs:label rdf:datatype="&xsd;string">Compound</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000039"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000056 -->
<owl:Class rdf:about="&obo;CDAO_0000056">
<rdfs:label rdf:datatype="&xsd;string">CharacterStateDataMatrix</rdfs:label>
<rdfs:subClassOf rdf:resource="&owl;Thing"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000178"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000025"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000208"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000138"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000142"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000071"/>
</owl:Restriction>
</rdfs:subClassOf>
<dc:description>A matrix of character-state data, typically containing observed data, though in some cases the states in the matrix might be simulated or hypothetical. Synonyms: character Data matrix, character-state matrix</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000057 -->
<owl:Class rdf:about="&obo;CDAO_0000057">
<rdfs:label rdf:datatype="&xsd;string">RibonucleotideResidueStateDatum</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000050"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000058 -->
<owl:Class rdf:about="&obo;CDAO_0000058">
<rdfs:label rdf:datatype="&xsd;string">TimeCalibratedLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000063"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000059 -->
<owl:Class rdf:about="&obo;CDAO_0000059">
<rdfs:label rdf:datatype="&xsd;string">SetOfNodes</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000118"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000198"/>
<owl:allValuesFrom rdf:resource="&obo;CDAO_0000140"/>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000060 -->
<owl:Class rdf:about="&obo;CDAO_0000060">
<rdfs:label rdf:datatype="&xsd;string">MRCANode</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000080"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000163"/>
<owl:onClass rdf:resource="&obo;CDAO_0000118"/>
<owl:minQualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:minQualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000061 -->
<owl:Class rdf:about="&obo;CDAO_0000061">
<rdfs:label rdf:datatype="&xsd;string">FASTADataMatrix</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000107"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000062 -->
<owl:Class rdf:about="&obo;CDAO_0000062">
<rdfs:label rdf:datatype="&xsd;string">evolutionaryTransition</rdfs:label>
<owl:equivalentClass rdf:resource="&obo;CDAO_0000065"/>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000097"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000159"/>
<owl:onClass rdf:resource="&obo;CDAO_0000091"/>
<owl:qualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:qualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000186"/>
<owl:onClass rdf:resource="&obo;CDAO_0000091"/>
<owl:qualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:qualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000169"/>
<owl:onClass rdf:resource="&obo;CDAO_0000071"/>
<owl:qualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:qualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000063 -->
<owl:Class rdf:about="&obo;CDAO_0000063">
<rdfs:label rdf:datatype="&xsd;string">EdgeLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&owl;Thing"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000064 -->
<owl:Class rdf:about="&obo;CDAO_0000064">
<rdfs:label rdf:datatype="&xsd;string">cladogeneticChange</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000097"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000065 -->
<owl:Class rdf:about="&obo;CDAO_0000065">
<rdfs:label rdf:datatype="&xsd;string">anageneticChange</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000097"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000066 -->
<owl:Class rdf:about="&obo;CDAO_0000066">
<rdfs:label rdf:datatype="&xsd;string">TUAnnotation</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000040"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000067 -->
<owl:Class rdf:about="&obo;CDAO_0000067">
<rdfs:label rdf:datatype="&xsd;string">PhyloTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000074"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000068 -->
<owl:Class rdf:about="&obo;CDAO_0000068">
<rdfs:label rdf:datatype="&xsd;string">ContinuousCharacter</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000071"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000207"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000019"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000153"/>
<owl:allValuesFrom rdf:resource="&obo;CDAO_0000019"/>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000069 -->
<owl:Class rdf:about="&obo;CDAO_0000069">
<rdfs:label rdf:datatype="&xsd;string">PHYLIPTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000074"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000070 -->
<owl:Class rdf:about="&obo;CDAO_0000070">
<rdfs:label rdf:datatype="&xsd;string">Subtree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000110"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000155"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000110"/>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000071 -->
<owl:Class rdf:about="&obo;CDAO_0000071">
<rdfs:label rdf:datatype="&xsd;string">Character</rdfs:label>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000153"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000098"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:comment rdf:datatype="&xsd;string">Traits shown to be relevant for phylogenetic classification</rdfs:comment>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000072 -->
<owl:Class rdf:about="&obo;CDAO_0000072">
<rdfs:label rdf:datatype="&xsd;string">GalledTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000006"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000073 -->
<owl:Class rdf:about="&obo;CDAO_0000073">
<rdfs:label rdf:datatype="&xsd;string">SpeciesTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000110"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000074 -->
<owl:Class rdf:about="&obo;CDAO_0000074">
<rdfs:label rdf:datatype="&xsd;string">TreeFormat</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000044"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000075 -->
<owl:Class rdf:about="&obo;CDAO_0000075">
<rdfs:label rdf:datatype="&xsd;string">StandardCharacter</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000111"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000076 -->
<owl:Class rdf:about="&obo;CDAO_0000076">
<rdfs:label rdf:datatype="&xsd;string">AminoAcidResidue</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000034"/>
<dc:description>This class will be declared equivalent ot the amino acid class description imported</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000077 -->
<owl:Class rdf:about="&obo;CDAO_0000077">
<rdfs:label rdf:datatype="&xsd;string">geneDuplication</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000064"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000078 -->
<owl:Class rdf:about="&obo;CDAO_0000078">
<rdfs:label rdf:datatype="&xsd;string">CompoundCharacter</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000111"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000170"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000136"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000142"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000071"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000153"/>
<owl:allValuesFrom rdf:resource="&obo;CDAO_0000136"/>
</owl:Restriction>
</rdfs:subClassOf>
<dc:description>A character that could be divided into separate characters but is not due to the non-independence of changes that would result, e.g., as in the case of a subsequence that is either present or absent as a block.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000079 -->
<owl:Class rdf:about="&obo;CDAO_0000079">
<rdfs:label rdf:datatype="&xsd;string">SIMMAPTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000074"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000080 -->
<owl:Class rdf:about="&obo;CDAO_0000080">
<rdfs:label rdf:datatype="&xsd;string">CommonAncestralNode</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000026"/>
<rdfs:subClassOf>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000053"/>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000174"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000053"/>
</owl:Restriction>
</owl:unionOf>
</owl:Class>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000081 -->
<owl:Class rdf:about="&obo;CDAO_0000081">
<rdfs:label rdf:datatype="&xsd;string">NewickTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000074"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000082 -->
<owl:Class rdf:about="&obo;CDAO_0000082">
<rdfs:label rdf:datatype="&xsd;string">TimeProportionalLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000063"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000083 -->
<owl:Class rdf:about="&obo;CDAO_0000083">
<rdfs:label rdf:datatype="&xsd;string">DiscreteCharDistanceLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000100"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000084 -->
<owl:Class rdf:about="&obo;CDAO_0000084">
<rdfs:label rdf:datatype="&xsd;string">StarTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000012"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000149"/>
<owl:allValuesFrom rdf:resource="&obo;CDAO_0000108"/>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000085 -->
<owl:Class rdf:about="&obo;CDAO_0000085">
<rdfs:label rdf:datatype="&xsd;string">FullyResolvedUnrootedTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000018"/>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000088"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000086 -->
<owl:Class rdf:about="&obo;CDAO_0000086">
<rdfs:label rdf:datatype="&xsd;string">ParaphyleticGroup</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000127"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000199"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000070"/>
</owl:Restriction>
</rdfs:subClassOf>
<owl:disjointWith rdf:resource="&obo;CDAO_0000129"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000087 -->
<owl:Class rdf:about="&obo;CDAO_0000087">
<rdfs:label rdf:datatype="&xsd;string">geneticEvent</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000041"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000088 -->
<owl:Class rdf:about="&obo;CDAO_0000088">
<rdfs:label rdf:datatype="&xsd;string">UnrootedTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000110"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000089 -->
<owl:Class rdf:about="&obo;CDAO_0000089">
<rdfs:label rdf:datatype="&xsd;string">CategoricalStateDatum</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000098"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000090 -->
<owl:Class rdf:about="&obo;CDAO_0000090">
<rdfs:label rdf:datatype="&xsd;string">DiscreteCharLikelihoodLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000100"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000091 -->
<owl:Class rdf:about="&obo;CDAO_0000091">
<rdfs:label rdf:datatype="&xsd;string">CharacterStateDomain</rdfs:label>
<dc:description>The universe of possible states for a particular type of character, e.g., the states of an Amino_Acid character come from the Amino_Acid domain.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000092 -->
<owl:Class rdf:about="&obo;CDAO_0000092">
<rdfs:label rdf:datatype="&xsd;string">CoordinateList</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000022"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000093 -->
<owl:Class rdf:about="&obo;CDAO_0000093">
<rdfs:label rdf:datatype="&xsd;string">GammaDistribution</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000020"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000094 -->
<owl:Class rdf:about="&obo;CDAO_0000094">
<rdfs:label rdf:datatype="&xsd;string">DesoxiRibonucleotideResidueCharacter</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000115"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000195"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000002"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000153"/>
<owl:allValuesFrom rdf:resource="&obo;CDAO_0000002"/>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000095 -->
<owl:Class rdf:about="&obo;CDAO_0000095">
<rdfs:label rdf:datatype="&xsd;string">CoordinateRange</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000022"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000096 -->
<owl:Class rdf:about="&obo;CDAO_0000096">
<rdfs:label rdf:datatype="&xsd;string">ReticulateEvolution</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000006"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000097 -->
<owl:Class rdf:about="&obo;CDAO_0000097">
<rdfs:label rdf:datatype="&xsd;string">hereditaryChange</rdfs:label>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000186"/>
<owl:onClass rdf:resource="&obo;CDAO_0000091"/>
<owl:qualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:qualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000159"/>
<owl:onClass rdf:resource="&obo;CDAO_0000091"/>
<owl:qualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:qualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000169"/>
<owl:onClass rdf:resource="&obo;CDAO_0000071"/>
<owl:qualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:qualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000098 -->
<owl:Class rdf:about="&obo;CDAO_0000098">
<rdfs:label rdf:datatype="&xsd;string">CharacterStateDatum</rdfs:label>
<rdfs:subClassOf rdf:resource="&owl;Thing"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000205"/>
<owl:onClass rdf:resource="&obo;CDAO_0000071"/>
<owl:qualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:qualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000191"/>
<owl:onClass rdf:resource="&obo;CDAO_0000138"/>
<owl:qualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:qualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
<dc:description>The instance of a given character for a given TU. Its state is an object property drawn from a particular character state domain, e.g., the state of an Amino_Acid_State_Datum is an object property drawn from the domain Amino_Acid.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000099 -->
<owl:Class rdf:about="&obo;CDAO_0000099">
<rdfs:label rdf:datatype="&xsd;string">Edge</rdfs:label>
<rdfs:subClassOf rdf:resource="&owl;Thing"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000193"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000101"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000162"/>
<owl:onClass rdf:resource="&obo;CDAO_0000140"/>
<owl:qualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">2</owl:qualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
<dc:description>An edge connecting two nodes in a (Phylogenetic) Tree or Network, also known as a 'branch'. Edges may have attributes such as length, degree of support, and direction. An edge can be a surrogate for a 'split' or bipartition, since each edge in a tree divides the terminal nodes into two sets.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000100 -->
<owl:Class rdf:about="&obo;CDAO_0000100">
<rdfs:label rdf:datatype="&xsd;string">DiscreteCharacterLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000063"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000101 -->
<owl:Class rdf:about="&obo;CDAO_0000101">
<rdfs:label rdf:datatype="&xsd;string">EdgeAnnotation</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000040"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000102 -->
<owl:Class rdf:about="&obo;CDAO_0000102">
<rdfs:label rdf:datatype="&xsd;string">FullyResolvedRootedTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000012"/>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000018"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000178"/>
<owl:allValuesFrom>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000033"/>
<rdf:Description rdf:about="&obo;CDAO_0000099"/>
<rdf:Description rdf:about="&obo;CDAO_0000108"/>
</owl:unionOf>
</owl:Class>
</owl:allValuesFrom>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000103 -->
<owl:Class rdf:about="&obo;CDAO_0000103">
<rdfs:label rdf:datatype="&xsd;string">GrafenLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000063"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000104 -->
<owl:Class rdf:about="&obo;CDAO_0000104">
<rdfs:label rdf:datatype="&xsd;string">CoordinateSystem</rdfs:label>
<rdfs:subClassOf rdf:resource="&owl;Thing"/>
<dc:description>A reference to an external coordinate system. Coordinates for data must refer to some such external coordinate system.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000105 -->
<owl:Class rdf:about="&obo;CDAO_0000105">
<rdfs:label rdf:datatype="&xsd;string">GenBankDataMatrix</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000107"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000107 -->
<owl:Class rdf:about="&obo;CDAO_0000107">
<rdfs:label rdf:datatype="&xsd;string">DataMatrixFormat</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000025"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000108 -->
<owl:Class rdf:about="&obo;CDAO_0000108">
<rdfs:label rdf:datatype="&xsd;string">TerminalNode</rdfs:label>
<owl:equivalentClass>
<owl:Class>
<owl:intersectionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000140"/>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000149"/>
<owl:allValuesFrom>
<owl:Class>
<owl:complementOf rdf:resource="&obo;CDAO_0000140"/>
</owl:Class>
</owl:allValuesFrom>
</owl:Restriction>
</owl:intersectionOf>
</owl:Class>
</owl:equivalentClass>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000140"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000109 -->
<owl:Class rdf:about="&obo;CDAO_0000109">
<rdfs:label rdf:datatype="&xsd;string">RibonucleotideResidueCharacter</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000115"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000153"/>
<owl:allValuesFrom rdf:resource="&obo;CDAO_0000057"/>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000110 -->
<owl:Class rdf:about="&obo;CDAO_0000110">
<rdfs:label rdf:datatype="&xsd;string">Tree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000006"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000111 -->
<owl:Class rdf:about="&obo;CDAO_0000111">
<rdfs:label rdf:datatype="&xsd;string">CategoricalCharacter</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000071"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000112 -->
<owl:Class rdf:about="&obo;CDAO_0000112">
<rdfs:label rdf:datatype="&xsd;string">AminoAcidResidueStateDatum</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000050"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000113 -->
<owl:Class rdf:about="&obo;CDAO_0000113">
<rdfs:label rdf:datatype="&xsd;string">PHYLIPDataMatrix</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000107"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000114 -->
<owl:Class rdf:about="&obo;CDAO_0000114">
<rdfs:label rdf:datatype="&xsd;string">ContinuousCharLikelihoodLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000009"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000115 -->
<owl:Class rdf:about="&obo;CDAO_0000115">
<rdfs:label rdf:datatype="&xsd;string">MolecularCharacter</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000111"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000116 -->
<owl:Class rdf:about="&obo;CDAO_0000116">
<rdfs:label rdf:datatype="&xsd;string">hereditaryPersistance</rdfs:label>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000190"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000097"/>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000117 -->
<owl:Class rdf:about="&obo;CDAO_0000117">
<rdfs:label rdf:datatype="&xsd;string">SetOfCharacters</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000118"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000118 -->
<owl:Class rdf:about="&obo;CDAO_0000118">
<rdfs:label rdf:datatype="&xsd;string">SetOfThings</rdfs:label>
<rdfs:subClassOf rdf:resource="&owl;Thing"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000198"/>
<owl:allValuesFrom>
<owl:Class>
<owl:unionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000071"/>
<rdf:Description rdf:about="&obo;CDAO_0000117"/>
</owl:unionOf>
</owl:Class>
</owl:allValuesFrom>
</owl:Restriction>
</rdfs:subClassOf>
<dc:description>The class is used to describe either colletions of characters or higher order grouping (e.g., groups of groups of characters). This extends the CharSet block of NEXUS.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000120 -->
<owl:Class rdf:about="&obo;CDAO_0000120">
<rdfs:label rdf:datatype="&xsd;string">Sequence</rdfs:label>
<rdfs:subClassOf rdf:resource="&owl;Thing"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000178"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000098"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000178"/>
<owl:allValuesFrom>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000151"/>
<owl:onClass rdf:resource="&obo;CDAO_0000022"/>
<owl:minQualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:minQualifiedCardinality>
</owl:Restriction>
</owl:allValuesFrom>
</owl:Restriction>
</rdfs:subClassOf>
<dc:description>A set of ordered states, typically the residues in a macromolecular sequence.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000121 -->
<owl:Class rdf:about="&obo;CDAO_0000121">
<rdfs:label rdf:datatype="&xsd;string">speciation</rdfs:label>
<owl:equivalentClass rdf:resource="&obo;CDAO_0000122"/>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000064"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000122 -->
<owl:Class rdf:about="&obo;CDAO_0000122">
<rdfs:label rdf:datatype="&xsd;string">cladogenesis</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000064"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000124 -->
<owl:Class rdf:about="&obo;CDAO_0000124">
<rdfs:label rdf:datatype="&xsd;string">Bifurcation</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000026"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000177"/>
<owl:cardinality rdf:datatype="&xsd;nonNegativeInteger">2</owl:cardinality>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000125 -->
<owl:Class rdf:about="&obo;CDAO_0000125">
<rdfs:label rdf:datatype="&xsd;string">DiscreteCharBayesianLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000100"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000126 -->
<owl:Class rdf:about="&obo;CDAO_0000126">
<rdfs:label rdf:datatype="&xsd;string">TaxonomicLink</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000066"/>
<dc:description>Link to an externally defined taxonomic hierarchy.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000127 -->
<owl:Class rdf:about="&obo;CDAO_0000127">
<rdfs:label rdf:datatype="&xsd;string">MonophyleticGroup</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000006"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000128 -->
<owl:Class rdf:about="&obo;CDAO_0000128">
<rdfs:label rdf:datatype="&xsd;string">molecularRecombination</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000132"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000129 -->
<owl:Class rdf:about="&obo;CDAO_0000129">
<rdfs:label rdf:datatype="&xsd;string">HolophyleticGroup</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000127"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000130 -->
<owl:Class rdf:about="&obo;CDAO_0000130">
<rdfs:label rdf:datatype="&xsd;string">FullyResolvedTree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000110"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000131 -->
<owl:Class rdf:about="&obo;CDAO_0000131">
<rdfs:label rdf:datatype="&xsd;string">AminoAcidResidueCharacter</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000115"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000168"/>
<owl:someValuesFrom rdf:resource="&obo;CDAO_0000112"/>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000153"/>
<owl:allValuesFrom rdf:resource="&obo;CDAO_0000112"/>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000132 -->
<owl:Class rdf:about="&obo;CDAO_0000132">
<rdfs:label rdf:datatype="&xsd;string">recombination</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000087"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000133 -->
<owl:Class rdf:about="&obo;CDAO_0000133">
<rdfs:label rdf:datatype="&xsd;string">DesoxiRibonucleotideResidue</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000034"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000134 -->
<owl:Class rdf:about="&obo;CDAO_0000134">
<rdfs:label rdf:datatype="&xsd;string">RootedSubtree</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000012"/>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000070"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000136 -->
<owl:Class rdf:about="&obo;CDAO_0000136">
<rdfs:label rdf:datatype="&xsd;string">CompoundStateDatum</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000089"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000137 -->
<owl:Class rdf:about="&obo;CDAO_0000137">
<rdfs:label rdf:datatype="&xsd;string">GapCost</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000007"/>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000138 -->
<owl:Class rdf:about="&obo;CDAO_0000138">
<rdfs:label rdf:datatype="&xsd;string">TU</rdfs:label>
<rdfs:subClassOf rdf:resource="&owl;Thing"/>
<dc:description>A unit of analysis that may be tied to a node in a tree and to a row in a character matrix. It subsumes the traditional concepts of 'OTU' and 'HTU'.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000139 -->
<owl:Class rdf:about="&obo;CDAO_0000139">
<rdfs:label rdf:datatype="&xsd;string">DirectedEdge</rdfs:label>
<owl:equivalentClass>
<owl:Class>
<owl:intersectionOf rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000099"/>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000201"/>
<owl:onClass rdf:resource="&obo;CDAO_0000140"/>
<owl:qualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:qualifiedCardinality>
</owl:Restriction>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000209"/>
<owl:onClass rdf:resource="&obo;CDAO_0000140"/>
<owl:qualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:qualifiedCardinality>
</owl:Restriction>
</owl:intersectionOf>
</owl:Class>
</owl:equivalentClass>
<dc:description>A directed edge. Rooted trees have directed edges. The direction is specified by way of the parent and child relationships of nodes that the edge connects.</dc:description>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000140 -->
<owl:Class rdf:about="&obo;CDAO_0000140">
<rdfs:label rdf:datatype="&xsd;string">Node</rdfs:label>
<rdfs:subClassOf rdf:resource="&owl;Thing"/>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000143"/>
<owl:onClass rdf:resource="&obo;CDAO_0000139"/>
<owl:maxQualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:maxQualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
<rdfs:subClassOf>
<owl:Restriction>
<owl:onProperty rdf:resource="&obo;CDAO_0000194"/>
<owl:onClass rdf:resource="&obo;CDAO_0000006"/>
<owl:minQualifiedCardinality rdf:datatype="&xsd;nonNegativeInteger">1</owl:minQualifiedCardinality>
</owl:Restriction>
</rdfs:subClassOf>
</owl:Class>
<!-- http://purl.obolibrary.org/obo/CDAO_0000141 -->
<owl:Class rdf:about="&obo;CDAO_0000141">
<rdfs:label rdf:datatype="&xsd;string">ContinuousCharDistanceLengthType</rdfs:label>
<rdfs:subClassOf rdf:resource="&obo;CDAO_0000009"/>
</owl:Class>
<!--
///////////////////////////////////////////////////////////////////////////////////////
//
// Individuals
//
///////////////////////////////////////////////////////////////////////////////////////
-->
<!-- http://purl.obolibrary.org/obo/CDAO_0000220 -->
<owl:Thing rdf:about="&obo;CDAO_0000220">
<rdf:type rdf:resource="&obo;CDAO_0000133"/>
<rdf:type rdf:resource="&owl;NamedIndividual"/>
<rdfs:label rdf:datatype="&xsd;string">dA</rdfs:label>
</owl:Thing>
<!-- http://purl.obolibrary.org/obo/CDAO_0000221 -->
<owl:Thing rdf:about="&obo;CDAO_0000221">
<rdf:type rdf:resource="&obo;CDAO_0000015"/>
<rdf:type rdf:resource="&owl;NamedIndividual"/>
<rdfs:label rdf:datatype="&xsd;string">absent</rdfs:label>
</owl:Thing>
<!-- http://purl.obolibrary.org/obo/CDAO_0000222 -->
<owl:Thing rdf:about="&obo;CDAO_0000222">
<rdf:type rdf:resource="&obo;CDAO_0000015"/>
<rdf:type rdf:resource="&owl;NamedIndividual"/>
<rdfs:label rdf:datatype="&xsd;string">unknown</rdfs:label>
</owl:Thing>
<!-- http://purl.obolibrary.org/obo/CDAO_0000223 -->
<owl:Thing rdf:about="&obo;CDAO_0000223">
<rdf:type rdf:resource="&obo;CDAO_0000015"/>
<rdf:type rdf:resource="&owl;NamedIndividual"/>
<rdfs:label rdf:datatype="&xsd;string">gap</rdfs:label>
</owl:Thing>
<!-- http://purl.obolibrary.org/obo/CDAO_0000224 -->
<owl:Thing rdf:about="&obo;CDAO_0000224">
<rdf:type rdf:resource="&obo;CDAO_0000133"/>
<rdf:type rdf:resource="&owl;NamedIndividual"/>
<rdfs:label rdf:datatype="&xsd;string">dG</rdfs:label>
</owl:Thing>
<!-- http://purl.obolibrary.org/obo/CDAO_0000225 -->
<owl:Thing rdf:about="&obo;CDAO_0000225">
<rdf:type rdf:resource="&obo;CDAO_0000057"/>
<rdf:type rdf:resource="&owl;NamedIndividual"/>
<rdfs:label rdf:datatype="&xsd;string">rU</rdfs:label>
</owl:Thing>
<!-- http://purl.obolibrary.org/obo/CDAO_0000226 -->
<owl:Thing rdf:about="&obo;CDAO_0000226">
<rdf:type rdf:resource="&obo;CDAO_0000133"/>
<rdf:type rdf:resource="&owl;NamedIndividual"/>
<rdfs:label rdf:datatype="&xsd;string">dC</rdfs:label>
</owl:Thing>
<!-- http://purl.obolibrary.org/obo/CDAO_0000227 -->
<owl:Thing rdf:about="&obo;CDAO_0000227">
<rdf:type rdf:resource="&obo;CDAO_0000133"/>
<rdf:type rdf:resource="&owl;NamedIndividual"/>
<rdfs:label rdf:datatype="&xsd;string">dT</rdfs:label>
</owl:Thing>
<!--
///////////////////////////////////////////////////////////////////////////////////////
//
// General axioms
//
///////////////////////////////////////////////////////////////////////////////////////
-->
<rdf:Description>
<rdf:type rdf:resource="&owl;AllDisjointClasses"/>
<owl:members rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000068"/>
<rdf:Description rdf:about="&obo;CDAO_0000094"/>
<rdf:Description rdf:about="&obo;CDAO_0000131"/>
</owl:members>
</rdf:Description>
<rdf:Description>
<rdf:type rdf:resource="&owl;AllDisjointClasses"/>
<owl:members rdf:parseType="Collection">
<rdf:Description rdf:about="&obo;CDAO_0000002"/>
<rdf:Description rdf:about="&obo;CDAO_0000019"/>
<rdf:Description rdf:about="&obo;CDAO_0000112"/>
</owl:members>
</rdf:Description>
</rdf:RDF>
<!-- Generated by the OWL API (version 3.2.3.1824) http://owlapi.sourceforge.net -->
'''
cdao_elements = {}
root = ET.fromstring(cdao_owl)
for node_type in 'ObjectProperty', 'Class', 'DatatypeProperty':
for element in root.findall('{http://www.w3.org/2002/07/owl#}%s' % node_type):
obo = element.attrib['{http://www.w3.org/1999/02/22-rdf-syntax-ns#}about'].split('/')[-1]
cdao = element.find('{http://www.w3.org/2000/01/rdf-schema#}label').text
cdao_elements[cdao] = obo
| [
"eric.talevich@gmail.com"
] | eric.talevich@gmail.com |
96d51106afa543e4c0fa9dd52a64b843819f1c4e | 23130cd12e38dbce8db8102810edaad70b240ae2 | /lintcode/604.py | 87ad2b4e294171a68625eef8adc80e2ab6a38d0d | [
"MIT"
] | permissive | kangli-bionic/algorithm | ee6687c82101088db20f10fb958b4e45e97d3d31 | c3c38723b9c5f1cc745550d89e228f92fd4abfb2 | refs/heads/master | 2023-01-05T09:29:33.204253 | 2020-10-25T17:29:38 | 2020-10-25T17:29:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 654 | py | """
604. Window Sum
https://www.lintcode.com/problem/window-sum/description
"""
class Solution:
"""
@param nums: a list of integers.
@param k: length of window.
@return: the sum of the element inside the window at each moving.
"""
def winSum(self, nums, k):
n = len(nums)
right = 0
curr_sum = 0
result = []
for left in range(n):
while right < n and right - left < k:
curr_sum += nums[right]
right += 1
result.append(curr_sum)
if right >= n:
break
curr_sum -= nums[left]
return result
| [
"hipaulshi@gmail.com"
] | hipaulshi@gmail.com |
252e619211ed66f1c15ae2ad2e998cdfb7eb987a | a8289cb7273245e7ec1e6079c7f266db4d38c03f | /Django_Viewsets_RESTAPI/Viewsets_RESTAPI/urls.py | 4fc6746613611cd39c4e03d1f948db1a31cf403b | [] | no_license | palmarytech/Python_Snippet | 6acbd572d939bc9d5d765800f35a0204bc044708 | 41b4ebe15509d166c82edd23b713a1f3bf0458c5 | refs/heads/master | 2022-10-06T22:51:00.469383 | 2020-03-13T08:32:11 | 2020-03-13T08:32:11 | 272,350,189 | 1 | 0 | null | 2020-06-15T05:30:44 | 2020-06-15T05:30:44 | null | UTF-8 | Python | false | false | 1,449 | py | """Viewsets_RESTAPI URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
# from musics import views # If import mutiple models at the same time, can't write this way.
from musics.views import MusicViewSet
from shares.views import ShareViewSet
router = DefaultRouter()
router.register(r'music', MusicViewSet, base_name='music')
router.register(r'shares', ShareViewSet, base_name='share')
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api/', include(router.urls), name="api"),
# path("api/", include("languages.urls")),
path("", include("languages.urls")),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) # Adding this line will make the login button show up
]
| [
"leamon.lee13@gmail.com"
] | leamon.lee13@gmail.com |
5837f376ec08bb98bb6bcdad25b085acba191a75 | 8dbc30ab4f0c76bfc08784a6e06b68cae61888a7 | /collective/fbshare/browser/view.py | c2f66ea6010a51dbbeb56be090b22a4499fd00fd | [] | no_license | RedTurtle/collective.fbshare | 11d19b5ab91b7ae728d3602b30d0f1b9bec3fe1a | 66d8a5092a31a23d6b508c8fb23c19da548d7c2f | refs/heads/master | 2021-07-11T13:36:37.216587 | 2016-04-19T06:56:13 | 2016-04-19T06:56:13 | 5,167,545 | 1 | 2 | null | 2021-03-25T13:55:45 | 2012-07-24T15:39:35 | Python | UTF-8 | Python | false | false | 934 | py | # -*- coding: utf-8 -*-
from collective.fbshare.interfaces import IFbShareSettings
from plone.registry.interfaces import IRegistry
from Products.Five.browser import BrowserView
from zExceptions import NotFound
from zope.component import queryUtility
class ShareDefaultImage(BrowserView):
"""Return a bytestream with the default image"""
def data(self):
registry = queryUtility(IRegistry)
settings = registry.forInterface(IFbShareSettings, check=False)
return settings.default_image
def __call__(self, *args, **kwargs):
bytes = self.data()
if bytes:
response = self.request.response
response.setHeader('Content-Type','image/jpg')
response.setHeader('Content-Disposition', 'inline; filename=collective.fbshare.default_image.jpg')
response.write(bytes)
return
# no data? no image
raise NotFound() | [
"luca@keul.it"
] | luca@keul.it |
1ac4d89906a70db4ec6a361cbe5ae3f6b506fe00 | 12ee4c670e3be681376b07af291c22175b680447 | /videos/migrations/0002_video_category.py | 32a4b76909e59df49cff7196d5ca3d8c4321a06e | [] | no_license | chayan007/miworld | b1cd0febac40d665e8925fea5872df8f27456f05 | 969c551acbd9b3872988756aa4bbab7f42a990cc | refs/heads/master | 2022-12-11T08:37:22.173629 | 2019-02-24T12:19:33 | 2019-02-24T12:19:33 | 172,792,993 | 0 | 0 | null | 2022-11-22T03:22:19 | 2019-02-26T21:25:19 | JavaScript | UTF-8 | Python | false | false | 384 | py | # Generated by Django 2.1.4 on 2019-02-04 10:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('videos', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='video',
name='category',
field=models.CharField(max_length=50, null=True),
),
]
| [
"sonicxxx7@gmail.com"
] | sonicxxx7@gmail.com |
a749526e7102540e5a156df975af7fdbfaa9190d | e23a4f57ce5474d468258e5e63b9e23fb6011188 | /070_oop/001_classes/_exercises/_templates/Python_3_Deep_Dive_Part_4/Section 14 Metaprogramming/156. Metaprogramming Application 2.py | ff9aa57dd6c6305e1ed6ad98c8b863c7473ec381 | [] | no_license | syurskyi/Python_Topics | 52851ecce000cb751a3b986408efe32f0b4c0835 | be331826b490b73f0a176e6abed86ef68ff2dd2b | refs/heads/master | 2023-06-08T19:29:16.214395 | 2023-05-29T17:09:11 | 2023-05-29T17:09:11 | 220,583,118 | 3 | 2 | null | 2023-02-16T03:08:10 | 2019-11-09T02:58:47 | Python | UTF-8 | Python | false | false | 7,619 | py | # %%
'''
### Metaprogramming - Application 2
'''
# %%
'''
There's another pattern we can implement using metaprogramming - Singletons.
'''
# %%
'''
If you read online, you'll see that singleton objects are controversial in Python.
I'm not going to get into a debate on this, other than to say I do not use singleton objects, not because I have deep
thoughts about it (or even shallow ones for that matter), but rather because I have never had a need for them.
'''
# %%
'''
However, the question often comes up, so here it is - the metaclass way of implementing the singleton pattern.
Whether you think you should use it or not, is entirely up to you!
'''
# %%
'''
We have seen singleton objects - objects such as `None`, `True` or `False` for example.
'''
# %%
'''
No matter where we create them in our code, they always refer to the **same** object.
'''
# %%
'''
We can recover the type used to create `None` objects:
'''
# %%
NoneType = type(None)
# %%
'''
And now we can create multiple instances of that type:
'''
# %%
n1 = NoneType()
n2 = NoneType()
# %%
id(n1), id(n2)
# %%
'''
As you can see, any instance of `NoneType` is actually the **same** object.
'''
# %%
'''
The same holds true for booleans:
'''
# %%
b1 = bool([])
b2 = bool("")
# %%
id(b1), id(b2)
# %%
'''
These are all examples of singleton objects. Now matter how we create them, we always end up with a reference to
the same instance.
'''
# %%
'''
There is no built-in mechanism to Python for singleton objects, so we have to do it ourselves.
'''
# %%
'''
The basic idea is this:
When an instance of the class is being created (but **before** the instance is actually created), check if an instance
has already been created, in which case return that instance, otherwise, create a new instance and store that instance
reference somewhere so we can recover it the next time an instance is requested.
'''
# %%
'''
We could do it entirely in the class itself, without any metaclasses, using the `__new__` method.
We can start with this:
'''
# %%
class Hundred:
def __new__(cls):
new_instance = super().__new__(cls)
setattr(new_instance, 'name', 'hundred')
setattr(new_instance, 'value', 100)
return new_instance
# %%
h1 = Hundred()
# %%
vars(h1)
# %%
'''
But of course, this is not a singleton object.
'''
# %%
h2 = Hundred()
# %%
print(h1 is h2)
# %%
'''
So, let's fix this to make it a singleton:
'''
# %%
class Hundred:
_existing_instance = None # a class attribute!
def __new__(cls):
if not cls._existing_instance:
print('creating new instance...')
new_instance = super().__new__(cls)
setattr(new_instance, 'name', 'hundred')
setattr(new_instance, 'value', 100)
cls._existing_instance = new_instance
else:
print('instance exists already, using that one...')
return cls._existing_instance
# %%
h1 = Hundred()
# %%
h2 = Hundred()
# %%
print(h1 is h2)
# %%
'''
And there you are, we have a singleton object.
'''
# %%
'''
So this works, but if you need to have multiple of these singleton objects, the code will just become repetitive.
'''
# %%
'''
Metaclasses to the rescue!
'''
# %%
'''
Remember what we are trying to do:
If we create two instances of our class `Hundred` we expect the same instance back.
'''
# %%
'''
But how do we create an instance of a class - we **call** it, so `Hundred()`.
'''
# %%
'''
Which `__call__` method is that? It is not the one in the `Hundred` class, that would make **instances** of `Hundred`
callable, it is the `__call__` method in the **metaclass**.
'''
# %%
'''
So, we need to override the `__call__` in our metaclass.
'''
# %%
class Singleton(type):
def __call__(cls, *args, **kwargs):
print(f'Request received to create an instance of class: {cls}...')
return super().__call__(*args, **kwargs)
# %%
class Hundred(metaclass=Singleton):
value = 100
# %%
h = Hundred()
# %%
h.value
# %%
'''
OK, that works, but now we need to make it into a singleton instance.
'''
# %%
'''
We have to be careful here. Initially we had used the class itself (`Hundred`) to store, as a class variable, whether
an instance had already been created.
And here we could try to do the same thing.
We could store the instance as a class variable in the class of the instance being created
That's actually quite simple, since the class is received as the first argument of the `__call__` method.
'''
# %%
class Singleton(type):
def __call__(cls, *args, **kwargs):
print(f'Request received to create an instance of class: {cls}...')
if getattr(cls, 'existing_instance', None) is None:
print('Creating instance for the first time...')
setattr(cls, 'existing_instance', super().__call__(*args, **kwargs))
else:
print('Using existing instance...')
return getattr(cls, 'existing_instance')
# %%
class Hundred(metaclass=Singleton):
value = 100
# %%
h1 = Hundred()
# %%
h2 = Hundred()
# %%
print(h1 is h2, h1.value, h2.value)
# %%
'''
So that seems to work just fine. Let's create another singleton class and see if things still work.
'''
# %%
class Thousand(metaclass=Singleton):
value = 1000
# %%
t1 = Thousand()
# %%
t2 = Thousand()
# %%
print(h1 is h2, h1.value, h2.value)
# %%
print(t1 is t2, t1.value, t2.value)
# %%
print(h1 is t1, h2 is t2)
# %%
'''
So far so good.
'''
# %%
'''
Finally let's make sure everything works with **inheritance** too - if we inherit from a Singleton class, that subclass
should also be a singleton.
'''
# %%
class HundredFold(Hundred):
value = 100 * 100
# %%
hf1 = HundredFold()
# %%
'''
Whaaat? Using existing instance? But this is the first time we created it!!
'''
# %%
'''
The problem is this: How are we checking if an instance has already been created?
'''
# %%
'''
We did this:
```if getattr(cls, 'existing_instance')```
'''
# %%
'''
But since `HundredFold` inherits from `Hundred`, it also inherited the class attribute `existing_instance`.
'''
# %%
'''
This means we have to be a bit more careful in our metaclass, we need to see if we have an instance of the **specific**
class already created - and we cannot rely on storing a class attribute in the classes themselves since that breaks
the pattern when subclassing.
'''
# %%
'''
So, instead, we are going to store the class, and the instance of that class, in a dictionary **in the metaclass**
itself, and use that dictionary to lookup the existing instance (if any) for a specific class.
'''
# %%
class Singleton(type):
instances = {}
def __call__(cls, *args, **kwargs):
print(f'Request received to create an instance of class: {cls}...')
existing_instance = Singleton.instances.get(cls, None)
if existing_instance is None:
print('Creating instance for the first time...')
existing_instance = super().__call__(*args, **kwargs)
Singleton.instances[cls] = existing_instance
else:
print('Using existing instance...')
return existing_instance
# %%
class Hundred(metaclass=Singleton):
value = 100
class Thousand(metaclass=Singleton):
value = 1000
class HundredFold(Hundred):
value = 100 * 100
# %%
h1 = Hundred()
h2 = Hundred()
# %%
t1 = Thousand()
t2 = Thousand()
# %%
hf1 = HundredFold()
hf2 = HundredFold()
# %%
print(h1 is h2, t1 is t2, hf1 is hf2)
# %%
print(h1.value, h2.value, t1.value, t2.value, hf1.value, hf2.value)
# %%
'''
And just to make sure :-)
'''
# %%
print(h1 is hf1) | [
"sergejyurskyj@yahoo.com"
] | sergejyurskyj@yahoo.com |
176397951d78145067e5b871383ecc4d42840ee2 | 05ba1957e63510fd8f4f9a3430ec6875d9ecb1cd | /.history/fh/c_20200819004934.py | 6424d258230e0c58a1cdbfe7cdc81b12ec0b9785 | [] | no_license | cod-lab/try | 906b55dd76e77dbb052603f0a1c03ab433e2d4d1 | 3bc7e4ca482459a65b37dda12f24c0e3c71e88b6 | refs/heads/master | 2021-11-02T15:18:24.058888 | 2020-10-07T07:21:15 | 2020-10-07T07:21:15 | 245,672,870 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,919 | py | import fileinput as fi
import requests as r
import pprint as p
import sys as s
# Get Current List
def read_file(file,current_list):
with open(file,'r') as f:
for i, line in enumerate(f):
if 37<i<43:
current_list[i] = line # current_list[i] = current_list[i][:-1] # also works-1
# Get New List
def get_repos_list(user,new_list):
payload = {'sort': 'created'}
# response = re.get('https://api.github.com/users/cod-lab/repos?sort=created, timeout=10) # also works
response = r.get('https://api.github.com/users/' + user + '/repos', params=payload, timeout=10)
result = response.json() # got list of all public repos
# getting filtered list (latest 5 public repos which r not forked)
j=1
for i in range(len(result)):
if result[i]['fork'] == False:
new_list[j+37] = "* [" + result[i]['name'] + "](" + result[i]['html_url'] + ")\n"
j+=1
if j>5: break
if len(new_list)<5: s.exit("\nError: less than 5 repos available") # terminate prgm right away after printing msg
# OverWrite New List to file if there's any difference
def write_file(file,current_list,new_list):
for line in fi.FileInput(file,inplace=1):
for i in current_list:
if current_list[i] in line: # if current_list[i]+"\n" == line: # also works-1
line = new_list[i] # line = new_list[i]+"\n" # also works-1
print(line,end='')
user='cod-lab'
file='a.md'
current_list={}
new_list={}
# print('\nread_file block----------------------\n')
# try: read_file(file,current_list)
read_file(file,current_list)
# except FileNotFoundError: s.exit('No such file!!\nEnter correct file name..') # terminate prgm right away after printing msg
# print('\nread_file block end------------------\n')
# print('\nget_repos block----------------------\n')
# try: get_repos_list(user,new_list)
get_repos_list(user,new_list)
# except r.exceptions.ConnectTimeout: s.exit('The server is not responding currently!!\nPlease try again later..') # problem connecting srvr or srvr not responding # terminate prgm right away after printing msg
# except r.exceptions.ReadTimeout: s.exit('The server is not responding currently!!\nPlease try again later..') # unable to read received response # terminate prgm right away after printing msg
print('\nget_repos block end------------------\n')
# '''
print("current_list: ")
p.pprint(current_list, indent=2, width=3)
print("\nnew_list: ")
p.pprint(new_list, indent=2, width=3)
# '''
diff=0
for i in range(5):
if current_list[i+38] != new_list[i+38]: diff+=1
print("\ndiff: ",diff,"\n")
if diff>0:
print('\nwrite_file block----------------------\n')
write_file(file,current_list,new_list)
print('\nwrite_file block end------------------\n')
| [
"arihant806@gmail.com"
] | arihant806@gmail.com |
c7d7aa6f65faeb715e9af1f895734602000e741c | df3c8c521a51f2b412118bd9d0e477da06a3b7cc | /views/get_reactions_to_post/tests/test_case_01.py | e8cc5b4a38bcf767434778e105fc1ab98edd39e3 | [] | no_license | bharatmudragada/fb_post | c30b900731db5844df6b438e5d38a0dfb607412a | c5e7bb185a561bdcfcd7b2e30264554b07106044 | refs/heads/master | 2020-06-21T04:05:22.296755 | 2019-07-17T07:48:22 | 2019-07-17T07:48:22 | 197,339,717 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 928 | py | """
# TODO: Update test case description
"""
from django_swagger_utils.utils.test import CustomAPITestCase
from . import APP_NAME, OPERATION_NAME, REQUEST_METHOD, URL_SUFFIX
REQUEST_BODY = """
"""
TEST_CASE = {
"request": {
"path_params": {"post_id": "ibgroup"},
"query_params": {},
"header_params": {},
"securities": {"oauth": {"tokenUrl": "http://auth.ibtspl.com/oauth2/", "flow": "password", "scopes": ["read"], "type": "oauth2"}},
"body": REQUEST_BODY,
},
}
class TestCase01GetReactionsToPostAPITestCase(CustomAPITestCase):
app_name = APP_NAME
operation_name = OPERATION_NAME
request_method = REQUEST_METHOD
url_suffix = URL_SUFFIX
test_case_dict = TEST_CASE
def test_case(self):
self.default_test_case() # Returns response object.
# Which can be used for further response object checks.
# Add database state checks here. | [
"bharathmudragada123@gmail.com"
] | bharathmudragada123@gmail.com |
1492bd5f614068c35c19883d6fc5a9624c0ae5c8 | bcd878b91e75fc14c66943911908447078cd581e | /tensorflow_serving/example/inception_export.py | 6bcd2b36b41b18999ed0c54c1bc4ae212cfa7433 | [
"Apache-2.0"
] | permissive | cfregly/serving | 677367ffa0263f52bf4c3b06287566e20f61e77a | bdd0b47e715a596a8a927deac5018bfb656848d2 | refs/heads/master | 2021-01-14T09:42:24.046049 | 2016-04-04T21:54:08 | 2016-04-04T21:54:08 | 55,674,476 | 1 | 1 | null | 2016-04-07T07:46:01 | 2016-04-07T07:46:01 | null | UTF-8 | Python | false | false | 4,618 | py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
#!/usr/grte/v4/bin/python2.7
"""Export inception model given existing training checkpoints.
"""
import os.path
import sys
# This is a placeholder for a Google-internal import.
import tensorflow as tf
from inception import inception_model
from tensorflow_serving.session_bundle import exporter
tf.app.flags.DEFINE_string('checkpoint_dir', '/tmp/inception_train',
"""Directory where to read training checkpoints.""")
tf.app.flags.DEFINE_string('export_dir', '/tmp/inception_export',
"""Directory where to export inference model.""")
tf.app.flags.DEFINE_integer('image_size', 299,
"""Needs to provide same value as in training.""")
FLAGS = tf.app.flags.FLAGS
NUM_CLASSES = 1000
NUM_TOP_CLASSES = 5
def export():
with tf.Graph().as_default():
# Build inference model.
# Please refer to Tensorflow inception model for details.
# Input transformation.
# TODO(b/27776734): Add batching support.
jpegs = tf.placeholder(tf.string, shape=(1))
image_buffer = tf.squeeze(jpegs, [0])
# Decode the string as an RGB JPEG.
# Note that the resulting image contains an unknown height and width
# that is set dynamically by decode_jpeg. In other words, the height
# and width of image is unknown at compile-time.
image = tf.image.decode_jpeg(image_buffer, channels=3)
# After this point, all image pixels reside in [0,1)
# until the very end, when they're rescaled to (-1, 1). The various
# adjust_* ops all require this range for dtype float.
image = tf.image.convert_image_dtype(image, dtype=tf.float32)
# Crop the central region of the image with an area containing 87.5% of
# the original image.
image = tf.image.central_crop(image, central_fraction=0.875)
# Resize the image to the original height and width.
image = tf.expand_dims(image, 0)
image = tf.image.resize_bilinear(image,
[FLAGS.image_size, FLAGS.image_size],
align_corners=False)
image = tf.squeeze(image, [0])
# Finally, rescale to [-1,1] instead of [0, 1)
image = tf.sub(image, 0.5)
image = tf.mul(image, 2.0)
images = tf.expand_dims(image, 0)
# Run inference.
logits, _ = inception_model.inference(images, NUM_CLASSES + 1)
# Transform output to topK result.
values, indices = tf.nn.top_k(logits, NUM_TOP_CLASSES)
# Restore variables from training checkpoint.
variable_averages = tf.train.ExponentialMovingAverage(
inception_model.MOVING_AVERAGE_DECAY)
variables_to_restore = variable_averages.variables_to_restore()
saver = tf.train.Saver(variables_to_restore)
with tf.Session() as sess:
# Restore variables from training checkpoints.
ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
# Assuming model_checkpoint_path looks something like:
# /my-favorite-path/imagenet_train/model.ckpt-0,
# extract global_step from it.
global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
print('Successfully loaded model from %s at step=%s.' %
(ckpt.model_checkpoint_path, global_step))
else:
print('No checkpoint file found at %s' % FLAGS.checkpoint_dir)
return
# Export inference model.
model_exporter = exporter.Exporter(saver)
signature = exporter.classification_signature(
input_tensor=jpegs, classes_tensor=indices, scores_tensor=values)
model_exporter.init(default_graph_signature=signature)
model_exporter.export(FLAGS.export_dir, tf.constant(global_step), sess)
print('Successfully exported model to %s' % FLAGS.export_dir)
def main(unused_argv=None):
export()
if __name__ == '__main__':
tf.app.run() | [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
da54578f4d643573bbc62d2a04f74d415e2671eb | a6996ea8cc1f0bdcbdb0b82d514da22db48065f9 | /create_index.py | fab09a2f24c5e683db95537aa77063742160ff7d | [
"MIT"
] | permissive | katsby-skye/arxiv-search | ac275d42c2128f693653682cc8dc57a6ef9ccd99 | e5c714b474a2ac5e54452642428cee35e2a0c8b9 | refs/heads/master | 2020-04-28T07:11:50.521900 | 2019-04-18T07:32:47 | 2019-04-18T07:32:47 | 175,083,748 | 2 | 1 | MIT | 2019-04-18T07:32:49 | 2019-03-11T21:06:17 | Python | UTF-8 | Python | false | false | 387 | py | """Use this to initialize the search index for testing."""
import json
import click
from search.factory import create_ui_web_app
from search.services import index
app = create_ui_web_app()
app.app_context().push()
@app.cli.command()
def create_index():
"""Initialize the search index."""
index.current_session().create_index()
if __name__ == '__main__':
create_index()
| [
"brp53@cornell.edu"
] | brp53@cornell.edu |
989e8a3dff4b10f57408941766688533677e929a | 3dff4bef08954fadb7cc83c4f212fffa81b7d27e | /api_site/src/api_x/config/etc/beta.py | 319f422b8199fc39e3ad1d54c83a6af7b95695a7 | [] | no_license | webee/pay | 3ec91cb415d9e3addabe961448533d861c0bd67a | b48c6892686bf3f9014bb67ed119506e41050d45 | refs/heads/master | 2020-04-29T14:31:09.643993 | 2016-02-02T07:14:14 | 2016-02-02T07:14:14 | 176,198,802 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 174 | py | # coding=utf-8
class App:
TESTING = True
HOST_URL = 'http://pay.lvye.com/api/__'
CHECKOUT_URL = 'http://pay.lvye.com/__/checkout/{sn}'
TEST_CHANNELS = {'zyt_sample'}
| [
"yiwang@lvye.com"
] | yiwang@lvye.com |
87b406089d8124860e5df6cee98e2d1dc37d6514 | 92c6aa579d06d3ff58c9e6d8f5cfa696622623f5 | /flask_mysql/server.py | f8769b77b04fb73d9249cabc9e4b6c7b1d20691b | [] | no_license | askrr3/demo | 8ce6cd1cad3192b46a8583776c654ecfe2992c44 | cb7dbebf2c8cd1e363bad134e67db4a87389a0fe | refs/heads/master | 2021-01-18T22:53:26.127132 | 2016-07-20T19:38:50 | 2016-07-20T19:38:50 | 63,808,838 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 353 | py |
from flask import Flask
# import the Connector function
from mysqlconnection import MySQLConnector
app = Flask(__name__)
# connect and store the connection in "mysql" note that you pass the database name to the function
mysql = MySQLConnector(app, 'mydb')
# an example of running a query
print mysql.query_db("SELECT * FROM users")
app.run(debug=True) | [
"johndoe@example.com"
] | johndoe@example.com |
f252cdd46cf777f6aa3ce61f7216a0d67440387b | dd205a3cd8c457cfee9a1c0c1df2d3ef9d4e69d8 | /easy/jump_cloud_revisit.py | fcfd8fa7a335724596c4d29e857d137c2ceaca81 | [] | no_license | NaNdalal-dev/hacker-rank-problems | c86a2c28979391336517e6c151cbaf57542f9d58 | cce957364c4920af622afea9244b8bcc984deb62 | refs/heads/master | 2023-03-29T19:04:53.720657 | 2021-04-04T14:12:49 | 2021-04-04T14:12:49 | 332,231,011 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 333 | py | '''
Jumping on the Clouds: Revisited
https://www.hackerrank.com/challenges/jumping-on-the-clouds-revisited/problem
'''
def jumpingOnClouds(c, k):
l=len(c)
e=100
i=0
while True:
rem=(i+k)%l
if rem==0:
if c[rem]==1 :
e=e-3
break
else:
e-=1
break
if c[rem]==1 :
e=e-3
else:
e-=1
i+=k
return e
| [
"dnandalal7@gmail.com"
] | dnandalal7@gmail.com |
651f7888323079293dfce203eae4791834c80408 | a394b1053f018ff8be63221c61682df03af4937b | /osf/migrations/0058_merge_20170913_2232.py | dae51095b0957ad3237d3cd6dd2a591ff6789da0 | [
"Apache-2.0",
"LGPL-2.0-or-later",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"MIT",
"AGPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"MPL-1.1",
"CPAL-1.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | RCOSDP/RDM-osf.io | 81b11d9511f6248ec9bccb6c586b54a58429e1e7 | 5d632eb6d4566d7d31cd8d6b40d1bc93c60ddf5e | refs/heads/develop | 2023-09-01T09:10:17.297444 | 2023-08-28T04:59:04 | 2023-08-28T04:59:04 | 123,298,542 | 12 | 24 | Apache-2.0 | 2023-09-12T08:58:28 | 2018-02-28T14:46:05 | Python | UTF-8 | Python | false | false | 351 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-14 03:32
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('osf', '0057_order_fileversion_by_date_created'),
('osf', '0054_add_file_version_indices'),
]
operations = [
]
| [
"sloria1@gmail.com"
] | sloria1@gmail.com |
6f11d373f2b16a3dfaf1af6154056173d748cf2f | 18f7d65bda4e5f55d71f78a69f30dd2e58c2f37b | /script.module.7of9-pirateslife4me/resources/root/webscrapers.py | d6704cf8c6081d12de71be4c8860d27ba6d95f25 | [] | no_license | Iph47/kdc_git_repo | 13700d229436a69b4b22e87668154b783aca05cc | 8d903bb5efa7e189f3faaf7eb1637820148f0985 | refs/heads/master | 2022-11-08T11:30:22.323438 | 2020-06-18T01:11:11 | 2020-06-18T01:11:11 | 273,349,618 | 3 | 0 | null | 2020-06-18T22:10:39 | 2020-06-18T22:10:39 | null | UTF-8 | Python | false | false | 7,451 | py | import xbmc,os
addon_id = 'script.module.7of9-pirateslife4me'
icon = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id, 'icon.png'))
fanart = xbmc.translatePath(os.path.join('special://home/addons/' + addon_id , 'fanart.jpg'))
def cat():
addDir('[COLOR white][B]Arconaitv.me[/COLOR][/B]','arconaitv',2,'https://pbs.twimg.com/profile_images/590745210000433152/2u_nu2TM.png',fanart,'')
addDir('[COLOR white][B]Fluxus TV[/COLOR][/B]','fluxustv',2,'https://pbs.twimg.com/profile_images/858019601820467200/FWi_rtsG.jpg',fanart,'')
addDir('[COLOR white][B]iBrod.tv[/COLOR][/B]','ibrod',2,'https://www.ibrod.tv/images/logo.png',fanart,'')
addDir('[COLOR white][B]LiveonlineTv247.to[/COLOR][/B]','liveonlinetv',2,'https://lh3.googleusercontent.com/_QDQuHHm1aj1wyBTRVBoemhvttNZ5fF4RhLG4BWoYpx0z69OKsbvg568hxup5oBqsyrJs7XV-w=s640-h400-e365',fanart,'')
addDir('[COLOR white][B]Mamahd.com[/COLOR][/B]','mamahd',2,'http://www.topmanzana.com/static/mamahd.jpg',fanart,'')
addDir('[COLOR white][B]Shadownet.ro[/COLOR][/B]','shadownet',2,'https://s4.postimg.org/iy7lkmw8d/logon.png',fanart,'')
addDir('[COLOR white][B]Ustreamix.com[/COLOR][/B]','ustreamix',2,'https://cdn6.aptoide.com/imgs/a/7/8/a78c34966c4e443e7235d839b5856c0d_icon.png?w=256',fanart,'')
addDir('[COLOR white][B]Youtube.com[/COLOR][/B]','youtube',2,'https://pbs.twimg.com/profile_images/877566581135597568/PkjTkC0V_400x400.jpg',fanart,'')
def get(url):
if url == 'shadownet':
shadownet()
elif 'shadownetchan:' in url:
shadownetchannels(url)
elif url == 'ustreamix':
ustreamix()
elif url == 'ibrod':
ibrod()
elif url == 'fluxustv':
fluxustv()
elif url == 'liveonlinetv':
liveonlinetv()
elif url == 'arconaitv':
arconaitv()
elif url == 'youtube':
xbmc.executebuiltin('ActivateWindow(Videos,plugin://plugin.video.youtube/kodion/search/query/?event_type=live&q=live%20tv&search_type=video)')
elif url == 'mamahd':
mamahd()
elif url == 'crichd':
crichd()
def mamahd():
import re
open = OPEN_URL('http://mamahd.com')
part = regex_from_to(open,'<div class="standard row channels">','</div>')
regex = re.compile('href="(.+?)".+?src="(.+?)".+?span>(.+?)<',re.MULTILINE|re.DOTALL).findall(part)
for url,icon,name in regex:
if not 'Stream' in name:
if not 'Bundesliga' in name:
if not 'Channel' in name:
if not 'HD ' in name:
addDir(name,url,10,icon,fanart,'')
def arconaitv():
url = 'https://www.arconaitv.me'
page = OPEN_URL(url)
part = regex_from_to(page,'id="cable">','id="donate">')
all_vids=regex_get_all(part,"div class='box-content'",'</a>')
for a in all_vids:
url = regex_from_to(a,"href='","'")
name = regex_from_to(a,"title='","'").replace('#038;','')
if not url=='https://www.arconaitv.me/':
if not name == 'A-E':
if not name == 'F-J':
if not name == 'K-O':
if not name == 'P-T':
if not name == 'U-Z':
addDir('[B][COLOR white]%s[/COLOR][/B]'%name,'https://www.arconaitv.me/'+url,10,icon,fanart,'')
def liveonlinetv():
open = OPEN_URL('http://liveonlinetv247.info/tvchannels.php')
all = regex_get_all(open,'<li>','</li>')
for a in all:
name = regex_from_to(a,'">','<')
url = regex_from_to(a,'href=".*?channel=','"')
if not 'Live' in name:
if not 'UEFA' in name:
if not 'Barclays Premier League' in name:
if not 'IPL' in name:
addDir('[B][COLOR white]%s[/COLOR][/B]'%name,'liveonlinetv247:'+url,10,icon,fanart,'')
def fluxustv():
import re
open = OPEN_URL('https://raw.githubusercontent.com/fluxustv/IPTV/master/list.m3u')
regex = re.compile('#EXTINF:.+?\,(.+?)\n(.+?)\n', re.MULTILINE|re.DOTALL).findall(open)
for name,url in regex:
addDir('[B][COLOR white]%s[/COLOR][/B]'%name,url,10,icon,fanart,'')
def ibrod():
open = OPEN_URL('https://www.ibrod.tv/tvchans.php')
all = regex_get_all(open,'<li> <span>','</a></li>')
for a in all:
name = regex_from_to(a,'</span> <span>','</span>')
url = regex_from_to(a,'href="','"')
addDir('[B][COLOR white]%s[/COLOR][/B]'%name,'http://www.ibrod.tv/'+url,10,'https://www.ibrod.tv/images/logo.png',fanart,'')
def shadownet():
open = OPEN_URL('http://www.shadownet.me')
part = regex_from_to(open,'id="SideCategoryList">','class="afterSideCategoryList">')
all = regex_get_all(part,'<li class="">','</a>')
for a in all:
name = regex_from_to(a,'/">','<').replace('amp;','')
url = regex_from_to(a,'href="','"')
addDir('[B][COLOR white]%s[/COLOR][/B]'%name,'shadownetchan:' + url,2,icon,fanart,'')
def shadownetchannels(url):
import urllib
url = (url).replace('shadownetchan:','')
open = OPEN_URL(url)
part = regex_from_to(open,'id="CategoryContent">','<br class="Clear" />')
all = regex_get_all(part,'<div class="ProductImage">','</li>')
for a in all:
name = regex_from_to(a,'alt="','"')
url1 = regex_from_to(a,'href="','"')
icon = regex_from_to(a,'img src="','"')
addDir('[B][COLOR white]%s[/COLOR][/B]'%name,url1,10,icon,fanart,name)
try:
np = regex_from_to(open,'<div class="FloatRight"><a href="','"')
addDir('[COLOR red][B]Next Page >[/COLOR][/B]','shadownetchan:'+urllib.quote_plus(np),2,icon,fanart,'')
except:
pass
def ustreamix():
open = OPEN_URL('http://v2.ustreamix.com')
t = OPEN_URL('http://www.newtvworld.com/livetv/india/DiscoveryChannel.html')
log(t)
all = regex_get_all(open,'<p><a','</a>')
for a in sorted(all):
name = regex_from_to(a,'target="_blank">','<')
url = regex_from_to(a,'href="','"')
addDir('[B][COLOR white]%s[/COLOR][/B]'%name,'http://v2.ustreamix.com'+url,10,icon,fanart,'')
logfile = xbmc.translatePath(os.path.join('special://home/addons/script.module.7of9-pirateslife4me', 'log.txt'))
def log(text):
file = open(logfile,"w+")
file.write(str(text))
######################################################################################################
def regex_from_to(text, from_string, to_string, excluding=True):
import re,string
if excluding:
try: r = re.search("(?i)" + from_string + "([\S\s]+?)" + to_string, text).group(1)
except: r = ''
else:
try: r = re.search("(?i)(" + from_string + "[\S\s]+?" + to_string + ")", text).group(1)
except: r = ''
return r
def regex_get_all(text, start_with, end_with):
import re,string
r = re.findall("(?i)(" + start_with + "[\S\s]+?" + end_with + ")", text)
return r
def OPEN_URL(url):
import requests
headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
link = requests.session().get(url, headers=headers, verify=False).text
link = link.encode('ascii', 'ignore')
return link
def addDir(name,url,mode,iconimage,fanart,description):
import xbmcgui,xbmcplugin,urllib,sys
u=sys.argv[0]+"?url="+url+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&iconimage="+urllib.quote_plus(iconimage)+"&description="+urllib.quote_plus(description)
ok=True
liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
liz.setInfo( type="Video", infoLabels={"Title": name,"Plot":description})
liz.setProperty('fanart_image', fanart)
if mode==7:
liz.setProperty("IsPlayable","true")
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
else:
ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
return ok
xbmcplugin.endOfDirectory | [
"36279834+tox303@users.noreply.github.com"
] | 36279834+tox303@users.noreply.github.com |
0d2ba5f81ca457b54a1682575851fcf8f6ed0ae9 | e97c5e5beb22444b7eabd743a35493ab6fd4cb2f | /libs/log.py | e05a450020120351fef15832250286ba1117b8fc | [
"BSD-2-Clause-Patent"
] | permissive | greenelab/phenoplier | bea7f62949a00564e41f73b361f20a08e2e77903 | b0e753415e098e93a1f206bb90b103a97456a96f | refs/heads/main | 2023-08-23T20:57:49.525441 | 2023-06-15T06:00:32 | 2023-06-22T16:12:37 | 273,271,013 | 5 | 2 | NOASSERTION | 2023-06-20T20:35:45 | 2020-06-18T15:13:58 | Jupyter Notebook | UTF-8 | Python | false | false | 590 | py | """
Provides logging functions.
"""
import logging
import logging.config
import yaml
import conf
def _get_logger_config():
"""Reads the logging config file in YAML format."""
with open(conf.GENERAL["LOG_CONFIG_FILE"], "r") as f:
return yaml.safe_load(f.read())
logging.config.dictConfig(_get_logger_config())
def get_logger(log_name: str = None) -> logging.Logger:
"""
Returns a Logger instance.
Args:
log_name: logger name.
Returns:
A Logger instance configured with default settings.
"""
return logging.getLogger(log_name)
| [
"miltondp@gmail.com"
] | miltondp@gmail.com |
eab3ff73caf97a4d6ce6cb79b317e5aaa74dd265 | 3d1a8ccef4153b6154c0aa0232787b73f45137ba | /services/customer/db.py | 8e5a6ce81812465a01743fb386158c3603de9757 | [] | no_license | jan25/hotrod-python | a0527930b2afc33ca3589c1cf7ae07814148535a | dbce7df1bc2d764351dd2ba1122078fc525caed7 | refs/heads/master | 2020-06-03T14:59:35.627093 | 2019-06-22T16:52:19 | 2019-06-22T16:52:19 | 191,616,546 | 6 | 0 | null | null | null | null | UTF-8 | Python | false | false | 479 | py | from .client import Customer
customers = {
"123": Customer(id="123", name="Rachel's Floral Designs", location="115,277"),
"567": Customer(id="567", name="Amazing Coffee Roasters", location="211,653"),
"392": Customer(id="392", name="Trom Chocolatier", location="577,322"),
"731": Customer(id="731", name="Japanese Deserts", location="728,326")
}
def get_customer_by_id(customer_id):
if customer_id not in customers: return
return customers[customer_id]
| [
"abhilashgnan@gmail.com"
] | abhilashgnan@gmail.com |
8d00ae753d8fc0aca6f67ec1de5de4edebd5cbf2 | ca539b0df7ca5a91f80b2e2f64e7379e69243298 | /312.py | 50ff4fd4692929c4fe89ae5e5d19a20f67879cb1 | [] | no_license | yorick76ee/leetcode | 9a9e5d696f3e32d9854c2ed9804bd0f98b03c228 | d9880892fe15f9bb2916beed3abb654869945468 | refs/heads/master | 2020-03-18T22:59:29.687669 | 2016-07-18T19:56:55 | 2016-07-18T19:56:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 536 | py | class Solution(object):
def h(self, nums, l, r, d):
if (l,r) not in d:
d[(l,r)] = 0
for i in range(l, r+1):
d[(l,r)] = max(d[(l,r)], self.h(nums, l, i-1, d) + self.h(nums, i+1, r, d) + nums[i]*nums[l-1]*nums[r+1])
if l == 1 and r == 4:
print i,':',d[(l,r)]
return d[(l,r)]
def maxCoins(self, nums):
return self.h([1]+nums+[1], 1, len(nums), {})
if __name__ == '__main__':
wds= Solution()
print wds.maxCoins([3,1,5,8])
| [
"641614152@qq.com"
] | 641614152@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.