hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f72beaa7ee8d91281059cff457c016f1e6f65cb3 | 3,651 | py | Python | bindings/python/ensmallen/datasets/string/candidatussericytochromatiabacteriums15bmn24raac196.py | AnacletoLAB/ensmallen_graph | b2c1b18fb1e5801712852bcc239f239e03076f09 | [
"MIT"
] | 5 | 2021-02-17T00:44:45.000Z | 2021-08-09T16:41:47.000Z | bindings/python/ensmallen/datasets/string/candidatussericytochromatiabacteriums15bmn24raac196.py | AnacletoLAB/ensmallen_graph | b2c1b18fb1e5801712852bcc239f239e03076f09 | [
"MIT"
] | 18 | 2021-01-07T16:47:39.000Z | 2021-08-12T21:51:32.000Z | bindings/python/ensmallen/datasets/string/candidatussericytochromatiabacteriums15bmn24raac196.py | AnacletoLAB/ensmallen | b2c1b18fb1e5801712852bcc239f239e03076f09 | [
"MIT"
] | 3 | 2021-01-14T02:20:59.000Z | 2021-08-04T19:09:52.000Z | """
This file offers the methods to automatically retrieve the graph Candidatus Sericytochromatia bacterium S15B-MN24 RAAC_196.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets},
author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others},
journal={Nucleic acids research},
volume={47},
number={D1},
pages={D607--D613},
year={2019},
publisher={Oxford University Press}
}
```
"""
from typing import Dict
from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph
from ...ensmallen import Graph # pylint: disable=import-error
def CandidatusSericytochromatiaBacteriumS15bMn24Raac196(
directed: bool = False,
preprocess: bool = True,
load_nodes: bool = True,
verbose: int = 2,
cache: bool = True,
cache_path: str = "graphs/string",
version: str = "links.v11.5",
**additional_graph_kwargs: Dict
) -> Graph:
"""Return new instance of the Candidatus Sericytochromatia bacterium S15B-MN24 RAAC_196 graph.
The graph is automatically retrieved from the STRING repository.
Parameters
-------------------
directed: bool = False
Wether to load the graph as directed or undirected.
By default false.
preprocess: bool = True
Whether to preprocess the graph to be loaded in
optimal time and memory.
load_nodes: bool = True,
Whether to load the nodes vocabulary or treat the nodes
simply as a numeric range.
verbose: int = 2,
Wether to show loading bars during the retrieval and building
of the graph.
cache: bool = True
Whether to use cache, i.e. download files only once
and preprocess them only once.
cache_path: str = "graphs"
Where to store the downloaded graphs.
version: str = "links.v11.5"
The version of the graph to retrieve.
The available versions are:
- homology.v11.5
- physical.links.v11.5
- links.v11.5
additional_graph_kwargs: Dict
Additional graph kwargs.
Returns
-----------------------
Instace of Candidatus Sericytochromatia bacterium S15B-MN24 RAAC_196 graph.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets},
author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others},
journal={Nucleic acids research},
volume={47},
number={D1},
pages={D607--D613},
year={2019},
publisher={Oxford University Press}
}
```
"""
return AutomaticallyRetrievedGraph(
graph_name="CandidatusSericytochromatiaBacteriumS15bMn24Raac196",
repository="string",
version=version,
directed=directed,
preprocess=preprocess,
load_nodes=load_nodes,
verbose=verbose,
cache=cache,
cache_path=cache_path,
additional_graph_kwargs=additional_graph_kwargs
)()
| 34.771429 | 223 | 0.690222 | from typing import Dict
from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph
from ...ensmallen import Graph
def CandidatusSericytochromatiaBacteriumS15bMn24Raac196(
directed: bool = False,
preprocess: bool = True,
load_nodes: bool = True,
verbose: int = 2,
cache: bool = True,
cache_path: str = "graphs/string",
version: str = "links.v11.5",
**additional_graph_kwargs: Dict
) -> Graph:
return AutomaticallyRetrievedGraph(
graph_name="CandidatusSericytochromatiaBacteriumS15bMn24Raac196",
repository="string",
version=version,
directed=directed,
preprocess=preprocess,
load_nodes=load_nodes,
verbose=verbose,
cache=cache,
cache_path=cache_path,
additional_graph_kwargs=additional_graph_kwargs
)()
| true | true |
f72beafa6216e6ee1923e3c7055a37cbcdd6d963 | 2,305 | py | Python | oop-intro/Game.py | emptyspace42/mycode | 834c0a2817ffffa92b90ec3bd05ef41cb73a8879 | [
"MIT"
] | 5 | 2018-05-21T18:16:13.000Z | 2018-05-22T22:41:40.000Z | oop-intro/Game.py | cazzara/mycode | 834c0a2817ffffa92b90ec3bd05ef41cb73a8879 | [
"MIT"
] | null | null | null | oop-intro/Game.py | cazzara/mycode | 834c0a2817ffffa92b90ec3bd05ef41cb73a8879 | [
"MIT"
] | null | null | null | from Player import Player
from time import sleep
from Cheater import Cheater_Loaded, Cheater_Swapper
from random import random
class Game:
def __init__(self):
self.main()
def make_player(self):
p = None
name = input("Enter your name: ")
cheat = input("Are you a cheater? (y/n)")
if cheat[0].lower() == 'y':
cheat_type = int(random()*10)
if cheat_type <= 5:
p = Cheater_Loaded(name)
else:
p = Cheater_Swapper(name)
else:
p = Player(name)
return p
def play_hand(self, player):
print("1...")
sleep(1)
print("2...")
sleep(1)
print("3...")
sleep(1)
player.roll()
if self.is_cheater(player):
player.cheat()
def is_cheater(self, player):
return isinstance(player, Cheater_Swapper) or isinstance(player, Cheater_Loaded)
def main(self):
print("Welcome to the super fun dice game!")
print("-----Player 1-----")
player1 = self.make_player()
print("-----Player 2-----")
player2 = self.make_player()
print("Alright, {} vs {}!!".format(player1.get_name(), player2.get_name()))
print("*****Begin!*****")
print("Player 1 Rolling:")
self.play_hand(player1)
print("Player 2 Rolling:")
self.play_hand(player2)
p1_total = sum(player1.get_dice())
p2_total = sum(player2.get_dice())
print("{} rolled {}...Total: {}".format(player1.get_name(), player1.get_dice(), p1_total))
print("{} rolled {}...Total: {}".format(player2.get_name(), player2.get_dice(), p2_total))
if p1_total == p2_total:
print("A Draw! :O")
elif p1_total > p2_total:
if self.is_cheater(player1):
print("{} Wins! (But you cheated!)".format(player1.get_name()))
else:
print("{} Wins!".format(player1.get_name()))
else:
if self.is_cheater(player2):
print("{} Wins! (But you cheated!)".format(player2.get_name()))
else:
print("{} Wins!".format(player2.get_name()))
if __name__ == "__main__":
g = Game()
| 32.013889 | 98 | 0.527549 | from Player import Player
from time import sleep
from Cheater import Cheater_Loaded, Cheater_Swapper
from random import random
class Game:
def __init__(self):
self.main()
def make_player(self):
p = None
name = input("Enter your name: ")
cheat = input("Are you a cheater? (y/n)")
if cheat[0].lower() == 'y':
cheat_type = int(random()*10)
if cheat_type <= 5:
p = Cheater_Loaded(name)
else:
p = Cheater_Swapper(name)
else:
p = Player(name)
return p
def play_hand(self, player):
print("1...")
sleep(1)
print("2...")
sleep(1)
print("3...")
sleep(1)
player.roll()
if self.is_cheater(player):
player.cheat()
def is_cheater(self, player):
return isinstance(player, Cheater_Swapper) or isinstance(player, Cheater_Loaded)
def main(self):
print("Welcome to the super fun dice game!")
print("-----Player 1-----")
player1 = self.make_player()
print("-----Player 2-----")
player2 = self.make_player()
print("Alright, {} vs {}!!".format(player1.get_name(), player2.get_name()))
print("*****Begin!*****")
print("Player 1 Rolling:")
self.play_hand(player1)
print("Player 2 Rolling:")
self.play_hand(player2)
p1_total = sum(player1.get_dice())
p2_total = sum(player2.get_dice())
print("{} rolled {}...Total: {}".format(player1.get_name(), player1.get_dice(), p1_total))
print("{} rolled {}...Total: {}".format(player2.get_name(), player2.get_dice(), p2_total))
if p1_total == p2_total:
print("A Draw! :O")
elif p1_total > p2_total:
if self.is_cheater(player1):
print("{} Wins! (But you cheated!)".format(player1.get_name()))
else:
print("{} Wins!".format(player1.get_name()))
else:
if self.is_cheater(player2):
print("{} Wins! (But you cheated!)".format(player2.get_name()))
else:
print("{} Wins!".format(player2.get_name()))
if __name__ == "__main__":
g = Game()
| true | true |
f72bebf85db3d4c69b7d19ce58388cebfef5832f | 80 | py | Python | brian2/sphinxext/__init__.py | SimonAltrogge/brian2 | 6463c368a8277041051bf5ae4816f0dd5b6e057c | [
"BSD-2-Clause"
] | 674 | 2015-01-14T11:05:39.000Z | 2022-03-29T04:53:50.000Z | brian2/sphinxext/__init__.py | JongwanKim2090/brian2 | c212a57cb992b766786b5769ebb830ff12d8a8ad | [
"BSD-2-Clause"
] | 937 | 2015-01-05T13:24:22.000Z | 2022-03-25T13:10:13.000Z | brian2/sphinxext/__init__.py | JongwanKim2090/brian2 | c212a57cb992b766786b5769ebb830ff12d8a8ad | [
"BSD-2-Clause"
] | 237 | 2015-01-05T13:54:16.000Z | 2022-03-15T22:16:32.000Z | """
Brian-specific extension to the Sphinx documentation generation system.
"""
| 20 | 71 | 0.775 | true | true | |
f72bec6eb6fe20587d73322d3bca2f73d06296e7 | 24,462 | py | Python | XET.py | mezutelni/twrp-installer-xiaomi | 62ac87f316c70089e7188fa7b7f21d234c3643cd | [
"MIT"
] | 4 | 2017-10-09T20:23:56.000Z | 2019-06-27T03:59:26.000Z | XET.py | mezutelni/twrp-installer-xiaomi | 62ac87f316c70089e7188fa7b7f21d234c3643cd | [
"MIT"
] | 1 | 2017-12-01T19:12:44.000Z | 2018-01-06T14:42:47.000Z | XET.py | mezutelni/twrp-installer-xiaomi | 62ac87f316c70089e7188fa7b7f21d234c3643cd | [
"MIT"
] | null | null | null | #!/usr/bin/python3
import os
import sys
import time
import urllib.request
import hashlib
try:
from colorama import Fore, Back, Style, init
except ModuleNotFoundError:
print ("You have no colorama installed, i will install it for you")
print
path = sys.executable
#path = path[:-11]
path = path.replace("python.exe","")
os.system(path+"/Scripts/pip install colorama")
print
print ("Ok, now you can restart script :)")
from colorama import Fore, Back, Style, init
from twrp import twrpInstaller
init()
# here i'm checking wchich os you are using and setting command to clear cmd/terminal window
if sys.platform == "linux" or sys.platform == "linux2":
clear = lambda: os.system('clear')
s = "l"
elif sys.platform == "win32":
clear = lambda: os.system('cls')
s = "w"
# some global variables
dashed_line = (Fore.MAGENTA + "--------------------------------------------------------------------" + Fore.RESET)
killsystem = os.system("adb kill-server")
# this is path to /res/ folder and to .py file
resPath = os.path.abspath(os.path.dirname(__file__)) + os.sep + "res" + os.sep
filePath = os.path.abspath(os.path.dirname(__file__)) + os.sep
# resPath = os.path.dirname(sys.executable)+os.sep+"res"+os.sep
# filePath = os.path.dirname(sys.executable)+os.sep
# this is list of devices with official twrp support
devices = ["cancro", "libra", "ferrari", "aqua", "gemini", "virgo", "leo", "scorpio", "jason", "tiffany", "song",
"meri", "tisson", "capricorn", "natrium", "lithium", "chiron", "sagit", "hydrogen", "oxygen", "helium",
"HM2013023", "armani", "HM2014811", "HM2014813", "omega", "lcsh92_wet_jb9", "gucci", "dior", "hermes", "ido",
"land", "hennessy", "kate", "kenzo", "nikel", "prada", "markw", "ugg", "mido", "rolex", "santoni", "mocha",
"latte", "cappu","ugglite" ]
devicesDict = {'aries': "Mi 2", 'pisces': "Mi 3 TD", 'cancro': "Mi 3 W/Mi 4", 'libra': "Mi 4c",
'ferrari': "Mi 4i", 'aqua': "Mi 4s", 'gemini': "Mi 5", 'virgo': "Mi Note",
'leo': "Mi Note Pro", 'scorpio': "Mi Note 2", 'jason': "Mi Note 3", 'tiffany': "Mi 5x",
'song': "Mi 5c", 'meri': "Mi 5c", 'tissot': "Mi A1", 'capricorn': "Mi 5s", 'natrium': "Mi 5s+",
'lithium': "Mi MIX", 'chiron': "Mi MIX 2",'polaris':'Mi MIX 2s', 'sagit': "Mi 6", 'hydrogen': "Mi MAX",
'oxygen': "Mi MAX 2", 'helium': "Mi MAX PRO",
'HM2013023': "Redmi 1 - WCDMA",
'armani': "Redmi 1s - WCDMA", 'HM2014811': "Redmi 2 - WCDMA", 'HM2014813': "Redmi 2 - TD",
'omega': "Redmi PRO", 'lcsh92_wet_jb9': "Redmi note 1 - 3g-mtk", 'gucci': "Redmi note 1s",
'dior': "Redmi Note 1 - 4g", 'hermes': "Redmi Note 2", 'ido': "Redmi 3", 'land': "Redmi 3 S/X",
'hennessy': "Redmi Note 3 (MTK)", 'kate': "Redmi Note 3 Global",
'kenzo': "Redmi Note 3 Chinese", 'nikel': "Redmi Note 4", 'prada': "Redmi 4",
'markw': "Redmi 4 pro", 'ugg': "Redmi Note 5A", 'mido': "Redmi Note 4/4x", 'rolex': "Redmi 4a",
'santoni': "Redmi 4x", 'ugglite':'Redmi Note 5A','vince':'Redmi Note 5/5+','whyred':'Redmi Note 5 Pro',
'mocha': "Mi PAD", 'latte': "Mi PAD 2", 'cappu': "Mi PAD 3"}
googleApps = {
"youtube": "com.google.android.youtube",
"drive": "com.google.android.apps.docs",
"music": "com.google.android.music",
"maps": ":com.google.android.apps.maps",
"videos": "com.google.android.videos",
"photos": "com.google.android.apps.photos",
"chrome": "com.android.chrome",
"gmail": "com.google.android.gm",
"translate": "com.google.android.apps.translate",
"duo": "com.google.android.apps.tachyon"
}
miuiApps = {
"bugreport": "com.miui.bugreport",
"compass": "com.miui.compass",
"video": "com.miui.videoplayer",
"mail": "com.android.email",
"music": "com.miui.player",
"scanner": "com.xiaomi.scanner",
"browser": "com.android.browser",
"screenrecorder": "com.miui.screenrecorder",
"gallery": "com.miui.gallery",
"updater": "com.android.updater",
"midrop": "com.xiaomi.midrop",
"calendar": "com.android.calendar",
"miui assistant": "com.mi.android.globalpersonalassistant",
"notes": "com.miui.notes",
}
localmd5s = [
"f337d1707478d63315820a45030f547d", # 0.camera
"537e17e2585e731a1c26fbd81eb2affa", # 1.home
]
def getInt():
try:
case = int(input(Back.BLUE + "choose: " + Back.RESET))
return case
except ValueError:
print()
print(Fore.RED+"Wrong, choose right option!"+Fore.RESET)
case = int(getInt())
return case
def mydevice():
os.system("adb start-server")
os.system("adb shell mount /system")
glob_device = os.system("adb shell \"cat /system/build.prop | grep ro.product.device=\" > tmp ")
glob_device = open('tmp', 'r').read()
open('tmp', "r").close()
os.remove("tmp")
os.system("adb shell umount /system")
glob_device = glob_device.lstrip('ro.product.device')[1:]
codename = ''.join(glob_device.split())
devicename = codename
clear()
for key, values in devicesDict.items():
if key == codename:
codename = values
return codename
elif key != codename:
continue
codename = "none"
return codename
# Thanks to stackoverflow!
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def dpiChanger():
print(dashed_line)
os.system("adb shell mount /system")
print("Make sure that you made a build.prop backup! just in case")
dpi = input("Tell me what is your desired dpi: ")
print("Ok, i'll change dpi to this value!")
os.system('adb shell "grep -v "ro.sf.lcd_density" /system/build.prop > /system/build.prop.2"')
os.system('adb shell "cp /system/build.prop.2 /system/build.prop"')
os.system('adb shell "echo "ro.sf.lcd_density = ' + dpi + '" >> /system/build.prop"')
os.system('adb shell "chmod 644 /system/build.prop"')
print("Dpi has been changed!" + Fore.RESET)
os.system("adb shell umount /system")
input("push enter to continue")
print(dashed_line)
sTweaksMenu()
def mix2Cam():
print(dashed_line)
path = resPath + os.sep + "cam.apk"
os.system("adb shell mount /system")
isf = os.path.isfile(os.path.dirname(resPath) + os.sep + "cam.apk")
if not isf:
print(Fore.WHITE + "I need to download camera file first, be patient please" + Fore.RESET)
urllib.request.urlretrieve('http://www1.zippyshare.com/d/T0XrorQl/9267/cam.apk', resPath + 'cam.apk')
elif isf:
print(Fore.WHITE + "Ok, you have camera file already!" + Fore.RESET)
md5sum = md5(path)
if md5sum == localmd5s[0]:
os.system("adb push " + resPath + "cam.apk /system/priv-app/MiuiCamera/MiuiCamera.apk")
os.system("adb shell chmod 644 /system/priv-app/MiuiCamera/MiuiCamera.apk")
print(Back.BLUE + "Your old camera is still here, backed up, just in case" + Back.RESET)
os.system("adb shell umount /system")
input(Fore.GREEN + "push enter to continue" + Fore.RESET)
print(dashed_line)
sTweaksMenu()
else:
print("But it's looks like it's broken, let me re-download it!")
os.remove(path)
mix2Cam()
def comMiuiHome():
print(dashed_line)
path = resPath + os.sep + "com.miui.home"
os.system("adb shell mount /system")
os.system("adb shell mv /system/media/theme/default/com.miui.home /system/media/theme/default/com.miui.home.old")
isf = os.path.isfile(os.path.dirname(resPath) + os.sep + "com.miui.home")
if not isf:
print(Fore.WHITE + "I need to download custom home file first, be patient please" + Fore.RESET)
urllib.request.urlretrieve('http://www9.zippyshare.com/d/dRMuSMgW/9585/com.miui.home', resPath + 'com.miui.home')
elif isf:
print(Fore.WHITE + "Ok, you have custom home file already!" + Fore.RESET)
md5sum = md5(path)
if md5sum == localmd5s[1]:
os.system("adb push " + resPath + "com.miui.home /system/media/theme/default/com.miui.home")
os.system("adb shell chmod 644 /system/media/theme/default/com.miui.home")
print(Back.BLUE + "Your old com.miui.home is still here, backed up, just in case" + Back.RESET)
os.system("adb shell umount /system")
input(Fore.GREEN +"push enter to continue" + Fore.RESET)
print(dashed_line)
sTweaksMenu()
else:
os.remove(path)
print("But it's looks like it's broken, let me re-download it!")
comMiuiHome()
def bl():
os.system("adb reboot bootloader")
clear()
print(dashed_line)
print("Your bootloader status is: ")
os.system('fastboot oem device-info > results.txt 2>&1')
bl = open('results.txt', 'r').read()
os.remove('results.txt')
# bl = bl[72]+bl[73]+bl[74]+bl[75]+bl[76]
if bl[72] == "t":
bl = "Unlocked"
print(Fore.GREEN + bl + Fore.RESET)
elif bl[72] == "f":
bl = "Locked"
print(Fore.RED + bl + Fore.RESET)
print()
input(Back.BLUE + "Push enter to exit" + Back.RESET)
menu()
def sideloader():
while (True):
print(dashed_line)
print(
Fore.WHITE + "Due to problems with adb sideload implementation, you have to start sideload on your phone manually!" + Fore.RESET)
sideloadFile = input(Back.BLUE + "Drag and drop your file here: " + Back.RESET)
os.system("adb sideload " + sideloadFile)
ifContinue = input("Do you want to sideload next file? (y/n)")
ifContinue = str(ifContinue).lower()
if ifContinue == 'n':
print(Fore.WHITE + "Ok, we'll go back now" + Fore.RESET)
input("Push enter to continue")
print(dashed_line)
menu()
elif ifContinue == "y":
print(Fore.WHITE + "Ok! so here we go again" + Fore.RESET)
else:
print(
Fore.RED + "Wrong option, so we will stop now, if u want to continue sideloading, just re launch this option from menu" + Fore.RESET)
print(dashed_line)
time.sleep(5)
menu()
def remover(appList):
print(dashed_line + Fore.LIGHTCYAN_EX)
i = 1
for key, values in appList.items():
print("%i. %s" % (i, key.capitalize()))
i = i + 1
print()
print("0. Exit")
case = getInt()
i = 0
if case == 0:
clear()
sTweaksMenu()
else:
for key, values in appList.items():
pckg = values
if case == i + 1:
clear()
print(dashed_line + Fore.GREEN)
os.system("adb shell \"pm uninstall -k --user 0 %s\"" % pckg)
print (pckg)
if appList==miuiApps:
removermiui()
elif appList==googleApps:
removergoogle()
else:
i = i + 1
continue
def appremover():
print(dashed_line)
print(Fore.YELLOW + "| X.E.T |")
print("| App remover menu |")
print(dashed_line)
print(Fore.CYAN + "| 1. Miui Apps")
print(dashed_line)
print(Fore.CYAN +"| 2. Google Apps")
print(dashed_line)
print(Fore.CYAN +"| 3. Full")
print(Fore.RED + "| ^This one will remove all possible google and miui apps"+Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "| 0. Exit")
print(dashed_line)
case = getInt()
if case == 1:
clear()
remover(miuiApps)
elif case == 2:
clear()
remover(googleApps)
elif case == 3:
apps = list("")
pckg = list("")
i = 0
for key, values in googleApps.items():
apps.append(key)
pckg.append(values)
i = i + 1
continue
for key, values in miuiApps.items():
apps.append(key)
pckg.append(values)
i = i + 1
continue
print(Fore.RED + "Are you sure you want to remove: %s?" % ', '.join(apps))
case = input(Back.BLUE + "Y/N: " + Back.RESET)
if case.lower() == "y":
for x in pckg:
os.system("adb shell \" pm uninstall -k --user 0 %s\"" % x)
clear()
print(dashed_line)
print("Everything seems to be removed")
input("Press enter to go back")
sTweaksMenu()
elif case.lower() == "n":
sTweaksMenu()
elif case==0:
sTweaksMenu()
def rbMenu():
clear()
print(mydevice())
print(dashed_line)
print(Fore.YELLOW + "| X.E.T |")
print("| REBOOT MENU |")
print("| Some devices, like RN3P might have problems with reboots |")
print("| from system, but reboots should work from adb/fastboot |")
print(dashed_line + Fore.RESET)
print(Fore.CYAN + "|1. Reboot to recovery |")
print(Fore.WHITE + "|Reboot to recovery using ADB (so make sure to turn on debugging) |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|2. Reboot to fastboot |")
print(Fore.WHITE + "|Reboot to fastboot using ADB (so make sure to turn on debugging) |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|3. Reboot to system |")
print(Fore.WHITE + "|Reboot to system using ADB (so make sure to turn on debugging) |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|4. Reboot to system |")
print(Fore.WHITE + "|Reboot to system using Fastboot mode! |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|5. Reboot to adb-sideload |")
print(Fore.WHITE + "|Reboot to sideload using ADB-root (so use it when in recovery) |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|6. Boot twrp from file |")
print(Fore.WHITE + "|You can use it when you dont want to install it |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|0. Back to main menu |")
print(dashed_line + Fore.RESET)
case = getInt()
if case == 1:
clear()
os.system('adb reboot recovery')
os.system('adb kill-server')
rbMenu()
elif case == 2:
clear()
os.system('adb reboot bootloader')
os.system('adb kill-server')
rbMenu()
elif case == 3:
clear()
os.system('adb reboot')
os.system('adb kill-server')
rbMenu()
elif case == 4:
clear()
os.system('fastboot reboot')
menu()
elif case == 5:
clear()
os.system('adb reboot sideload')
menu()
elif case == 6:
clear()
twrp = input("Put twrp file here: ")
os.system('fastboot boot '+twrp)
menu()
elif case == 0:
killsystem
clear()
menu()
else:
clear()
print(Fore.RED + "Error you should choose right option!" + Fore.RESET)
input("push enter to continue")
rbMenu()
# Tweaks
def sTweaksMenu():
clear()
print(mydevice())
print(dashed_line)
print(Fore.YELLOW + "| X.E.T |")
print("| SYSTEM TWEEKS MENU |")
print(dashed_line)
print(Fore.CYAN + "|1. Build.prop backup |")
print(Fore.WHITE + "|Use it to backup your build.prop file! |")
print(dashed_line)
print(Fore.CYAN + "|2. Build.prop restore |")
print(Fore.WHITE + "|Use it to restore your build.prop file! |")
print(dashed_line)
print(Fore.CYAN + "|3. Change DPI |")
print(Fore.WHITE + "|For changing dpi more than once, you have to restore build.prop! |")
print(dashed_line)
print(Fore.CYAN + "|4. Install mix 2 camera |")
print(Fore.WHITE + "|Mix 2 camera ported for all Xiaomi devices;Tested only on miui9 |")
print(dashed_line)
print(Fore.CYAN + "|5. Install modified com.miui.home (desktop grid up to 10x10) |")
print(Fore.WHITE + "|Miui 9 exclusive |")
print(dashed_line)
print(Fore.CYAN + "|6. Activate Camera 2 API |")
print(Fore.WHITE + "|Use it to activate cam2api in your build.prop |")
print(dashed_line)
print(Fore.CYAN + "|7. System apps remover |")
print(Fore.WHITE + "|Remove google/miui apss without root, from system |")
print(dashed_line)
print(Fore.CYAN + "|0. Back to main menu |")
print(dashed_line)
case = getInt()
if case == 1:
clear()
print(dashed_line)
os.system("adb shell mount /system")
os.system("adb pull /system/build.prop " + resPath + "build.prop")
print(Fore.WHITE + "Backup complete! Your build.prop is now in res folder!" + Fore.RESET)
os.system("adb shell umount /system")
input("push enter to continue")
print(dashed_line)
sTweaksMenu()
elif case == 2:
clear()
print(dashed_line)
os.system("adb shell mount /system")
os.system("adb push " + resPath + "build.prop /system/build.prop")
os.system('adb shell "chmod 644 /system/build.prop"')
print(Fore.WHITE + "Restore complete!" + Fore.RESET)
os.system("adb shell umount /system")
input("push enter to continue")
print(dashed_line)
sTweaksMenu()
elif case == 3:
clear()
dpiChanger()
elif case == 4:
clear()
mix2Cam()
elif case == 5:
clear()
comMiuiHome()
elif case == 6:
clear()
os.system("adb shell mount /system")
os.system('adb shell "echo persist.camera.HAL3.enabled=1 >> /system/build.prop"')
print("You have enabled Camera 2 API YAY!")
os.system("adb shell umount /system")
input("push enter to continue")
sTweaksMenu()
elif case == 7:
clear()
appremover()
elif case == 8:
clear()
autoroot()
elif case == 0:
killsystem
clear()
menu()
else:
clear()
print(Fore.RED + "Error you should choose right option!" + Fore.RESET)
input("push enter to continue")
sTweaksMenu()
# about
def aboutMenu():
clear()
print(mydevice())
print(dashed_line)
print(Fore.YELLOW + "| X.E.T |")
print("| About |")
print(dashed_line)
print(Fore.CYAN + "|1. About script |")
print(dashed_line)
print(Fore.CYAN + "|2. Contact |")
print(dashed_line)
print(Fore.CYAN + "|3. Donations |")
print(dashed_line)
print(Fore.CYAN + "|4. Credits |")
print(dashed_line)
print(Fore.CYAN + "|0. Back |")
print(dashed_line)
case = getInt()
if case == 1:
print(dashed_line)
print("Simply script, created by student, to make some tweaks easier to apply")
print("First script purpose was to only automatize twrp installing (that's why repo is called twrp-installer)")
print("Script is aiming to support Xiaomi devices(Some features are universal) on both Windows and Linux")
print("When more test will be made, there will be stable executable version avalible for Windows")
print(dashed_line)
input()
aboutMenu()
elif case == 2:
print(dashed_line)
print("U can contact me on various sites, mostly under nickname Mezutelni")
print("- github.com/mezutelni/")
print("- miuipolska.pl/forum/profile/7082-mezutelni/")
print("- forum.xda-developers.com/member.php?u=6270598")
print(dashed_line)
input()
aboutMenu()
elif case == 3:
print(dashed_line)
print(
"If you want to buy me a beer, or keep my servers online, or simply say Thank You, please consider Donation for me")
print("You can do it by PayPal on PayPal.me/Mezutelni or by contacting with me directly (see contact)")
print(dashed_line)
input()
aboutMenu()
elif case == 4:
print(dashed_line)
print("Thanks to: ")
print("- Facebook group \" Złomowisko Rudej\" for inspiration and help with testing")
print("- MiuiPolska forum society for help with testing and trusting me")
print("- Orjon from MiuiPolska for idea and alpha code for google's app remover")
print(dashed_line)
input()
aboutMenu()
elif case == 0:
menu()
else:
aboutMenu()
# main
def menu():
clear()
print(mydevice())
print(dashed_line)
print(Fore.YELLOW + "| X.E.T |")
print("| Xiaomi Essential Tools |")
print(dashed_line + Fore.RESET)
print(Fore.CYAN + "|1. Reboot menu |")
print(Fore.WHITE + "|Simple reboot menu, to make your life more comfortable! |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|2. System tweaks |")
print(Fore.WHITE + "|Here you can find system tweaks, they are all applied in recovery!|" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|3. Install Recovery |")
print(Fore.WHITE + "|Use it to install recovery | Due to server problems, auto installer is off for now|" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|4. Check bootloader status (locked/unlocked) |")
print(Fore.WHITE + "|You have to be in fastboot mode to make it work |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|5. ADB sideloader |")
print(Fore.WHITE + "|Start in recovery, then use it to flash all zips you want! |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|9. About |")
print(dashed_line)
print(Fore.CYAN + "|0. Exit |")
print(dashed_line + Fore.RESET)
case = getInt()
if case == 1:
killsystem
rbMenu()
elif case == 2:
killsystem
sTweaksMenu()
elif case == 3:
killsystem
twrpInstaller(mydevice(), s)
menu()
elif case == 4:
clear()
bl()
input("push enter to continue")
menu()
elif case == 5:
killsystem
clear()
sideloader()
elif case == 9:
clear()
aboutMenu()
elif case == 0:
killsystem
print(Fore.GREEN + "Consider a donation for me to keep my servers up!")
print("www.paypal.me/Mezutelni")
sys.exit()
else:
clear()
print("Error choose right option\n" + Fore.RESET)
input("push enter to continue")
menu()
menu()
| 39.518578 | 149 | 0.539245 |
import os
import sys
import time
import urllib.request
import hashlib
try:
from colorama import Fore, Back, Style, init
except ModuleNotFoundError:
print ("You have no colorama installed, i will install it for you")
print
path = sys.executable
path = path.replace("python.exe","")
os.system(path+"/Scripts/pip install colorama")
print
print ("Ok, now you can restart script :)")
from colorama import Fore, Back, Style, init
from twrp import twrpInstaller
init()
if sys.platform == "linux" or sys.platform == "linux2":
clear = lambda: os.system('clear')
s = "l"
elif sys.platform == "win32":
clear = lambda: os.system('cls')
s = "w"
# some global variables
dashed_line = (Fore.MAGENTA + "--------------------------------------------------------------------" + Fore.RESET)
killsystem = os.system("adb kill-server")
# this is path to /res/ folder and to .py file
resPath = os.path.abspath(os.path.dirname(__file__)) + os.sep + "res" + os.sep
filePath = os.path.abspath(os.path.dirname(__file__)) + os.sep
# resPath = os.path.dirname(sys.executable)+os.sep+"res"+os.sep
# filePath = os.path.dirname(sys.executable)+os.sep
# this is list of devices with official twrp support
devices = ["cancro", "libra", "ferrari", "aqua", "gemini", "virgo", "leo", "scorpio", "jason", "tiffany", "song",
"meri", "tisson", "capricorn", "natrium", "lithium", "chiron", "sagit", "hydrogen", "oxygen", "helium",
"HM2013023", "armani", "HM2014811", "HM2014813", "omega", "lcsh92_wet_jb9", "gucci", "dior", "hermes", "ido",
"land", "hennessy", "kate", "kenzo", "nikel", "prada", "markw", "ugg", "mido", "rolex", "santoni", "mocha",
"latte", "cappu","ugglite" ]
devicesDict = {'aries': "Mi 2", 'pisces': "Mi 3 TD", 'cancro': "Mi 3 W/Mi 4", 'libra': "Mi 4c",
'ferrari': "Mi 4i", 'aqua': "Mi 4s", 'gemini': "Mi 5", 'virgo': "Mi Note",
'leo': "Mi Note Pro", 'scorpio': "Mi Note 2", 'jason': "Mi Note 3", 'tiffany': "Mi 5x",
'song': "Mi 5c", 'meri': "Mi 5c", 'tissot': "Mi A1", 'capricorn': "Mi 5s", 'natrium': "Mi 5s+",
'lithium': "Mi MIX", 'chiron': "Mi MIX 2",'polaris':'Mi MIX 2s', 'sagit': "Mi 6", 'hydrogen': "Mi MAX",
'oxygen': "Mi MAX 2", 'helium': "Mi MAX PRO",
'HM2013023': "Redmi 1 - WCDMA",
'armani': "Redmi 1s - WCDMA", 'HM2014811': "Redmi 2 - WCDMA", 'HM2014813': "Redmi 2 - TD",
'omega': "Redmi PRO", 'lcsh92_wet_jb9': "Redmi note 1 - 3g-mtk", 'gucci': "Redmi note 1s",
'dior': "Redmi Note 1 - 4g", 'hermes': "Redmi Note 2", 'ido': "Redmi 3", 'land': "Redmi 3 S/X",
'hennessy': "Redmi Note 3 (MTK)", 'kate': "Redmi Note 3 Global",
'kenzo': "Redmi Note 3 Chinese", 'nikel': "Redmi Note 4", 'prada': "Redmi 4",
'markw': "Redmi 4 pro", 'ugg': "Redmi Note 5A", 'mido': "Redmi Note 4/4x", 'rolex': "Redmi 4a",
'santoni': "Redmi 4x", 'ugglite':'Redmi Note 5A','vince':'Redmi Note 5/5+','whyred':'Redmi Note 5 Pro',
'mocha': "Mi PAD", 'latte': "Mi PAD 2", 'cappu': "Mi PAD 3"}
googleApps = {
"youtube": "com.google.android.youtube",
"drive": "com.google.android.apps.docs",
"music": "com.google.android.music",
"maps": ":com.google.android.apps.maps",
"videos": "com.google.android.videos",
"photos": "com.google.android.apps.photos",
"chrome": "com.android.chrome",
"gmail": "com.google.android.gm",
"translate": "com.google.android.apps.translate",
"duo": "com.google.android.apps.tachyon"
}
miuiApps = {
"bugreport": "com.miui.bugreport",
"compass": "com.miui.compass",
"video": "com.miui.videoplayer",
"mail": "com.android.email",
"music": "com.miui.player",
"scanner": "com.xiaomi.scanner",
"browser": "com.android.browser",
"screenrecorder": "com.miui.screenrecorder",
"gallery": "com.miui.gallery",
"updater": "com.android.updater",
"midrop": "com.xiaomi.midrop",
"calendar": "com.android.calendar",
"miui assistant": "com.mi.android.globalpersonalassistant",
"notes": "com.miui.notes",
}
localmd5s = [
"f337d1707478d63315820a45030f547d", # 0.camera
"537e17e2585e731a1c26fbd81eb2affa", # 1.home
]
def getInt():
try:
case = int(input(Back.BLUE + "choose: " + Back.RESET))
return case
except ValueError:
print()
print(Fore.RED+"Wrong, choose right option!"+Fore.RESET)
case = int(getInt())
return case
def mydevice():
os.system("adb start-server")
os.system("adb shell mount /system")
glob_device = os.system("adb shell \"cat /system/build.prop | grep ro.product.device=\" > tmp ")
glob_device = open('tmp', 'r').read()
open('tmp', "r").close()
os.remove("tmp")
os.system("adb shell umount /system")
glob_device = glob_device.lstrip('ro.product.device')[1:]
codename = ''.join(glob_device.split())
devicename = codename
clear()
for key, values in devicesDict.items():
if key == codename:
codename = values
return codename
elif key != codename:
continue
codename = "none"
return codename
# Thanks to stackoverflow!
def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def dpiChanger():
print(dashed_line)
os.system("adb shell mount /system")
print("Make sure that you made a build.prop backup! just in case")
dpi = input("Tell me what is your desired dpi: ")
print("Ok, i'll change dpi to this value!")
os.system('adb shell "grep -v "ro.sf.lcd_density" /system/build.prop > /system/build.prop.2"')
os.system('adb shell "cp /system/build.prop.2 /system/build.prop"')
os.system('adb shell "echo "ro.sf.lcd_density = ' + dpi + '" >> /system/build.prop"')
os.system('adb shell "chmod 644 /system/build.prop"')
print("Dpi has been changed!" + Fore.RESET)
os.system("adb shell umount /system")
input("push enter to continue")
print(dashed_line)
sTweaksMenu()
def mix2Cam():
print(dashed_line)
path = resPath + os.sep + "cam.apk"
os.system("adb shell mount /system")
isf = os.path.isfile(os.path.dirname(resPath) + os.sep + "cam.apk")
if not isf:
print(Fore.WHITE + "I need to download camera file first, be patient please" + Fore.RESET)
urllib.request.urlretrieve('http://www1.zippyshare.com/d/T0XrorQl/9267/cam.apk', resPath + 'cam.apk')
elif isf:
print(Fore.WHITE + "Ok, you have camera file already!" + Fore.RESET)
md5sum = md5(path)
if md5sum == localmd5s[0]:
os.system("adb push " + resPath + "cam.apk /system/priv-app/MiuiCamera/MiuiCamera.apk")
os.system("adb shell chmod 644 /system/priv-app/MiuiCamera/MiuiCamera.apk")
print(Back.BLUE + "Your old camera is still here, backed up, just in case" + Back.RESET)
os.system("adb shell umount /system")
input(Fore.GREEN + "push enter to continue" + Fore.RESET)
print(dashed_line)
sTweaksMenu()
else:
print("But it's looks like it's broken, let me re-download it!")
os.remove(path)
mix2Cam()
def comMiuiHome():
print(dashed_line)
path = resPath + os.sep + "com.miui.home"
os.system("adb shell mount /system")
os.system("adb shell mv /system/media/theme/default/com.miui.home /system/media/theme/default/com.miui.home.old")
isf = os.path.isfile(os.path.dirname(resPath) + os.sep + "com.miui.home")
if not isf:
print(Fore.WHITE + "I need to download custom home file first, be patient please" + Fore.RESET)
urllib.request.urlretrieve('http://www9.zippyshare.com/d/dRMuSMgW/9585/com.miui.home', resPath + 'com.miui.home')
elif isf:
print(Fore.WHITE + "Ok, you have custom home file already!" + Fore.RESET)
md5sum = md5(path)
if md5sum == localmd5s[1]:
os.system("adb push " + resPath + "com.miui.home /system/media/theme/default/com.miui.home")
os.system("adb shell chmod 644 /system/media/theme/default/com.miui.home")
print(Back.BLUE + "Your old com.miui.home is still here, backed up, just in case" + Back.RESET)
os.system("adb shell umount /system")
input(Fore.GREEN +"push enter to continue" + Fore.RESET)
print(dashed_line)
sTweaksMenu()
else:
os.remove(path)
print("But it's looks like it's broken, let me re-download it!")
comMiuiHome()
def bl():
os.system("adb reboot bootloader")
clear()
print(dashed_line)
print("Your bootloader status is: ")
os.system('fastboot oem device-info > results.txt 2>&1')
bl = open('results.txt', 'r').read()
os.remove('results.txt')
if bl[72] == "t":
bl = "Unlocked"
print(Fore.GREEN + bl + Fore.RESET)
elif bl[72] == "f":
bl = "Locked"
print(Fore.RED + bl + Fore.RESET)
print()
input(Back.BLUE + "Push enter to exit" + Back.RESET)
menu()
def sideloader():
while (True):
print(dashed_line)
print(
Fore.WHITE + "Due to problems with adb sideload implementation, you have to start sideload on your phone manually!" + Fore.RESET)
sideloadFile = input(Back.BLUE + "Drag and drop your file here: " + Back.RESET)
os.system("adb sideload " + sideloadFile)
ifContinue = input("Do you want to sideload next file? (y/n)")
ifContinue = str(ifContinue).lower()
if ifContinue == 'n':
print(Fore.WHITE + "Ok, we'll go back now" + Fore.RESET)
input("Push enter to continue")
print(dashed_line)
menu()
elif ifContinue == "y":
print(Fore.WHITE + "Ok! so here we go again" + Fore.RESET)
else:
print(
Fore.RED + "Wrong option, so we will stop now, if u want to continue sideloading, just re launch this option from menu" + Fore.RESET)
print(dashed_line)
time.sleep(5)
menu()
def remover(appList):
print(dashed_line + Fore.LIGHTCYAN_EX)
i = 1
for key, values in appList.items():
print("%i. %s" % (i, key.capitalize()))
i = i + 1
print()
print("0. Exit")
case = getInt()
i = 0
if case == 0:
clear()
sTweaksMenu()
else:
for key, values in appList.items():
pckg = values
if case == i + 1:
clear()
print(dashed_line + Fore.GREEN)
os.system("adb shell \"pm uninstall -k --user 0 %s\"" % pckg)
print (pckg)
if appList==miuiApps:
removermiui()
elif appList==googleApps:
removergoogle()
else:
i = i + 1
continue
def appremover():
print(dashed_line)
print(Fore.YELLOW + "| X.E.T |")
print("| App remover menu |")
print(dashed_line)
print(Fore.CYAN + "| 1. Miui Apps")
print(dashed_line)
print(Fore.CYAN +"| 2. Google Apps")
print(dashed_line)
print(Fore.CYAN +"| 3. Full")
print(Fore.RED + "| ^This one will remove all possible google and miui apps"+Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "| 0. Exit")
print(dashed_line)
case = getInt()
if case == 1:
clear()
remover(miuiApps)
elif case == 2:
clear()
remover(googleApps)
elif case == 3:
apps = list("")
pckg = list("")
i = 0
for key, values in googleApps.items():
apps.append(key)
pckg.append(values)
i = i + 1
continue
for key, values in miuiApps.items():
apps.append(key)
pckg.append(values)
i = i + 1
continue
print(Fore.RED + "Are you sure you want to remove: %s?" % ', '.join(apps))
case = input(Back.BLUE + "Y/N: " + Back.RESET)
if case.lower() == "y":
for x in pckg:
os.system("adb shell \" pm uninstall -k --user 0 %s\"" % x)
clear()
print(dashed_line)
print("Everything seems to be removed")
input("Press enter to go back")
sTweaksMenu()
elif case.lower() == "n":
sTweaksMenu()
elif case==0:
sTweaksMenu()
def rbMenu():
clear()
print(mydevice())
print(dashed_line)
print(Fore.YELLOW + "| X.E.T |")
print("| REBOOT MENU |")
print("| Some devices, like RN3P might have problems with reboots |")
print("| from system, but reboots should work from adb/fastboot |")
print(dashed_line + Fore.RESET)
print(Fore.CYAN + "|1. Reboot to recovery |")
print(Fore.WHITE + "|Reboot to recovery using ADB (so make sure to turn on debugging) |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|2. Reboot to fastboot |")
print(Fore.WHITE + "|Reboot to fastboot using ADB (so make sure to turn on debugging) |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|3. Reboot to system |")
print(Fore.WHITE + "|Reboot to system using ADB (so make sure to turn on debugging) |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|4. Reboot to system |")
print(Fore.WHITE + "|Reboot to system using Fastboot mode! |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|5. Reboot to adb-sideload |")
print(Fore.WHITE + "|Reboot to sideload using ADB-root (so use it when in recovery) |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|6. Boot twrp from file |")
print(Fore.WHITE + "|You can use it when you dont want to install it |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|0. Back to main menu |")
print(dashed_line + Fore.RESET)
case = getInt()
if case == 1:
clear()
os.system('adb reboot recovery')
os.system('adb kill-server')
rbMenu()
elif case == 2:
clear()
os.system('adb reboot bootloader')
os.system('adb kill-server')
rbMenu()
elif case == 3:
clear()
os.system('adb reboot')
os.system('adb kill-server')
rbMenu()
elif case == 4:
clear()
os.system('fastboot reboot')
menu()
elif case == 5:
clear()
os.system('adb reboot sideload')
menu()
elif case == 6:
clear()
twrp = input("Put twrp file here: ")
os.system('fastboot boot '+twrp)
menu()
elif case == 0:
killsystem
clear()
menu()
else:
clear()
print(Fore.RED + "Error you should choose right option!" + Fore.RESET)
input("push enter to continue")
rbMenu()
# Tweaks
def sTweaksMenu():
clear()
print(mydevice())
print(dashed_line)
print(Fore.YELLOW + "| X.E.T |")
print("| SYSTEM TWEEKS MENU |")
print(dashed_line)
print(Fore.CYAN + "|1. Build.prop backup |")
print(Fore.WHITE + "|Use it to backup your build.prop file! |")
print(dashed_line)
print(Fore.CYAN + "|2. Build.prop restore |")
print(Fore.WHITE + "|Use it to restore your build.prop file! |")
print(dashed_line)
print(Fore.CYAN + "|3. Change DPI |")
print(Fore.WHITE + "|For changing dpi more than once, you have to restore build.prop! |")
print(dashed_line)
print(Fore.CYAN + "|4. Install mix 2 camera |")
print(Fore.WHITE + "|Mix 2 camera ported for all Xiaomi devices;Tested only on miui9 |")
print(dashed_line)
print(Fore.CYAN + "|5. Install modified com.miui.home (desktop grid up to 10x10) |")
print(Fore.WHITE + "|Miui 9 exclusive |")
print(dashed_line)
print(Fore.CYAN + "|6. Activate Camera 2 API |")
print(Fore.WHITE + "|Use it to activate cam2api in your build.prop |")
print(dashed_line)
print(Fore.CYAN + "|7. System apps remover |")
print(Fore.WHITE + "|Remove google/miui apss without root, from system |")
print(dashed_line)
print(Fore.CYAN + "|0. Back to main menu |")
print(dashed_line)
case = getInt()
if case == 1:
clear()
print(dashed_line)
os.system("adb shell mount /system")
os.system("adb pull /system/build.prop " + resPath + "build.prop")
print(Fore.WHITE + "Backup complete! Your build.prop is now in res folder!" + Fore.RESET)
os.system("adb shell umount /system")
input("push enter to continue")
print(dashed_line)
sTweaksMenu()
elif case == 2:
clear()
print(dashed_line)
os.system("adb shell mount /system")
os.system("adb push " + resPath + "build.prop /system/build.prop")
os.system('adb shell "chmod 644 /system/build.prop"')
print(Fore.WHITE + "Restore complete!" + Fore.RESET)
os.system("adb shell umount /system")
input("push enter to continue")
print(dashed_line)
sTweaksMenu()
elif case == 3:
clear()
dpiChanger()
elif case == 4:
clear()
mix2Cam()
elif case == 5:
clear()
comMiuiHome()
elif case == 6:
clear()
os.system("adb shell mount /system")
os.system('adb shell "echo persist.camera.HAL3.enabled=1 >> /system/build.prop"')
print("You have enabled Camera 2 API YAY!")
os.system("adb shell umount /system")
input("push enter to continue")
sTweaksMenu()
elif case == 7:
clear()
appremover()
elif case == 8:
clear()
autoroot()
elif case == 0:
killsystem
clear()
menu()
else:
clear()
print(Fore.RED + "Error you should choose right option!" + Fore.RESET)
input("push enter to continue")
sTweaksMenu()
# about
def aboutMenu():
clear()
print(mydevice())
print(dashed_line)
print(Fore.YELLOW + "| X.E.T |")
print("| About |")
print(dashed_line)
print(Fore.CYAN + "|1. About script |")
print(dashed_line)
print(Fore.CYAN + "|2. Contact |")
print(dashed_line)
print(Fore.CYAN + "|3. Donations |")
print(dashed_line)
print(Fore.CYAN + "|4. Credits |")
print(dashed_line)
print(Fore.CYAN + "|0. Back |")
print(dashed_line)
case = getInt()
if case == 1:
print(dashed_line)
print("Simply script, created by student, to make some tweaks easier to apply")
print("First script purpose was to only automatize twrp installing (that's why repo is called twrp-installer)")
print("Script is aiming to support Xiaomi devices(Some features are universal) on both Windows and Linux")
print("When more test will be made, there will be stable executable version avalible for Windows")
print(dashed_line)
input()
aboutMenu()
elif case == 2:
print(dashed_line)
print("U can contact me on various sites, mostly under nickname Mezutelni")
print("- github.com/mezutelni/")
print("- miuipolska.pl/forum/profile/7082-mezutelni/")
print("- forum.xda-developers.com/member.php?u=6270598")
print(dashed_line)
input()
aboutMenu()
elif case == 3:
print(dashed_line)
print(
"If you want to buy me a beer, or keep my servers online, or simply say Thank You, please consider Donation for me")
print("You can do it by PayPal on PayPal.me/Mezutelni or by contacting with me directly (see contact)")
print(dashed_line)
input()
aboutMenu()
elif case == 4:
print(dashed_line)
print("Thanks to: ")
print("- Facebook group \" Złomowisko Rudej\" for inspiration and help with testing")
print("- MiuiPolska forum society for help with testing and trusting me")
print("- Orjon from MiuiPolska for idea and alpha code for google's app remover")
print(dashed_line)
input()
aboutMenu()
elif case == 0:
menu()
else:
aboutMenu()
# main
def menu():
clear()
print(mydevice())
print(dashed_line)
print(Fore.YELLOW + "| X.E.T |")
print("| Xiaomi Essential Tools |")
print(dashed_line + Fore.RESET)
print(Fore.CYAN + "|1. Reboot menu |")
print(Fore.WHITE + "|Simple reboot menu, to make your life more comfortable! |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|2. System tweaks |")
print(Fore.WHITE + "|Here you can find system tweaks, they are all applied in recovery!|" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|3. Install Recovery |")
print(Fore.WHITE + "|Use it to install recovery | Due to server problems, auto installer is off for now|" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|4. Check bootloader status (locked/unlocked) |")
print(Fore.WHITE + "|You have to be in fastboot mode to make it work |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|5. ADB sideloader |")
print(Fore.WHITE + "|Start in recovery, then use it to flash all zips you want! |" + Fore.RESET)
print(dashed_line)
print(Fore.CYAN + "|9. About |")
print(dashed_line)
print(Fore.CYAN + "|0. Exit |")
print(dashed_line + Fore.RESET)
case = getInt()
if case == 1:
killsystem
rbMenu()
elif case == 2:
killsystem
sTweaksMenu()
elif case == 3:
killsystem
twrpInstaller(mydevice(), s)
menu()
elif case == 4:
clear()
bl()
input("push enter to continue")
menu()
elif case == 5:
killsystem
clear()
sideloader()
elif case == 9:
clear()
aboutMenu()
elif case == 0:
killsystem
print(Fore.GREEN + "Consider a donation for me to keep my servers up!")
print("www.paypal.me/Mezutelni")
sys.exit()
else:
clear()
print("Error choose right option\n" + Fore.RESET)
input("push enter to continue")
menu()
menu()
| true | true |
f72becd780ca4f371e5aa799094ea59aac89e645 | 27,367 | py | Python | ietf/liaisons/forms.py | hassanakbar4/ietfdb | cabee059092ae776015410640226064331c293b7 | [
"BSD-3-Clause"
] | 2 | 2022-03-12T04:37:08.000Z | 2022-03-13T00:48:39.000Z | ietf/liaisons/forms.py | hassanakbar4/ietfdb | cabee059092ae776015410640226064331c293b7 | [
"BSD-3-Clause"
] | 39 | 2021-05-31T21:10:14.000Z | 2022-03-07T16:07:14.000Z | ietf/liaisons/forms.py | hassanakbar4/ietfdb | cabee059092ae776015410640226064331c293b7 | [
"BSD-3-Clause"
] | 2 | 2021-10-05T12:48:20.000Z | 2021-11-08T11:38:35.000Z | # Copyright The IETF Trust 2011-2020, All Rights Reserved
# -*- coding: utf-8 -*-
import io
import datetime, os
import operator
from typing import Union # pyflakes:ignore
from email.utils import parseaddr
from form_utils.forms import BetterModelForm
from django import forms
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db.models.query import QuerySet
from django.forms.utils import ErrorList
from django.db.models import Q
#from django.forms.widgets import RadioFieldRenderer
from django.core.validators import validate_email
import debug # pyflakes:ignore
from ietf.ietfauth.utils import has_role
from ietf.name.models import DocRelationshipName
from ietf.liaisons.utils import get_person_for_user,is_authorized_individual
from ietf.liaisons.widgets import ButtonWidget,ShowAttachmentsWidget
from ietf.liaisons.models import (LiaisonStatement,
LiaisonStatementEvent,LiaisonStatementAttachment,LiaisonStatementPurposeName)
from ietf.liaisons.fields import SearchableLiaisonStatementsField
from ietf.group.models import Group
from ietf.person.models import Email
from ietf.person.fields import SearchableEmailField
from ietf.doc.models import Document, DocAlias
from ietf.utils.fields import DatepickerDateField
from functools import reduce
'''
NOTES:
Authorized individuals are people (in our Person table) who are authorized to send
messages on behalf of some other group - they have a formal role in the other group,
whereas the liasion manager has a formal role with the IETF (or more correctly,
with the IAB).
'''
# -------------------------------------------------
# Helper Functions
# -------------------------------------------------
def liaison_manager_sdos(person):
return Group.objects.filter(type="sdo", state="active", role__person=person, role__name="liaiman").distinct()
def flatten_choices(choices):
'''Returns a flat choice list given one with option groups defined'''
flat = []
for optgroup,options in choices:
flat.extend(options)
return flat
def get_internal_choices(user):
'''Returns the set of internal IETF groups the user has permissions for, as a list
of choices suitable for use in a select widget. If user == None, all active internal
groups are included.'''
choices = []
groups = get_groups_for_person(user.person if user else None)
main = [ (g.pk, 'The {}'.format(g.acronym.upper())) for g in groups.filter(acronym__in=('ietf','iesg','iab')) ]
areas = [ (g.pk, '{} - {}'.format(g.acronym,g.name)) for g in groups.filter(type='area') ]
wgs = [ (g.pk, '{} - {}'.format(g.acronym,g.name)) for g in groups.filter(type='wg') ]
choices.append(('Main IETF Entities', main))
choices.append(('IETF Areas', areas))
choices.append(('IETF Working Groups', wgs ))
return choices
def get_groups_for_person(person):
'''Returns queryset of internal Groups the person has interesting roles in.
This is a refactor of IETFHierarchyManager.get_entities_for_person(). If Person
is None or Secretariat or Liaison Manager all internal IETF groups are returned.
'''
if person == None or has_role(person.user, "Secretariat") or has_role(person.user, "Liaison Manager"):
# collect all internal IETF groups
queries = [Q(acronym__in=('ietf','iesg','iab')),
Q(type='area',state='active'),
Q(type='wg',state='active')]
else:
# Interesting roles, as Group queries
queries = [Q(role__person=person,role__name='chair',acronym='ietf'),
Q(role__person=person,role__name__in=('chair','execdir'),acronym='iab'),
Q(role__person=person,role__name='ad',type='area',state='active'),
Q(role__person=person,role__name__in=('chair','secretary'),type='wg',state='active'),
Q(parent__role__person=person,parent__role__name='ad',type='wg',state='active')]
return Group.objects.filter(reduce(operator.or_,queries)).order_by('acronym').distinct()
def liaison_form_factory(request, type=None, **kwargs):
"""Returns appropriate Liaison entry form"""
user = request.user
if kwargs.get('instance',None):
return EditLiaisonForm(user, **kwargs)
elif type == 'incoming':
return IncomingLiaisonForm(user, **kwargs)
elif type == 'outgoing':
return OutgoingLiaisonForm(user, **kwargs)
return None
def validate_emails(value):
'''Custom validator for emails'''
value = value.strip() # strip whitespace
if '\r\n' in value: # cc_contacts has newlines
value = value.replace('\r\n',',')
value = value.rstrip(',') # strip trailing comma
emails = value.split(',')
for email in emails:
name, addr = parseaddr(email)
try:
validate_email(addr)
except ValidationError:
raise forms.ValidationError('Invalid email address: %s' % addr)
try:
addr.encode('ascii')
except UnicodeEncodeError as e:
raise forms.ValidationError('Invalid email address: %s (check character %d)' % (addr,e.start))
# -------------------------------------------------
# Form Classes
# -------------------------------------------------
class AddCommentForm(forms.Form):
comment = forms.CharField(required=True, widget=forms.Textarea, strip=False)
private = forms.BooleanField(label="Private comment", required=False,help_text="If this box is checked the comment will not appear in the statement's public history view.")
# class RadioRenderer(RadioFieldRenderer):
# def render(self):
# output = []
# for widget in self:
# output.append(format_html(force_text(widget)))
# return mark_safe('\n'.join(output))
class SearchLiaisonForm(forms.Form):
'''Expects initial keyword argument queryset which then gets filtered based on form data'''
text = forms.CharField(required=False)
# scope = forms.ChoiceField(choices=(("all", "All text fields"), ("title", "Title field")), required=False, initial='title')
source = forms.CharField(required=False)
destination = forms.CharField(required=False)
start_date = DatepickerDateField(date_format="yyyy-mm-dd", picker_settings={"autoclose": "1" }, label='Start date', required=False)
end_date = DatepickerDateField(date_format="yyyy-mm-dd", picker_settings={"autoclose": "1" }, label='End date', required=False)
def __init__(self, *args, **kwargs):
self.queryset = kwargs.pop('queryset')
super(SearchLiaisonForm, self).__init__(*args, **kwargs)
def get_results(self):
results = self.queryset
if self.is_bound:
query = self.cleaned_data.get('text')
if query:
q = (Q(title__icontains=query) |
Q(from_contact__address__icontains=query) |
Q(to_contacts__icontains=query) |
Q(other_identifiers__icontains=query) |
Q(body__icontains=query) |
Q(attachments__title__icontains=query,liaisonstatementattachment__removed=False) |
Q(technical_contacts__icontains=query) |
Q(action_holder_contacts__icontains=query) |
Q(cc_contacts=query) |
Q(response_contacts__icontains=query))
results = results.filter(q)
source = self.cleaned_data.get('source')
if source:
source_list = source.split(',')
if len(source_list) > 1:
results = results.filter(Q(from_groups__acronym__in=source_list))
else:
results = results.filter(Q(from_groups__name__icontains=source) | Q(from_groups__acronym__iexact=source))
destination = self.cleaned_data.get('destination')
if destination:
destination_list = destination.split(',')
if len(destination_list) > 1:
results = results.filter(Q(to_groups__acronym__in=destination_list))
else:
results = results.filter(Q(to_groups__name__icontains=destination) | Q(to_groups__acronym__iexact=destination))
start_date = self.cleaned_data.get('start_date')
end_date = self.cleaned_data.get('end_date')
events = None
if start_date:
events = LiaisonStatementEvent.objects.filter(type='posted', time__gte=start_date)
if end_date:
events = events.filter(time__lte=end_date)
elif end_date:
events = LiaisonStatementEvent.objects.filter(type='posted', time__lte=end_date)
if events:
results = results.filter(liaisonstatementevent__in=events)
results = results.distinct().order_by('title')
return results
class CustomModelMultipleChoiceField(forms.ModelMultipleChoiceField):
'''If value is a QuerySet, return it as is (for use in widget.render)'''
def prepare_value(self, value):
if isinstance(value, QuerySet):
return value
if (hasattr(value, '__iter__') and
not isinstance(value, str) and
not hasattr(value, '_meta')):
return [super(CustomModelMultipleChoiceField, self).prepare_value(v) for v in value]
return super(CustomModelMultipleChoiceField, self).prepare_value(value)
class LiaisonModelForm(BetterModelForm):
'''Specify fields which require a custom widget or that are not part of the model.
NOTE: from_groups and to_groups are marked as not required because select2 has
a problem with validating
'''
from_groups = forms.ModelMultipleChoiceField(queryset=Group.objects.all(),label='Groups',required=False)
from_contact = forms.EmailField() # type: Union[forms.EmailField, SearchableEmailField]
to_contacts = forms.CharField(label="Contacts", widget=forms.Textarea(attrs={'rows':'3', }), strip=False)
to_groups = forms.ModelMultipleChoiceField(queryset=Group.objects,label='Groups',required=False)
deadline = DatepickerDateField(date_format="yyyy-mm-dd", picker_settings={"autoclose": "1" }, label='Deadline', required=True)
related_to = SearchableLiaisonStatementsField(label='Related Liaison Statement', required=False)
submitted_date = DatepickerDateField(date_format="yyyy-mm-dd", picker_settings={"autoclose": "1" }, label='Submission date', required=True, initial=datetime.date.today())
attachments = CustomModelMultipleChoiceField(queryset=Document.objects,label='Attachments', widget=ShowAttachmentsWidget, required=False)
attach_title = forms.CharField(label='Title', required=False)
attach_file = forms.FileField(label='File', required=False)
attach_button = forms.CharField(label='',
widget=ButtonWidget(label='Attach', show_on='id_attachments',
require=['id_attach_title', 'id_attach_file'],
required_label='title and file'),
required=False)
class Meta:
model = LiaisonStatement
exclude = ('attachments','state','from_name','to_name')
fieldsets = [('From', {'fields': ['from_groups','from_contact', 'response_contacts'], 'legend': ''}),
('To', {'fields': ['to_groups','to_contacts'], 'legend': ''}),
('Other email addresses', {'fields': ['technical_contacts','action_holder_contacts','cc_contacts'], 'legend': ''}),
('Purpose', {'fields':['purpose', 'deadline'], 'legend': ''}),
('Reference', {'fields': ['other_identifiers','related_to'], 'legend': ''}),
('Liaison Statement', {'fields': ['title', 'submitted_date', 'body', 'attachments'], 'legend': ''}),
('Add attachment', {'fields': ['attach_title', 'attach_file', 'attach_button'], 'legend': ''})]
def __init__(self, user, *args, **kwargs):
super(LiaisonModelForm, self).__init__(*args, **kwargs)
self.user = user
self.edit = False
self.person = get_person_for_user(user)
self.is_new = not self.instance.pk
self.fields["from_groups"].widget.attrs["placeholder"] = "Type in name to search for group"
self.fields["to_groups"].widget.attrs["placeholder"] = "Type in name to search for group"
self.fields["to_contacts"].label = 'Contacts'
self.fields["other_identifiers"].widget.attrs["rows"] = 2
# add email validators
for field in ['from_contact','to_contacts','technical_contacts','action_holder_contacts','cc_contacts']:
if field in self.fields:
self.fields[field].validators.append(validate_emails)
self.set_from_fields()
self.set_to_fields()
def clean_from_groups(self):
from_groups = self.cleaned_data.get('from_groups')
if not from_groups:
raise forms.ValidationError('You must specify a From Group')
return from_groups
def clean_to_groups(self):
to_groups = self.cleaned_data.get('to_groups')
if not to_groups:
raise forms.ValidationError('You must specify a To Group')
return to_groups
def clean_from_contact(self):
contact = self.cleaned_data.get('from_contact')
from_groups = self.cleaned_data.get('from_groups')
try:
email = Email.objects.get(address=contact)
if not email.origin:
email.origin = "liaison: %s" % (','.join([ g.acronym for g in from_groups.all() ]))
email.save()
except ObjectDoesNotExist:
raise forms.ValidationError('Email address does not exist')
return email
# Note to future person: This is the wrong place to fix the new lines
# in cc_contacts and to_contacts. Those belong in the save function.
# Or at least somewhere other than here.
def clean_cc_contacts(self):
'''Return a comma separated list of addresses'''
cc_contacts = self.cleaned_data.get('cc_contacts')
cc_contacts = cc_contacts.replace('\r\n',',')
cc_contacts = cc_contacts.rstrip(',')
return cc_contacts
## to_contacts can also have new lines
def clean_to_contacts(self):
'''Return a comma separated list of addresses'''
to_contacts = self.cleaned_data.get('to_contacts')
to_contacts = to_contacts.replace('\r\n',',')
to_contacts = to_contacts.rstrip(',')
return to_contacts
def clean(self):
if not self.cleaned_data.get('body', None) and not self.has_attachments():
self._errors['body'] = ErrorList(['You must provide a body or attachment files'])
self._errors['attachments'] = ErrorList(['You must provide a body or attachment files'])
# if purpose=response there must be a related statement
purpose = LiaisonStatementPurposeName.objects.get(slug='response')
if self.cleaned_data.get('purpose') == purpose and not self.cleaned_data.get('related_to'):
self._errors['related_to'] = ErrorList(['You must provide a related statement when purpose is In Response'])
return self.cleaned_data
def full_clean(self):
self.set_required_fields()
super(LiaisonModelForm, self).full_clean()
self.reset_required_fields()
def has_attachments(self):
for key in list(self.files.keys()):
if key.startswith('attach_file_') and key.replace('file', 'title') in list(self.data.keys()):
return True
return False
def is_approved(self):
assert NotImplemented
def save(self, *args, **kwargs):
super(LiaisonModelForm, self).save(*args,**kwargs)
# set state for new statements
if self.is_new:
self.instance.change_state(state_id='pending',person=self.person)
if self.is_approved():
self.instance.change_state(state_id='posted',person=self.person)
else:
# create modified event
LiaisonStatementEvent.objects.create(
type_id='modified',
by=self.person,
statement=self.instance,
desc='Statement Modified'
)
self.save_related_liaisons()
self.save_attachments()
self.save_tags()
return self.instance
def save_attachments(self):
'''Saves new attachments.
Files come in with keys like "attach_file_N" where N is index of attachments
displayed in the form. The attachment title is in the corresponding
request.POST[attach_title_N]
'''
written = self.instance.attachments.all().count()
for key in list(self.files.keys()):
title_key = key.replace('file', 'title')
attachment_title = self.data.get(title_key)
if not key.startswith('attach_file_') or not title_key in list(self.data.keys()):
continue
attached_file = self.files.get(key)
extension=attached_file.name.rsplit('.', 1)
if len(extension) > 1:
extension = '.' + extension[1]
else:
extension = ''
written += 1
name = self.instance.name() + ("-attachment-%s" % written)
attach, created = Document.objects.get_or_create(
name = name,
defaults=dict(
title = attachment_title,
type_id = "liai-att",
uploaded_filename = name + extension,
)
)
if created:
DocAlias.objects.create(name=attach.name).docs.add(attach)
LiaisonStatementAttachment.objects.create(statement=self.instance,document=attach)
attach_file = io.open(os.path.join(settings.LIAISON_ATTACH_PATH, attach.name + extension), 'wb')
attach_file.write(attached_file.read())
attach_file.close()
if not self.is_new:
# create modified event
LiaisonStatementEvent.objects.create(
type_id='modified',
by=self.person,
statement=self.instance,
desc='Added attachment: {}'.format(attachment_title)
)
def save_related_liaisons(self):
rel = DocRelationshipName.objects.get(slug='refold')
new_related = self.cleaned_data.get('related_to', [])
# add new ones
for stmt in new_related:
self.instance.source_of_set.get_or_create(target=stmt,relationship=rel)
# delete removed ones
for related in self.instance.source_of_set.all():
if related.target not in new_related:
related.delete()
def save_tags(self):
'''Create tags as needed'''
if self.instance.deadline and not self.instance.tags.filter(slug='taken'):
self.instance.tags.add('required')
def set_from_fields(self):
assert NotImplemented
def set_required_fields(self):
purpose = self.data.get('purpose', None)
if purpose in ['action', 'comment']:
self.fields['deadline'].required = True
else:
self.fields['deadline'].required = False
def reset_required_fields(self):
self.fields['deadline'].required = True
def set_to_fields(self):
assert NotImplemented
class IncomingLiaisonForm(LiaisonModelForm):
def clean(self):
if 'send' in list(self.data.keys()) and self.get_post_only():
raise forms.ValidationError('As an IETF Liaison Manager you can not send incoming liaison statements, you only can post them')
return super(IncomingLiaisonForm, self).clean()
def is_approved(self):
'''Incoming Liaison Statements do not required approval'''
return True
def get_post_only(self):
from_groups = self.cleaned_data.get('from_groups')
if has_role(self.user, "Secretariat") or is_authorized_individual(self.user,from_groups):
return False
return True
def set_from_fields(self):
'''Set from_groups and from_contact options and initial value based on user
accessing the form.'''
if has_role(self.user, "Secretariat"):
queryset = Group.objects.filter(type="sdo", state="active").order_by('name')
else:
queryset = Group.objects.filter(type="sdo", state="active", role__person=self.person, role__name__in=("liaiman", "auth")).distinct().order_by('name')
self.fields['from_contact'].initial = self.person.role_set.filter(group=queryset[0]).first().email.address
self.fields['from_contact'].widget.attrs['readonly'] = True
self.fields['from_groups'].queryset = queryset
self.fields['from_groups'].widget.submitter = str(self.person)
# if there's only one possibility make it the default
if len(queryset) == 1:
self.fields['from_groups'].initial = queryset
def set_to_fields(self):
'''Set to_groups and to_contacts options and initial value based on user
accessing the form. For incoming Liaisons, to_groups choices is the full set.
'''
self.fields['to_groups'].choices = get_internal_choices(None)
class OutgoingLiaisonForm(LiaisonModelForm):
from_contact = SearchableEmailField(only_users=True)
approved = forms.BooleanField(label="Obtained prior approval", required=False)
class Meta:
model = LiaisonStatement
exclude = ('attachments','state','from_name','to_name','action_holder_contacts')
# add approved field, no action_holder_contacts
fieldsets = [('From', {'fields': ['from_groups','from_contact','response_contacts','approved'], 'legend': ''}),
('To', {'fields': ['to_groups','to_contacts'], 'legend': ''}),
('Other email addresses', {'fields': ['technical_contacts','cc_contacts'], 'legend': ''}),
('Purpose', {'fields':['purpose', 'deadline'], 'legend': ''}),
('Reference', {'fields': ['other_identifiers','related_to'], 'legend': ''}),
('Liaison Statement', {'fields': ['title', 'submitted_date', 'body', 'attachments'], 'legend': ''}),
('Add attachment', {'fields': ['attach_title', 'attach_file', 'attach_button'], 'legend': ''})]
def is_approved(self):
return self.cleaned_data['approved']
def set_from_fields(self):
'''Set from_groups and from_contact options and initial value based on user
accessing the form'''
choices = get_internal_choices(self.user)
self.fields['from_groups'].choices = choices
# set initial value if only one entry
flat_choices = flatten_choices(choices)
if len(flat_choices) == 1:
self.fields['from_groups'].initial = [flat_choices[0][0]]
if has_role(self.user, "Secretariat"):
return
if self.person.role_set.filter(name='liaiman',group__state='active'):
email = self.person.role_set.filter(name='liaiman',group__state='active').first().email.address
elif self.person.role_set.filter(name__in=('ad','chair'),group__state='active'):
email = self.person.role_set.filter(name__in=('ad','chair'),group__state='active').first().email.address
else:
email = self.person.email_address()
self.fields['from_contact'].initial = email
self.fields['from_contact'].widget.attrs['readonly'] = True
def set_to_fields(self):
'''Set to_groups and to_contacts options and initial value based on user
accessing the form'''
# set options. if the user is a Liaison Manager and nothing more, reduce set to his SDOs
if has_role(self.user, "Liaison Manager") and not self.person.role_set.filter(name__in=('ad','chair'),group__state='active'):
queryset = Group.objects.filter(type="sdo", state="active", role__person=self.person, role__name="liaiman").distinct().order_by('name')
else:
# get all outgoing entities
queryset = Group.objects.filter(type="sdo", state="active").order_by('name')
self.fields['to_groups'].queryset = queryset
# set initial
if has_role(self.user, "Liaison Manager"):
self.fields['to_groups'].initial = [queryset.first()]
class EditLiaisonForm(LiaisonModelForm):
def __init__(self, *args, **kwargs):
super(EditLiaisonForm, self).__init__(*args, **kwargs)
self.edit = True
self.fields['attachments'].initial = self.instance.liaisonstatementattachment_set.exclude(removed=True)
related = [ str(x.pk) for x in self.instance.source_of_set.all() ]
self.fields['related_to'].initial = ','.join(related)
self.fields['submitted_date'].initial = self.instance.submitted
def save(self, *args, **kwargs):
super(EditLiaisonForm, self).save(*args,**kwargs)
if self.has_changed() and 'submitted_date' in self.changed_data:
event = self.instance.liaisonstatementevent_set.filter(type='submitted').first()
event.time = self.cleaned_data.get('submitted_date')
event.save()
return self.instance
def set_from_fields(self):
'''Set from_groups and from_contact options and initial value based on user
accessing the form.'''
if self.instance.is_outgoing():
self.fields['from_groups'].choices = get_internal_choices(self.user)
else:
if has_role(self.user, "Secretariat"):
queryset = Group.objects.filter(type="sdo").order_by('name')
else:
queryset = Group.objects.filter(type="sdo", role__person=self.person, role__name__in=("liaiman", "auth")).distinct().order_by('name')
self.fields['from_contact'].widget.attrs['readonly'] = True
self.fields['from_groups'].queryset = queryset
def set_to_fields(self):
'''Set to_groups and to_contacts options and initial value based on user
accessing the form. For incoming Liaisons, to_groups choices is the full set.
'''
if self.instance.is_outgoing():
# if the user is a Liaison Manager and nothing more, reduce to set to his SDOs
if has_role(self.user, "Liaison Manager") and not self.person.role_set.filter(name__in=('ad','chair'),group__state='active'):
queryset = Group.objects.filter(type="sdo", role__person=self.person, role__name="liaiman").distinct().order_by('name')
else:
# get all outgoing entities
queryset = Group.objects.filter(type="sdo").order_by('name')
self.fields['to_groups'].queryset = queryset
else:
self.fields['to_groups'].choices = get_internal_choices(None)
class EditAttachmentForm(forms.Form):
title = forms.CharField(max_length=255)
| 47.512153 | 176 | 0.637227 |
import io
import datetime, os
import operator
from typing import Union
from email.utils import parseaddr
from form_utils.forms import BetterModelForm
from django import forms
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db.models.query import QuerySet
from django.forms.utils import ErrorList
from django.db.models import Q
from django.core.validators import validate_email
import debug
from ietf.ietfauth.utils import has_role
from ietf.name.models import DocRelationshipName
from ietf.liaisons.utils import get_person_for_user,is_authorized_individual
from ietf.liaisons.widgets import ButtonWidget,ShowAttachmentsWidget
from ietf.liaisons.models import (LiaisonStatement,
LiaisonStatementEvent,LiaisonStatementAttachment,LiaisonStatementPurposeName)
from ietf.liaisons.fields import SearchableLiaisonStatementsField
from ietf.group.models import Group
from ietf.person.models import Email
from ietf.person.fields import SearchableEmailField
from ietf.doc.models import Document, DocAlias
from ietf.utils.fields import DatepickerDateField
from functools import reduce
def liaison_manager_sdos(person):
return Group.objects.filter(type="sdo", state="active", role__person=person, role__name="liaiman").distinct()
def flatten_choices(choices):
flat = []
for optgroup,options in choices:
flat.extend(options)
return flat
def get_internal_choices(user):
choices = []
groups = get_groups_for_person(user.person if user else None)
main = [ (g.pk, 'The {}'.format(g.acronym.upper())) for g in groups.filter(acronym__in=('ietf','iesg','iab')) ]
areas = [ (g.pk, '{} - {}'.format(g.acronym,g.name)) for g in groups.filter(type='area') ]
wgs = [ (g.pk, '{} - {}'.format(g.acronym,g.name)) for g in groups.filter(type='wg') ]
choices.append(('Main IETF Entities', main))
choices.append(('IETF Areas', areas))
choices.append(('IETF Working Groups', wgs ))
return choices
def get_groups_for_person(person):
if person == None or has_role(person.user, "Secretariat") or has_role(person.user, "Liaison Manager"):
queries = [Q(acronym__in=('ietf','iesg','iab')),
Q(type='area',state='active'),
Q(type='wg',state='active')]
else:
queries = [Q(role__person=person,role__name='chair',acronym='ietf'),
Q(role__person=person,role__name__in=('chair','execdir'),acronym='iab'),
Q(role__person=person,role__name='ad',type='area',state='active'),
Q(role__person=person,role__name__in=('chair','secretary'),type='wg',state='active'),
Q(parent__role__person=person,parent__role__name='ad',type='wg',state='active')]
return Group.objects.filter(reduce(operator.or_,queries)).order_by('acronym').distinct()
def liaison_form_factory(request, type=None, **kwargs):
user = request.user
if kwargs.get('instance',None):
return EditLiaisonForm(user, **kwargs)
elif type == 'incoming':
return IncomingLiaisonForm(user, **kwargs)
elif type == 'outgoing':
return OutgoingLiaisonForm(user, **kwargs)
return None
def validate_emails(value):
value = value.strip()
if '\r\n' in value:
value = value.replace('\r\n',',')
value = value.rstrip(',')
emails = value.split(',')
for email in emails:
name, addr = parseaddr(email)
try:
validate_email(addr)
except ValidationError:
raise forms.ValidationError('Invalid email address: %s' % addr)
try:
addr.encode('ascii')
except UnicodeEncodeError as e:
raise forms.ValidationError('Invalid email address: %s (check character %d)' % (addr,e.start))
class AddCommentForm(forms.Form):
comment = forms.CharField(required=True, widget=forms.Textarea, strip=False)
private = forms.BooleanField(label="Private comment", required=False,help_text="If this box is checked the comment will not appear in the statement's public history view.")
# class RadioRenderer(RadioFieldRenderer):
# def render(self):
# output = []
# for widget in self:
# output.append(format_html(force_text(widget)))
# return mark_safe('\n'.join(output))
class SearchLiaisonForm(forms.Form):
text = forms.CharField(required=False)
# scope = forms.ChoiceField(choices=(("all", "All text fields"), ("title", "Title field")), required=False, initial='title')
source = forms.CharField(required=False)
destination = forms.CharField(required=False)
start_date = DatepickerDateField(date_format="yyyy-mm-dd", picker_settings={"autoclose": "1" }, label='Start date', required=False)
end_date = DatepickerDateField(date_format="yyyy-mm-dd", picker_settings={"autoclose": "1" }, label='End date', required=False)
def __init__(self, *args, **kwargs):
self.queryset = kwargs.pop('queryset')
super(SearchLiaisonForm, self).__init__(*args, **kwargs)
def get_results(self):
results = self.queryset
if self.is_bound:
query = self.cleaned_data.get('text')
if query:
q = (Q(title__icontains=query) |
Q(from_contact__address__icontains=query) |
Q(to_contacts__icontains=query) |
Q(other_identifiers__icontains=query) |
Q(body__icontains=query) |
Q(attachments__title__icontains=query,liaisonstatementattachment__removed=False) |
Q(technical_contacts__icontains=query) |
Q(action_holder_contacts__icontains=query) |
Q(cc_contacts=query) |
Q(response_contacts__icontains=query))
results = results.filter(q)
source = self.cleaned_data.get('source')
if source:
source_list = source.split(',')
if len(source_list) > 1:
results = results.filter(Q(from_groups__acronym__in=source_list))
else:
results = results.filter(Q(from_groups__name__icontains=source) | Q(from_groups__acronym__iexact=source))
destination = self.cleaned_data.get('destination')
if destination:
destination_list = destination.split(',')
if len(destination_list) > 1:
results = results.filter(Q(to_groups__acronym__in=destination_list))
else:
results = results.filter(Q(to_groups__name__icontains=destination) | Q(to_groups__acronym__iexact=destination))
start_date = self.cleaned_data.get('start_date')
end_date = self.cleaned_data.get('end_date')
events = None
if start_date:
events = LiaisonStatementEvent.objects.filter(type='posted', time__gte=start_date)
if end_date:
events = events.filter(time__lte=end_date)
elif end_date:
events = LiaisonStatementEvent.objects.filter(type='posted', time__lte=end_date)
if events:
results = results.filter(liaisonstatementevent__in=events)
results = results.distinct().order_by('title')
return results
class CustomModelMultipleChoiceField(forms.ModelMultipleChoiceField):
def prepare_value(self, value):
if isinstance(value, QuerySet):
return value
if (hasattr(value, '__iter__') and
not isinstance(value, str) and
not hasattr(value, '_meta')):
return [super(CustomModelMultipleChoiceField, self).prepare_value(v) for v in value]
return super(CustomModelMultipleChoiceField, self).prepare_value(value)
class LiaisonModelForm(BetterModelForm):
from_groups = forms.ModelMultipleChoiceField(queryset=Group.objects.all(),label='Groups',required=False)
from_contact = forms.EmailField() # type: Union[forms.EmailField, SearchableEmailField]
to_contacts = forms.CharField(label="Contacts", widget=forms.Textarea(attrs={'rows':'3', }), strip=False)
to_groups = forms.ModelMultipleChoiceField(queryset=Group.objects,label='Groups',required=False)
deadline = DatepickerDateField(date_format="yyyy-mm-dd", picker_settings={"autoclose": "1" }, label='Deadline', required=True)
related_to = SearchableLiaisonStatementsField(label='Related Liaison Statement', required=False)
submitted_date = DatepickerDateField(date_format="yyyy-mm-dd", picker_settings={"autoclose": "1" }, label='Submission date', required=True, initial=datetime.date.today())
attachments = CustomModelMultipleChoiceField(queryset=Document.objects,label='Attachments', widget=ShowAttachmentsWidget, required=False)
attach_title = forms.CharField(label='Title', required=False)
attach_file = forms.FileField(label='File', required=False)
attach_button = forms.CharField(label='',
widget=ButtonWidget(label='Attach', show_on='id_attachments',
require=['id_attach_title', 'id_attach_file'],
required_label='title and file'),
required=False)
class Meta:
model = LiaisonStatement
exclude = ('attachments','state','from_name','to_name')
fieldsets = [('From', {'fields': ['from_groups','from_contact', 'response_contacts'], 'legend': ''}),
('To', {'fields': ['to_groups','to_contacts'], 'legend': ''}),
('Other email addresses', {'fields': ['technical_contacts','action_holder_contacts','cc_contacts'], 'legend': ''}),
('Purpose', {'fields':['purpose', 'deadline'], 'legend': ''}),
('Reference', {'fields': ['other_identifiers','related_to'], 'legend': ''}),
('Liaison Statement', {'fields': ['title', 'submitted_date', 'body', 'attachments'], 'legend': ''}),
('Add attachment', {'fields': ['attach_title', 'attach_file', 'attach_button'], 'legend': ''})]
def __init__(self, user, *args, **kwargs):
super(LiaisonModelForm, self).__init__(*args, **kwargs)
self.user = user
self.edit = False
self.person = get_person_for_user(user)
self.is_new = not self.instance.pk
self.fields["from_groups"].widget.attrs["placeholder"] = "Type in name to search for group"
self.fields["to_groups"].widget.attrs["placeholder"] = "Type in name to search for group"
self.fields["to_contacts"].label = 'Contacts'
self.fields["other_identifiers"].widget.attrs["rows"] = 2
# add email validators
for field in ['from_contact','to_contacts','technical_contacts','action_holder_contacts','cc_contacts']:
if field in self.fields:
self.fields[field].validators.append(validate_emails)
self.set_from_fields()
self.set_to_fields()
def clean_from_groups(self):
from_groups = self.cleaned_data.get('from_groups')
if not from_groups:
raise forms.ValidationError('You must specify a From Group')
return from_groups
def clean_to_groups(self):
to_groups = self.cleaned_data.get('to_groups')
if not to_groups:
raise forms.ValidationError('You must specify a To Group')
return to_groups
def clean_from_contact(self):
contact = self.cleaned_data.get('from_contact')
from_groups = self.cleaned_data.get('from_groups')
try:
email = Email.objects.get(address=contact)
if not email.origin:
email.origin = "liaison: %s" % (','.join([ g.acronym for g in from_groups.all() ]))
email.save()
except ObjectDoesNotExist:
raise forms.ValidationError('Email address does not exist')
return email
# Note to future person: This is the wrong place to fix the new lines
# in cc_contacts and to_contacts. Those belong in the save function.
# Or at least somewhere other than here.
def clean_cc_contacts(self):
cc_contacts = self.cleaned_data.get('cc_contacts')
cc_contacts = cc_contacts.replace('\r\n',',')
cc_contacts = cc_contacts.rstrip(',')
return cc_contacts
## to_contacts can also have new lines
def clean_to_contacts(self):
to_contacts = self.cleaned_data.get('to_contacts')
to_contacts = to_contacts.replace('\r\n',',')
to_contacts = to_contacts.rstrip(',')
return to_contacts
def clean(self):
if not self.cleaned_data.get('body', None) and not self.has_attachments():
self._errors['body'] = ErrorList(['You must provide a body or attachment files'])
self._errors['attachments'] = ErrorList(['You must provide a body or attachment files'])
# if purpose=response there must be a related statement
purpose = LiaisonStatementPurposeName.objects.get(slug='response')
if self.cleaned_data.get('purpose') == purpose and not self.cleaned_data.get('related_to'):
self._errors['related_to'] = ErrorList(['You must provide a related statement when purpose is In Response'])
return self.cleaned_data
def full_clean(self):
self.set_required_fields()
super(LiaisonModelForm, self).full_clean()
self.reset_required_fields()
def has_attachments(self):
for key in list(self.files.keys()):
if key.startswith('attach_file_') and key.replace('file', 'title') in list(self.data.keys()):
return True
return False
def is_approved(self):
assert NotImplemented
def save(self, *args, **kwargs):
super(LiaisonModelForm, self).save(*args,**kwargs)
# set state for new statements
if self.is_new:
self.instance.change_state(state_id='pending',person=self.person)
if self.is_approved():
self.instance.change_state(state_id='posted',person=self.person)
else:
# create modified event
LiaisonStatementEvent.objects.create(
type_id='modified',
by=self.person,
statement=self.instance,
desc='Statement Modified'
)
self.save_related_liaisons()
self.save_attachments()
self.save_tags()
return self.instance
def save_attachments(self):
written = self.instance.attachments.all().count()
for key in list(self.files.keys()):
title_key = key.replace('file', 'title')
attachment_title = self.data.get(title_key)
if not key.startswith('attach_file_') or not title_key in list(self.data.keys()):
continue
attached_file = self.files.get(key)
extension=attached_file.name.rsplit('.', 1)
if len(extension) > 1:
extension = '.' + extension[1]
else:
extension = ''
written += 1
name = self.instance.name() + ("-attachment-%s" % written)
attach, created = Document.objects.get_or_create(
name = name,
defaults=dict(
title = attachment_title,
type_id = "liai-att",
uploaded_filename = name + extension,
)
)
if created:
DocAlias.objects.create(name=attach.name).docs.add(attach)
LiaisonStatementAttachment.objects.create(statement=self.instance,document=attach)
attach_file = io.open(os.path.join(settings.LIAISON_ATTACH_PATH, attach.name + extension), 'wb')
attach_file.write(attached_file.read())
attach_file.close()
if not self.is_new:
# create modified event
LiaisonStatementEvent.objects.create(
type_id='modified',
by=self.person,
statement=self.instance,
desc='Added attachment: {}'.format(attachment_title)
)
def save_related_liaisons(self):
rel = DocRelationshipName.objects.get(slug='refold')
new_related = self.cleaned_data.get('related_to', [])
# add new ones
for stmt in new_related:
self.instance.source_of_set.get_or_create(target=stmt,relationship=rel)
# delete removed ones
for related in self.instance.source_of_set.all():
if related.target not in new_related:
related.delete()
def save_tags(self):
if self.instance.deadline and not self.instance.tags.filter(slug='taken'):
self.instance.tags.add('required')
def set_from_fields(self):
assert NotImplemented
def set_required_fields(self):
purpose = self.data.get('purpose', None)
if purpose in ['action', 'comment']:
self.fields['deadline'].required = True
else:
self.fields['deadline'].required = False
def reset_required_fields(self):
self.fields['deadline'].required = True
def set_to_fields(self):
assert NotImplemented
class IncomingLiaisonForm(LiaisonModelForm):
def clean(self):
if 'send' in list(self.data.keys()) and self.get_post_only():
raise forms.ValidationError('As an IETF Liaison Manager you can not send incoming liaison statements, you only can post them')
return super(IncomingLiaisonForm, self).clean()
def is_approved(self):
return True
def get_post_only(self):
from_groups = self.cleaned_data.get('from_groups')
if has_role(self.user, "Secretariat") or is_authorized_individual(self.user,from_groups):
return False
return True
def set_from_fields(self):
if has_role(self.user, "Secretariat"):
queryset = Group.objects.filter(type="sdo", state="active").order_by('name')
else:
queryset = Group.objects.filter(type="sdo", state="active", role__person=self.person, role__name__in=("liaiman", "auth")).distinct().order_by('name')
self.fields['from_contact'].initial = self.person.role_set.filter(group=queryset[0]).first().email.address
self.fields['from_contact'].widget.attrs['readonly'] = True
self.fields['from_groups'].queryset = queryset
self.fields['from_groups'].widget.submitter = str(self.person)
# if there's only one possibility make it the default
if len(queryset) == 1:
self.fields['from_groups'].initial = queryset
def set_to_fields(self):
self.fields['to_groups'].choices = get_internal_choices(None)
class OutgoingLiaisonForm(LiaisonModelForm):
from_contact = SearchableEmailField(only_users=True)
approved = forms.BooleanField(label="Obtained prior approval", required=False)
class Meta:
model = LiaisonStatement
exclude = ('attachments','state','from_name','to_name','action_holder_contacts')
fieldsets = [('From', {'fields': ['from_groups','from_contact','response_contacts','approved'], 'legend': ''}),
('To', {'fields': ['to_groups','to_contacts'], 'legend': ''}),
('Other email addresses', {'fields': ['technical_contacts','cc_contacts'], 'legend': ''}),
('Purpose', {'fields':['purpose', 'deadline'], 'legend': ''}),
('Reference', {'fields': ['other_identifiers','related_to'], 'legend': ''}),
('Liaison Statement', {'fields': ['title', 'submitted_date', 'body', 'attachments'], 'legend': ''}),
('Add attachment', {'fields': ['attach_title', 'attach_file', 'attach_button'], 'legend': ''})]
def is_approved(self):
return self.cleaned_data['approved']
def set_from_fields(self):
choices = get_internal_choices(self.user)
self.fields['from_groups'].choices = choices
flat_choices = flatten_choices(choices)
if len(flat_choices) == 1:
self.fields['from_groups'].initial = [flat_choices[0][0]]
if has_role(self.user, "Secretariat"):
return
if self.person.role_set.filter(name='liaiman',group__state='active'):
email = self.person.role_set.filter(name='liaiman',group__state='active').first().email.address
elif self.person.role_set.filter(name__in=('ad','chair'),group__state='active'):
email = self.person.role_set.filter(name__in=('ad','chair'),group__state='active').first().email.address
else:
email = self.person.email_address()
self.fields['from_contact'].initial = email
self.fields['from_contact'].widget.attrs['readonly'] = True
def set_to_fields(self):
if has_role(self.user, "Liaison Manager") and not self.person.role_set.filter(name__in=('ad','chair'),group__state='active'):
queryset = Group.objects.filter(type="sdo", state="active", role__person=self.person, role__name="liaiman").distinct().order_by('name')
else:
queryset = Group.objects.filter(type="sdo", state="active").order_by('name')
self.fields['to_groups'].queryset = queryset
if has_role(self.user, "Liaison Manager"):
self.fields['to_groups'].initial = [queryset.first()]
class EditLiaisonForm(LiaisonModelForm):
def __init__(self, *args, **kwargs):
super(EditLiaisonForm, self).__init__(*args, **kwargs)
self.edit = True
self.fields['attachments'].initial = self.instance.liaisonstatementattachment_set.exclude(removed=True)
related = [ str(x.pk) for x in self.instance.source_of_set.all() ]
self.fields['related_to'].initial = ','.join(related)
self.fields['submitted_date'].initial = self.instance.submitted
def save(self, *args, **kwargs):
super(EditLiaisonForm, self).save(*args,**kwargs)
if self.has_changed() and 'submitted_date' in self.changed_data:
event = self.instance.liaisonstatementevent_set.filter(type='submitted').first()
event.time = self.cleaned_data.get('submitted_date')
event.save()
return self.instance
def set_from_fields(self):
if self.instance.is_outgoing():
self.fields['from_groups'].choices = get_internal_choices(self.user)
else:
if has_role(self.user, "Secretariat"):
queryset = Group.objects.filter(type="sdo").order_by('name')
else:
queryset = Group.objects.filter(type="sdo", role__person=self.person, role__name__in=("liaiman", "auth")).distinct().order_by('name')
self.fields['from_contact'].widget.attrs['readonly'] = True
self.fields['from_groups'].queryset = queryset
def set_to_fields(self):
if self.instance.is_outgoing():
if has_role(self.user, "Liaison Manager") and not self.person.role_set.filter(name__in=('ad','chair'),group__state='active'):
queryset = Group.objects.filter(type="sdo", role__person=self.person, role__name="liaiman").distinct().order_by('name')
else:
queryset = Group.objects.filter(type="sdo").order_by('name')
self.fields['to_groups'].queryset = queryset
else:
self.fields['to_groups'].choices = get_internal_choices(None)
class EditAttachmentForm(forms.Form):
title = forms.CharField(max_length=255)
| true | true |
f72bedbab95f862cc621615212d09c74118e2e36 | 18,978 | py | Python | benchexec/tools/ultimate.py | mikhailramalho/benchexec | 5fc5180c26e0fa18e137b142c5890a3dd7cab795 | [
"Apache-2.0"
] | null | null | null | benchexec/tools/ultimate.py | mikhailramalho/benchexec | 5fc5180c26e0fa18e137b142c5890a3dd7cab795 | [
"Apache-2.0"
] | null | null | null | benchexec/tools/ultimate.py | mikhailramalho/benchexec | 5fc5180c26e0fa18e137b142c5890a3dd7cab795 | [
"Apache-2.0"
] | null | null | null | """
BenchExec is a framework for reliable benchmarking.
This file is part of BenchExec.
Copyright (C) 2015 Daniel Dietsch
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import functools
import logging
import os
import re
import subprocess
import sys
import benchexec.result as result
import benchexec.tools.template
import benchexec.util as util
from benchexec import BenchExecException
from benchexec.model import MEMLIMIT
from benchexec.tools.template import UnsupportedFeatureException
_OPTION_NO_WRAPPER = "--force-no-wrapper"
_SVCOMP17_VERSIONS = {"f7c3ed31"}
_SVCOMP17_FORBIDDEN_FLAGS = {"--full-output", "--architecture"}
_ULTIMATE_VERSION_REGEX = re.compile(r"^Version is (.*)$", re.MULTILINE)
# .jar files that are used as launcher arguments with most recent .jar first
_LAUNCHER_JARS = ["plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar"]
class UltimateTool(benchexec.tools.template.BaseTool):
"""
Abstract tool info for Ultimate-based tools.
"""
REQUIRED_PATHS = [
"artifacts.xml",
"config",
"configuration",
"cvc4",
"cvc4nyu",
"cvc4-LICENSE",
"features",
"LICENSE",
"LICENSE.GPL",
"LICENSE.GPL.LESSER",
"mathsat",
"mathsat-LICENSE",
"p2",
"plugins",
"README",
"Ultimate",
"Ultimate.ini",
"Ultimate.py",
"z3",
"z3-LICENSE",
]
REQUIRED_PATHS_SVCOMP17 = []
def __init__(self):
self._uses_propertyfile = False
@functools.lru_cache()
def executable(self):
exe = util.find_executable("Ultimate.py")
for (dirpath, dirnames, filenames) in os.walk(exe):
if "Ultimate" in filenames and "plugins" in dirnames:
return exe
break
# possibly another Ultimate.py was found, check in the current dir
current = os.getcwd()
for (dirpath, dirnames, filenames) in os.walk(current):
if (
"Ultimate" in filenames
and "Ultimate.py" in filenames
and "plugins" in dirnames
):
return "./Ultimate.py"
break
sys.exit(
"ERROR: Could not find Ultimate executable in '{0}' or '{1}'".format(
str(exe), str(current)
)
)
def _ultimate_version(self, executable):
data_dir = os.path.join(os.path.dirname(executable), "data")
launcher_jar = self._get_current_launcher_jar(executable)
cmds = [
# 2
[
self.get_java(),
"-Xss4m",
"-jar",
launcher_jar,
"-data",
"@noDefault",
"-ultimatedata",
data_dir,
"--version",
],
# 1
[
self.get_java(),
"-Xss4m",
"-jar",
launcher_jar,
"-data",
data_dir,
"--version",
],
]
self.api = len(cmds)
for cmd in cmds:
version = self._query_ultimate_version(cmd, self.api)
if version != "":
return version
self.api = self.api - 1
raise BenchExecException("Could not determine Ultimate version")
def _query_ultimate_version(self, cmd, api):
try:
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
(stdout, stderr) = process.communicate()
except OSError as e:
logging.warning(
"Cannot run Java to determine Ultimate version (API %s): %s",
api,
e.strerror,
)
return ""
stdout = util.decode_to_string(stdout).strip()
if stderr or process.returncode:
logging.warning(
"Cannot determine Ultimate version (API %s).\n"
"Command was: %s\n"
"Exit code: %s\n"
"Error output: %s\n"
"Standard output: %s",
api,
" ".join(map(util.escape_string_shell, cmd)),
process.returncode,
util.decode_to_string(stderr),
stdout,
)
return ""
version_ultimate_match = _ULTIMATE_VERSION_REGEX.search(stdout)
if not version_ultimate_match:
logging.warning(
"Cannot determine Ultimate version (API %s), output was: %s",
api,
stdout,
)
return ""
return version_ultimate_match.group(1)
@functools.lru_cache()
def _get_current_launcher_jar(self, executable):
ultimatedir = os.path.dirname(executable)
for jar in _LAUNCHER_JARS:
launcher_jar = os.path.join(ultimatedir, jar)
if os.path.isfile(launcher_jar):
return launcher_jar
raise FileNotFoundError(
"No suitable launcher jar found in {0}".format(ultimatedir)
)
@functools.lru_cache()
def version(self, executable):
wrapper_version = self._version_from_tool(executable)
if wrapper_version in _SVCOMP17_VERSIONS:
# Keep reported version number for old versions as they were before
return wrapper_version
ultimate_version = self._ultimate_version(executable)
return ultimate_version + "-" + wrapper_version
@functools.lru_cache()
def _is_svcomp17_version(self, executable):
return self.version(executable) in _SVCOMP17_VERSIONS
@functools.lru_cache()
def _requires_ultimate_data(self, executable):
if self._is_svcomp17_version(executable):
return False
version = self.version(executable)
ult, wrapper = version.split("-")
major, minor, patch = ult.split(".")
# all versions before 0.1.24 do not require ultimatedata
return not (int(major) == 0 and int(minor) < 2 and int(patch) < 24)
def cmdline(self, executable, options, tasks, propertyfile=None, rlimits=None):
if rlimits is None:
rlimits = {}
self._uses_propertyfile = propertyfile is not None
if _OPTION_NO_WRAPPER in options:
# do not use old wrapper script even if property file is given
self._uses_propertyfile = False
propertyfile = None
options.remove(_OPTION_NO_WRAPPER)
if self._is_svcomp17_version(executable):
assert propertyfile
cmdline = [executable, propertyfile]
cmdline += [
option for option in options if option not in _SVCOMP17_FORBIDDEN_FLAGS
]
cmdline.append("--full-output")
cmdline += tasks
self.__assert_cmdline(
cmdline,
"cmdline contains empty or None argument when using SVCOMP17 mode: ",
)
return cmdline
if self._uses_propertyfile:
# use the old wrapper script if a property file is given
cmdline = [executable, "--spec", propertyfile]
if tasks:
cmdline += ["--file"] + tasks
cmdline += options
self.__assert_cmdline(
cmdline,
"cmdline contains empty or None argument when using default SVCOMP mode: ",
)
return cmdline
# if no property file is given and toolchain (-tc) is, use ultimate directly
if "-tc" in options or "--toolchain" in options:
# ignore executable (old executable is just around for backwards compatibility)
mem_bytes = rlimits.get(MEMLIMIT, None)
cmdline = [self.get_java()]
# -ea has to be given directly to java
if "-ea" in options:
options = [e for e in options if e != "-ea"]
cmdline += ["-ea"]
if mem_bytes:
cmdline += ["-Xmx" + str(mem_bytes)]
cmdline += ["-Xss4m"]
cmdline += ["-jar", self._get_current_launcher_jar(executable)]
if self._requires_ultimate_data(executable):
if "-ultimatedata" not in options and "-data" not in options:
if self.api == 2:
cmdline += [
"-data",
"@noDefault",
"-ultimatedata",
os.path.join(os.path.dirname(executable), "data"),
]
if self.api == 1:
raise ValueError(
"Illegal option -ultimatedata for API {} and Ultimate version {}".format(
self.api, self.version(executable)
)
)
elif "-ultimatedata" in options and "-data" not in options:
if self.api == 2:
cmdline += ["-data", "@noDefault"]
if self.api == 1:
raise ValueError(
"Illegal option -ultimatedata for API {} and Ultimate version {}".format(
self.api, self.version(executable)
)
)
else:
if "-data" not in options:
if self.api == 2 or self.api == 1:
cmdline += [
"-data",
os.path.join(os.path.dirname(executable), "data"),
]
cmdline += options
if tasks:
cmdline += ["-i"] + tasks
self.__assert_cmdline(
cmdline,
"cmdline contains empty or None argument when using Ultimate raw mode: ",
)
return cmdline
# there is no way to run ultimate; not enough parameters
raise UnsupportedFeatureException(
"Unsupported argument combination: options={} propertyfile={} rlimits={}".format(
options, propertyfile, rlimits
)
)
def __assert_cmdline(self, cmdline, msg):
assert all(cmdline), msg + str(cmdline)
pass
def program_files(self, executable):
paths = (
self.REQUIRED_PATHS_SVCOMP17
if self._is_svcomp17_version(executable)
else self.REQUIRED_PATHS
)
return [executable] + self._program_files_from_executable(executable, paths)
def determine_result(self, returncode, returnsignal, output, is_timeout):
if self._uses_propertyfile:
return self._determine_result_with_propertyfile(
returncode, returnsignal, output, is_timeout
)
return self._determine_result_without_propertyfile(
returncode, returnsignal, output, is_timeout
)
def _determine_result_without_propertyfile(
self, returncode, returnsignal, output, is_timeout
):
# special strings in ultimate output
treeautomizer_sat = "TreeAutomizerSatResult"
treeautomizer_unsat = "TreeAutomizerUnsatResult"
unsupported_syntax_errorstring = "ShortDescription: Unsupported Syntax"
incorrect_syntax_errorstring = "ShortDescription: Incorrect Syntax"
type_errorstring = "Type Error"
witness_errorstring = "InvalidWitnessErrorResult"
exception_errorstring = "ExceptionOrErrorResult"
safety_string = "Ultimate proved your program to be correct"
all_spec_string = "AllSpecificationsHoldResult"
unsafety_string = "Ultimate proved your program to be incorrect"
mem_deref_false_string = "pointer dereference may fail"
mem_deref_false_string_2 = "array index can be out of bounds"
mem_free_false_string = "free of unallocated memory possible"
mem_memtrack_false_string = "not all allocated memory was freed"
termination_false_string = (
"Found a nonterminating execution for the following "
"lasso shaped sequence of statements"
)
termination_true_string = "TerminationAnalysisResult: Termination proven"
ltl_false_string = "execution that violates the LTL property"
ltl_true_string = "Buchi Automizer proved that the LTL property"
overflow_false_string = "overflow possible"
for line in output:
if line.find(unsupported_syntax_errorstring) != -1:
return "ERROR: UNSUPPORTED SYNTAX"
if line.find(incorrect_syntax_errorstring) != -1:
return "ERROR: INCORRECT SYNTAX"
if line.find(type_errorstring) != -1:
return "ERROR: TYPE ERROR"
if line.find(witness_errorstring) != -1:
return "ERROR: INVALID WITNESS FILE"
if line.find(exception_errorstring) != -1:
return "ERROR: EXCEPTION"
if self._contains_overapproximation_result(line):
return "UNKNOWN: OverapproxCex"
if line.find(termination_false_string) != -1:
return result.RESULT_FALSE_TERMINATION
if line.find(termination_true_string) != -1:
return result.RESULT_TRUE_PROP
if line.find(ltl_false_string) != -1:
return "FALSE(valid-ltl)"
if line.find(ltl_true_string) != -1:
return result.RESULT_TRUE_PROP
if line.find(unsafety_string) != -1:
return result.RESULT_FALSE_REACH
if line.find(mem_deref_false_string) != -1:
return result.RESULT_FALSE_DEREF
if line.find(mem_deref_false_string_2) != -1:
return result.RESULT_FALSE_DEREF
if line.find(mem_free_false_string) != -1:
return result.RESULT_FALSE_FREE
if line.find(mem_memtrack_false_string) != -1:
return result.RESULT_FALSE_MEMTRACK
if line.find(overflow_false_string) != -1:
return result.RESULT_FALSE_OVERFLOW
if line.find(safety_string) != -1 or line.find(all_spec_string) != -1:
return result.RESULT_TRUE_PROP
if line.find(treeautomizer_unsat) != -1:
return "unsat"
if line.find(treeautomizer_sat) != -1 or line.find(all_spec_string) != -1:
return "sat"
return result.RESULT_UNKNOWN
def _contains_overapproximation_result(self, line):
triggers = [
"Reason: overapproximation of",
"Reason: overapproximation of bitwiseAnd",
"Reason: overapproximation of bitwiseOr",
"Reason: overapproximation of bitwiseXor",
"Reason: overapproximation of shiftLeft",
"Reason: overapproximation of shiftRight",
"Reason: overapproximation of bitwiseComplement",
]
for trigger in triggers:
if line.find(trigger) != -1:
return True
return False
def _determine_result_with_propertyfile(
self, returncode, returnsignal, output, is_timeout
):
for line in output:
if line.startswith("FALSE(valid-free)"):
return result.RESULT_FALSE_FREE
elif line.startswith("FALSE(valid-deref)"):
return result.RESULT_FALSE_DEREF
elif line.startswith("FALSE(valid-memtrack)"):
return result.RESULT_FALSE_MEMTRACK
elif line.startswith("FALSE(valid-memcleanup)"):
return result.RESULT_FALSE_MEMCLEANUP
elif line.startswith("FALSE(TERM)"):
return result.RESULT_FALSE_TERMINATION
elif line.startswith("FALSE(OVERFLOW)"):
return result.RESULT_FALSE_OVERFLOW
elif line.startswith("FALSE"):
return result.RESULT_FALSE_REACH
elif line.startswith("TRUE"):
return result.RESULT_TRUE_PROP
elif line.startswith("UNKNOWN"):
return result.RESULT_UNKNOWN
elif line.startswith("ERROR"):
status = result.RESULT_ERROR
if line.startswith("ERROR: INVALID WITNESS FILE"):
status += " (invalid witness file)"
return status
return result.RESULT_UNKNOWN
def get_value_from_output(self, lines, identifier):
# search for the text in output and get its value,
# stop after the first line, that contains the searched text
for line in lines:
if identifier in line:
start_position = line.find("=") + 1
return line[start_position:].strip()
return None
@functools.lru_cache(maxsize=1)
def get_java(self):
candidates = [
"java",
"/usr/bin/java",
"/opt/oracle-jdk-bin-1.8.0.202/bin/java",
"/usr/lib/jvm/java-8-openjdk-amd64/bin/java",
]
for c in candidates:
candidate = self.which(c)
if not candidate:
continue
try:
process = subprocess.Popen(
[candidate, "-version"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
(stdout, stderr) = process.communicate()
except OSError as e:
continue
stdout = util.decode_to_string(stdout).strip()
if not stdout:
continue
if "1.8" in stdout:
return candidate
raise BenchExecException(
"Could not find a suitable Java version: Need Java 1.8"
)
def which(self, program):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
| 37.431953 | 101 | 0.566077 |
import functools
import logging
import os
import re
import subprocess
import sys
import benchexec.result as result
import benchexec.tools.template
import benchexec.util as util
from benchexec import BenchExecException
from benchexec.model import MEMLIMIT
from benchexec.tools.template import UnsupportedFeatureException
_OPTION_NO_WRAPPER = "--force-no-wrapper"
_SVCOMP17_VERSIONS = {"f7c3ed31"}
_SVCOMP17_FORBIDDEN_FLAGS = {"--full-output", "--architecture"}
_ULTIMATE_VERSION_REGEX = re.compile(r"^Version is (.*)$", re.MULTILINE)
_LAUNCHER_JARS = ["plugins/org.eclipse.equinox.launcher_1.3.100.v20150511-1540.jar"]
class UltimateTool(benchexec.tools.template.BaseTool):
REQUIRED_PATHS = [
"artifacts.xml",
"config",
"configuration",
"cvc4",
"cvc4nyu",
"cvc4-LICENSE",
"features",
"LICENSE",
"LICENSE.GPL",
"LICENSE.GPL.LESSER",
"mathsat",
"mathsat-LICENSE",
"p2",
"plugins",
"README",
"Ultimate",
"Ultimate.ini",
"Ultimate.py",
"z3",
"z3-LICENSE",
]
REQUIRED_PATHS_SVCOMP17 = []
def __init__(self):
self._uses_propertyfile = False
@functools.lru_cache()
def executable(self):
exe = util.find_executable("Ultimate.py")
for (dirpath, dirnames, filenames) in os.walk(exe):
if "Ultimate" in filenames and "plugins" in dirnames:
return exe
break
current = os.getcwd()
for (dirpath, dirnames, filenames) in os.walk(current):
if (
"Ultimate" in filenames
and "Ultimate.py" in filenames
and "plugins" in dirnames
):
return "./Ultimate.py"
break
sys.exit(
"ERROR: Could not find Ultimate executable in '{0}' or '{1}'".format(
str(exe), str(current)
)
)
def _ultimate_version(self, executable):
data_dir = os.path.join(os.path.dirname(executable), "data")
launcher_jar = self._get_current_launcher_jar(executable)
cmds = [
[
self.get_java(),
"-Xss4m",
"-jar",
launcher_jar,
"-data",
"@noDefault",
"-ultimatedata",
data_dir,
"--version",
],
[
self.get_java(),
"-Xss4m",
"-jar",
launcher_jar,
"-data",
data_dir,
"--version",
],
]
self.api = len(cmds)
for cmd in cmds:
version = self._query_ultimate_version(cmd, self.api)
if version != "":
return version
self.api = self.api - 1
raise BenchExecException("Could not determine Ultimate version")
def _query_ultimate_version(self, cmd, api):
try:
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
(stdout, stderr) = process.communicate()
except OSError as e:
logging.warning(
"Cannot run Java to determine Ultimate version (API %s): %s",
api,
e.strerror,
)
return ""
stdout = util.decode_to_string(stdout).strip()
if stderr or process.returncode:
logging.warning(
"Cannot determine Ultimate version (API %s).\n"
"Command was: %s\n"
"Exit code: %s\n"
"Error output: %s\n"
"Standard output: %s",
api,
" ".join(map(util.escape_string_shell, cmd)),
process.returncode,
util.decode_to_string(stderr),
stdout,
)
return ""
version_ultimate_match = _ULTIMATE_VERSION_REGEX.search(stdout)
if not version_ultimate_match:
logging.warning(
"Cannot determine Ultimate version (API %s), output was: %s",
api,
stdout,
)
return ""
return version_ultimate_match.group(1)
@functools.lru_cache()
def _get_current_launcher_jar(self, executable):
ultimatedir = os.path.dirname(executable)
for jar in _LAUNCHER_JARS:
launcher_jar = os.path.join(ultimatedir, jar)
if os.path.isfile(launcher_jar):
return launcher_jar
raise FileNotFoundError(
"No suitable launcher jar found in {0}".format(ultimatedir)
)
@functools.lru_cache()
def version(self, executable):
wrapper_version = self._version_from_tool(executable)
if wrapper_version in _SVCOMP17_VERSIONS:
return wrapper_version
ultimate_version = self._ultimate_version(executable)
return ultimate_version + "-" + wrapper_version
@functools.lru_cache()
def _is_svcomp17_version(self, executable):
return self.version(executable) in _SVCOMP17_VERSIONS
@functools.lru_cache()
def _requires_ultimate_data(self, executable):
if self._is_svcomp17_version(executable):
return False
version = self.version(executable)
ult, wrapper = version.split("-")
major, minor, patch = ult.split(".")
return not (int(major) == 0 and int(minor) < 2 and int(patch) < 24)
def cmdline(self, executable, options, tasks, propertyfile=None, rlimits=None):
if rlimits is None:
rlimits = {}
self._uses_propertyfile = propertyfile is not None
if _OPTION_NO_WRAPPER in options:
self._uses_propertyfile = False
propertyfile = None
options.remove(_OPTION_NO_WRAPPER)
if self._is_svcomp17_version(executable):
assert propertyfile
cmdline = [executable, propertyfile]
cmdline += [
option for option in options if option not in _SVCOMP17_FORBIDDEN_FLAGS
]
cmdline.append("--full-output")
cmdline += tasks
self.__assert_cmdline(
cmdline,
"cmdline contains empty or None argument when using SVCOMP17 mode: ",
)
return cmdline
if self._uses_propertyfile:
cmdline = [executable, "--spec", propertyfile]
if tasks:
cmdline += ["--file"] + tasks
cmdline += options
self.__assert_cmdline(
cmdline,
"cmdline contains empty or None argument when using default SVCOMP mode: ",
)
return cmdline
if "-tc" in options or "--toolchain" in options:
mem_bytes = rlimits.get(MEMLIMIT, None)
cmdline = [self.get_java()]
if "-ea" in options:
options = [e for e in options if e != "-ea"]
cmdline += ["-ea"]
if mem_bytes:
cmdline += ["-Xmx" + str(mem_bytes)]
cmdline += ["-Xss4m"]
cmdline += ["-jar", self._get_current_launcher_jar(executable)]
if self._requires_ultimate_data(executable):
if "-ultimatedata" not in options and "-data" not in options:
if self.api == 2:
cmdline += [
"-data",
"@noDefault",
"-ultimatedata",
os.path.join(os.path.dirname(executable), "data"),
]
if self.api == 1:
raise ValueError(
"Illegal option -ultimatedata for API {} and Ultimate version {}".format(
self.api, self.version(executable)
)
)
elif "-ultimatedata" in options and "-data" not in options:
if self.api == 2:
cmdline += ["-data", "@noDefault"]
if self.api == 1:
raise ValueError(
"Illegal option -ultimatedata for API {} and Ultimate version {}".format(
self.api, self.version(executable)
)
)
else:
if "-data" not in options:
if self.api == 2 or self.api == 1:
cmdline += [
"-data",
os.path.join(os.path.dirname(executable), "data"),
]
cmdline += options
if tasks:
cmdline += ["-i"] + tasks
self.__assert_cmdline(
cmdline,
"cmdline contains empty or None argument when using Ultimate raw mode: ",
)
return cmdline
raise UnsupportedFeatureException(
"Unsupported argument combination: options={} propertyfile={} rlimits={}".format(
options, propertyfile, rlimits
)
)
def __assert_cmdline(self, cmdline, msg):
assert all(cmdline), msg + str(cmdline)
pass
def program_files(self, executable):
paths = (
self.REQUIRED_PATHS_SVCOMP17
if self._is_svcomp17_version(executable)
else self.REQUIRED_PATHS
)
return [executable] + self._program_files_from_executable(executable, paths)
def determine_result(self, returncode, returnsignal, output, is_timeout):
if self._uses_propertyfile:
return self._determine_result_with_propertyfile(
returncode, returnsignal, output, is_timeout
)
return self._determine_result_without_propertyfile(
returncode, returnsignal, output, is_timeout
)
def _determine_result_without_propertyfile(
self, returncode, returnsignal, output, is_timeout
):
treeautomizer_sat = "TreeAutomizerSatResult"
treeautomizer_unsat = "TreeAutomizerUnsatResult"
unsupported_syntax_errorstring = "ShortDescription: Unsupported Syntax"
incorrect_syntax_errorstring = "ShortDescription: Incorrect Syntax"
type_errorstring = "Type Error"
witness_errorstring = "InvalidWitnessErrorResult"
exception_errorstring = "ExceptionOrErrorResult"
safety_string = "Ultimate proved your program to be correct"
all_spec_string = "AllSpecificationsHoldResult"
unsafety_string = "Ultimate proved your program to be incorrect"
mem_deref_false_string = "pointer dereference may fail"
mem_deref_false_string_2 = "array index can be out of bounds"
mem_free_false_string = "free of unallocated memory possible"
mem_memtrack_false_string = "not all allocated memory was freed"
termination_false_string = (
"Found a nonterminating execution for the following "
"lasso shaped sequence of statements"
)
termination_true_string = "TerminationAnalysisResult: Termination proven"
ltl_false_string = "execution that violates the LTL property"
ltl_true_string = "Buchi Automizer proved that the LTL property"
overflow_false_string = "overflow possible"
for line in output:
if line.find(unsupported_syntax_errorstring) != -1:
return "ERROR: UNSUPPORTED SYNTAX"
if line.find(incorrect_syntax_errorstring) != -1:
return "ERROR: INCORRECT SYNTAX"
if line.find(type_errorstring) != -1:
return "ERROR: TYPE ERROR"
if line.find(witness_errorstring) != -1:
return "ERROR: INVALID WITNESS FILE"
if line.find(exception_errorstring) != -1:
return "ERROR: EXCEPTION"
if self._contains_overapproximation_result(line):
return "UNKNOWN: OverapproxCex"
if line.find(termination_false_string) != -1:
return result.RESULT_FALSE_TERMINATION
if line.find(termination_true_string) != -1:
return result.RESULT_TRUE_PROP
if line.find(ltl_false_string) != -1:
return "FALSE(valid-ltl)"
if line.find(ltl_true_string) != -1:
return result.RESULT_TRUE_PROP
if line.find(unsafety_string) != -1:
return result.RESULT_FALSE_REACH
if line.find(mem_deref_false_string) != -1:
return result.RESULT_FALSE_DEREF
if line.find(mem_deref_false_string_2) != -1:
return result.RESULT_FALSE_DEREF
if line.find(mem_free_false_string) != -1:
return result.RESULT_FALSE_FREE
if line.find(mem_memtrack_false_string) != -1:
return result.RESULT_FALSE_MEMTRACK
if line.find(overflow_false_string) != -1:
return result.RESULT_FALSE_OVERFLOW
if line.find(safety_string) != -1 or line.find(all_spec_string) != -1:
return result.RESULT_TRUE_PROP
if line.find(treeautomizer_unsat) != -1:
return "unsat"
if line.find(treeautomizer_sat) != -1 or line.find(all_spec_string) != -1:
return "sat"
return result.RESULT_UNKNOWN
def _contains_overapproximation_result(self, line):
triggers = [
"Reason: overapproximation of",
"Reason: overapproximation of bitwiseAnd",
"Reason: overapproximation of bitwiseOr",
"Reason: overapproximation of bitwiseXor",
"Reason: overapproximation of shiftLeft",
"Reason: overapproximation of shiftRight",
"Reason: overapproximation of bitwiseComplement",
]
for trigger in triggers:
if line.find(trigger) != -1:
return True
return False
def _determine_result_with_propertyfile(
self, returncode, returnsignal, output, is_timeout
):
for line in output:
if line.startswith("FALSE(valid-free)"):
return result.RESULT_FALSE_FREE
elif line.startswith("FALSE(valid-deref)"):
return result.RESULT_FALSE_DEREF
elif line.startswith("FALSE(valid-memtrack)"):
return result.RESULT_FALSE_MEMTRACK
elif line.startswith("FALSE(valid-memcleanup)"):
return result.RESULT_FALSE_MEMCLEANUP
elif line.startswith("FALSE(TERM)"):
return result.RESULT_FALSE_TERMINATION
elif line.startswith("FALSE(OVERFLOW)"):
return result.RESULT_FALSE_OVERFLOW
elif line.startswith("FALSE"):
return result.RESULT_FALSE_REACH
elif line.startswith("TRUE"):
return result.RESULT_TRUE_PROP
elif line.startswith("UNKNOWN"):
return result.RESULT_UNKNOWN
elif line.startswith("ERROR"):
status = result.RESULT_ERROR
if line.startswith("ERROR: INVALID WITNESS FILE"):
status += " (invalid witness file)"
return status
return result.RESULT_UNKNOWN
def get_value_from_output(self, lines, identifier):
for line in lines:
if identifier in line:
start_position = line.find("=") + 1
return line[start_position:].strip()
return None
@functools.lru_cache(maxsize=1)
def get_java(self):
candidates = [
"java",
"/usr/bin/java",
"/opt/oracle-jdk-bin-1.8.0.202/bin/java",
"/usr/lib/jvm/java-8-openjdk-amd64/bin/java",
]
for c in candidates:
candidate = self.which(c)
if not candidate:
continue
try:
process = subprocess.Popen(
[candidate, "-version"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
(stdout, stderr) = process.communicate()
except OSError as e:
continue
stdout = util.decode_to_string(stdout).strip()
if not stdout:
continue
if "1.8" in stdout:
return candidate
raise BenchExecException(
"Could not find a suitable Java version: Need Java 1.8"
)
def which(self, program):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
| true | true |
f72beded7ef5a032d409d3786dee6fcc951198a6 | 18,914 | py | Python | site-packages/neutronclient/osc/v2/fwaas/firewallrule.py | hariza17/freezer_libraries | e0bd890eba5e7438976fb3b4d66c41c128bab790 | [
"PSF-2.0"
] | null | null | null | site-packages/neutronclient/osc/v2/fwaas/firewallrule.py | hariza17/freezer_libraries | e0bd890eba5e7438976fb3b4d66c41c128bab790 | [
"PSF-2.0"
] | null | null | null | site-packages/neutronclient/osc/v2/fwaas/firewallrule.py | hariza17/freezer_libraries | e0bd890eba5e7438976fb3b4d66c41c128bab790 | [
"PSF-2.0"
] | null | null | null | # Copyright 2016-2017 FUJITSU LIMITED
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import copy
import logging
from cliff import columns as cliff_columns
from osc_lib.command import command
from osc_lib import exceptions
from osc_lib import utils
from osc_lib.utils import columns as column_util
from neutronclient._i18n import _
from neutronclient.common import utils as nc_utils
from neutronclient.osc import utils as osc_utils
from neutronclient.osc.v2.fwaas import constants as const
LOG = logging.getLogger(__name__)
_attr_map = (
('id', 'ID', column_util.LIST_BOTH),
('name', 'Name', column_util.LIST_BOTH),
('enabled', 'Enabled', column_util.LIST_BOTH),
('summary', 'Summary', column_util.LIST_SHORT_ONLY),
('description', 'Description', column_util.LIST_LONG_ONLY),
('ip_version', 'IP Version', column_util.LIST_LONG_ONLY),
('action', 'Action', column_util.LIST_LONG_ONLY),
('protocol', 'Protocol', column_util.LIST_LONG_ONLY),
('source_ip_address', 'Source IP Address', column_util.LIST_LONG_ONLY),
('source_port', 'Source Port', column_util.LIST_LONG_ONLY),
('destination_ip_address', 'Destination IP Address',
column_util.LIST_LONG_ONLY),
('destination_port', 'Destination Port', column_util.LIST_LONG_ONLY),
('shared', 'Shared', column_util.LIST_LONG_ONLY),
('tenant_id', 'Project', column_util.LIST_LONG_ONLY),
('source_firewall_group_id', 'Source Firewall Group ID',
column_util.LIST_LONG_ONLY),
('destination_firewall_group_id', 'Destination Firewall Group ID',
column_util.LIST_LONG_ONLY),
)
def _get_common_parser(parser):
parser.add_argument(
'--name',
metavar='<name>',
help=_('Name of the firewall rule'))
parser.add_argument(
'--description',
metavar='<description>',
help=_('Description of the firewall rule'))
parser.add_argument(
'--protocol',
choices=['tcp', 'udp', 'icmp', 'any'],
type=nc_utils.convert_to_lowercase,
help=_('Protocol for the firewall rule'))
parser.add_argument(
'--action',
choices=['allow', 'deny', 'reject'],
type=nc_utils.convert_to_lowercase,
help=_('Action for the firewall rule'))
parser.add_argument(
'--ip-version',
metavar='<ip-version>',
choices=['4', '6'],
help=_('Set IP version 4 or 6 (default is 4)'))
src_ip_group = parser.add_mutually_exclusive_group()
src_ip_group.add_argument(
'--source-ip-address',
metavar='<source-ip-address>',
help=_('Source IP address or subnet'))
src_ip_group.add_argument(
'--no-source-ip-address',
action='store_true',
help=_('Detach source IP address'))
dst_ip_group = parser.add_mutually_exclusive_group()
dst_ip_group.add_argument(
'--destination-ip-address',
metavar='<destination-ip-address>',
help=_('Destination IP address or subnet'))
dst_ip_group.add_argument(
'--no-destination-ip-address',
action='store_true',
help=_('Detach destination IP address'))
src_port_group = parser.add_mutually_exclusive_group()
src_port_group.add_argument(
'--source-port',
metavar='<source-port>',
help=_('Source port number or range'
'(integer in [1, 65535] or range like 123:456)'))
src_port_group.add_argument(
'--no-source-port',
action='store_true',
help=_('Detach source port number or range'))
dst_port_group = parser.add_mutually_exclusive_group()
dst_port_group.add_argument(
'--destination-port',
metavar='<destination-port>',
help=_('Destination port number or range'
'(integer in [1, 65535] or range like 123:456)'))
dst_port_group.add_argument(
'--no-destination-port',
action='store_true',
help=_('Detach destination port number or range'))
shared_group = parser.add_mutually_exclusive_group()
shared_group.add_argument(
'--public',
action='store_true',
help=_('Make the firewall policy public, which allows it to be '
'used in all projects (as opposed to the default, '
'which is to restrict its use to the current project). '
'This option is deprecated and would be removed in R Release'))
shared_group.add_argument(
'--private',
action='store_true',
help=_(
'Restrict use of the firewall rule to the current project.'
'This option is deprecated and would be removed in R release.'))
shared_group.add_argument(
'--share',
action='store_true',
help=_('Share the firewall rule to be used in all projects '
'(by default, it is restricted to be used by the '
'current project).'))
shared_group.add_argument(
'--no-share',
action='store_true',
help=_('Restrict use of the firewall rule to the current project'))
enable_group = parser.add_mutually_exclusive_group()
enable_group.add_argument(
'--enable-rule',
action='store_true',
help=_('Enable this rule (default is enabled)'))
enable_group.add_argument(
'--disable-rule',
action='store_true',
help=_('Disable this rule'))
src_fwg_group = parser.add_mutually_exclusive_group()
src_fwg_group.add_argument(
'--source-firewall-group',
metavar='<source-firewall-group>',
help=_('Source firewall group (name or ID)'))
src_fwg_group.add_argument(
'--no-source-firewall-group',
action='store_true',
help=_('No associated destination firewall group'))
dst_fwg_group = parser.add_mutually_exclusive_group()
dst_fwg_group.add_argument(
'--destination-firewall-group',
metavar='<destination-firewall-group>',
help=_('Destination firewall group (name or ID)'))
dst_fwg_group.add_argument(
'--no-destination-firewall-group',
action='store_true',
help=_('No associated destination firewall group'))
return parser
def _get_common_attrs(client_manager, parsed_args, is_create=True):
attrs = {}
client = client_manager.neutronclient
if is_create:
if 'project' in parsed_args and parsed_args.project is not None:
attrs['tenant_id'] = osc_utils.find_project(
client_manager.identity,
parsed_args.project,
parsed_args.project_domain,
).id
if parsed_args.name:
attrs['name'] = str(parsed_args.name)
if parsed_args.description:
attrs['description'] = str(parsed_args.description)
if parsed_args.protocol:
protocol = parsed_args.protocol
attrs['protocol'] = None if protocol == 'any' else protocol
if parsed_args.action:
attrs['action'] = parsed_args.action
if parsed_args.ip_version:
attrs['ip_version'] = str(parsed_args.ip_version)
if parsed_args.source_port:
attrs['source_port'] = parsed_args.source_port
if parsed_args.no_source_port:
attrs['source_port'] = None
if parsed_args.source_ip_address:
attrs['source_ip_address'] = parsed_args.source_ip_address
if parsed_args.no_source_ip_address:
attrs['source_ip_address'] = None
if parsed_args.destination_port:
attrs['destination_port'] = str(parsed_args.destination_port)
if parsed_args.no_destination_port:
attrs['destination_port'] = None
if parsed_args.destination_ip_address:
attrs['destination_ip_address'] = str(
parsed_args.destination_ip_address)
if parsed_args.no_destination_ip_address:
attrs['destination_ip_address'] = None
if parsed_args.enable_rule:
attrs['enabled'] = True
if parsed_args.disable_rule:
attrs['enabled'] = False
if parsed_args.share or parsed_args.public:
attrs['shared'] = True
if parsed_args.no_share or parsed_args.private:
attrs['shared'] = False
if parsed_args.source_firewall_group:
attrs['source_firewall_group_id'] = client.find_resource(
const.FWG, parsed_args.source_firewall_group,
cmd_resource=const.CMD_FWG)['id']
if parsed_args.no_source_firewall_group:
attrs['source_firewall_group_id'] = None
if parsed_args.destination_firewall_group:
attrs['destination_firewall_group_id'] = client.find_resource(
const.FWG, parsed_args.destination_firewall_group,
cmd_resource=const.CMD_FWG)['id']
if parsed_args.no_destination_firewall_group:
attrs['destination_firewall_group_id'] = None
return attrs
class ProtocolColumn(cliff_columns.FormattableColumn):
def human_readable(self):
return self._value if self._value else 'any'
_formatters = {'protocol': ProtocolColumn}
class CreateFirewallRule(command.ShowOne):
_description = _("Create a new firewall rule")
def get_parser(self, prog_name):
parser = super(CreateFirewallRule, self).get_parser(prog_name)
_get_common_parser(parser)
osc_utils.add_project_owner_option_to_parser(parser)
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.neutronclient
attrs = _get_common_attrs(self.app.client_manager, parsed_args)
obj = client.create_fwaas_firewall_rule(
{const.FWR: attrs})[const.FWR]
columns, display_columns = column_util.get_columns(obj, _attr_map)
data = utils.get_dict_properties(obj, columns, formatters=_formatters)
return display_columns, data
class DeleteFirewallRule(command.Command):
_description = _("Delete firewall rule(s)")
def get_parser(self, prog_name):
parser = super(DeleteFirewallRule, self).get_parser(prog_name)
parser.add_argument(
const.FWR,
metavar='<firewall-rule>',
nargs='+',
help=_('Firewall rule(s) to delete (name or ID)'))
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.neutronclient
result = 0
for fwr in parsed_args.firewall_rule:
try:
fwr_id = client.find_resource(
const.FWR, fwr, cmd_resource=const.CMD_FWR)['id']
client.delete_fwaas_firewall_rule(fwr_id)
except Exception as e:
result += 1
LOG.error(_("Failed to delete Firewall rule with "
"name or ID '%(firewall_rule)s': %(e)s"),
{const.FWR: fwr, 'e': e})
if result > 0:
total = len(parsed_args.firewall_rule)
msg = (_("%(result)s of %(total)s firewall rule(s) failed "
"to delete.") % {'result': result, 'total': total})
raise exceptions.CommandError(msg)
class ListFirewallRule(command.Lister):
_description = _("List firewall rules that belong to a given tenant")
def get_parser(self, prog_name):
parser = super(ListFirewallRule, self).get_parser(prog_name)
parser.add_argument(
'--long',
action='store_true',
default=False,
help=_("List additional fields in output")
)
return parser
def extend_list(self, data, parsed_args):
ext_data = copy.deepcopy(data)
for d in ext_data:
protocol = d['protocol'].upper() if d['protocol'] else 'ANY'
src_ip = 'none specified'
dst_ip = 'none specified'
src_port = '(none specified)'
dst_port = '(none specified)'
if 'source_ip_address' in d and d['source_ip_address']:
src_ip = str(d['source_ip_address']).lower()
if 'source_port' in d and d['source_port']:
src_port = '(' + str(d['source_port']).lower() + ')'
if 'destination_ip_address' in d and d['destination_ip_address']:
dst_ip = str(d['destination_ip_address']).lower()
if 'destination_port' in d and d['destination_port']:
dst_port = '(' + str(d['destination_port']).lower() + ')'
action = d['action'] if d.get('action') else 'no-action'
src = 'source(port): ' + src_ip + src_port
dst = 'dest(port): ' + dst_ip + dst_port
d['summary'] = ',\n '.join([protocol, src, dst, action])
return ext_data
def take_action(self, parsed_args):
client = self.app.client_manager.neutronclient
obj = client.list_fwaas_firewall_rules()[const.FWRS]
obj_extend = self.extend_list(obj, parsed_args)
headers, columns = column_util.get_column_definitions(
_attr_map, long_listing=parsed_args.long)
return (headers, (utils.get_dict_properties(
s, columns, formatters=_formatters) for s in obj_extend))
class SetFirewallRule(command.Command):
_description = _("Set firewall rule properties")
def get_parser(self, prog_name):
parser = super(SetFirewallRule, self).get_parser(prog_name)
_get_common_parser(parser)
parser.add_argument(
const.FWR,
metavar='<firewall-rule>',
help=_('Firewall rule to set (name or ID)'))
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.neutronclient
attrs = _get_common_attrs(self.app.client_manager,
parsed_args, is_create=False)
fwr_id = client.find_resource(
const.FWR, parsed_args.firewall_rule,
cmd_resource=const.CMD_FWR)['id']
try:
client.update_fwaas_firewall_rule(fwr_id, {const.FWR: attrs})
except Exception as e:
msg = (_("Failed to set firewall rule '%(rule)s': %(e)s")
% {'rule': parsed_args.firewall_rule, 'e': e})
raise exceptions.CommandError(msg)
class ShowFirewallRule(command.ShowOne):
_description = _("Display firewall rule details")
def get_parser(self, prog_name):
parser = super(ShowFirewallRule, self).get_parser(prog_name)
parser.add_argument(
const.FWR,
metavar='<firewall-rule>',
help=_('Firewall rule to display (name or ID)'))
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.neutronclient
fwr_id = client.find_resource(
const.FWR, parsed_args.firewall_rule,
cmd_resource=const.CMD_FWR)['id']
obj = client.show_fwaas_firewall_rule(fwr_id)[const.FWR]
columns, display_columns = column_util.get_columns(obj, _attr_map)
data = utils.get_dict_properties(obj, columns, formatters=_formatters)
return (display_columns, data)
class UnsetFirewallRule(command.Command):
_description = _("Unset firewall rule properties")
def get_parser(self, prog_name):
parser = super(UnsetFirewallRule, self).get_parser(prog_name)
parser.add_argument(
const.FWR,
metavar='<firewall-rule>',
help=_('Firewall rule to unset (name or ID)'))
parser.add_argument(
'--source-ip-address',
action='store_true',
help=_('Source IP address or subnet'))
parser.add_argument(
'--destination-ip-address',
action='store_true',
help=_('Destination IP address or subnet'))
parser.add_argument(
'--source-port',
action='store_true',
help=_('Source port number or range'
'(integer in [1, 65535] or range like 123:456)'))
parser.add_argument(
'--destination-port',
action='store_true',
help=_('Destination port number or range'
'(integer in [1, 65535] or range like 123:456)'))
parser.add_argument(
'--share',
action='store_true',
help=_('Restrict use of the firewall rule to the current project'))
parser.add_argument(
'--public',
action='store_true',
help=_('Restrict use of the firewall rule to the current project. '
'This option is deprecated and would be removed in '
'R Release.'))
parser.add_argument(
'--enable-rule',
action='store_true',
help=_('Disable this rule'))
parser.add_argument(
'--source-firewall-group',
action='store_true',
help=_('Source firewall group (name or ID)'))
parser.add_argument(
'--destination-firewall-group',
action='store_true',
help=_('Destination firewall group (name or ID)'))
return parser
def _get_attrs(self, client_manager, parsed_args):
attrs = {}
if parsed_args.source_ip_address:
attrs['source_ip_address'] = None
if parsed_args.source_port:
attrs['source_port'] = None
if parsed_args.destination_ip_address:
attrs['destination_ip_address'] = None
if parsed_args.destination_port:
attrs['destination_port'] = None
if parsed_args.share or parsed_args.public:
attrs['shared'] = False
if parsed_args.enable_rule:
attrs['enabled'] = False
if parsed_args.source_firewall_group:
attrs['source_firewall_group_id'] = None
if parsed_args.source_firewall_group:
attrs['destination_firewall_group_id'] = None
return attrs
def take_action(self, parsed_args):
client = self.app.client_manager.neutronclient
attrs = self._get_attrs(self.app.client_manager, parsed_args)
fwr_id = client.find_resource(
const.FWR, parsed_args.firewall_rule,
cmd_resource=const.CMD_FWR)['id']
try:
client.update_fwaas_firewall_rule(fwr_id, {const.FWR: attrs})
except Exception as e:
msg = (_("Failed to unset firewall rule '%(rule)s': %(e)s")
% {'rule': parsed_args.firewall_rule, 'e': e})
raise exceptions.CommandError(msg)
| 39.987315 | 79 | 0.635297 |
import copy
import logging
from cliff import columns as cliff_columns
from osc_lib.command import command
from osc_lib import exceptions
from osc_lib import utils
from osc_lib.utils import columns as column_util
from neutronclient._i18n import _
from neutronclient.common import utils as nc_utils
from neutronclient.osc import utils as osc_utils
from neutronclient.osc.v2.fwaas import constants as const
LOG = logging.getLogger(__name__)
_attr_map = (
('id', 'ID', column_util.LIST_BOTH),
('name', 'Name', column_util.LIST_BOTH),
('enabled', 'Enabled', column_util.LIST_BOTH),
('summary', 'Summary', column_util.LIST_SHORT_ONLY),
('description', 'Description', column_util.LIST_LONG_ONLY),
('ip_version', 'IP Version', column_util.LIST_LONG_ONLY),
('action', 'Action', column_util.LIST_LONG_ONLY),
('protocol', 'Protocol', column_util.LIST_LONG_ONLY),
('source_ip_address', 'Source IP Address', column_util.LIST_LONG_ONLY),
('source_port', 'Source Port', column_util.LIST_LONG_ONLY),
('destination_ip_address', 'Destination IP Address',
column_util.LIST_LONG_ONLY),
('destination_port', 'Destination Port', column_util.LIST_LONG_ONLY),
('shared', 'Shared', column_util.LIST_LONG_ONLY),
('tenant_id', 'Project', column_util.LIST_LONG_ONLY),
('source_firewall_group_id', 'Source Firewall Group ID',
column_util.LIST_LONG_ONLY),
('destination_firewall_group_id', 'Destination Firewall Group ID',
column_util.LIST_LONG_ONLY),
)
def _get_common_parser(parser):
parser.add_argument(
'--name',
metavar='<name>',
help=_('Name of the firewall rule'))
parser.add_argument(
'--description',
metavar='<description>',
help=_('Description of the firewall rule'))
parser.add_argument(
'--protocol',
choices=['tcp', 'udp', 'icmp', 'any'],
type=nc_utils.convert_to_lowercase,
help=_('Protocol for the firewall rule'))
parser.add_argument(
'--action',
choices=['allow', 'deny', 'reject'],
type=nc_utils.convert_to_lowercase,
help=_('Action for the firewall rule'))
parser.add_argument(
'--ip-version',
metavar='<ip-version>',
choices=['4', '6'],
help=_('Set IP version 4 or 6 (default is 4)'))
src_ip_group = parser.add_mutually_exclusive_group()
src_ip_group.add_argument(
'--source-ip-address',
metavar='<source-ip-address>',
help=_('Source IP address or subnet'))
src_ip_group.add_argument(
'--no-source-ip-address',
action='store_true',
help=_('Detach source IP address'))
dst_ip_group = parser.add_mutually_exclusive_group()
dst_ip_group.add_argument(
'--destination-ip-address',
metavar='<destination-ip-address>',
help=_('Destination IP address or subnet'))
dst_ip_group.add_argument(
'--no-destination-ip-address',
action='store_true',
help=_('Detach destination IP address'))
src_port_group = parser.add_mutually_exclusive_group()
src_port_group.add_argument(
'--source-port',
metavar='<source-port>',
help=_('Source port number or range'
'(integer in [1, 65535] or range like 123:456)'))
src_port_group.add_argument(
'--no-source-port',
action='store_true',
help=_('Detach source port number or range'))
dst_port_group = parser.add_mutually_exclusive_group()
dst_port_group.add_argument(
'--destination-port',
metavar='<destination-port>',
help=_('Destination port number or range'
'(integer in [1, 65535] or range like 123:456)'))
dst_port_group.add_argument(
'--no-destination-port',
action='store_true',
help=_('Detach destination port number or range'))
shared_group = parser.add_mutually_exclusive_group()
shared_group.add_argument(
'--public',
action='store_true',
help=_('Make the firewall policy public, which allows it to be '
'used in all projects (as opposed to the default, '
'which is to restrict its use to the current project). '
'This option is deprecated and would be removed in R Release'))
shared_group.add_argument(
'--private',
action='store_true',
help=_(
'Restrict use of the firewall rule to the current project.'
'This option is deprecated and would be removed in R release.'))
shared_group.add_argument(
'--share',
action='store_true',
help=_('Share the firewall rule to be used in all projects '
'(by default, it is restricted to be used by the '
'current project).'))
shared_group.add_argument(
'--no-share',
action='store_true',
help=_('Restrict use of the firewall rule to the current project'))
enable_group = parser.add_mutually_exclusive_group()
enable_group.add_argument(
'--enable-rule',
action='store_true',
help=_('Enable this rule (default is enabled)'))
enable_group.add_argument(
'--disable-rule',
action='store_true',
help=_('Disable this rule'))
src_fwg_group = parser.add_mutually_exclusive_group()
src_fwg_group.add_argument(
'--source-firewall-group',
metavar='<source-firewall-group>',
help=_('Source firewall group (name or ID)'))
src_fwg_group.add_argument(
'--no-source-firewall-group',
action='store_true',
help=_('No associated destination firewall group'))
dst_fwg_group = parser.add_mutually_exclusive_group()
dst_fwg_group.add_argument(
'--destination-firewall-group',
metavar='<destination-firewall-group>',
help=_('Destination firewall group (name or ID)'))
dst_fwg_group.add_argument(
'--no-destination-firewall-group',
action='store_true',
help=_('No associated destination firewall group'))
return parser
def _get_common_attrs(client_manager, parsed_args, is_create=True):
attrs = {}
client = client_manager.neutronclient
if is_create:
if 'project' in parsed_args and parsed_args.project is not None:
attrs['tenant_id'] = osc_utils.find_project(
client_manager.identity,
parsed_args.project,
parsed_args.project_domain,
).id
if parsed_args.name:
attrs['name'] = str(parsed_args.name)
if parsed_args.description:
attrs['description'] = str(parsed_args.description)
if parsed_args.protocol:
protocol = parsed_args.protocol
attrs['protocol'] = None if protocol == 'any' else protocol
if parsed_args.action:
attrs['action'] = parsed_args.action
if parsed_args.ip_version:
attrs['ip_version'] = str(parsed_args.ip_version)
if parsed_args.source_port:
attrs['source_port'] = parsed_args.source_port
if parsed_args.no_source_port:
attrs['source_port'] = None
if parsed_args.source_ip_address:
attrs['source_ip_address'] = parsed_args.source_ip_address
if parsed_args.no_source_ip_address:
attrs['source_ip_address'] = None
if parsed_args.destination_port:
attrs['destination_port'] = str(parsed_args.destination_port)
if parsed_args.no_destination_port:
attrs['destination_port'] = None
if parsed_args.destination_ip_address:
attrs['destination_ip_address'] = str(
parsed_args.destination_ip_address)
if parsed_args.no_destination_ip_address:
attrs['destination_ip_address'] = None
if parsed_args.enable_rule:
attrs['enabled'] = True
if parsed_args.disable_rule:
attrs['enabled'] = False
if parsed_args.share or parsed_args.public:
attrs['shared'] = True
if parsed_args.no_share or parsed_args.private:
attrs['shared'] = False
if parsed_args.source_firewall_group:
attrs['source_firewall_group_id'] = client.find_resource(
const.FWG, parsed_args.source_firewall_group,
cmd_resource=const.CMD_FWG)['id']
if parsed_args.no_source_firewall_group:
attrs['source_firewall_group_id'] = None
if parsed_args.destination_firewall_group:
attrs['destination_firewall_group_id'] = client.find_resource(
const.FWG, parsed_args.destination_firewall_group,
cmd_resource=const.CMD_FWG)['id']
if parsed_args.no_destination_firewall_group:
attrs['destination_firewall_group_id'] = None
return attrs
class ProtocolColumn(cliff_columns.FormattableColumn):
def human_readable(self):
return self._value if self._value else 'any'
_formatters = {'protocol': ProtocolColumn}
class CreateFirewallRule(command.ShowOne):
_description = _("Create a new firewall rule")
def get_parser(self, prog_name):
parser = super(CreateFirewallRule, self).get_parser(prog_name)
_get_common_parser(parser)
osc_utils.add_project_owner_option_to_parser(parser)
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.neutronclient
attrs = _get_common_attrs(self.app.client_manager, parsed_args)
obj = client.create_fwaas_firewall_rule(
{const.FWR: attrs})[const.FWR]
columns, display_columns = column_util.get_columns(obj, _attr_map)
data = utils.get_dict_properties(obj, columns, formatters=_formatters)
return display_columns, data
class DeleteFirewallRule(command.Command):
_description = _("Delete firewall rule(s)")
def get_parser(self, prog_name):
parser = super(DeleteFirewallRule, self).get_parser(prog_name)
parser.add_argument(
const.FWR,
metavar='<firewall-rule>',
nargs='+',
help=_('Firewall rule(s) to delete (name or ID)'))
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.neutronclient
result = 0
for fwr in parsed_args.firewall_rule:
try:
fwr_id = client.find_resource(
const.FWR, fwr, cmd_resource=const.CMD_FWR)['id']
client.delete_fwaas_firewall_rule(fwr_id)
except Exception as e:
result += 1
LOG.error(_("Failed to delete Firewall rule with "
"name or ID '%(firewall_rule)s': %(e)s"),
{const.FWR: fwr, 'e': e})
if result > 0:
total = len(parsed_args.firewall_rule)
msg = (_("%(result)s of %(total)s firewall rule(s) failed "
"to delete.") % {'result': result, 'total': total})
raise exceptions.CommandError(msg)
class ListFirewallRule(command.Lister):
_description = _("List firewall rules that belong to a given tenant")
def get_parser(self, prog_name):
parser = super(ListFirewallRule, self).get_parser(prog_name)
parser.add_argument(
'--long',
action='store_true',
default=False,
help=_("List additional fields in output")
)
return parser
def extend_list(self, data, parsed_args):
ext_data = copy.deepcopy(data)
for d in ext_data:
protocol = d['protocol'].upper() if d['protocol'] else 'ANY'
src_ip = 'none specified'
dst_ip = 'none specified'
src_port = '(none specified)'
dst_port = '(none specified)'
if 'source_ip_address' in d and d['source_ip_address']:
src_ip = str(d['source_ip_address']).lower()
if 'source_port' in d and d['source_port']:
src_port = '(' + str(d['source_port']).lower() + ')'
if 'destination_ip_address' in d and d['destination_ip_address']:
dst_ip = str(d['destination_ip_address']).lower()
if 'destination_port' in d and d['destination_port']:
dst_port = '(' + str(d['destination_port']).lower() + ')'
action = d['action'] if d.get('action') else 'no-action'
src = 'source(port): ' + src_ip + src_port
dst = 'dest(port): ' + dst_ip + dst_port
d['summary'] = ',\n '.join([protocol, src, dst, action])
return ext_data
def take_action(self, parsed_args):
client = self.app.client_manager.neutronclient
obj = client.list_fwaas_firewall_rules()[const.FWRS]
obj_extend = self.extend_list(obj, parsed_args)
headers, columns = column_util.get_column_definitions(
_attr_map, long_listing=parsed_args.long)
return (headers, (utils.get_dict_properties(
s, columns, formatters=_formatters) for s in obj_extend))
class SetFirewallRule(command.Command):
_description = _("Set firewall rule properties")
def get_parser(self, prog_name):
parser = super(SetFirewallRule, self).get_parser(prog_name)
_get_common_parser(parser)
parser.add_argument(
const.FWR,
metavar='<firewall-rule>',
help=_('Firewall rule to set (name or ID)'))
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.neutronclient
attrs = _get_common_attrs(self.app.client_manager,
parsed_args, is_create=False)
fwr_id = client.find_resource(
const.FWR, parsed_args.firewall_rule,
cmd_resource=const.CMD_FWR)['id']
try:
client.update_fwaas_firewall_rule(fwr_id, {const.FWR: attrs})
except Exception as e:
msg = (_("Failed to set firewall rule '%(rule)s': %(e)s")
% {'rule': parsed_args.firewall_rule, 'e': e})
raise exceptions.CommandError(msg)
class ShowFirewallRule(command.ShowOne):
_description = _("Display firewall rule details")
def get_parser(self, prog_name):
parser = super(ShowFirewallRule, self).get_parser(prog_name)
parser.add_argument(
const.FWR,
metavar='<firewall-rule>',
help=_('Firewall rule to display (name or ID)'))
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.neutronclient
fwr_id = client.find_resource(
const.FWR, parsed_args.firewall_rule,
cmd_resource=const.CMD_FWR)['id']
obj = client.show_fwaas_firewall_rule(fwr_id)[const.FWR]
columns, display_columns = column_util.get_columns(obj, _attr_map)
data = utils.get_dict_properties(obj, columns, formatters=_formatters)
return (display_columns, data)
class UnsetFirewallRule(command.Command):
_description = _("Unset firewall rule properties")
def get_parser(self, prog_name):
parser = super(UnsetFirewallRule, self).get_parser(prog_name)
parser.add_argument(
const.FWR,
metavar='<firewall-rule>',
help=_('Firewall rule to unset (name or ID)'))
parser.add_argument(
'--source-ip-address',
action='store_true',
help=_('Source IP address or subnet'))
parser.add_argument(
'--destination-ip-address',
action='store_true',
help=_('Destination IP address or subnet'))
parser.add_argument(
'--source-port',
action='store_true',
help=_('Source port number or range'
'(integer in [1, 65535] or range like 123:456)'))
parser.add_argument(
'--destination-port',
action='store_true',
help=_('Destination port number or range'
'(integer in [1, 65535] or range like 123:456)'))
parser.add_argument(
'--share',
action='store_true',
help=_('Restrict use of the firewall rule to the current project'))
parser.add_argument(
'--public',
action='store_true',
help=_('Restrict use of the firewall rule to the current project. '
'This option is deprecated and would be removed in '
'R Release.'))
parser.add_argument(
'--enable-rule',
action='store_true',
help=_('Disable this rule'))
parser.add_argument(
'--source-firewall-group',
action='store_true',
help=_('Source firewall group (name or ID)'))
parser.add_argument(
'--destination-firewall-group',
action='store_true',
help=_('Destination firewall group (name or ID)'))
return parser
def _get_attrs(self, client_manager, parsed_args):
attrs = {}
if parsed_args.source_ip_address:
attrs['source_ip_address'] = None
if parsed_args.source_port:
attrs['source_port'] = None
if parsed_args.destination_ip_address:
attrs['destination_ip_address'] = None
if parsed_args.destination_port:
attrs['destination_port'] = None
if parsed_args.share or parsed_args.public:
attrs['shared'] = False
if parsed_args.enable_rule:
attrs['enabled'] = False
if parsed_args.source_firewall_group:
attrs['source_firewall_group_id'] = None
if parsed_args.source_firewall_group:
attrs['destination_firewall_group_id'] = None
return attrs
def take_action(self, parsed_args):
client = self.app.client_manager.neutronclient
attrs = self._get_attrs(self.app.client_manager, parsed_args)
fwr_id = client.find_resource(
const.FWR, parsed_args.firewall_rule,
cmd_resource=const.CMD_FWR)['id']
try:
client.update_fwaas_firewall_rule(fwr_id, {const.FWR: attrs})
except Exception as e:
msg = (_("Failed to unset firewall rule '%(rule)s': %(e)s")
% {'rule': parsed_args.firewall_rule, 'e': e})
raise exceptions.CommandError(msg)
| true | true |
f72bee82c057e8b1b9e1dcbe3c8f34b55a9c0a95 | 3,518 | py | Python | django_libs/test_email_backend.py | Reston/django-libs | 8c44a0851e3be564a100df50d257c1ce5b30dc25 | [
"MIT"
] | null | null | null | django_libs/test_email_backend.py | Reston/django-libs | 8c44a0851e3be564a100df50d257c1ce5b30dc25 | [
"MIT"
] | null | null | null | django_libs/test_email_backend.py | Reston/django-libs | 8c44a0851e3be564a100df50d257c1ce5b30dc25 | [
"MIT"
] | 1 | 2020-01-09T10:23:13.000Z | 2020-01-09T10:23:13.000Z | """Custom email backend for testing the project."""
import re
from django.core.mail.backends.smtp import EmailBackend as SmtpEmailBackend
from django.core.mail.message import sanitize_address
from . import default_settings as settings
class EmailBackend(SmtpEmailBackend):
"""
Email backend that sends all emails to a defined address, no matter what
the recipient really is.
In order to use it, set this in your local_settings.py::
EMAIL_BACKEND = 'django_libs.test_email_backend.EmailBackend'
TEST_EMAIL_BACKEND_RECIPIENTS = (
('Name', 'email@gmail.com'),
)
"""
def _send(self, email_message):
"""A helper method that does the actual sending."""
if not email_message.recipients() or \
not settings.TEST_EMAIL_BACKEND_RECIPIENTS:
return False
from_email = sanitize_address(
email_message.from_email, email_message.encoding)
recipients = [sanitize_address(addr, email_message.encoding)
for name, addr in settings.TEST_EMAIL_BACKEND_RECIPIENTS]
try:
self.connection.sendmail(
from_email, recipients, email_message.message().as_string())
except:
if not self.fail_silently:
raise
return False
return True
class WhitelistEmailBackend(SmtpEmailBackend):
"""
Email backend that sends only these emails, that match the whitelist
setting.
In order to use it, set this in your local_settings.py::
EMAIL_BACKEND = 'django_libs.test_email_backend.EmailBackend'
EMAIL_BACKEND_WHITELIST = [
r'.*@example\.com',
]
This setting would allow all emails to @example.com to be sent and all
others are discarded. The setting expects regex, so better test it before
adding it here to prevent errors.
If the setting does not exist, no emails are sent at all.
"""
def _send(self, email_message):
"""A helper method that does the actual sending."""
from_email = sanitize_address(
email_message.from_email, email_message.encoding)
recipients = self.clean_recipients(email_message)
if not recipients:
return False
try:
self.connection.sendmail(
from_email, recipients, email_message.message().as_string())
except:
if not self.fail_silently:
raise
return False
return True
def clean_recipients(self, email_message):
"""Removes all the unallowed recipients."""
new_recipients = []
recipients = [sanitize_address(addr, email_message.encoding)
for addr in email_message.recipients()]
for recipient in recipients:
if self.matches_whitelist(recipient):
new_recipients.append(recipient)
elif settings.EMAIL_BACKEND_REROUTE_BLACKLIST:
for name, addr in settings.TEST_EMAIL_BACKEND_RECIPIENTS:
new_recipients.append(addr)
# remove duplicates
new_recipients = list(set(new_recipients))
return new_recipients
def matches_whitelist(self, recipient):
"""Checks if the email address matches one of the whitelist entries."""
matches = False
for entry in settings.EMAIL_BACKEND_WHITELIST:
if re.match(entry, recipient):
matches = True
return matches
| 34.490196 | 79 | 0.645253 | import re
from django.core.mail.backends.smtp import EmailBackend as SmtpEmailBackend
from django.core.mail.message import sanitize_address
from . import default_settings as settings
class EmailBackend(SmtpEmailBackend):
def _send(self, email_message):
if not email_message.recipients() or \
not settings.TEST_EMAIL_BACKEND_RECIPIENTS:
return False
from_email = sanitize_address(
email_message.from_email, email_message.encoding)
recipients = [sanitize_address(addr, email_message.encoding)
for name, addr in settings.TEST_EMAIL_BACKEND_RECIPIENTS]
try:
self.connection.sendmail(
from_email, recipients, email_message.message().as_string())
except:
if not self.fail_silently:
raise
return False
return True
class WhitelistEmailBackend(SmtpEmailBackend):
def _send(self, email_message):
from_email = sanitize_address(
email_message.from_email, email_message.encoding)
recipients = self.clean_recipients(email_message)
if not recipients:
return False
try:
self.connection.sendmail(
from_email, recipients, email_message.message().as_string())
except:
if not self.fail_silently:
raise
return False
return True
def clean_recipients(self, email_message):
new_recipients = []
recipients = [sanitize_address(addr, email_message.encoding)
for addr in email_message.recipients()]
for recipient in recipients:
if self.matches_whitelist(recipient):
new_recipients.append(recipient)
elif settings.EMAIL_BACKEND_REROUTE_BLACKLIST:
for name, addr in settings.TEST_EMAIL_BACKEND_RECIPIENTS:
new_recipients.append(addr)
new_recipients = list(set(new_recipients))
return new_recipients
def matches_whitelist(self, recipient):
matches = False
for entry in settings.EMAIL_BACKEND_WHITELIST:
if re.match(entry, recipient):
matches = True
return matches
| true | true |
f72beeeefd11624a2d91beb7c8d8ca61bb669461 | 14,901 | py | Python | py/redrock/templates.py | echaussidon/redrock | 9a3d4f0aed8c0792f2cc731dbdf04a99018083bf | [
"BSD-3-Clause"
] | 14 | 2017-09-22T23:57:33.000Z | 2022-03-15T10:36:16.000Z | py/redrock/templates.py | echaussidon/redrock | 9a3d4f0aed8c0792f2cc731dbdf04a99018083bf | [
"BSD-3-Clause"
] | 154 | 2017-06-04T22:57:39.000Z | 2022-03-11T23:01:16.000Z | py/redrock/templates.py | echaussidon/redrock | 9a3d4f0aed8c0792f2cc731dbdf04a99018083bf | [
"BSD-3-Clause"
] | 10 | 2017-06-09T15:24:59.000Z | 2021-05-26T13:16:42.000Z | """
Classes and functions for templates.
"""
from __future__ import absolute_import, division, print_function
import sys
from glob import glob
import os
import traceback
import numpy as np
from astropy.io import fits
from .utils import native_endian, elapsed, transmission_Lyman
from .rebin import rebin_template, trapz_rebin
class Template(object):
"""A spectral Template PCA object.
The template data is read from a redrock-format template file.
Alternatively, the data can be specified in the constructor.
Args:
filename (str): the path to the template file, either absolute or
relative to the RR_TEMPLATE_DIR environment variable.
"""
def __init__(self, filename=None, spectype=None, redshifts=None,
wave=None, flux=None, subtype=None):
if filename is not None:
fx = None
if os.path.exists(filename):
fx = fits.open(filename, memmap=False)
else:
xfilename = os.path.join(os.getenv('RR_TEMPLATE_DIR'), filename)
if os.path.exists(xfilename):
fx = fits.open(xfilename, memmap=False)
else:
raise IOError('unable to find '+filename)
hdr = fx['BASIS_VECTORS'].header
if 'VERSION' in hdr:
self._version = hdr['VERSION']
else:
self._version = 'unknown'
self.wave = np.asarray(hdr['CRVAL1'] + \
hdr['CDELT1']*np.arange(hdr['NAXIS1']), dtype=np.float64)
if 'LOGLAM' in hdr and hdr['LOGLAM'] != 0:
self.wave = 10**self.wave
self.flux = np.asarray(native_endian(fx['BASIS_VECTORS'].data),
dtype=np.float64)
self._redshifts = None
## find out if redshift info is present in the file
old_style_templates = True
try:
self._redshifts = native_endian(fx['REDSHIFTS'].data)
old_style_templates = False
except KeyError:
pass
fx.close()
self._rrtype = hdr['RRTYPE'].strip().upper()
if old_style_templates:
if self._rrtype == 'GALAXY':
# redshifts = 10**np.arange(np.log10(1+0.005),
# np.log10(1+2.0), 1.5e-4) - 1
self._redshifts = 10**np.arange(np.log10(1-0.005),
np.log10(1+1.7), 3e-4) - 1
elif self._rrtype == 'STAR':
self._redshifts = np.arange(-0.002, 0.00201, 4e-5)
elif self._rrtype == 'QSO':
self._redshifts = 10**np.arange(np.log10(1+0.05),
np.log10(1+6.0), 5e-4) - 1
else:
raise ValueError("Unknown redshift range to use for "
"template type {}".format(self._rrtype))
zmin = self._redshifts[0]
zmax = self._redshifts[-1]
print("DEBUG: Using default redshift range {:.4f}-{:.4f} for "
"{}".format(zmin, zmax, os.path.basename(filename)))
else:
zmin = self._redshifts[0]
zmax = self._redshifts[-1]
print("DEBUG: Using redshift range {:.4f}-{:.4f} for "
"{}".format(zmin, zmax, os.path.basename(filename)))
self._subtype = None
if 'RRSUBTYP' in hdr:
self._subtype = hdr['RRSUBTYP'].strip().upper()
else:
self._subtype = ''
else:
self._rrtype = spectype
self._redshifts = redshifts
self.wave = wave
self.flux = flux
self._subtype = subtype
self._nbasis = self.flux.shape[0]
self._nwave = self.flux.shape[1]
@property
def nbasis(self):
return self._nbasis
@property
def nwave(self):
return self._nwave
@property
def template_type(self):
return self._rrtype
@property
def sub_type(self):
return self._subtype
@property
def full_type(self):
"""Return formatted type:subtype string.
"""
if self._subtype != '':
return '{}:::{}'.format(self._rrtype, self._subtype)
else:
return self._rrtype
@property
def redshifts(self):
return self._redshifts
def eval(self, coeff, wave, z):
"""Return template for given coefficients, wavelengths, and redshift
Args:
coeff : array of coefficients length self.nbasis
wave : wavelengths at which to evaluate template flux
z : redshift at which to evaluate template flux
Returns:
template flux array
Notes:
A single factor of (1+z)^-1 is applied to the resampled flux
to conserve integrated flux after redshifting.
"""
assert len(coeff) == self.nbasis
flux = self.flux.T.dot(coeff).T / (1+z)
return trapz_rebin(self.wave*(1+z), flux, wave)
def find_templates(template_dir=None):
"""Return list of redrock-\*.fits template files
Search directories in this order, returning results from first one found:
- template_dir
- $RR_TEMPLATE_DIR
- <redrock_code>/templates/
Args:
template_dir (str): optional directory containing the templates.
Returns:
list: a list of template files.
"""
if template_dir is None:
if 'RR_TEMPLATE_DIR' in os.environ:
template_dir = os.environ['RR_TEMPLATE_DIR']
else:
thisdir = os.path.dirname(__file__)
tempdir = os.path.join(os.path.abspath(thisdir), 'templates')
if os.path.exists(tempdir):
template_dir = tempdir
if template_dir is None:
raise IOError("ERROR: can't find template_dir, $RR_TEMPLATE_DIR, or {rrcode}/templates/")
else:
print('DEBUG: Read templates from {}'.format(template_dir) )
return sorted(glob(os.path.join(template_dir, 'rrtemplate-*.fits')))
class DistTemplatePiece(object):
"""One piece of the distributed template data.
This is a simple container for storing interpolated templates for a set of
redshift values. It is used for communicating the interpolated templates
between processes.
In the MPI case, each process will store at most two of these
simultaneously. This is the data that is computed on a single process and
passed between processes.
Args:
index (int): the chunk index of this piece- this corresponds to
the process rank that originally computed this piece.
redshifts (array): the redshift range contained in this piece.
data (list): a list of dictionaries, one for each redshift, and
each containing the 2D interpolated template values for all
"wavehash" keys.
"""
def __init__(self, index, redshifts, data):
self.index = index
self.redshifts = redshifts
self.data = data
def _mp_rebin_template(template, dwave, zlist, qout):
"""Function for multiprocessing version of rebinning.
"""
try:
results = dict()
for z in zlist:
binned = rebin_template(template, z, dwave)
results[z] = binned
qout.put(results)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
lines = [ "MP rebin: {}".format(x) for x in lines ]
print("".join(lines))
sys.stdout.flush()
return
class DistTemplate(object):
"""Distributed template data interpolated to all redshifts.
For a given template, the redshifts are distributed among the
processes in the communicator. Then each process will rebin the
template to those redshifts for the wavelength grids specified by
dwave.
Args:
template (Template): the template to distribute
dwave (dict): the keys are the "wavehash" and the values
are a 1D array containing the wavelength grid.
mp_procs (int): if not using MPI, restrict the number of
multiprocesses to this.
comm (mpi4py.MPI.Comm): (optional) the MPI communicator.
"""
def __init__(self, template, dwave, mp_procs=1, comm=None):
self._comm = comm
self._template = template
self._dwave = dwave
self._comm_rank = 0
self._comm_size = 1
if self._comm is not None:
self._comm_rank = self._comm.rank
self._comm_size = self._comm.size
self._distredshifts = np.array_split(self._template.redshifts,
self._comm_size)
myz = self._distredshifts[self._comm_rank]
nz = len(myz)
data = list()
# In the case of not using MPI (comm == None), one process is rebinning
# all the templates. In that scenario, use multiprocessing
# workers to do the rebinning.
if self._comm is not None:
# MPI case- compute our local redshifts
for z in myz:
binned = rebin_template(self._template, z, self._dwave)
data.append(binned)
else:
# We don't have MPI, so use multiprocessing
import multiprocessing as mp
qout = mp.Queue()
work = np.array_split(myz, mp_procs)
procs = list()
for i in range(mp_procs):
p = mp.Process(target=_mp_rebin_template,
args=(self._template, self._dwave, work[i], qout))
procs.append(p)
p.start()
# Extract the output into a single list
results = dict()
for i in range(mp_procs):
res = qout.get()
results.update(res)
for z in myz:
data.append(results[z])
# Correct spectra for Lyman-series
for i, z in enumerate(myz):
for k in list(self._dwave.keys()):
T = transmission_Lyman(z,self._dwave[k])
for vect in range(data[i][k].shape[1]):
data[i][k][:,vect] *= T
self._piece = DistTemplatePiece(self._comm_rank, myz, data)
@property
def comm(self):
return self._comm
@property
def template(self):
return self._template
@property
def local(self):
return self._piece
def cycle(self):
"""Pass our piece of data to the next process.
If we have returned to our original data, then return True, otherwise
return False.
Args:
Nothing
Returns (bool):
Whether we have finished (True) else False.
"""
# If we are not using MPI, this function is a no-op, so just return.
if self._comm is None:
return True
rank = self._comm_rank
nproc = self._comm_size
to_proc = rank + 1
if to_proc >= nproc:
to_proc = 0
from_proc = rank - 1
if from_proc < 0:
from_proc = nproc - 1
# Send our data and get a request handle for later checking.
req = self._comm.isend(self._piece, to_proc)
# Receive our data
incoming = self._comm.recv(source=from_proc)
# Wait for send to finishself._comm_rank = self._comm.rank
req.wait()
# Now replace our local piece with the new one
self._piece = incoming
# Are we done?
done = False
if self._piece.index == rank:
done = True
return done
def load_dist_templates(dwave, templates=None, comm=None, mp_procs=1):
"""Read and distribute templates from disk.
This reads one or more template files from disk and distributes them among
an MPI communicator. Each process will locally store interpolated data
for a redshift slice of each template. For a single redshift, the template
is interpolated to the wavelength grids specified by "dwave".
As an example, imagine 3 templates with independent redshift ranges. Also
imagine that the communicator has 2 processes. This function would return
a list of 3 DistTemplate objects. Within each of those objects, the 2
processes store the interpolated data for a subset of the redshift range:
DistTemplate #1: zmin1 <---- p0 ----> | <---- p1 ----> zmax1
DistTemplate #2: zmin2 <-- p0 --> | <-- p1 --> zmax2
DistTemplate #3: zmin3 <--- p0 ---> | <--- p1 ---> zmax3
Args:
dwave (dict): the dictionary of wavelength grids. Keys are the
"wavehash" and values are an array of wavelengths.
templates (str or None): if None, find all templates from the
redrock template directory. If a path to a file is specified,
load that single template. If a path to a directory is given,
load all templates in that directory.
comm (mpi4py.MPI.Comm): (optional) the MPI communicator.
mp_procs (int): if not using MPI, restrict the number of
multiprocesses to this.
Returns:
list: a list of DistTemplate objects.
"""
timer = elapsed(None, "", comm=comm)
template_files = None
if (comm is None) or (comm.rank == 0):
# Only one process needs to do this
if templates is not None:
if os.path.isfile(templates):
# we are using just a single file
template_files = [ templates ]
elif os.path.isdir(templates):
# this is a template dir
template_files = find_templates(template_dir=templates)
else:
print("{} is neither a file nor a directory"\
.format(templates))
sys.stdout.flush()
if comm is not None:
comm.Abort()
else:
template_files = find_templates()
if comm is not None:
template_files = comm.bcast(template_files, root=0)
template_data = list()
if (comm is None) or (comm.rank == 0):
for t in template_files:
template_data.append(Template(filename=t))
if comm is not None:
template_data = comm.bcast(template_data, root=0)
timer = elapsed(timer, "Read and broadcast of {} templates"\
.format(len(template_files)), comm=comm)
# Compute the interpolated templates in a distributed way with every
# process generating a slice of the redshift range.
dtemplates = list()
for t in template_data:
dtemplates.append(DistTemplate(t, dwave, mp_procs=mp_procs, comm=comm))
timer = elapsed(timer, "Rebinning templates", comm=comm)
return dtemplates
| 32.253247 | 97 | 0.587075 |
from __future__ import absolute_import, division, print_function
import sys
from glob import glob
import os
import traceback
import numpy as np
from astropy.io import fits
from .utils import native_endian, elapsed, transmission_Lyman
from .rebin import rebin_template, trapz_rebin
class Template(object):
def __init__(self, filename=None, spectype=None, redshifts=None,
wave=None, flux=None, subtype=None):
if filename is not None:
fx = None
if os.path.exists(filename):
fx = fits.open(filename, memmap=False)
else:
xfilename = os.path.join(os.getenv('RR_TEMPLATE_DIR'), filename)
if os.path.exists(xfilename):
fx = fits.open(xfilename, memmap=False)
else:
raise IOError('unable to find '+filename)
hdr = fx['BASIS_VECTORS'].header
if 'VERSION' in hdr:
self._version = hdr['VERSION']
else:
self._version = 'unknown'
self.wave = np.asarray(hdr['CRVAL1'] + \
hdr['CDELT1']*np.arange(hdr['NAXIS1']), dtype=np.float64)
if 'LOGLAM' in hdr and hdr['LOGLAM'] != 0:
self.wave = 10**self.wave
self.flux = np.asarray(native_endian(fx['BASIS_VECTORS'].data),
dtype=np.float64)
self._redshifts = None
try:
self._redshifts = native_endian(fx['REDSHIFTS'].data)
old_style_templates = False
except KeyError:
pass
fx.close()
self._rrtype = hdr['RRTYPE'].strip().upper()
if old_style_templates:
if self._rrtype == 'GALAXY':
self._redshifts = 10**np.arange(np.log10(1-0.005),
np.log10(1+1.7), 3e-4) - 1
elif self._rrtype == 'STAR':
self._redshifts = np.arange(-0.002, 0.00201, 4e-5)
elif self._rrtype == 'QSO':
self._redshifts = 10**np.arange(np.log10(1+0.05),
np.log10(1+6.0), 5e-4) - 1
else:
raise ValueError("Unknown redshift range to use for "
"template type {}".format(self._rrtype))
zmin = self._redshifts[0]
zmax = self._redshifts[-1]
print("DEBUG: Using default redshift range {:.4f}-{:.4f} for "
"{}".format(zmin, zmax, os.path.basename(filename)))
else:
zmin = self._redshifts[0]
zmax = self._redshifts[-1]
print("DEBUG: Using redshift range {:.4f}-{:.4f} for "
"{}".format(zmin, zmax, os.path.basename(filename)))
self._subtype = None
if 'RRSUBTYP' in hdr:
self._subtype = hdr['RRSUBTYP'].strip().upper()
else:
self._subtype = ''
else:
self._rrtype = spectype
self._redshifts = redshifts
self.wave = wave
self.flux = flux
self._subtype = subtype
self._nbasis = self.flux.shape[0]
self._nwave = self.flux.shape[1]
@property
def nbasis(self):
return self._nbasis
@property
def nwave(self):
return self._nwave
@property
def template_type(self):
return self._rrtype
@property
def sub_type(self):
return self._subtype
@property
def full_type(self):
if self._subtype != '':
return '{}:::{}'.format(self._rrtype, self._subtype)
else:
return self._rrtype
@property
def redshifts(self):
return self._redshifts
def eval(self, coeff, wave, z):
assert len(coeff) == self.nbasis
flux = self.flux.T.dot(coeff).T / (1+z)
return trapz_rebin(self.wave*(1+z), flux, wave)
def find_templates(template_dir=None):
if template_dir is None:
if 'RR_TEMPLATE_DIR' in os.environ:
template_dir = os.environ['RR_TEMPLATE_DIR']
else:
thisdir = os.path.dirname(__file__)
tempdir = os.path.join(os.path.abspath(thisdir), 'templates')
if os.path.exists(tempdir):
template_dir = tempdir
if template_dir is None:
raise IOError("ERROR: can't find template_dir, $RR_TEMPLATE_DIR, or {rrcode}/templates/")
else:
print('DEBUG: Read templates from {}'.format(template_dir) )
return sorted(glob(os.path.join(template_dir, 'rrtemplate-*.fits')))
class DistTemplatePiece(object):
def __init__(self, index, redshifts, data):
self.index = index
self.redshifts = redshifts
self.data = data
def _mp_rebin_template(template, dwave, zlist, qout):
try:
results = dict()
for z in zlist:
binned = rebin_template(template, z, dwave)
results[z] = binned
qout.put(results)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
lines = [ "MP rebin: {}".format(x) for x in lines ]
print("".join(lines))
sys.stdout.flush()
return
class DistTemplate(object):
def __init__(self, template, dwave, mp_procs=1, comm=None):
self._comm = comm
self._template = template
self._dwave = dwave
self._comm_rank = 0
self._comm_size = 1
if self._comm is not None:
self._comm_rank = self._comm.rank
self._comm_size = self._comm.size
self._distredshifts = np.array_split(self._template.redshifts,
self._comm_size)
myz = self._distredshifts[self._comm_rank]
nz = len(myz)
data = list()
# In the case of not using MPI (comm == None), one process is rebinning
# all the templates. In that scenario, use multiprocessing
# workers to do the rebinning.
if self._comm is not None:
# MPI case- compute our local redshifts
for z in myz:
binned = rebin_template(self._template, z, self._dwave)
data.append(binned)
else:
# We don't have MPI, so use multiprocessing
import multiprocessing as mp
qout = mp.Queue()
work = np.array_split(myz, mp_procs)
procs = list()
for i in range(mp_procs):
p = mp.Process(target=_mp_rebin_template,
args=(self._template, self._dwave, work[i], qout))
procs.append(p)
p.start()
results = dict()
for i in range(mp_procs):
res = qout.get()
results.update(res)
for z in myz:
data.append(results[z])
for i, z in enumerate(myz):
for k in list(self._dwave.keys()):
T = transmission_Lyman(z,self._dwave[k])
for vect in range(data[i][k].shape[1]):
data[i][k][:,vect] *= T
self._piece = DistTemplatePiece(self._comm_rank, myz, data)
@property
def comm(self):
return self._comm
@property
def template(self):
return self._template
@property
def local(self):
return self._piece
def cycle(self):
if self._comm is None:
return True
rank = self._comm_rank
nproc = self._comm_size
to_proc = rank + 1
if to_proc >= nproc:
to_proc = 0
from_proc = rank - 1
if from_proc < 0:
from_proc = nproc - 1
req = self._comm.isend(self._piece, to_proc)
incoming = self._comm.recv(source=from_proc)
req.wait()
self._piece = incoming
done = False
if self._piece.index == rank:
done = True
return done
def load_dist_templates(dwave, templates=None, comm=None, mp_procs=1):
timer = elapsed(None, "", comm=comm)
template_files = None
if (comm is None) or (comm.rank == 0):
if templates is not None:
if os.path.isfile(templates):
template_files = [ templates ]
elif os.path.isdir(templates):
template_files = find_templates(template_dir=templates)
else:
print("{} is neither a file nor a directory"\
.format(templates))
sys.stdout.flush()
if comm is not None:
comm.Abort()
else:
template_files = find_templates()
if comm is not None:
template_files = comm.bcast(template_files, root=0)
template_data = list()
if (comm is None) or (comm.rank == 0):
for t in template_files:
template_data.append(Template(filename=t))
if comm is not None:
template_data = comm.bcast(template_data, root=0)
timer = elapsed(timer, "Read and broadcast of {} templates"\
.format(len(template_files)), comm=comm)
dtemplates = list()
for t in template_data:
dtemplates.append(DistTemplate(t, dwave, mp_procs=mp_procs, comm=comm))
timer = elapsed(timer, "Rebinning templates", comm=comm)
return dtemplates
| true | true |
f72bf05616bf34cf98330d2cbaf1008bb162279a | 1,420 | py | Python | redbot/message/headers/x_cache.py | thinkbox/redbot | 90744dd971389bbf435d200483309b70b748785a | [
"Unlicense"
] | 1 | 2019-06-27T13:02:52.000Z | 2019-06-27T13:02:52.000Z | redbot/message/headers/x_cache.py | thinkbox/redbot | 90744dd971389bbf435d200483309b70b748785a | [
"Unlicense"
] | null | null | null | redbot/message/headers/x_cache.py | thinkbox/redbot | 90744dd971389bbf435d200483309b70b748785a | [
"Unlicense"
] | null | null | null | #!/usr/bin/env python
__author__ = "Mark Nottingham <mnot@mnot.net>"
__copyright__ = """\
Copyright (c) 2008-2013 Mark Nottingham
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.
"""
import redbot.speak as rs
from redbot.message import headers as rh
from redbot.message import http_syntax as syntax
@rh.GenericHeaderSyntax
def parse(subject, value, red):
# see #63
return value
def join(subject, values, red):
return values | 37.368421 | 77 | 0.783803 |
__author__ = "Mark Nottingham <mnot@mnot.net>"
__copyright__ = """\
Copyright (c) 2008-2013 Mark Nottingham
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.
"""
import redbot.speak as rs
from redbot.message import headers as rh
from redbot.message import http_syntax as syntax
@rh.GenericHeaderSyntax
def parse(subject, value, red):
return value
def join(subject, values, red):
return values | true | true |
f72bf18fa11ed33b50a81cfc1f4e0efdcb4066ad | 8,001 | py | Python | Source/FetchData/Fetch_Data_Stock_CHN_Daily.py | guissy/StockRecommendSystem | 2e8694d0bb2ceaa42585ee7414564d921cc5a854 | [
"MIT"
] | null | null | null | Source/FetchData/Fetch_Data_Stock_CHN_Daily.py | guissy/StockRecommendSystem | 2e8694d0bb2ceaa42585ee7414564d921cc5a854 | [
"MIT"
] | null | null | null | Source/FetchData/Fetch_Data_Stock_CHN_Daily.py | guissy/StockRecommendSystem | 2e8694d0bb2ceaa42585ee7414564d921cc5a854 | [
"MIT"
] | null | null | null | import sys, os, time, datetime, warnings, configparser
import pandas as pd
import numpy as np
import tushare as ts
import concurrent.futures
from tqdm import tqdm
cur_path = os.path.dirname(os.path.abspath(__file__))
for _ in range(2):
root_path = cur_path[0:cur_path.rfind('/', 0, len(cur_path))]
cur_path = root_path
sys.path.append(root_path + "/" + 'Source/DataBase/')
from Source.DataBase.DB_API import queryStock, storeStock, queryStockList, storeStockList, queryStockPublishDay, storePublishDay
def getStocksList(root_path):
try:
df = queryStockList(root_path, "DB_STOCK", "SHEET_CHN_DAILY")
df.index = df.index.astype(str).str.zfill(6)
except Exception as e:
df = pd.DataFrame()
if df.empty == False: return df
import subprocess
subprocess.Popen('brew services restart mongodb'.split())
stock_info = ts.get_stock_basics()
listData = pd.DataFrame(stock_info)
#listData.index.name = 'symbol'
#listData.index = listData.index.astype(str).str.zfill(6) #[str(symbol).zfill(6) for symbol in listData.index] #listData.index.astype(str).str.zfill(6)
#print(listData.index)
#listData['symbol'] = listData['symbol'].str.strip()
storeStockList(root_path, "DB_STOCK", "SHEET_CHN_DAILY", listData)
df = queryStockList(root_path, "DB_STOCK", "SHEET_CHN_DAILY")
df.index = df.index.astype(str).str.zfill(6)
return df
def getSingleStock(symbol):
repeat_times = 1
message = ""
df = pd.DataFrame()
for _ in range(repeat_times):
try:
data = ts.get_hist_data(symbol)
data.sort_index(ascending=True, inplace=True)
return data, ""
except Exception as e:
message = symbol + " fetch exception: " + str(e)
continue
return df, message
def getSingleStockByTime(symbol, from_date, till_date):
start = from_date.split('-')
start_y, start_m, start_d = start[0], start[1], start[2] # starting date
end = till_date.split('-')
end_y, end_m, end_d = end[0], end[1], end[2] # until now
repeat_times = 1
message = ""
df = pd.DataFrame()
for _ in range(repeat_times):
try:
data = ts.get_hist_data(symbol, from_date, till_date)
data.sort_index(ascending=True, inplace=True)
return data, ""
except Exception as e:
message = symbol + " fetch exception: " + str(e)
continue
return df, message
def judgeOpenDaysInRange(from_date, to_date):
holidays=["2017-01-01", "2017-01-02",
"2017-01-27", "2017-01-28", "2017-01-29", "2017-01-30", "2017-01-31", "2017-02-01", "2017-02-02",
"2017-04-02", "2017-04-03", "2017-04-04",
"2017-05-01",
"2017-05-28", "2017-05-29", "2017-05-30",
"2017-10-01", "2017-10-02", "2017-10-03", "2017-10-04", "2017-10-05","2017-10-06","2017-10-07","2017-10-08"]
#holidays = cal.holidays(from_date, to_date)
duedays = pd.bdate_range(from_date, to_date)
df = pd.DataFrame()
df['date'] = duedays
df['holiday'] = duedays.isin(holidays)
opendays = df[df['holiday'] == False]
return opendays
def judgeNeedPostDownload(from_date, to_date):
today = datetime.datetime.now()
start_date = pd.Timestamp(from_date)
end_date = pd.Timestamp(to_date)
if start_date > today: return False
if end_date > today: to_date = today.strftime("%Y-%m-%d")
dateList = judgeOpenDaysInRange(from_date, to_date)
if len(dateList) > 0: return True
return False
def updateSingleStockData(root_path, symbol, force_check):
startTime = time.time()
message = ""
if len(symbol) == 0: return startTime, message
till_date = (datetime.datetime.now()).strftime("%Y-%m-%d")
end_date = pd.Timestamp(till_date)
stockData, lastUpdateTime = queryStock(root_path, "DB_STOCK", "SHEET_CHN_DAILY", symbol)
if stockData.empty:
stockData, message = getSingleStock(symbol)
if stockData.empty == False:
storeStock(root_path, "DB_STOCK", "SHEET_CHN_DAILY", symbol, stockData)
return startTime, message
modified = False
first_date = pd.Timestamp(stockData.index[0])
last_date = pd.Timestamp(stockData.index[-1])
updateOnce = end_date > lastUpdateTime
if end_date > last_date and (updateOnce or force_check):
to_date = (last_date + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
if judgeNeedPostDownload(to_date, till_date):
message = message + ", download post data from " + to_date + " to " + till_date
moreStockData, tempMessage = getSingleStockByTime(symbol, to_date, till_date)
message = message + tempMessage
if len(moreStockData) > 0:
if isinstance(moreStockData.index, pd.DatetimeIndex):
moreStockData.index = moreStockData.index.strftime("%Y-%m-%d")
modified = True
stockData = pd.concat([stockData, moreStockData])
stockData.index.name = 'date'
if modified:
stockData = stockData[~stockData.index.duplicated(keep='first')]
storeStock(root_path, "DB_STOCK", "SHEET_CHN_DAILY", symbol, stockData)
elif updateOnce:
stockData = stockData[~stockData.index.duplicated(keep='first')]
storeStock(root_path, "DB_STOCK", "SHEET_CHN_DAILY", symbol, stockData)
message = message + ", nothing updated"
else:
message = ""
return startTime, message
def updateStockData_CHN(root_path, storeType, force_check = False):
symbols = getStocksList(root_path).index.values.tolist()
pbar = tqdm(total=len(symbols))
if storeType == 2:
for symbol in symbols:
startTime, message = updateSingleStockData(root_path, symbol, force_check)
outMessage = '%-*s fetched in: %.4s seconds' % (6, symbol, (time.time() - startTime))
pbar.set_description(outMessage)
pbar.update(1)
if storeType == 1:
log_errors = []
log_update = []
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
# Start the load operations and mark each future with its URL
future_to_stock = {executor.submit(updateSingleStockData, root_path, symbol, force_check): symbol for symbol in symbols}
for future in concurrent.futures.as_completed(future_to_stock):
stock = future_to_stock[future]
try:
startTime, message = future.result()
except Exception as exc:
startTime = time.time()
log_errors.append('%r generated an exception: %s' % (stock, exc))
else:
if len(message) > 0: log_update.append(message)
outMessage = '%-*s fetched in: %.4s seconds' % (6, stock, (time.time() - startTime))
pbar.set_description(outMessage)
pbar.update(1)
if len(log_errors) > 0: print(log_errors)
# if len(log_update) > 0: print(log_update)
pbar.close()
return symbols
if __name__ == "__main__":
pd.set_option('precision', 3)
pd.set_option('display.width',1000)
warnings.filterwarnings('ignore', category=pd.io.pytables.PerformanceWarning)
config = configparser.ConfigParser()
config.read(root_path + "/" + "config.ini")
storeType = int(config.get('Setting', 'StoreType'))
if storeType == 1:
from Start_DB_Server import StartServer, ShutdownServer
# start database server (async)
thread = StartServer(root_path)
# wait for db start, the standard procedure should listen to
# the completed event of function "StartServer"
time.sleep(5)
updateStockData_CHN(root_path, storeType)
if storeType == 1:
# stop database server (sync)
time.sleep(5)
ShutdownServer()
| 38.282297 | 155 | 0.632921 | import sys, os, time, datetime, warnings, configparser
import pandas as pd
import numpy as np
import tushare as ts
import concurrent.futures
from tqdm import tqdm
cur_path = os.path.dirname(os.path.abspath(__file__))
for _ in range(2):
root_path = cur_path[0:cur_path.rfind('/', 0, len(cur_path))]
cur_path = root_path
sys.path.append(root_path + "/" + 'Source/DataBase/')
from Source.DataBase.DB_API import queryStock, storeStock, queryStockList, storeStockList, queryStockPublishDay, storePublishDay
def getStocksList(root_path):
try:
df = queryStockList(root_path, "DB_STOCK", "SHEET_CHN_DAILY")
df.index = df.index.astype(str).str.zfill(6)
except Exception as e:
df = pd.DataFrame()
if df.empty == False: return df
import subprocess
subprocess.Popen('brew services restart mongodb'.split())
stock_info = ts.get_stock_basics()
listData = pd.DataFrame(stock_info)
ET_CHN_DAILY")
df.index = df.index.astype(str).str.zfill(6)
return df
def getSingleStock(symbol):
repeat_times = 1
message = ""
df = pd.DataFrame()
for _ in range(repeat_times):
try:
data = ts.get_hist_data(symbol)
data.sort_index(ascending=True, inplace=True)
return data, ""
except Exception as e:
message = symbol + " fetch exception: " + str(e)
continue
return df, message
def getSingleStockByTime(symbol, from_date, till_date):
start = from_date.split('-')
start_y, start_m, start_d = start[0], start[1], start[2]
end = till_date.split('-')
end_y, end_m, end_d = end[0], end[1], end[2]
repeat_times = 1
message = ""
df = pd.DataFrame()
for _ in range(repeat_times):
try:
data = ts.get_hist_data(symbol, from_date, till_date)
data.sort_index(ascending=True, inplace=True)
return data, ""
except Exception as e:
message = symbol + " fetch exception: " + str(e)
continue
return df, message
def judgeOpenDaysInRange(from_date, to_date):
holidays=["2017-01-01", "2017-01-02",
"2017-01-27", "2017-01-28", "2017-01-29", "2017-01-30", "2017-01-31", "2017-02-01", "2017-02-02",
"2017-04-02", "2017-04-03", "2017-04-04",
"2017-05-01",
"2017-05-28", "2017-05-29", "2017-05-30",
"2017-10-01", "2017-10-02", "2017-10-03", "2017-10-04", "2017-10-05","2017-10-06","2017-10-07","2017-10-08"]
duedays = pd.bdate_range(from_date, to_date)
df = pd.DataFrame()
df['date'] = duedays
df['holiday'] = duedays.isin(holidays)
opendays = df[df['holiday'] == False]
return opendays
def judgeNeedPostDownload(from_date, to_date):
today = datetime.datetime.now()
start_date = pd.Timestamp(from_date)
end_date = pd.Timestamp(to_date)
if start_date > today: return False
if end_date > today: to_date = today.strftime("%Y-%m-%d")
dateList = judgeOpenDaysInRange(from_date, to_date)
if len(dateList) > 0: return True
return False
def updateSingleStockData(root_path, symbol, force_check):
startTime = time.time()
message = ""
if len(symbol) == 0: return startTime, message
till_date = (datetime.datetime.now()).strftime("%Y-%m-%d")
end_date = pd.Timestamp(till_date)
stockData, lastUpdateTime = queryStock(root_path, "DB_STOCK", "SHEET_CHN_DAILY", symbol)
if stockData.empty:
stockData, message = getSingleStock(symbol)
if stockData.empty == False:
storeStock(root_path, "DB_STOCK", "SHEET_CHN_DAILY", symbol, stockData)
return startTime, message
modified = False
first_date = pd.Timestamp(stockData.index[0])
last_date = pd.Timestamp(stockData.index[-1])
updateOnce = end_date > lastUpdateTime
if end_date > last_date and (updateOnce or force_check):
to_date = (last_date + datetime.timedelta(days=1)).strftime("%Y-%m-%d")
if judgeNeedPostDownload(to_date, till_date):
message = message + ", download post data from " + to_date + " to " + till_date
moreStockData, tempMessage = getSingleStockByTime(symbol, to_date, till_date)
message = message + tempMessage
if len(moreStockData) > 0:
if isinstance(moreStockData.index, pd.DatetimeIndex):
moreStockData.index = moreStockData.index.strftime("%Y-%m-%d")
modified = True
stockData = pd.concat([stockData, moreStockData])
stockData.index.name = 'date'
if modified:
stockData = stockData[~stockData.index.duplicated(keep='first')]
storeStock(root_path, "DB_STOCK", "SHEET_CHN_DAILY", symbol, stockData)
elif updateOnce:
stockData = stockData[~stockData.index.duplicated(keep='first')]
storeStock(root_path, "DB_STOCK", "SHEET_CHN_DAILY", symbol, stockData)
message = message + ", nothing updated"
else:
message = ""
return startTime, message
def updateStockData_CHN(root_path, storeType, force_check = False):
symbols = getStocksList(root_path).index.values.tolist()
pbar = tqdm(total=len(symbols))
if storeType == 2:
for symbol in symbols:
startTime, message = updateSingleStockData(root_path, symbol, force_check)
outMessage = '%-*s fetched in: %.4s seconds' % (6, symbol, (time.time() - startTime))
pbar.set_description(outMessage)
pbar.update(1)
if storeType == 1:
log_errors = []
log_update = []
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
future_to_stock = {executor.submit(updateSingleStockData, root_path, symbol, force_check): symbol for symbol in symbols}
for future in concurrent.futures.as_completed(future_to_stock):
stock = future_to_stock[future]
try:
startTime, message = future.result()
except Exception as exc:
startTime = time.time()
log_errors.append('%r generated an exception: %s' % (stock, exc))
else:
if len(message) > 0: log_update.append(message)
outMessage = '%-*s fetched in: %.4s seconds' % (6, stock, (time.time() - startTime))
pbar.set_description(outMessage)
pbar.update(1)
if len(log_errors) > 0: print(log_errors)
pbar.close()
return symbols
if __name__ == "__main__":
pd.set_option('precision', 3)
pd.set_option('display.width',1000)
warnings.filterwarnings('ignore', category=pd.io.pytables.PerformanceWarning)
config = configparser.ConfigParser()
config.read(root_path + "/" + "config.ini")
storeType = int(config.get('Setting', 'StoreType'))
if storeType == 1:
from Start_DB_Server import StartServer, ShutdownServer
thread = StartServer(root_path)
time.sleep(5)
updateStockData_CHN(root_path, storeType)
if storeType == 1:
time.sleep(5)
ShutdownServer()
| true | true |
f72bf3adc21681236ec82aae83471ffedf35ef9b | 817 | py | Python | src/10-async-web/acityscape_api/app.py | NissesSenap/async-techniques-python-course | 455c7222b52e7c3aa7f4eb4b03e9b6f0a99adaef | [
"MIT"
] | 380 | 2018-09-26T17:40:52.000Z | 2022-03-29T02:38:17.000Z | src/10-async-web/acityscape_api/app.py | NissesSenap/async-techniques-python-course | 455c7222b52e7c3aa7f4eb4b03e9b6f0a99adaef | [
"MIT"
] | 13 | 2018-09-30T05:55:40.000Z | 2022-01-24T20:40:09.000Z | src/10-async-web/acityscape_api/app.py | NissesSenap/async-techniques-python-course | 455c7222b52e7c3aa7f4eb4b03e9b6f0a99adaef | [
"MIT"
] | 214 | 2018-09-26T18:53:17.000Z | 2021-12-30T16:58:27.000Z | import quart
from views import city_api
from views import home
from config import settings
import services.weather_service
import services.sun_service
import services.location_service
app = quart.Quart(__name__)
is_debug = True
app.register_blueprint(home.blueprint)
app.register_blueprint(city_api.blueprint)
def configure_app():
mode = 'dev' if is_debug else 'prod'
data = settings.load(mode)
services.weather_service.global_init(data.get('weather_key'))
services.sun_service.use_cached_data = data.get('use_cached_data')
services.location_service.use_cached_data = data.get('use_cached_data')
print("Using cached data? {}".format(data.get('use_cached_data')))
def run_web_app():
app.run(debug=is_debug, port=5001)
configure_app()
if __name__ == '__main__':
run_web_app()
| 23.342857 | 75 | 0.767442 | import quart
from views import city_api
from views import home
from config import settings
import services.weather_service
import services.sun_service
import services.location_service
app = quart.Quart(__name__)
is_debug = True
app.register_blueprint(home.blueprint)
app.register_blueprint(city_api.blueprint)
def configure_app():
mode = 'dev' if is_debug else 'prod'
data = settings.load(mode)
services.weather_service.global_init(data.get('weather_key'))
services.sun_service.use_cached_data = data.get('use_cached_data')
services.location_service.use_cached_data = data.get('use_cached_data')
print("Using cached data? {}".format(data.get('use_cached_data')))
def run_web_app():
app.run(debug=is_debug, port=5001)
configure_app()
if __name__ == '__main__':
run_web_app()
| true | true |
f72bf4d9ad27aa607870ea1c9ce5ee5bb7ccd384 | 1,009 | py | Python | plaid_project/contrib/sites/migrations/0003_set_site_domain_and_name.py | reetikaSR/PlaidProject | 904bd7fd3412a4b5149aae899abcf8794bebba81 | [
"MIT"
] | null | null | null | plaid_project/contrib/sites/migrations/0003_set_site_domain_and_name.py | reetikaSR/PlaidProject | 904bd7fd3412a4b5149aae899abcf8794bebba81 | [
"MIT"
] | null | null | null | plaid_project/contrib/sites/migrations/0003_set_site_domain_and_name.py | reetikaSR/PlaidProject | 904bd7fd3412a4b5149aae899abcf8794bebba81 | [
"MIT"
] | null | null | null | """
To understand why this file is here, please read:
http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""
from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID,
defaults={
"domain": "127.0.0.1",
"name": "plaid_project",
},
)
def update_site_backward(apps, schema_editor):
"""Revert site domain and name to default."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID, defaults={"domain": "example.com", "name": "example.com"}
)
class Migration(migrations.Migration):
dependencies = [("sites", "0002_alter_domain_unique")]
operations = [migrations.RunPython(update_site_forward, update_site_backward)]
| 28.828571 | 129 | 0.684836 | from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID,
defaults={
"domain": "127.0.0.1",
"name": "plaid_project",
},
)
def update_site_backward(apps, schema_editor):
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings.SITE_ID, defaults={"domain": "example.com", "name": "example.com"}
)
class Migration(migrations.Migration):
dependencies = [("sites", "0002_alter_domain_unique")]
operations = [migrations.RunPython(update_site_forward, update_site_backward)]
| true | true |
f72bf52ed5ae857e2f0a8b16ca7cacfc142bfbdb | 3,895 | py | Python | utils.py | ambareeshravi/TrafficSignClassifier_API | 8628057439ee70f6d827abf931071e9b6539bd5b | [
"MIT"
] | null | null | null | utils.py | ambareeshravi/TrafficSignClassifier_API | 8628057439ee70f6d827abf931071e9b6539bd5b | [
"MIT"
] | null | null | null | utils.py | ambareeshravi/TrafficSignClassifier_API | 8628057439ee70f6d827abf931071e9b6539bd5b | [
"MIT"
] | null | null | null | '''
Author: Ambareesh Ravi
Date: Jul 31, 2021
Title: utils.py
Description:
Contains utility and helper functions for the project
'''
# Libraries imports
import numpy as np
import pandas as pd
import os
from tqdm import tqdm
from time import time
from glob import glob
from PIL import Image
import matplotlib.pyplot as plt
import argparse
import cv2
# Global variables
MANUAL_SEED = 42
np.random.seed(42)
def INFO(s):
'''
Prints information in a particular format
Args:
s - string <str> to be printed
Returns:
-
Exception:
-
'''
print("-"*40)
print("INFO:", s)
print("-"*40)
def read_directory_content(path):
'''
Reads all files in a directory given a path
Args:
path - path for the directory as <str>
Returns:
sorted list of files in the directory
Exception:
-
'''
if "*" not in path: path = os.path.join(path, "*")
return sorted(glob(path))
def create_directory(path):
'''
Creates a directory given a path if the path does not exist
Args:
path - path for the directory as <str>
Returns:
-
Exception:
-
'''
# Create a directory
if not os.path.exists(path): os.mkdir(path)
def save_image(array, path, resize = False, extension = ".png"):
'''
Saves an array into an image file
Args:
array - image as a <np.array>
path - path for the image as <str>
resize - [optional] to resize image to given size - <tuple> of <int> (w,h)
extension - [optional] type of image file as <str>
Returns:
-
Exception:
-
'''
# Add image extension
if extension not in path:
path = path.split(".")[0] + extension
# Save image into a file using PIL Image handle
img = Image.fromarray(array)
# Resize image if reaquired
if resize: img = img.resize(resize)
# Save image
img.save(path)
def read_image(image_path):
'''
Reads an image from the given path as a PIL.Image handle
Args:
image_path - path for the image as <str>
Returns:
-
Exception:
-
'''
return Image.open(image_path)
class Visualizer:
def __init__(self,):
'''
Initializes the class to visualize results in comparison with the inputs
Args:
-
Returns:
-
Exception:
-
'''
pass
def gray2color(self, x):
'''
Converts a single channel grayscale image to coloured 3 channel format
Args:
x - input as <np.array>
Returns:
-
Exception:
-
'''
return np.repeat(np.expand_dims(x, axis = -1), 3, axis = -1)
def visualize_composite(self, input_image, label, prediction, margin = 8, save_path = None):
'''
Function to visualize input, label, prediction together in an image
Args:
input_image - input RGB image as <np.array>
label - label binary mask Grayscale image as <np.array>
prediction - predicted binary mask Grayscale image as <np.array>
margin - margin between images in terms of pixels in <int>
save_path - path to save the file <str>
Returns:
-
Exception:
-
'''
rounded_pred = np.round(prediction)
margin = np.ones((label.shape[0], margin, 3))
composite = np.hstack((input_image, margin, self.gray2color(label), margin, self.gray2color(rounded_pred)))
img = Image.fromarray((composite*255).astype(np.uint8))
if save_path: save_image()
return img
| 22.911765 | 115 | 0.558408 |
import numpy as np
import pandas as pd
import os
from tqdm import tqdm
from time import time
from glob import glob
from PIL import Image
import matplotlib.pyplot as plt
import argparse
import cv2
MANUAL_SEED = 42
np.random.seed(42)
def INFO(s):
print("-"*40)
print("INFO:", s)
print("-"*40)
def read_directory_content(path):
if "*" not in path: path = os.path.join(path, "*")
return sorted(glob(path))
def create_directory(path):
if not os.path.exists(path): os.mkdir(path)
def save_image(array, path, resize = False, extension = ".png"):
if extension not in path:
path = path.split(".")[0] + extension
img = Image.fromarray(array)
if resize: img = img.resize(resize)
img.save(path)
def read_image(image_path):
return Image.open(image_path)
class Visualizer:
def __init__(self,):
pass
def gray2color(self, x):
return np.repeat(np.expand_dims(x, axis = -1), 3, axis = -1)
def visualize_composite(self, input_image, label, prediction, margin = 8, save_path = None):
rounded_pred = np.round(prediction)
margin = np.ones((label.shape[0], margin, 3))
composite = np.hstack((input_image, margin, self.gray2color(label), margin, self.gray2color(rounded_pred)))
img = Image.fromarray((composite*255).astype(np.uint8))
if save_path: save_image()
return img
| true | true |
f72bf7299d2697d596b1a5964fe20792a37b1d6a | 14,540 | py | Python | fortiosapi/fortiosapi.py | javcasalc/fortiosapi | 5dd35b59cfa8b87aee2a10f2303595c3da2347df | [
"Apache-2.0"
] | null | null | null | fortiosapi/fortiosapi.py | javcasalc/fortiosapi | 5dd35b59cfa8b87aee2a10f2303595c3da2347df | [
"Apache-2.0"
] | null | null | null | fortiosapi/fortiosapi.py | javcasalc/fortiosapi | 5dd35b59cfa8b87aee2a10f2303595c3da2347df | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Copyright 2015 Fortinet, Inc.
#
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
###################################################################
#
# fortiosapi.py aims at simplyfing the configuration and
# integration of Fortgate configuration using the restapi
#
# A Python module to abstract configuration using FortiOS REST API
#
###################################################################
import json
# Set default logging handler to avoid "No handler found" warnings.
import logging
import subprocess
import time
import paramiko
import requests
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
# Disable warnings about certificates.
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# may need to move to specifying the ca or use Verify=false
# cafile = 'cacert.pem'
# r = requests.get(url, verify=cafile)
logging.getLogger(__name__).addHandler(NullHandler())
# create logger
LOG = logging.getLogger('fortiosapi')
class FortiOSAPI(object):
def __init__(self):
self._https = True
self._fortiversion = "Version is set when logged"
# reference the fortinet version of the targeted product.
self._session = requests.session() # use single session
# persistant and same for all
self._session.verify = False
# (can be changed to) self._session.verify = '/path/to/certfile'
def logging(self, response):
try:
LOG.debug("Request : %s on url : %s ", response.request.method,
response.request.url)
LOG.debug("Response : http code %s reason : %s ",
response.status_code, response.reason)
LOG.debug("raw response: %s ", response.content)
except:
LOG.warning("method errors in request when global")
def debug(self, status):
if status == 'on':
LOG.setLevel(logging.DEBUG)
def formatresponse(self, res, vdom=None):
LOG.debug("formating response")
self.logging(res)
# Generic way to format the return from FortiAPI
# If vdom is global the resp is a dict of resp (even 1)
# 1 per vdom we check only the first one here (might need a more
# complex check)
if vdom == "global":
resp = json.loads(res.content.decode('utf-8'))[0]
resp['vdom'] = "global"
else:
LOG.debug("content res: %s", res.content)
resp = json.loads(res.content.decode('utf-8'))
return resp
def https(self, status):
if status == 'on':
self._https = True
if status == 'off':
self._https = False
def update_cookie(self):
# Retrieve server csrf and update session's headers
LOG.debug("cookies are : %s ", self._session.cookies)
for cookie in self._session.cookies:
if cookie.name == 'ccsrftoken':
csrftoken = cookie.value[1:-1] # token stored as a list
LOG.debug("csrftoken before update : %s ", csrftoken)
self._session.headers.update({'X-CSRFTOKEN': csrftoken})
LOG.debug("csrftoken after update : %s ", csrftoken)
def login(self, host, username, password, https_port=443):
self.host = host
if self._https is True:
self.url_prefix = 'https://' + self.host + ':' + https_port
else:
self.url_prefix = 'http://' + self.host
url = self.url_prefix + '/logincheck'
res = self._session.post(
url,
data='username=' + username + '&secretkey=' + password + "&ajax=1")
self.logging(res)
# Ajax=1 documented in 5.6 API ref but available on 5.4
if res.content.decode('ascii')[0] == '1':
# Update session's csrftoken
self.update_cookie()
else:
raise Exception('login failed')
try:
self._fortiversion = self.monitor('system', 'interface')['version']
except:
raise Exception('can not get following login')
# Might be wise to return the license status here
def get_version(self):
return self._fortiversion
def get_mkey(self, path, name, vdom=None, data=None):
# retreive the table mkey from schema
schema = self.schema(path, name, vdom=None)
try:
keyname = schema['mkey']
except KeyError:
LOG.warning("there is no mkey for %s/%s", path, name)
return None
try:
mkey = data[keyname]
except KeyError:
LOG.warning("mkey %s not set in the data", mkey)
return None
return mkey
def logout(self):
url = self.url_prefix + '/logout'
res = self._session.post(url)
self._session.close()
self._session.cookies.clear()
self.logging(res)
def cmdb_url(self, path, name, vdom, mkey=None):
# return builded URL
url_postfix = '/api/v2/cmdb/' + path + '/' + name
if mkey:
url_postfix = url_postfix + '/' + str(mkey)
if vdom:
LOG.debug("vdom is: %s", vdom)
if vdom == "global":
url_postfix += '?global=1'
else:
url_postfix += '?vdom=' + vdom
url = self.url_prefix + url_postfix
LOG.debug("urlbuild is %s with crsf: %s", url, self._session.headers)
return url
def mon_url(self, path, name, vdom=None, mkey=None):
# return builded URL
url_postfix = '/api/v2/monitor/' + path + '/' + name
if mkey:
url_postfix = url_postfix + '/' + str(mkey)
if vdom:
LOG.debug("vdom is: %s", vdom)
if vdom == "global":
url_postfix += '?global=1'
else:
url_postfix += '?vdom=' + vdom
url = self.url_prefix + url_postfix
return url
def monitor(self, path, name, vdom=None, mkey=None, parameters=None):
url = self.mon_url(path, name, vdom, mkey)
res = self._session.get(url, params=parameters)
LOG.debug("in MONITOR function")
return self.formatresponse(res, vdom=vdom)
def download(self, path, name, vdom=None, mkey=None, parameters=None):
url = self.mon_url(path, name)
res = self._session.get(url, params=parameters)
LOG.debug("in DOWNLOAD function")
return res
def upload(self, path, name, vdom=None, mkey=None,
parameters=None, data=None, files=None):
url = self.mon_url(path, name)
res = self._session.post(url, params=parameters,
data=data, files=files)
LOG.debug("in UPLOAD function")
return res
def get(self, path, name, vdom=None, mkey=None, parameters=None):
url = self.cmdb_url(path, name, vdom, mkey)
res = self._session.get(url, params=parameters)
LOG.debug("in GET function")
return self.formatresponse(res, vdom=vdom)
def schema(self, path, name, vdom=None):
# vdom or global is managed in cmdb_url
if vdom is None:
url = self.cmdb_url(path, name, vdom) + "?action=schema"
else:
url = self.cmdb_url(path, name, vdom) + "&action=schema"
res = self._session.get(url)
self.logging(res)
if res.status_code is 200:
return json.loads(res.content.decode('utf-8'))['results']
else:
return json.loads(res.content.decode('utf-8'))
def get_name_path_dict(self, vdom=None):
# return builded URL
url_postfix = '/api/v2/cmdb/'
if vdom is None:
url_postfix += '?vdom=' + vdom + "&action=schema"
else:
url_postfix += "?action=schema"
url = self.url_prefix + url_postfix
cmdbschema = self._session.get(url)
self.logging(cmdbschema)
j = json.loads(cmdbschema.content.decode('utf-8'))['results']
dict = []
for keys in j:
if "__tree__" not in keys['path']:
dict.append(keys['path'] + " " + keys['name'])
return dict
def post(self, path, name, vdom=None,
mkey=None, parameters=None, data=None):
if not mkey:
mkey = self.get_mkey(path, name, vdom=vdom, data=data)
# post with mkey will return a 404 as the next level is not there yet
url = self.cmdb_url(path, name, vdom, mkey=None)
res = self._session.post(
url, params=parameters, data=json.dumps(data))
LOG.debug("in POST function")
return self.formatresponse(res, vdom=vdom)
def put(self, path, name, vdom=None,
mkey=None, parameters=None, data=None):
if not mkey:
mkey = self.get_mkey(path, name, vdom=vdom, data=data)
url = self.cmdb_url(path, name, vdom, mkey)
res = self._session.put(url, params=parameters,
data=json.dumps(data))
LOG.debug("in PUT function")
return self.formatresponse(res, vdom=vdom)
def delete(self, path, name, vdom=None,
mkey=None, parameters=None, data=None):
# Need to find the type of the mkey to avoid error when integer assume
# the other types will be ok.
if not mkey:
mkey = self.get_mkey(path, name, vdom=vdom, data=data)
url = self.cmdb_url(path, name, vdom, mkey)
res = self._session.delete(
url, params=parameters, data=json.dumps(data))
LOG.debug("in DELETE function")
return self.formatresponse(res, vdom=vdom)
# Set will try to put if err code is 424 will try put (ressource exists)
# may add a force option to delete and redo if troubles.
def set(self, path, name, vdom=None,
mkey=None, parameters=None, data=None):
# post with mkey will return a 404 as the next level is not there yet
url = self.cmdb_url(path, name, vdom, mkey=mkey)
if not mkey:
mkey = self.get_mkey(path, name, vdom=vdom, data=data)
url = self.cmdb_url(path, name, mkey=mkey, vdom=vdom)
res = self._session.put(
url, params=parameters, data=json.dumps(data))
LOG.debug("in SET function after PUT")
r = self.formatresponse(res, vdom=vdom)
if r['http_status'] == 404 or r['http_status'] == 405:
LOG.warning(
"Try to put on %s failed doing a put to force parameters\
change consider delete if still fails ",
res.request.url)
#need to reset the url without mkey if doing a post
url = self.cmdb_url(path, name, mkey=None, vdom=vdom)
res = self._session.post(
url, params=parameters, data=json.dumps(data))
LOG.debug("in SET function after POST")
return self.formatresponse(res, vdom=vdom)
else:
return r
# send multiline string ''' get system status ''' using ssh
def ssh(self, cmds, host, user, password=None, private_key=None, ssh_port=22):
''' Send a multi line string via ssh to the fortigate '''
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if private_key is None:
client.connect(host, port=ssh_port, username=user, password=password,
allow_agent=False, timeout=10)
else:
k = paramiko.RSAKey.from_private_key_file(private_key)
client.connect(host, port=ssh_port, username=user, pkey=k,
allow_agent=False, timeout=10)
LOG.debug("ssh login to %s:%s ", host, ssh_port)
# commands is a multiline string using the ''' string ''' format
try:
stdin, stdout, stderr = client.exec_command(cmds)
except:
LOG.debug("exec_command failed")
raise subprocess.CalledProcessError(returncode=retcode, cmd=cmds,
output=output)
LOG.debug("ssh command in: %s out: %s err: %s ",
stdin, stdout, stderr)
retcode = stdout.channel.recv_exit_status()
LOG.debug("Paramiko return code : %s ", retcode)
client.close() # @TODO re-use connections
if retcode > 0:
output = stderr.read().strip()
raise subprocess.CalledProcessError(returncode=retcode, cmd=cmds,
output=output)
results = stdout.read()
LOG.debug("ssh cmd %s | out: %s | err: %s ", cmds, results, retcode)
# fortigate ssh send errors on stdout so checking that
if "Command fail. Return code" in str(results):
# TODO fill retcode with the output of the FGT
raise subprocess.CalledProcessError(returncode=retcode, cmd=cmds,
output=results)
return (''.join(str(results)), ''.join(str(stderr)))
def license(self):
resp = self.monitor('license', 'status')
if resp['status'] == 'success':
return resp
else:
# if vm license not valid we try to update and check again
url = self.mon_url('system', 'fortiguard', mkey='update')
postres = self._session.post(url)
LOG.debug("Return POST fortiguard %s:", postres)
postresp = json.loads(postres.content.decode('utf-8'))
if postresp['status'] == 'success':
time.sleep(17)
return self.monitor('license', 'status')
# Todo for license check and update
# GET /api/v2/monitor/license/status
# To update FortiGuard license status, you can use the following API
# POST api/v2/monitor/system/fortiguard/update
| 39.297297 | 82 | 0.588308 |
session.headers)
return url
def mon_url(self, path, name, vdom=None, mkey=None):
url_postfix = '/api/v2/monitor/' + path + '/' + name
if mkey:
url_postfix = url_postfix + '/' + str(mkey)
if vdom:
LOG.debug("vdom is: %s", vdom)
if vdom == "global":
url_postfix += '?global=1'
else:
url_postfix += '?vdom=' + vdom
url = self.url_prefix + url_postfix
return url
def monitor(self, path, name, vdom=None, mkey=None, parameters=None):
url = self.mon_url(path, name, vdom, mkey)
res = self._session.get(url, params=parameters)
LOG.debug("in MONITOR function")
return self.formatresponse(res, vdom=vdom)
def download(self, path, name, vdom=None, mkey=None, parameters=None):
url = self.mon_url(path, name)
res = self._session.get(url, params=parameters)
LOG.debug("in DOWNLOAD function")
return res
def upload(self, path, name, vdom=None, mkey=None,
parameters=None, data=None, files=None):
url = self.mon_url(path, name)
res = self._session.post(url, params=parameters,
data=data, files=files)
LOG.debug("in UPLOAD function")
return res
def get(self, path, name, vdom=None, mkey=None, parameters=None):
url = self.cmdb_url(path, name, vdom, mkey)
res = self._session.get(url, params=parameters)
LOG.debug("in GET function")
return self.formatresponse(res, vdom=vdom)
def schema(self, path, name, vdom=None):
if vdom is None:
url = self.cmdb_url(path, name, vdom) + "?action=schema"
else:
url = self.cmdb_url(path, name, vdom) + "&action=schema"
res = self._session.get(url)
self.logging(res)
if res.status_code is 200:
return json.loads(res.content.decode('utf-8'))['results']
else:
return json.loads(res.content.decode('utf-8'))
def get_name_path_dict(self, vdom=None):
url_postfix = '/api/v2/cmdb/'
if vdom is None:
url_postfix += '?vdom=' + vdom + "&action=schema"
else:
url_postfix += "?action=schema"
url = self.url_prefix + url_postfix
cmdbschema = self._session.get(url)
self.logging(cmdbschema)
j = json.loads(cmdbschema.content.decode('utf-8'))['results']
dict = []
for keys in j:
if "__tree__" not in keys['path']:
dict.append(keys['path'] + " " + keys['name'])
return dict
def post(self, path, name, vdom=None,
mkey=None, parameters=None, data=None):
if not mkey:
mkey = self.get_mkey(path, name, vdom=vdom, data=data)
url = self.cmdb_url(path, name, vdom, mkey=None)
res = self._session.post(
url, params=parameters, data=json.dumps(data))
LOG.debug("in POST function")
return self.formatresponse(res, vdom=vdom)
def put(self, path, name, vdom=None,
mkey=None, parameters=None, data=None):
if not mkey:
mkey = self.get_mkey(path, name, vdom=vdom, data=data)
url = self.cmdb_url(path, name, vdom, mkey)
res = self._session.put(url, params=parameters,
data=json.dumps(data))
LOG.debug("in PUT function")
return self.formatresponse(res, vdom=vdom)
def delete(self, path, name, vdom=None,
mkey=None, parameters=None, data=None):
if not mkey:
mkey = self.get_mkey(path, name, vdom=vdom, data=data)
url = self.cmdb_url(path, name, vdom, mkey)
res = self._session.delete(
url, params=parameters, data=json.dumps(data))
LOG.debug("in DELETE function")
return self.formatresponse(res, vdom=vdom)
def set(self, path, name, vdom=None,
mkey=None, parameters=None, data=None):
url = self.cmdb_url(path, name, vdom, mkey=mkey)
if not mkey:
mkey = self.get_mkey(path, name, vdom=vdom, data=data)
url = self.cmdb_url(path, name, mkey=mkey, vdom=vdom)
res = self._session.put(
url, params=parameters, data=json.dumps(data))
LOG.debug("in SET function after PUT")
r = self.formatresponse(res, vdom=vdom)
if r['http_status'] == 404 or r['http_status'] == 405:
LOG.warning(
"Try to put on %s failed doing a put to force parameters\
change consider delete if still fails ",
res.request.url)
url = self.cmdb_url(path, name, mkey=None, vdom=vdom)
res = self._session.post(
url, params=parameters, data=json.dumps(data))
LOG.debug("in SET function after POST")
return self.formatresponse(res, vdom=vdom)
else:
return r
def ssh(self, cmds, host, user, password=None, private_key=None, ssh_port=22):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if private_key is None:
client.connect(host, port=ssh_port, username=user, password=password,
allow_agent=False, timeout=10)
else:
k = paramiko.RSAKey.from_private_key_file(private_key)
client.connect(host, port=ssh_port, username=user, pkey=k,
allow_agent=False, timeout=10)
LOG.debug("ssh login to %s:%s ", host, ssh_port)
try:
stdin, stdout, stderr = client.exec_command(cmds)
except:
LOG.debug("exec_command failed")
raise subprocess.CalledProcessError(returncode=retcode, cmd=cmds,
output=output)
LOG.debug("ssh command in: %s out: %s err: %s ",
stdin, stdout, stderr)
retcode = stdout.channel.recv_exit_status()
LOG.debug("Paramiko return code : %s ", retcode)
client.close()
if retcode > 0:
output = stderr.read().strip()
raise subprocess.CalledProcessError(returncode=retcode, cmd=cmds,
output=output)
results = stdout.read()
LOG.debug("ssh cmd %s | out: %s | err: %s ", cmds, results, retcode)
if "Command fail. Return code" in str(results):
raise subprocess.CalledProcessError(returncode=retcode, cmd=cmds,
output=results)
return (''.join(str(results)), ''.join(str(stderr)))
def license(self):
resp = self.monitor('license', 'status')
if resp['status'] == 'success':
return resp
else:
url = self.mon_url('system', 'fortiguard', mkey='update')
postres = self._session.post(url)
LOG.debug("Return POST fortiguard %s:", postres)
postresp = json.loads(postres.content.decode('utf-8'))
if postresp['status'] == 'success':
time.sleep(17)
return self.monitor('license', 'status')
| true | true |
f72bf76df8d11eb6f121b20434afa79afc78b832 | 5,472 | py | Python | tests/deep_eq.py | textioHQ/PynamoDB | cc00ff616d1ff04793af2a43a68cef7611de4e85 | [
"MIT"
] | 1,586 | 2017-04-11T13:09:30.000Z | 2022-03-30T01:38:48.000Z | tests/deep_eq.py | textioHQ/PynamoDB | cc00ff616d1ff04793af2a43a68cef7611de4e85 | [
"MIT"
] | 606 | 2017-04-11T12:53:27.000Z | 2022-03-29T12:12:51.000Z | tests/deep_eq.py | textioHQ/textio-pynamodb | cc00ff616d1ff04793af2a43a68cef7611de4e85 | [
"MIT"
] | 366 | 2017-05-04T19:36:31.000Z | 2022-03-20T14:05:53.000Z | # Copyright (c) 2010-2013 Samuel Sutch [samuel.sutch@gmail.com]
#
# 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.
import datetime, time, functools, operator
default_fudge = datetime.timedelta(seconds=0, microseconds=0, days=0)
def deep_eq(_v1, _v2, datetime_fudge=default_fudge, _assert=False):
"""
Tests for deep equality between two python data structures recursing
into sub-structures if necessary. Works with all python types including
iterators and generators. This function was dreampt up to test API responses
but could be used for anything. Be careful. With deeply nested structures
you may blow the stack.
Options:
datetime_fudge => this is a datetime.timedelta object which, when
comparing dates, will accept values that differ
by the number of seconds specified
_assert => passing yes for this will raise an assertion error
when values do not match, instead of returning
false (very useful in combination with pdb)
Doctests included:
>>> x1, y1 = ({'a': 'b'}, {'a': 'b'})
>>> deep_eq(x1, y1)
True
>>> x2, y2 = ({'a': 'b'}, {'b': 'a'})
>>> deep_eq(x2, y2)
False
>>> x3, y3 = ({'a': {'b': 'c'}}, {'a': {'b': 'c'}})
>>> deep_eq(x3, y3)
True
>>> x4, y4 = ({'c': 't', 'a': {'b': 'c'}}, {'a': {'b': 'n'}, 'c': 't'})
>>> deep_eq(x4, y4)
False
>>> x5, y5 = ({'a': [1,2,3]}, {'a': [1,2,3]})
>>> deep_eq(x5, y5)
True
>>> x6, y6 = ({'a': [1,'b',8]}, {'a': [2,'b',8]})
>>> deep_eq(x6, y6)
False
>>> x7, y7 = ('a', 'a')
>>> deep_eq(x7, y7)
True
>>> x8, y8 = (['p','n',['asdf']], ['p','n',['asdf']])
>>> deep_eq(x8, y8)
True
>>> x9, y9 = (['p','n',['asdf',['omg']]], ['p', 'n', ['asdf',['nowai']]])
>>> deep_eq(x9, y9)
False
>>> x10, y10 = (1, 2)
>>> deep_eq(x10, y10)
False
>>> deep_eq((str(p) for p in xrange(10)), (str(p) for p in xrange(10)))
True
>>> str(deep_eq(range(4), range(4)))
'True'
>>> deep_eq(xrange(100), xrange(100))
True
>>> deep_eq(xrange(2), xrange(5))
False
>>> import datetime
>>> from datetime import datetime as dt
>>> d1, d2 = (dt.now(), dt.now() + datetime.timedelta(seconds=4))
>>> deep_eq(d1, d2)
False
>>> deep_eq(d1, d2, datetime_fudge=datetime.timedelta(seconds=5))
True
"""
_deep_eq = functools.partial(deep_eq, datetime_fudge=datetime_fudge,
_assert=_assert)
def _check_assert(R, a, b, reason=''):
if _assert and not R:
assert 0, "an assertion has failed in deep_eq ({}) {} != {}".format(
reason, str(a), str(b))
return R
def _deep_dict_eq(d1, d2):
k1, k2 = (sorted(d1.keys()), sorted(d2.keys()))
if k1 != k2: # keys should be exactly equal
return _check_assert(False, k1, k2, "keys")
return _check_assert(operator.eq(sum(_deep_eq(d1[k], d2[k])
for k in k1),
len(k1)), d1, d2, "dictionaries")
def _deep_iter_eq(l1, l2):
if len(l1) != len(l2):
return _check_assert(False, l1, l2, "lengths")
return _check_assert(operator.eq(sum(_deep_eq(v1, v2)
for v1, v2 in zip(l1, l2)),
len(l1)), l1, l2, "iterables")
def op(a, b):
_op = operator.eq
if type(a) == datetime.datetime and type(b) == datetime.datetime:
s = datetime_fudge.seconds
t1, t2 = (time.mktime(a.timetuple()), time.mktime(b.timetuple()))
l = t1 - t2
l = -l if l > 0 else l
return _check_assert((-s if s > 0 else s) <= l, a, b, "dates")
return _check_assert(_op(a, b), a, b, "values")
c1, c2 = (_v1, _v2)
# guard against strings because they are iterable and their
# elements yield iterables infinitely.
# I N C E P T I O N
if not isinstance(_v1, str):
if isinstance(_v1, dict):
op = _deep_dict_eq
else:
try:
c1, c2 = (list(iter(_v1)), list(iter(_v2)))
except TypeError:
c1, c2 = _v1, _v2
else:
op = _deep_iter_eq
return op(c1, c2)
| 38.535211 | 82 | 0.561586 |
import datetime, time, functools, operator
default_fudge = datetime.timedelta(seconds=0, microseconds=0, days=0)
def deep_eq(_v1, _v2, datetime_fudge=default_fudge, _assert=False):
_deep_eq = functools.partial(deep_eq, datetime_fudge=datetime_fudge,
_assert=_assert)
def _check_assert(R, a, b, reason=''):
if _assert and not R:
assert 0, "an assertion has failed in deep_eq ({}) {} != {}".format(
reason, str(a), str(b))
return R
def _deep_dict_eq(d1, d2):
k1, k2 = (sorted(d1.keys()), sorted(d2.keys()))
if k1 != k2:
return _check_assert(False, k1, k2, "keys")
return _check_assert(operator.eq(sum(_deep_eq(d1[k], d2[k])
for k in k1),
len(k1)), d1, d2, "dictionaries")
def _deep_iter_eq(l1, l2):
if len(l1) != len(l2):
return _check_assert(False, l1, l2, "lengths")
return _check_assert(operator.eq(sum(_deep_eq(v1, v2)
for v1, v2 in zip(l1, l2)),
len(l1)), l1, l2, "iterables")
def op(a, b):
_op = operator.eq
if type(a) == datetime.datetime and type(b) == datetime.datetime:
s = datetime_fudge.seconds
t1, t2 = (time.mktime(a.timetuple()), time.mktime(b.timetuple()))
l = t1 - t2
l = -l if l > 0 else l
return _check_assert((-s if s > 0 else s) <= l, a, b, "dates")
return _check_assert(_op(a, b), a, b, "values")
c1, c2 = (_v1, _v2)
if not isinstance(_v1, str):
if isinstance(_v1, dict):
op = _deep_dict_eq
else:
try:
c1, c2 = (list(iter(_v1)), list(iter(_v2)))
except TypeError:
c1, c2 = _v1, _v2
else:
op = _deep_iter_eq
return op(c1, c2)
| true | true |
f72bf78a0312644a15cd73be8689aef834f595d3 | 437 | py | Python | exe077 - COntando vogais em Tupla.py | carlosbandelli/Exercicios_em_Python | 2cd5bd837fdc51932f9605db32366ad0e3871d87 | [
"MIT"
] | null | null | null | exe077 - COntando vogais em Tupla.py | carlosbandelli/Exercicios_em_Python | 2cd5bd837fdc51932f9605db32366ad0e3871d87 | [
"MIT"
] | null | null | null | exe077 - COntando vogais em Tupla.py | carlosbandelli/Exercicios_em_Python | 2cd5bd837fdc51932f9605db32366ad0e3871d87 | [
"MIT"
] | null | null | null | palavras = ('aprender', 'programar', 'Linguagem', 'python',
'cruso', 'gratis', 'estudar', 'praticar',
'trabalhar', 'mercado', 'programador', 'futuro')
for p in palavras: # para cada palavra dentro do array de palavra
print(f'\nNa palavra {p.upper()} temos', end='')
for letra in p: # para cada letra de palvra tirado do array palavras
if letra.lower() in 'aeiou':
print(letra, end=' ') | 54.625 | 72 | 0.606407 | palavras = ('aprender', 'programar', 'Linguagem', 'python',
'cruso', 'gratis', 'estudar', 'praticar',
'trabalhar', 'mercado', 'programador', 'futuro')
for p in palavras:
print(f'\nNa palavra {p.upper()} temos', end='')
for letra in p:
if letra.lower() in 'aeiou':
print(letra, end=' ') | true | true |
f72bf78b887dc5d6cf67f9a36e0f156cb0c5c2ab | 4,851 | py | Python | profiles_api/views.py | rawaihtun/profiles-rest-api | 2a810cfcf41b3fbf336956a30805492b8249d36e | [
"MIT"
] | null | null | null | profiles_api/views.py | rawaihtun/profiles-rest-api | 2a810cfcf41b3fbf336956a30805492b8249d36e | [
"MIT"
] | 4 | 2021-03-19T12:01:37.000Z | 2022-02-10T09:30:39.000Z | profiles_api/views.py | rawaihtun/profiles-rest-api | 2a810cfcf41b3fbf336956a30805492b8249d36e | [
"MIT"
] | null | null | null | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework import filters
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
# from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework.permissions import IsAuthenticated
from profiles_api import serializers
from profiles_api import models
from profiles_api import permissions
class HelloApiView(APIView):
"""Test API View"""
serializer_class = serializers.HelloSerializer
def get(self, request, format=None):
"""Returns a list of APIView features"""
an_apiview = [
'Uses HTTP methods as functions (get, post, patch, put, delete)',
'Is similar to a traditional Django View',
'Gives you the most control over your logic',
'Is mapped manually to URLs',
]
return Response({'message': 'Hello!', 'an_apiview': an_apiview})
def post(self, request):
"""Create hello message with our name"""
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
name = serializer.validated_data.get('name')
message = f'Hello {name}'
return Response({'message': message})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk=None):
"""Handle updating an object"""
return Response({'method': 'PUT'})
def patch(self, request, pk=None):
"""Handle partial update of object"""
return Response({'method': 'PATCH'})
def delete(self, request, pk=None):
"""Delete an object"""
return Response({'method': 'DELETE'})
class HelloViewSet(viewsets.ViewSet):
"""Test API ViewSet"""
serializer_class = serializers.HelloSerializer
def list(self, request):
"""Return a hello message."""
a_viewset = [
'Uses actions (list, create, retrieve, update, partial_update)',
'Automatically maps to URLS using Routers',
'Provides more functionality with less code',
]
return Response({'message': 'Hello!', 'a_viewset': a_viewset})
# class HelloViewSet(viewsets.ViewSet):
# serializer_class = serializers.HelloSerializer
#
# def list(self, request):
# """ Return hello message viewset"""
# a_viewset = [
# 'This is return',
# 'This is return',
# 'This is return',
# 'This is return'
# ]
#
# return Response({'message':'Hello viewset return', 'a_viewset':a_viewset})
def create(self, request):
""" Create User"""
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
name=serializer.validated_data.get('name')
message = f'Hello {name}'
return Response({'Message':message})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
def retrieve(self, request, pk=None):
"""Handle getting an object by its ID"""
return Response({'http_method': 'GET'})
def update(self, request, pk=None):
"""Handle updating an object"""
return Response({'http_method': 'PUT'})
def partial_update(self, request, pk=None):
"""Handle updating part of an object"""
return Response({'http_method': 'PATCH'})
def destroy(self, request, pk=None):
"""Handle removing an object"""
return Response({'http_method': 'DELETE'})
class UserProfileViewSet(viewsets.ModelViewSet):
"""Handle creating, creating and updating profiles"""
serializer_class = serializers.UserProfileSerializer
queryset = models.UserProfile.objects.all()
authentication_classes = (TokenAuthentication,)
permission_classes = (permissions.UpdateOwnPermissions,)
filter_backends = (filters.SearchFilter,)
search_fields = ('name', 'email',)
class UserLoginApiView(ObtainAuthToken):
"""Handle creating user authentication tokens"""
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
class UserProfileFeedViewSet(viewsets.ModelViewSet):
"""Handle creating, reading and updating user profile"""
authentication_classes = (TokenAuthentication,)
serializer_class = serializers.ProfileFeedItemSerializer
queryset = models.ProfileFeedItem.objects.all()
permission_classes = (permissions.UpdateOwnStatus,IsAuthenticated)
def perform_create(self, serializer):
"""set the user profile to logged in user"""
serializer.save(user_profile=self.request.user)
| 32.777027 | 84 | 0.669553 | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework import filters
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
from rest_framework.permissions import IsAuthenticated
from profiles_api import serializers
from profiles_api import models
from profiles_api import permissions
class HelloApiView(APIView):
serializer_class = serializers.HelloSerializer
def get(self, request, format=None):
an_apiview = [
'Uses HTTP methods as functions (get, post, patch, put, delete)',
'Is similar to a traditional Django View',
'Gives you the most control over your logic',
'Is mapped manually to URLs',
]
return Response({'message': 'Hello!', 'an_apiview': an_apiview})
def post(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
name = serializer.validated_data.get('name')
message = f'Hello {name}'
return Response({'message': message})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk=None):
return Response({'method': 'PUT'})
def patch(self, request, pk=None):
return Response({'method': 'PATCH'})
def delete(self, request, pk=None):
return Response({'method': 'DELETE'})
class HelloViewSet(viewsets.ViewSet):
serializer_class = serializers.HelloSerializer
def list(self, request):
a_viewset = [
'Uses actions (list, create, retrieve, update, partial_update)',
'Automatically maps to URLS using Routers',
'Provides more functionality with less code',
]
return Response({'message': 'Hello!', 'a_viewset': a_viewset})
def create(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
name=serializer.validated_data.get('name')
message = f'Hello {name}'
return Response({'Message':message})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
def retrieve(self, request, pk=None):
return Response({'http_method': 'GET'})
def update(self, request, pk=None):
return Response({'http_method': 'PUT'})
def partial_update(self, request, pk=None):
return Response({'http_method': 'PATCH'})
def destroy(self, request, pk=None):
return Response({'http_method': 'DELETE'})
class UserProfileViewSet(viewsets.ModelViewSet):
serializer_class = serializers.UserProfileSerializer
queryset = models.UserProfile.objects.all()
authentication_classes = (TokenAuthentication,)
permission_classes = (permissions.UpdateOwnPermissions,)
filter_backends = (filters.SearchFilter,)
search_fields = ('name', 'email',)
class UserLoginApiView(ObtainAuthToken):
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
class UserProfileFeedViewSet(viewsets.ModelViewSet):
authentication_classes = (TokenAuthentication,)
serializer_class = serializers.ProfileFeedItemSerializer
queryset = models.ProfileFeedItem.objects.all()
permission_classes = (permissions.UpdateOwnStatus,IsAuthenticated)
def perform_create(self, serializer):
serializer.save(user_profile=self.request.user)
| true | true |
f72bf7f75d268ffc1761eda7cbca14afc9a54931 | 9,513 | py | Python | tests/test_v2.py | dajiaji/pyseto | 6e3f1259bd1a1671cccd75cb557bb63182f9e01a | [
"MIT"
] | 25 | 2021-09-06T08:53:45.000Z | 2022-02-19T20:17:23.000Z | tests/test_v2.py | dajiaji/pyseto | 6e3f1259bd1a1671cccd75cb557bb63182f9e01a | [
"MIT"
] | 124 | 2021-09-05T05:44:05.000Z | 2022-03-27T05:57:25.000Z | tests/test_v2.py | dajiaji/pyseto | 6e3f1259bd1a1671cccd75cb557bb63182f9e01a | [
"MIT"
] | 3 | 2021-09-11T02:37:09.000Z | 2022-01-06T10:49:14.000Z | from secrets import token_bytes
import pytest
import pyseto
from pyseto import DecryptError, EncryptError, Key, VerifyError
from pyseto.versions.v2 import V2Local, V2Public
from .utils import get_path, load_key
class TestV2Local:
"""
Tests for v2.local.
"""
@pytest.mark.parametrize(
"key, msg",
[
(b"", "key must be specified."),
(token_bytes(1), "key must be 32 bytes long."),
(token_bytes(8), "key must be 32 bytes long."),
(token_bytes(16), "key must be 32 bytes long."),
(token_bytes(31), "key must be 32 bytes long."),
(token_bytes(33), "key must be 32 bytes long."),
],
)
def test_v2_local_new_with_invalid_arg(self, key, msg):
with pytest.raises(ValueError) as err:
Key.new(2, "local", key)
pytest.fail("Key.new() should fail.")
assert msg in str(err.value)
@pytest.mark.parametrize(
"key",
[
None,
0,
token_bytes(65),
],
)
def test_v2_local__generate_hash_with_invalid_arg(self, key):
with pytest.raises(EncryptError) as err:
V2Local._generate_hash(key, b"Hello world!", 32)
pytest.fail("V2Local._generate_hash() should fail.")
assert "Failed to generate hash." in str(err.value)
@pytest.mark.parametrize(
"ptk",
[
None,
0,
],
)
def test_v2_local__encode_pie_with_invalid_ptk(self, ptk):
with pytest.raises(EncryptError) as err:
V2Local._encode_pie("v2.local-wrap.pie.", token_bytes(32), ptk)
pytest.fail("V2Local._encode_pie() should fail.")
assert "Failed to encrypt." in str(err.value)
def test_v2_local_decrypt_via_decode_with_wrong_key(self):
k1 = Key.new(2, "local", token_bytes(32))
k2 = Key.new(2, "local", token_bytes(32))
token = pyseto.encode(k1, b"Hello world!")
with pytest.raises(DecryptError) as err:
pyseto.decode(k2, token)
pytest.fail("pyseto.decode() should fail.")
assert "Failed to decrypt." in str(err.value)
def test_v2_local_encrypt_with_invalid_arg(self):
k = Key.new(2, "local", token_bytes(32))
with pytest.raises(EncryptError) as err:
k.encrypt(None)
pytest.fail("pyseto.encrypt() should fail.")
assert "Failed to generate internal nonce." in str(err.value)
@pytest.mark.parametrize(
"nonce",
[
token_bytes(1),
token_bytes(8),
token_bytes(23),
token_bytes(25),
token_bytes(32),
],
)
def test_v2_local_encrypt_via_encode_with_wrong_nonce(self, nonce):
k = Key.new(2, "local", token_bytes(32))
with pytest.raises(ValueError) as err:
pyseto.encode(k, b"Hello world!", nonce=nonce)
pytest.fail("pyseto.encode() should fail.")
assert "nonce must be 24 bytes long." in str(err.value)
@pytest.mark.parametrize(
"paserk, msg",
[
("xx.local.AAAAAAAAAAAAAAAA", "Invalid PASERK version: xx."),
("k3.local.AAAAAAAAAAAAAAAA", "Invalid PASERK version: k3."),
("k2.local.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK format."),
("k2.public.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK format."),
("k2.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK type: xxx."),
("k2.public.AAAAAAAAAAAAAAAA", "Invalid PASERK type: public."),
(
"k2.local-wrap.AAAAAAAAAAAAAAAA",
"local-wrap needs wrapping_key.",
),
(
"k2.secret-wrap.AAAAAAAAAAAAAAAA",
"Invalid PASERK type: secret-wrap.",
),
(
"k2.local-pw.AAAAAAAAAAAAAAAA",
"local-pw needs password.",
),
(
"k2.seal.AAAAAAAAAAAAAAAA",
"seal needs unsealing_key.",
),
],
)
def test_v2_local_from_paserk_with_invalid_args(self, paserk, msg):
with pytest.raises(ValueError) as err:
V2Local.from_paserk(paserk)
pytest.fail("Key.from_paserk should fail.")
assert msg in str(err.value)
@pytest.mark.parametrize(
"paserk, msg",
[
("xx.local-wrap.AAAAAAAAAAAAAAAA", "Invalid PASERK version: xx."),
("k2.local-wrap.AAAAAAAAAAAAAAAA", "Invalid PASERK format."),
("k2.local-wrap.xxx.AAAAAAAAAAAAAAAA", "Unknown wrapping algorithm: xxx."),
("k2.xxx.pie.AAAAAAAAAAAAAAAA", "Invalid PASERK type: xxx."),
],
)
def test_v2_local_from_paserk_with_wrapping_key_and_invalid_args(self, paserk, msg):
with pytest.raises(ValueError) as err:
V2Local.from_paserk(paserk, wrapping_key=token_bytes(32))
pytest.fail("Key.from_paserk should fail.")
assert msg in str(err.value)
@pytest.mark.parametrize(
"paserk, msg",
[
("k2.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK type: xxx."),
("k2.seal.AAAAAAAAAAAAAAAA", "Invalid or unsupported PEM format."),
],
)
def test_v2_local_from_paserk_with_unsealing_key_and_invalid_args(self, paserk, msg):
with pytest.raises(ValueError) as err:
V2Local.from_paserk(paserk, unsealing_key=token_bytes(32))
pytest.fail("Key.from_paserk should fail.")
assert msg in str(err.value)
def test_v2_local_to_paserk_with_invalid_sealing_key(self):
k = Key.new(2, "local", token_bytes(32))
with pytest.raises(ValueError) as err:
k.to_paserk(sealing_key=b"not-PEM-formatted-key")
pytest.fail("Key.from_paserk should fail.")
assert "Invalid or unsupported PEM format." in str(err.value)
def test_v2_local_from_paserk_with_wrong_unsealing_key(self):
k = Key.new(2, "local", token_bytes(32))
with open(get_path("keys/public_key_x25519.pem")) as key_file:
sealed_key = k.to_paserk(sealing_key=key_file.read())
with open(get_path("keys/private_key_x25519_2.pem")) as key_file:
unsealing_key = key_file.read()
with pytest.raises(DecryptError) as err:
Key.from_paserk(sealed_key, unsealing_key=unsealing_key)
pytest.fail("Key.from_paserk should fail.")
assert "Failed to unseal a key." in str(err.value)
class TestV2Public:
"""
Tests for v2.public.
"""
def test_v2_public_to_paserk_id(self):
sk = Key.new(2, "public", load_key("keys/private_key_ed25519.pem"))
pk = Key.new(2, "public", load_key("keys/public_key_ed25519.pem"))
assert sk.to_peer_paserk_id() == pk.to_paserk_id()
assert pk.to_peer_paserk_id() == ""
def test_v2_public_verify_via_encode_with_wrong_key(self):
sk = Key.new(2, "public", load_key("keys/private_key_ed25519.pem"))
pk = Key.new(2, "public", load_key("keys/public_key_ed25519_2.pem"))
token = pyseto.encode(sk, b"Hello world!")
with pytest.raises(VerifyError) as err:
pyseto.decode(pk, token)
pytest.fail("pyseto.decode() should fail.")
assert "Failed to verify." in str(err.value)
def test_v2_public_to_paserk_with_sealing_key(self):
k = Key.new(2, "public", load_key("keys/private_key_ed25519.pem"))
with pytest.raises(ValueError) as err:
k.to_paserk(sealing_key=b"xxx")
pytest.fail("pyseto.to_paserk() should fail.")
assert "Key sealing can only be used for local key." in str(err.value)
# def test_v2_public_from_paserk_with_wrong_unsealing_key(self):
# key = Key.new(2, "local", token_bytes(32))
# pk = Key.new(2, "public", load_key("keys/public_key_ed25519.pem"))
# sealing_key = pk.public_bytes(Encoding.Raw, PublicFormat.Raw)
# sealed = key.to_paserk(sealing_key=sealing_key)
# sk = Key.new(2, "public", load_key("keys/private_key_ed25519_2.pem"))
# with pytest.raises(ValueError) as err:
# Key.from_paserk(unsealing_key=unsealing_key)
# pytest.fail("pyseto.from_paserk() should fail.")
# assert "Failed to unseal a key." in str(err.value)
@pytest.mark.parametrize(
"paserk, msg",
[
("xx.public.AAAAAAAAAAAAAAAA", "Invalid PASERK version: xx."),
("k3.public.AAAAAAAAAAAAAAAA", "Invalid PASERK version: k3."),
("k2.public.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK format."),
("k2.local.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK format."),
("k2.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK type: xxx."),
("k2.local.AAAAAAAAAAAAAAAA", "Invalid PASERK type: local."),
(
"k2.local-wrap.AAAAAAAAAAAAAAAA",
"Invalid PASERK type: local-wrap.",
),
(
"k2.secret-wrap.AAAAAAAAAAAAAAAA",
"secret-wrap needs wrapping_key.",
),
(
"k2.secret-pw.AAAAAAAAAAAAAAAA",
"secret-pw needs password.",
),
],
)
def test_v2_public_from_paserk_with_invalid_args(self, paserk, msg):
with pytest.raises(ValueError) as err:
V2Public.from_paserk(paserk)
pytest.fail("Key.from_paserk should fail.")
assert msg in str(err.value)
| 38.358871 | 89 | 0.599495 | from secrets import token_bytes
import pytest
import pyseto
from pyseto import DecryptError, EncryptError, Key, VerifyError
from pyseto.versions.v2 import V2Local, V2Public
from .utils import get_path, load_key
class TestV2Local:
@pytest.mark.parametrize(
"key, msg",
[
(b"", "key must be specified."),
(token_bytes(1), "key must be 32 bytes long."),
(token_bytes(8), "key must be 32 bytes long."),
(token_bytes(16), "key must be 32 bytes long."),
(token_bytes(31), "key must be 32 bytes long."),
(token_bytes(33), "key must be 32 bytes long."),
],
)
def test_v2_local_new_with_invalid_arg(self, key, msg):
with pytest.raises(ValueError) as err:
Key.new(2, "local", key)
pytest.fail("Key.new() should fail.")
assert msg in str(err.value)
@pytest.mark.parametrize(
"key",
[
None,
0,
token_bytes(65),
],
)
def test_v2_local__generate_hash_with_invalid_arg(self, key):
with pytest.raises(EncryptError) as err:
V2Local._generate_hash(key, b"Hello world!", 32)
pytest.fail("V2Local._generate_hash() should fail.")
assert "Failed to generate hash." in str(err.value)
@pytest.mark.parametrize(
"ptk",
[
None,
0,
],
)
def test_v2_local__encode_pie_with_invalid_ptk(self, ptk):
with pytest.raises(EncryptError) as err:
V2Local._encode_pie("v2.local-wrap.pie.", token_bytes(32), ptk)
pytest.fail("V2Local._encode_pie() should fail.")
assert "Failed to encrypt." in str(err.value)
def test_v2_local_decrypt_via_decode_with_wrong_key(self):
k1 = Key.new(2, "local", token_bytes(32))
k2 = Key.new(2, "local", token_bytes(32))
token = pyseto.encode(k1, b"Hello world!")
with pytest.raises(DecryptError) as err:
pyseto.decode(k2, token)
pytest.fail("pyseto.decode() should fail.")
assert "Failed to decrypt." in str(err.value)
def test_v2_local_encrypt_with_invalid_arg(self):
k = Key.new(2, "local", token_bytes(32))
with pytest.raises(EncryptError) as err:
k.encrypt(None)
pytest.fail("pyseto.encrypt() should fail.")
assert "Failed to generate internal nonce." in str(err.value)
@pytest.mark.parametrize(
"nonce",
[
token_bytes(1),
token_bytes(8),
token_bytes(23),
token_bytes(25),
token_bytes(32),
],
)
def test_v2_local_encrypt_via_encode_with_wrong_nonce(self, nonce):
k = Key.new(2, "local", token_bytes(32))
with pytest.raises(ValueError) as err:
pyseto.encode(k, b"Hello world!", nonce=nonce)
pytest.fail("pyseto.encode() should fail.")
assert "nonce must be 24 bytes long." in str(err.value)
@pytest.mark.parametrize(
"paserk, msg",
[
("xx.local.AAAAAAAAAAAAAAAA", "Invalid PASERK version: xx."),
("k3.local.AAAAAAAAAAAAAAAA", "Invalid PASERK version: k3."),
("k2.local.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK format."),
("k2.public.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK format."),
("k2.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK type: xxx."),
("k2.public.AAAAAAAAAAAAAAAA", "Invalid PASERK type: public."),
(
"k2.local-wrap.AAAAAAAAAAAAAAAA",
"local-wrap needs wrapping_key.",
),
(
"k2.secret-wrap.AAAAAAAAAAAAAAAA",
"Invalid PASERK type: secret-wrap.",
),
(
"k2.local-pw.AAAAAAAAAAAAAAAA",
"local-pw needs password.",
),
(
"k2.seal.AAAAAAAAAAAAAAAA",
"seal needs unsealing_key.",
),
],
)
def test_v2_local_from_paserk_with_invalid_args(self, paserk, msg):
with pytest.raises(ValueError) as err:
V2Local.from_paserk(paserk)
pytest.fail("Key.from_paserk should fail.")
assert msg in str(err.value)
@pytest.mark.parametrize(
"paserk, msg",
[
("xx.local-wrap.AAAAAAAAAAAAAAAA", "Invalid PASERK version: xx."),
("k2.local-wrap.AAAAAAAAAAAAAAAA", "Invalid PASERK format."),
("k2.local-wrap.xxx.AAAAAAAAAAAAAAAA", "Unknown wrapping algorithm: xxx."),
("k2.xxx.pie.AAAAAAAAAAAAAAAA", "Invalid PASERK type: xxx."),
],
)
def test_v2_local_from_paserk_with_wrapping_key_and_invalid_args(self, paserk, msg):
with pytest.raises(ValueError) as err:
V2Local.from_paserk(paserk, wrapping_key=token_bytes(32))
pytest.fail("Key.from_paserk should fail.")
assert msg in str(err.value)
@pytest.mark.parametrize(
"paserk, msg",
[
("k2.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK type: xxx."),
("k2.seal.AAAAAAAAAAAAAAAA", "Invalid or unsupported PEM format."),
],
)
def test_v2_local_from_paserk_with_unsealing_key_and_invalid_args(self, paserk, msg):
with pytest.raises(ValueError) as err:
V2Local.from_paserk(paserk, unsealing_key=token_bytes(32))
pytest.fail("Key.from_paserk should fail.")
assert msg in str(err.value)
def test_v2_local_to_paserk_with_invalid_sealing_key(self):
k = Key.new(2, "local", token_bytes(32))
with pytest.raises(ValueError) as err:
k.to_paserk(sealing_key=b"not-PEM-formatted-key")
pytest.fail("Key.from_paserk should fail.")
assert "Invalid or unsupported PEM format." in str(err.value)
def test_v2_local_from_paserk_with_wrong_unsealing_key(self):
k = Key.new(2, "local", token_bytes(32))
with open(get_path("keys/public_key_x25519.pem")) as key_file:
sealed_key = k.to_paserk(sealing_key=key_file.read())
with open(get_path("keys/private_key_x25519_2.pem")) as key_file:
unsealing_key = key_file.read()
with pytest.raises(DecryptError) as err:
Key.from_paserk(sealed_key, unsealing_key=unsealing_key)
pytest.fail("Key.from_paserk should fail.")
assert "Failed to unseal a key." in str(err.value)
class TestV2Public:
def test_v2_public_to_paserk_id(self):
sk = Key.new(2, "public", load_key("keys/private_key_ed25519.pem"))
pk = Key.new(2, "public", load_key("keys/public_key_ed25519.pem"))
assert sk.to_peer_paserk_id() == pk.to_paserk_id()
assert pk.to_peer_paserk_id() == ""
def test_v2_public_verify_via_encode_with_wrong_key(self):
sk = Key.new(2, "public", load_key("keys/private_key_ed25519.pem"))
pk = Key.new(2, "public", load_key("keys/public_key_ed25519_2.pem"))
token = pyseto.encode(sk, b"Hello world!")
with pytest.raises(VerifyError) as err:
pyseto.decode(pk, token)
pytest.fail("pyseto.decode() should fail.")
assert "Failed to verify." in str(err.value)
def test_v2_public_to_paserk_with_sealing_key(self):
k = Key.new(2, "public", load_key("keys/private_key_ed25519.pem"))
with pytest.raises(ValueError) as err:
k.to_paserk(sealing_key=b"xxx")
pytest.fail("pyseto.to_paserk() should fail.")
assert "Key sealing can only be used for local key." in str(err.value)
@pytest.mark.parametrize(
"paserk, msg",
[
("xx.public.AAAAAAAAAAAAAAAA", "Invalid PASERK version: xx."),
("k3.public.AAAAAAAAAAAAAAAA", "Invalid PASERK version: k3."),
("k2.public.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK format."),
("k2.local.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK format."),
("k2.xxx.AAAAAAAAAAAAAAAA", "Invalid PASERK type: xxx."),
("k2.local.AAAAAAAAAAAAAAAA", "Invalid PASERK type: local."),
(
"k2.local-wrap.AAAAAAAAAAAAAAAA",
"Invalid PASERK type: local-wrap.",
),
(
"k2.secret-wrap.AAAAAAAAAAAAAAAA",
"secret-wrap needs wrapping_key.",
),
(
"k2.secret-pw.AAAAAAAAAAAAAAAA",
"secret-pw needs password.",
),
],
)
def test_v2_public_from_paserk_with_invalid_args(self, paserk, msg):
with pytest.raises(ValueError) as err:
V2Public.from_paserk(paserk)
pytest.fail("Key.from_paserk should fail.")
assert msg in str(err.value)
| true | true |
f72bfa6d085487f6f133c3d61b0833f55d54597a | 136 | py | Python | oandapy/entities/positions.py | gustavooferreira/oandaApi | 3c22c088e090e726cccebd201efb4254503246a0 | [
"MIT"
] | 4 | 2016-07-17T15:39:50.000Z | 2016-10-06T23:41:28.000Z | oandapy/entities/positions.py | gustavooferreira/oandaApi | 3c22c088e090e726cccebd201efb4254503246a0 | [
"MIT"
] | 1 | 2018-12-09T21:20:57.000Z | 2018-12-09T21:20:57.000Z | oandapy/entities/positions.py | gustavooferreira/oandaApi | 3c22c088e090e726cccebd201efb4254503246a0 | [
"MIT"
] | 1 | 2018-12-06T18:39:36.000Z | 2018-12-06T18:39:36.000Z | # -*- coding: utf-8 -*-
# vim:fenc=utf-8
"""
Entities for Positions
"""
def main():
pass
if __name__ == '__main__':
main()
| 9.066667 | 26 | 0.544118 |
def main():
pass
if __name__ == '__main__':
main()
| true | true |
f72bfdbd824f7c5caeb25c8512edc95565455d2e | 13,091 | py | Python | naucse/views.py | befeleme/naucse.python.cz | dee2c8cce8db90108b01b40c0981053943352d11 | [
"MIT"
] | 4 | 2019-02-14T08:02:41.000Z | 2020-10-20T10:35:55.000Z | naucse/views.py | befeleme/naucse.python.cz | dee2c8cce8db90108b01b40c0981053943352d11 | [
"MIT"
] | 71 | 2018-08-26T22:31:39.000Z | 2022-01-20T10:29:23.000Z | naucse/views.py | befeleme/naucse.python.cz | dee2c8cce8db90108b01b40c0981053943352d11 | [
"MIT"
] | 40 | 2018-08-22T14:44:59.000Z | 2021-09-20T16:11:27.000Z | import datetime
from pathlib import Path
import functools
import calendar
import os
from flask import Flask, render_template, jsonify, url_for, Response, abort, g, redirect
from flask import send_from_directory
import ics
from arca import Arca
from naucse import models
from naucse.urlconverters import register_url_converters
from naucse.templates import setup_jinja_env
app = Flask('naucse')
app.config['JSON_AS_ASCII'] = False
@app.before_request
def _get_model():
"""Set `g.model` to the root of the naucse model
A single model is used (and stored in app config).
In debug mode (elsa serve), the model is re-initialized for each request,
so changes are picked up.
In non-debug mode (elsa freeze), the model is initialized once, and
frozen (so all course data is requested and rendered upfront).
"""
freezing = os.environ.get('NAUCSE_FREEZE', not app.config['DEBUG'])
initialize = True
try:
g.model = app.config['NAUCSE_MODEL']
except KeyError:
g.model = init_model()
app.config['NAUCSE_MODEL'] = g.model
else:
if freezing:
# Model already initialized; don't look for changes
return
# (Re-)initialize model
g.model.load_licenses(Path(app.root_path).parent / 'licenses')
g.model.load_local_courses(Path(app.root_path).parent)
if freezing:
g.model.freeze()
def init_model():
trusted = os.environ.get('NAUCSE_TRUSTED_REPOS', None)
if trusted is None:
trusted_repo_patterns = ()
else:
trusted_repo_patterns = tuple(
line for line in trusted.split() if line
)
return models.Root(
url_factories={
'api': {
models.Root: lambda **kw: url_for('api', **kw),
models.Course: lambda **kw: url_for('course_api', **kw),
models.RunYear: lambda **kw: url_for('run_year_api', **kw),
},
'web': {
models.Lesson: lambda **kw: url_for('page',
page_slug='index', **kw),
models.Page: lambda **kw: url_for('page', **kw),
models.Solution: lambda **kw: url_for('solution', **kw),
models.Course: lambda **kw: url_for('course', **kw),
models.Session: lambda **kw: url_for('session', **kw),
models.SessionPage: lambda **kw: url_for(
'session', **kw),
models.StaticFile: lambda **kw: url_for('page_static', **kw),
models.Root: lambda **kw: url_for('index', **kw)
},
},
schema_url_factory=lambda m, is_input, **kw: url_for(
'schema', model_slug=m.model_slug,
is_input=is_input, **kw),
arca=Arca(settings={
"ARCA_BACKEND": "arca.backend.CurrentEnvironmentBackend",
"ARCA_BACKEND_CURRENT_ENVIRONMENT_REQUIREMENTS": "requirements.txt",
"ARCA_BACKEND_VERBOSITY": 2,
"ARCA_BACKEND_KEEP_CONTAINER_RUNNING": True,
"ARCA_BACKEND_USE_REGISTRY_NAME": "docker.io/naucse/naucse.python.cz",
"ARCA_SINGLE_PULL": True,
"ARCA_IGNORE_CACHE_ERRORS": True,
"ARCA_CACHE_BACKEND": "dogpile.cache.dbm",
"ARCA_CACHE_BACKEND_ARGUMENTS": {
"filename": ".arca/cache/naucse.dbm"
},
"ARCA_BASE_DIR": str(Path('.arca').resolve()),
}),
trusted_repo_patterns=trusted_repo_patterns,
)
register_url_converters(app)
setup_jinja_env(app.jinja_env)
@app.route('/')
def index():
return render_template("index.html", edit_info=g.model.edit_info)
@app.route('/courses/')
def courses():
return render_template(
"course_list.html",
featured_courses=g.model.featured_courses,
edit_info=g.model.course_edit_info,
)
@app.route('/runs/')
@app.route('/<int:year>/')
@app.route('/runs/<any(all):all>/')
def runs(year=None, all=None):
# XXX: Simplify?
today = datetime.date.today()
# List of years to show in the pagination
# If the current year is not there (no runs that start in the current year
# yet), add it manually
all_years = sorted(g.model.explicit_run_years)
if today.year not in all_years:
all_years.append(today.year)
first_year, last_year = min(all_years), max(all_years)
if year is not None:
if year > last_year:
# Instead of showing a future year, redirect to the 'Current' page
return redirect(url_for('runs'))
if year not in all_years:
# Otherwise, if there are no runs in requested year, return 404.
abort(404)
if all is not None:
run_data = {}
courses = g.model.courses
for slug, course in g.model.courses.items():
if course.start_date:
run_data.setdefault(course.start_date.year, {})[slug] = course
paginate_prev = {'year': first_year}
paginate_next = {'all': 'all'}
elif year is None:
# Show runs that are either ongoing or ended in the last 3 months
runs = {**g.model.run_years.get(today.year, {}),
**g.model.run_years.get(today.year - 1, {})}
ongoing = {slug: run for slug, run in runs.items()
if run.end_date >= today}
cutoff = today - datetime.timedelta(days=3*31)
recent = {slug: run for slug, run in runs.items()
if today > run.end_date > cutoff}
run_data = {"ongoing": ongoing, "recent": recent}
paginate_prev = {'year': None}
paginate_next = {'year': last_year}
else:
run_data = {year: g.model.run_years.get(year, {})}
past_years = [y for y in all_years if y < year]
if past_years:
paginate_next = {'year': max(past_years)}
else:
paginate_next = {'all': 'all'}
future_years = [y for y in all_years if y > year]
if future_years:
paginate_prev = {'year': min(future_years)}
else:
paginate_prev = {'year': None}
return render_template(
"run_list.html",
run_data=run_data,
today=datetime.date.today(),
year=year,
all=all,
all_years=all_years,
paginate_next=paginate_next,
paginate_prev=paginate_prev,
edit_info=g.model.runs_edit_info,
)
@app.route('/<course:course_slug>/')
def course(course_slug, year=None):
try:
course = g.model.courses[course_slug]
except KeyError:
print(g.model.courses)
abort(404)
recent_runs = course.get_recent_derived_runs()
return render_template(
"course.html",
course=course,
recent_runs=recent_runs,
edit_info=course.edit_info,
)
@app.route('/<course:course_slug>/sessions/<session_slug>/',
defaults={'page_slug': 'front'})
@app.route('/<course:course_slug>/sessions/<session_slug>/<page_slug>/')
def session(course_slug, session_slug, page_slug):
try:
course = g.model.courses[course_slug]
session = course.sessions[session_slug]
page = session.pages[page_slug]
except KeyError:
abort(404)
template = {
'front': 'coverpage.html',
'back': 'backpage.html',
}[page.slug]
materials_by_type = {}
for material in session.materials:
materials_by_type.setdefault(material.type, []).append(material)
return render_template(
template,
session=session,
course=session.course,
edit_info=session.edit_info,
materials_by_type=materials_by_type,
page=page,
)
def _get_canonicality_info(lesson):
"""Get canonical URL -- i.e., a lesson from 'lessons' with the same slug"""
# XXX: This could be made much more fancy
lessons_course = g.model.get_course('lessons')
is_canonical_lesson = (lessons_course == lesson.course)
if is_canonical_lesson:
canonical_url = None
else:
if lessons_course._has_lesson(lesson.slug):
canonical = lessons_course.lessons[lesson.slug]
canonical_url = canonical.get_url(external=True)
else:
canonical_url = None
return is_canonical_lesson, canonical_url
@app.route('/<course:course_slug>/<lesson:lesson_slug>/',
defaults={'page_slug': 'index'})
@app.route('/<course:course_slug>/<lesson:lesson_slug>/<page_slug>/')
def page(course_slug, lesson_slug, page_slug='index'):
try:
course = g.model.courses[course_slug]
lesson = course.lessons[lesson_slug]
page = lesson.pages[page_slug]
except KeyError:
raise abort(404)
is_canonical_lesson, canonical_url = _get_canonicality_info(lesson)
return render_template(
"lesson.html",
page=page,
content=page.content,
course=course,
canonical_url=canonical_url,
is_canonical_lesson=is_canonical_lesson,
page_attribution=page.attribution,
edit_info=page.edit_info,
)
@app.route('/<course:course_slug>/<lesson:lesson_slug>/<page_slug>'
+ '/solutions/<int:solution_index>/')
def solution(course_slug, lesson_slug, page_slug, solution_index):
try:
course = g.model.courses[course_slug]
lesson = course.lessons[lesson_slug]
page = lesson.pages[page_slug]
solution = page.solutions[solution_index]
except KeyError:
raise abort(404)
is_canonical_lesson, canonical_url = _get_canonicality_info(lesson)
return render_template(
"lesson.html",
page=page,
content=solution.content,
course=course,
canonical_url=canonical_url,
is_canonical_lesson=is_canonical_lesson,
page_attribution=page.attribution,
edit_info=page.edit_info,
solution=solution,
)
@app.route('/<course:course_slug>/<lesson:lesson_slug>/static/<path:filename>')
def page_static(course_slug, lesson_slug, filename):
try:
course = g.model.courses[course_slug]
lesson = course.lessons[lesson_slug]
static = lesson.static_files[filename]
except KeyError:
raise abort(404)
print('sending', static.base_path, static.filename)
return send_from_directory(static.base_path, static.path)
def list_months(start_date, end_date):
"""Return a span of months as a list of (year, month) tuples
The months of start_date and end_date are both included.
"""
months = []
year = start_date.year
month = start_date.month
while (year, month) <= (end_date.year, end_date.month):
months.append((year, month))
month += 1
if month > 12:
month = 1
year += 1
return months
@app.route('/<course:course_slug>/calendar/')
def course_calendar(course_slug):
try:
course = g.model.courses[course_slug]
except KeyError:
abort(404)
if not course.start_date:
abort(404)
sessions_by_date = {
s.date: s for s in course.sessions.values()
if hasattr(s, 'date')
}
return render_template(
'course_calendar.html',
course=course,
sessions_by_date=sessions_by_date,
months=list_months(course.start_date, course.end_date),
calendar=calendar.Calendar(),
edit_info=course.edit_info,
)
@app.route('/<course:course_slug>/calendar.ics')
def course_calendar_ics(course_slug):
try:
course = g.model.courses[course_slug]
except KeyError:
abort(404)
if not course.start_date:
abort(404)
events = []
for session in course.sessions.values():
time = getattr(session, 'time', None)
if time is None:
# Sessions without times don't show up in the calendar
continue
created = os.environ.get('NAUCSE_CALENDAR_DTSTAMP', None)
cal_event = ics.Event(
name=session.title,
begin=time['start'],
end=time['end'],
uid=session.get_url(external=True),
created=created,
)
events.append(cal_event)
cal = ics.Calendar(events=events)
return Response(str(cal), mimetype="text/calendar")
@app.route('/v0/schema/<is_input:is_input>.json', defaults={'model_slug': 'root'})
@app.route('/v0/schema/<is_input:is_input>/<model_slug>.json')
def schema(model_slug, is_input):
try:
cls = models.models[model_slug]
except KeyError:
abort(404)
return jsonify(models.get_schema(cls, is_input=is_input))
@app.route('/v0/naucse.json')
def api():
return jsonify(models.dump(g.model))
@app.route('/v0/years/<int:year>.json')
def run_year_api(year):
try:
run_year = g.model.run_years[year]
except KeyError:
abort(404)
return jsonify(models.dump(run_year))
@app.route('/v0/<course:course_slug>.json')
def course_api(course_slug):
try:
course = g.model.courses[course_slug]
except KeyError:
abort(404)
return jsonify(models.dump(course))
| 30.730047 | 88 | 0.625544 | import datetime
from pathlib import Path
import functools
import calendar
import os
from flask import Flask, render_template, jsonify, url_for, Response, abort, g, redirect
from flask import send_from_directory
import ics
from arca import Arca
from naucse import models
from naucse.urlconverters import register_url_converters
from naucse.templates import setup_jinja_env
app = Flask('naucse')
app.config['JSON_AS_ASCII'] = False
@app.before_request
def _get_model():
freezing = os.environ.get('NAUCSE_FREEZE', not app.config['DEBUG'])
initialize = True
try:
g.model = app.config['NAUCSE_MODEL']
except KeyError:
g.model = init_model()
app.config['NAUCSE_MODEL'] = g.model
else:
if freezing:
return
# (Re-)initialize model
g.model.load_licenses(Path(app.root_path).parent / 'licenses')
g.model.load_local_courses(Path(app.root_path).parent)
if freezing:
g.model.freeze()
def init_model():
trusted = os.environ.get('NAUCSE_TRUSTED_REPOS', None)
if trusted is None:
trusted_repo_patterns = ()
else:
trusted_repo_patterns = tuple(
line for line in trusted.split() if line
)
return models.Root(
url_factories={
'api': {
models.Root: lambda **kw: url_for('api', **kw),
models.Course: lambda **kw: url_for('course_api', **kw),
models.RunYear: lambda **kw: url_for('run_year_api', **kw),
},
'web': {
models.Lesson: lambda **kw: url_for('page',
page_slug='index', **kw),
models.Page: lambda **kw: url_for('page', **kw),
models.Solution: lambda **kw: url_for('solution', **kw),
models.Course: lambda **kw: url_for('course', **kw),
models.Session: lambda **kw: url_for('session', **kw),
models.SessionPage: lambda **kw: url_for(
'session', **kw),
models.StaticFile: lambda **kw: url_for('page_static', **kw),
models.Root: lambda **kw: url_for('index', **kw)
},
},
schema_url_factory=lambda m, is_input, **kw: url_for(
'schema', model_slug=m.model_slug,
is_input=is_input, **kw),
arca=Arca(settings={
"ARCA_BACKEND": "arca.backend.CurrentEnvironmentBackend",
"ARCA_BACKEND_CURRENT_ENVIRONMENT_REQUIREMENTS": "requirements.txt",
"ARCA_BACKEND_VERBOSITY": 2,
"ARCA_BACKEND_KEEP_CONTAINER_RUNNING": True,
"ARCA_BACKEND_USE_REGISTRY_NAME": "docker.io/naucse/naucse.python.cz",
"ARCA_SINGLE_PULL": True,
"ARCA_IGNORE_CACHE_ERRORS": True,
"ARCA_CACHE_BACKEND": "dogpile.cache.dbm",
"ARCA_CACHE_BACKEND_ARGUMENTS": {
"filename": ".arca/cache/naucse.dbm"
},
"ARCA_BASE_DIR": str(Path('.arca').resolve()),
}),
trusted_repo_patterns=trusted_repo_patterns,
)
register_url_converters(app)
setup_jinja_env(app.jinja_env)
@app.route('/')
def index():
return render_template("index.html", edit_info=g.model.edit_info)
@app.route('/courses/')
def courses():
return render_template(
"course_list.html",
featured_courses=g.model.featured_courses,
edit_info=g.model.course_edit_info,
)
@app.route('/runs/')
@app.route('/<int:year>/')
@app.route('/runs/<any(all):all>/')
def runs(year=None, all=None):
# XXX: Simplify?
today = datetime.date.today()
# List of years to show in the pagination
# If the current year is not there (no runs that start in the current year
# yet), add it manually
all_years = sorted(g.model.explicit_run_years)
if today.year not in all_years:
all_years.append(today.year)
first_year, last_year = min(all_years), max(all_years)
if year is not None:
if year > last_year:
# Instead of showing a future year, redirect to the 'Current' page
return redirect(url_for('runs'))
if year not in all_years:
# Otherwise, if there are no runs in requested year, return 404.
abort(404)
if all is not None:
run_data = {}
courses = g.model.courses
for slug, course in g.model.courses.items():
if course.start_date:
run_data.setdefault(course.start_date.year, {})[slug] = course
paginate_prev = {'year': first_year}
paginate_next = {'all': 'all'}
elif year is None:
# Show runs that are either ongoing or ended in the last 3 months
runs = {**g.model.run_years.get(today.year, {}),
**g.model.run_years.get(today.year - 1, {})}
ongoing = {slug: run for slug, run in runs.items()
if run.end_date >= today}
cutoff = today - datetime.timedelta(days=3*31)
recent = {slug: run for slug, run in runs.items()
if today > run.end_date > cutoff}
run_data = {"ongoing": ongoing, "recent": recent}
paginate_prev = {'year': None}
paginate_next = {'year': last_year}
else:
run_data = {year: g.model.run_years.get(year, {})}
past_years = [y for y in all_years if y < year]
if past_years:
paginate_next = {'year': max(past_years)}
else:
paginate_next = {'all': 'all'}
future_years = [y for y in all_years if y > year]
if future_years:
paginate_prev = {'year': min(future_years)}
else:
paginate_prev = {'year': None}
return render_template(
"run_list.html",
run_data=run_data,
today=datetime.date.today(),
year=year,
all=all,
all_years=all_years,
paginate_next=paginate_next,
paginate_prev=paginate_prev,
edit_info=g.model.runs_edit_info,
)
@app.route('/<course:course_slug>/')
def course(course_slug, year=None):
try:
course = g.model.courses[course_slug]
except KeyError:
print(g.model.courses)
abort(404)
recent_runs = course.get_recent_derived_runs()
return render_template(
"course.html",
course=course,
recent_runs=recent_runs,
edit_info=course.edit_info,
)
@app.route('/<course:course_slug>/sessions/<session_slug>/',
defaults={'page_slug': 'front'})
@app.route('/<course:course_slug>/sessions/<session_slug>/<page_slug>/')
def session(course_slug, session_slug, page_slug):
try:
course = g.model.courses[course_slug]
session = course.sessions[session_slug]
page = session.pages[page_slug]
except KeyError:
abort(404)
template = {
'front': 'coverpage.html',
'back': 'backpage.html',
}[page.slug]
materials_by_type = {}
for material in session.materials:
materials_by_type.setdefault(material.type, []).append(material)
return render_template(
template,
session=session,
course=session.course,
edit_info=session.edit_info,
materials_by_type=materials_by_type,
page=page,
)
def _get_canonicality_info(lesson):
# XXX: This could be made much more fancy
lessons_course = g.model.get_course('lessons')
is_canonical_lesson = (lessons_course == lesson.course)
if is_canonical_lesson:
canonical_url = None
else:
if lessons_course._has_lesson(lesson.slug):
canonical = lessons_course.lessons[lesson.slug]
canonical_url = canonical.get_url(external=True)
else:
canonical_url = None
return is_canonical_lesson, canonical_url
@app.route('/<course:course_slug>/<lesson:lesson_slug>/',
defaults={'page_slug': 'index'})
@app.route('/<course:course_slug>/<lesson:lesson_slug>/<page_slug>/')
def page(course_slug, lesson_slug, page_slug='index'):
try:
course = g.model.courses[course_slug]
lesson = course.lessons[lesson_slug]
page = lesson.pages[page_slug]
except KeyError:
raise abort(404)
is_canonical_lesson, canonical_url = _get_canonicality_info(lesson)
return render_template(
"lesson.html",
page=page,
content=page.content,
course=course,
canonical_url=canonical_url,
is_canonical_lesson=is_canonical_lesson,
page_attribution=page.attribution,
edit_info=page.edit_info,
)
@app.route('/<course:course_slug>/<lesson:lesson_slug>/<page_slug>'
+ '/solutions/<int:solution_index>/')
def solution(course_slug, lesson_slug, page_slug, solution_index):
try:
course = g.model.courses[course_slug]
lesson = course.lessons[lesson_slug]
page = lesson.pages[page_slug]
solution = page.solutions[solution_index]
except KeyError:
raise abort(404)
is_canonical_lesson, canonical_url = _get_canonicality_info(lesson)
return render_template(
"lesson.html",
page=page,
content=solution.content,
course=course,
canonical_url=canonical_url,
is_canonical_lesson=is_canonical_lesson,
page_attribution=page.attribution,
edit_info=page.edit_info,
solution=solution,
)
@app.route('/<course:course_slug>/<lesson:lesson_slug>/static/<path:filename>')
def page_static(course_slug, lesson_slug, filename):
try:
course = g.model.courses[course_slug]
lesson = course.lessons[lesson_slug]
static = lesson.static_files[filename]
except KeyError:
raise abort(404)
print('sending', static.base_path, static.filename)
return send_from_directory(static.base_path, static.path)
def list_months(start_date, end_date):
months = []
year = start_date.year
month = start_date.month
while (year, month) <= (end_date.year, end_date.month):
months.append((year, month))
month += 1
if month > 12:
month = 1
year += 1
return months
@app.route('/<course:course_slug>/calendar/')
def course_calendar(course_slug):
try:
course = g.model.courses[course_slug]
except KeyError:
abort(404)
if not course.start_date:
abort(404)
sessions_by_date = {
s.date: s for s in course.sessions.values()
if hasattr(s, 'date')
}
return render_template(
'course_calendar.html',
course=course,
sessions_by_date=sessions_by_date,
months=list_months(course.start_date, course.end_date),
calendar=calendar.Calendar(),
edit_info=course.edit_info,
)
@app.route('/<course:course_slug>/calendar.ics')
def course_calendar_ics(course_slug):
try:
course = g.model.courses[course_slug]
except KeyError:
abort(404)
if not course.start_date:
abort(404)
events = []
for session in course.sessions.values():
time = getattr(session, 'time', None)
if time is None:
# Sessions without times don't show up in the calendar
continue
created = os.environ.get('NAUCSE_CALENDAR_DTSTAMP', None)
cal_event = ics.Event(
name=session.title,
begin=time['start'],
end=time['end'],
uid=session.get_url(external=True),
created=created,
)
events.append(cal_event)
cal = ics.Calendar(events=events)
return Response(str(cal), mimetype="text/calendar")
@app.route('/v0/schema/<is_input:is_input>.json', defaults={'model_slug': 'root'})
@app.route('/v0/schema/<is_input:is_input>/<model_slug>.json')
def schema(model_slug, is_input):
try:
cls = models.models[model_slug]
except KeyError:
abort(404)
return jsonify(models.get_schema(cls, is_input=is_input))
@app.route('/v0/naucse.json')
def api():
return jsonify(models.dump(g.model))
@app.route('/v0/years/<int:year>.json')
def run_year_api(year):
try:
run_year = g.model.run_years[year]
except KeyError:
abort(404)
return jsonify(models.dump(run_year))
@app.route('/v0/<course:course_slug>.json')
def course_api(course_slug):
try:
course = g.model.courses[course_slug]
except KeyError:
abort(404)
return jsonify(models.dump(course))
| true | true |
f72bfe29fee50157b229530a1755cc94f9b37546 | 23,048 | py | Python | lib/keystore.py | GetAywa/electrum-aywa | 07a548bd14cdf563da49c1f1e52644b833ca972e | [
"MIT"
] | null | null | null | lib/keystore.py | GetAywa/electrum-aywa | 07a548bd14cdf563da49c1f1e52644b833ca972e | [
"MIT"
] | null | null | null | lib/keystore.py | GetAywa/electrum-aywa | 07a548bd14cdf563da49c1f1e52644b833ca972e | [
"MIT"
] | null | null | null | #!/usr/bin/env python2
# -*- mode: python -*-
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2016 The Electrum developers
#
# 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 unicodedata import normalize
from . import bitcoin
from .bitcoin import *
from .util import PrintError, InvalidPassword, hfu
from .mnemonic import Mnemonic, load_wordlist
from .plugins import run_hook
class KeyStore(PrintError):
def has_seed(self):
return False
def is_watching_only(self):
return False
def can_import(self):
return False
def get_tx_derivations(self, tx):
keypairs = {}
for txin in tx.inputs():
num_sig = txin.get('num_sig')
if num_sig is None:
continue
x_signatures = txin['signatures']
signatures = [sig for sig in x_signatures if sig]
if len(signatures) == num_sig:
# input is complete
continue
for k, x_pubkey in enumerate(txin['x_pubkeys']):
if x_signatures[k] is not None:
# this pubkey already signed
continue
derivation = self.get_pubkey_derivation(x_pubkey)
if not derivation:
continue
keypairs[x_pubkey] = derivation
return keypairs
def can_sign(self, tx):
if self.is_watching_only():
return False
return bool(self.get_tx_derivations(tx))
class Software_KeyStore(KeyStore):
def __init__(self):
KeyStore.__init__(self)
def may_have_password(self):
return not self.is_watching_only()
def sign_message(self, sequence, message, password):
privkey, compressed = self.get_private_key(sequence, password)
key = regenerate_key(privkey)
return key.sign_message(message, compressed)
def decrypt_message(self, sequence, message, password):
privkey, compressed = self.get_private_key(sequence, password)
ec = regenerate_key(privkey)
decrypted = ec.decrypt_message(message)
return decrypted
def sign_transaction(self, tx, password):
if self.is_watching_only():
return
# Raise if password is not correct.
self.check_password(password)
# Add private keys
keypairs = self.get_tx_derivations(tx)
for k, v in keypairs.items():
keypairs[k] = self.get_private_key(v, password)
# Sign
if keypairs:
tx.sign(keypairs)
class Imported_KeyStore(Software_KeyStore):
# keystore for imported private keys
def __init__(self, d):
Software_KeyStore.__init__(self)
self.keypairs = d.get('keypairs', {})
def is_deterministic(self):
return False
def can_change_password(self):
return True
def get_master_public_key(self):
return None
def dump(self):
return {
'type': 'imported',
'keypairs': self.keypairs,
}
def can_import(self):
return True
def check_password(self, password):
pubkey = list(self.keypairs.keys())[0]
self.get_private_key(pubkey, password)
def import_privkey(self, sec, password):
txin_type, privkey, compressed = deserialize_privkey(sec)
pubkey = public_key_from_private_key(privkey, compressed)
self.keypairs[pubkey] = pw_encode(sec, password)
return txin_type, pubkey
def delete_imported_key(self, key):
self.keypairs.pop(key)
def get_private_key(self, pubkey, password):
sec = pw_decode(self.keypairs[pubkey], password)
txin_type, privkey, compressed = deserialize_privkey(sec)
# this checks the password
if pubkey != public_key_from_private_key(privkey, compressed):
raise InvalidPassword()
return privkey, compressed
def get_pubkey_derivation(self, x_pubkey):
if x_pubkey[0:2] in ['02', '03', '04']:
if x_pubkey in self.keypairs.keys():
return x_pubkey
elif x_pubkey[0:2] == 'fd':
addr = bitcoin.script_to_address(x_pubkey[2:])
if addr in self.addresses:
return self.addresses[addr].get('pubkey')
def update_password(self, old_password, new_password):
self.check_password(old_password)
if new_password == '':
new_password = None
for k, v in self.keypairs.items():
b = pw_decode(v, old_password)
c = pw_encode(b, new_password)
self.keypairs[k] = c
class Deterministic_KeyStore(Software_KeyStore):
def __init__(self, d):
Software_KeyStore.__init__(self)
self.seed = d.get('seed', '')
self.passphrase = d.get('passphrase', '')
def is_deterministic(self):
return True
def dump(self):
d = {}
if self.seed:
d['seed'] = self.seed
if self.passphrase:
d['passphrase'] = self.passphrase
return d
def has_seed(self):
return bool(self.seed)
def is_watching_only(self):
return not self.has_seed()
def can_change_password(self):
return not self.is_watching_only()
def add_seed(self, seed):
if self.seed:
raise Exception("a seed exists")
self.seed = self.format_seed(seed)
def get_seed(self, password):
return pw_decode(self.seed, password)
def get_passphrase(self, password):
return pw_decode(self.passphrase, password) if self.passphrase else ''
class Xpub:
def __init__(self):
self.xpub = None
self.xpub_receive = None
self.xpub_change = None
def get_master_public_key(self):
return self.xpub
def derive_pubkey(self, for_change, n):
xpub = self.xpub_change if for_change else self.xpub_receive
if xpub is None:
xpub = bip32_public_derivation(self.xpub, "", "/%d"%for_change)
if for_change:
self.xpub_change = xpub
else:
self.xpub_receive = xpub
return self.get_pubkey_from_xpub(xpub, (n,))
@classmethod
def get_pubkey_from_xpub(self, xpub, sequence):
_, _, _, _, c, cK = deserialize_xpub(xpub)
for i in sequence:
cK, c = CKD_pub(cK, c, i)
return bh2u(cK)
def get_xpubkey(self, c, i):
s = ''.join(map(lambda x: bitcoin.int_to_hex(x,2), (c, i)))
return 'ff' + bh2u(bitcoin.DecodeBase58Check(self.xpub)) + s
@classmethod
def parse_xpubkey(self, pubkey):
assert pubkey[0:2] == 'ff'
pk = bfh(pubkey)
pk = pk[1:]
xkey = bitcoin.EncodeBase58Check(pk[0:78])
dd = pk[78:]
s = []
while dd:
n = int(bitcoin.rev_hex(bh2u(dd[0:2])), 16)
dd = dd[2:]
s.append(n)
assert len(s) == 2
return xkey, s
def get_pubkey_derivation(self, x_pubkey):
if x_pubkey[0:2] != 'ff':
return
xpub, derivation = self.parse_xpubkey(x_pubkey)
if self.xpub != xpub:
return
return derivation
class BIP32_KeyStore(Deterministic_KeyStore, Xpub):
def __init__(self, d):
Xpub.__init__(self)
Deterministic_KeyStore.__init__(self, d)
self.xpub = d.get('xpub')
self.xprv = d.get('xprv')
def format_seed(self, seed):
return ' '.join(seed.split())
def dump(self):
d = Deterministic_KeyStore.dump(self)
d['type'] = 'bip32'
d['xpub'] = self.xpub
d['xprv'] = self.xprv
return d
def get_master_private_key(self, password):
return pw_decode(self.xprv, password)
def check_password(self, password):
xprv = pw_decode(self.xprv, password)
if deserialize_xprv(xprv)[4] != deserialize_xpub(self.xpub)[4]:
raise InvalidPassword()
def update_password(self, old_password, new_password):
self.check_password(old_password)
if new_password == '':
new_password = None
if self.has_seed():
decoded = self.get_seed(old_password)
self.seed = pw_encode(decoded, new_password)
if self.passphrase:
decoded = self.get_passphrase(old_password)
self.passphrase = pw_encode(decoded, new_password)
if self.xprv is not None:
b = pw_decode(self.xprv, old_password)
self.xprv = pw_encode(b, new_password)
def is_watching_only(self):
return self.xprv is None
def add_xprv(self, xprv):
self.xprv = xprv
self.xpub = bitcoin.xpub_from_xprv(xprv)
def add_xprv_from_seed(self, bip32_seed, xtype, derivation):
xprv, xpub = bip32_root(bip32_seed, xtype)
xprv, xpub = bip32_private_derivation(xprv, "m/", derivation)
self.add_xprv(xprv)
def get_private_key(self, sequence, password):
xprv = self.get_master_private_key(password)
_, _, _, _, c, k = deserialize_xprv(xprv)
pk = bip32_private_key(sequence, k, c)
return pk, True
class Old_KeyStore(Deterministic_KeyStore):
def __init__(self, d):
Deterministic_KeyStore.__init__(self, d)
self.mpk = d.get('mpk')
def get_hex_seed(self, password):
return pw_decode(self.seed, password).encode('utf8')
def dump(self):
d = Deterministic_KeyStore.dump(self)
d['mpk'] = self.mpk
d['type'] = 'old'
return d
def add_seed(self, seedphrase):
Deterministic_KeyStore.add_seed(self, seedphrase)
s = self.get_hex_seed(None)
self.mpk = self.mpk_from_seed(s)
def add_master_public_key(self, mpk):
self.mpk = mpk
def format_seed(self, seed):
from . import old_mnemonic, mnemonic
seed = mnemonic.normalize_text(seed)
# see if seed was entered as hex
if seed:
try:
bfh(seed)
return str(seed)
except Exception:
pass
words = seed.split()
seed = old_mnemonic.mn_decode(words)
if not seed:
raise Exception("Invalid seed")
return seed
def get_seed(self, password):
from . import old_mnemonic
s = self.get_hex_seed(password)
return ' '.join(old_mnemonic.mn_encode(s))
@classmethod
def mpk_from_seed(klass, seed):
secexp = klass.stretch_key(seed)
master_private_key = ecdsa.SigningKey.from_secret_exponent(secexp, curve = SECP256k1)
master_public_key = master_private_key.get_verifying_key().to_string()
return bh2u(master_public_key)
@classmethod
def stretch_key(self, seed):
x = seed
for i in range(100000):
x = hashlib.sha256(x + seed).digest()
return string_to_number(x)
@classmethod
def get_sequence(self, mpk, for_change, n):
return string_to_number(Hash(("%d:%d:"%(n, for_change)).encode('ascii') + bfh(mpk)))
@classmethod
def get_pubkey_from_mpk(self, mpk, for_change, n):
z = self.get_sequence(mpk, for_change, n)
master_public_key = ecdsa.VerifyingKey.from_string(bfh(mpk), curve = SECP256k1)
pubkey_point = master_public_key.pubkey.point + z*SECP256k1.generator
public_key2 = ecdsa.VerifyingKey.from_public_point(pubkey_point, curve = SECP256k1)
return '04' + bh2u(public_key2.to_string())
def derive_pubkey(self, for_change, n):
return self.get_pubkey_from_mpk(self.mpk, for_change, n)
def get_private_key_from_stretched_exponent(self, for_change, n, secexp):
order = generator_secp256k1.order()
secexp = (secexp + self.get_sequence(self.mpk, for_change, n)) % order
pk = number_to_string(secexp, generator_secp256k1.order())
return pk
def get_private_key(self, sequence, password):
seed = self.get_hex_seed(password)
self.check_seed(seed)
for_change, n = sequence
secexp = self.stretch_key(seed)
pk = self.get_private_key_from_stretched_exponent(for_change, n, secexp)
return pk, False
def check_seed(self, seed):
secexp = self.stretch_key(seed)
master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
master_public_key = master_private_key.get_verifying_key().to_string()
if master_public_key != bfh(self.mpk):
print_error('invalid password (mpk)', self.mpk, bh2u(master_public_key))
raise InvalidPassword()
def check_password(self, password):
seed = self.get_hex_seed(password)
self.check_seed(seed)
def get_master_public_key(self):
return self.mpk
def get_xpubkey(self, for_change, n):
s = ''.join(map(lambda x: bitcoin.int_to_hex(x,2), (for_change, n)))
return 'fe' + self.mpk + s
@classmethod
def parse_xpubkey(self, x_pubkey):
assert x_pubkey[0:2] == 'fe'
pk = x_pubkey[2:]
mpk = pk[0:128]
dd = pk[128:]
s = []
while dd:
n = int(bitcoin.rev_hex(dd[0:4]), 16)
dd = dd[4:]
s.append(n)
assert len(s) == 2
return mpk, s
def get_pubkey_derivation(self, x_pubkey):
if x_pubkey[0:2] != 'fe':
return
mpk, derivation = self.parse_xpubkey(x_pubkey)
if self.mpk != mpk:
return
return derivation
def update_password(self, old_password, new_password):
self.check_password(old_password)
if new_password == '':
new_password = None
if self.has_seed():
decoded = pw_decode(self.seed, old_password)
self.seed = pw_encode(decoded, new_password)
class Hardware_KeyStore(KeyStore, Xpub):
# Derived classes must set:
# - device
# - DEVICE_IDS
# - wallet_type
#restore_wallet_class = BIP32_RD_Wallet
max_change_outputs = 1
def __init__(self, d):
Xpub.__init__(self)
KeyStore.__init__(self)
# Errors and other user interaction is done through the wallet's
# handler. The handler is per-window and preserved across
# device reconnects
self.xpub = d.get('xpub')
self.label = d.get('label')
self.derivation = d.get('derivation')
self.handler = None
run_hook('init_keystore', self)
def set_label(self, label):
self.label = label
def may_have_password(self):
return False
def is_deterministic(self):
return True
def dump(self):
return {
'type': 'hardware',
'hw_type': self.hw_type,
'xpub': self.xpub,
'derivation':self.derivation,
'label':self.label,
}
def unpaired(self):
'''A device paired with the wallet was diconnected. This can be
called in any thread context.'''
self.print_error("unpaired")
def paired(self):
'''A device paired with the wallet was (re-)connected. This can be
called in any thread context.'''
self.print_error("paired")
def can_export(self):
return False
def is_watching_only(self):
'''The wallet is not watching-only; the user will be prompted for
pin and passphrase as appropriate when needed.'''
assert not self.has_seed()
return False
def can_change_password(self):
return False
def bip39_normalize_passphrase(passphrase):
return normalize('NFKD', passphrase or '')
def bip39_to_seed(mnemonic, passphrase):
import pbkdf2, hashlib, hmac
PBKDF2_ROUNDS = 2048
mnemonic = normalize('NFKD', ' '.join(mnemonic.split()))
passphrase = bip39_normalize_passphrase(passphrase)
return pbkdf2.PBKDF2(mnemonic, 'mnemonic' + passphrase,
iterations = PBKDF2_ROUNDS, macmodule = hmac,
digestmodule = hashlib.sha512).read(64)
# returns tuple (is_checksum_valid, is_wordlist_valid)
def bip39_is_checksum_valid(mnemonic):
words = [ normalize('NFKD', word) for word in mnemonic.split() ]
words_len = len(words)
wordlist = load_wordlist("english.txt")
n = len(wordlist)
checksum_length = 11*words_len//33
entropy_length = 32*checksum_length
i = 0
words.reverse()
while words:
w = words.pop()
try:
k = wordlist.index(w)
except ValueError:
return False, False
i = i*n + k
if words_len not in [12, 15, 18, 21, 24]:
return False, True
entropy = i >> checksum_length
checksum = i % 2**checksum_length
h = '{:x}'.format(entropy)
while len(h) < entropy_length/4:
h = '0'+h
b = bytearray.fromhex(h)
hashed = int(hfu(hashlib.sha256(b).digest()), 16)
calculated_checksum = hashed >> (256 - checksum_length)
return checksum == calculated_checksum, True
def from_bip39_seed(seed, passphrase, derivation):
k = BIP32_KeyStore({})
bip32_seed = bip39_to_seed(seed, passphrase)
t = 'standard' # bip43
k.add_xprv_from_seed(bip32_seed, t, derivation)
return k
# extended pubkeys
def is_xpubkey(x_pubkey):
return x_pubkey[0:2] == 'ff'
def parse_xpubkey(x_pubkey):
assert x_pubkey[0:2] == 'ff'
return BIP32_KeyStore.parse_xpubkey(x_pubkey)
def xpubkey_to_address(x_pubkey):
if x_pubkey[0:2] == 'fd':
address = bitcoin.script_to_address(x_pubkey[2:])
return x_pubkey, address
if x_pubkey[0:2] in ['02', '03', '04']:
pubkey = x_pubkey
elif x_pubkey[0:2] == 'ff':
xpub, s = BIP32_KeyStore.parse_xpubkey(x_pubkey)
pubkey = BIP32_KeyStore.get_pubkey_from_xpub(xpub, s)
elif x_pubkey[0:2] == 'fe':
mpk, s = Old_KeyStore.parse_xpubkey(x_pubkey)
pubkey = Old_KeyStore.get_pubkey_from_mpk(mpk, s[0], s[1])
else:
raise BaseException("Cannot parse pubkey")
if pubkey:
address = public_key_to_p2pkh(bfh(pubkey))
return pubkey, address
def xpubkey_to_pubkey(x_pubkey):
pubkey, address = xpubkey_to_address(x_pubkey)
return pubkey
hw_keystores = {}
def register_keystore(hw_type, constructor):
hw_keystores[hw_type] = constructor
def hardware_keystore(d):
hw_type = d['hw_type']
if hw_type in hw_keystores:
constructor = hw_keystores[hw_type]
return constructor(d)
raise BaseException('unknown hardware type', hw_type)
def load_keystore(storage, name):
w = storage.get('wallet_type', 'standard')
d = storage.get(name, {})
t = d.get('type')
if not t:
raise BaseException('wallet format requires update')
if t == 'old':
k = Old_KeyStore(d)
elif t == 'imported':
k = Imported_KeyStore(d)
elif t == 'bip32':
k = BIP32_KeyStore(d)
elif t == 'hardware':
k = hardware_keystore(d)
else:
raise BaseException('unknown wallet type', t)
return k
def is_old_mpk(mpk):
try:
int(mpk, 16)
except:
return False
return len(mpk) == 128
def is_address_list(text):
parts = text.split()
return bool(parts) and all(bitcoin.is_address(x) for x in parts)
def get_private_keys(text):
parts = text.split('\n')
parts = map(lambda x: ''.join(x.split()), parts)
parts = list(filter(bool, parts))
if bool(parts) and all(bitcoin.is_private_key(x) for x in parts):
return parts
def is_private_key_list(text):
return bool(get_private_keys(text))
is_mpk = lambda x: is_old_mpk(x) or is_xpub(x)
is_private = lambda x: is_seed(x) or is_xprv(x) or is_private_key_list(x)
is_master_key = lambda x: is_old_mpk(x) or is_xprv(x) or is_xpub(x)
is_master_key_plus_drk = lambda x: is_drkp(x) or is_drkv(x) or is_master_key(x)
is_private_key = lambda x: is_xprv(x) or is_private_key_list(x)
is_bip32_key = lambda x: is_xprv(x) or is_xpub(x)
def bip44_derivation(account_id):
bip = 44
coin = 1 if bitcoin.NetworkConstants.TESTNET else 5
return "m/%d'/%d'/%d'" % (bip, coin, int(account_id))
def from_seed(seed, passphrase, is_p2sh):
t = seed_type(seed)
if t == 'old':
keystore = Old_KeyStore({})
keystore.add_seed(seed)
elif t in ['standard']:
keystore = BIP32_KeyStore({})
keystore.add_seed(seed)
keystore.passphrase = passphrase
bip32_seed = Mnemonic.mnemonic_to_seed(seed, passphrase)
der = "m/"
xtype = 'standard'
keystore.add_xprv_from_seed(bip32_seed, xtype, der)
else:
raise BaseException(t)
return keystore
def from_private_key_list(text):
keystore = Imported_KeyStore({})
for x in get_private_keys(text):
keystore.import_key(x, None)
return keystore
def from_old_mpk(mpk):
keystore = Old_KeyStore({})
keystore.add_master_public_key(mpk)
return keystore
def from_xpub(xpub):
k = BIP32_KeyStore({})
k.xpub = xpub
return k
def from_xprv(xprv):
xpub = bitcoin.xpub_from_xprv(xprv)
k = BIP32_KeyStore({})
k.xprv = xprv
k.xpub = xpub
return k
def from_drkp(drkp):
xtype, depth, fingerprint, child_number, c, cK = deserialize_drkp(drkp)
xpub = serialize_xpub(xtype, c, cK, depth, fingerprint, child_number)
k = BIP32_KeyStore({})
k.xpub = xpub
return k
def from_drkv(drkv):
xtype, depth, fingerprint, child_number, c, k = deserialize_drkv(drkv)
xprv = serialize_xprv(xtype, c, k, depth, fingerprint, child_number)
xpub = bitcoin.xpub_from_xprv(xprv)
k = BIP32_KeyStore({})
k.xprv = xprv
k.xpub = xpub
return k
def from_master_key(text):
if is_xprv(text):
k = from_xprv(text)
elif is_old_mpk(text):
k = from_old_mpk(text)
elif is_xpub(text):
k = from_xpub(text)
elif is_drkv(text):
k = from_drkv(text)
elif is_drkp(text):
k = from_drkp(text)
else:
raise BaseException('Invalid key')
return k
| 30.730667 | 95 | 0.63025 |
from unicodedata import normalize
from . import bitcoin
from .bitcoin import *
from .util import PrintError, InvalidPassword, hfu
from .mnemonic import Mnemonic, load_wordlist
from .plugins import run_hook
class KeyStore(PrintError):
def has_seed(self):
return False
def is_watching_only(self):
return False
def can_import(self):
return False
def get_tx_derivations(self, tx):
keypairs = {}
for txin in tx.inputs():
num_sig = txin.get('num_sig')
if num_sig is None:
continue
x_signatures = txin['signatures']
signatures = [sig for sig in x_signatures if sig]
if len(signatures) == num_sig:
continue
for k, x_pubkey in enumerate(txin['x_pubkeys']):
if x_signatures[k] is not None:
continue
derivation = self.get_pubkey_derivation(x_pubkey)
if not derivation:
continue
keypairs[x_pubkey] = derivation
return keypairs
def can_sign(self, tx):
if self.is_watching_only():
return False
return bool(self.get_tx_derivations(tx))
class Software_KeyStore(KeyStore):
def __init__(self):
KeyStore.__init__(self)
def may_have_password(self):
return not self.is_watching_only()
def sign_message(self, sequence, message, password):
privkey, compressed = self.get_private_key(sequence, password)
key = regenerate_key(privkey)
return key.sign_message(message, compressed)
def decrypt_message(self, sequence, message, password):
privkey, compressed = self.get_private_key(sequence, password)
ec = regenerate_key(privkey)
decrypted = ec.decrypt_message(message)
return decrypted
def sign_transaction(self, tx, password):
if self.is_watching_only():
return
self.check_password(password)
keypairs = self.get_tx_derivations(tx)
for k, v in keypairs.items():
keypairs[k] = self.get_private_key(v, password)
if keypairs:
tx.sign(keypairs)
class Imported_KeyStore(Software_KeyStore):
def __init__(self, d):
Software_KeyStore.__init__(self)
self.keypairs = d.get('keypairs', {})
def is_deterministic(self):
return False
def can_change_password(self):
return True
def get_master_public_key(self):
return None
def dump(self):
return {
'type': 'imported',
'keypairs': self.keypairs,
}
def can_import(self):
return True
def check_password(self, password):
pubkey = list(self.keypairs.keys())[0]
self.get_private_key(pubkey, password)
def import_privkey(self, sec, password):
txin_type, privkey, compressed = deserialize_privkey(sec)
pubkey = public_key_from_private_key(privkey, compressed)
self.keypairs[pubkey] = pw_encode(sec, password)
return txin_type, pubkey
def delete_imported_key(self, key):
self.keypairs.pop(key)
def get_private_key(self, pubkey, password):
sec = pw_decode(self.keypairs[pubkey], password)
txin_type, privkey, compressed = deserialize_privkey(sec)
if pubkey != public_key_from_private_key(privkey, compressed):
raise InvalidPassword()
return privkey, compressed
def get_pubkey_derivation(self, x_pubkey):
if x_pubkey[0:2] in ['02', '03', '04']:
if x_pubkey in self.keypairs.keys():
return x_pubkey
elif x_pubkey[0:2] == 'fd':
addr = bitcoin.script_to_address(x_pubkey[2:])
if addr in self.addresses:
return self.addresses[addr].get('pubkey')
def update_password(self, old_password, new_password):
self.check_password(old_password)
if new_password == '':
new_password = None
for k, v in self.keypairs.items():
b = pw_decode(v, old_password)
c = pw_encode(b, new_password)
self.keypairs[k] = c
class Deterministic_KeyStore(Software_KeyStore):
def __init__(self, d):
Software_KeyStore.__init__(self)
self.seed = d.get('seed', '')
self.passphrase = d.get('passphrase', '')
def is_deterministic(self):
return True
def dump(self):
d = {}
if self.seed:
d['seed'] = self.seed
if self.passphrase:
d['passphrase'] = self.passphrase
return d
def has_seed(self):
return bool(self.seed)
def is_watching_only(self):
return not self.has_seed()
def can_change_password(self):
return not self.is_watching_only()
def add_seed(self, seed):
if self.seed:
raise Exception("a seed exists")
self.seed = self.format_seed(seed)
def get_seed(self, password):
return pw_decode(self.seed, password)
def get_passphrase(self, password):
return pw_decode(self.passphrase, password) if self.passphrase else ''
class Xpub:
def __init__(self):
self.xpub = None
self.xpub_receive = None
self.xpub_change = None
def get_master_public_key(self):
return self.xpub
def derive_pubkey(self, for_change, n):
xpub = self.xpub_change if for_change else self.xpub_receive
if xpub is None:
xpub = bip32_public_derivation(self.xpub, "", "/%d"%for_change)
if for_change:
self.xpub_change = xpub
else:
self.xpub_receive = xpub
return self.get_pubkey_from_xpub(xpub, (n,))
@classmethod
def get_pubkey_from_xpub(self, xpub, sequence):
_, _, _, _, c, cK = deserialize_xpub(xpub)
for i in sequence:
cK, c = CKD_pub(cK, c, i)
return bh2u(cK)
def get_xpubkey(self, c, i):
s = ''.join(map(lambda x: bitcoin.int_to_hex(x,2), (c, i)))
return 'ff' + bh2u(bitcoin.DecodeBase58Check(self.xpub)) + s
@classmethod
def parse_xpubkey(self, pubkey):
assert pubkey[0:2] == 'ff'
pk = bfh(pubkey)
pk = pk[1:]
xkey = bitcoin.EncodeBase58Check(pk[0:78])
dd = pk[78:]
s = []
while dd:
n = int(bitcoin.rev_hex(bh2u(dd[0:2])), 16)
dd = dd[2:]
s.append(n)
assert len(s) == 2
return xkey, s
def get_pubkey_derivation(self, x_pubkey):
if x_pubkey[0:2] != 'ff':
return
xpub, derivation = self.parse_xpubkey(x_pubkey)
if self.xpub != xpub:
return
return derivation
class BIP32_KeyStore(Deterministic_KeyStore, Xpub):
def __init__(self, d):
Xpub.__init__(self)
Deterministic_KeyStore.__init__(self, d)
self.xpub = d.get('xpub')
self.xprv = d.get('xprv')
def format_seed(self, seed):
return ' '.join(seed.split())
def dump(self):
d = Deterministic_KeyStore.dump(self)
d['type'] = 'bip32'
d['xpub'] = self.xpub
d['xprv'] = self.xprv
return d
def get_master_private_key(self, password):
return pw_decode(self.xprv, password)
def check_password(self, password):
xprv = pw_decode(self.xprv, password)
if deserialize_xprv(xprv)[4] != deserialize_xpub(self.xpub)[4]:
raise InvalidPassword()
def update_password(self, old_password, new_password):
self.check_password(old_password)
if new_password == '':
new_password = None
if self.has_seed():
decoded = self.get_seed(old_password)
self.seed = pw_encode(decoded, new_password)
if self.passphrase:
decoded = self.get_passphrase(old_password)
self.passphrase = pw_encode(decoded, new_password)
if self.xprv is not None:
b = pw_decode(self.xprv, old_password)
self.xprv = pw_encode(b, new_password)
def is_watching_only(self):
return self.xprv is None
def add_xprv(self, xprv):
self.xprv = xprv
self.xpub = bitcoin.xpub_from_xprv(xprv)
def add_xprv_from_seed(self, bip32_seed, xtype, derivation):
xprv, xpub = bip32_root(bip32_seed, xtype)
xprv, xpub = bip32_private_derivation(xprv, "m/", derivation)
self.add_xprv(xprv)
def get_private_key(self, sequence, password):
xprv = self.get_master_private_key(password)
_, _, _, _, c, k = deserialize_xprv(xprv)
pk = bip32_private_key(sequence, k, c)
return pk, True
class Old_KeyStore(Deterministic_KeyStore):
def __init__(self, d):
Deterministic_KeyStore.__init__(self, d)
self.mpk = d.get('mpk')
def get_hex_seed(self, password):
return pw_decode(self.seed, password).encode('utf8')
def dump(self):
d = Deterministic_KeyStore.dump(self)
d['mpk'] = self.mpk
d['type'] = 'old'
return d
def add_seed(self, seedphrase):
Deterministic_KeyStore.add_seed(self, seedphrase)
s = self.get_hex_seed(None)
self.mpk = self.mpk_from_seed(s)
def add_master_public_key(self, mpk):
self.mpk = mpk
def format_seed(self, seed):
from . import old_mnemonic, mnemonic
seed = mnemonic.normalize_text(seed)
if seed:
try:
bfh(seed)
return str(seed)
except Exception:
pass
words = seed.split()
seed = old_mnemonic.mn_decode(words)
if not seed:
raise Exception("Invalid seed")
return seed
def get_seed(self, password):
from . import old_mnemonic
s = self.get_hex_seed(password)
return ' '.join(old_mnemonic.mn_encode(s))
@classmethod
def mpk_from_seed(klass, seed):
secexp = klass.stretch_key(seed)
master_private_key = ecdsa.SigningKey.from_secret_exponent(secexp, curve = SECP256k1)
master_public_key = master_private_key.get_verifying_key().to_string()
return bh2u(master_public_key)
@classmethod
def stretch_key(self, seed):
x = seed
for i in range(100000):
x = hashlib.sha256(x + seed).digest()
return string_to_number(x)
@classmethod
def get_sequence(self, mpk, for_change, n):
return string_to_number(Hash(("%d:%d:"%(n, for_change)).encode('ascii') + bfh(mpk)))
@classmethod
def get_pubkey_from_mpk(self, mpk, for_change, n):
z = self.get_sequence(mpk, for_change, n)
master_public_key = ecdsa.VerifyingKey.from_string(bfh(mpk), curve = SECP256k1)
pubkey_point = master_public_key.pubkey.point + z*SECP256k1.generator
public_key2 = ecdsa.VerifyingKey.from_public_point(pubkey_point, curve = SECP256k1)
return '04' + bh2u(public_key2.to_string())
def derive_pubkey(self, for_change, n):
return self.get_pubkey_from_mpk(self.mpk, for_change, n)
def get_private_key_from_stretched_exponent(self, for_change, n, secexp):
order = generator_secp256k1.order()
secexp = (secexp + self.get_sequence(self.mpk, for_change, n)) % order
pk = number_to_string(secexp, generator_secp256k1.order())
return pk
def get_private_key(self, sequence, password):
seed = self.get_hex_seed(password)
self.check_seed(seed)
for_change, n = sequence
secexp = self.stretch_key(seed)
pk = self.get_private_key_from_stretched_exponent(for_change, n, secexp)
return pk, False
def check_seed(self, seed):
secexp = self.stretch_key(seed)
master_private_key = ecdsa.SigningKey.from_secret_exponent( secexp, curve = SECP256k1 )
master_public_key = master_private_key.get_verifying_key().to_string()
if master_public_key != bfh(self.mpk):
print_error('invalid password (mpk)', self.mpk, bh2u(master_public_key))
raise InvalidPassword()
def check_password(self, password):
seed = self.get_hex_seed(password)
self.check_seed(seed)
def get_master_public_key(self):
return self.mpk
def get_xpubkey(self, for_change, n):
s = ''.join(map(lambda x: bitcoin.int_to_hex(x,2), (for_change, n)))
return 'fe' + self.mpk + s
@classmethod
def parse_xpubkey(self, x_pubkey):
assert x_pubkey[0:2] == 'fe'
pk = x_pubkey[2:]
mpk = pk[0:128]
dd = pk[128:]
s = []
while dd:
n = int(bitcoin.rev_hex(dd[0:4]), 16)
dd = dd[4:]
s.append(n)
assert len(s) == 2
return mpk, s
def get_pubkey_derivation(self, x_pubkey):
if x_pubkey[0:2] != 'fe':
return
mpk, derivation = self.parse_xpubkey(x_pubkey)
if self.mpk != mpk:
return
return derivation
def update_password(self, old_password, new_password):
self.check_password(old_password)
if new_password == '':
new_password = None
if self.has_seed():
decoded = pw_decode(self.seed, old_password)
self.seed = pw_encode(decoded, new_password)
class Hardware_KeyStore(KeyStore, Xpub):
max_change_outputs = 1
def __init__(self, d):
Xpub.__init__(self)
KeyStore.__init__(self)
# handler. The handler is per-window and preserved across
# device reconnects
self.xpub = d.get('xpub')
self.label = d.get('label')
self.derivation = d.get('derivation')
self.handler = None
run_hook('init_keystore', self)
def set_label(self, label):
self.label = label
def may_have_password(self):
return False
def is_deterministic(self):
return True
def dump(self):
return {
'type': 'hardware',
'hw_type': self.hw_type,
'xpub': self.xpub,
'derivation':self.derivation,
'label':self.label,
}
def unpaired(self):
self.print_error("unpaired")
def paired(self):
self.print_error("paired")
def can_export(self):
return False
def is_watching_only(self):
assert not self.has_seed()
return False
def can_change_password(self):
return False
def bip39_normalize_passphrase(passphrase):
return normalize('NFKD', passphrase or '')
def bip39_to_seed(mnemonic, passphrase):
import pbkdf2, hashlib, hmac
PBKDF2_ROUNDS = 2048
mnemonic = normalize('NFKD', ' '.join(mnemonic.split()))
passphrase = bip39_normalize_passphrase(passphrase)
return pbkdf2.PBKDF2(mnemonic, 'mnemonic' + passphrase,
iterations = PBKDF2_ROUNDS, macmodule = hmac,
digestmodule = hashlib.sha512).read(64)
# returns tuple (is_checksum_valid, is_wordlist_valid)
def bip39_is_checksum_valid(mnemonic):
words = [ normalize('NFKD', word) for word in mnemonic.split() ]
words_len = len(words)
wordlist = load_wordlist("english.txt")
n = len(wordlist)
checksum_length = 11*words_len//33
entropy_length = 32*checksum_length
i = 0
words.reverse()
while words:
w = words.pop()
try:
k = wordlist.index(w)
except ValueError:
return False, False
i = i*n + k
if words_len not in [12, 15, 18, 21, 24]:
return False, True
entropy = i >> checksum_length
checksum = i % 2**checksum_length
h = '{:x}'.format(entropy)
while len(h) < entropy_length/4:
h = '0'+h
b = bytearray.fromhex(h)
hashed = int(hfu(hashlib.sha256(b).digest()), 16)
calculated_checksum = hashed >> (256 - checksum_length)
return checksum == calculated_checksum, True
def from_bip39_seed(seed, passphrase, derivation):
k = BIP32_KeyStore({})
bip32_seed = bip39_to_seed(seed, passphrase)
t = 'standard' # bip43
k.add_xprv_from_seed(bip32_seed, t, derivation)
return k
# extended pubkeys
def is_xpubkey(x_pubkey):
return x_pubkey[0:2] == 'ff'
def parse_xpubkey(x_pubkey):
assert x_pubkey[0:2] == 'ff'
return BIP32_KeyStore.parse_xpubkey(x_pubkey)
def xpubkey_to_address(x_pubkey):
if x_pubkey[0:2] == 'fd':
address = bitcoin.script_to_address(x_pubkey[2:])
return x_pubkey, address
if x_pubkey[0:2] in ['02', '03', '04']:
pubkey = x_pubkey
elif x_pubkey[0:2] == 'ff':
xpub, s = BIP32_KeyStore.parse_xpubkey(x_pubkey)
pubkey = BIP32_KeyStore.get_pubkey_from_xpub(xpub, s)
elif x_pubkey[0:2] == 'fe':
mpk, s = Old_KeyStore.parse_xpubkey(x_pubkey)
pubkey = Old_KeyStore.get_pubkey_from_mpk(mpk, s[0], s[1])
else:
raise BaseException("Cannot parse pubkey")
if pubkey:
address = public_key_to_p2pkh(bfh(pubkey))
return pubkey, address
def xpubkey_to_pubkey(x_pubkey):
pubkey, address = xpubkey_to_address(x_pubkey)
return pubkey
hw_keystores = {}
def register_keystore(hw_type, constructor):
hw_keystores[hw_type] = constructor
def hardware_keystore(d):
hw_type = d['hw_type']
if hw_type in hw_keystores:
constructor = hw_keystores[hw_type]
return constructor(d)
raise BaseException('unknown hardware type', hw_type)
def load_keystore(storage, name):
w = storage.get('wallet_type', 'standard')
d = storage.get(name, {})
t = d.get('type')
if not t:
raise BaseException('wallet format requires update')
if t == 'old':
k = Old_KeyStore(d)
elif t == 'imported':
k = Imported_KeyStore(d)
elif t == 'bip32':
k = BIP32_KeyStore(d)
elif t == 'hardware':
k = hardware_keystore(d)
else:
raise BaseException('unknown wallet type', t)
return k
def is_old_mpk(mpk):
try:
int(mpk, 16)
except:
return False
return len(mpk) == 128
def is_address_list(text):
parts = text.split()
return bool(parts) and all(bitcoin.is_address(x) for x in parts)
def get_private_keys(text):
parts = text.split('\n')
parts = map(lambda x: ''.join(x.split()), parts)
parts = list(filter(bool, parts))
if bool(parts) and all(bitcoin.is_private_key(x) for x in parts):
return parts
def is_private_key_list(text):
return bool(get_private_keys(text))
is_mpk = lambda x: is_old_mpk(x) or is_xpub(x)
is_private = lambda x: is_seed(x) or is_xprv(x) or is_private_key_list(x)
is_master_key = lambda x: is_old_mpk(x) or is_xprv(x) or is_xpub(x)
is_master_key_plus_drk = lambda x: is_drkp(x) or is_drkv(x) or is_master_key(x)
is_private_key = lambda x: is_xprv(x) or is_private_key_list(x)
is_bip32_key = lambda x: is_xprv(x) or is_xpub(x)
def bip44_derivation(account_id):
bip = 44
coin = 1 if bitcoin.NetworkConstants.TESTNET else 5
return "m/%d'/%d'/%d'" % (bip, coin, int(account_id))
def from_seed(seed, passphrase, is_p2sh):
t = seed_type(seed)
if t == 'old':
keystore = Old_KeyStore({})
keystore.add_seed(seed)
elif t in ['standard']:
keystore = BIP32_KeyStore({})
keystore.add_seed(seed)
keystore.passphrase = passphrase
bip32_seed = Mnemonic.mnemonic_to_seed(seed, passphrase)
der = "m/"
xtype = 'standard'
keystore.add_xprv_from_seed(bip32_seed, xtype, der)
else:
raise BaseException(t)
return keystore
def from_private_key_list(text):
keystore = Imported_KeyStore({})
for x in get_private_keys(text):
keystore.import_key(x, None)
return keystore
def from_old_mpk(mpk):
keystore = Old_KeyStore({})
keystore.add_master_public_key(mpk)
return keystore
def from_xpub(xpub):
k = BIP32_KeyStore({})
k.xpub = xpub
return k
def from_xprv(xprv):
xpub = bitcoin.xpub_from_xprv(xprv)
k = BIP32_KeyStore({})
k.xprv = xprv
k.xpub = xpub
return k
def from_drkp(drkp):
xtype, depth, fingerprint, child_number, c, cK = deserialize_drkp(drkp)
xpub = serialize_xpub(xtype, c, cK, depth, fingerprint, child_number)
k = BIP32_KeyStore({})
k.xpub = xpub
return k
def from_drkv(drkv):
xtype, depth, fingerprint, child_number, c, k = deserialize_drkv(drkv)
xprv = serialize_xprv(xtype, c, k, depth, fingerprint, child_number)
xpub = bitcoin.xpub_from_xprv(xprv)
k = BIP32_KeyStore({})
k.xprv = xprv
k.xpub = xpub
return k
def from_master_key(text):
if is_xprv(text):
k = from_xprv(text)
elif is_old_mpk(text):
k = from_old_mpk(text)
elif is_xpub(text):
k = from_xpub(text)
elif is_drkv(text):
k = from_drkv(text)
elif is_drkp(text):
k = from_drkp(text)
else:
raise BaseException('Invalid key')
return k
| true | true |
f72bffcf3e618c50ae473c4085888ea423e1b4c8 | 6,863 | py | Python | tests/system_tests_console.py | kishorkunal-raj/qpid-dispatch | f629b448dc1ae92d46c31f3c8d7bf317412b9e22 | [
"Apache-2.0"
] | 1 | 2019-07-16T10:24:40.000Z | 2019-07-16T10:24:40.000Z | tests/system_tests_console.py | kishorkunal-raj/qpid-dispatch | f629b448dc1ae92d46c31f3c8d7bf317412b9e22 | [
"Apache-2.0"
] | 121 | 2020-09-16T06:03:53.000Z | 2022-03-30T13:03:23.000Z | tests/system_tests_console.py | irinabov/debian-qpid-dispatch | 42fb2ffb65f8e8c8d616633c0b4308d6531a281d | [
"Apache-2.0"
] | null | null | null | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License
#
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import os
import errno
import re
import time
import unittest
from subprocess import PIPE
import subprocess
from system_test import main_module, SkipIfNeeded, TestCase
from system_test import Qdrouterd, TIMEOUT, AsyncTestSender, AsyncTestReceiver
try:
import queue as Queue # 3.x
except ImportError:
import Queue as Queue # 2.7
from threading import Thread
from threading import Event
import uuid
from proton import Message
from proton.handlers import MessagingHandler
from proton.reactor import Container
class ConsolePreReq(object):
@staticmethod
def is_cmd(name):
''' determine if a command is present and executes on the system '''
try:
devnull = open(os.devnull, "w")
subprocess.Popen([name], stdout=devnull, stderr=devnull).communicate()
except OSError as e:
if errno == errno.ENOENT:
return False
return True
@staticmethod
def should_skip():
try:
found_npm = ConsolePreReq.is_cmd('npm')
return not found_npm
except OSError:
return True
class ConsoleTest(TestCase):
"""Run npm console tests"""
@classmethod
def setUpClass(cls):
super(ConsoleTest, cls).setUpClass()
def router(name, mode, extra):
config = [
('router', {'mode': mode, 'id': name}),
('listener', {'role': 'normal', 'port': cls.tester.get_port()})
]
if extra:
config.extend(extra)
config = Qdrouterd.Config(config)
cls.routers.append(cls.tester.qdrouterd(name, config, wait=True))
return cls.routers[-1]
cls.routers = []
interrouter_port = cls.tester.get_port()
cls.http_port = cls.tester.get_port()
cls.sender_port = cls.tester.get_port()
cls.receiver_port = cls.tester.get_port()
router('A', 'interior',
[('listener', {'role': 'inter-router', 'port': interrouter_port}),
('listener', {'role': 'normal', 'port': cls.sender_port}),
('listener', {'role': 'normal', 'port': cls.http_port, 'http': True})])
cls.INT_A = cls.routers[0]
cls.INT_A.listener = cls.INT_A.addresses[0]
router('B', 'interior',
[('connector', {'name': 'connectorToA', 'role': 'inter-router',
'port': interrouter_port}),
('listener', {'role': 'normal', 'port': cls.receiver_port})])
cls.INT_B = cls.routers[1]
cls.INT_B.listener = cls.INT_B.addresses[0]
cls.INT_A.wait_router_connected('B')
cls.INT_B.wait_router_connected('A')
def run_console_test(self):
address = "toB"
# create a slow receiver so that we get delayedDeliveries
receiver = AsyncSlowReceiver(self.INT_B.listener, address)
sender = AsyncStopableSender(self.INT_A.listener, address)
pret = 0
out = ''
prg = ['npm', 'test', '--', '--watchAll=false']
p = self.popen(prg,
cwd=os.path.join(os.environ.get('BUILD_DIR'), 'console'),
env=dict(os.environ, TEST_PORT="%d" % self.http_port),
stdout=PIPE,
expect=None)
out = p.communicate()[0]
pret = p.returncode
# write the output
with open('run_console_test.out', 'w') as popenfile:
popenfile.write('returncode was %s\n' % p.returncode)
popenfile.write('out was:\n')
popenfile.writelines(str(out))
sender.stop()
receiver.stop()
time.sleep(1)
assert pret == 0, \
"console test exit status %d, output:\n%s" % (pret, out)
return out
# If we are unable to run the npm command. Skip the test
@SkipIfNeeded(ConsolePreReq.should_skip(), 'Test skipped: npm command not found')
def test_console(self):
self.run_console_test()
class AsyncStopableSender(AsyncTestSender):
def __init__(self, hostport, address):
super(AsyncStopableSender, self).__init__(hostport, address, 999999999)
self._stop_thread = False
self.sent = 0
def _main(self):
self._container.start()
while self._container.process():
if self._stop_thread:
if self._conn:
self._conn.close()
self._conn = None
def on_sendable(self, event):
self._sender.send(Message(body="message %d" % self.sent))
self.sent += 1
def stop(self, timeout=TIMEOUT):
self._stop_thread = True
self._container.wakeup()
self._thread.join(timeout=TIMEOUT)
if self._thread.is_alive():
raise Exception("AsyncStopableSender did not exit")
# Based on gsim's slow_recv.py
class TimedFlow(MessagingHandler):
def __init__(self, receiver, credit):
super(TimedFlow, self).__init__()
self.receiver = receiver
self.credit = credit
def on_timer_task(self, event):
self.receiver.flow(self.credit)
class AsyncSlowReceiver(AsyncTestReceiver):
def __init__(self, hostport, target):
super(AsyncSlowReceiver, self).__init__(hostport, target, msg_args={"prefetch": 0})
def on_link_opened(self, event):
super(AsyncSlowReceiver, self).on_link_opened(event)
self.request_batch(event)
def request_batch(self, event):
event.container.schedule(1, TimedFlow(event.receiver, 10))
def check_empty(self, receiver):
return not receiver.credit and not receiver.queued
def on_link_flow(self, event):
if self.check_empty(event.receiver):
self.request_batch(event)
def on_message(self, event):
print (event.message.body)
if self.check_empty(event.receiver):
self.request_batch(event)
if __name__ == '__main__':
unittest.main(main_module())
| 32.837321 | 91 | 0.635582 |
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import os
import errno
import re
import time
import unittest
from subprocess import PIPE
import subprocess
from system_test import main_module, SkipIfNeeded, TestCase
from system_test import Qdrouterd, TIMEOUT, AsyncTestSender, AsyncTestReceiver
try:
import queue as Queue
except ImportError:
import Queue as Queue
from threading import Thread
from threading import Event
import uuid
from proton import Message
from proton.handlers import MessagingHandler
from proton.reactor import Container
class ConsolePreReq(object):
@staticmethod
def is_cmd(name):
try:
devnull = open(os.devnull, "w")
subprocess.Popen([name], stdout=devnull, stderr=devnull).communicate()
except OSError as e:
if errno == errno.ENOENT:
return False
return True
@staticmethod
def should_skip():
try:
found_npm = ConsolePreReq.is_cmd('npm')
return not found_npm
except OSError:
return True
class ConsoleTest(TestCase):
@classmethod
def setUpClass(cls):
super(ConsoleTest, cls).setUpClass()
def router(name, mode, extra):
config = [
('router', {'mode': mode, 'id': name}),
('listener', {'role': 'normal', 'port': cls.tester.get_port()})
]
if extra:
config.extend(extra)
config = Qdrouterd.Config(config)
cls.routers.append(cls.tester.qdrouterd(name, config, wait=True))
return cls.routers[-1]
cls.routers = []
interrouter_port = cls.tester.get_port()
cls.http_port = cls.tester.get_port()
cls.sender_port = cls.tester.get_port()
cls.receiver_port = cls.tester.get_port()
router('A', 'interior',
[('listener', {'role': 'inter-router', 'port': interrouter_port}),
('listener', {'role': 'normal', 'port': cls.sender_port}),
('listener', {'role': 'normal', 'port': cls.http_port, 'http': True})])
cls.INT_A = cls.routers[0]
cls.INT_A.listener = cls.INT_A.addresses[0]
router('B', 'interior',
[('connector', {'name': 'connectorToA', 'role': 'inter-router',
'port': interrouter_port}),
('listener', {'role': 'normal', 'port': cls.receiver_port})])
cls.INT_B = cls.routers[1]
cls.INT_B.listener = cls.INT_B.addresses[0]
cls.INT_A.wait_router_connected('B')
cls.INT_B.wait_router_connected('A')
def run_console_test(self):
address = "toB"
receiver = AsyncSlowReceiver(self.INT_B.listener, address)
sender = AsyncStopableSender(self.INT_A.listener, address)
pret = 0
out = ''
prg = ['npm', 'test', '--', '--watchAll=false']
p = self.popen(prg,
cwd=os.path.join(os.environ.get('BUILD_DIR'), 'console'),
env=dict(os.environ, TEST_PORT="%d" % self.http_port),
stdout=PIPE,
expect=None)
out = p.communicate()[0]
pret = p.returncode
with open('run_console_test.out', 'w') as popenfile:
popenfile.write('returncode was %s\n' % p.returncode)
popenfile.write('out was:\n')
popenfile.writelines(str(out))
sender.stop()
receiver.stop()
time.sleep(1)
assert pret == 0, \
"console test exit status %d, output:\n%s" % (pret, out)
return out
@SkipIfNeeded(ConsolePreReq.should_skip(), 'Test skipped: npm command not found')
def test_console(self):
self.run_console_test()
class AsyncStopableSender(AsyncTestSender):
def __init__(self, hostport, address):
super(AsyncStopableSender, self).__init__(hostport, address, 999999999)
self._stop_thread = False
self.sent = 0
def _main(self):
self._container.start()
while self._container.process():
if self._stop_thread:
if self._conn:
self._conn.close()
self._conn = None
def on_sendable(self, event):
self._sender.send(Message(body="message %d" % self.sent))
self.sent += 1
def stop(self, timeout=TIMEOUT):
self._stop_thread = True
self._container.wakeup()
self._thread.join(timeout=TIMEOUT)
if self._thread.is_alive():
raise Exception("AsyncStopableSender did not exit")
class TimedFlow(MessagingHandler):
def __init__(self, receiver, credit):
super(TimedFlow, self).__init__()
self.receiver = receiver
self.credit = credit
def on_timer_task(self, event):
self.receiver.flow(self.credit)
class AsyncSlowReceiver(AsyncTestReceiver):
def __init__(self, hostport, target):
super(AsyncSlowReceiver, self).__init__(hostport, target, msg_args={"prefetch": 0})
def on_link_opened(self, event):
super(AsyncSlowReceiver, self).on_link_opened(event)
self.request_batch(event)
def request_batch(self, event):
event.container.schedule(1, TimedFlow(event.receiver, 10))
def check_empty(self, receiver):
return not receiver.credit and not receiver.queued
def on_link_flow(self, event):
if self.check_empty(event.receiver):
self.request_batch(event)
def on_message(self, event):
print (event.message.body)
if self.check_empty(event.receiver):
self.request_batch(event)
if __name__ == '__main__':
unittest.main(main_module())
| true | true |
f72bfffe1663a5030918dbba8147d3457fb5b2fd | 3,095 | py | Python | examples/basic_2.py | yoavfreund/DAPPER | c2fa5cc446a2b22a1efc174afc7e091363c9375d | [
"MIT"
] | null | null | null | examples/basic_2.py | yoavfreund/DAPPER | c2fa5cc446a2b22a1efc174afc7e091363c9375d | [
"MIT"
] | null | null | null | examples/basic_2.py | yoavfreund/DAPPER | c2fa5cc446a2b22a1efc174afc7e091363c9375d | [
"MIT"
] | null | null | null | # ## Illustrate usage of DAPPER to benchmark multiple DA methods.
# #### Imports
# <b>NB:</b> If you're on <mark><b>Gooble Colab</b></mark>,
# then replace `%matplotlib notebook` below by
# `!python -m pip install git+https://github.com/nansencenter/DAPPER.git` .
# Also note that liveplotting does not work on Colab.
# %matplotlib notebook
import dapper as dpr
import dapper.da_methods as da
# #### DA method configurations
from dapper.mods.Lorenz63.sakov2012 import HMM # Expected rmse.a:
xps = dpr.xpList()
xps += da.Climatology() # 7.6
xps += da.OptInterp() # 1.25
xps += da.Persistence() # 10.7
xps += da.PreProg(lambda k, xx, yy: xx[k]) # 0
xps += da.Var3D(xB=0.1) # 1.03
xps += da.ExtKF(infl=90) # 0.87
xps += da.EnKF('Sqrt' , N=3 , infl=1.30) # 0.82
xps += da.EnKF('Sqrt' , N=10 , infl=1.02, rot=True) # 0.63
xps += da.EnKF('PertObs', N=500 , infl=0.95, rot=False) # 0.56
xps += da.EnKF_N( N=10 , rot=True) # 0.54
xps += da.iEnKS('Sqrt' , N=10 , infl=1.02, rot=True) # 0.31
xps += da.PartFilt( N=100 , reg=2.4 , NER=0.3) # 0.38
xps += da.PartFilt( N=800 , reg=0.9 , NER=0.2) # 0.28
# xps += da.PartFilt( N=4000, reg=0.7 , NER=0.05) # 0.27
# xps += da.PFxN(xN=1000, N=30 , Qs=2 , NER=0.2) # 0.56
# #### With Lorenz-96 instead
# +
# from dapper.mods.Lorenz96.sakov2008 import HMM # Expected rmse.a:
# xps = dpr.xpList()
# xps += da.Climatology() # 3.6
# xps += da.OptInterp() # 0.95
# xps += da.Var3D(xB=0.02) # 0.41
# xps += da.ExtKF(infl=6) # 0.24
# xps += da.EnKF('PertObs', N=40, infl=1.06) # 0.22
# xps += da.EnKF('Sqrt' , N=28, infl=1.02, rot=True) # 0.18
# # More sophisticated:
# xps += da.EnKF_N( N=24, rot=True) # 0.21
# xps += da.EnKF_N( N=24, rot=True, xN=2) # 0.18
# xps += da.iEnKS('Sqrt' , N=40, infl=1.01, rot=True) # 0.17
# # With localisation:
# xps += da.LETKF( N=7 , infl=1.04, rot=True, loc_rad=4) # 0.22
# xps += da.SL_EAKF( N=7 , infl=1.07, rot=True, loc_rad=6) # 0.23
# -
# #### Other models (suitable xp's listed in HMM files):
# +
# from dapper.mods.LA .evensen2009 import HMM
# from dapper.mods.KS .bocquet2019 import HMM
# from dapper.mods.LotkaVolterra.settings101 import HMM
# -
# #### Launch
# Write some more non-arg parameters to the `xps`. In this case we set the seed,
# so that repeat experiments produce exactly the same result.
for xp in xps:
xp.seed = 3000
# Adjust experiment duration
HMM.tseq.T = 50
# Run/assimilate (for each `xp` in `xps`)
save_as = xps.launch(HMM, liveplots=False)
# #### Print results
print(xps.tabulate_avrgs())
| 38.6875 | 80 | 0.51567 | ork on Colab.
# %matplotlib notebook
import dapper as dpr
import dapper.da_methods as da
# #### DA method configurations
from dapper.mods.Lorenz63.sakov2012 import HMM # Expected rmse.a:
xps = dpr.xpList()
xps += da.Climatology() # 7.6
xps += da.OptInterp() # 1.25
xps += da.Persistence() # 10.7
xps += da.PreProg(lambda k, xx, yy: xx[k]) # 0
xps += da.Var3D(xB=0.1) # 1.03
xps += da.ExtKF(infl=90) # 0.87
xps += da.EnKF('Sqrt' , N=3 , infl=1.30) # 0.82
xps += da.EnKF('Sqrt' , N=10 , infl=1.02, rot=True) # 0.63
xps += da.EnKF('PertObs', N=500 , infl=0.95, rot=False) # 0.56
xps += da.EnKF_N( N=10 , rot=True) # 0.54
xps += da.iEnKS('Sqrt' , N=10 , infl=1.02, rot=True) # 0.31
xps += da.PartFilt( N=100 , reg=2.4 , NER=0.3) # 0.38
xps += da.PartFilt( N=800 , reg=0.9 , NER=0.2) # 0.28
# xps += da.PartFilt( N=4000, reg=0.7 , NER=0.05) # 0.27
# xps += da.PFxN(xN=1000, N=30 , Qs=2 , NER=0.2) # 0.56
# #### With Lorenz-96 instead
# +
# from dapper.mods.Lorenz96.sakov2008 import HMM # Expected rmse.a:
# xps = dpr.xpList()
# xps += da.Climatology() # 3.6
# xps += da.OptInterp() # 0.95
# xps += da.Var3D(xB=0.02) # 0.41
# xps += da.ExtKF(infl=6) # 0.24
# xps += da.EnKF('PertObs', N=40, infl=1.06) # 0.22
# xps += da.EnKF('Sqrt' , N=28, infl=1.02, rot=True) # 0.18
# # More sophisticated:
# xps += da.EnKF_N( N=24, rot=True) # 0.21
# xps += da.EnKF_N( N=24, rot=True, xN=2) # 0.18
# xps += da.iEnKS('Sqrt' , N=40, infl=1.01, rot=True) # 0.17
# # With localisation:
# xps += da.LETKF( N=7 , infl=1.04, rot=True, loc_rad=4) # 0.22
# xps += da.SL_EAKF( N=7 , infl=1.07, rot=True, loc_rad=6) # 0.23
# -
# #### Other models (suitable xp's listed in HMM files):
HMM.tseq.T = 50
save_as = xps.launch(HMM, liveplots=False)
| true | true |
f72c023c3e475c0e66d6e44d0f104ade3ca2bea0 | 7,867 | py | Python | accelbyte_py_sdk/api/ugc/operations/public_group/get_group.py | AccelByte/accelbyte-python-sdk | dcd311fad111c59da828278975340fb92e0f26f7 | [
"MIT"
] | null | null | null | accelbyte_py_sdk/api/ugc/operations/public_group/get_group.py | AccelByte/accelbyte-python-sdk | dcd311fad111c59da828278975340fb92e0f26f7 | [
"MIT"
] | 1 | 2021-10-13T03:46:58.000Z | 2021-10-13T03:46:58.000Z | accelbyte_py_sdk/api/ugc/operations/public_group/get_group.py | AccelByte/accelbyte-python-sdk | dcd311fad111c59da828278975340fb92e0f26f7 | [
"MIT"
] | null | null | null | # Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# pylint: disable=duplicate-code
# pylint: disable=line-too-long
# pylint: disable=missing-function-docstring
# pylint: disable=missing-module-docstring
# pylint: disable=too-many-arguments
# pylint: disable=too-many-branches
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-lines
# pylint: disable=too-many-locals
# pylint: disable=too-many-public-methods
# pylint: disable=too-many-return-statements
# pylint: disable=too-many-statements
# pylint: disable=unused-import
# justice-ugc-service (2.1.0)
from __future__ import annotations
from typing import Any, Dict, List, Optional, Tuple, Union
from .....core import Operation
from .....core import HeaderStr
from .....core import HttpResponse
from ...models import ModelsCreateGroupResponse
from ...models import ResponseError
class GetGroup(Operation):
"""Get user's groups (GetGroup)
Required permission NAMESPACE:{namespace}:USER:{userId}:CONTENTGROUP [READ].
Required Permission(s):
- NAMESPACE:{namespace}:USER:{userId}:CONTENTGROUP [READ]
Properties:
url: /ugc/v1/public/namespaces/{namespace}/users/{userId}/groups/{groupId}
method: GET
tags: ["Public Group"]
consumes: ["application/json", "application/octet-stream"]
produces: ["application/json"]
securities: [BEARER_AUTH]
group_id: (groupId) REQUIRED str in path
namespace: (namespace) REQUIRED str in path
user_id: (userId) REQUIRED str in path
Responses:
200: OK - ModelsCreateGroupResponse (OK)
401: Unauthorized - ResponseError (Unauthorized)
404: Not Found - ResponseError (Not Found)
500: Internal Server Error - ResponseError (Internal Server Error)
"""
# region fields
_url: str = "/ugc/v1/public/namespaces/{namespace}/users/{userId}/groups/{groupId}"
_method: str = "GET"
_consumes: List[str] = ["application/json", "application/octet-stream"]
_produces: List[str] = ["application/json"]
_securities: List[List[str]] = [["BEARER_AUTH"]]
_location_query: str = None
group_id: str # REQUIRED in [path]
namespace: str # REQUIRED in [path]
user_id: str # REQUIRED in [path]
# endregion fields
# region properties
@property
def url(self) -> str:
return self._url
@property
def method(self) -> str:
return self._method
@property
def consumes(self) -> List[str]:
return self._consumes
@property
def produces(self) -> List[str]:
return self._produces
@property
def securities(self) -> List[List[str]]:
return self._securities
@property
def location_query(self) -> str:
return self._location_query
# endregion properties
# region get methods
# endregion get methods
# region get_x_params methods
def get_all_params(self) -> dict:
return {
"path": self.get_path_params(),
}
def get_path_params(self) -> dict:
result = {}
if hasattr(self, "group_id"):
result["groupId"] = self.group_id
if hasattr(self, "namespace"):
result["namespace"] = self.namespace
if hasattr(self, "user_id"):
result["userId"] = self.user_id
return result
# endregion get_x_params methods
# region is/has methods
# endregion is/has methods
# region with_x methods
def with_group_id(self, value: str) -> GetGroup:
self.group_id = value
return self
def with_namespace(self, value: str) -> GetGroup:
self.namespace = value
return self
def with_user_id(self, value: str) -> GetGroup:
self.user_id = value
return self
# endregion with_x methods
# region to methods
def to_dict(self, include_empty: bool = False) -> dict:
result: dict = {}
if hasattr(self, "group_id") and self.group_id:
result["groupId"] = str(self.group_id)
elif include_empty:
result["groupId"] = ""
if hasattr(self, "namespace") and self.namespace:
result["namespace"] = str(self.namespace)
elif include_empty:
result["namespace"] = ""
if hasattr(self, "user_id") and self.user_id:
result["userId"] = str(self.user_id)
elif include_empty:
result["userId"] = ""
return result
# endregion to methods
# region response methods
# noinspection PyMethodMayBeStatic
def parse_response(self, code: int, content_type: str, content: Any) -> Tuple[Union[None, ModelsCreateGroupResponse], Union[None, HttpResponse, ResponseError]]:
"""Parse the given response.
200: OK - ModelsCreateGroupResponse (OK)
401: Unauthorized - ResponseError (Unauthorized)
404: Not Found - ResponseError (Not Found)
500: Internal Server Error - ResponseError (Internal Server Error)
---: HttpResponse (Undocumented Response)
---: HttpResponse (Unexpected Content-Type Error)
---: HttpResponse (Unhandled Error)
"""
pre_processed_response, error = self.pre_process_response(code=code, content_type=content_type, content=content)
if error is not None:
return None, None if error.is_no_content() else error
code, content_type, content = pre_processed_response
if code == 200:
return ModelsCreateGroupResponse.create_from_dict(content), None
if code == 401:
return None, ResponseError.create_from_dict(content)
if code == 404:
return None, ResponseError.create_from_dict(content)
if code == 500:
return None, ResponseError.create_from_dict(content)
return None, self.handle_undocumented_response(code=code, content_type=content_type, content=content)
# endregion response methods
# region static methods
@classmethod
def create(
cls,
group_id: str,
namespace: str,
user_id: str,
) -> GetGroup:
instance = cls()
instance.group_id = group_id
instance.namespace = namespace
instance.user_id = user_id
return instance
@classmethod
def create_from_dict(cls, dict_: dict, include_empty: bool = False) -> GetGroup:
instance = cls()
if "groupId" in dict_ and dict_["groupId"] is not None:
instance.group_id = str(dict_["groupId"])
elif include_empty:
instance.group_id = ""
if "namespace" in dict_ and dict_["namespace"] is not None:
instance.namespace = str(dict_["namespace"])
elif include_empty:
instance.namespace = ""
if "userId" in dict_ and dict_["userId"] is not None:
instance.user_id = str(dict_["userId"])
elif include_empty:
instance.user_id = ""
return instance
@staticmethod
def get_field_info() -> Dict[str, str]:
return {
"groupId": "group_id",
"namespace": "namespace",
"userId": "user_id",
}
@staticmethod
def get_required_map() -> Dict[str, bool]:
return {
"groupId": True,
"namespace": True,
"userId": True,
}
# endregion static methods
| 29.575188 | 164 | 0.616245 |
from __future__ import annotations
from typing import Any, Dict, List, Optional, Tuple, Union
from .....core import Operation
from .....core import HeaderStr
from .....core import HttpResponse
from ...models import ModelsCreateGroupResponse
from ...models import ResponseError
class GetGroup(Operation):
_url: str = "/ugc/v1/public/namespaces/{namespace}/users/{userId}/groups/{groupId}"
_method: str = "GET"
_consumes: List[str] = ["application/json", "application/octet-stream"]
_produces: List[str] = ["application/json"]
_securities: List[List[str]] = [["BEARER_AUTH"]]
_location_query: str = None
group_id: str
namespace: str
user_id: str
@property
def url(self) -> str:
return self._url
@property
def method(self) -> str:
return self._method
@property
def consumes(self) -> List[str]:
return self._consumes
@property
def produces(self) -> List[str]:
return self._produces
@property
def securities(self) -> List[List[str]]:
return self._securities
@property
def location_query(self) -> str:
return self._location_query
def get_all_params(self) -> dict:
return {
"path": self.get_path_params(),
}
def get_path_params(self) -> dict:
result = {}
if hasattr(self, "group_id"):
result["groupId"] = self.group_id
if hasattr(self, "namespace"):
result["namespace"] = self.namespace
if hasattr(self, "user_id"):
result["userId"] = self.user_id
return result
def with_group_id(self, value: str) -> GetGroup:
self.group_id = value
return self
def with_namespace(self, value: str) -> GetGroup:
self.namespace = value
return self
def with_user_id(self, value: str) -> GetGroup:
self.user_id = value
return self
def to_dict(self, include_empty: bool = False) -> dict:
result: dict = {}
if hasattr(self, "group_id") and self.group_id:
result["groupId"] = str(self.group_id)
elif include_empty:
result["groupId"] = ""
if hasattr(self, "namespace") and self.namespace:
result["namespace"] = str(self.namespace)
elif include_empty:
result["namespace"] = ""
if hasattr(self, "user_id") and self.user_id:
result["userId"] = str(self.user_id)
elif include_empty:
result["userId"] = ""
return result
def parse_response(self, code: int, content_type: str, content: Any) -> Tuple[Union[None, ModelsCreateGroupResponse], Union[None, HttpResponse, ResponseError]]:
pre_processed_response, error = self.pre_process_response(code=code, content_type=content_type, content=content)
if error is not None:
return None, None if error.is_no_content() else error
code, content_type, content = pre_processed_response
if code == 200:
return ModelsCreateGroupResponse.create_from_dict(content), None
if code == 401:
return None, ResponseError.create_from_dict(content)
if code == 404:
return None, ResponseError.create_from_dict(content)
if code == 500:
return None, ResponseError.create_from_dict(content)
return None, self.handle_undocumented_response(code=code, content_type=content_type, content=content)
@classmethod
def create(
cls,
group_id: str,
namespace: str,
user_id: str,
) -> GetGroup:
instance = cls()
instance.group_id = group_id
instance.namespace = namespace
instance.user_id = user_id
return instance
@classmethod
def create_from_dict(cls, dict_: dict, include_empty: bool = False) -> GetGroup:
instance = cls()
if "groupId" in dict_ and dict_["groupId"] is not None:
instance.group_id = str(dict_["groupId"])
elif include_empty:
instance.group_id = ""
if "namespace" in dict_ and dict_["namespace"] is not None:
instance.namespace = str(dict_["namespace"])
elif include_empty:
instance.namespace = ""
if "userId" in dict_ and dict_["userId"] is not None:
instance.user_id = str(dict_["userId"])
elif include_empty:
instance.user_id = ""
return instance
@staticmethod
def get_field_info() -> Dict[str, str]:
return {
"groupId": "group_id",
"namespace": "namespace",
"userId": "user_id",
}
@staticmethod
def get_required_map() -> Dict[str, bool]:
return {
"groupId": True,
"namespace": True,
"userId": True,
}
| true | true |
f72c036616f99189d65b39be5f6f951c9fd19357 | 30,886 | py | Python | tensorflow/contrib/learn/python/learn/estimators/dnn.py | kadeng/tensorflow_project_workspace | dee284fb2d1796329895130a075cd57a62ea873f | [
"Apache-2.0"
] | null | null | null | tensorflow/contrib/learn/python/learn/estimators/dnn.py | kadeng/tensorflow_project_workspace | dee284fb2d1796329895130a075cd57a62ea873f | [
"Apache-2.0"
] | null | null | null | tensorflow/contrib/learn/python/learn/estimators/dnn.py | kadeng/tensorflow_project_workspace | dee284fb2d1796329895130a075cd57a62ea873f | [
"Apache-2.0"
] | null | null | null | # Copyright 2016 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.
# ==============================================================================
"""Deep Neural Network estimators."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from tensorflow.contrib import layers
from tensorflow.contrib.framework import deprecated
from tensorflow.contrib.framework import deprecated_arg_values
from tensorflow.contrib.framework.python.framework import experimental
from tensorflow.contrib.framework.python.ops import variables as contrib_variables
from tensorflow.contrib.layers.python.layers import optimizers
from tensorflow.contrib.learn.python.learn import evaluable
from tensorflow.contrib.learn.python.learn import metric_spec
from tensorflow.contrib.learn.python.learn import monitors as monitor_lib
from tensorflow.contrib.learn.python.learn import trainable
from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined
from tensorflow.contrib.learn.python.learn.estimators import estimator
from tensorflow.contrib.learn.python.learn.estimators import head as head_lib
from tensorflow.contrib.learn.python.learn.estimators import model_fn
from tensorflow.contrib.learn.python.learn.estimators import prediction_key
from tensorflow.contrib.learn.python.learn.utils import export
from tensorflow.python.ops import nn
from tensorflow.python.ops import partitioned_variables
from tensorflow.python.ops import variable_scope
from tensorflow.python.summary import summary
_CENTERED_BIAS_WEIGHT = "centered_bias_weight"
# The default learning rate of 0.05 is a historical artifact of the initial
# implementation, but seems a reasonable choice.
_LEARNING_RATE = 0.05
def _get_feature_dict(features):
if isinstance(features, dict):
return features
return {"": features}
def _get_optimizer(optimizer):
if callable(optimizer):
return optimizer()
else:
return optimizer
def _add_hidden_layer_summary(value, tag):
summary.scalar("%s_fraction_of_zero_values" % tag, nn.zero_fraction(value))
summary.histogram("%s_activation" % tag, value)
def _dnn_model_fn(features, labels, mode, params, config=None):
"""Deep Neural Net model_fn.
Args:
features: `Tensor` or dict of `Tensor` (depends on data passed to `fit`).
labels: `Tensor` of shape [batch_size, 1] or [batch_size] labels of
dtype `int32` or `int64` in the range `[0, n_classes)`.
mode: Defines whether this is training, evaluation or prediction.
See `ModeKeys`.
params: A dict of hyperparameters.
The following hyperparameters are expected:
* head: A `_Head` instance.
* hidden_units: List of hidden units per layer.
* feature_columns: An iterable containing all the feature columns used by
the model.
* optimizer: string, `Optimizer` object, or callable that defines the
optimizer to use for training. If `None`, will use the Adagrad
optimizer with a default learning rate of 0.05.
* activation_fn: Activation function applied to each layer. If `None`,
will use `tf.nn.relu`.
* dropout: When not `None`, the probability we will drop out a given
coordinate.
* gradient_clip_norm: A float > 0. If provided, gradients are
clipped to their global norm with this clipping ratio.
* embedding_lr_multipliers: Optional. A dictionary from
`EmbeddingColumn` to a `float` multiplier. Multiplier will be used to
multiply with learning rate for the embedding variables.
config: `RunConfig` object to configure the runtime settings.
Returns:
predictions: A dict of `Tensor` objects.
loss: A scalar containing the loss of the step.
train_op: The op for training.
"""
head = params["head"]
hidden_units = params["hidden_units"]
feature_columns = params["feature_columns"]
optimizer = params.get("optimizer") or "Adagrad"
activation_fn = params.get("activation_fn")
dropout = params.get("dropout")
gradient_clip_norm = params.get("gradient_clip_norm")
num_ps_replicas = config.num_ps_replicas if config else 0
embedding_lr_multipliers = params.get("embedding_lr_multipliers", {})
features = _get_feature_dict(features)
parent_scope = "dnn"
input_layer_partitioner = (partitioned_variables.min_max_variable_partitioner(
max_partitions=num_ps_replicas, min_slice_size=64 << 20))
input_layer_scope = parent_scope + "/input_from_feature_columns"
with variable_scope.variable_scope(
input_layer_scope,
values=list(six.itervalues(features)),
partitioner=input_layer_partitioner) as scope:
net = layers.input_from_feature_columns(
columns_to_tensors=features,
feature_columns=feature_columns,
weight_collections=[parent_scope],
scope=scope)
hidden_layer_partitioner = (
partitioned_variables.min_max_variable_partitioner(
max_partitions=num_ps_replicas))
for layer_id, num_hidden_units in enumerate(hidden_units):
with variable_scope.variable_scope(
parent_scope + "/hiddenlayer_%d" % layer_id,
values=[net],
partitioner=hidden_layer_partitioner) as scope:
net = layers.fully_connected(
net,
num_hidden_units,
activation_fn=activation_fn,
variables_collections=[parent_scope],
scope=scope)
if dropout is not None and mode == model_fn.ModeKeys.TRAIN:
net = layers.dropout(net, keep_prob=(1.0 - dropout))
_add_hidden_layer_summary(net, scope.name)
with variable_scope.variable_scope(
parent_scope + "/logits",
values=[net],
partitioner=hidden_layer_partitioner) as scope:
logits = layers.fully_connected(
net,
head.logits_dimension,
activation_fn=None,
variables_collections=[parent_scope],
scope=scope)
_add_hidden_layer_summary(logits, scope.name)
def _train_op_fn(loss):
"""Returns the op to optimize the loss."""
return optimizers.optimize_loss(
loss=loss,
global_step=contrib_variables.get_global_step(),
learning_rate=_LEARNING_RATE,
optimizer=_get_optimizer(optimizer),
gradient_multipliers=(
dnn_linear_combined._extract_embedding_lr_multipliers( # pylint: disable=protected-access
embedding_lr_multipliers, parent_scope, input_layer_scope)),
clip_gradients=gradient_clip_norm,
name=parent_scope,
# Empty summaries to prevent optimizers from logging the training_loss.
summaries=[])
return head.head_ops(features, labels, mode, _train_op_fn, logits)
class DNNClassifier(evaluable.Evaluable, trainable.Trainable):
"""A classifier for TensorFlow DNN models.
Example:
```python
sparse_feature_a = sparse_column_with_hash_bucket(...)
sparse_feature_b = sparse_column_with_hash_bucket(...)
sparse_feature_a_emb = embedding_column(sparse_id_column=sparse_feature_a,
...)
sparse_feature_b_emb = embedding_column(sparse_id_column=sparse_feature_b,
...)
estimator = DNNClassifier(
feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb],
hidden_units=[1024, 512, 256])
# Or estimator using the ProximalAdagradOptimizer optimizer with
# regularization.
estimator = DNNClassifier(
feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb],
hidden_units=[1024, 512, 256],
optimizer=tf.train.ProximalAdagradOptimizer(
learning_rate=0.1,
l1_regularization_strength=0.001
))
# Input builders
def input_fn_train: # returns x, y (where y represents label's class index).
pass
estimator.fit(input_fn=input_fn_train)
def input_fn_eval: # returns x, y (where y represents label's class index).
pass
estimator.evaluate(input_fn=input_fn_eval)
estimator.predict(x=x) # returns predicted labels (i.e. label's class index).
```
Input of `fit` and `evaluate` should have following features,
otherwise there will be a `KeyError`:
* if `weight_column_name` is not `None`, a feature with
`key=weight_column_name` whose value is a `Tensor`.
* for each `column` in `feature_columns`:
- if `column` is a `SparseColumn`, a feature with `key=column.name`
whose `value` is a `SparseTensor`.
- if `column` is a `WeightedSparseColumn`, two features: the first with
`key` the id column name, the second with `key` the weight column name.
Both features' `value` must be a `SparseTensor`.
- if `column` is a `RealValuedColumn`, a feature with `key=column.name`
whose `value` is a `Tensor`.
"""
def __init__(self,
hidden_units,
feature_columns,
model_dir=None,
n_classes=2,
weight_column_name=None,
optimizer=None,
activation_fn=nn.relu,
dropout=None,
gradient_clip_norm=None,
enable_centered_bias=False,
config=None,
feature_engineering_fn=None,
embedding_lr_multipliers=None):
"""Initializes a DNNClassifier instance.
Args:
hidden_units: List of hidden units per layer. All layers are fully
connected. Ex. `[64, 32]` means first layer has 64 nodes and second one
has 32.
feature_columns: An iterable containing all the feature columns used by
the model. All items in the set should be instances of classes derived
from `FeatureColumn`.
model_dir: Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into a estimator to
continue training a previously saved model.
n_classes: number of label classes. Default is binary classification.
It must be greater than 1. Note: Class labels are integers representing
the class index (i.e. values from 0 to n_classes-1). For arbitrary
label values (e.g. string labels), convert to class indices first.
weight_column_name: A string defining feature column name representing
weights. It is used to down weight or boost examples during training. It
will be multiplied by the loss of the example.
optimizer: An instance of `tf.Optimizer` used to train the model. If
`None`, will use an Adagrad optimizer.
activation_fn: Activation function applied to each layer. If `None`, will
use `tf.nn.relu`.
dropout: When not `None`, the probability we will drop out a given
coordinate.
gradient_clip_norm: A float > 0. If provided, gradients are
clipped to their global norm with this clipping ratio. See
`tf.clip_by_global_norm` for more details.
enable_centered_bias: A bool. If True, estimator will learn a centered
bias variable for each class. Rest of the model structure learns the
residual after centered bias.
config: `RunConfig` object to configure the runtime settings.
feature_engineering_fn: Feature engineering function. Takes features and
labels which are the output of `input_fn` and
returns features and labels which will be fed
into the model.
embedding_lr_multipliers: Optional. A dictionary from `EmbeddingColumn` to
a `float` multiplier. Multiplier will be used to multiply with
learning rate for the embedding variables.
Returns:
A `DNNClassifier` estimator.
Raises:
ValueError: If `n_classes` < 2.
"""
self._hidden_units = hidden_units
self._feature_columns = tuple(feature_columns or [])
self._enable_centered_bias = enable_centered_bias
self._estimator = estimator.Estimator(
model_fn=_dnn_model_fn,
model_dir=model_dir,
config=config,
params={
"head":
head_lib._multi_class_head( # pylint: disable=protected-access
n_classes,
weight_column_name=weight_column_name,
enable_centered_bias=enable_centered_bias),
"hidden_units":
hidden_units,
"feature_columns":
self._feature_columns,
"optimizer":
optimizer,
"activation_fn":
activation_fn,
"dropout":
dropout,
"gradient_clip_norm":
gradient_clip_norm,
"embedding_lr_multipliers":
embedding_lr_multipliers,
},
feature_engineering_fn=feature_engineering_fn)
def fit(self,
x=None,
y=None,
input_fn=None,
steps=None,
batch_size=None,
monitors=None,
max_steps=None):
"""See trainable.Trainable. Note: Labels must be integer class indices."""
# TODO(roumposg): Remove when deprecated monitors are removed.
hooks = monitor_lib.replace_monitors_with_hooks(monitors, self)
self._estimator.fit(x=x,
y=y,
input_fn=input_fn,
steps=steps,
batch_size=batch_size,
monitors=hooks,
max_steps=max_steps)
return self
def evaluate(self,
x=None,
y=None,
input_fn=None,
feed_fn=None,
batch_size=None,
steps=None,
metrics=None,
name=None,
checkpoint_path=None,
hooks=None):
"""See evaluable.Evaluable. Note: Labels must be integer class indices."""
return self._estimator.evaluate(
x=x,
y=y,
input_fn=input_fn,
feed_fn=feed_fn,
batch_size=batch_size,
steps=steps,
metrics=metrics,
name=name,
checkpoint_path=checkpoint_path,
hooks=hooks)
@deprecated_arg_values(
estimator.AS_ITERABLE_DATE,
estimator.AS_ITERABLE_INSTRUCTIONS,
as_iterable=False)
def predict(self, x=None, input_fn=None, batch_size=None, as_iterable=True):
"""Returns predicted classes for given features.
Args:
x: features.
input_fn: Input function. If set, x must be None.
batch_size: Override default batch size.
as_iterable: If True, return an iterable which keeps yielding predictions
for each example until inputs are exhausted. Note: The inputs must
terminate if you want the iterable to terminate (e.g. be sure to pass
num_epochs=1 if you are using something like read_batch_features).
Returns:
Numpy array of predicted classes with shape [batch_size] (or an iterable
of predicted classes if as_iterable is True). Each predicted class is
represented by its class index (i.e. integer from 0 to n_classes-1).
"""
key = prediction_key.PredictionKey.CLASSES
preds = self._estimator.predict(
x=x,
input_fn=input_fn,
batch_size=batch_size,
outputs=[key],
as_iterable=as_iterable)
if as_iterable:
return (pred[key] for pred in preds)
return preds[key].reshape(-1)
@deprecated_arg_values(
estimator.AS_ITERABLE_DATE,
estimator.AS_ITERABLE_INSTRUCTIONS,
as_iterable=False)
def predict_proba(self,
x=None,
input_fn=None,
batch_size=None,
as_iterable=True):
"""Returns prediction probabilities for given features.
Args:
x: features.
input_fn: Input function. If set, x and y must be None.
batch_size: Override default batch size.
as_iterable: If True, return an iterable which keeps yielding predictions
for each example until inputs are exhausted. Note: The inputs must
terminate if you want the iterable to terminate (e.g. be sure to pass
num_epochs=1 if you are using something like read_batch_features).
Returns:
Numpy array of predicted probabilities with shape [batch_size, n_classes]
(or an iterable of predicted probabilities if as_iterable is True).
"""
key = prediction_key.PredictionKey.PROBABILITIES
preds = self._estimator.predict(
x=x,
input_fn=input_fn,
batch_size=batch_size,
outputs=[key],
as_iterable=as_iterable)
if as_iterable:
return (pred[key] for pred in preds)
return preds[key]
def _get_predict_ops(self, features):
"""See `Estimator` class."""
# This method exists to support some models that use the legacy interface.
# pylint: disable=protected-access
return self._estimator._get_predict_ops(features)
def get_variable_names(self):
"""Returns list of all variable names in this model.
Returns:
List of names.
"""
return self._estimator.get_variable_names()
def get_variable_value(self, name):
"""Returns value of the variable given by name.
Args:
name: string, name of the tensor.
Returns:
`Tensor` object.
"""
return self._estimator.get_variable_value(name)
def export(self,
export_dir,
input_fn=None,
input_feature_key=None,
use_deprecated_input_fn=True,
signature_fn=None,
default_batch_size=1,
exports_to_keep=None):
"""See BaseEstimator.export."""
def default_input_fn(unused_estimator, examples):
return layers.parse_feature_columns_from_examples(examples,
self._feature_columns)
return self._estimator.export(
export_dir=export_dir,
input_fn=input_fn or default_input_fn,
input_feature_key=input_feature_key,
use_deprecated_input_fn=use_deprecated_input_fn,
signature_fn=(signature_fn or
export.classification_signature_fn_with_prob),
prediction_key=prediction_key.PredictionKey.PROBABILITIES,
default_batch_size=default_batch_size,
exports_to_keep=exports_to_keep)
@experimental
def export_savedmodel(self,
export_dir_base,
input_fn,
default_output_alternative_key=None,
assets_extra=None,
as_text=False,
exports_to_keep=None):
return self._estimator.export_savedmodel(
export_dir_base,
input_fn,
default_output_alternative_key=default_output_alternative_key,
assets_extra=assets_extra,
as_text=as_text,
exports_to_keep=exports_to_keep)
@property
def model_dir(self):
return self._estimator.model_dir
@property
@deprecated("2016-10-30",
"This method will be removed after the deprecation date. "
"To inspect variables, use get_variable_names() and "
"get_variable_value().")
def weights_(self):
hiddenlayer_weights = [
self.get_variable_value("dnn/hiddenlayer_%d/weights" % i)
for i, _ in enumerate(self._hidden_units)
]
logits_weights = [self.get_variable_value("dnn/logits/weights")]
return hiddenlayer_weights + logits_weights
@property
@deprecated("2016-10-30",
"This method will be removed after the deprecation date. "
"To inspect variables, use get_variable_names() and "
"get_variable_value().")
def bias_(self):
hiddenlayer_bias = [
self.get_variable_value("dnn/hiddenlayer_%d/biases" % i)
for i, _ in enumerate(self._hidden_units)
]
logits_bias = [self.get_variable_value("dnn/logits/biases")]
if self._enable_centered_bias:
centered_bias = [self.get_variable_value(_CENTERED_BIAS_WEIGHT)]
else:
centered_bias = []
return hiddenlayer_bias + logits_bias + centered_bias
@property
def config(self):
return self._estimator.config
class DNNRegressor(evaluable.Evaluable, trainable.Trainable):
"""A regressor for TensorFlow DNN models.
Example:
```python
sparse_feature_a = sparse_column_with_hash_bucket(...)
sparse_feature_b = sparse_column_with_hash_bucket(...)
sparse_feature_a_emb = embedding_column(sparse_id_column=sparse_feature_a,
...)
sparse_feature_b_emb = embedding_column(sparse_id_column=sparse_feature_b,
...)
estimator = DNNRegressor(
feature_columns=[sparse_feature_a, sparse_feature_b],
hidden_units=[1024, 512, 256])
# Or estimator using the ProximalAdagradOptimizer optimizer with
# regularization.
estimator = DNNRegressor(
feature_columns=[sparse_feature_a, sparse_feature_b],
hidden_units=[1024, 512, 256],
optimizer=tf.train.ProximalAdagradOptimizer(
learning_rate=0.1,
l1_regularization_strength=0.001
))
# Input builders
def input_fn_train: # returns x, y
pass
estimator.fit(input_fn=input_fn_train)
def input_fn_eval: # returns x, y
pass
estimator.evaluate(input_fn=input_fn_eval)
estimator.predict(x=x)
```
Input of `fit` and `evaluate` should have following features,
otherwise there will be a `KeyError`:
* if `weight_column_name` is not `None`, a feature with
`key=weight_column_name` whose value is a `Tensor`.
* for each `column` in `feature_columns`:
- if `column` is a `SparseColumn`, a feature with `key=column.name`
whose `value` is a `SparseTensor`.
- if `column` is a `WeightedSparseColumn`, two features: the first with
`key` the id column name, the second with `key` the weight column name.
Both features' `value` must be a `SparseTensor`.
- if `column` is a `RealValuedColumn`, a feature with `key=column.name`
whose `value` is a `Tensor`.
"""
def __init__(self,
hidden_units,
feature_columns,
model_dir=None,
weight_column_name=None,
optimizer=None,
activation_fn=nn.relu,
dropout=None,
gradient_clip_norm=None,
enable_centered_bias=False,
config=None,
feature_engineering_fn=None,
label_dimension=1,
embedding_lr_multipliers=None):
"""Initializes a `DNNRegressor` instance.
Args:
hidden_units: List of hidden units per layer. All layers are fully
connected. Ex. `[64, 32]` means first layer has 64 nodes and second one
has 32.
feature_columns: An iterable containing all the feature columns used by
the model. All items in the set should be instances of classes derived
from `FeatureColumn`.
model_dir: Directory to save model parameters, graph and etc. This can
also be used to load checkpoints from the directory into a estimator to
continue training a previously saved model.
weight_column_name: A string defining feature column name representing
weights. It is used to down weight or boost examples during training. It
will be multiplied by the loss of the example.
optimizer: An instance of `tf.Optimizer` used to train the model. If
`None`, will use an Adagrad optimizer.
activation_fn: Activation function applied to each layer. If `None`, will
use `tf.nn.relu`.
dropout: When not `None`, the probability we will drop out a given
coordinate.
gradient_clip_norm: A `float` > 0. If provided, gradients are clipped
to their global norm with this clipping ratio. See
`tf.clip_by_global_norm` for more details.
enable_centered_bias: A bool. If True, estimator will learn a centered
bias variable for each class. Rest of the model structure learns the
residual after centered bias.
config: `RunConfig` object to configure the runtime settings.
feature_engineering_fn: Feature engineering function. Takes features and
labels which are the output of `input_fn` and
returns features and labels which will be fed
into the model.
label_dimension: Dimension of the label for multilabels. Defaults to 1.
embedding_lr_multipliers: Optional. A dictionary from `EbeddingColumn` to
a `float` multiplier. Multiplier will be used to multiply with
learning rate for the embedding variables.
Returns:
A `DNNRegressor` estimator.
"""
self._feature_columns = tuple(feature_columns or [])
self._estimator = estimator.Estimator(
model_fn=_dnn_model_fn,
model_dir=model_dir,
config=config,
params={
"head":
head_lib._regression_head( # pylint: disable=protected-access
label_dimension=label_dimension,
weight_column_name=weight_column_name,
enable_centered_bias=enable_centered_bias),
"hidden_units":
hidden_units,
"feature_columns":
self._feature_columns,
"optimizer":
optimizer,
"activation_fn":
activation_fn,
"dropout":
dropout,
"gradient_clip_norm":
gradient_clip_norm,
"embedding_lr_multipliers":
embedding_lr_multipliers,
},
feature_engineering_fn=feature_engineering_fn)
def fit(self,
x=None,
y=None,
input_fn=None,
steps=None,
batch_size=None,
monitors=None,
max_steps=None):
"""See trainable.Trainable."""
# TODO(roumposg): Remove when deprecated monitors are removed.
hooks = monitor_lib.replace_monitors_with_hooks(monitors, self)
self._estimator.fit(x=x,
y=y,
input_fn=input_fn,
steps=steps,
batch_size=batch_size,
monitors=hooks,
max_steps=max_steps)
return self
def evaluate(self,
x=None,
y=None,
input_fn=None,
feed_fn=None,
batch_size=None,
steps=None,
metrics=None,
name=None,
checkpoint_path=None,
hooks=None):
"""See evaluable.Evaluable."""
# TODO(zakaria): remove once deprecation is finished (b/31229024)
custom_metrics = {}
if metrics:
for key, metric in six.iteritems(metrics):
if (not isinstance(metric, metric_spec.MetricSpec) and
not isinstance(key, tuple)):
custom_metrics[(key, prediction_key.PredictionKey.SCORES)] = metric
else:
custom_metrics[key] = metric
return self._estimator.evaluate(
x=x,
y=y,
input_fn=input_fn,
feed_fn=feed_fn,
batch_size=batch_size,
steps=steps,
metrics=custom_metrics,
name=name,
checkpoint_path=checkpoint_path,
hooks=hooks)
@deprecated_arg_values(
estimator.AS_ITERABLE_DATE,
estimator.AS_ITERABLE_INSTRUCTIONS,
as_iterable=False)
def predict(self, x=None, input_fn=None, batch_size=None, as_iterable=True):
"""Returns predicted scores for given features.
Args:
x: features.
input_fn: Input function. If set, x must be None.
batch_size: Override default batch size.
as_iterable: If True, return an iterable which keeps yielding predictions
for each example until inputs are exhausted. Note: The inputs must
terminate if you want the iterable to terminate (e.g. be sure to pass
num_epochs=1 if you are using something like read_batch_features).
Returns:
Numpy array of predicted scores (or an iterable of predicted scores if
as_iterable is True). If `label_dimension == 1`, the shape of the output
is `[batch_size]`, otherwise the shape is `[batch_size, label_dimension]`.
"""
key = prediction_key.PredictionKey.SCORES
preds = self._estimator.predict(
x=x,
input_fn=input_fn,
batch_size=batch_size,
outputs=[key],
as_iterable=as_iterable)
if as_iterable:
return (pred[key] for pred in preds)
return preds[key]
def _get_predict_ops(self, features):
"""See `Estimator` class."""
# This method exists to support some models that use the legacy interface.
# pylint: disable=protected-access
return self._estimator._get_predict_ops(features)
def get_variable_names(self):
"""Returns list of all variable names in this model.
Returns:
List of names.
"""
return self._estimator.get_variable_names()
def get_variable_value(self, name):
"""Returns value of the variable given by name.
Args:
name: string, name of the tensor.
Returns:
`Tensor` object.
"""
return self._estimator.get_variable_value(name)
def export(self,
export_dir,
input_fn=None,
input_feature_key=None,
use_deprecated_input_fn=True,
signature_fn=None,
default_batch_size=1,
exports_to_keep=None):
"""See BaseEstimator.export."""
def default_input_fn(unused_estimator, examples):
return layers.parse_feature_columns_from_examples(examples,
self._feature_columns)
return self._estimator.export(
export_dir=export_dir,
input_fn=input_fn or default_input_fn,
input_feature_key=input_feature_key,
use_deprecated_input_fn=use_deprecated_input_fn,
signature_fn=signature_fn or export.regression_signature_fn,
prediction_key=prediction_key.PredictionKey.SCORES,
default_batch_size=default_batch_size,
exports_to_keep=exports_to_keep)
@property
def model_dir(self):
return self._estimator.model_dir
@property
def config(self):
return self._estimator.config
| 37.896933 | 102 | 0.662015 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from tensorflow.contrib import layers
from tensorflow.contrib.framework import deprecated
from tensorflow.contrib.framework import deprecated_arg_values
from tensorflow.contrib.framework.python.framework import experimental
from tensorflow.contrib.framework.python.ops import variables as contrib_variables
from tensorflow.contrib.layers.python.layers import optimizers
from tensorflow.contrib.learn.python.learn import evaluable
from tensorflow.contrib.learn.python.learn import metric_spec
from tensorflow.contrib.learn.python.learn import monitors as monitor_lib
from tensorflow.contrib.learn.python.learn import trainable
from tensorflow.contrib.learn.python.learn.estimators import dnn_linear_combined
from tensorflow.contrib.learn.python.learn.estimators import estimator
from tensorflow.contrib.learn.python.learn.estimators import head as head_lib
from tensorflow.contrib.learn.python.learn.estimators import model_fn
from tensorflow.contrib.learn.python.learn.estimators import prediction_key
from tensorflow.contrib.learn.python.learn.utils import export
from tensorflow.python.ops import nn
from tensorflow.python.ops import partitioned_variables
from tensorflow.python.ops import variable_scope
from tensorflow.python.summary import summary
_CENTERED_BIAS_WEIGHT = "centered_bias_weight"
_LEARNING_RATE = 0.05
def _get_feature_dict(features):
if isinstance(features, dict):
return features
return {"": features}
def _get_optimizer(optimizer):
if callable(optimizer):
return optimizer()
else:
return optimizer
def _add_hidden_layer_summary(value, tag):
summary.scalar("%s_fraction_of_zero_values" % tag, nn.zero_fraction(value))
summary.histogram("%s_activation" % tag, value)
def _dnn_model_fn(features, labels, mode, params, config=None):
head = params["head"]
hidden_units = params["hidden_units"]
feature_columns = params["feature_columns"]
optimizer = params.get("optimizer") or "Adagrad"
activation_fn = params.get("activation_fn")
dropout = params.get("dropout")
gradient_clip_norm = params.get("gradient_clip_norm")
num_ps_replicas = config.num_ps_replicas if config else 0
embedding_lr_multipliers = params.get("embedding_lr_multipliers", {})
features = _get_feature_dict(features)
parent_scope = "dnn"
input_layer_partitioner = (partitioned_variables.min_max_variable_partitioner(
max_partitions=num_ps_replicas, min_slice_size=64 << 20))
input_layer_scope = parent_scope + "/input_from_feature_columns"
with variable_scope.variable_scope(
input_layer_scope,
values=list(six.itervalues(features)),
partitioner=input_layer_partitioner) as scope:
net = layers.input_from_feature_columns(
columns_to_tensors=features,
feature_columns=feature_columns,
weight_collections=[parent_scope],
scope=scope)
hidden_layer_partitioner = (
partitioned_variables.min_max_variable_partitioner(
max_partitions=num_ps_replicas))
for layer_id, num_hidden_units in enumerate(hidden_units):
with variable_scope.variable_scope(
parent_scope + "/hiddenlayer_%d" % layer_id,
values=[net],
partitioner=hidden_layer_partitioner) as scope:
net = layers.fully_connected(
net,
num_hidden_units,
activation_fn=activation_fn,
variables_collections=[parent_scope],
scope=scope)
if dropout is not None and mode == model_fn.ModeKeys.TRAIN:
net = layers.dropout(net, keep_prob=(1.0 - dropout))
_add_hidden_layer_summary(net, scope.name)
with variable_scope.variable_scope(
parent_scope + "/logits",
values=[net],
partitioner=hidden_layer_partitioner) as scope:
logits = layers.fully_connected(
net,
head.logits_dimension,
activation_fn=None,
variables_collections=[parent_scope],
scope=scope)
_add_hidden_layer_summary(logits, scope.name)
def _train_op_fn(loss):
return optimizers.optimize_loss(
loss=loss,
global_step=contrib_variables.get_global_step(),
learning_rate=_LEARNING_RATE,
optimizer=_get_optimizer(optimizer),
gradient_multipliers=(
dnn_linear_combined._extract_embedding_lr_multipliers(
embedding_lr_multipliers, parent_scope, input_layer_scope)),
clip_gradients=gradient_clip_norm,
name=parent_scope,
summaries=[])
return head.head_ops(features, labels, mode, _train_op_fn, logits)
class DNNClassifier(evaluable.Evaluable, trainable.Trainable):
def __init__(self,
hidden_units,
feature_columns,
model_dir=None,
n_classes=2,
weight_column_name=None,
optimizer=None,
activation_fn=nn.relu,
dropout=None,
gradient_clip_norm=None,
enable_centered_bias=False,
config=None,
feature_engineering_fn=None,
embedding_lr_multipliers=None):
self._hidden_units = hidden_units
self._feature_columns = tuple(feature_columns or [])
self._enable_centered_bias = enable_centered_bias
self._estimator = estimator.Estimator(
model_fn=_dnn_model_fn,
model_dir=model_dir,
config=config,
params={
"head":
head_lib._multi_class_head(
n_classes,
weight_column_name=weight_column_name,
enable_centered_bias=enable_centered_bias),
"hidden_units":
hidden_units,
"feature_columns":
self._feature_columns,
"optimizer":
optimizer,
"activation_fn":
activation_fn,
"dropout":
dropout,
"gradient_clip_norm":
gradient_clip_norm,
"embedding_lr_multipliers":
embedding_lr_multipliers,
},
feature_engineering_fn=feature_engineering_fn)
def fit(self,
x=None,
y=None,
input_fn=None,
steps=None,
batch_size=None,
monitors=None,
max_steps=None):
hooks = monitor_lib.replace_monitors_with_hooks(monitors, self)
self._estimator.fit(x=x,
y=y,
input_fn=input_fn,
steps=steps,
batch_size=batch_size,
monitors=hooks,
max_steps=max_steps)
return self
def evaluate(self,
x=None,
y=None,
input_fn=None,
feed_fn=None,
batch_size=None,
steps=None,
metrics=None,
name=None,
checkpoint_path=None,
hooks=None):
return self._estimator.evaluate(
x=x,
y=y,
input_fn=input_fn,
feed_fn=feed_fn,
batch_size=batch_size,
steps=steps,
metrics=metrics,
name=name,
checkpoint_path=checkpoint_path,
hooks=hooks)
@deprecated_arg_values(
estimator.AS_ITERABLE_DATE,
estimator.AS_ITERABLE_INSTRUCTIONS,
as_iterable=False)
def predict(self, x=None, input_fn=None, batch_size=None, as_iterable=True):
key = prediction_key.PredictionKey.CLASSES
preds = self._estimator.predict(
x=x,
input_fn=input_fn,
batch_size=batch_size,
outputs=[key],
as_iterable=as_iterable)
if as_iterable:
return (pred[key] for pred in preds)
return preds[key].reshape(-1)
@deprecated_arg_values(
estimator.AS_ITERABLE_DATE,
estimator.AS_ITERABLE_INSTRUCTIONS,
as_iterable=False)
def predict_proba(self,
x=None,
input_fn=None,
batch_size=None,
as_iterable=True):
key = prediction_key.PredictionKey.PROBABILITIES
preds = self._estimator.predict(
x=x,
input_fn=input_fn,
batch_size=batch_size,
outputs=[key],
as_iterable=as_iterable)
if as_iterable:
return (pred[key] for pred in preds)
return preds[key]
def _get_predict_ops(self, features):
return self._estimator._get_predict_ops(features)
def get_variable_names(self):
return self._estimator.get_variable_names()
def get_variable_value(self, name):
return self._estimator.get_variable_value(name)
def export(self,
export_dir,
input_fn=None,
input_feature_key=None,
use_deprecated_input_fn=True,
signature_fn=None,
default_batch_size=1,
exports_to_keep=None):
def default_input_fn(unused_estimator, examples):
return layers.parse_feature_columns_from_examples(examples,
self._feature_columns)
return self._estimator.export(
export_dir=export_dir,
input_fn=input_fn or default_input_fn,
input_feature_key=input_feature_key,
use_deprecated_input_fn=use_deprecated_input_fn,
signature_fn=(signature_fn or
export.classification_signature_fn_with_prob),
prediction_key=prediction_key.PredictionKey.PROBABILITIES,
default_batch_size=default_batch_size,
exports_to_keep=exports_to_keep)
@experimental
def export_savedmodel(self,
export_dir_base,
input_fn,
default_output_alternative_key=None,
assets_extra=None,
as_text=False,
exports_to_keep=None):
return self._estimator.export_savedmodel(
export_dir_base,
input_fn,
default_output_alternative_key=default_output_alternative_key,
assets_extra=assets_extra,
as_text=as_text,
exports_to_keep=exports_to_keep)
@property
def model_dir(self):
return self._estimator.model_dir
@property
@deprecated("2016-10-30",
"This method will be removed after the deprecation date. "
"To inspect variables, use get_variable_names() and "
"get_variable_value().")
def weights_(self):
hiddenlayer_weights = [
self.get_variable_value("dnn/hiddenlayer_%d/weights" % i)
for i, _ in enumerate(self._hidden_units)
]
logits_weights = [self.get_variable_value("dnn/logits/weights")]
return hiddenlayer_weights + logits_weights
@property
@deprecated("2016-10-30",
"This method will be removed after the deprecation date. "
"To inspect variables, use get_variable_names() and "
"get_variable_value().")
def bias_(self):
hiddenlayer_bias = [
self.get_variable_value("dnn/hiddenlayer_%d/biases" % i)
for i, _ in enumerate(self._hidden_units)
]
logits_bias = [self.get_variable_value("dnn/logits/biases")]
if self._enable_centered_bias:
centered_bias = [self.get_variable_value(_CENTERED_BIAS_WEIGHT)]
else:
centered_bias = []
return hiddenlayer_bias + logits_bias + centered_bias
@property
def config(self):
return self._estimator.config
class DNNRegressor(evaluable.Evaluable, trainable.Trainable):
def __init__(self,
hidden_units,
feature_columns,
model_dir=None,
weight_column_name=None,
optimizer=None,
activation_fn=nn.relu,
dropout=None,
gradient_clip_norm=None,
enable_centered_bias=False,
config=None,
feature_engineering_fn=None,
label_dimension=1,
embedding_lr_multipliers=None):
self._feature_columns = tuple(feature_columns or [])
self._estimator = estimator.Estimator(
model_fn=_dnn_model_fn,
model_dir=model_dir,
config=config,
params={
"head":
head_lib._regression_head(
label_dimension=label_dimension,
weight_column_name=weight_column_name,
enable_centered_bias=enable_centered_bias),
"hidden_units":
hidden_units,
"feature_columns":
self._feature_columns,
"optimizer":
optimizer,
"activation_fn":
activation_fn,
"dropout":
dropout,
"gradient_clip_norm":
gradient_clip_norm,
"embedding_lr_multipliers":
embedding_lr_multipliers,
},
feature_engineering_fn=feature_engineering_fn)
def fit(self,
x=None,
y=None,
input_fn=None,
steps=None,
batch_size=None,
monitors=None,
max_steps=None):
hooks = monitor_lib.replace_monitors_with_hooks(monitors, self)
self._estimator.fit(x=x,
y=y,
input_fn=input_fn,
steps=steps,
batch_size=batch_size,
monitors=hooks,
max_steps=max_steps)
return self
def evaluate(self,
x=None,
y=None,
input_fn=None,
feed_fn=None,
batch_size=None,
steps=None,
metrics=None,
name=None,
checkpoint_path=None,
hooks=None):
custom_metrics = {}
if metrics:
for key, metric in six.iteritems(metrics):
if (not isinstance(metric, metric_spec.MetricSpec) and
not isinstance(key, tuple)):
custom_metrics[(key, prediction_key.PredictionKey.SCORES)] = metric
else:
custom_metrics[key] = metric
return self._estimator.evaluate(
x=x,
y=y,
input_fn=input_fn,
feed_fn=feed_fn,
batch_size=batch_size,
steps=steps,
metrics=custom_metrics,
name=name,
checkpoint_path=checkpoint_path,
hooks=hooks)
@deprecated_arg_values(
estimator.AS_ITERABLE_DATE,
estimator.AS_ITERABLE_INSTRUCTIONS,
as_iterable=False)
def predict(self, x=None, input_fn=None, batch_size=None, as_iterable=True):
key = prediction_key.PredictionKey.SCORES
preds = self._estimator.predict(
x=x,
input_fn=input_fn,
batch_size=batch_size,
outputs=[key],
as_iterable=as_iterable)
if as_iterable:
return (pred[key] for pred in preds)
return preds[key]
def _get_predict_ops(self, features):
return self._estimator._get_predict_ops(features)
def get_variable_names(self):
return self._estimator.get_variable_names()
def get_variable_value(self, name):
return self._estimator.get_variable_value(name)
def export(self,
export_dir,
input_fn=None,
input_feature_key=None,
use_deprecated_input_fn=True,
signature_fn=None,
default_batch_size=1,
exports_to_keep=None):
def default_input_fn(unused_estimator, examples):
return layers.parse_feature_columns_from_examples(examples,
self._feature_columns)
return self._estimator.export(
export_dir=export_dir,
input_fn=input_fn or default_input_fn,
input_feature_key=input_feature_key,
use_deprecated_input_fn=use_deprecated_input_fn,
signature_fn=signature_fn or export.regression_signature_fn,
prediction_key=prediction_key.PredictionKey.SCORES,
default_batch_size=default_batch_size,
exports_to_keep=exports_to_keep)
@property
def model_dir(self):
return self._estimator.model_dir
@property
def config(self):
return self._estimator.config
| true | true |
f72c0438b220afbd9e2368f18d00c300ac52ab61 | 8,977 | py | Python | precision_search/model/TEMPONet_float.py | EmbeddedML-EDAGroup/Q-PPG | ed42829d0a456db4f0b31d63ba8b22ba483c7b08 | [
"Apache-2.0"
] | 1 | 2021-12-18T21:04:29.000Z | 2021-12-18T21:04:29.000Z | precision_search/model/TEMPONet_float.py | EmbeddedML-EDAGroup/Q-PPG | ed42829d0a456db4f0b31d63ba8b22ba483c7b08 | [
"Apache-2.0"
] | null | null | null | precision_search/model/TEMPONet_float.py | EmbeddedML-EDAGroup/Q-PPG | ed42829d0a456db4f0b31d63ba8b22ba483c7b08 | [
"Apache-2.0"
] | null | null | null | #*----------------------------------------------------------------------------*
#* Copyright (C) 2021 Politecnico di Torino, Italy *
#* SPDX-License-Identifier: Apache-2.0 *
#* *
#* Licensed under the Apache License, Version 2.0 (the "License"); *
#* you may not use this file except in compliance with the License. *
#* You may obtain a copy of the License at *
#* *
#* http://www.apache.org/licenses/LICENSE-2.0 *
#* *
#* Unless required by applicable law or agreed to in writing, software *
#* distributed under the License is distributed on an "AS IS" BASIS, *
#* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
#* See the License for the specific language governing permissions and *
#* limitations under the License. *
#* *
#* Author: Alessio Burrello *
#*----------------------------------------------------------------------------*
import torch.nn as nn
import torch.nn.functional as F
from base import BaseModel
from math import ceil
import sys
sys.path.append("..")
from models import quant_module_1d as qm
__all__ = ['TempoNetfloat']
def TempoNetfloat(**kwargs):
return TEMPONet(**kwargs)
class TEMPONet(BaseModel):
"""
TEMPONet architecture:
Three repeated instances of TemporalConvBlock and ConvBlock organized as follows:
- TemporalConvBlock
- ConvBlock
Two instances of Regressor followed by a final Linear layer with a single neuron.
"""
def __init__(self, dataset_name='PPG_Dalia', dataset_args={}):
super(TEMPONet, self).__init__()
self.dil = [
2, 2, 1,
4, 4,
8, 8
]
self.rf = [
5, 5, 5,
9, 9,
17, 17
]
self.ch = [
32, 32, 64,
64, 64, 128,
128, 128, 128,
256, 128
]
# 1st instance of two TempConvBlocks and ConvBlock
k_tcb00 = ceil(self.rf[0] / self.dil[0])
self.tcb00 = TempConvBlock(
ch_in=4,
ch_out=self.ch[0],
k_size=k_tcb00,
dil=self.dil[0],
pad=((k_tcb00 - 1) * self.dil[0] + 1) // 2
)
k_tcb01 = ceil(self.rf[1] / self.dil[1])
self.tcb01 = TempConvBlock(
ch_in=self.ch[0],
ch_out=self.ch[1],
k_size=k_tcb01,
dil=self.dil[1],
pad=((k_tcb01 - 1) * self.dil[1] + 1) // 2
)
k_cb0 = ceil(self.rf[2] / self.dil[2])
self.cb0 = ConvBlock(
ch_in=self.ch[1],
ch_out=self.ch[2],
k_size=k_cb0,
strd=1,
pad=((k_cb0 - 1) * self.dil[2] + 1) // 2,
dilation=self.dil[2]
)
# 2nd instance of two TempConvBlocks and ConvBlock
k_tcb10 = ceil(self.rf[3] / self.dil[3])
self.tcb10 = TempConvBlock(
ch_in=self.ch[2],
ch_out=self.ch[3],
k_size=k_tcb10,
dil=self.dil[3],
pad=((k_tcb10 - 1) * self.dil[3] + 1) // 2
)
k_tcb11 = ceil(self.rf[4] / self.dil[4])
self.tcb11 = TempConvBlock(
ch_in=self.ch[3],
ch_out=self.ch[4],
k_size=k_tcb11,
dil=self.dil[4],
pad=((k_tcb11 - 1) * self.dil[4] + 1) // 2
)
self.cb1 = ConvBlock(
ch_in=self.ch[4],
ch_out=self.ch[5],
k_size=5,
strd=2,
pad=2
)
# 3td instance of TempConvBlock and ConvBlock
k_tcb20 = ceil(self.rf[5] / self.dil[5])
self.tcb20 = TempConvBlock(
ch_in=self.ch[5],
ch_out=self.ch[6],
k_size=k_tcb20,
dil=self.dil[5],
pad=((k_tcb20 - 1) * self.dil[5] + 1) // 2
)
k_tcb21 = ceil(self.rf[6] / self.dil[6])
self.tcb21 = TempConvBlock(
ch_in=self.ch[6],
ch_out=self.ch[7],
k_size=k_tcb21,
dil=self.dil[6],
pad=((k_tcb21 - 1) * self.dil[6] + 1) // 2
)
self.cb2 = ConvBlock(
ch_in=self.ch[7],
ch_out=self.ch[8],
k_size=5,
strd=4,
pad=4
)
# 1st instance of regressor
self.regr0 = Regressor(
ft_in=self.ch[8] * 4,
ft_out=self.ch[9]
)
# 2nd instance of regressor
self.regr1 = Regressor(
ft_in=self.ch[9],
ft_out=self.ch[10]
)
self.out_neuron = nn.Linear(
in_features=self.ch[10],
out_features=1
)
def forward(self, x):
x = self.cb0(
self.tcb01(
self.tcb00(
x
)
)
)
x = self.cb1(
self.tcb11(
self.tcb10(
x
)
)
)
x = self.cb2(
self.tcb21(
self.tcb20(
x
)
)
)
x = x.flatten(1)
x = self.regr0(
x
)
x = self.regr1(
x
)
x = self.out_neuron(
x
)
return x
class TempConvBlock(BaseModel):
"""
Temporal Convolutional Block composed of one temporal convolutional layers.
The block is composed of :
- Conv1d layer
- Chomp1d layer
- ReLU layer
- BatchNorm1d layer
:param ch_in: Number of input channels
:param ch_out: Number of output channels
:param k_size: Kernel size
:param dil: Amount of dilation
:param pad: Amount of padding
"""
def __init__(self, ch_in, ch_out, k_size, dil, pad):
super(TempConvBlock, self).__init__()
self.tcn0 = nn.Conv1d(
in_channels=ch_in,
out_channels=ch_out,
kernel_size=k_size,
dilation=dil,
bias = False,
padding=pad
)
self.relu0 = nn.ReLU6()
self.bn0 = nn.BatchNorm1d(
num_features=ch_out
)
def forward(self, x):
x = self.relu0(self.bn0(self.tcn0(x)))
return x
class ConvBlock(BaseModel):
"""
Convolutional Block composed of:
- Conv1d layer
- AvgPool1d layer
- ReLU layer
- BatchNorm1d layer
:param ch_in: Number of input channels
:param ch_out: Number of output channels
:param k_size: Kernel size
:param strd: Amount of stride
:param pad: Amount of padding
"""
def __init__(self, ch_in, ch_out, k_size, strd, pad, dilation=1):
super(ConvBlock, self).__init__()
self.conv0 = nn.Conv1d(
in_channels=ch_in,
out_channels=ch_out,
kernel_size=k_size,
stride=strd,
dilation=dilation,
bias = False,
padding=pad
)
self.pool0 = nn.AvgPool1d(
kernel_size=2,
stride=2,
padding=0
)
self.relu0 = nn.ReLU6()
self.bn0 = nn.BatchNorm1d(ch_out)
def forward(self, x):
x = self.relu0(self.bn0(self.pool0(self.conv0(x))))
return x
class Regressor(BaseModel):
"""
Regressor block composed of :
- Linear layer
- ReLU layer
- BatchNorm1d layer
:param ft_in: Number of input channels
:param ft_out: Number of output channels
"""
def __init__(self, ft_in, ft_out):
super(Regressor, self).__init__()
self.ft_in = ft_in
self.ft_out = ft_out
self.fc0 = nn.Linear(
in_features=ft_in,
out_features=ft_out,
bias = False
)
self.relu0 = nn.ReLU6()
self.bn0 = nn.BatchNorm1d(
num_features=ft_out
)
def forward(self, x):
x = self.relu0(self.bn0(self.fc0(x)))
return x
class Chomp1d(BaseModel):
"""
Module that perform a chomping operation on the input tensor.
It is used to chomp the amount of zero-padding added on the right of the input tensor, this operation is necessary to compute causal convolutions.
:param chomp_size: amount of padding 0s to be removed
"""
def __init__(self, chomp_size):
super(Chomp1d, self).__init__()
self.chomp_size = chomp_size
def forward(self, x):
return x[:, :, :-self.chomp_size].contiguous()
| 28.22956 | 150 | 0.479782 |
import torch.nn as nn
import torch.nn.functional as F
from base import BaseModel
from math import ceil
import sys
sys.path.append("..")
from models import quant_module_1d as qm
__all__ = ['TempoNetfloat']
def TempoNetfloat(**kwargs):
return TEMPONet(**kwargs)
class TEMPONet(BaseModel):
def __init__(self, dataset_name='PPG_Dalia', dataset_args={}):
super(TEMPONet, self).__init__()
self.dil = [
2, 2, 1,
4, 4,
8, 8
]
self.rf = [
5, 5, 5,
9, 9,
17, 17
]
self.ch = [
32, 32, 64,
64, 64, 128,
128, 128, 128,
256, 128
]
k_tcb00 = ceil(self.rf[0] / self.dil[0])
self.tcb00 = TempConvBlock(
ch_in=4,
ch_out=self.ch[0],
k_size=k_tcb00,
dil=self.dil[0],
pad=((k_tcb00 - 1) * self.dil[0] + 1) // 2
)
k_tcb01 = ceil(self.rf[1] / self.dil[1])
self.tcb01 = TempConvBlock(
ch_in=self.ch[0],
ch_out=self.ch[1],
k_size=k_tcb01,
dil=self.dil[1],
pad=((k_tcb01 - 1) * self.dil[1] + 1) // 2
)
k_cb0 = ceil(self.rf[2] / self.dil[2])
self.cb0 = ConvBlock(
ch_in=self.ch[1],
ch_out=self.ch[2],
k_size=k_cb0,
strd=1,
pad=((k_cb0 - 1) * self.dil[2] + 1) // 2,
dilation=self.dil[2]
)
k_tcb10 = ceil(self.rf[3] / self.dil[3])
self.tcb10 = TempConvBlock(
ch_in=self.ch[2],
ch_out=self.ch[3],
k_size=k_tcb10,
dil=self.dil[3],
pad=((k_tcb10 - 1) * self.dil[3] + 1) // 2
)
k_tcb11 = ceil(self.rf[4] / self.dil[4])
self.tcb11 = TempConvBlock(
ch_in=self.ch[3],
ch_out=self.ch[4],
k_size=k_tcb11,
dil=self.dil[4],
pad=((k_tcb11 - 1) * self.dil[4] + 1) // 2
)
self.cb1 = ConvBlock(
ch_in=self.ch[4],
ch_out=self.ch[5],
k_size=5,
strd=2,
pad=2
)
k_tcb20 = ceil(self.rf[5] / self.dil[5])
self.tcb20 = TempConvBlock(
ch_in=self.ch[5],
ch_out=self.ch[6],
k_size=k_tcb20,
dil=self.dil[5],
pad=((k_tcb20 - 1) * self.dil[5] + 1) // 2
)
k_tcb21 = ceil(self.rf[6] / self.dil[6])
self.tcb21 = TempConvBlock(
ch_in=self.ch[6],
ch_out=self.ch[7],
k_size=k_tcb21,
dil=self.dil[6],
pad=((k_tcb21 - 1) * self.dil[6] + 1) // 2
)
self.cb2 = ConvBlock(
ch_in=self.ch[7],
ch_out=self.ch[8],
k_size=5,
strd=4,
pad=4
)
self.regr0 = Regressor(
ft_in=self.ch[8] * 4,
ft_out=self.ch[9]
)
self.regr1 = Regressor(
ft_in=self.ch[9],
ft_out=self.ch[10]
)
self.out_neuron = nn.Linear(
in_features=self.ch[10],
out_features=1
)
def forward(self, x):
x = self.cb0(
self.tcb01(
self.tcb00(
x
)
)
)
x = self.cb1(
self.tcb11(
self.tcb10(
x
)
)
)
x = self.cb2(
self.tcb21(
self.tcb20(
x
)
)
)
x = x.flatten(1)
x = self.regr0(
x
)
x = self.regr1(
x
)
x = self.out_neuron(
x
)
return x
class TempConvBlock(BaseModel):
def __init__(self, ch_in, ch_out, k_size, dil, pad):
super(TempConvBlock, self).__init__()
self.tcn0 = nn.Conv1d(
in_channels=ch_in,
out_channels=ch_out,
kernel_size=k_size,
dilation=dil,
bias = False,
padding=pad
)
self.relu0 = nn.ReLU6()
self.bn0 = nn.BatchNorm1d(
num_features=ch_out
)
def forward(self, x):
x = self.relu0(self.bn0(self.tcn0(x)))
return x
class ConvBlock(BaseModel):
def __init__(self, ch_in, ch_out, k_size, strd, pad, dilation=1):
super(ConvBlock, self).__init__()
self.conv0 = nn.Conv1d(
in_channels=ch_in,
out_channels=ch_out,
kernel_size=k_size,
stride=strd,
dilation=dilation,
bias = False,
padding=pad
)
self.pool0 = nn.AvgPool1d(
kernel_size=2,
stride=2,
padding=0
)
self.relu0 = nn.ReLU6()
self.bn0 = nn.BatchNorm1d(ch_out)
def forward(self, x):
x = self.relu0(self.bn0(self.pool0(self.conv0(x))))
return x
class Regressor(BaseModel):
def __init__(self, ft_in, ft_out):
super(Regressor, self).__init__()
self.ft_in = ft_in
self.ft_out = ft_out
self.fc0 = nn.Linear(
in_features=ft_in,
out_features=ft_out,
bias = False
)
self.relu0 = nn.ReLU6()
self.bn0 = nn.BatchNorm1d(
num_features=ft_out
)
def forward(self, x):
x = self.relu0(self.bn0(self.fc0(x)))
return x
class Chomp1d(BaseModel):
def __init__(self, chomp_size):
super(Chomp1d, self).__init__()
self.chomp_size = chomp_size
def forward(self, x):
return x[:, :, :-self.chomp_size].contiguous()
| true | true |
f72c0485c62be64f09e5a685e3cf499a790a4ccf | 13,340 | py | Python | crossmodal_embedding/tasks/crossmodal/training_star_task.py | ai-systems/crossmodal_embedding | 5c61775531fd350c48a965450ab5e99b28deec5e | [
"MIT"
] | null | null | null | crossmodal_embedding/tasks/crossmodal/training_star_task.py | ai-systems/crossmodal_embedding | 5c61775531fd350c48a965450ab5e99b28deec5e | [
"MIT"
] | null | null | null | crossmodal_embedding/tasks/crossmodal/training_star_task.py | ai-systems/crossmodal_embedding | 5c61775531fd350c48a965450ab5e99b28deec5e | [
"MIT"
] | null | null | null | from prefect import Task
from loguru import logger
from tqdm import tqdm
from crossmodal_embedding.models import CrossModalEmbedding, SiameseNet
from crossmodal_embedding.models import InputData, InputDataTest
from sklearn.metrics import precision_recall_fscore_support, f1_score
import torch.optim as optim
import torch.nn as nn
import torch
import torch.nn as nn
from crossmodal_embedding.util.evaluation import (
compute_map_basic,
compute_map_with_unification,
)
from torch.utils.data import WeightedRandomSampler
import sys
import json
from torch.utils.tensorboard import SummaryWriter
class TrainingTaskStar(Task):
def create_weights(self, df):
positives = 0
negatives = 0
weights = list()
for index, row in df.iterrows():
if row["score"] == 0:
negatives = negatives + 1
else:
positives = positives + 1
weight_positive = 1.0 / float(positives)
weight_negative = 1.0 / float(negatives)
for index, row in df.iterrows():
if row["score"] == 0:
weights.append(weight_negative)
else:
weights.append(weight_positive)
return torch.tensor(weights)
def run(
self,
train,
test,
dev,
num_negatives,
output_log,
output_model,
vocab_size,
batch_size=10,
num_epochs=5,
learning_rate=0.0001,
max_sequence_len=100,
hidden_size=10,
out_embedding=128,
attention_heads=5,
word_embedding=50,
decay=0.01,
):
logger.info(f" Negative Examples: {num_negatives}")
logger.info("Let's train the Cross-Modal Embedding ! (^・ω・^ )")
# Device configuration
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Check for multi_GPUS
multiple_gpus = 0
train_class_weight = self.create_weights(train)
train_dataset = InputData(train)
logger.info(f"TRAIN: {len(train_dataset)}")
dev_dataset = InputData(dev)
logger.info(f"DEV: {len(dev_dataset)}")
test_dataset = InputDataTest(test, vocab_size)
logger.info(f"TEST: {len(test_dataset)}")
sampler_train = WeightedRandomSampler(
train_class_weight, len(train_class_weight)
)
# Data loader
train_loader = torch.utils.data.DataLoader(
dataset=train_dataset, batch_size=batch_size, sampler=sampler_train,
)
dev_loader = torch.utils.data.DataLoader(
dataset=dev_dataset, batch_size=batch_size, shuffle=False
)
test_loader = torch.utils.data.DataLoader(
dataset=test_dataset, batch_size=batch_size, shuffle=False
)
model = SiameseNet(
out_embedding,
batch_size,
vocab_size,
max_len=max_sequence_len,
hidden_size=hidden_size,
out_embedding=out_embedding,
device=device,
attention_heads=attention_heads,
word_embedding=word_embedding,
)
if torch.cuda.device_count() > 1:
logger.info(
f"**********Let's use {torch.cuda.device_count()} GPUs!********"
)
multiple_gpus = 1
model = nn.DataParallel(model)
else:
logger.info("********* Only one GPU *******")
model = model.to(device)
# Loss and optimizer
criterion = nn.NLLLoss()
optimizer = torch.optim.AdamW(
model.parameters(), lr=learning_rate, weight_decay=decay
)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer, "min", verbose=True, patience=1, cooldown=3
)
# Train the model
best_value = 0
all_best = dict()
result_dict = dict()
total_step = len(train_loader)
for epoch in tqdm(range(num_epochs), desc=f"Epoch"):
epoch_loss = 0.0
running_loss = 0.0
model.train()
t = tqdm(iter(train_loader), leave=False, total=len(train_loader))
for (
i,
(statement1, st1_mask, st1_len, statement2, st2_mask, st2_len, score),
) in enumerate(t):
# Move tensors to the configured device
statement1 = statement1.to(device)
st1_mask = st1_mask.to(device)
st1_len = st1_len.to(device)
statement2 = statement2.to(device)
st2_mask = st2_mask.to(device)
st2_len = st2_len.to(device)
score = score.to(device)
optimizer.zero_grad()
sim = model(
statement1, st1_mask, st1_len, statement2, st2_mask, st2_len
)
loss = criterion(sim, score)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
# print statistics
running_loss += loss.item()
if i % 10 == 0:
t.set_description("loss: {:.4f}".format(running_loss / 10))
running_loss = 0
logger.info(
f"********Epoch: {epoch+1} *****Loss: {epoch_loss / len(train_loader)}"
)
result_dict[epoch] = dict()
result_dict[epoch]["train_loss"] = epoch_loss / len(train_loader)
scheduler.step(epoch_loss / len(train_loader))
if (epoch + 1) % 1 == 0:
model.eval()
with torch.no_grad():
logger.info("Evaluating on Train set!")
t = tqdm(iter(train_loader), leave=False, total=len(train_loader))
y_pred_list = []
y_real_list = []
for (
i,
(
statement1,
st1_mask,
st1_len,
statement2,
st2_mask,
st2_len,
score,
),
) in enumerate(t):
# Move tensors to the configured device
statement1 = statement1.to(device)
st1_mask = st1_mask.to(device)
st1_len = st1_len.to(device)
statement2 = statement2.to(device)
st2_mask = st2_mask.to(device)
st2_len = st2_len.to(device)
y_real_list.extend(score.cpu().tolist())
score = score.to(device)
sim = model(
statement1, st1_mask, st1_len, statement2, st2_mask, st2_len
)
y_dev_pred = torch.argmax(sim, dim=1)
# y_dev_pred = torch.argmax(sim, dim=1)
y_pred_list.extend(y_dev_pred.cpu().tolist())
f1_value = f1_score(y_real_list, y_pred_list)
(precision, recall, _, _,) = precision_recall_fscore_support(
y_real_list, y_pred_list, average="binary"
)
# logger.info("**** TRAINING SET **** ")
# logger.info(f"F1-value: {f1_value}")
# logger.info(f"Precision: {precision}")
# logger.info(f"Recall: {recall}")
logger.info("Evaluating on Dev set!")
t = tqdm(iter(dev_loader), leave=False, total=len(dev_loader))
y_pred_list = []
y_real_list = []
epoch_test_loss = 0.0
for (
i,
(
statement1,
st1_mask,
st1_len,
statement2,
st2_mask,
st2_len,
score,
),
) in enumerate(t):
statement1 = statement1.to(device)
st1_mask = st1_mask.to(device)
st1_len = st1_len.to(device)
statement2 = statement2.to(device)
st2_mask = st2_mask.to(device)
st2_len = st2_len.to(device)
y_real_list.extend(score.cpu().tolist())
score = score.to(device)
sim = model(
statement1, st1_mask, st2_len, statement2, st2_mask, st2_len
)
loss_test = criterion(sim, score)
epoch_test_loss += loss_test.item()
y_dev_pred = torch.argmax(sim, dim=1)
y_pred_list.extend(y_dev_pred.cpu().tolist())
logger.info(f"DEV LOSS: {epoch_test_loss / len(dev_loader)}")
# scheduler.step(epoch_test_loss / len(dev_loader))
f1_value = f1_score(y_real_list, y_pred_list)
(precision, recall, _, _,) = precision_recall_fscore_support(
y_real_list, y_pred_list, average="binary"
)
# logger.info("**** DEV SET **** ")
# logger.info(f"F1-value: {f1_value}")
# logger.info(f"Precision: {precision.tolist()}")
# logger.info(f"Recall: {recall.tolist()}")
result_dict[epoch]["f1"] = f1_value
result_dict[epoch]["precision"] = precision.tolist()
result_dict[epoch]["recall"] = recall.tolist()
if f1_value > best_value:
best_value = f1_value
model = model.to("cpu")
if multiple_gpus:
torch.save(
model.module.state_dict(), f"./models/{output_model}",
)
else:
torch.save(
model.state_dict(), f"./models/{output_model}",
)
all_best["f1"] = f1_value
all_best["precision"] = precision.tolist()
all_best["recall"] = recall.tolist()
model = model.to(device)
best_model = model
with torch.no_grad():
best_model.eval()
logger.info("Evaluating on Test set!")
all_embeddings = dict()
t = tqdm(iter(test_loader), leave=False, total=len(test_loader))
y_pred_list = []
y_real_list = []
for (
i,
(statement1, st1_mask, st1_len, statement2, st2_mask, st2_len, score),
) in enumerate(t):
# Move tensors to the configured device
statement1 = statement1.to(device)
st1_mask = st1_mask.to(device)
st1_len = st1_len.to(device)
statement2 = statement2.to(device)
st2_mask = st2_mask.to(device)
st2_len = st2_len.to(device)
y_real_list.extend(score.cpu().tolist())
score = score.to(device)
sim = best_model(
statement1, st1_mask, st1_len, statement2, st2_mask, st2_len
)
# y_dev_pred = torch.round(sim)
y_dev_pred = torch.argmax(sim, dim=1)
y_pred_list.extend(y_dev_pred.cpu().tolist())
f1_value = f1_score(y_real_list, y_pred_list)
(precision, recall, _, _,) = precision_recall_fscore_support(
y_real_list, y_pred_list, average="binary"
)
logger.info("****** PARAMETERS ********")
logger.info(f"Num negatives: {num_negatives}")
logger.info(f"Batch_size: {batch_size}")
logger.info(f"Max len: {max_sequence_len}")
logger.info(f"Word embedding: {word_embedding}")
logger.info(f"Out embedding: {out_embedding}")
logger.info(f"Hidden Size: {hidden_size}")
logger.info(f"Decay: {decay}")
logger.info(f"ATT heads: {attention_heads}")
logger.info(f"Learning rate: {learning_rate}")
logger.info("****** BEST RESULTS TEST******")
logger.info(f"F1 SCORE {f1_value}")
logger.info(f"PRECISION: {precision}")
logger.info(f"RECALL: {recall}")
all_best["f1_test"] = f1_value
all_best["precision_test"] = precision.tolist()
all_best["recall_test"] = recall.tolist()
logger.info("******** BEST RESULTS DEV **********")
logger.info(all_best)
with open(f"./logs/{output_log}", "w") as f:
json.dump(result_dict, f)
with open(f"./logs/best_{output_log}", "w") as f:
json.dump(result_dict, f)
| 37.366947 | 88 | 0.496027 | from prefect import Task
from loguru import logger
from tqdm import tqdm
from crossmodal_embedding.models import CrossModalEmbedding, SiameseNet
from crossmodal_embedding.models import InputData, InputDataTest
from sklearn.metrics import precision_recall_fscore_support, f1_score
import torch.optim as optim
import torch.nn as nn
import torch
import torch.nn as nn
from crossmodal_embedding.util.evaluation import (
compute_map_basic,
compute_map_with_unification,
)
from torch.utils.data import WeightedRandomSampler
import sys
import json
from torch.utils.tensorboard import SummaryWriter
class TrainingTaskStar(Task):
def create_weights(self, df):
positives = 0
negatives = 0
weights = list()
for index, row in df.iterrows():
if row["score"] == 0:
negatives = negatives + 1
else:
positives = positives + 1
weight_positive = 1.0 / float(positives)
weight_negative = 1.0 / float(negatives)
for index, row in df.iterrows():
if row["score"] == 0:
weights.append(weight_negative)
else:
weights.append(weight_positive)
return torch.tensor(weights)
def run(
self,
train,
test,
dev,
num_negatives,
output_log,
output_model,
vocab_size,
batch_size=10,
num_epochs=5,
learning_rate=0.0001,
max_sequence_len=100,
hidden_size=10,
out_embedding=128,
attention_heads=5,
word_embedding=50,
decay=0.01,
):
logger.info(f" Negative Examples: {num_negatives}")
logger.info("Let's train the Cross-Modal Embedding ! (^・ω・^ )")
# Device configuration
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Check for multi_GPUS
multiple_gpus = 0
train_class_weight = self.create_weights(train)
train_dataset = InputData(train)
logger.info(f"TRAIN: {len(train_dataset)}")
dev_dataset = InputData(dev)
logger.info(f"DEV: {len(dev_dataset)}")
test_dataset = InputDataTest(test, vocab_size)
logger.info(f"TEST: {len(test_dataset)}")
sampler_train = WeightedRandomSampler(
train_class_weight, len(train_class_weight)
)
# Data loader
train_loader = torch.utils.data.DataLoader(
dataset=train_dataset, batch_size=batch_size, sampler=sampler_train,
)
dev_loader = torch.utils.data.DataLoader(
dataset=dev_dataset, batch_size=batch_size, shuffle=False
)
test_loader = torch.utils.data.DataLoader(
dataset=test_dataset, batch_size=batch_size, shuffle=False
)
model = SiameseNet(
out_embedding,
batch_size,
vocab_size,
max_len=max_sequence_len,
hidden_size=hidden_size,
out_embedding=out_embedding,
device=device,
attention_heads=attention_heads,
word_embedding=word_embedding,
)
if torch.cuda.device_count() > 1:
logger.info(
f"**********Let's use {torch.cuda.device_count()} GPUs!********"
)
multiple_gpus = 1
model = nn.DataParallel(model)
else:
logger.info("********* Only one GPU *******")
model = model.to(device)
criterion = nn.NLLLoss()
optimizer = torch.optim.AdamW(
model.parameters(), lr=learning_rate, weight_decay=decay
)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer, "min", verbose=True, patience=1, cooldown=3
)
best_value = 0
all_best = dict()
result_dict = dict()
total_step = len(train_loader)
for epoch in tqdm(range(num_epochs), desc=f"Epoch"):
epoch_loss = 0.0
running_loss = 0.0
model.train()
t = tqdm(iter(train_loader), leave=False, total=len(train_loader))
for (
i,
(statement1, st1_mask, st1_len, statement2, st2_mask, st2_len, score),
) in enumerate(t):
statement1 = statement1.to(device)
st1_mask = st1_mask.to(device)
st1_len = st1_len.to(device)
statement2 = statement2.to(device)
st2_mask = st2_mask.to(device)
st2_len = st2_len.to(device)
score = score.to(device)
optimizer.zero_grad()
sim = model(
statement1, st1_mask, st1_len, statement2, st2_mask, st2_len
)
loss = criterion(sim, score)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
running_loss += loss.item()
if i % 10 == 0:
t.set_description("loss: {:.4f}".format(running_loss / 10))
running_loss = 0
logger.info(
f"********Epoch: {epoch+1} *****Loss: {epoch_loss / len(train_loader)}"
)
result_dict[epoch] = dict()
result_dict[epoch]["train_loss"] = epoch_loss / len(train_loader)
scheduler.step(epoch_loss / len(train_loader))
if (epoch + 1) % 1 == 0:
model.eval()
with torch.no_grad():
logger.info("Evaluating on Train set!")
t = tqdm(iter(train_loader), leave=False, total=len(train_loader))
y_pred_list = []
y_real_list = []
for (
i,
(
statement1,
st1_mask,
st1_len,
statement2,
st2_mask,
st2_len,
score,
),
) in enumerate(t):
statement1 = statement1.to(device)
st1_mask = st1_mask.to(device)
st1_len = st1_len.to(device)
statement2 = statement2.to(device)
st2_mask = st2_mask.to(device)
st2_len = st2_len.to(device)
y_real_list.extend(score.cpu().tolist())
score = score.to(device)
sim = model(
statement1, st1_mask, st1_len, statement2, st2_mask, st2_len
)
y_dev_pred = torch.argmax(sim, dim=1)
y_pred_list.extend(y_dev_pred.cpu().tolist())
f1_value = f1_score(y_real_list, y_pred_list)
(precision, recall, _, _,) = precision_recall_fscore_support(
y_real_list, y_pred_list, average="binary"
)
logger.info("Evaluating on Dev set!")
t = tqdm(iter(dev_loader), leave=False, total=len(dev_loader))
y_pred_list = []
y_real_list = []
epoch_test_loss = 0.0
for (
i,
(
statement1,
st1_mask,
st1_len,
statement2,
st2_mask,
st2_len,
score,
),
) in enumerate(t):
statement1 = statement1.to(device)
st1_mask = st1_mask.to(device)
st1_len = st1_len.to(device)
statement2 = statement2.to(device)
st2_mask = st2_mask.to(device)
st2_len = st2_len.to(device)
y_real_list.extend(score.cpu().tolist())
score = score.to(device)
sim = model(
statement1, st1_mask, st2_len, statement2, st2_mask, st2_len
)
loss_test = criterion(sim, score)
epoch_test_loss += loss_test.item()
y_dev_pred = torch.argmax(sim, dim=1)
y_pred_list.extend(y_dev_pred.cpu().tolist())
logger.info(f"DEV LOSS: {epoch_test_loss / len(dev_loader)}")
f1_value = f1_score(y_real_list, y_pred_list)
(precision, recall, _, _,) = precision_recall_fscore_support(
y_real_list, y_pred_list, average="binary"
)
result_dict[epoch]["f1"] = f1_value
result_dict[epoch]["precision"] = precision.tolist()
result_dict[epoch]["recall"] = recall.tolist()
if f1_value > best_value:
best_value = f1_value
model = model.to("cpu")
if multiple_gpus:
torch.save(
model.module.state_dict(), f"./models/{output_model}",
)
else:
torch.save(
model.state_dict(), f"./models/{output_model}",
)
all_best["f1"] = f1_value
all_best["precision"] = precision.tolist()
all_best["recall"] = recall.tolist()
model = model.to(device)
best_model = model
with torch.no_grad():
best_model.eval()
logger.info("Evaluating on Test set!")
all_embeddings = dict()
t = tqdm(iter(test_loader), leave=False, total=len(test_loader))
y_pred_list = []
y_real_list = []
for (
i,
(statement1, st1_mask, st1_len, statement2, st2_mask, st2_len, score),
) in enumerate(t):
statement1 = statement1.to(device)
st1_mask = st1_mask.to(device)
st1_len = st1_len.to(device)
statement2 = statement2.to(device)
st2_mask = st2_mask.to(device)
st2_len = st2_len.to(device)
y_real_list.extend(score.cpu().tolist())
score = score.to(device)
sim = best_model(
statement1, st1_mask, st1_len, statement2, st2_mask, st2_len
)
y_dev_pred = torch.argmax(sim, dim=1)
y_pred_list.extend(y_dev_pred.cpu().tolist())
f1_value = f1_score(y_real_list, y_pred_list)
(precision, recall, _, _,) = precision_recall_fscore_support(
y_real_list, y_pred_list, average="binary"
)
logger.info("****** PARAMETERS ********")
logger.info(f"Num negatives: {num_negatives}")
logger.info(f"Batch_size: {batch_size}")
logger.info(f"Max len: {max_sequence_len}")
logger.info(f"Word embedding: {word_embedding}")
logger.info(f"Out embedding: {out_embedding}")
logger.info(f"Hidden Size: {hidden_size}")
logger.info(f"Decay: {decay}")
logger.info(f"ATT heads: {attention_heads}")
logger.info(f"Learning rate: {learning_rate}")
logger.info("****** BEST RESULTS TEST******")
logger.info(f"F1 SCORE {f1_value}")
logger.info(f"PRECISION: {precision}")
logger.info(f"RECALL: {recall}")
all_best["f1_test"] = f1_value
all_best["precision_test"] = precision.tolist()
all_best["recall_test"] = recall.tolist()
logger.info("******** BEST RESULTS DEV **********")
logger.info(all_best)
with open(f"./logs/{output_log}", "w") as f:
json.dump(result_dict, f)
with open(f"./logs/best_{output_log}", "w") as f:
json.dump(result_dict, f)
| true | true |
f72c04c1115d6d2253cc4ff13cc515e322a0dd87 | 6,763 | py | Python | config.py | YetheYe/Mask_RCNN | 6895c617af13ecbf0bb27790e29a6271725cb34f | [
"MIT"
] | null | null | null | config.py | YetheYe/Mask_RCNN | 6895c617af13ecbf0bb27790e29a6271725cb34f | [
"MIT"
] | null | null | null | config.py | YetheYe/Mask_RCNN | 6895c617af13ecbf0bb27790e29a6271725cb34f | [
"MIT"
] | null | null | null | """
Mask R-CNN
Base Configurations class.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
"""
import math
import numpy as np
# Base Configuration Class
# Don't use this class directly. Instead, sub-class it and override
# the configurations you need to change.
class Config(object):
"""Base configuration class. For custom configurations, create a
sub-class that inherits from this one and override properties
that need to be changed.
"""
# Name the configurations. For example, 'COCO', 'Experiment 3', ...etc.
# Useful if your code needs to do things differently depending on which
# experiment is running.
NAME = None # Override in sub-classes
# NUMBER OF GPUs to use. For CPU training, use 1
GPU_COUNT = 1
# Number of images to train with on each GPU. A 12GB GPU can typically
# handle 2 images of 1024x1024px.
# Adjust based on your GPU memory and image sizes. Use the highest
# number that your GPU can handle for best performance.
IMAGES_PER_GPU = 2
# Number of training steps per epoch
# This doesn't need to match the size of the training set. Tensorboard
# updates are saved at the end of each epoch, so setting this to a
# smaller number means getting more frequent TensorBoard updates.
# Validation stats are also calculated at each epoch end and they
# might take a while, so don't set this too small to avoid spending
# a lot of time on validation stats.
STEPS_PER_EPOCH = 1000
# Number of validation steps to run at the end of every training epoch.
# A bigger number improves accuracy of validation stats, but slows
# down the training.
VALIDATION_STEPS = 50
# Backbone network architecture
# Supported values are: resnet50, resnet101
BACKBONE = "resnet101"
# The strides of each layer of the FPN Pyramid. These values
# are based on a Resnet101 backbone.
BACKBONE_STRIDES = [4, 8, 16, 32, 64]
# Number of classification classes (including background)
NUM_CLASSES = 1 # Override in sub-classes
# Length of square anchor side in pixels
RPN_ANCHOR_SCALES = (128, 256, 512)
# Ratios of anchors at each cell (width/height)
# A value of 1 represents a square anchor, and 0.5 is a wide anchor
RPN_ANCHOR_RATIOS = [0.5, 1, 2]
# Anchor stride
# If 1 then anchors are created for each cell in the backbone feature map.
# If 2, then anchors are created for every other cell, and so on.
RPN_ANCHOR_STRIDE = 1
# Non-max suppression threshold to filter RPN proposals.
# You can increase this during training to generate more propsals.
RPN_NMS_THRESHOLD = 0.7
# How many anchors per image to use for RPN training
RPN_TRAIN_ANCHORS_PER_IMAGE = 256
# ROIs kept after non-maximum supression (training and inference)
POST_NMS_ROIS_TRAINING = 2000
POST_NMS_ROIS_INFERENCE = 1000
# If enabled, resizes instance masks to a smaller size to reduce
# memory load. Recommended when using high-resolution images.
USE_MINI_MASK = True
MINI_MASK_SHAPE = (56, 56) # (height, width) of the mini-mask
# Input image resizing
# Images are resized such that the small side is IMAGE_MIN_DIM and
# the long side is <= IMAGE_MAX_DIM. If both conditions can't be
# satisfied at the same time then IMAGE_MAX_DIM is enforced.
# Resizing modes:
# none: No resizing
# square: Pad with zeros to make it a square (MAX_DIM, MAX_DIM)
# TODO: currently, only 'square' mode is supported
IMAGE_RESIZE_MODE = "square"
IMAGE_MIN_DIM = 800
IMAGE_MAX_DIM = 1024
# Image mean (RGB)
MEAN_PIXEL = np.array([123.7, 116.8, 103.9])
# Number of ROIs per image to feed to classifier/mask heads
# The Mask RCNN paper uses 512 but often the RPN doesn't generate
# enough positive proposals to fill this and keep a positive:negative
# ratio of 1:3. You can increase the number of proposals by adjusting
# the RPN NMS threshold.
TRAIN_ROIS_PER_IMAGE = 200
# Percent of positive ROIs used to train classifier/mask heads
ROI_POSITIVE_RATIO = 0.33
# Pooled ROIs
POOL_SIZE = 7
MASK_POOL_SIZE = 14
MASK_SHAPE = [28, 28]
# Maximum number of ground truth instances to use in one image
MAX_GT_INSTANCES = 100
# Bounding box refinement standard deviation for RPN and final detections.
RPN_BBOX_STD_DEV = np.array([0.1, 0.1, 0.2, 0.2])
BBOX_STD_DEV = np.array([0.1, 0.1, 0.2, 0.2])
# Max number of final detections
DETECTION_MAX_INSTANCES = 100
# Minimum probability value to accept a detected instance
# ROIs below this threshold are skipped
DETECTION_MIN_CONFIDENCE = 0.5
# Non-maximum suppression threshold for detection
DETECTION_NMS_THRESHOLD = 0.3
# Learning rate and momentum
# The Mask RCNN paper uses lr=0.02, but on TensorFlow it causes
# weights to explode. Likely due to differences in optimzer
# implementation.
LEARNING_RATE = 0.001
LEARNING_MOMENTUM = 0.9
# Weight decay regularization
WEIGHT_DECAY = 0.0001
# Use RPN ROIs or externally generated ROIs for training
# Keep this True for most situations. Set to False if you want to train
# the head branches on ROI generated by code rather than the ROIs from
# the RPN. For example, to debug the classifier head without having to
# train the RPN.
USE_RPN_ROIS = True
# Train or freeze batch normalization layers
# None: Train BN layers. This is the normal mode
# False: Freeze BN layers. Good when using a small batch size
# True: (don't use). Set layer in training mode even when inferencing
TRAIN_BN = False # Defaulting to False since batch size is often small
# Gradient norm clipping
GRADIENT_CLIP_NORM = 5.0
def __init__(self):
"""Set values of computed attributes."""
# Effective batch size
self.BATCH_SIZE = self.IMAGES_PER_GPU * self.GPU_COUNT
# Input image size
if self.IMAGE_RESIZE_MODE == "crop":
self.IMAGE_SHAPE = np.array([self.IMAGE_MIN_DIM, self.IMAGE_MIN_DIM, 3])
else:
self.IMAGE_SHAPE = np.array([self.IMAGE_MAX_DIM, self.IMAGE_MAX_DIM, 3])
# Image meta data length
# See compose_image_meta() for details
self.IMAGE_META_SIZE = 1 + 3 + 3 + 4 + 1 + self.NUM_CLASSES
def display(self):
"""Display Configuration values."""
print("\nConfigurations:")
for a in dir(self):
if not a.startswith("__") and not callable(getattr(self, a)):
print("{:30} {}".format(a, getattr(self, a)))
print("\n")
| 36.556757 | 84 | 0.69067 |
import math
import numpy as np
# the configurations you need to change.
class Config(object):
# Name the configurations. For example, 'COCO', 'Experiment 3', ...etc.
# Useful if your code needs to do things differently depending on which
# experiment is running.
NAME = None # Override in sub-classes
# NUMBER OF GPUs to use. For CPU training, use 1
GPU_COUNT = 1
# Number of images to train with on each GPU. A 12GB GPU can typically
# handle 2 images of 1024x1024px.
# Adjust based on your GPU memory and image sizes. Use the highest
# number that your GPU can handle for best performance.
IMAGES_PER_GPU = 2
# Number of training steps per epoch
# This doesn't need to match the size of the training set. Tensorboard
# a lot of time on validation stats.
STEPS_PER_EPOCH = 1000
# Number of validation steps to run at the end of every training epoch.
# A bigger number improves accuracy of validation stats, but slows
# down the training.
VALIDATION_STEPS = 50
# Backbone network architecture
# Supported values are: resnet50, resnet101
BACKBONE = "resnet101"
# The strides of each layer of the FPN Pyramid. These values
# are based on a Resnet101 backbone.
BACKBONE_STRIDES = [4, 8, 16, 32, 64]
# Number of classification classes (including background)
NUM_CLASSES = 1 # Override in sub-classes
# Length of square anchor side in pixels
RPN_ANCHOR_SCALES = (128, 256, 512)
# Ratios of anchors at each cell (width/height)
# A value of 1 represents a square anchor, and 0.5 is a wide anchor
RPN_ANCHOR_RATIOS = [0.5, 1, 2]
# Anchor stride
# If 1 then anchors are created for each cell in the backbone feature map.
# If 2, then anchors are created for every other cell, and so on.
RPN_ANCHOR_STRIDE = 1
# Non-max suppression threshold to filter RPN proposals.
# You can increase this during training to generate more propsals.
RPN_NMS_THRESHOLD = 0.7
# How many anchors per image to use for RPN training
RPN_TRAIN_ANCHORS_PER_IMAGE = 256
# ROIs kept after non-maximum supression (training and inference)
POST_NMS_ROIS_TRAINING = 2000
POST_NMS_ROIS_INFERENCE = 1000
# If enabled, resizes instance masks to a smaller size to reduce
# memory load. Recommended when using high-resolution images.
USE_MINI_MASK = True
MINI_MASK_SHAPE = (56, 56) # (height, width) of the mini-mask
# Input image resizing
# Images are resized such that the small side is IMAGE_MIN_DIM and
# the long side is <= IMAGE_MAX_DIM. If both conditions can't be
IMAGE_RESIZE_MODE = "square"
IMAGE_MIN_DIM = 800
IMAGE_MAX_DIM = 1024
MEAN_PIXEL = np.array([123.7, 116.8, 103.9])
# enough positive proposals to fill this and keep a positive:negative
# ratio of 1:3. You can increase the number of proposals by adjusting
# the RPN NMS threshold.
TRAIN_ROIS_PER_IMAGE = 200
# Percent of positive ROIs used to train classifier/mask heads
ROI_POSITIVE_RATIO = 0.33
# Pooled ROIs
POOL_SIZE = 7
MASK_POOL_SIZE = 14
MASK_SHAPE = [28, 28]
# Maximum number of ground truth instances to use in one image
MAX_GT_INSTANCES = 100
# Bounding box refinement standard deviation for RPN and final detections.
RPN_BBOX_STD_DEV = np.array([0.1, 0.1, 0.2, 0.2])
BBOX_STD_DEV = np.array([0.1, 0.1, 0.2, 0.2])
# Max number of final detections
DETECTION_MAX_INSTANCES = 100
# Minimum probability value to accept a detected instance
# ROIs below this threshold are skipped
DETECTION_MIN_CONFIDENCE = 0.5
# Non-maximum suppression threshold for detection
DETECTION_NMS_THRESHOLD = 0.3
# Learning rate and momentum
# The Mask RCNN paper uses lr=0.02, but on TensorFlow it causes
# weights to explode. Likely due to differences in optimzer
# implementation.
LEARNING_RATE = 0.001
LEARNING_MOMENTUM = 0.9
# Weight decay regularization
WEIGHT_DECAY = 0.0001
# Use RPN ROIs or externally generated ROIs for training
# Keep this True for most situations. Set to False if you want to train
# the head branches on ROI generated by code rather than the ROIs from
# the RPN. For example, to debug the classifier head without having to
# train the RPN.
USE_RPN_ROIS = True
# Train or freeze batch normalization layers
# None: Train BN layers. This is the normal mode
# False: Freeze BN layers. Good when using a small batch size
# True: (don't use). Set layer in training mode even when inferencing
TRAIN_BN = False
GRADIENT_CLIP_NORM = 5.0
def __init__(self):
self.BATCH_SIZE = self.IMAGES_PER_GPU * self.GPU_COUNT
if self.IMAGE_RESIZE_MODE == "crop":
self.IMAGE_SHAPE = np.array([self.IMAGE_MIN_DIM, self.IMAGE_MIN_DIM, 3])
else:
self.IMAGE_SHAPE = np.array([self.IMAGE_MAX_DIM, self.IMAGE_MAX_DIM, 3])
self.IMAGE_META_SIZE = 1 + 3 + 3 + 4 + 1 + self.NUM_CLASSES
def display(self):
print("\nConfigurations:")
for a in dir(self):
if not a.startswith("__") and not callable(getattr(self, a)):
print("{:30} {}".format(a, getattr(self, a)))
print("\n")
| true | true |
f72c04c84917b4d25698a444e88719304b1f71e7 | 17,176 | py | Python | test/test_utils/vcfutils/test_parser.py | dylex/wecall | 35d24cefa4fba549e737cd99329ae1b17dd0156b | [
"MIT"
] | 8 | 2018-10-08T15:47:21.000Z | 2021-11-09T07:13:05.000Z | test/test_utils/vcfutils/test_parser.py | dylex/wecall | 35d24cefa4fba549e737cd99329ae1b17dd0156b | [
"MIT"
] | 4 | 2018-11-05T09:16:27.000Z | 2020-04-09T12:32:56.000Z | test/test_utils/vcfutils/test_parser.py | dylex/wecall | 35d24cefa4fba549e737cd99329ae1b17dd0156b | [
"MIT"
] | 4 | 2019-09-03T15:46:39.000Z | 2021-06-04T07:28:33.000Z | # All content Copyright (C) 2018 Genomics plc
import os
import re
import unittest
from wecall.genomics.variant import Variant
from wecall.vcfutils.genotype_call import GenotypeCall
from wecall.vcfutils.parser import VCFReader, VCFReaderContextManager, decode_VCF_string, \
parse_VCF_comma_separated_pair_value
from wecall.vcfutils.schema import Schema
from wecall.vcfutils.writer import VCFWriterContextManager
from wecall_test_drivers.base_test import BaseTest
class ParserTest(BaseTest):
def setUp(self):
BaseTest.setUp(self)
self.data_dir = os.path.join(os.path.dirname(__file__), "example_data")
def variant_is_equal(self, var1, var2):
self.assertEqual(var1.chrom, var2[0])
self.assertEqual(var1.pos_from, var2[1])
self.assertEqual(var1.ids, var2[2])
self.assertEqual(var1.ref, var2[3])
self.assertEqual(var1.alt, var2[4])
def test_read_VCF_line(self):
with open(os.path.join(self.data_dir, "vcf_example.vcf"), "r") as vcf_file:
vcf_handler = VCFReader(vcf_file)
vcf_handler.read_header()
self.assertEqual(len(vcf_handler.header.file_metadata), 7)
self.assertEqual(len(vcf_handler.header.samples), 2)
records = list(vcf_handler.read_records())
self.assertEqual(len(records), 2)
# test first record fully
self.variant_is_equal(records[0], ("20", 9, set(), "CT", "C")) # zero=based representation
self.assertEqual(records[0].filters, set())
self.assertEqual(records[0].passes_filter, True)
self.assertEqual(len(records[0].info), 12)
self.assertEqual(records[0].info["PP"], [3000])
self.assertEqual(records[0].info["DP"], [250])
self.assertEqual(records[0].info["DPR"], [140])
self.assertEqual(records[0].info["DPF"], [110])
self.assertEqual(records[0].info["VC"], [100])
self.assertEqual(records[0].info["VCR"], [49])
self.assertEqual(records[0].info["VCF"], [51])
self.assertEqual(records[0].info["ABPV"], [0.2])
self.assertEqual(records[0].info["SBPV"], [0.3])
self.assertEqual(records[0].info["MQ"], [70])
self.assertEqual(records[0].info["BR"], [31])
self.assertEqual(records[0].info["QD"], [None])
self.assertEqual(records[0].samples, ['sample1', 'sample2'])
self.assertEqual(records[0].sample_info.get_field('sample1', "GT"), GenotypeCall("0/1"))
self.assertEqual(records[0].sample_info.get_field('sample2', "GT"), GenotypeCall("1/1"))
self.assertEqual(records[0].sample_info.get_field('sample1', 'PL'), [3000, 0, 3000])
self.assertEqual(records[0].sample_info.get_field('sample2', 'PL'), [114, 0, 0])
self.assertEqual(records[0].sample_info.get_field('sample1', 'GQ'), [1000])
self.assertEqual(records[0].sample_info.get_field('sample2', 'GQ'), [None])
# check that ordering in the dictionaries is preserved
expected_keys = ["PP", "DP", "DPR", "DPF", "VC", "VCR",
"VCF", "ABPV", "SBPV", "MQ", "BR", "QD"]
self.assertEqual(list(records[0].info.keys()), expected_keys)
# ensure last record is still being read correctly
self.variant_is_equal(records[-1], ("20", 10, set(), "T", "G"))
def test_reads_simple_file(self):
filename = os.path.join(self.work_dir, "test.vcf")
with VCFWriterContextManager(filename) as left_vcf:
left_vcf.write_variant(Variant("1", 1, "A", "T"))
left_vcf.write_variant(Variant("2", 1, "A", "T"))
left_vcf.write_variant(Variant("10", 1, "A", "T"))
expected_variants = [
Variant("1", 1, "A", "T"),
Variant("2", 1, "A", "T"),
Variant("10", 1, "A", "T"),
]
with VCFReaderContextManager(filename) as vcf_reader:
actual_variants = [record.variant for record in vcf_reader.read_records()]
self.assertEqual(expected_variants, actual_variants)
class TestVCFStringParsing(unittest.TestCase):
def test_should_decode_empty_VCF_string(self):
self.assertEqual('', decode_VCF_string('""'))
def test_should_decode_simple_VCF_string(self):
self.assertEqual('foo', decode_VCF_string('"foo"'))
def test_should_decode_VCF_string_with_single_double_quote(self):
self.assertEqual('"', decode_VCF_string('"\\""'))
def test_should_decode_VCF_string_with_single_backslash(self):
self.assertEqual('\\', decode_VCF_string('"\\\\"'))
def test_should_decode_complex_VCF_string(self):
self.assertEqual(
'abc\\def"ghi',
decode_VCF_string('"abc\\\\def\\\"ghi"'))
def test_should_fail_to_decode_unquoted_string(self):
with self.assertRaisesRegex(Exception, 'expected a VCF encoded string: \'foo\''):
print(decode_VCF_string('foo'))
def test_should_fail_to_decode_string_with_stray_backslash(self):
with self.assertRaisesRegex(Exception, re.escape('expected a VCF encoded string: \'"\\\\"\'')):
print(decode_VCF_string('"\\"'))
def test_should_fail_to_decode_string_with_unencoded_double_quote(self):
with self.assertRaisesRegex(Exception, 'expected a VCF encoded string: \'"\""\''):
print(decode_VCF_string('"\""'))
class TestCommaSeparatedPairParser(unittest.TestCase):
def test_should_parse_simple_comma_separated_pairs(self):
parsed = parse_VCF_comma_separated_pair_value('<first=foo,second=bar>')
expected = {'first': 'foo', 'second': 'bar'}
self.assertEqual(expected, parsed)
def test_should_parse_empty_simple_value(self):
parsed = parse_VCF_comma_separated_pair_value('<first=,second=bar>')
expected = {'first': '', 'second': 'bar'}
self.assertEqual(expected, parsed)
def test_should_fail_to_parse_non_bracketed_string(self):
with self.assertRaisesRegex(Exception, 'expected braced key-value pairs: \'first=foo\''):
print(parse_VCF_comma_separated_pair_value('first=foo'))
def test_should_parse_quoted_comma_separated_pairs(self):
parsed = parse_VCF_comma_separated_pair_value(
'<first="foo",second="bar">')
expected = {'first': '"foo"', 'second': '"bar"'}
self.assertEqual(expected, parsed)
def test_should_parse_empty_quoted_value(self):
parsed = parse_VCF_comma_separated_pair_value('<first="">')
expected = {'first': '""'}
self.assertEqual(expected, parsed)
def test_should_parse_values_with_quoted_commas(self):
parsed = parse_VCF_comma_separated_pair_value('<first="foo,bar">')
expected = {'first': '"foo,bar"'}
self.assertEqual(expected, parsed)
def test_should_parse_values_with_quoted_double_quote(self):
parsed = parse_VCF_comma_separated_pair_value('<first="foo\\\"bar">')
expected = {'first': '"foo\\\"bar"'}
self.assertEqual(expected, parsed)
def test_should_fail_with_badly_quoted_double_quote(self):
with self.assertRaisesRegex(Exception, 'failed to parse key-value pairs from \'<first="foo\"bar">\''):
print(parse_VCF_comma_separated_pair_value('<first="foo\"bar">'))
class TestHeaderParsing(unittest.TestCase):
# version parsing
def test_should_parse_well_formatted_version(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
self.assertEqual(expected, header)
def test_should_store_header_as_attribute_of_parser(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
self.assertEqual(header, reader.header)
def test_should_fail_with_unexpected_version(self):
lines = [
'##fileformat=VCFv0.0\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(Exception, 'unexpected version: \'0.0\''):
print(reader.read_header())
def test_should_fail_to_parse_malformed_header_line(self):
lines = [
'##fileformat=VCFv4.2\n',
'##malformed line!\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(Exception, 'failed to parse header line: \'##malformed line!\''):
print(reader.read_header())
def test_should_fail_if_version_is_not_defined(self):
lines = [
'##notFileformat=foo\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(Exception, 'unrecognised file format line: \'##notFileformat=foo\''):
print(reader.read_header())
# file metadata parsing
def test_should_parse_well_formatted_file_metadata(self):
lines = [
'##fileformat=VCFv4.2\n',
'##fileDate=2013-07-08\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.file_metadata['fileDate'] = '2013-07-08'
self.assertEqual(expected, header)
# info data parsing
def test_should_parse_minimal_info_header_fields(self):
lines = [
'##fileformat=VCFv4.2\n',
'##INFO=<ID=key,Number=1,Type=String,Description="description">\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.set_info_data('key', '1', 'String', 'description')
self.assertEqual(expected, header)
def test_should_parse_all_info_header_fields(self):
lines = [
'##fileformat=VCFv4.2\n',
'##INFO=<ID=key,Number=1,Type=String,Description="description",Source="foo",Version="bar">\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.set_info_data(
'key',
'1',
'String',
'description',
'foo',
'bar')
self.assertEqual(expected, header)
# sample data parsing
def test_should_parse_valid_sample_header_fields(self):
lines = [
'##fileformat=VCFv4.2\n',
'##FORMAT=<ID=key,Number=1,Type=String,Description="description">\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.set_sample_data('key', '1', 'String', 'description')
self.assertEqual(expected, header)
# filter parsing
def test_should_parse_valid_filter_header_fields(self):
lines = [
'##fileformat=VCFv4.2\n',
'##FILTER=<ID=key,Description="description">\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.set_filter('key', 'description')
self.assertEqual(expected, header)
# contig parsing
def test_should_parse_valid_contig_header_fields(self):
lines = [
'##fileformat=VCFv4.2\n',
'##contig=<ID=key,length=666>\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.set_contig('key', 666)
self.assertEqual(expected, header)
# column headers + sample names
def test_should_parse_required_column_headers(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
self.assertEqual(expected, header)
def test_should_fail_without_required_column_headers(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(
Exception,
re.escape("expected column header line: '#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER'")
):
print(reader.read_header())
def test_should_parse_column_headers_with_format_but_no_samples(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
self.assertEqual(expected, header)
def test_should_parse_column_headers_with_complex_sample_names(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tOWEN_TOBY-RHYS.JONES\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.samples = ['OWEN_TOBY-RHYS.JONES']
self.assertEqual(expected, header)
def test_should_not_parse_column_headers_with_sample_names_containing_white_space(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tOWEN JONES\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(
Exception,
re.escape(
'expected column header line: '
'\'#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFORMAT\\tOWEN JONES\''
)
):
print(reader.read_header())
def test_should_fail_with_malformed_format_column_header(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFOO\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(
Exception,
re.escape('expected column header line: \'#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER\\tINFO\\tFOO\'')
):
print(reader.read_header())
def test_should_parse_column_headers_with_samples(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tFOO\tBAR\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.samples.append('FOO')
expected.samples.append('BAR')
self.assertEqual(expected, header)
def test_should_fail_if_column_header_line_is_missing(self):
lines = [
'##fileformat=VCFv4.2\n',
'the line after the header\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(Exception, 'expected column header line: \'the line after the header\''):
print(reader.read_header())
def test_should_fail_on_unexpected_EOF(self):
lines = [
'##fileformat=VCFv4.2\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(Exception, 'unexpected EOF'):
print(reader.read_header())
class TestRecordParsing(unittest.TestCase):
# version parsing
def test_should_parse_single_record(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
'chr0\t0\t.\tP\tQ\t0\tPASS\t\n',
]
reader = VCFReader(iter(lines))
record_count = len(list(reader.read_records()))
self.assertEqual(1, record_count)
def test_should_parse_header_when_parsing_records(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
'chr0\t0\t.\tP\tQ\t0\tPASS\t\n',
]
reader = VCFReader(iter(lines))
self.assertIsNone(reader.header)
list(reader.read_records())
self.assertIsNotNone(reader.header)
def test_should_parse_empty_file(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
record_count = len(list(reader.read_records()))
self.assertEqual(0, record_count)
| 35.783333 | 120 | 0.615859 |
import os
import re
import unittest
from wecall.genomics.variant import Variant
from wecall.vcfutils.genotype_call import GenotypeCall
from wecall.vcfutils.parser import VCFReader, VCFReaderContextManager, decode_VCF_string, \
parse_VCF_comma_separated_pair_value
from wecall.vcfutils.schema import Schema
from wecall.vcfutils.writer import VCFWriterContextManager
from wecall_test_drivers.base_test import BaseTest
class ParserTest(BaseTest):
def setUp(self):
BaseTest.setUp(self)
self.data_dir = os.path.join(os.path.dirname(__file__), "example_data")
def variant_is_equal(self, var1, var2):
self.assertEqual(var1.chrom, var2[0])
self.assertEqual(var1.pos_from, var2[1])
self.assertEqual(var1.ids, var2[2])
self.assertEqual(var1.ref, var2[3])
self.assertEqual(var1.alt, var2[4])
def test_read_VCF_line(self):
with open(os.path.join(self.data_dir, "vcf_example.vcf"), "r") as vcf_file:
vcf_handler = VCFReader(vcf_file)
vcf_handler.read_header()
self.assertEqual(len(vcf_handler.header.file_metadata), 7)
self.assertEqual(len(vcf_handler.header.samples), 2)
records = list(vcf_handler.read_records())
self.assertEqual(len(records), 2)
self.variant_is_equal(records[0], ("20", 9, set(), "CT", "C"))
self.assertEqual(records[0].filters, set())
self.assertEqual(records[0].passes_filter, True)
self.assertEqual(len(records[0].info), 12)
self.assertEqual(records[0].info["PP"], [3000])
self.assertEqual(records[0].info["DP"], [250])
self.assertEqual(records[0].info["DPR"], [140])
self.assertEqual(records[0].info["DPF"], [110])
self.assertEqual(records[0].info["VC"], [100])
self.assertEqual(records[0].info["VCR"], [49])
self.assertEqual(records[0].info["VCF"], [51])
self.assertEqual(records[0].info["ABPV"], [0.2])
self.assertEqual(records[0].info["SBPV"], [0.3])
self.assertEqual(records[0].info["MQ"], [70])
self.assertEqual(records[0].info["BR"], [31])
self.assertEqual(records[0].info["QD"], [None])
self.assertEqual(records[0].samples, ['sample1', 'sample2'])
self.assertEqual(records[0].sample_info.get_field('sample1', "GT"), GenotypeCall("0/1"))
self.assertEqual(records[0].sample_info.get_field('sample2', "GT"), GenotypeCall("1/1"))
self.assertEqual(records[0].sample_info.get_field('sample1', 'PL'), [3000, 0, 3000])
self.assertEqual(records[0].sample_info.get_field('sample2', 'PL'), [114, 0, 0])
self.assertEqual(records[0].sample_info.get_field('sample1', 'GQ'), [1000])
self.assertEqual(records[0].sample_info.get_field('sample2', 'GQ'), [None])
expected_keys = ["PP", "DP", "DPR", "DPF", "VC", "VCR",
"VCF", "ABPV", "SBPV", "MQ", "BR", "QD"]
self.assertEqual(list(records[0].info.keys()), expected_keys)
self.variant_is_equal(records[-1], ("20", 10, set(), "T", "G"))
def test_reads_simple_file(self):
filename = os.path.join(self.work_dir, "test.vcf")
with VCFWriterContextManager(filename) as left_vcf:
left_vcf.write_variant(Variant("1", 1, "A", "T"))
left_vcf.write_variant(Variant("2", 1, "A", "T"))
left_vcf.write_variant(Variant("10", 1, "A", "T"))
expected_variants = [
Variant("1", 1, "A", "T"),
Variant("2", 1, "A", "T"),
Variant("10", 1, "A", "T"),
]
with VCFReaderContextManager(filename) as vcf_reader:
actual_variants = [record.variant for record in vcf_reader.read_records()]
self.assertEqual(expected_variants, actual_variants)
class TestVCFStringParsing(unittest.TestCase):
def test_should_decode_empty_VCF_string(self):
self.assertEqual('', decode_VCF_string('""'))
def test_should_decode_simple_VCF_string(self):
self.assertEqual('foo', decode_VCF_string('"foo"'))
def test_should_decode_VCF_string_with_single_double_quote(self):
self.assertEqual('"', decode_VCF_string('"\\""'))
def test_should_decode_VCF_string_with_single_backslash(self):
self.assertEqual('\\', decode_VCF_string('"\\\\"'))
def test_should_decode_complex_VCF_string(self):
self.assertEqual(
'abc\\def"ghi',
decode_VCF_string('"abc\\\\def\\\"ghi"'))
def test_should_fail_to_decode_unquoted_string(self):
with self.assertRaisesRegex(Exception, 'expected a VCF encoded string: \'foo\''):
print(decode_VCF_string('foo'))
def test_should_fail_to_decode_string_with_stray_backslash(self):
with self.assertRaisesRegex(Exception, re.escape('expected a VCF encoded string: \'"\\\\"\'')):
print(decode_VCF_string('"\\"'))
def test_should_fail_to_decode_string_with_unencoded_double_quote(self):
with self.assertRaisesRegex(Exception, 'expected a VCF encoded string: \'"\""\''):
print(decode_VCF_string('"\""'))
class TestCommaSeparatedPairParser(unittest.TestCase):
def test_should_parse_simple_comma_separated_pairs(self):
parsed = parse_VCF_comma_separated_pair_value('<first=foo,second=bar>')
expected = {'first': 'foo', 'second': 'bar'}
self.assertEqual(expected, parsed)
def test_should_parse_empty_simple_value(self):
parsed = parse_VCF_comma_separated_pair_value('<first=,second=bar>')
expected = {'first': '', 'second': 'bar'}
self.assertEqual(expected, parsed)
def test_should_fail_to_parse_non_bracketed_string(self):
with self.assertRaisesRegex(Exception, 'expected braced key-value pairs: \'first=foo\''):
print(parse_VCF_comma_separated_pair_value('first=foo'))
def test_should_parse_quoted_comma_separated_pairs(self):
parsed = parse_VCF_comma_separated_pair_value(
'<first="foo",second="bar">')
expected = {'first': '"foo"', 'second': '"bar"'}
self.assertEqual(expected, parsed)
def test_should_parse_empty_quoted_value(self):
parsed = parse_VCF_comma_separated_pair_value('<first="">')
expected = {'first': '""'}
self.assertEqual(expected, parsed)
def test_should_parse_values_with_quoted_commas(self):
parsed = parse_VCF_comma_separated_pair_value('<first="foo,bar">')
expected = {'first': '"foo,bar"'}
self.assertEqual(expected, parsed)
def test_should_parse_values_with_quoted_double_quote(self):
parsed = parse_VCF_comma_separated_pair_value('<first="foo\\\"bar">')
expected = {'first': '"foo\\\"bar"'}
self.assertEqual(expected, parsed)
def test_should_fail_with_badly_quoted_double_quote(self):
with self.assertRaisesRegex(Exception, 'failed to parse key-value pairs from \'<first="foo\"bar">\''):
print(parse_VCF_comma_separated_pair_value('<first="foo\"bar">'))
class TestHeaderParsing(unittest.TestCase):
def test_should_parse_well_formatted_version(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
self.assertEqual(expected, header)
def test_should_store_header_as_attribute_of_parser(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
self.assertEqual(header, reader.header)
def test_should_fail_with_unexpected_version(self):
lines = [
'##fileformat=VCFv0.0\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(Exception, 'unexpected version: \'0.0\''):
print(reader.read_header())
def test_should_fail_to_parse_malformed_header_line(self):
lines = [
'##fileformat=VCFv4.2\n',
'##malformed line!\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(Exception, 'failed to parse header line: \'ader.read_header())
def test_should_fail_if_version_is_not_defined(self):
lines = [
'##notFileformat=foo\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(Exception, 'unrecognised file format line: \'er.read_header())
def test_should_parse_well_formatted_file_metadata(self):
lines = [
'##fileformat=VCFv4.2\n',
'##fileDate=2013-07-08\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.file_metadata['fileDate'] = '2013-07-08'
self.assertEqual(expected, header)
def test_should_parse_minimal_info_header_fields(self):
lines = [
'##fileformat=VCFv4.2\n',
'##INFO=<ID=key,Number=1,Type=String,Description="description">\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.set_info_data('key', '1', 'String', 'description')
self.assertEqual(expected, header)
def test_should_parse_all_info_header_fields(self):
lines = [
'##fileformat=VCFv4.2\n',
'##INFO=<ID=key,Number=1,Type=String,Description="description",Source="foo",Version="bar">\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.set_info_data(
'key',
'1',
'String',
'description',
'foo',
'bar')
self.assertEqual(expected, header)
def test_should_parse_valid_sample_header_fields(self):
lines = [
'##fileformat=VCFv4.2\n',
'##FORMAT=<ID=key,Number=1,Type=String,Description="description">\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.set_sample_data('key', '1', 'String', 'description')
self.assertEqual(expected, header)
def test_should_parse_valid_filter_header_fields(self):
lines = [
'##fileformat=VCFv4.2\n',
'##FILTER=<ID=key,Description="description">\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.set_filter('key', 'description')
self.assertEqual(expected, header)
def test_should_parse_valid_contig_header_fields(self):
lines = [
'##fileformat=VCFv4.2\n',
'##contig=<ID=key,length=666>\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.set_contig('key', 666)
self.assertEqual(expected, header)
def test_should_parse_required_column_headers(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
self.assertEqual(expected, header)
def test_should_fail_without_required_column_headers(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(
Exception,
re.escape("expected column header line: '#CHROM\\tPOS\\tID\\tREF\\tALT\\tQUAL\\tFILTER'")
):
print(reader.read_header())
def test_should_parse_column_headers_with_format_but_no_samples(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
self.assertEqual(expected, header)
def test_should_parse_column_headers_with_complex_sample_names(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tOWEN_TOBY-RHYS.JONES\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.samples = ['OWEN_TOBY-RHYS.JONES']
self.assertEqual(expected, header)
def test_should_not_parse_column_headers_with_sample_names_containing_white_space(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tOWEN JONES\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(
Exception,
re.escape(
'expected column header line: '
'\'
)
):
print(reader.read_header())
def test_should_fail_with_malformed_format_column_header(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFOO\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(
Exception,
re.escape('expected column header line: \'
):
print(reader.read_header())
def test_should_parse_column_headers_with_samples(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tFOO\tBAR\n',
]
reader = VCFReader(iter(lines))
header = reader.read_header()
expected = Schema()
expected.samples.append('FOO')
expected.samples.append('BAR')
self.assertEqual(expected, header)
def test_should_fail_if_column_header_line_is_missing(self):
lines = [
'##fileformat=VCFv4.2\n',
'the line after the header\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(Exception, 'expected column header line: \'the line after the header\''):
print(reader.read_header())
def test_should_fail_on_unexpected_EOF(self):
lines = [
'##fileformat=VCFv4.2\n',
]
reader = VCFReader(iter(lines))
with self.assertRaisesRegex(Exception, 'unexpected EOF'):
print(reader.read_header())
class TestRecordParsing(unittest.TestCase):
def test_should_parse_single_record(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
'chr0\t0\t.\tP\tQ\t0\tPASS\t\n',
]
reader = VCFReader(iter(lines))
record_count = len(list(reader.read_records()))
self.assertEqual(1, record_count)
def test_should_parse_header_when_parsing_records(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
'chr0\t0\t.\tP\tQ\t0\tPASS\t\n',
]
reader = VCFReader(iter(lines))
self.assertIsNone(reader.header)
list(reader.read_records())
self.assertIsNotNone(reader.header)
def test_should_parse_empty_file(self):
lines = [
'##fileformat=VCFv4.2\n',
'#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n',
]
reader = VCFReader(iter(lines))
record_count = len(list(reader.read_records()))
self.assertEqual(0, record_count)
| true | true |
f72c05338ce0e13464f88b0d16b63a74fd9ad1e2 | 6,580 | py | Python | recognition/alexnet_PD_finetuning.py | ogrenenmakine/VCL-PL-Semi-Supervised-Learning-from-Noisy-Web-Data-with-Variational-Contrastive-Learning | baef25837ce7e073d03f69a095d1992aa18dd2d5 | [
"MIT"
] | null | null | null | recognition/alexnet_PD_finetuning.py | ogrenenmakine/VCL-PL-Semi-Supervised-Learning-from-Noisy-Web-Data-with-Variational-Contrastive-Learning | baef25837ce7e073d03f69a095d1992aa18dd2d5 | [
"MIT"
] | null | null | null | recognition/alexnet_PD_finetuning.py | ogrenenmakine/VCL-PL-Semi-Supervised-Learning-from-Noisy-Web-Data-with-Variational-Contrastive-Learning | baef25837ce7e073d03f69a095d1992aa18dd2d5 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import math
from torch import nn
from torch.autograd import Variable
import torch
import torch.nn.functional as F
import torchvision
import torch.utils.data as data
import torchvision.transforms as transforms
import torchvision.utils as vutils
import numpy as np
from PIL import Image
import os
import matplotlib.pyplot as plt
import time
from torchsummary import summary
import config
from facenet_pytorch import training
from torch.utils.data import DataLoader, SubsetRandomSampler
from torch import optim
from torch.optim.lr_scheduler import MultiStepLR
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms
from PIL import Image
import glob
from utils.collate import collate_custom
import torchvision.models as models
from util import AverageMeter, learning_rate_decay, Logger
import collections
# In[ ]:
transform = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.RandomApply([
transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.1)
], p=0.8),
transforms.RandomGrayscale(0.2),
transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
])
# Root directory for dataset
data_root = "/home/mehmetyavuz/datasets/CelebA128/"
attr_root = "/home/mehmetyavuz/datasets/list_attr_celeba.txt"
# Number of workers for dataloader
workers = 8
# Batch size during training
batch_size = 64
# Spatial size of training images. All images will be resized to this
# size using a transformer.
image_size = (128,128)
epochs = 100
# In[ ]:
class CelebA(data.Dataset):
def __init__(self, data_path, attr_path, image_size, mode, selected_attrs):
super(CelebA, self).__init__()
self.data_path = data_path
att_list = open(attr_path, 'r', encoding='utf-8').readlines()[1].split()
atts = [att_list.index(att) + 1 for att in selected_attrs]
images = np.loadtxt(attr_path, skiprows=2, usecols=[0], dtype=np.str)
labels = np.loadtxt(attr_path, skiprows=2, usecols=atts, dtype=np.int)
self.tf = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
self.tf_a = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.RandomApply([
transforms.ColorJitter(hue=.05, saturation=.05),
], p=0.8),
transforms.RandomGrayscale(0.2),
])
if mode == 'train':
self.images = images[:1627]
self.labels = labels[:1627]
if mode == 'valid':
self.images = images[162770:182637]
self.labels = labels[162770:182637]
if mode == 'test':
self.images = images[182637:]
self.labels = labels[182637:]
self.length = len(self.images)
def __getitem__(self, index):
if index < 16277:
img = self.tf(self.tf_a(Image.open(os.path.join(self.data_path, self.images[index]))))
else:
img = self.tf(Image.open(os.path.join(self.data_path, self.images[index])))
att = torch.tensor((self.labels[index] + 1) // 2)
return img, att.to(torch.float32)
def __len__(self):
return self.length
# In[ ]:
attrs_default = ["5_o_Clock_Shadow", "Arched_Eyebrows", "Attractive", "Bags_Under_Eyes", "Bald", "Bangs", "Big_Lips", "Big_Nose", "Black_Hair", "Blond_Hair", "Blurry", "Brown_Hair", "Bushy_Eyebrows", "Chubby", "Double_Chin", "Eyeglasses", "Goatee", "Gray_Hair", "Heavy_Makeup", "High_Cheekbones", "Male", "Mouth_Slightly_Open", "Mustache", "Narrow_Eyes", "No_Beard", "Oval_Face", "Pale_Skin", "Pointy_Nose", "Receding_Hairline", "Rosy_Cheeks", "Sideburns", "Smiling", "Straight_Hair", "Wavy_Hair", "Wearing_Earrings", "Wearing_Hat", "Wearing_Lipstick", "Wearing_Necklace", "Wearing_Necktie", "Young"]
# In[ ]:
dataset = CelebA(data_root, attr_root, image_size, 'train', attrs_default)
train_loader = torch.utils.data.DataLoader(dataset, num_workers=workers,
batch_size=batch_size, pin_memory=True, collate_fn=collate_custom,
drop_last=True, shuffle=True)
dataset = CelebA(data_root, attr_root, image_size, 'valid', attrs_default)
val_loader = torch.utils.data.DataLoader(dataset,
batch_size=batch_size,
shuffle=False,
num_workers=workers)
dataset = CelebA(data_root, attr_root, image_size, 'test', attrs_default)
test_loader = torch.utils.data.DataLoader(dataset,
batch_size=batch_size,
shuffle=False,
num_workers=workers)
# In[ ]:
# Decide which device we want to run on
device = torch.device("cuda:0")
# In[ ]:
resnet = models.__dict__['alexnet'](pretrained=True)
resnet.classifier[6] = nn.Linear(4096,40,bias=True)
resnet = torch.nn.DataParallel(resnet)
resnet.cuda()
resnet.load_state_dict(torch.load('alexnet_pseudolabeling_001_0_normal.pth'))
# In[ ]:
optimizer = optim.Adam(resnet.parameters(), lr=0.00001)
scheduler = None
# In[ ]:
loss_fn = torch.nn.BCEWithLogitsLoss()
metrics = {
'acc': training.accuracy_ml
}
# In[ ]:
print('\n\nInitial')
print('-' * 10)
val_loss = 1
for epoch in range(epochs):
print('\nEpoch {}/{}'.format(epoch + 1, epochs))
print('-' * 10)
resnet.train()
training.pass_epoch(
resnet, loss_fn, train_loader, optimizer, scheduler,
batch_metrics=metrics, show_running=True, device=device,
#writer=writer
)
#if epoch + 1 >= 30:
resnet.eval()
val_metrics = training.pass_epoch(
resnet, loss_fn, val_loader,
batch_metrics=metrics, show_running=True, device=device,
#writer=writer
)
if val_metrics[0].item() < val_loss:
val_loss = val_metrics[0].item()
print('Test set Accuracy Lowest Validation Loss:')
training.pass_epoch(
resnet, loss_fn, test_loader,
batch_metrics=metrics, show_running=True, device=device,
#writer=writer
)
torch.save(resnet.state_dict(), "alexnet_PD_001_0_normal.pth")
#writer.close()
# In[ ]:
# In[ ]:
# In[ ]:
| 29.375 | 600 | 0.632827 |
import math
from torch import nn
from torch.autograd import Variable
import torch
import torch.nn.functional as F
import torchvision
import torch.utils.data as data
import torchvision.transforms as transforms
import torchvision.utils as vutils
import numpy as np
from PIL import Image
import os
import matplotlib.pyplot as plt
import time
from torchsummary import summary
import config
from facenet_pytorch import training
from torch.utils.data import DataLoader, SubsetRandomSampler
from torch import optim
from torch.optim.lr_scheduler import MultiStepLR
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms
from PIL import Image
import glob
from utils.collate import collate_custom
import torchvision.models as models
from util import AverageMeter, learning_rate_decay, Logger
import collections
transform = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.RandomApply([
transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.1)
], p=0.8),
transforms.RandomGrayscale(0.2),
transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
])
data_root = "/home/mehmetyavuz/datasets/CelebA128/"
attr_root = "/home/mehmetyavuz/datasets/list_attr_celeba.txt"
workers = 8
batch_size = 64
image_size = (128,128)
epochs = 100
class CelebA(data.Dataset):
def __init__(self, data_path, attr_path, image_size, mode, selected_attrs):
super(CelebA, self).__init__()
self.data_path = data_path
att_list = open(attr_path, 'r', encoding='utf-8').readlines()[1].split()
atts = [att_list.index(att) + 1 for att in selected_attrs]
images = np.loadtxt(attr_path, skiprows=2, usecols=[0], dtype=np.str)
labels = np.loadtxt(attr_path, skiprows=2, usecols=atts, dtype=np.int)
self.tf = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
self.tf_a = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.RandomApply([
transforms.ColorJitter(hue=.05, saturation=.05),
], p=0.8),
transforms.RandomGrayscale(0.2),
])
if mode == 'train':
self.images = images[:1627]
self.labels = labels[:1627]
if mode == 'valid':
self.images = images[162770:182637]
self.labels = labels[162770:182637]
if mode == 'test':
self.images = images[182637:]
self.labels = labels[182637:]
self.length = len(self.images)
def __getitem__(self, index):
if index < 16277:
img = self.tf(self.tf_a(Image.open(os.path.join(self.data_path, self.images[index]))))
else:
img = self.tf(Image.open(os.path.join(self.data_path, self.images[index])))
att = torch.tensor((self.labels[index] + 1) // 2)
return img, att.to(torch.float32)
def __len__(self):
return self.length
attrs_default = ["5_o_Clock_Shadow", "Arched_Eyebrows", "Attractive", "Bags_Under_Eyes", "Bald", "Bangs", "Big_Lips", "Big_Nose", "Black_Hair", "Blond_Hair", "Blurry", "Brown_Hair", "Bushy_Eyebrows", "Chubby", "Double_Chin", "Eyeglasses", "Goatee", "Gray_Hair", "Heavy_Makeup", "High_Cheekbones", "Male", "Mouth_Slightly_Open", "Mustache", "Narrow_Eyes", "No_Beard", "Oval_Face", "Pale_Skin", "Pointy_Nose", "Receding_Hairline", "Rosy_Cheeks", "Sideburns", "Smiling", "Straight_Hair", "Wavy_Hair", "Wearing_Earrings", "Wearing_Hat", "Wearing_Lipstick", "Wearing_Necklace", "Wearing_Necktie", "Young"]
dataset = CelebA(data_root, attr_root, image_size, 'train', attrs_default)
train_loader = torch.utils.data.DataLoader(dataset, num_workers=workers,
batch_size=batch_size, pin_memory=True, collate_fn=collate_custom,
drop_last=True, shuffle=True)
dataset = CelebA(data_root, attr_root, image_size, 'valid', attrs_default)
val_loader = torch.utils.data.DataLoader(dataset,
batch_size=batch_size,
shuffle=False,
num_workers=workers)
dataset = CelebA(data_root, attr_root, image_size, 'test', attrs_default)
test_loader = torch.utils.data.DataLoader(dataset,
batch_size=batch_size,
shuffle=False,
num_workers=workers)
device = torch.device("cuda:0")
resnet = models.__dict__['alexnet'](pretrained=True)
resnet.classifier[6] = nn.Linear(4096,40,bias=True)
resnet = torch.nn.DataParallel(resnet)
resnet.cuda()
resnet.load_state_dict(torch.load('alexnet_pseudolabeling_001_0_normal.pth'))
optimizer = optim.Adam(resnet.parameters(), lr=0.00001)
scheduler = None
loss_fn = torch.nn.BCEWithLogitsLoss()
metrics = {
'acc': training.accuracy_ml
}
print('\n\nInitial')
print('-' * 10)
val_loss = 1
for epoch in range(epochs):
print('\nEpoch {}/{}'.format(epoch + 1, epochs))
print('-' * 10)
resnet.train()
training.pass_epoch(
resnet, loss_fn, train_loader, optimizer, scheduler,
batch_metrics=metrics, show_running=True, device=device,
)
resnet.eval()
val_metrics = training.pass_epoch(
resnet, loss_fn, val_loader,
batch_metrics=metrics, show_running=True, device=device,
)
if val_metrics[0].item() < val_loss:
val_loss = val_metrics[0].item()
print('Test set Accuracy Lowest Validation Loss:')
training.pass_epoch(
resnet, loss_fn, test_loader,
batch_metrics=metrics, show_running=True, device=device,
)
torch.save(resnet.state_dict(), "alexnet_PD_001_0_normal.pth")
| true | true |
f72c055d3838a4636e2e7b02c3f27e7b13404fdf | 6,398 | py | Python | skyscrapers/skyscrapers.py | Adeon18/skyscrapers.py | 8dbd6e9d648a56f8dbab7de50ef6c606e4aed18e | [
"MIT"
] | null | null | null | skyscrapers/skyscrapers.py | Adeon18/skyscrapers.py | 8dbd6e9d648a56f8dbab7de50ef6c606e4aed18e | [
"MIT"
] | null | null | null | skyscrapers/skyscrapers.py | Adeon18/skyscrapers.py | 8dbd6e9d648a56f8dbab7de50ef6c606e4aed18e | [
"MIT"
] | null | null | null | """
https://github.com/Adeon18/skyscrapers
"""
def read_input(path: str) -> list:
"""
Read game board file from path.
Return list of str.
"""
with open(path, "r") as file:
output_lst = file.read().split("\n")
output_lst = output_lst[:-1]
return output_lst
def left_to_right_check(input_line: str, pivot: int) -> bool:
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most
hint is visible looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the input_line.
>>> left_to_right_check("412453*", 4)
True
>>> left_to_right_check("452453*", 5)
False
>>> left_to_right_check("512345*", 5)
True
>>> left_to_right_check("4124531", 4)
True
"""
row = input_line
max_num = 0
count = 0
for _, num in enumerate(row[1:-1]):
# If the row is *, we move on to the next
if num == "*":
continue
# Check if the current building is the one we need
if int(num) > max_num:
max_num = int(num)
count += 1
if count == pivot:
return True
return False
def check_not_finished_board(board: list) -> bool:
"""
Check if skyscraper board is not finished, i.e.,
'?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*',\
'4?????*', '*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>> check_not_finished_board(['***21**', '412453*',\
'423145*', '*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_not_finished_board(['***21**', '412453*',\
'423145*', '*5?3215', '*35214*', '*41532*', '*2*1***'])
False
"""
for row in board:
if "?" in row:
return False
return True
def check_uniqueness_in_rows(board: list) -> bool:
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length,
False otherwise.
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*',\
'*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_uniqueness_in_rows(['***21**', '452453*', '423145*',\
'*543215', '*35214*', '*41532*', '*2*1***'])
False
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*',\
'*553215', '*35214*', '*41532*', '*2*1***'])
False
"""
# We chop each row
for row in board[1:-1]:
elements_int = []
for elem in row[1:-1]:
# If element can't be converted to int, it is skipped
try:
if int(elem) in elements_int:
return False
else:
elements_int.append(int(elem))
except:
continue
return True
def check_horizontal_visibility(board: list) -> bool:
"""
Check row-wise visibility (left-right and vice versa)
Return True if all horizontal hints are satisfiable,
i.e., for line 412453* , hint is 4, and 1245 are the four buildings
that could be observed from the hint looking to the right.
>>> check_horizontal_visibility(['***21**', '412453*', '423145*',\
'*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_horizontal_visibility(['***21**', '452453*', '423145*',\
'*543215', '*35214*', '*41532*', '*2*1***'])
False
>>> check_horizontal_visibility(['***21**', '452413*', '423145*',\
'*543215', '*35214*', '*41532*', '*2*1***'])
False
"""
# Our right hint(default=*)
right_req = "*"
for row in board[1:-1]:
# We keep track of the max element and seen buildings
right_flag = 0
max_elem_right = 0
# We skip if there's no hint
if row[0] == "*":
continue
else:
right_req = int(row[0])
for elem in row[1:-1]:
# Check if the following element is bigger
if int(elem) > max_elem_right:
max_elem_right = int(elem)
right_flag += 1
# If the hints aren't met, we return False
if right_flag != right_req:
return False
# Same code, another direction, rewritten for better readability
left_req = "*"
for row in board[1:-1]:
left_flag = 0
max_elem_left = 0
if row[-1] == "*":
continue
else:
left_req = int(row[-1])
for elem in row[1:-1][::-1]:
if int(elem) > max_elem_left:
max_elem_left = int(elem)
left_flag += 1
# print('left ', right_flag, right_req)
if left_flag != left_req:
return False
return True
def check_columns(board: list) -> bool:
"""
Check column-wise compliance of the board for
uniqueness (buildings of unique height)
and visibility (top-bottom and vice versa).
Same as for horizontal cases, but aggregated in one
function for vertical case, i.e. columns.
>>> check_columns(['***21**', '412453*', '423145*',\
'*543215', '*35214*', '*41532*', '*2*1***'])
True
>>> check_columns(['***21**', '412453*', '423145*',\
'*543215', '*35214*', '*41232*', '*2*1***'])
False
>>> check_columns(['***21**', '412553*', '423145*',\
'*543215', '*35214*', '*41532*', '*2*1***'])
False
"""
new_lst = []
# Flip and check horisontally
for i, row in enumerate(board):
new_elem = ""
for j, _ in enumerate(row):
new_elem += board[j][i]
new_lst.append(new_elem)
if check_uniqueness_in_rows(new_lst) and check_not_finished_board(new_lst):
return check_horizontal_visibility(new_lst)
return False
def check_skyscrapers(input_path: str) -> bool:
"""
Main function to check the status of skyscraper game board.
Return True if the board status is compliant with the rules,
False otherwise.
"""
board = read_input(input_path)
# If everything is met return True
if (
check_horizontal_visibility(board)
and check_columns(board)
and check_uniqueness_in_rows(board)
and check_not_finished_board(board)
):
return True
return False
if __name__ == "__main__":
import doctest
print(doctest.testmod())
| 29.081818 | 79 | 0.557205 |
def read_input(path: str) -> list:
with open(path, "r") as file:
output_lst = file.read().split("\n")
output_lst = output_lst[:-1]
return output_lst
def left_to_right_check(input_line: str, pivot: int) -> bool:
row = input_line
max_num = 0
count = 0
for _, num in enumerate(row[1:-1]):
if num == "*":
continue
if int(num) > max_num:
max_num = int(num)
count += 1
if count == pivot:
return True
return False
def check_not_finished_board(board: list) -> bool:
for row in board:
if "?" in row:
return False
return True
def check_uniqueness_in_rows(board: list) -> bool:
for row in board[1:-1]:
elements_int = []
for elem in row[1:-1]:
try:
if int(elem) in elements_int:
return False
else:
elements_int.append(int(elem))
except:
continue
return True
def check_horizontal_visibility(board: list) -> bool:
# Our right hint(default=*)
right_req = "*"
for row in board[1:-1]:
# We keep track of the max element and seen buildings
right_flag = 0
max_elem_right = 0
# We skip if there's no hint
if row[0] == "*":
continue
else:
right_req = int(row[0])
for elem in row[1:-1]:
if int(elem) > max_elem_right:
max_elem_right = int(elem)
right_flag += 1
if right_flag != right_req:
return False
# Same code, another direction, rewritten for better readability
left_req = "*"
for row in board[1:-1]:
left_flag = 0
max_elem_left = 0
if row[-1] == "*":
continue
else:
left_req = int(row[-1])
for elem in row[1:-1][::-1]:
if int(elem) > max_elem_left:
max_elem_left = int(elem)
left_flag += 1
# print('left ', right_flag, right_req)
if left_flag != left_req:
return False
return True
def check_columns(board: list) -> bool:
new_lst = []
# Flip and check horisontally
for i, row in enumerate(board):
new_elem = ""
for j, _ in enumerate(row):
new_elem += board[j][i]
new_lst.append(new_elem)
if check_uniqueness_in_rows(new_lst) and check_not_finished_board(new_lst):
return check_horizontal_visibility(new_lst)
return False
def check_skyscrapers(input_path: str) -> bool:
board = read_input(input_path)
# If everything is met return True
if (
check_horizontal_visibility(board)
and check_columns(board)
and check_uniqueness_in_rows(board)
and check_not_finished_board(board)
):
return True
return False
if __name__ == "__main__":
import doctest
print(doctest.testmod())
| true | true |
f72c08bf0eb0d7eb846f18ba055eede40647f94e | 30,345 | py | Python | sdk/python/pulumi_google_native/apigee/v1/organization.py | AaronFriel/pulumi-google-native | 75d1cda425e33d4610348972cd70bddf35f1770d | [
"Apache-2.0"
] | 44 | 2021-04-18T23:00:48.000Z | 2022-02-14T17:43:15.000Z | sdk/python/pulumi_google_native/apigee/v1/organization.py | AaronFriel/pulumi-google-native | 75d1cda425e33d4610348972cd70bddf35f1770d | [
"Apache-2.0"
] | 354 | 2021-04-16T16:48:39.000Z | 2022-03-31T17:16:39.000Z | sdk/python/pulumi_google_native/apigee/v1/organization.py | AaronFriel/pulumi-google-native | 75d1cda425e33d4610348972cd70bddf35f1770d | [
"Apache-2.0"
] | 8 | 2021-04-24T17:46:51.000Z | 2022-01-05T10:40:21.000Z | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
from ._enums import *
from ._inputs import *
__all__ = ['OrganizationArgs', 'Organization']
@pulumi.input_type
class OrganizationArgs:
def __init__(__self__, *,
analytics_region: pulumi.Input[str],
parent: pulumi.Input[str],
runtime_type: pulumi.Input['OrganizationRuntimeType'],
addons_config: Optional[pulumi.Input['GoogleCloudApigeeV1AddonsConfigArgs']] = None,
attributes: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
authorized_network: Optional[pulumi.Input[str]] = None,
billing_type: Optional[pulumi.Input['OrganizationBillingType']] = None,
customer_name: Optional[pulumi.Input[str]] = None,
description: Optional[pulumi.Input[str]] = None,
display_name: Optional[pulumi.Input[str]] = None,
portal_disabled: Optional[pulumi.Input[bool]] = None,
properties: Optional[pulumi.Input['GoogleCloudApigeeV1PropertiesArgs']] = None,
runtime_database_encryption_key_name: Optional[pulumi.Input[str]] = None,
type: Optional[pulumi.Input['OrganizationType']] = None):
"""
The set of arguments for constructing a Organization resource.
:param pulumi.Input[str] analytics_region: Primary GCP region for analytics data storage. For valid values, see [Create an Apigee organization](https://cloud.google.com/apigee/docs/api-platform/get-started/create-org).
:param pulumi.Input['OrganizationRuntimeType'] runtime_type: Runtime type of the Apigee organization based on the Apigee subscription purchased.
:param pulumi.Input['GoogleCloudApigeeV1AddonsConfigArgs'] addons_config: Addon configurations of the Apigee organization.
:param pulumi.Input[Sequence[pulumi.Input[str]]] attributes: Not used by Apigee.
:param pulumi.Input[str] authorized_network: Compute Engine network used for Service Networking to be peered with Apigee runtime instances. See [Getting started with the Service Networking API](https://cloud.google.com/service-infrastructure/docs/service-networking/getting-started). Valid only when [RuntimeType](#RuntimeType) is set to `CLOUD`. The value must be set before the creation of a runtime instance and can be updated only when there are no runtime instances. For example: `default`. Apigee also supports shared VPC (that is, the host network project is not the same as the one that is peering with Apigee). See [Shared VPC overview](https://cloud.google.com/vpc/docs/shared-vpc). To use a shared VPC network, use the following format: `projects/{host-project-id}/{region}/networks/{network-name}`. For example: `projects/my-sharedvpc-host/global/networks/mynetwork` **Note:** Not supported for Apigee hybrid.
:param pulumi.Input['OrganizationBillingType'] billing_type: Billing type of the Apigee organization. See [Apigee pricing](https://cloud.google.com/apigee/pricing).
:param pulumi.Input[str] customer_name: Not used by Apigee.
:param pulumi.Input[str] description: Description of the Apigee organization.
:param pulumi.Input[str] display_name: Display name for the Apigee organization. Unused, but reserved for future use.
:param pulumi.Input[bool] portal_disabled: Configuration for the Portals settings.
:param pulumi.Input['GoogleCloudApigeeV1PropertiesArgs'] properties: Properties defined in the Apigee organization profile.
:param pulumi.Input[str] runtime_database_encryption_key_name: Cloud KMS key name used for encrypting the data that is stored and replicated across runtime instances. Update is not allowed after the organization is created. Required when [RuntimeType](#RuntimeType) is `CLOUD`. If not specified when [RuntimeType](#RuntimeType) is `TRIAL`, a Google-Managed encryption key will be used. For example: "projects/foo/locations/us/keyRings/bar/cryptoKeys/baz". **Note:** Not supported for Apigee hybrid.
:param pulumi.Input['OrganizationType'] type: Not used by Apigee.
"""
pulumi.set(__self__, "analytics_region", analytics_region)
pulumi.set(__self__, "parent", parent)
pulumi.set(__self__, "runtime_type", runtime_type)
if addons_config is not None:
pulumi.set(__self__, "addons_config", addons_config)
if attributes is not None:
pulumi.set(__self__, "attributes", attributes)
if authorized_network is not None:
pulumi.set(__self__, "authorized_network", authorized_network)
if billing_type is not None:
pulumi.set(__self__, "billing_type", billing_type)
if customer_name is not None:
pulumi.set(__self__, "customer_name", customer_name)
if description is not None:
pulumi.set(__self__, "description", description)
if display_name is not None:
pulumi.set(__self__, "display_name", display_name)
if portal_disabled is not None:
pulumi.set(__self__, "portal_disabled", portal_disabled)
if properties is not None:
pulumi.set(__self__, "properties", properties)
if runtime_database_encryption_key_name is not None:
pulumi.set(__self__, "runtime_database_encryption_key_name", runtime_database_encryption_key_name)
if type is not None:
pulumi.set(__self__, "type", type)
@property
@pulumi.getter(name="analyticsRegion")
def analytics_region(self) -> pulumi.Input[str]:
"""
Primary GCP region for analytics data storage. For valid values, see [Create an Apigee organization](https://cloud.google.com/apigee/docs/api-platform/get-started/create-org).
"""
return pulumi.get(self, "analytics_region")
@analytics_region.setter
def analytics_region(self, value: pulumi.Input[str]):
pulumi.set(self, "analytics_region", value)
@property
@pulumi.getter
def parent(self) -> pulumi.Input[str]:
return pulumi.get(self, "parent")
@parent.setter
def parent(self, value: pulumi.Input[str]):
pulumi.set(self, "parent", value)
@property
@pulumi.getter(name="runtimeType")
def runtime_type(self) -> pulumi.Input['OrganizationRuntimeType']:
"""
Runtime type of the Apigee organization based on the Apigee subscription purchased.
"""
return pulumi.get(self, "runtime_type")
@runtime_type.setter
def runtime_type(self, value: pulumi.Input['OrganizationRuntimeType']):
pulumi.set(self, "runtime_type", value)
@property
@pulumi.getter(name="addonsConfig")
def addons_config(self) -> Optional[pulumi.Input['GoogleCloudApigeeV1AddonsConfigArgs']]:
"""
Addon configurations of the Apigee organization.
"""
return pulumi.get(self, "addons_config")
@addons_config.setter
def addons_config(self, value: Optional[pulumi.Input['GoogleCloudApigeeV1AddonsConfigArgs']]):
pulumi.set(self, "addons_config", value)
@property
@pulumi.getter
def attributes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
Not used by Apigee.
"""
return pulumi.get(self, "attributes")
@attributes.setter
def attributes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "attributes", value)
@property
@pulumi.getter(name="authorizedNetwork")
def authorized_network(self) -> Optional[pulumi.Input[str]]:
"""
Compute Engine network used for Service Networking to be peered with Apigee runtime instances. See [Getting started with the Service Networking API](https://cloud.google.com/service-infrastructure/docs/service-networking/getting-started). Valid only when [RuntimeType](#RuntimeType) is set to `CLOUD`. The value must be set before the creation of a runtime instance and can be updated only when there are no runtime instances. For example: `default`. Apigee also supports shared VPC (that is, the host network project is not the same as the one that is peering with Apigee). See [Shared VPC overview](https://cloud.google.com/vpc/docs/shared-vpc). To use a shared VPC network, use the following format: `projects/{host-project-id}/{region}/networks/{network-name}`. For example: `projects/my-sharedvpc-host/global/networks/mynetwork` **Note:** Not supported for Apigee hybrid.
"""
return pulumi.get(self, "authorized_network")
@authorized_network.setter
def authorized_network(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "authorized_network", value)
@property
@pulumi.getter(name="billingType")
def billing_type(self) -> Optional[pulumi.Input['OrganizationBillingType']]:
"""
Billing type of the Apigee organization. See [Apigee pricing](https://cloud.google.com/apigee/pricing).
"""
return pulumi.get(self, "billing_type")
@billing_type.setter
def billing_type(self, value: Optional[pulumi.Input['OrganizationBillingType']]):
pulumi.set(self, "billing_type", value)
@property
@pulumi.getter(name="customerName")
def customer_name(self) -> Optional[pulumi.Input[str]]:
"""
Not used by Apigee.
"""
return pulumi.get(self, "customer_name")
@customer_name.setter
def customer_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "customer_name", value)
@property
@pulumi.getter
def description(self) -> Optional[pulumi.Input[str]]:
"""
Description of the Apigee organization.
"""
return pulumi.get(self, "description")
@description.setter
def description(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "description", value)
@property
@pulumi.getter(name="displayName")
def display_name(self) -> Optional[pulumi.Input[str]]:
"""
Display name for the Apigee organization. Unused, but reserved for future use.
"""
return pulumi.get(self, "display_name")
@display_name.setter
def display_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "display_name", value)
@property
@pulumi.getter(name="portalDisabled")
def portal_disabled(self) -> Optional[pulumi.Input[bool]]:
"""
Configuration for the Portals settings.
"""
return pulumi.get(self, "portal_disabled")
@portal_disabled.setter
def portal_disabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "portal_disabled", value)
@property
@pulumi.getter
def properties(self) -> Optional[pulumi.Input['GoogleCloudApigeeV1PropertiesArgs']]:
"""
Properties defined in the Apigee organization profile.
"""
return pulumi.get(self, "properties")
@properties.setter
def properties(self, value: Optional[pulumi.Input['GoogleCloudApigeeV1PropertiesArgs']]):
pulumi.set(self, "properties", value)
@property
@pulumi.getter(name="runtimeDatabaseEncryptionKeyName")
def runtime_database_encryption_key_name(self) -> Optional[pulumi.Input[str]]:
"""
Cloud KMS key name used for encrypting the data that is stored and replicated across runtime instances. Update is not allowed after the organization is created. Required when [RuntimeType](#RuntimeType) is `CLOUD`. If not specified when [RuntimeType](#RuntimeType) is `TRIAL`, a Google-Managed encryption key will be used. For example: "projects/foo/locations/us/keyRings/bar/cryptoKeys/baz". **Note:** Not supported for Apigee hybrid.
"""
return pulumi.get(self, "runtime_database_encryption_key_name")
@runtime_database_encryption_key_name.setter
def runtime_database_encryption_key_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "runtime_database_encryption_key_name", value)
@property
@pulumi.getter
def type(self) -> Optional[pulumi.Input['OrganizationType']]:
"""
Not used by Apigee.
"""
return pulumi.get(self, "type")
@type.setter
def type(self, value: Optional[pulumi.Input['OrganizationType']]):
pulumi.set(self, "type", value)
class Organization(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
addons_config: Optional[pulumi.Input[pulumi.InputType['GoogleCloudApigeeV1AddonsConfigArgs']]] = None,
analytics_region: Optional[pulumi.Input[str]] = None,
attributes: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
authorized_network: Optional[pulumi.Input[str]] = None,
billing_type: Optional[pulumi.Input['OrganizationBillingType']] = None,
customer_name: Optional[pulumi.Input[str]] = None,
description: Optional[pulumi.Input[str]] = None,
display_name: Optional[pulumi.Input[str]] = None,
parent: Optional[pulumi.Input[str]] = None,
portal_disabled: Optional[pulumi.Input[bool]] = None,
properties: Optional[pulumi.Input[pulumi.InputType['GoogleCloudApigeeV1PropertiesArgs']]] = None,
runtime_database_encryption_key_name: Optional[pulumi.Input[str]] = None,
runtime_type: Optional[pulumi.Input['OrganizationRuntimeType']] = None,
type: Optional[pulumi.Input['OrganizationType']] = None,
__props__=None):
"""
Creates an Apigee organization. See [Create an Apigee organization](https://cloud.google.com/apigee/docs/api-platform/get-started/create-org).
Auto-naming is currently not supported for this resource.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[pulumi.InputType['GoogleCloudApigeeV1AddonsConfigArgs']] addons_config: Addon configurations of the Apigee organization.
:param pulumi.Input[str] analytics_region: Primary GCP region for analytics data storage. For valid values, see [Create an Apigee organization](https://cloud.google.com/apigee/docs/api-platform/get-started/create-org).
:param pulumi.Input[Sequence[pulumi.Input[str]]] attributes: Not used by Apigee.
:param pulumi.Input[str] authorized_network: Compute Engine network used for Service Networking to be peered with Apigee runtime instances. See [Getting started with the Service Networking API](https://cloud.google.com/service-infrastructure/docs/service-networking/getting-started). Valid only when [RuntimeType](#RuntimeType) is set to `CLOUD`. The value must be set before the creation of a runtime instance and can be updated only when there are no runtime instances. For example: `default`. Apigee also supports shared VPC (that is, the host network project is not the same as the one that is peering with Apigee). See [Shared VPC overview](https://cloud.google.com/vpc/docs/shared-vpc). To use a shared VPC network, use the following format: `projects/{host-project-id}/{region}/networks/{network-name}`. For example: `projects/my-sharedvpc-host/global/networks/mynetwork` **Note:** Not supported for Apigee hybrid.
:param pulumi.Input['OrganizationBillingType'] billing_type: Billing type of the Apigee organization. See [Apigee pricing](https://cloud.google.com/apigee/pricing).
:param pulumi.Input[str] customer_name: Not used by Apigee.
:param pulumi.Input[str] description: Description of the Apigee organization.
:param pulumi.Input[str] display_name: Display name for the Apigee organization. Unused, but reserved for future use.
:param pulumi.Input[bool] portal_disabled: Configuration for the Portals settings.
:param pulumi.Input[pulumi.InputType['GoogleCloudApigeeV1PropertiesArgs']] properties: Properties defined in the Apigee organization profile.
:param pulumi.Input[str] runtime_database_encryption_key_name: Cloud KMS key name used for encrypting the data that is stored and replicated across runtime instances. Update is not allowed after the organization is created. Required when [RuntimeType](#RuntimeType) is `CLOUD`. If not specified when [RuntimeType](#RuntimeType) is `TRIAL`, a Google-Managed encryption key will be used. For example: "projects/foo/locations/us/keyRings/bar/cryptoKeys/baz". **Note:** Not supported for Apigee hybrid.
:param pulumi.Input['OrganizationRuntimeType'] runtime_type: Runtime type of the Apigee organization based on the Apigee subscription purchased.
:param pulumi.Input['OrganizationType'] type: Not used by Apigee.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: OrganizationArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
Creates an Apigee organization. See [Create an Apigee organization](https://cloud.google.com/apigee/docs/api-platform/get-started/create-org).
Auto-naming is currently not supported for this resource.
:param str resource_name: The name of the resource.
:param OrganizationArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(OrganizationArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
addons_config: Optional[pulumi.Input[pulumi.InputType['GoogleCloudApigeeV1AddonsConfigArgs']]] = None,
analytics_region: Optional[pulumi.Input[str]] = None,
attributes: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
authorized_network: Optional[pulumi.Input[str]] = None,
billing_type: Optional[pulumi.Input['OrganizationBillingType']] = None,
customer_name: Optional[pulumi.Input[str]] = None,
description: Optional[pulumi.Input[str]] = None,
display_name: Optional[pulumi.Input[str]] = None,
parent: Optional[pulumi.Input[str]] = None,
portal_disabled: Optional[pulumi.Input[bool]] = None,
properties: Optional[pulumi.Input[pulumi.InputType['GoogleCloudApigeeV1PropertiesArgs']]] = None,
runtime_database_encryption_key_name: Optional[pulumi.Input[str]] = None,
runtime_type: Optional[pulumi.Input['OrganizationRuntimeType']] = None,
type: Optional[pulumi.Input['OrganizationType']] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = OrganizationArgs.__new__(OrganizationArgs)
__props__.__dict__["addons_config"] = addons_config
if analytics_region is None and not opts.urn:
raise TypeError("Missing required property 'analytics_region'")
__props__.__dict__["analytics_region"] = analytics_region
__props__.__dict__["attributes"] = attributes
__props__.__dict__["authorized_network"] = authorized_network
__props__.__dict__["billing_type"] = billing_type
__props__.__dict__["customer_name"] = customer_name
__props__.__dict__["description"] = description
__props__.__dict__["display_name"] = display_name
if parent is None and not opts.urn:
raise TypeError("Missing required property 'parent'")
__props__.__dict__["parent"] = parent
__props__.__dict__["portal_disabled"] = portal_disabled
__props__.__dict__["properties"] = properties
__props__.__dict__["runtime_database_encryption_key_name"] = runtime_database_encryption_key_name
if runtime_type is None and not opts.urn:
raise TypeError("Missing required property 'runtime_type'")
__props__.__dict__["runtime_type"] = runtime_type
__props__.__dict__["type"] = type
__props__.__dict__["ca_certificate"] = None
__props__.__dict__["created_at"] = None
__props__.__dict__["environments"] = None
__props__.__dict__["expires_at"] = None
__props__.__dict__["last_modified_at"] = None
__props__.__dict__["name"] = None
__props__.__dict__["project"] = None
__props__.__dict__["state"] = None
super(Organization, __self__).__init__(
'google-native:apigee/v1:Organization',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'Organization':
"""
Get an existing Organization resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = OrganizationArgs.__new__(OrganizationArgs)
__props__.__dict__["addons_config"] = None
__props__.__dict__["analytics_region"] = None
__props__.__dict__["attributes"] = None
__props__.__dict__["authorized_network"] = None
__props__.__dict__["billing_type"] = None
__props__.__dict__["ca_certificate"] = None
__props__.__dict__["created_at"] = None
__props__.__dict__["customer_name"] = None
__props__.__dict__["description"] = None
__props__.__dict__["display_name"] = None
__props__.__dict__["environments"] = None
__props__.__dict__["expires_at"] = None
__props__.__dict__["last_modified_at"] = None
__props__.__dict__["name"] = None
__props__.__dict__["portal_disabled"] = None
__props__.__dict__["project"] = None
__props__.__dict__["properties"] = None
__props__.__dict__["runtime_database_encryption_key_name"] = None
__props__.__dict__["runtime_type"] = None
__props__.__dict__["state"] = None
__props__.__dict__["type"] = None
return Organization(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="addonsConfig")
def addons_config(self) -> pulumi.Output['outputs.GoogleCloudApigeeV1AddonsConfigResponse']:
"""
Addon configurations of the Apigee organization.
"""
return pulumi.get(self, "addons_config")
@property
@pulumi.getter(name="analyticsRegion")
def analytics_region(self) -> pulumi.Output[str]:
"""
Primary GCP region for analytics data storage. For valid values, see [Create an Apigee organization](https://cloud.google.com/apigee/docs/api-platform/get-started/create-org).
"""
return pulumi.get(self, "analytics_region")
@property
@pulumi.getter
def attributes(self) -> pulumi.Output[Sequence[str]]:
"""
Not used by Apigee.
"""
return pulumi.get(self, "attributes")
@property
@pulumi.getter(name="authorizedNetwork")
def authorized_network(self) -> pulumi.Output[str]:
"""
Compute Engine network used for Service Networking to be peered with Apigee runtime instances. See [Getting started with the Service Networking API](https://cloud.google.com/service-infrastructure/docs/service-networking/getting-started). Valid only when [RuntimeType](#RuntimeType) is set to `CLOUD`. The value must be set before the creation of a runtime instance and can be updated only when there are no runtime instances. For example: `default`. Apigee also supports shared VPC (that is, the host network project is not the same as the one that is peering with Apigee). See [Shared VPC overview](https://cloud.google.com/vpc/docs/shared-vpc). To use a shared VPC network, use the following format: `projects/{host-project-id}/{region}/networks/{network-name}`. For example: `projects/my-sharedvpc-host/global/networks/mynetwork` **Note:** Not supported for Apigee hybrid.
"""
return pulumi.get(self, "authorized_network")
@property
@pulumi.getter(name="billingType")
def billing_type(self) -> pulumi.Output[str]:
"""
Billing type of the Apigee organization. See [Apigee pricing](https://cloud.google.com/apigee/pricing).
"""
return pulumi.get(self, "billing_type")
@property
@pulumi.getter(name="caCertificate")
def ca_certificate(self) -> pulumi.Output[str]:
"""
Base64-encoded public certificate for the root CA of the Apigee organization. Valid only when [RuntimeType](#RuntimeType) is `CLOUD`.
"""
return pulumi.get(self, "ca_certificate")
@property
@pulumi.getter(name="createdAt")
def created_at(self) -> pulumi.Output[str]:
"""
Time that the Apigee organization was created in milliseconds since epoch.
"""
return pulumi.get(self, "created_at")
@property
@pulumi.getter(name="customerName")
def customer_name(self) -> pulumi.Output[str]:
"""
Not used by Apigee.
"""
return pulumi.get(self, "customer_name")
@property
@pulumi.getter
def description(self) -> pulumi.Output[str]:
"""
Description of the Apigee organization.
"""
return pulumi.get(self, "description")
@property
@pulumi.getter(name="displayName")
def display_name(self) -> pulumi.Output[str]:
"""
Display name for the Apigee organization. Unused, but reserved for future use.
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter
def environments(self) -> pulumi.Output[Sequence[str]]:
"""
List of environments in the Apigee organization.
"""
return pulumi.get(self, "environments")
@property
@pulumi.getter(name="expiresAt")
def expires_at(self) -> pulumi.Output[str]:
"""
Time that the Apigee organization is scheduled for deletion.
"""
return pulumi.get(self, "expires_at")
@property
@pulumi.getter(name="lastModifiedAt")
def last_modified_at(self) -> pulumi.Output[str]:
"""
Time that the Apigee organization was last modified in milliseconds since epoch.
"""
return pulumi.get(self, "last_modified_at")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
Name of the Apigee organization.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="portalDisabled")
def portal_disabled(self) -> pulumi.Output[bool]:
"""
Configuration for the Portals settings.
"""
return pulumi.get(self, "portal_disabled")
@property
@pulumi.getter
def project(self) -> pulumi.Output[str]:
"""
Project ID associated with the Apigee organization.
"""
return pulumi.get(self, "project")
@property
@pulumi.getter
def properties(self) -> pulumi.Output['outputs.GoogleCloudApigeeV1PropertiesResponse']:
"""
Properties defined in the Apigee organization profile.
"""
return pulumi.get(self, "properties")
@property
@pulumi.getter(name="runtimeDatabaseEncryptionKeyName")
def runtime_database_encryption_key_name(self) -> pulumi.Output[str]:
"""
Cloud KMS key name used for encrypting the data that is stored and replicated across runtime instances. Update is not allowed after the organization is created. Required when [RuntimeType](#RuntimeType) is `CLOUD`. If not specified when [RuntimeType](#RuntimeType) is `TRIAL`, a Google-Managed encryption key will be used. For example: "projects/foo/locations/us/keyRings/bar/cryptoKeys/baz". **Note:** Not supported for Apigee hybrid.
"""
return pulumi.get(self, "runtime_database_encryption_key_name")
@property
@pulumi.getter(name="runtimeType")
def runtime_type(self) -> pulumi.Output[str]:
"""
Runtime type of the Apigee organization based on the Apigee subscription purchased.
"""
return pulumi.get(self, "runtime_type")
@property
@pulumi.getter
def state(self) -> pulumi.Output[str]:
"""
State of the organization. Values other than ACTIVE means the resource is not ready to use.
"""
return pulumi.get(self, "state")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
Not used by Apigee.
"""
return pulumi.get(self, "type")
| 52.958115 | 929 | 0.680046 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
from ._enums import *
from ._inputs import *
__all__ = ['OrganizationArgs', 'Organization']
@pulumi.input_type
class OrganizationArgs:
def __init__(__self__, *,
analytics_region: pulumi.Input[str],
parent: pulumi.Input[str],
runtime_type: pulumi.Input['OrganizationRuntimeType'],
addons_config: Optional[pulumi.Input['GoogleCloudApigeeV1AddonsConfigArgs']] = None,
attributes: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
authorized_network: Optional[pulumi.Input[str]] = None,
billing_type: Optional[pulumi.Input['OrganizationBillingType']] = None,
customer_name: Optional[pulumi.Input[str]] = None,
description: Optional[pulumi.Input[str]] = None,
display_name: Optional[pulumi.Input[str]] = None,
portal_disabled: Optional[pulumi.Input[bool]] = None,
properties: Optional[pulumi.Input['GoogleCloudApigeeV1PropertiesArgs']] = None,
runtime_database_encryption_key_name: Optional[pulumi.Input[str]] = None,
type: Optional[pulumi.Input['OrganizationType']] = None):
pulumi.set(__self__, "analytics_region", analytics_region)
pulumi.set(__self__, "parent", parent)
pulumi.set(__self__, "runtime_type", runtime_type)
if addons_config is not None:
pulumi.set(__self__, "addons_config", addons_config)
if attributes is not None:
pulumi.set(__self__, "attributes", attributes)
if authorized_network is not None:
pulumi.set(__self__, "authorized_network", authorized_network)
if billing_type is not None:
pulumi.set(__self__, "billing_type", billing_type)
if customer_name is not None:
pulumi.set(__self__, "customer_name", customer_name)
if description is not None:
pulumi.set(__self__, "description", description)
if display_name is not None:
pulumi.set(__self__, "display_name", display_name)
if portal_disabled is not None:
pulumi.set(__self__, "portal_disabled", portal_disabled)
if properties is not None:
pulumi.set(__self__, "properties", properties)
if runtime_database_encryption_key_name is not None:
pulumi.set(__self__, "runtime_database_encryption_key_name", runtime_database_encryption_key_name)
if type is not None:
pulumi.set(__self__, "type", type)
@property
@pulumi.getter(name="analyticsRegion")
def analytics_region(self) -> pulumi.Input[str]:
return pulumi.get(self, "analytics_region")
@analytics_region.setter
def analytics_region(self, value: pulumi.Input[str]):
pulumi.set(self, "analytics_region", value)
@property
@pulumi.getter
def parent(self) -> pulumi.Input[str]:
return pulumi.get(self, "parent")
@parent.setter
def parent(self, value: pulumi.Input[str]):
pulumi.set(self, "parent", value)
@property
@pulumi.getter(name="runtimeType")
def runtime_type(self) -> pulumi.Input['OrganizationRuntimeType']:
return pulumi.get(self, "runtime_type")
@runtime_type.setter
def runtime_type(self, value: pulumi.Input['OrganizationRuntimeType']):
pulumi.set(self, "runtime_type", value)
@property
@pulumi.getter(name="addonsConfig")
def addons_config(self) -> Optional[pulumi.Input['GoogleCloudApigeeV1AddonsConfigArgs']]:
return pulumi.get(self, "addons_config")
@addons_config.setter
def addons_config(self, value: Optional[pulumi.Input['GoogleCloudApigeeV1AddonsConfigArgs']]):
pulumi.set(self, "addons_config", value)
@property
@pulumi.getter
def attributes(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
return pulumi.get(self, "attributes")
@attributes.setter
def attributes(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "attributes", value)
@property
@pulumi.getter(name="authorizedNetwork")
def authorized_network(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "authorized_network")
@authorized_network.setter
def authorized_network(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "authorized_network", value)
@property
@pulumi.getter(name="billingType")
def billing_type(self) -> Optional[pulumi.Input['OrganizationBillingType']]:
return pulumi.get(self, "billing_type")
@billing_type.setter
def billing_type(self, value: Optional[pulumi.Input['OrganizationBillingType']]):
pulumi.set(self, "billing_type", value)
@property
@pulumi.getter(name="customerName")
def customer_name(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "customer_name")
@customer_name.setter
def customer_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "customer_name", value)
@property
@pulumi.getter
def description(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "description")
@description.setter
def description(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "description", value)
@property
@pulumi.getter(name="displayName")
def display_name(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "display_name")
@display_name.setter
def display_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "display_name", value)
@property
@pulumi.getter(name="portalDisabled")
def portal_disabled(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "portal_disabled")
@portal_disabled.setter
def portal_disabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "portal_disabled", value)
@property
@pulumi.getter
def properties(self) -> Optional[pulumi.Input['GoogleCloudApigeeV1PropertiesArgs']]:
return pulumi.get(self, "properties")
@properties.setter
def properties(self, value: Optional[pulumi.Input['GoogleCloudApigeeV1PropertiesArgs']]):
pulumi.set(self, "properties", value)
@property
@pulumi.getter(name="runtimeDatabaseEncryptionKeyName")
def runtime_database_encryption_key_name(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "runtime_database_encryption_key_name")
@runtime_database_encryption_key_name.setter
def runtime_database_encryption_key_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "runtime_database_encryption_key_name", value)
@property
@pulumi.getter
def type(self) -> Optional[pulumi.Input['OrganizationType']]:
return pulumi.get(self, "type")
@type.setter
def type(self, value: Optional[pulumi.Input['OrganizationType']]):
pulumi.set(self, "type", value)
class Organization(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
addons_config: Optional[pulumi.Input[pulumi.InputType['GoogleCloudApigeeV1AddonsConfigArgs']]] = None,
analytics_region: Optional[pulumi.Input[str]] = None,
attributes: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
authorized_network: Optional[pulumi.Input[str]] = None,
billing_type: Optional[pulumi.Input['OrganizationBillingType']] = None,
customer_name: Optional[pulumi.Input[str]] = None,
description: Optional[pulumi.Input[str]] = None,
display_name: Optional[pulumi.Input[str]] = None,
parent: Optional[pulumi.Input[str]] = None,
portal_disabled: Optional[pulumi.Input[bool]] = None,
properties: Optional[pulumi.Input[pulumi.InputType['GoogleCloudApigeeV1PropertiesArgs']]] = None,
runtime_database_encryption_key_name: Optional[pulumi.Input[str]] = None,
runtime_type: Optional[pulumi.Input['OrganizationRuntimeType']] = None,
type: Optional[pulumi.Input['OrganizationType']] = None,
__props__=None):
...
@overload
def __init__(__self__,
resource_name: str,
args: OrganizationArgs,
opts: Optional[pulumi.ResourceOptions] = None):
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(OrganizationArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
addons_config: Optional[pulumi.Input[pulumi.InputType['GoogleCloudApigeeV1AddonsConfigArgs']]] = None,
analytics_region: Optional[pulumi.Input[str]] = None,
attributes: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
authorized_network: Optional[pulumi.Input[str]] = None,
billing_type: Optional[pulumi.Input['OrganizationBillingType']] = None,
customer_name: Optional[pulumi.Input[str]] = None,
description: Optional[pulumi.Input[str]] = None,
display_name: Optional[pulumi.Input[str]] = None,
parent: Optional[pulumi.Input[str]] = None,
portal_disabled: Optional[pulumi.Input[bool]] = None,
properties: Optional[pulumi.Input[pulumi.InputType['GoogleCloudApigeeV1PropertiesArgs']]] = None,
runtime_database_encryption_key_name: Optional[pulumi.Input[str]] = None,
runtime_type: Optional[pulumi.Input['OrganizationRuntimeType']] = None,
type: Optional[pulumi.Input['OrganizationType']] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = OrganizationArgs.__new__(OrganizationArgs)
__props__.__dict__["addons_config"] = addons_config
if analytics_region is None and not opts.urn:
raise TypeError("Missing required property 'analytics_region'")
__props__.__dict__["analytics_region"] = analytics_region
__props__.__dict__["attributes"] = attributes
__props__.__dict__["authorized_network"] = authorized_network
__props__.__dict__["billing_type"] = billing_type
__props__.__dict__["customer_name"] = customer_name
__props__.__dict__["description"] = description
__props__.__dict__["display_name"] = display_name
if parent is None and not opts.urn:
raise TypeError("Missing required property 'parent'")
__props__.__dict__["parent"] = parent
__props__.__dict__["portal_disabled"] = portal_disabled
__props__.__dict__["properties"] = properties
__props__.__dict__["runtime_database_encryption_key_name"] = runtime_database_encryption_key_name
if runtime_type is None and not opts.urn:
raise TypeError("Missing required property 'runtime_type'")
__props__.__dict__["runtime_type"] = runtime_type
__props__.__dict__["type"] = type
__props__.__dict__["ca_certificate"] = None
__props__.__dict__["created_at"] = None
__props__.__dict__["environments"] = None
__props__.__dict__["expires_at"] = None
__props__.__dict__["last_modified_at"] = None
__props__.__dict__["name"] = None
__props__.__dict__["project"] = None
__props__.__dict__["state"] = None
super(Organization, __self__).__init__(
'google-native:apigee/v1:Organization',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'Organization':
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = OrganizationArgs.__new__(OrganizationArgs)
__props__.__dict__["addons_config"] = None
__props__.__dict__["analytics_region"] = None
__props__.__dict__["attributes"] = None
__props__.__dict__["authorized_network"] = None
__props__.__dict__["billing_type"] = None
__props__.__dict__["ca_certificate"] = None
__props__.__dict__["created_at"] = None
__props__.__dict__["customer_name"] = None
__props__.__dict__["description"] = None
__props__.__dict__["display_name"] = None
__props__.__dict__["environments"] = None
__props__.__dict__["expires_at"] = None
__props__.__dict__["last_modified_at"] = None
__props__.__dict__["name"] = None
__props__.__dict__["portal_disabled"] = None
__props__.__dict__["project"] = None
__props__.__dict__["properties"] = None
__props__.__dict__["runtime_database_encryption_key_name"] = None
__props__.__dict__["runtime_type"] = None
__props__.__dict__["state"] = None
__props__.__dict__["type"] = None
return Organization(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="addonsConfig")
def addons_config(self) -> pulumi.Output['outputs.GoogleCloudApigeeV1AddonsConfigResponse']:
return pulumi.get(self, "addons_config")
@property
@pulumi.getter(name="analyticsRegion")
def analytics_region(self) -> pulumi.Output[str]:
return pulumi.get(self, "analytics_region")
@property
@pulumi.getter
def attributes(self) -> pulumi.Output[Sequence[str]]:
return pulumi.get(self, "attributes")
@property
@pulumi.getter(name="authorizedNetwork")
def authorized_network(self) -> pulumi.Output[str]:
return pulumi.get(self, "authorized_network")
@property
@pulumi.getter(name="billingType")
def billing_type(self) -> pulumi.Output[str]:
return pulumi.get(self, "billing_type")
@property
@pulumi.getter(name="caCertificate")
def ca_certificate(self) -> pulumi.Output[str]:
return pulumi.get(self, "ca_certificate")
@property
@pulumi.getter(name="createdAt")
def created_at(self) -> pulumi.Output[str]:
return pulumi.get(self, "created_at")
@property
@pulumi.getter(name="customerName")
def customer_name(self) -> pulumi.Output[str]:
return pulumi.get(self, "customer_name")
@property
@pulumi.getter
def description(self) -> pulumi.Output[str]:
return pulumi.get(self, "description")
@property
@pulumi.getter(name="displayName")
def display_name(self) -> pulumi.Output[str]:
return pulumi.get(self, "display_name")
@property
@pulumi.getter
def environments(self) -> pulumi.Output[Sequence[str]]:
return pulumi.get(self, "environments")
@property
@pulumi.getter(name="expiresAt")
def expires_at(self) -> pulumi.Output[str]:
return pulumi.get(self, "expires_at")
@property
@pulumi.getter(name="lastModifiedAt")
def last_modified_at(self) -> pulumi.Output[str]:
return pulumi.get(self, "last_modified_at")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
return pulumi.get(self, "name")
@property
@pulumi.getter(name="portalDisabled")
def portal_disabled(self) -> pulumi.Output[bool]:
return pulumi.get(self, "portal_disabled")
@property
@pulumi.getter
def project(self) -> pulumi.Output[str]:
return pulumi.get(self, "project")
@property
@pulumi.getter
def properties(self) -> pulumi.Output['outputs.GoogleCloudApigeeV1PropertiesResponse']:
return pulumi.get(self, "properties")
@property
@pulumi.getter(name="runtimeDatabaseEncryptionKeyName")
def runtime_database_encryption_key_name(self) -> pulumi.Output[str]:
return pulumi.get(self, "runtime_database_encryption_key_name")
@property
@pulumi.getter(name="runtimeType")
def runtime_type(self) -> pulumi.Output[str]:
return pulumi.get(self, "runtime_type")
@property
@pulumi.getter
def state(self) -> pulumi.Output[str]:
return pulumi.get(self, "state")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
return pulumi.get(self, "type")
| true | true |
f72c08e934eb334e53153f585231168d33ac7fca | 35,118 | py | Python | src/search.py | luisriverag/MagnetMagnet | 99f1805da0fa6399e4b28ab40d5784170bb91e82 | [
"MIT"
] | 44 | 2020-03-14T15:53:11.000Z | 2022-01-31T11:28:59.000Z | src/search.py | luisriverag/MagnetMagnet | 99f1805da0fa6399e4b28ab40d5784170bb91e82 | [
"MIT"
] | 6 | 2020-04-30T15:53:34.000Z | 2021-09-09T14:38:02.000Z | src/search.py | luisriverag/MagnetMagnet | 99f1805da0fa6399e4b28ab40d5784170bb91e82 | [
"MIT"
] | 16 | 2020-04-30T13:18:21.000Z | 2022-01-27T17:50:56.000Z | import math
import re
import pyperclip
import requests
from bs4 import BeautifulSoup
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import src.mglobals
path = src.mglobals.base_path
class Ui_searchMainWindow(object):
def copied_success_message(self):
successMessageBox = QMessageBox()
successMessageBox.setIcon(QMessageBox.Information)
successMessageBox.setText(
"Magnet links have been successfully copied to the clipboard.")
successMessageBox.setWindowTitle("Task Completed!")
successMessageBox.setStandardButtons(QMessageBox.Ok)
icon = QIcon()
icon.addPixmap(QPixmap(src.mglobals.icon), QIcon.Normal, QIcon.Off)
successMessageBox.setWindowIcon(icon)
successMessageBox.exec_()
def copy(self):
choice_row = self.tableTableWidget.currentRow()
choice_magnet = self.magnets[choice_row]
pyperclip.copy(choice_magnet)
self.copied_success_message()
def callback(self):
query = self.queryLineEdit.text()
limit = self.limitSlider.value()
def resize():
self.tableTableWidget.resizeColumnToContents(0)
self.tableTableWidget.resizeColumnToContents(1)
self.tableTableWidget.resizeColumnToContents(2)
self.tableTableWidget.resizeColumnToContents(3)
self.tableTableWidget.resizeColumnToContents(4)
def searched_success_message():
successMessageBox = QMessageBox()
successMessageBox.setIcon(QMessageBox.Information)
successMessageBox.setText(
"Magnet links have been successfully scraped.")
successMessageBox.setWindowTitle("Task Completed!")
successMessageBox.setStandardButtons(QMessageBox.Ok)
icon = QIcon()
icon.addPixmap(QPixmap(src.mglobals.icon), QIcon.Normal, QIcon.Off)
successMessageBox.setWindowIcon(icon)
successMessageBox.exec_()
def error_message():
errorMessageBox = QMessageBox()
errorMessageBox.setIcon(QMessageBox.Information)
errorMessageBox.setText(
"Something went wrong! Please inform me through GitHub!")
errorMessageBox.setWindowTitle("Error!")
errorMessageBox.setStandardButtons(QMessageBox.Ok)
icon = QIcon()
icon.addPixmap(QPixmap(src.mglobals.icon), QIcon.Normal, QIcon.Off)
errorMessageBox.setWindowIcon(icon)
errorMessageBox.exec_()
def x1377():
try:
main_link = "https://1377x.to/search/" + query + '/1/'
main_request = requests.get(
main_link, headers={'User-Agent': 'Mozilla/5.0'})
main_source = main_request.content
main_soup = BeautifulSoup(main_source, 'lxml')
limit_counter = 0
page_links_soup = main_soup.findAll(
'a', attrs={'href': re.compile("^/torrent/")})
for page_link in page_links_soup:
if limit_counter < limit:
page_link = "https://1377x.to" + page_link.get('href')
page_request = requests.get(
page_link, headers={'User-Agent': 'Mozilla/5.0'})
page_source = page_request.content
page_soup = BeautifulSoup(page_source, 'lxml')
title = (page_soup.find('h1').text).replace("\n", " ")
seeder = page_soup.find('span', class_="seeds").text
leecher = page_soup.find('span', class_="leeches").text
size = page_soup.findAll('span')[15].text
date = page_soup.findAll('span')[19].text
magnet = page_soup.find(
'a', attrs={'href': re.compile("^magnet:?")}).get('href')
row_position = self.tableTableWidget.rowCount()
self.tableTableWidget.insertRow(row_position)
self.tableTableWidget.setItem(
row_position, 0, QTableWidgetItem(title))
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(seeder))
self.tableTableWidget.setItem(row_position, 1, item)
self.tableTableWidget.setItem(
row_position, 2, QTableWidgetItem(leecher))
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(leecher))
self.tableTableWidget.setItem(row_position, 2, item)
self.tableTableWidget.setItem(
row_position, 3, QTableWidgetItem(size))
self.tableTableWidget.setItem(
row_position, 4, QTableWidgetItem(date))
self.tableTableWidget.setItem(
row_position, 5, QTableWidgetItem("1377x"))
self.magnets.append(magnet)
limit_counter = limit_counter + 1
except:
error_message()
def kat():
try:
main_link = "https://kat.rip/usearch/" + query
main_request = requests.get(
main_link, headers={'User-Agent': 'Mozilla/5.0'})
main_source = main_request.content
main_soup = BeautifulSoup(main_source, 'lxml')
titles_soup = main_soup.findAll('a', class_="cellMainLink")
seeders_soup = main_soup.findAll('td', class_="green center")
leechers_soup = main_soup.findAll(
'td', class_="red lasttd center")
sizes_soup = main_soup.findAll('td', class_="nobr center")
dates_soup = main_soup.findAll(
'td', class_="center", title=True)
magnets_soup = main_soup.findAll(
'a', attrs={'href': re.compile("^magnet:?"), 'title': "Torrent magnet link"})
titles = []
seeders = []
leechers = []
sizes = []
dates = []
limit_counter = 0
for title in titles_soup:
if limit_counter < limit:
titles.append(title.text)
limit_counter = limit_counter + 1
limit_counter = 0
for seeder in seeders_soup:
if limit_counter < limit:
seeders.append(seeder.text)
limit_counter = limit_counter + 1
limit_counter = 0
for leecher in leechers_soup:
if limit_counter < limit:
leechers.append(leecher.text)
limit_counter = limit_counter + 1
limit_counter = 0
for size in sizes_soup:
if limit_counter < limit:
sizes.append(size.text)
limit_counter = limit_counter + 1
limit_counter = 0
for date in dates_soup:
if limit_counter < limit:
dates.append(date.text)
limit_counter = limit_counter + 1
limit_counter = 0
count1 = 0
for magnet in magnets_soup:
if limit_counter < limit:
self.magnets.append(magnet.get('href'))
limit_counter = limit_counter + 1
count1 = count1 + 1
count2 = 0
while count2 < count1:
row_position = self.tableTableWidget.rowCount()
self.tableTableWidget.insertRow(row_position)
self.tableTableWidget.setItem(
row_position, 0, QTableWidgetItem(titles[count2]))
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(seeders[count2]))
self.tableTableWidget.setItem(row_position, 1, item)
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(leechers[count2]))
self.tableTableWidget.setItem(row_position, 2, item)
self.tableTableWidget.setItem(
row_position, 3, QTableWidgetItem(sizes[count2]))
self.tableTableWidget.setItem(
row_position, 4, QTableWidgetItem(dates[count2]))
self.tableTableWidget.setItem(
row_position, 5, QTableWidgetItem("KAT"))
count2 = count2 + 1
except:
error_message()
def nyaa():
try:
main_link = 'https://nyaa.si/?q=' + query
main_request = requests.get(
main_link, headers={'User-Agent': 'Mozilla/5.0'})
main_source = main_request.content
main_soup = BeautifulSoup(main_source, 'lxml')
titles_soup = main_soup.findAll('a', title=True, class_=False, attrs={
'href': re.compile("^/view/")})
seeders_soup = main_soup.findAll('td', class_="text-center")
leechers_soup = main_soup.findAll('td', class_="text-center")
sizes_soup = main_soup.findAll('td', class_="text-center")
dates_soup = main_soup.findAll('td', class_="text-center")
magnets_soup = main_soup.findAll(
'a', attrs={'href': re.compile("^magnet:?")})
titles = []
seeders = []
leechers = []
sizes = []
dates = []
limit_counter = 0
for title in titles_soup:
if limit_counter < limit:
titles.append(title.text)
limit_counter = limit_counter + 1
limit_counter = 0
for seeder in seeders_soup:
if limit_counter < limit*6:
seeders.append(seeder.text)
limit_counter = limit_counter + 1
limit_counter = 0
for leecher in leechers_soup:
if limit_counter < limit*6:
leechers.append(leecher.text)
limit_counter = limit_counter + 1
limit_counter = 0
for size in sizes_soup:
if limit_counter < limit*6:
sizes.append(size.text)
limit_counter = limit_counter + 1
limit_counter = 0
for date in dates_soup:
if limit_counter < limit*6:
dates.append(date.text)
limit_counter = limit_counter + 1
limit_counter = 0
count1 = 0
for magnet in magnets_soup:
if limit_counter < limit:
self.magnets.append(magnet.get('href'))
limit_counter = limit_counter + 1
count1 = count1 + 1
seeder1 = seeders[3]
seeders.pop(0)
seeders.pop(1)
seeders.pop(2)
seeders.pop(3)
seeders = seeders[6-1::6]
seeders.insert(0, seeder1)
leecher1 = leechers[4]
leechers.pop(0)
leechers.pop(1)
leechers.pop(2)
leechers.pop(3)
leechers.pop(4)
leechers = leechers[6-1::6]
leechers.insert(0, leecher1)
size1 = sizes[1]
sizes.pop(0)
sizes.pop(1)
sizes = sizes[6-1::6]
sizes.insert(0, size1)
date1 = dates[2]
dates.pop(0)
dates.pop(1)
dates.pop(2)
dates = dates[6-1::6]
dates.insert(0, date1)
count2 = 0
while count2 < count1:
row_position = self.tableTableWidget.rowCount()
self.tableTableWidget.insertRow(row_position)
self.tableTableWidget.setItem(
row_position, 0, QTableWidgetItem(titles[count2]))
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(seeders[count2]))
self.tableTableWidget.setItem(row_position, 1, item)
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(leechers[count2]))
self.tableTableWidget.setItem(row_position, 2, item)
self.tableTableWidget.setItem(
row_position, 3, QTableWidgetItem(sizes[count2]))
self.tableTableWidget.setItem(
row_position, 4, QTableWidgetItem(dates[count2]))
self.tableTableWidget.setItem(
row_position, 5, QTableWidgetItem("Nyaa"))
count2 = count2 + 1
except:
error_message()
def rarbg():
try:
token_url = "https://torrentapi.org/pubapi_v2.php?get_token=get_token&app_id=MagnetMagnet"
token_request = requests.get(token_url, headers={'User-Agent': 'Mozilla/5.0'})
token = token_request.json()["token"]
main_link = 'https://torrentapi.org/pubapi_v2.php?mode=search&search_string=' + \
query + '&token=' + token + '&format=json_extended&app_id=MagnetMagnet'
main_request = requests.get(
main_link, headers={'User-Agent': 'Mozilla/5.0'})
main_source = main_request.json()["torrent_results"]
limit_counter = 0
titles = []
seeders = []
leechers = []
sizes = []
dates = []
for item in main_source:
if limit_counter < limit:
def convert_size(size):
if size == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB",
"TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size, 1024)))
p = math.pow(1024, i)
s = round(size / p, 2)
size = "%s %s" % (s, size_name[i])
return size
titles.append(item["title"])
seeders.append(item["seeders"])
leechers.append(item["leechers"])
sizes.append(convert_size(item["size"]))
dates.append(item["pubdate"])
self.magnets.append(item["download"])
limit_counter += 1
else:
pass
print(titles)
count2 = 0
while count2 < limit_counter:
row_position = self.tableTableWidget.rowCount()
self.tableTableWidget.insertRow(row_position)
self.tableTableWidget.setItem(
row_position, 0, QTableWidgetItem(titles[count2]))
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(seeders[count2]))
self.tableTableWidget.setItem(row_position, 1, item)
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(leechers[count2]))
self.tableTableWidget.setItem(row_position, 2, item)
self.tableTableWidget.setItem(
row_position, 3, QTableWidgetItem(sizes[count2]))
self.tableTableWidget.setItem(
row_position, 4, QTableWidgetItem(dates[count2]))
self.tableTableWidget.setItem(
row_position, 5, QTableWidgetItem("RARBG"))
count2 = count2 + 1
except:
error_message()
def tpb():
try:
main_link = 'https://tpb.party/search/' + query + '/1/99/0/'
main_request = requests.get(
main_link, headers={'User-Agent': 'Mozilla/5.0'})
main_source = main_request.content
main_soup = BeautifulSoup(main_source, 'lxml')
titles_soup = main_soup.findAll('div', class_="detName")
seeders_soup = main_soup.findAll(
'td', attrs={'align': "right"})
seeders_soup = seeders_soup[0::2]
leechers_soup = main_soup.findAll(
'td', attrs={'align': "right"})
leechers_soup = leechers_soup[1::2]
sizes_soup = main_soup.findAll('font', class_="detDesc")
dates_soup = main_soup.findAll('font', class_="detDesc")
magnets_soup = main_soup.findAll(
'a', attrs={'href': re.compile("^magnet")})
titles = []
seeders = []
leechers = []
sizes = []
dates = []
limit_counter = 0
for title in titles_soup:
if limit_counter < limit:
title = title.text.replace("\n", "")
titles.append(title)
limit_counter = limit_counter + 1
limit_counter = 0
for seeder in seeders_soup:
if limit_counter < limit:
seeders.append(seeder.text)
limit_counter = limit_counter + 1
limit_counter = 0
for leecher in leechers_soup:
if limit_counter < limit:
leechers.append(leecher.text)
limit_counter = limit_counter + 1
limit_counter = 0
for size in sizes_soup:
if limit_counter < limit:
size = size.text.split(", ")
size = size[1].replace("Size ", "")
sizes.append(size)
limit_counter = limit_counter + 1
limit_counter = 0
for date in dates_soup:
if limit_counter < limit:
date = date.text.split(", ")
date = date[0].replace("Uploaded ", "")
dates.append(date)
limit_counter = limit_counter + 1
count1 = 0
limit_counter = 0
for magnet in magnets_soup:
if limit_counter < limit:
self.magnets.append(magnet.get('href'))
count1 = count1 + 1
limit_counter = limit_counter + 1
count2 = 0
while count2 < count1:
row_position = self.tableTableWidget.rowCount()
self.tableTableWidget.insertRow(row_position)
self.tableTableWidget.setItem(
row_position, 0, QTableWidgetItem(titles[count2]))
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(seeders[count2]))
self.tableTableWidget.setItem(row_position, 1, item)
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(leechers[count2]))
self.tableTableWidget.setItem(row_position, 2, item)
self.tableTableWidget.setItem(
row_position, 3, QTableWidgetItem(sizes[count2]))
self.tableTableWidget.setItem(
row_position, 4, QTableWidgetItem(dates[count2]))
self.tableTableWidget.setItem(
row_position, 5, QTableWidgetItem("TPB"))
count2 = count2 + 1
except:
error_message()
if (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
nyaa()
rarbg()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
nyaa()
rarbg()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
nyaa()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
rarbg()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
nyaa()
rarbg()
resize()
searched_success_message()
elif (self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
nyaa()
rarbg()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
nyaa()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
rarbg()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
nyaa()
rarbg()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
nyaa()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
rarbg()
tpb()
resize()
searched_success_message()
elif (self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
nyaa()
rarbg()
resize()
searched_success_message()
elif (self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
nyaa()
tpb()
resize()
searched_success_message()
elif (self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
nyaa()
rarbg()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.nyaaCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
nyaa()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
rarbg()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
tpb()
resize()
searched_success_message()
elif (self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
nyaa()
resize()
searched_success_message()
elif (self.katCheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
rarbg()
resize()
searched_success_message()
elif (self.katCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
tpb()
resize()
searched_success_message()
elif (self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
nyaa()
rarbg()
resize()
searched_success_message()
elif (self.nyaaCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
nyaa()
tpb()
resize()
searched_success_message()
elif (self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
rarbg()
tpb()
resize()
searched_success_message()
elif self.x1377CheckBox.isChecked():
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
resize()
searched_success_message()
elif self.katCheckBox.isChecked():
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
resize()
searched_success_message()
elif self.nyaaCheckBox.isChecked():
self.tableTableWidget.setRowCount(0)
self.magnets = []
nyaa()
resize()
searched_success_message()
elif self.rarbgCheckBox.isChecked():
self.tableTableWidget.setRowCount(0)
self.magnets = []
rarbg()
resize()
searched_success_message()
elif self.tpbCheckBox.isChecked():
self.tableTableWidget.setRowCount(0)
self.magnets = []
tpb()
resize()
searched_success_message()
def setupUi(self, searchMainWindow):
searchMainWindow.setObjectName("searchMainWindow")
searchMainWindow.resize(1500, 400)
font = QFont()
font.setFamily("Bahnschrift Light")
font.setPointSize(11)
searchMainWindow.setFont(font)
icon = QIcon()
icon.addPixmap(QPixmap(src.mglobals.icon), QIcon.Normal, QIcon.Off)
searchMainWindow.setWindowIcon(icon)
self.centralwidget = QWidget(searchMainWindow)
self.centralwidget.setObjectName("centralwidget")
self.queryLineEdit = QLineEdit(self.centralwidget)
self.queryLineEdit.setGeometry(QRect(30, 20, 200, 20))
font = QFont()
font.setPointSize(9)
self.queryLineEdit.setFont(font)
self.queryLineEdit.setObjectName("queryLineEdit")
self.x1377CheckBox = QCheckBox(self.centralwidget)
self.x1377CheckBox.setGeometry(QRect(30, 70, 90, 20))
self.x1377CheckBox.setObjectName("x1377CheckBox")
self.tableTableWidget = QTableWidget(self.centralwidget)
self.tableTableWidget.setGeometry(QRect(260, 20, 1161, 360))
self.tableTableWidget.setObjectName("tableTableWidget")
self.tableTableWidget.setColumnCount(6)
self.tableTableWidget.setRowCount(0)
item = QTableWidgetItem()
self.tableTableWidget.setHorizontalHeaderItem(0, item)
item = QTableWidgetItem()
self.tableTableWidget.setHorizontalHeaderItem(1, item)
item = QTableWidgetItem()
self.tableTableWidget.setHorizontalHeaderItem(2, item)
item = QTableWidgetItem()
self.tableTableWidget.setHorizontalHeaderItem(3, item)
item = QTableWidgetItem()
self.tableTableWidget.setHorizontalHeaderItem(4, item)
item = QTableWidgetItem()
self.tableTableWidget.setHorizontalHeaderItem(5, item)
self.tableTableWidget.setSortingEnabled(True)
self.katCheckBox = QCheckBox(self.centralwidget)
self.katCheckBox.setGeometry(QRect(30, 110, 90, 20))
self.katCheckBox.setObjectName("katCheckBox")
self.nyaaCheckBox = QCheckBox(self.centralwidget)
self.nyaaCheckBox.setGeometry(QRect(30, 150, 90, 20))
self.nyaaCheckBox.setObjectName("nyaaCheckBox")
self.rarbgCheckBox = QCheckBox(self.centralwidget)
self.rarbgCheckBox.setGeometry(QRect(30, 190, 90, 20))
self.rarbgCheckBox.setObjectName("rarbgCheckBox")
self.tpbCheckBox = QCheckBox(self.centralwidget)
self.tpbCheckBox.setGeometry(QRect(30, 230, 90, 20))
self.tpbCheckBox.setObjectName("tpbCheckBox")
self.searchPushButton = QPushButton(self.centralwidget)
self.searchPushButton.setGeometry(QRect(30, 350, 90, 30))
font = QFont()
font.setPointSize(8)
self.searchPushButton.setFont(font)
self.searchPushButton.setObjectName("searchPushButton")
self.limitSlider = QSlider(self.centralwidget)
self.limitSlider.setGeometry(QRect(1450, 40, 22, 320))
self.limitSlider.setMaximum(20)
self.limitSlider.setPageStep(2)
self.limitSlider.setSliderPosition(10)
self.limitSlider.setOrientation(Qt.Vertical)
self.limitSlider.setObjectName("limitSlider")
self.minimumLabel = QLabel(self.centralwidget)
self.minimumLabel.setGeometry(QRect(1452, 365, 16, 16))
font = QFont()
font.setPointSize(9)
self.minimumLabel.setFont(font)
self.minimumLabel.setAlignment(Qt.AlignCenter)
self.minimumLabel.setObjectName("minimumLabel")
self.maximumLabel = QLabel(self.centralwidget)
self.maximumLabel.setGeometry(QRect(1452, 20, 16, 16))
font = QFont()
font.setPointSize(9)
self.maximumLabel.setFont(font)
self.maximumLabel.setAlignment(Qt.AlignCenter)
self.maximumLabel.setObjectName("maximumLabel")
searchMainWindow.setCentralWidget(self.centralwidget)
self.searchPushButton.clicked.connect(self.callback)
self.tableTableWidget.itemClicked.connect(self.copy)
self.retranslateUi(searchMainWindow)
QMetaObject.connectSlotsByName(searchMainWindow)
def retranslateUi(self, searchMainWindow):
_translate = QCoreApplication.translate
searchMainWindow.setWindowTitle(_translate(
"searchMainWindow", "MagnetMagnet - Search"))
self.x1377CheckBox.setText(_translate("searchMainWindow", "1377x"))
item = self.tableTableWidget.horizontalHeaderItem(0)
item.setText(_translate("searchMainWindow", "Titles"))
item = self.tableTableWidget.horizontalHeaderItem(1)
item.setText(_translate("searchMainWindow", "Seeders"))
item = self.tableTableWidget.horizontalHeaderItem(2)
item.setText(_translate("searchMainWindow", "Leechers"))
item = self.tableTableWidget.horizontalHeaderItem(3)
item.setText(_translate("searchMainWindow", "Sizes"))
item = self.tableTableWidget.horizontalHeaderItem(4)
item.setText(_translate("searchMainWindow", "Dates"))
item = self.tableTableWidget.horizontalHeaderItem(5)
item.setText(_translate("searchMainWindow", "Source"))
self.katCheckBox.setText(_translate("searchMainWindow", "KAT"))
self.nyaaCheckBox.setText(_translate("searchMainWindow", "Nyaa"))
self.rarbgCheckBox.setText(_translate("searchMainWindow", "RARBG"))
self.tpbCheckBox.setText(_translate("searchMainWindow", "TPB"))
self.searchPushButton.setText(_translate("searchMainWindow", "Search"))
self.minimumLabel.setText(_translate("searchMainWindow", "0"))
self.maximumLabel.setText(_translate("searchMainWindow", "20"))
| 44.173585 | 179 | 0.539154 | import math
import re
import pyperclip
import requests
from bs4 import BeautifulSoup
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import src.mglobals
path = src.mglobals.base_path
class Ui_searchMainWindow(object):
def copied_success_message(self):
successMessageBox = QMessageBox()
successMessageBox.setIcon(QMessageBox.Information)
successMessageBox.setText(
"Magnet links have been successfully copied to the clipboard.")
successMessageBox.setWindowTitle("Task Completed!")
successMessageBox.setStandardButtons(QMessageBox.Ok)
icon = QIcon()
icon.addPixmap(QPixmap(src.mglobals.icon), QIcon.Normal, QIcon.Off)
successMessageBox.setWindowIcon(icon)
successMessageBox.exec_()
def copy(self):
choice_row = self.tableTableWidget.currentRow()
choice_magnet = self.magnets[choice_row]
pyperclip.copy(choice_magnet)
self.copied_success_message()
def callback(self):
query = self.queryLineEdit.text()
limit = self.limitSlider.value()
def resize():
self.tableTableWidget.resizeColumnToContents(0)
self.tableTableWidget.resizeColumnToContents(1)
self.tableTableWidget.resizeColumnToContents(2)
self.tableTableWidget.resizeColumnToContents(3)
self.tableTableWidget.resizeColumnToContents(4)
def searched_success_message():
successMessageBox = QMessageBox()
successMessageBox.setIcon(QMessageBox.Information)
successMessageBox.setText(
"Magnet links have been successfully scraped.")
successMessageBox.setWindowTitle("Task Completed!")
successMessageBox.setStandardButtons(QMessageBox.Ok)
icon = QIcon()
icon.addPixmap(QPixmap(src.mglobals.icon), QIcon.Normal, QIcon.Off)
successMessageBox.setWindowIcon(icon)
successMessageBox.exec_()
def error_message():
errorMessageBox = QMessageBox()
errorMessageBox.setIcon(QMessageBox.Information)
errorMessageBox.setText(
"Something went wrong! Please inform me through GitHub!")
errorMessageBox.setWindowTitle("Error!")
errorMessageBox.setStandardButtons(QMessageBox.Ok)
icon = QIcon()
icon.addPixmap(QPixmap(src.mglobals.icon), QIcon.Normal, QIcon.Off)
errorMessageBox.setWindowIcon(icon)
errorMessageBox.exec_()
def x1377():
try:
main_link = "https://1377x.to/search/" + query + '/1/'
main_request = requests.get(
main_link, headers={'User-Agent': 'Mozilla/5.0'})
main_source = main_request.content
main_soup = BeautifulSoup(main_source, 'lxml')
limit_counter = 0
page_links_soup = main_soup.findAll(
'a', attrs={'href': re.compile("^/torrent/")})
for page_link in page_links_soup:
if limit_counter < limit:
page_link = "https://1377x.to" + page_link.get('href')
page_request = requests.get(
page_link, headers={'User-Agent': 'Mozilla/5.0'})
page_source = page_request.content
page_soup = BeautifulSoup(page_source, 'lxml')
title = (page_soup.find('h1').text).replace("\n", " ")
seeder = page_soup.find('span', class_="seeds").text
leecher = page_soup.find('span', class_="leeches").text
size = page_soup.findAll('span')[15].text
date = page_soup.findAll('span')[19].text
magnet = page_soup.find(
'a', attrs={'href': re.compile("^magnet:?")}).get('href')
row_position = self.tableTableWidget.rowCount()
self.tableTableWidget.insertRow(row_position)
self.tableTableWidget.setItem(
row_position, 0, QTableWidgetItem(title))
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(seeder))
self.tableTableWidget.setItem(row_position, 1, item)
self.tableTableWidget.setItem(
row_position, 2, QTableWidgetItem(leecher))
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(leecher))
self.tableTableWidget.setItem(row_position, 2, item)
self.tableTableWidget.setItem(
row_position, 3, QTableWidgetItem(size))
self.tableTableWidget.setItem(
row_position, 4, QTableWidgetItem(date))
self.tableTableWidget.setItem(
row_position, 5, QTableWidgetItem("1377x"))
self.magnets.append(magnet)
limit_counter = limit_counter + 1
except:
error_message()
def kat():
try:
main_link = "https://kat.rip/usearch/" + query
main_request = requests.get(
main_link, headers={'User-Agent': 'Mozilla/5.0'})
main_source = main_request.content
main_soup = BeautifulSoup(main_source, 'lxml')
titles_soup = main_soup.findAll('a', class_="cellMainLink")
seeders_soup = main_soup.findAll('td', class_="green center")
leechers_soup = main_soup.findAll(
'td', class_="red lasttd center")
sizes_soup = main_soup.findAll('td', class_="nobr center")
dates_soup = main_soup.findAll(
'td', class_="center", title=True)
magnets_soup = main_soup.findAll(
'a', attrs={'href': re.compile("^magnet:?"), 'title': "Torrent magnet link"})
titles = []
seeders = []
leechers = []
sizes = []
dates = []
limit_counter = 0
for title in titles_soup:
if limit_counter < limit:
titles.append(title.text)
limit_counter = limit_counter + 1
limit_counter = 0
for seeder in seeders_soup:
if limit_counter < limit:
seeders.append(seeder.text)
limit_counter = limit_counter + 1
limit_counter = 0
for leecher in leechers_soup:
if limit_counter < limit:
leechers.append(leecher.text)
limit_counter = limit_counter + 1
limit_counter = 0
for size in sizes_soup:
if limit_counter < limit:
sizes.append(size.text)
limit_counter = limit_counter + 1
limit_counter = 0
for date in dates_soup:
if limit_counter < limit:
dates.append(date.text)
limit_counter = limit_counter + 1
limit_counter = 0
count1 = 0
for magnet in magnets_soup:
if limit_counter < limit:
self.magnets.append(magnet.get('href'))
limit_counter = limit_counter + 1
count1 = count1 + 1
count2 = 0
while count2 < count1:
row_position = self.tableTableWidget.rowCount()
self.tableTableWidget.insertRow(row_position)
self.tableTableWidget.setItem(
row_position, 0, QTableWidgetItem(titles[count2]))
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(seeders[count2]))
self.tableTableWidget.setItem(row_position, 1, item)
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(leechers[count2]))
self.tableTableWidget.setItem(row_position, 2, item)
self.tableTableWidget.setItem(
row_position, 3, QTableWidgetItem(sizes[count2]))
self.tableTableWidget.setItem(
row_position, 4, QTableWidgetItem(dates[count2]))
self.tableTableWidget.setItem(
row_position, 5, QTableWidgetItem("KAT"))
count2 = count2 + 1
except:
error_message()
def nyaa():
try:
main_link = 'https://nyaa.si/?q=' + query
main_request = requests.get(
main_link, headers={'User-Agent': 'Mozilla/5.0'})
main_source = main_request.content
main_soup = BeautifulSoup(main_source, 'lxml')
titles_soup = main_soup.findAll('a', title=True, class_=False, attrs={
'href': re.compile("^/view/")})
seeders_soup = main_soup.findAll('td', class_="text-center")
leechers_soup = main_soup.findAll('td', class_="text-center")
sizes_soup = main_soup.findAll('td', class_="text-center")
dates_soup = main_soup.findAll('td', class_="text-center")
magnets_soup = main_soup.findAll(
'a', attrs={'href': re.compile("^magnet:?")})
titles = []
seeders = []
leechers = []
sizes = []
dates = []
limit_counter = 0
for title in titles_soup:
if limit_counter < limit:
titles.append(title.text)
limit_counter = limit_counter + 1
limit_counter = 0
for seeder in seeders_soup:
if limit_counter < limit*6:
seeders.append(seeder.text)
limit_counter = limit_counter + 1
limit_counter = 0
for leecher in leechers_soup:
if limit_counter < limit*6:
leechers.append(leecher.text)
limit_counter = limit_counter + 1
limit_counter = 0
for size in sizes_soup:
if limit_counter < limit*6:
sizes.append(size.text)
limit_counter = limit_counter + 1
limit_counter = 0
for date in dates_soup:
if limit_counter < limit*6:
dates.append(date.text)
limit_counter = limit_counter + 1
limit_counter = 0
count1 = 0
for magnet in magnets_soup:
if limit_counter < limit:
self.magnets.append(magnet.get('href'))
limit_counter = limit_counter + 1
count1 = count1 + 1
seeder1 = seeders[3]
seeders.pop(0)
seeders.pop(1)
seeders.pop(2)
seeders.pop(3)
seeders = seeders[6-1::6]
seeders.insert(0, seeder1)
leecher1 = leechers[4]
leechers.pop(0)
leechers.pop(1)
leechers.pop(2)
leechers.pop(3)
leechers.pop(4)
leechers = leechers[6-1::6]
leechers.insert(0, leecher1)
size1 = sizes[1]
sizes.pop(0)
sizes.pop(1)
sizes = sizes[6-1::6]
sizes.insert(0, size1)
date1 = dates[2]
dates.pop(0)
dates.pop(1)
dates.pop(2)
dates = dates[6-1::6]
dates.insert(0, date1)
count2 = 0
while count2 < count1:
row_position = self.tableTableWidget.rowCount()
self.tableTableWidget.insertRow(row_position)
self.tableTableWidget.setItem(
row_position, 0, QTableWidgetItem(titles[count2]))
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(seeders[count2]))
self.tableTableWidget.setItem(row_position, 1, item)
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(leechers[count2]))
self.tableTableWidget.setItem(row_position, 2, item)
self.tableTableWidget.setItem(
row_position, 3, QTableWidgetItem(sizes[count2]))
self.tableTableWidget.setItem(
row_position, 4, QTableWidgetItem(dates[count2]))
self.tableTableWidget.setItem(
row_position, 5, QTableWidgetItem("Nyaa"))
count2 = count2 + 1
except:
error_message()
def rarbg():
try:
token_url = "https://torrentapi.org/pubapi_v2.php?get_token=get_token&app_id=MagnetMagnet"
token_request = requests.get(token_url, headers={'User-Agent': 'Mozilla/5.0'})
token = token_request.json()["token"]
main_link = 'https://torrentapi.org/pubapi_v2.php?mode=search&search_string=' + \
query + '&token=' + token + '&format=json_extended&app_id=MagnetMagnet'
main_request = requests.get(
main_link, headers={'User-Agent': 'Mozilla/5.0'})
main_source = main_request.json()["torrent_results"]
limit_counter = 0
titles = []
seeders = []
leechers = []
sizes = []
dates = []
for item in main_source:
if limit_counter < limit:
def convert_size(size):
if size == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB",
"TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size, 1024)))
p = math.pow(1024, i)
s = round(size / p, 2)
size = "%s %s" % (s, size_name[i])
return size
titles.append(item["title"])
seeders.append(item["seeders"])
leechers.append(item["leechers"])
sizes.append(convert_size(item["size"]))
dates.append(item["pubdate"])
self.magnets.append(item["download"])
limit_counter += 1
else:
pass
print(titles)
count2 = 0
while count2 < limit_counter:
row_position = self.tableTableWidget.rowCount()
self.tableTableWidget.insertRow(row_position)
self.tableTableWidget.setItem(
row_position, 0, QTableWidgetItem(titles[count2]))
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(seeders[count2]))
self.tableTableWidget.setItem(row_position, 1, item)
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(leechers[count2]))
self.tableTableWidget.setItem(row_position, 2, item)
self.tableTableWidget.setItem(
row_position, 3, QTableWidgetItem(sizes[count2]))
self.tableTableWidget.setItem(
row_position, 4, QTableWidgetItem(dates[count2]))
self.tableTableWidget.setItem(
row_position, 5, QTableWidgetItem("RARBG"))
count2 = count2 + 1
except:
error_message()
def tpb():
try:
main_link = 'https://tpb.party/search/' + query + '/1/99/0/'
main_request = requests.get(
main_link, headers={'User-Agent': 'Mozilla/5.0'})
main_source = main_request.content
main_soup = BeautifulSoup(main_source, 'lxml')
titles_soup = main_soup.findAll('div', class_="detName")
seeders_soup = main_soup.findAll(
'td', attrs={'align': "right"})
seeders_soup = seeders_soup[0::2]
leechers_soup = main_soup.findAll(
'td', attrs={'align': "right"})
leechers_soup = leechers_soup[1::2]
sizes_soup = main_soup.findAll('font', class_="detDesc")
dates_soup = main_soup.findAll('font', class_="detDesc")
magnets_soup = main_soup.findAll(
'a', attrs={'href': re.compile("^magnet")})
titles = []
seeders = []
leechers = []
sizes = []
dates = []
limit_counter = 0
for title in titles_soup:
if limit_counter < limit:
title = title.text.replace("\n", "")
titles.append(title)
limit_counter = limit_counter + 1
limit_counter = 0
for seeder in seeders_soup:
if limit_counter < limit:
seeders.append(seeder.text)
limit_counter = limit_counter + 1
limit_counter = 0
for leecher in leechers_soup:
if limit_counter < limit:
leechers.append(leecher.text)
limit_counter = limit_counter + 1
limit_counter = 0
for size in sizes_soup:
if limit_counter < limit:
size = size.text.split(", ")
size = size[1].replace("Size ", "")
sizes.append(size)
limit_counter = limit_counter + 1
limit_counter = 0
for date in dates_soup:
if limit_counter < limit:
date = date.text.split(", ")
date = date[0].replace("Uploaded ", "")
dates.append(date)
limit_counter = limit_counter + 1
count1 = 0
limit_counter = 0
for magnet in magnets_soup:
if limit_counter < limit:
self.magnets.append(magnet.get('href'))
count1 = count1 + 1
limit_counter = limit_counter + 1
count2 = 0
while count2 < count1:
row_position = self.tableTableWidget.rowCount()
self.tableTableWidget.insertRow(row_position)
self.tableTableWidget.setItem(
row_position, 0, QTableWidgetItem(titles[count2]))
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(seeders[count2]))
self.tableTableWidget.setItem(row_position, 1, item)
item = QTableWidgetItem()
item.setData(Qt.DisplayRole, int(leechers[count2]))
self.tableTableWidget.setItem(row_position, 2, item)
self.tableTableWidget.setItem(
row_position, 3, QTableWidgetItem(sizes[count2]))
self.tableTableWidget.setItem(
row_position, 4, QTableWidgetItem(dates[count2]))
self.tableTableWidget.setItem(
row_position, 5, QTableWidgetItem("TPB"))
count2 = count2 + 1
except:
error_message()
if (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
nyaa()
rarbg()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
nyaa()
rarbg()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
nyaa()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
rarbg()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
nyaa()
rarbg()
resize()
searched_success_message()
elif (self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
nyaa()
rarbg()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
nyaa()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
rarbg()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
nyaa()
rarbg()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
nyaa()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
rarbg()
tpb()
resize()
searched_success_message()
elif (self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
nyaa()
rarbg()
resize()
searched_success_message()
elif (self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
nyaa()
tpb()
resize()
searched_success_message()
elif (self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
nyaa()
rarbg()
tpb()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.katCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
kat()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.nyaaCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
nyaa()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
rarbg()
resize()
searched_success_message()
elif (self.x1377CheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
tpb()
resize()
searched_success_message()
elif (self.katCheckBox.isChecked() and self.nyaaCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
nyaa()
resize()
searched_success_message()
elif (self.katCheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
rarbg()
resize()
searched_success_message()
elif (self.katCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
tpb()
resize()
searched_success_message()
elif (self.nyaaCheckBox.isChecked() and self.rarbgCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
nyaa()
rarbg()
resize()
searched_success_message()
elif (self.nyaaCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
nyaa()
tpb()
resize()
searched_success_message()
elif (self.rarbgCheckBox.isChecked() and self.tpbCheckBox.isChecked()):
self.tableTableWidget.setRowCount(0)
self.magnets = []
rarbg()
tpb()
resize()
searched_success_message()
elif self.x1377CheckBox.isChecked():
self.tableTableWidget.setRowCount(0)
self.magnets = []
x1377()
resize()
searched_success_message()
elif self.katCheckBox.isChecked():
self.tableTableWidget.setRowCount(0)
self.magnets = []
kat()
resize()
searched_success_message()
elif self.nyaaCheckBox.isChecked():
self.tableTableWidget.setRowCount(0)
self.magnets = []
nyaa()
resize()
searched_success_message()
elif self.rarbgCheckBox.isChecked():
self.tableTableWidget.setRowCount(0)
self.magnets = []
rarbg()
resize()
searched_success_message()
elif self.tpbCheckBox.isChecked():
self.tableTableWidget.setRowCount(0)
self.magnets = []
tpb()
resize()
searched_success_message()
def setupUi(self, searchMainWindow):
searchMainWindow.setObjectName("searchMainWindow")
searchMainWindow.resize(1500, 400)
font = QFont()
font.setFamily("Bahnschrift Light")
font.setPointSize(11)
searchMainWindow.setFont(font)
icon = QIcon()
icon.addPixmap(QPixmap(src.mglobals.icon), QIcon.Normal, QIcon.Off)
searchMainWindow.setWindowIcon(icon)
self.centralwidget = QWidget(searchMainWindow)
self.centralwidget.setObjectName("centralwidget")
self.queryLineEdit = QLineEdit(self.centralwidget)
self.queryLineEdit.setGeometry(QRect(30, 20, 200, 20))
font = QFont()
font.setPointSize(9)
self.queryLineEdit.setFont(font)
self.queryLineEdit.setObjectName("queryLineEdit")
self.x1377CheckBox = QCheckBox(self.centralwidget)
self.x1377CheckBox.setGeometry(QRect(30, 70, 90, 20))
self.x1377CheckBox.setObjectName("x1377CheckBox")
self.tableTableWidget = QTableWidget(self.centralwidget)
self.tableTableWidget.setGeometry(QRect(260, 20, 1161, 360))
self.tableTableWidget.setObjectName("tableTableWidget")
self.tableTableWidget.setColumnCount(6)
self.tableTableWidget.setRowCount(0)
item = QTableWidgetItem()
self.tableTableWidget.setHorizontalHeaderItem(0, item)
item = QTableWidgetItem()
self.tableTableWidget.setHorizontalHeaderItem(1, item)
item = QTableWidgetItem()
self.tableTableWidget.setHorizontalHeaderItem(2, item)
item = QTableWidgetItem()
self.tableTableWidget.setHorizontalHeaderItem(3, item)
item = QTableWidgetItem()
self.tableTableWidget.setHorizontalHeaderItem(4, item)
item = QTableWidgetItem()
self.tableTableWidget.setHorizontalHeaderItem(5, item)
self.tableTableWidget.setSortingEnabled(True)
self.katCheckBox = QCheckBox(self.centralwidget)
self.katCheckBox.setGeometry(QRect(30, 110, 90, 20))
self.katCheckBox.setObjectName("katCheckBox")
self.nyaaCheckBox = QCheckBox(self.centralwidget)
self.nyaaCheckBox.setGeometry(QRect(30, 150, 90, 20))
self.nyaaCheckBox.setObjectName("nyaaCheckBox")
self.rarbgCheckBox = QCheckBox(self.centralwidget)
self.rarbgCheckBox.setGeometry(QRect(30, 190, 90, 20))
self.rarbgCheckBox.setObjectName("rarbgCheckBox")
self.tpbCheckBox = QCheckBox(self.centralwidget)
self.tpbCheckBox.setGeometry(QRect(30, 230, 90, 20))
self.tpbCheckBox.setObjectName("tpbCheckBox")
self.searchPushButton = QPushButton(self.centralwidget)
self.searchPushButton.setGeometry(QRect(30, 350, 90, 30))
font = QFont()
font.setPointSize(8)
self.searchPushButton.setFont(font)
self.searchPushButton.setObjectName("searchPushButton")
self.limitSlider = QSlider(self.centralwidget)
self.limitSlider.setGeometry(QRect(1450, 40, 22, 320))
self.limitSlider.setMaximum(20)
self.limitSlider.setPageStep(2)
self.limitSlider.setSliderPosition(10)
self.limitSlider.setOrientation(Qt.Vertical)
self.limitSlider.setObjectName("limitSlider")
self.minimumLabel = QLabel(self.centralwidget)
self.minimumLabel.setGeometry(QRect(1452, 365, 16, 16))
font = QFont()
font.setPointSize(9)
self.minimumLabel.setFont(font)
self.minimumLabel.setAlignment(Qt.AlignCenter)
self.minimumLabel.setObjectName("minimumLabel")
self.maximumLabel = QLabel(self.centralwidget)
self.maximumLabel.setGeometry(QRect(1452, 20, 16, 16))
font = QFont()
font.setPointSize(9)
self.maximumLabel.setFont(font)
self.maximumLabel.setAlignment(Qt.AlignCenter)
self.maximumLabel.setObjectName("maximumLabel")
searchMainWindow.setCentralWidget(self.centralwidget)
self.searchPushButton.clicked.connect(self.callback)
self.tableTableWidget.itemClicked.connect(self.copy)
self.retranslateUi(searchMainWindow)
QMetaObject.connectSlotsByName(searchMainWindow)
def retranslateUi(self, searchMainWindow):
_translate = QCoreApplication.translate
searchMainWindow.setWindowTitle(_translate(
"searchMainWindow", "MagnetMagnet - Search"))
self.x1377CheckBox.setText(_translate("searchMainWindow", "1377x"))
item = self.tableTableWidget.horizontalHeaderItem(0)
item.setText(_translate("searchMainWindow", "Titles"))
item = self.tableTableWidget.horizontalHeaderItem(1)
item.setText(_translate("searchMainWindow", "Seeders"))
item = self.tableTableWidget.horizontalHeaderItem(2)
item.setText(_translate("searchMainWindow", "Leechers"))
item = self.tableTableWidget.horizontalHeaderItem(3)
item.setText(_translate("searchMainWindow", "Sizes"))
item = self.tableTableWidget.horizontalHeaderItem(4)
item.setText(_translate("searchMainWindow", "Dates"))
item = self.tableTableWidget.horizontalHeaderItem(5)
item.setText(_translate("searchMainWindow", "Source"))
self.katCheckBox.setText(_translate("searchMainWindow", "KAT"))
self.nyaaCheckBox.setText(_translate("searchMainWindow", "Nyaa"))
self.rarbgCheckBox.setText(_translate("searchMainWindow", "RARBG"))
self.tpbCheckBox.setText(_translate("searchMainWindow", "TPB"))
self.searchPushButton.setText(_translate("searchMainWindow", "Search"))
self.minimumLabel.setText(_translate("searchMainWindow", "0"))
self.maximumLabel.setText(_translate("searchMainWindow", "20"))
| true | true |
f72c091ee41e3a1bdb0176021673692667130530 | 1,631 | py | Python | mcp/lib/Slack.py | vspeter/MCP | 1f8ee863d64a2c276c47f1f8c4803983bff88fb7 | [
"Apache-2.0"
] | null | null | null | mcp/lib/Slack.py | vspeter/MCP | 1f8ee863d64a2c276c47f1f8c4803983bff88fb7 | [
"Apache-2.0"
] | null | null | null | mcp/lib/Slack.py | vspeter/MCP | 1f8ee863d64a2c276c47f1f8c4803983bff88fb7 | [
"Apache-2.0"
] | 1 | 2021-02-24T16:51:11.000Z | 2021-02-24T16:51:11.000Z | import json
import logging
from urllib import request, parse
class Slack():
NOTSET = ':loudspeaker:'
DEBUG = ':speaker:'
INFO = ':information_source:'
WARNING = ':warning:'
ERROR = ':exclamation:'
CRITICAL = ':boom:'
SUCCESS = ':+1:'
DONE = ':checkered_flag:'
def __init__( self, proc, api_token, channel_name, site=None, proxy=None ):
self.api_token = api_token
self.channel_name = channel_name
self.user_name = 'mcp({0})-{1}'.format( site, proc ) if site else 'mcp-{0}'.format( proc )
self.slack_api_base_url = 'https://slack.com/api'
if proxy:
self.opener = request.build_opener( request.ProxyHandler( { 'http': proxy, 'https': proxy } ) )
else:
self.opener = request.build_opener( request.ProxyHandler( {} ) )
def post_message( self, message, emoji=NOTSET ):
if self.api_token is None:
return
data = {
'token': self.api_token,
'channel': self.channel_name,
'username': self.user_name,
'text': message,
'icon_emoji': emoji
}
url = '{0}/{1}'.format( self.slack_api_base_url, 'chat.postMessage' )
data = parse.urlencode( data )
try:
resp = self.opener.open( url, data=data.encode() )
except Exception as e:
logging.warning( 'Slack: Got Exception "{0}" when posting message'.format( e ) )
return
rc = resp.read()
resp.close()
try:
rc = json.loads( rc )
except TypeError:
logging.warning( 'Slack: Response not valid JSON.' )
return
if 'ok' not in rc:
logging.warning( 'Slack: Failed to post message {0}'.format( rc ) )
return
| 28.614035 | 101 | 0.619865 | import json
import logging
from urllib import request, parse
class Slack():
NOTSET = ':loudspeaker:'
DEBUG = ':speaker:'
INFO = ':information_source:'
WARNING = ':warning:'
ERROR = ':exclamation:'
CRITICAL = ':boom:'
SUCCESS = ':+1:'
DONE = ':checkered_flag:'
def __init__( self, proc, api_token, channel_name, site=None, proxy=None ):
self.api_token = api_token
self.channel_name = channel_name
self.user_name = 'mcp({0})-{1}'.format( site, proc ) if site else 'mcp-{0}'.format( proc )
self.slack_api_base_url = 'https://slack.com/api'
if proxy:
self.opener = request.build_opener( request.ProxyHandler( { 'http': proxy, 'https': proxy } ) )
else:
self.opener = request.build_opener( request.ProxyHandler( {} ) )
def post_message( self, message, emoji=NOTSET ):
if self.api_token is None:
return
data = {
'token': self.api_token,
'channel': self.channel_name,
'username': self.user_name,
'text': message,
'icon_emoji': emoji
}
url = '{0}/{1}'.format( self.slack_api_base_url, 'chat.postMessage' )
data = parse.urlencode( data )
try:
resp = self.opener.open( url, data=data.encode() )
except Exception as e:
logging.warning( 'Slack: Got Exception "{0}" when posting message'.format( e ) )
return
rc = resp.read()
resp.close()
try:
rc = json.loads( rc )
except TypeError:
logging.warning( 'Slack: Response not valid JSON.' )
return
if 'ok' not in rc:
logging.warning( 'Slack: Failed to post message {0}'.format( rc ) )
return
| true | true |
f72c09ac05b9052d87975715d4ccabff57f26a58 | 12,756 | py | Python | LaserRender.py | gsboylan/meerk40t | 7607b034368a428dfc5cab56629032d6074c756d | [
"MIT"
] | null | null | null | LaserRender.py | gsboylan/meerk40t | 7607b034368a428dfc5cab56629032d6074c756d | [
"MIT"
] | null | null | null | LaserRender.py | gsboylan/meerk40t | 7607b034368a428dfc5cab56629032d6074c756d | [
"MIT"
] | null | null | null | from math import floor
import wx
from PIL import Image
from ZMatrix import ZMatrix
from svgelements import *
"""
Laser Render provides GUI relevant methods of displaying the given project.
"""
DRAW_MODE_FILLS = 0x000001
DRAW_MODE_GUIDES = 0x000002
DRAW_MODE_GRID = 0x000004
DRAW_MODE_LASERPATH = 0x000008
DRAW_MODE_RETICLE = 0x000010
DRAW_MODE_SELECTION = 0x000020
DRAW_MODE_STROKES = 0x000040
DRAW_MODE_CACHE = 0x000080 # Set means do not cache.
DRAW_MODE_REFRESH = 0x000100
DRAW_MODE_ANIMATE = 0x000200
DRAW_MODE_PATH = 0x000400
DRAW_MODE_IMAGE = 0x000800
DRAW_MODE_TEXT = 0x001000
DRAW_MODE_BACKGROUND = 0x002000
DRAW_MODE_ICONS = 0x0040000
DRAW_MODE_TREE = 0x0080000
DRAW_MODE_INVERT = 0x400000
DRAW_MODE_FLIPXY = 0x800000
def swizzlecolor(c):
if c is None:
return None
if isinstance(c, int):
c = Color(c)
return c.blue << 16 | c.green << 8 | c.red
class LaserRender:
def __init__(self, device):
self.device = device
self.cache = None
self.pen = wx.Pen()
self.brush = wx.Brush()
self.color = wx.Colour()
def render(self, elements, gc, draw_mode=None, zoomscale=1):
"""
Render scene information.
:param gc:
:param draw_mode:
:return:
"""
if draw_mode is None:
draw_mode = self.device.draw_mode
if draw_mode & (DRAW_MODE_TEXT | DRAW_MODE_IMAGE | DRAW_MODE_PATH) != 0:
types = []
if draw_mode & DRAW_MODE_PATH == 0:
types.append(Path)
if draw_mode & DRAW_MODE_IMAGE == 0:
types.append(SVGImage)
if draw_mode & DRAW_MODE_TEXT == 0:
types.append(SVGText)
elements = [e for e in elements if type(e) in types]
for element in elements:
try:
element.draw(element, gc, draw_mode, zoomscale=zoomscale)
except AttributeError:
if isinstance(element, Path):
element.draw = self.draw_path
elif isinstance(element, SVGImage):
element.draw = self.draw_image
elif isinstance(element, SVGText):
element.draw = self.draw_text
elif isinstance(element, Group):
element.draw = self.draw_group
else:
continue
element.draw(element, gc, draw_mode, zoomscale=zoomscale)
def make_path(self, gc, path):
p = gc.CreatePath()
first_point = path.first_point
if first_point is not None:
p.MoveToPoint(first_point[0], first_point[1])
for e in path:
if isinstance(e, Move):
p.MoveToPoint(e.end[0], e.end[1])
elif isinstance(e, Line):
p.AddLineToPoint(e.end[0], e.end[1])
elif isinstance(e, Close):
p.CloseSubpath()
elif isinstance(e, QuadraticBezier):
p.AddQuadCurveToPoint(e.control[0], e.control[1],
e.end[0], e.end[1])
elif isinstance(e, CubicBezier):
p.AddCurveToPoint(e.control1[0], e.control1[1],
e.control2[0], e.control2[1],
e.end[0], e.end[1])
elif isinstance(e, Arc):
for curve in e.as_cubic_curves():
p.AddCurveToPoint(curve.control1[0], curve.control1[1],
curve.control2[0], curve.control2[1],
curve.end[0], curve.end[1])
return p
def set_pen(self, gc, stroke, width=1.0):
if width < 1.0:
width = 1.0
c = stroke
if c is not None and c != 'none':
swizzle_color = swizzlecolor(c)
self.color.SetRGBA(swizzle_color | c.alpha << 24) # wx has BBGGRR
self.pen.SetColour(self.color)
self.pen.SetWidth(width)
gc.SetPen(self.pen)
else:
gc.SetPen(wx.TRANSPARENT_PEN)
def set_brush(self, gc, fill):
c = fill
if c is not None and c != 'none':
swizzle_color = swizzlecolor(c)
self.color.SetRGBA(swizzle_color | c.alpha << 24) # wx has BBGGRR
self.brush.SetColour(self.color)
gc.SetBrush(self.brush)
else:
gc.SetBrush(wx.TRANSPARENT_BRUSH)
def set_element_pen(self, gc, element, zoomscale=1.0):
try:
sw = Length(element.stroke_width).value(ppi=96.0)
# if sw < 3.0:
# sw = 3.0
except AttributeError:
sw = 1.0
if sw is None:
sw = 1.0
limit = zoomscale**.5
if sw < limit:
sw = limit
self.set_pen(gc, element.stroke, width=sw)
def set_element_brush(self, gc, element):
self.set_brush(gc, element.fill)
def draw_path(self, element, gc, draw_mode, zoomscale=1.0):
"""Default draw routine for the laser path element."""
try:
matrix = element.transform
except AttributeError:
matrix = Matrix()
if not hasattr(element, 'cache') or element.cache is None:
cache = self.make_path(gc, element)
element.cache = cache
gc.PushState()
gc.ConcatTransform(wx.GraphicsContext.CreateMatrix(gc, ZMatrix(matrix)))
self.set_element_pen(gc, element, zoomscale=zoomscale)
self.set_element_brush(gc, element)
if draw_mode & DRAW_MODE_FILLS == 0 and element.fill is not None:
gc.FillPath(element.cache)
if draw_mode & DRAW_MODE_STROKES == 0 and element.stroke is not None:
gc.StrokePath(element.cache)
gc.PopState()
def draw_text(self, element, gc, draw_mode, zoomscale=1.0):
try:
matrix = element.transform
except AttributeError:
matrix = Matrix()
if hasattr(element, 'wxfont'):
font = element.wxfont
else:
if element.font_size < 1:
if element.font_size > 0:
element.transform.pre_scale(element.font_size,
element.font_size,
element.x,
element.y)
element.font_size = 1 # No zero sized fonts.
font = wx.Font(element.font_size, wx.SWISS, wx.NORMAL, wx.BOLD)
try:
f = []
if element.font_family is not None:
f.append(str(element.font_family))
if element.font_face is not None:
f.append(str(element.font_face))
if element.font_weight is not None:
f.append(str(element.font_weight))
f.append("%d" % element.font_size)
font.SetNativeFontInfoUserDesc(' '.join(f))
except:
pass
element.wxfont = font
gc.PushState()
gc.ConcatTransform(wx.GraphicsContext.CreateMatrix(gc, ZMatrix(matrix)))
self.set_element_pen(gc, element, zoomscale=zoomscale)
self.set_element_brush(gc, element)
if element.fill is None or element.fill == 'none':
gc.SetFont(font, wx.BLACK)
else:
gc.SetFont(font, wx.Colour(swizzlecolor(element.fill)))
text = element.text
x = element.x
y = element.y
if text is not None:
w, h = element.width, element.height
element.width, element.height = gc.GetTextExtent(element.text)
if w != element.width and h != element.height:
element.modified()
if not hasattr(element, 'anchor') or element.anchor == 'start':
y -= element.height
elif element.anchor == 'middle':
x -= (element.width / 2)
y -= element.height
elif element.anchor == 'end':
x -= element.width
y -= element.height
gc.DrawText(text, x, y)
gc.PopState()
def draw_image(self, node, gc, draw_mode, zoomscale=1.0):
try:
matrix = node.transform
except AttributeError:
matrix = Matrix()
gc.PushState()
gc.ConcatTransform(wx.GraphicsContext.CreateMatrix(gc, ZMatrix(matrix)))
if draw_mode & DRAW_MODE_CACHE == 0:
cache = None
try:
cache = node.cache
except AttributeError:
pass
if cache is None:
try:
max_allowed = node.max_allowed
except AttributeError:
max_allowed = 2048
node.c_width, node.c_height = node.image.size
node.cache = self.make_thumbnail(node.image, maximum=max_allowed)
gc.DrawBitmap(node.cache, 0, 0, node.c_width, node.c_height)
else:
node.c_width, node.c_height = node.image.size
cache = self.make_thumbnail(node.image)
gc.DrawBitmap(cache, 0, 0, node.c_width, node.c_height)
gc.PopState()
def draw_group(self, element, gc, draw_mode, zoomscale=1.0):
pass
def make_raster(self, elements, bounds, width=None, height=None, bitmap=False, step=1):
if bounds is None:
return None
xmin, ymin, xmax, ymax = bounds
xmax = ceil(xmax)
ymax = ceil(ymax)
xmin = floor(xmin)
ymin = floor(ymin)
image_width = int(xmax - xmin)
if image_width == 0:
image_width = 1
image_height = int(ymax - ymin)
if image_height == 0:
image_height = 1
if width is None:
width = image_width
if height is None:
height = image_height
width /= float(step)
height /= float(step)
width = int(width)
height = int(height)
bmp = wx.Bitmap(width, height, 32)
dc = wx.MemoryDC()
dc.SelectObject(bmp)
dc.SetBackground(wx.WHITE_BRUSH)
dc.Clear()
matrix = Matrix()
matrix.post_translate(-xmin, -ymin)
scale_x = width / float(image_width)
scale_y = height / float(image_height)
scale = min(scale_x, scale_y)
matrix.post_scale(scale)
gc = wx.GraphicsContext.Create(dc)
gc.SetInterpolationQuality(wx.INTERPOLATION_BEST)
gc.PushState()
gc.ConcatTransform(wx.GraphicsContext.CreateMatrix(gc, ZMatrix(matrix)))
gc.SetBrush(wx.WHITE_BRUSH)
gc.DrawRectangle(xmin - 1, ymin - 1, xmax + 1, ymax + 1)
if not isinstance(elements, (list, tuple)):
elements = [elements]
self.render(elements, gc, draw_mode=DRAW_MODE_CACHE)
gc.PopState()
img = bmp.ConvertToImage()
buf = img.GetData()
image = Image.frombuffer("RGB", tuple(bmp.GetSize()), bytes(buf), "raw", "RGB", 0, 1)
gc.Destroy()
del dc
if bitmap:
return bmp
return image
def make_thumbnail(self, pil_data, maximum=None, width=None, height=None):
"""Resizes the given pil image into wx.Bitmap object that fits the constraints."""
image_width, image_height = pil_data.size
if width is not None and height is None:
height = width * image_height / float(image_width)
if width is None and height is not None:
width = height * image_width / float(image_height)
if width is None and height is None:
width = image_width
height = image_height
if maximum is not None and (width > maximum or height > maximum):
scale_x = maximum / width
scale_y = maximum / height
scale = min(scale_x, scale_y)
width = int(round(width * scale))
height = int(round(height * scale))
if image_width != width or image_height != height:
pil_data = pil_data.copy().resize((width, height))
else:
pil_data = pil_data.copy()
if pil_data.mode != "RGBA":
pil_data = pil_data.convert('RGBA')
pil_bytes = pil_data.tobytes()
return wx.Bitmap.FromBufferRGBA(width, height, pil_bytes)
| 37.189504 | 94 | 0.541863 | from math import floor
import wx
from PIL import Image
from ZMatrix import ZMatrix
from svgelements import *
DRAW_MODE_FILLS = 0x000001
DRAW_MODE_GUIDES = 0x000002
DRAW_MODE_GRID = 0x000004
DRAW_MODE_LASERPATH = 0x000008
DRAW_MODE_RETICLE = 0x000010
DRAW_MODE_SELECTION = 0x000020
DRAW_MODE_STROKES = 0x000040
DRAW_MODE_CACHE = 0x000080
DRAW_MODE_REFRESH = 0x000100
DRAW_MODE_ANIMATE = 0x000200
DRAW_MODE_PATH = 0x000400
DRAW_MODE_IMAGE = 0x000800
DRAW_MODE_TEXT = 0x001000
DRAW_MODE_BACKGROUND = 0x002000
DRAW_MODE_ICONS = 0x0040000
DRAW_MODE_TREE = 0x0080000
DRAW_MODE_INVERT = 0x400000
DRAW_MODE_FLIPXY = 0x800000
def swizzlecolor(c):
if c is None:
return None
if isinstance(c, int):
c = Color(c)
return c.blue << 16 | c.green << 8 | c.red
class LaserRender:
def __init__(self, device):
self.device = device
self.cache = None
self.pen = wx.Pen()
self.brush = wx.Brush()
self.color = wx.Colour()
def render(self, elements, gc, draw_mode=None, zoomscale=1):
if draw_mode is None:
draw_mode = self.device.draw_mode
if draw_mode & (DRAW_MODE_TEXT | DRAW_MODE_IMAGE | DRAW_MODE_PATH) != 0:
types = []
if draw_mode & DRAW_MODE_PATH == 0:
types.append(Path)
if draw_mode & DRAW_MODE_IMAGE == 0:
types.append(SVGImage)
if draw_mode & DRAW_MODE_TEXT == 0:
types.append(SVGText)
elements = [e for e in elements if type(e) in types]
for element in elements:
try:
element.draw(element, gc, draw_mode, zoomscale=zoomscale)
except AttributeError:
if isinstance(element, Path):
element.draw = self.draw_path
elif isinstance(element, SVGImage):
element.draw = self.draw_image
elif isinstance(element, SVGText):
element.draw = self.draw_text
elif isinstance(element, Group):
element.draw = self.draw_group
else:
continue
element.draw(element, gc, draw_mode, zoomscale=zoomscale)
def make_path(self, gc, path):
p = gc.CreatePath()
first_point = path.first_point
if first_point is not None:
p.MoveToPoint(first_point[0], first_point[1])
for e in path:
if isinstance(e, Move):
p.MoveToPoint(e.end[0], e.end[1])
elif isinstance(e, Line):
p.AddLineToPoint(e.end[0], e.end[1])
elif isinstance(e, Close):
p.CloseSubpath()
elif isinstance(e, QuadraticBezier):
p.AddQuadCurveToPoint(e.control[0], e.control[1],
e.end[0], e.end[1])
elif isinstance(e, CubicBezier):
p.AddCurveToPoint(e.control1[0], e.control1[1],
e.control2[0], e.control2[1],
e.end[0], e.end[1])
elif isinstance(e, Arc):
for curve in e.as_cubic_curves():
p.AddCurveToPoint(curve.control1[0], curve.control1[1],
curve.control2[0], curve.control2[1],
curve.end[0], curve.end[1])
return p
def set_pen(self, gc, stroke, width=1.0):
if width < 1.0:
width = 1.0
c = stroke
if c is not None and c != 'none':
swizzle_color = swizzlecolor(c)
self.color.SetRGBA(swizzle_color | c.alpha << 24)
self.pen.SetColour(self.color)
self.pen.SetWidth(width)
gc.SetPen(self.pen)
else:
gc.SetPen(wx.TRANSPARENT_PEN)
def set_brush(self, gc, fill):
c = fill
if c is not None and c != 'none':
swizzle_color = swizzlecolor(c)
self.color.SetRGBA(swizzle_color | c.alpha << 24)
self.brush.SetColour(self.color)
gc.SetBrush(self.brush)
else:
gc.SetBrush(wx.TRANSPARENT_BRUSH)
def set_element_pen(self, gc, element, zoomscale=1.0):
try:
sw = Length(element.stroke_width).value(ppi=96.0)
except AttributeError:
sw = 1.0
if sw is None:
sw = 1.0
limit = zoomscale**.5
if sw < limit:
sw = limit
self.set_pen(gc, element.stroke, width=sw)
def set_element_brush(self, gc, element):
self.set_brush(gc, element.fill)
def draw_path(self, element, gc, draw_mode, zoomscale=1.0):
try:
matrix = element.transform
except AttributeError:
matrix = Matrix()
if not hasattr(element, 'cache') or element.cache is None:
cache = self.make_path(gc, element)
element.cache = cache
gc.PushState()
gc.ConcatTransform(wx.GraphicsContext.CreateMatrix(gc, ZMatrix(matrix)))
self.set_element_pen(gc, element, zoomscale=zoomscale)
self.set_element_brush(gc, element)
if draw_mode & DRAW_MODE_FILLS == 0 and element.fill is not None:
gc.FillPath(element.cache)
if draw_mode & DRAW_MODE_STROKES == 0 and element.stroke is not None:
gc.StrokePath(element.cache)
gc.PopState()
def draw_text(self, element, gc, draw_mode, zoomscale=1.0):
try:
matrix = element.transform
except AttributeError:
matrix = Matrix()
if hasattr(element, 'wxfont'):
font = element.wxfont
else:
if element.font_size < 1:
if element.font_size > 0:
element.transform.pre_scale(element.font_size,
element.font_size,
element.x,
element.y)
element.font_size = 1
font = wx.Font(element.font_size, wx.SWISS, wx.NORMAL, wx.BOLD)
try:
f = []
if element.font_family is not None:
f.append(str(element.font_family))
if element.font_face is not None:
f.append(str(element.font_face))
if element.font_weight is not None:
f.append(str(element.font_weight))
f.append("%d" % element.font_size)
font.SetNativeFontInfoUserDesc(' '.join(f))
except:
pass
element.wxfont = font
gc.PushState()
gc.ConcatTransform(wx.GraphicsContext.CreateMatrix(gc, ZMatrix(matrix)))
self.set_element_pen(gc, element, zoomscale=zoomscale)
self.set_element_brush(gc, element)
if element.fill is None or element.fill == 'none':
gc.SetFont(font, wx.BLACK)
else:
gc.SetFont(font, wx.Colour(swizzlecolor(element.fill)))
text = element.text
x = element.x
y = element.y
if text is not None:
w, h = element.width, element.height
element.width, element.height = gc.GetTextExtent(element.text)
if w != element.width and h != element.height:
element.modified()
if not hasattr(element, 'anchor') or element.anchor == 'start':
y -= element.height
elif element.anchor == 'middle':
x -= (element.width / 2)
y -= element.height
elif element.anchor == 'end':
x -= element.width
y -= element.height
gc.DrawText(text, x, y)
gc.PopState()
def draw_image(self, node, gc, draw_mode, zoomscale=1.0):
try:
matrix = node.transform
except AttributeError:
matrix = Matrix()
gc.PushState()
gc.ConcatTransform(wx.GraphicsContext.CreateMatrix(gc, ZMatrix(matrix)))
if draw_mode & DRAW_MODE_CACHE == 0:
cache = None
try:
cache = node.cache
except AttributeError:
pass
if cache is None:
try:
max_allowed = node.max_allowed
except AttributeError:
max_allowed = 2048
node.c_width, node.c_height = node.image.size
node.cache = self.make_thumbnail(node.image, maximum=max_allowed)
gc.DrawBitmap(node.cache, 0, 0, node.c_width, node.c_height)
else:
node.c_width, node.c_height = node.image.size
cache = self.make_thumbnail(node.image)
gc.DrawBitmap(cache, 0, 0, node.c_width, node.c_height)
gc.PopState()
def draw_group(self, element, gc, draw_mode, zoomscale=1.0):
pass
def make_raster(self, elements, bounds, width=None, height=None, bitmap=False, step=1):
if bounds is None:
return None
xmin, ymin, xmax, ymax = bounds
xmax = ceil(xmax)
ymax = ceil(ymax)
xmin = floor(xmin)
ymin = floor(ymin)
image_width = int(xmax - xmin)
if image_width == 0:
image_width = 1
image_height = int(ymax - ymin)
if image_height == 0:
image_height = 1
if width is None:
width = image_width
if height is None:
height = image_height
width /= float(step)
height /= float(step)
width = int(width)
height = int(height)
bmp = wx.Bitmap(width, height, 32)
dc = wx.MemoryDC()
dc.SelectObject(bmp)
dc.SetBackground(wx.WHITE_BRUSH)
dc.Clear()
matrix = Matrix()
matrix.post_translate(-xmin, -ymin)
scale_x = width / float(image_width)
scale_y = height / float(image_height)
scale = min(scale_x, scale_y)
matrix.post_scale(scale)
gc = wx.GraphicsContext.Create(dc)
gc.SetInterpolationQuality(wx.INTERPOLATION_BEST)
gc.PushState()
gc.ConcatTransform(wx.GraphicsContext.CreateMatrix(gc, ZMatrix(matrix)))
gc.SetBrush(wx.WHITE_BRUSH)
gc.DrawRectangle(xmin - 1, ymin - 1, xmax + 1, ymax + 1)
if not isinstance(elements, (list, tuple)):
elements = [elements]
self.render(elements, gc, draw_mode=DRAW_MODE_CACHE)
gc.PopState()
img = bmp.ConvertToImage()
buf = img.GetData()
image = Image.frombuffer("RGB", tuple(bmp.GetSize()), bytes(buf), "raw", "RGB", 0, 1)
gc.Destroy()
del dc
if bitmap:
return bmp
return image
def make_thumbnail(self, pil_data, maximum=None, width=None, height=None):
image_width, image_height = pil_data.size
if width is not None and height is None:
height = width * image_height / float(image_width)
if width is None and height is not None:
width = height * image_width / float(image_height)
if width is None and height is None:
width = image_width
height = image_height
if maximum is not None and (width > maximum or height > maximum):
scale_x = maximum / width
scale_y = maximum / height
scale = min(scale_x, scale_y)
width = int(round(width * scale))
height = int(round(height * scale))
if image_width != width or image_height != height:
pil_data = pil_data.copy().resize((width, height))
else:
pil_data = pil_data.copy()
if pil_data.mode != "RGBA":
pil_data = pil_data.convert('RGBA')
pil_bytes = pil_data.tobytes()
return wx.Bitmap.FromBufferRGBA(width, height, pil_bytes)
| true | true |
f72c09ef26d7bd7db7719016288f760059b46e7e | 561 | py | Python | starry_night.py | weijun-github/some-python-codes | db3d4b4ceb8b7c8ce0bd4b61da6227cd9e994718 | [
"MIT"
] | null | null | null | starry_night.py | weijun-github/some-python-codes | db3d4b4ceb8b7c8ce0bd4b61da6227cd9e994718 | [
"MIT"
] | null | null | null | starry_night.py | weijun-github/some-python-codes | db3d4b4ceb8b7c8ce0bd4b61da6227cd9e994718 | [
"MIT"
] | null | null | null | from turtle import *
from random import randint, random
def draw_star(points,size,col,x,y):
penup()
goto(x,y)
pendown()
angle = 180 - (180 / points)
color(col)
begin_fill()
for i in range(points):
forward(size)
right(angle)
end_fill()
# main code
Screen().bgcolor("dark blue")
speed(0)
while True:
points = randint(2,5) * 2 + 1
size = randint(10,50)
col = (random(),random(),random())
x = randint(-350,300)
y = randint(-250,250)
draw_star(points,size,col,x,y) | 20.777778 | 39 | 0.57041 | from turtle import *
from random import randint, random
def draw_star(points,size,col,x,y):
penup()
goto(x,y)
pendown()
angle = 180 - (180 / points)
color(col)
begin_fill()
for i in range(points):
forward(size)
right(angle)
end_fill()
Screen().bgcolor("dark blue")
speed(0)
while True:
points = randint(2,5) * 2 + 1
size = randint(10,50)
col = (random(),random(),random())
x = randint(-350,300)
y = randint(-250,250)
draw_star(points,size,col,x,y) | true | true |
f72c09f7de9a8713a8c125758c01f1bfe2118188 | 13,359 | py | Python | fanficfare/adapters/adapter_bloodtiesfancom.py | Kolbo5/FanFicFare | cf2ae9b12631bfeeb9198ca686f9e58d4579aeb3 | [
"Apache-2.0"
] | null | null | null | fanficfare/adapters/adapter_bloodtiesfancom.py | Kolbo5/FanFicFare | cf2ae9b12631bfeeb9198ca686f9e58d4579aeb3 | [
"Apache-2.0"
] | null | null | null | fanficfare/adapters/adapter_bloodtiesfancom.py | Kolbo5/FanFicFare | cf2ae9b12631bfeeb9198ca686f9e58d4579aeb3 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2011 Fanficdownloader team, 2018 FanFicFare team
#
# 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.
#
# Software: eFiction
from __future__ import absolute_import
import logging
logger = logging.getLogger(__name__)
import re
from bs4.element import Tag
from ..htmlcleanup import stripHTML
from .. import exceptions as exceptions
# py2 vs py3 transition
from ..six import text_type as unicode
from ..six.moves.urllib.error import HTTPError
from .base_adapter import BaseSiteAdapter, makeDate
# By virtue of being recent and requiring both is_adult and user/pass,
# adapter_fanficcastletvnet.py is the best choice for learning to
# write adapters--especially for sites that use the eFiction system.
# Most sites that have ".../viewstory.php?sid=123" in the story URL
# are eFiction.
# For non-eFiction sites, it can be considerably more complex, but
# this is still a good starting point.
# In general an 'adapter' needs to do these five things:
# - 'Register' correctly with the downloader
# - Site Login (if needed)
# - 'Are you adult?' check (if needed--some do one, some the other, some both)
# - Grab the chapter list
# - Grab the story meta-data (some (non-eFiction) adapters have to get it from the author page)
# - Grab the chapter texts
# Search for XXX comments--that's where things are most likely to need changing.
# This function is called by the downloader in all adapter_*.py files
# in this dir to register the adapter class. So it needs to be
# updated to reflect the class below it. That, plus getSiteDomain()
# take care of 'Registering'.
def getClass():
return BloodTiesFansComAdapter # XXX
# Class name has to be unique. Our convention is camel case the
# sitename with Adapter at the end. www is skipped.
class BloodTiesFansComAdapter(BaseSiteAdapter): # XXX
def __init__(self, config, url):
BaseSiteAdapter.__init__(self, config, url)
self.is_adult=False
# get storyId from url--url validation guarantees query is only sid=1234
self.story.setMetadata('storyId',self.parsedUrl.query.split('=',)[1])
# normalized story URL.
# XXX Most sites don't have the /fanfic part. Replace all to remove it usually.
self._setURL('http://' + self.getSiteDomain() + '/fiction/viewstory.php?sid='+self.story.getMetadata('storyId'))
# Each adapter needs to have a unique site abbreviation.
self.story.setMetadata('siteabbrev','btf') # XXX
# The date format will vary from site to site.
# http://docs.python.org/library/datetime.html#strftime-strptime-behavior
self.dateformat = "%d %b %Y" # XXX
@staticmethod # must be @staticmethod, don't remove it.
def getSiteDomain():
# The site domain. Does have www here, if it uses it.
return 'bloodties-fans.com' # XXX
@classmethod
def getSiteExampleURLs(cls):
return "http://"+cls.getSiteDomain()+"/fiction/viewstory.php?sid=1234"
def getSiteURLPattern(self):
return re.escape("http://"+self.getSiteDomain()+"/fiction/viewstory.php?sid=")+r"\d+$"
## Login seems to be reasonably standard across eFiction sites.
def needToLoginCheck(self, data):
if 'Registered Users Only' in data \
or 'There is no such account on our website' in data \
or "That password doesn't match the one in our database" in data:
return True
else:
return False
def performLogin(self, url):
params = {}
if self.password:
params['penname'] = self.username
params['password'] = self.password
else:
params['penname'] = self.getConfig("username")
params['password'] = self.getConfig("password")
params['cookiecheck'] = '1'
params['submit'] = 'Submit'
loginUrl = 'http://' + self.getSiteDomain() + '/fiction/user.php?action=login'
logger.debug("Will now login to URL (%s) as (%s)" % (loginUrl,
params['penname']))
d = self._fetchUrl(loginUrl, params)
if "Member Account" not in d : #Member Account
logger.info("Failed to login to URL %s as %s" % (loginUrl,
params['penname']))
raise exceptions.FailedToLogin(url,params['penname'])
return False
else:
return True
## Getting the chapter list and the meta data, plus 'is adult' checking.
def extractChapterUrlsAndMetadata(self):
if self.is_adult or self.getConfig("is_adult"):
# Weirdly, different sites use different warning numbers.
# If the title search below fails, there's a good chance
# you need a different number. print data at that point
# and see what the 'click here to continue' url says.
# Furthermore, there's a couple sites now with more than
# one warning level for different ratings. And they're
# fussy about it. midnightwhispers has three: 4, 2 & 1.
# we'll try 1 first.
addurl = "&ageconsent=ok&warning=4" # XXX
else:
addurl=""
# index=1 makes sure we see the story chapter index. Some
# sites skip that for one-chapter stories.
url = self.url+'&index=1'+addurl
logger.debug("URL: "+url)
try:
data = self._fetchUrl(url)
except HTTPError as e:
if e.code == 404:
raise exceptions.StoryDoesNotExist(self.url)
else:
raise e
# The actual text that is used to announce you need to be an
# adult varies from site to site. Again, print data before
# the title search to troubleshoot.
# Since the warning text can change by warning level, let's
# look for the warning pass url. nfacommunity uses
# &warning= -- actually, so do other sites. Must be an
# eFiction book.
# viewstory.php?sid=561&warning=4
# viewstory.php?sid=561&warning=1
# viewstory.php?sid=561&warning=2
#print data
#m = re.search(r"'viewstory.php\?sid=1882(&warning=4)'",data)
m = re.search(r"'viewstory.php\?sid=\d+((?:&ageconsent=ok)?&warning=\d+)'",data)
if m != None:
if self.is_adult or self.getConfig("is_adult"):
# We tried the default and still got a warning, so
# let's pull the warning number from the 'continue'
# link and reload data.
addurl = m.group(1)
# correct stupid & error in url.
addurl = addurl.replace("&","&")
url = self.url+'&index=1'+addurl
logger.debug("URL 2nd try: "+url)
try:
data = self._fetchUrl(url)
except HTTPError as e:
if e.code == 404:
raise exceptions.StoryDoesNotExist(self.url)
else:
raise e
else:
raise exceptions.AdultCheckRequired(self.url)
if "Access denied. This story has not been validated by the adminstrators of this site." in data:
raise exceptions.AccessDenied(self.getSiteDomain() +" says: Access denied. This story has not been validated by the adminstrators of this site.")
# use BeautifulSoup HTML parser to make everything easier to find.
soup = self.make_soup(data)
# print data
# Now go hunting for all the meta data and the chapter list.
## Title
a = soup.find('a', href=re.compile(r'viewstory.php\?sid='+self.story.getMetadata('storyId')+"$"))
self.story.setMetadata('title',stripHTML(a))
# Find authorid and URL from... author url.
a = soup.find('a', href=re.compile(r"viewuser.php\?uid=\d+"))
self.story.setMetadata('authorId',a['href'].split('=')[1])
self.story.setMetadata('authorUrl','http://'+self.host+'/fiction/'+a['href'])
self.story.setMetadata('author',a.string)
# Find the chapters:
for chapter in soup.findAll('a', href=re.compile(r'viewstory.php\?sid='+self.story.getMetadata('storyId')+r"&chapter=\d+$")):
# just in case there's tags, like <i> in chapter titles.
self.add_chapter(chapter,'http://'+self.host+'/fiction/'+chapter['href']+addurl)
# eFiction sites don't help us out a lot with their meta data
# formating, so it's a little ugly.
# utility method
def defaultGetattr(d,k):
try:
return d[k]
except:
return ""
listbox = soup.find('div',{'class':'listbox'})
# <strong>Rating:</strong> M<br /> etc
labels = listbox.findAll('strong')
for labelspan in labels:
value = labelspan.nextSibling
label = labelspan.string
if 'Summary' in label:
## Everything until the next strong tag.
svalue = ""
while not isinstance(value,Tag) or value.name != 'strong':
svalue += unicode(value)
value = value.nextSibling
self.setDescription(url,svalue)
#self.story.setMetadata('description',stripHTML(svalue))
if 'Rating' in label:
self.story.setMetadata('rating', value)
if 'Words' in label:
value=re.sub(r"\|",r"",value)
self.story.setMetadata('numWords', value)
if 'Categories' in label:
cats = labelspan.parent.findAll('a',href=re.compile(r'browse.php\?type=categories'))
catstext = [cat.string for cat in cats]
for cat in catstext:
self.story.addToList('category',cat.string)
if 'Characters' in label:
chars = labelspan.parent.findAll('a',href=re.compile(r'browse.php\?type=characters'))
charstext = [char.string for char in chars]
for char in charstext:
self.story.addToList('characters',char.string)
if 'Completed' in label:
if 'Yes' in value:
self.story.setMetadata('status', 'Completed')
else:
self.story.setMetadata('status', 'In-Progress')
if 'Published' in label:
value=re.sub(r"\|",r"",value)
self.story.setMetadata('datePublished', makeDate(stripHTML(value), self.dateformat))
if 'Updated' in label:
value=re.sub(r"\|",r"",value)
self.story.setMetadata('dateUpdated', makeDate(stripHTML(value), self.dateformat))
# moved outside because they changed *most*, but not *all* labels to <strong>
ships = listbox.findAll('a',href=re.compile(r'browse.php.type=class&(amp;)?type_id=2')) # crappy html: & vs & in url.
shipstext = [ship.string for ship in ships]
for ship in shipstext:
self.story.addToList('ships',ship.string)
genres = listbox.findAll('a',href=re.compile(r'browse.php\?type=class&(amp;)?type_id=1')) # crappy html: & vs & in url.
genrestext = [genre.string for genre in genres]
for genre in genrestext:
self.story.addToList('genre',genre.string)
try:
# Find Series name from series URL.
a = soup.find('a', href=re.compile(r"viewseries.php\?seriesid=\d+"))
series_name = a.string
series_url = 'http://'+self.host+'/fiction/'+a['href']
# use BeautifulSoup HTML parser to make everything easier to find.
seriessoup = self.make_soup(self._fetchUrl(series_url))
storyas = seriessoup.findAll('a', href=re.compile(r'^viewstory.php\?sid=\d+$'))
i=1
for a in storyas:
if a['href'] == ('viewstory.php?sid='+self.story.getMetadata('storyId')):
self.setSeries(series_name, i)
self.story.setMetadata('seriesUrl',series_url)
break
i+=1
except:
# I find it hard to care if the series parsing fails
pass
# grab the text for an individual chapter.
def getChapterText(self, url):
logger.debug('Getting chapter text from: %s' % url)
soup = self.make_soup(self._fetchUrl(url))
div = soup.find('div', {'id' : 'story'})
if None == div:
raise exceptions.FailedToDownload("Error downloading Chapter: %s! Missing required element!" % url)
return self.utf8FromSoup(url,div)
| 40.853211 | 157 | 0.601991 |
from __future__ import absolute_import
import logging
logger = logging.getLogger(__name__)
import re
from bs4.element import Tag
from ..htmlcleanup import stripHTML
from .. import exceptions as exceptions
from ..six import text_type as unicode
from ..six.moves.urllib.error import HTTPError
from .base_adapter import BaseSiteAdapter, makeDate
# This function is called by the downloader in all adapter_*.py files
# in this dir to register the adapter class. So it needs to be
# updated to reflect the class below it. That, plus getSiteDomain()
# take care of 'Registering'.
def getClass():
return BloodTiesFansComAdapter # XXX
# Class name has to be unique. Our convention is camel case the
# sitename with Adapter at the end. www is skipped.
class BloodTiesFansComAdapter(BaseSiteAdapter): # XXX
def __init__(self, config, url):
BaseSiteAdapter.__init__(self, config, url)
self.is_adult=False
# get storyId from url--url validation guarantees query is only sid=1234
self.story.setMetadata('storyId',self.parsedUrl.query.split('=',)[1])
# normalized story URL.
# XXX Most sites don't have the /fanfic part. Replace all to remove it usually.
self._setURL('http://' + self.getSiteDomain() + '/fiction/viewstory.php?sid='+self.story.getMetadata('storyId'))
self.story.setMetadata('siteabbrev','btf')
"%d %b %Y"
@staticmethod
def getSiteDomain():
# The site domain. Does have www here, if it uses it.
return 'bloodties-fans.com' # XXX
@classmethod
def getSiteExampleURLs(cls):
return "http://"+cls.getSiteDomain()+"/fiction/viewstory.php?sid=1234"
def getSiteURLPattern(self):
return re.escape("http://"+self.getSiteDomain()+"/fiction/viewstory.php?sid=")+r"\d+$"
## Login seems to be reasonably standard across eFiction sites.
def needToLoginCheck(self, data):
if 'Registered Users Only' in data \
or 'There is no such account on our website' in data \
or "That password doesn't match the one in our database" in data:
return True
else:
return False
def performLogin(self, url):
params = {}
if self.password:
params['penname'] = self.username
params['password'] = self.password
else:
params['penname'] = self.getConfig("username")
params['password'] = self.getConfig("password")
params['cookiecheck'] = '1'
params['submit'] = 'Submit'
loginUrl = 'http://' + self.getSiteDomain() + '/fiction/user.php?action=login'
logger.debug("Will now login to URL (%s) as (%s)" % (loginUrl,
params['penname']))
d = self._fetchUrl(loginUrl, params)
if "Member Account" not in d :
logger.info("Failed to login to URL %s as %s" % (loginUrl,
params['penname']))
raise exceptions.FailedToLogin(url,params['penname'])
return False
else:
return True
or self.getConfig("is_adult"):
# you need a different number. print data at that point
# and see what the 'click here to continue' url says.
# Furthermore, there's a couple sites now with more than
# fussy about it. midnightwhispers has three: 4, 2 & 1.
# we'll try 1 first.
addurl = "&ageconsent=ok&warning=4"
else:
addurl=""
url = self.url+'&index=1'+addurl
logger.debug("URL: "+url)
try:
data = self._fetchUrl(url)
except HTTPError as e:
if e.code == 404:
raise exceptions.StoryDoesNotExist(self.url)
else:
raise e
# look for the warning pass url. nfacommunity uses
# &warning= -- actually, so do other sites. Must be an
# eFiction book.
# viewstory.php?sid=561&warning=4
# viewstory.php?sid=561&warning=1
# viewstory.php?sid=561&warning=2
#print data
#m = re.search(r"'viewstory.php\?sid=1882(&warning=4)'",data)
m = re.search(r"'viewstory.php\?sid=\d+((?:&ageconsent=ok)?&warning=\d+)'",data)
if m != None:
if self.is_adult or self.getConfig("is_adult"):
# We tried the default and still got a warning, so
# let's pull the warning number from the 'continue'
addurl = m.group(1)
addurl = addurl.replace("&","&")
url = self.url+'&index=1'+addurl
logger.debug("URL 2nd try: "+url)
try:
data = self._fetchUrl(url)
except HTTPError as e:
if e.code == 404:
raise exceptions.StoryDoesNotExist(self.url)
else:
raise e
else:
raise exceptions.AdultCheckRequired(self.url)
if "Access denied. This story has not been validated by the adminstrators of this site." in data:
raise exceptions.AccessDenied(self.getSiteDomain() +" says: Access denied. This story has not been validated by the adminstrators of this site.")
soup = self.make_soup(data)
a = soup.find('a', href=re.compile(r'viewstory.php\?sid='+self.story.getMetadata('storyId')+"$"))
self.story.setMetadata('title',stripHTML(a))
a = soup.find('a', href=re.compile(r"viewuser.php\?uid=\d+"))
self.story.setMetadata('authorId',a['href'].split('=')[1])
self.story.setMetadata('authorUrl','http://'+self.host+'/fiction/'+a['href'])
self.story.setMetadata('author',a.string)
for chapter in soup.findAll('a', href=re.compile(r'viewstory.php\?sid='+self.story.getMetadata('storyId')+r"&chapter=\d+$")):
self.add_chapter(chapter,'http://'+self.host+'/fiction/'+chapter['href']+addurl)
# eFiction sites don't help us out a lot with their meta data
# utility method
def defaultGetattr(d,k):
try:
return d[k]
except:
return ""
listbox = soup.find('div',{'class':'listbox'})
# <strong>Rating:</strong> M<br /> etc
labels = listbox.findAll('strong')
for labelspan in labels:
value = labelspan.nextSibling
label = labelspan.string
if 'Summary' in label:
## Everything until the next strong tag.
svalue = ""
while not isinstance(value,Tag) or value.name != 'strong':
svalue += unicode(value)
value = value.nextSibling
self.setDescription(url,svalue)
#self.story.setMetadata('description',stripHTML(svalue))
if 'Rating' in label:
self.story.setMetadata('rating', value)
if 'Words' in label:
value=re.sub(r"\|",r"",value)
self.story.setMetadata('numWords', value)
if 'Categories' in label:
cats = labelspan.parent.findAll('a',href=re.compile(r'browse.php\?type=categories'))
catstext = [cat.string for cat in cats]
for cat in catstext:
self.story.addToList('category',cat.string)
if 'Characters' in label:
chars = labelspan.parent.findAll('a',href=re.compile(r'browse.php\?type=characters'))
charstext = [char.string for char in chars]
for char in charstext:
self.story.addToList('characters',char.string)
if 'Completed' in label:
if 'Yes' in value:
self.story.setMetadata('status', 'Completed')
else:
self.story.setMetadata('status', 'In-Progress')
if 'Published' in label:
value=re.sub(r"\|",r"",value)
self.story.setMetadata('datePublished', makeDate(stripHTML(value), self.dateformat))
if 'Updated' in label:
value=re.sub(r"\|",r"",value)
self.story.setMetadata('dateUpdated', makeDate(stripHTML(value), self.dateformat))
# moved outside because they changed *most*, but not *all* labels to <strong>
ships = listbox.findAll('a',href=re.compile(r'browse.php.type=class&(amp;)?type_id=2')) # crappy html: & vs & in url.
shipstext = [ship.string for ship in ships]
for ship in shipstext:
self.story.addToList('ships',ship.string)
genres = listbox.findAll('a',href=re.compile(r'browse.php\?type=class&(amp;)?type_id=1')) # crappy html: & vs & in url.
genrestext = [genre.string for genre in genres]
for genre in genrestext:
self.story.addToList('genre',genre.string)
try:
# Find Series name from series URL.
a = soup.find('a', href=re.compile(r"viewseries.php\?seriesid=\d+"))
series_name = a.string
series_url = 'http://'+self.host+'/fiction/'+a['href']
# use BeautifulSoup HTML parser to make everything easier to find.
seriessoup = self.make_soup(self._fetchUrl(series_url))
storyas = seriessoup.findAll('a', href=re.compile(r'^viewstory.php\?sid=\d+$'))
i=1
for a in storyas:
if a['href'] == ('viewstory.php?sid='+self.story.getMetadata('storyId')):
self.setSeries(series_name, i)
self.story.setMetadata('seriesUrl',series_url)
break
i+=1
except:
# I find it hard to care if the series parsing fails
pass
# grab the text for an individual chapter.
def getChapterText(self, url):
logger.debug('Getting chapter text from: %s' % url)
soup = self.make_soup(self._fetchUrl(url))
div = soup.find('div', {'id' : 'story'})
if None == div:
raise exceptions.FailedToDownload("Error downloading Chapter: %s! Missing required element!" % url)
return self.utf8FromSoup(url,div)
| true | true |
f72c0a308bec3bcb670b9a62046fd98d6431cf98 | 109 | py | Python | callbacks/__init__.py | ivancreator/sgotgbot | fea3a8234610d1dee473688959167f430d43ad75 | [
"MIT"
] | null | null | null | callbacks/__init__.py | ivancreator/sgotgbot | fea3a8234610d1dee473688959167f430d43ad75 | [
"MIT"
] | null | null | null | callbacks/__init__.py | ivancreator/sgotgbot | fea3a8234610d1dee473688959167f430d43ad75 | [
"MIT"
] | null | null | null | from aiogram.utils.callback_data import CallbackData
cb_account = CallbackData('account', 'action', 'value') | 36.333333 | 55 | 0.798165 | from aiogram.utils.callback_data import CallbackData
cb_account = CallbackData('account', 'action', 'value') | true | true |
f72c0a6ac92672124a848a9846ceb3739ebe1129 | 6,194 | py | Python | module/LP.py | banboooo044/optimization | a15614b367712d6046311eac311214d27999fc7c | [
"MIT"
] | null | null | null | module/LP.py | banboooo044/optimization | a15614b367712d6046311eac311214d27999fc7c | [
"MIT"
] | null | null | null | module/LP.py | banboooo044/optimization | a15614b367712d6046311eac311214d27999fc7c | [
"MIT"
] | null | null | null | # date : 2/11/2019
# author : takeshi
import pandas as pd
import numpy as np
from IPython.display import display
def linprog(c,A,comp,b,maximize=True):
'''
Maximize(or Minimize) a linear objective function subject to linear equality and inequality constraints.
Linear Programming is intended to solve the following problem form:
Maximize: c * x
Subject to: A * x [comp] b , (x >= 0)
Parameters
----------
c : array_like
Coefficients of the linear objective function to be maximized.
A : array_like
2-D array which, when matrix-multiplied by x,
gives the values of constraints at x.
comp : array_like
1-D array of values representing a sign of equality in each constraint (row).
if value is -1 , it means (<=)
if value is 0 , it means (=)
if value is 1 , it means (=>)
b : array_like
1-D array of values representing the RHS of each constraint (row).
maximize : bool, optional
If True, the linear objective function is to be maximized.
If False, the linear objective function is to be minimized.
(the default is True)
Returns
-------
pandas.DataFrame
final simplex table.
Optimal solution is table['Values'] , and Optimal value is table['z','Values'].
if x is (1 * n) matrix , x_i ( i >= n ) is Slack Variable.
'''
# optimize
def optimize(table,target):
if not __debug__:
if target == 'w':
print("Phase 1 : find initial solution")
else:
if maximize:
print("Phase 2 : Maximize the liner objective function")
else:
print("Phase 2 : Minimize the liner objective function")
baseIndex = table.index.values
nonBaseIndex = np.setdiff1d(np.vectorize(lambda i : 'x' + str(i))(np.arange(len(table.columns)-1)) ,baseIndex)
for i in range(100000):
if not __debug__:
print("roop {0}".foramt(i))
display(table)
nonBaseTable = table.loc[target,nonBaseIndex]
if ((nonBaseTable < -1e-8).values.sum()) == 0:
return table
# 新たな基底変数
nextIndex = (nonBaseTable.map(lambda x: -x)).idxmax(axis=1)
# 取り替えられる基底変数
idx = table.index.get_loc(target)
tmpLine = (table['Value'].iloc[:idx] / table.loc[ : ,nextIndex].iloc[:idx] )
prevIndex = str(tmpLine.map(lambda x: float('inf') if x < 0 else x ).idxmin())
nonBaseIndex[np.where(nonBaseIndex == nextIndex)] = prevIndex
table = table.rename(index={prevIndex : nextIndex})
table.loc[nextIndex] /= table.at[nextIndex,nextIndex]
pivotLine = table.loc[nextIndex]
unPivotIndex = list(table.index.drop(nextIndex))
table.loc[unPivotIndex] = table.loc[unPivotIndex].apply(lambda x: x - (x.at[nextIndex]*pivotLine) ,axis=1)
print("cannot find base solutions")
if not maximize:
c = (-c)
n,m = A.shape
slackVariableNum = 0
artificialVariableNum = 0
slackVariable = [0] * n
artificialVariable = [0] * n
for i in range(n):
# bの値を全て正の値にしておく
if b[i] < 0:
A[i] = -A[i]
comp[i] = -comp[i]
b[i] = -b[i]
# < ( -> スラック変数を導入 )
if comp[i] == -1:
slackVariableNum += 1
slackVariable[i] = 1
# = ( -> 人為変数を導入 )
elif comp[i] == 0:
artificialVariableNum += 1
artificialVariable[i] = 1
# > ( -> スラック変数,人為変数を導入 )
else:
slackVariableNum += 1
artificialVariableNum += 1
slackVariable[i] = -1
artificialVariable[i] = 1
variableNum = c.shape[0] + slackVariableNum + artificialVariableNum
addVariableNum = slackVariableNum + artificialVariableNum
# Valueを求める.
baseIndex = np.empty(n)
baseValue = np.empty(n)
A_ = np.append(A , np.zeros((n,addVariableNum)),axis=1)
slackIter = c.shape[0]
artificialIter = c.shape[0] + slackVariableNum
# (スラック変数 < 人為変数) の優先順位で基底変数に選ぶ.
# すると , i 本目の制約条件式のみに登場する変数を選ぶことができる.
# baseIndex[i] := i 本目の制約条件式のみに登場する変数の番号
# baseValue[i] := i本目の制約条件式のみに登場する変数の値 ( = Value = b[i] ) となる.
for i in range(n):
if slackVariable[i] != 0:
A_[i,slackIter] = slackVariable[i]
# 1の場合
if slackVariable[i] > 0:
baseIndex[i],baseValue[i] = slackIter, b[i]
slackIter += 1
if artificialVariable[i] != 0:
A_[i,artificialIter] = artificialVariable[i]
baseIndex[i],baseValue[i] = artificialIter, b[i]
artificialIter += 1
# フェーズ1 (Valueを見つける)
# 目的関数の値をzとおく
# Valueの列を追加
exA = np.append(baseValue.reshape(n,1),A_,axis=1)
# zの行を追加
c_ = np.array([0]*(c.shape[0] + slackVariableNum) + [-1]*(artificialVariableNum))
c_ = c_[np.vectorize(int)(baseIndex)]
w = (c_ @ exA).reshape(1,variableNum+1)
z = np.append(np.append(np.zeros(1),-c),np.array([0]*addVariableNum)).reshape(1,variableNum+1)
table = np.append(np.append(exA,w,axis=0),z,axis=0)
# データフレームにする
df = pd.DataFrame(table,
columns=['Value']+[ 'x' + str(i) for i in range(variableNum)],
index= list(np.vectorize(lambda i: 'x' + str(int(i)))(baseIndex)) + ['w','z']
)
table = optimize(df,'w')
if artificialVariableNum != 0:
table = table.iloc[:,:-artificialVariableNum]
variableNum -= artificialVariableNum
table = table.drop('w')
result = optimize(table,'z')
if not maximize:
result['Value']['z'] = -result['Value']['z']
return result
## Example
if __name__ == '__main__':
# maximize 2 * x_0 + 3 * x_1
# constraints :
# 1 * x_0 + 2 * x_1 <= 10
# 2 * x_0 + 1 * x_0 <= 8
# ( x_0 >= 0 , x_1 >= 0)
c = np.array([ 2,3])
A = np.array([ [1,2],
[2,1] ])
comp = np.array([-1,-1])
b = np.array([10,8])
# solve
df = linprog(c,A,comp,b,True)
# result
print(df)
| 34.99435 | 118 | 0.56474 |
import pandas as pd
import numpy as np
from IPython.display import display
def linprog(c,A,comp,b,maximize=True):
def optimize(table,target):
if not __debug__:
if target == 'w':
print("Phase 1 : find initial solution")
else:
if maximize:
print("Phase 2 : Maximize the liner objective function")
else:
print("Phase 2 : Minimize the liner objective function")
baseIndex = table.index.values
nonBaseIndex = np.setdiff1d(np.vectorize(lambda i : 'x' + str(i))(np.arange(len(table.columns)-1)) ,baseIndex)
for i in range(100000):
if not __debug__:
print("roop {0}".foramt(i))
display(table)
nonBaseTable = table.loc[target,nonBaseIndex]
if ((nonBaseTable < -1e-8).values.sum()) == 0:
return table
nextIndex = (nonBaseTable.map(lambda x: -x)).idxmax(axis=1)
idx = table.index.get_loc(target)
tmpLine = (table['Value'].iloc[:idx] / table.loc[ : ,nextIndex].iloc[:idx] )
prevIndex = str(tmpLine.map(lambda x: float('inf') if x < 0 else x ).idxmin())
nonBaseIndex[np.where(nonBaseIndex == nextIndex)] = prevIndex
table = table.rename(index={prevIndex : nextIndex})
table.loc[nextIndex] /= table.at[nextIndex,nextIndex]
pivotLine = table.loc[nextIndex]
unPivotIndex = list(table.index.drop(nextIndex))
table.loc[unPivotIndex] = table.loc[unPivotIndex].apply(lambda x: x - (x.at[nextIndex]*pivotLine) ,axis=1)
print("cannot find base solutions")
if not maximize:
c = (-c)
n,m = A.shape
slackVariableNum = 0
artificialVariableNum = 0
slackVariable = [0] * n
artificialVariable = [0] * n
for i in range(n):
if b[i] < 0:
A[i] = -A[i]
comp[i] = -comp[i]
b[i] = -b[i]
if comp[i] == -1:
slackVariableNum += 1
slackVariable[i] = 1
elif comp[i] == 0:
artificialVariableNum += 1
artificialVariable[i] = 1
else:
slackVariableNum += 1
artificialVariableNum += 1
slackVariable[i] = -1
artificialVariable[i] = 1
variableNum = c.shape[0] + slackVariableNum + artificialVariableNum
addVariableNum = slackVariableNum + artificialVariableNum
baseIndex = np.empty(n)
baseValue = np.empty(n)
A_ = np.append(A , np.zeros((n,addVariableNum)),axis=1)
slackIter = c.shape[0]
artificialIter = c.shape[0] + slackVariableNum
for i in range(n):
if slackVariable[i] != 0:
A_[i,slackIter] = slackVariable[i]
if slackVariable[i] > 0:
baseIndex[i],baseValue[i] = slackIter, b[i]
slackIter += 1
if artificialVariable[i] != 0:
A_[i,artificialIter] = artificialVariable[i]
baseIndex[i],baseValue[i] = artificialIter, b[i]
artificialIter += 1
exA = np.append(baseValue.reshape(n,1),A_,axis=1)
c_ = np.array([0]*(c.shape[0] + slackVariableNum) + [-1]*(artificialVariableNum))
c_ = c_[np.vectorize(int)(baseIndex)]
w = (c_ @ exA).reshape(1,variableNum+1)
z = np.append(np.append(np.zeros(1),-c),np.array([0]*addVariableNum)).reshape(1,variableNum+1)
table = np.append(np.append(exA,w,axis=0),z,axis=0)
df = pd.DataFrame(table,
columns=['Value']+[ 'x' + str(i) for i in range(variableNum)],
index= list(np.vectorize(lambda i: 'x' + str(int(i)))(baseIndex)) + ['w','z']
)
table = optimize(df,'w')
if artificialVariableNum != 0:
table = table.iloc[:,:-artificialVariableNum]
variableNum -= artificialVariableNum
table = table.drop('w')
result = optimize(table,'z')
if not maximize:
result['Value']['z'] = -result['Value']['z']
return result
e__ == '__main__':
c = np.array([ 2,3])
A = np.array([ [1,2],
[2,1] ])
comp = np.array([-1,-1])
b = np.array([10,8])
df = linprog(c,A,comp,b,True)
print(df)
| true | true |
f72c0bf5b4bcb72b7e7dd97debcab75606cc1e94 | 4,894 | py | Python | Widgets/openGL_widgets/VectorGLContext.py | qftphys/Software-for-visualising-magnetic-layers | 7e4c5680b8e87aa677bdf4c912cbccdcb11b09a3 | [
"MIT"
] | null | null | null | Widgets/openGL_widgets/VectorGLContext.py | qftphys/Software-for-visualising-magnetic-layers | 7e4c5680b8e87aa677bdf4c912cbccdcb11b09a3 | [
"MIT"
] | null | null | null | Widgets/openGL_widgets/VectorGLContext.py | qftphys/Software-for-visualising-magnetic-layers | 7e4c5680b8e87aa677bdf4c912cbccdcb11b09a3 | [
"MIT"
] | null | null | null | from PyQt5.QtWidgets import QWidget
from Widgets.openGL_widgets.AbstractGLContext import AbstractGLContext
from ColorPolicy import ColorPolicy
from ctypes import c_void_p
from PyQt5.Qt import Qt
from PyQt5.QtCore import QPoint, QThread
from cython_modules.color_policy import multi_iteration_normalize
from pattern_types.Patterns import AbstractGLContextDecorators
import numpy as np
import OpenGL.GLU as glu
import OpenGL.GL as gl
import math as mt
from multiprocessing import Pool
from ColorPolicy import ColorPolicy
class VectorGLContext(AbstractGLContext, QWidget):
def __init__(self, data_dict):
super().__init__()
super().shareData(**data_dict)
self.prerendering_calculation()
# self.drawing_function = self.slow_arrow_draw
self.drawing_function = self.vbo_arrow_draw
def prerendering_calculation(self):
super().prerendering_calculation()
if self.normalize:
VectorGLContext.normalize_specification(self.color_vectors, vbo=True)
self.interleaved = ColorPolicy.apply_vbo_interleave_format(self.vectors_list,
self.color_vectors)
self.buffers = None
## pad the color
self.color_vectors = ColorPolicy.apply_vbo_format(self.color_vectors, k=2)
self.color_vertices = len(self.vectors_list)
self.vertices = self.color_vertices*2
self.color_buffer_len = len(self.color_vectors[0])*4
self.inter_buffer_len = len(self.interleaved[0])*4
self.__FLOAT_BYTE_SIZE__ = 8
@AbstractGLContextDecorators.recording_decorator
def slow_arrow_draw(self):
gl.glLineWidth(2*self.scale)
gl.glPointSize(3*self.scale)
for vector, color in zip(self.vectors_list,
self.color_vectors[self.i]):
if not np.any(color):
continue
self.base_arrow(vector, color)
def base_arrow(self, vector, color):
gl.glColor3f(*color)
gl.glBegin(gl.GL_LINES)
gl.glVertex3f(*vector)
gl.glVertex3f(vector[0]+color[0], vector[1]+color[1],
vector[2]+color[2])
gl.glEnd()
gl.glBegin(gl.GL_POINTS)
gl.glVertex3f(vector[0]+color[0], vector[1]+color[1],
vector[2]+color[2])
gl.glEnd()
def standard_vbo_draw(self):
gl.glEnableClientState(gl.GL_COLOR_ARRAY)
gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[1])
gl.glColorPointer(3, gl.GL_FLOAT, 0, None)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[0])
gl.glVertexPointer(3, gl.GL_FLOAT, 0, None)
gl.glDrawArrays(gl.GL_LINES, 0, int(self.vertices))
# now the points
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[1])
gl.glColorPointer(3, gl.GL_FLOAT, 3*self.__FLOAT_BYTE_SIZE__, None)
# stride is 3 bytes (3 floats) VVVCCCVVVCCC etc...
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[0])
# offset is at 3 indices, so points at 4th vector 3(vertices)*4
gl.glVertexPointer(3, gl.GL_FLOAT, 3*self.__FLOAT_BYTE_SIZE__,
c_void_p(4*3))
gl.glDrawArrays(gl.GL_POINTS, 0, int(self.color_vertices))
gl.glDisableClientState(gl.GL_COLOR_ARRAY)
gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
def vbo_arrow_draw(self):
if self.buffers is None:
self.buffers = self.create_vbo()
else:
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[0])
gl.glBufferSubData(gl.GL_ARRAY_BUFFER, 0, self.inter_buffer_len,
np.array(self.interleaved[self.i],
dtype='float32').flatten())
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[1])
gl.glBufferSubData(gl.GL_ARRAY_BUFFER, 0, self.color_buffer_len,
np.array(self.color_vectors[self.i],
dtype='float32').flatten())
self.standard_vbo_draw()
def create_vbo(self):
buffers = gl.glGenBuffers(2)
gl.glLineWidth(2*self.scale)
gl.glPointSize(3*self.scale)
# vertices buffer
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffers[0])
gl.glBufferData(gl.GL_ARRAY_BUFFER,
np.array(self.interleaved[self.i],
dtype='float32').flatten(),
gl.GL_DYNAMIC_DRAW)
# color buffer
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffers[1])
gl.glBufferData(gl.GL_ARRAY_BUFFER,
np.array(self.color_vectors[self.i],
dtype='float32').flatten(),
gl.GL_DYNAMIC_DRAW)
return buffers
| 38.84127 | 86 | 0.626481 | from PyQt5.QtWidgets import QWidget
from Widgets.openGL_widgets.AbstractGLContext import AbstractGLContext
from ColorPolicy import ColorPolicy
from ctypes import c_void_p
from PyQt5.Qt import Qt
from PyQt5.QtCore import QPoint, QThread
from cython_modules.color_policy import multi_iteration_normalize
from pattern_types.Patterns import AbstractGLContextDecorators
import numpy as np
import OpenGL.GLU as glu
import OpenGL.GL as gl
import math as mt
from multiprocessing import Pool
from ColorPolicy import ColorPolicy
class VectorGLContext(AbstractGLContext, QWidget):
def __init__(self, data_dict):
super().__init__()
super().shareData(**data_dict)
self.prerendering_calculation()
self.drawing_function = self.vbo_arrow_draw
def prerendering_calculation(self):
super().prerendering_calculation()
if self.normalize:
VectorGLContext.normalize_specification(self.color_vectors, vbo=True)
self.interleaved = ColorPolicy.apply_vbo_interleave_format(self.vectors_list,
self.color_vectors)
self.buffers = None
olor_vectors = ColorPolicy.apply_vbo_format(self.color_vectors, k=2)
self.color_vertices = len(self.vectors_list)
self.vertices = self.color_vertices*2
self.color_buffer_len = len(self.color_vectors[0])*4
self.inter_buffer_len = len(self.interleaved[0])*4
self.__FLOAT_BYTE_SIZE__ = 8
@AbstractGLContextDecorators.recording_decorator
def slow_arrow_draw(self):
gl.glLineWidth(2*self.scale)
gl.glPointSize(3*self.scale)
for vector, color in zip(self.vectors_list,
self.color_vectors[self.i]):
if not np.any(color):
continue
self.base_arrow(vector, color)
def base_arrow(self, vector, color):
gl.glColor3f(*color)
gl.glBegin(gl.GL_LINES)
gl.glVertex3f(*vector)
gl.glVertex3f(vector[0]+color[0], vector[1]+color[1],
vector[2]+color[2])
gl.glEnd()
gl.glBegin(gl.GL_POINTS)
gl.glVertex3f(vector[0]+color[0], vector[1]+color[1],
vector[2]+color[2])
gl.glEnd()
def standard_vbo_draw(self):
gl.glEnableClientState(gl.GL_COLOR_ARRAY)
gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[1])
gl.glColorPointer(3, gl.GL_FLOAT, 0, None)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[0])
gl.glVertexPointer(3, gl.GL_FLOAT, 0, None)
gl.glDrawArrays(gl.GL_LINES, 0, int(self.vertices))
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[1])
gl.glColorPointer(3, gl.GL_FLOAT, 3*self.__FLOAT_BYTE_SIZE__, None)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[0])
gl.glVertexPointer(3, gl.GL_FLOAT, 3*self.__FLOAT_BYTE_SIZE__,
c_void_p(4*3))
gl.glDrawArrays(gl.GL_POINTS, 0, int(self.color_vertices))
gl.glDisableClientState(gl.GL_COLOR_ARRAY)
gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
def vbo_arrow_draw(self):
if self.buffers is None:
self.buffers = self.create_vbo()
else:
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[0])
gl.glBufferSubData(gl.GL_ARRAY_BUFFER, 0, self.inter_buffer_len,
np.array(self.interleaved[self.i],
dtype='float32').flatten())
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.buffers[1])
gl.glBufferSubData(gl.GL_ARRAY_BUFFER, 0, self.color_buffer_len,
np.array(self.color_vectors[self.i],
dtype='float32').flatten())
self.standard_vbo_draw()
def create_vbo(self):
buffers = gl.glGenBuffers(2)
gl.glLineWidth(2*self.scale)
gl.glPointSize(3*self.scale)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffers[0])
gl.glBufferData(gl.GL_ARRAY_BUFFER,
np.array(self.interleaved[self.i],
dtype='float32').flatten(),
gl.GL_DYNAMIC_DRAW)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffers[1])
gl.glBufferData(gl.GL_ARRAY_BUFFER,
np.array(self.color_vectors[self.i],
dtype='float32').flatten(),
gl.GL_DYNAMIC_DRAW)
return buffers
| true | true |
f72c0c49d7421b18eade26ce7db864b767a81dcd | 6,768 | py | Python | tests/infra/runner.py | iLuSIAnn/test | 10d0a20dc1a646b5c1f6c7bff2960e3f5df0510e | [
"Apache-2.0"
] | null | null | null | tests/infra/runner.py | iLuSIAnn/test | 10d0a20dc1a646b5c1f6c7bff2960e3f5df0510e | [
"Apache-2.0"
] | null | null | null | tests/infra/runner.py | iLuSIAnn/test | 10d0a20dc1a646b5c1f6c7bff2960e3f5df0510e | [
"Apache-2.0"
] | null | null | null | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the Apache 2.0 License.
import getpass
import time
import http
import logging
from random import seed
import infra.network
import infra.proc
import infra.remote_client
import infra.rates
import cimetrics.upload
from loguru import logger as LOG
logging.getLogger("matplotlib").setLevel(logging.WARNING)
logging.getLogger("paramiko").setLevel(logging.WARNING)
def minimum_number_of_local_nodes(args):
"""
If we are using bft then we need to have 3 nodes. CFT will run with 1 nodes, unless it expects a backup
"""
if args.consensus == "bft":
return 3
if args.send_tx_to == "backups":
return 2
return 1
def get_command_args(args, get_command):
command_args = []
return get_command(*command_args)
def filter_nodes(primary, backups, filter_type):
if filter_type == "primary":
return [primary]
elif filter_type == "backups":
if not backups:
raise Exception("--send-tx-to backups but no backup was found")
return backups
else:
return [primary] + backups
def configure_remote_client(args, client_id, client_host, node, command_args):
if client_host == "localhost":
client_host = infra.net.expand_localhost()
remote_impl = infra.remote.LocalRemote
else:
remote_impl = infra.remote.SSHRemote
try:
remote_client = infra.remote_client.CCFRemoteClient(
"client_" + str(client_id),
client_host,
args.client,
node.host,
node.rpc_port,
args.workspace,
args.label,
args.config,
command_args,
remote_impl,
)
remote_client.setup()
return remote_client
except Exception:
LOG.exception("Failed to start client {}".format(client_host))
raise
def run(get_command, args):
if args.fixed_seed:
seed(getpass.getuser())
hosts = args.nodes
if not hosts:
hosts = ["local://localhost"] * minimum_number_of_local_nodes(args)
LOG.info("Starting nodes on {}".format(hosts))
with infra.network.network(
hosts, args.binary_dir, args.debug_nodes, args.perf_nodes, pdb=args.pdb
) as network:
network.start_and_join(args)
primary, backups = network.find_nodes()
command_args = get_command_args(args, get_command)
nodes_to_send_to = filter_nodes(primary, backups, args.send_tx_to)
clients = []
client_hosts = []
if args.one_client_per_backup:
if not backups:
raise Exception(
"--one-client-per-backup was set but no backup was found"
)
client_hosts = ["localhost"] * len(backups)
else:
if args.client_nodes:
client_hosts.extend(args.client_nodes)
if args.num_localhost_clients:
client_hosts.extend(["localhost"] * int(args.num_localhost_clients))
if not client_hosts:
client_hosts = ["localhost"]
for client_id, client_host in enumerate(client_hosts):
node = nodes_to_send_to[client_id % len(nodes_to_send_to)]
remote_client = configure_remote_client(
args, client_id, client_host, node, command_args
)
clients.append(remote_client)
if args.network_only:
for remote_client in clients:
LOG.info(f"Client can be run with: {remote_client.remote.get_cmd()}")
while True:
time.sleep(60)
else:
for remote_client in clients:
remote_client.start()
hard_stop_timeout = 90
try:
with cimetrics.upload.metrics(complete=False) as metrics:
tx_rates = infra.rates.TxRates(primary)
start_time = time.time()
while True:
stop_waiting = True
for i, remote_client in enumerate(clients):
done = remote_client.check_done()
# all the clients need to be done
LOG.info(
f"Client {i} has {'completed' if done else 'not completed'} running ({time.time() - start_time:.2f}s / {hard_stop_timeout}s)"
)
stop_waiting = stop_waiting and done
if stop_waiting:
break
if time.time() > start_time + hard_stop_timeout:
raise TimeoutError(
f"Client still running after {hard_stop_timeout}s"
)
time.sleep(5)
tx_rates.get_metrics()
for remote_client in clients:
perf_result = remote_client.get_result()
LOG.success(f"{args.label}/{remote_client.name}: {perf_result}")
# TODO: Only results for first client are uploaded
# https://github.com/microsoft/CCF/issues/1046
if remote_client == clients[0]:
LOG.success(f"Uploading results for {remote_client.name}")
metrics.put(args.label, perf_result)
else:
LOG.warning(f"Skipping upload for {remote_client.name}")
primary, _ = network.find_primary()
with primary.client() as nc:
r = nc.get("/node/memory")
assert r.status_code == http.HTTPStatus.OK.value
results = r.body.json()
tx_rates.insert_metrics(**results)
# Construct name for heap metric, removing ^ suffix if present
heap_peak_metric = f"Mem_{args.label}"
if heap_peak_metric.endswith("^"):
heap_peak_metric = heap_peak_metric[:-1]
peak_value = results["peak_allocated_heap_size"]
metrics.put(heap_peak_metric, peak_value)
LOG.info(f"Rates:\n{tx_rates}")
tx_rates.save_results(args.metrics_file)
for remote_client in clients:
remote_client.stop()
except Exception:
LOG.error("Stopping clients due to exception")
for remote_client in clients:
remote_client.stop()
raise
| 35.067358 | 157 | 0.553783 |
import getpass
import time
import http
import logging
from random import seed
import infra.network
import infra.proc
import infra.remote_client
import infra.rates
import cimetrics.upload
from loguru import logger as LOG
logging.getLogger("matplotlib").setLevel(logging.WARNING)
logging.getLogger("paramiko").setLevel(logging.WARNING)
def minimum_number_of_local_nodes(args):
if args.consensus == "bft":
return 3
if args.send_tx_to == "backups":
return 2
return 1
def get_command_args(args, get_command):
command_args = []
return get_command(*command_args)
def filter_nodes(primary, backups, filter_type):
if filter_type == "primary":
return [primary]
elif filter_type == "backups":
if not backups:
raise Exception("--send-tx-to backups but no backup was found")
return backups
else:
return [primary] + backups
def configure_remote_client(args, client_id, client_host, node, command_args):
if client_host == "localhost":
client_host = infra.net.expand_localhost()
remote_impl = infra.remote.LocalRemote
else:
remote_impl = infra.remote.SSHRemote
try:
remote_client = infra.remote_client.CCFRemoteClient(
"client_" + str(client_id),
client_host,
args.client,
node.host,
node.rpc_port,
args.workspace,
args.label,
args.config,
command_args,
remote_impl,
)
remote_client.setup()
return remote_client
except Exception:
LOG.exception("Failed to start client {}".format(client_host))
raise
def run(get_command, args):
if args.fixed_seed:
seed(getpass.getuser())
hosts = args.nodes
if not hosts:
hosts = ["local://localhost"] * minimum_number_of_local_nodes(args)
LOG.info("Starting nodes on {}".format(hosts))
with infra.network.network(
hosts, args.binary_dir, args.debug_nodes, args.perf_nodes, pdb=args.pdb
) as network:
network.start_and_join(args)
primary, backups = network.find_nodes()
command_args = get_command_args(args, get_command)
nodes_to_send_to = filter_nodes(primary, backups, args.send_tx_to)
clients = []
client_hosts = []
if args.one_client_per_backup:
if not backups:
raise Exception(
"--one-client-per-backup was set but no backup was found"
)
client_hosts = ["localhost"] * len(backups)
else:
if args.client_nodes:
client_hosts.extend(args.client_nodes)
if args.num_localhost_clients:
client_hosts.extend(["localhost"] * int(args.num_localhost_clients))
if not client_hosts:
client_hosts = ["localhost"]
for client_id, client_host in enumerate(client_hosts):
node = nodes_to_send_to[client_id % len(nodes_to_send_to)]
remote_client = configure_remote_client(
args, client_id, client_host, node, command_args
)
clients.append(remote_client)
if args.network_only:
for remote_client in clients:
LOG.info(f"Client can be run with: {remote_client.remote.get_cmd()}")
while True:
time.sleep(60)
else:
for remote_client in clients:
remote_client.start()
hard_stop_timeout = 90
try:
with cimetrics.upload.metrics(complete=False) as metrics:
tx_rates = infra.rates.TxRates(primary)
start_time = time.time()
while True:
stop_waiting = True
for i, remote_client in enumerate(clients):
done = remote_client.check_done()
LOG.info(
f"Client {i} has {'completed' if done else 'not completed'} running ({time.time() - start_time:.2f}s / {hard_stop_timeout}s)"
)
stop_waiting = stop_waiting and done
if stop_waiting:
break
if time.time() > start_time + hard_stop_timeout:
raise TimeoutError(
f"Client still running after {hard_stop_timeout}s"
)
time.sleep(5)
tx_rates.get_metrics()
for remote_client in clients:
perf_result = remote_client.get_result()
LOG.success(f"{args.label}/{remote_client.name}: {perf_result}")
if remote_client == clients[0]:
LOG.success(f"Uploading results for {remote_client.name}")
metrics.put(args.label, perf_result)
else:
LOG.warning(f"Skipping upload for {remote_client.name}")
primary, _ = network.find_primary()
with primary.client() as nc:
r = nc.get("/node/memory")
assert r.status_code == http.HTTPStatus.OK.value
results = r.body.json()
tx_rates.insert_metrics(**results)
heap_peak_metric = f"Mem_{args.label}"
if heap_peak_metric.endswith("^"):
heap_peak_metric = heap_peak_metric[:-1]
peak_value = results["peak_allocated_heap_size"]
metrics.put(heap_peak_metric, peak_value)
LOG.info(f"Rates:\n{tx_rates}")
tx_rates.save_results(args.metrics_file)
for remote_client in clients:
remote_client.stop()
except Exception:
LOG.error("Stopping clients due to exception")
for remote_client in clients:
remote_client.stop()
raise
| true | true |
f72c0cf297fb6c440eea6a74e7fd555334feff9a | 558 | py | Python | src/Product.py | AbdulMutakabbir/CCH-manufacturing-facility-simulator | ffc1b294eecf69c940b04bfc3d66ef58c7b63de6 | [
"MIT"
] | null | null | null | src/Product.py | AbdulMutakabbir/CCH-manufacturing-facility-simulator | ffc1b294eecf69c940b04bfc3d66ef58c7b63de6 | [
"MIT"
] | null | null | null | src/Product.py | AbdulMutakabbir/CCH-manufacturing-facility-simulator | ffc1b294eecf69c940b04bfc3d66ef58c7b63de6 | [
"MIT"
] | null | null | null | # holds the data and methods for products
class Product:
__type: int = None # specifies P1 or P2
# Constructor:
# Inputs:
# p_type:int -> Product Type
def __init__(self, p_type):
if (p_type is not None) and (p_type >= 0) and (p_type <= 3):
self.__type = p_type
else:
raise Exception("ProductTypeError")
# returns the product type
def get_type(self):
if self.__type is None:
raise Exception("NotInitializedProduct")
else:
return self.__type
| 26.571429 | 68 | 0.586022 |
class Product:
__type: int = None
def __init__(self, p_type):
if (p_type is not None) and (p_type >= 0) and (p_type <= 3):
self.__type = p_type
else:
raise Exception("ProductTypeError")
def get_type(self):
if self.__type is None:
raise Exception("NotInitializedProduct")
else:
return self.__type
| true | true |
f72c0d36cca4aa60ffe71a6c3374a1be477a7388 | 21,847 | py | Python | universe/rewarder/rewarder_session.py | BitJetKit/universe | cc9ce6ec241821bfb0f3b85dd455bd36e4ee7a8c | [
"MIT"
] | 8,120 | 2016-12-05T06:37:45.000Z | 2022-03-21T14:45:20.000Z | universe/rewarder/rewarder_session.py | BitJetKit/universe | cc9ce6ec241821bfb0f3b85dd455bd36e4ee7a8c | [
"MIT"
] | 213 | 2016-12-05T09:57:37.000Z | 2018-04-05T18:55:14.000Z | universe/rewarder/rewarder_session.py | BitJetKit/universe | cc9ce6ec241821bfb0f3b85dd455bd36e4ee7a8c | [
"MIT"
] | 1,140 | 2016-12-05T06:50:43.000Z | 2022-03-23T08:28:32.000Z | from autobahn.twisted import websocket
import logging
import numpy as np
import threading
import time
from twisted.python import failure
from twisted.internet import defer, endpoints
import twisted.internet.error
from universe import utils
from universe.twisty import reactor
from universe.rewarder import connection_timer, env_status, reward_buffer, rewarder_client
from universe.utils import display
logger = logging.getLogger(__name__)
extra_logger = logging.getLogger('universe.extra.'+__name__)
def _ping(client):
return client.send('v0.control.ping', {}, expect_reply=True)
class RewarderSession(object):
def __init__(self):
self.lock = threading.RLock()
self.i = 0
# Mutated by main thread exclusively
self.names_by_id = {}
self.reward_buffers = {}
self.env_statuses = {}
self.errors = {}
self.networks = {}
self.clients = {}
def close(self, name=None, reason=u'closed by RewarderSession.close'):
if name is None:
names = list(self.names_by_id.values())
else:
logger.info('[%s] Closing rewarder connection', name)
names = [name]
self.ids_by_name = {name: id for id, name in self.names_by_id.items()}
for name in names:
with self.lock:
id = self.ids_by_name.pop(name, None)
if id is None:
# already closed
continue
del self.names_by_id[id]
del self.reward_buffers[id]
del self.env_statuses[id]
self.errors.pop(id, None)
network = self.networks.pop(id)
network.close()
client = self.clients.pop(id, None)
if client is not None:
reactor.callFromThread(client.close, reason=reason)
def connect(self, name, address, label, password, env_id=None, seed=None, fps=60,
start_timeout=None, observer=False, skip_network_calibration=False):
if name in self.reward_buffers:
self.close(name, reason='closing previous connection to reconnect with the same name')
network = Network()
self.names_by_id[self.i] = name
self.reward_buffers[self.i] = reward_buffer.RewardBuffer(label)
self.env_statuses[self.i] = env_status.EnvStatus(label=label, primary=False)
self.networks[self.i] = network
reactor.callFromThread(self._connect,
name=name,
address=address,
env_id=env_id,
seed=seed,
fps=fps,
i=self.i,
network=network,
env_status=self.env_statuses[self.i],
reward_buffer=self.reward_buffers[self.i],
label=label,
start_timeout=start_timeout,
password=password,
observer=observer,
skip_network_calibration=skip_network_calibration,
)
self.i += 1
return network
def _already_closed(self, i):
# Lock must be held
return i not in self.names_by_id
# Call only from Twisted thread
# TODO: probably time to convert to kwargs
@defer.inlineCallbacks
def _connect(self, name, address, env_id, seed, fps, i, network, env_status, reward_buffer,
label, password, start_timeout,
observer, skip_network_calibration,
attempt=0, elapsed_sleep_time=0,
):
endpoint = endpoints.clientFromString(reactor, 'tcp:'+address)
factory = websocket.WebSocketClientFactory('ws://'+address)
factory.protocol = rewarder_client.RewarderClient
assert password, "Missing password: {} for rewarder session".format(password)
factory.headers = {'authorization': utils.basic_auth_encode(password), 'openai-observer': 'true' if observer else 'false'}
factory.i = i
# Various important objects
factory.endpoint = endpoint
factory.env_status = env_status
factory.reward_buffer = reward_buffer
# Helpful strings
factory.label = label
factory.address = address
# Arguments to always send to the remote reset call
factory.arg_env_id = env_id
factory.arg_fps = fps
def record_error(e):
if isinstance(e, failure.Failure):
e = e.value
# logger.error('[%s] Recording rewarder error: %s', factory.label, e)
with self.lock:
# drop error on the floor if we're already closed
if self._already_closed(factory.i):
extra_logger.info('[%s] Ignoring error for already closed connection: %s', label, e)
elif factory.i not in self.clients:
extra_logger.info('[%s] Received error for connection which has not been fully initialized: %s', label, e)
# We could handle this better, but right now we
# just mark this as a fatal error for the
# backend. Often it actually is.
self.errors[factory.i] = e
else:
extra_logger.info('[%s] Recording fatal error for connection: %s', label, e)
self.errors[factory.i] = e
def retriable_error(e, error_message):
if isinstance(e, failure.Failure):
e = e.value
if self._already_closed(factory.i):
logger.error('[%s] Got error, but giving up on reconnecting, since %d already disconnected', factory.label, factory.i)
return
# Also need to handle DNS errors, so let's just handle everything for now.
#
# reason.trap(twisted.internet.error.ConnectError, error.ConnectionError)
if elapsed_sleep_time < start_timeout:
sleep = min((2 * attempt+1), 10)
logger.error('[%s] Waiting on rewarder: %s. Retry in %ds (slept %ds/%ds): %s', factory.label, error_message, sleep, elapsed_sleep_time, start_timeout, e)
reactor.callLater(
sleep, self._connect, name=name, address=address,
env_id=env_id, seed=seed, fps=fps, i=i, network=network,
env_status=env_status, reward_buffer=reward_buffer, label=label,
attempt=attempt+1, elapsed_sleep_time=elapsed_sleep_time+sleep,
start_timeout=start_timeout, password=password,
observer=observer, skip_network_calibration=skip_network_calibration,
)
else:
logger.error('[%s] %s. Retries exceeded (slept %ds/%ds): %s', factory.label, error_message, elapsed_sleep_time, start_timeout, e)
record_error(e)
factory.record_error = record_error
try:
retry_msg = 'establish rewarder TCP connection'
client = yield endpoint.connect(factory)
extra_logger.info('[%s] Rewarder TCP connection established', factory.label)
retry_msg = 'complete WebSocket handshake'
yield client.waitForWebsocketConnection()
extra_logger.info('[%s] Websocket client successfully connected', factory.label)
if not skip_network_calibration:
retry_msg = 'run network calibration'
yield network.calibrate(client)
extra_logger.info('[%s] Network calibration complete', factory.label)
retry_msg = ''
if factory.arg_env_id is not None:
# We aren't picky about episode ID: we may have
# already receieved an env.describe message
# telling us about a resetting environment, which
# we don't need to bump post.
#
# tl;dr hardcoding 0.0 here avoids a double reset.
reply = yield self._send_env_reset(client, seed=seed, episode_id='0')
else:
# No env_id requested, so we just proceed without a reset
reply = None
# We're connected and have measured the
# network. Mark everything as ready to go.
with self.lock:
if factory.i not in self.names_by_id:
# ID has been popped!
logger.info('[%s] Rewarder %d started, but has already been closed', factory.label, factory.i)
client.close(reason='RewarderSession: double-closing, client was closed while RewarderSession was starting')
elif reply is None:
logger.info('[%s] Attached to running environment without reset', factory.label)
else:
context, req, rep = reply
logger.info('[%s] Initial reset complete: episode_id=%s', factory.label, rep['headers']['episode_id'])
self.clients[factory.i] = client
except Exception as e:
if retry_msg:
retriable_error(e, 'failed to ' + retry_msg)
else:
record_error(e)
def pop_errors(self):
errors = {}
with self.lock:
if self.errors:
for i, error in self.errors.items():
name = self.names_by_id[i]
errors[name] = error
self.errors.clear()
return errors
def reset(self, seed=None, env_id=None):
with self.lock:
for i, reward_buffer in self.reward_buffers.items():
reward_buffer.mask()
reactor.callFromThread(self._reset, seed=seed, env_id=env_id)
def _reset(self, seed=None, env_id=None):
with self.lock:
for client in self.clients.values():
d = self._send_env_reset(client, seed=seed, env_id=env_id)
# Total hack to capture the variable in the closure
def callbacks(client):
def success(reply): pass
def fail(reason): client.factory.record_error(reason)
return success, fail
success, fail = callbacks(client)
d.addCallback(success)
d.addErrback(fail)
def _send_env_reset(self, client, seed=None, episode_id=None, env_id=None):
if episode_id is None:
episode_id = client.factory.env_status.episode_id
logger.info('[%s] Sending reset for env_id=%s fps=%s episode_id=%s', client.factory.label, client.factory.arg_env_id, client.factory.arg_fps, episode_id)
return client.send_reset(
env_id=client.factory.arg_env_id if env_id is None else env_id,
seed=seed,
fps=client.factory.arg_fps,
episode_id=episode_id)
def pop(self, warn=True, peek_d=None):
reward_d = {}
done_d = {}
info_d = {}
err_d = self.pop_errors()
for i, reward_buffer in self.reward_buffers.items():
name = self.names_by_id[i]
reward, done, info = reward_buffer.pop(peek_d.get(name))
reward_d[name] = reward
done_d[name] = done
info_d[name] = info
# TODO: use FPS here rather than 60
if warn and any(info.get('stats.reward.count', 0) > 60 for info in info_d.values()):
logger.warn('WARNING: returning more than 60 aggregated rewards: %s. Either your agent is not keeping up with the framerate, or you should have called ".reset()" to clear pending rewards and reset the environments to a known state.',
{name: '{} (episode_id={})'.format(info['stats.reward.count'], info.get('env_status.episode_id')) for name, info in info_d.items()})
return reward_d, done_d, info_d, err_d
def wait(self, timeout=None):
deadline = time.time() + timeout
for client in self.clients:
if timeout is not None:
remaining_timeout = deadline - time.time()
else:
remaining_timeout = None
client.reward_buffer.wait_for_step(timeout=remaining_timeout)
# Hack to test actions over websockets
# TODO: Carve websockets out of rewarder pkg (into vnc_env? - and move this there)
def send_action(self, action_n, env_id):
reactor.callFromThread(self._send_action, env_id, action_n)
return self.pop_errors()
def _send_action(self, env_id, action_n):
with self.lock:
for n, client in zip(action_n, self.clients.values()):
self._send_env_action(client, env_id, action_n[n])
def _send_env_action(self, client, env_id, action_n):
if len(action_n) == 0:
# Hack to skip empty actions. TODO: Find source (throttle?) and fix
return
message = {
'env_id': env_id,
'action': action_n,
}
client.send('v0.agent.action', message, expect_reply=False)
def rewards_count(self):
# TODO: any reason to lock these?
return [client.reward_buffer.count for client in self.clients]
def pop_observation(self):
return [client.reward_buffer.pop_observation() for client in self.clients]
# def _connection_time(self):
# deferreds = []
# for client in self.clients:
# endpoint = client.factory.endpoint
# d = connection_timer.start(endpoint)
# deferreds.append(d)
# d = defer.DeferredList(deferreds, fireOnOneErrback=True, consumeErrors=True)
# return d
# Run this in Twisty therad
class Network(object):
def __init__(self):
self.connection_samples = 10
self.application_ping_samples = 10
self.connection_time_m = None
self.lock = threading.Lock()
self.recalibrate = None
self.client = None
self._ntpdate_reversed_clock_skew = None
self._reversed_clock_skew = None
def active(self):
with self.lock:
return self._reversed_clock_skew is not None
# Used by external consumers
def reversed_clock_skew(self):
with self.lock:
if self._ntpdate_clock_skew is not None:
return self._ntpdate_reversed_clock_skew
else:
return self._reversed_clock_skew
def _report(self):
connection_time = display.display_timestamps(self.connection_time_m)
if self._ntpdate_clock_skew is not None:
ntpdate_clock_skew = display.display_timestamp(self._ntpdate_clock_skew[0])
else:
ntpdate_clock_skew = None
clock_skew = display.display_timestamps_pair(self.clock_skew_m)
application_rtt = display.display_timestamps(self.application_rtt_m)
request_overhead = display.display_timestamps(self.request_overhead_m)
response_overhead = display.display_timestamps(self.response_overhead_m)
extra_logger.info('[%s] Network calibration: ntpdate_clock_skew=%s clock_skew=%s connection_time=%s application_rtt=%s request_overhead=%s response_overhead=%s',
self.client.factory.label, ntpdate_clock_skew, clock_skew, connection_time, application_rtt,
request_overhead, response_overhead)
def _start(self):
def calibrate():
d = defer.Deferred()
def fail(reason):
logger.error('[%s] Could not recalibrate network: %s', self.client.factory.label, reason)
d.addErrback(fail)
self._start_measure_connection_time(d)
self._start()
self.recalibrate = reactor.callLater(5 * 60, calibrate)
def close(self):
if self.recalibrate:
try:
self.recalibrate.cancel()
except twisted.internet.error.AlreadyCalled:
pass
# Called externally
def calibrate(self, client):
d = defer.Deferred()
def success(res):
# If we succeed, kick off the periodic 5 minute
# recalibrations.
self._start()
return res
d.addCallback(success)
self.client = client
# Kinda a hack. Idea is to try using the ntpdate -q offset if
# we can.
skew = self._start_measure_clock_skew()
def succeed(offset):
with self.lock:
self._ntpdate_clock_skew = np.array([offset, offset])
self._ntpdate_reversed_clock_skew = np.array([-offset, -offset])
self._start_measure_connection_time(d)
skew.addCallback(succeed)
def fail(reason):
with self.lock:
self._ntpdate_clock_skew = None
self._ntpdate_reversed_clock_skew = None
extra_logger.info('[%s] Could not determine clock skew with ntpdate; falling back to application-level ping: %s', self.client.factory.label, reason.value)
self._start_measure_connection_time(d)
skew.addErrback(fail)
return d
def _start_measure_connection_time(self, d):
connection_time_m = np.zeros(self.connection_samples)
self._measure_connection_time(d, connection_time_m, 0)
def _measure_connection_time(self, d, connection_time_m, i):
extra_logger.debug('[%s] Measuring connection time (%d/%d)', self.client.factory.label, i+1, len(connection_time_m))
endpoint = self.client.factory.endpoint
timer = connection_timer.start(endpoint)
def success(delta):
connection_time_m[i] = delta
if i+1 < len(connection_time_m):
self._measure_connection_time(d, connection_time_m, i+1)
else:
self.connection_time_m = connection_time_m
self._start_measure_application_ping(d)
def fail(reason):
d.errback(reason)
timer.addCallback(success)
timer.addErrback(fail)
def _start_measure_application_ping(self, d=None):
clock_skew_m = np.zeros((self.application_ping_samples, 2))
request_overhead_m = np.zeros((self.application_ping_samples))
response_overhead_m = np.zeros((self.application_ping_samples))
application_rtt_m = np.zeros((self.application_ping_samples))
self._measure_application_ping(d, clock_skew_m, request_overhead_m, response_overhead_m, application_rtt_m, 0)
def _measure_application_ping(self, d, clock_skew_m, request_overhead_m, response_overhead_m, application_rtt_m, i):
extra_logger.debug('[%s] Issuing an application-level ping (%d/%d)', self.client.factory.label, i+1, len(clock_skew_m))
start = time.time()
ping = _ping(self.client)
def success(res):
context, request, response = res
end = time.time()
request_sent_at = request['headers']['sent_at'] # local
response_sent_at = response['headers']['sent_at'] # remote
response_received_at = context['start'] # local
# We try to put bounds on clock skew by subtracting
# local and remote times, for local and remote events
# that are causally related.
#
# For example, suppose that the following local/remote
# logical timestamps apply to a request (for a system
# with clock skew of 100):
#
# request_sent local: 0 remote: 100
# request_recieved local: 1 remote: 101
# response_sent local: 2 remote: 102
# response_received local: 3 remote: 103
#
# Then:
#
# # Remote event *after* local is upper bound
# request_recieved.remote - request_sent.local = 101
# # Remote event *before* local is lower bound
# response_sent.remote - response_received.local = 102 - 3 = 99
#
# There's danger of further clock drift over time, but
# we don't need these to be fully accurate, and this
# should be fine for now.
clock_skew_m[i, :] = (response_sent_at-response_received_at, response_sent_at-request_sent_at)
request_overhead_m[i] = request_sent_at - start
response_overhead_m[i] = end - response_received_at
application_rtt_m[i] = response_received_at - request_sent_at
if i+1 < len(clock_skew_m):
self._measure_application_ping(d, clock_skew_m, request_overhead_m, response_overhead_m, application_rtt_m, i+1)
else:
self.clock_skew_m = clock_skew_m
self.request_overhead_m = request_overhead_m
self.response_overhead_m = response_overhead_m
self.application_rtt_m = application_rtt_m
self._report()
self._update_exposed_metrics()
# Ok, all done!
if d is not None:
d.callback(self)
ping.addCallback(success)
ping.addErrback(d.errback)
def _update_exposed_metrics(self):
with self.lock:
self._clock_skew = self.clock_skew_m.mean(axis=0) # add to local time to get remote time, as (min, max) values
self._reversed_clock_skew = -self._clock_skew[[1, 0]] # add to remote time to get local time, in format (min, max)
def _start_measure_clock_skew(self):
host = self.client.factory.address.split(':')[0]
return connection_timer.measure_clock_skew(self.client.factory.label, host)
| 42.339147 | 245 | 0.602875 | from autobahn.twisted import websocket
import logging
import numpy as np
import threading
import time
from twisted.python import failure
from twisted.internet import defer, endpoints
import twisted.internet.error
from universe import utils
from universe.twisty import reactor
from universe.rewarder import connection_timer, env_status, reward_buffer, rewarder_client
from universe.utils import display
logger = logging.getLogger(__name__)
extra_logger = logging.getLogger('universe.extra.'+__name__)
def _ping(client):
return client.send('v0.control.ping', {}, expect_reply=True)
class RewarderSession(object):
def __init__(self):
self.lock = threading.RLock()
self.i = 0
self.names_by_id = {}
self.reward_buffers = {}
self.env_statuses = {}
self.errors = {}
self.networks = {}
self.clients = {}
def close(self, name=None, reason=u'closed by RewarderSession.close'):
if name is None:
names = list(self.names_by_id.values())
else:
logger.info('[%s] Closing rewarder connection', name)
names = [name]
self.ids_by_name = {name: id for id, name in self.names_by_id.items()}
for name in names:
with self.lock:
id = self.ids_by_name.pop(name, None)
if id is None:
continue
del self.names_by_id[id]
del self.reward_buffers[id]
del self.env_statuses[id]
self.errors.pop(id, None)
network = self.networks.pop(id)
network.close()
client = self.clients.pop(id, None)
if client is not None:
reactor.callFromThread(client.close, reason=reason)
def connect(self, name, address, label, password, env_id=None, seed=None, fps=60,
start_timeout=None, observer=False, skip_network_calibration=False):
if name in self.reward_buffers:
self.close(name, reason='closing previous connection to reconnect with the same name')
network = Network()
self.names_by_id[self.i] = name
self.reward_buffers[self.i] = reward_buffer.RewardBuffer(label)
self.env_statuses[self.i] = env_status.EnvStatus(label=label, primary=False)
self.networks[self.i] = network
reactor.callFromThread(self._connect,
name=name,
address=address,
env_id=env_id,
seed=seed,
fps=fps,
i=self.i,
network=network,
env_status=self.env_statuses[self.i],
reward_buffer=self.reward_buffers[self.i],
label=label,
start_timeout=start_timeout,
password=password,
observer=observer,
skip_network_calibration=skip_network_calibration,
)
self.i += 1
return network
def _already_closed(self, i):
return i not in self.names_by_id
@defer.inlineCallbacks
def _connect(self, name, address, env_id, seed, fps, i, network, env_status, reward_buffer,
label, password, start_timeout,
observer, skip_network_calibration,
attempt=0, elapsed_sleep_time=0,
):
endpoint = endpoints.clientFromString(reactor, 'tcp:'+address)
factory = websocket.WebSocketClientFactory('ws://'+address)
factory.protocol = rewarder_client.RewarderClient
assert password, "Missing password: {} for rewarder session".format(password)
factory.headers = {'authorization': utils.basic_auth_encode(password), 'openai-observer': 'true' if observer else 'false'}
factory.i = i
factory.endpoint = endpoint
factory.env_status = env_status
factory.reward_buffer = reward_buffer
factory.label = label
factory.address = address
factory.arg_env_id = env_id
factory.arg_fps = fps
def record_error(e):
if isinstance(e, failure.Failure):
e = e.value
with self.lock:
if self._already_closed(factory.i):
extra_logger.info('[%s] Ignoring error for already closed connection: %s', label, e)
elif factory.i not in self.clients:
extra_logger.info('[%s] Received error for connection which has not been fully initialized: %s', label, e)
# We could handle this better, but right now we
# just mark this as a fatal error for the
# backend. Often it actually is.
self.errors[factory.i] = e
else:
extra_logger.info('[%s] Recording fatal error for connection: %s', label, e)
self.errors[factory.i] = e
def retriable_error(e, error_message):
if isinstance(e, failure.Failure):
e = e.value
if self._already_closed(factory.i):
logger.error('[%s] Got error, but giving up on reconnecting, since %d already disconnected', factory.label, factory.i)
return
# Also need to handle DNS errors, so let's just handle everything for now.
if elapsed_sleep_time < start_timeout:
sleep = min((2 * attempt+1), 10)
logger.error('[%s] Waiting on rewarder: %s. Retry in %ds (slept %ds/%ds): %s', factory.label, error_message, sleep, elapsed_sleep_time, start_timeout, e)
reactor.callLater(
sleep, self._connect, name=name, address=address,
env_id=env_id, seed=seed, fps=fps, i=i, network=network,
env_status=env_status, reward_buffer=reward_buffer, label=label,
attempt=attempt+1, elapsed_sleep_time=elapsed_sleep_time+sleep,
start_timeout=start_timeout, password=password,
observer=observer, skip_network_calibration=skip_network_calibration,
)
else:
logger.error('[%s] %s. Retries exceeded (slept %ds/%ds): %s', factory.label, error_message, elapsed_sleep_time, start_timeout, e)
record_error(e)
factory.record_error = record_error
try:
retry_msg = 'establish rewarder TCP connection'
client = yield endpoint.connect(factory)
extra_logger.info('[%s] Rewarder TCP connection established', factory.label)
retry_msg = 'complete WebSocket handshake'
yield client.waitForWebsocketConnection()
extra_logger.info('[%s] Websocket client successfully connected', factory.label)
if not skip_network_calibration:
retry_msg = 'run network calibration'
yield network.calibrate(client)
extra_logger.info('[%s] Network calibration complete', factory.label)
retry_msg = ''
if factory.arg_env_id is not None:
# already receieved an env.describe message
# telling us about a resetting environment, which
# we don't need to bump post.
reply = yield self._send_env_reset(client, seed=seed, episode_id='0')
else:
reply = None
# network. Mark everything as ready to go.
with self.lock:
if factory.i not in self.names_by_id:
# ID has been popped!
logger.info('[%s] Rewarder %d started, but has already been closed', factory.label, factory.i)
client.close(reason='RewarderSession: double-closing, client was closed while RewarderSession was starting')
elif reply is None:
logger.info('[%s] Attached to running environment without reset', factory.label)
else:
context, req, rep = reply
logger.info('[%s] Initial reset complete: episode_id=%s', factory.label, rep['headers']['episode_id'])
self.clients[factory.i] = client
except Exception as e:
if retry_msg:
retriable_error(e, 'failed to ' + retry_msg)
else:
record_error(e)
def pop_errors(self):
errors = {}
with self.lock:
if self.errors:
for i, error in self.errors.items():
name = self.names_by_id[i]
errors[name] = error
self.errors.clear()
return errors
def reset(self, seed=None, env_id=None):
with self.lock:
for i, reward_buffer in self.reward_buffers.items():
reward_buffer.mask()
reactor.callFromThread(self._reset, seed=seed, env_id=env_id)
def _reset(self, seed=None, env_id=None):
with self.lock:
for client in self.clients.values():
d = self._send_env_reset(client, seed=seed, env_id=env_id)
# Total hack to capture the variable in the closure
def callbacks(client):
def success(reply): pass
def fail(reason): client.factory.record_error(reason)
return success, fail
success, fail = callbacks(client)
d.addCallback(success)
d.addErrback(fail)
def _send_env_reset(self, client, seed=None, episode_id=None, env_id=None):
if episode_id is None:
episode_id = client.factory.env_status.episode_id
logger.info('[%s] Sending reset for env_id=%s fps=%s episode_id=%s', client.factory.label, client.factory.arg_env_id, client.factory.arg_fps, episode_id)
return client.send_reset(
env_id=client.factory.arg_env_id if env_id is None else env_id,
seed=seed,
fps=client.factory.arg_fps,
episode_id=episode_id)
def pop(self, warn=True, peek_d=None):
reward_d = {}
done_d = {}
info_d = {}
err_d = self.pop_errors()
for i, reward_buffer in self.reward_buffers.items():
name = self.names_by_id[i]
reward, done, info = reward_buffer.pop(peek_d.get(name))
reward_d[name] = reward
done_d[name] = done
info_d[name] = info
# TODO: use FPS here rather than 60
if warn and any(info.get('stats.reward.count', 0) > 60 for info in info_d.values()):
logger.warn('WARNING: returning more than 60 aggregated rewards: %s. Either your agent is not keeping up with the framerate, or you should have called ".reset()" to clear pending rewards and reset the environments to a known state.',
{name: '{} (episode_id={})'.format(info['stats.reward.count'], info.get('env_status.episode_id')) for name, info in info_d.items()})
return reward_d, done_d, info_d, err_d
def wait(self, timeout=None):
deadline = time.time() + timeout
for client in self.clients:
if timeout is not None:
remaining_timeout = deadline - time.time()
else:
remaining_timeout = None
client.reward_buffer.wait_for_step(timeout=remaining_timeout)
# Hack to test actions over websockets
# TODO: Carve websockets out of rewarder pkg (into vnc_env? - and move this there)
def send_action(self, action_n, env_id):
reactor.callFromThread(self._send_action, env_id, action_n)
return self.pop_errors()
def _send_action(self, env_id, action_n):
with self.lock:
for n, client in zip(action_n, self.clients.values()):
self._send_env_action(client, env_id, action_n[n])
def _send_env_action(self, client, env_id, action_n):
if len(action_n) == 0:
# Hack to skip empty actions. TODO: Find source (throttle?) and fix
return
message = {
'env_id': env_id,
'action': action_n,
}
client.send('v0.agent.action', message, expect_reply=False)
def rewards_count(self):
# TODO: any reason to lock these?
return [client.reward_buffer.count for client in self.clients]
def pop_observation(self):
return [client.reward_buffer.pop_observation() for client in self.clients]
# def _connection_time(self):
# deferreds = []
# for client in self.clients:
# endpoint = client.factory.endpoint
# d = connection_timer.start(endpoint)
# deferreds.append(d)
# d = defer.DeferredList(deferreds, fireOnOneErrback=True, consumeErrors=True)
# return d
# Run this in Twisty therad
class Network(object):
def __init__(self):
self.connection_samples = 10
self.application_ping_samples = 10
self.connection_time_m = None
self.lock = threading.Lock()
self.recalibrate = None
self.client = None
self._ntpdate_reversed_clock_skew = None
self._reversed_clock_skew = None
def active(self):
with self.lock:
return self._reversed_clock_skew is not None
# Used by external consumers
def reversed_clock_skew(self):
with self.lock:
if self._ntpdate_clock_skew is not None:
return self._ntpdate_reversed_clock_skew
else:
return self._reversed_clock_skew
def _report(self):
connection_time = display.display_timestamps(self.connection_time_m)
if self._ntpdate_clock_skew is not None:
ntpdate_clock_skew = display.display_timestamp(self._ntpdate_clock_skew[0])
else:
ntpdate_clock_skew = None
clock_skew = display.display_timestamps_pair(self.clock_skew_m)
application_rtt = display.display_timestamps(self.application_rtt_m)
request_overhead = display.display_timestamps(self.request_overhead_m)
response_overhead = display.display_timestamps(self.response_overhead_m)
extra_logger.info('[%s] Network calibration: ntpdate_clock_skew=%s clock_skew=%s connection_time=%s application_rtt=%s request_overhead=%s response_overhead=%s',
self.client.factory.label, ntpdate_clock_skew, clock_skew, connection_time, application_rtt,
request_overhead, response_overhead)
def _start(self):
def calibrate():
d = defer.Deferred()
def fail(reason):
logger.error('[%s] Could not recalibrate network: %s', self.client.factory.label, reason)
d.addErrback(fail)
self._start_measure_connection_time(d)
self._start()
self.recalibrate = reactor.callLater(5 * 60, calibrate)
def close(self):
if self.recalibrate:
try:
self.recalibrate.cancel()
except twisted.internet.error.AlreadyCalled:
pass
# Called externally
def calibrate(self, client):
d = defer.Deferred()
def success(res):
# If we succeed, kick off the periodic 5 minute
# recalibrations.
self._start()
return res
d.addCallback(success)
self.client = client
# Kinda a hack. Idea is to try using the ntpdate -q offset if
# we can.
skew = self._start_measure_clock_skew()
def succeed(offset):
with self.lock:
self._ntpdate_clock_skew = np.array([offset, offset])
self._ntpdate_reversed_clock_skew = np.array([-offset, -offset])
self._start_measure_connection_time(d)
skew.addCallback(succeed)
def fail(reason):
with self.lock:
self._ntpdate_clock_skew = None
self._ntpdate_reversed_clock_skew = None
extra_logger.info('[%s] Could not determine clock skew with ntpdate; falling back to application-level ping: %s', self.client.factory.label, reason.value)
self._start_measure_connection_time(d)
skew.addErrback(fail)
return d
def _start_measure_connection_time(self, d):
connection_time_m = np.zeros(self.connection_samples)
self._measure_connection_time(d, connection_time_m, 0)
def _measure_connection_time(self, d, connection_time_m, i):
extra_logger.debug('[%s] Measuring connection time (%d/%d)', self.client.factory.label, i+1, len(connection_time_m))
endpoint = self.client.factory.endpoint
timer = connection_timer.start(endpoint)
def success(delta):
connection_time_m[i] = delta
if i+1 < len(connection_time_m):
self._measure_connection_time(d, connection_time_m, i+1)
else:
self.connection_time_m = connection_time_m
self._start_measure_application_ping(d)
def fail(reason):
d.errback(reason)
timer.addCallback(success)
timer.addErrback(fail)
def _start_measure_application_ping(self, d=None):
clock_skew_m = np.zeros((self.application_ping_samples, 2))
request_overhead_m = np.zeros((self.application_ping_samples))
response_overhead_m = np.zeros((self.application_ping_samples))
application_rtt_m = np.zeros((self.application_ping_samples))
self._measure_application_ping(d, clock_skew_m, request_overhead_m, response_overhead_m, application_rtt_m, 0)
def _measure_application_ping(self, d, clock_skew_m, request_overhead_m, response_overhead_m, application_rtt_m, i):
extra_logger.debug('[%s] Issuing an application-level ping (%d/%d)', self.client.factory.label, i+1, len(clock_skew_m))
start = time.time()
ping = _ping(self.client)
def success(res):
context, request, response = res
end = time.time()
request_sent_at = request['headers']['sent_at'] # local
response_sent_at = response['headers']['sent_at'] # remote
response_received_at = context['start'] # local
# We try to put bounds on clock skew by subtracting
# local and remote times, for local and remote events
# that are causally related.
#
# For example, suppose that the following local/remote
# logical timestamps apply to a request (for a system
# with clock skew of 100):
#
# request_sent local: 0 remote: 100
# request_recieved local: 1 remote: 101
# response_sent local: 2 remote: 102
# response_received local: 3 remote: 103
#
# Then:
#
# # Remote event *after* local is upper bound
# request_recieved.remote - request_sent.local = 101
# # Remote event *before* local is lower bound
# response_sent.remote - response_received.local = 102 - 3 = 99
#
# There's danger of further clock drift over time, but
# should be fine for now.
clock_skew_m[i, :] = (response_sent_at-response_received_at, response_sent_at-request_sent_at)
request_overhead_m[i] = request_sent_at - start
response_overhead_m[i] = end - response_received_at
application_rtt_m[i] = response_received_at - request_sent_at
if i+1 < len(clock_skew_m):
self._measure_application_ping(d, clock_skew_m, request_overhead_m, response_overhead_m, application_rtt_m, i+1)
else:
self.clock_skew_m = clock_skew_m
self.request_overhead_m = request_overhead_m
self.response_overhead_m = response_overhead_m
self.application_rtt_m = application_rtt_m
self._report()
self._update_exposed_metrics()
# Ok, all done!
if d is not None:
d.callback(self)
ping.addCallback(success)
ping.addErrback(d.errback)
def _update_exposed_metrics(self):
with self.lock:
self._clock_skew = self.clock_skew_m.mean(axis=0) # add to local time to get remote time, as (min, max) values
self._reversed_clock_skew = -self._clock_skew[[1, 0]] # add to remote time to get local time, in format (min, max)
def _start_measure_clock_skew(self):
host = self.client.factory.address.split(':')[0]
return connection_timer.measure_clock_skew(self.client.factory.label, host)
| true | true |
f72c0d7a15cd90ef41611423f1b1643e68712a61 | 2,372 | py | Python | discord/enums.py | alexyy802/GlowCord | af92f1a11843157aa5484c1781417456175a8ab3 | [
"MIT"
] | null | null | null | discord/enums.py | alexyy802/GlowCord | af92f1a11843157aa5484c1781417456175a8ab3 | [
"MIT"
] | null | null | null | discord/enums.py | alexyy802/GlowCord | af92f1a11843157aa5484c1781417456175a8ab3 | [
"MIT"
] | null | null | null | """
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Copyright (c) 2021-present tag-epic
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.
--------------
Aliased moodule. See the same file in the glowcord folder for more information
Autogenerated by aliasgen.py
"""
from glowcord.enums import ActivityType, Any, AuditLogAction, AuditLogActionCategory, ButtonStyle, ChannelType, ClassVar, ComponentType, ContentFilter, DefaultAvatar, Dict, Enum, EnumMeta, ExpireBehavior, ExpireBehaviour, InteractionResponseType, InteractionType, InviteTarget, List, MessageType, NSFWLevel, NotificationLevel, Optional, SpeakingState, StagePrivacyLevel, Status, StickerFormatType, StickerType, T, TYPE_CHECKING, TeamMembershipState, Type, TypeVar, UserFlags, VerificationLevel, VideoQualityMode, VoiceRegion, WebhookType, _create_value_cls, _is_descriptor, create_unknown_value, namedtuple, try_enum, types
__all__ = ("Enum", "ChannelType", "MessageType", "VoiceRegion", "SpeakingState", "VerificationLevel", "ContentFilter", "Status", "DefaultAvatar", "AuditLogAction", "AuditLogActionCategory", "UserFlags", "ActivityType", "NotificationLevel", "TeamMembershipState", "WebhookType", "ExpireBehaviour", "ExpireBehavior", "StickerType", "StickerFormatType", "InviteTarget", "VideoQualityMode", "ComponentType", "ButtonStyle", "StagePrivacyLevel", "InteractionType", "InteractionResponseType", "NSFWLevel") | 76.516129 | 623 | 0.802277 |
from glowcord.enums import ActivityType, Any, AuditLogAction, AuditLogActionCategory, ButtonStyle, ChannelType, ClassVar, ComponentType, ContentFilter, DefaultAvatar, Dict, Enum, EnumMeta, ExpireBehavior, ExpireBehaviour, InteractionResponseType, InteractionType, InviteTarget, List, MessageType, NSFWLevel, NotificationLevel, Optional, SpeakingState, StagePrivacyLevel, Status, StickerFormatType, StickerType, T, TYPE_CHECKING, TeamMembershipState, Type, TypeVar, UserFlags, VerificationLevel, VideoQualityMode, VoiceRegion, WebhookType, _create_value_cls, _is_descriptor, create_unknown_value, namedtuple, try_enum, types
__all__ = ("Enum", "ChannelType", "MessageType", "VoiceRegion", "SpeakingState", "VerificationLevel", "ContentFilter", "Status", "DefaultAvatar", "AuditLogAction", "AuditLogActionCategory", "UserFlags", "ActivityType", "NotificationLevel", "TeamMembershipState", "WebhookType", "ExpireBehaviour", "ExpireBehavior", "StickerType", "StickerFormatType", "InviteTarget", "VideoQualityMode", "ComponentType", "ButtonStyle", "StagePrivacyLevel", "InteractionType", "InteractionResponseType", "NSFWLevel") | true | true |
f72c0e67908a76e0ea66de8a4f836e96cdcb736d | 2,393 | py | Python | plugins/hw_wallet/plugin.py | futuro-coin/electrum-futuro | 04910904a6d4d330f202daf0c1975b8296ad8e5d | [
"MIT"
] | 4 | 2019-01-16T14:30:39.000Z | 2021-10-21T04:21:45.000Z | plugins/hw_wallet/plugin.py | futuro-coin/electrum-futuro | 04910904a6d4d330f202daf0c1975b8296ad8e5d | [
"MIT"
] | 1 | 2021-11-15T17:47:31.000Z | 2021-11-15T17:47:31.000Z | plugins/hw_wallet/plugin.py | futuro-coin/electrum-futuro | 04910904a6d4d330f202daf0c1975b8296ad8e5d | [
"MIT"
] | 2 | 2018-12-18T17:32:46.000Z | 2019-01-16T14:30:42.000Z | #!/usr/bin/env python2
# -*- mode: python -*-
#
# Electrum - lightweight Futurocoin client
# Copyright (C) 2016 The Electrum developers
#
# 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 electrum.plugins import BasePlugin, hook
from electrum.i18n import _
class HW_PluginBase(BasePlugin):
# Derived classes provide:
#
# class-static variables: client_class, firmware_URL, handler_class,
# libraries_available, libraries_URL, minimum_firmware,
# wallet_class, ckd_public, types, HidTransport
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
self.device = self.keystore_class.device
self.keystore_class.plugin = self
def is_enabled(self):
return True
def device_manager(self):
return self.parent.device_manager
@hook
def close_wallet(self, wallet):
for keystore in wallet.get_keystores():
if isinstance(keystore, self.keystore_class):
self.device_manager().unpair_xpub(keystore.xpub)
def setup_device(self, device_info, wizard, purpose):
"""Called when creating a new wallet or when using the device to decrypt
an existing wallet. Select the device to use. If the device is
uninitialized, go through the initialization process.
"""
raise NotImplementedError()
| 39.229508 | 80 | 0.72921 |
from electrum.plugins import BasePlugin, hook
from electrum.i18n import _
class HW_PluginBase(BasePlugin):
def __init__(self, parent, config, name):
BasePlugin.__init__(self, parent, config, name)
self.device = self.keystore_class.device
self.keystore_class.plugin = self
def is_enabled(self):
return True
def device_manager(self):
return self.parent.device_manager
@hook
def close_wallet(self, wallet):
for keystore in wallet.get_keystores():
if isinstance(keystore, self.keystore_class):
self.device_manager().unpair_xpub(keystore.xpub)
def setup_device(self, device_info, wizard, purpose):
raise NotImplementedError()
| true | true |
f72c0ea16de779f16beca6532d9f0bc2298b0a63 | 214 | py | Python | embiggen/sequences/generic_sequences/__init__.py | monarch-initiative/N2V | 8ae02ca125f1d24ca158c2849f2d9bb1711920b9 | [
"BSD-3-Clause"
] | 2 | 2020-01-30T11:57:37.000Z | 2020-05-02T00:05:49.000Z | embiggen/sequences/generic_sequences/__init__.py | monarch-initiative/N2V | 8ae02ca125f1d24ca158c2849f2d9bb1711920b9 | [
"BSD-3-Clause"
] | 93 | 2020-01-26T00:43:51.000Z | 2020-05-10T03:29:54.000Z | embiggen/sequences/generic_sequences/__init__.py | monarch-initiative/N2V | 8ae02ca125f1d24ca158c2849f2d9bb1711920b9 | [
"BSD-3-Clause"
] | 5 | 2020-02-13T07:18:11.000Z | 2020-03-19T08:03:34.000Z | """Module providing generic sequences that are used throught Embiggen."""
from embiggen.sequences.generic_sequences.edge_prediction_sequence import EdgePredictionSequence
__all__ = [
"EdgePredictionSequence"
] | 35.666667 | 96 | 0.827103 | from embiggen.sequences.generic_sequences.edge_prediction_sequence import EdgePredictionSequence
__all__ = [
"EdgePredictionSequence"
] | true | true |
f72c0f9f033cd93ca71e3dcc3956bdced61ba742 | 11,944 | py | Python | nngp/nngp.py | chrhenning/uncertainty_based_ood | 13c0b9910966544527497497f6ff0441d5334591 | [
"Apache-2.0"
] | null | null | null | nngp/nngp.py | chrhenning/uncertainty_based_ood | 13c0b9910966544527497497f6ff0441d5334591 | [
"Apache-2.0"
] | null | null | null | nngp/nngp.py | chrhenning/uncertainty_based_ood | 13c0b9910966544527497497f6ff0441d5334591 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
# Copyright 2021 Christian Henning
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @title :nngp/nngp.py
# @author :ch
# @contact :henningc@ethz.ch
# @created :04/19/2021
# @version :1.0
# @python_version :3.8.5
r"""
Deep Neural Network as Gaussian Process
---------------------------------------
The module :mod:`nngp.nngp` implements helper functions for Bayesian inference
with Gaussian Processes with a focus on kernels derived from neural network
architectures when taken to the infinite-width limit
(cf. :mod:`nngp.mlp_kernel`).
Specifically, we consider a Gaussian Process
:math:`\mathcal{GP}\big(\mu(x), k(x, x')\big)` with mean function
:math:`\mu(\cdot)` and kernel :math:`k(\cdot, \cdot)`. Unless specified
otherwise, we assume the mean function to be :math:`\mu(x) = 0`. Note, that any
multivariate Gaussian prescribed by the :math:`\mathcal{GP}` at a given set of
input locations is consistent (marginalization from any superset of locations
will always lead to the same distribution) and adheres exchangibility (order of
input locations doesn't affect the distribution except for repositioning the
corresponding function values).
For any given set of inputs :math:`X = x_1, \dots, x_n`, the
:math:`\mathcal{GP}` allows us to specify a prior distribution over function
values :math:`p(f_1, \dots, f_n; x_1, \dots, x_n) \equiv p(F; X)`.
In addition to inputs :math:`x` and function values :math:`f`, we consider
observations :math:`y`, which are obtained via a likelihood function
:math:`p(y \mid f)`.
Using the prior distribution over functions (the :math:`\mathcal{GP}`) and a
dataset :math:`\mathcal{D} = \{(x_n, y_n)\}_{n=1}^N` with inputs :math:`X` and
targets :math:`Y`, one can form a posterior distribution over function values
:math:`f` at an unknown location :math:`x^*` via
.. math::
p(f \mid \mathcal{D}; x^*) = p(f \mid Y; x^* X) = \frac{1}{p(Y; X)} \
\int p(Y \mid F) p(F, f; X, x^*) \, dF
Please see
`Rasmussen and Williams <http://www.gaussianprocess.org/gpml/chapters/RW.pdf>`__
for a broader introduction into Gaussian Processes.
"""
import torch
from warnings import warn
def inference_with_isotropic_gaussian_ll(Y, K_train, K_test, K_all, var=1e-10,
L_mat=None, return_cov=False):
r"""Bayesian inference with Gaussian likelihood and :math:`\mathcal{GP}`
prior.
Here, we consider the case
:math:`p(Y \mid F) = \mathcal{N}(Y; F, \sigma_\epsilon^2 I)`, where the
posterior predictive :math:`p(f \mid \mathcal{D}; x^*)` can be analytically
computed
.. math::
p(f \mid \mathcal{D}; x^*) &= \mathcal{N}(f; \mu^*, \Sigma^*) \\ \
\mu^* &= K(x^*, X) \big( K(X, X) + \sigma_\epsilon^2 I \big)^{-1} Y \\ \
\Sigma^* &= k(x^*, x^*) - K(x^*, X) \big( K(X, X) + \
\sigma_\epsilon^2 I \big)^{-1} K(X, x^*)
Args:
Y (torch.Tensor): The labels :math:`Y` from the training set encoded as
vector of shape ``[m]`` or ``[m, 1]``.
K_train (torch.Tensor): The training data kernel matrix :math:`K(X, X)`.
K_test (torch.Tensor): The test data kernel values :math:`k(x^*, x^*)`.
This is a vector either of shape ``[n]``, where ``n`` is the number
test points, or of shape ``[n, 1]``.
K_all (torch.Tensor): The kernel values between train and test points
:math:`K(x^*, X)`. This is expected to be matrix of shape ``[n,m]``,
where ``m`` is the number of training and ``n`` the number of test
points, or simply a vector of shape ``[m]``, if there is only one
test point.
var (float): The variance :math:`\sigma_\epsilon^2` of the likelihood.
L_mat (torch.Tensor, optional): The matrix :math:`L` resulting from a
Cholesky decomposition of :math:`K(X, X) + \sigma_\epsilon^2 I`.
If provided, the arguments ``K_train`` and ``var`` are ignored.
The function :func:`cholesky_adaptive_noise` may be helpful to
compute ``L_mat``.
return_cov (bool): If ``True``, the return value ``cov`` will be the
full covariance matrix. However, this option requires ``K_test``
to be the full ``[n, n]`` kernel matrix.
Returns:
(tuple): Tuple containing:
- **mean** (torch.Tensor): A tensor of shape ``[n]``, where ``n`` is the
number of test points. The tensor encodes the mean for each test point
of the posterior predictive :math:`\mu^*`.
- **cov** (torch.Tensor): Same as ``mean`` but encoding the variance
:math:`\Sigma^*` of each test point, i.e., the diagonal of the full
covariance matrix.
"""
m = K_train.shape[0] if L_mat is None else L_mat.shape[0]
n = K_test.shape[0]
assert Y.numel() == m
assert K_all.numel() == m*n
if Y.ndim == 1:
Y = Y.view(-1, 1)
if return_cov:
assert K_test.numel() == n*n and K_test.ndim == 2
elif K_test.ndim == 2:
K_test = K_test.view(-1)
if K_all.ndim == 1:
assert n == 1
K_all = K_all.view(n, m)
#inv_K = torch.linalg.inv(K_train + var * torch.eye(m).to(K_train.device))
#mu = torch.matmul(K_all, torch.matmul(inv_K, Y))
#if return_cov:
# sigma = K_test - torch.matmul(K_all, torch.matmul(inv_K, K_all.T))
#else:
# #sigma = K_test - torch.bmm(K_all.view(n, 1, m), torch.matmul(inv_K,
# # K_all.view(n, m, 1))).squeeze()
# sigma = K_test - (K_all * torch.matmul(inv_K,
# K_all.view(n, m, 1)).squeeze(dim=2)).sum(dim=1)
# Note, direct matrix inversion is considered extremely numerically
# unstable. Therefore, Rasmussen et al. propose the use of Cholesky
# decomposition, see Appendix A.4 in
# http://www.gaussianprocess.org/gpml/chapters/RW.pdf
if L_mat is None:
L = torch.linalg.cholesky(K_train + \
var * torch.eye(m).to(K_train.device))
else:
L = L_mat
alpha = torch.triangular_solve(torch.triangular_solve(Y, L, upper=False)[0],
L, upper=False, transpose=True)[0]
mu = torch.matmul(K_all, alpha)
v = torch.triangular_solve(K_all.T, L, upper=False)[0]
if return_cov:
sigma = K_test - torch.matmul(v.T, v)
else:
sigma = K_test - (v * v).sum(dim=0)
if torch.any(sigma < 0):
sigma[sigma < 0] = 1e-5
warn('Some entries of the covariance matrix are negative and set to ' +
'1e-5!')
return mu.squeeze(), sigma
def gen_inference_kernels(X_train, X_test, kernel_func, compute_K_train=True,
full_K_test=False):
r"""Generate the kernel matrices required for inference.
This function generates the kernel matrices / vectors :math:`K(X, X)`,
:math:`K(x^*, X)` and :math:`K(x^*, x^*)`, where :math:`X` are training
inputs and :math:`x^*` are unseen points.
Thus, the function can be seen as helper function for functions like
:func:`inference_with_isotropic_gaussian_ll`.
Args:
X_train (torch.Tensor): A batch of ``m`` training inputs. The tensor
should have shape ``[m, d_in]``, where ``d_in`` is the input
dimensionality. For scalar inputs, one may also pass a tensor of
shape ``[m]``.
X_test (torch.Tensor):A batch of ``n`` unseen test inputs.
kernel_func (func): The kernel function :math:`k(x, x')`. It is expected
to have an interface for a single input ``X`` as described in
the docstring of function:`nngp.mlp_kernel.init_kernel`.
.. code-block:: python
def kernel_func(X):
# Compute kernel values.
return K
compute_K_train (bool): Whether the kernel matrix :math:`K(X, X)`
should be computed. If ``False``, the return value ``K_train`` is
``None``.
full_K_test (bool): Whether the full kernel matrix :math:`K(x^*, x^*)`
of shape ``[n, n]`` should be computed.
Returns:
(tuple): Tuple containing:
- **K_train** (torch.Tensor or None): :math:`K(X, X)`, a tensor of
shape ``[m, m]``.
- **K_test** (torch.Tensor): :math:`K(x^*, x^*)`, a tensor of shape
``[n]``
- **K_all** (torch.Tensor): :math:`K(x^*, X)`, a tensor of shape
``[n,m]``
"""
if compute_K_train:
K_train = kernel_func(X_train)
else:
K_train = None
if full_K_test:
K_test = kernel_func(X_test)
else:
K_test = kernel_func((X_test, X_test))
# Contruct tuples between all train samples and all test samples.
if X_train.ndim == 1: # `d_in == 1`
X_train = X_train.view(-1, 1)
if X_test.ndim == 1:
X_test = X_test.view(-1, 1)
m = X_train.shape[0]
n = X_test.shape[0]
X_all = (X_train.repeat(n, 1),
X_test.view(n, 1, -1).repeat(1, m, 1).view(n*m, -1))
K_all = kernel_func(X_all)
K_all = K_all.view(n, m)
return K_train, K_test, K_all
def cholesky_adaptive_noise(K_train, var=1e-10, var_step=2.):
r"""Cholesky decomposition of a kernel matrix with noise perturbation.
This function computes the Cholesky decomposition of:
.. math::
L L^T = K(X, X) + \sigma_\epsilon^2 I
As kernel matrices :math:`K(X, X)` may easily be (numerically) singular,
tuning the noise :math:`\sigma_\epsilon^2` is crucial. Therefore, this
method will iteratively increase the noise level until the matrix becomes
non-singular.
Args:
(....): See docstring of method :meth:`kernel_efficient`.
var (float or list): The initial variance :math:`\sigma_\epsilon^2`.
If a list of values is provided, then each value in this list is
consecutively tested until a non-singular matrix is constructed.
Note, we assume that the list is sorted from small to large. If none
of the elements in this list will lead to a non-singular matrix, an
exception is raised.
var_step (float): If ``var`` is a single value, then the value specified
here will be iteratively multiplied to increase the variance
:math:`\sigma_\epsilon^2` (therefore ``var_step > 1`` is required).
Returns:
(tuple): Tuple containing:
- **L** (torch.Tensor): The matrix :math:`L` resulting from the
successful Cholesky decomposition.
- **var_chosen** (float): The variance :math:`\sigma_\epsilon^2` that
was chosen to obtain ``L``.
"""
m = K_train.shape[0]
if not isinstance(var, (list, tuple)):
assert var_step > 1.
i = 0
while True:
if isinstance(var, (list, tuple)):
if i >= len(var):
raise RuntimeError('List of variances didn\'t contain high ' +
'enough values.')
curr_var = var[i]
else:
if i == 0:
curr_var = var
else:
curr_var *= var_step
try:
L = torch.linalg.cholesky(K_train + curr_var * torch.eye(m).to( \
K_train.device))
except:
i += 1
continue
return L, curr_var
if __name__ == '__main__':
pass
| 39.681063 | 80 | 0.602646 |
import torch
from warnings import warn
def inference_with_isotropic_gaussian_ll(Y, K_train, K_test, K_all, var=1e-10,
L_mat=None, return_cov=False):
m = K_train.shape[0] if L_mat is None else L_mat.shape[0]
n = K_test.shape[0]
assert Y.numel() == m
assert K_all.numel() == m*n
if Y.ndim == 1:
Y = Y.view(-1, 1)
if return_cov:
assert K_test.numel() == n*n and K_test.ndim == 2
elif K_test.ndim == 2:
K_test = K_test.view(-1)
if K_all.ndim == 1:
assert n == 1
K_all = K_all.view(n, m)
var * torch.eye(m).to(K_train.device))
else:
L = L_mat
alpha = torch.triangular_solve(torch.triangular_solve(Y, L, upper=False)[0],
L, upper=False, transpose=True)[0]
mu = torch.matmul(K_all, alpha)
v = torch.triangular_solve(K_all.T, L, upper=False)[0]
if return_cov:
sigma = K_test - torch.matmul(v.T, v)
else:
sigma = K_test - (v * v).sum(dim=0)
if torch.any(sigma < 0):
sigma[sigma < 0] = 1e-5
warn('Some entries of the covariance matrix are negative and set to ' +
'1e-5!')
return mu.squeeze(), sigma
def gen_inference_kernels(X_train, X_test, kernel_func, compute_K_train=True,
full_K_test=False):
if compute_K_train:
K_train = kernel_func(X_train)
else:
K_train = None
if full_K_test:
K_test = kernel_func(X_test)
else:
K_test = kernel_func((X_test, X_test))
if X_train.ndim == 1:
X_train = X_train.view(-1, 1)
if X_test.ndim == 1:
X_test = X_test.view(-1, 1)
m = X_train.shape[0]
n = X_test.shape[0]
X_all = (X_train.repeat(n, 1),
X_test.view(n, 1, -1).repeat(1, m, 1).view(n*m, -1))
K_all = kernel_func(X_all)
K_all = K_all.view(n, m)
return K_train, K_test, K_all
def cholesky_adaptive_noise(K_train, var=1e-10, var_step=2.):
m = K_train.shape[0]
if not isinstance(var, (list, tuple)):
assert var_step > 1.
i = 0
while True:
if isinstance(var, (list, tuple)):
if i >= len(var):
raise RuntimeError('List of variances didn\'t contain high ' +
'enough values.')
curr_var = var[i]
else:
if i == 0:
curr_var = var
else:
curr_var *= var_step
try:
L = torch.linalg.cholesky(K_train + curr_var * torch.eye(m).to( \
K_train.device))
except:
i += 1
continue
return L, curr_var
if __name__ == '__main__':
pass
| true | true |
f72c0fcbfb5b7caec767f2ca3b4965a9ad74ab72 | 814 | py | Python | python/173.binary-search-tree-iterator.py | fengbaoheng/leetcode | 2b6ec9adea383503acc23622ca5623161f7ca520 | [
"MIT"
] | 1 | 2019-04-11T12:34:55.000Z | 2019-04-11T12:34:55.000Z | python/173.binary-search-tree-iterator.py | fengbaoheng/leetcode | 2b6ec9adea383503acc23622ca5623161f7ca520 | [
"MIT"
] | null | null | null | python/173.binary-search-tree-iterator.py | fengbaoheng/leetcode | 2b6ec9adea383503acc23622ca5623161f7ca520 | [
"MIT"
] | null | null | null | #
# @lc app=leetcode.cn id=173 lang=python3
#
# [173] 二叉搜索树迭代器
#
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = []
if root is not None:
self.stack.append(root)
# 并不需要一次全部遍历完
# 每次只找到最小的即可
def next(self) -> int:
node = self.stack.pop()
# 没有左子树的节点,即为当前最小的节点
while node.left is not None:
left_node = node.left
node.left = None
self.stack.append(node)
node = left_node
# 缓存该节点的右子树
if node.right is not None:
self.stack.append(node.right)
return node.val
def hasNext(self) -> bool:
return len(self.stack) != 0
| 19.380952 | 41 | 0.545455 |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class BSTIterator:
def __init__(self, root: TreeNode):
self.stack = []
if root is not None:
self.stack.append(root)
def next(self) -> int:
node = self.stack.pop()
while node.left is not None:
left_node = node.left
node.left = None
self.stack.append(node)
node = left_node
if node.right is not None:
self.stack.append(node.right)
return node.val
def hasNext(self) -> bool:
return len(self.stack) != 0
| true | true |
f72c101791b5714dbca430af69817d1077ddde46 | 307 | py | Python | platform/radio/efr32_multiphy_configurator/pyradioconfig/parts/nixi/targets/Target_IC.py | PascalGuenther/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 82 | 2016-06-29T17:24:43.000Z | 2021-04-16T06:49:17.000Z | platform/radio/efr32_multiphy_configurator/pyradioconfig/parts/nixi/targets/Target_IC.py | PascalGuenther/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 6 | 2022-01-12T18:22:08.000Z | 2022-03-25T10:19:27.000Z | platform/radio/efr32_multiphy_configurator/pyradioconfig/parts/nixi/targets/Target_IC.py | PascalGuenther/gecko_sdk | 2e82050dc8823c9fe0e8908c1b2666fb83056230 | [
"Zlib"
] | 56 | 2016-08-02T10:50:50.000Z | 2021-07-19T08:57:34.000Z | from pyradioconfig.calculator_model_framework.interfaces.itarget import ITarget
class Target_IC_Nixi(ITarget):
_targetName = ITarget.IC_str
_description = ""
_store_config_output = True
_cfg_location = "nixi"
_tag = ITarget.IC_str
def target_calculate(self, model):
pass
| 21.928571 | 79 | 0.732899 | from pyradioconfig.calculator_model_framework.interfaces.itarget import ITarget
class Target_IC_Nixi(ITarget):
_targetName = ITarget.IC_str
_description = ""
_store_config_output = True
_cfg_location = "nixi"
_tag = ITarget.IC_str
def target_calculate(self, model):
pass
| true | true |
f72c107476fbdd546cdfa11afec00d68c3ac2c51 | 6,189 | py | Python | test/tools/test_tools_jobs.py | Gizmokid2005/sopel | 249a05ab7c6ccb3fb0388e3194514b19897e6990 | [
"EFL-2.0"
] | 555 | 2015-07-25T21:21:43.000Z | 2022-03-28T02:22:38.000Z | test/tools/test_tools_jobs.py | Gizmokid2005/sopel | 249a05ab7c6ccb3fb0388e3194514b19897e6990 | [
"EFL-2.0"
] | 1,177 | 2015-07-31T09:52:31.000Z | 2022-03-26T05:10:34.000Z | test/tools/test_tools_jobs.py | MirahezeBots/sopel | 72aa4fa5bc0bda3cd309ae9c15e86088b29de903 | [
"EFL-2.0"
] | 406 | 2015-07-28T20:34:02.000Z | 2022-03-18T00:37:01.000Z | """Tests for Job Scheduler"""
from __future__ import generator_stop
import time
import pytest
from sopel import loader, plugin
from sopel.tools import jobs
TMP_CONFIG = """
[core]
owner = Bar
nick = Sopel
enable = coretasks
"""
class WithJobMockException(Exception):
pass
@pytest.fixture
def mockconfig(configfactory):
return configfactory('config.cfg', TMP_CONFIG)
def test_jobscheduler_stop(mockconfig, botfactory):
mockbot = botfactory(mockconfig)
scheduler = jobs.Scheduler(mockbot)
assert not scheduler.stopping.is_set(), 'Stopping must not be set at init'
scheduler.stop()
assert scheduler.stopping.is_set(), 'Stopping must have been set'
def test_job_is_ready_to_run():
now = time.time()
job = jobs.Job([5])
assert job.is_ready_to_run(now + 20)
assert not job.is_ready_to_run(now - 20)
def test_job_str():
job = jobs.Job([5])
expected = '<Job (unknown) [5s]>'
assert str(job) == expected
def test_job_str_intervals():
job = jobs.Job([5, 60, 30])
expected = '<Job (unknown) [5s, 30s, 60s]>'
assert str(job) == expected
def test_job_str_handler():
def handler():
pass
job = jobs.Job([5], handler=handler)
expected = '<Job handler [5s]>'
assert str(job) == expected
def test_job_str_handler_plugin():
def handler():
pass
job = jobs.Job([5], plugin='testplugin', handler=handler)
expected = '<Job testplugin.handler [5s]>'
assert str(job) == expected
def test_job_str_label():
def handler():
pass
job = jobs.Job([5], label='testhandler', handler=handler)
expected = '<Job testhandler [5s]>'
assert str(job) == expected
def test_job_str_label_plugin():
def handler():
pass
job = jobs.Job(
[5],
label='testhandler',
plugin='testplugin',
handler=handler,
)
expected = '<Job testplugin.testhandler [5s]>'
assert str(job) == expected
def test_job_str_label_plugin_intervals():
def handler():
pass
job = jobs.Job(
[5, 3600, 60],
label='testhandler',
plugin='testplugin',
handler=handler,
)
expected = '<Job testplugin.testhandler [5s, 60s, 3600s]>'
assert str(job) == expected
def test_job_next():
timestamp = 523549800
job = jobs.Job([5])
job.next_times[5] = timestamp
job.next(timestamp)
assert job.next_times == {
5: timestamp,
}
# assert idempotency
job.next(timestamp)
assert job.next_times == {
5: timestamp,
}
# now the "current time" is in the future compared to the last time
# so the next time should be last time + interval
job.next(timestamp + 1)
assert job.next_times == {
5: timestamp + 5,
}
# let's reset this
job.next_times[5] = timestamp
# now the "current time" is bigger than last time + interval
# so the next time will be the "current time"
job.next(timestamp + 6)
assert job.next_times == {
5: timestamp + 6,
}
def test_job_next_many():
timestamp = 523549800
job = jobs.Job([5, 30])
job.next_times[5] = timestamp + 5
job.next_times[30] = timestamp + 30
# let's move 6s in the future, so past the 5s and before the 30s
job.next(timestamp + 6)
# the 5s interval => from timestamp + to timestamp + 2 * 5
# the 30s interval => untouched, still in the future
assert job.next_times == {
5: timestamp + 10,
30: timestamp + 30,
}
# assert idempotency
job.next(timestamp + 6)
assert job.next_times == {
5: timestamp + 10,
30: timestamp + 30,
}
# let's reset
job.next_times[5] = timestamp + 5
job.next_times[30] = timestamp + 30
# now, the next time is bigger than last + 5s,
# but still lower than last + 30s
job.next(timestamp + 15)
assert job.next_times == {
5: timestamp + 15,
30: timestamp + 30,
}
# let's reset again
job.next_times[5] = timestamp + 5
job.next_times[30] = timestamp + 30
# and now, this time is bigger than both 5s and 30s
job.next(timestamp + 35)
assert job.next_times == {
5: timestamp + 35, # catching up
30: timestamp + 60, # next iteration as intended
}
def test_job_from_callable(mockconfig):
@plugin.interval(5)
@plugin.label('testjob')
def handler(manager):
"""The job's docstring."""
return 'tested'
loader.clean_callable(handler, mockconfig)
handler.plugin_name = 'testplugin'
job = jobs.Job.from_callable(mockconfig, handler)
assert len(job.next_times.items()) == 1
assert 5 in job.next_times
assert job.is_threaded()
assert job.intervals == set([5])
assert job.execute(None) == 'tested'
assert job.get_job_label() == 'testjob'
assert job.get_plugin_name() == 'testplugin'
assert job.get_doc() == "The job's docstring."
assert str(job) == '<Job testplugin.testjob [5s]>'
def test_job_with():
job = jobs.Job([5])
# play with time: move 1s back in the future
last_time = job.next_times[5] = time.time() - 1
assert last_time is not None
with job:
assert job.is_running.is_set()
assert job.next_times[5] == last_time
# now the job is not running anymore, and its next time is last_time + 5s
assert not job.is_running.is_set()
assert job.next_times[5] == last_time + 5
def test_job_with_exception():
job = jobs.Job([5])
# play with time: move 1s back in the future
last_time = job.next_times[5] = time.time() - 1
assert last_time is not None
with pytest.raises(WithJobMockException):
# the "with job" must not prevent the exception from being raised up
with job:
assert job.is_running.is_set()
assert job.next_times[5] == last_time
# fake an exception while the job is running
raise WithJobMockException
# now the job is not running anymore, and its next time is last_time + 5s
# even though an exception was raised!
assert not job.is_running.is_set()
assert job.next_times[5] == last_time + 5
| 23.895753 | 78 | 0.63112 | from __future__ import generator_stop
import time
import pytest
from sopel import loader, plugin
from sopel.tools import jobs
TMP_CONFIG = """
[core]
owner = Bar
nick = Sopel
enable = coretasks
"""
class WithJobMockException(Exception):
pass
@pytest.fixture
def mockconfig(configfactory):
return configfactory('config.cfg', TMP_CONFIG)
def test_jobscheduler_stop(mockconfig, botfactory):
mockbot = botfactory(mockconfig)
scheduler = jobs.Scheduler(mockbot)
assert not scheduler.stopping.is_set(), 'Stopping must not be set at init'
scheduler.stop()
assert scheduler.stopping.is_set(), 'Stopping must have been set'
def test_job_is_ready_to_run():
now = time.time()
job = jobs.Job([5])
assert job.is_ready_to_run(now + 20)
assert not job.is_ready_to_run(now - 20)
def test_job_str():
job = jobs.Job([5])
expected = '<Job (unknown) [5s]>'
assert str(job) == expected
def test_job_str_intervals():
job = jobs.Job([5, 60, 30])
expected = '<Job (unknown) [5s, 30s, 60s]>'
assert str(job) == expected
def test_job_str_handler():
def handler():
pass
job = jobs.Job([5], handler=handler)
expected = '<Job handler [5s]>'
assert str(job) == expected
def test_job_str_handler_plugin():
def handler():
pass
job = jobs.Job([5], plugin='testplugin', handler=handler)
expected = '<Job testplugin.handler [5s]>'
assert str(job) == expected
def test_job_str_label():
def handler():
pass
job = jobs.Job([5], label='testhandler', handler=handler)
expected = '<Job testhandler [5s]>'
assert str(job) == expected
def test_job_str_label_plugin():
def handler():
pass
job = jobs.Job(
[5],
label='testhandler',
plugin='testplugin',
handler=handler,
)
expected = '<Job testplugin.testhandler [5s]>'
assert str(job) == expected
def test_job_str_label_plugin_intervals():
def handler():
pass
job = jobs.Job(
[5, 3600, 60],
label='testhandler',
plugin='testplugin',
handler=handler,
)
expected = '<Job testplugin.testhandler [5s, 60s, 3600s]>'
assert str(job) == expected
def test_job_next():
timestamp = 523549800
job = jobs.Job([5])
job.next_times[5] = timestamp
job.next(timestamp)
assert job.next_times == {
5: timestamp,
}
job.next(timestamp)
assert job.next_times == {
5: timestamp,
}
job.next(timestamp + 1)
assert job.next_times == {
5: timestamp + 5,
}
job.next_times[5] = timestamp
# now the "current time" is bigger than last time + interval
# so the next time will be the "current time"
job.next(timestamp + 6)
assert job.next_times == {
5: timestamp + 6,
}
def test_job_next_many():
timestamp = 523549800
job = jobs.Job([5, 30])
job.next_times[5] = timestamp + 5
job.next_times[30] = timestamp + 30
# let's move 6s in the future, so past the 5s and before the 30s
job.next(timestamp + 6)
assert job.next_times == {
5: timestamp + 10,
30: timestamp + 30,
}
job.next(timestamp + 6)
assert job.next_times == {
5: timestamp + 10,
30: timestamp + 30,
}
job.next_times[5] = timestamp + 5
job.next_times[30] = timestamp + 30
# now, the next time is bigger than last + 5s,
# but still lower than last + 30s
job.next(timestamp + 15)
assert job.next_times == {
5: timestamp + 15,
30: timestamp + 30,
}
# let's reset again
job.next_times[5] = timestamp + 5
job.next_times[30] = timestamp + 30
job.next(timestamp + 35)
assert job.next_times == {
5: timestamp + 35,
30: timestamp + 60,
}
def test_job_from_callable(mockconfig):
@plugin.interval(5)
@plugin.label('testjob')
def handler(manager):
return 'tested'
loader.clean_callable(handler, mockconfig)
handler.plugin_name = 'testplugin'
job = jobs.Job.from_callable(mockconfig, handler)
assert len(job.next_times.items()) == 1
assert 5 in job.next_times
assert job.is_threaded()
assert job.intervals == set([5])
assert job.execute(None) == 'tested'
assert job.get_job_label() == 'testjob'
assert job.get_plugin_name() == 'testplugin'
assert job.get_doc() == "The job's docstring."
assert str(job) == '<Job testplugin.testjob [5s]>'
def test_job_with():
job = jobs.Job([5])
# play with time: move 1s back in the future
last_time = job.next_times[5] = time.time() - 1
assert last_time is not None
with job:
assert job.is_running.is_set()
assert job.next_times[5] == last_time
# now the job is not running anymore, and its next time is last_time + 5s
assert not job.is_running.is_set()
assert job.next_times[5] == last_time + 5
def test_job_with_exception():
job = jobs.Job([5])
# play with time: move 1s back in the future
last_time = job.next_times[5] = time.time() - 1
assert last_time is not None
with pytest.raises(WithJobMockException):
# the "with job" must not prevent the exception from being raised up
with job:
assert job.is_running.is_set()
assert job.next_times[5] == last_time
# fake an exception while the job is running
raise WithJobMockException
# now the job is not running anymore, and its next time is last_time + 5s
# even though an exception was raised!
assert not job.is_running.is_set()
assert job.next_times[5] == last_time + 5
| true | true |
f72c10ad899fc5c2be354213a6c67529edd4ffb0 | 4,949 | py | Python | arco.py | TunkShif/Arco | ae782e77f82b7fd685ede587e659f96a69ec3a87 | [
"MIT"
] | null | null | null | arco.py | TunkShif/Arco | ae782e77f82b7fd685ede587e659f96a69ec3a87 | [
"MIT"
] | null | null | null | arco.py | TunkShif/Arco | ae782e77f82b7fd685ede587e659f96a69ec3a87 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""Arco CLI
Usage:
arco (new | n) -t <title> -g <category> -f <filename>
arco (generate | g)
arco (deploy | d)
arco -h | --help
arco -v | --version
Subcommands:
new Create a new blank page
generate Generate pages
deploy Deployment for github
Options:
-h, --help Help information
-v, --version Show version
-g <tag> Specify the tag
-t <title> Specify the new page title
-f <filename> Specify the new page filename
"""
import os
import json
import markdown
from docopt import docopt
class Utils(object):
def mkdir(self, path):
"Create a folder"
os.mkdir(path)
print(f'INFO: Folder {path} created!')
def read_file(self, file):
"Return the content of a text file"
with open(file, 'r') as f:
return f.read()
def write_file(self, file, content):
"Write text to a file"
path = os.path.split(file)[0] # split file path
if path is not '': # if the folder do not exist, then create it
is_direction = os.path.isdir(path)
if not is_direction:
self.mkdir(path)
with open(file, 'wt') as f:
f.write(content)
print(f"INFO: File {file} modified!")
def gen_html(self, src):
"Return html generated from markdown"
exts = ['markdown.extensions.extra', 'markdown.extensions.codehilite',
'markdown.extensions.tables', 'markdown.extensions.toc',
'markdown.extensions.footnotes']
html = markdown.markdown(src, extensions=exts)
return html
class Arco(object):
def __init__(self, utils):
self.utils = utils
self.config = self.load_config()
def load_config(self):
"Load 'config.json' then return a dict"
raw = self.utils.read_file('config.json')
data = json.loads(raw)
print('INFO: Config loaded!')
return data
def new_page(self, title, tag, file):
"Generate a new markdown page"
text = f"TITLE: {title}\nTAG: {tag}\n"
self.utils.write_file(f'markdown/{file}', text)
def load_md(self, file):
"Return the title and tag of a markdown file"
with open(file, 'r') as f:
lines = f.readlines() # split title and tag
title = lines[0].split("TITLE: ")[1].strip()
tag = lines[1].split("TAG: ")[1].strip()
content = ''.join(lines[2:])
return title, tag, content
def gen_tag_list(self):
"Return a tag list with markdown file and each one's title"
tags = {}
for md in os.listdir('markdown'):
title, tag, _ = self.load_md(f'markdown/{md}')
if tag not in tags.keys():
tags[tag] = []
item = []
item.append(md)
item.append(title)
tags[tag].append(item)
return tags
def gen_page(self):
"Generate html from each markdown file"
root = self.config['root']
year = self.config['year']
author = self.config['author']
url = self.config['url']
if 'blog' not in os.listdir():
self.utils.mkdir('blog')
for md in os.listdir('markdown'):
title, tag, raw_content = self.load_md(f'markdown/{md}')
file_name = md.split('.')[0]
content = self.utils.gen_html(raw_content)
html = utils.read_file('template/page.html')
html = html.format(title, root, root, content, url, year, author)
self.utils.write_file(f'blog/{tag}/{file_name}.html', html)
print(f'INFO: File {file_name}.html generated!')
def gen_index(self):
html = self.utils.read_file('template/index.html')
title = self.config['title']
root = self.config['root']
year = self.config['year']
author = self.config['author']
tags = self.gen_tag_list()
group = []
for tag, pages in tags.items():
group.append('## '+tag)
for page in pages:
link = r"%s%s/%s.html" % (root, tag, page[0].split('.')[0])
item = r"- [%s](%s)" % (page[1], link)
group.append(item)
raw_links = '\n'.join(group)
content = self.utils.gen_html(raw_links)
html = html.format(title, root, title, content, year, author)
self.utils.write_file('blog/index.html', html)
print('INFO: File index.html generated!')
if __name__ == "__main__":
args = docopt(__doc__, version='Arco b0.2')
utils = Utils()
arco = Arco(utils)
if args['new'] or args['n']:
arco.new_page(args['-t'], args['-g'], args['-f'])
if args['generate'] or args['g']:
arco.gen_page()
arco.gen_index()
os.system('cp -r ./template/static/ ./blog/')
| 33.666667 | 78 | 0.555668 |
import os
import json
import markdown
from docopt import docopt
class Utils(object):
def mkdir(self, path):
os.mkdir(path)
print(f'INFO: Folder {path} created!')
def read_file(self, file):
with open(file, 'r') as f:
return f.read()
def write_file(self, file, content):
path = os.path.split(file)[0]
if path is not '':
is_direction = os.path.isdir(path)
if not is_direction:
self.mkdir(path)
with open(file, 'wt') as f:
f.write(content)
print(f"INFO: File {file} modified!")
def gen_html(self, src):
exts = ['markdown.extensions.extra', 'markdown.extensions.codehilite',
'markdown.extensions.tables', 'markdown.extensions.toc',
'markdown.extensions.footnotes']
html = markdown.markdown(src, extensions=exts)
return html
class Arco(object):
def __init__(self, utils):
self.utils = utils
self.config = self.load_config()
def load_config(self):
raw = self.utils.read_file('config.json')
data = json.loads(raw)
print('INFO: Config loaded!')
return data
def new_page(self, title, tag, file):
text = f"TITLE: {title}\nTAG: {tag}\n"
self.utils.write_file(f'markdown/{file}', text)
def load_md(self, file):
with open(file, 'r') as f:
lines = f.readlines()
title = lines[0].split("TITLE: ")[1].strip()
tag = lines[1].split("TAG: ")[1].strip()
content = ''.join(lines[2:])
return title, tag, content
def gen_tag_list(self):
tags = {}
for md in os.listdir('markdown'):
title, tag, _ = self.load_md(f'markdown/{md}')
if tag not in tags.keys():
tags[tag] = []
item = []
item.append(md)
item.append(title)
tags[tag].append(item)
return tags
def gen_page(self):
root = self.config['root']
year = self.config['year']
author = self.config['author']
url = self.config['url']
if 'blog' not in os.listdir():
self.utils.mkdir('blog')
for md in os.listdir('markdown'):
title, tag, raw_content = self.load_md(f'markdown/{md}')
file_name = md.split('.')[0]
content = self.utils.gen_html(raw_content)
html = utils.read_file('template/page.html')
html = html.format(title, root, root, content, url, year, author)
self.utils.write_file(f'blog/{tag}/{file_name}.html', html)
print(f'INFO: File {file_name}.html generated!')
def gen_index(self):
html = self.utils.read_file('template/index.html')
title = self.config['title']
root = self.config['root']
year = self.config['year']
author = self.config['author']
tags = self.gen_tag_list()
group = []
for tag, pages in tags.items():
group.append('## '+tag)
for page in pages:
link = r"%s%s/%s.html" % (root, tag, page[0].split('.')[0])
item = r"- [%s](%s)" % (page[1], link)
group.append(item)
raw_links = '\n'.join(group)
content = self.utils.gen_html(raw_links)
html = html.format(title, root, title, content, year, author)
self.utils.write_file('blog/index.html', html)
print('INFO: File index.html generated!')
if __name__ == "__main__":
args = docopt(__doc__, version='Arco b0.2')
utils = Utils()
arco = Arco(utils)
if args['new'] or args['n']:
arco.new_page(args['-t'], args['-g'], args['-f'])
if args['generate'] or args['g']:
arco.gen_page()
arco.gen_index()
os.system('cp -r ./template/static/ ./blog/')
| true | true |
f72c11ddf5cf9792898f16eb88c27c05d0a7fa22 | 121 | py | Python | modules/utility/exit_failure.py | naskya/testcase-generator | 02765184a275152e1d8c177f2028ca8db315cfee | [
"MIT"
] | 4 | 2020-09-23T07:11:41.000Z | 2022-02-02T09:08:21.000Z | modules/utility/exit_failure.py | naskya/testcase-generator | 02765184a275152e1d8c177f2028ca8db315cfee | [
"MIT"
] | 5 | 2021-08-29T18:23:01.000Z | 2021-11-20T03:53:19.000Z | modules/utility/exit_failure.py | naskya/testcase-generator | 02765184a275152e1d8c177f2028ca8db315cfee | [
"MIT"
] | null | null | null | import sys
import typing
import colorama
def exit_failure() -> typing.NoReturn:
colorama.deinit()
sys.exit(1)
| 12.1 | 38 | 0.710744 | import sys
import typing
import colorama
def exit_failure() -> typing.NoReturn:
colorama.deinit()
sys.exit(1)
| true | true |
f72c12cb5d888c460ea2425493c4ccae0a17c163 | 2,097 | py | Python | third_party/catapult/dashboard/dashboard/pinpoint/models/quest/run_telemetry_test.py | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/catapult/dashboard/dashboard/pinpoint/models/quest/run_telemetry_test.py | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/catapult/dashboard/dashboard/pinpoint/models/quest/run_telemetry_test.py | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | # Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Quest for running a Telemetry benchmark in Swarming."""
import copy
from dashboard.pinpoint.models.quest import run_test
_DEFAULT_EXTRA_ARGS = [
'-v', '--upload-results', '--output-format', 'histograms']
class RunTelemetryTest(run_test.RunTest):
def Start(self, change, isolate_server, isolate_hash):
# For results2 to differentiate between runs, we need to add the
# Telemetry parameter `--results-label <change>` to the runs.
extra_args = copy.copy(self._extra_args)
extra_args += ('--results-label', str(change))
return self._Start(change, isolate_server, isolate_hash, extra_args)
@classmethod
def FromDict(cls, arguments):
swarming_extra_args = []
benchmark = arguments.get('benchmark')
if not benchmark:
raise TypeError('Missing "benchmark" argument.')
if arguments.get('target') == 'performance_test_suite':
swarming_extra_args += ('--benchmarks', benchmark)
else:
# TODO: Remove this hack when all builders build performance_test_suite.
swarming_extra_args.append(benchmark)
story = arguments.get('story')
if story:
swarming_extra_args += ('--story-filter', story)
# TODO: Workaround for crbug.com/677843.
if (benchmark.startswith('startup.warm') or
benchmark.startswith('start_with_url.warm')):
swarming_extra_args += ('--pageset-repeat', '2')
else:
swarming_extra_args += ('--pageset-repeat', '1')
browser = arguments.get('browser')
if not browser:
raise TypeError('Missing "browser" argument.')
swarming_extra_args += ('--browser', browser)
if browser == 'android-webview':
# TODO: Share code with the perf waterfall configs. crbug.com/771680
swarming_extra_args += ('--webview-embedder-apk',
'../../out/Release/apks/SystemWebViewShell.apk')
return cls._FromDict(arguments, swarming_extra_args + _DEFAULT_EXTRA_ARGS)
| 34.377049 | 78 | 0.69051 |
import copy
from dashboard.pinpoint.models.quest import run_test
_DEFAULT_EXTRA_ARGS = [
'-v', '--upload-results', '--output-format', 'histograms']
class RunTelemetryTest(run_test.RunTest):
def Start(self, change, isolate_server, isolate_hash):
extra_args = copy.copy(self._extra_args)
extra_args += ('--results-label', str(change))
return self._Start(change, isolate_server, isolate_hash, extra_args)
@classmethod
def FromDict(cls, arguments):
swarming_extra_args = []
benchmark = arguments.get('benchmark')
if not benchmark:
raise TypeError('Missing "benchmark" argument.')
if arguments.get('target') == 'performance_test_suite':
swarming_extra_args += ('--benchmarks', benchmark)
else:
swarming_extra_args.append(benchmark)
story = arguments.get('story')
if story:
swarming_extra_args += ('--story-filter', story)
if (benchmark.startswith('startup.warm') or
benchmark.startswith('start_with_url.warm')):
swarming_extra_args += ('--pageset-repeat', '2')
else:
swarming_extra_args += ('--pageset-repeat', '1')
browser = arguments.get('browser')
if not browser:
raise TypeError('Missing "browser" argument.')
swarming_extra_args += ('--browser', browser)
if browser == 'android-webview':
swarming_extra_args += ('--webview-embedder-apk',
'../../out/Release/apks/SystemWebViewShell.apk')
return cls._FromDict(arguments, swarming_extra_args + _DEFAULT_EXTRA_ARGS)
| true | true |
f72c12d312063efabbecedfddb86898a11b4cc57 | 750 | py | Python | sdk/python/pulumi_aws_native/networkmanager/__init__.py | pulumi/pulumi-aws-native | 1ae4a4d9c2256b2a79ca536f8d8497b28d10e4c3 | [
"Apache-2.0"
] | 29 | 2021-09-30T19:32:07.000Z | 2022-03-22T21:06:08.000Z | sdk/python/pulumi_aws_native/networkmanager/__init__.py | pulumi/pulumi-aws-native | 1ae4a4d9c2256b2a79ca536f8d8497b28d10e4c3 | [
"Apache-2.0"
] | 232 | 2021-09-30T19:26:26.000Z | 2022-03-31T23:22:06.000Z | sdk/python/pulumi_aws_native/networkmanager/__init__.py | pulumi/pulumi-aws-native | 1ae4a4d9c2256b2a79ca536f8d8497b28d10e4c3 | [
"Apache-2.0"
] | 4 | 2021-11-10T19:42:01.000Z | 2022-02-05T10:15:49.000Z | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from .customer_gateway_association import *
from .device import *
from .get_customer_gateway_association import *
from .get_device import *
from .get_global_network import *
from .get_link import *
from .get_link_association import *
from .get_site import *
from .get_transit_gateway_registration import *
from .global_network import *
from .link import *
from .link_association import *
from .site import *
from .transit_gateway_registration import *
from ._inputs import *
from . import outputs
| 31.25 | 80 | 0.777333 |
from .. import _utilities
import typing
# Export this package's modules as members:
from .customer_gateway_association import *
from .device import *
from .get_customer_gateway_association import *
from .get_device import *
from .get_global_network import *
from .get_link import *
from .get_link_association import *
from .get_site import *
from .get_transit_gateway_registration import *
from .global_network import *
from .link import *
from .link_association import *
from .site import *
from .transit_gateway_registration import *
from ._inputs import *
from . import outputs
| true | true |
f72c136f7e297c4a25e30f41fa955aa92ac206dd | 28,541 | py | Python | python/ray/autoscaler/_private/command_runner.py | chinganc/ray | f91c4555270cbcb86adc6c41a9074e2f69721aad | [
"Apache-2.0"
] | null | null | null | python/ray/autoscaler/_private/command_runner.py | chinganc/ray | f91c4555270cbcb86adc6c41a9074e2f69721aad | [
"Apache-2.0"
] | null | null | null | python/ray/autoscaler/_private/command_runner.py | chinganc/ray | f91c4555270cbcb86adc6c41a9074e2f69721aad | [
"Apache-2.0"
] | null | null | null | from getpass import getuser
from shlex import quote
from typing import Dict
import click
import hashlib
import json
import logging
import os
import subprocess
import sys
import time
import warnings
from ray.autoscaler.command_runner import CommandRunnerInterface
from ray.autoscaler._private.docker import check_bind_mounts_cmd, \
check_docker_running_cmd, \
check_docker_image, \
docker_start_cmds, \
DOCKER_MOUNT_PREFIX, \
with_docker_exec
from ray.autoscaler._private.log_timer import LogTimer
from ray.autoscaler._private.subprocess_output_util import (
run_cmd_redirected, ProcessRunnerError, is_output_redirected)
from ray.autoscaler._private.cli_logger import cli_logger
import colorful as cf
logger = logging.getLogger(__name__)
# How long to wait for a node to start, in seconds
NODE_START_WAIT_S = 300
HASH_MAX_LENGTH = 10
KUBECTL_RSYNC = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "kubernetes/kubectl-rsync.sh")
_config = {"use_login_shells": True, "silent_rsync": True}
def is_rsync_silent():
return _config["silent_rsync"]
def set_rsync_silent(val):
"""Choose whether to silence rsync output.
Most commands will want to list rsync'd files themselves rather than
print the default rsync spew.
"""
_config["silent_rsync"] = val
def is_using_login_shells():
return _config["use_login_shells"]
def set_using_login_shells(val):
"""Choose between login and non-interactive shells.
Non-interactive shells have the benefit of receiving less output from
subcommands (since progress bars and TTY control codes are not printed).
Sometimes this can be significant since e.g. `pip install` prints
hundreds of progress bar lines when downloading.
Login shells have the benefit of working very close to how a proper bash
session does, regarding how scripts execute and how the environment is
setup. This is also how all commands were ran in the past. The only reason
to use login shells over non-interactive shells is if you need some weird
and non-robust tool to work.
Args:
val (bool): If true, login shells will be used to run all commands.
"""
_config["use_login_shells"] = val
def _with_environment_variables(cmd: str,
environment_variables: Dict[str, object]):
"""Prepend environment variables to a shell command.
Args:
cmd (str): The base command.
environment_variables (Dict[str, object]): The set of environment
variables. If an environment variable value is a dict, it will
automatically be converted to a one line yaml string.
"""
as_strings = []
for key, val in environment_variables.items():
val = json.dumps(val, separators=(",", ":"))
s = "export {}={};".format(key, quote(val))
as_strings.append(s)
all_vars = "".join(as_strings)
return all_vars + cmd
def _with_interactive(cmd):
force_interactive = (
f"true && source ~/.bashrc && "
f"export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && ({cmd})")
return ["bash", "--login", "-c", "-i", quote(force_interactive)]
class KubernetesCommandRunner(CommandRunnerInterface):
def __init__(self, log_prefix, namespace, node_id, auth_config,
process_runner):
self.log_prefix = log_prefix
self.process_runner = process_runner
self.node_id = str(node_id)
self.namespace = namespace
self.kubectl = ["kubectl", "-n", self.namespace]
def run(
self,
cmd=None,
timeout=120,
exit_on_fail=False,
port_forward=None,
with_output=False,
environment_variables: Dict[str, object] = None,
run_env="auto", # Unused argument.
ssh_options_override_ssh_key="", # Unused argument.
shutdown_after_run=False,
):
if shutdown_after_run:
cmd += "; sudo shutdown -h now"
if cmd and port_forward:
raise Exception(
"exec with Kubernetes can't forward ports and execute"
"commands together.")
if port_forward:
if not isinstance(port_forward, list):
port_forward = [port_forward]
port_forward_cmd = self.kubectl + [
"port-forward",
self.node_id,
] + [
"{}:{}".format(local, remote) for local, remote in port_forward
]
logger.info("Port forwarding with: {}".format(
" ".join(port_forward_cmd)))
port_forward_process = subprocess.Popen(port_forward_cmd)
port_forward_process.wait()
# We should never get here, this indicates that port forwarding
# failed, likely because we couldn't bind to a port.
pout, perr = port_forward_process.communicate()
exception_str = " ".join(
port_forward_cmd) + " failed with error: " + perr
raise Exception(exception_str)
else:
final_cmd = self.kubectl + ["exec", "-it"]
final_cmd += [
self.node_id,
"--",
]
if environment_variables:
cmd = _with_environment_variables(cmd, environment_variables)
cmd = _with_interactive(cmd)
cmd_prefix = " ".join(final_cmd)
final_cmd += cmd
# `kubectl exec` + subprocess w/ list of args has unexpected
# side-effects.
final_cmd = " ".join(final_cmd)
logger.info(self.log_prefix + "Running {}".format(final_cmd))
try:
if with_output:
return self.process_runner.check_output(
final_cmd, shell=True)
else:
self.process_runner.check_call(final_cmd, shell=True)
except subprocess.CalledProcessError:
if exit_on_fail:
quoted_cmd = cmd_prefix + quote(" ".join(cmd))
logger.error(
self.log_prefix +
"Command failed: \n\n {}\n".format(quoted_cmd))
sys.exit(1)
else:
raise
def run_rsync_up(self, source, target, options=None):
if target.startswith("~"):
target = "/root" + target[1:]
try:
self.process_runner.check_call([
KUBECTL_RSYNC,
"-avz",
source,
"{}@{}:{}".format(self.node_id, self.namespace, target),
])
except Exception as e:
warnings.warn(
self.log_prefix +
"rsync failed: '{}'. Falling back to 'kubectl cp'".format(e),
UserWarning)
if target.startswith("~"):
target = "/root" + target[1:]
self.process_runner.check_call(self.kubectl + [
"cp", source, "{}/{}:{}".format(self.namespace, self.node_id,
target)
])
def run_rsync_down(self, source, target, options=None):
if target.startswith("~"):
target = "/root" + target[1:]
try:
self.process_runner.check_call([
KUBECTL_RSYNC,
"-avz",
"{}@{}:{}".format(self.node_id, self.namespace, source),
target,
])
except Exception as e:
warnings.warn(
self.log_prefix +
"rsync failed: '{}'. Falling back to 'kubectl cp'".format(e),
UserWarning)
if target.startswith("~"):
target = "/root" + target[1:]
self.process_runner.check_call(self.kubectl + [
"cp", "{}/{}:{}".format(self.namespace, self.node_id, source),
target
])
def remote_shell_command_str(self):
return "{} exec -it {} bash".format(" ".join(self.kubectl),
self.node_id)
class SSHOptions:
def __init__(self, ssh_key, control_path=None, **kwargs):
self.ssh_key = ssh_key
self.arg_dict = {
# Supresses initial fingerprint verification.
"StrictHostKeyChecking": "no",
# SSH IP and fingerprint pairs no longer added to known_hosts.
# This is to remove a "REMOTE HOST IDENTIFICATION HAS CHANGED"
# warning if a new node has the same IP as a previously
# deleted node, because the fingerprints will not match in
# that case.
"UserKnownHostsFile": os.devnull,
# Try fewer extraneous key pairs.
"IdentitiesOnly": "yes",
# Abort if port forwarding fails (instead of just printing to
# stderr).
"ExitOnForwardFailure": "yes",
# Quickly kill the connection if network connection breaks (as
# opposed to hanging/blocking).
"ServerAliveInterval": 5,
"ServerAliveCountMax": 3
}
if control_path:
self.arg_dict.update({
"ControlMaster": "auto",
"ControlPath": "{}/%C".format(control_path),
"ControlPersist": "10s",
})
self.arg_dict.update(kwargs)
def to_ssh_options_list(self, *, timeout=60):
self.arg_dict["ConnectTimeout"] = "{}s".format(timeout)
ssh_key_option = ["-i", self.ssh_key] if self.ssh_key else []
return ssh_key_option + [
x for y in (["-o", "{}={}".format(k, v)]
for k, v in self.arg_dict.items()
if v is not None) for x in y
]
class SSHCommandRunner(CommandRunnerInterface):
def __init__(self, log_prefix, node_id, provider, auth_config,
cluster_name, process_runner, use_internal_ip):
ssh_control_hash = hashlib.md5(cluster_name.encode()).hexdigest()
ssh_user_hash = hashlib.md5(getuser().encode()).hexdigest()
ssh_control_path = "/tmp/ray_ssh_{}/{}".format(
ssh_user_hash[:HASH_MAX_LENGTH],
ssh_control_hash[:HASH_MAX_LENGTH])
self.log_prefix = log_prefix
self.process_runner = process_runner
self.node_id = node_id
self.use_internal_ip = use_internal_ip
self.provider = provider
self.ssh_private_key = auth_config.get("ssh_private_key")
self.ssh_user = auth_config["ssh_user"]
self.ssh_control_path = ssh_control_path
self.ssh_ip = None
self.ssh_proxy_command = auth_config.get("ssh_proxy_command", None)
self.ssh_options = SSHOptions(
self.ssh_private_key,
self.ssh_control_path,
ProxyCommand=self.ssh_proxy_command)
def _get_node_ip(self):
if self.use_internal_ip:
return self.provider.internal_ip(self.node_id)
else:
return self.provider.external_ip(self.node_id)
def _wait_for_ip(self, deadline):
# if we have IP do not print waiting info
ip = self._get_node_ip()
if ip is not None:
cli_logger.labeled_value("Fetched IP", ip)
return ip
interval = 10
with cli_logger.timed("Waiting for IP"):
while time.time() < deadline and \
not self.provider.is_terminated(self.node_id):
cli_logger.old_info(logger, "{}Waiting for IP...",
self.log_prefix)
ip = self._get_node_ip()
if ip is not None:
cli_logger.labeled_value("Received", ip)
return ip
cli_logger.print("Not yet available, retrying in {} seconds",
cf.bold(str(interval)))
time.sleep(interval)
return None
def _set_ssh_ip_if_required(self):
if self.ssh_ip is not None:
return
# We assume that this never changes.
# I think that's reasonable.
deadline = time.time() + NODE_START_WAIT_S
with LogTimer(self.log_prefix + "Got IP"):
ip = self._wait_for_ip(deadline)
cli_logger.doassert(ip is not None,
"Could not get node IP.") # todo: msg
assert ip is not None, "Unable to find IP of node"
self.ssh_ip = ip
# This should run before any SSH commands and therefore ensure that
# the ControlPath directory exists, allowing SSH to maintain
# persistent sessions later on.
try:
os.makedirs(self.ssh_control_path, mode=0o700, exist_ok=True)
except OSError as e:
cli_logger.warning("{}", str(e)) # todo: msg
cli_logger.old_warning(logger, "{}", str(e))
def _run_helper(self,
final_cmd,
with_output=False,
exit_on_fail=False,
silent=False):
"""Run a command that was already setup with SSH and `bash` settings.
Args:
cmd (List[str]):
Full command to run. Should include SSH options and other
processing that we do.
with_output (bool):
If `with_output` is `True`, command stdout and stderr
will be captured and returned.
exit_on_fail (bool):
If `exit_on_fail` is `True`, the process will exit
if the command fails (exits with a code other than 0).
Raises:
ProcessRunnerError if using new log style and disabled
login shells.
click.ClickException if using login shells.
"""
try:
# For now, if the output is needed we just skip the new logic.
# In the future we could update the new logic to support
# capturing output, but it is probably not needed.
if not cli_logger.old_style and not with_output:
return run_cmd_redirected(
final_cmd,
process_runner=self.process_runner,
silent=silent,
use_login_shells=is_using_login_shells())
if with_output:
return self.process_runner.check_output(final_cmd)
else:
return self.process_runner.check_call(final_cmd)
except subprocess.CalledProcessError as e:
quoted_cmd = " ".join(final_cmd[:-1] + [quote(final_cmd[-1])])
if not cli_logger.old_style and not is_using_login_shells():
raise ProcessRunnerError(
"Command failed",
"ssh_command_failed",
code=e.returncode,
command=quoted_cmd)
if exit_on_fail:
raise click.ClickException(
"Command failed:\n\n {}\n".format(quoted_cmd)) from None
else:
fail_msg = "SSH command failed."
if is_output_redirected():
fail_msg += " See above for the output from the failure."
raise click.ClickException(fail_msg) from None
def run(
self,
cmd,
timeout=120,
exit_on_fail=False,
port_forward=None,
with_output=False,
environment_variables: Dict[str, object] = None,
run_env="auto", # Unused argument.
ssh_options_override_ssh_key="",
shutdown_after_run=False,
):
if shutdown_after_run:
cmd += "; sudo shutdown -h now"
if ssh_options_override_ssh_key:
ssh_options = SSHOptions(ssh_options_override_ssh_key)
else:
ssh_options = self.ssh_options
assert isinstance(
ssh_options, SSHOptions
), "ssh_options must be of type SSHOptions, got {}".format(
type(ssh_options))
self._set_ssh_ip_if_required()
if is_using_login_shells():
ssh = ["ssh", "-tt"]
else:
ssh = ["ssh"]
if port_forward:
with cli_logger.group("Forwarding ports"):
if not isinstance(port_forward, list):
port_forward = [port_forward]
for local, remote in port_forward:
cli_logger.verbose(
"Forwarding port {} to port {} on localhost.",
cf.bold(local), cf.bold(remote)) # todo: msg
cli_logger.old_info(logger,
"{}Forwarding {} -> localhost:{}",
self.log_prefix, local, remote)
ssh += ["-L", "{}:localhost:{}".format(remote, local)]
final_cmd = ssh + ssh_options.to_ssh_options_list(timeout=timeout) + [
"{}@{}".format(self.ssh_user, self.ssh_ip)
]
if cmd:
if environment_variables:
cmd = _with_environment_variables(cmd, environment_variables)
if is_using_login_shells():
final_cmd += _with_interactive(cmd)
else:
final_cmd += [cmd]
cli_logger.old_info(logger, "{}Running {}", self.log_prefix,
" ".join(final_cmd))
else:
# We do this because `-o ControlMaster` causes the `-N` flag to
# still create an interactive shell in some ssh versions.
final_cmd.append("while true; do sleep 86400; done")
cli_logger.verbose("Running `{}`", cf.bold(cmd))
with cli_logger.indented():
cli_logger.very_verbose("Full command is `{}`",
cf.bold(" ".join(final_cmd)))
if cli_logger.verbosity > 0:
with cli_logger.indented():
return self._run_helper(final_cmd, with_output, exit_on_fail)
else:
return self._run_helper(final_cmd, with_output, exit_on_fail)
def run_rsync_up(self, source, target, options=None):
self._set_ssh_ip_if_required()
command = [
"rsync", "--rsh",
subprocess.list2cmdline(
["ssh"] + self.ssh_options.to_ssh_options_list(timeout=120)),
"-avz", source, "{}@{}:{}".format(self.ssh_user, self.ssh_ip,
target)
]
cli_logger.verbose("Running `{}`", cf.bold(" ".join(command)))
self._run_helper(command, silent=is_rsync_silent())
def run_rsync_down(self, source, target, options=None):
self._set_ssh_ip_if_required()
command = [
"rsync", "--rsh",
subprocess.list2cmdline(
["ssh"] + self.ssh_options.to_ssh_options_list(timeout=120)),
"-avz", "{}@{}:{}".format(self.ssh_user, self.ssh_ip,
source), target
]
cli_logger.verbose("Running `{}`", cf.bold(" ".join(command)))
self._run_helper(command, silent=is_rsync_silent())
def remote_shell_command_str(self):
if self.ssh_private_key:
return "ssh -o IdentitiesOnly=yes -i {} {}@{}\n".format(
self.ssh_private_key, self.ssh_user, self.ssh_ip)
else:
return "ssh -o IdentitiesOnly=yes {}@{}\n".format(
self.ssh_user, self.ssh_ip)
class DockerCommandRunner(CommandRunnerInterface):
def __init__(self, docker_config, **common_args):
self.ssh_command_runner = SSHCommandRunner(**common_args)
self.container_name = docker_config["container_name"]
self.docker_config = docker_config
self.home_dir = None
self.initialized = False
def run(
self,
cmd,
timeout=120,
exit_on_fail=False,
port_forward=None,
with_output=False,
environment_variables: Dict[str, object] = None,
run_env="auto",
ssh_options_override_ssh_key="",
shutdown_after_run=False,
):
if run_env == "auto":
run_env = "host" if cmd.find("docker") == 0 else "docker"
if environment_variables:
cmd = _with_environment_variables(cmd, environment_variables)
if run_env == "docker":
cmd = self._docker_expand_user(cmd, any_char=True)
cmd = " ".join(_with_interactive(cmd))
cmd = with_docker_exec(
[cmd],
container_name=self.container_name,
with_interactive=True)[0]
if shutdown_after_run:
# sudo shutdown should run after `with_docker_exec` command above
cmd += "; sudo shutdown -h now"
# Do not pass shutdown_after_run argument to ssh_command_runner.run()
# since it is handled above.
return self.ssh_command_runner.run(
cmd,
timeout=timeout,
exit_on_fail=exit_on_fail,
port_forward=port_forward,
with_output=with_output,
ssh_options_override_ssh_key=ssh_options_override_ssh_key)
def run_rsync_up(self, source, target, options=None):
options = options or {}
host_destination = os.path.join(DOCKER_MOUNT_PREFIX,
target.lstrip("/"))
self.ssh_command_runner.run(
f"mkdir -p {os.path.dirname(host_destination.rstrip('/'))}")
self.ssh_command_runner.run_rsync_up(
source, host_destination, options=None)
if self._check_container_status() and not options.get(
"file_mount", False):
if os.path.isdir(source):
# Adding a "." means that docker copies the *contents*
# Without it, docker copies the source *into* the target
host_destination += "/."
self.ssh_command_runner.run("docker cp {} {}:{}".format(
host_destination, self.container_name,
self._docker_expand_user(target)))
def run_rsync_down(self, source, target, options=None):
options = options or {}
host_source = os.path.join(DOCKER_MOUNT_PREFIX, source.lstrip("/"))
self.ssh_command_runner.run(
f"mkdir -p {os.path.dirname(host_source.rstrip('/'))}")
if source[-1] == "/":
source += "."
# Adding a "." means that docker copies the *contents*
# Without it, docker copies the source *into* the target
if not options.get("file_mount", False):
self.ssh_command_runner.run("docker cp {}:{} {}".format(
self.container_name, self._docker_expand_user(source),
host_source))
self.ssh_command_runner.run_rsync_down(
host_source, target, options=None)
def remote_shell_command_str(self):
inner_str = self.ssh_command_runner.remote_shell_command_str().replace(
"ssh", "ssh -tt", 1).strip("\n")
return inner_str + " docker exec -it {} /bin/bash\n".format(
self.container_name)
def _check_docker_installed(self):
no_exist = "NoExist"
output = self.ssh_command_runner.run(
f"command -v docker || echo '{no_exist}'", with_output=True)
cleaned_output = output.decode().strip()
if no_exist in cleaned_output or "docker" not in cleaned_output:
install_commands = [
"curl -fsSL https://get.docker.com -o get-docker.sh",
"sudo sh get-docker.sh", "sudo usermod -aG docker $USER",
"sudo systemctl restart docker -f"
]
logger.error(
"Docker not installed. You can install Docker by adding the "
"following commands to 'initialization_commands':\n" +
"\n".join(install_commands))
def _check_container_status(self):
if self.initialized:
return True
output = self.ssh_command_runner.run(
check_docker_running_cmd(self.container_name),
with_output=True).decode("utf-8").strip()
# Checks for the false positive where "true" is in the container name
return ("true" in output.lower()
and "no such object" not in output.lower())
def _docker_expand_user(self, string, any_char=False):
user_pos = string.find("~")
if user_pos > -1:
if self.home_dir is None:
self.home_dir = self.ssh_command_runner.run(
"docker exec {} env | grep HOME | cut -d'=' -f2".format(
self.container_name),
with_output=True).decode("utf-8").strip()
if any_char:
return string.replace("~/", self.home_dir + "/")
elif not any_char and user_pos == 0:
return string.replace("~", self.home_dir, 1)
return string
def run_init(self, *, as_head, file_mounts):
BOOTSTRAP_MOUNTS = [
"~/ray_bootstrap_config.yaml", "~/ray_bootstrap_key.pem"
]
image = self.docker_config.get("image")
image = self.docker_config.get(
f"{'head' if as_head else 'worker'}_image", image)
self._check_docker_installed()
if self.docker_config.get("pull_before_run", True):
assert image, "Image must be included in config if " + \
"pull_before_run is specified"
self.run("docker pull {}".format(image), run_env="host")
# Bootstrap files cannot be bind mounted because docker opens the
# underlying inode. When the file is switched, docker becomes outdated.
cleaned_bind_mounts = file_mounts.copy()
for mnt in BOOTSTRAP_MOUNTS:
cleaned_bind_mounts.pop(mnt, None)
start_command = docker_start_cmds(
self.ssh_command_runner.ssh_user, image, cleaned_bind_mounts,
self.container_name,
self.docker_config.get("run_options", []) + self.docker_config.get(
f"{'head' if as_head else 'worker'}_run_options", []))
if not self._check_container_status():
self.run(start_command, run_env="host")
else:
running_image = self.run(
check_docker_image(self.container_name),
with_output=True,
run_env="host").decode("utf-8").strip()
if running_image != image:
logger.error(f"A container with name {self.container_name} " +
f"is running image {running_image} instead " +
f"of {image} (which was provided in the YAML")
mounts = self.run(
check_bind_mounts_cmd(self.container_name),
with_output=True,
run_env="host").decode("utf-8").strip()
try:
active_mounts = json.loads(mounts)
active_remote_mounts = [
mnt["Destination"] for mnt in active_mounts
]
# Ignore ray bootstrap files.
for remote, local in cleaned_bind_mounts.items():
remote = self._docker_expand_user(remote)
if remote not in active_remote_mounts:
cli_logger.error(
"Please ray stop & restart cluster to "
f"allow mount {remote}:{local} to take hold")
except json.JSONDecodeError:
cli_logger.verbose(
"Unable to check if file_mounts specified in the YAML "
"differ from those on the running container.")
# Explicitly copy in ray bootstrap files.
for mount in BOOTSTRAP_MOUNTS:
if mount in file_mounts:
self.ssh_command_runner.run(
"docker cp {src} {container}:{dst}".format(
src=os.path.join(DOCKER_MOUNT_PREFIX, mount),
container=self.container_name,
dst=self._docker_expand_user(mount)))
self.initialized = True
| 39.750696 | 79 | 0.566063 | from getpass import getuser
from shlex import quote
from typing import Dict
import click
import hashlib
import json
import logging
import os
import subprocess
import sys
import time
import warnings
from ray.autoscaler.command_runner import CommandRunnerInterface
from ray.autoscaler._private.docker import check_bind_mounts_cmd, \
check_docker_running_cmd, \
check_docker_image, \
docker_start_cmds, \
DOCKER_MOUNT_PREFIX, \
with_docker_exec
from ray.autoscaler._private.log_timer import LogTimer
from ray.autoscaler._private.subprocess_output_util import (
run_cmd_redirected, ProcessRunnerError, is_output_redirected)
from ray.autoscaler._private.cli_logger import cli_logger
import colorful as cf
logger = logging.getLogger(__name__)
NODE_START_WAIT_S = 300
HASH_MAX_LENGTH = 10
KUBECTL_RSYNC = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "kubernetes/kubectl-rsync.sh")
_config = {"use_login_shells": True, "silent_rsync": True}
def is_rsync_silent():
return _config["silent_rsync"]
def set_rsync_silent(val):
_config["silent_rsync"] = val
def is_using_login_shells():
return _config["use_login_shells"]
def set_using_login_shells(val):
_config["use_login_shells"] = val
def _with_environment_variables(cmd: str,
environment_variables: Dict[str, object]):
as_strings = []
for key, val in environment_variables.items():
val = json.dumps(val, separators=(",", ":"))
s = "export {}={};".format(key, quote(val))
as_strings.append(s)
all_vars = "".join(as_strings)
return all_vars + cmd
def _with_interactive(cmd):
force_interactive = (
f"true && source ~/.bashrc && "
f"export OMP_NUM_THREADS=1 PYTHONWARNINGS=ignore && ({cmd})")
return ["bash", "--login", "-c", "-i", quote(force_interactive)]
class KubernetesCommandRunner(CommandRunnerInterface):
def __init__(self, log_prefix, namespace, node_id, auth_config,
process_runner):
self.log_prefix = log_prefix
self.process_runner = process_runner
self.node_id = str(node_id)
self.namespace = namespace
self.kubectl = ["kubectl", "-n", self.namespace]
def run(
self,
cmd=None,
timeout=120,
exit_on_fail=False,
port_forward=None,
with_output=False,
environment_variables: Dict[str, object] = None,
run_env="auto",
ssh_options_override_ssh_key="",
shutdown_after_run=False,
):
if shutdown_after_run:
cmd += "; sudo shutdown -h now"
if cmd and port_forward:
raise Exception(
"exec with Kubernetes can't forward ports and execute"
"commands together.")
if port_forward:
if not isinstance(port_forward, list):
port_forward = [port_forward]
port_forward_cmd = self.kubectl + [
"port-forward",
self.node_id,
] + [
"{}:{}".format(local, remote) for local, remote in port_forward
]
logger.info("Port forwarding with: {}".format(
" ".join(port_forward_cmd)))
port_forward_process = subprocess.Popen(port_forward_cmd)
port_forward_process.wait()
# We should never get here, this indicates that port forwarding
# failed, likely because we couldn't bind to a port.
pout, perr = port_forward_process.communicate()
exception_str = " ".join(
port_forward_cmd) + " failed with error: " + perr
raise Exception(exception_str)
else:
final_cmd = self.kubectl + ["exec", "-it"]
final_cmd += [
self.node_id,
"--",
]
if environment_variables:
cmd = _with_environment_variables(cmd, environment_variables)
cmd = _with_interactive(cmd)
cmd_prefix = " ".join(final_cmd)
final_cmd += cmd
final_cmd = " ".join(final_cmd)
logger.info(self.log_prefix + "Running {}".format(final_cmd))
try:
if with_output:
return self.process_runner.check_output(
final_cmd, shell=True)
else:
self.process_runner.check_call(final_cmd, shell=True)
except subprocess.CalledProcessError:
if exit_on_fail:
quoted_cmd = cmd_prefix + quote(" ".join(cmd))
logger.error(
self.log_prefix +
"Command failed: \n\n {}\n".format(quoted_cmd))
sys.exit(1)
else:
raise
def run_rsync_up(self, source, target, options=None):
if target.startswith("~"):
target = "/root" + target[1:]
try:
self.process_runner.check_call([
KUBECTL_RSYNC,
"-avz",
source,
"{}@{}:{}".format(self.node_id, self.namespace, target),
])
except Exception as e:
warnings.warn(
self.log_prefix +
"rsync failed: '{}'. Falling back to 'kubectl cp'".format(e),
UserWarning)
if target.startswith("~"):
target = "/root" + target[1:]
self.process_runner.check_call(self.kubectl + [
"cp", source, "{}/{}:{}".format(self.namespace, self.node_id,
target)
])
def run_rsync_down(self, source, target, options=None):
if target.startswith("~"):
target = "/root" + target[1:]
try:
self.process_runner.check_call([
KUBECTL_RSYNC,
"-avz",
"{}@{}:{}".format(self.node_id, self.namespace, source),
target,
])
except Exception as e:
warnings.warn(
self.log_prefix +
"rsync failed: '{}'. Falling back to 'kubectl cp'".format(e),
UserWarning)
if target.startswith("~"):
target = "/root" + target[1:]
self.process_runner.check_call(self.kubectl + [
"cp", "{}/{}:{}".format(self.namespace, self.node_id, source),
target
])
def remote_shell_command_str(self):
return "{} exec -it {} bash".format(" ".join(self.kubectl),
self.node_id)
class SSHOptions:
def __init__(self, ssh_key, control_path=None, **kwargs):
self.ssh_key = ssh_key
self.arg_dict = {
"StrictHostKeyChecking": "no",
"UserKnownHostsFile": os.devnull,
"IdentitiesOnly": "yes",
"ExitOnForwardFailure": "yes",
"ServerAliveInterval": 5,
"ServerAliveCountMax": 3
}
if control_path:
self.arg_dict.update({
"ControlMaster": "auto",
"ControlPath": "{}/%C".format(control_path),
"ControlPersist": "10s",
})
self.arg_dict.update(kwargs)
def to_ssh_options_list(self, *, timeout=60):
self.arg_dict["ConnectTimeout"] = "{}s".format(timeout)
ssh_key_option = ["-i", self.ssh_key] if self.ssh_key else []
return ssh_key_option + [
x for y in (["-o", "{}={}".format(k, v)]
for k, v in self.arg_dict.items()
if v is not None) for x in y
]
class SSHCommandRunner(CommandRunnerInterface):
def __init__(self, log_prefix, node_id, provider, auth_config,
cluster_name, process_runner, use_internal_ip):
ssh_control_hash = hashlib.md5(cluster_name.encode()).hexdigest()
ssh_user_hash = hashlib.md5(getuser().encode()).hexdigest()
ssh_control_path = "/tmp/ray_ssh_{}/{}".format(
ssh_user_hash[:HASH_MAX_LENGTH],
ssh_control_hash[:HASH_MAX_LENGTH])
self.log_prefix = log_prefix
self.process_runner = process_runner
self.node_id = node_id
self.use_internal_ip = use_internal_ip
self.provider = provider
self.ssh_private_key = auth_config.get("ssh_private_key")
self.ssh_user = auth_config["ssh_user"]
self.ssh_control_path = ssh_control_path
self.ssh_ip = None
self.ssh_proxy_command = auth_config.get("ssh_proxy_command", None)
self.ssh_options = SSHOptions(
self.ssh_private_key,
self.ssh_control_path,
ProxyCommand=self.ssh_proxy_command)
def _get_node_ip(self):
if self.use_internal_ip:
return self.provider.internal_ip(self.node_id)
else:
return self.provider.external_ip(self.node_id)
def _wait_for_ip(self, deadline):
ip = self._get_node_ip()
if ip is not None:
cli_logger.labeled_value("Fetched IP", ip)
return ip
interval = 10
with cli_logger.timed("Waiting for IP"):
while time.time() < deadline and \
not self.provider.is_terminated(self.node_id):
cli_logger.old_info(logger, "{}Waiting for IP...",
self.log_prefix)
ip = self._get_node_ip()
if ip is not None:
cli_logger.labeled_value("Received", ip)
return ip
cli_logger.print("Not yet available, retrying in {} seconds",
cf.bold(str(interval)))
time.sleep(interval)
return None
def _set_ssh_ip_if_required(self):
if self.ssh_ip is not None:
return
deadline = time.time() + NODE_START_WAIT_S
with LogTimer(self.log_prefix + "Got IP"):
ip = self._wait_for_ip(deadline)
cli_logger.doassert(ip is not None,
"Could not get node IP.") # todo: msg
assert ip is not None, "Unable to find IP of node"
self.ssh_ip = ip
# This should run before any SSH commands and therefore ensure that
# the ControlPath directory exists, allowing SSH to maintain
# persistent sessions later on.
try:
os.makedirs(self.ssh_control_path, mode=0o700, exist_ok=True)
except OSError as e:
cli_logger.warning("{}", str(e)) # todo: msg
cli_logger.old_warning(logger, "{}", str(e))
def _run_helper(self,
final_cmd,
with_output=False,
exit_on_fail=False,
silent=False):
try:
# For now, if the output is needed we just skip the new logic.
# In the future we could update the new logic to support
# capturing output, but it is probably not needed.
if not cli_logger.old_style and not with_output:
return run_cmd_redirected(
final_cmd,
process_runner=self.process_runner,
silent=silent,
use_login_shells=is_using_login_shells())
if with_output:
return self.process_runner.check_output(final_cmd)
else:
return self.process_runner.check_call(final_cmd)
except subprocess.CalledProcessError as e:
quoted_cmd = " ".join(final_cmd[:-1] + [quote(final_cmd[-1])])
if not cli_logger.old_style and not is_using_login_shells():
raise ProcessRunnerError(
"Command failed",
"ssh_command_failed",
code=e.returncode,
command=quoted_cmd)
if exit_on_fail:
raise click.ClickException(
"Command failed:\n\n {}\n".format(quoted_cmd)) from None
else:
fail_msg = "SSH command failed."
if is_output_redirected():
fail_msg += " See above for the output from the failure."
raise click.ClickException(fail_msg) from None
def run(
self,
cmd,
timeout=120,
exit_on_fail=False,
port_forward=None,
with_output=False,
environment_variables: Dict[str, object] = None,
run_env="auto", # Unused argument.
ssh_options_override_ssh_key="",
shutdown_after_run=False,
):
if shutdown_after_run:
cmd += "; sudo shutdown -h now"
if ssh_options_override_ssh_key:
ssh_options = SSHOptions(ssh_options_override_ssh_key)
else:
ssh_options = self.ssh_options
assert isinstance(
ssh_options, SSHOptions
), "ssh_options must be of type SSHOptions, got {}".format(
type(ssh_options))
self._set_ssh_ip_if_required()
if is_using_login_shells():
ssh = ["ssh", "-tt"]
else:
ssh = ["ssh"]
if port_forward:
with cli_logger.group("Forwarding ports"):
if not isinstance(port_forward, list):
port_forward = [port_forward]
for local, remote in port_forward:
cli_logger.verbose(
"Forwarding port {} to port {} on localhost.",
cf.bold(local), cf.bold(remote)) # todo: msg
cli_logger.old_info(logger,
"{}Forwarding {} -> localhost:{}",
self.log_prefix, local, remote)
ssh += ["-L", "{}:localhost:{}".format(remote, local)]
final_cmd = ssh + ssh_options.to_ssh_options_list(timeout=timeout) + [
"{}@{}".format(self.ssh_user, self.ssh_ip)
]
if cmd:
if environment_variables:
cmd = _with_environment_variables(cmd, environment_variables)
if is_using_login_shells():
final_cmd += _with_interactive(cmd)
else:
final_cmd += [cmd]
cli_logger.old_info(logger, "{}Running {}", self.log_prefix,
" ".join(final_cmd))
else:
# We do this because `-o ControlMaster` causes the `-N` flag to
# still create an interactive shell in some ssh versions.
final_cmd.append("while true; do sleep 86400; done")
cli_logger.verbose("Running `{}`", cf.bold(cmd))
with cli_logger.indented():
cli_logger.very_verbose("Full command is `{}`",
cf.bold(" ".join(final_cmd)))
if cli_logger.verbosity > 0:
with cli_logger.indented():
return self._run_helper(final_cmd, with_output, exit_on_fail)
else:
return self._run_helper(final_cmd, with_output, exit_on_fail)
def run_rsync_up(self, source, target, options=None):
self._set_ssh_ip_if_required()
command = [
"rsync", "--rsh",
subprocess.list2cmdline(
["ssh"] + self.ssh_options.to_ssh_options_list(timeout=120)),
"-avz", source, "{}@{}:{}".format(self.ssh_user, self.ssh_ip,
target)
]
cli_logger.verbose("Running `{}`", cf.bold(" ".join(command)))
self._run_helper(command, silent=is_rsync_silent())
def run_rsync_down(self, source, target, options=None):
self._set_ssh_ip_if_required()
command = [
"rsync", "--rsh",
subprocess.list2cmdline(
["ssh"] + self.ssh_options.to_ssh_options_list(timeout=120)),
"-avz", "{}@{}:{}".format(self.ssh_user, self.ssh_ip,
source), target
]
cli_logger.verbose("Running `{}`", cf.bold(" ".join(command)))
self._run_helper(command, silent=is_rsync_silent())
def remote_shell_command_str(self):
if self.ssh_private_key:
return "ssh -o IdentitiesOnly=yes -i {} {}@{}\n".format(
self.ssh_private_key, self.ssh_user, self.ssh_ip)
else:
return "ssh -o IdentitiesOnly=yes {}@{}\n".format(
self.ssh_user, self.ssh_ip)
class DockerCommandRunner(CommandRunnerInterface):
def __init__(self, docker_config, **common_args):
self.ssh_command_runner = SSHCommandRunner(**common_args)
self.container_name = docker_config["container_name"]
self.docker_config = docker_config
self.home_dir = None
self.initialized = False
def run(
self,
cmd,
timeout=120,
exit_on_fail=False,
port_forward=None,
with_output=False,
environment_variables: Dict[str, object] = None,
run_env="auto",
ssh_options_override_ssh_key="",
shutdown_after_run=False,
):
if run_env == "auto":
run_env = "host" if cmd.find("docker") == 0 else "docker"
if environment_variables:
cmd = _with_environment_variables(cmd, environment_variables)
if run_env == "docker":
cmd = self._docker_expand_user(cmd, any_char=True)
cmd = " ".join(_with_interactive(cmd))
cmd = with_docker_exec(
[cmd],
container_name=self.container_name,
with_interactive=True)[0]
if shutdown_after_run:
# sudo shutdown should run after `with_docker_exec` command above
cmd += "; sudo shutdown -h now"
# Do not pass shutdown_after_run argument to ssh_command_runner.run()
# since it is handled above.
return self.ssh_command_runner.run(
cmd,
timeout=timeout,
exit_on_fail=exit_on_fail,
port_forward=port_forward,
with_output=with_output,
ssh_options_override_ssh_key=ssh_options_override_ssh_key)
def run_rsync_up(self, source, target, options=None):
options = options or {}
host_destination = os.path.join(DOCKER_MOUNT_PREFIX,
target.lstrip("/"))
self.ssh_command_runner.run(
f"mkdir -p {os.path.dirname(host_destination.rstrip('/'))}")
self.ssh_command_runner.run_rsync_up(
source, host_destination, options=None)
if self._check_container_status() and not options.get(
"file_mount", False):
if os.path.isdir(source):
# Adding a "." means that docker copies the *contents*
# Without it, docker copies the source *into* the target
host_destination += "/."
self.ssh_command_runner.run("docker cp {} {}:{}".format(
host_destination, self.container_name,
self._docker_expand_user(target)))
def run_rsync_down(self, source, target, options=None):
options = options or {}
host_source = os.path.join(DOCKER_MOUNT_PREFIX, source.lstrip("/"))
self.ssh_command_runner.run(
f"mkdir -p {os.path.dirname(host_source.rstrip('/'))}")
if source[-1] == "/":
source += "."
# Adding a "." means that docker copies the *contents*
# Without it, docker copies the source *into* the target
if not options.get("file_mount", False):
self.ssh_command_runner.run("docker cp {}:{} {}".format(
self.container_name, self._docker_expand_user(source),
host_source))
self.ssh_command_runner.run_rsync_down(
host_source, target, options=None)
def remote_shell_command_str(self):
inner_str = self.ssh_command_runner.remote_shell_command_str().replace(
"ssh", "ssh -tt", 1).strip("\n")
return inner_str + " docker exec -it {} /bin/bash\n".format(
self.container_name)
def _check_docker_installed(self):
no_exist = "NoExist"
output = self.ssh_command_runner.run(
f"command -v docker || echo '{no_exist}'", with_output=True)
cleaned_output = output.decode().strip()
if no_exist in cleaned_output or "docker" not in cleaned_output:
install_commands = [
"curl -fsSL https://get.docker.com -o get-docker.sh",
"sudo sh get-docker.sh", "sudo usermod -aG docker $USER",
"sudo systemctl restart docker -f"
]
logger.error(
"Docker not installed. You can install Docker by adding the "
"following commands to 'initialization_commands':\n" +
"\n".join(install_commands))
def _check_container_status(self):
if self.initialized:
return True
output = self.ssh_command_runner.run(
check_docker_running_cmd(self.container_name),
with_output=True).decode("utf-8").strip()
# Checks for the false positive where "true" is in the container name
return ("true" in output.lower()
and "no such object" not in output.lower())
def _docker_expand_user(self, string, any_char=False):
user_pos = string.find("~")
if user_pos > -1:
if self.home_dir is None:
self.home_dir = self.ssh_command_runner.run(
"docker exec {} env | grep HOME | cut -d'=' -f2".format(
self.container_name),
with_output=True).decode("utf-8").strip()
if any_char:
return string.replace("~/", self.home_dir + "/")
elif not any_char and user_pos == 0:
return string.replace("~", self.home_dir, 1)
return string
def run_init(self, *, as_head, file_mounts):
BOOTSTRAP_MOUNTS = [
"~/ray_bootstrap_config.yaml", "~/ray_bootstrap_key.pem"
]
image = self.docker_config.get("image")
image = self.docker_config.get(
f"{'head' if as_head else 'worker'}_image", image)
self._check_docker_installed()
if self.docker_config.get("pull_before_run", True):
assert image, "Image must be included in config if " + \
"pull_before_run is specified"
self.run("docker pull {}".format(image), run_env="host")
# Bootstrap files cannot be bind mounted because docker opens the
# underlying inode. When the file is switched, docker becomes outdated.
cleaned_bind_mounts = file_mounts.copy()
for mnt in BOOTSTRAP_MOUNTS:
cleaned_bind_mounts.pop(mnt, None)
start_command = docker_start_cmds(
self.ssh_command_runner.ssh_user, image, cleaned_bind_mounts,
self.container_name,
self.docker_config.get("run_options", []) + self.docker_config.get(
f"{'head' if as_head else 'worker'}_run_options", []))
if not self._check_container_status():
self.run(start_command, run_env="host")
else:
running_image = self.run(
check_docker_image(self.container_name),
with_output=True,
run_env="host").decode("utf-8").strip()
if running_image != image:
logger.error(f"A container with name {self.container_name} " +
f"is running image {running_image} instead " +
f"of {image} (which was provided in the YAML")
mounts = self.run(
check_bind_mounts_cmd(self.container_name),
with_output=True,
run_env="host").decode("utf-8").strip()
try:
active_mounts = json.loads(mounts)
active_remote_mounts = [
mnt["Destination"] for mnt in active_mounts
]
# Ignore ray bootstrap files.
for remote, local in cleaned_bind_mounts.items():
remote = self._docker_expand_user(remote)
if remote not in active_remote_mounts:
cli_logger.error(
"Please ray stop & restart cluster to "
f"allow mount {remote}:{local} to take hold")
except json.JSONDecodeError:
cli_logger.verbose(
"Unable to check if file_mounts specified in the YAML "
"differ from those on the running container.")
# Explicitly copy in ray bootstrap files.
for mount in BOOTSTRAP_MOUNTS:
if mount in file_mounts:
self.ssh_command_runner.run(
"docker cp {src} {container}:{dst}".format(
src=os.path.join(DOCKER_MOUNT_PREFIX, mount),
container=self.container_name,
dst=self._docker_expand_user(mount)))
self.initialized = True
| true | true |
f72c13cb90eedb34f57932aeb5a75dd0d3d17462 | 9,968 | py | Python | paddlex/ppdet/modeling/assigners/atss_assigner.py | cheneyveron/PaddleX | 86f73fc6a66b12c638f642524bfd1cf730e26c4b | [
"Apache-2.0"
] | 8 | 2020-03-11T08:12:19.000Z | 2020-03-18T08:33:56.000Z | paddlex/ppdet/modeling/assigners/atss_assigner.py | cheneyveron/PaddleX | 86f73fc6a66b12c638f642524bfd1cf730e26c4b | [
"Apache-2.0"
] | 1 | 2020-03-15T13:05:43.000Z | 2020-03-15T13:05:43.000Z | paddlex/ppdet/modeling/assigners/atss_assigner.py | cheneyveron/PaddleX | 86f73fc6a66b12c638f642524bfd1cf730e26c4b | [
"Apache-2.0"
] | 2 | 2020-03-15T11:53:54.000Z | 2020-03-24T07:27:09.000Z | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddlex.ppdet.core.workspace import register
from ..ops import iou_similarity
from ..bbox_utils import bbox_center
from .utils import (pad_gt, check_points_inside_bboxes, compute_max_iou_anchor,
compute_max_iou_gt)
@register
class ATSSAssigner(nn.Layer):
"""Bridging the Gap Between Anchor-based and Anchor-free Detection
via Adaptive Training Sample Selection
"""
__shared__ = ['num_classes']
def __init__(self,
topk=9,
num_classes=80,
force_gt_matching=False,
eps=1e-9):
super(ATSSAssigner, self).__init__()
self.topk = topk
self.num_classes = num_classes
self.force_gt_matching = force_gt_matching
self.eps = eps
def _gather_topk_pyramid(self, gt2anchor_distances, num_anchors_list,
pad_gt_mask):
pad_gt_mask = pad_gt_mask.tile([1, 1, self.topk]).astype(paddle.bool)
gt2anchor_distances_list = paddle.split(
gt2anchor_distances, num_anchors_list, axis=-1)
num_anchors_index = np.cumsum(num_anchors_list).tolist()
num_anchors_index = [0, ] + num_anchors_index[:-1]
is_in_topk_list = []
topk_idxs_list = []
for distances, anchors_index in zip(gt2anchor_distances_list,
num_anchors_index):
num_anchors = distances.shape[-1]
topk_metrics, topk_idxs = paddle.topk(
distances, self.topk, axis=-1, largest=False)
topk_idxs_list.append(topk_idxs + anchors_index)
topk_idxs = paddle.where(pad_gt_mask, topk_idxs,
paddle.zeros_like(topk_idxs))
is_in_topk = F.one_hot(topk_idxs, num_anchors).sum(axis=-2)
is_in_topk = paddle.where(is_in_topk > 1,
paddle.zeros_like(is_in_topk),
is_in_topk)
is_in_topk_list.append(
is_in_topk.astype(gt2anchor_distances.dtype))
is_in_topk_list = paddle.concat(is_in_topk_list, axis=-1)
topk_idxs_list = paddle.concat(topk_idxs_list, axis=-1)
return is_in_topk_list, topk_idxs_list
@paddle.no_grad()
def forward(self,
anchor_bboxes,
num_anchors_list,
gt_labels,
gt_bboxes,
bg_index,
gt_scores=None):
r"""This code is based on
https://github.com/fcjian/TOOD/blob/master/mmdet/core/bbox/assigners/atss_assigner.py
The assignment is done in following steps
1. compute iou between all bbox (bbox of all pyramid levels) and gt
2. compute center distance between all bbox and gt
3. on each pyramid level, for each gt, select k bbox whose center
are closest to the gt center, so we total select k*l bbox as
candidates for each gt
4. get corresponding iou for the these candidates, and compute the
mean and std, set mean + std as the iou threshold
5. select these candidates whose iou are greater than or equal to
the threshold as positive
6. limit the positive sample's center in gt
7. if an anchor box is assigned to multiple gts, the one with the
highest iou will be selected.
Args:
anchor_bboxes (Tensor, float32): pre-defined anchors, shape(L, 4),
"xmin, xmax, ymin, ymax" format
num_anchors_list (List): num of anchors in each level
gt_labels (Tensor|List[Tensor], int64): Label of gt_bboxes, shape(B, n, 1)
gt_bboxes (Tensor|List[Tensor], float32): Ground truth bboxes, shape(B, n, 4)
bg_index (int): background index
gt_scores (Tensor|List[Tensor]|None, float32) Score of gt_bboxes,
shape(B, n, 1), if None, then it will initialize with one_hot label
Returns:
assigned_labels (Tensor): (B, L)
assigned_bboxes (Tensor): (B, L, 4)
assigned_scores (Tensor): (B, L, C)
"""
gt_labels, gt_bboxes, pad_gt_scores, pad_gt_mask = pad_gt(
gt_labels, gt_bboxes, gt_scores)
assert gt_labels.ndim == gt_bboxes.ndim and \
gt_bboxes.ndim == 3
num_anchors, _ = anchor_bboxes.shape
batch_size, num_max_boxes, _ = gt_bboxes.shape
# negative batch
if num_max_boxes == 0:
assigned_labels = paddle.full([batch_size, num_anchors], bg_index)
assigned_bboxes = paddle.zeros([batch_size, num_anchors, 4])
assigned_scores = paddle.zeros(
[batch_size, num_anchors, self.num_classes])
return assigned_labels, assigned_bboxes, assigned_scores
# 1. compute iou between gt and anchor bbox, [B, n, L]
ious = iou_similarity(gt_bboxes.reshape([-1, 4]), anchor_bboxes)
ious = ious.reshape([batch_size, -1, num_anchors])
# 2. compute center distance between all anchors and gt, [B, n, L]
gt_centers = bbox_center(gt_bboxes.reshape([-1, 4])).unsqueeze(1)
anchor_centers = bbox_center(anchor_bboxes)
gt2anchor_distances = (gt_centers - anchor_centers.unsqueeze(0)) \
.norm(2, axis=-1).reshape([batch_size, -1, num_anchors])
# 3. on each pyramid level, selecting topk closest candidates
# based on the center distance, [B, n, L]
is_in_topk, topk_idxs = self._gather_topk_pyramid(
gt2anchor_distances, num_anchors_list, pad_gt_mask)
# 4. get corresponding iou for the these candidates, and compute the
# mean and std, 5. set mean + std as the iou threshold
iou_candidates = ious * is_in_topk
iou_threshold = paddle.index_sample(
iou_candidates.flatten(stop_axis=-2),
topk_idxs.flatten(stop_axis=-2))
iou_threshold = iou_threshold.reshape([batch_size, num_max_boxes, -1])
iou_threshold = iou_threshold.mean(axis=-1, keepdim=True) + \
iou_threshold.std(axis=-1, keepdim=True)
is_in_topk = paddle.where(
iou_candidates > iou_threshold.tile([1, 1, num_anchors]),
is_in_topk, paddle.zeros_like(is_in_topk))
# 6. check the positive sample's center in gt, [B, n, L]
is_in_gts = check_points_inside_bboxes(anchor_centers, gt_bboxes)
# select positive sample, [B, n, L]
mask_positive = is_in_topk * is_in_gts * pad_gt_mask
# 7. if an anchor box is assigned to multiple gts,
# the one with the highest iou will be selected.
mask_positive_sum = mask_positive.sum(axis=-2)
if mask_positive_sum.max() > 1:
mask_multiple_gts = (mask_positive_sum.unsqueeze(1) > 1).tile(
[1, num_max_boxes, 1])
is_max_iou = compute_max_iou_anchor(ious)
mask_positive = paddle.where(mask_multiple_gts, is_max_iou,
mask_positive)
mask_positive_sum = mask_positive.sum(axis=-2)
# 8. make sure every gt_bbox matches the anchor
if self.force_gt_matching:
is_max_iou = compute_max_iou_gt(ious) * pad_gt_mask
mask_max_iou = (is_max_iou.sum(-2, keepdim=True) == 1).tile(
[1, num_max_boxes, 1])
mask_positive = paddle.where(mask_max_iou, is_max_iou,
mask_positive)
mask_positive_sum = mask_positive.sum(axis=-2)
assigned_gt_index = mask_positive.argmax(axis=-2)
assert mask_positive_sum.max() == 1, \
("one anchor just assign one gt, but received not equals 1. "
"Received: %f" % mask_positive_sum.max().item())
# assigned target
batch_ind = paddle.arange(
end=batch_size, dtype=gt_labels.dtype).unsqueeze(-1)
assigned_gt_index = assigned_gt_index + batch_ind * num_max_boxes
assigned_labels = paddle.gather(
gt_labels.flatten(), assigned_gt_index.flatten(), axis=0)
assigned_labels = assigned_labels.reshape([batch_size, num_anchors])
assigned_labels = paddle.where(
mask_positive_sum > 0, assigned_labels,
paddle.full_like(assigned_labels, bg_index))
assigned_bboxes = paddle.gather(
gt_bboxes.reshape([-1, 4]), assigned_gt_index.flatten(), axis=0)
assigned_bboxes = assigned_bboxes.reshape([batch_size, num_anchors, 4])
assigned_scores = F.one_hot(assigned_labels, self.num_classes)
if gt_scores is not None:
gather_scores = paddle.gather(
pad_gt_scores.flatten(), assigned_gt_index.flatten(), axis=0)
gather_scores = gather_scores.reshape([batch_size, num_anchors])
gather_scores = paddle.where(mask_positive_sum > 0, gather_scores,
paddle.zeros_like(gather_scores))
assigned_scores *= gather_scores.unsqueeze(-1)
return assigned_labels, assigned_bboxes, assigned_scores
| 47.018868 | 97 | 0.634129 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddlex.ppdet.core.workspace import register
from ..ops import iou_similarity
from ..bbox_utils import bbox_center
from .utils import (pad_gt, check_points_inside_bboxes, compute_max_iou_anchor,
compute_max_iou_gt)
@register
class ATSSAssigner(nn.Layer):
__shared__ = ['num_classes']
def __init__(self,
topk=9,
num_classes=80,
force_gt_matching=False,
eps=1e-9):
super(ATSSAssigner, self).__init__()
self.topk = topk
self.num_classes = num_classes
self.force_gt_matching = force_gt_matching
self.eps = eps
def _gather_topk_pyramid(self, gt2anchor_distances, num_anchors_list,
pad_gt_mask):
pad_gt_mask = pad_gt_mask.tile([1, 1, self.topk]).astype(paddle.bool)
gt2anchor_distances_list = paddle.split(
gt2anchor_distances, num_anchors_list, axis=-1)
num_anchors_index = np.cumsum(num_anchors_list).tolist()
num_anchors_index = [0, ] + num_anchors_index[:-1]
is_in_topk_list = []
topk_idxs_list = []
for distances, anchors_index in zip(gt2anchor_distances_list,
num_anchors_index):
num_anchors = distances.shape[-1]
topk_metrics, topk_idxs = paddle.topk(
distances, self.topk, axis=-1, largest=False)
topk_idxs_list.append(topk_idxs + anchors_index)
topk_idxs = paddle.where(pad_gt_mask, topk_idxs,
paddle.zeros_like(topk_idxs))
is_in_topk = F.one_hot(topk_idxs, num_anchors).sum(axis=-2)
is_in_topk = paddle.where(is_in_topk > 1,
paddle.zeros_like(is_in_topk),
is_in_topk)
is_in_topk_list.append(
is_in_topk.astype(gt2anchor_distances.dtype))
is_in_topk_list = paddle.concat(is_in_topk_list, axis=-1)
topk_idxs_list = paddle.concat(topk_idxs_list, axis=-1)
return is_in_topk_list, topk_idxs_list
@paddle.no_grad()
def forward(self,
anchor_bboxes,
num_anchors_list,
gt_labels,
gt_bboxes,
bg_index,
gt_scores=None):
gt_labels, gt_bboxes, pad_gt_scores, pad_gt_mask = pad_gt(
gt_labels, gt_bboxes, gt_scores)
assert gt_labels.ndim == gt_bboxes.ndim and \
gt_bboxes.ndim == 3
num_anchors, _ = anchor_bboxes.shape
batch_size, num_max_boxes, _ = gt_bboxes.shape
if num_max_boxes == 0:
assigned_labels = paddle.full([batch_size, num_anchors], bg_index)
assigned_bboxes = paddle.zeros([batch_size, num_anchors, 4])
assigned_scores = paddle.zeros(
[batch_size, num_anchors, self.num_classes])
return assigned_labels, assigned_bboxes, assigned_scores
ious = iou_similarity(gt_bboxes.reshape([-1, 4]), anchor_bboxes)
ious = ious.reshape([batch_size, -1, num_anchors])
gt_centers = bbox_center(gt_bboxes.reshape([-1, 4])).unsqueeze(1)
anchor_centers = bbox_center(anchor_bboxes)
gt2anchor_distances = (gt_centers - anchor_centers.unsqueeze(0)) \
.norm(2, axis=-1).reshape([batch_size, -1, num_anchors])
is_in_topk, topk_idxs = self._gather_topk_pyramid(
gt2anchor_distances, num_anchors_list, pad_gt_mask)
iou_candidates = ious * is_in_topk
iou_threshold = paddle.index_sample(
iou_candidates.flatten(stop_axis=-2),
topk_idxs.flatten(stop_axis=-2))
iou_threshold = iou_threshold.reshape([batch_size, num_max_boxes, -1])
iou_threshold = iou_threshold.mean(axis=-1, keepdim=True) + \
iou_threshold.std(axis=-1, keepdim=True)
is_in_topk = paddle.where(
iou_candidates > iou_threshold.tile([1, 1, num_anchors]),
is_in_topk, paddle.zeros_like(is_in_topk))
is_in_gts = check_points_inside_bboxes(anchor_centers, gt_bboxes)
# select positive sample, [B, n, L]
mask_positive = is_in_topk * is_in_gts * pad_gt_mask
# 7. if an anchor box is assigned to multiple gts,
# the one with the highest iou will be selected.
mask_positive_sum = mask_positive.sum(axis=-2)
if mask_positive_sum.max() > 1:
mask_multiple_gts = (mask_positive_sum.unsqueeze(1) > 1).tile(
[1, num_max_boxes, 1])
is_max_iou = compute_max_iou_anchor(ious)
mask_positive = paddle.where(mask_multiple_gts, is_max_iou,
mask_positive)
mask_positive_sum = mask_positive.sum(axis=-2)
# 8. make sure every gt_bbox matches the anchor
if self.force_gt_matching:
is_max_iou = compute_max_iou_gt(ious) * pad_gt_mask
mask_max_iou = (is_max_iou.sum(-2, keepdim=True) == 1).tile(
[1, num_max_boxes, 1])
mask_positive = paddle.where(mask_max_iou, is_max_iou,
mask_positive)
mask_positive_sum = mask_positive.sum(axis=-2)
assigned_gt_index = mask_positive.argmax(axis=-2)
assert mask_positive_sum.max() == 1, \
("one anchor just assign one gt, but received not equals 1. "
"Received: %f" % mask_positive_sum.max().item())
# assigned target
batch_ind = paddle.arange(
end=batch_size, dtype=gt_labels.dtype).unsqueeze(-1)
assigned_gt_index = assigned_gt_index + batch_ind * num_max_boxes
assigned_labels = paddle.gather(
gt_labels.flatten(), assigned_gt_index.flatten(), axis=0)
assigned_labels = assigned_labels.reshape([batch_size, num_anchors])
assigned_labels = paddle.where(
mask_positive_sum > 0, assigned_labels,
paddle.full_like(assigned_labels, bg_index))
assigned_bboxes = paddle.gather(
gt_bboxes.reshape([-1, 4]), assigned_gt_index.flatten(), axis=0)
assigned_bboxes = assigned_bboxes.reshape([batch_size, num_anchors, 4])
assigned_scores = F.one_hot(assigned_labels, self.num_classes)
if gt_scores is not None:
gather_scores = paddle.gather(
pad_gt_scores.flatten(), assigned_gt_index.flatten(), axis=0)
gather_scores = gather_scores.reshape([batch_size, num_anchors])
gather_scores = paddle.where(mask_positive_sum > 0, gather_scores,
paddle.zeros_like(gather_scores))
assigned_scores *= gather_scores.unsqueeze(-1)
return assigned_labels, assigned_bboxes, assigned_scores
| true | true |
f72c141ee52744b76809f89d01d00892da4316b0 | 1,625 | py | Python | models/heads/linear.py | lucasmtz/ACAR-Net | 08a224625f04bbf595baaeb1c79ec491642e0059 | [
"Apache-2.0"
] | null | null | null | models/heads/linear.py | lucasmtz/ACAR-Net | 08a224625f04bbf595baaeb1c79ec491642e0059 | [
"Apache-2.0"
] | null | null | null | models/heads/linear.py | lucasmtz/ACAR-Net | 08a224625f04bbf595baaeb1c79ec491642e0059 | [
"Apache-2.0"
] | null | null | null | import torch
import torch.nn as nn
import torchvision
__all__ = ["linear"]
class LinearHead(nn.Module):
def __init__(self, width, roi_spatial=7, num_classes=60, dropout=0.0, bias=False):
super().__init__()
self.roi_spatial = roi_spatial
self.roi_maxpool = nn.MaxPool2d(roi_spatial)
self.fc = nn.Linear(width, num_classes, bias=bias)
if dropout > 0:
self.dp = nn.Dropout(dropout)
else:
self.dp = None
# data: features, rois
# returns: outputs
def forward(self, data):
if not isinstance(data["features"], list):
features = [data["features"]]
else:
features = data["features"]
roi_features = []
for f in features:
sp = f.shape
h, w = sp[3:]
feats = nn.AdaptiveAvgPool3d((1, h, w))(f).view(-1, sp[1], h, w)
rois = data["rois"].clone()
rois[:, 1] = rois[:, 1] * w
rois[:, 2] = rois[:, 2] * h
rois[:, 3] = rois[:, 3] * w
rois[:, 4] = rois[:, 4] * h
rois = rois.detach()
roi_feats = torchvision.ops.roi_align(feats, rois, (self.roi_spatial, self.roi_spatial))
roi_feats = self.roi_maxpool(roi_feats).view(-1, sp[1])
roi_features.append(roi_feats)
roi_features = torch.cat(roi_features, dim=1)
if self.dp is not None:
roi_features = self.dp(roi_features)
outputs = self.fc(roi_features)
return {"outputs": outputs}
def linear(**kwargs):
model = LinearHead(**kwargs)
return model
| 28.017241 | 100 | 0.549538 | import torch
import torch.nn as nn
import torchvision
__all__ = ["linear"]
class LinearHead(nn.Module):
def __init__(self, width, roi_spatial=7, num_classes=60, dropout=0.0, bias=False):
super().__init__()
self.roi_spatial = roi_spatial
self.roi_maxpool = nn.MaxPool2d(roi_spatial)
self.fc = nn.Linear(width, num_classes, bias=bias)
if dropout > 0:
self.dp = nn.Dropout(dropout)
else:
self.dp = None
def forward(self, data):
if not isinstance(data["features"], list):
features = [data["features"]]
else:
features = data["features"]
roi_features = []
for f in features:
sp = f.shape
h, w = sp[3:]
feats = nn.AdaptiveAvgPool3d((1, h, w))(f).view(-1, sp[1], h, w)
rois = data["rois"].clone()
rois[:, 1] = rois[:, 1] * w
rois[:, 2] = rois[:, 2] * h
rois[:, 3] = rois[:, 3] * w
rois[:, 4] = rois[:, 4] * h
rois = rois.detach()
roi_feats = torchvision.ops.roi_align(feats, rois, (self.roi_spatial, self.roi_spatial))
roi_feats = self.roi_maxpool(roi_feats).view(-1, sp[1])
roi_features.append(roi_feats)
roi_features = torch.cat(roi_features, dim=1)
if self.dp is not None:
roi_features = self.dp(roi_features)
outputs = self.fc(roi_features)
return {"outputs": outputs}
def linear(**kwargs):
model = LinearHead(**kwargs)
return model
| true | true |
f72c167153faf45427e82959b2fabf65122a99b7 | 3,730 | py | Python | lib/follower.py | bopopescu/ros | 5dc6e23a280e1283de7b38f35116332a79ca33d2 | [
"MIT"
] | null | null | null | lib/follower.py | bopopescu/ros | 5dc6e23a280e1283de7b38f35116332a79ca33d2 | [
"MIT"
] | null | null | null | lib/follower.py | bopopescu/ros | 5dc6e23a280e1283de7b38f35116332a79ca33d2 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 by Murray Altheim. All rights reserved. This file is part of
# the Robot OS project and is released under the "Apache Licence, Version 2.0".
# Please see the LICENSE file included as part of this package.
#
# author: altheim
# created: 2020-03-31
# modified: 2020-03-31
# Import library functions we need
import time
from colorama import init, Fore, Style
init()
try:
import numpy
except ImportError:
exit("This script requires the numpy module\nInstall with: sudo pip3 install numpy")
from lib.tof import TimeOfFlight, Range
from lib.enums import Orientation
from lib.servo import Servo
from lib.logger import Logger, Level
# ..............................................................................
class WallFollower():
def __init__(self, config, level):
self._log = Logger('follower', Level.INFO)
self._config = config
if self._config:
self._log.info('configuration provided.')
_config = self._config['ros'].get('wall_follower')
self._port_angle = _config.get('port_angle')
self._stbd_angle = _config.get('starboard_angle')
_range_value = _config.get('tof_range')
_range = Range.from_str(_range_value)
_servo_number = _config.get('servo_number')
else:
self._log.warning('no configuration provided.')
self._port_angle = -90.0
self._stbd_angle = 90.0
_range = Range.PERFORMANCE
_servo_number = 2
# _range = Range.LONG
# _range = Range.MEDIUM
# _range = Range.SHORT
self._log.info('wall follower port angle: {:>5.2f}°; starboard angle: {:>5.2f}°'.format(self._port_angle, self._stbd_angle))
self._servo = Servo(self._config, _servo_number, level)
self._tof = TimeOfFlight(_range, Level.WARN)
self._max_retries = 10
self._enabled = False
self._closed = False
self._log.info('ready.')
# ..........................................................................
def scan(self):
mm = 0.0
wait_count = 0
while mm <= 0.1 and wait_count < self._max_retries:
mm = self._tof.read_distance()
time.sleep(0.0025)
wait_count += 1
self._log.info('distance: {:>5.0f}mm'.format(mm))
return mm
# ..........................................................................
def set_position(self, orientation):
if not self._enabled:
self._log.warning('cannot scan: disabled.')
return
if orientation == Orientation.PORT:
self._servo.set_position(self._port_angle)
elif orientation == Orientation.STBD:
self._servo.set_position(self._stbd_angle)
else:
raise ValueError('only port or starboard acceptable for wall follower orientation')
self._log.info('wall follower position set to {}.'.format(orientation))
# ..........................................................................
def enable(self):
if self._closed:
self._log.warning('cannot enable: closed.')
return
self._tof.enable()
self._enabled = True
# ..........................................................................
def disable(self):
self._enabled = False
self._servo.set_position(0.0)
self._servo.disable()
self._tof.disable()
# ..........................................................................
def close(self):
self.disable()
self._servo.close()
self._closed = True
#EOF
| 33.603604 | 132 | 0.538606 |
import time
from colorama import init, Fore, Style
init()
try:
import numpy
except ImportError:
exit("This script requires the numpy module\nInstall with: sudo pip3 install numpy")
from lib.tof import TimeOfFlight, Range
from lib.enums import Orientation
from lib.servo import Servo
from lib.logger import Logger, Level
class WallFollower():
def __init__(self, config, level):
self._log = Logger('follower', Level.INFO)
self._config = config
if self._config:
self._log.info('configuration provided.')
_config = self._config['ros'].get('wall_follower')
self._port_angle = _config.get('port_angle')
self._stbd_angle = _config.get('starboard_angle')
_range_value = _config.get('tof_range')
_range = Range.from_str(_range_value)
_servo_number = _config.get('servo_number')
else:
self._log.warning('no configuration provided.')
self._port_angle = -90.0
self._stbd_angle = 90.0
_range = Range.PERFORMANCE
_servo_number = 2
self._log.info('wall follower port angle: {:>5.2f}°; starboard angle: {:>5.2f}°'.format(self._port_angle, self._stbd_angle))
self._servo = Servo(self._config, _servo_number, level)
self._tof = TimeOfFlight(_range, Level.WARN)
self._max_retries = 10
self._enabled = False
self._closed = False
self._log.info('ready.')
def scan(self):
mm = 0.0
wait_count = 0
while mm <= 0.1 and wait_count < self._max_retries:
mm = self._tof.read_distance()
time.sleep(0.0025)
wait_count += 1
self._log.info('distance: {:>5.0f}mm'.format(mm))
return mm
def set_position(self, orientation):
if not self._enabled:
self._log.warning('cannot scan: disabled.')
return
if orientation == Orientation.PORT:
self._servo.set_position(self._port_angle)
elif orientation == Orientation.STBD:
self._servo.set_position(self._stbd_angle)
else:
raise ValueError('only port or starboard acceptable for wall follower orientation')
self._log.info('wall follower position set to {}.'.format(orientation))
def enable(self):
if self._closed:
self._log.warning('cannot enable: closed.')
return
self._tof.enable()
self._enabled = True
def disable(self):
self._enabled = False
self._servo.set_position(0.0)
self._servo.disable()
self._tof.disable()
def close(self):
self.disable()
self._servo.close()
self._closed = True
| true | true |
f72c18024f079862885e04b1184e3b2d20a53ce4 | 312 | py | Python | src/Aula15ex67Tabuada.py | maberf/python | 0d36f1586c5f52081c2b27d42a1d37cee13116b0 | [
"MIT"
] | null | null | null | src/Aula15ex67Tabuada.py | maberf/python | 0d36f1586c5f52081c2b27d42a1d37cee13116b0 | [
"MIT"
] | null | null | null | src/Aula15ex67Tabuada.py | maberf/python | 0d36f1586c5f52081c2b27d42a1d37cee13116b0 | [
"MIT"
] | null | null | null | # TABUADA
#Mostra a tabuada de vários números, um de cada vez
#O programa encerra quando o número digitado é negativo
while True:
num = int(input('Número? '))
print('=' * 10)
if num < 0:
break
for i in range(1, 11):
print(f'{num} x {i} = {num * i}')
print('='*10)
print('Fim') | 26 | 55 | 0.580128 |
while True:
num = int(input('Número? '))
print('=' * 10)
if num < 0:
break
for i in range(1, 11):
print(f'{num} x {i} = {num * i}')
print('='*10)
print('Fim') | true | true |
f72c197e8fe4e17b1d25cf875d15b358ebf7e019 | 3,413 | py | Python | Dataproc/synth.py | Firehed/google-cloud-php | 5c49ed7a36c276fc59a9eaf9a03db4cd522b6932 | [
"Apache-2.0"
] | 1 | 2019-11-17T06:56:43.000Z | 2019-11-17T06:56:43.000Z | Dataproc/synth.py | Firehed/google-cloud-php | 5c49ed7a36c276fc59a9eaf9a03db4cd522b6932 | [
"Apache-2.0"
] | null | null | null | Dataproc/synth.py | Firehed/google-cloud-php | 5c49ed7a36c276fc59a9eaf9a03db4cd522b6932 | [
"Apache-2.0"
] | 1 | 2019-10-16T03:38:59.000Z | 2019-10-16T03:38:59.000Z | # Copyright 2018 Google LLC
#
# 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.
"""This script is used to synthesize generated parts of this library."""
import os
import synthtool as s
import synthtool.gcp as gcp
import logging
logging.basicConfig(level=logging.DEBUG)
gapic = gcp.GAPICGenerator()
common = gcp.CommonTemplates()
for version in ['V1', 'V1beta2']:
lower_version = version.lower()
library = gapic.php_library(
service='dataproc',
version=lower_version,
artman_output_name=f'google-cloud-dataproc-{lower_version}')
# copy all src including partial veneer classes
s.move(library / 'src')
# copy proto files to src also
s.move(library / 'proto/src/Google/Cloud/Dataproc', 'src/')
s.move(library / 'tests/')
# copy GPBMetadata file to metadata
s.move(library / 'proto/src/GPBMetadata/Google/Cloud/Dataproc', 'metadata/')
# Use new namespaces
s.replace(
f'src/{version}/Gapic/JobControllerGapicClient.php',
r'ListJobsRequest_JobStateMatcher',
r'ListJobsRequest\\JobStateMatcher')
# document and utilize apiEndpoint instead of serviceAddress
s.replace(
"**/Gapic/*GapicClient.php",
r"'serviceAddress' =>",
r"'apiEndpoint' =>")
s.replace(
"**/Gapic/*GapicClient.php",
r"@type string \$serviceAddress\n\s+\*\s+The address",
r"""@type string $serviceAddress
* **Deprecated**. This option will be removed in a future major release. Please
* utilize the `$apiEndpoint` option instead.
* @type string $apiEndpoint
* The address""")
s.replace(
"**/Gapic/*GapicClient.php",
r"\$transportConfig, and any \$serviceAddress",
r"$transportConfig, and any `$apiEndpoint`")
# prevent proto messages from being marked final
s.replace(
"src/V*/**/*.php",
r"final class",
r"class")
# Replace "Unwrapped" with "Value" for method names.
s.replace(
"src/V*/**/*.php",
r"public function ([s|g]\w{3,})Unwrapped",
r"public function \1Value"
)
# fix year
for client in ['ClusterController', 'JobController']:
s.replace(
f'**/V1/Gapic/{client}GapicClient.php',
r'Copyright \d{4}',
'Copyright 2017')
s.replace(
f'**/V1/{client}Client.php',
r'Copyright \d{4}',
'Copyright 2017')
s.replace(
'**/V1beta2/Gapic/*GapicClient.php',
r'Copyright \d{4}',
r'Copyright 2019')
s.replace(
'**/V1beta2/*Client.php',
r'Copyright \d{4}',
r'Copyright 2019')
s.replace(
'**/V1/Gapic/WorkflowTemplateServiceGapicClient.php',
r'Copyright \d{4}',
'Copyright 2018')
s.replace(
'**/V1/WorkflowTemplateServiceClient.php',
r'Copyright \d{4}',
'Copyright 2018')
s.replace(
'tests/**/V1/*Test.php',
r'Copyright \d{4}',
'Copyright 2018')
s.replace(
'tests/**/V1beta2/*Test.php',
r'Copyright \d{4}',
'Copyright 2019')
| 29.17094 | 94 | 0.658951 |
import os
import synthtool as s
import synthtool.gcp as gcp
import logging
logging.basicConfig(level=logging.DEBUG)
gapic = gcp.GAPICGenerator()
common = gcp.CommonTemplates()
for version in ['V1', 'V1beta2']:
lower_version = version.lower()
library = gapic.php_library(
service='dataproc',
version=lower_version,
artman_output_name=f'google-cloud-dataproc-{lower_version}')
s.move(library / 'src')
s.move(library / 'proto/src/Google/Cloud/Dataproc', 'src/')
s.move(library / 'tests/')
s.move(library / 'proto/src/GPBMetadata/Google/Cloud/Dataproc', 'metadata/')
s.replace(
f'src/{version}/Gapic/JobControllerGapicClient.php',
r'ListJobsRequest_JobStateMatcher',
r'ListJobsRequest\\JobStateMatcher')
s.replace(
"**/Gapic/*GapicClient.php",
r"'serviceAddress' =>",
r"'apiEndpoint' =>")
s.replace(
"**/Gapic/*GapicClient.php",
r"@type string \$serviceAddress\n\s+\*\s+The address",
r"""@type string $serviceAddress
* **Deprecated**. This option will be removed in a future major release. Please
* utilize the `$apiEndpoint` option instead.
* @type string $apiEndpoint
* The address""")
s.replace(
"**/Gapic/*GapicClient.php",
r"\$transportConfig, and any \$serviceAddress",
r"$transportConfig, and any `$apiEndpoint`")
s.replace(
"src/V*/**/*.php",
r"final class",
r"class")
s.replace(
"src/V*/**/*.php",
r"public function ([s|g]\w{3,})Unwrapped",
r"public function \1Value"
)
for client in ['ClusterController', 'JobController']:
s.replace(
f'**/V1/Gapic/{client}GapicClient.php',
r'Copyright \d{4}',
'Copyright 2017')
s.replace(
f'**/V1/{client}Client.php',
r'Copyright \d{4}',
'Copyright 2017')
s.replace(
'**/V1beta2/Gapic/*GapicClient.php',
r'Copyright \d{4}',
r'Copyright 2019')
s.replace(
'**/V1beta2/*Client.php',
r'Copyright \d{4}',
r'Copyright 2019')
s.replace(
'**/V1/Gapic/WorkflowTemplateServiceGapicClient.php',
r'Copyright \d{4}',
'Copyright 2018')
s.replace(
'**/V1/WorkflowTemplateServiceClient.php',
r'Copyright \d{4}',
'Copyright 2018')
s.replace(
'tests/**/V1/*Test.php',
r'Copyright \d{4}',
'Copyright 2018')
s.replace(
'tests/**/V1beta2/*Test.php',
r'Copyright \d{4}',
'Copyright 2019')
| true | true |
f72c198a930ed3f71634b2475161d1817b4821ff | 12,725 | py | Python | simulacionPlanificador.py | inakiuy/teoria-de-la-computacion | e9087e70622a72b8ddd44a3552f13c0e1794587d | [
"MIT"
] | null | null | null | simulacionPlanificador.py | inakiuy/teoria-de-la-computacion | e9087e70622a72b8ddd44a3552f13c0e1794587d | [
"MIT"
] | null | null | null | simulacionPlanificador.py | inakiuy/teoria-de-la-computacion | e9087e70622a72b8ddd44a3552f13c0e1794587d | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
from collections import deque
import random
SETS = 3 # Cantidad de sets generados
TASKS_CREATED = 10 # Cantidad de tareas creadas por cada set
MAX_SERVICETIME = 100 # Maximo Tiempo de Servicio de una tarea. 28800 = 8h
MAX_SERVICELIST_SIZE = 4 # Maxima canitad de particiones realizadas al tiempo de servicio
MAX_TIMEOUT = 150 # Maximo Tiempo de Timeout de una tarea
DIA_TRABAJO = 300 # Cuantos ciclos dura un dia de trabajo
MAX_TIME = 3000 # Cuantos ciclos dura la simulacion. SETS * TASKS_CREATED * MAX_SERVICETIME = 2880000
ALGO = "fcfs" # Algoritmo de planificacion FirstComeFirstServe
#ALGO = "sjf" # Algoritmo de planificacion ShortesJobFirst
INTERVALO_LOG = 1500 # Cada cuantos ciclos imprimir log.
class Tarea:
""" Clase tarea """
### Constructor
def __init__(self, pname, pserviceTime, ppriority, purgency, ptimeOut, ptaskType):
# Propiedades basicas
self.name = pname
self.serviceTime = pserviceTime
self.serviceList = Tarea.randomServiceList(pserviceTime)
self.priority = int(ppriority * purgency)
self.timeOut = ptimeOut
self.taskType = ptaskType
# Propiedades estadisticas
self.startTime = None
self.finishTime = None
self.waitingTime = 0
self.workDone = 0
self.waitingQueueArriveTime = None
self.serviceListCopy = self.serviceList.copy()
### Particiona de forma aleatoria un tiempo de servicio
### para simular tareas que necesitan espera
def randomServiceList(pserviceTime):
list_size = random.randrange(1,MAX_SERVICELIST_SIZE)
lista = deque(maxlen=list_size)
position = 0
# print(f'Tamanio lista: {list_size}')
for i in range(list_size - 1 ):
partition = random.randrange(position, pserviceTime)
# print(f'Loop: {i}, Posicion: {position}, Particion: {partition}, PserviceTime: {pserviceTime}')
time = partition - position
if (time != 0):
lista.append(time)
position = partition
lista.append(pserviceTime - position)
# print(f'Ver lista: {lista}')
return lista
### Generador de tareas aleatorias
def createRandomList(n_val, setNumber):
task_list = []
for n in range(n_val):
name = n + (TASKS_CREATED * setNumber)
serviceTime = random.randint(1,MAX_SERVICETIME)
priority = random.randint(0,5)
urgency = random.random() # random entre 0 y 1
timeout = random.randint(1,MAX_TIMEOUT) # Si no se ejecuta se da por no completada
tasktype = random.randrange(0,5) # Simulamos 5 tipos de tareas
task = Tarea(name, serviceTime, priority, urgency, timeout, tasktype)
task_list.append(task)
#print("Set de tareas generado correctamente")
return task_list
### Imprime estadisticas de forma legible
def prettyStats(self):
print(f'Tarea: {self.name}\n\tstart: {self.startTime}\n\tfinish: {self.finishTime}\n\twaiting: {self.waitingTime}\n\twork: {self.workDone}\n\tserviceList: {list(self.serviceListCopy)}')
### Imprime estadisticas crudas
def rawStats(self):
print(f'{self.name};{self.startTime};{self.finishTime};{self.waitingTime};{self.workDone};{list(self.serviceListCopy)}')
### Representacion de la tarea como string
def __repr__(self):
return f'\n{{name: {self.name}, time: {self.serviceTime}, serviceList: {list(self.serviceList)}, startTime: {self.startTime}, finishTime: {self.finishTime}, waitingTime: {self.waitingTime}, workDone: {self.workDone}, serviceListCopy: {list(self.serviceListCopy)}}}\n'
#return f'\n{{name: {self.name}, time: {self.serviceTime}, serviceList: {list(self.serviceList)}, priority: {self.priority}, timeout: {self.timeOut}, tasktype: {self.taskType}}}\n'
class Planificador:
""" Cola de tareas """
### Constructor
def __init__(self, ALGO):
self.algorithm = ALGO
self.planQueue = deque(maxlen=TASKS_CREATED * SETS)
self.waitingQueue = deque(maxlen=TASKS_CREATED * SETS)
self.finishedQueue = deque(maxlen=TASKS_CREATED * SETS)
### Poner una tarea en la cola de planificacion
def putTaskPlanQueue(self, task):
if (self.algorithm == "fcfs"):
# FCFS
self.fcfs(task)
elif (self.algorithm == "sjf"):
# SJF
self.sjf(task)
else:
raise Exception("Planificador no selecionado. Revise la constante ALGO")
# print(f'Tarea agregada: {task}')
### Entregar una tarea al usuario dede la cola de planificados
def getTaskPlanQueue(self):
return self.planQueue.popleft() if (self.planQueue) else None
### Poner una tarea en la cola de espera
def putTaskWaitingQueue(self, task, time):
task.waitingQueueArriveTime = time
self.waitingQueue.append(task)
return 0
### Eliminar una determinada tarea en la cola de espera
def removeTaskWaitingQueue(self, task):
self.waitingQueue.remove(task)
return 0
### Poner una tarea en la cola de finalizados
def putTaskFinishedQueue(self, task, time):
task.finishTime = time
self.finishedQueue.append(task)
return 0
### Imprimir todas las tareas en la cola
def printTasks(self):
print(f'Cola de tareas: {list(self.planQueue)}')
return 0
### Agregar tareas a la cola de planificacion
def addTasks(self, taskList, time):
for task in taskList:
task.startTime = time
self.putTaskPlanQueue(task)
return 0
### Algoritmo FCFS
def fcfs(self, task):
self.planQueue.append(task)
### Algoritmo SJF
def sjf(self, task):
serviceTime = task.serviceTime
queueList = list(self.planQueue)
i = 0
try:
while (queueList[i].serviceTime < serviceTime):
i += 1
self.planQueue.insert(i, task)
except:
self.planQueue.append(task)
# Replanificardor: Avanza el tiempo en 1 y las tareas que yas terminaron
# de esperar las mueve a la cola planQueue
def schedule(self, time):
#Necesaria por que no puedo modificar las colas mientras itero sobre ellas
tempList = []
# Si hay tareas esperando que ya cumplieron el tiempo de espera
# y que tienen ciclos de trabajo pendientes, pasarlas nuevamente
# a la cola de planificación
if (self.waitingQueue): # Si no esta vacia
for tarea in self.waitingQueue:
if (tarea.serviceList): # Si aun le quedan operaciones por hacer
timeWaited = time - tarea.waitingQueueArriveTime
timeToWait = tarea.serviceList[0]
if (timeWaited >= timeToWait):
tarea.serviceList.popleft()
if (tarea.serviceList): # Si le quedan operaciones
# Pasa a planificado
#print("Tiene operaciones, pasa a planificador")
tempList.append(tarea)
self.putTaskPlanQueue(tarea)
else:
# Pasa a finalizado
tempList.append(tarea)
#print("Ya no tiene operaciones, pasa a finalizado")
self.putTaskFinishedQueue(tarea, time)
else:
print('No debería estar aca')
# Elimino las tareas de la cola de espera
for tarea in tempList:
self.removeTaskWaitingQueue(tarea)
# A todas las tareas que están planificadas y no se avanzaron
# sumarle al waitingTime para estadisticas
if (self.planQueue):
for tarea in self.planQueue:
tarea.waitingTime += 1
### Imprimir estadisticas de la tareas
### Por omision imprime "pretty" legible para humanos
### poner raw en true devuelve lista separada por ";"
def printStatistics(self, raw):
print(f'\nCOLA TAREAS PLANIFICADAS')
if raw:
print(f'name;startTime;finishTime;waitingTime;workDone;serviceListCopy;')
if (self.planQueue):
for tarea in self.planQueue:
tarea.rawStats() if (raw) else tarea.prettyStats()
else:
print(f'No quedaron tareas en esta cola')
print(f'\nCOLA TAREAS ESPERANDO')
if raw:
print(f'name;startTime;finishTime;waitingTime;workDone;serviceListCopy;')
if (self.waitingQueue):
for tarea in self.waitingQueue:
tarea.rawStats() if (raw) else tarea.prettyStats()
else:
print(f'No quedaron tareas en esta cola')
print(f'\nCOLA TAREAS FINALIZADAS')
if raw:
print(f'name;startTime;finishTime;waitingTime;workDone;serviceListCopy;')
if (self.finishedQueue):
for tarea in self.finishedQueue:
tarea.rawStats() if (raw) else tarea.prettyStats()
else:
print(f'No quedaron tareas en esta cola')
class Persona:
""" Clase Persona que realiza trabajos """
# Constructor
def __init__(self, pname):
self.name = pname
self.task = None
# Realizar tarea
def work(self):
self.task.workDone += 1
def main():
""" Tests de planificación """
print(f'=== TESTS DE PLANIFICADOR {ALGO} ===')
print(f'Generamos {SETS} sets de pruebas')
setsTareas = deque()
for i in range(SETS):
setsTareas.append(Tarea.createRandomList(TASKS_CREATED, i))
planFCFS = Planificador(ALGO)
planFCFS.addTasks(setsTareas.popleft(), 0)
planFCFS.printTasks()
trabajador = Persona("Trabajador 1")
tarea = planFCFS.getTaskPlanQueue()
trabajador.task = tarea
workToBeDone = tarea.serviceList.popleft()
# SIMULACION DE TIEMPO
for time in range(MAX_TIME):
# Si paso 1 dia, agregamos mas tareas
if ( time != 0 and time % DIA_TRABAJO == 0 and setsTareas):
print(f'\n********************* NUEVO DIA: {time} *************************')
planFCFS.addTasks(setsTareas.popleft(), time)
# Imprimimos avance cada cierto intervalo
if ( time % INTERVALO_LOG == 0):
print(f'\n///////////////////////////////// Tiempo: {time} /////////////////////////////////')
print(f'Trabajador trabajando en: {trabajador.task}')
if (trabajador.task != None):
# Teniendo una tarea asignada
if ( tarea.workDone < workToBeDone ): # Si el trabajo realizado es menor al necesario, trabajar
trabajador.work()
elif (not tarea.serviceList): # Si en la lista de trabajo NO hay trabajo, pasa a cola de finalizado
trabajador.task = None
planFCFS.putTaskFinishedQueue(tarea, time)
else:
trabajador.task = None
planFCFS.putTaskWaitingQueue(tarea, time)
# Si no estamos trabajando en una tarea y aun quedan tareas
# en la cola de planQueue obtener una
if (trabajador.task == None and planFCFS.planQueue):
tarea = planFCFS.getTaskPlanQueue()
trabajador.task = tarea
workToBeDone = tarea.serviceList.popleft()
trabajador.work()
# Vemos el estado de las colas cada 100 tick del reloj
if ( time % INTERVALO_LOG == 0 ):
print(f'FinCiclo-PlanQ: {planFCFS.planQueue}\n-------------------------')
print(f'FinCiclo-WaitQ: {planFCFS.waitingQueue}\n-------------------------')
print(f'FinCiclo-FiniQ: {planFCFS.finishedQueue}\n-------------------------')
# Reprogramamos tareas
planFCFS.schedule(time)
print(f'\n--------------- FIN DEL TIEMPO SIMULADO ---------------')
print(f'FIN-PlanQ: {planFCFS.planQueue}\n-------------------------')
print(f'FIN-WaitQ: {planFCFS.waitingQueue}\n-------------------------')
print(f'FIN-FiniQ: {planFCFS.finishedQueue}\n-------------------------')
print(f'\n--------------- ESTADISTICAS PRETTY ---------------')
planFCFS.printStatistics(raw=False)
print(f'\n--------------- ESTADISTICAS RAW ---------------')
planFCFS.printStatistics(raw=True)
if __name__ == "__main__":
""" This is executed when run from the command line """
main() | 40.015723 | 275 | 0.595521 |
from collections import deque
import random
SETS = 3
TASKS_CREATED = 10
MAX_SERVICETIME = 100
MAX_SERVICELIST_SIZE = 4
MAX_TIMEOUT = 150
DIA_TRABAJO = 300
MAX_TIME = 3000
ALGO = "fcfs"
me, pserviceTime, ppriority, purgency, ptimeOut, ptaskType):
self.name = pname
self.serviceTime = pserviceTime
self.serviceList = Tarea.randomServiceList(pserviceTime)
self.priority = int(ppriority * purgency)
self.timeOut = ptimeOut
self.taskType = ptaskType
self.startTime = None
self.finishTime = None
self.waitingTime = 0
self.workDone = 0
self.waitingQueueArriveTime = None
self.serviceListCopy = self.serviceList.copy()
for i in range(list_size - 1 ):
partition = random.randrange(position, pserviceTime)
time = partition - position
if (time != 0):
lista.append(time)
position = partition
lista.append(pserviceTime - position)
return lista
[]
for n in range(n_val):
name = n + (TASKS_CREATED * setNumber)
serviceTime = random.randint(1,MAX_SERVICETIME)
priority = random.randint(0,5)
urgency = random.random()
timeout = random.randint(1,MAX_TIMEOUT)
tasktype = random.randrange(0,5)
task = Tarea(name, serviceTime, priority, urgency, timeout, tasktype)
task_list.append(task)
return task_list
startTime}\n\tfinish: {self.finishTime}\n\twaiting: {self.waitingTime}\n\twork: {self.workDone}\n\tserviceList: {list(self.serviceListCopy)}')
startTime};{self.finishTime};{self.waitingTime};{self.workDone};{list(self.serviceListCopy)}')
iceTime}, serviceList: {list(self.serviceList)}, startTime: {self.startTime}, finishTime: {self.finishTime}, waitingTime: {self.waitingTime}, workDone: {self.workDone}, serviceListCopy: {list(self.serviceListCopy)}}}\n'
class Planificador:
O):
self.algorithm = ALGO
self.planQueue = deque(maxlen=TASKS_CREATED * SETS)
self.waitingQueue = deque(maxlen=TASKS_CREATED * SETS)
self.finishedQueue = deque(maxlen=TASKS_CREATED * SETS)
self.fcfs(task)
elif (self.algorithm == "sjf"):
self.sjf(task)
else:
raise Exception("Planificador no selecionado. Revise la constante ALGO")
self.waitingQueue.append(task)
return 0
self.finishedQueue.append(task)
return 0
ue)}')
return 0
.startTime = time
self.putTaskPlanQueue(task)
return 0
self.planQueue.append(task)
serviceTime = task.serviceTime
queueList = list(self.planQueue)
i = 0
try:
while (queueList[i].serviceTime < serviceTime):
i += 1
self.planQueue.insert(i, task)
except:
self.planQueue.append(task)
def schedule(self, time):
tempList = []
if (self.waitingQueue):
for tarea in self.waitingQueue:
if (tarea.serviceList):
timeWaited = time - tarea.waitingQueueArriveTime
timeToWait = tarea.serviceList[0]
if (timeWaited >= timeToWait):
tarea.serviceList.popleft()
if (tarea.serviceList):
tempList.append(tarea)
self.putTaskPlanQueue(tarea)
else:
tempList.append(tarea)
self.putTaskFinishedQueue(tarea, time)
else:
print('No debería estar aca')
for tarea in tempList:
self.removeTaskWaitingQueue(tarea)
if (self.planQueue):
for tarea in self.planQueue:
tarea.waitingTime += 1
tarea.rawStats() if (raw) else tarea.prettyStats()
else:
print(f'No quedaron tareas en esta cola')
print(f'\nCOLA TAREAS ESPERANDO')
if raw:
print(f'name;startTime;finishTime;waitingTime;workDone;serviceListCopy;')
if (self.waitingQueue):
for tarea in self.waitingQueue:
tarea.rawStats() if (raw) else tarea.prettyStats()
else:
print(f'No quedaron tareas en esta cola')
print(f'\nCOLA TAREAS FINALIZADAS')
if raw:
print(f'name;startTime;finishTime;waitingTime;workDone;serviceListCopy;')
if (self.finishedQueue):
for tarea in self.finishedQueue:
tarea.rawStats() if (raw) else tarea.prettyStats()
else:
print(f'No quedaron tareas en esta cola')
class Persona:
def __init__(self, pname):
self.name = pname
self.task = None
def work(self):
self.task.workDone += 1
def main():
print(f'=== TESTS DE PLANIFICADOR {ALGO} ===')
print(f'Generamos {SETS} sets de pruebas')
setsTareas = deque()
for i in range(SETS):
setsTareas.append(Tarea.createRandomList(TASKS_CREATED, i))
planFCFS = Planificador(ALGO)
planFCFS.addTasks(setsTareas.popleft(), 0)
planFCFS.printTasks()
trabajador = Persona("Trabajador 1")
tarea = planFCFS.getTaskPlanQueue()
trabajador.task = tarea
workToBeDone = tarea.serviceList.popleft()
for time in range(MAX_TIME):
if ( time != 0 and time % DIA_TRABAJO == 0 and setsTareas):
print(f'\n********************* NUEVO DIA: {time} *************************')
planFCFS.addTasks(setsTareas.popleft(), time)
if ( time % INTERVALO_LOG == 0):
print(f'\n///////////////////////////////// Tiempo: {time} /////////////////////////////////')
print(f'Trabajador trabajando en: {trabajador.task}')
if (trabajador.task != None):
if ( tarea.workDone < workToBeDone ):
trabajador.work()
elif (not tarea.serviceList):
trabajador.task = None
planFCFS.putTaskFinishedQueue(tarea, time)
else:
trabajador.task = None
planFCFS.putTaskWaitingQueue(tarea, time)
if (trabajador.task == None and planFCFS.planQueue):
tarea = planFCFS.getTaskPlanQueue()
trabajador.task = tarea
workToBeDone = tarea.serviceList.popleft()
trabajador.work()
if ( time % INTERVALO_LOG == 0 ):
print(f'FinCiclo-PlanQ: {planFCFS.planQueue}\n-------------------------')
print(f'FinCiclo-WaitQ: {planFCFS.waitingQueue}\n-------------------------')
print(f'FinCiclo-FiniQ: {planFCFS.finishedQueue}\n-------------------------')
planFCFS.schedule(time)
print(f'\n--------------- FIN DEL TIEMPO SIMULADO ---------------')
print(f'FIN-PlanQ: {planFCFS.planQueue}\n-------------------------')
print(f'FIN-WaitQ: {planFCFS.waitingQueue}\n-------------------------')
print(f'FIN-FiniQ: {planFCFS.finishedQueue}\n-------------------------')
print(f'\n--------------- ESTADISTICAS PRETTY ---------------')
planFCFS.printStatistics(raw=False)
print(f'\n--------------- ESTADISTICAS RAW ---------------')
planFCFS.printStatistics(raw=True)
if __name__ == "__main__":
main() | true | true |
f72c19b9cb3d05c83471ebe6d0f7ab647fcf3c80 | 5,478 | py | Python | saas/api/backend.py | markcstansberry/djaodjin-saas | 0749dac36c3b039334fe9f115d92b3167eea03d6 | [
"BSD-2-Clause"
] | null | null | null | saas/api/backend.py | markcstansberry/djaodjin-saas | 0749dac36c3b039334fe9f115d92b3167eea03d6 | [
"BSD-2-Clause"
] | 4 | 2021-04-08T21:56:58.000Z | 2022-02-10T13:26:56.000Z | saas/api/backend.py | markcstansberry/djaodjin-saas | 0749dac36c3b039334fe9f115d92b3167eea03d6 | [
"BSD-2-Clause"
] | null | null | null | # Copyright (c) 2019, DjaoDjin inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pylint:disable=useless-super-delegation
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.generics import (RetrieveAPIView,
RetrieveUpdateDestroyAPIView)
from rest_framework.response import Response
from ..backends import ProcessorError
from ..docs import swagger_auto_schema
from ..mixins import OrganizationMixin
from .serializers import (BankSerializer, CardSerializer,
CardTokenSerializer)
#pylint: disable=no-init
class RetrieveBankAPIView(OrganizationMixin, RetrieveAPIView):
"""
Retrieves a payout account
Pass through that calls the processor API to retrieve some details about
the deposit account associated to a provider (if that information is
available through the :doc:`payment processor backend<backends>` API).
This API does not trigger payment of a subscriber to a provider. Checkout
of a subscription cart is done either through the
:ref:`HTML page<pages_cart>` or :ref:`API end point<api_checkout>`.
**Tags**: billing
**Examples**
.. code-block:: http
GET /api/billing/cowork/bank/ HTTP/1.1
responds
.. code-block:: json
{
"bank_name": "Stripe Test Bank",
"last4": "***-htrTZ",
"balance_amount": 0,
"balance_unit": "usd"
}
"""
serializer_class = BankSerializer
def retrieve(self, request, *args, **kwargs):
#pylint: disable=unused-argument
return Response(
self.organization.retrieve_bank())
class PaymentMethodDetailAPIView(OrganizationMixin,
RetrieveUpdateDestroyAPIView):
"""
Retrieves a payment method
Pass through to the processor to retrieve some details about
the payment method (ex: credit card) associated to a subscriber.
**Tags**: billing
**Examples**
.. code-block:: http
GET /api/billing/cowork/card/ HTTP/1.1
responds
.. code-block:: json
{
"last4": "1234",
"exp_date": "12/2019"
}
"""
serializer_class = CardSerializer
def delete(self, request, *args, **kwargs):
"""
Deletes a payment method
Pass through to the processor to remove the payment method (ex: credit
card) associated to a subscriber.
**Tags**: billing
**Examples**
.. code-block:: http
DELETE /api/billing/cowork/card/ HTTP/1.1
"""
return super(PaymentMethodDetailAPIView, self).delete(
request, *args, **kwargs)
@swagger_auto_schema(request_body=CardTokenSerializer)
def put(self, request, *args, **kwargs):
"""
Updates a payment method
Pass through to the processor to update some details about
the payment method (ex: credit card) associated to a subscriber.
**Tags**: billing
**Examples**
.. code-block:: http
PUT /api/billing/cowork/card/ HTTP/1.1
.. code-block:: json
{
"token": "xyz"
}
responds
.. code-block:: json
{
"last4": "1234",
"exp_date": "12/2019"
}
"""
return super(PaymentMethodDetailAPIView, self).put(
request, *args, **kwargs)
def destroy(self, request, *args, **kwargs):
self.organization.delete_card()
return Response(status=status.HTTP_204_NO_CONTENT)
def retrieve(self, request, *args, **kwargs):
#pylint: disable=unused-argument
return Response(self.organization.retrieve_card())
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
serializer = CardTokenSerializer(data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
token = serializer.validated_data['token']
try:
self.organization.update_card(token, self.request.user)
except ProcessorError as err:
raise ValidationError(err)
return self.retrieve(request, *args, **kwargs)
| 30.949153 | 78 | 0.667579 |
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.generics import (RetrieveAPIView,
RetrieveUpdateDestroyAPIView)
from rest_framework.response import Response
from ..backends import ProcessorError
from ..docs import swagger_auto_schema
from ..mixins import OrganizationMixin
from .serializers import (BankSerializer, CardSerializer,
CardTokenSerializer)
class RetrieveBankAPIView(OrganizationMixin, RetrieveAPIView):
serializer_class = BankSerializer
def retrieve(self, request, *args, **kwargs):
return Response(
self.organization.retrieve_bank())
class PaymentMethodDetailAPIView(OrganizationMixin,
RetrieveUpdateDestroyAPIView):
serializer_class = CardSerializer
def delete(self, request, *args, **kwargs):
return super(PaymentMethodDetailAPIView, self).delete(
request, *args, **kwargs)
@swagger_auto_schema(request_body=CardTokenSerializer)
def put(self, request, *args, **kwargs):
return super(PaymentMethodDetailAPIView, self).put(
request, *args, **kwargs)
def destroy(self, request, *args, **kwargs):
self.organization.delete_card()
return Response(status=status.HTTP_204_NO_CONTENT)
def retrieve(self, request, *args, **kwargs):
return Response(self.organization.retrieve_card())
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
serializer = CardTokenSerializer(data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
token = serializer.validated_data['token']
try:
self.organization.update_card(token, self.request.user)
except ProcessorError as err:
raise ValidationError(err)
return self.retrieve(request, *args, **kwargs)
| true | true |
f72c1a54af7f21cf6b27146291cd2fe43fcaa17f | 11,489 | py | Python | src/maggma/api/query_operator.py | wuxiaohua1011/maggma | b7a059b2d12d9b96aa2092c40eb41f121c0a598b | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/maggma/api/query_operator.py | wuxiaohua1011/maggma | b7a059b2d12d9b96aa2092c40eb41f121c0a598b | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/maggma/api/query_operator.py | wuxiaohua1011/maggma | b7a059b2d12d9b96aa2092c40eb41f121c0a598b | [
"BSD-3-Clause-LBNL"
] | null | null | null | from typing import List, Dict, Optional, Any, Mapping
from pydantic import BaseModel
from fastapi import Query
from monty.json import MSONable
from maggma.core import Store
from maggma.api.util import STORE_PARAMS, dynamic_import
from pydantic.fields import ModelField
import inspect
import warnings
class QueryOperator(MSONable):
"""
Base Query Operator class for defining powerfull query language
in the Materials API
"""
def query(self) -> STORE_PARAMS:
"""
The query function that does the work for this query operator
"""
raise NotImplementedError("Query operators must implement query")
def meta(self, store: Store, query: Dict) -> Dict:
"""
Returns meta data to return with the Response
Args:
store: the Maggma Store that the resource uses
query: the query being executed in this API call
"""
return {}
def post_process(self, doc: Dict) -> Dict:
"""
An optional post-processing function for the data
"""
return doc
class PaginationQuery(QueryOperator):
"""Query opertators to provides Pagination in the Materials API"""
def __init__(
self, default_skip: int = 0, default_limit: int = 10, max_limit: int = 100
):
"""
Args:
default_skip: the default number of documents to skip
default_limit: the default number of documents to return
max_limit: max number of documents to return
"""
self.default_skip = default_skip
self.default_limit = default_limit
self.max_limit = max_limit
def query(
skip: int = Query(
default_skip, description="Number of entries to skip in the search"
),
limit: int = Query(
default_limit,
description="Max number of entries to return in a single query."
f" Limited to {max_limit}",
),
) -> STORE_PARAMS:
"""
Pagination parameters for the API Endpoint
"""
if limit > max_limit:
raise Exception(
"Requested more data per query than allowed by this endpoint."
f"The max limit is {max_limit} entries"
)
return {"skip": skip, "limit": limit}
self.query = query # type: ignore
def meta(self, store: Store, query: Dict) -> Dict:
"""
Metadata for the pagination params
"""
return {"max_limit": self.max_limit}
class SparseFieldsQuery(QueryOperator):
def __init__(self, model: BaseModel, default_fields: Optional[List[str]] = None):
"""
Args:
model: PyDantic Model that represents the underlying data source
default_fields: default fields to return in the API response if no fields are explicitly requested
"""
self.model = model
model_fields = list(self.model.__fields__.keys())
self.default_fields = (
model_fields if default_fields is None else list(default_fields)
)
assert set(self.default_fields).issubset(
model_fields
), "default projection contains some fields that are not in the model fields"
default_fields_string = ",".join(self.default_fields) # type: ignore
def query(
fields: str = Query(
default_fields_string,
description=f"Fields to project from {model.__name__} " # type: ignore
f"as a list of comma seperated strings",
),
all_fields: bool = Query(False, description="Include all fields."),
) -> STORE_PARAMS:
"""
Projection parameters for the API Endpoint
"""
projection_fields: List[str] = [s.strip() for s in fields.split(",")]
# need to strip to avoid input such as "name, weight" to be parsed into ["name", " weight"]
# we need ["name", "weight"]
if all_fields:
projection_fields = model_fields
return {"properties": projection_fields}
self.query = query # type: ignore
"""
Factory function to generate a dependency for sparse field sets in FastAPI
"""
def meta(self, store: Store, query: Dict) -> Dict:
"""
Returns metadata for the Sparse field set
"""
return {"default_fields": self.default_fields}
def as_dict(self) -> Dict:
"""
Special as_dict implemented to convert pydantic models into strings
"""
d = super().as_dict() # Ensures sub-classes serialize correctly
d["model"] = f"{self.model.__module__}.{self.model.__name__}" # type: ignore
return d
@classmethod
def from_dict(cls, d):
"""
Special from_dict to autoload the pydantic model from the location string
"""
model = d.get("model")
if isinstance(model, str):
module_path = ".".join(model.split(".")[:-1])
class_name = model.split(".")[-1]
model = dynamic_import(module_path, class_name)
assert issubclass(
model, BaseModel
), "The resource model has to be a PyDantic Model"
d["model"] = model
cls(**d)
class DefaultDynamicQuery(QueryOperator):
def __init__(
self, model: BaseModel, additional_signature_fields: Mapping[str, List] = None,
):
"""
This function will take query, parse it, and output the mongo criteria.
About the query:
The format of the input query will come from two sources: the data model (which we will sometimes refer to as
default values, and the additional paremeters that users can choose to pass in)
additional_signature_field must be int the shape of NAME_OF_THE_QUERY -> [DEFAULT_VALUE, QUERY]
where QUERY is a FastAPI params.Query object
About how does this script parse the query:
it will first generate default queries from input data model
Then it will merge with the optional additional_signature_fields
About mongo criteria output:
current implementation only supports 6 operations, namely equal, not equal, less than, greater than, in,
and not in. Therefore, the criteria output will be also limited to those operations.
Args:
model: PyDantic Model to base the query language on
additional_signature_fields: mapping of NAME_OF_THE_FIELD -> [DEFAULT_VALUE, QUERY]
"""
self.model = model
default_mapping = {
"eq": "$eq",
"not_eq": "$ne",
"lt": "$lt",
"gt": "$gt",
"in": "$in",
"not_in": "$nin",
}
mapping: dict = default_mapping
self.additional_signature_fields: Mapping[
str, List
] = dict() if additional_signature_fields is None else additional_signature_fields
# construct fields
# find all fields in data_object
all_fields: Dict[str, ModelField] = model.__fields__
# turn fields into operators, also do type checking
params = self.fields_to_operator(all_fields)
# combine with additional_fields
# user's input always have higher priority than the the default data model's
params.update(self.additional_signature_fields)
def query(**kwargs) -> STORE_PARAMS:
crit = dict()
for k, v in kwargs.items():
if v is not None:
if "_" not in k:
k = k + "_eq"
name, operator = k.split("_", 1)
try:
crit[name] = {mapping[operator]: v}
except KeyError:
raise KeyError(
f"Cannot find key {k} in current query to database mapping"
)
return {"criteria": crit}
# building the signatures for FastAPI Swagger UI
signatures: List[Any] = []
signatures.extend(
inspect.Parameter(
param,
inspect.Parameter.POSITIONAL_OR_KEYWORD,
default=query[1],
annotation=query[0],
)
for param, query in params.items()
)
setattr(query, "__signature__", inspect.Signature(signatures))
self.query = query # type: ignore
def fields_to_operator(self, all_fields: Dict[str, ModelField]) -> Dict[str, list]:
"""
Getting a list of tuple of fields
turn them into a mapping of
FIELD_[operator] -> query
Args:
all_fields: dictionary of str -> ModelField
Returns:
a dictionary of FIELD_[operator] -> query
"""
params = dict()
for name, model_field in all_fields.items():
if model_field.type_ in [str, int, float]:
t: Any = model_field.type_
name = model_field.name
params[f"{name}"] = [
t,
Query(
default=model_field.default,
description=f"Querying if {model_field.name} is equal to another",
),
] # supporting both with and with out explicit _eq
params[f"{name}_eq"] = [
t,
Query(
default=model_field.default,
description=f"Querying if {model_field.name} is equal to another",
),
]
params[f"{name}_not_eq"] = [
t,
Query(
default=model_field.default,
description=f"Querying if {model_field.name} is not equal to another",
),
]
params[f"{name}_in"] = [
List[t],
Query(
default=model_field.default,
description=f"Querying if item is in {model_field.name}",
),
]
params[f"{name}_not_in"] = [
List[t],
Query(
default=model_field.default,
description=f"Querying if item is not in {model_field.name} ",
),
]
if model_field.type_ == int or model_field == float:
params[f"{name}_lt"] = [
model_field.type_,
Query(
model_field.default,
description=f"Querying if {model_field.name} is less than to another",
),
]
params[f"{name}_gt"] = [
model_field.type_,
Query(
model_field.default,
description=f"Querying if {model_field.name} is greater than to another",
),
]
else:
warnings.warn(
f"Field name {name} with {model_field.type_} not implemented"
)
return params
| 35.242331 | 117 | 0.542606 | from typing import List, Dict, Optional, Any, Mapping
from pydantic import BaseModel
from fastapi import Query
from monty.json import MSONable
from maggma.core import Store
from maggma.api.util import STORE_PARAMS, dynamic_import
from pydantic.fields import ModelField
import inspect
import warnings
class QueryOperator(MSONable):
def query(self) -> STORE_PARAMS:
raise NotImplementedError("Query operators must implement query")
def meta(self, store: Store, query: Dict) -> Dict:
return {}
def post_process(self, doc: Dict) -> Dict:
return doc
class PaginationQuery(QueryOperator):
def __init__(
self, default_skip: int = 0, default_limit: int = 10, max_limit: int = 100
):
self.default_skip = default_skip
self.default_limit = default_limit
self.max_limit = max_limit
def query(
skip: int = Query(
default_skip, description="Number of entries to skip in the search"
),
limit: int = Query(
default_limit,
description="Max number of entries to return in a single query."
f" Limited to {max_limit}",
),
) -> STORE_PARAMS:
if limit > max_limit:
raise Exception(
"Requested more data per query than allowed by this endpoint."
f"The max limit is {max_limit} entries"
)
return {"skip": skip, "limit": limit}
self.query = query
def meta(self, store: Store, query: Dict) -> Dict:
return {"max_limit": self.max_limit}
class SparseFieldsQuery(QueryOperator):
def __init__(self, model: BaseModel, default_fields: Optional[List[str]] = None):
self.model = model
model_fields = list(self.model.__fields__.keys())
self.default_fields = (
model_fields if default_fields is None else list(default_fields)
)
assert set(self.default_fields).issubset(
model_fields
), "default projection contains some fields that are not in the model fields"
default_fields_string = ",".join(self.default_fields)
def query(
fields: str = Query(
default_fields_string,
description=f"Fields to project from {model.__name__} "
f"as a list of comma seperated strings",
),
all_fields: bool = Query(False, description="Include all fields."),
) -> STORE_PARAMS:
projection_fields: List[str] = [s.strip() for s in fields.split(",")]
if all_fields:
projection_fields = model_fields
return {"properties": projection_fields}
self.query = query
def meta(self, store: Store, query: Dict) -> Dict:
return {"default_fields": self.default_fields}
def as_dict(self) -> Dict:
d = super().as_dict()
d["model"] = f"{self.model.__module__}.{self.model.__name__}"
return d
@classmethod
def from_dict(cls, d):
model = d.get("model")
if isinstance(model, str):
module_path = ".".join(model.split(".")[:-1])
class_name = model.split(".")[-1]
model = dynamic_import(module_path, class_name)
assert issubclass(
model, BaseModel
), "The resource model has to be a PyDantic Model"
d["model"] = model
cls(**d)
class DefaultDynamicQuery(QueryOperator):
def __init__(
self, model: BaseModel, additional_signature_fields: Mapping[str, List] = None,
):
self.model = model
default_mapping = {
"eq": "$eq",
"not_eq": "$ne",
"lt": "$lt",
"gt": "$gt",
"in": "$in",
"not_in": "$nin",
}
mapping: dict = default_mapping
self.additional_signature_fields: Mapping[
str, List
] = dict() if additional_signature_fields is None else additional_signature_fields
all_fields: Dict[str, ModelField] = model.__fields__
params = self.fields_to_operator(all_fields)
params.update(self.additional_signature_fields)
def query(**kwargs) -> STORE_PARAMS:
crit = dict()
for k, v in kwargs.items():
if v is not None:
if "_" not in k:
k = k + "_eq"
name, operator = k.split("_", 1)
try:
crit[name] = {mapping[operator]: v}
except KeyError:
raise KeyError(
f"Cannot find key {k} in current query to database mapping"
)
return {"criteria": crit}
signatures: List[Any] = []
signatures.extend(
inspect.Parameter(
param,
inspect.Parameter.POSITIONAL_OR_KEYWORD,
default=query[1],
annotation=query[0],
)
for param, query in params.items()
)
setattr(query, "__signature__", inspect.Signature(signatures))
self.query = query
def fields_to_operator(self, all_fields: Dict[str, ModelField]) -> Dict[str, list]:
params = dict()
for name, model_field in all_fields.items():
if model_field.type_ in [str, int, float]:
t: Any = model_field.type_
name = model_field.name
params[f"{name}"] = [
t,
Query(
default=model_field.default,
description=f"Querying if {model_field.name} is equal to another",
),
]
params[f"{name}_eq"] = [
t,
Query(
default=model_field.default,
description=f"Querying if {model_field.name} is equal to another",
),
]
params[f"{name}_not_eq"] = [
t,
Query(
default=model_field.default,
description=f"Querying if {model_field.name} is not equal to another",
),
]
params[f"{name}_in"] = [
List[t],
Query(
default=model_field.default,
description=f"Querying if item is in {model_field.name}",
),
]
params[f"{name}_not_in"] = [
List[t],
Query(
default=model_field.default,
description=f"Querying if item is not in {model_field.name} ",
),
]
if model_field.type_ == int or model_field == float:
params[f"{name}_lt"] = [
model_field.type_,
Query(
model_field.default,
description=f"Querying if {model_field.name} is less than to another",
),
]
params[f"{name}_gt"] = [
model_field.type_,
Query(
model_field.default,
description=f"Querying if {model_field.name} is greater than to another",
),
]
else:
warnings.warn(
f"Field name {name} with {model_field.type_} not implemented"
)
return params
| true | true |
f72c1ab1de5a5c97a92db41310f7ac5f79e19552 | 4,330 | py | Python | bika/lims/browser/artemplate.py | hocinebendou/bika.gsoc | 85bc0c587de7f52073ae0e89bddbc77bf875f295 | [
"MIT"
] | null | null | null | bika/lims/browser/artemplate.py | hocinebendou/bika.gsoc | 85bc0c587de7f52073ae0e89bddbc77bf875f295 | [
"MIT"
] | null | null | null | bika/lims/browser/artemplate.py | hocinebendou/bika.gsoc | 85bc0c587de7f52073ae0e89bddbc77bf875f295 | [
"MIT"
] | null | null | null | from bika.lims.interfaces import IJSONReadExtender, IARTemplate
from zope.component import adapts
from zope.interface import implements
class JSONReadExtender(object):
"""- Place additional information about profile services
into the returned records.
Used in AR Add to prevent extra requests
"""
implements(IJSONReadExtender)
adapts(IARTemplate)
def __init__(self, context):
self.context = context
def render_template_partitions(self):
"""
Supplies a more detailed view of the Partitions for this
template. It's built to mimic the partitions that are stored in the
ar_add form state variable, so that when a partition is chosen, there
is no further translation necessary.
It combines the Analyses and Partitions AT schema field values.
For some fields (separate, minvol) there is no information, when partitions
are specified in the AR Template.
:return a list of dictionaries like this:
container
[]
container_titles
[]
preservation
[]
preservation_titles
[]
separate
false
minvol
"0.0000 m3 "
services
["2fdc040e05bb42ca8b52e41761fdb795", 6 more...]
service_titles
["Copper", "Iron", "Magnesium", 4 more...]
"""
Analyses = self.context.Schema()['Analyses'].get(self.context)
Parts = self.context.Schema()['Partitions'].get(self.context)
if not Parts:
# default value copied in from content/artemplate.py
Parts = [{'part_id': 'part-1',
'Container': '',
'Preservation': '',
'container_uid': '',
'preservation_uid': ''}]
parts = []
not_found = set()
for Part in Parts:
part = {
'part_id': Part.get("part_id", "part-1"),
'container_titles': Part.get("Container", ""),
'container': Part.get("container_uid", ""),
'preservation_titles': Part.get("Preservation", ""),
'preservation': Part.get("preservation_uid", ""),
'services': [],
'service_titles': [],
}
for analysis in Analyses:
uid = analysis['service_uid']
partiton = analysis['partition']
if partiton == part['part_id']:
part['services'].append(uid)
part['service_titles'].append(uid)
not_found.discard(analysis['service_uid'])
else:
if uid in part['services']:
part['services'].remove(uid)
if uid in part['service_titles']:
part['service_titles'].remove(uid)
not_found.add(analysis['service_uid'])
parts.append(part)
# all others go into the first part. Mostly this will be due to
# partition info not being defined?
for uid in not_found:
if uid not in part['services']:
parts[0]['services'].append(uid)
if uid not in part['service_titles']:
parts[0]['service_titles'].append(uid)
return parts
def __call__(self, request, data):
bsc = self.context.bika_setup_catalog
service_data = []
for item in self.context.getAnalyses():
service_uid = item['service_uid']
service = bsc(UID=service_uid)[0].getObject()
this_service = {'UID': service.UID(),
'Title': service.Title(),
'Keyword': service.getKeyword(),
'Price': service.getPrice(),
'VAT': service.getVAT(),
'PointOfCapture': service.getPointOfCapture(),
'CategoryTitle': service.getCategory().Title()}
service_data.append(this_service)
data['service_data'] = service_data
data['Partitions'] = self.render_template_partitions()
| 38.318584 | 83 | 0.526328 | from bika.lims.interfaces import IJSONReadExtender, IARTemplate
from zope.component import adapts
from zope.interface import implements
class JSONReadExtender(object):
implements(IJSONReadExtender)
adapts(IARTemplate)
def __init__(self, context):
self.context = context
def render_template_partitions(self):
Analyses = self.context.Schema()['Analyses'].get(self.context)
Parts = self.context.Schema()['Partitions'].get(self.context)
if not Parts:
Parts = [{'part_id': 'part-1',
'Container': '',
'Preservation': '',
'container_uid': '',
'preservation_uid': ''}]
parts = []
not_found = set()
for Part in Parts:
part = {
'part_id': Part.get("part_id", "part-1"),
'container_titles': Part.get("Container", ""),
'container': Part.get("container_uid", ""),
'preservation_titles': Part.get("Preservation", ""),
'preservation': Part.get("preservation_uid", ""),
'services': [],
'service_titles': [],
}
for analysis in Analyses:
uid = analysis['service_uid']
partiton = analysis['partition']
if partiton == part['part_id']:
part['services'].append(uid)
part['service_titles'].append(uid)
not_found.discard(analysis['service_uid'])
else:
if uid in part['services']:
part['services'].remove(uid)
if uid in part['service_titles']:
part['service_titles'].remove(uid)
not_found.add(analysis['service_uid'])
parts.append(part)
for uid in not_found:
if uid not in part['services']:
parts[0]['services'].append(uid)
if uid not in part['service_titles']:
parts[0]['service_titles'].append(uid)
return parts
def __call__(self, request, data):
bsc = self.context.bika_setup_catalog
service_data = []
for item in self.context.getAnalyses():
service_uid = item['service_uid']
service = bsc(UID=service_uid)[0].getObject()
this_service = {'UID': service.UID(),
'Title': service.Title(),
'Keyword': service.getKeyword(),
'Price': service.getPrice(),
'VAT': service.getVAT(),
'PointOfCapture': service.getPointOfCapture(),
'CategoryTitle': service.getCategory().Title()}
service_data.append(this_service)
data['service_data'] = service_data
data['Partitions'] = self.render_template_partitions()
| true | true |
f72c1c45126418c8a2273a6fc96e135d6bcf4da8 | 22,915 | py | Python | .infra/setup/playbooks/roles/ansible.kubernetes-modules/library/openshift_v1_group_list.py | cvicens/lab-knative | ef98aa111e566c6d33fd72c61f9c0d93a2c05b2f | [
"Apache-2.0"
] | null | null | null | .infra/setup/playbooks/roles/ansible.kubernetes-modules/library/openshift_v1_group_list.py | cvicens/lab-knative | ef98aa111e566c6d33fd72c61f9c0d93a2c05b2f | [
"Apache-2.0"
] | null | null | null | .infra/setup/playbooks/roles/ansible.kubernetes-modules/library/openshift_v1_group_list.py | cvicens/lab-knative | ef98aa111e566c6d33fd72c61f9c0d93a2c05b2f | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python
# -*- coding: utf-8 -*-
from ansible.module_utils.openshift_common import OpenShiftAnsibleModule, OpenShiftAnsibleException
DOCUMENTATION = '''
module: openshift_v1_group_list
short_description: OpenShift GroupList
description:
- Retrieve a list of groups. List operations provide a snapshot read of the underlying
objects, returning a resource_version representing a consistent version of the listed
objects.
version_added: 2.3.0
author: OpenShift (@openshift)
options:
api_key:
description:
- Token used to connect to the API.
cert_file:
description:
- Path to a certificate used to authenticate with the API.
type: path
context:
description:
- The name of a context found in the Kubernetes config file.
debug:
description:
- Enable debug output from the OpenShift helper. Logging info is written to KubeObjHelper.log
default: false
type: bool
force:
description:
- If set to C(True), and I(state) is C(present), an existing object will updated,
and lists will be replaced, rather than merged.
default: false
type: bool
host:
description:
- Provide a URL for acessing the Kubernetes API.
key_file:
description:
- Path to a key file used to authenticate with the API.
type: path
kubeconfig:
description:
- Path to an existing Kubernetes config file. If not provided, and no other connection
options are provided, the openshift client will attempt to load the default
configuration file from I(~/.kube/config.json).
type: path
password:
description:
- Provide a password for connecting to the API. Use in conjunction with I(username).
resource_definition:
description:
- Provide the YAML definition for the object, bypassing any modules parameters
intended to define object attributes.
type: dict
src:
description:
- Provide a path to a file containing the YAML definition of the object. Mutually
exclusive with I(resource_definition).
type: path
ssl_ca_cert:
description:
- Path to a CA certificate used to authenticate with the API.
type: path
state:
description:
- Determines if an object should be created, patched, or deleted. When set to
C(present), the object will be created, if it does not exist, or patched, if
parameter values differ from the existing object's attributes, and deleted,
if set to C(absent). A patch operation results in merging lists and updating
dictionaries, with lists being merged into a unique set of values. If a list
contains a dictionary with a I(name) or I(type) attribute, a strategic merge
is performed, where individual elements with a matching I(name_) or I(type)
are merged. To force the replacement of lists, set the I(force) option to C(True).
default: present
choices:
- present
- absent
username:
description:
- Provide a username for connecting to the API.
verify_ssl:
description:
- Whether or not to verify the API server's SSL certificates.
type: bool
requirements:
- openshift == 0.3.3
'''
EXAMPLES = '''
'''
RETURN = '''
api_version:
type: string
description: Requested API version
group_list:
type: complex
returned: when I(state) = C(present)
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value, and
may reject unrecognized values.
type: str
items:
description:
- Items is the list of groups
type: list
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value,
and may reject unrecognized values.
type: str
kind:
description:
- Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to.
Cannot be updated. In CamelCase.
type: str
metadata:
description:
- Standard object's metadata.
type: complex
contains:
annotations:
description:
- Annotations is an unstructured key value map stored with a resource
that may be set by external tools to store and retrieve arbitrary
metadata. They are not queryable and should be preserved when modifying
objects.
type: complex
contains: str, str
cluster_name:
description:
- The name of the cluster which the object belongs to. This is used
to distinguish resources with same name and namespace in different
clusters. This field is not set anywhere right now and apiserver is
going to ignore it if set in create or update request.
type: str
creation_timestamp:
description:
- CreationTimestamp is a timestamp representing the server time when
this object was created. It is not guaranteed to be set in happens-before
order across separate operations. Clients may not set this value.
It is represented in RFC3339 form and is in UTC. Populated by the
system. Read-only. Null for lists.
type: complex
contains: {}
deletion_grace_period_seconds:
description:
- Number of seconds allowed for this object to gracefully terminate
before it will be removed from the system. Only set when deletionTimestamp
is also set. May only be shortened. Read-only.
type: int
deletion_timestamp:
description:
- DeletionTimestamp is RFC 3339 date and time at which this resource
will be deleted. This field is set by the server when a graceful deletion
is requested by the user, and is not directly settable by a client.
The resource is expected to be deleted (no longer visible from resource
lists, and not reachable by name) after the time in this field. Once
set, this value may not be unset or be set further into the future,
although it may be shortened or the resource may be deleted prior
to this time. For example, a user may request that a pod is deleted
in 30 seconds. The Kubelet will react by sending a graceful termination
signal to the containers in the pod. After that 30 seconds, the Kubelet
will send a hard termination signal (SIGKILL) to the container and
after cleanup, remove the pod from the API. In the presence of network
partitions, this object may still exist after this timestamp, until
an administrator or automated process can determine the resource is
fully terminated. If not set, graceful deletion of the object has
not been requested. Populated by the system when a graceful deletion
is requested. Read-only.
type: complex
contains: {}
finalizers:
description:
- Must be empty before the object is deleted from the registry. Each
entry is an identifier for the responsible component that will remove
the entry from the list. If the deletionTimestamp of the object is
non-nil, entries in this list can only be removed.
type: list
contains: str
generate_name:
description:
- GenerateName is an optional prefix, used by the server, to generate
a unique name ONLY IF the Name field has not been provided. If this
field is used, the name returned to the client will be different than
the name passed. This value will also be combined with a unique suffix.
The provided value has the same validation rules as the Name field,
and may be truncated by the length of the suffix required to make
the value unique on the server. If this field is specified and the
generated name exists, the server will NOT return a 409 - instead,
it will either return 201 Created or 500 with Reason ServerTimeout
indicating a unique name could not be found in the time allotted,
and the client should retry (optionally after the time indicated in
the Retry-After header). Applied only if Name is not specified.
type: str
generation:
description:
- A sequence number representing a specific generation of the desired
state. Populated by the system. Read-only.
type: int
initializers:
description:
- An initializer is a controller which enforces some system invariant
at object creation time. This field is a list of initializers that
have not yet acted on this object. If nil or empty, this object has
been completely initialized. Otherwise, the object is considered uninitialized
and is hidden (in list/watch and get calls) from clients that haven't
explicitly asked to observe uninitialized objects. When an object
is created, the system will populate this list with the current set
of initializers. Only privileged users may set or modify this list.
Once it is empty, it may not be modified further by any user.
type: complex
contains:
pending:
description:
- Pending is a list of initializers that must execute in order before
this object is visible. When the last pending initializer is removed,
and no failing result is set, the initializers struct will be
set to nil and the object is considered as initialized and visible
to all clients.
type: list
contains:
name:
description:
- name of the process that is responsible for initializing this
object.
type: str
result:
description:
- If result is set with the Failure field, the object will be persisted
to storage and then deleted, ensuring that other clients can observe
the deletion.
type: complex
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation
of an object. Servers should convert recognized schemas to
the latest internal value, and may reject unrecognized values.
type: str
code:
description:
- Suggested HTTP return code for this status, 0 if not set.
type: int
details:
description:
- Extended data associated with the reason. Each reason may
define its own extended details. This field is optional and
the data returned is not guaranteed to conform to any schema
except that defined by the reason type.
type: complex
contains:
causes:
description:
- The Causes array includes more details associated with
the StatusReason failure. Not all StatusReasons may provide
detailed causes.
type: list
contains:
field:
description:
- 'The field of the resource that has caused this error,
as named by its JSON serialization. May include dot
and postfix notation for nested attributes. Arrays
are zero-indexed. Fields may appear more than once
in an array of causes due to fields having multiple
errors. Optional. Examples: "name" - the field "name"
on the current resource "items[0].name" - the field
"name" on the first array entry in "items"'
type: str
message:
description:
- A human-readable description of the cause of the error.
This field may be presented as-is to a reader.
type: str
reason:
description:
- A machine-readable description of the cause of the
error. If this value is empty there is no information
available.
type: str
group:
description:
- The group attribute of the resource associated with the
status StatusReason.
type: str
kind:
description:
- The kind attribute of the resource associated with the
status StatusReason. On some operations may differ from
the requested resource Kind.
type: str
name:
description:
- The name attribute of the resource associated with the
status StatusReason (when there is a single name which
can be described).
type: str
retry_after_seconds:
description:
- If specified, the time in seconds before the operation
should be retried.
type: int
uid:
description:
- UID of the resource. (when there is a single resource
which can be described).
type: str
kind:
description:
- Kind is a string value representing the REST resource this
object represents. Servers may infer this from the endpoint
the client submits requests to. Cannot be updated. In CamelCase.
type: str
message:
description:
- A human-readable description of the status of this operation.
type: str
metadata:
description:
- Standard list metadata.
type: complex
contains:
resource_version:
description:
- String that identifies the server's internal version of
this object that can be used by clients to determine when
objects have changed. Value must be treated as opaque
by clients and passed unmodified back to the server. Populated
by the system. Read-only.
type: str
self_link:
description:
- SelfLink is a URL representing this object. Populated
by the system. Read-only.
type: str
reason:
description:
- A machine-readable description of why this operation is in
the "Failure" status. If this value is empty there is no information
available. A Reason clarifies an HTTP status code but does
not override it.
type: str
status:
description:
- 'Status of the operation. One of: "Success" or "Failure".'
type: str
labels:
description:
- Map of string keys and values that can be used to organize and categorize
(scope and select) objects. May match selectors of replication controllers
and services.
type: complex
contains: str, str
name:
description:
- Name must be unique within a namespace. Is required when creating
resources, although some resources may allow a client to request the
generation of an appropriate name automatically. Name is primarily
intended for creation idempotence and configuration definition. Cannot
be updated.
type: str
namespace:
description:
- Namespace defines the space within each name must be unique. An empty
namespace is equivalent to the "default" namespace, but "default"
is the canonical representation. Not all objects are required to be
scoped to a namespace - the value of this field for those objects
will be empty. Must be a DNS_LABEL. Cannot be updated.
type: str
owner_references:
description:
- List of objects depended by this object. If ALL objects in the list
have been deleted, this object will be garbage collected. If this
object is managed by a controller, then an entry in this list will
point to this controller, with the controller field set to true. There
cannot be more than one managing controller.
type: list
contains:
api_version:
description:
- API version of the referent.
type: str
block_owner_deletion:
description:
- If true, AND if the owner has the "foregroundDeletion" finalizer,
then the owner cannot be deleted from the key-value store until
this reference is removed. Defaults to false. To set this field,
a user needs "delete" permission of the owner, otherwise 422 (Unprocessable
Entity) will be returned.
type: bool
controller:
description:
- If true, this reference points to the managing controller.
type: bool
kind:
description:
- Kind of the referent.
type: str
name:
description:
- Name of the referent.
type: str
uid:
description:
- UID of the referent.
type: str
resource_version:
description:
- An opaque value that represents the internal version of this object
that can be used by clients to determine when objects have changed.
May be used for optimistic concurrency, change detection, and the
watch operation on a resource or set of resources. Clients must treat
these values as opaque and passed unmodified back to the server. They
may only be valid for a particular resource or set of resources. Populated
by the system. Read-only. Value must be treated as opaque by clients
and .
type: str
self_link:
description:
- SelfLink is a URL representing this object. Populated by the system.
Read-only.
type: str
uid:
description:
- UID is the unique in time and space value for this object. It is typically
generated by the server on successful creation of a resource and is
not allowed to change on PUT operations. Populated by the system.
Read-only.
type: str
users:
description:
- Users is the list of users in this group.
type: list
contains: str
kind:
description:
- Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to. Cannot
be updated. In CamelCase.
type: str
metadata:
description:
- Standard object's metadata.
type: complex
contains:
resource_version:
description:
- String that identifies the server's internal version of this object that
can be used by clients to determine when objects have changed. Value must
be treated as opaque by clients and passed unmodified back to the server.
Populated by the system. Read-only.
type: str
self_link:
description:
- SelfLink is a URL representing this object. Populated by the system. Read-only.
type: str
'''
def main():
try:
module = OpenShiftAnsibleModule('group_list', 'v1')
except OpenShiftAnsibleException as exc:
# The helper failed to init, so there is no module object. All we can do is raise the error.
raise Exception(exc.message)
try:
module.execute_module()
except OpenShiftAnsibleException as exc:
module.fail_json(msg="Module failed!", error=str(exc))
if __name__ == '__main__':
main()
| 47.247423 | 100 | 0.560201 |
from ansible.module_utils.openshift_common import OpenShiftAnsibleModule, OpenShiftAnsibleException
DOCUMENTATION = '''
module: openshift_v1_group_list
short_description: OpenShift GroupList
description:
- Retrieve a list of groups. List operations provide a snapshot read of the underlying
objects, returning a resource_version representing a consistent version of the listed
objects.
version_added: 2.3.0
author: OpenShift (@openshift)
options:
api_key:
description:
- Token used to connect to the API.
cert_file:
description:
- Path to a certificate used to authenticate with the API.
type: path
context:
description:
- The name of a context found in the Kubernetes config file.
debug:
description:
- Enable debug output from the OpenShift helper. Logging info is written to KubeObjHelper.log
default: false
type: bool
force:
description:
- If set to C(True), and I(state) is C(present), an existing object will updated,
and lists will be replaced, rather than merged.
default: false
type: bool
host:
description:
- Provide a URL for acessing the Kubernetes API.
key_file:
description:
- Path to a key file used to authenticate with the API.
type: path
kubeconfig:
description:
- Path to an existing Kubernetes config file. If not provided, and no other connection
options are provided, the openshift client will attempt to load the default
configuration file from I(~/.kube/config.json).
type: path
password:
description:
- Provide a password for connecting to the API. Use in conjunction with I(username).
resource_definition:
description:
- Provide the YAML definition for the object, bypassing any modules parameters
intended to define object attributes.
type: dict
src:
description:
- Provide a path to a file containing the YAML definition of the object. Mutually
exclusive with I(resource_definition).
type: path
ssl_ca_cert:
description:
- Path to a CA certificate used to authenticate with the API.
type: path
state:
description:
- Determines if an object should be created, patched, or deleted. When set to
C(present), the object will be created, if it does not exist, or patched, if
parameter values differ from the existing object's attributes, and deleted,
if set to C(absent). A patch operation results in merging lists and updating
dictionaries, with lists being merged into a unique set of values. If a list
contains a dictionary with a I(name) or I(type) attribute, a strategic merge
is performed, where individual elements with a matching I(name_) or I(type)
are merged. To force the replacement of lists, set the I(force) option to C(True).
default: present
choices:
- present
- absent
username:
description:
- Provide a username for connecting to the API.
verify_ssl:
description:
- Whether or not to verify the API server's SSL certificates.
type: bool
requirements:
- openshift == 0.3.3
'''
EXAMPLES = '''
'''
RETURN = '''
api_version:
type: string
description: Requested API version
group_list:
type: complex
returned: when I(state) = C(present)
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value, and
may reject unrecognized values.
type: str
items:
description:
- Items is the list of groups
type: list
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value,
and may reject unrecognized values.
type: str
kind:
description:
- Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to.
Cannot be updated. In CamelCase.
type: str
metadata:
description:
- Standard object's metadata.
type: complex
contains:
annotations:
description:
- Annotations is an unstructured key value map stored with a resource
that may be set by external tools to store and retrieve arbitrary
metadata. They are not queryable and should be preserved when modifying
objects.
type: complex
contains: str, str
cluster_name:
description:
- The name of the cluster which the object belongs to. This is used
to distinguish resources with same name and namespace in different
clusters. This field is not set anywhere right now and apiserver is
going to ignore it if set in create or update request.
type: str
creation_timestamp:
description:
- CreationTimestamp is a timestamp representing the server time when
this object was created. It is not guaranteed to be set in happens-before
order across separate operations. Clients may not set this value.
It is represented in RFC3339 form and is in UTC. Populated by the
system. Read-only. Null for lists.
type: complex
contains: {}
deletion_grace_period_seconds:
description:
- Number of seconds allowed for this object to gracefully terminate
before it will be removed from the system. Only set when deletionTimestamp
is also set. May only be shortened. Read-only.
type: int
deletion_timestamp:
description:
- DeletionTimestamp is RFC 3339 date and time at which this resource
will be deleted. This field is set by the server when a graceful deletion
is requested by the user, and is not directly settable by a client.
The resource is expected to be deleted (no longer visible from resource
lists, and not reachable by name) after the time in this field. Once
set, this value may not be unset or be set further into the future,
although it may be shortened or the resource may be deleted prior
to this time. For example, a user may request that a pod is deleted
in 30 seconds. The Kubelet will react by sending a graceful termination
signal to the containers in the pod. After that 30 seconds, the Kubelet
will send a hard termination signal (SIGKILL) to the container and
after cleanup, remove the pod from the API. In the presence of network
partitions, this object may still exist after this timestamp, until
an administrator or automated process can determine the resource is
fully terminated. If not set, graceful deletion of the object has
not been requested. Populated by the system when a graceful deletion
is requested. Read-only.
type: complex
contains: {}
finalizers:
description:
- Must be empty before the object is deleted from the registry. Each
entry is an identifier for the responsible component that will remove
the entry from the list. If the deletionTimestamp of the object is
non-nil, entries in this list can only be removed.
type: list
contains: str
generate_name:
description:
- GenerateName is an optional prefix, used by the server, to generate
a unique name ONLY IF the Name field has not been provided. If this
field is used, the name returned to the client will be different than
the name passed. This value will also be combined with a unique suffix.
The provided value has the same validation rules as the Name field,
and may be truncated by the length of the suffix required to make
the value unique on the server. If this field is specified and the
generated name exists, the server will NOT return a 409 - instead,
it will either return 201 Created or 500 with Reason ServerTimeout
indicating a unique name could not be found in the time allotted,
and the client should retry (optionally after the time indicated in
the Retry-After header). Applied only if Name is not specified.
type: str
generation:
description:
- A sequence number representing a specific generation of the desired
state. Populated by the system. Read-only.
type: int
initializers:
description:
- An initializer is a controller which enforces some system invariant
at object creation time. This field is a list of initializers that
have not yet acted on this object. If nil or empty, this object has
been completely initialized. Otherwise, the object is considered uninitialized
and is hidden (in list/watch and get calls) from clients that haven't
explicitly asked to observe uninitialized objects. When an object
is created, the system will populate this list with the current set
of initializers. Only privileged users may set or modify this list.
Once it is empty, it may not be modified further by any user.
type: complex
contains:
pending:
description:
- Pending is a list of initializers that must execute in order before
this object is visible. When the last pending initializer is removed,
and no failing result is set, the initializers struct will be
set to nil and the object is considered as initialized and visible
to all clients.
type: list
contains:
name:
description:
- name of the process that is responsible for initializing this
object.
type: str
result:
description:
- If result is set with the Failure field, the object will be persisted
to storage and then deleted, ensuring that other clients can observe
the deletion.
type: complex
contains:
api_version:
description:
- APIVersion defines the versioned schema of this representation
of an object. Servers should convert recognized schemas to
the latest internal value, and may reject unrecognized values.
type: str
code:
description:
- Suggested HTTP return code for this status, 0 if not set.
type: int
details:
description:
- Extended data associated with the reason. Each reason may
define its own extended details. This field is optional and
the data returned is not guaranteed to conform to any schema
except that defined by the reason type.
type: complex
contains:
causes:
description:
- The Causes array includes more details associated with
the StatusReason failure. Not all StatusReasons may provide
detailed causes.
type: list
contains:
field:
description:
- 'The field of the resource that has caused this error,
as named by its JSON serialization. May include dot
and postfix notation for nested attributes. Arrays
are zero-indexed. Fields may appear more than once
in an array of causes due to fields having multiple
errors. Optional. Examples: "name" - the field "name"
on the current resource "items[0].name" - the field
"name" on the first array entry in "items"'
type: str
message:
description:
- A human-readable description of the cause of the error.
This field may be presented as-is to a reader.
type: str
reason:
description:
- A machine-readable description of the cause of the
error. If this value is empty there is no information
available.
type: str
group:
description:
- The group attribute of the resource associated with the
status StatusReason.
type: str
kind:
description:
- The kind attribute of the resource associated with the
status StatusReason. On some operations may differ from
the requested resource Kind.
type: str
name:
description:
- The name attribute of the resource associated with the
status StatusReason (when there is a single name which
can be described).
type: str
retry_after_seconds:
description:
- If specified, the time in seconds before the operation
should be retried.
type: int
uid:
description:
- UID of the resource. (when there is a single resource
which can be described).
type: str
kind:
description:
- Kind is a string value representing the REST resource this
object represents. Servers may infer this from the endpoint
the client submits requests to. Cannot be updated. In CamelCase.
type: str
message:
description:
- A human-readable description of the status of this operation.
type: str
metadata:
description:
- Standard list metadata.
type: complex
contains:
resource_version:
description:
- String that identifies the server's internal version of
this object that can be used by clients to determine when
objects have changed. Value must be treated as opaque
by clients and passed unmodified back to the server. Populated
by the system. Read-only.
type: str
self_link:
description:
- SelfLink is a URL representing this object. Populated
by the system. Read-only.
type: str
reason:
description:
- A machine-readable description of why this operation is in
the "Failure" status. If this value is empty there is no information
available. A Reason clarifies an HTTP status code but does
not override it.
type: str
status:
description:
- 'Status of the operation. One of: "Success" or "Failure".'
type: str
labels:
description:
- Map of string keys and values that can be used to organize and categorize
(scope and select) objects. May match selectors of replication controllers
and services.
type: complex
contains: str, str
name:
description:
- Name must be unique within a namespace. Is required when creating
resources, although some resources may allow a client to request the
generation of an appropriate name automatically. Name is primarily
intended for creation idempotence and configuration definition. Cannot
be updated.
type: str
namespace:
description:
- Namespace defines the space within each name must be unique. An empty
namespace is equivalent to the "default" namespace, but "default"
is the canonical representation. Not all objects are required to be
scoped to a namespace - the value of this field for those objects
will be empty. Must be a DNS_LABEL. Cannot be updated.
type: str
owner_references:
description:
- List of objects depended by this object. If ALL objects in the list
have been deleted, this object will be garbage collected. If this
object is managed by a controller, then an entry in this list will
point to this controller, with the controller field set to true. There
cannot be more than one managing controller.
type: list
contains:
api_version:
description:
- API version of the referent.
type: str
block_owner_deletion:
description:
- If true, AND if the owner has the "foregroundDeletion" finalizer,
then the owner cannot be deleted from the key-value store until
this reference is removed. Defaults to false. To set this field,
a user needs "delete" permission of the owner, otherwise 422 (Unprocessable
Entity) will be returned.
type: bool
controller:
description:
- If true, this reference points to the managing controller.
type: bool
kind:
description:
- Kind of the referent.
type: str
name:
description:
- Name of the referent.
type: str
uid:
description:
- UID of the referent.
type: str
resource_version:
description:
- An opaque value that represents the internal version of this object
that can be used by clients to determine when objects have changed.
May be used for optimistic concurrency, change detection, and the
watch operation on a resource or set of resources. Clients must treat
these values as opaque and passed unmodified back to the server. They
may only be valid for a particular resource or set of resources. Populated
by the system. Read-only. Value must be treated as opaque by clients
and .
type: str
self_link:
description:
- SelfLink is a URL representing this object. Populated by the system.
Read-only.
type: str
uid:
description:
- UID is the unique in time and space value for this object. It is typically
generated by the server on successful creation of a resource and is
not allowed to change on PUT operations. Populated by the system.
Read-only.
type: str
users:
description:
- Users is the list of users in this group.
type: list
contains: str
kind:
description:
- Kind is a string value representing the REST resource this object represents.
Servers may infer this from the endpoint the client submits requests to. Cannot
be updated. In CamelCase.
type: str
metadata:
description:
- Standard object's metadata.
type: complex
contains:
resource_version:
description:
- String that identifies the server's internal version of this object that
can be used by clients to determine when objects have changed. Value must
be treated as opaque by clients and passed unmodified back to the server.
Populated by the system. Read-only.
type: str
self_link:
description:
- SelfLink is a URL representing this object. Populated by the system. Read-only.
type: str
'''
def main():
try:
module = OpenShiftAnsibleModule('group_list', 'v1')
except OpenShiftAnsibleException as exc:
# The helper failed to init, so there is no module object. All we can do is raise the error.
raise Exception(exc.message)
try:
module.execute_module()
except OpenShiftAnsibleException as exc:
module.fail_json(msg="Module failed!", error=str(exc))
if __name__ == '__main__':
main()
| true | true |
f72c1d801a02316cde52c7ee09431a992b7ae36e | 2,353 | py | Python | research/delf/delf/python/examples/detector.py | 873040/Abhishek | 2ddd716e66bc5cc6e6f0787508dd07da0e02e75a | [
"Apache-2.0"
] | 6 | 2020-01-15T09:55:24.000Z | 2021-04-22T09:03:46.000Z | research/delf/delf/python/examples/detector.py | 873040/Abhishek | 2ddd716e66bc5cc6e6f0787508dd07da0e02e75a | [
"Apache-2.0"
] | 10 | 2019-12-28T21:31:19.000Z | 2020-04-12T20:01:58.000Z | research/delf/delf/python/examples/detector.py | 873040/Abhishek | 2ddd716e66bc5cc6e6f0787508dd07da0e02e75a | [
"Apache-2.0"
] | 8 | 2020-04-12T04:30:33.000Z | 2021-09-17T20:54:44.000Z | # 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.
# ==============================================================================
"""Module to construct object detector function."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def MakeDetector(sess, model_dir, import_scope=None):
"""Creates a function to detect objects in an image.
Args:
sess: TensorFlow session to use.
model_dir: Directory where SavedModel is located.
import_scope: Optional scope to use for model.
Returns:
Function that receives an image and returns detection results.
"""
tf.saved_model.loader.load(
sess, [tf.saved_model.tag_constants.SERVING],
model_dir,
import_scope=import_scope)
import_scope_prefix = import_scope + '/' if import_scope is not None else ''
input_images = sess.graph.get_tensor_by_name('%sinput_images:0' %
import_scope_prefix)
boxes = sess.graph.get_tensor_by_name('%sdetection_boxes:0' %
import_scope_prefix)
scores = sess.graph.get_tensor_by_name('%sdetection_scores:0' %
import_scope_prefix)
class_indices = sess.graph.get_tensor_by_name('%sdetection_classes:0' %
import_scope_prefix)
def DetectorFn(images):
"""Receives an image and returns detected boxes.
Args:
images: Uint8 array with shape (batch, height, width 3) containing a batch
of RGB images.
Returns:
Tuple (boxes, scores, class_indices).
"""
return sess.run([boxes, scores, class_indices],
feed_dict={input_images: images})
return DetectorFn
| 37.349206 | 80 | 0.663408 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def MakeDetector(sess, model_dir, import_scope=None):
tf.saved_model.loader.load(
sess, [tf.saved_model.tag_constants.SERVING],
model_dir,
import_scope=import_scope)
import_scope_prefix = import_scope + '/' if import_scope is not None else ''
input_images = sess.graph.get_tensor_by_name('%sinput_images:0' %
import_scope_prefix)
boxes = sess.graph.get_tensor_by_name('%sdetection_boxes:0' %
import_scope_prefix)
scores = sess.graph.get_tensor_by_name('%sdetection_scores:0' %
import_scope_prefix)
class_indices = sess.graph.get_tensor_by_name('%sdetection_classes:0' %
import_scope_prefix)
def DetectorFn(images):
return sess.run([boxes, scores, class_indices],
feed_dict={input_images: images})
return DetectorFn
| true | true |
f72c1f06d6b7f222137806f0a368da2e76782f5f | 1,411 | py | Python | project-EE/run_cleaning.py | Mariagca/EscapeEarth | 5c57ff9dc1a1aed8a3d74d664287f54746c85dff | [
"MIT"
] | 2 | 2020-10-08T20:47:36.000Z | 2020-12-12T22:20:41.000Z | project-EE/run_cleaning.py | Mariagca/EscapeEarth | 5c57ff9dc1a1aed8a3d74d664287f54746c85dff | [
"MIT"
] | null | null | null | project-EE/run_cleaning.py | Mariagca/EscapeEarth | 5c57ff9dc1a1aed8a3d74d664287f54746c85dff | [
"MIT"
] | 6 | 2020-10-08T21:18:23.000Z | 2020-10-08T21:34:35.000Z | #imports
import cleaning_modules as cm
import os
#BE SURE TO CHOOSE OR AMEND THE 'rawdatapath' & 'filename_danielle' paths for your computer!!
# our inputs
tic_list = [7582594, 7582633, 7620704, 7618785, 7584049]
sectornumber = 14
rawdatapath = '/Users/helenfellow/Desktop/sec14_rawdata_subsample/'
rawdatapath_danielle = '/Users/helenfellow/Desktop/sec14_rawdata_subsample/'
cleandata, cleanticids = cm.Dataclean(tic_list,sectornumber,rawdatapath)
#data = cleaned data as a lightkurve class object
for count, i in enumerate(cleanticids):
tic = i
data = cleandata[count]
filename_danielle = '/Users/helenfellow/Desktop/Internship/{}/lc.fits'.format(tic)
filename_maria= '/Users/helenfellow/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_elise = '~/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_olivia = '~/Desktop/Brown Scholars/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_sarah = '~/Desktop/AMNH/BridgeUp Internship/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_anna_claire = '~/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_eliza = '~/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
#commentout
os.makedirs(os.path.dirname(filename_danielle), exist_ok=True) #verify/make folder with tic_id as the name
data.to_fits(filename_danielle,flux_column_name = 'flux',overwrite=True);
| 45.516129 | 110 | 0.764706 |
import cleaning_modules as cm
import os
tic_list = [7582594, 7582633, 7620704, 7618785, 7584049]
sectornumber = 14
rawdatapath = '/Users/helenfellow/Desktop/sec14_rawdata_subsample/'
rawdatapath_danielle = '/Users/helenfellow/Desktop/sec14_rawdata_subsample/'
cleandata, cleanticids = cm.Dataclean(tic_list,sectornumber,rawdatapath)
for count, i in enumerate(cleanticids):
tic = i
data = cleandata[count]
filename_danielle = '/Users/helenfellow/Desktop/Internship/{}/lc.fits'.format(tic)
filename_maria= '/Users/helenfellow/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_elise = '~/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_olivia = '~/Desktop/Brown Scholars/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_sarah = '~/Desktop/AMNH/BridgeUp Internship/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_anna_claire = '~/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
filename_eliza = '~/Desktop/Internship/EscapeEarth/{}/lc.fits'.format(tic)
os.makedirs(os.path.dirname(filename_danielle), exist_ok=True)
data.to_fits(filename_danielle,flux_column_name = 'flux',overwrite=True);
| true | true |
f72c1f9c72b57af7309945959a0c4b2f24dee261 | 631 | py | Python | elk_project/manage.py | joyliao07/elk | c697d6847c57c0e7f3b4dc71a373c5fe0407e237 | [
"MIT"
] | null | null | null | elk_project/manage.py | joyliao07/elk | c697d6847c57c0e7f3b4dc71a373c5fe0407e237 | [
"MIT"
] | 7 | 2019-12-04T23:17:25.000Z | 2021-06-09T17:54:51.000Z | elk_project/manage.py | joyliao07/elk | c697d6847c57c0e7f3b4dc71a373c5fe0407e237 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'elk_project.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()
| 28.681818 | 75 | 0.684628 |
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'elk_project.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()
| true | true |
f72c1fde1011d3abd20dca04a582e9d40af5f026 | 911 | py | Python | heap sort.py | angelopassaro/Hacktoberfest-1 | 21f90f5d49efba9b1a27f4d9b923f5017ab43f0e | [
"Apache-2.0"
] | 1 | 2020-10-06T01:20:07.000Z | 2020-10-06T01:20:07.000Z | heap sort.py | angelopassaro/Hacktoberfest-1 | 21f90f5d49efba9b1a27f4d9b923f5017ab43f0e | [
"Apache-2.0"
] | null | null | null | heap sort.py | angelopassaro/Hacktoberfest-1 | 21f90f5d49efba9b1a27f4d9b923f5017ab43f0e | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# coding: utf-8
# In[4]:
def heapify(arr, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i] # swap
# Heapify the root.
heapify(arr, n, largest)
# The main function to sort an array of given size
def heapSort(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
# One by one extract elements
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
# Driver code to test above
arr = [ 12, 11, 13, 5, 6, 7]
heapSort(arr)
n = len(arr)
print ("Sorted array is")
for i in range(n):
print ("%d" %arr[i]),
# This code is contributed by Mohit Kumra
# In[ ]:
| 17.862745 | 51 | 0.556531 |
def heapify(arr, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i]
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
arr = [ 12, 11, 13, 5, 6, 7]
heapSort(arr)
n = len(arr)
print ("Sorted array is")
for i in range(n):
print ("%d" %arr[i]),
| true | true |
f72c206e11dd63945aef32da40727635e29f68fe | 3,204 | py | Python | tests/sources/test_url.py | mikewcasale/climetlab | 924aa602dcd638ff1a49a9d8b4b6f7bd29361d1e | [
"Apache-2.0"
] | null | null | null | tests/sources/test_url.py | mikewcasale/climetlab | 924aa602dcd638ff1a49a9d8b4b6f7bd29361d1e | [
"Apache-2.0"
] | null | null | null | tests/sources/test_url.py | mikewcasale/climetlab | 924aa602dcd638ff1a49a9d8b4b6f7bd29361d1e | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
# (C) Copyright 2020 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmental organisation
# nor does it submit to any jurisdiction.
#
import datetime
import mimetypes
import os
import sys
import pytest
from climetlab import load_source
from climetlab.sources.url import canonical_extension
from climetlab.testing import climetlab_file
@pytest.mark.skipif( # TODO: fix
sys.platform == "win32",
reason="file:// not working on Windows yet",
)
def test_url_file_source():
filename = os.path.abspath(climetlab_file("docs/examples/test.nc"))
s = load_source("url", f"file://{filename}")
assert len(s) == 2
def test_url_ftp_source_anonymous():
date = datetime.datetime.now() - datetime.timedelta(days=1)
load_source(
"url-pattern",
(
"ftp://ftp.ncep.noaa.gov/pub/data/nccf/com/gfs/prod/"
"gfs.{date:date(%Y%m%d)}/00/atmos/wafsgfs_P_t00z_intdsk84.grib2"
),
{"date": date},
)
def test_url_ftp_source_with_user_pass():
import ftplib
date = datetime.datetime.now() - datetime.timedelta(days=1)
try:
load_source(
"url-pattern",
(
"ftp://wmo:essential@dissemination.ecmwf.int/{date:date(%Y%m%d)}000000/"
"A_HPXA89ECMF{date:date(%d)}0000_C_ECMF_{date:date(%Y%m%d)}"
"000000_an_msl_global_0p5deg_grib2.bin"
),
{"date": date},
)
except ftplib.error_temp:
# Sometimes this site returns:
# ftplib.error_temp: 421 Maximum number of connections exceeded (500)
pass
def test_url_source_1():
load_source(
"url",
"http://download.ecmwf.int/test-data/metview/gallery/temp.bufr",
)
def test_url_source_2():
load_source(
"url",
"https://github.com/ecmwf/climetlab/raw/master/docs/examples/test.grib",
)
def test_url_source_3():
load_source(
"url",
"https://github.com/ecmwf/climetlab/raw/master/docs/examples/test.nc",
)
def test_mimetypes():
assert mimetypes.guess_type("x.grib") == ("application/x-grib", None)
assert canonical_extension("x.grib") == ".grib"
assert canonical_extension("x.grib1") == ".grib"
assert canonical_extension("x.grib2") == ".grib"
assert mimetypes.guess_type("x.nc") == ("application/x-netcdf", None)
assert canonical_extension("x.nc") == ".nc"
assert canonical_extension("x.nc4") == ".nc"
assert canonical_extension("x.cdf") == ".nc"
assert canonical_extension("x.netcdf") == ".nc"
def test_canonical_extension():
assert canonical_extension("x.tar") == ".tar"
assert canonical_extension("x.tgz") == ".tar.gz"
assert canonical_extension("x.foo") == ".foo"
assert canonical_extension("x.csv") == ".csv"
assert canonical_extension("x.csv.gz") == ".csv.gz"
if __name__ == "__main__":
from climetlab.testing import main
main(globals())
| 28.607143 | 88 | 0.652934 |
import datetime
import mimetypes
import os
import sys
import pytest
from climetlab import load_source
from climetlab.sources.url import canonical_extension
from climetlab.testing import climetlab_file
@pytest.mark.skipif(
sys.platform == "win32",
reason="file:// not working on Windows yet",
)
def test_url_file_source():
filename = os.path.abspath(climetlab_file("docs/examples/test.nc"))
s = load_source("url", f"file://{filename}")
assert len(s) == 2
def test_url_ftp_source_anonymous():
date = datetime.datetime.now() - datetime.timedelta(days=1)
load_source(
"url-pattern",
(
"ftp://ftp.ncep.noaa.gov/pub/data/nccf/com/gfs/prod/"
"gfs.{date:date(%Y%m%d)}/00/atmos/wafsgfs_P_t00z_intdsk84.grib2"
),
{"date": date},
)
def test_url_ftp_source_with_user_pass():
import ftplib
date = datetime.datetime.now() - datetime.timedelta(days=1)
try:
load_source(
"url-pattern",
(
"ftp://wmo:essential@dissemination.ecmwf.int/{date:date(%Y%m%d)}000000/"
"A_HPXA89ECMF{date:date(%d)}0000_C_ECMF_{date:date(%Y%m%d)}"
"000000_an_msl_global_0p5deg_grib2.bin"
),
{"date": date},
)
except ftplib.error_temp:
pass
def test_url_source_1():
load_source(
"url",
"http://download.ecmwf.int/test-data/metview/gallery/temp.bufr",
)
def test_url_source_2():
load_source(
"url",
"https://github.com/ecmwf/climetlab/raw/master/docs/examples/test.grib",
)
def test_url_source_3():
load_source(
"url",
"https://github.com/ecmwf/climetlab/raw/master/docs/examples/test.nc",
)
def test_mimetypes():
assert mimetypes.guess_type("x.grib") == ("application/x-grib", None)
assert canonical_extension("x.grib") == ".grib"
assert canonical_extension("x.grib1") == ".grib"
assert canonical_extension("x.grib2") == ".grib"
assert mimetypes.guess_type("x.nc") == ("application/x-netcdf", None)
assert canonical_extension("x.nc") == ".nc"
assert canonical_extension("x.nc4") == ".nc"
assert canonical_extension("x.cdf") == ".nc"
assert canonical_extension("x.netcdf") == ".nc"
def test_canonical_extension():
assert canonical_extension("x.tar") == ".tar"
assert canonical_extension("x.tgz") == ".tar.gz"
assert canonical_extension("x.foo") == ".foo"
assert canonical_extension("x.csv") == ".csv"
assert canonical_extension("x.csv.gz") == ".csv.gz"
if __name__ == "__main__":
from climetlab.testing import main
main(globals())
| true | true |
f72c2077893d50552e9dcf77f984503151020b67 | 2,825 | py | Python | Testing/Alignment.py | freder/PageBotExamples | eb4ced53a673b9376e8357afa9ea0795b022b13c | [
"Ruby",
"MIT"
] | 5 | 2020-06-20T22:01:23.000Z | 2021-08-06T04:39:50.000Z | Testing/Alignment.py | freder/PageBotExamples | eb4ced53a673b9376e8357afa9ea0795b022b13c | [
"Ruby",
"MIT"
] | 5 | 2020-05-17T09:32:27.000Z | 2021-03-15T19:45:52.000Z | Testing/Alignment.py | freder/PageBotExamples | eb4ced53a673b9376e8357afa9ea0795b022b13c | [
"Ruby",
"MIT"
] | 2 | 2021-02-25T19:07:45.000Z | 2022-01-09T21:14:06.000Z | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T E X A M P L E S
#
# Copyright (c) 2017 Thom Janssen <https://github.com/thomgb>
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# Supporting Flat, xxyxyz.org/flat
# -----------------------------------------------------------------------------
#
# TODO: Floating on second line does not seem to work currently
from pagebot.toolbox.color import color
from pagebot import getContext
EXPORT_PATH = '_export/Start'
# Export in _export folder that does not commit in Git.
# Force to export to a few file formats:
EXPORT_PATH_PDF = EXPORT_PATH + '.pdf'
EXPORT_PATH_JPG = EXPORT_PATH + '.jpg'
EXPORT_PATH_PNG = EXPORT_PATH + '.png'
EXPORT_PATH_SVG = EXPORT_PATH + '.svg'
# Document is the main instance holding all information about the document
# together (pages, styles, etc.)
from pagebot.document import Document
from pagebot.elements import *
from pagebot.conditions import *
from pagebot.toolbox.color import Color
W, H = 500, 400
def makeDocument(context):
# Creates the publication/document that holds the pages.
doc = Document(w=W, h=H, context=context)
print(doc.view)
print(doc.pages)
doc.view.padding = 0 # Don't show cropmarks in this example.
#doc.margin =
doc.view.showPadding = True
c1 = [Right2Right(), Float2Top(), Float2Left()]
c2 = [Right2Right(), Float2Top()]
c3 = [Left2Left()]
c4 = [Left2Left(), Float2TopLeft()]
c5 = [Right2Right(), Float2TopLeft()]
c6 = [Left2Left(), Float2TopRight()]
conditions = [c1]#, c2]#, c3, c4, c5, c6]
page = doc[1]
for c in conditions:
makePage(doc, page, c)
#page = page.next
testCoordinates(context)
rectSets = []
def makePage(doc, page, conditions):
# Gets page by pageNumber, first in row (at this point there is only one in
# this row).
page.padding = 1
page.showPadding = True
numberOfSquares = 8
ratio = 1 / numberOfSquares
rects = []
for n in range(numberOfSquares):
r = newRect(w=40, h=42, mr=4, mt=4, parent=page,
fill=color(1 - n*ratio, 0, 0.5),
conditions=conditions, margin=0)
rects.append(r)
rectSets.append(rects)
score = doc.solve()
doc.build()
def testCoordinates(context):
context.fill((0, 1, 0))
context.stroke(None)
for rects in rectSets:
i = 0
for r in rects:
i +=1
x = r.getFloatSideLeft()
y = r.getFloatSideTop()
#print('%d %d' % (x, y))
context.circle(x, y, 2)
context.text('%d' % i, (x + 5, y - 5))
context = getContext()
makeDocument(context)
| 27.163462 | 79 | 0.593982 |
from pagebot.toolbox.color import color
from pagebot import getContext
EXPORT_PATH = '_export/Start'
EXPORT_PATH_PDF = EXPORT_PATH + '.pdf'
EXPORT_PATH_JPG = EXPORT_PATH + '.jpg'
EXPORT_PATH_PNG = EXPORT_PATH + '.png'
EXPORT_PATH_SVG = EXPORT_PATH + '.svg'
from pagebot.document import Document
from pagebot.elements import *
from pagebot.conditions import *
from pagebot.toolbox.color import Color
W, H = 500, 400
def makeDocument(context):
doc = Document(w=W, h=H, context=context)
print(doc.view)
print(doc.pages)
doc.view.padding = 0
#doc.margin =
doc.view.showPadding = True
c1 = [Right2Right(), Float2Top(), Float2Left()]
c2 = [Right2Right(), Float2Top()]
c3 = [Left2Left()]
c4 = [Left2Left(), Float2TopLeft()]
c5 = [Right2Right(), Float2TopLeft()]
c6 = [Left2Left(), Float2TopRight()]
conditions = [c1]#, c2]#, c3, c4, c5, c6]
page = doc[1]
for c in conditions:
makePage(doc, page, c)
#page = page.next
testCoordinates(context)
rectSets = []
def makePage(doc, page, conditions):
# Gets page by pageNumber, first in row (at this point there is only one in
# this row).
page.padding = 1
page.showPadding = True
numberOfSquares = 8
ratio = 1 / numberOfSquares
rects = []
for n in range(numberOfSquares):
r = newRect(w=40, h=42, mr=4, mt=4, parent=page,
fill=color(1 - n*ratio, 0, 0.5),
conditions=conditions, margin=0)
rects.append(r)
rectSets.append(rects)
score = doc.solve()
doc.build()
def testCoordinates(context):
context.fill((0, 1, 0))
context.stroke(None)
for rects in rectSets:
i = 0
for r in rects:
i +=1
x = r.getFloatSideLeft()
y = r.getFloatSideTop()
#print('%d %d' % (x, y))
context.circle(x, y, 2)
context.text('%d' % i, (x + 5, y - 5))
context = getContext()
makeDocument(context)
| true | true |
f72c210c8aaaf5a73cd82343cc65417943d52979 | 13,090 | py | Python | geofabric/model/catchment.py | CSIRO-enviro-informatics/geofabric-dataset | fbca2c79a8e7532f751fb51bebd3433c42d9f422 | [
"Apache-2.0"
] | 3 | 2019-07-16T14:07:54.000Z | 2020-07-04T17:55:24.000Z | geofabric/model/catchment.py | CSIRO-enviro-informatics/geofabric-dataset | fbca2c79a8e7532f751fb51bebd3433c42d9f422 | [
"Apache-2.0"
] | 24 | 2018-09-20T05:17:32.000Z | 2021-12-13T19:49:50.000Z | geofabric/model/catchment.py | CSIRO-enviro-informatics/geofabric-dataset | fbca2c79a8e7532f751fb51bebd3433c42d9f422 | [
"Apache-2.0"
] | 3 | 2018-10-23T05:58:22.000Z | 2019-11-03T23:04:35.000Z | # -*- coding: utf-8 -*-
#
import rdflib
from urllib.request import Request, urlopen
from flask import render_template, url_for
from lxml.etree import ParseError
from rdflib import URIRef, Literal, BNode
from lxml import etree
from geofabric import _config as config
from geofabric.helpers import gml_extract_geom_to_geojson, \
wfs_extract_features_as_geojson, \
wfs_extract_features_as_profile, gml_extract_geom_to_geosparql, \
GEO_hasGeometry, GEO_hasDefaultGeometry, RDF_a, \
HYF_HY_CatchmentRealization, HYF_realizedCatchment, HYF_lowerCatchment, \
HYF_catchmentRealization, HYF_HY_Catchment, HYF_HY_HydroFeature, \
calculate_bbox, NotFoundError
from geofabric.model import GFModel
from functools import lru_cache
from datetime import datetime
# TODO: look into using cachetools.LFUCache or TTLCache
@lru_cache(maxsize=128)
def retrieve_catchment(identifier):
assert isinstance(identifier, int)
catchment_wfs_uri = config.GF_OWS_ENDPOINT + \
'?request=GetFeature' \
'&service=WFS' \
'&version=2.0.0' \
'&typeName=ahgf_shcatch:AHGFCatchment' \
'&Filter=<Filter><PropertyIsEqualTo>' \
'<PropertyName>ahgf_shcatch:hydroid</PropertyName>' \
'<Literal>{:d}</Literal>' \
'</PropertyIsEqualTo></Filter>'.format(identifier)
try:
r = Request(catchment_wfs_uri, method="GET")
with urlopen(r) as response: # type: http.client.HTTPResponse
if not (299 >= response.status >= 200):
raise RuntimeError(
"Cannot get Catchment from WFS backend.")
try:
tree = etree.parse(response)
except ParseError as e:
print(e)
print(response.read())
return []
except Exception as e:
raise e
return tree
ns = {
'x': 'http://linked.data.gov.au/dataset/geof/v2/ahgf_shcatch',
'wfs': 'http://www.opengis.net/wfs/2.0',
'gml': "http://www.opengis.net/gml/3.2"
}
catchment_tag_map = {
"{{{}}}hydroid".format(ns['x']): 'hydroid',
"{{{}}}wkb_geometry".format(ns['x']): 'wkb_geometry',
"{{{}}}ahgfftype".format(ns['x']): 'ahgfftype',
"{{{}}}netnodeid".format(ns['x']): 'netnodeid',
"{{{}}}ncb_id".format(ns['x']): 'ncb_id',
"{{{}}}segmentno".format(ns['x']): 'segmentno',
"{{{}}}streamname".format(ns['x']): 'streamname',
"{{{}}}hassegment".format(ns['x']): 'hassegment',
"{{{}}}extrnlbasn".format(ns['x']): 'extrnlbasn',
"{{{}}}nextdownid".format(ns['x']): 'nextdownid',
"{{{}}}srcfcname".format(ns['x']): 'srcfcname',
"{{{}}}srcfctype".format(ns['x']): 'srcfctype',
"{{{}}}sourceid".format(ns['x']): 'sourceid',
"{{{}}}featrel".format(ns['x']): 'featrel',
"{{{}}}fsource".format(ns['x']): 'fsource',
"{{{}}}attrrel".format(ns['x']): 'attrrel',
"{{{}}}attrsource".format(ns['x']): 'attrsource',
"{{{}}}planacc".format(ns['x']): 'planacc',
"{{{}}}albersarea".format(ns['x']): 'albersarea',
"{{{}}}shape_length".format(ns['x']): 'shape_length',
"{{{}}}shape_area".format(ns['x']): 'shape_area',
"{{{}}}shape".format(ns['x']): 'shape',
}
def catchment_hyfeatures_converter(wfs_features):
if len(wfs_features) < 1:
return None
to_converter = {
'wkb_geometry': gml_extract_geom_to_geosparql,
'shape': gml_extract_geom_to_geosparql,
'nextdownid': lambda x: (set(), URIRef("".join([config.URI_CONTRACTED_CATCHMENT_INSTANCE_BASE, x.text]))),
}
to_float = ('shape_length', 'shape_area', 'albersarea')
to_int = ('hydroid', 'ahgfftype', 'netnodeid', 'ncb_id', 'segmentno', 'sourceid')
to_datetime = ('attrrel', 'featrel')
is_geom = ('wkb_geometry', 'shape')
predicate_map = {
'nextdownid': HYF_lowerCatchment
}
features_list = []
if isinstance(wfs_features, (dict,)):
features_source = wfs_features.items()
elif isinstance(wfs_features, (list, set)):
features_source = iter(wfs_features)
else:
features_source = [wfs_features]
triples = set()
feature_nodes = []
for hydroid, catchment_element in features_source: # type: int, etree._Element
feature_uri = rdflib.URIRef(
"".join([config.URI_CONTRACTED_CATCHMENT_INSTANCE_BASE,
str(hydroid)]))
triples.add((feature_uri, RDF_a, HYF_HY_HydroFeature))
triples.add((feature_uri, RDF_a, HYF_HY_Catchment))
for c in catchment_element.iterchildren(): # type: etree._Element
try:
var = catchment_tag_map[c.tag]
except KeyError:
continue
try:
conv_func = to_converter[var]
_triples, val = conv_func(c)
for (s, p, o) in iter(_triples):
triples.add((s, p, o))
except KeyError:
val = c.text
if var in to_datetime:
if val.endswith('Z'):
val = val[:-1]
try:
val = datetime.strptime(val, "%Y-%m-%dT%H:%M:%S")
val = Literal(val)
except ValueError:
val = "Invalid time format"
elif var in to_float:
val = Literal(float(val))
elif var in to_int:
val = Literal(int(val))
else:
if not isinstance(val, (URIRef, Literal, BNode)):
val = Literal(str(val))
if var in is_geom:
realization = BNode()
triples.add((realization, RDF_a, HYF_HY_CatchmentRealization))
triples.add((realization, GEO_hasGeometry, val))
triples.add((realization, HYF_realizedCatchment, feature_uri))
triples.add((feature_uri, HYF_catchmentRealization, realization))
#triples.add((feature_uri, GEO_hasDefaultGeometry, var))
elif var in predicate_map.keys():
predicate = predicate_map[var]
triples.add((feature_uri, predicate, val))
else:
dummy_prop = URIRef("{}/{}".format(ns['x'], var))
triples.add((feature_uri, dummy_prop, val))
features_list.append(feature_uri)
return triples, feature_nodes
def catchment_features_geojson_converter(wfs_features):
if len(wfs_features) < 1:
return None
to_converter = {
'wkb_geometry': gml_extract_geom_to_geojson,
'shape': gml_extract_geom_to_geojson,
}
to_float = ('shape_length', 'shape_area', 'albersarea')
to_int = ('hydroid', 'ahgfftype', 'netnodeid', 'ncb_id', 'segmentno', 'nextdownid', 'sourceid')
# to_datetime = ('attrrel', 'featrel')
to_datetime = []
is_geom = ('wkb_geometry', 'shape')
features_list = []
if isinstance(wfs_features, (dict,)):
features_source = wfs_features.items()
elif isinstance(wfs_features, (list, set)):
features_source = iter(wfs_features)
else:
features_source = [wfs_features]
for hydroid, catchment_element in features_source: # type: int, etree._Element
catchment_dict = {"type": "Feature", "id": hydroid, "geometry": {}, "properties": {}}
for c in catchment_element.iterchildren(): # type: etree._Element
try:
var = catchment_tag_map[c.tag]
except KeyError:
continue
try:
conv_func = to_converter[var]
val = conv_func(c)
except KeyError:
val = c.text
if var in to_datetime:
if val.endswith('Z'):
val = val[:-1]
try:
val = datetime.strptime(val, "%Y-%m-%dT%H:%M:%S")
except ValueError:
val = "Invalid time format"
elif var in to_float:
val = float(val)
elif var in to_int:
val = int(val)
if var in is_geom:
catchment_dict['geometry'] = val
else:
catchment_dict['properties'][var] = val
features_list.append(catchment_dict)
return features_list
def extract_catchments_as_geojson(tree):
geojson_features = wfs_extract_features_as_geojson(tree, ns['x'], "AHGFCatchment", catchment_features_geojson_converter)
return geojson_features
def extract_catchments_as_hyfeatures(tree, model=None):
g = rdflib.Graph()
triples, features = wfs_extract_features_as_profile(tree, ns['x'], "AHGFCatchment", catchment_hyfeatures_converter, model)
for (s, p, o) in iter(triples):
g.add((s, p, o))
return g
class Catchment(GFModel):
@classmethod
def make_instance_label(cls, instance_id):
return "Catchment ID: {}".format(str(instance_id))
@classmethod
def make_canonical_uri(cls, instance_id):
return "".join([config.URI_CONTRACTED_CATCHMENT_INSTANCE_BASE, instance_id])
@classmethod
def make_local_url(cls, instance_id):
return url_for('classes.catchment', contractedcatchment_id=instance_id)
@classmethod
def get_index(cls, page, per_page):
per_page = max(int(per_page), 1)
offset = (max(int(page), 1)-1)*per_page
catchments_wfs_uri = config.GF_OWS_ENDPOINT + \
'?service=wfs' \
'&version=2.0.0' \
'&request=GetFeature' \
'&typeName=ahgf_shcatch:AHGFCatchment' \
'&propertyName=hydroid' \
'&sortBy=hydroid' \
'&count={}&startIndex={}'.format(per_page, offset)
try:
r = Request(catchments_wfs_uri, method="GET")
with urlopen(r) as response: # type: http.client.HTTPResponse
if not (299 >= response.status >= 200):
raise RuntimeError("Cannot get Contracted Catchments index from WFS backend.")
try:
tree = etree.parse(response)
except ParseError as e:
print(e)
print(response.read())
return []
except Exception as e:
raise e
items = tree.xpath('//x:hydroid/text()', namespaces={
'x': 'http://linked.data.gov.au/dataset/geof/v2/ahgf_shcatch'})
return items
def __init__(self, identifier):
super(Catchment, self).__init__()
identifier = int(identifier)
catchment_xml_tree = retrieve_catchment(identifier)
self.xml_tree = catchment_xml_tree
catchments = extract_catchments_as_geojson(catchment_xml_tree)
if catchments['features'] is None or len(catchments['features']) < 1:
raise NotFoundError()
catchment = catchments['features'][0]
self.geometry = catchment['geometry']
for k, v in catchment['properties'].items():
setattr(self, k, v)
def get_bbox(self, pad=0):
coords = self.geometry['coordinates']
json_bbox = calculate_bbox(coords, pad=pad)
(n, s, e, w) = json_bbox
return (w,s,e,n) # (minx, miny, maxx, maxy)
def to_hyfeatures_graph(self):
g = extract_catchments_as_hyfeatures(self.xml_tree)
return g
def export_html(self, view='geofabric'):
bbox_string = ",".join(str(i) for i in self.get_bbox(pad=12))
hydroid = self.hydroid
wms_url = config.GF_OWS_ENDPOINT +\
"?service=wms&version=2.0.0&request=GetMap" \
"&width=800&height=600" \
"&format=text/html;+subtype=openlayers" \
"&CRS=EPSG:4326" \
"&layers=osm_au,ahgf_shcatch:AHGFCatchment" \
"&style=ahgfcatchment" \
"&bbox=" + bbox_string +\
"&CQL_FILTER=INCLUDE;hydroid="+str(hydroid)
nextdownid = getattr(self, 'nextdownid', None)
if view == 'geofabric':
view_html = render_template(
'class_catchment_geof.html',
wms_url=wms_url,
hydroid=hydroid,
nextdownid=nextdownid,
shape_length=self.shape_length,
shape_area=self.shape_area,
albers_area=self.albersarea,
)
elif view == "hyfeatures":
view_html = render_template(
'class_catchment_hyf.html',
wms_url=wms_url,
hydroid=hydroid,
nextdownid=nextdownid,
shape_length=self.shape_length,
shape_area=self.shape_area,
albers_area=self.albersarea,
)
else:
return NotImplementedError("HTML representation of View '{}' is not implemented.".format(view))
return view_html
| 40.526316 | 126 | 0.572193 |
import rdflib
from urllib.request import Request, urlopen
from flask import render_template, url_for
from lxml.etree import ParseError
from rdflib import URIRef, Literal, BNode
from lxml import etree
from geofabric import _config as config
from geofabric.helpers import gml_extract_geom_to_geojson, \
wfs_extract_features_as_geojson, \
wfs_extract_features_as_profile, gml_extract_geom_to_geosparql, \
GEO_hasGeometry, GEO_hasDefaultGeometry, RDF_a, \
HYF_HY_CatchmentRealization, HYF_realizedCatchment, HYF_lowerCatchment, \
HYF_catchmentRealization, HYF_HY_Catchment, HYF_HY_HydroFeature, \
calculate_bbox, NotFoundError
from geofabric.model import GFModel
from functools import lru_cache
from datetime import datetime
@lru_cache(maxsize=128)
def retrieve_catchment(identifier):
assert isinstance(identifier, int)
catchment_wfs_uri = config.GF_OWS_ENDPOINT + \
'?request=GetFeature' \
'&service=WFS' \
'&version=2.0.0' \
'&typeName=ahgf_shcatch:AHGFCatchment' \
'&Filter=<Filter><PropertyIsEqualTo>' \
'<PropertyName>ahgf_shcatch:hydroid</PropertyName>' \
'<Literal>{:d}</Literal>' \
'</PropertyIsEqualTo></Filter>'.format(identifier)
try:
r = Request(catchment_wfs_uri, method="GET")
with urlopen(r) as response:
if not (299 >= response.status >= 200):
raise RuntimeError(
"Cannot get Catchment from WFS backend.")
try:
tree = etree.parse(response)
except ParseError as e:
print(e)
print(response.read())
return []
except Exception as e:
raise e
return tree
ns = {
'x': 'http://linked.data.gov.au/dataset/geof/v2/ahgf_shcatch',
'wfs': 'http://www.opengis.net/wfs/2.0',
'gml': "http://www.opengis.net/gml/3.2"
}
catchment_tag_map = {
"{{{}}}hydroid".format(ns['x']): 'hydroid',
"{{{}}}wkb_geometry".format(ns['x']): 'wkb_geometry',
"{{{}}}ahgfftype".format(ns['x']): 'ahgfftype',
"{{{}}}netnodeid".format(ns['x']): 'netnodeid',
"{{{}}}ncb_id".format(ns['x']): 'ncb_id',
"{{{}}}segmentno".format(ns['x']): 'segmentno',
"{{{}}}streamname".format(ns['x']): 'streamname',
"{{{}}}hassegment".format(ns['x']): 'hassegment',
"{{{}}}extrnlbasn".format(ns['x']): 'extrnlbasn',
"{{{}}}nextdownid".format(ns['x']): 'nextdownid',
"{{{}}}srcfcname".format(ns['x']): 'srcfcname',
"{{{}}}srcfctype".format(ns['x']): 'srcfctype',
"{{{}}}sourceid".format(ns['x']): 'sourceid',
"{{{}}}featrel".format(ns['x']): 'featrel',
"{{{}}}fsource".format(ns['x']): 'fsource',
"{{{}}}attrrel".format(ns['x']): 'attrrel',
"{{{}}}attrsource".format(ns['x']): 'attrsource',
"{{{}}}planacc".format(ns['x']): 'planacc',
"{{{}}}albersarea".format(ns['x']): 'albersarea',
"{{{}}}shape_length".format(ns['x']): 'shape_length',
"{{{}}}shape_area".format(ns['x']): 'shape_area',
"{{{}}}shape".format(ns['x']): 'shape',
}
def catchment_hyfeatures_converter(wfs_features):
if len(wfs_features) < 1:
return None
to_converter = {
'wkb_geometry': gml_extract_geom_to_geosparql,
'shape': gml_extract_geom_to_geosparql,
'nextdownid': lambda x: (set(), URIRef("".join([config.URI_CONTRACTED_CATCHMENT_INSTANCE_BASE, x.text]))),
}
to_float = ('shape_length', 'shape_area', 'albersarea')
to_int = ('hydroid', 'ahgfftype', 'netnodeid', 'ncb_id', 'segmentno', 'sourceid')
to_datetime = ('attrrel', 'featrel')
is_geom = ('wkb_geometry', 'shape')
predicate_map = {
'nextdownid': HYF_lowerCatchment
}
features_list = []
if isinstance(wfs_features, (dict,)):
features_source = wfs_features.items()
elif isinstance(wfs_features, (list, set)):
features_source = iter(wfs_features)
else:
features_source = [wfs_features]
triples = set()
feature_nodes = []
for hydroid, catchment_element in features_source:
feature_uri = rdflib.URIRef(
"".join([config.URI_CONTRACTED_CATCHMENT_INSTANCE_BASE,
str(hydroid)]))
triples.add((feature_uri, RDF_a, HYF_HY_HydroFeature))
triples.add((feature_uri, RDF_a, HYF_HY_Catchment))
for c in catchment_element.iterchildren():
try:
var = catchment_tag_map[c.tag]
except KeyError:
continue
try:
conv_func = to_converter[var]
_triples, val = conv_func(c)
for (s, p, o) in iter(_triples):
triples.add((s, p, o))
except KeyError:
val = c.text
if var in to_datetime:
if val.endswith('Z'):
val = val[:-1]
try:
val = datetime.strptime(val, "%Y-%m-%dT%H:%M:%S")
val = Literal(val)
except ValueError:
val = "Invalid time format"
elif var in to_float:
val = Literal(float(val))
elif var in to_int:
val = Literal(int(val))
else:
if not isinstance(val, (URIRef, Literal, BNode)):
val = Literal(str(val))
if var in is_geom:
realization = BNode()
triples.add((realization, RDF_a, HYF_HY_CatchmentRealization))
triples.add((realization, GEO_hasGeometry, val))
triples.add((realization, HYF_realizedCatchment, feature_uri))
triples.add((feature_uri, HYF_catchmentRealization, realization))
elif var in predicate_map.keys():
predicate = predicate_map[var]
triples.add((feature_uri, predicate, val))
else:
dummy_prop = URIRef("{}/{}".format(ns['x'], var))
triples.add((feature_uri, dummy_prop, val))
features_list.append(feature_uri)
return triples, feature_nodes
def catchment_features_geojson_converter(wfs_features):
if len(wfs_features) < 1:
return None
to_converter = {
'wkb_geometry': gml_extract_geom_to_geojson,
'shape': gml_extract_geom_to_geojson,
}
to_float = ('shape_length', 'shape_area', 'albersarea')
to_int = ('hydroid', 'ahgfftype', 'netnodeid', 'ncb_id', 'segmentno', 'nextdownid', 'sourceid')
to_datetime = []
is_geom = ('wkb_geometry', 'shape')
features_list = []
if isinstance(wfs_features, (dict,)):
features_source = wfs_features.items()
elif isinstance(wfs_features, (list, set)):
features_source = iter(wfs_features)
else:
features_source = [wfs_features]
for hydroid, catchment_element in features_source:
catchment_dict = {"type": "Feature", "id": hydroid, "geometry": {}, "properties": {}}
for c in catchment_element.iterchildren():
try:
var = catchment_tag_map[c.tag]
except KeyError:
continue
try:
conv_func = to_converter[var]
val = conv_func(c)
except KeyError:
val = c.text
if var in to_datetime:
if val.endswith('Z'):
val = val[:-1]
try:
val = datetime.strptime(val, "%Y-%m-%dT%H:%M:%S")
except ValueError:
val = "Invalid time format"
elif var in to_float:
val = float(val)
elif var in to_int:
val = int(val)
if var in is_geom:
catchment_dict['geometry'] = val
else:
catchment_dict['properties'][var] = val
features_list.append(catchment_dict)
return features_list
def extract_catchments_as_geojson(tree):
geojson_features = wfs_extract_features_as_geojson(tree, ns['x'], "AHGFCatchment", catchment_features_geojson_converter)
return geojson_features
def extract_catchments_as_hyfeatures(tree, model=None):
g = rdflib.Graph()
triples, features = wfs_extract_features_as_profile(tree, ns['x'], "AHGFCatchment", catchment_hyfeatures_converter, model)
for (s, p, o) in iter(triples):
g.add((s, p, o))
return g
class Catchment(GFModel):
@classmethod
def make_instance_label(cls, instance_id):
return "Catchment ID: {}".format(str(instance_id))
@classmethod
def make_canonical_uri(cls, instance_id):
return "".join([config.URI_CONTRACTED_CATCHMENT_INSTANCE_BASE, instance_id])
@classmethod
def make_local_url(cls, instance_id):
return url_for('classes.catchment', contractedcatchment_id=instance_id)
@classmethod
def get_index(cls, page, per_page):
per_page = max(int(per_page), 1)
offset = (max(int(page), 1)-1)*per_page
catchments_wfs_uri = config.GF_OWS_ENDPOINT + \
'?service=wfs' \
'&version=2.0.0' \
'&request=GetFeature' \
'&typeName=ahgf_shcatch:AHGFCatchment' \
'&propertyName=hydroid' \
'&sortBy=hydroid' \
'&count={}&startIndex={}'.format(per_page, offset)
try:
r = Request(catchments_wfs_uri, method="GET")
with urlopen(r) as response:
if not (299 >= response.status >= 200):
raise RuntimeError("Cannot get Contracted Catchments index from WFS backend.")
try:
tree = etree.parse(response)
except ParseError as e:
print(e)
print(response.read())
return []
except Exception as e:
raise e
items = tree.xpath('//x:hydroid/text()', namespaces={
'x': 'http://linked.data.gov.au/dataset/geof/v2/ahgf_shcatch'})
return items
def __init__(self, identifier):
super(Catchment, self).__init__()
identifier = int(identifier)
catchment_xml_tree = retrieve_catchment(identifier)
self.xml_tree = catchment_xml_tree
catchments = extract_catchments_as_geojson(catchment_xml_tree)
if catchments['features'] is None or len(catchments['features']) < 1:
raise NotFoundError()
catchment = catchments['features'][0]
self.geometry = catchment['geometry']
for k, v in catchment['properties'].items():
setattr(self, k, v)
def get_bbox(self, pad=0):
coords = self.geometry['coordinates']
json_bbox = calculate_bbox(coords, pad=pad)
(n, s, e, w) = json_bbox
return (w,s,e,n)
def to_hyfeatures_graph(self):
g = extract_catchments_as_hyfeatures(self.xml_tree)
return g
def export_html(self, view='geofabric'):
bbox_string = ",".join(str(i) for i in self.get_bbox(pad=12))
hydroid = self.hydroid
wms_url = config.GF_OWS_ENDPOINT +\
"?service=wms&version=2.0.0&request=GetMap" \
"&width=800&height=600" \
"&format=text/html;+subtype=openlayers" \
"&CRS=EPSG:4326" \
"&layers=osm_au,ahgf_shcatch:AHGFCatchment" \
"&style=ahgfcatchment" \
"&bbox=" + bbox_string +\
"&CQL_FILTER=INCLUDE;hydroid="+str(hydroid)
nextdownid = getattr(self, 'nextdownid', None)
if view == 'geofabric':
view_html = render_template(
'class_catchment_geof.html',
wms_url=wms_url,
hydroid=hydroid,
nextdownid=nextdownid,
shape_length=self.shape_length,
shape_area=self.shape_area,
albers_area=self.albersarea,
)
elif view == "hyfeatures":
view_html = render_template(
'class_catchment_hyf.html',
wms_url=wms_url,
hydroid=hydroid,
nextdownid=nextdownid,
shape_length=self.shape_length,
shape_area=self.shape_area,
albers_area=self.albersarea,
)
else:
return NotImplementedError("HTML representation of View '{}' is not implemented.".format(view))
return view_html
| true | true |
f72c2280bf4ad25e6907abd6b677f870efbe0e50 | 1,135 | py | Python | src/models/ep.py | tonyduan/ge-vae | fe3325cb643900d09536b3e1d964443d25625781 | [
"MIT"
] | 7 | 2019-11-04T09:13:44.000Z | 2021-04-22T01:28:27.000Z | src/models/ep.py | tonyduan/ge-vae | fe3325cb643900d09536b3e1d964443d25625781 | [
"MIT"
] | null | null | null | src/models/ep.py | tonyduan/ge-vae | fe3325cb643900d09536b3e1d964443d25625781 | [
"MIT"
] | 3 | 2019-11-02T10:50:29.000Z | 2020-02-09T02:50:48.000Z | import torch
import torch.nn as nn
from torch.distributions import Bernoulli
from src.modules.attn import MAB, PMA, SAB, ISAB, ISABStack
from src.utils import *
from src.modules.mlp import *
class EdgePredictor(nn.Module):
def __init__(self, embedding_dim, device):
super().__init__()
self.pairwise_query = ISABStack(8, embedding_dim, 256, num_heads = 4,
num_inds = 16, device = device)
self.device = device
self.baseline = nn.Parameter(torch.zeros(1, device = device))
self.scale1 = nn.Parameter(torch.zeros(1, device = device))
def forward(self, E, V):
mask = construct_embedding_mask(V).byte()
Z1 = self.pairwise_query(E, mask)
F = Z1 @ Z1.transpose(1, 2)
return F * torch.exp(self.scale1) + self.baseline #+ \
def log_prob_per_edge(self, E, A, V):
mask = construct_adjacency_mask(V)
counts = V * (V - 1) / 2
loss = Bernoulli(logits = self.forward(E, V)).log_prob(A)
loss = torch.sum(torch.triu(loss, diagonal = 1) * mask, dim = (1, 2))
return loss #/ counts
| 35.46875 | 78 | 0.61674 | import torch
import torch.nn as nn
from torch.distributions import Bernoulli
from src.modules.attn import MAB, PMA, SAB, ISAB, ISABStack
from src.utils import *
from src.modules.mlp import *
class EdgePredictor(nn.Module):
def __init__(self, embedding_dim, device):
super().__init__()
self.pairwise_query = ISABStack(8, embedding_dim, 256, num_heads = 4,
num_inds = 16, device = device)
self.device = device
self.baseline = nn.Parameter(torch.zeros(1, device = device))
self.scale1 = nn.Parameter(torch.zeros(1, device = device))
def forward(self, E, V):
mask = construct_embedding_mask(V).byte()
Z1 = self.pairwise_query(E, mask)
F = Z1 @ Z1.transpose(1, 2)
return F * torch.exp(self.scale1) + self.baseline
def log_prob_per_edge(self, E, A, V):
mask = construct_adjacency_mask(V)
counts = V * (V - 1) / 2
loss = Bernoulli(logits = self.forward(E, V)).log_prob(A)
loss = torch.sum(torch.triu(loss, diagonal = 1) * mask, dim = (1, 2))
return loss
| true | true |
f72c22ad9e0dc3e5f4ab51f0e1e77ab067f3acac | 14,720 | py | Python | CybORG/CybORG/Tests/test_sim/test_Actions/test_BlueActions/test_blue_analyse.py | rafvasq/cage-challenge-1 | 95affdfa38afc1124f1a1a09c92fbc0ed5b96318 | [
"MIT"
] | 18 | 2021-08-20T15:07:55.000Z | 2022-03-11T12:05:15.000Z | CybORG/CybORG/Tests/test_sim/test_Actions/test_BlueActions/test_blue_analyse.py | rafvasq/cage-challenge-1 | 95affdfa38afc1124f1a1a09c92fbc0ed5b96318 | [
"MIT"
] | 7 | 2021-11-09T06:46:58.000Z | 2022-03-31T12:35:06.000Z | CybORG/CybORG/Tests/test_sim/test_Actions/test_BlueActions/test_blue_analyse.py | rafvasq/cage-challenge-1 | 95affdfa38afc1124f1a1a09c92fbc0ed5b96318 | [
"MIT"
] | 13 | 2021-08-17T00:26:31.000Z | 2022-03-29T20:06:45.000Z | # These tests check that the Blue Monitor action is working vs Abstract Red Actions.
# tests need to check that a range of inputs result in the correct changes to the state and return the correct obs
# tests should establish varying environmental states that results in these actions performing differently
import inspect
from CybORG import CybORG
from CybORG.Shared.Actions import DiscoverRemoteSystems, DiscoverNetworkServices, ExploitRemoteService, \
PrivilegeEscalate, Impact, Analyse
from CybORG.Shared.Enums import TrinaryEnum, FileType, Path
from CybORG.Tests.EphemeralPort import Win2008EphemeralPort, LinuxEphemeralPort
from CybORG.Tests.test_sim.test_Acceptance.test_reward_function import security_values, availability_values
import pytest
from CybORG.Agents import B_lineAgent
@pytest.mark.skip()
def test_blue_analyse_on_red_killchain(security_values,availability_values):
# create cyborg environment
path = str(inspect.getfile(CybORG))
path = path[:-10] + '/Shared/Scenarios/Scenario1b.yaml'
cyborg = CybORG(path, 'sim')
# Run blue monitor with no red activity.
blue_session = cyborg.get_observation('Blue')['Defender']['Sessions'][0]['ID']
blue_hosts = cyborg.get_action_space('Blue')['hostname']
def blue_analyse(expected_result, host, reward=0.0):
blue_action = Analyse(session=blue_session, agent='Blue', hostname=host)
results = cyborg.step('Blue', blue_action)
assert not results.done
assert results.reward == round(reward, 1)
assert results.observation == expected_result
windows_reverse_shell = {'Density': 0.9,
'File Name': 'cmd.exe',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': 'C:\\temp\\',
'Signed': False}
linux_reverse_shell = {'Density': 0.9,
'File Name': 'cmd.sh',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': '/tmp/',
'Signed': False}
windows_potato_exploit = {'Density': 0.9,
'File Name': 'escalate.exe',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': 'C:\\temp\\',
'Signed': False}
linux_kernel_exploit = {'Density': 0.9,
'File Name': 'escalate.sh',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': '/tmp/',
'Signed': False}
# test discover remote systems
# act on all subnets in action space
action_space = cyborg.get_action_space('Red')
initial_observation = cyborg.get_observation('Red')
session = list(action_space['session'].keys())[0]
for subnet in action_space["subnet"]:
# ping sweep leaves no artifacts for scenario1b
expected_observation = {'success': TrinaryEnum.TRUE}
action = DiscoverRemoteSystems(subnet=subnet, agent='Red', session=session)
cyborg.step(action=action, agent='Red')
# test if output of observation matches expected output
for host in blue_hosts:
blue_analyse(expected_observation, host)
# test discover network services
# act on ip addresses discovered in first subnet
addresses = [i for i in action_space["ip_address"]]
attacker_address = cyborg.environment_controller.hostname_ip_map['User0']
for address in addresses:
expected_observation = {'success': TrinaryEnum.TRUE}
action = DiscoverNetworkServices(agent='Red', ip_address=address, session=session)
cyborg.step(action=action, agent='Red')
# test if output of observation matches expected output
for host in blue_hosts:
blue_analyse(expected_observation, host)
# test exploit action by acting on all known ip_addresses
# own all hosts on the client subnet
reward = 0
for address in addresses:
action = ExploitRemoteService(agent='Red', ip_address=address, session=session)
cyborg.step(action=action, agent='Red')
# test if output of observation matches expected output
hostname = {v: i for i, v in cyborg.environment_controller.hostname_ip_map.items()}[address]
if not action_space["ip_address"][address]:
expected_observation = {'success': TrinaryEnum.TRUE}
elif address == cyborg.environment_controller.hostname_ip_map['User0'] or address == \
cyborg.environment_controller.hostname_ip_map['User1'] or address == \
cyborg.environment_controller.hostname_ip_map['User2']:
expected_observation = {hostname: {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
reward += security_values[hostname][0]
elif address == cyborg.environment_controller.hostname_ip_map['User3'] or address == \
cyborg.environment_controller.hostname_ip_map['User4']:
expected_observation = {hostname: {'Files': [linux_reverse_shell]},
'success': TrinaryEnum.TRUE}
else:
raise NotImplementedError
blue_analyse(expected_observation, hostname, reward)
# priv esc on all hosts in client subnet
action_space = cyborg.get_action_space('Red')
hostnames = action_space['hostname']
count = 2
for hostname in hostnames:
action = PrivilegeEscalate(agent='Red', hostname=hostname, session=session)
cyborg.step(action=action, agent='Red')
if hostnames[hostname]:
last_action = cyborg.get_last_action('Red')
assert last_action == action
# test if output of observation matches expected output
if 'User' in hostname:
if '0' in hostname or '1' in hostname or '2' in hostname:
expected_observation = {hostname: {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
else:
expected_observation = {hostname: {'Files': [linux_reverse_shell,
linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
reward += security_values[hostname][1]
else:
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, host=hostname, reward=reward)
# recon hosts in enterprise subnet
action_space = cyborg.get_action_space('Red')
addresses = [i for i in action_space["ip_address"]]
for address in addresses:
if not action_space["ip_address"][address] \
or address == cyborg.environment_controller.hostname_ip_map['User0'] \
or address == cyborg.environment_controller.hostname_ip_map['User1'] \
or address == cyborg.environment_controller.hostname_ip_map['User2'] \
or address == cyborg.environment_controller.hostname_ip_map['User3'] \
or address == cyborg.environment_controller.hostname_ip_map['User4']:
continue
else:
expected_observation = {'success': TrinaryEnum.TRUE}
hostname = {v: i for i, v in cyborg.environment_controller.hostname_ip_map.items()}[address]
action = DiscoverNetworkServices(agent='Red', ip_address=address, session=session)
result = cyborg.step(action=action, agent='Red')
# test if output of observation matches expected output
blue_analyse(expected_observation, hostname, reward)
# exploit hosts in enterprise subnet
action_space = cyborg.get_action_space('Red')
addresses = [i for i in action_space["ip_address"]]
for address in addresses:
hostname = {v: i for i, v in cyborg.environment_controller.hostname_ip_map.items()}[address]
if not action_space["ip_address"][address] \
or address == cyborg.environment_controller.hostname_ip_map['User0'] \
or address == cyborg.environment_controller.hostname_ip_map['User1'] \
or address == cyborg.environment_controller.hostname_ip_map['User2'] \
or address == cyborg.environment_controller.hostname_ip_map['User3'] \
or address == cyborg.environment_controller.hostname_ip_map['User4']:
continue
elif address == cyborg.environment_controller.hostname_ip_map['Enterprise0']:
expected_observation = {'success': TrinaryEnum.TRUE}
count += 1
elif address == cyborg.environment_controller.hostname_ip_map['Enterprise1']:
expected_observation = {hostname: {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
count += 1
else:
raise ValueError
action = ExploitRemoteService(agent='Red', ip_address=address, session=session)
cyborg.step(action=action, agent='Red')
# test if output of observation matches expected output
blue_analyse(expected_observation, hostname, reward)
# priv esc hosts in enterprise subnet
enterprise_subnet = cyborg.environment_controller.subnet_cidr_map['Enterprise']
action_space = cyborg.get_action_space('Red')
hostnames = action_space['hostname']
count = 6
for hostname in hostnames:
if 'User' in hostname:
continue
action = PrivilegeEscalate(agent='Red', hostname=hostname, session=session)
result = cyborg.step(action=action, agent='Red')
# test if output of observation matches expected output
if hostname == 'Enterprise0':
expected_observation = {'Enterprise0': {'Files': [linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
elif hostname == 'Enterprise1':
expected_observation = {'Enterprise1': {'Files': [windows_reverse_shell,
windows_potato_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
else:
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, hostname, reward)
# scan enterprise subnet
action_space = cyborg.get_action_space('Red')
assert enterprise_subnet in action_space['subnet']
assert action_space['subnet'][enterprise_subnet]
action = DiscoverRemoteSystems(agent='Red', subnet=enterprise_subnet, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Enterprise2', reward)
# scan the third enterprise host
enterprise2_ip = cyborg.environment_controller.hostname_ip_map['Enterprise2']
assert enterprise2_ip in action_space['ip_address']
assert action_space['ip_address'][enterprise2_ip]
action = DiscoverNetworkServices(agent='Red', ip_address=enterprise2_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Enterprise2', reward)
# exploit the 3rd enterprise host
action = ExploitRemoteService(agent='Red', ip_address=enterprise2_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'Enterprise2': {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Enterprise2', reward)
# priv esc on enterprise host
assert 'Enterprise2' in action_space['hostname']
assert action_space['hostname']['Enterprise2']
action = PrivilegeEscalate(agent='Red', hostname='Enterprise2', session=session)
result = cyborg.step('Red', action)
expected_observation = {'Enterprise2': {'Files': [windows_reverse_shell,
windows_potato_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
blue_analyse(expected_observation, 'Enterprise2', reward)
# scan the op server
op_server_ip = cyborg.environment_controller.hostname_ip_map['Op_Server0']
assert op_server_ip in action_space['ip_address']
assert action_space['ip_address'][op_server_ip]
action = DiscoverNetworkServices(agent='Red', ip_address=op_server_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Op_Server0', reward)
# exploit the op server
count = 9
action = ExploitRemoteService(agent='Red', ip_address=op_server_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Op_Server0', reward)
# priv esc on op server
action = PrivilegeEscalate(agent='Red', hostname='Op_Server0', session=session)
result = cyborg.step('Red', action)
expected_observation = {'Op_Server0': {'Files': [linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
blue_analyse(expected_observation, 'Op_Server0', reward)
action = Impact(agent='Red', hostname='Op_Server0', session=session)
result = cyborg.step('Red', action)
expected_observation = {'Op_Server0': {'Files': [linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Op_Server0', reward=reward-10.0)
@pytest.fixture()
def cyborg(request,agents = {'Red':B_lineAgent},seed = 1):
path = str(inspect.getfile(CybORG))
path = path[:-10] + '/Shared/Scenarios/Scenario1b.yaml'
cyborg = CybORG(path, 'sim', agents=agents)
cyborg.set_seed(seed)
return cyborg
def test_analyse_bug_aug19(cyborg):
cyborg.reset()
for i in range(10):
action = Analyse(session=0,agent='Blue',hostname='Enterprise0')
results = cyborg.step(action=action,agent='Blue')
obs = results.observation
for hostid, host in obs.items():
if hostid == 'success':
continue
if hostid != 'Enterprise0':
assert 'Processes' in host, f'repeats: {i}'
for process in host['Processes']:
assert 'Connections' in process
| 48.580858 | 114 | 0.640014 |
import inspect
from CybORG import CybORG
from CybORG.Shared.Actions import DiscoverRemoteSystems, DiscoverNetworkServices, ExploitRemoteService, \
PrivilegeEscalate, Impact, Analyse
from CybORG.Shared.Enums import TrinaryEnum, FileType, Path
from CybORG.Tests.EphemeralPort import Win2008EphemeralPort, LinuxEphemeralPort
from CybORG.Tests.test_sim.test_Acceptance.test_reward_function import security_values, availability_values
import pytest
from CybORG.Agents import B_lineAgent
@pytest.mark.skip()
def test_blue_analyse_on_red_killchain(security_values,availability_values):
path = str(inspect.getfile(CybORG))
path = path[:-10] + '/Shared/Scenarios/Scenario1b.yaml'
cyborg = CybORG(path, 'sim')
blue_session = cyborg.get_observation('Blue')['Defender']['Sessions'][0]['ID']
blue_hosts = cyborg.get_action_space('Blue')['hostname']
def blue_analyse(expected_result, host, reward=0.0):
blue_action = Analyse(session=blue_session, agent='Blue', hostname=host)
results = cyborg.step('Blue', blue_action)
assert not results.done
assert results.reward == round(reward, 1)
assert results.observation == expected_result
windows_reverse_shell = {'Density': 0.9,
'File Name': 'cmd.exe',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': 'C:\\temp\\',
'Signed': False}
linux_reverse_shell = {'Density': 0.9,
'File Name': 'cmd.sh',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': '/tmp/',
'Signed': False}
windows_potato_exploit = {'Density': 0.9,
'File Name': 'escalate.exe',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': 'C:\\temp\\',
'Signed': False}
linux_kernel_exploit = {'Density': 0.9,
'File Name': 'escalate.sh',
'Known File': FileType.UNKNOWN,
'Known Path': Path.TEMP,
'Path': '/tmp/',
'Signed': False}
action_space = cyborg.get_action_space('Red')
initial_observation = cyborg.get_observation('Red')
session = list(action_space['session'].keys())[0]
for subnet in action_space["subnet"]:
expected_observation = {'success': TrinaryEnum.TRUE}
action = DiscoverRemoteSystems(subnet=subnet, agent='Red', session=session)
cyborg.step(action=action, agent='Red')
for host in blue_hosts:
blue_analyse(expected_observation, host)
addresses = [i for i in action_space["ip_address"]]
attacker_address = cyborg.environment_controller.hostname_ip_map['User0']
for address in addresses:
expected_observation = {'success': TrinaryEnum.TRUE}
action = DiscoverNetworkServices(agent='Red', ip_address=address, session=session)
cyborg.step(action=action, agent='Red')
for host in blue_hosts:
blue_analyse(expected_observation, host)
reward = 0
for address in addresses:
action = ExploitRemoteService(agent='Red', ip_address=address, session=session)
cyborg.step(action=action, agent='Red')
hostname = {v: i for i, v in cyborg.environment_controller.hostname_ip_map.items()}[address]
if not action_space["ip_address"][address]:
expected_observation = {'success': TrinaryEnum.TRUE}
elif address == cyborg.environment_controller.hostname_ip_map['User0'] or address == \
cyborg.environment_controller.hostname_ip_map['User1'] or address == \
cyborg.environment_controller.hostname_ip_map['User2']:
expected_observation = {hostname: {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
reward += security_values[hostname][0]
elif address == cyborg.environment_controller.hostname_ip_map['User3'] or address == \
cyborg.environment_controller.hostname_ip_map['User4']:
expected_observation = {hostname: {'Files': [linux_reverse_shell]},
'success': TrinaryEnum.TRUE}
else:
raise NotImplementedError
blue_analyse(expected_observation, hostname, reward)
action_space = cyborg.get_action_space('Red')
hostnames = action_space['hostname']
count = 2
for hostname in hostnames:
action = PrivilegeEscalate(agent='Red', hostname=hostname, session=session)
cyborg.step(action=action, agent='Red')
if hostnames[hostname]:
last_action = cyborg.get_last_action('Red')
assert last_action == action
if 'User' in hostname:
if '0' in hostname or '1' in hostname or '2' in hostname:
expected_observation = {hostname: {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
else:
expected_observation = {hostname: {'Files': [linux_reverse_shell,
linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
reward += security_values[hostname][1]
else:
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, host=hostname, reward=reward)
action_space = cyborg.get_action_space('Red')
addresses = [i for i in action_space["ip_address"]]
for address in addresses:
if not action_space["ip_address"][address] \
or address == cyborg.environment_controller.hostname_ip_map['User0'] \
or address == cyborg.environment_controller.hostname_ip_map['User1'] \
or address == cyborg.environment_controller.hostname_ip_map['User2'] \
or address == cyborg.environment_controller.hostname_ip_map['User3'] \
or address == cyborg.environment_controller.hostname_ip_map['User4']:
continue
else:
expected_observation = {'success': TrinaryEnum.TRUE}
hostname = {v: i for i, v in cyborg.environment_controller.hostname_ip_map.items()}[address]
action = DiscoverNetworkServices(agent='Red', ip_address=address, session=session)
result = cyborg.step(action=action, agent='Red')
blue_analyse(expected_observation, hostname, reward)
action_space = cyborg.get_action_space('Red')
addresses = [i for i in action_space["ip_address"]]
for address in addresses:
hostname = {v: i for i, v in cyborg.environment_controller.hostname_ip_map.items()}[address]
if not action_space["ip_address"][address] \
or address == cyborg.environment_controller.hostname_ip_map['User0'] \
or address == cyborg.environment_controller.hostname_ip_map['User1'] \
or address == cyborg.environment_controller.hostname_ip_map['User2'] \
or address == cyborg.environment_controller.hostname_ip_map['User3'] \
or address == cyborg.environment_controller.hostname_ip_map['User4']:
continue
elif address == cyborg.environment_controller.hostname_ip_map['Enterprise0']:
expected_observation = {'success': TrinaryEnum.TRUE}
count += 1
elif address == cyborg.environment_controller.hostname_ip_map['Enterprise1']:
expected_observation = {hostname: {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
count += 1
else:
raise ValueError
action = ExploitRemoteService(agent='Red', ip_address=address, session=session)
cyborg.step(action=action, agent='Red')
blue_analyse(expected_observation, hostname, reward)
enterprise_subnet = cyborg.environment_controller.subnet_cidr_map['Enterprise']
action_space = cyborg.get_action_space('Red')
hostnames = action_space['hostname']
count = 6
for hostname in hostnames:
if 'User' in hostname:
continue
action = PrivilegeEscalate(agent='Red', hostname=hostname, session=session)
result = cyborg.step(action=action, agent='Red')
if hostname == 'Enterprise0':
expected_observation = {'Enterprise0': {'Files': [linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
elif hostname == 'Enterprise1':
expected_observation = {'Enterprise1': {'Files': [windows_reverse_shell,
windows_potato_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
else:
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, hostname, reward)
action_space = cyborg.get_action_space('Red')
assert enterprise_subnet in action_space['subnet']
assert action_space['subnet'][enterprise_subnet]
action = DiscoverRemoteSystems(agent='Red', subnet=enterprise_subnet, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Enterprise2', reward)
enterprise2_ip = cyborg.environment_controller.hostname_ip_map['Enterprise2']
assert enterprise2_ip in action_space['ip_address']
assert action_space['ip_address'][enterprise2_ip]
action = DiscoverNetworkServices(agent='Red', ip_address=enterprise2_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Enterprise2', reward)
action = ExploitRemoteService(agent='Red', ip_address=enterprise2_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'Enterprise2': {'Files': [windows_reverse_shell]},
'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Enterprise2', reward)
assert 'Enterprise2' in action_space['hostname']
assert action_space['hostname']['Enterprise2']
action = PrivilegeEscalate(agent='Red', hostname='Enterprise2', session=session)
result = cyborg.step('Red', action)
expected_observation = {'Enterprise2': {'Files': [windows_reverse_shell,
windows_potato_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
blue_analyse(expected_observation, 'Enterprise2', reward)
op_server_ip = cyborg.environment_controller.hostname_ip_map['Op_Server0']
assert op_server_ip in action_space['ip_address']
assert action_space['ip_address'][op_server_ip]
action = DiscoverNetworkServices(agent='Red', ip_address=op_server_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Op_Server0', reward)
count = 9
action = ExploitRemoteService(agent='Red', ip_address=op_server_ip, session=session)
result = cyborg.step('Red', action)
expected_observation = {'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Op_Server0', reward)
action = PrivilegeEscalate(agent='Red', hostname='Op_Server0', session=session)
result = cyborg.step('Red', action)
expected_observation = {'Op_Server0': {'Files': [linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
reward += -1.0
blue_analyse(expected_observation, 'Op_Server0', reward)
action = Impact(agent='Red', hostname='Op_Server0', session=session)
result = cyborg.step('Red', action)
expected_observation = {'Op_Server0': {'Files': [linux_kernel_exploit]},
'success': TrinaryEnum.TRUE}
blue_analyse(expected_observation, 'Op_Server0', reward=reward-10.0)
@pytest.fixture()
def cyborg(request,agents = {'Red':B_lineAgent},seed = 1):
path = str(inspect.getfile(CybORG))
path = path[:-10] + '/Shared/Scenarios/Scenario1b.yaml'
cyborg = CybORG(path, 'sim', agents=agents)
cyborg.set_seed(seed)
return cyborg
def test_analyse_bug_aug19(cyborg):
cyborg.reset()
for i in range(10):
action = Analyse(session=0,agent='Blue',hostname='Enterprise0')
results = cyborg.step(action=action,agent='Blue')
obs = results.observation
for hostid, host in obs.items():
if hostid == 'success':
continue
if hostid != 'Enterprise0':
assert 'Processes' in host, f'repeats: {i}'
for process in host['Processes']:
assert 'Connections' in process
| true | true |
f72c237205ee71fae08437e7206ee77f08a6cd89 | 802 | py | Python | mfgp/task2/init_train_idxs.py | kunalghosh/Multi_Fidelity_Prediction_GP | c858554f5c1f0c4aafa12cf7c441bd2d56b115f5 | [
"BSD-3-Clause"
] | null | null | null | mfgp/task2/init_train_idxs.py | kunalghosh/Multi_Fidelity_Prediction_GP | c858554f5c1f0c4aafa12cf7c441bd2d56b115f5 | [
"BSD-3-Clause"
] | 3 | 2021-08-31T08:53:49.000Z | 2021-10-05T15:10:42.000Z | mfgp/task2/init_train_idxs.py | kunalghosh/Multi_Fidelity_Prediction_GP | c858554f5c1f0c4aafa12cf7c441bd2d56b115f5 | [
"BSD-3-Clause"
] | null | null | null | # Run `init_train_idxs.py <int: dataset size> <int: initial training set size>`:
# Creates a `train_idxs.npz` file with the initial set of training indices.
# e.g `python init_train_idxs.py 64000 1000`
import sys
import numpy as np
from sklearn.model_selection import train_test_split
dataset_size = int(sys.argv[1])
init_trainset_size = int(sys.argv[2])
validation_set_size = 500 # usually training set is much larger so 500 is reasonable
np.random.seed(1)
train_idxs, remaining_idxs = train_test_split(range(dataset_size), train_size = init_trainset_size, random_state=0)
valid_idxs, test_idxs = train_test_split(remaining_idxs, train_size = 500, random_state=0)
# save the values in train_idxs.npy
np.savez("train_idxs.npz", train_idxs=train_idxs, valid_idxs=valid_idxs, test_idxs=test_idxs)
| 40.1 | 115 | 0.794264 |
import sys
import numpy as np
from sklearn.model_selection import train_test_split
dataset_size = int(sys.argv[1])
init_trainset_size = int(sys.argv[2])
validation_set_size = 500
np.random.seed(1)
train_idxs, remaining_idxs = train_test_split(range(dataset_size), train_size = init_trainset_size, random_state=0)
valid_idxs, test_idxs = train_test_split(remaining_idxs, train_size = 500, random_state=0)
np.savez("train_idxs.npz", train_idxs=train_idxs, valid_idxs=valid_idxs, test_idxs=test_idxs)
| true | true |
f72c2414f2962eb27d54c0fb810c1358dceaa89f | 3,325 | py | Python | tools/visualize_json_results.py | hhy-ee/PedestrianDetection-NohNMS | 482078a6bd0ff8cf03fbf7f6988e475f75c56e57 | [
"Apache-2.0"
] | null | null | null | tools/visualize_json_results.py | hhy-ee/PedestrianDetection-NohNMS | 482078a6bd0ff8cf03fbf7f6988e475f75c56e57 | [
"Apache-2.0"
] | null | null | null | tools/visualize_json_results.py | hhy-ee/PedestrianDetection-NohNMS | 482078a6bd0ff8cf03fbf7f6988e475f75c56e57 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import json
import numpy as np
import os
from collections import defaultdict
import cv2
import tqdm
from fvcore.common.file_io import PathManager
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.structures import Boxes, BoxMode, Instances
from detectron2.utils.logger import setup_logger
from detectron2.utils.visualizer import Visualizer
def create_instances(predictions, image_size):
ret = Instances(image_size)
score = np.asarray([x["score"] for x in predictions])
chosen = (score > args.conf_threshold).nonzero()[0]
if chosen.shape[0] == 0:
return None
score = score[chosen]
bbox = np.asarray([predictions[i]["bbox"] for i in chosen])
bbox = BoxMode.convert(bbox, BoxMode.XYWH_ABS, BoxMode.XYXY_ABS)
labels = np.asarray([dataset_id_map(predictions[i]["category_id"]) for i in chosen])
ret.scores = score
ret.pred_boxes = Boxes(bbox)
ret.pred_classes = labels
try:
ret.pred_masks = [predictions[i]["segmentation"] for i in chosen]
except KeyError:
pass
return ret
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="A script that visualizes the json predictions from COCO or LVIS dataset."
)
parser.add_argument("--input", required=True, help="JSON file produced by the model")
parser.add_argument("--output", required=True, help="output directory")
parser.add_argument("--dataset", help="name of the dataset", default="coco_2017_val")
parser.add_argument("--conf-threshold", default=0.5, type=float, help="confidence threshold")
args = parser.parse_args()
logger = setup_logger()
with PathManager.open(args.input, "r") as f:
predictions = json.load(f)
pred_by_image = defaultdict(list)
for p in predictions:
pred_by_image[p["image_id"]].append(p)
dicts = list(DatasetCatalog.get(args.dataset))
metadata = MetadataCatalog.get(args.dataset)
if hasattr(metadata, "thing_dataset_id_to_contiguous_id"):
def dataset_id_map(ds_id):
return metadata.thing_dataset_id_to_contiguous_id[ds_id]
elif "lvis" in args.dataset:
# LVIS results are in the same format as COCO results, but have a different
# mapping from dataset category id to contiguous category id in [0, #categories - 1]
def dataset_id_map(ds_id):
return ds_id - 1
else:
raise ValueError("Unsupported dataset: {}".format(args.dataset))
os.makedirs(args.output, exist_ok=True)
for dic in tqdm.tqdm(dicts):
img = cv2.imread(dic["file_name"], cv2.IMREAD_COLOR)[:, :, ::-1]
basename = os.path.basename(dic["file_name"])
predictions = create_instances(pred_by_image[dic["image_id"]], img.shape[:2])
if predictions is not None:
vis = Visualizer(img, metadata)
vis_pred = vis.draw_instance_predictions(predictions).get_image()
else:
vis_pred = img
vis = Visualizer(img, metadata)
vis_gt = vis.draw_dataset_dict(dic).get_image()
concat = np.concatenate((vis_pred, vis_gt), axis=0)
cv2.imwrite(os.path.join(args.output, basename), concat[:, :, ::-1])
| 34.635417 | 97 | 0.687519 |
import argparse
import json
import numpy as np
import os
from collections import defaultdict
import cv2
import tqdm
from fvcore.common.file_io import PathManager
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.structures import Boxes, BoxMode, Instances
from detectron2.utils.logger import setup_logger
from detectron2.utils.visualizer import Visualizer
def create_instances(predictions, image_size):
ret = Instances(image_size)
score = np.asarray([x["score"] for x in predictions])
chosen = (score > args.conf_threshold).nonzero()[0]
if chosen.shape[0] == 0:
return None
score = score[chosen]
bbox = np.asarray([predictions[i]["bbox"] for i in chosen])
bbox = BoxMode.convert(bbox, BoxMode.XYWH_ABS, BoxMode.XYXY_ABS)
labels = np.asarray([dataset_id_map(predictions[i]["category_id"]) for i in chosen])
ret.scores = score
ret.pred_boxes = Boxes(bbox)
ret.pred_classes = labels
try:
ret.pred_masks = [predictions[i]["segmentation"] for i in chosen]
except KeyError:
pass
return ret
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="A script that visualizes the json predictions from COCO or LVIS dataset."
)
parser.add_argument("--input", required=True, help="JSON file produced by the model")
parser.add_argument("--output", required=True, help="output directory")
parser.add_argument("--dataset", help="name of the dataset", default="coco_2017_val")
parser.add_argument("--conf-threshold", default=0.5, type=float, help="confidence threshold")
args = parser.parse_args()
logger = setup_logger()
with PathManager.open(args.input, "r") as f:
predictions = json.load(f)
pred_by_image = defaultdict(list)
for p in predictions:
pred_by_image[p["image_id"]].append(p)
dicts = list(DatasetCatalog.get(args.dataset))
metadata = MetadataCatalog.get(args.dataset)
if hasattr(metadata, "thing_dataset_id_to_contiguous_id"):
def dataset_id_map(ds_id):
return metadata.thing_dataset_id_to_contiguous_id[ds_id]
elif "lvis" in args.dataset:
aset_id_map(ds_id):
return ds_id - 1
else:
raise ValueError("Unsupported dataset: {}".format(args.dataset))
os.makedirs(args.output, exist_ok=True)
for dic in tqdm.tqdm(dicts):
img = cv2.imread(dic["file_name"], cv2.IMREAD_COLOR)[:, :, ::-1]
basename = os.path.basename(dic["file_name"])
predictions = create_instances(pred_by_image[dic["image_id"]], img.shape[:2])
if predictions is not None:
vis = Visualizer(img, metadata)
vis_pred = vis.draw_instance_predictions(predictions).get_image()
else:
vis_pred = img
vis = Visualizer(img, metadata)
vis_gt = vis.draw_dataset_dict(dic).get_image()
concat = np.concatenate((vis_pred, vis_gt), axis=0)
cv2.imwrite(os.path.join(args.output, basename), concat[:, :, ::-1])
| true | true |
f72c262fa25643ba7ad1ef2d7e89c9bd6e9b9e00 | 1,084 | py | Python | redis_cache/compat.py | fu2re/django-redis-cache | 50807ae71bac0714ee625b443205153e9d917e54 | [
"BSD-3-Clause"
] | null | null | null | redis_cache/compat.py | fu2re/django-redis-cache | 50807ae71bac0714ee625b443205153e9d917e54 | [
"BSD-3-Clause"
] | null | null | null | redis_cache/compat.py | fu2re/django-redis-cache | 50807ae71bac0714ee625b443205153e9d917e54 | [
"BSD-3-Clause"
] | 1 | 2020-02-18T13:20:21.000Z | 2020-02-18T13:20:21.000Z | import sys
import django
PY3 = (sys.version_info >= (3,))
try:
# Django 1.5+
from django.utils.encoding import smart_text, smart_bytes
except ImportError:
# older Django, thus definitely Python 2
from django.utils.encoding import smart_unicode, smart_str
smart_text = smart_unicode
smart_bytes = smart_str
if PY3:
bytes_type = bytes
else:
bytes_type = str
if django.VERSION[:2] >= (1, 6):
from django.core.cache.backends.base import DEFAULT_TIMEOUT as DJANGO_DEFAULT_TIMEOUT
DEFAULT_TIMEOUT = DJANGO_DEFAULT_TIMEOUT
else:
DEFAULT_TIMEOUT = None
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
Backported from Django 1.5+.
"""
if not PY3:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
| 25.809524 | 89 | 0.714945 | import sys
import django
PY3 = (sys.version_info >= (3,))
try:
from django.utils.encoding import smart_text, smart_bytes
except ImportError:
from django.utils.encoding import smart_unicode, smart_str
smart_text = smart_unicode
smart_bytes = smart_str
if PY3:
bytes_type = bytes
else:
bytes_type = str
if django.VERSION[:2] >= (1, 6):
from django.core.cache.backends.base import DEFAULT_TIMEOUT as DJANGO_DEFAULT_TIMEOUT
DEFAULT_TIMEOUT = DJANGO_DEFAULT_TIMEOUT
else:
DEFAULT_TIMEOUT = None
def python_2_unicode_compatible(klass):
if not PY3:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
| true | true |
f72c26bb4fa6463bbf958a86e7df8748e04888fa | 30,608 | py | Python | mwparserfromhell/wikicode.py | TheSandDoctor/mwparserfromhell | de15b8b64497d3386f133400b73dcaf36a131743 | [
"MIT"
] | null | null | null | mwparserfromhell/wikicode.py | TheSandDoctor/mwparserfromhell | de15b8b64497d3386f133400b73dcaf36a131743 | [
"MIT"
] | null | null | null | mwparserfromhell/wikicode.py | TheSandDoctor/mwparserfromhell | de15b8b64497d3386f133400b73dcaf36a131743 | [
"MIT"
] | null | null | null | #
# Copyright (C) 2012-2019 Ben Kurtovic <ben.kurtovic@gmail.com>
#
# 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.
import re
from itertools import chain
from .nodes import (Argument, Comment, ExternalLink, Heading, HTMLEntity,
Node, Tag, Template, Text, Wikilink)
from .smart_list.ListProxy import _ListProxy
from .string_mixin import StringMixIn
from .utils import parse_anything
__all__ = ["Wikicode"]
FLAGS = re.IGNORECASE | re.DOTALL | re.UNICODE
class Wikicode(StringMixIn):
"""A ``Wikicode`` is a container for nodes that operates like a string.
Additionally, it contains methods that can be used to extract data from or
modify the nodes, implemented in an interface similar to a list. For
example, :meth:`index` can get the index of a node in the list, and
:meth:`insert` can add a new node at that index. The :meth:`filter()
<ifilter>` series of functions is very useful for extracting and iterating
over, for example, all of the templates in the object.
"""
RECURSE_OTHERS = 2
def __init__(self, nodes):
super().__init__()
self._nodes = nodes
def __unicode__(self):
return "".join([str(node) for node in self.nodes])
@staticmethod
def _get_children(node, contexts=False, restrict=None, parent=None):
"""Iterate over all child :class:`.Node`\\ s of a given *node*."""
yield (parent, node) if contexts else node
if restrict and isinstance(node, restrict):
return
for code in node.__children__():
for child in code.nodes:
sub = Wikicode._get_children(child, contexts, restrict, code)
yield from sub
@staticmethod
def _slice_replace(code, index, old, new):
"""Replace the string *old* with *new* across *index* in *code*."""
nodes = [str(node) for node in code.get(index)]
substring = "".join(nodes).replace(old, new)
code.nodes[index] = parse_anything(substring).nodes
@staticmethod
def _build_matcher(matches, flags):
"""Helper for :meth:`_indexed_ifilter` and others.
If *matches* is a function, return it. If it's a regex, return a
wrapper around it that can be called with a node to do a search. If
it's ``None``, return a function that always returns ``True``.
"""
if matches:
if callable(matches):
return matches
return lambda obj: re.search(matches, str(obj), flags)
return lambda obj: True
def _indexed_ifilter(self, recursive=True, matches=None, flags=FLAGS,
forcetype=None):
"""Iterate over nodes and their corresponding indices in the node list.
The arguments are interpreted as for :meth:`ifilter`. For each tuple
``(i, node)`` yielded by this method, ``self.index(node) == i``. Note
that if *recursive* is ``True``, ``self.nodes[i]`` might not be the
node itself, but will still contain it.
"""
match = self._build_matcher(matches, flags)
if recursive:
restrict = forcetype if recursive == self.RECURSE_OTHERS else None
def getter(i, node):
for ch in self._get_children(node, restrict=restrict):
yield (i, ch)
inodes = chain(*(getter(i, n) for i, n in enumerate(self.nodes)))
else:
inodes = enumerate(self.nodes)
for i, node in inodes:
if (not forcetype or isinstance(node, forcetype)) and match(node):
yield (i, node)
def _is_child_wikicode(self, obj, recursive=True):
"""Return whether the given :class:`.Wikicode` is a descendant."""
def deref(nodes):
if isinstance(nodes, _ListProxy):
return nodes._parent # pylint: disable=protected-access
return nodes
target = deref(obj.nodes)
if target is deref(self.nodes):
return True
if recursive:
todo = [self]
while todo:
code = todo.pop()
if target is deref(code.nodes):
return True
for node in code.nodes:
todo += list(node.__children__())
return False
def _do_strong_search(self, obj, recursive=True):
"""Search for the specific element *obj* within the node list.
*obj* can be either a :class:`.Node` or a :class:`.Wikicode` object. If
found, we return a tuple (*context*, *index*) where *context* is the
:class:`.Wikicode` that contains *obj* and *index* is its index there,
as a :class:`slice`. Note that if *recursive* is ``False``, *context*
will always be ``self`` (since we only look for *obj* among immediate
descendants), but if *recursive* is ``True``, then it could be any
:class:`.Wikicode` contained by a node within ``self``. If *obj* is not
found, :exc:`ValueError` is raised.
"""
if isinstance(obj, Wikicode):
if not self._is_child_wikicode(obj, recursive):
raise ValueError(obj)
return obj, slice(0, len(obj.nodes))
if isinstance(obj, Node):
mkslice = lambda i: slice(i, i + 1)
if not recursive:
return self, mkslice(self.index(obj))
for node in self.nodes:
for context, child in self._get_children(node, contexts=True):
if obj is child:
if not context:
context = self
return context, mkslice(context.index(child))
raise ValueError(obj)
raise TypeError(obj)
def _do_weak_search(self, obj, recursive):
"""Search for an element that looks like *obj* within the node list.
This follows the same rules as :meth:`_do_strong_search` with some
differences. *obj* is treated as a string that might represent any
:class:`.Node`, :class:`.Wikicode`, or combination of the two present
in the node list. Thus, matching is weak (using string comparisons)
rather than strong (using ``is``). Because multiple nodes can match
*obj*, the result is a list of tuples instead of just one (however,
:exc:`ValueError` is still raised if nothing is found). Individual
matches will never overlap.
The tuples contain a new first element, *exact*, which is ``True`` if
we were able to match *obj* exactly to one or more adjacent nodes, or
``False`` if we found *obj* inside a node or incompletely spanning
multiple nodes.
"""
obj = parse_anything(obj)
if not obj or obj not in self:
raise ValueError(obj)
results = []
contexts = [self]
while contexts:
context = contexts.pop()
i = len(context.nodes) - 1
while i >= 0:
node = context.get(i)
if obj.get(-1) == node:
for j in range(-len(obj.nodes), -1):
if obj.get(j) != context.get(i + j + 1):
break
else:
i -= len(obj.nodes) - 1
index = slice(i, i + len(obj.nodes))
results.append((True, context, index))
elif recursive and obj in node:
contexts.extend(node.__children__())
i -= 1
if not results:
if not recursive:
raise ValueError(obj)
results.append((False, self, slice(0, len(self.nodes))))
return results
def _get_tree(self, code, lines, marker, indent):
"""Build a tree to illustrate the way the Wikicode object was parsed.
The method that builds the actual tree is ``__showtree__`` of ``Node``
objects. *code* is the ``Wikicode`` object to build a tree for. *lines*
is the list to append the tree to, which is returned at the end of the
method. *marker* is some object to be used to indicate that the builder
should continue on from the last line instead of starting a new one; it
should be any object that can be tested for with ``is``. *indent* is
the starting indentation.
"""
def write(*args):
"""Write a new line following the proper indentation rules."""
if lines and lines[-1] is marker: # Continue from the last line
lines.pop() # Remove the marker
last = lines.pop()
lines.append(last + " ".join(args))
else:
lines.append(" " * 6 * indent + " ".join(args))
get = lambda code: self._get_tree(code, lines, marker, indent + 1)
mark = lambda: lines.append(marker)
for node in code.nodes:
node.__showtree__(write, get, mark)
return lines
@classmethod
def _build_filter_methods(cls, **meths):
"""Given Node types, build the corresponding i?filter shortcuts.
The should be given as keys storing the method's base name paired with
values storing the corresponding :class:`.Node` type. For example, the
dict may contain the pair ``("templates", Template)``, which will
produce the methods :meth:`ifilter_templates` and
:meth:`filter_templates`, which are shortcuts for
:meth:`ifilter(forcetype=Template) <ifilter>` and
:meth:`filter(forcetype=Template) <filter>`, respectively. These
shortcuts are added to the class itself, with an appropriate docstring.
"""
doc = """Iterate over {0}.
This is equivalent to :meth:`{1}` with *forcetype* set to
:class:`~{2.__module__}.{2.__name__}`.
"""
make_ifilter = lambda ftype: (lambda self, *a, **kw:
self.ifilter(forcetype=ftype, *a, **kw))
make_filter = lambda ftype: (lambda self, *a, **kw:
self.filter(forcetype=ftype, *a, **kw))
for name, ftype in meths.items():
ifilter = make_ifilter(ftype)
filter = make_filter(ftype)
ifilter.__doc__ = doc.format(name, "ifilter", ftype)
filter.__doc__ = doc.format(name, "filter", ftype)
setattr(cls, "ifilter_" + name, ifilter)
setattr(cls, "filter_" + name, filter)
@property
def nodes(self):
"""A list of :class:`.Node` objects.
This is the internal data actually stored within a :class:`.Wikicode`
object.
"""
return self._nodes
@nodes.setter
def nodes(self, value):
if not isinstance(value, list):
value = parse_anything(value).nodes
self._nodes = value
def get(self, index):
"""Return the *index*\\ th node within the list of nodes."""
return self.nodes[index]
def set(self, index, value):
"""Set the ``Node`` at *index* to *value*.
Raises :exc:`IndexError` if *index* is out of range, or
:exc:`ValueError` if *value* cannot be coerced into one :class:`.Node`.
To insert multiple nodes at an index, use :meth:`get` with either
:meth:`remove` and :meth:`insert` or :meth:`replace`.
"""
nodes = parse_anything(value).nodes
if len(nodes) > 1:
raise ValueError("Cannot coerce multiple nodes into one index")
if index >= len(self.nodes) or -1 * index > len(self.nodes):
raise IndexError("List assignment index out of range")
if nodes:
self.nodes[index] = nodes[0]
else:
self.nodes.pop(index)
def contains(self, obj):
"""Return whether this Wikicode object contains *obj*.
If *obj* is a :class:`.Node` or :class:`.Wikicode` object, then we
search for it exactly among all of our children, recursively.
Otherwise, this method just uses :meth:`.__contains__` on the string.
"""
if not isinstance(obj, (Node, Wikicode)):
return obj in self
try:
self._do_strong_search(obj, recursive=True)
except ValueError:
return False
return True
def index(self, obj, recursive=False):
"""Return the index of *obj* in the list of nodes.
Raises :exc:`ValueError` if *obj* is not found. If *recursive* is
``True``, we will look in all nodes of ours and their descendants, and
return the index of our direct descendant node within *our* list of
nodes. Otherwise, the lookup is done only on direct descendants.
"""
strict = isinstance(obj, Node)
equivalent = (lambda o, n: o is n) if strict else (lambda o, n: o == n)
for i, node in enumerate(self.nodes):
if recursive:
for child in self._get_children(node):
if equivalent(obj, child):
return i
elif equivalent(obj, node):
return i
raise ValueError(obj)
def get_ancestors(self, obj):
"""Return a list of all ancestor nodes of the :class:`.Node` *obj*.
The list is ordered from the most shallow ancestor (greatest great-
grandparent) to the direct parent. The node itself is not included in
the list. For example::
>>> text = "{{a|{{b|{{c|{{d}}}}}}}}"
>>> code = mwparserfromhell.parse(text)
>>> node = code.filter_templates(matches=lambda n: n == "{{d}}")[0]
>>> code.get_ancestors(node)
['{{a|{{b|{{c|{{d}}}}}}}}', '{{b|{{c|{{d}}}}}}', '{{c|{{d}}}}']
Will return an empty list if *obj* is at the top level of this Wikicode
object. Will raise :exc:`ValueError` if it wasn't found.
"""
def _get_ancestors(code, needle):
for node in code.nodes:
if node is needle:
return []
for code in node.__children__():
ancestors = _get_ancestors(code, needle)
if ancestors is not None:
return [node] + ancestors
if isinstance(obj, Wikicode):
obj = obj.get(0)
elif not isinstance(obj, Node):
raise ValueError(obj)
ancestors = _get_ancestors(self, obj)
if ancestors is None:
raise ValueError(obj)
return ancestors
def get_parent(self, obj):
"""Return the direct parent node of the :class:`.Node` *obj*.
This function is equivalent to calling :meth:`.get_ancestors` and
taking the last element of the resulting list. Will return None if
the node exists but does not have a parent; i.e., it is at the top
level of the Wikicode object.
"""
ancestors = self.get_ancestors(obj)
return ancestors[-1] if ancestors else None
def insert(self, index, value):
"""Insert *value* at *index* in the list of nodes.
*value* can be anything parsable by :func:`.parse_anything`, which
includes strings or other :class:`.Wikicode` or :class:`.Node` objects.
"""
nodes = parse_anything(value).nodes
for node in reversed(nodes):
self.nodes.insert(index, node)
def insert_before(self, obj, value, recursive=True):
"""Insert *value* immediately before *obj*.
*obj* can be either a string, a :class:`.Node`, or another
:class:`.Wikicode` object (as created by :meth:`get_sections`, for
example). If *obj* is a string, we will operate on all instances of
that string within the code, otherwise only on the specific instance
given. *value* can be anything parsable by :func:`.parse_anything`. If
*recursive* is ``True``, we will try to find *obj* within our child
nodes even if it is not a direct descendant of this :class:`.Wikicode`
object. If *obj* is not found, :exc:`ValueError` is raised.
"""
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
context.insert(index.start, value)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
context.insert(index.start, value)
else:
obj = str(obj)
self._slice_replace(context, index, obj, str(value) + obj)
def insert_after(self, obj, value, recursive=True):
"""Insert *value* immediately after *obj*.
*obj* can be either a string, a :class:`.Node`, or another
:class:`.Wikicode` object (as created by :meth:`get_sections`, for
example). If *obj* is a string, we will operate on all instances of
that string within the code, otherwise only on the specific instance
given. *value* can be anything parsable by :func:`.parse_anything`. If
*recursive* is ``True``, we will try to find *obj* within our child
nodes even if it is not a direct descendant of this :class:`.Wikicode`
object. If *obj* is not found, :exc:`ValueError` is raised.
"""
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
context.insert(index.stop, value)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
context.insert(index.stop, value)
else:
obj = str(obj)
self._slice_replace(context, index, obj, obj + str(value))
def replace(self, obj, value, recursive=True):
"""Replace *obj* with *value*.
*obj* can be either a string, a :class:`.Node`, or another
:class:`.Wikicode` object (as created by :meth:`get_sections`, for
example). If *obj* is a string, we will operate on all instances of
that string within the code, otherwise only on the specific instance
given. *value* can be anything parsable by :func:`.parse_anything`.
If *recursive* is ``True``, we will try to find *obj* within our child
nodes even if it is not a direct descendant of this :class:`.Wikicode`
object. If *obj* is not found, :exc:`ValueError` is raised.
"""
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
context.insert(index.start, value)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
context.insert(index.start, value)
else:
self._slice_replace(context, index, str(obj), str(value))
def append(self, value):
"""Insert *value* at the end of the list of nodes.
*value* can be anything parsable by :func:`.parse_anything`.
"""
nodes = parse_anything(value).nodes
for node in nodes:
self.nodes.append(node)
def remove(self, obj, recursive=True):
"""Remove *obj* from the list of nodes.
*obj* can be either a string, a :class:`.Node`, or another
:class:`.Wikicode` object (as created by :meth:`get_sections`, for
example). If *obj* is a string, we will operate on all instances of
that string within the code, otherwise only on the specific instance
given. If *recursive* is ``True``, we will try to find *obj* within our
child nodes even if it is not a direct descendant of this
:class:`.Wikicode` object. If *obj* is not found, :exc:`ValueError` is
raised.
"""
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
else:
self._slice_replace(context, index, str(obj), "")
def matches(self, other):
"""Do a loose equivalency test suitable for comparing page names.
*other* can be any string-like object, including :class:`.Wikicode`, or
an iterable of these. This operation is symmetric; both sides are
adjusted. Specifically, whitespace and markup is stripped and the first
letter's case is normalized. Typical usage is
``if template.name.matches("stub"): ...``.
"""
normalize = lambda s: (s[0].upper() + s[1:]).replace("_", " ") if s else s
this = normalize(self.strip_code().strip())
if isinstance(other, (str, bytes, Wikicode, Node)):
that = parse_anything(other).strip_code().strip()
return this == normalize(that)
for obj in other:
that = parse_anything(obj).strip_code().strip()
if this == normalize(that):
return True
return False
def ifilter(self, recursive=True, matches=None, flags=FLAGS,
forcetype=None):
"""Iterate over nodes in our list matching certain conditions.
If *forcetype* is given, only nodes that are instances of this type (or
tuple of types) are yielded. Setting *recursive* to ``True`` will
iterate over all children and their descendants. ``RECURSE_OTHERS``
will only iterate over children that are not the instances of
*forcetype*. ``False`` will only iterate over immediate children.
``RECURSE_OTHERS`` can be used to iterate over all un-nested templates,
even if they are inside of HTML tags, like so:
>>> code = mwparserfromhell.parse("{{foo}}<b>{{foo|{{bar}}}}</b>")
>>> code.filter_templates(code.RECURSE_OTHERS)
["{{foo}}", "{{foo|{{bar}}}}"]
*matches* can be used to further restrict the nodes, either as a
function (taking a single :class:`.Node` and returning a boolean) or a
regular expression (matched against the node's string representation
with :func:`re.search`). If *matches* is a regex, the flags passed to
:func:`re.search` are :const:`re.IGNORECASE`, :const:`re.DOTALL`, and
:const:`re.UNICODE`, but custom flags can be specified by passing
*flags*.
"""
gen = self._indexed_ifilter(recursive, matches, flags, forcetype)
return (node for i, node in gen)
def filter(self, *args, **kwargs):
"""Return a list of nodes within our list matching certain conditions.
This is equivalent to calling :func:`list` on :meth:`ifilter`.
"""
return list(self.ifilter(*args, **kwargs))
def get_sections(self, levels=None, matches=None, flags=FLAGS, flat=False,
include_lead=None, include_headings=True):
"""Return a list of sections within the page.
Sections are returned as :class:`.Wikicode` objects with a shared node
list (implemented using :class:`.SmartList`) so that changes to
sections are reflected in the parent Wikicode object.
Each section contains all of its subsections, unless *flat* is
``True``. If *levels* is given, it should be a iterable of integers;
only sections whose heading levels are within it will be returned. If
*matches* is given, it should be either a function or a regex; only
sections whose headings match it (without the surrounding equal signs)
will be included. *flags* can be used to override the default regex
flags (see :meth:`ifilter`) if a regex *matches* is used.
If *include_lead* is ``True``, the first, lead section (without a
heading) will be included in the list; ``False`` will not include it;
the default will include it only if no specific *levels* were given. If
*include_headings* is ``True``, the section's beginning
:class:`.Heading` object will be included; otherwise, this is skipped.
"""
title_matcher = self._build_matcher(matches, flags)
matcher = lambda heading: (title_matcher(heading.title) and
(not levels or heading.level in levels))
iheadings = self._indexed_ifilter(recursive=False, forcetype=Heading)
sections = [] # Tuples of (index_of_first_node, section)
open_headings = [] # Tuples of (index, heading), where index and
# heading.level are both monotonically increasing
# Add the lead section if appropriate:
if include_lead or not (include_lead is not None or matches or levels):
itr = self._indexed_ifilter(recursive=False, forcetype=Heading)
try:
first = next(itr)[0]
sections.append((0, Wikicode(self.nodes[:first])))
except StopIteration: # No headings in page
sections.append((0, Wikicode(self.nodes[:])))
# Iterate over headings, adding sections to the list as they end:
for i, heading in iheadings:
if flat: # With flat, all sections close at the next heading
newly_closed, open_headings = open_headings, []
else: # Otherwise, figure out which sections have closed, if any
closed_start_index = len(open_headings)
for j, (start, last_heading) in enumerate(open_headings):
if heading.level <= last_heading.level:
closed_start_index = j
break
newly_closed = open_headings[closed_start_index:]
del open_headings[closed_start_index:]
for start, closed_heading in newly_closed:
if matcher(closed_heading):
sections.append((start, Wikicode(self.nodes[start:i])))
start = i if include_headings else (i + 1)
open_headings.append((start, heading))
# Add any remaining open headings to the list of sections:
for start, heading in open_headings:
if matcher(heading):
sections.append((start, Wikicode(self.nodes[start:])))
# Ensure that earlier sections are earlier in the returned list:
return [section for i, section in sorted(sections)]
def strip_code(self, normalize=True, collapse=True,
keep_template_params=False):
"""Return a rendered string without unprintable code such as templates.
The way a node is stripped is handled by the
:meth:`~.Node.__strip__` method of :class:`.Node` objects, which
generally return a subset of their nodes or ``None``. For example,
templates and tags are removed completely, links are stripped to just
their display part, headings are stripped to just their title.
If *normalize* is ``True``, various things may be done to strip code
further, such as converting HTML entities like ``Σ``, ``Σ``,
and ``Σ`` to ``Σ``. If *collapse* is ``True``, we will try to
remove excess whitespace as well (three or more newlines are converted
to two, for example). If *keep_template_params* is ``True``, then
template parameters will be preserved in the output (normally, they are
removed completely).
"""
kwargs = {
"normalize": normalize,
"collapse": collapse,
"keep_template_params": keep_template_params
}
nodes = []
for node in self.nodes:
stripped = node.__strip__(**kwargs)
if stripped:
nodes.append(str(stripped))
if collapse:
stripped = "".join(nodes).strip("\n")
while "\n\n\n" in stripped:
stripped = stripped.replace("\n\n\n", "\n\n")
return stripped
else:
return "".join(nodes)
def get_tree(self):
"""Return a hierarchical tree representation of the object.
The representation is a string makes the most sense printed. It is
built by calling :meth:`_get_tree` on the :class:`.Wikicode` object and
its children recursively. The end result may look something like the
following::
>>> text = "Lorem ipsum {{foo|bar|{{baz}}|spam=eggs}}"
>>> print(mwparserfromhell.parse(text).get_tree())
Lorem ipsum
{{
foo
| 1
= bar
| 2
= {{
baz
}}
| spam
= eggs
}}
"""
marker = object() # Random object we can find with certainty in a list
return "\n".join(self._get_tree(self, [], marker, 0))
Wikicode._build_filter_methods(
arguments=Argument, comments=Comment, external_links=ExternalLink,
headings=Heading, html_entities=HTMLEntity, tags=Tag, templates=Template,
text=Text, wikilinks=Wikilink)
| 44.945668 | 82 | 0.59785 |
import re
from itertools import chain
from .nodes import (Argument, Comment, ExternalLink, Heading, HTMLEntity,
Node, Tag, Template, Text, Wikilink)
from .smart_list.ListProxy import _ListProxy
from .string_mixin import StringMixIn
from .utils import parse_anything
__all__ = ["Wikicode"]
FLAGS = re.IGNORECASE | re.DOTALL | re.UNICODE
class Wikicode(StringMixIn):
RECURSE_OTHERS = 2
def __init__(self, nodes):
super().__init__()
self._nodes = nodes
def __unicode__(self):
return "".join([str(node) for node in self.nodes])
@staticmethod
def _get_children(node, contexts=False, restrict=None, parent=None):
yield (parent, node) if contexts else node
if restrict and isinstance(node, restrict):
return
for code in node.__children__():
for child in code.nodes:
sub = Wikicode._get_children(child, contexts, restrict, code)
yield from sub
@staticmethod
def _slice_replace(code, index, old, new):
nodes = [str(node) for node in code.get(index)]
substring = "".join(nodes).replace(old, new)
code.nodes[index] = parse_anything(substring).nodes
@staticmethod
def _build_matcher(matches, flags):
if matches:
if callable(matches):
return matches
return lambda obj: re.search(matches, str(obj), flags)
return lambda obj: True
def _indexed_ifilter(self, recursive=True, matches=None, flags=FLAGS,
forcetype=None):
match = self._build_matcher(matches, flags)
if recursive:
restrict = forcetype if recursive == self.RECURSE_OTHERS else None
def getter(i, node):
for ch in self._get_children(node, restrict=restrict):
yield (i, ch)
inodes = chain(*(getter(i, n) for i, n in enumerate(self.nodes)))
else:
inodes = enumerate(self.nodes)
for i, node in inodes:
if (not forcetype or isinstance(node, forcetype)) and match(node):
yield (i, node)
def _is_child_wikicode(self, obj, recursive=True):
def deref(nodes):
if isinstance(nodes, _ListProxy):
return nodes._parent
return nodes
target = deref(obj.nodes)
if target is deref(self.nodes):
return True
if recursive:
todo = [self]
while todo:
code = todo.pop()
if target is deref(code.nodes):
return True
for node in code.nodes:
todo += list(node.__children__())
return False
def _do_strong_search(self, obj, recursive=True):
if isinstance(obj, Wikicode):
if not self._is_child_wikicode(obj, recursive):
raise ValueError(obj)
return obj, slice(0, len(obj.nodes))
if isinstance(obj, Node):
mkslice = lambda i: slice(i, i + 1)
if not recursive:
return self, mkslice(self.index(obj))
for node in self.nodes:
for context, child in self._get_children(node, contexts=True):
if obj is child:
if not context:
context = self
return context, mkslice(context.index(child))
raise ValueError(obj)
raise TypeError(obj)
def _do_weak_search(self, obj, recursive):
obj = parse_anything(obj)
if not obj or obj not in self:
raise ValueError(obj)
results = []
contexts = [self]
while contexts:
context = contexts.pop()
i = len(context.nodes) - 1
while i >= 0:
node = context.get(i)
if obj.get(-1) == node:
for j in range(-len(obj.nodes), -1):
if obj.get(j) != context.get(i + j + 1):
break
else:
i -= len(obj.nodes) - 1
index = slice(i, i + len(obj.nodes))
results.append((True, context, index))
elif recursive and obj in node:
contexts.extend(node.__children__())
i -= 1
if not results:
if not recursive:
raise ValueError(obj)
results.append((False, self, slice(0, len(self.nodes))))
return results
def _get_tree(self, code, lines, marker, indent):
def write(*args):
if lines and lines[-1] is marker:
lines.pop()
last = lines.pop()
lines.append(last + " ".join(args))
else:
lines.append(" " * 6 * indent + " ".join(args))
get = lambda code: self._get_tree(code, lines, marker, indent + 1)
mark = lambda: lines.append(marker)
for node in code.nodes:
node.__showtree__(write, get, mark)
return lines
@classmethod
def _build_filter_methods(cls, **meths):
doc = """Iterate over {0}.
This is equivalent to :meth:`{1}` with *forcetype* set to
:class:`~{2.__module__}.{2.__name__}`.
"""
make_ifilter = lambda ftype: (lambda self, *a, **kw:
self.ifilter(forcetype=ftype, *a, **kw))
make_filter = lambda ftype: (lambda self, *a, **kw:
self.filter(forcetype=ftype, *a, **kw))
for name, ftype in meths.items():
ifilter = make_ifilter(ftype)
filter = make_filter(ftype)
ifilter.__doc__ = doc.format(name, "ifilter", ftype)
filter.__doc__ = doc.format(name, "filter", ftype)
setattr(cls, "ifilter_" + name, ifilter)
setattr(cls, "filter_" + name, filter)
@property
def nodes(self):
return self._nodes
@nodes.setter
def nodes(self, value):
if not isinstance(value, list):
value = parse_anything(value).nodes
self._nodes = value
def get(self, index):
return self.nodes[index]
def set(self, index, value):
nodes = parse_anything(value).nodes
if len(nodes) > 1:
raise ValueError("Cannot coerce multiple nodes into one index")
if index >= len(self.nodes) or -1 * index > len(self.nodes):
raise IndexError("List assignment index out of range")
if nodes:
self.nodes[index] = nodes[0]
else:
self.nodes.pop(index)
def contains(self, obj):
if not isinstance(obj, (Node, Wikicode)):
return obj in self
try:
self._do_strong_search(obj, recursive=True)
except ValueError:
return False
return True
def index(self, obj, recursive=False):
strict = isinstance(obj, Node)
equivalent = (lambda o, n: o is n) if strict else (lambda o, n: o == n)
for i, node in enumerate(self.nodes):
if recursive:
for child in self._get_children(node):
if equivalent(obj, child):
return i
elif equivalent(obj, node):
return i
raise ValueError(obj)
def get_ancestors(self, obj):
def _get_ancestors(code, needle):
for node in code.nodes:
if node is needle:
return []
for code in node.__children__():
ancestors = _get_ancestors(code, needle)
if ancestors is not None:
return [node] + ancestors
if isinstance(obj, Wikicode):
obj = obj.get(0)
elif not isinstance(obj, Node):
raise ValueError(obj)
ancestors = _get_ancestors(self, obj)
if ancestors is None:
raise ValueError(obj)
return ancestors
def get_parent(self, obj):
ancestors = self.get_ancestors(obj)
return ancestors[-1] if ancestors else None
def insert(self, index, value):
nodes = parse_anything(value).nodes
for node in reversed(nodes):
self.nodes.insert(index, node)
def insert_before(self, obj, value, recursive=True):
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
context.insert(index.start, value)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
context.insert(index.start, value)
else:
obj = str(obj)
self._slice_replace(context, index, obj, str(value) + obj)
def insert_after(self, obj, value, recursive=True):
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
context.insert(index.stop, value)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
context.insert(index.stop, value)
else:
obj = str(obj)
self._slice_replace(context, index, obj, obj + str(value))
def replace(self, obj, value, recursive=True):
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
context.insert(index.start, value)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
context.insert(index.start, value)
else:
self._slice_replace(context, index, str(obj), str(value))
def append(self, value):
nodes = parse_anything(value).nodes
for node in nodes:
self.nodes.append(node)
def remove(self, obj, recursive=True):
if isinstance(obj, (Node, Wikicode)):
context, index = self._do_strong_search(obj, recursive)
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
else:
for exact, context, index in self._do_weak_search(obj, recursive):
if exact:
for i in range(index.start, index.stop):
context.nodes.pop(index.start)
else:
self._slice_replace(context, index, str(obj), "")
def matches(self, other):
normalize = lambda s: (s[0].upper() + s[1:]).replace("_", " ") if s else s
this = normalize(self.strip_code().strip())
if isinstance(other, (str, bytes, Wikicode, Node)):
that = parse_anything(other).strip_code().strip()
return this == normalize(that)
for obj in other:
that = parse_anything(obj).strip_code().strip()
if this == normalize(that):
return True
return False
def ifilter(self, recursive=True, matches=None, flags=FLAGS,
forcetype=None):
gen = self._indexed_ifilter(recursive, matches, flags, forcetype)
return (node for i, node in gen)
def filter(self, *args, **kwargs):
return list(self.ifilter(*args, **kwargs))
def get_sections(self, levels=None, matches=None, flags=FLAGS, flat=False,
include_lead=None, include_headings=True):
title_matcher = self._build_matcher(matches, flags)
matcher = lambda heading: (title_matcher(heading.title) and
(not levels or heading.level in levels))
iheadings = self._indexed_ifilter(recursive=False, forcetype=Heading)
sections = []
open_headings = []
if include_lead or not (include_lead is not None or matches or levels):
itr = self._indexed_ifilter(recursive=False, forcetype=Heading)
try:
first = next(itr)[0]
sections.append((0, Wikicode(self.nodes[:first])))
except StopIteration:
sections.append((0, Wikicode(self.nodes[:])))
for i, heading in iheadings:
if flat:
newly_closed, open_headings = open_headings, []
else:
closed_start_index = len(open_headings)
for j, (start, last_heading) in enumerate(open_headings):
if heading.level <= last_heading.level:
closed_start_index = j
break
newly_closed = open_headings[closed_start_index:]
del open_headings[closed_start_index:]
for start, closed_heading in newly_closed:
if matcher(closed_heading):
sections.append((start, Wikicode(self.nodes[start:i])))
start = i if include_headings else (i + 1)
open_headings.append((start, heading))
for start, heading in open_headings:
if matcher(heading):
sections.append((start, Wikicode(self.nodes[start:])))
return [section for i, section in sorted(sections)]
def strip_code(self, normalize=True, collapse=True,
keep_template_params=False):
kwargs = {
"normalize": normalize,
"collapse": collapse,
"keep_template_params": keep_template_params
}
nodes = []
for node in self.nodes:
stripped = node.__strip__(**kwargs)
if stripped:
nodes.append(str(stripped))
if collapse:
stripped = "".join(nodes).strip("\n")
while "\n\n\n" in stripped:
stripped = stripped.replace("\n\n\n", "\n\n")
return stripped
else:
return "".join(nodes)
def get_tree(self):
marker = object()
return "\n".join(self._get_tree(self, [], marker, 0))
Wikicode._build_filter_methods(
arguments=Argument, comments=Comment, external_links=ExternalLink,
headings=Heading, html_entities=HTMLEntity, tags=Tag, templates=Template,
text=Text, wikilinks=Wikilink)
| true | true |
f72c27667d2dfd2d0ef541566592c06f430e047b | 147 | py | Python | scene/__init__.py | cloose/ray-tracer-challenge | 5e9dd56fb67c5cba47172986a963fc22a8cbcaa2 | [
"MIT"
] | null | null | null | scene/__init__.py | cloose/ray-tracer-challenge | 5e9dd56fb67c5cba47172986a963fc22a8cbcaa2 | [
"MIT"
] | null | null | null | scene/__init__.py | cloose/ray-tracer-challenge | 5e9dd56fb67c5cba47172986a963fc22a8cbcaa2 | [
"MIT"
] | null | null | null | from .camera import *
from .obj_file import *
from .obj_parser import *
from .ray_tracer import *
from .scene_parser import *
from .world import *
| 21 | 27 | 0.755102 | from .camera import *
from .obj_file import *
from .obj_parser import *
from .ray_tracer import *
from .scene_parser import *
from .world import *
| true | true |
f72c27de3695f8b7dc7c5ae95c8a39f24e92433e | 10,650 | py | Python | darling_ansible/python_venv/lib/python3.7/site-packages/oci/core/models/update_vnic_details.py | revnav/sandbox | f9c8422233d093b76821686b6c249417502cf61d | [
"Apache-2.0"
] | null | null | null | darling_ansible/python_venv/lib/python3.7/site-packages/oci/core/models/update_vnic_details.py | revnav/sandbox | f9c8422233d093b76821686b6c249417502cf61d | [
"Apache-2.0"
] | null | null | null | darling_ansible/python_venv/lib/python3.7/site-packages/oci/core/models/update_vnic_details.py | revnav/sandbox | f9c8422233d093b76821686b6c249417502cf61d | [
"Apache-2.0"
] | 1 | 2020-06-25T03:12:58.000Z | 2020-06-25T03:12:58.000Z | # coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class UpdateVnicDetails(object):
"""
UpdateVnicDetails model.
"""
def __init__(self, **kwargs):
"""
Initializes a new UpdateVnicDetails object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param defined_tags:
The value to assign to the defined_tags property of this UpdateVnicDetails.
:type defined_tags: dict(str, dict(str, object))
:param display_name:
The value to assign to the display_name property of this UpdateVnicDetails.
:type display_name: str
:param freeform_tags:
The value to assign to the freeform_tags property of this UpdateVnicDetails.
:type freeform_tags: dict(str, str)
:param hostname_label:
The value to assign to the hostname_label property of this UpdateVnicDetails.
:type hostname_label: str
:param nsg_ids:
The value to assign to the nsg_ids property of this UpdateVnicDetails.
:type nsg_ids: list[str]
:param skip_source_dest_check:
The value to assign to the skip_source_dest_check property of this UpdateVnicDetails.
:type skip_source_dest_check: bool
"""
self.swagger_types = {
'defined_tags': 'dict(str, dict(str, object))',
'display_name': 'str',
'freeform_tags': 'dict(str, str)',
'hostname_label': 'str',
'nsg_ids': 'list[str]',
'skip_source_dest_check': 'bool'
}
self.attribute_map = {
'defined_tags': 'definedTags',
'display_name': 'displayName',
'freeform_tags': 'freeformTags',
'hostname_label': 'hostnameLabel',
'nsg_ids': 'nsgIds',
'skip_source_dest_check': 'skipSourceDestCheck'
}
self._defined_tags = None
self._display_name = None
self._freeform_tags = None
self._hostname_label = None
self._nsg_ids = None
self._skip_source_dest_check = None
@property
def defined_tags(self):
"""
Gets the defined_tags of this UpdateVnicDetails.
Defined tags for this resource. Each key is predefined and scoped to a
namespace. For more information, see `Resource Tags`__.
Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:return: The defined_tags of this UpdateVnicDetails.
:rtype: dict(str, dict(str, object))
"""
return self._defined_tags
@defined_tags.setter
def defined_tags(self, defined_tags):
"""
Sets the defined_tags of this UpdateVnicDetails.
Defined tags for this resource. Each key is predefined and scoped to a
namespace. For more information, see `Resource Tags`__.
Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:param defined_tags: The defined_tags of this UpdateVnicDetails.
:type: dict(str, dict(str, object))
"""
self._defined_tags = defined_tags
@property
def display_name(self):
"""
Gets the display_name of this UpdateVnicDetails.
A user-friendly name. Does not have to be unique, and it's changeable.
Avoid entering confidential information.
:return: The display_name of this UpdateVnicDetails.
:rtype: str
"""
return self._display_name
@display_name.setter
def display_name(self, display_name):
"""
Sets the display_name of this UpdateVnicDetails.
A user-friendly name. Does not have to be unique, and it's changeable.
Avoid entering confidential information.
:param display_name: The display_name of this UpdateVnicDetails.
:type: str
"""
self._display_name = display_name
@property
def freeform_tags(self):
"""
Gets the freeform_tags of this UpdateVnicDetails.
Free-form tags for this resource. Each tag is a simple key-value pair with no
predefined name, type, or namespace. For more information, see `Resource Tags`__.
Example: `{\"Department\": \"Finance\"}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:return: The freeform_tags of this UpdateVnicDetails.
:rtype: dict(str, str)
"""
return self._freeform_tags
@freeform_tags.setter
def freeform_tags(self, freeform_tags):
"""
Sets the freeform_tags of this UpdateVnicDetails.
Free-form tags for this resource. Each tag is a simple key-value pair with no
predefined name, type, or namespace. For more information, see `Resource Tags`__.
Example: `{\"Department\": \"Finance\"}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:param freeform_tags: The freeform_tags of this UpdateVnicDetails.
:type: dict(str, str)
"""
self._freeform_tags = freeform_tags
@property
def hostname_label(self):
"""
Gets the hostname_label of this UpdateVnicDetails.
The hostname for the VNIC's primary private IP. Used for DNS. The value is the hostname
portion of the primary private IP's fully qualified domain name (FQDN)
(for example, `bminstance-1` in FQDN `bminstance-1.subnet123.vcn1.oraclevcn.com`).
Must be unique across all VNICs in the subnet and comply with
`RFC 952`__ and
`RFC 1123`__.
The value appears in the :class:`Vnic` object and also the
:class:`PrivateIp` object returned by
:func:`list_private_ips` and
:func:`get_private_ip`.
For more information, see
`DNS in Your Virtual Cloud Network`__.
__ https://tools.ietf.org/html/rfc952
__ https://tools.ietf.org/html/rfc1123
__ https://docs.cloud.oracle.com/Content/Network/Concepts/dns.htm
:return: The hostname_label of this UpdateVnicDetails.
:rtype: str
"""
return self._hostname_label
@hostname_label.setter
def hostname_label(self, hostname_label):
"""
Sets the hostname_label of this UpdateVnicDetails.
The hostname for the VNIC's primary private IP. Used for DNS. The value is the hostname
portion of the primary private IP's fully qualified domain name (FQDN)
(for example, `bminstance-1` in FQDN `bminstance-1.subnet123.vcn1.oraclevcn.com`).
Must be unique across all VNICs in the subnet and comply with
`RFC 952`__ and
`RFC 1123`__.
The value appears in the :class:`Vnic` object and also the
:class:`PrivateIp` object returned by
:func:`list_private_ips` and
:func:`get_private_ip`.
For more information, see
`DNS in Your Virtual Cloud Network`__.
__ https://tools.ietf.org/html/rfc952
__ https://tools.ietf.org/html/rfc1123
__ https://docs.cloud.oracle.com/Content/Network/Concepts/dns.htm
:param hostname_label: The hostname_label of this UpdateVnicDetails.
:type: str
"""
self._hostname_label = hostname_label
@property
def nsg_ids(self):
"""
Gets the nsg_ids of this UpdateVnicDetails.
A list of the OCIDs of the network security groups (NSGs) to add the VNIC to. Setting this as
an empty array removes the VNIC from all network security groups.
For more information about NSGs, see
:class:`NetworkSecurityGroup`.
:return: The nsg_ids of this UpdateVnicDetails.
:rtype: list[str]
"""
return self._nsg_ids
@nsg_ids.setter
def nsg_ids(self, nsg_ids):
"""
Sets the nsg_ids of this UpdateVnicDetails.
A list of the OCIDs of the network security groups (NSGs) to add the VNIC to. Setting this as
an empty array removes the VNIC from all network security groups.
For more information about NSGs, see
:class:`NetworkSecurityGroup`.
:param nsg_ids: The nsg_ids of this UpdateVnicDetails.
:type: list[str]
"""
self._nsg_ids = nsg_ids
@property
def skip_source_dest_check(self):
"""
Gets the skip_source_dest_check of this UpdateVnicDetails.
Whether the source/destination check is disabled on the VNIC.
Defaults to `false`, which means the check is performed.
For information about why you would skip the source/destination check, see
`Using a Private IP as a Route Target`__.
Example: `true`
__ https://docs.cloud.oracle.com/Content/Network/Tasks/managingroutetables.htm#privateip
:return: The skip_source_dest_check of this UpdateVnicDetails.
:rtype: bool
"""
return self._skip_source_dest_check
@skip_source_dest_check.setter
def skip_source_dest_check(self, skip_source_dest_check):
"""
Sets the skip_source_dest_check of this UpdateVnicDetails.
Whether the source/destination check is disabled on the VNIC.
Defaults to `false`, which means the check is performed.
For information about why you would skip the source/destination check, see
`Using a Private IP as a Route Target`__.
Example: `true`
__ https://docs.cloud.oracle.com/Content/Network/Tasks/managingroutetables.htm#privateip
:param skip_source_dest_check: The skip_source_dest_check of this UpdateVnicDetails.
:type: bool
"""
self._skip_source_dest_check = skip_source_dest_check
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| 35.264901 | 245 | 0.65615 |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class UpdateVnicDetails(object):
def __init__(self, **kwargs):
self.swagger_types = {
'defined_tags': 'dict(str, dict(str, object))',
'display_name': 'str',
'freeform_tags': 'dict(str, str)',
'hostname_label': 'str',
'nsg_ids': 'list[str]',
'skip_source_dest_check': 'bool'
}
self.attribute_map = {
'defined_tags': 'definedTags',
'display_name': 'displayName',
'freeform_tags': 'freeformTags',
'hostname_label': 'hostnameLabel',
'nsg_ids': 'nsgIds',
'skip_source_dest_check': 'skipSourceDestCheck'
}
self._defined_tags = None
self._display_name = None
self._freeform_tags = None
self._hostname_label = None
self._nsg_ids = None
self._skip_source_dest_check = None
@property
def defined_tags(self):
return self._defined_tags
@defined_tags.setter
def defined_tags(self, defined_tags):
self._defined_tags = defined_tags
@property
def display_name(self):
return self._display_name
@display_name.setter
def display_name(self, display_name):
self._display_name = display_name
@property
def freeform_tags(self):
return self._freeform_tags
@freeform_tags.setter
def freeform_tags(self, freeform_tags):
self._freeform_tags = freeform_tags
@property
def hostname_label(self):
return self._hostname_label
@hostname_label.setter
def hostname_label(self, hostname_label):
self._hostname_label = hostname_label
@property
def nsg_ids(self):
return self._nsg_ids
@nsg_ids.setter
def nsg_ids(self, nsg_ids):
self._nsg_ids = nsg_ids
@property
def skip_source_dest_check(self):
return self._skip_source_dest_check
@skip_source_dest_check.setter
def skip_source_dest_check(self, skip_source_dest_check):
self._skip_source_dest_check = skip_source_dest_check
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
f72c287955fbff99748da09097b2149ee342155e | 2,564 | py | Python | smartrecruiters_python_client/models/json_patch.py | roksela/smartrecruiters-python-client | 6d0849d173a3d6718b5f0769098f4c76857f637d | [
"MIT"
] | 5 | 2018-03-27T08:20:13.000Z | 2022-03-30T06:23:38.000Z | smartrecruiters_python_client/models/json_patch.py | roksela/smartrecruiters-python-client | 6d0849d173a3d6718b5f0769098f4c76857f637d | [
"MIT"
] | null | null | null | smartrecruiters_python_client/models/json_patch.py | roksela/smartrecruiters-python-client | 6d0849d173a3d6718b5f0769098f4c76857f637d | [
"MIT"
] | 2 | 2018-12-05T04:48:37.000Z | 2020-12-17T12:12:12.000Z | # coding: utf-8
"""
Unofficial python library for the SmartRecruiters API
The SmartRecruiters API provides a platform to integrate services or applications, build apps and create fully customizable career sites. It exposes SmartRecruiters functionality and allows to connect and build software enhancing it.
OpenAPI spec version: 1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class JSONPatch(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
"""
JSONPatch - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
}
self.attribute_map = {
}
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, JSONPatch):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| 27.276596 | 237 | 0.543682 |
from pprint import pformat
from six import iteritems
import re
class JSONPatch(object):
def __init__(self):
self.swagger_types = {
}
self.attribute_map = {
}
def to_dict(self):
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
return pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, JSONPatch):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
f72c2931d18a600dc4eaf9f2b95c5f5248adbea1 | 900 | py | Python | transmissionServer.py | crate19970523/yoloKnifeCallPolice- | 47b716dbacdd0d31282d13e0ec957711b3f967ca | [
"MIT"
] | null | null | null | transmissionServer.py | crate19970523/yoloKnifeCallPolice- | 47b716dbacdd0d31282d13e0ec957711b3f967ca | [
"MIT"
] | null | null | null | transmissionServer.py | crate19970523/yoloKnifeCallPolice- | 47b716dbacdd0d31282d13e0ec957711b3f967ca | [
"MIT"
] | null | null | null | #coding:utf-8
from flask import request, Flask
import time
import os
app = Flask(__name__)
@app.route("/", methods=['POST'])
def get_frame():
start_time = time.time()
upload_file = request.files['file']
old_file_name = upload_file.filename
if upload_file:
file_path = os.path.join('./imgtest/', old_file_name) #Server端的存放位置
upload_file.save(file_path)
print ("success")
if not os.path.isfile('imgtest/ltuschool.jpg'):
print('有近來喔')
os.rename('./imgtest/ltu.jpg','./imgtest/ltuschool.jpg')
print('file saved to %s' % file_path)
duration = time.time() - start_time
print('duration:[%.0fms]' % (duration*1000))
return 'success'
else:
return 'failed'
def transmission():
app.run("192.168.43.179", port=5000) #Server端的IP以及port
if __name__ == "__main__":
transmission() | 31.034483 | 77 | 0.622222 |
from flask import request, Flask
import time
import os
app = Flask(__name__)
@app.route("/", methods=['POST'])
def get_frame():
start_time = time.time()
upload_file = request.files['file']
old_file_name = upload_file.filename
if upload_file:
file_path = os.path.join('./imgtest/', old_file_name)
upload_file.save(file_path)
print ("success")
if not os.path.isfile('imgtest/ltuschool.jpg'):
print('有近來喔')
os.rename('./imgtest/ltu.jpg','./imgtest/ltuschool.jpg')
print('file saved to %s' % file_path)
duration = time.time() - start_time
print('duration:[%.0fms]' % (duration*1000))
return 'success'
else:
return 'failed'
def transmission():
app.run("192.168.43.179", port=5000)
if __name__ == "__main__":
transmission() | true | true |
f72c298f250b50e48003137adac62548fe42bbfa | 721 | py | Python | tests/test_split_audio_file.py | greenkeytech/greenkey-asrtoolkit | f9a5990ee5c67b85dd8ff763777c986b03252ee5 | [
"Apache-2.0"
] | 31 | 2019-08-03T08:42:37.000Z | 2022-01-12T18:00:11.000Z | tests/test_split_audio_file.py | greenkeytech/greenkey-asrtoolkit | f9a5990ee5c67b85dd8ff763777c986b03252ee5 | [
"Apache-2.0"
] | 28 | 2019-07-29T17:58:17.000Z | 2021-08-20T14:30:25.000Z | tests/test_split_audio_file.py | greenkeytech/greenkey-asrtoolkit | f9a5990ee5c67b85dd8ff763777c986b03252ee5 | [
"Apache-2.0"
] | 12 | 2019-07-29T13:16:41.000Z | 2022-02-20T21:19:35.000Z | #!/usr/bin/env python
"""
Test audio file splitter
"""
import os
from asrtoolkit.split_audio_file import split_audio_file
from utils import get_test_dir
test_dir = get_test_dir(__file__)
def test_split_audio_file():
"""
Test audio file splitter
"""
split_audio_file(
f"{test_dir}/small-test-file.mp3",
f"{test_dir}/small-test-file.stm",
f"{test_dir}/split",
)
assert set(os.listdir(f"{test_dir}/split")) == {
"small_test_file_seg_00001.stm",
"small_test_file_seg_00000.mp3",
"small_test_file_seg_00001.mp3",
"small_test_file_seg_00000.stm",
}
if __name__ == "__main__":
import sys
import pytest
pytest.main(sys.argv)
| 20.027778 | 56 | 0.660194 |
import os
from asrtoolkit.split_audio_file import split_audio_file
from utils import get_test_dir
test_dir = get_test_dir(__file__)
def test_split_audio_file():
split_audio_file(
f"{test_dir}/small-test-file.mp3",
f"{test_dir}/small-test-file.stm",
f"{test_dir}/split",
)
assert set(os.listdir(f"{test_dir}/split")) == {
"small_test_file_seg_00001.stm",
"small_test_file_seg_00000.mp3",
"small_test_file_seg_00001.mp3",
"small_test_file_seg_00000.stm",
}
if __name__ == "__main__":
import sys
import pytest
pytest.main(sys.argv)
| true | true |
f72c29994545a8752c8d6412f035b921d01d390f | 4,755 | py | Python | tests/test_parvec.py | DaveMcEwan/dmppl | 68e8a121d4591360080cd40121add1796ae48a1b | [
"MIT"
] | 1 | 2020-05-05T19:46:43.000Z | 2020-05-05T19:46:43.000Z | tests/test_parvec.py | DaveMcEwan/dmppl | 68e8a121d4591360080cd40121add1796ae48a1b | [
"MIT"
] | null | null | null | tests/test_parvec.py | DaveMcEwan/dmppl | 68e8a121d4591360080cd40121add1796ae48a1b | [
"MIT"
] | null | null | null | from dmppl.scripts.parvec import entryPoint
from dmppl.base import rdTxt
from dmppl.test import runEntryPoint
import os
import tempfile
import shutil
import sys
import unittest
class Test_Parvec(unittest.TestCase): # {{{
def setUp(self):
# Different PRNGs between CPython versions.
# Check against golden for 3.5, 3.6, 3.7, but for other versions just check
# the same thing is generated twice using the same seed.
self.knownPrng = sys.version_info[:2] in [(3, 5), (3, 6), (3, 7)]
self.tstDir = tempfile.mkdtemp()
self.yml0 = '''\
PP_CPU$_$:
- [0, 1, 2]
- ["LSU", "ALU"]
- ["SS", "TT", "FF"]
PB_L$CACHE_EVICT:
- [1, 2]
- {pre-name: foo, post-value: bar}
- ["PERIODIC", "ROUNDROBIN"]
PI_FIFO$_LAYOUT:
- 0..10..2
- ["LINE", "CIRC"]
PL_COUNTER$_THRESH$:
- pre-value: "('d"
post-value: ");"
pre-name: "#blah "
- 0..2
- 0..5
- 100..333..5
'''
self.fnamei0 = os.path.join(self.tstDir, "tst0.yml")
with open(self.fnamei0, 'w') as fd:
fd.write(self.yml0)
self.goldenOut0 = '''\
// seed: 0
fooPB_L1CACHE_EVICT ROUNDROBINbar
fooPB_L2CACHE_EVICT ROUNDROBINbar
`define PI_FIFO0_LAYOUT CIRC
`define PI_FIFO2_LAYOUT LINE
`define PI_FIFO4_LAYOUT LINE
`define PI_FIFO6_LAYOUT LINE
`define PI_FIFO8_LAYOUT LINE
#blah PL_COUNTER0_THRESH0 ('d250);
#blah PL_COUNTER0_THRESH1 ('d210);
#blah PL_COUNTER0_THRESH2 ('d285);
#blah PL_COUNTER0_THRESH3 ('d165);
#blah PL_COUNTER0_THRESH4 ('d260);
#blah PL_COUNTER1_THRESH0 ('d140);
#blah PL_COUNTER1_THRESH1 ('d190);
#blah PL_COUNTER1_THRESH2 ('d140);
#blah PL_COUNTER1_THRESH3 ('d130);
#blah PL_COUNTER1_THRESH4 ('d295);
`define PP_CPU0_ALU SS
`define PP_CPU0_LSU TT
`define PP_CPU1_ALU TT
`define PP_CPU1_LSU TT
`define PP_CPU2_ALU FF
`define PP_CPU2_LSU SS
'''
self.yml1 = '''\
WEALTH_$:
- [Alice, Bob]
- 0..1000
GOODNESS_$_$:
- [Alice, Bob, Charlie, Eve]
- [Black, White, Gray]
- [lovely, evil]
'''
self.fnamei1 = os.path.join(self.tstDir, "tst1.yml")
with open(self.fnamei1, 'w') as fd:
fd.write(self.yml1)
self.goldenOut1 = '''\
// seed: 123
`define GOODNESS_Alice_Black evil
`define GOODNESS_Alice_Gray lovely
`define GOODNESS_Alice_White evil
`define GOODNESS_Bob_Black lovely
`define GOODNESS_Bob_Gray lovely
`define GOODNESS_Bob_White evil
`define GOODNESS_Charlie_Black evil
`define GOODNESS_Charlie_Gray lovely
`define GOODNESS_Charlie_White lovely
`define GOODNESS_Eve_Black lovely
`define GOODNESS_Eve_Gray evil
`define GOODNESS_Eve_White evil
`define WEALTH_Alice 138
`define WEALTH_Bob 345
'''
def tearDown(self):
shutil.rmtree(self.tstDir)
def test_Basic0(self):
self.maxDiff = None
if self.knownPrng:
cmd = "parvec --seed 123 %s" % (self.fnamei1)
stdout, stderr = runEntryPoint(cmd, entryPoint)
self.assertEqual(stderr, "")
self.assertEqual(self.goldenOut1, stdout)
else:
pass
def test_StdIO(self):
self.maxDiff = None
if self.knownPrng:
cmd = "parvec --seed 0"
stdout, stderr = runEntryPoint(cmd, entryPoint, stdinput=self.yml0)
self.assertEqual(stderr, "")
self.assertEqual(self.goldenOut0, stdout)
else:
pass
def test_Features0(self):
self.maxDiff = None
if self.knownPrng:
fnameo0 = self.fnamei0 + ".out"
cmd = "parvec --seed 0 %s -o %s" % (self.fnamei0, fnameo0)
stdout, stderr = runEntryPoint(cmd, entryPoint)
self.assertEqual(stderr, "")
self.assertEqual(stdout, "")
resultTxt = rdTxt(os.path.join(self.tstDir, fnameo0))
self.assertEqual(self.goldenOut0, resultTxt)
else:
fnameo0_A = self.fnamei0 + ".outA"
fnameo0_B = self.fnamei0 + ".outB"
cmdA = "parvec --seed 0 %s -o %s" % (self.fnamei0, fnameo0_A)
cmdB = "parvec --seed 0 %s -o %s" % (self.fnamei0, fnameo0_B)
stdoutA, stderrA = runEntryPoint(cmdA, entryPoint)
#stdoutA, stderrA = runEntryPoint(cmdA, entryPoint, redirect=False)
self.assertEqual(stderrA, "")
self.assertEqual(stdoutA, "")
stdoutB, stderrB = runEntryPoint(cmdB, entryPoint)
#stdoutB, stderrB = runEntryPoint(cmdB, entryPoint, redirect=False)
self.assertEqual(stderrB, "")
self.assertEqual(stdoutB, "")
resultTxtA = rdTxt(os.path.join(self.tstDir, fnameo0_A))
resultTxtB = rdTxt(os.path.join(self.tstDir, fnameo0_B))
self.assertEqual(resultTxtA, resultTxtB)
# }}} class Test_Parvec
| 30.876623 | 83 | 0.63428 | from dmppl.scripts.parvec import entryPoint
from dmppl.base import rdTxt
from dmppl.test import runEntryPoint
import os
import tempfile
import shutil
import sys
import unittest
class Test_Parvec(unittest.TestCase):
def setUp(self):
self.knownPrng = sys.version_info[:2] in [(3, 5), (3, 6), (3, 7)]
self.tstDir = tempfile.mkdtemp()
self.yml0 = '''\
PP_CPU$_$:
- [0, 1, 2]
- ["LSU", "ALU"]
- ["SS", "TT", "FF"]
PB_L$CACHE_EVICT:
- [1, 2]
- {pre-name: foo, post-value: bar}
- ["PERIODIC", "ROUNDROBIN"]
PI_FIFO$_LAYOUT:
- 0..10..2
- ["LINE", "CIRC"]
PL_COUNTER$_THRESH$:
- pre-value: "('d"
post-value: ");"
pre-name: "#blah "
- 0..2
- 0..5
- 100..333..5
'''
self.fnamei0 = os.path.join(self.tstDir, "tst0.yml")
with open(self.fnamei0, 'w') as fd:
fd.write(self.yml0)
self.goldenOut0 = '''\
// seed: 0
fooPB_L1CACHE_EVICT ROUNDROBINbar
fooPB_L2CACHE_EVICT ROUNDROBINbar
`define PI_FIFO0_LAYOUT CIRC
`define PI_FIFO2_LAYOUT LINE
`define PI_FIFO4_LAYOUT LINE
`define PI_FIFO6_LAYOUT LINE
`define PI_FIFO8_LAYOUT LINE
#blah PL_COUNTER0_THRESH0 ('d250);
#blah PL_COUNTER0_THRESH1 ('d210);
#blah PL_COUNTER0_THRESH2 ('d285);
#blah PL_COUNTER0_THRESH3 ('d165);
#blah PL_COUNTER0_THRESH4 ('d260);
#blah PL_COUNTER1_THRESH0 ('d140);
#blah PL_COUNTER1_THRESH1 ('d190);
#blah PL_COUNTER1_THRESH2 ('d140);
#blah PL_COUNTER1_THRESH3 ('d130);
#blah PL_COUNTER1_THRESH4 ('d295);
`define PP_CPU0_ALU SS
`define PP_CPU0_LSU TT
`define PP_CPU1_ALU TT
`define PP_CPU1_LSU TT
`define PP_CPU2_ALU FF
`define PP_CPU2_LSU SS
'''
self.yml1 = '''\
WEALTH_$:
- [Alice, Bob]
- 0..1000
GOODNESS_$_$:
- [Alice, Bob, Charlie, Eve]
- [Black, White, Gray]
- [lovely, evil]
'''
self.fnamei1 = os.path.join(self.tstDir, "tst1.yml")
with open(self.fnamei1, 'w') as fd:
fd.write(self.yml1)
self.goldenOut1 = '''\
// seed: 123
`define GOODNESS_Alice_Black evil
`define GOODNESS_Alice_Gray lovely
`define GOODNESS_Alice_White evil
`define GOODNESS_Bob_Black lovely
`define GOODNESS_Bob_Gray lovely
`define GOODNESS_Bob_White evil
`define GOODNESS_Charlie_Black evil
`define GOODNESS_Charlie_Gray lovely
`define GOODNESS_Charlie_White lovely
`define GOODNESS_Eve_Black lovely
`define GOODNESS_Eve_Gray evil
`define GOODNESS_Eve_White evil
`define WEALTH_Alice 138
`define WEALTH_Bob 345
'''
def tearDown(self):
shutil.rmtree(self.tstDir)
def test_Basic0(self):
self.maxDiff = None
if self.knownPrng:
cmd = "parvec --seed 123 %s" % (self.fnamei1)
stdout, stderr = runEntryPoint(cmd, entryPoint)
self.assertEqual(stderr, "")
self.assertEqual(self.goldenOut1, stdout)
else:
pass
def test_StdIO(self):
self.maxDiff = None
if self.knownPrng:
cmd = "parvec --seed 0"
stdout, stderr = runEntryPoint(cmd, entryPoint, stdinput=self.yml0)
self.assertEqual(stderr, "")
self.assertEqual(self.goldenOut0, stdout)
else:
pass
def test_Features0(self):
self.maxDiff = None
if self.knownPrng:
fnameo0 = self.fnamei0 + ".out"
cmd = "parvec --seed 0 %s -o %s" % (self.fnamei0, fnameo0)
stdout, stderr = runEntryPoint(cmd, entryPoint)
self.assertEqual(stderr, "")
self.assertEqual(stdout, "")
resultTxt = rdTxt(os.path.join(self.tstDir, fnameo0))
self.assertEqual(self.goldenOut0, resultTxt)
else:
fnameo0_A = self.fnamei0 + ".outA"
fnameo0_B = self.fnamei0 + ".outB"
cmdA = "parvec --seed 0 %s -o %s" % (self.fnamei0, fnameo0_A)
cmdB = "parvec --seed 0 %s -o %s" % (self.fnamei0, fnameo0_B)
stdoutA, stderrA = runEntryPoint(cmdA, entryPoint)
#stdoutA, stderrA = runEntryPoint(cmdA, entryPoint, redirect=False)
self.assertEqual(stderrA, "")
self.assertEqual(stdoutA, "")
stdoutB, stderrB = runEntryPoint(cmdB, entryPoint)
#stdoutB, stderrB = runEntryPoint(cmdB, entryPoint, redirect=False)
self.assertEqual(stderrB, "")
self.assertEqual(stdoutB, "")
resultTxtA = rdTxt(os.path.join(self.tstDir, fnameo0_A))
resultTxtB = rdTxt(os.path.join(self.tstDir, fnameo0_B))
self.assertEqual(resultTxtA, resultTxtB)
# }}} class Test_Parvec
| true | true |
f72c29c259a32921c65201a24cdc494eaddc5c96 | 3,974 | gyp | Python | gyp/freetype.gyp | Frankie-666/color-emoji.skia | f1634a9952086155b9069d49ab91f1fa43b5ec6a | [
"BSD-3-Clause"
] | 1 | 2018-06-18T03:20:08.000Z | 2018-06-18T03:20:08.000Z | gyp/freetype.gyp | Frankie-666/color-emoji.skia | f1634a9952086155b9069d49ab91f1fa43b5ec6a | [
"BSD-3-Clause"
] | null | null | null | gyp/freetype.gyp | Frankie-666/color-emoji.skia | f1634a9952086155b9069d49ab91f1fa43b5ec6a | [
"BSD-3-Clause"
] | null | null | null | {
'targets': [
{
'target_name': 'freetype',
'type': 'static_library',
'standalone_static_library': 1,
'sources': [
# base components (required)
'../third_party/externals/freetype/src/base/ftsystem.c',
'../third_party/externals/freetype/src/base/ftinit.c',
'../third_party/externals/freetype/src/base/ftdebug.c',
'../third_party/externals/freetype/src/base/ftbase.c',
'../third_party/externals/freetype/src/base/ftbbox.c', # recommended, see <freetype/ftbbox.h>
'../third_party/externals/freetype/src/base/ftglyph.c', # recommended, see <freetype/ftglyph.h>
'../third_party/externals/freetype/src/base/ftbitmap.c', # optional, see <freetype/ftbitmap.h>
'../third_party/externals/freetype/src/base/ftfstype.c', # optional
'../third_party/externals/freetype/src/base/ftgasp.c', # optional, see <freetype/ftgasp.h>
'../third_party/externals/freetype/src/base/ftlcdfil.c', # optional, see <freetype/ftlcdfil.h>
'../third_party/externals/freetype/src/base/ftmm.c', # optional, see <freetype/ftmm.h>
'../third_party/externals/freetype/src/base/ftpatent.c', # optional
'../third_party/externals/freetype/src/base/ftstroke.c', # optional, see <freetype/ftstroke.h>
'../third_party/externals/freetype/src/base/ftsynth.c', # optional, see <freetype/ftsynth.h>
'../third_party/externals/freetype/src/base/fttype1.c', # optional, see <freetype/t1tables.h>
'../third_party/externals/freetype/src/base/ftwinfnt.c', # optional, see <freetype/ftwinfnt.h>
'../third_party/externals/freetype/src/base/ftxf86.c', # optional, see <freetype/ftxf86.h>
# font drivers (optional; at least one is needed)
'../third_party/externals/freetype/src/cff/cff.c', # CFF/OpenType font driver
'../third_party/externals/freetype/src/sfnt/sfnt.c', # SFNT files support (TrueType & OpenType)
'../third_party/externals/freetype/src/truetype/truetype.c', # TrueType font driver
# rasterizers (optional; at least one is needed for vector formats)
'../third_party/externals/freetype/src/raster/raster.c', # monochrome rasterizer
'../third_party/externals/freetype/src/smooth/smooth.c', # anti-aliasing rasterizer
# auxiliary modules (optional)
'../third_party/externals/freetype/src/autofit/autofit.c', # auto hinting module
'../third_party/externals/freetype/src/psaux/psaux.c', # PostScript Type 1 parsing
'../third_party/externals/freetype/src/pshinter/pshinter.c', # PS hinting module
'../third_party/externals/freetype/src/psnames/psnames.c', # PostScript glyph names support
],
'include_dirs': [
'../third_party/externals/freetype/internal',
'../third_party/externals/freetype/builds',
'../third_party/externals/freetype/include',
'../third_party/externals/freetype',
],
'cflags': [
'-DFT2_BUILD_LIBRARY',
],
'direct_dependent_settings': {
'include_dirs': [
'../third_party/externals/freetype/include',
],
},
'conditions': [
[ 'skia_os == "mac"', {
'sources': [
'../third_party/externals/freetype/src/base/ftmac.c', # only on the Macintosh
],
}],
[ 'skia_os == "android"', {
# These flags are used by the Android OS. They are probably overkill
# for Skia, but we add them for consistency.
'cflags': [
'-W',
'-Wall',
'-fPIC',
'-DPIC',
'-DDARWIN_NO_CARBON',
'-DFT2_BUILD_LIBRARY',
'-O2',
],
}],
],
},
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
| 45.678161 | 111 | 0.606945 | {
'targets': [
{
'target_name': 'freetype',
'type': 'static_library',
'standalone_static_library': 1,
'sources': [
'../third_party/externals/freetype/src/base/ftsystem.c',
'../third_party/externals/freetype/src/base/ftinit.c',
'../third_party/externals/freetype/src/base/ftdebug.c',
'../third_party/externals/freetype/src/base/ftbase.c',
'../third_party/externals/freetype/src/base/ftbbox.c',
'../third_party/externals/freetype/src/base/ftglyph.c',
'../third_party/externals/freetype/src/base/ftbitmap.c',
'../third_party/externals/freetype/src/base/ftfstype.c',
'../third_party/externals/freetype/src/base/ftgasp.c',
'../third_party/externals/freetype/src/base/ftlcdfil.c',
'../third_party/externals/freetype/src/base/ftmm.c',
'../third_party/externals/freetype/src/base/ftpatent.c',
'../third_party/externals/freetype/src/base/ftstroke.c',
'../third_party/externals/freetype/src/base/ftsynth.c',
'../third_party/externals/freetype/src/base/fttype1.c',
'../third_party/externals/freetype/src/base/ftwinfnt.c',
'../third_party/externals/freetype/src/base/ftxf86.c',
'../third_party/externals/freetype/src/cff/cff.c',
'../third_party/externals/freetype/src/sfnt/sfnt.c',
'../third_party/externals/freetype/src/truetype/truetype.c',
'../third_party/externals/freetype/src/raster/raster.c',
'../third_party/externals/freetype/src/smooth/smooth.c',
'../third_party/externals/freetype/src/autofit/autofit.c',
'../third_party/externals/freetype/src/psaux/psaux.c',
'../third_party/externals/freetype/src/pshinter/pshinter.c',
'../third_party/externals/freetype/src/psnames/psnames.c',
],
'include_dirs': [
'../third_party/externals/freetype/internal',
'../third_party/externals/freetype/builds',
'../third_party/externals/freetype/include',
'../third_party/externals/freetype',
],
'cflags': [
'-DFT2_BUILD_LIBRARY',
],
'direct_dependent_settings': {
'include_dirs': [
'../third_party/externals/freetype/include',
],
},
'conditions': [
[ 'skia_os == "mac"', {
'sources': [
'../third_party/externals/freetype/src/base/ftmac.c',
],
}],
[ 'skia_os == "android"', {
'cflags': [
'-W',
'-Wall',
'-fPIC',
'-DPIC',
'-DDARWIN_NO_CARBON',
'-DFT2_BUILD_LIBRARY',
'-O2',
],
}],
],
},
],
}
| true | true |
f72c2a8a8a6c7d963cd917f661bb29b5ba4d5351 | 12,831 | py | Python | utils/data_utils.py | joshchang1112/gcnn-survey-paper | 591af8d6c4374378831cab2cdec79575e2540d79 | [
"Apache-2.0"
] | 155 | 2019-12-18T19:01:02.000Z | 2022-03-12T16:34:06.000Z | utils/data_utils.py | google/gcnn-survey-paper | 591af8d6c4374378831cab2cdec79575e2540d79 | [
"Apache-2.0"
] | null | null | null | utils/data_utils.py | google/gcnn-survey-paper | 591af8d6c4374378831cab2cdec79575e2540d79 | [
"Apache-2.0"
] | 23 | 2020-05-11T12:39:58.000Z | 2022-03-04T09:13:58.000Z | #Copyright 2018 Google LLC
#
#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
#
# https://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.
"""Utils functions to load and process citation data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import pickle as pkl
import sys
import networkx as nx
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
import tensorflow as tf
from third_party.gcn.gcn.utils import normalize_adj
from third_party.gcn.gcn.utils import parse_index_file
from third_party.gcn.gcn.utils import sample_mask
from third_party.gcn.gcn.utils import sparse_to_tuple
from third_party.gcn.gcn.utils import preprocess_features
def load_test_edge_mask(dataset_str, data_path, drop_edge_prop):
"""Remove test edges by loading edge masks."""
edge_mask_path = os.path.join(
data_path, 'emask.{}.remove{}.npz'.format(dataset_str, drop_edge_prop))
with tf.gfile.Open(edge_mask_path) as f:
mask = sp.load_npz(f)
return mask
def load_edge_masks(dataset_str, data_path, adj_true, drop_edge_prop):
"""Loads adjacency matrix as sparse matrix and masks for val & test links.
Args:
dataset_str: dataset to use
data_path: path to data folder
adj_true: true adjacency matrix in dense format,
drop_edge_prop: proportion of edges to remove.
Returns:
adj_matrix: adjacency matrix
train_mask: mask for train edges
val_mask: mask for val edges
test_mask: mask for test edges
"""
edge_mask_path = os.path.join(
data_path, 'emask.{}.remove{}.'.format(dataset_str, drop_edge_prop))
val_mask = sp.load_npz(edge_mask_path + 'val.npz')
test_mask = sp.load_npz(edge_mask_path + 'test.npz')
train_mask = 1. - val_mask.todense() - test_mask.todense()
# remove val and test edges from true A
adj_train = np.multiply(adj_true, train_mask)
train_mask -= np.eye(train_mask.shape[0])
return adj_train, sparse_to_tuple(val_mask), sparse_to_tuple(
val_mask), sparse_to_tuple(test_mask)
def add_top_k_edges(data, edge_mask_path, gae_scores_path, topk, nb_nodes,
norm_adj):
"""Loads GAE scores and adds topK edges to train adjacency."""
test_mask = sp.load_npz(os.path.join(edge_mask_path, 'test_mask.npz'))
train_mask = 1. - test_mask.todense()
# remove val and test edges from true A
adj_train_curr = np.multiply(data['adj_true'], train_mask)
# Predict test edges using precomputed scores
scores = np.load(os.path.join(gae_scores_path, 'gae_scores.npy'))
# scores_mask = 1 - np.eye(nb_nodes)
scores_mask = np.zeros((nb_nodes, nb_nodes))
scores_mask[:140, 140:] = 1.
scores_mask[140:, :140] = 1.
scores = np.multiply(scores, scores_mask).reshape((-1,))
threshold = scores[np.argsort(-scores)[topk]]
adj_train_curr += 1 * (scores > threshold).reshape((nb_nodes, nb_nodes))
adj_train_curr = 1 * (adj_train_curr > 0)
if norm_adj:
adj_train_norm = normalize_adj(data['adj_train'])
else:
adj_train_norm = sp.coo_matrix(data['adj_train'])
return adj_train_curr, sparse_to_tuple(adj_train_norm)
def process_adj(adj, model_name):
"""Symmetrically normalize adjacency matrix."""
if model_name == 'Cheby':
laplacian = sp.eye(adj.shape[0]) - normalize_adj(adj - sp.eye(adj.shape[0]))
# TODO(chamii): compare with
# adj)
largest_eigval, _ = eigsh(laplacian, 1, which='LM')
laplacian_norm = (2. / largest_eigval[0]) * laplacian - sp.eye(adj.shape[0])
return laplacian_norm
else:
return normalize_adj(adj)
def load_data(dataset_str, data_path):
if dataset_str in ['cora', 'citeseer', 'pubmed']:
return load_citation_data(dataset_str, data_path)
else:
return load_ppi_data(data_path)
def load_ppi_data(data_path):
"""Load PPI dataset."""
with tf.gfile.Open(os.path.join(data_path, 'ppi.edges.npz')) as f:
adj = sp.load_npz(f)
with tf.gfile.Open(os.path.join(data_path, 'ppi.features.norm.npy')) as f:
features = np.load(f)
with tf.gfile.Open(os.path.join(data_path, 'ppi.labels.npz')) as f:
labels = sp.load_npz(f).todense()
train_mask = np.load(
tf.gfile.Open(os.path.join(data_path, 'ppi.train_mask.npy'))) > 0
val_mask = np.load(
tf.gfile.Open(os.path.join(data_path, 'ppi.test_mask.npy'))) > 0
test_mask = np.load(
tf.gfile.Open(os.path.join(data_path, 'ppi.test_mask.npy'))) > 0
return adj, features, labels, train_mask, val_mask, test_mask
def load_citation_data(dataset_str, data_path):
"""Load data."""
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = {}
for name in names:
with tf.gfile.Open(
os.path.join(data_path, 'ind.{}.{}'.format(dataset_str, name)),
'rb') as f:
if sys.version_info > (3, 0):
objects[name] = pkl.load(f) # , encoding='latin1') comment to pass lint
else:
objects[name] = pkl.load(f)
test_idx_reorder = parse_index_file(
os.path.join(data_path, 'ind.{}.test.index'.format(dataset_str)))
test_idx_range = np.sort(test_idx_reorder)
if dataset_str == 'citeseer':
# Fix citeseer dataset (there are some isolated nodes in the graph)
# Find isolated nodes, add them as zero-vecs into the right position
test_idx_range_full = range(
min(test_idx_reorder),
max(test_idx_reorder) + 1)
tx_extended = sp.lil_matrix((len(test_idx_range_full),
objects['x'].shape[1]))
tx_extended[test_idx_range - min(test_idx_range), :] = objects['tx']
objects['tx'] = tx_extended
ty_extended = np.zeros((len(test_idx_range_full),
objects['y'].shape[1]))
ty_extended[test_idx_range - min(test_idx_range), :] = objects['ty']
objects['ty'] = ty_extended
features = sp.vstack((objects['allx'], objects['tx'])).tolil()
features[test_idx_reorder, :] = features[test_idx_range, :]
adj = nx.adjacency_matrix(nx.from_dict_of_lists(objects['graph']))
labels = np.vstack((objects['ally'], objects['ty']))
labels[test_idx_reorder, :] = labels[test_idx_range, :]
idx_test = test_idx_range.tolist()
idx_train = range(len(objects['y']))
idx_val = range(len(objects['y']), len(objects['y']) + 500)
train_mask = sample_mask(idx_train, labels.shape[0])
val_mask = sample_mask(idx_val, labels.shape[0])
test_mask = sample_mask(idx_test, labels.shape[0])
features = preprocess_features(features)
return adj, features, labels, train_mask, val_mask, test_mask
def construct_feed_dict(adj_normalized, adj, features, placeholders):
# construct feed dictionary
feed_dict = dict()
feed_dict.update({placeholders['features']: features})
feed_dict.update({placeholders['adj']: adj_normalized})
feed_dict.update({placeholders['adj_orig']: adj})
return feed_dict
def mask_val_test_edges(adj, prop):
"""Function to mask test and val edges."""
# NOTE: Splits are randomized and results might slightly
# deviate from reported numbers in the paper.
# Remove diagonal elements
adj = adj - sp.dia_matrix(
(adj.diagonal()[np.newaxis, :], [0]), shape=adj.shape)
adj.eliminate_zeros()
# Check that diag is zero:
assert np.diag(adj.todense()).sum() == 0
adj_triu = sp.triu(adj)
adj_tuple = sparse_to_tuple(adj_triu)
edges = adj_tuple[0]
edges_all = sparse_to_tuple(adj)[0]
num_test = int(np.floor(edges.shape[0] * prop))
# num_val = int(np.floor(edges.shape[0] * 0.05)) # we keep 5% for validation
# we keep 10% of training edges for validation
num_val = int(np.floor((edges.shape[0] - num_test) * 0.05))
all_edge_idx = range(edges.shape[0])
np.random.shuffle(all_edge_idx)
val_edge_idx = all_edge_idx[:num_val]
test_edge_idx = all_edge_idx[num_val:(num_val + num_test)]
test_edges = edges[test_edge_idx]
val_edges = edges[val_edge_idx]
train_edges = np.delete(
edges, np.hstack([test_edge_idx, val_edge_idx]), axis=0)
def ismember(a, b, tol=5):
rows_close = np.all(np.round(a - b[:, None], tol) == 0, axis=-1)
return np.any(rows_close)
test_edges_false = []
while len(test_edges_false) < len(test_edges):
idx_i = np.random.randint(0, adj.shape[0])
idx_j = np.random.randint(0, adj.shape[0])
if idx_i == idx_j:
continue
if ismember([idx_i, idx_j], edges_all):
continue
if test_edges_false:
if ismember([idx_j, idx_i], np.array(test_edges_false)):
continue
if ismember([idx_i, idx_j], np.array(test_edges_false)):
continue
test_edges_false.append([idx_i, idx_j])
val_edges_false = []
while len(val_edges_false) < len(val_edges):
idx_i = np.random.randint(0, adj.shape[0])
idx_j = np.random.randint(0, adj.shape[0])
if idx_i == idx_j:
continue
if ismember([idx_i, idx_j], train_edges):
continue
if ismember([idx_j, idx_i], train_edges):
continue
if ismember([idx_i, idx_j], val_edges):
continue
if ismember([idx_j, idx_i], val_edges):
continue
if val_edges_false:
if ismember([idx_j, idx_i], np.array(val_edges_false)):
continue
if ismember([idx_i, idx_j], np.array(val_edges_false)):
continue
val_edges_false.append([idx_i, idx_j])
assert ~ismember(test_edges_false, edges_all)
assert ~ismember(val_edges_false, edges_all)
assert ~ismember(val_edges, train_edges)
assert ~ismember(test_edges, train_edges)
assert ~ismember(val_edges, test_edges)
data = np.ones(train_edges.shape[0])
# Re-build adj matrix
adj_train = sp.csr_matrix((data, (train_edges[:, 0], train_edges[:, 1])),
shape=adj.shape)
adj_train = adj_train + adj_train.T
# NOTE: these edge lists only contain single direction of edge!
num_nodes = adj.shape[0]
val_mask = np.zeros((num_nodes, num_nodes))
for i, j in val_edges:
val_mask[i, j] = 1
val_mask[j, i] = 1
for i, j in val_edges_false:
val_mask[i, j] = 1
val_mask[j, i] = 1
test_mask = np.zeros((num_nodes, num_nodes))
for i, j in test_edges:
test_mask[i, j] = 1
test_mask[j, i] = 1
for i, j in test_edges_false:
test_mask[i, j] = 1
test_mask[j, i] = 1
return adj_train, sparse_to_tuple(val_mask), sparse_to_tuple(test_mask)
def mask_test_edges(adj, prop):
"""Function to mask test edges.
Args:
adj: scipy sparse matrix
prop: proportion of edges to remove (float in [0, 1])
Returns:
adj_train: adjacency with edges removed
test_edges: list of positive and negative test edges
"""
# Remove diagonal elements
adj = adj - sp.dia_matrix(
(adj.diagonal()[np.newaxis, :], [0]), shape=adj.shape)
adj.eliminate_zeros()
# Check that diag is zero:
assert np.diag(adj.todense()).sum() == 0
adj_triu = sp.triu(adj)
adj_tuple = sparse_to_tuple(adj_triu)
edges = adj_tuple[0]
edges_all = sparse_to_tuple(adj)[0]
num_test = int(np.floor(edges.shape[0] * prop))
all_edge_idx = range(edges.shape[0])
np.random.shuffle(all_edge_idx)
test_edge_idx = all_edge_idx[:num_test]
test_edges = edges[test_edge_idx]
train_edges = np.delete(edges, test_edge_idx, axis=0)
def ismember(a, b, tol=5):
rows_close = np.all(np.round(a - b[:, None], tol) == 0, axis=-1)
return np.any(rows_close)
test_edges_false = []
while len(test_edges_false) < len(test_edges):
idx_i = np.random.randint(0, adj.shape[0])
idx_j = np.random.randint(0, adj.shape[0])
if idx_i == idx_j:
continue
if ismember([idx_i, idx_j], edges_all):
continue
if test_edges_false:
if ismember([idx_j, idx_i], np.array(test_edges_false)):
continue
if ismember([idx_i, idx_j], np.array(test_edges_false)):
continue
test_edges_false.append([idx_i, idx_j])
assert ~ismember(test_edges_false, edges_all)
assert ~ismember(test_edges, train_edges)
data = np.ones(train_edges.shape[0])
# Re-build adj matrix
adj_train = sp.csr_matrix((data, (train_edges[:, 0], train_edges[:, 1])),
shape=adj.shape)
adj_train = adj_train + adj_train.T
# NOTE: these edge lists only contain single direction of edge!
num_nodes = adj.shape[0]
test_mask = np.zeros((num_nodes, num_nodes))
for i, j in test_edges:
test_mask[i, j] = 1
test_mask[j, i] = 1
for i, j in test_edges_false:
test_mask[i, j] = 1
test_mask[j, i] = 1
return adj_train, sparse_to_tuple(test_mask)
| 34.772358 | 80 | 0.691996 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import pickle as pkl
import sys
import networkx as nx
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
import tensorflow as tf
from third_party.gcn.gcn.utils import normalize_adj
from third_party.gcn.gcn.utils import parse_index_file
from third_party.gcn.gcn.utils import sample_mask
from third_party.gcn.gcn.utils import sparse_to_tuple
from third_party.gcn.gcn.utils import preprocess_features
def load_test_edge_mask(dataset_str, data_path, drop_edge_prop):
edge_mask_path = os.path.join(
data_path, 'emask.{}.remove{}.npz'.format(dataset_str, drop_edge_prop))
with tf.gfile.Open(edge_mask_path) as f:
mask = sp.load_npz(f)
return mask
def load_edge_masks(dataset_str, data_path, adj_true, drop_edge_prop):
edge_mask_path = os.path.join(
data_path, 'emask.{}.remove{}.'.format(dataset_str, drop_edge_prop))
val_mask = sp.load_npz(edge_mask_path + 'val.npz')
test_mask = sp.load_npz(edge_mask_path + 'test.npz')
train_mask = 1. - val_mask.todense() - test_mask.todense()
adj_train = np.multiply(adj_true, train_mask)
train_mask -= np.eye(train_mask.shape[0])
return adj_train, sparse_to_tuple(val_mask), sparse_to_tuple(
val_mask), sparse_to_tuple(test_mask)
def add_top_k_edges(data, edge_mask_path, gae_scores_path, topk, nb_nodes,
norm_adj):
test_mask = sp.load_npz(os.path.join(edge_mask_path, 'test_mask.npz'))
train_mask = 1. - test_mask.todense()
adj_train_curr = np.multiply(data['adj_true'], train_mask)
scores = np.load(os.path.join(gae_scores_path, 'gae_scores.npy'))
scores_mask = np.zeros((nb_nodes, nb_nodes))
scores_mask[:140, 140:] = 1.
scores_mask[140:, :140] = 1.
scores = np.multiply(scores, scores_mask).reshape((-1,))
threshold = scores[np.argsort(-scores)[topk]]
adj_train_curr += 1 * (scores > threshold).reshape((nb_nodes, nb_nodes))
adj_train_curr = 1 * (adj_train_curr > 0)
if norm_adj:
adj_train_norm = normalize_adj(data['adj_train'])
else:
adj_train_norm = sp.coo_matrix(data['adj_train'])
return adj_train_curr, sparse_to_tuple(adj_train_norm)
def process_adj(adj, model_name):
if model_name == 'Cheby':
laplacian = sp.eye(adj.shape[0]) - normalize_adj(adj - sp.eye(adj.shape[0]))
largest_eigval, _ = eigsh(laplacian, 1, which='LM')
laplacian_norm = (2. / largest_eigval[0]) * laplacian - sp.eye(adj.shape[0])
return laplacian_norm
else:
return normalize_adj(adj)
def load_data(dataset_str, data_path):
if dataset_str in ['cora', 'citeseer', 'pubmed']:
return load_citation_data(dataset_str, data_path)
else:
return load_ppi_data(data_path)
def load_ppi_data(data_path):
with tf.gfile.Open(os.path.join(data_path, 'ppi.edges.npz')) as f:
adj = sp.load_npz(f)
with tf.gfile.Open(os.path.join(data_path, 'ppi.features.norm.npy')) as f:
features = np.load(f)
with tf.gfile.Open(os.path.join(data_path, 'ppi.labels.npz')) as f:
labels = sp.load_npz(f).todense()
train_mask = np.load(
tf.gfile.Open(os.path.join(data_path, 'ppi.train_mask.npy'))) > 0
val_mask = np.load(
tf.gfile.Open(os.path.join(data_path, 'ppi.test_mask.npy'))) > 0
test_mask = np.load(
tf.gfile.Open(os.path.join(data_path, 'ppi.test_mask.npy'))) > 0
return adj, features, labels, train_mask, val_mask, test_mask
def load_citation_data(dataset_str, data_path):
names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
objects = {}
for name in names:
with tf.gfile.Open(
os.path.join(data_path, 'ind.{}.{}'.format(dataset_str, name)),
'rb') as f:
if sys.version_info > (3, 0):
objects[name] = pkl.load(f)
else:
objects[name] = pkl.load(f)
test_idx_reorder = parse_index_file(
os.path.join(data_path, 'ind.{}.test.index'.format(dataset_str)))
test_idx_range = np.sort(test_idx_reorder)
if dataset_str == 'citeseer':
test_idx_range_full = range(
min(test_idx_reorder),
max(test_idx_reorder) + 1)
tx_extended = sp.lil_matrix((len(test_idx_range_full),
objects['x'].shape[1]))
tx_extended[test_idx_range - min(test_idx_range), :] = objects['tx']
objects['tx'] = tx_extended
ty_extended = np.zeros((len(test_idx_range_full),
objects['y'].shape[1]))
ty_extended[test_idx_range - min(test_idx_range), :] = objects['ty']
objects['ty'] = ty_extended
features = sp.vstack((objects['allx'], objects['tx'])).tolil()
features[test_idx_reorder, :] = features[test_idx_range, :]
adj = nx.adjacency_matrix(nx.from_dict_of_lists(objects['graph']))
labels = np.vstack((objects['ally'], objects['ty']))
labels[test_idx_reorder, :] = labels[test_idx_range, :]
idx_test = test_idx_range.tolist()
idx_train = range(len(objects['y']))
idx_val = range(len(objects['y']), len(objects['y']) + 500)
train_mask = sample_mask(idx_train, labels.shape[0])
val_mask = sample_mask(idx_val, labels.shape[0])
test_mask = sample_mask(idx_test, labels.shape[0])
features = preprocess_features(features)
return adj, features, labels, train_mask, val_mask, test_mask
def construct_feed_dict(adj_normalized, adj, features, placeholders):
feed_dict = dict()
feed_dict.update({placeholders['features']: features})
feed_dict.update({placeholders['adj']: adj_normalized})
feed_dict.update({placeholders['adj_orig']: adj})
return feed_dict
def mask_val_test_edges(adj, prop):
adj = adj - sp.dia_matrix(
(adj.diagonal()[np.newaxis, :], [0]), shape=adj.shape)
adj.eliminate_zeros()
assert np.diag(adj.todense()).sum() == 0
adj_triu = sp.triu(adj)
adj_tuple = sparse_to_tuple(adj_triu)
edges = adj_tuple[0]
edges_all = sparse_to_tuple(adj)[0]
num_test = int(np.floor(edges.shape[0] * prop))
r((edges.shape[0] - num_test) * 0.05))
all_edge_idx = range(edges.shape[0])
np.random.shuffle(all_edge_idx)
val_edge_idx = all_edge_idx[:num_val]
test_edge_idx = all_edge_idx[num_val:(num_val + num_test)]
test_edges = edges[test_edge_idx]
val_edges = edges[val_edge_idx]
train_edges = np.delete(
edges, np.hstack([test_edge_idx, val_edge_idx]), axis=0)
def ismember(a, b, tol=5):
rows_close = np.all(np.round(a - b[:, None], tol) == 0, axis=-1)
return np.any(rows_close)
test_edges_false = []
while len(test_edges_false) < len(test_edges):
idx_i = np.random.randint(0, adj.shape[0])
idx_j = np.random.randint(0, adj.shape[0])
if idx_i == idx_j:
continue
if ismember([idx_i, idx_j], edges_all):
continue
if test_edges_false:
if ismember([idx_j, idx_i], np.array(test_edges_false)):
continue
if ismember([idx_i, idx_j], np.array(test_edges_false)):
continue
test_edges_false.append([idx_i, idx_j])
val_edges_false = []
while len(val_edges_false) < len(val_edges):
idx_i = np.random.randint(0, adj.shape[0])
idx_j = np.random.randint(0, adj.shape[0])
if idx_i == idx_j:
continue
if ismember([idx_i, idx_j], train_edges):
continue
if ismember([idx_j, idx_i], train_edges):
continue
if ismember([idx_i, idx_j], val_edges):
continue
if ismember([idx_j, idx_i], val_edges):
continue
if val_edges_false:
if ismember([idx_j, idx_i], np.array(val_edges_false)):
continue
if ismember([idx_i, idx_j], np.array(val_edges_false)):
continue
val_edges_false.append([idx_i, idx_j])
assert ~ismember(test_edges_false, edges_all)
assert ~ismember(val_edges_false, edges_all)
assert ~ismember(val_edges, train_edges)
assert ~ismember(test_edges, train_edges)
assert ~ismember(val_edges, test_edges)
data = np.ones(train_edges.shape[0])
adj_train = sp.csr_matrix((data, (train_edges[:, 0], train_edges[:, 1])),
shape=adj.shape)
adj_train = adj_train + adj_train.T
num_nodes = adj.shape[0]
val_mask = np.zeros((num_nodes, num_nodes))
for i, j in val_edges:
val_mask[i, j] = 1
val_mask[j, i] = 1
for i, j in val_edges_false:
val_mask[i, j] = 1
val_mask[j, i] = 1
test_mask = np.zeros((num_nodes, num_nodes))
for i, j in test_edges:
test_mask[i, j] = 1
test_mask[j, i] = 1
for i, j in test_edges_false:
test_mask[i, j] = 1
test_mask[j, i] = 1
return adj_train, sparse_to_tuple(val_mask), sparse_to_tuple(test_mask)
def mask_test_edges(adj, prop):
adj = adj - sp.dia_matrix(
(adj.diagonal()[np.newaxis, :], [0]), shape=adj.shape)
adj.eliminate_zeros()
assert np.diag(adj.todense()).sum() == 0
adj_triu = sp.triu(adj)
adj_tuple = sparse_to_tuple(adj_triu)
edges = adj_tuple[0]
edges_all = sparse_to_tuple(adj)[0]
num_test = int(np.floor(edges.shape[0] * prop))
all_edge_idx = range(edges.shape[0])
np.random.shuffle(all_edge_idx)
test_edge_idx = all_edge_idx[:num_test]
test_edges = edges[test_edge_idx]
train_edges = np.delete(edges, test_edge_idx, axis=0)
def ismember(a, b, tol=5):
rows_close = np.all(np.round(a - b[:, None], tol) == 0, axis=-1)
return np.any(rows_close)
test_edges_false = []
while len(test_edges_false) < len(test_edges):
idx_i = np.random.randint(0, adj.shape[0])
idx_j = np.random.randint(0, adj.shape[0])
if idx_i == idx_j:
continue
if ismember([idx_i, idx_j], edges_all):
continue
if test_edges_false:
if ismember([idx_j, idx_i], np.array(test_edges_false)):
continue
if ismember([idx_i, idx_j], np.array(test_edges_false)):
continue
test_edges_false.append([idx_i, idx_j])
assert ~ismember(test_edges_false, edges_all)
assert ~ismember(test_edges, train_edges)
data = np.ones(train_edges.shape[0])
adj_train = sp.csr_matrix((data, (train_edges[:, 0], train_edges[:, 1])),
shape=adj.shape)
adj_train = adj_train + adj_train.T
num_nodes = adj.shape[0]
test_mask = np.zeros((num_nodes, num_nodes))
for i, j in test_edges:
test_mask[i, j] = 1
test_mask[j, i] = 1
for i, j in test_edges_false:
test_mask[i, j] = 1
test_mask[j, i] = 1
return adj_train, sparse_to_tuple(test_mask)
| true | true |
f72c2b187dd8c532b6839213766774021ef6ff74 | 33 | py | Python | tests/__init__.py | yoophi/flask-google-login-example | 57cbbcbd054a6ba47c2a492950bf500b6b595b7d | [
"MIT"
] | null | null | null | tests/__init__.py | yoophi/flask-google-login-example | 57cbbcbd054a6ba47c2a492950bf500b6b595b7d | [
"MIT"
] | null | null | null | tests/__init__.py | yoophi/flask-google-login-example | 57cbbcbd054a6ba47c2a492950bf500b6b595b7d | [
"MIT"
] | null | null | null | """Unit test package for app."""
| 16.5 | 32 | 0.636364 | true | true | |
f72c2cf7b738c597ce705f662cdf1e0bb2603530 | 323 | py | Python | mmcap/models/utils/__init__.py | hnp0411/mmcaptioning | 47bcdee3734cdaaa96a34e927cdec5cc43cab538 | [
"Apache-2.0"
] | null | null | null | mmcap/models/utils/__init__.py | hnp0411/mmcaptioning | 47bcdee3734cdaaa96a34e927cdec5cc43cab538 | [
"Apache-2.0"
] | null | null | null | mmcap/models/utils/__init__.py | hnp0411/mmcaptioning | 47bcdee3734cdaaa96a34e927cdec5cc43cab538 | [
"Apache-2.0"
] | null | null | null | from .gaussian_target import gaussian_radius, gen_gaussian_target
from .res_layer import ResLayer
from .position_embedding_2d import PositionEmbeddingSine
from .sampling import topktopp
__all__ = ['ResLayer',
'gaussian_radius', 'gen_gaussian_target',
'PositionEmbeddingSine',
'topktopp']
| 32.3 | 65 | 0.749226 | from .gaussian_target import gaussian_radius, gen_gaussian_target
from .res_layer import ResLayer
from .position_embedding_2d import PositionEmbeddingSine
from .sampling import topktopp
__all__ = ['ResLayer',
'gaussian_radius', 'gen_gaussian_target',
'PositionEmbeddingSine',
'topktopp']
| true | true |
f72c2daa1aa4397686149633191ba4e69a6e8ed2 | 425 | py | Python | MachineLearning/DecisionTree/loan_delinquency.py | yexianyi/AI_Practice | 80499ab3a06ac055641aa069fe1e37864c9e41c4 | [
"Apache-2.0"
] | null | null | null | MachineLearning/DecisionTree/loan_delinquency.py | yexianyi/AI_Practice | 80499ab3a06ac055641aa069fe1e37864c9e41c4 | [
"Apache-2.0"
] | null | null | null | MachineLearning/DecisionTree/loan_delinquency.py | yexianyi/AI_Practice | 80499ab3a06ac055641aa069fe1e37864c9e41c4 | [
"Apache-2.0"
] | null | null | null | '''
Decision Tree
Predict if it is possible to default on the loan
'''
import numpy as np
from sklearn import tree
data = np.genfromtxt("exercise.csv", delimiter=",")
# get train data set
x_data = data[1:, 1:-1]
# get test data set
y_data = data[1:, -1]
print(x_data)
print(y_data)
# Create decision tree
dtree = tree.DecisionTreeClassifier(min_samples_leaf=5)
dtree.fit(x_data, y_data)
print(dtree.score(x_data, y_data))
| 20.238095 | 55 | 0.734118 | import numpy as np
from sklearn import tree
data = np.genfromtxt("exercise.csv", delimiter=",")
x_data = data[1:, 1:-1]
y_data = data[1:, -1]
print(x_data)
print(y_data)
dtree = tree.DecisionTreeClassifier(min_samples_leaf=5)
dtree.fit(x_data, y_data)
print(dtree.score(x_data, y_data))
| true | true |
f72c2df55f1cc8270d405748ec5245b4671cc4a9 | 1,680 | py | Python | test/test_flac3d.py | ffilotto/meshio | 4413be41e6a63e33273665986f42dab80d585d10 | [
"MIT"
] | null | null | null | test/test_flac3d.py | ffilotto/meshio | 4413be41e6a63e33273665986f42dab80d585d10 | [
"MIT"
] | null | null | null | test/test_flac3d.py | ffilotto/meshio | 4413be41e6a63e33273665986f42dab80d585d10 | [
"MIT"
] | null | null | null | import copy
import pathlib
import sys
import helpers
import numpy
import pytest
import meshio
@pytest.mark.parametrize(
"mesh, binary, data",
[
(helpers.tet_mesh, False, []),
(helpers.hex_mesh, False, []),
(helpers.tet_mesh, False, [1, 2]),
(helpers.tet_mesh, True, []),
(helpers.hex_mesh, True, []),
(helpers.tet_mesh, True, [1, 2]),
],
)
def test(mesh, binary, data):
if data:
mesh = copy.deepcopy(mesh)
mesh.cell_data["flac3d:zone"] = [numpy.array(data)]
helpers.write_read(
lambda f, m: meshio.flac3d.write(f, m, binary=binary),
meshio.flac3d.read,
mesh,
1.0e-15,
)
# the failure perhaps has to do with dictionary ordering
@pytest.mark.skipif(sys.version_info < (3, 6), reason="Fails with 3.5")
@pytest.mark.parametrize(
"filename", ["flac3d_mesh_ex.f3grid", "flac3d_mesh_ex_bin.f3grid"],
)
def test_reference_file(filename):
this_dir = pathlib.Path(__file__).resolve().parent
filename = this_dir / "meshes" / "flac3d" / filename
mesh = meshio.read(filename)
# points
assert numpy.isclose(mesh.points.sum(), 307.0)
# cells
ref_num_cells = [
("hexahedron", 45),
("pyramid", 9),
("hexahedron", 18),
("wedge", 9),
("hexahedron", 6),
("wedge", 3),
("hexahedron", 6),
("wedge", 3),
("pyramid", 6),
("tetra", 3),
]
assert [(k, len(v)) for k, v in mesh.cells] == ref_num_cells
# Cell data
ref_sum_cell_data = [45, 9, 18, 9, 6, 3, 6, 3, 6, 3]
assert [len(arr) for arr in mesh.cell_data["flac3d:zone"]] == ref_sum_cell_data
| 25.454545 | 83 | 0.583333 | import copy
import pathlib
import sys
import helpers
import numpy
import pytest
import meshio
@pytest.mark.parametrize(
"mesh, binary, data",
[
(helpers.tet_mesh, False, []),
(helpers.hex_mesh, False, []),
(helpers.tet_mesh, False, [1, 2]),
(helpers.tet_mesh, True, []),
(helpers.hex_mesh, True, []),
(helpers.tet_mesh, True, [1, 2]),
],
)
def test(mesh, binary, data):
if data:
mesh = copy.deepcopy(mesh)
mesh.cell_data["flac3d:zone"] = [numpy.array(data)]
helpers.write_read(
lambda f, m: meshio.flac3d.write(f, m, binary=binary),
meshio.flac3d.read,
mesh,
1.0e-15,
)
@pytest.mark.skipif(sys.version_info < (3, 6), reason="Fails with 3.5")
@pytest.mark.parametrize(
"filename", ["flac3d_mesh_ex.f3grid", "flac3d_mesh_ex_bin.f3grid"],
)
def test_reference_file(filename):
this_dir = pathlib.Path(__file__).resolve().parent
filename = this_dir / "meshes" / "flac3d" / filename
mesh = meshio.read(filename)
assert numpy.isclose(mesh.points.sum(), 307.0)
ref_num_cells = [
("hexahedron", 45),
("pyramid", 9),
("hexahedron", 18),
("wedge", 9),
("hexahedron", 6),
("wedge", 3),
("hexahedron", 6),
("wedge", 3),
("pyramid", 6),
("tetra", 3),
]
assert [(k, len(v)) for k, v in mesh.cells] == ref_num_cells
ref_sum_cell_data = [45, 9, 18, 9, 6, 3, 6, 3, 6, 3]
assert [len(arr) for arr in mesh.cell_data["flac3d:zone"]] == ref_sum_cell_data
| true | true |
f72c2f6aa5e33817498aeaf30c0f710fd5347dc0 | 471 | py | Python | examples/idioms/programs/177.3241-find-files-with-a-given-list-of-filename-extensions.py | laowantong/paroxython | 4626798a60eeaa765dbfab9e63e04030c9fcb1d0 | [
"MIT"
] | 31 | 2020-05-02T13:34:26.000Z | 2021-06-06T17:25:52.000Z | examples/idioms/programs/177.3241-find-files-with-a-given-list-of-filename-extensions.py | laowantong/paroxython | 4626798a60eeaa765dbfab9e63e04030c9fcb1d0 | [
"MIT"
] | 108 | 2019-11-18T19:41:52.000Z | 2022-03-18T13:58:17.000Z | examples/idioms/programs/177.3241-find-files-with-a-given-list-of-filename-extensions.py | laowantong/paroxython | 4626798a60eeaa765dbfab9e63e04030c9fcb1d0 | [
"MIT"
] | 4 | 2020-05-19T08:57:44.000Z | 2020-09-21T08:53:46.000Z | """Find files with a given list of filename extensions.
Construct a list _L that contains all filenames that have the extension ".jpg" , ".jpeg" or ".png" in directory _D and all it's subdirectories.
Source: Bart
"""
# Implementation author: charlax
# Created on 2019-09-27T11:33:27.420533Z
# Last modified on 2019-09-27T11:33:27.420533Z
# Version 1
import glob
import itertools
list(itertools.chain(*(glob.glob("*/**.%s" % ext) for ext in ["jpg", "jpeg", "png"])))
| 27.705882 | 143 | 0.713376 |
import glob
import itertools
list(itertools.chain(*(glob.glob("*/**.%s" % ext) for ext in ["jpg", "jpeg", "png"])))
| true | true |
f72c31469cfb67208d5848f60740b7c718ec496d | 160 | py | Python | src/battery/battery.py | BigOz/flourish | a45f9d0290878c69237fdd1949ee42f9e6039df9 | [
"BSD-2-Clause"
] | null | null | null | src/battery/battery.py | BigOz/flourish | a45f9d0290878c69237fdd1949ee42f9e6039df9 | [
"BSD-2-Clause"
] | null | null | null | src/battery/battery.py | BigOz/flourish | a45f9d0290878c69237fdd1949ee42f9e6039df9 | [
"BSD-2-Clause"
] | null | null | null | class Battery:
def __init__(self, evaluator):
raise NotImplementedError
def get_action(self, current_state):
raise NotImplementedError
| 22.857143 | 40 | 0.7125 | class Battery:
def __init__(self, evaluator):
raise NotImplementedError
def get_action(self, current_state):
raise NotImplementedError
| true | true |
f72c3198aa025287611b7e30ff0d1259ec7834b8 | 8,969 | py | Python | cache_dependencies/tests/test_transaction.py | Tusky/cache-dependencies | 6c19d0c2adfce19c3fdc53ad5704eddc6d84e106 | [
"BSD-3-Clause"
] | 3 | 2017-08-08T20:06:56.000Z | 2018-09-19T03:16:20.000Z | cache_dependencies/tests/test_transaction.py | Tusky/cache-dependencies | 6c19d0c2adfce19c3fdc53ad5704eddc6d84e106 | [
"BSD-3-Clause"
] | 1 | 2017-10-24T23:11:32.000Z | 2017-10-24T23:11:32.000Z | cache_dependencies/tests/test_transaction.py | Tusky/cache-dependencies | 6c19d0c2adfce19c3fdc53ad5704eddc6d84e106 | [
"BSD-3-Clause"
] | 8 | 2017-10-24T07:43:56.000Z | 2021-06-17T07:03:02.000Z | import time
import unittest
from cache_dependencies import interfaces, transaction
try:
from unittest import mock
except ImportError:
import mock
try:
str = unicode # Python 2.* compatible
string_types = (basestring,)
integer_types = (int, long)
except NameError:
string_types = (str,)
integer_types = (int,)
class AbstractTransactionTestCase(unittest.TestCase):
def setUp(self):
self.current_time = mock.Mock(return_value=time.time())
self.lock = mock.Mock(spec=interfaces.IDependency)
self.parent = mock.Mock(spec=interfaces.ITransaction)
self.transaction = self._make_transaction(self.lock, self.parent, self.current_time)
self.dependency = self._make_dependency()
def _make_transaction(self, lock, parent, current_time_accessor):
raise NotImplementedError
@staticmethod
def _make_dependency():
instance = mock.Mock(spec=interfaces.IDependency)
instance.extend = mock.Mock(return_value=True)
return instance
def test_evaluate(self):
self.transaction.evaluate(self.dependency, 1)
self.lock.evaluate.assert_called_once_with(self.dependency, self.transaction, 1)
def test_get_session_id(self):
session1_id = self.transaction.get_session_id()
session2_id = self.transaction.get_session_id()
self.assertEqual(session1_id, session2_id)
self.assertIsInstance(session2_id, string_types)
def run(self, result=None):
if self.__class__.__name__.startswith('Abstract'):
return
super(AbstractTransactionTestCase, self).run(result)
class TransactionTestCase(AbstractTransactionTestCase):
def _make_transaction(self, lock, parent, current_time_accessor):
class Transaction(transaction.Transaction):
_current_time = current_time_accessor
return Transaction(lock)
def test_parent(self):
self.assertIsNone(self.transaction.parent())
def test_get_start_time(self):
self.current_time.reset_mock()
self.assertAlmostEqual(self.transaction.get_start_time(), self.current_time.return_value)
initial_return_value = self.current_time.return_value
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_start_time(), initial_return_value)
self.current_time.assert_not_called()
def test_get_end_time(self):
self.current_time.reset_mock()
with self.assertRaises(RuntimeError):
self.transaction.get_end_time()
self.current_time.return_value += 1
self.transaction.finish()
self.assertAlmostEqual(self.transaction.get_end_time(), self.current_time.return_value)
initial_return_value = self.current_time.return_value
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_end_time(), initial_return_value)
self.current_time.assert_called_once_with()
def test_add_dependency_and_finish(self):
dependency1 = self._make_dependency()
dependency1.id = 1
dependency2 = self._make_dependency()
dependency2.id = 2
dependency3 = self._make_dependency()
dependency3.id = 3
self.transaction.add_dependency(dependency1, None)
self.lock.acquire.assert_called_once_with(dependency1, self.transaction, None)
self.lock.reset_mock()
self.transaction.add_dependency(dependency2, None)
self.lock.acquire.assert_called_once_with(dependency2, self.transaction, None)
self.lock.reset_mock()
dependency1.extend.assert_called_once_with(dependency2)
dependency1.reset_mock()
self.transaction.add_dependency(dependency3, 1)
self.lock.acquire.assert_called_once_with(dependency3, self.transaction, 1)
self.lock.reset_mock()
dependency1.extend.assert_not_called()
self.transaction.finish()
self.assertEqual(self.lock.release.call_count, 2)
args, kwargs = self.lock.release.call_args_list[-1]
self.assertEqual(len(args[0].delegates), 1)
self.assertEqual(args[0].delegates[0].id, 1)
self.assertIs(args[1], self.transaction)
self.assertIsNone(args[2])
args, kwargs = self.lock.release.call_args_list[-2]
self.assertEqual(len(args[0].delegates), 1)
self.assertEqual(args[0].delegates[0].id, 3)
self.assertIs(args[1], self.transaction)
self.assertEqual(args[2], 1)
def test_bool(self):
self.assertTrue(self.transaction)
class SavePointTestCase(AbstractTransactionTestCase):
def _make_transaction(self, lock, parent, current_time_accessor):
return transaction.SavePoint(lock, parent)
def test_parent(self):
self.assertIs(self.transaction.parent(), self.parent)
def test_get_start_time(self):
self.transaction.get_start_time()
self.parent.get_start_time.assert_called_once_with()
def test_get_end_time(self):
self.transaction.get_end_time()
self.parent.get_end_time.assert_called_once_with()
def test_add_dependency(self):
self.transaction.add_dependency(self.dependency, 1)
self.lock.acquire.assert_called_once_with(self.dependency, self.transaction, 1)
self.parent.add_dependency.assert_called_once_with(self.dependency, 1)
def test_bool(self):
self.assertTrue(self.transaction)
class DummyTransactionTestCase(AbstractTransactionTestCase):
def _make_transaction(self, lock, parent, current_time_accessor):
class DummyTransaction(transaction.DummyTransaction):
_current_time = current_time_accessor
return DummyTransaction(lock)
def test_parent(self):
self.assertIsNone(self.transaction.parent())
def test_get_start_time(self):
self.current_time.reset_mock()
self.assertAlmostEqual(self.transaction.get_start_time(), self.current_time.return_value)
initial_return_value = self.current_time.return_value
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_start_time(), self.current_time.return_value)
self.assertEqual(self.current_time.call_count, 2)
def test_get_end_time(self):
self.current_time.reset_mock()
self.current_time.return_value += 1
self.assertAlmostEqual(self.transaction.get_end_time(), self.current_time.return_value)
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_end_time(), self.current_time.return_value)
self.assertEqual(self.current_time.call_count, 2)
def test_bool(self):
self.assertFalse(self.transaction)
class TransactionManagerTestCase(unittest.TestCase):
def setUp(self):
self.transaction = mock.Mock(spec=interfaces.ITransaction)
self.lock = mock.Mock(spec=interfaces.IDependency)
self.transaction_manager = transaction.TransactionManager(self.lock)
def test_current_none(self):
current_transaction = self.transaction_manager.current()
self.assertIsInstance(current_transaction, transaction.DummyTransaction)
def test_current_set_get(self):
self.transaction_manager.current(self.transaction)
self.assertIs(self.transaction_manager.current(), self.transaction)
def test_begin(self):
initial_transaction = self.transaction_manager.begin()
self.assertIsInstance(initial_transaction, transaction.Transaction)
save_point = self.transaction_manager.begin()
self.assertIsInstance(save_point, transaction.SavePoint)
self.assertIs(save_point.parent(), initial_transaction)
nested_save_point = self.transaction_manager.begin()
self.assertIsInstance(nested_save_point, transaction.SavePoint)
self.assertIs(nested_save_point.parent(), save_point)
def test_finish_delegate_transaction(self):
self.transaction_manager.current(self.transaction)
self.transaction_manager.finish()
self.transaction.finish.assert_called_once_with()
def test_finish_transaction(self):
self.transaction_manager.begin()
self.transaction_manager.finish()
self.assertIsInstance(self.transaction_manager.current(), transaction.DummyTransaction)
def test_finish_savepoint(self):
initial_transaction = self.transaction_manager.begin()
self.transaction_manager.begin()
self.transaction_manager.finish()
self.assertIs(self.transaction_manager.current(), initial_transaction)
def test_flush(self):
self.transaction_manager.begin()
self.transaction_manager.begin()
self.transaction_manager.begin()
self.transaction_manager.flush()
self.assertIsInstance(self.transaction_manager.current(), transaction.DummyTransaction)
| 38.659483 | 97 | 0.721485 | import time
import unittest
from cache_dependencies import interfaces, transaction
try:
from unittest import mock
except ImportError:
import mock
try:
str = unicode
string_types = (basestring,)
integer_types = (int, long)
except NameError:
string_types = (str,)
integer_types = (int,)
class AbstractTransactionTestCase(unittest.TestCase):
def setUp(self):
self.current_time = mock.Mock(return_value=time.time())
self.lock = mock.Mock(spec=interfaces.IDependency)
self.parent = mock.Mock(spec=interfaces.ITransaction)
self.transaction = self._make_transaction(self.lock, self.parent, self.current_time)
self.dependency = self._make_dependency()
def _make_transaction(self, lock, parent, current_time_accessor):
raise NotImplementedError
@staticmethod
def _make_dependency():
instance = mock.Mock(spec=interfaces.IDependency)
instance.extend = mock.Mock(return_value=True)
return instance
def test_evaluate(self):
self.transaction.evaluate(self.dependency, 1)
self.lock.evaluate.assert_called_once_with(self.dependency, self.transaction, 1)
def test_get_session_id(self):
session1_id = self.transaction.get_session_id()
session2_id = self.transaction.get_session_id()
self.assertEqual(session1_id, session2_id)
self.assertIsInstance(session2_id, string_types)
def run(self, result=None):
if self.__class__.__name__.startswith('Abstract'):
return
super(AbstractTransactionTestCase, self).run(result)
class TransactionTestCase(AbstractTransactionTestCase):
def _make_transaction(self, lock, parent, current_time_accessor):
class Transaction(transaction.Transaction):
_current_time = current_time_accessor
return Transaction(lock)
def test_parent(self):
self.assertIsNone(self.transaction.parent())
def test_get_start_time(self):
self.current_time.reset_mock()
self.assertAlmostEqual(self.transaction.get_start_time(), self.current_time.return_value)
initial_return_value = self.current_time.return_value
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_start_time(), initial_return_value)
self.current_time.assert_not_called()
def test_get_end_time(self):
self.current_time.reset_mock()
with self.assertRaises(RuntimeError):
self.transaction.get_end_time()
self.current_time.return_value += 1
self.transaction.finish()
self.assertAlmostEqual(self.transaction.get_end_time(), self.current_time.return_value)
initial_return_value = self.current_time.return_value
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_end_time(), initial_return_value)
self.current_time.assert_called_once_with()
def test_add_dependency_and_finish(self):
dependency1 = self._make_dependency()
dependency1.id = 1
dependency2 = self._make_dependency()
dependency2.id = 2
dependency3 = self._make_dependency()
dependency3.id = 3
self.transaction.add_dependency(dependency1, None)
self.lock.acquire.assert_called_once_with(dependency1, self.transaction, None)
self.lock.reset_mock()
self.transaction.add_dependency(dependency2, None)
self.lock.acquire.assert_called_once_with(dependency2, self.transaction, None)
self.lock.reset_mock()
dependency1.extend.assert_called_once_with(dependency2)
dependency1.reset_mock()
self.transaction.add_dependency(dependency3, 1)
self.lock.acquire.assert_called_once_with(dependency3, self.transaction, 1)
self.lock.reset_mock()
dependency1.extend.assert_not_called()
self.transaction.finish()
self.assertEqual(self.lock.release.call_count, 2)
args, kwargs = self.lock.release.call_args_list[-1]
self.assertEqual(len(args[0].delegates), 1)
self.assertEqual(args[0].delegates[0].id, 1)
self.assertIs(args[1], self.transaction)
self.assertIsNone(args[2])
args, kwargs = self.lock.release.call_args_list[-2]
self.assertEqual(len(args[0].delegates), 1)
self.assertEqual(args[0].delegates[0].id, 3)
self.assertIs(args[1], self.transaction)
self.assertEqual(args[2], 1)
def test_bool(self):
self.assertTrue(self.transaction)
class SavePointTestCase(AbstractTransactionTestCase):
def _make_transaction(self, lock, parent, current_time_accessor):
return transaction.SavePoint(lock, parent)
def test_parent(self):
self.assertIs(self.transaction.parent(), self.parent)
def test_get_start_time(self):
self.transaction.get_start_time()
self.parent.get_start_time.assert_called_once_with()
def test_get_end_time(self):
self.transaction.get_end_time()
self.parent.get_end_time.assert_called_once_with()
def test_add_dependency(self):
self.transaction.add_dependency(self.dependency, 1)
self.lock.acquire.assert_called_once_with(self.dependency, self.transaction, 1)
self.parent.add_dependency.assert_called_once_with(self.dependency, 1)
def test_bool(self):
self.assertTrue(self.transaction)
class DummyTransactionTestCase(AbstractTransactionTestCase):
def _make_transaction(self, lock, parent, current_time_accessor):
class DummyTransaction(transaction.DummyTransaction):
_current_time = current_time_accessor
return DummyTransaction(lock)
def test_parent(self):
self.assertIsNone(self.transaction.parent())
def test_get_start_time(self):
self.current_time.reset_mock()
self.assertAlmostEqual(self.transaction.get_start_time(), self.current_time.return_value)
initial_return_value = self.current_time.return_value
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_start_time(), self.current_time.return_value)
self.assertEqual(self.current_time.call_count, 2)
def test_get_end_time(self):
self.current_time.reset_mock()
self.current_time.return_value += 1
self.assertAlmostEqual(self.transaction.get_end_time(), self.current_time.return_value)
self.current_time.return_value += 1
time.sleep(1)
self.assertAlmostEqual(self.transaction.get_end_time(), self.current_time.return_value)
self.assertEqual(self.current_time.call_count, 2)
def test_bool(self):
self.assertFalse(self.transaction)
class TransactionManagerTestCase(unittest.TestCase):
def setUp(self):
self.transaction = mock.Mock(spec=interfaces.ITransaction)
self.lock = mock.Mock(spec=interfaces.IDependency)
self.transaction_manager = transaction.TransactionManager(self.lock)
def test_current_none(self):
current_transaction = self.transaction_manager.current()
self.assertIsInstance(current_transaction, transaction.DummyTransaction)
def test_current_set_get(self):
self.transaction_manager.current(self.transaction)
self.assertIs(self.transaction_manager.current(), self.transaction)
def test_begin(self):
initial_transaction = self.transaction_manager.begin()
self.assertIsInstance(initial_transaction, transaction.Transaction)
save_point = self.transaction_manager.begin()
self.assertIsInstance(save_point, transaction.SavePoint)
self.assertIs(save_point.parent(), initial_transaction)
nested_save_point = self.transaction_manager.begin()
self.assertIsInstance(nested_save_point, transaction.SavePoint)
self.assertIs(nested_save_point.parent(), save_point)
def test_finish_delegate_transaction(self):
self.transaction_manager.current(self.transaction)
self.transaction_manager.finish()
self.transaction.finish.assert_called_once_with()
def test_finish_transaction(self):
self.transaction_manager.begin()
self.transaction_manager.finish()
self.assertIsInstance(self.transaction_manager.current(), transaction.DummyTransaction)
def test_finish_savepoint(self):
initial_transaction = self.transaction_manager.begin()
self.transaction_manager.begin()
self.transaction_manager.finish()
self.assertIs(self.transaction_manager.current(), initial_transaction)
def test_flush(self):
self.transaction_manager.begin()
self.transaction_manager.begin()
self.transaction_manager.begin()
self.transaction_manager.flush()
self.assertIsInstance(self.transaction_manager.current(), transaction.DummyTransaction)
| true | true |
f72c31f2bcdc0ad3367f05a6e93c9a41b1a34424 | 1,886 | py | Python | src/oci/data_labeling_service_dataplane/models/text_dataset_format_details.py | ezequielramos/oci-python-sdk | cc4235cf217beaf9feed75760e9ce82610222762 | [
"Apache-2.0",
"BSD-3-Clause"
] | 249 | 2017-09-11T22:06:05.000Z | 2022-03-04T17:09:29.000Z | src/oci/data_labeling_service_dataplane/models/text_dataset_format_details.py | ezequielramos/oci-python-sdk | cc4235cf217beaf9feed75760e9ce82610222762 | [
"Apache-2.0",
"BSD-3-Clause"
] | 228 | 2017-09-11T23:07:26.000Z | 2022-03-23T10:58:50.000Z | src/oci/data_labeling_service_dataplane/models/text_dataset_format_details.py | ezequielramos/oci-python-sdk | cc4235cf217beaf9feed75760e9ce82610222762 | [
"Apache-2.0",
"BSD-3-Clause"
] | 224 | 2017-09-27T07:32:43.000Z | 2022-03-25T16:55:42.000Z | # coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from .dataset_format_details import DatasetFormatDetails
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class TextDatasetFormatDetails(DatasetFormatDetails):
"""
Indicates the dataset is comprised of txt files.
"""
def __init__(self, **kwargs):
"""
Initializes a new TextDatasetFormatDetails object with values from keyword arguments. The default value of the :py:attr:`~oci.data_labeling_service_dataplane.models.TextDatasetFormatDetails.format_type` attribute
of this class is ``TEXT`` and it should not be changed.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param format_type:
The value to assign to the format_type property of this TextDatasetFormatDetails.
Allowed values for this property are: "DOCUMENT", "IMAGE", "TEXT"
:type format_type: str
"""
self.swagger_types = {
'format_type': 'str'
}
self.attribute_map = {
'format_type': 'formatType'
}
self._format_type = None
self._format_type = 'TEXT'
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| 37.72 | 245 | 0.697243 |
from .dataset_format_details import DatasetFormatDetails
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class TextDatasetFormatDetails(DatasetFormatDetails):
def __init__(self, **kwargs):
self.swagger_types = {
'format_type': 'str'
}
self.attribute_map = {
'format_type': 'formatType'
}
self._format_type = None
self._format_type = 'TEXT'
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
f72c32112bb05acf4043ba5c15ccde4c05c4d6f3 | 24,352 | py | Python | compiler/characterizer/model_check.py | ycyang0508/OpenRAM | 54c6043cb81c51f5f4a2f77e91145545ce0ed6d6 | [
"BSD-3-Clause"
] | 1 | 2022-02-17T22:12:46.000Z | 2022-02-17T22:12:46.000Z | compiler/characterizer/model_check.py | ycyang0508/OpenRAM | 54c6043cb81c51f5f4a2f77e91145545ce0ed6d6 | [
"BSD-3-Clause"
] | null | null | null | compiler/characterizer/model_check.py | ycyang0508/OpenRAM | 54c6043cb81c51f5f4a2f77e91145545ce0ed6d6 | [
"BSD-3-Clause"
] | null | null | null | # See LICENSE for licensing information.
#
# Copyright (c) 2016-2021 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
import sys,re,shutil
import debug
import tech
import math
from .stimuli import *
from .trim_spice import *
from .charutils import *
import utils
from globals import OPTS
from .delay import delay
from .measurements import *
class model_check(delay):
"""Functions to test for the worst case delay in a target SRAM
The current worst case determines a feasible period for the SRAM then tests
several bits and record the delay and differences between the bits.
"""
def __init__(self, sram, spfile, corner, custom_delaychain=False):
super().__init__(sram, spfile, corner)
self.period = tech.spice["feasible_period"]
self.create_data_names()
self.custom_delaychain=custom_delaychain
def create_data_names(self):
self.wl_meas_name, self.wl_model_name = "wl_measures", "wl_model"
self.sae_meas_name, self.sae_model_name = "sae_measures", "sae_model"
self.wl_slew_name, self.sae_slew_name = "wl_slews", "sae_slews"
self.bl_meas_name, self.bl_slew_name = "bl_measures", "bl_slews"
self.power_name = "total_power"
def create_measurement_names(self, port):
"""Create measurement names. The names themselves currently define the type of measurement"""
#Create delay measurement names
wl_en_driver_delay_names = ["delay_wl_en_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_en_driver_stages())]
wl_driver_delay_names = ["delay_wl_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_driver_stages())]
sen_driver_delay_names = ["delay_sen_dvr_{}".format(stage) for stage in range(1,self.get_num_sen_driver_stages())]
if self.custom_delaychain:
dc_delay_names = ['delay_dc_out_final']
else:
dc_delay_names = ["delay_delay_chain_stage_{}".format(stage) for stage in range(1,self.get_num_delay_stages()+1)]
self.wl_delay_meas_names = wl_en_driver_delay_names+["delay_wl_en", "delay_wl_bar"]+wl_driver_delay_names+["delay_wl"]
if port not in self.sram.readonly_ports:
self.rbl_delay_meas_names = ["delay_gated_clk_nand", "delay_delay_chain_in"]+dc_delay_names
else:
self.rbl_delay_meas_names = ["delay_gated_clk_nand"]+dc_delay_names
self.sae_delay_meas_names = ["delay_pre_sen"]+sen_driver_delay_names+["delay_sen"]
# if self.custom_delaychain:
# self.delay_chain_indices = (len(self.rbl_delay_meas_names), len(self.rbl_delay_meas_names)+1)
# else:
self.delay_chain_indices = (len(self.rbl_delay_meas_names)-len(dc_delay_names), len(self.rbl_delay_meas_names))
#Create slew measurement names
wl_en_driver_slew_names = ["slew_wl_en_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_en_driver_stages())]
wl_driver_slew_names = ["slew_wl_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_driver_stages())]
sen_driver_slew_names = ["slew_sen_dvr_{}".format(stage) for stage in range(1,self.get_num_sen_driver_stages())]
if self.custom_delaychain:
dc_slew_names = ['slew_dc_out_final']
else:
dc_slew_names = ["slew_delay_chain_stage_{}".format(stage) for stage in range(1,self.get_num_delay_stages()+1)]
self.wl_slew_meas_names = ["slew_wl_gated_clk_bar"]+wl_en_driver_slew_names+["slew_wl_en", "slew_wl_bar"]+wl_driver_slew_names+["slew_wl"]
if port not in self.sram.readonly_ports:
self.rbl_slew_meas_names = ["slew_rbl_gated_clk_bar","slew_gated_clk_nand", "slew_delay_chain_in"]+dc_slew_names
else:
self.rbl_slew_meas_names = ["slew_rbl_gated_clk_bar"]+dc_slew_names
self.sae_slew_meas_names = ["slew_replica_bl0", "slew_pre_sen"]+sen_driver_slew_names+["slew_sen"]
self.bitline_meas_names = ["delay_wl_to_bl", "delay_bl_to_dout"]
self.power_meas_names = ['read0_power']
def create_signal_names(self, port):
"""Creates list of the signal names used in the spice file along the wl and sen paths.
Names are re-harded coded here; i.e. the names are hardcoded in most of OpenRAM and are
replicated here.
"""
delay.create_signal_names(self)
#Signal names are all hardcoded, need to update to make it work for probe address and different configurations.
wl_en_driver_signals = ["Xsram.Xcontrol{}.Xbuf_wl_en.Zb{}_int".format('{}', stage) for stage in range(1,self.get_num_wl_en_driver_stages())]
wl_driver_signals = ["Xsram.Xbank0.Xwordline_driver{}.Xwl_driver_inv{}.Zb{}_int".format('{}', self.wordline_row, stage) for stage in range(1,self.get_num_wl_driver_stages())]
sen_driver_signals = ["Xsram.Xcontrol{}.Xbuf_s_en.Zb{}_int".format('{}',stage) for stage in range(1,self.get_num_sen_driver_stages())]
if self.custom_delaychain:
delay_chain_signal_names = []
else:
delay_chain_signal_names = ["Xsram.Xcontrol{}.Xreplica_bitline.Xdelay_chain.dout_{}".format('{}', stage) for stage in range(1,self.get_num_delay_stages())]
if len(self.sram.all_ports) > 1:
port_format = '{}'
else:
port_format = ''
self.wl_signal_names = ["Xsram.Xcontrol{}.gated_clk_bar".format('{}')]+\
wl_en_driver_signals+\
["Xsram.wl_en{}".format('{}'), "Xsram.Xbank0.Xwordline_driver{}.wl_bar_{}".format('{}',self.wordline_row)]+\
wl_driver_signals+\
["Xsram.Xbank0.wl{}_{}".format(port_format, self.wordline_row)]
pre_delay_chain_names = ["Xsram.Xcontrol{}.gated_clk_bar".format('{}')]
if port not in self.sram.readonly_ports:
pre_delay_chain_names+= ["Xsram.Xcontrol{}.Xand2_rbl_in.zb_int".format('{}'), "Xsram.Xcontrol{}.rbl_in".format('{}')]
self.rbl_en_signal_names = pre_delay_chain_names+\
delay_chain_signal_names+\
["Xsram.Xcontrol{}.Xreplica_bitline.delayed_en".format('{}')]
self.sae_signal_names = ["Xsram.Xcontrol{}.Xreplica_bitline.bl0_0".format('{}'), "Xsram.Xcontrol{}.pre_s_en".format('{}')]+\
sen_driver_signals+\
["Xsram.s_en{}".format('{}')]
dout_name = "{0}{1}_{2}".format(self.dout_name,"{}",self.probe_data) #Empty values are the port and probe data bit
self.bl_signal_names = ["Xsram.Xbank0.wl{}_{}".format(port_format, self.wordline_row),\
"Xsram.Xbank0.bl{}_{}".format(port_format, self.bitline_column),\
dout_name]
def create_measurement_objects(self):
"""Create the measurements used for read and write ports"""
self.create_wordline_meas_objs()
self.create_sae_meas_objs()
self.create_bl_meas_objs()
self.create_power_meas_objs()
self.all_measures = self.wl_meas_objs+self.sae_meas_objs+self.bl_meas_objs+self.power_meas_objs
def create_power_meas_objs(self):
"""Create power measurement object. Only one."""
self.power_meas_objs = []
self.power_meas_objs.append(power_measure(self.power_meas_names[0], "FALL", measure_scale=1e3))
def create_wordline_meas_objs(self):
"""Create the measurements to measure the wordline path from the gated_clk_bar signal"""
self.wl_meas_objs = []
trig_dir = "RISE"
targ_dir = "FALL"
for i in range(1, len(self.wl_signal_names)):
self.wl_meas_objs.append(delay_measure(self.wl_delay_meas_names[i-1],
self.wl_signal_names[i-1],
self.wl_signal_names[i],
trig_dir,
targ_dir,
measure_scale=1e9))
self.wl_meas_objs.append(slew_measure(self.wl_slew_meas_names[i-1],
self.wl_signal_names[i-1],
trig_dir,
measure_scale=1e9))
temp_dir = trig_dir
trig_dir = targ_dir
targ_dir = temp_dir
self.wl_meas_objs.append(slew_measure(self.wl_slew_meas_names[-1], self.wl_signal_names[-1], trig_dir, measure_scale=1e9))
def create_bl_meas_objs(self):
"""Create the measurements to measure the bitline to dout, static stages"""
#Bitline has slightly different measurements, objects appends hardcoded.
self.bl_meas_objs = []
trig_dir, targ_dir = "RISE", "FALL" #Only check read 0
self.bl_meas_objs.append(delay_measure(self.bitline_meas_names[0],
self.bl_signal_names[0],
self.bl_signal_names[-1],
trig_dir,
targ_dir,
measure_scale=1e9))
def create_sae_meas_objs(self):
"""Create the measurements to measure the sense amp enable path from the gated_clk_bar signal. The RBL splits this path into two."""
self.sae_meas_objs = []
trig_dir = "RISE"
targ_dir = "FALL"
#Add measurements from gated_clk_bar to RBL
for i in range(1, len(self.rbl_en_signal_names)):
self.sae_meas_objs.append(delay_measure(self.rbl_delay_meas_names[i-1],
self.rbl_en_signal_names[i-1],
self.rbl_en_signal_names[i],
trig_dir,
targ_dir,
measure_scale=1e9))
self.sae_meas_objs.append(slew_measure(self.rbl_slew_meas_names[i-1],
self.rbl_en_signal_names[i-1],
trig_dir,
measure_scale=1e9))
temp_dir = trig_dir
trig_dir = targ_dir
targ_dir = temp_dir
if self.custom_delaychain: #Hack for custom delay chains
self.sae_meas_objs[-2] = delay_measure(self.rbl_delay_meas_names[-1],
self.rbl_en_signal_names[-2],
self.rbl_en_signal_names[-1],
"RISE",
"RISE",
measure_scale=1e9)
self.sae_meas_objs.append(slew_measure(self.rbl_slew_meas_names[-1],
self.rbl_en_signal_names[-1],
trig_dir,
measure_scale=1e9))
#Add measurements from rbl_out to sae. Trigger directions do not invert from previous stage due to RBL.
trig_dir = "FALL"
targ_dir = "RISE"
for i in range(1, len(self.sae_signal_names)):
self.sae_meas_objs.append(delay_measure(self.sae_delay_meas_names[i-1],
self.sae_signal_names[i-1],
self.sae_signal_names[i],
trig_dir,
targ_dir,
measure_scale=1e9))
self.sae_meas_objs.append(slew_measure(self.sae_slew_meas_names[i-1],
self.sae_signal_names[i-1],
trig_dir,
measure_scale=1e9))
temp_dir = trig_dir
trig_dir = targ_dir
targ_dir = temp_dir
self.sae_meas_objs.append(slew_measure(self.sae_slew_meas_names[-1],
self.sae_signal_names[-1],
trig_dir,
measure_scale=1e9))
def write_delay_measures(self):
"""
Write the measure statements to quantify the delay and power results for all targeted ports.
"""
self.sf.write("\n* Measure statements for delay and power\n")
# Output some comments to aid where cycles start and what is happening
for comment in self.cycle_comments:
self.sf.write("* {}\n".format(comment))
for read_port in self.targ_read_ports:
self.write_measures_read_port(read_port)
def get_delay_measure_variants(self, port, measure_obj):
"""Get the measurement values that can either vary from simulation to simulation (vdd, address)
or port to port (time delays)"""
#Return value is intended to match the delay measure format: trig_td, targ_td, vdd, port
#Assuming only read 0 for now
debug.info(3,"Power measurement={}".format(measure_obj))
if (type(measure_obj) is delay_measure or type(measure_obj) is slew_measure):
meas_cycle_delay = self.cycle_times[self.measure_cycles[port]["read0"]] + self.period/2
return (meas_cycle_delay, meas_cycle_delay, self.vdd_voltage, port)
elif type(measure_obj) is power_measure:
return self.get_power_measure_variants(port, measure_obj, "read")
else:
debug.error("Measurement not recognized by the model checker.",1)
def get_power_measure_variants(self, port, power_obj, operation):
"""Get the measurement values that can either vary port to port (time delays)"""
#Return value is intended to match the power measure format: t_initial, t_final, port
t_initial = self.cycle_times[self.measure_cycles[port]["read0"]]
t_final = self.cycle_times[self.measure_cycles[port]["read0"]+1]
return (t_initial, t_final, port)
def write_measures_read_port(self, port):
"""
Write the measure statements for all nodes along the wordline path.
"""
# add measure statements for delays/slews
for measure in self.all_measures:
measure_variant_inp_tuple = self.get_delay_measure_variants(port, measure)
measure.write_measure(self.stim, measure_variant_inp_tuple)
def get_measurement_values(self, meas_objs, port):
"""Gets the delays and slews from a specified port from the spice output file and returns them as lists."""
delay_meas_list = []
slew_meas_list = []
power_meas_list=[]
for measure in meas_objs:
measure_value = measure.retrieve_measure(port=port)
if type(measure_value) != float:
debug.error("Failed to Measure Value:\n\t\t{}={}".format(measure.name, measure_value),1)
if type(measure) is delay_measure:
delay_meas_list.append(measure_value)
elif type(measure)is slew_measure:
slew_meas_list.append(measure_value)
elif type(measure)is power_measure:
power_meas_list.append(measure_value)
else:
debug.error("Measurement object not recognized.",1)
return delay_meas_list, slew_meas_list,power_meas_list
def run_delay_simulation(self):
"""
This tries to simulate a period and checks if the result works. If
so, it returns True and the delays, slews, and powers. It
works on the trimmed netlist by default, so powers do not
include leakage of all cells.
"""
#Sanity Check
debug.check(self.period > 0, "Target simulation period non-positive")
wl_delay_result = [[] for i in self.all_ports]
wl_slew_result = [[] for i in self.all_ports]
sae_delay_result = [[] for i in self.all_ports]
sae_slew_result = [[] for i in self.all_ports]
bl_delay_result = [[] for i in self.all_ports]
bl_slew_result = [[] for i in self.all_ports]
power_result = [[] for i in self.all_ports]
# Checking from not data_value to data_value
self.write_delay_stimulus()
self.stim.run_sim() #running sim prodoces spice output file.
#Retrieve the results from the output file
for port in self.targ_read_ports:
#Parse and check the voltage measurements
wl_delay_result[port], wl_slew_result[port],_ = self.get_measurement_values(self.wl_meas_objs, port)
sae_delay_result[port], sae_slew_result[port],_ = self.get_measurement_values(self.sae_meas_objs, port)
bl_delay_result[port], bl_slew_result[port],_ = self.get_measurement_values(self.bl_meas_objs, port)
_,__,power_result[port] = self.get_measurement_values(self.power_meas_objs, port)
return (True,wl_delay_result, sae_delay_result, wl_slew_result, sae_slew_result, bl_delay_result, bl_slew_result, power_result)
def get_model_delays(self, port):
"""Get model delays based on port. Currently assumes single RW port."""
return self.sram.control_logic_rw.get_wl_sen_delays()
def get_num_delay_stages(self):
"""Gets the number of stages in the delay chain from the control logic"""
return len(self.sram.control_logic_rw.replica_bitline.delay_fanout_list)
def get_num_delay_fanout_list(self):
"""Gets the number of stages in the delay chain from the control logic"""
return self.sram.control_logic_rw.replica_bitline.delay_fanout_list
def get_num_delay_stage_fanout(self):
"""Gets fanout in each stage in the delay chain. Assumes each stage is the same"""
return self.sram.control_logic_rw.replica_bitline.delay_fanout_list[0]
def get_num_wl_en_driver_stages(self):
"""Gets the number of stages in the wl_en driver from the control logic"""
return self.sram.control_logic_rw.wl_en_driver.num_stages
def get_num_sen_driver_stages(self):
"""Gets the number of stages in the sen driver from the control logic"""
return self.sram.control_logic_rw.s_en_driver.num_stages
def get_num_wl_driver_stages(self):
"""Gets the number of stages in the wordline driver from the control logic"""
return self.sram.bank.wordline_driver.inv.num_stages
def scale_delays(self, delay_list):
"""Takes in a list of measured delays and convert it to simple units to easily compare to model values."""
converted_values = []
#Calculate average
total = 0
for meas_value in delay_list:
total+=meas_value
average = total/len(delay_list)
#Convert values
for meas_value in delay_list:
converted_values.append(meas_value/average)
return converted_values
def min_max_normalization(self, value_list):
"""Re-scales input values on a range from 0-1 where min(list)=0, max(list)=1"""
scaled_values = []
min_max_diff = max(value_list) - min(value_list)
average = sum(value_list)/len(value_list)
for value in value_list:
scaled_values.append((value-average)/(min_max_diff))
return scaled_values
def calculate_error_l2_norm(self, list_a, list_b):
"""Calculates error between two lists using the l2 norm"""
error_list = []
for val_a, val_b in zip(list_a, list_b):
error_list.append((val_a-val_b)**2)
return error_list
def compare_measured_and_model(self, measured_vals, model_vals):
"""First scales both inputs into similar ranges and then compares the error between both."""
scaled_meas = self.min_max_normalization(measured_vals)
debug.info(1, "Scaled measurements:\n{}".format(scaled_meas))
scaled_model = self.min_max_normalization(model_vals)
debug.info(1, "Scaled model:\n{}".format(scaled_model))
errors = self.calculate_error_l2_norm(scaled_meas, scaled_model)
debug.info(1, "Errors:\n{}\n".format(errors))
def analyze(self, probe_address, probe_data, slews, loads, port):
"""Measures entire delay path along the wordline and sense amp enable and compare it to the model delays."""
self.load=max(loads)
self.slew=max(slews)
self.set_probe(probe_address, probe_data)
self.create_signal_names(port)
self.create_measurement_names(port)
self.create_measurement_objects()
data_dict = {}
read_port = self.read_ports[0] #only test the first read port
read_port = port
self.targ_read_ports = [read_port]
self.targ_write_ports = [self.write_ports[0]]
debug.info(1,"Model test: corner {}".format(self.corner))
(success, wl_delays, sae_delays, wl_slews, sae_slews, bl_delays, bl_slews, powers)=self.run_delay_simulation()
debug.check(success, "Model measurements Failed: period={}".format(self.period))
debug.info(1,"Measured Wordline delays (ns):\n\t {}".format(wl_delays[read_port]))
debug.info(1,"Measured Wordline slews:\n\t {}".format(wl_slews[read_port]))
debug.info(1,"Measured SAE delays (ns):\n\t {}".format(sae_delays[read_port]))
debug.info(1,"Measured SAE slews:\n\t {}".format(sae_slews[read_port]))
debug.info(1,"Measured Bitline delays (ns):\n\t {}".format(bl_delays[read_port]))
data_dict[self.wl_meas_name] = wl_delays[read_port]
data_dict[self.sae_meas_name] = sae_delays[read_port]
data_dict[self.wl_slew_name] = wl_slews[read_port]
data_dict[self.sae_slew_name] = sae_slews[read_port]
data_dict[self.bl_meas_name] = bl_delays[read_port]
data_dict[self.power_name] = powers[read_port]
if OPTS.auto_delay_chain_sizing: #Model is not used in this case
wl_model_delays, sae_model_delays = self.get_model_delays(read_port)
debug.info(1,"Wordline model delays:\n\t {}".format(wl_model_delays))
debug.info(1,"SAE model delays:\n\t {}".format(sae_model_delays))
data_dict[self.wl_model_name] = wl_model_delays
data_dict[self.sae_model_name] = sae_model_delays
#Some evaluations of the model and measured values
# debug.info(1, "Comparing wordline measurements and model.")
# self.compare_measured_and_model(wl_delays[read_port], wl_model_delays)
# debug.info(1, "Comparing SAE measurements and model")
# self.compare_measured_and_model(sae_delays[read_port], sae_model_delays)
return data_dict
def get_all_signal_names(self):
"""Returns all signals names as a dict indexed by hardcoded names. Useful for writing the head of the CSV."""
name_dict = {}
#Signal names are more descriptive than the measurement names, first value trimmed to match size of measurements names.
name_dict[self.wl_meas_name] = self.wl_signal_names[1:]
name_dict[self.sae_meas_name] = self.rbl_en_signal_names[1:]+self.sae_signal_names[1:]
name_dict[self.wl_slew_name] = self.wl_slew_meas_names
name_dict[self.sae_slew_name] = self.rbl_slew_meas_names+self.sae_slew_meas_names
name_dict[self.bl_meas_name] = self.bitline_meas_names[0:1]
name_dict[self.power_name] = self.power_meas_names
#name_dict[self.wl_slew_name] = self.wl_slew_meas_names
if OPTS.auto_delay_chain_sizing:
name_dict[self.wl_model_name] = name_dict["wl_measures"] #model uses same names as measured.
name_dict[self.sae_model_name] = name_dict["sae_measures"]
return name_dict
| 54.115556 | 182 | 0.627217 |
import sys,re,shutil
import debug
import tech
import math
from .stimuli import *
from .trim_spice import *
from .charutils import *
import utils
from globals import OPTS
from .delay import delay
from .measurements import *
class model_check(delay):
def __init__(self, sram, spfile, corner, custom_delaychain=False):
super().__init__(sram, spfile, corner)
self.period = tech.spice["feasible_period"]
self.create_data_names()
self.custom_delaychain=custom_delaychain
def create_data_names(self):
self.wl_meas_name, self.wl_model_name = "wl_measures", "wl_model"
self.sae_meas_name, self.sae_model_name = "sae_measures", "sae_model"
self.wl_slew_name, self.sae_slew_name = "wl_slews", "sae_slews"
self.bl_meas_name, self.bl_slew_name = "bl_measures", "bl_slews"
self.power_name = "total_power"
def create_measurement_names(self, port):
wl_en_driver_delay_names = ["delay_wl_en_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_en_driver_stages())]
wl_driver_delay_names = ["delay_wl_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_driver_stages())]
sen_driver_delay_names = ["delay_sen_dvr_{}".format(stage) for stage in range(1,self.get_num_sen_driver_stages())]
if self.custom_delaychain:
dc_delay_names = ['delay_dc_out_final']
else:
dc_delay_names = ["delay_delay_chain_stage_{}".format(stage) for stage in range(1,self.get_num_delay_stages()+1)]
self.wl_delay_meas_names = wl_en_driver_delay_names+["delay_wl_en", "delay_wl_bar"]+wl_driver_delay_names+["delay_wl"]
if port not in self.sram.readonly_ports:
self.rbl_delay_meas_names = ["delay_gated_clk_nand", "delay_delay_chain_in"]+dc_delay_names
else:
self.rbl_delay_meas_names = ["delay_gated_clk_nand"]+dc_delay_names
self.sae_delay_meas_names = ["delay_pre_sen"]+sen_driver_delay_names+["delay_sen"]
self.delay_chain_indices = (len(self.rbl_delay_meas_names)-len(dc_delay_names), len(self.rbl_delay_meas_names))
wl_en_driver_slew_names = ["slew_wl_en_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_en_driver_stages())]
wl_driver_slew_names = ["slew_wl_dvr_{}".format(stage) for stage in range(1,self.get_num_wl_driver_stages())]
sen_driver_slew_names = ["slew_sen_dvr_{}".format(stage) for stage in range(1,self.get_num_sen_driver_stages())]
if self.custom_delaychain:
dc_slew_names = ['slew_dc_out_final']
else:
dc_slew_names = ["slew_delay_chain_stage_{}".format(stage) for stage in range(1,self.get_num_delay_stages()+1)]
self.wl_slew_meas_names = ["slew_wl_gated_clk_bar"]+wl_en_driver_slew_names+["slew_wl_en", "slew_wl_bar"]+wl_driver_slew_names+["slew_wl"]
if port not in self.sram.readonly_ports:
self.rbl_slew_meas_names = ["slew_rbl_gated_clk_bar","slew_gated_clk_nand", "slew_delay_chain_in"]+dc_slew_names
else:
self.rbl_slew_meas_names = ["slew_rbl_gated_clk_bar"]+dc_slew_names
self.sae_slew_meas_names = ["slew_replica_bl0", "slew_pre_sen"]+sen_driver_slew_names+["slew_sen"]
self.bitline_meas_names = ["delay_wl_to_bl", "delay_bl_to_dout"]
self.power_meas_names = ['read0_power']
def create_signal_names(self, port):
delay.create_signal_names(self)
wl_en_driver_signals = ["Xsram.Xcontrol{}.Xbuf_wl_en.Zb{}_int".format('{}', stage) for stage in range(1,self.get_num_wl_en_driver_stages())]
wl_driver_signals = ["Xsram.Xbank0.Xwordline_driver{}.Xwl_driver_inv{}.Zb{}_int".format('{}', self.wordline_row, stage) for stage in range(1,self.get_num_wl_driver_stages())]
sen_driver_signals = ["Xsram.Xcontrol{}.Xbuf_s_en.Zb{}_int".format('{}',stage) for stage in range(1,self.get_num_sen_driver_stages())]
if self.custom_delaychain:
delay_chain_signal_names = []
else:
delay_chain_signal_names = ["Xsram.Xcontrol{}.Xreplica_bitline.Xdelay_chain.dout_{}".format('{}', stage) for stage in range(1,self.get_num_delay_stages())]
if len(self.sram.all_ports) > 1:
port_format = '{}'
else:
port_format = ''
self.wl_signal_names = ["Xsram.Xcontrol{}.gated_clk_bar".format('{}')]+\
wl_en_driver_signals+\
["Xsram.wl_en{}".format('{}'), "Xsram.Xbank0.Xwordline_driver{}.wl_bar_{}".format('{}',self.wordline_row)]+\
wl_driver_signals+\
["Xsram.Xbank0.wl{}_{}".format(port_format, self.wordline_row)]
pre_delay_chain_names = ["Xsram.Xcontrol{}.gated_clk_bar".format('{}')]
if port not in self.sram.readonly_ports:
pre_delay_chain_names+= ["Xsram.Xcontrol{}.Xand2_rbl_in.zb_int".format('{}'), "Xsram.Xcontrol{}.rbl_in".format('{}')]
self.rbl_en_signal_names = pre_delay_chain_names+\
delay_chain_signal_names+\
["Xsram.Xcontrol{}.Xreplica_bitline.delayed_en".format('{}')]
self.sae_signal_names = ["Xsram.Xcontrol{}.Xreplica_bitline.bl0_0".format('{}'), "Xsram.Xcontrol{}.pre_s_en".format('{}')]+\
sen_driver_signals+\
["Xsram.s_en{}".format('{}')]
dout_name = "{0}{1}_{2}".format(self.dout_name,"{}",self.probe_data)
self.bl_signal_names = ["Xsram.Xbank0.wl{}_{}".format(port_format, self.wordline_row),\
"Xsram.Xbank0.bl{}_{}".format(port_format, self.bitline_column),\
dout_name]
def create_measurement_objects(self):
self.create_wordline_meas_objs()
self.create_sae_meas_objs()
self.create_bl_meas_objs()
self.create_power_meas_objs()
self.all_measures = self.wl_meas_objs+self.sae_meas_objs+self.bl_meas_objs+self.power_meas_objs
def create_power_meas_objs(self):
self.power_meas_objs = []
self.power_meas_objs.append(power_measure(self.power_meas_names[0], "FALL", measure_scale=1e3))
def create_wordline_meas_objs(self):
self.wl_meas_objs = []
trig_dir = "RISE"
targ_dir = "FALL"
for i in range(1, len(self.wl_signal_names)):
self.wl_meas_objs.append(delay_measure(self.wl_delay_meas_names[i-1],
self.wl_signal_names[i-1],
self.wl_signal_names[i],
trig_dir,
targ_dir,
measure_scale=1e9))
self.wl_meas_objs.append(slew_measure(self.wl_slew_meas_names[i-1],
self.wl_signal_names[i-1],
trig_dir,
measure_scale=1e9))
temp_dir = trig_dir
trig_dir = targ_dir
targ_dir = temp_dir
self.wl_meas_objs.append(slew_measure(self.wl_slew_meas_names[-1], self.wl_signal_names[-1], trig_dir, measure_scale=1e9))
def create_bl_meas_objs(self):
self.bl_meas_objs = []
trig_dir, targ_dir = "RISE", "FALL"
self.bl_meas_objs.append(delay_measure(self.bitline_meas_names[0],
self.bl_signal_names[0],
self.bl_signal_names[-1],
trig_dir,
targ_dir,
measure_scale=1e9))
def create_sae_meas_objs(self):
self.sae_meas_objs = []
trig_dir = "RISE"
targ_dir = "FALL"
for i in range(1, len(self.rbl_en_signal_names)):
self.sae_meas_objs.append(delay_measure(self.rbl_delay_meas_names[i-1],
self.rbl_en_signal_names[i-1],
self.rbl_en_signal_names[i],
trig_dir,
targ_dir,
measure_scale=1e9))
self.sae_meas_objs.append(slew_measure(self.rbl_slew_meas_names[i-1],
self.rbl_en_signal_names[i-1],
trig_dir,
measure_scale=1e9))
temp_dir = trig_dir
trig_dir = targ_dir
targ_dir = temp_dir
if self.custom_delaychain:
self.sae_meas_objs[-2] = delay_measure(self.rbl_delay_meas_names[-1],
self.rbl_en_signal_names[-2],
self.rbl_en_signal_names[-1],
"RISE",
"RISE",
measure_scale=1e9)
self.sae_meas_objs.append(slew_measure(self.rbl_slew_meas_names[-1],
self.rbl_en_signal_names[-1],
trig_dir,
measure_scale=1e9))
trig_dir = "FALL"
targ_dir = "RISE"
for i in range(1, len(self.sae_signal_names)):
self.sae_meas_objs.append(delay_measure(self.sae_delay_meas_names[i-1],
self.sae_signal_names[i-1],
self.sae_signal_names[i],
trig_dir,
targ_dir,
measure_scale=1e9))
self.sae_meas_objs.append(slew_measure(self.sae_slew_meas_names[i-1],
self.sae_signal_names[i-1],
trig_dir,
measure_scale=1e9))
temp_dir = trig_dir
trig_dir = targ_dir
targ_dir = temp_dir
self.sae_meas_objs.append(slew_measure(self.sae_slew_meas_names[-1],
self.sae_signal_names[-1],
trig_dir,
measure_scale=1e9))
def write_delay_measures(self):
self.sf.write("\n* Measure statements for delay and power\n")
for comment in self.cycle_comments:
self.sf.write("* {}\n".format(comment))
for read_port in self.targ_read_ports:
self.write_measures_read_port(read_port)
def get_delay_measure_variants(self, port, measure_obj):
debug.info(3,"Power measurement={}".format(measure_obj))
if (type(measure_obj) is delay_measure or type(measure_obj) is slew_measure):
meas_cycle_delay = self.cycle_times[self.measure_cycles[port]["read0"]] + self.period/2
return (meas_cycle_delay, meas_cycle_delay, self.vdd_voltage, port)
elif type(measure_obj) is power_measure:
return self.get_power_measure_variants(port, measure_obj, "read")
else:
debug.error("Measurement not recognized by the model checker.",1)
def get_power_measure_variants(self, port, power_obj, operation):
t_initial = self.cycle_times[self.measure_cycles[port]["read0"]]
t_final = self.cycle_times[self.measure_cycles[port]["read0"]+1]
return (t_initial, t_final, port)
def write_measures_read_port(self, port):
for measure in self.all_measures:
measure_variant_inp_tuple = self.get_delay_measure_variants(port, measure)
measure.write_measure(self.stim, measure_variant_inp_tuple)
def get_measurement_values(self, meas_objs, port):
delay_meas_list = []
slew_meas_list = []
power_meas_list=[]
for measure in meas_objs:
measure_value = measure.retrieve_measure(port=port)
if type(measure_value) != float:
debug.error("Failed to Measure Value:\n\t\t{}={}".format(measure.name, measure_value),1)
if type(measure) is delay_measure:
delay_meas_list.append(measure_value)
elif type(measure)is slew_measure:
slew_meas_list.append(measure_value)
elif type(measure)is power_measure:
power_meas_list.append(measure_value)
else:
debug.error("Measurement object not recognized.",1)
return delay_meas_list, slew_meas_list,power_meas_list
def run_delay_simulation(self):
debug.check(self.period > 0, "Target simulation period non-positive")
wl_delay_result = [[] for i in self.all_ports]
wl_slew_result = [[] for i in self.all_ports]
sae_delay_result = [[] for i in self.all_ports]
sae_slew_result = [[] for i in self.all_ports]
bl_delay_result = [[] for i in self.all_ports]
bl_slew_result = [[] for i in self.all_ports]
power_result = [[] for i in self.all_ports]
self.write_delay_stimulus()
self.stim.run_sim()
for port in self.targ_read_ports:
wl_delay_result[port], wl_slew_result[port],_ = self.get_measurement_values(self.wl_meas_objs, port)
sae_delay_result[port], sae_slew_result[port],_ = self.get_measurement_values(self.sae_meas_objs, port)
bl_delay_result[port], bl_slew_result[port],_ = self.get_measurement_values(self.bl_meas_objs, port)
_,__,power_result[port] = self.get_measurement_values(self.power_meas_objs, port)
return (True,wl_delay_result, sae_delay_result, wl_slew_result, sae_slew_result, bl_delay_result, bl_slew_result, power_result)
def get_model_delays(self, port):
return self.sram.control_logic_rw.get_wl_sen_delays()
def get_num_delay_stages(self):
return len(self.sram.control_logic_rw.replica_bitline.delay_fanout_list)
def get_num_delay_fanout_list(self):
return self.sram.control_logic_rw.replica_bitline.delay_fanout_list
def get_num_delay_stage_fanout(self):
return self.sram.control_logic_rw.replica_bitline.delay_fanout_list[0]
def get_num_wl_en_driver_stages(self):
return self.sram.control_logic_rw.wl_en_driver.num_stages
def get_num_sen_driver_stages(self):
return self.sram.control_logic_rw.s_en_driver.num_stages
def get_num_wl_driver_stages(self):
return self.sram.bank.wordline_driver.inv.num_stages
def scale_delays(self, delay_list):
converted_values = []
total = 0
for meas_value in delay_list:
total+=meas_value
average = total/len(delay_list)
for meas_value in delay_list:
converted_values.append(meas_value/average)
return converted_values
def min_max_normalization(self, value_list):
scaled_values = []
min_max_diff = max(value_list) - min(value_list)
average = sum(value_list)/len(value_list)
for value in value_list:
scaled_values.append((value-average)/(min_max_diff))
return scaled_values
def calculate_error_l2_norm(self, list_a, list_b):
error_list = []
for val_a, val_b in zip(list_a, list_b):
error_list.append((val_a-val_b)**2)
return error_list
def compare_measured_and_model(self, measured_vals, model_vals):
scaled_meas = self.min_max_normalization(measured_vals)
debug.info(1, "Scaled measurements:\n{}".format(scaled_meas))
scaled_model = self.min_max_normalization(model_vals)
debug.info(1, "Scaled model:\n{}".format(scaled_model))
errors = self.calculate_error_l2_norm(scaled_meas, scaled_model)
debug.info(1, "Errors:\n{}\n".format(errors))
def analyze(self, probe_address, probe_data, slews, loads, port):
self.load=max(loads)
self.slew=max(slews)
self.set_probe(probe_address, probe_data)
self.create_signal_names(port)
self.create_measurement_names(port)
self.create_measurement_objects()
data_dict = {}
read_port = self.read_ports[0]
read_port = port
self.targ_read_ports = [read_port]
self.targ_write_ports = [self.write_ports[0]]
debug.info(1,"Model test: corner {}".format(self.corner))
(success, wl_delays, sae_delays, wl_slews, sae_slews, bl_delays, bl_slews, powers)=self.run_delay_simulation()
debug.check(success, "Model measurements Failed: period={}".format(self.period))
debug.info(1,"Measured Wordline delays (ns):\n\t {}".format(wl_delays[read_port]))
debug.info(1,"Measured Wordline slews:\n\t {}".format(wl_slews[read_port]))
debug.info(1,"Measured SAE delays (ns):\n\t {}".format(sae_delays[read_port]))
debug.info(1,"Measured SAE slews:\n\t {}".format(sae_slews[read_port]))
debug.info(1,"Measured Bitline delays (ns):\n\t {}".format(bl_delays[read_port]))
data_dict[self.wl_meas_name] = wl_delays[read_port]
data_dict[self.sae_meas_name] = sae_delays[read_port]
data_dict[self.wl_slew_name] = wl_slews[read_port]
data_dict[self.sae_slew_name] = sae_slews[read_port]
data_dict[self.bl_meas_name] = bl_delays[read_port]
data_dict[self.power_name] = powers[read_port]
if OPTS.auto_delay_chain_sizing:
wl_model_delays, sae_model_delays = self.get_model_delays(read_port)
debug.info(1,"Wordline model delays:\n\t {}".format(wl_model_delays))
debug.info(1,"SAE model delays:\n\t {}".format(sae_model_delays))
data_dict[self.wl_model_name] = wl_model_delays
data_dict[self.sae_model_name] = sae_model_delays
return data_dict
def get_all_signal_names(self):
name_dict = {}
name_dict[self.wl_meas_name] = self.wl_signal_names[1:]
name_dict[self.sae_meas_name] = self.rbl_en_signal_names[1:]+self.sae_signal_names[1:]
name_dict[self.wl_slew_name] = self.wl_slew_meas_names
name_dict[self.sae_slew_name] = self.rbl_slew_meas_names+self.sae_slew_meas_names
name_dict[self.bl_meas_name] = self.bitline_meas_names[0:1]
name_dict[self.power_name] = self.power_meas_names
if OPTS.auto_delay_chain_sizing:
name_dict[self.wl_model_name] = name_dict["wl_measures"]
name_dict[self.sae_model_name] = name_dict["sae_measures"]
return name_dict
| true | true |
f72c33ad93ae6e46739f72e67c233be7339ce4cc | 1,937 | py | Python | .ignore/old/SDN_MininetUtils.py | souvikdas95/SDN_VideoStreaming | a75a77a1d2a087c96102b2c02f5a67d3a90f1fa2 | [
"Apache-2.0"
] | 4 | 2018-04-26T20:33:15.000Z | 2022-01-20T22:43:08.000Z | .ignore/old/SDN_MininetUtils.py | souvikdas95/SDN_VideoStreaming | a75a77a1d2a087c96102b2c02f5a67d3a90f1fa2 | [
"Apache-2.0"
] | null | null | null | .ignore/old/SDN_MininetUtils.py | souvikdas95/SDN_VideoStreaming | a75a77a1d2a087c96102b2c02f5a67d3a90f1fa2 | [
"Apache-2.0"
] | 3 | 2019-05-02T08:51:20.000Z | 2021-04-02T15:29:52.000Z | #!/usr/bin/python
import mininet.util;
from mininet.util import quietRun, moveIntf;
def _makeIntfPair( intf1, intf2, addr1=None, addr2=None, node1=None, node2=None,
deleteIntfs=True, runCmd=None ):
"""Make a veth pair connnecting new interfaces intf1 and intf2
intf1: name for interface 1
intf2: name for interface 2
addr1: MAC address for interface 1 (optional)
addr2: MAC address for interface 2 (optional)
node1: home node for interface 1 (optional)
node2: home node for interface 2 (optional)
deleteIntfs: delete intfs before creating them
runCmd: function to run shell commands (quietRun)
raises Exception on failure
Changes:
The problem here is that we can not add a link to another
netns within a Docker container since it does not know
the other process (process not found error).
So we have to do it different:
We create the veth pair inside the default netns and move them
into their netns (container) afterwards."""
if deleteIntfs:
# Delete any old interfaces with the same names
quietRun( 'ip link del ' + intf1, shell=True )
quietRun( 'ip link del ' + intf2, shell=True )
# first: create the veth pair in default namespace
if addr1 is None and addr2 is None:
cmdOutput = quietRun( 'ip link add name %s '
'type veth peer name %s ' %
( intf1, intf2 ),
shell=True )
else:
cmdOutput = quietRun( 'ip link add name %s '
'address %s '
'type veth peer name %s '
'address %s ' %
( intf1, addr1, intf2, addr2 ),
shell=True )
if cmdOutput:
raise Exception( "Error creating interface pair (%s,%s): %s " %
( intf1, intf2, cmdOutput ) )
# second: move both endpoints into the corresponding namespaces
moveIntf(intf1, node1)
moveIntf(intf2, node2)
# Override Method
mininet.util.makeIntfPair = _makeIntfPair; | 35.87037 | 81 | 0.663913 |
import mininet.util;
from mininet.util import quietRun, moveIntf;
def _makeIntfPair( intf1, intf2, addr1=None, addr2=None, node1=None, node2=None,
deleteIntfs=True, runCmd=None ):
if deleteIntfs:
quietRun( 'ip link del ' + intf1, shell=True )
quietRun( 'ip link del ' + intf2, shell=True )
if addr1 is None and addr2 is None:
cmdOutput = quietRun( 'ip link add name %s '
'type veth peer name %s ' %
( intf1, intf2 ),
shell=True )
else:
cmdOutput = quietRun( 'ip link add name %s '
'address %s '
'type veth peer name %s '
'address %s ' %
( intf1, addr1, intf2, addr2 ),
shell=True )
if cmdOutput:
raise Exception( "Error creating interface pair (%s,%s): %s " %
( intf1, intf2, cmdOutput ) )
moveIntf(intf1, node1)
moveIntf(intf2, node2)
mininet.util.makeIntfPair = _makeIntfPair; | true | true |
f72c344a4be417fe87d7e7e8ebbc0ea10789d3b1 | 22,433 | py | Python | nuitka/specs/BuiltinParameterSpecs.py | gdementen/Nuitka | 1f12be2364d07ffb168a7302dde94cb25eca9a70 | [
"Apache-2.0"
] | 5,421 | 2018-09-24T08:04:06.000Z | 2022-03-31T20:02:37.000Z | venv/Lib/site-packages/nuitka/specs/BuiltinParameterSpecs.py | matthijsvanvliet/raytracing-python | 73d692b47330ab94eedde579a51063e3a907e92b | [
"MIT"
] | 1,348 | 2018-09-22T13:41:00.000Z | 2022-03-31T22:33:40.000Z | venv/Lib/site-packages/nuitka/specs/BuiltinParameterSpecs.py | matthijsvanvliet/raytracing-python | 73d692b47330ab94eedde579a51063e3a907e92b | [
"MIT"
] | 396 | 2018-09-28T15:37:03.000Z | 2022-03-29T10:52:09.000Z | # Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Optimizations of built-ins to built-in calls.
"""
from __future__ import print_function
import math
from nuitka.__past__ import builtins
from nuitka.PythonVersions import python_version
from nuitka.Tracing import optimization_logger
from .ParameterSpecs import ParameterSpec, TooManyArguments, matchCall
class BuiltinParameterSpec(ParameterSpec):
__slots__ = ("builtin",)
def __init__(
self,
name,
arg_names,
default_count,
list_star_arg=None,
dict_star_arg=None,
pos_only_args=(),
kw_only_args=(),
):
ParameterSpec.__init__(
self,
ps_name=name,
ps_normal_args=arg_names,
ps_list_star_arg=list_star_arg,
ps_dict_star_arg=dict_star_arg,
ps_default_count=default_count,
ps_pos_only_args=pos_only_args,
ps_kw_only_args=kw_only_args,
)
self.builtin = getattr(builtins, name, None)
assert default_count <= len(arg_names) + len(kw_only_args) + len(pos_only_args)
def __repr__(self):
return "<BuiltinParameterSpec %s>" % self.name
def getName(self):
return self.name
def isCompileTimeComputable(self, values):
# By default, we make this dependent on the ability to compute the
# arguments, which is of course a good start for most cases, so this
# is for overloads, pylint: disable=no-self-use
for value in values:
if value is not None and not value.isCompileTimeConstant():
return False
return True
def simulateCall(self, given_values):
# Using star dict call for simulation and catch any exception as really
# fatal, pylint: disable=broad-except,too-many-branches
try:
given_normal_args = given_values[: self.getArgumentCount()]
if self.list_star_arg:
given_list_star_args = given_values[self.getArgumentCount()]
else:
given_list_star_args = None
if self.dict_star_arg:
given_dict_star_args = given_values[-1]
else:
given_dict_star_args = None
arg_dict = {}
for arg_name, given_value in zip(
self.getArgumentNames(), given_normal_args
):
assert type(given_value) not in (
tuple,
list,
), "do not like a tuple %s" % (given_value,)
if given_value is not None:
arg_dict[arg_name] = given_value.getCompileTimeConstant()
if given_dict_star_args:
for given_dict_star_arg in reversed(given_dict_star_args):
arg_name = given_dict_star_arg.subnode_key.getCompileTimeConstant()
arg_value = (
given_dict_star_arg.subnode_value.getCompileTimeConstant()
)
arg_dict[arg_name] = arg_value
arg_list = []
for arg_name in self.getArgumentNames():
if arg_name not in arg_dict:
break
arg_list.append(arg_dict[arg_name])
del arg_dict[arg_name]
except Exception as e:
optimization_logger.sysexit_exception("Fatal optimization problem", e)
if given_list_star_args:
return self.builtin(
*(
arg_list
+ list(
value.getCompileTimeConstant() for value in given_list_star_args
)
),
**arg_dict
)
else:
return self.builtin(*arg_list, **arg_dict)
class BuiltinParameterSpecNoKeywords(BuiltinParameterSpec):
__slots__ = ()
def allowsKeywords(self):
return False
def simulateCall(self, given_values):
# Using star dict call for simulation and catch any exception as really fatal,
# pylint: disable=broad-except
try:
if self.list_star_arg:
given_list_star_arg = given_values[self.getArgumentCount()]
else:
given_list_star_arg = None
arg_list = []
refuse_more = False
for _arg_name, given_value in zip(self.getArgumentNames(), given_values):
assert type(given_value) not in (
tuple,
list,
), "do not like tuple %s" % (given_value,)
if given_value is not None:
if not refuse_more:
arg_list.append(given_value.getCompileTimeConstant())
else:
assert False
else:
refuse_more = True
if given_list_star_arg is not None:
arg_list += [
value.getCompileTimeConstant() for value in given_list_star_arg
]
except Exception as e:
optimization_logger.sysexit_exception("matching call", e)
return self.builtin(*arg_list)
class BuiltinParameterSpecExceptionsKwOnly(BuiltinParameterSpec):
def __init__(self, exception_name, kw_only_args):
BuiltinParameterSpec.__init__(
self,
name=exception_name,
arg_names=(),
default_count=len(kw_only_args), # For exceptions, they will be required.
list_star_arg="args",
kw_only_args=kw_only_args,
)
class BuiltinParameterSpecExceptions(BuiltinParameterSpec):
def __init__(self, exception_name):
BuiltinParameterSpec.__init__(
self,
name=exception_name,
arg_names=(),
default_count=0,
list_star_arg="args",
)
def allowsKeywords(self):
return False
def getKeywordRefusalText(self):
return "exceptions.%s does not take keyword arguments" % self.name
def getCallableName(self):
return "exceptions." + self.getName()
def makeBuiltinExceptionParameterSpec(exception_name):
"""Factory function to create parameter spec for an exception from its name.
Args:
exception_name - (str) name of the built-in exception
Returns:
ParameterSpec that can be used to evaluate calls of these exceptions.
"""
if exception_name == "ImportError" and python_version >= 0x300:
# This is currently the only known built-in exception that does it, but let's
# be general, as surely that list is going to expand only.
return BuiltinParameterSpecExceptionsKwOnly(
exception_name=exception_name, kw_only_args=("name", "path")
)
else:
return BuiltinParameterSpecExceptions(exception_name=exception_name)
class BuiltinParameterSpecPosArgs(BuiltinParameterSpec):
def __init__(
self,
name,
pos_only_args,
arg_names,
default_count,
list_star_arg=None,
dict_star_arg=None,
):
BuiltinParameterSpec.__init__(
self,
name=name,
arg_names=arg_names,
default_count=default_count,
pos_only_args=pos_only_args,
list_star_arg=list_star_arg,
dict_star_arg=dict_star_arg,
)
if python_version < 0x370:
builtin_int_spec = BuiltinParameterSpec("int", ("x", "base"), default_count=2)
else:
builtin_int_spec = BuiltinParameterSpecPosArgs(
"int", ("x",), ("base",), default_count=2
)
# These builtins are only available for Python2
if python_version < 0x300:
builtin_long_spec = BuiltinParameterSpec("long", ("x", "base"), default_count=2)
builtin_execfile_spec = BuiltinParameterSpecNoKeywords(
"execfile", ("filename", "globals", "locals"), default_count=2
)
builtin_unicode_p2_spec = BuiltinParameterSpec(
"unicode", ("string", "encoding", "errors"), default_count=3
)
builtin_xrange_spec = BuiltinParameterSpecNoKeywords(
"xrange" if python_version < 0x300 else "range",
("start", "stop", "step"),
default_count=2,
)
if python_version < 0x370:
builtin_bool_spec = BuiltinParameterSpec("bool", ("x",), default_count=1)
else:
builtin_bool_spec = BuiltinParameterSpecNoKeywords("bool", ("x",), default_count=1)
if python_version < 0x370:
builtin_float_spec = BuiltinParameterSpec("float", ("x",), default_count=1)
else:
builtin_float_spec = BuiltinParameterSpecNoKeywords(
"float", ("x",), default_count=1
)
builtin_complex_spec = BuiltinParameterSpec(
"complex", ("real", "imag"), default_count=2
)
# This built-in have variable parameters for Python2/3
if python_version < 0x300:
builtin_str_spec = BuiltinParameterSpec("str", ("object",), default_count=1)
else:
builtin_str_spec = BuiltinParameterSpec(
"str", ("object", "encoding", "errors"), default_count=3
)
builtin_len_spec = BuiltinParameterSpecNoKeywords("len", ("object",), default_count=0)
builtin_dict_spec = BuiltinParameterSpec(
"dict", (), default_count=0, list_star_arg="list_args", dict_star_arg="dict_args"
)
builtin_any_spec = BuiltinParameterSpecNoKeywords("any", ("object",), default_count=0)
builtin_abs_spec = BuiltinParameterSpecNoKeywords("abs", ("object",), default_count=0)
builtin_all_spec = BuiltinParameterSpecNoKeywords("all", ("object",), default_count=0)
if python_version < 0x370:
builtin_tuple_spec = BuiltinParameterSpec("tuple", ("sequence",), default_count=1)
builtin_list_spec = BuiltinParameterSpec("list", ("sequence",), default_count=1)
else:
builtin_tuple_spec = BuiltinParameterSpecNoKeywords(
"tuple", ("sequence",), default_count=1
)
builtin_list_spec = BuiltinParameterSpecNoKeywords(
"list", ("sequence",), default_count=1
)
builtin_set_spec = BuiltinParameterSpecNoKeywords("set", ("iterable",), default_count=1)
builtin_frozenset_spec = BuiltinParameterSpecNoKeywords(
"frozenset", ("iterable",), default_count=1
)
builtin_import_spec = BuiltinParameterSpec(
"__import__", ("name", "globals", "locals", "fromlist", "level"), default_count=4
)
if python_version < 0x300:
builtin_open_spec = BuiltinParameterSpec(
"open", ("name", "mode", "buffering"), default_count=3
)
else:
builtin_open_spec = BuiltinParameterSpec(
"open",
(
"file",
"mode",
"buffering",
"encoding",
"errors",
"newline",
"closefd",
"opener",
),
default_count=7,
)
builtin_chr_spec = BuiltinParameterSpecNoKeywords("chr", ("i",), default_count=0)
builtin_ord_spec = BuiltinParameterSpecNoKeywords("ord", ("c",), default_count=0)
builtin_bin_spec = BuiltinParameterSpecNoKeywords("bin", ("number",), default_count=0)
builtin_oct_spec = BuiltinParameterSpecNoKeywords("oct", ("number",), default_count=0)
builtin_hex_spec = BuiltinParameterSpecNoKeywords("hex", ("number",), default_count=0)
builtin_id_spec = BuiltinParameterSpecNoKeywords("id", ("object",), default_count=0)
builtin_repr_spec = BuiltinParameterSpecNoKeywords("repr", ("object",), default_count=0)
builtin_dir_spec = BuiltinParameterSpecNoKeywords("dir", ("object",), default_count=1)
builtin_vars_spec = BuiltinParameterSpecNoKeywords("vars", ("object",), default_count=1)
builtin_locals_spec = BuiltinParameterSpecNoKeywords("locals", (), default_count=0)
builtin_globals_spec = BuiltinParameterSpecNoKeywords("globals", (), default_count=0)
builtin_eval_spec = BuiltinParameterSpecNoKeywords(
"eval", ("source", "globals", "locals"), 2
)
if python_version < 0x300:
builtin_compile_spec = BuiltinParameterSpec(
"compile",
("source", "filename", "mode", "flags", "dont_inherit"),
default_count=2,
)
else:
builtin_compile_spec = BuiltinParameterSpec(
"compile",
("source", "filename", "mode", "flags", "dont_inherit", "optimize"),
default_count=3,
)
if python_version >= 0x300:
builtin_exec_spec = BuiltinParameterSpecNoKeywords(
"exec", ("source", "globals", "locals"), default_count=2
)
# Note: Iter in fact names its first argument if the default applies
# "collection", fixed up in a wrapper.
builtin_iter_spec = BuiltinParameterSpecNoKeywords(
"iter", ("callable", "sentinel"), default_count=1
)
builtin_next_spec = BuiltinParameterSpecNoKeywords(
"next", ("iterator", "default"), default_count=1
)
# Note: type with 1 and type with 3 arguments are too different.
builtin_type1_spec = BuiltinParameterSpecNoKeywords(
"type", ("object",), default_count=0
)
builtin_type3_spec = BuiltinParameterSpecNoKeywords(
"type", ("name", "bases", "dict"), default_count=0
)
builtin_super_spec = BuiltinParameterSpecNoKeywords(
"super", ("type", "object"), default_count=1 if python_version < 0x300 else 2
)
builtin_hasattr_spec = BuiltinParameterSpecNoKeywords(
"hasattr", ("object", "name"), default_count=0
)
builtin_getattr_spec = BuiltinParameterSpecNoKeywords(
"getattr", ("object", "name", "default"), default_count=1
)
builtin_setattr_spec = BuiltinParameterSpecNoKeywords(
"setattr", ("object", "name", "value"), default_count=0
)
builtin_isinstance_spec = BuiltinParameterSpecNoKeywords(
"isinstance", ("instance", "classes"), default_count=0
)
builtin_issubclass_spec = BuiltinParameterSpecNoKeywords(
"issubclass", ("cls", "classes"), default_count=0
)
class BuiltinBytearraySpec(BuiltinParameterSpecPosArgs):
def isCompileTimeComputable(self, values):
# For bytearrays, we need to avoid the case of large bytearray
# construction from an integer at compile time.
result = BuiltinParameterSpec.isCompileTimeComputable(self, values=values)
if result and len(values) == 1:
index_value = values[0].getIndexValue()
if index_value is None:
return result
return index_value < 256
else:
return result
builtin_bytearray_spec = BuiltinBytearraySpec(
"bytearray", ("string",), ("encoding", "errors"), default_count=2
)
builtin_bytes_p3_spec = BuiltinBytearraySpec(
"bytes", ("string",), ("encoding", "errors"), default_count=3
)
# Beware: One argument version defines "stop", not "start".
builtin_slice_spec = BuiltinParameterSpecNoKeywords(
"slice", ("start", "stop", "step"), default_count=2
)
builtin_hash_spec = BuiltinParameterSpecNoKeywords("hash", ("object",), default_count=0)
builtin_format_spec = BuiltinParameterSpecNoKeywords(
"format", ("value", "format_spec"), default_count=1
)
if python_version < 0x380:
builtin_sum_spec = BuiltinParameterSpecNoKeywords(
"sum", ("sequence", "start"), default_count=1
)
else:
builtin_sum_spec = BuiltinParameterSpecPosArgs(
"sum", ("sequence",), ("start",), default_count=1
)
builtin_staticmethod_spec = BuiltinParameterSpecNoKeywords(
"staticmethod", ("function",), default_count=0
)
builtin_classmethod_spec = BuiltinParameterSpecNoKeywords(
"classmethod", ("function",), default_count=0
)
if python_version < 0x300:
builtin_sorted_spec = BuiltinParameterSpecNoKeywords(
"sorted", ("iterable", "cmp", "key", "reverse"), default_count=2
)
else:
builtin_sorted_spec = BuiltinParameterSpecNoKeywords(
"sorted", ("iterable", "key", "reverse"), default_count=2
)
builtin_reversed_spec = BuiltinParameterSpecNoKeywords(
"reversed", ("object",), default_count=0
)
builtin_reversed_spec = BuiltinParameterSpecNoKeywords(
"reversed", ("object",), default_count=0
)
if python_version < 0x300:
builtin_enumerate_spec = BuiltinParameterSpec(
"enumerate", ("sequence", "start"), default_count=1
)
else:
builtin_enumerate_spec = BuiltinParameterSpec(
"enumerate", ("iterable", "start"), default_count=1
)
class BuiltinRangeSpec(BuiltinParameterSpecNoKeywords):
def isCompileTimeComputable(self, values):
# For ranges, we need have many cases that can prevent the ability
# to pre-compute, pylint: disable=too-many-branches,too-many-return-statements
result = BuiltinParameterSpecNoKeywords.isCompileTimeComputable(
self, values=values
)
if result:
arg_count = len(values)
if arg_count == 1:
low = values[0]
# If it's not a number constant, we can compute the exception
# that will be raised.
if not low.isNumberConstant():
return True
return low.getCompileTimeConstant() < 256
elif arg_count == 2:
low, high = values
# If it's not a number constant, we can compute the exception
# that will be raised.
if not low.isNumberConstant() or not high.isNumberConstant():
return True
return (
high.getCompileTimeConstant() - low.getCompileTimeConstant() < 256
)
elif arg_count == 3:
low, high, step = values
if (
not low.isNumberConstant()
or not high.isNumberConstant()
or not step.isNumberConstant()
):
return True
low = low.getCompileTimeConstant()
high = high.getCompileTimeConstant()
step = step.getCompileTimeConstant()
# It's going to give a ZeroDivisionError in this case.
if step == 0:
return True
if low < high:
if step < 0:
return True
else:
return math.ceil(float(high - low) / step) < 256
else:
if step > 0:
return True
else:
return math.ceil(float(high - low) / step) < 256
else:
assert False
else:
return False
builtin_range_spec = BuiltinRangeSpec(
"range", ("start", "stop", "step"), default_count=2
)
if python_version >= 0x300:
builtin_ascii_spec = BuiltinParameterSpecNoKeywords(
"ascii", ("object",), default_count=0
)
builtin_divmod_spec = BuiltinParameterSpecNoKeywords(
"divmod", ("left", "right"), default_count=0
)
def extractBuiltinArgs(node, builtin_spec, builtin_class, empty_special_class=None):
# Many cases to deal with, pylint: disable=too-many-branches
try:
kw = node.subnode_kwargs
# TODO: Could check for too many / too few, even if they are unknown, we
# might raise that error, but that need not be optimized immediately.
if kw is not None:
if not kw.isMappingWithConstantStringKeys():
return None
pairs = kw.getMappingStringKeyPairs()
if pairs and not builtin_spec.allowsKeywords():
raise TooManyArguments(TypeError(builtin_spec.getKeywordRefusalText()))
else:
pairs = ()
args = node.subnode_args
if args:
if not args.canPredictIterationValues():
return None
positional = args.getIterationValues()
else:
positional = ()
if not positional and not pairs and empty_special_class is not None:
return empty_special_class(source_ref=node.getSourceReference())
args_dict = matchCall(
func_name=builtin_spec.getName(),
args=builtin_spec.getArgumentNames(),
kw_only_args=builtin_spec.getKwOnlyParameterNames(),
star_list_arg=builtin_spec.getStarListArgumentName(),
star_dict_arg=builtin_spec.getStarDictArgumentName(),
num_defaults=builtin_spec.getDefaultCount(),
num_posonly=builtin_spec.getPosOnlyParameterCount(),
positional=positional,
pairs=pairs,
)
except TooManyArguments as e:
from nuitka.nodes.NodeMakingHelpers import (
makeRaiseExceptionReplacementExpressionFromInstance,
wrapExpressionWithSideEffects,
)
return wrapExpressionWithSideEffects(
new_node=makeRaiseExceptionReplacementExpressionFromInstance(
expression=node, exception=e.getRealException()
),
old_node=node,
side_effects=node.extractSideEffectsPreCall(),
)
# Using list reference for passing the arguments without names where it
# it possible, otherwise dictionary to make those distinuishable.
args_list = []
for argument_name in builtin_spec.getArgumentNames():
args_list.append(args_dict[argument_name])
if builtin_spec.getStarListArgumentName() is not None:
args_list.append(args_dict[builtin_spec.getStarListArgumentName()])
if builtin_spec.getStarDictArgumentName() is not None:
args_list.append(args_dict[builtin_spec.getStarDictArgumentName()])
for argument_name in builtin_spec.getKwOnlyParameterNames():
args_list.append(args_dict[argument_name])
# Using list reference for passing the arguments without names,
result = builtin_class(*args_list, source_ref=node.getSourceReference())
if python_version < 0x380:
result.setCompatibleSourceReference(node.getCompatibleSourceReference())
return result
| 33.432191 | 88 | 0.642179 |
from __future__ import print_function
import math
from nuitka.__past__ import builtins
from nuitka.PythonVersions import python_version
from nuitka.Tracing import optimization_logger
from .ParameterSpecs import ParameterSpec, TooManyArguments, matchCall
class BuiltinParameterSpec(ParameterSpec):
__slots__ = ("builtin",)
def __init__(
self,
name,
arg_names,
default_count,
list_star_arg=None,
dict_star_arg=None,
pos_only_args=(),
kw_only_args=(),
):
ParameterSpec.__init__(
self,
ps_name=name,
ps_normal_args=arg_names,
ps_list_star_arg=list_star_arg,
ps_dict_star_arg=dict_star_arg,
ps_default_count=default_count,
ps_pos_only_args=pos_only_args,
ps_kw_only_args=kw_only_args,
)
self.builtin = getattr(builtins, name, None)
assert default_count <= len(arg_names) + len(kw_only_args) + len(pos_only_args)
def __repr__(self):
return "<BuiltinParameterSpec %s>" % self.name
def getName(self):
return self.name
def isCompileTimeComputable(self, values):
for value in values:
if value is not None and not value.isCompileTimeConstant():
return False
return True
def simulateCall(self, given_values):
try:
given_normal_args = given_values[: self.getArgumentCount()]
if self.list_star_arg:
given_list_star_args = given_values[self.getArgumentCount()]
else:
given_list_star_args = None
if self.dict_star_arg:
given_dict_star_args = given_values[-1]
else:
given_dict_star_args = None
arg_dict = {}
for arg_name, given_value in zip(
self.getArgumentNames(), given_normal_args
):
assert type(given_value) not in (
tuple,
list,
), "do not like a tuple %s" % (given_value,)
if given_value is not None:
arg_dict[arg_name] = given_value.getCompileTimeConstant()
if given_dict_star_args:
for given_dict_star_arg in reversed(given_dict_star_args):
arg_name = given_dict_star_arg.subnode_key.getCompileTimeConstant()
arg_value = (
given_dict_star_arg.subnode_value.getCompileTimeConstant()
)
arg_dict[arg_name] = arg_value
arg_list = []
for arg_name in self.getArgumentNames():
if arg_name not in arg_dict:
break
arg_list.append(arg_dict[arg_name])
del arg_dict[arg_name]
except Exception as e:
optimization_logger.sysexit_exception("Fatal optimization problem", e)
if given_list_star_args:
return self.builtin(
*(
arg_list
+ list(
value.getCompileTimeConstant() for value in given_list_star_args
)
),
**arg_dict
)
else:
return self.builtin(*arg_list, **arg_dict)
class BuiltinParameterSpecNoKeywords(BuiltinParameterSpec):
__slots__ = ()
def allowsKeywords(self):
return False
def simulateCall(self, given_values):
try:
if self.list_star_arg:
given_list_star_arg = given_values[self.getArgumentCount()]
else:
given_list_star_arg = None
arg_list = []
refuse_more = False
for _arg_name, given_value in zip(self.getArgumentNames(), given_values):
assert type(given_value) not in (
tuple,
list,
), "do not like tuple %s" % (given_value,)
if given_value is not None:
if not refuse_more:
arg_list.append(given_value.getCompileTimeConstant())
else:
assert False
else:
refuse_more = True
if given_list_star_arg is not None:
arg_list += [
value.getCompileTimeConstant() for value in given_list_star_arg
]
except Exception as e:
optimization_logger.sysexit_exception("matching call", e)
return self.builtin(*arg_list)
class BuiltinParameterSpecExceptionsKwOnly(BuiltinParameterSpec):
def __init__(self, exception_name, kw_only_args):
BuiltinParameterSpec.__init__(
self,
name=exception_name,
arg_names=(),
default_count=len(kw_only_args),
list_star_arg="args",
kw_only_args=kw_only_args,
)
class BuiltinParameterSpecExceptions(BuiltinParameterSpec):
def __init__(self, exception_name):
BuiltinParameterSpec.__init__(
self,
name=exception_name,
arg_names=(),
default_count=0,
list_star_arg="args",
)
def allowsKeywords(self):
return False
def getKeywordRefusalText(self):
return "exceptions.%s does not take keyword arguments" % self.name
def getCallableName(self):
return "exceptions." + self.getName()
def makeBuiltinExceptionParameterSpec(exception_name):
if exception_name == "ImportError" and python_version >= 0x300:
# be general, as surely that list is going to expand only.
return BuiltinParameterSpecExceptionsKwOnly(
exception_name=exception_name, kw_only_args=("name", "path")
)
else:
return BuiltinParameterSpecExceptions(exception_name=exception_name)
class BuiltinParameterSpecPosArgs(BuiltinParameterSpec):
def __init__(
self,
name,
pos_only_args,
arg_names,
default_count,
list_star_arg=None,
dict_star_arg=None,
):
BuiltinParameterSpec.__init__(
self,
name=name,
arg_names=arg_names,
default_count=default_count,
pos_only_args=pos_only_args,
list_star_arg=list_star_arg,
dict_star_arg=dict_star_arg,
)
if python_version < 0x370:
builtin_int_spec = BuiltinParameterSpec("int", ("x", "base"), default_count=2)
else:
builtin_int_spec = BuiltinParameterSpecPosArgs(
"int", ("x",), ("base",), default_count=2
)
# These builtins are only available for Python2
if python_version < 0x300:
builtin_long_spec = BuiltinParameterSpec("long", ("x", "base"), default_count=2)
builtin_execfile_spec = BuiltinParameterSpecNoKeywords(
"execfile", ("filename", "globals", "locals"), default_count=2
)
builtin_unicode_p2_spec = BuiltinParameterSpec(
"unicode", ("string", "encoding", "errors"), default_count=3
)
builtin_xrange_spec = BuiltinParameterSpecNoKeywords(
"xrange" if python_version < 0x300 else "range",
("start", "stop", "step"),
default_count=2,
)
if python_version < 0x370:
builtin_bool_spec = BuiltinParameterSpec("bool", ("x",), default_count=1)
else:
builtin_bool_spec = BuiltinParameterSpecNoKeywords("bool", ("x",), default_count=1)
if python_version < 0x370:
builtin_float_spec = BuiltinParameterSpec("float", ("x",), default_count=1)
else:
builtin_float_spec = BuiltinParameterSpecNoKeywords(
"float", ("x",), default_count=1
)
builtin_complex_spec = BuiltinParameterSpec(
"complex", ("real", "imag"), default_count=2
)
# This built-in have variable parameters for Python2/3
if python_version < 0x300:
builtin_str_spec = BuiltinParameterSpec("str", ("object",), default_count=1)
else:
builtin_str_spec = BuiltinParameterSpec(
"str", ("object", "encoding", "errors"), default_count=3
)
builtin_len_spec = BuiltinParameterSpecNoKeywords("len", ("object",), default_count=0)
builtin_dict_spec = BuiltinParameterSpec(
"dict", (), default_count=0, list_star_arg="list_args", dict_star_arg="dict_args"
)
builtin_any_spec = BuiltinParameterSpecNoKeywords("any", ("object",), default_count=0)
builtin_abs_spec = BuiltinParameterSpecNoKeywords("abs", ("object",), default_count=0)
builtin_all_spec = BuiltinParameterSpecNoKeywords("all", ("object",), default_count=0)
if python_version < 0x370:
builtin_tuple_spec = BuiltinParameterSpec("tuple", ("sequence",), default_count=1)
builtin_list_spec = BuiltinParameterSpec("list", ("sequence",), default_count=1)
else:
builtin_tuple_spec = BuiltinParameterSpecNoKeywords(
"tuple", ("sequence",), default_count=1
)
builtin_list_spec = BuiltinParameterSpecNoKeywords(
"list", ("sequence",), default_count=1
)
builtin_set_spec = BuiltinParameterSpecNoKeywords("set", ("iterable",), default_count=1)
builtin_frozenset_spec = BuiltinParameterSpecNoKeywords(
"frozenset", ("iterable",), default_count=1
)
builtin_import_spec = BuiltinParameterSpec(
"__import__", ("name", "globals", "locals", "fromlist", "level"), default_count=4
)
if python_version < 0x300:
builtin_open_spec = BuiltinParameterSpec(
"open", ("name", "mode", "buffering"), default_count=3
)
else:
builtin_open_spec = BuiltinParameterSpec(
"open",
(
"file",
"mode",
"buffering",
"encoding",
"errors",
"newline",
"closefd",
"opener",
),
default_count=7,
)
builtin_chr_spec = BuiltinParameterSpecNoKeywords("chr", ("i",), default_count=0)
builtin_ord_spec = BuiltinParameterSpecNoKeywords("ord", ("c",), default_count=0)
builtin_bin_spec = BuiltinParameterSpecNoKeywords("bin", ("number",), default_count=0)
builtin_oct_spec = BuiltinParameterSpecNoKeywords("oct", ("number",), default_count=0)
builtin_hex_spec = BuiltinParameterSpecNoKeywords("hex", ("number",), default_count=0)
builtin_id_spec = BuiltinParameterSpecNoKeywords("id", ("object",), default_count=0)
builtin_repr_spec = BuiltinParameterSpecNoKeywords("repr", ("object",), default_count=0)
builtin_dir_spec = BuiltinParameterSpecNoKeywords("dir", ("object",), default_count=1)
builtin_vars_spec = BuiltinParameterSpecNoKeywords("vars", ("object",), default_count=1)
builtin_locals_spec = BuiltinParameterSpecNoKeywords("locals", (), default_count=0)
builtin_globals_spec = BuiltinParameterSpecNoKeywords("globals", (), default_count=0)
builtin_eval_spec = BuiltinParameterSpecNoKeywords(
"eval", ("source", "globals", "locals"), 2
)
if python_version < 0x300:
builtin_compile_spec = BuiltinParameterSpec(
"compile",
("source", "filename", "mode", "flags", "dont_inherit"),
default_count=2,
)
else:
builtin_compile_spec = BuiltinParameterSpec(
"compile",
("source", "filename", "mode", "flags", "dont_inherit", "optimize"),
default_count=3,
)
if python_version >= 0x300:
builtin_exec_spec = BuiltinParameterSpecNoKeywords(
"exec", ("source", "globals", "locals"), default_count=2
)
# Note: Iter in fact names its first argument if the default applies
# "collection", fixed up in a wrapper.
builtin_iter_spec = BuiltinParameterSpecNoKeywords(
"iter", ("callable", "sentinel"), default_count=1
)
builtin_next_spec = BuiltinParameterSpecNoKeywords(
"next", ("iterator", "default"), default_count=1
)
# Note: type with 1 and type with 3 arguments are too different.
builtin_type1_spec = BuiltinParameterSpecNoKeywords(
"type", ("object",), default_count=0
)
builtin_type3_spec = BuiltinParameterSpecNoKeywords(
"type", ("name", "bases", "dict"), default_count=0
)
builtin_super_spec = BuiltinParameterSpecNoKeywords(
"super", ("type", "object"), default_count=1 if python_version < 0x300 else 2
)
builtin_hasattr_spec = BuiltinParameterSpecNoKeywords(
"hasattr", ("object", "name"), default_count=0
)
builtin_getattr_spec = BuiltinParameterSpecNoKeywords(
"getattr", ("object", "name", "default"), default_count=1
)
builtin_setattr_spec = BuiltinParameterSpecNoKeywords(
"setattr", ("object", "name", "value"), default_count=0
)
builtin_isinstance_spec = BuiltinParameterSpecNoKeywords(
"isinstance", ("instance", "classes"), default_count=0
)
builtin_issubclass_spec = BuiltinParameterSpecNoKeywords(
"issubclass", ("cls", "classes"), default_count=0
)
class BuiltinBytearraySpec(BuiltinParameterSpecPosArgs):
def isCompileTimeComputable(self, values):
# For bytearrays, we need to avoid the case of large bytearray
# construction from an integer at compile time.
result = BuiltinParameterSpec.isCompileTimeComputable(self, values=values)
if result and len(values) == 1:
index_value = values[0].getIndexValue()
if index_value is None:
return result
return index_value < 256
else:
return result
builtin_bytearray_spec = BuiltinBytearraySpec(
"bytearray", ("string",), ("encoding", "errors"), default_count=2
)
builtin_bytes_p3_spec = BuiltinBytearraySpec(
"bytes", ("string",), ("encoding", "errors"), default_count=3
)
# Beware: One argument version defines "stop", not "start".
builtin_slice_spec = BuiltinParameterSpecNoKeywords(
"slice", ("start", "stop", "step"), default_count=2
)
builtin_hash_spec = BuiltinParameterSpecNoKeywords("hash", ("object",), default_count=0)
builtin_format_spec = BuiltinParameterSpecNoKeywords(
"format", ("value", "format_spec"), default_count=1
)
if python_version < 0x380:
builtin_sum_spec = BuiltinParameterSpecNoKeywords(
"sum", ("sequence", "start"), default_count=1
)
else:
builtin_sum_spec = BuiltinParameterSpecPosArgs(
"sum", ("sequence",), ("start",), default_count=1
)
builtin_staticmethod_spec = BuiltinParameterSpecNoKeywords(
"staticmethod", ("function",), default_count=0
)
builtin_classmethod_spec = BuiltinParameterSpecNoKeywords(
"classmethod", ("function",), default_count=0
)
if python_version < 0x300:
builtin_sorted_spec = BuiltinParameterSpecNoKeywords(
"sorted", ("iterable", "cmp", "key", "reverse"), default_count=2
)
else:
builtin_sorted_spec = BuiltinParameterSpecNoKeywords(
"sorted", ("iterable", "key", "reverse"), default_count=2
)
builtin_reversed_spec = BuiltinParameterSpecNoKeywords(
"reversed", ("object",), default_count=0
)
builtin_reversed_spec = BuiltinParameterSpecNoKeywords(
"reversed", ("object",), default_count=0
)
if python_version < 0x300:
builtin_enumerate_spec = BuiltinParameterSpec(
"enumerate", ("sequence", "start"), default_count=1
)
else:
builtin_enumerate_spec = BuiltinParameterSpec(
"enumerate", ("iterable", "start"), default_count=1
)
class BuiltinRangeSpec(BuiltinParameterSpecNoKeywords):
def isCompileTimeComputable(self, values):
# For ranges, we need have many cases that can prevent the ability
# to pre-compute, pylint: disable=too-many-branches,too-many-return-statements
result = BuiltinParameterSpecNoKeywords.isCompileTimeComputable(
self, values=values
)
if result:
arg_count = len(values)
if arg_count == 1:
low = values[0]
# If it's not a number constant, we can compute the exception
if not low.isNumberConstant():
return True
return low.getCompileTimeConstant() < 256
elif arg_count == 2:
low, high = values
# that will be raised.
if not low.isNumberConstant() or not high.isNumberConstant():
return True
return (
high.getCompileTimeConstant() - low.getCompileTimeConstant() < 256
)
elif arg_count == 3:
low, high, step = values
if (
not low.isNumberConstant()
or not high.isNumberConstant()
or not step.isNumberConstant()
):
return True
low = low.getCompileTimeConstant()
high = high.getCompileTimeConstant()
step = step.getCompileTimeConstant()
# It's going to give a ZeroDivisionError in this case.
if step == 0:
return True
if low < high:
if step < 0:
return True
else:
return math.ceil(float(high - low) / step) < 256
else:
if step > 0:
return True
else:
return math.ceil(float(high - low) / step) < 256
else:
assert False
else:
return False
builtin_range_spec = BuiltinRangeSpec(
"range", ("start", "stop", "step"), default_count=2
)
if python_version >= 0x300:
builtin_ascii_spec = BuiltinParameterSpecNoKeywords(
"ascii", ("object",), default_count=0
)
builtin_divmod_spec = BuiltinParameterSpecNoKeywords(
"divmod", ("left", "right"), default_count=0
)
def extractBuiltinArgs(node, builtin_spec, builtin_class, empty_special_class=None):
try:
kw = node.subnode_kwargs
if kw is not None:
if not kw.isMappingWithConstantStringKeys():
return None
pairs = kw.getMappingStringKeyPairs()
if pairs and not builtin_spec.allowsKeywords():
raise TooManyArguments(TypeError(builtin_spec.getKeywordRefusalText()))
else:
pairs = ()
args = node.subnode_args
if args:
if not args.canPredictIterationValues():
return None
positional = args.getIterationValues()
else:
positional = ()
if not positional and not pairs and empty_special_class is not None:
return empty_special_class(source_ref=node.getSourceReference())
args_dict = matchCall(
func_name=builtin_spec.getName(),
args=builtin_spec.getArgumentNames(),
kw_only_args=builtin_spec.getKwOnlyParameterNames(),
star_list_arg=builtin_spec.getStarListArgumentName(),
star_dict_arg=builtin_spec.getStarDictArgumentName(),
num_defaults=builtin_spec.getDefaultCount(),
num_posonly=builtin_spec.getPosOnlyParameterCount(),
positional=positional,
pairs=pairs,
)
except TooManyArguments as e:
from nuitka.nodes.NodeMakingHelpers import (
makeRaiseExceptionReplacementExpressionFromInstance,
wrapExpressionWithSideEffects,
)
return wrapExpressionWithSideEffects(
new_node=makeRaiseExceptionReplacementExpressionFromInstance(
expression=node, exception=e.getRealException()
),
old_node=node,
side_effects=node.extractSideEffectsPreCall(),
)
args_list = []
for argument_name in builtin_spec.getArgumentNames():
args_list.append(args_dict[argument_name])
if builtin_spec.getStarListArgumentName() is not None:
args_list.append(args_dict[builtin_spec.getStarListArgumentName()])
if builtin_spec.getStarDictArgumentName() is not None:
args_list.append(args_dict[builtin_spec.getStarDictArgumentName()])
for argument_name in builtin_spec.getKwOnlyParameterNames():
args_list.append(args_dict[argument_name])
result = builtin_class(*args_list, source_ref=node.getSourceReference())
if python_version < 0x380:
result.setCompatibleSourceReference(node.getCompatibleSourceReference())
return result
| true | true |
f72c344f2c08cfd3448f089e38a1116d9b085c4c | 17,366 | py | Python | docker-images/taigav2/taiga-back/settings/common.py | mattcongy/itshop | 6be025a9eaa7fe7f495b5777d1f0e5a3184121c9 | [
"MIT"
] | 1 | 2017-05-29T19:01:06.000Z | 2017-05-29T19:01:06.000Z | docker-images/taigav2/taiga-back/settings/common.py | mattcongy/itshop | 6be025a9eaa7fe7f495b5777d1f0e5a3184121c9 | [
"MIT"
] | null | null | null | docker-images/taigav2/taiga-back/settings/common.py | mattcongy/itshop | 6be025a9eaa7fe7f495b5777d1f0e5a3184121c9 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os.path, sys, os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
APPEND_SLASH = False
ALLOWED_HOSTS = ["*"]
ADMINS = (
("Admin", "example@example.com"),
)
DEBUG = False
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "taiga",
}
}
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "unique-snowflake"
}
}
PASSWORD_HASHERS = [
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
]
# Default configuration for reverse proxy
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https")
# Errors report configuration
SEND_BROKEN_LINK_EMAILS = True
IGNORABLE_404_ENDS = (".php", ".cgi")
IGNORABLE_404_STARTS = ("/phpmyadmin/",)
ATOMIC_REQUESTS = True
TIME_ZONE = "UTC"
LOGIN_URL="/auth/login/"
USE_TZ = True
USE_I18N = True
USE_L10N = True
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
# Languages we provide translations for, out of the box.
LANGUAGES = [
#("af", "Afrikaans"), # Afrikaans
#("ar", "العربية"), # Arabic
#("ast", "Asturiano"), # Asturian
#("az", "Azərbaycan dili"), # Azerbaijani
#("bg", "Български"), # Bulgarian
#("be", "Беларуская"), # Belarusian
#("bn", "বাংলা"), # Bengali
#("br", "Bretón"), # Breton
#("bs", "Bosanski"), # Bosnian
("ca", "Català"), # Catalan
#("cs", "Čeština"), # Czech
#("cy", "Cymraeg"), # Welsh
#("da", "Dansk"), # Danish
("de", "Deutsch"), # German
#("el", "Ελληνικά"), # Greek
("en", "English (US)"), # English
#("en-au", "English (Australia)"), # Australian English
#("en-gb", "English (UK)"), # British English
#("eo", "esperanta"), # Esperanto
("es", "Español"), # Spanish
#("es-ar", "Español (Argentina)"), # Argentinian Spanish
#("es-mx", "Español (México)"), # Mexican Spanish
#("es-ni", "Español (Nicaragua)"), # Nicaraguan Spanish
#("es-ve", "Español (Venezuela)"), # Venezuelan Spanish
#("et", "Eesti"), # Estonian
#("eu", "Euskara"), # Basque
#("fa", "فارسی"), # Persian
("fi", "Suomi"), # Finnish
("fr", "Français"), # French
#("fy", "Frysk"), # Frisian
#("ga", "Irish"), # Irish
#("gl", "Galego"), # Galician
#("he", "עברית"), # Hebrew
#("hi", "हिन्दी"), # Hindi
#("hr", "Hrvatski"), # Croatian
#("hu", "Magyar"), # Hungarian
#("ia", "Interlingua"), # Interlingua
#("id", "Bahasa Indonesia"), # Indonesian
#("io", "IDO"), # Ido
#("is", "Íslenska"), # Icelandic
("it", "Italiano"), # Italian
#("ja", "日本語"), # Japanese
#("ka", "ქართული"), # Georgian
#("kk", "Қазақша"), # Kazakh
#("km", "ភាសាខ្មែរ"), # Khmer
#("kn", "ಕನ್ನಡ"), # Kannada
#("ko", "한국어"), # Korean
#("lb", "Lëtzebuergesch"), # Luxembourgish
#("lt", "Lietuvių"), # Lithuanian
#("lv", "Latviešu"), # Latvian
#("mk", "Македонски"), # Macedonian
#("ml", "മലയാളം"), # Malayalam
#("mn", "Монгол"), # Mongolian
#("mr", "मराठी"), # Marathi
#("my", "မြန်မာ"), # Burmese
("nb", "Norsk (bokmål)"), # Norwegian Bokmal
#("ne", "नेपाली"), # Nepali
("nl", "Nederlands"), # Dutch
#("nn", "Norsk (nynorsk)"), # Norwegian Nynorsk
#("os", "Ирон æвзаг"), # Ossetic
#("pa", "ਪੰਜਾਬੀ"), # Punjabi
("pl", "Polski"), # Polish
#("pt", "Português (Portugal)"), # Portuguese
("pt-br", "Português (Brasil)"), # Brazilian Portuguese
#("ro", "Română"), # Romanian
("ru", "Русский"), # Russian
#("sk", "Slovenčina"), # Slovak
#("sl", "Slovenščina"), # Slovenian
#("sq", "Shqip"), # Albanian
#("sr", "Српски"), # Serbian
#("sr-latn", "srpski"), # Serbian Latin
("sv", "Svenska"), # Swedish
#("sw", "Kiswahili"), # Swahili
#("ta", "தமிழ்"), # Tamil
#("te", "తెలుగు"), # Telugu
#("th", "ภาษาไทย"), # Thai
("tr", "Türkçe"), # Turkish
#("tt", "татар теле"), # Tatar
#("udm", "удмурт кыл"), # Udmurt
#("uk", "Українська"), # Ukrainian
#("ur", "اردو"), # Urdu
#("vi", "Tiếng Việt"), # Vietnamese
#("zh-hans", "中文(简体)"), # Simplified Chinese
("zh-hant", "中文(香港)"), # Traditional Chinese
]
# Languages using BiDi (right-to-left) layout
LANGUAGES_BIDI = ["he", "ar", "fa", "ur"]
LOCALE_PATHS = (
os.path.join(BASE_DIR, "locale"),
os.path.join(BASE_DIR, "taiga", "locale"),
)
SITES = {
"api": {"domain": "localhost:8000", "scheme": "http", "name": "api"},
"front": {"domain": "localhost:9001", "scheme": "http", "name": "front"},
}
SITE_ID = "api"
# Session configuration (only used for admin)
SESSION_ENGINE = "django.contrib.sessions.backends.db"
SESSION_COOKIE_AGE = 1209600 # (2 weeks)
# MAIL OPTIONS
DEFAULT_FROM_EMAIL = "john@doe.com"
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
DJMAIL_REAL_BACKEND = "django.core.mail.backends.console.EmailBackend"
DJMAIL_SEND_ASYNC = True
DJMAIL_MAX_RETRY_NUMBER = 3
DJMAIL_TEMPLATE_EXTENSION = "jinja"
# Events backend
EVENTS_PUSH_BACKEND = "taiga.events.backends.postgresql.EventsPushBackend"
# EVENTS_PUSH_BACKEND = "taiga.events.backends.rabbitmq.EventsPushBackend"
# EVENTS_PUSH_BACKEND_OPTIONS = {"url": "//guest:guest@127.0.0.1/"}
# Message System
MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"
# The absolute url is mandatory because attachments
# urls depends on it. On production should be set
# something like https://media.taiga.io/
MEDIA_URL = "http://localhost:8000/media/"
STATIC_URL = "http://localhost:8000/static/"
# Static configuration.
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Don't forget to use absolute paths, not relative paths.
)
# Defautl storage
DEFAULT_FILE_STORAGE = "taiga.base.storage.FileSystemStorage"
SECRET_KEY = "aw3+t2r(8(0kkrhg8)gx6i96v5^kv%6cfep9wxfom0%7dy0m9e"
TEMPLATES = [
{
"BACKEND": "django_jinja.backend.Jinja2",
"DIRS": [
os.path.join(BASE_DIR, "templates"),
],
"APP_DIRS": True,
"OPTIONS": {
'context_processors': [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.request",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
"match_extension": ".jinja",
}
},
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
os.path.join(BASE_DIR, "templates"),
],
"APP_DIRS": True,
"OPTIONS": {
'context_processors': [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.request",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
}
},
]
MIDDLEWARE_CLASSES = [
"taiga.base.middleware.cors.CoorsMiddleware",
"taiga.events.middleware.SessionIDMiddleware",
# Common middlewares
"django.middleware.common.CommonMiddleware",
"django.middleware.locale.LocaleMiddleware",
# Only needed by django admin
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
ROOT_URLCONF = "taiga.urls"
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.admin",
"django.contrib.staticfiles",
"django.contrib.sitemaps",
"taiga.base",
"taiga.base.api",
"taiga.locale",
"taiga.events",
"taiga.front",
"taiga.users",
"taiga.userstorage",
"taiga.external_apps",
"taiga.projects",
"taiga.projects.references",
"taiga.projects.custom_attributes",
"taiga.projects.history",
"taiga.projects.notifications",
"taiga.projects.attachments",
"taiga.projects.likes",
"taiga.projects.votes",
"taiga.projects.milestones",
"taiga.projects.epics",
"taiga.projects.userstories",
"taiga.projects.tasks",
"taiga.projects.issues",
"taiga.projects.wiki",
"taiga.searches",
"taiga.timeline",
"taiga.mdrender",
"taiga.export_import",
"taiga.feedback",
"taiga.stats",
"taiga.hooks.github",
"taiga.hooks.gitlab",
"taiga.hooks.bitbucket",
"taiga.hooks.gogs",
"taiga.webhooks",
"djmail",
"django_jinja",
"django_jinja.contrib._humanize",
"sr",
"easy_thumbnails",
"raven.contrib.django.raven_compat",
]
WSGI_APPLICATION = "taiga.wsgi.application"
LOGGING = {
"version": 1,
"disable_existing_loggers": True,
"filters": {
"require_debug_false": {
"()": "django.utils.log.RequireDebugFalse"
}
},
"formatters": {
"complete": {
"format": "%(levelname)s:%(asctime)s:%(module)s %(message)s"
},
"simple": {
"format": "%(levelname)s:%(asctime)s: %(message)s"
},
"null": {
"format": "%(message)s",
},
},
"handlers": {
"null": {
"level":"DEBUG",
"class":"logging.NullHandler",
},
"console":{
"level":"DEBUG",
"class":"logging.StreamHandler",
"formatter": "simple",
},
"mail_admins": {
"level": "ERROR",
"filters": ["require_debug_false"],
"class": "django.utils.log.AdminEmailHandler",
}
},
"loggers": {
"django": {
"handlers":["null"],
"propagate": True,
"level":"INFO",
},
"django.request": {
"handlers": ["mail_admins", "console"],
"level": "ERROR",
"propagate": False,
},
"taiga.export_import": {
"handlers": ["mail_admins", "console"],
"level": "ERROR",
"propagate": False,
},
"taiga": {
"handlers": ["console"],
"level": "DEBUG",
"propagate": False,
}
}
}
AUTH_USER_MODEL = "users.User"
FORMAT_MODULE_PATH = "taiga.base.formats"
DATE_INPUT_FORMATS = (
"%Y-%m-%d", "%m/%d/%Y", "%d/%m/%Y", "%b %d %Y",
"%b %d, %Y", "%d %b %Y", "%d %b, %Y", "%B %d %Y",
"%B %d, %Y", "%d %B %Y", "%d %B, %Y"
)
# Authentication settings (only for django admin)
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend", # default
)
MAX_AGE_AUTH_TOKEN = None
MAX_AGE_CANCEL_ACCOUNT = 30 * 24 * 60 * 60 # 30 days in seconds
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
# Mainly used by taiga-front
"taiga.auth.backends.Token",
# Mainly used for api debug.
"taiga.auth.backends.Session",
# Application tokens auth
"taiga.external_apps.auth_backends.Token",
),
"DEFAULT_THROTTLE_CLASSES": (
"taiga.base.throttling.AnonRateThrottle",
"taiga.base.throttling.UserRateThrottle"
),
"DEFAULT_THROTTLE_RATES": {
"anon": None,
"user": None,
"import-mode": None,
"import-dump-mode": "1/minute",
"create-memberships": None
},
"FILTER_BACKEND": "taiga.base.filters.FilterBackend",
"EXCEPTION_HANDLER": "taiga.base.exceptions.exception_handler",
"PAGINATE_BY": 30,
"PAGINATE_BY_PARAM": "page_size",
"MAX_PAGINATE_BY": 1000,
"DATETIME_FORMAT": "%Y-%m-%dT%H:%M:%S%z"
}
# Extra expose header related to Taiga APP (see taiga.base.middleware.cors=)
APP_EXTRA_EXPOSE_HEADERS = [
"taiga-info-total-opened-milestones",
"taiga-info-total-closed-milestones",
"taiga-info-project-memberships",
"taiga-info-project-is-private",
"taiga-info-order-updated"
]
DEFAULT_PROJECT_TEMPLATE = "scrum"
PUBLIC_REGISTER_ENABLED = False
# None or [] values in USER_EMAIL_ALLOWED_DOMAINS means allow any domain
USER_EMAIL_ALLOWED_DOMAINS = None
SEARCHES_MAX_RESULTS = 150
SOUTH_MIGRATION_MODULES = {
'easy_thumbnails': 'easy_thumbnails.south_migrations',
}
THN_AVATAR_SIZE = 80 # 80x80 pixels
THN_AVATAR_BIG_SIZE = 300 # 300x300 pixels
THN_LOGO_SMALL_SIZE = 80 # 80x80 pixels
THN_LOGO_BIG_SIZE = 300 # 300x300 pixels
THN_TIMELINE_IMAGE_SIZE = 640 # 640x??? pixels
THN_CARD_IMAGE_WIDTH = 300 # 300 pixels
THN_CARD_IMAGE_HEIGHT = 200 # 200 pixels
THN_AVATAR_SMALL = "avatar"
THN_AVATAR_BIG = "big-avatar"
THN_LOGO_SMALL = "logo-small"
THN_LOGO_BIG = "logo-big"
THN_ATTACHMENT_TIMELINE = "timeline-image"
THN_ATTACHMENT_CARD = "card-image"
THUMBNAIL_ALIASES = {
"": {
THN_AVATAR_SMALL: {"size": (THN_AVATAR_SIZE, THN_AVATAR_SIZE), "crop": True},
THN_AVATAR_BIG: {"size": (THN_AVATAR_BIG_SIZE, THN_AVATAR_BIG_SIZE), "crop": True},
THN_LOGO_SMALL: {"size": (THN_LOGO_SMALL_SIZE, THN_LOGO_SMALL_SIZE), "crop": True},
THN_LOGO_BIG: {"size": (THN_LOGO_BIG_SIZE, THN_LOGO_BIG_SIZE), "crop": True},
THN_ATTACHMENT_TIMELINE: {"size": (THN_TIMELINE_IMAGE_SIZE, 0), "crop": True},
THN_ATTACHMENT_CARD: {"size": (THN_CARD_IMAGE_WIDTH, THN_CARD_IMAGE_HEIGHT), "crop": True},
},
}
TAGS_PREDEFINED_COLORS = ["#fce94f", "#edd400", "#c4a000", "#8ae234",
"#73d216", "#4e9a06", "#d3d7cf", "#fcaf3e",
"#f57900", "#ce5c00", "#729fcf", "#3465a4",
"#204a87", "#888a85", "#ad7fa8", "#75507b",
"#5c3566", "#ef2929", "#cc0000", "#a40000",
"#2e3436",]
# Feedback module settings
FEEDBACK_ENABLED = True
FEEDBACK_EMAIL = "support@taiga.io"
# Stats module settings
STATS_ENABLED = False
STATS_CACHE_TIMEOUT = 60*60 # In second
# 0 notifications will work in a synchronous way
# >0 an external process will check the pending notifications and will send them
# collapsed during that interval
CHANGE_NOTIFICATIONS_MIN_INTERVAL = 0 #seconds
# List of functions called for filling correctly the ProjectModulesConfig associated to a project
# This functions should receive a Project parameter and return a dict with the desired configuration
PROJECT_MODULES_CONFIGURATORS = {
"github": "taiga.hooks.github.services.get_or_generate_config",
"gitlab": "taiga.hooks.gitlab.services.get_or_generate_config",
"bitbucket": "taiga.hooks.bitbucket.services.get_or_generate_config",
"gogs": "taiga.hooks.gogs.services.get_or_generate_config",
}
BITBUCKET_VALID_ORIGIN_IPS = ["131.103.20.165", "131.103.20.166", "104.192.143.192/28", "104.192.143.208/28"]
GITLAB_VALID_ORIGIN_IPS = []
EXPORTS_TTL = 60 * 60 * 24 # 24 hours
CELERY_ENABLED = False
WEBHOOKS_ENABLED = False
# If is True /front/sitemap.xml show a valid sitemap of taiga-front client
FRONT_SITEMAP_ENABLED = False
FRONT_SITEMAP_CACHE_TIMEOUT = 24*60*60 # In second
EXTRA_BLOCKING_CODES = []
MAX_PRIVATE_PROJECTS_PER_USER = None # None == no limit
MAX_PUBLIC_PROJECTS_PER_USER = None # None == no limit
MAX_MEMBERSHIPS_PRIVATE_PROJECTS = None # None == no limit
MAX_MEMBERSHIPS_PUBLIC_PROJECTS = None # None == no limit
MAX_PENDING_MEMBERSHIPS = 30 # Max number of unconfirmed memberships in a project
from .sr import *
# NOTE: DON'T INSERT MORE SETTINGS AFTER THIS LINE
TEST_RUNNER="django.test.runner.DiscoverRunner"
if "test" in sys.argv:
print ("\033[1;91mNo django tests.\033[0m")
print ("Try: \033[1;33mpy.test\033[0m")
sys.exit(0)
| 31.632058 | 109 | 0.620293 |
import os.path, sys, os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
APPEND_SLASH = False
ALLOWED_HOSTS = ["*"]
ADMINS = (
("Admin", "example@example.com"),
)
DEBUG = False
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "taiga",
}
}
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "unique-snowflake"
}
}
PASSWORD_HASHERS = [
"django.contrib.auth.hashers.PBKDF2PasswordHasher",
]
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTOCOL", "https")
SEND_BROKEN_LINK_EMAILS = True
IGNORABLE_404_ENDS = (".php", ".cgi")
IGNORABLE_404_STARTS = ("/phpmyadmin/",)
ATOMIC_REQUESTS = True
TIME_ZONE = "UTC"
LOGIN_URL="/auth/login/"
USE_TZ = True
USE_I18N = True
USE_L10N = True
LANGUAGE_CODE = 'en-us'
LANGUAGES = [
"English (US)"),
AGES_BIDI = ["he", "ar", "fa", "ur"]
LOCALE_PATHS = (
os.path.join(BASE_DIR, "locale"),
os.path.join(BASE_DIR, "taiga", "locale"),
)
SITES = {
"api": {"domain": "localhost:8000", "scheme": "http", "name": "api"},
"front": {"domain": "localhost:9001", "scheme": "http", "name": "front"},
}
SITE_ID = "api"
SESSION_ENGINE = "django.contrib.sessions.backends.db"
SESSION_COOKIE_AGE = 1209600
DEFAULT_FROM_EMAIL = "john@doe.com"
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
DJMAIL_REAL_BACKEND = "django.core.mail.backends.console.EmailBackend"
DJMAIL_SEND_ASYNC = True
DJMAIL_MAX_RETRY_NUMBER = 3
DJMAIL_TEMPLATE_EXTENSION = "jinja"
EVENTS_PUSH_BACKEND = "taiga.events.backends.postgresql.EventsPushBackend"
MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"
MEDIA_URL = "http://localhost:8000/media/"
STATIC_URL = "http://localhost:8000/static/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
STATICFILES_DIRS = (
)
# Defautl storage
DEFAULT_FILE_STORAGE = "taiga.base.storage.FileSystemStorage"
SECRET_KEY = "aw3+t2r(8(0kkrhg8)gx6i96v5^kv%6cfep9wxfom0%7dy0m9e"
TEMPLATES = [
{
"BACKEND": "django_jinja.backend.Jinja2",
"DIRS": [
os.path.join(BASE_DIR, "templates"),
],
"APP_DIRS": True,
"OPTIONS": {
'context_processors': [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.request",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
"match_extension": ".jinja",
}
},
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
os.path.join(BASE_DIR, "templates"),
],
"APP_DIRS": True,
"OPTIONS": {
'context_processors': [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.request",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
],
}
},
]
MIDDLEWARE_CLASSES = [
"taiga.base.middleware.cors.CoorsMiddleware",
"taiga.events.middleware.SessionIDMiddleware",
# Common middlewares
"django.middleware.common.CommonMiddleware",
"django.middleware.locale.LocaleMiddleware",
# Only needed by django admin
"django.contrib.sessions.middleware.SessionMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
]
ROOT_URLCONF = "taiga.urls"
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.admin",
"django.contrib.staticfiles",
"django.contrib.sitemaps",
"taiga.base",
"taiga.base.api",
"taiga.locale",
"taiga.events",
"taiga.front",
"taiga.users",
"taiga.userstorage",
"taiga.external_apps",
"taiga.projects",
"taiga.projects.references",
"taiga.projects.custom_attributes",
"taiga.projects.history",
"taiga.projects.notifications",
"taiga.projects.attachments",
"taiga.projects.likes",
"taiga.projects.votes",
"taiga.projects.milestones",
"taiga.projects.epics",
"taiga.projects.userstories",
"taiga.projects.tasks",
"taiga.projects.issues",
"taiga.projects.wiki",
"taiga.searches",
"taiga.timeline",
"taiga.mdrender",
"taiga.export_import",
"taiga.feedback",
"taiga.stats",
"taiga.hooks.github",
"taiga.hooks.gitlab",
"taiga.hooks.bitbucket",
"taiga.hooks.gogs",
"taiga.webhooks",
"djmail",
"django_jinja",
"django_jinja.contrib._humanize",
"sr",
"easy_thumbnails",
"raven.contrib.django.raven_compat",
]
WSGI_APPLICATION = "taiga.wsgi.application"
LOGGING = {
"version": 1,
"disable_existing_loggers": True,
"filters": {
"require_debug_false": {
"()": "django.utils.log.RequireDebugFalse"
}
},
"formatters": {
"complete": {
"format": "%(levelname)s:%(asctime)s:%(module)s %(message)s"
},
"simple": {
"format": "%(levelname)s:%(asctime)s: %(message)s"
},
"null": {
"format": "%(message)s",
},
},
"handlers": {
"null": {
"level":"DEBUG",
"class":"logging.NullHandler",
},
"console":{
"level":"DEBUG",
"class":"logging.StreamHandler",
"formatter": "simple",
},
"mail_admins": {
"level": "ERROR",
"filters": ["require_debug_false"],
"class": "django.utils.log.AdminEmailHandler",
}
},
"loggers": {
"django": {
"handlers":["null"],
"propagate": True,
"level":"INFO",
},
"django.request": {
"handlers": ["mail_admins", "console"],
"level": "ERROR",
"propagate": False,
},
"taiga.export_import": {
"handlers": ["mail_admins", "console"],
"level": "ERROR",
"propagate": False,
},
"taiga": {
"handlers": ["console"],
"level": "DEBUG",
"propagate": False,
}
}
}
AUTH_USER_MODEL = "users.User"
FORMAT_MODULE_PATH = "taiga.base.formats"
DATE_INPUT_FORMATS = (
"%Y-%m-%d", "%m/%d/%Y", "%d/%m/%Y", "%b %d %Y",
"%b %d, %Y", "%d %b %Y", "%d %b, %Y", "%B %d %Y",
"%B %d, %Y", "%d %B %Y", "%d %B, %Y"
)
# Authentication settings (only for django admin)
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend", # default
)
MAX_AGE_AUTH_TOKEN = None
MAX_AGE_CANCEL_ACCOUNT = 30 * 24 * 60 * 60 # 30 days in seconds
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
# Mainly used by taiga-front
"taiga.auth.backends.Token",
# Mainly used for api debug.
"taiga.auth.backends.Session",
# Application tokens auth
"taiga.external_apps.auth_backends.Token",
),
"DEFAULT_THROTTLE_CLASSES": (
"taiga.base.throttling.AnonRateThrottle",
"taiga.base.throttling.UserRateThrottle"
),
"DEFAULT_THROTTLE_RATES": {
"anon": None,
"user": None,
"import-mode": None,
"import-dump-mode": "1/minute",
"create-memberships": None
},
"FILTER_BACKEND": "taiga.base.filters.FilterBackend",
"EXCEPTION_HANDLER": "taiga.base.exceptions.exception_handler",
"PAGINATE_BY": 30,
"PAGINATE_BY_PARAM": "page_size",
"MAX_PAGINATE_BY": 1000,
"DATETIME_FORMAT": "%Y-%m-%dT%H:%M:%S%z"
}
# Extra expose header related to Taiga APP (see taiga.base.middleware.cors=)
APP_EXTRA_EXPOSE_HEADERS = [
"taiga-info-total-opened-milestones",
"taiga-info-total-closed-milestones",
"taiga-info-project-memberships",
"taiga-info-project-is-private",
"taiga-info-order-updated"
]
DEFAULT_PROJECT_TEMPLATE = "scrum"
PUBLIC_REGISTER_ENABLED = False
# None or [] values in USER_EMAIL_ALLOWED_DOMAINS means allow any domain
USER_EMAIL_ALLOWED_DOMAINS = None
SEARCHES_MAX_RESULTS = 150
SOUTH_MIGRATION_MODULES = {
'easy_thumbnails': 'easy_thumbnails.south_migrations',
}
THN_AVATAR_SIZE = 80 # 80x80 pixels
THN_AVATAR_BIG_SIZE = 300 # 300x300 pixels
THN_LOGO_SMALL_SIZE = 80 # 80x80 pixels
THN_LOGO_BIG_SIZE = 300 # 300x300 pixels
THN_TIMELINE_IMAGE_SIZE = 640 # 640x??? pixels
THN_CARD_IMAGE_WIDTH = 300 # 300 pixels
THN_CARD_IMAGE_HEIGHT = 200 # 200 pixels
THN_AVATAR_SMALL = "avatar"
THN_AVATAR_BIG = "big-avatar"
THN_LOGO_SMALL = "logo-small"
THN_LOGO_BIG = "logo-big"
THN_ATTACHMENT_TIMELINE = "timeline-image"
THN_ATTACHMENT_CARD = "card-image"
THUMBNAIL_ALIASES = {
"": {
THN_AVATAR_SMALL: {"size": (THN_AVATAR_SIZE, THN_AVATAR_SIZE), "crop": True},
THN_AVATAR_BIG: {"size": (THN_AVATAR_BIG_SIZE, THN_AVATAR_BIG_SIZE), "crop": True},
THN_LOGO_SMALL: {"size": (THN_LOGO_SMALL_SIZE, THN_LOGO_SMALL_SIZE), "crop": True},
THN_LOGO_BIG: {"size": (THN_LOGO_BIG_SIZE, THN_LOGO_BIG_SIZE), "crop": True},
THN_ATTACHMENT_TIMELINE: {"size": (THN_TIMELINE_IMAGE_SIZE, 0), "crop": True},
THN_ATTACHMENT_CARD: {"size": (THN_CARD_IMAGE_WIDTH, THN_CARD_IMAGE_HEIGHT), "crop": True},
},
}
TAGS_PREDEFINED_COLORS = ["#fce94f", "#edd400", "#c4a000", "#8ae234",
"#73d216", "#4e9a06", "#d3d7cf", "#fcaf3e",
"#f57900", "#ce5c00", "#729fcf", "#3465a4",
"#204a87", "#888a85", "#ad7fa8", "#75507b",
"#5c3566", "#ef2929", "#cc0000", "#a40000",
"#2e3436",]
# Feedback module settings
FEEDBACK_ENABLED = True
FEEDBACK_EMAIL = "support@taiga.io"
# Stats module settings
STATS_ENABLED = False
STATS_CACHE_TIMEOUT = 60*60 # In second
# 0 notifications will work in a synchronous way
# >0 an external process will check the pending notifications and will send them
# collapsed during that interval
CHANGE_NOTIFICATIONS_MIN_INTERVAL = 0 #seconds
# List of functions called for filling correctly the ProjectModulesConfig associated to a project
# This functions should receive a Project parameter and return a dict with the desired configuration
PROJECT_MODULES_CONFIGURATORS = {
"github": "taiga.hooks.github.services.get_or_generate_config",
"gitlab": "taiga.hooks.gitlab.services.get_or_generate_config",
"bitbucket": "taiga.hooks.bitbucket.services.get_or_generate_config",
"gogs": "taiga.hooks.gogs.services.get_or_generate_config",
}
BITBUCKET_VALID_ORIGIN_IPS = ["131.103.20.165", "131.103.20.166", "104.192.143.192/28", "104.192.143.208/28"]
GITLAB_VALID_ORIGIN_IPS = []
EXPORTS_TTL = 60 * 60 * 24 # 24 hours
CELERY_ENABLED = False
WEBHOOKS_ENABLED = False
# If is True /front/sitemap.xml show a valid sitemap of taiga-front client
FRONT_SITEMAP_ENABLED = False
FRONT_SITEMAP_CACHE_TIMEOUT = 24*60*60 # In second
EXTRA_BLOCKING_CODES = []
MAX_PRIVATE_PROJECTS_PER_USER = None # None == no limit
MAX_PUBLIC_PROJECTS_PER_USER = None # None == no limit
MAX_MEMBERSHIPS_PRIVATE_PROJECTS = None # None == no limit
MAX_MEMBERSHIPS_PUBLIC_PROJECTS = None # None == no limit
MAX_PENDING_MEMBERSHIPS = 30 # Max number of unconfirmed memberships in a project
from .sr import *
# NOTE: DON'T INSERT MORE SETTINGS AFTER THIS LINE
TEST_RUNNER="django.test.runner.DiscoverRunner"
if "test" in sys.argv:
print ("\033[1;91mNo django tests.\033[0m")
print ("Try: \033[1;33mpy.test\033[0m")
sys.exit(0)
| true | true |
f72c3524f818483a439794d6f178598c2f531f0c | 773 | py | Python | models/product.py | KennyLingineni/MiniAmazon | 95c72d3693466ca2265d0e13f2cb172e1a98c260 | [
"Unlicense"
] | null | null | null | models/product.py | KennyLingineni/MiniAmazon | 95c72d3693466ca2265d0e13f2cb172e1a98c260 | [
"Unlicense"
] | null | null | null | models/product.py | KennyLingineni/MiniAmazon | 95c72d3693466ca2265d0e13f2cb172e1a98c260 | [
"Unlicense"
] | null | null | null | from MiniAmazon.models import db
def search_by_name(query):
#Search for the product here
db_query = {'name': query}
matchingproducts = db['products'].find(db_query) # Products is the table/collection. It returns a cursor(pointer).Cursor is a type of Generator.
if matchingproducts:
return list(matchingproducts) # make sure you convert the cursor to list before you send
else:
return []
def add_product(producttobeadded):
#Add the Product Here
db['products'].insert_one(producttobeadded)
def update_product(productnametobeupdated, updated_product):
filter={'name': productnametobeupdated}
update = {
'$set': updated_product
}
# update in DB
db['products'].update_one(filter=filter, update=update) | 33.608696 | 149 | 0.711514 | from MiniAmazon.models import db
def search_by_name(query):
db_query = {'name': query}
matchingproducts = db['products'].find(db_query)
if matchingproducts:
return list(matchingproducts)
else:
return []
def add_product(producttobeadded):
db['products'].insert_one(producttobeadded)
def update_product(productnametobeupdated, updated_product):
filter={'name': productnametobeupdated}
update = {
'$set': updated_product
}
db['products'].update_one(filter=filter, update=update) | true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.