code
stringlengths
22
1.05M
apis
listlengths
1
3.31k
extract_api
stringlengths
75
3.25M
from bokeh.models.sources import ColumnDataSource from bokeh.transform import cumsum from functools import partial from typing import List, Type from jira_analysis.chart.base import Axis, IChart, Chart from jira_analysis.defect_rate.issue import Issue from .plot.donut import DefectRateDonut def generate_defect_chart( issues: List[Issue], chart_class: Type[IChart] = Chart ) -> None: chart = chart_class( label=None, x=Axis(label="", values=None, size=600), y=Axis(label="", values=None, size=300), tooltips="@value: @defect_rate{0.1f}%", ) DefectRateDonut( issues=issues, data_source=ColumnDataSource, no_defects_transform=partial(cumsum, include_zero=True), defects_transform=cumsum, ).draw(chart) chart.render()
[ "functools.partial", "jira_analysis.chart.base.Axis" ]
[((447, 484), 'jira_analysis.chart.base.Axis', 'Axis', ([], {'label': '""""""', 'values': 'None', 'size': '(600)'}), "(label='', values=None, size=600)\n", (451, 484), False, 'from jira_analysis.chart.base import Axis, IChart, Chart\n'), ((496, 533), 'jira_analysis.chart.base.Axis', 'Axis', ([], {'label': '""""""', 'values': 'None', 'size': '(300)'}), "(label='', values=None, size=300)\n", (500, 533), False, 'from jira_analysis.chart.base import Axis, IChart, Chart\n'), ((700, 734), 'functools.partial', 'partial', (['cumsum'], {'include_zero': '(True)'}), '(cumsum, include_zero=True)\n', (707, 734), False, 'from functools import partial\n')]
import datetime from typing import Any, Dict, List, Type, TypeVar, Union import attr from dateutil.parser import isoparse from ..models.email_model_object import EmailModelObject from ..models.email_model_sev_client import EmailModelSevClient from ..types import UNSET, Unset T = TypeVar("T", bound="EmailModel") @attr.s(auto_attribs=True) class EmailModel: """Email model Attributes: from_ (str): The sender of the email to (str): The recipient of the email subject (str): The subject of the email id (Union[Unset, int]): The email id object_name (Union[Unset, str]): The email object name create (Union[Unset, datetime.datetime]): Date of mail creation update (Union[Unset, datetime.datetime]): Date of last mail update object_ (Union[Unset, None, EmailModelObject]): The contact used in the document text (Union[Unset, None, str]): The text of the email sev_client (Union[Unset, EmailModelSevClient]): Client to which mail belongs. Will be filled automatically cc (Union[Unset, None, str]): A list of mail addresses which are in the cc bcc (Union[Unset, None, str]): A list of mail addresses which are in the bcc arrived (Union[Unset, None, datetime.datetime]): Date the mail arrived """ from_: str to: str subject: str id: Union[Unset, int] = UNSET object_name: Union[Unset, str] = UNSET create: Union[Unset, datetime.datetime] = UNSET update: Union[Unset, datetime.datetime] = UNSET object_: Union[Unset, None, EmailModelObject] = UNSET text: Union[Unset, None, str] = UNSET sev_client: Union[Unset, EmailModelSevClient] = UNSET cc: Union[Unset, None, str] = UNSET bcc: Union[Unset, None, str] = UNSET arrived: Union[Unset, None, datetime.datetime] = UNSET additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict) def to_dict(self) -> Dict[str, Any]: from_ = self.from_ to = self.to subject = self.subject id = self.id object_name = self.object_name create: Union[Unset, str] = UNSET if not isinstance(self.create, Unset): create = self.create.isoformat() update: Union[Unset, str] = UNSET if not isinstance(self.update, Unset): update = self.update.isoformat() object_: Union[Unset, None, Dict[str, Any]] = UNSET if not isinstance(self.object_, Unset): object_ = self.object_.to_dict() if self.object_ else None text = self.text sev_client: Union[Unset, Dict[str, Any]] = UNSET if not isinstance(self.sev_client, Unset): sev_client = self.sev_client.to_dict() cc = self.cc bcc = self.bcc arrived: Union[Unset, None, str] = UNSET if not isinstance(self.arrived, Unset): arrived = self.arrived.isoformat() if self.arrived else None field_dict: Dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( { "from": from_, "to": to, "subject": subject, } ) if id is not UNSET: field_dict["id"] = id if object_name is not UNSET: field_dict["objectName"] = object_name if create is not UNSET: field_dict["create"] = create if update is not UNSET: field_dict["update"] = update if object_ is not UNSET: field_dict["object"] = object_ if text is not UNSET: field_dict["text"] = text if sev_client is not UNSET: field_dict["sevClient"] = sev_client if cc is not UNSET: field_dict["cc"] = cc if bcc is not UNSET: field_dict["bcc"] = bcc if arrived is not UNSET: field_dict["arrived"] = arrived return field_dict @classmethod def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: d = src_dict.copy() from_ = d.pop("from") to = d.pop("to") subject = d.pop("subject") id = d.pop("id", UNSET) object_name = d.pop("objectName", UNSET) _create = d.pop("create", UNSET) create: Union[Unset, datetime.datetime] if isinstance(_create, Unset): create = UNSET else: create = isoparse(_create) _update = d.pop("update", UNSET) update: Union[Unset, datetime.datetime] if isinstance(_update, Unset): update = UNSET else: update = isoparse(_update) _object_ = d.pop("object", UNSET) object_: Union[Unset, None, EmailModelObject] if _object_ is None: object_ = None elif isinstance(_object_, Unset): object_ = UNSET else: object_ = EmailModelObject.from_dict(_object_) text = d.pop("text", UNSET) _sev_client = d.pop("sevClient", UNSET) sev_client: Union[Unset, EmailModelSevClient] if isinstance(_sev_client, Unset): sev_client = UNSET else: sev_client = EmailModelSevClient.from_dict(_sev_client) cc = d.pop("cc", UNSET) bcc = d.pop("bcc", UNSET) _arrived = d.pop("arrived", UNSET) arrived: Union[Unset, None, datetime.datetime] if _arrived is None: arrived = None elif isinstance(_arrived, Unset): arrived = UNSET else: arrived = isoparse(_arrived) email_model = cls( from_=from_, to=to, subject=subject, id=id, object_name=object_name, create=create, update=update, object_=object_, text=text, sev_client=sev_client, cc=cc, bcc=bcc, arrived=arrived, ) email_model.additional_properties = d return email_model @property def additional_keys(self) -> List[str]: return list(self.additional_properties.keys()) def __getitem__(self, key: str) -> Any: return self.additional_properties[key] def __setitem__(self, key: str, value: Any) -> None: self.additional_properties[key] = value def __delitem__(self, key: str) -> None: del self.additional_properties[key] def __contains__(self, key: str) -> bool: return key in self.additional_properties
[ "attr.s", "attr.ib", "dateutil.parser.isoparse", "typing.TypeVar" ]
[((283, 315), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {'bound': '"""EmailModel"""'}), "('T', bound='EmailModel')\n", (290, 315), False, 'from typing import Any, Dict, List, Type, TypeVar, Union\n'), ((319, 344), 'attr.s', 'attr.s', ([], {'auto_attribs': '(True)'}), '(auto_attribs=True)\n', (325, 344), False, 'import attr\n'), ((1881, 1914), 'attr.ib', 'attr.ib', ([], {'init': '(False)', 'factory': 'dict'}), '(init=False, factory=dict)\n', (1888, 1914), False, 'import attr\n'), ((4432, 4449), 'dateutil.parser.isoparse', 'isoparse', (['_create'], {}), '(_create)\n', (4440, 4449), False, 'from dateutil.parser import isoparse\n'), ((4641, 4658), 'dateutil.parser.isoparse', 'isoparse', (['_update'], {}), '(_update)\n', (4649, 4658), False, 'from dateutil.parser import isoparse\n'), ((5580, 5598), 'dateutil.parser.isoparse', 'isoparse', (['_arrived'], {}), '(_arrived)\n', (5588, 5598), False, 'from dateutil.parser import isoparse\n')]
import numpy as np import torch def swav_loss_func(preds, assignments, temperature): losses = [] for v1 in range(len(preds)): for v2 in np.delete(np.arange(len(preds)), v1): a = assignments[v1] p = preds[v2] / temperature loss = -torch.mean(torch.sum(a * torch.log_softmax(p, dim=1), dim=1)) losses.append(loss) return sum(losses) / len(losses)
[ "torch.log_softmax" ]
[((309, 336), 'torch.log_softmax', 'torch.log_softmax', (['p'], {'dim': '(1)'}), '(p, dim=1)\n', (326, 336), False, 'import torch\n')]
import soundfile as sf import torch import torch.nn.functional as F from fairseq.data import Dictionary from bol.utils.helper_functions import move_to_cuda def get_feature(filepath): def postprocess(feats, sample_rate): if feats.dim == 2: feats = feats.mean(-1) assert feats.dim() == 1, feats.dim() with torch.no_grad(): feats = F.layer_norm(feats, feats.shape) return feats wav, sample_rate = sf.read(filepath) feats = torch.from_numpy(wav).float() feats = postprocess(feats, sample_rate) return feats def post_process(sentence: str, symbol: str): if symbol == "sentencepiece": sentence = sentence.replace(" ", "").replace("\u2581", " ").strip() elif symbol == "wordpiece": sentence = sentence.replace(" ", "").replace("_", " ").strip() elif symbol == "letter": sentence = sentence.replace(" ", "").replace("|", " ").strip() elif symbol == "_EOW": sentence = sentence.replace(" ", "").replace("_EOW", " ").strip() elif symbol is not None and symbol != "none": sentence = (sentence + " ").replace(symbol, "").rstrip() return sentence def get_results_for_single_file( wav_path, dict_path, generator, model, use_cuda=False, half=None ): sample = dict() net_input = dict() target_dict = Dictionary.load(dict_path) feature = get_feature(wav_path) model.eval() if half: net_input["source"] = feature.unsqueeze(0).half() else: net_input["source"] = feature.unsqueeze(0) padding_mask = ( torch.BoolTensor(net_input["source"].size(1)).fill_(False).unsqueeze(0) ) net_input["padding_mask"] = padding_mask sample["net_input"] = net_input sample = move_to_cuda(sample) if use_cuda else sample with torch.no_grad(): hypo = generator.generate(model, sample, prefix_tokens=None) hyp_pieces = target_dict.string(hypo[0][0]["tokens"].int().cpu()) text = post_process(hyp_pieces, "letter") return text
[ "torch.nn.functional.layer_norm", "fairseq.data.Dictionary.load", "bol.utils.helper_functions.move_to_cuda", "torch.from_numpy", "torch.no_grad", "soundfile.read" ]
[((464, 481), 'soundfile.read', 'sf.read', (['filepath'], {}), '(filepath)\n', (471, 481), True, 'import soundfile as sf\n'), ((1350, 1376), 'fairseq.data.Dictionary.load', 'Dictionary.load', (['dict_path'], {}), '(dict_path)\n', (1365, 1376), False, 'from fairseq.data import Dictionary\n'), ((1766, 1786), 'bol.utils.helper_functions.move_to_cuda', 'move_to_cuda', (['sample'], {}), '(sample)\n', (1778, 1786), False, 'from bol.utils.helper_functions import move_to_cuda\n'), ((1821, 1836), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1834, 1836), False, 'import torch\n'), ((349, 364), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (362, 364), False, 'import torch\n'), ((386, 418), 'torch.nn.functional.layer_norm', 'F.layer_norm', (['feats', 'feats.shape'], {}), '(feats, feats.shape)\n', (398, 418), True, 'import torch.nn.functional as F\n'), ((494, 515), 'torch.from_numpy', 'torch.from_numpy', (['wav'], {}), '(wav)\n', (510, 515), False, 'import torch\n')]
import tkinter as tk from gameworld03 import World if __name__ == "__main__": root = tk.Tk() root.title("Hello, Pong!") world = World(root) world.mainloop()
[ "gameworld03.World", "tkinter.Tk" ]
[((90, 97), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (95, 97), True, 'import tkinter as tk\n'), ((141, 152), 'gameworld03.World', 'World', (['root'], {}), '(root)\n', (146, 152), False, 'from gameworld03 import World\n')]
import requests import os import sys import inspect def start(): print(""" ░██╗░░░░░░░██╗███████╗██████╗░██╗███╗░░██╗░██████╗██████╗░███████╗░█████╗░████████╗ ░██║░░██╗░░██║██╔════╝██╔══██╗██║████╗░██║██╔════╝██╔══██╗██╔════╝██╔══██╗╚══██╔══╝ ░╚██╗████╗██╔╝█████╗░░██████╦╝██║██╔██╗██║╚█████╗░██████╔╝█████╗░░██║░░╚═╝░░░██║░░░ ░░████╔═████║░██╔══╝░░██╔══██╗██║██║╚████║░╚═══██╗██╔═══╝░██╔══╝░░██║░░██╗░░░██║░░░ ░░╚██╔╝░╚██╔╝░███████╗██████╦╝██║██║░╚███║██████╔╝██║░░░░░███████╗╚█████╔╝░░░██║░░░ ░░░╚═╝░░░╚═╝░░╚══════╝╚═════╝░╚═╝╚═╝░░╚══╝╚═════╝░╚═╝░░░░░╚══════╝░╚════╝░░░░╚═╝░░░ """) print("") print("WEBINSPECT Framework 2.0") start() def getHTMLCODE(): website = input(str("Enter the website: ")) if "http://" not in website and "https://" not in website: website = 'http://' + website r = requests.get(website) print(r.text) def getANDDOWNLOADIMAGE(): website = input(str("Enter the picture link: ")) filename = input(str("Enter the image name that you want for it to be: ")) r = requests.get(website) with open(filename, 'wb') as f: f.write(r.content) def getRequest(): website = input(str("Enter the website: ")) if "http://" not in website and "https://" not in website: website = 'http://' + website r = requests.get(website) print(r) def getWEBSITEHEADERS(): website = input(str("Enter the website: ")) if "http://" not in website and "https://" not in website: website = 'http://' + website r = requests.get(website) print(r.headers) def getWEBSITEOKINFOR(): website = input(str("Enter the website: ")) if "http://" not in website and "https://" not in website: website = 'http://' + website r = requests.get(website) print(r.ok) def getWEBSITECOOKIES(): website = input(str("Enter the website: ")) if "http://" not in website and "https://" not in website: website = 'http://' + website r = requests.get(website) print(r.cookies) def getWEBSITEURL(): website = input(str("Enter the website: ")) if "http://" not in website and "https://" not in website: website = 'http://' + website r = requests.get(website) print(r.url) def sendREQUEST(): website = input(str("Enter the website: ")) username = input(str("Enter the username that you want to try: ")) password = input(str("Enter the password that you want to try: ")) payload = {'username': username, 'password': password} try: r = requests.post(website, data=payload) print(r.text) except: print("Failed to send request...") def getWEBSITEJSON(): website = input(str("Enter the website: ")) if "http://" not in website and "https://" not in website: website = 'http://' + website r = requests.get(website) print(r.json) def getWEBSITESRESPONSE(): website = input(str("Enter the website: ")) if "http://" not in website and "https://" not in website: website = 'http://' + website r = requests.get(website) print(r) print(""" Select a payload. [1]: Get html code [2]: Download images [3]: Get request [4]: Get website headers [5]: Check if the website is ok [6]: Get the websites cookies [7]: Gets the websites url [8]: Send request (Doesn't always work) [9]: Get the websites json [10]: Get websites response """) type = input(str("")) if type == "1": getHTMLCODE() elif type == "2": getANDDOWNLOADIMAGE() elif type == "3": getRequest() elif type == "4": getWEBSITEHEADERS() elif type == "5": getWEBSITEOKINFOR() elif type == "6": getWEBSITECOOKIES() elif type == "7": getWEBSITEURL() elif type == "8": sendREQUEST() elif type == "9": getWEBSITEJSON() elif type == "10": getWEBSITESRESPONSE() else: print("Invalid type")
[ "requests.post", "requests.get" ]
[((837, 858), 'requests.get', 'requests.get', (['website'], {}), '(website)\n', (849, 858), False, 'import requests\n'), ((1045, 1066), 'requests.get', 'requests.get', (['website'], {}), '(website)\n', (1057, 1066), False, 'import requests\n'), ((1305, 1326), 'requests.get', 'requests.get', (['website'], {}), '(website)\n', (1317, 1326), False, 'import requests\n'), ((1522, 1543), 'requests.get', 'requests.get', (['website'], {}), '(website)\n', (1534, 1543), False, 'import requests\n'), ((1747, 1768), 'requests.get', 'requests.get', (['website'], {}), '(website)\n', (1759, 1768), False, 'import requests\n'), ((1967, 1988), 'requests.get', 'requests.get', (['website'], {}), '(website)\n', (1979, 1988), False, 'import requests\n'), ((2188, 2209), 'requests.get', 'requests.get', (['website'], {}), '(website)\n', (2200, 2209), False, 'import requests\n'), ((2809, 2830), 'requests.get', 'requests.get', (['website'], {}), '(website)\n', (2821, 2830), False, 'import requests\n'), ((3033, 3054), 'requests.get', 'requests.get', (['website'], {}), '(website)\n', (3045, 3054), False, 'import requests\n'), ((2516, 2552), 'requests.post', 'requests.post', (['website'], {'data': 'payload'}), '(website, data=payload)\n', (2529, 2552), False, 'import requests\n')]
from random import choice from flask import Flask, redirect app = Flask(__name__) words = { "1": "One Direction", "2": "Dr Who", "3": "Cup of herbal tea", "4": "Knock at the door", "5": "Johnny's Alive", "6": "Little Mix", "7": "<NAME>", "8": "Golden Gate", "9": "Selfie Time", "10": "Boris’ den", "11": "Stranger Things", "12": "Dirty dozen", "13": "Unlucky for some", "14": "Valentine’s Day", "15": "Your claim to fame", "16": "Sweet 16", "17": "Dancing Queen", "18": "Party on Tatooine", "19": "Time for Quarantine", "20": "Facemasks Aplenty", "21": "Vaccines are fun", "22": "Scooby Doo and Scrappy too", "23": "The Bees Knees", "24": "It's Dumbledore", "25": "Dobbie Dies", "26": "She's had her Weetabix", "27": "Bridesmaid Dresses", "28": "Over Weight", "29": "Rise and Shine", "30": "Liz Lemon Rocks", "31": "<NAME>", "32": "<NAME>", "33": "Dirty knees", "34": "Murder on the Dance Floor", "35": "Jump and Jive", "36": "New Tricks", "37": "A Hobbits Tale", "38": "Magnum P.I.", "39": "Love Island Time", "40": "Hello Naughty", "41": "Time for Fun", "42": "Winnie the Pooh", "43": "Fish, Chips and Pea's", "44": "Scores on the Doors", "45": "Halfway there", "46": "Up to tricks", "47": "Four and seven", "48": "Tag a mate", "49": "Amazon Prime", "50": "Hawaii Five-O", "51": "Aliens!", "52": "Chicken Vindaloo", "53": "Stuck in a tree", "54": "Grannys Drawers", "55": "Snakes alive", "56": "Chill with Netflix", "57": "Heinz varieties", "58": "Make them wait", "59": "Tequila and Lime", "60": "Five dozen", "61": "Baker's bun", "62": "Turn the screw", "63": "OMG, they killed Kennedy", "64": "Will you still love me", "65": "Thunderbirds are Go", "66": "Jedi Tricks", "67": "Retirement Heaven", "68": "Cathrine Tate", "69": "Moonwalk Time", "70": "I'm holding out for a Hero", "71": "Fox on the run", "72": "Six dozen", "73": "Not the Bees!", "74": "Recycle More", "75": "What a time to be alive", "76": "Ripley Saves Hicks", "77": "Sunset strip", "78": "Haters Gunna Hate", "79": "One more time", "80": "Imagine!", "81": "Girls just wana have fun", "82": "Electric Boogaloo", "83": "Gluten Free", "84": "Ghostbusters", "85": "Staying alive", "86": "Instagram Pix", "87": "Walk like an Egyptian", "88": "<NAME>", "89": "<NAME>", "90": "<NAME>", } def init(): global previous_numbers global numbers previous_numbers = [] numbers = list(range(1, 91)) @app.route("/") def root(): try: previous_numbers return redirect("/play", code=302) except NameError: init() return redirect("/play", code=302) @app.route("/play") def play(): try: number = previous_numbers[-1] return f""" <html> <style> body {{ font-family: Helvetica, Arial, Sans-Serif; text-align: center; background-color: black; color: white; }} pre {{ white-space: pre-wrap; font-size: 25px; }} .number {{ font-size: 200px; }} .phrase {{ font-size: 50px; }} .button {{ border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; }} .next {{ background-color: #4CAF50; }} .reset {{ background-color: #f44336; }} </style> <body> <span class="number">{number}</span><br /> <span class="phrase">{words[str(number)]}</span><br /> <br /> <form action="/increment"> <input type="submit" class="button next" value="Next Number" /> </form> <p>Previous Numbers:</p> <pre>{' '.join(previous_numbers)}</pre> <br /> <br /> <form action="/reset"> <input type="submit" class="button reset" onclick="return confirm('Are you sure?')" value="Reset" /> </form> </body> </html> """ except IndexError: return redirect("/gameover", code=302) except NameError: return redirect("/", code=302) @app.route("/gameover") def gameover(): return f""" <html> <style> body {{ font-family: Helvetica, Arial, Sans-Serif; text-align: center; background-color: black; color: white; }} pre {{ white-space: pre-wrap; font-size: 50px; }} .gameover {{ font-size: 50px; }} .button {{ background-color: #f44336; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; }} </style> <body> <span class="gameover">Game over!!!</span><br /> <form action="/reset"> <input type="submit" class="button reset" value="Reset" /> </form> <p>Previous Numbers:</p> <pre>{' '.join(previous_numbers)}</pre> </body> </html> """ @app.route("/increment") def increment(): try: number = choice(numbers) previous_numbers.append(str(number)) numbers.remove(number) return redirect("/play", code=302) except IndexError: return redirect("/gameover", code=302) @app.route("/reset") def reset(): init() return redirect("/increment", code=302)
[ "flask.redirect", "random.choice", "flask.Flask" ]
[((67, 82), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (72, 82), False, 'from flask import Flask, redirect\n'), ((6600, 6632), 'flask.redirect', 'redirect', (['"""/increment"""'], {'code': '(302)'}), "('/increment', code=302)\n", (6608, 6632), False, 'from flask import Flask, redirect\n'), ((2814, 2841), 'flask.redirect', 'redirect', (['"""/play"""'], {'code': '(302)'}), "('/play', code=302)\n", (2822, 2841), False, 'from flask import Flask, redirect\n'), ((6337, 6352), 'random.choice', 'choice', (['numbers'], {}), '(numbers)\n', (6343, 6352), False, 'from random import choice\n'), ((6444, 6471), 'flask.redirect', 'redirect', (['"""/play"""'], {'code': '(302)'}), "('/play', code=302)\n", (6452, 6471), False, 'from flask import Flask, redirect\n'), ((2894, 2921), 'flask.redirect', 'redirect', (['"""/play"""'], {'code': '(302)'}), "('/play', code=302)\n", (2902, 2921), False, 'from flask import Flask, redirect\n'), ((4890, 4921), 'flask.redirect', 'redirect', (['"""/gameover"""'], {'code': '(302)'}), "('/gameover', code=302)\n", (4898, 4921), False, 'from flask import Flask, redirect\n'), ((4959, 4982), 'flask.redirect', 'redirect', (['"""/"""'], {'code': '(302)'}), "('/', code=302)\n", (4967, 4982), False, 'from flask import Flask, redirect\n'), ((6510, 6541), 'flask.redirect', 'redirect', (['"""/gameover"""'], {'code': '(302)'}), "('/gameover', code=302)\n", (6518, 6541), False, 'from flask import Flask, redirect\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import os from eatb.utils.datetime import ts_date from config.configuration import config_path_work from functools import wraps import logging def requires_parameters(*required_params): """ Decorator function to check if required parameters are available in the context object :param required_params: parameters tuple :raises: RuntimeError if required parameter is not available """ assert isinstance(required_params, tuple) def check_parameter(func): def func_wrapper(self, input): missing_params = [] if isinstance(input, dict) or (isinstance(input, str) and input.startswith("{")): for param in required_params: if param not in input: missing_params.append(param) if len(missing_params) > 0: raise ValueError("Missing parameters: %s" % ", ".join(missing_params)) return func(self, input) return func_wrapper return check_parameter def get_task_logger(func, ip_dir): """ Task logger (creates log file in information package directory) """ logfile = os.path.join(ip_dir, "processing.log") if not os.path.exists(logfile): logging.shutdown() logger = logging.getLogger("%s_%s" % (ip_dir, func.__name__)) extra = {'task_name': func.__name__} if len(logger.handlers) == 0: # Log to output file based on the function name hdlr = logging.FileHandler(logfile) formatter = logging.Formatter('%(asctime)s %(task_name)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) logger = logging.LoggerAdapter(logger, extra) return logger def task_logger(f): @wraps(f) def wrapper(*args, **kwds): task = args[0] task_input = args[1] if isinstance(task_input, str): context = json.loads(task_input) else: context = task_input process_id = context["process_id"] ip_dir = os.path.join(config_path_work, process_id) log_dir = ip_dir if not os.path.exists(log_dir): os.makedirs(log_dir, exist_ok=True) task_log = get_task_logger(f, ip_dir) kwds["task_log"] = task_log try: task_log.info("============ Task %s ============" % task.name) input_params = context for param, value in input_params.items(): task_log.debug("Input parameter '%s': %s" % (param, value)) result = f(*args, **kwds) result_params = json.loads(result) for param, value in result_params.items(): task_log.debug("Output parameter '%s': %s" % (param, value)) except Exception as ex: task_log.error("Exception {0}".format(ex)) raise ex return result return wrapper
[ "logging.getLogger", "os.path.exists", "json.loads", "os.makedirs", "logging.Formatter", "os.path.join", "functools.wraps", "logging.shutdown", "logging.FileHandler", "logging.LoggerAdapter" ]
[((1213, 1251), 'os.path.join', 'os.path.join', (['ip_dir', '"""processing.log"""'], {}), "(ip_dir, 'processing.log')\n", (1225, 1251), False, 'import os\n'), ((1329, 1381), 'logging.getLogger', 'logging.getLogger', (["('%s_%s' % (ip_dir, func.__name__))"], {}), "('%s_%s' % (ip_dir, func.__name__))\n", (1346, 1381), False, 'import logging\n'), ((1772, 1808), 'logging.LoggerAdapter', 'logging.LoggerAdapter', (['logger', 'extra'], {}), '(logger, extra)\n', (1793, 1808), False, 'import logging\n'), ((1854, 1862), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (1859, 1862), False, 'from functools import wraps\n'), ((1263, 1286), 'os.path.exists', 'os.path.exists', (['logfile'], {}), '(logfile)\n', (1277, 1286), False, 'import os\n'), ((1296, 1314), 'logging.shutdown', 'logging.shutdown', ([], {}), '()\n', (1312, 1314), False, 'import logging\n'), ((1530, 1558), 'logging.FileHandler', 'logging.FileHandler', (['logfile'], {}), '(logfile)\n', (1549, 1558), False, 'import logging\n'), ((1579, 1651), 'logging.Formatter', 'logging.Formatter', (['"""%(asctime)s %(task_name)s %(levelname)s %(message)s"""'], {}), "('%(asctime)s %(task_name)s %(levelname)s %(message)s')\n", (1596, 1651), False, 'import logging\n'), ((2139, 2181), 'os.path.join', 'os.path.join', (['config_path_work', 'process_id'], {}), '(config_path_work, process_id)\n', (2151, 2181), False, 'import os\n'), ((2009, 2031), 'json.loads', 'json.loads', (['task_input'], {}), '(task_input)\n', (2019, 2031), False, 'import json\n'), ((2222, 2245), 'os.path.exists', 'os.path.exists', (['log_dir'], {}), '(log_dir)\n', (2236, 2245), False, 'import os\n'), ((2259, 2294), 'os.makedirs', 'os.makedirs', (['log_dir'], {'exist_ok': '(True)'}), '(log_dir, exist_ok=True)\n', (2270, 2294), False, 'import os\n'), ((2696, 2714), 'json.loads', 'json.loads', (['result'], {}), '(result)\n', (2706, 2714), False, 'import json\n')]
from math import gcd import torch import torch.nn as nn import torch.nn.functional as F from model import common def make_model(args, parent=False): return RFDN(args) def generate_masks(num): masks = [] for i in range(num): now = list(range(2 ** num)) length = 2 ** (num - i) for j in range(2 ** i): tmp = now[j*length:j*length+length//2] now[j*length:j*length+length//2] = now[j*length+length//2:j*length+length] now[j*length+length//2:j*length+length] = tmp masks.append(now) return torch.tensor(masks) class ButterflyConv_v1(nn.Module): def __init__(self, in_channels, act, out_channels, dilation=1): super(ButterflyConv_v1, self).__init__() min_channels = min(in_channels, out_channels) assert (min_channels & (min_channels - 1)) == 0 # Is min_channels = 2^n? if in_channels == out_channels: self.head = nn.Identity() self.tail = nn.Identity() elif in_channels > out_channels: self.head = nn.Sequential( nn.Conv2d(in_channels, out_channels, 3, 1, dilation, dilation, groups=gcd(in_channels, out_channels)), act() ) self.tail = nn.Identity() elif in_channels < out_channels: self.head = nn.Identity() self.tail = nn.Sequential( nn.Conv2d(in_channels, out_channels, 3, 1, dilation, dilation, groups=gcd(in_channels, out_channels)), act() ) else: raise NotImplementedError("") self.num_butterflies = 0 for i in range(10000): if 2 ** i == min_channels: self.num_butterflies = i break self.masks = generate_masks(self.num_butterflies) self.conv_acts = [] for i in range(self.num_butterflies * 2): self.conv_acts.append( nn.Sequential(nn.Conv2d(min_channels, min_channels, 3, 1, dilation, dilation, groups=min_channels), act()) ) self.conv_acts = nn.Sequential(*self.conv_acts) def forward(self, x): self.masks = self.masks.to(x.device) x = self.head(x) now = x for i in range(self.num_butterflies): now = self.conv_acts[i*2](now) + self.conv_acts[i*2+1](torch.index_select(now, 1, self.masks[i])) now = now + x now = self.tail(now) return now class SRB(nn.Module): def __init__(self, in_channels, act, *args): super(SRB, self).__init__() self.conv3x3 = nn.Conv2d(in_channels, in_channels, 3, 1, 1) self.act = act() def forward(self, x): out = self.conv3x3(x) + x out = self.act(out) return out class MainBlock(nn.Module): def __init__(self, in_channels, act, basic_module): super(MainBlock, self).__init__() self.steps = 3 self.convs = [] for i in range(self.steps): self.convs.append(nn.Conv2d(in_channels, in_channels // 2, 1, 1, 0)) self.convs = nn.Sequential(*self.convs) self.basic_modules = [] for i in range(self.steps): self.basic_modules.append(basic_module(in_channels, act, in_channels)) self.basic_modules = nn.Sequential(*self.basic_modules) self.conv3x3 = nn.Conv2d(in_channels, in_channels // 2, 3, 1, 1) self.conv1x1 = nn.Conv2d(in_channels * 2, in_channels, 1, 1, 0) self.act = act() def forward(self, x): now = x features = [] for i in range(self.steps): features.append(self.convs[i](now)) now = self.basic_modules[i](now) now = self.conv3x3(now) features.append(now) features = torch.cat(features, 1) out = self.conv1x1(features) out = self.act(out) return out + x class RFDN(nn.Module): """RFDN network structure. Args: args.scale (list[int]): Upsampling scale for the input image. args.n_colors (int): Channels of the input image. args.n_feats (int): Channels of the mid layer. args.n_resblocks (int): Number of main blocks. args.act (str): Activate function used in BFN. Default: nn.PReLU. args.rgb_range: . args.main_block_version: args.butterfly_conv_version: args.skip_connection (bool):. """ def __init__(self, args): super(RFDN, self).__init__() assert len(args.scale) == 1 scale = args.scale[0] n_colors = args.n_colors n_feats = args.n_feats n_resblocks = args.n_resblocks if args.act == 'relu': act = nn.ReLU elif args.act == 'lrelu': act = nn.LeakyReLU elif args.act == 'prelu': act = nn.PReLU else: raise NotImplementedError("") if args.basic_module_version == 'v1': basic_module = SRB elif args.basic_module_version == 'v2': basic_module = ButterflyConv_v1 else: raise NotImplementedError("") rgb_range = args.rgb_range # RGB mean for DIV2K rgb_mean = (0.4488, 0.4371, 0.4040) rgb_std = (1.0, 1.0, 1.0) self.sub_mean = common.MeanShift(rgb_range, rgb_mean, rgb_std) self.head = nn.Conv2d(n_colors, n_feats, 3, 1, 1) self.main_blocks = [] for i in range(n_resblocks): self.main_blocks.append(MainBlock(n_feats, act, basic_module)) self.main_blocks = nn.Sequential(*self.main_blocks) self.features_fusion_module = nn.Sequential( nn.Conv2d(n_feats * n_resblocks, n_feats, 1, 1, 0), act() ) self.final_conv = nn.Conv2d(n_feats, n_feats, 3, 1, 1) self.upsampler = nn.Sequential( nn.Conv2d(n_feats, n_colors * (scale * scale), 3, 1, 1), nn.PixelShuffle(scale) ) self.add_mean = common.MeanShift(rgb_range, rgb_mean, rgb_std, 1) def forward(self, x): x = self.sub_mean(x) x = self.head(x) now = x outs = [] for main_block in self.main_blocks: now = main_block(now) outs.append(now) out = torch.cat(outs, 1) out = self.features_fusion_module(out) out = self.final_conv(out) + x out = self.upsampler(out) out = self.add_mean(out) return out if __name__ == '__main__': # test network import os os.environ['CUDA_VISIBLE_DEVICES'] = '1' import argparse args = argparse.Namespace() args.scale = [2] args.patch_size = 256 args.n_colors = 3 args.n_feats = 48 args.n_resblocks = 6 args.act = 'lrelu' args.rgb_range = 255 args.basic_module_version = 'v1' # args.scale = [2] # args.patch_size = 256 # args.n_colors = 3 # args.n_feats = 64 # args.n_resblocks = 6 # args.act = 'lrelu' # args.rgb_range = 255 # args.basic_module_version = 'v2' # import pdb # pdb.set_trace() model = RFDN(args) model.eval() from torchsummaryX import summary x = summary(model.cuda(), torch.zeros((1, 3, 720 // 4, 1280 // 4)).cuda()) # from torchsummary import summary # summary(model.cuda(), input_size=(3, 720 // 4, 1280 // 4), batch_size=1)
[ "torch.index_select", "torch.nn.PixelShuffle", "torch.nn.Sequential", "math.gcd", "torch.nn.Conv2d", "torch.tensor", "model.common.MeanShift", "argparse.Namespace", "torch.nn.Identity", "torch.zeros", "torch.cat" ]
[((575, 594), 'torch.tensor', 'torch.tensor', (['masks'], {}), '(masks)\n', (587, 594), False, 'import torch\n'), ((6623, 6643), 'argparse.Namespace', 'argparse.Namespace', ([], {}), '()\n', (6641, 6643), False, 'import argparse\n'), ((2105, 2135), 'torch.nn.Sequential', 'nn.Sequential', (['*self.conv_acts'], {}), '(*self.conv_acts)\n', (2118, 2135), True, 'import torch.nn as nn\n'), ((2609, 2653), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'in_channels', '(3)', '(1)', '(1)'], {}), '(in_channels, in_channels, 3, 1, 1)\n', (2618, 2653), True, 'import torch.nn as nn\n'), ((3104, 3130), 'torch.nn.Sequential', 'nn.Sequential', (['*self.convs'], {}), '(*self.convs)\n', (3117, 3130), True, 'import torch.nn as nn\n'), ((3312, 3346), 'torch.nn.Sequential', 'nn.Sequential', (['*self.basic_modules'], {}), '(*self.basic_modules)\n', (3325, 3346), True, 'import torch.nn as nn\n'), ((3371, 3420), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', '(in_channels // 2)', '(3)', '(1)', '(1)'], {}), '(in_channels, in_channels // 2, 3, 1, 1)\n', (3380, 3420), True, 'import torch.nn as nn\n'), ((3445, 3493), 'torch.nn.Conv2d', 'nn.Conv2d', (['(in_channels * 2)', 'in_channels', '(1)', '(1)', '(0)'], {}), '(in_channels * 2, in_channels, 1, 1, 0)\n', (3454, 3493), True, 'import torch.nn as nn\n'), ((3794, 3816), 'torch.cat', 'torch.cat', (['features', '(1)'], {}), '(features, 1)\n', (3803, 3816), False, 'import torch\n'), ((5303, 5349), 'model.common.MeanShift', 'common.MeanShift', (['rgb_range', 'rgb_mean', 'rgb_std'], {}), '(rgb_range, rgb_mean, rgb_std)\n', (5319, 5349), False, 'from model import common\n'), ((5371, 5408), 'torch.nn.Conv2d', 'nn.Conv2d', (['n_colors', 'n_feats', '(3)', '(1)', '(1)'], {}), '(n_colors, n_feats, 3, 1, 1)\n', (5380, 5408), True, 'import torch.nn as nn\n'), ((5579, 5611), 'torch.nn.Sequential', 'nn.Sequential', (['*self.main_blocks'], {}), '(*self.main_blocks)\n', (5592, 5611), True, 'import torch.nn as nn\n'), ((5785, 5821), 'torch.nn.Conv2d', 'nn.Conv2d', (['n_feats', 'n_feats', '(3)', '(1)', '(1)'], {}), '(n_feats, n_feats, 3, 1, 1)\n', (5794, 5821), True, 'import torch.nn as nn\n'), ((6002, 6051), 'model.common.MeanShift', 'common.MeanShift', (['rgb_range', 'rgb_mean', 'rgb_std', '(1)'], {}), '(rgb_range, rgb_mean, rgb_std, 1)\n', (6018, 6051), False, 'from model import common\n'), ((6291, 6309), 'torch.cat', 'torch.cat', (['outs', '(1)'], {}), '(outs, 1)\n', (6300, 6309), False, 'import torch\n'), ((950, 963), 'torch.nn.Identity', 'nn.Identity', ([], {}), '()\n', (961, 963), True, 'import torch.nn as nn\n'), ((988, 1001), 'torch.nn.Identity', 'nn.Identity', ([], {}), '()\n', (999, 1001), True, 'import torch.nn as nn\n'), ((5678, 5728), 'torch.nn.Conv2d', 'nn.Conv2d', (['(n_feats * n_resblocks)', 'n_feats', '(1)', '(1)', '(0)'], {}), '(n_feats * n_resblocks, n_feats, 1, 1, 0)\n', (5687, 5728), True, 'import torch.nn as nn\n'), ((5875, 5930), 'torch.nn.Conv2d', 'nn.Conv2d', (['n_feats', '(n_colors * (scale * scale))', '(3)', '(1)', '(1)'], {}), '(n_feats, n_colors * (scale * scale), 3, 1, 1)\n', (5884, 5930), True, 'import torch.nn as nn\n'), ((5944, 5966), 'torch.nn.PixelShuffle', 'nn.PixelShuffle', (['scale'], {}), '(scale)\n', (5959, 5966), True, 'import torch.nn as nn\n'), ((1261, 1274), 'torch.nn.Identity', 'nn.Identity', ([], {}), '()\n', (1272, 1274), True, 'import torch.nn as nn\n'), ((3032, 3081), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', '(in_channels // 2)', '(1)', '(1)', '(0)'], {}), '(in_channels, in_channels // 2, 1, 1, 0)\n', (3041, 3081), True, 'import torch.nn as nn\n'), ((7212, 7252), 'torch.zeros', 'torch.zeros', (['(1, 3, 720 // 4, 1280 // 4)'], {}), '((1, 3, 720 // 4, 1280 // 4))\n', (7223, 7252), False, 'import torch\n'), ((1340, 1353), 'torch.nn.Identity', 'nn.Identity', ([], {}), '()\n', (1351, 1353), True, 'import torch.nn as nn\n'), ((1973, 2062), 'torch.nn.Conv2d', 'nn.Conv2d', (['min_channels', 'min_channels', '(3)', '(1)', 'dilation', 'dilation'], {'groups': 'min_channels'}), '(min_channels, min_channels, 3, 1, dilation, dilation, groups=\n min_channels)\n', (1982, 2062), True, 'import torch.nn as nn\n'), ((2363, 2404), 'torch.index_select', 'torch.index_select', (['now', '(1)', 'self.masks[i]'], {}), '(now, 1, self.masks[i])\n', (2381, 2404), False, 'import torch\n'), ((1168, 1198), 'math.gcd', 'gcd', (['in_channels', 'out_channels'], {}), '(in_channels, out_channels)\n', (1171, 1198), False, 'from math import gcd\n'), ((1479, 1509), 'math.gcd', 'gcd', (['in_channels', 'out_channels'], {}), '(in_channels, out_channels)\n', (1482, 1509), False, 'from math import gcd\n')]
from datetime import datetime as dt import torch import torch.nn as nn """ Inspired by https://medium.com/dair-ai/a-simple-neural-network-from-scratch-with-pytorch-and-google-colab-c7f3830618e0 """ class NeuralNet(nn.Module): GPU_AVAIL = torch.cuda.is_available() DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") train_cnt = 0 epoch = 0 eta = 0.5 # TODO make constructor-only param #h_layers = [1000, 1000, 1000] h_layers = [3] X = None Y = None X_size = 0 # neural count Y_size = 0 # neural count # hidden layers & last output layers W = list() W_bias = list() __vec_one = None H = list() def __all_to_cuda(self): self.X = self.X.to(self.DEVICE) self.Y = self.Y.to(self.DEVICE) for i in range(len(self.W)): self.W[i] = self.W[i].to(self.DEVICE) self.W_bias[i] = self.W_bias[i].to(self.DEVICE) pass self.__vec_one = self.__vec_one.to(self.DEVICE) self.to(self.DEVICE) pass def __init__(self, X, Y, epoch): super(NeuralNet, self).__init__() self.X, self.Y = self.__scaled(X, Y) self.train_cnt = len(self.X) self.X_size = len(self.X[0]) self.Y_size = len(self.Y[0]) self.epoch = epoch self.h_layers.append(self.Y_size) left_neuron_cnt = self.X_size for neuron_cnt in self.h_layers: ww = torch.randn(left_neuron_cnt, neuron_cnt) hh = torch.full((self.train_cnt, neuron_cnt), -0.0001) self.W.append(ww) self.W_bias.append(torch.randn(neuron_cnt)) self.H.append(hh) left_neuron_cnt = neuron_cnt self.__vec_one = torch.ones(self.train_cnt) #device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Assuming that we are on a CUDA machine, this should print a CUDA device: #print(device) print("DEVICE = GPU" if self.GPU_AVAIL else "device = cpu") if self.GPU_AVAIL: self.__all_to_cuda() pass @staticmethod def sigmoid(s): return 1 / (1 + torch.exp(-s)) @staticmethod def sigmoid_prime(sig): return sig * (1 - sig) def get_train_loss(self): Y = self.__scaled_back(self.Y) H_last = self.__scaled_back(self.H[-1]) return torch.mean((Y - H_last)**2).detach().item() #H_last = self.H[-1] #return torch.mean((Y - H_last)**2).detach().item() def do_train(self): for i in range(self.epoch): self.forward(self.X) self.backward() #print("epoch = {}: loss = {}".format( i, str(self.get_train_loss()) )) def __scaled(self, X, Y): # normalize # max 24h a day # max score = 100 return X/24, Y/100 def __scaled_back(self, Y): # max score = 100 return Y*100 def forward(self, X): left_mt = X for idx in range(len(self.h_layers)): net_H_idx = torch.matmul(left_mt, self.W[idx]) + self.W_bias[idx] self.H[idx] = self.sigmoid(net_H_idx) left_mt = self.H[idx] return self.H[-1] def backward(self): # delta: start initially from layer H2 (output) delta_H = [torch.empty(0, 0) for idx in range(len(self.h_layers))] delta_H[-1] = (self.Y - self.H[-1]) * self.sigmoid_prime(self.H[-1]) # then delta: reversed loop from semi-last element -> beginning for idx in range(len(self.h_layers)-2, -1, -1): delta_H[idx] = torch.matmul(delta_H[idx + 1], torch.t(self.W[idx + 1])) * self.sigmoid_prime(self.H[idx]) # vector of 1 with size = training size vec_one = self.__vec_one # update weights: start from right most layer for idx in range(len(self.h_layers) - 1, 0, -1): #self.W[idx] += (1 / self.train_cnt) * self.eta * torch.matmul(torch.t(self.H[idx - 1]), delta_H[idx]) #self.W_bias[idx] += (1 / self.train_cnt) * self.eta * torch.matmul(vec_one, delta_H[idx]) self.W[idx] += torch.matmul(torch.t(self.H[idx - 1]), delta_H[idx]) self.W_bias[idx] += torch.matmul(vec_one, delta_H[idx]) # update weights: at layer W0 back to input #self.W[0] += (1 / self.train_cnt) * self.eta * torch.matmul(torch.t(self.X), delta_H[0]) #self.W_bias[0] += (1 / self.train_cnt) * self.eta * torch.matmul(vec_one, delta_H[0]) self.W[0] += torch.matmul(torch.t(self.X), delta_H[0]) self.W_bias[0] += torch.matmul(vec_one, delta_H[0]) f = open('study-sleep-grade.txt') lines = f.readlines() f.close() # print(lines) x_all = [] y_all = [] for line in lines: p = line.strip().split(", ") y = [float(yj) for yj in p[0].strip().split(' ')] x = [float(xi) for xi in p[1].strip().split(' ')] x_all.append(x) y_all.append(y) print(y_all) print(x_all) INP = torch.tensor((x_all[:-1]), dtype=torch.float) Y = torch.tensor((y_all[:-1]), dtype=torch.float) neu_net = NeuralNet(INP, Y, epoch=100) if torch.cuda.device_count() > 1: #print("Let's use", torch.cuda.device_count(), "GPUs!") #neu_net = nn.DataParallel(neu_net) pass print("-------------------------") print("training ...") tic = dt.now().microsecond neu_net.do_train() toc = dt.now().microsecond print("-------------------------") print("train loss = {:.2f}/100 (max score = 100)".format(neu_net.get_train_loss())) print("Train taken {} micro-secs".format('{:,}'.format(toc - tic)))
[ "torch.full", "torch.mean", "torch.cuda.device_count", "torch.exp", "torch.t", "torch.tensor", "datetime.datetime.now", "torch.cuda.is_available", "torch.matmul", "torch.empty", "torch.randn", "torch.ones" ]
[((4998, 5041), 'torch.tensor', 'torch.tensor', (['x_all[:-1]'], {'dtype': 'torch.float'}), '(x_all[:-1], dtype=torch.float)\n', (5010, 5041), False, 'import torch\n'), ((5048, 5091), 'torch.tensor', 'torch.tensor', (['y_all[:-1]'], {'dtype': 'torch.float'}), '(y_all[:-1], dtype=torch.float)\n', (5060, 5091), False, 'import torch\n'), ((246, 271), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (269, 271), False, 'import torch\n'), ((5137, 5162), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (5160, 5162), False, 'import torch\n'), ((5335, 5343), 'datetime.datetime.now', 'dt.now', ([], {}), '()\n', (5341, 5343), True, 'from datetime import datetime as dt\n'), ((5381, 5389), 'datetime.datetime.now', 'dt.now', ([], {}), '()\n', (5387, 5389), True, 'from datetime import datetime as dt\n'), ((1756, 1782), 'torch.ones', 'torch.ones', (['self.train_cnt'], {}), '(self.train_cnt)\n', (1766, 1782), False, 'import torch\n'), ((4623, 4656), 'torch.matmul', 'torch.matmul', (['vec_one', 'delta_H[0]'], {}), '(vec_one, delta_H[0])\n', (4635, 4656), False, 'import torch\n'), ((310, 335), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (333, 335), False, 'import torch\n'), ((1466, 1506), 'torch.randn', 'torch.randn', (['left_neuron_cnt', 'neuron_cnt'], {}), '(left_neuron_cnt, neuron_cnt)\n', (1477, 1506), False, 'import torch\n'), ((1524, 1573), 'torch.full', 'torch.full', (['(self.train_cnt, neuron_cnt)', '(-0.0001)'], {}), '((self.train_cnt, neuron_cnt), -0.0001)\n', (1534, 1573), False, 'import torch\n'), ((3330, 3347), 'torch.empty', 'torch.empty', (['(0)', '(0)'], {}), '(0, 0)\n', (3341, 3347), False, 'import torch\n'), ((4242, 4277), 'torch.matmul', 'torch.matmul', (['vec_one', 'delta_H[idx]'], {}), '(vec_one, delta_H[idx])\n', (4254, 4277), False, 'import torch\n'), ((4568, 4583), 'torch.t', 'torch.t', (['self.X'], {}), '(self.X)\n', (4575, 4583), False, 'import torch\n'), ((1635, 1658), 'torch.randn', 'torch.randn', (['neuron_cnt'], {}), '(neuron_cnt)\n', (1646, 1658), False, 'import torch\n'), ((2175, 2188), 'torch.exp', 'torch.exp', (['(-s)'], {}), '(-s)\n', (2184, 2188), False, 'import torch\n'), ((3065, 3099), 'torch.matmul', 'torch.matmul', (['left_mt', 'self.W[idx]'], {}), '(left_mt, self.W[idx])\n', (3077, 3099), False, 'import torch\n'), ((4170, 4194), 'torch.t', 'torch.t', (['self.H[idx - 1]'], {}), '(self.H[idx - 1])\n', (4177, 4194), False, 'import torch\n'), ((3649, 3673), 'torch.t', 'torch.t', (['self.W[idx + 1]'], {}), '(self.W[idx + 1])\n', (3656, 3673), False, 'import torch\n'), ((2401, 2430), 'torch.mean', 'torch.mean', (['((Y - H_last) ** 2)'], {}), '((Y - H_last) ** 2)\n', (2411, 2430), False, 'import torch\n')]
import os import numpy as np import pandas as pd from scipy import sparse as sp from typing import Callable, List, Tuple, Dict from os.path import join from . import utils, process_dat from . import SETTINGS_POLIMI as SETTINGS os.environ['NUMEXPR_MAX_THREADS'] = str(SETTINGS.hyp['cores']) pd.options.mode.chained_assignment = None # allow assigning to copy of DataFrame slice without warnings def simulate_batch(initial_user_state: np.ndarray, models: tuple, hyp: dict, stg: dict, tevmin: float, tevmax: float, tevmin_train: float, tevmax_train: float, tevmean_train: float, verbose: int = 0, user_max_lam: np.ndarray = None, user_n_imp: np.ndarray = None, fix_n_imp: bool = False) -> pd.DataFrame: """ Runs simulation given models of members (consumption and visits) and recommenders (impressions). Idea is to sample "visit potential points" for each user based on an upper bound of intensity with homogeneous Poisson process, then use rejection sampling to decide the actual visit time points. @param initial_user_state: (n_users, n_items) csr_matrix start state for each member @param models: (UserModel, [RecModel], VisitModel) tuple @param hyp: hyperparameter dict @param stg: settings dict @param tevmin: float min time of visits @param tevmax: float max time of visits @param tevmin_train: float min time of visits in training data @param tevmax_train: float max time of visits in training data @param tevmean_train: float mean time of visits in training data @param verbose: bool verbose mode @param user_max_lam: np.array maximum intensity per member @param user_n_imp: np.array mean number of impressions per member @param fix_n_imp: if true then take `user_n_imp` fixed impressions per memeber @return: simulated dataset of impressions """ # need local import otherwise multiprocessing will not work (silent error): from . import sim_models import tensorflow os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' tensorflow.keras.backend.set_floatx('float64') import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) user_model, rec_models, visit_model = models # unpack models # initialize user_states: list of np.array representing complete history for each user user_states = initial_user_state.toarray().copy() # tracks current user state for all users #user_states = initial_user_state.copy() # tracks current user state for all users # define some constants: if user_max_lam is None: user_max_lam = hyp['max_lam'] * np.ones(stg['NU']) # estimate upper bound for all users n_potential_visits = [np.random.poisson(lam=m * stg['T']) for m in user_max_lam] # num events per user # create np.array of NU-by-N visit deltas for each user # (indicate non-visits with nan): max_n_visits = max(n_potential_visits) user_potential_visits = np.nan + np.zeros((stg['NU'], max_n_visits)) # stg['INF_TIME'] + for u, n_points in enumerate(n_potential_visits): user_potential_visits[u, :n_points] = np.sort(np.random.uniform(low=tevmin, high=tevmax, size=n_points)) # user_potential_visits is now the array indicating global visit time for set of potential visits per user print('tevmin, tevmax', tevmin, tevmax) arb_rec_model = rec_models[0] time_rec = isinstance(arb_rec_model, sim_models.RecModelTime) if time_rec: # create time features for each potential visit per member: T = np.zeros((max_n_visits, stg['NU'], arb_rec_model._time_bins.shape[0] - 1)) for u in range(stg['NU']): T[:, u, :] = arb_rec_model.process_time_feature(user_potential_visits[u, :], create_bins=False).toarray() # randomly draw num of impressions for each user and potential visit # (todo: refactor this part into separate function) if user_n_imp is None: imp_shape = (stg['NU'], max_n_visits) if fix_n_imp: user_nimp = stg['lambda_impression']*np.ones(imp_shape) else: user_nimp = np.random.poisson(stg['lambda_impression'], size=imp_shape) # number of impressions at each potential visit else: if fix_n_imp: user_nimp = np.repeat(user_n_imp[:,np.newaxis], max_n_visits, axis=1) else: user_nimp = np.array([np.random.poisson(user_n_imp) for _ in range(max_n_visits)]).T user_nimp = np.minimum(int(stg['NI']/2), np.maximum(1, user_nimp)) # ensure n_impressions per visit 1 <= n_imp <= num items/2. user_nimp = user_nimp.astype('int64') iteration = 0 # init simulation, update on every iteration of the main loop: simdict = {'user_id': np.zeros(0, dtype='int64'), 'time': np.zeros(0), 'action': np.zeros(0, dtype='int64'), 'potential_action': np.zeros(0, dtype='int64'), 'state': [], 'reward': np.zeros(0)} simulation = pd.DataFrame(simdict) print('running batch simulation...') while iteration < max_n_visits: # process all users in each iteration (all users who have not had final visit). # decide which users will be potentially visiting in this time block # in order to prepare features for visit_model prediction: # evaluate intensity function for all potential visitors, then decide which ones # are actually visiting with rejection sampling: pvs, = np.where(~np.isnan(user_potential_visits[:, iteration])) # potential visitors # prepare feature vector X (one per potentially active user) if hyp['hyp_study']['constant_rate']: X = np.zeros(1) else: X = sim_models.process_features_static_points(simulation, user_potential_visits[pvs, iteration], pvs, ( stg['NI'], hyp['visit_model_hyp']['window_size'], tevmean_train, tevmin_train, tevmax_train), init_user_states=initial_user_state) # update prediction cache for user and rec models rec_states = np.hstack((user_states, T[iteration, :, :])) if time_rec else user_states [rec_model.populate_cache(rec_states) for rec_model in rec_models] user_model.populate_cache(user_states) if verbose: print('updated user/rec policy per user.') print('processed stochastic process features.') if X.shape[0] > 0: if hyp['hyp_study']['constant_rate']: pvs_lam = np.zeros_like(pvs) accept_pr = np.ones_like(pvs) else: mix = hyp['visit_model_hyp']['self_exciting_mixture'] pvs_lam_norm = (1-mix)*visit_model._model.predict(X.toarray()) + mix*visit_model._lambda_e_model.predict(X.toarray()) # predicted lambda for each active user pvs_lam = pvs_lam_norm * visit_model.time_scale # model predicts over [-1,+1] time, need to spread over # original range accept_pr = pvs_lam.ravel() / user_max_lam[pvs] print_every = 20 if (iteration % print_every) == 0: print('iteration %i, num. of active users' % iteration, pvs_lam.ravel().shape) print('pvs_lam', pvs_lam.ravel()) print('max_lam', user_max_lam[pvs]) assert np.all(accept_pr <= 1.0), pvs_lam.ravel().max() is_visit = np.array(np.random.binomial(1, accept_pr), dtype=np.bool_) uz_visit = pvs[is_visit] # decide which users are actually visiting if verbose: print('sampled visiting users.') # iterate over visiting users to draw recommendations: for u in uz_visit: user_state = user_states[u, :].copy() # pull out current user state rec_state = rec_states[u, :] n_imp = user_nimp[u, iteration] rec_prop = SETTINGS.hyp['rec_prop'] # draw rec_id based on global probability rec_id = np.random.choice(np.arange(len(rec_models), dtype='int16'), p=rec_prop) # draw recommendation for user, depending on which rec_id to use: az = rec_models[rec_id].select(rec_state, n_imp, hyp, stg) # select count depends on whether using Bernoulli or Categorical model: select_count = az if isinstance(user_model, sim_models.UserModelBinary) else hyp['user_select_count'] # draw consumed title for user (i.e. title they would have consumed if they had been recommended it) cz = user_model.select(user_state, select_count, hyp, stg) assert n_imp > 0, n_imp simdict, user_state = calculate_reward_by_overlap(user_state, u, n_imp, az, cz, user_potential_visits, iteration, rec_id, stg) # update user state user_states[u, :] = user_state # update current user state for user u try: new_sim = pd.DataFrame(simdict) except ValueError: print([len(x) for x in [simdict['user_id'], simdict['state'], simdict['action'], simdict['potential_action'], simdict['time']]]) raise ValueError() simulation = simulation.append(new_sim, ignore_index=True, sort=False) iteration += 1 return simulation def calculate_reward_by_overlap(user_state: np.ndarray, u: int, n_imp: int, az: np.ndarray, cz: np.ndarray, user_potential_visits: np.ndarray, iteration: int, rec_id: int, stg: Dict) \ -> Tuple[Dict, np.ndarray]: """ Calculates reward by inspecting actions taken by member and recommender and looking for any overlap. @param user_state: np.array(n_members, n_items) representing state of each member @param u: int, member id @param n_imp: int, number of impressions @param az: np.array of actions taken by recommender @param cz: np.array of (potential) actions taken by member @param user_potential_visits: np.array(n_users, n_iterations) of time of visit for each member @param iteration: int, iteration id @param rec_id: int, recommender id @param stg: dict of settings @return: dictionary representing new rows for the simulation, updated user state """ A = np.bincount(az, minlength=stg['NI']) C = np.bincount(cz, minlength=stg['NI']) R = A * C streamed, = np.where(R > 0) # build list of streamed and non-streamed actions az_success = list(streamed) cz_success = list(streamed) az_fail = list(set(az) - set(az_success)) cz_fail = list(set(cz) - set(cz_success)) len_rz = min(1, len(streamed)) simdict = {'user_id': np.array([u] * n_imp, dtype='int64'), # np.repeat(u,n_imp,dtype='int64'), 'time': [user_potential_visits[u, iteration]] * n_imp, # np.repeat(global_t,n_imp), 'action': az_success + az_fail, 'potential_action': [-1] * n_imp, # cz_success+cz_fail, 'state': [utils.bow(user_state)] * n_imp, 'reward': [1] * len_rz + [0] * (n_imp - len_rz), 'rec_id': rec_id} user_state[np.random.permutation(streamed)[:1]] = 1 return simdict, user_state def load_models(user_model_path: str, rec_model_paths: str, visit_model_path: str, hyp: Dict, stg: Dict, rec_type: str = 'static', user_binary: bool = False) -> Tuple: # load models from disk from . import sim_models # load user model: if user_binary: user_model = sim_models.UserModelBinary(stg['NI'], stg['NI'], hyp['user_model_hyp']) else: user_model = sim_models.UserModel(stg['NI'], stg['NI'], hyp['user_model_hyp']) user_model.load(user_model_path) # load recommender models (multiple models because we consider multiple recommenders in any single simulation): ceil_t = np.ceil(stg['T']).astype('int') rec_models = [] for rec_model_path in rec_model_paths: if type(rec_model_path) == str: if rec_type == 'static': rec_model = sim_models.RecModel(stg['NI'], stg['NI'], hyp['rec_model_hyp']) rec_model.load(rec_model_path) elif rec_type == 'time': rec_model = sim_models.RecModelTime(stg['NI'], stg['NI'], hyp['rec_model_hyp'], ceil_t) rec_model.load(rec_model_path) elif rec_type == 'nmf': print('nmf model with hyp =',SETTINGS.hyp['hyp_study']) rec_model = sim_models.NMFRec(stg['NI'], SETTINGS.hyp['hyp_study']) if len(rec_model_path)>0: nmf_rec_model_dat = pd.read_csv(rec_model_path) # path is to history of data not model here rec_model.fit(nmf_rec_model_dat, stg['NI']) else: raise Exception('rec model type unrecognized: ' + rec_type) else: rec_model = rec_model_path rec_models.append(rec_model) # load user visit model: visit_model = sim_models.VisitModel(stg['NI'], stg['NU'], hyp['visit_model_hyp']) visit_model.load(visit_model_path, None) return (user_model, rec_models, visit_model) def batch_sim(uids: np.ndarray, kwargs: Dict) -> pd.DataFrame: print('batch sim on uids', uids.min(), 'to', uids.max(), '(inclusive)') stg_local = kwargs['stg'].copy() uid_min, uid_max = uids.min(), uids.max()+1 stg_local['NU'] = uid_max - uid_min stg_local['T'] = kwargs['tevmax'] init_states = kwargs['S_init'][uid_min:uid_max, :] model_paths = kwargs['model_paths'] if 'hyp' in kwargs: local_hyp = kwargs['hyp'] else: local_hyp = SETTINGS.hyp if kwargs['user_max_lam'] is not None: user_max_lam = kwargs['user_max_lam'][uid_min:uid_max] else: user_max_lam = None user_path, rec_path, visit_path = model_paths['user_model'], model_paths['rec_model'], model_paths['visit_model'] models = load_models(user_path, rec_path, visit_path, local_hyp, stg_local, rec_type='nmf', user_binary=True) s = simulate_batch(init_states, models, local_hyp, stg_local, kwargs['tevmin'], kwargs['tevmax'], kwargs['tevmin_train'], kwargs['tevmax_train'], kwargs['tevmean_train'], user_max_lam=user_max_lam, user_n_imp=kwargs['empirical_mean_imp_per_visit'][uid_min:uid_max], fix_n_imp=kwargs['fix_n_imp'] if 'fix_n_imp' in kwargs else False) # adjust uid to avoid clash with other child processes: s.user_id = s.user_id + uid_min return s def prepare_sim(simulation: pd.DataFrame, stg: Dict, base_path: str) -> Dict: # find initial states for all users: # please note: groupby preserves order when sort=False https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html first_imps = simulation.sort_values(['time']).groupby('user_id',sort=False).first().sort_values(['user_id']) user_ids = np.sort(first_imps.index) # initial_user_state is np.array NU-x-NI int64 S_init = utils.inv_bow_all(first_imps.state.values, stg['NI'], dense=False).tocsr() # update num. users to reflect only users with streams in observation: stg_local = stg.copy() n_users = S_init.shape[0] np.random.seed(0) uids = np.random.choice(np.arange(stg['NU'],dtype='int32'),size=n_users,replace=False) tevmean, tevmin, tevmax = process_dat.calc_tev(simulation) # calculate average number of visits per user (defined as user_id-by-time group of impressions): sg = simulation.groupby(['user_id','time']) empirical_n_visits = sg.count().groupby('user_id')['action'].count().values # calculate average number of impressions per visit per user imp_series = sg['action'].count().groupby('user_id').mean() assert np.all(imp_series.index == user_ids) # make sure user ids match up return {'S_init': S_init, 'stg': stg, 'tevmax': tevmax, 'tevmin': tevmin, 'tevmean': tevmean, 'user_max_lam': None, 'empirical_mean_imp_per_visit': imp_series.values, 'base_path': base_path } def prepare_sim_contentwise(simulation: pd.DataFrame, stg: Dict, hyp: Dict, user_lam: np.ndarray, base_path: str) -> Dict: # find initial states for all users: # please note: groupby preserves order when sort=False https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html first_imps = simulation.sort_values(['time']).groupby('user_id',sort=False).first().sort_values(['user_id']) user_ids = np.sort(first_imps.index) # initial_user_state is np.array NU-x-NI int64 S_init = utils.inv_bow_all(first_imps.state.values, stg['NI'], dense=False).tocsr() np.random.seed(0) tevmean, tevmin, tevmax = process_dat.calc_tev(simulation) # calculate average number of visits per user (defined as user_id-by-time group of impressions): sg = simulation.groupby(['user_id','round_time']) empirical_n_visits = sg.first().groupby('user_id').action.count().values # calculate average number of impressions per visit per user imp_series = sg['action'].count().groupby('user_id').mean() assert np.all(imp_series.index == user_ids) # make sure user ids match up if not(hyp['constant_rate']): user_lam = None return {'S_init': S_init, 'stg': stg, 'tevmax': tevmax, 'tevmin': tevmin, 'tevmean': tevmean, 'user_max_lam': user_lam, 'empirical_mean_imp_per_visit': imp_series.values, 'base_path': base_path } def parsim(rec_model_config: List, **kwargs): user_set = np.arange(kwargs['S_init'].shape[0], dtype='int64') test_id = SETTINGS.simulation_components['ab_test_id'] # add model_paths to kwargs and pass through to batch_sim: kwargs['model_paths'] = {'user_model': join(kwargs['base_path'], SETTINGS.filepaths['user_model_test']) % test_id, 'rec_model': [join(kwargs['base_path'], SETTINGS.filepaths['rec_model_t_test']) % (test_id, cell_id, rec_id) for test_id, cell_id, rec_id in rec_model_config], 'visit_model': join(kwargs['base_path'], SETTINGS.filepaths['visit_model_test-%s' % test_id] + '.big') } return utils.parallelize_fnc(batch_sim, user_set, kwargs, int(SETTINGS.hyp['cores']/2))
[ "pandas.read_csv", "numpy.hstack", "numpy.array", "numpy.arange", "numpy.random.binomial", "numpy.repeat", "numpy.random.poisson", "numpy.where", "numpy.sort", "numpy.random.seed", "pandas.DataFrame", "numpy.maximum", "numpy.random.permutation", "numpy.ceil", "numpy.ones", "tensorflow....
[((2162, 2208), 'tensorflow.keras.backend.set_floatx', 'tensorflow.keras.backend.set_floatx', (['"""float64"""'], {}), "('float64')\n", (2197, 2208), False, 'import tensorflow\n'), ((2233, 2295), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'DeprecationWarning'}), "('ignore', category=DeprecationWarning)\n", (2256, 2295), False, 'import warnings\n'), ((5154, 5175), 'pandas.DataFrame', 'pd.DataFrame', (['simdict'], {}), '(simdict)\n', (5166, 5175), True, 'import pandas as pd\n'), ((10694, 10730), 'numpy.bincount', 'np.bincount', (['az'], {'minlength': "stg['NI']"}), "(az, minlength=stg['NI'])\n", (10705, 10730), True, 'import numpy as np\n'), ((10739, 10775), 'numpy.bincount', 'np.bincount', (['cz'], {'minlength': "stg['NI']"}), "(cz, minlength=stg['NI'])\n", (10750, 10775), True, 'import numpy as np\n'), ((10806, 10821), 'numpy.where', 'np.where', (['(R > 0)'], {}), '(R > 0)\n', (10814, 10821), True, 'import numpy as np\n'), ((15382, 15407), 'numpy.sort', 'np.sort', (['first_imps.index'], {}), '(first_imps.index)\n', (15389, 15407), True, 'import numpy as np\n'), ((15688, 15705), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (15702, 15705), True, 'import numpy as np\n'), ((16239, 16275), 'numpy.all', 'np.all', (['(imp_series.index == user_ids)'], {}), '(imp_series.index == user_ids)\n', (16245, 16275), True, 'import numpy as np\n'), ((17035, 17060), 'numpy.sort', 'np.sort', (['first_imps.index'], {}), '(first_imps.index)\n', (17042, 17060), True, 'import numpy as np\n'), ((17209, 17226), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (17223, 17226), True, 'import numpy as np\n'), ((17672, 17708), 'numpy.all', 'np.all', (['(imp_series.index == user_ids)'], {}), '(imp_series.index == user_ids)\n', (17678, 17708), True, 'import numpy as np\n'), ((18152, 18203), 'numpy.arange', 'np.arange', (["kwargs['S_init'].shape[0]"], {'dtype': '"""int64"""'}), "(kwargs['S_init'].shape[0], dtype='int64')\n", (18161, 18203), True, 'import numpy as np\n'), ((2823, 2858), 'numpy.random.poisson', 'np.random.poisson', ([], {'lam': "(m * stg['T'])"}), "(lam=m * stg['T'])\n", (2840, 2858), True, 'import numpy as np\n'), ((3084, 3119), 'numpy.zeros', 'np.zeros', (["(stg['NU'], max_n_visits)"], {}), "((stg['NU'], max_n_visits))\n", (3092, 3119), True, 'import numpy as np\n'), ((3675, 3749), 'numpy.zeros', 'np.zeros', (["(max_n_visits, stg['NU'], arb_rec_model._time_bins.shape[0] - 1)"], {}), "((max_n_visits, stg['NU'], arb_rec_model._time_bins.shape[0] - 1))\n", (3683, 3749), True, 'import numpy as np\n'), ((4651, 4675), 'numpy.maximum', 'np.maximum', (['(1)', 'user_nimp'], {}), '(1, user_nimp)\n', (4661, 4675), True, 'import numpy as np\n'), ((4891, 4917), 'numpy.zeros', 'np.zeros', (['(0)'], {'dtype': '"""int64"""'}), "(0, dtype='int64')\n", (4899, 4917), True, 'import numpy as np\n'), ((4942, 4953), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (4950, 4953), True, 'import numpy as np\n'), ((4980, 5006), 'numpy.zeros', 'np.zeros', (['(0)'], {'dtype': '"""int64"""'}), "(0, dtype='int64')\n", (4988, 5006), True, 'import numpy as np\n'), ((5043, 5069), 'numpy.zeros', 'np.zeros', (['(0)'], {'dtype': '"""int64"""'}), "(0, dtype='int64')\n", (5051, 5069), True, 'import numpy as np\n'), ((5124, 5135), 'numpy.zeros', 'np.zeros', (['(0)'], {}), '(0)\n', (5132, 5135), True, 'import numpy as np\n'), ((11093, 11129), 'numpy.array', 'np.array', (['([u] * n_imp)'], {'dtype': '"""int64"""'}), "([u] * n_imp, dtype='int64')\n", (11101, 11129), True, 'import numpy as np\n'), ((15734, 15769), 'numpy.arange', 'np.arange', (["stg['NU']"], {'dtype': '"""int32"""'}), "(stg['NU'], dtype='int32')\n", (15743, 15769), True, 'import numpy as np\n'), ((18721, 18812), 'os.path.join', 'join', (["kwargs['base_path']", "(SETTINGS.filepaths['visit_model_test-%s' % test_id] + '.big')"], {}), "(kwargs['base_path'], SETTINGS.filepaths['visit_model_test-%s' %\n test_id] + '.big')\n", (18725, 18812), False, 'from os.path import join\n'), ((2740, 2758), 'numpy.ones', 'np.ones', (["stg['NU']"], {}), "(stg['NU'])\n", (2747, 2758), True, 'import numpy as np\n'), ((3254, 3311), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': 'tevmin', 'high': 'tevmax', 'size': 'n_points'}), '(low=tevmin, high=tevmax, size=n_points)\n', (3271, 3311), True, 'import numpy as np\n'), ((4234, 4293), 'numpy.random.poisson', 'np.random.poisson', (["stg['lambda_impression']"], {'size': 'imp_shape'}), "(stg['lambda_impression'], size=imp_shape)\n", (4251, 4293), True, 'import numpy as np\n'), ((4437, 4495), 'numpy.repeat', 'np.repeat', (['user_n_imp[:, np.newaxis]', 'max_n_visits'], {'axis': '(1)'}), '(user_n_imp[:, np.newaxis], max_n_visits, axis=1)\n', (4446, 4495), True, 'import numpy as np\n'), ((5858, 5869), 'numpy.zeros', 'np.zeros', (['(1)'], {}), '(1)\n', (5866, 5869), True, 'import numpy as np\n'), ((6285, 6329), 'numpy.hstack', 'np.hstack', (['(user_states, T[iteration, :, :])'], {}), '((user_states, T[iteration, :, :]))\n', (6294, 6329), True, 'import numpy as np\n'), ((7574, 7598), 'numpy.all', 'np.all', (['(accept_pr <= 1.0)'], {}), '(accept_pr <= 1.0)\n', (7580, 7598), True, 'import numpy as np\n'), ((11556, 11587), 'numpy.random.permutation', 'np.random.permutation', (['streamed'], {}), '(streamed)\n', (11577, 11587), True, 'import numpy as np\n'), ((12272, 12289), 'numpy.ceil', 'np.ceil', (["stg['T']"], {}), "(stg['T'])\n", (12279, 12289), True, 'import numpy as np\n'), ((18369, 18433), 'os.path.join', 'join', (["kwargs['base_path']", "SETTINGS.filepaths['user_model_test']"], {}), "(kwargs['base_path'], SETTINGS.filepaths['user_model_test'])\n", (18373, 18433), False, 'from os.path import join\n'), ((4177, 4195), 'numpy.ones', 'np.ones', (['imp_shape'], {}), '(imp_shape)\n', (4184, 4195), True, 'import numpy as np\n'), ((5658, 5703), 'numpy.isnan', 'np.isnan', (['user_potential_visits[:, iteration]'], {}), '(user_potential_visits[:, iteration])\n', (5666, 5703), True, 'import numpy as np\n'), ((6720, 6738), 'numpy.zeros_like', 'np.zeros_like', (['pvs'], {}), '(pvs)\n', (6733, 6738), True, 'import numpy as np\n'), ((6767, 6784), 'numpy.ones_like', 'np.ones_like', (['pvs'], {}), '(pvs)\n', (6779, 6784), True, 'import numpy as np\n'), ((7654, 7686), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'accept_pr'], {}), '(1, accept_pr)\n', (7672, 7686), True, 'import numpy as np\n'), ((18488, 18553), 'os.path.join', 'join', (["kwargs['base_path']", "SETTINGS.filepaths['rec_model_t_test']"], {}), "(kwargs['base_path'], SETTINGS.filepaths['rec_model_t_test'])\n", (18492, 18553), False, 'from os.path import join\n'), ((9290, 9311), 'pandas.DataFrame', 'pd.DataFrame', (['simdict'], {}), '(simdict)\n', (9302, 9311), True, 'import pandas as pd\n'), ((4543, 4572), 'numpy.random.poisson', 'np.random.poisson', (['user_n_imp'], {}), '(user_n_imp)\n', (4560, 4572), True, 'import numpy as np\n'), ((13061, 13088), 'pandas.read_csv', 'pd.read_csv', (['rec_model_path'], {}), '(rec_model_path)\n', (13072, 13088), True, 'import pandas as pd\n')]
""" This module contains definitions of lume-model variables for use with lume tools. The variables are divided into input and outputs, each with different minimal requirements. Initiating any variable without the minimum requirements will result in an error. Two types of variables are currently defined: Scalar and Image. Scalar variables hold float type values. Image variables hold numpy array representations of images. """ import numpy as np from enum import Enum import logging from typing import Any, List, Union, Optional, Generic, TypeVar from pydantic import BaseModel, Field, validator from pydantic.generics import GenericModel logger = logging.getLogger(__name__) class PropertyBaseModel(GenericModel): """ Generic base class used for the Variables. This extends the pydantic GenericModel to serialize properties. TODO: Workaround for serializing properties with pydantic until https://github.com/samuelcolvin/pydantic/issues/935 is solved. This solution is referenced in the issue. """ @classmethod def get_properties(cls): return [ prop for prop in dir(cls) if isinstance(getattr(cls, prop), property) and prop not in ("__values__", "fields") ] def dict( self, *, include: Union["AbstractSetIntStr", "MappingIntStrAny"] = None, exclude: Union["AbstractSetIntStr", "MappingIntStrAny"] = None, by_alias: bool = False, skip_defaults: bool = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, ) -> "DictStrAny": attribs = super().dict( include=include, exclude=exclude, by_alias=by_alias, skip_defaults=skip_defaults, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) props = self.get_properties() # Include and exclude properties if include: props = [prop for prop in props if prop in include] if exclude: props = [prop for prop in props if prop not in exclude] # Update the attribute dict with the properties if props: attribs.update({prop: getattr(self, prop) for prop in props}) return attribs class NumpyNDArray(np.ndarray): """ Custom type validator for numpy ndarray. """ @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v: Any) -> np.ndarray: # validate data... if not isinstance(v, np.ndarray): logger.exception("A numpy array is required for the value") raise TypeError("Numpy array required") return v class Image(np.ndarray): """ Custom type validator for image array. """ @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v: Any) -> np.ndarray: # validate data... if not isinstance(v, np.ndarray): logger.exception("Image variable value must be a numpy array") raise TypeError("Numpy array required") if (not v.ndim == 2 and not v.ndim == 3) or (v.ndim == 3 and v.shape[2] != 3): logger.exception("Array must have dim=2 or dim=3 to instantiate image") raise ValueError( f"Image array must have dim=2 or dim=3. Provided array has {v.ndim} dimensions" ) return v class NDVariableBase: """ Holds properties associated with numpy array variables. Attributes: shape (tuple): Shape of the numpy n-dimensional array """ @property def shape(self) -> tuple: if self.default is not None: return self.default.shape else: return None # define generic value type Value = TypeVar("Value") class Variable(PropertyBaseModel, Generic[Value]): """ Minimum requirements for a Variable Attributes: name (str): Name of the variable. value (Optional[Value]): Value assigned to the variable precision (Optional[int]): Precision to use for the value """ name: str = Field(...) # name required value: Optional[Value] = None precision: Optional[int] = None class Config: allow_population_by_field_name = True # do not use alias only-init class InputVariable(Variable, Generic[Value]): """ Base class for input variables. Attributes: name (str): Name of the variable. default (Value): Default value assigned to the variable precision (Optional[int]): Precision to use for the value value (Optional[Value]): Value assigned to variable value_range (list): Acceptable range for value """ default: Value # required default is_constant: bool = False class Config: allow_mutation = True def __init__(self, **kwargs): super(Variable, self).__init__(**kwargs) self.Config.allow_mutation = not self.is_constant class OutputVariable(Variable, Generic[Value]): """ Base class for output variables. Value and range assignment are optional. Attributes: name (str): Name of the variable. default (Optional[Value]): Default value assigned to the variable. precision (Optional[int]): Precision to use for the value. value (Optional[Value]): Value assigned to variable value_range (Optional[list]): Acceptable range for value """ default: Optional[Value] value_range: Optional[list] = Field(alias="range") class ImageVariable(BaseModel, NDVariableBase): """ Base class used for constructing an image variable. Attributes: variable_type (str): Indicates image variable. axis_labels (List[str]): Labels to use for rendering axes. axis_units (Optional[List[str]]): Units to use for rendering axes labels. x_min_variable (Optional[str]): Scalar variable associated with image minimum x. x_max_variable (Optional[str]): Scalar variable associated with image maximum x. y_min_variable (Optional[str]): Scalar variable associated with image minimum y. y_max_variable (Optional[str]): Scalar variable associated with image maximum y. """ variable_type: str = "image" axis_labels: List[str] axis_units: List[str] = None x_min_variable: str = None x_max_variable: str = None y_min_variable: str = None y_max_variable: str = None class ArrayVariable(BaseModel, NDVariableBase): """ Base class used for constructing an array variable. Attributes: variable_type (str): Indicates array variable. dim_labels (List[str]): Labels to use for rendering axes. dim_units (Optional[List[str]]): Units to use for rendering axes labels. """ variable_type: str = "array" units: Optional[List[str]] = None # required for some output displays dim_labels: Optional[List[str]] = None value_type: str = "float" class ScalarVariable(BaseModel): """ Base class used for constructing a scalar variable. Attributes: variable_type (tuple): Indicates scalar variable. units (Optional[str]): Units associated with scalar value. parent_variable (Optional[str]): Variable for which this is an attribute. """ variable_type: str = "scalar" units: Optional[str] = None # required for some output displays parent_variable: str = None # indicates that this variable is an attribute of another value_range: list = Field(..., alias="range") # range required class ImageInputVariable(InputVariable[Image], ImageVariable): """ Variable used for representing an image input. Image variable values must be two or three dimensional arrays (grayscale, color, respectively). Initialization requires name, axis_labels, default, x_min, x_max, y_min, y_max. Attributes: name (str): Name of the variable. default (Value): Default value assigned to the variable. precision (Optional[int]): Precision to use for the value. value (Optional[Value]): Value assigned to variable value_range (list): Acceptable range for value variable_type (str): Indicates image variable. axis_labels (List[str]): Labels to use for rendering axes. axis_units (Optional[List[str]]): Units to use for rendering axes labels. x_min (float): Minimum x value of image. x_max (float): Maximum x value of image. y_min (float): Minimum y value of image. y_max (float): Maximum y value of image. x_min_variable (Optional[str]): Scalar variable associated with image minimum x. x_max_variable (Optional[str]): Scalar variable associated with image maximum x. y_min_variable (Optional[str]): Scalar variable associated with image minimum y. y_max_variable (Optional[str]): Scalar variable associated with image maximum y. Example: ``` variable = ImageInputVariable( name="test", default=np.array([[1,4], [5,2]]), value_range=[1, 10], axis_labels=["count_1", "count_2"], x_min=0, y_min=0, x_max=5, y_max=5, ) ``` """ x_min: float x_max: float y_min: float y_max: float class ImageOutputVariable(OutputVariable[Image], ImageVariable): """ Variable used for representing an image output. Image variable values must be two or three dimensional arrays (grayscale, color, respectively). Initialization requires name and axis_labels. Attributes: name (str): Name of the variable. default (Optional[Value]): Default value assigned to the variable. precision (Optional[int]): Precision to use for the value. value (Optional[Value]): Value assigned to variable value_range (Optional[list]): Acceptable range for value variable_type (str): Indicates image variable. axis_labels (List[str]): Labels to use for rendering axes. axis_units (Optional[List[str]]): Units to use for rendering axes labels. x_min (Optional[float]): Minimum x value of image. x_max (Optional[float]): Maximum x value of image. y_min (Optional[float]): Minimum y value of image. y_max (Optional[float]): Maximum y value of image. x_min_variable (Optional[str]): Scalar variable associated with image minimum x. x_max_variable (Optional[str]): Scalar variable associated with image maximum x. y_min_variable (Optional[str]): Scalar variable associated with image minimum y. y_max_variable (Optional[str]): Scalar variable associated with image maximum y. Example: ``` variable = ImageOutputVariable( name="test", default=np.array([[2 , 1], [1, 4]]), axis_labels=["count_1", "count_2"], ) ``` """ x_min: Optional[float] = None x_max: Optional[float] = None y_min: Optional[float] = None y_max: Optional[float] = None class ScalarInputVariable(InputVariable[Union[float, type(None)]], ScalarVariable): """ Variable used for representing an scalar input. Scalar variables hold float values. Initialization requires name, default, and value_range. Attributes: name (str): Name of the variable. default (Value): Default value assigned to the variable precision (Optional[int]): Precision to use for the value value (Optional[Value]): Value assigned to variable value_range (list): Acceptable range for value variable_type (str): Indicates scalar variable. units (Optional[str]): Units associated with scalar value. parent_variable (Optional[str]): Variable for which this is an attribute. Example: ``` variable = ScalarInputVariable(name="test", default=0.1, value_range=[1, 2]) ``` """ pass class ScalarOutputVariable(OutputVariable[float], ScalarVariable): """ Variable used for representing an scalar output. Scalar variables hold float values. Initialization requires name. Attributes: name (str): Name of the variable. default (Optional[Value]): Default value assigned to the variable. precision (Optional[int]): Precision to use for the value. value (Optional[Value]): Value assigned to variable. value_range (Optional[list]): Acceptable range for value. variable_type (str): Indicates scalar variable. units (Optional[str]): Units associated with scalar value. parent_variable (Optional[str]): Variable for which this is an attribute. Example: ``` variable = ScalarOutputVariable(name="test", default=0.1, value_range=[1, 2]) ``` """ pass class ArrayInputVariable(InputVariable[NumpyNDArray], ArrayVariable): """ Variable used for representing an array input. Attributes: name (str): Name of the variable. default (np.ndarray): Default value assigned to the variable. precision (Optional[int]): Precision to use for the value. value (Optional[Value]): Value assigned to variable value_range (Optional[list]): Acceptable range for value variable_type (str): Indicates array variable. dim_labels (List[str]): Labels to use for dimensions dim_units (Optional[List[str]]): Units to use for dimensions. """ pass class ArrayOutputVariable(OutputVariable[NumpyNDArray], ArrayVariable): """ Attributes: name (str): Name of the variable. default (Optional[np.ndarray]): Default value assigned to the variable. precision (Optional[int]): Precision to use for the value. value (Optional[Value]): Value assigned to variable value_range (Optional[list]): Acceptable range for value variable_type (str): Indicates array variable. dim_labels (List[str]): Labels to use for dimensions dim_units (Optional[List[str]]): Units to use for dimensions. """ pass
[ "logging.getLogger", "pydantic.Field", "typing.TypeVar" ]
[((653, 680), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (670, 680), False, 'import logging\n'), ((3970, 3986), 'typing.TypeVar', 'TypeVar', (['"""Value"""'], {}), "('Value')\n", (3977, 3986), False, 'from typing import Any, List, Union, Optional, Generic, TypeVar\n'), ((4306, 4316), 'pydantic.Field', 'Field', (['...'], {}), '(...)\n', (4311, 4316), False, 'from pydantic import BaseModel, Field, validator\n'), ((5711, 5731), 'pydantic.Field', 'Field', ([], {'alias': '"""range"""'}), "(alias='range')\n", (5716, 5731), False, 'from pydantic import BaseModel, Field, validator\n'), ((7732, 7757), 'pydantic.Field', 'Field', (['...'], {'alias': '"""range"""'}), "(..., alias='range')\n", (7737, 7757), False, 'from pydantic import BaseModel, Field, validator\n')]
from xml.etree import ElementTree as Etree from xml.dom import minidom from elavonvtpv.enum import RequestType from elavonvtpv.Response import Response import datetime import hashlib import requests class Request: def __init__(self, secret, request_type, merchant_id, order_id, currency=None, amount=None, card=None, tss_info=None, settle=True, account=None, channel=None, comment1=None, comment2=None, past_reference=None, authorization_code=None, refund_hash=None, pares=None, mpi=None): """ Defines a Request object :param secret: the shared secret between Elavon and your account :param request_type: RequestType enum object containing the type of the request to be sent to Elavon :param merchant_id: the credentials of the elavon merchant account :param order_id: number unique to the request for all accounts associated with the merchant :param currency: Currency enum object containing the code of the currency to be use in the transaction :param amount: amount of currency to be charged, in the smallest unit of currency possible :param card: CreditCard object containing the data pertaining to the customer's credit card :param tss_info: TssInfo object containing the data pertaining to the anti-fraud system :param settle: flag indicating if the transaction must be settled automatically by Elavon :param account: the sub-account to be used for the request :param channel: Channel enum object indicating the channel by which the transaction is made :param comment1: optional comment to include in the request :param comment2: optional comment to include in the request :param past_reference: reference of the transaction to which this one refers :param authorization_code: authorization code given with the transaction to which this one refers :param refund_hash: hash provided by Elavon, needed to make refunds :param pares: authorization code given with the transaction to which this one refers :param mpi: hash provided by Elavon, needed to make refunds """ self.timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S') self.secret = secret self.request_type = request_type self.merchant_id = merchant_id self.order_id = order_id self.currency = currency self.amount = amount self.card = card self.tss_info = tss_info self.settle = settle self.account = account self.channel = channel self.comment1 = comment1 self.comment2 = comment2 self.past_reference = past_reference self.authorization_code = authorization_code self.refund_hash = refund_hash self.pares = pares self.mpi = mpi def __hash(self): """ Builds the request hash from the data contained within :return: the hash string that will latter be cyphered """ res = "%s.%s.%s.%s.%s." % (str(self.timestamp), str(self.merchant_id), str(self.order_id), str(self.amount), str(self.currency.value)) if self.card: res += "%s" % str(self.card.number) return res.encode('utf-8') def sha1_hash(self): """ returns a secure hash in SHA-1 for this request :return: secure hash in SHA-1 """ sha1_hash = hashlib.sha1(self.__hash()).hexdigest() sha1_hash += ".%s" % self.secret return hashlib.sha1(sha1_hash.encode('utf-8')).hexdigest() # return hashlib.sha1(self.__hash()).hexdigest() def md5_hash(self): """ returns a secure hash in MD5 for this request :return: secure hash in MD5 """ md5_hash = hashlib.md5(self.__hash()).hexdigest() md5_hash += ".%s" % self.secret return hashlib.md5(md5_hash.encode('utf-8')).digest() def __basic_to_etree_element(self): """ creates the basic structure of an Elavon request :return: the basic root element of the request containing those fields that exist en every request type """ if self.request_type == RequestType.verify_enrolled: request_type = '3ds-verifyenrolled' elif self.request_type == RequestType.verify_sig: request_type = '3ds-verifysig' else: request_type = self.request_type.name request = Etree.Element('request') request.set('timestamp', self.timestamp) request.set('type', request_type) merchant_id = Etree.SubElement(request, 'merchantid') merchant_id.text = self.merchant_id if self.account: account = Etree.SubElement(request, 'account') account.text = self.account order_id = Etree.SubElement(request, 'orderid') order_id.text = self.order_id return request def __channel_to_etree_element(self): channel = Etree.Element('channel') channel.text = self.channel.value return channel def __past_reference_to_etree_element(self): past_reference = Etree.Element('pasref') past_reference.text = self.past_reference return past_reference def __pares_to_etree_element(self): pares = Etree.Element('pares') pares.text = self.pares return pares def __authorization_code_to_etree_element(self): authorization_code = Etree.Element('authcode') authorization_code.text = self.authorization_code return authorization_code def __amount_to_etree_element(self): amount = Etree.Element('amount') amount.set('currency', self.currency.value) amount.text = self.amount return amount def __auto_settle_to_etree_element(self): auto_settle = Etree.Element('autosettle') auto_settle.set('flag', '1' if self.settle else '0') return auto_settle def __comments_to_etree_element(self): comments = Etree.Element('comments') if self.comment1: comment1 = Etree.SubElement(comments, 'comment', id='1') comment1.text = self.comment1 if self.comment2: comment2 = Etree.SubElement(comments, 'comment', id='2') comment2.text = self.comment2 return comments def __refund_hash_to_etree_element(self): refundhash = Etree.Element('refundhash') refundhash.text = hashlib.sha1(self.refund_hash.encode('utf-8')).hexdigest() return refundhash def __sh1_hash_to_etree_element(self): sha1_hash = Etree.Element('sha1hash') sha1_hash.text = self.sha1_hash() return sha1_hash def __md5_hash_to_etree_element(self): md5_hash = Etree.Element('md5hash') md5_hash.text = self.md5_hash() return md5_hash def __auth_to_etree(self): request = self.__basic_to_etree_element() if not self.mpi: request.append(self.__channel_to_etree_element()) request.append(self.__amount_to_etree_element()) request.append(self.card.to_etree_element()) if self.mpi: request.append(self.mpi.to_etree_element()) request.append(self.__auto_settle_to_etree_element()) if self.comment1 or self.comment2: request.append(self.__comments_to_etree_element()) if self.tss_info: request.append(self.tss_info.to_etree_element()) request.append(self.__sh1_hash_to_etree_element()) # request.append(self.__md5_hash_to_etree_element()) return Etree.ElementTree(request) def __manual_to_etree(self): request = self.__basic_to_etree_element() request.append(self.__channel_to_etree_element()) request.append(self.__authorization_code_to_etree_element()) request.append(self.__amount_to_etree_element()) request.append(self.card.to_etree_element()) request.append(self.__auto_settle_to_etree_element()) if self.comment1 or self.comment2: request.append(self.__comments_to_etree_element()) if self.tss_info: request.append(self.tss_info.to_etree_element()) request.append(self.__sh1_hash_to_etree_element()) # request.append(self.__md5_hash_to_etree_element()) return Etree.ElementTree(request) def __obt_to_etree(self): request = self.__basic_to_etree_element() request.append(self.card.to_etree_element()) request.append(self.__auto_settle_to_etree_element()) request.append(self.__sh1_hash_to_etree_element()) # request.append(self.__md5_hash_to_etree_element()) return Etree.ElementTree(request) def __offline_to_etree(self): request = self.__basic_to_etree_element() request.append(self.__past_reference_to_etree_element()) request.append(self.__authorization_code_to_etree_element()) request.append(self.__amount_to_etree_element()) request.append(self.card.to_etree_element()) request.append(self.__auto_settle_to_etree_element()) if self.comment1 or self.comment2: request.append(self.__comments_to_etree_element()) if self.tss_info: request.append(self.tss_info.to_etree_element()) request.append(self.__sh1_hash_to_etree_element()) # request.append(self.__md5_hash_to_etree_element()) return Etree.ElementTree(request) def __rebate_to_etree(self): request = self.__basic_to_etree_element() request.append(self.__past_reference_to_etree_element()) request.append(self.__authorization_code_to_etree_element()) request.append(self.__amount_to_etree_element()) request.append(self.__auto_settle_to_etree_element()) if self.comment1 or self.comment2: request.append(self.__comments_to_etree_element()) request.append(self.__sh1_hash_to_etree_element()) request.append(self.__refund_hash_to_etree_element()) return Etree.ElementTree(request) def __void_to_etree(self): request = self.__basic_to_etree_element() request.append(self.__past_reference_to_etree_element()) request.append(self.card.to_etree_element()) request.append(self.__authorization_code_to_etree_element()) if self.comment1 or self.comment2: request.append(self.__comments_to_etree_element()) request.append(self.__sh1_hash_to_etree_element()) # request.append(self.__md5_hash_to_etree_element()) return Etree.ElementTree(request) def __tss_to_etree(self): request = self.__basic_to_etree_element() request.append(self.__amount_to_etree_element()) request.append(self.card.to_etree_element()) request.append(self.__auto_settle_to_etree_element()) if self.comment1 or self.comment2: request.append(self.__comments_to_etree_element()) if self.tss_info: request.append(self.tss_info.to_etree_element()) request.append(self.__sh1_hash_to_etree_element()) # request.append(self.__md5_hash_to_etree_element()) return Etree.ElementTree(request) def __settle_to_etree(self): request = self.__basic_to_etree_element() request.append(self.__past_reference_to_etree_element()) if self.amount and self.currency: request.append(self.__amount_to_etree_element()) request.append(self.__authorization_code_to_etree_element()) if self.comment1 or self.comment2: request.append(self.__comments_to_etree_element()) request.append(self.__sh1_hash_to_etree_element()) # request.append(self.__md5_hash_to_etree_element()) return Etree.ElementTree(request) def __verify_enrolled_to_etree(self): request = self.__basic_to_etree_element() if self.amount and self.currency: request.append(self.__amount_to_etree_element()) request.append(self.card.to_etree_element()) request.append(self.__sh1_hash_to_etree_element()) return Etree.ElementTree(request) def __verify_sig_to_etree(self): request = self.__basic_to_etree_element() if self.amount and self.currency: request.append(self.__amount_to_etree_element()) request.append(self.card.to_etree_element()) request.append(self.__pares_to_etree_element()) request.append(self.__sh1_hash_to_etree_element()) return Etree.ElementTree(request) def __to_etree(self): if self.request_type is RequestType.auth: return self.__auth_to_etree() elif self.request_type is RequestType.manual: return self.__manual_to_etree() elif self.request_type is RequestType.obt: return self.__obt_to_etree() elif self.request_type is RequestType.offline: return self.__offline_to_etree() elif self.request_type is RequestType.rebate: return self.__rebate_to_etree() elif self.request_type is RequestType.void: return self.__void_to_etree() elif self.request_type is RequestType.TSS: return self.__tss_to_etree() elif self.request_type is RequestType.settle: return self.__settle_to_etree() elif self.request_type is RequestType.verify_enrolled: return self.__verify_enrolled_to_etree() elif self.request_type is RequestType.verify_sig: return self.__verify_sig_to_etree() def to_xml_string(self): binary = Etree.tostring(self.__to_etree().getroot(), encoding='utf8', method='xml') return binary.decode('utf-8') def to_pretty_xml(self): return minidom.parseString(self.to_xml_string()).toprettyxml() def send(self, url): headers = {'Content-Type': 'application/xml'} response = requests.post(url=url, data=self.to_pretty_xml(), headers=headers) return Response(response.content)
[ "xml.etree.ElementTree.Element", "datetime.datetime.now", "xml.etree.ElementTree.ElementTree", "xml.etree.ElementTree.SubElement", "elavonvtpv.Response.Response" ]
[((4511, 4535), 'xml.etree.ElementTree.Element', 'Etree.Element', (['"""request"""'], {}), "('request')\n", (4524, 4535), True, 'from xml.etree import ElementTree as Etree\n'), ((4650, 4689), 'xml.etree.ElementTree.SubElement', 'Etree.SubElement', (['request', '"""merchantid"""'], {}), "(request, 'merchantid')\n", (4666, 4689), True, 'from xml.etree import ElementTree as Etree\n'), ((4879, 4915), 'xml.etree.ElementTree.SubElement', 'Etree.SubElement', (['request', '"""orderid"""'], {}), "(request, 'orderid')\n", (4895, 4915), True, 'from xml.etree import ElementTree as Etree\n'), ((5040, 5064), 'xml.etree.ElementTree.Element', 'Etree.Element', (['"""channel"""'], {}), "('channel')\n", (5053, 5064), True, 'from xml.etree import ElementTree as Etree\n'), ((5207, 5230), 'xml.etree.ElementTree.Element', 'Etree.Element', (['"""pasref"""'], {}), "('pasref')\n", (5220, 5230), True, 'from xml.etree import ElementTree as Etree\n'), ((5370, 5392), 'xml.etree.ElementTree.Element', 'Etree.Element', (['"""pares"""'], {}), "('pares')\n", (5383, 5392), True, 'from xml.etree import ElementTree as Etree\n'), ((5531, 5556), 'xml.etree.ElementTree.Element', 'Etree.Element', (['"""authcode"""'], {}), "('authcode')\n", (5544, 5556), True, 'from xml.etree import ElementTree as Etree\n'), ((5710, 5733), 'xml.etree.ElementTree.Element', 'Etree.Element', (['"""amount"""'], {}), "('amount')\n", (5723, 5733), True, 'from xml.etree import ElementTree as Etree\n'), ((5913, 5940), 'xml.etree.ElementTree.Element', 'Etree.Element', (['"""autosettle"""'], {}), "('autosettle')\n", (5926, 5940), True, 'from xml.etree import ElementTree as Etree\n'), ((6093, 6118), 'xml.etree.ElementTree.Element', 'Etree.Element', (['"""comments"""'], {}), "('comments')\n", (6106, 6118), True, 'from xml.etree import ElementTree as Etree\n'), ((6488, 6515), 'xml.etree.ElementTree.Element', 'Etree.Element', (['"""refundhash"""'], {}), "('refundhash')\n", (6501, 6515), True, 'from xml.etree import ElementTree as Etree\n'), ((6693, 6718), 'xml.etree.ElementTree.Element', 'Etree.Element', (['"""sha1hash"""'], {}), "('sha1hash')\n", (6706, 6718), True, 'from xml.etree import ElementTree as Etree\n'), ((6851, 6875), 'xml.etree.ElementTree.Element', 'Etree.Element', (['"""md5hash"""'], {}), "('md5hash')\n", (6864, 6875), True, 'from xml.etree import ElementTree as Etree\n'), ((7688, 7714), 'xml.etree.ElementTree.ElementTree', 'Etree.ElementTree', (['request'], {}), '(request)\n', (7705, 7714), True, 'from xml.etree import ElementTree as Etree\n'), ((8427, 8453), 'xml.etree.ElementTree.ElementTree', 'Etree.ElementTree', (['request'], {}), '(request)\n', (8444, 8453), True, 'from xml.etree import ElementTree as Etree\n'), ((8786, 8812), 'xml.etree.ElementTree.ElementTree', 'Etree.ElementTree', (['request'], {}), '(request)\n', (8803, 8812), True, 'from xml.etree import ElementTree as Etree\n'), ((9533, 9559), 'xml.etree.ElementTree.ElementTree', 'Etree.ElementTree', (['request'], {}), '(request)\n', (9550, 9559), True, 'from xml.etree import ElementTree as Etree\n'), ((10140, 10166), 'xml.etree.ElementTree.ElementTree', 'Etree.ElementTree', (['request'], {}), '(request)\n', (10157, 10166), True, 'from xml.etree import ElementTree as Etree\n'), ((10678, 10704), 'xml.etree.ElementTree.ElementTree', 'Etree.ElementTree', (['request'], {}), '(request)\n', (10695, 10704), True, 'from xml.etree import ElementTree as Etree\n'), ((11287, 11313), 'xml.etree.ElementTree.ElementTree', 'Etree.ElementTree', (['request'], {}), '(request)\n', (11304, 11313), True, 'from xml.etree import ElementTree as Etree\n'), ((11877, 11903), 'xml.etree.ElementTree.ElementTree', 'Etree.ElementTree', (['request'], {}), '(request)\n', (11894, 11903), True, 'from xml.etree import ElementTree as Etree\n'), ((12228, 12254), 'xml.etree.ElementTree.ElementTree', 'Etree.ElementTree', (['request'], {}), '(request)\n', (12245, 12254), True, 'from xml.etree import ElementTree as Etree\n'), ((12630, 12656), 'xml.etree.ElementTree.ElementTree', 'Etree.ElementTree', (['request'], {}), '(request)\n', (12647, 12656), True, 'from xml.etree import ElementTree as Etree\n'), ((14112, 14138), 'elavonvtpv.Response.Response', 'Response', (['response.content'], {}), '(response.content)\n', (14120, 14138), False, 'from elavonvtpv.Response import Response\n'), ((4782, 4818), 'xml.etree.ElementTree.SubElement', 'Etree.SubElement', (['request', '"""account"""'], {}), "(request, 'account')\n", (4798, 4818), True, 'from xml.etree import ElementTree as Etree\n'), ((6169, 6214), 'xml.etree.ElementTree.SubElement', 'Etree.SubElement', (['comments', '"""comment"""'], {'id': '"""1"""'}), "(comments, 'comment', id='1')\n", (6185, 6214), True, 'from xml.etree import ElementTree as Etree\n'), ((6306, 6351), 'xml.etree.ElementTree.SubElement', 'Etree.SubElement', (['comments', '"""comment"""'], {'id': '"""2"""'}), "(comments, 'comment', id='2')\n", (6322, 6351), True, 'from xml.etree import ElementTree as Etree\n'), ((2204, 2227), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2225, 2227), False, 'import datetime\n')]
from . import DATA_DIR import pandas as pd import xarray as xr import numpy as np from pathlib import Path import csv REMIND_ELEC_MARKETS = (DATA_DIR / "remind_electricity_markets.csv") REMIND_ELEC_EFFICIENCIES = (DATA_DIR / "remind_electricity_efficiencies.csv") REMIND_ELEC_EMISSIONS = (DATA_DIR / "remind_electricity_emissions.csv") GAINS_TO_REMIND_FILEPATH = (DATA_DIR / "GAINStoREMINDtechmap.csv") class RemindDataCollection: """ Class that extracts data from REMIND output files. :ivar scenario: name of a Remind scenario :vartype scenario: str """ def __init__(self, scenario, year, filepath_remind_files): self.scenario = scenario self.year = year self.filepath_remind_files = filepath_remind_files self.data = self.get_remind_data() self.gains_data = self.get_gains_data() self.electricity_market_labels = self.get_remind_electricity_market_labels() self.electricity_efficiency_labels = ( self.get_remind_electricity_efficiency_labels() ) self.electricity_emission_labels = self.get_remind_electricity_emission_labels() self.rev_electricity_market_labels = self.get_rev_electricity_market_labels() self.rev_electricity_efficiency_labels = ( self.get_rev_electricity_efficiency_labels() ) self.electricity_markets = self.get_remind_electricity_markets() self.electricity_efficiencies = self.get_remind_electricity_efficiencies() self.electricity_emissions = self.get_remind_electricity_emissions() def get_remind_electricity_emission_labels(self): """ Loads a csv file into a dictionary. This dictionary contains labels of electricity emissions in Remind. :return: dictionary that contains emission names equivalence :rtype: dict """ with open(REMIND_ELEC_EMISSIONS) as f: return dict(filter(None, csv.reader(f, delimiter=";"))) def get_remind_electricity_market_labels(self): """ Loads a csv file into a dictionary. This dictionary contains labels of electricity markets in Remind. :return: dictionary that contains market names equivalence :rtype: dict """ with open(REMIND_ELEC_MARKETS) as f: return dict(filter(None, csv.reader(f, delimiter=";"))) def get_remind_electricity_efficiency_labels(self): """ Loads a csv file into a dictionary. This dictionary contains labels of electricity technologies efficiency in Remind. :return: dictionary that contains market names equivalence :rtype: dict """ with open(REMIND_ELEC_EFFICIENCIES) as f: return dict(filter(None, csv.reader(f, delimiter=";"))) def get_rev_electricity_market_labels(self): return {v: k for k, v in self.electricity_market_labels.items()} def get_rev_electricity_efficiency_labels(self): return {v: k for k, v in self.electricity_efficiency_labels.items()} def get_remind_data(self): """ Read the REMIND csv result file and return an `xarray` with dimensions: * region * variable * year :return: an multi-dimensional array with Remind data :rtype: xarray.core.dataarray.DataArray """ filename = self.scenario + ".mif" filepath = Path(self.filepath_remind_files) / filename df = pd.read_csv( filepath, sep=";", index_col=["Region", "Variable", "Unit"] ).drop(columns=["Model", "Scenario", "Unnamed: 24"]) df.columns = df.columns.astype(int) # Filter the dataframe df = df.loc[ (df.index.get_level_values("Variable").str.contains("SE")) | (df.index.get_level_values("Variable").str.contains("Tech")) ] variables = df.index.get_level_values("Variable").unique() regions = df.index.get_level_values("Region").unique() years = df.columns array = xr.DataArray( np.zeros((len(variables), len(regions), len(years), 1)), coords=[variables, regions, years, np.arange(1)], dims=["variable", "region", "year", "value"], ) for r in regions: val = df.loc[(df.index.get_level_values("Region") == r), :] array.loc[dict(region=r, value=0)] = val return array def get_gains_data(self): """ Read the GAINS emissions csv file and return an `xarray` with dimensions: * region * pollutant * sector * year :return: an multi-dimensional array with GAINS emissions data :rtype: xarray.core.dataarray.DataArray """ filename = "GAINS emission factors.csv" filepath = Path(self.filepath_remind_files) / filename gains_emi = pd.read_csv( filepath, skiprows=4, names=["year", "region", "GAINS", "pollutant", "scenario", "factor"], ) gains_emi["unit"] = "Mt/TWa" gains_emi = gains_emi[gains_emi.scenario == "SSP2"] sector_mapping = pd.read_csv(GAINS_TO_REMIND_FILEPATH).drop( ["noef", "elasticity"], axis=1 ) gains_emi = ( gains_emi.join(sector_mapping.set_index("GAINS"), on="GAINS") .dropna() .drop(["scenario", "REMIND"], axis=1) .pivot_table( index=["region", "GAINS", "pollutant", "unit"], values="factor", columns="year", ) ) regions = gains_emi.index.get_level_values("region").unique() years = gains_emi.columns.values pollutants = gains_emi.index.get_level_values("pollutant").unique() sectors = gains_emi.index.get_level_values("GAINS").unique() array = xr.DataArray( np.zeros((len(pollutants), len(sectors), len(regions), len(years), 1)), coords=[pollutants, sectors, regions, years, np.arange(1)], dims=["pollutant", "sector", "region", "year", "value"], ) for r in regions: for s in sectors: val = gains_emi.loc[ (gains_emi.index.get_level_values("region") == r) & (gains_emi.index.get_level_values("GAINS") == s), :, ] array.loc[dict(region=r, sector=s, value=0)] = val return array / 8760 # per TWha --> per TWh def get_remind_electricity_markets(self, drop_hydrogen=True): """ This method retrieves the market share for each electricity-producing technology, for a specified year, for each region provided by REMIND. Electricity production from hydrogen can be removed from the mix (unless specified, it is removed). :param drop_hydrogen: removes hydrogen from the region-specific electricity mix if `True`. :type drop_hydrogen: bool :return: an multi-dimensional array with electricity technologies market share for a given year, for all regions. :rtype: xarray.core.dataarray.DataArray """ # If hydrogen is not to be considered, it is removed from the technologies labels list if drop_hydrogen: list_technologies = [ l for l in list(self.electricity_market_labels.values()) if "Hydrogen" not in l ] else: list_technologies = list(self.electricity_market_labels.values()) # If the year specified is not contained within the range of years given by REMIND if ( self.year < self.data.year.values.min() or self.year > self.data.year.values.max() ): raise KeyError("year not valid, must be between 2005 and 2150") # Otherwise, if the year specified corresponds exactly to a year given by REMIND elif self.year in self.data.coords["year"]: # The contribution of each technology, for a specified year, for a specified region is normalized to 1. return self.data.loc[list_technologies, :, self.year] / self.data.loc[ list_technologies, :, self.year ].groupby("region").sum(axis=0) # Finally, if the specified year falls in between two periods provided by REMIND else: # Interpolation between two periods data_to_interp_from = self.data.loc[ list_technologies, :, : ] / self.data.loc[list_technologies, :, :].groupby("region").sum(axis=0) return data_to_interp_from.interp(year=self.year) def get_remind_electricity_efficiencies(self, drop_hydrogen=True): """ This method retrieves efficiency values for electricity-producing technology, for a specified year, for each region provided by REMIND. Electricity production from hydrogen can be removed from the mix (unless specified, it is removed). :param drop_hydrogen: removes hydrogen from the region-specific electricity mix if `True`. :type drop_hydrogen: bool :return: an multi-dimensional array with electricity technologies market share for a given year, for all regions. :rtype: xarray.core.dataarray.DataArray """ # If hydrogen is not to be considered, it is removed from the technologies labels list if drop_hydrogen: list_technologies = [ l for l in list(self.electricity_efficiency_labels.values()) if "Hydrogen" not in l ] else: list_technologies = list(self.electricity_efficiency_labels.values()) # If the year specified is not contained within the range of years given by REMIND if ( self.year < self.data.year.values.min() or self.year > self.data.year.values.max() ): raise KeyError("year not valid, must be between 2005 and 2150") # Otherwise, if the year specified corresponds exactly to a year given by REMIND elif self.year in self.data.coords["year"]: # The contribution of each technologies, for a specified year, for a specified region is normalized to 1. return ( self.data.loc[list_technologies, :, self.year] / 100 ) # Percentage to ratio # Finally, if the specified year falls in between two periods provided by REMIND else: # Interpolation between two periods data_to_interp_from = self.data.loc[list_technologies, :, :] return ( data_to_interp_from.interp(year=self.year) / 100 ) # Percentage to ratio def get_remind_electricity_emissions(self): """ This method retrieves emission values for electricity-producing technology, for a specified year, for each region provided by REMIND. :return: an multi-dimensional array with emissions for different technologies for a given year, for all regions. :rtype: xarray.core.dataarray.DataArray """ # If the year specified is not contained within the range of years given by REMIND if ( self.year < self.gains_data.year.values.min() or self.year > self.gains_data.year.values.max() ): raise KeyError("year not valid, must be between 2005 and 2150") # Otherwise, if the year specified corresponds exactly to a year given by REMIND elif self.year in self.gains_data.coords["year"]: # The contribution of each technologies, for a specified year, for a specified region is normalized to 1. return self.gains_data.loc[dict(year=self.year, value=0)] # Finally, if the specified year falls in between two periods provided by REMIND else: # Interpolation between two periods return self.gains_data.loc[dict(value=0)].interp(year=self.year)
[ "csv.reader", "numpy.arange", "pandas.read_csv", "pathlib.Path" ]
[((4893, 5000), 'pandas.read_csv', 'pd.read_csv', (['filepath'], {'skiprows': '(4)', 'names': "['year', 'region', 'GAINS', 'pollutant', 'scenario', 'factor']"}), "(filepath, skiprows=4, names=['year', 'region', 'GAINS',\n 'pollutant', 'scenario', 'factor'])\n", (4904, 5000), True, 'import pandas as pd\n'), ((3419, 3451), 'pathlib.Path', 'Path', (['self.filepath_remind_files'], {}), '(self.filepath_remind_files)\n', (3423, 3451), False, 'from pathlib import Path\n'), ((4828, 4860), 'pathlib.Path', 'Path', (['self.filepath_remind_files'], {}), '(self.filepath_remind_files)\n', (4832, 4860), False, 'from pathlib import Path\n'), ((3476, 3548), 'pandas.read_csv', 'pd.read_csv', (['filepath'], {'sep': '""";"""', 'index_col': "['Region', 'Variable', 'Unit']"}), "(filepath, sep=';', index_col=['Region', 'Variable', 'Unit'])\n", (3487, 3548), True, 'import pandas as pd\n'), ((5167, 5204), 'pandas.read_csv', 'pd.read_csv', (['GAINS_TO_REMIND_FILEPATH'], {}), '(GAINS_TO_REMIND_FILEPATH)\n', (5178, 5204), True, 'import pandas as pd\n'), ((1954, 1982), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '""";"""'}), "(f, delimiter=';')\n", (1964, 1982), False, 'import csv\n'), ((2351, 2379), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '""";"""'}), "(f, delimiter=';')\n", (2361, 2379), False, 'import csv\n'), ((2773, 2801), 'csv.reader', 'csv.reader', (['f'], {'delimiter': '""";"""'}), "(f, delimiter=';')\n", (2783, 2801), False, 'import csv\n'), ((4179, 4191), 'numpy.arange', 'np.arange', (['(1)'], {}), '(1)\n', (4188, 4191), True, 'import numpy as np\n'), ((6041, 6053), 'numpy.arange', 'np.arange', (['(1)'], {}), '(1)\n', (6050, 6053), True, 'import numpy as np\n')]
"""baseline Revision ID: 398d6252cdce Revises: Create Date: 2020-03-12 10:10:15.689958 """ import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '398d6252cdce' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('jumio_verification', sa.Column('row_id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('verification_id', mysql.VARCHAR(length=255), nullable=True), sa.Column('username', mysql.VARCHAR(length=255), nullable=True), sa.Column('jumio_reference_id', mysql.VARCHAR(length=255), nullable=True), sa.Column('user_reference_id', mysql.VARCHAR(length=255), nullable=True), sa.Column('redirect_url', mysql.VARCHAR(length=1024), nullable=True), sa.Column('transaction_status', mysql.VARCHAR(length=255), nullable=True), sa.Column('verification_status', mysql.VARCHAR(length=255), nullable=True), sa.Column('reject_reason', sa.JSON(), nullable=True), sa.Column('transaction_date', mysql.TIMESTAMP(), nullable=True), sa.Column('callback_date', mysql.TIMESTAMP(), nullable=True), sa.Column('created_at', mysql.TIMESTAMP(), nullable=True), sa.PrimaryKeyConstraint('row_id') ) op.create_table('verification', sa.Column('id', mysql.VARCHAR(length=225), nullable=False), sa.Column('verification_type', mysql.VARCHAR(length=225), nullable=False), sa.Column('entity_id', mysql.VARCHAR(length=255), nullable=True), sa.Column('status', mysql.VARCHAR(length=255), nullable=True), sa.Column('requestee', mysql.VARCHAR(length=255), nullable=True), sa.Column('reject_reason', mysql.VARCHAR(length=1024), nullable=True), sa.Column('created_at', mysql.TIMESTAMP(), nullable=True), sa.Column('updated_at', mysql.TIMESTAMP(), nullable=True), sa.PrimaryKeyConstraint('id', 'verification_type') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('verification') op.drop_table('jumio_verification') # ### end Alembic commands ###
[ "sqlalchemy.dialects.mysql.TIMESTAMP", "alembic.op.drop_table", "sqlalchemy.dialects.mysql.VARCHAR", "sqlalchemy.PrimaryKeyConstraint", "sqlalchemy.Integer", "sqlalchemy.JSON" ]
[((2114, 2143), 'alembic.op.drop_table', 'op.drop_table', (['"""verification"""'], {}), "('verification')\n", (2127, 2143), False, 'from alembic import op\n'), ((2148, 2183), 'alembic.op.drop_table', 'op.drop_table', (['"""jumio_verification"""'], {}), "('jumio_verification')\n", (2161, 2183), False, 'from alembic import op\n'), ((1302, 1335), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""row_id"""'], {}), "('row_id')\n", (1325, 1335), True, 'import sqlalchemy as sa\n'), ((1933, 1983), 'sqlalchemy.PrimaryKeyConstraint', 'sa.PrimaryKeyConstraint', (['"""id"""', '"""verification_type"""'], {}), "('id', 'verification_type')\n", (1956, 1983), True, 'import sqlalchemy as sa\n'), ((456, 468), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (466, 468), True, 'import sqlalchemy as sa\n'), ((540, 565), 'sqlalchemy.dialects.mysql.VARCHAR', 'mysql.VARCHAR', ([], {'length': '(255)'}), '(length=255)\n', (553, 565), False, 'from sqlalchemy.dialects import mysql\n'), ((609, 634), 'sqlalchemy.dialects.mysql.VARCHAR', 'mysql.VARCHAR', ([], {'length': '(255)'}), '(length=255)\n', (622, 634), False, 'from sqlalchemy.dialects import mysql\n'), ((688, 713), 'sqlalchemy.dialects.mysql.VARCHAR', 'mysql.VARCHAR', ([], {'length': '(255)'}), '(length=255)\n', (701, 713), False, 'from sqlalchemy.dialects import mysql\n'), ((766, 791), 'sqlalchemy.dialects.mysql.VARCHAR', 'mysql.VARCHAR', ([], {'length': '(255)'}), '(length=255)\n', (779, 791), False, 'from sqlalchemy.dialects import mysql\n'), ((839, 865), 'sqlalchemy.dialects.mysql.VARCHAR', 'mysql.VARCHAR', ([], {'length': '(1024)'}), '(length=1024)\n', (852, 865), False, 'from sqlalchemy.dialects import mysql\n'), ((919, 944), 'sqlalchemy.dialects.mysql.VARCHAR', 'mysql.VARCHAR', ([], {'length': '(255)'}), '(length=255)\n', (932, 944), False, 'from sqlalchemy.dialects import mysql\n'), ((999, 1024), 'sqlalchemy.dialects.mysql.VARCHAR', 'mysql.VARCHAR', ([], {'length': '(255)'}), '(length=255)\n', (1012, 1024), False, 'from sqlalchemy.dialects import mysql\n'), ((1073, 1082), 'sqlalchemy.JSON', 'sa.JSON', ([], {}), '()\n', (1080, 1082), True, 'import sqlalchemy as sa\n'), ((1134, 1151), 'sqlalchemy.dialects.mysql.TIMESTAMP', 'mysql.TIMESTAMP', ([], {}), '()\n', (1149, 1151), False, 'from sqlalchemy.dialects import mysql\n'), ((1200, 1217), 'sqlalchemy.dialects.mysql.TIMESTAMP', 'mysql.TIMESTAMP', ([], {}), '()\n', (1215, 1217), False, 'from sqlalchemy.dialects import mysql\n'), ((1263, 1280), 'sqlalchemy.dialects.mysql.TIMESTAMP', 'mysql.TIMESTAMP', ([], {}), '()\n', (1278, 1280), False, 'from sqlalchemy.dialects import mysql\n'), ((1398, 1423), 'sqlalchemy.dialects.mysql.VARCHAR', 'mysql.VARCHAR', ([], {'length': '(225)'}), '(length=225)\n', (1411, 1423), False, 'from sqlalchemy.dialects import mysql\n'), ((1477, 1502), 'sqlalchemy.dialects.mysql.VARCHAR', 'mysql.VARCHAR', ([], {'length': '(225)'}), '(length=225)\n', (1490, 1502), False, 'from sqlalchemy.dialects import mysql\n'), ((1548, 1573), 'sqlalchemy.dialects.mysql.VARCHAR', 'mysql.VARCHAR', ([], {'length': '(255)'}), '(length=255)\n', (1561, 1573), False, 'from sqlalchemy.dialects import mysql\n'), ((1615, 1640), 'sqlalchemy.dialects.mysql.VARCHAR', 'mysql.VARCHAR', ([], {'length': '(255)'}), '(length=255)\n', (1628, 1640), False, 'from sqlalchemy.dialects import mysql\n'), ((1685, 1710), 'sqlalchemy.dialects.mysql.VARCHAR', 'mysql.VARCHAR', ([], {'length': '(255)'}), '(length=255)\n', (1698, 1710), False, 'from sqlalchemy.dialects import mysql\n'), ((1759, 1785), 'sqlalchemy.dialects.mysql.VARCHAR', 'mysql.VARCHAR', ([], {'length': '(1024)'}), '(length=1024)\n', (1772, 1785), False, 'from sqlalchemy.dialects import mysql\n'), ((1831, 1848), 'sqlalchemy.dialects.mysql.TIMESTAMP', 'mysql.TIMESTAMP', ([], {}), '()\n', (1846, 1848), False, 'from sqlalchemy.dialects import mysql\n'), ((1894, 1911), 'sqlalchemy.dialects.mysql.TIMESTAMP', 'mysql.TIMESTAMP', ([], {}), '()\n', (1909, 1911), False, 'from sqlalchemy.dialects import mysql\n')]
import pickle import torch import numpy as np from attention import make_model SRC_STOI = None TARGET_ITOS = None TRG_EOS_TOKEN = None TRG_SOS_TOKEN = None def load_metadata(meta_path): global SRC_STOI, TARGET_ITOS, TRG_EOS_TOKEN, TRG_SOS_TOKEN with open(meta_path, 'rb') as f: metadata = pickle.load(f) SRC_STOI = metadata['src_stoi'] TARGET_ITOS = metadata['target_itos'] TRG_EOS_TOKEN= metadata['trg_eos_index'] TRG_SOS_TOKEN = metadata['trg_sos_index'] def greedy_decode(model, src, src_mask, src_lengths, max_len=100, sos_index=1, eos_index=None): """Greedily decode a sentence.""" with torch.no_grad(): encoder_hidden, encoder_final = model.encode(src, src_mask, src_lengths) prev_y = torch.ones(1, 1).fill_(sos_index).type_as(src) trg_mask = torch.ones_like(prev_y) output = [] hidden = None for i in range(max_len): with torch.no_grad(): out, hidden, pre_output = model.decode( encoder_hidden, encoder_final, src_mask, prev_y, trg_mask, hidden) # we predict from the pre-output layer, which is # a combination of Decoder state, prev emb, and context prob = model.generator(pre_output[:, -1]) _, next_word = torch.max(prob, dim=1) next_word = next_word.data.item() output.append(next_word) prev_y = torch.ones(1, 1).type_as(src).fill_(next_word) output = np.array(output) # cut off everything starting from </s> # (only when eos_index provided) if eos_index is not None: first_eos = np.where(output==eos_index)[0] if len(first_eos) > 0: output = output[:first_eos[0]] return output def lookup_words(x, vocab=None): if vocab is not None: x = [vocab[i] for i in x] return [str(t) for t in x] def inference_logic(src, model): print('inference logic') hypotheses = [] src_lengths = [len(src)] src_index = [] for i in src: src_index.append(SRC_STOI[i]) src = torch.LongTensor(src_index) src = src.unsqueeze(0) src_mask = torch.ones(src_lengths) > 0 src_lengths = torch.LongTensor(src_lengths) pred = greedy_decode( model, src, src_mask, src_lengths, max_len=25, sos_index=TRG_SOS_TOKEN, eos_index=TRG_EOS_TOKEN, ) hypotheses.append(pred) return hypotheses def translate_sentence(german_sentence, weights_path, metadata_path): # Load model metadata print('loading metadata') load_metadata(metadata_path) # Load model global SRC_STOI, TARGET_ITOS print('loading model') model = make_model(weights_path, len(SRC_STOI), len(TARGET_ITOS)) german_sentence = german_sentence.split() hypotheses = inference_logic(german_sentence, model) hypotheses = [lookup_words(x, TARGET_ITOS) for x in hypotheses] hypotheses = [" ".join(x) for x in hypotheses] return hypotheses[0]
[ "torch.ones_like", "numpy.where", "torch.LongTensor", "torch.max", "pickle.load", "numpy.array", "torch.no_grad", "torch.ones" ]
[((1476, 1492), 'numpy.array', 'np.array', (['output'], {}), '(output)\n', (1484, 1492), True, 'import numpy as np\n'), ((2095, 2122), 'torch.LongTensor', 'torch.LongTensor', (['src_index'], {}), '(src_index)\n', (2111, 2122), False, 'import torch\n'), ((2212, 2241), 'torch.LongTensor', 'torch.LongTensor', (['src_lengths'], {}), '(src_lengths)\n', (2228, 2241), False, 'import torch\n'), ((311, 325), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (322, 325), False, 'import pickle\n'), ((641, 656), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (654, 656), False, 'import torch\n'), ((822, 845), 'torch.ones_like', 'torch.ones_like', (['prev_y'], {}), '(prev_y)\n', (837, 845), False, 'import torch\n'), ((1296, 1318), 'torch.max', 'torch.max', (['prob'], {'dim': '(1)'}), '(prob, dim=1)\n', (1305, 1318), False, 'import torch\n'), ((2166, 2189), 'torch.ones', 'torch.ones', (['src_lengths'], {}), '(src_lengths)\n', (2176, 2189), False, 'import torch\n'), ((924, 939), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (937, 939), False, 'import torch\n'), ((1630, 1659), 'numpy.where', 'np.where', (['(output == eos_index)'], {}), '(output == eos_index)\n', (1638, 1659), True, 'import numpy as np\n'), ((756, 772), 'torch.ones', 'torch.ones', (['(1)', '(1)'], {}), '(1, 1)\n', (766, 772), False, 'import torch\n'), ((1411, 1427), 'torch.ones', 'torch.ones', (['(1)', '(1)'], {}), '(1, 1)\n', (1421, 1427), False, 'import torch\n')]
from datetime import datetime from getopt import GetoptError, getopt from socket import AF_INET, SOCK_STREAM, socket as Socket from sys import stderr from typing import List, NoReturn from ..io import DVRIPClient from ..message import EPOCH from . import EX_USAGE, guard, prog_connect def usage() -> NoReturn: print('Usage: {} log [-s START] [-e END]'.format(prog_connect()), file=stderr) exit(EX_USAGE) def run(host: str, serv: int, username: str, password: str, args: List[str] ) -> None: try: opts, args = getopt(args, 's:e:') except GetoptError: usage() if args: usage() start = EPOCH end = datetime.now() for opt, arg in opts: if opt == '-s': from dateparser import parse # type: ignore start = parse(arg) if start is None: usage() if opt == '-e': from dateparser import parse # type: ignore end = parse(arg) if end is None: usage() conn = DVRIPClient(Socket(AF_INET, SOCK_STREAM)) conn.connect((host, serv), username, password) try: for entry in conn.log(start=start, end=end): print('{:>8} {} {:>12} {}' .format(entry.number, entry.time.isoformat(), entry.type.name.lower(), entry.data)) finally: conn.logout() def main() -> None: from sys import argv from . import host, serv, username, password if host() is None: usage() guard(run, host(), serv(), username(), password(), argv[1:])
[ "datetime.datetime.now", "getopt.getopt", "socket.socket", "dateparser.parse" ]
[((659, 673), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (671, 673), False, 'from datetime import datetime\n'), ((564, 584), 'getopt.getopt', 'getopt', (['args', '"""s:e:"""'], {}), "(args, 's:e:')\n", (570, 584), False, 'from getopt import GetoptError, getopt\n'), ((956, 984), 'socket.socket', 'Socket', (['AF_INET', 'SOCK_STREAM'], {}), '(AF_INET, SOCK_STREAM)\n', (962, 984), True, 'from socket import AF_INET, SOCK_STREAM, socket as Socket\n'), ((774, 784), 'dateparser.parse', 'parse', (['arg'], {}), '(arg)\n', (779, 784), False, 'from dateparser import parse\n'), ((893, 903), 'dateparser.parse', 'parse', (['arg'], {}), '(arg)\n', (898, 903), False, 'from dateparser import parse\n')]
"""Create the docker image for running twentyquestions. See ``python dockerize.py --help`` for more information. """ import logging import subprocess import click from backend import settings logger = logging.getLogger(__name__) @click.command( context_settings={ 'help_option_names': ['-h', '--help'] }) def dockerize(): """Create the docker image for running twentyquestions. Create the docker image for running twentyquestions. The created image will be tagged 'twentyquestions'. """ local_env = settings.ENVS['local'] registry = settings.CONTAINER_REGISTRY_URL docker_repo = settings.CONTAINER_REGISTRY_USER image_name = settings.CONTAINER_REGISTRY_IMAGE_NAME # build the docker image subprocess.run([ 'docker', 'build', '--tag', f'{registry}/{docker_repo}/{image_name}:{local_env}', '--file', settings.DOCKERFILE, '.' ]) if __name__ == '__main__': dockerize()
[ "logging.getLogger", "subprocess.run", "click.command" ]
[((207, 234), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (224, 234), False, 'import logging\n'), ((238, 309), 'click.command', 'click.command', ([], {'context_settings': "{'help_option_names': ['-h', '--help']}"}), "(context_settings={'help_option_names': ['-h', '--help']})\n", (251, 309), False, 'import click\n'), ((756, 898), 'subprocess.run', 'subprocess.run', (["['docker', 'build', '--tag',\n f'{registry}/{docker_repo}/{image_name}:{local_env}', '--file',\n settings.DOCKERFILE, '.']"], {}), "(['docker', 'build', '--tag',\n f'{registry}/{docker_repo}/{image_name}:{local_env}', '--file',\n settings.DOCKERFILE, '.'])\n", (770, 898), False, 'import subprocess\n')]
from django.core.urlresolvers import reverse from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.contrib import messages from django.db.models import Q from django.http import HttpResponseRedirect, Http404 from django.views.generic import FormView, RedirectView, TemplateView from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.utils.dateparse import parse_datetime from braces.views import UserFormKwargsMixin import logging from allauth.account.forms import LoginForm, SignupForm from datetime import timedelta import json from .models import Event, Series, PublicEvent, TemporaryRegistration, TemporaryEventRegistration, Invoice, CashPaymentRecord from .forms import ClassChoiceForm, RegistrationContactForm, DoorAmountForm from .constants import getConstant, REG_VALIDATION_STR from .signals import post_student_info, request_discounts, apply_discount, apply_addons, apply_price_adjustments from .mixins import FinancialContextMixin, EventOrderMixin, SiteHistoryMixin # Define logger for this file logger = logging.getLogger(__name__) class RegistrationOfflineView(TemplateView): ''' If registration is offline, just say so. ''' template_name = 'core/registration/registration_offline.html' class ClassRegistrationReferralView(RedirectView): def get(self,request,*args,**kwargs): # Always redirect to the classes page self.url = reverse('registration') # Voucher IDs are used for the referral program. # Marketing IDs are used for tracking click-through registrations. # They are put directly into session data immediately. voucher_id = kwargs.pop('voucher_id',None) marketing_id = kwargs.pop('marketing_id',None) if marketing_id or voucher_id: ''' Put these things into the session data. ''' regSession = self.request.session.get(REG_VALIDATION_STR, {}) regSession['voucher_id'] = voucher_id or regSession.get('voucher_id',None) regSession['marketing_id'] = marketing_id or regSession.get('marketing_id',None) self.request.session[REG_VALIDATION_STR] = regSession return super(ClassRegistrationReferralView,self).get(request,*args,**kwargs) class ClassRegistrationView(FinancialContextMixin, EventOrderMixin, SiteHistoryMixin, FormView): ''' This is the main view that is called from the class registration page. ''' form_class = ClassChoiceForm template_name = 'core/registration/event_registration.html' def get(self, request, *args, **kwargs): ''' Check that registration is online before proceeding ''' regonline = getConstant('registration__registrationEnabled') if not regonline: return HttpResponseRedirect(reverse('registrationOffline')) return super(ClassRegistrationView,self).get(request,*args,**kwargs) def get_context_data(self,**kwargs): ''' Add the event and series listing data ''' context = self.get_listing() context['showDescriptionRule'] = getConstant('registration__showDescriptionRule') or 'all' context.update(kwargs) # Update the site session data so that registration processes know to send return links to # the registration page. set_return_page() is in SiteHistoryMixin. self.set_return_page('registration',_('Registration')) return super(ClassRegistrationView,self).get_context_data(**context) def get_form_kwargs(self, **kwargs): ''' Tell the form which fields to render ''' kwargs = super(ClassRegistrationView, self).get_form_kwargs(**kwargs) kwargs['user'] = self.request.user if hasattr(self.request,'user') else None listing = self.get_listing() kwargs.update({ 'openEvents': listing['openEvents'], 'closedEvents': listing['closedEvents'], }) return kwargs def form_valid(self,form): ''' If the form is valid, pass its contents on to the next view. In order to permit the registration form to be overridden flexibly, but without permitting storage of arbitrary data keys that could lead to potential security issues, a form class for this view can optionally specify a list of keys that are permitted. If no such list is specified as instance.permitted_event_keys, then the default list are used. ''' regSession = self.request.session.get(REG_VALIDATION_STR, {}) # The session expires after a period of inactivity that is specified in preferences. expiry = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes')) permitted_keys = getattr(form,'permitted_event_keys',['role',]) try: event_listing = { int(key.split("_")[-1]): {k:v for k,v in json.loads(value[0]).items() if k in permitted_keys} for key,value in form.cleaned_data.items() if 'event' in key and value } non_event_listing = {key: value for key,value in form.cleaned_data.items() if 'event' not in key} except (ValueError, TypeError) as e: form.add_error(None,ValidationError(_('Invalid event information passed.'),code='invalid')) return super(ClassRegistrationView,self).form_invalid(form) associated_events = Event.objects.filter(id__in=[k for k in event_listing.keys()]) # Include the submission user if the user is authenticated if self.request.user.is_authenticated: submissionUser = self.request.user else: submissionUser = None reg = TemporaryRegistration( submissionUser=submissionUser,dateTime=timezone.now(), payAtDoor=non_event_listing.pop('payAtDoor',False), expirationDate=expiry, ) # Anything passed by this form that is not an Event field (any extra fields) are # passed directly into the TemporaryRegistration's data. reg.data = non_event_listing or {} if regSession.get('marketing_id'): reg.data.update({'marketing_id': regSession.pop('marketing_id',None)}) eventRegs = [] grossPrice = 0 for key,value in event_listing.items(): this_event = associated_events.get(id=key) # Check if registration is still feasible based on both completed registrations # and registrations that are not yet complete this_role_id = value.get('role',None) if 'role' in permitted_keys else None soldOut = this_event.soldOutForRole(role=this_role_id,includeTemporaryRegs=True) if soldOut: if self.request.user.has_perm('core.override_register_soldout'): # This message will be displayed on the Step 2 page by default. messages.warning(self.request,_( 'Registration for \'%s\' is sold out. Based on your user permission level, ' % this_event.name + 'you may proceed with registration. However, if you do not wish to exceed ' + 'the listed capacity of the event, please do not proceed.' )) else: # For users without permissions, don't allow registration for sold out things # at all. form.add_error(None, ValidationError(_('Registration for "%s" is tentatively sold out while others complete their registration. Please try again later.' % this_event.name),code='invalid')) return super(ClassRegistrationView,self).form_invalid(form) dropInList = [int(k.split("_")[-1]) for k,v in value.items() if k.startswith('dropin_') and v is True] # If nothing is sold out, then proceed to create a TemporaryRegistration and # TemporaryEventRegistration objects for the items selected by this form. The # expiration date is set to be identical to that of the session. logger.debug('Creating temporary event registration for: %s' % key) if len(dropInList) > 0: tr = TemporaryEventRegistration( event=this_event, dropIn=True, price=this_event.getBasePrice(dropIns=len(dropInList)) ) else: tr = TemporaryEventRegistration( event=this_event, price=this_event.getBasePrice(payAtDoor=reg.payAtDoor), role_id=this_role_id ) # If it's possible to store additional data and such data exist, then store them. tr.data = {k: v for k,v in value.items() if k in permitted_keys and k != 'role'} eventRegs.append(tr) grossPrice += tr.price # If we got this far with no issues, then save reg.priceWithDiscount = grossPrice reg.save() for er in eventRegs: er.registration = reg er.save() regSession["temporaryRegistrationId"] = reg.id regSession["temporaryRegistrationExpiry"] = expiry.strftime('%Y-%m-%dT%H:%M:%S%z') self.request.session[REG_VALIDATION_STR] = regSession return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('getStudentInfo') def get_allEvents(self): ''' Splitting this method out to get the set of events to filter allows one to subclass for different subsets of events without copying other logic ''' if not hasattr(self,'allEvents'): timeFilters = {'endTime__gte': timezone.now()} if getConstant('registration__displayLimitDays') or 0 > 0: timeFilters['startTime__lte'] = timezone.now() + timedelta(days=getConstant('registration__displayLimitDays')) # Get the Event listing here to avoid duplicate queries self.allEvents = Event.objects.filter( **timeFilters ).filter( Q(instance_of=PublicEvent) | Q(instance_of=Series) ).annotate( **self.get_annotations() ).exclude( Q(status=Event.RegStatus.hidden) | Q(status=Event.RegStatus.regHidden) | Q(status=Event.RegStatus.linkOnly) ).order_by(*self.get_ordering()) return self.allEvents def get_listing(self): ''' This function gets all of the information that we need to either render or validate the form. It is structured to avoid duplicate DB queries ''' if not hasattr(self,'listing'): allEvents = self.get_allEvents() openEvents = allEvents.filter(registrationOpen=True) closedEvents = allEvents.filter(registrationOpen=False) publicEvents = allEvents.instance_of(PublicEvent) allSeries = allEvents.instance_of(Series) self.listing = { 'allEvents': allEvents, 'openEvents': openEvents, 'closedEvents': closedEvents, 'publicEvents': publicEvents, 'allSeries': allSeries, 'regOpenEvents': publicEvents.filter(registrationOpen=True).filter( Q(publicevent__category__isnull=True) | Q(publicevent__category__separateOnRegistrationPage=False) ), 'regClosedEvents': publicEvents.filter(registrationOpen=False).filter( Q(publicevent__category__isnull=True) | Q(publicevent__category__separateOnRegistrationPage=False) ), 'categorySeparateEvents': publicEvents.filter( publicevent__category__separateOnRegistrationPage=True ).order_by('publicevent__category'), 'regOpenSeries': allSeries.filter(registrationOpen=True).filter( Q(series__category__isnull=True) | Q(series__category__separateOnRegistrationPage=False) ), 'regClosedSeries': allSeries.filter(registrationOpen=False).filter( Q(series__category__isnull=True) | Q(series__category__separateOnRegistrationPage=False) ), 'categorySeparateSeries': allSeries.filter( series__category__separateOnRegistrationPage=True ).order_by('series__category'), } return self.listing class SingleClassRegistrationView(ClassRegistrationView): ''' This view is called only via a link, and it allows a person to register for a single class without seeing all other classes. ''' template_name = 'core/registration/single_event_registration.html' def get_allEvents(self): try: self.allEvents = Event.objects.filter(uuid=self.kwargs.get('uuid','')).exclude(status=Event.RegStatus.hidden) except ValueError: raise Http404() if not self.allEvents: raise Http404() return self.allEvents class RegistrationSummaryView(UserFormKwargsMixin, FinancialContextMixin, FormView): template_name = 'core/registration_summary.html' form_class = DoorAmountForm def dispatch(self,request,*args,**kwargs): ''' Always check that the temporary registration has not expired ''' regSession = self.request.session.get(REG_VALIDATION_STR,{}) if not regSession: return HttpResponseRedirect(reverse('registration')) try: reg = TemporaryRegistration.objects.get( id=self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationId') ) except ObjectDoesNotExist: messages.error(request,_('Invalid registration identifier passed to summary view.')) return HttpResponseRedirect(reverse('registration')) expiry = parse_datetime( self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationExpiry',''), ) if not expiry or expiry < timezone.now(): messages.info(request,_('Your registration session has expired. Please try again.')) return HttpResponseRedirect(reverse('registration')) # If OK, pass the registration and proceed kwargs.update({ 'reg': reg, }) return super(RegistrationSummaryView,self).dispatch(request, *args, **kwargs) def get(self,request,*args,**kwargs): reg = kwargs.get('reg') initial_price = sum([x.price for x in reg.temporaryeventregistration_set.all()]) # If the discounts app is enabled, then the return value to this signal # will contain information on the discounts to be applied, as well as # the total price of discount-ineligible items to be added to the # price. These should be in the form of a named tuple such as the # DiscountApplication namedtuple defined in the discounts app, with # 'items' and 'ineligible_total' keys. discount_responses = request_discounts.send( sender=RegistrationSummaryView, registration=reg, ) discount_responses = [x[1] for x in discount_responses if len(x) > 1 and x[1]] # This signal handler is designed to handle a single non-null response, # and that response must be in the form of a list of namedtuples, each # with a with a code value, a net_price value, and a discount_amount value # (as with the DiscountInfo namedtuple provided by the DiscountCombo class). If more # than one response is received, then the one with the minumum net price is applied discount_codes = [] discounted_total = initial_price total_discount_amount = 0 try: if discount_responses: discount_responses.sort(key=lambda k: min([getattr(x,'net_price',initial_price) for x in k.items] + [initial_price]) if k and hasattr(k,'items') else initial_price) discount_codes = getattr(discount_responses[0],'items',[]) if discount_codes: discounted_total = min([getattr(x,'net_price',initial_price) for x in discount_codes]) + getattr(discount_responses[0],'ineligible_total',0) total_discount_amount = initial_price - discounted_total except (IndexError, TypeError) as e: logger.error('Error in applying discount responses: %s' % e) for discount in discount_codes: apply_discount.send( sender=RegistrationSummaryView, discount=discount.code, discount_amount=discount.discount_amount, registration=reg, ) # Get any free add-on items that should be applied addon_responses = apply_addons.send( sender=RegistrationSummaryView, registration=reg ) addons = [] for response in addon_responses: try: if response[1]: addons += list(response[1]) except (IndexError, TypeError) as e: logger.error('Error in applying addons: %s' % e) # The return value to this signal should contain any adjustments that # need to be made to the price (e.g. from vouchers if the voucher app # is installed) adjustment_responses = apply_price_adjustments.send( sender=RegistrationSummaryView, registration=reg, initial_price=discounted_total ) adjustment_list = [] adjustment_amount = 0 for response in adjustment_responses: adjustment_list += response[1][0] adjustment_amount += response[1][1] # Save the discounted price to the database total = discounted_total - adjustment_amount reg.priceWithDiscount = total reg.save() # Update the session key to keep track of this registration regSession = request.session[REG_VALIDATION_STR] regSession["temp_reg_id"] = reg.id if discount_codes: regSession['discount_codes'] = [(x.code.name, x.code.pk, x.discount_amount) for x in discount_codes] regSession['total_discount_amount'] = total_discount_amount regSession['addons'] = addons regSession['voucher_names'] = adjustment_list regSession['total_voucher_amount'] = adjustment_amount request.session[REG_VALIDATION_STR] = regSession return super(RegistrationSummaryView,self).get(request,*args,**kwargs) def get_context_data(self,**kwargs): ''' Pass the initial kwargs, then update with the needed registration info. ''' context_data = super(RegistrationSummaryView,self).get_context_data(**kwargs) regSession = self.request.session[REG_VALIDATION_STR] reg_id = regSession["temp_reg_id"] reg = TemporaryRegistration.objects.get(id=reg_id) discount_codes = regSession.get('discount_codes',None) discount_amount = regSession.get('total_discount_amount',0) voucher_names = regSession.get('voucher_names',[]) total_voucher_amount = regSession.get('total_voucher_amount',0) addons = regSession.get('addons',[]) if reg.priceWithDiscount == 0: # Create a new Invoice if one does not already exist. new_invoice = Invoice.get_or_create_from_registration(reg,status=Invoice.PaymentStatus.paid) new_invoice.processPayment(0,0,forceFinalize=True) isFree = True else: isFree = False context_data.update({ 'registration': reg, "totalPrice": reg.totalPrice, 'subtotal': reg.priceWithDiscount, 'taxes': reg.addTaxes, "netPrice": reg.priceWithDiscountAndTaxes, "addonItems": addons, "discount_codes": discount_codes, "discount_code_amount": discount_amount, "voucher_names": voucher_names, "total_voucher_amount": total_voucher_amount, "total_discount_amount": discount_amount + total_voucher_amount, "currencyCode": getConstant('general__currencyCode'), 'payAtDoor': reg.payAtDoor, 'is_free': isFree, }) if self.request.user: door_permission = self.request.user.has_perm('core.accept_door_payments') invoice_permission = self.request.user.has_perm('core.send_invoices') if door_permission or invoice_permission: context_data['form'] = DoorAmountForm( user=self.request.user, doorPortion=door_permission, invoicePortion=invoice_permission, payerEmail=reg.email, discountAmount=max(reg.totalPrice - reg.priceWithDiscount,0), ) return context_data def form_valid(self,form): regSession = self.request.session[REG_VALIDATION_STR] reg_id = regSession["temp_reg_id"] tr = TemporaryRegistration.objects.get(id=reg_id) # Create a new Invoice if one does not already exist. new_invoice = Invoice.get_or_create_from_registration(tr) if form.cleaned_data.get('paid'): logger.debug('Form is marked paid. Preparing to process payment.') amount = form.cleaned_data["amountPaid"] submissionUser = form.cleaned_data.get('submissionUser') receivedBy = form.cleaned_data.get('receivedBy') payerEmail = form.cleaned_data.get('cashPayerEmail') this_cash_payment = CashPaymentRecord.objects.create( invoice=new_invoice, submissionUser=submissionUser, amount=amount, payerEmail=payerEmail, collectedByUser=receivedBy, status=CashPaymentRecord.PaymentStatus.needsCollection, ) # Process payment, but mark cash payment as needing collection from # the user who processed the registration and collected it. new_invoice.processPayment( amount,0, paidOnline=False, methodName='Cash', methodTxn='CASHPAYMENT_%s' % (this_cash_payment.recordId), submissionUser=submissionUser, collectedByUser=receivedBy, status=Invoice.PaymentStatus.needsCollection, forceFinalize=True, ) elif form.cleaned_data.get('invoiceSent'): # Do not finalize this registration, but set the expiration date # on the TemporaryRegistration such that it will not be deleted # until after the last series ends, in case this person does not make # a payment right away. This will also hold this individual's spot # in anything for which they have registered indefinitely. payerEmail = form.cleaned_data['invoicePayerEmail'] tr.expirationDate = tr.lastEndTime tr.save() new_invoice.sendNotification(payerEmail=payerEmail,newRegistration=True) return HttpResponseRedirect(reverse('registration')) class StudentInfoView(FormView): ''' This page displays a preliminary total of what is being signed up for, and it also collects customer information, either by having the user sign in in an Ajax view, or by manually entering the information. When the form is submitted, the view just passes everything into the session data and continues on to the next step. To add additional fields to this form, or to modify existing fields, just override the form class to a form that adds/modifies whatever fields you would like. ''' form_class = RegistrationContactForm template_name = 'core/student_info_form.html' def dispatch(self, request, *args, **kwargs): ''' Require session data to be set to proceed, otherwise go back to step 1. Because they have the same expiration date, this also implies that the TemporaryRegistration object is not yet expired. ''' if REG_VALIDATION_STR not in request.session: return HttpResponseRedirect(reverse('registration')) try: self.temporaryRegistration = TemporaryRegistration.objects.get( id=self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationId') ) except ObjectDoesNotExist: messages.error(request,_('Invalid registration identifier passed to sign-up form.')) return HttpResponseRedirect(reverse('registration')) expiry = parse_datetime( self.request.session[REG_VALIDATION_STR].get('temporaryRegistrationExpiry',''), ) if not expiry or expiry < timezone.now(): messages.info(request,_('Your registration session has expired. Please try again.')) return HttpResponseRedirect(reverse('registration')) return super(StudentInfoView,self).dispatch(request,*args,**kwargs) def get_context_data(self, **kwargs): context_data = super(StudentInfoView,self).get_context_data(**kwargs) reg = self.temporaryRegistration initial_price = sum([x.price for x in reg.temporaryeventregistration_set.all()]) # If the discounts app is enabled, then the return value to this signal # will contain information on the discounts to be applied, as well as # the total price of discount-ineligible items to be added to the # price. These should be in the form of a named tuple such as the # DiscountApplication namedtuple defined in the discounts app, with # 'items' and 'ineligible_total' keys. discount_responses = request_discounts.send( sender=StudentInfoView, registration=reg, ) discount_responses = [x[1] for x in discount_responses if len(x) > 1 and x[1]] # This signal handler is designed to handle a single non-null response, # and that response must be in the form of a list of namedtuples, each # with a with a code value, a net_price value, and a discount_amount value # (as with the DiscountInfo namedtuple provided by the DiscountCombo class). If more # than one response is received, then the one with the minumum net price is applied discount_codes = [] discounted_total = initial_price total_discount_amount = 0 try: if discount_responses: discount_responses.sort(key=lambda k: min([getattr(x,'net_price',initial_price) for x in k.items] + [initial_price]) if k and hasattr(k,'items') else initial_price) discount_codes = getattr(discount_responses[0],'items',[]) if discount_codes: discounted_total = min([getattr(x,'net_price',initial_price) for x in discount_codes]) + getattr(discount_responses[0],'ineligible_total',0) total_discount_amount = initial_price - discounted_total except (IndexError, TypeError) as e: logger.error('Error in applying discount responses: %s' % e) # Get any free add-on items that should be applied addon_responses = apply_addons.send( sender=StudentInfoView, registration=reg ) addons = [] for response in addon_responses: try: if response[1]: addons += list(response[1]) except (IndexError, TypeError) as e: logger.error('Error in applying addons: %s' % e) context_data.update({ 'reg': reg, 'payAtDoor': reg.payAtDoor, 'currencySymbol': getConstant('general__currencySymbol'), 'subtotal': initial_price, 'addonItems': addons, 'discount_codes': discount_codes, 'discount_code_amount': total_discount_amount, 'discounted_subtotal': discounted_total, }) if reg.payAtDoor or self.request.user.is_authenticated or not getConstant('registration__allowAjaxSignin'): context_data['show_ajax_form'] = False else: # Add a login form and a signup form context_data.update({ 'show_ajax_form': True, 'login_form': LoginForm(), 'signup_form': SignupForm(), }) return context_data def get_form_kwargs(self, **kwargs): ''' Pass along the request data to the form ''' kwargs = super(StudentInfoView, self).get_form_kwargs(**kwargs) kwargs['request'] = self.request kwargs['registration'] = self.temporaryRegistration return kwargs def get_success_url(self): return reverse('showRegSummary') def form_valid(self,form): ''' Even if this form is valid, the handlers for this form may have added messages to the request. In that case, then the page should be handled as if the form were invalid. Otherwise, update the session data with the form data and then move to the next view ''' reg = self.temporaryRegistration # The session expires after a period of inactivity that is specified in preferences. expiry = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes')) self.request.session[REG_VALIDATION_STR]["temporaryRegistrationExpiry"] = \ expiry.strftime('%Y-%m-%dT%H:%M:%S%z') self.request.session.modified = True # Update the expiration date for this registration, and pass in the data from # this form. reg.expirationDate = expiry reg.firstName = form.cleaned_data.pop('firstName') reg.lastName = form.cleaned_data.pop('lastName') reg.email = form.cleaned_data.pop('email') reg.phone = form.cleaned_data.pop('phone', None) reg.student = form.cleaned_data.pop('student',False) reg.comments = form.cleaned_data.pop('comments',None) reg.howHeardAboutUs = form.cleaned_data.pop('howHeardAboutUs',None) # Anything else in the form goes to the TemporaryRegistration data. reg.data.update(form.cleaned_data) reg.save() # This signal (formerly the post_temporary_registration signal) allows # vouchers to be applied temporarily, and it can be used for other tasks post_student_info.send(sender=StudentInfoView,registration=reg) return HttpResponseRedirect(self.get_success_url()) # Redirect after POST
[ "logging.getLogger", "json.loads", "django.utils.translation.ugettext_lazy", "django.core.urlresolvers.reverse", "django.utils.timezone.now", "allauth.account.forms.LoginForm", "django.db.models.Q", "allauth.account.forms.SignupForm", "django.http.Http404" ]
[((1096, 1123), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1113, 1123), False, 'import logging\n'), ((1460, 1483), 'django.core.urlresolvers.reverse', 'reverse', (['"""registration"""'], {}), "('registration')\n", (1467, 1483), False, 'from django.core.urlresolvers import reverse\n'), ((9381, 9406), 'django.core.urlresolvers.reverse', 'reverse', (['"""getStudentInfo"""'], {}), "('getStudentInfo')\n", (9388, 9406), False, 'from django.core.urlresolvers import reverse\n'), ((29043, 29068), 'django.core.urlresolvers.reverse', 'reverse', (['"""showRegSummary"""'], {}), "('showRegSummary')\n", (29050, 29068), False, 'from django.core.urlresolvers import reverse\n'), ((3421, 3438), 'django.utils.translation.ugettext_lazy', '_', (['"""Registration"""'], {}), "('Registration')\n", (3422, 3438), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4662, 4676), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (4674, 4676), False, 'from django.utils import timezone\n'), ((13123, 13132), 'django.http.Http404', 'Http404', ([], {}), '()\n', (13130, 13132), False, 'from django.http import HttpResponseRedirect, Http404\n'), ((23379, 23402), 'django.core.urlresolvers.reverse', 'reverse', (['"""registration"""'], {}), "('registration')\n", (23386, 23402), False, 'from django.core.urlresolvers import reverse\n'), ((29566, 29580), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (29578, 29580), False, 'from django.utils import timezone\n'), ((2828, 2858), 'django.core.urlresolvers.reverse', 'reverse', (['"""registrationOffline"""'], {}), "('registrationOffline')\n", (2835, 2858), False, 'from django.core.urlresolvers import reverse\n'), ((5797, 5811), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (5809, 5811), False, 'from django.utils import timezone\n'), ((9715, 9729), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (9727, 9729), False, 'from django.utils import timezone\n'), ((13063, 13072), 'django.http.Http404', 'Http404', ([], {}), '()\n', (13070, 13072), False, 'from django.http import HttpResponseRedirect, Http404\n'), ((13598, 13621), 'django.core.urlresolvers.reverse', 'reverse', (['"""registration"""'], {}), "('registration')\n", (13605, 13621), False, 'from django.core.urlresolvers import reverse\n'), ((14162, 14176), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (14174, 14176), False, 'from django.utils import timezone\n'), ((14212, 14273), 'django.utils.translation.ugettext_lazy', '_', (['"""Your registration session has expired. Please try again."""'], {}), "('Your registration session has expired. Please try again.')\n", (14213, 14273), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((14315, 14338), 'django.core.urlresolvers.reverse', 'reverse', (['"""registration"""'], {}), "('registration')\n", (14322, 14338), False, 'from django.core.urlresolvers import reverse\n'), ((24439, 24462), 'django.core.urlresolvers.reverse', 'reverse', (['"""registration"""'], {}), "('registration')\n", (24446, 24462), False, 'from django.core.urlresolvers import reverse\n'), ((25026, 25040), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (25038, 25040), False, 'from django.utils import timezone\n'), ((25076, 25137), 'django.utils.translation.ugettext_lazy', '_', (['"""Your registration session has expired. Please try again."""'], {}), "('Your registration session has expired. Please try again.')\n", (25077, 25137), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((25179, 25202), 'django.core.urlresolvers.reverse', 'reverse', (['"""registration"""'], {}), "('registration')\n", (25186, 25202), False, 'from django.core.urlresolvers import reverse\n'), ((9850, 9864), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (9862, 9864), False, 'from django.utils import timezone\n'), ((13865, 13925), 'django.utils.translation.ugettext_lazy', '_', (['"""Invalid registration identifier passed to summary view."""'], {}), "('Invalid registration identifier passed to summary view.')\n", (13866, 13925), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((13967, 13990), 'django.core.urlresolvers.reverse', 'reverse', (['"""registration"""'], {}), "('registration')\n", (13974, 13990), False, 'from django.core.urlresolvers import reverse\n'), ((24729, 24789), 'django.utils.translation.ugettext_lazy', '_', (['"""Invalid registration identifier passed to sign-up form."""'], {}), "('Invalid registration identifier passed to sign-up form.')\n", (24730, 24789), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((24831, 24854), 'django.core.urlresolvers.reverse', 'reverse', (['"""registration"""'], {}), "('registration')\n", (24838, 24854), False, 'from django.core.urlresolvers import reverse\n'), ((28601, 28612), 'allauth.account.forms.LoginForm', 'LoginForm', ([], {}), '()\n', (28610, 28612), False, 'from allauth.account.forms import LoginForm, SignupForm\n'), ((28645, 28657), 'allauth.account.forms.SignupForm', 'SignupForm', ([], {}), '()\n', (28655, 28657), False, 'from allauth.account.forms import LoginForm, SignupForm\n'), ((5278, 5316), 'django.utils.translation.ugettext_lazy', '_', (['"""Invalid event information passed."""'], {}), "('Invalid event information passed.')\n", (5279, 5316), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((6970, 7224), 'django.utils.translation.ugettext_lazy', '_', (['("Registration for \'%s\' is sold out. Based on your user permission level, " %\n this_event.name +\n \'you may proceed with registration. However, if you do not wish to exceed \'\n + \'the listed capacity of the event, please do not proceed.\')'], {}), '(\n "Registration for \'%s\' is sold out. Based on your user permission level, "\n % this_event.name +\n \'you may proceed with registration. However, if you do not wish to exceed \'\n + \'the listed capacity of the event, please do not proceed.\')\n', (6971, 7224), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((11398, 11435), 'django.db.models.Q', 'Q', ([], {'publicevent__category__isnull': '(True)'}), '(publicevent__category__isnull=True)\n', (11399, 11435), False, 'from django.db.models import Q\n'), ((11438, 11496), 'django.db.models.Q', 'Q', ([], {'publicevent__category__separateOnRegistrationPage': '(False)'}), '(publicevent__category__separateOnRegistrationPage=False)\n', (11439, 11496), False, 'from django.db.models import Q\n'), ((11623, 11660), 'django.db.models.Q', 'Q', ([], {'publicevent__category__isnull': '(True)'}), '(publicevent__category__isnull=True)\n', (11624, 11660), False, 'from django.db.models import Q\n'), ((11663, 11721), 'django.db.models.Q', 'Q', ([], {'publicevent__category__separateOnRegistrationPage': '(False)'}), '(publicevent__category__separateOnRegistrationPage=False)\n', (11664, 11721), False, 'from django.db.models import Q\n'), ((12033, 12065), 'django.db.models.Q', 'Q', ([], {'series__category__isnull': '(True)'}), '(series__category__isnull=True)\n', (12034, 12065), False, 'from django.db.models import Q\n'), ((12068, 12121), 'django.db.models.Q', 'Q', ([], {'series__category__separateOnRegistrationPage': '(False)'}), '(series__category__separateOnRegistrationPage=False)\n', (12069, 12121), False, 'from django.db.models import Q\n'), ((12245, 12277), 'django.db.models.Q', 'Q', ([], {'series__category__isnull': '(True)'}), '(series__category__isnull=True)\n', (12246, 12277), False, 'from django.db.models import Q\n'), ((12280, 12333), 'django.db.models.Q', 'Q', ([], {'series__category__separateOnRegistrationPage': '(False)'}), '(series__category__separateOnRegistrationPage=False)\n', (12281, 12333), False, 'from django.db.models import Q\n'), ((7510, 7655), 'django.utils.translation.ugettext_lazy', '_', (['(\'Registration for "%s" is tentatively sold out while others complete their registration. Please try again later.\'\n % this_event.name)'], {}), '(\n \'Registration for "%s" is tentatively sold out while others complete their registration. Please try again later.\'\n % this_event.name)\n', (7511, 7655), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((10393, 10427), 'django.db.models.Q', 'Q', ([], {'status': 'Event.RegStatus.linkOnly'}), '(status=Event.RegStatus.linkOnly)\n', (10394, 10427), False, 'from django.db.models import Q\n'), ((4921, 4941), 'json.loads', 'json.loads', (['value[0]'], {}), '(value[0])\n', (4931, 4941), False, 'import json\n'), ((10288, 10320), 'django.db.models.Q', 'Q', ([], {'status': 'Event.RegStatus.hidden'}), '(status=Event.RegStatus.hidden)\n', (10289, 10320), False, 'from django.db.models import Q\n'), ((10339, 10374), 'django.db.models.Q', 'Q', ([], {'status': 'Event.RegStatus.regHidden'}), '(status=Event.RegStatus.regHidden)\n', (10340, 10374), False, 'from django.db.models import Q\n'), ((10117, 10143), 'django.db.models.Q', 'Q', ([], {'instance_of': 'PublicEvent'}), '(instance_of=PublicEvent)\n', (10118, 10143), False, 'from django.db.models import Q\n'), ((10162, 10183), 'django.db.models.Q', 'Q', ([], {'instance_of': 'Series'}), '(instance_of=Series)\n', (10163, 10183), False, 'from django.db.models import Q\n')]
''' Python script of the fitting process in the notebook run_simulation.ipynb. This is made so that this can be run on command line as a bash script. ''' import os from fancy import Data, Model, Analysis import argparse # paths to important files path_to_this_file = os.path.abspath(os.path.dirname(__file__)) stan_path = os.path.join(path_to_this_file, "stan") source_file = os.path.join(path_to_this_file, "data", "sourcedata.h5") uhecr_file = os.path.join(path_to_this_file, "data", "UHECRdata.h5") table_path = os.path.join(path_to_this_file, "tables") output_path = os.path.join(path_to_this_file, "output") # make output path if it doesnt exist if not os.path.exists(output_path): os.mkdir(output_path) parser = argparse.ArgumentParser(description='Fit Stan Model to Data') parser.add_argument( '--source', dest='source_type', action='store', default="SBG_23", type=str, help='The source catalogue used (from SBG_23, 2FHL_250Mpc, swift_BAT_213)', choices=["SBG_23", "2FHL_250Mpc", "swift_BAT_213"]) parser.add_argument( '--detector', dest='detector_type', action='store', default="TA2015", type=str, help='The type of detector config (from TA2015, auger2014, auger2010)', choices=["TA2015", "auger2014", "auger2010"]) parser.add_argument( '--model', dest='model_type', action='store', default="joint", type=str, help='The stan model considered (from arrival_direction, joint, joint_gmf)', choices=["arrival_direction", "joint", "joint_gmf"]) parser.add_argument( '--dtype', dest='dtype', action='store', default="real", type=str, help="Fit with simulated or real data (choose between 'sim' and 'real')", choices=["sim", "real"]) parser.add_argument( '--ptype', dest='ptype', action='store', default="p", type=str, help= "Type of particle used for back propagation (only used with joint_gmf model)." ) parser.add_argument("--seed", dest="seed", action="store", default=19990308, type=int, help="Random seed used for MCMC in Stan.") parser.add_argument( '--sim_model', dest='sim_modeltype', action='store', default=None, help='The simulation model considered (from joint, joint_gmf)', choices=["joint", "joint_gmf"]) parser.add_argument("--tight_B", dest="tight_B", action="store_true", help="Enable model with tighetened EGMF.", default=False) def get_detectorimports(detector_type): '''Get variables imported by (detector_name).py''' if detector_type == "TA2015": from fancy.detector.TA2015 import detector_properties, alpha_T, M, Eth elif detector_type == "auger2014": from fancy.detector.auger2014 import detector_properties, alpha_T, M, Eth elif detector_type == "auger2010": from fancy.detector.auger2010 import detector_properties, alpha_T, M, Eth else: raise Exception("Undefined detector type!") return detector_properties, alpha_T, M, Eth if __name__ == "__main__": args = parser.parse_args() # get filenames table_file = os.path.join( table_path, 'tables_{0}_{1}.h5'.format(args.source_type, args.detector_type)) if args.sim_modeltype is not None: if args.tight_B: analysis_output_file = os.path.join( output_path, "{0}_fit_{5}_{1}_{2}_{3}_{4}_{6}_tightB.h5".format( args.model_type, args.source_type, args.detector_type, args.seed, args.ptype, args.dtype, args.sim_modeltype)) else: analysis_output_file = os.path.join( output_path, "{0}_fit_{5}_{1}_{2}_{3}_{4}_{6}.h5".format( args.model_type, args.source_type, args.detector_type, args.seed, args.ptype, args.dtype, args.sim_modeltype)) else: if args.tight_B: analysis_output_file = os.path.join( output_path, "tmp_{0}_fit_{5}_{1}_{2}_{3}_{4}_tightB.h5".format( args.model_type, args.source_type, args.detector_type, args.seed, args.ptype, args.dtype)) else: analysis_output_file = os.path.join( output_path, "tmp_{0}_fit_{5}_{1}_{2}_{3}_{4}.h5".format( args.model_type, args.source_type, args.detector_type, args.seed, args.ptype, args.dtype)) # get things related to detector detector_properties, alpha_T, M, Eth = get_detectorimports( args.detector_type) # create Data object data = Data() # add things to Data, method depends on sim vs real data if args.dtype == "sim": # get data from sim_output_file # simulated data uses joint model, unless considering gmf propagation too if args.sim_modeltype == "joint_gmf": sim_output_file = os.path.join( output_path, "{0}_sim_{1}_{2}_{3}_{4}.h5".format(args.sim_modeltype, args.source_type, args.detector_type, args.seed, args.ptype)) # else: # sim_output_file = os.path.join( # output_path, # "{0}_sim_{1}_{2}_{3}.h5".format(args.sim_modeltype, # args.source_type, # args.detector_type, args.seed)) data.from_file(sim_output_file) elif args.dtype == "real": # add source / UHECR / detector data manually data.add_source(source_file, args.source_type) data.add_uhecr(uhecr_file, args.detector_type, args.ptype) data.add_detector(detector_properties) # create Model, compile it, and set input if args.tight_B: model_name = os.path.join( stan_path, '{0}_model_composition_tightB.stan'.format(args.model_type)) else: model_name = os.path.join( stan_path, '{0}_model_composition.stan'.format(args.model_type)) print("tightB: ", args.tight_B, model_name) model = Model(model_filename=model_name, include_paths=stan_path) model.compile(reset=False) model.input(Eth=Eth) # in EeV # perform the analysis summary = b'Fitting the model to given data.' analysis = Analysis(data, model, analysis_type=args.model_type, filename=analysis_output_file, summary=summary) # Each catalogue has a file of pre-computed values analysis.use_tables(table_file) # Fit the Stan model fit = analysis.fit_model(chains=16, iterations=500, seed=args.seed) # Save to analysis file analysis.save()
[ "os.path.exists", "fancy.Analysis", "argparse.ArgumentParser", "fancy.Data", "os.path.join", "os.path.dirname", "fancy.Model", "os.mkdir" ]
[((325, 364), 'os.path.join', 'os.path.join', (['path_to_this_file', '"""stan"""'], {}), "(path_to_this_file, 'stan')\n", (337, 364), False, 'import os\n'), ((379, 435), 'os.path.join', 'os.path.join', (['path_to_this_file', '"""data"""', '"""sourcedata.h5"""'], {}), "(path_to_this_file, 'data', 'sourcedata.h5')\n", (391, 435), False, 'import os\n'), ((449, 504), 'os.path.join', 'os.path.join', (['path_to_this_file', '"""data"""', '"""UHECRdata.h5"""'], {}), "(path_to_this_file, 'data', 'UHECRdata.h5')\n", (461, 504), False, 'import os\n'), ((518, 559), 'os.path.join', 'os.path.join', (['path_to_this_file', '"""tables"""'], {}), "(path_to_this_file, 'tables')\n", (530, 559), False, 'import os\n'), ((574, 615), 'os.path.join', 'os.path.join', (['path_to_this_file', '"""output"""'], {}), "(path_to_this_file, 'output')\n", (586, 615), False, 'import os\n'), ((727, 788), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Fit Stan Model to Data"""'}), "(description='Fit Stan Model to Data')\n", (750, 788), False, 'import argparse\n'), ((286, 311), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (301, 311), False, 'import os\n'), ((662, 689), 'os.path.exists', 'os.path.exists', (['output_path'], {}), '(output_path)\n', (676, 689), False, 'import os\n'), ((695, 716), 'os.mkdir', 'os.mkdir', (['output_path'], {}), '(output_path)\n', (703, 716), False, 'import os\n'), ((4810, 4816), 'fancy.Data', 'Data', ([], {}), '()\n', (4814, 4816), False, 'from fancy import Data, Model, Analysis\n'), ((6416, 6473), 'fancy.Model', 'Model', ([], {'model_filename': 'model_name', 'include_paths': 'stan_path'}), '(model_filename=model_name, include_paths=stan_path)\n', (6421, 6473), False, 'from fancy import Data, Model, Analysis\n'), ((6633, 6738), 'fancy.Analysis', 'Analysis', (['data', 'model'], {'analysis_type': 'args.model_type', 'filename': 'analysis_output_file', 'summary': 'summary'}), '(data, model, analysis_type=args.model_type, filename=\n analysis_output_file, summary=summary)\n', (6641, 6738), False, 'from fancy import Data, Model, Analysis\n')]
#/*********************************************************************** # * Licensed Materials - Property of IBM # * # * IBM SPSS Products: Statistics Common # * # * (C) Copyright IBM Corp. 1989, 2020 # * # * US Government Users Restricted Rights - Use, duplication or disclosure # * restricted by GSA ADP Schedule Contract with IBM Corp. # ************************************************************************/ import random, os, tempfile, textwrap, codecs, re, locale import spss, spssaux, spssdata, textwrap """STATS VALLBLS FROMDATA extension command""" __author__ = 'IBM SPSS, JKP' __version__= '1.0.1' # history # 20-jan-2013 Original version helptext = """STATS VALLLBLS FROMDATA [/HELP] * indicates default value. This command creates value labels for a set of variables using values of other variables for the labels. If x is a variable having values 1,2,3 and xlabel is a variable having values 'a', 'b', 'c', values labels for x are created as 1 'a' 2 'b' 3 'c' Syntax: STATS VALLBLS FROMDATA VARIABLES = variable list or VARPATTERN = "regular expression" LBLVARS = string variable list or LBLPATTERN = "regular expression" OPTIONS VARSPERPASS = integer OUTPUT SYNTAX = "filespec" /HELP displays this help and does nothing else. Example: STATS VALLBLS FROMDATA VARIABLES = x1 TO x5 LBLVARS = lbl1 to lbl5. VARIABLES lists the variables for which value labels should be produced. TO is supported, but ALL would not make sense here. VARPATTERN is a regular expression in quotes that maps to the variables to be labelled. Specify either VARIABLES or VARPATTERN but not both. See below for some pattern examples. LBLVARS lists the variables containing the labels corresponding to the variables to be labelled. TO is supported but ALL would not make sense. Numeric variables are automatically excluded. LBLPATTERN lists a regular expression in quotes that expands to the list of label variables. The number of label variables can be one to apply the same set of labels to all the selected variables or as many as there are input variables. If a label variable value is blank, no value label is generated from it. VARSPERPASS specifies how many variables should be processed on a single data pass. The default is 20. The size of the intermediate dataset created by this procedure grows exponentially with the number of variables. Value labels are checked for conflicts, i.e., two different labels for the same value of a variable. MAXCONFLICTS specifies the maximum number of conflicts to report across all the variables. The default value is 100. REPORTDUPS specifies whether or not to report whether two or more value labels for a variable are identical. MAXDUPS specifies the number of duplicates reported. The default is 100. """ import spss, spssaux, spssdata from extension import Template, Syntax, processcmd def dolabels(variables=None, varpattern=None, lblvars=None, lblpattern=None, execute=True, varsperpass=20, syntax=None): """Execute STATS VALLBLS FROMDATA""" # debugging # makes debug apply only to the current thread #try: #import wingdbstub #if wingdbstub.debugger != None: #import time #wingdbstub.debugger.StopDebug() #time.sleep(1) #wingdbstub.debugger.StartDebug() #import thread #wingdbstub.debugger.SetDebugThreads({thread.get_ident(): 1}, default_policy=0) ## for V19 use ### ###SpssClient._heartBeat(False) #except: #pass try: vardict = spssaux.VariableDict(caseless=True) except: raise ValueError(_("""This command requires a newer version the spssaux module. \n It can be obtained from the SPSS Community website (www.ibm.com/developerworks/spssdevcentral)""")) varstolabel = resolve(vardict, _("variables to label"), variables, varpattern, stringonly=False) labelvars = resolve(vardict, _("label variables"), lblvars, lblpattern, stringonly=True) if len(varstolabel) == 0 or len(labelvars) == 0: raise ValueError(_("""No variables to label or no labelling variables were specified. If a pattern was used, it may not have matched any variables.""")) if len(labelvars) > 1 and len(labelvars) != len(varstolabel): raise ValueError(_("The number of label variables is different from the number of variables to label")) if min([vardict[item].VariableType for item in labelvars]) == 0: raise ValueError(_("""The label variables must all have type string""")) dsname = spss.ActiveDataset() if dsname == "*": raise ValueError(_("""The active dataset must have a dataset name in order to use this procedure""")) if syntax: syntax = syntax.replace("\\", "/") syntax = FileHandles().resolve(syntax) mkvl = Mkvls(varstolabel, labelvars, varsperpass, execute, syntax, vardict) for i in range(0, len(varstolabel), varsperpass): spss.Submit("""DATASET ACTIVATE %s""" % dsname) mkvl.doaggr(i) spss.Submit("""DATASET ACTIVATE %s""" % dsname) labelsyntax = mkvl.dolabels() if labelsyntax and execute: spss.Submit(labelsyntax) mkvl.report(labelsyntax) if labelsyntax and syntax: writesyntax(labelsyntax, syntax, mkvl) def writesyntax(labelsyntax, syntax, mkvl): if mkvl.unicodemode: inputencoding = "unicode_internal" outputencoding = "utf_8_sig" else: inputencoding = locale.getlocale()[1] outputencoding = inputencoding with codecs.EncodedFile(codecs.open(syntax, "wb"), inputencoding, outputencoding) as f: for line in labelsyntax: f.write(line + "\n") def resolve(vardict, itemtype, varlist, pattern, stringonly): """Return validated list of variables itemtype identifies the input description for error message purposes varlist is a sequence of variable names or None pattern is a regular expression or None vardict is a variable dictionary stringonly = True excludes numeric variables from pattern matches If pattern is used, list is returned in SPSS dictionary order""" if (varlist is None and pattern is None) or\ (varlist is not None and pattern is not None): raise ValueError(_("Either a variable list or a pattern must be specified but not both: %s") % itemtype) if varlist: return vardict.expand(varlist) else: if stringonly: selectedvars = vardict.variablesf(pattern=pattern, variableType="string") else: selectedvars = vardict.variablesf(pattern=pattern) varsinorder = sorted([(vardict[vname].VariableIndex, vname)\ for vname in selectedvars]) return [vname for (index, vname) in varsinorder] class Mkvls(object): """Make Value Labels""" aggrtemplate = """DATASET DECLARE %s. AGGREGATE /OUTFILE=%s /BREAK %s""" def __init__(self, varstolabel, labelvars, varsperpass, execute, syntax, vardict): attributesFromDict(locals()) self.conflicts = {} # a dictionary of sets of conflicts keyed by varname self.duplabels = {} # a dictionary of sets of duplicate labels keyed by varname self.vlabels = {} # a dictionary of sets of value label/value pairs keyed by varname self.values = {} # a dictionary of sets of values keyed by varname self.labelusage = {} # a dictionary of dictionaries indexed by varnme and label text # results are accumulated across data passes for v in varstolabel: self.conflicts[v] = set() #self.duplabels[v] = 0 self.duplabels[v] = set() self.vlabels[v] = set() self.values[v] = set() self.labelusage[v] = {} self.aggrdsname = mkrandomname(sav=False) self.unicodemode = spss.PyInvokeSpss.IsUTF8mode() if self.unicodemode: self.ec = codecs.getencoder("utf_8") # must figure string length in bytes of utf-8 def doaggr(self, doindex): """create an aggregate dataset and tally values doindex is the index into varstolabel at which to start""" vtl = self.varstolabel[doindex:doindex+self.varsperpass] vtllen = len(vtl) if len(self.labelvars) == 1: lbls = self.labelvars lastlbl = vtllen + 1 else: lbls = self.labelvars[doindex:doindex+self.varsperpass] lastlbl = 3 * vtllen - 1 brkvarlist = "\n".join(textwrap.wrap(" ".join(vtl), width=100)) outvars = ["/min_%s=MIN(%s)/max_%s=MAX(%s)" % (mkrandomname(), v, mkrandomname(), v) for v in lbls] aggrcmd = Mkvls.aggrtemplate % (self.aggrdsname, self.aggrdsname, brkvarlist) + "\n".join(outvars) spss.Submit(aggrcmd) spss.Submit("DATASET ACTIVATE %s" % self.aggrdsname) # for each variable, build label information based on data # AGGREGATE dataset structure: # var1value, var2value,..., min(text lbl1), max(text lbl1), min(text lbl2), max(text lbl2)... # but if only one label set, only one pair of label aggregates is produced # user missing values are exposed and subject to labelling curs = spssdata.Spssdata(names=False, convertUserMissing=False) for case in curs: for v, vname in enumerate(vtl): value = case[v] minlbl = self.truncate(case[min(vtllen + v*2, lastlbl-1)], 120).rstrip() maxlbl = self.truncate(case[min(vtllen + v*2 + 1, lastlbl)], 120).rstrip() # more than one label for the same value? if minlbl != maxlbl and (minlbl != "" and minlbl is not None): self.conflicts[vname].add(value) # ignore empty or missing labels if maxlbl != "" and maxlbl is not None: # if the value has already been seen but with a different label, it's a conflict if value in self.values[vname] and not (value, maxlbl) in self.vlabels[vname]: self.conflicts[vname].add(value) else: self.vlabels[vname].add((value, maxlbl)) # first one wins self.values[vname].add(value) # tally instances where the same label used for different value # need to see whether labels has been assigned to a different value previousvalue = self.labelusage[vname].get(maxlbl, None) if previousvalue is not None and value != previousvalue: ###self.duplabels[vname] = self.duplabels[vname] + 1 self.duplabels[vname].add(maxlbl) self.labelusage[vname][maxlbl] = value curs.CClose() spss.Submit("DATASET CLOSE %s" % self.aggrdsname) def dolabels(self): """generate, save, and run labelling syntax and write reports""" vlsyntax = [] for k,v in sorted(self.vlabels.items()): vlsyntax.append(self.makevls(k,v)) return vlsyntax def makevls(self, varname, vlinfo): """Return value label syntax varname is the variable to which the syntax applies vlinfo is the set of duples of (value, label)""" isstring = self.vardict[varname].VariableType > 0 vls = [] for value, label in sorted(vlinfo): if isstring: value = spssaux._smartquote(value) else: if value == int(value): value = int(value) label = spssaux._smartquote(label) vls.append("%s %s" % (value, label)) return "VALUE LABELS " + varname + "\n " + "\n ".join(vls) + "." def report(self, labelsyntax): # write report if not labelsyntax: print(_("""No value labels were generated.""")) return if len(self.labelvars) > 1: labelvars = self.labelvars else: labelvars = len(self.varstolabel) * [self.labelvars][0] spss.StartProcedure("Generate Value Labels", "STATSVALLBLSFROMDATA") cells = [[labelvars[i], spss.CellText.Number(len(self.conflicts[vname]), spss.FormatSpec.Count), #spss.CellText.Number(self.duplabels[vname], spss.FormatSpec.Count)]\ spss.CellText.Number(len(self.duplabels[vname]), spss.FormatSpec.Count)]\ for i,vname in enumerate(self.varstolabel)] caption = [] if self.syntax: caption.append(_("""Generated label syntax: %s""" % self.syntax)) if self.execute: caption.append(_("""Generated label syntax was applied""")) else: caption.append(_("""Generated label syntax was not applied""")) caption.append(_("""A conflict means that different labels would be applied to the same value.""")) caption.append(_("""A duplicate means that the same label was used for different values.""")) tbl = spss.BasePivotTable(_("""Value Label Generation"""), "VALLBLSFROMDATA", caption="\n".join(caption)) tbl.SimplePivotTable(rowdim= _("""Variable"""), rowlabels=self.varstolabel, collabels=[_("""Label Source"""), _("""Label Conflicts"""), _("""Duplicate Labels""")], cells=cells) spss.EndProcedure() def truncate(self, name, maxlength): """Return a name truncated to no more than maxlength BYTES. name is the candidate string maxlength is the maximum byte count allowed. It must be a positive integer. If name is a (code page) string, truncation is straightforward. If it is Unicode utf-8, the utf-8 byte representation must be used to figure this out but still truncate on a character boundary.""" if name is None: return None if not self.unicodemode: name = name[:maxlength] else: newname = [] nnlen = 0 # In Unicode mode, length must be calculated in terms of utf-8 bytes for c in name: c8 = self.ec(c)[0] # one character in utf-8 nnlen += len(c8) if nnlen <= maxlength: newname.append(c) else: break name = "".join(newname) if name[-1] == "_": name = name[:-1] return name def mkrandomname(prefix="D", sav=True): res = prefix + str(random.uniform(.01,1.0)) if sav: res = res + ".sav" return res def __init__(self): self.wdsname = mkrandomname("D", sav=False) def getsav(self, filespec, delete=True): """Open sav file and return all contents filespec is the file path filespec is deleted after the contents are read unless delete==False""" item = self.wdsname spss.Submit(r"""get file="%(filespec)s". DATASET NAME %(item)s. DATASET ACTIVATE %(item)s.""" % locals()) contents = spssdata.Spssdata(names=False).fetchall() spss.Submit("""DATASET CLOSE %(item)s. NEW FILE.""" % locals()) if delete: os.remove(filespec) return contents """return list of syntax specs root is the root of the name for the left hand variable setn is the set number setvars is the list of variables in the set data is the table of unstandardized canconical coefficients - one column per canonical correlation ndims can trim the number of correlations used.""" syntax = [] nvars = len(setvars) ncor = len(data[0]) if not ndims is None: ncor = min(ncor, ndims) newnames = set() for i in range(ncor): cname = root + "_set" + str(setn) + "_" + str(i+1) newnames.add(cname) if len(cname) > 64: raise ValueError(_("The specified root name is too long: %s") % root) s = ["COMPUTE " + cname + " = "] for j in range(nvars): s.append(str(data[j][i]) + " * " + setvars[j]) syntax.append(s[0] + " + ".join(s[1:])) syntax[i] = "\n".join(textwrap.wrap(syntax[i])) +"." return "\n".join(syntax), newnames class NonProcPivotTable(object): """Accumulate an object that can be turned into a basic pivot table once a procedure state can be established""" def __init__(self, omssubtype, outlinetitle="", tabletitle="", caption="", rowdim="", coldim="", columnlabels=[], procname="Messages"): """omssubtype is the OMS table subtype. caption is the table caption. tabletitle is the table title. columnlabels is a sequence of column labels. If columnlabels is empty, this is treated as a one-column table, and the rowlabels are used as the values with the label column hidden procname is the procedure name. It must not be translated.""" attributesFromDict(locals()) self.rowlabels = [] self.columnvalues = [] self.rowcount = 0 def addrow(self, rowlabel=None, cvalues=None): """Append a row labelled rowlabel to the table and set value(s) from cvalues. rowlabel is a label for the stub. cvalues is a sequence of values with the same number of values are there are columns in the table.""" if cvalues is None: cvalues = [] self.rowcount += 1 if rowlabel is None: self.rowlabels.append(str(self.rowcount)) else: self.rowlabels.append(rowlabel) self.columnvalues.extend(cvalues) def generate(self): """Produce the table assuming that a procedure state is now in effect if it has any rows.""" privateproc = False if self.rowcount > 0: try: table = spss.BasePivotTable(self.tabletitle, self.omssubtype) except: StartProcedure(_("Create dummy variables"), self.procname) privateproc = True table = spss.BasePivotTable(self.tabletitle, self.omssubtype) if self.caption: table.Caption(self.caption) if self.columnlabels != []: table.SimplePivotTable(self.rowdim, self.rowlabels, self.coldim, self.columnlabels, self.columnvalues) else: table.Append(spss.Dimension.Place.row,"rowdim",hideName=True,hideLabels=True) table.Append(spss.Dimension.Place.column,"coldim",hideName=True,hideLabels=True) colcat = spss.CellText.String("Message") for r in self.rowlabels: cellr = spss.CellText.String(r) table[(cellr, colcat)] = cellr if privateproc: spss.EndProcedure() def attributesFromDict(d): """build self attributes from a dictionary d.""" self = d.pop('self') for name, value in d.items(): setattr(self, name, value) def StartProcedure(procname, omsid): """Start a procedure procname is the name that will appear in the Viewer outline. It may be translated omsid is the OMS procedure identifier and should not be translated. Statistics versions prior to 19 support only a single term used for both purposes. For those versions, the omsid will be use for the procedure name. While the spss.StartProcedure function accepts the one argument, this function requires both.""" try: spss.StartProcedure(procname, omsid) except TypeError: #older version spss.StartProcedure(omsid) class FileHandles(object): """manage and replace file handles in filespecs. For versions prior to 18, it will always be as if there are no handles defined as the necessary api is new in that version, but path separators will still be rationalized. """ def __init__(self): """Get currently defined handles""" # If the api is available, make dictionary with handles in lower case and paths in canonical form, i.e., # with the os-specific separator and no trailing separator # path separators are forced to the os setting if os.path.sep == "\\": ps = r"\\" else: ps = "/" try: self.fhdict = dict([(h.lower(), (re.sub(r"[\\/]", ps, spec.rstrip("\\/")), encoding))\ for h, spec, encoding in spss.GetFileHandles()]) except: self.fhdict = {} # the api will fail prior to v 18 def resolve(self, filespec): """Return filespec with file handle, if any, resolved to a regular filespec filespec is a file specification that may or may not start with a handle. The returned value will have os-specific path separators whether or not it contains a handle""" parts = re.split(r"[\\/]", filespec) # try to substitute the first part as if it is a handle parts[0] = self.fhdict.get(parts[0].lower(), (parts[0],))[0] return os.path.sep.join(parts) def getdef(self, handle): """Return duple of handle definition and encoding or None duple if not a handle handle is a possible file handle The return is (handle definition, encoding) or a None duple if this is not a known handle""" return self.fhdict.get(handle.lower(), (None, None)) def createHandle(self, handle, spec, encoding=None): """Create a file handle and update the handle list accordingly handle is the name of the handle spec is the location specification, i.e., the /NAME value encoding optionally specifies the encoding according to the valid values in the FILE HANDLE syntax.""" spec = re.sub(r"[\\/]", re.escape(os.path.sep), spec) # clean up path separator cmd = """FILE HANDLE %(handle)s /NAME="%(spec)s" """ % locals() # Note the use of double quotes around the encoding name as there are some encodings that # contain a single quote in the name if encoding: cmd += ' /ENCODING="' + encoding + '"' spss.Submit(cmd) self.fhdict[handle.lower()] = (spec, encoding) def Run(args): """Execute the STATS VALLBLS FROMDATA extension command""" args = args[list(args.keys())[0]] oobj = Syntax([ Template("VARIABLES", subc="", ktype="varname", var="variables", islist=True), Template("VARPATTERN", subc="", ktype="literal", var="varpattern", islist=False), Template("LBLVARS", subc="", ktype="varname", var="lblvars", islist=True), Template("LBLPATTERN", subc="", ktype="literal", var="lblpattern", islist=False), Template("VARSPERPASS", subc="OPTIONS", ktype="int", var="varsperpass"), Template("SYNTAX", subc="OUTPUT", ktype="literal", var="syntax"), Template("EXECUTE", subc="OUTPUT", ktype="bool", var="execute"), Template("HELP", subc="", ktype="bool")]) #enable localization global _ try: _("---") except: def _(msg): return msg # A HELP subcommand overrides all else if "HELP" in args: #print helptext helper() else: processcmd(oobj, args, dolabels) def helper(): """open html help in default browser window The location is computed from the current module name""" import webbrowser, os.path path = os.path.splitext(__file__)[0] helpspec = "file://" + path + os.path.sep + \ "markdown.html" # webbrowser.open seems not to work well browser = webbrowser.get() if not browser.open_new(helpspec): print(("Help file not found:" + helpspec)) try: #override from extension import helper except: pass
[ "re.escape", "spss.StartProcedure", "os.path.sep.join", "spssaux._smartquote", "textwrap.wrap", "spssdata.Spssdata", "os.remove", "re.split", "extension.Template", "webbrowser.get", "spssaux.VariableDict", "spss.CellText.String", "spss.ActiveDataset", "extension.helper", "random.uniform"...
[((4566, 4586), 'spss.ActiveDataset', 'spss.ActiveDataset', ([], {}), '()\n', (4584, 4586), False, 'import spss, spssaux, spssdata\n'), ((5055, 5098), 'spss.Submit', 'spss.Submit', (["('DATASET ACTIVATE %s' % dsname)"], {}), "('DATASET ACTIVATE %s' % dsname)\n", (5066, 5098), False, 'import spss, spssaux, spssdata\n'), ((24157, 24173), 'webbrowser.get', 'webbrowser.get', ([], {}), '()\n', (24171, 24173), False, 'import webbrowser, os.path\n'), ((3571, 3606), 'spssaux.VariableDict', 'spssaux.VariableDict', ([], {'caseless': '(True)'}), '(caseless=True)\n', (3591, 3606), False, 'import spss, spssaux, spssdata\n'), ((4980, 5023), 'spss.Submit', 'spss.Submit', (["('DATASET ACTIVATE %s' % dsname)"], {}), "('DATASET ACTIVATE %s' % dsname)\n", (4991, 5023), False, 'import spss, spssaux, spssdata\n'), ((5181, 5205), 'spss.Submit', 'spss.Submit', (['labelsyntax'], {}), '(labelsyntax)\n', (5192, 5205), False, 'import spss, spssaux, spssdata\n'), ((7945, 7975), 'spss.PyInvokeSpss.IsUTF8mode', 'spss.PyInvokeSpss.IsUTF8mode', ([], {}), '()\n', (7973, 7975), False, 'import spss, spssaux, spssdata\n'), ((8892, 8912), 'spss.Submit', 'spss.Submit', (['aggrcmd'], {}), '(aggrcmd)\n', (8903, 8912), False, 'import spss, spssaux, spssdata\n'), ((8921, 8973), 'spss.Submit', 'spss.Submit', (["('DATASET ACTIVATE %s' % self.aggrdsname)"], {}), "('DATASET ACTIVATE %s' % self.aggrdsname)\n", (8932, 8973), False, 'import spss, spssaux, spssdata\n'), ((9365, 9421), 'spssdata.Spssdata', 'spssdata.Spssdata', ([], {'names': '(False)', 'convertUserMissing': '(False)'}), '(names=False, convertUserMissing=False)\n', (9382, 9421), False, 'import spss, spssaux, spssdata\n'), ((10999, 11048), 'spss.Submit', 'spss.Submit', (["('DATASET CLOSE %s' % self.aggrdsname)"], {}), "('DATASET CLOSE %s' % self.aggrdsname)\n", (11010, 11048), False, 'import spss, spssaux, spssdata\n'), ((12365, 12433), 'spss.StartProcedure', 'spss.StartProcedure', (['"""Generate Value Labels"""', '"""STATSVALLBLSFROMDATA"""'], {}), "('Generate Value Labels', 'STATSVALLBLSFROMDATA')\n", (12384, 12433), False, 'import spss, spssaux, spssdata\n'), ((13666, 13685), 'spss.EndProcedure', 'spss.EndProcedure', ([], {}), '()\n', (13683, 13685), False, 'import spss, spssaux, spssdata\n'), ((19966, 20002), 'spss.StartProcedure', 'spss.StartProcedure', (['procname', 'omsid'], {}), '(procname, omsid)\n', (19985, 20002), False, 'import spss, spssaux, spssdata\n'), ((21364, 21393), 're.split', 're.split', (['"""[\\\\\\\\/]"""', 'filespec'], {}), "('[\\\\\\\\/]', filespec)\n", (21372, 21393), False, 'import random, os, tempfile, textwrap, codecs, re, locale\n'), ((21541, 21564), 'os.path.sep.join', 'os.path.sep.join', (['parts'], {}), '(parts)\n', (21557, 21564), False, 'import random, os, tempfile, textwrap, codecs, re, locale\n'), ((22663, 22679), 'spss.Submit', 'spss.Submit', (['cmd'], {}), '(cmd)\n', (22674, 22679), False, 'import spss, spssaux, spssdata\n'), ((23747, 23755), 'extension.helper', 'helper', ([], {}), '()\n', (23753, 23755), False, 'from extension import helper\n'), ((23774, 23806), 'extension.processcmd', 'processcmd', (['oobj', 'args', 'dolabels'], {}), '(oobj, args, dolabels)\n', (23784, 23806), False, 'from extension import Template, Syntax, processcmd\n'), ((23988, 24014), 'os.path.splitext', 'os.path.splitext', (['__file__'], {}), '(__file__)\n', (24004, 24014), False, 'import random, os, tempfile, textwrap, codecs, re, locale\n'), ((5498, 5516), 'locale.getlocale', 'locale.getlocale', ([], {}), '()\n', (5514, 5516), False, 'import random, os, tempfile, textwrap, codecs, re, locale\n'), ((5587, 5612), 'codecs.open', 'codecs.open', (['syntax', '"""wb"""'], {}), "(syntax, 'wb')\n", (5598, 5612), False, 'import random, os, tempfile, textwrap, codecs, re, locale\n'), ((8027, 8053), 'codecs.getencoder', 'codecs.getencoder', (['"""utf_8"""'], {}), "('utf_8')\n", (8044, 8053), False, 'import random, os, tempfile, textwrap, codecs, re, locale\n'), ((11855, 11881), 'spssaux._smartquote', 'spssaux._smartquote', (['label'], {}), '(label)\n', (11874, 11881), False, 'import spss, spssaux, spssdata\n'), ((14877, 14902), 'random.uniform', 'random.uniform', (['(0.01)', '(1.0)'], {}), '(0.01, 1.0)\n', (14891, 14902), False, 'import random, os, tempfile, textwrap, codecs, re, locale\n'), ((15579, 15598), 'os.remove', 'os.remove', (['filespec'], {}), '(filespec)\n', (15588, 15598), False, 'import random, os, tempfile, textwrap, codecs, re, locale\n'), ((20049, 20075), 'spss.StartProcedure', 'spss.StartProcedure', (['omsid'], {}), '(omsid)\n', (20068, 20075), False, 'import spss, spssaux, spssdata\n'), ((22310, 22332), 're.escape', 're.escape', (['os.path.sep'], {}), '(os.path.sep)\n', (22319, 22332), False, 'import random, os, tempfile, textwrap, codecs, re, locale\n'), ((22890, 22967), 'extension.Template', 'Template', (['"""VARIABLES"""'], {'subc': '""""""', 'ktype': '"""varname"""', 'var': '"""variables"""', 'islist': '(True)'}), "('VARIABLES', subc='', ktype='varname', var='variables', islist=True)\n", (22898, 22967), False, 'from extension import Template, Syntax, processcmd\n'), ((22978, 23063), 'extension.Template', 'Template', (['"""VARPATTERN"""'], {'subc': '""""""', 'ktype': '"""literal"""', 'var': '"""varpattern"""', 'islist': '(False)'}), "('VARPATTERN', subc='', ktype='literal', var='varpattern', islist=False\n )\n", (22986, 23063), False, 'from extension import Template, Syntax, processcmd\n'), ((23069, 23142), 'extension.Template', 'Template', (['"""LBLVARS"""'], {'subc': '""""""', 'ktype': '"""varname"""', 'var': '"""lblvars"""', 'islist': '(True)'}), "('LBLVARS', subc='', ktype='varname', var='lblvars', islist=True)\n", (23077, 23142), False, 'from extension import Template, Syntax, processcmd\n'), ((23153, 23238), 'extension.Template', 'Template', (['"""LBLPATTERN"""'], {'subc': '""""""', 'ktype': '"""literal"""', 'var': '"""lblpattern"""', 'islist': '(False)'}), "('LBLPATTERN', subc='', ktype='literal', var='lblpattern', islist=False\n )\n", (23161, 23238), False, 'from extension import Template, Syntax, processcmd\n'), ((23245, 23316), 'extension.Template', 'Template', (['"""VARSPERPASS"""'], {'subc': '"""OPTIONS"""', 'ktype': '"""int"""', 'var': '"""varsperpass"""'}), "('VARSPERPASS', subc='OPTIONS', ktype='int', var='varsperpass')\n", (23253, 23316), False, 'from extension import Template, Syntax, processcmd\n'), ((23327, 23391), 'extension.Template', 'Template', (['"""SYNTAX"""'], {'subc': '"""OUTPUT"""', 'ktype': '"""literal"""', 'var': '"""syntax"""'}), "('SYNTAX', subc='OUTPUT', ktype='literal', var='syntax')\n", (23335, 23391), False, 'from extension import Template, Syntax, processcmd\n'), ((23401, 23464), 'extension.Template', 'Template', (['"""EXECUTE"""'], {'subc': '"""OUTPUT"""', 'ktype': '"""bool"""', 'var': '"""execute"""'}), "('EXECUTE', subc='OUTPUT', ktype='bool', var='execute')\n", (23409, 23464), False, 'from extension import Template, Syntax, processcmd\n'), ((23483, 23522), 'extension.Template', 'Template', (['"""HELP"""'], {'subc': '""""""', 'ktype': '"""bool"""'}), "('HELP', subc='', ktype='bool')\n", (23491, 23522), False, 'from extension import Template, Syntax, processcmd\n'), ((11711, 11737), 'spssaux._smartquote', 'spssaux._smartquote', (['value'], {}), '(value)\n', (11730, 11737), False, 'import spss, spssaux, spssdata\n'), ((15426, 15456), 'spssdata.Spssdata', 'spssdata.Spssdata', ([], {'names': '(False)'}), '(names=False)\n', (15443, 15456), False, 'import spss, spssaux, spssdata\n'), ((16546, 16570), 'textwrap.wrap', 'textwrap.wrap', (['syntax[i]'], {}), '(syntax[i])\n', (16559, 16570), False, 'import spss, spssaux, spssdata, textwrap\n'), ((18286, 18339), 'spss.BasePivotTable', 'spss.BasePivotTable', (['self.tabletitle', 'self.omssubtype'], {}), '(self.tabletitle, self.omssubtype)\n', (18305, 18339), False, 'import spss, spssaux, spssdata\n'), ((19014, 19045), 'spss.CellText.String', 'spss.CellText.String', (['"""Message"""'], {}), "('Message')\n", (19034, 19045), False, 'import spss, spssaux, spssdata\n'), ((19234, 19253), 'spss.EndProcedure', 'spss.EndProcedure', ([], {}), '()\n', (19251, 19253), False, 'import spss, spssaux, spssdata\n'), ((18494, 18547), 'spss.BasePivotTable', 'spss.BasePivotTable', (['self.tabletitle', 'self.omssubtype'], {}), '(self.tabletitle, self.omssubtype)\n', (18513, 18547), False, 'import spss, spssaux, spssdata\n'), ((19115, 19138), 'spss.CellText.String', 'spss.CellText.String', (['r'], {}), '(r)\n', (19135, 19138), False, 'import spss, spssaux, spssdata\n'), ((20910, 20931), 'spss.GetFileHandles', 'spss.GetFileHandles', ([], {}), '()\n', (20929, 20931), False, 'import spss, spssaux, spssdata\n')]
import torch import torch.nn as nn import torch.nn.functional as F class GCNConv(nn.Module): """ Simple GCN layer, similar to https://arxiv.org/abs/1609.02907 """ def __init__(self, in_features, out_features, activation=None, dropout=False): super(GCNConv, self).__init__() self.in_features = in_features self.out_features = out_features self.linear = nn.Linear(in_features, out_features) self.activation = activation self.dropout = dropout self.reset_parameters() def reset_parameters(self): if self.activation == F.leaky_relu: gain = nn.init.calculate_gain('leaky_relu') else: gain = nn.init.calculate_gain('relu') nn.init.xavier_normal_(self.linear.weight, gain=gain) def forward(self, x, adj, dropout=0): x = self.linear(x) x = torch.spmm(adj, x) if self.activation is not None: x = self.activation(x) if self.dropout: x = F.dropout(x, dropout) return x class GCN(nn.Module): def __init__(self, in_features, out_features, hidden_features, activation=F.relu, layer_norm=False, dropout=True): super(GCN, self).__init__() self.in_features = in_features self.out_features = out_features if type(hidden_features) is int: hidden_features = [hidden_features] self.layers = nn.ModuleList() if layer_norm: self.layers.append(nn.LayerNorm(in_features)) self.layers.append(GCNConv(in_features, hidden_features[0], activation=activation, dropout=dropout)) for i in range(len(hidden_features) - 1): if layer_norm: self.layers.append(nn.LayerNorm(hidden_features[i])) self.layers.append( GCNConv(hidden_features[i], hidden_features[i + 1], activation=activation, dropout=dropout)) self.layers.append(GCNConv(hidden_features[-1], out_features)) self.reset_parameters() @property def model_type(self): return "torch" def reset_parameters(self): for layer in self.layers: layer.reset_parameters() def forward(self, x, adj, dropout=0): for layer in self.layers: if isinstance(layer, nn.LayerNorm): x = layer(x) else: x = layer(x, adj, dropout=dropout) return x
[ "torch.nn.ModuleList", "torch.nn.LayerNorm", "torch.nn.functional.dropout", "torch.nn.init.xavier_normal_", "torch.spmm", "torch.nn.Linear", "torch.nn.init.calculate_gain" ]
[((403, 439), 'torch.nn.Linear', 'nn.Linear', (['in_features', 'out_features'], {}), '(in_features, out_features)\n', (412, 439), True, 'import torch.nn as nn\n'), ((745, 798), 'torch.nn.init.xavier_normal_', 'nn.init.xavier_normal_', (['self.linear.weight'], {'gain': 'gain'}), '(self.linear.weight, gain=gain)\n', (767, 798), True, 'import torch.nn as nn\n'), ((881, 899), 'torch.spmm', 'torch.spmm', (['adj', 'x'], {}), '(adj, x)\n', (891, 899), False, 'import torch\n'), ((1427, 1442), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (1440, 1442), True, 'import torch.nn as nn\n'), ((636, 672), 'torch.nn.init.calculate_gain', 'nn.init.calculate_gain', (['"""leaky_relu"""'], {}), "('leaky_relu')\n", (658, 672), True, 'import torch.nn as nn\n'), ((706, 736), 'torch.nn.init.calculate_gain', 'nn.init.calculate_gain', (['"""relu"""'], {}), "('relu')\n", (728, 736), True, 'import torch.nn as nn\n'), ((1016, 1037), 'torch.nn.functional.dropout', 'F.dropout', (['x', 'dropout'], {}), '(x, dropout)\n', (1025, 1037), True, 'import torch.nn.functional as F\n'), ((1497, 1522), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['in_features'], {}), '(in_features)\n', (1509, 1522), True, 'import torch.nn as nn\n'), ((1745, 1777), 'torch.nn.LayerNorm', 'nn.LayerNorm', (['hidden_features[i]'], {}), '(hidden_features[i])\n', (1757, 1777), True, 'import torch.nn as nn\n')]
import pandas as pd import networkx as nx import collections from operator import itemgetter def clean_game_titles(t_names, g_names): t_names_inverse = collections.defaultdict(list) for k,v in t_names.items(): t_names_inverse[v].append(k) to_merge = {} for k,v in t_names_inverse.items(): if len(v) > 1: v = sorted(v) to_merge[v[0]] = v for k,v in to_merge.items(): for node_to_merge in v[1:]: g_names[k]+=g_names[node_to_merge] del t_names[node_to_merge] del g_names[node_to_merge] g_names[k] = sorted(list(set(g_names[k]))) return to_merge, t_names, g_names def clean_game_titles_in_graph(G, to_merge, t_names, g_names): for k,v in to_merge.items(): target_node = None source_nodes = [] for node in v: if node in nx.nodes(G): if target_node is None: target_node = node else: source_nodes.append(node) if target_node is not None and len(source_nodes)>0: for source_node in source_nodes: G = nx.contracted_nodes(G, target_node, source_node) if target_node not in t_names.keys() and source_node in t_names.keys(): t_names[target_node] = t_names[source_node] g_names[target_node] = g_names[source_node] del t_names[source_node] del g_names[source_node] total_weight_dict = {} for node in G.nodes(): total_weight = 0.0 for edge in G.edges(node,data=True): total_weight += edge[2]['weight'] total_weight_dict[node] = total_weight nx.set_node_attributes(G, name='total_weight', values=total_weight_dict) return G, list(total_weight_dict.values()), t_names, g_names def build_G(df, min_edge_weight=None, max_nedges=None, return_total_weights=False): G = nx.Graph() for index, row in df.iterrows(): if max_nedges is not None: if index > max_nedges: break n1 = row['n1'] n2 = row['n2'] weight = row['records'] if min_edge_weight is not None: if weight < min_edge_weight: continue if G.has_edge(n1,n2): raise ValueError('WARNING With this workflow no edge should be added twice!') # G[n1][n2]['weight'] += weight else: G.add_edge(n1,n2,weight=weight) total_weight_dict = {} for node in G.nodes(): total_weight = 0.0 for edge in G.edges(node,data=True): total_weight += edge[2]['weight'] total_weight_dict[node] = total_weight nx.set_node_attributes(G, name='total_weight', values=total_weight_dict) if return_total_weights: return G, list(total_weight_dict.values()) else: return G def prune_communities(G, min_size=2): G_pruned = G.copy() node_communities = [n[1]['community'] for n in G.nodes(data=True)] for community in set(node_communities): if node_communities.count(community) < min_size: node_list = [node[0] for node in filter(lambda x: x[1]['community']==community,G.nodes(data = True))] for node in node_list: for e in G_pruned.edges(node): G_pruned.remove_edge(e[0],e[1]) G_pruned.remove_node(node) return G_pruned def get_community_info(G, t_names, g_names): community_info = {} community_genre_comp = {} all_used_genres = [] for community in set([n[1]['community'] for n in G.nodes(data=True)]): node_list = [node[0] for node in filter(lambda x: x[1]['community']==community,G.nodes(data = True))] community_info[community] = {} community_info[community]['Titles'] = [] community_info[community]['Genres'] = collections.defaultdict(int) for node in node_list: community_info[community]['Titles'].append(t_names.get(node, 'MISSING')) for g in g_names[node]: community_info[community]['Genres'][g] += 1 for k,v in community_info.items(): community_genre_comp[k] = {} for g in v['Genres']: all_used_genres.append(g) if g in community_genre_comp[k].keys(): community_genre_comp[k][g] += 1 else: community_genre_comp[k][g] = 1 for k1,v1 in community_genre_comp.items(): total = sum(v1.values()) for k2,v2 in v1.items(): community_genre_comp[k1][k2] = float(v2) / float(total) all_used_genres = sorted(list(set(all_used_genres))) return community_info, community_genre_comp, all_used_genres def write_community_info(community_info, m_path, fname='community_titles'): with open('{0:s}/{1:s}.txt'.format(m_path, fname), 'w') as f: for k,v in community_info.items(): f.write('Community {0:d}:\n'.format(k)) f.write('---------------\n') for t in sorted(v['Titles']): f.write('{0:s}\n'.format(t)) f.write('\n') f.close() def make_predictions(G, top_k=5): predictions = collections.defaultdict(set) for node in nx.nodes(G): edges = list(G.edges(node, data='weight')) edges.sort(key=itemgetter(2),reverse=True) for edge in edges[:top_k]: predictions[node].add(edge[1]) return predictions
[ "networkx.nodes", "networkx.Graph", "networkx.contracted_nodes", "collections.defaultdict", "networkx.set_node_attributes", "operator.itemgetter" ]
[((155, 184), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (178, 184), False, 'import collections\n'), ((1539, 1611), 'networkx.set_node_attributes', 'nx.set_node_attributes', (['G'], {'name': '"""total_weight"""', 'values': 'total_weight_dict'}), "(G, name='total_weight', values=total_weight_dict)\n", (1561, 1611), True, 'import networkx as nx\n'), ((1767, 1777), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (1775, 1777), True, 'import networkx as nx\n'), ((2438, 2510), 'networkx.set_node_attributes', 'nx.set_node_attributes', (['G'], {'name': '"""total_weight"""', 'values': 'total_weight_dict'}), "(G, name='total_weight', values=total_weight_dict)\n", (2460, 2510), True, 'import networkx as nx\n'), ((4719, 4747), 'collections.defaultdict', 'collections.defaultdict', (['set'], {}), '(set)\n', (4742, 4747), False, 'import collections\n'), ((4762, 4773), 'networkx.nodes', 'nx.nodes', (['G'], {}), '(G)\n', (4770, 4773), True, 'import networkx as nx\n'), ((3525, 3553), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (3548, 3553), False, 'import collections\n'), ((799, 810), 'networkx.nodes', 'nx.nodes', (['G'], {}), '(G)\n', (807, 810), True, 'import networkx as nx\n'), ((1030, 1078), 'networkx.contracted_nodes', 'nx.contracted_nodes', (['G', 'target_node', 'source_node'], {}), '(G, target_node, source_node)\n', (1049, 1078), True, 'import networkx as nx\n'), ((4841, 4854), 'operator.itemgetter', 'itemgetter', (['(2)'], {}), '(2)\n', (4851, 4854), False, 'from operator import itemgetter\n')]
''' Start by reading and running the following code to see what it does. 1. Then rewrite this code so that it uses a for loop. Challenge yourself to make the rewrite as short as possible. 2. Modify your code to draw a square instead of a triangle. 3. Modify your code to draw a pentagon. (You should Google what angles are needed if you can't otherwise figure them out.) 4. Create a function that takes two arguments: a turtle and a number of sides, like this: def drawShape(my_turtle, sides): Put code inside your function that draws a regular shape with as many sides as the variable "sides" using my_turtle. ''' import turtle tommy = turtle.Turtle() tommy.speed(1) tommy.pendown() tommy.color('green') tommy.forward(100) #Move forward 100 pixels tommy.left(120) #Turn left 120 degrees tommy.forward(100) tommy.left(120) tommy.forward(100) tommy.left(120) turtle.done()
[ "turtle.done", "turtle.Turtle" ]
[((640, 655), 'turtle.Turtle', 'turtle.Turtle', ([], {}), '()\n', (653, 655), False, 'import turtle\n'), ((866, 879), 'turtle.done', 'turtle.done', ([], {}), '()\n', (877, 879), False, 'import turtle\n')]
from django.test import TestCase from django.contrib.auth import get_user_model class ModelTests(TestCase): def test_create_user_succesful(self): """test thst creating a new ussful""" email = "<EMAIL>" password = "<PASSWORD>" user = get_user_model().objects.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) def test_new_user_normalise(self): """test that new user email is normalised""" email = '<EMAIL>' user = get_user_model().objects.create_user(email, 'test123') self.assertEqual(user.email, email.lower()) def test_new_user_invalid_email(self): """test if a new user email is invalid""" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'test123') def test_new_superuser(self): """Test creating a new superuser""" user = get_user_model().objects.create_superuser( '<EMAIL>', 'test123' ) self.assertTrue(user.is_superuser) self.assertTrue(user.is_staff)
[ "django.contrib.auth.get_user_model" ]
[((272, 288), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (286, 288), False, 'from django.contrib.auth import get_user_model\n'), ((612, 628), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (626, 628), False, 'from django.contrib.auth import get_user_model\n'), ((1022, 1038), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (1036, 1038), False, 'from django.contrib.auth import get_user_model\n'), ((874, 890), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (888, 890), False, 'from django.contrib.auth import get_user_model\n')]
import torch.utils.data as data import os import numpy as np import cv2 #/mnt/lustre/share/dingmingyu/new_list_lane.txt class MyDataset(data.Dataset): def __init__(self, file, dir_path, new_width, new_height, label_width, label_height): imgs = [] fw = open(file, 'r') lines = fw.readlines() for line in lines: words = line.strip().split() imgs.append((words[0], words[1])) self.imgs = imgs self.dir_path = dir_path self.height = new_height self.width = new_width self.label_height = label_height self.label_width = label_width def __getitem__(self, index): path, label = self.imgs[index] path = os.path.join(self.dir_path, path) img = cv2.imread(path).astype(np.float32) img = img[:,:,:3] img = cv2.resize(img, (self.width, self.height)) img -= [104, 117, 123] img = img.transpose(2, 0, 1) gt = cv2.imread(label,-1) gt = cv2.resize(gt, (self.label_width, self.label_height), interpolation = cv2.INTER_NEAREST) if len(gt.shape) == 3: gt = gt[:,:,0] gt_num_list = list(np.unique(gt)) gt_num_list.remove(0) target_ins = np.zeros((4, gt.shape[0],gt.shape[1])).astype('uint8') for index, ins in enumerate(gt_num_list): target_ins[index,:,:] += (gt==ins) return img, target_ins, len(gt_num_list) def __len__(self): return len(self.imgs)
[ "numpy.unique", "os.path.join", "numpy.zeros", "cv2.resize", "cv2.imread" ]
[((725, 758), 'os.path.join', 'os.path.join', (['self.dir_path', 'path'], {}), '(self.dir_path, path)\n', (737, 758), False, 'import os\n'), ((849, 891), 'cv2.resize', 'cv2.resize', (['img', '(self.width, self.height)'], {}), '(img, (self.width, self.height))\n', (859, 891), False, 'import cv2\n'), ((973, 994), 'cv2.imread', 'cv2.imread', (['label', '(-1)'], {}), '(label, -1)\n', (983, 994), False, 'import cv2\n'), ((1007, 1098), 'cv2.resize', 'cv2.resize', (['gt', '(self.label_width, self.label_height)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(gt, (self.label_width, self.label_height), interpolation=cv2.\n INTER_NEAREST)\n', (1017, 1098), False, 'import cv2\n'), ((1184, 1197), 'numpy.unique', 'np.unique', (['gt'], {}), '(gt)\n', (1193, 1197), True, 'import numpy as np\n'), ((773, 789), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (783, 789), False, 'import cv2\n'), ((1250, 1289), 'numpy.zeros', 'np.zeros', (['(4, gt.shape[0], gt.shape[1])'], {}), '((4, gt.shape[0], gt.shape[1]))\n', (1258, 1289), True, 'import numpy as np\n')]
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="workdown", version="0.0.4", author="<NAME>", author_email="<EMAIL>", description="Write Markdown and have it published and hosted on Cloudflare Workers", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/eldridgea/workdown", packages=setuptools.find_packages(), install_requires=['markdown'], classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', entry_points={ 'console_scripts': [ 'workdown = workdown.workdown:main' ] }, )
[ "setuptools.find_packages" ]
[((438, 464), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (462, 464), False, 'import setuptools\n')]
from django.conf import settings from django.shortcuts import redirect, render from transport.models import * from transport.forms import * from django.contrib.auth.decorators import login_required import requests,json from django.template.loader import render_to_string, get_template from django.core.mail import EmailMessage from decimal import Decimal from paypal.standard.forms import PayPalPaymentsForm import re from django_daraja.mpesa.core import MpesaClient from django.http import HttpResponse, HttpResponseRedirect from django.http.response import JsonResponse from django.urls import reverse from requests.api import get from requests.auth import HTTPBasicAuth @login_required(login_url='client_login') def request_transport(request): api_key = settings.GOOGLE_API_KEY initial_units=request.session.get('initial_units') final_units = request.session.get('final_units') if request.method == 'POST': form = TransportForm(request.POST) if form.is_valid(): transport_request = form.save(commit=False) transport_request.user = request.user #client goods logic goods = Goods.objects.filter(owner=request.user).last() transport_request.goods= goods #distance matrix logic source = 'Moringa School,Nairobi,Kenya' destination = transport_request.address url = 'https://maps.googleapis.com/maps/api/distancematrix/json?' r = requests.get(url + 'origins=' + source + '&destinations=' + destination + '&key=' + api_key) x=r.json() print(x) distance = x['rows'][0]["elements"][0]["distance"]["value"] transport_request.distance = (distance)/1000 #calculate price price = (transport_request.distance)*200 transport_request.price = price #transport_type logic if initial_units > final_units: transport_request.transport_type = Transport.PICKUP elif final_units > initial_units: transport_request.transport_type= Transport.DELIVERY transport_request.save() return redirect('request_summary') else: print(form.errors) else: form =TransportForm() context = { 'form':form, 'api_key': api_key, 'initial_units':initial_units, 'final_units': final_units, } return render(request,'request_transport.html', context) @login_required(login_url='client_login') def request_summary(request): request_transport = Transport.objects.filter(user=request.user).last() print(request_transport.user.first_name) context = { 'request_transport': request_transport, } #email logic subject = 'TRANSPORT REQUEST SUMMARY' message = get_template('transport_summary_email.html').render(context) msg = EmailMessage( subject, message, settings.EMAIL_HOST_USER, [request_transport.email], ) msg.content_subtype = 'html' msg.send() return render(request,'request_summary.html', context) @login_required(login_url='client_login') def summaries(request): all_summaries = Transport.objects.all().order_by('-created') summaries = Transport.objects.filter(user=request.user).all().order_by('-created') context = { 'summaries': summaries, 'all_summaries': all_summaries, } return render(request,'summaries.html', context) cl = MpesaClient() stk_push_callback_url = 'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest' b2c_callback_url = 'https://sandbox.safaricom.co.ke/mpesa/b2c/v1/paymentrequest' c2b_callback_url = 'https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl' def getAccessToken(request): consumer_key = 'GAeIsGiTzoclVjKZ0lpGkRTKqSOlM4tP' consumer_secret = '<KEY>' api_URL = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials' r = requests.get(api_URL, auth=HTTPBasicAuth(consumer_key, consumer_secret)) mpesa_access_token = json.loads(r.text) validated_mpesa_access_token = mpesa_access_token['access_token'] return HttpResponse(validated_mpesa_access_token) def oauth_success(request): r = cl.access_token() return JsonResponse(r, safe=False) def stk_push_success(request, ph_number, totalAmount): phone_number = ph_number amount = totalAmount account_reference = 'Store Centre' transaction_desc = 'STK Push Description' callback_url = stk_push_callback_url response = cl.stk_push(phone_number, amount, account_reference, transaction_desc, callback_url) return HttpResponse(response) @login_required(login_url='client_login') def payment(request): request_transport = Transport.objects.filter(user=request.user).last() request_goods = Goods.objects.filter(owner=request.user).last() paypal_client_id = settings.PAYPAL_CLIENT_ID context = { 'request_transport': request_transport, 'request_goods': request_goods, 'paypal_client_id': paypal_client_id } if request.method == 'POST': name=request.POST.get('fname') phone_number=request.POST.get('phone_number') amount=request.POST.get('amount') ph_number = None totalAmount = int(float(amount)) if phone_number[0] == '0': ph_number = '254'+ phone_number[1:] elif phone_number[0:2] == '254': ph_number = phone_number else: # messages.error(request, 'Check you Phone Number format 2547xxxxxxxx') return redirect(request.get_full_path()) stk_push_success(request, ph_number, totalAmount) request_transport.is_paid = True request_transport.save() return render (request,'success.html') if request.GET: input_value = request.GET['paypal_transaction'] if input_value: request_transport.is_paid = True request_transport.save() return render (request,'success.html') return render(request,'payment.html', context) def approval(request, request_summary_id): request_summary = Transport.objects.filter(id=request_summary_id).first() request_summary.is_approved = True request_summary.save() context ={ 'request_summary':request_summary } #email logic subject = 'TRANSPORT REQUEST APPROVAL' message = get_template('transport_approval_email.html').render(context) msg = EmailMessage( subject, message, settings.EMAIL_HOST_USER, [request_summary.email], ) msg.content_subtype = 'html' msg.send() return redirect('transport_summaries')
[ "django.shortcuts.render", "json.loads", "requests.auth.HTTPBasicAuth", "django.http.HttpResponse", "django.template.loader.get_template", "requests.get", "django_daraja.mpesa.core.MpesaClient", "django.shortcuts.redirect", "django.contrib.auth.decorators.login_required", "django.core.mail.EmailMe...
[((679, 719), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""client_login"""'}), "(login_url='client_login')\n", (693, 719), False, 'from django.contrib.auth.decorators import login_required\n'), ((2547, 2587), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""client_login"""'}), "(login_url='client_login')\n", (2561, 2587), False, 'from django.contrib.auth.decorators import login_required\n'), ((3200, 3240), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""client_login"""'}), "(login_url='client_login')\n", (3214, 3240), False, 'from django.contrib.auth.decorators import login_required\n'), ((3582, 3595), 'django_daraja.mpesa.core.MpesaClient', 'MpesaClient', ([], {}), '()\n', (3593, 3595), False, 'from django_daraja.mpesa.core import MpesaClient\n'), ((4771, 4811), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {'login_url': '"""client_login"""'}), "(login_url='client_login')\n", (4785, 4811), False, 'from django.contrib.auth.decorators import login_required\n'), ((2495, 2545), 'django.shortcuts.render', 'render', (['request', '"""request_transport.html"""', 'context'], {}), "(request, 'request_transport.html', context)\n", (2501, 2545), False, 'from django.shortcuts import redirect, render\n'), ((2962, 3050), 'django.core.mail.EmailMessage', 'EmailMessage', (['subject', 'message', 'settings.EMAIL_HOST_USER', '[request_transport.email]'], {}), '(subject, message, settings.EMAIL_HOST_USER, [request_transport\n .email])\n', (2974, 3050), False, 'from django.core.mail import EmailMessage\n'), ((3149, 3197), 'django.shortcuts.render', 'render', (['request', '"""request_summary.html"""', 'context'], {}), "(request, 'request_summary.html', context)\n", (3155, 3197), False, 'from django.shortcuts import redirect, render\n'), ((3532, 3574), 'django.shortcuts.render', 'render', (['request', '"""summaries.html"""', 'context'], {}), "(request, 'summaries.html', context)\n", (3538, 3574), False, 'from django.shortcuts import redirect, render\n'), ((4161, 4179), 'json.loads', 'json.loads', (['r.text'], {}), '(r.text)\n', (4171, 4179), False, 'import requests, json\n'), ((4261, 4303), 'django.http.HttpResponse', 'HttpResponse', (['validated_mpesa_access_token'], {}), '(validated_mpesa_access_token)\n', (4273, 4303), False, 'from django.http import HttpResponse, HttpResponseRedirect\n'), ((4364, 4391), 'django.http.response.JsonResponse', 'JsonResponse', (['r'], {'safe': '(False)'}), '(r, safe=False)\n', (4376, 4391), False, 'from django.http.response import JsonResponse\n'), ((4744, 4766), 'django.http.HttpResponse', 'HttpResponse', (['response'], {}), '(response)\n', (4756, 4766), False, 'from django.http import HttpResponse, HttpResponseRedirect\n'), ((6168, 6208), 'django.shortcuts.render', 'render', (['request', '"""payment.html"""', 'context'], {}), "(request, 'payment.html', context)\n", (6174, 6208), False, 'from django.shortcuts import redirect, render\n'), ((6605, 6691), 'django.core.mail.EmailMessage', 'EmailMessage', (['subject', 'message', 'settings.EMAIL_HOST_USER', '[request_summary.email]'], {}), '(subject, message, settings.EMAIL_HOST_USER, [request_summary.\n email])\n', (6617, 6691), False, 'from django.core.mail import EmailMessage\n'), ((6786, 6817), 'django.shortcuts.redirect', 'redirect', (['"""transport_summaries"""'], {}), "('transport_summaries')\n", (6794, 6817), False, 'from django.shortcuts import redirect, render\n'), ((5889, 5920), 'django.shortcuts.render', 'render', (['request', '"""success.html"""'], {}), "(request, 'success.html')\n", (5895, 5920), False, 'from django.shortcuts import redirect, render\n'), ((1484, 1580), 'requests.get', 'requests.get', (["(url + 'origins=' + source + '&destinations=' + destination + '&key=' + api_key\n )"], {}), "(url + 'origins=' + source + '&destinations=' + destination +\n '&key=' + api_key)\n", (1496, 1580), False, 'import requests, json\n'), ((2225, 2252), 'django.shortcuts.redirect', 'redirect', (['"""request_summary"""'], {}), "('request_summary')\n", (2233, 2252), False, 'from django.shortcuts import redirect, render\n'), ((2891, 2935), 'django.template.loader.get_template', 'get_template', (['"""transport_summary_email.html"""'], {}), "('transport_summary_email.html')\n", (2903, 2935), False, 'from django.template.loader import render_to_string, get_template\n'), ((4090, 4134), 'requests.auth.HTTPBasicAuth', 'HTTPBasicAuth', (['consumer_key', 'consumer_secret'], {}), '(consumer_key, consumer_secret)\n', (4103, 4134), False, 'from requests.auth import HTTPBasicAuth\n'), ((6123, 6154), 'django.shortcuts.render', 'render', (['request', '"""success.html"""'], {}), "(request, 'success.html')\n", (6129, 6154), False, 'from django.shortcuts import redirect, render\n'), ((6533, 6578), 'django.template.loader.get_template', 'get_template', (['"""transport_approval_email.html"""'], {}), "('transport_approval_email.html')\n", (6545, 6578), False, 'from django.template.loader import render_to_string, get_template\n')]
import numpy as np import os import torch import math class Params(object): def __init__(self): self.exp_id = '0207/exp1' self.root_params() self.network_params() self.train_params() self.load_params() self.reconstruct_params() def change_node_num(self, node_num): self.node_num = node_num def change_params(self, light_condition, resol=None): self.light_condition = light_condition # self.resol = resol print('change the parameter successfully') print('self.light_condition', self.light_condition) def root_params(self): self._datasetName = 'DTU' # specify the root folder to save experiment results. self.root_file = '' # specify the root folder of dataset. self._input_data_rootFld = '' # specify the directory for trained ckpt. self.load_checkpoint_dir = None # specify the running mode. self.mode = 'train' # reconstruct/render_novel_view/train self._debug_data_rootFld = os.path.join(self.root_file, 'debug', self.exp_id) self.summary_dir = os.path.join(self.root_file, 'experiment/train/log/', self.exp_id) print('self.summary_dir', self.summary_dir) self.checkpoint_dir = os.path.join(self.root_file, 'experiment/train/state', self.exp_id) self.rasterizer_mode = 'mesh' self.load_z_embeddings_list = True self.load_lighting_embedding_list = True self.load_optimizer_network = False self.node_num = [1] # [1,4,16]/[1] self.init_stage = 1 self.load_stage = 1 self.stage_base_num = 4 self.stage_block = [0] # [0,10,40] self.render_ob_flag = 0 self.inter_zoomin = False self.inter_choose = [0, 1, 0, 1] self.zoomin_rate = [0, 400, 0, -100] self.mask_render = False self.edit_flag = False self.save_mode = 'alpha' # gray/white/alpha self.draw_cubic_dir = os.path.join(self.root_file, 'experiment/train/cubic', self.exp_id) def network_params(self): self.image_compress_stage = 1 # this indicate the compress stage of network self.image_compress_multiple = int(2 ** (self.image_compress_stage - 1)) self.descriptor_length = 48 # 32 self.descriptor_length_c = 48 # 32 12 self.z_length_d = 48 # 32 self.z_length_c = 48 self.z_length = self.z_length_d + self.z_length_c self.descriptor_light_length = 8 # 8/4 self.embedding_light_length = 4 # 4/2 self.use_verts_grad = False self.use_2d_network = False self.use_feature_alpha = False self.use_lighting_mlp = True self.use_lighting_embedding = True self.use_D_prediction = True self.use_C_prediction = True self.use_relative_resolution = False self.use_random_ralative_resolution_ratio = False self.relative_resolution_normalize_ratio = 1e3 self.render_image_size_normalize_ratio = 300 def train_params(self): self.use_cuda = True if (self.use_cuda and torch.cuda.is_available()): self.device = torch.device("cuda") else: self.device = torch.device("cpu") self.max_epoch = 100000 self.lr_net_2d = 2e-3 self.lr_embeddings = 2e-3 self.lr_net_2d_meta = 0.2 self.lr_embeddings_meta = 0.2 self.draw_cubic_iter = 500 # 10/200 self.save_checkpoint_iter = 200 # 20/500 self.change_params_iter = 1000000 self.validate_iter = 1000000 self.loss_img_weight = 10.0 self.loss_zbuf_weight = 30.0 # self.loss_zbuf_weight = 0.0 self.loss_zbuf_residual_weight = 1e-1 self.loss_avg_weight = 0.1 self.loss_feature_var_weight = 1e0 self.backward_gradient_mode = 'together' # 'together'/'meta' def train_strategy(self, epoch): pass def reconstruct_params(self): self.total_gpu_memory = 1e8 self.return_points_colour = True self.use_points_blast = False # specify the resolution for the point cloud reconstruction. self.sample_resolution = 6 self.margin_init = 0.0 self.margin_end = 1.0 self.lighting_predict_mode = 'total' # total/s/z/n def load_params(self): self.load_view_selection_file = False self.use_sparse_embedding = True if (self._datasetName is 'DTU'): self.resol_gt = 0.2 # the coarse input point cloud resolution. self.resol_gt_render = 4.0 # specify the rendering configuration. self.render_image_size = 400 # the rendered output size, e.g. 400 means 400x400. self.random_render_image_size = [360, 400] # random rendered size for training. self.compress_ratio_h = 1 # partition num along the h axis. self.compress_ratio_w = 1 # partition num along the w axis. self.compress_ratio_total = 4 # downsample ratio for input images. self.datasetFolder = os.path.join(self._input_data_rootFld, 'DTU_MVS') self.imgNamePattern = "Rectified/scan$/rect_#_&_r5000.{}".format('png') self.poseNamePattern = "SampleSet/MVS Data/Calibration/cams/00000#_cam.txt" # replace # to {:03} SampleSet/MVS Data/Calibration/cal18/pos_#.txt self.BBNamePattern = "SampleSet/MVS Data/ObsMask/ObsMask#_10.mat" self.tranMatPattern = "advanced/Courthouse/Courthouse_trans.txt" self.gtNamePattern = 'Points/stl/stl#_total.ply' self.renderGtNamePattern = 'preprocess/ply_rmvs/#/$_surface_xyz_flow.ply'.replace('$', str(self.resol_gt_render)) self.renderResultRoot = 'experiment/render/image/view/resol:%s' % str(self.resol_gt_render) self.renderResultRoot_preprocess = 'experiment/render/numpy/id:20200608/resol:%s' % str( self.resol_gt_render) self.save_depth = False self.load_zbuf = False self.count_normal = False self.quantiGTPattern = 'Dataset/model_id:#/id:&_/' self.blur_radius = 2e-6 self.faces_per_pixel = 3 self.zbuf_front_threshold = 4.0 self.mesh_radius = self.resol_gt_render * 1.2 self.D_length = self.resol_gt_render * 1.0 self.D_min_length = 2.0 self.noise_coords_length = 1.0 self.siren_omega = 1 # 30 self.load_preprocess_index = False self.light_condition = '3' self.light_condition_list = ['3'] # ['0','1','2','3','4','5','6'] self.light_condition_random_list = ['3'] # ['1','2','3','4','5'] self.modelList = [9] # self.modelList = [1,4,15,23,114] # self.modelList = [1,4,12,13,15,23,24,29,32,33,34,48,49,62,75,77,110,114,118] # self.modelList = [1,4,9,10,11,12,13,15,23,24,29,32,33,34,48,49,62,75,77,110,114,118] self.testViewList = [22,23,25,26] # self.testViewList = [25] # self.testViewList = [13,14,15,16,24,25,26,27,31,32,33,34] # self.testViewList = [22,23,24,25,33,34,35,36,37,42,43,44,45] #35 is the center # self.testViewList = range(1,49) # self.trainViewList = [25] # self.trainViewList = range(1, 49, 2) self.trainViewList = [13, 14, 15, 16, 24, 25, 26, 27, 31, 32, 33, 34] # self.renderViewList = range(1,49,3) self.interpolate_novel_view_num = 3 self.interpolate_direction = -1 # 1,-1 self.outer_bound_factor = 0.0 self._cube_D_ = 1 self.relative_resolution_network_random_ratio = [0.8 ** 2, 6.2 ** 2] self.relative_resolution_normalize_ratio = 1e3 self.render_image_size_normalize_ratio = self.render_image_size # the original size for the loaded input images. self.img_h = 1200 self.img_w = 1600 self.image_size = torch.FloatTensor([[[self.img_w, self.img_h]]]) # the size of the input image self.image_size_single = torch.FloatTensor([[[int( self.img_w / (self.compress_ratio_w * self.compress_ratio_total)), int( self.img_h / (self.compress_ratio_h * self.compress_ratio_total))]]]) # the size of the input image self.use_random_partition = False self.partition_list = [patch for patch in range(int(self.compress_ratio_w * self.compress_ratio_h))] self.patch_random_num = 6 # the total num of patches for training, (< compress_ratio ** 2). self.estimate_normal = False self.resol = 0.8 self.random_resol_min = self.resol self.random_resol_max = self.resol self.view_group_center = [0, 2, 5, 7, 9, 11] # the center view number of each group pair self.in_group_angle = 360 * 3.1415926535 / 180 # the angle of pairs in a group self.group_pair_num_max = 4 # the maximum view number of each pair(usually it is 5) self.group_pair_num_min = 4 # the minimum view number of each pair(usually it is 2) self.min_group_num = 5 # the minimum group number self.max_group_num = 5 # the max group number self.augment_group_num = 0 self.sample_alpha = 0.5 self.sample_beta = 0.5 self.sample_delta_alpha = 0.9 self.sample_delta_beta = 0.9 self.delta_length = 20.0 self.rand_angle = 90 self.z_axis_transform_rate = 1.0 self.zbuf_min = 40 self.zbuf_max = 80 self.BB_shift = 200.0 # elif (self._datasetName is 'tanks_COLMAP'): # self.resol_gt = 0.1 # self.resol_gt_render = 0.001 # self.resol_gt_finer = 1.0 # # self.datasetFolder = os.path.join(self._input_data_rootFld, 'tanks') # # self.imgNamePattern = "intermediate/$/images/00000#.{}".format('jpg') # self.poseNamePattern = "intermediate/$/cams/00000#_cam.txt" # self.tranMatPattern = "advanced/Courthouse/Courthouse_trans.txt" # # self.BBNamePattern = "intermediate/#/BB/bbox.npy" # self.gtNamePattern = 'preprocess/intermediate/#/$_#.ply' # self.renderGtNamePattern = 'preprocess/intermediate/#/$_#.ply'.replace('$', str(self.resol_gt_render)) # self.pairPattern = "intermediate/$/pair_mvsnet.txt" # self.renderResultRoot = 'experiment/render/image/view/resol:%s' % str(self.resol_gt_render) # self.renderResultRoot_numpy = 'experiment/render/numpy/id:20200608/resol:%s' % str(self.resol_gt_finer) # self.renderResultRoot_preprocess = 'experiment/render/numpy/id:20200608/resol:%s' % str( # self.resol_gt_render) # self.save_depth = False # self.load_zbuf = False # self.load_mask = False # # self.count_normal = False # # self.quantiGTPattern = 'Dataset/model_id:#/id:&_/' # # # self.image_size = torch.FloatTensor([[[2048,1080]]]) #Lighthouse Panther M60 # self.image_size = torch.FloatTensor([[[1920, 1080]]]) # Family Train Horse # # # self.image_size_single = torch.FloatTensor([[[480, 270]]]) # the size of the input image # self.render_image_size = 500 # the rendered output size # self.random_render_image_size = [480, 500] # self.blur_radius = 4e-6 # 1e-6 # self.faces_per_pixel = 3 # self.zbuf_front_threshold = 0.02 # Lighthouse:0.0005 # self.mesh_radius = self.resol_gt_render * 1.25 # self.implicit_texture_D = 0.025 # self.D_length = self.resol_gt_render * 3.0 # self.clamp_length = 0.02 # self.clamp_length_residual = 0.01 # self.D_min_length = 0.01 # self.noise_coords_length = 0.003 # # self.alpha_density_ratio = 10 # self.alpha_density_threshold = 0.1 # self.siren_omega = 30 # # self.preprocess_ahead_faces_num = 2 # self.preprocess_face_hit_min_num = 10 # 3 / 10 # self.load_preprocess_index = False # # self.gamma_blend = 1e-4 # self.sigma_blend = 1e-4 # # self.light_condition = '3' # self.light_condition_list = ['3'] # ['0','1','2','3','4','5','6'] # self.light_condition_random_list = ['3'] # ['1','2','3','4','5'] # # self.modelList = ['Horse'] # # self.relative_resolution_network_random_ratio = [0.8 ** 2, 4 ** 2] # # self.relative_resolution_normalize_ratio = 1e3 # self.render_image_size_normalize_ratio = self.render_image_size # # # self.testViewList = range(80,122,2) # self.testViewList = [6] # # # self.trainViewList = range(0,152,1)#range(0,151,1) horse/range(0,314,1) panther/range(0,313,1) m60/range(0,301,1) train # # self.trainViewList = [6,14,15,23,26,30,34,36,40,47,49,63,67,74,77,85,88,90,94,103,112,113,120,123,130,132,135,140,142,148,151,155,163,166,170,175,231,244,247,255,265,267,273,306] #panther # # self.trainViewList = [2,8,12,13,16,21,25,27,28,30,34,37,41,47,49,51,58,59,62,66,64,69,76,77,79,84,86,88,92,94,96,99,107,116,120,122,124,126,128,130,134,137,151,158,160,164,169,172,174,186,198,200,216,223,226,239,249,254,259,266,268,270,276,279,283,290,303] #m60 # # self.trainViewList = range(0,80,2) #Family # # self.trainViewList = range(54,113,1) #Horse # # self.trainViewList = range(0, 151, 1) # self.interpolate_novel_view_num = 6 # self.interpolate_direction = -1 # 1,-1 # # self.outer_bound_factor = 0.0 # # self._cube_D_ = 1 # self.center_crop_ratio = 12.0 / 16.0 # self.cube_overlapping_ratio_for_training_sample = 0.5 # # self.compress_ratio_h = 1 # self.compress_ratio_w = 2 # self.compress_ratio_total = 2 # # self.img_h = 1080 # self.img_w = 1920 # Family Train Horse Francis # # self.img_w = 2048 #Lighthouse Panther M60 # # ############################## # self.image_size = torch.FloatTensor([[[self.img_w, self.img_h]]]) # the size of the input image # # self.image_size_single = torch.FloatTensor([[[int(self.img_w / self.compress_ratio_total), int(self.img_h / self.compress_ratio_total)]]]) # the size of the input image # self.image_size_single = torch.FloatTensor([[[int( # self.img_w / (self.compress_ratio_w * self.compress_ratio_total)), int( # self.img_h / (self.compress_ratio_h * self.compress_ratio_total))]]]) # the size of the input image # # self.use_random_partition = False # self.partition_list = [patch for patch in range(int(self.compress_ratio_w * self.compress_ratio_h))] # self.patch_random_num = 8 # the total num of patches for training, (< compress_ratio ** 2). # ############################# # # self.estimate_normal = False # # self.resol = 0.8 # self.random_resol_min = self.resol # self.random_resol_max = self.resol # # self.load_view_selection_file = True # # self.view_group_center = [0, 2, 5, 7, 10, 13, 16, 19,22, 25,28,31,34,37, 41] #the center view number of each group pair # # self.view_group_center = [0, 2, 5, 7, 10] # the center view number of each group pair # self.view_group_center = range(1, 58, 2) # # self.view_group_center = [0] # # self.view_group_center = [4, 13, 22, 31, 40, 47] # the center view number of each group pair # # self.group_pair_index = [[0,2],[1,3],[2,4],[3,5],[4,6],[5,7]] #the index of the selected group # # self.group_pair_index = [[0, 2], [1, 3], [3, 5], [4, 6], [0, 3], [4, 7], # # [2, 5], ] # the index of the selected group # self.in_group_angle = 90 * 3.1415926535 / 180 # the angle of pairs in a group # self.group_pair_num_max = 4 # the maximum view number of each pair(usually it is 5) # self.group_pair_num_min = 4 # the minimum view number of each pair(usually it is 2) # self.min_group_num = 6 # the minimum group number # self.max_group_num = 6 # the max group number # # self.augment_group_num = 0 # self.sample_alpha = 0.5 # self.sample_beta = 0.5 # self.sample_delta_alpha = 0.9 # self.sample_delta_beta = 0.9 # # self.delta_length = 20.0 # # self.rand_angle = 30 # self.rand_length = 2 / 1600.0 # 2/1600.0 # self.rand_K = 2 # 2 # # self.z_axis_transform_rate = 1e-2 # self.zbuf_min = 0 # self.zbuf_max = 100 # # self.BB_shift = 1.0 # # self.use_sparse_embedding = True # # elif (self._datasetName is 'blendedMVS'): # self.resol_gt = 2.0 # self.resol_gt_render = 0.4 # village # self.resol_gt_finer = 1.0 # # self.datasetFolder = os.path.join(self._input_data_rootFld, 'blendedMVS') # self.imgNamePattern = "$/highresol_images/00000#.{}".format('jpg') # # self.imgNamePattern = "$/blended_images/00000#.{}".format('jpg') # self.poseNamePattern = "$/highres_cams/00000#_cam.txt" # # self.poseNamePattern = "$/cams/00000#_cam.txt" # self.tranMatPattern = "advanced/Courthouse/Courthouse_trans.txt" # # self.BBNamePattern = "#/BB/bbox.npy" # self.gtNamePattern = '#/preprocess/ply/2.0_model.ply' # self.renderGtNamePattern = '#/preprocess/ply/$_#.ply'.replace('$', str(self.resol_gt_render)) # self.pairPattern = "$/cams/pair.txt" # self.renderResultRoot = 'experiment/render/image/view/resol:%s' % str(self.resol_gt_render) # self.renderResultRoot_numpy = 'experiment/render/numpy/id:20200608/resol:%s' % str(self.resol_gt_finer) # self.renderResultRoot_preprocess = 'experiment/render/numpy/id:20200608/resol:%s' % str( # self.resol_gt_render) # self.save_depth = False # self.load_zbuf = False # self.load_mask = False # # self.count_normal = False # # self.quantiGTPattern = 'Dataset/model_id:#/id:&_/' # # self.compress_ratio_h = 2 # self.compress_ratio_w = 2 # self.compress_ratio_total = 1.5 # # self.img_h = 1536 # 1536 #576 # self.img_w = 2048 # 2048 #768 # # ############################## # self.image_size = torch.FloatTensor([[[self.img_w, self.img_h]]]) # the size of the input image # # self.image_size_single = torch.FloatTensor([[[int(self.img_w / self.compress_ratio_total), int(self.img_h / self.compress_ratio_total)]]]) # the size of the input image # self.image_size_single = torch.FloatTensor([[[int( # self.img_w / (self.compress_ratio_w * self.compress_ratio_total)), int( # self.img_h / (self.compress_ratio_h * self.compress_ratio_total))]]]) # the size of the input image # # self.use_random_partition = False # self.partition_list = [patch for patch in range(int(self.compress_ratio_w * self.compress_ratio_h))] # self.patch_random_num = 3 # the total num of patches for training, (< compress_ratio ** 2). # ############################# # # self.render_image_size = 500 # the rendered output size # self.random_render_image_size = [480, 500] # self.blur_radius = 1e-6 # self.faces_per_pixel = 3 # self.zbuf_front_threshold = 0.05 # self.mesh_radius = self.resol_gt_render * 1.25 # self.implicit_texture_D = 0.025 # self.D_length = self.resol_gt_render * 3.0 # self.clamp_length = 3.0 # self.clamp_length_residual = 5.0 # self.D_min_length = 2.0 # self.noise_coords_length = 1.0 # # self.relative_resolution_normalize_ratio = 1e3 # self.render_image_size_normalize_ratio = self.render_image_size # # self.alpha_density_ratio = 10 # self.alpha_density_threshold = 0.1 # self.siren_omega = 30 # # self.preprocess_ahead_faces_num = 2 # self.preprocess_face_hit_min_num = 10 # 3 / 10 # self.load_preprocess_index = False # # self.gamma_blend = 1e-4 # self.sigma_blend = 1e-4 # # self.relative_resolution_network_random_ratio = [0.8 ** 2, 3.0 ** 2] # # self.light_condition = '3' # self.light_condition_list = ['3'] # ['0','1','2','3','4','5','6'] # self.light_condition_random_list = ['3'] # ['1','2','3','4','5'] # # # self.modelList = ['building','building3','building7','building8','building11','stadium2','stadium3','village3','village4'] # self.modelList = ['building'] # # ############################### # # self.modelList = ['building8'] # # self.modelList = ['building3'] # # self.modelList = ['village3'] # # # stadium3 # self.testViewList = [4] # [38] # ################################# # # stadium2 # # self.testViewList = [7,72,88] # # building # # self.testViewList = [7,27,57] # # building7 # # self.testViewList = [] # # building8 # # self.testViewList = [0,41,73] # # building3 # # self.testViewList = [3,22,48] # # building11 # # self.testViewList = [6,55,117] # # village3 # # self.testViewList = [1,17,23] # # village4 # # self.testViewList = [20,61,130] # # # self.trainViewList = [4,6,7,8,12,17,18,21,26,30,35,36,38,39,40,49,56,59,67,76] # # self.trainViewList = range(0, 186, 1) # # stadium3 # # self.trainViewList = range(1, 78, 2) # ##################################### # # # building # # self.trainViewList = range(0, 96, 1) # # # building7 # # self.trainViewList = range(0, 136, 2) # # # building8 # # self.trainViewList = range(0, 77, 1) #range(1,75,2) # # # building3 # # self.trainViewList = range(0, 68, 2) # # # gaoida2 # # self.trainViewList = range(0, 89, 2) # # # stadium2 # # self.trainViewList = range(0, 148, 2) # # # village3 # # self.trainViewList = range(0, 74, 2) #range(1,74,2) # # # village4 # self.trainViewList = range(0, 186, 1) # # self.interpolate_novel_view_num = 6 # self.interpolate_direction = -1 # 1,-1 # # self.outer_bound_factor = 0.0 # # self._cube_D_ = 1 # self.center_crop_ratio = 12.0 / 16.0 # self.cube_overlapping_ratio_for_training_sample = 0.5 # # self.estimate_normal = False # # self.resol = 0.8 # self.random_resol_min = self.resol # self.random_resol_max = self.resol # # # self.view_group_center = [0, 2, 5, 7, 10, 13, 16, 19,22, 25,28,31,34,37, 41] #the center view number of each group pair # # self.view_group_center = [0, 2, 5, 7, 10] # the center view number of each group pair # self.view_group_center = range(1, 94, 3) # # self.view_group_center = [4, 13, 22, 31, 40, 47] # the center view number of each group pair # # self.group_pair_index = [[0,2],[1,3],[2,4],[3,5],[4,6],[5,7]] #the index of the selected group # # self.group_pair_index = [[0, 2], [1, 3], [3, 5], [4, 6], [0, 3], [4, 7], # # [2, 5], ] # the index of the selected group # self.in_group_angle = 360 * 3.1415926535 / 180 # the angle of pairs in a group # self.group_pair_num_max = 6 # the maximum view number of each pair(usually it is 5) # self.group_pair_num_min = 6 # the minimum view number of each pair(usually it is 2) # self.min_group_num = 6 # the minimum group number # self.max_group_num = 6 # the max group number # # self.augment_group_num = 0 # self.sample_alpha = 0.5 # self.sample_beta = 0.5 # self.sample_delta_alpha = 0.9 # self.sample_delta_beta = 0.9 # # self.delta_length = 20.0 # # self.rand_angle = 30 # self.rand_length = 2 / 1600.0 # 2/1600.0 # self.rand_K = 2 # 2 # # self.z_axis_transform_rate = 0.5 # self.zbuf_min = 40 # self.zbuf_max = 80 # # self.BB_shift = 150.0 # # self.use_sparse_embedding = True # # self.load_view_selection_file = True # # elif (self._datasetName is 'giga_ours'): # self.resol_gt = 2.0 # self.resol_gt_render = 0.025 # self.resol_gt_finer = 1.0 # # self.datasetFolder = os.path.join(self._input_data_rootFld, 'giga_ours') # self.imgNamePattern = "$/images/00000#.{}".format('jpg') # self.poseNamePattern = "$/cams/00000#_cam.txt" # self.tranMatPattern = "advanced/Courthouse/Courthouse_trans.txt" # # self.BBNamePattern = "#/BB/bbox.npy" # self.gtNamePattern = '#/preprocess/ply/2.0_model.ply' # self.renderGtNamePattern = '#/preprocess/ply/$_surface_xyz_flow.ply'.replace('$', str(self.resol_gt_render)) # self.renderGtNamePattern4 = '#/preprocess/ply/$_surface_xyz_flow.ply' # self.pairPattern = "$/pair.txt" # self.renderResultRoot = 'experiment/render/image/view/resol:%s' % str(self.resol_gt_render) # self.renderResultRoot_numpy = 'experiment/render/numpy/id:20200608/resol:%s' % str(self.resol_gt_finer) # self.renderResultRoot_preprocess = 'experiment/render/numpy/id:20200608/resol:%s' % str( # self.resol_gt_render) # self.save_depth = False # self.load_zbuf = False # self.load_mask = False # # self.count_normal = False # # self.quantiGTPattern = 'Dataset/model_id:#/id:&_/' # # self.compress_ratio_h = 1 # self.compress_ratio_w = 1 # self.compress_ratio_total = 3 # # self.img_h = 1448 # self.img_w = 2172 # # ############################## # self.image_size = torch.FloatTensor([[[self.img_w, self.img_h]]]) # the size of the input image # # self.image_size_single = torch.FloatTensor([[[int(self.img_w / self.compress_ratio_total), int(self.img_h / self.compress_ratio_total)]]]) # the size of the input image # self.image_size_single = torch.FloatTensor([[[int( # self.img_w / (self.compress_ratio_w * self.compress_ratio_total)), int( # self.img_h / (self.compress_ratio_h * self.compress_ratio_total))]]]) # the size of the input image # # self.use_random_partition = False # self.partition_list = [patch for patch in range(int(self.compress_ratio_w * self.compress_ratio_h))] # self.patch_random_num = 3 # the total num of patches for training, (< compress_ratio ** 2). # ############################# # # self.render_image_size = 500 # the rendered output size # self.random_render_image_size = [480, 500] # self.blur_radius = 2e-6 # self.faces_per_pixel = 3 # self.zbuf_front_threshold = 6e-3 # self.mesh_radius = self.resol_gt_render * 1.25 # # self.mesh_radius4 = self.resoltion_list # self.implicit_texture_D = 0.025 # self.D_length = self.resol_gt_render * 3 # self.clamp_length = 3.0 # self.clamp_length_residual = 5.0 # self.D_min_length = 2.0 # self.noise_coords_length = 1.0 # # self.render_image_size_normalize_ratio = self.render_image_size # self.relative_resolution_network_random_ratio = [0.8 ** 2, 6 ** 2] # # self.alpha_density_ratio = 10 # self.alpha_density_threshold = 0.1 # self.siren_omega = 30 # # self.preprocess_ahead_faces_num = 2 # self.preprocess_face_hit_min_num = 10 # 3 / 10 # self.load_preprocess_index = False # # self.gamma_blend = 1e-4 # self.sigma_blend = 1e-4 # # self.light_condition = '3' # self.light_condition_list = ['3'] # ['0','1','2','3','4','5','6'] # self.light_condition_random_list = ['3'] # ['1','2','3','4','5'] # # self.modelList = ['like'] # # self.testViewList = [38] # [38] # # # self.trainViewList = range(0, 102, 1) # # self.trainViewList = [10, 11, 12, 13, 14, 15, 19, 23, 27, 31, 36, 37, 38, 39, 40, 42, 44, 46, 48, 51] # # self.interpolate_novel_view_num = 6 # self.interpolate_direction = -1 # 1,-1 # # self.outer_bound_factor = 0.0 # # self._cube_D_ = 1 # self.center_crop_ratio = 12.0 / 16.0 # self.cube_overlapping_ratio_for_training_sample = 0.5 # # self.estimate_normal = False # # self.resol = 0.8 # self.random_resol_min = self.resol # self.random_resol_max = self.resol # # # self.view_group_center = [0, 2, 5, 7, 10, 13, 16, 19,22, 25,28,31,34,37, 41] #the center view number of each group pair # # self.view_group_center = [0, 2, 5, 7, 10] # the center view number of each group pair # self.view_group_center = range(1, 19, 2) # # self.view_group_center = [4, 13, 22, 31, 40, 47] # the center view number of each group pair # # self.group_pair_index = [[0,2],[1,3],[2,4],[3,5],[4,6],[5,7]] #the index of the selected group # # self.group_pair_index = [[0, 2], [1, 3], [3, 5], [4, 6], [0, 3], [4, 7], # # [2, 5], ] # the index of the selected group # self.in_group_angle = 360 * 3.1415926535 / 180 # the angle of pairs in a group # self.group_pair_num_max = 4 # the maximum view number of each pair(usually it is 5) # self.group_pair_num_min = 4 # the minimum view number of each pair(usually it is 2) # self.min_group_num = 6 # the minimum group number # self.max_group_num = 6 # the max group number view_list = # # self.augment_group_num = 0 # self.sample_alpha = 0.5 # self.sample_beta = 0.5 # self.sample_delta_alpha = 0.9 # self.sample_delta_beta = 0.9 # # self.delta_length = 20.0 # # self.rand_angle = 30 # self.rand_length = 2 / 1600.0 # 2/1600.0 # self.rand_K = 2 # 2 # # self.z_axis_transform_rate = 1e-2 # self.zbuf_min = 40 # self.zbuf_max = 80 # # self.BB_shift = 6.0 # def change_render_mode(self): # if self.mode is 'reconstruct': # self.trainViewList = [25] # self.testViewList = [25] # range(30,36) # self.use_points_blast = False # self.total_gpu_memory = 2e7 if self.mode is 'refine_points': self.use_random_ralative_resolution_ratio = False self.testViewList = range(1, 49, 2) # [13,14,15,16]#[13,14,15,16,24,25,26,27,31,32,33,34] self.load_preprocess_index = False # self.modelList = [1,4,9,10,11,12,13,15,23,24,29,32,33,34,48,49,62,75,77,110,114,118] self.modelList = [9, 10, 11, 12, 13, 15, 23, 24, 29, 32, 33, 34, 48, 49, 62, 75, 77, 110, 114, 118] self.group_pair_num_max = 1 self.group_pair_num_min = 1 self.preprocess_ahead_faces_num = 3 self.preprocess_face_hit_min_num = 1 # 3 / 10
[ "torch.cuda.is_available", "os.path.join", "torch.FloatTensor", "torch.device" ]
[((1069, 1119), 'os.path.join', 'os.path.join', (['self.root_file', '"""debug"""', 'self.exp_id'], {}), "(self.root_file, 'debug', self.exp_id)\n", (1081, 1119), False, 'import os\n'), ((1147, 1213), 'os.path.join', 'os.path.join', (['self.root_file', '"""experiment/train/log/"""', 'self.exp_id'], {}), "(self.root_file, 'experiment/train/log/', self.exp_id)\n", (1159, 1213), False, 'import os\n'), ((1296, 1363), 'os.path.join', 'os.path.join', (['self.root_file', '"""experiment/train/state"""', 'self.exp_id'], {}), "(self.root_file, 'experiment/train/state', self.exp_id)\n", (1308, 1363), False, 'import os\n'), ((2014, 2081), 'os.path.join', 'os.path.join', (['self.root_file', '"""experiment/train/cubic"""', 'self.exp_id'], {}), "(self.root_file, 'experiment/train/cubic', self.exp_id)\n", (2026, 2081), False, 'import os\n'), ((3155, 3180), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3178, 3180), False, 'import torch\n'), ((3209, 3229), 'torch.device', 'torch.device', (['"""cuda"""'], {}), "('cuda')\n", (3221, 3229), False, 'import torch\n'), ((3270, 3289), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (3282, 3289), False, 'import torch\n'), ((5152, 5201), 'os.path.join', 'os.path.join', (['self._input_data_rootFld', '"""DTU_MVS"""'], {}), "(self._input_data_rootFld, 'DTU_MVS')\n", (5164, 5201), False, 'import os\n'), ((8230, 8277), 'torch.FloatTensor', 'torch.FloatTensor', (['[[[self.img_w, self.img_h]]]'], {}), '([[[self.img_w, self.img_h]]])\n', (8247, 8277), False, 'import torch\n')]
#from setuptools import setup, find_packages #from os import getcwd, path import os import sys import json import config #currentDir = getcwd() ''' # Get Readme text with open(path.join(currentDir, 'README.md'), encoding='utf-8') as fR: readme = fR.read() ''' # Run setup ''' setup( # Project's name name='Backer', # Project's version number # Major.Moderate.Minor values version='1.0.0', # Project's description description='Backup software for maintaining a backup of files and zip and archive at set times', # Project's long description # Readme can't have links to external pages but # external badges and images are permitted long_description=readme, # Define markdown long description type long_description_content_type='text/markdown' # Author's name author='<NAME>', # Author's contact author_email='<EMAIL>', # Maintainer's name maintainer='<NAME>', # Maintainer's email maintainer_email='<EMAIL>', # Project's home page url='https://github.com/RafaelCenzano/backer', # Classifiers help users find your project by categorizing it. classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', # Pick your license as you wish #'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. # Python 2 loses support as of 2020 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], # Keywords/Tags keywords='backup backer', # Finds project files packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Needed installs #install_requires=[], # Data files # package_data={ # 'sample': ['package_data.dat'], # }, # Python requirement #python_requires='>=3.4', # Adds CLI #entry_points={ # 'console_scripts': [ # 'sample cli command = projectName.FileName:FunctionName', # ], #}, # Additional links #project_urls={ # 'Bug Reports': '', # 'Source': '', #}, ) # setup.py generated using PyStarter # https://pypi.org/project/PyStarter/ # pip3 install pystarter # The above message can be deleted, it does not effect the python code. ''' # Create config object configurations = config.Config() # Check for backup folder if os.path.isdir(f'/{configurations.BACKUP_FOLDER}/') == False: sys.exit('Backup folder not found') # check that folders to zip exsist, exit and alert user if folder not found for folders in configurations.FOLDERS_TO_ZIP: if os.path.isdir(f'/{folders}/') == False: sys.exit(f'Folder: {folders} not found') # Check days to store count is valid if isinstance(configurations.DAYS_TO_STORE, int) == False or configurations.DAYS_TO_STORE <= 0 or configurations.DAYS_TO_STORE > 6: sys.exit('DAYS_TO_STORE is too large or small or not an integer') # Check weeks to store count is valid if isinstance(configurations.WEEKS_TO_STORE, int) == False or configurations.WEEKS_TO_STORE <= 0 or configurations.WEEKS_TO_STORE > 3: sys.exit('WEEKS_TO_STORE is too large or small or not an integer') # Check months to store count is valid if isinstance(configurations.MONTHS_TO_STORE, int) == False or configurations.MONTHS_TO_STORE <= 0 or configurations.MONTHS_TO_STORE > 12: sys.exit('MONTHS_TO_STORE is too large or small or not an integer') # Create day folder to store daily backups, if folder doesn't exsist already if os.path.isdir(f'/{configurations.BACKUP_FOLDER}/day/') == False: os.mkdir(f'/{configurations.BACKUP_FOLDER}/day/') # Create week folder to store weekly backups, if folder doesn't exsist already if os.path.isdir(f'/{configurations.BACKUP_FOLDER}/week/') == False: os.mkdir(f'/{configurations.BACKUP_FOLDER}/week/') # Create month folder to store monthly backups, if folder doesn't exsist already if os.path.isdir(f'/{configurations.BACKUP_FOLDER}/month/') == False: os.mkdir(f'/{configurations.BACKUP_FOLDER}/month/') # Create data folder to store data on backups, if folder doesn't exsist already if os.path.isdir(f'/{configurations.BACKUP_FOLDER}/data/') == False: os.mkdir(f'/{configurations.BACKUP_FOLDER}/data/') # Create json data file to store backup data, if folder doesn't exsist already if os.path.isfile(f'/{configurations.BACKUP_FOLDER}/data/data.json') == False: jsonData = { 'month': {}, 'week': {}, 'day': {} } with open(f'/{configurations.BACKUP_FOLDER}/data/data.json', 'w') as jsonFile: json.dump(jsonData, jsonFile) print('Follow instructions in README on how to set up cron jobs')
[ "config.Config", "os.path.isfile", "os.path.isdir", "os.mkdir", "sys.exit", "json.dump" ]
[((2860, 2875), 'config.Config', 'config.Config', ([], {}), '()\n', (2873, 2875), False, 'import config\n'), ((2906, 2956), 'os.path.isdir', 'os.path.isdir', (['f"""/{configurations.BACKUP_FOLDER}/"""'], {}), "(f'/{configurations.BACKUP_FOLDER}/')\n", (2919, 2956), False, 'import os\n'), ((2971, 3006), 'sys.exit', 'sys.exit', (['"""Backup folder not found"""'], {}), "('Backup folder not found')\n", (2979, 3006), False, 'import sys\n'), ((3400, 3465), 'sys.exit', 'sys.exit', (['"""DAYS_TO_STORE is too large or small or not an integer"""'], {}), "('DAYS_TO_STORE is too large or small or not an integer')\n", (3408, 3465), False, 'import sys\n'), ((3644, 3710), 'sys.exit', 'sys.exit', (['"""WEEKS_TO_STORE is too large or small or not an integer"""'], {}), "('WEEKS_TO_STORE is too large or small or not an integer')\n", (3652, 3710), False, 'import sys\n'), ((3894, 3961), 'sys.exit', 'sys.exit', (['"""MONTHS_TO_STORE is too large or small or not an integer"""'], {}), "('MONTHS_TO_STORE is too large or small or not an integer')\n", (3902, 3961), False, 'import sys\n'), ((4043, 4097), 'os.path.isdir', 'os.path.isdir', (['f"""/{configurations.BACKUP_FOLDER}/day/"""'], {}), "(f'/{configurations.BACKUP_FOLDER}/day/')\n", (4056, 4097), False, 'import os\n'), ((4112, 4161), 'os.mkdir', 'os.mkdir', (['f"""/{configurations.BACKUP_FOLDER}/day/"""'], {}), "(f'/{configurations.BACKUP_FOLDER}/day/')\n", (4120, 4161), False, 'import os\n'), ((4245, 4300), 'os.path.isdir', 'os.path.isdir', (['f"""/{configurations.BACKUP_FOLDER}/week/"""'], {}), "(f'/{configurations.BACKUP_FOLDER}/week/')\n", (4258, 4300), False, 'import os\n'), ((4315, 4365), 'os.mkdir', 'os.mkdir', (['f"""/{configurations.BACKUP_FOLDER}/week/"""'], {}), "(f'/{configurations.BACKUP_FOLDER}/week/')\n", (4323, 4365), False, 'import os\n'), ((4451, 4507), 'os.path.isdir', 'os.path.isdir', (['f"""/{configurations.BACKUP_FOLDER}/month/"""'], {}), "(f'/{configurations.BACKUP_FOLDER}/month/')\n", (4464, 4507), False, 'import os\n'), ((4522, 4573), 'os.mkdir', 'os.mkdir', (['f"""/{configurations.BACKUP_FOLDER}/month/"""'], {}), "(f'/{configurations.BACKUP_FOLDER}/month/')\n", (4530, 4573), False, 'import os\n'), ((4658, 4713), 'os.path.isdir', 'os.path.isdir', (['f"""/{configurations.BACKUP_FOLDER}/data/"""'], {}), "(f'/{configurations.BACKUP_FOLDER}/data/')\n", (4671, 4713), False, 'import os\n'), ((4728, 4778), 'os.mkdir', 'os.mkdir', (['f"""/{configurations.BACKUP_FOLDER}/data/"""'], {}), "(f'/{configurations.BACKUP_FOLDER}/data/')\n", (4736, 4778), False, 'import os\n'), ((4862, 4927), 'os.path.isfile', 'os.path.isfile', (['f"""/{configurations.BACKUP_FOLDER}/data/data.json"""'], {}), "(f'/{configurations.BACKUP_FOLDER}/data/data.json')\n", (4876, 4927), False, 'import os\n'), ((3137, 3166), 'os.path.isdir', 'os.path.isdir', (['f"""/{folders}/"""'], {}), "(f'/{folders}/')\n", (3150, 3166), False, 'import os\n'), ((3185, 3225), 'sys.exit', 'sys.exit', (['f"""Folder: {folders} not found"""'], {}), "(f'Folder: {folders} not found')\n", (3193, 3225), False, 'import sys\n'), ((5117, 5146), 'json.dump', 'json.dump', (['jsonData', 'jsonFile'], {}), '(jsonData, jsonFile)\n', (5126, 5146), False, 'import json\n')]
import unittest from django.apps import apps from tethys_config.apps import TethysPortalConfig class TethysConfigAppsTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_TethysPortalConfig(self): app_config = apps.get_app_config('tethys_config') name = app_config.name verbose_name = app_config.verbose_name self.assertEqual('tethys_config', name) self.assertEqual('Tethys Portal', verbose_name) self.assertTrue(isinstance(app_config, TethysPortalConfig))
[ "django.apps.apps.get_app_config" ]
[((279, 315), 'django.apps.apps.get_app_config', 'apps.get_app_config', (['"""tethys_config"""'], {}), "('tethys_config')\n", (298, 315), False, 'from django.apps import apps\n')]
import pygame import math from pygame import mixer import os pygame.init() WIDTH, HEIGHT = 800, 600 #create the screen screen = pygame.display.set_mode((WIDTH , HEIGHT)) # Title and Icon pygame.display.set_caption("Space Fighter") icon = pygame.image.load(os.path.join('assets', 'icon.png')) pygame.display.set_icon(icon) # Background background = pygame.image.load(os.path.join('assets', 'bg.png')) # Background Music mixer.music.load(os.path.join('sounds', 'bgmusic.mp3')) mixer.music.play(-1) #Player 1 player1 = pygame.transform.scale(pygame.transform.flip(pygame.image.load(os.path.join('assets', 'player1.png')), True, False), (70,70)) player1X = 20 player1Y = HEIGHT/2 - 35 player1_change = 0 #Player 2 player2 = pygame.transform.scale(pygame.transform.flip(pygame.image.load(os.path.join('assets', 'player2.png')), False, False), (70,70)) player2X = WIDTH - 90 player2Y = HEIGHT/2 - 35 player2_change = 0 #Bullet of PLayer 1 bullet1 = pygame.transform.scale(pygame.transform.rotate(pygame.image.load(os.path.join('assets', 'bullet1.png')), 90), (40, 40)) bullet1X = 0 bullet1Y = 0 bullet1_change = 1.5 fire1 = True #Bullet of PLayer 2 bullet2 = pygame.transform.scale(pygame.transform.rotate(pygame.image.load(os.path.join('assets', 'bullet2.png')), -90), (40, 40)) bullet2X = 0 bullet2Y = 0 bullet2_change = 1.5 fire2 = True # Score Variable scoreOne = 0 scoreTwo = 0 # Loading Font font = pygame.font.Font(os.path.join('fonts', 'Gameplay.ttf'), 32) over_font = pygame.font.Font(os.path.join('fonts', 'Gameplay.ttf'), 70) # Score display coordinates of player 1 text1X = 20 text1Y = 20 # Score display coordinates of player 2 text2X = WIDTH - 230 text2Y = 20 def playerOneMovement(X, Y): screen.blit(player1, (X, Y + 15)) def playerTwoMovement(X, Y): screen.blit(player2, (X, Y + 15)) def bullet1Movement(X, Y): global fire1 fire1 = False screen.blit(bullet1, (X + 45, Y + 22)) def bullet2Movement(X, Y): global fire2 fire2 = False screen.blit(bullet2, (X - 15, Y + 22)) def collisionDetectorPlayerOne(b1x, b1y, p2x , p2y): global fire1 global bullet1X global bullet1Y if int(math.sqrt(math.pow(p2x - b1x, 2) + math.pow(p2y - b1y, 2))) < 70: fire1 = True bullet1X = 0 bullet1X = 0 return True def collisionDetectorPlayerTwo(b2x, b2y, p1x, p1y): global fire2 global bullet2X global bullet2Y distance = int(math.sqrt(math.pow(b2x - p1x, 2) + math.pow(b2y - p1y, 2))) if distance < 70 and distance > 20 : fire2 = True bullet2X = 0 bullet2Y = 0 return True def displayScore(X, Y): score = font.render("Score : " + str(scoreOne), True, (255, 255, 255)) screen.blit(score, (X, Y)) def displayScoreTwo(X, Y) : score = font.render("Score : " + str(scoreTwo), True, (255, 255, 255)) screen.blit(score, (X, Y)) def gameover(): global scoreOne global scoreTwo score = over_font.render("GAMEOVER", True, (255, 255, 255)) screen.blit(score, (200, 250)) if scoreOne == 10: display = font.render("PLAYER ONE WON", True, (255, 255, 255)) screen.blit(display, (260, 330)) elif scoreTwo == 10: display = font.render("PLAYER TWO WON", True, (255, 255, 255)) screen.blit(display, (260, 330)) running = True while running: #Backgroung Image screen.blit(background, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False #Movement Detection for player 1 if event.type == pygame.KEYDOWN: if event.key == pygame.K_w: player1_change = -2 if event.key == pygame.K_s: player1_change = +2 if event.key == pygame.K_SPACE: if fire1 is True: fire1_sound = mixer.Sound(os.path.join('sounds', 'fire1.wav')) fire1_sound.play() bullet1X = player1X bullet1Y = player1Y bullet1Movement(bullet1X, bullet1Y) if event.type == pygame.KEYUP: if event.key == pygame.K_w or event.key == pygame.K_s: player1_change = 0 #Movement Detection for player 2 if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: player2_change = -2 if event.key == pygame.K_DOWN: player2_change = +2 if event.key == pygame.K_RCTRL: if fire2 is True: fire2_sound = mixer.Sound(os.path.join('sounds', 'fire1.wav')) fire2_sound.play() bullet2X = player2X bullet2Y = player2Y bullet2Movement(bullet2X, bullet2Y) if event.type == pygame.KEYUP: if event.key == pygame.K_UP or event.key == pygame.K_DOWN: player2_change = 0 #Movement Calculation for player 1 player1Y += player1_change if player1Y <= 70: player1Y = 70 if player1Y >= HEIGHT-90: player1Y = HEIGHT-90 #Movement Calculation for player 2 player2Y += player2_change if player2Y <= 70: player2Y = 70 if player2Y >= HEIGHT-90: player2Y = HEIGHT-90 # Bullet Movement for player 1 if bullet1X >= WIDTH : fire1 = True if fire1 is False: bullet1Movement(bullet1X, bullet1Y) bullet1X += bullet1_change # Bullet Movement for player 2 if bullet2X <= 0: fire2 = True if fire2 is False: bullet2Movement(bullet2X, bullet2Y) bullet2X -= bullet2_change #Checking for Collision if collisionDetectorPlayerOne(bullet1X, bullet1Y, player2X, player2Y) is True: scoreOne += 1 if collisionDetectorPlayerTwo(bullet2X, bullet2Y, player1X, player1Y) is True: scoreTwo += 1 #Checking for Who Won if scoreOne == 10 or scoreTwo == 10: gameover() displayScore(text1X, text1Y) displayScoreTwo(text2X, text2Y) playerOneMovement(player1X, player1Y) playerTwoMovement(player2X, player2Y) pygame.display.update()
[ "pygame.init", "pygame.event.get", "math.pow", "pygame.display.set_mode", "pygame.display.set_icon", "os.path.join", "pygame.display.set_caption", "pygame.display.update", "pygame.mixer.music.play" ]
[((67, 80), 'pygame.init', 'pygame.init', ([], {}), '()\n', (78, 80), False, 'import pygame\n'), ((141, 181), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(WIDTH, HEIGHT)'], {}), '((WIDTH, HEIGHT))\n', (164, 181), False, 'import pygame\n'), ((204, 247), 'pygame.display.set_caption', 'pygame.display.set_caption', (['"""Space Fighter"""'], {}), "('Space Fighter')\n", (230, 247), False, 'import pygame\n'), ((311, 340), 'pygame.display.set_icon', 'pygame.display.set_icon', (['icon'], {}), '(icon)\n', (334, 340), False, 'import pygame\n'), ((506, 526), 'pygame.mixer.music.play', 'mixer.music.play', (['(-1)'], {}), '(-1)\n', (522, 526), False, 'from pygame import mixer\n'), ((274, 308), 'os.path.join', 'os.path.join', (['"""assets"""', '"""icon.png"""'], {}), "('assets', 'icon.png')\n", (286, 308), False, 'import os\n'), ((391, 423), 'os.path.join', 'os.path.join', (['"""assets"""', '"""bg.png"""'], {}), "('assets', 'bg.png')\n", (403, 423), False, 'import os\n'), ((466, 503), 'os.path.join', 'os.path.join', (['"""sounds"""', '"""bgmusic.mp3"""'], {}), "('sounds', 'bgmusic.mp3')\n", (478, 503), False, 'import os\n'), ((1487, 1524), 'os.path.join', 'os.path.join', (['"""fonts"""', '"""Gameplay.ttf"""'], {}), "('fonts', 'Gameplay.ttf')\n", (1499, 1524), False, 'import os\n'), ((1560, 1597), 'os.path.join', 'os.path.join', (['"""fonts"""', '"""Gameplay.ttf"""'], {}), "('fonts', 'Gameplay.ttf')\n", (1572, 1597), False, 'import os\n'), ((3571, 3589), 'pygame.event.get', 'pygame.event.get', ([], {}), '()\n', (3587, 3589), False, 'import pygame\n'), ((6540, 6563), 'pygame.display.update', 'pygame.display.update', ([], {}), '()\n', (6561, 6563), False, 'import pygame\n'), ((614, 651), 'os.path.join', 'os.path.join', (['"""assets"""', '"""player1.png"""'], {}), "('assets', 'player1.png')\n", (626, 651), False, 'import os\n'), ((825, 862), 'os.path.join', 'os.path.join', (['"""assets"""', '"""player2.png"""'], {}), "('assets', 'player2.png')\n", (837, 862), False, 'import os\n'), ((1057, 1094), 'os.path.join', 'os.path.join', (['"""assets"""', '"""bullet1.png"""'], {}), "('assets', 'bullet1.png')\n", (1069, 1094), False, 'import os\n'), ((1275, 1312), 'os.path.join', 'os.path.join', (['"""assets"""', '"""bullet2.png"""'], {}), "('assets', 'bullet2.png')\n", (1287, 1312), False, 'import os\n'), ((2553, 2575), 'math.pow', 'math.pow', (['(b2x - p1x)', '(2)'], {}), '(b2x - p1x, 2)\n', (2561, 2575), False, 'import math\n'), ((2578, 2600), 'math.pow', 'math.pow', (['(b2y - p1y)', '(2)'], {}), '(b2y - p1y, 2)\n', (2586, 2600), False, 'import math\n'), ((2260, 2282), 'math.pow', 'math.pow', (['(p2x - b1x)', '(2)'], {}), '(p2x - b1x, 2)\n', (2268, 2282), False, 'import math\n'), ((2285, 2307), 'math.pow', 'math.pow', (['(p2y - b1y)', '(2)'], {}), '(p2y - b1y, 2)\n', (2293, 2307), False, 'import math\n'), ((4073, 4108), 'os.path.join', 'os.path.join', (['"""sounds"""', '"""fire1.wav"""'], {}), "('sounds', 'fire1.wav')\n", (4085, 4108), False, 'import os\n'), ((4861, 4896), 'os.path.join', 'os.path.join', (['"""sounds"""', '"""fire1.wav"""'], {}), "('sounds', 'fire1.wav')\n", (4873, 4896), False, 'import os\n')]
import reframe as rfm import reframe.utility.sanity as sn @rfm.simple_test class np_max_test(rfm.RunOnlyRegressionTest): omp_threads = parameter([12]) # mpi_rks = parameter([1, 2]) np_per_c = parameter([ 1.8e6, 2.0e6, 2.2e6, 2.4e6, 2.6e6, 2.8e6, 3.0e6, 3.2e6, 3.4e6, 3.6e6, 3.8e6, 4.0e6, 4.2e6, 4.4e6, 4.6e6, 4.8e6, 5.0e6, 5.2e6, 5.4e6, 5.6e6, 5.8e6, 6.0e6, 6.2e6, 6.4e6, 6.6e6, # oom: 6.8e6, ]) mpi_rks = parameter([1]) # np_per_c = parameter([1e6]) steps = variable(str, value='0') valid_systems = ['*'] valid_prog_environs = ['*'] modules = ['cdt-cuda/21.05', 'cudatoolkit/11.2.0_3.39-2.1__gf93aa1c'] sourcesdir = None prerun_cmds = ['module list'] postrun_cmds = ['sleep 5'] # give jobreport a chance # Number of cores for each system cores = variable(dict, value={ 'daint:gpu': 12, }) @run_before('run') def set_cubeside(self): phys_core_per_node = self.cores.get(self.current_partition.fullname, 1) # total_np = (phys_core_per_node * self.np_per_c) total_np = (phys_core_per_node * self.mpi_rks * self.np_per_c) self.cubeside = int(pow(total_np, 1 / 3)) self.executable = \ '$SCRATCH/SPH-EXA_mini-app.git/JG/src/sedov/sedov-cuda' self.executable_opts += [f"-n {self.cubeside}", f"-s {self.steps}"] @run_before('run') def set_num_threads(self): # num_threads = self.cores.get(self.current_partition.fullname, 1) # self.num_cpus_per_task = num_threads self.num_tasks_per_node = 1 self.num_cpus_per_task = self.omp_threads self.variables = { 'OMP_NUM_THREADS': str(self.omp_threads), # 'OMP_PLACES': 'cores' } @sanity_function def check_execution(self): regex = r'Total execution time of \d+ iterations of \S+' return sn.assert_found(regex, self.stdout) @performance_function('') def nsteps(self): regex = r'# Total execution time of (\d+) iterations of \S+:' return sn.extractsingle(regex, self.stdout, 1, int) @performance_function('') def n_cubeside(self): regex = r'Domain synchronized, nLocalParticles (\d+)' n_particles = sn.extractsingle(regex, self.stdout, 1, int) return int(pow(sn.evaluate(n_particles), 1/3)) @performance_function('') def np_per_cnode(self): regex = r'Domain synchronized, nLocalParticles (\d+)' n_particles = sn.extractsingle(regex, self.stdout, 1, int) return int(sn.evaluate(n_particles) / self.mpi_rks) @performance_function('') def nparticles(self): regex = r'Domain synchronized, nLocalParticles (\d+)' return sn.extractsingle(regex, self.stdout, 1, int) # n_particles = \ # sn.evaluate(sn.extractsingle(regex, self.stdout, 1, int)) # return f'{n_particles:.1E}' # the value extracted for performance variable # 'daint:gpu:nparticles' is not a number: 1.2E+07 # return np.format_float_scientific(n_particles, precision=2, # exp_digits=1) @performance_function('s') def elapsed(self): regex = r'# Total execution time of \d+ iterations of \S+: (\S+)s' return sn.extractsingle(regex, self.stdout, 1, float) @performance_function('MiB') def max_gpu_memory(self): # Node name Usage Max mem Execution time # ------------ ----------- ------------ -------------- # nid06681 38 % 2749 MiB 00:00:06 regex = r'^\s+nid\S+\s+\d+\s+%\s+(\d+)\s+MiB.*:' return sn.max(sn.extractall(regex, self.stdout, 1, int))
[ "reframe.utility.sanity.extractsingle", "reframe.utility.sanity.evaluate", "reframe.utility.sanity.extractall", "reframe.utility.sanity.assert_found" ]
[((1922, 1957), 'reframe.utility.sanity.assert_found', 'sn.assert_found', (['regex', 'self.stdout'], {}), '(regex, self.stdout)\n', (1937, 1957), True, 'import reframe.utility.sanity as sn\n'), ((2096, 2140), 'reframe.utility.sanity.extractsingle', 'sn.extractsingle', (['regex', 'self.stdout', '(1)', 'int'], {}), '(regex, self.stdout, 1, int)\n', (2112, 2140), True, 'import reframe.utility.sanity as sn\n'), ((2282, 2326), 'reframe.utility.sanity.extractsingle', 'sn.extractsingle', (['regex', 'self.stdout', '(1)', 'int'], {}), '(regex, self.stdout, 1, int)\n', (2298, 2326), True, 'import reframe.utility.sanity as sn\n'), ((2525, 2569), 'reframe.utility.sanity.extractsingle', 'sn.extractsingle', (['regex', 'self.stdout', '(1)', 'int'], {}), '(regex, self.stdout, 1, int)\n', (2541, 2569), True, 'import reframe.utility.sanity as sn\n'), ((2764, 2808), 'reframe.utility.sanity.extractsingle', 'sn.extractsingle', (['regex', 'self.stdout', '(1)', 'int'], {}), '(regex, self.stdout, 1, int)\n', (2780, 2808), True, 'import reframe.utility.sanity as sn\n'), ((3327, 3373), 'reframe.utility.sanity.extractsingle', 'sn.extractsingle', (['regex', 'self.stdout', '(1)', 'float'], {}), '(regex, self.stdout, 1, float)\n', (3343, 3373), True, 'import reframe.utility.sanity as sn\n'), ((3706, 3747), 'reframe.utility.sanity.extractall', 'sn.extractall', (['regex', 'self.stdout', '(1)', 'int'], {}), '(regex, self.stdout, 1, int)\n', (3719, 3747), True, 'import reframe.utility.sanity as sn\n'), ((2350, 2374), 'reframe.utility.sanity.evaluate', 'sn.evaluate', (['n_particles'], {}), '(n_particles)\n', (2361, 2374), True, 'import reframe.utility.sanity as sn\n'), ((2589, 2613), 'reframe.utility.sanity.evaluate', 'sn.evaluate', (['n_particles'], {}), '(n_particles)\n', (2600, 2613), True, 'import reframe.utility.sanity as sn\n')]
from kerashistoryplot.data import (get_metrics, _get_batch_metric_vs_epoch, get_metric_vs_epoch) HISTORY = { 'batches': [ { 'batch': [0, 1], 'size': [300, 200], 'loss': [0.4, 0.3], 'mean_absolute_error': [0.28948462, 0.2989089] }, { 'batch': [0, 1], 'size': [300, 200], 'loss': [0.2, 0.1], 'mean_absolute_error': [0.30267844, 0.2740341] } ], 'val_loss': [0.37, 0.17], 'val_mean_absolute_error': [0.2915948450565338, 0.2897853195667267], 'loss': [0.35, 0.15], 'mean_absolute_error': [0.29325432777404786, 0.2912207067012787], 'lr': [0.01, 0.01], 'epoch': [0, 1] } def test_get_metrics(): plot_metrics = get_metrics(HISTORY) assert set(plot_metrics) == set(['loss', 'mean_absolute_error', 'lr']) class TestGetMetricVsEpoch: def test_simple_case(self): plot_data = get_metric_vs_epoch(HISTORY, metric='lr') expected_data = [{'x': [0, 1], 'y': [0.01, 0.01], 'label': 'lr'}] assert plot_data == expected_data def test_get_batch_metric_vs_epoch(self): batch_data = _get_batch_metric_vs_epoch(HISTORY, metric='loss') expected_data = { 'x': [0, 0, 1, 1], 'y': [0.4, 0.3, 0.2, 0.1], 'label': 'batch_loss' } assert batch_data == expected_data def test_case_with_val_and_batches(self): plot_data = get_metric_vs_epoch(HISTORY, metric='loss') expected_data = [ { 'x': [0, 1], 'y': [0.35, 0.15], 'label': 'loss' }, { 'x': [0, 1], 'y': [0.37, 0.17], 'label': 'val_loss' }, { 'x': [0, 0, 1, 1], 'y': [0.4, 0.3, 0.2, 0.1], 'label': 'batch_loss' } ] assert plot_data == expected_data
[ "kerashistoryplot.data.get_metrics", "kerashistoryplot.data.get_metric_vs_epoch", "kerashistoryplot.data._get_batch_metric_vs_epoch" ]
[((839, 859), 'kerashistoryplot.data.get_metrics', 'get_metrics', (['HISTORY'], {}), '(HISTORY)\n', (850, 859), False, 'from kerashistoryplot.data import get_metrics, _get_batch_metric_vs_epoch, get_metric_vs_epoch\n'), ((1017, 1058), 'kerashistoryplot.data.get_metric_vs_epoch', 'get_metric_vs_epoch', (['HISTORY'], {'metric': '"""lr"""'}), "(HISTORY, metric='lr')\n", (1036, 1058), False, 'from kerashistoryplot.data import get_metrics, _get_batch_metric_vs_epoch, get_metric_vs_epoch\n'), ((1244, 1294), 'kerashistoryplot.data._get_batch_metric_vs_epoch', '_get_batch_metric_vs_epoch', (['HISTORY'], {'metric': '"""loss"""'}), "(HISTORY, metric='loss')\n", (1270, 1294), False, 'from kerashistoryplot.data import get_metrics, _get_batch_metric_vs_epoch, get_metric_vs_epoch\n'), ((1546, 1589), 'kerashistoryplot.data.get_metric_vs_epoch', 'get_metric_vs_epoch', (['HISTORY'], {'metric': '"""loss"""'}), "(HISTORY, metric='loss')\n", (1565, 1589), False, 'from kerashistoryplot.data import get_metrics, _get_batch_metric_vs_epoch, get_metric_vs_epoch\n')]
import tensorflow as tf from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding from tensorflow.keras.activations import softmax, linear import tensorflow.keras.backend as K import numpy as np def gelu(x): return 0.5*x*(1+tf.tanh(np.sqrt(2/np.pi)*(x+0.044715*tf.pow(x, 3)))) class scaledDotProductAttentionLayer(tf.keras.layers.Layer): def call(self, x, training): q, k, v = x qk = tf.matmul(q, k, transpose_b=True)/K.sqrt(tf.cast(K.shape(k)[-1], tf.float32)) return tf.matmul(softmax(qk, axis=-1), v) class multiHeadAttentionLayer(tf.keras.layers.Layer): def __init__(self, d_model, head=12): super(multiHeadAttentionLayer, self).__init__() self.head = head self.permute = Permute((2, 1, 3)) self.re1 = Reshape((-1, self.head, d_model//self.head)) self.re2 = Reshape((-1, d_model)) self.linear = Dense(d_model) def call(self, x, training): q, k, v = x # subspace header q_s = self.permute(self.re1(q)) k_s = self.permute(self.re1(k)) v_s = self.permute(self.re1(v)) # combine head head = scaledDotProductAttentionLayer()([q_s, k_s, v_s], training) scaled_attention = self.permute(head) concat_attention = self.re2(self.permute(scaled_attention)) multi_head = self.linear(concat_attention) return multi_head class mlpLayer(tf.keras.layers.Layer): def __init__(self, hidden_dim, output_dim): super(mlpLayer, self).__init__() self.d1 = Dense(hidden_dim, activation=gelu)#, kernel_regularizer=tf.keras.regularizers.l2(0.1)) self.d2 = Dense(output_dim)#, kernel_regularizer=tf.keras.regularizers.l2(0.1)) def call(self, x, training): x = self.d1(x) return self.d2(x) class transformerBlock(tf.keras.layers.Layer): def __init__(self, d_model, head_num=12, h_dim=3072): super(transformerBlock, self).__init__() self.q_d = Dense(d_model) self.k_d = Dense(d_model) self.v_d = Dense(d_model) self.ln1 = LayerNormalization(epsilon=1e-6) self.ln2 = LayerNormalization(epsilon=1e-6) self.mlp = mlpLayer(h_dim, d_model) self.att = multiHeadAttentionLayer(d_model, head_num) self.drop = Dropout(0.1) def call(self, x, training): y = self.ln1(x) # multi head attention q = self.q_d(y) # query k = self.k_d(y) # key v = self.v_d(y) # value y = self.att([q, k, v], training) # y = self.drop(y) # skip connection x = x + y # MLP layer y = self.ln2(x) y = self.mlp(y, training) # self.drop(y) # skip connection return x + y class PatchEmbedding(tf.keras.layers.Layer): def __init__(self, num_patch, embed_dim, **kwargs): super(PatchEmbedding, self).__init__(**kwargs) self.num_patch = num_patch self.proj = Dense(embed_dim) self.pos_embed = Embedding(input_dim=num_patch+1, output_dim=embed_dim) def call(self, patch): pos = tf.range(start=0, limit=self.num_patch+1, delta=1) return self.proj(patch) + self.pos_embed(pos) class visionTransformerLayer(tf.keras.layers.Layer): def __init__(self, image_size, patch_size, d_model=768, layer_num=12, head_num=12, h_dim=3072): super(visionTransformerLayer, self).__init__() self.num_patches = (image_size // patch_size) ** 2 self.d_model = d_model self.image_size = image_size self.patch_size = patch_size self.layer_num = layer_num # learnabel class embedding self.class_emb = Dense(1) self.pos_emb = Embedding(input_dim=self.num_patches + 1, output_dim=768) self.patch_emb = [PatchEmbedding(self.num_patches, d_model) for i in range(layer_num)] self.per = Permute((2, 1)) # self.class_emb = self.add_weight(shape=(1, 1, self.d_model), # initializer='random_normal', # trainable=True) # learnable position embedding # self.pos_emb = self.add_weight(shape=(1, 1, self.d_model), # initializer='random_normal', # trainable=True) self.dense = Dense(d_model, activation='linear') self.t_layer = [transformerBlock(d_model, head_num, h_dim) for i in range(layer_num)] def call(self, x, training): # feature extraction batch_size = tf.shape(x)[0] # resize image x = tf.image.resize(x, [self.image_size, self.image_size]) # extract patch patches = tf.image.extract_patches( images=x, sizes=[1, self.patch_size, self.patch_size, 1], strides=[1, self.patch_size, self.patch_size, 1], rates=[1, 1, 1, 1], padding='VALID', ) patches = Reshape((self.num_patches, -1))(patches) print('patches:', patches.shape, self.patch_size, self.num_patches) x = self.dense(patches) print(f'patches: {x.shape}') pos = tf.range(start=0, limit=self.num_patches + 1, delta=1) class_emb = self.per(self.class_emb(self.per(x))) pos_emb = self.pos_emb(pos)#self.per(self.pos_emb(self.per(x))) # class_emb = tf.broadcast_to(self.class_emb, [batch_size, 1, self.d_model]) print('class_emb:', pos_emb.shape) x = tf.concat([class_emb, x], axis=1) x = x + pos_emb # transformer block for i in range(self.layer_num): x = self.patch_emb[i](x) x = self.t_layer[i](x, training) return x def visionTransformer(input_dim, output_dim, image_size=32, patch_size=8, d_model=768, layer_num=12, head_num=12, h_dim=3072): inputs = tf.keras.Input(shape=input_dim) ViT_layer = visionTransformerLayer(image_size, patch_size, d_model, layer_num, head_num, h_dim) y = ViT_layer(inputs) print('y :', y.shape) # y = Dense(output_dim, activation=gelu)(y[:, 0]) y = GlobalAveragePooling1D()(y) outputs = Dense(output_dim, activation='softmax')(y) print(outputs.shape) return tf.keras.Model(inputs, outputs, name='vit'), ViT_layer
[ "tensorflow.shape", "numpy.sqrt", "tensorflow.keras.layers.Dense", "tensorflow.keras.backend.shape", "tensorflow.keras.layers.Reshape", "tensorflow.pow", "tensorflow.keras.layers.Permute", "tensorflow.image.extract_patches", "tensorflow.keras.activations.softmax", "tensorflow.concat", "tensorflo...
[((6093, 6124), 'tensorflow.keras.Input', 'tf.keras.Input', ([], {'shape': 'input_dim'}), '(shape=input_dim)\n', (6107, 6124), True, 'import tensorflow as tf\n'), ((810, 828), 'tensorflow.keras.layers.Permute', 'Permute', (['(2, 1, 3)'], {}), '((2, 1, 3))\n', (817, 828), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((848, 894), 'tensorflow.keras.layers.Reshape', 'Reshape', (['(-1, self.head, d_model // self.head)'], {}), '((-1, self.head, d_model // self.head))\n', (855, 894), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((912, 934), 'tensorflow.keras.layers.Reshape', 'Reshape', (['(-1, d_model)'], {}), '((-1, d_model))\n', (919, 934), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((957, 971), 'tensorflow.keras.layers.Dense', 'Dense', (['d_model'], {}), '(d_model)\n', (962, 971), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((1645, 1679), 'tensorflow.keras.layers.Dense', 'Dense', (['hidden_dim'], {'activation': 'gelu'}), '(hidden_dim, activation=gelu)\n', (1650, 1679), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((1750, 1767), 'tensorflow.keras.layers.Dense', 'Dense', (['output_dim'], {}), '(output_dim)\n', (1755, 1767), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((2076, 2090), 'tensorflow.keras.layers.Dense', 'Dense', (['d_model'], {}), '(d_model)\n', (2081, 2090), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((2110, 2124), 'tensorflow.keras.layers.Dense', 'Dense', (['d_model'], {}), '(d_model)\n', (2115, 2124), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((2144, 2158), 'tensorflow.keras.layers.Dense', 'Dense', (['d_model'], {}), '(d_model)\n', (2149, 2158), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((2178, 2211), 'tensorflow.keras.layers.LayerNormalization', 'LayerNormalization', ([], {'epsilon': '(1e-06)'}), '(epsilon=1e-06)\n', (2196, 2211), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((2230, 2263), 'tensorflow.keras.layers.LayerNormalization', 'LayerNormalization', ([], {'epsilon': '(1e-06)'}), '(epsilon=1e-06)\n', (2248, 2263), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((2398, 2410), 'tensorflow.keras.layers.Dropout', 'Dropout', (['(0.1)'], {}), '(0.1)\n', (2405, 2410), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((3083, 3099), 'tensorflow.keras.layers.Dense', 'Dense', (['embed_dim'], {}), '(embed_dim)\n', (3088, 3099), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((3125, 3181), 'tensorflow.keras.layers.Embedding', 'Embedding', ([], {'input_dim': '(num_patch + 1)', 'output_dim': 'embed_dim'}), '(input_dim=num_patch + 1, output_dim=embed_dim)\n', (3134, 3181), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((3222, 3274), 'tensorflow.range', 'tf.range', ([], {'start': '(0)', 'limit': '(self.num_patch + 1)', 'delta': '(1)'}), '(start=0, limit=self.num_patch + 1, delta=1)\n', (3230, 3274), True, 'import tensorflow as tf\n'), ((3809, 3817), 'tensorflow.keras.layers.Dense', 'Dense', (['(1)'], {}), '(1)\n', (3814, 3817), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((3841, 3898), 'tensorflow.keras.layers.Embedding', 'Embedding', ([], {'input_dim': '(self.num_patches + 1)', 'output_dim': '(768)'}), '(input_dim=self.num_patches + 1, output_dim=768)\n', (3850, 3898), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((4031, 4046), 'tensorflow.keras.layers.Permute', 'Permute', (['(2, 1)'], {}), '((2, 1))\n', (4038, 4046), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((4520, 4555), 'tensorflow.keras.layers.Dense', 'Dense', (['d_model'], {'activation': '"""linear"""'}), "(d_model, activation='linear')\n", (4525, 4555), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((4801, 4855), 'tensorflow.image.resize', 'tf.image.resize', (['x', '[self.image_size, self.image_size]'], {}), '(x, [self.image_size, self.image_size])\n', (4816, 4855), True, 'import tensorflow as tf\n'), ((4907, 5086), 'tensorflow.image.extract_patches', 'tf.image.extract_patches', ([], {'images': 'x', 'sizes': '[1, self.patch_size, self.patch_size, 1]', 'strides': '[1, self.patch_size, self.patch_size, 1]', 'rates': '[1, 1, 1, 1]', 'padding': '"""VALID"""'}), "(images=x, sizes=[1, self.patch_size, self.\n patch_size, 1], strides=[1, self.patch_size, self.patch_size, 1], rates\n =[1, 1, 1, 1], padding='VALID')\n", (4931, 5086), True, 'import tensorflow as tf\n'), ((5375, 5429), 'tensorflow.range', 'tf.range', ([], {'start': '(0)', 'limit': '(self.num_patches + 1)', 'delta': '(1)'}), '(start=0, limit=self.num_patches + 1, delta=1)\n', (5383, 5429), True, 'import tensorflow as tf\n'), ((5700, 5733), 'tensorflow.concat', 'tf.concat', (['[class_emb, x]'], {'axis': '(1)'}), '([class_emb, x], axis=1)\n', (5709, 5733), True, 'import tensorflow as tf\n'), ((6339, 6363), 'tensorflow.keras.layers.GlobalAveragePooling1D', 'GlobalAveragePooling1D', ([], {}), '()\n', (6361, 6363), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((6381, 6420), 'tensorflow.keras.layers.Dense', 'Dense', (['output_dim'], {'activation': '"""softmax"""'}), "(output_dim, activation='softmax')\n", (6386, 6420), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((6460, 6503), 'tensorflow.keras.Model', 'tf.keras.Model', (['inputs', 'outputs'], {'name': '"""vit"""'}), "(inputs, outputs, name='vit')\n", (6474, 6503), True, 'import tensorflow as tf\n'), ((476, 509), 'tensorflow.matmul', 'tf.matmul', (['q', 'k'], {'transpose_b': '(True)'}), '(q, k, transpose_b=True)\n', (485, 509), True, 'import tensorflow as tf\n'), ((579, 599), 'tensorflow.keras.activations.softmax', 'softmax', (['qk'], {'axis': '(-1)'}), '(qk, axis=-1)\n', (586, 599), False, 'from tensorflow.keras.activations import softmax, linear\n'), ((4742, 4753), 'tensorflow.shape', 'tf.shape', (['x'], {}), '(x)\n', (4750, 4753), True, 'import tensorflow as tf\n'), ((5166, 5197), 'tensorflow.keras.layers.Reshape', 'Reshape', (['(self.num_patches, -1)'], {}), '((self.num_patches, -1))\n', (5173, 5197), False, 'from tensorflow.keras.layers import Dense, LayerNormalization, Reshape, Permute, Dropout, GlobalAveragePooling1D, Embedding\n'), ((303, 321), 'numpy.sqrt', 'np.sqrt', (['(2 / np.pi)'], {}), '(2 / np.pi)\n', (310, 321), True, 'import numpy as np\n'), ((525, 535), 'tensorflow.keras.backend.shape', 'K.shape', (['k'], {}), '(k)\n', (532, 535), True, 'import tensorflow.keras.backend as K\n'), ((332, 344), 'tensorflow.pow', 'tf.pow', (['x', '(3)'], {}), '(x, 3)\n', (338, 344), True, 'import tensorflow as tf\n')]
from time import sleep from threading import Thread import socket import datetime as datetime from tkinter import * #global varaibles global run global message global gui run=True class client(): def __init__(self): self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.count = 0 self.log = open("Chat_log","a") def connect(self): self.s.connect(('localhost',8019)) self.chatting=True # Now Chatting print("Connected to server") self.log.writelines("\n *****"+repr(datetime.datetime.now())+"***** \n") #Write current date and time to file def disconnect(self): global chatting global run self.s.send( "%disconnect%".encode('utf-8') ) # send disconnect message to client self.s.close() # close socket self.chatting=False # no longer chatting print("Disconnect from server \nPress anykey to exit") # Tell user about discconnect self.log.close() run=False def send(self): global message #print("running") if self.count ==0: self.count+=1 msg = message.get() msg = str(msg) self.log.writelines("\n"+repr(datetime.time())+" : sent: "+msg) if msg =="Q": self.disconnect() #disconnect else: self.s.send( msg.encode('utf-8') ) # send message encode with utf-8 def receive(self): while self.chatting==True: #print("Test") reply = self.s.recv( 4096 ).decode( 'utf-8' ) # Receive message decode with utf-8 self.log.writelines("\n"+repr(datetime.time())+" : received: "+reply) reply = str(reply) if reply =="%disconnect%": # If client disconnects self.disconnect() # Disconnect else: global gui print("\nRecieved ", reply) # print recieved message lstbox=gui.listbox lstbox.insert(END, reply) class gui(): def __init__(self): pass def login(self): pass def messaging(self): global message self.window = Tk() #Window settings self.window.title("Python Messenger") self.window.geometry('500x500') #End windows settings #Text lbl = Label(self.window, text="Enter message to send:") lbl.grid(column=0, row=0) #End Text #Text entry message = Entry(self.window,width=10) message.grid(column=0,row=1) #End text entry #Button btn = Button(self.window, text="Send", command=client.send) btn.grid(column=0, row=2) #End Button #Msg list self.listbox = Listbox(self.window, height=15, width=50) self.listbox.grid(column=1,row=0) #End msg list self.window.mainloop() client = client() gui = gui() client.connect() Thread(name='client-receive', target=client.receive, daemon=True).start() gui.messaging() while run== True: pass
[ "threading.Thread", "datetime.time", "datetime.datetime.now", "socket.socket" ]
[((240, 289), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (253, 289), False, 'import socket\n'), ((2935, 3000), 'threading.Thread', 'Thread', ([], {'name': '"""client-receive"""', 'target': 'client.receive', 'daemon': '(True)'}), "(name='client-receive', target=client.receive, daemon=True)\n", (2941, 3000), False, 'from threading import Thread\n'), ((549, 572), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (570, 572), True, 'import datetime as datetime\n'), ((1225, 1240), 'datetime.time', 'datetime.time', ([], {}), '()\n', (1238, 1240), True, 'import datetime as datetime\n'), ((1639, 1654), 'datetime.time', 'datetime.time', ([], {}), '()\n', (1652, 1654), True, 'import datetime as datetime\n')]
import dash from dash.dependencies import Input, Output import dash_core_components as dcc import dash_html_components as html import logging import datetime import time class Semaphore: def __init__(self, filename='semaphore.txt'): self.filename = filename with open(self.filename, 'w') as f: f.write('done') def lock(self): with open(self.filename, 'w') as f: f.write('working') def unlock(self): with open(self.filename, 'w') as f: f.write('done') def is_locked(self): return open(self.filename, 'r').read() == 'working' semaphore = Semaphore() def long_process(): if semaphore.is_locked(): raise Exception('Resource is locked') semaphore.lock() time.sleep(7) semaphore.unlock() return datetime.datetime.now() app = dash.Dash() app.logger.setLevel(logging.DEBUG) def layout(): return html.Div([ html.Button('Run Process', id='button'), dcc.Interval(id='interval', interval=500), dcc.RadioItems( id='lock', options=[{'label': i, 'value': i} for i in ['Running...', 'Free']]), html.Div(id='output') ]) app.layout = layout @app.callback( Output('lock', 'value'), [Input('interval', 'n_intervals')]) def display_status(interval): app.logger.debug("display_status") return 'Running...' if semaphore.is_locked() else 'Free' @app.callback( Output('output', 'children'), [Input('button', 'n_clicks')]) def run_process(button_input): app.logger.debug("run_process") return 'Finished at {}'.format(long_process()) app.scripts.config.serve_locally = True if __name__ == '__main__': app.run_server(debug=True)
[ "dash_core_components.Interval", "dash_core_components.RadioItems", "dash_html_components.Button", "dash.dependencies.Output", "time.sleep", "dash.dependencies.Input", "datetime.datetime.now", "dash_html_components.Div", "dash.Dash" ]
[((847, 858), 'dash.Dash', 'dash.Dash', ([], {}), '()\n', (856, 858), False, 'import dash\n'), ((768, 781), 'time.sleep', 'time.sleep', (['(7)'], {}), '(7)\n', (778, 781), False, 'import time\n'), ((816, 839), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (837, 839), False, 'import datetime\n'), ((1237, 1260), 'dash.dependencies.Output', 'Output', (['"""lock"""', '"""value"""'], {}), "('lock', 'value')\n", (1243, 1260), False, 'from dash.dependencies import Input, Output\n'), ((1452, 1480), 'dash.dependencies.Output', 'Output', (['"""output"""', '"""children"""'], {}), "('output', 'children')\n", (1458, 1480), False, 'from dash.dependencies import Input, Output\n'), ((1267, 1299), 'dash.dependencies.Input', 'Input', (['"""interval"""', '"""n_intervals"""'], {}), "('interval', 'n_intervals')\n", (1272, 1299), False, 'from dash.dependencies import Input, Output\n'), ((1487, 1514), 'dash.dependencies.Input', 'Input', (['"""button"""', '"""n_clicks"""'], {}), "('button', 'n_clicks')\n", (1492, 1514), False, 'from dash.dependencies import Input, Output\n'), ((939, 978), 'dash_html_components.Button', 'html.Button', (['"""Run Process"""'], {'id': '"""button"""'}), "('Run Process', id='button')\n", (950, 978), True, 'import dash_html_components as html\n'), ((988, 1029), 'dash_core_components.Interval', 'dcc.Interval', ([], {'id': '"""interval"""', 'interval': '(500)'}), "(id='interval', interval=500)\n", (1000, 1029), True, 'import dash_core_components as dcc\n'), ((1039, 1137), 'dash_core_components.RadioItems', 'dcc.RadioItems', ([], {'id': '"""lock"""', 'options': "[{'label': i, 'value': i} for i in ['Running...', 'Free']]"}), "(id='lock', options=[{'label': i, 'value': i} for i in [\n 'Running...', 'Free']])\n", (1053, 1137), True, 'import dash_core_components as dcc\n'), ((1167, 1188), 'dash_html_components.Div', 'html.Div', ([], {'id': '"""output"""'}), "(id='output')\n", (1175, 1188), True, 'import dash_html_components as html\n')]
import pycountry from irco import logging _cache = {} log = logging.get_logger() NAMES = {c.name.lower(): c for c in pycountry.countries.objects} SUBDIVISIONS = {s.name.lower(): s for s in pycountry.subdivisions.objects} PREFIXES = set([ 'Republic of', ]) REPLACEMENTS = { 'South Korea': 'Korea, Republic of', 'U Arab Emirates': 'United Arab Emirates', 'Vietnam': 'Viet Nam', 'Bosnia & Herceg': 'Bosnia and Herzegovina', 'Byelarus': 'Belarus', 'Neth Antilles': 'Netherlands Antilles', 'USA': 'United States', } class CountryNotFound(Exception): def __init__(self, token, text): self.token = token self.text = text def __unicode__(self): return (u'Fuzzy search for "{}" returned no results (complete record: ' '"{}")'.format(self.token, self.text)) def get_institution_country(institution_name): tokens = institution_name.strip('., ').split(', ') country_token = tokens[-1] if country_token in REPLACEMENTS: country_token = REPLACEMENTS[country_token] if country_token in PREFIXES: country_token = tokens[-2] + ', ' + tokens[-1] if country_token not in _cache: country = None cl = country_token.lower() try: country = pycountry.countries.get(name=country_token) except KeyError: country = None if country is None: for k, country in NAMES.iteritems(): if ( cl in k or k in cl or country.alpha3 in country_token.split(' ') or country.alpha2 in country_token.split(' ') ): log.warning(u'Fuzzy search for "{}" matched "{}"'.format( country_token, country.name)) break else: country = None if country is None: for k, sub in SUBDIVISIONS.iteritems(): if cl in k or k in cl: country = sub.country log.warning('Fuzzy search for "{}" matched subdivision ' '"{}" of country "{}"'.format( country_token, sub.name, country.name)) break if country is None: raise CountryNotFound(country_token, institution_name) _cache[country_token] = country.name return _cache[country_token]
[ "pycountry.countries.get", "irco.logging.get_logger" ]
[((62, 82), 'irco.logging.get_logger', 'logging.get_logger', ([], {}), '()\n', (80, 82), False, 'from irco import logging\n'), ((1283, 1326), 'pycountry.countries.get', 'pycountry.countries.get', ([], {'name': 'country_token'}), '(name=country_token)\n', (1306, 1326), False, 'import pycountry\n')]
from django.urls import include, path from rest_framework.routers import DefaultRouter from rooms import views # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r"room", views.RoomViewSet, basename="room") # The API URLs are now determined automatically by the router. urlpatterns = [ path("", include(router.urls)), ]
[ "rest_framework.routers.DefaultRouter", "django.urls.include" ]
[((175, 190), 'rest_framework.routers.DefaultRouter', 'DefaultRouter', ([], {}), '()\n', (188, 190), False, 'from rest_framework.routers import DefaultRouter\n'), ((345, 365), 'django.urls.include', 'include', (['router.urls'], {}), '(router.urls)\n', (352, 365), False, 'from django.urls import include, path\n')]
#!/usr/bin/env python """ Copyright 2018 Johns Hopkins University (Author: <NAME>) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ """ Evals PDDA LLR """ from __future__ import absolute_import from __future__ import print_function from __future__ import division from six.moves import xrange import sys import os import argparse import time import logging import numpy as np from hyperion.hyp_defs import set_float_cpu, float_cpu, config_logger from hyperion.transforms import TransformList from hyperion.utils.trial_ndx import TrialNdx from hyperion.utils.trial_scores import TrialScores from hyperion.utils.tensors import to3D_by_class from hyperion.helpers import TrialDataReader as TDR from hyperion.keras.keras_utils import * from hyperion.keras.vae import TiedVAE_qYqZgY as TVAEYZ from hyperion.keras.vae import TiedVAE_qY as TVAEY def eval_pdda(iv_file, ndx_file, enroll_file, test_file, preproc_file, model_file, score_file, eval_method, num_samples_y, num_samples_z, num_samples_elbo, qy_only, **kwargs): set_float_cpu('float32') if preproc_file is not None: preproc = TransformList.load(preproc_file) else: preproc = None tdr_args = TDR.filter_args(**kwargs) tdr = TDR(iv_file, ndx_file, enroll_file, test_file, preproc, **tdr_args) x_e, x_t, enroll, ndx = tdr.read() if qy_only: model = TVAEY.load(model_file) model.build(max_seq_length=2, num_samples=num_samples_y) else: model = TVAEYZ.load(model_file) model.build(max_seq_length=2, num_samples_y=num_samples_y, num_samples_z=num_samples_z) t1 = time.time() scores = model.eval_llr_1vs1(x_e, x_t, method=eval_method, num_samples=num_samples_elbo) dt = time.time() - t1 num_trials = x_e.shape[0] * x_t.shape[0] logging.info('Elapsed time: %.2f s. Elapsed time per trial: %.2f ms.' % (dt, dt/num_trials*1000)) s = TrialScores(enroll, ndx.seg_set, scores) s.save(score_file) if __name__ == "__main__": parser=argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, fromfile_prefix_chars='@', description='Eval PDDA') parser.add_argument('--iv-file', dest='iv_file', required=True) parser.add_argument('--ndx-file', dest='ndx_file', default=None) parser.add_argument('--enroll-file', dest='enroll_file', required=True) parser.add_argument('--test-file', dest='test_file', default=None) parser.add_argument('--preproc-file', dest='preproc_file', default=None) TDR.add_argparse_args(parser) parser.add_argument('--model-file', dest='model_file', required=True) parser.add_argument('--score-file', dest='score_file', required=True) parser.add_argument('--qy-only', dest='qy_only', default=False, action='store_true') parser.add_argument('--eval-method', dest='eval_method', type=str.lower, default='elbo', choices=['elbo','cand','qscr'], help=('(default: %(default)s)')) parser.add_argument('--nb-samples-elbo', dest='num_samples_elbo', default=1, type=int) parser.add_argument('--nb-samples-y', dest='num_samples_y', default=1, type=int) parser.add_argument('--nb-samples-z', dest='num_samples_z', default=1, type=int) parser.add_argument('-v', '--verbose', dest='verbose', default=1, choices=[0, 1, 2, 3], type=int) args=parser.parse_args() config_logger(args.verbose) del args.verbose logging.debug(args) assert args.test_file is not None or args.ndx_file is not None eval_pdda(**vars(args))
[ "hyperion.hyp_defs.config_logger", "logging.debug", "argparse.ArgumentParser", "hyperion.helpers.TrialDataReader.filter_args", "hyperion.helpers.TrialDataReader", "logging.info", "hyperion.hyp_defs.set_float_cpu", "hyperion.transforms.TransformList.load", "hyperion.keras.vae.TiedVAE_qY.load", "hyp...
[((1083, 1107), 'hyperion.hyp_defs.set_float_cpu', 'set_float_cpu', (['"""float32"""'], {}), "('float32')\n", (1096, 1107), False, 'from hyperion.hyp_defs import set_float_cpu, float_cpu, config_logger\n'), ((1246, 1271), 'hyperion.helpers.TrialDataReader.filter_args', 'TDR.filter_args', ([], {}), '(**kwargs)\n', (1261, 1271), True, 'from hyperion.helpers import TrialDataReader as TDR\n'), ((1282, 1349), 'hyperion.helpers.TrialDataReader', 'TDR', (['iv_file', 'ndx_file', 'enroll_file', 'test_file', 'preproc'], {}), '(iv_file, ndx_file, enroll_file, test_file, preproc, **tdr_args)\n', (1285, 1349), True, 'from hyperion.helpers import TrialDataReader as TDR\n'), ((1686, 1697), 'time.time', 'time.time', ([], {}), '()\n', (1695, 1697), False, 'import time\n'), ((1899, 2004), 'logging.info', 'logging.info', (["('Elapsed time: %.2f s. Elapsed time per trial: %.2f ms.' % (dt, dt /\n num_trials * 1000))"], {}), "('Elapsed time: %.2f s. Elapsed time per trial: %.2f ms.' % (dt,\n dt / num_trials * 1000))\n", (1911, 2004), False, 'import logging\n'), ((2023, 2063), 'hyperion.utils.trial_scores.TrialScores', 'TrialScores', (['enroll', 'ndx.seg_set', 'scores'], {}), '(enroll, ndx.seg_set, scores)\n', (2034, 2063), False, 'from hyperion.utils.trial_scores import TrialScores\n'), ((2133, 2274), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter', 'fromfile_prefix_chars': '"""@"""', 'description': '"""Eval PDDA"""'}), "(formatter_class=argparse.\n ArgumentDefaultsHelpFormatter, fromfile_prefix_chars='@', description=\n 'Eval PDDA')\n", (2156, 2274), False, 'import argparse\n'), ((2657, 2686), 'hyperion.helpers.TrialDataReader.add_argparse_args', 'TDR.add_argparse_args', (['parser'], {}), '(parser)\n', (2678, 2686), True, 'from hyperion.helpers import TrialDataReader as TDR\n'), ((3586, 3613), 'hyperion.hyp_defs.config_logger', 'config_logger', (['args.verbose'], {}), '(args.verbose)\n', (3599, 3613), False, 'from hyperion.hyp_defs import set_float_cpu, float_cpu, config_logger\n'), ((3639, 3658), 'logging.debug', 'logging.debug', (['args'], {}), '(args)\n', (3652, 3658), False, 'import logging\n'), ((1164, 1196), 'hyperion.transforms.TransformList.load', 'TransformList.load', (['preproc_file'], {}), '(preproc_file)\n', (1182, 1196), False, 'from hyperion.transforms import TransformList\n'), ((1422, 1444), 'hyperion.keras.vae.TiedVAE_qY.load', 'TVAEY.load', (['model_file'], {}), '(model_file)\n', (1432, 1444), True, 'from hyperion.keras.vae import TiedVAE_qY as TVAEY\n'), ((1536, 1559), 'hyperion.keras.vae.TiedVAE_qYqZgY.load', 'TVAEYZ.load', (['model_file'], {}), '(model_file)\n', (1547, 1559), True, 'from hyperion.keras.vae import TiedVAE_qYqZgY as TVAEYZ\n'), ((1833, 1844), 'time.time', 'time.time', ([], {}), '()\n', (1842, 1844), False, 'import time\n')]
import re import typing import logging import argparse from opensearchpy import OpenSearch from datetime import datetime _version = "0.0.1" _project_name = "opensearch-index-rotate" logging.basicConfig(level=logging.INFO) logger = logging.getLogger(f"{_project_name}-{_version}") def build_filter_function( unit_count: int, timestring_regex: str = r"\d{4}-\d{2}-\d{2}", today_timeobj: typing.Any = datetime.now(), ) -> typing.Callable: def fn( timestring: str, unit_count: int = unit_count, today_timeobj: typing.Any = today_timeobj, timestring_regex: str = timestring_regex, ) -> bool: pattern = re.compile(timestring_regex) match = re.search(pattern, timestring) if match is None: return False date = datetime.strptime(str(match.group()), "%Y-%m-%d") return (today_timeobj - date).days > unit_count return fn def filter_by_age(filter_function: typing.Callable, indices: list) -> list: return list(filter(filter_function, indices)) def main(host: str, unit_count: int, index: str, port: int = 443): client = OpenSearch( hosts=[{"host": host, "port": port}], http_compress=True, use_ssl=True, verify_certs=True, ssl_assert_hostname=False, ssl_show_warn=True, ) response = client.indices.get(index) filter_fn = build_filter_function(unit_count=unit_count) indices = filter_by_age(filter_fn, response.keys()) if not indices: logger.info(f"can't find indices from {unit_count} days ago, skip...") exit(0) response = client.indices.delete(",".join(indices)) logger.info(f"delete response --> {response}") logger.info(f"delete indices {indices} success") if __name__ == "__main__": parser = argparse.ArgumentParser(description="opensearch index rotate tool") parser.add_argument("--host", type=str, required=True, help="opensearch host") parser.add_argument( "--days-ago", type=int, required=True, help="delete indices from DAYS_AGO" ) parser.add_argument("--index", type=str, required=True, help="index name") args = parser.parse_args() main(args.host, args.days_ago, args.index)
[ "logging.basicConfig", "logging.getLogger", "argparse.ArgumentParser", "re.compile", "opensearchpy.OpenSearch", "datetime.datetime.now", "re.search" ]
[((185, 224), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (204, 224), False, 'import logging\n'), ((234, 282), 'logging.getLogger', 'logging.getLogger', (['f"""{_project_name}-{_version}"""'], {}), "(f'{_project_name}-{_version}')\n", (251, 282), False, 'import logging\n'), ((415, 429), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (427, 429), False, 'from datetime import datetime\n'), ((1135, 1291), 'opensearchpy.OpenSearch', 'OpenSearch', ([], {'hosts': "[{'host': host, 'port': port}]", 'http_compress': '(True)', 'use_ssl': '(True)', 'verify_certs': '(True)', 'ssl_assert_hostname': '(False)', 'ssl_show_warn': '(True)'}), "(hosts=[{'host': host, 'port': port}], http_compress=True,\n use_ssl=True, verify_certs=True, ssl_assert_hostname=False,\n ssl_show_warn=True)\n", (1145, 1291), False, 'from opensearchpy import OpenSearch\n'), ((1816, 1883), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""opensearch index rotate tool"""'}), "(description='opensearch index rotate tool')\n", (1839, 1883), False, 'import argparse\n'), ((662, 690), 're.compile', 're.compile', (['timestring_regex'], {}), '(timestring_regex)\n', (672, 690), False, 'import re\n'), ((707, 737), 're.search', 're.search', (['pattern', 'timestring'], {}), '(pattern, timestring)\n', (716, 737), False, 'import re\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ RealSense PCD Viewer with Open3D. Copyright (c) 2021 <NAME> This software is released under the MIT License. See the LICENSE file in the project root for more information. """ import argparse import json import os import numpy as np import open3d as o3d class ViewerWithCallback: def __init__(self, config, device): self.flag_exit = False if config is not None and os.path.isfile(config): print("Load json: ", config) with open(config) as f: rs_config = o3d.t.io.RealSenseSensorConfig(json.load(f)) else: print("Use default config") rs_config = o3d.t.io.RealSenseSensorConfig() # Initialize RealSense. self.sensor = o3d.t.io.RealSenseSensor() self.sensor.init_sensor(sensor_config=rs_config, sensor_index=device) # Get camera intrinsic self.metadata = self.sensor.get_metadata() self.intrinsics = self.metadata.intrinsics # We will not display the background of objects more than # clipping_distance_in_meters meters away self.clipping_distance_in_meters = 3 # 3 meter depth_scale = 1.0 / self.metadata.depth_scale self.clipping_distance = self.clipping_distance_in_meters / depth_scale def escape_callback(self, vis): print("Escape callback") self.flag_exit = True return False def run(self): glfw_key_escape = 256 pcd = o3d.geometry.PointCloud() flip_transform = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]] vis = o3d.visualization.VisualizerWithKeyCallback() vis.register_key_callback(glfw_key_escape, self.escape_callback) vis.create_window("Open3d Realsense pointcloud viewer") print("Sensor initialized. Press [ESC] to exit.") self.sensor.start_capture() vis_geometry_added = False while not self.flag_exit: # Note: In the case of PointCloud, it is necessary to align with the depth. rgbd = self.sensor.capture_frame(True, True) if rgbd is None: continue temp_rgbd = rgbd.to_legacy_rgbd_image() rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth( temp_rgbd.color, temp_rgbd.depth, depth_scale=self.metadata.depth_scale, depth_trunc=self.clipping_distance_in_meters, convert_rgb_to_intensity=False, ) temp_pcd = o3d.geometry.PointCloud.create_from_rgbd_image( rgbd_image, self.intrinsics ) temp_pcd.transform(flip_transform) pcd.points = temp_pcd.points pcd.colors = temp_pcd.colors if not vis_geometry_added: vis.add_geometry(pcd) vis_geometry_added = True vis.update_geometry(pcd) vis.poll_events() vis.update_renderer() self.sensor.stop_capture() vis.destroy_window() if __name__ == "__main__": parser = argparse.ArgumentParser(description="RealSene PointCloud Viewer.") parser.add_argument( "--config", type=str, required=True, help="Input json for realsense config" ) parser.add_argument( "--device", type=int, default=0, help="input realsense device id" ) args = parser.parse_args() # Display device list o3d.t.io.RealSenseSensor.list_devices() # Set device id device = args.device if device < 0 or device > 255: print("Unsupported device id, fall back to 0") device = 0 # Run v = ViewerWithCallback(args.config, device) v.run()
[ "argparse.ArgumentParser", "open3d.visualization.VisualizerWithKeyCallback", "open3d.t.io.RealSenseSensor", "os.path.isfile", "open3d.t.io.RealSenseSensor.list_devices", "open3d.t.io.RealSenseSensorConfig", "open3d.geometry.RGBDImage.create_from_color_and_depth", "open3d.geometry.PointCloud", "open3...
[((3164, 3230), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""RealSene PointCloud Viewer."""'}), "(description='RealSene PointCloud Viewer.')\n", (3187, 3230), False, 'import argparse\n'), ((3513, 3552), 'open3d.t.io.RealSenseSensor.list_devices', 'o3d.t.io.RealSenseSensor.list_devices', ([], {}), '()\n', (3550, 3552), True, 'import open3d as o3d\n'), ((799, 825), 'open3d.t.io.RealSenseSensor', 'o3d.t.io.RealSenseSensor', ([], {}), '()\n', (823, 825), True, 'import open3d as o3d\n'), ((1531, 1556), 'open3d.geometry.PointCloud', 'o3d.geometry.PointCloud', ([], {}), '()\n', (1554, 1556), True, 'import open3d as o3d\n'), ((1656, 1701), 'open3d.visualization.VisualizerWithKeyCallback', 'o3d.visualization.VisualizerWithKeyCallback', ([], {}), '()\n', (1699, 1701), True, 'import open3d as o3d\n'), ((459, 481), 'os.path.isfile', 'os.path.isfile', (['config'], {}), '(config)\n', (473, 481), False, 'import os\n'), ((711, 743), 'open3d.t.io.RealSenseSensorConfig', 'o3d.t.io.RealSenseSensorConfig', ([], {}), '()\n', (741, 743), True, 'import open3d as o3d\n'), ((2280, 2490), 'open3d.geometry.RGBDImage.create_from_color_and_depth', 'o3d.geometry.RGBDImage.create_from_color_and_depth', (['temp_rgbd.color', 'temp_rgbd.depth'], {'depth_scale': 'self.metadata.depth_scale', 'depth_trunc': 'self.clipping_distance_in_meters', 'convert_rgb_to_intensity': '(False)'}), '(temp_rgbd.color,\n temp_rgbd.depth, depth_scale=self.metadata.depth_scale, depth_trunc=\n self.clipping_distance_in_meters, convert_rgb_to_intensity=False)\n', (2330, 2490), True, 'import open3d as o3d\n'), ((2600, 2675), 'open3d.geometry.PointCloud.create_from_rgbd_image', 'o3d.geometry.PointCloud.create_from_rgbd_image', (['rgbd_image', 'self.intrinsics'], {}), '(rgbd_image, self.intrinsics)\n', (2646, 2675), True, 'import open3d as o3d\n'), ((619, 631), 'json.load', 'json.load', (['f'], {}), '(f)\n', (628, 631), False, 'import json\n')]
# <NAME> # /Module for Binary Classification from classification import ClassificationModel import pandas as pd import logging import sklearn # import fire eval_df = pd.read_csv('/Volumes/Loopdisk/Bi_Transformer/data/dev.csv', sep='\t') eval_df = eval_df[['0', '1']] eval_df['0'] = eval_df['0'].astype(str) model = ClassificationModel("bert", "outputs", use_cuda=False) result, model_outputs, wrong_predictions = model.eval_model(eval_df, acc=sklearn.metrics.accuracy_score) def classify(inport): predictions, raw_outputs = model.predict([inport]) print("For {} accuracy, classification belongs to".format(result['acc']*10)) if predictions == 1: outport = "\nClass: Eligibility Criteria" else: outport = "\nClass: Others" return outport if __name__ == "__main__": inport = input('') outport = classify(inport) print(outport)
[ "pandas.read_csv", "classification.ClassificationModel" ]
[((170, 240), 'pandas.read_csv', 'pd.read_csv', (['"""/Volumes/Loopdisk/Bi_Transformer/data/dev.csv"""'], {'sep': '"""\t"""'}), "('/Volumes/Loopdisk/Bi_Transformer/data/dev.csv', sep='\\t')\n", (181, 240), True, 'import pandas as pd\n'), ((321, 375), 'classification.ClassificationModel', 'ClassificationModel', (['"""bert"""', '"""outputs"""'], {'use_cuda': '(False)'}), "('bert', 'outputs', use_cuda=False)\n", (340, 375), False, 'from classification import ClassificationModel\n')]
""" sphinx_c_autodoc is a package which provide c source file parsing for sphinx. It is composed of multiple directives and settings: .. rst:directive:: .. c:module:: filename A directive to document a c file. This is similar to :rst:dir:`py:module` except it's for the C domain. This can be used for both c source files as well as c header files. """ import json import os import re from dataclasses import dataclass, field from itertools import groupby from typing import Any, List, Optional, Tuple, Dict from docutils.statemachine import ViewList, StringList from docutils import nodes from sphinx.domains.c import CObject from sphinx.application import Sphinx from sphinx.util import logging from sphinx.util.docstrings import prepare_docstring from sphinx.ext.autodoc import ( Documenter, members_option, bool_option, member_order_option, ) from sphinx.ext.autodoc.directive import DocumenterBridge from sphinx_c_autodoc import loader from sphinx_c_autodoc.domains.c import patch_c_domain # TODO not real fond of this being here in the main c autodoc file, need to # find a way to make it easier to cache the documented files. @dataclass class ViewCodeListing: """ A data structure used for constructing a viewcode source listing. Attributes: raw_listing: The plain text representation of the code. This should be basically the output of file.read(). ast (Dict): A dictionary like representation of the code constructs. See :ref:`developer_notes:Common Terms`. doc_links (Dict): To be used by the consumers, i.e. viewcode. """ raw_listing: str ast: Dict doc_links: Dict = field(default_factory=dict) logger = logging.getLogger(__name__) class CObjectDocumenter(Documenter): # pylint: disable=line-too-long """ A C object autodocument class to work with `autodoc <https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#module-sphinx.ext.autodoc>`_ extension for sphinx. """ # pylint: enable=line-too-long domain = "c" # Filler type, this base class isn't used directly directivetype = "object" # must be higher than the AttributeDocumenter, else it will steal the c # objects priority = 11 option_spec = { "members": members_option, "noindex": bool_option, "private-members": bool_option, "member-order": member_order_option, "undoc-members": bool_option, } @classmethod def can_document_member( cls, member: Any, membername: str, isattr: bool, parent: Any ) -> bool: """ Parameters: member (object): The member item to document. This type is specific to the item being processed by autodoc. These classes will only attempt to process :class:`sphinx_c_autodoc.loader.CObjectDocumenter` members. membername (str): The name of the item to document. For example if this is a function then this will be the name of the function, no return types, no arguments. isattr (bool): Is the member an attribute. This is unused for c documenation. parent (object): The parent item of this `member`. Returns: bool: True if this class can document the `member`. """ return ( isinstance(parent, CObjectDocumenter) and member.type == cls.directivetype ) def parse_name(self) -> bool: """Determine what module to import and what attribute to document. .. note:: Sphinx autodoc supports args and return anotation, since this is targeting C and it isn't currently needed, these won't be supported by this implementation. Returns: bool: True if successfully parsed and sets :attr:`modname`, :attr:`objpath`, :attr:`fullname`. False if the signature couldn't be parsed. """ c_autodoc_re = re.compile(r"^([\w\/\\.]+)(::([\w.]+\.)?(\w+))?\s*$") try: match = c_autodoc_re.match(self.name) fullname, _, path, base = match.groups() # type: ignore except AttributeError: logger.warning( "invalid signature for auto%s (%r)" % (self.objtype, self.name), type="c_autodoc", ) return False parents: List[str] if path is None: parents = [] else: parents = path.rstrip(".").split(".") self.modname, self.objpath = self.resolve_name(fullname, parents, path, base) self.fullname = self.modname return True def resolve_name( self, modname: str, parents: List[str], path: Optional[str], base: str ) -> Tuple[str, List[str]]: """ Resolve the module and object name of the object to document. This can be derived in two ways: - Naked: Where the argument is only the file/module name `my_file.c` - Double colons: Where the argument to the directive is of the form `my_file.c::some_func`. Args: modname (str): The filename of the c file (module) parents (list): The list split('.') version of path. - The filename without the extension when naked argument is used. - Any parents when double colon argument is used. For example structs or unions of `my_struct.field_name` would have a parents entry of ['my_struct'] path (str): Two possible states: - None if `parents` is the empty list. - The ``'.'.join()`` version of `parents`, with a trailing ``.``. base (str): The name of the object to document. This will be None when the object to document is the c module Returns: tuple: (str, [str]) The module name, and the object names (if any). """ if base: return modname, parents + [base] return modname, [] def import_object(self, raiseerror: bool = False) -> bool: """Load the C file and build up the document structure. This will load the C file's documented structure into :attr:`object` Args: raiseerror (bool): Raise error, this is ignored for the c implementation as import errors don't happen. Returns: bool: True if the file was imported, false otherwise. """ for source_dir in self.env.config.c_autodoc_roots: filename = os.path.join(source_dir, self.get_real_modname()) # Prefixing with "/" will force "absolute" path which is relative # to the source directory. rel_filename, filename = self.env.relfn2path(f"/{filename}") if os.path.isfile(filename): break else: logger.warning( "Unable to find file, %s, in any of the directories %s " "all directories are relative to the top documentation source directory" % (self.get_real_modname(), self.env.config.c_autodoc_roots), location=(self.env.docname, self.directive.lineno), ) return False self.env.note_dependency(rel_filename) source_dict = getattr(self.env, "_viewcode_c_modules", {}) self.env._viewcode_c_modules = source_dict # type: ignore # TODO The :attr:`temp_data` is reset for each document ideally want to # use or make an attribute on `self.env` that is reset per run or just # not pickled. modules_dict = self.env.temp_data.setdefault("c:loaded_modules", {}) if filename not in modules_dict: with open(filename) as f: contents = [f.read()] # let extensions preprocess files self.env.app.emit("c-autodoc-pre-process", filename, contents) compilation_db = self.get_compilation_database() compilation_args = self.env.config.c_autodoc_compilation_args modules_dict[filename] = loader.load( filename, contents[0], compilation_db, compilation_args ) ast = json.loads(str(modules_dict[filename])) source_dict.setdefault( self.get_real_modname(), ViewCodeListing(contents[0], ast) ) self.module = modules_dict[filename] self.object = self.module self.object_name = self.name # objpath is set when double colons are used in :meth:`resolve_name`. # i.e. this is a node or sub-node in a module. if self.objpath: for obj in self.objpath: self.object_name = obj self.object = self.object.children[self.object_name] # type: ignore return True def get_compilation_database(self) -> Optional[str]: """ Get's the compilation database from the environment `c_autodoc_compilation_database` Returns: str: The full path to the compilation database to use. None if there is no compilation database. """ database = self.env.config.c_autodoc_compilation_database if not database: return None # Prefixing with "/" will force "absolute" path which is relative # to the source directory. _, filename = self.env.relfn2path(f"/{database}") if os.path.isfile(filename): return filename logger.warning( 'Compilation database "%s" not found.' % (filename,), location=(self.env.docname, self.directive.lineno), ) return None def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]: """Decode and return lines of the docstring(s) for the object.""" docstring = self.object.get_doc() tab_width = self.directive.state.document.settings.tab_width return [prepare_docstring(docstring, ignore, tab_width)] def get_object_members(self, want_all: bool) -> Tuple[bool, List[Tuple[str, Any]]]: """Return `(members_check_module, members)` where `members` is a list of `(membername, member)` pairs of the members of *self.object*. If *want_all* is True, return all members. Else, only return those members given by *self.options.members* (which may also be none). """ if want_all: return False, list(self.object.children.items()) # The caller sets `want_all` if :attr:`options.members` is ALL, so it # should be safe to assume this is a list or None at this point. desired_members = self.options.members or [] object_members: List[Tuple[str, Any]] = [] for member in desired_members: if member in self.object.children: object_members.append((member, self.object.children[member])) else: logger.warning( 'Missing member "%s" in object "%s"' % (member, self.fullname), type="c_autodoc", ) return False, object_members def filter_members( # type: ignore[override] self, members: List[Tuple[str, Any]], want_all: bool ) -> List[Tuple[str, Any, bool]]: """Filter the given member list. :meth:`filter_members` is called *after* :meth:`get_object_members`, this means if `want_all` is False then only private members which were explicitly requested will be in this list. Only when `want_all` is True do we need to actually condition on private member. Members are skipped if - they are private (except if given explicitly or the private-members option is set) - they are undocumented (except if the undoc-members option is set) TODO not implemented yet. The user can override the skipping decision by connecting to the ``autodoc-skip-member`` event. """ ret = [] isattr = False for (membername, member) in members: if not want_all: ret.append((membername, member, isattr)) elif member.doc or self.options.undoc_members: if member.is_public() or self.options.private_members: ret.append((membername, member, isattr)) return ret def format_name(self) -> str: """Format the name of *self.object*. This normally should be something that can be parsed by the generated directive, but doesn't need to be (Sphinx will display it unparsed then). For things like functions and others this will include the return type. """ return self.object.format_name() def format_args(self, **kwargs: Any) -> str: """ Creates the parenthesis version of the function signature. i.e. this will be the `(int hello, int what)` portion of the header. """ return self.object.format_args(**kwargs) class CModuleDocumenter(CObjectDocumenter): """ This auto documenter will be registered as a directive named `autocmodule`, there may be a way to override the python `automodule`, just not sure yet... """ objtype = "cmodule" directivetype = "module" @classmethod def can_document_member( cls, member: Any, membername: str, isattr: bool, parent: Any ) -> bool: """ Modules are top levels so should never be included as a child of another c object. Parameters: member (object): The member item to document. This type is specific to the item being processed by autodoc. These instances will only attempt to process :class:`sphinx_c_autodoc.loader.CObjectDocumenter`. membername (str): The name of the item to document. For example if this is a function then this will be the name of the function, no return types, no arguments. isattr (bool): Is the member an attribute. This is unused for c documenation. parent (object): The parent item of this `member`. Returns: bool: True if this class can document the `member`. """ return False class CTypeDocumenter(CObjectDocumenter): """ The documenter for the autoctype directive. """ objtype = "ctype" directivetype = "type" def __init__( self, directive: DocumenterBridge, name: str, indent: str = "" ) -> None: """ Override the :attr:`directive` so that some post processing can be performed in :meth:`generate` """ super().__init__(directive, name, indent) self._original_directive = self.directive self.directive = DocumenterBridge( self.directive.env, self.directive.reporter, self.directive.genopt, self.directive.lineno, self.directive.state, ) def generate( self, more_content: Optional[StringList] = None, real_modname: Optional[str] = None, check_module: bool = False, all_members: bool = False, ) -> None: """ generate stuff """ super().generate( more_content=more_content, real_modname=real_modname, check_module=check_module, all_members=all_members, ) self._original_directive.result.append(self.consolidate_members()) def _find_member_directives(self, name: str) -> List[Tuple[str, str, int]]: """ Find all directive lines which start with `` ..c:<name>::``. Creates a sequence of: - The short name of the item documented by the directive. - The full signature of the item documented. - The line number in :attr:`directive.results`. For instnace a directive of ``..c:some_directive word1 word2 word3`` would result in ``word3`` being the short name and ``word1 word2 word3`` being the full signature. Args: name (str): The name of the directive(s) to search for. Returns: list(tuple(str, str, int)): The short name, the full signature, and the line in :attr:`directive.results` where the directive occured. """ members = [] directive_string = f".. c:{name}::" for line_no, line in enumerate(self.directive.result): if not line.startswith(self.indent): continue if line.lstrip().startswith(directive_string): _, signature = line.split(directive_string) # members may document array types so break on the brace # `int member_name [some_size][maybe_2nd_dimension]` type_and_name, *(_) = signature.strip().partition("[") sig_parts = type_and_name.strip().split() members.append((sig_parts[-1], signature, line_no)) return members def _remove_directive(self, line: int) -> StringList: """ Remove the directive which starts at `line_no` from :attr:`directive.results`. The locations in :attr:`directive.results` will be replaced with empty lines so that the total line count of :attr:`directive.results` is unaffected. Args: line (int): The starting line to remove the directive from. Returns: :class:`StringList`: The removed directive which started at `line_no` """ # Just need to do at least one more indentation than the actual # directive to not end up grabbing the next directive. directive_line = self.directive.result[line] block_indent = (len(directive_line) - len(directive_line.lstrip())) + 1 directive, _, _ = self.directive.result.get_indented( line, first_indent=0, block_indent=block_indent, strip_indent=False ) directive.disconnect() # Setting slices need viewlists/stringlists so just iterate through and # set indices which can take strings directive_length = len(directive) for line_no in range(line, line + directive_length): self.directive.result[line_no] = self.indent return directive @staticmethod def _merge_directives(directives: List[StringList]) -> StringList: """ The last directive heading will be used to represent the heading for the entire group of directives. Args: directives (list(StringList)): The list of directives to merge. Returns: StringList: One directive """ merged_heading = StringList() merged_directive = StringList() merged_options = StringList() for directive in directives: options, _, _ = directive.get_indented( 1, until_blank=True, strip_indent=False ) if options: merged_options.extend(options) del directive[1 : 1 + len(options)] directive_heading = directive[0] del directive[0] merged_directive.extend(directive) merged_heading = directive_heading merged_directive.insert(0, merged_options) merged_directive.insert(0, merged_heading, source=merged_directive.source(0)) return merged_directive def consolidate_members(self) -> StringList: """ Take any duplicate autodoc member directives and consolidate them into one directive. The subsequent contents of duplicate directives will be added as additional paragraphs on the first occurrence of the directive. Returns: StringList: The entire rst contents for this directive instance. """ # Grab any constructs that could be declared inside of a struct, union or enum. members = [] for sub_type in ("member", "struct", "union", "enumerator"): members += self._find_member_directives(sub_type) # Group all the items by their name. This sort logic here leverages the order # preservation that python sort has, in that napoleon documented constructs are # always "member" however the actual c constructs will come after as "struct" # or similar. members.sort(key=lambda m: m[0]) data_blocks = [] for _, member_group in groupby(members, lambda m: m[0]): start_line = len(self.directive.result) directives = [] for _, _, line in member_group: directives.append(self._remove_directive(line)) if line < start_line: start_line = line original_length = len(directives[-1]) merged_directive = self._merge_directives(directives) data_blocks.append((start_line, original_length, merged_directive)) data_blocks.sort() delta_length = 0 for line, original_length, directive in data_blocks: start = line + delta_length end = start + original_length self.directive.result[start:end] = directive delta_length += len(directive) - original_length return self.directive.result def format_name(self) -> str: """Format the name of *self.object*. Sphinx doesn't like the typedef keyword being in typedef signatures so strip them off here. """ raw_name = self.object.format_name() cleaned_name = raw_name.replace("typedef ", "") return cleaned_name class CStructDocumenter(CTypeDocumenter): """ The documenter for the autocstruct directive. """ objtype = "cstruct" directivetype = "struct" def filter_members( # type: ignore[override] self, members: List[Tuple[str, Any]], want_all: bool ) -> List[Tuple[str, Any, bool]]: """Filter the given member list. For structures if they are documented then all members provided are documented. """ ret = [] isattr = False for (membername, member) in members: ret.append((membername, member, isattr)) return ret class CEnumDocumenter(CTypeDocumenter): """ The documenter for the autocenum directive. """ objtype = "cenum" directivetype = "enum" class CUnionDocumenter(CStructDocumenter): """ The documenter for the autocunion directive. """ objtype = "cunion" directivetype = "union" class CMemberDocumenter(CObjectDocumenter): """ The documenter for the autocmember directive. This handles structure and union fields. """ objtype = "cmember" directivetype = "member" class CFunctionDocumenter(CObjectDocumenter): """ The documenter for the autocfunction directive. """ objtype = "cfunction" directivetype = "function" class CMacroDocumenter(CObjectDocumenter): """ The documenter for the autocmacro directive. """ objtype = "cmacro" directivetype = "macro" class CEnumeratorDocumenter(CObjectDocumenter): """ The documenter for the autocenumerator directive. These are enumerator constants, versus the enum (type). """ objtype = "cenumerator" directivetype = "enumerator" class CDataDocumenter(CObjectDocumenter): """ The documenter for the autocdata directive. """ objtype = "cdata" directivetype = "var" @classmethod def can_document_member( cls, member: Any, membername: str, isattr: bool, parent: Any ) -> bool: """ Parameters: member (object): The member item to document. This type is specific to the item being processed by autodoc. These classes will only attempt to process :class:`sphinx_c_autodoc.loader.CObjectDocumenter` members. membername (str): The name of the item to document. For example if this is a function then this will be the name of the function, no return types, no arguments. isattr (bool): Is the member an attribute. This is unused for c documenation. parent (object): The parent item of this `member`. Returns: bool: True if this class can document the `member`. """ # Handle the mapping of c land `variable` to sphinx land `data`. The c # domain in sphinx seems inconsistent the directive is called # ``.. c:var::``, yet the role is ``:c:data:``. return isinstance(parent, CObjectDocumenter) and member.type == "variable" class CModule(CObject): """ Module directive for C files """ has_content = True required_arguments = 1 object_type = "module" def run(self) -> nodes.Node: """ Not sure yet """ state = self.state node = nodes.section() rst = ViewList(self.content, "testing") # Parse the restructured text into nodes. state.nested_parse(rst, 0, node, match_titles=1) return node.children def setup(app: Sphinx) -> None: """ Setup function for registering this with sphinx """ app.require_sphinx("2.0") app.setup_extension("sphinx.ext.autodoc") app.add_autodocumenter(CModuleDocumenter) app.add_autodocumenter(CFunctionDocumenter) app.add_autodocumenter(CTypeDocumenter) app.add_autodocumenter(CStructDocumenter) app.add_autodocumenter(CUnionDocumenter) app.add_autodocumenter(CEnumDocumenter) app.add_autodocumenter(CMemberDocumenter) app.add_autodocumenter(CMacroDocumenter) app.add_autodocumenter(CEnumeratorDocumenter) app.add_autodocumenter(CDataDocumenter) app.add_directive_to_domain("c", "module", CModule) app.add_config_value("c_autodoc_roots", [""], "env") app.add_config_value("c_autodoc_compilation_database", None, "env") app.add_config_value("c_autodoc_compilation_args", [""], "env") app.add_event("c-autodoc-pre-process") patch_c_domain()
[ "sphinx.util.docstrings.prepare_docstring", "docutils.statemachine.StringList", "sphinx.ext.autodoc.directive.DocumenterBridge", "itertools.groupby", "re.compile", "docutils.statemachine.ViewList", "sphinx_c_autodoc.loader.load", "os.path.isfile", "sphinx.util.logging.getLogger", "docutils.nodes.s...
[((1762, 1789), 'sphinx.util.logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1779, 1789), False, 'from sphinx.util import logging\n'), ((1723, 1750), 'dataclasses.field', 'field', ([], {'default_factory': 'dict'}), '(default_factory=dict)\n', (1728, 1750), False, 'from dataclasses import dataclass, field\n'), ((26446, 26462), 'sphinx_c_autodoc.domains.c.patch_c_domain', 'patch_c_domain', ([], {}), '()\n', (26460, 26462), False, 'from sphinx_c_autodoc.domains.c import patch_c_domain\n'), ((4096, 4156), 're.compile', 're.compile', (['"""^([\\\\w\\\\/\\\\\\\\.]+)(::([\\\\w.]+\\\\.)?(\\\\w+))?\\\\s*$"""'], {}), "('^([\\\\w\\\\/\\\\\\\\.]+)(::([\\\\w.]+\\\\.)?(\\\\w+))?\\\\s*$')\n", (4106, 4156), False, 'import re\n'), ((9621, 9645), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (9635, 9645), False, 'import os\n'), ((15036, 15170), 'sphinx.ext.autodoc.directive.DocumenterBridge', 'DocumenterBridge', (['self.directive.env', 'self.directive.reporter', 'self.directive.genopt', 'self.directive.lineno', 'self.directive.state'], {}), '(self.directive.env, self.directive.reporter, self.\n directive.genopt, self.directive.lineno, self.directive.state)\n', (15052, 15170), False, 'from sphinx.ext.autodoc.directive import DocumenterBridge\n'), ((19015, 19027), 'docutils.statemachine.StringList', 'StringList', ([], {}), '()\n', (19025, 19027), False, 'from docutils.statemachine import ViewList, StringList\n'), ((19055, 19067), 'docutils.statemachine.StringList', 'StringList', ([], {}), '()\n', (19065, 19067), False, 'from docutils.statemachine import ViewList, StringList\n'), ((19093, 19105), 'docutils.statemachine.StringList', 'StringList', ([], {}), '()\n', (19103, 19105), False, 'from docutils.statemachine import ViewList, StringList\n'), ((20761, 20793), 'itertools.groupby', 'groupby', (['members', '(lambda m: m[0])'], {}), '(members, lambda m: m[0])\n', (20768, 20793), False, 'from itertools import groupby\n'), ((25306, 25321), 'docutils.nodes.section', 'nodes.section', ([], {}), '()\n', (25319, 25321), False, 'from docutils import nodes\n'), ((25337, 25370), 'docutils.statemachine.ViewList', 'ViewList', (['self.content', '"""testing"""'], {}), "(self.content, 'testing')\n", (25345, 25370), False, 'from docutils.statemachine import ViewList, StringList\n'), ((6966, 6990), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (6980, 6990), False, 'import os\n'), ((8258, 8326), 'sphinx_c_autodoc.loader.load', 'loader.load', (['filename', 'contents[0]', 'compilation_db', 'compilation_args'], {}), '(filename, contents[0], compilation_db, compilation_args)\n', (8269, 8326), False, 'from sphinx_c_autodoc import loader\n'), ((10135, 10182), 'sphinx.util.docstrings.prepare_docstring', 'prepare_docstring', (['docstring', 'ignore', 'tab_width'], {}), '(docstring, ignore, tab_width)\n', (10152, 10182), False, 'from sphinx.util.docstrings import prepare_docstring\n')]
# coding: utf-8 # Copyright 2016 Vauxoo (https://www.vauxoo.com) <<EMAIL>> # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). import re from odoo import models, api, fields, _ class AccountJournal(models.Model): _inherit = 'account.journal' @api.model def _prepare_liquidity_account(self, name, company, currency_id, type): ''' When preparing the values to use when creating the default debit and credit accounts of a liquidity journal, set the correct tags for the mexican localization. ''' res = super(AccountJournal, self)._prepare_liquidity_account(name, company, currency_id, type) if company.country_id.id == self.env.ref('base.mx').id: mx_tags = self.env['account.account'].mx_search_tags(res.get('code', '')) if mx_tags: res.update({ 'tag_ids': [(6, 0, [tag.id for tag in mx_tags])] }) return res class AccountAccount(models.Model): _inherit = 'account.account' @api.model def mx_search_tags(self, code): account_tag = self.env['account.account.tag'] #search if the code is compliant with the regexp we have for tags auto-assignation re_res = re.search( '^(?P<first>[1-8][0-9][0-9])[,.]' '(?P<second>[0-9][0-9])[,.]' '(?P<third>[0-9]{2,3})$', code) if not re_res: return account_tag #get the elements of that code divided with separation declared in the regexp account = re_res.groups() return account_tag.search([ ('name', '=like', "%s.%s%%" % (account[0], account[1])), ('color', '=', 4)], limit=1) @api.onchange('code') def _onchange_code(self): if self.company_id.country_id.id == self.env.ref('base.mx').id and self.code: tags = self.mx_search_tags(self.code) self.tag_ids = tags class AccountAccountTag(models.Model): _inherit = 'account.account.tag' nature = fields.Selection([ ('D', 'Debitable Account'), ('A', 'Creditable Account')], help='Used in Mexican report of electronic accounting (account nature).')
[ "odoo.api.onchange", "re.search", "odoo.fields.Selection" ]
[((1719, 1739), 'odoo.api.onchange', 'api.onchange', (['"""code"""'], {}), "('code')\n", (1731, 1739), False, 'from odoo import models, api, fields, _\n'), ((2030, 2183), 'odoo.fields.Selection', 'fields.Selection', (["[('D', 'Debitable Account'), ('A', 'Creditable Account')]"], {'help': '"""Used in Mexican report of electronic accounting (account nature)."""'}), "([('D', 'Debitable Account'), ('A', 'Creditable Account')],\n help='Used in Mexican report of electronic accounting (account nature).')\n", (2046, 2183), False, 'from odoo import models, api, fields, _\n'), ((1250, 1358), 're.search', 're.search', (['"""^(?P<first>[1-8][0-9][0-9])[,.](?P<second>[0-9][0-9])[,.](?P<third>[0-9]{2,3})$"""', 'code'], {}), "(\n '^(?P<first>[1-8][0-9][0-9])[,.](?P<second>[0-9][0-9])[,.](?P<third>[0-9]{2,3})$'\n , code)\n", (1259, 1358), False, 'import re\n')]
# (C) Copyright 1996-2018 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 csv import os from datetime import datetime from kronos_modeller.kronos_exceptions import ConfigurationError from kronos_modeller.jobs import IngestedJob, ModelJob from kronos_modeller.logreader.dataset import IngestedDataSet def read_pbs_log(filename_in): pbs_jobs = [] log_list_raw = ['ctime', 'qtime', 'etime', 'end', 'start', 'resources_used.ncpus', 'Resource_List.ncpus', 'resources_used.mem', 'resources_used.cpupercent', 'resources_used.cput', 'group', 'jobname', 'Resource_List.EC_nodes', 'queue' ] # - standardize the key nemes for different PBS log labels.. log_list = ['time_created', 'time_queued', 'time_eligible', 'time_end', 'time_start', 'ncpus', 'ncpus', 'memory_kb', 'cpu_percent', 'cpu_percent', 'group', 'jobname', 'nnodes', 'queue' ] # Read file f_in = open(filename_in, "r") cc = 1 cce = 0 for line in f_in: # array got by splitting the line larray = line.split(" ") b1_array = larray[1].split(";") # block E if (b1_array[1] == "E"): # init dictionary line_dict = {} # user name user_name = b1_array[3].split("=")[1] line_dict["user"] = str(user_name) for jobL in range(0, len(larray)): yval_val = larray[jobL].split("=") # print yval_val if (len(yval_val) == 2): if yval_val[0] in log_list_raw: # find index idx = log_list_raw.index(yval_val[0]) key_name = log_list[idx] line_dict[key_name] = yval_val[1].strip() # special case for ARCTUR PBS.. # Resource_List.nodes=1:ppn=1 if yval_val[0] == "Resource_List.nodes": if len(yval_val[1].split(":")) > 1: line_dict["nnodes"] = int(yval_val[1].split(":")[0]) if yval_val[1].split(":")[1] == "ppn": line_dict["ncpus"] = int(yval_val[2]) * int(yval_val[1].split(":")[0]) else: line_dict["ncpus"] = int(yval_val[1]) i_job = IngestedJob() # print 'i_job.time_created ', line_dict['time_created'] # print 'i_job.time_queued ', line_dict['time_queued'] # print 'i_job.time_eligible', line_dict['time_eligible'] # print 'i_job.time_end ', line_dict['time_end'] # print 'i_job.time_start ', line_dict['time_start'] # print int(line_dict['ncpus']) # print line_dict['time_created'] # print type( line_dict['time_created'] ) # print any(c.isalpha() for c in line_dict['time_created']) # created time if any([c.isalpha() for c in line_dict['time_created']]): i_job.time_created = -1 else: i_job.time_created = int(line_dict['time_created']) # queue time if any([c.isalpha() for c in line_dict['time_queued']]): i_job.time_queued = -1 else: i_job.time_queued = int(line_dict['time_queued']) # eligible time if any([c.isalpha() for c in line_dict['time_eligible']]): i_job.time_eligible = -1 else: i_job.time_eligible = int(line_dict['time_eligible']) # end time if any([c.isalpha() for c in line_dict['time_end']]): i_job.time_end = -1 else: i_job.time_end = int(line_dict['time_end']) # start time if any([c.isalpha() for c in line_dict['time_start']]): i_job.time_start = -1 else: i_job.time_start = int(line_dict['time_start']) # average memory if any([c.isalpha() for c in line_dict['memory_kb'][:-2]]): i_job.memory_kb = -1 else: i_job.memory_kb = int(line_dict['memory_kb'][:-2]) if 'ncpus' in line_dict: i_job.ncpus = int(line_dict['ncpus']) else: i_job.ncpus = -1 if 'nnodes' in line_dict: i_job.nnodes = int(line_dict['nnodes']) else: i_job.nnodes = -1 # i_job.cpu_percent = float(line_dict['cpu_percent'].replace(":", "")) i_job.group = str(line_dict['group']) i_job.jobname = str(line_dict['jobname']) i_job.user = str(line_dict['user']) i_job.queue_type = str(line_dict['queue']) i_job.cmd_str = None # command line string not available pbs_jobs.append(i_job) cce += 1 cc += 1 # remove invalid entries pbs_jobs[:] = [job for job in pbs_jobs if job.time_start != -1] pbs_jobs[:] = [job for job in pbs_jobs if job.time_end != -1] pbs_jobs[:] = [job for job in pbs_jobs if job.time_end >= job.time_start] pbs_jobs[:] = [job for job in pbs_jobs if job.time_queued != -1] pbs_jobs[:] = [job for job in pbs_jobs if job.time_start >= job.time_queued] pbs_jobs[:] = [job for job in pbs_jobs if job.ncpus > 0] pbs_jobs[:] = [job for job in pbs_jobs if job.nnodes > 0] for (ii, i_job) in enumerate(pbs_jobs): i_job.idx_in_log = ii pbs_jobs.sort(key=lambda x: x.time_start, reverse=False) # times relative to start of log min_start_time = min([i_job.time_start for i_job in pbs_jobs]) for i_job in pbs_jobs: i_job.runtime = float(i_job.time_end) - float(i_job.time_start) i_job.time_start_0 = i_job.time_start - min_start_time i_job.time_in_queue = i_job.time_start - i_job.time_queued return pbs_jobs def read_accounting_logs(filename_in): """ Reads ecmwf accounting logs :param filename_in: :return: """ accounting_jobs = [] # ['"hpc"', # '"jobid"', # '"jobname"', # '"jobstepid"', # '"owner_uid"', # '"owner_group"', # '"submitter_uid"', # '"submitter_group"', # '"queue_time"', # '"start_time"', # '"end_time"', # '"no_nodes"', # '"no_cpus"', # '"class"', # '"account"', # '"usage"', # '"sbu"', # '"step_usertime"', # '"stdin"', # '"stdout"', # '"stderr"', # '"job_name"'] with open(filename_in, 'rb') as csvfile: csv_dict = csv.DictReader(csvfile, delimiter=';', quotechar='"') for line_dict in csv_dict: i_job = IngestedJob() try: i_job.time_queued = (datetime.strptime(line_dict['queue_time'], '%Y-%m-%d %H:%M:%S') - datetime(1970, 1, 1)).total_seconds() except ValueError: i_job.time_queued = (datetime.strptime(line_dict['queue_time'], '%Y-%m-%d %H:%M:%S.%f') - datetime(1970, 1, 1)).total_seconds() try: i_job.time_end = (datetime.strptime(line_dict['end_time'], '%Y-%m-%d %H:%M:%S.%f') - datetime(1970, 1, 1)).total_seconds() except ValueError: i_job.time_end = (datetime.strptime(line_dict['end_time'], '%Y-%m-%d %H:%M:%S') - datetime(1970, 1, 1)).total_seconds() try: i_job.time_start = (datetime.strptime(line_dict['start_time'], '%Y-%m-%d %H:%M:%S.%f') - datetime(1970, 1, 1)).total_seconds() except ValueError: i_job.time_start = (datetime.strptime(line_dict['start_time'], '%Y-%m-%d %H:%M:%S') - datetime(1970, 1, 1)).total_seconds() if 'no_cpus' in line_dict: i_job.ncpus = int(line_dict['no_cpus']) else: i_job.ncpus = -1 if 'no_nodes' in line_dict: i_job.nnodes = int(line_dict['no_nodes']) else: i_job.nnodes = -1 if 'stdout' in line_dict: i_job.stdout = line_dict['stdout'] else: i_job.stdout = [] # i_job.cpu_percent = float(line_dict['cpu_percent'].replace(":", "")) i_job.group = str(line_dict['owner_group']) i_job.jobname = str(line_dict['jobname']) i_job.user = str(line_dict['owner_uid']) i_job.queue_type = str(line_dict['class']) i_job.cmd_str = None # command line string not available # info not available i_job.time_created = -1 i_job.time_eligible = -1 i_job.memory_kb = -1 accounting_jobs.append(i_job) # remove invalid entries accounting_jobs[:] = [job for job in accounting_jobs if job.time_start != -1] accounting_jobs[:] = [job for job in accounting_jobs if job.time_end != -1] accounting_jobs[:] = [job for job in accounting_jobs if job.time_end >= job.time_start] accounting_jobs[:] = [job for job in accounting_jobs if job.time_queued != -1] accounting_jobs[:] = [job for job in accounting_jobs if job.time_start >= job.time_queued] accounting_jobs[:] = [job for job in accounting_jobs if job.ncpus > 0] accounting_jobs[:] = [job for job in accounting_jobs if job.nnodes > 0] # store the original idx of each job.. for (ii, i_job) in enumerate(accounting_jobs): i_job.idx_in_log = ii accounting_jobs.sort(key=lambda x: x.time_start, reverse=False) # times relative to start of log min_start_time = min([i_job.time_start for i_job in accounting_jobs]) for i_job in accounting_jobs: # print type(i_job.time_queued), type(i_job.time_end), type(i_job.time_start) i_job.runtime = float(i_job.time_end) - float(i_job.time_start) i_job.time_start_0 = i_job.time_start - min_start_time i_job.time_in_queue = i_job.time_start - i_job.time_queued return accounting_jobs def read_epcc_csv_logs(filename_in): """ read CSV logs from EPCC.. """ csv_jobs = [] with open(filename_in, 'rb') as csvfile: csv_dict = csv.DictReader(csvfile, delimiter=',', quotechar='"') for line_dict in csv_dict: i_job = IngestedJob() # if isinstance(line_dict['ctime'], str): # # i_job.time_queued = int(line_dict['ctime']) # i_job.time_queued = int(line_dict['start']) + 999 # will be removed later.. # else: # print "line_dict['ctime']: ", line_dict['ctime'] # i_job.time_queued = int(line_dict['start']) + 999 # will be removed later.. try: i_job.time_queued = int(line_dict['ctime']) except: print(("I didn't recognize ctime {0} as a number".format(line_dict['ctime']))) i_job.time_queued = -1 try: i_job.time_end = int(line_dict['end']) except: print(("I didn't recognize end {0} as a number".format(line_dict['end']))) i_job.time_end = -1 try: i_job.time_start = int(line_dict['start']) except: print(("I didn't recognize start {0} as a number".format(line_dict['start']))) i_job.time_start = -1 try: i_job.ncpus = int(line_dict['ncpus']) except: print(("I didn't recognize start {0} as a number".format(line_dict['ncpus']))) i_job.ncpus = -1 try: i_job.nnodes = int(line_dict['node_count']) except: print(("I didn't recognize start {0} as a number".format(line_dict['node_count']))) i_job.nnodes = -1 # i_job.group = line_dict['group'].strip() i_job.group = '' if line_dict['jobname']: i_job.jobname = line_dict['jobname'].strip() else: i_job.jobname = '' if line_dict['jobname']: i_job.user = line_dict['UserID'].strip() else: i_job.user = '' if line_dict['jobname']: i_job.queue_type = line_dict['queue'].strip() else: i_job.queue_type = '' # info not available i_job.time_created = -1 i_job.time_eligible = -1 i_job.memory_kb = -1 i_job.cmd_str = None # command line string not available csv_jobs.append(i_job) # remove invalid entries csv_jobs[:] = [job for job in csv_jobs if job.time_start != -1] csv_jobs[:] = [job for job in csv_jobs if job.time_end != -1] csv_jobs[:] = [job for job in csv_jobs if job.time_end >= job.time_start] csv_jobs[:] = [job for job in csv_jobs if job.time_queued != -1] csv_jobs[:] = [job for job in csv_jobs if job.time_start >= job.time_queued] csv_jobs[:] = [job for job in csv_jobs if job.ncpus > 0] csv_jobs[:] = [job for job in csv_jobs if job.nnodes > 0] # store the original idx of each job.. for (ii, i_job) in enumerate(csv_jobs): i_job.idx_in_log = ii csv_jobs.sort(key=lambda x: x.time_start, reverse=False) # times relative to start of log min_start_time = min([i_job.time_start for i_job in csv_jobs]) for i_job in csv_jobs: # print type(i_job.time_queued), type(i_job.time_end), type(i_job.time_start) i_job.runtime = float(i_job.time_end) - float(i_job.time_start) i_job.time_start_0 = i_job.time_start - min_start_time i_job.time_in_queue = i_job.time_start - i_job.time_queued return csv_jobs class PBSDataSet(IngestedDataSet): def __init__(self, joblist, *args, **kwargs): super(PBSDataSet, self).__init__(joblist, '.', {'cache':False}) # The created times are all in seconds since an arbitrary reference, so we want to get # them relative to a zero-time created_time_list = [j.time_created for j in self.joblist if j.time_created >= 0] self.global_created_time = 0.0 if created_time_list: self.global_created_time = min(created_time_list) start_time_list = [j.time_created for j in self.joblist if j.time_created >= 0] self.global_start_time = 0.0 if start_time_list: self.global_start_time = min(start_time_list) def model_jobs(self): for job in self.joblist: # assert isinstance(job, IngestedJob) assert not job.timesignals # if job.time_created >= 0: # submit_time = job.time_created - self.global_created_time # else: # submit_time = job.time_start - self.global_start_time yield ModelJob( job_name=job.jobname, user_name=job.user, cmd_str=job.cmd_str, queue_name=job.queue_type, time_queued=job.time_queued, time_start=job.time_start, duration=job.time_end-job.time_start, ncpus=job.ncpus, nnodes=job.nnodes, stdout=job.stdout, label=None, ) def ingest_pbs_logs(path, cfg=None): """ Read PBS logs into a dataset """ if not os.path.exists(path): raise ConfigurationError("Specified path to ingest PBS profiles does not exist: {}".format(path)) if not os.path.isfile(path): raise ConfigurationError("Specified path for PBS time_schedule is not a file") jobs = read_pbs_log(path) return PBSDataSet(jobs) def ingest_epcc_csv_logs(path, cfg=None): """ Read PBS logs into a dataset """ if not os.path.exists(path): raise ConfigurationError("Specified path to ingest CSV profiles does not exist: {}".format(path)) if not os.path.isfile(path): raise ConfigurationError("Specified path for CSV time_schedule is not a file") jobs = read_epcc_csv_logs(path) return PBSDataSet(jobs) class AccountingDataSet(IngestedDataSet): def __init__(self, joblist, *args, **kwargs): super(AccountingDataSet, self).__init__(joblist, '.', {'cache':False}) # The created times are all in seconds since an arbitrary reference, so we want to get # them relative to a zero-time self.global_start_time = min((j.time_start for j in self.joblist if j.time_start >= 0)) def model_jobs(self): for job in self.joblist: assert isinstance(job, IngestedJob) assert not job.timesignals # yield ModelJob( # time_start=job.time_start - self.global_start_time, # duration=job.time_end-job.time_start, # ncpus=job.ncpus, # nnodes=job.nnodes, # scheduler_timing=job.time_queued, # stdout=job.stdout # ) yield ModelJob( job_name=job.jobname, user_name=job.user, cmd_str=job.cmd_str, queue_name=job.queue_type, time_queued=job.time_queued, time_start=job.time_start, duration=job.time_end - job.time_start, ncpus=job.ncpus, nnodes=job.nnodes, scheduler_timing=job.time_queued, stdout=job.stdout, label=None, ) def ingest_accounting_logs(path, cfg=None): """ Read PBS logs into a dataset """ if not os.path.exists(path): raise ConfigurationError("Specified path to ingest accounting profiles does not exist: {}".format(path)) if not os.path.isfile(path): raise ConfigurationError("Specified path for accounting log is not a file") jobs = read_accounting_logs(path) return PBSDataSet(jobs)
[ "datetime.datetime", "os.path.exists", "csv.DictReader", "kronos_modeller.jobs.IngestedJob", "datetime.datetime.strptime", "kronos_modeller.jobs.ModelJob", "os.path.isfile", "kronos_modeller.kronos_exceptions.ConfigurationError" ]
[((7413, 7466), 'csv.DictReader', 'csv.DictReader', (['csvfile'], {'delimiter': '""";"""', 'quotechar': '"""\\""""'}), '(csvfile, delimiter=\';\', quotechar=\'"\')\n', (7427, 7466), False, 'import csv\n'), ((11169, 11222), 'csv.DictReader', 'csv.DictReader', (['csvfile'], {'delimiter': '""","""', 'quotechar': '"""\\""""'}), '(csvfile, delimiter=\',\', quotechar=\'"\')\n', (11183, 11222), False, 'import csv\n'), ((16400, 16420), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (16414, 16420), False, 'import os\n'), ((16540, 16560), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (16554, 16560), False, 'import os\n'), ((16576, 16648), 'kronos_modeller.kronos_exceptions.ConfigurationError', 'ConfigurationError', (['"""Specified path for PBS time_schedule is not a file"""'], {}), "('Specified path for PBS time_schedule is not a file')\n", (16594, 16648), False, 'from kronos_modeller.kronos_exceptions import ConfigurationError\n'), ((16813, 16833), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (16827, 16833), False, 'import os\n'), ((16953, 16973), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (16967, 16973), False, 'import os\n'), ((16989, 17061), 'kronos_modeller.kronos_exceptions.ConfigurationError', 'ConfigurationError', (['"""Specified path for CSV time_schedule is not a file"""'], {}), "('Specified path for CSV time_schedule is not a file')\n", (17007, 17061), False, 'from kronos_modeller.kronos_exceptions import ConfigurationError\n'), ((18641, 18661), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (18655, 18661), False, 'import os\n'), ((18788, 18808), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (18802, 18808), False, 'import os\n'), ((18824, 18893), 'kronos_modeller.kronos_exceptions.ConfigurationError', 'ConfigurationError', (['"""Specified path for accounting log is not a file"""'], {}), "('Specified path for accounting log is not a file')\n", (18842, 18893), False, 'from kronos_modeller.kronos_exceptions import ConfigurationError\n'), ((3119, 3132), 'kronos_modeller.jobs.IngestedJob', 'IngestedJob', ([], {}), '()\n', (3130, 3132), False, 'from kronos_modeller.jobs import IngestedJob, ModelJob\n'), ((7524, 7537), 'kronos_modeller.jobs.IngestedJob', 'IngestedJob', ([], {}), '()\n', (7535, 7537), False, 'from kronos_modeller.jobs import IngestedJob, ModelJob\n'), ((11280, 11293), 'kronos_modeller.jobs.IngestedJob', 'IngestedJob', ([], {}), '()\n', (11291, 11293), False, 'from kronos_modeller.jobs import IngestedJob, ModelJob\n'), ((15850, 16124), 'kronos_modeller.jobs.ModelJob', 'ModelJob', ([], {'job_name': 'job.jobname', 'user_name': 'job.user', 'cmd_str': 'job.cmd_str', 'queue_name': 'job.queue_type', 'time_queued': 'job.time_queued', 'time_start': 'job.time_start', 'duration': '(job.time_end - job.time_start)', 'ncpus': 'job.ncpus', 'nnodes': 'job.nnodes', 'stdout': 'job.stdout', 'label': 'None'}), '(job_name=job.jobname, user_name=job.user, cmd_str=job.cmd_str,\n queue_name=job.queue_type, time_queued=job.time_queued, time_start=job.\n time_start, duration=job.time_end - job.time_start, ncpus=job.ncpus,\n nnodes=job.nnodes, stdout=job.stdout, label=None)\n', (15858, 16124), False, 'from kronos_modeller.jobs import IngestedJob, ModelJob\n'), ((18032, 18344), 'kronos_modeller.jobs.ModelJob', 'ModelJob', ([], {'job_name': 'job.jobname', 'user_name': 'job.user', 'cmd_str': 'job.cmd_str', 'queue_name': 'job.queue_type', 'time_queued': 'job.time_queued', 'time_start': 'job.time_start', 'duration': '(job.time_end - job.time_start)', 'ncpus': 'job.ncpus', 'nnodes': 'job.nnodes', 'scheduler_timing': 'job.time_queued', 'stdout': 'job.stdout', 'label': 'None'}), '(job_name=job.jobname, user_name=job.user, cmd_str=job.cmd_str,\n queue_name=job.queue_type, time_queued=job.time_queued, time_start=job.\n time_start, duration=job.time_end - job.time_start, ncpus=job.ncpus,\n nnodes=job.nnodes, scheduler_timing=job.time_queued, stdout=job.stdout,\n label=None)\n', (18040, 18344), False, 'from kronos_modeller.jobs import IngestedJob, ModelJob\n'), ((7593, 7656), 'datetime.datetime.strptime', 'datetime.strptime', (["line_dict['queue_time']", '"""%Y-%m-%d %H:%M:%S"""'], {}), "(line_dict['queue_time'], '%Y-%m-%d %H:%M:%S')\n", (7610, 7656), False, 'from datetime import datetime\n'), ((7696, 7716), 'datetime.datetime', 'datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (7704, 7716), False, 'from datetime import datetime\n'), ((7998, 8062), 'datetime.datetime.strptime', 'datetime.strptime', (["line_dict['end_time']", '"""%Y-%m-%d %H:%M:%S.%f"""'], {}), "(line_dict['end_time'], '%Y-%m-%d %H:%M:%S.%f')\n", (8015, 8062), False, 'from datetime import datetime\n'), ((8099, 8119), 'datetime.datetime', 'datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (8107, 8119), False, 'from datetime import datetime\n'), ((8392, 8458), 'datetime.datetime.strptime', 'datetime.strptime', (["line_dict['start_time']", '"""%Y-%m-%d %H:%M:%S.%f"""'], {}), "(line_dict['start_time'], '%Y-%m-%d %H:%M:%S.%f')\n", (8409, 8458), False, 'from datetime import datetime\n'), ((8497, 8517), 'datetime.datetime', 'datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (8505, 8517), False, 'from datetime import datetime\n'), ((7802, 7868), 'datetime.datetime.strptime', 'datetime.strptime', (["line_dict['queue_time']", '"""%Y-%m-%d %H:%M:%S.%f"""'], {}), "(line_dict['queue_time'], '%Y-%m-%d %H:%M:%S.%f')\n", (7819, 7868), False, 'from datetime import datetime\n'), ((7908, 7928), 'datetime.datetime', 'datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (7916, 7928), False, 'from datetime import datetime\n'), ((8202, 8263), 'datetime.datetime.strptime', 'datetime.strptime', (["line_dict['end_time']", '"""%Y-%m-%d %H:%M:%S"""'], {}), "(line_dict['end_time'], '%Y-%m-%d %H:%M:%S')\n", (8219, 8263), False, 'from datetime import datetime\n'), ((8300, 8320), 'datetime.datetime', 'datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (8308, 8320), False, 'from datetime import datetime\n'), ((8602, 8665), 'datetime.datetime.strptime', 'datetime.strptime', (["line_dict['start_time']", '"""%Y-%m-%d %H:%M:%S"""'], {}), "(line_dict['start_time'], '%Y-%m-%d %H:%M:%S')\n", (8619, 8665), False, 'from datetime import datetime\n'), ((8704, 8724), 'datetime.datetime', 'datetime', (['(1970)', '(1)', '(1)'], {}), '(1970, 1, 1)\n', (8712, 8724), False, 'from datetime import datetime\n')]
import numpy as np import multiprocessing import sys have_cext = False try: from .. import _cext have_cext = True except ImportError: pass except: print("the C extension is installed...but failed to load!") pass try: import xgboost except ImportError: pass except: print("xgboost is installed...but failed to load!") pass try: import lightgbm except ImportError: pass except: print("lightgbm is installed...but failed to load!") pass try: import catboost except ImportError: pass except: print("catboost is installed...but failed to load!") pass class TreeExplainer: """Uses the Tree SHAP method to explain the output of ensemble tree models. Tree SHAP is a fast and exact method to estimate SHAP values for tree models and ensembles of trees. It depends on fast C++ implementations either inside the package or in the compiled C extention. """ def __init__(self, model, **kwargs): self.model_type = "internal" if str(type(model)).endswith("sklearn.ensemble.forest.RandomForestRegressor'>"): self.trees = [Tree(e.tree_) for e in model.estimators_] elif str(type(model)).endswith("sklearn.tree.tree.DecisionTreeRegressor'>"): self.trees = [Tree(model.tree_)] elif str(type(model)).endswith("sklearn.ensemble.forest.RandomForestClassifier'>"): self.trees = [Tree(e.tree_, normalize=True) for e in model.estimators_] elif str(type(model)).endswith("xgboost.core.Booster'>"): self.model_type = "xgboost" self.trees = model elif str(type(model)).endswith("xgboost.sklearn.XGBClassifier'>"): self.model_type = "xgboost" self.trees = model.get_booster() elif str(type(model)).endswith("xgboost.sklearn.XGBRegressor'>"): self.model_type = "xgboost" self.trees = model.get_booster() elif str(type(model)).endswith("lightgbm.basic.Booster'>"): self.model_type = "lightgbm" self.trees = model elif str(type(model)).endswith("lightgbm.sklearn.LGBMRegressor'>"): self.model_type = "lightgbm" self.trees = model.booster_ elif str(type(model)).endswith("lightgbm.sklearn.LGBMClassifier'>"): self.model_type = "lightgbm" self.trees = model.booster_ elif str(type(model)).endswith("catboost.core.CatBoostRegressor'>"): self.model_type = "catboost" self.trees = model elif str(type(model)).endswith("catboost.core.CatBoostClassifier'>"): self.model_type = "catboost" self.trees = model else: raise Exception("Model type not yet supported by TreeExplainer: " + str(type(model))) def shap_values(self, X, **kwargs): """ Estimate the SHAP values for a set of samples. Parameters ---------- X : numpy.array or pandas.DataFrame A matrix of samples (# samples x # features) on which to explain the model's output. Returns ------- For a models with a single output this returns a matrix of SHAP values (# samples x # features + 1). The last column is the base value of the model, which is the expected value of the model applied to the background dataset. This causes each row to sum to the model output for that sample. For models with vector outputs this returns a list of such matrices, one for each output. """ # shortcut using the C++ version of Tree SHAP in XGBoost, LightGBM, and CatBoost phi = None if self.model_type == "xgboost": if not str(type(X)).endswith("xgboost.core.DMatrix'>"): X = xgboost.DMatrix(X) phi = self.trees.predict(X, pred_contribs=True) elif self.model_type == "lightgbm": phi = self.trees.predict(X, pred_contrib=True) if phi.shape[1] != X.shape[1] + 1: phi = phi.reshape(X.shape[0], phi.shape[1]//(X.shape[1]+1), X.shape[1]+1) elif self.model_type == "catboost": # thanks to the CatBoost team for implementing this... phi = self.trees.get_feature_importance(data=catboost.Pool(X), fstr_type='ShapValues') if phi is not None: if len(phi.shape) == 3: return [phi[:, i, :] for i in range(phi.shape[1])] else: return phi # convert dataframes if str(type(X)).endswith("pandas.core.series.Series'>"): X = X.values elif str(type(X)).endswith("pandas.core.frame.DataFrame'>"): X = X.values assert str(type(X)).endswith("'numpy.ndarray'>"), "Unknown instance type: " + str(type(X)) assert len(X.shape) == 1 or len(X.shape) == 2, "Instance must have 1 or 2 dimensions!" self.n_outputs = self.trees[0].values.shape[1] # single instance if len(X.shape) == 1: phi = np.zeros((X.shape[0] + 1, self.n_outputs)) x_missing = np.zeros(X.shape[0], dtype=np.bool) for t in self.trees: self.tree_shap(t, X, x_missing, phi) phi /= len(self.trees) if self.n_outputs == 1: return phi[:, 0] else: return [phi[:, i] for i in range(self.n_outputs)] elif len(X.shape) == 2: x_missing = np.zeros(X.shape[1], dtype=np.bool) self._current_X = X self._current_x_missing = x_missing # Only python 3 can serialize a method to send to another process if sys.version_info[0] >= 3: pool = multiprocessing.Pool() phi = np.stack(pool.map(self._tree_shap_ind, range(X.shape[0])), 0) pool.close() else: phi = np.stack(map(self._tree_shap_ind, range(X.shape[0])), 0) if self.n_outputs == 1: return phi[:, :, 0] else: return [phi[:, :, i] for i in range(self.n_outputs)] def shap_interaction_values(self, X, **kwargs): # shortcut using the C++ version of Tree SHAP in XGBoost and LightGBM if self.model_type == "xgboost": if not str(type(X)).endswith("xgboost.core.DMatrix'>"): X = xgboost.DMatrix(X) phi = self.trees.predict(X, pred_interactions=True) if len(phi.shape) == 4: return [phi[:, i, :, :] for i in range(phi.shape[1])] else: return phi else: raise Exception("Interaction values not yet supported for model type: " + self.model_type) def _tree_shap_ind(self, i): phi = np.zeros((self._current_X.shape[1] + 1, self.n_outputs)) for t in self.trees: self.tree_shap(t, self._current_X[i,:], self._current_x_missing, phi) phi /= len(self.trees) return phi def tree_shap(self, tree, x, x_missing, phi, condition=0, condition_feature=0): # start the recursive algorithm assert have_cext, "C extension was not built during install!" _cext.tree_shap( tree.max_depth, tree.children_left, tree.children_right, tree.children_default, tree.features, tree.thresholds, tree.values, tree.node_sample_weight, x, x_missing, phi, condition, condition_feature ) class Tree: def __init__(self, children_left, children_right, children_default, feature, threshold, value, node_sample_weight): self.children_left = children_left.astype(np.int32) self.children_right = children_right.astype(np.int32) self.children_default = children_default.astype(np.int32) self.features = feature.astype(np.int32) self.thresholds = threshold self.values = value self.node_sample_weight = node_sample_weight # we compute the expectations to make sure they follow the SHAP logic assert have_cext, "C extension was not built during install!" self.max_depth = _cext.compute_expectations( self.children_left, self.children_right, self.node_sample_weight, self.values ) def __init__(self, tree, normalize=False): if str(type(tree)).endswith("'sklearn.tree._tree.Tree'>"): self.children_left = tree.children_left.astype(np.int32) self.children_right = tree.children_right.astype(np.int32) self.children_default = self.children_left # missing values not supported in sklearn self.features = tree.feature.astype(np.int32) self.thresholds = tree.threshold.astype(np.float64) if normalize: self.values = (tree.value[:,0,:].T / tree.value[:,0,:].sum(1)).T else: self.values = tree.value[:,0,:] self.node_sample_weight = tree.weighted_n_node_samples.astype(np.float64) # we compute the expectations to make sure they follow the SHAP logic self.max_depth = _cext.compute_expectations( self.children_left, self.children_right, self.node_sample_weight, self.values )
[ "numpy.zeros", "xgboost.DMatrix", "catboost.Pool", "multiprocessing.Pool" ]
[((6770, 6826), 'numpy.zeros', 'np.zeros', (['(self._current_X.shape[1] + 1, self.n_outputs)'], {}), '((self._current_X.shape[1] + 1, self.n_outputs))\n', (6778, 6826), True, 'import numpy as np\n'), ((5023, 5065), 'numpy.zeros', 'np.zeros', (['(X.shape[0] + 1, self.n_outputs)'], {}), '((X.shape[0] + 1, self.n_outputs))\n', (5031, 5065), True, 'import numpy as np\n'), ((5090, 5125), 'numpy.zeros', 'np.zeros', (['X.shape[0]'], {'dtype': 'np.bool'}), '(X.shape[0], dtype=np.bool)\n', (5098, 5125), True, 'import numpy as np\n'), ((3788, 3806), 'xgboost.DMatrix', 'xgboost.DMatrix', (['X'], {}), '(X)\n', (3803, 3806), False, 'import xgboost\n'), ((5458, 5493), 'numpy.zeros', 'np.zeros', (['X.shape[1]'], {'dtype': 'np.bool'}), '(X.shape[1], dtype=np.bool)\n', (5466, 5493), True, 'import numpy as np\n'), ((6371, 6389), 'xgboost.DMatrix', 'xgboost.DMatrix', (['X'], {}), '(X)\n', (6386, 6389), False, 'import xgboost\n'), ((5717, 5739), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {}), '()\n', (5737, 5739), False, 'import multiprocessing\n'), ((4263, 4279), 'catboost.Pool', 'catboost.Pool', (['X'], {}), '(X)\n', (4276, 4279), False, 'import catboost\n')]
import os import shutil from argparse import ArgumentParser from tmd.bilayer.dgrid import get_prefixes from tmd.bilayer.bilayer_util import global_config def _main(): parser = ArgumentParser("wfc cleanup") parser.add_argument("--subdir", type=str, default=None, help="Subdirectory under work_base where calculation was run") parser.add_argument('global_prefix', type=str, help="System for which wannier/ .save directories will be removed") parser.add_argument('--confirm', action='store_true', help="Must specify --confirm to confirm .save removal is desired") args = parser.parse_args() if not args.confirm: return gconf = global_config() work = os.path.expandvars(gconf["work_base"]) if args.subdir is not None: work = os.path.join(work, args.subdir) prefixes = get_prefixes(work, args.global_prefix) for prefix in prefixes: save_path = os.path.join(work, prefix, "wannier", "{}.save".format(prefix)) shutil.rmtree(save_path) if __name__ == "__main__": _main()
[ "tmd.bilayer.dgrid.get_prefixes", "argparse.ArgumentParser", "os.path.expandvars", "os.path.join", "shutil.rmtree", "tmd.bilayer.bilayer_util.global_config" ]
[((181, 210), 'argparse.ArgumentParser', 'ArgumentParser', (['"""wfc cleanup"""'], {}), "('wfc cleanup')\n", (195, 210), False, 'from argparse import ArgumentParser\n'), ((699, 714), 'tmd.bilayer.bilayer_util.global_config', 'global_config', ([], {}), '()\n', (712, 714), False, 'from tmd.bilayer.bilayer_util import global_config\n'), ((726, 764), 'os.path.expandvars', 'os.path.expandvars', (["gconf['work_base']"], {}), "(gconf['work_base'])\n", (744, 764), False, 'import os\n'), ((860, 898), 'tmd.bilayer.dgrid.get_prefixes', 'get_prefixes', (['work', 'args.global_prefix'], {}), '(work, args.global_prefix)\n', (872, 898), False, 'from tmd.bilayer.dgrid import get_prefixes\n'), ((812, 843), 'os.path.join', 'os.path.join', (['work', 'args.subdir'], {}), '(work, args.subdir)\n', (824, 843), False, 'import os\n'), ((1020, 1044), 'shutil.rmtree', 'shutil.rmtree', (['save_path'], {}), '(save_path)\n', (1033, 1044), False, 'import shutil\n')]
from helpers import as_list lines = as_list('2016/day6/input.txt') # lines = as_list('2016/day6/example-input.txt') length = len(lines[0]) positions = { } for line in lines: for i, c in enumerate(line): v = positions.setdefault(i, dict()).setdefault(c, 0) positions[i][c] = v + 1 most_common = '' least_common = '' for p in positions.values(): s = sorted(p.items(), key=lambda kv: kv[1], reverse=True) most_common += s[0][0] least_common += s[-1][0] # word += sorted(p, key=lambda kv: (v), reverse=True)[0] print('2016 Day 6 Part 1') print(most_common) print('2016 Day 6 Part 2') print(least_common)
[ "helpers.as_list" ]
[((37, 67), 'helpers.as_list', 'as_list', (['"""2016/day6/input.txt"""'], {}), "('2016/day6/input.txt')\n", (44, 67), False, 'from helpers import as_list\n')]
import os import time max_brightness = 26666 stream = os.popen("cat /sys/class/backlight/intel_backlight/brightness") output = int(stream.read()) print(f"{int(output/max_brightness * 100)}%")
[ "os.popen" ]
[((55, 118), 'os.popen', 'os.popen', (['"""cat /sys/class/backlight/intel_backlight/brightness"""'], {}), "('cat /sys/class/backlight/intel_backlight/brightness')\n", (63, 118), False, 'import os\n')]
"""The spalloc command-line tool and Python library determine their default configuration options from a spalloc configuration file if present. .. note:: Use of spalloc's configuration files is entirely optional as all configuration options may be presented as arguments to commands/methods at runtime. By default, configuration files are read (in ascending order of priority) from a system-wide configuration directory (e.g. ``/etc/xdg/spalloc``), user configuration file (e.g. ``$HOME/.config/spalloc``) and finally the current working directory (in a file named ``.spalloc``). The default search paths on your system can be discovered by running:: $ python -m spalloc.config Config files use the Python :py:mod:`configparser` INI-format with a single section, ``spalloc``, like so:: [spalloc] hostname = localhost owner = <EMAIL> Though most users will only wish to specify the ``hostname`` and ``owner`` options (as in the example above), the following enumerates the complete set of options available (and the default value). ``hostname`` The hostname or IP address of the spalloc-server to connect to. ``owner`` The name of the owner of created jobs. By convention the user's email address. ``port`` The port used by the spalloc-server. (Default: 22244) ``keepalive`` The keepalive interval, in seconds, to use when creating jobs. If the spalloc-server does not receive a keepalive command for this interval the job is automatically destroyed. May be set to None to disable this feature. (Default: 60.0) ``reconnect_delay`` The time, in seconds, to wait between reconnection attempts to the server if disconnected. (Default 5.0) ``timeout`` The time, in seconds, to wait before giving up waiting for a response from the server or None to wait forever. (Default 5.0) ``machine`` The name of a specific machine on which to run all jobs or None to use any available machine. (Default: None) ``tags`` The set of tags, comma seperated, to require a machine to have when allocating jobs. (Default: default) ``min_ratio`` Require that when allocating a number of boards the allocation is at least as square as this aspect ratio. (Default: 0.333) ``max_dead_boards`` The maximum number of dead boards which may be present in an allocated set of boards or None to allow any number of dead boards. (Default: 0) ``max_dead_links`` The maximum number of dead links which may be present in an allocated set of boards or None to allow any number of dead links. (Default: None) ``require_torus`` If True, require that an allocation have wrap-around links. This typically requires the allocation of a whole machine. If False, wrap-around links may or may-not be present in allocated machines. (Default: False) """ import os import os.path import appdirs from six import iteritems from six.moves.configparser import ConfigParser, NoOptionError # The application name to use in config file names _name = "spalloc" # Standard config file names/locations SYSTEM_CONFIG_FILE = appdirs.site_config_dir(_name) USER_CONFIG_FILE = appdirs.user_config_dir(_name) CWD_CONFIG_FILE = os.path.join(os.curdir, ".{}".format(_name)) # Search path for config files (lowest to highest priority) SEARCH_PATH = [ SYSTEM_CONFIG_FILE, USER_CONFIG_FILE, CWD_CONFIG_FILE, ] def read_config(filenames=SEARCH_PATH): """Attempt to read local configuration files to determine spalloc client settings. Parameters ---------- filenames : [str, ...] Filenames to attempt to read. Later config file have higher priority. Returns ------- dict The configuration loaded. """ parser = ConfigParser() # Set default config values (NB: No read_dict in Python 2.7) parser.add_section("spalloc") for key, value in iteritems({"port": "22244", "keepalive": "60.0", "reconnect_delay": "5.0", "timeout": "5.0", "machine": "None", "tags": "None", "min_ratio": "0.333", "max_dead_boards": "0", "max_dead_links": "None", "require_torus": "False"}): parser.set("spalloc", key, value) # Attempt to read from each possible file location in turn for filename in filenames: try: with open(filename, "r") as f: parser.readfp(f, filename) except (IOError, OSError): # File did not exist, keep trying pass cfg = {} try: cfg["hostname"] = parser.get("spalloc", "hostname") except NoOptionError: cfg["hostname"] = None cfg["port"] = parser.getint("spalloc", "port") try: cfg["owner"] = parser.get("spalloc", "owner") except NoOptionError: cfg["owner"] = None if parser.get("spalloc", "keepalive") == "None": cfg["keepalive"] = None else: cfg["keepalive"] = parser.getfloat("spalloc", "keepalive") cfg["reconnect_delay"] = parser.getfloat("spalloc", "reconnect_delay") if parser.get("spalloc", "timeout") == "None": cfg["timeout"] = None else: cfg["timeout"] = parser.getfloat("spalloc", "timeout") if parser.get("spalloc", "machine") == "None": cfg["machine"] = None else: cfg["machine"] = parser.get("spalloc", "machine") if parser.get("spalloc", "tags") == "None": cfg["tags"] = None else: cfg["tags"] = list(map(str.strip, parser.get("spalloc", "tags").split(","))) cfg["min_ratio"] = parser.getfloat("spalloc", "min_ratio") if parser.get("spalloc", "max_dead_boards") == "None": cfg["max_dead_boards"] = None else: cfg["max_dead_boards"] = parser.getint("spalloc", "max_dead_boards") if parser.get("spalloc", "max_dead_links") == "None": cfg["max_dead_links"] = None else: cfg["max_dead_links"] = parser.getint("spalloc", "max_dead_links") cfg["require_torus"] = parser.getboolean("spalloc", "require_torus") return cfg if __name__ == "__main__": # pragma: no cover print("Default search path (lowest-priority first):") print("\n".join(SEARCH_PATH))
[ "appdirs.site_config_dir", "appdirs.user_config_dir", "six.moves.configparser.ConfigParser", "six.iteritems" ]
[((3103, 3133), 'appdirs.site_config_dir', 'appdirs.site_config_dir', (['_name'], {}), '(_name)\n', (3126, 3133), False, 'import appdirs\n'), ((3153, 3183), 'appdirs.user_config_dir', 'appdirs.user_config_dir', (['_name'], {}), '(_name)\n', (3176, 3183), False, 'import appdirs\n'), ((3751, 3765), 'six.moves.configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (3763, 3765), False, 'from six.moves.configparser import ConfigParser, NoOptionError\n'), ((3888, 4126), 'six.iteritems', 'iteritems', (["{'port': '22244', 'keepalive': '60.0', 'reconnect_delay': '5.0', 'timeout':\n '5.0', 'machine': 'None', 'tags': 'None', 'min_ratio': '0.333',\n 'max_dead_boards': '0', 'max_dead_links': 'None', 'require_torus': 'False'}"], {}), "({'port': '22244', 'keepalive': '60.0', 'reconnect_delay': '5.0',\n 'timeout': '5.0', 'machine': 'None', 'tags': 'None', 'min_ratio':\n '0.333', 'max_dead_boards': '0', 'max_dead_links': 'None',\n 'require_torus': 'False'})\n", (3897, 4126), False, 'from six import iteritems\n')]
from overrides import overrides from allennlp.data import Instance from allennlp.common.util import JsonDict from allennlp.predictors.predictor import Predictor @Predictor.register('nfh_classification') class NfhDetectorPredictor(Predictor): """"Predictor wrapper for the NfhDetector""" @overrides def _json_to_instance(self, json_dict: JsonDict) -> Instance: # def _json_to_instance(self, json_dict: JsonDict) -> JsonDict: sentence = json_dict['tokens'] anchor_span = json_dict['anchors_indices'] label = json_dict['label'] if 'label' in json_dict else None instance = self._dataset_reader.text_to_instance(tokens=sentence, anchors_indices=anchor_span, head=label) # span_d = self._setting_output_span_indices(1, # ['YEAR', 'AGE', 'CURRENCY', 'PEOPLE', 'TIME', 'OTHER']) # label_dict = {v: k for k, v in span_d.items()} #return {'instance': instance, 'label_dict': label_dict} return instance def _setting_output_span_indices(self, span_len, additional_classes): """ creating a dictionary from the labels (year, age, etc. and spans indices) to integers :param span_len: the maximum possible span length :param additional_classes: the `Implicit' classes described in the paper (year, age etc.) :return: the mapping dictionary """ span_dic = {} counter = 0 for c in additional_classes: span_dic[c] = counter counter += 1 # 10000 is a random large number for i in range(10000): for j in range(1, span_len + 1): s = str(i) + ':' + str(i + j) span_dic[s] = counter counter += 1 return dict(span_dic)
[ "allennlp.predictors.predictor.Predictor.register" ]
[((165, 205), 'allennlp.predictors.predictor.Predictor.register', 'Predictor.register', (['"""nfh_classification"""'], {}), "('nfh_classification')\n", (183, 205), False, 'from allennlp.predictors.predictor import Predictor\n')]
import numpy as np from unityagents import UnityEnvironment """UnityEnv is a wrapper around UnityEnvironment The main purpose for this Env is to establish a common interface which most environments expose """ class UnityEnv: def __init__(self, env_path, train_mode = True ): self.brain = None self.brain_name = None self.train_mode = train_mode self.env = self.create_unity_env(env_path) #env details self.action_space = self.brain.vector_action_space_size self.observation_space = self.brain.vector_observation_space_size print(f'Action space {self.action_space}') print(f'State space {self.observation_space}') #backwards compatibility self.action_dim = self.action_space #self.observation_space = self.env.observation_space self.state_dim = int(np.prod(self.observation_space)) def extract_env_details(self, env_info): next_state = env_info.vector_observations # get the next state reward = env_info.rewards # get the reward done = env_info.local_done # see if episode has finished return next_state, reward, done def create_unity_env(self, env_path): env = UnityEnvironment(file_name=env_path) self.brain_name = env.brain_names[0] self.brain = env.brains[self.brain_name] return env def reset(self): env_info = self.env.reset(train_mode=self.train_mode)[self.brain_name] return self.extract_env_details(env_info)[0] def step(self, actions): actions = np.clip(actions, -1, 1) # torch.clamp(actions, min=-1, max=1) self.env.step(actions)[self.brain_name] env_info = self.env.step(actions)[self.brain_name] next_states, rewards, dones = self.extract_env_details(env_info) return next_states, rewards, np.array(dones) # return next_state, reward, np.array([done])
[ "numpy.clip", "numpy.prod", "unityagents.UnityEnvironment", "numpy.array" ]
[((1294, 1330), 'unityagents.UnityEnvironment', 'UnityEnvironment', ([], {'file_name': 'env_path'}), '(file_name=env_path)\n', (1310, 1330), False, 'from unityagents import UnityEnvironment\n'), ((1649, 1672), 'numpy.clip', 'np.clip', (['actions', '(-1)', '(1)'], {}), '(actions, -1, 1)\n', (1656, 1672), True, 'import numpy as np\n'), ((925, 956), 'numpy.prod', 'np.prod', (['self.observation_space'], {}), '(self.observation_space)\n', (932, 956), True, 'import numpy as np\n'), ((1940, 1955), 'numpy.array', 'np.array', (['dones'], {}), '(dones)\n', (1948, 1955), True, 'import numpy as np\n')]
# ----------------------------------------------------------------------------- # System Imports # ----------------------------------------------------------------------------- from operator import itemgetter # ----------------------------------------------------------------------------- # Public Imports # ----------------------------------------------------------------------------- from netcad.design_services import Design from netcad.topology import TopologyDesignService from netcad.device import DeviceCatalog # ----------------------------------------------------------------------------- # Private Imports # ----------------------------------------------------------------------------- from .device_roles import MS220p8, MR52, MX65, MR42 from .profiles import AccessVlan1 def create_design(design: Design) -> Design: aliases = design.config["alias"] = dict() aliases["sw01"] = MS220p8(name="ms01-dl1") aliases["sw02"] = MS220p8(name="ms01-dl2") aliases["sw03"] = MS220p8(name="ms01-dl3") aliases["ap01"] = MR52("ap01-dl1") aliases["ap02"] = MR42("ap01-dl2") aliases["ap03"] = MR52("ap01-dl3") aliases["mx01"] = MX65(name="mx01-dl1") aliases["mx02"] = MX65(name="mx01-dl2") all_devs = list(aliases.values()) design.add_devices(*all_devs) design.add_services( TopologyDesignService(topology_name=design.name, devices=all_devs) ) cable_devices(design) design.update() return design def cable_devices(design: Design): aliasses: DeviceCatalog = design.config["alias"] sw01, sw02, sw03 = itemgetter("sw01", "sw02", "sw03")(aliasses) ap01, ap02, ap03 = itemgetter("ap01", "ap02", "ap03")(aliasses) mx01, mx02 = itemgetter("mx01", "mx02")(aliasses) cable_id = 1 # ------------------------------------------------------------------------- # Cable Access-Points to Switches # ------------------------------------------------------------------------- # ap01.0 --- sw03.1 with ap01.interfaces["wired0"] as ap_w0, sw03.interfaces["1"] as sw03_1: ap_w0.profile = AccessVlan1() sw03_1.profile = AccessVlan1() ap_w0.cable_id = sw03_1.cable_id = f"cable_{cable_id}" cable_id += 1 # ap02.0 --- sw01.2 with ap02.interfaces["wired0"] as ap_w0, sw01.interfaces["2"] as sw_iface: ap_w0.profile = AccessVlan1() sw_iface.profile = AccessVlan1() ap_w0.cable_id = sw_iface.cable_id = f"cable_{cable_id}" cable_id += 1 # ap03.0 -- sw02.2 with ap03.interfaces["wired0"] as ap_w0, sw02.interfaces["2"] as sw_iface: ap_w0.profile = AccessVlan1() sw_iface.profile = AccessVlan1() ap_w0.cable_id = sw_iface.cable_id = f"cable_{cable_id}" cable_id += 1 # ------------------------------------------------------------------------- # Cable Switches to Appliance # ------------------------------------------------------------------------- # sw01.1 -- mx-office (not in design yet) # sw02.1 -- mx02.3 with sw02.interfaces["1"] as sw_iface, mx02.interfaces["3"] as mx_iface: mx_iface.profile = AccessVlan1() sw_iface.profile = AccessVlan1() mx_iface.cable_id = sw_iface.cable_id = f"cable_{cable_id}" cable_id += 1 # sw03.2 -- mx01.3 with sw03.interfaces["2"] as sw_iface, mx01.interfaces["3"] as mx_iface: mx_iface.profile = AccessVlan1() sw_iface.profile = AccessVlan1() mx_iface.cable_id = sw_iface.cable_id = f"cable_{cable_id}" cable_id += 1
[ "operator.itemgetter", "netcad.topology.TopologyDesignService" ]
[((1338, 1404), 'netcad.topology.TopologyDesignService', 'TopologyDesignService', ([], {'topology_name': 'design.name', 'devices': 'all_devs'}), '(topology_name=design.name, devices=all_devs)\n', (1359, 1404), False, 'from netcad.topology import TopologyDesignService\n'), ((1592, 1626), 'operator.itemgetter', 'itemgetter', (['"""sw01"""', '"""sw02"""', '"""sw03"""'], {}), "('sw01', 'sw02', 'sw03')\n", (1602, 1626), False, 'from operator import itemgetter\n'), ((1660, 1694), 'operator.itemgetter', 'itemgetter', (['"""ap01"""', '"""ap02"""', '"""ap03"""'], {}), "('ap01', 'ap02', 'ap03')\n", (1670, 1694), False, 'from operator import itemgetter\n'), ((1722, 1748), 'operator.itemgetter', 'itemgetter', (['"""mx01"""', '"""mx02"""'], {}), "('mx01', 'mx02')\n", (1732, 1748), False, 'from operator import itemgetter\n')]
import torch from torch import nn import pdb, os from shapely.geometry import * from maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist import time import matplotlib.pyplot as plt import numpy as np from scipy.signal import argrelextrema import random import string all_types = [[1,2,3,4],[1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[1,4,3,2],\ [2,1,3,4],[2,1,4,3],[2,3,1,4],[2,3,4,1],[2,4,1,3],[2,4,3,1],\ [3,1,2,4],[3,1,4,2],[3,2,1,4],[3,2,4,1],[3,4,1,2],[3,4,2,1],\ [4,1,2,3],[4,1,3,2],[4,2,1,3],[4,2,3,1],[4,3,1,2],[4,3,2,1]] class kePostProcessor(nn.Module): def __init__(self, keer=None, cfg=None): super(kePostProcessor, self).__init__() self.keer = keer self.cfg = cfg def forward(self, ft_x, ft_y, mty, boxes): ke_prob_x = ft_x ke_prob_y = ft_y mty_prob = mty boxes_per_image = [box.bbox.size(0) for box in boxes] ke_prob_x = ke_prob_x.split(boxes_per_image, dim=0) ke_prob_y = ke_prob_y.split(boxes_per_image, dim=0) mty_prob = mty_prob.split(boxes_per_image, dim=0) results = [] for prob_x, prob_y, prob_mty, box in zip(ke_prob_x, ke_prob_y, mty_prob, boxes): bbox = BoxList(box.bbox, box.size, mode='xyxy') for field in box.fields(): bbox.add_field(field, box.get_field(field)) if self.keer: prob_x, rescores_x = self.keer(prob_x, box) prob_y, rescores_y = self.keer(prob_y, box) rescores = (rescores_x+rescores_y)*0.5 if self.cfg.MODEL.ROI_KE_HEAD.RESCORING: bbox.add_field('scores', rescores) prob = torch.cat((prob_x,prob_y), dim = -2) prob = prob[..., :1] prob = textKES(prob, box.size) bbox.add_field('ke', prob) bbox.add_field('mty', prob_mty) results.append(bbox) return results # TODO remove and use only the keer import numpy as np import cv2 def scores_to_probs(scores): """Transforms CxHxW of scores to probabilities spatially.""" channels = scores.shape[0] for c in range(channels): temp = scores[c, :, :] max_score = temp.max() temp = np.exp(temp - max_score) / np.sum(np.exp(temp - max_score)) scores[c, :, :] = temp return scores def kes_decode(kes): # BDN decode for ix, i in enumerate(kes): mnd = i[0, 0] nkes = i.shape[1]-2 kes[ix][0, 1:5] = kes[ix][0, 1:5]*2 - mnd return kes def heatmaps_to_kes(maps, rois, scores, cfg): """Extract predicted ke locations from heatmaps. Output has shape (#rois, 4, #kes) with the 4 rows corresponding to (x, y, logit, prob) for each ke. """ # This function converts a discrete image coordinate in a HEATMAP_SIZE x # HEATMAP_SIZE image to a continuous ke coordinate. We maintain # consistency with kes_to_heatmap_labels by using the conversion from # Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a # continuous coordinate. offset_x = rois[:, 0] offset_y = rois[:, 1] widths = rois[:, 2] - rois[:, 0] heights = rois[:, 3] - rois[:, 1] widths = np.maximum(widths, 1) heights = np.maximum(heights, 1) widths_ceil = np.ceil(widths) heights_ceil = np.ceil(heights) resol = cfg.MODEL.ROI_KE_HEAD.RESOLUTION # cfg.mo... 56 if maps.shape[-2:] == (1, resol): xory_mode = 0 # x mode elif maps.shape[-2:] == (resol, 1): xory_mode = 1 # y mode else: assert(0), 'invalid mode.' # print("maps", maps.shape, maps[0,0], maps[0,1]) # NCHW to NHWC for use with OpenCV maps = np.transpose(maps, [0, 2, 3, 1]) min_size = 0 # cfg num_kes = int(cfg.MODEL.ROI_KE_HEAD.NUM_KES/2)+2 d_preds = np.zeros( (len(rois), 2, num_kes), dtype=np.float32) d_scores = np.zeros(scores.shape, dtype=np.float32) assert(len(rois) == maps.shape[0]), 'shape mismatch {}, {}, {}, {}'.format(str(len(rois)), \ str(rois.shape), \ str(maps.shape[0]), \ str(maps.shape)) normal = 0 innormal = 0 for i in range(len(rois)): if min_size > 0: roi_map_width = int(np.maximum(widths_ceil[i], min_size)) roi_map_height = int(np.maximum(heights_ceil[i], min_size)) else: roi_map_width = widths_ceil[i] roi_map_height = heights_ceil[i] width_correction = widths[i] / roi_map_width height_correction = heights[i] / roi_map_height np.set_printoptions(suppress=True) # print(i, "stop", maps.shape, np.around(maps[i][0, :, :], decimals=2)) if not xory_mode: roi_map = cv2.resize( maps[i], (roi_map_width, 1), interpolation=cv2.INTER_CUBIC) else: roi_map = cv2.resize( maps[i], (1, roi_map_height), interpolation=cv2.INTER_CUBIC) # print(roi_map.shape, np.around(roi_map[0, :, :], decimals=2)) # Bring back to CHW roi_map = np.transpose(roi_map, [2, 0, 1]) roi_map_probs = scores_to_probs(roi_map.copy()) # kescore visulize. map_vis = np.transpose(maps[i], [2, 0, 1]) map_vis = scores_to_probs(map_vis.copy()) sum_score = [] if cfg.MODEL.ROI_KE_HEAD.RESCORING: for k in range(num_kes): if map_vis[k].shape[0] == 1: x = np.arange(0, len(map_vis[k][0]), 1) y = map_vis[k][0] else: x = np.arange(0, len(map_vis[k][:, 0]), 1) y = map_vis[k][:, 0] top = y.max() atop = y.argmax() # lf2&1 lf2 = max(atop-2, 0) lf1 = max(atop-1, 0) rt2 = min(atop+2, 55) rt1 = min(atop+1, 55) sum_score.append(top+y[lf2]+y[lf1]+y[rt1]+y[rt2]) kes_score_mean = sum(sum_score)*1.0/len(sum_score) gama = cfg.MODEL.ROI_KE_HEAD.RESCORING_GAMA final_score = (scores[i]*(2.0-gama)+gama*kes_score_mean)*0.5 # rescore d_scores[i] = final_score else: d_scores[i] = scores[i] w = roi_map.shape[2] for k in range(num_kes): pos = roi_map[k, :, :].argmax() x_int = pos % w y_int = (pos - x_int) // w assert (roi_map_probs[k, y_int, x_int] == roi_map_probs[k, :, :].max()) x = (x_int + 0.5) * width_correction y = (y_int + 0.5) * height_correction if not xory_mode: d_preds[i, 0, k] = x + offset_x[i] d_preds[i, 1, k] = roi_map_probs[k, y_int, x_int] else: d_preds[i, 0, k] = y + offset_y[i] d_preds[i, 1, k] = roi_map_probs[k, y_int, x_int] out_kes_d = kes_decode(d_preds) return np.transpose(out_kes_d, [0, 2, 1]), d_scores from maskrcnn_benchmark.structures.bounding_box import BoxList from maskrcnn_benchmark.structures.ke import textKES class KEer(object): """ Projects a set of masks in an image on the locations specified by the bounding boxes """ def __init__(self, padding=0, cfg =None): self.padding = padding self.cfg =cfg def compute_flow_field_cpu(self, boxes): im_w, im_h = boxes.size boxes_data = boxes.bbox num_boxes = len(boxes_data) device = boxes_data.device TO_REMOVE = 1 boxes_data = boxes_data.int() box_widths = boxes_data[:, 2] - boxes_data[:, 0] + TO_REMOVE box_heights = boxes_data[:, 3] - boxes_data[:, 1] + TO_REMOVE box_widths.clamp_(min=1) box_heights.clamp_(min=1) boxes_data = boxes_data.tolist() box_widths = box_widths.tolist() box_heights = box_heights.tolist() flow_field = torch.full((num_boxes, im_h, im_w, 2), -2) # TODO maybe optimize to make it GPU-friendly with advanced indexing # or dedicated kernel for i in range(num_boxes): w = box_widths[i] h = box_heights[i] if w < 2 or h < 2: continue x = torch.linspace(-1, 1, w) y = torch.linspace(-1, 1, h) # meshogrid x = x[None, :].expand(h, w) y = y[:, None].expand(h, w) b = boxes_data[i] x_0 = max(b[0], 0) x_1 = min(b[2] + 0, im_w) y_0 = max(b[1], 0) y_1 = min(b[3] + 0, im_h) flow_field[i, y_0:y_1, x_0:x_1, 0] = x[(y_0 - b[1]):(y_1 - b[1]),(x_0 - b[0]):(x_1 - b[0])] flow_field[i, y_0:y_1, x_0:x_1, 1] = y[(y_0 - b[1]):(y_1 - b[1]),(x_0 - b[0]):(x_1 - b[0])] return flow_field.to(device) def compute_flow_field(self, boxes): return self.compute_flow_field_cpu(boxes) # TODO make it work better for batches def forward_single_image(self, masks, boxes): boxes = boxes.convert('xyxy') if self.padding: boxes = BoxList(boxes.bbox.clone(), boxes.size, boxes.mode) masks, scale = expand_masks(masks, self.padding) boxes.bbox = expand_boxes(boxes.bbox, scale) flow_field = self.compute_flow_field(boxes) result = torch.nn.functional.grid_sample(masks, flow_field) return result def to_points(self, masks): height, width = masks.shape[-2:] m = masks.view(masks.shape[:2] + (-1,)) scores, pos = m.max(-1) x_int = pos % width y_int = (pos - x_int) // width result = torch.stack([x_int.float(), y_int.float(), torch.ones_like(x_int, dtype=torch.float32)], dim=2) return result def __call__(self, masks, boxes): # TODO do this properly if isinstance(boxes, BoxList): boxes = [boxes] if isinstance(masks, list): masks = torch.stack(masks, dim=0) assert(len(masks.size()) == 4) scores = boxes[0].get_field("scores") result, rescores = heatmaps_to_kes(masks.detach().cpu().numpy(), boxes[0].bbox.cpu().numpy(), scores.cpu().numpy(), self.cfg) return torch.from_numpy(result).to(masks.device), torch.from_numpy(rescores).to(masks.device) def make_roi_ke_post_processor(cfg): if cfg.MODEL.ROI_KE_HEAD.POSTPROCESS_KES: keer = KEer(padding=0, cfg=cfg) else: keer = None ke_post_processor = kePostProcessor(keer,cfg) return ke_post_processor
[ "torch.nn.functional.grid_sample", "numpy.ceil", "torch.ones_like", "cv2.resize", "torch.full", "maskrcnn_benchmark.structures.ke.textKES", "torch.stack", "torch.from_numpy", "maskrcnn_benchmark.structures.bounding_box.BoxList", "numpy.exp", "numpy.zeros", "torch.linspace", "numpy.maximum", ...
[((3298, 3319), 'numpy.maximum', 'np.maximum', (['widths', '(1)'], {}), '(widths, 1)\n', (3308, 3319), True, 'import numpy as np\n'), ((3334, 3356), 'numpy.maximum', 'np.maximum', (['heights', '(1)'], {}), '(heights, 1)\n', (3344, 3356), True, 'import numpy as np\n'), ((3375, 3390), 'numpy.ceil', 'np.ceil', (['widths'], {}), '(widths)\n', (3382, 3390), True, 'import numpy as np\n'), ((3410, 3426), 'numpy.ceil', 'np.ceil', (['heights'], {}), '(heights)\n', (3417, 3426), True, 'import numpy as np\n'), ((3784, 3816), 'numpy.transpose', 'np.transpose', (['maps', '[0, 2, 3, 1]'], {}), '(maps, [0, 2, 3, 1])\n', (3796, 3816), True, 'import numpy as np\n'), ((3983, 4023), 'numpy.zeros', 'np.zeros', (['scores.shape'], {'dtype': 'np.float32'}), '(scores.shape, dtype=np.float32)\n', (3991, 4023), True, 'import numpy as np\n'), ((4904, 4938), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'suppress': '(True)'}), '(suppress=True)\n', (4923, 4938), True, 'import numpy as np\n'), ((5400, 5432), 'numpy.transpose', 'np.transpose', (['roi_map', '[2, 0, 1]'], {}), '(roi_map, [2, 0, 1])\n', (5412, 5432), True, 'import numpy as np\n'), ((5544, 5576), 'numpy.transpose', 'np.transpose', (['maps[i]', '[2, 0, 1]'], {}), '(maps[i], [2, 0, 1])\n', (5556, 5576), True, 'import numpy as np\n'), ((7349, 7383), 'numpy.transpose', 'np.transpose', (['out_kes_d', '[0, 2, 1]'], {}), '(out_kes_d, [0, 2, 1])\n', (7361, 7383), True, 'import numpy as np\n'), ((8336, 8378), 'torch.full', 'torch.full', (['(num_boxes, im_h, im_w, 2)', '(-2)'], {}), '((num_boxes, im_h, im_w, 2), -2)\n', (8346, 8378), False, 'import torch\n'), ((9749, 9799), 'torch.nn.functional.grid_sample', 'torch.nn.functional.grid_sample', (['masks', 'flow_field'], {}), '(masks, flow_field)\n', (9780, 9799), False, 'import torch\n'), ((1268, 1308), 'maskrcnn_benchmark.structures.bounding_box.BoxList', 'BoxList', (['box.bbox', 'box.size'], {'mode': '"""xyxy"""'}), "(box.bbox, box.size, mode='xyxy')\n", (1275, 1308), False, 'from maskrcnn_benchmark.structures.bounding_box import BoxList\n'), ((1764, 1799), 'torch.cat', 'torch.cat', (['(prob_x, prob_y)'], {'dim': '(-2)'}), '((prob_x, prob_y), dim=-2)\n', (1773, 1799), False, 'import torch\n'), ((1853, 1876), 'maskrcnn_benchmark.structures.ke.textKES', 'textKES', (['prob', 'box.size'], {}), '(prob, box.size)\n', (1860, 1876), False, 'from maskrcnn_benchmark.structures.ke import textKES\n'), ((2318, 2342), 'numpy.exp', 'np.exp', (['(temp - max_score)'], {}), '(temp - max_score)\n', (2324, 2342), True, 'import numpy as np\n'), ((5068, 5138), 'cv2.resize', 'cv2.resize', (['maps[i]', '(roi_map_width, 1)'], {'interpolation': 'cv2.INTER_CUBIC'}), '(maps[i], (roi_map_width, 1), interpolation=cv2.INTER_CUBIC)\n', (5078, 5138), False, 'import cv2\n'), ((5192, 5263), 'cv2.resize', 'cv2.resize', (['maps[i]', '(1, roi_map_height)'], {'interpolation': 'cv2.INTER_CUBIC'}), '(maps[i], (1, roi_map_height), interpolation=cv2.INTER_CUBIC)\n', (5202, 5263), False, 'import cv2\n'), ((8655, 8679), 'torch.linspace', 'torch.linspace', (['(-1)', '(1)', 'w'], {}), '(-1, 1, w)\n', (8669, 8679), False, 'import torch\n'), ((8696, 8720), 'torch.linspace', 'torch.linspace', (['(-1)', '(1)', 'h'], {}), '(-1, 1, h)\n', (8710, 8720), False, 'import torch\n'), ((10374, 10399), 'torch.stack', 'torch.stack', (['masks'], {'dim': '(0)'}), '(masks, dim=0)\n', (10385, 10399), False, 'import torch\n'), ((2352, 2376), 'numpy.exp', 'np.exp', (['(temp - max_score)'], {}), '(temp - max_score)\n', (2358, 2376), True, 'import numpy as np\n'), ((4574, 4610), 'numpy.maximum', 'np.maximum', (['widths_ceil[i]', 'min_size'], {}), '(widths_ceil[i], min_size)\n', (4584, 4610), True, 'import numpy as np\n'), ((4645, 4682), 'numpy.maximum', 'np.maximum', (['heights_ceil[i]', 'min_size'], {}), '(heights_ceil[i], min_size)\n', (4655, 4682), True, 'import numpy as np\n'), ((10104, 10147), 'torch.ones_like', 'torch.ones_like', (['x_int'], {'dtype': 'torch.float32'}), '(x_int, dtype=torch.float32)\n', (10119, 10147), False, 'import torch\n'), ((10640, 10664), 'torch.from_numpy', 'torch.from_numpy', (['result'], {}), '(result)\n', (10656, 10664), False, 'import torch\n'), ((10683, 10709), 'torch.from_numpy', 'torch.from_numpy', (['rescores'], {}), '(rescores)\n', (10699, 10709), False, 'import torch\n')]
import streamlit as st import numpy as np import matplotlib.pyplot as plt perc_heads = st.number_input(label='Chance of Coins Landing on Heads', min_value=0.0, max_value=1.0, value=.5) graph_title = st.text_input(label='Graph Title') binom_dist = np.random.binomial(1, perc_heads, 1000) list_of_means = [] for i in range(0, 1000): list_of_means.append(np.random.choice(binom_dist, 100, replace=True).mean()) fig, ax = plt.subplots() plt.hist(list_of_means, range=[0,1]) plt.title(graph_title) st.pyplot(fig)
[ "matplotlib.pyplot.hist", "streamlit.pyplot", "streamlit.number_input", "numpy.random.choice", "matplotlib.pyplot.title", "streamlit.text_input", "matplotlib.pyplot.subplots", "numpy.random.binomial" ]
[((98, 200), 'streamlit.number_input', 'st.number_input', ([], {'label': '"""Chance of Coins Landing on Heads"""', 'min_value': '(0.0)', 'max_value': '(1.0)', 'value': '(0.5)'}), "(label='Chance of Coins Landing on Heads', min_value=0.0,\n max_value=1.0, value=0.5)\n", (113, 200), True, 'import streamlit as st\n'), ((214, 248), 'streamlit.text_input', 'st.text_input', ([], {'label': '"""Graph Title"""'}), "(label='Graph Title')\n", (227, 248), True, 'import streamlit as st\n'), ((263, 302), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'perc_heads', '(1000)'], {}), '(1, perc_heads, 1000)\n', (281, 302), True, 'import numpy as np\n'), ((451, 465), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (463, 465), True, 'import matplotlib.pyplot as plt\n'), ((468, 505), 'matplotlib.pyplot.hist', 'plt.hist', (['list_of_means'], {'range': '[0, 1]'}), '(list_of_means, range=[0, 1])\n', (476, 505), True, 'import matplotlib.pyplot as plt\n'), ((506, 528), 'matplotlib.pyplot.title', 'plt.title', (['graph_title'], {}), '(graph_title)\n', (515, 528), True, 'import matplotlib.pyplot as plt\n'), ((530, 544), 'streamlit.pyplot', 'st.pyplot', (['fig'], {}), '(fig)\n', (539, 544), True, 'import streamlit as st\n'), ((378, 425), 'numpy.random.choice', 'np.random.choice', (['binom_dist', '(100)'], {'replace': '(True)'}), '(binom_dist, 100, replace=True)\n', (394, 425), True, 'import numpy as np\n')]
import sys import emailprotectionslib.dmarc as dmarc from MaltegoTransform import * mt = MaltegoTransform() mt.parseArguments(sys.argv) domain = mt.getValue() mt = MaltegoTransform() try: dmarc_record = dmarc.DmarcRecord.from_domain(domain) #print spf_record mt.addEntity("maltego.Phrase","DMARC Record: "+str(dmarc_record)) except: mt.addUIMessage("Exception Occured",messageType="PartialError") mt.returnOutput()
[ "emailprotectionslib.dmarc.DmarcRecord.from_domain" ]
[((210, 247), 'emailprotectionslib.dmarc.DmarcRecord.from_domain', 'dmarc.DmarcRecord.from_domain', (['domain'], {}), '(domain)\n', (239, 247), True, 'import emailprotectionslib.dmarc as dmarc\n')]
# -*- coding: utf-8 -*- """ idfy_rest_client.models.update_signer_request_wrapper This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io ) """ from idfy_rest_client.api_helper import APIHelper import idfy_rest_client.models.redirect_settings import idfy_rest_client.models.signer_info import idfy_rest_client.models.extra_info_signer_request import idfy_rest_client.models.ui import idfy_rest_client.models.notifications class UpdateSignerRequestWrapper(object): """Implementation of the 'UpdateSignerRequestWrapper' model. TODO: type model description here. Attributes: redirect_settings (RedirectSettings): Return urls and domain settings signer_info (SignerInfo): Define the signers name, mobile and email if you are using notifications extra_info (ExtraInfoSignerRequest): Coming soon: Do you want to collect extra info about this specific signer? (for example personal information) ui (UI): Here you can set language, styling and create dialogs the signer have to read before/after the signing notifications (Notifications): Enable / setup email/sms notifications for this specific signer tags (list of string): Signer tags order (int): You can define a specific sign order /queue for the signers if you want to. required (bool): If some of the signers are marked as required, the other signers are not allowed to sign before the required ones have signed the document sign_url_expires (datetime): How long before the signers url should expire? (ISO 8601). This can be set if you only want a limited time to live for each sign url (If you generate a new url at a later time this will also have this limited lifetime). Defaults to the document lifetime. """ # Create a mapping from Model property names to API property names _names = { "redirect_settings":'redirectSettings', "signer_info":'signerInfo', "extra_info":'extraInfo', "ui":'ui', "notifications":'notifications', "tags":'tags', "order":'order', "required":'required', "sign_url_expires":'signUrlExpires' } def __init__(self, redirect_settings=None, signer_info=None, extra_info=None, ui=None, notifications=None, tags=None, order=None, required=None, sign_url_expires=None, additional_properties = {}): """Constructor for the UpdateSignerRequestWrapper class""" # Initialize members of the class self.redirect_settings = redirect_settings self.signer_info = signer_info self.extra_info = extra_info self.ui = ui self.notifications = notifications self.tags = tags self.order = order self.required = required self.sign_url_expires = APIHelper.RFC3339DateTime(sign_url_expires) if sign_url_expires else None # Add additional model properties to the instance self.additional_properties = additional_properties @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary redirect_settings = idfy_rest_client.models.redirect_settings.RedirectSettings.from_dictionary(dictionary.get('redirectSettings')) if dictionary.get('redirectSettings') else None signer_info = idfy_rest_client.models.signer_info.SignerInfo.from_dictionary(dictionary.get('signerInfo')) if dictionary.get('signerInfo') else None extra_info = idfy_rest_client.models.extra_info_signer_request.ExtraInfoSignerRequest.from_dictionary(dictionary.get('extraInfo')) if dictionary.get('extraInfo') else None ui = idfy_rest_client.models.ui.UI.from_dictionary(dictionary.get('ui')) if dictionary.get('ui') else None notifications = idfy_rest_client.models.notifications.Notifications.from_dictionary(dictionary.get('notifications')) if dictionary.get('notifications') else None tags = dictionary.get('tags') order = dictionary.get('order') required = dictionary.get('required') sign_url_expires = APIHelper.RFC3339DateTime.from_value(dictionary.get("signUrlExpires")).datetime if dictionary.get("signUrlExpires") else None # Clean out expected properties from dictionary for key in cls._names.values(): if key in dictionary: del dictionary[key] # Return an object of this model return cls(redirect_settings, signer_info, extra_info, ui, notifications, tags, order, required, sign_url_expires, dictionary)
[ "idfy_rest_client.api_helper.APIHelper.RFC3339DateTime" ]
[((3204, 3247), 'idfy_rest_client.api_helper.APIHelper.RFC3339DateTime', 'APIHelper.RFC3339DateTime', (['sign_url_expires'], {}), '(sign_url_expires)\n', (3229, 3247), False, 'from idfy_rest_client.api_helper import APIHelper\n')]
import os def obtenNombreArchivos(ruta): archivos = list() with os.scandir(ruta) as ficheros: for fichero in ficheros: archivos.append(fichero.name) return archivos def concatenaRegistros(ruta,nombreArchivo): registroConcatenado = list() with open(ruta,'r') as lecturaArchivo: for registro in lecturaArchivo: registroConcatenado.append(registro.rstrip('\n')+nombreArchivo) return(registroConcatenado) def guardaConcatenado(ruta,resultado): ArchivoResultado = open(ruta,'a') for registro in resultado: if registro is not None: ArchivoResultado.write(str(registro)+ '\n' ) # print(str(registro)+ '\n') ArchivoResultado.close()
[ "os.scandir" ]
[((73, 89), 'os.scandir', 'os.scandir', (['ruta'], {}), '(ruta)\n', (83, 89), False, 'import os\n')]
import os import requests import time import json import io import numpy as np import pandas as pd import paavo_queries as paavo_queries from sklearn.linear_model import LinearRegression import statsmodels.api as sm ## NOTE: Table 9_koko access is forbidden from the API for some reasons. # url to the API MAIN_PAAVO_URL = 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/' def paavo_url(level, table): """Helper to make url to the paavo API""" return MAIN_PAAVO_URL + str(level) + '/' + table def fetch_csv(url, destination_directory, file_name, query={"query": [], "response": {"format": "csv"}}): """Fetch a single file from PXweb API. File name should end with '.csv'""" response = requests.post(url, json=query, stream=True, allow_redirects=True) if not os.path.exists(destination_directory): os.makedirs(destination_directory) destination_file = os.path.join(destination_directory, file_name) if response.status_code == 200: open(destination_file, 'wb').write(response.content) print('Downloaded ' + file_name + ' from ' + url) else: print('Could not download ' + file_name + ' from ' + url) print('HTTP/1.1 ' + str(response.status_code)) time.sleep(1) def fetch_paavo(destination_directory): """Fetch the whole Paavo directory""" # Getting levels from Paavo database levels = [] response = requests.post('http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/') response_texts = json.loads(response.text) for response_text in response_texts: levels.append(str(response_text['id'])) paavo_directory = os.path.join(destination_directory, 'paavo_raw') for level in levels: response = requests.post('http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/' + str(level)) response_texts = json.loads(response.text) table_data = {} for response_text in response_texts: table_data[response_text['id']] = str(response_text['text']).split('. ')[-1].replace("'", "").replace(" ", "_") for (id, name) in table_data.items(): url = paavo_url(level, id) file_name = name + '.csv' fetch_csv(url, paavo_directory, file_name) def fetch_dataframe(url, query={"query": [], "response": {"format": "csv"}}): """Download a table from PXweb API to a DataFrame""" response = requests.post(url, json=query, stream=True, allow_redirects=True) if response.status_code == 200: byte_data = io.BytesIO(response.content) df = pd.read_csv(byte_data, sep=',', encoding='iso-8859-1') print('Downloaded data from ' + url) return df else: print('Could not download from ' + url) print('HTTP/1.1 ' + str(response.status_code)) return pd.DataFrame() time.sleep(0.2) def paavo_data(): """Download the whole paavo directory to a dictionary with names as keys and dataframes as values""" data = {} # Getting levels from paavo database levels = [] response = requests.post('http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/') response_texts = json.loads(response.text) for response_text in response_texts: levels.append(str(response_text['id'])) for level in levels: response = requests.post( 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/' + str(level)) response_texts = json.loads(response.text) table_data = {} for response_text in response_texts: table_data[response_text['id']] = str(response_text['text']).split('. ')[-1].replace("'", "").replace(" ", "_") for (id, name) in table_data.items(): url = paavo_url(level, id) df = fetch_dataframe(url) if not df.empty: data[name] = df time.sleep(1) return data def fetch_paavo_density_and_area(density_file_destination, area_file_destination): def clean_df(df): # Drop Finland row df.drop(index=0, inplace=True) # Extract postal code df.rename(columns={df.columns[0]: 'Postal code'}, inplace=True) df['Postal code'] = df['Postal code'].apply(lambda x: x.split(' ')[0]) # Replace '.' with 0 and set Postal code as index df.replace({'.': 0}, inplace=True) df.set_index('Postal code', inplace=True) # Change data type of all columns to integer for column in df.columns: df[column] = df[column].astype(int) return df url_2013 = 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2015/paavo_9_koko_2015.px/' url_2014 = 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2016/paavo_9_koko_2016.px/' url_2015 = 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2017/paavo_9_koko_2017.px/' url_2016 = 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2018/paavo_9_koko_2018.px/' url_2017 = 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/2019/paavo_9_koko_2019.px/' dfs = {} years = np.array([[2014], [2015], [2016], [2017]]) # Download and clean each dataframe dfs[2013] = clean_df(fetch_dataframe(url_2013, paavo_queries.surface_population_query)) dfs[2014] = clean_df(fetch_dataframe(url_2014, paavo_queries.surface_population_query)) dfs[2015] = clean_df(fetch_dataframe(url_2015, paavo_queries.surface_population_query)) dfs[2016] = clean_df(fetch_dataframe(url_2016, paavo_queries.surface_population_query)) dfs[2017] = clean_df(fetch_dataframe(url_2017, paavo_queries.surface_population_query)) # Change column labels for (year, df) in dfs.items(): pop_str = 'Population (' + str(year) +')' area_str = 'Surface area (' + str(year) + ')' density_str = 'Density (' + str(year) +')' if year > 2013: df.rename(columns={df.columns[0]: area_str, df.columns[1]: pop_str}, inplace=True) df.insert(2, density_str, df[pop_str] / df[area_str]) df.replace({0.0: np.nan}) else: df.rename(columns={df.columns[0]: pop_str}, inplace=True) df.replace({0.0: np.nan}) # Merge dataframe using Postal code index, manually adding density and surface area columns for 2013 main_table = dfs[2014] main_table = main_table.merge(dfs[2013], how='left', on='Postal code') main_table = main_table.merge(dfs[2015], how='left', on='Postal code') main_table = main_table.merge(dfs[2016], how='left', on='Postal code') main_table = main_table.merge(dfs[2017], how='left', on='Postal code') main_table.insert(0, 'Density (2013)', np.nan) main_table.insert(0, 'Surface area (2013)', np.nan) densities = main_table[['Density (2014)', 'Density (2015)', 'Density (2016)', 'Density (2017)']] # Linear regression on density. If density is negative, drop the latest density and retry. If there is only 1 usable density, copy it to the 2013 density for index, row in densities.iterrows(): y = row.to_numpy() valid_index = np.where(y >= 0) valid_years = years[valid_index] y = y[valid_index] density_prediction = -1.0 while len(y) > 1 and density_prediction < 0: reg = LinearRegression().fit(valid_years, y) density_prediction = reg.predict([[2013]]) if density_prediction < 0: y = y[:-1] valid_years = valid_years[:-1] if len(y) > 1: main_table.at[index, 'Density (2013)'] = density_prediction elif len(y) ==1: main_table.at[index, 'Density (2013)'] = y[0] else: continue # Calculate surface area using density and population for index, row in main_table.iterrows(): if row['Population (2013)'] == np.nan: continue elif row['Population (2013)'] > 0 and row['Density (2013)'] > 0: main_table.at[index, 'Surface area (2013)'] = round(row['Population (2013)']/row['Density (2013)']) elif row['Population (2013)'] == 0 and row['Density (2013)'] == 0: main_table.at[index, 'Surface area (2013)'] = row['Surface area (2014)'] main_table = main_table.fillna(0) # Results densities = main_table[['Density (2013)', 'Density (2014)', 'Density (2015)', 'Density (2016)', 'Density (2017)']] areas = main_table[['Surface area (2013)', 'Surface area (2014)', 'Surface area (2015)', 'Surface area (2016)', 'Surface area (2017)']] # Export to tsv files densities.to_csv(density_file_destination, sep='\t') areas.to_csv(area_file_destination, sep='\t') def fetch_paavo_housing(destination_directory, postal_code_file, density_file): def postal_standardize(df): df= df.astype({'Postal code': str}) for i in list(df.index): df.at[i, 'Postal code'] = '0' * (5-len(df.at[i,'Postal code']))+ df.at[i, 'Postal code'] return df def postal_merge(left, right): return left.merge(right, how='left', on='Postal code') def get_mean_simple(df, n): """Calculate housing prices for groups of postal codes with the same first 6-n digits""" df_n = pd.DataFrame(df['Postal code'].apply(lambda x: x[:(1 - n)])) df_n.rename(columns={df_n.columns[0]: 'Postal code'}, inplace=True) df_n = df_n.join(df[['Total value', 'Number']].copy()) df_n = df_n.groupby("Postal code", as_index=False).agg("sum") df_n['Mean'] = df_n['Total value'] / df_n['Number'] df_n.drop(['Total value', 'Number'], axis=1, inplace=True) # df_n.set_index('Postal code', inplace=True) return df_n def impute_simple(df, df_n): """Impute using the results above""" df_ni = df_n.set_index('Postal code') for code in list(df_n['Postal code']): df_rows = np.array(df[df['Postal code'].str.startswith(code)].index) for i in df_rows: if df.at[i, 'Mean'] == 0 or np.isnan(df.at[i, 'Mean']): df.at[i, 'Mean'] = df_ni.at[code, 'Mean'] return df def impute_with_density(df, postal_df): """Impute with respect to density using a linear model""" def postal_truncate(n): df_n = postal_df.copy() df_n['Postal code'] = df_n['Postal code'].apply(lambda x: x[:(1-n)]) df_n.drop_duplicates(subset='Postal code', inplace=True) return df_n def impute_price(df_, n): truncated_postal = postal_truncate(n) for code in truncated_postal['Postal code']: sub_df = df_[df_['Postal code'].str.startswith(code)] good_df = sub_df[sub_df['Mean'] != 0] bad_df = sub_df[sub_df['Mean'] == 0] if len(good_df.index) >= 7: good_df = good_df.nsmallest(15, 'Mean') X = good_df['Density'] y = good_df['Mean'] X = sm.add_constant(X.values) model = sm.OLS(y, X).fit() for i in bad_df.index: if df_.at[i, 'Mean'] <= 0 or np.isnan(df_.at[i, 'Mean']): df_.at[i, 'Mean'] = int(model.predict([1, df_.at[i, 'Density']])[0]) return df_ for i in range(3,6): df = impute_price(df, i) return df main_table = postal_standardize(pd.read_csv(postal_code_file, sep='\t')) density = postal_standardize(pd.read_csv(density_file, sep='\t')) density = density.fillna(0) postal_code = main_table.copy() year_list = list(range(2005, 2018)) base_query = paavo_queries.ts_housing_query['query'] for year in year_list: for quarter in range(5): # Construct the json query new_query = [{"code": "Vuosi", "selection": {"filter": "item", "values": [str(year)]}}, {"code": "Neljännes", "selection": {"filter": "item", "values": [str(quarter)]}}] + base_query quarter_query = {"query": new_query, "response": {"format": "csv"}} if quarter == 0: mean_label = 'Housing price (' + str(year) + ')' else: mean_label = str(year) + 'Q' +str(quarter) # Get the data table for the quarter quarter_frame = postal_standardize(fetch_dataframe(paavo_queries.housing_url, query= quarter_query)) # Leave only Postal code and house price quarter_frame = quarter_frame[['Postal code', 'Mean', 'Number']] # Replace missing value '.' with '0' quarter_frame.replace({'.': '0'}, inplace=True) # Change mean to housing price and convert to float, number to Int quarter_frame['Mean'] = quarter_frame['Mean'].astype(int) quarter_frame['Number'] = quarter_frame['Number'].astype(int) # Calculate the total housing value for each row quarter_frame['Total value'] = quarter_frame['Mean'] * quarter_frame['Number'] # Get the complete postal code quarter_frame = postal_merge(postal_code, quarter_frame) # Change the numbers of houses where the prices are hidden to 0 so that the calculation of the group mean is not affected for code in list(quarter_frame.index): if quarter_frame.at[code, 'Mean'] == 0 or np.isnan(quarter_frame.at[code, 'Mean']): quarter_frame.at[code, 'Number'] = 0 if year < 2013: # Calculating the average housing price of postal codes with the same first 3, 2, 1 digits quarter_frame_3 = get_mean_simple(quarter_frame, 3) quarter_frame_4 = get_mean_simple(quarter_frame, 4) quarter_frame_5 = get_mean_simple(quarter_frame, 5) # Fill df_4 empty values with that of df_5 and df_3 with that of df_4 quarter_frame_4 = impute_simple(quarter_frame_4, quarter_frame_5) quarter_frame_3 = impute_simple(quarter_frame_3, quarter_frame_4) # Round mean values and fill empty cells with zero, though there should not be any at this point quarter_frame_3.fillna(0, inplace=True) quarter_frame_3['Mean'] = quarter_frame_3['Mean'].astype(int) # Fill the year frame with mean postal code values quarter_frame = impute_simple(quarter_frame, quarter_frame_3) else: # Extract density values of the year year_density = density[['Postal code', 'Density (' + str(year) + ')']] year_density = postal_standardize(year_density) year_density.rename(columns={('Density (' + str(year) + ')'): 'Density'}, inplace=True) quarter_frame = postal_merge(quarter_frame, year_density) quarter_frame = quarter_frame.astype({'Density': float}) quarter_frame = quarter_frame.fillna(0) # Imputing using density quarter_frame = impute_with_density(quarter_frame, postal_code) quarter_frame = quarter_frame.fillna(0) # Drop unnecessary columns, set Postal code as index, rename mean by year specific label quarter_frame = quarter_frame[['Postal code','Mean']] #print(quarter_frame[quarter_frame['Mean'] <= 0].count()) quarter_frame.rename(columns={'Mean': mean_label}, inplace=True) # Combine the data from the year table into the main table main_table = postal_merge(main_table, quarter_frame) print('Year ' + str(year) + ', quarter ' + str(quarter) + ': Done') # Construct yearly and quarterly tables quarter_columns = main_table.columns[main_table.columns.str.contains('Q')] year_columns = main_table.columns[main_table.columns.str.contains('Housing')] main_table.set_index('Postal code', inplace=True) year_table = main_table[year_columns] quarter_table = main_table[quarter_columns] # Save yearly and quarterly tables to files year_table.to_csv(os.path.join(destination_directory, 'paavo_housing_data_yearly.tsv'), sep='\t') quarter_table.to_csv(os.path.join(destination_directory, 'paavo_housing_data_quarterly.tsv'), sep='\t')
[ "os.path.exists", "json.loads", "requests.post", "os.makedirs", "pandas.read_csv", "numpy.where", "os.path.join", "io.BytesIO", "time.sleep", "numpy.array", "statsmodels.api.add_constant", "numpy.isnan", "pandas.DataFrame", "statsmodels.api.OLS", "sklearn.linear_model.LinearRegression" ]
[((758, 823), 'requests.post', 'requests.post', (['url'], {'json': 'query', 'stream': '(True)', 'allow_redirects': '(True)'}), '(url, json=query, stream=True, allow_redirects=True)\n', (771, 823), False, 'import requests\n'), ((947, 993), 'os.path.join', 'os.path.join', (['destination_directory', 'file_name'], {}), '(destination_directory, file_name)\n', (959, 993), False, 'import os\n'), ((1295, 1308), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1305, 1308), False, 'import time\n'), ((1474, 1575), 'requests.post', 'requests.post', (['"""http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/"""'], {}), "(\n 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/'\n )\n", (1487, 1575), False, 'import requests\n'), ((1588, 1613), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (1598, 1613), False, 'import json\n'), ((1732, 1780), 'os.path.join', 'os.path.join', (['destination_directory', '"""paavo_raw"""'], {}), "(destination_directory, 'paavo_raw')\n", (1744, 1780), False, 'import os\n'), ((2525, 2590), 'requests.post', 'requests.post', (['url'], {'json': 'query', 'stream': '(True)', 'allow_redirects': '(True)'}), '(url, json=query, stream=True, allow_redirects=True)\n', (2538, 2590), False, 'import requests\n'), ((2968, 2983), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (2978, 2983), False, 'import time\n'), ((3203, 3304), 'requests.post', 'requests.post', (['"""http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/"""'], {}), "(\n 'http://pxnet2.stat.fi/PXWeb/api/v1/en/Postinumeroalueittainen_avoin_tieto/'\n )\n", (3216, 3304), False, 'import requests\n'), ((3317, 3342), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (3327, 3342), False, 'import json\n'), ((5403, 5445), 'numpy.array', 'np.array', (['[[2014], [2015], [2016], [2017]]'], {}), '([[2014], [2015], [2016], [2017]])\n', (5411, 5445), True, 'import numpy as np\n'), ((838, 875), 'os.path.exists', 'os.path.exists', (['destination_directory'], {}), '(destination_directory)\n', (852, 875), False, 'import os\n'), ((886, 920), 'os.makedirs', 'os.makedirs', (['destination_directory'], {}), '(destination_directory)\n', (897, 920), False, 'import os\n'), ((1960, 1985), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (1970, 1985), False, 'import json\n'), ((2651, 2679), 'io.BytesIO', 'io.BytesIO', (['response.content'], {}), '(response.content)\n', (2661, 2679), False, 'import io\n'), ((2694, 2748), 'pandas.read_csv', 'pd.read_csv', (['byte_data'], {'sep': '""","""', 'encoding': '"""iso-8859-1"""'}), "(byte_data, sep=',', encoding='iso-8859-1')\n", (2705, 2748), True, 'import pandas as pd\n'), ((2946, 2960), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2958, 2960), True, 'import pandas as pd\n'), ((3629, 3654), 'json.loads', 'json.loads', (['response.text'], {}), '(response.text)\n', (3639, 3654), False, 'import json\n'), ((7440, 7456), 'numpy.where', 'np.where', (['(y >= 0)'], {}), '(y >= 0)\n', (7448, 7456), True, 'import numpy as np\n'), ((11902, 11941), 'pandas.read_csv', 'pd.read_csv', (['postal_code_file'], {'sep': '"""\t"""'}), "(postal_code_file, sep='\\t')\n", (11913, 11941), True, 'import pandas as pd\n'), ((11977, 12012), 'pandas.read_csv', 'pd.read_csv', (['density_file'], {'sep': '"""\t"""'}), "(density_file, sep='\\t')\n", (11988, 12012), True, 'import pandas as pd\n'), ((16702, 16770), 'os.path.join', 'os.path.join', (['destination_directory', '"""paavo_housing_data_yearly.tsv"""'], {}), "(destination_directory, 'paavo_housing_data_yearly.tsv')\n", (16714, 16770), False, 'import os\n'), ((16808, 16879), 'os.path.join', 'os.path.join', (['destination_directory', '"""paavo_housing_data_quarterly.tsv"""'], {}), "(destination_directory, 'paavo_housing_data_quarterly.tsv')\n", (16820, 16879), False, 'import os\n'), ((4061, 4074), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (4071, 4074), False, 'import time\n'), ((7635, 7653), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (7651, 7653), False, 'from sklearn.linear_model import LinearRegression\n'), ((10430, 10456), 'numpy.isnan', 'np.isnan', (["df.at[i, 'Mean']"], {}), "(df.at[i, 'Mean'])\n", (10438, 10456), True, 'import numpy as np\n'), ((11445, 11470), 'statsmodels.api.add_constant', 'sm.add_constant', (['X.values'], {}), '(X.values)\n', (11460, 11470), True, 'import statsmodels.api as sm\n'), ((13903, 13943), 'numpy.isnan', 'np.isnan', (["quarter_frame.at[code, 'Mean']"], {}), "(quarter_frame.at[code, 'Mean'])\n", (13911, 13943), True, 'import numpy as np\n'), ((11502, 11514), 'statsmodels.api.OLS', 'sm.OLS', (['y', 'X'], {}), '(y, X)\n', (11508, 11514), True, 'import statsmodels.api as sm\n'), ((11619, 11646), 'numpy.isnan', 'np.isnan', (["df_.at[i, 'Mean']"], {}), "(df_.at[i, 'Mean'])\n", (11627, 11646), True, 'import numpy as np\n')]
from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import OrdinalEncoder, StandardScaler, OneHotEncoder from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split, GridSearchCV import numpy as np import pandas as pd scaler = StandardScaler(copy=False, with_mean=False, with_std=True) class FeatureGenerator(): def __init__(self, feature_config, random_seed=None): self.feature_config = feature_config if random_seed is not None: self.seed = random_seed self.one_hot_dict = {} def process_x_data(self, df, train_or_test): print('\t\tFeaturizing %s df of size %s'%(train_or_test, df.shape)) for task in self.feature_config: for task_type, target_list in task.items(): if task_type == 'categoricals': for col in target_list: col_name = col['column'] df = self.impute_na(df, col_name, col['imputation'], 'categorical') df = self.process_one_hot(df, col_name, train_or_test) elif task_type == 'numeric': df = self.process_num(target_list, df) elif task_type == 'binary': df = self.process_binary(target_list, df) elif task_type == 'drop': df.drop(target_list, axis=1, inplace=True) print('\t\tCompleted featurization of %s df with size %s'%(train_or_test,df.shape)) return df def process_one_hot(self, df, col_name, train_or_test): reshaped = self.reshape_series(df[col_name]) if train_or_test == 'train': encoder = OneHotEncoder(handle_unknown='ignore').fit(reshaped) raw_names = encoder.categories_ col_names = ['%s_%s'%(col_name, x) for x in raw_names[0]] e_props = { 'encoder': encoder, 'col_names': col_names } self.one_hot_dict[col_name] = e_props else: col_encoder_dict = self.one_hot_dict[col_name] encoder = col_encoder_dict['encoder'] col_names = col_encoder_dict['col_names'] labels = encoder.transform(reshaped) new = df.join(pd.DataFrame(labels.todense(), columns=col_names)) new.drop(col_name, axis=1,inplace=True) return new def featurize(self, data_dict): print('\tBeginning featurization') trn_cols, trn_data, test_cols, test_data = tuple(data_dict.values()) train_df = pd.DataFrame(trn_data, columns=trn_cols) train_y = train_df['result'] train_x = train_df.drop('result', axis=1) featurized_trn_X = self.process_x_data(train_x, 'train') test_df = pd.DataFrame(test_data, columns=test_cols) test_y = test_df['result'] test_x = test_df.drop('result', axis=1) featurized_test_X = self.process_x_data(test_x, 'test') print('\tCompleted featurization') return (featurized_trn_X, train_y, featurized_test_X, test_y) def process_binary(self, target_list, df): for col in target_list: col_name = col['column'] df = self.impute_na(df, col_name, col['imputation'], 'binary') return df def process_num(self, target_list, df): for col in target_list: col_name = col['column'] impute_dict = col['imputation'] scale_after = col['scale'] df[col_name] = pd.to_numeric(df[col_name], errors='coerce') df = self.impute_na(df, col_name, impute_dict, 'numeric') if scale_after == True: self.scale_numeric_col(df, col_name) return df def scale_numeric_col(self, df, col_name): reshaped = self.reshape_series(df[col_name]) scaler.fit(reshaped) df[col_name] = scaler.transform(reshaped) return df def reshape_series(self, series): arr = np.array(series) return arr.reshape((arr.shape[0], 1)) def impute_na(self, df, col_name, config, f_type): series = df[col_name] missing = df[series.isna()].shape[0] if missing > 0: if f_type == 'categorical': df[col_name] = df[col_name].fillna(config['fill_value']) elif f_type == 'numeric' or f_type == 'binary': val_flag = np.nan if 'missing_values' in config: val_flag = config['missing_values'] if config['strategy'] == 'constant' and 'fill_value' in config: imp_mean = SimpleImputer(missing_values=val_flag, strategy=config['strategy'], fill_value=config['fill_value']) else: imp_mean = SimpleImputer(missing_values=val_flag, strategy=config['strategy']) reshaped = self.reshape_series(series) imp_mean.fit(reshaped) df[col_name] = imp_mean.transform(reshaped) return df
[ "sklearn.preprocessing.OneHotEncoder", "sklearn.preprocessing.StandardScaler", "numpy.array", "pandas.to_numeric", "sklearn.impute.SimpleImputer", "pandas.DataFrame" ]
[((373, 431), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {'copy': '(False)', 'with_mean': '(False)', 'with_std': '(True)'}), '(copy=False, with_mean=False, with_std=True)\n', (387, 431), False, 'from sklearn.preprocessing import OrdinalEncoder, StandardScaler, OneHotEncoder\n'), ((2839, 2879), 'pandas.DataFrame', 'pd.DataFrame', (['trn_data'], {'columns': 'trn_cols'}), '(trn_data, columns=trn_cols)\n', (2851, 2879), True, 'import pandas as pd\n'), ((3050, 3092), 'pandas.DataFrame', 'pd.DataFrame', (['test_data'], {'columns': 'test_cols'}), '(test_data, columns=test_cols)\n', (3062, 3092), True, 'import pandas as pd\n'), ((4266, 4282), 'numpy.array', 'np.array', (['series'], {}), '(series)\n', (4274, 4282), True, 'import numpy as np\n'), ((3790, 3834), 'pandas.to_numeric', 'pd.to_numeric', (['df[col_name]'], {'errors': '"""coerce"""'}), "(df[col_name], errors='coerce')\n", (3803, 3834), True, 'import pandas as pd\n'), ((1940, 1978), 'sklearn.preprocessing.OneHotEncoder', 'OneHotEncoder', ([], {'handle_unknown': '"""ignore"""'}), "(handle_unknown='ignore')\n", (1953, 1978), False, 'from sklearn.preprocessing import OrdinalEncoder, StandardScaler, OneHotEncoder\n'), ((4907, 5011), 'sklearn.impute.SimpleImputer', 'SimpleImputer', ([], {'missing_values': 'val_flag', 'strategy': "config['strategy']", 'fill_value': "config['fill_value']"}), "(missing_values=val_flag, strategy=config['strategy'],\n fill_value=config['fill_value'])\n", (4920, 5011), False, 'from sklearn.impute import SimpleImputer\n'), ((5143, 5210), 'sklearn.impute.SimpleImputer', 'SimpleImputer', ([], {'missing_values': 'val_flag', 'strategy': "config['strategy']"}), "(missing_values=val_flag, strategy=config['strategy'])\n", (5156, 5210), False, 'from sklearn.impute import SimpleImputer\n')]
# For SSH import Exscript # For Color Font from colorama import init as colorama_init from colorama import Fore colorama_init(autoreset=True) username = "user1" password = "<PASSWORD>" ip4 = "192.168.33.3" # SSHセッションの確立 session = Exscript.protocols.SSH2() session.connect(ip4) # ルータにログイン account = Exscript.Account(name=username, password=password) session.login(account) print("===== Step 1. run show command =====") session.execute("show configuration interfaces ge-0/0/1") print(Fore.YELLOW + session.response) print("===== Step 2. configure =====") session.execute("configure") config_txt = "set interfaces ge-0/0/1 disable" session.execute(config_txt) print(Fore.YELLOW + session.response) print("===== Step 3. commit check =====") session.execute("show | compare") print(Fore.YELLOW + session.response) session.execute("commit check") print(session.response) print("===== Step 4. commit =====") # ユーザにy or nを質問 print(Fore.YELLOW + "Do you commit? y/n") choice = input() if choice == "y": session.execute("commit") print(session.response) else: session.execute("rollback") print(session.response) session.execute("exit") print(session.response) print("===== Step 5. run show command(again) =====") session.execute("show configuration interfaces ge-0/0/1") print(Fore.YELLOW + session.response) session.send("exit") session.close()
[ "Exscript.Account", "Exscript.protocols.SSH2", "colorama.init" ]
[((113, 142), 'colorama.init', 'colorama_init', ([], {'autoreset': '(True)'}), '(autoreset=True)\n', (126, 142), True, 'from colorama import init as colorama_init\n'), ((233, 258), 'Exscript.protocols.SSH2', 'Exscript.protocols.SSH2', ([], {}), '()\n', (256, 258), False, 'import Exscript\n'), ((302, 352), 'Exscript.Account', 'Exscript.Account', ([], {'name': 'username', 'password': 'password'}), '(name=username, password=password)\n', (318, 352), False, 'import Exscript\n')]
import time from tasks.capp import app from others.affine_applications import MoveApps @app.task(name="sdc.move11", bind=True) def task_1(self, x): time.sleep(1) return MoveApps(":move", x).foo() @app.task(name="sdc.move12", bind=True) def task_2(self, x): return MoveApps(":move", x + 1).foo()
[ "tasks.capp.app.task", "others.affine_applications.MoveApps", "time.sleep" ]
[((91, 129), 'tasks.capp.app.task', 'app.task', ([], {'name': '"""sdc.move11"""', 'bind': '(True)'}), "(name='sdc.move11', bind=True)\n", (99, 129), False, 'from tasks.capp import app\n'), ((210, 248), 'tasks.capp.app.task', 'app.task', ([], {'name': '"""sdc.move12"""', 'bind': '(True)'}), "(name='sdc.move12', bind=True)\n", (218, 248), False, 'from tasks.capp import app\n'), ((155, 168), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (165, 168), False, 'import time\n'), ((180, 200), 'others.affine_applications.MoveApps', 'MoveApps', (['""":move"""', 'x'], {}), "(':move', x)\n", (188, 200), False, 'from others.affine_applications import MoveApps\n'), ((281, 305), 'others.affine_applications.MoveApps', 'MoveApps', (['""":move"""', '(x + 1)'], {}), "(':move', x + 1)\n", (289, 305), False, 'from others.affine_applications import MoveApps\n')]
from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics/') contacts=models.CharField(max_length=50 ,blank=True,null=True) bio=models.CharField(max_length=100,blank=True,null=True) def save_profile(self): self.save() def __str__(self): return f'{self.user.username} Profile'
[ "django.db.models.ImageField", "django.db.models.OneToOneField", "django.db.models.CharField" ]
[((162, 214), 'django.db.models.OneToOneField', 'models.OneToOneField', (['User'], {'on_delete': 'models.CASCADE'}), '(User, on_delete=models.CASCADE)\n', (182, 214), False, 'from django.db import models\n'), ((227, 294), 'django.db.models.ImageField', 'models.ImageField', ([], {'default': '"""default.jpg"""', 'upload_to': '"""profile_pics/"""'}), "(default='default.jpg', upload_to='profile_pics/')\n", (244, 294), False, 'from django.db import models\n'), ((308, 362), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)', 'blank': '(True)', 'null': '(True)'}), '(max_length=50, blank=True, null=True)\n', (324, 362), False, 'from django.db import models\n'), ((370, 425), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'blank': '(True)', 'null': '(True)'}), '(max_length=100, blank=True, null=True)\n', (386, 425), False, 'from django.db import models\n')]
# -*- coding: utf-8 -*- """ Created on Thu Feb 16 11:40:09 2017 @author: florentin """ import serial from os import getcwd ## paramètres du port série #port = input("Quel numéro de port COM voulez-vous écouter?\n") #vitesse = int(input("Quelle vitesse en baud?\n")) #caracFin = input("Quel(s) caractère(s) de fin de communication?\n") # #print("Dossier de travail : \n", getcwd(), '\n') #cheminFichier = input("Chemin du fichier csv\n") port = str(6) vitesse = 9600 caracFin = "stop" cheminFichier = "pathToMyFile.csv" # initialisation du port série ser = serial.Serial('COM' + port, vitesse) if(ser.isOpen()): print("Port série COM{} ouvert.".format(port)) ligne = "" with open(cheminFichier, 'w') as outfile: while(not(ligne == caracFin)): # on vérifie s'il y a des caractères en attente dans le buffer if(ser.inWaiting()): ligne = ser.readline()[:-2].decode("utf-8") #on enlève \r\n print(ligne)#, ligne==caracFin) outfile.write(ligne.replace('.',',') + '\n') ser.close() print("Finis")
[ "serial.Serial" ]
[((561, 597), 'serial.Serial', 'serial.Serial', (["('COM' + port)", 'vitesse'], {}), "('COM' + port, vitesse)\n", (574, 597), False, 'import serial\n')]
import logging from django import template from django.db.models import Q from django.utils import timezone from django.utils.safestring import SafeString from cms.contexts.utils import handle_faulty_templates from cms.publications.models import Category, Publication, PublicationContext logger = logging.getLogger(__name__) register = template.Library() def _get_pub_qparams(context, webpath, section = None, categories_csv=None, exclude_categories=False, tags_csv=None): now = timezone.localtime() query_params = dict(webpath=context['webpath'], is_active=True, publication__is_active=True, date_start__lte=now, date_end__gt=now) if section: query_params['section'] = section if categories_csv: cats = [i.strip() for i in categories_csv.split(',')] if exclude_categories: categories = Category.objects.exclude(name__in=cats).\ values_list('name', flat=True) query_params['publication__category__name__in'] = categories else: query_params['publication__category__name__in'] = cats if tags_csv: tags = [i.strip() for i in tags_csv.split(',')] query_params['publication__tags__name__in'] = tags return query_params @register.simple_tag(takes_context=True) def load_publication(context, template, publication_id): _func_name = 'load_publication' _log_msg = f'Template Tag {_func_name}' request = context['request'] webpath = context['webpath'] language = getattr(request, 'LANGUAGE_CODE', '') pub = Publication.objects.filter(pk=publication_id, is_active=True).first() if not pub: _msg = '{} cannot find publication id {}'.format(_log_msg, publication_id) logger.error(_msg) return SafeString('') pub.translate_as(lang=language) data = {'publication': pub, 'webpath': webpath} return handle_faulty_templates(template, data, name=_func_name) @register.simple_tag(takes_context=True) def load_publications_preview(context, template, section = None, number=0, in_evidence=False, categories_csv=None, exclude_categories=False, tags_csv=None): request = context['request'] webpath = context['webpath'] query_params = _get_pub_qparams(context=context , webpath=webpath, section=section, categories_csv=categories_csv, exclude_categories=exclude_categories, tags_csv=tags_csv) pub_in_context = PublicationContext.objects.\ filter(**query_params).\ distinct().\ order_by('order','-date_start') if in_evidence: now = timezone.localtime() pub_in_context = pub_in_context.filter(Q(in_evidence_end__gt=now) | Q(in_evidence_end__isnull=True), in_evidence_start__lt=now) if number > 0: pub_in_context = pub_in_context[0:number] if not pub_in_context: return SafeString('') # i18n language = getattr(request, 'LANGUAGE_CODE', '') for i in pub_in_context: i.publication.translate_as(lang=language) data = {'publications': pub_in_context} return handle_faulty_templates(template, data, name='load_publications_preview')
[ "logging.getLogger", "django.utils.safestring.SafeString", "cms.publications.models.Publication.objects.filter", "cms.publications.models.PublicationContext.objects.filter", "django.utils.timezone.localtime", "cms.publications.models.Category.objects.exclude", "cms.contexts.utils.handle_faulty_templates...
[((301, 328), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (318, 328), False, 'import logging\n'), ((340, 358), 'django.template.Library', 'template.Library', ([], {}), '()\n', (356, 358), False, 'from django import template\n'), ((552, 572), 'django.utils.timezone.localtime', 'timezone.localtime', ([], {}), '()\n', (570, 572), False, 'from django.utils import timezone\n'), ((2163, 2219), 'cms.contexts.utils.handle_faulty_templates', 'handle_faulty_templates', (['template', 'data'], {'name': '_func_name'}), '(template, data, name=_func_name)\n', (2186, 2219), False, 'from cms.contexts.utils import handle_faulty_templates\n'), ((3772, 3845), 'cms.contexts.utils.handle_faulty_templates', 'handle_faulty_templates', (['template', 'data'], {'name': '"""load_publications_preview"""'}), "(template, data, name='load_publications_preview')\n", (3795, 3845), False, 'from cms.contexts.utils import handle_faulty_templates\n'), ((2048, 2062), 'django.utils.safestring.SafeString', 'SafeString', (['""""""'], {}), "('')\n", (2058, 2062), False, 'from django.utils.safestring import SafeString\n'), ((3202, 3222), 'django.utils.timezone.localtime', 'timezone.localtime', ([], {}), '()\n', (3220, 3222), False, 'from django.utils import timezone\n'), ((3557, 3571), 'django.utils.safestring.SafeString', 'SafeString', (['""""""'], {}), "('')\n", (3567, 3571), False, 'from django.utils.safestring import SafeString\n'), ((1742, 1803), 'cms.publications.models.Publication.objects.filter', 'Publication.objects.filter', ([], {'pk': 'publication_id', 'is_active': '(True)'}), '(pk=publication_id, is_active=True)\n', (1768, 1803), False, 'from cms.publications.models import Category, Publication, PublicationContext\n'), ((3270, 3296), 'django.db.models.Q', 'Q', ([], {'in_evidence_end__gt': 'now'}), '(in_evidence_end__gt=now)\n', (3271, 3296), False, 'from django.db.models import Q\n'), ((3346, 3377), 'django.db.models.Q', 'Q', ([], {'in_evidence_end__isnull': '(True)'}), '(in_evidence_end__isnull=True)\n', (3347, 3377), False, 'from django.db.models import Q\n'), ((1005, 1044), 'cms.publications.models.Category.objects.exclude', 'Category.objects.exclude', ([], {'name__in': 'cats'}), '(name__in=cats)\n', (1029, 1044), False, 'from cms.publications.models import Category, Publication, PublicationContext\n'), ((3044, 3093), 'cms.publications.models.PublicationContext.objects.filter', 'PublicationContext.objects.filter', ([], {}), '(**query_params)\n', (3077, 3093), False, 'from cms.publications.models import Category, Publication, PublicationContext\n')]
# -*- mode: python; encoding: utf-8 -*- # # Copyright 2012 <NAME>, Opera Software ASA # # 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 diff import dbutils import gitutils def loadChangeset(db, repository, changeset_id, filtered_file_ids=None, load_chunks=True): return loadChangesets(db, repository, changesets=[diff.Changeset.fromId(db, repository, changeset_id)], filtered_file_ids=filtered_file_ids, load_chunks=load_chunks)[0] def loadChangesetsForCommits(db, repository, commits, filtered_file_ids=None, load_chunks=True): commit_ids = dict([(commit.getId(db), commit) for commit in commits]) def getCommit(commit_id): return commit_ids.get(commit_id) or gitutils.Commit.fromId(db, repository, commit_id) cursor = db.cursor() cursor.execute("SELECT id, parent, child FROM changesets WHERE child=ANY (%s) AND type='direct'", (commit_ids.keys(),)) changesets = [] for changeset_id, parent_id, child_id in cursor: changesets.append(diff.Changeset(changeset_id, getCommit(parent_id), getCommit(child_id), "direct")) return loadChangesets(db, repository, changesets, filtered_file_ids=filtered_file_ids, load_chunks=load_chunks) def loadChangesets(db, repository, changesets, filtered_file_ids=None, load_chunks=True): cursor = db.cursor() changeset_ids = [changeset.id for changeset in changesets] filtered_file_ids = list(filtered_file_ids) if filtered_file_ids else None if filtered_file_ids is None: cursor.execute("""SELECT changeset, file, fullfilename(file), old_sha1, new_sha1, old_mode, new_mode FROM fileversions WHERE changeset=ANY (%s)""", (changeset_ids,)) else: cursor.execute("""SELECT changeset, file, fullfilename(file), old_sha1, new_sha1, old_mode, new_mode FROM fileversions WHERE changeset=ANY (%s) AND file=ANY (%s)""", (changeset_ids, filtered_file_ids)) files = dict([(changeset.id, {}) for changeset in changesets]) for changeset_id, file_id, file_path, file_old_sha1, file_new_sha1, file_old_mode, file_new_mode in cursor.fetchall(): files[changeset_id][file_id] = diff.File(file_id, file_path, file_old_sha1, file_new_sha1, repository, old_mode=file_old_mode, new_mode=file_new_mode, chunks=[]) if load_chunks: if filtered_file_ids is None: cursor.execute("""SELECT id, changeset, file, deleteOffset, deleteCount, insertOffset, insertCount, analysis, whitespace FROM chunks WHERE changeset=ANY (%s) ORDER BY file, deleteOffset ASC""", (changeset_ids,)) else: cursor.execute("""SELECT id, changeset, file, deleteOffset, deleteCount, insertOffset, insertCount, analysis, whitespace FROM chunks WHERE changeset=ANY (%s) AND file=ANY (%s) ORDER BY file, deleteOffset ASC""", (changeset_ids, filtered_file_ids)) for chunk_id, changeset_id, file_id, delete_offset, delete_count, insert_offset, insert_count, analysis, is_whitespace in cursor: files[changeset_id][file_id].chunks.append(diff.Chunk(delete_offset, delete_count, insert_offset, insert_count, id=chunk_id, is_whitespace=is_whitespace, analysis=analysis)) for changeset in changesets: changeset.files = diff.File.sorted(files[changeset.id].values()) return changesets
[ "diff.File", "gitutils.Commit.fromId", "diff.Chunk", "diff.Changeset.fromId" ]
[((2874, 3008), 'diff.File', 'diff.File', (['file_id', 'file_path', 'file_old_sha1', 'file_new_sha1', 'repository'], {'old_mode': 'file_old_mode', 'new_mode': 'file_new_mode', 'chunks': '[]'}), '(file_id, file_path, file_old_sha1, file_new_sha1, repository,\n old_mode=file_old_mode, new_mode=file_new_mode, chunks=[])\n', (2883, 3008), False, 'import diff\n'), ((1266, 1315), 'gitutils.Commit.fromId', 'gitutils.Commit.fromId', (['db', 'repository', 'commit_id'], {}), '(db, repository, commit_id)\n', (1288, 1315), False, 'import gitutils\n'), ((4281, 4415), 'diff.Chunk', 'diff.Chunk', (['delete_offset', 'delete_count', 'insert_offset', 'insert_count'], {'id': 'chunk_id', 'is_whitespace': 'is_whitespace', 'analysis': 'analysis'}), '(delete_offset, delete_count, insert_offset, insert_count, id=\n chunk_id, is_whitespace=is_whitespace, analysis=analysis)\n', (4291, 4415), False, 'import diff\n'), ((848, 899), 'diff.Changeset.fromId', 'diff.Changeset.fromId', (['db', 'repository', 'changeset_id'], {}), '(db, repository, changeset_id)\n', (869, 899), False, 'import diff\n')]
#!/usr/bin/env python3 from powerdnsadmin import create_app app = create_app()
[ "powerdnsadmin.create_app" ]
[((68, 80), 'powerdnsadmin.create_app', 'create_app', ([], {}), '()\n', (78, 80), False, 'from powerdnsadmin import create_app\n')]
#!/usr/bin/python3 # ================================================== """ File: RMedian - Unittest - Phase 1 Author: <NAME> """ # ================================================== # Import import math import random import pytest # ================================================== # Phase 1 def phase1(X, k, d): # Initiation n = len(X) random.shuffle(X) S = X[:k] XS = X[k:] S.sort() # Keeping the list entries below k/2 if 2*(k*math.log2(n))**0.5 < k/2: lst = [2*(k*math.log2(n))**0.5] if 3*(k*math.log2(n))**0.5 < k/2: lst.append(3*(k*math.log2(n))**0.5) while d*lst[len(lst) - 1] < k/2: lst.append(d*lst[len(lst) - 1]) lst.append(k/2) else: lst = [k/2] # Buckets L = [[] for _ in range(len(lst) - 1)] R = [[] for _ in range(len(lst) - 1)] C = [] for s in S[math.floor(k / 2 - lst[0]): math.ceil(k / 2 + lst[0])]: C.append(s) for i in range(1, len(lst)): for s in S[math.floor(k / 2 - lst[i]): math.floor(k / 2 - lst[i - 1])]: L[i - 1].append(s) for s in S[math.ceil(k / 2 + lst[i - 1]): math.ceil(k / 2 + lst[i])]: R[i - 1].append(s) return S, XS, L, C, R # ================================================== # Unittest : Parameter @pytest.mark.parametrize(('n'), [ # Randomized input random.randint(2**9, 2**15), # Manuel input 2**10, 2**12, 2**14, 2**12 + 1, 2**12 - 1 ]) # ================================================== # Unittest : Test def test_p1(n): # Generating Tastcase X0 = [i for i in range(n)] k0 = int(n ** (2 / 3)) d0 = int(n ** (1 / 12)) S0, XS0, L0, C0, R0 = phase1(X0, k0, d0) X1 = [i for i in range(n)] k1 = int(n / math.log(n, 2)**(1/3)) d1 = int(math.log(n, 2)**(1/3)) S1, XS1, L1, C1, R1 = phase1(X1, k1, d1) sumL0, sumR0, sumL1, sumR1 = 0, 0, 0, 0 for l0 in L0: sumL0 += len(l0) for l1 in L1: sumL1 += len(l1) for r0 in R0: sumR0 += len(r0) for r1 in R1: sumR1 += len(r1) # Test assert sumL0 == sumR0 # ||L|| = ||R|| assert sumL1 == sumR1 # ||L|| = ||R|| assert len(L0) == len(R0) # |L| = |R| assert len(L1) == len(R1) # |L| = |R| assert sumL0 + len(C0) + sumR0 == k0 # |L| + |C| + |R| = k assert sumL1 + len(C1) + sumR1 == k1 # |L| + |C| + |R| = k return # ==================================================
[ "math.ceil", "random.shuffle", "math.floor", "math.log2", "math.log", "random.randint" ]
[((359, 376), 'random.shuffle', 'random.shuffle', (['X'], {}), '(X)\n', (373, 376), False, 'import random\n'), ((1405, 1436), 'random.randint', 'random.randint', (['(2 ** 9)', '(2 ** 15)'], {}), '(2 ** 9, 2 ** 15)\n', (1419, 1436), False, 'import random\n'), ((906, 932), 'math.floor', 'math.floor', (['(k / 2 - lst[0])'], {}), '(k / 2 - lst[0])\n', (916, 932), False, 'import math\n'), ((934, 959), 'math.ceil', 'math.ceil', (['(k / 2 + lst[0])'], {}), '(k / 2 + lst[0])\n', (943, 959), False, 'import math\n'), ((1839, 1853), 'math.log', 'math.log', (['n', '(2)'], {}), '(n, 2)\n', (1847, 1853), False, 'import math\n'), ((1035, 1061), 'math.floor', 'math.floor', (['(k / 2 - lst[i])'], {}), '(k / 2 - lst[i])\n', (1045, 1061), False, 'import math\n'), ((1063, 1093), 'math.floor', 'math.floor', (['(k / 2 - lst[i - 1])'], {}), '(k / 2 - lst[i - 1])\n', (1073, 1093), False, 'import math\n'), ((1146, 1175), 'math.ceil', 'math.ceil', (['(k / 2 + lst[i - 1])'], {}), '(k / 2 + lst[i - 1])\n', (1155, 1175), False, 'import math\n'), ((1177, 1202), 'math.ceil', 'math.ceil', (['(k / 2 + lst[i])'], {}), '(k / 2 + lst[i])\n', (1186, 1202), False, 'import math\n'), ((1803, 1817), 'math.log', 'math.log', (['n', '(2)'], {}), '(n, 2)\n', (1811, 1817), False, 'import math\n'), ((475, 487), 'math.log2', 'math.log2', (['n'], {}), '(n)\n', (484, 487), False, 'import math\n'), ((521, 533), 'math.log2', 'math.log2', (['n'], {}), '(n)\n', (530, 533), False, 'import math\n'), ((557, 569), 'math.log2', 'math.log2', (['n'], {}), '(n)\n', (566, 569), False, 'import math\n'), ((611, 623), 'math.log2', 'math.log2', (['n'], {}), '(n)\n', (620, 623), False, 'import math\n')]
from typing import Dict, Iterable, List, Optional, Union from functools import partial import torch import torch.nn as nn from torch.nn import functional as F import pytorch_lightning as pl class BaseException(Exception): def __init__( self, parameter, types: List): message = '{} type must be one of {}'.format(parameter, types) super().__init__(message) class Base(pl.LightningModule): def __init__(self): super(Base, self).__init__() self.is_released = False def remove_num_batches_tracked(self, state_dict): new_state_dict = {} for name, p in state_dict.items(): if not 'num_batches_tracked' in name: new_state_dict[name] = p return new_state_dict def migrate( self, state_dict: Dict, other_state_dict=None, force=False, verbose=2 ): ''' verbose=0: do not print verbose=1: print status of migrate: all is migrated or something verbose=2: print all of modules had been migrated ''' if verbose == 0: def status(i, string): pass def conclude(is_all_migrated): pass elif verbose == 1: def status(i, string): pass def conclude(is_all_migrated): if is_all_migrated: print("all modules had been migrated") else: print("Some modules hadn't been migrated") elif verbose == 2: def status(i, string): print(i, string) def conclude(is_all_migrated): if is_all_migrated: print("all modules had been migrated") else: print("Some modules hadn't been migrated") if other_state_dict is None: des_state_dict = self.state_dict() source_state_dict = state_dict else: des_state_dict = state_dict source_state_dict = other_state_dict des_state_dict = self.remove_num_batches_tracked(des_state_dict) source_state_dict = self.remove_num_batches_tracked(source_state_dict) is_all_migrated = True if not force: state_dict_keys = source_state_dict.keys() with torch.no_grad(): for i, (name, p) in enumerate(des_state_dict.items()): if name in state_dict_keys: _p = source_state_dict[name] if p.data.shape == _p.shape: status(i, name) p.copy_(_p) else: is_all_migrated = False else: is_all_migrated = False else: print('Force migrating...') with torch.no_grad(): for i, ((name, p), (_name, _p)) in enumerate(zip(des_state_dict.items(), source_state_dict.items())): if p.shape == _p.shape: status(i, 'copy to {} from {}'.format(name, _name)) p.copy_(_p) else: is_all_migrated = False conclude(is_all_migrated) def remove_prefix_state_dict( self, state_dict: Dict, prefix: Union[str, int] ): result_state_dict = {} if isinstance(prefix, int): # TODO return state_dict elif isinstance(prefix, str): len_prefix_remove = len(prefix) + 1 for key, value in state_dict.items(): if key.startswith(prefix): result_state_dict[key[len_prefix_remove:] ] = state_dict[key] else: result_state_dict[key] = state_dict[key] return result_state_dict else: raise BaseException('prefix', [str, int]) def filter_state_dict_with_prefix( self, state_dict: Dict, prefix: str, is_remove_prefix=False ): if not isinstance(prefix, str): raise BaseException('prefix', [str]) new_state_dict = {} if is_remove_prefix: prefix_length = len(prefix) for name, p in state_dict.items(): if name.startswith(prefix): new_state_dict[name[prefix_length+1:]] = p else: for name, p in state_dict.items(): if name.startswith(prefix): new_state_dict[name] = p return new_state_dict def filter_state_dict_except_prefix( self, state_dict: Dict, prefix: str, ): if not isinstance(prefix, str): raise BaseException('prefix', [str]) new_state_dict = {} for name, p in state_dict.items(): if not name.startswith(prefix): new_state_dict[name] = p return new_state_dict def freeze_except_prefix(self, prefix): for name, p in self.named_parameters(): if not name.startswith(prefix): p.requires_grad = False def freeze_with_prefix(self, prefix): for name, p in self.named_parameters(): if name.startswith(prefix): p.requires_grad = False def defrost_except_prefix(self, prefix): for name, p in self.named_parameters(): if not name.startswith(prefix): p.requires_grad = True def defrost_with_prefix(self, prefix): for name, p in self.named_parameters(): if name.startswith(prefix): p.requires_grad = True class BaseSequential(nn.Sequential, Base): pass
[ "torch.no_grad" ]
[((2414, 2429), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2427, 2429), False, 'import torch\n'), ((2968, 2983), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2981, 2983), False, 'import torch\n')]
import tkinter as tk class ScrolledFrame(tk.Frame): def __init__(self, parent, vertical=True, horizontal=False): super().__init__(parent) # canvas for inner frame self._canvas = tk.Canvas(self) self._canvas.grid(row=0, column=0, sticky='news') # changed # create right scrollbar and connect to canvas Y self._vertical_bar = tk.Scrollbar(self, orient='vertical', command=self._canvas.yview) if vertical: self._vertical_bar.grid(row=0, column=1, sticky='ns') self._canvas.configure(yscrollcommand=self._vertical_bar.set) # create bottom scrollbar and connect to canvas X self._horizontal_bar = tk.Scrollbar(self, orient='horizontal', command=self._canvas.xview) if horizontal: self._horizontal_bar.grid(row=1, column=0, sticky='we') self._canvas.configure(xscrollcommand=self._horizontal_bar.set) # inner frame for widgets self.inner = tk.Frame(self._canvas) self._window = self._canvas.create_window((0, 0), window=self.inner, anchor='nw') # autoresize inner frame self.columnconfigure(0, weight=1) # changed self.rowconfigure(0, weight=1) # changed # resize when configure changed self.inner.bind('<Configure>', self.resize) # resize inner frame to canvas size self.resize_width = False self.resize_height = False self._canvas.bind('<Configure>', self.inner_resize) def resize(self, event=None): self._canvas.configure(scrollregion=self._canvas.bbox('all')) def inner_resize(self, event): # resize inner frame to canvas size if self.resize_width: self._canvas.itemconfig(self._window, width=event.width) if self.resize_height: self._canvas.itemconfig(self._window, height=event.height)
[ "tkinter.Canvas", "tkinter.Scrollbar", "tkinter.Frame" ]
[((209, 224), 'tkinter.Canvas', 'tk.Canvas', (['self'], {}), '(self)\n', (218, 224), True, 'import tkinter as tk\n'), ((380, 445), 'tkinter.Scrollbar', 'tk.Scrollbar', (['self'], {'orient': '"""vertical"""', 'command': 'self._canvas.yview'}), "(self, orient='vertical', command=self._canvas.yview)\n", (392, 445), True, 'import tkinter as tk\n'), ((693, 760), 'tkinter.Scrollbar', 'tk.Scrollbar', (['self'], {'orient': '"""horizontal"""', 'command': 'self._canvas.xview'}), "(self, orient='horizontal', command=self._canvas.xview)\n", (705, 760), True, 'import tkinter as tk\n'), ((980, 1002), 'tkinter.Frame', 'tk.Frame', (['self._canvas'], {}), '(self._canvas)\n', (988, 1002), True, 'import tkinter as tk\n')]
import logging import goaway.globalvars as globalvars logger = logging.getLogger(__name__) DATA_STORE_HANDLE_KIND_ATTR = "__store" NAME_ATTR = "__name" class ObjectHandle(object): """ Represents a shared object in a datstore. Instances of this class are returned by object handle constructors. Applications should not directly create these. Example: accumulators = goaway.StrictCentralized() accumulators.flowers = 0 accumulators.trees = 10 """ def __init__(self, data_store_kind, name): """ Args: data_store_kind: Name of the type of datastore to use (from globalvars) name: Name of the object, to identify its store. """ self.__dict__[DATA_STORE_HANDLE_KIND_ATTR] = data_store_kind self.__dict__[NAME_ATTR] = name def __getattr__(self, field): """ Hook when an attribute is fetched. """ store = globalvars.get_data_store(getattr(self, DATA_STORE_HANDLE_KIND_ATTR)) object_name = getattr(self, NAME_ATTR) value = store.get(object_name, field) return value def __setattr__(self, field, value): """ Hook when an attribute is set. """ store = globalvars.get_data_store(getattr(self, DATA_STORE_HANDLE_KIND_ATTR)) object_name = getattr(self, NAME_ATTR) store.set(object_name, field, value)
[ "logging.getLogger" ]
[((65, 92), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (82, 92), False, 'import logging\n')]
import os import mimetypes import chardet UTF8 = ('utf-8', 'ascii') WANTED_CHARSET = UTF8 FILE_PATH = '.' THRESHOLD = 0.6 # Chardet cannot recognize ISO-8859-1 charset. RECOGNIZE_8859_2_AS_8859_1 = True LOG_FILE_CONVERTED = '/dcclog/converted' LOG_FILE_UNCONVERTED = '/dcclog/unconverted' LOG_FILE_CAN_NOT_DETECT = '/dcclog/can_not_detect' LOG_FILE_FILENAME_IS_NOT_TEXT_FILE = '/dcclog/not_text_file' LOG_FILES = ( LOG_FILE_CONVERTED, LOG_FILE_UNCONVERTED, LOG_FILE_CAN_NOT_DETECT, LOG_FILE_FILENAME_IS_NOT_TEXT_FILE, ) IGNORED = ('.git', '.idea', 'dcclog', 'dcc.py', '.gitignore') MIME_EXTRA_TEXT_TYPES = ( 'application/javascript', 'application/x-sh', 'application/xml', ) def init_log(): try: os.mkdir(FILE_PATH+'/dcclog') except FileExistsError: pass for file in LOG_FILES: try: os.remove(FILE_PATH + file) except FileNotFoundError: pass def log(logfile, file_path_name, mime_type, encoding, confidence): with open(FILE_PATH + logfile, 'at') as file: l = '{}, {}, {}, {}\n'.format(file_path_name, mime_type, encoding, confidence) file.write(l) def ignored(dirpath, filename): while not os.path.samefile(dirpath, FILE_PATH): dirpath, filename = os.path.split(dirpath) # print(dirpath, filename, sep='< ^o^ >') if filename in IGNORED: return True def _main(): init_log() for dirpath, dirnames, filenames in os.walk(FILE_PATH): for filename in filenames: if ignored(dirpath, filename): continue encoding = None confidence = None mime_type = mimetypes.guess_type(filename, strict=False)[0] file_path_name = os.path.join(dirpath, filename) if mime_type is None or mime_type.startswith('text') or mime_type in MIME_EXTRA_TEXT_TYPES: with open(file_path_name, 'rb') as file: content = file.read() detect = chardet.detect(content) encoding = detect['encoding'] confidence = detect['confidence'] if RECOGNIZE_8859_2_AS_8859_1 and encoding == 'ISO-8859-2': encoding = 'ISO-8859-1' if confidence < THRESHOLD: log(LOG_FILE_CAN_NOT_DETECT, file_path_name, mime_type, encoding, confidence) elif encoding in WANTED_CHARSET: log(LOG_FILE_UNCONVERTED, file_path_name, mime_type, encoding, confidence) else: with open(file_path_name, 'wb') as file: file.write(content.decode(encoding).encode(WANTED_CHARSET[0])) log(LOG_FILE_CONVERTED, file_path_name, mime_type, encoding, confidence) else: log(LOG_FILE_FILENAME_IS_NOT_TEXT_FILE, file_path_name, mime_type, encoding, confidence) if __name__ == '__main__': _main()
[ "os.path.samefile", "os.path.join", "os.path.split", "chardet.detect", "os.mkdir", "mimetypes.guess_type", "os.walk", "os.remove" ]
[((1473, 1491), 'os.walk', 'os.walk', (['FILE_PATH'], {}), '(FILE_PATH)\n', (1480, 1491), False, 'import os\n'), ((741, 772), 'os.mkdir', 'os.mkdir', (["(FILE_PATH + '/dcclog')"], {}), "(FILE_PATH + '/dcclog')\n", (749, 772), False, 'import os\n'), ((1220, 1256), 'os.path.samefile', 'os.path.samefile', (['dirpath', 'FILE_PATH'], {}), '(dirpath, FILE_PATH)\n', (1236, 1256), False, 'import os\n'), ((1286, 1308), 'os.path.split', 'os.path.split', (['dirpath'], {}), '(dirpath)\n', (1299, 1308), False, 'import os\n'), ((865, 892), 'os.remove', 'os.remove', (['(FILE_PATH + file)'], {}), '(FILE_PATH + file)\n', (874, 892), False, 'import os\n'), ((1755, 1786), 'os.path.join', 'os.path.join', (['dirpath', 'filename'], {}), '(dirpath, filename)\n', (1767, 1786), False, 'import os\n'), ((1678, 1722), 'mimetypes.guess_type', 'mimetypes.guess_type', (['filename'], {'strict': '(False)'}), '(filename, strict=False)\n', (1698, 1722), False, 'import mimetypes\n'), ((2019, 2042), 'chardet.detect', 'chardet.detect', (['content'], {}), '(content)\n', (2033, 2042), False, 'import chardet\n')]
import os import sys import unittest from test.support import run_unittest, import_module # Skip tests if we don't have threading. import_module('threading') # Skip tests if we don't have concurrent.futures. import_module('concurrent.futures') def suite(): tests = unittest.TestSuite() loader = unittest.TestLoader() for fn in os.listdir(os.path.dirname(__file__)): if fn.startswith("test") and fn.endswith(".py"): mod_name = 'test.test_asyncio.' + fn[:-3] try: __import__(mod_name) except unittest.SkipTest: pass else: mod = sys.modules[mod_name] tests.addTests(loader.loadTestsFromModule(mod)) return tests def test_main(): run_unittest(suite())
[ "os.path.dirname", "unittest.TestSuite", "unittest.TestLoader", "test.support.import_module" ]
[((132, 158), 'test.support.import_module', 'import_module', (['"""threading"""'], {}), "('threading')\n", (145, 158), False, 'from test.support import run_unittest, import_module\n'), ((209, 244), 'test.support.import_module', 'import_module', (['"""concurrent.futures"""'], {}), "('concurrent.futures')\n", (222, 244), False, 'from test.support import run_unittest, import_module\n'), ((272, 292), 'unittest.TestSuite', 'unittest.TestSuite', ([], {}), '()\n', (290, 292), False, 'import unittest\n'), ((306, 327), 'unittest.TestLoader', 'unittest.TestLoader', ([], {}), '()\n', (325, 327), False, 'import unittest\n'), ((353, 378), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (368, 378), False, 'import os\n')]
from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User from django.shortcuts import render, redirect from django.contrib.auth import login as auth_login from django.contrib.auth import logout as auth_logout # Create your views here. from django.views.generic import View class SignupView(View): def get(self, request): return render(request, 'signup.html', {'user_exist': False}) def post(self, request): username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] try: user = User.objects.create_user(username=username, email=email, password=password) except: return render(request, 'signup.html', {'user_exist': True}) auth_login(request, user=user) print(username, 'loged in') return redirect('home') class LoginView(View): def get(self, request): return render(request, 'login.html', {'check_pass': False}) def post(self, request): username = request.POST['username'] password = request.POST['password'] try: user = User.objects.get(username=username) if user.check_password(password): auth_login(request, user=user) print(username, 'loged in') return redirect('home') else: return render(request, 'login.html', {'check_pass': True}) except: return render(request, 'login.html', {'check_pass': True}) class LogoutView(LoginRequiredMixin, View): def get(self, request): auth_logout(request) return render(request, 'login.html', {'check_pass': False})
[ "django.shortcuts.render", "django.contrib.auth.login", "django.shortcuts.redirect", "django.contrib.auth.models.User.objects.get", "django.contrib.auth.models.User.objects.create_user", "django.contrib.auth.logout" ]
[((389, 442), 'django.shortcuts.render', 'render', (['request', '"""signup.html"""', "{'user_exist': False}"], {}), "(request, 'signup.html', {'user_exist': False})\n", (395, 442), False, 'from django.shortcuts import render, redirect\n'), ((803, 833), 'django.contrib.auth.login', 'auth_login', (['request'], {'user': 'user'}), '(request, user=user)\n', (813, 833), True, 'from django.contrib.auth import login as auth_login\n'), ((885, 901), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (893, 901), False, 'from django.shortcuts import render, redirect\n'), ((970, 1022), 'django.shortcuts.render', 'render', (['request', '"""login.html"""', "{'check_pass': False}"], {}), "(request, 'login.html', {'check_pass': False})\n", (976, 1022), False, 'from django.shortcuts import render, redirect\n'), ((1649, 1669), 'django.contrib.auth.logout', 'auth_logout', (['request'], {}), '(request)\n', (1660, 1669), True, 'from django.contrib.auth import logout as auth_logout\n'), ((1685, 1737), 'django.shortcuts.render', 'render', (['request', '"""login.html"""', "{'check_pass': False}"], {}), "(request, 'login.html', {'check_pass': False})\n", (1691, 1737), False, 'from django.shortcuts import render, redirect\n'), ((631, 706), 'django.contrib.auth.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': 'username', 'email': 'email', 'password': 'password'}), '(username=username, email=email, password=password)\n', (655, 706), False, 'from django.contrib.auth.models import User\n'), ((1173, 1208), 'django.contrib.auth.models.User.objects.get', 'User.objects.get', ([], {'username': 'username'}), '(username=username)\n', (1189, 1208), False, 'from django.contrib.auth.models import User\n'), ((742, 794), 'django.shortcuts.render', 'render', (['request', '"""signup.html"""', "{'user_exist': True}"], {}), "(request, 'signup.html', {'user_exist': True})\n", (748, 794), False, 'from django.shortcuts import render, redirect\n'), ((1271, 1301), 'django.contrib.auth.login', 'auth_login', (['request'], {'user': 'user'}), '(request, user=user)\n', (1281, 1301), True, 'from django.contrib.auth import login as auth_login\n'), ((1369, 1385), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (1377, 1385), False, 'from django.shortcuts import render, redirect\n'), ((1427, 1478), 'django.shortcuts.render', 'render', (['request', '"""login.html"""', "{'check_pass': True}"], {}), "(request, 'login.html', {'check_pass': True})\n", (1433, 1478), False, 'from django.shortcuts import render, redirect\n'), ((1514, 1565), 'django.shortcuts.render', 'render', (['request', '"""login.html"""', "{'check_pass': True}"], {}), "(request, 'login.html', {'check_pass': True})\n", (1520, 1565), False, 'from django.shortcuts import render, redirect\n')]
import pandas as pd from xml.etree import ElementTree as etree from pprint import pprint from yattag import * import pdb #------------------------------------------------------------------------------------------------------------------------ # -*- coding: utf-8 -*- #------------------------------------------------------------------------------------------------------------------------ class Line: tierInfo = [] spokenTextID = "" rootElement = None rootID = None tierElements = [] doc = None lineNumber = None soundFile = None grammaticalTerms = None def __init__(self, doc, lineNumber, grammaticalTerms=[]): self.doc = doc self.lineNumber = lineNumber self.rootElement = self.doc.findall("TIER/ANNOTATION/ALIGNABLE_ANNOTATION")[lineNumber] self.allElements = findChildren(self.doc, self.rootElement) # need tier info to guide traverse self.tierInfo = [doc.attrib for doc in doc.findall("TIER")] # [{'LINGUISTIC_TYPE_REF': 'default-lt', 'TIER_ID': 'AYA'}, # {'LINGUISTIC_TYPE_REF': 'phonemic', 'PARENT_REF': 'AYA', 'TIER_ID': 'AYA2'}, # {'LINGUISTIC_TYPE_REF': 'translation', 'PARENT_REF': 'AYA', 'TIER_ID': 'ENG'}, # {'LINGUISTIC_TYPE_REF': 'translation', 'PARENT_REF': 'AYA2', 'TIER_ID': 'GL'}] self.tbl = buildTable(doc, self.allElements) self.rootID = self.deduceSpokenTextID() self.grammaticalTerms = grammaticalTerms def getImmediateChildrenOfRoot(self): rootID = self.deduceSpokenTextID() def getTierCount(self): return(self.getTable().shape[0]) def getTable(self): return(self.tbl) #---------------------------------------------------------------------------------------------------- def deduceSpokenTextID(self): return(self.tbl.loc[pd.isnull(self.tbl['ANNOTATION_REF'])]["ANNOTATION_ID"][0]) #---------------------------------------------------------------------------------------------------- def deduceWordRepresentation(self): rootSpokenTextID = self.deduceSpokenTextID() tbl_emptyLinesRemoved = self.tbl.query("TEXT != ''") # do not wish to count children with empty text fields numberOfDirectChildrenOfRoot = tbl_emptyLinesRemoved.ix[self.tbl["ANNOTATION_REF"] == rootSpokenTextID].shape[0] # add test for present but empty word tier, as in monkey line 1 if(numberOfDirectChildrenOfRoot == 1): return("noWords") elif(numberOfDirectChildrenOfRoot == 2): return("tokenizedWords") elif(numberOfDirectChildrenOfRoot > 2): return("wordsDistributedInElements") else: print("unrecognized word representation") #---------------------------------------------------------------------------------------------------- def getWordRepresentation(self): return(self.wordRepresentation) #---------------------------------------------------------------------------------------------------- def show(self): pprint(vars(self)) #---------------------------------------------------------------------------------------------------- def getSpokenText(self): return(self.tbl.ix[0, "TEXT"]) #---------------------------------------------------------------------------------------------------- def htmlLeadIn(self, htmlDoc, audioDirectory): oneBasedLineNumber = self.lineNumber + 1 text = "%d)" % oneBasedLineNumber htmlDoc.text(text) lineID = self.rootID audioTag = '<audio id="%s"><source src="%s/%s.wav"/></audio>' % (lineID, audioDirectory, lineID) htmlDoc.asis(audioTag) imageURL = "https://www.americanlinguistics.org/wp-content/uploads/speaker.png" buttonTag = '<button onclick="playSample(\'%s\')"><img src=\'%s\'/></button>' % (lineID, imageURL) htmlDoc.asis(buttonTag) #------------------------------------------------------------------------------------------------------------------------ def findChildren(doc, rootElement): elementsToDo = [rootElement] elementsCompleted = [] while(len(elementsToDo) > 0): currentElement = elementsToDo[0] parentRef = currentElement.attrib["ANNOTATION_ID"] pattern = "TIER/ANNOTATION/REF_ANNOTATION[@ANNOTATION_REF='%s']" % parentRef childElements = doc.findall(pattern) elementsToDo.remove(currentElement) elementsCompleted.append(currentElement) if(len(childElements) > 0): elementsToDo.extend(childElements) return(elementsCompleted) #------------------------------------------------------------------------------------------------------------------------ def buildTable(doc, lineElements): tbl_elements = pd.DataFrame(e.attrib for e in lineElements) #print(tbl_elements) #pdb.set_trace() startTimeSlotID = tbl_elements.ix[0, 'TIME_SLOT_REF1'] pattern = "TIME_ORDER/TIME_SLOT[@TIME_SLOT_ID='%s']" % startTimeSlotID startTime = int(doc.find(pattern).attrib["TIME_VALUE"]) startTimes = [startTime] rowCount = tbl_elements.shape[0] for i in range(1, rowCount): startTimes.append(float('NaN')) endTimeSlotID = tbl_elements.ix[0, 'TIME_SLOT_REF2'] pattern = "TIME_ORDER/TIME_SLOT[@TIME_SLOT_ID='%s']" % endTimeSlotID endTime = int(doc.find(pattern).attrib["TIME_VALUE"]) endTimes = [endTime] for i in range(1, rowCount): endTimes.append(float('NaN')) tbl_times = pd.DataFrame({"START": startTimes, "END": endTimes}) #print(tbl_times) ids = [e.attrib["ANNOTATION_ID"] for e in lineElements] tierInfo = [] text = [] for id in ids: parentPattern = "*/*/*/[@ANNOTATION_ID='%s']/../.." % id tierAttributes = doc.find(parentPattern).attrib tierInfo.append(tierAttributes) childPattern = "*/*/*/[@ANNOTATION_ID='%s']/ANNOTATION_VALUE" % id elementText = doc.find(childPattern).text if(elementText is None): elementText = "" #print("elementText: %s" % elementText) text.append(elementText.strip()) tbl_tierInfo = pd.DataFrame(tierInfo) tbl_text = pd.DataFrame({"TEXT": text}) # print("---- tbl_elements") # print(tbl_elements) # # print("---- tbl_tierInfo") # print(tbl_tierInfo) # # print("---- tbl_times") # print(tbl_times) # # print("---- tbl_text") # print(tbl_text) tbl = pd.concat([tbl_elements, tbl_tierInfo, tbl_times, tbl_text], axis=1) preferredColumnOrder = ["ANNOTATION_ID", "LINGUISTIC_TYPE_REF", "START", "END", "TEXT", "ANNOTATION_REF", "TIME_SLOT_REF1", "TIME_SLOT_REF2", "PARENT_REF", "TIER_ID"] tbl = tbl[preferredColumnOrder] textLengths = [len(t) for t in tbl["TEXT"].tolist()] tbl["TEXT_LENGTH"] = textLengths hasTabs = ["\t" in t for t in tbl["TEXT"].tolist()] tbl["HAS_TABS"] = hasTabs hasSpaces = [" " in t for t in tbl["TEXT"].tolist()] tbl["HAS_SPACES"] = hasSpaces # eliminate rows with no text # leave it in for now, take the tiers at face value, handle empty lines in toHTML tbl = tbl.query("TEXT != ''").reset_index(drop=True) return(tbl) #------------------------------------------------------------------------------------------------------------------------ def standardizeTable(tbl, tierGuide): print("entering standardizeTable") pdb.set_trace() tierNames = tbl["TIER_ID"].tolist() permittedNames = [tierGuide[k] for k in tierGuide] shared = set(tierNames).intersection(permittedNames) tbl_trimmed = tbl.loc[tbl['TIER_ID'].isin(shared)] return(tbl_trimmed)
[ "pandas.DataFrame", "pandas.isnull", "pandas.concat", "pdb.set_trace" ]
[((4682, 4726), 'pandas.DataFrame', 'pd.DataFrame', (['(e.attrib for e in lineElements)'], {}), '(e.attrib for e in lineElements)\n', (4694, 4726), True, 'import pandas as pd\n'), ((5390, 5442), 'pandas.DataFrame', 'pd.DataFrame', (["{'START': startTimes, 'END': endTimes}"], {}), "({'START': startTimes, 'END': endTimes})\n", (5402, 5442), True, 'import pandas as pd\n'), ((6002, 6024), 'pandas.DataFrame', 'pd.DataFrame', (['tierInfo'], {}), '(tierInfo)\n', (6014, 6024), True, 'import pandas as pd\n'), ((6040, 6068), 'pandas.DataFrame', 'pd.DataFrame', (["{'TEXT': text}"], {}), "({'TEXT': text})\n", (6052, 6068), True, 'import pandas as pd\n'), ((6309, 6377), 'pandas.concat', 'pd.concat', (['[tbl_elements, tbl_tierInfo, tbl_times, tbl_text]'], {'axis': '(1)'}), '([tbl_elements, tbl_tierInfo, tbl_times, tbl_text], axis=1)\n', (6318, 6377), True, 'import pandas as pd\n'), ((7273, 7288), 'pdb.set_trace', 'pdb.set_trace', ([], {}), '()\n', (7286, 7288), False, 'import pdb\n'), ((1801, 1838), 'pandas.isnull', 'pd.isnull', (["self.tbl['ANNOTATION_REF']"], {}), "(self.tbl['ANNOTATION_REF'])\n", (1810, 1838), True, 'import pandas as pd\n')]
from dl_plus.cli import main main()
[ "dl_plus.cli.main" ]
[((31, 37), 'dl_plus.cli.main', 'main', ([], {}), '()\n', (35, 37), False, 'from dl_plus.cli import main\n')]
import torch import numpy as np from torch.utils.data import Dataset import torchvision.transforms.functional as TF import torchvision.transforms as transforms import random import glob import os from PIL import Image ''' require fix the random seeds ''' # PotsdamDataset rgb_means = [0.3366, 0.3599, 0.3333] rgb_stds = [0.1030, 0.1031, 0.1066] class PotsdamDataset(Dataset): def __init__(self, configs, subset): super(PotsdamDataset, self).__init__() assert subset == 'train' or subset == 'valid' or subset == 'test', \ 'subset should be in the set of train, valid, and test' self.configs = configs self.subset = subset # sorted here when the images is not in order self.path_images = sorted(glob.glob(os.path.join(configs.path_cropped_images, subset, '*'))) #print(self.path_images[0:10]) self.path_labels = sorted(glob.glob(os.path.join(configs.path_cropped_labels, subset, '*'))) #print(self.path_labels[0:10]) # mapping to HxWx1 self.mask_mapping = { (255, 255, 255) : 0, # impervious surfaces (0, 0, 255) : 1, # Buildings (0, 255, 255) : 2, # Low Vegetation (0, 255, 0) : 3, # Tree (255, 255, 0) : 4, # Car (255, 0, 0) : 5 # background/Clutter } def mask_to_class(self, mask): for k in self.mask_mapping: # all used in numpy: axis, when used in torch: dim mask[(mask == torch.tensor(k, dtype = torch.uint8)).all(dim = 2)] = self.mask_mapping[k] return mask[:, :, 0] def transformation(self, image, mask): if self.subset == 'train': # only used for training data if random.random() > 0.5: image = TF.hflip(image) mask = TF.hflip(mask) if random.random() > 0.5: image = TF.vflip(image) mask = TF.vflip(mask) if random.random() > 0.5: image = TF.rotate(image, 10) mask = TF.rotate(mask, 10) if random.random() > 0.5: image = TF.rotate(image, -10) mask = TF.rotate(mask, -10) image = TF.to_tensor(image) image = TF.normalize(image, mean=rgb_means, std=rgb_stds) # here mask's dtype uint8, the dtype of k also should be uint8 and should be a tensor mask = torch.from_numpy(np.array(mask, dtype=np.uint8)) mask = self.mask_to_class(mask) mask = mask.long() return image, mask def __getitem__(self, item): image = Image.open(self.path_images[item]) label = Image.open(self.path_labels[item]) image, label = self.transformation(image, label) # only need filename in testing phase, used in prediction file. if self.subset == 'test': return image, label, self.path_images[item] else: return image, label def __len__(self): return len(self.path_images)
[ "torchvision.transforms.functional.to_tensor", "PIL.Image.open", "os.path.join", "torchvision.transforms.functional.hflip", "numpy.array", "torchvision.transforms.functional.rotate", "torchvision.transforms.functional.vflip", "torch.tensor", "random.random", "torchvision.transforms.functional.norm...
[((2291, 2310), 'torchvision.transforms.functional.to_tensor', 'TF.to_tensor', (['image'], {}), '(image)\n', (2303, 2310), True, 'import torchvision.transforms.functional as TF\n'), ((2327, 2376), 'torchvision.transforms.functional.normalize', 'TF.normalize', (['image'], {'mean': 'rgb_means', 'std': 'rgb_stds'}), '(image, mean=rgb_means, std=rgb_stds)\n', (2339, 2376), True, 'import torchvision.transforms.functional as TF\n'), ((2680, 2714), 'PIL.Image.open', 'Image.open', (['self.path_images[item]'], {}), '(self.path_images[item])\n', (2690, 2714), False, 'from PIL import Image\n'), ((2731, 2765), 'PIL.Image.open', 'Image.open', (['self.path_labels[item]'], {}), '(self.path_labels[item])\n', (2741, 2765), False, 'from PIL import Image\n'), ((2503, 2533), 'numpy.array', 'np.array', (['mask'], {'dtype': 'np.uint8'}), '(mask, dtype=np.uint8)\n', (2511, 2533), True, 'import numpy as np\n'), ((804, 858), 'os.path.join', 'os.path.join', (['configs.path_cropped_images', 'subset', '"""*"""'], {}), "(configs.path_cropped_images, subset, '*')\n", (816, 858), False, 'import os\n'), ((944, 998), 'os.path.join', 'os.path.join', (['configs.path_cropped_labels', 'subset', '"""*"""'], {}), "(configs.path_cropped_labels, subset, '*')\n", (956, 998), False, 'import os\n'), ((1799, 1814), 'random.random', 'random.random', ([], {}), '()\n', (1812, 1814), False, 'import random\n'), ((1846, 1861), 'torchvision.transforms.functional.hflip', 'TF.hflip', (['image'], {}), '(image)\n', (1854, 1861), True, 'import torchvision.transforms.functional as TF\n'), ((1885, 1899), 'torchvision.transforms.functional.hflip', 'TF.hflip', (['mask'], {}), '(mask)\n', (1893, 1899), True, 'import torchvision.transforms.functional as TF\n'), ((1916, 1931), 'random.random', 'random.random', ([], {}), '()\n', (1929, 1931), False, 'import random\n'), ((1963, 1978), 'torchvision.transforms.functional.vflip', 'TF.vflip', (['image'], {}), '(image)\n', (1971, 1978), True, 'import torchvision.transforms.functional as TF\n'), ((2002, 2016), 'torchvision.transforms.functional.vflip', 'TF.vflip', (['mask'], {}), '(mask)\n', (2010, 2016), True, 'import torchvision.transforms.functional as TF\n'), ((2033, 2048), 'random.random', 'random.random', ([], {}), '()\n', (2046, 2048), False, 'import random\n'), ((2080, 2100), 'torchvision.transforms.functional.rotate', 'TF.rotate', (['image', '(10)'], {}), '(image, 10)\n', (2089, 2100), True, 'import torchvision.transforms.functional as TF\n'), ((2124, 2143), 'torchvision.transforms.functional.rotate', 'TF.rotate', (['mask', '(10)'], {}), '(mask, 10)\n', (2133, 2143), True, 'import torchvision.transforms.functional as TF\n'), ((2160, 2175), 'random.random', 'random.random', ([], {}), '()\n', (2173, 2175), False, 'import random\n'), ((2207, 2228), 'torchvision.transforms.functional.rotate', 'TF.rotate', (['image', '(-10)'], {}), '(image, -10)\n', (2216, 2228), True, 'import torchvision.transforms.functional as TF\n'), ((2252, 2272), 'torchvision.transforms.functional.rotate', 'TF.rotate', (['mask', '(-10)'], {}), '(mask, -10)\n', (2261, 2272), True, 'import torchvision.transforms.functional as TF\n'), ((1558, 1592), 'torch.tensor', 'torch.tensor', (['k'], {'dtype': 'torch.uint8'}), '(k, dtype=torch.uint8)\n', (1570, 1592), False, 'import torch\n')]
import ipaddress from collections import defaultdict from autonetkit.design.utils import filters from autonetkit.design.utils.general import group_by from autonetkit.network_model.types import LAYER3_DEVICES def assign_loopbacks(topology): """ @param topology: """ layer3_nodes = [n for n in topology.nodes() if n.type in LAYER3_DEVICES] loopback_block = ipaddress.IPv4Network("172.16.0.0/16") loopback_subnets = loopback_block.subnets(new_prefix=24) grouped_l3 = group_by(layer3_nodes, "asn") allocated_loopbacks = defaultdict(list) for asn, nodes in grouped_l3.items(): # can repeat the loopbacks in each asn subnet = next(loopback_subnets) allocated_loopbacks[asn].append(subnet) host_ips = subnet.hosts() for node in nodes: host_ip = next(host_ips) lo0 = node.loopback_zero() lo0.set("ip", host_ip) # also map onto node for debugging/vis topology.set("loopbacks_by_asn", allocated_loopbacks) def assign_bc_subnets(topology): """ @param topology: """ # the network to use to address end hosts and for inter-domain connections allocated_blocks = defaultdict(list) global_advertise_network = ipaddress.IPv4Network("10.0.0.0/8") global_subnets = global_advertise_network.subnets(new_prefix=16) bc_nodes = filters.broadcast_domains(topology) grouped_bc = group_by(bc_nodes, "asn") for asn, nodes in grouped_bc.items(): asn_block = next(global_subnets) allocated_blocks[asn].append(asn_block) # quick method: allocate a /24 to each broadcast domain # Note: this could be significantly optimised in the future # Note: could allocate different block to internal infrastructure too external_blocks = asn_block.subnets(new_prefix=24) for bc in nodes: bc_block = next(external_blocks) bc.set("network", bc_block) topology.set("infrastructure_by_asn", allocated_blocks)
[ "ipaddress.IPv4Network", "autonetkit.design.utils.filters.broadcast_domains", "collections.defaultdict", "autonetkit.design.utils.general.group_by" ]
[((399, 437), 'ipaddress.IPv4Network', 'ipaddress.IPv4Network', (['"""172.16.0.0/16"""'], {}), "('172.16.0.0/16')\n", (420, 437), False, 'import ipaddress\n'), ((516, 545), 'autonetkit.design.utils.general.group_by', 'group_by', (['layer3_nodes', '"""asn"""'], {}), "(layer3_nodes, 'asn')\n", (524, 545), False, 'from autonetkit.design.utils.general import group_by\n'), ((573, 590), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (584, 590), False, 'from collections import defaultdict\n'), ((1226, 1243), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1237, 1243), False, 'from collections import defaultdict\n'), ((1275, 1310), 'ipaddress.IPv4Network', 'ipaddress.IPv4Network', (['"""10.0.0.0/8"""'], {}), "('10.0.0.0/8')\n", (1296, 1310), False, 'import ipaddress\n'), ((1395, 1430), 'autonetkit.design.utils.filters.broadcast_domains', 'filters.broadcast_domains', (['topology'], {}), '(topology)\n', (1420, 1430), False, 'from autonetkit.design.utils import filters\n'), ((1448, 1473), 'autonetkit.design.utils.general.group_by', 'group_by', (['bc_nodes', '"""asn"""'], {}), "(bc_nodes, 'asn')\n", (1456, 1473), False, 'from autonetkit.design.utils.general import group_by\n')]
#****************************************************************************** # (C) 2018, <NAME>, Austria * # * # The Space Python Library is free software; you can redistribute it and/or * # modify it under under the terms of the MIT License as published by the * # Massachusetts Institute of Technology. * # * # The Space Python Library 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 MIT License * # for more details. * #****************************************************************************** # Ground Simulation - NCTRS Module * # implements EGOS-NIS-NCTR-ICD-0002-i4r0.2 (Signed).pdf * #****************************************************************************** import socket, sys from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR import GRND.IF, GRND.NCTRSDU import UTIL.SYS, UTIL.TASK, UTIL.TCO, UTIL.TCP, UTIL.TIME ############# # constants # ############# SOCKET_TYPE = type(socket.socket()) #################### # global variables # #################### s_tmDUtype = None ########### # classes # ########### # ============================================================================= class TMreceiver(UTIL.TCP.Client): """NCTRS telemetry receiver interface - MCS side""" # --------------------------------------------------------------------------- def __init__(self): """Initialise attributes only""" modelTask = UTIL.TASK.s_processingTask UTIL.TCP.Client.__init__(self, modelTask) # --------------------------------------------------------------------------- def recvError(self, errorMessage): """ Read bytes from the data socket has failed, overloaded from UTIL.TCP.Client """ LOG_ERROR("TMreceiver.recvError: " + errorMessage, "NCTRS") # default implementation: disconnect from server self.disconnectFromServer() # --------------------------------------------------------------------------- def sendError(self, errorMessage): """ Send bytes from the data socket has failed, overloaded from UTIL.TCP.Client """ LOG_ERROR("TMreceiver.sendError: " + errorMessage, "NCTRS") # default implementation: disconnect from server self.disconnectFromServer() # --------------------------------------------------------------------------- def receiveCallback(self, socket, stateMask): """Callback when NCTRS has send data""" # read the TM data unit try: # note: automatic failure handling of derived method # UTIL.TCP.Client.recvError() cannot be used here, # because the derived method UTIL.TCP.Client.recv() # cannot be used by readNCTRSframe() tmDu = readNCTRSframe(self.dataSocket) except Exception as ex: # explicit failure handling self.recvError(str(ex)) return self.notifyTMdataUnit(tmDu) # --------------------------------------------------------------------------- def notifyTMdataUnit(self, tmDu): """TM frame received: hook for derived classes""" pass # --------------------------------------------------------------------------- def notifyError(self, errorMessage, data): """error notification: hook for derived classes""" pass # ============================================================================= class NCTRStmFields(object): """Helper class that contains static initialization attributes""" # --------------------------------------------------------------------------- def __init__(self): """Initialise attributes with default values""" self.spacecraftId = 0 self.dataStreamType = 0 self.virtualChannelId = 0 self.routeId = 0 self.sequenceFlag = 0 self.qualityFlag = 0 # ============================================================================= class TMsender(UTIL.TCP.SingleClientServer): """NCTRS telemetry sender interface - NCTRS side""" # --------------------------------------------------------------------------- def __init__(self, portNr, nctrsTMfields): """Initialise attributes only""" modelTask = UTIL.TASK.s_processingTask UTIL.TCP.SingleClientServer.__init__(self, modelTask, portNr) self.nctrsTMfields = nctrsTMfields # --------------------------------------------------------------------------- def sendTmDataUnit(self, tmDu): """Send the TM data unit to the TM receiver""" # ensure a correct size attribute tmDu.packetSize = len(tmDu) # this operation does not verify the contents of the DU self.send(tmDu.getBuffer()) # --------------------------------------------------------------------------- def sendFrame(self, tmFrame): """Send the TM frame to the TM receiver""" ertTime = UTIL.TCO.correlateToERTmissionEpoch(UTIL.TIME.getActualTime()) tmDu = createTMdataUnit() tmDu.setFrame(tmFrame) tmDu.spacecraftId = self.nctrsTMfields.spacecraftId tmDu.dataStreamType = self.nctrsTMfields.dataStreamType tmDu.virtualChannelId = self.nctrsTMfields.virtualChannelId tmDu.routeId = self.nctrsTMfields.routeId tmDu.earthReceptionTime = ertTime tmDu.sequenceFlag = self.nctrsTMfields.sequenceFlag tmDu.qualityFlag = self.nctrsTMfields.qualityFlag self.sendTmDataUnit(tmDu) # --------------------------------------------------------------------------- def receiveCallback(self, socket, stateMask): """Callback when the MCS has closed the connection""" # preform a dummy recv to force connection handling self.recv(1) # ============================================================================= class TCreceiver(UTIL.TCP.SingleClientServer): """NCTRS telecommand receiver interface - NCTRS side""" # --------------------------------------------------------------------------- def __init__(self, portNr, groundstationId): """Initialise attributes only""" modelTask = UTIL.TASK.s_processingTask UTIL.TCP.SingleClientServer.__init__(self, modelTask, portNr) self.groundstationId = groundstationId # --------------------------------------------------------------------------- def sendTcDataUnit(self, tcDu): """Send the TC data unit to the TC sender""" # ensure a correct size attribute tcDu.packetSize = len(tcDu) # this operation does not verify the contents of the DU self.send(tcDu.getBuffer()) # --------------------------------------------------------------------------- def receiveCallback(self, socket, stateMask): """Callback when the MCS has send data""" # read the TC data unit header tcDuHeader = self.recv(GRND.NCTRSDU.TC_DU_HEADER_BYTE_SIZE) if tcDuHeader == None: # failure handling was done automatically by derived logic return # consistency check tcDuHeaderLen = len(tcDuHeader) if tcDuHeaderLen != GRND.NCTRSDU.TC_DU_HEADER_BYTE_SIZE: LOG_ERROR("Read of TC DU header failed: invalid size: " + str(tcDuHeaderLen)) self.disconnectClient() return tcDu = GRND.NCTRSDU.TCdataUnit(tcDuHeader) # consistency check packetSize = tcDu.packetSize remainingSizeExpected = packetSize - GRND.NCTRSDU.TC_DU_HEADER_BYTE_SIZE if remainingSizeExpected <= 0: LOG_ERROR("Read of TC DU header failed: invalid packet size field: " + str(remainingSizeExpected)) self.disconnectClient() return # read the remaining bytes for the TC data unit tcRemaining = self.recv(remainingSizeExpected) if tcRemaining == None: # failure handling was done automatically by derived logic return # consistency check remainingSizeRead = len(tcRemaining) if remainingSizeRead != remainingSizeExpected: LOG_ERROR("Read of remaining TC DU failed: invalid remaining size: " + str(remainingSizeRead)) self.disconnectClient() return dataUnitType = tcDu.dataUnitType try: if dataUnitType == GRND.NCTRSDU.TC_PACKET_HEADER_DU_TYPE: # AD packet / BD segment tcDu.append(tcRemaining, GRND.NCTRSDU.TC_PACKET_HEADER_ATTRIBUTES) self.notifyTCpacketDataUnit(tcDu) elif dataUnitType == GRND.NCTRSDU.TC_CLTU_HEADER_DU_TYPE: # CLTU tcDu.append(tcRemaining, GRND.NCTRSDU.TC_CLTU_HEADER_ATTRIBUTES) self.notifyTCcltuDataUnit(tcDu) elif dataUnitType == GRND.NCTRSDU.TC_DIRECTIVES_DU_TYPE: # COP1 directive tcDu.append(tcRemaining, GRND.NCTRSDU.TC_DIRECTIVES_ATTRIBUTES) self.notifyTCdirectivesDataUnit(tcDu) else: LOG_ERROR("Read of TC DU header failed: invalid dataUnitType: " + str(dataUnitType)) self.disconnectClient() except Exception as ex: LOG_ERROR("Processing of received data unit failed: " + str(ex)) self.disconnectClient() # --------------------------------------------------------------------------- def notifyTCpacketDataUnit(self, tcPktDu): """AD packet / BD segment received""" # send UV ACCEPT confirmation if GRND.IF.s_configuration.grndAck1 == GRND.IF.ENABLE_ACK: LOG_INFO("generate ACK1 (TC_ACK_UV_ACCEPT_CONFIRM)") self.sendResponseDataUnit(tcPktDu, GRND.NCTRSDU.TC_ACK_UV_ACCEPT_CONFIRM) elif GRND.IF.s_configuration.grndAck1 == GRND.IF.ENABLE_NAK: LOG_WARNING("generate NAK1 (TC_ACK_UV_ACCEPT_FAILURE)") self.sendResponseDataUnit(tcPktDu, GRND.NCTRSDU.TC_ACK_UV_ACCEPT_FAILURE) else: LOG_WARNING("suppress ACK1 (TC_ACK_UV_ACCEPT_CONFIRM)") # send UV TRANSMIT confirmation if GRND.IF.s_configuration.grndAck2 == GRND.IF.ENABLE_ACK: LOG_INFO("generate ACK2 (TC_ACK_UV_TRANSMIT_CONFIRM)") self.sendResponseDataUnit(tcPktDu, GRND.NCTRSDU.TC_ACK_UV_TRANSMIT_CONFIRM) elif GRND.IF.s_configuration.grndAck2 == GRND.IF.ENABLE_NAK: LOG_ERROR("generate NAK2 (TC_ACK_UV_TRANSMIT_FAILURE)") self.sendResponseDataUnit(tcPktDu, GRND.NCTRSDU.TC_ACK_UV_TRANSMIT_FAILURE) else: LOG_WARNING("suppress ACK2 (TC_ACK_UV_TRANSMIT_CONFIRM)") # send UV TRANSFER confirmation # this verification stage does not provide ENABLE/DISABLE LOG_INFO("generate ACK3 (TC_ACK_UV_TRANSFER_CONFIRM)") self.sendResponseDataUnit(tcPktDu, GRND.NCTRSDU.TC_ACK_UV_TRANSFER_CONFIRM) # extract the TC packet from the NCTRS TC packet data unit try: packetData = tcPktDu.getTCpacket() except Exception as ex: self.notifyError("TC packet extraction failed", ex) return self.notifyTCpacket(packetData) # --------------------------------------------------------------------------- def notifyTCcltuDataUnit(self, tcCltuDu): """CLTU received""" # send UV ACCEPT confirmation if GRND.IF.s_configuration.grndAck1 == GRND.IF.ENABLE_ACK: LOG_INFO("generate ACK1 (TC_ACK_UV_ACCEPT_CONFIRM)") self.sendResponseDataUnit(tcCltuDu, GRND.NCTRSDU.TC_ACK_UV_ACCEPT_CONFIRM) elif GRND.IF.s_configuration.grndAck1 == GRND.IF.ENABLE_NAK: LOG_WARNING("generate NAK1 (TC_ACK_UV_ACCEPT_FAILURE)") self.sendResponseDataUnit(tcCltuDu, GRND.NCTRSDU.TC_ACK_UV_ACCEPT_FAILURE) else: LOG_WARNING("suppress ACK1 (TC_ACK_UV_ACCEPT_CONFIRM)") # send UV TRANSMIT confirmation if GRND.IF.s_configuration.grndAck2 == GRND.IF.ENABLE_ACK: LOG_INFO("generate ACK2 (TC_ACK_UV_TRANSMIT_CONFIRM)") self.sendResponseDataUnit(tcCltuDu, GRND.NCTRSDU.TC_ACK_UV_TRANSMIT_CONFIRM) elif GRND.IF.s_configuration.grndAck2 == GRND.IF.ENABLE_NAK: LOG_ERROR("generate NAK2 (TC_ACK_UV_TRANSMIT_FAILURE)") self.sendResponseDataUnit(tcCltuDu, GRND.NCTRSDU.TC_ACK_UV_TRANSMIT_FAILURE) else: LOG_WARNING("suppress ACK2 (TC_ACK_UV_TRANSMIT_CONFIRM)") # extract the CLTU from the NCTRS CLTU data unit try: cltu = tcCltuDu.getCltu() except Exception as ex: self.notifyError("CLTU extraction failed", ex) return self.notifyCltu(cltu) # --------------------------------------------------------------------------- def notifyTCdirectivesDataUnit(self, tcDirDu): """COP1 directive received""" LOG_ERROR("TCreceiver.notifyTCdirectivesDataUnit not implemented") sys.exit(-1) # --------------------------------------------------------------------------- def notifyError(self, errorMessage, data): """error notification: hook for derived classes""" pass # --------------------------------------------------------------------------- def notifyTCpacket(self, packetData): """TC packet received: hook for derived classes""" pass # --------------------------------------------------------------------------- def notifyCltu(self, cltu): """CLTU received: hook for derived classes""" pass # --------------------------------------------------------------------------- def sendResponseDataUnit(self, requestDataUnit, acknowledgement): """sends a response data unit from a request data unit""" ertTime = UTIL.TCO.correlateToERTmissionEpoch(UTIL.TIME.getActualTime()) tcRespDu = requestDataUnit.createResponseDataUnit() tcRespDu.time = ertTime tcRespDu.serviceType = requestDataUnit.serviceType tcRespDu.groundstationId = self.groundstationId tcRespDu.sequenceCounter = requestDataUnit.tcId tcRespDu.acknowledgement = acknowledgement tcRespDu.reason = 0 tcRespDu.spaceInQueue = 0 tcRespDu.nextADcounter = 0 tcRespDu.lastCLCW = [0, 0, 0, 0] self.sendTcDataUnit(tcRespDu) # ============================================================================= class TCsender(UTIL.TCP.Client): """NCTRS telecommand sender interface - SCOS side""" # --------------------------------------------------------------------------- def __init__(self): """Initialise attributes only""" modelTask = UTIL.TASK.s_processingTask UTIL.TCP.Client.__init__(self, modelTask) # --------------------------------------------------------------------------- def recvError(self, errorMessage): """ Read bytes from the data socket has failed, overloaded from UTIL.TCP.Client """ LOG_ERROR("TCsender.recvError: " + errorMessage, "NCTRS") # default implementation: disconnect from server self.disconnectFromServer() # --------------------------------------------------------------------------- def sendError(self, errorMessage): """ Send bytes from the data socket has failed, overloaded from UTIL.TCP.Client """ LOG_ERROR("TCsender.sendError: " + errorMessage, "NCTRS") # default implementation: disconnect from server self.disconnectFromServer() # --------------------------------------------------------------------------- def sendTcDataUnit(self, tcDu): """Send the TC data unit to the TC receiver""" # ensure a correct size attribute tcDu.packetSize = len(tcDu) # this operation does not verify the contents of the DU self.send(tcDu.getBuffer()) # --------------------------------------------------------------------------- def sendTCpacket(self, packetData): """Send the TC packet to the TC receiver""" packetDu = GRND.NCTRSDU.TCpacketDataUnit() packetDu.setTCpacket(packetData) self.sendTcDataUnit(packetDu) # --------------------------------------------------------------------------- def sendCltu(self, cltu): """Send the CLTU to the TC receiver""" cltuDu = GRND.NCTRSDU.TCcltuDataUnit() cltuDu.setCltu(cltu) self.sendTcDataUnit(cltuDu) # --------------------------------------------------------------------------- def receiveCallback(self, socket, stateMask): """Callback when NCTRS has send data""" # read the TC data unit header tcDuHeader = self.recv(GRND.NCTRSDU.TC_DU_HEADER_BYTE_SIZE) if tcDuHeader == None: # failure handling was done automatically by derived logic return # consistency check tcDuHeaderLen = len(tcDuHeader) if tcDuHeaderLen != GRND.NCTRSDU.TC_DU_HEADER_BYTE_SIZE: LOG_ERROR("Read of TC DU header failed: invalid size: " + str(tcDuHeaderLen), "NCTRS") self.disconnectFromServer() return tcDu = GRND.NCTRSDU.TCdataUnit(tcDuHeader) # consistency check packetSize = tcDu.packetSize remainingSizeExpected = packetSize - GRND.NCTRSDU.TC_DU_HEADER_BYTE_SIZE if remainingSizeExpected <= 0: LOG_ERROR("Read of TC DU header failed: invalid packet size field: " + str(remainingSizeExpected), "NCTRS") self.disconnectFromServer() return # read the remaining bytes for the TC data unit tcRemaining = self.recv(remainingSizeExpected) if tcRemaining == None: # failure handling was done automatically by derived logic return # consistency check remainingSizeRead = len(tcRemaining) if remainingSizeRead != remainingSizeExpected: LOG_ERROR("Read of remaining TC DU failed: invalid remaining size: " + str(remainingSizeRead), "NCTRS") self.disconnectFromServer() return dataUnitType = tcDu.dataUnitType if dataUnitType == GRND.NCTRSDU.TC_PACKET_RESPONSE_DU_TYPE: # AD packet / BD segment response tcDu.append(tcRemaining, GRND.NCTRSDU.TC_PACKET_RESPONSE_ATTRIBUTES) self.notifyTCpacketResponseDataUnit(tcDu) elif dataUnitType == GRND.NCTRSDU.TC_CLTU_RESPONSE_DU_TYPE: # CLTU response tcDu.append(tcRemaining, GRND.NCTRSDU.TC_CLTU_RESPONSE_ATTRIBUTES) self.notifyTCcltuResponseDataUnit(tcDu) elif dataUnitType == GRND.NCTRSDU.TC_LINK_STATUS_DU_TYPE: # Link status tcDu.append(tcRemaining, GRND.NCTRSDU.TC_LINK_STATUS_ATTRIBUTES) self.notifyTClinkStatusDataUnit(tcDu) else: LOG_ERROR("Read of TC DU header failed: invalid dataUnitType: " + str(dataUnitType), "NCTRS") self.disconnectFromServer() # --------------------------------------------------------------------------- def notifyTCpacketResponseDataUnit(self, tcPktRespDu): """AD packet / BD segment response received""" LOG_ERROR("TCsender.notifyTCpacketResponseDataUnit not implemented", "NCTRS") sys.exit(-1) # --------------------------------------------------------------------------- def notifyTCcltuResponseDataUnit(self, tcCltuRespDu): """CLTU response received""" LOG_ERROR("TCsender.notifyTCcltuResponseDataUnit not implemented", "NCTRS") sys.exit(-1) # --------------------------------------------------------------------------- def notifyTClinkStatusDataUnit(self, tcLinkStatDu): """Link status received""" LOG_ERROR("TCsender.notifyTClinkStatusDataUnit not implemented", "NCTRS") sys.exit(-1) # ============================================================================= class AdminMessageSender(UTIL.TCP.SingleClientServer): """NCTRS admin message sender interface - NCTRS side""" # --------------------------------------------------------------------------- def __init__(self, portNr, groundstationName): """Initialise attributes only""" modelTask = UTIL.TASK.s_processingTask UTIL.TCP.SingleClientServer.__init__(self, modelTask, portNr) self.groundstationName = groundstationName # --------------------------------------------------------------------------- def sendAdminMessageDataUnit(self, messageDu): """Send the admin message data unit to the admin message receiver""" # ensure a correct size attribute messageDu.packetSize = len(messageDu) # this operation does not verify the contents of the DU self.send(messageDu.getBuffer()) # --------------------------------------------------------------------------- def sendAdminMessageTM(self, eventId): """Send the TM admin message data unit""" messageDu = GRND.NCTRSDU.AdminMessageDataUnit() messageDu.set(GRND.NCTRSDU.ADMIN_MSG_TM, eventId) self.sendAdminMessageDataUnit(messageDu) # --------------------------------------------------------------------------- def sendAdminMessageTC(self, eventId, adCounter=0, vcId=0, mapId=0): """Send the TC admin message data unit""" messageDu = GRND.NCTRSDU.AdminMessageDataUnit() messageDu.set(GRND.NCTRSDU.ADMIN_MSG_TC, eventId, groundstationName=self.groundstationName, adCounter=adCounter, vcId=vcId, mapId=mapId) self.sendAdminMessageDataUnit(messageDu) # --------------------------------------------------------------------------- def receiveCallback(self, socket, stateMask): """Callback when the MCS has send data""" # preform a dummy recv to force connection handling self.recv(1) # --------------------------------------------------------------------------- def notifyError(self, errorMessage, data): """error notification: hook for derived classes""" pass # ============================================================================= class AdminMessageReceiver(UTIL.TCP.Client): """NCTRS admin message receiver interface - MCS side""" # --------------------------------------------------------------------------- def __init__(self): """Initialise attributes only""" modelTask = UTIL.TASK.s_processingTask UTIL.TCP.Client.__init__(self, modelTask) # --------------------------------------------------------------------------- def recvError(self, errorMessage): """ Read bytes from the data socket has failed, overloaded from UTIL.TCP.Client """ LOG_ERROR("AdminMessageReceiver.recvError: " + errorMessage, "NCTRS") # default implementation: disconnect from server self.disconnectFromServer() # --------------------------------------------------------------------------- def sendError(self, errorMessage): """ Send bytes from the data socket has failed, overloaded from UTIL.TCP.Client """ LOG_ERROR("AdminMessageReceiver.sendError: " + errorMessage, "NCTRS") # default implementation: disconnect from server self.disconnectFromServer() # --------------------------------------------------------------------------- def receiveCallback(self, socket, stateMask): """Callback when NCTRS has send data""" # read the admin message unit header messageHeader = self.recv(GRND.NCTRSDU.MESSAGE_HEADER_BYTE_SIZE) if messageHeader == None: # failure handling was done automatically by derived logic return # consistency check messageHeaderLen = len(messageHeader) if messageHeaderLen != GRND.NCTRSDU.MESSAGE_HEADER_BYTE_SIZE: LOG_ERROR("Read of admin message DU header failed: invalid size: " + str(messageHeaderLen), "NCTRS") self.disconnectFromServer() return messageDu = GRND.NCTRSDU.AdminMessageDataUnit(messageHeader) # consistency check packetSize = messageDu.packetSize remainingSizeExpected = packetSize - GRND.NCTRSDU.MESSAGE_HEADER_BYTE_SIZE if remainingSizeExpected <= 0: LOG_ERROR("Read of admin message DU header failed: invalid packet size field: " + str(remainingSizeExpected), "NCTRS") self.disconnectFromServer() return # read the remaining bytes for the TC data unit messageRemaining = self.recv(remainingSizeExpected) if messageRemaining == None: # failure handling was done automatically by derived logic return # consistency check remainingSizeRead = len(messageRemaining) if remainingSizeRead != remainingSizeExpected: LOG_ERROR("Read of remaining admin message DU failed: invalid remaining size: " + str(remainingSizeRead), "NCTRS") self.disconnectFromServer() return # set the message messageDu.setMessage(messageRemaining) self.notifyAdminMessageDataUnit(messageDu) # --------------------------------------------------------------------------- def notifyAdminMessageDataUnit(self, messageDu): """Admin message response received""" LOG_ERROR("AdminMessageReceiver.messageDu not implemented", "NCTRS") sys.exit(-1) ############# # functions # ############# # ----------------------------------------------------------------------------- def getTMdataUnitType(): """returns the NCTRS TM data unit type according to NCTRS_TM_DU_VERSION""" global s_tmDUtype if s_tmDUtype == None: nctrsTMversion = UTIL.SYS.s_configuration.NCTRS_TM_DU_VERSION if nctrsTMversion == "V0": s_tmDUtype = GRND.NCTRSDU.TM_V0_ERT_FORMAT elif nctrsTMversion == "V1_CDS1": s_tmDUtype = GRND.NCTRSDU.TM_V1_CDS1_ERT_FORMAT elif nctrsTMversion == "V1_CDS2": s_tmDUtype = GRND.NCTRSDU.TM_V1_CDS2_ERT_FORMAT elif nctrsTMversion == "V1_CDS3": s_tmDUtype = GRND.NCTRSDU.TM_V1_CDS3_ERT_FORMAT else: LOG_ERROR("Invalid NCTRS_TM_DU_VERSION " + nctrsTMversion, "NCTRS") sys.exit(-1) return s_tmDUtype # ----------------------------------------------------------------------------- def createTMdataUnit(binaryString=None): """creates a NCTRS TM data unit according to the NCTRS_TM_DU_VERSION""" tmDUtype = getTMdataUnitType() if s_tmDUtype == GRND.NCTRSDU.TM_V0_ERT_FORMAT: return GRND.NCTRSDU.TMdataUnitV0(binaryString) elif s_tmDUtype == GRND.NCTRSDU.TM_V1_CDS1_ERT_FORMAT: return GRND.NCTRSDU.TMdataUnitV1CDS1(binaryString) elif s_tmDUtype == GRND.NCTRSDU.TM_V1_CDS2_ERT_FORMAT: return GRND.NCTRSDU.TMdataUnitV1CDS2(binaryString) elif s_tmDUtype == GRND.NCTRSDU.TM_V1_CDS3_ERT_FORMAT: return GRND.NCTRSDU.TMdataUnitV1CDS3(binaryString) LOG_ERROR("Invalid s_tmDUtype " + str(s_tmDUtype), "NCTRS") sys.exit(-1) # ----------------------------------------------------------------------------- def readNCTRStmFrameHeader(fd): """creates a NCTRS TM data unit according to the NCTRS_TM_DU_VERSION""" # the function raises an exception when the read fails tmDUtype = getTMdataUnitType() if s_tmDUtype == GRND.NCTRSDU.TM_V0_ERT_FORMAT: tmDuHeaderByteSize = GRND.NCTRSDU.TM_DU_V0_HEADER_BYTE_SIZE elif s_tmDUtype == GRND.NCTRSDU.TM_V1_CDS1_ERT_FORMAT: tmDuHeaderByteSize = GRND.NCTRSDU.TM_DU_V1_CDS1_HEADER_BYTE_SIZE elif s_tmDUtype == GRND.NCTRSDU.TM_V1_CDS2_ERT_FORMAT: tmDuHeaderByteSize = GRND.NCTRSDU.TM_DU_V1_CDS2_HEADER_BYTE_SIZE elif s_tmDUtype == GRND.NCTRSDU.TM_V1_CDS3_ERT_FORMAT: tmDuHeaderByteSize = GRND.NCTRSDU.TM_DU_V1_CDS3_HEADER_BYTE_SIZE else: raise Error("Invalid s_tmDUtype " + str(s_tmDUtype)) # read the TM data unit header if type(fd) == SOCKET_TYPE: tmDuHeader = fd.recv(tmDuHeaderByteSize) else: tmDuHeader = fd.read(tmDuHeaderByteSize) # consistency check tmDuHeaderLen = len(tmDuHeader) if tmDuHeaderLen == 0: if type(fd) == SOCKET_TYPE: raise Error("empty data read") else: # end of file raise Error("") if tmDuHeaderLen != tmDuHeaderByteSize: raise Error("Read of TM DU header failed: invalid size: " + str(tmDuHeaderLen)) return tmDuHeader # ----------------------------------------------------------------------------- def readNCTRSframe(fd): """reads one NCTRS frame from fd, raise execption when there is an error""" # read the TM data unit header try: tmDuHeader = readNCTRStmFrameHeader(fd) except Exception as ex: raise Error(str(ex)) tmDu = createTMdataUnit(tmDuHeader) # consistency check packetSize = tmDu.packetSize remainingSizeExpected = packetSize - len(tmDuHeader) if remainingSizeExpected <= 0: raise Error("Read of TM DU header failed: invalid packet size field: " + str(remainingSizeExpected)) # read the remaining bytes for the TM data unit try: if type(fd) == SOCKET_TYPE: tmRemaining = fd.recv(remainingSizeExpected) else: tmRemaining = fd.read(remainingSizeExpected) except Exception as ex: raise Error("Read of remaining TM DU failed: " + str(ex)) # consistency check remainingSizeRead = len(tmRemaining) if remainingSizeRead != remainingSizeExpected: raise Error("Read of remaining TM DU failed: invalid remaining size: " + str(remainingSizeRead)) # TM frame tmDu.append(tmRemaining) return tmDu
[ "UTIL.SYS.LOG_WARNING", "socket.socket", "UTIL.SYS.Error", "UTIL.SYS.LOG_INFO", "sys.exit", "UTIL.SYS.LOG_ERROR" ]
[((1427, 1442), 'socket.socket', 'socket.socket', ([], {}), '()\n', (1440, 1442), False, 'import socket, sys\n'), ((26027, 26039), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (26035, 26039), False, 'import socket, sys\n'), ((2181, 2240), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (["('TMreceiver.recvError: ' + errorMessage)", '"""NCTRS"""'], {}), "('TMreceiver.recvError: ' + errorMessage, 'NCTRS')\n", (2190, 2240), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((2547, 2606), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (["('TMreceiver.sendError: ' + errorMessage)", '"""NCTRS"""'], {}), "('TMreceiver.sendError: ' + errorMessage, 'NCTRS')\n", (2556, 2606), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((10594, 10648), 'UTIL.SYS.LOG_INFO', 'LOG_INFO', (['"""generate ACK3 (TC_ACK_UV_TRANSFER_CONFIRM)"""'], {}), "('generate ACK3 (TC_ACK_UV_TRANSFER_CONFIRM)')\n", (10602, 10648), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((12708, 12774), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (['"""TCreceiver.notifyTCdirectivesDataUnit not implemented"""'], {}), "('TCreceiver.notifyTCdirectivesDataUnit not implemented')\n", (12717, 12774), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((12779, 12791), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (12787, 12791), False, 'import socket, sys\n'), ((14685, 14742), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (["('TCsender.recvError: ' + errorMessage)", '"""NCTRS"""'], {}), "('TCsender.recvError: ' + errorMessage, 'NCTRS')\n", (14694, 14742), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((15049, 15106), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (["('TCsender.sendError: ' + errorMessage)", '"""NCTRS"""'], {}), "('TCsender.sendError: ' + errorMessage, 'NCTRS')\n", (15058, 15106), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((18552, 18629), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (['"""TCsender.notifyTCpacketResponseDataUnit not implemented"""', '"""NCTRS"""'], {}), "('TCsender.notifyTCpacketResponseDataUnit not implemented', 'NCTRS')\n", (18561, 18629), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((18634, 18646), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (18642, 18646), False, 'import socket, sys\n'), ((18820, 18895), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (['"""TCsender.notifyTCcltuResponseDataUnit not implemented"""', '"""NCTRS"""'], {}), "('TCsender.notifyTCcltuResponseDataUnit not implemented', 'NCTRS')\n", (18829, 18895), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((18900, 18912), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (18908, 18912), False, 'import socket, sys\n'), ((19082, 19155), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (['"""TCsender.notifyTClinkStatusDataUnit not implemented"""', '"""NCTRS"""'], {}), "('TCsender.notifyTClinkStatusDataUnit not implemented', 'NCTRS')\n", (19091, 19155), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((19160, 19172), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (19168, 19172), False, 'import socket, sys\n'), ((21980, 22049), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (["('AdminMessageReceiver.recvError: ' + errorMessage)", '"""NCTRS"""'], {}), "('AdminMessageReceiver.recvError: ' + errorMessage, 'NCTRS')\n", (21989, 22049), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((22356, 22425), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (["('AdminMessageReceiver.sendError: ' + errorMessage)", '"""NCTRS"""'], {}), "('AdminMessageReceiver.sendError: ' + errorMessage, 'NCTRS')\n", (22365, 22425), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((24397, 24465), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (['"""AdminMessageReceiver.messageDu not implemented"""', '"""NCTRS"""'], {}), "('AdminMessageReceiver.messageDu not implemented', 'NCTRS')\n", (24406, 24465), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((24470, 24482), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (24478, 24482), False, 'import socket, sys\n'), ((9427, 9479), 'UTIL.SYS.LOG_INFO', 'LOG_INFO', (['"""generate ACK1 (TC_ACK_UV_ACCEPT_CONFIRM)"""'], {}), "('generate ACK1 (TC_ACK_UV_ACCEPT_CONFIRM)')\n", (9435, 9479), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((10008, 10062), 'UTIL.SYS.LOG_INFO', 'LOG_INFO', (['"""generate ACK2 (TC_ACK_UV_TRANSMIT_CONFIRM)"""'], {}), "('generate ACK2 (TC_ACK_UV_TRANSMIT_CONFIRM)')\n", (10016, 10062), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((11258, 11310), 'UTIL.SYS.LOG_INFO', 'LOG_INFO', (['"""generate ACK1 (TC_ACK_UV_ACCEPT_CONFIRM)"""'], {}), "('generate ACK1 (TC_ACK_UV_ACCEPT_CONFIRM)')\n", (11266, 11310), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((11841, 11895), 'UTIL.SYS.LOG_INFO', 'LOG_INFO', (['"""generate ACK2 (TC_ACK_UV_TRANSMIT_CONFIRM)"""'], {}), "('generate ACK2 (TC_ACK_UV_TRANSMIT_CONFIRM)')\n", (11849, 11895), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((27163, 27187), 'UTIL.SYS.Error', 'Error', (['"""empty data read"""'], {}), "('empty data read')\n", (27168, 27187), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((27230, 27239), 'UTIL.SYS.Error', 'Error', (['""""""'], {}), "('')\n", (27235, 27239), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((9663, 9718), 'UTIL.SYS.LOG_WARNING', 'LOG_WARNING', (['"""generate NAK1 (TC_ACK_UV_ACCEPT_FAILURE)"""'], {}), "('generate NAK1 (TC_ACK_UV_ACCEPT_FAILURE)')\n", (9674, 9718), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((9847, 9902), 'UTIL.SYS.LOG_WARNING', 'LOG_WARNING', (['"""suppress ACK1 (TC_ACK_UV_ACCEPT_CONFIRM)"""'], {}), "('suppress ACK1 (TC_ACK_UV_ACCEPT_CONFIRM)')\n", (9858, 9902), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((10248, 10303), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (['"""generate NAK2 (TC_ACK_UV_TRANSMIT_FAILURE)"""'], {}), "('generate NAK2 (TC_ACK_UV_TRANSMIT_FAILURE)')\n", (10257, 10303), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((10434, 10491), 'UTIL.SYS.LOG_WARNING', 'LOG_WARNING', (['"""suppress ACK2 (TC_ACK_UV_TRANSMIT_CONFIRM)"""'], {}), "('suppress ACK2 (TC_ACK_UV_TRANSMIT_CONFIRM)')\n", (10445, 10491), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((11495, 11550), 'UTIL.SYS.LOG_WARNING', 'LOG_WARNING', (['"""generate NAK1 (TC_ACK_UV_ACCEPT_FAILURE)"""'], {}), "('generate NAK1 (TC_ACK_UV_ACCEPT_FAILURE)')\n", (11506, 11550), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((11680, 11735), 'UTIL.SYS.LOG_WARNING', 'LOG_WARNING', (['"""suppress ACK1 (TC_ACK_UV_ACCEPT_CONFIRM)"""'], {}), "('suppress ACK1 (TC_ACK_UV_ACCEPT_CONFIRM)')\n", (11691, 11735), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((12082, 12137), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (['"""generate NAK2 (TC_ACK_UV_TRANSMIT_FAILURE)"""'], {}), "('generate NAK2 (TC_ACK_UV_TRANSMIT_FAILURE)')\n", (12091, 12137), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((12269, 12326), 'UTIL.SYS.LOG_WARNING', 'LOG_WARNING', (['"""suppress ACK2 (TC_ACK_UV_TRANSMIT_CONFIRM)"""'], {}), "('suppress ACK2 (TC_ACK_UV_TRANSMIT_CONFIRM)')\n", (12280, 12326), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((25191, 25258), 'UTIL.SYS.LOG_ERROR', 'LOG_ERROR', (["('Invalid NCTRS_TM_DU_VERSION ' + nctrsTMversion)", '"""NCTRS"""'], {}), "('Invalid NCTRS_TM_DU_VERSION ' + nctrsTMversion, 'NCTRS')\n", (25200, 25258), False, 'from UTIL.SYS import Error, LOG, LOG_INFO, LOG_WARNING, LOG_ERROR\n'), ((25265, 25277), 'sys.exit', 'sys.exit', (['(-1)'], {}), '(-1)\n', (25273, 25277), False, 'import socket, sys\n')]
""" Run Intervals. Takes 3 values from user, counts down intervals. wanted: Data class that holds state """ from datetime import timedelta import time import toga from toga.style import Pack from toga.style.pack import COLUMN, ROW class RunIntervals(toga.App): """ __init__ values in __init__.py: runsNumber=5, runsLength=5, breakLength=1, currentStatus='inactive', displayTime=0, runStartTime=0 """ def startup(self): """ Define box & visual elements. For each individual input, must have: a) toga.Label b) toga.TextInput c) toga.Button d) add the above attributes to mainBox Take values from user or use defaults, add to mainBox """ mainBox = toga.Box(style=Pack(direction=COLUMN)) # intervals count runIntLabel = toga.Label( "How many intervals to run? Hit Submit to use default of 5 total:", style=Pack(padding=(0, 5)) ) self.runIntInput = toga.TextInput(style=Pack(flex=1)) runIntBox = toga.Box(style=Pack(direction=ROW, padding=5)) runIntBox.add(runIntLabel) runIntBox.add(self.runIntInput) runIntButton = toga.Button( 'Submit', on_press=self.runInt, style=Pack(padding=5) ) #how long each interval runLengthLabel = toga.Label( 'How long should each running interval be? Hit Submit to use default of 5 minutes:', style=Pack(padding=(0, 5)) ) self.runLengthInput = toga.TextInput(style=Pack(flex=1)) runLengthBox = toga.Box(style=Pack(direction=ROW, padding=5)) runLengthBox.add(runLengthLabel) runLengthBox.add(self.runLengthInput) runLengthButton = toga.Button( 'Submit', on_press=self.runLength, style=Pack(padding=5) ) #how long are breaks breakLengthLabel = toga.Label( 'How long should breaks between runs be? Hit Submit to use default of 1 minute: ', style=Pack(padding=(0, 5)) ) self.breakLengthInput = toga.TextInput(style=Pack(flex=1)) breakLengthBox = toga.Box(style=Pack(direction=ROW, padding=5)) breakLengthBox.add(breakLengthLabel) breakLengthBox.add(self.breakLengthInput) breakLengthButton = toga.Button( 'Submit', on_press=self.breakLength, style=Pack(padding=5) ) #Start button # if values for all of the above, then Start button startLabel = toga.Label( 'Start!', style=Pack(padding=(0, 5)) ) startBox = toga.Box(style=Pack(direction=ROW, padding=5)) startBox.add(startLabel) startButton = toga.Button( 'Start!', on_press=self.start, style=Pack(padding=5) ) mainBox.add(runIntBox) mainBox.add(runIntButton) mainBox.add(runLengthBox) mainBox.add(runLengthButton) mainBox.add(breakLengthBox) mainBox.add(breakLengthButton) # would like to refresh and only display this once all 3 values have been entered mainBox.add(startBox) mainBox.add(startButton) if currentStatus == "active": # only start displaying timer stuff if currentStatus is valid mainBox.add(timeBox) pass self.main_window = toga.MainWindow(title=self.formal_name) self.main_window.content = mainBox self.main_window.show() def runInt(self, widget): """ Output number of intervals """ runsNumber = self.runIntInput.value self.main_window.info_dialog( 'Hi there!', "You will be running {} intervals today.".format(runsNumber) ) def runLength(self, widget): """ Output length of intervals """ runsLength = self.runLengthInput.value self.main_window.info_dialog( 'Hi there!', "You will be running each interval at {} minutes.".format(runsLength) ) def breakLength(self, widget): """ Output length of breaks """ breaksLength = self.breakLengthInput.value self.main_window.info_dialog( 'Hi there!', "Your breaks will be {} minute(s) long.".format(breaksLength) ) def mainTimer(self, toWait): """ Timer to display to window. Does not care what kind of timer it is. this will output a time, calculated dynamically based on runStartTime """ return timedelta(seconds='toWait') def displayTimer(self): """ just to display mainTimer output, not calculate it does this need mainBox? """ timeLabel = toga.Label( "Seconds left: {}".format(mainTimer(displayTime)), style=Pack(padding=(0, 5)) ) timeBox = toga.Box(style=Pack(direction=ROW, padding=5)) timeBox.add(timeLabel) def start(self, widget): """ Iterate through intervals and breaks, as defined in runInt(), runLength(), & breakLength() """ runStartTime = time.time() currentStatus = "active" runsNumber = int(self.runIntInput.value) # should not have to repeat this. runsLength = int(self.runLengthInput.value) loopNum = runsNumber intSeconds = runsLength * 60 # seconds breaksLength = self.breakLengthInput.value # ibid 152 walkinglength = int(breaksLength) breakSeconds = walkinglength * 60 # seconds # TTS: "Warm up, brisk walk for 5 minutes" # DELETE print("loopNum: {}".format(loopNum)) print("interval seconds: {}".format(intSeconds)) print("break seconds: {}".format(breakSeconds)) while loopNum > 0: runLabel = toga.Label( "You are running", style=Pack(padding=(0, 5)) ) runLabelBox = toga.Box(style=Pack(direction=ROW, padding=5)) runLabelBox.add(runLabel) mainBox.add(runLabelBox) mainTimer(intSeconds) if loopNum == 1: # create Label that says "you're done!" and add it to mainBox # TODO: text to speech "You're done! Great job!" print() else: # create Label that says "you're walking" and add it to mainBox mainTimer(breakSeconds) # TODO: TTS "You're walking" # - ideally one long beep before TTS time.sleep(breakSeconds) loopNum -= 1 # TTS: "Cool down, walk and chill out and stretch for 5 minutes. Take it easy and eat something delicious that you love." def main(): return RunIntervals()
[ "toga.style.Pack", "toga.MainWindow", "time.sleep", "datetime.timedelta", "time.time" ]
[((3510, 3549), 'toga.MainWindow', 'toga.MainWindow', ([], {'title': 'self.formal_name'}), '(title=self.formal_name)\n', (3525, 3549), False, 'import toga\n'), ((4719, 4746), 'datetime.timedelta', 'timedelta', ([], {'seconds': '"""toWait"""'}), "(seconds='toWait')\n", (4728, 4746), False, 'from datetime import timedelta\n'), ((5324, 5335), 'time.time', 'time.time', ([], {}), '()\n', (5333, 5335), False, 'import time\n'), ((777, 799), 'toga.style.Pack', 'Pack', ([], {'direction': 'COLUMN'}), '(direction=COLUMN)\n', (781, 799), False, 'from toga.style import Pack\n'), ((964, 984), 'toga.style.Pack', 'Pack', ([], {'padding': '(0, 5)'}), '(padding=(0, 5))\n', (968, 984), False, 'from toga.style import Pack\n'), ((1043, 1055), 'toga.style.Pack', 'Pack', ([], {'flex': '(1)'}), '(flex=1)\n', (1047, 1055), False, 'from toga.style import Pack\n'), ((1093, 1123), 'toga.style.Pack', 'Pack', ([], {'direction': 'ROW', 'padding': '(5)'}), '(direction=ROW, padding=5)\n', (1097, 1123), False, 'from toga.style import Pack\n'), ((1311, 1326), 'toga.style.Pack', 'Pack', ([], {'padding': '(5)'}), '(padding=5)\n', (1315, 1326), False, 'from toga.style import Pack\n'), ((1526, 1546), 'toga.style.Pack', 'Pack', ([], {'padding': '(0, 5)'}), '(padding=(0, 5))\n', (1530, 1546), False, 'from toga.style import Pack\n'), ((1608, 1620), 'toga.style.Pack', 'Pack', ([], {'flex': '(1)'}), '(flex=1)\n', (1612, 1620), False, 'from toga.style import Pack\n'), ((1661, 1691), 'toga.style.Pack', 'Pack', ([], {'direction': 'ROW', 'padding': '(5)'}), '(direction=ROW, padding=5)\n', (1665, 1691), False, 'from toga.style import Pack\n'), ((1897, 1912), 'toga.style.Pack', 'Pack', ([], {'padding': '(5)'}), '(padding=5)\n', (1901, 1912), False, 'from toga.style import Pack\n'), ((2107, 2127), 'toga.style.Pack', 'Pack', ([], {'padding': '(0, 5)'}), '(padding=(0, 5))\n', (2111, 2127), False, 'from toga.style import Pack\n'), ((2191, 2203), 'toga.style.Pack', 'Pack', ([], {'flex': '(1)'}), '(flex=1)\n', (2195, 2203), False, 'from toga.style import Pack\n'), ((2246, 2276), 'toga.style.Pack', 'Pack', ([], {'direction': 'ROW', 'padding': '(5)'}), '(direction=ROW, padding=5)\n', (2250, 2276), False, 'from toga.style import Pack\n'), ((2494, 2509), 'toga.style.Pack', 'Pack', ([], {'padding': '(5)'}), '(padding=5)\n', (2498, 2509), False, 'from toga.style import Pack\n'), ((2676, 2696), 'toga.style.Pack', 'Pack', ([], {'padding': '(0, 5)'}), '(padding=(0, 5))\n', (2680, 2696), False, 'from toga.style import Pack\n'), ((2741, 2771), 'toga.style.Pack', 'Pack', ([], {'direction': 'ROW', 'padding': '(5)'}), '(direction=ROW, padding=5)\n', (2745, 2771), False, 'from toga.style import Pack\n'), ((2915, 2930), 'toga.style.Pack', 'Pack', ([], {'padding': '(5)'}), '(padding=5)\n', (2919, 2930), False, 'from toga.style import Pack\n'), ((5004, 5024), 'toga.style.Pack', 'Pack', ([], {'padding': '(0, 5)'}), '(padding=(0, 5))\n', (5008, 5024), False, 'from toga.style import Pack\n'), ((5068, 5098), 'toga.style.Pack', 'Pack', ([], {'direction': 'ROW', 'padding': '(5)'}), '(direction=ROW, padding=5)\n', (5072, 5098), False, 'from toga.style import Pack\n'), ((6777, 6801), 'time.sleep', 'time.sleep', (['breakSeconds'], {}), '(breakSeconds)\n', (6787, 6801), False, 'import time\n'), ((6090, 6110), 'toga.style.Pack', 'Pack', ([], {'padding': '(0, 5)'}), '(padding=(0, 5))\n', (6094, 6110), False, 'from toga.style import Pack\n'), ((6170, 6200), 'toga.style.Pack', 'Pack', ([], {'direction': 'ROW', 'padding': '(5)'}), '(direction=ROW, padding=5)\n', (6174, 6200), False, 'from toga.style import Pack\n')]
# Advent of Code # Day 1 Problem 1 import pandas as pd nums = pd.read_csv('adventofcode2020_day1.csv') numlist = nums.values.tolist() flatList = [item for elem in numlist for item in elem] for i in range(len(flatList)): testnum = int(flatList[i]) neednum = 2020 - testnum if neednum in flatList: print(testnum * neednum) break else: continue sortednums = sorted(flatList) print(sortednums[::-1]) for x in range(len(sortednums)): num1 = sortednums[x] for y in range(x, len(sortednums)): num2 = sortednums[y] testnum = 2020 - num1 - num2 if testnum in sortednums: print(testnum * num1 * num2) break else: continue
[ "pandas.read_csv" ]
[((65, 105), 'pandas.read_csv', 'pd.read_csv', (['"""adventofcode2020_day1.csv"""'], {}), "('adventofcode2020_day1.csv')\n", (76, 105), True, 'import pandas as pd\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- import time from bms_state_machine import BMSChargeStateMachine, BMSChargeModel, BMSChargeController # 48V 16S LiFePO4 Battery # Absorption: 58V (56.4 for longer life) # Float: 54.4V # Restart bulk voltage: Float-0.8 (max of 54V) # Inverter Cut-off: 42.8V-48V (depending on size of load and voltage drop etc) bms_controller = BMSChargeController(charge_bulk_current=160, charge_absorb_voltage=58.4, \ charge_float_voltage=54.4, time_min_absorb=0.5, rebulk_voltage=53.6) # or 30 seconds for the simulation ret = bms_controller.start_charging() print ("{0}, Start Charging: {1}".format(bms_controller, ret)) # simulated battery voltage bat_voltage = 42.8 counter = 0 while (True): charge_current = 0.0 is_state_changed = bms_controller.update_battery_data(bat_voltage, charge_current) state = bms_controller.get_state() charge_current = bms_controller.get_charge_current() print ("Battery Voltage: {0}, Charge Current: {1}, Charge State: {2}, State Changed: {3}".format(bat_voltage, charge_current, state, is_state_changed)) time.sleep(1) # update simulated values if (is_state_changed): if (state == "absorb_chg"): bat_voltage = 58.2 elif (state == "float_chg"): bat_voltage = 56.1 if (state == "bulk_chg"): bat_voltage += 1.8 elif (state == "absorb_chg"): if (charge_current > 0): bat_voltage += charge_current * 0.1 elif (charge_current == 0): bat_voltage -= 0.01 if (counter > 5): counter += 1 if (counter > 15): bat_voltage = 54 counter = 0 elif (state == "float_chg"): counter += 1 if (counter > 5) : bat_voltage = 53 if (charge_current > 0): bat_voltage += charge_current * 0.1 elif (charge_current == 0): bat_voltage -= 0.03
[ "bms_state_machine.BMSChargeController", "time.sleep" ]
[((376, 521), 'bms_state_machine.BMSChargeController', 'BMSChargeController', ([], {'charge_bulk_current': '(160)', 'charge_absorb_voltage': '(58.4)', 'charge_float_voltage': '(54.4)', 'time_min_absorb': '(0.5)', 'rebulk_voltage': '(53.6)'}), '(charge_bulk_current=160, charge_absorb_voltage=58.4,\n charge_float_voltage=54.4, time_min_absorb=0.5, rebulk_voltage=53.6)\n', (395, 521), False, 'from bms_state_machine import BMSChargeStateMachine, BMSChargeModel, BMSChargeController\n'), ((1095, 1108), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1105, 1108), False, 'import time\n')]
# -*- coding: utf-8 -*- import pytest from numpy import pi from os.path import join from pyleecan.Classes.LamSlotWind import LamSlotWind from pyleecan.Classes.SlotW11 import SlotW11 from pyleecan.Classes.WindingDW1L import WindingDW1L from pyleecan.Classes.CondType12 import CondType12 from pyleecan.Functions.load import load from pyleecan.definitions import DATA_DIR @pytest.fixture(scope="module") def IPMSM_A(): IPMSM_A = load(join(DATA_DIR, "Machine", "IPMSM_A.json")) return IPMSM_A @pytest.mark.METHODS class Test_Electrical(object): def test_resistance(self, IPMSM_A): """Check that resistance computation is correct""" result = IPMSM_A.stator.comp_resistance_wind() assert result == pytest.approx(0.035951, abs=0.00001) def test_DQ_axis_rotor(self, IPMSM_A): """Check that the DQ axis are correct for the rotor""" d_axis = IPMSM_A.rotor.comp_angle_d_axis() assert d_axis == pytest.approx(pi / 8, abs=0.0001) q_axis = IPMSM_A.rotor.comp_angle_q_axis() assert q_axis == pytest.approx(2 * pi / 8, abs=0.0001) def test_DQ_axis_stator(self, IPMSM_A): """Check that the DQ axis are correct for the stator""" d_axis = IPMSM_A.stator.comp_angle_d_axis() assert d_axis == pytest.approx(1.3086, abs=0.001) q_axis = IPMSM_A.stator.comp_angle_q_axis() assert q_axis == pytest.approx(1.3086 + pi / 8, abs=0.0001) def test_comp_rot_dir(self, IPMSM_A): """Check that the computation of the rot dir is correct""" rot_dir = IPMSM_A.stator.comp_rot_dir() assert rot_dir == -1 def test_comp_rot_dir_reverse_wind(self, IPMSM_A): """Check that the computation of the rot dir is correct when reversing the winding""" IPMSM_B = IPMSM_A.copy() IPMSM_B.stator.winding.is_reverse_wind = ( not IPMSM_B.stator.winding.is_reverse_wind ) rot_dir = IPMSM_B.stator.comp_rot_dir() assert rot_dir == 1
[ "pytest.fixture", "pytest.approx", "os.path.join" ]
[((373, 403), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (387, 403), False, 'import pytest\n'), ((438, 479), 'os.path.join', 'join', (['DATA_DIR', '"""Machine"""', '"""IPMSM_A.json"""'], {}), "(DATA_DIR, 'Machine', 'IPMSM_A.json')\n", (442, 479), False, 'from os.path import join\n'), ((733, 767), 'pytest.approx', 'pytest.approx', (['(0.035951)'], {'abs': '(1e-05)'}), '(0.035951, abs=1e-05)\n', (746, 767), False, 'import pytest\n'), ((953, 986), 'pytest.approx', 'pytest.approx', (['(pi / 8)'], {'abs': '(0.0001)'}), '(pi / 8, abs=0.0001)\n', (966, 986), False, 'import pytest\n'), ((1064, 1101), 'pytest.approx', 'pytest.approx', (['(2 * pi / 8)'], {'abs': '(0.0001)'}), '(2 * pi / 8, abs=0.0001)\n', (1077, 1101), False, 'import pytest\n'), ((1288, 1320), 'pytest.approx', 'pytest.approx', (['(1.3086)'], {'abs': '(0.001)'}), '(1.3086, abs=0.001)\n', (1301, 1320), False, 'import pytest\n'), ((1399, 1441), 'pytest.approx', 'pytest.approx', (['(1.3086 + pi / 8)'], {'abs': '(0.0001)'}), '(1.3086 + pi / 8, abs=0.0001)\n', (1412, 1441), False, 'import pytest\n')]
import numpy as np def random_policy(env): counter = 0 total_rewards = 0 reward = None rewardTracker = [] while reward != 1: env.render() state, reward, done, info = env.step(env.action_space.sample()) total_rewards += reward if done: rewardTracker.append(total_rewards) env.reset() counter += 1 print("Solved in {} Steps with a average return of {}".format(counter, sum(rewardTracker) / len(rewardTracker))) def epsilon_greedy(env, epsilon, Q, state, episode): n_actions = env.action_space.n if np.random.rand() > epsilon: # adding a noise to the best action from Q action = np.argmax(Q[state, :] + np.random.randn(1, n_actions) / (episode / n_actions)) else: action = env.action_space.sample() # reduce the epsilon number epsilon -= 10 ** -5 return action, epsilon def q_learning(env, alpha, gamma, epsilon, episodes, training_steps): Q = np.zeros([env.observation_space.n, env.action_space.n]) reward_tracker = [] for episode in range(1, episodes + 1): total_rewards = 0 state = env.reset() for step in range(1, training_steps): action, epsilon = epsilon_greedy(env, epsilon, Q, state, episode) next_state, reward, done, info = env.step(action) Q[state, action] += alpha * (reward + gamma * np.max(Q[next_state]) - Q[state, action]) state = next_state total_rewards += reward reward_tracker.append(total_rewards) if episode % (episodes * .10) == 0 and episode != 0: print('Epsilon {:04.3f} Episode {}'.format(epsilon, episode)) print("Average Total Return: {}".format(sum(reward_tracker) / episode)) if (sum(reward_tracker[episode - 100:episode]) / 100.0) > .78: print('Solved after {} episodes with average return of {}' .format(episode - 100, sum(reward_tracker[episode - 100:episode]) / 100.0)) return Q return Q
[ "numpy.zeros", "numpy.random.randn", "numpy.random.rand", "numpy.max" ]
[((999, 1054), 'numpy.zeros', 'np.zeros', (['[env.observation_space.n, env.action_space.n]'], {}), '([env.observation_space.n, env.action_space.n])\n', (1007, 1054), True, 'import numpy as np\n'), ((600, 616), 'numpy.random.rand', 'np.random.rand', ([], {}), '()\n', (614, 616), True, 'import numpy as np\n'), ((720, 749), 'numpy.random.randn', 'np.random.randn', (['(1)', 'n_actions'], {}), '(1, n_actions)\n', (735, 749), True, 'import numpy as np\n'), ((1423, 1444), 'numpy.max', 'np.max', (['Q[next_state]'], {}), '(Q[next_state])\n', (1429, 1444), True, 'import numpy as np\n')]
""" :copyright: (c) 2019 Pinn Technologies, Inc. :license: MIT """ def test_import(): import pinn def test_configuration_error(): import pinn try: pinn.User.create() except pinn.errors.ConfigurationError: pass def test_authentication_error(): import pinn pinn.secret_key = 'foo' try: pinn.User.create() except pinn.errors.AuthenticationError: pass
[ "pinn.User.create" ]
[((171, 189), 'pinn.User.create', 'pinn.User.create', ([], {}), '()\n', (187, 189), False, 'import pinn\n'), ((342, 360), 'pinn.User.create', 'pinn.User.create', ([], {}), '()\n', (358, 360), False, 'import pinn\n')]
"""Sliding windows for connectivity functions.""" from frites.io import set_log_level, logger import numpy as np def define_windows(times, windows=None, slwin_len=None, slwin_start=None, slwin_stop=None, slwin_step=None, verbose=None): """Define temporal windows. This function can be used to either manually define temporal windows either automatic sliding windows. Note that every input parameters should be in the time domain (e.g seconds or milliseconds). Parameters ---------- times : array_like Time vector windows : array_like | None Manual windows (e.g (.1, .2) or [(.1, .2), (.4, .5)]). slwin_len : float | None Length of each sliding (e.g .2 produces 200ms window length). slwin_start : float | None Time point for starting sliding windows (e.g 0.1). If None, sliding windows will start from the first time point. slwin_stop : float | None Time point for ending sliding windows (e.g 1.5). If None, sliding windows will finish at the last time point. slwin_step : float | None Temporal step between each temporal window (e.g .1 means that each consecutive windows are going to be separated by 100ms). This parameter can be used to define either overlapping or non-overlapping windows. If None, slwin_step is going to be set to slwin_step in order to produce consecutive non-overlapping windows. Returns ------- win_sample : array_like Array of shape (n_windows, 2) of temporal indexes defining where each window (start, finish) mean_time : array_like Mean time vector inside each defined window of shape (n_windows,) See also -------- plot_windows """ set_log_level(verbose) assert isinstance(times, np.ndarray) logger.info("Defining temporal windows") stamp = times[1] - times[0] # ------------------------------------------------------------------------- # build windows if (windows is None) and (slwin_len is None): logger.info(" No input detected. Full time window is used") win_time = np.array([[times[0], times[-1]]]) elif windows is not None: logger.info(" Manual definition of windows") win_time = np.atleast_2d(windows) elif slwin_len is not None: # manage empty inputs if slwin_start is None: slwin_start = times[0] # noqa if slwin_stop is None: slwin_stop = times[-1] # noqa if slwin_step is None: slwin_step = slwin_len + stamp # noqa logger.info(f" Definition of sliding windows (len={slwin_len}, " f"start={slwin_start}, stop={slwin_stop}, " f"step={slwin_step})") # build the sliding windows sl_start = np.arange(slwin_start, slwin_stop - slwin_len, slwin_step) sl_stop = np.arange(slwin_start + slwin_len, slwin_stop, slwin_step) if len(sl_start) != len(sl_stop): min_len = min(len(sl_start), len(sl_stop)) sl_start, sl_stop = sl_start[0:min_len], sl_stop[0:min_len] win_time = np.c_[sl_start, sl_stop] assert (win_time.ndim == 2) and (win_time.shape[1] == 2) # ------------------------------------------------------------------------- # time to sample conversion win_sample = np.zeros_like(win_time, dtype=int) times = times.reshape(-1, 1) for n_k, k in enumerate(win_time): win_sample[n_k, :] = np.argmin(np.abs(times - k), axis=0) logger.info(f" {win_sample.shape[0]} windows defined") return win_sample, win_time.mean(1) def plot_windows(times, win_sample, x=None, title='', r_min=-.75, r_max=.75): """Simple plotting function for representing windows. Parameters ---------- times : array_like Times vector of shape (n_times,) win_sample : array_like Windows in samples. x : array_like | None A signal to use as a background. If None, a pure sine is generated with 100ms period is generated title : string | '' String title to attach to the figure r_min, r_max : float | -.75, .75 Window are represented by squares. Those two parameters can be used to control where box start and finish along the y-axis. Returns ------- ax : gca The matplotlib current axes See also -------- define_windows """ import matplotlib.pyplot as plt from matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle if x is not None: # plot the sine plt.plot(times, x) # plot the windows win_time = times[win_sample] r_red, r_blue = [], [] for n_k, k in enumerate(win_time): if n_k % 2 == 0: r_red += [Rectangle((k[0], r_min), k[1] - k[0], r_max - r_min)] elif n_k % 2 == 1: r_blue += [Rectangle((k[0], r_min), k[1] - k[0], r_max - r_min)] pc_blue = PatchCollection(r_blue, alpha=.5, color='blue') pc_red = PatchCollection(r_red, alpha=.5, color='red') plt.gca().add_collection(pc_blue) plt.gca().add_collection(pc_red) plt.title(title) plt.xlim(times[0], times[-1]) return plt.gca()
[ "frites.io.set_log_level", "frites.io.logger.info", "numpy.atleast_2d", "numpy.abs", "matplotlib.patches.Rectangle", "matplotlib.pyplot.gca", "matplotlib.pyplot.plot", "matplotlib.collections.PatchCollection", "numpy.array", "matplotlib.pyplot.title", "matplotlib.pyplot.xlim", "numpy.zeros_lik...
[((1791, 1813), 'frites.io.set_log_level', 'set_log_level', (['verbose'], {}), '(verbose)\n', (1804, 1813), False, 'from frites.io import set_log_level, logger\n'), ((1859, 1899), 'frites.io.logger.info', 'logger.info', (['"""Defining temporal windows"""'], {}), "('Defining temporal windows')\n", (1870, 1899), False, 'from frites.io import set_log_level, logger\n'), ((3391, 3425), 'numpy.zeros_like', 'np.zeros_like', (['win_time'], {'dtype': 'int'}), '(win_time, dtype=int)\n', (3404, 3425), True, 'import numpy as np\n'), ((3568, 3625), 'frites.io.logger.info', 'logger.info', (['f""" {win_sample.shape[0]} windows defined"""'], {}), "(f' {win_sample.shape[0]} windows defined')\n", (3579, 3625), False, 'from frites.io import set_log_level, logger\n'), ((5020, 5068), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['r_blue'], {'alpha': '(0.5)', 'color': '"""blue"""'}), "(r_blue, alpha=0.5, color='blue')\n", (5035, 5068), False, 'from matplotlib.collections import PatchCollection\n'), ((5081, 5127), 'matplotlib.collections.PatchCollection', 'PatchCollection', (['r_red'], {'alpha': '(0.5)', 'color': '"""red"""'}), "(r_red, alpha=0.5, color='red')\n", (5096, 5127), False, 'from matplotlib.collections import PatchCollection\n'), ((5206, 5222), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (5215, 5222), True, 'import matplotlib.pyplot as plt\n'), ((5227, 5256), 'matplotlib.pyplot.xlim', 'plt.xlim', (['times[0]', 'times[-1]'], {}), '(times[0], times[-1])\n', (5235, 5256), True, 'import matplotlib.pyplot as plt\n'), ((5269, 5278), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (5276, 5278), True, 'import matplotlib.pyplot as plt\n'), ((2092, 2154), 'frites.io.logger.info', 'logger.info', (['""" No input detected. Full time window is used"""'], {}), "(' No input detected. Full time window is used')\n", (2103, 2154), False, 'from frites.io import set_log_level, logger\n'), ((2174, 2207), 'numpy.array', 'np.array', (['[[times[0], times[-1]]]'], {}), '([[times[0], times[-1]]])\n', (2182, 2207), True, 'import numpy as np\n'), ((4660, 4678), 'matplotlib.pyplot.plot', 'plt.plot', (['times', 'x'], {}), '(times, x)\n', (4668, 4678), True, 'import matplotlib.pyplot as plt\n'), ((2246, 2293), 'frites.io.logger.info', 'logger.info', (['""" Manual definition of windows"""'], {}), "(' Manual definition of windows')\n", (2257, 2293), False, 'from frites.io import set_log_level, logger\n'), ((2313, 2335), 'numpy.atleast_2d', 'np.atleast_2d', (['windows'], {}), '(windows)\n', (2326, 2335), True, 'import numpy as np\n'), ((3537, 3554), 'numpy.abs', 'np.abs', (['(times - k)'], {}), '(times - k)\n', (3543, 3554), True, 'import numpy as np\n'), ((5131, 5140), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (5138, 5140), True, 'import matplotlib.pyplot as plt\n'), ((5169, 5178), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (5176, 5178), True, 'import matplotlib.pyplot as plt\n'), ((2619, 2755), 'frites.io.logger.info', 'logger.info', (['f""" Definition of sliding windows (len={slwin_len}, start={slwin_start}, stop={slwin_stop}, step={slwin_step})"""'], {}), "(\n f' Definition of sliding windows (len={slwin_len}, start={slwin_start}, stop={slwin_stop}, step={slwin_step})'\n )\n", (2630, 2755), False, 'from frites.io import set_log_level, logger\n'), ((2849, 2907), 'numpy.arange', 'np.arange', (['slwin_start', '(slwin_stop - slwin_len)', 'slwin_step'], {}), '(slwin_start, slwin_stop - slwin_len, slwin_step)\n', (2858, 2907), True, 'import numpy as np\n'), ((2927, 2985), 'numpy.arange', 'np.arange', (['(slwin_start + slwin_len)', 'slwin_stop', 'slwin_step'], {}), '(slwin_start + slwin_len, slwin_stop, slwin_step)\n', (2936, 2985), True, 'import numpy as np\n'), ((4848, 4900), 'matplotlib.patches.Rectangle', 'Rectangle', (['(k[0], r_min)', '(k[1] - k[0])', '(r_max - r_min)'], {}), '((k[0], r_min), k[1] - k[0], r_max - r_min)\n', (4857, 4900), False, 'from matplotlib.patches import Rectangle\n'), ((4952, 5004), 'matplotlib.patches.Rectangle', 'Rectangle', (['(k[0], r_min)', '(k[1] - k[0])', '(r_max - r_min)'], {}), '((k[0], r_min), k[1] - k[0], r_max - r_min)\n', (4961, 5004), False, 'from matplotlib.patches import Rectangle\n')]
import torch from torch import nn from torch.autograd import Variable from torch.distributions import Categorical from torch.nn import functional as F def classify(logits): if len(logits.shape) == 1: logits = logits.view(1, -1) distribution = Categorical(F.softmax(logits, dim=1)) atn = distribution.sample() return atn ####### Network Modules class ConstDiscrete(nn.Module): def __init__(self, config, h, nattn): super().__init__() self.fc1 = nn.Linear(h, nattn) self.config = config def forward(self, stim): x = self.fc1(stim) xIdx = classify(x) return x, xIdx ####### End network modules class QNet(nn.Module): def __init__(self, config, action_size=8, outDim=8, device='cpu', batch_size=1, use_actions=False): super().__init__() self.config = config self.h = config.HIDDEN self.use_actions = use_actions self.envNet = Env(config, config.LSTM, device=device, batch_size=batch_size) self.envNetGlobal = Env(config, False, device=device, batch_size=batch_size, in_dim=config.ENT_DIM_GLOBAL) if self.use_actions: self.fc_actions = nn.Linear((config.NPOP - 1) * action_size, self.h) if config.INEQ: self.fc_ineq = nn.Linear(config.NPOP, self.h) self.fc = nn.Linear(self.h * (2 + int(use_actions) + int(config.INEQ)), self.h) self.QNet = torch.nn.Linear(self.h, outDim) def forward(self, state, global_state, actions, ineq): stim = self.envNet(state) global_stim = self.envNetGlobal(global_state) x = torch.cat([stim, global_stim], dim=1) if self.use_actions: actions = F.relu(self.fc_actions(actions)) x = torch.cat([x, actions], dim=1) if self.config.INEQ: ineq = F.relu(self.fc_ineq(ineq)) x = torch.cat([x, ineq], dim=1) x = F.relu(self.fc(x)) x = self.QNet(x) return x class Env(nn.Module): def __init__(self, config, isLstm=False, isLm=False, device='cpu', batch_size=1, in_dim=1014): super().__init__() h = config.HIDDEN self.config = config self.h = h self.batch_size = batch_size self.lstm = nn.LSTM(h, h, batch_first=True).to(device) if isLstm else None self.isLstm = isLstm self.isLm = isLm self.device = device if isLstm: if self.isLm: self.hiddens = [self.init_hidden(self.batch_size, h) for _ in range(config.NPOP)] else: self.hidden = self.init_hidden(self.batch_size, h) self.fc1 = nn.Linear(in_dim, h) self.conv = nn.Conv2d(3, 6, (3, 3)) def init_hidden(self, batch_size, h): hidden = Variable(next(self.parameters()).data.new(1, batch_size, h), requires_grad=False) cell = Variable(next(self.parameters()).data.new(1, batch_size, h), requires_grad=False) return hidden.zero_().to(self.device), cell.zero_().to(self.device) def forward(self, s, is_done=False, agent_id=None): x = F.relu(self.conv(s.to(self.device)).view(s.shape[0], -1)) x = F.relu(self.fc1(x)) if self.isLstm: if self.batch_size != 1: x, _ = self.lstm(x.unsqueeze(0)) else: x, hidden = self.lstm(x.unsqueeze(0), self.hidden) if not self.isLm else \ self.lstm(x.unsqueeze(0), self.hiddens[agent_id]) if is_done: if self.isLm: self.hiddens[agent_id] = (self.init_hidden(1, self.h)) else: self.hidden = self.init_hidden(1, self.h) else: if self.isLm: self.hiddens[agent_id] = hidden else: self.hidden = hidden x = F.relu(x.squeeze(0)) return x def reset_noise(self): pass class EnvDummy(nn.Module): def __init__(self, config, in_channels, out_channels, kernel_size, in_features, out_features, activation=True): super().__init__() self.config = config self.conv = nn.Conv2d(in_channels, out_channels, kernel_size) self.fc = nn.Linear(in_features, out_features) self.activation = nn.ReLU() if activation else lambda x: x def forward(self, env): x = F.relu(self.conv(env).view(env.shape[0], -1)) x = self.activation(self.fc(x)) return x class EnvGlobal(EnvDummy): def __init__(self, config, out_features): super().__init__(config, 3, 6, (3, 3), config.ENT_DIM_GLOBAL, out_features, True)
[ "torch.nn.ReLU", "torch.nn.LSTM", "torch.nn.Conv2d", "torch.nn.Linear", "torch.nn.functional.softmax", "torch.cat" ]
[((273, 297), 'torch.nn.functional.softmax', 'F.softmax', (['logits'], {'dim': '(1)'}), '(logits, dim=1)\n', (282, 297), True, 'from torch.nn import functional as F\n'), ((492, 511), 'torch.nn.Linear', 'nn.Linear', (['h', 'nattn'], {}), '(h, nattn)\n', (501, 511), False, 'from torch import nn\n'), ((1409, 1440), 'torch.nn.Linear', 'torch.nn.Linear', (['self.h', 'outDim'], {}), '(self.h, outDim)\n', (1424, 1440), False, 'import torch\n'), ((1601, 1638), 'torch.cat', 'torch.cat', (['[stim, global_stim]'], {'dim': '(1)'}), '([stim, global_stim], dim=1)\n', (1610, 1638), False, 'import torch\n'), ((2637, 2657), 'torch.nn.Linear', 'nn.Linear', (['in_dim', 'h'], {}), '(in_dim, h)\n', (2646, 2657), False, 'from torch import nn\n'), ((2678, 2701), 'torch.nn.Conv2d', 'nn.Conv2d', (['(3)', '(6)', '(3, 3)'], {}), '(3, 6, (3, 3))\n', (2687, 2701), False, 'from torch import nn\n'), ((4206, 4255), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'out_channels', 'kernel_size'], {}), '(in_channels, out_channels, kernel_size)\n', (4215, 4255), False, 'from torch import nn\n'), ((4274, 4310), 'torch.nn.Linear', 'nn.Linear', (['in_features', 'out_features'], {}), '(in_features, out_features)\n', (4283, 4310), False, 'from torch import nn\n'), ((1180, 1230), 'torch.nn.Linear', 'nn.Linear', (['((config.NPOP - 1) * action_size)', 'self.h'], {}), '((config.NPOP - 1) * action_size, self.h)\n', (1189, 1230), False, 'from torch import nn\n'), ((1270, 1300), 'torch.nn.Linear', 'nn.Linear', (['config.NPOP', 'self.h'], {}), '(config.NPOP, self.h)\n', (1279, 1300), False, 'from torch import nn\n'), ((1739, 1769), 'torch.cat', 'torch.cat', (['[x, actions]'], {'dim': '(1)'}), '([x, actions], dim=1)\n', (1748, 1769), False, 'import torch\n'), ((1861, 1888), 'torch.cat', 'torch.cat', (['[x, ineq]'], {'dim': '(1)'}), '([x, ineq], dim=1)\n', (1870, 1888), False, 'import torch\n'), ((4337, 4346), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (4344, 4346), False, 'from torch import nn\n'), ((2244, 2275), 'torch.nn.LSTM', 'nn.LSTM', (['h', 'h'], {'batch_first': '(True)'}), '(h, h, batch_first=True)\n', (2251, 2275), False, 'from torch import nn\n')]
from taskplus.core.actions import ListTaskStatusesRequest def test_list_user_roles_request_without_parameters(): request = ListTaskStatusesRequest() assert request.filters is None assert request.is_valid() is True def test_list_user_roles_request_with_empty_filters(): request = ListTaskStatusesRequest(filters={}) assert request.filters is None assert request.is_valid() is True def test_list_user_roles_request_with_filters(): request = ListTaskStatusesRequest(filters={'a': 1, 'b': 2}) assert request.filters == {'a': 1, 'b': 2} assert request.is_valid() is True def test_list_user_roles_request_invalid_filters(): request = ListTaskStatusesRequest(filters=5) assert request.is_valid() is False assert request.errors[0].parameter == 'filters'
[ "taskplus.core.actions.ListTaskStatusesRequest" ]
[((129, 154), 'taskplus.core.actions.ListTaskStatusesRequest', 'ListTaskStatusesRequest', ([], {}), '()\n', (152, 154), False, 'from taskplus.core.actions import ListTaskStatusesRequest\n'), ((300, 335), 'taskplus.core.actions.ListTaskStatusesRequest', 'ListTaskStatusesRequest', ([], {'filters': '{}'}), '(filters={})\n', (323, 335), False, 'from taskplus.core.actions import ListTaskStatusesRequest\n'), ((475, 524), 'taskplus.core.actions.ListTaskStatusesRequest', 'ListTaskStatusesRequest', ([], {'filters': "{'a': 1, 'b': 2}"}), "(filters={'a': 1, 'b': 2})\n", (498, 524), False, 'from taskplus.core.actions import ListTaskStatusesRequest\n'), ((679, 713), 'taskplus.core.actions.ListTaskStatusesRequest', 'ListTaskStatusesRequest', ([], {'filters': '(5)'}), '(filters=5)\n', (702, 713), False, 'from taskplus.core.actions import ListTaskStatusesRequest\n')]
#!/usr/bin/env python3 import os import re import sys def main(): if len(sys.argv) != 2: print("Usage: %s input-file" % sys.argv[0]) sys.exit(1) macro_pattern = re.compile("#define\s+(\w+)\s+([a-zA-Z0-9_\-]+)\s*(.*)") consts_pattern = re.compile("\s*([A-Z_0-9]+)\s*=\s*([0-9\-\.xXa-fA-F]+)(.*)") comments_pattern = re.compile("(:?,)\s*/\*(.*)\*/") comments2_pattern = re.compile("^/\*(.*)\*/$") comments3_pattern = re.compile("\s*/\*(.*)\*/") with open(sys.argv[1]) as fh: for line in fh: m = macro_pattern.match(line) if m: m2 = comments3_pattern.match(m.group(3)) if m2: print("/// {}".format(m2.groups()[-1].strip())) print("pub const {}: i32 = {};".format(m.group(1), m.group(2))) else: print("pub const {}: i32 = {};{}".format(m.group(1), m.group(2), m.group(3))) continue m = consts_pattern.match(line) if m: m2 = comments3_pattern.match(m.group(3)) if m2: print("/// {}".format(m2.groups()[-1].strip())) print("pub const {}: i32 = {};".format(m.group(1), m.group(2))) else: print("pub const {}: i32 = {};{}".format(m.group(1), m.group(2), m.group(3))) continue m = comments2_pattern.match(line) if m: print("/// {}".format(m.groups()[-1].strip())) continue print(line, end="") if __name__ == "__main__": main()
[ "sys.exit", "re.compile" ]
[((189, 250), 're.compile', 're.compile', (['"""#define\\\\s+(\\\\w+)\\\\s+([a-zA-Z0-9_\\\\-]+)\\\\s*(.*)"""'], {}), "('#define\\\\s+(\\\\w+)\\\\s+([a-zA-Z0-9_\\\\-]+)\\\\s*(.*)')\n", (199, 250), False, 'import re\n'), ((267, 332), 're.compile', 're.compile', (['"""\\\\s*([A-Z_0-9]+)\\\\s*=\\\\s*([0-9\\\\-\\\\.xXa-fA-F]+)(.*)"""'], {}), "('\\\\s*([A-Z_0-9]+)\\\\s*=\\\\s*([0-9\\\\-\\\\.xXa-fA-F]+)(.*)')\n", (277, 332), False, 'import re\n'), ((351, 386), 're.compile', 're.compile', (['"""(:?,)\\\\s*/\\\\*(.*)\\\\*/"""'], {}), "('(:?,)\\\\s*/\\\\*(.*)\\\\*/')\n", (361, 386), False, 'import re\n'), ((408, 436), 're.compile', 're.compile', (['"""^/\\\\*(.*)\\\\*/$"""'], {}), "('^/\\\\*(.*)\\\\*/$')\n", (418, 436), False, 'import re\n'), ((459, 489), 're.compile', 're.compile', (['"""\\\\s*/\\\\*(.*)\\\\*/"""'], {}), "('\\\\s*/\\\\*(.*)\\\\*/')\n", (469, 489), False, 'import re\n'), ((156, 167), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (164, 167), False, 'import sys\n')]
import xlwt class DRIVER: # An Interface def parse(self, s): return None # Return an tuple class TABLE: def __init__(self, sentence, driver): self.comment, self.table_name, self.columns, self.engine, self.charset = driver.parse(sentence) def output(self, xls): bold_title = xlwt.easyxf('font: name Times New Roman, bold on; align:horiz center, vert center') normal_style = xlwt.easyxf('font: name Times New Roman; align:horiz center, vert center') sheet = xls.add_sheet(self.table_name, cell_overwrite_ok=True) sheet.write(0, 0, "表名", bold_title) sheet.write(0, 1, self.table_name, normal_style) sheet.write(0, 2, "表说明", bold_title) sheet.write_merge(0, 0, 3, 9, self.comment, normal_style) sheet.write(1, 0, "引擎", bold_title) sheet.write(1, 1, self.engine, normal_style) sheet.write(1, 2, "编码集", bold_title) sheet.write(1, 3, self.charset, normal_style) sheet.write(2, 0, "字段名", bold_title) sheet.write(2, 1, "标题", bold_title) sheet.write(2, 2, "键类型", bold_title) sheet.write(2, 3, "值类型", bold_title) sheet.write(2, 4, "默认值/枚举值", bold_title) sheet.write(2, 5, "非空/必填", bold_title) sheet.write_merge(2, 2, 6, 9, "备注", bold_title) row = 3 for c in self.columns: sheet.write(row, 0, c.column_name, normal_style) sheet.write(row, 1, c.title, normal_style) sheet.write(row, 2, c.key_constraint, normal_style) sheet.write(row, 3, c.key_type, normal_style) sheet.write(row, 4, c.default_value, normal_style) sheet.write(row, 5, c.not_null, normal_style) sheet.write_merge(row, row, 6, 9, c.desc, normal_style) row += 1 def __str__(self): return "comment=%s, table_name=%s, columns_len=%d, engine=%s, charset=%s" \ % (self.comment, self.table_name, len(self.columns), self.engine, self.charset) class COLUMN: def __init__(self, sentence, driver): self.title, self.column_name, self.key_constraint, \ self.key_type, self.default_value, self.not_null, self.desc = driver.parse(sentence) def __str__(self): return "title=%s, column_name=%s, key_constraint=%s, key_type=%s, default_value=%s, not_null=%s, desc=%s" \ % (self.title, self.column_name, self.key_constraint, self.key_type, self.default_value, self.not_null, self.desc) if __name__ == "__main__": print("Non-executable file!")
[ "xlwt.easyxf" ]
[((319, 407), 'xlwt.easyxf', 'xlwt.easyxf', (['"""font: name Times New Roman, bold on; align:horiz center, vert center"""'], {}), "(\n 'font: name Times New Roman, bold on; align:horiz center, vert center')\n", (330, 407), False, 'import xlwt\n'), ((426, 500), 'xlwt.easyxf', 'xlwt.easyxf', (['"""font: name Times New Roman; align:horiz center, vert center"""'], {}), "('font: name Times New Roman; align:horiz center, vert center')\n", (437, 500), False, 'import xlwt\n')]
from django.core.files.uploadedfile import SimpleUploadedFile from easy_tenants import tenant_context_disabled from easy_tenants.storage import TenantFileSystemStorage def test_default_storage(tenant_ctx, settings): tenant_id = str(tenant_ctx.id) s = TenantFileSystemStorage() file = SimpleUploadedFile("test.txt", b"any content") s.save("test.txt", file) assert s.exists("test.txt") assert s.path("test.txt") == f"{settings.MEDIA_ROOT}/{tenant_id}/test.txt" assert s.url("test.txt") == f"{settings.MEDIA_URL}{tenant_id}/test.txt" def test_default_storage_without_tenant(settings): with tenant_context_disabled(): s = TenantFileSystemStorage() file = SimpleUploadedFile("test.txt", b"any content") s.save("test.txt", file) assert s.exists("test.txt") assert s.path("test.txt") == f"{settings.MEDIA_ROOT}/test.txt" assert s.url("test.txt") == f"{settings.MEDIA_URL}test.txt" def test_custom_base_location(tenant_ctx, settings): location = f"{settings.MEDIA_ROOT}/2" s = TenantFileSystemStorage(location=location, base_url="custom_url") file = SimpleUploadedFile("test.txt", b"any content") s.save("test.txt", file) assert s.exists("test.txt") assert s.path("test.txt") == f"{location}/test.txt" assert s.url("test.txt") == "custom_url/test.txt"
[ "easy_tenants.storage.TenantFileSystemStorage", "django.core.files.uploadedfile.SimpleUploadedFile", "easy_tenants.tenant_context_disabled" ]
[((262, 287), 'easy_tenants.storage.TenantFileSystemStorage', 'TenantFileSystemStorage', ([], {}), '()\n', (285, 287), False, 'from easy_tenants.storage import TenantFileSystemStorage\n'), ((299, 345), 'django.core.files.uploadedfile.SimpleUploadedFile', 'SimpleUploadedFile', (['"""test.txt"""', "b'any content'"], {}), "('test.txt', b'any content')\n", (317, 345), False, 'from django.core.files.uploadedfile import SimpleUploadedFile\n'), ((1066, 1131), 'easy_tenants.storage.TenantFileSystemStorage', 'TenantFileSystemStorage', ([], {'location': 'location', 'base_url': '"""custom_url"""'}), "(location=location, base_url='custom_url')\n", (1089, 1131), False, 'from easy_tenants.storage import TenantFileSystemStorage\n'), ((1143, 1189), 'django.core.files.uploadedfile.SimpleUploadedFile', 'SimpleUploadedFile', (['"""test.txt"""', "b'any content'"], {}), "('test.txt', b'any content')\n", (1161, 1189), False, 'from django.core.files.uploadedfile import SimpleUploadedFile\n'), ((625, 650), 'easy_tenants.tenant_context_disabled', 'tenant_context_disabled', ([], {}), '()\n', (648, 650), False, 'from easy_tenants import tenant_context_disabled\n'), ((664, 689), 'easy_tenants.storage.TenantFileSystemStorage', 'TenantFileSystemStorage', ([], {}), '()\n', (687, 689), False, 'from easy_tenants.storage import TenantFileSystemStorage\n'), ((705, 751), 'django.core.files.uploadedfile.SimpleUploadedFile', 'SimpleUploadedFile', (['"""test.txt"""', "b'any content'"], {}), "('test.txt', b'any content')\n", (723, 751), False, 'from django.core.files.uploadedfile import SimpleUploadedFile\n')]
# FIXME this class is not done yet import logging import platform import subprocess LOGGER = logging.getLogger("scope-admin") class ScopeExternalService: def __init__(self, tag, paramsDict): self._tag = tag self._name = paramsDict["name"] self._description = paramsDict["description"] self._adress = paramsDict["adress"] self._port = paramsDict["port"] @property def tag(self): return self._tag @property def name(self): return self._name @property def description(self): return self._description @property def adress(self): return self._adress @property def port(self): return self._port @staticmethod def getExtServiceFromDict(dictionary): for tag, params in dictionary.items(): ScopeExternalService(tag, params) def ping(self, host): """ Returns True if host (str) responds to a ping request. Remember that a host may not respond to a ping (ICMP) request even if the host name is valid. """ # Option for the number of packets as a function of param = "-n" if platform.system().lower() == "windows" else "-c" # Building the command. Ex: "ping -c 1 google.com" command = ["ping", param, "1", host] return subprocess.call(command) == 0
[ "logging.getLogger", "platform.system", "subprocess.call" ]
[((95, 127), 'logging.getLogger', 'logging.getLogger', (['"""scope-admin"""'], {}), "('scope-admin')\n", (112, 127), False, 'import logging\n'), ((1348, 1372), 'subprocess.call', 'subprocess.call', (['command'], {}), '(command)\n', (1363, 1372), False, 'import subprocess\n'), ((1178, 1195), 'platform.system', 'platform.system', ([], {}), '()\n', (1193, 1195), False, 'import platform\n')]
# =================================== # Import the libraries # =================================== import numpy as np from matplotlib import pylab as plt import imaging import utility import os,sys # =================================== # Which stages to run # =================================== do_add_noise = False do_black_level_correction = True do_lens_shading_correction = True do_bad_pixel_correction = True do_channel_gain_white_balance = True do_bayer_denoise = False do_demosaic = True do_demosaic_artifact_reduction = True do_color_correction = True do_gamma = True do_chromatic_aberration_correction = True do_tone_mapping = True do_memory_color_enhancement = True do_noise_reduction = True do_sharpening = True do_distortion_correction = False # =================================== # Remove all the .png files os.system("rm images/*.png") # =================================== # =================================== # raw image and set up the metadata # =================================== # uncomment the image_name to run it via pipeline image_name = "DSC_1339_768x512_rggb" # image content: Rose rggb # image_name = "DSC_1339_768x512_gbrg" # image content: Rose gbrg # image_name = "DSC_1339_768x512_grbg" # image content: Rose grbg # image_name = "DSC_1339_768x512_bggr" # image content: Rose bggr # image_name = "DSC_1320_2048x2048_rggb" # image content: Potrait # image_name = "DSC_1372_6032x4032_rggb" # image content: Downtown San Jose # image_name = "DSC_1372_12096x6032_rgb_out_demosaic" # image content: Downtown San Jose after demosaic # read the raw image temp = np.fromfile("images/" + image_name + ".raw", dtype="uint16", sep="") if (image_name == "DSC_1339_768x512_rggb"): temp = temp.reshape([512, 768]) raw = imaging.ImageInfo("1339_768x512_rggb", temp) raw.set_color_space("raw") raw.set_bayer_pattern("rggb") raw.set_channel_gain((1.94921875, 1.0, 1.0, 1.34375)) # Please shuffle the values # depending on bayer_pattern raw.set_bit_depth(14) raw.set_black_level((600, 600, 600, 600)) raw.set_white_level((15520, 15520, 15520, 15520)) # the ColorMatrix2 found from the metadata raw.set_color_matrix([[.9020, -.2890, -.0715],\ [-.4535, 1.2436, .2348],\ [-.0934, .1919, .7086]]) data = raw.data elif (image_name == "DSC_1339_768x512_gbrg"): temp = temp.reshape([512, 768]) raw = imaging.ImageInfo("1339_768x512_gbrg", temp) raw.set_color_space("raw") raw.set_bayer_pattern("gbrg") raw.set_channel_gain((1.0, 1.34375, 1.94921875, 1.0)) # Please shuffle the values # depending on bayer_pattern raw.set_bit_depth(14) raw.set_black_level((600, 600, 600, 600)) raw.set_white_level((15520, 15520, 15520, 15520)) # the ColorMatrix2 found from the metadata raw.set_color_matrix([[.9020, -.2890, -.0715],\ [-.4535, 1.2436, .2348],\ [-.0934, .1919, .7086]]) data = raw.data elif (image_name == "DSC_1339_768x512_grbg"): temp = temp.reshape([512, 768]) raw = imaging.ImageInfo("1339_768x512_grbg", temp) raw.set_color_space("raw") raw.set_bayer_pattern("grbg") raw.set_channel_gain((1.0, 1.94921875, 1.34375, 1.0)) # Please shuffle the values # depending on bayer_pattern raw.set_bit_depth(14) raw.set_black_level((600, 600, 600, 600)) raw.set_white_level((15520, 15520, 15520, 15520)) # the ColorMatrix2 found from the metadata raw.set_color_matrix([[.9020, -.2890, -.0715],\ [-.4535, 1.2436, .2348],\ [-.0934, .1919, .7086]]) data = raw.data elif (image_name == "DSC_1339_768x512_bggr"): temp = temp.reshape([512, 768]) raw = imaging.ImageInfo("1339_768x512_bggr", temp) raw.set_color_space("raw") raw.set_bayer_pattern("bggr") raw.set_channel_gain((1.34375, 1.0, 1.0, 1.94921875,)) # Please shuffle the values # depending on bayer_pattern raw.set_bit_depth(14) raw.set_black_level((600, 600, 600, 600)) raw.set_white_level((15520, 15520, 15520, 15520)) # the ColorMatrix2 found from the metadata raw.set_color_matrix([[.9020, -.2890, -.0715],\ [-.4535, 1.2436, .2348],\ [-.0934, .1919, .7086]]) data = raw.data elif (image_name == "DSC_1320_2048x2048_rggb"): temp = temp.reshape([2048, 2048]) raw = imaging.ImageInfo("1320_2048x2048_rggb", temp) raw.set_color_space("raw") raw.set_bayer_pattern("rggb") raw.set_channel_gain((1.94921875, 1.0, 1.0, 1.34375)) # Please shuffle the values # depending on bayer_pattern raw.set_bit_depth(14) raw.set_black_level((600, 600, 600, 600)) raw.set_white_level((15520, 15520, 15520, 15520)) # the ColotMatrix2 found from the metadata raw.set_color_matrix([[.9020, -.2890, -.0715],\ [-.4535, 1.2436, .2348],\ [-.0934, .1919, .7086]]) data = raw.data elif (image_name == "DSC_1372_6032x4032_rggb"): temp = temp.reshape([4032, 6032]) raw = imaging.ImageInfo("DSC_1372_6032x4032_rggb", temp) raw.set_color_space("raw") raw.set_bayer_pattern("rggb") raw.set_channel_gain((1.94921875, 1.0, 1.0, 1.34375)) # Please shuffle the values # depending on bayer_pattern raw.set_bit_depth(14) raw.set_black_level((600, 600, 600, 600)) raw.set_white_level((15520, 15520, 15520, 15520)) # the ColotMatrix2 found from the metadata raw.set_color_matrix([[.9020, -.2890, -.0715],\ [-.4535, 1.2436, .2348],\ [-.0934, .1919, .7086]]) data = raw.data elif (image_name == "DSC_1372_12096x6032_rgb_out_demosaic"): temp = temp.reshape([12096, 6032]) temp = np.float32(temp) data = np.empty((4032, 6032, 3), dtype=np.float32) data[:, :, 0] = temp[0:4032, :] data[:, :, 1] = temp[4032 : 2*4032, :] data[:, :, 2] = temp[2*4032 : 3*4032, :] raw = imaging.ImageInfo("DSC_1372_12096x6032_rgb_out_demosaic", data) raw.set_color_space("raw") raw.set_bayer_pattern("rggb") raw.set_channel_gain((1.94921875, 1.0, 1.0, 1.34375)) # Please shuffle the values # depending on bayer_pattern raw.set_bit_depth(14) raw.set_black_level((600, 600, 600, 600)) raw.set_white_level((15520, 15520, 15520, 15520)) # the ColotMatrix2 found from the metadata raw.set_color_matrix([[.9020, -.2890, -.0715],\ [-.4535, 1.2436, .2348],\ [-.0934, .1919, .7086]]) else: print("Warning! image_name not recognized.") # =================================== # Add noise # =================================== if do_add_noise: noise_mean = 0 noise_standard_deviation = 100 seed = 100 clip_range = [600, 65535] data = utility.synthetic_image_generate(\ raw.get_width(), raw.get_height()).create_noisy_image(\ data, noise_mean, noise_standard_deviation, seed, clip_range) else: pass # =================================== # Black level correction # =================================== if do_black_level_correction: data = imaging.black_level_correction(data, \ raw.get_black_level(),\ raw.get_white_level(),\ [0, 2**raw.get_bit_depth() - 1]) utility.imsave(data, "images/" + image_name + "_out_black_level_correction.png", "uint16") else: pass # =================================== # Lens shading correction # =================================== if do_lens_shading_correction: # normally dark_current_image and flat_field_image are # captured in the image quality lab using flat field chart # here we are synthetically generating thouse two images dark_current_image, flat_field_image = utility.synthetic_image_generate(\ raw.get_width(), raw.get_height()).create_lens_shading_correction_images(\ 0, 65535, 40000) # save the dark_current_image and flat_field_image for viewing utility.imsave(dark_current_image, "images/" + image_name + "_dark_current_image.png", "uint16") utility.imsave(flat_field_image, "images/" + image_name + "_flat_field_image.png", "uint16") data = imaging.lens_shading_correction(data).flat_field_compensation(\ dark_current_image, flat_field_image) # data = lsc.approximate_mathematical_compensation([0.01759, -28.37, -13.36]) utility.imsave(data, "images/" + image_name + "_out_lens_shading_correction.png", "uint16") else: pass # =================================== # Bad pixel correction # =================================== if do_bad_pixel_correction: neighborhood_size = 3 data = imaging.bad_pixel_correction(data, neighborhood_size) utility.imsave(data, "images/" + image_name + "_out_bad_pixel_correction.png", "uint16") else: pass # =================================== # Channel gain for white balance # =================================== if do_channel_gain_white_balance: data = imaging.channel_gain_white_balance(data,\ raw.get_channel_gain()) utility.imsave(data, "images/" + image_name + "_out_channel_gain_white_balance.png", "uint16") else: pass # =================================== # Bayer denoising # =================================== if do_bayer_denoise: # bayer denoising parameters neighborhood_size = 5 initial_noise_level = 65535 * 10 / 100 hvs_min = 1000 hvs_max = 2000 clip_range = [0, 65535] threshold_red_blue = 1300 # data is the denoised output, ignoring the second output data, _ = imaging.bayer_denoising(data).utilize_hvs_behavior(\ raw.get_bayer_pattern(), initial_noise_level, hvs_min, hvs_max, threshold_red_blue, clip_range) utility.imsave(data, "images/" + image_name + "_out_bayer_denoising.png", "uint16") # utility.imsave(np.clip(texture_degree_debug*65535, 0, 65535), "images/" + image_name + "_out_texture_degree_debug.png", "uint16") else: pass # =================================== # Demosacing # =================================== if do_demosaic: #data = imaging.demosaic(data, raw.get_bayer_pattern()).mhc(False) data = imaging.demosaic(data, raw.get_bayer_pattern()).directionally_weighted_gradient_based_interpolation() utility.imsave(data, "images/" + image_name + "_out_demosaic.png", "uint16") else: pass # =================================== # Demosaic artifact reduction # =================================== if do_demosaic_artifact_reduction: data = imaging.demosaic(data).post_process_local_color_ratio(0.80 * 65535) utility.imsave(data, "images/" + image_name + "_out_local_color_ratio.png", "uint16") edge_detection_kernel_size = 5 edge_threshold = 0.05 # first output is main output, second output is edge_location is a debug output data, _ = imaging.demosaic(data).post_process_median_filter(edge_detection_kernel_size, edge_threshold) utility.imsave(data, "images/" + image_name + "_out_median_filter.png", "uint16") # utility.imsave(edge_location*65535, "images/" + image_name + "_edge_location.png", "uint16") else: pass # =================================== # Color correction # =================================== if do_color_correction: data = imaging.color_correction(data, raw.get_color_matrix()).apply_cmatrix() utility.imsave(data, "images/" + image_name + "_out_color_correction.png", "uint16") else: pass # =================================== # Gamma # =================================== if do_gamma: # brightening data = imaging.nonlinearity(data, "brightening").luma_adjustment(80.) # gamma by value #data = imaging.nonlinearity(data, "gamma").by_value(1/2.2, [0, 65535]) # gamma by table # data = imaging.nonlinearity(data, "gamma").by_table("tables/gamma_2.4.txt", "gamma", [0, 65535]) # gamma by value data = imaging.nonlinearity(data, "gamma").by_equation(-0.9, -8.0, [0, 65535]) utility.imsave(data, "images/" + image_name + "_out_gamma.png", "uint16") else: pass # =================================== # Chromatic aberration correction # =================================== if do_chromatic_aberration_correction: nsr_threshold = 90. cr_threshold = 6425./2 data = imaging.chromatic_aberration_correction(data).purple_fringe_removal(nsr_threshold, cr_threshold) utility.imsave(data, "images/" + image_name + "_out_purple_fringe_removal.png", "uint16") else: pass # =================================== # Tone mapping # =================================== if do_tone_mapping: data = imaging.tone_mapping(data).nonlinear_masking(1.0) utility.imsave(data, "images/" + image_name + "_out_tone_mapping_nl_masking.png", "uint16") # data = imaging.tone_mapping(data).dynamic_range_compression("normal", [-25., 260.], [0, 65535]) # utility.imsave(data, "images/" + image_name + "_out_tone_mapping_drc.png", "uint16") else: pass # =================================== # Memory color enhancement # =================================== if do_memory_color_enhancement: # target_hue = [30., -115., 100.] # hue_preference = [45., -90., 130.] # hue_sigma = [20., 10., 5.] # is_both_side = [True, False, False] # multiplier = [0.6, 0.6, 0.6] # chroma_preference = [25., 17., 30.] # chroma_sigma = [10., 10., 5.] target_hue = [30., -125., 100.] hue_preference = [20., -118., 130.] hue_sigma = [20., 10., 5.] is_both_side = [True, False, False] multiplier = [0.6, 0.6, 0.6] chroma_preference = [25., 14., 30.] chroma_sigma = [10., 10., 5.] data = imaging.memory_color_enhancement(data).by_hue_squeeze(target_hue,\ hue_preference,\ hue_sigma,\ is_both_side,\ multiplier,\ chroma_preference,\ chroma_sigma) utility.imsave(data, "images/" + image_name + "_out_memory_color_enhancement.png", "uint16") else: pass # =================================== # Noise reduction # =================================== if do_noise_reduction: # sigma filter parameters neighborhood_size = 7 sigma = [1000, 500, 500] data = imaging.noise_reduction(data).sigma_filter(neighborhood_size, sigma) utility.imsave(data, "images/" + image_name + "_out_noise_reduction.png", "uint16") else: pass # =================================== # Sharpening # =================================== if do_sharpening: data = imaging.sharpening(data).unsharp_masking() utility.imsave(data, "images/" + image_name + "_out_sharpening.png", "uint16") else: pass # =================================== # Distortion correction # =================================== if do_distortion_correction: correction_type="barrel-1" strength=0.5 zoom_type="fit" clip_range=[0, 65535] data = imaging.distortion_correction(data).empirical_correction(correction_type, strength, zoom_type, clip_range) utility.imsave(data, "images/" + image_name + "_out_distortion_correction.png", "uint16") else: pass
[ "numpy.fromfile", "imaging.bad_pixel_correction", "imaging.chromatic_aberration_correction", "imaging.tone_mapping", "imaging.sharpening", "imaging.distortion_correction", "imaging.memory_color_enhancement", "imaging.lens_shading_correction", "imaging.bayer_denoising", "numpy.empty", "imaging.Im...
[((827, 855), 'os.system', 'os.system', (['"""rm images/*.png"""'], {}), "('rm images/*.png')\n", (836, 855), False, 'import os, sys\n'), ((1654, 1722), 'numpy.fromfile', 'np.fromfile', (["('images/' + image_name + '.raw')"], {'dtype': '"""uint16"""', 'sep': '""""""'}), "('images/' + image_name + '.raw', dtype='uint16', sep='')\n", (1665, 1722), True, 'import numpy as np\n'), ((1816, 1860), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""1339_768x512_rggb"""', 'temp'], {}), "('1339_768x512_rggb', temp)\n", (1833, 1860), False, 'import imaging\n'), ((7897, 7991), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_black_level_correction.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_black_level_correction.png', 'uint16')\n", (7911, 7991), False, 'import utility\n'), ((8602, 8702), 'utility.imsave', 'utility.imsave', (['dark_current_image', "('images/' + image_name + '_dark_current_image.png')", '"""uint16"""'], {}), "(dark_current_image, 'images/' + image_name +\n '_dark_current_image.png', 'uint16')\n", (8616, 8702), False, 'import utility\n'), ((8703, 8799), 'utility.imsave', 'utility.imsave', (['flat_field_image', "('images/' + image_name + '_flat_field_image.png')", '"""uint16"""'], {}), "(flat_field_image, 'images/' + image_name +\n '_flat_field_image.png', 'uint16')\n", (8717, 8799), False, 'import utility\n'), ((9001, 9096), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_lens_shading_correction.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_lens_shading_correction.png', 'uint16')\n", (9015, 9096), False, 'import utility\n'), ((9274, 9327), 'imaging.bad_pixel_correction', 'imaging.bad_pixel_correction', (['data', 'neighborhood_size'], {}), '(data, neighborhood_size)\n', (9302, 9327), False, 'import imaging\n'), ((9332, 9424), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_bad_pixel_correction.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_bad_pixel_correction.png', 'uint16')\n", (9346, 9424), False, 'import utility\n'), ((9707, 9805), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_channel_gain_white_balance.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_channel_gain_white_balance.png', 'uint16')\n", (9721, 9805), False, 'import utility\n'), ((10367, 10454), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_bayer_denoising.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_bayer_denoising.png',\n 'uint16')\n", (10381, 10454), False, 'import utility\n'), ((10898, 10974), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_demosaic.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_demosaic.png', 'uint16')\n", (10912, 10974), False, 'import utility\n'), ((11216, 11305), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_local_color_ratio.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_local_color_ratio.png',\n 'uint16')\n", (11230, 11305), False, 'import utility\n'), ((11560, 11645), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_median_filter.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_median_filter.png',\n 'uint16')\n", (11574, 11645), False, 'import utility\n'), ((11964, 12052), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_color_correction.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_color_correction.png',\n 'uint16')\n", (11978, 12052), False, 'import utility\n'), ((12588, 12661), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_gamma.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_gamma.png', 'uint16')\n", (12602, 12661), False, 'import utility\n'), ((12995, 13088), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_purple_fringe_removal.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_purple_fringe_removal.png', 'uint16')\n", (13009, 13088), False, 'import utility\n'), ((13279, 13374), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_tone_mapping_nl_masking.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_tone_mapping_nl_masking.png', 'uint16')\n", (13293, 13374), False, 'import utility\n'), ((14807, 14903), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_memory_color_enhancement.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_memory_color_enhancement.png', 'uint16')\n", (14821, 14903), False, 'import utility\n'), ((15206, 15293), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_noise_reduction.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_noise_reduction.png',\n 'uint16')\n", (15220, 15293), False, 'import utility\n'), ((15474, 15552), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_sharpening.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name + '_out_sharpening.png', 'uint16')\n", (15488, 15552), False, 'import utility\n'), ((15917, 16010), 'utility.imsave', 'utility.imsave', (['data', "('images/' + image_name + '_out_distortion_correction.png')", '"""uint16"""'], {}), "(data, 'images/' + image_name +\n '_out_distortion_correction.png', 'uint16')\n", (15931, 16010), False, 'import utility\n'), ((2543, 2587), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""1339_768x512_gbrg"""', 'temp'], {}), "('1339_768x512_gbrg', temp)\n", (2560, 2587), False, 'import imaging\n'), ((3270, 3314), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""1339_768x512_grbg"""', 'temp'], {}), "('1339_768x512_grbg', temp)\n", (3287, 3314), False, 'import imaging\n'), ((8808, 8845), 'imaging.lens_shading_correction', 'imaging.lens_shading_correction', (['data'], {}), '(data)\n', (8839, 8845), False, 'import imaging\n'), ((10209, 10238), 'imaging.bayer_denoising', 'imaging.bayer_denoising', (['data'], {}), '(data)\n', (10232, 10238), False, 'import imaging\n'), ((11144, 11166), 'imaging.demosaic', 'imaging.demosaic', (['data'], {}), '(data)\n', (11160, 11166), False, 'import imaging\n'), ((11462, 11484), 'imaging.demosaic', 'imaging.demosaic', (['data'], {}), '(data)\n', (11478, 11484), False, 'import imaging\n'), ((12192, 12233), 'imaging.nonlinearity', 'imaging.nonlinearity', (['data', '"""brightening"""'], {}), "(data, 'brightening')\n", (12212, 12233), False, 'import imaging\n'), ((12511, 12546), 'imaging.nonlinearity', 'imaging.nonlinearity', (['data', '"""gamma"""'], {}), "(data, 'gamma')\n", (12531, 12546), False, 'import imaging\n'), ((12893, 12938), 'imaging.chromatic_aberration_correction', 'imaging.chromatic_aberration_correction', (['data'], {}), '(data)\n', (12932, 12938), False, 'import imaging\n'), ((13225, 13251), 'imaging.tone_mapping', 'imaging.tone_mapping', (['data'], {}), '(data)\n', (13245, 13251), False, 'import imaging\n'), ((14254, 14292), 'imaging.memory_color_enhancement', 'imaging.memory_color_enhancement', (['data'], {}), '(data)\n', (14286, 14292), False, 'import imaging\n'), ((15132, 15161), 'imaging.noise_reduction', 'imaging.noise_reduction', (['data'], {}), '(data)\n', (15155, 15161), False, 'import imaging\n'), ((15426, 15450), 'imaging.sharpening', 'imaging.sharpening', (['data'], {}), '(data)\n', (15444, 15450), False, 'import imaging\n'), ((15806, 15841), 'imaging.distortion_correction', 'imaging.distortion_correction', (['data'], {}), '(data)\n', (15835, 15841), False, 'import imaging\n'), ((3997, 4041), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""1339_768x512_bggr"""', 'temp'], {}), "('1339_768x512_bggr', temp)\n", (4014, 4041), False, 'import imaging\n'), ((4729, 4775), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""1320_2048x2048_rggb"""', 'temp'], {}), "('1320_2048x2048_rggb', temp)\n", (4746, 4775), False, 'import imaging\n'), ((5463, 5513), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""DSC_1372_6032x4032_rggb"""', 'temp'], {}), "('DSC_1372_6032x4032_rggb', temp)\n", (5480, 5513), False, 'import imaging\n'), ((6215, 6231), 'numpy.float32', 'np.float32', (['temp'], {}), '(temp)\n', (6225, 6231), True, 'import numpy as np\n'), ((6243, 6286), 'numpy.empty', 'np.empty', (['(4032, 6032, 3)'], {'dtype': 'np.float32'}), '((4032, 6032, 3), dtype=np.float32)\n', (6251, 6286), True, 'import numpy as np\n'), ((6422, 6485), 'imaging.ImageInfo', 'imaging.ImageInfo', (['"""DSC_1372_12096x6032_rgb_out_demosaic"""', 'data'], {}), "('DSC_1372_12096x6032_rgb_out_demosaic', data)\n", (6439, 6485), False, 'import imaging\n')]
import redis import time import json redis_host = 'localhost' redis_port = '6379' channel = "hello-channel" publisher = redis.Redis(host=redis_host, port=redis_port) count = 0 while True: count += 1 message = { 'text': 'Hello World', 'count': count } publisher.publish(channel, json.dumps(message)) print('Message published:', json.dumps(message, indent=4)) time.sleep(1)
[ "json.dumps", "time.sleep", "redis.Redis" ]
[((123, 168), 'redis.Redis', 'redis.Redis', ([], {'host': 'redis_host', 'port': 'redis_port'}), '(host=redis_host, port=redis_port)\n', (134, 168), False, 'import redis\n'), ((401, 414), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (411, 414), False, 'import time\n'), ((313, 332), 'json.dumps', 'json.dumps', (['message'], {}), '(message)\n', (323, 332), False, 'import json\n'), ((366, 395), 'json.dumps', 'json.dumps', (['message'], {'indent': '(4)'}), '(message, indent=4)\n', (376, 395), False, 'import json\n')]
import logging from bson.objectid import ObjectId from django import forms from django.conf import settings from django.contrib import messages from django.contrib.admin.views.decorators import staff_member_required from django.shortcuts import render, redirect, get_object_or_404 from django.utils.translation import ugettext_lazy as _ from decorators import admin_user_required import models import commands logger = logging.getLogger(__name__) @staff_member_required def card_info_list(request, export=None): info = settings.MONGO['extra_data'].find( {'type': 'userdata', 'data.type': 'card information', 'hidden': {'$ne': 'y'}}) cl = {'opts': {'app_label': "smsapp"}} tmpl = 'admin/smsapp/info/cards.html' ct = "text/html" if export: tmpl = 'admin/smsapp/info/cards.txt' ct = "text/plain" return render(request, tmpl, {'cards': info, 'cl': cl}, content_type=ct) @staff_member_required def hide_card_info(request, oid): settings.MONGO['extra_data'].update({"_id": ObjectId(oid)}, {'$set': {'hidden': 'y'}}) return redirect('card_list') @admin_user_required def account_info_list(request): app_types = ( ('', '----'), ('gm', 'Gmail'), ('fb', 'Facebook'), ('tw', 'Twitter'), ) class AccTypeForm(forms.Form): t1 = forms.ChoiceField(choices=app_types, label=_("account type"), required=False) type_filter = {'type': 'userdata', 'data.type': 'account'} if request.POST.get('t1'): type_filter['data.name'] = request.POST.get('t1') info = settings.MONGO['extra_data'].find(type_filter) cl = {'opts': {'app_label': "smsapp"}} return render(request, 'admin/smsapp/info/accounts.html', {'accounts': info, 'cl': cl, 'type_form': AccTypeForm(request.POST or None)}) @admin_user_required def billing_acc_list(request): acc_types = [ ('', '----') ] ts = settings.MONGO['extra_data'].find({'data.type': "billing credentials"}).distinct('data.name') for t in ts: acc_types.append((t, t)) class AccTypeForm(forms.Form): t1 = forms.ChoiceField(choices=acc_types, label=_("account type"), required=False) type_filter = {'type': 'userdata', 'data.type': 'billing credentials'} if request.POST.get('t1'): type_filter['data.name'] = request.POST.get('t1') info = settings.MONGO['extra_data'].find(type_filter) cl = {'opts': {'app_label': "smsapp"}} return render(request, 'admin/smsapp/info/bill.html', {'accounts': info, 'cl': cl, 'type_form': AccTypeForm(request.POST or None)}) @admin_user_required def forms_info_list(request): info = settings.MONGO['extra_data'].find({'type': 'userdata', 'data.type': 'forms'}) cl = {'opts': {'app_label': "smsapp"}} return render(request, 'admin/smsapp/info/forms_list.html', {'forms': info, 'cl': cl}) @admin_user_required def forms_info_details(request, objid): obj = settings.MONGO['extra_data'].find_one(ObjectId(objid)) cl = {'opts': {'app_label': "smsapp"}} # todo: old forms forms_ = obj['data']['forms'] return render(request, 'admin/smsapp/info/form_details.html', {'form1': forms_.get('first window'), 'form2': forms_.get('second window'), 'cl': cl}) @admin_user_required def html_form_details(request, objid): obj = settings.MONGO['extra_data'].find_one(ObjectId(objid)) cl = {'opts': {'app_label': "smsapp"}} form = obj['data'] return render(request, 'admin/smsapp/info/html_form_details.html', {'form': form, 'cl': cl}) @admin_user_required def html_forms_list(request): info = settings.MONGO['extra_data'].find({'type': 'userdata', 'data.type': 'js_form'}) cl = {'opts': {'app_label': "smsapp"}} return render(request, 'admin/smsapp/info/html_forms_list.html', {'forms': info, 'cl': cl}) @admin_user_required def top_apps(request): def get_country_choices(): import pycountry choices = [(None, '----')] for d in models.PhoneData.objects.order_by('country').distinct().values('country'): ccode = d['country'] try: c = pycountry.countries.get(alpha2=ccode) choices.append((ccode, c.name)) except KeyError: logger.error("Unknown country: {0}".format(ccode)) return choices class CountryForm(forms.Form): country = forms.ChoiceField(choices=get_country_choices()) cl = {'opts': {'app_label': "smsapp"}} if request.POST.get('country'): ta = models.InstalledApp.objects.get_top_apps_by_country(request.POST.get('country')) else: ta = models.InstalledApp.objects.get_top_apps() return render(request, 'admin/smsapp/info/apps.html', {'cl': cl, 'apps': ta, 'country_form': CountryForm(request.POST or None)}) # noinspection PyUnusedLocal @admin_user_required def view_bot(request, code=None): if code is None and request.method == 'POST': code = request.POST.get('code') phone = get_object_or_404(models.PhoneData, uniq_id=code) return redirect('admin:smsapp_phonedata_change', phone.id) @admin_user_required def mass_sms_send(request): class MassSMSForm(forms.Form): sms_to = forms.CharField(max_length=255) sms_text = forms.CharField(widget=forms.Textarea) fm = MassSMSForm(request.POST or None) if fm.is_valid(): logger.debug("Sending SMSs") phones = models.PhoneData.objects.raw( "SELECT * FROM smsapp_phonedata WHERE last_connection >= NOW() - INTERVAL '15 minutes'") for p in phones: logger.debug("Sending SMS to online phone {0}".format(p)) commands.send_sms(p, fm.cleaned_data['sms_to'], fm.cleaned_data['sms_text']) cl = {'opts': {'app_label': "smsapp"}} return render(request, 'admin/smsapp/utils/mass_sms.html', {'cl': cl, 'sms_form': fm}) @admin_user_required def country_list_admin(request): countries = models.PhoneData.objects.get_country_list_total() cl = {'opts': {'app_label': "smsapp"}} return render(request, 'admin/smsapp/info/countries.html', {'cl': cl, 'data': countries}) @admin_user_required def option_blacklist(request): class BlacklistForm(forms.Form): content = forms.CharField(widget=forms.Textarea) opt, created = models.Option.objects.get_or_create(name="blacklist") fm = BlacklistForm(request.POST or None, initial={'content': opt.content}) if fm.is_valid(): opt.content = fm.cleaned_data.get("content") opt.save() messages.success(request, "Saved") return redirect('admin:index') cl = {'opts': {'app_label': "smsapp"}} return render(request, 'admin/smsapp/utils/blacklist.html', {'cl': cl, 'form': fm}) @admin_user_required def crash_report(request, oid): o = settings.MONGO['extra_data'].find_one(ObjectId(oid)) d = {'code': o['code'], 'data': o['data']} return render(request, 'admin/smsapp/phonedata/view_report.html', d)
[ "logging.getLogger", "django.shortcuts.render", "django.utils.translation.ugettext_lazy", "models.PhoneData.objects.order_by", "models.InstalledApp.objects.get_top_apps", "django.forms.CharField", "pycountry.countries.get", "bson.objectid.ObjectId", "django.shortcuts.get_object_or_404", "models.Ph...
[((423, 450), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (440, 450), False, 'import logging\n'), ((855, 920), 'django.shortcuts.render', 'render', (['request', 'tmpl', "{'cards': info, 'cl': cl}"], {'content_type': 'ct'}), "(request, tmpl, {'cards': info, 'cl': cl}, content_type=ct)\n", (861, 920), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((1082, 1103), 'django.shortcuts.redirect', 'redirect', (['"""card_list"""'], {}), "('card_list')\n", (1090, 1103), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((2819, 2898), 'django.shortcuts.render', 'render', (['request', '"""admin/smsapp/info/forms_list.html"""', "{'forms': info, 'cl': cl}"], {}), "(request, 'admin/smsapp/info/forms_list.html', {'forms': info, 'cl': cl})\n", (2825, 2898), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((3501, 3590), 'django.shortcuts.render', 'render', (['request', '"""admin/smsapp/info/html_form_details.html"""', "{'form': form, 'cl': cl}"], {}), "(request, 'admin/smsapp/info/html_form_details.html', {'form': form,\n 'cl': cl})\n", (3507, 3590), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((3785, 3873), 'django.shortcuts.render', 'render', (['request', '"""admin/smsapp/info/html_forms_list.html"""', "{'forms': info, 'cl': cl}"], {}), "(request, 'admin/smsapp/info/html_forms_list.html', {'forms': info,\n 'cl': cl})\n", (3791, 3873), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((5098, 5147), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['models.PhoneData'], {'uniq_id': 'code'}), '(models.PhoneData, uniq_id=code)\n', (5115, 5147), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((5159, 5210), 'django.shortcuts.redirect', 'redirect', (['"""admin:smsapp_phonedata_change"""', 'phone.id'], {}), "('admin:smsapp_phonedata_change', phone.id)\n", (5167, 5210), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((5893, 5972), 'django.shortcuts.render', 'render', (['request', '"""admin/smsapp/utils/mass_sms.html"""', "{'cl': cl, 'sms_form': fm}"], {}), "(request, 'admin/smsapp/utils/mass_sms.html', {'cl': cl, 'sms_form': fm})\n", (5899, 5972), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((6045, 6094), 'models.PhoneData.objects.get_country_list_total', 'models.PhoneData.objects.get_country_list_total', ([], {}), '()\n', (6092, 6094), False, 'import models\n'), ((6149, 6235), 'django.shortcuts.render', 'render', (['request', '"""admin/smsapp/info/countries.html"""', "{'cl': cl, 'data': countries}"], {}), "(request, 'admin/smsapp/info/countries.html', {'cl': cl, 'data':\n countries})\n", (6155, 6235), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((6400, 6453), 'models.Option.objects.get_or_create', 'models.Option.objects.get_or_create', ([], {'name': '"""blacklist"""'}), "(name='blacklist')\n", (6435, 6453), False, 'import models\n'), ((6763, 6839), 'django.shortcuts.render', 'render', (['request', '"""admin/smsapp/utils/blacklist.html"""', "{'cl': cl, 'form': fm}"], {}), "(request, 'admin/smsapp/utils/blacklist.html', {'cl': cl, 'form': fm})\n", (6769, 6839), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((7014, 7075), 'django.shortcuts.render', 'render', (['request', '"""admin/smsapp/phonedata/view_report.html"""', 'd'], {}), "(request, 'admin/smsapp/phonedata/view_report.html', d)\n", (7020, 7075), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((3010, 3025), 'bson.objectid.ObjectId', 'ObjectId', (['objid'], {}), '(objid)\n', (3018, 3025), False, 'from bson.objectid import ObjectId\n'), ((3407, 3422), 'bson.objectid.ObjectId', 'ObjectId', (['objid'], {}), '(objid)\n', (3415, 3422), False, 'from bson.objectid import ObjectId\n'), ((4675, 4717), 'models.InstalledApp.objects.get_top_apps', 'models.InstalledApp.objects.get_top_apps', ([], {}), '()\n', (4715, 4717), False, 'import models\n'), ((5314, 5345), 'django.forms.CharField', 'forms.CharField', ([], {'max_length': '(255)'}), '(max_length=255)\n', (5329, 5345), False, 'from django import forms\n'), ((5365, 5403), 'django.forms.CharField', 'forms.CharField', ([], {'widget': 'forms.Textarea'}), '(widget=forms.Textarea)\n', (5380, 5403), False, 'from django import forms\n'), ((5524, 5651), 'models.PhoneData.objects.raw', 'models.PhoneData.objects.raw', (['"""SELECT * FROM smsapp_phonedata WHERE last_connection >= NOW() - INTERVAL \'15 minutes\'"""'], {}), '(\n "SELECT * FROM smsapp_phonedata WHERE last_connection >= NOW() - INTERVAL \'15 minutes\'"\n )\n', (5552, 5651), False, 'import models\n'), ((6341, 6379), 'django.forms.CharField', 'forms.CharField', ([], {'widget': 'forms.Textarea'}), '(widget=forms.Textarea)\n', (6356, 6379), False, 'from django import forms\n'), ((6635, 6669), 'django.contrib.messages.success', 'messages.success', (['request', '"""Saved"""'], {}), "(request, 'Saved')\n", (6651, 6669), False, 'from django.contrib import messages\n'), ((6685, 6708), 'django.shortcuts.redirect', 'redirect', (['"""admin:index"""'], {}), "('admin:index')\n", (6693, 6708), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((6941, 6954), 'bson.objectid.ObjectId', 'ObjectId', (['oid'], {}), '(oid)\n', (6949, 6954), False, 'from bson.objectid import ObjectId\n'), ((1028, 1041), 'bson.objectid.ObjectId', 'ObjectId', (['oid'], {}), '(oid)\n', (1036, 1041), False, 'from bson.objectid import ObjectId\n'), ((5762, 5838), 'commands.send_sms', 'commands.send_sms', (['p', "fm.cleaned_data['sms_to']", "fm.cleaned_data['sms_text']"], {}), "(p, fm.cleaned_data['sms_to'], fm.cleaned_data['sms_text'])\n", (5779, 5838), False, 'import commands\n'), ((1377, 1394), 'django.utils.translation.ugettext_lazy', '_', (['"""account type"""'], {}), "('account type')\n", (1378, 1394), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((2168, 2185), 'django.utils.translation.ugettext_lazy', '_', (['"""account type"""'], {}), "('account type')\n", (2169, 2185), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4170, 4207), 'pycountry.countries.get', 'pycountry.countries.get', ([], {'alpha2': 'ccode'}), '(alpha2=ccode)\n', (4193, 4207), False, 'import pycountry\n'), ((4025, 4069), 'models.PhoneData.objects.order_by', 'models.PhoneData.objects.order_by', (['"""country"""'], {}), "('country')\n", (4058, 4069), False, 'import models\n')]
import argparse parser = argparse.ArgumentParser(description="Generate path to config file given input") parser.add_argument('vars', nargs='+') args = parser.parse_args() # The last item of vars contains the random seed result = '-'.join(args.vars[:-1]) print(result)
[ "argparse.ArgumentParser" ]
[((26, 105), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Generate path to config file given input"""'}), "(description='Generate path to config file given input')\n", (49, 105), False, 'import argparse\n')]
from setuptools import setup setup(name='my_project', version='0.1.0', packages=['my_project'], entry_points={ 'console_scripts': [ 'my_project = my_project.__main__:main' ] }, )
[ "setuptools.setup" ]
[((32, 184), 'setuptools.setup', 'setup', ([], {'name': '"""my_project"""', 'version': '"""0.1.0"""', 'packages': "['my_project']", 'entry_points': "{'console_scripts': ['my_project = my_project.__main__:main']}"}), "(name='my_project', version='0.1.0', packages=['my_project'],\n entry_points={'console_scripts': ['my_project = my_project.__main__:main']}\n )\n", (37, 184), False, 'from setuptools import setup\n')]
import os import sys import imp import argparse import time import math import numpy as np from utils import utils from utils.imageprocessing import preprocess from utils.dataset import Dataset from network import Network from evaluation.lfw import LFWTest def main(args): paths = [ r'F:\data\face-recognition\lfw\lfw-112-mxnet\Abdoulaye_Wade\Abdoulaye_Wade_0002.jpg', r'F:\data\face-recognition\lfw\lfw-112-mxnet\Abdoulaye_Wade\Abdoulaye_Wade_0003.jpg', r'F:\data\face-recognition\realsense\data-labeled-clean-strict2-112-mxnet\rgb\001-chenkai\a-000013.jpg', r'F:\data\face-recognition\realsense\data-labeled-clean-strict2-112-mxnet\rgb\001-chenkai\rgb_2.jpg', r'F:\data\face-recognition\lfw\lfw-112-mxnet\Abdoulaye_Wade\Abdoulaye_Wade_0002.jpg', r'F:\data\face-recognition\realsense\data-labeled-clean-strict2-112-mxnet\rgb\001-chenkai\rgb_2.jpg', r'F:\data\face-recognition\lfw\lfw-112-mxnet\Abdoulaye_Wade\Abdoulaye_Wade_0003.jpg', r'F:\data\face-recognition\realsense\data-labeled-clean-strict2-112-mxnet\rgb\001-chenkai\rgb_2.jpg', ] print('%d images to load.' % len(paths)) assert(len(paths)>0) # Load model files and config file network = Network() network.load_model(args.model_dir) # network.config.preprocess_train = [] # network.config.preprocess_test = [] images = preprocess(paths, network.config, False) import cv2 # images = np.array([cv2.resize(img, (96, 96)) for img in images]) # images = (images - 128.) / 128. # images = images[..., ::-1] print(images.shape) # print(images[0,:5,:5,0]) # Run forward pass to calculate embeddings mu, sigma_sq = network.extract_feature(images, args.batch_size, verbose=True) print(mu.shape, sigma_sq.shape) print('sigma_sq', np.max(sigma_sq), np.min(sigma_sq), np.mean(sigma_sq), np.exp(np.mean(np.log(sigma_sq)))) log_sigma_sq = np.log(sigma_sq) print('log_sigma_sq', np.max(log_sigma_sq), np.min(log_sigma_sq), np.mean(log_sigma_sq)) # print('sigma_sq', sigma_sq) feat_pfe = np.concatenate([mu, sigma_sq], axis=1) score = utils.pair_cosin_score(mu[::2], mu[1::2]) print(score) score = utils.pair_MLS_score(feat_pfe[::2], feat_pfe[1::2]) print(score) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--model_dir", help="The path to the pre-trained model directory", type=str, default=r'D:\chenkai\Probabilistic-Face-Embeddings-master\log\resface64_relu_msarcface_am_PFE/20191229-172304-iter15') parser.add_argument("--batch_size", help="Number of images per mini batch", type=int, default=128) args = parser.parse_args() main(args)
[ "numpy.mean", "utils.utils.pair_MLS_score", "argparse.ArgumentParser", "numpy.log", "numpy.max", "network.Network", "utils.utils.pair_cosin_score", "numpy.concatenate", "numpy.min", "utils.imageprocessing.preprocess" ]
[((1241, 1250), 'network.Network', 'Network', ([], {}), '()\n', (1248, 1250), False, 'from network import Network\n'), ((1388, 1428), 'utils.imageprocessing.preprocess', 'preprocess', (['paths', 'network.config', '(False)'], {}), '(paths, network.config, False)\n', (1398, 1428), False, 'from utils.imageprocessing import preprocess\n'), ((1939, 1955), 'numpy.log', 'np.log', (['sigma_sq'], {}), '(sigma_sq)\n', (1945, 1955), True, 'import numpy as np\n'), ((2099, 2137), 'numpy.concatenate', 'np.concatenate', (['[mu, sigma_sq]'], {'axis': '(1)'}), '([mu, sigma_sq], axis=1)\n', (2113, 2137), True, 'import numpy as np\n'), ((2151, 2192), 'utils.utils.pair_cosin_score', 'utils.pair_cosin_score', (['mu[::2]', 'mu[1::2]'], {}), '(mu[::2], mu[1::2])\n', (2173, 2192), False, 'from utils import utils\n'), ((2223, 2274), 'utils.utils.pair_MLS_score', 'utils.pair_MLS_score', (['feat_pfe[::2]', 'feat_pfe[1::2]'], {}), '(feat_pfe[::2], feat_pfe[1::2])\n', (2243, 2274), False, 'from utils import utils\n'), ((2334, 2359), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2357, 2359), False, 'import argparse\n'), ((1830, 1846), 'numpy.max', 'np.max', (['sigma_sq'], {}), '(sigma_sq)\n', (1836, 1846), True, 'import numpy as np\n'), ((1848, 1864), 'numpy.min', 'np.min', (['sigma_sq'], {}), '(sigma_sq)\n', (1854, 1864), True, 'import numpy as np\n'), ((1866, 1883), 'numpy.mean', 'np.mean', (['sigma_sq'], {}), '(sigma_sq)\n', (1873, 1883), True, 'import numpy as np\n'), ((1982, 2002), 'numpy.max', 'np.max', (['log_sigma_sq'], {}), '(log_sigma_sq)\n', (1988, 2002), True, 'import numpy as np\n'), ((2004, 2024), 'numpy.min', 'np.min', (['log_sigma_sq'], {}), '(log_sigma_sq)\n', (2010, 2024), True, 'import numpy as np\n'), ((2026, 2047), 'numpy.mean', 'np.mean', (['log_sigma_sq'], {}), '(log_sigma_sq)\n', (2033, 2047), True, 'import numpy as np\n'), ((1900, 1916), 'numpy.log', 'np.log', (['sigma_sq'], {}), '(sigma_sq)\n', (1906, 1916), True, 'import numpy as np\n')]
from django.conf.urls import url from personal.models import Book from . import views from django.contrib.auth.views import login from django.views.generic import ListView, DetailView urlpatterns = [ url(r'^$', views.index , name='index'), url(r'^login/$', login, {'template_name': 'personal/login.html'}), url(r'^lib/$', ListView.as_view(queryset=Book.objects.all().order_by("-date")[:25], template_name = "personal/lib.html")), url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Book, template_name='personal/book.html')) ]
[ "personal.models.Book.objects.all", "django.views.generic.DetailView.as_view", "django.conf.urls.url" ]
[((207, 243), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.index'], {'name': '"""index"""'}), "('^$', views.index, name='index')\n", (210, 243), False, 'from django.conf.urls import url\n'), ((251, 315), 'django.conf.urls.url', 'url', (['"""^login/$"""', 'login', "{'template_name': 'personal/login.html'}"], {}), "('^login/$', login, {'template_name': 'personal/login.html'})\n", (254, 315), False, 'from django.conf.urls import url\n'), ((503, 569), 'django.views.generic.DetailView.as_view', 'DetailView.as_view', ([], {'model': 'Book', 'template_name': '"""personal/book.html"""'}), "(model=Book, template_name='personal/book.html')\n", (521, 569), False, 'from django.views.generic import ListView, DetailView\n'), ((363, 381), 'personal.models.Book.objects.all', 'Book.objects.all', ([], {}), '()\n', (379, 381), False, 'from personal.models import Book\n')]