blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 281 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2
values | repo_name stringlengths 6 116 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 313
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 18.2k 668M ⌀ | star_events_count int64 0 102k | fork_events_count int64 0 38.2k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 107
values | src_encoding stringclasses 20
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 4 6.02M | extension stringclasses 78
values | content stringlengths 2 6.02M | authors listlengths 1 1 | author stringlengths 0 175 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
93c32506dd7b864ec9a89b3f123aa1883ffad867 | 91dcb87cd550f66760f9bffdcd15d728b30c5fce | /test.py | 223506dbea16c2c0b3a63618c753b4f0694d752f | [] | no_license | Tamagotono/CycleTester | 835c87a1f02c23ebe979e0ccf2f6a7f03cef4e3c | c565e3868df33d74f8ddfe0f5efb508d7b45a697 | refs/heads/master | 2020-03-08T13:06:18.781859 | 2018-06-23T01:33:45 | 2018-06-23T01:33:45 | 128,149,040 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,307 | py |
#import machine, display, time,
import machine, _thread, math
#import m5stack
import utime, machine #Cycle count required imports
from micropython import const
import hardware_config
import gc
tft, btn_a, btn_b, btn_c = hardware_config.M5stack()
class Relay(machine.Signal):
"""
Notes:
Adds extra feature to the machine.Signal class
Adds:
toggle: Inverts the current state of the pin.
"""
def __init__(self, gpio_pin_number: int, inverted=False):
super().__init__(gpio_pin_number, inverted)
def toggle(self):
self.value(not self.value())
class Button:
def __init__(self, gpio_pin_number: int):
self.gpio_pin = machine.Pin(gpio_pin_number, machine.Pin.IN, machine.Pin.PULL_UP)
def prettyTime(milliseconds: int, msPrecision: int=1, verbose: bool=False) -> str:
"""
Args:
milliseconds: The value in milliseconds to on_off_time_calc
msPrecision: The number of digits to show for the milliseconds portion of the output.
Default = 1
verbose: If verbose is True, it will output days, hours, minutes, seconds, milliseconds.
If verbose is False, it will display only the minimum values needed.
Default = False
Returns: A string with the converted time in human readable on_off_time_calc with the precision specified.
"""
seconds, milliseconds = divmod(milliseconds, 1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
weeks, days = divmod(days, 7)
years, weeks = divmod(weeks, 52)
time=str("%1dy %1dw %1dd" % (years, weeks, days))
if verbose == False:
if years == 0:
time=str("%1dw %1dd %1dh" % (weeks, days, hours))
if weeks == 0:
time=str("%1dd %1dh %02dm" % (days, hours, minutes))
if days == 0:
time=str("%1dh %02dm %02ds" % (hours, minutes, seconds))
if hours == 0:
time=str("%02dm %02ds" % (minutes, seconds))
if minutes == 0:
time=str("%04.2fs" % (seconds+(milliseconds/1000)))
if seconds == 0:
time=str("%1dms" % (truncate(milliseconds, precision=msPrecision)))
else:
time=str("%1dy %1dw %1dd %1dh %02dm %02d.%3ds" % (years, weeks, days, hours, minutes, seconds, milliseconds))
return time
def truncate(original_number: float, precision: int=1) -> str:
"""
Args:
original_number: The float that you want truncated (not rounded)
precision: Int defining how many decimal places to truncate at.
Returns: The string of the original float, but truncated to the specified number of decimal places.
Default = 1
Notes: This has to return a string due to the accuracy in the MCU causing numbers to have too many digits.
"""
precision=int(precision)
if precision>0:
temp = str(float(original_number)).split('.') # float to force a decimal point, string to split.
temp[1] = temp[1]+('0'*precision) # make sure we have enough digits for the next step.
truncated_number = temp[0]+'.'+temp[1][:precision]
else:
truncated_number = str(int(original_number))
return truncated_number
def cycle(on_time_ms: int, off_time_ms: int, relay: Relay) -> None:
"""
Args:
on_time_ms (int): The desired time in milliseconds for the ON period of the cycle.
off_time_ms (int): The desired time in milliseconds for the OFF period of the cycle.
relay (Relay): The instance of the relay to be acted on.
Returns:
None
"""
relay.on()
utime.sleep_ms(on_time_ms)
relay.off()
utime.sleep_ms(off_time_ms)
gc.collect()
class UI:
"""
Args:
title_size (int): The number of lines for the Title section. Default = 1
nav_size (int): The number of lines for the Navigation section. Set to 0 for test UIs. Default = 0
parameter_size (int): The number of lines for the Parameter section. Set to 0 for menu UIs. Default = 4
status_size (int): The number of lines for the Status section. Set to 0 for menu UIs. Default = 3
notification_size (int): The number of lines for the Notification section. Default = 1
Note:
This is the display for a specific test / menu. All calls to change the
information on the screen need to go through the GUI2LCD instance.
"""
global tft
def __init__(self):
tft.clear()
self.screenwidth, self.screenheight = tft.screensize()
self.header = self.DisplaySection(0,0,40, self.screenwidth)
self.prameters = self.DisplaySection(0,41,120, self.screenwidth, fill_color=tft.GREEN)
# self.status = self.DisplaySection(0,121,60, self.screenwidth)
class DisplaySection:
def __init__(self,
x:int,
y:int,
frame_height:int,
frame_width:int,
frame_color:int = tft.WHITE,
fill_color:int = tft.BLUE,
text_color:int = tft.WHITE,
font = tft.FONT_DejaVu18,
):
self.x = x
self.y = y
self.frame_width = frame_width
self.frame_height = frame_height
self.frame_color = frame_color
self.fill_color = fill_color
self.text_color = text_color
self.font = font
tft.font(self.font)
self.frame_height = 40
self.line_height, self.text_y = self.line_height_margin_calc(10)
self.num_of_lines = int(self.frame_height / self.line_height)
self.lines = {}
tft.set_bg(self.fill_color)
tft.set_fg(self.text_color)
self.create_lines(self.num_of_lines)
self.initialize_section()
def initialize_section(self):
tft.font(self.font)
tft.rect(self.x, self.y, self.frame_width, self.frame_height, self.frame_color, self.fill_color)
self.create_lines(self.num_of_lines)
self.update_all_lines()
def line_height_margin_calc(self, margin:int = 10) -> int:
"""
Args:
margin_pct (int): the percentage of font size for vertical margins
Returns:
The total hight of the line in pixels
The number of pixels used above the font used for margins, to set the vertical offset for text_y
"""
margin_pct = margin/100
font_height = int(tft.fontSize()[1])
margin_px = int(font_height)
line_height_px = int(font_height * (1 + margin_pct))
print("line_height_margin_calc: line_height_px = " + str(line_height_px) + 'margin:' + str(margin/2))
return line_height_px, int(margin_px/2)
def create_lines(self, num_of_lines:int):
"""
Args:
num_of_lines (int): initializes the dictionary of the text for each line number
Returns:
Nothing
"""
line_num = 1
while line_num <= num_of_lines:
self.lines[line_num] = str(line_num)
line_num += 1
print(self.lines.items())
def update_line(self, line_number:int):
"""
Args:
line_number (int): The line number to update on the desplay
Returns:
Nothing
"""
line_y = ((line_number - 1) * self.line_height)
text_y = line_y + self.text_y
tft.rect(self.x, line_y, self.frame_width, self.line_height, self.fill_color, self.fill_color)
tft.text(self.x, text_y, self.lines.get(line_number, "ERROR"),
self.text_color, transparent=True)
def update_all_lines(self):
"""
Returns:
Nothing
Notes:
Quick way to update all lines in the section
"""
line_num = 1
while line_num <= self.num_of_lines:
self.update_line(line_num)
line_num += 1
# def header(self):
# FRAME_COLOR = tft.BLUE
# FILL_COLOR = tft.BLUE
# TEXT_COLOR = 0xffffff
# HEIGHT = 40
# LINE1_Y = 0
# LINE2_Y = 20
#
# tft.rect(0, 0, 320, HEIGHT, FRAME_COLOR, FILL_COLOR)
# tft.textClear(tft.CENTER,LINE1_Y, self.h1_text)
# tft.text(tft.CENTER,LINE1_Y, self.h1_text, TEXT_COLOR, transparent=True)
# tft.textClear(tft.CENTER,LINE2_Y, self.h2_text)
# tft.text(tft.CENTER,LINE2_Y, self.h2_text, TEXT_COLOR, transparent=True)
#
# def test_param(self):
# FRAME_COLOR = tft.BLUE
# FILL_COLOR = tft.BLUE
# TEXT_COLOR = 0xffffff
# HEIGHT = 60
# text_line_1 = ''
# text_line_2 = ''
#
# tft.rect(0, 0, 320, 20, tft.RED, tft.RED)
# #printLCD(TEST_NAME_1, Y=LCDTitle1, Background=BLACK)
# #printLCD(TEST_NAME_2, Y=LCDTitle2, Background=BLACK)
#
# def test_status(self):
# FRAME_COLOR = tft.BLUE
# FILL_COLOR = tft.BLUE
# TEXT_COLOR = 0xffffff
# HEIGHT = 60
# #text_line_1 = ''
# #text_line_2 = ''
#
# tft.rect(0, 0, 320, 20, tft.RED, tft.RED)
# printLCD(TEST_NAME_1, Y=LCDTitle1, Background=BLUE)
# printLCD(TEST_NAME_2, Y=LCDTitle2, Background=BLUE)
def footer(self):
tft.rect( 25, 210, 80, 30, tft.RED, tft.BLUE)
tft.text( 50, 215, "UP", tft.WHITE, transparent=True)
tft.rect(120, 210, 80, 30, tft.RED, tft.BLUE)
tft.text(120, 215, "DOWN", tft.WHITE, transparent=True)
tft.rect(215, 210, 80, 30, tft.RED, tft.BLUE)
tft.text(235, 215, "SEL", tft.WHITE, transparent=True)
def printLCD(text, X=0, Y=0, bg_color=0x000000, text_color=0xffffff, transparent=True):
text = str(text)
tft.textClear(X, Y, text)
tft.text(X, Y, text, text_color, transparent=True)
| [
"tamagotono@gmail.com"
] | tamagotono@gmail.com |
1f03ffd14d66533504fd6a54fb4f47985741b73e | f16f513bd487e415807a584da353f01799fc86be | /base/splider.py | c6cd1c47e8387c33c0317388575f961511e57934 | [] | no_license | xfz1987/python_study | 53497e4d436f0dd647ff001658a8f433941e7602 | 4615ae291162041d599f4e750f8958cf0e35b63e | refs/heads/master | 2020-04-02T00:13:49.127764 | 2018-10-19T14:27:33 | 2018-10-19T14:27:33 | 130,190,038 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 410 | py | import urllib
import urllib.request
import re
def get_html(url):
page = urllib.request.urlopen(url)
html = page.read
return html
reg = r'src="(.+?\.jpg)" width'
reg_img = reg.compile(reg)
imglist = reg_img.findall(get_html('http://xxxx'))
x = 0
# 如果imglist有100万张图片,则 需要分成4个部分来做,4*10
for img in imglist:
urllib.urlretrieve(img, '%s.jpg', %x)
x += 1
# regx101 | [
"gaozifeng001@ke.com"
] | gaozifeng001@ke.com |
d294ee636acb84148e16ac385f849a18ab6a1d2d | e63f11c621ffa2c54a8bc4714c6fb0f868f902d6 | /LianJia_Scrapy/item_url.py | 964827b681f15e340e7a2dee5981496f848a2108 | [] | no_license | aquablue1/LianJia_Scrapy | 5821fd93eca796d319f408d351cc30d860a0edb4 | 580ced19204d5eb9614c6a8b362b2cb9eba88388 | refs/heads/master | 2021-05-05T22:07:14.261137 | 2018-01-06T05:01:43 | 2018-01-06T05:01:43 | 116,090,808 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 308 | py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class LianjiaScrapyItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
url = scrapy.Field() | [
"94apieceofcake@gmail.com"
] | 94apieceofcake@gmail.com |
50fc6df7b930d2331bc283900b08c7c8a49056ab | eee30cd1c2afd38262c3d0203e228317951eb8d7 | /gym_env/__init__.py | d634c5af11eab3be23d8d0419bc8aa6cfb2c83cd | [] | no_license | SaadHz/gym_env | 427dbf4824d3060abf0c88b2469cec2de27e246f | 8d9c04af82418f7842de75e5126e421be55a7815 | refs/heads/master | 2022-09-04T07:14:10.672309 | 2020-05-21T00:49:47 | 2020-05-21T00:49:47 | 265,711,101 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 199 | py | from gym.envs.registration import register
register(
id='env-v0',
entry_point='gym_env.envs:EnvEnv',
)
register(
id='env-extrahard-v0',
entry_point='gym_env.envs:EnvExtraHardEnv',
)
| [
"noreply@github.com"
] | noreply@github.com |
1b6e6daf46bf32ded7ccee0ee73d5e1c97accff3 | 6007c6064c3adcb6787d0ab12062bffc4dc85431 | /embeddings/__init__.py | 5cfcf77de15f485ff04ad07895d575a8399f46b3 | [] | no_license | Simon0xzx/tcl | 10d30a33b498c5b82bb41522ca206962a5ac6b49 | 637366bdee479ffb462d228ff10a44efd34fe2f5 | refs/heads/master | 2023-03-12T22:37:53.504829 | 2021-03-05T01:59:00 | 2021-03-05T01:59:00 | 344,325,326 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 95 | py | from embeddings.contrastive_encoder import ContrastiveEncoder
__all__ = ['ContrastiveEncoder'] | [
"simon0xzx@gmail.com"
] | simon0xzx@gmail.com |
fbc401f6fb472124d7e84ef8d13b3aca106c8e57 | 1a19f22b05d4658af821947b2ec3223480ba7c2f | /k_means.py | 0469a9852accbdd0a186409687b74176e3efc58d | [] | no_license | DavilBot/ML | 9de8979820ae849bedc4956d8b40934a7a8dca6a | 34db7d8835553d0a1fee835b619c12e613086a39 | refs/heads/master | 2020-03-21T05:03:37.928654 | 2018-08-02T12:52:00 | 2018-08-02T12:52:00 | 138,142,229 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,268 | py | import pandas as pd
import numpy as np
from dr import SQLConnector
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn import preprocessing
import sys
s = SQLConnector(host="localhost",pwd="r0b0t161",db="db_crypto",user="robot")
query = "SELECT * FROM `prices1m` ORDER BY `updated_at` DESC LIMIT 61458 "
data_p = pd.read_csv("prices1m.csv")
data_p.columns = ['id', 'ticker', 'mts', 'open', 'close', 'high', 'low', 'volume', 'updated_at']
#print(data_p['open'])
data_r = pd.read_csv("trendhistory_2018_06_13.csv", nrows = 50045)
o = data_p['open'].values
c = data_p['close'].values
h = data_p['high'].values
l = data_p['low'].values
#print(df.head())
X = np.array(list(zip(o, c, h, l)))
X = preprocessing.scale(X)
y = np.where (data_p['close'].shift(-1) > data_p['close'],1,-1)
#split = int(0.7*len(df))
#X_train, X_test, y_train, y_test = X[:split], X[split:], y[:split], y[split:]
model = KMeans(n_clusters = 4, random_state = 0 )
model.fit(X)
correct = 0
for i in range(len(X)):
predict_ = np.array(X[i].astype(float))
predict_ = predict_.reshape(-1, len(predict_))
prediction = model.predict(predict_)
if prediction[0] == y[i]:
correct+=1
print('Predicted :{}'.format(model.predict(X)))
print(correct/len(X))
| [
"kattabekovbeknur@gmail.com"
] | kattabekovbeknur@gmail.com |
28d7ed4552e9ad17858d34157706d73cae556aec | 485439bbe4e0399a279abeabd91987c304efcd43 | /etra/tests/test_io.py | 6b865276e72ec67a6af276c93661a9dd3e2c39dc | [] | no_license | truongdo/etra | 5056bd4f21814a5ee6915ba0886fd8c936d58d71 | 2da2a2cc11479c348584e0987931fb76e6658c20 | refs/heads/master | 2020-04-06T06:27:51.261467 | 2017-02-01T04:57:46 | 2017-02-01T04:57:46 | 72,731,844 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,354 | py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 Truong Do <truongdq54@gmail.com>
#
# Distributed under terms of the MIT license.
"""
"""
from __future__ import print_function
import unittest
import tempfile
import os
import sys
import numpy as np
import etra.io as myio
class IoTest(unittest.TestCase):
def setUp(self):
self.tmp_file = tempfile.mkstemp()[1]
def test_open(self):
with myio.smart_open("ls |") as fin:
self.assertIsInstance(fin, file)
self.assertEqual(fin.name, "<fdopen>")
with myio.smart_open("|cat -") as fin:
self.assertIsInstance(fin, file)
self.assertEqual(fin.name, "<fdopen>")
self.assertEqual(fin.mode, "wb")
with myio.smart_open() as fin:
self.assertIsInstance(fin, file)
self.assertEqual(fin.name, "<stdin>")
with myio.smart_open(self.tmp_file) as fin:
self.assertIsInstance(fin, file)
self.assertEqual(fin.name, self.tmp_file)
with myio.smart_open(self.tmp_file, "w") as fout:
fout.write("hello\n")
a = open(self.tmp_file).readline().strip()
self.assertEqual(a, "hello")
def tearDown(self):
os.remove(self.tmp_file)
pass
if __name__ == "__main__":
unittest.main()
| [
"truongdq54@gmail.com"
] | truongdq54@gmail.com |
48c2c3dca0b6a2b6c85044a00f274533db952693 | 60a831fb3c92a9d2a2b52ff7f5a0f665d4692a24 | /IronPythonStubs/release/stubs.min/System/Windows/Controls/__init___parts/ContextMenuEventArgs.py | ddb3667cf2693b5c400b6c59a3043b012c6b0300 | [
"MIT"
] | permissive | shnlmn/Rhino-Grasshopper-Scripts | a9411098c5d1bbc55feb782def565d535b27b709 | 0e43c3c1d09fb12cdbd86a3c4e2ba49982e0f823 | refs/heads/master | 2020-04-10T18:59:43.518140 | 2020-04-08T02:49:07 | 2020-04-08T02:49:07 | 161,219,695 | 11 | 2 | null | null | null | null | UTF-8 | Python | false | false | 479 | py | class ContextMenuEventArgs(RoutedEventArgs):
""" Provides data for the context menu event. """
CursorLeft=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the horizontal position of the mouse.
Get: CursorLeft(self: ContextMenuEventArgs) -> float
"""
CursorTop=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the vertical position of the mouse.
Get: CursorTop(self: ContextMenuEventArgs) -> float
"""
| [
"magnetscoil@gmail.com"
] | magnetscoil@gmail.com |
e821be69dbcc904309be14ca117f4bbb2b7155e6 | 45e376ae66b78b17788b1d3575b334b2cb1d0b1c | /tests/cloudformation/checks/resource/aws/test_ECRImmutableTags.py | 2bafbbce0a26573bbd0e9e83dbbd29b4d6be0c56 | [
"Apache-2.0"
] | permissive | bridgecrewio/checkov | aeb8febed2ed90e61d5755f8f9d80b125362644d | e64cbd27ffb6f09c2c9f081b45b7a821a3aa1a4d | refs/heads/main | 2023-08-31T06:57:21.990147 | 2023-08-30T23:01:47 | 2023-08-30T23:01:47 | 224,386,599 | 5,929 | 1,056 | Apache-2.0 | 2023-09-14T20:10:23 | 2019-11-27T08:55:14 | Python | UTF-8 | Python | false | false | 827 | py | import os
import unittest
from checkov.cloudformation.checks.resource.aws.ECRImmutableTags import check
from checkov.cloudformation.runner import Runner
from checkov.runner_filter import RunnerFilter
class TestECRImmutableTags(unittest.TestCase):
def test_summary(self):
runner = Runner()
current_dir = os.path.dirname(os.path.realpath(__file__))
test_files_dir = current_dir + "/example_ECRImmutableTags"
report = runner.run(root_folder=test_files_dir,runner_filter=RunnerFilter(checks=[check.id]))
summary = report.get_summary()
self.assertEqual(summary['passed'], 1)
self.assertEqual(summary['failed'], 2)
self.assertEqual(summary['skipped'], 0)
self.assertEqual(summary['parsing_errors'], 0)
if __name__ == '__main__':
unittest.main()
| [
"noreply@github.com"
] | noreply@github.com |
caa9cb15bb5cd49e3cb59f5ace978e207c998922 | db37e5eab7b60057bbc1ae153df8693f0159b02c | /examples/decoupledibpm/flapping2dRe75/run/scripts/plot_vorticity_compare_li_et_al_2015.py | 63ee97afbb13882c1575b1ae99fc77dbdad3f383 | [
"BSD-3-Clause"
] | permissive | stjordanis/petibm-examples | 83f7212eadbc1bbfb2071d550969b252cbcfcd89 | 794de3613967c14750c750aed386602c988cff05 | refs/heads/master | 2022-04-12T20:29:33.566464 | 2020-02-29T22:45:39 | 2020-02-29T22:45:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,078 | py | """Plot the vorticity at saved time steps."""
from matplotlib import pyplot, image
import numpy
import pathlib
import petibmpy
simudir = pathlib.Path(__file__).absolute().parents[1] # simulation directory
datadir = simudir / 'output' # directory with field solution files
name = 'wz' # name of the variable to load and plot
save_figure = True # save Matplotlib figure as PNG
show_figure = True # show Matplotlib figure
# Load the grid from file.
filepath = datadir / 'grid.h5'
grid = petibmpy.read_grid_hdf5(filepath, name)
states = [2400, 2600, 2800, 3000, 3200]
pyplot.rc('font', family='serif', size=14)
fig, (ax1, ax2) = pyplot.subplots(nrows=2, ncols=5, figsize=(10.0, 5.0))
levels = numpy.linspace(-20.0, 20.0, num=40) # contour levels
for i, state in enumerate(states):
print(f'[time step {state}] Load and plot contours of {name}')
# Load data from file.
filepath = datadir / f'{state:0>7}.h5'
data = petibmpy.read_field_hdf5(filepath, name)
# Load body coordinates from file.
filepath = datadir / f'ellipse_{state:0>7}.2D'
body = petibmpy.read_body(filepath)
# Plot the contour of the field variable.
ax1[i].contour(*grid, data, levels=levels, linewidths=0.5, extend='both')
ax1[i].plot(*body, color='black', linewidth=0.5)
ax1[i].axis('scaled', adjustable='box')
ax1[i].set_xlim(-3.5, 2.5)
ax1[i].set_ylim(-5.0, 1.0)
ax1[i].axis('off')
# Add images from Li et al. (2015) to the figure.
datadir = simudir.parent / 'data'
times = [3.0, 3.25, 3.5, 3.75, 4.0]
for i, time in enumerate(times):
print(f'[time {time}] Display image from Li et al. (2015)')
filepath = datadir / f'li_et_al_2015_flapping_wz_{time:.2f}.png'
im = image.imread(str(filepath))
ax2[i].imshow(im)
ax2[i].axis('off')
fig.tight_layout()
if save_figure:
figdir = simudir / 'figures' # folder to contain PNG files
figdir.mkdir(parents=True, exist_ok=True)
filepath = figdir / f'wz_compare_li_et_al_2015.png'
fig.savefig(filepath, dpi=300, bbox_inches='tight')
if show_figure:
pyplot.show()
| [
"mesnardo@gwu.edu"
] | mesnardo@gwu.edu |
551b97e38f2e043bd809906f8163f999d24964e3 | 20b9da3b15dae444c0e9fac75fbb1073471dde28 | /tests/conftest.py | c8787e2c1746c3197efb65e73dc03c683cecc429 | [] | no_license | laurenvagts/tunnel-rpc | b391a93959cb09b1fe733e7fd7588e3838455352 | b41c0892e186e08a9d9e9ea14bb3a3b5063253df | refs/heads/master | 2020-05-15T06:26:27.588465 | 2019-04-18T21:19:25 | 2019-04-18T21:19:25 | 182,124,671 | 0 | 0 | null | 2019-04-18T16:49:41 | 2019-04-18T16:49:41 | null | UTF-8 | Python | false | false | 561 | py | # -*- coding: utf-8 -*-
"""Pytest Fixtures for Tunnel RPC.
"""
import pytest
@pytest.fixture()
def docker_api_client():
"""Provides a docker-api client.
"""
import docker
return docker.APIClient()
@pytest.fixture()
# pragma pylint: disable=redefined-outer-name
def tunnel_container_factory(docker_api_client):
"""Provides a container creation factory.
Assumes The tunnel_rpc create_container works properly.
"""
from tunnel_rpc.methods import create_container
return lambda: create_container(docker_api_client)
| [
"lsmith@zenoscave.com"
] | lsmith@zenoscave.com |
fc52f5865ae7315907978b9cccc14a8492727c62 | 51395b305df5c4f6eb5b1bf9832923f4bc709ea9 | /tools/convert_state.py | 993b876fdea64345e854f8d029922aed087f706f | [
"Apache-2.0"
] | permissive | Tingfengguangling/ManiSkill-Learn | 9cb62290ff2b9126d6b372c0de51e2b523a8d718 | 41df74d4025b23d7136bd597fcf8ca920f51cada | refs/heads/main | 2023-08-30T23:21:46.610746 | 2021-10-21T05:51:33 | 2021-10-21T05:51:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,852 | py | import argparse
import os
os.environ["D4RL_SUPPRESS_IMPORT_ERROR"] = "1"
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
import os.path as osp
from multiprocessing import Process
import h5py
from mani_skill_learn.env import make_gym_env, ReplayMemory
from mani_skill_learn.utils.fileio import load_h5_as_dict_array, merge_h5_trajectory
from mani_skill_learn.utils.data import sample_element_in_dict_array, compress_size
from mani_skill_learn.utils.meta import get_total_memory, flush_print
def auto_fix_wrong_name(traj):
for key in traj:
if key in ['action', 'reward', 'done', 'env_level', 'next_env_level', 'next_env_state', 'env_state']:
traj[key + 's'] = traj[key]
del traj[key]
return traj
tmp_folder_in_docker = '/tmp'
def convert_state_representation(keys, args, worker_id, main_process_id):
env = make_gym_env(args.env_name, unwrapped=True, obs_mode=args.obs_mode)
assert hasattr(env, 'get_obs'), f'env {env} does not contain get_obs'
get_obs = env.get_obs
cnt = 0
output_file = osp.join(tmp_folder_in_docker, f'{worker_id}.h5')
if worker_id == 0:
flush_print(f'Save trajectory to {output_file}')
output_h5 = h5py.File(output_file, 'w')
input_h5 = h5py.File(args.traj_name, 'r')
for j, key in enumerate(keys):
trajectory = load_h5_as_dict_array(input_h5[key])
trajectory = auto_fix_wrong_name(trajectory)
env.reset(level=trajectory['env_levels'][0])
length = trajectory['obs'].shape[0]
if 'info_eval_info_success' in trajectory:
if 'info_keep_threshold' not in trajectory:
success = trajectory['info_eval_info_success'][-1]
else:
success = trajectory['info_eval_info_success'][-1]
keep_threshold = trajectory['info_keep_threshold'][-1]
success = success >= keep_threshold
elif 'eval_info_success' in trajectory:
success = trajectory['eval_info_success'][-1]
keep_threshold = trajectory['keep_threshold'][-1]
success = success >= keep_threshold
else:
flush_print(trajectory.keys(), 'No success info')
raise Exception("")
if not success:
if worker_id == 0:
flush_print(f'Worker {worker_id}, Skip {j + 1}/{len(keys)}, Choose {cnt}')
continue
replay = ReplayMemory(length)
next_obs = None
for i in range(length):
if next_obs is None:
env_state = sample_element_in_dict_array(trajectory['env_states'], i)
env.set_state(env_state)
obs = get_obs()
obs = compress_size(obs)
else:
obs = next_obs
# from mani_skill_learn.utils.data import get_shape_and_type
# flush_print(get_shape_and_type(obs))
# exit(0)
next_env_state = sample_element_in_dict_array(trajectory['next_env_states'], i)
env.set_state(next_env_state)
next_obs = get_obs()
next_obs = compress_size(next_obs)
item_i = {
'obs': obs,
'next_obs': next_obs,
'actions': trajectory['actions'][i],
'dones': trajectory['dones'][i],
'rewards': trajectory['rewards'][i],
}
mem = get_total_memory('G', False, init_pid=main_process_id)
replay.push(**item_i)
if worker_id == 0:
flush_print(f'Convert Trajectory: choose{cnt + 1}, {j + 1}/{len(keys)}, Step {i + 1}/{length}, total mem:{mem}')
group = output_h5.create_group(f'traj_{cnt}')
cnt += 1
replay.to_h5(group, with_traj_index=False)
output_h5.close()
flush_print(f'Finish using {output_file}')
def get_running_steps(num, n):
assert num >= n
min_steps = num // n
running_steps = []
for i in range(n):
if i < num - min_steps * n:
running_steps.append(min_steps + 1)
else:
running_steps.append(min_steps)
assert sum(running_steps) == num
return running_steps
def parse_args():
parser = argparse.ArgumentParser(description='Convert the representation of the trajectory')
# Configurations
parser.add_argument('--env-name', default='OpenCabinetDrawer_1045_link_0-v0',
help='The name of the environment')
parser.add_argument('--traj-name',
default='./debug_mani_skill/OpenCabinetDrawer_1045_link_0-v0/test/trajectory.h5',
help='The generated trajectory with some policies')
parser.add_argument('--output-name',
default='./debug_mani_skill/OpenCabinetDrawer_1045_link_0-v0/test/trajectory_pcd.h5',
help='The generated trajectory with some policies')
parser.add_argument('--max-num-traj', default=-1, type=int, help='The generated trajectory with some policies')
parser.add_argument('--obs-mode', default='pointcloud', type=str, help='The mode of the observer')
parser.add_argument('--num-procs', default=10, type=int, help='The mode of the observer')
# Convert setting
parser.add_argument('--add-random', default=False, action='store_true', help='Add random trajectory')
args = parser.parse_args()
args.traj_name = osp.abspath(args.traj_name)
args.output_name = osp.abspath(args.output_name)
return args
def main():
os.makedirs(osp.dirname(args.output_name), exist_ok=True)
with h5py.File(args.traj_name, 'r') as h5_file:
keys = sorted(h5_file.keys())
if args.max_num_traj < 0:
args.max_num_traj = len(keys)
args.max_num_traj = min(len(keys), args.max_num_traj)
args.num_procs = min(args.num_procs, args.max_num_traj)
keys = keys[:args.max_num_traj]
running_steps = get_running_steps(len(keys), args.num_procs)
flush_print(f'Num of trajs {len(keys)}', args.num_procs)
processes = []
from copy import deepcopy
for i, x in enumerate(running_steps):
p = Process(target=convert_state_representation, args=(deepcopy(keys[:x]), args, i, os.getpid()))
keys = keys[x:]
processes.append(p)
p.start()
for p in processes:
p.join()
files = []
for worker_id in range(len(running_steps)):
tmp_h5 = osp.join(tmp_folder_in_docker, f'{worker_id}.h5')
files.append(tmp_h5)
from shutil import rmtree
rmtree(args.output_name, ignore_errors=True)
merge_h5_trajectory(files, args.output_name)
for file in files:
rmtree(file, ignore_errors=True)
if __name__ == '__main__':
args = parse_args()
main()
| [
"z6ling@eng.ucsd.edu"
] | z6ling@eng.ucsd.edu |
94c044bdea784aa5da43326d563b722a3d5c4fc6 | 29da2ca6def1270be13a3096685a8e5d82828dff | /CIM14/CDPSM/GIS_Connectivity/IEC61970/Core/SubGeographicalRegion.py | 0030c2438ce680b5ea6c4d046032e16e4f3f5353 | [
"MIT"
] | permissive | rimbendhaou/PyCIM | 75eb3bcd3729b2410c03f3d5c66d6f1e05e21df3 | d578bb0bf1af344342bd23344385ed9c06c2d0ee | refs/heads/master | 2022-04-28T01:16:12.673867 | 2020-04-16T02:19:09 | 2020-04-16T02:19:09 | 256,085,381 | 0 | 0 | MIT | 2020-04-16T02:15:20 | 2020-04-16T02:08:14 | null | UTF-8 | Python | false | false | 3,823 | py | # Copyright (C) 2010-2011 Richard Lincoln
#
# 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.
from CIM14.CDPSM.GIS_Connectivity.IEC61970.Core.IdentifiedObject import IdentifiedObject
class SubGeographicalRegion(IdentifiedObject):
"""A subset of a geographical region of a power system network model.
"""
def __init__(self, Region=None, Lines=None, Substations=None, *args, **kw_args):
"""Initialises a new 'SubGeographicalRegion' instance.
@param Region: The association is used in the naming hierarchy.
@param Lines: A Line can be contained by a SubGeographical Region.
@param Substations: The association is used in the naming hierarchy.
"""
self._Region = None
self.Region = Region
self._Lines = []
self.Lines = [] if Lines is None else Lines
self._Substations = []
self.Substations = [] if Substations is None else Substations
super(SubGeographicalRegion, self).__init__(*args, **kw_args)
_attrs = []
_attr_types = {}
_defaults = {}
_enums = {}
_refs = ["Region", "Lines", "Substations"]
_many_refs = ["Lines", "Substations"]
def getRegion(self):
"""The association is used in the naming hierarchy.
"""
return self._Region
def setRegion(self, value):
if self._Region is not None:
filtered = [x for x in self.Region.Regions if x != self]
self._Region._Regions = filtered
self._Region = value
if self._Region is not None:
if self not in self._Region._Regions:
self._Region._Regions.append(self)
Region = property(getRegion, setRegion)
def getLines(self):
"""A Line can be contained by a SubGeographical Region.
"""
return self._Lines
def setLines(self, value):
for x in self._Lines:
x.Region = None
for y in value:
y._Region = self
self._Lines = value
Lines = property(getLines, setLines)
def addLines(self, *Lines):
for obj in Lines:
obj.Region = self
def removeLines(self, *Lines):
for obj in Lines:
obj.Region = None
def getSubstations(self):
"""The association is used in the naming hierarchy.
"""
return self._Substations
def setSubstations(self, value):
for x in self._Substations:
x.Region = None
for y in value:
y._Region = self
self._Substations = value
Substations = property(getSubstations, setSubstations)
def addSubstations(self, *Substations):
for obj in Substations:
obj.Region = self
def removeSubstations(self, *Substations):
for obj in Substations:
obj.Region = None
| [
"rwl@thinker.cable.virginmedia.net"
] | rwl@thinker.cable.virginmedia.net |
d2a24b502e662de76e225776017d1137001d947d | b7a29ba48a1393cae06d0de16b37968dc307760b | /tweet_slicer.py | 19b12bed44eba0ea5c44b77e07ddd7e5afa9c602 | [] | no_license | kkwteh/insight_project | fbf7ad8a5e5370df509859e0b37923366c643f58 | bd9087ddeceaa0d22a7ef7f32f342392c3a475c7 | refs/heads/master | 2016-09-06T20:13:01.909486 | 2013-03-04T21:43:33 | 2013-03-04T21:43:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,165 | py | #!/Users/teh/code/insight_project/ENV/bin/python
import pages_getter
import top_words_data
import params
import sys
import itertools
import time
import twitter
import pickle
import re
import os
import string
import sets
import unicodedata
import threading
import urllib2
from Queue import Queue
from collections import Counter
from nltk.tokenize import word_tokenize
from nltk.tokenize import wordpunct_tokenize
from nltk.corpus import wordnet as wn
from nltk.stem import PorterStemmer
def init_data(lang):
if lang == "en":
top_pairs = top_words_data.pairs
elif lang == "es":
top_pairs = top_words_data.es_pairs
top_words = [pair[0] for pair in top_pairs]
return top_words
def simple_get(query, lang):
twitter_search = pages_getter.init_twitter()
num_pages = 15
per_page = 100
query_list = [query for i in range(num_pages)]
page_nums = [i + 1 for i in range(num_pages)]
pages_with_queries = pages_getter.get_pages_of_tweets(twitter_search,
query_list,
page_nums,
per_page,
lang)
pages = [pair[1] for pair in pages_with_queries]
tweets = flatten(pages)
return tweets
def slice_up(query, lang):
query = query.lower()
num_results = params.number_candidates_considered
top_twitter_words = init_data(lang)
tweets = simple_get(query, lang)
split_tweets = clean_tweets(query, tweets)
capital_count, count, keys = count_words_in_tweets(query,
split_tweets,
top_twitter_words)
top_results = extract_top_results(query,
num_results,
capital_count,
count,
keys)
return tweets, count, keys, top_results
def flatten(pages):
return list(itertools.chain.from_iterable(pages))
def clean_tweets(query, tweets):
split_tweets = sets.Set()
query_words = query.split()
tweets = uniq_on_id(tweets)
for tweet in tweets[:]:
if related([tweet['text'].lower()], query_words):
tweet['text'] = re.sub("\ART", "", tweet['text'])
tweet['text'] = re.sub("@\w*", "", tweet['text'])
tweet['text'] = re.sub("#\w*", "", tweet['text'])
tweet['text'] = re.sub("\S*\.\S+", "", tweet['text'])
split_tweets.add(tuple(wordpunct_tokenize(tweet['text'])))
else:
tweets.remove(tweet)
return list(split_tweets)
def uniq_on_id(tweets):
ids_seen = []
uniq_ids_tweets = []
for tweet in tweets:
if tweet['from_user_id'] not in ids_seen:
ids_seen.append(tweet['from_user_id'])
uniq_ids_tweets.append(tweet)
return uniq_ids_tweets
def extract_top_results(query, num_results, capital_cnt, cnt, keys):
cap_freq = params.capitalization_frequency_cutoff
prop_heavy = params.proportion_of_heavy_candidates
capital_frac = [(key, capital_cnt[key] * 1.0 / cnt[key]) for key in
capital_cnt if cnt[key] > 1]
capital_frac = [(a,b) for (a,b) in capital_frac if cap_freq <= b]
capital_frac.sort(key= lambda (a,b): -cnt[a])
just_counts = [cnt[key] for key in keys]
total_candidates = num_results
max_heavy_candidates = int(prop_heavy * total_candidates)
heavy_factor = params.counts_as_heavy_factor
heavy_candidates = [key for key in cnt if (cnt[key] > heavy_factor *
sum(just_counts))]
heavy_candidates.sort(key= lambda w: -cnt[w])
heavy_candidates = heavy_candidates[:max_heavy_candidates]
num_capital_candidates = (total_candidates - len(heavy_candidates))
capital_candidates = [a for (a,b) in capital_frac if a not in
heavy_candidates]
capital_candidates = capital_candidates[:num_capital_candidates]
top_results = heavy_candidates + capital_candidates
candidate_pairs = [(x,y) for (x,y) in itertools.product(top_results,
repeat = 2) if x < y ]
for w1, w2 in candidate_pairs:
if have_common_stems(w1,w2):
descending_pair = sorted([w1,w2], key= lambda w: -cnt[w])
top_results, cnt = consolidate (descending_pair, top_results, cnt)
top_results.sort(key = lambda w: -cnt[w])
return top_results
def consolidate (descending_pair, top_results, count):
high, low = descending_pair
if high not in top_results or low not in top_results:
return top_results, count
else:
count[high] += count[low]
del count[low]
top_results.remove(low)
return top_results, count
def count_words_in_tweets(query, split_tweets, top_twitter_words):
low_information_words = top_twitter_words
cnt = Counter()
capital_cnt = Counter()
query_words = query.lower().split()
min_len = params.minimum_word_length
for split_tweet in split_tweets:
for word in split_tweet:
if (word.lower() not in low_information_words and
re.search("[0-9\W]",word) is None and
related([word.lower()],query_words) is not True and
len(word) >= min_len):
cnt[word.lower()] += 1
if len(re.findall("\A[A-Z]", word)) == 1:
capital_cnt[word.lower()] += 1
keys = [key for key in cnt]
keys.sort(key=lambda k:-cnt[k])
return capital_cnt, cnt, keys
def have_common_stems(word1, word2):
stemmer = PorterStemmer()
if (stemmer.stem(word1) == stemmer.stem(word2)):
return True
else:
return False
def related(word_list1, word_list2):
pairs = itertools.product(word_list1, word_list2)
for a, b in pairs:
if (a.find(b) != -1 or b.find(a) != -1):
return True
return False
| [
"kkwteh@gmail.com"
] | kkwteh@gmail.com |
d53b1fc1e1689725994bab778b7f669f9af08d11 | bd1362c60313784c90013dfc9f0169e64389bf27 | /scripts/feature/min_Xhour.py | 0f41041b31ea7c176d8d0c2e6714c2969c296d22 | [] | no_license | ForceCry/iem | 391aa9daf796591909cb9d4e60e27375adfb0eab | 4b0390d89e6570b99ca83a5fa9b042226e17c1ad | refs/heads/master | 2020-12-24T19:04:55.517409 | 2013-04-09T14:25:36 | 2013-04-09T14:25:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 869 | py | # Generate some comparison data between ASOS sites, tricky, me thinks
import iemdb
import datetime
import numpy
import mx.DateTime
ASOS = iemdb.connect('asos', bypass=True)
acursor = ASOS.cursor()
acursor.execute("SET TIME ZONE 'GMT'")
maxv = 0
def get_data(year, station):
global maxv
data = {}
acursor.execute("""SELECT valid, sknt from t"""+year+""" where station = %s
and (extract(minute from valid) between 50 and 59 or
extract(minute from valid) = 0)
and sknt >= 0 ORDER by valid ASC""", (station,
))
vals = [0,0,0,0]
for row in acursor:
vals.insert(0, row[1] )
vals.pop()
if min(vals) >= maxv:
print vals, min(vals), row[0]
maxv = min(vals)
station1 = 'DSM'
for year in range(1973,2011):
get_data(str(year), station1)
| [
"akrherz@95f8c243-6001-0410-b151-932e6a9ed213"
] | akrherz@95f8c243-6001-0410-b151-932e6a9ed213 |
d38835820987626147fbbc92be11ed27bd6a29e7 | fc10435144fa9ece97f0598fe7ca49f4fbac7193 | /day_5/reduce_most/reduce_most.py | ecf48066b6e741d7466e736efe4baa0f08b771ca | [] | no_license | mo-tion/AdventOfCode2018 | ace19f75e5009d358c6584af4b0db9796e7fb311 | 91c1e85c1006b0ab021b43d1ace964f2ac5a3abc | refs/heads/master | 2020-04-09T04:02:25.740727 | 2018-12-22T17:42:00 | 2018-12-22T17:42:00 | 160,007,943 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,075 | py | import numpy as np
def react_polymer(polymer):
while True:
reduced = False
new_polymer = ""
last_char = None
for i, ch in enumerate(polymer):
if last_char is not None:
if ch is not last_char and (ch.lower() == last_char.lower() or ch.upper() == last_char.upper()):
reduced = True
last_char = None
else:
new_polymer += last_char
last_char = ch
else:
last_char = ch
if last_char is not None:
new_polymer+=last_char
polymer = new_polymer
if not reduced:
break
return len(polymer)
with open("polymer.txt", "r") as freq_file:
input_poly = freq_file.readlines()[0]
alphabet = map(chr, range(97, 123))
len_reacted = []
for ch in alphabet:
reduced_poly = input_poly.replace(ch, '')
reduced_poly = reduced_poly.replace(ch.upper(), '')
len_reacted.append(react_polymer(reduced_poly))
print(np.min(np.array(len_reacted)))
| [
"m.eder@komastudios.com"
] | m.eder@komastudios.com |
c02ce5a8423e7a07dbf65307fb26cf43f7f4e06a | 5fc8acc18c9436a5cd3ffd609108a51e0a259b1d | /backend/test_app_2344_dev_2466/urls.py | 4994650eadd63d8204f557dbe2b404d09a5d8a44 | [] | no_license | crowdbotics-apps/test-app-2344-dev-2466 | 1f3677880346518cd2fb9e3a908aea3339ba78e1 | eb950c673394c455d4d7eeb1ec362bc596a6f444 | refs/heads/master | 2023-02-09T16:02:19.128443 | 2020-04-08T13:20:57 | 2020-04-08T13:20:57 | 254,093,628 | 0 | 0 | null | 2023-01-24T01:59:00 | 2020-04-08T13:20:29 | JavaScript | UTF-8 | Python | false | false | 1,947 | py | """test_app_2344_dev_2466 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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, include
from allauth.account.views import confirm_email
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
urlpatterns = [
path("", include("home.urls")),
path("accounts/", include("allauth.urls")),
path("api/v1/", include("home.api.v1.urls")),
path("admin/", admin.site.urls),
path("users/", include("users.urls", namespace="users")),
path("rest-auth/", include("rest_auth.urls")),
# Override email confirm to use allauth's HTML view instead of rest_auth's API view
path("rest-auth/registration/account-confirm-email/<str:key>/", confirm_email),
path("rest-auth/registration/", include("rest_auth.registration.urls")),
]
admin.site.site_header = "Test-app-2344"
admin.site.site_title = "Test-app-2344 Admin Portal"
admin.site.index_title = "Test-app-2344 Admin"
# swagger
schema_view = get_schema_view(
openapi.Info(
title="Test-app-2344 API",
default_version="v1",
description="API documentation for Test-app-2344 App",
),
public=True,
permission_classes=(permissions.IsAuthenticated,),
)
urlpatterns += [
path("api-docs/", schema_view.with_ui("swagger", cache_timeout=0), name="api_docs")
]
| [
"team@crowdbotics.com"
] | team@crowdbotics.com |
1152ab09724194cae4e2fab10d422c80f3789189 | 57265c1c743f5da6778d5c065e03be93d4f0c93f | /djkombu/tests/testproj/manage.py | b9066fff599f1c1260d7622099fa544098000b78 | [
"BSD-3-Clause"
] | permissive | barseghyanartur/django-kombu | fb63dab46cce7048f50c5131a8edde98f0734c5e | 0f7dbdbd153e7a6d9971dfbb030433a6a85dd984 | refs/heads/master | 2021-01-23T04:59:18.617326 | 2017-06-02T11:51:07 | 2017-06-02T11:51:07 | 92,947,716 | 0 | 0 | null | 2017-05-31T13:21:10 | 2017-05-31T13:21:10 | null | UTF-8 | Python | false | false | 320 | py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings")
sys.path.insert(0, os.path.join(os.getcwd(), '..', '..', '..'))
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| [
"artur.barseghyan@gmail.com"
] | artur.barseghyan@gmail.com |
66611c6c5b0fa19a5a7700b930f3d0f758de9885 | 3e51cf3ee20b2f81314d7f4e320a51d49b311e06 | /Knights/puzzle.py | ba7d3def94182303a00a59231b6008d726bd7b0d | [] | no_license | desoto13/IntroToAI | d407ee3517355a3261fca8732b99085c13be0deb | f4239433366aab916e7d353baef07e165551a8e7 | refs/heads/main | 2023-03-24T06:09:38.563627 | 2021-03-16T09:09:16 | 2021-03-16T09:09:16 | 345,940,857 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,703 | py | from logic import *
AKnight = Symbol("A is a Knight")
AKnave = Symbol("A is a Knave")
BKnight = Symbol("B is a Knight")
BKnave = Symbol("B is a Knave")
CKnight = Symbol("C is a Knight")
CKnave = Symbol("C is a Knave")
# Puzzle 0
# A says "I am both a knight and a knave."
knowledge0 = And(Implication(Not(And(AKnave,AKnight)),AKnave),
Or(AKnave,AKnight))
# Puzzle 1
# A says "We are both knaves."
# B says nothing.
knowledge1 = And(Implication(Not(And(AKnave,BKnave)),AKnave),
Implication(AKnave,BKnight),
Or(AKnave,AKnight),Or(BKnight,BKnave))
# Puzzle 2
# A says "We are the same kind."
# B says "We are of different kinds."
knowledge2 = And(Implication(Or(AKnight,AKnave),BKnight),Implication(BKnight,AKnave),Or(AKnight,AKnave),Or(BKnight,BKnave))
# Puzzle 3
# A says either "I am a knight." or "I am a knave.", but you don't know which.
# B says "A said 'I am a knave'."
# B says "C is a knave."
# C says "A is a knight."
knowledge3 = And(Implication(Or(AKnight,AKnave),AKnight),
Implication(CKnave,BKnight),Implication(CKnight,BKnave),
Implication(AKnight,CKnight),
Or(AKnight,AKnave),Or(BKnight,BKnave),Or(CKnight,CKnave))
def main():
symbols = [AKnight, AKnave, BKnight, BKnave, CKnight, CKnave]
puzzles = [
("Puzzle 0", knowledge0),
("Puzzle 1", knowledge1),
("Puzzle 2", knowledge2),
("Puzzle 3", knowledge3)
]
for puzzle, knowledge in puzzles:
print(puzzle)
if len(knowledge.conjuncts) == 0:
print(" Not yet implemented.")
else:
for symbol in symbols:
if model_check(knowledge, symbol):
print(f" {symbol}")
if __name__ == "__main__":
main()
| [
"mrmisa_windel@yahoo.com"
] | mrmisa_windel@yahoo.com |
4530e7da967992e4e873d204c25802ea30dd670f | 9afb5742e08add8800ad2086ecddd74f017ac9a5 | /tests/test_errors.py | 2c27177c209173f9920701ae351953c2f5064ff8 | [
"BSD-2-Clause"
] | permissive | blockdiag/sphinxcontrib-actdiag | e7fac2739b7aef862f6b0dbea69548ec51960df9 | 8b7ec29b310e718c4510a99fd22c624adc5b19bf | refs/heads/master | 2023-04-10T07:36:45.862708 | 2021-12-05T14:37:35 | 2021-12-05T14:37:35 | 34,159,673 | 1 | 2 | NOASSERTION | 2023-03-18T23:32:50 | 2015-04-18T09:11:37 | Python | UTF-8 | Python | false | false | 1,992 | py | # -*- coding: utf-8 -*-
from mock import patch
from sphinx_testing import with_app
import sys
import unittest
class TestSphinxcontribActdiagErrors(unittest.TestCase):
@with_app(srcdir='tests/docs/basic', write_docstring=True)
def test_parse_error(self, app, status, warning):
"""
.. actdiag::
{ A -> B;
"""
app.builder.build_all()
self.assertIn('got unexpected token:', warning.getvalue())
@with_app(srcdir='tests/docs/basic', confoverrides=dict(actdiag_html_image_format='JPG'))
def test_unknown_format_error(self, app, status, warning):
app.builder.build_all()
self.assertIn('unknown format: JPG', warning.getvalue())
@with_app(srcdir='tests/docs/basic', confoverrides=dict(actdiag_html_image_format='PDF'))
def test_reportlab_not_found_error(self, app, status, warning):
try:
# unload reportlab and make loading it impossible
sys.modules.pop('reportlab', None)
path = sys.path
sys.path = []
app.builder.build_all()
self.assertIn('Could not output PDF format. Install reportlab.',
warning.getvalue())
finally:
sys.path = path
@with_app(srcdir='tests/docs/basic')
@patch("actdiag.utils.rst.nodes.actdiag.processor.drawer.DiagramDraw")
def test_rendering_error(self, app, status, warning, DiagramDraw):
DiagramDraw.side_effect = RuntimeError("UNKNOWN ERROR!")
app.builder.build_all()
self.assertIn('UNKNOWN ERROR!', warning.getvalue())
@with_app(srcdir='tests/docs/basic')
@patch("sphinxcontrib.actdiag.actdiag.drawer.DiagramDraw.draw")
def test_font_settings_error(self, app, status, warning, draw):
draw.side_effect = UnicodeEncodeError("", "", 0, 0, "")
app.builder.build_all()
self.assertIn('UnicodeEncodeError caught (check your font settings)',
warning.getvalue())
| [
"i.tkomiya@gmail.com"
] | i.tkomiya@gmail.com |
bc3a16db4d19b8e9d60b28add19d1c884286d471 | 50c2e7facba5f0be15ed8d89ce5633cb1f698058 | /test_recompressor.py | f79dc177be67572e08068f8c0afd6b4ef6b070f2 | [] | no_license | Gray0Ed/ggp_thesis | 59cfbd072aba059294187c134d57b9b7536886c9 | d4f7aac8c47e49f687ed33721e0010ff35318083 | refs/heads/master | 2020-09-25T10:14:13.417641 | 2016-10-03T16:42:55 | 2016-10-03T16:42:55 | 67,509,252 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,873 | py | import os
import sys
from os.path import isfile
RECOMPRESSOR_INPUTS_D = 'test/recompressor_inputs/'
RECOMPRESSOR_OUTPUTS_D = 'test/recompressor_outputs/'
COMMAND_CHAIN = [
("python simplify_by_sancho.py {0} {1} >{2} 2>{3}", "simplified"),
("./rule_engine/reprinter {0} {1} >{2} 2>{3}", "first_reprinted"),
#("python flatten_by_sancho.py {0} {1} >{2} 2>{3}", "flattened"),
("./rule_engine/flatten {0} {1} >{2} 2>{3}", "flattened"),
("./rule_engine/reprinter {0} {1} >{2} 2>{3}", "reprinted"),
("time ./rule_engine/recompressor {0} {1} >{2} 2>{3}", "recompressed"),
]
def run_cmd(cmd_s):
print cmd_s
return os.system(cmd_s)
def run_cmd_fail(cmd_s):
if run_cmd(cmd_s):
raise Exception("Command:\n%s\nfailed." % cmd_s)
def make():
if run_cmd("cd rule_engine && make") != 0:
raise Exception("compilation failed")
def main():
os.system('mkdir -p test/recompressor_outputs')
global inputs
if len(sys.argv) > 1:
inputs = sys.argv[1:]
else:
raise Exception("No inputs provided")
make()
for inpf in inputs:
cmd_input = None
out_dir = (RECOMPRESSOR_OUTPUTS_D + inpf + '/')
run_cmd("mkdir -p %s" % out_dir)
for command_pattern, output_suffix in COMMAND_CHAIN:
if cmd_input is None:
cmd_input = RECOMPRESSOR_INPUTS_D + inpf
if not isfile(cmd_input):
raise Exception("file %s does not exist" % cmd_input)
cmd_output = out_dir + output_suffix
cmd_stdout = cmd_output + '.stdout'
cmd_stderr = cmd_output + '.stderr'
cmd = command_pattern.format(
cmd_input, cmd_output,
cmd_stdout, cmd_stderr)
run_cmd_fail(cmd)
cmd_input = cmd_output
if __name__ == '__main__':
main()
| [
"kwasniakjanek@gmail.com"
] | kwasniakjanek@gmail.com |
24d5d090979b05f93260f3915616be3065a6f89d | dabbbfda49d058a7f4006f809a5bd502a4da0f76 | /kumaoche/__init__.py | f4201cf655a15066660cb808cf26fdefb4979848 | [
"MIT"
] | permissive | kumak1/kumaoche | 9f3f2f7e709db83e6781e86ffc3fbd9e7583fbc7 | 4421670bd8db5654fd33378ffe298bb8f0e12788 | refs/heads/master | 2021-06-27T01:33:17.403004 | 2021-03-27T14:06:19 | 2021-03-27T14:06:19 | 222,382,432 | 0 | 0 | MIT | 2021-03-27T14:06:19 | 2019-11-18T06:53:41 | Python | UTF-8 | Python | false | false | 58 | py | # -*- coding: utf-8 -*-
from .container import Container
| [
"makino@pepabo.com"
] | makino@pepabo.com |
da144278f9b5122abe6a2ada6e8b937379d84335 | 9e643d565e38de1728eabf31304e7dcbdf3ebfdd | /Python/Django/manyToMany/apps/manyToManyApp/migrations/0001_initial.py | 522b5d14fb92bd5b6297d49a27747de163be6a68 | [] | no_license | joeyzoland/DojoAssignments | 88dca37ad1d5b585a4af1dabc49935ef34adf6a0 | 0cae15aa448c490af931b41939638456456cef63 | refs/heads/master | 2021-01-11T17:55:13.775179 | 2018-09-17T07:32:12 | 2018-09-17T07:32:12 | 79,875,553 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,308 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-23 16:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Interest',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=45)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
),
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=45)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
),
migrations.AddField(
model_name='interest',
name='users',
field=models.ManyToManyField(related_name='interests', to='manyToManyApp.User'),
),
]
| [
"joeyzoland@gmail.com"
] | joeyzoland@gmail.com |
fc3224cee8e0bbf961ab7c2a6c57029296d8cb27 | c534bc4803aa6c191efc8d1562b3e1e4fb3bf689 | /mustangroundup/apps.py | b9a43e621723cdfe9d828468454346bf217a47c4 | [
"Apache-2.0"
] | permissive | Agentscreech/mustang-roundup | 8b18be96ce2dcd763987bc843e686041f867e74d | 1077ed67c7f198d2288553553f4ccac31979b055 | refs/heads/master | 2021-04-06T10:57:56.634956 | 2018-05-11T02:01:20 | 2018-05-11T02:01:20 | 124,710,693 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 155 | py | from django.apps import AppConfig
class MustangroundupConfig(AppConfig):
name = 'mustangroundup'
def ready(self):
from . import signals
| [
"travis.walentin@gmail.com"
] | travis.walentin@gmail.com |
e7d7859716360c2810a05219a324d9dfb4e0b73d | 3adeb86bf163ffa3fc80d66454ca6fa884deeb25 | /Temprorary/adb_tool.py | 0840c4c061dcff3f553a1cc14b387694cc2d97ad | [] | no_license | SummerOcean/autoAPP | eebacdbe5fce2e3598121805f9db18a45abb7947 | c6d13214190935cf111b654c14e0c4a52523c8ae | refs/heads/master | 2023-03-09T05:09:52.173293 | 2020-12-23T12:42:40 | 2020-12-23T12:42:40 | 341,506,014 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 28,399 | py | # encoding: utf-8
"""
# @author: 薛钦耀
# @E-mail: xueqinyao@dingtalk.com
# @software: pycharm
# @file: adb_tool.py
# @time: 2020/3/4 18:51
# @project: ERP
# @project: saleman_APP
# @project: warehouse_PDA
# @此模块提供:adb 工具类
"""
import os
import platform
import re
import time
import utils.timetools
class AdbTools(object):
def __init__(self, device_id=''):
self.__system = platform.system()
self.__find = ''
self.__command = ''
self.__device_id = device_id
self.__get_find()
self.__check_adb()
self.__connection_devices()
def __get_find(self):
"""
判断系统类型,windows使用findstr,linux使用grep
:return:
"""
if self.__system is "Windows":
self.__find = "findstr"
else:
self.__find = "grep"
def __check_adb(self):
"""
检查adb
判断是否设置环境变量ANDROID_HOME
:return:
"""
if "ANDROID_HOME" in os.environ:
if self.__system == "Windows":
path = os.path.join(os.environ["ANDROID_HOME"], "platform-tools", "adb.exe")
if os.path.exists(path):
self.__command = path
else:
raise EnvironmentError(
"Adb not found in $ANDROID_HOME path: %s." % os.environ["ANDROID_HOME"])
else:
path = os.path.join(os.environ["ANDROID_HOME"], "platform-tools", "adb")
if os.path.exists(path):
self.__command = path
else:
raise EnvironmentError(
"Adb not found in $ANDROID_HOME path: %s." % os.environ["ANDROID_HOME"])
else:
raise EnvironmentError(
"Adb not found in $ANDROID_HOME path: %s." % os.environ["ANDROID_HOME"])
def __connection_devices(self):
"""
连接指定设备,单个设备可不传device_id
:return:
"""
if self.__device_id == "":
return
self.__device_id = "-s %s" % self.__device_id
def adb(self, args):
"""
执行adb命令
:param args:参数
:return:
"""
cmd = "%s %s %s" % (self.__command, self.__device_id, str(args))
# print(cmd)
return os.popen(cmd)
def shell(self, args):
"""
执行adb shell命令
:param args:参数
:return:
"""
cmd = "%s %s shell %s" % (self.__command, self.__device_id, str(args))
# print(cmd)
return os.popen(cmd)
def mkdir(self, path):
"""
创建目录
:param path: 路径
:return:
"""
return self.shell('mkdir %s' % path)
def get_devices(self):
"""
获取设备列表
:return:
"""
l = self.adb('devices').readlines()
return (i.split()[0] for i in l if 'devices' not in i and len(i) > 5)
def get_current_application(self):
"""
获取当前运行的应用信息
:return:
"""
return self.shell('dumpsys window w | %s \/ | %s name=' % (self.__find, self.__find)).read()
def get_current_package(self):
"""
获取当前运行app包名
:return:
"""
reg = re.compile(r'name=(.+?)/')
return re.findall(reg, self.get_current_application())[0]
def get_current_activity(self):
"""
获取当前运行activity
:return: package/activity
"""
reg = re.compile(r'name=(.+?)\)')
return re.findall(reg, self.get_current_application())[0]
def __get_process(self, package_name):
"""
获取进程信息
:param package_name:
:return:
"""
if self.__system is "Windows":
pid_command = self.shell("ps | %s %s$" % (self.__find, package_name)).read()
else:
pid_command = self.shell("ps | %s -w %s" % (self.__find, package_name)).read()
return pid_command
def process_exists(self, package_name):
"""
返回进程是否存在
:param package_name:
:return:
"""
process = self.__get_process(package_name)
return package_name in process
def get_pid(self, package_name):
"""
获取pid
:return:
"""
pid_command = self.__get_process(package_name)
if pid_command == '':
print("The process doesn't exist.")
return pid_command
req = re.compile(r"\d+")
result = str(pid_command).split()
result.remove(result[0])
return req.findall(" ".join(result))[0]
def get_uid(self, pid):
"""
获取uid
:param pid:
:return:
"""
result = self.shell("cat /proc/%s/status" % pid).readlines()
for i in result:
if 'uid' in i.lower():
return i.split()[1]
def get_flow_data_tcp(self, uid):
"""
获取应用tcp流量
:return:(接收, 发送)
"""
tcp_rcv = self.shell("cat proc/uid_stat/%s/tcp_rcv" % uid).read().split()[0]
tcp_snd = self.shell("cat proc/uid_stat/%s/tcp_snd" % uid).read().split()[0]
return tcp_rcv, tcp_snd
def get_flow_data_all(self, uid):
"""
获取应用流量全部数据
包含该应用多个进程的所有数据 tcp udp等
(rx_bytes, tx_bytes) >> (接收, 发送)
:param uid:
:return:list(dict)
"""
all_data = []
d = {}
data = self.shell("cat /proc/net/xt_qtaguid/stats | %s %s" % (self.__find, uid)).readlines()
for i in data:
if not i.startswith('\n'):
item = i.strip().split()
d['idx'] = item[0]
d['iface'] = item[1]
d['acct_tag_hex'] = item[2]
d['uid_tag_int'] = item[3]
d['cnt_set'] = item[4]
d['rx_bytes'] = item[5]
d['rx_packets'] = item[6]
d['tx_bytes'] = item[7]
d['tx_packets'] = item[8]
d['rx_tcp_bytes'] = item[9]
d['rx_tcp_packets'] = item[10]
d['rx_udp_bytes'] = item[11]
d['rx_udp_packets'] = item[12]
d['rx_other_bytes'] = item[13]
d['rx_other_packets'] = item[14]
d['tx_tcp_bytes'] = item[15]
d['tx_tcp_packets'] = item[16]
d['tx_udp_bytes'] = item[17]
d['tx_udp_packets'] = item[18]
d['tx_other_bytes'] = item[19]
d['tx_other_packets'] = item[20]
all_data.append(d)
d = {}
return all_data
@staticmethod
def dump_apk(path):
"""
dump apk文件
:param path: apk路径
:return:
"""
# 检查build-tools是否添加到环境变量中
# 需要用到里面的aapt命令
l = os.environ['PATH'].split(';')
build_tools = False
for i in l:
if 'build-tools' in i:
build_tools = True
if not build_tools:
raise EnvironmentError("ANDROID_HOME BUILD-TOOLS COMMAND NOT FOUND.\nPlease set the environment variable.")
return os.popen('aapt dump badging %s' % (path,))
@staticmethod
def dump_xml(path, filename):
"""
dump apk xml文件
:return:
"""
return os.popen('aapt dump xmlstrings %s %s' % (path, filename))
def uiautomator_dump(self):
"""
获取屏幕uiautomator xml文件
:return:
"""
return self.shell('uiautomator dump').read().split()[-1]
def pull(self, source, target):
"""
从手机端拉取文件到电脑端
:return:
"""
self.adb('pull %s %s' % (source, target))
def push(self, source, target):
"""
从电脑端推送文件到手机端
:param source:
:param target:
:return:
"""
self.adb('push %s %s' % (source, target))
def remove(self, path):
"""
从手机端删除文件
:return:
"""
self.shell('rm %s' % (path,))
def clear_app_data(self, package):
"""
清理应用数据
:return:
"""
self.shell('pm clear %s' % (package,))
def install(self, path):
"""
安装apk文件
:return:
"""
# adb install 安装错误常见列表
errors = {'INSTALL_FAILED_ALREADY_EXISTS': '程序已经存在',
'INSTALL_DEVICES_NOT_FOUND': '找不到设备',
'INSTALL_FAILED_DEVICE_OFFLINE': '设备离线',
'INSTALL_FAILED_INVALID_APK': '无效的APK',
'INSTALL_FAILED_INVALID_URI': '无效的链接',
'INSTALL_FAILED_INSUFFICIENT_STORAGE': '没有足够的存储空间',
'INSTALL_FAILED_DUPLICATE_PACKAGE': '已存在同名程序',
'INSTALL_FAILED_NO_SHARED_USER': '要求的共享用户不存在',
'INSTALL_FAILED_UPDATE_INCOMPATIBLE': '版本不能共存',
'INSTALL_FAILED_SHARED_USER_INCOMPATIBLE': '需求的共享用户签名错误',
'INSTALL_FAILED_MISSING_SHARED_LIBRARY': '需求的共享库已丢失',
'INSTALL_FAILED_REPLACE_COULDNT_DELETE': '需求的共享库无效',
'INSTALL_FAILED_DEXOPT': 'dex优化验证失败',
'INSTALL_FAILED_DEVICE_NOSPACE': '手机存储空间不足导致apk拷贝失败',
'INSTALL_FAILED_DEVICE_COPY_FAILED': '文件拷贝失败',
'INSTALL_FAILED_OLDER_SDK': '系统版本过旧',
'INSTALL_FAILED_CONFLICTING_PROVIDER': '存在同名的内容提供者',
'INSTALL_FAILED_NEWER_SDK': '系统版本过新',
'INSTALL_FAILED_TEST_ONLY': '调用者不被允许测试的测试程序',
'INSTALL_FAILED_CPU_ABI_INCOMPATIBLE': '包含的本机代码不兼容',
'CPU_ABIINSTALL_FAILED_MISSING_FEATURE': '使用了一个无效的特性',
'INSTALL_FAILED_CONTAINER_ERROR': 'SD卡访问失败',
'INSTALL_FAILED_INVALID_INSTALL_LOCATION': '无效的安装路径',
'INSTALL_FAILED_MEDIA_UNAVAILABLE': 'SD卡不存在',
'INSTALL_FAILED_INTERNAL_ERROR': '系统问题导致安装失败',
'INSTALL_PARSE_FAILED_NO_CERTIFICATES': '文件未通过认证 >> 设置开启未知来源',
'INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES': '文件认证不一致 >> 先卸载原来的再安装',
'INSTALL_FAILED_INVALID_ZIP_FILE': '非法的zip文件 >> 先卸载原来的再安装',
'INSTALL_CANCELED_BY_USER': '需要用户确认才可进行安装',
'INSTALL_FAILED_VERIFICATION_FAILURE': '验证失败 >> 尝试重启手机',
'DEFAULT': '未知错误'
}
print('Installing...')
l = self.adb('install -r %s' % (path,)).read()
if 'Success' in l:
print('Install Success')
if 'Failure' in l:
reg = re.compile('\\[(.+?)\\]')
key = re.findall(reg, l)[0]
try:
print('Install Failure >> %s' % errors[key])
except KeyError:
print('Install Failure >> %s' % key)
return l
def uninstall(self, package):
"""
卸载apk
:param package: 包名
:return:
"""
print('Uninstalling...')
l = self.adb('uninstall %s' % (package,)).read()
print(l)
def screenshot(self, target_path=''):
"""
手机截图
:param target_path: 目标路径
:return:
"""
format_time = utils.timetools.timestamp('%Y%m%d%H%M%S')
self.shell('screencap -p /sdcard/%s.png' % (format_time,))
time.sleep(1)
if target_path == '':
self.pull('/sdcard/%s.png' % (format_time,), os.path.expanduser('~'))
else:
self.pull('/sdcard/%s.png' % (format_time,), target_path)
self.remove('/sdcard/%s.png' % (format_time,))
def get_cache_logcat(self):
"""
导出缓存日志
:return:
"""
return self.adb('logcat -v time -d')
def get_crash_logcat(self):
"""
导出崩溃日志
:return:
"""
return self.adb('logcat -v time -d | %s AndroidRuntime' % (self.__find,))
def clear_cache_logcat(self):
"""
清理缓存区日志
:return:
"""
self.adb('logcat -c')
def get_device_time(self):
"""
获取设备时间
:return:
"""
return self.shell('date').read().strip()
def ls(self, command):
"""
shell ls命令
:return:
"""
return self.shell('ls %s' % (command,)).readlines()
def file_exists(self, target):
"""
判断文件在目标路径是否存在
:return:
"""
l = self.ls(target)
for i in l:
if i.strip() == target:
return True
return False
def is_install(self, target_app):
"""
判断目标app在设备上是否已安装
:param target_app: 目标app包名
:return: bool
"""
return target_app in self.shell('pm list packages %s' % (target_app,)).read()
def get_device_model(self):
"""
获取设备型号
:return:
"""
return self.shell('getprop ro.product.model').read().strip()
def get_device_id(self):
"""
获取设备id
:return:
"""
return self.adb('get-serialno').read().strip()
def get_device_android_version(self):
"""
获取设备Android版本
:return:
"""
return self.shell('getprop ro.build.version.release').read().strip()
def get_device_sdk_version(self):
"""
获取设备SDK版本
:return:
"""
return self.shell('getprop ro.build.version.sdk').read().strip()
def get_device_mac_address(self):
"""
获取设备MAC地址
:return:
"""
return self.shell('cat /sys/class/net/wlan0/address').read().strip()
def get_device_ip_address(self):
"""
获取设备IP地址
pass: 适用WIFI 蜂窝数据
:return:
"""
if not self.get_wifi_state() and not self.get_data_state():
return
l = self.shell('ip addr | %s global' % self.__find).read()
reg = re.compile('\d+\.\d+\.\d+\.\d+')
return re.findall(reg, l)[0]
def get_device_imei(self):
"""
获取设备IMEI
:return:
"""
sdk = self.get_device_sdk_version()
# Android 5.0以下方法
if int(sdk) < 21:
l = self.shell('dumpsys iphonesubinfo').read()
reg = re.compile('[0-9]{15}')
return re.findall(reg, l)[0]
elif self.root():
l = self.shell('service call iphonesubinfo 1').read()
print(l)
print(re.findall(re.compile("'.+?'"), l))
imei = ''
for i in re.findall(re.compile("'.+?'"), l):
imei += i.replace('.', '').replace("'", '').replace(' ', '')
return imei
else:
print('The device not root.')
return ''
def check_sim_card(self):
"""
检查设备SIM卡
:return:
"""
return len(self.shell('getprop | %s gsm.operator.alpha]' % self.__find).read().strip().split()[-1]) > 2
def get_device_operators(self):
"""
获取运营商
:return:
"""
return self.shell('getprop | %s gsm.operator.alpha]' % self.__find).read().strip().split()[-1]
def get_device_state(self):
"""
获取设备状态
:return:
"""
return self.adb('get-state').read().strip()
def get_display_state(self):
"""
获取屏幕状态
:return: 亮屏/灭屏
"""
l = self.shell('dumpsys power').readlines()
for i in l:
if 'mScreenOn=' in i:
return i.split()[-1] == 'mScreenOn=true'
if 'Display Power' in i:
return 'ON' in i.split('=')[-1].upper()
def get_screen_normal_size(self):
"""
获取设备屏幕分辨率 >> 标配
:return:
"""
return self.shell('wm size').read().strip().split()[-1].split('x')
def get_screen_reality_size(self):
"""
获取设备屏幕分辨率 >> 实际分辨率
:return:
"""
x = 0
y = 0
l = self.shell(r'getevent -p | %s -e "0"' % self.__find).readlines()
for n in l:
if len(n.split()) > 0:
if n.split()[0] == '0035':
x = int(n.split()[7].split(',')[0])
elif n.split()[0] == '0036':
y = int(n.split()[7].split(',')[0])
return x, y
def get_device_interior_sdcard(self):
"""
获取内部SD卡空间
:return: (path,total,used,free,block)
"""
return self.shell('df | %s \/mnt\/shell\/emulated' % self.__find).read().strip().split()
def get_device_external_sdcard(self):
"""
获取外部SD卡空间
:return: (path,total,used,free,block)
"""
return self.shell('df | %s \/storage' % self.__find).read().strip().split()
def __fill_rom(self, path, stream, count):
"""
填充数据
:param path: 填充地址
:param stream: 填充流大小
:param count: 填充次数
:return:
"""
self.shell('dd if=/dev/zero of=%s bs=%s count=%s' % (path, stream, count)).read().strip()
def fill_interior_sdcard(self, filename, size):
"""
填充内置SD卡
:param filename: 文件名
:param size: 填充大小,单位byte
:return:
"""
if size > 10485760: # 10m
self.__fill_rom('sdcard/%s' % filename, 10485760, size / 10485760)
else:
self.__fill_rom('sdcard/%s' % filename, size, 1)
def fill_external_sdcard(self, filename, size):
"""
填充外置SD卡
:param filename: 文件名
:param size: 填充大小,单位byte
:return:
"""
path = self.get_device_external_sdcard()[0]
if size > 10485760: # 10m
self.__fill_rom('%s/%s' % (path, filename), 10485760, size / 10485760)
else:
self.__fill_rom('%s/%s' % (path, filename), size, 1)
def kill_process(self, pid):
"""
杀死进程
pass: 一般需要权限不推荐使用
:return:
"""
return self.shell('kill %s' % pid).read().strip()
def quit_app(self, package):
"""
退出应用
:return:
"""
return self.shell('am force-stop %s' % package).read().strip()
def reboot(self):
"""
重启设备
:return:
"""
self.adb('reboot')
def recovery(self):
"""
重启设备并进入recovery模式
:return:
"""
self.adb('reboot recovery')
def fastboot(self):
"""
重启设备并进入fastboot模式
:return:
"""
self.adb('reboot bootloader')
def root(self):
"""
获取root状态
:return:
"""
return 'not found' not in self.shell('su -c ls -l /data/').read().strip()
def wifi(self, power):
"""
开启/关闭wifi
pass: 需要root权限
:return:
"""
if not self.root():
print('The device not root.')
return
if power:
self.shell('su -c svc wifi enable').read().strip()
else:
self.shell('su -c svc wifi disable').read().strip()
def data(self, power):
"""
开启/关闭蜂窝数据
pass: 需要root权限
:return:
"""
if not self.root():
print('The device not root.')
return
if power:
self.shell('su -c svc data enable').read().strip()
else:
self.shell('su -c svc data disable').read().strip()
def get_wifi_state(self):
"""
获取WiFi连接状态
:return:
"""
return 'enabled' in self.shell('dumpsys wifi | %s ^Wi-Fi' % self.__find).read().strip()
def get_data_state(self):
"""
获取移动网络连接状态
:return:
"""
return '2' in self.shell('dumpsys telephony.registry | %s mDataConnectionState' % self.__find).read().strip()
def get_network_state(self):
"""
设备是否连上互联网
:return:
"""
return 'unknown host' not in self.shell('ping -w 1 www.baidu.com').read().strip()
def get_wifi_password_list(self):
"""
获取WIFI密码列表
:return:
"""
if not self.root():
print('The device not root.')
return []
l = re.findall(re.compile('ssid=".+?"\s{3}psk=".+?"'), self.shell('su -c cat /data/misc/wifi/*.conf').read())
return [re.findall(re.compile('".+?"'), i) for i in l]
def call(self, number):
"""
拨打电话
:param number:
:return:
"""
self.shell('am start -a android.intent.action.CALL -d tel:%s' % number)
def open_url(self, url):
"""
打开网页
:return:
"""
self.shell('am start -a android.intent.action.VIEW -d %s' % url)
def start_application(self, component):
"""
启动一个应用
e.g: com.android.settings/com.android.settings.Settings
"""
self.shell("am start -n %s" % component)
def send_keyevent(self, keycode):
"""
发送一个按键事件
https://developer.android.com/reference/android/view/KeyEvent.html
:return:
"""
self.shell('input keyevent %s' % keycode)
def rotation_screen(self, param):
"""
旋转屏幕
:param param: 0 >> 纵向,禁止自动旋转; 1 >> 自动旋转
:return:
"""
self.shell('/system/bin/content insert --uri content://settings/system --bind '
'name:s:accelerometer_rotation --bind value:i:%s' % param)
def instrument(self, command):
"""
启动instrument app
:param command: 命令
:return:
"""
return self.shell('am instrument %s' % command).read()
def export_apk(self, package, target_path='', timeout=5000):
"""
从设备导出应用
:param timeout: 超时时间
:param target_path: 导出后apk存储路径
:param package: 包名
:return:
"""
num = 0
if target_path == '':
self.adb('pull /data/app/%s-1/base.apk %s' % (package, os.path.expanduser('~')))
while 1:
num += 1
if num <= timeout:
if os.path.exists(os.path.join(os.path.expanduser('~'), 'base.apk')):
os.rename(os.path.join(os.path.expanduser('~'), 'base.apk'),
os.path.join(os.path.expanduser('~'), '%s.apk' % package))
else:
self.adb('pull /data/app/%s-1/base.apk %s' % (package, target_path))
while 1:
num += 1
if num <= timeout:
if os.path.exists(os.path.join(os.path.expanduser('~'), 'base.apk')):
os.rename(os.path.join(os.path.expanduser('~'), 'base.apk'),
os.path.join(os.path.expanduser('~'), '%s.apk' % package))
class KeyCode:
KEYCODE_CALL = 5 # 拨号键
KEYCODE_ENDCALL = 6 # 挂机键
KEYCODE_HOME = 3 # Home键
KEYCODE_MENU = 82 # 菜单键
KEYCODE_BACK = 4 # 返回键
KEYCODE_SEARCH = 84 # 搜索键
KEYCODE_CAMERA = 27 # 拍照键
KEYCODE_FOCUS = 80 # 对焦键
KEYCODE_POWER = 26 # 电源键
KEYCODE_NOTIFICATION = 83 # 通知键
KEYCODE_MUTE = 91 # 话筒静音键
KEYCODE_VOLUME_MUTE = 164 # 扬声器静音键
KEYCODE_VOLUME_UP = 24 # 音量+键
KEYCODE_VOLUME_DOWN = 25 # 音量-键
KEYCODE_ENTER = 66 # 回车键
KEYCODE_ESCAPE = 111 # ESC键
KEYCODE_DPAD_CENTER = 23 # 导航键 >> 确定键
KEYCODE_DPAD_UP = 19 # 导航键 >> 向上
KEYCODE_DPAD_DOWN = 20 # 导航键 >> 向下
KEYCODE_DPAD_LEFT = 21 # 导航键 >> 向左
KEYCODE_DPAD_RIGHT = 22 # 导航键 >> 向右
KEYCODE_MOVE_HOME = 122 # 光标移动到开始键
KEYCODE_MOVE_END = 123 # 光标移动到末尾键
KEYCODE_PAGE_UP = 92 # 向上翻页键
KEYCODE_PAGE_DOWN = 93 # 向下翻页键
KEYCODE_DEL = 67 # 退格键
KEYCODE_FORWARD_DEL = 112 # 删除键
KEYCODE_INSERT = 124 # 插入键
KEYCODE_TAB = 61 # Tab键
KEYCODE_NUM_LOCK = 143 # 小键盘锁
KEYCODE_CAPS_LOCK = 115 # 大写锁定键
KEYCODE_BREAK = 121 # Break / Pause键
KEYCODE_SCROLL_LOCK = 116 # 滚动锁定键
KEYCODE_ZOOM_IN = 168 # 放大键
KEYCODE_ZOOM_OUT = 169 # 缩小键
KEYCODE_0 = 7
KEYCODE_1 = 8
KEYCODE_2 = 9
KEYCODE_3 = 10
KEYCODE_4 = 11
KEYCODE_5 = 12
KEYCODE_6 = 13
KEYCODE_7 = 14
KEYCODE_8 = 15
KEYCODE_9 = 16
KEYCODE_A = 29
KEYCODE_B = 30
KEYCODE_C = 31
KEYCODE_D = 32
KEYCODE_E = 33
KEYCODE_F = 34
KEYCODE_G = 35
KEYCODE_H = 36
KEYCODE_I = 37
KEYCODE_J = 38
KEYCODE_K = 39
KEYCODE_L = 40
KEYCODE_M = 41
KEYCODE_N = 42
KEYCODE_O = 43
KEYCODE_P = 44
KEYCODE_Q = 45
KEYCODE_R = 46
KEYCODE_S = 47
KEYCODE_T = 48
KEYCODE_U = 49
KEYCODE_V = 50
KEYCODE_W = 51
KEYCODE_X = 52
KEYCODE_Y = 53
KEYCODE_Z = 54
KEYCODE_PLUS = 81 # +
KEYCODE_MINUS = 69 # -
KEYCODE_STAR = 17 # *
KEYCODE_SLASH = 76 # /
KEYCODE_EQUALS = 70 # =
KEYCODE_AT = 77 # @
KEYCODE_POUND = 18 # #
KEYCODE_APOSTROPHE = 75 # '
KEYCODE_BACKSLASH = 73 # \
KEYCODE_COMMA = 55 # ,
KEYCODE_PERIOD = 56 # .
KEYCODE_LEFT_BRACKET = 71 # [
KEYCODE_RIGHT_BRACKET = 72 # ]
KEYCODE_SEMICOLON = 74 # ;
KEYCODE_GRAVE = 68 # `
KEYCODE_SPACE = 62 # 空格键
KEYCODE_MEDIA_PLAY = 126 # 多媒体键 >> 播放
KEYCODE_MEDIA_STOP = 86 # 多媒体键 >> 停止
KEYCODE_MEDIA_PAUSE = 127 # 多媒体键 >> 暂停
KEYCODE_MEDIA_PLAY_PAUSE = 85 # 多媒体键 >> 播放 / 暂停
KEYCODE_MEDIA_FAST_FORWARD = 90 # 多媒体键 >> 快进
KEYCODE_MEDIA_REWIND = 89 # 多媒体键 >> 快退
KEYCODE_MEDIA_NEXT = 87 # 多媒体键 >> 下一首
KEYCODE_MEDIA_PREVIOUS = 88 # 多媒体键 >> 上一首
KEYCODE_MEDIA_CLOSE = 128 # 多媒体键 >> 关闭
KEYCODE_MEDIA_EJECT = 129 # 多媒体键 >> 弹出
KEYCODE_MEDIA_RECORD = 130 # 多媒体键 >> 录音
if __name__ == '__main__':
a = AdbTools()
pass
| [
"xueqinyao@dingtalk.com"
] | xueqinyao@dingtalk.com |
5c5b0bd6253cdaf85c6cc7a917501d4d07ad5459 | 7e4b2017d3530558a602944fd9dfc1f13cf4fe1c | /gameOfLife.py | 992e8d8e35b55aa717edc9d174f9bf01aec9c472 | [] | no_license | Dillonb/gameOfLife | 5fc3ea658e1337aab7d8a53298ab1a7772e270ca | 40c7dd58c0a3c4aea829be917f413e7306d914ad | refs/heads/master | 2021-01-10T22:01:06.834572 | 2013-01-05T20:12:01 | 2013-01-05T20:12:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,241 | py | import pygame
import random
import math
import copy
pygame.init()
screensize = [800,600]
screen = pygame.display.set_mode(screensize)
screen.fill([255,255,255])
mainloop = True
autorun = False
fps = 60
generations = 0
gridsize = 60
def refreshGrid():
global grid, nextGrid, gridsize, generations
grid = []
nextGrid = []
for i in range(0,gridsize):
tmp = []
for i2 in range(0,gridsize):
#tmp.append(False)
if random.randint(0,1) == 0:
tmp.append(False)
else:
tmp.append(True)
grid.append(tmp)
nextGrid.append(tmp)
generations = 0
refreshGrid()
def clearGrid():
global grid,nextGrid, gridsize, generations, lastDrawnGrid
for x in range(0,gridsize):
for y in range(0,gridsize):
grid[x][y] = False
nextGrid[x][y] = False
generations = 0
lastDrawnGrid = []
def getNumNeighbors(x,y):
global grid, gridsize
numNeighbors = 0
for xDif in range(-1,2):
for yDif in range(-1,2):
if xDif == 0 and yDif == 0:
continue
xCoord = x+xDif
yCoord = y+yDif
#print "Checking " + str(xCoord) + ", " + str(yCoord)
if xCoord < 0 or yCoord < 0 or xCoord >= gridsize or yCoord >= gridsize:
pass
else:
if grid[xCoord][yCoord]:
numNeighbors += 1
return numNeighbors
def generation():
global grid, gridsize, nextGrid, generations
nextGrid = copy.deepcopy(grid)
for x in range(0,gridsize):
for y in range(0,gridsize):
n = getNumNeighbors(x,y)
if n == 2:
pass
elif n == 3:
nextGrid[x][y] = True
else:
nextGrid[x][y] = False
grid = nextGrid
generations += 1
xstretch = screensize[0]/gridsize
ystretch = screensize[1]/gridsize
print xstretch,ystretch
Clock = pygame.time.Clock()
lastDrawnGrid = None
def drawScreen():
screen.fill([255,255,255])
#draw the screen
screen.lock()
for x in range(0,gridsize):
for y in range(0,gridsize):
if grid[x][y]:
pygame.draw.rect(screen, (0,0,0), (x*xstretch,y*ystretch, xstretch, ystretch))
screen.unlock()
while mainloop:
tickFPS = Clock.tick(fps)
if autorun:
runningState = "Running."
else:
runningState = "Idle."
pygame.display.set_caption("%s Press Esc to quit. FPS: %.2f Generations: %d" % (runningState, Clock.get_fps(), generations))
if autorun:
generation()
#only draw the screen if there's something new
if lastDrawnGrid != grid:
drawScreen()
lastDrawnGrid = grid
for event in pygame.event.get():
if event.type == pygame.QUIT:
mainloop = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
mainloop = False
if event.key == pygame.K_g:
generation()
if event.key == pygame.K_r:
refreshGrid()
if event.key == pygame.K_c:
clearGrid()
if event.key == pygame.K_SPACE:
if autorun == False:
autorun = True
else:
autorun = False
elif event.type == pygame.MOUSEBUTTONDOWN:
xtile = int(math.ceil(event.pos[0] / xstretch))
ytile = int(math.ceil(event.pos[1] / ystretch))
if xtile >= gridsize or ytile >= gridsize:
continue
if event.button == 1:
grid[xtile][ytile] = True
generations = 0
lastDrawnGrid = []
elif event.button == 3:
grid[xtile][ytile] = False
generations = 0
lastDrawnGrid = []
elif event.button == 2:
print "Neighbors: " + str(getNumNeighbors(xtile,ytile))
pygame.display.update()
pygame.quit()
| [
"dillonbeliveau@gmail.com"
] | dillonbeliveau@gmail.com |
766a9ff7a619ceeea50d1015ba64e5ec26cfc7e6 | 60ed2327a3ead99b0168ca361aa0bf5bbedad2ba | /morse.py | b12077c9ab67f7eebcede16944dd30bffb4b938b | [] | no_license | BatIgor/MainGit | d4e7c061b40ccf62c4aaad943bcc9c44e4f75aab | 5a56c2378142cc749536a35feaeda1298c93de4a | refs/heads/master | 2016-08-07T09:02:48.931723 | 2015-02-24T06:57:58 | 2015-02-24T06:57:58 | 25,722,216 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,549 | py | import RPi.GPIO as GPIO
import time
CODE = {' ': ' ',
"'": '.----.',
'(': '-.--.-',
')': '-.--.-',
',': '--..--',
'-': '-....-',
'.': '.-.-.-',
'/': '-..-.',
'0': '-----',
'1': '.----',
'2': '..---',
'3': '...--',
'4': '....-',
'5': '.....',
'6': '-....',
'7': '--...',
'8': '---..',
'9': '----.',
':': '---...',
';': '-.-.-.',
'?': '..--..',
'A': '.-',
'B': '-...',
'C': '-.-.',
'D': '-..',
'E': '.',
'F': '..-.',
'G': '--.',
'H': '....',
'I': '..',
'J': '.---',
'K': '-.-',
'L': '.-..',
'M': '--',
'N': '-.',
'O': '---',
'P': '.--.',
'Q': '--.-',
'R': '.-.',
'S': '...',
'T': '-',
'U': '..-',
'V': '...-',
'W': '.--',
'X': '-..-',
'Y': '-.--',
'Z': '--..',
'_': '..--.-'}
ledPin=8
GPIO.setmode(GPIO.BCM)
GPIO.setup(ledPin,GPIO.OUT)
def dot():
GPIO.output(ledPin,1)
time.sleep(0.2)
GPIO.output(ledPin,0)
time.sleep(0.2)
def dash():
GPIO.output(ledPin,1)
time.sleep(0.5)
GPIO.output(ledPin,0)
time.sleep(0.2)
while True:
input = open('/home/pi/temperature/temp_in', 'r').read()
for letter in input:
for symbol in CODE[letter.upper()]:
if symbol == '-':
dash()
elif symbol == '.':
dot()
else:
time.sleep(2.5)
time.sleep(0.5)
| [
"BatIgorIsOne@gmail.com"
] | BatIgorIsOne@gmail.com |
f6e6920ed77e4cb0ea4d2e0e1a88523bff8dd0c4 | f9811d17bc77392aa4d19cd454a782ae55fcebc5 | /kenv/bin/twill-sh | 3ce5f9bc9a2b59892c7b78a504149cf40049ff87 | [
"BSD-3-Clause"
] | permissive | schiiz1/flask-kit | 7416ed21ffa207c24ff547a7eb00ac6574230e4c | ec2ca2fb00ccf1e3c48028ec1b0d9da3c06d9b18 | refs/heads/master | 2021-01-21T00:36:09.971636 | 2013-09-28T18:22:01 | 2013-09-28T18:22:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 295 | #!/home/cece/important/codes/flask/flask-kit/kenv/bin/python2
# EASY-INSTALL-ENTRY-SCRIPT: 'twill==0.9','console_scripts','twill-sh'
__requires__ = 'twill==0.9'
import sys
from pkg_resources import load_entry_point
sys.exit(
load_entry_point('twill==0.9', 'console_scripts', 'twill-sh')()
)
| [
"dontaskcece@gmail.com"
] | dontaskcece@gmail.com | |
c3e36c0a497e93f9eb962d1a92c97efd69e6eb38 | 6163d7097ed2fb8fd2dc11e08d2c5a91ee1a882b | /Assignment1/204102311_SatyakiGhosh/(12)_complex_numbers.py | 5d67153cfcb5d3a8d2bb555cb03bc78d8e25af85 | [] | no_license | pankajiitg/EE524 | a7f47b4e21e33bbdfdffda9a6e035e57a28540d4 | 7c40ed3c973082f13007db23d3a79562f682f27f | refs/heads/master | 2023-01-22T16:07:37.439674 | 2020-10-10T17:19:15 | 2020-10-10T17:19:15 | 299,058,223 | 1 | 0 | null | 2020-12-04T18:10:45 | 2020-09-27T15:12:27 | Jupyter Notebook | UTF-8 | Python | false | false | 1,133 | py | import cmath
class Complex_Numbers:
def __init__(self,value):
self.cmplx=value
def conjugate(self):
c=self.cmplx
x=c.real
y=c.imag
return complex(x,-y)
def absolute_value(self):
return abs(self.cmplx)
def add(self,other_no):
return self.cmplx+other_no.cmplx
def multiply(self,other_no):
return self.cmplx*other_no.cmplx
def divide(self,other_no):
return self.cmplx/other_no.cmplx
def phase(self):
return cmath.phase(self.cmplx)
a=complex(1,1)
b=complex(3,5)
c1=Complex_Numbers(a)
c2=Complex_Numbers(b)
print(f'First complex number: {a}')
print(f'Second complex number: {b}')
print(f'Additon {a} and {b}: {c1.add(c2)}')
print(f'Conjugate of {a}: {c1.conjugate()}')
print(f'Conjugate of {b}: {c2.conjugate()}')
print(f'Multiplication {a} and {b}: {c1.multiply(c2)}')
print(f'Division of {a} by {b}: {c1.divide(c2)}')
print(f'Absolute value of {a}: {c1.absolute_value()}')
print(f'Absolute value of {b}: {c2.absolute_value()}')
print(f'Phase of {a}: {c1.phase()} radians')
print(f'Phase of {b}: {c2.phase()} radians')
| [
"noreply@github.com"
] | noreply@github.com |
8e7299dd2aad37517c5c310a5577872623ee04aa | 2852e55840f9b80bc0e3d37707962589ba4f6841 | /unit_converter.py | 989f9e31f799aa9fc038ff50f54c3d4c42ad0e32 | [] | no_license | scotttgregg/full_stack_bootcamp | 2d55809c36f6e88cecbf47e37d0e6f4ea6487238 | db50823dec8e678361c604cf36f5fcbfcb21ca1e | refs/heads/master | 2020-03-07T23:57:02.511858 | 2018-04-04T19:11:18 | 2018-04-04T19:11:18 | 127,794,383 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,670 | py | # # unit_converter
distance = float(input("What is the distance?\n"))
input_unit = input("What is the unit?\n")
output_unit = input("what is the output unit?\n")
def feet_to_meters():
return distance * .0348
def km_to_meters():
return distance * 1000
def mi_to_meters():
return distance * 1609.34
def m_to_feet():
return distance * 3.28084
def km_to_feet():
return distance * 3280.84
def mi_to_feet():
return distance * 5280
def ft_to_km():
return distance * .0003048
def m_to_km():
return distance * .001
def mi_to_km():
return distance * 1.60934
def ft_to_mi():
return distance * .000189394
def m_to_mi():
return distance * .000621371
def km_to_mi():
return distance * .621371
if input_unit == "ft" and output_unit == "m":
print(feet_to_meters())
elif input_unit == "km" and output_unit == "m":
print(km_to_meters())
elif input_unit == "mi" and output_unit == "m":
print(mi_to_meters())
elif input_unit == output_unit:
print(distance + output_unit)
elif input_unit == "m" and output_unit == "ft":
print(m_to_feet())
elif input_unit == "km" and output_unit == "ft":
print(km_to_feet())
elif input_unit == "mi" and output_unit == "ft":
print(mi_to_feet())
elif input_unit == "ft" and output_unit == "km":
print(ft_to_km())
elif input_unit == "m" and output_unit == "km":
print(m_to_km())
elif input_unit == "mi" and output_unit == "km":
print(mi_to_km())
elif input_unit == "ft" and output_unit == "mi":
print(ft_to_mi())
elif input_unit == "km" and output_unit == "mi":
print(km_to_mi())
elif input_unit == "m" and output_unit == "mi":
print(m_to_mi())
| [
"scotttgregg@gmail.com"
] | scotttgregg@gmail.com |
4deec08548750a09067311640ad0f0451de8e00c | 20aa496f212f9ad4febfe48a8ab0553cf3757d95 | /problems/remove_nth_node_end.py | 2a0cb31b55dc023aa0e49dc42dd00af312c00923 | [] | no_license | hungnb31/leetcode_practices | 538c016408dbf3c97545eadcd1c106c188d0cf63 | e1146d990bec25dbae2bd691317e2a948f3882c2 | refs/heads/master | 2023-06-02T06:11:27.899767 | 2021-06-14T16:33:50 | 2021-06-14T16:33:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 790 | py | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
curr = ListNode()
print(curr.next)
print(curr.val)
curr.next = head
length = 0
first = head
# loop through the list and find out the length of the list
while (first):
length += 1
first = first.next
length -= n
first = curr
while(length > 0):
length -= 1
first = first.next
first.next = first.next.next
return curr.next
| [
"nbhung189@gmail.com"
] | nbhung189@gmail.com |
7b8acd9d6cdc943d7c0a08b177749f2e34291015 | eea113ed18deed6365ae3aa61c6d13da38ceae7e | /listelement/migrations/0001_initial.py | 445c1aeacbe7fc30b3d90d57682be820cd0635ba | [] | no_license | vhalvarez/django-vue | 754ddf0628a7cb14a4840a9eb2b9f2eed8cd37d6 | 42a136061cee59b834ff5e7220d8774113803e89 | refs/heads/main | 2023-08-27T19:49:50.492781 | 2021-11-08T15:57:24 | 2021-11-08T15:57:24 | 425,902,008 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,576 | py | # Generated by Django 3.2.9 on 2021-11-08 15:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('url_clean', models.CharField(max_length=255)),
],
),
migrations.CreateModel(
name='Type',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('url_clean', models.CharField(max_length=255)),
],
),
migrations.CreateModel(
name='Element',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('url_clean', models.CharField(max_length=255)),
('description', models.TextField()),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='listelement.category')),
('type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='listelement.type')),
],
),
]
| [
"alvarez.programmer@gmail.com"
] | alvarez.programmer@gmail.com |
5c9907e3fbe8731805a65d404099833b1adbf9a0 | c37724c911895f27dc0a0eb0ce9344e12e1f8574 | /week1.py | 52531c79f410e41a60a82d3458a1d4eb8af0d7f1 | [] | no_license | kelvin926/korea_univ_python_1 | 4dbc59695ae4dab59e629bf7bc64199814a9e399 | 399622d18219c53612391f49baa84e773e6ae3bf | refs/heads/master | 2023-06-01T09:26:44.059294 | 2021-06-07T19:26:21 | 2021-06-07T19:26:21 | 350,217,411 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,021 | py | # print("hello")
# a = input('a =')
# print(a)
# print(input() + "을 입력하셨답니당")
# a = 1
# id(a)
# type(a)
# age = input("나이?")
# print(age)
# kk = 3
# print(kk)
# id(age)
# id(kk)
# ll = input()
# print(ll)
# id(ll)
# c = 3
# d = 3
# print(id(c))
# print(id(d))
# import keyword
# print(keyword.kwlist)
# s = "python"
# print(s[1:3])
# a=[1,2,3]
# b=['a','b']
# c=[[1,2],[20,30]]
# print(a.append(4))
# print(a.insert(2,10))
# print(a.remove(3))
# d={'a':100,'b':95}
# print(d.keys())
# print(d.values())
# puppy=dict()
# puppy["이름"]="밍키"
# puppy["나이"]=3
# puppy["ahaanrp"]=10.5
# print(puppy)
# a = (1,2,3,10)
# b = (10,20,30)
# print(a + b)
# age = len(a)
# print(age)
# age = int(input("나이?"))
# fee = 10000
# if (age >= 65):
# fee = int(fee*0.8)
# print('입장료는' , fee, '원 입니다')
year = int(input("년도?"))
if (year % 400 == 0 or (year % 4 == 0 and year % 100)):
print(year, "년은 윤년이다")
else:
print(year, "년은 윤년이 아니다")
| [
"kelvin926@naver.com"
] | kelvin926@naver.com |
96ef25c541ae0e163f6224cb39ae094fe2d4ecef | 352adcdfe8ad0c18ea2dce50f7e910d66b04c6b5 | /BuildServer/utils/normalize_packagefiles.py | 5e2c1eea1fea0a19ab19cce6ea96881902bd00bf | [] | no_license | IBT-FMI/NeuroGentooProject | 174a033fc0165ab87df99c5368403af9658f28b5 | 5985a7857e3bb702d89baaa9d8a0328a89bf5867 | refs/heads/master | 2021-09-21T00:44:10.657602 | 2018-08-17T20:07:44 | 2018-08-17T20:07:44 | 104,134,315 | 0 | 0 | null | 2018-01-24T12:40:53 | 2017-09-19T22:09:14 | Shell | UTF-8 | Python | false | false | 541 | py | #!/bin/env python3
import portage.env.config as pec
import sys
dict={}
type=sys.argv[1]
if type == "mask":
type=pec.PackageMaskFile
elif type == "use":
type=pec.PackageUseFile
elif type == "keywords":
type=pec.PackageKeywordsFile
elif type == "unmask":
type=pecPackageMaskFile
for file in sys.argv[2:]:
pf=type(file)
pf.load()
for k,v in pf.items():
if k not in dict:
dict[k]=set()
if v is not None:
dict[k]|=set([x for x in v if x is not None])
for k,vs in sorted(dict.items()):
print(k, " ", " ".join(sorted(vs)))
| [
"schmidom@student.ethz.ch"
] | schmidom@student.ethz.ch |
97be3b993b4f278ccdd868203a24902e3bcbe2bc | fff80cdaf12712704f36038479f50418253f42f3 | /openbmc/common/recipes-rest/rest-api/files/node_bios.py | 5541e54e2f792c8d93e5251ae2259776849425c1 | [] | no_license | rudolfkopriva/Facebook | 1ea0cfbc116f68ae0317332eeb9155461af5645a | 56e4c6a83f992bb01849ad353004b28409e53eef | refs/heads/master | 2023-02-14T01:54:36.519860 | 2021-01-05T02:09:26 | 2021-01-05T02:09:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 15,158 | py | #!/usr/bin/env python
import os.path
from node import node
from pal import *
IOM_M2 = 1 # IOM type: M.2
IOM_IOC = 2 # IOM type: IOC
PLATFORM_FILE = "/tmp/system.bin"
def get_iom_type():
pal_sku_file = open(PLATFORM_FILE, "r")
pal_sku = pal_sku_file.read()
iom_type = int(pal_sku) & 0x3 # The IOM type is the last 2 bits
if (iom_type != IOM_M2) and (iom_type != IOM_IOC):
print("Rest-API: System type is unknown! Please confirm the system type.")
return -1
else:
return iom_type
"""""" """""" """""" """""" """""" """''
Main Node
""" """""" """""" """""" """""" """""" ""
class biosNode(node):
def __init__(self, name, info=None, actions=None):
self.name = name
if info == None:
self.info = {}
else:
self.info = info
if actions == None:
self.actions = []
else:
self.actions = actions
def getInformation(self, param={}):
info = {"Description": "BIOS Information"}
return info
def get_node_bios(name):
return biosNode(name)
"""""" """""" """""" """""" """""" """''
Boot Order Information
""" """""" """""" """""" """""" """""" ""
class bios_boot_order_trunk_node(node):
def __init__(self, name, info=None, actions=None):
self.name = name
if info == None:
self.info = {}
else:
self.info = info
if actions == None:
self.actions = []
else:
self.actions = actions
def getInformation(self, param={}):
info = {"Description": "BIOS Boot Order Information"}
return info
"""""" """""" """""" """""" """''
Boot Mode
""" """""" """""" """""" """""" ""
class bios_boot_mode_node(node):
def __init__(self, name, info=None, actions=None):
self.name = name
if info == None:
self.info = {}
else:
self.info = info
if actions == None:
self.actions = []
else:
self.actions = actions
def getInformation(self, param={}):
cmd = "/usr/local/bin/bios-util " + self.name + " --boot_order get --boot_mode"
boot_order = Popen(cmd, shell=True, stdout=PIPE).stdout.read().decode()
boot_order = boot_order.split("\n")[0].split(": ")
info = {
boot_order[0]: boot_order[1],
"Note #1: Actions Format:": "{ 'action': 'set', 'mode': {0,1} }",
"Note #2: Boot Mode No.": "{ 0: 'Legacy', 1: 'UEFI' }",
}
return info
def doAction(self, data, param={}):
if data["action"] == "set" and len(data) == 2:
cmd = (
"/usr/local/bin/bios-util "
+ self.name
+ " --boot_order set --boot_mode "
+ data["mode"]
)
data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
err = data.stderr.read().decode()
data = data.stdout.read().decode()
if err.startswith("usage"):
res = "failure"
else:
res = "success"
else:
res = "failure"
result = {"result": res}
return result
"""""" """""" """""" """""" """''
Clear CMOS
""" """""" """""" """""" """""" ""
class bios_clear_cmos_node(node):
def __init__(self, name, info=None, actions=None):
self.name = name
if info == None:
self.info = {}
else:
self.info = info
if actions == None:
self.actions = []
else:
self.actions = actions
def getInformation(self, param={}):
cmd = "/usr/local/bin/bios-util " + self.name + " --boot_order get --clear_CMOS"
clear_cmos = Popen(cmd, shell=True, stdout=PIPE).stdout.read().decode()
clear_cmos = clear_cmos.split("\n")[0].split(": ")
info = {clear_cmos[0]: clear_cmos[1]}
return info
def doAction(self, data, param={}):
if data["action"] == "enable":
cmd = (
"/usr/local/bin/bios-util "
+ self.name
+ " --boot_order enable --clear_CMOS"
)
data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
err = data.stderr.read().decode()
data = data.stdout.read().decode()
if err.startswith("usage"):
res = "failure"
else:
res = "success"
elif data["action"] == "disable":
cmd = (
"/usr/local/bin/bios-util "
+ self.name
+ " --boot_order disable --clear_CMOS"
)
data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
err = data.stderr.read().decode()
data = data.stdout.read().decode()
if err.startswith("usage"):
res = "failure"
else:
res = "success"
else:
res = "failure"
result = {"result": res}
return result
"""""" """""" """""" """""" """''
Force Boot BIOS Setup
""" """""" """""" """""" """""" ""
class bios_force_boot_setup_node(node):
def __init__(self, name, info=None, actions=None):
self.name = name
if info == None:
self.info = {}
else:
self.info = info
if actions == None:
self.actions = []
else:
self.actions = actions
def getInformation(self, param={}):
cmd = (
"/usr/local/bin/bios-util "
+ self.name
+ " --boot_order get --force_boot_BIOS_setup"
)
force_boot_bios_setup = (
Popen(cmd, shell=True, stdout=PIPE).stdout.read().decode()
)
force_boot_bios_setup = force_boot_bios_setup.split("\n")[0].split(": ")
info = {force_boot_bios_setup[0]: force_boot_bios_setup[1]}
return info
def doAction(self, data, param={}):
if data["action"] == "enable":
cmd = (
"/usr/local/bin/bios-util "
+ self.name
+ " --boot_order enable --force_boot_BIOS_setup"
)
data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
err = data.stderr.read().decode()
data = data.stdout.read().decode()
if err.startswith("usage"):
res = "failure"
else:
res = "success"
elif data["action"] == "disable":
cmd = (
"/usr/local/bin/bios-util "
+ self.name
+ " --boot_order disable --force_boot_BIOS_setup"
)
data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
err = data.stderr.read().decode()
data = data.stdout.read().decode()
if err.startswith("usage"):
res = "failure"
else:
res = "success"
else:
res = "failure"
result = {"result": res}
return result
"""""" """""" """""" """""" """''
Boot Order
""" """""" """""" """""" """""" ""
class bios_boot_order_node(node):
def __init__(self, name, info=None, actions=None):
self.name = name
if info == None:
self.info = {}
else:
self.info = info
if actions == None:
self.actions = []
else:
self.actions = actions
def getInformation(self, param={}):
cmd = "/usr/local/bin/bios-util " + self.name + " --boot_order get --boot_order"
boot_order = Popen(cmd, shell=True, stdout=PIPE).stdout.read().decode()
boot_order = boot_order.split("\n")[0].split(": ")
info = {
boot_order[0]: boot_order[1],
"Note #1: Actions Format:": "{'action': 'set', '1st': <1st_no>, '2nd': <2nd_no>, '3rd': <3rd_no>, '4th': <4th_no>, '5th': <5th_no>}",
"Note #2: Boot Order No.": "{ 0: 'USB Device', 1: 'IPv4 Network', 9: 'IPv6 Network', 2: 'SATA HDD', 3: 'SATA-CDROM', 4: 'Other Removalbe Device', 255: 'Reserved' }",
}
return info
def doAction(self, data, param={}):
if data["action"] == "set" and len(data) == 6:
cmd = (
"/usr/local/bin/bios-util "
+ self.name
+ " --boot_order set --boot_order "
+ data["1st"]
+ " "
+ data["2nd"]
+ " "
+ data["3rd"]
+ " "
+ data["4th"]
+ " "
+ data["5th"]
)
data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
err = data.stderr.read().decode()
data = data.stdout.read().decode()
if err != "" or data != "":
res = "failure"
else:
res = "success"
elif data["action"] == "disable":
cmd = (
"/usr/local/bin/bios-util "
+ self.name
+ " --boot_order disable --boot_order"
)
data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
err = data.stderr.read().decode()
data = data.stdout.read().decode()
if err.startswith("usage"):
res = "failure"
else:
res = "success"
else:
res = "failure"
result = {"result": res}
return result
def get_node_bios_boot_order_trunk(name):
return bios_boot_order_trunk_node(name)
def get_node_bios_boot_mode(name):
actions = ["set"]
return bios_boot_mode_node(name=name, actions=actions)
def get_node_bios_clear_cmos(name):
actions = ["enable", "disable"]
return bios_clear_cmos_node(name=name, actions=actions)
def get_node_bios_force_boot_setup(name):
actions = ["enable", "disable"]
return bios_force_boot_setup_node(name=name, actions=actions)
def get_node_bios_boot_order(name):
actions = ["set", "disable"]
return bios_boot_order_node(name=name, actions=actions)
"""""" """""" """""" """""" """""" """''
BIOS POST Code Information
""" """""" """""" """""" """""" """""" ""
class bios_postcode_node(node):
def __init__(self, name, info=None, actions=None):
self.name = name
if info == None:
self.info = {}
else:
self.info = info
if actions == None:
self.actions = []
else:
self.actions = actions
def getInformation(self, param={}):
cmd = "/usr/local/bin/bios-util " + self.name + " --postcode get"
postcode = Popen(cmd, shell=True, stdout=PIPE).stdout.read().decode()
postcode = postcode.replace("\n", "").strip()
info = {"POST Code": postcode}
return info
def get_node_bios_postcode_trunk(name):
return bios_postcode_node(name)
"""""" """""" """""" """""" """""" """''
Platform Information
""" """""" """""" """""" """""" """""" ""
class bios_plat_info_node(node):
def __init__(self, name, info=None, actions=None):
self.name = name
if info == None:
self.info = {}
else:
self.info = info
if actions == None:
self.actions = []
else:
self.actions = actions
def getInformation(self, param={}):
cmd = "/usr/local/bin/bios-util " + self.name + " --plat_info get"
data = plat_info = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
plat_info = data.stdout.read().decode()
err = data.stderr.read().decode()
if err.startswith("usage"):
plat_info = "Currently the platform does not support plat-info\n"
plat_info = plat_info.split("\n")
plat_info_len = len(plat_info)
info = {"Platform Information": plat_info[0 : plat_info_len - 1]}
return info
def get_node_bios_plat_info_trunk(name):
return bios_plat_info_node(name)
"""""" """""" """""" """""" """""" """''
PCIe Port Configuration
""" """""" """""" """""" """""" """""" ""
class bios_pcie_port_config_node(node):
def __init__(self, name, info=None, actions=None):
self.name = name
if info == None:
self.info = {}
else:
self.info = info
if actions == None:
self.actions = []
else:
self.actions = actions
def getInformation(self, param={}):
cmd = "/usr/local/bin/bios-util " + self.name + " --pcie_port_config get"
data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
pcie_port_config = data.stdout.read().decode()
err = data.stderr.read().decode()
if err.startswith("usage"):
pcie_port_config = (
"Currently the platform does not support pcie-port-config\n"
)
pcie_port_config = pcie_port_config.split("\n")
pcie_port_config_len = len(pcie_port_config)
iom_type = get_iom_type()
if iom_type == IOM_M2:
info = {
"PCIe Port Configuration": pcie_port_config[
0 : pcie_port_config_len - 1
],
"Note: Actions Format:": "{'action': <enable, disable>, 'pcie_dev': <scc_ioc, flash1, flash2, nic>}",
}
elif iom_type == IOM_IOC:
info = {
"PCIe Port Configuration": pcie_port_config[
0 : pcie_port_config_len - 1
],
"Note: Actions Format:": "{'action': <enable, disable>, 'pcie_dev': <scc_ioc, iom_ioc, nic>}",
}
else:
info = []
return info
def doAction(self, data, param={}):
if data["action"] == "enable" and len(data) == 2:
cmd = (
"/usr/local/bin/bios-util "
+ self.name
+ " --pcie_port_config enable --"
+ data["pcie_dev"]
)
data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
err = data.stderr.read().decode()
data = data.stdout.read().decode()
if err.startswith("usage"):
res = "failure"
else:
res = "success"
elif data["action"] == "disable":
cmd = (
"/usr/local/bin/bios-util "
+ self.name
+ " --pcie_port_config disable --"
+ data["pcie_dev"]
)
data = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
err = data.stderr.read().decode()
data = data.stdout.read().decode()
if err.startswith("usage"):
res = "failure"
else:
res = "success"
else:
res = "failure"
result = {"result": res}
return result
def get_node_bios_pcie_port_config_trunk(name):
actions = ["enable", "disable"]
return bios_pcie_port_config_node(name=name, actions=actions)
| [
"nateweiler84@gmail.com"
] | nateweiler84@gmail.com |
8d24cc2d78f5fd39172d51acefe72ccc68acd70a | c769535cfc2941952dd9d086bd7f2295fa37beea | /Problem Solving/Udemy/Practice 86. How to display Error message for non existed files.py | 01fda31faf72751479f6a4ffd393d5934a437768 | [] | no_license | kgpyi/python | 8af2a3f98cc1817e9688b314f9a1e6ff774f70c2 | f54363e49a7d016454b9394fdb55212c6f9ee580 | refs/heads/master | 2023-01-03T17:04:29.484618 | 2020-10-26T22:54:33 | 2020-10-26T22:54:33 | 307,523,154 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 166 | py | fp = input("Enter file path: ")
try:
file = open(fp)
except FileNotFoundError:
print("Error! This file path does not exist.")
else:
print(file.read())
| [
"hssunami@gmail.com"
] | hssunami@gmail.com |
632f50ce657bd31338db5ba020bec2b0f1357596 | 6e155cd7444e69b719d129e9dcaed2b788d4359b | /shop/shop/celery.py | 2582d795673aac826732cb8f19387b7702df0cf7 | [] | no_license | tishmanoni/My-store | 0ac1beb26fd4c3176f90346b23b9e9c955e90729 | 79bec452be871089edd6415b00bd094dc6288443 | refs/heads/master | 2022-12-06T05:33:21.163835 | 2020-08-29T19:39:45 | 2020-08-29T19:39:45 | 291,334,250 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 282 | py | import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shop.settings')
app = Celery('shop')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
| [
"66375712+tishmanoni@users.noreply.github.com"
] | 66375712+tishmanoni@users.noreply.github.com |
dcefd9f8f4a93157e0c78fb7e7a879a96c1b190a | 5fe8b2e09a48b473cc28a4ba56e96075af945d07 | /app_Bananapi-M2p.py | 2af89937507c6029f1540089b20c073d465764e6 | [
"Apache-2.0"
] | permissive | stozk/msb-client-websocket-python | bf2821593386aa02b9f53069d72ec5dae98f3335 | 2c5dacaa27b2a5b543ba8693ca888ddd5dc46e38 | refs/heads/master | 2023-04-06T18:10:30.968152 | 2021-04-07T19:14:32 | 2021-04-07T19:14:32 | 275,241,849 | 0 | 0 | Apache-2.0 | 2020-06-26T20:29:16 | 2020-06-26T20:29:15 | null | UTF-8 | Python | false | false | 11,372 | py | # -*- coding: utf-8 -*-
"""
Copyright (c) 2019 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA)
Authors: Daniel Stock, Matthias Stoehr
Licensed under the Apache License, Version 2.0
See the file "LICENSE" for the full license governing this code.
"""
import datetime
import threading
import uuid
from msb_client.ComplexDataFormat import ComplexDataFormat
from msb_client.DataType import DataType
from msb_client.Event import Event
from msb_client.CustomMetaData import CustomMetaData
from msb_client.TypeDescription import TypeDescription
from msb_client.TypeDescriptor import TypeDescriptor
from msb_client.Function import Function
from msb_client.MsbClient import MsbClient
if __name__ == "__main__":
"""This is a sample client for the MSB python client library."""
# define service properties as constructor parameters
SERVICE_TYPE = "SmartObject"
SO_UUID = "b27e385d-2bf3-4337-9d68-a23606e27342"
SO_NAME = "Banana Pi M2+"
SO_DESCRIPTION = "Raspberry PI 3 + Enviro+ sensor board"
SO_TOKEN = "a23606e27342"
myMsbClient = MsbClient(
SERVICE_TYPE,
SO_UUID,
SO_NAME,
SO_DESCRIPTION,
SO_TOKEN,
)
# msb_url = "wss://192.168.1.9:8084"
msb_url = "wss://192.168.1.9:8084"
myMsbClient.enableDebug(True)
myMsbClient.enableTrace(False)
myMsbClient.enableDataFormatValidation(True)
myMsbClient.disableAutoReconnect(False)
myMsbClient.setReconnectInterval(10000)
myMsbClient.disableEventCache(False)
myMsbClient.setEventCacheSize(1000)
myMsbClient.disableHostnameVerification(True)
myMsbClient.addMetaData(
CustomMetaData(
"SEN",
"Sensor - device which, when excited by a physical phenomenon, produces an electric signal characterizing the physical phenomenon",
TypeDescription(
TypeDescriptor.CDD,
"0112/2///61360_4#AAA103#001",
"https://cdd.iec.ch/cdd/iec61360/iec61360.nsf/2a050a792eee78e1c12575560054b803/219d27329351ec25c1257dd300515f69",
),
)
)
myMsbClient.addMetaData(
CustomMetaData(
"Fine Particle Sensor",
"Sensor which measures fine particles",
TypeDescription(
TypeDescriptor.CUSTOM, "0112/2///61360_4#AAA103#001-FEIN", ""
),
)
)
myMsbClient.addMetaData(
CustomMetaData(
"MUP",
"CPU - processor whose elements have been miniaturized into an integrated circuit",
TypeDescription(
TypeDescriptor.CDD,
"0112/2///61360_4#AAA062#001",
"https://cdd.iec.ch/cdd/iec61360/iec61360.nsf/2a050a792eee78e1c12575560054b803/670dc436b7e157cac1257dd300515f41",
),
"/",
"METHOD_STUB_TO_GET_DATA",
DataType.STRING,
)
)
myMsbClient.addMetaData(
CustomMetaData(
"CPU_Architecture",
"CPU_Architecture",
TypeDescription(TypeDescriptor.CUSTOM, "0112/2///61360_4#AAA062#001", ""),
"/",
"METHOD_STUB_TO_GET_DATA",
DataType.STRING,
)
)
myMsbClient.addMetaData(
CustomMetaData(
"RAM",
"memory that permits access to any of its address locations in any desired sequence",
TypeDescription(
TypeDescriptor.CDD,
"0112/2///61360_4#AAA062#001",
"https://cdd.iec.ch/cdd/iec61360/iec61360.nsf/2a050a792eee78e1c12575560054b803/670dc436b7e157cac1257dd300515f41",
),
"/",
"METHOD_STUB_TO_GET_DATA",
DataType.DOUBLE,
)
)
myMsbClient.addMetaData(
CustomMetaData(
"OS_platform",
"Operating system platform",
TypeDescription(TypeDescriptor.CUSTOM, "OS_platform", ""),
"/",
"METHOD_STUB_TO_GET_DATA",
DataType.STRING,
)
)
myMsbClient.addMetaData(
CustomMetaData(
"OS_hostname",
"OS_hostname",
TypeDescription(TypeDescriptor.CUSTOM, "OS_hostname", ""),
"/",
"METHOD_STUB_TO_GET_DATA",
DataType.STRING,
)
)
myMsbClient.addMetaData(
CustomMetaData(
"OS_platform_release",
"OS_platform_release",
TypeDescription(TypeDescriptor.CUSTOM, "OS_platform_release", ""),
"/",
"METHOD_STUB_TO_GET_DATA",
DataType.STRING,
)
)
myMsbClient.addMetaData(
CustomMetaData(
"OS_platform_version",
"OS_platform_version",
TypeDescription(TypeDescriptor.CUSTOM, "OS_platform_version", ""),
"/",
"METHOD_STUB_TO_GET_DATA",
DataType.STRING,
)
)
myMsbClient.addMetaData(
CustomMetaData(
"OS_system_serial",
"OS_system_serial",
TypeDescription(TypeDescriptor.CUSTOM, "OS_system_serial", ""),
"/",
"METHOD_STUB_TO_GET_DATA",
DataType.STRING,
)
)
myMsbClient.addMetaData(
CustomMetaData(
"CPU_CORES",
"CPU core count",
TypeDescription(TypeDescriptor.CUSTOM, "CPU_CORES", ""),
"/",
"METHOD_STUB_TO_GET_DATA",
DataType.INT32,
)
)
e_particle_concentration = Event(
"PARTICLE_CONCENTRATION",
"Aktuelle Partikelkonzentration",
"Aktuelle Konzentration der Feinstaubpartikel in PPM",
DataType.INT32,
1,
False,
)
e_particle_concentration.addMetaData(
CustomMetaData(
"Particle Concentration",
"Particle Concentration",
TypeDescription(
TypeDescriptor.CDD,
"0112/2///61987#ABT514#001",
"https://cdd.iec.ch/cdd/iec61987/iec61987.nsf/ListsOfUnitsAllVersions/0112-2---61987%23ABT514",
),
"/PARTICLE_CONCENTRATION",
)
)
e_particle_concentration.addMetaData(
TypeDescription(
TypeDescriptor.CDD,
"0112/2///61987#ABT514#001",
"https://cdd.iec.ch/cdd/iec61987/iec61987.nsf/ListsOfUnitsAllVersions/0112-2---61987%23ABT514",
"/PARTICLE_CONCENTRATION",
)
)
myMsbClient.addEvent(e_particle_concentration)
e_temperature = Event(
"AMBIENT_TEMPERATURE",
"Current ambient temperature",
"Current temperature reading in °C",
DataType.DOUBLE,
1,
False,
)
e_temperature.addMetaData(
CustomMetaData(
"Temperature",
"Ambient temperature",
TypeDescription(
TypeDescriptor.CDD,
"0112/2///61987#ABT514#001",
"https://cdd.iec.ch/cdd/iec61987/iec61987.nsf/ListsOfUnitsAllVersions/0112-2---61987%23ABT514",
),
"/AMBIENT_TEMPERATURE",
DataType.DOUBLE,
)
)
e_temperature.addMetaData(
TypeDescription(
TypeDescriptor.CDD,
"0112/2///62720#UAA033#001",
"https://cdd.iec.ch/cdd/iec61360/iec61360.nsf/Units/0112-2---62720%23UAA033",
"/AMBIENT_TEMPERATURE",
)
)
myMsbClient.addEvent(e_temperature)
def sendParticleData():
print("Method stub for data sending")
def startReadFineParticle():
print("Method stub for particle reading")
f_start_fp_detection = Function(
"START_FP_DETECTION",
"Start fine particle measurement",
"Starts the Process of fine particle measurements",
DataType.BOOLEAN,
startReadFineParticle,
False,
["PARTICLE_CONCENTRATION"],
)
f_start_fp_detection.addMetaData(
CustomMetaData(
"Funktion_Temperatur",
"Funktion_Umgebungstemperatur",
TypeDescription(
TypeDescriptor.CDD,
"0112/2///61987#ABT514#001",
"https://cdd.iec.ch/cdd/iec61987/iec61987.nsf/ListsOfUnitsAllVersions/0112-2---61987%23ABT514",
),
"/START_FP_DETECTION",
)
)
myMsbClient.addFunction(f_start_fp_detection)
e_cpu_speed_reading = Event(
"CPU_SPEED_READINGS",
"CPU speed readings",
"CPU speed readings for fingerprinting",
DataType.DOUBLE,
1,
True,
)
e_cpu_speed_reading.addMetaData(
CustomMetaData(
"CPU speed readings",
"CPU speed readings",
TypeDescription(TypeDescriptor.FINGERPRINT, "FP_CPU_SPEED_READINGS", ""),
"/CPU_SPEED_READINGS",
DataType.DOUBLE,
)
)
myMsbClient.addEvent(e_cpu_speed_reading)
f_cpu_speed = Function(
"CPU_SPEED",
"Start CPU speed measurement",
"Starts CPU speed measurement for fingerprinting",
DataType.BOOLEAN,
startReadFineParticle,
False,
["CPU_SPEED_READINGS"],
)
f_cpu_speed.addMetaData(
CustomMetaData(
"CPU_SPEED",
"Measure CPU speed for fingerprinting",
TypeDescription(TypeDescriptor.FINGERPRINT, "FP_CPU_SPEED", ""),
"/CPU_SPEED",
)
)
myMsbClient.addFunction(f_cpu_speed)
e_cpu_temp_reading = Event(
"CPU_TEMPERATURE_READINGS",
"CPU temperature readings",
"CPU temperature readings for fingerprinting",
DataType.DOUBLE,
1,
False,
)
e_cpu_temp_reading.addMetaData(
CustomMetaData(
"CPU temperature",
"CPU temperature readings for fingerprinting",
TypeDescription(
TypeDescriptor.FINGERPRINT, "FP_CPU_TEMPERATURE_READINGS", ""
),
"/CPU_TEMPERATURE_READINGS",
DataType.DOUBLE,
)
)
myMsbClient.addEvent(e_cpu_temp_reading)
f_cpu_temp = Function(
"CPU_TEMPERATURE",
"Get CPU temperature measurement",
"Get the CPU tempreature for fingerprinting",
DataType.DOUBLE,
startReadFineParticle,
False,
["CPU_TEMPERATURE_READINGS"],
)
f_cpu_temp.addMetaData(
CustomMetaData(
"CPU_TEMPERATURE",
"Measure CPU temperature for fingerprinting",
TypeDescription(TypeDescriptor.FINGERPRINT, "FP_CPU_TEMPERATURE", ""),
"/CPU_TEMPERATURE",
)
)
myMsbClient.addFunction(f_cpu_temp)
f_storage_speeds = Function(
"STORAGE_W_SPEED",
"Measure storage speed",
"Measure the CPU Speed for fingerprinting",
DataType.DOUBLE,
startReadFineParticle,
False,
[],
)
f_storage_speeds.addMetaData(
CustomMetaData(
"STORAGE_W_SPEED",
"Measure the CPU Speed for fingerprinting",
TypeDescription(TypeDescriptor.FINGERPRINT, "FP_STORAGE_W_SPEED", ""),
"/STORAGE_W_SPEED",
)
)
myMsbClient.addFunction(f_storage_speeds)
print(myMsbClient.objectToJson(myMsbClient.getSelfDescription()))
myMsbClient.connect(msb_url)
myMsbClient.register() | [
"daniel.stock@ipa.fraunhofer.de"
] | daniel.stock@ipa.fraunhofer.de |
18266e011e33f769d47826ae713896b03fa623ed | ceecc742e744505f7a2d57c6d06eb1c145da539d | /ltsm/lstm.py | 5d7c8f544e23d8265e2d2f8620df86b89c1bf930 | [] | no_license | ndingibr/ltsm | b709466f5df67751c2a57c407902d4fe33b8693b | 6429e40fbe1c88b459ab6b84cb96b3b10550a787 | refs/heads/master | 2023-03-31T18:25:55.040560 | 2019-06-05T09:59:41 | 2019-06-05T09:59:41 | 190,370,797 | 0 | 0 | null | 2023-03-24T21:55:12 | 2019-06-05T09:57:44 | Python | UTF-8 | Python | false | false | 5,513 | py | import os
import json
import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from core.data_processor import data_processor
from core.model import model
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import r2_score
def main():
configs = json.load(open('config.json', 'r'))
if not os.path.exists(configs['model']['save_dir']): os.makedirs(configs['model']['save_dir'])
file_path = os.path.join('data', configs['data']['filename'])
connection = os.path.join(configs['data']['postgres_connection'])
processor = data_processor(file_path, connection)
test_end_date = configs['training']['test_end_date']
table_name = configs['data']['table_name']
metric_table = configs['data']['metric_table']
raw_data = processor.get_data()
closes = ['EUR/USD Close', 'USD/JPY Close', 'USD/CHF Close', 'GBP/USD Close', 'USD/CAD Close', 'EUR/GBP Close', 'EUR/JPY Close', 'EUR/CHF Close', 'AUD/USD Close', 'GBP/JPY Close', 'CHF/JPY Close', 'GBP/CHF Close', 'NZD/USD Close']
processor.check_table(table_name)
processor.create_tables(table_name)
processor.check_table(metric_table)
processor.create_metrictable(metric_table)
all_tests = pd.DataFrame()
metrics = pd.DataFrame(pd.DataFrame(columns=['Date','Trade','RMSE','RSquared','Increase_Pecentage', 'Increase_PecentageActual']))
start = True
for trade in closes:
print(trade)
df = raw_data[['Date', trade]]
min_date = df['Date'].min()
df = processor.get_data_in_range(df, min_date, test_end_date)
print(len(df))
df['Date'] = pd.to_datetime(df.Date,format='%Y-%m-%d')
df.index = df['Date']
data = df.sort_index(ascending=True, axis=0)
new_data = pd.DataFrame(index=range(0,len(df)),columns=['Date', trade])
for i in range(0,len(data)):
new_data['Date'][i] = data['Date'][i]
new_data[trade][i] = data[trade][i]
#setting index
new_data.index = new_data.Date
new_data.drop('Date', axis=1, inplace=True)
#creating train and test sets
dataset = new_data.values
split_index = len(df) - 5
train = dataset[0:split_index,:]
valid = dataset[split_index:,:]
#converting dataset into x_train and y_train
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(train)
x_train, y_train = [], []
for i in range(60,len(train)):
x_train.append(scaled_data[i-60:i,0])
y_train.append(scaled_data[i,0])
x_train, y_train = np.array(x_train), np.array(y_train)
print(x_train.shape)
x_train = np.reshape(x_train, (x_train.shape[0],x_train.shape[1],1))
model_result = model(x_train, y_train)
lstm_model = model_result.lstm_keras()
begin_index = len(df) - 70
end_index = len(df) - 5
inputs = dataset[begin_index:split_index,:]
scaler_input = MinMaxScaler(feature_range=(0, 1))
scaled_input = scaler_input.fit_transform(inputs)
print(len(inputs))
X_test = []
for i in range(0, 5):
X_test.append(scaled_input[i:i + 60,0])
X_test = np.array(X_test)
print(X_test.shape)
X_test = np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1))
closing_price = lstm_model.predict(X_test)
closing_price = scaler.inverse_transform(closing_price)
#rms=np.sqrt(np.mean(np.power((valid-closing_price),2)))
#print(rms)
valid = new_data[end_index:]
print(valid)
valid['Predictions'] = closing_price
#plt.plot(train[trade])
#plt.plot(valid[[trade,'Predictions']])
#plt.show()
latest_test_set = df.tail(5)
latest_test_set = latest_test_set.copy()
#min = latest_test_set[trade].ix[0]
#max = latest_test_set[trade].ix[len(latest_test_set) - 1]
#actual_change = (max - min)/min
if start == True:
all_tests['Date'] = latest_test_set['Date']
all_tests[trade] = closing_price
start = False
rsquared = r2_score(latest_test_set[trade], closing_price)
print(all_tests)
print('Min = ' + str(all_tests[trade].ix[0]))
print('Max = ' + str(all_tests[trade].ix[len(latest_test_set) - 1]))
min = all_tests[trade].ix[0]
max = all_tests[trade].ix[len(latest_test_set) - 1]
change = (max - min)/min
metrics = metrics.append({'Date': datetime.datetime.now(), 'Trade': trade, 'RMSE': 0, 'RSquared': 0, 'Increase_Pecentage' : change, 'Increase_PecentageActual' : 0}, ignore_index=True)
print(all_tests)
processor.save_csv(os.path.join('data', configs['data']['predictions_filename']), all_tests)
processor.load_table_cv(os.path.join('data', configs['data']['predictions_filename']), table_name)
processor.save_csv(os.path.join('data', configs['data']['filename_metrics']), metrics)
processor.load_table_cv(os.path.join('data', configs['data']['filename_metrics']), metric_table)
print('done')
if __name__ == '__main__':
main() | [
"noreply@github.com"
] | noreply@github.com |
b50310ac4f276484c335b80e242918ef1d820838 | d29eb63a0f89ebfd195e629bf010868802845bb8 | /BACKEND/i2c.py | c158535d2c342fbabb1d97495fe6b5727c0f2060 | [] | no_license | corneliscasper/project | ae1ea12196f70ece0bc9da867d52af01fbc043da | c9e0151b4c190df80db0a77a4087c922f1d0ab6e | refs/heads/master | 2022-11-09T04:02:11.967320 | 2020-06-16T14:05:19 | 2020-06-16T14:05:19 | 267,550,367 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 841 | py | import smbus
from time import *
class i2c_device:
def __init__(self, addr, port=1):
self.addr = addr
self.bus = smbus.SMBus(port)
# Write a single command
def write_cmd(self, cmd):
self.bus.write_byte(self.addr, cmd)
sleep(0.0001)
# Write a command and argument
def write_cmd_arg(self, cmd, data):
self.bus.write_byte_data(self.addr, cmd, data)
sleep(0.0001)
# Write a block of data
def write_block_data(self, cmd, data):
self.bus.write_block_data(self.addr, cmd, data)
sleep(0.0001)
# Read a single byte
def read(self):
return self.bus.read_byte(self.addr)
# Read
def read_data(self, cmd):
return self.bus.read_byte_data(self.addr, cmd)
# Read a block of data
def read_block_data(self, cmd):
return self.bus.read_block_data(self.addr, cmd)
| [
"casper.cornelis@student.howest.be"
] | casper.cornelis@student.howest.be |
26dd6edfa365858aaeb16e66eb84b35a578f409b | f9abb45e40220f435630695abc5ae784cb805254 | /src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/red_modules.py | 144b9ec187f53dcead24605c9566a0f60eb9282f | [
"Apache-2.0"
] | permissive | Paramashiva/RED | a05386468e5854235e74f6b8e92c3281c56d72b5 | bc91515284442feb37bd1db374310ccf0d654454 | refs/heads/master | 2020-03-24T17:45:21.659474 | 2018-06-18T13:56:24 | 2018-06-18T13:56:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,070 | py | #
# Copyright 2016 Nokia Solutions and Networks
# Licensed under the Apache License, Version 2.0,
# see license.txt file for details.
#
def get_modules_search_paths():
import sys
import robot # Robot will add some paths to PYTHONPATH
return sys.path
def get_module_path(module_name):
import imp
try:
_, path, _ = imp.find_module(module_name)
return path
except ImportError as e:
# when trying to locate jar modules via jython
import platform
if 'Jython' in platform.python_implementation():
source = _find_jar_source_path(module_name)
if source:
if 'file:' in source:
source = source[source.index('file:') + 5:]
if '.jar!' in source:
source = source[:source.rindex('.jar!')] + '.jar'
elif '.jar/' in source:
source = source[:source.rindex('.jar/')] + '.jar'
elif '.jar\\' in source:
source = source[:source.rindex('.jar\\')] + '.jar'
return source
raise e
def _find_jar_source_path(module_name):
import org.python.core.imp as jimp
from types import ModuleType
module = jimp.load(module_name)
if isinstance(module, ModuleType):
source = module.__file__
if '__pyclasspath__' in source:
res = source[source.index('__pyclasspath__') + 16:]
return jimp.getSyspathJavaLoader().getResource(res).getPath()
return source
else:
return module.getResource('/' + module_name.replace('.', '/') + ".class").getPath()
if __name__ == '__main__':
import sys
import json
if sys.argv[1] == '-pythonpath':
print(json.dumps(get_modules_search_paths()))
elif sys.argv[1] == '-modulename':
module_name = sys.argv[2]
if len(sys.argv) > 3:
sys.path.extend(sys.argv[3].split(';'))
print(get_module_path(module_name))
else:
raise Exception('Unrecognized argument:' + sys.argv[1])
| [
"modrz@users.noreply.github.com"
] | modrz@users.noreply.github.com |
7997ca20533e73e6a379dfcf4dd3282002852b22 | 62e1d914fa8785136d27c7351ff95fd5d8780b82 | /core/admin.py | 8157a9e69a8b7d3fcd45bd5f5a620964acc1a185 | [] | no_license | FernandoNici/agenda | 8ba25793cfe108852ffff2a385f8704e1889f350 | efc040512743e905030abd55ee10d713ab767c9f | refs/heads/master | 2022-05-22T00:36:30.459064 | 2020-05-01T18:07:14 | 2020-05-01T18:07:14 | 258,665,308 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 283 | py | from django.contrib import admin
# Register your models here.
from core.models import Evento
class EventoAdmin(admin.ModelAdmin):
list_display = ('id', 'titulo', 'data_criacao', 'data_evento')
list_filter = ('titulo', 'usuario',)
admin.site.register(Evento, EventoAdmin)
| [
"fernando.nici@gmail.com"
] | fernando.nici@gmail.com |
079530b221e8520dbec1afc70e82ce7bd75f45fa | 786de89be635eb21295070a6a3452f3a7fe6712c | /CalibManager/tags/V00-00-34/src/GUIMetrology.py | 4a583bd900a6318fb105b38bb6814264be14a4b0 | [] | no_license | connectthefuture/psdmrepo | 85267cfe8d54564f99e17035efe931077c8f7a37 | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | refs/heads/master | 2021-01-13T03:26:35.494026 | 2015-09-03T22:22:11 | 2015-09-03T22:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 22,961 | py |
#--------------------------------------------------------------------------
# File and Version Information:
# $Id$
#
# Description:
# Module GUIMetrology...
#
#------------------------------------------------------------------------
"""Renders the main GUI for the CalibManager.
This software was developed for the SIT project. If you use all or
part of it, please give an appropriate acknowledgment.
@see RelatedModule
@version $Id:$
@author Mikhail S. Dubrovin
"""
#------------------------------
# Module's version from CVS --
#------------------------------
__version__ = "$Revision: 4 $"
# $Source$
#--------------------------------
# Imports of standard modules --
#--------------------------------
import sys
import os
from PyQt4 import QtGui, QtCore
#import time # for sleep(sec)
#-----------------------------
# Imports for other modules --
#-----------------------------
from ConfigParametersForApp import cp
from Logger import logger
from FileNameManager import fnm
from GUIFileBrowser import *
from GUIRunRange import *
import GlobalUtils as gu
from xlsx_parser import convert_xlsx_to_text
from OpticAlignmentCspadV1 import *
#---------------------
# Class definition --
#---------------------
class GUIMetrology ( QtGui.QWidget ) :
"""Main GUI for main button bar.
@see BaseClass
@see OtherClass
"""
def __init__ (self, parent=None, app=None) :
self.name = 'GUIMetrology'
self.myapp = app
QtGui.QWidget.__init__(self, parent)
self.fname_prefix = cp.fname_prefix
self.fname_metrology_xlsx = cp.fname_metrology_xlsx
self.fname_metrology_text = cp.fname_metrology_text
self.img_arr = None
self.list_of_calib_types = ['center', 'tilt', 'geometry']
cp.setIcons()
self.setGeometry(10, 25, 725, 200)
self.setWindowTitle('Metrology')
#self.setWindowIcon(cp.icon_monitor)
self.palette = QtGui.QPalette()
self.resetColorIsSet = False
self.setFrame()
self.setParams()
#self.titFileXlsx = QtGui.QLabel('File xlsx:')
self.ediFileXlsx = QtGui.QLineEdit ( fnm.path_metrology_xlsx() )
self.ediFileXlsx.setReadOnly(True)
self.ediFileText = QtGui.QLineEdit ( fnm.path_metrology_text() )
self.ediFileText.setReadOnly(True)
self.butFileXlsx = QtGui.QPushButton(' 1. Select xlsx file:')
self.butConvert = QtGui.QPushButton(' 2. Convert xlsx to text file(s)')
self.butFileText = QtGui.QPushButton(' 3. Select text file:')
self.butEvaluate = QtGui.QPushButton(' 4. Evaluate')
self.butDeploy = QtGui.QPushButton(' 5. Deploy')
self.butList = QtGui.QPushButton('List')
self.butRemove = QtGui.QPushButton('Remove')
self.butViewOffice= QtGui.QPushButton('View xlsx')
self.butViewText = QtGui.QPushButton('View text')
self.butScript = QtGui.QPushButton(self.script + cp.char_expand )
self.butSrc = QtGui.QPushButton(self.source_name + cp.char_expand )
self.labSrc = QtGui.QLabel('for detector')
self.labScript = QtGui.QLabel('using script')
self.guirunrange = GUIRunRange()
self.butViewOffice .setIcon(cp.icon_monitor)
self.butViewText .setIcon(cp.icon_monitor)
#self.butConvert .setIcon(cp.icon_convert)
self.grid = QtGui.QGridLayout()
self.grid_row = 0
self.grid.addWidget(self.butFileXlsx, self.grid_row, 0)
self.grid.addWidget(self.ediFileXlsx, self.grid_row, 1, 1, 8)
self.grid.addWidget(self.butViewOffice, self.grid_row, 8)
self.grid.addWidget(self.butConvert, self.grid_row+1, 0)
self.grid.addWidget(self.butList, self.grid_row+1, 1, 1, 1)
self.grid.addWidget(self.butRemove, self.grid_row+1, 2, 1, 1)
self.grid.addWidget(self.butFileText, self.grid_row+2, 0)
self.grid.addWidget(self.ediFileText, self.grid_row+2, 1, 1, 8)
self.grid.addWidget(self.butViewText, self.grid_row+2, 8)
self.grid.addWidget(self.butEvaluate, self.grid_row+3, 0)
self.grid.addWidget(self.labScript, self.grid_row+3, 1)
self.grid.addWidget(self.butScript, self.grid_row+3, 2)
self.grid.addWidget(self.butDeploy, self.grid_row+4, 0)
self.grid.addWidget(self.labSrc, self.grid_row+4, 1)
self.grid.addWidget(self.butSrc, self.grid_row+4, 2)
self.grid.addWidget(self.guirunrange, self.grid_row+4, 3, 1, 5)
#self.setLayout(self.grid)
self.vbox = QtGui.QVBoxLayout()
self.vbox.addLayout(self.grid)
self.vbox.addStretch(1)
self.setLayout(self.vbox)
self.connect( self.butFileXlsx, QtCore.SIGNAL('clicked()'), self.onButFileXlsx )
self.connect( self.butFileText, QtCore.SIGNAL('clicked()'), self.onButFileText )
self.connect( self.butViewOffice, QtCore.SIGNAL('clicked()'), self.onButViewOffice )
self.connect( self.butViewText, QtCore.SIGNAL('clicked()'), self.onButViewText )
self.connect( self.butConvert, QtCore.SIGNAL('clicked()'), self.onButConvert )
self.connect( self.butRemove, QtCore.SIGNAL('clicked()'), self.onButRemove )
self.connect( self.butList, QtCore.SIGNAL('clicked()'), self.onButList )
self.connect( self.butEvaluate, QtCore.SIGNAL('clicked()'), self.onButEvaluate )
self.connect( self.butDeploy, QtCore.SIGNAL('clicked()'), self.onButDeploy )
self.connect( self.butScript, QtCore.SIGNAL('clicked()'), self.onButScript )
self.connect( self.butSrc, QtCore.SIGNAL('clicked()'), self.onButSrc )
self.showToolTips()
self.setStyle()
cp.guimetrology = self
#self.move(10,25)
#print 'End of init'
#-------------------
# Private methods --
#-------------------
def showToolTips(self):
#pass
self.ediFileXlsx .setToolTip('Persistent path to xlsx file')
self.butFileXlsx .setToolTip('Open file browser dialog window\nand select xlsx file. This file is\nusually e-mailed from detector group.')
self.butViewOffice.setToolTip('Open openoffice.org window')
self.butViewText .setToolTip('Open file viewer window')
self.butFileText .setToolTip('Open file browser dialog window\nand select metrology text file')
self.ediFileText .setToolTip('Path to the text metrology file which\nis used to evaluate calibration constants.')
self.butConvert .setToolTip('Convert xlsx to text metrology file(s)')
self.butList .setToolTip('List temporarty metrology text file(s)')
self.butRemove .setToolTip('Remove temporarty metrology text file(s)')
self.butEvaluate .setToolTip('Run quality check script and\nevaluate geometry alignment parameters')
self.butDeploy .setToolTip('Deploy geometry alignment parameters')
self.butScript .setToolTip('Select the script to process optic metrology file')
self.butSrc .setToolTip('Select name of the detector')
def setFrame(self):
self.frame = QtGui.QFrame(self)
self.frame.setFrameStyle( QtGui.QFrame.Box | QtGui.QFrame.Sunken ) #Box, Panel | Sunken, Raised
self.frame.setLineWidth(0)
self.frame.setMidLineWidth(1)
self.frame.setGeometry(self.rect())
#self.frame.setVisible(False)
def setParams(self) :
#if self.path_fm_selected != '' :
# self.path_fm_selected = os.path.dirname(self.path_fm_selected)
self.str_run_from = '0'
self.str_run_to = 'end'
self.source_name = 'Select'
self.script = 'Select'
self.calib_type = 'Select'
def setStyle(self):
self.setMinimumSize(725,200)
self.setMaximumSize(800,200)
self. setStyleSheet(cp.styleBkgd)
self.butViewOffice.setStyleSheet(cp.styleButton)
self.butViewText .setStyleSheet(cp.styleButton)
#self.butViewOffice.setFixedWidth(200)
#self.butViewOffice.setMinimumHeight(60)
#self.butViewOffice.setMinimumSize(180,60)
self.butFileXlsx .setStyleSheet(cp.styleButtonLeft)
self.butConvert .setStyleSheet(cp.styleButtonLeft)
self.butFileText .setStyleSheet(cp.styleButtonLeft)
self.butEvaluate .setStyleSheet(cp.styleButtonLeft)
self.butDeploy .setStyleSheet(cp.styleButtonLeft)
self.ediFileXlsx.setFixedWidth(400)
self.ediFileXlsx.setStyleSheet(cp.styleEditInfo)
self.ediFileXlsx.setEnabled(False)
self.ediFileText.setFixedWidth(400)
self.ediFileText.setStyleSheet(cp.styleEditInfo)
self.ediFileText.setEnabled(False)
self.labSrc .setStyleSheet(cp.styleLabel)
self.labScript .setStyleSheet(cp.styleLabel)
#self.butFBrowser.setVisible(False)
#self.butSave.setText('')
#self.butExit.setText('')
#self.butExit.setFlat(True)
self.setStyleButtons()
def setStyleButtons(self):
if self.source_name == 'Select' : self.butSrc.setStyleSheet(cp.stylePink)
else : self.butSrc.setStyleSheet(cp.styleButton)
if self.script == 'Select' : self.butScript.setStyleSheet(cp.stylePink)
else : self.butScript.setStyleSheet(cp.styleButton)
def resizeEvent(self, e):
#logger.debug('resizeEvent', self.name)
self.frame.setGeometry(self.rect())
#print 'GUIMetrology.resizeEvent: %s' % str(self.size())
def moveEvent(self, e):
#logger.debug('moveEvent', self.name)
#self.position = self.mapToGlobal(self.pos())
#self.position = self.pos()
#logger.debug('moveEvent - pos:' + str(self.position), __name__)
pass
def closeEvent(self, event):
logger.debug('closeEvent', self.name)
try : cp.guifilebrowser.close()
except : pass
def onExit(self):
logger.debug('onExit', self.name)
self.close()
def onButFileXlsx(self):
logger.debug('onButFileXlsx', __name__)
but = self.butFileXlsx
edi = self.ediFileXlsx
par = self.fname_metrology_xlsx
#prefix = self.fname_prefix.value()
filter = 'Text files (*.xlsx )\nAll files (*)'
self.onButFile(but, edi, par, filter, set_path=True)
def onButFileText(self):
logger.debug('onButFileText', __name__)
but = self.butFileText
edi = self.ediFileText
par = self.fname_metrology_text
basename = os.path.basename( fnm.path_metrology_ptrn() )
fname, ext = os.path.splitext(basename)
filter = 'Text files (' + fname + '*' + ext + ')\nAll files (*)'
self.onButFile(but, edi, par, filter, set_path=False)
def onButFile(self, but, edi, par, filter, set_path=True):
logger.debug('onButFile', __name__)
path = str( edi.displayText() )
dname, fname = os.path.split(path)
msg = 'dir : %s file : %s' % (dname, fname)
logger.info(msg, __name__)
path = str( QtGui.QFileDialog.getOpenFileName(self, 'Open file', dname, filter=filter) )
dname, fname = os.path.split(path)
if dname == '' or fname == '' :
logger.info('Input directiry name or file name is empty... use default values', __name__)
return
else :
edi.setText(path)
if set_path : par.setValue(path)
else : par.setValue(fname)
logger.info('Selected file: %s' % path, __name__)
def onButViewOffice(self):
logger.debug('onLogger', self.name)
try :
#cp.viewoffice.close()
#del cp.viewoffice
self.butViewOffice.setStyleSheet(cp.styleButton)
#self.butViewOffice.setText('Open openoffice')
cmd = 'openoffice.org %s &' % fnm.path_metrology_xlsx()
msg = 'Confirm command: %s' % cmd
resp = gu.confirm_or_cancel_dialog_box(parent=self.butViewOffice, text=msg, title='Please confirm or cancel!')
if resp :
logger.info('Approved command:\n' + cmd, __name__)
self.commandInSubproc(cmd)
else :
logger.info('Command is cancelled', __name__)
except :
self.butViewOffice.setStyleSheet(cp.styleButtonGood)
#self.butViewOffice.setText('Close openoffice')
#cp.viewoffice = MaskEditor(**pars)
#cp.viewoffice.move(self.pos().__add__(QtCore.QPoint(820,-7))) # open window with offset w.r.t. parent
#cp.viewoffice.show()
def onButViewText(self):
logger.debug('onButViewText', __name__)
try :
cp.guifilebrowser.close()
#self.but_view.setStyleSheet(cp.styleButtonBad)
except :
#self.but_view.setStyleSheet(cp.styleButtonGood)
list_of_files = fnm.get_list_of_metrology_text_files()
if self.script != 'Select' :
list_of_files += self.list_metrology_alignment_const_fnames()
cp.guifilebrowser = GUIFileBrowser(None, list_of_files, fnm.path_metrology_text())
cp.guifilebrowser.move(self.pos().__add__(QtCore.QPoint(880,40))) # open window with offset w.r.t. parent
cp.guifilebrowser.show()
def onButConvert(self):
logger.debug('onButConvert', __name__)
#ifname = fnm.path_metrology_xlsx()
#ofname = fnm.path_metrology_text()
list_ofnames = convert_xlsx_to_text(fnm.path_metrology_xlsx(), fnm.path_metrology_ptrn(), print_bits=0)
msg = 'File %s is converted to the temporarty metrology text file(s):\n' % fnm.path_metrology_xlsx()
for name in list_ofnames : msg += ' %s\n' % name
logger.info(msg, __name__)
def onButRemove(self):
#logger.debug('onButRemove', __name__)
cmd = 'rm'
for fname in fnm.get_list_of_metrology_text_files() : cmd += ' %s' % fname
msg = 'Confirm command: %s' % cmd
resp = gu.confirm_or_cancel_dialog_box(parent=self.butViewOffice, text=msg, title='Please confirm or cancel!')
if resp :
logger.info('Approved command:\n' + cmd, __name__)
self.commandInSubproc(cmd)
else :
logger.info('Command is cancelled', __name__)
def onButList(self):
msg = 'List of metrology text files in %s\n' % fnm.path_dir_work()
for fname in fnm.get_list_of_metrology_text_files() : msg += ' %s\n' % fname
logger.info(msg, __name__)
def get_detector_selected(self):
lst = cp.list_of_dets_selected()
len_lst = len(lst)
msg = '%d detector(s) selected: %s' % (len_lst, str(lst))
#logger.info(msg, __name__ )
if len_lst !=1 :
msg += ' Select THE ONE!'
logger.warning(msg, __name__ )
return None
return lst[0]
def onButScript(self):
logger.debug('onButScript', __name__ )
det = self.get_detector_selected()
if det is None : return
if det != cp.list_of_dets[0] :
logger.warning('Scripts are implemented for CSPAD ONLY !!!: ', __name__)
lst = cp.dict_of_metrology_scripts[det]
selected = gu.selectFromListInPopupMenu(lst)
if selected is None : return # selection is cancelled
if selected is self.script : return # the same
txt = str(selected)
self.setScript(txt)
self.setSrc()
self.setStyleButtons()
def onButSrc(self):
logger.debug('onButSrc', __name__ )
det = self.get_detector_selected()
if det is None : return
try :
lst = ru.list_of_sources_for_det(det)
except :
lst = cp.dict_of_det_sources[det]
selected = gu.selectFromListInPopupMenu(lst)
if selected is None : return # selection is cancelled
if selected is self.source_name : return # the same
txt = str(selected)
self.setSrc(txt)
self.setStyleButtons()
def setScript(self,txt='Select'):
self.script = txt
self.butScript.setText( txt + cp.char_expand )
logger.info('Script is selected: ' + txt, __name__)
def setSrc(self,txt='Select'):
self.source_name = txt
self.butSrc.setText( txt + cp.char_expand )
logger.info('Source selected: ' + txt, __name__)
def onButEvaluate(self):
logger.debug('onButEvaluate', __name__)
det = self.get_detector_selected()
if det is None : return
list_of_metrology_scripts = cp.dict_of_metrology_scripts[det]
if self.script == 'Select' :
msg = 'Script for processing metrology file is not selected. Select it first...'
logger.warning(msg, __name__)
return
#print 'list_of_metrology_scripts', list_of_metrology_scripts
#for CSPAD script CSPADV1
if det == cp.list_of_dets[0] and self.script == list_of_metrology_scripts[0] :
msg = 'Evaluate parameters for %s using script %s' % (det, self.script)
logger.info(msg, __name__)
self.procCspadV1()
# for other detectors and scripts for now...
else :
msg = 'Script %s is not yet implemented for detector %s...' % (self.script, det)
logger.warning(msg, __name__)
return
def procCspadV1(self):
"""Create and save interim files for calibration types"""
self.list_of_calib_types = ['center', 'tilt', 'geometry']
fname_metrology = fnm.path_metrology_text()
msg = 'procCspadV1 for metrology data in file %s' % fname_metrology
logger.info(msg, __name__)
optal = OpticAlignmentCspadV1(fname_metrology, print_bits=0, plot_bits=0)
txt_qc_table_xy = optal.txt_qc_table_xy()
txt_qc_table_z = optal.txt_qc_table_z()
txt_center = optal.txt_center_pix_formatted_array()
txt_tilt = optal.txt_tilt_formatted_array()
txt_geometry = optal.txt_geometry()
logger.info('Quality check in X-Y plane:\n'+txt_qc_table_xy, __name__)
logger.info('Quality check in Z:\n'+txt_qc_table_z, __name__)
logger.info('parameters of type "center":\n'+txt_center, __name__)
logger.info('parameters of type "tilt":\n'+txt_tilt, __name__)
logger.info('parameters of type "geometry":\n'+txt_geometry, __name__)
# Save calibration files in work directory
dic_type_fname = self.dict_metrology_alignment_const_fname_for_type()
gu.save_textfile(txt_center, dic_type_fname['center'])
gu.save_textfile(txt_tilt, dic_type_fname['tilt'])
gu.save_textfile(txt_geometry, dic_type_fname['geometry'])
msg = 'Save interim metrology alignment files:'
for type in self.list_of_calib_types :
msg += '\n %s %s' % (type.ljust(16), dic_type_fname[type])
logger.info(msg, __name__)
def dict_metrology_alignment_const_fname_for_type(self) :
#lst_const_types = cp.const_types_cspad # ex. ['center', 'tilt',...]
lst_const_types = self.list_of_calib_types
lst_of_insets = ['%s-%s' % (self.script,type) for type in lst_const_types] # ex. ['CSPADV1-tilt', ...]
lst_of_const_fnames = gu.get_list_of_files_for_list_of_insets(fnm.path_metrology_alignment_const(), lst_of_insets)
return dict(zip(lst_const_types, lst_of_const_fnames))
def list_metrology_alignment_const_fnames(self) :
return self.dict_metrology_alignment_const_fname_for_type().values()
def onButDeploy(self):
logger.debug('onButDeploy', __name__)
if self.script == 'Select' :
msg = 'Script for processing metrology file is not selected.... Select it first and evaluate constants (Item 4)'
logger.warning(msg, __name__)
return
if self.source_name == 'Select' :
msg = 'Detector is not selected. Select it first...'
logger.warning(msg, __name__)
return
list_of_cmds = self.list_of_copy_cmds()
txt = '\nList of commands for tentetive file deployment:'
for cmd in list_of_cmds :
txt += '\n' + cmd
logger.info(txt, __name__)
msg = 'Approve commands \njust printed in the logger'
if self.approveCommand(self.butDeploy, msg) :
for cmd in list_of_cmds :
fd.procDeployCommand(cmd, 'metrology-alignment')
#print 'Command for deployer: ', cmd
if cp.guistatus is not None : cp.guistatus.updateStatusInfo()
def approveCommand(self, but, msg):
resp = gu.confirm_or_cancel_dialog_box(parent=but, text=msg, title='Please confirm or cancel!')
if resp : logger.info('Commands approved', __name__)
else : logger.info('Command is cancelled', __name__)
return resp
def list_of_copy_cmds(self):
det = self.get_detector_selected()
if det is None : return
dst_calib_dir = fnm.path_to_calib_dir()
dst_calib_type = cp.dict_of_det_calib_types[det]
dst_source = self.source_name
dst_fname = '%s.data' % cp.guirunrange.getRunRange()
#print 'dst_calib_dir ', dst_calib_dir
#print 'dst_calib_type ', dst_calib_type
#print 'dst_source ', dst_source
#print 'dst_fname ', dst_fname
list_of_cmds = []
for type, fname in self.dict_metrology_alignment_const_fname_for_type().iteritems() :
dst_path = os.path.join(dst_calib_dir, dst_calib_type, dst_source, type, dst_fname)
cmd = 'cp %s %s' % (fname, dst_path)
list_of_cmds.append(cmd)
return list_of_cmds
def commandInSubproc(self, cmd):
cmd_seq = cmd.split()
msg = 'Command: ' + cmd
#out, err = gu.subproc(cmd_seq)
#if err != '' : msg += '\nERROR: ' + err
#if out != '' : msg += '\nRESPONCE: ' + out
os.system(cmd)
logger.info(msg, __name__)
#os.system('chmod 670 %s' % path)
#-----------------------------
# In case someone decides to run this module
#
if __name__ == "__main__" :
app = QtGui.QApplication(sys.argv)
ex = GUIMetrology()
ex.show()
app.exec_()
#-----------------------------
| [
"dubrovin@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7"
] | dubrovin@SLAC.STANFORD.EDU@b967ad99-d558-0410-b138-e0f6c56caec7 |
4f21cc8ad151a60f883a38689c27e520a45da35f | 44413721791e00e5e0d728d2063cce9d072680bc | /env/bin/jupyter-run | d9f7fbc646cb396d16e13ba97ee516a6d2e357f6 | [] | no_license | andriyka/term-extraction-and-ontology-learning | 5174ba52db93bc3dd22b75a41c998c5e23a3bcd5 | 2fa478f1f6f28949d461331f6e8348f86bd344e1 | refs/heads/master | 2020-03-21T19:05:07.755413 | 2018-07-09T16:46:58 | 2018-07-09T16:46:58 | 138,929,875 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 278 | #!/home/ankus/Documents/ucu/terms/ate/env/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from jupyter_client.runapp import RunApp
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(RunApp.launch_instance())
| [
"ankus@ciklum.com"
] | ankus@ciklum.com | |
5490642f0d814cac8828eee54583a3bcdd470589 | eb5a845f144fbc4e1076deded9a8f15c3b77512f | /logic/asignacion.py | 67226121f415bc3281511fddc71f096b2494fa85 | [] | no_license | johncardozo/chorario | 619afa8fb018e6d5cbadfac24bd5210f33151713 | fbbf43a9c51312bb7a310d9106d4bfcbd4fcb692 | refs/heads/master | 2023-06-27T00:05:35.071031 | 2021-07-28T04:19:28 | 2021-07-28T04:19:28 | 392,017,423 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,361 | py | from .globales import obtener_numero_dia
def asignar(lista_cursos, lista_profes):
'''
Asigna los cursos a los profesores
'''
# Recorre los cursos
for curso in lista_cursos:
# Recorre los profesores
for profe in lista_profes:
# Obtiene el tipo de profesor
tipo_profesor = profe['tipo']
# Verifica que el profesor no sobrepase
# la cantidad de cursos asignados dado su tipo
if (
(tipo_profesor == 'MT' and len(profe["cursos"]) == 5) or
(tipo_profesor == 'TC' and len(profe["cursos"]) == 6)
):
# Continua con el siguiente profesor
continue
# Recorre las franjas del curso
disponibilidades_validas = []
for franja in curso['franjas']:
# Obtiene el numero del dia de la franja
numero_dia = obtener_numero_dia(franja['dia'])
# Intenta obtener la disponibilidad que hace match con la HI de la franja
disp_inicial = next(
(disp for disp in profe['horario'][numero_dia] if franja['hi'] >= disp['hi']
and franja['hi'] < disp['hf']
and disp['disponible']
and not disp['asignado']), None)
# Intenta obtener la disponibilidad que hace match con la HF de la franja
disp_final = next(
(disp for disp in profe['horario'][numero_dia] if franja['hf'] >= disp['hi']
and franja['hf'] < disp['hf']
and disp['disponible']
and not disp['asignado']), None)
# Verifica si se encontró una disponibilidad inicial y final
if disp_inicial and disp_final:
# Busca la posicion inicial y final
posicion_inicial = profe['horario'][numero_dia].index(
disp_inicial)
posicion_final = profe['horario'][numero_dia].index(
disp_final)
# Obtiene todas las disponibilidades entre
# la disponibilidad inicial y la final
disp_franja = profe['horario'][numero_dia][posicion_inicial:posicion_final+1]
# Verifica que todas las disponibilidades obtenidas estén disponibles
todas = all(d['disponible'] and not d['asignado']
for d in disp_franja)
if todas:
# Agrega las disponibilidades de la franja
disponibilidades_validas.append(disp_franja)
else:
# Si no todas las disponibilidades son válidas no continua buscando
break
# print(
# f"C={curso['curso']}, F={franja['hi']}-{franja['hf']}, P={profe['profesor']}, dia={numero_dia}, inicial={posicion_inicial}->{disp_inicial['hi']}-{disp_inicial['hf']}, final={posicion_final}->{disp_final['hi']}-{disp_final['hf']} - LIBRE={todas}")
# Verifica si todas las disponibilidades del profesor
# están disponibles para todas las franjas de curso
if len(curso['franjas']) == len(disponibilidades_validas):
# Recorre las disponibilidades para marcarlas como asignadas
for grupo in disponibilidades_validas:
for disponibilidad in grupo:
disponibilidad['asignado'] = True
disponibilidad['curso'] = curso['curso']
# Recorre las franjas del curso para marcarlas como asignadas
for franja in curso['franjas']:
franja['asignada'] = True
franja['profesor'] = profe['profesor']
# Asigna el profesor al curso
curso['asignado'] = True
curso['profesor'] = profe['profesor']
# Agrega el curso al profesor
profe['cursos'].append(curso['curso'])
# print(
# f"El profesor {profe['profesor']} fue asignado al curso {curso['curso']}")
# No busca más profesores
break
| [
"johncardozo@gmail.com"
] | johncardozo@gmail.com |
cefc100e75066c2549e6292c5c94cabeb1551849 | a2389673b5452a1920cf02df44a522ef390d2a69 | /ImageLoader.py | d20c3f6a8a9c5f2f130a513d6c1627310cc7356b | [] | no_license | cbelangerstpierre/Dinosaur_T-Rex_Game | c3bf37c2209a6b614b4a9f047286be7d98888ae8 | 2b1eb7e0048e8558c259453617781bcf2b75e6ba | refs/heads/main | 2023-06-26T18:05:53.845161 | 2021-07-13T18:24:39 | 2021-07-13T18:24:39 | 385,103,509 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,834 | py | import pygame
import os
import MainWindow
class ImageLoader:
DIR_ASSETS = "assets"
DIR_IMAGES = "images"
# Background images
BG = pygame.transform.scale(
pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "white.jpg")),
(MainWindow.MainWindow.WIDTH, MainWindow.MainWindow.HEIGHT)
)
FLOOR = pygame.transform.scale(
pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "terrain.png")),
(MainWindow.MainWindow.WIDTH * 5, int(MainWindow.MainWindow.HEIGHT / 5))
)
CLOUD = pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "cloud.png"))
# Dino images
DINO_SPRINTING = [
pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "dino-3.png")),
pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "dino-4.png"))
]
DINO_JUMPING = pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "dino-1.png"))
DINO_LOW = [
pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "dino-low-1.png")),
pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "dino-low-2.png"))
]
# Enemies images
CACTUS_1 = pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "cactus-1.png"))
CACTUS_2 = pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "cactus-2.png"))
CACTUS_3 = pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "cactus-3.png"))
CACTUS_BIG_1 = pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "cactus-large-1.png"))
CACTUS_BIG_2 = pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "cactus-large-2.png"))
CACTUS_BIG_3 = pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "cactus-large-3.png"))
BIRD_1 = pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "bird-1.png"))
BIRD_2 = pygame.image.load(os.path.join(DIR_ASSETS, DIR_IMAGES, "bird-2.png"))
| [
"cedricbstpierre@yahoo.com"
] | cedricbstpierre@yahoo.com |
00779cff775c9bac89ae3297326dbe31f7d95861 | 00eeaf221e1e62f59132d461795edabbb75d5e39 | /connectivity_trial.py | 765af20606667b2ecfda4c7dae3baf03fd06a60d | [] | no_license | ShivaniThakare/MusicRecommendation | dda9a64dd7a7327df3be6540834798cca7e9faa9 | f6c62ca9db72d3b83dd679d346d13909fcce4c52 | refs/heads/master | 2023-05-04T20:30:51.132210 | 2021-05-15T11:02:40 | 2021-05-15T11:02:40 | 367,607,513 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,816 | py | # -*- coding: utf-8 -*-
from flask import Flask, render_template, request, redirect, url_for, jsonify
from flask_mysqldb import MySQL
from datetime import timedelta
import random
import os
import sys
from music import Music
from the_user import Myuser
import numpy as np
import time
np.set_printoptions(threshold=sys.maxsize)
app = Flask(__name__)
app.secret_key = 'ussa2020'
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'audio'
mysql = MySQL(app)
app.permanent_session_lifetime = timedelta(minutes=5)
s = []
tempS = []
final_song = []
cur_user = Myuser()
def firstsignup():
for i in range(0, 10):
s.append(random.randint(0, 499))
cur = mysql.connection.cursor()
for i in s:
cur.execute('SELECT song FROM songs WHERE song_id = %s', (i, ))
account = cur.fetchone()
tempS.append(account[0])
mysql.connection.commit()
cur.close()
cur_user.setsong_list(tempS)
def loadlist(username):
temp = []
cur = mysql.connection.cursor()
for i in range(0, 10):
cur.execute('select songname from beforelogout where username = %s and songid = %s', (username, i + 1))
templist = cur.fetchone()
temp.append(templist[0])
mysql.connection.commit()
cur.close()
cur_user.setsong_list(temp)
def getobj(tempS):
theuser = cur_user.getuser_name
a = np.zeros(shape=[500, 500], dtype=np.float32) # Q matrix initialized to 0
b = np.zeros(shape=[500, 500], dtype=np.float32) # R matrix initialized to 0
cur = mysql.connection.cursor()
cur.execute('select rowno from matrixinput where username = %s', (theuser, )) # to see if the user exits. if it does then the result is not null ie. if the rows are fetched.
if cur.fetchone(): # see if the rows are fetched for a particular user
for i in range(0, 500):
for j in range(0, 500):
cur.execute("select Qmatrix, Rmatrix from matrixinput where username = %s and rowno = %s and colno = %s", (theuser, i, j))
tuple_ = cur.fetchone()
a[i][j] = tuple_[0] # creating the q matrix from the DB
b[i][j] = tuple_[1] # creating the r matrix from the DB
s = [] # if the user does not exist then R-matrix and Q-matrix initialized to 0 are used for object creation.
for i in range(0, 10):
cur.execute("select Song_id from songs where song = %s", (tempS[i], )) # tempS has 10 songs based on user type. if new user, then random songs. if existing user, then songs that were last reommended to him ie. from before logout table.
# fetch the actual song id of the 10 songs in tempS from the songs table in DB
t = cur.fetchone()
s.append(t[0])
mysql.connection.commit()
cur.close()
# creating an object of music class so as to bring the recommendation model to the updated position of the user.
myobj = Music(s, a, b) # song id of playlist, q matrix, r matrix
return myobj
@app.route("/finalhome2")
def finalhome2():
return render_template("finalhome2.html", final_song=final_song, S=tempS)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == "POST":
details = request.form
username = details['username']
password = details['password']
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM user_info WHERE username = %s AND password = %s', (username, password))
account = cur.fetchone()
if account:
# Create session data, we can access this data in other routes
# return 'success'
cur_user.setmyuser_name(username)
loadlist(username)
tempS = cur_user.getsong_list()
a = '/static/'
b = '.mp3'
for i in range(0, 10):
final_song.append(a + tempS[i] + b)
return render_template("finalhome2.html", final_song=final_song, S=tempS, username=username)
mysql.connection.commit()
cur.close()
return render_template('login.html')
@app.route('/', methods=['GET', 'POST'])
def signup():
error = None
if request.method == "POST":
details = request.form
username = details['username']
password = details['password']
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM user_info WHERE username = %s', (username,))
account = cur.fetchone()
if account:
return redirect(url_for('login'))
else:
cur.execute("INSERT INTO user_info(username, password) VALUES (%s, %s)", (username, password))
# msg = 'You have successfully registered!'
firstsignup()
cur_user.setmyuser_name(username)
tempS = cur_user.getsong_list()
print(tempS)
a = '/static/'
b = '.mp3'
for i in range(0, 10):
final_song.append(a + tempS[i] + b)
return render_template("finalhome2.html", final_song=final_song, S=tempS, username=username)
mysql.connection.commit()
cur.close()
return render_template('signup.html', error=error)
@app.route('/background_process', methods=["POST"])
def background_process():
response = request.get_json()
print(response)
song_id = int(response['songnum'])
songname = response['songname']
length = int(response['len'])
cur = mysql.connection.cursor()
cur.execute("SELECT songlike FROM liked WHERE song_name = %s", (songname,))
if cur.fetchone() is None:
cur.execute("INSERT INTO liked(username, song_id, song_name, songlike, song_len) VALUES (%s, %s, %s, %s, %s)", (cur_user.getuser_name(), song_id, songname, length, 0))
mysql.connection.commit()
else:
cur.execute("UPDATE liked SET songlike = %s WHERE song_name = %s and username = %s", (length, songname, cur_user.getuser_name()))
mysql.connection.commit()
cur.close()
return jsonify(response)
@app.route('/trackTiming', methods=['GET', 'POST'])
def trackTiming():
response_x = request.get_json()
songname = response_x['trackTitle1']
song_id = response_x['_currentTrack']
temp_time = response_x['trackCurrentTime1']
abc = 0
abc = sum(x * int(t) for x, t in zip([60, 1], temp_time.split(":")))
cur = mysql.connection.cursor()
cur.execute("SELECT song_len FROM liked WHERE song_name = %s and username = %s", (songname, cur_user.getuser_name()))
songlist = cur.fetchone()
print(songlist)
if songlist is None:
print("inside If")
cur.execute("INSERT INTO liked(username, song_id, song_name, songlike, song_len) VALUES (%s, %s, %s, %s, %s)", (cur_user.getuser_name(), song_id, songname, 1, abc))
mysql.connection.commit()
else:
print("inside else")
songlen = list(songlist)
print(songlen)
final_len = int(songlen[0]) + int(abc)
cur.execute("UPDATE liked SET song_len = %s WHERE song_name = %s and username = %s", (final_len, songname, cur_user.getuser_name()))
mysql.connection.commit()
cur.close()
return jsonify(response_x)
@app.route("/newrecommendation", methods=['GET', 'POST'])
def newrecommendation():
# userinput matrix creation
print("recommendation start")
tempS = cur_user.getsong_list()
rows, cols = (10, 4)
userinput = [[0 for i in range(cols)] for j in range(rows)]
i = 0
cur = mysql.connection.cursor()
for song in tempS:
cur.execute("SELECT songlike, song_len FROM liked WHERE song_name = %s and username=%s", (song, cur_user.getuser_name()))
temptuple = cur.fetchone()
print(temptuple)
if temptuple is None:
userinput[i][1] = 0
userinput[i][2] = 0
else:
userinput[i][1] = temptuple[0]
userinput[i][2] = temptuple[1]
cur.execute("SELECT song_id, genre FROM songs WHERE Song = %s", (song,))
temptuple = cur.fetchone()
userinput[i][0] = temptuple[0]
userinput[i][3] = temptuple[1]
i = i + 1
mysql.connection.commit()
cur.close()
# calling newrecommendation
print("user input liya")
myMusic = getobj(tempS)
print("obj create hua")
t0 = time.time()
myMusic.NewRecommendation(userinput)
t1 = time.time() - t0
print("Time elapsed for recommendation: ", t1)
usercur = cur_user.getuser_name()
print("recommendation hua")
# songid search in db, create final_song list which contain songname , send in finalhome2
cummulative = []
reward = 0.0
t2 = time.time()
cur = mysql.connection.cursor()
a1 = time.time()
cur.execute("select rowno from matrixinput where username = %s", (usercur, ))
if cur.fetchone():
for i in range(0, 500):
cur.execute("delete from matrixinput where username=%s and rowno=%s ", (usercur, i))
a2 = time.time() - a1
print("Time for matrix del inner in DB:", a2)
for i in range(0, 500):
for j in range(0, 500):
reward += myMusic.R[i][j]
cur.execute("INSERT INTO matrixinput(username, rowno, colno, Qmatrix, Rmatrix) VALUES (%s, %s, %s, %s, %s)", (usercur, i, j, myMusic.Q[i][j], myMusic.R[i][j]))
cummulative.append(reward)
print(cummulative)
t3 = time.time() - t2
print("Time for matrix insertion in DB:", t3)
print("db me matrix gaya")
playlist = []
for i in range(0, 10):
cur.execute('SELECT song FROM songs WHERE song_id = %s', (myMusic.playlist[i][1], ))
account = cur.fetchone()
playlist.append(account[0])
mysql.connection.commit()
cur.close()
cur_user.setsong_list(playlist)
a = "/static/"
b = ".mp3"
final_song = []
for i in range(0, 10):
final_song.append(a + playlist[i] + b)
return render_template("finalhome2.html", final_song=final_song, S=playlist, username=usercur)
@app.route("/logout", methods=['GET', 'POST'])
def logout():
currrentuser = cur_user.getuser_name()
tempS = cur_user.getsong_list()
print(tempS)
cur = mysql.connection.cursor()
cur.execute('select songid from beforelogout where username = %s', (currrentuser, ))
if cur.fetchone():
print("inside if")
for i in range(0, 10):
cur.execute('update beforelogout set songname = %s where username=%s and songid=%s', (tempS[i], currrentuser, i + 1))
else:
for i in range(0, 10):
cur.execute('insert into beforelogout(username, songid, songname) values (%s, %s, %s)', (currrentuser, i + 1, tempS[i]))
mysql.connection.commit()
cur.close()
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)
| [
"thakareshivani444@gmail.com"
] | thakareshivani444@gmail.com |
e6f3d7c3ba67ddac6b6adb028bb8489957cda513 | 4f1cebe6cbbe9a1402e5d747ca166249e60b733c | /mysite/ehealth/consumers.py | e0e115a9974185b2664fda76e64416dd52accfc1 | [] | no_license | GalaxyBound/HealthApplication | 74da5c8e238654d9f9026a53692af19e3ea941e6 | c800485b25cf5255229d24988a10c79351059791 | refs/heads/master | 2020-03-27T08:24:06.807515 | 2018-10-29T02:20:55 | 2018-10-29T02:20:55 | 146,250,710 | 2 | 0 | null | 2018-10-29T02:20:56 | 2018-08-27T05:28:18 | JavaScript | UTF-8 | Python | false | false | 806 | py | from channels.generic.websocket import WebsocketConsumer
import json
from asgiref.sync import async_to_sync
class VitalsConsumer(WebsocketConsumer):
def connect(self):
async_to_sync(self.channel_layer.group_add)(
'vitals',
self.channel_name
)
self.accept()
def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)(
'vitals',
self.channel_name
)
pass
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['vitals']
self.send(text_data=json.dumps({
'vitals': message
}))
def vitals_alarm(self, vital_data):
self.send(
text_data = vital_data["text"]
) | [
"josh@infinx.com.au"
] | josh@infinx.com.au |
f5e51b2d85c0f977f3d3f7c2ae50bde80a6b674a | 61ac84c86d086e630cbe3a81e9930f71b1198329 | /python/z3/z3.py | 70dcb158ef1afa09c4feee02e6d59d4746fb87fd | [] | no_license | rosstex/516project | 8c3f8b2edf6a54e73b9d40465da7e1d91ae92b21 | e3bac97d9ee33124c8ef6a3eb01bb15fca0478ea | refs/heads/master | 2020-04-07T10:53:49.211809 | 2019-01-15T21:59:44 | 2019-01-15T21:59:44 | 158,304,522 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 303,889 | py |
############################################
# Copyright (c) 2012 Microsoft Corporation
#
# Z3 Python interface
#
# Author: Leonardo de Moura (leonardo)
############################################
"""Z3 is a high performance theorem prover developed at Microsoft Research. Z3 is used in many applications such as: software/hardware verification and testing, constraint solving, analysis of hybrid systems, security, biology (in silico analysis), and geometrical problems.
Several online tutorials for Z3Py are available at:
http://rise4fun.com/Z3Py/tutorial/guide
Please send feedback, comments and/or corrections on the Issue tracker for https://github.com/Z3prover/z3.git. Your comments are very valuable.
Small example:
>>> x = Int('x')
>>> y = Int('y')
>>> s = Solver()
>>> s.add(x > 0)
>>> s.add(x < 2)
>>> s.add(y == x + 1)
>>> s.check()
sat
>>> m = s.model()
>>> m[x]
1
>>> m[y]
2
Z3 exceptions:
>>> try:
... x = BitVec('x', 32)
... y = Bool('y')
... # the expression x + y is type incorrect
... n = x + y
... except Z3Exception as ex:
... print("failed: %s" % ex)
failed: sort mismatch
"""
from . import z3core
from .z3core import *
from .z3types import *
from .z3consts import *
from .z3printer import *
from fractions import Fraction
import sys
import io
import math
import copy
if sys.version < '3':
def _is_int(v):
return isinstance(v, (int, long))
else:
def _is_int(v):
return isinstance(v, int)
def enable_trace(msg):
Z3_enable_trace(msg)
def disable_trace(msg):
Z3_disable_trace(msg)
def get_version_string():
major = ctypes.c_uint(0)
minor = ctypes.c_uint(0)
build = ctypes.c_uint(0)
rev = ctypes.c_uint(0)
Z3_get_version(major, minor, build, rev)
return "%s.%s.%s" % (major.value, minor.value, build.value)
def get_version():
major = ctypes.c_uint(0)
minor = ctypes.c_uint(0)
build = ctypes.c_uint(0)
rev = ctypes.c_uint(0)
Z3_get_version(major, minor, build, rev)
return (major.value, minor.value, build.value, rev.value)
def get_full_version():
return Z3_get_full_version()
# We use _z3_assert instead of the assert command because we want to
# produce nice error messages in Z3Py at rise4fun.com
def _z3_assert(cond, msg):
if not cond:
raise Z3Exception(msg)
def _z3_check_cint_overflow(n, name):
_z3_assert(ctypes.c_int(n).value == n, name + " is too large")
def open_log(fname):
"""Log interaction to a file. This function must be invoked immediately after init(). """
Z3_open_log(fname)
def append_log(s):
"""Append user-defined string to interaction log. """
Z3_append_log(s)
def to_symbol(s, ctx=None):
"""Convert an integer or string into a Z3 symbol."""
if _is_int(s):
return Z3_mk_int_symbol(_get_ctx(ctx).ref(), s)
else:
return Z3_mk_string_symbol(_get_ctx(ctx).ref(), s)
def _symbol2py(ctx, s):
"""Convert a Z3 symbol back into a Python object. """
if Z3_get_symbol_kind(ctx.ref(), s) == Z3_INT_SYMBOL:
return "k!%s" % Z3_get_symbol_int(ctx.ref(), s)
else:
return Z3_get_symbol_string(ctx.ref(), s)
# Hack for having nary functions that can receive one argument that is the
# list of arguments.
# Use this when function takes a single list of arguments
def _get_args(args):
try:
if len(args) == 1 and (isinstance(args[0], tuple) or isinstance(args[0], list)):
return args[0]
elif len(args) == 1 and (isinstance(args[0], set) or isinstance(args[0], AstVector)):
return [arg for arg in args[0]]
else:
return args
except: # len is not necessarily defined when args is not a sequence (use reflection?)
return args
# Use this when function takes multiple arguments
def _get_args_ast_list(args):
try:
if isinstance(args, set) or isinstance(args, AstVector) or isinstance(args, tuple):
return [arg for arg in args]
else:
return args
except:
return args
def _to_param_value(val):
if isinstance(val, bool):
if val == True:
return "true"
else:
return "false"
else:
return str(val)
def z3_error_handler(c, e):
# Do nothing error handler, just avoid exit(0)
# The wrappers in z3core.py will raise a Z3Exception if an error is detected
return
class Context:
"""A Context manages all other Z3 objects, global configuration options, etc.
Z3Py uses a default global context. For most applications this is sufficient.
An application may use multiple Z3 contexts. Objects created in one context
cannot be used in another one. However, several objects may be "translated" from
one context to another. It is not safe to access Z3 objects from multiple threads.
The only exception is the method `interrupt()` that can be used to interrupt() a long
computation.
The initialization method receives global configuration options for the new context.
"""
def __init__(self, *args, **kws):
if __debug__:
_z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
conf = Z3_mk_config()
for key in kws:
value = kws[key]
Z3_set_param_value(conf, str(key).upper(), _to_param_value(value))
prev = None
for a in args:
if prev is None:
prev = a
else:
Z3_set_param_value(conf, str(prev), _to_param_value(a))
prev = None
self.ctx = Z3_mk_context_rc(conf)
self.eh = Z3_set_error_handler(self.ctx, z3_error_handler)
Z3_set_ast_print_mode(self.ctx, Z3_PRINT_SMTLIB2_COMPLIANT)
Z3_del_config(conf)
def __del__(self):
Z3_del_context(self.ctx)
self.ctx = None
self.eh = None
def ref(self):
"""Return a reference to the actual C pointer to the Z3 context."""
return self.ctx
def interrupt(self):
"""Interrupt a solver performing a satisfiability test, a tactic processing a goal, or simplify functions.
This method can be invoked from a thread different from the one executing the
interruptible procedure.
"""
Z3_interrupt(self.ref())
# Global Z3 context
_main_ctx = None
def main_ctx():
"""Return a reference to the global Z3 context.
>>> x = Real('x')
>>> x.ctx == main_ctx()
True
>>> c = Context()
>>> c == main_ctx()
False
>>> x2 = Real('x', c)
>>> x2.ctx == c
True
>>> eq(x, x2)
False
"""
global _main_ctx
if _main_ctx is None:
_main_ctx = Context()
return _main_ctx
def _get_ctx(ctx):
if ctx is None:
return main_ctx()
else:
return ctx
def set_param(*args, **kws):
"""Set Z3 global (or module) parameters.
>>> set_param(precision=10)
"""
if __debug__:
_z3_assert(len(args) % 2 == 0, "Argument list must have an even number of elements.")
new_kws = {}
for k in kws:
v = kws[k]
if not set_pp_option(k, v):
new_kws[k] = v
for key in new_kws:
value = new_kws[key]
Z3_global_param_set(str(key).upper(), _to_param_value(value))
prev = None
for a in args:
if prev is None:
prev = a
else:
Z3_global_param_set(str(prev), _to_param_value(a))
prev = None
def reset_params():
"""Reset all global (or module) parameters.
"""
Z3_global_param_reset_all()
def set_option(*args, **kws):
"""Alias for 'set_param' for backward compatibility.
"""
return set_param(*args, **kws)
def get_param(name):
"""Return the value of a Z3 global (or module) parameter
>>> get_param('nlsat.reorder')
'true'
"""
ptr = (ctypes.c_char_p * 1)()
if Z3_global_param_get(str(name), ptr):
r = z3core._to_pystr(ptr[0])
return r
raise Z3Exception("failed to retrieve value for '%s'" % name)
#########################################
#
# ASTs base class
#
#########################################
# Mark objects that use pretty printer
class Z3PPObject:
"""Superclass for all Z3 objects that have support for pretty printing."""
def use_pp(self):
return True
class AstRef(Z3PPObject):
"""AST are Direct Acyclic Graphs (DAGs) used to represent sorts, declarations and expressions."""
def __init__(self, ast, ctx=None):
self.ast = ast
self.ctx = _get_ctx(ctx)
Z3_inc_ref(self.ctx.ref(), self.as_ast())
def __del__(self):
if self.ctx.ref() is not None:
Z3_dec_ref(self.ctx.ref(), self.as_ast())
def __deepcopy__(self, memo={}):
return _to_ast_ref(self.ast, self.ctx)
def __str__(self):
return obj_to_string(self)
def __repr__(self):
return obj_to_string(self)
def __eq__(self, other):
return self.eq(other)
def __hash__(self):
return self.hash()
def __nonzero__(self):
return self.__bool__()
def __bool__(self):
if is_true(self):
return True
elif is_false(self):
return False
elif is_eq(self) and self.num_args() == 2:
return self.arg(0).eq(self.arg(1))
else:
raise Z3Exception("Symbolic expressions cannot be cast to concrete Boolean values.")
def sexpr(self):
"""Return a string representing the AST node in s-expression notation.
>>> x = Int('x')
>>> ((x + 1)*x).sexpr()
'(* (+ x 1) x)'
"""
return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
def as_ast(self):
"""Return a pointer to the corresponding C Z3_ast object."""
return self.ast
def get_id(self):
"""Return unique identifier for object. It can be used for hash-tables and maps."""
return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
def ctx_ref(self):
"""Return a reference to the C context where this AST node is stored."""
return self.ctx.ref()
def eq(self, other):
"""Return `True` if `self` and `other` are structurally identical.
>>> x = Int('x')
>>> n1 = x + 1
>>> n2 = 1 + x
>>> n1.eq(n2)
False
>>> n1 = simplify(n1)
>>> n2 = simplify(n2)
>>> n1.eq(n2)
True
"""
if __debug__:
_z3_assert(is_ast(other), "Z3 AST expected")
return Z3_is_eq_ast(self.ctx_ref(), self.as_ast(), other.as_ast())
def translate(self, target):
"""Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
>>> c1 = Context()
>>> c2 = Context()
>>> x = Int('x', c1)
>>> y = Int('y', c2)
>>> # Nodes in different contexts can't be mixed.
>>> # However, we can translate nodes from one context to another.
>>> x.translate(c2) + y
x + y
"""
if __debug__:
_z3_assert(isinstance(target, Context), "argument must be a Z3 context")
return _to_ast_ref(Z3_translate(self.ctx.ref(), self.as_ast(), target.ref()), target)
def __copy__(self):
return self.translate(self.ctx)
def hash(self):
"""Return a hashcode for the `self`.
>>> n1 = simplify(Int('x') + 1)
>>> n2 = simplify(2 + Int('x') - 1)
>>> n1.hash() == n2.hash()
True
"""
return Z3_get_ast_hash(self.ctx_ref(), self.as_ast())
def is_ast(a):
"""Return `True` if `a` is an AST node.
>>> is_ast(10)
False
>>> is_ast(IntVal(10))
True
>>> is_ast(Int('x'))
True
>>> is_ast(BoolSort())
True
>>> is_ast(Function('f', IntSort(), IntSort()))
True
>>> is_ast("x")
False
>>> is_ast(Solver())
False
"""
return isinstance(a, AstRef)
def eq(a, b):
"""Return `True` if `a` and `b` are structurally identical AST nodes.
>>> x = Int('x')
>>> y = Int('y')
>>> eq(x, y)
False
>>> eq(x + 1, x + 1)
True
>>> eq(x + 1, 1 + x)
False
>>> eq(simplify(x + 1), simplify(1 + x))
True
"""
if __debug__:
_z3_assert(is_ast(a) and is_ast(b), "Z3 ASTs expected")
return a.eq(b)
def _ast_kind(ctx, a):
if is_ast(a):
a = a.as_ast()
return Z3_get_ast_kind(ctx.ref(), a)
def _ctx_from_ast_arg_list(args, default_ctx=None):
ctx = None
for a in args:
if is_ast(a) or is_probe(a):
if ctx is None:
ctx = a.ctx
else:
if __debug__:
_z3_assert(ctx == a.ctx, "Context mismatch")
if ctx is None:
ctx = default_ctx
return ctx
def _ctx_from_ast_args(*args):
return _ctx_from_ast_arg_list(args)
def _to_func_decl_array(args):
sz = len(args)
_args = (FuncDecl * sz)()
for i in range(sz):
_args[i] = args[i].as_func_decl()
return _args, sz
def _to_ast_array(args):
sz = len(args)
_args = (Ast * sz)()
for i in range(sz):
_args[i] = args[i].as_ast()
return _args, sz
def _to_ref_array(ref, args):
sz = len(args)
_args = (ref * sz)()
for i in range(sz):
_args[i] = args[i].as_ast()
return _args, sz
def _to_ast_ref(a, ctx):
k = _ast_kind(ctx, a)
if k == Z3_SORT_AST:
return _to_sort_ref(a, ctx)
elif k == Z3_FUNC_DECL_AST:
return _to_func_decl_ref(a, ctx)
else:
return _to_expr_ref(a, ctx)
#########################################
#
# Sorts
#
#########################################
def _sort_kind(ctx, s):
return Z3_get_sort_kind(ctx.ref(), s)
class SortRef(AstRef):
"""A Sort is essentially a type. Every Z3 expression has a sort. A sort is an AST node."""
def as_ast(self):
return Z3_sort_to_ast(self.ctx_ref(), self.ast)
def get_id(self):
return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
def kind(self):
"""Return the Z3 internal kind of a sort. This method can be used to test if `self` is one of the Z3 builtin sorts.
>>> b = BoolSort()
>>> b.kind() == Z3_BOOL_SORT
True
>>> b.kind() == Z3_INT_SORT
False
>>> A = ArraySort(IntSort(), IntSort())
>>> A.kind() == Z3_ARRAY_SORT
True
>>> A.kind() == Z3_INT_SORT
False
"""
return _sort_kind(self.ctx, self.ast)
def subsort(self, other):
"""Return `True` if `self` is a subsort of `other`.
>>> IntSort().subsort(RealSort())
True
"""
return False
def cast(self, val):
"""Try to cast `val` as an element of sort `self`.
This method is used in Z3Py to convert Python objects such as integers,
floats, longs and strings into Z3 expressions.
>>> x = Int('x')
>>> RealSort().cast(x)
ToReal(x)
"""
if __debug__:
_z3_assert(is_expr(val), "Z3 expression expected")
_z3_assert(self.eq(val.sort()), "Sort mismatch")
return val
def name(self):
"""Return the name (string) of sort `self`.
>>> BoolSort().name()
'Bool'
>>> ArraySort(IntSort(), IntSort()).name()
'Array'
"""
return _symbol2py(self.ctx, Z3_get_sort_name(self.ctx_ref(), self.ast))
def __eq__(self, other):
"""Return `True` if `self` and `other` are the same Z3 sort.
>>> p = Bool('p')
>>> p.sort() == BoolSort()
True
>>> p.sort() == IntSort()
False
"""
if other is None:
return False
return Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
def __ne__(self, other):
"""Return `True` if `self` and `other` are not the same Z3 sort.
>>> p = Bool('p')
>>> p.sort() != BoolSort()
False
>>> p.sort() != IntSort()
True
"""
return not Z3_is_eq_sort(self.ctx_ref(), self.ast, other.ast)
def __hash__(self):
""" Hash code. """
return AstRef.__hash__(self)
def is_sort(s):
"""Return `True` if `s` is a Z3 sort.
>>> is_sort(IntSort())
True
>>> is_sort(Int('x'))
False
>>> is_expr(Int('x'))
True
"""
return isinstance(s, SortRef)
def _to_sort_ref(s, ctx):
if __debug__:
_z3_assert(isinstance(s, Sort), "Z3 Sort expected")
k = _sort_kind(ctx, s)
if k == Z3_BOOL_SORT:
return BoolSortRef(s, ctx)
elif k == Z3_INT_SORT or k == Z3_REAL_SORT:
return ArithSortRef(s, ctx)
elif k == Z3_BV_SORT:
return BitVecSortRef(s, ctx)
elif k == Z3_ARRAY_SORT:
return ArraySortRef(s, ctx)
elif k == Z3_DATATYPE_SORT:
return DatatypeSortRef(s, ctx)
elif k == Z3_FINITE_DOMAIN_SORT:
return FiniteDomainSortRef(s, ctx)
elif k == Z3_FLOATING_POINT_SORT:
return FPSortRef(s, ctx)
elif k == Z3_ROUNDING_MODE_SORT:
return FPRMSortRef(s, ctx)
return SortRef(s, ctx)
def _sort(ctx, a):
return _to_sort_ref(Z3_get_sort(ctx.ref(), a), ctx)
def DeclareSort(name, ctx=None):
"""Create a new uninterpreted sort named `name`.
If `ctx=None`, then the new sort is declared in the global Z3Py context.
>>> A = DeclareSort('A')
>>> a = Const('a', A)
>>> b = Const('b', A)
>>> a.sort() == A
True
>>> b.sort() == A
True
>>> a == b
a == b
"""
ctx = _get_ctx(ctx)
return SortRef(Z3_mk_uninterpreted_sort(ctx.ref(), to_symbol(name, ctx)), ctx)
#########################################
#
# Function Declarations
#
#########################################
class FuncDeclRef(AstRef):
"""Function declaration. Every constant and function have an associated declaration.
The declaration assigns a name, a sort (i.e., type), and for function
the sort (i.e., type) of each of its arguments. Note that, in Z3,
a constant is a function with 0 arguments.
"""
def as_ast(self):
return Z3_func_decl_to_ast(self.ctx_ref(), self.ast)
def get_id(self):
return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
def as_func_decl(self):
return self.ast
def name(self):
"""Return the name of the function declaration `self`.
>>> f = Function('f', IntSort(), IntSort())
>>> f.name()
'f'
>>> isinstance(f.name(), str)
True
"""
return _symbol2py(self.ctx, Z3_get_decl_name(self.ctx_ref(), self.ast))
def arity(self):
"""Return the number of arguments of a function declaration. If `self` is a constant, then `self.arity()` is 0.
>>> f = Function('f', IntSort(), RealSort(), BoolSort())
>>> f.arity()
2
"""
return int(Z3_get_arity(self.ctx_ref(), self.ast))
def domain(self, i):
"""Return the sort of the argument `i` of a function declaration. This method assumes that `0 <= i < self.arity()`.
>>> f = Function('f', IntSort(), RealSort(), BoolSort())
>>> f.domain(0)
Int
>>> f.domain(1)
Real
"""
if __debug__:
_z3_assert(i < self.arity(), "Index out of bounds")
return _to_sort_ref(Z3_get_domain(self.ctx_ref(), self.ast, i), self.ctx)
def range(self):
"""Return the sort of the range of a function declaration. For constants, this is the sort of the constant.
>>> f = Function('f', IntSort(), RealSort(), BoolSort())
>>> f.range()
Bool
"""
return _to_sort_ref(Z3_get_range(self.ctx_ref(), self.ast), self.ctx)
def kind(self):
"""Return the internal kind of a function declaration. It can be used to identify Z3 built-in functions such as addition, multiplication, etc.
>>> x = Int('x')
>>> d = (x + 1).decl()
>>> d.kind() == Z3_OP_ADD
True
>>> d.kind() == Z3_OP_MUL
False
"""
return Z3_get_decl_kind(self.ctx_ref(), self.ast)
def params(self):
ctx = self.ctx
n = Z3_get_decl_num_parameters(self.ctx_ref(), self.ast)
result = [ None for i in range(n) ]
for i in range(n):
k = Z3_get_decl_parameter_kind(self.ctx_ref(), self.ast, i)
if k == Z3_PARAMETER_INT:
result[i] = Z3_get_decl_int_parameter(self.ctx_ref(), self.ast, i)
elif k == Z3_PARAMETER_DOUBLE:
result[i] = Z3_get_decl_double_parameter(self.ctx_ref(), self.ast, i)
elif k == Z3_PARAMETER_RATIONAL:
result[i] = Z3_get_decl_rational_parameter(self.ctx_ref(), self.ast, i)
elif k == Z3_PARAMETER_SYMBOL:
result[i] = Z3_get_decl_symbol_parameter(self.ctx_ref(), self.ast, i)
elif k == Z3_PARAMETER_SORT:
result[i] = SortRef(Z3_get_decl_sort_parameter(self.ctx_ref(), self.ast, i), ctx)
elif k == Z3_PARAMETER_AST:
result[i] = ExprRef(Z3_get_decl_ast_parameter(self.ctx_ref(), self.ast, i), ctx)
elif k == Z3_PARAMETER_FUNC_DECL:
result[i] = FuncDeclRef(Z3_get_decl_func_decl_parameter(self.ctx_ref(), self.ast, i), ctx)
else:
assert(False)
return result
def __call__(self, *args):
"""Create a Z3 application expression using the function `self`, and the given arguments.
The arguments must be Z3 expressions. This method assumes that
the sorts of the elements in `args` match the sorts of the
domain. Limited coercion is supported. For example, if
args[0] is a Python integer, and the function expects a Z3
integer, then the argument is automatically converted into a
Z3 integer.
>>> f = Function('f', IntSort(), RealSort(), BoolSort())
>>> x = Int('x')
>>> y = Real('y')
>>> f(x, y)
f(x, y)
>>> f(x, x)
f(x, ToReal(x))
"""
args = _get_args(args)
num = len(args)
if __debug__:
_z3_assert(num == self.arity(), "Incorrect number of arguments to %s" % self)
_args = (Ast * num)()
saved = []
for i in range(num):
# self.domain(i).cast(args[i]) may create a new Z3 expression,
# then we must save in 'saved' to prevent it from being garbage collected.
tmp = self.domain(i).cast(args[i])
saved.append(tmp)
_args[i] = tmp.as_ast()
return _to_expr_ref(Z3_mk_app(self.ctx_ref(), self.ast, len(args), _args), self.ctx)
def is_func_decl(a):
"""Return `True` if `a` is a Z3 function declaration.
>>> f = Function('f', IntSort(), IntSort())
>>> is_func_decl(f)
True
>>> x = Real('x')
>>> is_func_decl(x)
False
"""
return isinstance(a, FuncDeclRef)
def Function(name, *sig):
"""Create a new Z3 uninterpreted function with the given sorts.
>>> f = Function('f', IntSort(), IntSort())
>>> f(f(0))
f(f(0))
"""
sig = _get_args(sig)
if __debug__:
_z3_assert(len(sig) > 0, "At least two arguments expected")
arity = len(sig) - 1
rng = sig[arity]
if __debug__:
_z3_assert(is_sort(rng), "Z3 sort expected")
dom = (Sort * arity)()
for i in range(arity):
if __debug__:
_z3_assert(is_sort(sig[i]), "Z3 sort expected")
dom[i] = sig[i].ast
ctx = rng.ctx
return FuncDeclRef(Z3_mk_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
def _to_func_decl_ref(a, ctx):
return FuncDeclRef(a, ctx)
def RecFunction(name, *sig):
"""Create a new Z3 recursive with the given sorts."""
sig = _get_args(sig)
if __debug__:
_z3_assert(len(sig) > 0, "At least two arguments expected")
arity = len(sig) - 1
rng = sig[arity]
if __debug__:
_z3_assert(is_sort(rng), "Z3 sort expected")
dom = (Sort * arity)()
for i in range(arity):
if __debug__:
_z3_assert(is_sort(sig[i]), "Z3 sort expected")
dom[i] = sig[i].ast
ctx = rng.ctx
return FuncDeclRef(Z3_mk_rec_func_decl(ctx.ref(), to_symbol(name, ctx), arity, dom, rng.ast), ctx)
def RecAddDefinition(f, args, body):
"""Set the body of a recursive function.
Recursive definitions are only unfolded during search.
>>> ctx = Context()
>>> fac = RecFunction('fac', IntSort(ctx), IntSort(ctx))
>>> n = Int('n', ctx)
>>> RecAddDefinition(fac, n, If(n == 0, 1, n*fac(n-1)))
>>> simplify(fac(5))
fac(5)
>>> s = Solver(ctx=ctx)
>>> s.add(fac(n) < 3)
>>> s.check()
sat
>>> s.model().eval(fac(5))
120
"""
if is_app(args):
args = [args]
ctx = body.ctx
args = _get_args(args)
n = len(args)
_args = (Ast * n)()
for i in range(n):
_args[i] = args[i].ast
Z3_add_rec_def(ctx.ref(), f.ast, n, _args, body.ast)
#########################################
#
# Expressions
#
#########################################
class ExprRef(AstRef):
"""Constraints, formulas and terms are expressions in Z3.
Expressions are ASTs. Every expression has a sort.
There are three main kinds of expressions:
function applications, quantifiers and bounded variables.
A constant is a function application with 0 arguments.
For quantifier free problems, all expressions are
function applications.
"""
def as_ast(self):
return self.ast
def get_id(self):
return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
def sort(self):
"""Return the sort of expression `self`.
>>> x = Int('x')
>>> (x + 1).sort()
Int
>>> y = Real('y')
>>> (x + y).sort()
Real
"""
return _sort(self.ctx, self.as_ast())
def sort_kind(self):
"""Shorthand for `self.sort().kind()`.
>>> a = Array('a', IntSort(), IntSort())
>>> a.sort_kind() == Z3_ARRAY_SORT
True
>>> a.sort_kind() == Z3_INT_SORT
False
"""
return self.sort().kind()
def __eq__(self, other):
"""Return a Z3 expression that represents the constraint `self == other`.
If `other` is `None`, then this method simply returns `False`.
>>> a = Int('a')
>>> b = Int('b')
>>> a == b
a == b
>>> a is None
False
"""
if other is None:
return False
a, b = _coerce_exprs(self, other)
return BoolRef(Z3_mk_eq(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __hash__(self):
""" Hash code. """
return AstRef.__hash__(self)
def __ne__(self, other):
"""Return a Z3 expression that represents the constraint `self != other`.
If `other` is `None`, then this method simply returns `True`.
>>> a = Int('a')
>>> b = Int('b')
>>> a != b
a != b
>>> a is not None
True
"""
if other is None:
return True
a, b = _coerce_exprs(self, other)
_args, sz = _to_ast_array((a, b))
return BoolRef(Z3_mk_distinct(self.ctx_ref(), 2, _args), self.ctx)
def params(self):
return self.decl().params()
def decl(self):
"""Return the Z3 function declaration associated with a Z3 application.
>>> f = Function('f', IntSort(), IntSort())
>>> a = Int('a')
>>> t = f(a)
>>> eq(t.decl(), f)
True
>>> (a + 1).decl()
+
"""
if __debug__:
_z3_assert(is_app(self), "Z3 application expected")
return FuncDeclRef(Z3_get_app_decl(self.ctx_ref(), self.as_ast()), self.ctx)
def num_args(self):
"""Return the number of arguments of a Z3 application.
>>> a = Int('a')
>>> b = Int('b')
>>> (a + b).num_args()
2
>>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
>>> t = f(a, b, 0)
>>> t.num_args()
3
"""
if __debug__:
_z3_assert(is_app(self), "Z3 application expected")
return int(Z3_get_app_num_args(self.ctx_ref(), self.as_ast()))
def arg(self, idx):
"""Return argument `idx` of the application `self`.
This method assumes that `self` is a function application with at least `idx+1` arguments.
>>> a = Int('a')
>>> b = Int('b')
>>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
>>> t = f(a, b, 0)
>>> t.arg(0)
a
>>> t.arg(1)
b
>>> t.arg(2)
0
"""
if __debug__:
_z3_assert(is_app(self), "Z3 application expected")
_z3_assert(idx < self.num_args(), "Invalid argument index")
return _to_expr_ref(Z3_get_app_arg(self.ctx_ref(), self.as_ast(), idx), self.ctx)
def children(self):
"""Return a list containing the children of the given expression
>>> a = Int('a')
>>> b = Int('b')
>>> f = Function('f', IntSort(), IntSort(), IntSort(), IntSort())
>>> t = f(a, b, 0)
>>> t.children()
[a, b, 0]
"""
if is_app(self):
return [self.arg(i) for i in range(self.num_args())]
else:
return []
def _to_expr_ref(a, ctx):
if isinstance(a, Pattern):
return PatternRef(a, ctx)
ctx_ref = ctx.ref()
k = Z3_get_ast_kind(ctx_ref, a)
if k == Z3_QUANTIFIER_AST:
return QuantifierRef(a, ctx)
sk = Z3_get_sort_kind(ctx_ref, Z3_get_sort(ctx_ref, a))
if sk == Z3_BOOL_SORT:
return BoolRef(a, ctx)
if sk == Z3_INT_SORT:
if k == Z3_NUMERAL_AST:
return IntNumRef(a, ctx)
return ArithRef(a, ctx)
if sk == Z3_REAL_SORT:
if k == Z3_NUMERAL_AST:
return RatNumRef(a, ctx)
if _is_algebraic(ctx, a):
return AlgebraicNumRef(a, ctx)
return ArithRef(a, ctx)
if sk == Z3_BV_SORT:
if k == Z3_NUMERAL_AST:
return BitVecNumRef(a, ctx)
else:
return BitVecRef(a, ctx)
if sk == Z3_ARRAY_SORT:
return ArrayRef(a, ctx)
if sk == Z3_DATATYPE_SORT:
return DatatypeRef(a, ctx)
if sk == Z3_FLOATING_POINT_SORT:
if k == Z3_APP_AST and _is_numeral(ctx, a):
return FPNumRef(a, ctx)
else:
return FPRef(a, ctx)
if sk == Z3_FINITE_DOMAIN_SORT:
if k == Z3_NUMERAL_AST:
return FiniteDomainNumRef(a, ctx)
else:
return FiniteDomainRef(a, ctx)
if sk == Z3_ROUNDING_MODE_SORT:
return FPRMRef(a, ctx)
if sk == Z3_SEQ_SORT:
return SeqRef(a, ctx)
if sk == Z3_RE_SORT:
return ReRef(a, ctx)
return ExprRef(a, ctx)
def _coerce_expr_merge(s, a):
if is_expr(a):
s1 = a.sort()
if s is None:
return s1
if s1.eq(s):
return s
elif s.subsort(s1):
return s1
elif s1.subsort(s):
return s
else:
if __debug__:
_z3_assert(s1.ctx == s.ctx, "context mismatch")
_z3_assert(False, "sort mismatch")
else:
return s
def _coerce_exprs(a, b, ctx=None):
if not is_expr(a) and not is_expr(b):
a = _py2expr(a, ctx)
b = _py2expr(b, ctx)
s = None
s = _coerce_expr_merge(s, a)
s = _coerce_expr_merge(s, b)
a = s.cast(a)
b = s.cast(b)
return (a, b)
def _reduce(f, l, a):
r = a
for e in l:
r = f(r, e)
return r
def _coerce_expr_list(alist, ctx=None):
has_expr = False
for a in alist:
if is_expr(a):
has_expr = True
break
if not has_expr:
alist = [ _py2expr(a, ctx) for a in alist ]
s = _reduce(_coerce_expr_merge, alist, None)
return [ s.cast(a) for a in alist ]
def is_expr(a):
"""Return `True` if `a` is a Z3 expression.
>>> a = Int('a')
>>> is_expr(a)
True
>>> is_expr(a + 1)
True
>>> is_expr(IntSort())
False
>>> is_expr(1)
False
>>> is_expr(IntVal(1))
True
>>> x = Int('x')
>>> is_expr(ForAll(x, x >= 0))
True
>>> is_expr(FPVal(1.0))
True
"""
return isinstance(a, ExprRef)
def is_app(a):
"""Return `True` if `a` is a Z3 function application.
Note that, constants are function applications with 0 arguments.
>>> a = Int('a')
>>> is_app(a)
True
>>> is_app(a + 1)
True
>>> is_app(IntSort())
False
>>> is_app(1)
False
>>> is_app(IntVal(1))
True
>>> x = Int('x')
>>> is_app(ForAll(x, x >= 0))
False
"""
if not isinstance(a, ExprRef):
return False
k = _ast_kind(a.ctx, a)
return k == Z3_NUMERAL_AST or k == Z3_APP_AST
def is_const(a):
"""Return `True` if `a` is Z3 constant/variable expression.
>>> a = Int('a')
>>> is_const(a)
True
>>> is_const(a + 1)
False
>>> is_const(1)
False
>>> is_const(IntVal(1))
True
>>> x = Int('x')
>>> is_const(ForAll(x, x >= 0))
False
"""
return is_app(a) and a.num_args() == 0
def is_var(a):
"""Return `True` if `a` is variable.
Z3 uses de-Bruijn indices for representing bound variables in
quantifiers.
>>> x = Int('x')
>>> is_var(x)
False
>>> is_const(x)
True
>>> f = Function('f', IntSort(), IntSort())
>>> # Z3 replaces x with bound variables when ForAll is executed.
>>> q = ForAll(x, f(x) == x)
>>> b = q.body()
>>> b
f(Var(0)) == Var(0)
>>> b.arg(1)
Var(0)
>>> is_var(b.arg(1))
True
"""
return is_expr(a) and _ast_kind(a.ctx, a) == Z3_VAR_AST
def get_var_index(a):
"""Return the de-Bruijn index of the Z3 bounded variable `a`.
>>> x = Int('x')
>>> y = Int('y')
>>> is_var(x)
False
>>> is_const(x)
True
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> # Z3 replaces x and y with bound variables when ForAll is executed.
>>> q = ForAll([x, y], f(x, y) == x + y)
>>> q.body()
f(Var(1), Var(0)) == Var(1) + Var(0)
>>> b = q.body()
>>> b.arg(0)
f(Var(1), Var(0))
>>> v1 = b.arg(0).arg(0)
>>> v2 = b.arg(0).arg(1)
>>> v1
Var(1)
>>> v2
Var(0)
>>> get_var_index(v1)
1
>>> get_var_index(v2)
0
"""
if __debug__:
_z3_assert(is_var(a), "Z3 bound variable expected")
return int(Z3_get_index_value(a.ctx.ref(), a.as_ast()))
def is_app_of(a, k):
"""Return `True` if `a` is an application of the given kind `k`.
>>> x = Int('x')
>>> n = x + 1
>>> is_app_of(n, Z3_OP_ADD)
True
>>> is_app_of(n, Z3_OP_MUL)
False
"""
return is_app(a) and a.decl().kind() == k
def If(a, b, c, ctx=None):
"""Create a Z3 if-then-else expression.
>>> x = Int('x')
>>> y = Int('y')
>>> max = If(x > y, x, y)
>>> max
If(x > y, x, y)
>>> simplify(max)
If(x <= y, y, x)
"""
if isinstance(a, Probe) or isinstance(b, Tactic) or isinstance(c, Tactic):
return Cond(a, b, c, ctx)
else:
ctx = _get_ctx(_ctx_from_ast_arg_list([a, b, c], ctx))
s = BoolSort(ctx)
a = s.cast(a)
b, c = _coerce_exprs(b, c, ctx)
if __debug__:
_z3_assert(a.ctx == b.ctx, "Context mismatch")
return _to_expr_ref(Z3_mk_ite(ctx.ref(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
def Distinct(*args):
"""Create a Z3 distinct expression.
>>> x = Int('x')
>>> y = Int('y')
>>> Distinct(x, y)
x != y
>>> z = Int('z')
>>> Distinct(x, y, z)
Distinct(x, y, z)
>>> simplify(Distinct(x, y, z))
Distinct(x, y, z)
>>> simplify(Distinct(x, y, z), blast_distinct=True)
And(Not(x == y), Not(x == z), Not(y == z))
"""
args = _get_args(args)
ctx = _ctx_from_ast_arg_list(args)
if __debug__:
_z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
args = _coerce_expr_list(args, ctx)
_args, sz = _to_ast_array(args)
return BoolRef(Z3_mk_distinct(ctx.ref(), sz, _args), ctx)
def _mk_bin(f, a, b):
args = (Ast * 2)()
if __debug__:
_z3_assert(a.ctx == b.ctx, "Context mismatch")
args[0] = a.as_ast()
args[1] = b.as_ast()
return f(a.ctx.ref(), 2, args)
def Const(name, sort):
"""Create a constant of the given sort.
>>> Const('x', IntSort())
x
"""
if __debug__:
_z3_assert(isinstance(sort, SortRef), "Z3 sort expected")
ctx = sort.ctx
return _to_expr_ref(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), sort.ast), ctx)
def Consts(names, sort):
"""Create a several constants of the given sort.
`names` is a string containing the names of all constants to be created.
Blank spaces separate the names of different constants.
>>> x, y, z = Consts('x y z', IntSort())
>>> x + y + z
x + y + z
"""
if isinstance(names, str):
names = names.split(" ")
return [Const(name, sort) for name in names]
def FreshConst(sort, prefix='c'):
"""Create a fresh constant of a specified sort"""
ctx = _get_ctx(sort.ctx)
return _to_expr_ref(Z3_mk_fresh_const(ctx.ref(), prefix, sort.ast), ctx)
def Var(idx, s):
"""Create a Z3 free variable. Free variables are used to create quantified formulas.
>>> Var(0, IntSort())
Var(0)
>>> eq(Var(0, IntSort()), Var(0, BoolSort()))
False
"""
if __debug__:
_z3_assert(is_sort(s), "Z3 sort expected")
return _to_expr_ref(Z3_mk_bound(s.ctx_ref(), idx, s.ast), s.ctx)
def RealVar(idx, ctx=None):
"""
Create a real free variable. Free variables are used to create quantified formulas.
They are also used to create polynomials.
>>> RealVar(0)
Var(0)
"""
return Var(idx, RealSort(ctx))
def RealVarVector(n, ctx=None):
"""
Create a list of Real free variables.
The variables have ids: 0, 1, ..., n-1
>>> x0, x1, x2, x3 = RealVarVector(4)
>>> x2
Var(2)
"""
return [ RealVar(i, ctx) for i in range(n) ]
#########################################
#
# Booleans
#
#########################################
class BoolSortRef(SortRef):
"""Boolean sort."""
def cast(self, val):
"""Try to cast `val` as a Boolean.
>>> x = BoolSort().cast(True)
>>> x
True
>>> is_expr(x)
True
>>> is_expr(True)
False
>>> x.sort()
Bool
"""
if isinstance(val, bool):
return BoolVal(val, self.ctx)
if __debug__:
if not is_expr(val):
_z3_assert(is_expr(val), "True, False or Z3 Boolean expression expected. Received %s" % val)
if not self.eq(val.sort()):
_z3_assert(self.eq(val.sort()), "Value cannot be converted into a Z3 Boolean value")
return val
def subsort(self, other):
return isinstance(other, ArithSortRef)
def is_int(self):
return True
def is_bool(self):
return True
class BoolRef(ExprRef):
"""All Boolean expressions are instances of this class."""
def sort(self):
return BoolSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
def __rmul__(self, other):
return self * other
def __mul__(self, other):
"""Create the Z3 expression `self * other`.
"""
if other == 1:
return self
if other == 0:
return 0
return If(self, other, 0)
def is_bool(a):
"""Return `True` if `a` is a Z3 Boolean expression.
>>> p = Bool('p')
>>> is_bool(p)
True
>>> q = Bool('q')
>>> is_bool(And(p, q))
True
>>> x = Real('x')
>>> is_bool(x)
False
>>> is_bool(x == 0)
True
"""
return isinstance(a, BoolRef)
def is_true(a):
"""Return `True` if `a` is the Z3 true expression.
>>> p = Bool('p')
>>> is_true(p)
False
>>> is_true(simplify(p == p))
True
>>> x = Real('x')
>>> is_true(x == 0)
False
>>> # True is a Python Boolean expression
>>> is_true(True)
False
"""
return is_app_of(a, Z3_OP_TRUE)
def is_false(a):
"""Return `True` if `a` is the Z3 false expression.
>>> p = Bool('p')
>>> is_false(p)
False
>>> is_false(False)
False
>>> is_false(BoolVal(False))
True
"""
return is_app_of(a, Z3_OP_FALSE)
def is_and(a):
"""Return `True` if `a` is a Z3 and expression.
>>> p, q = Bools('p q')
>>> is_and(And(p, q))
True
>>> is_and(Or(p, q))
False
"""
return is_app_of(a, Z3_OP_AND)
def is_or(a):
"""Return `True` if `a` is a Z3 or expression.
>>> p, q = Bools('p q')
>>> is_or(Or(p, q))
True
>>> is_or(And(p, q))
False
"""
return is_app_of(a, Z3_OP_OR)
def is_implies(a):
"""Return `True` if `a` is a Z3 implication expression.
>>> p, q = Bools('p q')
>>> is_implies(Implies(p, q))
True
>>> is_implies(And(p, q))
False
"""
return is_app_of(a, Z3_OP_IMPLIES)
def is_not(a):
"""Return `True` if `a` is a Z3 not expression.
>>> p = Bool('p')
>>> is_not(p)
False
>>> is_not(Not(p))
True
"""
return is_app_of(a, Z3_OP_NOT)
def is_eq(a):
"""Return `True` if `a` is a Z3 equality expression.
>>> x, y = Ints('x y')
>>> is_eq(x == y)
True
"""
return is_app_of(a, Z3_OP_EQ)
def is_distinct(a):
"""Return `True` if `a` is a Z3 distinct expression.
>>> x, y, z = Ints('x y z')
>>> is_distinct(x == y)
False
>>> is_distinct(Distinct(x, y, z))
True
"""
return is_app_of(a, Z3_OP_DISTINCT)
def BoolSort(ctx=None):
"""Return the Boolean Z3 sort. If `ctx=None`, then the global context is used.
>>> BoolSort()
Bool
>>> p = Const('p', BoolSort())
>>> is_bool(p)
True
>>> r = Function('r', IntSort(), IntSort(), BoolSort())
>>> r(0, 1)
r(0, 1)
>>> is_bool(r(0, 1))
True
"""
ctx = _get_ctx(ctx)
return BoolSortRef(Z3_mk_bool_sort(ctx.ref()), ctx)
def BoolVal(val, ctx=None):
"""Return the Boolean value `True` or `False`. If `ctx=None`, then the global context is used.
>>> BoolVal(True)
True
>>> is_true(BoolVal(True))
True
>>> is_true(True)
False
>>> is_false(BoolVal(False))
True
"""
ctx = _get_ctx(ctx)
if val == False:
return BoolRef(Z3_mk_false(ctx.ref()), ctx)
else:
return BoolRef(Z3_mk_true(ctx.ref()), ctx)
def Bool(name, ctx=None):
"""Return a Boolean constant named `name`. If `ctx=None`, then the global context is used.
>>> p = Bool('p')
>>> q = Bool('q')
>>> And(p, q)
And(p, q)
"""
ctx = _get_ctx(ctx)
return BoolRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), BoolSort(ctx).ast), ctx)
def Bools(names, ctx=None):
"""Return a tuple of Boolean constants.
`names` is a single string containing all names separated by blank spaces.
If `ctx=None`, then the global context is used.
>>> p, q, r = Bools('p q r')
>>> And(p, Or(q, r))
And(p, Or(q, r))
"""
ctx = _get_ctx(ctx)
if isinstance(names, str):
names = names.split(" ")
return [Bool(name, ctx) for name in names]
def BoolVector(prefix, sz, ctx=None):
"""Return a list of Boolean constants of size `sz`.
The constants are named using the given prefix.
If `ctx=None`, then the global context is used.
>>> P = BoolVector('p', 3)
>>> P
[p__0, p__1, p__2]
>>> And(P)
And(p__0, p__1, p__2)
"""
return [ Bool('%s__%s' % (prefix, i)) for i in range(sz) ]
def FreshBool(prefix='b', ctx=None):
"""Return a fresh Boolean constant in the given context using the given prefix.
If `ctx=None`, then the global context is used.
>>> b1 = FreshBool()
>>> b2 = FreshBool()
>>> eq(b1, b2)
False
"""
ctx = _get_ctx(ctx)
return BoolRef(Z3_mk_fresh_const(ctx.ref(), prefix, BoolSort(ctx).ast), ctx)
def Implies(a, b, ctx=None):
"""Create a Z3 implies expression.
>>> p, q = Bools('p q')
>>> Implies(p, q)
Implies(p, q)
>>> simplify(Implies(p, q))
Or(Not(p), q)
"""
ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
s = BoolSort(ctx)
a = s.cast(a)
b = s.cast(b)
return BoolRef(Z3_mk_implies(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
def Xor(a, b, ctx=None):
"""Create a Z3 Xor expression.
>>> p, q = Bools('p q')
>>> Xor(p, q)
Xor(p, q)
>>> simplify(Xor(p, q))
Not(p) == q
"""
ctx = _get_ctx(_ctx_from_ast_arg_list([a, b], ctx))
s = BoolSort(ctx)
a = s.cast(a)
b = s.cast(b)
return BoolRef(Z3_mk_xor(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
def Not(a, ctx=None):
"""Create a Z3 not expression or probe.
>>> p = Bool('p')
>>> Not(Not(p))
Not(Not(p))
>>> simplify(Not(Not(p)))
p
"""
ctx = _get_ctx(_ctx_from_ast_arg_list([a], ctx))
if is_probe(a):
# Not is also used to build probes
return Probe(Z3_probe_not(ctx.ref(), a.probe), ctx)
else:
s = BoolSort(ctx)
a = s.cast(a)
return BoolRef(Z3_mk_not(ctx.ref(), a.as_ast()), ctx)
def _has_probe(args):
"""Return `True` if one of the elements of the given collection is a Z3 probe."""
for arg in args:
if is_probe(arg):
return True
return False
def And(*args):
"""Create a Z3 and-expression or and-probe.
>>> p, q, r = Bools('p q r')
>>> And(p, q, r)
And(p, q, r)
>>> P = BoolVector('p', 5)
>>> And(P)
And(p__0, p__1, p__2, p__3, p__4)
"""
last_arg = None
if len(args) > 0:
last_arg = args[len(args)-1]
if isinstance(last_arg, Context):
ctx = args[len(args)-1]
args = args[:len(args)-1]
elif len(args) == 1 and isinstance(args[0], AstVector):
ctx = args[0].ctx
args = [a for a in args[0]]
else:
ctx = main_ctx()
args = _get_args(args)
ctx_args = _ctx_from_ast_arg_list(args, ctx)
if __debug__:
_z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
_z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
if _has_probe(args):
return _probe_and(args, ctx)
else:
args = _coerce_expr_list(args, ctx)
_args, sz = _to_ast_array(args)
return BoolRef(Z3_mk_and(ctx.ref(), sz, _args), ctx)
def Or(*args):
"""Create a Z3 or-expression or or-probe.
>>> p, q, r = Bools('p q r')
>>> Or(p, q, r)
Or(p, q, r)
>>> P = BoolVector('p', 5)
>>> Or(P)
Or(p__0, p__1, p__2, p__3, p__4)
"""
last_arg = None
if len(args) > 0:
last_arg = args[len(args)-1]
if isinstance(last_arg, Context):
ctx = args[len(args)-1]
args = args[:len(args)-1]
else:
ctx = main_ctx()
args = _get_args(args)
ctx_args = _ctx_from_ast_arg_list(args, ctx)
if __debug__:
_z3_assert(ctx_args is None or ctx_args == ctx, "context mismatch")
_z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression or probe")
if _has_probe(args):
return _probe_or(args, ctx)
else:
args = _coerce_expr_list(args, ctx)
_args, sz = _to_ast_array(args)
return BoolRef(Z3_mk_or(ctx.ref(), sz, _args), ctx)
#########################################
#
# Patterns
#
#########################################
class PatternRef(ExprRef):
"""Patterns are hints for quantifier instantiation.
"""
def as_ast(self):
return Z3_pattern_to_ast(self.ctx_ref(), self.ast)
def get_id(self):
return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
def is_pattern(a):
"""Return `True` if `a` is a Z3 pattern (hint for quantifier instantiation.
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> q = ForAll(x, f(x) == 0, patterns = [ f(x) ])
>>> q
ForAll(x, f(x) == 0)
>>> q.num_patterns()
1
>>> is_pattern(q.pattern(0))
True
>>> q.pattern(0)
f(Var(0))
"""
return isinstance(a, PatternRef)
def MultiPattern(*args):
"""Create a Z3 multi-pattern using the given expressions `*args`
>>> f = Function('f', IntSort(), IntSort())
>>> g = Function('g', IntSort(), IntSort())
>>> x = Int('x')
>>> q = ForAll(x, f(x) != g(x), patterns = [ MultiPattern(f(x), g(x)) ])
>>> q
ForAll(x, f(x) != g(x))
>>> q.num_patterns()
1
>>> is_pattern(q.pattern(0))
True
>>> q.pattern(0)
MultiPattern(f(Var(0)), g(Var(0)))
"""
if __debug__:
_z3_assert(len(args) > 0, "At least one argument expected")
_z3_assert(all([ is_expr(a) for a in args ]), "Z3 expressions expected")
ctx = args[0].ctx
args, sz = _to_ast_array(args)
return PatternRef(Z3_mk_pattern(ctx.ref(), sz, args), ctx)
def _to_pattern(arg):
if is_pattern(arg):
return arg
else:
return MultiPattern(arg)
#########################################
#
# Quantifiers
#
#########################################
class QuantifierRef(BoolRef):
"""Universally and Existentially quantified formulas."""
def as_ast(self):
return self.ast
def get_id(self):
return Z3_get_ast_id(self.ctx_ref(), self.as_ast())
def sort(self):
"""Return the Boolean sort or sort of Lambda."""
if self.is_lambda():
return _sort(self.ctx, self.as_ast())
return BoolSort(self.ctx)
def is_forall(self):
"""Return `True` if `self` is a universal quantifier.
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> q = ForAll(x, f(x) == 0)
>>> q.is_forall()
True
>>> q = Exists(x, f(x) != 0)
>>> q.is_forall()
False
"""
return Z3_is_quantifier_forall(self.ctx_ref(), self.ast)
def is_exists(self):
"""Return `True` if `self` is an existential quantifier.
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> q = ForAll(x, f(x) == 0)
>>> q.is_exists()
False
>>> q = Exists(x, f(x) != 0)
>>> q.is_exists()
True
"""
return Z3_is_quantifier_exists(self.ctx_ref(), self.ast)
def is_lambda(self):
"""Return `True` if `self` is a lambda expression.
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> q = Lambda(x, f(x))
>>> q.is_lambda()
True
>>> q = Exists(x, f(x) != 0)
>>> q.is_lambda()
False
"""
return Z3_is_lambda(self.ctx_ref(), self.ast)
def weight(self):
"""Return the weight annotation of `self`.
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> q = ForAll(x, f(x) == 0)
>>> q.weight()
1
>>> q = ForAll(x, f(x) == 0, weight=10)
>>> q.weight()
10
"""
return int(Z3_get_quantifier_weight(self.ctx_ref(), self.ast))
def num_patterns(self):
"""Return the number of patterns (i.e., quantifier instantiation hints) in `self`.
>>> f = Function('f', IntSort(), IntSort())
>>> g = Function('g', IntSort(), IntSort())
>>> x = Int('x')
>>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
>>> q.num_patterns()
2
"""
return int(Z3_get_quantifier_num_patterns(self.ctx_ref(), self.ast))
def pattern(self, idx):
"""Return a pattern (i.e., quantifier instantiation hints) in `self`.
>>> f = Function('f', IntSort(), IntSort())
>>> g = Function('g', IntSort(), IntSort())
>>> x = Int('x')
>>> q = ForAll(x, f(x) != g(x), patterns = [ f(x), g(x) ])
>>> q.num_patterns()
2
>>> q.pattern(0)
f(Var(0))
>>> q.pattern(1)
g(Var(0))
"""
if __debug__:
_z3_assert(idx < self.num_patterns(), "Invalid pattern idx")
return PatternRef(Z3_get_quantifier_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
def num_no_patterns(self):
"""Return the number of no-patterns."""
return Z3_get_quantifier_num_no_patterns(self.ctx_ref(), self.ast)
def no_pattern(self, idx):
"""Return a no-pattern."""
if __debug__:
_z3_assert(idx < self.num_no_patterns(), "Invalid no-pattern idx")
return _to_expr_ref(Z3_get_quantifier_no_pattern_ast(self.ctx_ref(), self.ast, idx), self.ctx)
def body(self):
"""Return the expression being quantified.
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> q = ForAll(x, f(x) == 0)
>>> q.body()
f(Var(0)) == 0
"""
return _to_expr_ref(Z3_get_quantifier_body(self.ctx_ref(), self.ast), self.ctx)
def num_vars(self):
"""Return the number of variables bounded by this quantifier.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> x = Int('x')
>>> y = Int('y')
>>> q = ForAll([x, y], f(x, y) >= x)
>>> q.num_vars()
2
"""
return int(Z3_get_quantifier_num_bound(self.ctx_ref(), self.ast))
def var_name(self, idx):
"""Return a string representing a name used when displaying the quantifier.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> x = Int('x')
>>> y = Int('y')
>>> q = ForAll([x, y], f(x, y) >= x)
>>> q.var_name(0)
'x'
>>> q.var_name(1)
'y'
"""
if __debug__:
_z3_assert(idx < self.num_vars(), "Invalid variable idx")
return _symbol2py(self.ctx, Z3_get_quantifier_bound_name(self.ctx_ref(), self.ast, idx))
def var_sort(self, idx):
"""Return the sort of a bound variable.
>>> f = Function('f', IntSort(), RealSort(), IntSort())
>>> x = Int('x')
>>> y = Real('y')
>>> q = ForAll([x, y], f(x, y) >= x)
>>> q.var_sort(0)
Int
>>> q.var_sort(1)
Real
"""
if __debug__:
_z3_assert(idx < self.num_vars(), "Invalid variable idx")
return _to_sort_ref(Z3_get_quantifier_bound_sort(self.ctx_ref(), self.ast, idx), self.ctx)
def children(self):
"""Return a list containing a single element self.body()
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> q = ForAll(x, f(x) == 0)
>>> q.children()
[f(Var(0)) == 0]
"""
return [ self.body() ]
def is_quantifier(a):
"""Return `True` if `a` is a Z3 quantifier.
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> q = ForAll(x, f(x) == 0)
>>> is_quantifier(q)
True
>>> is_quantifier(f(x))
False
"""
return isinstance(a, QuantifierRef)
def _mk_quantifier(is_forall, vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
if __debug__:
_z3_assert(is_bool(body) or is_app(vs) or (len(vs) > 0 and is_app(vs[0])), "Z3 expression expected")
_z3_assert(is_const(vs) or (len(vs) > 0 and all([ is_const(v) for v in vs])), "Invalid bounded variable(s)")
_z3_assert(all([is_pattern(a) or is_expr(a) for a in patterns]), "Z3 patterns expected")
_z3_assert(all([is_expr(p) for p in no_patterns]), "no patterns are Z3 expressions")
if is_app(vs):
ctx = vs.ctx
vs = [vs]
else:
ctx = vs[0].ctx
if not is_expr(body):
body = BoolVal(body, ctx)
num_vars = len(vs)
if num_vars == 0:
return body
_vs = (Ast * num_vars)()
for i in range(num_vars):
## TODO: Check if is constant
_vs[i] = vs[i].as_ast()
patterns = [ _to_pattern(p) for p in patterns ]
num_pats = len(patterns)
_pats = (Pattern * num_pats)()
for i in range(num_pats):
_pats[i] = patterns[i].ast
_no_pats, num_no_pats = _to_ast_array(no_patterns)
qid = to_symbol(qid, ctx)
skid = to_symbol(skid, ctx)
return QuantifierRef(Z3_mk_quantifier_const_ex(ctx.ref(), is_forall, weight, qid, skid,
num_vars, _vs,
num_pats, _pats,
num_no_pats, _no_pats,
body.as_ast()), ctx)
def ForAll(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
"""Create a Z3 forall formula.
The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> x = Int('x')
>>> y = Int('y')
>>> ForAll([x, y], f(x, y) >= x)
ForAll([x, y], f(x, y) >= x)
>>> ForAll([x, y], f(x, y) >= x, patterns=[ f(x, y) ])
ForAll([x, y], f(x, y) >= x)
>>> ForAll([x, y], f(x, y) >= x, weight=10)
ForAll([x, y], f(x, y) >= x)
"""
return _mk_quantifier(True, vs, body, weight, qid, skid, patterns, no_patterns)
def Exists(vs, body, weight=1, qid="", skid="", patterns=[], no_patterns=[]):
"""Create a Z3 exists formula.
The parameters `weight`, `qif`, `skid`, `patterns` and `no_patterns` are optional annotations.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> x = Int('x')
>>> y = Int('y')
>>> q = Exists([x, y], f(x, y) >= x, skid="foo")
>>> q
Exists([x, y], f(x, y) >= x)
>>> is_quantifier(q)
True
>>> r = Tactic('nnf')(q).as_expr()
>>> is_quantifier(r)
False
"""
return _mk_quantifier(False, vs, body, weight, qid, skid, patterns, no_patterns)
def Lambda(vs, body):
"""Create a Z3 lambda expression.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> mem0 = Array('mem0', IntSort(), IntSort())
>>> lo, hi, e, i = Ints('lo hi e i')
>>> mem1 = Lambda([i], If(And(lo <= i, i <= hi), e, mem0[i]))
>>> mem1
Lambda(i, If(And(lo <= i, i <= hi), e, mem0[i]))
"""
ctx = body.ctx
if is_app(vs):
vs = [vs]
num_vars = len(vs)
_vs = (Ast * num_vars)()
for i in range(num_vars):
## TODO: Check if is constant
_vs[i] = vs[i].as_ast()
return QuantifierRef(Z3_mk_lambda_const(ctx.ref(), num_vars, _vs, body.as_ast()), ctx)
#########################################
#
# Arithmetic
#
#########################################
class ArithSortRef(SortRef):
"""Real and Integer sorts."""
def is_real(self):
"""Return `True` if `self` is of the sort Real.
>>> x = Real('x')
>>> x.is_real()
True
>>> (x + 1).is_real()
True
>>> x = Int('x')
>>> x.is_real()
False
"""
return self.kind() == Z3_REAL_SORT
def is_int(self):
"""Return `True` if `self` is of the sort Integer.
>>> x = Int('x')
>>> x.is_int()
True
>>> (x + 1).is_int()
True
>>> x = Real('x')
>>> x.is_int()
False
"""
return self.kind() == Z3_INT_SORT
def subsort(self, other):
"""Return `True` if `self` is a subsort of `other`."""
return self.is_int() and is_arith_sort(other) and other.is_real()
def cast(self, val):
"""Try to cast `val` as an Integer or Real.
>>> IntSort().cast(10)
10
>>> is_int(IntSort().cast(10))
True
>>> is_int(10)
False
>>> RealSort().cast(10)
10
>>> is_real(RealSort().cast(10))
True
"""
if is_expr(val):
if __debug__:
_z3_assert(self.ctx == val.ctx, "Context mismatch")
val_s = val.sort()
if self.eq(val_s):
return val
if val_s.is_int() and self.is_real():
return ToReal(val)
if val_s.is_bool() and self.is_int():
return If(val, 1, 0)
if val_s.is_bool() and self.is_real():
return ToReal(If(val, 1, 0))
if __debug__:
_z3_assert(False, "Z3 Integer/Real expression expected" )
else:
if self.is_int():
return IntVal(val, self.ctx)
if self.is_real():
return RealVal(val, self.ctx)
if __debug__:
_z3_assert(False, "int, long, float, string (numeral), or Z3 Integer/Real expression expected. Got %s" % self)
def is_arith_sort(s):
"""Return `True` if s is an arithmetical sort (type).
>>> is_arith_sort(IntSort())
True
>>> is_arith_sort(RealSort())
True
>>> is_arith_sort(BoolSort())
False
>>> n = Int('x') + 1
>>> is_arith_sort(n.sort())
True
"""
return isinstance(s, ArithSortRef)
class ArithRef(ExprRef):
"""Integer and Real expressions."""
def sort(self):
"""Return the sort (type) of the arithmetical expression `self`.
>>> Int('x').sort()
Int
>>> (Real('x') + 1).sort()
Real
"""
return ArithSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
def is_int(self):
"""Return `True` if `self` is an integer expression.
>>> x = Int('x')
>>> x.is_int()
True
>>> (x + 1).is_int()
True
>>> y = Real('y')
>>> (x + y).is_int()
False
"""
return self.sort().is_int()
def is_real(self):
"""Return `True` if `self` is an real expression.
>>> x = Real('x')
>>> x.is_real()
True
>>> (x + 1).is_real()
True
"""
return self.sort().is_real()
def __add__(self, other):
"""Create the Z3 expression `self + other`.
>>> x = Int('x')
>>> y = Int('y')
>>> x + y
x + y
>>> (x + y).sort()
Int
"""
a, b = _coerce_exprs(self, other)
return ArithRef(_mk_bin(Z3_mk_add, a, b), self.ctx)
def __radd__(self, other):
"""Create the Z3 expression `other + self`.
>>> x = Int('x')
>>> 10 + x
10 + x
"""
a, b = _coerce_exprs(self, other)
return ArithRef(_mk_bin(Z3_mk_add, b, a), self.ctx)
def __mul__(self, other):
"""Create the Z3 expression `self * other`.
>>> x = Real('x')
>>> y = Real('y')
>>> x * y
x*y
>>> (x * y).sort()
Real
"""
if isinstance(other, BoolRef):
return If(other, self, 0)
a, b = _coerce_exprs(self, other)
return ArithRef(_mk_bin(Z3_mk_mul, a, b), self.ctx)
def __rmul__(self, other):
"""Create the Z3 expression `other * self`.
>>> x = Real('x')
>>> 10 * x
10*x
"""
a, b = _coerce_exprs(self, other)
return ArithRef(_mk_bin(Z3_mk_mul, b, a), self.ctx)
def __sub__(self, other):
"""Create the Z3 expression `self - other`.
>>> x = Int('x')
>>> y = Int('y')
>>> x - y
x - y
>>> (x - y).sort()
Int
"""
a, b = _coerce_exprs(self, other)
return ArithRef(_mk_bin(Z3_mk_sub, a, b), self.ctx)
def __rsub__(self, other):
"""Create the Z3 expression `other - self`.
>>> x = Int('x')
>>> 10 - x
10 - x
"""
a, b = _coerce_exprs(self, other)
return ArithRef(_mk_bin(Z3_mk_sub, b, a), self.ctx)
def __pow__(self, other):
"""Create the Z3 expression `self**other` (** is the power operator).
>>> x = Real('x')
>>> x**3
x**3
>>> (x**3).sort()
Real
>>> simplify(IntVal(2)**8)
256
"""
a, b = _coerce_exprs(self, other)
return ArithRef(Z3_mk_power(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __rpow__(self, other):
"""Create the Z3 expression `other**self` (** is the power operator).
>>> x = Real('x')
>>> 2**x
2**x
>>> (2**x).sort()
Real
>>> simplify(2**IntVal(8))
256
"""
a, b = _coerce_exprs(self, other)
return ArithRef(Z3_mk_power(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
def __div__(self, other):
"""Create the Z3 expression `other/self`.
>>> x = Int('x')
>>> y = Int('y')
>>> x/y
x/y
>>> (x/y).sort()
Int
>>> (x/y).sexpr()
'(div x y)'
>>> x = Real('x')
>>> y = Real('y')
>>> x/y
x/y
>>> (x/y).sort()
Real
>>> (x/y).sexpr()
'(/ x y)'
"""
a, b = _coerce_exprs(self, other)
return ArithRef(Z3_mk_div(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __truediv__(self, other):
"""Create the Z3 expression `other/self`."""
return self.__div__(other)
def __rdiv__(self, other):
"""Create the Z3 expression `other/self`.
>>> x = Int('x')
>>> 10/x
10/x
>>> (10/x).sexpr()
'(div 10 x)'
>>> x = Real('x')
>>> 10/x
10/x
>>> (10/x).sexpr()
'(/ 10.0 x)'
"""
a, b = _coerce_exprs(self, other)
return ArithRef(Z3_mk_div(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
def __rtruediv__(self, other):
"""Create the Z3 expression `other/self`."""
return self.__rdiv__(other)
def __mod__(self, other):
"""Create the Z3 expression `other%self`.
>>> x = Int('x')
>>> y = Int('y')
>>> x % y
x%y
>>> simplify(IntVal(10) % IntVal(3))
1
"""
a, b = _coerce_exprs(self, other)
if __debug__:
_z3_assert(a.is_int(), "Z3 integer expression expected")
return ArithRef(Z3_mk_mod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __rmod__(self, other):
"""Create the Z3 expression `other%self`.
>>> x = Int('x')
>>> 10 % x
10%x
"""
a, b = _coerce_exprs(self, other)
if __debug__:
_z3_assert(a.is_int(), "Z3 integer expression expected")
return ArithRef(Z3_mk_mod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
def __neg__(self):
"""Return an expression representing `-self`.
>>> x = Int('x')
>>> -x
-x
>>> simplify(-(-x))
x
"""
return ArithRef(Z3_mk_unary_minus(self.ctx_ref(), self.as_ast()), self.ctx)
def __pos__(self):
"""Return `self`.
>>> x = Int('x')
>>> +x
x
"""
return self
def __le__(self, other):
"""Create the Z3 expression `other <= self`.
>>> x, y = Ints('x y')
>>> x <= y
x <= y
>>> y = Real('y')
>>> x <= y
ToReal(x) <= y
"""
a, b = _coerce_exprs(self, other)
return BoolRef(Z3_mk_le(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __lt__(self, other):
"""Create the Z3 expression `other < self`.
>>> x, y = Ints('x y')
>>> x < y
x < y
>>> y = Real('y')
>>> x < y
ToReal(x) < y
"""
a, b = _coerce_exprs(self, other)
return BoolRef(Z3_mk_lt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __gt__(self, other):
"""Create the Z3 expression `other > self`.
>>> x, y = Ints('x y')
>>> x > y
x > y
>>> y = Real('y')
>>> x > y
ToReal(x) > y
"""
a, b = _coerce_exprs(self, other)
return BoolRef(Z3_mk_gt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __ge__(self, other):
"""Create the Z3 expression `other >= self`.
>>> x, y = Ints('x y')
>>> x >= y
x >= y
>>> y = Real('y')
>>> x >= y
ToReal(x) >= y
"""
a, b = _coerce_exprs(self, other)
return BoolRef(Z3_mk_ge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def is_arith(a):
"""Return `True` if `a` is an arithmetical expression.
>>> x = Int('x')
>>> is_arith(x)
True
>>> is_arith(x + 1)
True
>>> is_arith(1)
False
>>> is_arith(IntVal(1))
True
>>> y = Real('y')
>>> is_arith(y)
True
>>> is_arith(y + 1)
True
"""
return isinstance(a, ArithRef)
def is_int(a):
"""Return `True` if `a` is an integer expression.
>>> x = Int('x')
>>> is_int(x + 1)
True
>>> is_int(1)
False
>>> is_int(IntVal(1))
True
>>> y = Real('y')
>>> is_int(y)
False
>>> is_int(y + 1)
False
"""
return is_arith(a) and a.is_int()
def is_real(a):
"""Return `True` if `a` is a real expression.
>>> x = Int('x')
>>> is_real(x + 1)
False
>>> y = Real('y')
>>> is_real(y)
True
>>> is_real(y + 1)
True
>>> is_real(1)
False
>>> is_real(RealVal(1))
True
"""
return is_arith(a) and a.is_real()
def _is_numeral(ctx, a):
return Z3_is_numeral_ast(ctx.ref(), a)
def _is_algebraic(ctx, a):
return Z3_is_algebraic_number(ctx.ref(), a)
def is_int_value(a):
"""Return `True` if `a` is an integer value of sort Int.
>>> is_int_value(IntVal(1))
True
>>> is_int_value(1)
False
>>> is_int_value(Int('x'))
False
>>> n = Int('x') + 1
>>> n
x + 1
>>> n.arg(1)
1
>>> is_int_value(n.arg(1))
True
>>> is_int_value(RealVal("1/3"))
False
>>> is_int_value(RealVal(1))
False
"""
return is_arith(a) and a.is_int() and _is_numeral(a.ctx, a.as_ast())
def is_rational_value(a):
"""Return `True` if `a` is rational value of sort Real.
>>> is_rational_value(RealVal(1))
True
>>> is_rational_value(RealVal("3/5"))
True
>>> is_rational_value(IntVal(1))
False
>>> is_rational_value(1)
False
>>> n = Real('x') + 1
>>> n.arg(1)
1
>>> is_rational_value(n.arg(1))
True
>>> is_rational_value(Real('x'))
False
"""
return is_arith(a) and a.is_real() and _is_numeral(a.ctx, a.as_ast())
def is_algebraic_value(a):
"""Return `True` if `a` is an algebraic value of sort Real.
>>> is_algebraic_value(RealVal("3/5"))
False
>>> n = simplify(Sqrt(2))
>>> n
1.4142135623?
>>> is_algebraic_value(n)
True
"""
return is_arith(a) and a.is_real() and _is_algebraic(a.ctx, a.as_ast())
def is_add(a):
"""Return `True` if `a` is an expression of the form b + c.
>>> x, y = Ints('x y')
>>> is_add(x + y)
True
>>> is_add(x - y)
False
"""
return is_app_of(a, Z3_OP_ADD)
def is_mul(a):
"""Return `True` if `a` is an expression of the form b * c.
>>> x, y = Ints('x y')
>>> is_mul(x * y)
True
>>> is_mul(x - y)
False
"""
return is_app_of(a, Z3_OP_MUL)
def is_sub(a):
"""Return `True` if `a` is an expression of the form b - c.
>>> x, y = Ints('x y')
>>> is_sub(x - y)
True
>>> is_sub(x + y)
False
"""
return is_app_of(a, Z3_OP_SUB)
def is_div(a):
"""Return `True` if `a` is an expression of the form b / c.
>>> x, y = Reals('x y')
>>> is_div(x / y)
True
>>> is_div(x + y)
False
>>> x, y = Ints('x y')
>>> is_div(x / y)
False
>>> is_idiv(x / y)
True
"""
return is_app_of(a, Z3_OP_DIV)
def is_idiv(a):
"""Return `True` if `a` is an expression of the form b div c.
>>> x, y = Ints('x y')
>>> is_idiv(x / y)
True
>>> is_idiv(x + y)
False
"""
return is_app_of(a, Z3_OP_IDIV)
def is_mod(a):
"""Return `True` if `a` is an expression of the form b % c.
>>> x, y = Ints('x y')
>>> is_mod(x % y)
True
>>> is_mod(x + y)
False
"""
return is_app_of(a, Z3_OP_MOD)
def is_le(a):
"""Return `True` if `a` is an expression of the form b <= c.
>>> x, y = Ints('x y')
>>> is_le(x <= y)
True
>>> is_le(x < y)
False
"""
return is_app_of(a, Z3_OP_LE)
def is_lt(a):
"""Return `True` if `a` is an expression of the form b < c.
>>> x, y = Ints('x y')
>>> is_lt(x < y)
True
>>> is_lt(x == y)
False
"""
return is_app_of(a, Z3_OP_LT)
def is_ge(a):
"""Return `True` if `a` is an expression of the form b >= c.
>>> x, y = Ints('x y')
>>> is_ge(x >= y)
True
>>> is_ge(x == y)
False
"""
return is_app_of(a, Z3_OP_GE)
def is_gt(a):
"""Return `True` if `a` is an expression of the form b > c.
>>> x, y = Ints('x y')
>>> is_gt(x > y)
True
>>> is_gt(x == y)
False
"""
return is_app_of(a, Z3_OP_GT)
def is_is_int(a):
"""Return `True` if `a` is an expression of the form IsInt(b).
>>> x = Real('x')
>>> is_is_int(IsInt(x))
True
>>> is_is_int(x)
False
"""
return is_app_of(a, Z3_OP_IS_INT)
def is_to_real(a):
"""Return `True` if `a` is an expression of the form ToReal(b).
>>> x = Int('x')
>>> n = ToReal(x)
>>> n
ToReal(x)
>>> is_to_real(n)
True
>>> is_to_real(x)
False
"""
return is_app_of(a, Z3_OP_TO_REAL)
def is_to_int(a):
"""Return `True` if `a` is an expression of the form ToInt(b).
>>> x = Real('x')
>>> n = ToInt(x)
>>> n
ToInt(x)
>>> is_to_int(n)
True
>>> is_to_int(x)
False
"""
return is_app_of(a, Z3_OP_TO_INT)
class IntNumRef(ArithRef):
"""Integer values."""
def as_long(self):
"""Return a Z3 integer numeral as a Python long (bignum) numeral.
>>> v = IntVal(1)
>>> v + 1
1 + 1
>>> v.as_long() + 1
2
"""
if __debug__:
_z3_assert(self.is_int(), "Integer value expected")
return int(self.as_string())
def as_string(self):
"""Return a Z3 integer numeral as a Python string.
>>> v = IntVal(100)
>>> v.as_string()
'100'
"""
return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
class RatNumRef(ArithRef):
"""Rational values."""
def numerator(self):
""" Return the numerator of a Z3 rational numeral.
>>> is_rational_value(RealVal("3/5"))
True
>>> n = RealVal("3/5")
>>> n.numerator()
3
>>> is_rational_value(Q(3,5))
True
>>> Q(3,5).numerator()
3
"""
return IntNumRef(Z3_get_numerator(self.ctx_ref(), self.as_ast()), self.ctx)
def denominator(self):
""" Return the denominator of a Z3 rational numeral.
>>> is_rational_value(Q(3,5))
True
>>> n = Q(3,5)
>>> n.denominator()
5
"""
return IntNumRef(Z3_get_denominator(self.ctx_ref(), self.as_ast()), self.ctx)
def numerator_as_long(self):
""" Return the numerator as a Python long.
>>> v = RealVal(10000000000)
>>> v
10000000000
>>> v + 1
10000000000 + 1
>>> v.numerator_as_long() + 1 == 10000000001
True
"""
return self.numerator().as_long()
def denominator_as_long(self):
""" Return the denominator as a Python long.
>>> v = RealVal("1/3")
>>> v
1/3
>>> v.denominator_as_long()
3
"""
return self.denominator().as_long()
def is_int(self):
return False
def is_real(self):
return True
def is_int_value(self):
return self.denominator().is_int() and self.denominator_as_long() == 1
def as_long(self):
_z3_assert(self.is_int(), "Expected integer fraction")
return self.numerator_as_long()
def as_decimal(self, prec):
""" Return a Z3 rational value as a string in decimal notation using at most `prec` decimal places.
>>> v = RealVal("1/5")
>>> v.as_decimal(3)
'0.2'
>>> v = RealVal("1/3")
>>> v.as_decimal(3)
'0.333?'
"""
return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
def as_string(self):
"""Return a Z3 rational numeral as a Python string.
>>> v = Q(3,6)
>>> v.as_string()
'1/2'
"""
return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
def as_fraction(self):
"""Return a Z3 rational as a Python Fraction object.
>>> v = RealVal("1/5")
>>> v.as_fraction()
Fraction(1, 5)
"""
return Fraction(self.numerator_as_long(), self.denominator_as_long())
class AlgebraicNumRef(ArithRef):
"""Algebraic irrational values."""
def approx(self, precision=10):
"""Return a Z3 rational number that approximates the algebraic number `self`.
The result `r` is such that |r - self| <= 1/10^precision
>>> x = simplify(Sqrt(2))
>>> x.approx(20)
6838717160008073720548335/4835703278458516698824704
>>> x.approx(5)
2965821/2097152
"""
return RatNumRef(Z3_get_algebraic_number_upper(self.ctx_ref(), self.as_ast(), precision), self.ctx)
def as_decimal(self, prec):
"""Return a string representation of the algebraic number `self` in decimal notation using `prec` decimal places
>>> x = simplify(Sqrt(2))
>>> x.as_decimal(10)
'1.4142135623?'
>>> x.as_decimal(20)
'1.41421356237309504880?'
"""
return Z3_get_numeral_decimal_string(self.ctx_ref(), self.as_ast(), prec)
def _py2expr(a, ctx=None):
if isinstance(a, bool):
return BoolVal(a, ctx)
if _is_int(a):
return IntVal(a, ctx)
if isinstance(a, float):
return RealVal(a, ctx)
if is_expr(a):
return a
if __debug__:
_z3_assert(False, "Python bool, int, long or float expected")
def IntSort(ctx=None):
"""Return the integer sort in the given context. If `ctx=None`, then the global context is used.
>>> IntSort()
Int
>>> x = Const('x', IntSort())
>>> is_int(x)
True
>>> x.sort() == IntSort()
True
>>> x.sort() == BoolSort()
False
"""
ctx = _get_ctx(ctx)
return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
def RealSort(ctx=None):
"""Return the real sort in the given context. If `ctx=None`, then the global context is used.
>>> RealSort()
Real
>>> x = Const('x', RealSort())
>>> is_real(x)
True
>>> is_int(x)
False
>>> x.sort() == RealSort()
True
"""
ctx = _get_ctx(ctx)
return ArithSortRef(Z3_mk_real_sort(ctx.ref()), ctx)
def _to_int_str(val):
if isinstance(val, float):
return str(int(val))
elif isinstance(val, bool):
if val:
return "1"
else:
return "0"
elif _is_int(val):
return str(val)
elif isinstance(val, str):
return val
if __debug__:
_z3_assert(False, "Python value cannot be used as a Z3 integer")
def IntVal(val, ctx=None):
"""Return a Z3 integer value. If `ctx=None`, then the global context is used.
>>> IntVal(1)
1
>>> IntVal("100")
100
"""
ctx = _get_ctx(ctx)
return IntNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), IntSort(ctx).ast), ctx)
def RealVal(val, ctx=None):
"""Return a Z3 real value.
`val` may be a Python int, long, float or string representing a number in decimal or rational notation.
If `ctx=None`, then the global context is used.
>>> RealVal(1)
1
>>> RealVal(1).sort()
Real
>>> RealVal("3/5")
3/5
>>> RealVal("1.5")
3/2
"""
ctx = _get_ctx(ctx)
return RatNumRef(Z3_mk_numeral(ctx.ref(), str(val), RealSort(ctx).ast), ctx)
def RatVal(a, b, ctx=None):
"""Return a Z3 rational a/b.
If `ctx=None`, then the global context is used.
>>> RatVal(3,5)
3/5
>>> RatVal(3,5).sort()
Real
"""
if __debug__:
_z3_assert(_is_int(a) or isinstance(a, str), "First argument cannot be converted into an integer")
_z3_assert(_is_int(b) or isinstance(b, str), "Second argument cannot be converted into an integer")
return simplify(RealVal(a, ctx)/RealVal(b, ctx))
def Q(a, b, ctx=None):
"""Return a Z3 rational a/b.
If `ctx=None`, then the global context is used.
>>> Q(3,5)
3/5
>>> Q(3,5).sort()
Real
"""
return simplify(RatVal(a, b))
def Int(name, ctx=None):
"""Return an integer constant named `name`. If `ctx=None`, then the global context is used.
>>> x = Int('x')
>>> is_int(x)
True
>>> is_int(x + 1)
True
"""
ctx = _get_ctx(ctx)
return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), IntSort(ctx).ast), ctx)
def Ints(names, ctx=None):
"""Return a tuple of Integer constants.
>>> x, y, z = Ints('x y z')
>>> Sum(x, y, z)
x + y + z
"""
ctx = _get_ctx(ctx)
if isinstance(names, str):
names = names.split(" ")
return [Int(name, ctx) for name in names]
def IntVector(prefix, sz, ctx=None):
"""Return a list of integer constants of size `sz`.
>>> X = IntVector('x', 3)
>>> X
[x__0, x__1, x__2]
>>> Sum(X)
x__0 + x__1 + x__2
"""
return [ Int('%s__%s' % (prefix, i)) for i in range(sz) ]
def FreshInt(prefix='x', ctx=None):
"""Return a fresh integer constant in the given context using the given prefix.
>>> x = FreshInt()
>>> y = FreshInt()
>>> eq(x, y)
False
>>> x.sort()
Int
"""
ctx = _get_ctx(ctx)
return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, IntSort(ctx).ast), ctx)
def Real(name, ctx=None):
"""Return a real constant named `name`. If `ctx=None`, then the global context is used.
>>> x = Real('x')
>>> is_real(x)
True
>>> is_real(x + 1)
True
"""
ctx = _get_ctx(ctx)
return ArithRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), RealSort(ctx).ast), ctx)
def Reals(names, ctx=None):
"""Return a tuple of real constants.
>>> x, y, z = Reals('x y z')
>>> Sum(x, y, z)
x + y + z
>>> Sum(x, y, z).sort()
Real
"""
ctx = _get_ctx(ctx)
if isinstance(names, str):
names = names.split(" ")
return [Real(name, ctx) for name in names]
def RealVector(prefix, sz, ctx=None):
"""Return a list of real constants of size `sz`.
>>> X = RealVector('x', 3)
>>> X
[x__0, x__1, x__2]
>>> Sum(X)
x__0 + x__1 + x__2
>>> Sum(X).sort()
Real
"""
return [ Real('%s__%s' % (prefix, i)) for i in range(sz) ]
def FreshReal(prefix='b', ctx=None):
"""Return a fresh real constant in the given context using the given prefix.
>>> x = FreshReal()
>>> y = FreshReal()
>>> eq(x, y)
False
>>> x.sort()
Real
"""
ctx = _get_ctx(ctx)
return ArithRef(Z3_mk_fresh_const(ctx.ref(), prefix, RealSort(ctx).ast), ctx)
def ToReal(a):
""" Return the Z3 expression ToReal(a).
>>> x = Int('x')
>>> x.sort()
Int
>>> n = ToReal(x)
>>> n
ToReal(x)
>>> n.sort()
Real
"""
if __debug__:
_z3_assert(a.is_int(), "Z3 integer expression expected.")
ctx = a.ctx
return ArithRef(Z3_mk_int2real(ctx.ref(), a.as_ast()), ctx)
def ToInt(a):
""" Return the Z3 expression ToInt(a).
>>> x = Real('x')
>>> x.sort()
Real
>>> n = ToInt(x)
>>> n
ToInt(x)
>>> n.sort()
Int
"""
if __debug__:
_z3_assert(a.is_real(), "Z3 real expression expected.")
ctx = a.ctx
return ArithRef(Z3_mk_real2int(ctx.ref(), a.as_ast()), ctx)
def IsInt(a):
""" Return the Z3 predicate IsInt(a).
>>> x = Real('x')
>>> IsInt(x + "1/2")
IsInt(x + 1/2)
>>> solve(IsInt(x + "1/2"), x > 0, x < 1)
[x = 1/2]
>>> solve(IsInt(x + "1/2"), x > 0, x < 1, x != "1/2")
no solution
"""
if __debug__:
_z3_assert(a.is_real(), "Z3 real expression expected.")
ctx = a.ctx
return BoolRef(Z3_mk_is_int(ctx.ref(), a.as_ast()), ctx)
def Sqrt(a, ctx=None):
""" Return a Z3 expression which represents the square root of a.
>>> x = Real('x')
>>> Sqrt(x)
x**(1/2)
"""
if not is_expr(a):
ctx = _get_ctx(ctx)
a = RealVal(a, ctx)
return a ** "1/2"
def Cbrt(a, ctx=None):
""" Return a Z3 expression which represents the cubic root of a.
>>> x = Real('x')
>>> Cbrt(x)
x**(1/3)
"""
if not is_expr(a):
ctx = _get_ctx(ctx)
a = RealVal(a, ctx)
return a ** "1/3"
#########################################
#
# Bit-Vectors
#
#########################################
class BitVecSortRef(SortRef):
"""Bit-vector sort."""
def size(self):
"""Return the size (number of bits) of the bit-vector sort `self`.
>>> b = BitVecSort(32)
>>> b.size()
32
"""
return int(Z3_get_bv_sort_size(self.ctx_ref(), self.ast))
def subsort(self, other):
return is_bv_sort(other) and self.size() < other.size()
def cast(self, val):
"""Try to cast `val` as a Bit-Vector.
>>> b = BitVecSort(32)
>>> b.cast(10)
10
>>> b.cast(10).sexpr()
'#x0000000a'
"""
if is_expr(val):
if __debug__:
_z3_assert(self.ctx == val.ctx, "Context mismatch")
# Idea: use sign_extend if sort of val is a bitvector of smaller size
return val
else:
return BitVecVal(val, self)
def is_bv_sort(s):
"""Return True if `s` is a Z3 bit-vector sort.
>>> is_bv_sort(BitVecSort(32))
True
>>> is_bv_sort(IntSort())
False
"""
return isinstance(s, BitVecSortRef)
class BitVecRef(ExprRef):
"""Bit-vector expressions."""
def sort(self):
"""Return the sort of the bit-vector expression `self`.
>>> x = BitVec('x', 32)
>>> x.sort()
BitVec(32)
>>> x.sort() == BitVecSort(32)
True
"""
return BitVecSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
def size(self):
"""Return the number of bits of the bit-vector expression `self`.
>>> x = BitVec('x', 32)
>>> (x + 1).size()
32
>>> Concat(x, x).size()
64
"""
return self.sort().size()
def __add__(self, other):
"""Create the Z3 expression `self + other`.
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x + y
x + y
>>> (x + y).sort()
BitVec(32)
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __radd__(self, other):
"""Create the Z3 expression `other + self`.
>>> x = BitVec('x', 32)
>>> 10 + x
10 + x
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvadd(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
def __mul__(self, other):
"""Create the Z3 expression `self * other`.
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x * y
x*y
>>> (x * y).sort()
BitVec(32)
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __rmul__(self, other):
"""Create the Z3 expression `other * self`.
>>> x = BitVec('x', 32)
>>> 10 * x
10*x
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvmul(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
def __sub__(self, other):
"""Create the Z3 expression `self - other`.
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x - y
x - y
>>> (x - y).sort()
BitVec(32)
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __rsub__(self, other):
"""Create the Z3 expression `other - self`.
>>> x = BitVec('x', 32)
>>> 10 - x
10 - x
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvsub(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
def __or__(self, other):
"""Create the Z3 expression bitwise-or `self | other`.
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x | y
x | y
>>> (x | y).sort()
BitVec(32)
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __ror__(self, other):
"""Create the Z3 expression bitwise-or `other | self`.
>>> x = BitVec('x', 32)
>>> 10 | x
10 | x
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
def __and__(self, other):
"""Create the Z3 expression bitwise-and `self & other`.
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x & y
x & y
>>> (x & y).sort()
BitVec(32)
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvand(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __rand__(self, other):
"""Create the Z3 expression bitwise-or `other & self`.
>>> x = BitVec('x', 32)
>>> 10 & x
10 & x
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvand(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
def __xor__(self, other):
"""Create the Z3 expression bitwise-xor `self ^ other`.
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x ^ y
x ^ y
>>> (x ^ y).sort()
BitVec(32)
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __rxor__(self, other):
"""Create the Z3 expression bitwise-xor `other ^ self`.
>>> x = BitVec('x', 32)
>>> 10 ^ x
10 ^ x
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvxor(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
def __pos__(self):
"""Return `self`.
>>> x = BitVec('x', 32)
>>> +x
x
"""
return self
def __neg__(self):
"""Return an expression representing `-self`.
>>> x = BitVec('x', 32)
>>> -x
-x
>>> simplify(-(-x))
x
"""
return BitVecRef(Z3_mk_bvneg(self.ctx_ref(), self.as_ast()), self.ctx)
def __invert__(self):
"""Create the Z3 expression bitwise-not `~self`.
>>> x = BitVec('x', 32)
>>> ~x
~x
>>> simplify(~(~x))
x
"""
return BitVecRef(Z3_mk_bvnot(self.ctx_ref(), self.as_ast()), self.ctx)
def __div__(self, other):
"""Create the Z3 expression (signed) division `self / other`.
Use the function UDiv() for unsigned division.
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x / y
x/y
>>> (x / y).sort()
BitVec(32)
>>> (x / y).sexpr()
'(bvsdiv x y)'
>>> UDiv(x, y).sexpr()
'(bvudiv x y)'
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __truediv__(self, other):
"""Create the Z3 expression (signed) division `self / other`."""
return self.__div__(other)
def __rdiv__(self, other):
"""Create the Z3 expression (signed) division `other / self`.
Use the function UDiv() for unsigned division.
>>> x = BitVec('x', 32)
>>> 10 / x
10/x
>>> (10 / x).sexpr()
'(bvsdiv #x0000000a x)'
>>> UDiv(10, x).sexpr()
'(bvudiv #x0000000a x)'
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvsdiv(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
def __rtruediv__(self, other):
"""Create the Z3 expression (signed) division `other / self`."""
return self.__rdiv__(other)
def __mod__(self, other):
"""Create the Z3 expression (signed) mod `self % other`.
Use the function URem() for unsigned remainder, and SRem() for signed remainder.
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> x % y
x%y
>>> (x % y).sort()
BitVec(32)
>>> (x % y).sexpr()
'(bvsmod x y)'
>>> URem(x, y).sexpr()
'(bvurem x y)'
>>> SRem(x, y).sexpr()
'(bvsrem x y)'
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __rmod__(self, other):
"""Create the Z3 expression (signed) mod `other % self`.
Use the function URem() for unsigned remainder, and SRem() for signed remainder.
>>> x = BitVec('x', 32)
>>> 10 % x
10%x
>>> (10 % x).sexpr()
'(bvsmod #x0000000a x)'
>>> URem(10, x).sexpr()
'(bvurem #x0000000a x)'
>>> SRem(10, x).sexpr()
'(bvsrem #x0000000a x)'
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvsmod(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
def __le__(self, other):
"""Create the Z3 expression (signed) `other <= self`.
Use the function ULE() for unsigned less than or equal to.
>>> x, y = BitVecs('x y', 32)
>>> x <= y
x <= y
>>> (x <= y).sexpr()
'(bvsle x y)'
>>> ULE(x, y).sexpr()
'(bvule x y)'
"""
a, b = _coerce_exprs(self, other)
return BoolRef(Z3_mk_bvsle(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __lt__(self, other):
"""Create the Z3 expression (signed) `other < self`.
Use the function ULT() for unsigned less than.
>>> x, y = BitVecs('x y', 32)
>>> x < y
x < y
>>> (x < y).sexpr()
'(bvslt x y)'
>>> ULT(x, y).sexpr()
'(bvult x y)'
"""
a, b = _coerce_exprs(self, other)
return BoolRef(Z3_mk_bvslt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __gt__(self, other):
"""Create the Z3 expression (signed) `other > self`.
Use the function UGT() for unsigned greater than.
>>> x, y = BitVecs('x y', 32)
>>> x > y
x > y
>>> (x > y).sexpr()
'(bvsgt x y)'
>>> UGT(x, y).sexpr()
'(bvugt x y)'
"""
a, b = _coerce_exprs(self, other)
return BoolRef(Z3_mk_bvsgt(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __ge__(self, other):
"""Create the Z3 expression (signed) `other >= self`.
Use the function UGE() for unsigned greater than or equal to.
>>> x, y = BitVecs('x y', 32)
>>> x >= y
x >= y
>>> (x >= y).sexpr()
'(bvsge x y)'
>>> UGE(x, y).sexpr()
'(bvuge x y)'
"""
a, b = _coerce_exprs(self, other)
return BoolRef(Z3_mk_bvsge(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __rshift__(self, other):
"""Create the Z3 expression (arithmetical) right shift `self >> other`
Use the function LShR() for the right logical shift
>>> x, y = BitVecs('x y', 32)
>>> x >> y
x >> y
>>> (x >> y).sexpr()
'(bvashr x y)'
>>> LShR(x, y).sexpr()
'(bvlshr x y)'
>>> BitVecVal(4, 3)
4
>>> BitVecVal(4, 3).as_signed_long()
-4
>>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
-2
>>> simplify(BitVecVal(4, 3) >> 1)
6
>>> simplify(LShR(BitVecVal(4, 3), 1))
2
>>> simplify(BitVecVal(2, 3) >> 1)
1
>>> simplify(LShR(BitVecVal(2, 3), 1))
1
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __lshift__(self, other):
"""Create the Z3 expression left shift `self << other`
>>> x, y = BitVecs('x y', 32)
>>> x << y
x << y
>>> (x << y).sexpr()
'(bvshl x y)'
>>> simplify(BitVecVal(2, 3) << 1)
4
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), a.as_ast(), b.as_ast()), self.ctx)
def __rrshift__(self, other):
"""Create the Z3 expression (arithmetical) right shift `other` >> `self`.
Use the function LShR() for the right logical shift
>>> x = BitVec('x', 32)
>>> 10 >> x
10 >> x
>>> (10 >> x).sexpr()
'(bvashr #x0000000a x)'
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvashr(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
def __rlshift__(self, other):
"""Create the Z3 expression left shift `other << self`.
Use the function LShR() for the right logical shift
>>> x = BitVec('x', 32)
>>> 10 << x
10 << x
>>> (10 << x).sexpr()
'(bvshl #x0000000a x)'
"""
a, b = _coerce_exprs(self, other)
return BitVecRef(Z3_mk_bvshl(self.ctx_ref(), b.as_ast(), a.as_ast()), self.ctx)
class BitVecNumRef(BitVecRef):
"""Bit-vector values."""
def as_long(self):
"""Return a Z3 bit-vector numeral as a Python long (bignum) numeral.
>>> v = BitVecVal(0xbadc0de, 32)
>>> v
195936478
>>> print("0x%.8x" % v.as_long())
0x0badc0de
"""
return int(self.as_string())
def as_signed_long(self):
"""Return a Z3 bit-vector numeral as a Python long (bignum) numeral. The most significant bit is assumed to be the sign.
>>> BitVecVal(4, 3).as_signed_long()
-4
>>> BitVecVal(7, 3).as_signed_long()
-1
>>> BitVecVal(3, 3).as_signed_long()
3
>>> BitVecVal(2**32 - 1, 32).as_signed_long()
-1
>>> BitVecVal(2**64 - 1, 64).as_signed_long()
-1
"""
sz = self.size()
val = self.as_long()
if val >= 2**(sz - 1):
val = val - 2**sz
if val < -2**(sz - 1):
val = val + 2**sz
return int(val)
def as_string(self):
return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
def is_bv(a):
"""Return `True` if `a` is a Z3 bit-vector expression.
>>> b = BitVec('b', 32)
>>> is_bv(b)
True
>>> is_bv(b + 10)
True
>>> is_bv(Int('x'))
False
"""
return isinstance(a, BitVecRef)
def is_bv_value(a):
"""Return `True` if `a` is a Z3 bit-vector numeral value.
>>> b = BitVec('b', 32)
>>> is_bv_value(b)
False
>>> b = BitVecVal(10, 32)
>>> b
10
>>> is_bv_value(b)
True
"""
return is_bv(a) and _is_numeral(a.ctx, a.as_ast())
def BV2Int(a, is_signed=False):
"""Return the Z3 expression BV2Int(a).
>>> b = BitVec('b', 3)
>>> BV2Int(b).sort()
Int
>>> x = Int('x')
>>> x > BV2Int(b)
x > BV2Int(b)
>>> x > BV2Int(b, is_signed=False)
x > BV2Int(b)
>>> x > BV2Int(b, is_signed=True)
x > If(b < 0, BV2Int(b) - 8, BV2Int(b))
>>> solve(x > BV2Int(b), b == 1, x < 3)
[b = 1, x = 2]
"""
if __debug__:
_z3_assert(is_bv(a), "Z3 bit-vector expression expected")
ctx = a.ctx
## investigate problem with bv2int
return ArithRef(Z3_mk_bv2int(ctx.ref(), a.as_ast(), is_signed), ctx)
def Int2BV(a, num_bits):
"""Return the z3 expression Int2BV(a, num_bits).
It is a bit-vector of width num_bits and represents the
modulo of a by 2^num_bits
"""
ctx = a.ctx
return BitVecRef(Z3_mk_int2bv(ctx.ref(), num_bits, a.as_ast()), ctx)
def BitVecSort(sz, ctx=None):
"""Return a Z3 bit-vector sort of the given size. If `ctx=None`, then the global context is used.
>>> Byte = BitVecSort(8)
>>> Word = BitVecSort(16)
>>> Byte
BitVec(8)
>>> x = Const('x', Byte)
>>> eq(x, BitVec('x', 8))
True
"""
ctx = _get_ctx(ctx)
return BitVecSortRef(Z3_mk_bv_sort(ctx.ref(), sz), ctx)
def BitVecVal(val, bv, ctx=None):
"""Return a bit-vector value with the given number of bits. If `ctx=None`, then the global context is used.
>>> v = BitVecVal(10, 32)
>>> v
10
>>> print("0x%.8x" % v.as_long())
0x0000000a
"""
if is_bv_sort(bv):
ctx = bv.ctx
return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), bv.ast), ctx)
else:
ctx = _get_ctx(ctx)
return BitVecNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), BitVecSort(bv, ctx).ast), ctx)
def BitVec(name, bv, ctx=None):
"""Return a bit-vector constant named `name`. `bv` may be the number of bits of a bit-vector sort.
If `ctx=None`, then the global context is used.
>>> x = BitVec('x', 16)
>>> is_bv(x)
True
>>> x.size()
16
>>> x.sort()
BitVec(16)
>>> word = BitVecSort(16)
>>> x2 = BitVec('x', word)
>>> eq(x, x2)
True
"""
if isinstance(bv, BitVecSortRef):
ctx = bv.ctx
else:
ctx = _get_ctx(ctx)
bv = BitVecSort(bv, ctx)
return BitVecRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), bv.ast), ctx)
def BitVecs(names, bv, ctx=None):
"""Return a tuple of bit-vector constants of size bv.
>>> x, y, z = BitVecs('x y z', 16)
>>> x.size()
16
>>> x.sort()
BitVec(16)
>>> Sum(x, y, z)
0 + x + y + z
>>> Product(x, y, z)
1*x*y*z
>>> simplify(Product(x, y, z))
x*y*z
"""
ctx = _get_ctx(ctx)
if isinstance(names, str):
names = names.split(" ")
return [BitVec(name, bv, ctx) for name in names]
def Concat(*args):
"""Create a Z3 bit-vector concatenation expression.
>>> v = BitVecVal(1, 4)
>>> Concat(v, v+1, v)
Concat(Concat(1, 1 + 1), 1)
>>> simplify(Concat(v, v+1, v))
289
>>> print("%.3x" % simplify(Concat(v, v+1, v)).as_long())
121
"""
args = _get_args(args)
sz = len(args)
if __debug__:
_z3_assert(sz >= 2, "At least two arguments expected.")
ctx = None
for a in args:
if is_expr(a):
ctx = a.ctx
break
if is_seq(args[0]) or isinstance(args[0], str):
args = [_coerce_seq(s, ctx) for s in args]
if __debug__:
_z3_assert(all([is_seq(a) for a in args]), "All arguments must be sequence expressions.")
v = (Ast * sz)()
for i in range(sz):
v[i] = args[i].as_ast()
return SeqRef(Z3_mk_seq_concat(ctx.ref(), sz, v), ctx)
if is_re(args[0]):
if __debug__:
_z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
v = (Ast * sz)()
for i in range(sz):
v[i] = args[i].as_ast()
return ReRef(Z3_mk_re_concat(ctx.ref(), sz, v), ctx)
if __debug__:
_z3_assert(all([is_bv(a) for a in args]), "All arguments must be Z3 bit-vector expressions.")
r = args[0]
for i in range(sz - 1):
r = BitVecRef(Z3_mk_concat(ctx.ref(), r.as_ast(), args[i+1].as_ast()), ctx)
return r
def Extract(high, low, a):
"""Create a Z3 bit-vector extraction expression, or create a string extraction expression.
>>> x = BitVec('x', 8)
>>> Extract(6, 2, x)
Extract(6, 2, x)
>>> Extract(6, 2, x).sort()
BitVec(5)
>>> simplify(Extract(StringVal("abcd"),2,1))
"c"
"""
if isinstance(high, str):
high = StringVal(high)
if is_seq(high):
s = high
offset, length = _coerce_exprs(low, a, s.ctx)
return SeqRef(Z3_mk_seq_extract(s.ctx_ref(), s.as_ast(), offset.as_ast(), length.as_ast()), s.ctx)
if __debug__:
_z3_assert(low <= high, "First argument must be greater than or equal to second argument")
_z3_assert(_is_int(high) and high >= 0 and _is_int(low) and low >= 0, "First and second arguments must be non negative integers")
_z3_assert(is_bv(a), "Third argument must be a Z3 Bitvector expression")
return BitVecRef(Z3_mk_extract(a.ctx_ref(), high, low, a.as_ast()), a.ctx)
def _check_bv_args(a, b):
if __debug__:
_z3_assert(is_bv(a) or is_bv(b), "At least one of the arguments must be a Z3 bit-vector expression")
def ULE(a, b):
"""Create the Z3 expression (unsigned) `other <= self`.
Use the operator <= for signed less than or equal to.
>>> x, y = BitVecs('x y', 32)
>>> ULE(x, y)
ULE(x, y)
>>> (x <= y).sexpr()
'(bvsle x y)'
>>> ULE(x, y).sexpr()
'(bvule x y)'
"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BoolRef(Z3_mk_bvule(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def ULT(a, b):
"""Create the Z3 expression (unsigned) `other < self`.
Use the operator < for signed less than.
>>> x, y = BitVecs('x y', 32)
>>> ULT(x, y)
ULT(x, y)
>>> (x < y).sexpr()
'(bvslt x y)'
>>> ULT(x, y).sexpr()
'(bvult x y)'
"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BoolRef(Z3_mk_bvult(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def UGE(a, b):
"""Create the Z3 expression (unsigned) `other >= self`.
Use the operator >= for signed greater than or equal to.
>>> x, y = BitVecs('x y', 32)
>>> UGE(x, y)
UGE(x, y)
>>> (x >= y).sexpr()
'(bvsge x y)'
>>> UGE(x, y).sexpr()
'(bvuge x y)'
"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BoolRef(Z3_mk_bvuge(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def UGT(a, b):
"""Create the Z3 expression (unsigned) `other > self`.
Use the operator > for signed greater than.
>>> x, y = BitVecs('x y', 32)
>>> UGT(x, y)
UGT(x, y)
>>> (x > y).sexpr()
'(bvsgt x y)'
>>> UGT(x, y).sexpr()
'(bvugt x y)'
"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BoolRef(Z3_mk_bvugt(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def UDiv(a, b):
"""Create the Z3 expression (unsigned) division `self / other`.
Use the operator / for signed division.
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> UDiv(x, y)
UDiv(x, y)
>>> UDiv(x, y).sort()
BitVec(32)
>>> (x / y).sexpr()
'(bvsdiv x y)'
>>> UDiv(x, y).sexpr()
'(bvudiv x y)'
"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BitVecRef(Z3_mk_bvudiv(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def URem(a, b):
"""Create the Z3 expression (unsigned) remainder `self % other`.
Use the operator % for signed modulus, and SRem() for signed remainder.
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> URem(x, y)
URem(x, y)
>>> URem(x, y).sort()
BitVec(32)
>>> (x % y).sexpr()
'(bvsmod x y)'
>>> URem(x, y).sexpr()
'(bvurem x y)'
"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BitVecRef(Z3_mk_bvurem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def SRem(a, b):
"""Create the Z3 expression signed remainder.
Use the operator % for signed modulus, and URem() for unsigned remainder.
>>> x = BitVec('x', 32)
>>> y = BitVec('y', 32)
>>> SRem(x, y)
SRem(x, y)
>>> SRem(x, y).sort()
BitVec(32)
>>> (x % y).sexpr()
'(bvsmod x y)'
>>> SRem(x, y).sexpr()
'(bvsrem x y)'
"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BitVecRef(Z3_mk_bvsrem(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def LShR(a, b):
"""Create the Z3 expression logical right shift.
Use the operator >> for the arithmetical right shift.
>>> x, y = BitVecs('x y', 32)
>>> LShR(x, y)
LShR(x, y)
>>> (x >> y).sexpr()
'(bvashr x y)'
>>> LShR(x, y).sexpr()
'(bvlshr x y)'
>>> BitVecVal(4, 3)
4
>>> BitVecVal(4, 3).as_signed_long()
-4
>>> simplify(BitVecVal(4, 3) >> 1).as_signed_long()
-2
>>> simplify(BitVecVal(4, 3) >> 1)
6
>>> simplify(LShR(BitVecVal(4, 3), 1))
2
>>> simplify(BitVecVal(2, 3) >> 1)
1
>>> simplify(LShR(BitVecVal(2, 3), 1))
1
"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BitVecRef(Z3_mk_bvlshr(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def RotateLeft(a, b):
"""Return an expression representing `a` rotated to the left `b` times.
>>> a, b = BitVecs('a b', 16)
>>> RotateLeft(a, b)
RotateLeft(a, b)
>>> simplify(RotateLeft(a, 0))
a
>>> simplify(RotateLeft(a, 16))
a
"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BitVecRef(Z3_mk_ext_rotate_left(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def RotateRight(a, b):
"""Return an expression representing `a` rotated to the right `b` times.
>>> a, b = BitVecs('a b', 16)
>>> RotateRight(a, b)
RotateRight(a, b)
>>> simplify(RotateRight(a, 0))
a
>>> simplify(RotateRight(a, 16))
a
"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BitVecRef(Z3_mk_ext_rotate_right(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def SignExt(n, a):
"""Return a bit-vector expression with `n` extra sign-bits.
>>> x = BitVec('x', 16)
>>> n = SignExt(8, x)
>>> n.size()
24
>>> n
SignExt(8, x)
>>> n.sort()
BitVec(24)
>>> v0 = BitVecVal(2, 2)
>>> v0
2
>>> v0.size()
2
>>> v = simplify(SignExt(6, v0))
>>> v
254
>>> v.size()
8
>>> print("%.x" % v.as_long())
fe
"""
if __debug__:
_z3_assert(_is_int(n), "First argument must be an integer")
_z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
return BitVecRef(Z3_mk_sign_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
def ZeroExt(n, a):
"""Return a bit-vector expression with `n` extra zero-bits.
>>> x = BitVec('x', 16)
>>> n = ZeroExt(8, x)
>>> n.size()
24
>>> n
ZeroExt(8, x)
>>> n.sort()
BitVec(24)
>>> v0 = BitVecVal(2, 2)
>>> v0
2
>>> v0.size()
2
>>> v = simplify(ZeroExt(6, v0))
>>> v
2
>>> v.size()
8
"""
if __debug__:
_z3_assert(_is_int(n), "First argument must be an integer")
_z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
return BitVecRef(Z3_mk_zero_ext(a.ctx_ref(), n, a.as_ast()), a.ctx)
def RepeatBitVec(n, a):
"""Return an expression representing `n` copies of `a`.
>>> x = BitVec('x', 8)
>>> n = RepeatBitVec(4, x)
>>> n
RepeatBitVec(4, x)
>>> n.size()
32
>>> v0 = BitVecVal(10, 4)
>>> print("%.x" % v0.as_long())
a
>>> v = simplify(RepeatBitVec(4, v0))
>>> v.size()
16
>>> print("%.x" % v.as_long())
aaaa
"""
if __debug__:
_z3_assert(_is_int(n), "First argument must be an integer")
_z3_assert(is_bv(a), "Second argument must be a Z3 Bitvector expression")
return BitVecRef(Z3_mk_repeat(a.ctx_ref(), n, a.as_ast()), a.ctx)
def BVRedAnd(a):
"""Return the reduction-and expression of `a`."""
if __debug__:
_z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
return BitVecRef(Z3_mk_bvredand(a.ctx_ref(), a.as_ast()), a.ctx)
def BVRedOr(a):
"""Return the reduction-or expression of `a`."""
if __debug__:
_z3_assert(is_bv(a), "First argument must be a Z3 Bitvector expression")
return BitVecRef(Z3_mk_bvredor(a.ctx_ref(), a.as_ast()), a.ctx)
def BVAddNoOverflow(a, b, signed):
"""A predicate the determines that bit-vector addition does not overflow"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BoolRef(Z3_mk_bvadd_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
def BVAddNoUnderflow(a, b):
"""A predicate the determines that signed bit-vector addition does not underflow"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BoolRef(Z3_mk_bvadd_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def BVSubNoOverflow(a, b):
"""A predicate the determines that bit-vector subtraction does not overflow"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BoolRef(Z3_mk_bvsub_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def BVSubNoUnderflow(a, b, signed):
"""A predicate the determines that bit-vector subtraction does not underflow"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BoolRef(Z3_mk_bvsub_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
def BVSDivNoOverflow(a, b):
"""A predicate the determines that bit-vector signed division does not overflow"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BoolRef(Z3_mk_bvsdiv_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def BVSNegNoOverflow(a):
"""A predicate the determines that bit-vector unary negation does not overflow"""
if __debug__:
_z3_assert(is_bv(a), "Argument should be a bit-vector")
return BoolRef(Z3_mk_bvneg_no_overflow(a.ctx_ref(), a.as_ast()), a.ctx)
def BVMulNoOverflow(a, b, signed):
"""A predicate the determines that bit-vector multiplication does not overflow"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BoolRef(Z3_mk_bvmul_no_overflow(a.ctx_ref(), a.as_ast(), b.as_ast(), signed), a.ctx)
def BVMulNoUnderflow(a, b):
"""A predicate the determines that bit-vector signed multiplication does not underflow"""
_check_bv_args(a, b)
a, b = _coerce_exprs(a, b)
return BoolRef(Z3_mk_bvmul_no_underflow(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
#########################################
#
# Arrays
#
#########################################
class ArraySortRef(SortRef):
"""Array sorts."""
def domain(self):
"""Return the domain of the array sort `self`.
>>> A = ArraySort(IntSort(), BoolSort())
>>> A.domain()
Int
"""
return _to_sort_ref(Z3_get_array_sort_domain(self.ctx_ref(), self.ast), self.ctx)
def range(self):
"""Return the range of the array sort `self`.
>>> A = ArraySort(IntSort(), BoolSort())
>>> A.range()
Bool
"""
return _to_sort_ref(Z3_get_array_sort_range(self.ctx_ref(), self.ast), self.ctx)
class ArrayRef(ExprRef):
"""Array expressions. """
def sort(self):
"""Return the array sort of the array expression `self`.
>>> a = Array('a', IntSort(), BoolSort())
>>> a.sort()
Array(Int, Bool)
"""
return ArraySortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
def domain(self):
"""Shorthand for `self.sort().domain()`.
>>> a = Array('a', IntSort(), BoolSort())
>>> a.domain()
Int
"""
return self.sort().domain()
def range(self):
"""Shorthand for `self.sort().range()`.
>>> a = Array('a', IntSort(), BoolSort())
>>> a.range()
Bool
"""
return self.sort().range()
def __getitem__(self, arg):
"""Return the Z3 expression `self[arg]`.
>>> a = Array('a', IntSort(), BoolSort())
>>> i = Int('i')
>>> a[i]
a[i]
>>> a[i].sexpr()
'(select a i)'
"""
arg = self.domain().cast(arg)
return _to_expr_ref(Z3_mk_select(self.ctx_ref(), self.as_ast(), arg.as_ast()), self.ctx)
def default(self):
return _to_expr_ref(Z3_mk_array_default(self.ctx_ref(), self.as_ast()), self.ctx)
def is_array(a):
"""Return `True` if `a` is a Z3 array expression.
>>> a = Array('a', IntSort(), IntSort())
>>> is_array(a)
True
>>> is_array(Store(a, 0, 1))
True
>>> is_array(a[0])
False
"""
return isinstance(a, ArrayRef)
def is_const_array(a):
"""Return `True` if `a` is a Z3 constant array.
>>> a = K(IntSort(), 10)
>>> is_const_array(a)
True
>>> a = Array('a', IntSort(), IntSort())
>>> is_const_array(a)
False
"""
return is_app_of(a, Z3_OP_CONST_ARRAY)
def is_K(a):
"""Return `True` if `a` is a Z3 constant array.
>>> a = K(IntSort(), 10)
>>> is_K(a)
True
>>> a = Array('a', IntSort(), IntSort())
>>> is_K(a)
False
"""
return is_app_of(a, Z3_OP_CONST_ARRAY)
def is_map(a):
"""Return `True` if `a` is a Z3 map array expression.
>>> f = Function('f', IntSort(), IntSort())
>>> b = Array('b', IntSort(), IntSort())
>>> a = Map(f, b)
>>> a
Map(f, b)
>>> is_map(a)
True
>>> is_map(b)
False
"""
return is_app_of(a, Z3_OP_ARRAY_MAP)
def is_default(a):
"""Return `True` if `a` is a Z3 default array expression.
>>> d = Default(K(IntSort(), 10))
>>> is_default(d)
True
"""
return is_app_of(a, Z3_OP_ARRAY_DEFAULT)
def get_map_func(a):
"""Return the function declaration associated with a Z3 map array expression.
>>> f = Function('f', IntSort(), IntSort())
>>> b = Array('b', IntSort(), IntSort())
>>> a = Map(f, b)
>>> eq(f, get_map_func(a))
True
>>> get_map_func(a)
f
>>> get_map_func(a)(0)
f(0)
"""
if __debug__:
_z3_assert(is_map(a), "Z3 array map expression expected.")
return FuncDeclRef(Z3_to_func_decl(a.ctx_ref(), Z3_get_decl_ast_parameter(a.ctx_ref(), a.decl().ast, 0)), a.ctx)
def ArraySort(*sig):
"""Return the Z3 array sort with the given domain and range sorts.
>>> A = ArraySort(IntSort(), BoolSort())
>>> A
Array(Int, Bool)
>>> A.domain()
Int
>>> A.range()
Bool
>>> AA = ArraySort(IntSort(), A)
>>> AA
Array(Int, Array(Int, Bool))
"""
sig = _get_args(sig)
if __debug__:
_z3_assert(len(sig) > 1, "At least two arguments expected")
arity = len(sig) - 1
r = sig[arity]
d = sig[0]
if __debug__:
for s in sig:
_z3_assert(is_sort(s), "Z3 sort expected")
_z3_assert(s.ctx == r.ctx, "Context mismatch")
ctx = d.ctx
if len(sig) == 2:
return ArraySortRef(Z3_mk_array_sort(ctx.ref(), d.ast, r.ast), ctx)
dom = (Sort * arity)()
for i in range(arity):
dom[i] = sig[i].ast
return ArraySortRef(Z3_mk_array_sort_n(ctx.ref(), arity, dom, r.ast), ctx)
def Array(name, dom, rng):
"""Return an array constant named `name` with the given domain and range sorts.
>>> a = Array('a', IntSort(), IntSort())
>>> a.sort()
Array(Int, Int)
>>> a[0]
a[0]
"""
s = ArraySort(dom, rng)
ctx = s.ctx
return ArrayRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), s.ast), ctx)
def Update(a, i, v):
"""Return a Z3 store array expression.
>>> a = Array('a', IntSort(), IntSort())
>>> i, v = Ints('i v')
>>> s = Update(a, i, v)
>>> s.sort()
Array(Int, Int)
>>> prove(s[i] == v)
proved
>>> j = Int('j')
>>> prove(Implies(i != j, s[j] == a[j]))
proved
"""
if __debug__:
_z3_assert(is_array(a), "First argument must be a Z3 array expression")
i = a.domain().cast(i)
v = a.range().cast(v)
ctx = a.ctx
return _to_expr_ref(Z3_mk_store(ctx.ref(), a.as_ast(), i.as_ast(), v.as_ast()), ctx)
def Default(a):
""" Return a default value for array expression.
>>> b = K(IntSort(), 1)
>>> prove(Default(b) == 1)
proved
"""
if __debug__:
_z3_assert(is_array(a), "First argument must be a Z3 array expression")
return a.default()
def Store(a, i, v):
"""Return a Z3 store array expression.
>>> a = Array('a', IntSort(), IntSort())
>>> i, v = Ints('i v')
>>> s = Store(a, i, v)
>>> s.sort()
Array(Int, Int)
>>> prove(s[i] == v)
proved
>>> j = Int('j')
>>> prove(Implies(i != j, s[j] == a[j]))
proved
"""
return Update(a, i, v)
def Select(a, i):
"""Return a Z3 select array expression.
>>> a = Array('a', IntSort(), IntSort())
>>> i = Int('i')
>>> Select(a, i)
a[i]
>>> eq(Select(a, i), a[i])
True
"""
if __debug__:
_z3_assert(is_array(a), "First argument must be a Z3 array expression")
return a[i]
def Map(f, *args):
"""Return a Z3 map array expression.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> a1 = Array('a1', IntSort(), IntSort())
>>> a2 = Array('a2', IntSort(), IntSort())
>>> b = Map(f, a1, a2)
>>> b
Map(f, a1, a2)
>>> prove(b[0] == f(a1[0], a2[0]))
proved
"""
args = _get_args(args)
if __debug__:
_z3_assert(len(args) > 0, "At least one Z3 array expression expected")
_z3_assert(is_func_decl(f), "First argument must be a Z3 function declaration")
_z3_assert(all([is_array(a) for a in args]), "Z3 array expected expected")
_z3_assert(len(args) == f.arity(), "Number of arguments mismatch")
_args, sz = _to_ast_array(args)
ctx = f.ctx
return ArrayRef(Z3_mk_map(ctx.ref(), f.ast, sz, _args), ctx)
def K(dom, v):
"""Return a Z3 constant array expression.
>>> a = K(IntSort(), 10)
>>> a
K(Int, 10)
>>> a.sort()
Array(Int, Int)
>>> i = Int('i')
>>> a[i]
K(Int, 10)[i]
>>> simplify(a[i])
10
"""
if __debug__:
_z3_assert(is_sort(dom), "Z3 sort expected")
ctx = dom.ctx
if not is_expr(v):
v = _py2expr(v, ctx)
return ArrayRef(Z3_mk_const_array(ctx.ref(), dom.ast, v.as_ast()), ctx)
def Ext(a, b):
"""Return extensionality index for arrays.
"""
if __debug__:
_z3_assert(is_array(a) and is_array(b))
return _to_expr_ref(Z3_mk_array_ext(ctx.ref(), a.as_ast(), b.as_ast()));
def is_select(a):
"""Return `True` if `a` is a Z3 array select application.
>>> a = Array('a', IntSort(), IntSort())
>>> is_select(a)
False
>>> i = Int('i')
>>> is_select(a[i])
True
"""
return is_app_of(a, Z3_OP_SELECT)
def is_store(a):
"""Return `True` if `a` is a Z3 array store application.
>>> a = Array('a', IntSort(), IntSort())
>>> is_store(a)
False
>>> is_store(Store(a, 0, 1))
True
"""
return is_app_of(a, Z3_OP_STORE)
#########################################
#
# Sets
#
#########################################
def SetSort(s):
""" Create a set sort over element sort s"""
return ArraySort(s, BoolSort())
def EmptySet(s):
"""Create the empty set
>>> EmptySet(IntSort())
K(Int, False)
"""
ctx = s.ctx
return ArrayRef(Z3_mk_empty_set(ctx.ref(), s.ast), ctx)
def FullSet(s):
"""Create the full set
>>> FullSet(IntSort())
K(Int, True)
"""
ctx = s.ctx
return ArrayRef(Z3_mk_full_set(ctx.ref(), s.ast), ctx)
def SetUnion(*args):
""" Take the union of sets
>>> a = Const('a', SetSort(IntSort()))
>>> b = Const('b', SetSort(IntSort()))
>>> SetUnion(a, b)
union(a, b)
"""
args = _get_args(args)
ctx = _ctx_from_ast_arg_list(args)
_args, sz = _to_ast_array(args)
return ArrayRef(Z3_mk_set_union(ctx.ref(), sz, _args), ctx)
def SetIntersect(*args):
""" Take the union of sets
>>> a = Const('a', SetSort(IntSort()))
>>> b = Const('b', SetSort(IntSort()))
>>> SetIntersect(a, b)
intersect(a, b)
"""
args = _get_args(args)
ctx = _ctx_from_ast_arg_list(args)
_args, sz = _to_ast_array(args)
return ArrayRef(Z3_mk_set_intersect(ctx.ref(), sz, _args), ctx)
def SetAdd(s, e):
""" Add element e to set s
>>> a = Const('a', SetSort(IntSort()))
>>> SetAdd(a, 1)
Store(a, 1, True)
"""
ctx = _ctx_from_ast_arg_list([s,e])
e = _py2expr(e, ctx)
return ArrayRef(Z3_mk_set_add(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
def SetDel(s, e):
""" Remove element e to set s
>>> a = Const('a', SetSort(IntSort()))
>>> SetDel(a, 1)
Store(a, 1, False)
"""
ctx = _ctx_from_ast_arg_list([s,e])
e = _py2expr(e, ctx)
return ArrayRef(Z3_mk_set_del(ctx.ref(), s.as_ast(), e.as_ast()), ctx)
def SetComplement(s):
""" The complement of set s
>>> a = Const('a', SetSort(IntSort()))
>>> SetComplement(a)
complement(a)
"""
ctx = s.ctx
return ArrayRef(Z3_mk_set_complement(ctx.ref(), s.as_ast()), ctx)
def SetDifference(a, b):
""" The set difference of a and b
>>> a = Const('a', SetSort(IntSort()))
>>> b = Const('b', SetSort(IntSort()))
>>> SetDifference(a, b)
difference(a, b)
"""
ctx = _ctx_from_ast_arg_list([a, b])
return ArrayRef(Z3_mk_set_difference(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
def IsMember(e, s):
""" Check if e is a member of set s
>>> a = Const('a', SetSort(IntSort()))
>>> IsMember(1, a)
a[1]
"""
ctx = _ctx_from_ast_arg_list([s,e])
e = _py2expr(e, ctx)
return BoolRef(Z3_mk_set_member(ctx.ref(), e.as_ast(), s.as_ast()), ctx)
def IsSubset(a, b):
""" Check if a is a subset of b
>>> a = Const('a', SetSort(IntSort()))
>>> b = Const('b', SetSort(IntSort()))
>>> IsSubset(a, b)
subset(a, b)
"""
ctx = _ctx_from_ast_arg_list([a, b])
return BoolRef(Z3_mk_set_subset(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
#########################################
#
# Datatypes
#
#########################################
def _valid_accessor(acc):
"""Return `True` if acc is pair of the form (String, Datatype or Sort). """
return isinstance(acc, tuple) and len(acc) == 2 and isinstance(acc[0], str) and (isinstance(acc[1], Datatype) or is_sort(acc[1]))
class Datatype:
"""Helper class for declaring Z3 datatypes.
>>> List = Datatype('List')
>>> List.declare('cons', ('car', IntSort()), ('cdr', List))
>>> List.declare('nil')
>>> List = List.create()
>>> # List is now a Z3 declaration
>>> List.nil
nil
>>> List.cons(10, List.nil)
cons(10, nil)
>>> List.cons(10, List.nil).sort()
List
>>> cons = List.cons
>>> nil = List.nil
>>> car = List.car
>>> cdr = List.cdr
>>> n = cons(1, cons(0, nil))
>>> n
cons(1, cons(0, nil))
>>> simplify(cdr(n))
cons(0, nil)
>>> simplify(car(n))
1
"""
def __init__(self, name, ctx=None):
self.ctx = _get_ctx(ctx)
self.name = name
self.constructors = []
def __deepcopy__(self, memo={}):
r = Datatype(self.name, self.ctx)
r.constructors = copy.deepcopy(self.constructors)
return r
def declare_core(self, name, rec_name, *args):
if __debug__:
_z3_assert(isinstance(name, str), "String expected")
_z3_assert(isinstance(rec_name, str), "String expected")
_z3_assert(all([_valid_accessor(a) for a in args]), "Valid list of accessors expected. An accessor is a pair of the form (String, Datatype|Sort)")
self.constructors.append((name, rec_name, args))
def declare(self, name, *args):
"""Declare constructor named `name` with the given accessors `args`.
Each accessor is a pair `(name, sort)`, where `name` is a string and `sort` a Z3 sort or a reference to the datatypes being declared.
In the following example `List.declare('cons', ('car', IntSort()), ('cdr', List))`
declares the constructor named `cons` that builds a new List using an integer and a List.
It also declares the accessors `car` and `cdr`. The accessor `car` extracts the integer of a `cons` cell,
and `cdr` the list of a `cons` cell. After all constructors were declared, we use the method create() to create
the actual datatype in Z3.
>>> List = Datatype('List')
>>> List.declare('cons', ('car', IntSort()), ('cdr', List))
>>> List.declare('nil')
>>> List = List.create()
"""
if __debug__:
_z3_assert(isinstance(name, str), "String expected")
_z3_assert(name != "", "Constructor name cannot be empty")
return self.declare_core(name, "is-" + name, *args)
def __repr__(self):
return "Datatype(%s, %s)" % (self.name, self.constructors)
def create(self):
"""Create a Z3 datatype based on the constructors declared using the method `declare()`.
The function `CreateDatatypes()` must be used to define mutually recursive datatypes.
>>> List = Datatype('List')
>>> List.declare('cons', ('car', IntSort()), ('cdr', List))
>>> List.declare('nil')
>>> List = List.create()
>>> List.nil
nil
>>> List.cons(10, List.nil)
cons(10, nil)
"""
return CreateDatatypes([self])[0]
class ScopedConstructor:
"""Auxiliary object used to create Z3 datatypes."""
def __init__(self, c, ctx):
self.c = c
self.ctx = ctx
def __del__(self):
if self.ctx.ref() is not None:
Z3_del_constructor(self.ctx.ref(), self.c)
class ScopedConstructorList:
"""Auxiliary object used to create Z3 datatypes."""
def __init__(self, c, ctx):
self.c = c
self.ctx = ctx
def __del__(self):
if self.ctx.ref() is not None:
Z3_del_constructor_list(self.ctx.ref(), self.c)
def CreateDatatypes(*ds):
"""Create mutually recursive Z3 datatypes using 1 or more Datatype helper objects.
In the following example we define a Tree-List using two mutually recursive datatypes.
>>> TreeList = Datatype('TreeList')
>>> Tree = Datatype('Tree')
>>> # Tree has two constructors: leaf and node
>>> Tree.declare('leaf', ('val', IntSort()))
>>> # a node contains a list of trees
>>> Tree.declare('node', ('children', TreeList))
>>> TreeList.declare('nil')
>>> TreeList.declare('cons', ('car', Tree), ('cdr', TreeList))
>>> Tree, TreeList = CreateDatatypes(Tree, TreeList)
>>> Tree.val(Tree.leaf(10))
val(leaf(10))
>>> simplify(Tree.val(Tree.leaf(10)))
10
>>> n1 = Tree.node(TreeList.cons(Tree.leaf(10), TreeList.cons(Tree.leaf(20), TreeList.nil)))
>>> n1
node(cons(leaf(10), cons(leaf(20), nil)))
>>> n2 = Tree.node(TreeList.cons(n1, TreeList.nil))
>>> simplify(n2 == n1)
False
>>> simplify(TreeList.car(Tree.children(n2)) == n1)
True
"""
ds = _get_args(ds)
if __debug__:
_z3_assert(len(ds) > 0, "At least one Datatype must be specified")
_z3_assert(all([isinstance(d, Datatype) for d in ds]), "Arguments must be Datatypes")
_z3_assert(all([d.ctx == ds[0].ctx for d in ds]), "Context mismatch")
_z3_assert(all([d.constructors != [] for d in ds]), "Non-empty Datatypes expected")
ctx = ds[0].ctx
num = len(ds)
names = (Symbol * num)()
out = (Sort * num)()
clists = (ConstructorList * num)()
to_delete = []
for i in range(num):
d = ds[i]
names[i] = to_symbol(d.name, ctx)
num_cs = len(d.constructors)
cs = (Constructor * num_cs)()
for j in range(num_cs):
c = d.constructors[j]
cname = to_symbol(c[0], ctx)
rname = to_symbol(c[1], ctx)
fs = c[2]
num_fs = len(fs)
fnames = (Symbol * num_fs)()
sorts = (Sort * num_fs)()
refs = (ctypes.c_uint * num_fs)()
for k in range(num_fs):
fname = fs[k][0]
ftype = fs[k][1]
fnames[k] = to_symbol(fname, ctx)
if isinstance(ftype, Datatype):
if __debug__:
_z3_assert(ds.count(ftype) == 1, "One and only one occurrence of each datatype is expected")
sorts[k] = None
refs[k] = ds.index(ftype)
else:
if __debug__:
_z3_assert(is_sort(ftype), "Z3 sort expected")
sorts[k] = ftype.ast
refs[k] = 0
cs[j] = Z3_mk_constructor(ctx.ref(), cname, rname, num_fs, fnames, sorts, refs)
to_delete.append(ScopedConstructor(cs[j], ctx))
clists[i] = Z3_mk_constructor_list(ctx.ref(), num_cs, cs)
to_delete.append(ScopedConstructorList(clists[i], ctx))
Z3_mk_datatypes(ctx.ref(), num, names, out, clists)
result = []
## Create a field for every constructor, recognizer and accessor
for i in range(num):
dref = DatatypeSortRef(out[i], ctx)
num_cs = dref.num_constructors()
for j in range(num_cs):
cref = dref.constructor(j)
cref_name = cref.name()
cref_arity = cref.arity()
if cref.arity() == 0:
cref = cref()
setattr(dref, cref_name, cref)
rref = dref.recognizer(j)
setattr(dref, "is_" + cref_name, rref)
for k in range(cref_arity):
aref = dref.accessor(j, k)
setattr(dref, aref.name(), aref)
result.append(dref)
return tuple(result)
class DatatypeSortRef(SortRef):
"""Datatype sorts."""
def num_constructors(self):
"""Return the number of constructors in the given Z3 datatype.
>>> List = Datatype('List')
>>> List.declare('cons', ('car', IntSort()), ('cdr', List))
>>> List.declare('nil')
>>> List = List.create()
>>> # List is now a Z3 declaration
>>> List.num_constructors()
2
"""
return int(Z3_get_datatype_sort_num_constructors(self.ctx_ref(), self.ast))
def constructor(self, idx):
"""Return a constructor of the datatype `self`.
>>> List = Datatype('List')
>>> List.declare('cons', ('car', IntSort()), ('cdr', List))
>>> List.declare('nil')
>>> List = List.create()
>>> # List is now a Z3 declaration
>>> List.num_constructors()
2
>>> List.constructor(0)
cons
>>> List.constructor(1)
nil
"""
if __debug__:
_z3_assert(idx < self.num_constructors(), "Invalid constructor index")
return FuncDeclRef(Z3_get_datatype_sort_constructor(self.ctx_ref(), self.ast, idx), self.ctx)
def recognizer(self, idx):
"""In Z3, each constructor has an associated recognizer predicate.
If the constructor is named `name`, then the recognizer `is_name`.
>>> List = Datatype('List')
>>> List.declare('cons', ('car', IntSort()), ('cdr', List))
>>> List.declare('nil')
>>> List = List.create()
>>> # List is now a Z3 declaration
>>> List.num_constructors()
2
>>> List.recognizer(0)
is(cons)
>>> List.recognizer(1)
is(nil)
>>> simplify(List.is_nil(List.cons(10, List.nil)))
False
>>> simplify(List.is_cons(List.cons(10, List.nil)))
True
>>> l = Const('l', List)
>>> simplify(List.is_cons(l))
is(cons, l)
"""
if __debug__:
_z3_assert(idx < self.num_constructors(), "Invalid recognizer index")
return FuncDeclRef(Z3_get_datatype_sort_recognizer(self.ctx_ref(), self.ast, idx), self.ctx)
def accessor(self, i, j):
"""In Z3, each constructor has 0 or more accessor. The number of accessors is equal to the arity of the constructor.
>>> List = Datatype('List')
>>> List.declare('cons', ('car', IntSort()), ('cdr', List))
>>> List.declare('nil')
>>> List = List.create()
>>> List.num_constructors()
2
>>> List.constructor(0)
cons
>>> num_accs = List.constructor(0).arity()
>>> num_accs
2
>>> List.accessor(0, 0)
car
>>> List.accessor(0, 1)
cdr
>>> List.constructor(1)
nil
>>> num_accs = List.constructor(1).arity()
>>> num_accs
0
"""
if __debug__:
_z3_assert(i < self.num_constructors(), "Invalid constructor index")
_z3_assert(j < self.constructor(i).arity(), "Invalid accessor index")
return FuncDeclRef(Z3_get_datatype_sort_constructor_accessor(self.ctx_ref(), self.ast, i, j), self.ctx)
class DatatypeRef(ExprRef):
"""Datatype expressions."""
def sort(self):
"""Return the datatype sort of the datatype expression `self`."""
return DatatypeSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
def EnumSort(name, values, ctx=None):
"""Return a new enumeration sort named `name` containing the given values.
The result is a pair (sort, list of constants).
Example:
>>> Color, (red, green, blue) = EnumSort('Color', ['red', 'green', 'blue'])
"""
if __debug__:
_z3_assert(isinstance(name, str), "Name must be a string")
_z3_assert(all([isinstance(v, str) for v in values]), "Eumeration sort values must be strings")
_z3_assert(len(values) > 0, "At least one value expected")
ctx = _get_ctx(ctx)
num = len(values)
_val_names = (Symbol * num)()
for i in range(num):
_val_names[i] = to_symbol(values[i])
_values = (FuncDecl * num)()
_testers = (FuncDecl * num)()
name = to_symbol(name)
S = DatatypeSortRef(Z3_mk_enumeration_sort(ctx.ref(), name, num, _val_names, _values, _testers), ctx)
V = []
for i in range(num):
V.append(FuncDeclRef(_values[i], ctx))
V = [a() for a in V]
return S, V
#########################################
#
# Parameter Sets
#
#########################################
class ParamsRef:
"""Set of parameters used to configure Solvers, Tactics and Simplifiers in Z3.
Consider using the function `args2params` to create instances of this object.
"""
def __init__(self, ctx=None, params=None):
self.ctx = _get_ctx(ctx)
if params is None:
self.params = Z3_mk_params(self.ctx.ref())
else:
self.params = params
Z3_params_inc_ref(self.ctx.ref(), self.params)
def __deepcopy__(self, memo={}):
return ParamsRef(self.ctx, self.params)
def __del__(self):
if self.ctx.ref() is not None:
Z3_params_dec_ref(self.ctx.ref(), self.params)
def set(self, name, val):
"""Set parameter name with value val."""
if __debug__:
_z3_assert(isinstance(name, str), "parameter name must be a string")
name_sym = to_symbol(name, self.ctx)
if isinstance(val, bool):
Z3_params_set_bool(self.ctx.ref(), self.params, name_sym, val)
elif _is_int(val):
Z3_params_set_uint(self.ctx.ref(), self.params, name_sym, val)
elif isinstance(val, float):
Z3_params_set_double(self.ctx.ref(), self.params, name_sym, val)
elif isinstance(val, str):
Z3_params_set_symbol(self.ctx.ref(), self.params, name_sym, to_symbol(val, self.ctx))
else:
if __debug__:
_z3_assert(False, "invalid parameter value")
def __repr__(self):
return Z3_params_to_string(self.ctx.ref(), self.params)
def validate(self, ds):
_z3_assert(isinstance(ds, ParamDescrsRef), "parameter description set expected")
Z3_params_validate(self.ctx.ref(), self.params, ds.descr)
def args2params(arguments, keywords, ctx=None):
"""Convert python arguments into a Z3_params object.
A ':' is added to the keywords, and '_' is replaced with '-'
>>> args2params(['model', True, 'relevancy', 2], {'elim_and' : True})
(params model true relevancy 2 elim_and true)
"""
if __debug__:
_z3_assert(len(arguments) % 2 == 0, "Argument list must have an even number of elements.")
prev = None
r = ParamsRef(ctx)
for a in arguments:
if prev is None:
prev = a
else:
r.set(prev, a)
prev = None
for k in keywords:
v = keywords[k]
r.set(k, v)
return r
class ParamDescrsRef:
"""Set of parameter descriptions for Solvers, Tactics and Simplifiers in Z3.
"""
def __init__(self, descr, ctx=None):
_z3_assert(isinstance(descr, ParamDescrs), "parameter description object expected")
self.ctx = _get_ctx(ctx)
self.descr = descr
Z3_param_descrs_inc_ref(self.ctx.ref(), self.descr)
def __deepcopy__(self, memo={}):
return ParamsDescrsRef(self.descr, self.ctx)
def __del__(self):
if self.ctx.ref() is not None:
Z3_param_descrs_dec_ref(self.ctx.ref(), self.descr)
def size(self):
"""Return the size of in the parameter description `self`.
"""
return int(Z3_param_descrs_size(self.ctx.ref(), self.descr))
def __len__(self):
"""Return the size of in the parameter description `self`.
"""
return self.size()
def get_name(self, i):
"""Return the i-th parameter name in the parameter description `self`.
"""
return _symbol2py(self.ctx, Z3_param_descrs_get_name(self.ctx.ref(), self.descr, i))
def get_kind(self, n):
"""Return the kind of the parameter named `n`.
"""
return Z3_param_descrs_get_kind(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
def get_documentation(self, n):
"""Return the documentation string of the parameter named `n`.
"""
return Z3_param_descrs_get_documentation(self.ctx.ref(), self.descr, to_symbol(n, self.ctx))
def __getitem__(self, arg):
if _is_int(arg):
return self.get_name(arg)
else:
return self.get_kind(arg)
def __repr__(self):
return Z3_param_descrs_to_string(self.ctx.ref(), self.descr)
#########################################
#
# Goals
#
#########################################
class Goal(Z3PPObject):
"""Goal is a collection of constraints we want to find a solution or show to be unsatisfiable (infeasible).
Goals are processed using Tactics. A Tactic transforms a goal into a set of subgoals.
A goal has a solution if one of its subgoals has a solution.
A goal is unsatisfiable if all subgoals are unsatisfiable.
"""
def __init__(self, models=True, unsat_cores=False, proofs=False, ctx=None, goal=None):
if __debug__:
_z3_assert(goal is None or ctx is not None, "If goal is different from None, then ctx must be also different from None")
self.ctx = _get_ctx(ctx)
self.goal = goal
if self.goal is None:
self.goal = Z3_mk_goal(self.ctx.ref(), models, unsat_cores, proofs)
Z3_goal_inc_ref(self.ctx.ref(), self.goal)
def __deepcopy__(self, memo={}):
return Goal(False, False, False, self.ctx, self.goal)
def __del__(self):
if self.goal is not None and self.ctx.ref() is not None:
Z3_goal_dec_ref(self.ctx.ref(), self.goal)
def depth(self):
"""Return the depth of the goal `self`. The depth corresponds to the number of tactics applied to `self`.
>>> x, y = Ints('x y')
>>> g = Goal()
>>> g.add(x == 0, y >= x + 1)
>>> g.depth()
0
>>> r = Then('simplify', 'solve-eqs')(g)
>>> # r has 1 subgoal
>>> len(r)
1
>>> r[0].depth()
2
"""
return int(Z3_goal_depth(self.ctx.ref(), self.goal))
def inconsistent(self):
"""Return `True` if `self` contains the `False` constraints.
>>> x, y = Ints('x y')
>>> g = Goal()
>>> g.inconsistent()
False
>>> g.add(x == 0, x == 1)
>>> g
[x == 0, x == 1]
>>> g.inconsistent()
False
>>> g2 = Tactic('propagate-values')(g)[0]
>>> g2.inconsistent()
True
"""
return Z3_goal_inconsistent(self.ctx.ref(), self.goal)
def prec(self):
"""Return the precision (under-approximation, over-approximation, or precise) of the goal `self`.
>>> g = Goal()
>>> g.prec() == Z3_GOAL_PRECISE
True
>>> x, y = Ints('x y')
>>> g.add(x == y + 1)
>>> g.prec() == Z3_GOAL_PRECISE
True
>>> t = With(Tactic('add-bounds'), add_bound_lower=0, add_bound_upper=10)
>>> g2 = t(g)[0]
>>> g2
[x == y + 1, x <= 10, x >= 0, y <= 10, y >= 0]
>>> g2.prec() == Z3_GOAL_PRECISE
False
>>> g2.prec() == Z3_GOAL_UNDER
True
"""
return Z3_goal_precision(self.ctx.ref(), self.goal)
def precision(self):
"""Alias for `prec()`.
>>> g = Goal()
>>> g.precision() == Z3_GOAL_PRECISE
True
"""
return self.prec()
def size(self):
"""Return the number of constraints in the goal `self`.
>>> g = Goal()
>>> g.size()
0
>>> x, y = Ints('x y')
>>> g.add(x == 0, y > x)
>>> g.size()
2
"""
return int(Z3_goal_size(self.ctx.ref(), self.goal))
def __len__(self):
"""Return the number of constraints in the goal `self`.
>>> g = Goal()
>>> len(g)
0
>>> x, y = Ints('x y')
>>> g.add(x == 0, y > x)
>>> len(g)
2
"""
return self.size()
def get(self, i):
"""Return a constraint in the goal `self`.
>>> g = Goal()
>>> x, y = Ints('x y')
>>> g.add(x == 0, y > x)
>>> g.get(0)
x == 0
>>> g.get(1)
y > x
"""
return _to_expr_ref(Z3_goal_formula(self.ctx.ref(), self.goal, i), self.ctx)
def __getitem__(self, arg):
"""Return a constraint in the goal `self`.
>>> g = Goal()
>>> x, y = Ints('x y')
>>> g.add(x == 0, y > x)
>>> g[0]
x == 0
>>> g[1]
y > x
"""
if arg >= len(self):
raise IndexError
return self.get(arg)
def assert_exprs(self, *args):
"""Assert constraints into the goal.
>>> x = Int('x')
>>> g = Goal()
>>> g.assert_exprs(x > 0, x < 2)
>>> g
[x > 0, x < 2]
"""
args = _get_args(args)
s = BoolSort(self.ctx)
for arg in args:
arg = s.cast(arg)
Z3_goal_assert(self.ctx.ref(), self.goal, arg.as_ast())
def append(self, *args):
"""Add constraints.
>>> x = Int('x')
>>> g = Goal()
>>> g.append(x > 0, x < 2)
>>> g
[x > 0, x < 2]
"""
self.assert_exprs(*args)
def insert(self, *args):
"""Add constraints.
>>> x = Int('x')
>>> g = Goal()
>>> g.insert(x > 0, x < 2)
>>> g
[x > 0, x < 2]
"""
self.assert_exprs(*args)
def add(self, *args):
"""Add constraints.
>>> x = Int('x')
>>> g = Goal()
>>> g.add(x > 0, x < 2)
>>> g
[x > 0, x < 2]
"""
self.assert_exprs(*args)
def convert_model(self, model):
"""Retrieve model from a satisfiable goal
>>> a, b = Ints('a b')
>>> g = Goal()
>>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
>>> t = Then(Tactic('split-clause'), Tactic('solve-eqs'))
>>> r = t(g)
>>> r[0]
[Or(b == 0, b == 1), Not(0 <= b)]
>>> r[1]
[Or(b == 0, b == 1), Not(1 <= b)]
>>> # Remark: the subgoal r[0] is unsatisfiable
>>> # Creating a solver for solving the second subgoal
>>> s = Solver()
>>> s.add(r[1])
>>> s.check()
sat
>>> s.model()
[b = 0]
>>> # Model s.model() does not assign a value to `a`
>>> # It is a model for subgoal `r[1]`, but not for goal `g`
>>> # The method convert_model creates a model for `g` from a model for `r[1]`.
>>> r[1].convert_model(s.model())
[b = 0, a = 1]
"""
if __debug__:
_z3_assert(isinstance(model, ModelRef), "Z3 Model expected")
return ModelRef(Z3_goal_convert_model(self.ctx.ref(), self.goal, model.model), self.ctx)
def __repr__(self):
return obj_to_string(self)
def sexpr(self):
"""Return a textual representation of the s-expression representing the goal."""
return Z3_goal_to_string(self.ctx.ref(), self.goal)
def dimacs(self):
"""Return a textual representation of the goal in DIMACS format."""
return Z3_goal_to_dimacs_string(self.ctx.ref(), self.goal)
def translate(self, target):
"""Copy goal `self` to context `target`.
>>> x = Int('x')
>>> g = Goal()
>>> g.add(x > 10)
>>> g
[x > 10]
>>> c2 = Context()
>>> g2 = g.translate(c2)
>>> g2
[x > 10]
>>> g.ctx == main_ctx()
True
>>> g2.ctx == c2
True
>>> g2.ctx == main_ctx()
False
"""
if __debug__:
_z3_assert(isinstance(target, Context), "target must be a context")
return Goal(goal=Z3_goal_translate(self.ctx.ref(), self.goal, target.ref()), ctx=target)
def __copy__(self):
return self.translate(self.ctx)
def __deepcopy__(self):
return self.translate(self.ctx)
def simplify(self, *arguments, **keywords):
"""Return a new simplified goal.
This method is essentially invoking the simplify tactic.
>>> g = Goal()
>>> x = Int('x')
>>> g.add(x + 1 >= 2)
>>> g
[x + 1 >= 2]
>>> g2 = g.simplify()
>>> g2
[x >= 1]
>>> # g was not modified
>>> g
[x + 1 >= 2]
"""
t = Tactic('simplify')
return t.apply(self, *arguments, **keywords)[0]
def as_expr(self):
"""Return goal `self` as a single Z3 expression.
>>> x = Int('x')
>>> g = Goal()
>>> g.as_expr()
True
>>> g.add(x > 1)
>>> g.as_expr()
x > 1
>>> g.add(x < 10)
>>> g.as_expr()
And(x > 1, x < 10)
"""
sz = len(self)
if sz == 0:
return BoolVal(True, self.ctx)
elif sz == 1:
return self.get(0)
else:
return And([ self.get(i) for i in range(len(self)) ], self.ctx)
#########################################
#
# AST Vector
#
#########################################
class AstVector(Z3PPObject):
"""A collection (vector) of ASTs."""
def __init__(self, v=None, ctx=None):
self.vector = None
if v is None:
self.ctx = _get_ctx(ctx)
self.vector = Z3_mk_ast_vector(self.ctx.ref())
else:
self.vector = v
assert ctx is not None
self.ctx = ctx
Z3_ast_vector_inc_ref(self.ctx.ref(), self.vector)
def __deepcopy__(self, memo={}):
return AstVector(self.vector, self.ctx)
def __del__(self):
if self.vector is not None and self.ctx.ref() is not None:
Z3_ast_vector_dec_ref(self.ctx.ref(), self.vector)
def __len__(self):
"""Return the size of the vector `self`.
>>> A = AstVector()
>>> len(A)
0
>>> A.push(Int('x'))
>>> A.push(Int('x'))
>>> len(A)
2
"""
return int(Z3_ast_vector_size(self.ctx.ref(), self.vector))
def __getitem__(self, i):
"""Return the AST at position `i`.
>>> A = AstVector()
>>> A.push(Int('x') + 1)
>>> A.push(Int('y'))
>>> A[0]
x + 1
>>> A[1]
y
"""
if isinstance(i, int):
if i < 0:
i += self.__len__()
if i >= self.__len__():
raise IndexError
return _to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, i), self.ctx)
elif isinstance(i, slice):
return [_to_ast_ref(Z3_ast_vector_get(self.ctx.ref(), self.vector, ii), self.ctx) for ii in range(*i.indices(self.__len__()))]
def __setitem__(self, i, v):
"""Update AST at position `i`.
>>> A = AstVector()
>>> A.push(Int('x') + 1)
>>> A.push(Int('y'))
>>> A[0]
x + 1
>>> A[0] = Int('x')
>>> A[0]
x
"""
if i >= self.__len__():
raise IndexError
Z3_ast_vector_set(self.ctx.ref(), self.vector, i, v.as_ast())
def push(self, v):
"""Add `v` in the end of the vector.
>>> A = AstVector()
>>> len(A)
0
>>> A.push(Int('x'))
>>> len(A)
1
"""
Z3_ast_vector_push(self.ctx.ref(), self.vector, v.as_ast())
def resize(self, sz):
"""Resize the vector to `sz` elements.
>>> A = AstVector()
>>> A.resize(10)
>>> len(A)
10
>>> for i in range(10): A[i] = Int('x')
>>> A[5]
x
"""
Z3_ast_vector_resize(self.ctx.ref(), self.vector, sz)
def __contains__(self, item):
"""Return `True` if the vector contains `item`.
>>> x = Int('x')
>>> A = AstVector()
>>> x in A
False
>>> A.push(x)
>>> x in A
True
>>> (x+1) in A
False
>>> A.push(x+1)
>>> (x+1) in A
True
>>> A
[x, x + 1]
"""
for elem in self:
if elem.eq(item):
return True
return False
def translate(self, other_ctx):
"""Copy vector `self` to context `other_ctx`.
>>> x = Int('x')
>>> A = AstVector()
>>> A.push(x)
>>> c2 = Context()
>>> B = A.translate(c2)
>>> B
[x]
"""
return AstVector(Z3_ast_vector_translate(self.ctx.ref(), self.vector, other_ctx.ref()), other_ctx)
def __copy__(self):
return self.translate(self.ctx)
def __deepcopy__(self):
return self.translate(self.ctx)
def __repr__(self):
return obj_to_string(self)
def sexpr(self):
"""Return a textual representation of the s-expression representing the vector."""
return Z3_ast_vector_to_string(self.ctx.ref(), self.vector)
#########################################
#
# AST Map
#
#########################################
class AstMap:
"""A mapping from ASTs to ASTs."""
def __init__(self, m=None, ctx=None):
self.map = None
if m is None:
self.ctx = _get_ctx(ctx)
self.map = Z3_mk_ast_map(self.ctx.ref())
else:
self.map = m
assert ctx is not None
self.ctx = ctx
Z3_ast_map_inc_ref(self.ctx.ref(), self.map)
def __deepcopy__(self, memo={}):
return AstMap(self.map, self.ctx)
def __del__(self):
if self.map is not None and self.ctx.ref() is not None:
Z3_ast_map_dec_ref(self.ctx.ref(), self.map)
def __len__(self):
"""Return the size of the map.
>>> M = AstMap()
>>> len(M)
0
>>> x = Int('x')
>>> M[x] = IntVal(1)
>>> len(M)
1
"""
return int(Z3_ast_map_size(self.ctx.ref(), self.map))
def __contains__(self, key):
"""Return `True` if the map contains key `key`.
>>> M = AstMap()
>>> x = Int('x')
>>> M[x] = x + 1
>>> x in M
True
>>> x+1 in M
False
"""
return Z3_ast_map_contains(self.ctx.ref(), self.map, key.as_ast())
def __getitem__(self, key):
"""Retrieve the value associated with key `key`.
>>> M = AstMap()
>>> x = Int('x')
>>> M[x] = x + 1
>>> M[x]
x + 1
"""
return _to_ast_ref(Z3_ast_map_find(self.ctx.ref(), self.map, key.as_ast()), self.ctx)
def __setitem__(self, k, v):
"""Add/Update key `k` with value `v`.
>>> M = AstMap()
>>> x = Int('x')
>>> M[x] = x + 1
>>> len(M)
1
>>> M[x]
x + 1
>>> M[x] = IntVal(1)
>>> M[x]
1
"""
Z3_ast_map_insert(self.ctx.ref(), self.map, k.as_ast(), v.as_ast())
def __repr__(self):
return Z3_ast_map_to_string(self.ctx.ref(), self.map)
def erase(self, k):
"""Remove the entry associated with key `k`.
>>> M = AstMap()
>>> x = Int('x')
>>> M[x] = x + 1
>>> len(M)
1
>>> M.erase(x)
>>> len(M)
0
"""
Z3_ast_map_erase(self.ctx.ref(), self.map, k.as_ast())
def reset(self):
"""Remove all entries from the map.
>>> M = AstMap()
>>> x = Int('x')
>>> M[x] = x + 1
>>> M[x+x] = IntVal(1)
>>> len(M)
2
>>> M.reset()
>>> len(M)
0
"""
Z3_ast_map_reset(self.ctx.ref(), self.map)
def keys(self):
"""Return an AstVector containing all keys in the map.
>>> M = AstMap()
>>> x = Int('x')
>>> M[x] = x + 1
>>> M[x+x] = IntVal(1)
>>> M.keys()
[x, x + x]
"""
return AstVector(Z3_ast_map_keys(self.ctx.ref(), self.map), self.ctx)
#########################################
#
# Model
#
#########################################
class FuncEntry:
"""Store the value of the interpretation of a function in a particular point."""
def __init__(self, entry, ctx):
self.entry = entry
self.ctx = ctx
Z3_func_entry_inc_ref(self.ctx.ref(), self.entry)
def __deepcopy__(self, memo={}):
return FuncEntry(self.entry, self.ctx)
def __del__(self):
if self.ctx.ref() is not None:
Z3_func_entry_dec_ref(self.ctx.ref(), self.entry)
def num_args(self):
"""Return the number of arguments in the given entry.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> s = Solver()
>>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
>>> s.check()
sat
>>> m = s.model()
>>> f_i = m[f]
>>> f_i.num_entries()
1
>>> e = f_i.entry(0)
>>> e.num_args()
2
"""
return int(Z3_func_entry_get_num_args(self.ctx.ref(), self.entry))
def arg_value(self, idx):
"""Return the value of argument `idx`.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> s = Solver()
>>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
>>> s.check()
sat
>>> m = s.model()
>>> f_i = m[f]
>>> f_i.num_entries()
1
>>> e = f_i.entry(0)
>>> e
[1, 2, 20]
>>> e.num_args()
2
>>> e.arg_value(0)
1
>>> e.arg_value(1)
2
>>> try:
... e.arg_value(2)
... except IndexError:
... print("index error")
index error
"""
if idx >= self.num_args():
raise IndexError
return _to_expr_ref(Z3_func_entry_get_arg(self.ctx.ref(), self.entry, idx), self.ctx)
def value(self):
"""Return the value of the function at point `self`.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> s = Solver()
>>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
>>> s.check()
sat
>>> m = s.model()
>>> f_i = m[f]
>>> f_i.num_entries()
1
>>> e = f_i.entry(0)
>>> e
[1, 2, 20]
>>> e.num_args()
2
>>> e.value()
20
"""
return _to_expr_ref(Z3_func_entry_get_value(self.ctx.ref(), self.entry), self.ctx)
def as_list(self):
"""Return entry `self` as a Python list.
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> s = Solver()
>>> s.add(f(0, 1) == 10, f(1, 2) == 20, f(1, 0) == 10)
>>> s.check()
sat
>>> m = s.model()
>>> f_i = m[f]
>>> f_i.num_entries()
1
>>> e = f_i.entry(0)
>>> e.as_list()
[1, 2, 20]
"""
args = [ self.arg_value(i) for i in range(self.num_args())]
args.append(self.value())
return args
def __repr__(self):
return repr(self.as_list())
class FuncInterp(Z3PPObject):
"""Stores the interpretation of a function in a Z3 model."""
def __init__(self, f, ctx):
self.f = f
self.ctx = ctx
if self.f is not None:
Z3_func_interp_inc_ref(self.ctx.ref(), self.f)
def __deepcopy__(self, memo={}):
return FuncInterp(self.f, self.ctx)
def __del__(self):
if self.f is not None and self.ctx.ref() is not None:
Z3_func_interp_dec_ref(self.ctx.ref(), self.f)
def else_value(self):
"""
Return the `else` value for a function interpretation.
Return None if Z3 did not specify the `else` value for
this object.
>>> f = Function('f', IntSort(), IntSort())
>>> s = Solver()
>>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
>>> s.check()
sat
>>> m = s.model()
>>> m[f]
[2 -> 0, else -> 1]
>>> m[f].else_value()
1
"""
r = Z3_func_interp_get_else(self.ctx.ref(), self.f)
if r:
return _to_expr_ref(r, self.ctx)
else:
return None
def num_entries(self):
"""Return the number of entries/points in the function interpretation `self`.
>>> f = Function('f', IntSort(), IntSort())
>>> s = Solver()
>>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
>>> s.check()
sat
>>> m = s.model()
>>> m[f]
[2 -> 0, else -> 1]
>>> m[f].num_entries()
1
"""
return int(Z3_func_interp_get_num_entries(self.ctx.ref(), self.f))
def arity(self):
"""Return the number of arguments for each entry in the function interpretation `self`.
>>> f = Function('f', IntSort(), IntSort())
>>> s = Solver()
>>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
>>> s.check()
sat
>>> m = s.model()
>>> m[f].arity()
1
"""
return int(Z3_func_interp_get_arity(self.ctx.ref(), self.f))
def entry(self, idx):
"""Return an entry at position `idx < self.num_entries()` in the function interpretation `self`.
>>> f = Function('f', IntSort(), IntSort())
>>> s = Solver()
>>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
>>> s.check()
sat
>>> m = s.model()
>>> m[f]
[2 -> 0, else -> 1]
>>> m[f].num_entries()
1
>>> m[f].entry(0)
[2, 0]
"""
if idx >= self.num_entries():
raise IndexError
return FuncEntry(Z3_func_interp_get_entry(self.ctx.ref(), self.f, idx), self.ctx)
def translate(self, other_ctx):
"""Copy model 'self' to context 'other_ctx'.
"""
return ModelRef(Z3_model_translate(self.ctx.ref(), self.model, other_ctx.ref()), other_ctx)
def __copy__(self):
return self.translate(self.ctx)
def __deepcopy__(self):
return self.translate(self.ctx)
def as_list(self):
"""Return the function interpretation as a Python list.
>>> f = Function('f', IntSort(), IntSort())
>>> s = Solver()
>>> s.add(f(0) == 1, f(1) == 1, f(2) == 0)
>>> s.check()
sat
>>> m = s.model()
>>> m[f]
[2 -> 0, else -> 1]
>>> m[f].as_list()
[[2, 0], 1]
"""
r = [ self.entry(i).as_list() for i in range(self.num_entries())]
r.append(self.else_value())
return r
def __repr__(self):
return obj_to_string(self)
class ModelRef(Z3PPObject):
"""Model/Solution of a satisfiability problem (aka system of constraints)."""
def __init__(self, m, ctx):
assert ctx is not None
self.model = m
self.ctx = ctx
Z3_model_inc_ref(self.ctx.ref(), self.model)
def __del__(self):
if self.ctx.ref() is not None:
Z3_model_dec_ref(self.ctx.ref(), self.model)
def __repr__(self):
return obj_to_string(self)
def sexpr(self):
"""Return a textual representation of the s-expression representing the model."""
return Z3_model_to_string(self.ctx.ref(), self.model)
def eval(self, t, model_completion=False):
"""Evaluate the expression `t` in the model `self`. If `model_completion` is enabled, then a default interpretation is automatically added for symbols that do not have an interpretation in the model `self`.
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0, x < 2)
>>> s.check()
sat
>>> m = s.model()
>>> m.eval(x + 1)
2
>>> m.eval(x == 1)
True
>>> y = Int('y')
>>> m.eval(y + x)
1 + y
>>> m.eval(y)
y
>>> m.eval(y, model_completion=True)
0
>>> # Now, m contains an interpretation for y
>>> m.eval(y + x)
1
"""
r = (Ast * 1)()
if Z3_model_eval(self.ctx.ref(), self.model, t.as_ast(), model_completion, r):
return _to_expr_ref(r[0], self.ctx)
raise Z3Exception("failed to evaluate expression in the model")
def evaluate(self, t, model_completion=False):
"""Alias for `eval`.
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0, x < 2)
>>> s.check()
sat
>>> m = s.model()
>>> m.evaluate(x + 1)
2
>>> m.evaluate(x == 1)
True
>>> y = Int('y')
>>> m.evaluate(y + x)
1 + y
>>> m.evaluate(y)
y
>>> m.evaluate(y, model_completion=True)
0
>>> # Now, m contains an interpretation for y
>>> m.evaluate(y + x)
1
"""
return self.eval(t, model_completion)
def __len__(self):
"""Return the number of constant and function declarations in the model `self`.
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0, f(x) != x)
>>> s.check()
sat
>>> m = s.model()
>>> len(m)
2
"""
return int(Z3_model_get_num_consts(self.ctx.ref(), self.model)) + int(Z3_model_get_num_funcs(self.ctx.ref(), self.model))
def get_interp(self, decl):
"""Return the interpretation for a given declaration or constant.
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0, x < 2, f(x) == 0)
>>> s.check()
sat
>>> m = s.model()
>>> m[x]
1
>>> m[f]
[else -> 0]
"""
if __debug__:
_z3_assert(isinstance(decl, FuncDeclRef) or is_const(decl), "Z3 declaration expected")
if is_const(decl):
decl = decl.decl()
try:
if decl.arity() == 0:
_r = Z3_model_get_const_interp(self.ctx.ref(), self.model, decl.ast)
if _r.value is None:
return None
r = _to_expr_ref(_r, self.ctx)
if is_as_array(r):
return self.get_interp(get_as_array_func(r))
else:
return r
else:
return FuncInterp(Z3_model_get_func_interp(self.ctx.ref(), self.model, decl.ast), self.ctx)
except Z3Exception:
return None
def num_sorts(self):
"""Return the number of uninterpreted sorts that contain an interpretation in the model `self`.
>>> A = DeclareSort('A')
>>> a, b = Consts('a b', A)
>>> s = Solver()
>>> s.add(a != b)
>>> s.check()
sat
>>> m = s.model()
>>> m.num_sorts()
1
"""
return int(Z3_model_get_num_sorts(self.ctx.ref(), self.model))
def get_sort(self, idx):
"""Return the uninterpreted sort at position `idx` < self.num_sorts().
>>> A = DeclareSort('A')
>>> B = DeclareSort('B')
>>> a1, a2 = Consts('a1 a2', A)
>>> b1, b2 = Consts('b1 b2', B)
>>> s = Solver()
>>> s.add(a1 != a2, b1 != b2)
>>> s.check()
sat
>>> m = s.model()
>>> m.num_sorts()
2
>>> m.get_sort(0)
A
>>> m.get_sort(1)
B
"""
if idx >= self.num_sorts():
raise IndexError
return _to_sort_ref(Z3_model_get_sort(self.ctx.ref(), self.model, idx), self.ctx)
def sorts(self):
"""Return all uninterpreted sorts that have an interpretation in the model `self`.
>>> A = DeclareSort('A')
>>> B = DeclareSort('B')
>>> a1, a2 = Consts('a1 a2', A)
>>> b1, b2 = Consts('b1 b2', B)
>>> s = Solver()
>>> s.add(a1 != a2, b1 != b2)
>>> s.check()
sat
>>> m = s.model()
>>> m.sorts()
[A, B]
"""
return [ self.get_sort(i) for i in range(self.num_sorts()) ]
def get_universe(self, s):
"""Return the interpretation for the uninterpreted sort `s` in the model `self`.
>>> A = DeclareSort('A')
>>> a, b = Consts('a b', A)
>>> s = Solver()
>>> s.add(a != b)
>>> s.check()
sat
>>> m = s.model()
>>> m.get_universe(A)
[A!val!0, A!val!1]
"""
if __debug__:
_z3_assert(isinstance(s, SortRef), "Z3 sort expected")
try:
return AstVector(Z3_model_get_sort_universe(self.ctx.ref(), self.model, s.ast), self.ctx)
except Z3Exception:
return None
def __getitem__(self, idx):
"""If `idx` is an integer, then the declaration at position `idx` in the model `self` is returned. If `idx` is a declaration, then the actual interpretation is returned.
The elements can be retrieved using position or the actual declaration.
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0, x < 2, f(x) == 0)
>>> s.check()
sat
>>> m = s.model()
>>> len(m)
2
>>> m[0]
x
>>> m[1]
f
>>> m[x]
1
>>> m[f]
[else -> 0]
>>> for d in m: print("%s -> %s" % (d, m[d]))
x -> 1
f -> [else -> 0]
"""
if _is_int(idx):
if idx >= len(self):
raise IndexError
num_consts = Z3_model_get_num_consts(self.ctx.ref(), self.model)
if (idx < num_consts):
return FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, idx), self.ctx)
else:
return FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, idx - num_consts), self.ctx)
if isinstance(idx, FuncDeclRef):
return self.get_interp(idx)
if is_const(idx):
return self.get_interp(idx.decl())
if isinstance(idx, SortRef):
return self.get_universe(idx)
if __debug__:
_z3_assert(False, "Integer, Z3 declaration, or Z3 constant expected")
return None
def decls(self):
"""Return a list with all symbols that have an interpretation in the model `self`.
>>> f = Function('f', IntSort(), IntSort())
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0, x < 2, f(x) == 0)
>>> s.check()
sat
>>> m = s.model()
>>> m.decls()
[x, f]
"""
r = []
for i in range(Z3_model_get_num_consts(self.ctx.ref(), self.model)):
r.append(FuncDeclRef(Z3_model_get_const_decl(self.ctx.ref(), self.model, i), self.ctx))
for i in range(Z3_model_get_num_funcs(self.ctx.ref(), self.model)):
r.append(FuncDeclRef(Z3_model_get_func_decl(self.ctx.ref(), self.model, i), self.ctx))
return r
def translate(self, target):
"""Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
"""
if __debug__:
_z3_assert(isinstance(target, Context), "argument must be a Z3 context")
model = Z3_model_translate(self.ctx.ref(), self.model, target.ref())
return Model(model, target)
def __copy__(self):
return self.translate(self.ctx)
def __deepcopy__(self):
return self.translate(self.ctx)
def Model(ctx = None):
ctx = _get_ctx(ctx)
return ModelRef(Z3_mk_model(ctx.ref()), ctx)
def is_as_array(n):
"""Return true if n is a Z3 expression of the form (_ as-array f)."""
return isinstance(n, ExprRef) and Z3_is_as_array(n.ctx.ref(), n.as_ast())
def get_as_array_func(n):
"""Return the function declaration f associated with a Z3 expression of the form (_ as-array f)."""
if __debug__:
_z3_assert(is_as_array(n), "as-array Z3 expression expected.")
return FuncDeclRef(Z3_get_as_array_func_decl(n.ctx.ref(), n.as_ast()), n.ctx)
#########################################
#
# Statistics
#
#########################################
class Statistics:
"""Statistics for `Solver.check()`."""
def __init__(self, stats, ctx):
self.stats = stats
self.ctx = ctx
Z3_stats_inc_ref(self.ctx.ref(), self.stats)
def __deepcopy__(self, memo={}):
return Statistics(self.stats, self.ctx)
def __del__(self):
if self.ctx.ref() is not None:
Z3_stats_dec_ref(self.ctx.ref(), self.stats)
def __repr__(self):
if in_html_mode():
out = io.StringIO()
even = True
out.write(u('<table border="1" cellpadding="2" cellspacing="0">'))
for k, v in self:
if even:
out.write(u('<tr style="background-color:#CFCFCF">'))
even = False
else:
out.write(u('<tr>'))
even = True
out.write(u('<td>%s</td><td>%s</td></tr>' % (k, v)))
out.write(u('</table>'))
return out.getvalue()
else:
return Z3_stats_to_string(self.ctx.ref(), self.stats)
def __len__(self):
"""Return the number of statistical counters.
>>> x = Int('x')
>>> s = Then('simplify', 'nlsat').solver()
>>> s.add(x > 0)
>>> s.check()
sat
>>> st = s.statistics()
>>> len(st)
6
"""
return int(Z3_stats_size(self.ctx.ref(), self.stats))
def __getitem__(self, idx):
"""Return the value of statistical counter at position `idx`. The result is a pair (key, value).
>>> x = Int('x')
>>> s = Then('simplify', 'nlsat').solver()
>>> s.add(x > 0)
>>> s.check()
sat
>>> st = s.statistics()
>>> len(st)
6
>>> st[0]
('nlsat propagations', 2)
>>> st[1]
('nlsat stages', 2)
"""
if idx >= len(self):
raise IndexError
if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
val = int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
else:
val = Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
return (Z3_stats_get_key(self.ctx.ref(), self.stats, idx), val)
def keys(self):
"""Return the list of statistical counters.
>>> x = Int('x')
>>> s = Then('simplify', 'nlsat').solver()
>>> s.add(x > 0)
>>> s.check()
sat
>>> st = s.statistics()
"""
return [Z3_stats_get_key(self.ctx.ref(), self.stats, idx) for idx in range(len(self))]
def get_key_value(self, key):
"""Return the value of a particular statistical counter.
>>> x = Int('x')
>>> s = Then('simplify', 'nlsat').solver()
>>> s.add(x > 0)
>>> s.check()
sat
>>> st = s.statistics()
>>> st.get_key_value('nlsat propagations')
2
"""
for idx in range(len(self)):
if key == Z3_stats_get_key(self.ctx.ref(), self.stats, idx):
if Z3_stats_is_uint(self.ctx.ref(), self.stats, idx):
return int(Z3_stats_get_uint_value(self.ctx.ref(), self.stats, idx))
else:
return Z3_stats_get_double_value(self.ctx.ref(), self.stats, idx)
raise Z3Exception("unknown key")
def __getattr__(self, name):
"""Access the value of statistical using attributes.
Remark: to access a counter containing blank spaces (e.g., 'nlsat propagations'),
we should use '_' (e.g., 'nlsat_propagations').
>>> x = Int('x')
>>> s = Then('simplify', 'nlsat').solver()
>>> s.add(x > 0)
>>> s.check()
sat
>>> st = s.statistics()
>>> st.nlsat_propagations
2
>>> st.nlsat_stages
2
"""
key = name.replace('_', ' ')
try:
return self.get_key_value(key)
except Z3Exception:
raise AttributeError
#########################################
#
# Solver
#
#########################################
class CheckSatResult:
"""Represents the result of a satisfiability check: sat, unsat, unknown.
>>> s = Solver()
>>> s.check()
sat
>>> r = s.check()
>>> isinstance(r, CheckSatResult)
True
"""
def __init__(self, r):
self.r = r
def __deepcopy__(self, memo={}):
return CheckSatResult(self.r)
def __eq__(self, other):
return isinstance(other, CheckSatResult) and self.r == other.r
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
if in_html_mode():
if self.r == Z3_L_TRUE:
return "<b>sat</b>"
elif self.r == Z3_L_FALSE:
return "<b>unsat</b>"
else:
return "<b>unknown</b>"
else:
if self.r == Z3_L_TRUE:
return "sat"
elif self.r == Z3_L_FALSE:
return "unsat"
else:
return "unknown"
sat = CheckSatResult(Z3_L_TRUE)
unsat = CheckSatResult(Z3_L_FALSE)
unknown = CheckSatResult(Z3_L_UNDEF)
class Solver(Z3PPObject):
"""Solver API provides methods for implementing the main SMT 2.0 commands: push, pop, check, get-model, etc."""
def __init__(self, solver=None, ctx=None):
assert solver is None or ctx is not None
self.ctx = _get_ctx(ctx)
self.backtrack_level = 4000000000
self.solver = None
if solver is None:
self.solver = Z3_mk_solver(self.ctx.ref())
else:
self.solver = solver
Z3_solver_inc_ref(self.ctx.ref(), self.solver)
def __del__(self):
if self.solver is not None and self.ctx.ref() is not None:
Z3_solver_dec_ref(self.ctx.ref(), self.solver)
def set(self, *args, **keys):
"""Set a configuration option. The method `help()` return a string containing all available options.
>>> s = Solver()
>>> # The option MBQI can be set using three different approaches.
>>> s.set(mbqi=True)
>>> s.set('MBQI', True)
>>> s.set(':mbqi', True)
"""
p = args2params(args, keys, self.ctx)
Z3_solver_set_params(self.ctx.ref(), self.solver, p.params)
def push(self):
"""Create a backtracking point.
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0)
>>> s
[x > 0]
>>> s.push()
>>> s.add(x < 1)
>>> s
[x > 0, x < 1]
>>> s.check()
unsat
>>> s.pop()
>>> s.check()
sat
>>> s
[x > 0]
"""
Z3_solver_push(self.ctx.ref(), self.solver)
def pop(self, num=1):
"""Backtrack \c num backtracking points.
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0)
>>> s
[x > 0]
>>> s.push()
>>> s.add(x < 1)
>>> s
[x > 0, x < 1]
>>> s.check()
unsat
>>> s.pop()
>>> s.check()
sat
>>> s
[x > 0]
"""
Z3_solver_pop(self.ctx.ref(), self.solver, num)
def num_scopes(self):
"""Return the current number of backtracking points.
>>> s = Solver()
>>> s.num_scopes()
0L
>>> s.push()
>>> s.num_scopes()
1L
>>> s.push()
>>> s.num_scopes()
2L
>>> s.pop()
>>> s.num_scopes()
1L
"""
return Z3_solver_get_num_scopes(self.ctx.ref(), self.solver)
def reset(self):
"""Remove all asserted constraints and backtracking points created using `push()`.
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0)
>>> s
[x > 0]
>>> s.reset()
>>> s
[]
"""
Z3_solver_reset(self.ctx.ref(), self.solver)
def assert_exprs(self, *args):
"""Assert constraints into the solver.
>>> x = Int('x')
>>> s = Solver()
>>> s.assert_exprs(x > 0, x < 2)
>>> s
[x > 0, x < 2]
"""
args = _get_args(args)
s = BoolSort(self.ctx)
for arg in args:
if isinstance(arg, Goal) or isinstance(arg, AstVector):
for f in arg:
Z3_solver_assert(self.ctx.ref(), self.solver, f.as_ast())
else:
arg = s.cast(arg)
Z3_solver_assert(self.ctx.ref(), self.solver, arg.as_ast())
def add(self, *args):
"""Assert constraints into the solver.
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0, x < 2)
>>> s
[x > 0, x < 2]
"""
self.assert_exprs(*args)
def __iadd__(self, fml):
self.add(fml)
return self
def append(self, *args):
"""Assert constraints into the solver.
>>> x = Int('x')
>>> s = Solver()
>>> s.append(x > 0, x < 2)
>>> s
[x > 0, x < 2]
"""
self.assert_exprs(*args)
def insert(self, *args):
"""Assert constraints into the solver.
>>> x = Int('x')
>>> s = Solver()
>>> s.insert(x > 0, x < 2)
>>> s
[x > 0, x < 2]
"""
self.assert_exprs(*args)
def assert_and_track(self, a, p):
"""Assert constraint `a` and track it in the unsat core using the Boolean constant `p`.
If `p` is a string, it will be automatically converted into a Boolean constant.
>>> x = Int('x')
>>> p3 = Bool('p3')
>>> s = Solver()
>>> s.set(unsat_core=True)
>>> s.assert_and_track(x > 0, 'p1')
>>> s.assert_and_track(x != 1, 'p2')
>>> s.assert_and_track(x < 0, p3)
>>> print(s.check())
unsat
>>> c = s.unsat_core()
>>> len(c)
2
>>> Bool('p1') in c
True
>>> Bool('p2') in c
False
>>> p3 in c
True
"""
if isinstance(p, str):
p = Bool(p, self.ctx)
_z3_assert(isinstance(a, BoolRef), "Boolean expression expected")
_z3_assert(isinstance(p, BoolRef) and is_const(p), "Boolean expression expected")
Z3_solver_assert_and_track(self.ctx.ref(), self.solver, a.as_ast(), p.as_ast())
def check(self, *assumptions):
"""Check whether the assertions in the given solver plus the optional assumptions are consistent or not.
>>> x = Int('x')
>>> s = Solver()
>>> s.check()
sat
>>> s.add(x > 0, x < 2)
>>> s.check()
sat
>>> s.model().eval(x)
1
>>> s.add(x < 1)
>>> s.check()
unsat
>>> s.reset()
>>> s.add(2**x == 4)
>>> s.check()
unknown
"""
assumptions = _get_args(assumptions)
num = len(assumptions)
_assumptions = (Ast * num)()
for i in range(num):
_assumptions[i] = assumptions[i].as_ast()
r = Z3_solver_check_assumptions(self.ctx.ref(), self.solver, num, _assumptions)
return CheckSatResult(r)
def model(self):
"""Return a model for the last `check()`.
This function raises an exception if
a model is not available (e.g., last `check()` returned unsat).
>>> s = Solver()
>>> a = Int('a')
>>> s.add(a + 2 == 0)
>>> s.check()
sat
>>> s.model()
[a = -2]
"""
try:
return ModelRef(Z3_solver_get_model(self.ctx.ref(), self.solver), self.ctx)
except Z3Exception:
raise Z3Exception("model is not available")
def unsat_core(self):
"""Return a subset (as an AST vector) of the assumptions provided to the last check().
These are the assumptions Z3 used in the unsatisfiability proof.
Assumptions are available in Z3. They are used to extract unsatisfiable cores.
They may be also used to "retract" assumptions. Note that, assumptions are not really
"soft constraints", but they can be used to implement them.
>>> p1, p2, p3 = Bools('p1 p2 p3')
>>> x, y = Ints('x y')
>>> s = Solver()
>>> s.add(Implies(p1, x > 0))
>>> s.add(Implies(p2, y > x))
>>> s.add(Implies(p2, y < 1))
>>> s.add(Implies(p3, y > -3))
>>> s.check(p1, p2, p3)
unsat
>>> core = s.unsat_core()
>>> len(core)
2
>>> p1 in core
True
>>> p2 in core
True
>>> p3 in core
False
>>> # "Retracting" p2
>>> s.check(p1, p3)
sat
"""
return AstVector(Z3_solver_get_unsat_core(self.ctx.ref(), self.solver), self.ctx)
def consequences(self, assumptions, variables):
"""Determine fixed values for the variables based on the solver state and assumptions.
>>> s = Solver()
>>> a, b, c, d = Bools('a b c d')
>>> s.add(Implies(a,b), Implies(b, c))
>>> s.consequences([a],[b,c,d])
(sat, [Implies(a, b), Implies(a, c)])
>>> s.consequences([Not(c),d],[a,b,c,d])
(sat, [Implies(d, d), Implies(Not(c), Not(c)), Implies(Not(c), Not(b)), Implies(Not(c), Not(a))])
"""
if isinstance(assumptions, list):
_asms = AstVector(None, self.ctx)
for a in assumptions:
_asms.push(a)
assumptions = _asms
if isinstance(variables, list):
_vars = AstVector(None, self.ctx)
for a in variables:
_vars.push(a)
variables = _vars
_z3_assert(isinstance(assumptions, AstVector), "ast vector expected")
_z3_assert(isinstance(variables, AstVector), "ast vector expected")
consequences = AstVector(None, self.ctx)
r = Z3_solver_get_consequences(self.ctx.ref(), self.solver, assumptions.vector, variables.vector, consequences.vector)
sz = len(consequences)
consequences = [ consequences[i] for i in range(sz) ]
return CheckSatResult(r), consequences
def from_file(self, filename):
"""Parse assertions from a file"""
try:
Z3_solver_from_file(self.ctx.ref(), self.solver, filename)
except Z3Exception as e:
_handle_parse_error(e, self.ctx)
def from_string(self, s):
"""Parse assertions from a string"""
try:
Z3_solver_from_string(self.ctx.ref(), self.solver, s)
except Z3Exception as e:
_handle_parse_error(e, self.ctx)
def cube(self, vars = None):
"""Get set of cubes
The method takes an optional set of variables that restrict which
variables may be used as a starting point for cubing.
If vars is not None, then the first case split is based on a variable in
this set.
"""
self.cube_vs = AstVector(None, self.ctx)
if vars is not None:
for v in vars:
self.cube_vs.push(v)
while True:
lvl = self.backtrack_level
self.backtrack_level = 4000000000
r = AstVector(Z3_solver_cube(self.ctx.ref(), self.solver, self.cube_vs.vector, lvl), self.ctx)
if (len(r) == 1 and is_false(r[0])):
return
yield r
if (len(r) == 0):
return
def cube_vars(self):
"""Access the set of variables that were touched by the most recently generated cube.
This set of variables can be used as a starting point for additional cubes.
The idea is that variables that appear in clauses that are reduced by the most recent
cube are likely more useful to cube on."""
return self.cube_vs
def proof(self):
"""Return a proof for the last `check()`. Proof construction must be enabled."""
return _to_expr_ref(Z3_solver_get_proof(self.ctx.ref(), self.solver), self.ctx)
def assertions(self):
"""Return an AST vector containing all added constraints.
>>> s = Solver()
>>> s.assertions()
[]
>>> a = Int('a')
>>> s.add(a > 0)
>>> s.add(a < 10)
>>> s.assertions()
[a > 0, a < 10]
"""
return AstVector(Z3_solver_get_assertions(self.ctx.ref(), self.solver), self.ctx)
def units(self):
"""Return an AST vector containing all currently inferred units.
"""
return AstVector(Z3_solver_get_units(self.ctx.ref(), self.solver), self.ctx)
def non_units(self):
"""Return an AST vector containing all atomic formulas in solver state that are not units.
"""
return AstVector(Z3_solver_get_non_units(self.ctx.ref(), self.solver), self.ctx)
def statistics(self):
"""Return statistics for the last `check()`.
>>> s = SimpleSolver()
>>> x = Int('x')
>>> s.add(x > 0)
>>> s.check()
sat
>>> st = s.statistics()
>>> st.get_key_value('final checks')
1
>>> len(st) > 0
True
>>> st[0] != 0
True
"""
return Statistics(Z3_solver_get_statistics(self.ctx.ref(), self.solver), self.ctx)
def reason_unknown(self):
"""Return a string describing why the last `check()` returned `unknown`.
>>> x = Int('x')
>>> s = SimpleSolver()
>>> s.add(2**x == 4)
>>> s.check()
unknown
>>> s.reason_unknown()
'(incomplete (theory arithmetic))'
"""
return Z3_solver_get_reason_unknown(self.ctx.ref(), self.solver)
def help(self):
"""Display a string describing all available options."""
print(Z3_solver_get_help(self.ctx.ref(), self.solver))
def param_descrs(self):
"""Return the parameter description set."""
return ParamDescrsRef(Z3_solver_get_param_descrs(self.ctx.ref(), self.solver), self.ctx)
def __repr__(self):
"""Return a formatted string with all added constraints."""
return obj_to_string(self)
def translate(self, target):
"""Translate `self` to the context `target`. That is, return a copy of `self` in the context `target`.
>>> c1 = Context()
>>> c2 = Context()
>>> s1 = Solver(ctx=c1)
>>> s2 = s1.translate(c2)
"""
if __debug__:
_z3_assert(isinstance(target, Context), "argument must be a Z3 context")
solver = Z3_solver_translate(self.ctx.ref(), self.solver, target.ref())
return Solver(solver, target)
def __copy__(self):
return self.translate(self.ctx)
def __deepcopy__(self):
return self.translate(self.ctx)
def sexpr(self):
"""Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
>>> x = Int('x')
>>> s = Solver()
>>> s.add(x > 0)
>>> s.add(x < 2)
>>> r = s.sexpr()
"""
return Z3_solver_to_string(self.ctx.ref(), self.solver)
def to_smt2(self):
"""return SMTLIB2 formatted benchmark for solver's assertions"""
es = self.assertions()
sz = len(es)
sz1 = sz
if sz1 > 0:
sz1 -= 1
v = (Ast * sz1)()
for i in range(sz1):
v[i] = es[i].as_ast()
if sz > 0:
e = es[sz1].as_ast()
else:
e = BoolVal(True, self.ctx).as_ast()
return Z3_benchmark_to_smtlib_string(self.ctx.ref(), "benchmark generated from python API", "", "unknown", "", sz1, v, e)
def SolverFor(logic, ctx=None):
"""Create a solver customized for the given logic.
The parameter `logic` is a string. It should be contains
the name of a SMT-LIB logic.
See http://www.smtlib.org/ for the name of all available logics.
>>> s = SolverFor("QF_LIA")
>>> x = Int('x')
>>> s.add(x > 0)
>>> s.add(x < 2)
>>> s.check()
sat
>>> s.model()
[x = 1]
"""
ctx = _get_ctx(ctx)
logic = to_symbol(logic)
return Solver(Z3_mk_solver_for_logic(ctx.ref(), logic), ctx)
def SimpleSolver(ctx=None):
"""Return a simple general purpose solver with limited amount of preprocessing.
>>> s = SimpleSolver()
>>> x = Int('x')
>>> s.add(x > 0)
>>> s.check()
sat
"""
ctx = _get_ctx(ctx)
return Solver(Z3_mk_simple_solver(ctx.ref()), ctx)
#########################################
#
# Fixedpoint
#
#########################################
class Fixedpoint(Z3PPObject):
"""Fixedpoint API provides methods for solving with recursive predicates"""
def __init__(self, fixedpoint=None, ctx=None):
assert fixedpoint is None or ctx is not None
self.ctx = _get_ctx(ctx)
self.fixedpoint = None
if fixedpoint is None:
self.fixedpoint = Z3_mk_fixedpoint(self.ctx.ref())
else:
self.fixedpoint = fixedpoint
Z3_fixedpoint_inc_ref(self.ctx.ref(), self.fixedpoint)
self.vars = []
def __deepcopy__(self, memo={}):
return FixedPoint(self.fixedpoint, self.ctx)
def __del__(self):
if self.fixedpoint is not None and self.ctx.ref() is not None:
Z3_fixedpoint_dec_ref(self.ctx.ref(), self.fixedpoint)
def set(self, *args, **keys):
"""Set a configuration option. The method `help()` return a string containing all available options.
"""
p = args2params(args, keys, self.ctx)
Z3_fixedpoint_set_params(self.ctx.ref(), self.fixedpoint, p.params)
def help(self):
"""Display a string describing all available options."""
print(Z3_fixedpoint_get_help(self.ctx.ref(), self.fixedpoint))
def param_descrs(self):
"""Return the parameter description set."""
return ParamDescrsRef(Z3_fixedpoint_get_param_descrs(self.ctx.ref(), self.fixedpoint), self.ctx)
def assert_exprs(self, *args):
"""Assert constraints as background axioms for the fixedpoint solver."""
args = _get_args(args)
s = BoolSort(self.ctx)
for arg in args:
if isinstance(arg, Goal) or isinstance(arg, AstVector):
for f in arg:
f = self.abstract(f)
Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, f.as_ast())
else:
arg = s.cast(arg)
arg = self.abstract(arg)
Z3_fixedpoint_assert(self.ctx.ref(), self.fixedpoint, arg.as_ast())
def add(self, *args):
"""Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
self.assert_exprs(*args)
def __iadd__(self, fml):
self.add(fml)
return self
def append(self, *args):
"""Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
self.assert_exprs(*args)
def insert(self, *args):
"""Assert constraints as background axioms for the fixedpoint solver. Alias for assert_expr."""
self.assert_exprs(*args)
def add_rule(self, head, body = None, name = None):
"""Assert rules defining recursive predicates to the fixedpoint solver.
>>> a = Bool('a')
>>> b = Bool('b')
>>> s = Fixedpoint()
>>> s.register_relation(a.decl())
>>> s.register_relation(b.decl())
>>> s.fact(a)
>>> s.rule(b, a)
>>> s.query(b)
sat
"""
if name is None:
name = ""
name = to_symbol(name, self.ctx)
if body is None:
head = self.abstract(head)
Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, head.as_ast(), name)
else:
body = _get_args(body)
f = self.abstract(Implies(And(body, self.ctx),head))
Z3_fixedpoint_add_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
def rule(self, head, body = None, name = None):
"""Assert rules defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
self.add_rule(head, body, name)
def fact(self, head, name = None):
"""Assert facts defining recursive predicates to the fixedpoint solver. Alias for add_rule."""
self.add_rule(head, None, name)
def query(self, *query):
"""Query the fixedpoint engine whether formula is derivable.
You can also pass an tuple or list of recursive predicates.
"""
query = _get_args(query)
sz = len(query)
if sz >= 1 and isinstance(query[0], FuncDeclRef):
_decls = (FuncDecl * sz)()
i = 0
for q in query:
_decls[i] = q.ast
i = i + 1
r = Z3_fixedpoint_query_relations(self.ctx.ref(), self.fixedpoint, sz, _decls)
else:
if sz == 1:
query = query[0]
else:
query = And(query, self.ctx)
query = self.abstract(query, False)
r = Z3_fixedpoint_query(self.ctx.ref(), self.fixedpoint, query.as_ast())
return CheckSatResult(r)
def query_from_lvl (self, lvl, *query):
"""Query the fixedpoint engine whether formula is derivable starting at the given query level.
"""
query = _get_args(query)
sz = len(query)
if sz >= 1 and isinstance(query[0], FuncDecl):
_z3_assert (False, "unsupported")
else:
if sz == 1:
query = query[0]
else:
query = And(query)
query = self.abstract(query, False)
r = Z3_fixedpoint_query_from_lvl (self.ctx.ref(), self.fixedpoint, query.as_ast(), lvl)
return CheckSatResult(r)
def push(self):
"""create a backtracking point for added rules, facts and assertions"""
Z3_fixedpoint_push(self.ctx.ref(), self.fixedpoint)
def pop(self):
"""restore to previously created backtracking point"""
Z3_fixedpoint_pop(self.ctx.ref(), self.fixedpoint)
def update_rule(self, head, body, name):
"""update rule"""
if name is None:
name = ""
name = to_symbol(name, self.ctx)
body = _get_args(body)
f = self.abstract(Implies(And(body, self.ctx),head))
Z3_fixedpoint_update_rule(self.ctx.ref(), self.fixedpoint, f.as_ast(), name)
def get_answer(self):
"""Retrieve answer from last query call."""
r = Z3_fixedpoint_get_answer(self.ctx.ref(), self.fixedpoint)
return _to_expr_ref(r, self.ctx)
def get_ground_sat_answer(self):
"""Retrieve a ground cex from last query call."""
r = Z3_fixedpoint_get_ground_sat_answer(self.ctx.ref(), self.fixedpoint)
return _to_expr_ref(r, self.ctx)
def get_rules_along_trace(self):
"""retrieve rules along the counterexample trace"""
return AstVector(Z3_fixedpoint_get_rules_along_trace(self.ctx.ref(), self.fixedpoint), self.ctx)
def get_rule_names_along_trace(self):
"""retrieve rule names along the counterexample trace"""
# this is a hack as I don't know how to return a list of symbols from C++;
# obtain names as a single string separated by semicolons
names = _symbol2py (self.ctx, Z3_fixedpoint_get_rule_names_along_trace(self.ctx.ref(), self.fixedpoint))
# split into individual names
return names.split (';')
def get_num_levels(self, predicate):
"""Retrieve number of levels used for predicate in PDR engine"""
return Z3_fixedpoint_get_num_levels(self.ctx.ref(), self.fixedpoint, predicate.ast)
def get_cover_delta(self, level, predicate):
"""Retrieve properties known about predicate for the level'th unfolding. -1 is treated as the limit (infinity)"""
r = Z3_fixedpoint_get_cover_delta(self.ctx.ref(), self.fixedpoint, level, predicate.ast)
return _to_expr_ref(r, self.ctx)
def add_cover(self, level, predicate, property):
"""Add property to predicate for the level'th unfolding. -1 is treated as infinity (infinity)"""
Z3_fixedpoint_add_cover(self.ctx.ref(), self.fixedpoint, level, predicate.ast, property.ast)
def register_relation(self, *relations):
"""Register relation as recursive"""
relations = _get_args(relations)
for f in relations:
Z3_fixedpoint_register_relation(self.ctx.ref(), self.fixedpoint, f.ast)
def set_predicate_representation(self, f, *representations):
"""Control how relation is represented"""
representations = _get_args(representations)
representations = [to_symbol(s) for s in representations]
sz = len(representations)
args = (Symbol * sz)()
for i in range(sz):
args[i] = representations[i]
Z3_fixedpoint_set_predicate_representation(self.ctx.ref(), self.fixedpoint, f.ast, sz, args)
def parse_string(self, s):
"""Parse rules and queries from a string"""
try:
return AstVector(Z3_fixedpoint_from_string(self.ctx.ref(), self.fixedpoint, s), self.ctx)
except Z3Exception as e:
_handle_parse_error(e, self.ctx)
def parse_file(self, f):
"""Parse rules and queries from a file"""
try:
return AstVector(Z3_fixedpoint_from_file(self.ctx.ref(), self.fixedpoint, f), self.ctx)
except Z3Exception as e:
_handle_parse_error(e, self.ctx)
def get_rules(self):
"""retrieve rules that have been added to fixedpoint context"""
return AstVector(Z3_fixedpoint_get_rules(self.ctx.ref(), self.fixedpoint), self.ctx)
def get_assertions(self):
"""retrieve assertions that have been added to fixedpoint context"""
return AstVector(Z3_fixedpoint_get_assertions(self.ctx.ref(), self.fixedpoint), self.ctx)
def __repr__(self):
"""Return a formatted string with all added rules and constraints."""
return self.sexpr()
def sexpr(self):
"""Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
"""
return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, 0, (Ast * 0)())
def to_string(self, queries):
"""Return a formatted string (in Lisp-like format) with all added constraints.
We say the string is in s-expression format.
Include also queries.
"""
args, len = _to_ast_array(queries)
return Z3_fixedpoint_to_string(self.ctx.ref(), self.fixedpoint, len, args)
def statistics(self):
"""Return statistics for the last `query()`.
"""
return Statistics(Z3_fixedpoint_get_statistics(self.ctx.ref(), self.fixedpoint), self.ctx)
def reason_unknown(self):
"""Return a string describing why the last `query()` returned `unknown`.
"""
return Z3_fixedpoint_get_reason_unknown(self.ctx.ref(), self.fixedpoint)
def declare_var(self, *vars):
"""Add variable or several variables.
The added variable or variables will be bound in the rules
and queries
"""
vars = _get_args(vars)
for v in vars:
self.vars += [v]
def abstract(self, fml, is_forall=True):
if self.vars == []:
return fml
if is_forall:
return ForAll(self.vars, fml)
else:
return Exists(self.vars, fml)
#########################################
#
# Finite domains
#
#########################################
class FiniteDomainSortRef(SortRef):
"""Finite domain sort."""
def size(self):
"""Return the size of the finite domain sort"""
r = (ctypes.c_ulonglong * 1)()
if Z3_get_finite_domain_sort_size(self.ctx_ref(), self.ast, r):
return r[0]
else:
raise Z3Exception("Failed to retrieve finite domain sort size")
def FiniteDomainSort(name, sz, ctx=None):
"""Create a named finite domain sort of a given size sz"""
if not isinstance(name, Symbol):
name = to_symbol(name)
ctx = _get_ctx(ctx)
return FiniteDomainSortRef(Z3_mk_finite_domain_sort(ctx.ref(), name, sz), ctx)
def is_finite_domain_sort(s):
"""Return True if `s` is a Z3 finite-domain sort.
>>> is_finite_domain_sort(FiniteDomainSort('S', 100))
True
>>> is_finite_domain_sort(IntSort())
False
"""
return isinstance(s, FiniteDomainSortRef)
class FiniteDomainRef(ExprRef):
"""Finite-domain expressions."""
def sort(self):
"""Return the sort of the finite-domain expression `self`."""
return FiniteDomainSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
def as_string(self):
"""Return a Z3 floating point expression as a Python string."""
return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
def is_finite_domain(a):
"""Return `True` if `a` is a Z3 finite-domain expression.
>>> s = FiniteDomainSort('S', 100)
>>> b = Const('b', s)
>>> is_finite_domain(b)
True
>>> is_finite_domain(Int('x'))
False
"""
return isinstance(a, FiniteDomainRef)
class FiniteDomainNumRef(FiniteDomainRef):
"""Integer values."""
def as_long(self):
"""Return a Z3 finite-domain numeral as a Python long (bignum) numeral.
>>> s = FiniteDomainSort('S', 100)
>>> v = FiniteDomainVal(3, s)
>>> v
3
>>> v.as_long() + 1
4
"""
return int(self.as_string())
def as_string(self):
"""Return a Z3 finite-domain numeral as a Python string.
>>> s = FiniteDomainSort('S', 100)
>>> v = FiniteDomainVal(42, s)
>>> v.as_string()
'42'
"""
return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
def FiniteDomainVal(val, sort, ctx=None):
"""Return a Z3 finite-domain value. If `ctx=None`, then the global context is used.
>>> s = FiniteDomainSort('S', 256)
>>> FiniteDomainVal(255, s)
255
>>> FiniteDomainVal('100', s)
100
"""
if __debug__:
_z3_assert(is_finite_domain_sort(sort), "Expected finite-domain sort" )
ctx = sort.ctx
return FiniteDomainNumRef(Z3_mk_numeral(ctx.ref(), _to_int_str(val), sort.ast), ctx)
def is_finite_domain_value(a):
"""Return `True` if `a` is a Z3 finite-domain value.
>>> s = FiniteDomainSort('S', 100)
>>> b = Const('b', s)
>>> is_finite_domain_value(b)
False
>>> b = FiniteDomainVal(10, s)
>>> b
10
>>> is_finite_domain_value(b)
True
"""
return is_finite_domain(a) and _is_numeral(a.ctx, a.as_ast())
#########################################
#
# Optimize
#
#########################################
class OptimizeObjective:
def __init__(self, opt, value, is_max):
self._opt = opt
self._value = value
self._is_max = is_max
def lower(self):
opt = self._opt
return _to_expr_ref(Z3_optimize_get_lower(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
def upper(self):
opt = self._opt
return _to_expr_ref(Z3_optimize_get_upper(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
def lower_values(self):
opt = self._opt
return AstVector(Z3_optimize_get_lower_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
def upper_values(self):
opt = self._opt
return AstVector(Z3_optimize_get_upper_as_vector(opt.ctx.ref(), opt.optimize, self._value), opt.ctx)
def value(self):
if self._is_max:
return self.upper()
else:
return self.lower()
def __str__(self):
return "%s:%s" % (self._value, self._is_max)
class Optimize(Z3PPObject):
"""Optimize API provides methods for solving using objective functions and weighted soft constraints"""
def __init__(self, ctx=None):
self.ctx = _get_ctx(ctx)
self.optimize = Z3_mk_optimize(self.ctx.ref())
Z3_optimize_inc_ref(self.ctx.ref(), self.optimize)
def __deepcopy__(self, memo={}):
return Optimize(self.optimize, self.ctx)
def __del__(self):
if self.optimize is not None and self.ctx.ref() is not None:
Z3_optimize_dec_ref(self.ctx.ref(), self.optimize)
def set(self, *args, **keys):
"""Set a configuration option. The method `help()` return a string containing all available options.
"""
p = args2params(args, keys, self.ctx)
Z3_optimize_set_params(self.ctx.ref(), self.optimize, p.params)
def help(self):
"""Display a string describing all available options."""
print(Z3_optimize_get_help(self.ctx.ref(), self.optimize))
def param_descrs(self):
"""Return the parameter description set."""
return ParamDescrsRef(Z3_optimize_get_param_descrs(self.ctx.ref(), self.optimize), self.ctx)
def assert_exprs(self, *args):
"""Assert constraints as background axioms for the optimize solver."""
args = _get_args(args)
s = BoolSort(self.ctx)
for arg in args:
if isinstance(arg, Goal) or isinstance(arg, AstVector):
for f in arg:
Z3_optimize_assert(self.ctx.ref(), self.optimize, f.as_ast())
else:
arg = s.cast(arg)
Z3_optimize_assert(self.ctx.ref(), self.optimize, arg.as_ast())
def add(self, *args):
"""Assert constraints as background axioms for the optimize solver. Alias for assert_expr."""
self.assert_exprs(*args)
def __iadd__(self, fml):
self.add(fml)
return self
def add_soft(self, arg, weight = "1", id = None):
"""Add soft constraint with optional weight and optional identifier.
If no weight is supplied, then the penalty for violating the soft constraint
is 1.
Soft constraints are grouped by identifiers. Soft constraints that are
added without identifiers are grouped by default.
"""
if _is_int(weight):
weight = "%d" % weight
elif isinstance(weight, float):
weight = "%f" % weight
if not isinstance(weight, str):
raise Z3Exception("weight should be a string or an integer")
if id is None:
id = ""
id = to_symbol(id, self.ctx)
v = Z3_optimize_assert_soft(self.ctx.ref(), self.optimize, arg.as_ast(), weight, id)
return OptimizeObjective(self, v, False)
def maximize(self, arg):
"""Add objective function to maximize."""
return OptimizeObjective(self, Z3_optimize_maximize(self.ctx.ref(), self.optimize, arg.as_ast()), True)
def minimize(self, arg):
"""Add objective function to minimize."""
return OptimizeObjective(self, Z3_optimize_minimize(self.ctx.ref(), self.optimize, arg.as_ast()), False)
def push(self):
"""create a backtracking point for added rules, facts and assertions"""
Z3_optimize_push(self.ctx.ref(), self.optimize)
def pop(self):
"""restore to previously created backtracking point"""
Z3_optimize_pop(self.ctx.ref(), self.optimize)
def check(self, *assumptions):
"""Check satisfiability while optimizing objective functions."""
assumptions = _get_args(assumptions)
num = len(assumptions)
_assumptions = (Ast * num)()
for i in range(num):
_assumptions[i] = assumptions[i].as_ast()
return CheckSatResult(Z3_optimize_check(self.ctx.ref(), self.optimize, num, _assumptions))
def reason_unknown(self):
"""Return a string that describes why the last `check()` returned `unknown`."""
return Z3_optimize_get_reason_unknown(self.ctx.ref(), self.optimize)
def model(self):
"""Return a model for the last check()."""
try:
return ModelRef(Z3_optimize_get_model(self.ctx.ref(), self.optimize), self.ctx)
except Z3Exception:
raise Z3Exception("model is not available")
def unsat_core(self):
return AstVector(Z3_optimize_get_unsat_core(self.ctx.ref(), self.optimize), self.ctx)
def lower(self, obj):
if not isinstance(obj, OptimizeObjective):
raise Z3Exception("Expecting objective handle returned by maximize/minimize")
return obj.lower()
def upper(self, obj):
if not isinstance(obj, OptimizeObjective):
raise Z3Exception("Expecting objective handle returned by maximize/minimize")
return obj.upper()
def lower_values(self, obj):
if not isinstance(obj, OptimizeObjective):
raise Z3Exception("Expecting objective handle returned by maximize/minimize")
return obj.lower_values()
def upper_values(self, obj):
if not isinstance(obj, OptimizeObjective):
raise Z3Exception("Expecting objective handle returned by maximize/minimize")
return obj.upper_values()
def from_file(self, filename):
"""Parse assertions and objectives from a file"""
try:
Z3_optimize_from_file(self.ctx.ref(), self.optimize, filename)
except Z3Exception as e:
_handle_parse_error(e, self.ctx)
def from_string(self, s):
"""Parse assertions and objectives from a string"""
try:
Z3_optimize_from_string(self.ctx.ref(), self.optimize, s)
except Z3Exception as e:
_handle_parse_error(e, self.ctx)
def assertions(self):
"""Return an AST vector containing all added constraints."""
return AstVector(Z3_optimize_get_assertions(self.ctx.ref(), self.optimize), self.ctx)
def objectives(self):
"""returns set of objective functions"""
return AstVector(Z3_optimize_get_objectives(self.ctx.ref(), self.optimize), self.ctx)
def __repr__(self):
"""Return a formatted string with all added rules and constraints."""
return self.sexpr()
def sexpr(self):
"""Return a formatted string (in Lisp-like format) with all added constraints. We say the string is in s-expression format.
"""
return Z3_optimize_to_string(self.ctx.ref(), self.optimize)
def statistics(self):
"""Return statistics for the last check`.
"""
return Statistics(Z3_optimize_get_statistics(self.ctx.ref(), self.optimize), self.ctx)
#########################################
#
# ApplyResult
#
#########################################
class ApplyResult(Z3PPObject):
"""An ApplyResult object contains the subgoals produced by a tactic when applied to a goal. It also contains model and proof converters."""
def __init__(self, result, ctx):
self.result = result
self.ctx = ctx
Z3_apply_result_inc_ref(self.ctx.ref(), self.result)
def __deepcopy__(self, memo={}):
return ApplyResult(self.result, self.ctx)
def __del__(self):
if self.ctx.ref() is not None:
Z3_apply_result_dec_ref(self.ctx.ref(), self.result)
def __len__(self):
"""Return the number of subgoals in `self`.
>>> a, b = Ints('a b')
>>> g = Goal()
>>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
>>> t = Tactic('split-clause')
>>> r = t(g)
>>> len(r)
2
>>> t = Then(Tactic('split-clause'), Tactic('split-clause'))
>>> len(t(g))
4
>>> t = Then(Tactic('split-clause'), Tactic('split-clause'), Tactic('propagate-values'))
>>> len(t(g))
1
"""
return int(Z3_apply_result_get_num_subgoals(self.ctx.ref(), self.result))
def __getitem__(self, idx):
"""Return one of the subgoals stored in ApplyResult object `self`.
>>> a, b = Ints('a b')
>>> g = Goal()
>>> g.add(Or(a == 0, a == 1), Or(b == 0, b == 1), a > b)
>>> t = Tactic('split-clause')
>>> r = t(g)
>>> r[0]
[a == 0, Or(b == 0, b == 1), a > b]
>>> r[1]
[a == 1, Or(b == 0, b == 1), a > b]
"""
if idx >= len(self):
raise IndexError
return Goal(goal=Z3_apply_result_get_subgoal(self.ctx.ref(), self.result, idx), ctx=self.ctx)
def __repr__(self):
return obj_to_string(self)
def sexpr(self):
"""Return a textual representation of the s-expression representing the set of subgoals in `self`."""
return Z3_apply_result_to_string(self.ctx.ref(), self.result)
def as_expr(self):
"""Return a Z3 expression consisting of all subgoals.
>>> x = Int('x')
>>> g = Goal()
>>> g.add(x > 1)
>>> g.add(Or(x == 2, x == 3))
>>> r = Tactic('simplify')(g)
>>> r
[[Not(x <= 1), Or(x == 2, x == 3)]]
>>> r.as_expr()
And(Not(x <= 1), Or(x == 2, x == 3))
>>> r = Tactic('split-clause')(g)
>>> r
[[x > 1, x == 2], [x > 1, x == 3]]
>>> r.as_expr()
Or(And(x > 1, x == 2), And(x > 1, x == 3))
"""
sz = len(self)
if sz == 0:
return BoolVal(False, self.ctx)
elif sz == 1:
return self[0].as_expr()
else:
return Or([ self[i].as_expr() for i in range(len(self)) ])
#########################################
#
# Tactics
#
#########################################
class Tactic:
"""Tactics transform, solver and/or simplify sets of constraints (Goal). A Tactic can be converted into a Solver using the method solver().
Several combinators are available for creating new tactics using the built-in ones: Then(), OrElse(), FailIf(), Repeat(), When(), Cond().
"""
def __init__(self, tactic, ctx=None):
self.ctx = _get_ctx(ctx)
self.tactic = None
if isinstance(tactic, TacticObj):
self.tactic = tactic
else:
if __debug__:
_z3_assert(isinstance(tactic, str), "tactic name expected")
try:
self.tactic = Z3_mk_tactic(self.ctx.ref(), str(tactic))
except Z3Exception:
raise Z3Exception("unknown tactic '%s'" % tactic)
Z3_tactic_inc_ref(self.ctx.ref(), self.tactic)
def __deepcopy__(self, memo={}):
return Tactic(self.tactic, self.ctx)
def __del__(self):
if self.tactic is not None and self.ctx.ref() is not None:
Z3_tactic_dec_ref(self.ctx.ref(), self.tactic)
def solver(self):
"""Create a solver using the tactic `self`.
The solver supports the methods `push()` and `pop()`, but it
will always solve each `check()` from scratch.
>>> t = Then('simplify', 'nlsat')
>>> s = t.solver()
>>> x = Real('x')
>>> s.add(x**2 == 2, x > 0)
>>> s.check()
sat
>>> s.model()
[x = 1.4142135623?]
"""
return Solver(Z3_mk_solver_from_tactic(self.ctx.ref(), self.tactic), self.ctx)
def apply(self, goal, *arguments, **keywords):
"""Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
>>> x, y = Ints('x y')
>>> t = Tactic('solve-eqs')
>>> t.apply(And(x == 0, y >= x + 1))
[[y >= 1]]
"""
if __debug__:
_z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expressions expected")
goal = _to_goal(goal)
if len(arguments) > 0 or len(keywords) > 0:
p = args2params(arguments, keywords, self.ctx)
return ApplyResult(Z3_tactic_apply_ex(self.ctx.ref(), self.tactic, goal.goal, p.params), self.ctx)
else:
return ApplyResult(Z3_tactic_apply(self.ctx.ref(), self.tactic, goal.goal), self.ctx)
def __call__(self, goal, *arguments, **keywords):
"""Apply tactic `self` to the given goal or Z3 Boolean expression using the given options.
>>> x, y = Ints('x y')
>>> t = Tactic('solve-eqs')
>>> t(And(x == 0, y >= x + 1))
[[y >= 1]]
"""
return self.apply(goal, *arguments, **keywords)
def help(self):
"""Display a string containing a description of the available options for the `self` tactic."""
print(Z3_tactic_get_help(self.ctx.ref(), self.tactic))
def param_descrs(self):
"""Return the parameter description set."""
return ParamDescrsRef(Z3_tactic_get_param_descrs(self.ctx.ref(), self.tactic), self.ctx)
def _to_goal(a):
if isinstance(a, BoolRef):
goal = Goal(ctx = a.ctx)
goal.add(a)
return goal
else:
return a
def _to_tactic(t, ctx=None):
if isinstance(t, Tactic):
return t
else:
return Tactic(t, ctx)
def _and_then(t1, t2, ctx=None):
t1 = _to_tactic(t1, ctx)
t2 = _to_tactic(t2, ctx)
if __debug__:
_z3_assert(t1.ctx == t2.ctx, "Context mismatch")
return Tactic(Z3_tactic_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
def _or_else(t1, t2, ctx=None):
t1 = _to_tactic(t1, ctx)
t2 = _to_tactic(t2, ctx)
if __debug__:
_z3_assert(t1.ctx == t2.ctx, "Context mismatch")
return Tactic(Z3_tactic_or_else(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
def AndThen(*ts, **ks):
"""Return a tactic that applies the tactics in `*ts` in sequence.
>>> x, y = Ints('x y')
>>> t = AndThen(Tactic('simplify'), Tactic('solve-eqs'))
>>> t(And(x == 0, y > x + 1))
[[Not(y <= 1)]]
>>> t(And(x == 0, y > x + 1)).as_expr()
Not(y <= 1)
"""
if __debug__:
_z3_assert(len(ts) >= 2, "At least two arguments expected")
ctx = ks.get('ctx', None)
num = len(ts)
r = ts[0]
for i in range(num - 1):
r = _and_then(r, ts[i+1], ctx)
return r
def Then(*ts, **ks):
"""Return a tactic that applies the tactics in `*ts` in sequence. Shorthand for AndThen(*ts, **ks).
>>> x, y = Ints('x y')
>>> t = Then(Tactic('simplify'), Tactic('solve-eqs'))
>>> t(And(x == 0, y > x + 1))
[[Not(y <= 1)]]
>>> t(And(x == 0, y > x + 1)).as_expr()
Not(y <= 1)
"""
return AndThen(*ts, **ks)
def OrElse(*ts, **ks):
"""Return a tactic that applies the tactics in `*ts` until one of them succeeds (it doesn't fail).
>>> x = Int('x')
>>> t = OrElse(Tactic('split-clause'), Tactic('skip'))
>>> # Tactic split-clause fails if there is no clause in the given goal.
>>> t(x == 0)
[[x == 0]]
>>> t(Or(x == 0, x == 1))
[[x == 0], [x == 1]]
"""
if __debug__:
_z3_assert(len(ts) >= 2, "At least two arguments expected")
ctx = ks.get('ctx', None)
num = len(ts)
r = ts[0]
for i in range(num - 1):
r = _or_else(r, ts[i+1], ctx)
return r
def ParOr(*ts, **ks):
"""Return a tactic that applies the tactics in `*ts` in parallel until one of them succeeds (it doesn't fail).
>>> x = Int('x')
>>> t = ParOr(Tactic('simplify'), Tactic('fail'))
>>> t(x + 1 == 2)
[[x == 1]]
"""
if __debug__:
_z3_assert(len(ts) >= 2, "At least two arguments expected")
ctx = _get_ctx(ks.get('ctx', None))
ts = [ _to_tactic(t, ctx) for t in ts ]
sz = len(ts)
_args = (TacticObj * sz)()
for i in range(sz):
_args[i] = ts[i].tactic
return Tactic(Z3_tactic_par_or(ctx.ref(), sz, _args), ctx)
def ParThen(t1, t2, ctx=None):
"""Return a tactic that applies t1 and then t2 to every subgoal produced by t1. The subgoals are processed in parallel.
>>> x, y = Ints('x y')
>>> t = ParThen(Tactic('split-clause'), Tactic('propagate-values'))
>>> t(And(Or(x == 1, x == 2), y == x + 1))
[[x == 1, y == 2], [x == 2, y == 3]]
"""
t1 = _to_tactic(t1, ctx)
t2 = _to_tactic(t2, ctx)
if __debug__:
_z3_assert(t1.ctx == t2.ctx, "Context mismatch")
return Tactic(Z3_tactic_par_and_then(t1.ctx.ref(), t1.tactic, t2.tactic), t1.ctx)
def ParAndThen(t1, t2, ctx=None):
"""Alias for ParThen(t1, t2, ctx)."""
return ParThen(t1, t2, ctx)
def With(t, *args, **keys):
"""Return a tactic that applies tactic `t` using the given configuration options.
>>> x, y = Ints('x y')
>>> t = With(Tactic('simplify'), som=True)
>>> t((x + 1)*(y + 2) == 0)
[[2*x + y + x*y == -2]]
"""
ctx = keys.pop('ctx', None)
t = _to_tactic(t, ctx)
p = args2params(args, keys, t.ctx)
return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
def WithParams(t, p):
"""Return a tactic that applies tactic `t` using the given configuration options.
>>> x, y = Ints('x y')
>>> p = ParamsRef()
>>> p.set("som", True)
>>> t = WithParams(Tactic('simplify'), p)
>>> t((x + 1)*(y + 2) == 0)
[[2*x + y + x*y == -2]]
"""
t = _to_tactic(t, None)
return Tactic(Z3_tactic_using_params(t.ctx.ref(), t.tactic, p.params), t.ctx)
def Repeat(t, max=4294967295, ctx=None):
"""Return a tactic that keeps applying `t` until the goal is not modified anymore or the maximum number of iterations `max` is reached.
>>> x, y = Ints('x y')
>>> c = And(Or(x == 0, x == 1), Or(y == 0, y == 1), x > y)
>>> t = Repeat(OrElse(Tactic('split-clause'), Tactic('skip')))
>>> r = t(c)
>>> for subgoal in r: print(subgoal)
[x == 0, y == 0, x > y]
[x == 0, y == 1, x > y]
[x == 1, y == 0, x > y]
[x == 1, y == 1, x > y]
>>> t = Then(t, Tactic('propagate-values'))
>>> t(c)
[[x == 1, y == 0]]
"""
t = _to_tactic(t, ctx)
return Tactic(Z3_tactic_repeat(t.ctx.ref(), t.tactic, max), t.ctx)
def TryFor(t, ms, ctx=None):
"""Return a tactic that applies `t` to a given goal for `ms` milliseconds.
If `t` does not terminate in `ms` milliseconds, then it fails.
"""
t = _to_tactic(t, ctx)
return Tactic(Z3_tactic_try_for(t.ctx.ref(), t.tactic, ms), t.ctx)
def tactics(ctx=None):
"""Return a list of all available tactics in Z3.
>>> l = tactics()
>>> l.count('simplify') == 1
True
"""
ctx = _get_ctx(ctx)
return [ Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref())) ]
def tactic_description(name, ctx=None):
"""Return a short description for the tactic named `name`.
>>> d = tactic_description('simplify')
"""
ctx = _get_ctx(ctx)
return Z3_tactic_get_descr(ctx.ref(), name)
def describe_tactics():
"""Display a (tabular) description of all available tactics in Z3."""
if in_html_mode():
even = True
print('<table border="1" cellpadding="2" cellspacing="0">')
for t in tactics():
if even:
print('<tr style="background-color:#CFCFCF">')
even = False
else:
print('<tr>')
even = True
print('<td>%s</td><td>%s</td></tr>' % (t, insert_line_breaks(tactic_description(t), 40)))
print('</table>')
else:
for t in tactics():
print('%s : %s' % (t, tactic_description(t)))
class Probe:
"""Probes are used to inspect a goal (aka problem) and collect information that may be used to decide which solver and/or preprocessing step will be used."""
def __init__(self, probe, ctx=None):
self.ctx = _get_ctx(ctx)
self.probe = None
if isinstance(probe, ProbeObj):
self.probe = probe
elif isinstance(probe, float):
self.probe = Z3_probe_const(self.ctx.ref(), probe)
elif _is_int(probe):
self.probe = Z3_probe_const(self.ctx.ref(), float(probe))
elif isinstance(probe, bool):
if probe:
self.probe = Z3_probe_const(self.ctx.ref(), 1.0)
else:
self.probe = Z3_probe_const(self.ctx.ref(), 0.0)
else:
if __debug__:
_z3_assert(isinstance(probe, str), "probe name expected")
try:
self.probe = Z3_mk_probe(self.ctx.ref(), probe)
except Z3Exception:
raise Z3Exception("unknown probe '%s'" % probe)
Z3_probe_inc_ref(self.ctx.ref(), self.probe)
def __deepcopy__(self, memo={}):
return Probe(self.probe, self.ctx)
def __del__(self):
if self.probe is not None and self.ctx.ref() is not None:
Z3_probe_dec_ref(self.ctx.ref(), self.probe)
def __lt__(self, other):
"""Return a probe that evaluates to "true" when the value returned by `self` is less than the value returned by `other`.
>>> p = Probe('size') < 10
>>> x = Int('x')
>>> g = Goal()
>>> g.add(x > 0)
>>> g.add(x < 10)
>>> p(g)
1.0
"""
return Probe(Z3_probe_lt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
def __gt__(self, other):
"""Return a probe that evaluates to "true" when the value returned by `self` is greater than the value returned by `other`.
>>> p = Probe('size') > 10
>>> x = Int('x')
>>> g = Goal()
>>> g.add(x > 0)
>>> g.add(x < 10)
>>> p(g)
0.0
"""
return Probe(Z3_probe_gt(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
def __le__(self, other):
"""Return a probe that evaluates to "true" when the value returned by `self` is less than or equal to the value returned by `other`.
>>> p = Probe('size') <= 2
>>> x = Int('x')
>>> g = Goal()
>>> g.add(x > 0)
>>> g.add(x < 10)
>>> p(g)
1.0
"""
return Probe(Z3_probe_le(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
def __ge__(self, other):
"""Return a probe that evaluates to "true" when the value returned by `self` is greater than or equal to the value returned by `other`.
>>> p = Probe('size') >= 2
>>> x = Int('x')
>>> g = Goal()
>>> g.add(x > 0)
>>> g.add(x < 10)
>>> p(g)
1.0
"""
return Probe(Z3_probe_ge(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
def __eq__(self, other):
"""Return a probe that evaluates to "true" when the value returned by `self` is equal to the value returned by `other`.
>>> p = Probe('size') == 2
>>> x = Int('x')
>>> g = Goal()
>>> g.add(x > 0)
>>> g.add(x < 10)
>>> p(g)
1.0
"""
return Probe(Z3_probe_eq(self.ctx.ref(), self.probe, _to_probe(other, self.ctx).probe), self.ctx)
def __ne__(self, other):
"""Return a probe that evaluates to "true" when the value returned by `self` is not equal to the value returned by `other`.
>>> p = Probe('size') != 2
>>> x = Int('x')
>>> g = Goal()
>>> g.add(x > 0)
>>> g.add(x < 10)
>>> p(g)
0.0
"""
p = self.__eq__(other)
return Probe(Z3_probe_not(self.ctx.ref(), p.probe), self.ctx)
def __call__(self, goal):
"""Evaluate the probe `self` in the given goal.
>>> p = Probe('size')
>>> x = Int('x')
>>> g = Goal()
>>> g.add(x > 0)
>>> g.add(x < 10)
>>> p(g)
2.0
>>> g.add(x < 20)
>>> p(g)
3.0
>>> p = Probe('num-consts')
>>> p(g)
1.0
>>> p = Probe('is-propositional')
>>> p(g)
0.0
>>> p = Probe('is-qflia')
>>> p(g)
1.0
"""
if __debug__:
_z3_assert(isinstance(goal, Goal) or isinstance(goal, BoolRef), "Z3 Goal or Boolean expression expected")
goal = _to_goal(goal)
return Z3_probe_apply(self.ctx.ref(), self.probe, goal.goal)
def is_probe(p):
"""Return `True` if `p` is a Z3 probe.
>>> is_probe(Int('x'))
False
>>> is_probe(Probe('memory'))
True
"""
return isinstance(p, Probe)
def _to_probe(p, ctx=None):
if is_probe(p):
return p
else:
return Probe(p, ctx)
def probes(ctx=None):
"""Return a list of all available probes in Z3.
>>> l = probes()
>>> l.count('memory') == 1
True
"""
ctx = _get_ctx(ctx)
return [ Z3_get_probe_name(ctx.ref(), i) for i in range(Z3_get_num_probes(ctx.ref())) ]
def probe_description(name, ctx=None):
"""Return a short description for the probe named `name`.
>>> d = probe_description('memory')
"""
ctx = _get_ctx(ctx)
return Z3_probe_get_descr(ctx.ref(), name)
def describe_probes():
"""Display a (tabular) description of all available probes in Z3."""
if in_html_mode():
even = True
print('<table border="1" cellpadding="2" cellspacing="0">')
for p in probes():
if even:
print('<tr style="background-color:#CFCFCF">')
even = False
else:
print('<tr>')
even = True
print('<td>%s</td><td>%s</td></tr>' % (p, insert_line_breaks(probe_description(p), 40)))
print('</table>')
else:
for p in probes():
print('%s : %s' % (p, probe_description(p)))
def _probe_nary(f, args, ctx):
if __debug__:
_z3_assert(len(args) > 0, "At least one argument expected")
num = len(args)
r = _to_probe(args[0], ctx)
for i in range(num - 1):
r = Probe(f(ctx.ref(), r.probe, _to_probe(args[i+1], ctx).probe), ctx)
return r
def _probe_and(args, ctx):
return _probe_nary(Z3_probe_and, args, ctx)
def _probe_or(args, ctx):
return _probe_nary(Z3_probe_or, args, ctx)
def FailIf(p, ctx=None):
"""Return a tactic that fails if the probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
In the following example, the tactic applies 'simplify' if and only if there are more than 2 constraints in the goal.
>>> t = OrElse(FailIf(Probe('size') > 2), Tactic('simplify'))
>>> x, y = Ints('x y')
>>> g = Goal()
>>> g.add(x > 0)
>>> g.add(y > 0)
>>> t(g)
[[x > 0, y > 0]]
>>> g.add(x == y + 1)
>>> t(g)
[[Not(x <= 0), Not(y <= 0), x == 1 + y]]
"""
p = _to_probe(p, ctx)
return Tactic(Z3_tactic_fail_if(p.ctx.ref(), p.probe), p.ctx)
def When(p, t, ctx=None):
"""Return a tactic that applies tactic `t` only if probe `p` evaluates to true. Otherwise, it returns the input goal unmodified.
>>> t = When(Probe('size') > 2, Tactic('simplify'))
>>> x, y = Ints('x y')
>>> g = Goal()
>>> g.add(x > 0)
>>> g.add(y > 0)
>>> t(g)
[[x > 0, y > 0]]
>>> g.add(x == y + 1)
>>> t(g)
[[Not(x <= 0), Not(y <= 0), x == 1 + y]]
"""
p = _to_probe(p, ctx)
t = _to_tactic(t, ctx)
return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx)
def Cond(p, t1, t2, ctx=None):
"""Return a tactic that applies tactic `t1` to a goal if probe `p` evaluates to true, and `t2` otherwise.
>>> t = Cond(Probe('is-qfnra'), Tactic('qfnra'), Tactic('smt'))
"""
p = _to_probe(p, ctx)
t1 = _to_tactic(t1, ctx)
t2 = _to_tactic(t2, ctx)
return Tactic(Z3_tactic_cond(t1.ctx.ref(), p.probe, t1.tactic, t2.tactic), t1.ctx)
#########################################
#
# Utils
#
#########################################
def simplify(a, *arguments, **keywords):
"""Simplify the expression `a` using the given options.
This function has many options. Use `help_simplify` to obtain the complete list.
>>> x = Int('x')
>>> y = Int('y')
>>> simplify(x + 1 + y + x + 1)
2 + 2*x + y
>>> simplify((x + 1)*(y + 1), som=True)
1 + x + y + x*y
>>> simplify(Distinct(x, y, 1), blast_distinct=True)
And(Not(x == y), Not(x == 1), Not(y == 1))
>>> simplify(And(x == 0, y == 1), elim_and=True)
Not(Or(Not(x == 0), Not(y == 1)))
"""
if __debug__:
_z3_assert(is_expr(a), "Z3 expression expected")
if len(arguments) > 0 or len(keywords) > 0:
p = args2params(arguments, keywords, a.ctx)
return _to_expr_ref(Z3_simplify_ex(a.ctx_ref(), a.as_ast(), p.params), a.ctx)
else:
return _to_expr_ref(Z3_simplify(a.ctx_ref(), a.as_ast()), a.ctx)
def help_simplify():
"""Return a string describing all options available for Z3 `simplify` procedure."""
print(Z3_simplify_get_help(main_ctx().ref()))
def simplify_param_descrs():
"""Return the set of parameter descriptions for Z3 `simplify` procedure."""
return ParamDescrsRef(Z3_simplify_get_param_descrs(main_ctx().ref()), main_ctx())
def substitute(t, *m):
"""Apply substitution m on t, m is a list of pairs of the form (from, to). Every occurrence in t of from is replaced with to.
>>> x = Int('x')
>>> y = Int('y')
>>> substitute(x + 1, (x, y + 1))
y + 1 + 1
>>> f = Function('f', IntSort(), IntSort())
>>> substitute(f(x) + f(y), (f(x), IntVal(1)), (f(y), IntVal(1)))
1 + 1
"""
if isinstance(m, tuple):
m1 = _get_args(m)
if isinstance(m1, list) and all(isinstance(p, tuple) for p in m1):
m = m1
if __debug__:
_z3_assert(is_expr(t), "Z3 expression expected")
_z3_assert(all([isinstance(p, tuple) and is_expr(p[0]) and is_expr(p[1]) and p[0].sort().eq(p[1].sort()) for p in m]), "Z3 invalid substitution, expression pairs expected.")
num = len(m)
_from = (Ast * num)()
_to = (Ast * num)()
for i in range(num):
_from[i] = m[i][0].as_ast()
_to[i] = m[i][1].as_ast()
return _to_expr_ref(Z3_substitute(t.ctx.ref(), t.as_ast(), num, _from, _to), t.ctx)
def substitute_vars(t, *m):
"""Substitute the free variables in t with the expression in m.
>>> v0 = Var(0, IntSort())
>>> v1 = Var(1, IntSort())
>>> x = Int('x')
>>> f = Function('f', IntSort(), IntSort(), IntSort())
>>> # replace v0 with x+1 and v1 with x
>>> substitute_vars(f(v0, v1), x + 1, x)
f(x + 1, x)
"""
if __debug__:
_z3_assert(is_expr(t), "Z3 expression expected")
_z3_assert(all([is_expr(n) for n in m]), "Z3 invalid substitution, list of expressions expected.")
num = len(m)
_to = (Ast * num)()
for i in range(num):
_to[i] = m[i].as_ast()
return _to_expr_ref(Z3_substitute_vars(t.ctx.ref(), t.as_ast(), num, _to), t.ctx)
def Sum(*args):
"""Create the sum of the Z3 expressions.
>>> a, b, c = Ints('a b c')
>>> Sum(a, b, c)
a + b + c
>>> Sum([a, b, c])
a + b + c
>>> A = IntVector('a', 5)
>>> Sum(A)
a__0 + a__1 + a__2 + a__3 + a__4
"""
args = _get_args(args)
if len(args) == 0:
return 0
ctx = _ctx_from_ast_arg_list(args)
if ctx is None:
return _reduce(lambda a, b: a + b, args, 0)
args = _coerce_expr_list(args, ctx)
if is_bv(args[0]):
return _reduce(lambda a, b: a + b, args, 0)
else:
_args, sz = _to_ast_array(args)
return ArithRef(Z3_mk_add(ctx.ref(), sz, _args), ctx)
def Product(*args):
"""Create the product of the Z3 expressions.
>>> a, b, c = Ints('a b c')
>>> Product(a, b, c)
a*b*c
>>> Product([a, b, c])
a*b*c
>>> A = IntVector('a', 5)
>>> Product(A)
a__0*a__1*a__2*a__3*a__4
"""
args = _get_args(args)
if len(args) == 0:
return 1
ctx = _ctx_from_ast_arg_list(args)
if ctx is None:
return _reduce(lambda a, b: a * b, args, 1)
args = _coerce_expr_list(args, ctx)
if is_bv(args[0]):
return _reduce(lambda a, b: a * b, args, 1)
else:
_args, sz = _to_ast_array(args)
return ArithRef(Z3_mk_mul(ctx.ref(), sz, _args), ctx)
def AtMost(*args):
"""Create an at-most Pseudo-Boolean k constraint.
>>> a, b, c = Bools('a b c')
>>> f = AtMost(a, b, c, 2)
"""
args = _get_args(args)
if __debug__:
_z3_assert(len(args) > 1, "Non empty list of arguments expected")
ctx = _ctx_from_ast_arg_list(args)
if __debug__:
_z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
args1 = _coerce_expr_list(args[:-1], ctx)
k = args[-1]
_args, sz = _to_ast_array(args1)
return BoolRef(Z3_mk_atmost(ctx.ref(), sz, _args, k), ctx)
def AtLeast(*args):
"""Create an at-most Pseudo-Boolean k constraint.
>>> a, b, c = Bools('a b c')
>>> f = AtLeast(a, b, c, 2)
"""
args = _get_args(args)
if __debug__:
_z3_assert(len(args) > 1, "Non empty list of arguments expected")
ctx = _ctx_from_ast_arg_list(args)
if __debug__:
_z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
args1 = _coerce_expr_list(args[:-1], ctx)
k = args[-1]
_args, sz = _to_ast_array(args1)
return BoolRef(Z3_mk_atleast(ctx.ref(), sz, _args, k), ctx)
def _pb_args_coeffs(args, default_ctx = None):
args = _get_args_ast_list(args)
if len(args) == 0:
return _get_ctx(default_ctx), 0, (Ast * 0)(), (ctypes.c_int * 0)()
args, coeffs = zip(*args)
if __debug__:
_z3_assert(len(args) > 0, "Non empty list of arguments expected")
ctx = _ctx_from_ast_arg_list(args)
if __debug__:
_z3_assert(ctx is not None, "At least one of the arguments must be a Z3 expression")
args = _coerce_expr_list(args, ctx)
_args, sz = _to_ast_array(args)
_coeffs = (ctypes.c_int * len(coeffs))()
for i in range(len(coeffs)):
_z3_check_cint_overflow(coeffs[i], "coefficient")
_coeffs[i] = coeffs[i]
return ctx, sz, _args, _coeffs
def PbLe(args, k):
"""Create a Pseudo-Boolean inequality k constraint.
>>> a, b, c = Bools('a b c')
>>> f = PbLe(((a,1),(b,3),(c,2)), 3)
"""
_z3_check_cint_overflow(k, "k")
ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
return BoolRef(Z3_mk_pble(ctx.ref(), sz, _args, _coeffs, k), ctx)
def PbGe(args, k):
"""Create a Pseudo-Boolean inequality k constraint.
>>> a, b, c = Bools('a b c')
>>> f = PbGe(((a,1),(b,3),(c,2)), 3)
"""
_z3_check_cint_overflow(k, "k")
ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
return BoolRef(Z3_mk_pbge(ctx.ref(), sz, _args, _coeffs, k), ctx)
def PbEq(args, k, ctx = None):
"""Create a Pseudo-Boolean inequality k constraint.
>>> a, b, c = Bools('a b c')
>>> f = PbEq(((a,1),(b,3),(c,2)), 3)
"""
_z3_check_cint_overflow(k, "k")
ctx, sz, _args, _coeffs = _pb_args_coeffs(args)
return BoolRef(Z3_mk_pbeq(ctx.ref(), sz, _args, _coeffs, k), ctx)
def solve(*args, **keywords):
"""Solve the constraints `*args`.
This is a simple function for creating demonstrations. It creates a solver,
configure it using the options in `keywords`, adds the constraints
in `args`, and invokes check.
>>> a = Int('a')
>>> solve(a > 0, a < 2)
[a = 1]
"""
s = Solver()
s.set(**keywords)
s.add(*args)
if keywords.get('show', False):
print(s)
r = s.check()
if r == unsat:
print("no solution")
elif r == unknown:
print("failed to solve")
try:
print(s.model())
except Z3Exception:
return
else:
print(s.model())
def solve_using(s, *args, **keywords):
"""Solve the constraints `*args` using solver `s`.
This is a simple function for creating demonstrations. It is similar to `solve`,
but it uses the given solver `s`.
It configures solver `s` using the options in `keywords`, adds the constraints
in `args`, and invokes check.
"""
if __debug__:
_z3_assert(isinstance(s, Solver), "Solver object expected")
s.set(**keywords)
s.add(*args)
if keywords.get('show', False):
print("Problem:")
print(s)
r = s.check()
if r == unsat:
print("no solution")
elif r == unknown:
print("failed to solve")
try:
print(s.model())
except Z3Exception:
return
else:
if keywords.get('show', False):
print("Solution:")
print(s.model())
def prove(claim, **keywords):
"""Try to prove the given claim.
This is a simple function for creating demonstrations. It tries to prove
`claim` by showing the negation is unsatisfiable.
>>> p, q = Bools('p q')
>>> prove(Not(And(p, q)) == Or(Not(p), Not(q)))
proved
"""
if __debug__:
_z3_assert(is_bool(claim), "Z3 Boolean expression expected")
s = Solver()
s.set(**keywords)
s.add(Not(claim))
if keywords.get('show', False):
print(s)
r = s.check()
if r == unsat:
print("proved")
elif r == unknown:
print("failed to prove")
print(s.model())
else:
print("counterexample")
print(s.model())
def _solve_html(*args, **keywords):
"""Version of function `solve` used in RiSE4Fun."""
s = Solver()
s.set(**keywords)
s.add(*args)
if keywords.get('show', False):
print("<b>Problem:</b>")
print(s)
r = s.check()
if r == unsat:
print("<b>no solution</b>")
elif r == unknown:
print("<b>failed to solve</b>")
try:
print(s.model())
except Z3Exception:
return
else:
if keywords.get('show', False):
print("<b>Solution:</b>")
print(s.model())
def _solve_using_html(s, *args, **keywords):
"""Version of function `solve_using` used in RiSE4Fun."""
if __debug__:
_z3_assert(isinstance(s, Solver), "Solver object expected")
s.set(**keywords)
s.add(*args)
if keywords.get('show', False):
print("<b>Problem:</b>")
print(s)
r = s.check()
if r == unsat:
print("<b>no solution</b>")
elif r == unknown:
print("<b>failed to solve</b>")
try:
print(s.model())
except Z3Exception:
return
else:
if keywords.get('show', False):
print("<b>Solution:</b>")
print(s.model())
def _prove_html(claim, **keywords):
"""Version of function `prove` used in RiSE4Fun."""
if __debug__:
_z3_assert(is_bool(claim), "Z3 Boolean expression expected")
s = Solver()
s.set(**keywords)
s.add(Not(claim))
if keywords.get('show', False):
print(s)
r = s.check()
if r == unsat:
print("<b>proved</b>")
elif r == unknown:
print("<b>failed to prove</b>")
print(s.model())
else:
print("<b>counterexample</b>")
print(s.model())
def _dict2sarray(sorts, ctx):
sz = len(sorts)
_names = (Symbol * sz)()
_sorts = (Sort * sz) ()
i = 0
for k in sorts:
v = sorts[k]
if __debug__:
_z3_assert(isinstance(k, str), "String expected")
_z3_assert(is_sort(v), "Z3 sort expected")
_names[i] = to_symbol(k, ctx)
_sorts[i] = v.ast
i = i + 1
return sz, _names, _sorts
def _dict2darray(decls, ctx):
sz = len(decls)
_names = (Symbol * sz)()
_decls = (FuncDecl * sz) ()
i = 0
for k in decls:
v = decls[k]
if __debug__:
_z3_assert(isinstance(k, str), "String expected")
_z3_assert(is_func_decl(v) or is_const(v), "Z3 declaration or constant expected")
_names[i] = to_symbol(k, ctx)
if is_const(v):
_decls[i] = v.decl().ast
else:
_decls[i] = v.ast
i = i + 1
return sz, _names, _decls
def parse_smt2_string(s, sorts={}, decls={}, ctx=None):
"""Parse a string in SMT 2.0 format using the given sorts and decls.
The arguments sorts and decls are Python dictionaries used to initialize
the symbol table used for the SMT 2.0 parser.
>>> parse_smt2_string('(declare-const x Int) (assert (> x 0)) (assert (< x 10))')
[x > 0, x < 10]
>>> x, y = Ints('x y')
>>> f = Function('f', IntSort(), IntSort())
>>> parse_smt2_string('(assert (> (+ foo (g bar)) 0))', decls={ 'foo' : x, 'bar' : y, 'g' : f})
[x + f(y) > 0]
>>> parse_smt2_string('(declare-const a U) (assert (> a 0))', sorts={ 'U' : IntSort() })
[a > 0]
"""
ctx = _get_ctx(ctx)
ssz, snames, ssorts = _dict2sarray(sorts, ctx)
dsz, dnames, ddecls = _dict2darray(decls, ctx)
return AstVector(Z3_parse_smtlib2_string(ctx.ref(), s, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
def parse_smt2_file(f, sorts={}, decls={}, ctx=None):
"""Parse a file in SMT 2.0 format using the given sorts and decls.
This function is similar to parse_smt2_string().
"""
ctx = _get_ctx(ctx)
ssz, snames, ssorts = _dict2sarray(sorts, ctx)
dsz, dnames, ddecls = _dict2darray(decls, ctx)
return AstVector(Z3_parse_smtlib2_file(ctx.ref(), f, ssz, snames, ssorts, dsz, dnames, ddecls), ctx)
#########################################
#
# Floating-Point Arithmetic
#
#########################################
# Global default rounding mode
_dflt_rounding_mode = Z3_OP_FPA_RM_TOWARD_ZERO
_dflt_fpsort_ebits = 11
_dflt_fpsort_sbits = 53
def get_default_rounding_mode(ctx=None):
"""Retrieves the global default rounding mode."""
global _dflt_rounding_mode
if _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO:
return RTZ(ctx)
elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE:
return RTN(ctx)
elif _dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE:
return RTP(ctx)
elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
return RNE(ctx)
elif _dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
return RNA(ctx)
def set_default_rounding_mode(rm, ctx=None):
global _dflt_rounding_mode
if is_fprm_value(rm):
_dflt_rounding_mode = rm.decl().kind()
else:
_z3_assert(_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_ZERO or
_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_NEGATIVE or
_dflt_rounding_mode == Z3_OP_FPA_RM_TOWARD_POSITIVE or
_dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN or
_dflt_rounding_mode == Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY,
"illegal rounding mode")
_dflt_rounding_mode = rm
def get_default_fp_sort(ctx=None):
return FPSort(_dflt_fpsort_ebits, _dflt_fpsort_sbits, ctx)
def set_default_fp_sort(ebits, sbits, ctx=None):
global _dflt_fpsort_ebits
global _dflt_fpsort_sbits
_dflt_fpsort_ebits = ebits
_dflt_fpsort_sbits = sbits
def _dflt_rm(ctx=None):
return get_default_rounding_mode(ctx)
def _dflt_fps(ctx=None):
return get_default_fp_sort(ctx)
def _coerce_fp_expr_list(alist, ctx):
first_fp_sort = None
for a in alist:
if is_fp(a):
if first_fp_sort is None:
first_fp_sort = a.sort()
elif first_fp_sort == a.sort():
pass # OK, same as before
else:
# we saw at least 2 different float sorts; something will
# throw a sort mismatch later, for now assume None.
first_fp_sort = None
break
r = []
for i in range(len(alist)):
a = alist[i]
if (isinstance(a, str) and a.contains('2**(') and a.endswith(')')) or _is_int(a) or isinstance(a, float) or isinstance(a, bool):
r.append(FPVal(a, None, first_fp_sort, ctx))
else:
r.append(a)
return _coerce_expr_list(r, ctx)
### FP Sorts
class FPSortRef(SortRef):
"""Floating-point sort."""
def ebits(self):
"""Retrieves the number of bits reserved for the exponent in the FloatingPoint sort `self`.
>>> b = FPSort(8, 24)
>>> b.ebits()
8
"""
return int(Z3_fpa_get_ebits(self.ctx_ref(), self.ast))
def sbits(self):
"""Retrieves the number of bits reserved for the significand in the FloatingPoint sort `self`.
>>> b = FPSort(8, 24)
>>> b.sbits()
24
"""
return int(Z3_fpa_get_sbits(self.ctx_ref(), self.ast))
def cast(self, val):
"""Try to cast `val` as a floating-point expression.
>>> b = FPSort(8, 24)
>>> b.cast(1.0)
1
>>> b.cast(1.0).sexpr()
'(fp #b0 #x7f #b00000000000000000000000)'
"""
if is_expr(val):
if __debug__:
_z3_assert(self.ctx == val.ctx, "Context mismatch")
return val
else:
return FPVal(val, None, self, self.ctx)
def Float16(ctx=None):
"""Floating-point 16-bit (half) sort."""
ctx = _get_ctx(ctx)
return FPSortRef(Z3_mk_fpa_sort_16(ctx.ref()), ctx)
def FloatHalf(ctx=None):
"""Floating-point 16-bit (half) sort."""
ctx = _get_ctx(ctx)
return FPSortRef(Z3_mk_fpa_sort_half(ctx.ref()), ctx)
def Float32(ctx=None):
"""Floating-point 32-bit (single) sort."""
ctx = _get_ctx(ctx)
return FPSortRef(Z3_mk_fpa_sort_32(ctx.ref()), ctx)
def FloatSingle(ctx=None):
"""Floating-point 32-bit (single) sort."""
ctx = _get_ctx(ctx)
return FPSortRef(Z3_mk_fpa_sort_single(ctx.ref()), ctx)
def Float64(ctx=None):
"""Floating-point 64-bit (double) sort."""
ctx = _get_ctx(ctx)
return FPSortRef(Z3_mk_fpa_sort_64(ctx.ref()), ctx)
def FloatDouble(ctx=None):
"""Floating-point 64-bit (double) sort."""
ctx = _get_ctx(ctx)
return FPSortRef(Z3_mk_fpa_sort_double(ctx.ref()), ctx)
def Float128(ctx=None):
"""Floating-point 128-bit (quadruple) sort."""
ctx = _get_ctx(ctx)
return FPSortRef(Z3_mk_fpa_sort_128(ctx.ref()), ctx)
def FloatQuadruple(ctx=None):
"""Floating-point 128-bit (quadruple) sort."""
ctx = _get_ctx(ctx)
return FPSortRef(Z3_mk_fpa_sort_quadruple(ctx.ref()), ctx)
class FPRMSortRef(SortRef):
""""Floating-point rounding mode sort."""
def is_fp_sort(s):
"""Return True if `s` is a Z3 floating-point sort.
>>> is_fp_sort(FPSort(8, 24))
True
>>> is_fp_sort(IntSort())
False
"""
return isinstance(s, FPSortRef)
def is_fprm_sort(s):
"""Return True if `s` is a Z3 floating-point rounding mode sort.
>>> is_fprm_sort(FPSort(8, 24))
False
>>> is_fprm_sort(RNE().sort())
True
"""
return isinstance(s, FPRMSortRef)
### FP Expressions
class FPRef(ExprRef):
"""Floating-point expressions."""
def sort(self):
"""Return the sort of the floating-point expression `self`.
>>> x = FP('1.0', FPSort(8, 24))
>>> x.sort()
FPSort(8, 24)
>>> x.sort() == FPSort(8, 24)
True
"""
return FPSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
def ebits(self):
"""Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
>>> b = FPSort(8, 24)
>>> b.ebits()
8
"""
return self.sort().ebits();
def sbits(self):
"""Retrieves the number of bits reserved for the exponent in the FloatingPoint expression `self`.
>>> b = FPSort(8, 24)
>>> b.sbits()
24
"""
return self.sort().sbits();
def as_string(self):
"""Return a Z3 floating point expression as a Python string."""
return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
def __le__(self, other):
return fpLEQ(self, other, self.ctx)
def __lt__(self, other):
return fpLT(self, other, self.ctx)
def __ge__(self, other):
return fpGEQ(self, other, self.ctx)
def __gt__(self, other):
return fpGT(self, other, self.ctx)
def __add__(self, other):
"""Create the Z3 expression `self + other`.
>>> x = FP('x', FPSort(8, 24))
>>> y = FP('y', FPSort(8, 24))
>>> x + y
x + y
>>> (x + y).sort()
FPSort(8, 24)
"""
[a, b] = _coerce_fp_expr_list([self, other], self.ctx)
return fpAdd(_dflt_rm(), a, b, self.ctx)
def __radd__(self, other):
"""Create the Z3 expression `other + self`.
>>> x = FP('x', FPSort(8, 24))
>>> 10 + x
1.25*(2**3) + x
"""
[a, b] = _coerce_fp_expr_list([other, self], self.ctx)
return fpAdd(_dflt_rm(), a, b, self.ctx)
def __sub__(self, other):
"""Create the Z3 expression `self - other`.
>>> x = FP('x', FPSort(8, 24))
>>> y = FP('y', FPSort(8, 24))
>>> x - y
x - y
>>> (x - y).sort()
FPSort(8, 24)
"""
[a, b] = _coerce_fp_expr_list([self, other], self.ctx)
return fpSub(_dflt_rm(), a, b, self.ctx)
def __rsub__(self, other):
"""Create the Z3 expression `other - self`.
>>> x = FP('x', FPSort(8, 24))
>>> 10 - x
1.25*(2**3) - x
"""
[a, b] = _coerce_fp_expr_list([other, self], self.ctx)
return fpSub(_dflt_rm(), a, b, self.ctx)
def __mul__(self, other):
"""Create the Z3 expression `self * other`.
>>> x = FP('x', FPSort(8, 24))
>>> y = FP('y', FPSort(8, 24))
>>> x * y
x * y
>>> (x * y).sort()
FPSort(8, 24)
>>> 10 * y
1.25*(2**3) * y
"""
[a, b] = _coerce_fp_expr_list([self, other], self.ctx)
return fpMul(_dflt_rm(), a, b, self.ctx)
def __rmul__(self, other):
"""Create the Z3 expression `other * self`.
>>> x = FP('x', FPSort(8, 24))
>>> y = FP('y', FPSort(8, 24))
>>> x * y
x * y
>>> x * 10
x * 1.25*(2**3)
"""
[a, b] = _coerce_fp_expr_list([other, self], self.ctx)
return fpMul(_dflt_rm(), a, b, self.ctx)
def __pos__(self):
"""Create the Z3 expression `+self`."""
return self
def __neg__(self):
"""Create the Z3 expression `-self`.
>>> x = FP('x', Float32())
>>> -x
-x
"""
return fpNeg(self)
def __div__(self, other):
"""Create the Z3 expression `self / other`.
>>> x = FP('x', FPSort(8, 24))
>>> y = FP('y', FPSort(8, 24))
>>> x / y
x / y
>>> (x / y).sort()
FPSort(8, 24)
>>> 10 / y
1.25*(2**3) / y
"""
[a, b] = _coerce_fp_expr_list([self, other], self.ctx)
return fpDiv(_dflt_rm(), a, b, self.ctx)
def __rdiv__(self, other):
"""Create the Z3 expression `other / self`.
>>> x = FP('x', FPSort(8, 24))
>>> y = FP('y', FPSort(8, 24))
>>> x / y
x / y
>>> x / 10
x / 1.25*(2**3)
"""
[a, b] = _coerce_fp_expr_list([other, self], self.ctx)
return fpDiv(_dflt_rm(), a, b, self.ctx)
if not sys.version < '3':
def __truediv__(self, other):
"""Create the Z3 expression division `self / other`."""
return self.__div__(other)
def __rtruediv__(self, other):
"""Create the Z3 expression division `other / self`."""
return self.__rdiv__(other)
def __mod__(self, other):
"""Create the Z3 expression mod `self % other`."""
return fpRem(self, other)
def __rmod__(self, other):
"""Create the Z3 expression mod `other % self`."""
return fpRem(other, self)
class FPRMRef(ExprRef):
"""Floating-point rounding mode expressions"""
def as_string(self):
"""Return a Z3 floating point expression as a Python string."""
return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
def RoundNearestTiesToEven(ctx=None):
ctx = _get_ctx(ctx)
return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
def RNE (ctx=None):
ctx = _get_ctx(ctx)
return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_even(ctx.ref()), ctx)
def RoundNearestTiesToAway(ctx=None):
ctx = _get_ctx(ctx)
return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
def RNA (ctx=None):
ctx = _get_ctx(ctx)
return FPRMRef(Z3_mk_fpa_round_nearest_ties_to_away(ctx.ref()), ctx)
def RoundTowardPositive(ctx=None):
ctx = _get_ctx(ctx)
return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
def RTP(ctx=None):
ctx = _get_ctx(ctx)
return FPRMRef(Z3_mk_fpa_round_toward_positive(ctx.ref()), ctx)
def RoundTowardNegative(ctx=None):
ctx = _get_ctx(ctx)
return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
def RTN(ctx=None):
ctx = _get_ctx(ctx)
return FPRMRef(Z3_mk_fpa_round_toward_negative(ctx.ref()), ctx)
def RoundTowardZero(ctx=None):
ctx = _get_ctx(ctx)
return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
def RTZ(ctx=None):
ctx = _get_ctx(ctx)
return FPRMRef(Z3_mk_fpa_round_toward_zero(ctx.ref()), ctx)
def is_fprm(a):
"""Return `True` if `a` is a Z3 floating-point rounding mode expression.
>>> rm = RNE()
>>> is_fprm(rm)
True
>>> rm = 1.0
>>> is_fprm(rm)
False
"""
return isinstance(a, FPRMRef)
def is_fprm_value(a):
"""Return `True` if `a` is a Z3 floating-point rounding mode numeral value."""
return is_fprm(a) and _is_numeral(a.ctx, a.ast)
### FP Numerals
class FPNumRef(FPRef):
"""The sign of the numeral.
>>> x = FPVal(+1.0, FPSort(8, 24))
>>> x.sign()
False
>>> x = FPVal(-1.0, FPSort(8, 24))
>>> x.sign()
True
"""
def sign(self):
l = (ctypes.c_int)()
if Z3_fpa_get_numeral_sign(self.ctx.ref(), self.as_ast(), byref(l)) == False:
raise Z3Exception("error retrieving the sign of a numeral.")
return l.value != 0
"""The sign of a floating-point numeral as a bit-vector expression.
Remark: NaN's are invalid arguments.
"""
def sign_as_bv(self):
return BitVecNumRef(Z3_fpa_get_numeral_sign_bv(self.ctx.ref(), self.as_ast()), self.ctx)
"""The significand of the numeral.
>>> x = FPVal(2.5, FPSort(8, 24))
>>> x.significand()
1.25
"""
def significand(self):
return Z3_fpa_get_numeral_significand_string(self.ctx.ref(), self.as_ast())
"""The significand of the numeral as a long.
>>> x = FPVal(2.5, FPSort(8, 24))
>>> x.significand_as_long()
1.25
"""
def significand_as_long(self):
ptr = (ctypes.c_ulonglong * 1)()
if not Z3_fpa_get_numeral_significand_uint64(self.ctx.ref(), self.as_ast(), ptr):
raise Z3Exception("error retrieving the significand of a numeral.")
return ptr[0]
"""The significand of the numeral as a bit-vector expression.
Remark: NaN are invalid arguments.
"""
def significand_as_bv(self):
return BitVecNumRef(Z3_fpa_get_numeral_significand_bv(self.ctx.ref(), self.as_ast()), self.ctx)
"""The exponent of the numeral.
>>> x = FPVal(2.5, FPSort(8, 24))
>>> x.exponent()
1
"""
def exponent(self, biased=True):
return Z3_fpa_get_numeral_exponent_string(self.ctx.ref(), self.as_ast(), biased)
"""The exponent of the numeral as a long.
>>> x = FPVal(2.5, FPSort(8, 24))
>>> x.exponent_as_long()
1
"""
def exponent_as_long(self, biased=True):
ptr = (ctypes.c_longlong * 1)()
if not Z3_fpa_get_numeral_exponent_int64(self.ctx.ref(), self.as_ast(), ptr, biased):
raise Z3Exception("error retrieving the exponent of a numeral.")
return ptr[0]
"""The exponent of the numeral as a bit-vector expression.
Remark: NaNs are invalid arguments.
"""
def exponent_as_bv(self, biased=True):
return BitVecNumRef(Z3_fpa_get_numeral_exponent_bv(self.ctx.ref(), self.as_ast(), biased), self.ctx)
"""Indicates whether the numeral is a NaN."""
def isNaN(self):
return Z3_fpa_is_numeral_nan(self.ctx.ref(), self.as_ast())
"""Indicates whether the numeral is +oo or -oo."""
def isInf(self):
return Z3_fpa_is_numeral_inf(self.ctx.ref(), self.as_ast())
"""Indicates whether the numeral is +zero or -zero."""
def isZero(self):
return Z3_fpa_is_numeral_zero(self.ctx.ref(), self.as_ast())
"""Indicates whether the numeral is normal."""
def isNormal(self):
return Z3_fpa_is_numeral_normal(self.ctx.ref(), self.as_ast())
"""Indicates whether the numeral is subnormal."""
def isSubnormal(self):
return Z3_fpa_is_numeral_subnormal(self.ctx.ref(), self.as_ast())
"""Indicates whether the numeral is positive."""
def isPositive(self):
return Z3_fpa_is_numeral_positive(self.ctx.ref(), self.as_ast())
"""Indicates whether the numeral is negative."""
def isNegative(self):
return Z3_fpa_is_numeral_negative(self.ctx.ref(), self.as_ast())
"""
The string representation of the numeral.
>>> x = FPVal(20, FPSort(8, 24))
>>> x.as_string()
1.25*(2**4)
"""
def as_string(self):
s = Z3_get_numeral_string(self.ctx.ref(), self.as_ast())
return ("FPVal(%s, %s)" % (s, self.sort()))
def is_fp(a):
"""Return `True` if `a` is a Z3 floating-point expression.
>>> b = FP('b', FPSort(8, 24))
>>> is_fp(b)
True
>>> is_fp(b + 1.0)
True
>>> is_fp(Int('x'))
False
"""
return isinstance(a, FPRef)
def is_fp_value(a):
"""Return `True` if `a` is a Z3 floating-point numeral value.
>>> b = FP('b', FPSort(8, 24))
>>> is_fp_value(b)
False
>>> b = FPVal(1.0, FPSort(8, 24))
>>> b
1
>>> is_fp_value(b)
True
"""
return is_fp(a) and _is_numeral(a.ctx, a.ast)
def FPSort(ebits, sbits, ctx=None):
"""Return a Z3 floating-point sort of the given sizes. If `ctx=None`, then the global context is used.
>>> Single = FPSort(8, 24)
>>> Double = FPSort(11, 53)
>>> Single
FPSort(8, 24)
>>> x = Const('x', Single)
>>> eq(x, FP('x', FPSort(8, 24)))
True
"""
ctx = _get_ctx(ctx)
return FPSortRef(Z3_mk_fpa_sort(ctx.ref(), ebits, sbits), ctx)
def _to_float_str(val, exp=0):
if isinstance(val, float):
if math.isnan(val):
res = "NaN"
elif val == 0.0:
sone = math.copysign(1.0, val)
if sone < 0.0:
return "-0.0"
else:
return "+0.0"
elif val == float("+inf"):
res = "+oo"
elif val == float("-inf"):
res = "-oo"
else:
v = val.as_integer_ratio()
num = v[0]
den = v[1]
rvs = str(num) + '/' + str(den)
res = rvs + 'p' + _to_int_str(exp)
elif isinstance(val, bool):
if val:
res = "1.0"
else:
res = "0.0"
elif _is_int(val):
res = str(val)
elif isinstance(val, str):
inx = val.find('*(2**')
if inx == -1:
res = val
elif val[-1] == ')':
res = val[0:inx]
exp = str(int(val[inx+5:-1]) + int(exp))
else:
_z3_assert(False, "String does not have floating-point numeral form.")
elif __debug__:
_z3_assert(False, "Python value cannot be used to create floating-point numerals.")
if exp == 0:
return res
else:
return res + 'p' + exp
def fpNaN(s):
"""Create a Z3 floating-point NaN term.
>>> s = FPSort(8, 24)
>>> set_fpa_pretty(True)
>>> fpNaN(s)
NaN
>>> pb = get_fpa_pretty()
>>> set_fpa_pretty(False)
>>> fpNaN(s)
fpNaN(FPSort(8, 24))
>>> set_fpa_pretty(pb)
"""
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
return FPNumRef(Z3_mk_fpa_nan(s.ctx_ref(), s.ast), s.ctx)
def fpPlusInfinity(s):
"""Create a Z3 floating-point +oo term.
>>> s = FPSort(8, 24)
>>> pb = get_fpa_pretty()
>>> set_fpa_pretty(True)
>>> fpPlusInfinity(s)
+oo
>>> set_fpa_pretty(False)
>>> fpPlusInfinity(s)
fpPlusInfinity(FPSort(8, 24))
>>> set_fpa_pretty(pb)
"""
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, False), s.ctx)
def fpMinusInfinity(s):
"""Create a Z3 floating-point -oo term."""
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, True), s.ctx)
def fpInfinity(s, negative):
"""Create a Z3 floating-point +oo or -oo term."""
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
_z3_assert(isinstance(negative, bool), "expected Boolean flag")
return FPNumRef(Z3_mk_fpa_inf(s.ctx_ref(), s.ast, negative), s.ctx)
def fpPlusZero(s):
"""Create a Z3 floating-point +0.0 term."""
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, False), s.ctx)
def fpMinusZero(s):
"""Create a Z3 floating-point -0.0 term."""
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, True), s.ctx)
def fpZero(s, negative):
"""Create a Z3 floating-point +0.0 or -0.0 term."""
_z3_assert(isinstance(s, FPSortRef), "sort mismatch")
_z3_assert(isinstance(negative, bool), "expected Boolean flag")
return FPNumRef(Z3_mk_fpa_zero(s.ctx_ref(), s.ast, negative), s.ctx)
def FPVal(sig, exp=None, fps=None, ctx=None):
"""Return a floating-point value of value `val` and sort `fps`. If `ctx=None`, then the global context is used.
>>> v = FPVal(20.0, FPSort(8, 24))
>>> v
1.25*(2**4)
>>> print("0x%.8x" % v.exponent_as_long(False))
0x00000004
>>> v = FPVal(2.25, FPSort(8, 24))
>>> v
1.125*(2**1)
>>> v = FPVal(-2.25, FPSort(8, 24))
>>> v
-1.125*(2**1)
>>> FPVal(-0.0, FPSort(8, 24))
-0.0
>>> FPVal(0.0, FPSort(8, 24))
+0.0
>>> FPVal(+0.0, FPSort(8, 24))
+0.0
"""
ctx = _get_ctx(ctx)
if is_fp_sort(exp):
fps = exp
exp = None
elif fps is None:
fps = _dflt_fps(ctx)
_z3_assert(is_fp_sort(fps), "sort mismatch")
if exp is None:
exp = 0
val = _to_float_str(sig)
if val == "NaN" or val == "nan":
return fpNaN(fps)
elif val == "-0.0":
return fpMinusZero(fps)
elif val == "0.0" or val == "+0.0":
return fpPlusZero(fps)
elif val == "+oo" or val == "+inf" or val == "+Inf":
return fpPlusInfinity(fps)
elif val == "-oo" or val == "-inf" or val == "-Inf":
return fpMinusInfinity(fps)
else:
return FPNumRef(Z3_mk_numeral(ctx.ref(), val, fps.ast), ctx)
def FP(name, fpsort, ctx=None):
"""Return a floating-point constant named `name`.
`fpsort` is the floating-point sort.
If `ctx=None`, then the global context is used.
>>> x = FP('x', FPSort(8, 24))
>>> is_fp(x)
True
>>> x.ebits()
8
>>> x.sort()
FPSort(8, 24)
>>> word = FPSort(8, 24)
>>> x2 = FP('x', word)
>>> eq(x, x2)
True
"""
if isinstance(fpsort, FPSortRef) and ctx is None:
ctx = fpsort.ctx
else:
ctx = _get_ctx(ctx)
return FPRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), fpsort.ast), ctx)
def FPs(names, fpsort, ctx=None):
"""Return an array of floating-point constants.
>>> x, y, z = FPs('x y z', FPSort(8, 24))
>>> x.sort()
FPSort(8, 24)
>>> x.sbits()
24
>>> x.ebits()
8
>>> fpMul(RNE(), fpAdd(RNE(), x, y), z)
fpMul(RNE(), fpAdd(RNE(), x, y), z)
"""
ctx = _get_ctx(ctx)
if isinstance(names, str):
names = names.split(" ")
return [FP(name, fpsort, ctx) for name in names]
def fpAbs(a, ctx=None):
"""Create a Z3 floating-point absolute value expression.
>>> s = FPSort(8, 24)
>>> rm = RNE()
>>> x = FPVal(1.0, s)
>>> fpAbs(x)
fpAbs(1)
>>> y = FPVal(-20.0, s)
>>> y
-1.25*(2**4)
>>> fpAbs(y)
fpAbs(-1.25*(2**4))
>>> fpAbs(-1.25*(2**4))
fpAbs(-1.25*(2**4))
>>> fpAbs(x).sort()
FPSort(8, 24)
"""
ctx = _get_ctx(ctx)
[a] = _coerce_fp_expr_list([a], ctx)
return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
def fpNeg(a, ctx=None):
"""Create a Z3 floating-point addition expression.
>>> s = FPSort(8, 24)
>>> rm = RNE()
>>> x = FP('x', s)
>>> fpNeg(x)
-x
>>> fpNeg(x).sort()
FPSort(8, 24)
"""
ctx = _get_ctx(ctx)
[a] = _coerce_fp_expr_list([a], ctx)
return FPRef(Z3_mk_fpa_neg(ctx.ref(), a.as_ast()), ctx)
def _mk_fp_unary(f, rm, a, ctx):
ctx = _get_ctx(ctx)
[a] = _coerce_fp_expr_list([a], ctx)
if __debug__:
_z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
_z3_assert(is_fp(a), "Second argument must be a Z3 floating-point expression")
return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast()), ctx)
def _mk_fp_unary_norm(f, a, ctx):
ctx = _get_ctx(ctx)
[a] = _coerce_fp_expr_list([a], ctx)
if __debug__:
_z3_assert(is_fp(a), "First argument must be a Z3 floating-point expression")
return FPRef(f(ctx.ref(), a.as_ast()), ctx)
def _mk_fp_unary_pred(f, a, ctx):
ctx = _get_ctx(ctx)
[a] = _coerce_fp_expr_list([a], ctx)
if __debug__:
_z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
return BoolRef(f(ctx.ref(), a.as_ast()), ctx)
def _mk_fp_bin(f, rm, a, b, ctx):
ctx = _get_ctx(ctx)
[a, b] = _coerce_fp_expr_list([a, b], ctx)
if __debug__:
_z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
_z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast()), ctx)
def _mk_fp_bin_norm(f, a, b, ctx):
ctx = _get_ctx(ctx)
[a, b] = _coerce_fp_expr_list([a, b], ctx)
if __debug__:
_z3_assert(is_fp(a) or is_fp(b), "First or second argument must be a Z3 floating-point expression")
return FPRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
def _mk_fp_bin_pred(f, a, b, ctx):
ctx = _get_ctx(ctx)
[a, b] = _coerce_fp_expr_list([a, b], ctx)
if __debug__:
_z3_assert(is_fp(a) or is_fp(b), "Second or third argument must be a Z3 floating-point expression")
return BoolRef(f(ctx.ref(), a.as_ast(), b.as_ast()), ctx)
def _mk_fp_tern(f, rm, a, b, c, ctx):
ctx = _get_ctx(ctx)
[a, b, c] = _coerce_fp_expr_list([a, b, c], ctx)
if __debug__:
_z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
_z3_assert(is_fp(a) or is_fp(b) or is_fp(c), "At least one of the arguments must be a Z3 floating-point expression")
return FPRef(f(ctx.ref(), rm.as_ast(), a.as_ast(), b.as_ast(), c.as_ast()), ctx)
def fpAdd(rm, a, b, ctx=None):
"""Create a Z3 floating-point addition expression.
>>> s = FPSort(8, 24)
>>> rm = RNE()
>>> x = FP('x', s)
>>> y = FP('y', s)
>>> fpAdd(rm, x, y)
fpAdd(RNE(), x, y)
>>> fpAdd(RTZ(), x, y) # default rounding mode is RTZ
x + y
>>> fpAdd(rm, x, y).sort()
FPSort(8, 24)
"""
return _mk_fp_bin(Z3_mk_fpa_add, rm, a, b, ctx)
def fpSub(rm, a, b, ctx=None):
"""Create a Z3 floating-point subtraction expression.
>>> s = FPSort(8, 24)
>>> rm = RNE()
>>> x = FP('x', s)
>>> y = FP('y', s)
>>> fpSub(rm, x, y)
fpSub(RNE(), x, y)
>>> fpSub(rm, x, y).sort()
FPSort(8, 24)
"""
return _mk_fp_bin(Z3_mk_fpa_sub, rm, a, b, ctx)
def fpMul(rm, a, b, ctx=None):
"""Create a Z3 floating-point multiplication expression.
>>> s = FPSort(8, 24)
>>> rm = RNE()
>>> x = FP('x', s)
>>> y = FP('y', s)
>>> fpMul(rm, x, y)
fpMul(RNE(), x, y)
>>> fpMul(rm, x, y).sort()
FPSort(8, 24)
"""
return _mk_fp_bin(Z3_mk_fpa_mul, rm, a, b, ctx)
def fpDiv(rm, a, b, ctx=None):
"""Create a Z3 floating-point division expression.
>>> s = FPSort(8, 24)
>>> rm = RNE()
>>> x = FP('x', s)
>>> y = FP('y', s)
>>> fpDiv(rm, x, y)
fpDiv(RNE(), x, y)
>>> fpDiv(rm, x, y).sort()
FPSort(8, 24)
"""
return _mk_fp_bin(Z3_mk_fpa_div, rm, a, b, ctx)
def fpRem(a, b, ctx=None):
"""Create a Z3 floating-point remainder expression.
>>> s = FPSort(8, 24)
>>> x = FP('x', s)
>>> y = FP('y', s)
>>> fpRem(x, y)
fpRem(x, y)
>>> fpRem(x, y).sort()
FPSort(8, 24)
"""
return _mk_fp_bin_norm(Z3_mk_fpa_rem, a, b, ctx)
def fpMin(a, b, ctx=None):
"""Create a Z3 floating-point minimum expression.
>>> s = FPSort(8, 24)
>>> rm = RNE()
>>> x = FP('x', s)
>>> y = FP('y', s)
>>> fpMin(x, y)
fpMin(x, y)
>>> fpMin(x, y).sort()
FPSort(8, 24)
"""
return _mk_fp_bin_norm(Z3_mk_fpa_min, a, b, ctx)
def fpMax(a, b, ctx=None):
"""Create a Z3 floating-point maximum expression.
>>> s = FPSort(8, 24)
>>> rm = RNE()
>>> x = FP('x', s)
>>> y = FP('y', s)
>>> fpMax(x, y)
fpMax(x, y)
>>> fpMax(x, y).sort()
FPSort(8, 24)
"""
return _mk_fp_bin_norm(Z3_mk_fpa_max, a, b, ctx)
def fpFMA(rm, a, b, c, ctx=None):
"""Create a Z3 floating-point fused multiply-add expression.
"""
return _mk_fp_tern(Z3_mk_fpa_fma, rm, a, b, c, ctx)
def fpSqrt(rm, a, ctx=None):
"""Create a Z3 floating-point square root expression.
"""
return _mk_fp_unary(Z3_mk_fpa_sqrt, rm, a, ctx)
def fpRoundToIntegral(rm, a, ctx=None):
"""Create a Z3 floating-point roundToIntegral expression.
"""
return _mk_fp_unary(Z3_mk_fpa_round_to_integral, rm, a, ctx)
def fpIsNaN(a, ctx=None):
"""Create a Z3 floating-point isNaN expression.
>>> s = FPSort(8, 24)
>>> x = FP('x', s)
>>> y = FP('y', s)
>>> fpIsNaN(x)
fpIsNaN(x)
"""
return _mk_fp_unary_norm(Z3_mk_fpa_is_nan, a, ctx)
def fpIsInf(a, ctx=None):
"""Create a Z3 floating-point isInfinite expression.
>>> s = FPSort(8, 24)
>>> x = FP('x', s)
>>> fpIsInf(x)
fpIsInf(x)
"""
return _mk_fp_unary_norm(Z3_mk_fpa_is_infinite, a, ctx)
def fpIsZero(a, ctx=None):
"""Create a Z3 floating-point isZero expression.
"""
return _mk_fp_unary_norm(Z3_mk_fpa_is_zero, a, ctx)
def fpIsNormal(a, ctx=None):
"""Create a Z3 floating-point isNormal expression.
"""
return _mk_fp_unary_norm(Z3_mk_fpa_is_normal, a, ctx)
def fpIsSubnormal(a, ctx=None):
"""Create a Z3 floating-point isSubnormal expression.
"""
return _mk_fp_unary_norm(Z3_mk_fpa_is_subnormal, a, ctx)
def fpIsNegative(a, ctx=None):
"""Create a Z3 floating-point isNegative expression.
"""
return _mk_fp_unary_norm(Z3_mk_fpa_is_negative, a, ctx)
def fpIsPositive(a, ctx=None):
"""Create a Z3 floating-point isPositive expression.
"""
return _mk_fp_unary_norm(Z3_mk_fpa_is_positive, a, ctx)
return FPRef(Z3_mk_fpa_is_positive(a.ctx_ref(), a.as_ast()), a.ctx)
def _check_fp_args(a, b):
if __debug__:
_z3_assert(is_fp(a) or is_fp(b), "At least one of the arguments must be a Z3 floating-point expression")
def fpLT(a, b, ctx=None):
"""Create the Z3 floating-point expression `other < self`.
>>> x, y = FPs('x y', FPSort(8, 24))
>>> fpLT(x, y)
x < y
>>> (x < y).sexpr()
'(fp.lt x y)'
"""
return _mk_fp_bin_pred(Z3_mk_fpa_lt, a, b, ctx)
def fpLEQ(a, b, ctx=None):
"""Create the Z3 floating-point expression `other <= self`.
>>> x, y = FPs('x y', FPSort(8, 24))
>>> fpLEQ(x, y)
x <= y
>>> (x <= y).sexpr()
'(fp.leq x y)'
"""
return _mk_fp_bin_pred(Z3_mk_fpa_leq, a, b, ctx)
def fpGT(a, b, ctx=None):
"""Create the Z3 floating-point expression `other > self`.
>>> x, y = FPs('x y', FPSort(8, 24))
>>> fpGT(x, y)
x > y
>>> (x > y).sexpr()
'(fp.gt x y)'
"""
return _mk_fp_bin_pred(Z3_mk_fpa_gt, a, b, ctx)
def fpGEQ(a, b, ctx=None):
"""Create the Z3 floating-point expression `other >= self`.
>>> x, y = FPs('x y', FPSort(8, 24))
>>> fpGEQ(x, y)
x >= y
>>> (x >= y).sexpr()
'(fp.geq x y)'
"""
return _mk_fp_bin_pred(Z3_mk_fpa_geq, a, b, ctx)
def fpEQ(a, b, ctx=None):
"""Create the Z3 floating-point expression `fpEQ(other, self)`.
>>> x, y = FPs('x y', FPSort(8, 24))
>>> fpEQ(x, y)
fpEQ(x, y)
>>> fpEQ(x, y).sexpr()
'(fp.eq x y)'
"""
return _mk_fp_bin_pred(Z3_mk_fpa_eq, a, b, ctx)
def fpNEQ(a, b, ctx=None):
"""Create the Z3 floating-point expression `Not(fpEQ(other, self))`.
>>> x, y = FPs('x y', FPSort(8, 24))
>>> fpNEQ(x, y)
Not(fpEQ(x, y))
>>> (x != y).sexpr()
'(distinct x y)'
"""
return Not(fpEQ(a, b, ctx))
def fpFP(sgn, exp, sig, ctx=None):
"""Create the Z3 floating-point value `fpFP(sgn, sig, exp)` from the three bit-vectors sgn, sig, and exp.
>>> s = FPSort(8, 24)
>>> x = fpFP(BitVecVal(1, 1), BitVecVal(2**7-1, 8), BitVecVal(2**22, 23))
>>> print(x)
fpFP(1, 127, 4194304)
>>> xv = FPVal(-1.5, s)
>>> print(xv)
-1.5
>>> slvr = Solver()
>>> slvr.add(fpEQ(x, xv))
>>> slvr.check()
sat
>>> xv = FPVal(+1.5, s)
>>> print(xv)
1.5
>>> slvr = Solver()
>>> slvr.add(fpEQ(x, xv))
>>> slvr.check()
unsat
"""
_z3_assert(is_bv(sgn) and is_bv(exp) and is_bv(sig), "sort mismatch")
_z3_assert(sgn.sort().size() == 1, "sort mismatch")
ctx = _get_ctx(ctx)
_z3_assert(ctx == sgn.ctx == exp.ctx == sig.ctx, "context mismatch")
return FPRef(Z3_mk_fpa_fp(ctx.ref(), sgn.ast, exp.ast, sig.ast), ctx)
def fpToFP(a1, a2=None, a3=None, ctx=None):
"""Create a Z3 floating-point conversion expression from other term sorts
to floating-point.
From a bit-vector term in IEEE 754-2008 format:
>>> x = FPVal(1.0, Float32())
>>> x_bv = fpToIEEEBV(x)
>>> simplify(fpToFP(x_bv, Float32()))
1
From a floating-point term with different precision:
>>> x = FPVal(1.0, Float32())
>>> x_db = fpToFP(RNE(), x, Float64())
>>> x_db.sort()
FPSort(11, 53)
From a real term:
>>> x_r = RealVal(1.5)
>>> simplify(fpToFP(RNE(), x_r, Float32()))
1.5
From a signed bit-vector term:
>>> x_signed = BitVecVal(-5, BitVecSort(32))
>>> simplify(fpToFP(RNE(), x_signed, Float32()))
-1.25*(2**2)
"""
ctx = _get_ctx(ctx)
if is_bv(a1) and is_fp_sort(a2):
return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), a1.ast, a2.ast), ctx)
elif is_fprm(a1) and is_fp(a2) and is_fp_sort(a3):
return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
elif is_fprm(a1) and is_real(a2) and is_fp_sort(a3):
return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
elif is_fprm(a1) and is_bv(a2) and is_fp_sort(a3):
return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), a1.ast, a2.ast, a3.ast), ctx)
else:
raise Z3Exception("Unsupported combination of arguments for conversion to floating-point term.")
def fpBVToFP(v, sort, ctx=None):
"""Create a Z3 floating-point conversion expression that represents the
conversion from a bit-vector term to a floating-point term.
>>> x_bv = BitVecVal(0x3F800000, 32)
>>> x_fp = fpBVToFP(x_bv, Float32())
>>> x_fp
fpToFP(1065353216)
>>> simplify(x_fp)
1
"""
_z3_assert(is_bv(v), "First argument must be a Z3 floating-point rounding mode expression.")
_z3_assert(is_fp_sort(sort), "Second argument must be a Z3 floating-point sort.")
ctx = _get_ctx(ctx)
return FPRef(Z3_mk_fpa_to_fp_bv(ctx.ref(), v.ast, sort.ast), ctx)
def fpFPToFP(rm, v, sort, ctx=None):
"""Create a Z3 floating-point conversion expression that represents the
conversion from a floating-point term to a floating-point term of different precision.
>>> x_sgl = FPVal(1.0, Float32())
>>> x_dbl = fpFPToFP(RNE(), x_sgl, Float64())
>>> x_dbl
fpToFP(RNE(), 1)
>>> simplify(x_dbl)
1
>>> x_dbl.sort()
FPSort(11, 53)
"""
_z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
_z3_assert(is_fp(v), "Second argument must be a Z3 floating-point expression.")
_z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
ctx = _get_ctx(ctx)
return FPRef(Z3_mk_fpa_to_fp_float(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
def fpRealToFP(rm, v, sort, ctx=None):
"""Create a Z3 floating-point conversion expression that represents the
conversion from a real term to a floating-point term.
>>> x_r = RealVal(1.5)
>>> x_fp = fpRealToFP(RNE(), x_r, Float32())
>>> x_fp
fpToFP(RNE(), 3/2)
>>> simplify(x_fp)
1.5
"""
_z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
_z3_assert(is_real(v), "Second argument must be a Z3 expression or real sort.")
_z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
ctx = _get_ctx(ctx)
return FPRef(Z3_mk_fpa_to_fp_real(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
def fpSignedToFP(rm, v, sort, ctx=None):
"""Create a Z3 floating-point conversion expression that represents the
conversion from a signed bit-vector term (encoding an integer) to a floating-point term.
>>> x_signed = BitVecVal(-5, BitVecSort(32))
>>> x_fp = fpSignedToFP(RNE(), x_signed, Float32())
>>> x_fp
fpToFP(RNE(), 4294967291)
>>> simplify(x_fp)
-1.25*(2**2)
"""
_z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
_z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
_z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
ctx = _get_ctx(ctx)
return FPRef(Z3_mk_fpa_to_fp_signed(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
def fpUnsignedToFP(rm, v, sort, ctx=None):
"""Create a Z3 floating-point conversion expression that represents the
conversion from an unsigned bit-vector term (encoding an integer) to a floating-point term.
>>> x_signed = BitVecVal(-5, BitVecSort(32))
>>> x_fp = fpUnsignedToFP(RNE(), x_signed, Float32())
>>> x_fp
fpToFPUnsigned(RNE(), 4294967291)
>>> simplify(x_fp)
1*(2**32)
"""
_z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression.")
_z3_assert(is_bv(v), "Second argument must be a Z3 expression or real sort.")
_z3_assert(is_fp_sort(sort), "Third argument must be a Z3 floating-point sort.")
ctx = _get_ctx(ctx)
return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, v.ast, sort.ast), ctx)
def fpToFPUnsigned(rm, x, s, ctx=None):
"""Create a Z3 floating-point conversion expression, from unsigned bit-vector to floating-point expression."""
if __debug__:
_z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
_z3_assert(is_bv(x), "Second argument must be a Z3 bit-vector expression")
_z3_assert(is_fp_sort(s), "Third argument must be Z3 floating-point sort")
ctx = _get_ctx(ctx)
return FPRef(Z3_mk_fpa_to_fp_unsigned(ctx.ref(), rm.ast, x.ast, s.ast), ctx)
def fpToSBV(rm, x, s, ctx=None):
"""Create a Z3 floating-point conversion expression, from floating-point expression to signed bit-vector.
>>> x = FP('x', FPSort(8, 24))
>>> y = fpToSBV(RTZ(), x, BitVecSort(32))
>>> print(is_fp(x))
True
>>> print(is_bv(y))
True
>>> print(is_fp(y))
False
>>> print(is_bv(x))
False
"""
if __debug__:
_z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
_z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
_z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
ctx = _get_ctx(ctx)
return BitVecRef(Z3_mk_fpa_to_sbv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
def fpToUBV(rm, x, s, ctx=None):
"""Create a Z3 floating-point conversion expression, from floating-point expression to unsigned bit-vector.
>>> x = FP('x', FPSort(8, 24))
>>> y = fpToUBV(RTZ(), x, BitVecSort(32))
>>> print(is_fp(x))
True
>>> print(is_bv(y))
True
>>> print(is_fp(y))
False
>>> print(is_bv(x))
False
"""
if __debug__:
_z3_assert(is_fprm(rm), "First argument must be a Z3 floating-point rounding mode expression")
_z3_assert(is_fp(x), "Second argument must be a Z3 floating-point expression")
_z3_assert(is_bv_sort(s), "Third argument must be Z3 bit-vector sort")
ctx = _get_ctx(ctx)
return BitVecRef(Z3_mk_fpa_to_ubv(ctx.ref(), rm.ast, x.ast, s.size()), ctx)
def fpToReal(x, ctx=None):
"""Create a Z3 floating-point conversion expression, from floating-point expression to real.
>>> x = FP('x', FPSort(8, 24))
>>> y = fpToReal(x)
>>> print(is_fp(x))
True
>>> print(is_real(y))
True
>>> print(is_fp(y))
False
>>> print(is_real(x))
False
"""
if __debug__:
_z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
ctx = _get_ctx(ctx)
return ArithRef(Z3_mk_fpa_to_real(ctx.ref(), x.ast), ctx)
def fpToIEEEBV(x, ctx=None):
"""\brief Conversion of a floating-point term into a bit-vector term in IEEE 754-2008 format.
The size of the resulting bit-vector is automatically determined.
Note that IEEE 754-2008 allows multiple different representations of NaN. This conversion
knows only one NaN and it will always produce the same bit-vector representation of
that NaN.
>>> x = FP('x', FPSort(8, 24))
>>> y = fpToIEEEBV(x)
>>> print(is_fp(x))
True
>>> print(is_bv(y))
True
>>> print(is_fp(y))
False
>>> print(is_bv(x))
False
"""
if __debug__:
_z3_assert(is_fp(x), "First argument must be a Z3 floating-point expression")
ctx = _get_ctx(ctx)
return BitVecRef(Z3_mk_fpa_to_ieee_bv(ctx.ref(), x.ast), ctx)
#########################################
#
# Strings, Sequences and Regular expressions
#
#########################################
class SeqSortRef(SortRef):
"""Sequence sort."""
def is_string(self):
"""Determine if sort is a string
>>> s = StringSort()
>>> s.is_string()
True
>>> s = SeqSort(IntSort())
>>> s.is_string()
False
"""
return Z3_is_string_sort(self.ctx_ref(), self.ast)
def StringSort(ctx=None):
"""Create a string sort
>>> s = StringSort()
>>> print(s)
String
"""
ctx = _get_ctx(ctx)
return SeqSortRef(Z3_mk_string_sort(ctx.ref()), ctx)
def SeqSort(s):
"""Create a sequence sort over elements provided in the argument
>>> s = SeqSort(IntSort())
>>> s == Unit(IntVal(1)).sort()
True
"""
return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
class SeqRef(ExprRef):
"""Sequence expression."""
def sort(self):
return SeqSortRef(Z3_get_sort(self.ctx_ref(), self.as_ast()), self.ctx)
def __add__(self, other):
return Concat(self, other)
def __radd__(self, other):
return Concat(other, self)
def __getitem__(self, i):
if _is_int(i):
i = IntVal(i, self.ctx)
return SeqRef(Z3_mk_seq_at(self.ctx_ref(), self.as_ast(), i.as_ast()), self.ctx)
def is_string(self):
return Z3_is_string_sort(self.ctx_ref(), Z3_get_sort(self.ctx_ref(), self.as_ast()))
def is_string_value(self):
return Z3_is_string(self.ctx_ref(), self.as_ast())
def as_string(self):
"""Return a string representation of sequence expression."""
return Z3_ast_to_string(self.ctx_ref(), self.as_ast())
def _coerce_seq(s, ctx=None):
if isinstance(s, str):
ctx = _get_ctx(ctx)
s = StringVal(s, ctx)
if not is_expr(s):
raise Z3Exception("Non-expression passed as a sequence")
if not is_seq(s):
raise Z3Exception("Non-sequence passed as a sequence")
return s
def _get_ctx2(a, b, ctx=None):
if is_expr(a):
return a.ctx
if is_expr(b):
return b.ctx
if ctx is None:
ctx = main_ctx()
return ctx
def is_seq(a):
"""Return `True` if `a` is a Z3 sequence expression.
>>> print (is_seq(Unit(IntVal(0))))
True
>>> print (is_seq(StringVal("abc")))
True
"""
return isinstance(a, SeqRef)
def is_string(a):
"""Return `True` if `a` is a Z3 string expression.
>>> print (is_string(StringVal("ab")))
True
"""
return isinstance(a, SeqRef) and a.is_string()
def is_string_value(a):
"""return 'True' if 'a' is a Z3 string constant expression.
>>> print (is_string_value(StringVal("a")))
True
>>> print (is_string_value(StringVal("a") + StringVal("b")))
False
"""
return isinstance(a, SeqRef) and a.is_string_value()
def StringVal(s, ctx=None):
"""create a string expression"""
ctx = _get_ctx(ctx)
return SeqRef(Z3_mk_string(ctx.ref(), s), ctx)
def String(name, ctx=None):
"""Return a string constant named `name`. If `ctx=None`, then the global context is used.
>>> x = String('x')
"""
ctx = _get_ctx(ctx)
return SeqRef(Z3_mk_const(ctx.ref(), to_symbol(name, ctx), StringSort(ctx).ast), ctx)
def SubString(s, offset, length):
"""Extract substring or subsequence starting at offset"""
return Extract(s, offset, length)
def SubSeq(s, offset, length):
"""Extract substring or subsequence starting at offset"""
return Extract(s, offset, length)
def Strings(names, ctx=None):
"""Return a tuple of String constants. """
ctx = _get_ctx(ctx)
if isinstance(names, str):
names = names.split(" ")
return [String(name, ctx) for name in names]
def Empty(s):
"""Create the empty sequence of the given sort
>>> e = Empty(StringSort())
>>> print(e)
""
>>> e2 = StringVal("")
>>> print(e.eq(e2))
True
>>> e3 = Empty(SeqSort(IntSort()))
>>> print(e3)
seq.empty
>>> e4 = Empty(ReSort(SeqSort(IntSort())))
>>> print(e4)
re.empty
"""
if isinstance(s, SeqSortRef):
return SeqRef(Z3_mk_seq_empty(s.ctx_ref(), s.ast), s.ctx)
if isinstance(s, ReSortRef):
return ReRef(Z3_mk_re_empty(s.ctx_ref(), s.ast), s.ctx)
raise Z3Exception("Non-sequence, non-regular expression sort passed to Empty")
def Full(s):
"""Create the regular expression that accepts the universal language
>>> e = Full(ReSort(SeqSort(IntSort())))
>>> print(e)
re.all
>>> e1 = Full(ReSort(StringSort()))
>>> print(e1)
re.all
"""
if isinstance(s, ReSortRef):
return ReRef(Z3_mk_re_full(s.ctx_ref(), s.ast), s.ctx)
raise Z3Exception("Non-sequence, non-regular expression sort passed to Full")
def Unit(a):
"""Create a singleton sequence"""
return SeqRef(Z3_mk_seq_unit(a.ctx_ref(), a.as_ast()), a.ctx)
def PrefixOf(a, b):
"""Check if 'a' is a prefix of 'b'
>>> s1 = PrefixOf("ab", "abc")
>>> simplify(s1)
True
>>> s2 = PrefixOf("bc", "abc")
>>> simplify(s2)
False
"""
ctx = _get_ctx2(a, b)
a = _coerce_seq(a, ctx)
b = _coerce_seq(b, ctx)
return BoolRef(Z3_mk_seq_prefix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def SuffixOf(a, b):
"""Check if 'a' is a suffix of 'b'
>>> s1 = SuffixOf("ab", "abc")
>>> simplify(s1)
False
>>> s2 = SuffixOf("bc", "abc")
>>> simplify(s2)
True
"""
ctx = _get_ctx2(a, b)
a = _coerce_seq(a, ctx)
b = _coerce_seq(b, ctx)
return BoolRef(Z3_mk_seq_suffix(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def Contains(a, b):
"""Check if 'a' contains 'b'
>>> s1 = Contains("abc", "ab")
>>> simplify(s1)
True
>>> s2 = Contains("abc", "bc")
>>> simplify(s2)
True
>>> x, y, z = Strings('x y z')
>>> s3 = Contains(Concat(x,y,z), y)
>>> simplify(s3)
True
"""
ctx = _get_ctx2(a, b)
a = _coerce_seq(a, ctx)
b = _coerce_seq(b, ctx)
return BoolRef(Z3_mk_seq_contains(a.ctx_ref(), a.as_ast(), b.as_ast()), a.ctx)
def Replace(s, src, dst):
"""Replace the first occurrence of 'src' by 'dst' in 's'
>>> r = Replace("aaa", "a", "b")
>>> simplify(r)
"baa"
"""
ctx = _get_ctx2(dst, s)
if ctx is None and is_expr(src):
ctx = src.ctx
src = _coerce_seq(src, ctx)
dst = _coerce_seq(dst, ctx)
s = _coerce_seq(s, ctx)
return SeqRef(Z3_mk_seq_replace(src.ctx_ref(), s.as_ast(), src.as_ast(), dst.as_ast()), s.ctx)
def IndexOf(s, substr):
return IndexOf(s, substr, IntVal(0))
def IndexOf(s, substr, offset):
"""Retrieve the index of substring within a string starting at a specified offset.
>>> simplify(IndexOf("abcabc", "bc", 0))
1
>>> simplify(IndexOf("abcabc", "bc", 2))
4
"""
ctx = None
if is_expr(offset):
ctx = offset.ctx
ctx = _get_ctx2(s, substr, ctx)
s = _coerce_seq(s, ctx)
substr = _coerce_seq(substr, ctx)
if _is_int(offset):
offset = IntVal(offset, ctx)
return SeqRef(Z3_mk_seq_index(s.ctx_ref(), s.as_ast(), substr.as_ast(), offset.as_ast()), s.ctx)
def Length(s):
"""Obtain the length of a sequence 's'
>>> l = Length(StringVal("abc"))
>>> simplify(l)
3
"""
s = _coerce_seq(s)
return ArithRef(Z3_mk_seq_length(s.ctx_ref(), s.as_ast()), s.ctx)
def StrToInt(s):
"""Convert string expression to integer
>>> a = StrToInt("1")
>>> simplify(1 == a)
True
>>> b = StrToInt("2")
>>> simplify(1 == b)
False
>>> c = StrToInt(IntToStr(2))
>>> simplify(1 == c)
False
"""
s = _coerce_seq(s)
return ArithRef(Z3_mk_str_to_int(s.ctx_ref(), s.as_ast()), s.ctx)
def IntToStr(s):
"""Convert integer expression to string"""
if not is_expr(s):
s = _py2expr(s)
return SeqRef(Z3_mk_int_to_str(s.ctx_ref(), s.as_ast()), s.ctx)
def Re(s, ctx=None):
"""The regular expression that accepts sequence 's'
>>> s1 = Re("ab")
>>> s2 = Re(StringVal("ab"))
>>> s3 = Re(Unit(BoolVal(True)))
"""
s = _coerce_seq(s, ctx)
return ReRef(Z3_mk_seq_to_re(s.ctx_ref(), s.as_ast()), s.ctx)
## Regular expressions
class ReSortRef(SortRef):
"""Regular expression sort."""
def ReSort(s):
if is_ast(s):
return ReSortRef(Z3_mk_re_sort(s.ctx.ref(), s.ast), s.ctx)
if s is None or isinstance(s, Context):
ctx = _get_ctx(s)
return ReSortRef(Z3_mk_re_sort(ctx.ref(), Z3_mk_string_sort(ctx.ref())), s.ctx)
raise Z3Exception("Regular expression sort constructor expects either a string or a context or no argument")
class ReRef(ExprRef):
"""Regular expressions."""
def __add__(self, other):
return Union(self, other)
def is_re(s):
return isinstance(s, ReRef)
def InRe(s, re):
"""Create regular expression membership test
>>> re = Union(Re("a"),Re("b"))
>>> print (simplify(InRe("a", re)))
True
>>> print (simplify(InRe("b", re)))
True
>>> print (simplify(InRe("c", re)))
False
"""
s = _coerce_seq(s, re.ctx)
return BoolRef(Z3_mk_seq_in_re(s.ctx_ref(), s.as_ast(), re.as_ast()), s.ctx)
def Union(*args):
"""Create union of regular expressions.
>>> re = Union(Re("a"), Re("b"), Re("c"))
>>> print (simplify(InRe("d", re)))
False
"""
args = _get_args(args)
sz = len(args)
if __debug__:
_z3_assert(sz > 0, "At least one argument expected.")
_z3_assert(all([is_re(a) for a in args]), "All arguments must be regular expressions.")
if sz == 1:
return args[0]
ctx = args[0].ctx
v = (Ast * sz)()
for i in range(sz):
v[i] = args[i].as_ast()
return ReRef(Z3_mk_re_union(ctx.ref(), sz, v), ctx)
def Plus(re):
"""Create the regular expression accepting one or more repetitions of argument.
>>> re = Plus(Re("a"))
>>> print(simplify(InRe("aa", re)))
True
>>> print(simplify(InRe("ab", re)))
False
>>> print(simplify(InRe("", re)))
False
"""
return ReRef(Z3_mk_re_plus(re.ctx_ref(), re.as_ast()), re.ctx)
def Option(re):
"""Create the regular expression that optionally accepts the argument.
>>> re = Option(Re("a"))
>>> print(simplify(InRe("a", re)))
True
>>> print(simplify(InRe("", re)))
True
>>> print(simplify(InRe("aa", re)))
False
"""
return ReRef(Z3_mk_re_option(re.ctx_ref(), re.as_ast()), re.ctx)
def Complement(re):
"""Create the complement regular expression."""
return ReRef(Z3_mk_re_complement(re.ctx_ref(), re.as_ast()), re.ctx)
def Star(re):
"""Create the regular expression accepting zero or more repetitions of argument.
>>> re = Star(Re("a"))
>>> print(simplify(InRe("aa", re)))
True
>>> print(simplify(InRe("ab", re)))
False
>>> print(simplify(InRe("", re)))
True
"""
return ReRef(Z3_mk_re_star(re.ctx_ref(), re.as_ast()), re.ctx)
def Loop(re, lo, hi=0):
"""Create the regular expression accepting between a lower and upper bound repetitions
>>> re = Loop(Re("a"), 1, 3)
>>> print(simplify(InRe("aa", re)))
True
>>> print(simplify(InRe("aaaa", re)))
False
>>> print(simplify(InRe("", re)))
False
"""
return ReRef(Z3_mk_re_loop(re.ctx_ref(), re.as_ast(), lo, hi), re.ctx)
| [
"rapt@cs.princeton.edu"
] | rapt@cs.princeton.edu |
c45cf427c9cf9cbc40a8acfde513ec9d8c16e029 | b469cadf70bd6286d5c18847f033990ca88910d1 | /mes_from_cpmd/cal_cube_from_wan_for_dens.py | 09b4b7d3552f06f0fe3205d4c8e3a3fcccc4f9fe | [] | no_license | chdressler/MES_from_cpmd | bf2ef68b19af147342ee9422a6d96452f6c93344 | a70d31b9fa2a63b6a39811d74e30be76f4eefaf8 | refs/heads/master | 2023-08-25T10:48:16.153154 | 2021-11-09T15:04:54 | 2021-11-09T15:04:54 | 388,055,888 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,214 | py | import numpy as np
import ipdb
from mes_from_cpmd.misc import git_control
import numpy as np
import os
import sys
import argparse
import subprocess
def main():
print("command line:")
print(sys.argv)
git_control.get_git_version()
parser = argparse.ArgumentParser('converts CPMD DENSITY files into .cube files, Warning: this script has to be executed on an AMD or Intel node (because it requires an old precompiled fortran script)')
parser.add_argument("path_to_input_for_cpmd", help="path to files required for density calculation of the target molecule due to the basis function of the potential (for CPMD: prepare_wfo, calc_wfo, wfo.job, wfo.inp, col_dens, new_run_cpmd2cube )")
parser.add_argument("n", help="number of basis funtion of perturbing potentials used for calculation",type=int)
args = parser.parse_args()
path_inp = args.path_to_input_for_cpmd
wd = os.getcwd()
for j in range(args.n):
i = j+1
os.chdir("./"+ str(i))
list_files = subprocess.run(["cp", path_inp +"/run_cpmd2cube", "." ])
list_files = subprocess.run(["bash", "run_cpmd2cube"])
os.chdir(wd)
| [
"christian.dressler@chemie.uni-halle.de"
] | christian.dressler@chemie.uni-halle.de |
71d3f03e8c8b134d94333037096cdf1cf2eb937e | fc556324a0803bdfbee9179cf472a1a38cc207ac | /TestSignInLottery/test_signin.py | 51aa7578b028240d797e4f3a093e363734c4d1c0 | [] | no_license | lele1120/testAuto | b7c2d6dd3817efa87f4bb6b1a044a75bbe5ced86 | 9e9f413a99078241f7200a779cc29c77a03fb56c | refs/heads/master | 2020-04-05T10:22:23.792060 | 2019-04-08T01:14:56 | 2019-04-08T01:14:56 | 156,796,174 | 6 | 0 | null | 2019-01-23T07:19:18 | 2018-11-09T02:05:54 | Python | UTF-8 | Python | false | false | 13,973 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import re
import time
import pytest
from os import path
from Params.params import get_value
from Common import Operate
from Common import Consts
from Common import Assert
import sys
test = Assert.Assertions()
action = Operate.Operation()
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
class TestSignIn:
@pytest.allure.feature('sigin')
@pytest.allure.feature("01.启动app后进入比财")
@pytest.allure.severity('critical')
def test_go_main_01(self, d):
"""
首次启动app点击进入比财,如果有广告页点击x关闭,
:param d:
:return:
"""
time.sleep(5)
with pytest.allure.step("启动页点击进入比财"):
action.click_element(d, "启动页进入比财")
with pytest.allure.step("如果弹出广告页点x关闭"):
if d(resourceId=get_value("广告页")).exists: # 如果弹出广告页
action.click_element(d, "广告页关闭") # 点击x关闭
with pytest.allure.step("验证启动app点击进入比财是否进入首页"):
test.assert_element_exists_save_picture(d, d(text="一键登录").exists, "验证是否有文本为一键登录的控件")
Consts.RESULT_LIST.append('True')
@pytest.allure.feature('sigin')
@pytest.allure.feature("02.比财登录")
@pytest.allure.severity('critical')
def test_login_02(self, d):
"""
比财账号登录
"""
global USER_ID # 使用账号
USER_ID = str(get_value("xc手机号"))
picture_verification_code = str(get_value("四位图片验证码"))
login_verification_code = str(get_value("登录验证码"))
with pytest.allure.step("点击app首页一键登录"):
action.click_element(d, "首页一键登录")
with pytest.allure.step("在登录页账号输入框输入账号"):
action.input_element(d, "登录页账号输入框", USER_ID)
with pytest.allure.step("点击获取验证码"):
action.click_element(d, "登录页获取验证码按钮") # 点击获取验证码
# 如果弹出4位数字图片验证码
with pytest.allure.step("输入4位验证码"):
time.sleep(2)
if d(text=u"请填写图像验证码").exists:
action.input_element(d, "图片验证码输入框", picture_verification_code)
with pytest.allure.step("点击确认按钮"):
action.click_element(d, "图片验证码确定按钮")
with pytest.allure.step("输入6位验证码"):
action.input_element(d, "登录验证码输入框", login_verification_code)
with pytest.allure.step("点击立即登录"):
action.click_element(d, "立即登录按钮")
with pytest.allure.step("验证是否登录成功"):
test.assert_element_exists_save_picture(d, not d(resourceId=get_value("首页一键登录")).exists, "验证是否登录")
Consts.RESULT_LIST.append('True')
@pytest.allure.feature('sigin')
@pytest.allure.feature("03.弹出侧边栏")
@pytest.allure.severity('critical')
def test_sidebar_eject_03(self, d):
"""
验证点击左上角图标弹出侧边栏功能
"""
global cebian_button # 侧边栏按钮
global realname_status # 实名认证状态
cebian_button = ["我的关注", "我的消息", "我的钱包", "关于我们"]
with pytest.allure.step("点击左上角图标"):
action.click_element(d, "首页左上角图标")
time.sleep(10)
with pytest.allure.step("检验侧边栏控件"):
for i in range(cebian_button.__len__()):
test.assert_element_exists_save_picture(d, d(text=cebian_button[i]).exists,
"验证侧边栏" + cebian_button[i] + "按钮控件存在")
with pytest.allure.step("验证账号为已登录状态,账号为" + USER_ID):
user_id = d(resourceId=get_value("侧边栏账号")).get_text()
test.assert_equal_save_picture(d, user_id, USER_ID.replace((USER_ID[3:7]), "****"),
"账号" + USER_ID + "已登录状态")
Consts.RESULT_LIST.append('True')
@pytest.allure.feature('sigin')
@pytest.allure.feature("04.点击签到")
@pytest.allure.severity('critical')
def test_click_sign_in_04(self, d):
"""
点击签到
:param d:
:return:
"""
if d(resourceId="com.bs.finance:id/tab3_dot").exists:
not_sign_in = 1 # 签到上方红点存在,今日还未点击过签到按钮
else:
not_sign_in = 0 # 签到上方红点不存在,今日已点击过签到按钮
time.sleep(5)
with pytest.allure.step("点击签到"):
action.click_element(d, "签到")
time.sleep(5)
with pytest.allure.step("校验是否跳转成功"):
test.assert_title(d, "签到")
# time.sleep(10)
# 需要添加 查找当天数据 没查到向下滑动 再查 获取当天记录对比
# sign_in_state = d(className="android.view.View")[29].info['contentDescription']
# test.assert_equal_save_picture(d, sign_in_state, "今日已签到", "签到")
Consts.RESULT_LIST.append('True')
@pytest.allure.feature('sigin')
@pytest.allure.feature("05.签到抽奖校验")
@pytest.allure.severity('critical')
def test_click_sign_in_luck_draw_05(self, d):
"""
签到抽奖校验
:param d:
:return:
"""
global red_envelope_money
with pytest.allure.step("签到抽奖校验"):
time.sleep(10)
# for i in range(d(className="android.widget.Image").__len__()):
# if d(className="android.widget.Image")[i].exists:
# if d(className="android.widget.Image")[i].info['contentDescription'] == "5@2x":
# print("今日未抽奖")
# with pytest.allure.step("点击抽奖"):
# d(className="android.widget.Image")[i].click()
# time.sleep(5)
# d(className="android.widget.Image")[i].click()
# time.sleep(5)
# for j in range(d(className="android.view.View").__len__()):
# print("----------------------------------------------------------------")
# print(d(className="android.view.View")[j].info['contentDescription'])
# print("----------------------------------------------------------------")
# if "获得" in str(d(className="android.view.View")[j].info['contentDescription']):
# print("*-*-*-*-*-*-*")
# print(j)
# print("*-*-*-*-*-*-*")
# red_envelope_money_text = (d(className="android.view.View")[j]).info['contentDescription']
# print("*********************************")
# print(red_envelope_money_text)
# print("*********************************")
# red_envelope_money = re.findall(r'-?\d+\.?\d*e?-?\d*?', red_envelope_money_text)
# print("抽中金额:" + str(red_envelope_money) + "元")
# time.sleep(2)
#
# d(text=u"查看我的中奖记录").click(timeout=10)
#
# time.sleep(2)
#
# d(resourceId="com.bs.finance:id/rl_back").click(timeout=10)
#
# break
if d(text=u"5@2x").exists:
print("今日未抽奖")
with pytest.allure.step("点击抽奖"):
d(text=u"5@2x").click(timeout=10)
time.sleep(10)
d.click(0.269, 0.533)
time.sleep(2)
d(text=u"查看我的中奖记录").click(timeout=10)
else:
print("该用户已抽奖")
Consts.RESULT_LIST.append('True')
@pytest.allure.feature('sigin')
@pytest.allure.feature("06.查看活动规则")
@pytest.allure.severity('critical')
def test_look_activity_rules_06(self, d):
"""
查看活动规则
:param d:
:return:
"""
with pytest.allure.step("查看活动规则"):
d(text=u"活动规则").click(timeout=10)
time.sleep(5)
test.assert_element_exists_save_picture(d, d(text=u"签到抽奖规则").exists, "签到规则跳转")
with pytest.allure.step("点击活动规则关闭"):
# d(className="android.view.View", instance=5).click(timeout=10)
d(className="android.widget.Image").click(timeout=10)
# d(text=u"yAAAAAElFTkSuQmCC").click(timeout=10)
Consts.RESULT_LIST.append('True')
@pytest.allure.feature('sigin')
@pytest.allure.feature("07.点击分享")
@pytest.allure.severity('critical')
def test_click_share_friend_07(self, d):
"""
点击分享给朋友
:param d:
:return:
"""
time.sleep(2)
with pytest.allure.step("点击分享按钮"):
d(text=u"分享").click(timeout=10) # 点击分享
with pytest.allure.step("点击发送给朋友"):
# d(text=u"发送给朋友", className="android.view.View").click(timeout=10) # 点击发送给朋友
d(text=u"微信").click(timeout=10) # 点击发送给朋友
time.sleep(3)
with pytest.allure.step("选择要发送的人"):
d(resourceId="com.tencent.mm:id/q0", text=u"熊出没请您注意").click(timeout=10)
with pytest.allure.step("点击分享"):
d(resourceId="com.tencent.mm:id/az_").click(timeout=10)
with pytest.allure.step("点击返回比财"):
d(resourceId="com.tencent.mm:id/az9").click(timeout=10) # 返回比财
Consts.RESULT_LIST.append('True')
@pytest.allure.feature('sigin')
@pytest.allure.feature("08.点击分享圈")
@pytest.allure.severity('critical')
def test_click_share_circle_of_friend_08(self, d):
"""
点击分享给朋友圈
:param d:
:return:
"""
time.sleep(2)
with pytest.allure.step("点击分享按钮"):
d(text=u"分享").click(timeout=10) # 点击分享
with pytest.allure.step("点击发送到朋友圈"):
# d(text=u"发送到朋友圈").click(timeout=10) # 点击发送给朋友圈
d(text=u"朋友圈", className="android.view.View").click(timeout=10) # 点击发送给朋友圈
with pytest.allure.step("点击发表"):
d(resourceId="com.tencent.mm:id/jx").click(timeout=10)
Consts.RESULT_LIST.append('True')
@pytest.allure.feature('sigin')
@pytest.allure.feature("09.签到页查看我的中奖记录")
@pytest.allure.severity('critical')
def test_click_my_winning_record_09(self, d):
"""
在签到页点击我的中奖记录
:param d:
:return:
"""
with pytest.allure.step("向下滑动"):
time.sleep(5)
d(scrollable=True).scroll(steps=30) # 向下滑动
time.sleep(5)
with pytest.allure.step("点击我的中奖记录"):
d(text=u"我的中奖记录").click(timeout=10)
time.sleep(5)
test.assert_title(d, "签到")
with pytest.allure.step("我的中奖记录中含有今日已发放记录"):
now_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
test.assert_element_exists_save_picture(d, d(text=str(now_date)).exists, "签到记录中记录今日签到记录")
with pytest.allure.step("点击我的中奖记录"):
action.click_element(d, "左上角关闭")
Consts.RESULT_LIST.append('True')
@pytest.allure.feature('sigin')
@pytest.allure.feature("10.点击设置")
@pytest.allure.severity('Block')
def test_click_set_up_10(self, d):
"""
点击设置
:param d:
:return:
"""
with pytest.allure.step("点击左上角图标"):
action.click_element(d, "首页左上角图标")
with pytest.allure.step("点击设置"):
time.sleep(5)
action.click_element(d, "侧边栏设置")
with pytest.allure.step("title校验"):
test.assert_title(d, "设置")
Consts.RESULT_LIST.append('True')
@pytest.allure.feature('sigin')
@pytest.allure.feature("11.app退出")
@pytest.allure.severity('critical')
def test_sign_out_app_11(self, d):
"""
退出app
:param d:
:return:
"""
with pytest.allure.step("点击安全退出"):
action.click_element(d, "安全退出")
with pytest.allure.step("点击确认退出_是"):
action.click_element(d, "确认退出_是")
time.sleep(5)
with pytest.allure.step("验证app已成功退出"):
assert d(text="一键登录").exists # 验证是否有文本为一键登录的控件
action.display_picture(d, "app退出")
Consts.RESULT_LIST.append('True')
| [
"357072695@qq.com"
] | 357072695@qq.com |
aba6226994ff403bbe174e0bd632eb8ba130dcd3 | 671aad3a211344d1832183ddfb10cc8a8c6110ff | /python3/prime_number.py | 2dd8ba5c6fb4ba8a454439cdb4b5032cf4462eb2 | [] | no_license | WhiteRabbit82651/study | ac6862d51c2f9684b3d662c5561dd6a58b1c3b07 | 2b595b3fdf770dda9c0c2854716ae9fcfd9c6316 | refs/heads/main | 2023-07-21T22:27:00.461341 | 2021-08-22T02:41:44 | 2021-08-22T02:41:44 | 309,523,599 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 391 | py | #encode:utf-8
# 素数を計算する
# 冗長な気もするけどコンテストに出るわけでもないので吉とする
cnt = 0
for n in range(99999):
if n > 1:
for x in range(n+1):
if x > 1:
ans = n % x
if ans == 0:
break
if n == x:
cnt += 1
print("%dth is %d" % (cnt, n))
| [
"parvati@kali"
] | parvati@kali |
d4e499c20fc433e7ece9d2ba14bde83e473bf504 | 3195582a3b39fbd3e710fc20a05917d3ce0812a3 | /Python/Sets/set_union.py | 9991754e89fb9308214b24dac6d02de48ef8b05b | [
"MIT"
] | permissive | rho2/HackerRank | 1f2dba2b8918fa0600d3ccaf31a53deeddac2415 | 4d9cdfcabeb20212db308d8e4f2ac1b8ebf7d266 | refs/heads/master | 2021-01-18T17:02:41.568504 | 2018-01-06T20:21:49 | 2018-01-06T20:21:49 | 68,400,463 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 92 | py | _ = input()
n = set(input().split())
_ = input()
b = set(input().split())
print(len(n | b)) | [
"rho2@robin-manjaro.Speedport_W_921V_1_39_000"
] | rho2@robin-manjaro.Speedport_W_921V_1_39_000 |
4c5174f549cbf5f655c5447974a3e066f35dc33c | 67300733102a5a32b2977770be2cedc4630b0113 | /falsification.py | 3fc55147688a42496371c303f5e564d8d577a408 | [] | no_license | GaiaSaveri/CPS-Project | ce61a01952cfee569eb7af8b839381f872f27291 | 95db6a606c011c11efb72504f2904e7061571e51 | refs/heads/main | 2023-06-02T20:35:41.758591 | 2021-06-14T17:01:28 | 2021-06-14T17:01:28 | 376,894,463 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,079 | py | import os
os.environ['JAVA_HOME'] = "/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home"
from moonlight import *
from stl import monitor_steady, diff
from experiments import ekf, t, save, load
from mpc import *
def falsification(N, ref):
cstr = CSTR()
minSTL = float('Inf')
dict = {}
for i in range(N):
Q = abs(np.random.normal(2.0, 1))
R = abs(np.random.normal(0.001, 0.01))
mpc = MPC(cstr, h=10, Q=Q, R=R, observer=ekf)
dict['Q'] = Q
dict['R'] = R
_, T, _ = mpc.mpc(ref, t)
dict['T'] = T[:len(t)]
d = diff(T[:len(T)], ref)
d_signal = [[dd] for dd in d]
result = monitor_steady.monitor(list(t), d_signal)
stl = result[0][1]
dict['rob'] = stl
if stl < minSTL:
minSTL = stl
save(path="data/", controller="MPC_fals", ref=ref, T=dict)
if minSTL < 0:
break
N = 100
ref = [320, 325, 330, 335, 340, 345, 350, 355, 360, 365, 370, 375, 380, 385]
for i in range(len(ref)):
falsification(N, ref[i])
| [
"noreply@github.com"
] | noreply@github.com |
c0f5bba099980515291045f96ed84d08451afe1d | 72ed71cb73c8990a29fa042c8f6e962bf19aa3ae | /ff.py | a276a8b59dd6c7f149b8707d67825bb126dcf765 | [] | no_license | MURHAF-ELMASRI/game | c63c1c6368c630a9eef316ecfe066120e2ec1651 | 3c681eccfddd9ea12b982b85ed19911a2079ce00 | refs/heads/master | 2022-09-26T12:27:14.438697 | 2020-06-09T13:56:51 | 2020-06-09T13:56:51 | 269,734,028 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,037 | py | def longWord(s):
repet=[-1]*(128+32)
temp=0
best_w_len=0
beg=0
s+=s[0]
s=list(s)
i=0
while(i<len(s)):
#print('9 line', s[i],repet[ord(s[i])])
if(repet[ord(s[i])]!=-1):
x=repet[ord(s[i])]
if(temp>best_w_len):
#print('temp',temp)
best_w_len=temp
beg=i-best_w_len
repet=[-1]*(128+32)
s[len(s)-1]=s[i]
#print('i ',i)
#print(s)
#print('24 line',s[i],end=' ')
#print( repet[ord(s[i])])
#print('line 25 ' , temp)
temp=0
i=x+1
continue
temp+=1
repet[ord(s[i])]=i
i+=1
best_w=''
for i in range(best_w_len):
best_w=best_w+s[beg]
beg+=1
return best_w
s = 'Al-Khwarizmi'
s = 'Solution'
s = 'Microsoft'
s = 'abcd'
s = 'abbcde'
s = 'Microssdoftxyz'
s = 'abcdefghabcdefghijklmnopqrstuvwx'
s = 'Microsoftopqrstuvwxyzabcd'
print(longWord(s))
| [
"murahf@gmail.com"
] | murahf@gmail.com |
48c467558080e77284bd7bbee50be92fe958fe57 | 939a0bd95bb9a39ce0885146bf2affc1565e64bf | /recipe/migrations/0011_auto_20210324_0805.py | 3c7e32c8eae03866986d52bc04fed6e8b741f330 | [] | no_license | sho25052007/quook_recipe_app | 073b2902d6d00b9e345366a59e3e724488dc77a4 | 43dfb202d03ebffb56a3433fb441d737e56d16f0 | refs/heads/main | 2023-04-03T16:14:13.419087 | 2021-04-06T14:11:44 | 2021-04-06T14:11:44 | 345,418,534 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 548 | py | # Generated by Django 3.1.7 on 2021-03-24 08:05
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipe', '0010_auto_20210324_0803'),
]
operations = [
migrations.AlterField(
model_name='recipe',
name='title',
field=models.CharField(max_length=30, null=True, validators=[django.core.validators.RegexValidator('^/^[a-zA-Z ]*$/', 'Only alphabet characters and spaces are allowed.')]),
),
]
| [
"sho25052007@gmail.com"
] | sho25052007@gmail.com |
481bfcb9d763bdb166823bdebb2dfcddf686ee0e | 20780f8619ae61efe55f59417e0014c391bcff1a | /src/numpy/ndchar.py | 7abc216d08f34c6a26142ba6caedbb79b271fe93 | [
"Apache-2.0"
] | permissive | mumupy/pythonlearn | e694fd4fb915c90792db30f8090f370acb3ac68e | 5be03d156f11af2467a6052a476de4b706f7d53a | refs/heads/master | 2020-03-23T17:26:09.811562 | 2019-09-22T06:21:17 | 2019-09-22T06:21:17 | 141,859,868 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 790 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/9/20 18:53
# @Author : ganliang
# @File : ndchar.py
# @Desc : 数据字符
import numpy as np
print np.char.add("baby", "mm")
print (np.char.add(['hello', 'hi'], [' abc', ' xyz']))
print np.char.multiply("baby", 10)
print np.char.center("baby", 10, ".")
print np.char.capitalize("baby")
print np.char.title("baby lover cws")
print np.char.lower("baby lover cws")
print np.char.upper("baby lover cws")
print np.char.split("baby lover cws")
print np.char.splitlines("baby lover cws")
print np.char.strip(" baby lover cws ")
print np.char.join(":", " baby lover cws ")
print np.char.replace("baby lover cws", "cws", "")
print np.char.encode("baby lover cws", "utf-8")
print np.char.decode("baby lover cws", "cp500")
| [
"lovecws"
] | lovecws |
0d1cb7925a58261d9e23d04bfa835151026b290e | d968882c6bdecb2347307aea7381b9495911a0a6 | /microconventions/type_conventions.py | 743a0db4e8a8e19220b9f89b9415898b16077566 | [] | no_license | fagan2888/microconventions | a070bddf94c0788ed4ff3ab31941d0daccf30fd5 | 037f9fcc67caa28916c6b81f4742a68afaf296b0 | refs/heads/master | 2022-11-10T21:52:53.632179 | 2020-07-02T14:28:59 | 2020-07-02T14:28:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 204 | py | from typing import List, Union, Any, Optional
KeyList = List[Optional[str]]
NameList = List[Optional[str]]
Value = Union[str,int]
ValueList = List[Optional[Value]]
DelayList = List[Optional[int]]
| [
"info@3za.org"
] | info@3za.org |
59d2b6f6ff978db7cf306d41680e2b1d011ce9fd | 74eb5e80565ebc5900ff3bd59cee78e7403a8827 | /multiprocess/whateveryouwant.py | a9f3aadb2c64a6cad7a770756e2dcbbe12937407 | [] | no_license | qcurteman/memory_manager | bdc235ece0553d9cc1a6af578b769eac8f23b90a | 172cb718454503775ed1580585a1eb3c5d761194 | refs/heads/master | 2020-03-31T10:12:52.764510 | 2018-10-24T18:03:15 | 2018-10-24T18:03:15 | 152,125,971 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 690 | py | from multiprocessing import Process
import os
import numpy as np
column_size = 8
row_size = 4
memaa = np.empty(shape=(row_size, column_size), dtype='int8')
def modifyprint(arr, vv):
rsize = arr.shape[0]
csize = arr.shape[1]
for r in range(0, rsize):
for c in range(0, csize):
arr[r,c] = vv
print('[', os.getpid(), '] ------')
print(arr)
print()
print(memaa)
print()
def f(arr, va):
modifyprint(arr,va)
if __name__ == '__main__':
viewa = memaa[0:2, :column_size]
modifyprint(viewa, 11)
p = Process(target=f, args=(viewa, 22,))
p.start()
p.join()
print('back to main - print whole array')
print(memaa) | [
"qcurteman@gmail.com"
] | qcurteman@gmail.com |
0a7dd1186e8d62b8c4d4c592dffc1bda1f51539f | 98f042865b5ffb11b16331d4b8f732b512fca527 | /resources/basic_resource.py | b4b2558940997365b4d24e3799b7c30107bf591c | [] | no_license | wesleybez/mfa_iot_lpwan | 53707daf6efaa83287774e52de45ac6d0b764918 | 137ada07fceeb27abe52b77740017f95a59ba8a4 | refs/heads/main | 2023-04-28T12:26:43.240931 | 2021-05-11T22:43:13 | 2021-05-11T22:43:13 | 327,968,205 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,147 | py | #https://github.com/Tanganelli/CoAPthon
from coapthon.server.coap import CoAP
from coapthon.resources.resource import Resource
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
class BasicResource(Resource):
def __init__(self, name="BasicResource", coap_server=None):
super(BasicResource, self).__init__(name, coap_server, visible=True,
observable=False, allow_children=True)
self.payload = "Basic Resource"
def render_GET(self, request):
logger.debug("entrou no render_GET")
self.payload = "{temperatura:30, {nome:abc, idade:33}}"
return self
def render_PUT(self, request):
logger.debug("entrou no render_PUT")
self.payload = request.payload
return self
def render_POST(self, request):
logger.debug("entrou no render_POST")
res = BasicResource()
res.location_query = request.uri_query
res.payload = request.payload
return res
def render_DELETE(self, request):
logger.debug("entrou no render_DELETE")
return True
| [
"wesleybez@gmail.com"
] | wesleybez@gmail.com |
2541bc3717df13f38034e534423c96eec29b2d31 | 9cadeb694a677c4ad567d514eee042891c65eeaf | /apiServer/wsgi.py | 64aabb0e27969ed54fed3cc2e2a79148e4e57375 | [] | no_license | epikjjh/Stock-Seeker | b8267fda13df6579f3883f66f94007d6ca11187a | 934d97c0ceb89c1fcdfb469c1807d09c2671cc67 | refs/heads/master | 2022-12-22T23:38:24.947593 | 2020-09-22T11:50:56 | 2020-09-22T11:50:56 | 297,632,451 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 397 | py | """
WSGI config for stockSeeker project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'apiServer.settings')
application = get_wsgi_application()
| [
"epikjjh@gmail.com"
] | epikjjh@gmail.com |
2ca74b87fb00d97fdb9b1cd2746f2e542e60938b | b65c1f6000af4ddeb7280e7d93bf861fbf1964bc | /contracts/tests/test_load_data.py | e385455a7533122a2a8978adbb1a3792d745a638 | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | EricSchles/calc | ef00aaddfec010321867a8287db0a565dbb7985e | eaa1ab227a5a07f5f4f7d2c64a278977cd43cb18 | refs/heads/develop | 2021-01-25T14:33:58.124300 | 2017-10-11T19:29:20 | 2017-10-11T19:29:20 | 72,668,485 | 1 | 0 | null | 2016-11-02T18:17:57 | 2016-11-02T18:17:57 | null | UTF-8 | Python | false | false | 483 | py | import pathlib
from django.core.management import call_command
from django.test import TestCase
from contracts.models import Contract
MY_DIR = pathlib.Path(__file__).resolve().parent
class LoadS70TestCase(TestCase):
sample_filename = MY_DIR.parent / 'docs' / 'hourly_prices_sample.csv'
def test_loads_sample(self):
call_command(
'load_data',
filename=self.sample_filename
)
self.assertEquals(Contract.objects.count(), 79)
| [
"varmaa@gmail.com"
] | varmaa@gmail.com |
49ea9ed475b06f56c31886fdda4e54704aaed67f | acb8e84e3b9c987fcab341f799f41d5a5ec4d587 | /langs/8/uyw.py | 29818697f710297c138205642ed9c41a60d45a3c | [] | no_license | G4te-Keep3r/HowdyHackers | 46bfad63eafe5ac515da363e1c75fa6f4b9bca32 | fb6d391aaecb60ab5c4650d4ae2ddd599fd85db2 | refs/heads/master | 2020-08-01T12:08:10.782018 | 2016-11-13T20:45:50 | 2016-11-13T20:45:50 | 73,624,224 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 486 | py | import sys
def printFunction(lineRemaining):
if lineRemaining[0] == '"' and lineRemaining[-1] == '"':
if len(lineRemaining) > 2:
#data to print
lineRemaining = lineRemaining[1:-1]
print ' '.join(lineRemaining)
else:
print
def main(fileName):
with open(fileName) as f:
for line in f:
data = line.split()
if data[0] == 'uYW':
printFunction(data[1:])
else:
print 'ERROR'
return
if __name__ == '__main__':
main(sys.argv[1]) | [
"juliettaylorswift@gmail.com"
] | juliettaylorswift@gmail.com |
52d071b4aa727cef03dc1e3903b86700548018c9 | 03e09a951833e68a10113ed826deca132c1180a8 | /instagram.py | efd87765dc5fb4ec308e2697b902f2b6be49c3f4 | [] | no_license | Jonny1426/Instagram-automate-user-actions | 8e99d94198d1643c46a3bc868db86e95df150317 | 5df3ce76be7f76690ec777a9fbc2303340655bea | refs/heads/master | 2020-06-23T16:42:22.699772 | 2020-01-19T13:58:40 | 2020-01-19T13:58:40 | 198,683,603 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,157 | py | from instapy import InstaPy
from instapy import smart_run
''' Dados do Usuario '''
insta_username = input(str("Username: ")) #Nome do usuario
insta_password = input(str("Password: ")) # Senha do usuario
'''Inicio de sessão no instapy '''
session = InstaPy(username=insta_username, password=insta_password, headless_browser=False)
with smart_run(session):
''' Definindo requisitos e limites para interagir '''
session.set_relationship_bounds(enabled=True, delimit_by_numbers=True, max_followers=6700, min_followers=30, min_following=57)
'''Aqui fazemos o programa interar com seguidores de usuarios do instagram, usernames se encontram em um arquivo txt'''
usuarios = open("usuarios.txt", "r")
lista = usuarios.readlines()
for user in lista:
session.set_user_interact(amount=2, randomize=True, percentage=100, media=None)
session.set_do_follow(enabled=True, percentage=65)
session.set_do_like(enabled=True, percentage=80)
session.set_do_comment(enabled=False)
session.interact_user_followers([user], amount=2, randomize=True)
usuarios.close()
| [
"noreply@github.com"
] | noreply@github.com |
dba58d500dc281d3b42ffe31ba813201ef1ff43f | e4abeab73f2aa2de037aa84d195dce986af5208a | /lmp/script/sample_from_dataset.py | 758446f580908db34133a1f847dfbd2745eb7d72 | [
"Beerware"
] | permissive | france5289/language-model-playground | 1792fc712bace3ca3e7a0b8b3ba4745b2d6c9b5c | 02181561107dac13d52e411bc970e245277854d4 | refs/heads/main | 2023-08-07T01:59:56.928232 | 2021-09-22T06:57:28 | 2021-09-22T06:57:28 | 409,092,012 | 0 | 0 | NOASSERTION | 2021-09-22T06:39:53 | 2021-09-22T06:39:52 | null | UTF-8 | Python | false | false | 2,896 | py | r"""Sample dataset using index.
Tool for observing data point in specified dataset.
Use index to sample from dataset.
See Also
========
lmp.dset
All available dataset.
Examples
========
The following example sample index ``0`` from
:py:class:`lmp.dset.WikiText2Dset` ``train`` dataset.
.. code-block:: sh
python -m lmp.script.sample_from_dataset wikitext-2
The following example sample index ``1`` from
:py:class:`lmp.dset.WikiText2Dset` ``train`` dataset.
.. code-block:: sh
python -m lmp.script.sample_from_dataset wikitext-2 --idx 1
The following example sample index ``1`` from
:py:class:`lmp.dset.WikiText2Dset` ``test`` dataset.
.. code-block:: sh
python -m lmp.script.sample_from_dataset wikitext-2 --idx 1 --ver test
Use ``-h`` or ``--help`` options to get list of available dataset.
.. code-block:: sh
python -m lmp.script.sample_from_dataset -h
Use ``-h`` or ``--help`` options on specific dataset to get a list of available
versions.
.. code-block:: sh
python -m lmp.script.sample_from_dataset wikitext-2 -h
"""
import argparse
import lmp.util.dset
from lmp.dset import DSET_OPTS
def parse_arg() -> argparse.Namespace:
r"""Parse arguments from CLI.
Argument must begin with a dataset name ``dset_name``.
The following arguments are optional:
--ver Version of the dataset.
Default to ``dset``'s default version.
--idx Sample index.
Default to ``0``.
Returns
=======
argparse.Namespace
Arguments from CLI.
"""
# Create parser.
parser = argparse.ArgumentParser(
'python -m lmp.script.sample_from_dataset',
description='Sample dataset using index.',
)
# Create subparser for each dataset.
subparsers = parser.add_subparsers(dest='dset_name', required=True)
for dset_name, dset_clss in DSET_OPTS.items():
# Use dataset name as CLI argument.
dset_parser = subparsers.add_parser(
dset_name,
description=f'Sample {dset_name} dataset using index.',
)
# Optional arguments.
dset_parser.add_argument(
'--idx',
default=0,
help='Sample index.',
type=int,
)
dset_parser.add_argument(
'--ver',
default=None,
help=' '.join([
f'Version of the {dset_name} dataset.',
f'Defaults to {dset_clss.df_ver}.',
]),
choices=dset_clss.vers,
type=str,
)
return parser.parse_args()
def main() -> None:
r"""Script entry point."""
# Parse command-line argument.
args = parse_arg()
# Get dataset instance with specified version.
dset = lmp.util.dset.load(dset_name=args.dset_name, ver=args.ver)
# Output sample result.
print(dset[args.idx])
if __name__ == '__main__':
main()
| [
"ProFatXuanAll@gmail.com"
] | ProFatXuanAll@gmail.com |
a94e89fe8281b9012860d68a54eeebca40b932e7 | 671132fe2df0ac6359cf89fb5dd66ed107643456 | /Chapter03/timeSeries.py | cd577937ac439401a5f7b5cd305ea6af917e154a | [
"MIT"
] | permissive | allen-zqh/plotly | 0e0814b6bc95856cba00c4c8dc37bf824d6e8409 | bcaf0930901e77db07245b63bff049eb75893416 | refs/heads/master | 2022-11-22T09:23:17.027977 | 2020-07-27T07:13:03 | 2020-07-27T07:13:03 | 282,809,802 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 586 | py | import plotly as py
import plotly.graph_objs as go
from datetime import datetime
# ----------pre def
pyplt = py.offline.plot
# ----------code
x_datetime = [datetime(year=2013, month=10, day=4),
datetime(year=2013, month=11, day=5),
datetime(year=2013, month=12, day=6)]
x_string = ['2013-10-04', '2013-11-05', '2013-12-06']
trace_datetime = go.Scatter(x=x_datetime, y=[1, 3, 6],name='trace_datetime')
trace_string = go.Scatter(x=x_string, y=[2, 4, 7],name='trace_string')
data = [trace_datetime, trace_string]
pyplt(data, filename='tmp/timeSeries.html')
| [
"allen_zqh@bupt.edu.cn"
] | allen_zqh@bupt.edu.cn |
7fc845ff7f633ccceb024e13feab6eda8d83a5c1 | aac1b8efaeccc544d229aa52093a36802250b4cf | /pre/python/lib/python2.7/dist-packages/twisted/conch/test/test_ckeygen.py | 41a02083ab4cf574d9e9fe70617cab39af519f8c | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ag1455/OpenPLi-PC | 4f63bbd389ff9604ab7aaf72d10ee6552b794c87 | 256401ac313df2e45c516af1a4d5398f54703b9c | refs/heads/master | 2023-08-22T18:20:07.491386 | 2023-08-14T17:29:59 | 2023-08-14T17:29:59 | 233,239,212 | 27 | 22 | null | 2020-12-28T22:09:26 | 2020-01-11T13:50:25 | Python | UTF-8 | Python | false | false | 20,281 | py | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.conch.scripts.ckeygen}.
"""
import getpass
import sys
import os
import subprocess
from io import BytesIO, StringIO
from twisted.python.compat import unicode, _PY3
from twisted.python.reflect import requireModule
if requireModule('cryptography') and requireModule('pyasn1'):
from twisted.conch.ssh.keys import (Key, BadKeyError,
BadFingerPrintFormat, FingerprintFormats)
from twisted.conch.scripts.ckeygen import (
changePassPhrase, displayPublicKey, printFingerprint,
_saveKey, enumrepresentation)
else:
skip = "cryptography and pyasn1 required for twisted.conch.scripts.ckeygen"
from twisted.python.filepath import FilePath
from twisted.trial.unittest import TestCase
from twisted.conch.test.keydata import (
publicRSA_openssh, privateRSA_openssh, privateRSA_openssh_encrypted, privateECDSA_openssh)
def makeGetpass(*passphrases):
"""
Return a callable to patch C{getpass.getpass}. Yields a passphrase each
time called. Use case is to provide an old, then new passphrase(s) as if
requested interactively.
@param passphrases: The list of passphrases returned, one per each call.
@return: A callable to patch C{getpass.getpass}.
"""
passphrases = iter(passphrases)
def fakeGetpass(_):
return next(passphrases)
return fakeGetpass
class KeyGenTests(TestCase):
"""
Tests for various functions used to implement the I{ckeygen} script.
"""
def setUp(self):
"""
Patch C{sys.stdout} so tests can make assertions about what's printed.
"""
if _PY3:
self.stdout = StringIO()
else:
self.stdout = BytesIO()
self.patch(sys, 'stdout', self.stdout)
def _testrun(self, keyType, keySize=None):
filename = self.mktemp()
if keySize is None:
subprocess.call(['ckeygen', '-t', keyType, '-f', filename, '--no-passphrase'])
else:
subprocess.call(['ckeygen', '-t', keyType, '-f', filename, '--no-passphrase',
'-b', keySize])
privKey = Key.fromFile(filename)
pubKey = Key.fromFile(filename + '.pub')
if keyType == 'ecdsa':
self.assertEqual(privKey.type(), 'EC')
else:
self.assertEqual(privKey.type(), keyType.upper())
self.assertTrue(pubKey.isPublic())
def test_keygeneration(self):
self._testrun('ecdsa', '384')
self._testrun('ecdsa')
self._testrun('dsa', '2048')
self._testrun('dsa')
self._testrun('rsa', '2048')
self._testrun('rsa')
def test_runBadKeytype(self):
filename = self.mktemp()
with self.assertRaises(subprocess.CalledProcessError):
with open(os.devnull, "rb") as devnull:
subprocess.check_call(
['ckeygen', '-t', 'foo', '-f', filename],
stderr=devnull)
def test_enumrepresentation(self):
"""
L{enumrepresentation} takes a dictionary as input and returns a
dictionary with its attributes changed to enum representation.
"""
options = enumrepresentation({'format': 'md5-hex'})
self.assertIs(options['format'],
FingerprintFormats.MD5_HEX)
def test_enumrepresentationsha256(self):
"""
Test for format L{FingerprintFormats.SHA256-BASE64}.
"""
options = enumrepresentation({'format': 'sha256-base64'})
self.assertIs(options['format'],
FingerprintFormats.SHA256_BASE64)
def test_enumrepresentationBadFormat(self):
"""
Test for unsupported fingerprint format
"""
with self.assertRaises(BadFingerPrintFormat) as em:
enumrepresentation({'format': 'sha-base64'})
self.assertEqual('Unsupported fingerprint format: sha-base64',
em.exception.args[0])
def test_printFingerprint(self):
"""
L{printFingerprint} writes a line to standard out giving the number of
bits of the key, its fingerprint, and the basename of the file from it
was read.
"""
filename = self.mktemp()
FilePath(filename).setContent(publicRSA_openssh)
printFingerprint({'filename': filename,
'format': 'md5-hex'})
self.assertEqual(
self.stdout.getvalue(),
'2048 85:25:04:32:58:55:96:9f:57:ee:fb:a8:1a:ea:69:da temp\n')
def test_printFingerprintsha256(self):
"""
L{printFigerprint} will print key fingerprint in
L{FingerprintFormats.SHA256-BASE64} format if explicitly specified.
"""
filename = self.mktemp()
FilePath(filename).setContent(publicRSA_openssh)
printFingerprint({'filename': filename,
'format': 'sha256-base64'})
self.assertEqual(
self.stdout.getvalue(),
'2048 FBTCOoknq0mHy+kpfnY9tDdcAJuWtCpuQMaV3EsvbUI= temp\n')
def test_printFingerprintBadFingerPrintFormat(self):
"""
L{printFigerprint} raises C{keys.BadFingerprintFormat} when unsupported
formats are requested.
"""
filename = self.mktemp()
FilePath(filename).setContent(publicRSA_openssh)
with self.assertRaises(BadFingerPrintFormat) as em:
printFingerprint({'filename': filename, 'format':'sha-base64'})
self.assertEqual('Unsupported fingerprint format: sha-base64',
em.exception.args[0])
def test_saveKey(self):
"""
L{_saveKey} writes the private and public parts of a key to two
different files and writes a report of this to standard out.
"""
base = FilePath(self.mktemp())
base.makedirs()
filename = base.child('id_rsa').path
key = Key.fromString(privateRSA_openssh)
_saveKey(key, {'filename': filename, 'pass': 'passphrase',
'format': 'md5-hex'})
self.assertEqual(
self.stdout.getvalue(),
"Your identification has been saved in %s\n"
"Your public key has been saved in %s.pub\n"
"The key fingerprint in <FingerprintFormats=MD5_HEX> is:\n"
"85:25:04:32:58:55:96:9f:57:ee:fb:a8:1a:ea:69:da\n" % (
filename,
filename))
self.assertEqual(
key.fromString(
base.child('id_rsa').getContent(), None, 'passphrase'),
key)
self.assertEqual(
Key.fromString(base.child('id_rsa.pub').getContent()),
key.public())
def test_saveKeyECDSA(self):
"""
L{_saveKey} writes the private and public parts of a key to two
different files and writes a report of this to standard out.
Test with ECDSA key.
"""
base = FilePath(self.mktemp())
base.makedirs()
filename = base.child('id_ecdsa').path
key = Key.fromString(privateECDSA_openssh)
_saveKey(key, {'filename': filename, 'pass': 'passphrase',
'format': 'md5-hex'})
self.assertEqual(
self.stdout.getvalue(),
"Your identification has been saved in %s\n"
"Your public key has been saved in %s.pub\n"
"The key fingerprint in <FingerprintFormats=MD5_HEX> is:\n"
"1e:ab:83:a6:f2:04:22:99:7c:64:14:d2:ab:fa:f5:16\n" % (
filename,
filename))
self.assertEqual(
key.fromString(
base.child('id_ecdsa').getContent(), None, 'passphrase'),
key)
self.assertEqual(
Key.fromString(base.child('id_ecdsa.pub').getContent()),
key.public())
def test_saveKeysha256(self):
"""
L{_saveKey} will generate key fingerprint in
L{FingerprintFormats.SHA256-BASE64} format if explicitly specified.
"""
base = FilePath(self.mktemp())
base.makedirs()
filename = base.child('id_rsa').path
key = Key.fromString(privateRSA_openssh)
_saveKey(key, {'filename': filename, 'pass': 'passphrase',
'format': 'sha256-base64'})
self.assertEqual(
self.stdout.getvalue(),
"Your identification has been saved in %s\n"
"Your public key has been saved in %s.pub\n"
"The key fingerprint in <FingerprintFormats=SHA256_BASE64> is:\n"
"FBTCOoknq0mHy+kpfnY9tDdcAJuWtCpuQMaV3EsvbUI=\n" % (
filename,
filename))
self.assertEqual(
key.fromString(
base.child('id_rsa').getContent(), None, 'passphrase'),
key)
self.assertEqual(
Key.fromString(base.child('id_rsa.pub').getContent()),
key.public())
def test_saveKeyBadFingerPrintformat(self):
"""
L{_saveKey} raises C{keys.BadFingerprintFormat} when unsupported
formats are requested.
"""
base = FilePath(self.mktemp())
base.makedirs()
filename = base.child('id_rsa').path
key = Key.fromString(privateRSA_openssh)
with self.assertRaises(BadFingerPrintFormat) as em:
_saveKey(key, {'filename': filename, 'pass': 'passphrase',
'format': 'sha-base64'})
self.assertEqual('Unsupported fingerprint format: sha-base64',
em.exception.args[0])
def test_saveKeyEmptyPassphrase(self):
"""
L{_saveKey} will choose an empty string for the passphrase if
no-passphrase is C{True}.
"""
base = FilePath(self.mktemp())
base.makedirs()
filename = base.child('id_rsa').path
key = Key.fromString(privateRSA_openssh)
_saveKey(key, {'filename': filename, 'no-passphrase': True,
'format': 'md5-hex'})
self.assertEqual(
key.fromString(
base.child('id_rsa').getContent(), None, b''),
key)
def test_saveKeyECDSAEmptyPassphrase(self):
"""
L{_saveKey} will choose an empty string for the passphrase if
no-passphrase is C{True}.
"""
base = FilePath(self.mktemp())
base.makedirs()
filename = base.child('id_ecdsa').path
key = Key.fromString(privateECDSA_openssh)
_saveKey(key, {'filename': filename, 'no-passphrase': True,
'format': 'md5-hex'})
self.assertEqual(
key.fromString(
base.child('id_ecdsa').getContent(), None),
key)
def test_saveKeyNoFilename(self):
"""
When no path is specified, it will ask for the path used to store the
key.
"""
base = FilePath(self.mktemp())
base.makedirs()
keyPath = base.child('custom_key').path
import twisted.conch.scripts.ckeygen
self.patch(twisted.conch.scripts.ckeygen, 'raw_input', lambda _: keyPath)
key = Key.fromString(privateRSA_openssh)
_saveKey(key, {'filename': None, 'no-passphrase': True,
'format': 'md5-hex'})
persistedKeyContent = base.child('custom_key').getContent()
persistedKey = key.fromString(persistedKeyContent, None, b'')
self.assertEqual(key, persistedKey)
def test_displayPublicKey(self):
"""
L{displayPublicKey} prints out the public key associated with a given
private key.
"""
filename = self.mktemp()
pubKey = Key.fromString(publicRSA_openssh)
FilePath(filename).setContent(privateRSA_openssh)
displayPublicKey({'filename': filename})
displayed = self.stdout.getvalue().strip('\n')
if isinstance(displayed, unicode):
displayed = displayed.encode("ascii")
self.assertEqual(
displayed,
pubKey.toString('openssh'))
def test_displayPublicKeyEncrypted(self):
"""
L{displayPublicKey} prints out the public key associated with a given
private key using the given passphrase when it's encrypted.
"""
filename = self.mktemp()
pubKey = Key.fromString(publicRSA_openssh)
FilePath(filename).setContent(privateRSA_openssh_encrypted)
displayPublicKey({'filename': filename, 'pass': 'encrypted'})
displayed = self.stdout.getvalue().strip('\n')
if isinstance(displayed, unicode):
displayed = displayed.encode("ascii")
self.assertEqual(
displayed,
pubKey.toString('openssh'))
def test_displayPublicKeyEncryptedPassphrasePrompt(self):
"""
L{displayPublicKey} prints out the public key associated with a given
private key, asking for the passphrase when it's encrypted.
"""
filename = self.mktemp()
pubKey = Key.fromString(publicRSA_openssh)
FilePath(filename).setContent(privateRSA_openssh_encrypted)
self.patch(getpass, 'getpass', lambda x: 'encrypted')
displayPublicKey({'filename': filename})
displayed = self.stdout.getvalue().strip('\n')
if isinstance(displayed, unicode):
displayed = displayed.encode("ascii")
self.assertEqual(
displayed,
pubKey.toString('openssh'))
def test_displayPublicKeyWrongPassphrase(self):
"""
L{displayPublicKey} fails with a L{BadKeyError} when trying to decrypt
an encrypted key with the wrong password.
"""
filename = self.mktemp()
FilePath(filename).setContent(privateRSA_openssh_encrypted)
self.assertRaises(
BadKeyError, displayPublicKey,
{'filename': filename, 'pass': 'wrong'})
def test_changePassphrase(self):
"""
L{changePassPhrase} allows a user to change the passphrase of a
private key interactively.
"""
oldNewConfirm = makeGetpass('encrypted', 'newpass', 'newpass')
self.patch(getpass, 'getpass', oldNewConfirm)
filename = self.mktemp()
FilePath(filename).setContent(privateRSA_openssh_encrypted)
changePassPhrase({'filename': filename})
self.assertEqual(
self.stdout.getvalue().strip('\n'),
'Your identification has been saved with the new passphrase.')
self.assertNotEqual(privateRSA_openssh_encrypted,
FilePath(filename).getContent())
def test_changePassphraseWithOld(self):
"""
L{changePassPhrase} allows a user to change the passphrase of a
private key, providing the old passphrase and prompting for new one.
"""
newConfirm = makeGetpass('newpass', 'newpass')
self.patch(getpass, 'getpass', newConfirm)
filename = self.mktemp()
FilePath(filename).setContent(privateRSA_openssh_encrypted)
changePassPhrase({'filename': filename, 'pass': 'encrypted'})
self.assertEqual(
self.stdout.getvalue().strip('\n'),
'Your identification has been saved with the new passphrase.')
self.assertNotEqual(privateRSA_openssh_encrypted,
FilePath(filename).getContent())
def test_changePassphraseWithBoth(self):
"""
L{changePassPhrase} allows a user to change the passphrase of a private
key by providing both old and new passphrases without prompting.
"""
filename = self.mktemp()
FilePath(filename).setContent(privateRSA_openssh_encrypted)
changePassPhrase(
{'filename': filename, 'pass': 'encrypted',
'newpass': 'newencrypt'})
self.assertEqual(
self.stdout.getvalue().strip('\n'),
'Your identification has been saved with the new passphrase.')
self.assertNotEqual(privateRSA_openssh_encrypted,
FilePath(filename).getContent())
def test_changePassphraseWrongPassphrase(self):
"""
L{changePassPhrase} exits if passed an invalid old passphrase when
trying to change the passphrase of a private key.
"""
filename = self.mktemp()
FilePath(filename).setContent(privateRSA_openssh_encrypted)
error = self.assertRaises(
SystemExit, changePassPhrase,
{'filename': filename, 'pass': 'wrong'})
self.assertEqual('Could not change passphrase: old passphrase error',
str(error))
self.assertEqual(privateRSA_openssh_encrypted,
FilePath(filename).getContent())
def test_changePassphraseEmptyGetPass(self):
"""
L{changePassPhrase} exits if no passphrase is specified for the
C{getpass} call and the key is encrypted.
"""
self.patch(getpass, 'getpass', makeGetpass(''))
filename = self.mktemp()
FilePath(filename).setContent(privateRSA_openssh_encrypted)
error = self.assertRaises(
SystemExit, changePassPhrase, {'filename': filename})
self.assertEqual(
'Could not change passphrase: Passphrase must be provided '
'for an encrypted key',
str(error))
self.assertEqual(privateRSA_openssh_encrypted,
FilePath(filename).getContent())
def test_changePassphraseBadKey(self):
"""
L{changePassPhrase} exits if the file specified points to an invalid
key.
"""
filename = self.mktemp()
FilePath(filename).setContent(b'foobar')
error = self.assertRaises(
SystemExit, changePassPhrase, {'filename': filename})
if _PY3:
expected = "Could not change passphrase: cannot guess the type of b'foobar'"
else:
expected = "Could not change passphrase: cannot guess the type of 'foobar'"
self.assertEqual(expected, str(error))
self.assertEqual(b'foobar', FilePath(filename).getContent())
def test_changePassphraseCreateError(self):
"""
L{changePassPhrase} doesn't modify the key file if an unexpected error
happens when trying to create the key with the new passphrase.
"""
filename = self.mktemp()
FilePath(filename).setContent(privateRSA_openssh)
def toString(*args, **kwargs):
raise RuntimeError('oops')
self.patch(Key, 'toString', toString)
error = self.assertRaises(
SystemExit, changePassPhrase,
{'filename': filename,
'newpass': 'newencrypt'})
self.assertEqual(
'Could not change passphrase: oops', str(error))
self.assertEqual(privateRSA_openssh, FilePath(filename).getContent())
def test_changePassphraseEmptyStringError(self):
"""
L{changePassPhrase} doesn't modify the key file if C{toString} returns
an empty string.
"""
filename = self.mktemp()
FilePath(filename).setContent(privateRSA_openssh)
def toString(*args, **kwargs):
return ''
self.patch(Key, 'toString', toString)
error = self.assertRaises(
SystemExit, changePassPhrase,
{'filename': filename, 'newpass': 'newencrypt'})
if _PY3:
expected = (
"Could not change passphrase: cannot guess the type of b''")
else:
expected = (
"Could not change passphrase: cannot guess the type of ''")
self.assertEqual(expected, str(error))
self.assertEqual(privateRSA_openssh, FilePath(filename).getContent())
def test_changePassphrasePublicKey(self):
"""
L{changePassPhrase} exits when trying to change the passphrase on a
public key, and doesn't change the file.
"""
filename = self.mktemp()
FilePath(filename).setContent(publicRSA_openssh)
error = self.assertRaises(
SystemExit, changePassPhrase,
{'filename': filename, 'newpass': 'pass'})
self.assertEqual(
'Could not change passphrase: key not encrypted', str(error))
self.assertEqual(publicRSA_openssh, FilePath(filename).getContent())
| [
"a.g.prosat@gmail.com"
] | a.g.prosat@gmail.com |
ac92840d81b09de0258ab555bab204bc20403d4c | d23da78d6c6d127c9c1df92850195613adc208b3 | /reversebyrecursion.py | c258c0f18dcb06a4c47a2a5e8cca0704b9ed1779 | [] | no_license | P-Madhulatha/become-coder | 9cea9dc09a72346982c22f7970b09c0c9643520c | 19be34b7f90c82abb32295ad1c655669ad8641ae | refs/heads/main | 2023-05-08T21:10:26.813985 | 2021-06-10T07:22:53 | 2021-06-10T07:22:53 | 369,201,855 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 120 | py | def rev(num):
if num==0:
return 1
return (num//10)*10+(num%10)
num=int(input())
print(rev(num))
| [
"noreply@github.com"
] | noreply@github.com |
e53f286f2ec166822f7132bd7d8b9537d365ae4d | 52c160960fe24e8294b27be1728013bb48d5c270 | /scripts/install.py | 88c87ab86474cccd80a0c648c31f880bab5687c1 | [
"MIT"
] | permissive | vchrisb/vagrant-scaleio-aws | 9ed038a42b0dfbf62d8c5a0677436ce1cd3f18c6 | e4e5887aa871cb0578485ac7571bc0788c2bfa10 | refs/heads/master | 2020-05-16T23:42:39.379182 | 2015-09-01T07:07:56 | 2015-09-01T07:07:56 | 40,844,858 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 5,777 | py | #!/usr/bin/env python
from scaleiopy import im
from scaleiopy import scaleioobject as sioobj
#from scaleio import installerfsm as instfsm
import time
import json
from pprint import pprint
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--nodeUsername", metavar='USERNAME', required=True, help="Username for ScaleIO Node OS")
parser.add_argument("--nodePassword", metavar='PASSWORD',required=True, help="Password for ScaleIO Node OS")
parser.add_argument("--mdmPassword", metavar='PASSWORD', required=True, help="Password for ScaleIO MDM")
parser.add_argument("--liaPassword", metavar='PASSWORD', required=True, help="Password for ScaleIO LIA")
parser.add_argument("--gwUsername", metavar='USERNAME', required=True, help="Username for ScaleIO GW")
parser.add_argument("--gwPassword", metavar='PASSWORD', required=True, help="Password for ScaleIO GW")
parser.add_argument("--gwIPaddress", metavar='IP', required=True, help="IP address for ScaleIO GW")
parser.add_argument("--packagePath", metavar='IP', required=True, help="Path where ScaleIO Packages are located")
parser.add_argument("--mdm1IPaddress", metavar='IP', required=True, help="IP address for ScaleIO MDM1")
parser.add_argument("--mdm2IPaddress", metavar='IP', required=True, help="IP address for ScaleIO MDM2")
parser.add_argument("--tbIPaddress", metavar='IP', required=True, help="IP address for ScaleIO TB")
parser.add_argument("--nodeIPaddresses", metavar='IP', nargs='+', required=True, help="IP addresses for ScaleIO nodes")
parser.add_argument("--device", metavar='IP', required=True, help="device for ScaleIO node")
args = parser.parse_args()
###################
# Construct nodes #
###################
nodeUsername = args.nodeUsername #'root' # Username for ScaleIO Node OS (these machines need to be pre installed)
nodePassword = args.nodePassword #'vagrant' # Password for ScaleIO Node OS
mdm1_node = sioobj.ScaleIO_Node_Object(None, None, [args.mdm1IPaddress], None, 'linux', nodePassword, nodeUsername)
mdm2_node = sioobj.ScaleIO_Node_Object(None, None, [args.mdm2IPaddress], None, 'linux', nodePassword, nodeUsername)
tb_node = sioobj.ScaleIO_Node_Object(None, None, [args.tbIPaddress], None, 'linux', nodePassword, nodeUsername)
##########################################
# Construct basic info for System_Object #
##########################################
mdmIPs = [mdm1_node.nodeIPs[0],mdm2_node.nodeIPs[0]]
sdcList = []
sdsList = []
mdmPassword = args.mdmPassword
liaPassword = args.liaPassword
licenseKey = None
installationId = None
########################################
# Create MDMs and TB for System_Object #
########################################
primaryMdm = sioobj.Mdm_Object(json.loads(mdm1_node.to_JSON()), None, None, mdm1_node.nodeIPs)
secondaryMdm = sioobj.Mdm_Object(json.loads(mdm2_node.to_JSON()), None, None, mdm2_node.nodeIPs)
tb = sioobj.Tb_Object(json.loads(tb_node.to_JSON()), None, tb_node.nodeIPs)
callHomeConfiguration = None # {'callHomeConfiguration':'None'}
remoteSyslogConfiguration = None # {'remoteSysogConfiguration':'None'}
################################################################
#Create SDS and SDC objects - To be added to SDS list in System_Object #
################################################################
for node_ip in args.nodeIPaddresses:
sio_node = sioobj.ScaleIO_Node_Object(None, None, [node_ip], None, 'linux', nodePassword, nodeUsername)
sds_obj = sioobj.Sds_Object(json.loads(sio_node.to_JSON()), None, 'SDS_' + str(sio_node.nodeIPs[0]), 'default', None, sio_node.nodeIPs, None, None, None, False, '7072')
sds_obj.addDevice(args.device, None, None)
sdsList.append(json.loads(sds_obj.to_JSON()))
sdc_obj = sioobj.Sdc_Object(json.loads(sio_node.to_JSON()), None, None)
sdcList.append(json.loads(sdc_obj.to_JSON()))
######################################################
# Construct a complete ScaleIO cluster configuration #
######################################################
sioobj = sioobj.ScaleIO_System_Object(installationId,
mdmIPs,
mdmPassword,
liaPassword,
licenseKey,
json.loads(primaryMdm.to_JSON()),
json.loads(secondaryMdm.to_JSON()),
json.loads(tb.to_JSON()),
sdsList,
sdcList,
callHomeConfiguration,
remoteSyslogConfiguration
)
# Export sioobj to JSON (should upload clean in IM)
###########################################################################
# Push System_Object JSON - To be used by IM to install ScaleIO on nodes #
###########################################################################
#######################
# LOGIN TO SCALEIO IM #
#######################
imconn = im.Im("https://" + args.gwIPaddress,args.gwUsername,args.gwPassword,verify_ssl=False,debugLevel='INFO') # "Password1!") # HTTPS must be used as there seem to be an issue with 302 responses in Requests when using POST
imconn._login()
### UPLOAD RPM PACKAGES TO BE DEPLOYED BY IM ###
imconn.uploadPackages(args.packagePath) # Adjust to your needs. All RPMs for RHEL7 should exist in this dir except for GUI and Gateway
####################
# INSTALLER STAGES #
####################
# Initialize Installer
im_installer = im.InstallerFSM(imconn, True)
print "Create minimal cluster as Python objects"
imconn.push_cluster_configuration(sioobj.to_JSON())
print "Start Install process!!!"
im_installer.Execute() # Start install process
time.sleep(30) # Wait a few seconds before continuing
| [
"vchrisb@users.noreply.github.com"
] | vchrisb@users.noreply.github.com |
d38ad13d5b90a52d56ed6d9da5384a5f4df4d21f | 746bf62ae3599f0d2dcd620ae37cd11370733cc3 | /leetcode/spiralmatrixtwo.py | c0075822c99847054ebdbfc8e1a03cd68cd9c653 | [] | no_license | wanglinjie/coding | ec0e614343b39dc02191455165eb1a5c9e6747ce | 350f28cad5ec384df476f6403cb7a7db419de329 | refs/heads/master | 2021-04-22T14:00:48.825959 | 2017-05-02T12:49:05 | 2017-05-02T12:49:05 | 48,011,510 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,106 | py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# date:20160711
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
"""
if not n:
return []
rows = n
columns = n
loop = 0
if n & 0x1:
loop = n / 2 + 1
else:
loop = n / 2
# 为什么使用下面创建数组,matrix[1][2]=1赋值,会将第2列的值都赋值为1?
# matrix = [[0] * n] * n
matrix = []
for i in xrange(n):
matrix.append([0] * n)
number = 1
for i in xrange(loop):
row = i
column = i
read_num = 0
read_rows = rows - 2 * i
read_columns = columns - 2 * i
if (read_rows == 1) or (read_columns == 1):
read_num = read_rows * read_columns
else:
read_num = 2 * read_rows + 2 * (read_columns - 2)
while read_num:
read_num -= 1
matrix[row][column] = number
# print matrix
# print row, column, number
# print
number += 1
if (row == i) and (column < (columns - i - 1)):
column += 1
elif (column == (columns - i - 1)) and (row < (rows - i - 1)):
row += 1
elif (row == (rows - i - 1)) and (column > i):
column -= 1
elif (column == i) and (row > i):
row -= 1
return matrix
n = 3
# so = Solution()
# print so.generateMatrix(n)
matrix = [[0] * n] * n
# matrix = []
# for i in xrange(n):
# matrix.append([0]*n)
# matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
print matrix
matrix[0][1] = 1
print matrix
print matrix[0][2]
matrix[0][2] = 2
print matrix | [
"hitwhwlj@163.com"
] | hitwhwlj@163.com |
db39ab194ef50c47dac4933b268bd54e7709502b | c4c79211b126a9a77c129f309873625cd7be0537 | /resume-analyzer/resume/urls.py | b05f4f0570ef5a6b40266367303f7e0f450f5259 | [] | no_license | joonyi/Django | 77dd29df9f824255e90a307f8ece810d0ba09417 | b5d9b0a8ce1a7afe0cf8bd039156842775c574dc | refs/heads/master | 2022-05-05T01:22:48.387066 | 2022-04-06T12:25:57 | 2022-04-06T12:25:57 | 221,844,523 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 393 | py | from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from .api import ResumeList, ResumeDetail, ResumeAuthentication
# from resume import views
urlpatterns = [
path('', ResumeList.as_view()),
path('<int:company_id>/', ResumeDetail.as_view()),
path('auth/', ResumeAuthentication.as_view())
]
urlpatterns = format_suffix_patterns(urlpatterns)
| [
"joonyi2011@gmail.com"
] | joonyi2011@gmail.com |
cfebc0cf1762c76051bc5679deb3514b327202f2 | 497a0de6c7be6d2c4f2620fef365ad27715cd1d7 | /parser.py | 46c7ce84e1013644c9d1ec285ae34d2a5fd9b09f | [] | no_license | kuzmik/whatsapp-parser | 59fe3f0a7139a25aa5512e4b1f35f0a5ed128b98 | f505b215c090d7b69b9a565816a5eafddf6117b0 | refs/heads/master | 2021-01-15T21:30:36.167180 | 2017-08-10T03:01:02 | 2017-08-10T03:01:02 | 99,871,503 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,911 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
import argparse
import os
import re
import sqlite3
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--filename', help='the file to parse')
parser.add_argument('-d', '--write-to-db', action="store_true", default=False, help="Write the log to the database")
args = parser.parse_args()
if not args.filename:
print "You need to specify a file to parse"
parser.print_help()
exit(1)
# create a sqlite3 database to hold the logs
if args.write_to_db:
db = sqlite3.connect('logs.db')
db.text_factory = str
db.execute('CREATE TABLE IF NOT EXISTS logs (id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp DATETIME, username TEXT, message TEXT)')
# https://regex101.com/r/pMp8Gz/1
#TODO: combine these two res into one. should be doable.
re_parser = re.compile('(?P<timestamp>\d{1,2}[/.]\d{1,2}[/.]\d{2,4},? \d{1,2}:\d{2}(?::\d{2})?(?: [AP]M)?)(?: -|:) (?P<username>.+?): (?P<message>.+)')
re_attach = re.compile('(?P<filename>.+) <.+attached>', re.UNICODE)
log = open(args.filename).readlines()
for line in log:
match = re_parser.match(line)
if match:
line = line.replace('\r\n', ' ')
dt = datetime.strptime(match.group('timestamp'), '%m/%d/%y, %H:%M:%S')
who = match.group('username')
message = match.group('message')
amatch = re_attach.match(message)
if amatch:
pass
# attachment messages look like: `ATTACHMENT: 2017-03-19-PHOTO-00003492.jpg <<U+200E>attached>`
print 'ATTACHMENT: {} -> {}'.format(match.group('username'), amatch.group('filename'))
else:
pass
# normal chat message
print "({}) {}: {}".format(dt, who, message)
if args.write_to_db:
db.execute(u'insert into logs (timestamp, username, message) values(?, ?, ?)', (dt, who, message))
# Fix my name
if args.write_to_db:
db.execute('update logs set username = "Nick Kuzmik" where username = "Nick"')
db.commit()
| [
"nick.martini@gmail.com"
] | nick.martini@gmail.com |
fe3cb1fb55073ac15e92623356da8d653622ca98 | 04936e0275e7516da7176365510116a3636caa37 | /blog/migrations/0003_auto_20150616_0948.py | d38b630beb2b035bca5eaf617b8b71750f965493 | [] | no_license | amarshukla/myBlog | 5e6cf0a6a9b4aa2df75220691825b42d2ba4728b | 9308636b915354d57dc4a82fe5b22787f9de7551 | refs/heads/master | 2021-01-22T12:12:10.631491 | 2015-07-02T16:36:27 | 2015-07-02T16:36:27 | 37,149,214 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,112 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_album_artist_customer_employee_genre_invoice_invoiceline_mediatype_playlist_playlisttrack_track'),
]
operations = [
migrations.DeleteModel(
name='Album',
),
migrations.DeleteModel(
name='Artist',
),
migrations.DeleteModel(
name='Customer',
),
migrations.DeleteModel(
name='Employee',
),
migrations.DeleteModel(
name='Genre',
),
migrations.DeleteModel(
name='Invoice',
),
migrations.DeleteModel(
name='Invoiceline',
),
migrations.DeleteModel(
name='Mediatype',
),
migrations.DeleteModel(
name='Playlist',
),
migrations.DeleteModel(
name='Playlisttrack',
),
migrations.DeleteModel(
name='Track',
),
]
| [
"amarshukla123@gmail.com"
] | amarshukla123@gmail.com |
320ce472a049c0d4a5b95fb42f0380c7fe149eae | 62b050fd0d19e315b0b2ef8e001ea0165ce01348 | /LogProducer/log_manager.py | 0d513bec043d0b0b90f0b016601ddceaf16cfe36 | [] | no_license | quangkhanh250699/GGTraceStreaming | c71fb4119e587b5002e8b56d9b1d9707ebd789ea | 5fe1e196809ebc62915ebbb163e9953a04666625 | refs/heads/main | 2023-02-05T15:00:03.785249 | 2020-12-21T17:41:02 | 2020-12-21T17:41:02 | 315,303,845 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,142 | py | # author: Khanh.Quang
# institute: Hanoi University of Science and Technology
# file name: log_manager.py
# project name: LogProducer
# date: 24/11/2020
from connector import Connector, KafkaConnector
from config import ConnectorConfig, LoggerConfig
from logger import TaskUsageLogger, Logger, TaskEventLogger
from timer import Timer
from typing import List, Tuple, Set
import time
def _get_connector(config: ConnectorConfig):
name = config.name
if name == "KAFKA_CONNECTOR":
return KafkaConnector(config)
else:
raise Exception("Not found type of connector!")
def _get_logger(config: LoggerConfig):
name = config.name
if name == "TASK_USAGE":
return TaskUsageLogger.get_instance(config)
elif name == "TASK_EVENT":
return TaskEventLogger.get_instance(config)
else:
raise Exception("Not found type of logger config named {}".format(name))
class LogManager:
__logger_configs: List[LoggerConfig]
__connector_configs: List[ConnectorConfig]
__loggers: List[Logger]
__connectors: List[Connector]
__logger_types: Set
__interval_log: float
__interval_waiting: float
def __init__(self, configs: List[Tuple[LoggerConfig, ConnectorConfig]],
interval_log: 5,
interval_waiting: 2):
self.__interval_log = interval_log
self.__interval_waiting = interval_waiting
Timer(self.__interval_log)
self.__logger_configs = [config[0] for config in configs]
self.__connector_configs = [config[1] for config in configs]
self.__loggers = list()
self.__connectors = list()
self.__logger_types = set()
self.__set_log_and_connection()
def dispatch_logs(self):
while True:
clock = Timer.clock()
for i in range(len(self.__loggers)):
payload = self.__loggers[i].log()
print(self.__loggers[i].get_name() + " sent " + str(payload.__len__()) + " messages")
self.__connectors[i].submit(payload)
time.sleep(self.__interval_waiting)
def __set_log_and_connection(self):
for i in range(len(self.__logger_configs)):
logger_config = self.__logger_configs[i]
connector_config = self.__connector_configs[i]
name = logger_config.name
if name in self.__logger_types:
continue
self.__logger_types.add(name)
self.__loggers.append(_get_logger(logger_config))
self.__connectors.append(_get_connector(connector_config))
if __name__ == '__main__':
task_usage_logger_config = LoggerConfig("TASK_USAGE", 300)
task_usage_connector_config = ConnectorConfig("KAFKA_CONNECTOR", "TASK-USAGE")
task_event_logger_config = LoggerConfig("TASK_EVENT", 300)
task_event_connector_config = ConnectorConfig("KAFKA_CONNECTOR", "TASK-EVENT")
manager = LogManager([(task_usage_logger_config, task_usage_connector_config),
(task_event_logger_config, task_event_connector_config)],
100, 5)
manager.dispatch_logs()
| [
"quangkhanh250699@gmail.com"
] | quangkhanh250699@gmail.com |
6063ec497dbc221ec2e75ecfdaed805bbc9aeede | 00d8393f987738ec1d70c116b98614e29c8f1c1a | /rpa_basic/1_excel/15_unmerge.py | 8ffd183bade4788055657cc3041beb291015536f | [] | no_license | hanwoolsky/RPA_Python | 2be524a8ea616502ecdfc33ba4d4d550e2f4544f | f48cc20f2fe299caab2cde7904284b582ec5b6b4 | refs/heads/main | 2023-02-24T11:05:22.416239 | 2021-02-02T05:57:41 | 2021-02-02T05:57:41 | 334,890,652 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 199 | py | from openpyxl import load_workbook
wb = load_workbook("sample_merge.xlsx")
ws = wb.active
# 셀 나누기
ws.unmerge_cells("B2:D2") #B2부터 D2까지 합치겠음
wb.save("sample_merge.xlsx") | [
"hhw0925@naver.com"
] | hhw0925@naver.com |
440bfdebbceb6eaef3277aca9941a759e42ae116 | 7beff965d7b0e6155d6d52b27d71c557421d5ada | /aoj/grl_7_a.py | 830ad7ec1ba09ea22f3deb70e180d4910bd89f7e | [] | no_license | uk-ar/competitive_programming | 82a53a1007798843ac006b9c7d313826e6cb45c3 | d2523cf303f47644cada3b03e9eed2349bdbe394 | refs/heads/master | 2023-03-28T13:20:07.728861 | 2021-03-30T20:25:55 | 2021-03-30T20:25:55 | 249,638,234 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,613 | py | #!/usr/bin/env python3
# N,M = map(int,sys.stdin.readline().split())
# a = tuple(map(int,sys.stdin.readline().split())) # single line with multi param
# a = tuple(int(sys.stdin.readline()) for _ in range(N)) # multi line with single param
# a = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(N)) # multi line with multi param
# s = sys.stdin.readline().rstrip()
# N = int(sys.stdin.readline())
# INF = float("inf")
import sys,collections
sys.setrecursionlimit(100000)
INF = float("inf")
X,Y,E = map(int,sys.stdin.readline().split())
xy = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(E)) # multi line with multi param
#uvc = [[0,1,1],[0,2,3],[1,2,1],[2,3,2]]
#xy = [[0,0],[1,2],[2,2],[1,3]]
V = X+Y+2
uvc = [[x+1,y+X+1,1] for x,y in xy]
for i in range(X):
uvc.append([0,i+1,1])
for i in range(Y):
uvc.append([X+i+1,V-1,1])
G = {i:{} for i in range(V)}
mG = {i:{} for i in range(V)}
for u,v,c in uvc:
G[u][v] = c
G[v][u] = 0 # reverse edge
mG[u][v] = 0
mG[v][u] = 0
# print(G)
# print(mG)
def dfs(current,flow):
if current == V-1:
return flow
visited.add(current)
for nex,nex_c in G[current].items():
if not nex in visited and nex_c != 0:
f = dfs(nex,min(flow,nex_c))
if f != 0:
mG[current][nex] = mG[current][nex] + f
G[current][nex] = G[current][nex] - f
G[nex][current] = G[nex][current] + f
return f
return 0
visited = set()
while dfs(0,INF) != 0:
visited = set()
pass
print(sum(mG[0].values()))
| [
"yuuki.ari@gmail.com"
] | yuuki.ari@gmail.com |
16b9e3117deda1fc093cba36290f4be82997e077 | 2e943e43d169d91673ec3f160673c511315dc724 | /twitter.py | f1e96b390c43af7adec0604b1adc322467e01e14 | [] | no_license | emptyflash/slitscan_bot | 2127974a5dfec507857aaec4769d80e8b8743895 | 52cade0d27414f927f6c1391b276376a43422de8 | refs/heads/master | 2022-12-12T05:59:05.182878 | 2019-10-23T16:40:59 | 2019-10-23T16:40:59 | 102,990,459 | 1 | 0 | null | 2022-12-08T00:41:56 | 2017-09-09T23:14:00 | Python | UTF-8 | Python | false | false | 414 | py | import tweepy
from creds import CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
def upload_images(images):
return [api.media_upload(i).media_id_string for i in images]
def tweet_images(image_ids):
api.update_status(status="", media_ids=image_ids)
| [
"emptyflash@gmail.com"
] | emptyflash@gmail.com |
fa622d926d4f97435b8b18333ed9ee028845fb7c | 6675789cc39b4194974dfb80647850bdcd2210c8 | /autodc/components/feature_engineering/transformations/preprocessor/weight_balancer.py | ede6cd72340e016622208ccaeba501c0093bce4a | [
"MIT"
] | permissive | dingdian110/AutoDC | 87c88ab6871a70a2ba6ade2ff571f30000b7fd06 | f5ccca6bea993bcff3e804fb859e8b25ae020b5c | refs/heads/master | 2023-08-26T17:17:55.960309 | 2021-10-30T07:14:19 | 2021-10-30T07:14:19 | 383,118,722 | 3 | 2 | null | null | null | null | UTF-8 | Python | false | false | 547 | py | from autodc.components.feature_engineering.transformations.base_transformer import *
class WeightBalancer(Transformer):
def __init__(self, random_state=1):
super().__init__("weight_balancer", 20)
self.random_state = random_state
def operate(self, input_datanode: DataNode, target_fields=None):
output_datanode = input_datanode.copy_()
if output_datanode.data_balance != 1:
output_datanode.enable_balance = 1
output_datanode.trans_hist.append(self.type)
return output_datanode
| [
"baiyang85@gmail.com"
] | baiyang85@gmail.com |
da88288f281baad769af1ccbf83b2777ed6a91a0 | 3f7c27ccd0ab1fcbd2583cf4b764b81bd27dd718 | /apps/members/urls.py | 03acc1cb09f082fefdc65dd6e430675e3a4ac2b6 | [] | no_license | adamtlord/foreverland | 001ca1a91a3cc468405efb80fe7981e75b82021c | 8206ddeeb8cfbd2752ef6fa9839424718cb96e07 | refs/heads/master | 2020-04-16T00:50:51.582008 | 2016-09-21T03:27:39 | 2016-09-21T03:27:39 | 11,668,672 | 0 | 0 | null | 2016-09-04T03:46:51 | 2013-07-25T19:05:55 | Python | UTF-8 | Python | false | false | 144 | py | from django.conf.urls import patterns, url
urlpatterns = patterns('members.views',
url(r'^$', 'list_members', {}, name='list_members'),
)
| [
"adam.lord@gmail.com"
] | adam.lord@gmail.com |
72a51d7c5fad898be8b1c326d1301e36e6318c29 | fd161a5e18014f0ff82a7dddc25e95ad6dddd2ac | /models/dnc/dnc_ff_split_controller.py | af53120d1e588d6e18f4189087dd1d332c51a201 | [
"MIT"
] | permissive | Kajiyu/MANNs | 1826c0aad76a708030cef61c974ee1bdf3b58635 | 3d6876aefdf4efeebb3861f8430e6dbe62f8df6d | refs/heads/master | 2020-03-27T16:03:46.591270 | 2018-09-02T01:56:29 | 2018-09-02T01:56:29 | 146,757,184 | 14 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,657 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import os, sys
from models.meta.controller import Controller
from models.utils import *
class DNCFFSplitController(Controller):
def __init__(self, args):
super(DNCFFSplitController, self).__init__(args)
self.in_to_hid = nn.Linear(self.input_dim, self.hidden_dim)
self.mem_to_hid = nn.Linear(self.read_vec_dim, self.hidden_dim)
layers = []
layers.append(nn.Linear(2*self.hidden_dim, self.hidden_dim))
layers.append(nn.ReLU())
for i in range(self.num_hid_layers):
layers.append(nn.Linear(self.hidden_dim, self.hidden_dim))
layers.append(nn.ReLU())
if self.dropout_value > 0:
layers.append(nn.Dropout(p=self.dropout_value))
self.linears = nn.Sequential(*layers)
m = self.num_address
w = self.mem_cell_dim
r = self.read_heads
self.interface_size = (w * r) + (3 * w) + (5 * r) + 3
self.hid_to_mem = nn.Linear(self.hidden_dim, self.interface_size)
self.hid_to_out = nn.Linear(self.hidden_dim, self.output_dim)
def _init_weights(self):
pass
def forward(self, x, read):
x = self.in_to_hid(x)
read = self.mem_to_hid(read)
input_vec = torch.cat((x, read), dim=-1)
output_vec = self.linears(input_vec)
out_to_mem_vec = self.hid_to_mem(output_vec)
output_vec = self.hid_to_out(output_vec)
return out_to_mem_vec, output_vec | [
"kajimars.uts1@gmail.com"
] | kajimars.uts1@gmail.com |
90903a0da15b909462c311070545e1c44c8a4c67 | 1e76ae22907c53f4b5813e5d152ae3e3bf933265 | /lstm/d_LSTM_v1.py | c18f4d200304b14a57342ef3078f8962396fdfb8 | [
"Apache-2.0"
] | permissive | alecuba16/python_pytorch_keras_models | 2ab2c6ce536693ffe3fc947f5b3c2db8c80f7284 | 0784476661b30ee7dfb70ec708bf1a3a1b7f2650 | refs/heads/main | 2023-08-17T15:57:03.389791 | 2021-09-10T10:39:10 | 2021-09-10T10:39:10 | 405,043,359 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 18,630 | py | import pandas as pd
import numpy as np
from functions.load_wtdata import load_wtdata
from pathlib import Path
import gc
import tempfile
import os
#Configs
db_config = {'table_cast_park_dic':'1_cast_park_table_dic','host':"127.0.0.1",'user':"itestit",'password':"itestit2014",'db':"SCHistorical_DB"}
exclude_columns = ['alarm_block_code','alarm_all','alarm_all_block_code','alarm','ot','ot_block_code','ot_all','ot_all_block_code']
datetime_name = 'date_time'
result_folder = 'results'
if not os.path.exists(result_folder):
os.makedirs(result_folder)
batch_size = 500
Marging=15 #15 dias antes los datos son malos.
# 2014-2015
# 'unix_timestamp_ini':1388534400,
# 'unix_timestamp_end':1420070399,
# 2015-2016
# 'unix_timestamp_ini':1420070499,
# 'unix_timestamp_end':1451606399,
# 2014-2016
#'unix_timestamp_ini':1388534400,
#'unix_timestamp_end':1451606399,
# 2016->
#'unix_timestamp_ini_test':1451606400,
#'unix_timestamp_end_test':1498236799,
#wt_query = {'timesteps':100,'epochs':50,'class_weight':{0: 1.,1: 10.},'ld_id':194,'ld_code':"B211",'wp_id':20,'wp_code':"izco",'seconds_to_aggregate':600,'array_id_walm':"607,608,613,627,631,659",'array_ot':"10067,10068",'freq_dat_med_min':10,'fault':'Gbox','type':"phealtdeep",'filter':"",'power_condition':"",'include_variables':"",'exclude_variables':"regex:model|fake_data|^SPCosPhi|^FrecRed|^Estado",'target_name':"alarm",'unix_timestamp_ini':1388534400,'unix_timestamp_end':1420070399,'unix_timestamp_ini_test':1420070499,'unix_timestamp_end_test':1500000000}
#wt_query = {'timesteps':100,'epochs':50,'class_weight':{0: 1.,1: 500.},'ld_id':212,'ld_code':"B312",'wp_id':20,'wp_code':"izco",'seconds_to_aggregate':600,'array_id_walm':"614,615,616,636,639,641",'array_ot':"10004",'freq_dat_med_min':10,'fault':'Gen','type':"phealtdeep",'filter':"",'power_condition':"",'include_variables':"",'exclude_variables':"regex:model|fake_data|^SPCosPhi|^FrecRed|^Estado",'target_name':"alarm",'unix_timestamp_ini':1388534400,'unix_timestamp_end':1420070399,'unix_timestamp_ini_test':1420070499,'unix_timestamp_end_test':1500000000}
#wt_query = {'timesteps':100,'epochs':50,'class_weight':{0: 1.,1: 100.},'ld_id':211,'ld_code':"B311",'wp_id':20,'wp_code':"izco",'seconds_to_aggregate':600,'array_id_walm':"614,615,616,636,639,641",'array_ot':"10004",'freq_dat_med_min':10,'fault':'Gen','type':"phealtdeep",'filter':"",'power_condition':"",'include_variables':"",'exclude_variables':"regex:model|fake_data|^SPCosPhi|^FrecRed|^Estado",'target_name':"alarm",'unix_timestamp_ini':1388534400,'unix_timestamp_end':1451606399,'unix_timestamp_ini_test':1420070499,'unix_timestamp_end_test':1500000000}
#wt_query = {'timesteps':100,'epochs':50,'class_weight':{0: 1.,1: 500.},'ld_id':189,'ld_code':"B206",'wp_id':20,'wp_code':"izco",'seconds_to_aggregate':600,'array_id_walm':"614,615,616,636,639,641",'array_ot':"10004",'freq_dat_med_min':10,'fault':'Gen','type':"phealtdeep",'filter':"",'power_condition':"",'include_variables':"",'exclude_variables':"regex:model|fake_data|^SPCosPhi|^FrecRed|^Estado",'target_name':"alarm",'unix_timestamp_ini':1388534400,'unix_timestamp_end':1420070399,'unix_timestamp_ini_test':1420070499,'unix_timestamp_end_test':1500000000}
#wt_query = {'timesteps':100,'epochs':50,'class_weight':{0: 1.,1: 500.},'ld_id':179,'ld_code':"B113",'wp_id':20,'wp_code':"izco",'seconds_to_aggregate':600,'array_id_walm':"614,615,616,636,639,641",'array_ot':"10004",'freq_dat_med_min':10,'fault':'Gen','type':"phealtdeep",'filter':"",'power_condition':"",'include_variables':"",'exclude_variables':"regex:model|fake_data|^SPCosPhi|^FrecRed|^Estado",'target_name':"alarm",'unix_timestamp_ini':1388534400,'unix_timestamp_end':1420070399,'unix_timestamp_ini_test':1420070499,'unix_timestamp_end_test':1500000000}
wt_query = {'timesteps':100,'epochs':50,'class_weight':{0: 1.,1: 500.},'ld_id':201,'ld_code':"B301",'wp_id':20,'wp_code':"izco",'seconds_to_aggregate':600,'array_id_walm':"614,615,616,636,639,641",'array_ot':"10004",'freq_dat_med_min':10,'fault':'Gen','type':"phealtdeep",'filter':"",'power_condition':"",'include_variables':"",'exclude_variables':"regex:model|fake_data|^SPCosPhi|^FrecRed|^Estado",'target_name':"alarm",'unix_timestamp_ini':1388534400,'unix_timestamp_end':1420070399,'unix_timestamp_ini_test':1420070499,'unix_timestamp_end_test':1500000000}
#Fuhrlander
#wt_query = {'timesteps':50,'epochs':10,'class_weight':{0: 1.,1: 500.},'ld_id':80,'ld_code':"FL701",'wp_id':13,'wp_code':"sant",'seconds_to_aggregate':300,'array_id_walm':"1271,1329,964,1306,2302,2304,2306,1369,1370",'array_ot':"",'freq_dat_med_min':5,'fault':'Gbox','type':"phealtdeep",'filter':"",'power_condition':"",'include_variables':"",'exclude_variables':"regex:model|fake_data|^SPCosPhi|^FrecRed|^Estado",'target_name':"alarm",'unix_timestamp_ini':1325376000,'unix_timestamp_end':1356998399,'unix_timestamp_ini_test':1388534400,'unix_timestamp_end_test':1420070399}
timesteps=wt_query['timesteps']
filename=str(result_folder+'/'+wt_query['ld_code'])+'_wtdata_train_'+wt_query['fault']+'_'+wt_query['target_name']+'_'+str(wt_query['unix_timestamp_ini'])+'_'+str(wt_query['unix_timestamp_end'])+'.csv.gz'
if not Path(filename).is_file():
print(filename+" not found...Downloading train data...")
wtdata_train=load_wtdata(wt_query=wt_query,db_config=db_config)
wtdata_train.to_csv(filename, sep=',',index =False,compression='gzip')
else:
print("Loading disk train data...")
wtdata_train = pd.read_csv(filename, sep=',', compression='gzip',low_memory=False)
#Format date_time
wtdata_train[datetime_name]=pd.to_datetime(wtdata_train[datetime_name],format='%Y-%m-%d %H:%M:%S')
if wt_query['target_name']=='alarm' and 'ot_all' in wtdata_train.columns:
#wtdata_train.loc[wtdata_train['ot_all'] == 1, 'alarm'] = 0
wtdata_train = wtdata_train[wtdata_train['ot_all'] != 1]
if wt_query['target_name']=='alarm' and 'ot' in wtdata_train.columns:
wtdata_train=wtdata_train[wtdata_train['ot'] != 1]
#Modify alarm to do pre_alarm
#from datetime import datetime, timedelta
#Anticipation = 14
#Marging=14
#dates_prealarm=[]
#active_alarms=wtdata_train[wtdata_train[wt_query['target_name']]==1][datetime_name].values
#for alarm in active_alarms:
# for m in range(0,Marging):
# dates_prealarm.append(alarm - np.timedelta64(Anticipation+m, 'D'))
#wtdata_train.loc[wtdata_train[datetime_name].isin(active_alarms),wt_query['target_name']]=0
#wtdata_train.loc[wtdata_train[datetime_name].isin(dates_prealarm),wt_query['target_name']]=1
from datetime import datetime, timedelta
dates_prealarm=[]
active_alarms=wtdata_train[wtdata_train[wt_query['target_name']]==1][datetime_name].values
for alarm in active_alarms:
for m in range(0,Marging):
dates_prealarm.append(alarm - np.timedelta64(m, 'D'))
wtdata_train.loc[wtdata_train[datetime_name].isin(active_alarms),wt_query['target_name']]=0
wtdata_train.loc[wtdata_train[datetime_name].isin(dates_prealarm),wt_query['target_name']]=1
del dates_prealarm, active_alarms
a=set(wtdata_train.columns)
a.difference
to_drop = set(wtdata_train.columns).intersection(exclude_columns).difference([wt_query['target_name']])
if any(to_drop):
wtdata_train = wtdata_train.drop(to_drop, axis=1)
#Identify columns all NA
idx_NA_columns_train = pd.isnull(wtdata_train).sum()>0.9*wtdata_train.shape[0]
if any(idx_NA_columns_train):
wtdata_train=wtdata_train.drop(idx_NA_columns_train[idx_NA_columns_train==True].index,axis=1)
wtdata_train = wtdata_train.dropna(axis=0,how='any',subset=set(wtdata_train.columns).difference(['date_time']))
y_train = wtdata_train.loc[:, wt_query['target_name']]
y_train = y_train.as_matrix()
X_train = wtdata_train.drop([wt_query['target_name']], axis=1)
del wtdata_train
gc.collect()
## Splitting the dataset into the Training set and Test set
#def non_shuffling_train_test_split(X, y, test_size=0.2):
# import numpy as np
# i = int((1 - test_size) * X.shape[0]) + 1
# X_train, X_test = np.split(X, [i])
# y_train, y_test = np.split(y, [i])
# return X_train, X_test, y_train, y_test
#
#X_train, X_test, y_train, y_test = non_shuffling_train_test_split(X, y, test_size = 0.1)
#Copy and Drop date_time
X_train_df=X_train[datetime_name]
to_drop = set(X_train.columns).intersection([datetime_name,wt_query['target_name']])
X_train=X_train.drop(to_drop, axis=1)
num_features = X_train.shape[1]
num_rows = X_train.shape[0]
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train.as_matrix())
# Reshaping
#X_train = np.reshape(X_train, (X_train.shape[0], 1,X_train.shape[1]))
# Creating a data structure with timesteps and t+1 output
#Save in disk to get free memory
temp_train = tempfile.NamedTemporaryFile(prefix='temp_train')
X_temp_timestepped=np.memmap(temp_train, dtype='float64', mode='w+', shape=((X_train.shape[0]-timesteps),timesteps,X_train.shape[1]))
#X_temp_timestepped=np.empty(shape=((num_rows-timesteps)*timesteps,num_features))
#X_temp_timestepped=np.memmap('temp_matrix.tmp', dtype='float64', mode='w+', shape=((num_rows-timesteps)*timesteps,num_features))
for i in range(timesteps,X_train.shape[0]):
X_temp_timestepped[i-timesteps,:]=np.reshape(X_train[i-timesteps:i, :],(timesteps,X_train.shape[1]))
X_train=X_temp_timestepped
del X_temp_timestepped
y_train=y_train[timesteps:]
gc.collect()
#Disable GPU
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
#Seed
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
filename_model=str(result_folder+'/'+wt_query['ld_code'])+'_wtdata_train_'+wt_query['fault']+'_'+wt_query['target_name']+'_'+str(wt_query['unix_timestamp_ini'])+'_'+str(wt_query['unix_timestamp_end'])+'_model'
if not Path(filename_model+'.json').is_file():
def build_classifier2(input_dim):
classifier = Sequential()
classifier.add(LSTM(units = 10, return_sequences=True,input_shape = (timesteps,input_dim[1])))
classifier.add(LSTM(units = 10, return_sequences=True))
classifier.add(LSTM(units = 10))
classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
return classifier
classifier2 = build_classifier2([X_train.shape[0],X_train.shape[2]])
# Fitting the ANN to the Training set
classifier2.fit(np.array(X_train), np.array(y_train), batch_size = batch_size, epochs = wt_query['epochs'],class_weight = wt_query['class_weight'])
#Save model
# serialize model to JSON
model_json = classifier2.to_json()
filename_model=str(result_folder+'/'+wt_query['ld_code'])+'_wtdata_train_'+wt_query['fault']+'_'+wt_query['target_name']+'_'+str(wt_query['unix_timestamp_ini'])+'_'+str(wt_query['unix_timestamp_end'])+'_model'
with open(filename_model+'.json', "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
classifier2.save_weights(filename_model+'.h5')
print("Saved model to disk")
else:
json_file = open(filename_model + '.json', 'r')
classifier2 = json_file.read()
json_file.close()
from keras.models import model_from_json
classifier2 = model_from_json(classifier2)
# load weights into new model
classifier2.load_weights(filename_model+'.h5')
print("Loaded model from disk")
# # load json and create model
# json_file = open(filename_model+'.json', 'r')
# classifier2 = json_file.read()
# json_file.close()
# from keras.models import model_from_json
# classifier2 = model_from_json(classifier2)
# # load weights into new model
# classifier2.load_weights(filename_model+'.h5')
# print("Loaded model from disk")
## Load test data
bk_ini=wt_query['unix_timestamp_ini']
bk_end=wt_query['unix_timestamp_end']
wt_query['unix_timestamp_ini']=wt_query['unix_timestamp_ini_test']
wt_query['unix_timestamp_end']=wt_query['unix_timestamp_end_test']
filename=str(result_folder+'/'+wt_query['ld_code'])+'_wtdata_test_'+wt_query['fault']+'_'+wt_query['target_name']+'_'+str(wt_query['unix_timestamp_ini'])+'_'+str(wt_query['unix_timestamp_end'])+'.csv.gz'
if not Path(filename).is_file():
print(filename + " not found...Downloading test data...")
wtdata_test=load_wtdata(wt_query=wt_query,db_config=db_config)
wtdata_test.to_csv(filename, sep=',',index =False,compression='gzip')
else:
print("Loading disk test data...")
wtdata_test = pd.read_csv(filename, sep=',', compression='gzip',low_memory=False)
wt_query['unix_timestamp_ini']=bk_ini
wt_query['unix_timestamp_end']=bk_end
wtdata_test[datetime_name]=pd.to_datetime(wtdata_test[datetime_name],format='%Y-%m-%d %H:%M:%S')
if wt_query['target_name']=='alarm' and 'ot_all' in wtdata_test.columns:
wtdata_test.loc[wtdata_test['ot_all'] == 1, 'alarm'] = 0
if wt_query['target_name']=='alarm' and 'ot' in wtdata_test.columns:
wtdata_test.loc[wtdata_test['ot'] == 1, 'alarm'] = 0
to_drop = set(wtdata_test.columns).intersection(exclude_columns).difference([wt_query['target_name']])
if any(to_drop):
wtdata_test = wtdata_test.drop(to_drop, axis=1)
dates_prealarm=[]
active_alarms=wtdata_test[wtdata_test[wt_query['target_name']]==1][datetime_name].values
for alarm in active_alarms:
for m in range(0,Marging):
dates_prealarm.append(alarm - np.timedelta64(m, 'D'))
wtdata_test.loc[wtdata_test[datetime_name].isin(active_alarms),wt_query['target_name']]=0
wtdata_test.loc[wtdata_test[datetime_name].isin(dates_prealarm),wt_query['target_name']]=1
if any(idx_NA_columns_train):
wtdata_test=wtdata_test.drop(idx_NA_columns_train[idx_NA_columns_train==True].index,axis=1)
wtdata_test = wtdata_test.dropna(axis=0,how='any',subset=set(wtdata_test.columns).difference(['date_time']))
y_test = wtdata_test.loc[:, wt_query['target_name']]
y_test = y_test.as_matrix()
X_test = wtdata_test.drop([wt_query['target_name']], axis=1)
del wtdata_test
X_test_df=X_test[datetime_name]
to_drop = set(X_test.columns).intersection([datetime_name,wt_query['target_name']])
X_test=X_test.drop(to_drop, axis=1)
X_test = sc.transform(X_test.as_matrix())
temp_test = tempfile.NamedTemporaryFile(prefix='temp_train')
X_temp_timestepped=np.memmap(temp_test, dtype='float64', mode='w+', shape=((X_test.shape[0]-timesteps),timesteps,X_test.shape[1]))
#X_temp_timestepped=np.empty(shape=((num_rows-timesteps)*timesteps,num_features))
#X_temp_timestepped=np.memmap('temp_matrix.tmp', dtype='float64', mode='w+', shape=((num_rows-timesteps)*timesteps,num_features))
for i in range(timesteps,X_test.shape[0]):
X_temp_timestepped[i-timesteps,:]=np.reshape(X_test[i-timesteps:i, :],(timesteps,X_test.shape[1]))
X_test=X_temp_timestepped
del X_temp_timestepped
y_test=y_test[timesteps:]
gc.collect()
## End prepare test data
# Predicting the Test set results
y_pred = classifier2.predict(X_test)
y_pred_df = pd.DataFrame(y_pred)
y_pred_bin = (y_pred > 0.5)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred_bin)
from sklearn.metrics import cohen_kappa_score
kap = cohen_kappa_score(y_pred_bin,y_test)
accuracy='NA'
if(np.unique(y_test).size>1 and np.unique(y_pred_bin).size>1):
numerator=(cm[0,0]+cm[1,1])
denominator=sum(sum(cm))
if(denominator!=0 and (numerator!=denominator or denominator!=0)) :
accuracy=(cm[0,0]+cm[1,1])/sum(sum(cm))
print(accuracy)
print(kap)
#print(y_pred_df)
pre_alarm_dates=pd.DataFrame({'datetime':X_test_df[timesteps:].as_matrix(), 'predict':y_pred[:,0]})
rest_filename=str(result_folder+'/'+wt_query['ld_code'])+'_'+wt_query['fault']+'_result_test_'+str(wt_query['unix_timestamp_ini'])+'_'+str(wt_query['unix_timestamp_end'])+'.csv'
pre_alarm_dates.to_csv(rest_filename, sep=',',index =False)
import matplotlib.pyplot as plt
from datetime import datetime
date_time = pd.to_datetime(X_test_df[timesteps:],format='%Y-%m-%d %H:%M:%S')
plt.plot(date_time,y_test, color = 'red', label = 'Real alarm')
plt.plot(date_time,y_pred, color = 'green', label = 'Prediction probability')
#plt.plot(predicted_stock_price, color = 'blue', label = 'Predicted Google Stock Price')
#plt.plot(date_time,y_pred_bin, color = 'blue', label = 'Prediction alarm')
plt.title('Alarm Prediction test '+str(Marging)+' Marging')
plt.xlabel('Time')
plt.ylabel('Alarm probability')
plt.legend()
plot_filename=str(result_folder+'/'+wt_query['ld_code'])+'_'+wt_query['fault']+'_prediction_test_'+str(wt_query['unix_timestamp_ini_test'])+'_'+str(wt_query['unix_timestamp_end_test'])+'.png'
fig = plt.gcf()
fig.set_size_inches(50, 30)
plt.savefig(plot_filename,dpi=100)
plt.close()
#plt.show()
#Predict train
y_pred = classifier2.predict(X_train)
y_pred_df = pd.DataFrame(y_pred)
y_pred_bin = (y_pred > 0.5)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_train, y_pred_bin)
from sklearn.metrics import cohen_kappa_score
kap = cohen_kappa_score(y_pred_bin,y_train)
accuracy='NA'
if(np.unique(y_train).size>1 and np.unique(y_pred_bin).size>1):
numerator=(cm[0,0]+cm[1,1])
denominator=sum(sum(cm))
if(denominator!=0 and (numerator!=denominator or denominator!=0)) :
accuracy=(cm[0,0]+cm[1,1])/sum(sum(cm))
print(accuracy)
print(kap)
#print(y_pred_df)
pre_alarm_dates=pd.DataFrame({'datetime':X_train_df[timesteps:].as_matrix(), 'predict':y_pred[:,0]})
rest_filename=str(result_folder+'/'+wt_query['ld_code'])+'_'+wt_query['fault']+'_result_train_'+str(wt_query['unix_timestamp_ini'])+'_'+str(wt_query['unix_timestamp_end'])+'.csv'
pre_alarm_dates.to_csv(rest_filename, sep=',',index =False)
import matplotlib.pyplot as plt
from datetime import datetime
date_time = pd.to_datetime(X_train_df[timesteps:],format='%Y-%m-%d %H:%M:%S')
plt.plot(date_time,y_train, color = 'red', label = 'Real alarm')
plt.plot(date_time,y_pred, color = 'green', label = 'Prediction probability')
#plt.plot(predicted_stock_price, color = 'blue', label = 'Predicted Google Stock Price')
#plt.plot(date_time,y_pred_bin, color = 'blue', label = 'Prediction alarm')
plt.title('Alarm Prediction train '+str(Marging)+' Marging')
plt.xlabel('Time')
plt.ylabel('Alarm probability')
plt.legend()
plot_filename=str(result_folder+'/'+wt_query['ld_code'])+'_'+wt_query['fault']+'_prediction_train_'+str(wt_query['unix_timestamp_ini'])+'_'+str(wt_query['unix_timestamp_end'])+'.png'
fig = plt.gcf()
fig.set_size_inches(50, 30)
plt.savefig(plot_filename,dpi=100)
plt.close()
#pre_alarm_dates.to_csv('results.csv', sep=',',index =False)
#print(pre_alarm_dates)
| [
"alecuba16@gmail.com"
] | alecuba16@gmail.com |
4974e9cbccec4d64b57eed4fb4a101e46dff0344 | 5ba747b414d7ff4412e0397d0ab94f21c4f3f4fe | /Localization.py | 5b97c6dce0c3a08be880aaf125207e160efbb782 | [] | no_license | shivansh2818-10/ROS | a3242c027fb42f81179c5f7131c36bab07c05344 | bdb8e720a19caae5ec08c7c395b8ab29a90479b8 | refs/heads/master | 2023-03-22T05:07:41.179560 | 2020-07-01T08:06:54 | 2020-07-01T08:06:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 955 | py | #!/usr/bin/env python
import rospy
import roslib
import tf
from geometry_msgs.msg import PoseArray
#Defining a class
class Marker_detect():
def __init__(self):
rospy.init_node('marker_detection',anonymous=False) # initializing a ros node with name marker_detection
self.whycon_marker = {} # Declaring dictionaries
rospy.Subscriber('/whycon/poses',PoseArray,self.whycon_data) # Subscribing to topic
# Callback for /whycon/poses
# Please fill in the function
def whycon_data(self,msg):
#Getting markers position with round-off upto 4 digits
roundoff=4
for count in range(len(msg.poses)):
self.whycon_marker[count]=[round(msg.poses[count].position.x,roundoff),round(msg.poses[count].position.y,roundoff),round(msg.poses[count].position.z,roundoff)]
# Printing the detected markers on terminal
print(self.whycon_marker)
if __name__=="__main__":
marker = Marker_detect()
while not rospy.is_shutdown():
rospy.spin() | [
"noreply@github.com"
] | noreply@github.com |
37fccb494d7a0de401f2e81b87225627a70c440e | 0ef468991fbb546c239f78b9712894f4e9981723 | /thread/lock.py | d729b0369a044b47d29809ff94e175d71b7e3c60 | [] | no_license | devil1949/test | 54b2a095e62e96d620a1b4cfade6141954dee510 | 28f140c3ddaf7d7e3fb50927b4d8d5b29e498337 | refs/heads/master | 2020-04-06T09:38:43.489034 | 2017-09-13T17:18:38 | 2017-09-13T17:18:38 | 26,108,515 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 357 | py | #!/usr/bin/env python3
# coding:utf-8
import threading
import time
num = 0
def run(n):
global num
time.sleep(0.1)
lock.acquire()
num += 1
lock.release()
print(num)
lock = threading.RLock()
#lock = threading.BoundedSemaphore(1)
for i in range(10):
threading.Thread(target=run, args=(i,)).start()
| [
"noreply@github.com"
] | noreply@github.com |
d973a98d468f699d88ed22bda3be21818e1727e8 | 4c44c593048fa4e00fb0334209632a286886efd9 | /import_template_supplierinfo/wizards/import_file.py | 6e86c4502afe621620950784d04bcf17a2bff77f | [] | 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 | 1,065 | py | ###############################################################################
# For copyright and license notices, see __manifest__.py file in root directory
###############################################################################
import base64
import io
import logging
from odoo import models
_log = logging.getLogger(__name__)
try:
import pandas as pd
except (ImportError, IOError) as err:
_log.debug(err)
class ImportFile(models.TransientModel):
_inherit = 'import.file'
def dataframe_get(self):
self.ensure_one()
if self.template_id.model_id.model == 'import.template.supplierinfo':
buf = io.BytesIO()
buf.write(base64.b64decode(self.file))
ext = self.file_filename.split('.')[-1:][0]
if ext in ['xlsx', 'xls']:
df = pd.read_excel(
buf, engine='xlrd', encoding='utf-8', na_values=['NULL'],
converters={'name': str})
return df.where((pd.notnull(df)), None)
return super().dataframe_get()
| [
"roberto@trey.es"
] | roberto@trey.es |
269093e40a4014ea89ecd80de5f371b123bd4fa7 | 8acffb8c4ddca5bfef910e58d3faa0e4de83fce8 | /ml-flask/Lib/site-packages/srsly/tests/cloudpickle/cloudpickle_file_test.py | 02c568f8652ef647b699a151dff037527a6e8836 | [
"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 | 129 | py | version https://git-lfs.github.com/spec/v1
oid sha256:a058ea411ee874062513e922cfd60cc7f362eda3000cc849fc6af9c828f1412b
size 3430
| [
"yamprakash130@gmail.com"
] | yamprakash130@gmail.com |
357c28d294966c59ebddbe20816d7baa5f0767e4 | 170db40693a8427a880caac66d51f1f2c168df76 | /MyQuestions/AvenierEncoding February 2020/Finals/Cakewalk/Solution.py | b88c708a3f91f38dda23b5d16d666f4e48b45960 | [] | no_license | Namratabhatt/Competitive-Codes | 8f283b628aae662a9eb980e997bee59797aa5b02 | 93f86936e52ebd2fd8b3502ebdcadc9ef0d23678 | refs/heads/master | 2021-03-23T15:29:13.019488 | 2020-03-05T15:36:02 | 2020-03-05T15:36:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,021 | py | # Given 3 lengths of a triangle, print if its a right angled triangle
from collections import defaultdict, deque
from itertools import permutations
from sys import stdin,stdout
from bisect import bisect_left, bisect_right
from copy import deepcopy
# from random import randint,randrange,choice
import heapq
int_input=lambda : int(stdin.readline())
string_input=lambda : stdin.readline()
multi_int_input =lambda : map(int, stdin.readline().split())
multi_input = lambda : stdin.readline().split()
list_input=lambda : list(map(int,stdin.readline().split()))
string_list_input=lambda: list(string_input())
import os,sys
stdin = open(os.path.join(sys.path[0],'input0.in'),'r')
sys.stdout = open(os.path.join(sys.path[0],'output0.in'),'w')
test = int_input()
for _ in range(test):
a,b,c = multi_int_input()
if a==0 or b == 0 or c == 0:
print("NO")
else:
if (a**2 + b**2 == c**2) or (a**2 +c**2 == b**2) or (b**2 + c**2 == a**2):
print("YES")
else:
print("NO") | [
"arnabchanda964@gmail.com"
] | arnabchanda964@gmail.com |
94c5818497052b6c30c7ed4d8bcc5fb03398fc99 | 221c885457f1817c6234acf4d73b6bf969af453b | /mySite/settings.py | 24b5e653a9bbf8b63b56fd546924b14edda53695 | [] | no_license | bellgab/my-first-blog | 9cf036ac1287f7446d89f394f70f3a19bbc49b3c | 1239d5707457fea7174249fddd77979623f75918 | refs/heads/master | 2020-03-17T14:02:51.855097 | 2018-05-16T11:25:08 | 2018-05-16T11:25:08 | 133,655,535 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,193 | py | """
Django settings for mySite project.
Generated by 'django-admin startproject' using Django 2.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/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/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gd+(jzesa7o*)+-id(x%3_e3nom7jtwztwoghf1o_g=g_9-w@u'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', '.pythonanywhere.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
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': [],
'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/2.0/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/2.0/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/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Budapest'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
| [
"bellgab@gmail.com"
] | bellgab@gmail.com |
00a5a8e33f0cc2bf74d33a24835b9f8394488bd4 | 8f96c3710cb439a6d72691b249129bc4e64b2310 | /rcfg/manage.py | d9622f020926ea2d2565f0758360da3259b06a81 | [
"MIT"
] | permissive | tony-mikhailov/Kalachakra | dd4eaf339f8ff67fe20c3af4a7a5f9a3be3e85d2 | 7a46be7e75bad0500914e5a7c44662c6740ebaa2 | refs/heads/master | 2023-05-12T10:55:04.698114 | 2020-04-26T14:11:52 | 2020-04-26T14:11:52 | 250,850,878 | 0 | 0 | MIT | 2021-06-10T18:45:32 | 2020-03-28T17:11:49 | JavaScript | UTF-8 | Python | false | false | 624 | py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rcfg.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| [
"anton@mikhailov.center"
] | anton@mikhailov.center |
efc31c1fe13aed5e645ccf3e6dcca2d9403c5c83 | c4ff1e384482fc80e85b0cf70725f1f54c159983 | /parse_case.py | c1fc03ee315ed7919b3e4adb5a0f8a7783aae385 | [] | no_license | wendyyuwm/socket | 2bb3bbb01ca108da8b30f82b1acb99b76b468774 | cea9e0671ac611ee1e804f504233f04cc6915cd4 | refs/heads/master | 2021-06-05T17:29:38.305053 | 2021-04-30T09:47:38 | 2021-04-30T09:47:38 | 63,161,749 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 597 | py | from testrail import *
import shlex
client = APIClient("http://10.0.18.130/testrail/")
client.user = 'stiger_he@ovt.com'
client.password = 'PfOf1KTtCAYDwRM9mh0q-utLfbuYwxVfa3s.lSJoM'
case = client.send_get('get_case/122')
# print(case)
# print(case['custom_preconds'])
# print(case['custom_steps_separated'])
cmdstr = case['custom_steps_separated'][0]['content'].split('\n')[0]
# print(case['custom_steps_separated'][0]['content'].split('\n'))
print(cmdstr)
# print(case['custom_steps_separated'][0]['expected'])
cmds = shlex.split(cmdstr)
print(cmds)
print(tuple(cmds[1:]))
| [
"noreply@github.com"
] | noreply@github.com |
88c524a2aa42d1c53e01946abb653c80c94e0e38 | 7a0acc1c2e808c7d363043546d9581d21a129693 | /selenium/src/py/lib/epydoc/docwriter/html.py | 352d45d89179d2f5cf75d6da437d6060d4ff70aa | [
"Apache-2.0"
] | permissive | epall/selenium | 39b9759f8719a168b021b28e500c64afc5f83582 | 273260522efb84116979da2a499f64510250249b | refs/heads/master | 2022-06-25T22:15:25.493076 | 2010-03-11T00:43:02 | 2010-03-11T00:43:02 | 552,908 | 3 | 0 | Apache-2.0 | 2022-06-10T22:44:36 | 2010-03-08T19:10:45 | C | UTF-8 | Python | false | false | 123,261 | py | #
# epydoc -- HTML output generator
# Edward Loper
#
# Created [01/30/01 05:18 PM]
# $Id: html.py 1210 2006-04-10 13:25:50Z edloper $
#
"""
The HTML output generator for epydoc. The main interface provided by
this module is the L{HTMLWriter} class.
"""
__docformat__ = 'epytext en'
import re, os, sys, codecs, sre_constants, pprint
import urllib
from epydoc.apidoc import *
import epydoc.docstringparser
import time, epydoc, epydoc.markup
from epydoc.docwriter.html_colorize import colorize_re
from epydoc.docwriter.html_colorize import PythonSourceColorizer
from epydoc.docwriter import html_colorize
from epydoc.docwriter.html_css import STYLESHEETS
from epydoc.docwriter.html_help import HTML_HELP
from epydoc.docwriter.dotgraph import *
from epydoc import log
from epydoc.util import plaintext_to_html, is_src_filename
from epydoc.compat import * # Backwards compatibility
######################################################################
## Template Compiler
######################################################################
# The compile_tempalte() method defined in this section is used to
# define several of HTMLWriter's methods.
def compile_template(docstring, template_string,
output_function='out', debug=epydoc.DEBUG):
"""
Given a template string containing inline python source code,
return a python function that will fill in the template, and
output the result. The signature for this function is taken from
the first line of C{docstring}. Output is generated by making
repeated calls to the output function with the given name (which
is typically one of the function's parameters).
The templating language used by this function passes through all
text as-is, with three exceptions:
- If every line in the template string is indented by at least
M{x} spaces, then the first M{x} spaces are stripped from each
line.
- Any line that begins with '>>>' (with no indentation)
should contain python code, and will be inserted as-is into
the template-filling function. If the line begins a control
block (such as 'if' or 'for'), then the control block will
be closed by the first '>>>'-marked line whose indentation is
less than or equal to the line's own indentation (including
lines that only contain comments.)
- In any other line, any expression between two '$' signs will
be evaluated and inserted into the line (using C{str()} to
convert the result to a string).
Here is a simple example:
>>> TEMPLATE = '''
... <book>
... <title>$book.title$</title>
... <pages>$book.count_pages()$</pages>
... >>> for chapter in book.chapters:
... <chaptername>$chapter.name$</chaptername>
... >>> #endfor
... </book>
>>> write_book = compile_template('write_book(out, book)', TEMPLATE)
@newfield acknowledgements: Acknowledgements
@acknowledgements: The syntax used by C{compile_template} is
loosely based on Cheetah.
"""
# Extract signature from the docstring:
signature = docstring.lstrip().split('\n',1)[0].strip()
func_name = signature.split('(',1)[0].strip()
# Regexp to search for inline substitutions:
INLINE = re.compile(r'\$([^\$]+)\$')
# Regexp to search for python statements in the template:
COMMAND = re.compile(r'(^>>>.*)\n?', re.MULTILINE)
# Strip indentation from the template.
template_string = strip_indent(template_string)
# If we're debugging, then we'll store the generated function,
# so we can print it along with any tracebacks that depend on it.
if debug:
signature = re.sub(r'\)\s*$', ', __debug=__debug)', signature)
# Funciton declaration line
pysrc_lines = ['def %s:' % signature]
indents = [-1]
if debug:
pysrc_lines.append(' try:')
indents.append(-1)
commands = COMMAND.split(template_string.strip()+'\n')
for i, command in enumerate(commands):
if command == '': continue
# String literal segment:
if i%2 == 0:
pieces = INLINE.split(command)
for j, piece in enumerate(pieces):
if j%2 == 0:
# String piece
pysrc_lines.append(' '*len(indents)+
'%s(%r)' % (output_function, piece))
else:
# Variable piece
pysrc_lines.append(' '*len(indents)+
'%s(unicode(%s))' % (output_function, piece))
# Python command:
else:
srcline = command[3:].lstrip()
# Update indentation
indent = len(command)-len(srcline)
while indent <= indents[-1]: indents.pop()
# Add on the line.
srcline = srcline.rstrip()
pysrc_lines.append(' '*len(indents)+srcline)
if srcline.endswith(':'):
indents.append(indent)
if debug:
pysrc_lines.append(' except Exception,e:')
pysrc_lines.append(' pysrc, func_name = __debug ')
pysrc_lines.append(' lineno = sys.exc_info()[2].tb_lineno')
pysrc_lines.append(' print ("Exception in template %s() on "')
pysrc_lines.append(' "line %d:" % (func_name, lineno))')
pysrc_lines.append(' print pysrc[lineno-1]')
pysrc_lines.append(' raise')
pysrc = '\n'.join(pysrc_lines)+'\n'
if debug: localdict = {'__debug': (pysrc_lines, func_name)}
else: localdict = {}
try: exec pysrc in globals(), localdict
except SyntaxError:
log.error('Error in script:\n' + pysrc + '\n')
raise
template_func = localdict[func_name]
template_func.__doc__ = docstring
return template_func
def strip_indent(s):
"""
Given a multiline string C{s}, find the minimum indentation for
all non-blank lines, and return a new string formed by stripping
that amount of indentation from all lines in C{s}.
"""
# Strip indentation from the template.
minindent = sys.maxint
lines = s.split('\n')
for line in lines:
stripline = line.lstrip()
if stripline:
minindent = min(minindent, len(line)-len(stripline))
return '\n'.join([l[minindent:] for l in lines])
######################################################################
## HTML Writer
######################################################################
class HTMLWriter:
#////////////////////////////////////////////////////////////
# Table of Contents
#////////////////////////////////////////////////////////////
#
# 1. Interface Methods
#
# 2. Page Generation -- write complete web page files
# 2.1. Module Pages
# 2.2. Class Pages
# 2.3. Trees Page
# 2.4. Indices Page
# 2.5. Help Page
# 2.6. Frames-based table of contents pages
# 2.7. Homepage (index.html)
# 2.8. CSS Stylesheet
# 2.9. Javascript file
#
# 3. Page Element Generation -- write pieces of a web page file
# 3.1. Page Header
# 3.2. Page Footer
# 3.3. Navigation Bar
# 3.4. Breadcrumbs
# 3.5. Summary Tables
#
# 4. Helper functions
def __init__(self, docindex, **kwargs):
"""
Construct a new HTML writer, using the given documentation
index.
@param docmap: The documentation index.
@type prj_name: C{string}
@keyword prj_name: The name of the project. Defaults to
none.
@type prj_url: C{string}
@keyword prj_url: The target for the project hopeage link on
the navigation bar. If C{prj_url} is not specified,
then no hyperlink is created.
@type prj_link: C{string}
@keyword prj_link: The label for the project link on the
navigation bar. This link can contain arbitrary HTML
code (e.g. images). By default, a label is constructed
from C{prj_name}.
@type top_page: C{string}
@keyword top_page: The top page for the documentation. This
is the default page shown main frame, when frames are
enabled. C{top} can be a URL, the name of a
module, the name of a class, or one of the special
strings C{"trees.html"}, C{"indices.html"}, or
C{"help.html"}. By default, the top-level package or
module is used, if there is one; otherwise, C{"trees"}
is used.
@type css: C{string}
@keyword css: The CSS stylesheet file. If C{css} is a file
name, then the specified file's conents will be used.
Otherwise, if C{css} is the name of a CSS stylesheet in
L{epydoc.docwriter.html_css}, then that stylesheet will
be used. Otherwise, an error is reported. If no stylesheet
is specified, then the default stylesheet is used.
@type help_file: C{string}
@keyword help_file: The name of the help file. If no help file is
specified, then the default help file will be used.
@type show_private: C{boolean}
@keyword show_private: Whether to create documentation for
private objects. By default, private objects are documented.
@type show_frames: C{boolean})
@keyword show_frames: Whether to create a frames-based table of
contents. By default, it is produced.
@type show_imports: C{boolean}
@keyword show_imports: Whether or not to display lists of
imported functions and classes. By default, they are
not shown.
@type variable_maxlines: C{int}
@keyword variable_maxlines: The maximum number of lines that
should be displayed for the value of a variable in the
variable details section. By default, 8 lines are
displayed.
@type variable_linelength: C{int}
@keyword variable_linelength: The maximum line length used for
displaying the values of variables in the variable
details sections. If a line is longer than this length,
then it will be wrapped to the next line. The default
line length is 70 characters.
@type variable_summary_linelength: C{int}
@keyword variable_summary_linelength: The maximum line length
used for displaying the values of variables in the summary
section. If a line is longer than this length, then it
will be truncated. The default is 40 characters.
@type variable_tooltip_linelength: C{int}
@keyword variable_tooltip_linelength: The maximum line length
used for tooltips for the values of variables. If a
line is longer than this length, then it will be
truncated. The default is 600 characters.
@type property_function_linelength: C{int}
@keyword property_function_linelength: The maximum line length
used to dispaly property functions (C{fget}, C{fset}, and
C{fdel}) that contain something other than a function
object. The default length is 40 characters.
@type inheritance: C{string}
@keyword inheritance: How inherited objects should be displayed.
If C{inheritance='grouped'}, then inherited objects are
gathered into groups; if C{inheritance='listed'}, then
inherited objects are listed in a short list at the
end of their group; if C{inheritance='included'}, then
inherited objects are mixed in with non-inherited
objects. The default is 'grouped'.
@type include_sourcecode: C{boolean}
@param include_sourcecode: If true, then generate colorized
source code files for each python module.
"""
self.docindex = docindex
# Process keyword arguments.
self._show_private = kwargs.get('show_private', 1)
"""Should private docs be included?"""
self._prj_name = kwargs.get('prj_name', None)
"""The project's name (for the project link in the navbar)"""
self._prj_url = kwargs.get('prj_url', None)
"""URL for the project link in the navbar"""
self._prj_link = kwargs.get('prj_link', None)
"""HTML code for the project link in the navbar"""
self._top_page = kwargs.get('top_page', None)
"""The 'main' page"""
self._css = kwargs.get('css')
"""CSS stylesheet to use"""
self._helpfile = kwargs.get('help_file', None)
"""Filename of file to extract help contents from"""
self._frames_index = kwargs.get('show_frames', 1)
"""Should a frames index be created?"""
self._show_imports = kwargs.get('show_imports', False)
"""Should imports be listed?"""
self._propfunc_linelen = kwargs.get('property_function_linelength', 40)
"""[XXX] Not used!"""
self._variable_maxlines = kwargs.get('variable_maxlines', 8)
"""Max lines for variable values"""
self._variable_linelen = kwargs.get('variable_linelength', 70)
"""Max line length for variable values"""
self._variable_summary_linelen = \
kwargs.get('variable_summary_linelength', 55)
"""Max length for variable value summaries"""
self._variable_tooltip_linelen = \
kwargs.get('variable_tooltip_linelength', 600)
"""Max length for variable tooltips"""
self._inheritance = kwargs.get('inheritance', 'listed')
"""How should inheritance be displayed? 'listed', 'included',
or 'grouped'"""
self._incl_sourcecode = kwargs.get('include_source_code', True)
"""Should pages be generated for source code of modules?"""
self._mark_docstrings = kwargs.get('mark_docstrings', False)
"""Wrap <span class='docstring'>...</span> around docstrings?"""
self._graph_types = kwargs.get('graphs', ()) or ()
"""Graphs that we should include in our output."""
# For use with select_variables():
if self._show_private:
self._public_filter = None
else:
self._public_filter = True
# Make sure inheritance has a sane value.
if self._inheritance not in ('listed', 'included', 'grouped'):
raise ValueError, 'Bad value for inheritance'
# Create the project homepage link, if it was not specified.
if (self._prj_name or self._prj_url) and not self._prj_link:
self._prj_link = plaintext_to_html(self._prj_name or
'Project Homepage')
# Add a hyperlink to _prj_url, if _prj_link doesn't already
# contain any hyperlinks.
if (self._prj_link and self._prj_url and
not re.search(r'<a[^>]*\shref', self._prj_link)):
self._prj_link = ('<a class="navbar" target="_top" href="'+
self._prj_url+'">'+self._prj_link+'</a>')
# Precompute lists & sets of APIDoc objects that we're
# interested in.
self.valdocs = valdocs = sorted(docindex.reachable_valdocs(
imports=False, packages=False, bases=False, submodules=False,
subclasses=False, private=self._show_private))
self.module_list = [d for d in valdocs if isinstance(d, ModuleDoc)]
"""The list of L{ModuleDoc}s for the documented modules."""
self.module_set = set(self.module_list)
"""The set of L{ModuleDoc}s for the documented modules."""
self.class_list = [d for d in valdocs if isinstance(d, ClassDoc)]
"""The list of L{ClassDoc}s for the documented classes."""
self.class_set = set(self.class_list)
"""The set of L{ClassDoc}s for the documented classes."""
self.routine_list = [d for d in valdocs if isinstance(d, RoutineDoc)]
"""The list of L{RoutineDoc}s for the documented routines."""
self.indexed_docs = []
"""The list of L{APIDoc}s for variables and values that should
be included in the index."""
# Construct the value for self.indexed_docs.
self.indexed_docs += [d for d in valdocs
if not isinstance(d, GenericValueDoc)]
for doc in valdocs:
if isinstance(doc, NamespaceDoc):
self.indexed_docs += [doc for doc in doc.variables.values() if
isinstance(doc.value, GenericValueDoc)]
self.indexed_docs.sort()
# Figure out the url for the top page.
self._top_page_url = self._find_top_page(self._top_page)
# Figure out how many output files there will be (for progress
# reporting).
self.modules_with_sourcecode = set()
for doc in self.module_list:
if isinstance(doc, ModuleDoc) and is_src_filename(doc.filename):
self.modules_with_sourcecode.add(doc)
self._num_files = len(self.class_list) + 2*len(self.module_list) + 9
if self._incl_sourcecode:
self._num_files += len(self.modules_with_sourcecode)
def _find_top_page(self, pagename):
"""
Find the top page for the API documentation. This page is
used as the default page shown in the main frame, when frames
are used. When frames are not used, this page is copied to
C{index.html}.
@param pagename: The name of the page, as specified by the
keyword argument C{top} to the constructor.
@type pagename: C{string}
@return: The URL of the top page.
@rtype: C{string}
"""
# If a page name was specified, then we need to figure out
# what it points to.
if pagename:
# If it's a URL, then use it directly.
if pagename.lower().startswith('http:'):
return pagename
# If it's an object, then use that object's page.
try:
doc = self.docindex.get_valdoc(pagename)
return self.url(doc)
except:
pass
# Otherwise, give up.
log.warning('Could not find top page %r; using trees.html '
'instead' % pagename)
# If no page name was specified, then try to choose one
# automatically.
else:
root = [val_doc for val_doc in self.docindex.root
if isinstance(val_doc, (ClassDoc, ModuleDoc))]
if len(root) == 0:
# No docs?? Try the trees page.
return 'trees.html'
elif len(root) == 1:
# One item in the root; use that.
return self.url(root[0])
else:
# Multiple root items; if they're all in one package,
# then use that. Otherwise, use trees.html
root = sorted(root, key=lambda v:len(v.canonical_name))
top = root[0]
for doc in root[1:]:
if not top.canonical_name.dominates(doc.canonical_name):
return 'trees.html'
else:
return self.url(top)
#////////////////////////////////////////////////////////////
#{ 1. Interface Methods
#////////////////////////////////////////////////////////////
def write(self, directory=None):
"""
Write the documentation to the given directory.
@type directory: C{string}
@param directory: The directory to which output should be
written. If no directory is specified, output will be
written to the current directory. If the directory does
not exist, it will be created.
@rtype: C{None}
@raise OSError: If C{directory} cannot be created.
@raise OSError: If any file cannot be created or written to.
"""
# For progress reporting:
self._files_written = 0.
# Keep track of failed xrefs, and report them at the end.
self._failed_xrefs = {}
# Create destination directories, if necessary
if not directory: directory = os.curdir
self._mkdir(directory)
self._directory = directory
# Write the CSS file.
self._files_written += 1
log.progress(self._files_written/self._num_files, 'epydoc.css')
self.write_css(directory, self._css)
# Write the Javascript file.
self._files_written += 1
log.progress(self._files_written/self._num_files, 'epydoc.js')
self.write_javascript(directory)
# Write the term & identifier indices
self._write(self.write_indices, directory, 'indices.html')
# Write the trees file (package & class hierarchies)
self._write(self.write_trees, directory, 'trees.html')
# Write the help file.
self._write(self.write_help, directory,'help.html')
# Write the frames-based table of contents.
self._write(self.write_frames_index, directory, 'frames.html')
self._write(self.write_toc, directory, 'toc.html')
self._write(self.write_project_toc, directory, 'toc-everything.html')
for doc in self.module_list:
filename = 'toc-%s' % urllib.unquote(self.url(doc))
self._write(self.write_module_toc, directory, filename, doc)
# Write the object documentation.
for doc in self.module_list:
filename = urllib.unquote(self.url(doc))
self._write(self.write_module, directory, filename, doc)
for doc in self.class_list:
filename = urllib.unquote(self.url(doc))
self._write(self.write_class, directory, filename, doc)
# Write source code files.
if self._incl_sourcecode:
for doc in self.modules_with_sourcecode:
filename = urllib.unquote(self.pysrc_url(doc))
self._write(self.write_sourcecode, directory, filename, doc)
# Write the index.html files.
# (this must be done last, since it might copy another file)
self._files_written += 1
log.progress(self._files_written/self._num_files, 'index.html')
self.write_homepage(directory)
# Report any failed crossreferences
if self._failed_xrefs:
estr = 'Failed identifier crossreference targets:\n'
failed_identifiers = self._failed_xrefs.keys()
failed_identifiers.sort()
for identifier in failed_identifiers:
names = self._failed_xrefs[identifier].keys()
names.sort()
estr += '- %s' % identifier
estr += '\n'
for name in names:
estr += ' (from %s)\n' % name
log.docstring_warning(estr)
def _write(self, write_func, directory, filename, *args):
# Display our progress.
self._files_written += 1
log.progress(self._files_written/self._num_files, filename)
path = os.path.join(directory, filename)
f = codecs.open(path, 'w', 'ascii', errors='xmlcharrefreplace')
write_func(f.write, *args)
f.close()
def _mkdir(self, directory):
"""
If the given directory does not exist, then attempt to create it.
@rtype: C{None}
"""
if not os.path.isdir(directory):
if os.path.exists(directory):
raise OSError('%r is not a directory' % directory)
os.mkdir(directory)
#////////////////////////////////////////////////////////////
#{ 2.1. Module Pages
#////////////////////////////////////////////////////////////
def write_module(self, out, doc):
"""
Write an HTML page containing the API documentation for the
given module to C{out}.
@param doc: A L{ModuleDoc} containing the API documentation
for the module that should be described.
"""
longname = doc.canonical_name
shortname = doc.canonical_name[-1]
# Write the page header (incl. navigation bar & breadcrumbs)
self.write_header(out, str(longname))
self.write_navbar(out, doc)
self.write_breadcrumbs(out, doc, self.url(doc))
# Write the name of the module we're describing.
if doc.is_package is True: typ = 'Package'
else: typ = 'Module'
if longname[0].startswith('script-'):
shortname = str(longname)[7:]
typ = 'Script'
out('<!-- ==================== %s ' % typ.upper() +
'DESCRIPTION ==================== -->\n')
out('<h2 class="%s">%s %s' % (typ.lower(), typ, shortname))
src_link = self.pysrc_link(doc)
if src_link: out('\n<br/>' + src_link)
out('</h2>\n')
# If the module has a description, then list it.
if doc.descr not in (None, UNKNOWN):
out(self.descr(doc, 2)+'<br /><br />\n\n')
# Write any standarad metadata (todo, author, etc.)
if doc.metadata is not UNKNOWN and doc.metadata:
out('<hr />\n')
self.write_standard_fields(out, doc)
# If it's a package, then list the modules it contains.
if doc.is_package is True:
self.write_module_list(out, doc)
# Write summary tables describing the variables that the
# module defines.
self.write_summary_table(out, "Classes", doc, "class")
self.write_summary_table(out, "Functions", doc, "function")
self.write_summary_table(out, "Variables", doc, "other")
# Write a list of all imported objects.
if self._show_imports:
self.write_imports(out, doc)
# Write detailed descriptions of functions & variables defined
# in this module.
self.write_details_list(out, "Function Details", doc, "function")
self.write_details_list(out, "Variables Details", doc, "other")
# Write the page footer (including navigation bar)
self.write_navbar(out, doc)
self.write_footer(out)
#////////////////////////////////////////////////////////////
#{ 2.??. Source Code Pages
#////////////////////////////////////////////////////////////
def write_sourcecode(self, out, doc):
filename = doc.filename
name = str(doc.canonical_name)
# Header
self.write_header(out, name)
self.write_navbar(out, doc)
self.write_breadcrumbs(out, doc, self.pysrc_url(doc))
# Source code listing
out('<h2 class="py-src">Source Code for %s</h2>\n' %
self.href(doc, label='%s %s' % (self.doc_kind(doc), name)))
out('<div class="py-src">\n')
out('<pre class="py-src">\n')
out(PythonSourceColorizer(filename, name, self.docindex,
self.indexed_docs, self.url).colorize())
out('</pre>\n</div>\n<br />\n')
# Footer
self.write_navbar(out, doc)
self.write_footer(out)
#////////////////////////////////////////////////////////////
#{ 2.2. Class Pages
#////////////////////////////////////////////////////////////
def write_class(self, out, doc):
"""
Write an HTML page containing the API documentation for the
given class to C{out}.
@param doc: A L{ClassDoc} containing the API documentation
for the class that should be described.
"""
longname = doc.canonical_name
shortname = doc.canonical_name[-1]
# Write the page header (incl. navigation bar & breadcrumbs)
self.write_header(out, str(longname))
self.write_navbar(out, doc)
self.write_breadcrumbs(out, doc, self.url(doc))
# Write the name of the class we're describing.
if doc.is_type(): typ = 'Type'
elif doc.is_exception(): typ = 'Exception'
else: typ = 'Class'
out('<!-- ==================== %s ' % typ.upper() +
'DESCRIPTION ==================== -->\n')
out('<h2 class="%s">%s %s' %
(typ.lower(), typ, shortname))
src_link = self.pysrc_link(doc)
if src_link: out('\n<br/>' + src_link)
out('</h2>\n')
if ((doc.bases not in (UNKNOWN, None) and len(doc.bases) > 0) or
(doc.subclasses not in (UNKNOWN,None) and len(doc.subclasses)>0)):
# Display bases graphically, if requested.
if 'umlclasstree' in self._graph_types:
linker = _HTMLDocstringLinker(self, doc)
graph = uml_class_tree_graph(doc, linker, doc)
out('<center>\n%s</center>\n' % self.render_graph(graph))
elif 'classtree' in self._graph_types:
linker = _HTMLDocstringLinker(self, doc)
graph = class_tree_graph([doc], linker, doc)
out('<center>\n%s</center>\n' % self.render_graph(graph))
# Otherwise, use ascii-art.
else:
# Write the base class tree.
if doc.bases not in (UNKNOWN, None) and len(doc.bases) > 0:
out('<pre class="base-tree">\n%s</pre>\n\n' %
self.base_tree(doc))
# Write the known subclasses
if (doc.subclasses not in (UNKNOWN, None) and
len(doc.subclasses) > 0):
out('<dl><dt>Known Subclasses:</dt>\n<dd>\n ')
out(',\n '.join([self.href(c, context=doc)
for c in doc.subclasses]))
out('\n</dd></dl>\n\n')
out('<hr />\n')
# If the class has a description, then list it.
if doc.descr not in (None, UNKNOWN):
out(self.descr(doc, 2)+'<br /><br />\n\n')
# Write any standarad metadata (todo, author, etc.)
if doc.metadata is not UNKNOWN and doc.metadata:
out('<hr />\n')
self.write_standard_fields(out, doc)
# Write summary tables describing the variables that the
# class defines.
self.write_summary_table(out, "Nested Classes", doc, "class")
self.write_summary_table(out, "Instance Methods", doc,
"instancemethod")
self.write_summary_table(out, "Class Methods", doc, "classmethod")
self.write_summary_table(out, "Static Methods", doc, "staticmethod")
self.write_summary_table(out, "Class Variables", doc,
"classvariable")
self.write_summary_table(out, "Instance Variables", doc,
"instancevariable")
self.write_summary_table(out, "Properties", doc, "property")
# Write a list of all imported objects.
if self._show_imports:
self.write_imports(out, doc)
# Write detailed descriptions of functions & variables defined
# in this class.
# [xx] why group methods into one section but split vars into two?
# seems like we should either group in both cases or split in both
# cases.
self.write_details_list(out, "Method Details", doc, "method")
self.write_details_list(out, "Class Variable Details", doc,
"classvariable")
self.write_details_list(out, "Instance Variable Details", doc,
"instancevariable")
self.write_details_list(out, "Property Details", doc, "property")
# Write the page footer (including navigation bar)
self.write_navbar(out, doc)
self.write_footer(out)
#////////////////////////////////////////////////////////////
#{ 2.3. Trees page
#////////////////////////////////////////////////////////////
def write_trees(self, out):
"""
Write an HTML page containing the module and class hierarchies
to the given streams.
@param public: The output stream for the public version of the page.
@param private: The output stream for the private version of the page.
"""
# Header material.
self.write_header(out, 'Trees')
self.write_navbar(out, 'trees')
self.write_breadcrumbs(out, 'trees', 'trees.html')
# Write the module hierarchy
out('<!-- ==================== '
'MODULE HIERARCHY ==================== -->\n')
out('<h2>Module Hierarchy</h2>\n')
self.write_module_tree(out)
# Does the project define any classes?
defines_classes = len(self.class_list) > 0
# Write the class hierarchy
if defines_classes:
out('<!-- ==================== '
'CLASS HIERARCHY ==================== -->\n')
out('<h2>Class Hierarchy</h2>\n')
self.write_class_tree(out)
# Footer material.
self.write_navbar(out, 'trees')
self.write_footer(out)
#////////////////////////////////////////////////////////////
#{ 2.4. Indices page
#////////////////////////////////////////////////////////////
def write_indices(self, out):
"""
Write an HTML page containing the term and identifier indices
to the given streams.
@bug: If there are private indexed terms, but no public
indexed terms, then this function will still write a
header for the Term Index to the public stream.
@param public: The output stream for the public version of the page.
@param private: The output stream for the private version of the page.
"""
# Header material.
self.write_header(out, 'Index')
self.write_navbar(out, 'indices')
self.write_breadcrumbs(out, 'indices', 'indices.html')
out('<br />\n')
terms = self._extract_term_index()
if terms:
self.write_term_index(out, terms)
# [xx] this will only find variables if they have values.
# (e.g., it won't list any instance variables.)
identifiers = []
for doc in self.indexed_docs:
name = doc.canonical_name
if self.url(doc) is None: continue
key = name[-1].lower()
key = (key[:1] in 'abcdefghijklmnopqrstuvwxyz', key)
identifiers.append( (key, name, doc) )
identifiers.sort()
if identifiers:
self.write_identifier_index(out, identifiers)
# Footer material.
self.write_navbar(out, 'indices')
self.write_footer(out)
write_identifier_index_header = compile_template(
"""
write_identifier_index_header(self, out)
""",
# /------------------------- Template -------------------------\
'''
<!-- ==================== IDENTIFIER INDEX ==================== -->
<table class="index" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="index"><th colspan="2">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr><th class="index">Identifier Index</th>
<td width="100%" align="right"> [
<a href="#_">_</a>
>>> for c in "abcdefghijklmnopqrstuvwxyz":
<a href="#$c$">$c$</a>
>>> #endfor
] </td>
</tr></table>
</th></tr>
''')
# \------------------------------------------------------------/
write_identifier_index = compile_template(
"""
write_identifier_index(self, out, index)
""",
# /------------------------- Template -------------------------\
'''
>>> #self.write_table_header(out, "index", "Identifier Index")
>>> self.write_identifier_index_header(out)
>>> letters = "abcdefghijklmnopqrstuvwxyz"
<a name="_"></a>
>>> for sortkey, name, doc in index:
>>> if self._doc_or_ancestor_is_private(doc):
>>> if not self._show_private: continue
<tr class="private"><td width="15%">
>>> else:
<tr><td width="15%">
>>> #endif
>>> while letters and letters[0] <= name[-1][:1].lower():
<a name="$letters[0]$"></a>
>>> letters = letters[1:]
>>> #endif
$self.href(doc, name[-1])$
</td>
<td>$self.doc_kind(doc)$
>>> container_name = name.container()
>>> if container_name is not None:
>>> container = self.docindex.get_valdoc(container_name)
>>> if container is not None:
in $self.doc_kind(container)$ $self.href(container)$
>>> #endif
>>> #endif
</td>
</tr>
>>> #endfor
</table>
>>> for letter in letters:
<a name="$letter$"></a>
>>> #endfor
<br />
''')
# \------------------------------------------------------------/
write_term_index = compile_template(
"""
write_term_index(self, out, index)
""",
# /------------------------- Template -------------------------\
'''
>>> if not index: return
>>> self.write_table_header(out, "index", "Term Index")
>>> for (key, term, links) in index:
<tr><td width="15%">$term.to_plaintext(None)$</td>
<td>
>>> for link in links[:-1]:
<em>$self.href(link)$</em>,
>>> #endfor
<em>$self.href(links[-1])$</em>
</td>
</tr>
>>> #endfor
</table>
<br />
''')
# \------------------------------------------------------------/
#////////////////////////////////////////////////////////////
#{ 2.5. Help Page
#////////////////////////////////////////////////////////////
def write_help(self, out):
"""
Write an HTML help file to the given stream. If
C{self._helpfile} contains a help file, then use it;
otherwise, use the default helpfile from
L{epydoc.docwriter.html_help}.
@param public: The output stream for the public version of the page.
@param private: The output stream for the private version of the page.
"""
# todo: optionally parse .rst etc help files?
# Get the contents of the help file.
if self._helpfile:
if os.path.exists(self._helpfile):
try: help = open(self._helpfile).read()
except: raise IOError("Can't open help file: %r" %
self._helpfile)
else:
raise IOError("Can't find help file: %r" % self._helpfile)
else:
if self._prj_name: thisprj = self._prj_name
else: thisprj = 'this project'
help = HTML_HELP % {'this_project':thisprj}
# Insert the help contents into a webpage.
self.write_header(out, 'Help')
self.write_navbar(out, 'help')
self.write_breadcrumbs(out, 'help', 'help.html')
out(help)
self.write_navbar(out, 'help')
self.write_footer(out)
#////////////////////////////////////////////////////////////
#{ 2.6. Frames-based Table of Contents
#////////////////////////////////////////////////////////////
write_frames_index = compile_template(
"""
write_frames_index(self, out)
Write the frames index file for the frames-based table of
contents to the given streams.
""",
# /------------------------- Template -------------------------\
'''
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> $self._prj_name or "API Documentation"$ </title>
</head>
<frameset cols="20%,80%">
<frameset rows="30%,70%">
<frame src="toc.html" name="moduleListFrame"
id="moduleListFrame" />
<frame src="toc-everything.html" name="moduleFrame"
id="moduleFrame" />
</frameset>
<frame src="$self._top_page_url$" name="mainFrame" id="mainFrame" />
</frameset>
</html>
''')
# \------------------------------------------------------------/
write_toc = compile_template(
"""
write_toc(self, out)
""",
# /------------------------- Template -------------------------\
'''
>>> self.write_header(out, "Table of Contents")
<h1 class="tocheading">Table of Contents</h1>
<hr />
<p class="toc">
<a target="moduleFrame" href="toc-everything.html">Everything</a>
</p>
>>> self.write_toc_section(out, "Modules", self.module_list)
<hr />
>>> if self._show_private:
$self.PRIVATE_LINK$
>>> #endif
>>> self.write_footer(out, short=True)
''')
# \------------------------------------------------------------/
def write_toc_section(self, out, name, docs, fullname=True):
if not docs: return
# Assign names to each item, and sort by name.
if fullname:
docs = [(str(d.canonical_name), d) for d in docs]
else:
docs = [(str(d.canonical_name[-1]), d) for d in docs]
docs.sort()
out(' <h2 class="tocheading">%s</h2>\n' % name)
for label, doc in docs:
doc_url = self.url(doc)
toc_url = 'toc-%s' % doc_url
is_private = self._doc_or_ancestor_is_private(doc)
if is_private:
if not self._show_private: continue
out(' <div class="private">\n')
out(' <p class="toc">\n')
if isinstance(doc, ModuleDoc):
out(' <a target="moduleFrame" href="%s"\n'
' onclick="setFrame(\'%s\',\'%s\');"'
' >%s</a></p>' % (toc_url, toc_url, doc_url, label))
else:
out(' <a target="mainFrame" href="%s"\n'
' >%s</a></p>' % (doc_url, label))
if is_private:
out(' </div>\n')
def write_project_toc(self, out):
self.write_header(out, "Everything")
out('<h1 class="tocheading">Everything</h1>\n')
out('<hr />\n')
# List the classes.
self.write_toc_section(out, "All Classes", self.class_list)
# List the functions.
funcs = [d for d in self.routine_list
if not isinstance(self.docindex.container(d),
(ClassDoc, types.NoneType))]
self.write_toc_section(out, "All Functions", funcs)
# List the variables.
vars = []
for doc in self.module_list:
vars += doc.select_variables(value_type='other',
imported=False,
public=self._public_filter)
self.write_toc_section(out, "All Variables", vars)
# Footer material.
out('<hr />\n')
if self._show_private:
out(self.PRIVATE_LINK+'\n')
self.write_footer(out, short=True)
def write_module_toc(self, out, doc):
"""
Write an HTML page containing the table of contents page for
the given module to the given streams. This page lists the
modules, classes, exceptions, functions, and variables defined
by the module.
@param public: The output stream for the public version of the page.
@param private: The output stream for the private version of the page.
"""
name = doc.canonical_name[-1]
self.write_header(out, name)
out('<h1 class="tocheading">Module %s</h1>\n' % name)
out('<hr />\n')
# List the classes.
classes = doc.select_variables(value_type='class', imported=False,
public=self._public_filter)
self.write_toc_section(out, "Classes", classes, fullname=False)
# List the functions.
funcs = doc.select_variables(value_type='function', imported=False,
public=self._public_filter)
self.write_toc_section(out, "Functions", funcs, fullname=False)
# List the variables.
variables = doc.select_variables(value_type='other', imported=False,
public=self._public_filter)
self.write_toc_section(out, "Variables", variables, fullname=False)
# Footer material.
out('<hr />\n')
if self._show_private:
out(self.PRIVATE_LINK+'\n')
self.write_footer(out, short=True)
#////////////////////////////////////////////////////////////
#{ 2.7. Project homepage (index.html)
#////////////////////////////////////////////////////////////
def write_homepage(self, directory):
"""
Write an C{index.html} file in the given directory. The
contents of this file are copied or linked from an existing
page, so this method must be called after all pages have been
written. The page used is determined by L{_frames_index} and
L{_top_page}:
- If L{_frames_index} is true, then C{frames.html} is
copied.
- Otherwise, the page specified by L{_top_page} is
copied.
"""
filename = os.path.join(directory, 'index.html')
if self._frames_index: top = 'frames.html'
else: top = self._top_page_url
# Copy the non-frames index file from top, if it's internal.
if top[:5] != 'http:' and '/' not in top:
try:
# Read top into `s`.
topfile = os.path.join(directory, top)
s = open(topfile, 'r').read()
# Write the output file.
open(filename, 'w').write(s)
return
except:
log.error('Warning: error copying index; '
'using a redirect page')
# Use a redirect if top is external, or if we faild to copy.
name = self._prj_name or 'this project'
f = open(filename, 'w')
self.write_redirect_index(f.write, top, name)
f.close()
write_redirect_index = compile_template(
"""
write_redirect_index(self, out, top, name)
""",
# /------------------------- Template -------------------------\
'''
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Redirect </title>
<meta http-equiv="refresh" content="1;url=$top$" />
<link rel="stylesheet" href="epydoc.css" type="text/css"></link>
</head>
<body>
<p>Redirecting to the API documentation for
<a href="$top$">$self._prj_name or "this project"$</a>...</p>
</body>
</html>
''')
# \------------------------------------------------------------/
#////////////////////////////////////////////////////////////
#{ 2.8. Stylesheet (epydoc.css)
#////////////////////////////////////////////////////////////
def write_css(self, directory, cssname):
"""
Write the CSS stylesheet in the given directory. If
C{cssname} contains a stylesheet file or name (from
L{epydoc.docwriter.html_css}), then use that stylesheet;
otherwise, use the default stylesheet.
@rtype: C{None}
"""
filename = os.path.join(directory, 'epydoc.css')
# Get the contents for the stylesheet file.
if cssname is None:
css = STYLESHEETS['default'][0]
else:
if os.path.exists(cssname):
try: css = open(cssname).read()
except: raise IOError("Can't open CSS file: %r" % cssname)
elif STYLESHEETS.has_key(cssname):
css = STYLESHEETS[cssname][0]
else:
raise IOError("Can't find CSS file: %r" % cssname)
# Write the stylesheet.
cssfile = open(filename, 'w')
cssfile.write(css)
cssfile.close()
#////////////////////////////////////////////////////////////
#{ 2.9. Javascript (epydoc.js)
#////////////////////////////////////////////////////////////
def write_javascript(self, directory):
jsfile = open(os.path.join(directory, 'epydoc.js'), 'w')
print >> jsfile, self.TOGGLE_PRIVATE_JS
print >> jsfile, self.GET_COOKIE_JS
print >> jsfile, self.SET_FRAME_JS
print >> jsfile, self.HIDE_PRIVATE_JS
print >> jsfile, self.TOGGLE_CALLGRAPH_JS
print >> jsfile, html_colorize.PYSRC_JAVASCRIPTS
jsfile.close()
#: A javascript that is used to show or hide the API documentation
#: for private objects. In order for this to work correctly, all
#: documentation for private objects should be enclosed in
#: C{<div class="private">...</div>} elements.
TOGGLE_PRIVATE_JS = '''
function toggle_private() {
// Search for any private/public links on this page. Store
// their old text in "cmd," so we will know what action to
// take; and change their text to the opposite action.
var cmd = "?";
var elts = document.getElementsByTagName("a");
for(var i=0; i<elts.length; i++) {
if (elts[i].className == "privatelink") {
cmd = elts[i].innerHTML;
elts[i].innerHTML = ((cmd=="show private")?"hide private":
"show private");
}
}
// Update all DIVs containing private objects.
var elts = document.getElementsByTagName("div");
for(var i=0; i<elts.length; i++) {
if (elts[i].className == "private") {
elts[i].style.display = ((cmd=="hide private")?"none":"block");
}
}
// Update all table rowss containing private objects. Note, we
// use "" instead of "block" becaue IE & firefox disagree on what
// this should be (block vs table-row), and "" just gives the
// default for both browsers.
var elts = document.getElementsByTagName("tr");
for(var i=0; i<elts.length; i++) {
if (elts[i].className == "private") {
elts[i].style.display = ((cmd=="hide private")?"none":"");
}
}
// Update all list items containing private objects.
var elts = document.getElementsByTagName("li");
for(var i=0; i<elts.length; i++) {
if (elts[i].className == "private") {
elts[i].style.display = ((cmd=="hide private")?"none":"list-item");
}
}
// Update all list items containing private objects.
var elts = document.getElementsByTagName("ul");
for(var i=0; i<elts.length; i++) {
if (elts[i].className == "private") {
elts[i].style.display = ((cmd=="hide private")?"none":"block");
}
}
// Set a cookie to remember the current option.
document.cookie = "EpydocPrivate="+cmd;
}
'''.strip()
#: A javascript that is used to read the value of a cookie. This
#: is used to remember whether private variables should be shown or
#: hidden.
GET_COOKIE_JS = '''
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else
{ begin += 2; }
var end = document.cookie.indexOf(";", begin);
if (end == -1)
{ end = dc.length; }
return unescape(dc.substring(begin + prefix.length, end));
}
'''.strip()
#: A javascript that is used to set the contents of two frames at
#: once. This is used by the project table-of-contents frame to
#: set both the module table-of-contents frame and the main frame
#: when the user clicks on a module.
SET_FRAME_JS = '''
function setFrame(url1, url2) {
parent.frames[1].location.href = url1;
parent.frames[2].location.href = url2;
}
'''.strip()
#: A javascript that is used to hide private variables, unless
#: either: (a) the cookie says not to; or (b) we appear to be
#: linking to a private variable.
HIDE_PRIVATE_JS = '''
function checkCookie() {
var cmd=getCookie("EpydocPrivate");
if (cmd!="show private" && location.href.indexOf("#_") < 0)
toggle_private();
}
'''.strip()
TOGGLE_CALLGRAPH_JS = '''
function toggleCallGraph(id) {
var elt = document.getElementById(id);
if (elt.style.display == "none")
elt.style.display = "block";
else
elt.style.display = "none";
}
'''.strip()
#////////////////////////////////////////////////////////////
#{ 2.10. Graphs
#////////////////////////////////////////////////////////////
# [xx] use DotGraph.to_html??
def render_graph(self, graph, css='graph-without-title'):
if graph is None: return ''
graph.caption = graph.title = None
image_url = '%s.gif' % graph.uid
image_file = os.path.join(self._directory, image_url)
return graph.to_html(image_file, image_url)
def render_callgraph(self, callgraph):
graph_html = self.render_graph(callgraph, css='graph-with-title')
if graph_html == '': return ''
return ('<div style="display:none" id="%s-div"><center>\n'
'<table border="0" cellpadding="0" cellspacing="0">\n'
' <tr><td>%s</td></tr>\n'
' <tr><th>Call Graph</th></tr>\n'
'</table><br />\n</center></div>\n' %
(callgraph.uid, graph_html))
def callgraph_link(self, callgraph):
if callgraph is None: return ''
return ('<br /><span class="codelink"><a href="javascript: void(0);" '
'onclick="toggleCallGraph(\'%s-div\');return false;">'
'call graph</a></span> ' % callgraph.uid)
#////////////////////////////////////////////////////////////
#{ 3.1. Page Header
#////////////////////////////////////////////////////////////
write_header = compile_template(
"""
write_header(self, out, title)
Generate HTML code for the standard page header, and write it
to C{out}. C{title} is a string containing the page title.
It should be appropriately escaped/encoded.
""",
# /------------------------- Template -------------------------\
'''
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>$title$</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
''')
# \------------------------------------------------------------/
#////////////////////////////////////////////////////////////
#{ 3.2. Page Footer
#////////////////////////////////////////////////////////////
write_footer = compile_template(
"""
write_footer(self, out, short=False)
Generate HTML code for the standard page footer, and write it
to C{out}.
""",
# /------------------------- Template -------------------------\
'''
>>> if not short:
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">Generated by Epydoc
$epydoc.__version__$ on $time.asctime()$</td>
<td align="right" class="footer">
<a href="http://epydoc.sourceforge.net">http://epydoc.sf.net</a>
</td>
</tr>
</table>
>>> #endif
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie()
// -->
</script>
</body>
</html>
''')
# \------------------------------------------------------------/
#////////////////////////////////////////////////////////////
#{ 3.3. Navigation Bar
#////////////////////////////////////////////////////////////
write_navbar = compile_template(
"""
write_navbar(self, out, context)
Generate HTML code for the navigation bar, and write it to
C{out}. The navigation bar typically looks like::
[ Home Trees Index Help Project ]
@param context: A value indicating what page we're generating
a navigation bar for. If we're generating an API
documentation page for an object, then C{context} is a
L{ValueDoc} containing the documentation for that object;
otherwise, C{context} is a string name for the page. The
following string names are recognized: C{'tree'}, C{'index'},
and C{'help'}.
""",
# /------------------------- Template -------------------------\
'''
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
>>> if self._top_page_url not in ("trees.html", "indices.html", "help.html"):
<!-- Home link -->
>>> if (isinstance(context, ValueDoc) and
>>> self._top_page_url == self.url(context.canonical_name)):
<th bgcolor="#70b0f0" class="navselect"
> Home </th>
>>> else:
<th class="navbar"> <a class="navbar"
href="$self._top_page_url$">Home</a> </th>
>>> #endif
<!-- Tree link -->
>>> if context == "trees":
<th bgcolor="#70b0f0" class="navselect"
> Trees </th>
>>> else:
<th class="navbar"> <a class="navbar"
href="trees.html">Trees</a> </th>
>>> #endif
<!-- Index link -->
>>> if context == "indices":
<th bgcolor="#70b0f0" class="navselect"
> Index </th>
>>> else:
<th class="navbar"> <a class="navbar"
href="indices.html">Index</a> </th>
>>> #endif
<!-- Help link -->
>>> if context == "help":
<th bgcolor="#70b0f0" class="navselect"
> Help </th>
>>> else:
<th class="navbar"> <a class="navbar"
href="help.html">Help</a> </th>
>>> #endif
>>> if self._prj_link:
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center">
<p class="nomargin">
$self._prj_link$
</p></th></tr></table></th>
>>> else:
<th class="navbar" width="100%"></th>
>>> #endif
</tr>
</table>
''')
# \------------------------------------------------------------/
#////////////////////////////////////////////////////////////
#{ 3.4. Breadcrumbs
#////////////////////////////////////////////////////////////
write_breadcrumbs = compile_template(
"""
write_breadcrumbs(self, out, context, context_url)
Generate HTML for the breadcrumbs line, and write it to
C{out}. The breadcrumbs line is an invisible table with a
list of pointers to the current object's ancestors on the
left; and the show/hide private selector and the
frames/noframes selector on the right.
@param context: The API documentation for the object whose
breadcrumbs we should generate.
@type context: L{ValueDoc}
""",
# /------------------------- Template -------------------------\
'''
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
>>> if isinstance(context, APIDoc):
<td width="100%">
<span class="breadcrumbs">
>>> crumbs = self.breadcrumbs(context)
>>> for crumb in crumbs[:-1]:
$crumb$ ::
>>> #endfor
$crumbs[-1]$
</span>
</td>
>>> else:
<td width="100%"> </td>
>>> #endif
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
>>> if self._show_private:
<tr><td align="right">$self.PRIVATE_LINK$</td></tr>
>>> #endif
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="$context_url$"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
''')
# \------------------------------------------------------------/
def breadcrumbs(self, doc):
crumbs = [self._crumb(doc)]
# Generate the crumbs for uid's ancestors.
while True:
container = self.docindex.container(doc)
if container is None:
if doc.canonical_name is UNKNOWN:
return ['??']+crumbs
elif isinstance(doc, ModuleDoc):
return ['Package %s' % ident
for ident in doc.canonical_name[:-1]]+crumbs
else:
return list(doc.canonical_name)+crumbs
else:
label = self._crumb(container)
name = container.canonical_name
crumbs.insert(0, self.href(container, label)) # [xx] code=0??
doc = container
def _crumb(self, doc):
if (len(doc.canonical_name)==1 and
doc.canonical_name[0].startswith('script-')):
return 'Script %s' % doc.canonical_name[0][7:]
return '%s %s' % (self.doc_kind(doc), doc.canonical_name[-1])
#////////////////////////////////////////////////////////////
#{ 3.5. Summary Tables
#////////////////////////////////////////////////////////////
def write_summary_table(self, out, heading, doc, value_type):
"""
Generate HTML code for a summary table, and write it to
C{out}. A summary table is a table that includes a one-row
description for each variable (of a given type) in a module
or class.
@param heading: The heading for the summary table; typically,
this indicates what kind of value the table describes
(e.g., functions or classes).
@param doc: A L{ValueDoc} object containing the API
documentation for the module or class whose variables
we should summarize.
@param value_type: A string indicating what type of value
should be listed in this summary table. This value
is passed on to C{doc}'s C{select_variables()} method.
"""
# inh_var_groups is a dictionary used to hold "inheritance
# pseudo-groups", which are created when inheritance is
# 'grouped'. It maps each base to a list of vars inherited
# from that base.
grouped_inh_vars = {}
# Divide all public variables of the given type into groups.
groups = [(plaintext_to_html(group_name),
doc.select_variables(group=group_name, imported=False,
value_type=value_type,
public=self._public_filter))
for group_name in doc.group_names()]
# Discard any empty groups; and return if they're all empty.
groups = [(g,vars) for (g,vars) in groups if vars]
if not groups: return
# Write a header
self.write_table_header(out, "summary", heading)
# Write a section for each group.
for name, var_docs in groups:
self.write_summary_group(out, doc, name,
var_docs, grouped_inh_vars)
# Write a section for each inheritance pseudo-group (used if
# inheritance=='grouped')
if grouped_inh_vars:
for base in doc.mro():
if base in grouped_inh_vars:
hdr = 'Inherited from %s' % self.href(base, context=doc)
tr_class = ''
if len([v for v in grouped_inh_vars[base]
if v.is_public]) == 0:
tr_class = ' class="private"'
self.write_group_header(out, hdr, tr_class)
for var_doc in grouped_inh_vars[base]:
self.write_summary_line(out, var_doc, doc)
# Write a footer for the table.
out(self.TABLE_FOOTER)
out('\n<br />\n')
def write_summary_group(self, out, doc, name, var_docs, grouped_inh_vars):
# Split up the var_docs list, according to the way each var
# should be displayed:
# - listed_inh_vars -- for listed inherited variables.
# - grouped_inh_vars -- for grouped inherited variables.
# - normal_vars -- for all other variables.
listed_inh_vars = {}
normal_vars = []
for var_doc in var_docs:
if var_doc.container != doc:
base = var_doc.container
if (base not in self.class_set or
self._inheritance == 'listed'):
listed_inh_vars.setdefault(base,[]).append(var_doc)
elif self._inheritance == 'grouped':
grouped_inh_vars.setdefault(base,[]).append(var_doc)
else:
normal_vars.append(var_doc)
else:
normal_vars.append(var_doc)
# Write a header for the group.
if name != '':
tr_class = ''
if len([v for v in var_docs if v.is_public]) == 0:
tr_class = ' class="private"'
self.write_group_header(out, name, tr_class)
# Write a line for each normal var:
for var_doc in normal_vars:
self.write_summary_line(out, var_doc, doc)
# Write a subsection for inherited vars:
if listed_inh_vars:
self.write_inheritance_list(out, doc, listed_inh_vars)
def write_inheritance_list(self, out, doc, listed_inh_vars):
out(' <tr>\n <td colspan="2">\n')
for base in doc.mro():
if base not in listed_inh_vars: continue
public_vars = [v for v in listed_inh_vars[base]
if v.is_public]
private_vars = [v for v in listed_inh_vars[base]
if not v.is_public]
if public_vars:
out(' <p class="varlist">'
'<span class="varlist-header">Inherited '
'from <code>%s</code></span>:\n' %
self.href(base, context=doc))
self.write_var_list(out, public_vars)
out(' </p>\n')
if private_vars and self._show_private:
out(' <div class="private">')
out(' <p class="varlist">'
'<span class="varlist-header">Inherited '
'from <code>%s</code></span> (private):\n' %
self.href(base, context=doc))
self.write_var_list(out, private_vars)
out(' </p></div>\n')
out(' </td>\n </tr>\n')
def write_var_list(self, out, vardocs):
out(' ')
out(',\n '.join(['<code>%s</code>' % self.href(v,v.name)
for v in vardocs])+'\n')
def write_summary_line(self, out, var_doc, container):
"""
Generate HTML code for a single line of a summary table, and
write it to C{out}. See L{write_summary_table} for more
information.
@param var_doc: The API documentation for the variable that
should be described by this line of the summary table.
@param container: The API documentation for the class or
module whose summary table we're writing.
"""
# If it's a private variable, then mark its <tr>.
if var_doc.is_public: tr_class = ''
else: tr_class = ' class="private"'
# Convert the summary to HTML.
summary = self.summary(var_doc, indent=6)
# If it's inherited, then add a note to the summary.
if var_doc.container != container and self._inheritance=="included":
summary += ("\n <em>(Inherited from " +
self.href(var_doc.container) + ")</em>")
if isinstance(var_doc.value, RoutineDoc):
if summary: summary = '<br />'+summary
self.write_function_summary_line(out, var_doc, tr_class, summary)
else:
# This is used for nested classes, properties, & variables
self.write_variable_summary_line(out, var_doc, tr_class, summary)
write_function_summary_line = compile_template(
"""
write_function_summary_line(self, out, var_doc, tr_class, summary)
Generate HTML code for a single line of a summary table,
describing a variable whose value is a function, and write
it to C{out}.
@param var_doc: The API documentation for the variable that
should be described by this line of the summary table.
@param container: The API documentation for the class or
module whose summary table we're writing.
""",
# /------------------------- Template -------------------------\
'''
<tr$tr_class$>
<td width="15%" align="right" valign="top" class="rtype">
$self.rtype(var_doc, indent=6) or " "$
</td>
<td>
$self.function_signature(var_doc, link_name=True)$
$summary$
</td>
</tr>
''')
# \------------------------------------------------------------/
write_variable_summary_line = compile_template(
'''
write_variable_summary_line(self, out, var_doc, tr_class, summary)
''',
# /------------------------- Template -------------------------\
'''
<tr$tr_class$>
<td width="15%">
<strong>$self.href(var_doc)$</strong></td>
<td>$summary or " "$</td>
</tr>
''')
# \------------------------------------------------------------/
#////////////////////////////////////////////////////////////
#{ 3.6. Details Lists
#////////////////////////////////////////////////////////////
def write_details_list(self, out, heading, doc, value_type):
# Get a list of the VarDocs we should describe.
if isinstance(doc, ClassDoc):
var_docs = doc.select_variables(value_type=value_type,
imported=False, inherited=False,
public=self._public_filter)
else:
var_docs = doc.select_variables(value_type=value_type,
imported=False,
public=self._public_filter)
if not var_docs: return
# Write a header
self.write_table_header(out, "details", heading)
out(self.TABLE_FOOTER)
for var_doc in var_docs:
self.write_details_entry(out, var_doc)
out('<br />\n')
def write_details_entry(self, out, var_doc):
descr = self.descr(var_doc, indent=2)
if var_doc.is_public: div_class = ''
else: div_class = ' class="private"'
# Functions
if isinstance(var_doc.value, RoutineDoc):
rtype = self.rtype(var_doc, indent=10)
rdescr = self.return_descr(var_doc, indent=10)
arg_descrs = []
# [xx] if we have a @type but no @param, this won't list it!
# [xx] put them in the right order??
for (arg_names, arg_descr) in var_doc.value.arg_descrs:
lhs = ', '.join([self.arg_name_to_html(var_doc.value, n)
for n in arg_names])
rhs = self.docstring_to_html(arg_descr, var_doc.value, 10)
arg_descrs.append( (lhs, rhs) )
# Perpare the call-graph, if requested
if 'callgraph' in self._graph_types:
linker = _HTMLDocstringLinker(self, var_doc.value)
callgraph = call_graph([var_doc.value], self.docindex,
linker, var_doc, add_callers=True,
add_callees=True)
if callgraph is not None and len(callgraph.nodes) == 0:
callgraph = None
else:
callgraph = None
self.write_function_details_entry(out, var_doc, descr, callgraph,
rtype, rdescr, arg_descrs,
div_class)
# Properties
elif isinstance(var_doc.value, PropertyDoc):
prop_doc = var_doc.value
accessors = [(name, self.property_accessor_to_html(val_doc),
self.summary(val_doc)) for (name, val_doc) in
[('Get', prop_doc.fget), ('Set', prop_doc.fset),
('Delete', prop_doc.fdel)]]
self.write_property_details_entry(out, var_doc, descr,
accessors, div_class)
# Variables
else:
self.write_variable_details_entry(out, var_doc, descr, div_class)
def labelled_list_item(self, lhs, rhs):
# If the RHS starts with a paragraph, then move the
# paragraph-start tag to the beginning of the lhs instead (so
# there won't be a line break after the '-').
m = re.match(r'^<p( [^>]+)?>', rhs)
if m:
lhs = m.group() + lhs
rhs = rhs[m.end():]
return '<li>%s - %s</li>' % (lhs, rhs)
def property_accessor_to_html(self, val_doc):
if val_doc not in (None, UNKNOWN):
if isinstance(val_doc, RoutineDoc):
return self.function_signature(val_doc, css_class=
"summary-sig")
elif isinstance(val_doc, GenericValueDoc):
if val_doc.parse_repr is not UNKNOWN:
return plaintext_to_html(val_doc.parse_repr)
else:
pyval_repr = val_doc.pyval_repr()
if pyval_repr is not UNKNOWN:
return plaintext_to_html(pyval_repr)
else:
return self.href(val_doc)
else:
return self.href(val_doc)
else:
return '??'
def arg_name_to_html(self, func_doc, arg_name):
"""
A helper function used to format an argument name, for use in
the argument description list under a routine's details entry.
This just wraps strong & code tags around the arg name; and if
the arg name is associated with a type, then adds it
parenthetically after the name.
"""
s = '<strong class="pname"><code>%s</code></strong>' % arg_name
if arg_name in func_doc.arg_types:
typ = func_doc.arg_types[arg_name]
typ_html = self.docstring_to_html(typ, func_doc, 10)
s += " (<code>%s</code>)" % typ_html
return s
write_function_details_entry = compile_template(
'''
write_function_details_entry(self, out, var_doc, descr, callgraph, \
rtype, rdescr, arg_descrs, div_class)
''',
# /------------------------- Template -------------------------\
'''
>>> func_doc = var_doc.value
<a name="$var_doc.name$"></a>
<div$div_class$>
<table width="100%" class="func-details" bgcolor="#e0e0e0"><tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3>$self.function_signature(var_doc)$
>>> if var_doc.name in self.SPECIAL_METHODS:
<br /><em class="fname">($self.SPECIAL_METHODS[var_doc.name]$)</em>
>>> #endif
</h3>
</td><td align="right" valign="top"
>$self.pysrc_link(func_doc)$ </span
>$self.callgraph_link(callgraph)$</td>
</table>
$self.render_callgraph(callgraph)$
$descr$
<dl><dt></dt><dd>
>>> # === parameters ===
>>> if arg_descrs:
<dl><dt>Parameters:</dt></dl>
<ul>
>>> for lhs, rhs in arg_descrs:
$self.labelled_list_item(lhs, rhs)$
>>> #endfor
</ul>
>>> #endif
>>> # === return type ===
>>> if rdescr and rtype:
<dl><dt>Returns: <code>$rtype$</code></dt>
<dd>$rdescr$</dd></dl>
>>> elif rdescr:
<dl><dt>Returns:</dt>
<dd>$rdescr$</dd></dl>
>>> elif rtype:
<dl><dt>Returns: <code>$rtype$</code></dt></dl>
>>> #endif
>>> # === exceptions ===
>>> if func_doc.exception_descrs not in (None, UNKNOWN, (), []):
<dl><dt>Raises:</dt></dl>
<ul>
>>> for name, descr in func_doc.exception_descrs:
$self.labelled_list_item(
"<code><strong class=\'fraise\'>" +
self.href(name) + "</strong></code>",
self.docstring_to_html(descr, func_doc, 8))$
>>> #endfor
</ul>
>>> #endif
>>> # === overrides ===
>>> if var_doc.overrides not in (None, UNKNOWN):
<dl><dt>Overrides:
$self.href(var_doc.overrides.value, context=var_doc)$
>>> if (func_doc.docstring in (None, UNKNOWN) and
>>> var_doc.overrides.value.docstring not in (None, UNKNOWN)):
<dd><em class="note">(inherited documentation)</em></dd>
>>> #endif
</dt></dl>
>>> #endif
>>> # === metadata ===
>>> self.write_standard_fields(out, func_doc)
</dd></dl>
</td></tr></table>
</div>
''')
# \------------------------------------------------------------/
# Names for the __special__ methods.
SPECIAL_METHODS ={
'__init__': 'Constructor',
'__del__': 'Destructor',
'__add__': 'Addition operator',
'__sub__': 'Subtraction operator',
'__and__': 'And operator',
'__or__': 'Or operator',
'__repr__': 'Representation operator',
'__call__': 'Call operator',
'__getattr__': 'Qualification operator',
'__getitem__': 'Indexing operator',
'__setitem__': 'Index assignment operator',
'__delitem__': 'Index deletion operator',
'__delslice__': 'Slice deletion operator',
'__setslice__': 'Slice assignment operator',
'__getslice__': 'Slicling operator',
'__len__': 'Length operator',
'__cmp__': 'Comparison operator',
'__eq__': 'Equality operator',
'__in__': 'Containership operator',
'__gt__': 'Greater-than operator',
'__lt__': 'Less-than operator',
'__ge__': 'Greater-than-or-equals operator',
'__le__': 'Less-than-or-equals operator',
'__radd__': 'Right-side addition operator',
'__hash__': 'Hashing function',
'__contains__': 'In operator',
'__nonzero__': 'Boolean test operator',
'__str__': 'Informal representation operator',
}
write_property_details_entry = compile_template(
'''
write_property_details_entry(self, out, var_doc, descr, \
accessors, div_class)
''',
# /------------------------- Template -------------------------\
'''
>>> prop_doc = var_doc.value
<a name="$var_doc.name$"></a>
<div$div_class$>
<table width="100%" class="prop-details" bgcolor="#e0e0e0"><tr><td>
<h3>$var_doc.name$</h3>
$descr$
<dl><dt></dt><dd>
>>> if prop_doc.type_descr not in (None, UNKNOWN):
<dl><dt>Type:</dt>
<dd>$self.type_descr(var_doc, indent=6)$</dd></dl>
>>> #endif
>>> for (name, val, summary) in accessors:
<dt>$name$ Method:</dt>
<dd>$val$
>>> if summary:
- $summary$
>>> #endif
</dd>
>>> #endfor
</dd></dl>
</td></tr></table>
</div>
''')
# \------------------------------------------------------------/
write_variable_details_entry = compile_template(
'''
write_variable_details_entry(self, out, var_doc, descr, div_class)
''',
# /------------------------- Template -------------------------\
'''
<a name="$var_doc.name$"></a>
<div$div_class$>
<table width="100%" class="var-details" bgcolor="#e0e0e0"><tr><td>
<h3>$var_doc.name$</h3>
$descr$
<dl><dt></dt><dd>
>>> if var_doc.type_descr not in (None, UNKNOWN):
<dl><dt>Type:</dt>
<dd>$self.type_descr(var_doc, indent=6)$</dd></dl>
>>> #endif
>>> tooltip = self.variable_tooltip(var_doc)
>>> if var_doc.value is not UNKNOWN:
<dl$tooltip$><dt>Value:</dt>
<dd><table><tr><td><pre class="variable">
$self.pprint_value(var_doc.value)$
</pre></td></tr></table></dd>
</dl>
>>> #endif
</dd></dl>
</td></tr></table>
</div>
''')
# \------------------------------------------------------------/
_variable_linelen = 70
_variable_maxlines = 3
_variable_tooltip_linelen = 70
def variable_tooltip(self, var_doc):
if var_doc.value in (None, UNKNOWN):
return ''
else:
pyval_repr = var_doc.value.pyval_repr()
if pyval_repr is not UNKNOWN:
s = pyval_repr
elif var_doc.value.parse_repr is not UNKNOWN:
s = var_doc.value.parse_repr
else:
return ''
if len(s) > self._variable_tooltip_linelen:
s = s[:self._variable_tooltip_linelen-3]+'...'
return ' title="%s"' % plaintext_to_html(s)
def pprint_value(self, val_doc, multiline=True, summary_linelen=0):
if val_doc.pyval is not UNKNOWN:
return self.pprint_pyval(val_doc.pyval, multiline,
summary_linelen)
elif val_doc.parse_repr is not UNKNOWN:
s = plaintext_to_html(val_doc.parse_repr)
return self._linewrap_html(s, self._variable_linelen,
self._variable_maxlines)
else:
return self.href(val_doc)
def pprint_pyval(self, pyval, multiline=True, summary_linelen=0):
# Handle the most common cases first. The following types
# will never need any line wrapping, etc; and they cover most
# variable values (esp int, for constants). I leave out
# LongType on purpose, since long values may need line-
# wrapping.
if (type(pyval) is types.IntType or type(pyval) is types.FloatType or
type(pyval) is types.NoneType or type(pyval) is types.ComplexType):
# none of these should contain '&', '<' or '>'.
vstr = repr(pyval)
return vstr + ' ' * (self._variable_linelen-len(vstr))
# For strings, use repr. Use tripple-quoted-strings where
# appropriate.
elif type(pyval) is types.StringType:
vstr = repr(pyval)
if vstr.find(r'\n') >= 0 and multiline:
body = vstr[1:-1].replace(r'\n', '\n')
vstr = ('<span class="variable-quote">'+vstr[0]*3+'</span>'+
plaintext_to_html(body) +
'<span class="variable-quote">'+vstr[0]*3+'</span>')
else:
vstr = ('<span class="variable-quote">'+vstr[0]+'</span>'+
plaintext_to_html(vstr[1:-1])+
'<span class="variable-quote">'+vstr[0]+'</span>')
# For lists, tuples, and dicts, use pprint. When possible,
# restrict the amount of stuff that pprint needs to look at,
# since pprint is surprisingly slow.
elif type(pyval) is types.TupleType or type(pyval) is types.ListType:
try: vstr = repr(pyval)
except: vstr = '...'
if multiline and len(vstr) > self._variable_linelen:
vstr = pprint.pformat(pyval[:self._variable_maxlines+1])
vstr = plaintext_to_html(vstr)
elif type(pyval) is type({}):
try: vstr = repr(pyval)
except: vstr = '...'
if multiline and len(vstr) > self._variable_linelen:
if len(pyval) < self._variable_maxlines+50:
vstr = pprint.pformat(pyval)
else:
shortval = {}
for (k,v) in pyval.items()[:self._variable_maxlines+1]:
shortval[k]=v
vstr = pprint.pformat(shortval)
vstr = plaintext_to_html(vstr)
# For regexps, use colorize_re.
elif type(pyval).__name__ == 'SRE_Pattern':
try: vstr = colorize_re(pyval)
except TypeError, sre_constants.error:
try: vstr = plaintext_to_html(repr(pyval))
except: vstr = '...'
# For other objects, use repr to generate a representation.
else:
try: vstr = plaintext_to_html(repr(pyval))
except: vstr = '...'
# For the summary table, just return the value; don't
# bother to word-wrap.
if not multiline:
vstr = vstr.replace('\n', '')
# Change spaces to (except spaces in html tags)
vstr = vstr.replace(' ', ' ')
vstr = vstr.replace('<span ', '<span ')
vstr = self._linewrap_html(vstr, summary_linelen, 1)
return '<code>%s</code>\n' % vstr
# Do line-wrapping.
return self._linewrap_html(vstr, self._variable_linelen,
self._variable_maxlines)
def _linewrap_html(self, s, linelen, maxlines):
"""
Add line-wrapping to the HTML string C{s}. Line length is
determined by C{linelen}; and the maximum number of
lines to display is determined by C{maxlines}. This
function treats HTML entities (e.g., C{&}) as single
characters; and ignores HTML tags (e.g., C{<p>}).
"""
LINEWRAP_MARKER = r'<span class="variable-linewrap">\</span>'
ELLIPSIS_MARKER = r'<span class="variable-ellipsis">...</span>'
open_elements = [] # tag stack
lines = []
start = end = cnum = 0
while len(lines) <= maxlines and end < len(s):
# Skip over HTML tags.
if s[end] == '<':
newend = s.find('>', end)
tag = s[end+1:newend]
if tag[-1]!="/":
# non-empty tag
tagname = tag.split(None,1)[0]
if tagname[0] == "/":
open_elements.pop()
else:
open_elements.append(tagname)
end = newend
cnum -= 1
# HTML entities just count as 1 char.
elif s[end] == '&':
end = s.find(';', end)
# Go on to the next character.
cnum += 1
end += 1
# Check for end-of-line.
if s[end-1] == '\n':
lines.append(s[start:end-1])
cnum = 0
start = end
# Check for line-wrap
if cnum == linelen and end<len(s) and s[end] != '\n':
if maxlines == 1:
closing_tags = ""
for tag in open_elements:
closing_tags += "</%s>" % (tag,)
return s[start:end]+closing_tags+ELLIPSIS_MARKER
lines.append(s[start:end]+LINEWRAP_MARKER)
cnum = 0
start = end
# Add on anything that's left.
if end == len(s):
lines.append(s[start:end])
# Use the ellipsis marker if the string is too long.
if len(lines) > maxlines:
closing_tags = ""
for tag in open_elements:
closing_tags += "</%s>" % (tag,)
lines[-1] = closing_tags+ELLIPSIS_MARKER
cnum = 3
# Pad the last line to linelen.
lines[-1] += ' '*(linelen-cnum+1)
return ('\n').join(lines)
#////////////////////////////////////////////////////////////
#{ Base Tree
#////////////////////////////////////////////////////////////
def base_tree(self, doc, width=None, postfix='', context=None):
"""
@return: The HTML code for a class's base tree. The tree is
drawn 'upside-down' and right justified, to allow for
multiple inheritance.
@rtype: C{string}
"""
if context is None:
context = doc
if width == None: width = self.find_tree_width(doc, context)
if isinstance(doc, ClassDoc) and doc.bases != UNKNOWN:
bases = doc.bases
else:
bases = []
if postfix == '':
# [XX] use var name instead of canonical name?
s = (' '*(width-2) + '<strong class="uidshort">'+
self.contextual_label(doc, context)+'</strong>\n')
else: s = ''
for i in range(len(bases)-1, -1, -1):
base = bases[i]
label = self.contextual_label(base, context)
s = (' '*(width-4-len(label)) + self.href(base, label)
+' --+'+postfix+'\n' +
' '*(width-4) +
' |'+postfix+'\n' +
s)
if i != 0:
s = (self.base_tree(base, width-4, ' |'+postfix)+s)
else:
s = (self.base_tree(base, width-4, ' '+postfix)+s)
return s
def find_tree_width(self, doc, context):
"""
Helper function for L{base_tree}.
@return: The width of a base tree, when drawn
right-justified. This is used by L{base_tree} to
determine how far to indent lines of the base tree.
@rtype: C{int}
"""
if not isinstance(doc, ClassDoc): return 2
if doc.bases == UNKNOWN: return 2
width = 2
for base in doc.bases:
width = max(width, len(self.contextual_label(base, context))+4,
self.find_tree_width(base, context)+4)
return width
def contextual_label(self, doc, context):
"""
Return the label for L{doc} to be shown in C{context}.
"""
context = context.canonical_name
if context is not UNKNOWN:
context = context.container()
return str(doc.canonical_name.contextualize(context))
#////////////////////////////////////////////////////////////
#{ Function Signatures
#////////////////////////////////////////////////////////////
def function_signature(self, api_doc, css_class='sig',
link_name=False):
# [XX] clean this up!
if isinstance(api_doc, VariableDoc):
func_doc = api_doc.value
# This should never happen, but just in case:
if api_doc.value in (None, UNKNOWN):
return (('<span class="%s"><span class="%s-name">%s'+
'</span>(...)</span>') %
(css_class, css_class, api_doc.name))
# Get the function's name.
if link_name:
name = self.href(api_doc, css_class=css_class+'-name')
else:
name = ('<span class="%s-name">%s</span>' %
(css_class, api_doc.name))
else:
func_doc = api_doc
name = self.href(api_doc, css_class=css_class+'-name')
if func_doc.posargs == UNKNOWN:
args = ['...']
else:
args = [self.func_arg(n, d, css_class) for (n, d)
in zip(func_doc.posargs, func_doc.posarg_defaults)]
if func_doc.vararg:
if func_doc.vararg == '...':
args.append('<span class="%s-arg">...</span>' % css_class)
else:
args.append('<span class="%s-arg">*%s</span>' %
(css_class, func_doc.vararg))
if func_doc.kwarg:
args.append('<span class="%s-arg">**%s</span>' %
(css_class, func_doc.kwarg))
return ('<span class="%s">%s(%s)</span>' %
(css_class, name, ',\n '.join(args)))
# [xx] tuple args???
def func_arg(self, name, default, css_class):
name = self._arg_name(name)
s = '<span class="%s-arg">%s</span>' % (css_class, name)
if default is not None:
if default.parse_repr is not UNKNOWN:
s += ('=<span class="%s-default">%s</span>' %
(css_class, plaintext_to_html(default.parse_repr)))
else:
pyval_repr = default.pyval_repr()
if pyval_repr is not UNKNOWN:
s += ('=<span class="%s-default">%s</span>' %
(css_class, plaintext_to_html(pyval_repr)))
else:
s += '=<span class="%s-default">??</span>' % css_class
return s
def _arg_name(self, arg):
if isinstance(arg, basestring):
return arg
elif len(arg) == 1:
return '(%s,)' % self._arg_name(arg[0])
else:
return '(%s)' % (', '.join([self._arg_name(a) for a in arg]))
#////////////////////////////////////////////////////////////
#{ Import Lists
#////////////////////////////////////////////////////////////
def write_imports(self, out, doc):
assert isinstance(doc, NamespaceDoc)
imports = doc.select_variables(imported=True,
public=self._public_filter)
if not imports: return
out('<p class="imports">')
out('<span class="varlist-header">Imports:</span>\n ')
out(',\n '.join([self._import(v, doc) for v in imports]))
out('\n</p>\n')
def _import(self, var_doc, context):
if var_doc.imported_from not in (None, UNKNOWN):
return self.href(var_doc.imported_from, context=context)
elif (var_doc.value not in (None, UNKNOWN) and not
isinstance(var_doc.value, GenericValueDoc)):
return self.href(var_doc.value, context=context)
else:
return plaintext_to_html(var_doc.name)
#////////////////////////////////////////////////////////////
#{ Function Attributes
#////////////////////////////////////////////////////////////
#////////////////////////////////////////////////////////////
#{ Module Trees
#////////////////////////////////////////////////////////////
def write_module_tree(self, out):
if not self.module_list: return
# Write entries for all top-level modules/packages.
out('<ul>\n')
for doc in self.module_list:
if (doc.package in (None, UNKNOWN) or
doc.package not in self.module_set):
self.write_module_tree_item(out, doc)
out('</ul>\n')
def write_module_list(self, out, doc):
if len(doc.submodules) == 0: return
self.write_table_header(out, "details", "Submodules")
for group_name in doc.group_names():
if not doc.submodule_groups[group_name]: continue
if group_name:
self.write_group_header(out, group_name)
out(' <tr><td><ul>\n')
for submodule in doc.submodule_groups[group_name]:
self.write_module_tree_item(out, submodule, package=doc)
out(' </ul></td></tr>\n')
out(self.TABLE_FOOTER+'\n<br />\n')
def write_module_tree_item(self, out, doc, package=None):
# If it's a private variable, then mark its <li>.
var = package and package.variables.get(doc.canonical_name[-1])
if var is not None:
priv = var.is_public is False
else:
priv = doc.canonical_name[-1].startswith('_')
out(' <li%s> <strong class="uidlink">%s</strong>'
% (priv and ' class="private"' or '', self.href(doc)))
if doc.summary not in (None, UNKNOWN):
out(': <em class="summary">'+
self.description(doc.summary, doc, 8)+'</em>')
out('</li>\n')
if doc.submodules != UNKNOWN and doc.submodules:
out(' <ul%s>\n' % (priv and ' class="private"' or ''))
for submodule in doc.submodules:
self.write_module_tree_item(out, submodule, package=doc)
out(' </ul>\n </li>\n')
#////////////////////////////////////////////////////////////
#{ Class trees
#////////////////////////////////////////////////////////////
def write_class_tree(self, out):
"""
Write HTML code for a nested list showing the base/subclass
relationships between all documented classes. Each element of
the top-level list is a class with no (documented) bases; and
under each class is listed all of its subclasses. Note that
in the case of multiple inheritance, a class may appear
multiple times. This is used by L{write_trees} to write
the class hierarchy.
@todo: For multiple inheritance, don't repeat subclasses the
second time a class is mentioned; instead, link to the
first mention.
"""
# [XX] backref for multiple inheritance?
if not self.class_list: return
# Build a set containing all classes that we should list.
# This includes everything in class_list, plus any of those
# class' bases, but not undocumented subclasses.
class_set = self.class_set.copy()
for doc in self.class_list:
if doc.bases != UNKNOWN:
for base in doc.bases:
if base not in class_set:
if isinstance(base, ClassDoc):
class_set.update(base.mro())
else:
# [XX] need to deal with this -- how?
pass
#class_set.add(base)
out('<ul>\n')
for doc in sorted(class_set):
if doc.bases != UNKNOWN and len(doc.bases)==0:
self.write_class_tree_item(out, doc, class_set)
out('</ul>\n')
write_class_tree_item = compile_template(
'''
write_class_tree_item(self, out, doc, class_set)
''',
# /------------------------- Template -------------------------\
'''
>>> if doc.summary in (None, UNKNOWN):
<li> <strong class="uidlink">$self.href(doc)$</strong>
>>> else:
<li> <strong class="uidlink">$self.href(doc)$</strong>:
<em class="summary">$self.description(doc.summary, doc, 8)$</em>
>>> # endif
>>> if doc.subclasses:
<ul>
>>> for subclass in set(doc.subclasses):
>>> if subclass in class_set:
>>> self.write_class_tree_item(out, subclass, class_set)
>>> #endif
>>> #endfor
</ul>
>>> #endif
</li>
''')
# \------------------------------------------------------------/
#////////////////////////////////////////////////////////////
#{ Standard Fields
#////////////////////////////////////////////////////////////
def write_standard_fields(self, out, doc):
"""
Write HTML code containing descriptions of any standard markup
fields that are defined by the given L{APIDoc} object (such as
C{@author} and C{@todo} fields).
@param doc: The L{APIDoc} object containing the API documentation
for the object whose standard markup fields should be
described.
"""
fields = []
field_values = {}
#if _sort_fields: fields = STANDARD_FIELD_NAMES [XX]
for (field, arg, descr) in doc.metadata:
if field not in field_values:
fields.append(field)
if field.takes_arg:
subfields = field_values.setdefault(field,{})
subfields.setdefault(arg,[]).append(descr)
else:
field_values.setdefault(field,[]).append(descr)
for field in fields:
if field.takes_arg:
for arg, descrs in field_values[field].items():
self.write_standard_field(out, doc, field, descrs, arg)
else:
self.write_standard_field(out, doc, field, field_values[field])
write_standard_field = compile_template(
"""
write_standard_field(self, out, doc, field, descrs, arg='')
""",
# /------------------------- Template -------------------------\
"""
>>> if arg: arglabel = ' (%s)' % arg
>>> else: arglabel = ''
>>> if len(descrs) == 1:
<p><strong>$field.singular+arglabel$:</strong>
$self.description(descrs[0], doc, 8)$
</p>
>>> elif field.short:
<dl><dt>$field.plural+arglabel$:</dt>
<dd>
>>> for descr in descrs[:-1]:
$self.description(descr, doc, 10)$,
>>> # end for
$self.description(descrs[-1], doc, 10)$
</dd>
</dl>
>>> else:
<p><strong>$field.plural+arglabel$:</strong>
<ul>
>>> for descr in descrs:
<li>
$self.description(descr, doc, 8)$
</li>
>>> # end for
</ul>
>>> # end else
>>> # end for
""")
# \------------------------------------------------------------/
#////////////////////////////////////////////////////////////
#{ Term index generation
#////////////////////////////////////////////////////////////
def _get_index_terms(self, parsed_docstring, link, terms, links):
"""
A helper function for L{_extract_term_index}.
For each index term M{t} with key M{k} in C{parsed_docstring},
modify C{terms} and C{links} as follows:
- Set C{terms[M{k}] = t} (if C{terms[M{k}]} doesn't exist).
- Append C{link} to C{links[M{k}]}.
"""
if parsed_docstring in (None, UNKNOWN): return
for term in parsed_docstring.index_terms():
key = self._term_index_to_anchor(term)
if not terms.has_key(key):
terms[key] = term
links[key] = []
links[key].append(link)
def _term_index_to_anchor(self, term):
"""
Given the name of an inline index item, construct a URI anchor.
These anchors are used to create links from the index page to each
index item.
"""
# Include "-" so we don't accidentally collide with the name
# of a python identifier.
s = re.sub(r'\s\s+', '-', term.to_plaintext(None))
return "index-"+re.sub("[^a-zA-Z0-9]", "_", s)
def _extract_term_index(self):
"""
Extract the set of terms that should be indexed from all
documented docstrings. Return the extracted set as a
list of tuples of the form C{(key, term, [links])}.
This list is used by L{write_indices()} to construct the
term index.
@rtype: C{list} of C{(string, ParsedDocstring, list of ValueDoc)}
"""
terms = {}
links = {}
for doc in self.valdocs:
self._get_index_terms(doc.descr, doc, terms, links)
if doc.metadata not in (None, UNKNOWN):
for (field, arg, descr) in doc.metadata:
self._get_index_terms(descr, doc, terms, links)
# [xx] summary? type_descr? others?
if isinstance(doc, NamespaceDoc):
for var in doc.variables.values():
self._get_index_terms(var.descr, var, terms, links)
for (field, arg, descr) in var.metadata:
self._get_index_terms(descr, var, terms, links)
elif isinstance(doc, RoutineDoc):
self._get_index_terms(doc.return_descr, doc, terms, links)
self._get_index_terms(doc.return_type, doc, terms, links)
if doc.arg_descrs not in (None, UNKNOWN):
for arg, descr in doc.arg_descrs:
self._get_index_terms(descr, doc, terms, links)
if doc.arg_types not in (None, UNKNOWN):
for arg, descr in doc.arg_types.items():
self._get_index_terms(descr, doc, terms, links)
if doc.exception_descrs not in (None, UNKNOWN):
for excname, descr in doc.exception_descrs:
self._get_index_terms(descr, doc, terms, links)
elif isinstance(doc, PropertyDoc):
self._get_index_terms(doc.type_descr, doc, terms, links)
# Combine terms & links into one list
keys = terms.keys()
keys.sort()
return [(k, terms[k], links[k]) for k in keys]
#////////////////////////////////////////////////////////////
#{ Helper functions
#////////////////////////////////////////////////////////////
# [XX] Is it worth-while to pull the anchor tricks that I do here?
# Or should I just live with the fact that show/hide private moves
# stuff around?
write_table_header = compile_template(
'''
write_table_header(self, out, css_class, heading=None, \
private_link=True)
''',
# /------------------------- Template -------------------------\
'''
>>> if heading is not None:
>>> anchor = "section-%s" % re.sub("\W", "", heading)
<!-- ==================== $heading.upper()$ ==================== -->
<a name="$anchor$"></a>
>>> #endif
<table class="$css_class$" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
>>> if heading is not None:
<tr bgcolor="#70b0f0" class="$css_class$">
>>> if private_link:
<td colspan="2">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<th align="left" class="$css_class$">$heading$</th>
<td align="right" valign="top"
><span class="options">[<a href="#$anchor$"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
>>> else:
<th align="left" colspan="2" class="$css_class$">$heading$</th>
>>> #endif
</tr>
>>> #endif
''')
# \------------------------------------------------------------/
TABLE_FOOTER = '</table>\n'
PRIVATE_LINK = '''
<span class="options">[<a href="javascript: void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span>
'''.strip()
write_group_header = compile_template(
'''
write_group_header(self, out, group, tr_class='')
''',
# /------------------------- Template -------------------------\
'''
<tr bgcolor="#e8f0f8" $tr_class$>
<th colspan="2" class="group"
> $group$</th></tr>
''')
# \------------------------------------------------------------/
def url(self, obj):
"""
Return the URL for the given object, which can be a
C{VariableDoc}, a C{ValueDoc}, or a C{DottedName}.
"""
# Module: <canonical_name>-module.html
if isinstance(obj, ModuleDoc):
if obj not in self.module_set: return None
return urllib.quote('%s'%obj.canonical_name) + '-module.html'
# Class: <canonical_name>-class.html
elif isinstance(obj, ClassDoc):
if obj not in self.class_set: return None
return urllib.quote('%s'%obj.canonical_name) + '-class.html'
# Variable
elif isinstance(obj, VariableDoc):
val_doc = obj.value
if isinstance(val_doc, (ModuleDoc, ClassDoc)):
return self.url(val_doc)
elif obj.container in (None, UNKNOWN):
if val_doc in (None, UNKNOWN): return None
return self.url(val_doc)
elif obj.is_imported == True:
if obj.imported_from is not UNKNOWN:
return self.url(obj.imported_from)
else:
return None
else:
container_url = self.url(obj.container)
if container_url is None: return None
return '%s#%s' % (container_url, urllib.quote('%s'%obj.name))
# Value (other than module or class)
elif isinstance(obj, ValueDoc):
container = self.docindex.container(obj)
if container is None:
return None # We couldn't find it!
else:
container_url = self.url(container)
if container_url is None: return None
anchor = urllib.quote('%s'%obj.canonical_name[-1])
return '%s#%s' % (container_url, anchor)
# Dotted name: look up the corresponding APIDoc
elif isinstance(obj, DottedName):
val_doc = self.docindex.get_valdoc(obj)
if val_doc is None: return None
return self.url(val_doc)
# Special pages:
elif obj == 'indices':
return 'indices.html'
elif obj == 'help':
return 'help.html'
elif obj == 'trees':
return 'trees.html'
else:
raise ValueError, "Don't know what to do with %r" % obj
def pysrc_link(self, api_doc):
if not self._incl_sourcecode:
return ''
url = self.pysrc_url(api_doc)
if url is not None:
return ('<span class="codelink"><a href="%s">source '
'code</a></span>' % url)
else:
return ''
def pysrc_url(self, api_doc):
if isinstance(api_doc, VariableDoc):
if api_doc.value not in (None, UNKNOWN):
return pysrc_link(api_doc.value)
else:
return None
elif isinstance(api_doc, ModuleDoc):
if api_doc in self.modules_with_sourcecode:
return ('%s-pysrc.html' %
urllib.quote('%s' % api_doc.canonical_name))
else:
return None
else:
module = api_doc.defining_module
if module == UNKNOWN: return None
module_pysrc_url = self.pysrc_url(module)
if module_pysrc_url is None: return None
module_name = module.canonical_name
if not module_name.dominates(api_doc.canonical_name, True):
log.debug('%r is in %r but name does not dominate' %
(api_doc, module))
return module_pysrc_url
mname_len = len(module.canonical_name)
anchor = '%s' % api_doc.canonical_name[mname_len:]
return '%s#%s' % (module_pysrc_url, urllib.quote(anchor))
# We didn't find it:
return None
# [xx] add code to automatically do <code> wrapping or the like?
def href(self, target, label=None, css_class=None, context=None):
"""
Return the HTML code for an HREF link to the given target
(which can be a C{VariableDoc}, a C{ValueDoc}, or a
C{DottedName}.
If a C{NamespaceDoc} C{context} is specified, the target label is
contextualized to it.
"""
assert isinstance(target, (APIDoc, DottedName))
# Pick a label, if none was given.
if label is None:
if isinstance(target, VariableDoc):
label = target.name
elif (isinstance(target, ValueDoc) and
target.canonical_name is not UNKNOWN):
label = target.canonical_name
elif isinstance(target, DottedName):
label = target
else:
raise ValueError("Unable to find a label for %r" % target)
if context is not None and isinstance(label, DottedName):
label = label.contextualize(context.canonical_name.container())
label = plaintext_to_html(str(label))
# Munge names for scripts & unreachable values
if label.startswith('script-'):
label = label[7:] + ' (script)'
if label.startswith('??'):
label = '<i>unreachable</i>' + label[2:]
label = re.sub(r'-\d+$', '', label)
# Get the url for the target.
url = self.url(target)
if url is None: return label
# Construct a string for the class attribute.
if css_class is None:
css = ''
else:
css = ' class="%s"' % css_class
return '<a href="%s"%s>%s</a>' % (url, css, label)
def summary(self, api_doc, indent=0):
assert isinstance(api_doc, APIDoc)
if (isinstance(api_doc, VariableDoc) and
api_doc.summary in (None, UNKNOWN)):
if api_doc.value in (None, UNKNOWN): return ''
api_doc = api_doc.value
if api_doc.summary in (None, UNKNOWN): return ''
return self.docstring_to_html(api_doc.summary, api_doc, indent)
def descr(self, api_doc, indent=0):
assert isinstance(api_doc, APIDoc)
if (isinstance(api_doc, VariableDoc) and
api_doc.descr in (None, UNKNOWN)):
if api_doc.value in (None, UNKNOWN): return ''
api_doc = api_doc.value
if api_doc.descr in (None, UNKNOWN): return ''
return self.docstring_to_html(api_doc.descr, api_doc, indent)
def type_descr(self, api_doc, indent=0):
assert isinstance(api_doc, APIDoc)
if (isinstance(api_doc, VariableDoc) and
api_doc.type_descr in (None, UNKNOWN)):
if api_doc.value in (None, UNKNOWN): return ''
api_doc = api_doc.value
if api_doc.type_descr in (None, UNKNOWN): return ''
return self.docstring_to_html(api_doc.type_descr, api_doc, indent)
def rtype(self, api_doc, indent=0):
if isinstance(api_doc, VariableDoc):
if api_doc.value in (None, UNKNOWN): return ''
api_doc = api_doc.value
assert isinstance(api_doc, RoutineDoc)
if api_doc.return_type in (None, UNKNOWN): return ''
return self.docstring_to_html(api_doc.return_type, api_doc, indent)
def return_descr(self, api_doc, indent=0):
if isinstance(api_doc, VariableDoc):
if api_doc.value in (None, UNKNOWN): return ''
api_doc = api_doc.value
assert isinstance(api_doc, RoutineDoc)
if api_doc.return_descr in (None, UNKNOWN): return ''
return self.docstring_to_html(api_doc.return_descr, api_doc, indent)
def docstring_to_html(self, parsed_docstring, where=None, indent=0):
if parsed_docstring in (None, UNKNOWN): return ''
linker = _HTMLDocstringLinker(self, where)
s = parsed_docstring.to_html(linker, indent=indent,
directory=self._directory,
docindex=self.docindex,
context=where).strip()
if self._mark_docstrings:
s = '<span class="docstring">%s</span><!--end docstring-->' % s
return s
# [XX] Just use docstring_to_html???
def description(self, parsed_docstring, where=None, indent=0):
assert isinstance(where, (APIDoc, type(None)))
if parsed_docstring in (None, UNKNOWN): return ''
linker = _HTMLDocstringLinker(self, where)
descr = parsed_docstring.to_html(linker, indent=indent,
directory=self._directory,
docindex=self.docindex,
context=where).strip()
if descr == '': return ' '
return descr
# [xx] Should this be defined by the APIDoc classes themselves??
def doc_kind(self, doc):
if isinstance(doc, ModuleDoc) and doc.is_package == True:
return 'Package'
elif (isinstance(doc, ModuleDoc) and
doc.canonical_name[0].startswith('script')):
return 'Script'
elif isinstance(doc, ModuleDoc):
return 'Module'
elif isinstance(doc, ClassDoc):
return 'Class'
elif isinstance(doc, ClassMethodDoc):
return 'Class Method'
elif isinstance(doc, StaticMethodDoc):
return 'Static Method'
elif isinstance(doc, RoutineDoc):
if isinstance(self.docindex.container(doc), ClassDoc):
return 'Method'
else:
return 'Function'
else:
return 'Variable'
def _doc_or_ancestor_is_private(self, api_doc):
name = api_doc.canonical_name
for i in range(len(name), 0, -1):
var_doc = self.docindex.get_vardoc(name[:i])
if var_doc is not None and var_doc.is_public == False:
return True
return False
class _HTMLDocstringLinker(epydoc.markup.DocstringLinker):
def __init__(self, htmlwriter, container):
self.htmlwriter = htmlwriter
self.docindex = htmlwriter.docindex
self.container = container
def translate_indexterm(self, indexterm):
key = self.htmlwriter._term_index_to_anchor(indexterm)
return ('<a name="%s"></a><i class="indexterm">%s</i>' %
(key, indexterm.to_html(self)))
def translate_identifier_xref(self, identifier, label=None):
# Pick a label for this xref.
if label is None: label = plaintext_to_html(identifier)
# Find the APIDoc for it (if it's available).
doc = self.docindex.find(identifier, self.container)
# Translate it into HTML.
if doc is None:
return '<code class="link">%s</code>' % label
else:
return self.htmlwriter.href(doc, label, 'link')
# [xx] Should this be added to the DocstringLinker interface???
def url_for(self, identifier):
if isinstance(identifier, (basestring, DottedName)):
doc = self.docindex.find(identifier, self.container)
if doc:
return self.htmlwriter.url(doc)
else:
# [xx] ignore if it's inside an import??
# Record that we failed to find it.
failed_xrefs = self.htmlwriter._failed_xrefs
context = self.container.canonical_name
failed_xrefs.setdefault(identifier,{})[context] = 1
elif isinstance(identifier, APIDoc):
return self.htmlwriter.url(identifier)
doc = identifier
else:
raise TypeError('Expected string or APIDoc')
| [
"simon.m.stewart@07704840-8298-11de-bf8c-fd130f914ac9"
] | simon.m.stewart@07704840-8298-11de-bf8c-fd130f914ac9 |
ebe86a3f28c5fdac92681b01d584d6339dcff179 | 06a989de84bd8582f83b120d2847280635934611 | /Chapter9_Classes/car.py | 8169d3fa158971a346bb55dac2474bc3215e1e32 | [] | no_license | HeydarO/Python-Crash-Course- | 34db842a47d671923885dd2f900f940d20fe653c | 7918e6b12f5782cd270649061106dc12fd076c45 | refs/heads/main | 2023-06-01T12:47:42.699208 | 2021-06-25T02:18:56 | 2021-06-25T02:18:56 | 379,965,608 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,242 | py | """A set of classes used to represent gas and electric cars."""
# """A simple attempt to represent a car."""
#
# def __init__(self, make, model, year):
# """Initialize attributes to describe a car."""
# self.make = make
# self.model = model
# self.year = year
# self.odometer_reading = 0
#
# def get_descriptive_name(self):
# """Return a neatly formatted descriptive name."""
# long_name = f"{self.year} {self.make} {self.model}"
# return long_name.title()
#
# def read_odometer(self):
# """Print a statement showing the car's mileage."""
# print(f"This car has {self.odometer_reading} miles on it.")
#
# my_new_car = Car('audi', 'a3', 2017)
# print(my_new_car.get_descriptive_name())
# my_new_car.read_odometer()
### Modifying an Attribute Value Directly
# class Car:
# """A simple attempt to represent a car."""
#
# def __init__(self, make, model, year):
# """Initialize attributes to describe a car."""
# self.make = make
# self.model = model
# self.year = year
# self.odometer_reading = 0
#
# def get_descriptive_name(self):
# """Return a neatly formatted descriptive name."""
# long_name = f"{self.year} {self.make} {self.model}"
# return long_name.title()
#
# def read_odometer(self):
# """Print a statement showing the car's mileage."""
# print(f"This car has {self.odometer_reading} miles on it.")
#
# my_new_car = Car('audi', 'a3', 2017)
# print(my_new_car.get_descriptive_name())
#
# my_new_car.odometer_reading = 23
# my_new_car.read_odometer()
### Modifying an Attribute's Value Through a method
# class Car:
# """A simple attempt to represent a car."""
#
# def __init__(self, make, model, year):
# """Initialize attributes to describe a car."""
# self.make = make
# self.model = model
# self.year = year
# self.odometer_reading = 0
#
# def get_descriptive_name(self):
# """Return a neatly formatted descriptive name."""
# long_name = f"{self.year} {self.make} {self.model}"
# return long_name.title()
#
# def read_odometer(self):
# """Print a statement showing the car's mileage."""
# print(f"This car has {self.odometer_reading} miles on it.")
#
# def update_odometer(self, mileage):
# """
# Set the odometer reading to the given value.
# Reject the change if it attempts to roll the odometer back.
# """
# if mileage >= self.odometer_reading:
# self.odometer_reading = mileage
# else:
# print("You can't roll back an odometer!")
#
# my_new_car = Car('audi', 'a3', 2017)
# print(my_new_car.get_descriptive_name())
#
# my_new_car.update_odometer(23)
# my_new_car.read_odometer()
### Incrementing an Attribute's Value Through a Method
class Car:
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometer_reading} miles on it.")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
# my_used_car = Car('toyota', 'LE Plus', 2015)
# print(my_used_car.get_descriptive_name())
#
# my_used_car.update_odometer(40_500)
# my_used_car.read_odometer()
#
# my_used_car.increment_odometer(100)
# my_used_car.read_odometer()
| [
"orujoh@amazon.com"
] | orujoh@amazon.com |
33c59a32b9c1ff091541a19ffbf8c8fde09c3bf7 | e0183b9ce2e4c6ca21f876feded8dd549c71b296 | /Business/authCode.py | 21e4e29b92439fde5cc0c864e8f288272586bac3 | [] | no_license | Hanlen520/my_Android_Ui_Automation | 845b96d9dc8d8432d33ca12590098fc397e80bf8 | b5b5af6b4a13ae3723160484e39d8d8d6e1d9e8b | refs/heads/master | 2020-04-02T13:08:52.508934 | 2018-09-04T05:47:16 | 2018-09-04T05:47:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 623 | py | # !/usr/bin/env python
# -*- coding:utf-8 -*-
# project name: Android_Ui_Automation
# author: "Lei Yong"
# creation time: 2018/1/10 下午6:34
# Email: leiyong711@163.com
import os
# 读取手机文件
def sms():
smsLog = os.popen('adb shell cat /sdcard/SMS/smsLog.txt').read()
return smsLog.split("验证码是")[1]
# 读取短信验证码
def msm():
global sm
x = 1
while x == 1:
try:
sm = sms()
break
except:
x = 1
os.popen('adb shell rm /sdcard/SMS/smsLog.txt')
return sm
if __name__ == '__main__':
print '验证码%s' % msm()
| [
"gaopan157@163.com"
] | gaopan157@163.com |
824160e655f63eb10931e65ddd484418ebbb734e | 7c0999d4877090301a5cc2da76ddf5a9a734467e | /Udacity_ML/P4-smartcab/smartcab/agent.py | 92a65475f96c936bb1817decef358bf67bed3521 | [] | no_license | jay56567/Machine-Learning | fec00d7aed1d34e07d115bcbc2e106a3bb787935 | 7a6d6ae367ec9acc54af534565abc445123a0b3b | refs/heads/master | 2020-03-27T08:30:26.723930 | 2017-04-25T21:32:15 | 2017-04-25T21:32:15 | 63,445,878 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,773 | py | import random
from environment import Agent, Environment
from planner import RoutePlanner
from simulator import Simulator
class LearningAgent(Agent):
"""An agent that learns to drive in the smartcab world."""
def __init__(self, env):
super(LearningAgent, self).__init__(env) # sets self.env = env, state = None, next_waypoint = None, and a default color
self.color = 'red' # override color
self.planner = RoutePlanner(self.env, self) # simple route planner to get next_waypoint
# TODO: Initialize any additional variables here
self.state = None
def reset(self, destination=None):
self.planner.route_to(destination)
# TODO: Prepare for a new trip; reset any variables here, if required
def update(self, t):
# Gather inputs
self.next_waypoint = self.planner.next_waypoint() # from route planner, also displayed by simulator
inputs = self.env.sense(self)
deadline = self.env.get_deadline(self)
# TODO: Update state
self.state = inputs
# TODO: Select action according to your policy
action = random.choice([None,'forward','left','right'])
if self.next_waypoint == 'left':
if inputs['light'] == 'red' or inputs['oncoming'] == 'forward' or inputs['oncoming'] == 'right':
action = None
if self.next_waypoint == 'right':
if inputs['light'] == 'red' and inputs['left'] == 'forward':
action = None
if self.next_waypoint == 'forward':
if inputs['light'] == 'red':
action = None
# Execute action and get reward
reward = self.env.act(self, action)
# TODO: Learn policy based on state, action, reward
print "LearningAgent.update(): deadline = {}, inputs = {}, action = {}, reward = {}".format(deadline, inputs, action, reward) # [debug]
def run():
"""Run the agent for a finite number of trials."""
# Set up environment and agent
e = Environment() # create environment (also adds some dummy traffic)
a = e.create_agent(LearningAgent) # create agent
e.set_primary_agent(a, enforce_deadline=True) # specify agent to track
# NOTE: You can set enforce_deadline=False while debugging to allow longer trials
# Now simulate it
sim = Simulator(e, update_delay=0.5, display=True) # create simulator (uses pygame when display=True, if available)
# NOTE: To speed up simulation, reduce update_delay and/or set display=False
sim.run(n_trials=100) # run for a specified number of trials
# NOTE: To quit midway, press Esc or close pygame window, or hit Ctrl+C on the command-line
if __name__ == '__main__':
run()
| [
"jay.jie.hou@gmail.com"
] | jay.jie.hou@gmail.com |
c3df0ac58a6da679590d7b4d309dd0b86190657c | 863a1f5091f1faad2beaf2a6037e3a5c0ebdc194 | /Backuper.glyphsPlugin/Contents/Resources/plugin.py | 8a21cdbee8b408df2b4ca9d675f6a38770426e11 | [] | no_license | schriftgestalt/Backuper | e65f08ec016770564131c05dbd888fe6841c6612 | 2b738600c4a8cb288184ae2c216bcfcbf64e266b | refs/heads/master | 2023-07-17T19:50:00.265070 | 2021-09-01T21:38:34 | 2021-09-01T21:38:34 | 109,949,694 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,699 | py | # encoding: utf-8
###########################################################################################################
#
#
# General Plugin
#
# Read the docs:
# https://github.com/schriftgestalt/GlyphsSDK/tree/master/Python%20Templates/General%20Plugin
#
#
###########################################################################################################
from __future__ import print_function
import objc
from GlyphsApp import *
from GlyphsApp.plugins import *
from Foundation import NSFileManager
import os
class Backuper(GeneralPlugin):
@objc.python_method
def start(self):
Glyphs.addCallback(self.doBackup_, DOCUMENTOPENED)
def doBackup_(self, sender):
document = sender.object()
if document.fileURL() is None:
return
importedVersion = document.valueForKey_("importedVersion")
if importedVersion != None and int(Glyphs.buildNumber) > int(importedVersion):
documentPath = document.fileURL().path()
fileName = os.path.basename(documentPath)
bachupFolder = os.path.join(os.path.dirname(documentPath), "Backup")
bachupPath = os.path.join(bachupFolder, importedVersion + "_" + fileName)
fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath_isDirectory_(bachupFolder, None) == (False, False):
if not fileManager.createDirectoryAtPath_withIntermediateDirectories_attributes_error_(bachupFolder, True, None, None):
print("Could not make backup folder")
if fileManager.isReadableFileAtPath_(documentPath):
NSFileManager.defaultManager().copyItemAtPath_toPath_error_(documentPath, bachupPath, None)
@objc.python_method
def __file__(self):
"""Please leave this method unchanged"""
return __file__
| [
"georg.seifert@mac.com"
] | georg.seifert@mac.com |
a3c76c8e21fd1819784a3c1f6c2afc568674b8a5 | d9f89be08b2e4e68c9e31f59f00983a826b6eeb6 | /music_shop_select.py | d9e55a8de3f1f2b8fadaf47b009bd600f1f335be | [] | no_license | amikhalenko/python_learning | 38eb828a2c10541e163db892e7040fdde4bdab5e | b334303cfea18455d08152f13ebe6b480a79cc22 | refs/heads/master | 2023-05-02T23:14:13.029282 | 2021-05-22T23:46:57 | 2021-05-22T23:46:57 | 289,753,752 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 943 | py | import sqlalchemy as sqlalchemy
engine = sqlalchemy.create_engine('postgresql://music:music@127.0.0.1:5432/music_shop')
engine
connection = engine.connect()
print(engine.table_names())
sel = connection.execute("""SELECT Album_name, Album_year FROM Album
WHERE Album_year = 2018;""").fetchall()
print(sel)
sel = connection.execute("""SELECT Track_name, Duration FROM Track
ORDER BY Duration DESC
LIMIT 1;""").fetchall()
print(sel)
sel = connection.execute("""SELECT Track_name FROM Track
WHERE Duration >=3.30
;""").fetchall()
print(sel)
sel = connection.execute("""SELECT Collection_Name FROM Collection
WHERE Collection_year BETWEEN 2018 AND 2020;""").fetchall()
print(sel)
sel = connection.execute("""SELECT Name_artist FROM Artist
WHERE Name_artist NOT LIKE '%% %%';""").fetchall()
print(sel)
sel = connection.execute("""SELECT Track_name FROM Track
WHERE Track_name LIKE '%% My %%';""").fetchall()
print(sel) | [
"noreply@github.com"
] | noreply@github.com |
ac987b204cf9dec2983df1a53e9a131e9324e87f | cf2018bc93372768d8da14486b646620754f705e | /feature_selection.py | e5a809f5318c752af0e1058f5143c66ba4b88ab1 | [] | no_license | kudeore/docker_airfair_prediction_Flask | 31570958fc0a31d4353c566fb4be3da1de721347 | 8b83ff70296dee912cb1e505c932b84fc0958398 | refs/heads/main | 2023-06-17T18:26:12.564051 | 2021-07-14T16:50:07 | 2021-07-14T16:50:07 | 386,002,186 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,612 | py | #!/usr/bin/env python
# coding: utf-8
# In[36]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import Preprocessing
# In[37]:
df = pd.read_excel(r"data\Data_Train.xlsx")
# In[38]:
pd.set_option('display.max_columns', None)
# In[39]:
df = Preprocessing.preprocessing_datetime(df)
# In[40]:
df = Preprocessing.preposses_encoding(df)
# In[41]:
df.head()
# In[42]:
#selct the best feature by using sklearn Extra tree regressor
#first separate dependent and independen features
# In[43]:
X = df.drop(["Price"], axis = 1)
# In[49]:
X = X.fillna(0)
# In[46]:
Y = df["Price"]
# In[70]:
from sklearn.linear_model import LassoCV
from sklearn.preprocessing import StandardScaler
# In[71]:
Sc = StandardScaler()
# In[72]:
X= Sc.fit_transform(X)
# In[91]:
lasso = LassoCV().fit(X, Y)
importance = np.abs(lasso.coef_)
# In[92]:
#importance = np.sort(importance)
#importance
# In[115]:
from sklearn.feature_selection import SelectFromModel
from time import time
threshold = np.sort(importance)[-20] + 0.01
tic = time()
sfm = SelectFromModel(lasso, threshold=threshold).fit(X, Y)
toc = time()
print(threshold)
# In[116]:
features = df.drop(["Price"],axis=1).columns
# In[117]:
plt.figure(figsize= (16,10))
sns.barplot(x=importance, y=features)
# In[118]:
selected_features= features[sfm.get_support()]
# In[121]:
print(len(selected_features), len(features))
# In[126]:
selected_features
# In[130]:
features
# In[141]:
df1 = df[selected_features]
# In[ ]:
# In[ ]:
| [
"noreply@github.com"
] | noreply@github.com |
cc9cc185267a71d20dc8291c5dafe6bf0b1432db | 82cce8d146d20f89ac9f42521e904dff9307cc4b | /utils/gen-brownian-schedule.py | 12609f20389a030707f5f76f69130f746aa1e54e | [] | no_license | anirudhSK/cell-codel | a667fbeebdd5ddd15328d3334e9c87453ade838b | 9a5d3596f6e9f99f4689184ef048bdfd58918cc3 | refs/heads/master | 2021-01-22T00:58:31.813877 | 2013-09-05T18:21:34 | 2013-09-05T18:21:34 | 5,831,335 | 4 | 1 | null | null | null | null | UTF-8 | Python | false | false | 851 | py | import sys
import random
if (len(sys.argv) < 3 ) :
print "Usage :",sys.argv[0]," <sigma in pkts per sec> <duration in sec>"
exit()
sigma=float(sys.argv[1])
duration=int(sys.argv[2])
RATE_MAX=1250 # in pkts per second
''' rate evolution using Brownian Motion '''
def rate(prev_rate):
tmp_rate=0
''' do repeated sampling till it falls within our range '''
while (tmp_rate <=0 or tmp_rate >= RATE_MAX) :
tmp_rate=prev_rate + random.gauss(0,sigma)
return tmp_rate
''' schedule generation '''
prev_rate=0
for i in range (0,duration): # run for 'duration' seconds
cur_rate=rate(prev_rate)# get rate using Brownian motion
delta=1000/cur_rate; # compute pkt delta in ms
t=i*1000 # convert bin into ms
while (t < (i+1)*1000) :# iterate over bin
print int(round(t))
t=t+delta;
prev_rate=cur_rate
| [
"anirudh@Sim-Box.(none)"
] | anirudh@Sim-Box.(none) |
dfea669c4519269a2654b492fe8a992552b69e3a | 010279e2ba272d09e9d2c4e903722e5faba2cf7a | /contrib/python/scipy/py2/scipy/optimize/tests/test__basinhopping.py | 84deeb847253a4b53ed032c0aaecd9b4a43171a0 | [
"Python-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Qhull",
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | catboost/catboost | 854c1a1f439a96f1ae6b48e16644be20aa04dba2 | f5042e35b945aded77b23470ead62d7eacefde92 | refs/heads/master | 2023-09-01T12:14:14.174108 | 2023-09-01T10:01:01 | 2023-09-01T10:22:12 | 97,556,265 | 8,012 | 1,425 | Apache-2.0 | 2023-09-11T03:32:32 | 2017-07-18T05:29:04 | Python | UTF-8 | Python | false | false | 15,398 | py | """
Unit tests for the basin hopping global minimization algorithm.
"""
from __future__ import division, print_function, absolute_import
import copy
from numpy.testing import assert_almost_equal, assert_equal, assert_
from pytest import raises as assert_raises
import numpy as np
from numpy import cos, sin
from scipy.optimize import basinhopping, OptimizeResult
from scipy.optimize._basinhopping import (
Storage, RandomDisplacement, Metropolis, AdaptiveStepsize)
def func1d(x):
f = cos(14.5 * x - 0.3) + (x + 0.2) * x
df = np.array(-14.5 * sin(14.5 * x - 0.3) + 2. * x + 0.2)
return f, df
def func2d_nograd(x):
f = cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] + 0.2) * x[0]
return f
def func2d(x):
f = cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] + 0.2) * x[0]
df = np.zeros(2)
df[0] = -14.5 * sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2
df[1] = 2. * x[1] + 0.2
return f, df
def func2d_easyderiv(x):
f = 2.0*x[0]**2 + 2.0*x[0]*x[1] + 2.0*x[1]**2 - 6.0*x[0]
df = np.zeros(2)
df[0] = 4.0*x[0] + 2.0*x[1] - 6.0
df[1] = 2.0*x[0] + 4.0*x[1]
return f, df
class MyTakeStep1(RandomDisplacement):
"""use a copy of displace, but have it set a special parameter to
make sure it's actually being used."""
def __init__(self):
self.been_called = False
super(MyTakeStep1, self).__init__()
def __call__(self, x):
self.been_called = True
return super(MyTakeStep1, self).__call__(x)
def myTakeStep2(x):
"""redo RandomDisplacement in function form without the attribute stepsize
to make sure everything still works ok
"""
s = 0.5
x += np.random.uniform(-s, s, np.shape(x))
return x
class MyAcceptTest(object):
"""pass a custom accept test
This does nothing but make sure it's being used and ensure all the
possible return values are accepted
"""
def __init__(self):
self.been_called = False
self.ncalls = 0
self.testres = [False, 'force accept', True, np.bool_(True),
np.bool_(False), [], {}, 0, 1]
def __call__(self, **kwargs):
self.been_called = True
self.ncalls += 1
if self.ncalls - 1 < len(self.testres):
return self.testres[self.ncalls - 1]
else:
return True
class MyCallBack(object):
"""pass a custom callback function
This makes sure it's being used. It also returns True after 10
steps to ensure that it's stopping early.
"""
def __init__(self):
self.been_called = False
self.ncalls = 0
def __call__(self, x, f, accepted):
self.been_called = True
self.ncalls += 1
if self.ncalls == 10:
return True
class TestBasinHopping(object):
def setup_method(self):
""" Tests setup.
Run tests based on the 1-D and 2-D functions described above.
"""
self.x0 = (1.0, [1.0, 1.0])
self.sol = (-0.195, np.array([-0.195, -0.1]))
self.tol = 3 # number of decimal places
self.niter = 100
self.disp = False
# fix random seed
np.random.seed(1234)
self.kwargs = {"method": "L-BFGS-B", "jac": True}
self.kwargs_nograd = {"method": "L-BFGS-B"}
def test_TypeError(self):
# test the TypeErrors are raised on bad input
i = 1
# if take_step is passed, it must be callable
assert_raises(TypeError, basinhopping, func2d, self.x0[i],
take_step=1)
# if accept_test is passed, it must be callable
assert_raises(TypeError, basinhopping, func2d, self.x0[i],
accept_test=1)
def test_1d_grad(self):
# test 1d minimizations with gradient
i = 0
res = basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs,
niter=self.niter, disp=self.disp)
assert_almost_equal(res.x, self.sol[i], self.tol)
def test_2d(self):
# test 2d minimizations with gradient
i = 1
res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
niter=self.niter, disp=self.disp)
assert_almost_equal(res.x, self.sol[i], self.tol)
assert_(res.nfev > 0)
def test_njev(self):
# test njev is returned correctly
i = 1
minimizer_kwargs = self.kwargs.copy()
# L-BFGS-B doesn't use njev, but BFGS does
minimizer_kwargs["method"] = "BFGS"
res = basinhopping(func2d, self.x0[i],
minimizer_kwargs=minimizer_kwargs, niter=self.niter,
disp=self.disp)
assert_(res.nfev > 0)
assert_equal(res.nfev, res.njev)
def test_jac(self):
# test jacobian returned
minimizer_kwargs = self.kwargs.copy()
# BFGS returns a Jacobian
minimizer_kwargs["method"] = "BFGS"
res = basinhopping(func2d_easyderiv, [0.0, 0.0],
minimizer_kwargs=minimizer_kwargs, niter=self.niter,
disp=self.disp)
assert_(hasattr(res.lowest_optimization_result, "jac"))
# in this case, the jacobian is just [df/dx, df/dy]
_, jacobian = func2d_easyderiv(res.x)
assert_almost_equal(res.lowest_optimization_result.jac, jacobian,
self.tol)
def test_2d_nograd(self):
# test 2d minimizations without gradient
i = 1
res = basinhopping(func2d_nograd, self.x0[i],
minimizer_kwargs=self.kwargs_nograd,
niter=self.niter, disp=self.disp)
assert_almost_equal(res.x, self.sol[i], self.tol)
def test_all_minimizers(self):
# test 2d minimizations with gradient. Nelder-Mead, Powell and COBYLA
# don't accept jac=True, so aren't included here.
i = 1
methods = ['CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'SLSQP']
minimizer_kwargs = copy.copy(self.kwargs)
for method in methods:
minimizer_kwargs["method"] = method
res = basinhopping(func2d, self.x0[i],
minimizer_kwargs=minimizer_kwargs,
niter=self.niter, disp=self.disp)
assert_almost_equal(res.x, self.sol[i], self.tol)
def test_all_nograd_minimizers(self):
# test 2d minimizations without gradient. Newton-CG requires jac=True,
# so not included here.
i = 1
methods = ['CG', 'BFGS', 'L-BFGS-B', 'TNC', 'SLSQP',
'Nelder-Mead', 'Powell', 'COBYLA']
minimizer_kwargs = copy.copy(self.kwargs_nograd)
for method in methods:
minimizer_kwargs["method"] = method
res = basinhopping(func2d_nograd, self.x0[i],
minimizer_kwargs=minimizer_kwargs,
niter=self.niter, disp=self.disp)
tol = self.tol
if method == 'COBYLA':
tol = 2
assert_almost_equal(res.x, self.sol[i], decimal=tol)
def test_pass_takestep(self):
# test that passing a custom takestep works
# also test that the stepsize is being adjusted
takestep = MyTakeStep1()
initial_step_size = takestep.stepsize
i = 1
res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
niter=self.niter, disp=self.disp,
take_step=takestep)
assert_almost_equal(res.x, self.sol[i], self.tol)
assert_(takestep.been_called)
# make sure that the built in adaptive step size has been used
assert_(initial_step_size != takestep.stepsize)
def test_pass_simple_takestep(self):
# test that passing a custom takestep without attribute stepsize
takestep = myTakeStep2
i = 1
res = basinhopping(func2d_nograd, self.x0[i],
minimizer_kwargs=self.kwargs_nograd,
niter=self.niter, disp=self.disp,
take_step=takestep)
assert_almost_equal(res.x, self.sol[i], self.tol)
def test_pass_accept_test(self):
# test passing a custom accept test
# makes sure it's being used and ensures all the possible return values
# are accepted.
accept_test = MyAcceptTest()
i = 1
# there's no point in running it more than a few steps.
basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
niter=10, disp=self.disp, accept_test=accept_test)
assert_(accept_test.been_called)
def test_pass_callback(self):
# test passing a custom callback function
# This makes sure it's being used. It also returns True after 10 steps
# to ensure that it's stopping early.
callback = MyCallBack()
i = 1
# there's no point in running it more than a few steps.
res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
niter=30, disp=self.disp, callback=callback)
assert_(callback.been_called)
assert_("callback" in res.message[0])
assert_equal(res.nit, 10)
def test_minimizer_fail(self):
# test if a minimizer fails
i = 1
self.kwargs["options"] = dict(maxiter=0)
self.niter = 10
res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
niter=self.niter, disp=self.disp)
# the number of failed minimizations should be the number of
# iterations + 1
assert_equal(res.nit + 1, res.minimization_failures)
def test_niter_zero(self):
# gh5915, what happens if you call basinhopping with niter=0
i = 0
basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs,
niter=0, disp=self.disp)
def test_seed_reproducibility(self):
# seed should ensure reproducibility between runs
minimizer_kwargs = {"method": "L-BFGS-B", "jac": True}
f_1 = []
def callback(x, f, accepted):
f_1.append(f)
basinhopping(func2d, [1.0, 1.0], minimizer_kwargs=minimizer_kwargs,
niter=10, callback=callback, seed=10)
f_2 = []
def callback2(x, f, accepted):
f_2.append(f)
basinhopping(func2d, [1.0, 1.0], minimizer_kwargs=minimizer_kwargs,
niter=10, callback=callback2, seed=10)
assert_equal(np.array(f_1), np.array(f_2))
def test_monotonic_basin_hopping(self):
# test 1d minimizations with gradient and T=0
i = 0
res = basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs,
niter=self.niter, disp=self.disp, T=0)
assert_almost_equal(res.x, self.sol[i], self.tol)
class Test_Storage(object):
def setup_method(self):
self.x0 = np.array(1)
self.f0 = 0
minres = OptimizeResult()
minres.x = self.x0
minres.fun = self.f0
self.storage = Storage(minres)
def test_higher_f_rejected(self):
new_minres = OptimizeResult()
new_minres.x = self.x0 + 1
new_minres.fun = self.f0 + 1
ret = self.storage.update(new_minres)
minres = self.storage.get_lowest()
assert_equal(self.x0, minres.x)
assert_equal(self.f0, minres.fun)
assert_(not ret)
def test_lower_f_accepted(self):
new_minres = OptimizeResult()
new_minres.x = self.x0 + 1
new_minres.fun = self.f0 - 1
ret = self.storage.update(new_minres)
minres = self.storage.get_lowest()
assert_(self.x0 != minres.x)
assert_(self.f0 != minres.fun)
assert_(ret)
class Test_RandomDisplacement(object):
def setup_method(self):
self.stepsize = 1.0
self.displace = RandomDisplacement(stepsize=self.stepsize)
self.N = 300000
self.x0 = np.zeros([self.N])
def test_random(self):
# the mean should be 0
# the variance should be (2*stepsize)**2 / 12
# note these tests are random, they will fail from time to time
x = self.displace(self.x0)
v = (2. * self.stepsize) ** 2 / 12
assert_almost_equal(np.mean(x), 0., 1)
assert_almost_equal(np.var(x), v, 1)
class Test_Metropolis(object):
def setup_method(self):
self.T = 2.
self.met = Metropolis(self.T)
def test_boolean_return(self):
# the return must be a bool. else an error will be raised in
# basinhopping
ret = self.met(f_new=0., f_old=1.)
assert isinstance(ret, bool)
def test_lower_f_accepted(self):
assert_(self.met(f_new=0., f_old=1.))
def test_KeyError(self):
# should raise KeyError if kwargs f_old or f_new is not passed
assert_raises(KeyError, self.met, f_old=1.)
assert_raises(KeyError, self.met, f_new=1.)
def test_accept(self):
# test that steps are randomly accepted for f_new > f_old
one_accept = False
one_reject = False
for i in range(1000):
if one_accept and one_reject:
break
ret = self.met(f_new=1., f_old=0.5)
if ret:
one_accept = True
else:
one_reject = True
assert_(one_accept)
assert_(one_reject)
def test_GH7495(self):
# an overflow in exp was producing a RuntimeWarning
# create own object here in case someone changes self.T
met = Metropolis(2)
with np.errstate(over='raise'):
met.accept_reject(0, 2000)
class Test_AdaptiveStepsize(object):
def setup_method(self):
self.stepsize = 1.
self.ts = RandomDisplacement(stepsize=self.stepsize)
self.target_accept_rate = 0.5
self.takestep = AdaptiveStepsize(takestep=self.ts, verbose=False,
accept_rate=self.target_accept_rate)
def test_adaptive_increase(self):
# if few steps are rejected, the stepsize should increase
x = 0.
self.takestep(x)
self.takestep.report(False)
for i in range(self.takestep.interval):
self.takestep(x)
self.takestep.report(True)
assert_(self.ts.stepsize > self.stepsize)
def test_adaptive_decrease(self):
# if few steps are rejected, the stepsize should increase
x = 0.
self.takestep(x)
self.takestep.report(True)
for i in range(self.takestep.interval):
self.takestep(x)
self.takestep.report(False)
assert_(self.ts.stepsize < self.stepsize)
def test_all_accepted(self):
# test that everything works OK if all steps were accepted
x = 0.
for i in range(self.takestep.interval + 1):
self.takestep(x)
self.takestep.report(True)
assert_(self.ts.stepsize > self.stepsize)
def test_all_rejected(self):
# test that everything works OK if all steps were rejected
x = 0.
for i in range(self.takestep.interval + 1):
self.takestep(x)
self.takestep.report(False)
assert_(self.ts.stepsize < self.stepsize)
| [
"arcadia-devtools@yandex-team.ru"
] | arcadia-devtools@yandex-team.ru |
7e74fa3054af9e5c296cb668f23cc4c208dcaf83 | 98b63e3dc79c75048163512c3d1b71d4b6987493 | /tensorflow/python/distribute/multi_process_runner.py | 95841b8ee902049af7e05da8109e06d2221e1413 | [
"Apache-2.0"
] | permissive | galeone/tensorflow | 11a4e4a3f42f4f61a65b432c429ace00401c9cc4 | 1b6f13331f4d8e7fccc66bfeb0b066e77a2b7206 | refs/heads/master | 2022-11-13T11:56:56.143276 | 2020-11-10T14:35:01 | 2020-11-10T14:35:01 | 310,642,488 | 21 | 12 | Apache-2.0 | 2020-11-06T16:01:03 | 2020-11-06T16:01:02 | null | UTF-8 | Python | false | false | 55,559 | py | # Lint as: python3
# Copyright 2019 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.
# ==============================================================================
"""Multi-process runner for testing purpose."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import contextlib
import json
import os
import signal
import sys
import threading
import time
import unittest
import weakref
from absl import logging
import six
from six.moves import queue as Queue
from tensorflow.python import tf2
from tensorflow.python.compat import v2_compat
from tensorflow.python.distribute import multi_process_lib
from tensorflow.python.eager import context
from tensorflow.python.util.tf_export import tf_export
multiprocessing = multi_process_lib.multiprocessing
# pylint: disable=g-import-not-at-top
try:
# `faulthandler` is not available in py2.
import faulthandler
except ImportError:
faulthandler = None
# TODO(b/150264776): Remove after resolving CI issue.
try:
import dill
except ImportError:
dill = None
# TODO(b/150264776): Remove after resolving CI issue.
try:
import tblib.pickling_support
# For pickling traceback objects.
tblib.pickling_support.install()
except ImportError:
pass
# _ProcessStatusInfo contains process status information. When is_successful
# attribute is True, the subprocess has ended successfully, or if False, the
# exception stack trace info is stored in exc_info to pass on to parent process
# to be re-raised.
_ProcessStatusInfo = collections.namedtuple(
'_ProcessStatusInfo',
['task_type', 'task_id', 'is_successful', 'exc_info', 'return_value'])
# Information returned from a successful MultiProcessRunner run.
MultiProcessRunnerResult = collections.namedtuple('MultiProcessRunnerResult',
['return_value', 'stdout'])
TestEnvironment = collections.namedtuple('TestEnvironment', [
'task_type', 'task_id', 'cluster_spec', 'rpc_layer', 'grpc_fail_fast',
'v2_enabled', 'executing_eagerly'
])
# Resources for communication between worker processes and the main process.
#
# `process_status_queue` is used by `multi_process_runner` internally for
# communication from subprocesses to the parent process for whether it's been
# successful, and if not what the error stack trace is.
# `parent_to_sub_queue` is used for communications from parent to subprocess.
# Currently this is only used to terminate subprocesses.
# TODO(rchao): Remove this once subprocess is terminated by SIGKILL.
# `streaming_pipe_w` is to stream stdout and stderr from subprocesses to parent
# process.
# `barrier` is a barrier for the party of all subprocesses.
Resources = collections.namedtuple('Resources', [
'process_status_queue', 'parent_to_sub_queue', 'streaming_pipe_w', 'barrier'
])
# Default time out sec is selected so that it's handled before the default
# "medium" timeout of the test runs.
_DEFAULT_TIMEOUT_SEC = 200
# The timeout in seconds to wait to force kill a child process. When a child
# process times out we first try to SIGTERM it so that it has a chance to dump
# stacktraces. However dumping stacktrace can take a long time.
_FORCE_KILL_WAIT_SEC = 30
class MultiProcessRunner(object):
"""A utility class to start multiple processes to simulate a cluster.
We need to use multiple processes to simulate a cluster in TF 2.0 tests
because TF 2.0 has some process-global data structures that have to be
separated by processes. We also need child processes to test out our fault
tolerance because shutting down a standard TensorFlow server within its
process is not supported.
Note: the main test program that uses this runner class must run main program
via `test_main` defined in this file. Using this runner in non-test binaries
is not supported yet.
This class is not thread-safe. Child processes will inherit TF2 behavior flag.
"""
def __init__(self,
fn,
cluster_spec,
rpc_layer=None,
max_run_time=None,
grpc_fail_fast=None,
stream_output=True,
return_output=False,
use_dill_for_args=True,
daemon=False,
dependence_on_chief=True,
auto_restart=False,
args=None,
kwargs=None):
"""Instantiation of a `MultiProcessRunner`.
Args:
fn: Function to be run on child processes. This will be run on processes
for all task types.
cluster_spec: Dict for cluster spec. The utility function
`tf.__internal__.distribute.multi_process_runner.create_cluster_spec`
can be conveniently used to create such dict. The following is an
example of cluster with three workers and two ps's.
{"worker": ["worker0.example.com:2222",
"worker1.example.com:2222",
"worker2.example.com:2222"],
"ps": ["ps0.example.com:2222",
"ps1.example.com:2222"]}
rpc_layer: RPC layer to use. Default value is 'grpc'.
max_run_time: `None` or integer. If not `None`, child processes are forced
to exit at approximately this many seconds after this utility is called.
We achieve this through `signal.alarm()` api. Note that this is best
effort at Python level since Python signal handler does not get executed
when it runs lower level C/C++ code. So it can be delayed for
arbitrarily long time. If any of the child process is still running when
`max_run_time` is up, they will be force-terminated and an
`UnexpectedSubprocessExitError` may be raised. If `None`, child
processes are not forced to exit.
grpc_fail_fast: Whether GRPC connection between processes should fail
without retrying. Defaults to None, in which case the environment
variable is not explicitly set.
stream_output: True if the output/error from the subprocesses should be
streamed to be printed in parent process' log. Defaults to True.
return_output: If True, the output/error from the subprocesses should be
collected to be attached to the resulting namedtuple returned from
`join()`. The list of output can be retrieved via `stdout` attribute.
Defaults to False.
use_dill_for_args: Whether to use dill to pickle `args` and `kwargs`. dill
can pickle more objects, but doesn't work with types in
`multiprocessing` library like `Mutex`.
daemon: Whether to start processes as daemons.
dependence_on_chief: Whether to terminates the cluster if the chief exits.
If auto_restart is True, it only terminates the cluster if the chief
exits with a zero exit code.
auto_restart: Whether to automatically restart processes that exit with
non-zero exit code.
args: Positional arguments to be sent to `fn` run on subprocesses.
kwargs: Keyword arguments to be sent to `fn` run on subprocesses.
Raises:
RuntimeError: if `multi_process_runner.test_main()` is not called.
ValueError: if there are more than one chief in the `cluster_spec`.
"""
assert cluster_spec is not None
if 'chief' in cluster_spec and len(cluster_spec['chief']) > 1:
raise ValueError('If chief exists in the cluster, there must be at most '
'one chief. Current `cluster_spec` has {} chiefs.'
.format(len(cluster_spec['chief'])))
if not multi_process_lib.initialized():
raise NotInitializedError(
'`multi_process_runner` is not initialized. '
'Please call `tf.__internal__.distribute.multi_process_runner.'
'test_main()` within `if __name__ == \'__main__\':` block '
'in your python module to properly initialize '
'`multi_process_runner`.')
if not callable(fn):
raise ValueError('fn is not a callable')
self._fn = fn
self._cluster_spec = cluster_spec
self._rpc_layer = rpc_layer or 'grpc'
self._max_run_time = max_run_time
self._grpc_fail_fast = grpc_fail_fast
self._stream_output = stream_output
# TODO(rchao): Revisit return_output argument to consider other solution.
self._return_output = return_output
self._dependence_on_chief = dependence_on_chief
self._use_dill_for_args = use_dill_for_args
self._daemon = daemon
self._auto_restart = auto_restart
self._args = args or ()
self._kwargs = kwargs or {}
# Child processes should have the same v2 and eager behavior.
self._v2_enabled = tf2.enabled()
self._executing_eagerly = context.executing_eagerly()
self._joined = False
self._process_lock = threading.Lock()
# Guarded by self._process_lock.
self._processes = {}
# Record which processes are terminated. Due to a bug in Python<3.7,
# terminated processes return 255 exit code, which should cause an exception
# in join().
# https://bugs.python.org/issue30589
# Guarded by self._process_lock.
self._terminated = set()
self._reading_threads = []
self._manager = manager()
self._process_status_queue = self._manager.Queue()
self._parent_to_sub_queue = self._manager.Queue()
parties = sum(len(addresses) for addresses in self._cluster_spec.values())
self._barrier = self._manager.Barrier(parties)
# We use a queue to collect outputs from worker processes since it's thread
# safe.
self._streaming_queue = self._manager.Queue()
self._watchdog_thread = None
def set_args(self, args=None, kwargs=None):
self._args = args or self._args
self._kwargs = kwargs or self._kwargs
def _continuously_readline_from_sub(self, pipe_r, task_type, task_id):
"""Function to continuously read lines from subprocesses."""
with os.fdopen(pipe_r.fileno(), 'r', closefd=False) as reader:
for line in reader:
task_string = '[{}-{}]:'.format(task_type, task_id)
formatted_line = '{} {}'.format(task_string.ljust(14), line)
if self._stream_output:
# TODO(rchao): Use a lock here to ensure the printed lines are not
# broken.
print(formatted_line, end='', flush=True)
if self._return_output:
self._streaming_queue.put(formatted_line)
def _start_subprocess_and_reading_thread(self,
task_type,
task_id,
cluster_spec=None,
fn=None,
args=None,
kwargs=None):
"""Start a subprocess and a thread the reads lines from the subprocess."""
if dill is None:
raise unittest.SkipTest(
'TODO(b/150264776): Resolve dependency issue in CI')
test_env = TestEnvironment(
task_type=task_type,
task_id=task_id,
cluster_spec=cluster_spec or self._cluster_spec,
rpc_layer=self._rpc_layer,
grpc_fail_fast=self._grpc_fail_fast,
v2_enabled=self._v2_enabled,
executing_eagerly=self._executing_eagerly,
)
pipe_r, pipe_w = multiprocessing.Pipe(duplex=False)
resources = Resources(
process_status_queue=self._process_status_queue,
parent_to_sub_queue=self._parent_to_sub_queue,
streaming_pipe_w=pipe_w,
barrier=self._barrier,
)
if fn is None:
fn, args, kwargs = self._fn, self._args, self._kwargs
# Always use dill to pickle fn so that we support more callable
# types, e.g. lambda.
fn = dill.dumps(fn, dill.HIGHEST_PROTOCOL)
if self._use_dill_for_args:
args = dill.dumps(args, dill.HIGHEST_PROTOCOL)
kwargs = dill.dumps(kwargs, dill.HIGHEST_PROTOCOL)
p = _Process(
test_env=test_env,
target=_ProcFunc(),
args=(resources, test_env, fn, args, kwargs, self._use_dill_for_args),
daemon=self._daemon)
p.start()
self._processes[(task_type, task_id)] = p
self._terminated.discard((task_type, task_id))
# For each subprocess, we dedicate a thread continuously reading lines
# from them.
thread = threading.Thread( # pylint: disable=unexpected-keyword-arg
target=self._continuously_readline_from_sub,
args=(pipe_r, task_type, task_id))
thread.start()
self._reading_threads.append(thread)
if self._watchdog_thread is None or not self._watchdog_thread.is_alive():
self._watchdog_thread = threading.Thread(target=self._process_watchdog)
self._watchdog_thread.start()
def start(self):
"""Starts processes, one for each task in `cluster_spec`.
Note that this is best effort by the applicable multiprocessing library,
and it may take up to seconds for a subprocess to be successfully started.
"""
with self._process_lock:
if self._processes:
raise ValueError('MultiProcessRunner already started.')
if self._joined:
raise ValueError('cannot start new processes after'
'MultiProcessRunner.join() is called')
for task_type, addresses in self._cluster_spec.items():
for task_id, _ in enumerate(addresses):
self._start_subprocess_and_reading_thread(task_type, task_id)
# TODO(rchao): Remove the need of using SIGALRM if possible. At this time,
# without this the tests become very flaky.
if self._max_run_time is not None:
def handler(signum, frame):
del signum, frame
self.terminate_all()
signal.signal(signal.SIGALRM, handler)
signal.alarm(self._max_run_time)
def start_in_process_as(self, as_task_type, as_task_id):
"""Start the processes, with the specified task run in main process.
This is similar to `start()` except that the task with task_type
`as_task_type` and task_id `as_task_id` is run in the main process.
This method is particularly useful when debugging tool such as `pdb` is
needed in some specific task. Note that since this method is blocking until
that specific task exits, additional actions would need a thread to be
called:
```python
def fn():
# user code to be run
import pdb; pdb.set_trace()
def follow_ups():
time.sleep(5)
mpr.start_single_process(
task_type='evaluator',
task_id=0)
mpr = multi_process_runner.MultiProcessRunner(
fn,
multi_worker_test_base.create_cluster_spec(
has_chief=True, num_workers=1))
threading.Thread(target=follow_ups).start()
mpr.start_in_process_as(as_task_type='chief', as_task_id=0)
mpr.join()
```
Note that if `return_output=True`, the logs/stdout by task
run by the main process is not available in result.stdout.
Args:
as_task_type: The task type to be run in the main process.
as_task_id: The task id to be run in the main process.
"""
if self._processes:
raise ValueError('MultiProcessRunner already started.')
with self._process_lock:
if self._joined:
raise ValueError('cannot start new processes after'
'MultiProcessRunner.join() is called')
for task_type, addresses in self._cluster_spec.items():
for task_id, _ in enumerate(addresses):
if not (task_type == as_task_type and task_id == as_task_id):
self._start_subprocess_and_reading_thread(task_type, task_id)
_set_tf_config(as_task_type, as_task_id, self._cluster_spec,
self._rpc_layer)
self._fn(*self._args, **self._kwargs)
def start_single_process(self,
task_type,
task_id,
cluster_spec=None,
fn=None,
args=None,
kwargs=None):
"""Starts a single process.
This starts a process in the cluster with the task type, task id, and the
process function (`fn`). If process function is `None`, the function
provided at `__init__` will be used. If `cluster_spec` is `None`, the
cluster spec provided at `__init__` will be used.
TODO(rchao): It is meant that all subprocesses will be updated with the new
cluster spec, but this has yet to be implemented. At this time only the
newly started subprocess picks up this updated cluster spec.
Args:
task_type: The task type.
task_id: The task id.
cluster_spec: The cluster spec to be used on the newly started
process. If `None`, the cluster spec provided at `__init__` will be
used.
fn: The process function to be run on the newly started
process. If specified, specify `args` and `kwargs` as well. If `None`,
the function provided at `__init__` will be used.
args: Optional positional arguments to be supplied in `fn`.
kwargs: Optional keyword arguments to be supplied in `fn`.
"""
with self._process_lock:
if self._joined:
raise ValueError('cannot start new processes after'
'MultiProcessRunner.join() is called')
self._start_subprocess_and_reading_thread(
task_type,
task_id,
cluster_spec=cluster_spec,
fn=fn,
args=args or (),
kwargs=kwargs or {})
def _queue_to_list(self, queue_to_convert):
"""Convert `queue.Queue` to `list`."""
list_to_return = []
# Calling `queue.empty()` is not reliable.
while True:
try:
list_to_return.append(queue_to_convert.get(block=False))
except Queue.Empty:
break
return list_to_return
def _get_process_statuses(self):
# One worker may have multiple statuses. We only keep the last one.
statuses = {}
for status in self._queue_to_list(self._process_status_queue):
statuses[(status.task_type, status.task_id)] = status
return statuses
def get_process_id(self, task_type, task_id):
"""Returns the subprocess id given the task type and task id."""
with self._process_lock:
p = self._processes.get((task_type, task_id), None)
return p.pid if p else None
def get_process_exit_code(self, task_type, task_id):
"""Returns the subprocess exit code given the task type and task id.
Args:
task_type: The task type.
task_id: The task id.
Returns:
The subprocess exit code; `None` if the subprocess has not exited yet.
Raises:
KeyError: If the corresponding subprocess is not found with `task_type`
and `task_id`.
"""
with self._process_lock:
p = self._processes[(task_type, task_id)]
return p.exitcode if p else None
def process_exists(self, task_type, task_id):
"""Returns whether the subprocess still exists given the task type and id.
Args:
task_type: The task type.
task_id: The task id.
Returns:
Boolean; whether the subprocess still exists. If the subprocess has
exited, this returns False.
"""
return self.get_process_exit_code(task_type, task_id) is None
def _process_watchdog(self):
"""Simulates a cluster management system.
- If auto_restart is True, it restarts processes that exit with a non-zero
exit code. Note that when join() times out it overrides auto_restart to
False.
- If dependence_on_chief is True, it terminates all processes once the chief
exits. If auto_restart is also True, it only terminates all processes if
the chief exit with a zero exit code, otherwise it restarts the chief.
This runs in self._watchdog_thread.
"""
while True:
time.sleep(1)
with self._process_lock:
chief = self._processes.get(('chief', 0), None)
# Terminate the cluster when _dependence_on_chief is True if either:
# - chief has exited with zero exit code.
# - chief has exited with non-zero exit code and self._auto_restart is
# False.
if chief and self._dependence_on_chief and chief.exitcode is not None:
if chief.exitcode == 0 or (not self._auto_restart):
for p in self._processes.values():
# Give other processes a chance to exit on their own.
p.join(timeout=3)
self._terminate_all()
for p in self._processes.values():
p.join()
return
# Auto restart failed processes if self._auto_restart is True.
if self._auto_restart:
has_failure = False
for (task_type, task_id), p in self._processes.items():
if p.exitcode is not None and p.exitcode != 0:
has_failure = True
logging.info('Restarting failed %s-%d', task_type, task_id)
self._start_subprocess_and_reading_thread(task_type, task_id)
if has_failure:
continue
# Exit the thread if all processes have exited at this point.
if all(p.exitcode is not None for p in self._processes.values()):
return
def _reraise_if_subprocess_error(self, process_statuses):
for process_status in process_statuses.values():
assert isinstance(process_status, _ProcessStatusInfo)
if not process_status.is_successful:
process_status.exc_info[1].mpr_result = self._get_mpr_result(
process_statuses)
six.reraise(*process_status.exc_info)
def join(self, timeout=_DEFAULT_TIMEOUT_SEC):
"""Joins all the processes with timeout.
If any of the subprocesses does not exit approximately after `timeout`
seconds has passed after `join` call, this raises a
`SubprocessTimeoutError`.
Note: At timeout, it uses SIGTERM to terminate the subprocesses, in order to
log the stack traces of the subprocesses when they exit. However, this
results in timeout when the test runs with tsan (thread sanitizer); if tsan
is being run on the test targets that rely on timeout to assert information,
`MultiProcessRunner.terminate_all()` must be called after `join()`, before
the test exits, so the subprocesses are terminated with SIGKILL, and data
race is removed.
Args:
timeout: optional integer or `None`. If provided as an integer, and not
all processes report status within roughly `timeout` seconds, a
`SubprocessTimeoutError` exception will be raised. If `None`, `join` never
times out.
Returns:
A `MultiProcessRunnerResult` object, which has two attributes,
`return_value` and `stdout`. `return_value` always contains a list of
return values from the subprocesses, although the order is not meaningful.
If `return_output` argument is True at `__init__`, `stdout` is available
that contains a list of all messages from subprocesses' stdout and stderr.
Raises:
SubprocessTimeoutError: if not all processes report status approximately
within `timeout` seconds. When this is raised, a
`MultiProcessRunnerResult` object can be retrieved by
`SubprocessTimeoutError`'s mpr_result attribute, which has the same
structure as above 'Returns' section describes.
UnexpectedSubprocessExitError: If any of the subprocesses did not exit
properly (for example, they exit on SIGTERM or SIGKILL signal). When
this is raised, a `MultiProcessRunnerResult` object can be retrieved by
`UnexpectedSubprocessExitError`'s mpr_result attribute, which has the
same structure as above 'Returns' section describes. If `max_run_time`
is not `None`, it is expected that some subprocesses may be
force-killed when `max_run_time` is up, and this is raised in those
cases.
Exception: if there is an Exception propagated from any subprocess. When
this is raised, a `MultiProcessRunnerResult` object can be retrieved by
`UnexpectedSubprocessExitError`'s mpr_result attribute, which has the
same structure as above 'Returns' section describes.
"""
if timeout and not isinstance(timeout, int):
raise ValueError('`timeout` must be an integer or `None`.')
with self._process_lock:
if self._joined:
raise ValueError("MultiProcessRunner can't be joined twice.")
self._joined = True
self._watchdog_thread.join(timeout)
if self._watchdog_thread.is_alive():
# Timeout. Force termination to dump worker processes stack trace.
with self._process_lock:
self._auto_restart = False
logging.error('Timeout when joining for child processes. Terminating...')
self.terminate_all(sig=signal.SIGTERM)
# Wait for the processes to terminate by themselves first, so they have a
# chance to dump stacktraces. After _FORCE_KILL_WAIT_SEC, we SIGKILL them.
self._watchdog_thread.join(_FORCE_KILL_WAIT_SEC)
if self._watchdog_thread.is_alive():
logging.error('Timeout when waiting for child processes to '
'print stacktrace. Sending SIGKILL...')
self.terminate_all()
self._watchdog_thread.join()
process_statuses = self._get_process_statuses()
self._reraise_if_subprocess_error(process_statuses)
raise SubprocessTimeoutError(
'One or more subprocesses timed out, where timeout was set to {}s. '
'Please change the `timeout` argument for '
'`MultiProcessRunner.join()` or `multi_process_runner.run()` '
'if it should be adjusted.'.format(timeout),
self._get_mpr_result(process_statuses))
for (task_type, task_id), p in self._processes.items():
logging.info('%s-%d exit code: %s', task_type, task_id, p.exitcode)
process_statuses = self._get_process_statuses()
self._reraise_if_subprocess_error(process_statuses)
# Checking all the processes that are expected to exit properly.
for (task_type, task_id), p in self._processes.items():
# Successfully exiting process has exit code 0. We ignore processes that
# are terminated.
assert p.exitcode is not None
if (p.exitcode > 0 and (task_type, task_id) not in self._terminated):
raise UnexpectedSubprocessExitError(
'Subprocess %s-%d exited with exit code %s. See logs for details.'
% (task_type, task_id, p.exitcode),
self._get_mpr_result(process_statuses))
logging.info('Joining log reading threads.')
for thread in self._reading_threads:
thread.join()
logging.info('Joined log reading threads.')
# Clear the alarm.
signal.alarm(0)
return self._get_mpr_result(process_statuses)
def _get_mpr_result(self, process_statuses):
stdout = self._queue_to_list(self._streaming_queue)
return_values = []
for process_status in process_statuses.values():
if process_status.return_value is not None:
return_values.append(process_status.return_value)
return MultiProcessRunnerResult(stdout=stdout, return_value=return_values)
def terminate(self, task_type, task_id):
"""Terminates the process with `task_type` and `task_id`.
If auto_retart=True, the terminated task will be restarted unless the chief
has already exited with zero exit code.
Args:
task_type: the task type.
task_id: the task id.
"""
with self._process_lock:
p = self._processes.get((task_type, task_id), None)
if p is None:
raise ValueError('{}-{} does not exist'.format(task_type, task_id))
self._terminated.add((task_type, task_id))
# TODO(crccw): change to use Process.terminate() as well.
self._parent_to_sub_queue.put('terminate {} {}'.format(
task_type, task_id))
p.join()
def _terminate_all(self, sig=None):
"""Terminates all subprocesses.
The caller is required to hold self._process_lock.
Args:
sig: the signal used to terminate the process. The default is SIGKILL.
"""
# Use SIGKILL as default. In systems where that's unavailable such as
# windows, use SIGTERM.
sig = sig or getattr(signal, 'SIGKILL', signal.SIGTERM)
for (task_type, task_id), p in self._processes.items():
if p.exitcode is not None:
logging.info('%s-%d has already exited. Not terminating.', task_type,
task_id)
continue
try:
os.kill(p.pid, sig)
self._terminated.add((task_type, task_id))
logging.info('%s-%d terminated with signal %r.', task_type, task_id,
sig)
except ProcessLookupError:
logging.info('Attempting to kill %s-%d but it does not exist.',
task_type, task_id)
def terminate_all(self, sig=None):
"""Terminates all subprocesses."""
with self._process_lock:
self._terminate_all(sig)
class _Process(multi_process_lib.Process):
"""A modified `multiprocessing.Process` that can set up environment variables."""
# TODO(crccw): consider moving other logics in _ProcFunc to _Process.
def __init__(self, test_env, **kwargs):
super(_Process, self).__init__(**kwargs)
self._test_env = test_env
self._actual_run = getattr(self, 'run')
self.run = self._run_with_setenv
def _run_with_setenv(self):
# We need to set environment variables before doing anything because
# setenv() is not thread-safe.
test_env = self._test_env
if test_env.grpc_fail_fast is not None:
os.environ['GRPC_FAIL_FAST'] = str(test_env.grpc_fail_fast)
_set_tf_config(test_env.task_type, test_env.task_id, test_env.cluster_spec,
test_env.rpc_layer)
return self._actual_run()
class _ProcFunc(object):
"""Represents a callable to run in a subprocess."""
@contextlib.contextmanager
def _runtime_mode(self, executing_eagerly):
if executing_eagerly:
with context.eager_mode():
yield
else:
with context.graph_mode():
yield
def _message_checking_func(self, task_type, task_id):
"""A function that regularly checks messages from parent process."""
# TODO(rchao): Remove this once parent uses SIGKILL to terminate subprocess.
while True:
try:
message = self._resources.parent_to_sub_queue.get(block=False)
# Currently the only possible message is termination.
if not message.startswith('terminate'):
raise ValueError('Unrecognized message: {}'.format(message))
if message == 'terminate {} {}'.format(task_type, task_id):
break
else:
# If the message is not targeting this process, put it back to the
# queue.
self._resources.parent_to_sub_queue.put(message)
time.sleep(1)
except Queue.Empty:
time.sleep(0.1)
self._resources.process_status_queue.put(
_ProcessStatusInfo(
task_type=task_type,
task_id=task_id,
is_successful=True,
exc_info=None,
return_value=None))
# `os._exit(1)` is used to more reliably terminate a subprocess.
os._exit(1) # pylint: disable=protected-access
def _close_streaming(self):
"""Close stdout, stderr and streaming pipe.
We need to explicitly close them since Tensorflow may take a while to exit,
so that the reading threads in the main process can exit more quickly.
"""
sys.stdout.flush()
sys.stderr.flush()
sys.stdout.close()
sys.stderr.close()
self._resources.streaming_pipe_w.close()
def __call__(self, resources, test_env, fn, args, kwargs, use_dill_for_args):
"""The wrapper function that actually gets run in child process(es)."""
global _barrier
self._resources = resources
_barrier = self._resources.barrier
fn = dill.loads(fn)
if use_dill_for_args:
args = dill.loads(args)
kwargs = dill.loads(kwargs)
if faulthandler is not None:
faulthandler.enable()
faulthandler.register(signal.SIGTERM, chain=True)
# All logging should go to stderr to be streamed to the main process.
logging.set_stderrthreshold(logging.DEBUG)
# Assign sys.stdout and sys.stderr as duplicates of `streaming_pipe_w` so
# print() and logging.*() write directly to `streaming_pipe_w`.
# Unfortunately since we cannot prepend task_type and task_id information to
# the streamed logs we will need a thread per subprocess to distinguish
# where the piece of message is from.
os.dup2(resources.streaming_pipe_w.fileno(), sys.stdout.fileno())
os.dup2(resources.streaming_pipe_w.fileno(), sys.stderr.fileno())
pid = os.getpid()
logging.info('Subprocess with PID %d (%s, %d) is now being started.', pid,
test_env.task_type, test_env.task_id)
# The thread will be dedicated to checking messages from the parent process.
threading.Thread( # pylint: disable=unexpected-keyword-arg
target=self._message_checking_func,
args=(test_env.task_type, test_env.task_id),
daemon=True).start()
if test_env.v2_enabled:
v2_compat.enable_v2_behavior()
with self._runtime_mode(test_env.executing_eagerly):
info = _run_contained(test_env.task_type, test_env.task_id, fn, args,
kwargs)
self._resources.process_status_queue.put(info)
# Re-raise the exception in addition to reporting it to the parent
# process, so that even if `--test_timeout` flag is set and the
# error doesn't make it to be shown in parent process before bazel's
# timeout, the log would still show what happens in this subprocess,
# instead of silently suppressing the error due to early bazel
# timeout. Raising an error in the subprocess produces stack trace in
# the log, but the program continues running.
if not info.is_successful:
six.reraise(*info.exc_info)
self._close_streaming()
# Exit with code 0 as it's considered successful exit at this point.
sys.exit(0)
# Active MultiProcessPoolRunner. We need to shut them down when the program
# exits, and this is by setting the `tearDownModule` of the module containing
# `__main__`. Note this it set in both the parent process and the subprocesses.
_active_pool_runners = weakref.WeakSet()
def _shutdown_all_pool_runners():
for pool in _active_pool_runners:
pool.shutdown()
def is_oss():
"""Returns whether the test is run under OSS."""
return len(sys.argv) >= 1 and 'bazel' in sys.argv[0]
class MultiProcessPoolRunner(object):
"""A utility class to start a process pool to simulate a cluster.
It's similar to MultiProcessRunner, but uses a pool of processes to avoid the
expensive initialization cost of Tensorflow.
"""
def __init__(self, cluster_spec, initializer=None):
"""Creates a multi-process pool runner.
Args:
cluster_spec: Dict for cluster spec. The following is an example of
cluster with three workers.
{"worker": ["worker0.example.com:2222",
"worker1.example.com:2222",
"worker2.example.com:2222"]}
initializer: a callable to called at the startup of worker processes.
Raises:
RuntimeError: if `multi_process_runner.test_main()` is not called.
ValueError: if there are more than one chief in the `cluster_spec`.
"""
_active_pool_runners.add(self)
self._cluster_spec = cluster_spec
self._initializer = initializer
self._conn = {}
self._runner = None
def __del__(self):
self.shutdown()
def shutdown(self):
"""Shuts down the worker pool."""
for conn in self._conn.values():
conn.close()
self._conn = {}
if self._runner is not None:
try:
self._runner.join()
except Exception as e: # pylint: disable=broad-except
logging.error(
'Ignoring exception when shutting down MultiProcessPoolRunner: %s',
e)
self._runner = None
def _start(self):
"""Starts the worker pool."""
# We need different arguments for different processes so we're passing a
# no-op fn here and use start_single_process instead.
if dill is None:
raise unittest.SkipTest(
'TODO(b/150264776): Resolve dependency issue in CI')
self._runner = MultiProcessRunner(
fn=lambda: None,
cluster_spec=self._cluster_spec,
use_dill_for_args=False)
if self._initializer:
initializer = dill.dumps(self._initializer, dill.HIGHEST_PROTOCOL)
else:
initializer = None
for task_type, addresses in self._cluster_spec.items():
for task_id, _ in enumerate(addresses):
conn1, conn2 = multiprocessing.Pipe(duplex=True)
self._conn[(task_type, task_id)] = conn1
self._runner.start_single_process(
task_type,
task_id,
fn=_pool_runner_worker,
args=(task_type, task_id, initializer, conn2))
def run(self, fn, args=None, kwargs=None):
"""Runs `fn` with `args` and `kwargs` on all jobs.
Args:
fn: The function to be run.
args: Optional positional arguments to be supplied in `fn`.
kwargs: Optional keyword arguments to be supplied in `fn`.
Returns:
A list of return values.
"""
# TODO(b/150264776): skip in OSS until it's implemented.
multi_process_lib.Process()
if self._runner is None:
self._start()
fn = dill.dumps(fn, dill.HIGHEST_PROTOCOL)
for conn in self._conn.values():
conn.send((fn, args or [], kwargs or {}))
process_statuses = []
for (task_type, task_id), conn in self._conn.items():
logging.info('Waiting for the result from %s-%d', task_type, task_id)
try:
process_statuses.append(conn.recv())
except EOFError:
# This shouldn't happen due to exceptions in fn. This usually
# means bugs in the runner.
self.shutdown()
raise RuntimeError('Unexpected EOF. Worker process may have died. '
'Please report a bug')
return_values = []
for process_status in process_statuses:
assert isinstance(process_status, _ProcessStatusInfo)
if not process_status.is_successful:
six.reraise(*process_status.exc_info)
if process_status.return_value is not None:
return_values.append(process_status.return_value)
return return_values
def _pool_runner_worker(task_type, task_id, initializer, conn):
"""Function that runs on the workers in a pool.
It listens for callables to run and returns the result until `conn` is closed.
It captures the exceptions during executing the callable and return it through
`conn`.
Args:
task_type: the task type.
task_id: the task index.
initializer: a callable to execute during startup.
conn: a multiprocessing.Connection object to listen for tasks and send
results.
"""
if initializer:
initializer = dill.loads(initializer)
initializer()
while True:
try:
fn, args, kwargs = conn.recv()
except EOFError:
break
fn = dill.loads(fn)
info = _run_contained(task_type, task_id, fn, args, kwargs)
sys.stdout.flush()
sys.stderr.flush()
conn.send(info)
def _run_contained(task_type, task_id, fn, args, kwargs):
"""Runs `fn` with `args` and `kwargs`.
The function returns _ProcessStatusInfo which captures the return value and
the exception.
Args:
task_type: the task type.
task_id: the task index.
fn: the function to be run.
args: optional positional arguments to be supplied in `fn`.
kwargs: optional keyword arguments to be supplied in `fn`.
Returns:
a _ProcessStatusInfo.
"""
is_successful = False
return_value = None
exc_info = None
try:
return_value = fn(*args, **kwargs)
is_successful = True
return _ProcessStatusInfo(
task_type=task_type,
task_id=task_id,
is_successful=is_successful,
exc_info=exc_info,
return_value=return_value)
# If `fn` ends up exiting with `sys.exit()`, the `SystemExit` is not
# handled here.
except Exception: # pylint: disable=broad-except
exc_info = sys.exc_info()
return _ProcessStatusInfo(
task_type=task_type,
task_id=task_id,
is_successful=is_successful,
exc_info=exc_info,
return_value=return_value)
@tf_export('__internal__.distribute.multi_process_runner'
'.SubprocessTimeoutError',
v1=[])
class SubprocessTimeoutError(RuntimeError):
"""An error that indicates there is at least one subprocess timing out.
When this is raised, a namedtuple object representing the multi-process run
result can be retrieved by
`tf.__internal__.distribute.multi_process_runner.SubprocessTimeoutError`'s
`mpr_result` attribute. See
`tf.__internal__.distribute.multi_process_runner.run` for more information.
"""
def __init__(self, msg, mpr_result):
super(SubprocessTimeoutError, self).__init__(msg)
self.mpr_result = mpr_result
@tf_export('__internal__.distribute.multi_process_runner'
'.UnexpectedSubprocessExitError',
v1=[])
class UnexpectedSubprocessExitError(RuntimeError):
"""An error indicating there is at least one subprocess with unexpected exit.
When this is raised, a namedtuple object representing the multi-process run
result can be retrieved by
`tf.__internal__.distribute.multi_process_runner
.UnexpectedSubprocessExitError`'s
`mpr_result` attribute. See
`tf.__internal__.distribute.multi_process_runner.run` for more information.
"""
def __init__(self, msg, mpr_result):
super(UnexpectedSubprocessExitError, self).__init__(msg)
self.mpr_result = mpr_result
@tf_export(
'__internal__.distribute.multi_process_runner.NotInitializedError', v1=[])
class NotInitializedError(RuntimeError):
"""An error indicating `multi_process_runner.run` is used without init.
When this is raised, user is supposed to call
`tf.__internal__.distribute.multi_process_runner.test_main()` within
`if __name__ == '__main__':` block to properly initialize
`multi_process_runner.run`.
"""
pass
def _set_tf_config(task_type, task_id, cluster_spec, rpc_layer=None):
"""Set TF_CONFIG environment variable."""
tf_config_dict = {
'cluster': cluster_spec,
'task': {
'type': task_type,
'index': task_id,
},
}
if rpc_layer is not None:
tf_config_dict['rpc_layer'] = rpc_layer
os.environ['TF_CONFIG'] = json.dumps(tf_config_dict)
@tf_export('__internal__.distribute.multi_process_runner.run', v1=[])
def run(fn,
cluster_spec,
rpc_layer=None,
max_run_time=None,
return_output=False,
timeout=_DEFAULT_TIMEOUT_SEC,
args=None,
kwargs=None):
"""Run `fn` in multiple processes according to `cluster_spec`.
Given a callable `fn`, `tf.__internal__.distribute.multi_process_runner.run`
launches multiple processes, each of which runs `fn`. These processes are
referred to as "subprocesses" or "child processes". Each of those subprocesses
will have their `TF_CONFIG` environment variable set, according to
`cluster_spec` and their task types. The stdout of the subprocesses are
streamed to the main process' and thus available in logs (if `stream_output`
is True), with [type-id] prefix.
`tf.__internal__.distribute.multi_process_runner.run` will block until all
subprocesses have successfully exited, and return a namedtuple object that
represents the run result. This object has a `return_value` attribute, which
is a list that contains subprocesses `fn`'s return values, for those
subprocesses that successfully returned from `fn`. The order of `return_value`
list is not meaningful. If an optional arg `return_output` (default to False)
is set to True, the namedtuple object will have an additional attribute
`stdout`, which is a list containing the stdout of the subprocesses. If any
subprocess' `fn` ends up raising an error, that error will be reraised from
`tf.__internal__.distribute.multi_process_runner.run`, and the aforementioned
namedtuple object will be available through the exception's
`mpr_result` attribute.
This utility is used for simulating running TensorFlow programs across
multiple task types, and each of the task type may contain more than one task
(except for "chief" where more than one task is prohibited). Test coverage of
multi-worker training is the main application of this utility, where code
written for multi-worker training can be realistically covered in unit tests.
Any test module that uses
`tf.__internal__.distribute.multi_process_runner.run()` must call
`tf.__internal__.distribute.multi_process_runner.test_main()` instead of
regular `test.main()` inside `if __name__ == '__main__':` block for proper
initialization.
Args:
fn: Function to be run on child processes. This will be run on processes for
all task types.
cluster_spec: Dict for cluster spec. The utility function
`tf.__internal__.distribute.multi_process_runner.create_cluster_spec` can
be conveniently used to create such dict. The following is an example of
cluster with three workers and two ps's.
{"worker": ["worker0.example.com:2222",
"worker1.example.com:2222",
"worker2.example.com:2222"],
"ps": ["ps0.example.com:2222",
"ps1.example.com:2222"]}
rpc_layer: RPC layer to use. Default value is 'grpc'.
max_run_time: `None` or integer. If not `None`, child processes are forced
to exit at approximately this many seconds after this utility is called.
We achieve this through `signal.alarm()` api. Note that this is best
effort at Python level since Python signal handler does not get executed
when it runs lower level C/C++ code. So it can be delayed for arbitrarily
long time. If any of the child process is still running when
`max_run_time` is up, they will be force-terminated and an
`tf.__internal__.distribute.multi_process_runner
.UnexpectedSubprocessExitError`
may be raised. If `None`, child processes are not forced to exit.
return_output: If True, the output/error from the subprocesses should be
collected to be attached to the resulting namedtuple returned from this
utility. The list of output can be retrieved via `stdout` attribute.
Defaults to False.
timeout: optional integer or `None`. If provided as an integer, and not all
processes report status within roughly `timeout` seconds, a
`tf.__internal__.distribute.multi_process_runner.SubprocessTimeoutError`
exception will be raised. If `None`,
`tf.__internal__.distribute.multi_process_runner.run` never times out.
Defaults to the constant `_DEFAULT_TIMEOUT_SEC` defined in
`multi_process_runner` module.
args: Positional arguments to be sent to `fn` run on subprocesses.
kwargs: Keyword arguments to be sent to `fn` run on subprocesses.
Returns:
A namedtuple object, which has two attributes,
`return_value` and `stdout`. `return_value` always contains a list of
returnvalues from the subprocesses, although the order is not meaningful.
If `return_output` argument is True, `stdout` is available that contains a
list of all messages from subprocesses' stdout and stderr, and the order
is mostly chronological.
Raises:
RuntimeError: if
`tf.__internal__.distribute.multi_process_runner.test_main()` is
not called in test's `if __name__ == '__main__':` block.
ValueError: if there are more than one chief in the `cluster_spec`.
tf.__internal__.distribute.multi_process_runner.SubprocessTimeoutError: if
not all processes report status approximately
within `timeout` seconds. When this is raised, a
namedtuple object can be retrieved by
`tf.__internal__.distribute.multi_process_runner.SubprocessTimeoutError`'s
`mpr_result` attribute, which has the same
structure as above 'Returns' section describes.
tf.__internal__.distribute.multi_process_runner
.UnexpectedSubprocessExitError:
If any of the subprocesses did not exit
properly (for example, they exit on SIGTERM or SIGKILL signal). When
this is raised, a namedtuple object can be retrieved by
`tf.__internal__.distribute.multi_process_runner
.UnexpectedSubprocessExitError`'s
`mpr_result` attribute, which has the
same structure as above 'Returns' section describes. If `max_run_time`
is not `None`, it is expected that some subprocesses may be
force-killed when `max_run_time` is up, and this is raised in those
cases.
Exception: if there is an Exception propagated from any subprocess. When
this is raised, a namedtuple object can be retrieved by
`tf.__internal__.distribute.multi_process_runner
.UnexpectedSubprocessExitError`
`mpr_result` attribute, which has the
same structure as above 'Returns' section describes.
Examples:
```python
class SimpleMultiProcessTest(tf.test.TestCase):
def test_simple_printing_and_return(self):
def fn():
resolver = tf.distribute.cluster_resolver.TFConfigClusterResolver()
# This will print "[chief-0]: Task type: chief , task id: 0"
# for chief, for example.
logging.info('Task type: %s, task id: %d',
resolver.task_type, resolver.task_id)
return resolver.task_type
result = tf.__internal__.distribute.multi_process_runner.run(
fn=fn,
cluster_spec=(
tf.__internal__
.distribute.multi_process_runner.create_cluster_spec(
has_chief=True, num_workers=2)))
assert sorted(result.return_value) == ['chief', 'worker', 'worker']
def test_error_from_fn(self):
def fn():
resolver = tf.distribute.cluster_resolver.TFConfigClusterResolver()
raise ValueError('Task type {}, task id {} is errors out'.format(
resolver.task_type, resolver.task_id))
with self.assertRaisesRegexp(ValueError,
'Task type worker, task id 0 is errors out'):
cluster_spec = (
tf.__internal__.distribute.multi_process_runner.create_cluster_spec(
num_workers=1))
tf.__internal__.distribute.multi_process_runner.run(
fn=fn, cluster_spec=cluster_spec)
if __name__ == '__main__':
tf.__internal__.distribute.multi_process_runner.test_main()
```
"""
runner = MultiProcessRunner(
fn,
cluster_spec,
rpc_layer,
max_run_time=max_run_time,
return_output=return_output,
args=args,
kwargs=kwargs)
runner.start()
return runner.join(timeout)
# This is set by MultiProcessRunner in worker processes.
_barrier = None
@tf_export('__internal__.distribute.multi_process_runner.get_barrier', v1=[])
def get_barrier():
"""Returns a `multiprocessing.Barrier` for `multi_process_runner.run`.
`tf.__internal__.distribute.multi_process_runner.get_barrier()` returns
a `multiprocessing.Barrier` object which can be used within `fn` of
`tf.__internal__.distribute.multi_process_runner` to wait with
`barrier.wait()` call until all other tasks have also reached the
`barrier.wait()` call, before they can proceed individually.
Note that all tasks (subprocesses) have to reach `barrier.wait()` call to
proceed. Currently it is not supported to block on only a subset of tasks
in the cluster.
Example:
```python
def fn():
some_work_to_be_done_by_all_tasks()
tf.__internal__.distribute.multi_process_runner.get_barrier().wait()
# The barrier guarantees that at this point, all tasks have finished
# `some_work_to_be_done_by_all_tasks()`
some_other_work_to_be_done_by_all_tasks()
result = tf.__internal__.distribute.multi_process_runner.run(
fn=fn,
cluster_spec=(
tf.__internal__
.distribute.multi_process_runner.create_cluster_spec(
num_workers=2)))
```
Returns:
A `multiprocessing.Barrier` for `multi_process_runner.run`.
"""
if _barrier is None:
raise ValueError(
'barrier is not defined. It is likely because you are calling '
'get_barrier() in the main process. get_barrier() can only be called '
'in the subprocesses.'
)
return _barrier
_manager = None
_manager_lock = threading.Lock()
def manager():
"""Returns the multiprocessing manager object for concurrency tools.
The manager object is useful as it controls a server process that holds
the python objects that can be shared across processes. This can be used
for parent-subprocess communication:
```python
manager = multi_process_runner.manager()
some_event_happening_in_subprocess = manager.Event()
mpr = multi_process_runner.MultiProcessRunner(fn, cluster_spec,
args=(some_event_happening_in_subprocess,))
mpr.start()
some_event_happening_in_subprocess.wait()
# Do something that only should after some event happens in subprocess.
```
Note that the user of multi_process_runner should not create additional
`multiprocessing.Manager()` objects; doing so can result in segfault in
some cases.
This method should only be called after multi_process_runner.test_main() is
called.
"""
global _manager
with _manager_lock:
if _manager is None:
_manager = multiprocessing.Manager()
return _manager
@tf_export('__internal__.distribute.multi_process_runner.test_main', v1=[])
def test_main():
"""Main function to be called within `__main__` of a test file.
Any test module that uses
`tf.__internal__.distribute.multi_process_runner.run()`
must call this instead of regular `test.main()` inside
`if __name__ == '__main__':` block, or an error will be raised when
`tf.__internal__.distribute.multi_process_runner.run()` is used. This method
takes
care of needed initialization for launching multiple subprocesses.
Example:
```python
class MyTestClass(tf.test.TestCase):
def testSomething(self):
# Testing code making use of
# `tf.__internal__.distribute.multi_process_runner.run()`.
if __name__ == '__main__':
tf.__internal__.distribute.multi_process_runner.test_main()
```
"""
# Inject tearDownModule() to shut down all pool runners. Active pool runners
# will block the program from exiting. This is necessary for global pool
# runners. We tried atexit in the past, and it doesn't work in some
# deployment.
old_tear_down_module = getattr(sys.modules['__main__'], 'tearDownModule',
None)
def tear_down_module():
_shutdown_all_pool_runners()
if old_tear_down_module is not None:
old_tear_down_module()
setattr(sys.modules['__main__'], 'tearDownModule', tear_down_module)
multi_process_lib.test_main()
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
3a12e6bb5bc17371ed1458a7584ba6e0c9c9723d | 4f1c2b624417f7c1b860460c097fbf92926e817a | /app/app/settings.py | 55c8920c3de9c1981ec16f16c0f00d3bcf6df259 | [
"MIT"
] | permissive | millerjl1980/recipe-app-api | e4cf49881158d7cdf0126364c4bedd43fdff9201 | 736df8d6a6c4f700e50501640cb823505024e2b7 | refs/heads/main | 2023-08-11T19:08:28.998677 | 2021-10-10T22:28:07 | 2021-10-10T22:28:07 | 385,056,407 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,580 | py | """
Django settings for app project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-s0-7uh4rljwxtay=q$4fn$ic!n@r2k@xjim8sm2m#r_0=s9@vr'
# 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',
'rest_framework',
'rest_framework.authtoken',
'core',
'user',
'recipe',
]
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 = 'app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'HOST': os.environ.get('DB_HOST'),
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASS'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = '/vol/web/media'
STATIC_ROOT = '/vol/web/static'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
AUTH_USER_MODEL = 'core.User'
| [
"jmiller@elements.org"
] | jmiller@elements.org |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.