hexsha
stringlengths
40
40
size
int64
1
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
239
max_stars_repo_name
stringlengths
5
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
239
max_issues_repo_name
stringlengths
5
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
239
max_forks_repo_name
stringlengths
5
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.03M
avg_line_length
float64
1
958k
max_line_length
int64
1
1.03M
alphanum_fraction
float64
0
1
7956fd0fb520a59d5e2337c5959a149babd708b1
110
py
Python
dsbox/ml/neural_networks/processing/__init__.py
Pandinosaurus/dsbox
aea56049025ed7e6e66427f8636286f8be1b6e03
[ "Apache-2.0" ]
16
2020-05-11T09:10:15.000Z
2021-04-13T08:43:28.000Z
dsbox/ml/neural_networks/processing/__init__.py
Pandinosaurus/dsbox
aea56049025ed7e6e66427f8636286f8be1b6e03
[ "Apache-2.0" ]
1
2020-12-03T20:02:32.000Z
2020-12-03T20:02:32.000Z
dsbox/ml/neural_networks/processing/__init__.py
Pandinosaurus/dsbox
aea56049025ed7e6e66427f8636286f8be1b6e03
[ "Apache-2.0" ]
1
2020-05-11T17:22:20.000Z
2020-05-11T17:22:20.000Z
from .text_classification import Text2Sequence from . import text_classification __all__ = ["Text2Sequence"]
22
46
0.827273
7956fd2bf520297c6f02d03b4e6cc3086fa9f160
815
py
Python
skhep/utils/py23.py
AdvaitDhingra/scikit-hep
1e08901447c3e42e4c4b703ea6c09e3bd0db25af
[ "BSD-3-Clause" ]
150
2016-11-14T14:09:29.000Z
2022-03-18T16:37:03.000Z
skhep/utils/py23.py
AdvaitDhingra/scikit-hep
1e08901447c3e42e4c4b703ea6c09e3bd0db25af
[ "BSD-3-Clause" ]
123
2017-01-30T10:03:04.000Z
2022-03-31T06:26:09.000Z
skhep/utils/py23.py
AdvaitDhingra/scikit-hep
1e08901447c3e42e4c4b703ea6c09e3bd0db25af
[ "BSD-3-Clause" ]
41
2017-01-11T11:42:56.000Z
2021-12-06T22:38:32.000Z
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license, see LICENSE. """ Trivial module to deal with Python 2 and 3 compatibility. """ # ----------------------------------------------------------------------------- # Import statements # ----------------------------------------------------------------------------- import sys # ----------------------------------------------------------------------------- # Python 2 and 3 "conversions" # ----------------------------------------------------------------------------- if sys.version_info[0] > 2: string_types = (bytes, str) xrange = range long = int from io import IOBase file = IOBase def head(x): return iter(x).__next__() else: string_types = (str, unicode) def head(x): return iter(x).next()
25.46875
79
0.381595
7956fd4470e3c0033beaf38695f2807bead782c9
5,323
py
Python
HanderCode/aidaiwangApp/aidaiwangApp/BaseMonitor.py
mocne/PycharmProjects
b009e530f4f01e5b1826bbe2364d86b65bcd66e3
[ "MIT" ]
null
null
null
HanderCode/aidaiwangApp/aidaiwangApp/BaseMonitor.py
mocne/PycharmProjects
b009e530f4f01e5b1826bbe2364d86b65bcd66e3
[ "MIT" ]
null
null
null
HanderCode/aidaiwangApp/aidaiwangApp/BaseMonitor.py
mocne/PycharmProjects
b009e530f4f01e5b1826bbe2364d86b65bcd66e3
[ "MIT" ]
null
null
null
#coding:utf8 import subprocess import os import re from wsgiref.validate import validator import platform cpu = [] men = [] flow = [[], []] fps = [] battery = [] def get_cpu(pkg_name): if platform.system() == 'Windows': # windows操作系统 cmd = "adb shell dumpsys cpuinfo | findstr " + pkg_name # print(cmd) output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines() for info in output: if info.split()[1].decode().split("/")[1][:-1] == pkg_name: # 只有包名相等 # print("cpu=" + info.split()[2].decode()) cpu.append(float(info.split()[2].decode().split("%")[0])) # print("----cpu-----") # print(cpu) return cpu elif platform.system() == 'Darwin': # Mac 操作系统 cmd = "adb shell dumpsys cpuinfo | find " + pkg_name # print(cmd) output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines() for info in output: if info.split()[1].decode().split("/")[1][:-1] == pkg_name: # 只有包名相等 # print("cpu=" + info.split()[2].decode()) cpu.append(float(info.split()[2].decode().split("%")[0])) # print("----cpu-----") # print(cpu) return cpu def get_men(pkg_name): cmd = "adb shell dumpsys meminfo %s" % pkg_name # print(cmd) men_s = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines() for info in men_s: if len(info.split()) and info.split()[0].decode() == "TOTAL": # print("men="+info.split()[1].decode()) men.append(int(info.split()[1].decode())) # print("----men----") # print(men) return men # 得到fps ''' @author fenfenzhong ''' def get_fps(pkg_name): _adb = "adb shell dumpsys gfxinfo %s" % pkg_name # print(_adb) results = os.popen(_adb).read().strip() frames = [x for x in results.split('\n') if validator(x)] frame_count = len(frames) jank_count = 0 vsync_overtime = 0 render_time = 0 for frame in frames: time_block = re.split(r'\s+', frame.strip()) if len(time_block) == 3: try: render_time = float(time_block[0]) + float(time_block[1]) + float(time_block[2]) except Exception as e: render_time = 0 ''' 当渲染时间大于16.67,按照垂直同步机制,该帧就已经渲染超时 那么,如果它正好是16.67的整数倍,比如66.68,则它花费了4个垂直同步脉冲,减去本身需要一个,则超时3个 如果它不是16.67的整数倍,比如67,那么它花费的垂直同步脉冲应向上取整,即5个,减去本身需要一个,即超时4个,可直接算向下取整 最后的计算方法思路: 执行一次命令,总共收集到了m帧(理想情况下m=128),但是这m帧里面有些帧渲染超过了16.67毫秒,算一次jank,一旦jank, 需要用掉额外的垂直同步脉冲。其他的就算没有超过16.67,也按一个脉冲时间来算(理想情况下,一个脉冲就可以渲染完一帧) 所以FPS的算法可以变为: m / (m + 额外的垂直同步脉冲) * 60 ''' if render_time > 16.67: jank_count += 1 if render_time % 16.67 == 0: vsync_overtime += int(render_time / 16.67) - 1 else: vsync_overtime += int(render_time / 16.67) _fps = int(frame_count * 60 / (frame_count + vsync_overtime)) fps.append(_fps) # return (frame_count, jank_count, fps) # print("-----fps------") # print(fps) return fps def get_battery(): _batter = subprocess.Popen("adb shell dumpsys battery", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines() for info in _batter: if info.split()[0].decode() == "level:": battery.append(int(info.split()[1].decode())) # print("-----battery------") # print(battery) return int(info.split()[1].decode()) def get_pid(pkg_name): pid = subprocess.Popen("adb shell ps | findstr " + pkg_name, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines() for item in pid: if item.split()[8].decode() == pkg_name: return item.split()[1].decode() def get_flow(pkg_name, type): pid = get_pid(pkg_name) if pid is not None: _flow = subprocess.Popen("adb shell cat /proc/" + pid + "/net/dev", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.readlines() for item in _flow: if type == "wifi" and item.split()[0].decode() == "wlan0:": # wifi # 0 上传流量,1 下载流量 flow[0].append(int(item.split()[1].decode())) flow[1].append(int(item.split()[9].decode())) # print("------flow---------") # print(flow) return flow if type == "gprs" and item.split()[0].decode() == "rmnet0:": # gprs print("--------------") flow[0].append(int(item.split()[1].decode())) flow[1].append(int(item.split()[9].decode())) return flow else: flow[0].append(0) flow[1].append(0) return flow if __name__ == '__main__': # pid = get_pid("com.jianshu.haruki") print(get_flow("com.jianshu.haruki", "gprs")) print(get_flow("com.jianshu.haruki", "gprs")) print(get_flow("com.jianshu.haruki", "gprs"))
35.724832
117
0.547999
7956fdddd8766fffb317279fe7454aa25aa5cbe8
2,582
py
Python
d4rl/gym_minigrid/envs/fourrooms.py
xfdywy/d4rl
d15b165c1e68d8c04d19faf44cd387046a4988a2
[ "Apache-2.0" ]
552
2020-04-20T01:07:02.000Z
2022-03-31T16:47:39.000Z
d4rl/d4rl/gym_minigrid/envs/fourrooms.py
clvrai/goal_prox_il
7c809b2ee575a69a14997068db06f3c1f3c8bd08
[ "MIT" ]
103
2020-04-20T14:18:32.000Z
2022-03-30T14:33:45.000Z
d4rl/d4rl/gym_minigrid/envs/fourrooms.py
clvrai/goal_prox_il
7c809b2ee575a69a14997068db06f3c1f3c8bd08
[ "MIT" ]
135
2020-04-21T16:57:52.000Z
2022-03-30T14:29:55.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- from d4rl.gym_minigrid.minigrid import * from d4rl.gym_minigrid.register import register class FourRoomsEnv(MiniGridEnv): """ Classic 4 rooms gridworld environment. Can specify agent and goal position, if not it set at random. """ def __init__(self, agent_pos=None, goal_pos=None, **kwargs): self._agent_default_pos = agent_pos if goal_pos is None: goal_pos = (12, 12) self._goal_default_pos = goal_pos super().__init__(grid_size=19, max_steps=100, **kwargs) def get_target(self): return self._goal_default_pos def _gen_grid(self, width, height): # Create the grid self.grid = Grid(width, height) # Generate the surrounding walls self.grid.horz_wall(0, 0) self.grid.horz_wall(0, height - 1) self.grid.vert_wall(0, 0) self.grid.vert_wall(width - 1, 0) room_w = width // 2 room_h = height // 2 # For each row of rooms for j in range(0, 2): # For each column for i in range(0, 2): xL = i * room_w yT = j * room_h xR = xL + room_w yB = yT + room_h # Bottom wall and door if i + 1 < 2: self.grid.vert_wall(xR, yT, room_h) pos = (xR, self._rand_int(yT + 1, yB)) self.grid.set(*pos, None) # Bottom wall and door if j + 1 < 2: self.grid.horz_wall(xL, yB, room_w) pos = (self._rand_int(xL + 1, xR), yB) self.grid.set(*pos, None) # Randomize the player start position and orientation if self._agent_default_pos is not None: self.agent_pos = self._agent_default_pos self.grid.set(*self._agent_default_pos, None) self.agent_dir = self._rand_int(0, 4) # assuming random start direction else: self.place_agent() if self._goal_default_pos is not None: goal = Goal() self.put_obj(goal, *self._goal_default_pos) goal.init_pos, goal.cur_pos = self._goal_default_pos else: self.place_obj(Goal()) self.mission = 'Reach the goal' def step(self, action): obs, reward, done, info = MiniGridEnv.step(self, action) return obs, reward, done, info register( id='MiniGrid-FourRooms-v0', entry_point='gym_minigrid.envs:FourRoomsEnv' )
30.738095
84
0.559644
7956fdfb583e40dd6d78fc346493e11e392dead6
4,928
py
Python
experimental/python/gui/selectbox.py
Drahflow/Embroidermodder
5fe2bed6407845e9d183aee40095b3f778a5b559
[ "Zlib" ]
null
null
null
experimental/python/gui/selectbox.py
Drahflow/Embroidermodder
5fe2bed6407845e9d183aee40095b3f778a5b559
[ "Zlib" ]
null
null
null
experimental/python/gui/selectbox.py
Drahflow/Embroidermodder
5fe2bed6407845e9d183aee40095b3f778a5b559
[ "Zlib" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ============================= |module_summary| selectbox.py ============================= TOWRITE Classes summary: ================ ============================ ============================ :class:`~SelectBox` TOWRITE ============================ ============================ --------------------------------------------------------- | """ #-Imports.--------------------------------------------------------------------- #--PySide/PyQt Imports. try: ## from PySide import QtCore, QtGui # or... Improve performace with less dots... from PySide.QtCore import qDebug, Qt, QSize from PySide.QtGui import QRubberBand, QColor, QPen, QBrush, QPainter PYSIDE = True PYQT4 = False except ImportError: raise # ## from PyQt4 import QtCore, QtGui # # or... Improve performace with less dots... # from PyQt4.QtCore import qDebug, Qt, QSize # from PyQt4.QtGui import QRubberBand, QColor, QPen, QBrush, QPainter # PYSIDE = False # PYQT4 = True # C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++ #include "selectbox.h" #include <QPainter> # C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++C++ class SelectBox(QRubberBand): """ Subclass of `QRubberBand`_ TOWRITE """ def __init__(self, s, parent=None): """ Default class constructor. :param `s`: TOWRITE :type `s`: QRubberBand.Shape :param `parent`: Pointer to a parent widget instance. :type `parent`: `QWidget`_ """ super(SelectBox, self).__init__(parent) # private self._leftBrushColor = QColor() self._rightBrushColor = QColor() self._leftPenColor = QColor() self._rightPenColor = QColor() self._alpha = 255 # quint8 #: TODO: what is the initial int? self._dirBrush = QBrush() self._leftBrush = QBrush() self._rightBrush = QBrush() self._dirPen = QPen() self._leftPen = QPen() self._rightPen = QPen() self._boxDir = False #: TODO: is this initial bool value right? # Default values self.setColors(QColor(Qt.darkGreen), QColor(Qt.green), QColor(Qt.darkBlue), QColor(Qt.blue), 32) def setDirection(self, dir): """ TOWRITE :param `dir`: TOWRITE :type `dir`: int """ if not dir: self._dirPen = self._leftPen self._dirBrush = self._leftBrush else: self._dirPen = self._rightPen self._dirBrush = self._rightBrush self._boxDir = dir def setColors(self, colorL, fillL, colorR, fillR, newAlpha): """ TOWRITE :param `colorL`: TOWRITE :type `colorL`: `QColor`_ :param `fillL`: TOWRITE :type `fillL`: `QColor`_ :param `colorR`: TOWRITE :type `colorR`: `QColor`_ :param `fillR`: TOWRITE :type `fillR`: `QColor`_ :param `newAlpha`: TOWRITE :type `newAlpha`: int """ qDebug("SelectBox setColors()") self._alpha = newAlpha self._leftPenColor = colorL # TODO: allow customization self._leftBrushColor = QColor(fillL.red(), fillL.green(), fillL.blue(), alpha) self._rightPenColor = colorR # TODO: allow customization self._rightBrushColor = QColor(fillR.red(), fillR.green(), fillR.blue(), alpha) self._leftPen.setColor(self._leftPenColor) self._leftPen.setStyle(Qt.DashLine) self._leftBrush.setStyle(Qt.SolidPattern) self._leftBrush.setColor(self._leftBrushColor) self._rightPen.setColor(self._rightPenColor) self._rightPen.setStyle(Qt.SolidLine) self._rightBrush.setStyle(Qt.SolidPattern) self._rightBrush.setColor(self._rightBrushColor) if not self._boxDir: self._dirPen = self._leftPen self._dirBrush = self._leftBrush else: self._dirPen = self._rightPen self._dirBrush = self._rightBrush self.forceRepaint() def paintEvent(self, event): """ Handles the ``paintEvent`` event for :class:`SelectBox`. :param `event`: A `QPaintEvent`_ to be processed. """ painter = QPainter(self) painter.setPen(self._dirPen) width, height = self.width(), self.height() painter.fillRect(0, 0, width - 1, height - 1, self._dirBrush) painter.drawRect(0, 0, width - 1, height - 1) def forceRepaint(self): """ Force repaint the rubberband. .. NOTE:: HACK: Take that QRubberBand! """ # HACK: Take that QRubberBand! hack = self.size() # QSize self.resize(hack + QSize(1, 1)) self.resize(hack) # kate: bom off; indent-mode python; indent-width 4; replace-trailing-space-save on;
29.159763
104
0.551339
7956fe9e2ac504aff6c7f5966ba0f97325685f4c
3,147
py
Python
awardsApp/models.py
MutuaFranklin/App-Awards
020c85db144156ec02f12815cd675245d4ad9db3
[ "MIT" ]
null
null
null
awardsApp/models.py
MutuaFranklin/App-Awards
020c85db144156ec02f12815cd675245d4ad9db3
[ "MIT" ]
null
null
null
awardsApp/models.py
MutuaFranklin/App-Awards
020c85db144156ec02f12815cd675245d4ad9db3
[ "MIT" ]
null
null
null
from django.db import models from cloudinary.models import CloudinaryField from django.contrib.auth.models import User from profiles.models import Profile from tinymce.models import HTMLField # Create your models here. class Project(models.Model): title = models.CharField(max_length = 30) project_image = CloudinaryField('Project image') description = HTMLField() technologies = models.CharField(max_length=200, blank=True) project_link = models.URLField() publisher = models.ForeignKey(Profile, on_delete=models.CASCADE) date_published = models.DateTimeField(auto_now_add=True, null = True) def __str__(self): return self.title def save_project(self): self.save() def delete_project(self): self.delete() @classmethod def display_all_projects(cls): return cls.objects.all() @classmethod def search_project(cls,project_title): return Project.objects.filter(title__icontains = project_title) @classmethod def get_user_projects(cls,profile): return cls.objects.filter(profile=profile) @classmethod def update_project(cls, proj_id, updated_proj_title): project = cls.objects.filter(id = proj_id).update(title = updated_proj_title) return project class Meta: ordering = ['-date_published'] class Review(models.Model): project = models.ForeignKey(Project, on_delete= models.CASCADE, related_name='reviews') review = models.TextField() reviewed_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reviews') reviewed_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.project} Review' def save_review(self): self.save() def delete_review(self): self.delete() @classmethod def update_review(cls, proj_id, updated_review): review = cls.objects.filter(id = proj_id).update(review = updated_review) return review class Meta: ordering = ['-reviewed_on'] class Rating(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='ratings', null=True) design = models.IntegerField(blank=True) usability = models.IntegerField(blank=True) content = models.IntegerField(blank=True) score = models.FloatField(default=0, blank=True) rated_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='rater') def __str__(self): return f'{self.project} Rating' def save_rating(self): self.save() def delete_rating(self): self.delete() @classmethod def get_ratings(cls, id): ratings = Rating.objects.filter(post_id=id).all() return ratings @classmethod def update_rating(cls, reviewId, newReview): design_rating = cls.objects.filter(id = reviewId).update(design = newReview) # usability = cls.objects.filter(id = reviewId).update(usability = newReview) # content = cls.objects.filter(id = reviewId).update(content = newReview) return design_rating
27.605263
101
0.690181
7956feea8818cdfe883aa90017e7538dcecb44ad
12,329
py
Python
docusign_esign/models/access_code_format.py
joekohlsdorf/docusign-esign-python-client
40407544f79c88716d36fabf36f65c3ef1a5c3ba
[ "MIT" ]
58
2017-10-18T23:06:57.000Z
2021-04-15T23:14:58.000Z
docusign_esign/models/access_code_format.py
joekohlsdorf/docusign-esign-python-client
40407544f79c88716d36fabf36f65c3ef1a5c3ba
[ "MIT" ]
49
2017-10-27T05:54:09.000Z
2021-04-29T22:06:17.000Z
docusign_esign/models/access_code_format.py
joekohlsdorf/docusign-esign-python-client
40407544f79c88716d36fabf36f65c3ef1a5c3ba
[ "MIT" ]
49
2017-09-16T07:23:41.000Z
2021-05-07T20:21:20.000Z
# coding: utf-8 """ DocuSign REST API The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501 OpenAPI spec version: v2.1 Contact: devcenter@docusign.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from docusign_esign.client.configuration import Configuration class AccessCodeFormat(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'format_required': 'str', 'format_required_metadata': 'SettingsMetadata', 'letter_required': 'str', 'letter_required_metadata': 'SettingsMetadata', 'minimum_length': 'str', 'minimum_length_metadata': 'SettingsMetadata', 'number_required': 'str', 'number_required_metadata': 'SettingsMetadata', 'special_character_required': 'str', 'special_character_required_metadata': 'SettingsMetadata' } attribute_map = { 'format_required': 'formatRequired', 'format_required_metadata': 'formatRequiredMetadata', 'letter_required': 'letterRequired', 'letter_required_metadata': 'letterRequiredMetadata', 'minimum_length': 'minimumLength', 'minimum_length_metadata': 'minimumLengthMetadata', 'number_required': 'numberRequired', 'number_required_metadata': 'numberRequiredMetadata', 'special_character_required': 'specialCharacterRequired', 'special_character_required_metadata': 'specialCharacterRequiredMetadata' } def __init__(self, _configuration=None, **kwargs): # noqa: E501 """AccessCodeFormat - a model defined in Swagger""" # noqa: E501 if _configuration is None: _configuration = Configuration() self._configuration = _configuration self._format_required = None self._format_required_metadata = None self._letter_required = None self._letter_required_metadata = None self._minimum_length = None self._minimum_length_metadata = None self._number_required = None self._number_required_metadata = None self._special_character_required = None self._special_character_required_metadata = None self.discriminator = None setattr(self, "_{}".format('format_required'), kwargs.get('format_required', None)) setattr(self, "_{}".format('format_required_metadata'), kwargs.get('format_required_metadata', None)) setattr(self, "_{}".format('letter_required'), kwargs.get('letter_required', None)) setattr(self, "_{}".format('letter_required_metadata'), kwargs.get('letter_required_metadata', None)) setattr(self, "_{}".format('minimum_length'), kwargs.get('minimum_length', None)) setattr(self, "_{}".format('minimum_length_metadata'), kwargs.get('minimum_length_metadata', None)) setattr(self, "_{}".format('number_required'), kwargs.get('number_required', None)) setattr(self, "_{}".format('number_required_metadata'), kwargs.get('number_required_metadata', None)) setattr(self, "_{}".format('special_character_required'), kwargs.get('special_character_required', None)) setattr(self, "_{}".format('special_character_required_metadata'), kwargs.get('special_character_required_metadata', None)) @property def format_required(self): """Gets the format_required of this AccessCodeFormat. # noqa: E501 # noqa: E501 :return: The format_required of this AccessCodeFormat. # noqa: E501 :rtype: str """ return self._format_required @format_required.setter def format_required(self, format_required): """Sets the format_required of this AccessCodeFormat. # noqa: E501 :param format_required: The format_required of this AccessCodeFormat. # noqa: E501 :type: str """ self._format_required = format_required @property def format_required_metadata(self): """Gets the format_required_metadata of this AccessCodeFormat. # noqa: E501 :return: The format_required_metadata of this AccessCodeFormat. # noqa: E501 :rtype: SettingsMetadata """ return self._format_required_metadata @format_required_metadata.setter def format_required_metadata(self, format_required_metadata): """Sets the format_required_metadata of this AccessCodeFormat. :param format_required_metadata: The format_required_metadata of this AccessCodeFormat. # noqa: E501 :type: SettingsMetadata """ self._format_required_metadata = format_required_metadata @property def letter_required(self): """Gets the letter_required of this AccessCodeFormat. # noqa: E501 # noqa: E501 :return: The letter_required of this AccessCodeFormat. # noqa: E501 :rtype: str """ return self._letter_required @letter_required.setter def letter_required(self, letter_required): """Sets the letter_required of this AccessCodeFormat. # noqa: E501 :param letter_required: The letter_required of this AccessCodeFormat. # noqa: E501 :type: str """ self._letter_required = letter_required @property def letter_required_metadata(self): """Gets the letter_required_metadata of this AccessCodeFormat. # noqa: E501 :return: The letter_required_metadata of this AccessCodeFormat. # noqa: E501 :rtype: SettingsMetadata """ return self._letter_required_metadata @letter_required_metadata.setter def letter_required_metadata(self, letter_required_metadata): """Sets the letter_required_metadata of this AccessCodeFormat. :param letter_required_metadata: The letter_required_metadata of this AccessCodeFormat. # noqa: E501 :type: SettingsMetadata """ self._letter_required_metadata = letter_required_metadata @property def minimum_length(self): """Gets the minimum_length of this AccessCodeFormat. # noqa: E501 # noqa: E501 :return: The minimum_length of this AccessCodeFormat. # noqa: E501 :rtype: str """ return self._minimum_length @minimum_length.setter def minimum_length(self, minimum_length): """Sets the minimum_length of this AccessCodeFormat. # noqa: E501 :param minimum_length: The minimum_length of this AccessCodeFormat. # noqa: E501 :type: str """ self._minimum_length = minimum_length @property def minimum_length_metadata(self): """Gets the minimum_length_metadata of this AccessCodeFormat. # noqa: E501 :return: The minimum_length_metadata of this AccessCodeFormat. # noqa: E501 :rtype: SettingsMetadata """ return self._minimum_length_metadata @minimum_length_metadata.setter def minimum_length_metadata(self, minimum_length_metadata): """Sets the minimum_length_metadata of this AccessCodeFormat. :param minimum_length_metadata: The minimum_length_metadata of this AccessCodeFormat. # noqa: E501 :type: SettingsMetadata """ self._minimum_length_metadata = minimum_length_metadata @property def number_required(self): """Gets the number_required of this AccessCodeFormat. # noqa: E501 # noqa: E501 :return: The number_required of this AccessCodeFormat. # noqa: E501 :rtype: str """ return self._number_required @number_required.setter def number_required(self, number_required): """Sets the number_required of this AccessCodeFormat. # noqa: E501 :param number_required: The number_required of this AccessCodeFormat. # noqa: E501 :type: str """ self._number_required = number_required @property def number_required_metadata(self): """Gets the number_required_metadata of this AccessCodeFormat. # noqa: E501 :return: The number_required_metadata of this AccessCodeFormat. # noqa: E501 :rtype: SettingsMetadata """ return self._number_required_metadata @number_required_metadata.setter def number_required_metadata(self, number_required_metadata): """Sets the number_required_metadata of this AccessCodeFormat. :param number_required_metadata: The number_required_metadata of this AccessCodeFormat. # noqa: E501 :type: SettingsMetadata """ self._number_required_metadata = number_required_metadata @property def special_character_required(self): """Gets the special_character_required of this AccessCodeFormat. # noqa: E501 # noqa: E501 :return: The special_character_required of this AccessCodeFormat. # noqa: E501 :rtype: str """ return self._special_character_required @special_character_required.setter def special_character_required(self, special_character_required): """Sets the special_character_required of this AccessCodeFormat. # noqa: E501 :param special_character_required: The special_character_required of this AccessCodeFormat. # noqa: E501 :type: str """ self._special_character_required = special_character_required @property def special_character_required_metadata(self): """Gets the special_character_required_metadata of this AccessCodeFormat. # noqa: E501 :return: The special_character_required_metadata of this AccessCodeFormat. # noqa: E501 :rtype: SettingsMetadata """ return self._special_character_required_metadata @special_character_required_metadata.setter def special_character_required_metadata(self, special_character_required_metadata): """Sets the special_character_required_metadata of this AccessCodeFormat. :param special_character_required_metadata: The special_character_required_metadata of this AccessCodeFormat. # noqa: E501 :type: SettingsMetadata """ self._special_character_required_metadata = special_character_required_metadata def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(AccessCodeFormat, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, AccessCodeFormat): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, AccessCodeFormat): return True return self.to_dict() != other.to_dict()
34.438547
140
0.665747
7956ffa4a8ee873de0e971ecc1e4646e5813dd1c
1,537
py
Python
venv/Lib/site-packages/numpy/core/tests/test__exceptions.py
AdarshSai/Final_project
f966834ca72dd232102ed500ef47ef2b3bdbed5b
[ "MIT" ]
353
2020-12-10T10:47:17.000Z
2022-03-31T23:08:29.000Z
venv/Lib/site-packages/numpy/core/tests/test__exceptions.py
AdarshSai/Final_project
f966834ca72dd232102ed500ef47ef2b3bdbed5b
[ "MIT" ]
80
2020-12-10T09:54:22.000Z
2022-03-30T22:08:45.000Z
venv/Lib/site-packages/numpy/core/tests/test__exceptions.py
AdarshSai/Final_project
f966834ca72dd232102ed500ef47ef2b3bdbed5b
[ "MIT" ]
63
2020-12-10T17:10:34.000Z
2022-03-28T16:27:07.000Z
""" Tests of the ._exceptions module. Primarily for exercising the __str__ methods. """ import numpy as np _ArrayMemoryError = np.core._exceptions._ArrayMemoryError class TestArrayMemoryError: def test_str(self): e = _ArrayMemoryError((1023,), np.dtype(np.uint8)) str(e) # not crashing is enough # testing these properties is easier than testing the full string repr def test__size_to_string(self): """ Test e._size_to_string """ f = _ArrayMemoryError._size_to_string Ki = 1024 assert f(0) == '0 bytes' assert f(1) == '1 bytes' assert f(1023) == '1023 bytes' assert f(Ki) == '1.00 KiB' assert f(Ki+1) == '1.00 KiB' assert f(10*Ki) == '10.0 KiB' assert f(int(999.4*Ki)) == '999. KiB' assert f(int(1023.4*Ki)) == '1023. KiB' assert f(int(1023.5*Ki)) == '1.00 MiB' assert f(Ki*Ki) == '1.00 MiB' # 1023.9999 Mib should round to 1 GiB assert f(int(Ki*Ki*Ki*0.9999)) == '1.00 GiB' assert f(Ki*Ki*Ki*Ki*Ki*Ki) == '1.00 EiB' # larger than sys.maxsize, adding larger prefices isn't going to help # anyway. assert f(Ki*Ki*Ki*Ki*Ki*Ki*123456) == '123456. EiB' def test__total_size(self): """ Test e._total_size """ e = _ArrayMemoryError((1,), np.dtype(np.uint8)) assert e._total_size == 1 e = _ArrayMemoryError((2, 4), np.dtype((np.uint64, 16))) assert e._total_size == 1024
35.744186
80
0.573845
7957002bc673987f6efe5ce2574a3b90ed36cbeb
275
py
Python
tests/integration/conftest.py
usmannasir/hcloud-python
2a90551fb1c4d9d8a6aea5d8b6601a7c1360494d
[ "MIT" ]
1
2019-10-23T01:00:08.000Z
2019-10-23T01:00:08.000Z
tests/integration/conftest.py
usmannasir/hcloud-python
2a90551fb1c4d9d8a6aea5d8b6601a7c1360494d
[ "MIT" ]
null
null
null
tests/integration/conftest.py
usmannasir/hcloud-python
2a90551fb1c4d9d8a6aea5d8b6601a7c1360494d
[ "MIT" ]
1
2019-06-19T17:53:10.000Z
2019-06-19T17:53:10.000Z
import os import pytest from hcloud import Client @pytest.fixture(autouse=True, scope='function') def hetzner_client(): hetzner_client = Client(token="test-token", api_endpoint=os.getenv("FAKE_API_ENDPOINT", default="http://localhost:4000")) return hetzner_client
25
125
0.767273
7957015c2e4d9c377f921c599efeccf8b3a943ab
5,744
py
Python
model.py
jrrr/emr-semantic-representations
361330f16ce4aaba47641216af49886cc1c45623
[ "MIT" ]
null
null
null
model.py
jrrr/emr-semantic-representations
361330f16ce4aaba47641216af49886cc1c45623
[ "MIT" ]
null
null
null
model.py
jrrr/emr-semantic-representations
361330f16ce4aaba47641216af49886cc1c45623
[ "MIT" ]
null
null
null
#!/usr/bin/env python import sys, os, pickle import pandas as pd import numpy as np from sklearn import linear_model, ensemble, metrics, impute, preprocessing def load_listfile(path): names = [] labels = [] with open(path, 'r') as f: f.readline() # first line is header for line in f: line = line.strip() parts = line.split(',') names.append('_'.join(parts[0].split('_')[0:2])) labels.append(int(parts[-1])) return pd.DataFrame(index=names, columns=['label'], data=labels, dtype=int) if len(sys.argv) < 3: print('usage: {} <listfile_dir> <feature_files...>'.format(sys.argv[0])) quit() listfile_dir = sys.argv[1] feature_files = sys.argv[2:] print('loading features...') features = [] for feature_file in feature_files: with open(feature_file, 'rb') as f: features.append(pickle.load(f)) print('processing listfiles...') df_train = load_listfile(os.path.join(listfile_dir, 'train_listfile.csv')) df_val = load_listfile(os.path.join(listfile_dir, 'val_listfile.csv')) df_test = load_listfile(os.path.join(listfile_dir, 'test_listfile.csv')) print(df_train.shape, df_val.shape, df_test.shape) for feature in features: feature['df_train'] = feature['df'].loc[ feature['df'].index.intersection(df_train.index)] feature['df_val'] = feature['df'].loc[ feature['df'].index.intersection(df_val.index)] feature['df_test'] = feature['df'].loc[ feature['df'].index.intersection(df_test.index)] del feature['df'] print(feature['df_train'].shape, feature['df_val'].shape, feature['df_test'].shape) print('imputing values...') for feature in features: if feature['should_impute']: imputer = impute.SimpleImputer() imputer.fit(feature['df_train']) feature['df_train'][feature['df_train'].columns] = \ imputer.transform(feature['df_train'][feature['df_train'].columns]) feature['df_val'][feature['df_val'].columns] = \ imputer.transform(feature['df_val'][feature['df_val'].columns]) feature['df_test'][feature['df_test'].columns] = \ imputer.transform(feature['df_test'][feature['df_test'].columns]) print('standardizing values...') for feature in features: if feature['should_standardize']: scaler = preprocessing.StandardScaler() scaler.fit(feature['df_train']) std = 0.316 #std = 0.1 #std = 1 feature['df_train'][feature['df_train'].columns] = \ scaler.transform(feature['df_train'][feature['df_train'].columns])*std feature['df_val'][feature['df_val'].columns] = \ scaler.transform(feature['df_val'][feature['df_val'].columns])*std feature['df_test'][feature['df_test'].columns] = \ scaler.transform(feature['df_test'][feature['df_test'].columns])*std print('concatenating features...') df_train = pd.concat([df_train] + [feature['df_train'] for feature in features], axis=1, join='inner') df_val = pd.concat([df_val] + [feature['df_val'] for feature in features], axis=1, join='inner') df_test = pd.concat([df_test] + [feature['df_test'] for feature in features], axis=1, join='inner') print(df_train.shape, df_val.shape, df_test.shape) # fix for a weird bug where all-0 columns in BoC becomes NaN after concat df_train.fillna(value=0, inplace=True) df_val.fillna(value=0, inplace=True) df_test.fillna(value=0, inplace=True) train_X = df_train.drop('label', axis=1).values train_y = df_train['label'].values val_X = df_val.drop('label', axis=1).values val_y = df_val['label'].values test_X = df_test.drop('label', axis=1).values test_y = df_test['label'].values # uncomment the model to use print('fitting model...') model = linear_model.LogisticRegression(solver='lbfgs', random_state=42, penalty='l2', C=0.001, max_iter=10000, class_weight='balanced') #model = ensemble.RandomForestClassifier(n_estimators=200, # class_weight='balanced', random_state=42, max_leaf_nodes=200) model.fit(train_X, train_y) train_pred = model.predict(train_X) print('\n\n\ntrain:') print(metrics.confusion_matrix(train_y, train_pred)) print(metrics.classification_report(train_y, train_pred)) val_pred = model.predict(val_X) print('\n\n\nvalidation:') print(metrics.confusion_matrix(val_y, val_pred)) print(metrics.classification_report(val_y, val_pred)) val_prob = model.predict_proba(val_X)[:, 1] fpr, tpr, _ = metrics.roc_curve(val_y, val_prob) roc_auc = metrics.auc(fpr, tpr) print('ROC AUC:', roc_auc) quit() test_pred = model.predict(test_X) test_prob = model.predict_proba(test_X)[:, 1] fpr, tpr, _ = metrics.roc_curve(test_y, test_prob) test_roc_auc = metrics.auc(fpr, tpr) print('\\begin{tabular}{@{}c@{}} %.3f \\\\ \\textbf{%.3f} \end{tabular} &' % (metrics.accuracy_score(val_y, val_pred), metrics.accuracy_score(test_y, test_pred))) print('\\begin{tabular}{@{}c@{}} %.3f \\\\ \\textbf{%.3f} \end{tabular} &' % (metrics.precision_score(val_y, val_pred), metrics.precision_score(test_y, test_pred))) print('\\begin{tabular}{@{}c@{}} %.3f \\\\ \\textbf{%.3f} \end{tabular} &' % (metrics.recall_score(val_y, val_pred), metrics.recall_score(test_y, test_pred))) print('\\begin{tabular}{@{}c@{}} %.3f \\\\ \\textbf{%.3f} \end{tabular} &' % (metrics.f1_score(val_y, val_pred), metrics.f1_score(test_y, test_pred))) print('\\begin{tabular}{@{}c@{}} %.3f \\\\ \\textbf{%.3f} \end{tabular} \\\\ \\hline' % (roc_auc, test_roc_auc)) #variables = df_train.drop('label', axis=1).columns #coefs = model.coef_ #significance = [(v, c) for (v, c) in zip(variables, coefs[0,:])] #significance.sort(key=lambda x: x[1]) #print(significance[0:10]) #print(significance[-1:-11:-1])
39.613793
87
0.674443
79570248fa2894799cb4053f28eefdfff863d9c7
2,073
py
Python
lib/restapi/maclookapi.py
svalqui/NR
5b6e665fb1166e010ae64b15dde7eb039ca1af64
[ "MIT" ]
null
null
null
lib/restapi/maclookapi.py
svalqui/NR
5b6e665fb1166e010ae64b15dde7eb039ca1af64
[ "MIT" ]
null
null
null
lib/restapi/maclookapi.py
svalqui/NR
5b6e665fb1166e010ae64b15dde7eb039ca1af64
[ "MIT" ]
null
null
null
# # http://www.macvendorlookup.com/api/v2/{MAC_Address} # note 2017 # copied to sysad as is of more general use, should be removed from here later when sysad matures import requests import lib.restapimaster import time class QueryMac(lib.restapimaster.RestApi): def __init__(self): super(QueryMac, self).__init__() self.urlbase = "http://api.macvendors.com/" # self.urlbase = "http://www.macvendorlookup.com/api/v2/" self.url_queried = "" self.list_content = [] self.page = "" self.page_text = "" self.current_page = "" self.mac_manufacturer = "" def read_page(self, mac="", debug=False): self.url_queried = self.urlbase + mac if debug: print("reading ...", self.url_queried) self.page = requests.get(self.url_queried) time.sleep(0.1) if debug: print("Querying : ", self.url_queried) print(self.page.status_code) if len(self.page.headers) > 0: for key in self.page.headers.keys(): print(key, " -value: ", self.page.headers[key]) if self.page.status_code == 200: self.page_text = self.page.text return self.page_text def mac_company(self, mac="", debug=False): self.mac_manufacturer = "" self.mac_manufacturer = self.read_page(mac) return self.mac_manufacturer # self.urlbase = "http://www.macvendorlookup.com/api/v2/" # - L-Content : list here # - L-Content : dict found on list resending # country - D_Content : str Value : UNITED STATES # company - D_Content : str Value : Dell Inc # endDec - D_Content : str Value : 26403110125567 # endHex - D_Content : str Value : 180373FFFFFF # addressL3 - D_Content : str Value : Round Rock Texas 78682 # startDec - D_Content : str Value : 26403093348352 # addressL2 - D_Content : str Value : # addressL1 - D_Content : str Value : One Dell Way, MS:RR5-45 # startHex - D_Content : str Value : 180373000000 # type - D_Content : str Value : MA-L
25.9125
97
0.630005
795703967d789ee6321754e4ccaff2246198c72e
22,303
py
Python
tests/crypto/test_keyring.py
whitemike889/synapse
97bf3077550915161765fdd1cf9290d8039a55f9
[ "Apache-2.0" ]
null
null
null
tests/crypto/test_keyring.py
whitemike889/synapse
97bf3077550915161765fdd1cf9290d8039a55f9
[ "Apache-2.0" ]
null
null
null
tests/crypto/test_keyring.py
whitemike889/synapse
97bf3077550915161765fdd1cf9290d8039a55f9
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2017 New Vector Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from mock import Mock import canonicaljson import signedjson.key import signedjson.sign from signedjson.key import encode_verify_key_base64, get_verify_key from twisted.internet import defer from synapse.api.errors import SynapseError from synapse.crypto import keyring from synapse.crypto.keyring import ( PerspectivesKeyFetcher, ServerKeyFetcher, StoreKeyFetcher, ) from synapse.logging.context import ( LoggingContext, PreserveLoggingContext, make_deferred_yieldable, ) from synapse.storage.keys import FetchKeyResult from tests import unittest class MockPerspectiveServer(object): def __init__(self): self.server_name = "mock_server" self.key = signedjson.key.generate_signing_key(0) def get_verify_keys(self): vk = signedjson.key.get_verify_key(self.key) return {"%s:%s" % (vk.alg, vk.version): encode_verify_key_base64(vk)} def get_signed_key(self, server_name, verify_key): key_id = "%s:%s" % (verify_key.alg, verify_key.version) res = { "server_name": server_name, "old_verify_keys": {}, "valid_until_ts": time.time() * 1000 + 3600, "verify_keys": {key_id: {"key": encode_verify_key_base64(verify_key)}}, } self.sign_response(res) return res def sign_response(self, res): signedjson.sign.sign_json(res, self.server_name, self.key) class KeyringTestCase(unittest.HomeserverTestCase): def make_homeserver(self, reactor, clock): self.mock_perspective_server = MockPerspectiveServer() self.http_client = Mock() config = self.default_config() config["trusted_key_servers"] = [ { "server_name": self.mock_perspective_server.server_name, "verify_keys": self.mock_perspective_server.get_verify_keys(), } ] return self.setup_test_homeserver( handlers=None, http_client=self.http_client, config=config ) def check_context(self, _, expected): self.assertEquals( getattr(LoggingContext.current_context(), "request", None), expected ) def test_wait_for_previous_lookups(self): kr = keyring.Keyring(self.hs) lookup_1_deferred = defer.Deferred() lookup_2_deferred = defer.Deferred() # we run the lookup in a logcontext so that the patched inlineCallbacks can check # it is doing the right thing with logcontexts. wait_1_deferred = run_in_context( kr.wait_for_previous_lookups, {"server1": lookup_1_deferred} ) # there were no previous lookups, so the deferred should be ready self.successResultOf(wait_1_deferred) # set off another wait. It should block because the first lookup # hasn't yet completed. wait_2_deferred = run_in_context( kr.wait_for_previous_lookups, {"server1": lookup_2_deferred} ) self.assertFalse(wait_2_deferred.called) # let the first lookup complete (in the sentinel context) lookup_1_deferred.callback(None) # now the second wait should complete. self.successResultOf(wait_2_deferred) def test_verify_json_objects_for_server_awaits_previous_requests(self): key1 = signedjson.key.generate_signing_key(1) kr = keyring.Keyring(self.hs) json1 = {} signedjson.sign.sign_json(json1, "server10", key1) persp_resp = { "server_keys": [ self.mock_perspective_server.get_signed_key( "server10", signedjson.key.get_verify_key(key1) ) ] } persp_deferred = defer.Deferred() @defer.inlineCallbacks def get_perspectives(**kwargs): self.assertEquals(LoggingContext.current_context().request, "11") with PreserveLoggingContext(): yield persp_deferred defer.returnValue(persp_resp) self.http_client.post_json.side_effect = get_perspectives # start off a first set of lookups @defer.inlineCallbacks def first_lookup(): with LoggingContext("11") as context_11: context_11.request = "11" res_deferreds = kr.verify_json_objects_for_server( [("server10", json1, 0, "test10"), ("server11", {}, 0, "test11")] ) # the unsigned json should be rejected pretty quickly self.assertTrue(res_deferreds[1].called) try: yield res_deferreds[1] self.assertFalse("unsigned json didn't cause a failure") except SynapseError: pass self.assertFalse(res_deferreds[0].called) res_deferreds[0].addBoth(self.check_context, None) yield make_deferred_yieldable(res_deferreds[0]) # let verify_json_objects_for_server finish its work before we kill the # logcontext yield self.clock.sleep(0) d0 = first_lookup() # wait a tick for it to send the request to the perspectives server # (it first tries the datastore) self.pump() self.http_client.post_json.assert_called_once() # a second request for a server with outstanding requests # should block rather than start a second call @defer.inlineCallbacks def second_lookup(): with LoggingContext("12") as context_12: context_12.request = "12" self.http_client.post_json.reset_mock() self.http_client.post_json.return_value = defer.Deferred() res_deferreds_2 = kr.verify_json_objects_for_server( [("server10", json1, 0, "test")] ) res_deferreds_2[0].addBoth(self.check_context, None) yield make_deferred_yieldable(res_deferreds_2[0]) # let verify_json_objects_for_server finish its work before we kill the # logcontext yield self.clock.sleep(0) d2 = second_lookup() self.pump() self.http_client.post_json.assert_not_called() # complete the first request persp_deferred.callback(persp_resp) self.get_success(d0) self.get_success(d2) def test_verify_json_for_server(self): kr = keyring.Keyring(self.hs) key1 = signedjson.key.generate_signing_key(1) r = self.hs.datastore.store_server_verify_keys( "server9", time.time() * 1000, [("server9", get_key_id(key1), FetchKeyResult(get_verify_key(key1), 1000))], ) self.get_success(r) json1 = {} signedjson.sign.sign_json(json1, "server9", key1) # should fail immediately on an unsigned object d = _verify_json_for_server(kr, "server9", {}, 0, "test unsigned") self.failureResultOf(d, SynapseError) # should suceed on a signed object d = _verify_json_for_server(kr, "server9", json1, 500, "test signed") # self.assertFalse(d.called) self.get_success(d) def test_verify_json_for_server_with_null_valid_until_ms(self): """Tests that we correctly handle key requests for keys we've stored with a null `ts_valid_until_ms` """ mock_fetcher = keyring.KeyFetcher() mock_fetcher.get_keys = Mock(return_value=defer.succeed({})) kr = keyring.Keyring( self.hs, key_fetchers=(StoreKeyFetcher(self.hs), mock_fetcher) ) key1 = signedjson.key.generate_signing_key(1) r = self.hs.datastore.store_server_verify_keys( "server9", time.time() * 1000, [("server9", get_key_id(key1), FetchKeyResult(get_verify_key(key1), None))], ) self.get_success(r) json1 = {} signedjson.sign.sign_json(json1, "server9", key1) # should fail immediately on an unsigned object d = _verify_json_for_server(kr, "server9", {}, 0, "test unsigned") self.failureResultOf(d, SynapseError) # should fail on a signed object with a non-zero minimum_valid_until_ms, # as it tries to refetch the keys and fails. d = _verify_json_for_server( kr, "server9", json1, 500, "test signed non-zero min" ) self.get_failure(d, SynapseError) # We expect the keyring tried to refetch the key once. mock_fetcher.get_keys.assert_called_once_with( {"server9": {get_key_id(key1): 500}} ) # should succeed on a signed object with a 0 minimum_valid_until_ms d = _verify_json_for_server( kr, "server9", json1, 0, "test signed with zero min" ) self.get_success(d) def test_verify_json_dedupes_key_requests(self): """Two requests for the same key should be deduped.""" key1 = signedjson.key.generate_signing_key(1) def get_keys(keys_to_fetch): # there should only be one request object (with the max validity) self.assertEqual(keys_to_fetch, {"server1": {get_key_id(key1): 1500}}) return defer.succeed( { "server1": { get_key_id(key1): FetchKeyResult(get_verify_key(key1), 1200) } } ) mock_fetcher = keyring.KeyFetcher() mock_fetcher.get_keys = Mock(side_effect=get_keys) kr = keyring.Keyring(self.hs, key_fetchers=(mock_fetcher,)) json1 = {} signedjson.sign.sign_json(json1, "server1", key1) # the first request should succeed; the second should fail because the key # has expired results = kr.verify_json_objects_for_server( [("server1", json1, 500, "test1"), ("server1", json1, 1500, "test2")] ) self.assertEqual(len(results), 2) self.get_success(results[0]) e = self.get_failure(results[1], SynapseError).value self.assertEqual(e.errcode, "M_UNAUTHORIZED") self.assertEqual(e.code, 401) # there should have been a single call to the fetcher mock_fetcher.get_keys.assert_called_once() def test_verify_json_falls_back_to_other_fetchers(self): """If the first fetcher cannot provide a recent enough key, we fall back""" key1 = signedjson.key.generate_signing_key(1) def get_keys1(keys_to_fetch): self.assertEqual(keys_to_fetch, {"server1": {get_key_id(key1): 1500}}) return defer.succeed( { "server1": { get_key_id(key1): FetchKeyResult(get_verify_key(key1), 800) } } ) def get_keys2(keys_to_fetch): self.assertEqual(keys_to_fetch, {"server1": {get_key_id(key1): 1500}}) return defer.succeed( { "server1": { get_key_id(key1): FetchKeyResult(get_verify_key(key1), 1200) } } ) mock_fetcher1 = keyring.KeyFetcher() mock_fetcher1.get_keys = Mock(side_effect=get_keys1) mock_fetcher2 = keyring.KeyFetcher() mock_fetcher2.get_keys = Mock(side_effect=get_keys2) kr = keyring.Keyring(self.hs, key_fetchers=(mock_fetcher1, mock_fetcher2)) json1 = {} signedjson.sign.sign_json(json1, "server1", key1) results = kr.verify_json_objects_for_server( [("server1", json1, 1200, "test1"), ("server1", json1, 1500, "test2")] ) self.assertEqual(len(results), 2) self.get_success(results[0]) e = self.get_failure(results[1], SynapseError).value self.assertEqual(e.errcode, "M_UNAUTHORIZED") self.assertEqual(e.code, 401) # there should have been a single call to each fetcher mock_fetcher1.get_keys.assert_called_once() mock_fetcher2.get_keys.assert_called_once() class ServerKeyFetcherTestCase(unittest.HomeserverTestCase): def make_homeserver(self, reactor, clock): self.http_client = Mock() hs = self.setup_test_homeserver(handlers=None, http_client=self.http_client) return hs def test_get_keys_from_server(self): # arbitrarily advance the clock a bit self.reactor.advance(100) SERVER_NAME = "server2" fetcher = ServerKeyFetcher(self.hs) testkey = signedjson.key.generate_signing_key("ver1") testverifykey = signedjson.key.get_verify_key(testkey) testverifykey_id = "ed25519:ver1" VALID_UNTIL_TS = 200 * 1000 # valid response response = { "server_name": SERVER_NAME, "old_verify_keys": {}, "valid_until_ts": VALID_UNTIL_TS, "verify_keys": { testverifykey_id: { "key": signedjson.key.encode_verify_key_base64(testverifykey) } }, } signedjson.sign.sign_json(response, SERVER_NAME, testkey) def get_json(destination, path, **kwargs): self.assertEqual(destination, SERVER_NAME) self.assertEqual(path, "/_matrix/key/v2/server/key1") return response self.http_client.get_json.side_effect = get_json keys_to_fetch = {SERVER_NAME: {"key1": 0}} keys = self.get_success(fetcher.get_keys(keys_to_fetch)) k = keys[SERVER_NAME][testverifykey_id] self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS) self.assertEqual(k.verify_key, testverifykey) self.assertEqual(k.verify_key.alg, "ed25519") self.assertEqual(k.verify_key.version, "ver1") # check that the perspectives store is correctly updated lookup_triplet = (SERVER_NAME, testverifykey_id, None) key_json = self.get_success( self.hs.get_datastore().get_server_keys_json([lookup_triplet]) ) res = key_json[lookup_triplet] self.assertEqual(len(res), 1) res = res[0] self.assertEqual(res["key_id"], testverifykey_id) self.assertEqual(res["from_server"], SERVER_NAME) self.assertEqual(res["ts_added_ms"], self.reactor.seconds() * 1000) self.assertEqual(res["ts_valid_until_ms"], VALID_UNTIL_TS) # we expect it to be encoded as canonical json *before* it hits the db self.assertEqual( bytes(res["key_json"]), canonicaljson.encode_canonical_json(response) ) # change the server name: the result should be ignored response["server_name"] = "OTHER_SERVER" keys = self.get_success(fetcher.get_keys(keys_to_fetch)) self.assertEqual(keys, {}) class PerspectivesKeyFetcherTestCase(unittest.HomeserverTestCase): def make_homeserver(self, reactor, clock): self.mock_perspective_server = MockPerspectiveServer() self.http_client = Mock() config = self.default_config() config["trusted_key_servers"] = [ { "server_name": self.mock_perspective_server.server_name, "verify_keys": self.mock_perspective_server.get_verify_keys(), } ] return self.setup_test_homeserver( handlers=None, http_client=self.http_client, config=config ) def test_get_keys_from_perspectives(self): # arbitrarily advance the clock a bit self.reactor.advance(100) fetcher = PerspectivesKeyFetcher(self.hs) SERVER_NAME = "server2" testkey = signedjson.key.generate_signing_key("ver1") testverifykey = signedjson.key.get_verify_key(testkey) testverifykey_id = "ed25519:ver1" VALID_UNTIL_TS = 200 * 1000 # valid response response = { "server_name": SERVER_NAME, "old_verify_keys": {}, "valid_until_ts": VALID_UNTIL_TS, "verify_keys": { testverifykey_id: { "key": signedjson.key.encode_verify_key_base64(testverifykey) } }, } # the response must be signed by both the origin server and the perspectives # server. signedjson.sign.sign_json(response, SERVER_NAME, testkey) self.mock_perspective_server.sign_response(response) def post_json(destination, path, data, **kwargs): self.assertEqual(destination, self.mock_perspective_server.server_name) self.assertEqual(path, "/_matrix/key/v2/query") # check that the request is for the expected key q = data["server_keys"] self.assertEqual(list(q[SERVER_NAME].keys()), ["key1"]) return {"server_keys": [response]} self.http_client.post_json.side_effect = post_json keys_to_fetch = {SERVER_NAME: {"key1": 0}} keys = self.get_success(fetcher.get_keys(keys_to_fetch)) self.assertIn(SERVER_NAME, keys) k = keys[SERVER_NAME][testverifykey_id] self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS) self.assertEqual(k.verify_key, testverifykey) self.assertEqual(k.verify_key.alg, "ed25519") self.assertEqual(k.verify_key.version, "ver1") # check that the perspectives store is correctly updated lookup_triplet = (SERVER_NAME, testverifykey_id, None) key_json = self.get_success( self.hs.get_datastore().get_server_keys_json([lookup_triplet]) ) res = key_json[lookup_triplet] self.assertEqual(len(res), 1) res = res[0] self.assertEqual(res["key_id"], testverifykey_id) self.assertEqual(res["from_server"], self.mock_perspective_server.server_name) self.assertEqual(res["ts_added_ms"], self.reactor.seconds() * 1000) self.assertEqual(res["ts_valid_until_ms"], VALID_UNTIL_TS) self.assertEqual( bytes(res["key_json"]), canonicaljson.encode_canonical_json(response) ) def test_invalid_perspectives_responses(self): """Check that invalid responses from the perspectives server are rejected""" # arbitrarily advance the clock a bit self.reactor.advance(100) SERVER_NAME = "server2" testkey = signedjson.key.generate_signing_key("ver1") testverifykey = signedjson.key.get_verify_key(testkey) testverifykey_id = "ed25519:ver1" VALID_UNTIL_TS = 200 * 1000 def build_response(): # valid response response = { "server_name": SERVER_NAME, "old_verify_keys": {}, "valid_until_ts": VALID_UNTIL_TS, "verify_keys": { testverifykey_id: { "key": signedjson.key.encode_verify_key_base64(testverifykey) } }, } # the response must be signed by both the origin server and the perspectives # server. signedjson.sign.sign_json(response, SERVER_NAME, testkey) self.mock_perspective_server.sign_response(response) return response def get_key_from_perspectives(response): fetcher = PerspectivesKeyFetcher(self.hs) keys_to_fetch = {SERVER_NAME: {"key1": 0}} def post_json(destination, path, data, **kwargs): self.assertEqual(destination, self.mock_perspective_server.server_name) self.assertEqual(path, "/_matrix/key/v2/query") return {"server_keys": [response]} self.http_client.post_json.side_effect = post_json return self.get_success(fetcher.get_keys(keys_to_fetch)) # start with a valid response so we can check we are testing the right thing response = build_response() keys = get_key_from_perspectives(response) k = keys[SERVER_NAME][testverifykey_id] self.assertEqual(k.verify_key, testverifykey) # remove the perspectives server's signature response = build_response() del response["signatures"][self.mock_perspective_server.server_name] self.http_client.post_json.return_value = {"server_keys": [response]} keys = get_key_from_perspectives(response) self.assertEqual(keys, {}, "Expected empty dict with missing persp server sig") # remove the origin server's signature response = build_response() del response["signatures"][SERVER_NAME] self.http_client.post_json.return_value = {"server_keys": [response]} keys = get_key_from_perspectives(response) self.assertEqual(keys, {}, "Expected empty dict with missing origin server sig") def get_key_id(key): """Get the matrix ID tag for a given SigningKey or VerifyKey""" return "%s:%s" % (key.alg, key.version) @defer.inlineCallbacks def run_in_context(f, *args, **kwargs): with LoggingContext("testctx") as ctx: # we set the "request" prop to make it easier to follow what's going on in the # logs. ctx.request = "testctx" rv = yield f(*args, **kwargs) defer.returnValue(rv) def _verify_json_for_server(kr, *args): """thin wrapper around verify_json_for_server which makes sure it is wrapped with the patched defer.inlineCallbacks. """ @defer.inlineCallbacks def v(): rv1 = yield kr.verify_json_for_server(*args) defer.returnValue(rv1) return run_in_context(v)
37.171667
89
0.631754
795703b4edfffad4922e9d63810618e0d66bcefd
4,494
py
Python
.history/my_classes/ScopesClosuresAndDecorators/decorators_1_20210714130158.py
minefarmer/deep-Dive-1
b0675b853180c5b5781888266ea63a3793b8d855
[ "Unlicense" ]
null
null
null
.history/my_classes/ScopesClosuresAndDecorators/decorators_1_20210714130158.py
minefarmer/deep-Dive-1
b0675b853180c5b5781888266ea63a3793b8d855
[ "Unlicense" ]
null
null
null
.history/my_classes/ScopesClosuresAndDecorators/decorators_1_20210714130158.py
minefarmer/deep-Dive-1
b0675b853180c5b5781888266ea63a3793b8d855
[ "Unlicense" ]
null
null
null
"""Decorators Recall the simple closure example we did which allowed us to maintain a count of ho9w many times a function was called: def counter(fn): count = 0 def inner(*args, **kwargs): # using *args. **kwargs means we can call any function fn with any combination of positional and keyword arguments nonlocal count count += 1 print('Function {0} was called {1} times'.format(fn.__name__, count)) return fn(*args, **kwargs) return inner def add(a, b=0): return a + b add = counter(add) result = add(1, 2) # Function add was called 1 times # result = 3 print(result) I essentially modified our add function by wrapping it inside another function that added some functionally to it I can also say that we decorated ourfunction add with the function counter And I call counter a decorator function In general a decorator function: takes a function as an argument returns a closure the closure usually accepts any combination of parameters runs some code in the inner function(closure) the closure function calls the original function using the arguments passed to the closure returns whatever is returned by that function call Decorators and the @ symbool In our previous example, we saw that the counter was a decorator and we could decorate our add function using: add = counter(add) In general, if func is a decorator function, we decorate another function my_func using: my_func = func(my_func) This is so common that Python provides a convenient way of writing that: @counter (is the sameas writing) @func def add(a, b): def my_func(...): return a + b ... is the same as writing is the same as writing def add(a, b): def my_func(...): return a + b ... add = counter(add) my_func = func(my_func) Introspecting Decorated Functions Let's use the same count decorator def counter(fn): count = 0 def inner(*args, **kwargs): # using *args. **kwargs means we can call any function fn with any combination of positional and keyword arguments nonlocal count count += 1 print('Function {0} was called {1} times'.format(fn.__name__, count)) return fn(*args, **kwargs) return inner """ # @counter # if not commented out, python shows it is not defined from itertools import count def mult(a, b, c=1): # returns the product of three values I could have written: return a * b* c # mult = counter (the same thing as @counter) mult.__name__ # mult is now inner # The dunder 'name' property help(mult) # Help on function inner in module __main__: # inner(*args, kwargs) # we have lost our docstring, and even the original function signature # even using the inspect module's signature does not yield better results """ One approach to fixing this We can try to fix this problem, at least for the docstring and function name as follows: def counter(fn): count = 0 def inner(*args, **kwargs): nonlocal count count += 1 print*'unction {0} was called {1} times'.format(fn.__name__, count) return fn(*args, **kwargs) inner.__name__ = fn.__name__ # these two have been added in to change the function inner.doc__ = fn.__doc__ # these two have been added in to change the function return inner But this doesn't fix losing the function signature - doing so would be quite complicated The functools.wraps function The functools module has a wraps function that we can use to fix the metadata of our inner function in our decorator from functools import wraps in fact, the wraps function is itself a decorator """
37.764706
205
0.576547
795703c081a6af2c870a60e1b76c2cdf5832f961
869
py
Python
migrations/versions/88ebd18ef240_.py
Anioko/market-research
cdd5c1a2fafd206443ba3ebc112d68d101d8c2b5
[ "MIT" ]
null
null
null
migrations/versions/88ebd18ef240_.py
Anioko/market-research
cdd5c1a2fafd206443ba3ebc112d68d101d8c2b5
[ "MIT" ]
null
null
null
migrations/versions/88ebd18ef240_.py
Anioko/market-research
cdd5c1a2fafd206443ba3ebc112d68d101d8c2b5
[ "MIT" ]
1
2021-03-15T19:24:38.000Z
2021-03-15T19:24:38.000Z
"""empty message Revision ID: 88ebd18ef240 Revises: 51f8f2ef9d06 Create Date: 2021-03-11 11:20:35.999599 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '88ebd18ef240' down_revision = '51f8f2ef9d06' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('screener_questions', sa.Column('question_id', sa.Integer(), nullable=True)) op.create_foreign_key(None, 'screener_questions', 'questions', ['question_id'], ['id'], ondelete='CASCADE') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'screener_questions', type_='foreignkey') op.drop_column('screener_questions', 'question_id') # ### end Alembic commands ###
28.032258
111
0.710012
7957049cde542f3678a7d35c49e8554aff61e11c
8,713
py
Python
main.py
matanki-saito/VIC2JPModCore
03cf60db1188ea485cfe63238ad257ee73878768
[ "MIT" ]
null
null
null
main.py
matanki-saito/VIC2JPModCore
03cf60db1188ea485cfe63238ad257ee73878768
[ "MIT" ]
null
null
null
main.py
matanki-saito/VIC2JPModCore
03cf60db1188ea485cfe63238ad257ee73878768
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding:utf-8 -*- import hashlib import json import os import shutil import tempfile import urllib.request import zipfile from os.path import join from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive _ = join def upload_mod_to_google_drive(upload_file_path, name, folder_id): """ GoogleDriveにファイルをアップロードする :param upload_file_path: :param name: :param folder_id: :return: CDNのURL """ gauth = GoogleAuth() gauth.LocalWebserverAuth() # Create GoogleDrive instance with authenticated GoogleAuth instance. drive = GoogleDrive(gauth) file1 = drive.CreateFile({ 'title': name, 'parents': [ { "kind": "drive#fileLink", "id": folder_id } ] }) file1.SetContentFile(upload_file_path) file1.Upload() file1.InsertPermission({ 'type': 'anyone', 'value': 'anyone', 'role': 'reader'}) file1.FetchMetadata() return "{}/{}?key={}&alt=media".format("https://www.googleapis.com/drive/v3/files", file1['id'], "AIzaSyAAt1kNBcu9uiPWPIxAcR0gZefmWHcjjpM") def download_asset_from_github(repository_author, repository_name, out_file_path, release_tag=None, file_name=None): """ githubからアセットをダウンロード。未指定の場合は最新を取得 :param repository_author: :param repository_name: :param release_tag: :param file_name: :param out_file_path: :return: """ api_base_url = "https://api.github.com/repos/{}/{}".format(repository_author, repository_name) if release_tag is None: response = urllib.request.urlopen("{}/releases/latest".format(api_base_url)) content = json.loads(response.read().decode('utf8')) release_tag = content["tag_name"] if file_name is None: response = urllib.request.urlopen("{}/releases/tags/{}".format(api_base_url, release_tag)) content = json.loads(response.read().decode('utf8')) file_name = content["assets"][0]["name"] request_url = "{}/{}/{}/releases/download/{}/{}".format("https://github.com", repository_author, repository_name, release_tag, file_name ) req = urllib.request.Request(request_url) with open(out_file_path, "wb") as my_file: my_file.write(urllib.request.urlopen(req).read()) return out_file_path def assembly_core_mod_zip_file(resource_font_asset_zip_file_path, resource_image_file_path, resource_interface_dir_path, out_file_path): """ コアモッドを作成 :param resource_font_asset_zip_file_path: githubにあるフォントアセットのzipファイルのパス :param resource_image_file_path: 画像ファイルパス :param resource_interface_dir_path: インターフェースディレクトリパス :param out_file_path: 出力ファイルパス :return: """ with tempfile.TemporaryDirectory() as temp_dir_path: # interface shutil.copytree(resource_interface_dir_path, _(temp_dir_path, "interface")) # gfx salvage_files_from_github_font_zip(out_dir_path=_(temp_dir_path, "gfx", "fonts"), filter_f_f=lambda x: True, resource_path=resource_font_asset_zip_file_path) # zip化する return shutil.make_archive(out_file_path, 'zip', root_dir=temp_dir_path) def salvage_files_from_github_font_zip(out_dir_path, filter_f_f, resource_path): with zipfile.ZipFile(resource_path) as font_zip: special_files = filter(filter_f_f, font_zip.namelist()) font_zip.extractall(path=out_dir_path, members=special_files) def generate_dot_mod_file(mod_title_name, mod_file_name, mod_tags, mod_image_file_path, mod_supported_version, out_dir_path): """ .modファイルを作る :param mod_title_name: :param mod_file_name: zipファイルの名前(.zipを含まない) :param mod_tags: Set<String>型 :param mod_image_file_path: :param mod_supported_version: :param out_dir_path: 出力ディレクトリのパス :return: 出力ファイルパス """ os.makedirs(out_dir_path, exist_ok=True) out_file_path = _(out_dir_path, "{}.mod".format(mod_file_name)) with open(out_file_path, "w", encoding="utf-8") as fw: lines = [ 'name="{}"'.format(mod_title_name), 'archive="mod/{}.zip"'.format(mod_file_name), 'tags={}'.format("{" + " ".join(map(lambda c: '"{}"'.format(c), mod_tags)) + "}"), 'picture="{}"'.format(mod_image_file_path), 'supported_version="{}"'.format(mod_supported_version) ] fw.write("\n".join(lines)) return out_file_path def generate_distribution_file(url, mod_file_path, out_file_path): """ trielaで使用する配布用設定ファイルを作成する。 :param url: :param mod_file_path: :param out_file_path: :return: """ with open(mod_file_path, 'rb') as fr: md5 = hashlib.md5(fr.read()).hexdigest() d_new = {'file_md5': md5, 'url': url, 'file_size': os.path.getsize(mod_file_path)} with open(out_file_path, "w", encoding="utf-8") as fw: json.dump(d_new, fw, indent=2, ensure_ascii=False) def pack_mod(out_file_path, mod_zip_path, mod_title_name, mod_file_name, mod_tags, mod_image_file_path, mod_supported_version): with tempfile.TemporaryDirectory() as temp_dir_path: # .modファイルを作成する generate_dot_mod_file( mod_title_name=mod_title_name, mod_file_name=mod_file_name, mod_tags=mod_tags, mod_image_file_path=mod_image_file_path, mod_supported_version=mod_supported_version, out_dir_path=temp_dir_path) # zipをコピー shutil.copy(mod_zip_path, _(temp_dir_path, "{}.zip".format(mod_file_name))) return shutil.make_archive(out_file_path, 'zip', root_dir=temp_dir_path) def main(): # 一時フォルダ用意 os.makedirs(_(".", "tmp"), exist_ok=True) os.makedirs(_(".", "out"), exist_ok=True) # フォントセットの最新版をダウンロードする font_file_path = download_asset_from_github(repository_author="matanki-saito", repository_name="VIC2fontcreate", out_file_path=_(".", "tmp", "font.zip")) print("font_file_path:{}".format(font_file_path)) # コアModを構築する core_mod_zip_file_path = assembly_core_mod_zip_file( resource_font_asset_zip_file_path=font_file_path, resource_image_file_path=_(".", "resource", "title.jpg"), resource_interface_dir_path=_(".", "resource", "interface"), out_file_path=_(".", "tmp", "mod")) print("core_mod_zip_file_path:{}".format(core_mod_zip_file_path)) # packする mod_pack_file_path = pack_mod( out_file_path=_(".", "out", "vic2_ap0_mod"), mod_file_name="jpmod_ap0_mod", mod_zip_path=core_mod_zip_file_path, mod_title_name="JPMOD Main 1: Fonts and UI", mod_tags={"Translation", "Localisation"}, mod_supported_version="3.0.*", mod_image_file_path="title.jpg") print("mod_pack_file_path:{}".format(mod_pack_file_path)) # GoogleDriveにアップロード from datetime import datetime as dt from datetime import datetime as dt cdn_url = upload_mod_to_google_drive( upload_file_path=mod_pack_file_path, name=dt.now().strftime('%Y-%m-%d_%H-%M-%S-{}.zip'.format("eu4-core")), folder_id='1MUdH6S6O-M_Y5jRUzNrzQ8tPZOhm_aES') print("cdn_url:{}".format(cdn_url)) print("::set-output name=download_url::{}".format(cdn_url)) # distributionファイルを生成する generate_distribution_file(url=cdn_url, out_file_path=_(".", "out", "dist.v2.json"), mod_file_path=mod_pack_file_path) if __name__ == "__main__": main()
32.755639
98
0.582693
7957050ff8f3c8358643747fc79af99a1b0fa90d
34,172
py
Python
src/analyse.py
htrenquier/ml-attribute-based-testing
838ac29829b5fdd23cdac6413843c764c5934dce
[ "MIT" ]
null
null
null
src/analyse.py
htrenquier/ml-attribute-based-testing
838ac29829b5fdd23cdac6413843c764c5934dce
[ "MIT" ]
null
null
null
src/analyse.py
htrenquier/ml-attribute-based-testing
838ac29829b5fdd23cdac6413843c764c5934dce
[ "MIT" ]
null
null
null
from __future__ import division import numpy as np from sklearn import metrics as sk_metrics import metrics import metrics_color import plotting import model_trainer as mt import data_tools as dt import tests_logging as t_log import initialise import bdd100k_utils as bu import cv2 import os.path import json from itertools import product # Paths csv_path = '../res/csv/' png_path = '../res/png/' h5_path = '../res/h5/' labels_path = '../../bdd100k/classification/labels/' bdd100k_labels_path = "../../bdd100k/labels/" box_tr_file = '../../bdd100k/classification/labels/train_ground_truth_attributes.csv' val_labels_csv = '../../bdd100k/classification/labels/val_ground_truth.csv' box_val_file = '../../bdd100k/classification/labels/val_ground_truth_attributes.csv' val_json = '../../bdd100k/labels/bdd100k_labels_images_val.json' attr_tr_file = bdd100k_labels_path + 'bdd100k_labels_images_train_attributes.csv' attr_val_file = bdd100k_labels_path + 'bdd100k_labels_images_val_attributes.csv' box_tr_json = labels_path + 'box_size_train_attribute.json' class_map_file = labels_path + 'class_mapping.csv' box_val_json = labels_path + 'box_size_val_attribute.json' labels_path = '../../bdd100k/classification/labels/' # models = ('densenet121', 'mobilenet', 'mobilenetv2', 'nasnet', 'resnet50') models = ['densenet121', 'resnet50'] class MultidimMetricStructure: def __init__(self, entries_lists): self.entries_lists = list(entries_lists) self.struct = {tuple(key): [] for key in product(*entries_lists)} self.dims = [len(el) for el in entries_lists] def flush(self): self.struct = {tuple(key): [] for key in product(*self.entries_lists)} def set_value(self, entries_ids, value): self.struct[tuple(entries_ids)].append(value) def get_value_list(self, entries_ids): return self.struct[tuple(entries_ids)] def get_value_mean(self, entries_ids): return np.mean(self.struct[tuple(entries_ids)]) def global_mean(self): global_arr = [] for key in self.struct.keys(): global_arr += self.struct[key] return np.mean(global_arr) def get_means(self): means = np.zeros(self.dims) for index in product(*[xrange(k) for k in self.dims]): key = [self.entries_lists[c][entry] for c, entry in enumerate(list(index))] means[index] = np.mean(self.struct[tuple(key)]) return means def get_table_rec(self, entries_lists, arr): if not entries_lists: return [] else: return [self.get_table_rec(entries_lists[:-1], arr[k]) for k in xrange(len(entries_lists))] def get_entries_lists(self): return self.entries_lists class MetricStructure: def __init__(self, entries): self.entries = list(entries) self.struct = {entry: [] for entry in self.entries} def flush(self): self.struct = {entry: [] for entry in self.entries} def add_value(self, entry, value): self.struct[entry].append(value) def get_value_list(self, entry): return self.struct[entry] def get_value_mean(self, entry): return np.mean(self.struct[entry]) def global_mean(self): global_arr = [] for key in self.struct.keys(): global_arr += self.struct[key] return np.mean(global_arr) def get_means(self): means = np.zeros(len(self.entries)) for i, entry in enumerate(self.entries): means[i] = np.mean(self.struct[entry]) return means class DiscreteAttribute: """ Stores data ID to attribute's labels dictionary and later stores values in MetricStructure for different metrics """ def __init__(self, key_to_label, metric_name='score'): self.metrics = dict() self.key_to_label = key_to_label self.uniques = np.asarray(np.unique(key_to_label.values(), return_counts=True)) self.metrics.update({metric_name: MetricStructure(self.uniques[0])}) self.indexof = {self.uniques[0][k]: k for k in xrange(len(self.uniques[0]))} def __getitem__(self, id): return self.uniques[0][id] def flush(self): for m in self.metrics.values(): m.flush() def get_labels(self): return [str(l) for l in self.uniques[0]] def labelof(self, key): return self.key_to_label[key] def index_of(self, label): return self.indexof[label] def get_distribution(self): return [str(c) for c in self.uniques[1]] def add_value(self, metric_name, value, data_key): self.metrics[metric_name].add_value(self.key_to_label[data_key], value) def add_metric(self, name): metric = MetricStructure(self.uniques[0]) self.metrics.update({name: metric}) def get_metric_value_list(self, metric_name, label): """ :param metric_name: :param label: Attribute's label :return: """ return self.metrics[metric_name].get_value_list(label) def get_metric_mean(self, metric_name, label): return self.metrics[metric_name].get_value_mean(label) def get_metric_means(self, metric_name): return [m for m in self.metrics[metric_name].get_means()] def log_headers(self, fd): fd.write(",".join(self.get_labels()) + '\n') fd.write(",".join(self.get_distribution()) + '\n') def log_metric_means(self, name, fd): fd.writelines(",".join([str(m) for m in self.get_metric_means(name)]) + '\n') def get_metric_global_mean(self, name): return self.metrics[name].global_mean() def bdd100k_discrete_attribute_analyse(model_file, attribute, data_ids, y_metrics): res_file = csv_path + model_file.split('_')[0] + '_' + attribute['name'] + '_res_metrics.csv' for metric in attribute['metrics']: for i in xrange(len(data_ids)): attribute['d_attribute'].add_value(metric, y_metrics[metric][i], attribute['dk2ak'](data_ids[i])) fd = open(res_file, 'w') for metric in attribute['metrics']: attribute['d_attribute'].log_headers(fd) attribute['d_attribute'].log_metric_means(metric, fd) fd.write(str(attribute['d_attribute'].get_metric_global_mean(metric))) fd.close() def bdd100k_model_analysis(model_file, attributes, val_labels): print("") print(" =#= Analysing " + model_file.split('_')[0] + " =#= ") print("") threshold = 0 pr_file = '.'.join(model_file.split('.')[:-1]) + '_predictions.csv' predictions, y_scores, img_ids = dt.get_scores_from_file(csv_path + pr_file, val_labels) y_acc = [int(np.argmax(predictions[i]) == val_labels[i]) for i in img_ids] print('Model Accuracy:', np.mean(y_acc)) y_metrics = {'score': y_scores, 'acc': y_acc} # top_n_args, bot_n_args = dt.get_topbot_n_args(n_data, y_scores) for attribute in attributes.values(): # Attribute init + analysis attribute['d_attribute'] = DiscreteAttribute(attribute['map']) for metric in attribute['metrics']: attribute['d_attribute'].add_metric(metric) bdd100k_discrete_attribute_analyse(model_file, attribute, img_ids, y_metrics) for mc, metric in enumerate(attribute['metrics']): for lc, label_mean in enumerate(attribute['d_attribute'].get_metric_means(metric)): # print(c, label_mean, attr_mean - threshold) metric_mean = attribute['d_attribute'].get_metric_global_mean(metric) if label_mean < metric_mean - threshold: attribute['weaks'][mc].append(attribute['d_attribute'].get_labels()[lc]) # print(attribute['weaks']) def select_ft_data(model_file, ft_partition, ft_attribute=None, ft_label=None, do_plot_boxes=False): assert (bool(ft_attribute) == bool(ft_label)) attributes = bdd100k_analysis(model_file, do_plot_boxes) attributes['weather']['map'], \ attributes['scene']['map'], \ attributes['timeofday']['map'], wst_dk2ak = bu.wst_attribute_mapping(attr_tr_file) attributes['box_size']['map'], box_size_dk2ak = bu.box_size_attribute_mapping(box_tr_file, box_tr_json) if ft_label and ft_attribute: print('Selecting data for ' + ft_attribute + ' / ' + ft_label) sel_partition = local_ft_selection(attributes[ft_attribute], ft_label, ft_partition) else: print('Selecting data for global fine-tuning.') sel_partition = global_ft_selection(attributes, ft_partition) return sel_partition def bdd100k_analysis(model_file, do_plot_boxes=False): class_map_file = bu.class_mapping(input_json=val_json, output_csv=labels_path + 'class_mapping.csv') # Dataset for analysis val_partition, val_labels = bu.get_ids_labels(val_labels_csv, class_map_file) # Attribute mapping and data_key to attr_key function (dk2ak) weather, scene, timeofday, wst_dk2ak = bu.wst_attribute_mapping(attr_val_file) box_size, box_size_dk2ak = bu.box_size_attribute_mapping(box_val_file, box_val_json) # show_worst(model_file, 10, 'daytime', timeofday, dk2ak=wst_dk2ak) # for attr in attributes.values(): # print(attr['d_attribute'].get_labels()) # print(attr['d_attribute'].get_distribution()) attributes = {'weather': {'name': 'weather', 'map': weather, 'dk2ak': wst_dk2ak, 'd_attribute': None, 'metrics': ['score', 'acc'], 'weaks': [[], []]}, 'scene': {'name': 'scene', 'map': scene, 'dk2ak': wst_dk2ak, 'd_attribute': None, 'metrics': ['score', 'acc'], 'weaks': [[], []]}, 'timeofday': {'name': 'timeofday', 'map': timeofday, 'dk2ak': wst_dk2ak, 'd_attribute': None, 'metrics': ['score', 'acc'], 'weaks': [[], []]}, 'box_size': {'name': 'box_size', 'map': box_size, 'dk2ak': box_size_dk2ak, 'd_attribute': None, 'metrics': ['score', 'acc'], 'weaks': [[], []]}, } bdd100k_model_analysis(model_file, attributes, val_labels) if do_plot_boxes: plotting.plot_discrete_attribute_scores(attributes, 'score', model_file) # plotting.plot_discrete_attribute_scores(attributes, 'acc', model_file) return attributes def bdd100k_compare(model_file, ref_file, attribute, metric): class_map_file = bu.class_mapping(input_json=val_json, output_csv=labels_path + 'class_mapping.csv') # Dataset for analysis val_partition, val_labels = bu.get_ids_labels(val_labels_csv, class_map_file) # Attribute mapping and data_key to attr_key function (dk2ak) weather, scene, timeofday, wst_dk2ak = bu.wst_attribute_mapping(attr_val_file) box_size, box_size_dk2ak = bu.box_size_attribute_mapping(box_val_file, box_val_json) attributes = {'weather': {'name': 'weather', 'map': weather, 'dk2ak': wst_dk2ak, 'd_attribute': None, 'metrics': ['score', 'acc'], 'weaks': [[], []]}, 'scene': {'name': 'scene', 'map': scene, 'dk2ak': wst_dk2ak, 'd_attribute': None, 'metrics': ['score', 'acc'], 'weaks': [[], []]}, 'timeofday': {'name': 'timeofday', 'map': timeofday, 'dk2ak': wst_dk2ak, 'd_attribute': None, 'metrics': ['score', 'acc'], 'weaks': [[], []]}, 'box_size': {'name': 'box_size', 'map': box_size, 'dk2ak': box_size_dk2ak, 'd_attribute': None, 'metrics': ['score', 'acc'], 'weaks': [[], []]}, } bdd100k_model_analysis(model_file, attributes, val_labels) labels = attributes[attribute]['d_attribute'].get_labels() distrib = [int(v) for v in attributes[attribute]['d_attribute'].get_distribution()] series = [attributes[attribute]['d_attribute'].get_metric_value_list(metric, label) for label in labels] series_names = ["%s (%1.2f)" % (labels[k], distrib[k] / sum(distrib)) for k in xrange(len(labels))] attributes[attribute]['d_attribute'].flush() bdd100k_model_analysis(ref_file, attributes, val_labels) series_ref = [attributes[attribute]['d_attribute'].get_metric_value_list(metric, label) for label in labels] plotting.n_box_plot_compare(series, series_ref, series_names, metric) def local_ft_selection(attribute, label, ft_partition): sel_partition = [] count = 0 for data_key in ft_partition: if attribute['map'][attribute['dk2ak'](data_key)] == label: count += 1 sel_partition.append(data_key) print(str(count) + " data selected.") return sel_partition def global_ft_selection(attributes, ft_partition, n_sel_data): sel_partition_occurences = [[] for _ in xrange(len(attributes) + 1)] for data_key in ft_partition: count = 0 for attribute in attributes.values(): if attribute['map'][attribute['dk2ak'](data_key)] in attribute['weaks'][0]: count += 1 sel_partition_occurences[count].append(data_key) for k in xrange(len(sel_partition_occurences)): print(k, len(sel_partition_occurences[k])) sel_partition = [] k = len(sel_partition_occurences) - 1 while len(sel_partition) < n_sel_data and k > -1: sel_partition = sel_partition + sel_partition_occurences[k] print(len(sel_partition)) k -= 1 return sel_partition[:n_sel_data] def bdd100k_cc_analysis(): model_files = ['densenet121_bdd100k_cl0-500k_20ep_woda_ep20_vl0.22.hdf5', ] # 'resnet50_bdd100k_cl0-500k_20ep_woda_ep13_vl0.27.hdf5', # 'mobilenet_bdd100k_cl0-500k_20ep_woda_ep15_vl0.24.hdf5', # 'mobilenetv2_bdd100k_cl0-500k_20ep_woda_ep17_vl0.22.hdf5', # 'nasnet_bdd100k_cl0-500k_20ep_woda_ep17_vl0.24.hdf5'] class_map_file = bu.class_mapping(input_json=val_json, output_csv=labels_path + 'class_mapping.csv') # Dataset for analysis val_partition, val_labels = bu.get_ids_labels(val_labels_csv, class_map_file) for m in model_files: # test_subset creation pr_file = '.'.join(m.split('.')[:-1]) + '_predictions.csv' predictions, y_scores, img_ids = dt.get_scores_from_file(csv_path + pr_file, val_labels) top_n_args, bot_n_args = dt.get_topbot_n_args(20000, y_scores) cc_high = metrics_color.ColorDensityCube(resolution=4) for arg in top_n_args: cc_high.feed(cv2.imread(img_ids[arg])) print('high sum', np.sum(cc_high.get_cube().flatten())) cc_high.normalize() cc_high.plot_cube() cc_low = metrics_color.ColorDensityCube(resolution=4) for arg in bot_n_args: cc_low.feed(cv2.imread(img_ids[arg])) print('low sum', np.sum(cc_low.get_cube().flatten())) cc_low.normalize() cc_low.plot_cube() cc_diff = cc_high.substract(cc_low, 'value') print('diff mean', np.sum(cc_diff.get_cube().flatten())) print('diff mean', np.mean(cc_diff.get_cube().flatten())) cc_diff.normalize() # cc_diff.plot_cube() # cc_diff.normalize() cc_diff.plot_cube(title='Color cube analysis difference (' + str(20000) + ' images/series)', normalize=True, save=True) def colorcube_analysis(): # m = 'densenet121' for m in models: test_data = dt.get_data('cifar10', (50000, 60000)) top_n = 2000 model_name0 = mt.weight_file_name(m, 'cifar10-2-5', 50, False) # model_name0 = mt.weight_file_name(m, 'cifar10-2-5', 50, False, suffix='ft20ep-exp') model = mt.load_by_name(model_name0, test_data[0].shape[1:], h5_path+model_name0) # y_predicted = model.predict(np.array(test_data[0])) y_predicted = t_log.load_predictions(model_name0, file_path=csv_path) true_classes = [int(k) for k in test_data[1]] scores = metrics.prediction_ratings(y_predicted, true_classes) score_sorted_ids = np.argsort(scores) cc_high = metrics_color.ColorDensityCube(resolution=4) for img_id in score_sorted_ids[-top_n:]: cc_high.feed(test_data[0][img_id]) cc_high.normalize() cc_high.plot_cube() cc_low = metrics_color.ColorDensityCube(resolution=4) for img_id in score_sorted_ids[:top_n]: cc_low.feed(test_data[0][img_id]) cc_low.normalize() cc_diff = cc_high.substract(cc_low, 'value') cc_low.plot_cube() cc_diff.normalize() cc_diff.plot_cube(title='Color cube analysis difference (' + str(top_n) + ' images/series)', normalize=True, save=True) def histogram_analysis(): m = 'densenet121' test_data = dt.get_data('cifar10', (50000, 60000)) top_n = 2000 model_name0 = mt.weight_file_name(m, 'cifar10-2-5', 50, False) y_predicted = t_log.load_predictions(model_name0, file_path=csv_path) true_classes = [int(k) for k in test_data[1]] scores = metrics.prediction_ratings(y_predicted, true_classes) score_sorted_ids = np.argsort(scores) high_score_series = [] low_score_series = [] for k in xrange(0, top_n): high_score_series.append(test_data[0][score_sorted_ids[-k-1]]) low_score_series.append(test_data[0][score_sorted_ids[k]]) plotting.plot_hists(high_score_series, 'high scores', low_score_series, 'low scores', plotting.cs_bgr, title=' ') # title='Histogram analysis (' + str(top_n) + ' images/series)') def colorfulness_analysis(model='densenet121', top_n=2500): """ Experiment to analyse the relevance if the colorfulness attribute See the metrics_color.colorfulness() function for more details on the attribute :param model: The predictions of :model: will be used to compute the prediciton scores :param top_n: Number of elements in the series that will be plotted for analysis :return: """ # Load test data and model results test_data = dt.get_data('cifar10', (50000, 60000)) model_name0 = mt.weight_file_name(model, 'cifar10-2-5', 50, False) y_predicted = t_log.load_predictions(model_name0, file_path=csv_path) true_classes = [int(k) for k in test_data[1]] # Compute scores and sort test data ids by score scores = metrics.prediction_ratings(y_predicted, true_classes) score_sorted_ids = np.argsort(scores) # Compute metric for high score and low score data high_score_series = [] low_score_series = [] print(len(score_sorted_ids)) for k in xrange(0, top_n): high_score_series.append(metrics_color.colorfulness(test_data[0][score_sorted_ids[-k-1]])) low_score_series.append(metrics_color.colorfulness(test_data[0][score_sorted_ids[k]])) # Plot box plot of the two series plotting.box_plot(high_score_series, low_score_series, name_s1='high prediction scores', name_s2='low prediction scores', y_label='Colorfulness', title='Colorfulness analysis (' + str(top_n) + ' images/series)') def entropy_cc_analysis(): m = 'densenet121' test_data = dt.get_data('cifar10', (50000, 60000)) top_n = 2000 model_name0 = mt.weight_file_name(m, 'cifar10-2-5', 50, False) y_predicted = t_log.load_predictions(model_name0, file_path=csv_path) true_classes = [int(k) for k in test_data[1]] scores = metrics.prediction_ratings(y_predicted, true_classes) score_sorted_ids = np.argsort(scores) high_score_entropies = [] low_score_entropies = [] print(len(score_sorted_ids)) for k in xrange(0, top_n): # id = score_sorted_ids[-k - 1] # print(id) # img = test_data[id] high_score_entropies.append(metrics_color.entropy_cc(test_data[0][score_sorted_ids[-k-1]], 8)) low_score_entropies.append(metrics_color.entropy_cc(test_data[0][score_sorted_ids[k]], 8)) plotting.box_plot(high_score_entropies, low_score_entropies, name_s1='high prediction scores', name_s2='low prediction scores', y_label='Color entropy', title='Color entropy analysis (' + str(top_n) + ' images/series)') def data_analysis(): tr_data = dt.get_data('cifar10', (0, 20000)) val_data = dt.get_data('cifar10', (40000, 50000)) test_data = dt.get_data('cifar10', (50000, 60000)) for m in models[:1]: # model0, model_name0 = mt.train2(m, tr_data, val_data, 50, False, 'cifar10-2-5', h5_path) # model0, model_name0 = mt.train(m, 'cifar10-channelswitched', 50, data_augmentation=False, path=res_path) # acc, predicted_classes, y_predicted = dt.predict_and_acc(model0, test_data) # t_log.log_predictions(y_predicted, model_name0, file_path=csv_path) model_name0 = mt.weight_file_name(m, 'cifar10-2-5', 50, False) y_predicted = t_log.load_predictions(model_name0, file_path=csv_path) # true_classes = np.argmax(test_data[1], axis=1) # wrong true_classes = [int(k) for k in test_data[1]] pr = metrics.prediction_ratings(y_predicted, true_classes) imgs_entropies = [] # for image in test_data[0]: # imgs_entropies.append(metrics_color.entropy_cc(image, 8)) # c, i = metrics_color.contrast_intensity(image) # imgs_c.append(c) # imgs_i.append(i) # scores.append(metrics_color.colorfulness(image)) sorted_e = np.argsort(imgs_entropies) # id_list = [sorted_e[k] for k in [10, 100, 1000, 2000, 5000, 8000, 9000, 9900, 9990]] id_list = [21, 3767, 9176, 730, 5905] plotting.show_imgs(id_list, 'cdc entropy examples', test_data[0], showColorCube=True) # pr_sorted_args = np.argsort(pr) # low_e = [imgs_entropies[pr_sorted_args[k]] for k in xrange(2000)] # high_e = [imgs_entropies[pr_sorted_args[k]] for k in xrange(8000, 10000)] # plotting.box_plot(low_e, high_e,'low_score_e', 'high_score_e') # pr_sorted_args = np.argsort(pr) # low_c = [imgs_c[pr_sorted_args[k]] for k in xrange(2000)] # high_c = [imgs_c[pr_sorted_args[k]] for k in xrange(8000, 10000)] # plotting.box_plot(low_c, high_c,'low_score_c', 'high_score_c') # # low_i = [imgs_i[pr_sorted_args[k]] for k in xrange(2000)] # high_i = [imgs_i[pr_sorted_args[k]] for k in xrange(8000, 10000)] # plotting.box_plot(low_i, high_i, 'low_score_i', 'high_score_i') # max = np.max(scores) # index = list(scores).index(max) # scores.pop(index) # pr.pop(index) # plotting.quick_plot(pr, scores, png_path+model_name0+'contrast.png') # plotting.quick_plot(pr, imgs_c) # plotting.quick_plot(pr, imgs_i) def pr_on_fair_distribution(models=['densenet121'], top_n=100, res=4): test_data = dt.get_data('cifar10', (50000, 60000)) # Add every image's cube in densities densities = [] for img in test_data[0]: cc = metrics_color.ColorDensityCube(res) cc.feed(img) densities.append(cc.get_cube()) # ccf = np.array(cc.get_cube()).flatten() # Shape densities (list of cubes) to make a list per color densities_lists = np.swapaxes(np.swapaxes(np.swapaxes(densities, 0, 3), 0, 2), 0, 1) # print(densities_lists.shape) densities_cube = np.empty((res, res, res), dtype=object) # For each color keep the ids of the top_n most dense images in this color (same image can be in 2 colors) for i in xrange(res): for j in xrange(res): for k in xrange(res): # pr_most_dense = [] density_list = densities_lists[i][j][k].tolist() args_most_dense = np.argsort(density_list)[-top_n:] densities_cube[i][j][k] = args_most_dense # print(densities_cube.shape) # Per model analysis for m in models: # Load model predictions and ground_truth values model_name0 = mt.weight_file_name(m, 'cifar10-2-5', 50, False) y_predicted = t_log.load_predictions(model_name0, file_path=csv_path) true_classes = [int(k) for k in test_data[1]] pr = metrics.prediction_ratings(y_predicted, true_classes) # For each color get prediction score of the top_n images score_cube = np.zeros((res, res, res)) global_cc = metrics_color.ColorDensityCube(resolution=res) args_most_dense_all = [] for i in xrange(res): for j in xrange(res): for k in xrange(res): pr_most_dense = [] densities_args = densities_cube[i][j][k].tolist() # args_most_dense = np.argsort(density_list)[-topn:] ijk_cc = metrics_color.ColorDensityCube(res) for a in densities_cube[i][j][k].tolist(): pr_most_dense.append(pr[a]) ijk_cc.feed(test_data[0][a]) global_cc.feed(test_data[0][a]) ijk_cc.normalize() ttl = 'color = (' + str(float(i/res)) + ', ' + str(float(j/res)) + ', ' + str(float(k/res)) + ')' # ijk_cc.plot_cube() score_cube[i][j][k] = np.mean(pr_most_dense) print(np.mean(pr_most_dense)) # args_most_dense_all.append(args_most_dense) ttl = 'color = (' + str(float(i/res)) + ', ' + str(float(j/res)) + ', ' + str(float(k/res)) + ')' # plotting.show_imgs(densities_args[:10], ttl, test_data[0], showColorCube=True, resolution=4) global_cc.normalize() global_cc.plot_cube(title='Fair distributed dataset ColorCube') sc = metrics_color.ColorDensityCube(resolution=res, cube=score_cube) sc.normalize() sc.plot_cube(title='Scores per color for ' + m) def analyse_attributes(model_files): for mf in model_files: attributes = bdd100k_analysis(mf, do_plot_boxes=False) if '_ref' in mf: day_ref_scores = attributes['timeofday']['d_attribute'].get_metric_value_list('score', 'daytime') night_ref_scores = attributes['timeofday']['d_attribute'].get_metric_value_list('score', 'night') hw_ref_scores = attributes['scene']['d_attribute'].get_metric_value_list('score', 'highway') cs_ref_scores = attributes['scene']['d_attribute'].get_metric_value_list('score', 'city street') day_ref_acc = attributes['timeofday']['d_attribute'].get_metric_mean('acc', 'daytime') night_ref_acc = attributes['timeofday']['d_attribute'].get_metric_mean('score', 'night') hw_ref_acc = attributes['scene']['d_attribute'].get_metric_mean('score', 'highway') cs_ref_acc = attributes['scene']['d_attribute'].get_metric_mean('score', 'city street') else: # Score for day and night day_score = attributes['timeofday']['d_attribute'].get_metric_value_list('score', 'daytime') night_score = attributes['timeofday']['d_attribute'].get_metric_value_list('score', 'night') hw_score = attributes['scene']['d_attribute'].get_metric_value_list('score', 'highway') cs_score = attributes['scene']['d_attribute'].get_metric_value_list('score', 'city street') day_acc = attributes['timeofday']['d_attribute'].get_metric_mean('acc', 'daytime') night_acc = attributes['timeofday']['d_attribute'].get_metric_mean('score', 'night') hw_acc = attributes['scene']['d_attribute'].get_metric_mean('score', 'highway') cs_acc = attributes['scene']['d_attribute'].get_metric_mean('score', 'city street') print('Scores: day: %.4f (mean: %.4f / median: %.4f / Q.9: %.4f / acc: %.4f) \n' ' night: %.4f (mean: %.4f / median: %.4f / Q.9: %.4f / acc: %.4f)' % (np.mean(day_score), np.mean(day_score) - np.mean(day_ref_scores), np.median(day_score) - np.median(day_ref_scores), np.quantile(day_score, 0.1) - np.quantile(day_ref_scores, 0.1), day_acc - day_ref_acc, np.mean(night_score), np.mean(night_score) - np.mean(night_ref_scores), np.median(night_score) - np.median(night_ref_scores), np.quantile(night_score, 0.1) - np.quantile(night_ref_scores, 0.1), night_acc - night_ref_acc)) print('Scores: highway: %.4f (mean: %.4f / median: %.4f / Q.9: %.4f / acc: %.4f) \n' ' city street: %.4f (mean: %.4f / median: %.4f / Q.9: %.4f / acc: %.4f)' % (np.mean(hw_score), np.mean(hw_score) - np.mean(hw_ref_scores), np.median(hw_score) - np.median(hw_ref_scores), np.quantile(hw_score, 0.1) - np.quantile(hw_ref_scores, 0.1), hw_acc - hw_ref_acc, np.mean(cs_score), np.mean(cs_score) - np.mean(cs_ref_scores), np.median(cs_score) - np.median(cs_ref_scores), np.quantile(cs_score, 0.1) - np.quantile(cs_ref_scores, 0.1), cs_acc - cs_ref_acc)) print(',Difference fine-tuning/reference') print('Mean score, Mean score, Median, Quantile (90%), Local accuracy') print('%.4f, %.4f, %.4f, %.4f, %.4f\n' '%.4f, %.4f, %.4f, %.4f, %.4f' % (np.mean(day_score), np.mean(day_score) - np.mean(day_ref_scores), np.median(day_score) - np.median(day_ref_scores), np.quantile(day_score, 0.1) - np.quantile(day_ref_scores, 0.1), day_acc - day_ref_acc, np.mean(night_score), np.mean(night_score) - np.mean(night_ref_scores), np.median(night_score) - np.median(night_ref_scores), np.quantile(night_score, 0.1) - np.quantile(night_ref_scores, 0.1), night_acc - night_ref_acc)) print('%.4f, %.4f, %.4f, %.4f, %.4f\n' '%.4f, %.4f, %.4f, %.4f, %.4f' % (np.mean(hw_score), np.mean(hw_score) - np.mean(hw_ref_scores), np.median(hw_score) - np.median(hw_ref_scores), np.quantile(hw_score, 0.1) - np.quantile(hw_ref_scores, 0.1), hw_acc - hw_ref_acc, np.mean(cs_score), np.mean(cs_score) - np.mean(cs_ref_scores), np.median(cs_score) - np.median(cs_ref_scores), np.quantile(cs_score, 0.1) - np.quantile(cs_ref_scores, 0.1), cs_acc - cs_ref_acc)) def show_worst(model_file, n, attribute, mapping, dk2ak=None): # Dataset for analysis val_partition, val_labels = bu.get_ids_labels(val_labels_csv, class_map_file) pr_file = '.'.join(model_file.split('.')[:-1]) + '_predictions.csv' predictions, y_scores, img_ids = dt.get_scores_from_file(csv_path + pr_file, val_labels) args_sorted_scores = np.argsort(y_scores) shift = 10 worst_ids = [] i = 0 while len(worst_ids) < n + shift: if dk2ak: key = dk2ak(img_ids[args_sorted_scores[i]]) else: key = img_ids[args_sorted_scores[i]] if mapping[key] == attribute: worst_ids.append(img_ids[args_sorted_scores[i]]) i += 1 data = [] tag_list = [] for id in worst_ids: print(id) data.append(cv2.imread(id)) tag_list.append(str(np.argmax(predictions[id])) + ' (' + str(val_labels[id]) + ')') print(np.array(data).shape) plotting.show_imgs(xrange(shift, n + shift), 'Worst of ' + attribute, data, tag_list) return worst_ids def confusion(model='densenet121'): # Load test data and model results test_data = dt.get_data('cifar10', (50000, 60000)) model_name0 = mt.weight_file_name(model, 'cifar10-2-5', 50, False) y_predicted = t_log.load_predictions(model_name0, file_path=csv_path) predicted_classes = np.argmax(y_predicted, axis=1) true_classes = [int(k) for k in test_data[1]] print('Confusion Matrix for Total Test Data') print(sk_metrics.confusion_matrix(true_classes, predicted_classes)) scores = metrics.prediction_ratings(y_predicted, true_classes) prediction_scores = np.zeros((10, 1)).tolist() print(prediction_scores) for k in xrange(len(y_predicted)): prediction_scores[predicted_classes[k]].append(scores[k]) print(np.array(prediction_scores).shape) for cifar_class in prediction_scores: print(float(np.mean(cifar_class))) def main(): initialise.init() # colorcube_analysis() # histogram_analysis() # entropy_cc_analysis() # colorfulness_analysis() # r_on_fair_distribution() # data_analysis() # confusion() # select_ft_data('densenet121_bdd100k_cl0-500k_20ep_woda_ep20_vl0.22.hdf5', [], 0, do_plot_boxes=True) # bdd100k_analysis('densenet121_bdd100k_cl0-500k_20ep_woda_ep20_vl0.22.hdf5', do_plot_boxes=True) # bdd100k_cc_analysis() # main()
43.642401
117
0.621562
79570700ee6de05bf8f7b980c48e10a0087bec64
3,775
py
Python
dmifnet/psgn/training.py
leilimaster/DmifNet
cad50bb7a3762745f72b2498c2eef5ad5b21e4c6
[ "MIT" ]
25
2020-07-24T08:24:09.000Z
2022-02-22T07:08:54.000Z
dmifnet/psgn/training.py
leilimaster/DmifNet
cad50bb7a3762745f72b2498c2eef5ad5b21e4c6
[ "MIT" ]
2
2021-01-28T09:54:02.000Z
2021-02-02T09:08:11.000Z
dmifnet/psgn/training.py
leilimaster/DmifNet
cad50bb7a3762745f72b2498c2eef5ad5b21e4c6
[ "MIT" ]
1
2021-06-19T08:47:48.000Z
2021-06-19T08:47:48.000Z
import os from tqdm import trange import torch from dmifnet.common import chamfer_distance from dmifnet.training import BaseTrainer from dmifnet.utils import visualize as vis class Trainer(BaseTrainer): r''' Trainer object for the Point Set Generation Network. The PSGN network is trained on Chamfer distance. The Trainer object obtains methods to perform a train and eval step as well as to visualize the current training state by plotting the respective point clouds. Args: model (nn.Module): PSGN model optiimzer (PyTorch optimizer): The optimizer that should be used device (PyTorch device): the PyTorch device input_type (string): The input type (e.g. 'img') vis_dir (string): the visualisation directory ''' def __init__(self, model, optimizer, device=None, input_type='img', vis_dir=None): self.model = model self.optimizer = optimizer self.device = device self.input_type = input_type self.vis_dir = vis_dir if vis_dir is not None and not os.path.exists(vis_dir): os.makedirs(vis_dir) def train_step(self, data): r''' Performs a train step. The chamfer loss is calculated and an appropriate backward pass is performed. Args: data (tensor): training data ''' self.model.train() points = data.get('pointcloud').to(self.device) inputs = data.get('inputs').to(self.device) loss = self.compute_loss(points, inputs) self.optimizer.zero_grad() loss.backward() self.optimizer.step() return loss.item() def eval_step(self, data): r''' Performs an evaluation step. The chamfer loss is calculated and returned in a dictionary. Args: data (tensor): input data ''' self.model.eval() device = self.device points = data.get('pointcloud_chamfer').to(device) inputs = data.get('inputs').to(device) with torch.no_grad(): points_out = self.model(inputs) loss = chamfer_distance(points, points_out).mean() loss = loss.item() eval_dict = { 'loss': loss, 'chamfer': loss, } return eval_dict def visualize(self, data): r''' Visualizes the current output data of the model. The point clouds for respective input data is plotted. Args: data (tensor): input data ''' device = self.device points_gt = data.get('pointcloud').to(device) inputs = data.get('inputs').to(device) with torch.no_grad(): points_out = self.model(inputs) points_out = points_out.cpu().numpy() points_gt = points_gt.cpu().numpy() batch_size = inputs.size(0) for i in trange(batch_size): input_img_path = os.path.join(self.vis_dir, '%03d_in.png' % i) vis.visualize_data( inputs[i].cpu(), self.input_type, input_img_path) out_file = os.path.join(self.vis_dir, '%03d.png' % i) out_file_gt = os.path.join(self.vis_dir, '%03d_gt.png' % i) vis.visualize_pointcloud(points_out[i], out_file=out_file) vis.visualize_pointcloud(points_gt[i], out_file=out_file_gt) def compute_loss(self, points, inputs): r''' Computes the loss. The Point Set Generation Network is trained on the Chamfer distance. Args: points (tensor): GT point cloud data inputs (tensor): input data for the model ''' points_out = self.model(inputs) loss = chamfer_distance(points, points_out).mean() return loss
31.458333
76
0.61351
795707483fc5efb4e04a4df507c8993cc33001be
11,907
py
Python
GlyphBrowser.roboFontExt/lib/unicodeRanges.py
LettError/glyphBrowser
e080b38ff10e1957818bacc0565ac91c434e652f
[ "BSD-3-Clause" ]
13
2016-02-28T16:58:34.000Z
2022-03-26T01:33:30.000Z
lib/unicodeRanges.py
LettError/glyphBrowser
e080b38ff10e1957818bacc0565ac91c434e652f
[ "BSD-3-Clause" ]
15
2016-02-29T11:29:13.000Z
2021-12-08T20:12:38.000Z
lib/unicodeRanges.py
LettError/glyphBrowser
e080b38ff10e1957818bacc0565ac91c434e652f
[ "BSD-3-Clause" ]
5
2018-01-26T11:53:37.000Z
2021-03-29T16:33:58.000Z
# -*- coding: UTF-8 -*- # Generated from glyphNameFormatter range names # Generated on 2021 12 08 20:55:40 unicodeRangeNames ={ (0, 127): 'Basic Latin', (128, 255): 'Latin-1 Supplement', (256, 383): 'Latin Extended-A', (384, 591): 'Latin Extended-B', (592, 687): 'IPA Extensions', (688, 767): 'Spacing Modifier Letters', (768, 879): 'Combining Diacritical Marks', (880, 1023): 'Greek and Coptic', (1024, 1279): 'Cyrillic', (1280, 1327): 'Cyrillic Supplement', (1328, 1423): 'Armenian', (1424, 1535): 'Hebrew', (1536, 1791): 'Arabic', (1792, 1871): 'Syriac', (1872, 1919): 'Arabic Supplement', (1920, 1983): 'Thaana', (1984, 2047): 'NKo', (2048, 2111): 'Samaritan', (2112, 2143): 'Mandaic', (2144, 2159): 'Syriac Supplement', (2208, 2303): 'Arabic Extended-A', (2304, 2431): 'Devanagari', (2432, 2559): 'Bengali', (2560, 2687): 'Gurmukhi', (2688, 2815): 'Gujarati', (2816, 2943): 'Oriya', (2944, 3071): 'Tamil', (3072, 3199): 'Telugu', (3200, 3327): 'Kannada', (3328, 3455): 'Malayalam', (3456, 3583): 'Sinhala', (3584, 3711): 'Thai', (3712, 3839): 'Lao', (3840, 4095): 'Tibetan', (4096, 4255): 'Myanmar', (4256, 4351): 'Georgian', (4352, 4607): 'Hangul Jamo', (4608, 4991): 'Ethiopic', (4992, 5023): 'Ethiopic Supplement', (5024, 5119): 'Cherokee', (5120, 5759): 'Unified Canadian Aboriginal Syllabics', (5760, 5791): 'Ogham', (5792, 5887): 'Runic', (5888, 5919): 'Tagalog', (5920, 5951): 'Hanunoo', (5952, 5983): 'Buhid', (5984, 6015): 'Tagbanwa', (6016, 6143): 'Khmer', (6144, 6319): 'Mongolian', (6320, 6399): 'Unified Canadian Aboriginal Syllabics Extended', (6400, 6479): 'Limbu', (6480, 6527): 'Tai Le', (6528, 6623): 'New Tai Lue', (6624, 6655): 'Khmer Symbols', (6656, 6687): 'Buginese', (6688, 6831): 'Tai Tham', (6832, 6911): 'Combining Diacritical Marks Extended', (6912, 7039): 'Balinese', (7040, 7103): 'Sundanese', (7104, 7167): 'Batak', (7168, 7247): 'Lepcha', (7248, 7295): 'Ol Chiki', (7296, 7311): 'Cyrillic Extended-C', (7312, 7359): 'Georgian Extended', (7360, 7375): 'Sundanese Supplement', (7376, 7423): 'Vedic Extensions', (7424, 7551): 'Phonetic Extensions', (7552, 7615): 'Phonetic Extensions Supplement', (7616, 7679): 'Combining Diacritical Marks Supplement', (7680, 7935): 'Latin Extended Additional', (7936, 8191): 'Greek Extended', (8192, 8303): 'General Punctuation', (8304, 8351): 'Superscripts and Subscripts', (8352, 8399): 'Currency Symbols', (8400, 8447): 'Combining Diacritical Marks for Symbols', (8448, 8527): 'Letterlike Symbols', (8528, 8591): 'Number Forms', (8592, 8703): 'Arrows', (8704, 8959): 'Mathematical Operators', (8960, 9215): 'Miscellaneous Technical', (9216, 9279): 'Control Pictures', (9280, 9311): 'Optical Character Recognition', (9312, 9471): 'Enclosed Alphanumerics', (9472, 9599): 'Box Drawing', (9600, 9631): 'Block Elements', (9632, 9727): 'Geometric Shapes', (9728, 9983): 'Miscellaneous Symbols', (9984, 10175): 'Dingbats', (10176, 10223): 'Miscellaneous Mathematical Symbols-A', (10224, 10239): 'Supplemental Arrows-A', (10240, 10495): 'Braille Patterns', (10496, 10623): 'Supplemental Arrows-B', (10624, 10751): 'Miscellaneous Mathematical Symbols-B', (10752, 11007): 'Supplemental Mathematical Operators', (11008, 11263): 'Miscellaneous Symbols and Arrows', (11264, 11359): 'Glagolitic', (11360, 11391): 'Latin Extended-C', (11392, 11519): 'Coptic', (11520, 11567): 'Georgian Supplement', (11568, 11647): 'Tifinagh', (11648, 11743): 'Ethiopic Extended', (11744, 11775): 'Cyrillic Extended-A', (11776, 11903): 'Supplemental Punctuation', (11904, 12031): 'CJK Radicals Supplement', (12032, 12255): 'Kangxi Radicals', (12272, 12287): 'Ideographic Description Characters', (12288, 12351): 'CJK Symbols and Punctuation', (12352, 12447): 'Hiragana', (12448, 12543): 'Katakana', (12544, 12591): 'Bopomofo', (12592, 12687): 'Hangul Compatibility Jamo', (12688, 12703): 'Kanbun', (12704, 12735): 'Bopomofo Extended', (12736, 12783): 'CJK Strokes', (12784, 12799): 'Katakana Phonetic Extensions', (12800, 13055): 'Enclosed CJK Letters and Months', (13056, 13311): 'CJK Compatibility', (13312, 19903): 'CJK Unified Ideographs Extension A', (19904, 19967): 'Yijing Hexagram Symbols', (19968, 40959): 'CJK Unified Ideographs', (40960, 42127): 'Yi Syllables', (42128, 42191): 'Yi Radicals', (42192, 42239): 'Lisu', (42240, 42559): 'Vai', (42560, 42655): 'Cyrillic Extended-B', (42656, 42751): 'Bamum', (42752, 42783): 'Modifier Tone Letters', (42784, 43007): 'Latin Extended-D', (43008, 43055): 'Syloti Nagri', (43056, 43071): 'Common Indic Number Forms', (43072, 43135): 'Phags-pa', (43136, 43231): 'Saurashtra', (43232, 43263): 'Devanagari Extended', (43264, 43311): 'Kayah Li', (43312, 43359): 'Rejang', (43360, 43391): 'Hangul Jamo Extended-A', (43392, 43487): 'Javanese', (43488, 43519): 'Myanmar Extended-B', (43520, 43615): 'Cham', (43616, 43647): 'Myanmar Extended-A', (43648, 43743): 'Tai Viet', (43744, 43775): 'Meetei Mayek Extensions', (43776, 43823): 'Ethiopic Extended-A', (43824, 43887): 'Latin Extended-E', (43888, 43967): 'Cherokee Supplement', (43968, 44031): 'Meetei Mayek', (44032, 55215): 'Hangul Syllables', (55216, 55295): 'Hangul Jamo Extended-B', (55296, 56191): 'High Surrogates', (56192, 56319): 'High Private Use Surrogates', (56320, 57343): 'Low Surrogates', (57344, 63743): 'Private Use Area', (63744, 64255): 'CJK Compatibility Ideographs', (64256, 64335): 'Alphabetic Presentation Forms', (64336, 65023): 'Arabic Presentation Forms-A', (65024, 65039): 'Variation Selectors', (65040, 65055): 'Vertical Forms', (65056, 65071): 'Combining Half Marks', (65072, 65103): 'CJK Compatibility Forms', (65104, 65135): 'Small Form Variants', (65136, 65279): 'Arabic Presentation Forms-B', (65280, 65519): 'Halfwidth and Fullwidth Forms', (65520, 65535): 'Specials', (65536, 65663): 'Linear B Syllabary', (65664, 65791): 'Linear B Ideograms', (65792, 65855): 'Aegean Numbers', (65856, 65935): 'Ancient Greek Numbers', (65936, 65999): 'Ancient Symbols', (66000, 66047): 'Phaistos Disc', (66176, 66207): 'Lycian', (66208, 66271): 'Carian', (66272, 66303): 'Coptic Epact Numbers', (66304, 66351): 'Old Italic', (66352, 66383): 'Gothic', (66384, 66431): 'Old Permic', (66432, 66463): 'Ugaritic', (66464, 66527): 'Old Persian', (66560, 66639): 'Deseret', (66640, 66687): 'Shavian', (66688, 66735): 'Osmanya', (66736, 66815): 'Osage', (66816, 66863): 'Elbasan', (66864, 66927): 'Caucasian Albanian', (67072, 67455): 'Linear A', (67584, 67647): 'Cypriot Syllabary', (67648, 67679): 'Imperial Aramaic', (67680, 67711): 'Palmyrene', (67712, 67759): 'Nabataean', (67808, 67839): 'Hatran', (67840, 67871): 'Phoenician', (67872, 67903): 'Lydian', (67968, 67999): 'Meroitic Hieroglyphs', (68000, 68095): 'Meroitic Cursive', (68096, 68191): 'Kharoshthi', (68192, 68223): 'Old South Arabian', (68224, 68255): 'Old North Arabian', (68288, 68351): 'Manichaean', (68352, 68415): 'Avestan', (68416, 68447): 'Inscriptional Parthian', (68448, 68479): 'Inscriptional Pahlavi', (68480, 68527): 'Psalter Pahlavi', (68608, 68687): 'Old Turkic', (68736, 68863): 'Old Hungarian', (68864, 68927): 'Hanifi Rohingya', (69216, 69247): 'Rumi Numeral Symbols', (69376, 69423): 'Old Sogdian', (69424, 69487): 'Sogdian', (69600, 69631): 'Elymaic', (69632, 69759): 'Brahmi', (69760, 69839): 'Kaithi', (69840, 69887): 'Sora Sompeng', (69888, 69967): 'Chakma', (69968, 70015): 'Mahajani', (70016, 70111): 'Sharada', (70112, 70143): 'Sinhala Archaic Numbers', (70144, 70223): 'Khojki', (70272, 70319): 'Multani', (70320, 70399): 'Khudawadi', (70400, 70527): 'Grantha', (70656, 70783): 'Newa', (70784, 70879): 'Tirhuta', (71040, 71167): 'Siddham', (71168, 71263): 'Modi', (71264, 71295): 'Mongolian Supplement', (71296, 71375): 'Takri', (71424, 71487): 'Ahom', (71680, 71759): 'Dogra', (71840, 71935): 'Warang Citi', (72096, 72191): 'Nandinagari', (72192, 72271): 'Zanabazar Square', (72272, 72367): 'Soyombo', (72384, 72447): 'Pau Cin Hau', (72704, 72815): 'Bhaiksuki', (72816, 72895): 'Marchen', (72960, 73055): 'Masaram Gondi', (73056, 73135): 'Gunjala Gondi', (73440, 73471): 'Makasar', (73664, 73727): 'Tamil Supplement', (73728, 74751): 'Cuneiform', (74752, 74879): 'Cuneiform Numbers and Punctuation', (74880, 75087): 'Early Dynastic Cuneiform', (77824, 78895): 'Egyptian Hieroglyphs', (78896, 78911): 'Egyptian Hieroglyph Format Controls', (82944, 83583): 'Anatolian Hieroglyphs', (92160, 92735): 'Bamum Supplement', (92736, 92783): 'Mro', (92880, 92927): 'Bassa Vah', (92928, 93071): 'Pahawh Hmong', (93760, 93855): 'Medefaidrin', (93952, 94111): 'Miao', (94176, 94207): 'Ideographic Symbols and Punctuation', (94208, 100351): 'Tangut', (100352, 101119): 'Tangut Components', (110592, 110847): 'Kana Supplement', (110848, 110895): 'Kana Extended-A', (110896, 110959): 'Small Kana Extension', (110960, 111359): 'Nushu', (113664, 113823): 'Duployan', (113824, 113839): 'Shorthand Format Controls', (118784, 119039): 'Byzantine Musical Symbols', (119040, 119295): 'Musical Symbols', (119296, 119375): 'Ancient Greek Musical Notation', (119520, 119551): 'Mayan Numerals', (119552, 119647): 'Tai Xuan Jing Symbols', (119648, 119679): 'Counting Rod Numerals', (119808, 120831): 'Mathematical Alphanumeric Symbols', (120832, 121519): 'Sutton SignWriting', (122880, 122927): 'Glagolitic Supplement', (123136, 123215): 'Nyiakeng Puachue Hmong', (123584, 123647): 'Wancho', (124928, 125151): 'Mende Kikakui', (125184, 125279): 'Adlam', (126064, 126143): 'Indic Siyaq Numbers', (126208, 126287): 'Ottoman Siyaq Numbers', (126464, 126719): 'Arabic Mathematical Alphabetic Symbols', (126976, 127023): 'Mahjong Tiles', (127024, 127135): 'Domino Tiles', (127136, 127231): 'Playing Cards', (127232, 127487): 'Enclosed Alphanumeric Supplement', (127488, 127743): 'Enclosed Ideographic Supplement', (127744, 128511): 'Miscellaneous Symbols and Pictographs', (128512, 128591): 'Emoticons', (128592, 128639): 'Ornamental Dingbats', (128640, 128767): 'Transport and Map Symbols', (128768, 128895): 'Alchemical Symbols', (128896, 129023): 'Geometric Shapes Extended', (129024, 129279): 'Supplemental Arrows-C', (129280, 129535): 'Supplemental Symbols and Pictographs', (129536, 129647): 'Chess Symbols', (129648, 129791): 'Symbols and Pictographs Extended-A', (131072, 173791): 'CJK Unified Ideographs Extension B', (173824, 177983): 'CJK Unified Ideographs Extension C', (177984, 178207): 'CJK Unified Ideographs Extension D', (178208, 183983): 'CJK Unified Ideographs Extension E', (183984, 191471): 'CJK Unified Ideographs Extension F', (194560, 195103): 'CJK Compatibility Ideographs Supplement', (917504, 917631): 'Tags', (917760, 917999): 'Variation Selectors Supplement', (983040, 1048575): 'Supplementary Private Use Area-A', (1048576, 1114111): 'Supplementary Private Use Area-B'}
39.29703
67
0.616192
795707f06e7886c858c9a14831e2f85f8340f3cd
364
py
Python
store/urls.py
ruhulaminparvez/HomeFood
f2e83bb057fbdac1f4f552ee84ab16915162942d
[ "MIT" ]
5
2021-09-10T07:43:31.000Z
2022-03-26T10:34:29.000Z
store/urls.py
MahamudM90/eCommerce
82d64891254966048362d73247ee8e24ee0156c9
[ "MIT" ]
null
null
null
store/urls.py
MahamudM90/eCommerce
82d64891254966048362d73247ee8e24ee0156c9
[ "MIT" ]
2
2021-09-11T19:42:47.000Z
2021-12-06T17:48:50.000Z
from django.urls import path from . import views urlpatterns = [ path('', views.store, name="store"), path('cart/', views.cart, name="cart"), path('checkout/', views.checkout, name="checkout"), path('update_item/', views.updateItem, name="update_item"), path('process_order/', views.processOrder, name="process_order"), ]
30.333333
73
0.634615
795708336f9075f566264b13c8a3bb4299d835d1
2,841
py
Python
flambe/runnable/cluster_runnable.py
ethan-asapp/flambe
70257167058c7b82ee39f74167a6161bd264ad18
[ "MIT" ]
148
2019-08-29T21:19:03.000Z
2022-03-18T06:13:53.000Z
flambe/runnable/cluster_runnable.py
cle-ros/flambe
0dc2f5b2b286694defe8abf450fe5be9ae12c097
[ "MIT" ]
108
2019-09-03T14:36:10.000Z
2020-05-13T15:53:14.000Z
flambe/runnable/cluster_runnable.py
cle-ros/flambe
0dc2f5b2b286694defe8abf450fe5be9ae12c097
[ "MIT" ]
21
2019-09-08T14:09:45.000Z
2020-12-27T04:12:33.000Z
from abc import abstractmethod from typing import Optional, Dict, Callable from flambe.runnable import Runnable from flambe.cluster import Cluster from flambe.runnable.environment import RemoteEnvironment class ClusterRunnable(Runnable): """Base class for all runnables that are able to run on cluster. This type of Runnables must include logic in the 'run' method to deal with the fact that they could be running in a distributed cluster of machines. To provide useful information about the cluster, a RemoteEnvironment object will be injected when running remotely. Attributes ---------- config: configparser.ConfigParser The secrets that the user provides. For example, 'config["AWS"]["ACCESS_KEY"]' env: RemoteEnvironment The remote environment has information about the cluster where this ClusterRunnable will be running. IMPORTANT: this object will be available only when the ClusterRunnable is running remotely. user_provider: Callable[[], str] The logic for specifying the user triggering this Runnable. If not passed, by default it will pick the computer's user. """ def __init__(self, user_provider: Callable[[], str] = None, env: Optional[RemoteEnvironment] = None, **kwargs) -> None: super().__init__(user_provider=user_provider, **kwargs) self.env = env @abstractmethod def setup(self, cluster: Cluster, extensions: Dict[str, str], force: bool, **kwargs) -> None: """Setup the cluster. Parameters ---------- cluster: Cluster The cluster where this Runnable will be running extensions: Dict[str, str] The ClusterRunnable extensions force: bool The force value provided to Flambe """ raise NotImplementedError() def setup_inject_env(self, cluster: Cluster, extensions: Dict[str, str], force: bool, **kwargs) -> None: """Call setup and inject the RemoteEnvironment Parameters ---------- cluster: Cluster The cluster where this Runnable will be running extensions: Dict[str, str] The ClusterRunnable extensions force: bool The force value provided to Flambe """ self.setup(cluster=cluster, extensions=extensions, force=force, **kwargs) self.set_serializable_attr("env", cluster.get_remote_env(self.user_provider)) def set_serializable_attr(self, attr, value): """Set an attribute while keep supporting serializaton. """ setattr(self, attr, value) if hasattr(self, "_saved_kwargs"): self._saved_kwargs[attr] = value
34.646341
85
0.641675
79570868eef1b8c080e13f307dd08ef8d0597da5
785
py
Python
pyxley/charts/mg/figure.py
snowind/pyxley
cff9e50b8d80b9794c6907355e541f166959cd6c
[ "MIT" ]
2,536
2015-06-26T20:12:30.000Z
2022-03-01T07:26:44.000Z
pyxley/charts/mg/figure.py
zhiaozhou/pyxley
2dab00022d977d986169cd8a629b3a2f91be893f
[ "MIT" ]
51
2015-07-17T14:16:43.000Z
2021-07-09T21:34:36.000Z
pyxley/charts/mg/figure.py
zhiaozhou/pyxley
2dab00022d977d986169cd8a629b3a2f91be893f
[ "MIT" ]
335
2015-07-16T20:22:00.000Z
2022-02-25T07:18:15.000Z
from .axes import Axes from .layout import Layout from .graphic import Graphic class Figure(object): """ Metricsgraphics Figure class. This class is a composition of Axes, Graphic, and Layout options. Args: url (str): name of the endpoint to create. chart_id (str): html element id. """ def __init__(self, url, chart_id): self.url = url self.chart_id = chart_id self.axes = Axes() self.graphics = Graphic() self.layout = Layout() def get(self): """Return axes, graphics, and layout options.""" options = {} for x in [self.axes, self.graphics, self.layout]: for k, v in list(x.get().items()): options[k] = v return options
25.322581
73
0.573248
795708792b2f196d7353a83a8b4b30f0474ca574
6,101
py
Python
datafeeds/jqdatafeeds/stockfeedsjqdata.py
liuqiuxi/datafeeds
50d1615a96f7d17d3ecd8ab661c4e1d5f43b9e8d
[ "MIT" ]
1
2021-03-16T03:12:44.000Z
2021-03-16T03:12:44.000Z
datafeeds/jqdatafeeds/stockfeedsjqdata.py
liuqiuxi/datafeeds
50d1615a96f7d17d3ecd8ab661c4e1d5f43b9e8d
[ "MIT" ]
null
null
null
datafeeds/jqdatafeeds/stockfeedsjqdata.py
liuqiuxi/datafeeds
50d1615a96f7d17d3ecd8ab661c4e1d5f43b9e8d
[ "MIT" ]
null
null
null
# -*- coding:utf-8 -*- # @Time : 2019-12-27 15:48 # @Author : liuqiuxi # @Email : liuqiuxi1990@gmail.com # @File : stockfeedsjqdata.py # @Project : datafeeds # @Software: PyCharm # @Remark : This is class of stock market import datetime import pandas as pd import numpy as np from datafeeds.jqdatafeeds import BaseJqData from datafeeds.utils import BarFeedConfig from datafeeds import logger class AShareCalendarJqData(BaseJqData): def __init__(self): super(AShareCalendarJqData, self).__init__() def get_calendar(self, begin_datetime, end_datetime): connect = self.connect() data = connect.get_trade_days(start_date=begin_datetime, end_date=end_datetime, count=None) data = pd.DataFrame(data={"dateTime": data}) datetime_list = data.loc[:, "dateTime"].apply( lambda x: datetime.datetime.combine(date=x, time=datetime.time.min)) data.loc[:, "dateTime"] = datetime_list data.drop_duplicates(subset=["dateTime"], keep="first", inplace=True) data.sort_values(by="dateTime", axis=0, ascending=True, inplace=True) data.reset_index(drop=True, inplace=True) connect.logout() return data class AShareQuotationJqData(BaseJqData): LOGGER_NAME = "AShareQuotationJqData" def __init__(self): super(AShareQuotationJqData, self).__init__() self.__adjust_name_dict = {"F": "pre", "B": "post"} def get_quotation(self, securityIds, items, frequency, begin_datetime, end_datetime, adjusted=None): connect = self.connect() securityIds = self.wind_to_default(securityIds=securityIds) frequency = self.get_frequency_cycle(frequency=frequency) adjusted = self.__adjust_name_dict.get(adjusted, None) rename_dict = BarFeedConfig.get_jq_data_items().get(self.LOGGER_NAME) data = pd.DataFrame() for securityId in securityIds: data0 = connect.get_price(security=securityId, start_date=begin_datetime, end_date=end_datetime, frequency=frequency, skip_paused=False, fq=adjusted) data0.loc[:, "dateTime"] = data0.index securityId = self.default_to_wind(securityIds=[securityId]) data0.loc[:, "securityId"] = securityId data = pd.concat(objs=[data, data0], axis=0, join="outer") data.rename(columns=rename_dict, inplace=True) # choose items to data log = logger.get_logger(name=self.LOGGER_NAME) default_items = list(rename_dict.values()) real_items = [] for item in items: if item in ["securityId", "dateTime"]: log.info("There is no need add item: %s to parameters items" % item) elif item in default_items: real_items.append(item) else: log.warning("item %s not in default items, so we remove this item to data" % item) data = data.loc[:, ["dateTime", "securityId"] + real_items].copy(deep=True) connect.logout() return data class AShareDayVarsJqData(BaseJqData): def __init__(self): super(AShareDayVarsJqData, self).__init__() def get_value(self, date_datetime): connect = self.connect() data = connect.get_all_securities(types=["stock"], date=date_datetime) data.loc[:, "securityId"] = self.default_to_wind(securityIds=list(data.index)) data = data.loc[:, ["securityId", "start_date"]].copy(deep=True) data.loc[:, "code"] = data.index valuation = connect.valuation query = connect.query(valuation.code, valuation.market_cap, valuation.circulating_market_cap, valuation.pe_ratio, valuation.turnover_ratio, valuation.pb_ratio ).filter(connect.valuation.code.in_(list(data.index))) data0 = connect.get_fundamentals(query_object=query, date=date_datetime) data = pd.merge(left=data, right=data0, how="left", on="code") # 市值和总市值转化为元 data.loc[:, "circulating_market_cap"] = data.loc[:, "circulating_market_cap"] * 100000000 data.loc[:, "market_cap"] = data.loc[:, "market_cap"] * 100000000 # 换手率转化为基本单位 data.loc[:, "turnover_ratio"] = data.loc[:, "turnover_ratio"] / 100 # jQDATA暂时未有ST和停牌数据,以后有了再补充 data.rename(columns={"start_date": "listDate", "market_cap": "totalValue", "pe_ratio": "PE_TTM", "pb_ratio": "PB", "circulating_market_cap": "marketValue", "turnover_ratio": "turnover"}, inplace=True) data.loc[:, "dateTime"] = date_datetime data = data.loc[:, ["dateTime", "securityId", "marketValue", "totalValue", "turnover", "PE_TTM", "PB", "listDate"]].copy(deep=True) connect.logout() return data class AShareIndustryJqData(BaseJqData): def __init__(self): super(AShareIndustryJqData, self).__init__() def get_sw_industry(self, securityIds, date_datetime, lv): connect = self.connect() securityIds = self.wind_to_default(securityIds=securityIds) data0 = connect.get_industry(security=securityIds, date=date_datetime) data = pd.DataFrame(data={"securityId": securityIds}) # get SW key level key = "sw_l" + str(lv) data.loc[:, "industryName"] = data.loc[:, "securityId"].apply(lambda x: data0.get(x, np.nan)) data.loc[:, "industryName"] = data.loc[:, "industryName"].apply( lambda x: x.get(key) if isinstance(x, dict) else np.nan) data.loc[:, "industryName"] = data.loc[:, "industryName"].apply( lambda x: x.get("industry_name", np.nan) if isinstance(x, dict) else np.nan) data.loc[:, "securityId"] = self.default_to_wind(securityIds=list(data.loc[:, "securityId"])) data.loc[:, "dateTime"] = date_datetime connect.logout() return data
41.222973
119
0.62334
795709a758ab24bfead9e8f78c5bac62065e6b9f
970
py
Python
app/controllers/products/get_one.py
Brunoro811/api_dangels
21c064eaa4f5009412dddc9676044d6cc08a5b65
[ "MIT" ]
null
null
null
app/controllers/products/get_one.py
Brunoro811/api_dangels
21c064eaa4f5009412dddc9676044d6cc08a5b65
[ "MIT" ]
null
null
null
app/controllers/products/get_one.py
Brunoro811/api_dangels
21c064eaa4f5009412dddc9676044d6cc08a5b65
[ "MIT" ]
null
null
null
from flask import jsonify from http import HTTPStatus from sqlalchemy.orm.exc import NoResultFound from app.controllers.products.products_helpers import help_normalize_variations from app.models.product.products_model import ProductModel def get_one_product(id: int): try: product: ProductModel = ProductModel.query.get(id) if not product: raise NoResultFound """ obj_product_completed = {} print("Product: ", product.date_start) print("Product type: ", type(product.date_start)) obj_product_completed = { **product.asdict(), **help_normalize_variations(product.variations)[0], } """ return jsonify(product), HTTPStatus.OK except NoResultFound: return {"error": "Not found"}, HTTPStatus.NOT_FOUND # except AttributeError: # return {"error": "Not found"}, HTTPStatus.NOT_FOUND except Exception as e: raise e
27.714286
79
0.661856
79570ab526d12bb74cd4c30658cf229cae2a02dc
812
py
Python
tests/test_stats.py
bibsAPB/pathways-analysis
b3a094b98e3022b7a7d959f93e62101483117372
[ "MIT" ]
null
null
null
tests/test_stats.py
bibsAPB/pathways-analysis
b3a094b98e3022b7a7d959f93e62101483117372
[ "MIT" ]
null
null
null
tests/test_stats.py
bibsAPB/pathways-analysis
b3a094b98e3022b7a7d959f93e62101483117372
[ "MIT" ]
3
2018-04-24T14:28:43.000Z
2018-05-11T12:18:10.000Z
from models import Sample, SampleCollection, Experiment import pandas as pd from stats import ttest def test_ttest(): data1 = {'BAD': 1.2345, 'FUCA2': 6.5432} data2 = {'BAD': 2.3456, 'FUCA2': 7.6543} data3 = {'BAD': 6.3456, 'FUCA2': 11.6543} data4 = {'BAD': 7.1111, 'FUCA2': 9.9711} tumour_samples = [Sample.from_names('Tumour_1', data1), Sample.from_names('Tumour_2', data2)] normal_samples = [Sample.from_names('Normal_1', data3), Sample.from_names('Normal_2', data4)] tumour = SampleCollection('Tumour', tumour_samples) normal = SampleCollection('Normal', normal_samples) experiment = Experiment(case=tumour, control=normal) tt = ttest(experiment) assert isinstance(tt, pd.Series) assert all(gene in list(tt.keys()) for gene in experiment.get_all().genes)
36.909091
97
0.689655
79570ac8d41e94b03a3e5cf4282109696826b97d
6,708
py
Python
forms.py
kirankumarsripati/udacity-nd0044-01-fyyur
23cbef9725286adb86f0bcb0fc027e9a7161f1b2
[ "MIT" ]
null
null
null
forms.py
kirankumarsripati/udacity-nd0044-01-fyyur
23cbef9725286adb86f0bcb0fc027e9a7161f1b2
[ "MIT" ]
null
null
null
forms.py
kirankumarsripati/udacity-nd0044-01-fyyur
23cbef9725286adb86f0bcb0fc027e9a7161f1b2
[ "MIT" ]
null
null
null
from datetime import datetime from flask_wtf import Form from wtforms import StringField, SelectField, SelectMultipleField, DateTimeField, BooleanField, TextAreaField, ValidationError, IntegerField from wtforms.validators import DataRequired, AnyOf, URL, Length, NumberRange, Regexp import phonenumbers facebook_regex = "((http|https):\/\/|)(www\.|)facebook\.com\/[a-zA-Z0-9.]{1,}"; facebook_invalid_message = "Facebook URL is Invalid" def ValidatorChoices(choices, message = 'Invalid choice selected'): # only str or list values accepted def _validator(form, field): choices_values = [choice[1] for choice in choices] if isinstance(field.data, str): if field.data not in choices_values: raise ValidationError(message) else: for value in field.data: if value not in choices_values: raise ValidationError(message) return _validator def ValidatorPhone(): # Ref: https://stackoverflow.com/questions/36251149/validating-us-phone-number-in-wtfforms def _validate_phone(form, field): if len(field.data) > 16: raise ValidationError('Invalid phone number.') try: input_number = phonenumbers.parse(field.data) if not (phonenumbers.is_valid_number(input_number)): raise ValidationError('Invalid phone number.') except: try: input_number = phonenumbers.parse("+1"+field.data) if not (phonenumbers.is_valid_number(input_number)): raise ValidationError('Invalid phone number.') except: raise ValidationError('Invalid phone number.') return None return _validate_phone; genre_choices=[ ('Alternative', 'Alternative'), ('Blues', 'Blues'), ('Classical', 'Classical'), ('Country', 'Country'), ('Electronic', 'Electronic'), ('Folk', 'Folk'), ('Funk', 'Funk'), ('Hip-Hop', 'Hip-Hop'), ('Heavy Metal', 'Heavy Metal'), ('Instrumental', 'Instrumental'), ('Jazz', 'Jazz'), ('Musical Theatre', 'Musical Theatre'), ('Pop', 'Pop'), ('Punk', 'Punk'), ('R&B', 'R&B'), ('Reggae', 'Reggae'), ('Rock n Roll', 'Rock n Roll'), ('Soul', 'Soul'), ('Other', 'Other'), ] state_choices=[ ('AL', 'AL'), ('AK', 'AK'), ('AZ', 'AZ'), ('AR', 'AR'), ('CA', 'CA'), ('CO', 'CO'), ('CT', 'CT'), ('DE', 'DE'), ('DC', 'DC'), ('FL', 'FL'), ('GA', 'GA'), ('HI', 'HI'), ('ID', 'ID'), ('IL', 'IL'), ('IN', 'IN'), ('IA', 'IA'), ('KS', 'KS'), ('KY', 'KY'), ('LA', 'LA'), ('ME', 'ME'), ('MT', 'MT'), ('NE', 'NE'), ('NV', 'NV'), ('NH', 'NH'), ('NJ', 'NJ'), ('NM', 'NM'), ('NY', 'NY'), ('NC', 'NC'), ('ND', 'ND'), ('OH', 'OH'), ('OK', 'OK'), ('OR', 'OR'), ('MD', 'MD'), ('MA', 'MA'), ('MI', 'MI'), ('MN', 'MN'), ('MS', 'MS'), ('MO', 'MO'), ('PA', 'PA'), ('RI', 'RI'), ('SC', 'SC'), ('SD', 'SD'), ('TN', 'TN'), ('TX', 'TX'), ('UT', 'UT'), ('VT', 'VT'), ('VA', 'VA'), ('WA', 'WA'), ('WV', 'WV'), ('WI', 'WI'), ('WY', 'WY'), ] class ShowForm(Form): artist_id = StringField( 'artist_id' ) venue_id = StringField( 'venue_id' ) start_time = DateTimeField( 'start_time', validators=[DataRequired()], default= datetime.today() ) class VenueForm(Form): name = StringField( 'name', validators=[DataRequired()] ) city = StringField( 'city', validators=[DataRequired(), Length(max=120)] ) state = SelectField( 'state', validators=[DataRequired(), ValidatorChoices(choices=state_choices, message='Invalid State')], choices=state_choices ) address = StringField( 'address', validators=[DataRequired(), Length(max=120)] ) phone = StringField( 'phone', validators=[ValidatorPhone()] ) image_link = StringField( 'image_link', validators=[URL(), Length(max=500)] ) genres = SelectMultipleField( # DONE implement enum restriction 'genres', validators=[DataRequired(), ValidatorChoices(choices=genre_choices, message='Invalid Genre')], choices=genre_choices ) facebook_link = StringField( 'facebook_link', validators=[URL(), Length(max=120), Regexp(regex=facebook_regex, message=facebook_invalid_message)] ) website = StringField( 'website', validators=[URL(), Length(max=120)] ) seeking_talent = BooleanField( 'seeking_talent' ) seeking_description = TextAreaField( 'seeking_description', validators=[Length(max=500)] ) image_link = StringField( 'image_link', validators=[URL(), Length(max=500)] ) class ArtistForm(Form): name = StringField( 'name', validators=[DataRequired()] ) city = StringField( 'city', validators=[DataRequired(), Length(max=120)] ) state = SelectField( # DONE implement validation logic for state 'state', validators=[DataRequired(), ValidatorChoices(choices=state_choices, message='Invalid State')], choices=state_choices ) phone = StringField( 'phone', validators=[ValidatorPhone()] ) image_link = StringField( 'image_link', validators=[Length(max=120)] ) genres = SelectMultipleField( 'genres', validators=[DataRequired(), ValidatorChoices(choices=genre_choices, message='Invalid Genre')], choices=genre_choices ) facebook_link = StringField( # DONE implement enum restriction 'facebook_link', validators=[URL(), Length(max=120), Regexp(regex=facebook_regex, message=facebook_invalid_message)] ) website = StringField( 'website', validators=[URL(), Length(max=120)] ) seeking_venue = BooleanField( 'seeking_venue' ) seeking_description = TextAreaField( 'seeking_description', validators=[Length(max=500)] ) image_link = StringField( 'image_link', validators=[URL(), Length(max=500)] ) # DONE IMPLEMENT NEW ARTIST FORM AND NEW SHOW FORM class ShowForm(Form): artist_id = IntegerField( 'artist_id', validators=[DataRequired(), NumberRange(min=1, message="ID cannot be negative or string")] ) venue_id = IntegerField( 'venue_id', validators=[DataRequired(), NumberRange(min=1, message="ID cannot be negative or string")] ) start_time = DateTimeField( 'start_time', validators=[DataRequired()], default= datetime.now() )
29.813333
140
0.576327
79570bc2e433bbaf1287b4c23efd053db9945688
7,246
py
Python
lib/setuptools-0.6c11/setuptools/command/build_py.py
MiCHiLU/google_appengine_sdk
3da9f20d7e65e26c4938d2c4054bc4f39cbc5522
[ "Apache-2.0" ]
790
2015-01-03T02:13:39.000Z
2020-05-10T19:53:57.000Z
AppServer/lib/setuptools-0.6c11/setuptools/command/build_py.py
nlake44/appscale
6944af660ca4cb772c9b6c2332ab28e5ef4d849f
[ "Apache-2.0" ]
1,361
2015-01-08T23:09:40.000Z
2020-04-14T00:03:04.000Z
AppServer/lib/setuptools-0.6c11/setuptools/command/build_py.py
nlake44/appscale
6944af660ca4cb772c9b6c2332ab28e5ef4d849f
[ "Apache-2.0" ]
155
2015-01-08T22:59:31.000Z
2020-04-08T08:01:53.000Z
import os.path, sys, fnmatch from distutils.command.build_py import build_py as _build_py from distutils.util import convert_path from glob import glob class build_py(_build_py): """Enhanced 'build_py' command that includes data files with packages The data files are specified via a 'package_data' argument to 'setup()'. See 'setuptools.dist.Distribution' for more details. Also, this version of the 'build_py' command allows you to specify both 'py_modules' and 'packages' in the same setup operation. """ def finalize_options(self): _build_py.finalize_options(self) self.package_data = self.distribution.package_data self.exclude_package_data = self.distribution.exclude_package_data or {} if 'data_files' in self.__dict__: del self.__dict__['data_files'] def run(self): """Build modules, packages, and copy data files to build directory""" if not self.py_modules and not self.packages: return if self.py_modules: self.build_modules() if self.packages: self.build_packages() self.build_package_data() # Only compile actual .py files, using our base class' idea of what our # output files are. self.byte_compile(_build_py.get_outputs(self, include_bytecode=0)) def __getattr__(self,attr): if attr=='data_files': # lazily compute data files self.data_files = files = self._get_data_files(); return files return _build_py.__getattr__(self,attr) def _get_data_files(self): """Generate list of '(package,src_dir,build_dir,filenames)' tuples""" self.analyze_manifest() data = [] for package in self.packages or (): # Locate package source directory src_dir = self.get_package_dir(package) # Compute package build directory build_dir = os.path.join(*([self.build_lib] + package.split('.'))) # Length of path to strip from found files plen = len(src_dir)+1 # Strip directory from globbed filenames filenames = [ file[plen:] for file in self.find_data_files(package, src_dir) ] data.append( (package, src_dir, build_dir, filenames) ) return data def find_data_files(self, package, src_dir): """Return filenames for package's data files in 'src_dir'""" globs = (self.package_data.get('', []) + self.package_data.get(package, [])) files = self.manifest_files.get(package, [])[:] for pattern in globs: # Each pattern has to be converted to a platform-specific path files.extend(glob(os.path.join(src_dir, convert_path(pattern)))) return self.exclude_data_files(package, src_dir, files) def build_package_data(self): """Copy data files into build directory""" lastdir = None for package, src_dir, build_dir, filenames in self.data_files: for filename in filenames: target = os.path.join(build_dir, filename) self.mkpath(os.path.dirname(target)) self.copy_file(os.path.join(src_dir, filename), target) def analyze_manifest(self): self.manifest_files = mf = {} if not self.distribution.include_package_data: return src_dirs = {} for package in self.packages or (): # Locate package source directory src_dirs[assert_relative(self.get_package_dir(package))] = package self.run_command('egg_info') ei_cmd = self.get_finalized_command('egg_info') for path in ei_cmd.filelist.files: d,f = os.path.split(assert_relative(path)) prev = None oldf = f while d and d!=prev and d not in src_dirs: prev = d d, df = os.path.split(d) f = os.path.join(df, f) if d in src_dirs: if path.endswith('.py') and f==oldf: continue # it's a module, not data mf.setdefault(src_dirs[d],[]).append(path) def get_data_files(self): pass # kludge 2.4 for lazy computation if sys.version<"2.4": # Python 2.4 already has this code def get_outputs(self, include_bytecode=1): """Return complete list of files copied to the build directory This includes both '.py' files and data files, as well as '.pyc' and '.pyo' files if 'include_bytecode' is true. (This method is needed for the 'install_lib' command to do its job properly, and to generate a correct installation manifest.) """ return _build_py.get_outputs(self, include_bytecode) + [ os.path.join(build_dir, filename) for package, src_dir, build_dir,filenames in self.data_files for filename in filenames ] def check_package(self, package, package_dir): """Check namespace packages' __init__ for declare_namespace""" try: return self.packages_checked[package] except KeyError: pass init_py = _build_py.check_package(self, package, package_dir) self.packages_checked[package] = init_py if not init_py or not self.distribution.namespace_packages: return init_py for pkg in self.distribution.namespace_packages: if pkg==package or pkg.startswith(package+'.'): break else: return init_py f = open(init_py,'rU') if 'declare_namespace' not in f.read(): from distutils import log log.warn( "WARNING: %s is a namespace package, but its __init__.py does\n" "not declare_namespace(); setuptools 0.7 will REQUIRE this!\n" '(See the setuptools manual under "Namespace Packages" for ' "details.)\n", package ) f.close() return init_py def initialize_options(self): self.packages_checked={} _build_py.initialize_options(self) def exclude_data_files(self, package, src_dir, files): """Filter filenames for package's data files in 'src_dir'""" globs = (self.exclude_package_data.get('', []) + self.exclude_package_data.get(package, [])) bad = [] for pattern in globs: bad.extend( fnmatch.filter( files, os.path.join(src_dir, convert_path(pattern)) ) ) bad = dict.fromkeys(bad) seen = {} return [ f for f in files if f not in bad and f not in seen and seen.setdefault(f,1) # ditch dupes ] def assert_relative(path): if not os.path.isabs(path): return path from distutils.errors import DistutilsSetupError raise DistutilsSetupError( """Error: setup script specifies an absolute path: %s setup() arguments must *always* be /-separated paths relative to the setup.py directory, *never* absolute paths. """ % path )
35.174757
80
0.606956
79570c77e7e9ce9a79754dd08641160241729387
1,444
py
Python
main/models.py
PhobosXIII/qc
a025e25f9d3fddad1565819010362eb8672c0fa9
[ "Apache-2.0" ]
null
null
null
main/models.py
PhobosXIII/qc
a025e25f9d3fddad1565819010362eb8672c0fa9
[ "Apache-2.0" ]
null
null
null
main/models.py
PhobosXIII/qc
a025e25f9d3fddad1565819010362eb8672c0fa9
[ "Apache-2.0" ]
null
null
null
from ckeditor.fields import RichTextField from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models class News(models.Model): title = models.CharField('заголовок', max_length=255) text = RichTextField('текст новости') is_published = models.BooleanField('опубликована', default=False) published_date = models.DateTimeField('дата публикации', blank=True, null=True) class Meta: verbose_name = 'новость' verbose_name_plural = 'новости' ordering = ['-published_date'] def __str__(self): return self.title class HelpCategory(models.Model): title = models.CharField('заголовок', max_length=255) order_number = models.PositiveSmallIntegerField('номер', validators=[MinValueValidator(1), MaxValueValidator(99)]) class Meta: verbose_name = 'категория помощи' verbose_name_plural = 'категории помощи' ordering = ['order_number'] def __str__(self): return self.title class Faq(models.Model): category = models.ForeignKey(HelpCategory, verbose_name='категория') question = models.CharField('вопрос', max_length=255) answer = RichTextField('ответ') class Meta: verbose_name = 'вопрос-ответ' verbose_name_plural = 'вопросы-ответы' ordering = ['question'] def __str__(self): return self.question
30.723404
109
0.676593
79570cf0ea624170568cc1004eef343cc2c97d78
1,241
py
Python
Python/Searching/2/binary_search.py
Tikam02/Data_Structure_Algorithms
7c17f744975a72fa42f0f3f892c0b7e041cdef0c
[ "MIT" ]
5
2017-08-03T06:33:49.000Z
2021-08-06T13:20:57.000Z
Python/Searching/2/binary_search.py
Tikam02/Data_Structure_Algorithms
7c17f744975a72fa42f0f3f892c0b7e041cdef0c
[ "MIT" ]
null
null
null
Python/Searching/2/binary_search.py
Tikam02/Data_Structure_Algorithms
7c17f744975a72fa42f0f3f892c0b7e041cdef0c
[ "MIT" ]
6
2017-04-27T13:30:49.000Z
2020-11-01T20:28:55.000Z
#!/usr/bin/env python __author__ = "bt3" def binary_search(array, item, hi=None, lo=0): ''' >>> binary_search([2,3,5,6,8,10,15,23], 15) 6 >>> binary_search([2,3,5,6,8,10,15,23], 4) False >>> binary_search([1,3,4,5,7,8 ,10,12,23], 10) 6 >>> binary_search([1,3,4,5,7,8 ,10,12,23], 22) False ''' hi = hi or len(array) if hi < lo: return False mid = (hi + lo)//2 if item == array[mid]: return mid elif item < array[mid]: return binary_search(array, item, hi=mid-1, lo=lo) else: return binary_search(array, item, hi=hi, lo=mid+1) def binary_search_iter(array, item): ''' >>> binary_search_iter([2,3,5,6,8,10,15,23], 15) 6 >>> binary_search_iter([2,3,5,6,8,10,15,23], 4) False >>> binary_search_iter([1,3,4,5,7,8 ,10,12,23], 10) 6 >>> binary_search_iter([1,3,4,5,7,8 ,10,12,23], 22) False ''' lo, hi = 0, len(array) while lo < hi: mid = (hi+lo)//2 if array[mid] == item: return mid elif array[mid] > item: hi = mid else: lo=mid+1 return False if __name__ == '__main__': import doctest doctest.testmod()
18.522388
58
0.518936
79570d5048023e009e26bdaaf5034d152b38219e
12,332
py
Python
frappe/core/doctype/data_export/exporter.py
arslangzr/frappe
4ff86e1d63cd6887d0b90d8fbf6be284ff6ec21b
[ "MIT" ]
1
2021-12-11T04:06:44.000Z
2021-12-11T04:06:44.000Z
frappe/core/doctype/data_export/exporter.py
cpdeethree/frappe
fe4a317861a5fd7cc0a4489285c22c9af1ce0167
[ "MIT" ]
1
2021-10-01T13:08:45.000Z
2021-10-01T13:08:45.000Z
frappe/core/doctype/data_export/exporter.py
cpdeethree/frappe
fe4a317861a5fd7cc0a4489285c22c9af1ce0167
[ "MIT" ]
1
2019-07-05T09:02:16.000Z
2019-07-05T09:02:16.000Z
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe from frappe import _ import frappe.permissions import re, csv, os from frappe.utils.csvutils import UnicodeWriter from frappe.utils import cstr, formatdate, format_datetime, parse_json, cint, format_duration from frappe.core.doctype.access_log.access_log import make_access_log reflags = { "I":re.I, "L":re.L, "M":re.M, "U":re.U, "S":re.S, "X":re.X, "D": re.DEBUG } def get_data_keys(): return frappe._dict({ "data_separator": _('Start entering data below this line'), "main_table": _("Table") + ":", "parent_table": _("Parent Table") + ":", "columns": _("Column Name") + ":", "doctype": _("DocType") + ":" }) @frappe.whitelist() def export_data(doctype=None, parent_doctype=None, all_doctypes=True, with_data=False, select_columns=None, file_type='CSV', template=False, filters=None): _doctype = doctype if isinstance(_doctype, list): _doctype = _doctype[0] make_access_log(doctype=_doctype, file_type=file_type, columns=select_columns, filters=filters, method=parent_doctype) exporter = DataExporter(doctype=doctype, parent_doctype=parent_doctype, all_doctypes=all_doctypes, with_data=with_data, select_columns=select_columns, file_type=file_type, template=template, filters=filters) exporter.build_response() class DataExporter: def __init__(self, doctype=None, parent_doctype=None, all_doctypes=True, with_data=False, select_columns=None, file_type='CSV', template=False, filters=None): self.doctype = doctype self.parent_doctype = parent_doctype self.all_doctypes = all_doctypes self.with_data = cint(with_data) self.select_columns = select_columns self.file_type = file_type self.template = template self.filters = filters self.data_keys = get_data_keys() self.prepare_args() def prepare_args(self): if self.select_columns: self.select_columns = parse_json(self.select_columns) if self.filters: self.filters = parse_json(self.filters) self.docs_to_export = {} if self.doctype: if isinstance(self.doctype, str): self.doctype = [self.doctype] if len(self.doctype) > 1: self.docs_to_export = self.doctype[1] self.doctype = self.doctype[0] if not self.parent_doctype: self.parent_doctype = self.doctype self.column_start_end = {} if self.all_doctypes: self.child_doctypes = [] for df in frappe.get_meta(self.doctype).get_table_fields(): self.child_doctypes.append(dict(doctype=df.options, parentfield=df.fieldname)) def build_response(self): self.writer = UnicodeWriter() self.name_field = 'parent' if self.parent_doctype != self.doctype else 'name' if self.template: self.add_main_header() self.writer.writerow(['']) self.tablerow = [self.data_keys.doctype] self.labelrow = [_("Column Labels:")] self.fieldrow = [self.data_keys.columns] self.mandatoryrow = [_("Mandatory:")] self.typerow = [_('Type:')] self.inforow = [_('Info:')] self.columns = [] self.build_field_columns(self.doctype) if self.all_doctypes: for d in self.child_doctypes: self.append_empty_field_column() if (self.select_columns and self.select_columns.get(d['doctype'], None)) or not self.select_columns: # if atleast one column is selected for this doctype self.build_field_columns(d['doctype'], d['parentfield']) self.add_field_headings() self.add_data() if self.with_data and not self.data: frappe.respond_as_web_page(_('No Data'), _('There is no data to be exported'), indicator_color='orange') if self.file_type == 'Excel': self.build_response_as_excel() else: # write out response as a type csv frappe.response['result'] = cstr(self.writer.getvalue()) frappe.response['type'] = 'csv' frappe.response['doctype'] = self.doctype def add_main_header(self): self.writer.writerow([_('Data Import Template')]) self.writer.writerow([self.data_keys.main_table, self.doctype]) if self.parent_doctype != self.doctype: self.writer.writerow([self.data_keys.parent_table, self.parent_doctype]) else: self.writer.writerow(['']) self.writer.writerow(['']) self.writer.writerow([_('Notes:')]) self.writer.writerow([_('Please do not change the template headings.')]) self.writer.writerow([_('First data column must be blank.')]) self.writer.writerow([_('If you are uploading new records, leave the "name" (ID) column blank.')]) self.writer.writerow([_('If you are uploading new records, "Naming Series" becomes mandatory, if present.')]) self.writer.writerow([_('Only mandatory fields are necessary for new records. You can delete non-mandatory columns if you wish.')]) self.writer.writerow([_('For updating, you can update only selective columns.')]) self.writer.writerow([_('You can only upload upto 5000 records in one go. (may be less in some cases)')]) if self.name_field == "parent": self.writer.writerow([_('"Parent" signifies the parent table in which this row must be added')]) self.writer.writerow([_('If you are updating, please select "Overwrite" else existing rows will not be deleted.')]) def build_field_columns(self, dt, parentfield=None): meta = frappe.get_meta(dt) # build list of valid docfields tablecolumns = [] table_name = 'tab' + dt for f in frappe.db.get_table_columns_description(table_name): field = meta.get_field(f.name) if field and ((self.select_columns and f.name in self.select_columns[dt]) or not self.select_columns): tablecolumns.append(field) tablecolumns.sort(key = lambda a: int(a.idx)) _column_start_end = frappe._dict(start=0) if dt==self.doctype: if (meta.get('autoname') and meta.get('autoname').lower()=='prompt') or (self.with_data): self._append_name_column() # if importing only child table for new record, add parent field if meta.get('istable') and not self.with_data: self.append_field_column(frappe._dict({ "fieldname": "parent", "parent": "", "label": "Parent", "fieldtype": "Data", "reqd": 1, "info": _("Parent is the name of the document to which the data will get added to.") }), True) _column_start_end = frappe._dict(start=0) else: _column_start_end = frappe._dict(start=len(self.columns)) if self.with_data: self._append_name_column(dt) for docfield in tablecolumns: self.append_field_column(docfield, True) # all non mandatory fields for docfield in tablecolumns: self.append_field_column(docfield, False) # if there is one column, add a blank column (?) if len(self.columns)-_column_start_end.start == 1: self.append_empty_field_column() # append DocType name self.tablerow[_column_start_end.start + 1] = dt if parentfield: self.tablerow[_column_start_end.start + 2] = parentfield _column_start_end.end = len(self.columns) + 1 self.column_start_end[(dt, parentfield)] = _column_start_end def append_field_column(self, docfield, for_mandatory): if not docfield: return if for_mandatory and not docfield.reqd: return if not for_mandatory and docfield.reqd: return if docfield.fieldname in ('parenttype', 'trash_reason'): return if docfield.hidden: return if self.select_columns and docfield.fieldname not in self.select_columns.get(docfield.parent, []) \ and docfield.fieldname!="name": return self.tablerow.append("") self.fieldrow.append(docfield.fieldname) self.labelrow.append(_(docfield.label)) self.mandatoryrow.append(docfield.reqd and 'Yes' or 'No') self.typerow.append(docfield.fieldtype) self.inforow.append(self.getinforow(docfield)) self.columns.append(docfield.fieldname) def append_empty_field_column(self): self.tablerow.append("~") self.fieldrow.append("~") self.labelrow.append("") self.mandatoryrow.append("") self.typerow.append("") self.inforow.append("") self.columns.append("") @staticmethod def getinforow(docfield): """make info comment for options, links etc.""" if docfield.fieldtype == 'Select': if not docfield.options: return '' else: return _("One of") + ': %s' % ', '.join(filter(None, docfield.options.split('\n'))) elif docfield.fieldtype == 'Link': return 'Valid %s' % docfield.options elif docfield.fieldtype == 'Int': return 'Integer' elif docfield.fieldtype == "Check": return "0 or 1" elif docfield.fieldtype in ["Date", "Datetime"]: return cstr(frappe.defaults.get_defaults().date_format) elif hasattr(docfield, "info"): return docfield.info else: return '' def add_field_headings(self): self.writer.writerow(self.tablerow) self.writer.writerow(self.labelrow) self.writer.writerow(self.fieldrow) self.writer.writerow(self.mandatoryrow) self.writer.writerow(self.typerow) self.writer.writerow(self.inforow) if self.template: self.writer.writerow([self.data_keys.data_separator]) def add_data(self): from frappe.query_builder import DocType if self.template and not self.with_data: return frappe.permissions.can_export(self.parent_doctype, raise_exception=True) # sort nested set doctypes by `lft asc` order_by = None table_columns = frappe.db.get_table_columns(self.parent_doctype) if 'lft' in table_columns and 'rgt' in table_columns: order_by = '`tab{doctype}`.`lft` asc'.format(doctype=self.parent_doctype) # get permitted data only self.data = frappe.get_list(self.doctype, fields=["*"], filters=self.filters, limit_page_length=None, order_by=order_by) for doc in self.data: op = self.docs_to_export.get("op") names = self.docs_to_export.get("name") if names and op: if op == '=' and doc.name not in names: continue elif op == '!=' and doc.name in names: continue elif names: try: sflags = self.docs_to_export.get("flags", "I,U").upper() flags = 0 for a in re.split(r'\W+', sflags): flags = flags | reflags.get(a,0) c = re.compile(names, flags) m = c.match(doc.name) if not m: continue except Exception: if doc.name not in names: continue # add main table rows = [] self.add_data_row(rows, self.doctype, None, doc, 0) if self.all_doctypes: # add child tables for c in self.child_doctypes: child_doctype_table = DocType(c["doctype"]) data_row = ( frappe.qb.from_(child_doctype_table) .select("*") .where(child_doctype_table.parent == doc.name) .where(child_doctype_table.parentfield == c["parentfield"]) .orderby(child_doctype_table.idx) ) for ci, child in enumerate(data_row.run(as_dict=True)): self.add_data_row(rows, c['doctype'], c['parentfield'], child, ci) for row in rows: self.writer.writerow(row) def add_data_row(self, rows, dt, parentfield, doc, rowidx): d = doc.copy() meta = frappe.get_meta(dt) if self.all_doctypes: d.name = '"'+ d.name+'"' if len(rows) < rowidx + 1: rows.append([""] * (len(self.columns) + 1)) row = rows[rowidx] _column_start_end = self.column_start_end.get((dt, parentfield)) if _column_start_end: for i, c in enumerate(self.columns[_column_start_end.start:_column_start_end.end]): df = meta.get_field(c) fieldtype = df.fieldtype if df else "Data" value = d.get(c, "") if value: if fieldtype == "Date": value = formatdate(value) elif fieldtype == "Datetime": value = format_datetime(value) elif fieldtype == "Duration": value = format_duration(value, df.hide_days) row[_column_start_end.start + i + 1] = value def build_response_as_excel(self): filename = frappe.generate_hash("", 10) with open(filename, 'wb') as f: f.write(cstr(self.writer.getvalue()).encode('utf-8')) f = open(filename) reader = csv.reader(f) from frappe.utils.xlsxutils import make_xlsx xlsx_file = make_xlsx(reader, "Data Import Template" if self.template else 'Data Export') f.close() os.remove(filename) # write out response as a xlsx type frappe.response['filename'] = self.doctype + '.xlsx' frappe.response['filecontent'] = xlsx_file.getvalue() frappe.response['type'] = 'binary' def _append_name_column(self, dt=None): self.append_field_column(frappe._dict({ "fieldname": "name" if dt else self.name_field, "parent": dt or "", "label": "ID", "fieldtype": "Data", "reqd": 1, }), True)
32.797872
133
0.70686
79570f496dc5985e26cf5a114b506619d8b87fac
66,649
py
Python
tests/e2e/advanced/spatial_consistency/wpa2_personal/test_bridge_spatial.py
dutta-rohan/wlan-testing
77264245b62e21dff5f38c7eae74c22e0cdeefbb
[ "BSD-3-Clause" ]
7
2020-08-19T16:45:46.000Z
2022-02-10T09:55:22.000Z
tests/e2e/advanced/spatial_consistency/wpa2_personal/test_bridge_spatial.py
dutta-rohan/wlan-testing
77264245b62e21dff5f38c7eae74c22e0cdeefbb
[ "BSD-3-Clause" ]
47
2020-12-20T16:06:03.000Z
2022-03-23T03:01:22.000Z
tests/e2e/advanced/spatial_consistency/wpa2_personal/test_bridge_spatial.py
dutta-rohan/wlan-testing
77264245b62e21dff5f38c7eae74c22e0cdeefbb
[ "BSD-3-Clause" ]
9
2021-02-04T22:32:06.000Z
2021-12-14T17:45:51.000Z
import pytest import allure import os import time import pandas as pd pytestmark = [pytest.mark.advance, pytest.mark.spatial_consistency, pytest.mark.bridge] setup_params_general = { "mode": "BRIDGE", "ssid_modes": { "wpa2_personal": [ {"ssid_name": "ssid_wpa2_2g", "appliedRadios": ["2G"], "security_key": "something"}, {"ssid_name": "ssid_wpa2_5g", "appliedRadios": ["5G"], "security_key": "something"} ] }, "rf": {}, "radius": False } @pytest.mark.parametrize( 'setup_profiles', [setup_params_general], indirect=True, scope="class" ) @pytest.mark.usefixtures("setup_profiles") class Test_SpatialConsistency_Bridge(object): @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5052", name="WIFI-5052") @pytest.mark.wpa2_personal @pytest.mark.twog @pytest.mark.nss1 def test_nss1_wpa2_personal_2g_10db_0degree(self, setup_profiles, lf_tools, lf_test, station_names_twog, create_lanforge_chamberview_dut, get_configuration ): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][0] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "twog" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_twog, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 1'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'],['attenuations2: 100'],['chamber: DUT-Chamber'], ['tt_deg: 0']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_twog, mode=mode, instance_name="SPATIAL_NSS1_RVR1", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_twog) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(60): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else : print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5070", name="WIFI-5070") @pytest.mark.wpa2_personal @pytest.mark.twog @pytest.mark.nss2 def test_nss2_wpa2_personal_2g_10db_0degree(self, setup_profiles, lf_tools, lf_test, station_names_twog, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][0] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "twog" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_twog, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 2'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 0']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_twog, mode=mode, instance_name="SPATIAL_NSS2_RVR1", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_twog) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(90): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5069", name="WIFI-5069") @pytest.mark.wpa2_personal @pytest.mark.twog @pytest.mark.degree60 def test_nss1_wpa2_personal_2g_10db_60degree(self, setup_profiles, lf_tools, lf_test, station_names_twog, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][0] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "twog" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_twog, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 1'],['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 60']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_twog, mode=mode, instance_name="SPATIAL_NSS1_RVR1_Degree60", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_twog) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(45): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5068", name="WIFI-5068") @pytest.mark.wpa2_personal @pytest.mark.twog @pytest.mark.degree60_nss2 def test_nss2_wpa2_personal_2g_10db_60degree(self, setup_profiles, lf_tools, lf_test, station_names_twog, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][0] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "twog" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_twog, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 2'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 60']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_twog, mode=mode, instance_name="SPATIAL_NSS2_RVR1_Degree60", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_twog) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(90): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5057", name="WIFI-5057") @pytest.mark.wpa2_personal @pytest.mark.fiveg @pytest.mark.degree240_nss1 def test_nss1_wpa2_personal_5g_10db_240degree(self, setup_profiles, lf_tools, lf_test, station_names_fiveg, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][1] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "fiveg" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_fiveg, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 1'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 240']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_fiveg, mode=mode, instance_name="SPATIAL_NSS1_RVR1_Degree240_fiveg", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_fiveg) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(250): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5066", name="WIFI-5066") @pytest.mark.wpa2_personal @pytest.mark.fiveg @pytest.mark.degree0_nss2_10db def test_nss2_wpa2_personal_5g_10db_0degree(self, setup_profiles, lf_tools, lf_test, station_names_fiveg, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][1] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "fiveg" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_fiveg, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 2'],['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 0']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_fiveg, mode=mode, instance_name="SPATIAL_NSS2_RVR1_Degree0_fiveg", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_fiveg) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(500): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5065", name="WIFI-5065") @pytest.mark.wpa2_personal @pytest.mark.fiveg @pytest.mark.degree60_nss1_10db def test_nss1_wpa2_personal_5g_10db_60degree(self, setup_profiles, lf_tools, lf_test, station_names_fiveg, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][1] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "fiveg" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_fiveg, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 1'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 60']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_fiveg, mode=mode, instance_name="SPATIAL_NSS1_RVR1_Degree60_fiveg", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_fiveg) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(250): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5064", name="WIFI-5064") @pytest.mark.wpa2_personal @pytest.mark.fiveg @pytest.mark.degree60_nss2_10db def test_nss2_wpa2_personal_5g_10db_60degree(self, setup_profiles, lf_tools, lf_test, station_names_fiveg, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][1] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "fiveg" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_fiveg, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 2'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 60']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_fiveg, mode=mode, instance_name="SPATIAL_NSS2_RVR1_Degree60_fiveg_10db", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_fiveg) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(500): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5063", name="WIFI-5063") @pytest.mark.wpa2_personal @pytest.mark.twog @pytest.mark.degree120_nss1_10db def test_nss1_wpa2_personal_2g_10db_120degree(self, setup_profiles, lf_tools, lf_test, station_names_twog, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][0] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "twog" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_twog, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 1'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 120']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_twog, mode=mode, instance_name="SPATIAL_NSS1_RVR1_Degree120_twog_10db", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_twog) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(45): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5062", name="WIFI-5062") @pytest.mark.wpa2_personal @pytest.mark.twog @pytest.mark.degree120_nss2_10db def test_nss2_wpa2_personal_2g_10db_120degree(self, setup_profiles, lf_tools, lf_test, station_names_twog, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][0] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "twog" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_twog, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 2'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 120']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_twog, mode=mode, instance_name="SPATIAL_NSS2_RVR1_Degree120_twog_10db", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_twog) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(90): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5061", name="WIFI-5061") @pytest.mark.wpa2_personal @pytest.mark.twog @pytest.mark.degree240_nss1_10db def test_nss1_wpa2_personal_2g_10db_240degree(self, setup_profiles, lf_tools, lf_test, station_names_twog, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][0] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "twog" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_twog, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 1'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 240']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_twog, mode=mode, instance_name="SPATIAL_NSS1_RVR1_Degree240_twog_10db", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_twog) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(45): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5060", name="WIFI-5060") @pytest.mark.wpa2_personal @pytest.mark.twog @pytest.mark.degree240_nss2_10db def test_nss1_wpa2_personal_2g_10db_240degree(self, setup_profiles, lf_tools, lf_test, station_names_twog, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][0] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "twog" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_twog, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 2'],['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 240']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_twog, mode=mode, instance_name="SPATIAL_NSS2_RVR1_Degree240_twog_10db", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_twog) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(90): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5059", name="WIFI-5059") @pytest.mark.wpa2_personal @pytest.mark.fiveg @pytest.mark.degree120_nss1_10db def test_nss1_wpa2_personal_5g_10db_120degree(self, setup_profiles, lf_tools, lf_test, station_names_fiveg, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][1] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "fiveg" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_fiveg, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 1'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 120']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_fiveg, mode=mode, instance_name="SPATIAL_NSS1_RVR1_Degree120_fiveg_10db", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range ") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_fiveg) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(250): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5058", name="WIFI-5058") @pytest.mark.wpa2_personal @pytest.mark.fiveg @pytest.mark.degree120_nss2_10db def test_nss2_wpa2_personal_5g_10db_120degree(self, setup_profiles, lf_tools, lf_test, station_names_fiveg, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][1] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "fiveg" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_fiveg, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 2'],['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 120']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_fiveg, mode=mode, instance_name="SPATIAL_NSS2_RVR1_Degree120_fiveg_10db", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range ") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_fiveg) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(500): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5056", name="WIFI-5056") @pytest.mark.wpa2_personal @pytest.mark.fiveg @pytest.mark.degree240_nss2_10db def test_nss2_wpa2_personal_5g_10db_240degree(self, setup_profiles, lf_tools, lf_test, station_names_fiveg, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][1] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "fiveg" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_fiveg, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 2'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 240']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_fiveg, mode=mode, instance_name="SPATIAL_NSS2_RVR1_Degree240_fiveg_10db", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range ") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_fiveg) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(500): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5055", name="WIFI-5055") @pytest.mark.wpa2_personal @pytest.mark.twog @pytest.mark.degree300_nss1_10db def test_nss1_wpa2_personal_2g_10db_300degree(self, setup_profiles, lf_tools, lf_test, station_names_twog, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][0] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "twog" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_twog, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 1'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 300']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_twog, mode=mode, instance_name="SPATIAL_NSS1_RVR1_Degree300_twog_10db", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_twog) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(45): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5055", name="WIFI-5055") @pytest.mark.wpa2_personal @pytest.mark.twog @pytest.mark.degree300_nss1_10db def test_nss1_wpa2_personal_2g_10db_300degree(self, setup_profiles, lf_tools, lf_test, station_names_twog, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][0] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "twog" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_twog, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 1'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 300']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_twog, mode=mode, instance_name="SPATIAL_NSS1_RVR1_Degree300_twog_10db", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range Test - UDP 2.4G") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_twog) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(45): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5020", name="WIFI-5020") @pytest.mark.wpa2_personal @pytest.mark.fiveg @pytest.mark.degree300_nss1_10db def test_nss1_wpa2_personal_5g_10db_300degree(self, setup_profiles, lf_tools, lf_test, station_names_fiveg, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][1] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "fiveg" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_fiveg, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 1'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 300']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_fiveg, mode=mode, instance_name="SPATIAL_NSS1_RVR1_Degree300_fiveg_10db", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range ") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_fiveg) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(250): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False @allure.testcase(url="https://telecominfraproject.atlassian.net/browse/WIFI-5019", name="WIFI-5019") @pytest.mark.wpa2_personal @pytest.mark.fiveg @pytest.mark.degree300_nss2_10db def test_nss2_wpa2_personal_5g_10db_300degree(self, setup_profiles, lf_tools, lf_test, station_names_fiveg, create_lanforge_chamberview_dut, get_configuration): profile_data = setup_params_general["ssid_modes"]["wpa2_personal"][1] ssid_name = profile_data["ssid_name"] security_key = profile_data["security_key"] security = "wpa2" mode = "BRIDGE" band = "fiveg" vlan = 1 dut_name = create_lanforge_chamberview_dut station = lf_test.Client_Connect(ssid=ssid_name, security=security, passkey=security_key, mode=mode, band=band, station_name=station_names_fiveg, vlan_id=vlan) print("station", station) ser_no = lf_test.attenuator_serial() print(ser_no) val = [['modes: Auto'], ['pkts: MTU'], ['directions: DUT Transmit'], ['traffic_types:UDP'], ['bandw_options: AUTO'], ['spatial_streams: 2'], ['attenuator: ' + str(ser_no[0])], ['attenuator2: ' + str(ser_no[1])], ['attenuations: 100'], ['attenuations2: 100'], ['chamber: DUT-Chamber'], ['tt_deg: 300']] if station: time.sleep(3) rvr_o = lf_test.ratevsrange(station_name=station_names_fiveg, mode=mode, instance_name="SPATIAL_NSS2_RVR1_Degree300_fiveg_10db", vlan_id=vlan, dut_name=dut_name, raw_lines=val) report_name = rvr_o.report_name[0]['LAST']["response"].split(":::")[1].split("/")[-1] print("report name ", report_name) entries = os.listdir("../reports/" + report_name + '/') print("entries", entries) lf_tools.attach_report_graphs(report_name=report_name, pdf_name="Rate vs Range ") kpi = False for i in entries: if "kpi.csv" in i: kpi = i if kpi: allure.attach.file(source="../reports/" + report_name + "/" + kpi, name="kpi.csv") print("Test Completed... Cleaning up Stations") lf_test.Client_disconnect(station_name=station_names_fiveg) kpi_val = lf_tools.read_kpi_file(column_name=["numeric-score"], dir_name=report_name) print(type(kpi_val)) print(kpi_val) print(str(kpi_val[0])[1:-1]) if str(kpi_val) == "empty": print("kpi is empty, station did not got ip, Test failed") allure.attach(name="Kpi Data", body="station did not got ip Test failed.") assert False else: if float(str(kpi_val[0])[1:-1]) > float(500): print("Test passed successfully") allure.attach(name="Kpi Data", body=str(kpi_val)) assert True else: print(" valueTest faled due to lesser") allure.attach(name="Kpi Data", body=str(kpi_val)) assert False else: print("test failed due to no station ip") assert False
51.786325
162
0.547135
79570f53e45e8f4ce74b78e944be4e9b3e2e9a2e
506
py
Python
parse_scanners.py
RyPeck/Remote-VA-Scanners
2643c07dcad01d4b8e013d01f2bd3d154646eedf
[ "MIT" ]
null
null
null
parse_scanners.py
RyPeck/Remote-VA-Scanners
2643c07dcad01d4b8e013d01f2bd3d154646eedf
[ "MIT" ]
null
null
null
parse_scanners.py
RyPeck/Remote-VA-Scanners
2643c07dcad01d4b8e013d01f2bd3d154646eedf
[ "MIT" ]
1
2018-03-06T23:55:02.000Z
2018-03-06T23:55:02.000Z
#!/usr/bin/env python3 import csv import ipaddress scanners = [] with open("scanners.csv") as f: scan_reader = csv.DictReader(f) scanners = list(scan_reader) # Verify that we have a list of valid IP Addresses/CIDRs for line in scanners: ip_object = ipaddress.IPv4Network(line['cidr']) line['ip_object'] = ip_object # Print CIDR List of IP's for line in scanners: print(line['ip_object']) # Comma separated single line list print(','.join([str(l['ip_object']) for l in scanners]))
22
56
0.701581
7957106f5e8375adc0200c2c1e859cbf1b23b17b
3,901
py
Python
dexp/processing/filters/kernels/wiener_butterworth.py
haesleinhuepf/dexp
2ea84f3db323724588fac565fae56f0d522bc5ca
[ "BSD-3-Clause" ]
16
2021-04-21T14:09:19.000Z
2022-03-22T02:30:59.000Z
dexp/processing/filters/kernels/wiener_butterworth.py
haesleinhuepf/dexp
2ea84f3db323724588fac565fae56f0d522bc5ca
[ "BSD-3-Clause" ]
28
2021-04-15T17:43:08.000Z
2022-03-29T16:08:35.000Z
dexp/processing/filters/kernels/wiener_butterworth.py
haesleinhuepf/dexp
2ea84f3db323724588fac565fae56f0d522bc5ca
[ "BSD-3-Clause" ]
3
2022-02-08T17:41:30.000Z
2022-03-18T15:32:27.000Z
import math from typing import Tuple, Union from dexp.processing.filters.butterworth_filter import butterworth_kernel from dexp.processing.filters.kernels.wiener import wiener_kernel from dexp.utils.backends import Backend def wiener_butterworth_kernel( kernel, alpha: float = 1e-3, beta: float = 1e-1, cutoffs: Union[float, Tuple[float, ...], None] = None, cutoffs_in_freq_units=False, auto_cutoff_threshold=0.1, order: int = 5, dtype=None, ): """ Computes the Wiener-Butterworth back projector according to Guo et al, bioRxiv 2019. Parameters ---------- kernel : psf alpha : alpha beta : beta cutoffs : Butterworth cutoffs. cutoffs_in_freq_units : If True, the cutoffs are specified in frequency units. If False, the units are in normalised within [0,1] order : Butterworth order dtype : dtype for kernel Returns ------- Wiener-Butterworth for given psf. """ backend = Backend.current() xp = backend.get_xp_module() if dtype is None: dtype = kernel.dtype wk_f = wiener_kernel(kernel, alpha=alpha, frequency_domain=True, dtype=dtype) # TODO: figure out cutoff from PSF ? if cutoffs is None: cutoffs_in_freq_units = False psf_f = xp.log1p(xp.absolute(xp.fft.fftshift(xp.fft.fftn(kernel)))) psf_sumproj = [] for i in range(psf_f.ndim): s = psf_f.shape[i] slicing = (s // 2,) * i + (slice(None),) + (s // 2,) * (psf_f.ndim - 1 - i) psf_sumproj.append(psf_f[slicing]) psf_sumproj = tuple(p / p.max() for p in psf_sumproj) psf_sumproj = tuple(p[s // 2 :] for s, p in zip(psf_f.shape, psf_sumproj)) pass_band = tuple(p > auto_cutoff_threshold for p in psf_sumproj) cutoffs = tuple(float(xp.count_nonzero(b) / b.size) for b in pass_band) # cutoffs = (max(cutoffs),)*psf_f.ndim epsilon = math.sqrt((beta ** -2) - 1) bwk_f = butterworth_kernel( shape=kernel.shape, cutoffs=cutoffs, cutoffs_in_freq_units=cutoffs_in_freq_units, epsilon=epsilon, order=order, frequency_domain=True, dtype=dtype, ) # Weiner-Butterworth back projector wbwk_f = wk_f * bwk_f wbwk = xp.real(xp.fft.ifftn(wbwk_f)) wbwk = xp.clip(wbwk, a_min=0, a_max=None) wbwk /= wbwk.sum() # from napari import Viewer, gui_qt # with gui_qt(): # def _c(array): # return backend.to_numpy(xp.absolute(xp.fft.fftshift(array))) # # viewer = Viewer() # viewer.add_image(_c(wk_f), name='wk_f', colormap='viridis') # viewer.add_image(_c(bwk_f), name='bwk_f', colormap='viridis') # viewer.add_image(_c(wbwk_f), name='wbwk_f', colormap='viridis') # viewer.grid_view(2, 2, 1) wbwk = wbwk.astype(dtype=dtype, copy=False) return wbwk # # ### # # pfFFT = np.fft.fft2(pf) # # # Wiener-Butterworth back projector. # # # # These values are from Guo et al. # alpha = 0.001 # beta = 0.001 # n = 8 # # # # # # # Wiener filter # bWiener = pfFFT/(np.abs(pfFFT) * np.abs(pfFFT) + alpha) # # # Buttersworth filter # # kv = np.fft.fftfreq(pfFFT.shape[0]) # # kx = np.zeros((kv.size, kv.size)) # # for i in range(kv.size): # # kx[i, :] = np.copy(kv) # # ky = np.transpose(kx) # # kk = np.sqrt(kx*kx + ky*ky) # # # # This is the cut-off frequency. # # kc = 1.0/(0.5 * 2.355 * sigmaG) # # kkSqr = kk*kk/(kc*kc) # # eps = np.sqrt(1.0/(beta*beta) - 1) # # bBWorth = 1.0/np.sqrt(1.0 + eps * eps * np.power(kkSqr, n)) # # bw_kernel = butterworth_kernel(backend, # frequency_domain=True) # # # Weiner-Butterworth back projector # pbFFT = bWiener * bBWorth # # # back projector. # pb = np.real(np.fft.ifft2(pbFFT)) # # return [pf, pb]
27.666667
88
0.60241
795710d282d041513e2a4dd7864a88d957e508dd
1,409
py
Python
src/decode_number_to_letter.py
redfast00/daily-algorithm-challenge
3507164d5ec58abe68a6e820120625e100dee96c
[ "MIT" ]
null
null
null
src/decode_number_to_letter.py
redfast00/daily-algorithm-challenge
3507164d5ec58abe68a6e820120625e100dee96c
[ "MIT" ]
null
null
null
src/decode_number_to_letter.py
redfast00/daily-algorithm-challenge
3507164d5ec58abe68a6e820120625e100dee96c
[ "MIT" ]
null
null
null
def logger(function): '''Wrapper to inspect recursive functions.''' def inner(*args, **kwargs): result = function(*args, **kwargs) print(f'"{args[0]}" -> {result}') return result return inner def num_combinations(code): '''Returns the number of possible ways to decode a numberstring, where a = 1, b = 2, ..., z = 26. 111 -> aaa, ak, ka >>> num_combinations('111') 3 >>> num_combinations('121') 3 >>> num_combinations('128') 2 >>> num_combinations('1111') 5 >>> num_combinations('11111') 8 >>> num_combinations('10') 1 >>> num_combinations('101') 1 >>> num_combinations('204') 1 >>> num_combinations('110') 1 >>> num_combinations('04') 0 ''' if len(code) == 1: return 0 if code == '0' else 1 elif len(code) == 2: # max two combinations: each digit is a letter or the two digits form one letter return 0 if code[0] == '0' else ('0' not in code) + (1 <= int(code) <= 26) else: # check if last number is '0' if num_combinations(code[-1]): total = num_combinations(code[:-1]) if num_combinations(code[-2:]) == 2: total += num_combinations(code[:-2]) return total else: return num_combinations(code[-2:]) * num_combinations(code[:-2]) return total
28.18
88
0.546487
795712a5ec40591312fe1f2cefaa9445cba134d4
5,614
py
Python
local_backend/server.py
redis-developer/crowsnest
c38d59d6b332b9232f0fae9ce5abc2449d836372
[ "MIT" ]
null
null
null
local_backend/server.py
redis-developer/crowsnest
c38d59d6b332b9232f0fae9ce5abc2449d836372
[ "MIT" ]
null
null
null
local_backend/server.py
redis-developer/crowsnest
c38d59d6b332b9232f0fae9ce5abc2449d836372
[ "MIT" ]
null
null
null
# RedisEdge realtime video analytics web server import argparse import cv2 import io import numpy as np import redis from urllib.parse import urlparse from PIL import Image, ImageDraw from flask import Flask, render_template, Response, request from flask_cors import CORS, cross_origin import capture #import init import json import logging import pathlib import datetime import glob logging.basicConfig(level=logging.DEBUG) class RedisImageStream(object): def __init__(self, conn, args): self.conn = conn self.camera = args.camera self.boxes = args.boxes self.field = args.field.encode('utf-8') def get_last(self): ''' Gets latest from camera and model ''' p = self.conn.pipeline() p.xrevrange(self.camera, count=1) # Latest frame p.xrevrange(self.boxes, count=1) # Latest boxes cmsg, bmsg = p.execute() if cmsg: last_id = cmsg[0][0].decode('utf-8') label = f'{self.camera}:{last_id}' data = io.BytesIO(cmsg[0][1][self.field]) img = Image.open(data) if bmsg: boxes = np.fromstring(bmsg[0][1]['boxes'.encode('utf-8')][1:-1], sep=',') label += ' people: {}'.format(bmsg[0][1]['people'.encode('utf-8')].decode('utf-8')) for box in range(int(bmsg[0][1]['people'.encode('utf-8')])): # Draw boxes x1 = boxes[box*4] y1 = boxes[box*4+1] x2 = boxes[box*4+2] y2 = boxes[box*4+3] draw = ImageDraw.Draw(img) draw.rectangle(((x1, y1), (x2, y2)), width=5, outline='red') arr = np.array(img) arr = cv2.cvtColor(arr, cv2.COLOR_BGR2RGB) cv2.putText(arr, label, (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 1, cv2.LINE_AA) ret, img = cv2.imencode('.jpg', arr) return img.tobytes() else: with open("data/placeholder.jpg", "rb") as image: img = image.read() return img def gen(stream): while True: try: frame = stream.get_last() if frame is not None: yield (b'--frame\r\n' b'Pragma-directive: no-cache\r\n' b'Cache-directive: no-cache\r\n' b'Cache-control: no-cache\r\n' b'Pragma: no-cache\r\n' b'Expires: 0\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') except Exception as exception: # Output unexpected Exceptions. logging.error("Error occurred", exc_info=True) conn = None args = None app = Flask(__name__) CORS(app, support_credentials=True) @app.route('/video') def video_feed(): return Response(gen(RedisImageStream(conn, args)), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/settings', methods = ['POST']) @cross_origin(supports_credentials=True) def settings(): req = json.loads(request.get_data()) if not req['source'] and not req['model']: logging.error("Error occurred", exc_info=True) return 'Please enter a valid video source and/or model', 400 data = { "source": None, "model": None } if('source' in req): source = pathlib.Path(req['source']) if not source.exists(): logging.error("Error occurred", exc_info=True) return 'Please enter a valid video source', 400 data['source'] = req['source'] if('model' in req): model = pathlib.Path(req['model']) if not model.exists(): logging.error("Error occurred", exc_info=True) return 'Please enter a valid model', 400 data['model'] = req['model'] conn.publish('feed', json.dumps(data)) return json.dumps({'success':True}), 200, {'ContentType':'application/json'} @app.route('/peoplestream') @cross_origin(supports_credentials=True) def peoplestream(): people = conn.execute_command('XREVRANGE', 'camera:0:yolo', '+', '-', 'COUNT', 1) timestamp =people[0][0].decode('utf-8') numberOfPeople = people[0][1][b'people'].decode('utf-8') response = { "timestamp": timestamp, "numberOfPeople": numberOfPeople } return json.dumps(response), 200, {'ContentType':'application/json'} @app.route('/videos') @cross_origin(supports_credentials=True) def videos(): files = glob.glob("./data/*.mp4") return json.dumps(files), 200, {'ContentType':'application/json'} @app.route('/models') @cross_origin(supports_credentials=True) def models(): files = glob.glob("./models/*.pb") return json.dumps(files), 200, {'ContentType':'application/json'} if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('camera', help='Input camera stream key', nargs='?', type=str, default='camera:0') parser.add_argument('boxes', help='Input model stream key', nargs='?', type=str, default='camera:0:yolo') parser.add_argument('--field', help='Image field name', type=str, default='image') parser.add_argument('--fmt', help='Frame storage format', type=str, default='.jpg') parser.add_argument('-u', '--url', help='Redis URL', type=str, default='redis://127.0.0.1:6379') args = parser.parse_args() # Set up Redis connection url = urlparse(args.url) conn = redis.Redis(host="localhost", port="6379") if not conn.ping(): raise Exception('Redis unavailable') app.run(host='0.0.0.0')
35.987179
109
0.594585
795712c503350599b2defa4bd7f1c2e179015ac7
21,455
py
Python
tests/test_sklearn_glm_regressor_converter.py
RTHMaK/sklearn-onnx
dbbd4a04f0a395549b1e5465c5d65ceaef07a726
[ "MIT" ]
null
null
null
tests/test_sklearn_glm_regressor_converter.py
RTHMaK/sklearn-onnx
dbbd4a04f0a395549b1e5465c5d65ceaef07a726
[ "MIT" ]
null
null
null
tests/test_sklearn_glm_regressor_converter.py
RTHMaK/sklearn-onnx
dbbd4a04f0a395549b1e5465c5d65ceaef07a726
[ "MIT" ]
null
null
null
"""Tests GLMRegressor converter.""" import unittest from distutils.version import StrictVersion import numpy from sklearn import linear_model from sklearn.ensemble import GradientBoostingRegressor from sklearn.neural_network import MLPRegressor from sklearn.svm import LinearSVR from skl2onnx import convert_sklearn from skl2onnx.common.data_types import ( FloatTensorType, Int64TensorType, DoubleTensorType ) from onnxruntime import __version__ as ort_version from test_utils import dump_data_and_model, fit_regression_model class TestGLMRegressorConverter(unittest.TestCase): def test_model_linear_regression(self): model, X = fit_regression_model(linear_model.LinearRegression()) model_onnx = convert_sklearn( model, "linear regression", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnLinearRegression-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) @unittest.skipIf( StrictVersion(ort_version) <= StrictVersion("0.4.0"), reason="old onnxruntime does not support double") def test_model_linear_regression64(self): model, X = fit_regression_model(linear_model.LinearRegression()) model_onnx = convert_sklearn(model, "linear regression", [("input", DoubleTensorType(X.shape))], dtype=numpy.float64) self.assertIsNotNone(model_onnx) self.assertIn("elem_type: 11", str(model_onnx)) def test_model_linear_regression_int(self): model, X = fit_regression_model( linear_model.LinearRegression(), is_int=True) model_onnx = convert_sklearn( model, "linear regression", [("input", Int64TensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnLinearRegressionInt-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_linear_regression_nointercept(self): model, X = fit_regression_model( linear_model.LinearRegression(fit_intercept=False)) model_onnx = convert_sklearn( model, "linear regression", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnLinearRegressionNoIntercept-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_linear_svr(self): model, X = fit_regression_model(LinearSVR()) model_onnx = convert_sklearn( model, "linear SVR", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnLinearSvr-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_linear_svr_int(self): model, X = fit_regression_model(LinearSVR(), is_int=True) model_onnx = convert_sklearn( model, "linear SVR", [("input", Int64TensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnLinearSvrInt-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_ridge(self): model, X = fit_regression_model(linear_model.Ridge()) model_onnx = convert_sklearn( model, "ridge regression", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnRidge-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_ridge_int(self): model, X = fit_regression_model(linear_model.Ridge(), is_int=True) model_onnx = convert_sklearn( model, "ridge regression", [("input", Int64TensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnRidgeInt-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_sgd_regressor(self): model, X = fit_regression_model(linear_model.SGDRegressor()) model_onnx = convert_sklearn( model, "scikit-learn SGD regression", [("input", FloatTensorType([None, X.shape[1]]))], ) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnSGDRegressor-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_sgd_regressor_int(self): model, X = fit_regression_model( linear_model.SGDRegressor(), is_int=True) model_onnx = convert_sklearn( model, "SGD regression", [("input", Int64TensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnSGDRegressorInt-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_elastic_net_regressor(self): model, X = fit_regression_model(linear_model.ElasticNet()) model_onnx = convert_sklearn( model, "scikit-learn elastic-net regression", [("input", FloatTensorType([None, X.shape[1]]))], ) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnElasticNet-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_elastic_net_cv_regressor(self): model, X = fit_regression_model(linear_model.ElasticNetCV()) model_onnx = convert_sklearn( model, "scikit-learn elastic-net regression", [("input", FloatTensorType([None, X.shape[1]]))], ) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnElasticNetCV-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_elastic_net_regressor_int(self): model, X = fit_regression_model(linear_model.ElasticNet(), is_int=True) model_onnx = convert_sklearn( model, "elastic net regression", [("input", Int64TensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnElasticNetRegressorInt-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_lars(self): model, X = fit_regression_model(linear_model.Lars()) model_onnx = convert_sklearn( model, "lars", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnLars-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_lars_cv(self): model, X = fit_regression_model(linear_model.LarsCV()) model_onnx = convert_sklearn( model, "lars", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnLarsCV-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_lasso_lars(self): model, X = fit_regression_model(linear_model.LassoLars(alpha=0.01)) model_onnx = convert_sklearn( model, "lasso lars", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnLassoLars-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_lasso_lars_cv(self): model, X = fit_regression_model(linear_model.LassoLarsCV()) model_onnx = convert_sklearn( model, "lasso lars cv", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnLassoLarsCV-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_lasso_lars_ic(self): model, X = fit_regression_model(linear_model.LassoLarsIC()) model_onnx = convert_sklearn( model, "lasso lars cv", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnLassoLarsIC-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_lasso_cv(self): model, X = fit_regression_model(linear_model.LassoCV()) model_onnx = convert_sklearn( model, "lasso cv", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnLassoCV-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_lasso_lars_int(self): model, X = fit_regression_model(linear_model.LassoLars(), is_int=True) model_onnx = convert_sklearn( model, "lasso lars", [("input", Int64TensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnLassoLarsInt-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_multi_linear_regression(self): model, X = fit_regression_model(linear_model.LinearRegression(), n_targets=2) model_onnx = convert_sklearn( model, "linear regression", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, verbose=False, basename="SklearnLinearRegression-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_ard_regression(self): model, X = fit_regression_model(linear_model.ARDRegression()) model_onnx = convert_sklearn( model, "ard regression", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnARDRegression-Dec3", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_theilsen(self): model, X = fit_regression_model(linear_model.TheilSenRegressor()) model_onnx = convert_sklearn( model, "thiel-sen regressor", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnTheilSen-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_bayesian_ridge(self): model, X = fit_regression_model(linear_model.BayesianRidge()) model_onnx = convert_sklearn( model, "bayesian ridge", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnBayesianRidge-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_huber_regressor(self): model, X = fit_regression_model(linear_model.HuberRegressor()) model_onnx = convert_sklearn( model, "huber regressor", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, basename="SklearnHuberRegressor-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_multi_task_lasso(self): model, X = fit_regression_model(linear_model.MultiTaskLasso(), n_targets=2) model_onnx = convert_sklearn( model, "multi-task lasso", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, verbose=False, basename="SklearnMultiTaskLasso-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_multi_task_lasso_cv(self): model, X = fit_regression_model(linear_model.MultiTaskLassoCV(), n_targets=2) model_onnx = convert_sklearn( model, "mutli-task lasso cv", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, verbose=False, basename="SklearnMultiTaskLassoCV-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_multi_task_elasticnet(self): model, X = fit_regression_model(linear_model.MultiTaskElasticNet(), n_targets=2) model_onnx = convert_sklearn( model, "multi-task elasticnet", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, verbose=False, basename="SklearnMultiTaskElasticNet-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_orthogonal_matching_pursuit(self): model, X = fit_regression_model( linear_model.OrthogonalMatchingPursuit()) model_onnx = convert_sklearn( model, "orthogonal matching pursuit", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, verbose=False, basename="SklearnOrthogonalMatchingPursuit-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_passive_aggressive_regressor(self): model, X = fit_regression_model( linear_model.PassiveAggressiveRegressor()) model_onnx = convert_sklearn( model, "passive aggressive regressor", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, verbose=False, basename="SklearnPassiveAggressiveRegressor-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_ransac_regressor_default(self): model, X = fit_regression_model( linear_model.RANSACRegressor()) model_onnx = convert_sklearn( model, "ransac regressor", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, verbose=False, basename="SklearnRANSACRegressor-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_ransac_regressor_mlp(self): model, X = fit_regression_model( linear_model.RANSACRegressor( base_estimator=MLPRegressor(solver='lbfgs'))) model_onnx = convert_sklearn( model, "ransac regressor", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, verbose=False, basename="SklearnRANSACRegressorMLP-Dec3", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_ransac_regressor_tree(self): model, X = fit_regression_model( linear_model.RANSACRegressor( base_estimator=GradientBoostingRegressor())) model_onnx = convert_sklearn( model, "ransac regressor", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, verbose=False, basename="SklearnRANSACRegressorTree-Dec3", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_multi_task_elasticnet_cv(self): model, X = fit_regression_model(linear_model.MultiTaskElasticNetCV(), n_targets=2) model_onnx = convert_sklearn( model, "multi-task elasticnet cv", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, verbose=False, basename="SklearnMultiTaskElasticNetCV-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) def test_model_orthogonal_matching_pursuit_cv(self): model, X = fit_regression_model( linear_model.OrthogonalMatchingPursuitCV()) model_onnx = convert_sklearn( model, "orthogonal matching pursuit cv", [("input", FloatTensorType([None, X.shape[1]]))]) self.assertIsNotNone(model_onnx) dump_data_and_model( X, model, model_onnx, verbose=False, basename="SklearnOrthogonalMatchingPursuitCV-Dec4", allow_failure="StrictVersion(" "onnxruntime.__version__)" "<= StrictVersion('0.2.1')", ) if __name__ == "__main__": unittest.main()
35.172131
79
0.57003
795713612a9b2695829ffed07fdbfc57fe6aad1d
1,206
py
Python
basics/mnistspecificimage.py
johnolafenwa/DeepVision
3b76fb6fcb6f6374c7faf1f8372e3f3091817505
[ "MIT" ]
7
2018-08-03T04:51:12.000Z
2020-01-10T19:27:35.000Z
basics/mnistspecificimage.py
johnolafenwa/DeepVision
3b76fb6fcb6f6374c7faf1f8372e3f3091817505
[ "MIT" ]
null
null
null
basics/mnistspecificimage.py
johnolafenwa/DeepVision
3b76fb6fcb6f6374c7faf1f8372e3f3091817505
[ "MIT" ]
2
2018-08-03T05:36:52.000Z
2018-11-03T14:37:19.000Z
#import needed classes import keras from keras.datasets import mnist from keras.layers import Dense,Dropout from keras.models import Sequential from keras.optimizers import SGD import matplotlib.pyplot as plt #load the mnist dataset (train_x, train_y) , (test_x, test_y) = mnist.load_data() #Define the model model = Sequential() model.add(Dense(units=128,activation="relu",input_shape=(784,))) model.add(Dense(units=128,activation="relu")) model.add(Dense(units=128,activation="relu")) model.add(Dense(units=10,activation="softmax")) #Specify the training components model.compile(optimizer=SGD(0.001),loss="categorical_crossentropy",metrics=["accuracy"]) #Load the pretrained model model.load_weights("mnistmodel.h5") #Normalize the test dataset test_x = test_x.astype('float32') / 255 #Extract a specific image img = test_x[167] #Create a flattened copy of the image test_img = img.reshape((1,784)) #Predict the class img_class = model.predict_classes(test_img) classname = img_class[0] print("Class: ",classname) #Display the original non-flattened copy of the image plt.title("Prediction Result: %s"%(classname)) plt.imshow(img) plt.show()
25.125
89
0.741294
795713e608a74ce46683253055403a50eccb330c
1,316
py
Python
Medium/513.FindBottomLeftTreeValue.py
YuriSpiridonov/LeetCode
2dfcc9c71466ffa2ebc1c89e461ddfca92e2e781
[ "MIT" ]
39
2020-07-04T11:15:13.000Z
2022-02-04T22:33:42.000Z
Medium/513.FindBottomLeftTreeValue.py
YuriSpiridonov/LeetCode
2dfcc9c71466ffa2ebc1c89e461ddfca92e2e781
[ "MIT" ]
1
2020-07-15T11:53:37.000Z
2020-07-15T11:53:37.000Z
Medium/513.FindBottomLeftTreeValue.py
YuriSpiridonov/LeetCode
2dfcc9c71466ffa2ebc1c89e461ddfca92e2e781
[ "MIT" ]
20
2020-07-14T19:12:53.000Z
2022-03-02T06:28:17.000Z
""" Given a binary tree, find the leftmost value in the last row of the tree. Example: Input: 1 / \ 2 3 / / \ 4 5 6 / 7 Output: 7 Note: You may assume the tree (i.e., the given root node) is not NULL. """ #Difficulty: Medium #74 / 74 test cases passed. #Runtime: 40 ms #Memory Usage: 15.8 MB #Runtime: 40 ms, faster than 92.04% of Python3 online submissions for Find Bottom Left Tree Value. #Memory Usage: 15.8 MB, less than 100.00% of Python3 online submissions for Find Bottom Left Tree Value. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findBottomLeftValue(self, root: TreeNode) -> int: queue = [root] left = root.val while queue: level = [] length = len(queue) while length: node = queue.pop(0) level.append(node.val) length -= 1 if node.left: queue.append(node.left) if node.right: queue.append(node.right) left = level[0] return left
26.857143
104
0.530395
795714f1488545329bfe1a36fe7fc2b9b43b8840
2,122
py
Python
functions.py
joolsa/Binary-Classifier-for-Online-Hate-Detection-in-Multiple-Social-Media-Platforms
a3ed3d40d16b04e451146688e78a3d3eed373ba5
[ "MIT" ]
5
2020-04-16T09:38:19.000Z
2021-05-05T21:28:22.000Z
functions.py
ZhEnLEK/Binary-Classifier-for-Online-Hate-Detection-in-Multiple-Social-Media-Platforms
a3ed3d40d16b04e451146688e78a3d3eed373ba5
[ "MIT" ]
2
2020-01-26T19:39:30.000Z
2021-08-17T22:29:36.000Z
functions.py
ZhEnLEK/Binary-Classifier-for-Online-Hate-Detection-in-Multiple-Social-Media-Platforms
a3ed3d40d16b04e451146688e78a3d3eed373ba5
[ "MIT" ]
2
2020-04-28T13:02:03.000Z
2021-03-30T16:31:49.000Z
# Import packages and change some pandas display options import pandas as pd import numpy as np import re import warnings import xgboost as xgb import matplotlib.pyplot as plt from sklearn.metrics import auc, f1_score, roc_curve, roc_auc_score def get_simple_features(data): """ Creates simple features from the comments and adds them as new columns to the dataset.""" # data['words'] = data.Comment_text.apply(lambda x: len(x.split())) data['uppercase'] = data.Comment_text.apply(lambda x: len(re.findall("[A-Z]", x))) data['uppercase_per_word'] = data['uppercase'] / data['words'] data['punctuation'] = data.Comment_text.apply(lambda x: len(re.findall("[,.!?]", x))) data['punctuation_per_word'] = data['punctuation'] / data['words'] data['numbers'] = data.Comment_text.apply(lambda x: len(re.findall("[1-9]+", x))) data['numbers_per_word'] = data['numbers'] / data['words'] simple_features = ['words', 'uppercase', 'uppercase_per_word', 'punctuation', 'punctuation_per_word', 'numbers', 'numbers_per_word'] return data, simple_features def evaluate_model(y_test, y_pred, plot=False, model_name="", features=""): """ Evaluates model and plots ROC. """ fpr, tpr, _ = roc_curve(y_test, y_pred) roc_auc = auc(fpr, tpr) f1 = f1_score(y_test, y_pred > 0.5) print(model_name) print("F1 Score : {}".format(round(f1, 3))) print("AUC : {}".format(round(roc_auc, 3))) if plot: # Compute micro-average ROC curve and ROC area plt.figure(figsize=(9, 6)) lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic {} -- {}'.format(model_name, features)) plt.legend(loc="lower right") plt.show() print("-----------------------------------------------")
39.296296
105
0.618756
795715a0d14ee03059fad62653ae583d80fc761c
170
py
Python
cnn/gradEstimators/__init__.py
aqui-tna/darts-UNIQ
293a27b104bc0f53c6093829d1184686b788fba9
[ "Apache-2.0" ]
6
2019-04-28T05:30:00.000Z
2020-01-21T08:16:13.000Z
cnn/gradEstimators/__init__.py
aqui-tna/darts-UNIQ
293a27b104bc0f53c6093829d1184686b788fba9
[ "Apache-2.0" ]
null
null
null
cnn/gradEstimators/__init__.py
aqui-tna/darts-UNIQ
293a27b104bc0f53c6093829d1184686b788fba9
[ "Apache-2.0" ]
5
2019-04-29T05:57:04.000Z
2021-04-21T00:19:11.000Z
from .random_path import RandomPath as random_path from .layer_same_path import LayerSamePath as layer_same_path from .triple_alphas import TripleAlphas as triple_alphas
42.5
61
0.876471
7957161e44746afb33f98bcc12d9f60029f6c195
656
py
Python
normality/constants.py
EnjoyLifeFund/macHighSierra-py36-pkgs
5668b5785296b314ea1321057420bcd077dba9ea
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
1
2022-01-25T22:52:58.000Z
2022-01-25T22:52:58.000Z
normality/constants.py
EnjoyLifeFund/Debian_py36_packages
1985d4c73fabd5f08f54b922e73a9306e09c77a5
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
null
null
null
normality/constants.py
EnjoyLifeFund/Debian_py36_packages
1985d4c73fabd5f08f54b922e73a9306e09c77a5
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
null
null
null
WS = ' ' # Unicode character classes, see: # http://www.fileformat.info/info/unicode/category/index.htm # https://en.wikipedia.org/wiki/Unicode_character_property # http://www.unicode.org/charts/beta/script/ UNICODE_CATEGORIES = { 'Cc': None, 'Cf': None, 'Cs': None, 'Co': None, 'Cn': None, 'Lm': None, 'Mn': None, 'Mc': WS, 'Me': None, 'Zs': WS, 'Zl': WS, 'Zp': WS, 'Pc': None, 'Pd': WS, 'Ps': WS, 'Pe': WS, 'Pi': WS, 'Pf': WS, 'Po': WS, 'Sc': None, 'Sk': None, 'So': None } CONTROL_CODES = { 'Cc': WS, 'Cf': WS, 'Cs': WS, 'Co': WS, 'Cn': WS }
16.4
60
0.489329
79571720d92f455dbee68dee73f147588d7fdd55
3,149
py
Python
examples/debugging/simple_spread/feedforward/decentralised/run_mad4pg.py
mnguyen0226/Mava
80c583253d769b35491407e3fbbec812b7a085e1
[ "Apache-2.0" ]
null
null
null
examples/debugging/simple_spread/feedforward/decentralised/run_mad4pg.py
mnguyen0226/Mava
80c583253d769b35491407e3fbbec812b7a085e1
[ "Apache-2.0" ]
null
null
null
examples/debugging/simple_spread/feedforward/decentralised/run_mad4pg.py
mnguyen0226/Mava
80c583253d769b35491407e3fbbec812b7a085e1
[ "Apache-2.0" ]
null
null
null
# python3 # Copyright 2021 InstaDeep Ltd. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Example running MAD4PG on debug MPE environments.""" import functools from datetime import datetime from typing import Any import launchpad as lp import sonnet as snt from absl import app, flags from launchpad.nodes.python.local_multi_processing import PythonProcess from mava.systems.tf import mad4pg from mava.utils import lp_utils from mava.utils.environments import debugging_utils from mava.utils.loggers import logger_utils FLAGS = flags.FLAGS flags.DEFINE_string( "env_name", "simple_spread", "Debugging environment name (str).", ) flags.DEFINE_string( "action_space", "continuous", "Environment action space type (str).", ) flags.DEFINE_string( "mava_id", str(datetime.now()), "Experiment identifier that can be used to continue experiments.", ) flags.DEFINE_string("base_dir", "~/mava", "Base dir to store experiments.") def main(_: Any) -> None: # Environment. environment_factory = functools.partial( debugging_utils.make_environment, env_name=FLAGS.env_name, action_space=FLAGS.action_space, ) # Networks. network_factory = lp_utils.partial_kwargs(mad4pg.make_default_networks) # Checkpointer appends "Checkpoints" to checkpoint_dir. checkpoint_dir = f"{FLAGS.base_dir}/{FLAGS.mava_id}" # Log every [log_every] seconds. log_every = 10 logger_factory = functools.partial( logger_utils.make_logger, directory=FLAGS.base_dir, to_terminal=True, to_tensorboard=True, time_stamp=FLAGS.mava_id, time_delta=log_every, ) # Distributed program. program = mad4pg.MAD4PG( environment_factory=environment_factory, network_factory=network_factory, logger_factory=logger_factory, num_executors=1, policy_optimizer=snt.optimizers.Adam(learning_rate=1e-4), critic_optimizer=snt.optimizers.Adam(learning_rate=1e-4), checkpoint_subpath=checkpoint_dir, max_gradient_norm=40.0, ).build() # Ensure only trainer runs on gpu, while other processes run on cpu. gpu_id = -1 env_vars = {"CUDA_VISIBLE_DEVICES": str(gpu_id)} local_resources = { "trainer": [], "evaluator": PythonProcess(env=env_vars), "executor": PythonProcess(env=env_vars), } # Launch. lp.launch( program, lp.LaunchType.LOCAL_MULTI_PROCESSING, terminal="current_terminal", local_resources=local_resources, ) if __name__ == "__main__": app.run(main)
29.157407
75
0.709749
795717affe2e5517755db52592e2a288e8b9641a
1,141
py
Python
developement_code/truncate_val_to_test.py
darongliu/Input_Method
28055937fc777cbba8cbc4c87ba5a2670da7d4e2
[ "MIT" ]
1
2018-07-03T07:42:42.000Z
2018-07-03T07:42:42.000Z
developement_code/truncate_val_to_test.py
darongliu/Input_Method
28055937fc777cbba8cbc4c87ba5a2670da7d4e2
[ "MIT" ]
null
null
null
developement_code/truncate_val_to_test.py
darongliu/Input_Method
28055937fc777cbba8cbc4c87ba5a2670da7d4e2
[ "MIT" ]
null
null
null
import os import random import re val_file = "../data/all_chinese_char_seperate_val.ptt.corpus.20140906.txt" test_file= "../data/all_chinese_char_seperate_test.ptt.corpus.20140906.txt" test_file_ans = "../data/all_chinese_char_seperate_test_ans.ptt.corpus.20140906.txt" with open(val_file , 'r') as f_read , open(test_file , 'w') as f_test , open(test_file_ans , 'w') as f_ans: all_lines = f_read.readlines() for line in all_lines : count = 0 words = line.split() if len(words) <= 5 : continue else : pass while count < 2 : num = random.randrange(4,len(words),1) if words[num] == "o" : count = count + 1 else : break if count < 2 : for i in range(num+1) : f_test.write(words[i]) f_test.write(" ") f_test.write("\n") for i in range(len(words)) : f_ans.write(words[i]) f_ans.write(" ") f_ans.write("\n") else : pass
28.525
108
0.509202
79571b5c80111e578a3f2e61e6aefd2666bbe0f8
28,155
py
Python
run_ner_span.py
20000607-lxc/BERT-NER-Pytorch-master
47f2e1291ab53674986eb91abdb72693eafe9b61
[ "MIT" ]
null
null
null
run_ner_span.py
20000607-lxc/BERT-NER-Pytorch-master
47f2e1291ab53674986eb91abdb72693eafe9b61
[ "MIT" ]
null
null
null
run_ner_span.py
20000607-lxc/BERT-NER-Pytorch-master
47f2e1291ab53674986eb91abdb72693eafe9b61
[ "MIT" ]
null
null
null
import argparse import glob import logging import os import json import time import torch from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from torch.utils.data.distributed import DistributedSampler from callback.optimizater.adamw import AdamW from callback.lr_scheduler import get_linear_schedule_with_warmup from callback.progressbar import ProgressBar from callback.adversarial import FGM from tools.common import seed_everything, json_to_text from tools.common import init_logger, logger from models.transformers import WEIGHTS_NAME, BertConfig, AlbertConfig from models.bert_for_ner import BertSpanForNer from models.albert_for_ner import AlbertSpanForNer from processors.utils_ner import CNerTokenizer from processors.ner_span import convert_examples_to_features from processors.ner_span import ner_processors as processors from processors.ner_span import collate_fn from metrics.ner_metrics import SpanEntityScore from processors.utils_ner import bert_extract_item from tools.finetuning_argparse import get_argparse MODEL_CLASSES = { ## bert ernie bert_wwm bert_wwwm_ext 'bert': (BertConfig, BertSpanForNer, CNerTokenizer), 'albert': (AlbertConfig, AlbertSpanForNer, CNerTokenizer) } def train(args, train_dataset, model, tokenizer): """ Train the model """ args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) train_sampler = RandomSampler(train_dataset) if args.local_rank == -1 else DistributedSampler(train_dataset) train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size, collate_fn=collate_fn) if args.max_steps > 0: t_total = args.max_steps args.num_train_epochs = args.max_steps // (len(train_dataloader) // args.gradient_accumulation_steps) + 1 else: t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs # Prepare optimizer and schedule (linear warmup and decay) no_decay = ["bias", "LayerNorm.weight"] bert_parameters = model.bert.named_parameters() start_parameters = model.start_fc.named_parameters() end_parameters = model.end_fc.named_parameters() optimizer_grouped_parameters = [ {"params": [p for n, p in bert_parameters if not any(nd in n for nd in no_decay)], "weight_decay": args.weight_decay, 'lr': args.learning_rate}, {"params": [p for n, p in bert_parameters if any(nd in n for nd in no_decay)], "weight_decay": 0.0 , 'lr': args.learning_rate}, {"params": [p for n, p in start_parameters if not any(nd in n for nd in no_decay)], "weight_decay": args.weight_decay, 'lr': 0.001}, {"params": [p for n, p in start_parameters if any(nd in n for nd in no_decay)], "weight_decay": 0.0 , 'lr': 0.001}, {"params": [p for n, p in end_parameters if not any(nd in n for nd in no_decay)], "weight_decay": args.weight_decay, 'lr': 0.001}, {"params": [p for n, p in end_parameters if any(nd in n for nd in no_decay)], "weight_decay": 0.0 , 'lr': 0.001}, ] # optimizer_grouped_parameters = [ # {"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], # "weight_decay": args.weight_decay, }, # {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0}, # ] args.warmup_steps = int(t_total * args.warmup_proportion) optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=t_total) # Check if saved optimizer or scheduler states exist if os.path.isfile(os.path.join(args.model_name_or_path, "optimizer.pt")) and os.path.isfile( os.path.join(args.model_name_or_path, "scheduler.pt")): # Load in optimizer and scheduler states optimizer.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "optimizer.pt"))) scheduler.load_state_dict(torch.load(os.path.join(args.model_name_or_path, "scheduler.pt"))) if args.fp16: try: from apex import amp except ImportError: raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") model, optimizer = amp.initialize(model, optimizer, opt_level=args.fp16_opt_level) # multi-gpu training (should be after apex fp16 initialization) if args.n_gpu > 1: model = torch.nn.DataParallel(model) # Distributed training (should be after apex fp16 initialization) if args.local_rank != -1: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank, find_unused_parameters=True) # Train! logger.info("***** Running training *****") logger.info(" Num examples = %d", len(train_dataset)) logger.info(" Num Epochs = %d", args.num_train_epochs) logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size) logger.info(" Total train batch size (w. parallel, distributed & accumulation) = %d", args.train_batch_size * args.gradient_accumulation_steps * (torch.distributed.get_world_size() if args.local_rank != -1 else 1), ) logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps) logger.info(" Total optimization steps = %d", t_total) global_step = 0 steps_trained_in_current_epoch = 0 # Check if continuing training from a checkpoint if os.path.exists(args.model_name_or_path) and "checkpoint" in args.model_name_or_path: # set global_step to gobal_step of last saved checkpoint from model path global_step = int(args.model_name_or_path.split("-")[-1].split("/")[0]) epochs_trained = global_step // (len(train_dataloader) // args.gradient_accumulation_steps) steps_trained_in_current_epoch = global_step % (len(train_dataloader) // args.gradient_accumulation_steps) logger.info(" Continuing training from checkpoint, will skip to saved global_step") logger.info(" Continuing training from epoch %d", epochs_trained) logger.info(" Continuing training from global step %d", global_step) logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch) tr_loss, logging_loss = 0.0, 0.0 if args.do_adv: fgm = FGM(model, emb_name=args.adv_name, epsilon=args.adv_epsilon) model.zero_grad() seed_everything(args.seed) # Added here for reproductibility (even between python 2 and 3) for _ in range(int(args.num_train_epochs)): pbar = ProgressBar(n_total=len(train_dataloader), desc='Training') for step, batch in enumerate(train_dataloader): # Skip past any already trained steps if resuming training if steps_trained_in_current_epoch > 0: steps_trained_in_current_epoch -= 1 continue model.train() batch = tuple(t.to(args.device) for t in batch) inputs = {"input_ids": batch[0], "attention_mask": batch[1], "start_positions": batch[3], "end_positions": batch[4]} if args.model_type != "distilbert": # XLM and RoBERTa don"t use segment_ids inputs["token_type_ids"] = (batch[2] if args.model_type in ["bert", "xlnet"] else None) outputs = model(**inputs) loss = outputs[0] # model outputs are always tuple in pytorch-transformers (see doc) if args.n_gpu > 1: loss = loss.mean() # mean() to average on multi-gpu parallel training if args.gradient_accumulation_steps > 1: loss = loss / args.gradient_accumulation_steps if args.fp16: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() else: loss.backward() if args.do_adv: fgm.attack() loss_adv = model(**inputs)[0] if args.n_gpu > 1: loss_adv = loss_adv.mean() loss_adv.backward() fgm.restore() pbar(step, {'loss': loss.item()}) tr_loss += loss.item() if (step + 1) % args.gradient_accumulation_steps == 0: if args.fp16: torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm) else: torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm) scheduler.step() # Update learning rate schedule optimizer.step() model.zero_grad() global_step += 1 if args.local_rank in [-1, 0] and args.logging_steps > 0 and global_step % args.logging_steps == 0: # Log metrics logger.info("\n") if args.local_rank == -1: # Only evaluate when single GPU otherwise metrics may not average well evaluate(args, model, tokenizer) if args.local_rank in [-1, 0] and args.save_steps > 0 and global_step % args.save_steps == 0: # Save model checkpoint output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step)) if not os.path.exists(output_dir): os.makedirs(output_dir) model_to_save = ( model.module if hasattr(model, "module") else model ) # Take care of distributed/parallel training model_to_save.save_pretrained(output_dir) torch.save(args, os.path.join(output_dir, "training_args.bin")) tokenizer.save_vocabulary(output_dir) logger.info("Saving model checkpoint to %s", output_dir) torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) logger.info("Saving optimizer and scheduler states to %s", output_dir) logger.info("\n") if 'cuda' in str(args.device): torch.cuda.empty_cache() return global_step, tr_loss / global_step def evaluate(args, model, tokenizer, prefix=""): metric = SpanEntityScore(args.id2label) eval_output_dir = args.output_dir if not os.path.exists(eval_output_dir) and args.local_rank in [-1, 0]: os.makedirs(eval_output_dir) eval_features = load_and_cache_examples(args, args.task_name, tokenizer, data_type='dev') args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) # Eval! logger.info("***** Running evaluation %s *****", prefix) logger.info(" Num examples = %d", len(eval_features)) logger.info(" Batch size = %d", args.eval_batch_size) eval_loss = 0.0 nb_eval_steps = 0 pbar = ProgressBar(n_total=len(eval_features), desc="Evaluating") for step, f in enumerate(eval_features): input_lens = f.input_len input_ids = torch.tensor([f.input_ids[:input_lens]], dtype=torch.long).to(args.device) input_mask = torch.tensor([f.input_mask[:input_lens]], dtype=torch.long).to(args.device) segment_ids = torch.tensor([f.segment_ids[:input_lens]], dtype=torch.long).to(args.device) start_ids = torch.tensor([f.start_ids[:input_lens]], dtype=torch.long).to(args.device) end_ids = torch.tensor([f.end_ids[:input_lens]], dtype=torch.long).to(args.device) subjects = f.subjects model.eval() with torch.no_grad(): inputs = {"input_ids": input_ids, "attention_mask": input_mask, "start_positions": start_ids, "end_positions": end_ids} if args.model_type != "distilbert": # XLM and RoBERTa don"t use segment_ids inputs["token_type_ids"] = (segment_ids if args.model_type in ["bert", "xlnet"] else None) outputs = model(**inputs) tmp_eval_loss, start_logits, end_logits = outputs[:3] R = bert_extract_item(start_logits, end_logits) T = subjects metric.update(true_subject=T, pred_subject=R) if args.n_gpu > 1: tmp_eval_loss = tmp_eval_loss.mean() # mean() to average on multi-gpu parallel evaluating eval_loss += tmp_eval_loss.item() nb_eval_steps += 1 pbar(step) logger.info("\n") eval_loss = eval_loss / nb_eval_steps eval_info, entity_info = metric.result() results = {f'{key}': value for key, value in eval_info.items()} results['loss'] = eval_loss logger.info("***** Eval results %s *****", prefix) info = "-".join([f' {key}: {value:.4f} ' for key, value in results.items()]) logger.info(info) logger.info("***** Entity results %s *****", prefix) for key in sorted(entity_info.keys()): logger.info("******* %s results ********" % key) info = "-".join([f' {key}: {value:.4f} ' for key, value in entity_info[key].items()]) logger.info(info) return results def predict(args, model, tokenizer, prefix=""): pred_output_dir = args.output_dir if not os.path.exists(pred_output_dir) and args.local_rank in [-1, 0]: os.makedirs(pred_output_dir) test_dataset = load_and_cache_examples(args, args.task_name, tokenizer, data_type='test') print(len(test_dataset)) # Note that DistributedSampler samples randomly test_sampler = SequentialSampler(test_dataset) if args.local_rank == -1 else DistributedSampler(test_dataset) test_dataloader = DataLoader(test_dataset, sampler=test_sampler, batch_size=1, collate_fn=collate_fn) # Eval! logger.info("***** Running prediction %s *****", prefix) logger.info(" Num examples = %d", len(test_dataset)) logger.info(" Batch size = %d", 1) results = [] output_predict_file = os.path.join(pred_output_dir, prefix, "test_predict.json") pbar = ProgressBar(n_total=len(test_dataloader), desc="Predicting") for step, batch in enumerate(test_dataloader): model.eval() batch = tuple(t.to(args.device) for t in batch) with torch.no_grad(): inputs = {"input_ids": batch[0], "attention_mask": batch[1], "start_positions": None, "end_positions": None} if args.model_type != "distilbert": # XLM and RoBERTa don"t use segment_ids inputs["token_type_ids"] = (batch[2] if args.model_type in ["bert", "xlnet"] else None) outputs = model(**inputs) start_logits, end_logits = outputs[:2] R = bert_extract_item(start_logits, end_logits) if R: label_entities = [[args.id2label[x[0]], x[1], x[2]] for x in R] else: label_entities = [] json_d = {} json_d['id'] = step json_d['entities'] = label_entities results.append(json_d) pbar(step) logger.info("\n") with open(output_predict_file, "w") as writer: for record in results: writer.write(json.dumps(record) + '\n') if args.task_name == "cluener": output_submit_file = os.path.join(pred_output_dir, prefix, "test_submit.json") test_text = [] with open(os.path.join(args.data_dir, "test.json"), 'r') as fr: for line in fr: test_text.append(json.loads(line)) test_submit = [] for x, y in zip(test_text, results): json_d = {} json_d['id'] = x['id'] json_d['label'] = {} entities = y['entities'] words = list(x['text']) if len(entities) != 0: for subject in entities: tag = subject[0] start = subject[1] end = subject[2] word = "".join(words[start:end + 1]) if tag in json_d['label']: if word in json_d['label'][tag]: json_d['label'][tag][word].append([start, end]) else: json_d['label'][tag][word] = [[start, end]] else: json_d['label'][tag] = {} json_d['label'][tag][word] = [[start, end]] test_submit.append(json_d) json_to_text(output_submit_file, test_submit) def load_and_cache_examples(args, task, tokenizer, data_type='train'): if args.local_rank not in [-1, 0] and not evaluate: torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache processor = processors[task]() # Load data features from cache or dataset file cached_features_file = os.path.join(args.data_dir, 'cached_span-{}_{}_{}_{}'.format( data_type, list(filter(None, args.model_name_or_path.split('/'))).pop(), str(args.train_max_seq_length if data_type == 'train' else args.eval_max_seq_length), str(task))) if os.path.exists(cached_features_file) and not args.overwrite_cache: logger.info("Loading features from cached file %s", cached_features_file) features = torch.load(cached_features_file) else: logger.info("Creating features from dataset file at %s", args.data_dir) label_list = processor.get_labels() if data_type == 'train': examples = processor.get_train_examples(args.data_dir) elif data_type == 'dev': examples = processor.get_dev_examples(args.data_dir) else: examples = processor.get_test_examples(args.data_dir) features = convert_examples_to_features(examples=examples, tokenizer=tokenizer, label_list=label_list, max_seq_length=args.train_max_seq_length if data_type == 'train' \ else args.eval_max_seq_length, cls_token_at_end=bool(args.model_type in ["xlnet"]), pad_on_left=bool(args.model_type in ['xlnet']), cls_token=tokenizer.cls_token, cls_token_segment_id=2 if args.model_type in ["xlnet"] else 0, sep_token=tokenizer.sep_token, # pad on the left for xlnet pad_token=tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0], pad_token_segment_id=4 if args.model_type in ['xlnet'] else 0, ) if args.local_rank in [-1, 0]: logger.info("Saving features into cached file %s", cached_features_file) torch.save(features, cached_features_file) if args.local_rank == 0 and not evaluate: torch.distributed.barrier() # Make sure only the first process in distributed training process the dataset, and the others will use the cache # Convert to Tensors and build dataset if data_type == 'dev': return features all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long) all_segment_ids = torch.tensor([f.segment_ids for f in features], dtype=torch.long) all_start_ids = torch.tensor([f.start_ids for f in features], dtype=torch.long) all_end_ids = torch.tensor([f.end_ids for f in features], dtype=torch.long) all_input_lens = torch.tensor([f.input_len for f in features], dtype=torch.long) dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_start_ids, all_end_ids, all_input_lens) return dataset def main(): args = get_argparse().parse_args() if not os.path.exists(args.output_dir): os.mkdir(args.output_dir) args.output_dir = args.output_dir + '{}'.format(args.model_type) if not os.path.exists(args.output_dir): os.mkdir(args.output_dir) time_ = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime()) init_logger(log_file=args.output_dir + f'/{args.model_type}-{args.task_name}-{time_}.log') if os.path.exists(args.output_dir) and os.listdir( args.output_dir) and args.do_train and not args.overwrite_output_dir: raise ValueError( "Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format( args.output_dir)) # Setup distant debugging if needed if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("Waiting for debugger attach") ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True) ptvsd.wait_for_attach() # Setup CUDA, GPU & distributed training if args.local_rank == -1 or args.no_cuda: device = torch.device("cuda", 3)#torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu") args.n_gpu = 1#torch.cuda.device_count() else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs torch.cuda.set_device(args.local_rank) device = torch.device("cuda", args.local_rank) torch.distributed.init_process_group(backend="nccl") args.n_gpu = 1 args.device = device logger.warning("Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", args.local_rank, device, args.n_gpu, bool(args.local_rank != -1), args.fp16, ) # Set seed seed_everything(args.seed) # Prepare NER task args.task_name = args.task_name.lower() if args.task_name not in processors: raise ValueError("Task not found: %s" % (args.task_name)) processor = processors[args.task_name]() label_list = processor.get_labels() args.id2label = {i: label for i, label in enumerate(label_list)} args.label2id = {label: i for i, label in enumerate(label_list)} num_labels = len(label_list) # Load pretrained model and tokenizer if args.local_rank not in [-1, 0]: torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab args.model_type = args.model_type.lower() config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type] config = config_class.from_pretrained(args.config_name if args.config_name else args.model_name_or_path, num_labels=num_labels, loss_type=args.loss_type, cache_dir=args.cache_dir if args.cache_dir else None, soft_label=True) tokenizer = tokenizer_class.from_pretrained(args.tokenizer_name if args.tokenizer_name else args.model_name_or_path, do_lower_case=args.do_lower_case, cache_dir=args.cache_dir if args.cache_dir else None, ) model = model_class.from_pretrained(args.model_name_or_path, from_tf=bool(".ckpt" in args.model_name_or_path), config=config) if args.local_rank == 0: torch.distributed.barrier() # Make sure only the first process in distributed training will download model & vocab model.to(args.device) logger.info("Training/evaluation parameters %s", args) # Training if args.do_train: train_dataset = load_and_cache_examples(args, args.task_name, tokenizer, data_type='train') global_step, tr_loss = train(args, train_dataset, model, tokenizer) logger.info(" global_step = %s, average loss = %s", global_step, tr_loss) # Saving best-practices: if you use defaults names for the model, you can reload it using from_pretrained() if args.do_train and (args.local_rank == -1 or torch.distributed.get_rank() == 0): # Create output directory if needed if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]: os.makedirs(args.output_dir) logger.info("Saving model checkpoint to %s", args.output_dir) # Save a trained model, configuration and tokenizer using `save_pretrained()`. # They can then be reloaded using `from_pretrained()` model_to_save = ( model.module if hasattr(model, "module") else model ) # Take care of distributed/parallel training model_to_save.save_pretrained(args.output_dir) tokenizer.save_vocabulary(args.output_dir) # Good practice: save your training arguments together with the trained model torch.save(args, os.path.join(args.output_dir, "training_args.bin")) # Evaluation results = {} if args.do_eval and args.local_rank in [-1, 0]: tokenizer = tokenizer_class.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case) checkpoints = [args.output_dir] if args.eval_all_checkpoints: checkpoints = list( os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + "/**/" + WEIGHTS_NAME, recursive=True)) ) logging.getLogger("pytorch_transformers.modeling_utils").setLevel(logging.WARN) # Reduce logging logger.info("Evaluate the following checkpoints: %s", checkpoints) for checkpoint in checkpoints: global_step = checkpoint.split("-")[-1] if len(checkpoints) > 1 else "" prefix = checkpoint.split('/')[-1] if checkpoint.find('checkpoint') != -1 else "" model = model_class.from_pretrained(checkpoint) model.to(args.device) result = evaluate(args, model, tokenizer, prefix=prefix) if global_step: result = {"{}_{}".format(global_step, k): v for k, v in result.items()} results.update(result) output_eval_file = os.path.join(args.output_dir, "eval_results.txt") with open(output_eval_file, "w") as writer: for key in sorted(results.keys()): writer.write("{} = {}\n".format(key, str(results[key]))) if args.do_predict and args.local_rank in [-1, 0]: tokenizer = tokenizer_class.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case) checkpoints = [args.output_dir] if args.predict_checkpoints > 0: checkpoints = list( os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + '/**/' + WEIGHTS_NAME, recursive=True))) logging.getLogger("transformers.modeling_utils").setLevel(logging.WARN) # Reduce logging checkpoints = [x for x in checkpoints if x.split('-')[-1] == str(args.predict_checkpoints)] logger.info("Predict the following checkpoints: %s", checkpoints) for checkpoint in checkpoints: prefix = checkpoint.split('/')[-1] if checkpoint.find('checkpoint') != -1 else "" model = model_class.from_pretrained(checkpoint) model.to(args.device) predict(args, model, tokenizer, prefix=prefix) if __name__ == "__main__": main()
55.532544
150
0.630368
79571b712fdaec75f7c387b10aad8be64dfc3df3
2,253
py
Python
statistik_api.py
ophcode/sormasapi
01da5b362608568d8881af85177e1928a46b2715
[ "CC0-1.0" ]
4
2021-05-23T21:13:52.000Z
2021-09-06T20:58:13.000Z
statistik_api.py
ophcode/sormasapi
01da5b362608568d8881af85177e1928a46b2715
[ "CC0-1.0" ]
null
null
null
statistik_api.py
ophcode/sormasapi
01da5b362608568d8881af85177e1928a46b2715
[ "CC0-1.0" ]
null
null
null
""" Work in progress: - Does a database dump of all cases / persons in database - When restarted, only updates cases / persons that have been changed since last use - Potentially useful for automated statistics """ import sormasapi import config import time import os import json from pprint import pprint def initialize_json(filename, save_interval = 100): print("Getting all data... might take a while") casedict = {} uuids = sormasapi.get_all_case_uuids() print(str(len(uuids)) + " Fälle insgesamt") if os.path.exists(filename): with open(filename) as jsonfile: casedict = json.load(jsonfile) print(str(len(casedict)) + " Fälle aus Datei geladen") i = 0 for uuid in uuids: if uuid not in casedict: case = sormasapi.query("cases",uuid) casedict[uuid] = case i+=1 if i == save_interval: i=0 print(str(len(casedict))), with open(filename, "w") as outfile: json.dump(casedict, outfile) def initialize_person_json(): pass def load_and_update_json(filename, override_date=""): # 1) Reads json dump # 2) Updates all cases updated since last dump # 3) Adds new cases # override_date: force update since date / datetime (dd.mm.yyyy / dd.mm.yyyy HH:SS) casedict = {} with open(filename) as jsonfile: casedict = json.load(jsonfile) changedate = max([casedict[key]["changeDate"] for key in casedict]) if override_date: changedate = sormasapi.datestring_to_int(override_date) new_cases = sormasapi.get_since("cases", dateint = changedate) for case in new_cases: casedict[case["uuid"]] = case with open(filename, "w") as outfile: json.dump(casedict, outfile) print("Done") return casedict def if __name__== "__main__": os.environ['HTTPS_PROXY'] = config.proxy start_time = time.time() filename = "all_cases.json" #initialize_json(filename) casedict = load_and_update_json(filename) print(len(casedict)) print("--- %s seconds ---" % (time.time() - start_time))
32.185714
88
0.616511
79571b904051900eb6ed297d64f2d4102a9ba932
10,075
py
Python
src/superpoint.py
haoningwu3639/EE229_Project_VideoStabilization
74603e9dc5f10b3deffb2f4e0753c15dc8b9a92d
[ "MIT" ]
1
2021-06-13T06:32:29.000Z
2021-06-13T06:32:29.000Z
src/superpoint.py
haoningwu3639/EE229_Project_VideoStabilization
74603e9dc5f10b3deffb2f4e0753c15dc8b9a92d
[ "MIT" ]
null
null
null
src/superpoint.py
haoningwu3639/EE229_Project_VideoStabilization
74603e9dc5f10b3deffb2f4e0753c15dc8b9a92d
[ "MIT" ]
null
null
null
import numpy as np import torch class SuperPointNet(torch.nn.Module): """ SuperPoint Network Thanks to https://github.com/magicleap/SuperPointPretrainedNetwork """ def __init__(self): super(SuperPointNet, self).__init__() self.relu = torch.nn.ReLU(inplace=True) self.pool = torch.nn.MaxPool2d(kernel_size=2, stride=2) c1, c2, c3, c4, c5, d1 = 64, 64, 128, 128, 256, 256 # Shared Encoder. self.conv1a = torch.nn.Conv2d( 1, c1, kernel_size=3, stride=1, padding=1) self.conv1b = torch.nn.Conv2d( c1, c1, kernel_size=3, stride=1, padding=1) self.conv2a = torch.nn.Conv2d( c1, c2, kernel_size=3, stride=1, padding=1) self.conv2b = torch.nn.Conv2d( c2, c2, kernel_size=3, stride=1, padding=1) self.conv3a = torch.nn.Conv2d( c2, c3, kernel_size=3, stride=1, padding=1) self.conv3b = torch.nn.Conv2d( c3, c3, kernel_size=3, stride=1, padding=1) self.conv4a = torch.nn.Conv2d( c3, c4, kernel_size=3, stride=1, padding=1) self.conv4b = torch.nn.Conv2d( c4, c4, kernel_size=3, stride=1, padding=1) # Detector Head. self.convPa = torch.nn.Conv2d( c4, c5, kernel_size=3, stride=1, padding=1) self.convPb = torch.nn.Conv2d( c5, 65, kernel_size=1, stride=1, padding=0) # Descriptor Head. self.convDa = torch.nn.Conv2d( c4, c5, kernel_size=3, stride=1, padding=1) self.convDb = torch.nn.Conv2d( c5, d1, kernel_size=1, stride=1, padding=0) def forward(self, x): """ Forward pass that jointly computes unprocessed point and descriptor tensors. Input x: Image pytorch tensor shaped N x 1 x H x W. Output semi: Output point pytorch tensor shaped N x 65 x H/8 x W/8. desc: Output descriptor pytorch tensor shaped N x 256 x H/8 x W/8. """ # Shared Encoder. x = self.relu(self.conv1a(x)) x = self.relu(self.conv1b(x)) x = self.pool(x) x = self.relu(self.conv2a(x)) x = self.relu(self.conv2b(x)) x = self.pool(x) x = self.relu(self.conv3a(x)) x = self.relu(self.conv3b(x)) x = self.pool(x) x = self.relu(self.conv4a(x)) x = self.relu(self.conv4b(x)) # Detector Head. cPa = self.relu(self.convPa(x)) semi = self.convPb(cPa) # Descriptor Head. cDa = self.relu(self.convDa(x)) desc = self.convDb(cDa) dn = torch.norm(desc, p=2, dim=1) # Compute the norm. desc = desc.div(torch.unsqueeze(dn, 1)) # Divide by norm to normalize. return semi, desc class SuperPointWrapper(object): """ Wrapper around pytorch net to help with pre and post image processing. """ def __init__(self, weights_path, nms_dist=2, conf_thresh=1e-5, nn_thresh=0.7, cuda=False): self.name = 'SuperPoint' self.cuda = cuda self.nms_dist = nms_dist self.conf_thresh = conf_thresh self.nn_thresh = nn_thresh # L2 descriptor distance for good match. self.cell = 8 # Size of each output cell. Keep this fixed. self.border_remove = 4 # Remove points this close to the border. # Load the network in inference mode. self.net = SuperPointNet() if cuda: # Train on GPU, deploy on GPU. self.net.load_state_dict(torch.load(weights_path)) self.net = self.net.cuda() else: # Train on GPU, deploy on CPU. self.net.load_state_dict(torch.load(weights_path, map_location=lambda storage, loc: storage)) self.net.eval() def nms_fast(self, in_corners, H, W, dist_thresh): """ Run a faster approximate Non-Max-Suppression on numpy corners shaped: 3xN [x_i,y_i,conf_i]^T Algo summary: Create a grid sized HxW. Assign each corner location a 1, rest are zeros. Iterate through all the 1's and convert them either to -1 or 0. Suppress points by setting nearby values to 0. Grid Value Legend: -1 : Kept. 0 : Empty or suppressed. 1 : To be processed (converted to either kept or supressed). NOTE: The NMS first rounds points to integers, so NMS distance might not be exactly dist_thresh. It also assumes points are within image boundaries. Inputs in_corners - 3xN numpy array with corners [x_i, y_i, confidence_i]^T. H - Image height. W - Image width. dist_thresh - Distance to suppress, measured as an infinty norm distance. Returns nmsed_corners - 3xN numpy matrix with surviving corners. nmsed_inds - N length numpy vector with surviving corner indices. """ grid = np.zeros((H, W)).astype(int) # Track NMS data. inds = np.zeros((H, W)).astype(int) # Store indices of points. # Sort by confidence and round to nearest int. inds1 = np.argsort(-in_corners[2, :]) corners = in_corners[:, inds1] rcorners = corners[:2, :].round().astype(int) # Rounded corners. # Check for edge case of 0 or 1 corners. if rcorners.shape[1] == 0: return np.zeros((3, 0)).astype(int), np.zeros(0).astype(int) if rcorners.shape[1] == 1: out = np.vstack((rcorners, in_corners[2])).reshape(3, 1) return out, np.zeros((1)).astype(int) # Initialize the grid. for i, rc in enumerate(rcorners.T): grid[rcorners[1, i], rcorners[0, i]] = 1 inds[rcorners[1, i], rcorners[0, i]] = i # Pad the border of the grid, so that we can NMS points near the border. pad = dist_thresh grid = np.pad(grid, ((pad, pad), (pad, pad)), mode='constant') # Iterate through points, highest to lowest conf, suppress neighborhood. count = 0 for i, rc in enumerate(rcorners.T): # Account for top and left padding. pt = (rc[0]+pad, rc[1]+pad) if grid[pt[1], pt[0]] == 1: # If not yet suppressed. grid[pt[1]-pad:pt[1]+pad+1, pt[0]-pad:pt[0]+pad+1] = 0 grid[pt[1], pt[0]] = -1 count += 1 # Get all surviving -1's and return sorted array of remaining corners. keepy, keepx = np.where(grid == -1) keepy, keepx = keepy - pad, keepx - pad inds_keep = inds[keepy, keepx] out = corners[:, inds_keep] values = out[-1, :] inds2 = np.argsort(-values) out = out[:, inds2] out_inds = inds1[inds_keep[inds2]] return out, out_inds def run(self, img): """ Process a numpy image to extract points and descriptors. Input img - HxW numpy float32 input image in range [0,1]. Output corners - 3xN numpy array with corners [x_i, y_i, confidence_i]^T. desc - 256xN numpy array of corresponding unit normalized descriptors. heatmap - HxW numpy heatmap in range [0,1] of point confidences. """ assert img.ndim == 2, 'Image must be grayscale.' assert img.dtype == np.float32, 'Image must be float32.' H, W = img.shape[0], img.shape[1] inp = img.copy() inp = (inp.reshape(1, H, W)) inp = torch.from_numpy(inp) inp = torch.autograd.Variable(inp).view(1, 1, H, W) if self.cuda: inp = inp.cuda() # Forward pass of network. outs = self.net.forward(inp) semi, coarse_desc = outs[0], outs[1] # Convert pytorch -> numpy. semi = semi.data.cpu().numpy().squeeze() # --- Process points. dense = np.exp(semi) # Softmax. dense = dense / (np.sum(dense, axis=0)+.00001) # Should sum to 1. # Remove dustbin. nodust = dense[:-1, :, :] # Reshape to get full resolution heatmap. Hc = int(H / self.cell) Wc = int(W / self.cell) nodust = nodust.transpose(1, 2, 0) heatmap = np.reshape(nodust, [Hc, Wc, self.cell, self.cell]) heatmap = np.transpose(heatmap, [0, 2, 1, 3]) heatmap = np.reshape(heatmap, [Hc*self.cell, Wc*self.cell]) xs, ys = np.where(heatmap >= self.conf_thresh) # Confidence threshold. if len(xs) == 0: return np.zeros((3, 0)), None, None pts = np.zeros((3, len(xs))) # Populate point data sized 3xN. pts[0, :] = ys pts[1, :] = xs pts[2, :] = heatmap[xs, ys] # Apply NMS. pts, _ = self.nms_fast(pts, H, W, dist_thresh=self.nms_dist) inds = np.argsort(pts[2, :]) pts = pts[:, inds[::-1]] # Sort by confidence. # Remove points along border. bord = self.border_remove toremoveW = np.logical_or(pts[0, :] < bord, pts[0, :] >= (W-bord)) toremoveH = np.logical_or(pts[1, :] < bord, pts[1, :] >= (H-bord)) toremove = np.logical_or(toremoveW, toremoveH) pts = pts[:, ~toremove] # --- Process descriptor. D = coarse_desc.shape[1] if pts.shape[1] == 0: desc = np.zeros((D, 0)) else: # Interpolate into descriptor map using 2D point locations. samp_pts = torch.from_numpy(pts[:2, :].copy()) samp_pts[0, :] = (samp_pts[0, :] / (float(W)/2.)) - 1. samp_pts[1, :] = (samp_pts[1, :] / (float(H)/2.)) - 1. samp_pts = samp_pts.transpose(0, 1).contiguous() samp_pts = samp_pts.view(1, 1, -1, 2) samp_pts = samp_pts.float() if self.cuda: samp_pts = samp_pts.cuda() desc = torch.nn.functional.grid_sample(coarse_desc, samp_pts) desc = desc.data.cpu().numpy().reshape(D, -1) desc /= np.linalg.norm(desc, axis=0)[np.newaxis, :] return pts, desc, heatmap
42.87234
94
0.564367
79571c65423eb3a56d91f1c82f56cd4de13bb6ea
8,608
py
Python
handler.py
dudeitssm/aws-billing-to-slack
9d807247315a08d74f7000740621cdda7d70b40c
[ "MIT" ]
123
2019-10-08T02:17:18.000Z
2022-03-27T19:15:37.000Z
handler.py
dudeitssm/aws-billing-to-slack
9d807247315a08d74f7000740621cdda7d70b40c
[ "MIT" ]
13
2019-11-08T11:58:51.000Z
2022-03-27T17:15:47.000Z
handler.py
dudeitssm/aws-billing-to-slack
9d807247315a08d74f7000740621cdda7d70b40c
[ "MIT" ]
54
2019-10-15T14:17:08.000Z
2022-03-29T09:58:06.000Z
from collections import defaultdict import boto3 import datetime import os import requests import sys n_days = 7 yesterday = datetime.datetime.today() - datetime.timedelta(days=1) week_ago = yesterday - datetime.timedelta(days=n_days) # It seems that the sparkline symbols don't line up (probalby based on font?) so put them last # Also, leaving out the full block because Slack doesn't like it: '█' sparks = ['▁', '▂', '▃', '▄', '▅', '▆', '▇'] def sparkline(datapoints): lower = min(datapoints) upper = max(datapoints) width = upper - lower n_sparks = len(sparks) - 1 line = "" for dp in datapoints: scaled = 1 if width == 0 else (dp - lower) / width which_spark = int(scaled * n_sparks) line += (sparks[which_spark]) return line def delta(costs): if (len(costs) > 1 and costs[-1] >= 1 and costs[-2] >= 1): # This only handles positive numbers result = ((costs[-1]/costs[-2])-1)*100.0 else: result = 0 return result def report_cost(event, context, result: dict = None, yesterday: str = None, new_method=True): if yesterday is None: yesterday = datetime.datetime.today() - datetime.timedelta(days=1) else: yesterday = datetime.datetime.strptime(yesterday, '%Y-%m-%d') week_ago = yesterday - datetime.timedelta(days=n_days) # Generate list of dates, so that even if our data is sparse, # we have the correct length lists of costs (len is n_days) list_of_dates = [ (week_ago + datetime.timedelta(days=x)).strftime('%Y-%m-%d') for x in range(n_days) ] print(list_of_dates) # Get account account name from env, or account id/account alias from boto3 account_name = os.environ.get("AWS_ACCOUNT_NAME", None) if account_name is None: iam = boto3.client("iam") paginator = iam.get_paginator("list_account_aliases") for aliases in paginator.paginate(PaginationConfig={"MaxItems": 1}): if "AccountAliases" in aliases and len(aliases["AccountAliases"]) > 0: account_name = aliases["AccountAliases"][0] if account_name is None: account_name = boto3.client("sts").get_caller_identity().get("Account") if account_name is None: account_name = "[NOT FOUND]" client = boto3.client('ce') query = { "TimePeriod": { "Start": week_ago.strftime('%Y-%m-%d'), "End": yesterday.strftime('%Y-%m-%d'), }, "Granularity": "DAILY", "Filter": { "Not": { "Dimensions": { "Key": "RECORD_TYPE", "Values": [ "Credit", "Refund", "Upfront", "Support", ] } } }, "Metrics": ["UnblendedCost"], "GroupBy": [ { "Type": "DIMENSION", "Key": "SERVICE", }, ], } # Only run the query when on lambda, not when testing locally with example json if result is None: result = client.get_cost_and_usage(**query) cost_per_day_by_service = defaultdict(list) if new_method == False: # Build a map of service -> array of daily costs for the time frame for day in result['ResultsByTime']: for group in day['Groups']: key = group['Keys'][0] cost = float(group['Metrics']['UnblendedCost']['Amount']) cost_per_day_by_service[key].append(cost) else: # New method, which first creates a dict of dicts # then loop over the services and loop over the list_of_dates # and this means even for sparse data we get a full list of costs cost_per_day_dict = defaultdict(dict) for day in result['ResultsByTime']: start_date = day["TimePeriod"]["Start"] for group in day['Groups']: key = group['Keys'][0] cost = float(group['Metrics']['UnblendedCost']['Amount']) cost_per_day_dict[key][start_date] = cost for key in cost_per_day_dict.keys(): for start_date in list_of_dates: cost = cost_per_day_dict[key].get(start_date, 0.0) # fallback for sparse data cost_per_day_by_service[key].append(cost) # Sort the map by yesterday's cost most_expensive_yesterday = sorted(cost_per_day_by_service.items(), key=lambda i: i[1][-1], reverse=True) service_names = [k for k,_ in most_expensive_yesterday[:5]] longest_name_len = len(max(service_names, key = len)) buffer = f"{'Service':{longest_name_len}} ${'Yday':8} {'∆%':>5} {'Last 7d':7}\n" for service_name, costs in most_expensive_yesterday[:5]: buffer += f"{service_name:{longest_name_len}} ${costs[-1]:8,.2f} {delta(costs):4.0f}% {sparkline(costs):7}\n" other_costs = [0.0] * n_days for service_name, costs in most_expensive_yesterday[5:]: for i, cost in enumerate(costs): other_costs[i] += cost buffer += f"{'Other':{longest_name_len}} ${other_costs[-1]:8,.2f} {delta(other_costs):4.0f}% {sparkline(other_costs):7}\n" total_costs = [0.0] * n_days for day_number in range(n_days): for service_name, costs in most_expensive_yesterday: try: total_costs[day_number] += costs[day_number] except IndexError: total_costs[day_number] += 0.0 buffer += f"{'Total':{longest_name_len}} ${total_costs[-1]:8,.2f} {delta(total_costs):4.0f}% {sparkline(total_costs):7}\n" cost_per_day_by_service["total"] = total_costs[-1] credits_expire_date = os.environ.get('CREDITS_EXPIRE_DATE') if credits_expire_date: credits_expire_date = datetime.datetime.strptime(credits_expire_date, "%m/%d/%Y") credits_remaining_as_of = os.environ.get('CREDITS_REMAINING_AS_OF') credits_remaining_as_of = datetime.datetime.strptime(credits_remaining_as_of, "%m/%d/%Y") credits_remaining = float(os.environ.get('CREDITS_REMAINING')) days_left_on_credits = (credits_expire_date - credits_remaining_as_of).days allowed_credits_per_day = credits_remaining / days_left_on_credits relative_to_budget = (total_costs[-1] / allowed_credits_per_day) * 100.0 if relative_to_budget < 60: emoji = ":white_check_mark:" elif relative_to_budget > 110: emoji = ":rotating_light:" else: emoji = ":warning:" summary = (f"{emoji} Yesterday's cost for {account_name} ${total_costs[-1]:,.2f} " f"is {relative_to_budget:.2f}% of credit budget " f"${allowed_credits_per_day:,.2f} for the day." ) else: summary = f"Yesterday's cost for account {account_name} was ${total_costs[-1]:,.2f}" hook_url = os.environ.get('SLACK_WEBHOOK_URL') if hook_url: resp = requests.post( hook_url, json={ "text": summary + "\n\n```\n" + buffer + "\n```", } ) if resp.status_code != 200: print("HTTP %s: %s" % (resp.status_code, resp.text)) else: print(summary) print(buffer) # for running locally to test output return cost_per_day_by_service if __name__ == "__main__": # for running locally to test import json with open("example_boto3_result.json", "r") as f: example_result = json.load(f) with open("example_boto3_result2.json", "r") as f: example_result2 = json.load(f) # New Method with 2 example jsons cost_dict = report_cost(None, None, example_result, yesterday="2021-08-23", new_method=True) assert "{0:.2f}".format(cost_dict.get("total", 0.0)) == "286.37", f'{cost_dict.get("total"):,.2f} != 286.37' cost_dict = report_cost(None, None, example_result2, yesterday="2021-08-29", new_method=True) assert "{0:.2f}".format(cost_dict.get("total", 0.0)) == "21.45", f'{cost_dict.get("total"):,.2f} != 21.45' # Old Method with same jsons (will fail) cost_dict = report_cost(None, None, example_result, yesterday="2021-08-23", new_method=False) assert "{0:.2f}".format(cost_dict.get("total", 0.0)) == "286.37", f'{cost_dict.get("total"):,.2f} != 286.37' cost_dict = report_cost(None, None, example_result2, yesterday="2021-08-29", new_method=False) assert "{0:.2f}".format(cost_dict.get("total", 0.0)) == "21.45", f'{cost_dict.get("total"):,.2f} != 21.45'
38.257778
126
0.603625
79571dfa7e748d1f814800a975a79c38a5651883
691
py
Python
test_package/conanfile.py
ArsenStudio/conan-llvm
dd6cd5566ef399c6ee0cbaf6e990861eac7f8616
[ "MIT" ]
null
null
null
test_package/conanfile.py
ArsenStudio/conan-llvm
dd6cd5566ef399c6ee0cbaf6e990861eac7f8616
[ "MIT" ]
null
null
null
test_package/conanfile.py
ArsenStudio/conan-llvm
dd6cd5566ef399c6ee0cbaf6e990861eac7f8616
[ "MIT" ]
null
null
null
import os from conans import ConanFile, CMake, tools class LlvmTestConan(ConanFile): settings = "os", "compiler", "build_type", "arch" generators = "cmake" def build(self): cmake = CMake(self) # Current dir is "test_package/build/<build_id>" and CMakeLists.txt is # in "test_package" cmake.configure() cmake.build() def imports(self): self.copy("*.dll", dst="bin", src="bin") self.copy("*.dylib*", dst="bin", src="lib") self.copy('*.so*', dst='bin', src='lib') def test(self): if not tools.cross_building(self.settings): os.chdir("bin") self.run(".%sexample" % os.sep)
26.576923
78
0.57453
79571e2304255e90ca1b1756040055c1b39308a9
17,635
py
Python
wagtail-repository/wagtail/images/models.py
TobiasSkovgaardJepsen/wagtail-on-heroku
17e4720f86023225e0704890688998a80bb87a17
[ "BSD-3-Clause" ]
null
null
null
wagtail-repository/wagtail/images/models.py
TobiasSkovgaardJepsen/wagtail-on-heroku
17e4720f86023225e0704890688998a80bb87a17
[ "BSD-3-Clause" ]
4
2020-06-05T17:00:01.000Z
2021-06-17T20:15:01.000Z
wagtail-repository/wagtail/images/models.py
TobiasSkovgaardJepsen/wagtail-on-heroku
17e4720f86023225e0704890688998a80bb87a17
[ "BSD-3-Clause" ]
1
2019-04-16T14:14:55.000Z
2019-04-16T14:14:55.000Z
import hashlib import os.path from collections import OrderedDict from contextlib import contextmanager from io import BytesIO from django.conf import settings from django.core import checks from django.core.files import File from django.db import models from django.forms.utils import flatatt from django.urls import reverse from django.utils.functional import cached_property from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from taggit.managers import TaggableManager from unidecode import unidecode from willow.image import Image as WillowImage from wagtail.admin.utils import get_object_usage from wagtail.core import hooks from wagtail.core.models import CollectionMember from wagtail.images.exceptions import InvalidFilterSpecError from wagtail.images.rect import Rect from wagtail.search import index from wagtail.search.queryset import SearchableQuerySetMixin class SourceImageIOError(IOError): """ Custom exception to distinguish IOErrors that were thrown while opening the source image """ pass class ImageQuerySet(SearchableQuerySetMixin, models.QuerySet): pass def get_upload_to(instance, filename): """ Obtain a valid upload path for an image file. This needs to be a module-level function so that it can be referenced within migrations, but simply delegates to the `get_upload_to` method of the instance, so that AbstractImage subclasses can override it. """ return instance.get_upload_to(filename) def get_rendition_upload_to(instance, filename): """ Obtain a valid upload path for an image rendition file. This needs to be a module-level function so that it can be referenced within migrations, but simply delegates to the `get_upload_to` method of the instance, so that AbstractRendition subclasses can override it. """ return instance.get_upload_to(filename) class AbstractImage(CollectionMember, index.Indexed, models.Model): title = models.CharField(max_length=255, verbose_name=_('title')) file = models.ImageField( verbose_name=_('file'), upload_to=get_upload_to, width_field='width', height_field='height' ) width = models.IntegerField(verbose_name=_('width'), editable=False) height = models.IntegerField(verbose_name=_('height'), editable=False) created_at = models.DateTimeField(verbose_name=_('created at'), auto_now_add=True, db_index=True) uploaded_by_user = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_('uploaded by user'), null=True, blank=True, editable=False, on_delete=models.SET_NULL ) tags = TaggableManager(help_text=None, blank=True, verbose_name=_('tags')) focal_point_x = models.PositiveIntegerField(null=True, blank=True) focal_point_y = models.PositiveIntegerField(null=True, blank=True) focal_point_width = models.PositiveIntegerField(null=True, blank=True) focal_point_height = models.PositiveIntegerField(null=True, blank=True) file_size = models.PositiveIntegerField(null=True, editable=False) objects = ImageQuerySet.as_manager() def is_stored_locally(self): """ Returns True if the image is hosted on the local filesystem """ try: self.file.path return True except NotImplementedError: return False def get_file_size(self): if self.file_size is None: try: self.file_size = self.file.size except OSError: # File doesn't exist return self.save(update_fields=['file_size']) return self.file_size def get_upload_to(self, filename): folder_name = 'original_images' filename = self.file.field.storage.get_valid_name(filename) # do a unidecode in the filename and then # replace non-ascii characters in filename with _ , to sidestep issues with filesystem encoding filename = "".join((i if ord(i) < 128 else '_') for i in unidecode(filename)) # Truncate filename so it fits in the 100 character limit # https://code.djangoproject.com/ticket/9893 full_path = os.path.join(folder_name, filename) if len(full_path) >= 95: chars_to_trim = len(full_path) - 94 prefix, extension = os.path.splitext(filename) filename = prefix[:-chars_to_trim] + extension full_path = os.path.join(folder_name, filename) return full_path def get_usage(self): return get_object_usage(self) @property def usage_url(self): return reverse('wagtailimages:image_usage', args=(self.id,)) search_fields = CollectionMember.search_fields + [ index.SearchField('title', partial_match=True, boost=10), index.FilterField('title'), index.RelatedFields('tags', [ index.SearchField('name', partial_match=True, boost=10), ]), index.FilterField('uploaded_by_user'), ] def __str__(self): return self.title @contextmanager def get_willow_image(self): # Open file if it is closed close_file = False try: image_file = self.file if self.file.closed: # Reopen the file if self.is_stored_locally(): self.file.open('rb') else: # Some external storage backends don't allow reopening # the file. Get a fresh file instance. #1397 storage = self._meta.get_field('file').storage image_file = storage.open(self.file.name, 'rb') close_file = True except IOError as e: # re-throw this as a SourceImageIOError so that calling code can distinguish # these from IOErrors elsewhere in the process raise SourceImageIOError(str(e)) # Seek to beginning image_file.seek(0) try: yield WillowImage.open(image_file) finally: if close_file: image_file.close() def get_rect(self): return Rect(0, 0, self.width, self.height) def get_focal_point(self): if self.focal_point_x is not None and \ self.focal_point_y is not None and \ self.focal_point_width is not None and \ self.focal_point_height is not None: return Rect.from_point( self.focal_point_x, self.focal_point_y, self.focal_point_width, self.focal_point_height, ) def has_focal_point(self): return self.get_focal_point() is not None def set_focal_point(self, rect): if rect is not None: self.focal_point_x = rect.centroid_x self.focal_point_y = rect.centroid_y self.focal_point_width = rect.width self.focal_point_height = rect.height else: self.focal_point_x = None self.focal_point_y = None self.focal_point_width = None self.focal_point_height = None def get_suggested_focal_point(self): with self.get_willow_image() as willow: faces = willow.detect_faces() if faces: # Create a bounding box around all faces left = min(face[0] for face in faces) top = min(face[1] for face in faces) right = max(face[2] for face in faces) bottom = max(face[3] for face in faces) focal_point = Rect(left, top, right, bottom) else: features = willow.detect_features() if features: # Create a bounding box around all features left = min(feature[0] for feature in features) top = min(feature[1] for feature in features) right = max(feature[0] for feature in features) bottom = max(feature[1] for feature in features) focal_point = Rect(left, top, right, bottom) else: return None # Add 20% to width and height and give it a minimum size x, y = focal_point.centroid width, height = focal_point.size width *= 1.20 height *= 1.20 width = max(width, 100) height = max(height, 100) return Rect.from_point(x, y, width, height) @classmethod def get_rendition_model(cls): """ Get the Rendition model for this Image model """ return cls.renditions.rel.related_model def get_rendition(self, filter): if isinstance(filter, str): filter = Filter(spec=filter) cache_key = filter.get_cache_key(self) Rendition = self.get_rendition_model() try: rendition = self.renditions.get( filter_spec=filter.spec, focal_point_key=cache_key, ) except Rendition.DoesNotExist: # Generate the rendition image generated_image = filter.run(self, BytesIO()) # Generate filename input_filename = os.path.basename(self.file.name) input_filename_without_extension, input_extension = os.path.splitext(input_filename) # A mapping of image formats to extensions FORMAT_EXTENSIONS = { 'jpeg': '.jpg', 'png': '.png', 'gif': '.gif', } output_extension = filter.spec.replace('|', '.') + FORMAT_EXTENSIONS[generated_image.format_name] if cache_key: output_extension = cache_key + '.' + output_extension # Truncate filename to prevent it going over 60 chars output_filename_without_extension = input_filename_without_extension[:(59 - len(output_extension))] output_filename = output_filename_without_extension + '.' + output_extension rendition, created = self.renditions.get_or_create( filter_spec=filter.spec, focal_point_key=cache_key, defaults={'file': File(generated_image.f, name=output_filename)} ) return rendition def is_portrait(self): return (self.width < self.height) def is_landscape(self): return (self.height < self.width) @property def filename(self): return os.path.basename(self.file.name) @property def default_alt_text(self): # by default the alt text field (used in rich text insertion) is populated # from the title. Subclasses might provide a separate alt field, and # override this return self.title def is_editable_by_user(self, user): from wagtail.images.permissions import permission_policy return permission_policy.user_has_permission_for_instance(user, 'change', self) class Meta: abstract = True class Image(AbstractImage): admin_form_fields = ( 'title', 'file', 'collection', 'tags', 'focal_point_x', 'focal_point_y', 'focal_point_width', 'focal_point_height', ) class Filter: """ Represents one or more operations that can be applied to an Image to produce a rendition appropriate for final display on the website. Usually this would be a resize operation, but could potentially involve colour processing, etc. """ def __init__(self, spec=None): # The spec pattern is operation1-var1-var2|operation2-var1 self.spec = spec @cached_property def operations(self): # Search for operations self._search_for_operations() # Build list of operation objects operations = [] for op_spec in self.spec.split('|'): op_spec_parts = op_spec.split('-') if op_spec_parts[0] not in self._registered_operations: raise InvalidFilterSpecError("Unrecognised operation: %s" % op_spec_parts[0]) op_class = self._registered_operations[op_spec_parts[0]] operations.append(op_class(*op_spec_parts)) return operations def run(self, image, output): with image.get_willow_image() as willow: original_format = willow.format_name # Fix orientation of image willow = willow.auto_orient() env = { 'original-format': original_format, } for operation in self.operations: willow = operation.run(willow, image, env) or willow # Find the output format to use if 'output-format' in env: # Developer specified an output format output_format = env['output-format'] else: # Default to outputting in original format output_format = original_format # Convert BMP files to PNG if original_format == 'bmp': output_format = 'png' # Convert unanimated GIFs to PNG as well if original_format == 'gif' and not willow.has_animation(): output_format = 'png' if output_format == 'jpeg': # Allow changing of JPEG compression quality if 'jpeg-quality' in env: quality = env['jpeg-quality'] elif hasattr(settings, 'WAGTAILIMAGES_JPEG_QUALITY'): quality = settings.WAGTAILIMAGES_JPEG_QUALITY else: quality = 85 # If the image has an alpha channel, give it a white background if willow.has_alpha(): willow = willow.set_background_color_rgb((255, 255, 255)) return willow.save_as_jpeg(output, quality=quality, progressive=True, optimize=True) elif output_format == 'png': return willow.save_as_png(output) elif output_format == 'gif': return willow.save_as_gif(output) def get_cache_key(self, image): vary_parts = [] for operation in self.operations: for field in getattr(operation, 'vary_fields', []): value = getattr(image, field, '') vary_parts.append(str(value)) vary_string = '-'.join(vary_parts) # Return blank string if there are no vary fields if not vary_string: return '' return hashlib.sha1(vary_string.encode('utf-8')).hexdigest()[:8] _registered_operations = None @classmethod def _search_for_operations(cls): if cls._registered_operations is not None: return operations = [] for fn in hooks.get_hooks('register_image_operations'): operations.extend(fn()) cls._registered_operations = dict(operations) class AbstractRendition(models.Model): filter_spec = models.CharField(max_length=255, db_index=True) file = models.ImageField(upload_to=get_rendition_upload_to, width_field='width', height_field='height') width = models.IntegerField(editable=False) height = models.IntegerField(editable=False) focal_point_key = models.CharField(max_length=16, blank=True, default='', editable=False) @property def url(self): return self.file.url @property def alt(self): return self.image.title @property def attrs(self): """ The src, width, height, and alt attributes for an <img> tag, as a HTML string """ return flatatt(self.attrs_dict) @property def attrs_dict(self): """ A dict of the src, width, height, and alt attributes for an <img> tag. """ return OrderedDict([ ('src', self.url), ('width', self.width), ('height', self.height), ('alt', self.alt), ]) def img_tag(self, extra_attributes={}): attrs = self.attrs_dict.copy() attrs.update(extra_attributes) return mark_safe('<img{}>'.format(flatatt(attrs))) def __html__(self): return self.img_tag() def get_upload_to(self, filename): folder_name = 'images' filename = self.file.field.storage.get_valid_name(filename) return os.path.join(folder_name, filename) @classmethod def check(cls, **kwargs): errors = super(AbstractRendition, cls).check(**kwargs) if not cls._meta.abstract: if not any( set(constraint) == set(['image', 'filter_spec', 'focal_point_key']) for constraint in cls._meta.unique_together ): errors.append( checks.Error( "Custom rendition model %r has an invalid unique_together setting" % cls, hint="Custom rendition models must include the constraint " "('image', 'filter_spec', 'focal_point_key') in their unique_together definition.", obj=cls, id='wagtailimages.E001', ) ) return errors class Meta: abstract = True class Rendition(AbstractRendition): image = models.ForeignKey(Image, related_name='renditions', on_delete=models.CASCADE) class Meta: unique_together = ( ('image', 'filter_spec', 'focal_point_key'), )
34.110251
111
0.616331
79571e313745fe5e8f743647c9e8bfff7e036f4d
6,857
py
Python
spyder_pylint/pylint.py
stonebig/spyder
3556172888d8bb5dcc5f735676868a0d78d7d604
[ "MIT" ]
1
2016-05-26T13:26:21.000Z
2016-05-26T13:26:21.000Z
spyder_pylint/pylint.py
ShenggaoZhu/spyder
3556172888d8bb5dcc5f735676868a0d78d7d604
[ "MIT" ]
null
null
null
spyder_pylint/pylint.py
ShenggaoZhu/spyder
3556172888d8bb5dcc5f735676868a0d78d7d604
[ "MIT" ]
null
null
null
# -*- coding:utf-8 -*- # # Copyright © Spyder Project Contributors # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) """Pylint Code Analysis Plugin.""" # pylint: disable=C0103 # pylint: disable=R0903 # pylint: disable=R0911 # pylint: disable=R0201 # Standard library imports import os.path as osp # Third party imports from qtpy.QtCore import Qt, Signal, Slot from qtpy.QtWidgets import QGroupBox, QInputDialog, QLabel, QVBoxLayout # Local imports from spyder.config.base import get_translation from spyder.plugins import SpyderPluginMixin from spyder.plugins.configdialog import PluginConfigPage from spyder.utils import icon_manager as ima from spyder.utils.qthelpers import create_action from .widgets.pylintgui import (PYLINT_PATH, PylintWidget) _ = get_translation("pylint", "spyder_pylint") class PylintConfigPage(PluginConfigPage): def setup_page(self): settings_group = QGroupBox(_("Settings")) save_box = self.create_checkbox(_("Save file before analyzing it"), 'save_before', default=True) hist_group = QGroupBox(_("History")) hist_label1 = QLabel(_("The following option will be applied at next " "startup.")) hist_label1.setWordWrap(True) hist_spin = self.create_spinbox(_("History: "), _(" results"), 'max_entries', default=50, min_=10, max_=1000000, step=10) results_group = QGroupBox(_("Results")) results_label1 = QLabel(_("Results are stored here:")) results_label1.setWordWrap(True) # Warning: do not try to regroup the following QLabel contents with # widgets above -- this string was isolated here in a single QLabel # on purpose: to fix Issue 863 results_label2 = QLabel(PylintWidget.DATAPATH) results_label2.setTextInteractionFlags(Qt.TextSelectableByMouse) results_label2.setWordWrap(True) settings_layout = QVBoxLayout() settings_layout.addWidget(save_box) settings_group.setLayout(settings_layout) hist_layout = QVBoxLayout() hist_layout.addWidget(hist_label1) hist_layout.addWidget(hist_spin) hist_group.setLayout(hist_layout) results_layout = QVBoxLayout() results_layout.addWidget(results_label1) results_layout.addWidget(results_label2) results_group.setLayout(results_layout) vlayout = QVBoxLayout() vlayout.addWidget(settings_group) vlayout.addWidget(hist_group) vlayout.addWidget(results_group) vlayout.addStretch(1) self.setLayout(vlayout) class Pylint(PylintWidget, SpyderPluginMixin): """Python source code analysis based on pylint""" CONF_SECTION = 'pylint' CONFIGWIDGET_CLASS = PylintConfigPage edit_goto = Signal(str, int, str) def __init__(self, parent=None): PylintWidget.__init__(self, parent=parent, max_entries=self.get_option('max_entries', 50)) SpyderPluginMixin.__init__(self, parent) # Initialize plugin self.initialize_plugin() #------ SpyderPluginWidget API -------------------------------------------- def get_plugin_title(self): """Return widget title""" return _("Static code analysis") def get_plugin_icon(self): """Return widget icon""" path = osp.join(self.PLUGIN_PATH, self.IMG_PATH) return ima.icon('pylint', icon_path=path) def get_focus_widget(self): """ Return the widget to give focus to when this plugin's dockwidget is raised on top-level """ return self.treewidget def get_plugin_actions(self): """Return a list of actions related to plugin""" # Font history_action = create_action(self, _("History..."), None, ima.icon('history'), _("Set history maximum entries"), triggered=self.change_history_depth) self.treewidget.common_actions += (None, history_action) return [] def on_first_registration(self): """Action to be performed on first plugin registration""" self.main.tabify_plugins(self.main.help, self) self.dockwidget.hide() def register_plugin(self): """Register plugin in Spyder's main window""" self.edit_goto.connect(self.main.editor.load) self.redirect_stdio.connect(self.main.redirect_internalshell_stdio) self.main.add_dockwidget(self) pylint_act = create_action(self, _("Run static code analysis"), triggered=self.run_pylint) pylint_act.setEnabled(PYLINT_PATH is not None) self.register_shortcut(pylint_act, context="Pylint", name="Run analysis") self.main.source_menu_actions += [None, pylint_act] self.main.editor.pythonfile_dependent_actions += [pylint_act] def refresh_plugin(self): """Refresh pylint widget""" self.remove_obsolete_items() def closing_plugin(self, cancelable=False): """Perform actions before parent main window is closed""" return True def apply_plugin_settings(self, options): """Apply configuration file's plugin settings""" # The history depth option will be applied at # next Spyder startup, which is soon enough pass #------ Public API -------------------------------------------------------- @Slot() def change_history_depth(self): "Change history max entries""" depth, valid = QInputDialog.getInteger(self, _('History'), _('Maximum entries'), self.get_option('max_entries'), 10, 10000) if valid: self.set_option('max_entries', depth) @Slot() def run_pylint(self): """Run pylint code analysis""" if self.get_option('save_before', True)\ and not self.main.editor.save(): return self.analyze( self.main.editor.get_current_filename() ) def analyze(self, filename): """Reimplement analyze method""" if self.dockwidget and not self.ismaximized: self.dockwidget.setVisible(True) self.dockwidget.setFocus() self.dockwidget.raise_() PylintWidget.analyze(self, filename)
37.675824
80
0.601575
79571ec46799167719696ed8de7a1fb09e763929
6,647
py
Python
common/wgain_.py
nokia/integratedimputation
ca72bda54cb66e99d79ff0b174cf8f99ccb554ba
[ "BSD-3-Clause" ]
2
2022-01-13T13:05:38.000Z
2022-01-17T10:06:58.000Z
common/wgain_.py
nokia/integratedimputation
ca72bda54cb66e99d79ff0b174cf8f99ccb554ba
[ "BSD-3-Clause" ]
null
null
null
common/wgain_.py
nokia/integratedimputation
ca72bda54cb66e99d79ff0b174cf8f99ccb554ba
[ "BSD-3-Clause" ]
null
null
null
# © 2021 Nokia # # Licensed under the BSD 3 Clause license # SPDX-License-Identifier: BSD-3-Clause # http://proceedings.mlr.press/v80/yoon18a/yoon18a.pdf from defaults import * import utils import numpy as np import torch import torch.autograd as autograd # ============================================================================== # Defs ========================================================================= def calc_gradient_penalty(net_disc, real_data, generated_data, lambda_gp): # Calculate interpolation b_size = real_data.size(0) shape = [b_size] + [1] * (real_data.dim() - 1) alpha = torch.rand(shape, dtype=torch.float32, device=real_data.device) interpolated = alpha * real_data.detach() + (1 - alpha) * generated_data.detach() interpolated.requires_grad_(True) # Calculate scores of interpolated examples score_interpolated = net_disc(interpolated) # Calculate gradients of scores with respect to examples gradients = autograd.grad(outputs=score_interpolated, inputs=interpolated, grad_outputs=torch.ones_like(score_interpolated), create_graph=True, retain_graph=True)[0] # Flatten to easily take norm per example in batch gradients = gradients.view(b_size, -1) # Derivatives of the gradient close to 0 can cause problems because of # the square root, so manually calculate norm and add epsilon gradients_norm = torch.sqrt(torch.sum(gradients ** 2, dim=1) + 1e-12) # Return gradient penalty return(lambda_gp * ((gradients_norm - 1) ** 2).mean()) def evaluate( net_ae, dataloader_test, device, epoch, eval_acc ): for i_mr, missing_rate in enumerate(missing_rates_eval): for j_mt, missing_type in enumerate(missing_types_eval): if missing_type == 'seq': introduceMissingEval = utils.IntroduceMissingSeq(missing_rate) else: introduceMissingEval = utils.IntroduceMissing(missing_rate) with torch.no_grad(): net_ae.eval() for i, data in enumerate(dataloader_test, 0): x, l = data x = x.to(device) # Introduce missingness x_mis, mask = introduceMissingEval(x) # Attach mask to input mask_in = (mask * 2) - 1 # Centering the mask x_mis_in = torch.cat([x_mis, mask_in], dim = 1) # Main forward out = net_ae(x_mis_in) eval_acc.accumulate(x, x_mis, mask, out, l, epoch+1, 2*i_mr + j_mt) def train( alpha, iter_disc, lambda_gp, introduceMissingTrain, net_dict, opt_dict, dataloader_train, dataloader_test, device, eval_every, out_folder, eval_acc, epochs_end = 10, epochs_start = 0 ): if epochs_start != 0: utils.loadAll( net_dict, opt_dict, epochs_start, epoch_digits, out_folder ) net_ae = net_dict["net_ae"] opt_ae = opt_dict["opt_ae"] net_disc = net_dict["net_disc"] opt_disc = opt_dict["opt_disc"] logger = utils.Logger(["l_ae_mis", "l_ae_rec", "l_disc"], epoch_digits, out_folder, epochs_start != 0) for epoch in range(epochs_start, epochs_end): net_ae.train() net_disc.train() for i, data in enumerate(dataloader_train, 0): x, _ = data x = x.to(device) # Introduce missingness, generate noisy input x_mis, mask = introduceMissingTrain(x) # Attach mask to input mask_in = (mask * 2) - 1 # Centering the mask x_mis_in = torch.cat([x_mis, mask_in], dim = 1) # Discriminator ---------------------------------------------------- if introduceMissingTrain.missing_rate is not None and introduceMissingTrain.missing_rate != 0: with torch.no_grad(): out = net_ae(x_mis_in) out_imp = x_mis + ((1 - mask) * out) # Random sample/shuffle inputs perm_both = torch.cat([x.unsqueeze(3), out_imp.unsqueeze(3)], dim = 3) perm_mask = (torch.rand_like(x) > 0.5).to(torch.long).unsqueeze(3) perm_real = torch.gather(perm_both, 3, perm_mask).squeeze(3) perm_fake = torch.gather(perm_both, 3, (1 - perm_mask)).squeeze(3) out_disc_real = net_disc(perm_real) out_disc_fake = net_disc(perm_fake) out_disc_both = torch.cat([out_disc_real.unsqueeze(3), out_disc_fake.unsqueeze(3)], dim = 3) out_disc_real = torch.gather(out_disc_both, 3, perm_mask).squeeze(3) out_disc_fake = torch.gather(out_disc_both, 3, (1 - perm_mask)).squeeze(3) # Losses l_disc_real = -torch.mean((1 - mask) * out_disc_real) l_disc_fake = torch.mean((1 - mask) * out_disc_fake) l_grad_pen = calc_gradient_penalty(net_disc, x, out_imp, lambda_gp) l_disc = l_disc_real + l_disc_fake + l_grad_pen opt_disc.zero_grad() l_disc.backward() opt_disc.step() logger.accumulate([l_disc.item()], [2]) # AE --------------------------------------------------------------- if not (i % iter_disc): out = net_ae(x_mis_in) out_imp = x_mis + ((1 - mask) * out) out_disc_fake = net_disc(out_imp) l_ae_mis = -torch.mean((1 - mask) * out_disc_fake) l_ae_rec = torch.nn.MSELoss()(out, x) l_ae = (alpha * l_ae_rec) + l_ae_mis opt_ae.zero_grad() l_ae.backward() opt_ae.step() logger.accumulate([l_ae_mis.item(), l_ae_rec.item()]) # Eval if not ((epoch + 1) % eval_every): evaluate(net_ae, dataloader_test, device, epoch, eval_acc) logger.log(epoch + 1) eval_acc.log(epoch + 1) # Save utils.saveAll( net_dict, opt_dict, epoch + 1, epoch_digits, out_folder ) print('Finished Training')
34.087179
108
0.529412
79571f285de18d684b88ed9b1dd2751afdce597c
2,138
py
Python
cradmin_legacy/demo/project/demo/urls.py
appressoas/cradmin_legacy
b9d024299333dd04c87c1031bd5be5778aa7f1f1
[ "BSD-3-Clause" ]
null
null
null
cradmin_legacy/demo/project/demo/urls.py
appressoas/cradmin_legacy
b9d024299333dd04c87c1031bd5be5778aa7f1f1
[ "BSD-3-Clause" ]
17
2018-03-07T15:52:42.000Z
2022-03-12T01:07:06.000Z
cradmin_legacy/demo/project/demo/urls.py
appressoas/cradmin_legacy
b9d024299333dd04c87c1031bd5be5778aa7f1f1
[ "BSD-3-Clause" ]
1
2018-07-23T22:13:45.000Z
2018-07-23T22:13:45.000Z
from __future__ import unicode_literals from django.conf import settings from django.urls import path, include from django.contrib import admin from django.views import static from cradmin_legacy.demo.listfilterdemo.cradmin import ListfilterDemoCrAdminInstance from cradmin_legacy.demo.login_not_required_demo.cradmin import LoginNotRequiredCrAdminInstance from cradmin_legacy.demo.multiselect2demo.cradmin import MultiselectDemoCrAdminInstance from cradmin_legacy.demo.no_role_demo.cradmin import NoRoleCrAdminInstance from cradmin_legacy.demo.project.demo.views.demo_overview import DemoView from cradmin_legacy.demo.usermanagerdemo.cradmin import UsermanagerCrAdminInstance from cradmin_legacy.demo.webdemo.cradmin import WebdemoCrAdminInstance from cradmin_legacy.superuserui import superuserui_registry urlpatterns = [ path('authenticate/', include('cradmin_legacy.apps.cradmin_authenticate.urls')), path('resetpassword/', include('cradmin_legacy.apps.cradmin_resetpassword.urls')), path('activate_account/', include('cradmin_legacy.apps.cradmin_activate_account.urls')), path('register/', include('cradmin_legacy.apps.cradmin_register_account.urls')), path('djangoadmin/', admin.site.urls), path('webdemo/', include(WebdemoCrAdminInstance.urls())), path('listfilterdemo/', include(ListfilterDemoCrAdminInstance.urls())), path('multiselect2demo/', include(MultiselectDemoCrAdminInstance.urls())), path('login_not_required_demo/', include(LoginNotRequiredCrAdminInstance.urls())), path('no_role_demo/', include(NoRoleCrAdminInstance.urls())), path('webdemo/', include('cradmin_legacy.demo.webdemo.urls')), path('usermanagerdemo/', include(UsermanagerCrAdminInstance.urls())), path('cradmin_temporaryfileuploadstore/', include('cradmin_legacy.apps.cradmin_temporaryfileuploadstore.urls')), path('', DemoView.as_view()), path('media/<path:path>', static.serve, {'document_root': settings.MEDIA_ROOT}), path('polls/', include('cradmin_legacy.demo.polls_demo.urls')), path('superuser/', include(superuserui_registry.default.make_cradmin_instance_class().urls())), ]
57.783784
116
0.804022
79571fa2d047ee9d6be3b812af21bef2c023596a
7,216
py
Python
nova/api/openstack/compute/contrib/cloudpipe.py
bopopescu/nova_audit
1cd2901802f82d39411adfa04cf2f432ff3bf280
[ "Apache-2.0" ]
1
2020-02-21T19:19:11.000Z
2020-02-21T19:19:11.000Z
nova/api/openstack/compute/contrib/cloudpipe.py
bopopescu/nova_audit
1cd2901802f82d39411adfa04cf2f432ff3bf280
[ "Apache-2.0" ]
null
null
null
nova/api/openstack/compute/contrib/cloudpipe.py
bopopescu/nova_audit
1cd2901802f82d39411adfa04cf2f432ff3bf280
[ "Apache-2.0" ]
1
2020-07-24T09:15:58.000Z
2020-07-24T09:15:58.000Z
# Copyright 2011 OpenStack Foundation # # 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. """Connect your vlan to the world.""" from oslo.config import cfg from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova.api.openstack import xmlutil from nova.cloudpipe import pipelib from nova import compute from nova.compute import utils as compute_utils from nova.compute import vm_states from nova import db from nova import exception from nova import network from nova.openstack.common import fileutils from nova.openstack.common.gettextutils import _ from nova.openstack.common import timeutils from nova import utils CONF = cfg.CONF authorize = extensions.extension_authorizer('compute', 'cloudpipe') class CloudpipeTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('cloudpipe') elem = xmlutil.SubTemplateElement(root, 'instance_id', selector='instance_id') elem.text = str return xmlutil.MasterTemplate(root, 1) class CloudpipesTemplate(xmlutil.TemplateBuilder): def construct(self): root = xmlutil.TemplateElement('cloudpipes') elem1 = xmlutil.SubTemplateElement(root, 'cloudpipe', selector='cloudpipes') elem2 = xmlutil.SubTemplateElement(elem1, xmlutil.Selector(0), selector=xmlutil.get_items) elem2.text = 1 return xmlutil.MasterTemplate(root, 1) class CloudpipeController(object): """Handle creating and listing cloudpipe instances.""" def __init__(self): self.compute_api = compute.API() self.network_api = network.API() self.cloudpipe = pipelib.CloudPipe() self.setup() def setup(self): """Ensure the keychains and folders exist.""" # NOTE(vish): One of the drawbacks of doing this in the api is # the keys will only be on the api node that launched # the cloudpipe. fileutils.ensure_tree(CONF.keys_path) def _get_all_cloudpipes(self, context): """Get all cloudpipes.""" instances = self.compute_api.get_all(context, search_opts={'deleted': False}) return [instance for instance in instances if pipelib.is_vpn_image(instance['image_ref']) and instance['vm_state'] != vm_states.DELETED] def _get_cloudpipe_for_project(self, context, project_id): """Get the cloudpipe instance for a project ID.""" cloudpipes = self._get_all_cloudpipes(context) or [None] return cloudpipes[0] def _get_ip_and_port(self, instance): pass def _vpn_dict(self, context, project_id, instance): elevated = context.elevated() rv = {'project_id': project_id} if not instance: rv['state'] = 'pending' return rv rv['instance_id'] = instance['uuid'] rv['created_at'] = timeutils.isotime(instance['created_at']) nw_info = compute_utils.get_nw_info_for_instance(instance) if not nw_info: return rv vif = nw_info[0] ips = [ip for ip in vif.fixed_ips() if ip['version'] == 4] if ips: rv['internal_ip'] = ips[0]['address'] # NOTE(vish): Currently network_api.get does an owner check on # project_id. This is probably no longer necessary # but rather than risk changes in the db layer, # we are working around it here by changing the # project_id in the context. This can be removed # if we remove the project_id check in the db. elevated.project_id = project_id network = self.network_api.get(elevated, vif['network']['id']) if network: vpn_ip = network['vpn_public_address'] vpn_port = network['vpn_public_port'] rv['public_ip'] = vpn_ip rv['public_port'] = vpn_port if vpn_ip and vpn_port: if utils.vpn_ping(vpn_ip, vpn_port): rv['state'] = 'running' else: rv['state'] = 'down' else: rv['state'] = 'invalid' return rv @wsgi.serializers(xml=CloudpipeTemplate) def create(self, req, body): """Create a new cloudpipe instance, if none exists. Parameters: {cloudpipe: {'project_id': ''}} """ context = req.environ['nova.context'] authorize(context) params = body.get('cloudpipe', {}) project_id = params.get('project_id', context.project_id) # NOTE(vish): downgrade to project context. Note that we keep # the same token so we can still talk to glance context.project_id = project_id context.user_id = 'project-vpn' context.is_admin = False context.roles = [] instance = self._get_cloudpipe_for_project(context, project_id) if not instance: try: result = self.cloudpipe.launch_vpn_instance(context) instance = result[0][0] except db.NoMoreNetworks: msg = _("Unable to claim IP for VPN instances, ensure it " "isn't running, and try again in a few minutes") raise exception.HTTPBadRequest(explanation=msg) return {'instance_id': instance['uuid']} @wsgi.serializers(xml=CloudpipesTemplate) def index(self, req): """List running cloudpipe instances.""" context = req.environ['nova.context'] authorize(context) vpns = [self._vpn_dict(context, x['project_id'], x) for x in self._get_all_cloudpipes(context)] return {'cloudpipes': vpns} class Cloudpipe(extensions.ExtensionDescriptor): """Adds actions to create cloudpipe instances. When running with the Vlan network mode, you need a mechanism to route from the public Internet to your vlans. This mechanism is known as a cloudpipe. At the time of creating this class, only OpenVPN is supported. Support for a SSH Bastion host is forthcoming. """ name = "Cloudpipe" alias = "os-cloudpipe" namespace = "http://docs.openstack.org/compute/ext/cloudpipe/api/v1.1" updated = "2011-12-16T00:00:00+00:00" def get_resources(self): resources = [] res = extensions.ResourceExtension('os-cloudpipe', CloudpipeController()) resources.append(res) return resources
38.588235
79
0.625
7957216755a247acca13b837ab6622179b03d514
2,882
py
Python
tests/integration/backward_compatible/smart_listener_test.py
pabloingino/hazelcast-python-client
96be8576f404ef3bdae263e68b82295a4387aa4e
[ "Apache-2.0" ]
null
null
null
tests/integration/backward_compatible/smart_listener_test.py
pabloingino/hazelcast-python-client
96be8576f404ef3bdae263e68b82295a4387aa4e
[ "Apache-2.0" ]
null
null
null
tests/integration/backward_compatible/smart_listener_test.py
pabloingino/hazelcast-python-client
96be8576f404ef3bdae263e68b82295a4387aa4e
[ "Apache-2.0" ]
null
null
null
from tests.base import HazelcastTestCase from tests.util import random_string, event_collector from time import sleep class SmartListenerTest(HazelcastTestCase): @classmethod def setUpClass(cls): cls.rc = cls.create_rc() cls.cluster = cls.create_cluster(cls.rc, None) cls.m1 = cls.cluster.start_member() cls.m2 = cls.cluster.start_member() cls.m3 = cls.cluster.start_member() @classmethod def tearDownClass(cls): cls.rc.exit() def setUp(self): self.client = self.create_client( { "cluster_name": self.cluster.id, "smart_routing": True, } ) self.collector = event_collector() def tearDown(self): self.shutdown_all_clients() # -------------------------- test_local_only ----------------------- # def test_list_smart_listener_local_only(self): list = self.client.get_list(random_string()).blocking() list.add_listener(item_added_func=self.collector) list.add("item-value") sleep(5) self.assertEqual(1, len(self.collector.events)) def test_map_smart_listener_local_only(self): map = self.client.get_map(random_string()).blocking() map.add_entry_listener(added_func=self.collector) map.put("key", "value") sleep(5) self.assertEqual(1, len(self.collector.events)) def test_multimap_smart_listener_local_only(self): multimap = self.client.get_map(random_string()).blocking() multimap.add_entry_listener(added_func=self.collector) multimap.put("key", "value") sleep(5) self.assertEqual(1, len(self.collector.events)) def test_queue_smart_listener_local_only(self): queue = self.client.get_queue(random_string()).blocking() queue.add_listener(item_added_func=self.collector) queue.add("item-value") sleep(5) self.assertEqual(1, len(self.collector.events)) def test_replicated_map_smart_listener_local_only(self): replicated_map = self.client.get_replicated_map(random_string()).blocking() replicated_map.add_entry_listener(added_func=self.collector) replicated_map.put("key", "value") sleep(5) self.assertEqual(1, len(self.collector.events)) def test_set_smart_listener_local_only(self): set = self.client.get_set(random_string()).blocking() set.add_listener(item_added_func=self.collector) set.add("item-value") sleep(5) self.assertEqual(1, len(self.collector.events)) def test_topic_smart_listener_local_only(self): topic = self.client.get_topic(random_string()).blocking() topic.add_listener(on_message=self.collector) topic.publish("item-value") sleep(5) self.assertEqual(1, len(self.collector.events))
36.025
83
0.656142
79572189589cbd1019da5370252a79e5b69de813
1,229
py
Python
tools/MakeAllIntoOne.py
Nadern96/Realtime-Action-Recognition
63db3f650909b0428acff94d59b3d3dd1803c676
[ "MIT" ]
null
null
null
tools/MakeAllIntoOne.py
Nadern96/Realtime-Action-Recognition
63db3f650909b0428acff94d59b3d3dd1803c676
[ "MIT" ]
null
null
null
tools/MakeAllIntoOne.py
Nadern96/Realtime-Action-Recognition
63db3f650909b0428acff94d59b3d3dd1803c676
[ "MIT" ]
null
null
null
import os import json path = r"../data_proc/raw_skeletons/numbered/" f= open("../data_proc/raw_skeletons/skeletons_info.txt", 'w+') Classes = {'clap':1, 'hit':2, 'jump':3, 'kick':4, 'punch':5, 'push':6, 'run':7, 'shake':8, 'sit':9, 'situp':10, 'stand':11, 'turn':12, 'walk':13, 'wave':14, } count = 0 full = [] labesls = {} ImageCount = 0 for subdir, dirs, files in os.walk(path,topdown=True): files.sort() files = sorted(files, key= lambda x: int(x.replace('.txt',''))) for file in files: itemCount = 0 count += 1 print("proccessing file#" + file) pathtofile = os.path.join(subdir,file) with open(pathtofile) as f: items = json.load(f) labesls[items[0][3]] = 0 for item in items: # print(item) item[2] = int(item[2]) + ImageCount itemCount += 1 full.append(item) ImageCount += itemCount +1 print(labesls) with open('../data_proc/raw_skeletons/skeletons_info.txt', 'w+') as outfile: json.dump(full, outfile)
22.759259
76
0.497152
795722381a7ef827c9276d3096b13566e9606f57
177
py
Python
50.powx-n/solution.py
tsonglew/leetcode-solution
abce0c36def55a8d3bf86fca531246a29920e771
[ "Unlicense" ]
null
null
null
50.powx-n/solution.py
tsonglew/leetcode-solution
abce0c36def55a8d3bf86fca531246a29920e771
[ "Unlicense" ]
null
null
null
50.powx-n/solution.py
tsonglew/leetcode-solution
abce0c36def55a8d3bf86fca531246a29920e771
[ "Unlicense" ]
null
null
null
#!/usr/bin/python3 class Solution: def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ return pow(x, n)
17.7
26
0.446328
795722b4c9d6ba838606113cae7e20e4a2dddb48
56,726
py
Python
google/cloud/compute_v1/services/reservations/client.py
vam-google/python-compute
799f2f55e5e205317862a17ca7ed548ce2ca66e5
[ "Apache-2.0" ]
19
2021-02-10T21:17:20.000Z
2022-02-20T03:16:36.000Z
google/cloud/compute_v1/services/reservations/client.py
vam-google/python-compute
799f2f55e5e205317862a17ca7ed548ce2ca66e5
[ "Apache-2.0" ]
121
2021-01-08T23:46:58.000Z
2022-03-26T04:34:36.000Z
google/cloud/compute_v1/services/reservations/client.py
vam-google/python-compute
799f2f55e5e205317862a17ca7ed548ce2ca66e5
[ "Apache-2.0" ]
20
2021-01-08T23:14:16.000Z
2022-02-25T01:27:20.000Z
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from collections import OrderedDict from distutils import util import os import re from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.compute_v1.services.reservations import pagers from google.cloud.compute_v1.types import compute from .transports.base import ReservationsTransport, DEFAULT_CLIENT_INFO from .transports.rest import ReservationsRestTransport class ReservationsClientMeta(type): """Metaclass for the Reservations client. This provides class-level methods for building and retrieving support objects (e.g. transport) without polluting the client instance objects. """ _transport_registry = OrderedDict() # type: Dict[str, Type[ReservationsTransport]] _transport_registry["rest"] = ReservationsRestTransport def get_transport_class(cls, label: str = None,) -> Type[ReservationsTransport]: """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values())) class ReservationsClient(metaclass=ReservationsClientMeta): """The Reservations API.""" @staticmethod def _get_default_mtls_endpoint(api_endpoint): """Converts api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint mtls_endpoint_re = re.compile( r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" ) m = mtls_endpoint_re.match(api_endpoint) name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint if sandbox: return api_endpoint.replace( "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" ) return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") DEFAULT_ENDPOINT = "compute.googleapis.com" DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials info. Args: info (dict): The service account private key info. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: ReservationsClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_info(info) kwargs["credentials"] = credentials return cls(*args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: ReservationsClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs) from_service_account_json = from_service_account_file @property def transport(self) -> ReservationsTransport: """Returns the transport used by the client instance. Returns: ReservationsTransport: The transport used by the client instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @staticmethod def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_folder_path(folder: str,) -> str: """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod def parse_common_folder_path(path: str) -> Dict[str, str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P<folder>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_organization_path(organization: str,) -> str: """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod def parse_common_organization_path(path: str) -> Dict[str, str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P<organization>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_project_path(project: str,) -> str: """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod def parse_common_project_path(path: str) -> Dict[str, str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_location_path(project: str, location: str,) -> str: """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @staticmethod def parse_common_location_path(path: str) -> Dict[str, str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) return m.groupdict() if m else {} def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, ReservationsTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the reservations client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, ReservationsTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint) and "auto" (auto switch to the default mTLS endpoint if client certificate is present, this is the default value). However, the ``api_endpoint`` property takes precedence if provided. (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used to provide client certificate for mutual TLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. use_client_cert = bool( util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) ) client_cert_source_func = None is_mtls = False if use_client_cert: if client_options.client_cert_source: is_mtls = True client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() if is_mtls: client_cert_source_func = mtls.default_client_cert_source() else: client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint else: use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": if is_mtls: api_endpoint = self.DEFAULT_MTLS_ENDPOINT else: api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " "values: never, auto, always" ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, ReservationsTransport): # transport is a ReservationsTransport instance. if credentials or client_options.credentials_file: raise ValueError( "When providing a transport instance, " "provide its credentials directly." ) if client_options.scopes: raise ValueError( "When providing a transport instance, provide its scopes " "directly." ) self._transport = transport else: Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, credentials_file=client_options.credentials_file, host=api_endpoint, scopes=client_options.scopes, client_cert_source_for_mtls=client_cert_source_func, quota_project_id=client_options.quota_project_id, client_info=client_info, ) def aggregated_list( self, request: compute.AggregatedListReservationsRequest = None, *, project: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.AggregatedListPager: r"""Retrieves an aggregated list of reservations. Args: request (google.cloud.compute_v1.types.AggregatedListReservationsRequest): The request object. A request message for Reservations.AggregatedList. See the method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.compute_v1.services.reservations.pagers.AggregatedListPager: Contains a list of reservations. Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([project]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a compute.AggregatedListReservationsRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, compute.AggregatedListReservationsRequest): request = compute.AggregatedListReservationsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: request.project = project # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.aggregated_list] # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.AggregatedListPager( method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. return response def delete( self, request: compute.DeleteReservationRequest = None, *, project: str = None, zone: str = None, reservation: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Deletes the specified reservation. Args: request (google.cloud.compute_v1.types.DeleteReservationRequest): The request object. A request message for Reservations.Delete. See the method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field on the ``request`` instance; if ``request`` is provided, this should not be set. zone (str): Name of the zone for this request. This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. reservation (str): Name of the reservation to delete. This corresponds to the ``reservation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.compute_v1.types.Operation: Represents an Operation resource. Google Compute Engine has three Operation resources: - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) \* [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) \* [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) You can use an operation resource to manage asynchronous API requests. For more information, read Handling API responses. Operations can be global, regional or zonal. - For global operations, use the globalOperations resource. - For regional operations, use the regionOperations resource. - For zonal operations, use the zonalOperations resource. For more information, read Global, Regional, and Zonal Resources. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([project, zone, reservation]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a compute.DeleteReservationRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, compute.DeleteReservationRequest): request = compute.DeleteReservationRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: request.project = project if zone is not None: request.zone = zone if reservation is not None: request.reservation = reservation # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.delete] # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response def get( self, request: compute.GetReservationRequest = None, *, project: str = None, zone: str = None, reservation: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Reservation: r"""Retrieves information about the specified reservation. Args: request (google.cloud.compute_v1.types.GetReservationRequest): The request object. A request message for Reservations.Get. See the method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field on the ``request`` instance; if ``request`` is provided, this should not be set. zone (str): Name of the zone for this request. This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. reservation (str): Name of the reservation to retrieve. This corresponds to the ``reservation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.compute_v1.types.Reservation: Represents a reservation resource. A reservation ensures that capacity is held in a specific zone even if the reserved VMs are not running. For more information, read Reserving zonal resources. (== resource_for {$api_version}.reservations ==) """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([project, zone, reservation]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a compute.GetReservationRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, compute.GetReservationRequest): request = compute.GetReservationRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: request.project = project if zone is not None: request.zone = zone if reservation is not None: request.reservation = reservation # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.get] # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response def get_iam_policy( self, request: compute.GetIamPolicyReservationRequest = None, *, project: str = None, zone: str = None, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Policy: r"""Gets the access control policy for a resource. May be empty if no such policy or resource exists. Args: request (google.cloud.compute_v1.types.GetIamPolicyReservationRequest): The request object. A request message for Reservations.GetIamPolicy. See the method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field on the ``request`` instance; if ``request`` is provided, this should not be set. zone (str): The name of the zone for this request. This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. resource (str): Name or id of the resource for this request. This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.compute_v1.types.Policy: An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A Policy is a collection of bindings. A binding binds one or more members to a single role. Members can be user accounts, service accounts, Google groups, and domains (such as G Suite). A role is a named list of permissions; each role can be an IAM predefined role or a user-created custom role. For some types of Google Cloud resources, a binding can also specify a condition, which is a logical expression that allows access to a resource only if the expression evaluates to true. A condition can add constraints based on attributes of the request, the resource, or both. To learn which resources support conditions in their IAM policies, see the [IAM documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 } **YAML example:** bindings: - members: - user:\ mike@example.com - group:\ admins@example.com - domain:google.com - serviceAccount:\ my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:\ eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - etag: BwWWja0YfJA= - version: 3 For a description of IAM and its features, see the [IAM documentation](\ https://cloud.google.com/iam/docs/). """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([project, zone, resource]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a compute.GetIamPolicyReservationRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, compute.GetIamPolicyReservationRequest): request = compute.GetIamPolicyReservationRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: request.project = project if zone is not None: request.zone = zone if resource is not None: request.resource = resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response def insert( self, request: compute.InsertReservationRequest = None, *, project: str = None, zone: str = None, reservation_resource: compute.Reservation = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Creates a new reservation. For more information, read Reserving zonal resources. Args: request (google.cloud.compute_v1.types.InsertReservationRequest): The request object. A request message for Reservations.Insert. See the method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field on the ``request`` instance; if ``request`` is provided, this should not be set. zone (str): Name of the zone for this request. This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. reservation_resource (google.cloud.compute_v1.types.Reservation): The body resource for this request This corresponds to the ``reservation_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.compute_v1.types.Operation: Represents an Operation resource. Google Compute Engine has three Operation resources: - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) \* [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) \* [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) You can use an operation resource to manage asynchronous API requests. For more information, read Handling API responses. Operations can be global, regional or zonal. - For global operations, use the globalOperations resource. - For regional operations, use the regionOperations resource. - For zonal operations, use the zonalOperations resource. For more information, read Global, Regional, and Zonal Resources. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([project, zone, reservation_resource]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a compute.InsertReservationRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, compute.InsertReservationRequest): request = compute.InsertReservationRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: request.project = project if zone is not None: request.zone = zone if reservation_resource is not None: request.reservation_resource = reservation_resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.insert] # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response def list( self, request: compute.ListReservationsRequest = None, *, project: str = None, zone: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListPager: r"""A list of all the reservations that have been configured for the specified project in specified zone. Args: request (google.cloud.compute_v1.types.ListReservationsRequest): The request object. A request message for Reservations.List. See the method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field on the ``request`` instance; if ``request`` is provided, this should not be set. zone (str): Name of the zone for this request. This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.compute_v1.services.reservations.pagers.ListPager: Iterating over this object will yield results and resolve additional pages automatically. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([project, zone]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a compute.ListReservationsRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, compute.ListReservationsRequest): request = compute.ListReservationsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: request.project = project if zone is not None: request.zone = zone # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.list] # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListPager( method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. return response def resize( self, request: compute.ResizeReservationRequest = None, *, project: str = None, zone: str = None, reservation: str = None, reservations_resize_request_resource: compute.ReservationsResizeRequest = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Operation: r"""Resizes the reservation (applicable to standalone reservations only). For more information, read Modifying reservations. Args: request (google.cloud.compute_v1.types.ResizeReservationRequest): The request object. A request message for Reservations.Resize. See the method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field on the ``request`` instance; if ``request`` is provided, this should not be set. zone (str): Name of the zone for this request. This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. reservation (str): Name of the reservation to update. This corresponds to the ``reservation`` field on the ``request`` instance; if ``request`` is provided, this should not be set. reservations_resize_request_resource (google.cloud.compute_v1.types.ReservationsResizeRequest): The body resource for this request This corresponds to the ``reservations_resize_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.compute_v1.types.Operation: Represents an Operation resource. Google Compute Engine has three Operation resources: - [Global](/compute/docs/reference/rest/{$api_version}/globalOperations) \* [Regional](/compute/docs/reference/rest/{$api_version}/regionOperations) \* [Zonal](/compute/docs/reference/rest/{$api_version}/zoneOperations) You can use an operation resource to manage asynchronous API requests. For more information, read Handling API responses. Operations can be global, regional or zonal. - For global operations, use the globalOperations resource. - For regional operations, use the regionOperations resource. - For zonal operations, use the zonalOperations resource. For more information, read Global, Regional, and Zonal Resources. (== resource_for {$api_version}.globalOperations ==) (== resource_for {$api_version}.regionOperations ==) (== resource_for {$api_version}.zoneOperations ==) """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any( [project, zone, reservation, reservations_resize_request_resource] ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a compute.ResizeReservationRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, compute.ResizeReservationRequest): request = compute.ResizeReservationRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: request.project = project if zone is not None: request.zone = zone if reservation is not None: request.reservation = reservation if reservations_resize_request_resource is not None: request.reservations_resize_request_resource = ( reservations_resize_request_resource ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.resize] # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response def set_iam_policy( self, request: compute.SetIamPolicyReservationRequest = None, *, project: str = None, zone: str = None, resource: str = None, zone_set_policy_request_resource: compute.ZoneSetPolicyRequest = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.Policy: r"""Sets the access control policy on the specified resource. Replaces any existing policy. Args: request (google.cloud.compute_v1.types.SetIamPolicyReservationRequest): The request object. A request message for Reservations.SetIamPolicy. See the method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field on the ``request`` instance; if ``request`` is provided, this should not be set. zone (str): The name of the zone for this request. This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. resource (str): Name or id of the resource for this request. This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. zone_set_policy_request_resource (google.cloud.compute_v1.types.ZoneSetPolicyRequest): The body resource for this request This corresponds to the ``zone_set_policy_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.compute_v1.types.Policy: An Identity and Access Management (IAM) policy, which specifies access controls for Google Cloud resources. A Policy is a collection of bindings. A binding binds one or more members to a single role. Members can be user accounts, service accounts, Google groups, and domains (such as G Suite). A role is a named list of permissions; each role can be an IAM predefined role or a user-created custom role. For some types of Google Cloud resources, a binding can also specify a condition, which is a logical expression that allows access to a resource only if the expression evaluates to true. A condition can add constraints based on attributes of the request, the resource, or both. To learn which resources support conditions in their IAM policies, see the [IAM documentation](\ https://cloud.google.com/iam/help/conditions/resource-policies). **JSON example:** { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 } **YAML example:** bindings: - members: - user:\ mike@example.com - group:\ admins@example.com - domain:google.com - serviceAccount:\ my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:\ eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - etag: BwWWja0YfJA= - version: 3 For a description of IAM and its features, see the [IAM documentation](\ https://cloud.google.com/iam/docs/). """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any( [project, zone, resource, zone_set_policy_request_resource] ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a compute.SetIamPolicyReservationRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, compute.SetIamPolicyReservationRequest): request = compute.SetIamPolicyReservationRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: request.project = project if zone is not None: request.zone = zone if resource is not None: request.resource = resource if zone_set_policy_request_resource is not None: request.zone_set_policy_request_resource = ( zone_set_policy_request_resource ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response def test_iam_permissions( self, request: compute.TestIamPermissionsReservationRequest = None, *, project: str = None, zone: str = None, resource: str = None, test_permissions_request_resource: compute.TestPermissionsRequest = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> compute.TestPermissionsResponse: r"""Returns permissions that a caller has on the specified resource. Args: request (google.cloud.compute_v1.types.TestIamPermissionsReservationRequest): The request object. A request message for Reservations.TestIamPermissions. See the method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field on the ``request`` instance; if ``request`` is provided, this should not be set. zone (str): The name of the zone for this request. This corresponds to the ``zone`` field on the ``request`` instance; if ``request`` is provided, this should not be set. resource (str): Name or id of the resource for this request. This corresponds to the ``resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. test_permissions_request_resource (google.cloud.compute_v1.types.TestPermissionsRequest): The body resource for this request This corresponds to the ``test_permissions_request_resource`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.cloud.compute_v1.types.TestPermissionsResponse: """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any( [project, zone, resource, test_permissions_request_resource] ) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) # Minor optimization to avoid making a copy if the user passes # in a compute.TestIamPermissionsReservationRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, compute.TestIamPermissionsReservationRequest): request = compute.TestIamPermissionsReservationRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: request.project = project if zone is not None: request.zone = zone if resource is not None: request.resource = resource if test_permissions_request_resource is not None: request.test_permissions_request_resource = ( test_permissions_request_resource ) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] # Send the request. response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-compute",).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() __all__ = ("ReservationsClient",)
44.525903
107
0.600871
79572325fe643242e7bbec75c340edd2d1e870d4
5,088
py
Python
care/facility/models/patient_consultation.py
biwin/care
45063dc8f37272cbb27c69db9157a3aad4181e53
[ "MIT" ]
null
null
null
care/facility/models/patient_consultation.py
biwin/care
45063dc8f37272cbb27c69db9157a3aad4181e53
[ "MIT" ]
null
null
null
care/facility/models/patient_consultation.py
biwin/care
45063dc8f37272cbb27c69db9157a3aad4181e53
[ "MIT" ]
null
null
null
from django.db import models from multiselectfield import MultiSelectField from care.facility.models import CATEGORY_CHOICES, PatientBaseModel from care.facility.models.mixins.permissions.patient import PatientRelatedPermissionMixin from care.facility.models.patient_base import ADMIT_CHOICES, CURRENT_HEALTH_CHOICES, SYMPTOM_CHOICES, SuggestionChoices from care.users.models import User class PatientConsultation(PatientBaseModel, PatientRelatedPermissionMixin): SUGGESTION_CHOICES = [ (SuggestionChoices.HI, "HOME ISOLATION"), (SuggestionChoices.A, "ADMISSION"), (SuggestionChoices.R, "REFERRAL"), ] patient = models.ForeignKey("PatientRegistration", on_delete=models.CASCADE, related_name="consultations") facility = models.ForeignKey("Facility", on_delete=models.CASCADE, related_name="consultations") symptoms = MultiSelectField(choices=SYMPTOM_CHOICES, default=1, null=True, blank=True) other_symptoms = models.TextField(default="", blank=True) symptoms_onset_date = models.DateTimeField(null=True, blank=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=8, default=None, blank=True, null=True) examination_details = models.TextField(null=True, blank=True) existing_medication = models.TextField(null=True, blank=True) prescribed_medication = models.TextField(null=True, blank=True) suggestion = models.CharField(max_length=3, choices=SUGGESTION_CHOICES) referred_to = models.ForeignKey( "Facility", null=True, blank=True, on_delete=models.PROTECT, related_name="referred_patients", ) admitted = models.BooleanField(default=False) admitted_to = models.IntegerField(choices=ADMIT_CHOICES, default=None, null=True, blank=True) admission_date = models.DateTimeField(null=True, blank=True) discharge_date = models.DateTimeField(null=True, blank=True) bed_number = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return f"{self.patient.name}<>{self.facility.name}" def save(self, *args, **kwargs): if not self.pk or self.referred_to is not None: # pk is None when the consultation is created # referred to is not null when the person is being referred to a new facility self.patient.facility = self.referred_to or self.facility self.patient.save() super(PatientConsultation, self).save(*args, **kwargs) class Meta: constraints = [ models.CheckConstraint( name="if_referral_suggested", check=~models.Q(suggestion=SuggestionChoices.R) | models.Q(referred_to__isnull=False), ), models.CheckConstraint( name="if_admitted", check=models.Q(admitted=False) | models.Q(admission_date__isnull=False), ), ] class DailyRound(models.Model): consultation = models.ForeignKey(PatientConsultation, on_delete=models.PROTECT, related_name="daily_rounds") temperature = models.DecimalField(max_digits=5, decimal_places=2, blank=True, default=0) temperature_measured_at = models.DateTimeField(null=True, blank=True) physical_examination_info = models.TextField(null=True, blank=True) additional_symptoms = MultiSelectField(choices=SYMPTOM_CHOICES, default=1, null=True, blank=True) other_symptoms = models.TextField(default="", blank=True) patient_category = models.CharField(choices=CATEGORY_CHOICES, max_length=8, default=None, blank=True, null=True) current_health = models.IntegerField(default=0, choices=CURRENT_HEALTH_CHOICES, blank=True) recommend_discharge = models.BooleanField(default=False, verbose_name="Recommend Discharging Patient") other_details = models.TextField(null=True, blank=True) @staticmethod def has_write_permission(request): return request.user.is_superuser or ( request.user.user_type >= User.TYPE_VALUE_MAP["Staff"] and ( PatientConsultation.objects.get( external_id=request.parser_context["kwargs"]["consultation_external_id"] ).facility.created_by == request.user ) ) @staticmethod def has_read_permission(request): return request.user.is_superuser or ( request.user.user_type >= User.TYPE_VALUE_MAP["Staff"] and ( PatientConsultation.objects.get( external_id=request.parser_context["kwargs"]["consultation_external_id"] ).facility.created_by == request.user ) ) def has_object_read_permission(self, request): return request.user.is_superuser or request.user in ( self.consultation.facility.created_by, self.consultation.patient.created_by, ) def has_object_write_permission(self, request): return request.user.is_superuser or request.user in ( self.consultation.facility.created_by, self.consultation.patient.created_by, )
47.551402
119
0.705582
795723714301151d6c05e622070708442b560840
4,867
py
Python
src/selfcoin/common/ellipticcurve/math.py
wangyubin112/selfcoin
f53528645f7d500108c7a258f07a2551f933ce7b
[ "MIT" ]
null
null
null
src/selfcoin/common/ellipticcurve/math.py
wangyubin112/selfcoin
f53528645f7d500108c7a258f07a2551f933ce7b
[ "MIT" ]
null
null
null
src/selfcoin/common/ellipticcurve/math.py
wangyubin112/selfcoin
f53528645f7d500108c7a258f07a2551f933ce7b
[ "MIT" ]
null
null
null
from binascii import hexlify def multiply(Xp, Yp, n, N, A, P): """ Fast way to multily point and scalar in elliptic curves :param (Xp,Yp,Zp): First Point to mutiply :param n: Scalar to mutiply :param N: Order of the elliptic curve :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :param A: Coefficient of the first-order term of the equation Y^2 = X^3 + A*X + B (mod p) :return: Point that represents the sum of First and Second Point """ return fromJacobian(*(jacobianMultiply(*(toJacobian(Xp, Yp)), n, N, A, P)), P) def add(a_Xp, a_Yp, b_Xp, b_Yp, A, P): """ Fast way to add two points in elliptic curves :param a(Xp, Yp): First Point you want to add :param b: Second Point you want to add :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :param A: Coefficient of the first-order term of the equation Y^2 = X^3 + A*X + B (mod p) :return: Point that represents the sum of First and Second Point """ return fromJacobian(*(jacobianAdd(*(toJacobian(a_Xp, a_Yp)), *(toJacobian(b_Xp, b_Yp)), A, P)), P) def inv(a, n): """ Extended Euclidean Algorithm. It's the 'division' in elliptic curves :param a: Divisor :param n: Mod for division :return: Value representing the division """ if a == 0: return 0 lm, hm = 1, 0 low, high = a % n, n while low > 1: r = high//low nm, new = hm-lm*r, high-low*r lm, low, hm, high = nm, new, lm, low return lm % n def toJacobian(Xp, Yp): """ Convert point to Jacobian coordinates :param (Xp,Yp,Zp): First Point you want to add :return: Point in Jacobian coordinates """ return Xp, Yp, 1 def fromJacobian(Xp, Yp, Zp, P): """ Convert point back from Jacobian coordinates :param (Xp,Yp,Zp): First Point you want to add :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :return: Point in default coordinates """ z = inv(Zp, P) return (Xp * z**2) % P, (Yp * z**3) % P def jacobianDouble(Xp, Yp, Zp, A, P): """ Double a point in elliptic curves :param (Xp,Yp,Zp): Point you want to double :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :param A: Coefficient of the first-order term of the equation Y^2 = X^3 + A*X + B (mod p) :return: Point that represents the sum of First and Second Point """ if not Yp: return (0, 0, 0) ysq = (Yp ** 2) % P S = (4 * Xp * ysq) % P M = (3 * Xp ** 2 + A * Zp ** 4) % P nx = (M**2 - 2 * S) % P ny = (M * (S - nx) - 8 * ysq ** 2) % P nz = (2 * Yp * Zp) % P return nx, ny, nz def jacobianAdd(Xp, Yp, Zp, Xq, Yq, Zq, A, P): """ Add two points in elliptic curves :param (Xp,Yp,Zp): First Point you want to add :param (Xq,Yq,Zq): Second Point you want to add :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :param A: Coefficient of the first-order term of the equation Y^2 = X^3 + A*X + B (mod p) :return: Point that represents the sum of First and Second Point """ if not Yp: return (Xq, Yq, Zq) if not Yq: return (Xp, Yp, Zp) U1 = (Xp * Zq ** 2) % P U2 = (Xq * Zp ** 2) % P S1 = (Yp * Zq ** 3) % P S2 = (Yq * Zp ** 3) % P if U1 == U2: if S1 != S2: return (0, 0, 1) return jacobianDouble(Xp, Yp, Zp, A, P) H = U2 - U1 R = S2 - S1 H2 = (H * H) % P H3 = (H * H2) % P U1H2 = (U1 * H2) % P nx = (R ** 2 - H3 - 2 * U1H2) % P ny = (R * (U1H2 - nx) - S1 * H3) % P nz = (H * Zp * Zq) % P return nx, ny, nz def jacobianMultiply(Xp, Yp, Zp, n, N, A, P): """ Multily point and scalar in elliptic curves :param (Xp,Yp,Zp): First Point to mutiply :param n: Scalar to mutiply :param N: Order of the elliptic curve :param P: Prime number in the module of the equation Y^2 = X^3 + A*X + B (mod p) :param A: Coefficient of the first-order term of the equation Y^2 = X^3 + A*X + B (mod p) :return: Point that represents the sum of First and Second Point """ if Yp == 0 or n == 0: return (0, 0, 1) if n == 1: return (Xp, Yp, Zp) if n < 0 or n >= N: return jacobianMultiply(Xp, Yp, Zp, n % N, N, A, P) if (n % 2) == 0: return jacobianDouble(*(jacobianMultiply(*(Xp, Yp, Zp), n // 2, N, A, P)), A, P) if (n % 2) == 1: return jacobianAdd(*(jacobianDouble(*(jacobianMultiply(Xp, Yp, Zp, n // 2, N, A, P)), A, P)), *(Xp, Yp, Zp), A, P) def numberFrom(string): """ Get a number representation of a string :param String to be converted in a number :return: Number in hex from string """ return int(hexlify(string), 16)
31.4
122
0.564619
795723f6f9b51fb56b78e60538a7ac01f0b3d67e
367
py
Python
crowdsourcing/serializers/requester.py
ramcn/demo2
e5115d2354c2890ba004abedfe0d60c1bf602d5d
[ "MIT" ]
null
null
null
crowdsourcing/serializers/requester.py
ramcn/demo2
e5115d2354c2890ba004abedfe0d60c1bf602d5d
[ "MIT" ]
null
null
null
crowdsourcing/serializers/requester.py
ramcn/demo2
e5115d2354c2890ba004abedfe0d60c1bf602d5d
[ "MIT" ]
null
null
null
__author__ = 'elsabakiu' from crowdsourcing import models from datetime import datetime from rest_framework import serializers import json class RequesterSerializer(serializers.ModelSerializer): class Meta: model = models.Requester class RequesterRankingSerializer(serializers.ModelSerializer): class Meta: model = models.RequesterRanking
22.9375
62
0.792916
7957262be48f74d4e3b44c13532b3717a36da54a
7,421
py
Python
blink/biencoder/biencoder.py
pbmstrk/BLINK
7380cf7d63ff76563f017adc39fa5729ba36742a
[ "MIT" ]
865
2019-10-02T21:30:49.000Z
2022-03-30T08:02:31.000Z
blink/biencoder/biencoder.py
pbmstrk/BLINK
7380cf7d63ff76563f017adc39fa5729ba36742a
[ "MIT" ]
96
2019-12-01T02:22:51.000Z
2022-03-11T15:32:16.000Z
blink/biencoder/biencoder.py
pbmstrk/BLINK
7380cf7d63ff76563f017adc39fa5729ba36742a
[ "MIT" ]
167
2019-10-12T00:34:28.000Z
2022-03-27T14:24:44.000Z
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from tqdm import tqdm from pytorch_transformers.modeling_bert import ( BertPreTrainedModel, BertConfig, BertModel, ) from pytorch_transformers.tokenization_bert import BertTokenizer from blink.common.ranker_base import BertEncoder, get_model_obj from blink.common.optimizer import get_bert_optimizer def load_biencoder(params): # Init model biencoder = BiEncoderRanker(params) return biencoder class BiEncoderModule(torch.nn.Module): def __init__(self, params): super(BiEncoderModule, self).__init__() ctxt_bert = BertModel.from_pretrained(params["bert_model"]) cand_bert = BertModel.from_pretrained(params['bert_model']) self.context_encoder = BertEncoder( ctxt_bert, params["out_dim"], layer_pulled=params["pull_from_layer"], add_linear=params["add_linear"], ) self.cand_encoder = BertEncoder( cand_bert, params["out_dim"], layer_pulled=params["pull_from_layer"], add_linear=params["add_linear"], ) self.config = ctxt_bert.config def forward( self, token_idx_ctxt, segment_idx_ctxt, mask_ctxt, token_idx_cands, segment_idx_cands, mask_cands, ): embedding_ctxt = None if token_idx_ctxt is not None: embedding_ctxt = self.context_encoder( token_idx_ctxt, segment_idx_ctxt, mask_ctxt ) embedding_cands = None if token_idx_cands is not None: embedding_cands = self.cand_encoder( token_idx_cands, segment_idx_cands, mask_cands ) return embedding_ctxt, embedding_cands class BiEncoderRanker(torch.nn.Module): def __init__(self, params, shared=None): super(BiEncoderRanker, self).__init__() self.params = params self.device = torch.device( "cuda" if torch.cuda.is_available() and not params["no_cuda"] else "cpu" ) self.n_gpu = torch.cuda.device_count() # init tokenizer self.NULL_IDX = 0 self.START_TOKEN = "[CLS]" self.END_TOKEN = "[SEP]" self.tokenizer = BertTokenizer.from_pretrained( params["bert_model"], do_lower_case=params["lowercase"] ) # init model self.build_model() model_path = params.get("path_to_model", None) if model_path is not None: self.load_model(model_path) self.model = self.model.to(self.device) self.data_parallel = params.get("data_parallel") if self.data_parallel: self.model = torch.nn.DataParallel(self.model) def load_model(self, fname, cpu=False): if cpu: state_dict = torch.load(fname, map_location=lambda storage, location: "cpu") else: state_dict = torch.load(fname) self.model.load_state_dict(state_dict) def build_model(self): self.model = BiEncoderModule(self.params) def save_model(self, output_dir): if not os.path.exists(output_dir): os.makedirs(output_dir) model_to_save = get_model_obj(self.model) output_model_file = os.path.join(output_dir, WEIGHTS_NAME) output_config_file = os.path.join(output_dir, CONFIG_NAME) torch.save(model_to_save.state_dict(), output_model_file) model_to_save.config.to_json_file(output_config_file) def get_optimizer(self, optim_states=None, saved_optim_type=None): return get_bert_optimizer( [self.model], self.params["type_optimization"], self.params["learning_rate"], fp16=self.params.get("fp16"), ) def encode_context(self, cands): token_idx_cands, segment_idx_cands, mask_cands = to_bert_input( cands, self.NULL_IDX ) embedding_context, _ = self.model( token_idx_cands, segment_idx_cands, mask_cands, None, None, None ) return embedding_context.cpu().detach() def encode_candidate(self, cands): token_idx_cands, segment_idx_cands, mask_cands = to_bert_input( cands, self.NULL_IDX ) _, embedding_cands = self.model( None, None, None, token_idx_cands, segment_idx_cands, mask_cands ) return embedding_cands.cpu().detach() # TODO: why do we need cpu here? # return embedding_cands # Score candidates given context input and label input # If cand_encs is provided (pre-computed), cand_ves is ignored def score_candidate( self, text_vecs, cand_vecs, random_negs=True, cand_encs=None, # pre-computed candidate encoding. ): # Encode contexts first token_idx_ctxt, segment_idx_ctxt, mask_ctxt = to_bert_input( text_vecs, self.NULL_IDX ) embedding_ctxt, _ = self.model( token_idx_ctxt, segment_idx_ctxt, mask_ctxt, None, None, None ) # Candidate encoding is given, do not need to re-compute # Directly return the score of context encoding and candidate encoding if cand_encs is not None: return embedding_ctxt.mm(cand_encs.t()) # Train time. We compare with all elements of the batch token_idx_cands, segment_idx_cands, mask_cands = to_bert_input( cand_vecs, self.NULL_IDX ) _, embedding_cands = self.model( None, None, None, token_idx_cands, segment_idx_cands, mask_cands ) if random_negs: # train on random negatives return embedding_ctxt.mm(embedding_cands.t()) else: # train on hard negatives embedding_ctxt = embedding_ctxt.unsqueeze(1) # batchsize x 1 x embed_size embedding_cands = embedding_cands.unsqueeze(2) # batchsize x embed_size x 2 scores = torch.bmm(embedding_ctxt, embedding_cands) # batchsize x 1 x 1 scores = torch.squeeze(scores) return scores # label_input -- negatives provided # If label_input is None, train on in-batch negatives def forward(self, context_input, cand_input, label_input=None): flag = label_input is None scores = self.score_candidate(context_input, cand_input, flag) bs = scores.size(0) if label_input is None: target = torch.LongTensor(torch.arange(bs)) target = target.to(self.device) loss = F.cross_entropy(scores, target, reduction="mean") else: loss_fct = nn.BCEWithLogitsLoss(reduction="mean") # TODO: add parameters? loss = loss_fct(scores, label_input) return loss, scores def to_bert_input(token_idx, null_idx): """ token_idx is a 2D tensor int. return token_idx, segment_idx and mask """ segment_idx = token_idx * 0 mask = token_idx != null_idx # nullify elements in case self.NULL_IDX was not 0 token_idx = token_idx * mask.long() return token_idx, segment_idx, mask
35.004717
88
0.642232
79572651c46b30171ac8fa063dce50393c0efb2c
22,513
py
Python
Lib/site-packages/django/db/backends/base/operations.py
ashutoshsuman99/Web-Blog-D19
a01a0ccc40e8823110c01ebe4f43d9351df57295
[ "bzip2-1.0.6" ]
123
2015-01-15T06:56:45.000Z
2022-03-19T22:18:55.000Z
Lib/site-packages/django/db/backends/base/operations.py
ashutoshsuman99/Web-Blog-D19
a01a0ccc40e8823110c01ebe4f43d9351df57295
[ "bzip2-1.0.6" ]
21
2015-03-25T18:00:33.000Z
2019-08-12T17:11:10.000Z
Lib/site-packages/django/db/backends/base/operations.py
ashutoshsuman99/Web-Blog-D19
a01a0ccc40e8823110c01ebe4f43d9351df57295
[ "bzip2-1.0.6" ]
72
2015-01-14T16:29:47.000Z
2021-10-09T16:31:47.000Z
import datetime import decimal import warnings from importlib import import_module from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db.backends import utils from django.utils import six, timezone from django.utils.dateparse import parse_duration from django.utils.deprecation import RemovedInDjango20Warning from django.utils.encoding import force_text class BaseDatabaseOperations(object): """ This class encapsulates all backend-specific differences, such as the way a backend performs ordering or calculates the ID of a recently-inserted row. """ compiler_module = "django.db.models.sql.compiler" # Integer field safe ranges by `internal_type` as documented # in docs/ref/models/fields.txt. integer_field_ranges = { 'SmallIntegerField': (-32768, 32767), 'IntegerField': (-2147483648, 2147483647), 'BigIntegerField': (-9223372036854775808, 9223372036854775807), 'PositiveSmallIntegerField': (0, 32767), 'PositiveIntegerField': (0, 2147483647), } def __init__(self, connection): self.connection = connection self._cache = None def autoinc_sql(self, table, column): """ Returns any SQL needed to support auto-incrementing primary keys, or None if no SQL is necessary. This SQL is executed when a table is created. """ return None def bulk_batch_size(self, fields, objs): """ Returns the maximum allowed batch size for the backend. The fields are the fields going to be inserted in the batch, the objs contains all the objects to be inserted. """ return len(objs) def cache_key_culling_sql(self): """ Returns an SQL query that retrieves the first cache key greater than the n smallest. This is used by the 'db' cache backend to determine where to start culling. """ return "SELECT cache_key FROM %s ORDER BY cache_key LIMIT 1 OFFSET %%s" def unification_cast_sql(self, output_field): """ Given a field instance, returns the SQL necessary to cast the result of a union to that type. Note that the resulting string should contain a '%s' placeholder for the expression being cast. """ return '%s' def date_extract_sql(self, lookup_type, field_name): """ Given a lookup_type of 'year', 'month' or 'day', returns the SQL that extracts a value from the given date field field_name. """ raise NotImplementedError('subclasses of BaseDatabaseOperations may require a date_extract_sql() method') def date_interval_sql(self, timedelta): """ Implements the date interval functionality for expressions """ raise NotImplementedError('subclasses of BaseDatabaseOperations may require a date_interval_sql() method') def date_trunc_sql(self, lookup_type, field_name): """ Given a lookup_type of 'year', 'month' or 'day', returns the SQL that truncates the given date field field_name to a date object with only the given specificity. """ raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetrunc_sql() method') def datetime_cast_date_sql(self, field_name, tzname): """ Returns the SQL necessary to cast a datetime value to date value. """ raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_cast_date() method') def datetime_extract_sql(self, lookup_type, field_name, tzname): """ Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute' or 'second', returns the SQL that extracts a value from the given datetime field field_name, and a tuple of parameters. """ raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method') def datetime_trunc_sql(self, lookup_type, field_name, tzname): """ Given a lookup_type of 'year', 'month', 'day', 'hour', 'minute' or 'second', returns the SQL that truncates the given datetime field field_name to a datetime object with only the given specificity, and a tuple of parameters. """ raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_trunk_sql() method') def time_extract_sql(self, lookup_type, field_name): """ Given a lookup_type of 'hour', 'minute' or 'second', returns the SQL that extracts a value from the given time field field_name. """ return self.date_extract_sql(lookup_type, field_name) def deferrable_sql(self): """ Returns the SQL necessary to make a constraint "initially deferred" during a CREATE TABLE statement. """ return '' def distinct_sql(self, fields): """ Returns an SQL DISTINCT clause which removes duplicate rows from the result set. If any fields are given, only the given fields are being checked for duplicates. """ if fields: raise NotImplementedError('DISTINCT ON fields is not supported by this database backend') else: return 'DISTINCT' def drop_foreignkey_sql(self): """ Returns the SQL command that drops a foreign key. """ return "DROP CONSTRAINT" def drop_sequence_sql(self, table): """ Returns any SQL necessary to drop the sequence for the given table. Returns None if no SQL is necessary. """ return None def fetch_returned_insert_id(self, cursor): """ Given a cursor object that has just performed an INSERT...RETURNING statement into a table that has an auto-incrementing ID, returns the newly created ID. """ return cursor.fetchone()[0] def field_cast_sql(self, db_type, internal_type): """ Given a column type (e.g. 'BLOB', 'VARCHAR'), and an internal type (e.g. 'GenericIPAddressField'), returns the SQL necessary to cast it before using it in a WHERE statement. Note that the resulting string should contain a '%s' placeholder for the column being searched against. """ return '%s' def force_no_ordering(self): """ Returns a list used in the "ORDER BY" clause to force no ordering at all. Returning an empty list means that nothing will be included in the ordering. """ return [] def for_update_sql(self, nowait=False): """ Returns the FOR UPDATE SQL clause to lock rows for an update operation. """ if nowait: return 'FOR UPDATE NOWAIT' else: return 'FOR UPDATE' def fulltext_search_sql(self, field_name): """ Returns the SQL WHERE clause to use in order to perform a full-text search of the given field_name. Note that the resulting string should contain a '%s' placeholder for the value being searched against. """ raise NotImplementedError('Full-text search is not implemented for this database backend') def last_executed_query(self, cursor, sql, params): """ Returns a string of the query last executed by the given cursor, with placeholders replaced with actual values. `sql` is the raw query containing placeholders, and `params` is the sequence of parameters. These are used by default, but this method exists for database backends to provide a better implementation according to their own quoting schemes. """ # Convert params to contain Unicode values. to_unicode = lambda s: force_text(s, strings_only=True, errors='replace') if isinstance(params, (list, tuple)): u_params = tuple(to_unicode(val) for val in params) elif params is None: u_params = () else: u_params = {to_unicode(k): to_unicode(v) for k, v in params.items()} return six.text_type("QUERY = %r - PARAMS = %r") % (sql, u_params) def last_insert_id(self, cursor, table_name, pk_name): """ Given a cursor object that has just performed an INSERT statement into a table that has an auto-incrementing ID, returns the newly created ID. This method also receives the table name and the name of the primary-key column. """ return cursor.lastrowid def lookup_cast(self, lookup_type, internal_type=None): """ Returns the string to use in a query when performing lookups ("contains", "like", etc). The resulting string should contain a '%s' placeholder for the column being searched against. """ return "%s" def max_in_list_size(self): """ Returns the maximum number of items that can be passed in a single 'IN' list condition, or None if the backend does not impose a limit. """ return None def max_name_length(self): """ Returns the maximum length of table and column names, or None if there is no limit. """ return None def no_limit_value(self): """ Returns the value to use for the LIMIT when we are wanting "LIMIT infinity". Returns None if the limit clause can be omitted in this case. """ raise NotImplementedError('subclasses of BaseDatabaseOperations may require a no_limit_value() method') def pk_default_value(self): """ Returns the value to use during an INSERT statement to specify that the field should use its default value. """ return 'DEFAULT' def prepare_sql_script(self, sql): """ Takes a SQL script that may contain multiple lines and returns a list of statements to feed to successive cursor.execute() calls. Since few databases are able to process raw SQL scripts in a single cursor.execute() call and PEP 249 doesn't talk about this use case, the default implementation is conservative. """ try: import sqlparse except ImportError: raise ImproperlyConfigured( "sqlparse is required if you don't split your SQL " "statements manually." ) else: return [sqlparse.format(statement, strip_comments=True) for statement in sqlparse.split(sql) if statement] def process_clob(self, value): """ Returns the value of a CLOB column, for backends that return a locator object that requires additional processing. """ return value def return_insert_id(self): """ For backends that support returning the last insert ID as part of an insert query, this method returns the SQL and params to append to the INSERT query. The returned fragment should contain a format string to hold the appropriate column. """ pass def compiler(self, compiler_name): """ Returns the SQLCompiler class corresponding to the given name, in the namespace corresponding to the `compiler_module` attribute on this backend. """ if self._cache is None: self._cache = import_module(self.compiler_module) return getattr(self._cache, compiler_name) def quote_name(self, name): """ Returns a quoted version of the given table, index or column name. Does not quote the given name if it's already been quoted. """ raise NotImplementedError('subclasses of BaseDatabaseOperations may require a quote_name() method') def random_function_sql(self): """ Returns an SQL expression that returns a random value. """ return 'RANDOM()' def regex_lookup(self, lookup_type): """ Returns the string to use in a query when performing regular expression lookups (using "regex" or "iregex"). The resulting string should contain a '%s' placeholder for the column being searched against. If the feature is not supported (or part of it is not supported), a NotImplementedError exception can be raised. """ raise NotImplementedError('subclasses of BaseDatabaseOperations may require a regex_lookup() method') def savepoint_create_sql(self, sid): """ Returns the SQL for starting a new savepoint. Only required if the "uses_savepoints" feature is True. The "sid" parameter is a string for the savepoint id. """ return "SAVEPOINT %s" % self.quote_name(sid) def savepoint_commit_sql(self, sid): """ Returns the SQL for committing the given savepoint. """ return "RELEASE SAVEPOINT %s" % self.quote_name(sid) def savepoint_rollback_sql(self, sid): """ Returns the SQL for rolling back the given savepoint. """ return "ROLLBACK TO SAVEPOINT %s" % self.quote_name(sid) def set_time_zone_sql(self): """ Returns the SQL that will set the connection's time zone. Returns '' if the backend doesn't support time zones. """ return '' def sql_flush(self, style, tables, sequences, allow_cascade=False): """ Returns a list of SQL statements required to remove all data from the given database tables (without actually removing the tables themselves). The returned value also includes SQL statements required to reset DB sequences passed in :param sequences:. The `style` argument is a Style object as returned by either color_style() or no_style() in django.core.management.color. The `allow_cascade` argument determines whether truncation may cascade to tables with foreign keys pointing the tables being truncated. PostgreSQL requires a cascade even if these tables are empty. """ raise NotImplementedError('subclasses of BaseDatabaseOperations must provide a sql_flush() method') def sequence_reset_by_name_sql(self, style, sequences): """ Returns a list of the SQL statements required to reset sequences passed in :param sequences:. The `style` argument is a Style object as returned by either color_style() or no_style() in django.core.management.color. """ return [] def sequence_reset_sql(self, style, model_list): """ Returns a list of the SQL statements required to reset sequences for the given models. The `style` argument is a Style object as returned by either color_style() or no_style() in django.core.management.color. """ return [] # No sequence reset required by default. def start_transaction_sql(self): """ Returns the SQL statement required to start a transaction. """ return "BEGIN;" def end_transaction_sql(self, success=True): """ Returns the SQL statement required to end a transaction. """ if not success: return "ROLLBACK;" return "COMMIT;" def tablespace_sql(self, tablespace, inline=False): """ Returns the SQL that will be used in a query to define the tablespace. Returns '' if the backend doesn't support tablespaces. If inline is True, the SQL is appended to a row; otherwise it's appended to the entire CREATE TABLE or CREATE INDEX statement. """ return '' def prep_for_like_query(self, x): """Prepares a value for use in a LIKE query.""" return force_text(x).replace("\\", "\\\\").replace("%", "\%").replace("_", "\_") # Same as prep_for_like_query(), but called for "iexact" matches, which # need not necessarily be implemented using "LIKE" in the backend. prep_for_iexact_query = prep_for_like_query def validate_autopk_value(self, value): """ Certain backends do not accept some values for "serial" fields (for example zero in MySQL). This method will raise a ValueError if the value is invalid, otherwise returns validated value. """ return value def adapt_unknown_value(self, value): """ Transforms a value to something compatible with the backend driver. This method only depends on the type of the value. It's designed for cases where the target type isn't known, such as .raw() SQL queries. As a consequence it may not work perfectly in all circumstances. """ if isinstance(value, datetime.datetime): # must be before date return self.adapt_datetimefield_value(value) elif isinstance(value, datetime.date): return self.adapt_datefield_value(value) elif isinstance(value, datetime.time): return self.adapt_timefield_value(value) elif isinstance(value, decimal.Decimal): return self.adapt_decimalfield_value(value) else: return value def adapt_datefield_value(self, value): """ Transforms a date value to an object compatible with what is expected by the backend driver for date columns. """ if value is None: return None return six.text_type(value) def adapt_datetimefield_value(self, value): """ Transforms a datetime value to an object compatible with what is expected by the backend driver for datetime columns. """ if value is None: return None return six.text_type(value) def adapt_timefield_value(self, value): """ Transforms a time value to an object compatible with what is expected by the backend driver for time columns. """ if value is None: return None if timezone.is_aware(value): raise ValueError("Django does not support timezone-aware times.") return six.text_type(value) def adapt_decimalfield_value(self, value, max_digits, decimal_places): """ Transforms a decimal.Decimal value to an object compatible with what is expected by the backend driver for decimal (numeric) columns. """ return utils.format_number(value, max_digits, decimal_places) def adapt_ipaddressfield_value(self, value): """ Transforms a string representation of an IP address into the expected type for the backend driver. """ return value def year_lookup_bounds_for_date_field(self, value): """ Returns a two-elements list with the lower and upper bound to be used with a BETWEEN operator to query a DateField value using a year lookup. `value` is an int, containing the looked-up year. """ first = datetime.date(value, 1, 1) second = datetime.date(value, 12, 31) first = self.adapt_datefield_value(first) second = self.adapt_datefield_value(second) return [first, second] def year_lookup_bounds_for_datetime_field(self, value): """ Returns a two-elements list with the lower and upper bound to be used with a BETWEEN operator to query a DateTimeField value using a year lookup. `value` is an int, containing the looked-up year. """ first = datetime.datetime(value, 1, 1) second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999) if settings.USE_TZ: tz = timezone.get_current_timezone() first = timezone.make_aware(first, tz) second = timezone.make_aware(second, tz) first = self.adapt_datetimefield_value(first) second = self.adapt_datetimefield_value(second) return [first, second] def get_db_converters(self, expression): """ Get a list of functions needed to convert field data. Some field types on some backends do not provide data in the correct format, this is the hook for converter functions. """ return [] def convert_durationfield_value(self, value, expression, connection, context): if value is not None: value = str(decimal.Decimal(value) / decimal.Decimal(1000000)) value = parse_duration(value) return value def check_aggregate_support(self, aggregate_func): warnings.warn( "check_aggregate_support has been deprecated. Use " "check_expression_support instead.", RemovedInDjango20Warning, stacklevel=2) return self.check_expression_support(aggregate_func) def check_expression_support(self, expression): """ Check that the backend supports the provided expression. This is used on specific backends to rule out known expressions that have problematic or nonexistent implementations. If the expression has a known problem, the backend should raise NotImplementedError. """ pass def combine_expression(self, connector, sub_expressions): """Combine a list of subexpressions into a single expression, using the provided connecting operator. This is required because operators can vary between backends (e.g., Oracle with %% and &) and between subexpression types (e.g., date expressions) """ conn = ' %s ' % connector return conn.join(sub_expressions) def combine_duration_expression(self, connector, sub_expressions): return self.combine_expression(connector, sub_expressions) def modify_insert_params(self, placeholder, params): """Allow modification of insert parameters. Needed for Oracle Spatial backend due to #10888. """ return params def integer_field_range(self, internal_type): """ Given an integer field internal type (e.g. 'PositiveIntegerField'), returns a tuple of the (min_value, max_value) form representing the range of the column type bound to the field. """ return self.integer_field_ranges[internal_type]
38.028716
117
0.649314
795726afa77176a53ffe9d8950105c7bc5fa77ec
1,521
py
Python
neural_mmo/jsuarez/oldMobs.py
jyotishp/neural-mmo
a51187b922957921cacce64ebbda34e26ee4253e
[ "MIT" ]
null
null
null
neural_mmo/jsuarez/oldMobs.py
jyotishp/neural-mmo
a51187b922957921cacce64ebbda34e26ee4253e
[ "MIT" ]
null
null
null
neural_mmo/jsuarez/oldMobs.py
jyotishp/neural-mmo
a51187b922957921cacce64ebbda34e26ee4253e
[ "MIT" ]
null
null
null
#NPC definitions with AI overrides per NPC, as required. from neural_mmo.forge.blade.entity import NPC from neural_mmo.forge.blade.item import Item, RawMeat, Sword from neural_mmo.forge.blade.lib import AI from neural_mmo.forge.blade.lib.Enums import Material from neural_mmo.forge.blade.modules import DropTable, Skill class Chicken(NPC.Passive): def __init__(self, pos): super().__init__(pos) self.index = 2 self.maxHealth = 5 self.health = self.maxHealth self.expOnKill = 10 self.drops.add(RawMeat.Chicken, 1) self.drops.add(RawMeat.Chicken, 1, 0.5) def decide(self, world): action, args = AI.randomOnTurf(world, self, [Material.GRASS.value]) return action, args class Goblin(NPC.PassiveAgressive): def __init__(self, pos): super().__init__(pos) self.index = 3 self.searchRange = 5 self.maxHealth = 15 self.health = self.maxHealth self.expOnKill = 50 self.skills.melee.exp = Skill.Skill.expCalculator.expAtLevel(5) self.skills.defense.exp = Skill.Skill.expCalculator.expAtLevel(5) self.drops.add(RawMeat.Goblin, 1) self.drops.add(Item.Gold, DropTable.Range(1, 100), 0.5) self.drops.add(Sword.Copper, 1, 0.2) def decide(self, world): #action, args = AI.turfSearchAndDestroy(world, self, # whitelist=[Material.FOREST.value]) action, args = AI.randomOnTurf(world, self, [Material.FOREST.value]) return action, args
31.6875
71
0.671269
795728859e4e39399dfc7ec104be7902219b7b01
830
py
Python
code/generic/updates.py
ElliotMunro200/reinforcement_learning_an_introduction
c4fccb46a4bb00955549be3505144ec49f0132e5
[ "MIT" ]
234
2018-09-01T00:26:29.000Z
2022-03-21T03:55:50.000Z
code/generic/updates.py
15779235038/reinforcement_learning_an_introduction
a0ac9e5da6eaeae14d297a560c499d1a6e579c2a
[ "MIT" ]
7
2018-11-29T21:04:36.000Z
2021-12-13T17:11:50.000Z
code/generic/updates.py
15779235038/reinforcement_learning_an_introduction
a0ac9e5da6eaeae14d297a560c499d1a6e579c2a
[ "MIT" ]
63
2018-07-31T04:53:21.000Z
2022-03-24T04:03:43.000Z
#!/usr/bin/env python """ -------------------------------- project: code created: 27/06/2018 11:43 --------------------------------- update action-value dictionaries in-place """ from generic.policies import greedy def sarsa(action_values, old_state, action, reward, new_state, new_action, alpha, gamma): """update action values in-place""" action_values[old_state][action] += alpha * ( reward + gamma * action_values[new_state][new_action] - action_values[old_state][action] ) return None def q_learning(action_values, old_state, action, reward, new_state, alpha, gamma): new_action = greedy(action_values[new_state]) action_values[old_state][action] += alpha * ( reward + gamma * action_values[new_state][new_action] - action_values[old_state][action] ) return None
29.642857
100
0.650602
795728879ef5694bd3e33f38c9827de0f4d853fa
1,750
py
Python
tools/perf/page_sets/simple_mobile_sites.py
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
tools/perf/page_sets/simple_mobile_sites.py
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
tools/perf/page_sets/simple_mobile_sites.py
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page as page_module from telemetry.page import shared_page_state from telemetry import story class SimplePage(page_module.Page): def __init__(self, url, page_set): super(SimplePage, self).__init__( url=url, page_set=page_set, shared_page_state_class=shared_page_state.Shared10InchTabletPageState, credentials_path='data/credentials.json') def RunNavigateSteps(self, action_runner): super(SimplePage, self).RunNavigateSteps(action_runner) # TODO(epenner): Remove this wait (http://crbug.com/366933) action_runner.Wait(5) class SimpleScrollPage(SimplePage): def __init__(self, url, page_set): super(SimpleScrollPage, self).__init__(url=url, page_set=page_set) def RunPageInteractions(self, action_runner): # Make the scroll longer to reduce noise. with action_runner.CreateGestureInteraction('ScrollAction'): action_runner.ScrollPage(direction='down', speed_in_pixels_per_second=300) class SimpleMobileSitesPageSet(story.StorySet): """ Simple mobile sites """ def __init__(self): super(SimpleMobileSitesPageSet, self).__init__( archive_data_file='data/simple_mobile_sites.json', cloud_storage_bucket=story.PUBLIC_BUCKET) scroll_page_list = [ # Why: Scrolls moderately complex pages (up to 60 layers) 'http://www.ebay.co.uk/', 'https://www.flickr.com/', 'http://www.apple.com/mac/', 'http://www.nyc.gov', 'http://m.nytimes.com/' ] for url in scroll_page_list: self.AddStory(SimpleScrollPage(url, self))
32.407407
80
0.729143
795728bbbf4c5976f3f7407491f379c65a702939
6,143
py
Python
data_processing/ted_reader.py
cordercorder/NMT
cbc5ad010ce04da7a82f05ad1a3b6c16f8467266
[ "MIT" ]
6
2020-08-17T16:11:18.000Z
2020-10-10T12:26:03.000Z
data_processing/ted_reader.py
cordercorder/NMT
cbc5ad010ce04da7a82f05ad1a3b6c16f8467266
[ "MIT" ]
1
2020-07-11T16:42:55.000Z
2020-07-12T12:58:18.000Z
data_processing/ted_reader.py
cordercorder/NMT
cbc5ad010ce04da7a82f05ad1a3b6c16f8467266
[ "MIT" ]
2
2020-10-10T12:22:46.000Z
2021-11-12T15:39:27.000Z
import itertools import os import csv from collections import defaultdict from six.moves import zip class MultiLingualAlignedCorpusReader(object): """A class to read TED talk dataset """ def __init__(self, corpus_path, delimiter='\t', target_token=True, bilingual=True, corpus_type='file', lang_dict={'source': ['fr'], 'target': ['en']}, eval_lang_dict=None, zero_shot=False): self.empty_line_flag = 'NULL' self.corpus_path = corpus_path self.delimiter = delimiter self.bilingual = bilingual self.lang_dict = lang_dict self.lang_set = set() self.target_token = target_token self.zero_shot = zero_shot self.eval_lang_dict = eval_lang_dict self.corpus_type = corpus_type for list_ in self.lang_dict.values(): for lang in list_: self.lang_set.add(lang) self.data = dict() self.data['train'] = self.read_aligned_corpus(split_type='train') self.data['test'] = self.read_aligned_corpus(split_type='test') self.data['dev'] = self.read_aligned_corpus(split_type='dev') def read_data(self, file_loc_): data_list = list() with open(file_loc_) as fp: for line in fp: try: text = line.strip() except IndexError: text = self.empty_line_flag data_list.append(text) return data_list def filter_text(self, dict_): if self.target_token: field_index = 1 else: field_index = 0 data_dict = defaultdict(list) list1 = dict_['source'] list2 = dict_['target'] for sent1, sent2 in zip(list1, list2): try: src_sent = ' '.join(sent1.split()[field_index: ]) except IndexError: src_sent = 'NULL' if src_sent.find(self.empty_line_flag) != -1 or len(src_sent) == 0: continue elif sent2.find(self.empty_line_flag) != -1 or len(sent2) == 0: continue else: data_dict['source'].append(sent1) data_dict['target'].append(sent2) return data_dict def read_file(self, split_type, data_type): return self.data[split_type][data_type] def save_file(self, path_, split_type, data_type): with open(path_, 'w') as fp: for line in self.data[split_type][data_type]: fp.write(line + '\n') def add_target_token(self, list_, lang_id): new_list = list() # token = '__' + lang_id + '__' for sent in list_: new_list.append(sent) return new_list def read_from_single_file(self, path_, s_lang, t_lang): data_dict = defaultdict(list) with open(path_, 'r') as fp: reader = csv.DictReader(fp, delimiter='\t', quoting=csv.QUOTE_NONE) for row in reader: data_dict['source'].append(row[s_lang]) data_dict['target'].append(row[t_lang]) if self.target_token: text = self.add_target_token(data_dict['source'], t_lang) data_dict['source'] = text return data_dict['source'], data_dict['target'] def read_aligned_corpus(self, split_type='train'): data_dict = defaultdict(list) iterable = [] s_list = [] t_list = [] if self.zero_shot: if split_type == "train": iterable = zip(self.lang_dict['source'], self.lang_dict['target']) else: iterable = zip(self.eval_lang_dict['source'], self.eval_lang_dict['target']) elif self.bilingual: iterable = itertools.product(self.lang_dict['source'], self.lang_dict['target']) for s_lang, t_lang in iterable: if s_lang == t_lang: continue if self.corpus_type == 'file': split_type_file_path = os.path.join(self.corpus_path, "all_talks_{}.tsv".format(split_type)) s_list, t_list = self.read_from_single_file(split_type_file_path, s_lang=s_lang, t_lang=t_lang) data_dict['source'] += s_list data_dict['target'] += t_list new_data_dict = self.filter_text(data_dict) return new_data_dict if __name__ == "__main__": # TED Talks data directory ted_data_path = "ted_data" src_lang, trg_lang = "en", "ro" output_data_path = "data/{}_{}".format(src_lang, trg_lang) train_lang_dict={'source': [src_lang], 'target': [trg_lang]} eval_lang_dict = {'source': [src_lang], 'target': [trg_lang]} obj = MultiLingualAlignedCorpusReader(corpus_path=ted_data_path, lang_dict=train_lang_dict, target_token=True, corpus_type='file', eval_lang_dict=eval_lang_dict, zero_shot=False, bilingual=True) os.makedirs(output_data_path, exist_ok=True) obj.save_file(output_data_path + "/train.{}".format(src_lang), split_type='train', data_type='source') obj.save_file(output_data_path + "/train.{}".format(trg_lang), split_type='train', data_type='target') obj.save_file(output_data_path + "/test.{}".format(src_lang), split_type='test', data_type='source') obj.save_file(output_data_path + "/test.{}".format(trg_lang), split_type='test', data_type='target') obj.save_file(output_data_path + "/dev.{}".format(src_lang), split_type='dev', data_type='source') obj.save_file(output_data_path + "/dev.{}".format(trg_lang), split_type='dev', data_type='target')
37.457317
92
0.555103
79572962d250ab5526c6532836d18a6650053b9d
16,108
py
Python
fluids/state.py
iandewancker/Urban_Driving_Simulator
fff001cb7a58a3e4ef84415de6244e520af8ec55
[ "MIT" ]
null
null
null
fluids/state.py
iandewancker/Urban_Driving_Simulator
fff001cb7a58a3e4ef84415de6244e520af8ec55
[ "MIT" ]
null
null
null
fluids/state.py
iandewancker/Urban_Driving_Simulator
fff001cb7a58a3e4ef84415de6244e520af8ec55
[ "MIT" ]
null
null
null
import numpy as np import json import os from six import iteritems import random import pygame import hashlib from fluids.consts import * from fluids.assets import * from fluids.utils import * from fluids.version import __version__ basedir = os.path.dirname(__file__) id_index = 0 def get_id(): global id_index r = id_index id_index = id_index + 1 return r class State(object): """ This class represents the state of the world Parameters ---------- layout: str Name of json layout file specifiying environment object positions. Default is "fluids_state_city" controlled_cars: int Number of cars to accept external control for background_cars: int Number of cars to control with the background planner background_peds: int Number of pedestrians to control with the background planner use_traffic_lights: bool Sets whether traffic lights are generated use_ped_lights: bool Sets whether pedestrian lights are generated waypoint_width: int Sets width of waypoints. Increasing this makes waypoints span the lanes """ def __init__(self, layout =STATE_CITY, controlled_cars =0, background_cars =0, background_peds =0, waypoint_width =5, use_traffic_lights =True, use_ped_lights =True, vis_level =1, tunable_parameters =None): fluids_print("Loading layout: " + layout) layout = open(os.path.join(basedir, "layouts", layout + ".json")) cfilename = "{}{}.json".format( hashlib.md5(str(layout).encode()).hexdigest()[:10], __version__) cached_layout = lookup_cache(cfilename) cache_found = cached_layout is not False if cached_layout: fluids_print("Cached layout found") layout = cached_layout layout = json.load(layout) self.time = 0 self.objects = {} self.type_map = {k:{} for k in [Terrain, Lane, Street, CrossWalk, Sidewalk, TrafficLight, Car, CrossWalkLight, Pedestrian, PedCrossing]} self.static_objects = {} self.dynamic_objects = {} self.dimensions = (layout['dimension_x'] + 800, layout['dimension_y']) self.vis_level = vis_level lanes = [] sidewalks = [] fluids_print("Creating objects") for obj_info in layout['static_objects']: typ = {"Terrain" : Terrain, "Lane" : Lane, "Street" : Street, "CrossWalk" : CrossWalk, "PedCrossing": PedCrossing, "Sidewalk" : Sidewalk}[obj_info['type']] if typ == Lane: obj_info["wp_width"] = waypoint_width obj = typ(state=self, vis_level=vis_level, **obj_info) if typ == Lane: lanes.append(obj) if typ == Sidewalk: sidewalks.append(obj) key = get_id() self.type_map[typ][key] = obj self.objects[key] = obj self.static_objects[key] = obj obj_info['fluids_obj'] = obj car_ids = [] for obj_info in layout['dynamic_objects']: typ = {"Car" : Car, "TrafficLight" : TrafficLight, "CrossWalkLight": CrossWalkLight, "Pedestrian" : Pedestrian}[obj_info['type']] obj = typ(state=self, vis_level=vis_level, **obj_info) if not use_traffic_lights and type(obj) == TrafficLight: continue if not use_ped_lights and type(obj) == CrossWalkLight: continue key = get_id() if type == Car: car_ids.append(key) self.type_map[typ][key] = obj self.objects[key] = obj self.dynamic_objects[key] = obj fluids_print("Generating trajectory map") if 'waypoints' in layout: wp_map = {} self.waypoints = [] self.ped_waypoints = [] for wp_info in layout['waypoints']: index = wp_info.pop('index') wp = Waypoint(owner=None, ydim=waypoint_width, **wp_info) wp_map[index] = wp self.waypoints.append(wp) for wp in self.waypoints: wp.nxt = [wp_map[index] for index in wp.nxt] for wp_info in layout['ped_waypoints']: index = wp_info.pop('index') wp = Waypoint(owner=None, **wp_info) wp_map[index] = wp self.ped_waypoints.append(wp) for wp in self.ped_waypoints: wp.nxt = [wp_map[index] for index in wp.nxt] for k, obj in iteritems(self.objects): obj.waypoints = [wp_map[i] for i in obj.waypoints] for wp in obj.waypoints: wp.owner = obj for k, obj in iteritems(self.type_map[Lane]): obj.start_waypoint = wp_map[obj.start_waypoint] obj.end_waypoint = wp_map[obj.end_waypoint] for k, obj in iteritems(self.type_map[Sidewalk]): obj.start_waypoints = [wp_map[i] for i in obj.start_waypoints] obj.end_waypoints = [wp_map[i] for i in obj.end_waypoints] for k, obj in iteritems(self.type_map[CrossWalk]): obj.start_waypoints = [wp_map[i] for i in obj.start_waypoints] obj.end_waypoints = [wp_map[i] for i in obj.end_waypoints] else: self.generate_waypoints_init() layout['waypoints'] = [] layout['ped_waypoints'] = [] for wp in self.waypoints: wpdict = {"index":wp.index, "x":wp.x, "y": wp.y, "angle":wp.angle, "nxt":[w.index for w in wp.nxt]} layout['waypoints'].append(wpdict) for wp in self.ped_waypoints: wpdict = {"index":wp.index, "x":wp.x, "y": wp.y, "angle":wp.angle, "nxt":[w.index for w in wp.nxt]} layout['ped_waypoints'].append(wpdict) for obj_info in layout['static_objects']: obj = obj_info.pop('fluids_obj') if obj_info['type'] == 'Lane': obj_info['start_wp'] = obj.start_waypoint.index obj_info['end_wp'] = obj.end_waypoint.index elif obj_info['type'] in ['Sidewalk', 'CrossWalk']: obj_info['start_wps'] = [wp.index for wp in obj.start_waypoints] obj_info['end_wps'] = [wp.index for wp in obj.end_waypoints] obj_info['waypoints'] = [wp.index for wp in obj.waypoints] for waypoint in self.waypoints: waypoint.create_edges(buff=20) for waypoint in self.ped_waypoints: waypoint.create_edges(buff=5) fluids_print("Generating cars") for i in range(controlled_cars + background_cars): while True: start = lanes[np.random.random_integers(0, len(lanes)-1)] x = np.random.uniform(start.minx + 50, start.maxx - 50) y = np.random.uniform(start.miny + 50, start.maxy - 50) angle = start.angle + np.random.uniform(-0.1, 0.1) car = Car(state=self, x=x, y=y, angle=angle, vis_level=vis_level) min_d = min([car.dist_to(other) for k, other \ in iteritems(self.type_map[Car])] + [np.inf]) if min_d > 10 and not self.is_in_collision(car): key = get_id() for waypoint in self.waypoints: if car.intersects(waypoint): while car.intersects(waypoint): waypoint = random.choice(waypoint.nxt).out_p waypoint = random.choice(waypoint.nxt).out_p car.waypoints = [waypoint] break self.type_map[Car][key] = car self.objects[key] = car car_ids.append(key) self.dynamic_objects[key] = car break self.controlled_cars = {k: self.objects[k] for k in car_ids[:controlled_cars]} for k, car in iteritems(self.controlled_cars): car.color = (0x0b,0x04,0xf4)#(0x5B,0x5C,0xF7) self.background_cars = {k: self.objects[k] for k in car_ids[controlled_cars:]} for c in self.controlled_cars.values(): c.set_tunable_parameters(tunable_parameters) fluids_print("Generating peds") for i in range(background_peds): while True: wp = random.choice(self.ped_waypoints) ped = Pedestrian(state=self, x=wp.x, y=wp.y, angle=wp.angle, vis_level=vis_level) while ped.intersects(wp): wp = random.choice(wp.nxt).out_p ped.waypoints = [wp] if not self.is_in_collision(ped): key = get_id() self.objects[key] = ped self.type_map[Pedestrian][key] = ped self.dynamic_objects[key] = obj break if not cache_found: fluids_print("Caching layout to: " + cfilename) with open(get_cache_filename(cfilename), "w") as outfile: json.dump(layout, outfile, indent=1) fluids_print("State creation complete") if vis_level: self.static_surface = pygame.Surface(self.dimensions) try: self.static_debug_surface = pygame.Surface(self.dimensions, pygame.SRCALPHA) except ValueError: fluids_print("WARNING: Alpha channel not available. Visualization may be slow") self.static_debug_surface = self.static_surface.copy() for k, obj in iteritems(self.static_objects): if type(obj) != CrossWalk: obj.render(self.static_surface) else: obj.render(self.static_debug_surface) for waypoint in self.waypoints: waypoint.render(self.static_debug_surface) for waypoint in self.ped_waypoints: waypoint.render(self.static_debug_surface, color=(255, 255, 0)) def generate_waypoints_init(self): self.waypoints = [lane.start_waypoint for k, lane in \ iteritems(self.type_map[Lane])] self.waypoints.extend([lane.end_waypoint for k, lane in \ iteritems(self.type_map[Lane])]) new_waypoints = [] for k, street in iteritems(self.type_map[Street]): for waypoint in self.waypoints: if street.intersects(waypoint): test_point = (waypoint.x + np.cos(waypoint.angle), waypoint.y - np.sin(waypoint.angle)) if street.contains_point(test_point): street.in_waypoints.append(waypoint) assert(waypoint == waypoint.owner.end_waypoint) waypoint.owner = street else: street.out_waypoints.append(waypoint) for in_p in street.in_waypoints: for out_p in street.out_waypoints: dangle = (in_p.angle - out_p.angle) % (2 * np.pi) if dangle < 0.75*np.pi or dangle > 1.25*np.pi: in_p.nxt.append(out_p) for waypoint in self.waypoints: new_points = waypoint.smoothen(smooth_level=2000) new_waypoints.extend(new_points) for wp in new_points: wp.owner = waypoint.owner self.waypoints.extend(new_waypoints) self.ped_waypoints = [] for k, obj in iteritems(self.objects): if type(obj) in {CrossWalk, Sidewalk}: self.ped_waypoints.extend(obj.start_waypoints) self.ped_waypoints.extend(obj.end_waypoints) for k, cross in iteritems(self.type_map[PedCrossing]): for waypoint in self.ped_waypoints: if cross.intersects(waypoint): test_point = (waypoint.x + np.cos(waypoint.angle), waypoint.y - np.sin(waypoint.angle)) if cross.contains_point(test_point): cross.in_waypoints.append(waypoint) else: cross.out_waypoints.append(waypoint) for in_p in cross.in_waypoints: for out_p in cross.out_waypoints: dangle = (in_p.angle - out_p.angle) % (2 * np.pi) if dangle < 0.75*np.pi or dangle > 1.25*np.pi: in_p.nxt.append(out_p) new_waypoints = [] for waypoint in self.ped_waypoints: new_points = waypoint.smoothen(smooth_level=1500) new_waypoints.extend(new_points) for wp in new_points: wp.owner = waypoint.owner self.ped_waypoints.extend(new_waypoints) print(self.ped_waypoints) i = 0 for wp in self.waypoints: wp.index = i i += 1 wp.owner.waypoints.append(wp) for wp in self.ped_waypoints: wp.index = i i += 1 wp.owner.waypoints.append(wp) def get_static_surface(self): return self.static_surface def get_static_debug_surface(self): return self.static_debug_surface def get_dynamic_surface(self, background): dynamic_surface = background.copy() for typ in [Pedestrian, TrafficLight, CrossWalkLight]: for k, obj in iteritems(self.type_map[typ]): obj.render(dynamic_surface) for k, car in iteritems(self.background_cars): car.render(dynamic_surface) for k, car in iteritems(self.controlled_cars): car.render(dynamic_surface) if self.vis_level > 1: for kd, obj in iteritems(self.dynamic_objects): for ko, sobj in iteritems(self.objects): if obj.collides(sobj): pygame.draw.circle(dynamic_surface, (255, 0, 255), (int(obj.x), int(obj.y)), 10) return dynamic_surface def is_in_collision(self, obj): collideables = obj.collideables for ctype in collideables: if ctype in self.type_map: for k, other in iteritems(self.type_map[ctype]): if obj.collides(other): return True return False def min_distance_to_collision(self, obj): collideables = obj.collideables mind = 0 for ctype in collideables: for k, other in iteritems(self.type_map[ctype]): d = obj.dist_to(other) if d < mind: mind = d return mind def update_vis_level(self, new_vis_level): self.vis_level = new_vis_level for k, obj in iteritems(self.objects): obj.vis_level = new_vis_level def get_controlled_collisions(self): return
40.987277
95
0.529364
79572a728663c943add2d6c7486bc9bea8f8ecae
2,712
py
Python
examples/plan_marginal.py
thibsej/unbalanced-ot-functionals
bfd098e98ed10b90a36e0dbe7b099c1c31770931
[ "MIT" ]
14
2019-12-04T12:41:12.000Z
2022-03-30T11:37:00.000Z
examples/plan_marginal.py
thibsej/unbalanced-ot-functionals
bfd098e98ed10b90a36e0dbe7b099c1c31770931
[ "MIT" ]
1
2022-01-14T16:35:18.000Z
2022-01-18T09:15:03.000Z
examples/plan_marginal.py
thibsej/unbalanced-ot-functionals
bfd098e98ed10b90a36e0dbe7b099c1c31770931
[ "MIT" ]
3
2020-10-09T08:24:22.000Z
2022-02-18T15:48:35.000Z
import os import torch import numpy as np import matplotlib.pyplot as plt from unbalancedot.utils import euclidean_cost from unbalancedot.sinkhorn import BatchVanillaSinkhorn from unbalancedot.entropy import ( KullbackLeibler, Balanced, TotalVariation, Range, PowerEntropy, ) path = os.getcwd() + "/output" if not os.path.isdir(path): os.mkdir(path) def template_measure(nsample): x1 = np.linspace(0.0, 0.2, nsample) a1 = np.ones(nsample) a1[0], a1[-1] = 0.0, 0.0 a1 = a1 / np.sum(a1) x2 = np.linspace(0.9, 1.0, nsample) a2 = 0.05 - np.abs(x2 - 0.95) a2[0], a2[-1] = 0.0, 0.0 a2 = a2 / np.sum(a2) x = np.concatenate((x1, x2)) a = np.concatenate((0.65 * a1, 0.35 * a2)) a = a / np.sum(a) y1 = np.linspace(0.2, 0.4, nsample) b1 = np.linspace(0.0, 1.0, nsample) b1[0], b1[-1] = 0.0, 0.0 b1 = b1 / np.sum(b1) y2 = np.linspace(0.5, 0.9, nsample) b2 = np.sqrt(np.abs(1 - ((y2 - 0.7) / 0.2) ** 2)) b2[0], b2[-1] = 0.0, 0.0 b2 = b2 / np.sum(b2) y = np.concatenate((y1, y2)) b = np.concatenate((0.45 * b1, 0.55 * b2)) b = b / np.sum(b) return a, x, b, y # Init of measures and solvers a, x, b, y = template_measure(1000) A, X, B, Y = ( torch.from_numpy(a)[None, :], torch.from_numpy(x)[None, :, None], torch.from_numpy(b)[None, :], torch.from_numpy(y)[None, :, None], ) p, blur, reach = 2, 1e-3, 0.1 cost = euclidean_cost(p) solver = BatchVanillaSinkhorn( nits=10000, nits_grad=1, tol=1e-5, assume_convergence=True ) list_entropy = [ Balanced(blur), KullbackLeibler(blur, reach), TotalVariation(blur, reach), Range(blur, 0.7, 1.3), PowerEntropy(blur, reach, 0.0), ] # Init of plot blue = (0.55, 0.55, 0.95) red = (0.95, 0.55, 0.55) fig = plt.figure(figsize=(8, 4)) plt.fill_between(x, 0, a, color="b") plt.fill_between(y, 0, b, color="r") plt.tight_layout() plt.savefig(path + "/comparison_entropy_reference.eps", format="eps") # Plotting each entropy separately for entropy in list_entropy: fig = plt.figure(figsize=(8, 4)) f, g = solver.sinkhorn_asym(A, X, B, Y, cost, entropy) C = cost(X, Y) pi = ( ((f[:, :, None] + g[:, None, :] - C) / blur).exp() * A[:, :, None] * B[:, None, :] ) pi_1, pi_2 = pi.sum(dim=2), pi.sum(dim=1) pi_1, pi_2 = pi_1[0, :].data.numpy(), pi_2[0, :].data.numpy() plt.plot(x, a, color="b", linestyle="--") plt.plot(y, b, color="r", linestyle="--") plt.fill_between(x, 0, pi_1, color=red) plt.fill_between(y, 0, pi_2, color=blue) plt.tight_layout() plt.savefig(path + f"/comparison_entropy_{entropy.__name__}.eps", format="eps")
25.584906
69
0.586283
79572b5dc9ef668d065237c374c2b619290992c2
1,329
py
Python
IMU/VTK-6.2.0/Imaging/Core/Testing/Python/TestShiftScale.py
timkrentz/SunTracker
9a189cc38f45e5fbc4e4c700d7295a871d022795
[ "MIT" ]
4
2016-03-30T14:31:52.000Z
2019-02-02T05:01:32.000Z
IMU/VTK-6.2.0/Imaging/Core/Testing/Python/TestShiftScale.py
timkrentz/SunTracker
9a189cc38f45e5fbc4e4c700d7295a871d022795
[ "MIT" ]
null
null
null
IMU/VTK-6.2.0/Imaging/Core/Testing/Python/TestShiftScale.py
timkrentz/SunTracker
9a189cc38f45e5fbc4e4c700d7295a871d022795
[ "MIT" ]
2
2019-08-30T23:36:13.000Z
2019-11-08T16:52:01.000Z
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Shift and scale an image (in that order) # This filter is useful for converting to a lower precision data type. reader = vtk.vtkImageReader() reader.GetExecutive().SetReleaseDataFlag(0,0) reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetFilePrefix("" + str(VTK_DATA_ROOT) + "/Data/headsq/quarter") reader.SetDataMask(0x7fff) shiftScale = vtk.vtkImageShiftScale() shiftScale.SetInputConnection(reader.GetOutputPort()) shiftScale.SetShift(0) shiftScale.SetScale(0.5) shiftScale.SetOutputScalarTypeToDouble() shiftScale2 = vtk.vtkImageShiftScale() shiftScale2.SetInputConnection(shiftScale.GetOutputPort()) shiftScale2.SetShift(0) shiftScale2.SetScale(2.0) mag = vtk.vtkImageMagnify() mag.SetInputConnection(shiftScale2.GetOutputPort()) mag.SetMagnificationFactors(4,4,1) mag.InterpolateOff() viewer = vtk.vtkImageViewer() viewer.SetInputConnection(mag.GetOutputPort()) viewer.SetColorWindow(1024) viewer.SetColorLevel(1024) #make interface #skipping source #vtkPNMWriter w #w SetFileName "D:/vtknew/vtk/graphics/examplesTcl/mace2.ppm" #w SetInputConnection [shiftScale GetOutputPort] #w Write # --- end of script --
34.076923
71
0.787058
79572bc889d58cdb4e78e11fea2674c0a9662dab
1,320
py
Python
aliyun-python-sdk-csb/aliyunsdkcsb/request/v20171118/GetProjectRequest.py
DataDog/aliyun-openapi-python-sdk
5cbee29bce6416dd62f61f0c3786b1af6ea0d84f
[ "Apache-2.0" ]
null
null
null
aliyun-python-sdk-csb/aliyunsdkcsb/request/v20171118/GetProjectRequest.py
DataDog/aliyun-openapi-python-sdk
5cbee29bce6416dd62f61f0c3786b1af6ea0d84f
[ "Apache-2.0" ]
null
null
null
aliyun-python-sdk-csb/aliyunsdkcsb/request/v20171118/GetProjectRequest.py
DataDog/aliyun-openapi-python-sdk
5cbee29bce6416dd62f61f0c3786b1af6ea0d84f
[ "Apache-2.0" ]
1
2021-02-23T11:27:54.000Z
2021-02-23T11:27:54.000Z
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest class GetProjectRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'CSB', '2017-11-18', 'GetProject','CSB') self.set_protocol_type('https'); def get_ProjectName(self): return self.get_query_params().get('ProjectName') def set_ProjectName(self,ProjectName): self.add_query_param('ProjectName',ProjectName) def get_CsbId(self): return self.get_query_params().get('CsbId') def set_CsbId(self,CsbId): self.add_query_param('CsbId',CsbId)
35.675676
69
0.759091
79572d319cb9ac6a60fa0748e39983dedd2cc62f
1,929
py
Python
Cfg/cfg.py
cedo1995/GenRS
a63a2d694b38e3e14727f55220afcbbd020afd55
[ "MIT" ]
null
null
null
Cfg/cfg.py
cedo1995/GenRS
a63a2d694b38e3e14727f55220afcbbd020afd55
[ "MIT" ]
null
null
null
Cfg/cfg.py
cedo1995/GenRS
a63a2d694b38e3e14727f55220afcbbd020afd55
[ "MIT" ]
null
null
null
import sys import json # Configuration class class Cfg: def __init__(self): pass @staticmethod def load_conf(path="./cfg.JSON"): """ Loads a .JSON file, used for framework configuration or hyperparam configuration :param path: path to .JSON file :return settings: it contains information read in path in the form key: value """ with open(path) as conf_file: settings = json.load(conf_file) return settings # Framework configuration class class FrmCfg(Cfg): def __init__(self, path="./cfg.JSON"): """ Set the Framework configuration through a .JSON file that contains settings. @param path: path to .JSON file to load as framework configuration file """ super().__init__() self.__dict__ = self.load_conf(path) # in this way we can access directly to each field of cfg.JSON file def save_conf(self, path="./Saved/cfg.JSON"): """ :param path: where the conf will be saved """ with open(path, 'w+') as conf_file: # TODO change it in order to write a file loaded by the load_conf function json.dump(self.__dict__, conf_file) # Alg configuration class class AlgCfg(Cfg): def __init__(self, algo, cfg_path=None): """ :param algo: name of the algorithm to load config :param cfg_path: path to .JSON hyperparams file """ super().__init__() self.algo = algo if cfg_path is None: cfg_path = "./{}_cfg.JSON".format(algo) self.cfg = self.load_conf(cfg_path) def save_conf(self, path=None): if path is None: path = "./Cfg/Saved/{}_cfg.JSON".format(self.algo) with open(path, 'w+') as conf_file: # TODO change it in order to write a file loaded by the load_conf function json.dump(self.__dict__, conf_file)
30.140625
122
0.617937
79572dd0e97cb1c57d23ce5a7dd7adbc8a9237ca
3,895
py
Python
utils.py
mbroso/constraintnet_foc
c0c4e3674c6fde87d41118cef3cae8a3a5e22a17
[ "MIT" ]
null
null
null
utils.py
mbroso/constraintnet_foc
c0c4e3674c6fde87d41118cef3cae8a3a5e22a17
[ "MIT" ]
null
null
null
utils.py
mbroso/constraintnet_foc
c0c4e3674c6fde87d41118cef3cae8a3a5e22a17
[ "MIT" ]
null
null
null
"""Utils. Containing several helper function and classes. """ import numpy as np import torch import signal import matplotlib import matplotlib.pyplot as plt import gym from AccFocEnv.plotter import Plotter # Allows to change training device. device = torch.device("cpu") def load_env(opts, dont_render=False): """Load and initialize environment. Args: dont_render: Disable rendering. Returns: Tuple containing: env: Environment state_dim: Number of state dimensions action_dim: Number of action dimensions max_action: Absolute maximum value of action plotter: Plotter object if plotting is enabled """ if opts.render and not dont_render: plotter = Plotter(opts) env = gym.make(opts.env, opts=opts, plotter=plotter) else: plotter = None env = gym.make(opts.env, opts=opts) # Set seeds env.seed(opts.seed) torch.manual_seed(opts.seed) np.random.seed(opts.seed) state_dim = env.observation_space.shape[0] action_dim = env.action_space.shape[0] max_action = float(max(abs(opts.vehicle_a_min), abs(opts.vehicle_a_max))) return env, state_dim, action_dim, max_action, plotter class ReplayBuffer(object): """Replay buffer storing transitions of the environment for experience replay """ def __init__(self, state_dim, action_dim, max_size=int(1e6)): """Initialize object Args: state_dim: Number of observation dimensions. action_dim: Number of action dimensions. max_size: Maximum size of replay buffer. """ self.max_size = max_size self.ptr = 0 self.size = 0 self.state = np.zeros((max_size, state_dim)) self.action = np.zeros((max_size, action_dim)) self.next_state = np.zeros((max_size, state_dim)) self.reward = np.zeros((max_size, 1)) self.not_done = np.zeros((max_size, 1)) def add(self, state, action, next_state, reward, done): """Adds a transition to the buffer. Args: state: Current state. action: Choosen action. next_state: Next state. reward: Observed reward. done: Done flag, indicates terminal action. """ self.state[self.ptr] = state self.action[self.ptr] = action self.next_state[self.ptr] = next_state self.reward[self.ptr] = reward self.not_done[self.ptr] = 1. - done self.ptr = (self.ptr + 1) % self.max_size self.size = min(self.size + 1, self.max_size) def sample(self, batch_size): """Samples a mini batch of the replay buffer Args: batch_size: Number of transitions to sample. Returns: Tuple containing tensors of state, action, next_state, reward and not_done. """ ind = np.random.randint(0, self.size, size=batch_size) return ( torch.FloatTensor(self.state[ind]).to(device), torch.FloatTensor(self.action[ind]).to(device), torch.FloatTensor(self.next_state[ind]).to(device), torch.FloatTensor(self.reward[ind]).to(device), torch.FloatTensor(self.not_done[ind]).to(device) ) class GracefulKiller: """Allows graceful exit of running training """ def __init__(self): """Catch SIGINT and SIGTERM signal The kill_now variable can be read to check if the user pressed Ctrl-C. """ self.kill_now = False signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) def exit_gracefully(self, signum, frame): self.kill_now = True
30.669291
88
0.61027
79572e4b098b8a6b1a1f181adcaa0951c47cc78e
3,891
py
Python
VLC_Multicell/lifi_multicell/views.py
openvlc/OpenVLC
b627beac46dfc8ab8e741ed71df3dff4a18bf955
[ "BSD-3-Clause" ]
52
2018-10-13T16:39:35.000Z
2022-03-19T18:16:54.000Z
VLC_Multicell/lifi_multicell/views.py
Sadaina/OpenVLC
c6b745960a94ef15074b7802931ac63180a9a529
[ "BSD-3-Clause" ]
6
2021-06-25T14:42:29.000Z
2021-06-25T21:37:43.000Z
VLC_Multicell/lifi_multicell/views.py
Sadaina/SadainaVLC
c6b745960a94ef15074b7802931ac63180a9a529
[ "BSD-3-Clause" ]
28
2018-10-13T16:39:52.000Z
2022-03-28T19:19:51.000Z
import tkinter as tk from tkinter import ttk from tkinter import messagebox from lifi_multicell.constants import * import lifi_multicell.widgets as w from lifi_multicell.controller import Controller class MainView(tk.Frame): def __init__(self, **kwargs): super().__init__(**kwargs) self.c = Controller() # Interactions self.id_text = tk.StringVar() self.id_text.set("1") self.id_label = w.DeviceIdFrame(self, textvariable=self.id_text, font=("TkDefaultFont", 10), width=3, anchor=tk.CENTER) self.id_label.grid(row=2, column=0, sticky=tk.E) self.on_button = ttk.Button(self, text="ON", command=lambda state="ON": self.on_device(state), width=8) self.on_button.grid(row=2, column=1, sticky=tk.E) self.off_button = ttk.Button(self, text="OFF", command=lambda state="OFF": self.off_device(state), width=8) self.off_button.grid(row=2, column=2, sticky=tk.E) self.ssh_button = ttk.Button(self, text="SSH", command=lambda state="SSH": self.ssh_device(state), width=8) self.ssh_button.grid(row=2, column=3, sticky=tk.E) # Devices board representation self.board = w.DeviceBoard() self.board.grid(row=0, columnspan=4, sticky=tk.E) self.board.bind("<Configure>", self.redraw) def redraw(self, event=None): """ Draws the GUI showing the network state """ self.board.delete("rect") cellwidth = int(self.board.winfo_width() / columns_dev) cellheight = int(self.board.winfo_height() / rows_dev) for column in range(columns_dev): for row in range(rows_dev): x1 = column * cellwidth y1 = row * cellheight x2 = x1 + cellwidth y2 = y1 + cellheight tile = self.board.create_rectangle(x1, y1, x2, y2, fill="red", tags="rect") self.board.tiles[row, column] = tile self.board.tag_bind(tile, "<1>", lambda event, row=row, column=column: self.clicked(row=row, column=column, )) tile_id = (str(row * columns_dev + column + 1)) self.board.tiles_id[row, column] = tile_id self.board.create_text(x1 + 15, y1 + 15, fill="darkblue", font="Times 15 italic bold", text=tile_id) self.board.grid(row=1, sticky=tk.E) def clicked(self, row, column): tile_id = self.board.tiles_id[row, column] self.set_text_(dev_Id=tile_id) def set_text_(self, dev_Id=None): if self.id_label.existingDevice(dev_Id): self.id_text.set(dev_Id) def on_device(self, state): dev_id = int(self.id_text.get()) self.c.turn_on_device(dev_id) self.switch_color(dev_id, state) def off_device(self, state): dev_id = int(self.id_text.get()) turn_off = self.c.turn_off_device(dev_id) if turn_off == 1: messagebox.showwarning(ssh_warning_title, ssh_warning_msg) else: self.switch_color(dev_id, state) def ssh_device(self, state): dev_id = int(self.id_text.get()) self.c.ssh_device(dev_id) self.switch_color(dev_id, state) def id_to_tile(self, dev_id): """ Calculates the row and column for a selected device ID :return: int tuple [row, column] """ row = dev_id // columns_dev column = dev_id - row * columns_dev - 1 return [row, column] def switch_color(self, dev_id, state): [row, column] = self.id_to_tile(dev_id) tile = self.board.tiles[row, column] self.board.itemconfigure(tile, fill=tile_color[state]) class SshWarning(tk.messagebox.Message): def __init__(self, **kwargs): super().__init__(**kwargs) self.showwarning(title=ssh_warning_title, message=ssh_warning_msg)
36.707547
127
0.621177
79572eb7b598edd00d2b3a2ee976438f7f7a423e
643
py
Python
py-faster-rcnn/lib/fast_rcnn/nms_wrapper.py
pierre-ecarlat/food_detection
c23f328d1b04c4a97bbfdaa49846507115bd2c7e
[ "BSD-2-Clause" ]
null
null
null
py-faster-rcnn/lib/fast_rcnn/nms_wrapper.py
pierre-ecarlat/food_detection
c23f328d1b04c4a97bbfdaa49846507115bd2c7e
[ "BSD-2-Clause" ]
null
null
null
py-faster-rcnn/lib/fast_rcnn/nms_wrapper.py
pierre-ecarlat/food_detection
c23f328d1b04c4a97bbfdaa49846507115bd2c7e
[ "BSD-2-Clause" ]
null
null
null
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- from fast_rcnn.config import cfg from nms.gpu_nms import gpu_nms from nms.cpu_nms import cpu_nms def nms(dets, thresh, force_cpu=False): """Dispatch to either CPU or GPU NMS implementations.""" if dets.shape[0] == 0: return [] if cfg.USE_GPU_NMS and not force_cpu: return gpu_nms(dets, thresh, device_id=cfg.GPU_ID) else: return cpu_nms(dets, thresh)
30.619048
60
0.575428
79572f77eded687a173638e5d3f730d69c32d42e
9,408
py
Python
uw_spotseeker/tests/test_spot.py
devights/uw-restclients-spotseeker
d692773b4b3b6057c94748f35ba7d602cd53d016
[ "Apache-2.0" ]
1
2018-05-03T00:45:07.000Z
2018-05-03T00:45:07.000Z
uw_spotseeker/tests/test_spot.py
devights/uw-restclients-spotseeker
d692773b4b3b6057c94748f35ba7d602cd53d016
[ "Apache-2.0" ]
4
2019-12-16T19:49:21.000Z
2022-01-19T01:59:44.000Z
uw_spotseeker/tests/test_spot.py
uw-it-aca/uw-restclients-spotseeker
42b5dae637bcde875b27b32a37fe4dd9f867c537
[ "Apache-2.0" ]
null
null
null
# Copyright 2022 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from uw_spotseeker import Spotseeker from uw_spotseeker.utilities import fdao_spotseeker_override from restclients_core.exceptions import ( DataFailureException) from unittest import TestCase from PIL import Image import dateutil.parser import os import json try: from BytesIO import BytesIO except ImportError: from io import BytesIO @fdao_spotseeker_override class SpotseekerTestSpot(TestCase): def test_get_all_spots(self): spotseeker = Spotseeker() all_spots = spotseeker.all_spots() self.assertEqual(len(all_spots), 3) def test_get_spot(self): spotseeker = Spotseeker() spot_data = spotseeker.get_spot_by_id(123) self.assertEqual(spot_data.spot_id, "123") self.assertEqual(spot_data.name, "Test Spot") self.assertEqual(spot_data.uri, "/api/v1/spot/123") self.assertEqual(spot_data.latitude, 3.60) self.assertEqual(spot_data.longitude, 1.34) self.assertEqual(spot_data.height_from_sea_level, 0.10) self.assertEqual(spot_data.building_name, "Test Building") self.assertEqual(spot_data.floor, 0) self.assertEqual(spot_data.room_number, "456") self.assertEqual(spot_data.capacity, 0) self.assertEqual(spot_data.display_access_restrictions, "none") self.assertEqual(spot_data.organization, "Test Org") self.assertEqual(spot_data.manager, "Mr Test Org") self.assertEqual(spot_data.etag, "686897696a7c876b7e") self.assertEqual(spot_data.external_id, "asd123") self.assertEqual(spot_data.last_modified, dateutil.parser.parse("2012-07-13T05:00:00+00:00")) self._assert_spot_types(spot_data.spot_types, ["study_room", "cafe"]) self.assertEqual(len(spot_data.images), 1) self.assertEqual(spot_data.images[0].image_id, "1") self.assertEqual(spot_data.images[0].url, "/api/v1/spot/123/image/1") self.assertEqual(spot_data.images[0].content_type, "image/jpeg") self.assertEqual(spot_data.images[0].width, 0) self.assertEqual(spot_data.images[0].height, 0) self.assertEqual(spot_data.images[0].creation_date, dateutil.parser.parse( "Sun, 06 Nov 1994 08:49:37 GMT")) self.assertEqual(spot_data.images[0].modification_date, dateutil.parser.parse( "Mon, 07 Nov 1994 01:49:37 GMT")) self.assertEqual(spot_data.images[0].upload_user, "user name") self.assertEqual(spot_data.images[0].upload_application, "application name") self.assertEqual(spot_data.images[0].thumbnail_root, "/api/v1/spot/123/image/1/thumb") self.assertEqual(spot_data.images[0].description, "Information about the image") self.assertEqual(spot_data.images[0].display_index, 0) self.assertEqual(len(spot_data.spot_availability), 7) self._assert_spot_extended_info(spot_data.extended_info, [ ("field2", 0), ("field3", 0.0), ("whiteboards", True) ]) def test_search_spots(self): """ Tests search_spots function with mock data provided in the file named : spot?limit=5&center_latitude=47.653811& center_longitude=-122.307815&distance=100000& fuzzy_hours_start=Tuesday%2C05%3A00&fuzzy_hours_end= Tuesday%2C11%3A00&extended_info%3Aapp_type=food tests mock data is accessible if filename matches order of query_tuple passed. """ spotseeker = Spotseeker() query_tuple = [ ('limit', 5), ('center_latitude', u'47.653811'), ('center_longitude', u'-122.307815'), ('distance', 100000), ('fuzzy_hours_start', 'Tuesday,05:00'), ('fuzzy_hours_end', 'Tuesday,11:00'), ('extended_info:app_type', 'food')] spot_data_list = spotseeker.search_spots(query_tuple) spot_data = spot_data_list[0] self.assertEqual(len(spot_data_list), 5) self.assertEqual(spot_data.spot_id, 40) self.assertEqual(spot_data.name, "TestSpot1") self.assertEqual(spot_data.uri, "/api/v1/spot/40") self.assertEqual(spot_data.latitude, 47) self.assertEqual(spot_data.longitude, -12) self.assertEqual(spot_data.height_from_sea_level, 0.10) self.assertEqual(spot_data.building_name, "TestBuilding") self.assertEqual(spot_data.capacity, 0) self.assertEqual(spot_data.organization, "Test Org") self.assertEqual(spot_data.manager, "Test Manager") self.assertEqual(spot_data.etag, "123456789") self.assertEqual(spot_data.last_modified, dateutil.parser.parse("2012-07-13T05:00:00+00:00")) self.assertEqual(len(spot_data.images), 1) self.assertEqual(spot_data.images[0].image_id, "1") self.assertEqual(spot_data.images[0].url, "/api/v1/spot/123/image/1") self.assertEqual(spot_data.images[0].content_type, "image/jpeg") self.assertEqual(spot_data.images[0].width, 0) self.assertEqual(spot_data.images[0].height, 0) self.assertEqual(spot_data.images[0].creation_date, dateutil.parser.parse( "Sun, 06 Nov 1994 08:49:37 GMT")) self.assertEqual(spot_data.images[0].modification_date, dateutil.parser.parse( "Mon, 07 Nov 1994 01:49:37 GMT")) self.assertEqual(spot_data.images[0].upload_user, "user name") self.assertEqual(spot_data.images[0].upload_application, "application name") self.assertEqual(spot_data.images[0].thumbnail_root, "/api/v1/spot/123/image/1/thumb") self.assertEqual(spot_data.images[0].description, "Information about the image") self.assertEqual(spot_data.images[0].display_index, 0) self.assertEqual(len(spot_data.spot_availability), 5) def test_spot_items(self): spotseeker = Spotseeker() spot_data = spotseeker.get_spot_by_id(1) self.assertEqual(len(spot_data.items), 2) def test_bad_spot(self): spotseeker = Spotseeker() self.assertRaises(DataFailureException, spotseeker.get_spot_by_id, 999) def test_post_spot(self): spotseeker = Spotseeker() spot_data = spotseeker.get_spot_by_id(1) self.assertRaises(DataFailureException, spotseeker.post_spot, spot_data) def test_delete_spot(self): spotseeker = Spotseeker() spot_data = spotseeker.get_spot_by_id(1) response, content = spotseeker.delete_spot(1, "XXX") result = json.loads(content.decode('utf-8')) self.assertEqual(spot_data.spot_id, result["id"]) def test_put_spot(self): spotseeker = Spotseeker() directory = os.path.dirname(__file__) path = "../resources/spotseeker/file/api/v1/spot/1" mock_path = os.path.join(directory, path) with open(mock_path) as f: spot_json = json.load(f) response, content = spotseeker.put_spot(1, spot_json, "XXX") self.assertEqual(json.loads(content.decode('utf-8')), spot_json) def test_building_list(self): spotseeker = Spotseeker() buildings = spotseeker.get_building_list("seattle") self.assertEqual(len(buildings), 43) def test_get_image(self): directory = os.path.dirname(__file__) path = "../resources/spotseeker/file/api/v1/spot/20/image/1" mock_path = os.path.join(directory, path) with open(mock_path, "rb") as f: expected_img = Image.open(BytesIO(bytearray(f.read()))) spotseeker = Spotseeker() response, content = spotseeker.get_spot_image(20, 1) byte_img = bytearray(response.data) img = Image.open(BytesIO(byte_img)) self.assertEqual(img, expected_img) def test_post_image(self): spotseeker = Spotseeker() response = spotseeker.post_image(1, "") self.assertEqual(response, '') def test_delete_image(self): spotseeker = Spotseeker() response = spotseeker.delete_image(20, 1, "XXX") def test_post_item_image(self): spotseeker = Spotseeker() response = spotseeker.post_item_image(1, "") self.assertEqual(response, '') def test_delete_item_image(self): spotseeker = Spotseeker() response = spotseeker.delete_item_image(20, 1, "XXX") def _assert_spot_types(self, spot_types, type_stings): spot_types = [spot_type.name for spot_type in spot_types] self.assertEqual(set(spot_types), set(type_stings)) def _assert_spot_extended_info(self, spot_ei_data, ei_tuples): spot_ei_tuples = [(spot_ei.key, spot_ei.value) for spot_ei in spot_ei_data] self.assertEqual(set(spot_ei_tuples), set(ei_tuples))
42.958904
77
0.633291
79572fba8586691f8f62990e086c77d0fdcaa37e
3,877
py
Python
mushr_rhc_ros/src/mingpt/model_resnetdirect.py
rogeriobonatti/mushr_rhc
8316cad6544997c1742cc5f5b539f5886eb00e7f
[ "BSD-3-Clause" ]
null
null
null
mushr_rhc_ros/src/mingpt/model_resnetdirect.py
rogeriobonatti/mushr_rhc
8316cad6544997c1742cc5f5b539f5886eb00e7f
[ "BSD-3-Clause" ]
null
null
null
mushr_rhc_ros/src/mingpt/model_resnetdirect.py
rogeriobonatti/mushr_rhc
8316cad6544997c1742cc5f5b539f5886eb00e7f
[ "BSD-3-Clause" ]
null
null
null
""" GPT model: - the initial stem consists of a combination of token encoding and a positional encoding - the meat of it is a uniform sequence of Transformer blocks - each Transformer is a sequential combination of a 1-hidden-layer MLP block and a self-attention block - all blocks feed into a central residual pathway similar to resnets - the final decoder is a linear projection into a vanilla Softmax classifier """ import math import logging import torch import torch.nn as nn from torch.nn import functional as F from resnet_custom import resnet18_custom, resnet50_custom logger = logging.getLogger(__name__) import numpy as np import sys sys.path.append('../') from models.compass.select_backbone import select_resnet class ResnetDirect(nn.Module): """ the full GPT language model, with a context size of block_size """ def __init__(self, device, clip_len, restype): super().__init__() self.device = device if restype=='resnet18': self.resnet = resnet18_custom(pretrained=False, clip_len=clip_len+1) elif restype=='resnet50': self.resnet = resnet50_custom(pretrained=False, clip_len=clip_len+1) self.state_encoder = nn.Sequential(nn.Linear(1000, 64), nn.ReLU(), nn.Linear(64, 32), nn.ReLU(), nn.Linear(32,1)) logger.info("number of parameters: %e", sum(p.numel() for p in self.parameters())) criterion = torch.nn.MSELoss(reduction='mean') self.criterion = criterion.cuda(device) def configure_optimizers(self, train_config): optimizer = torch.optim.Adam(self.parameters(), train_config.learning_rate) return optimizer # state, and action def forward(self, x_imgs, x_act, y_imgs=None, y_act=None): # states: (batch, block_size, 4*84*84) # actions: (batch, block_size, 1) # targets: (batch, block_size, 1) # timesteps: (batch, 1, 1) # print("batch forward") input = torch.cat((x_imgs, y_imgs), dim=1) action_preds = self.state_encoder(self.resnet(input)) loss = None if y_act is not None: loss = self.criterion(y_act, action_preds) return action_preds, loss class ResnetDirectWithActions(nn.Module): """ the full GPT language model, with a context size of block_size """ def __init__(self, device, clip_len, restype): super().__init__() self.device = device if restype=='resnet18': self.resnet = resnet18_custom(pretrained=False, clip_len=clip_len+1) elif restype=='resnet50': self.resnet = resnet50_custom(pretrained=False, clip_len=clip_len+1) self.actions_encoder = nn.Sequential(nn.Linear(clip_len, 64), nn.ReLU(), nn.Linear(64, 128), nn.ReLU()) self.state_encoder = nn.Sequential(nn.Linear(1000+128, 64), nn.ReLU(), nn.Linear(64, 32), nn.ReLU(), nn.Linear(32,1)) logger.info("number of parameters: %e", sum(p.numel() for p in self.parameters())) criterion = torch.nn.MSELoss(reduction='mean') self.criterion = criterion.cuda(device) def configure_optimizers(self, train_config): optimizer = torch.optim.Adam(self.parameters(), train_config.learning_rate) return optimizer # state, and action def forward(self, x_imgs, x_act, y_imgs=None, y_act=None): # states: (batch, block_size, 4*84*84) # actions: (batch, block_size, 1) # targets: (batch, block_size, 1) # timesteps: (batch, 1, 1) # print("batch forward") input = torch.cat((x_imgs, y_imgs), dim=1) action_preds = self.state_encoder(torch.cat((self.resnet(input), self.actions_encoder(x_act)), dim=1)) loss = None if y_act is not None: loss = self.criterion(y_act, action_preds) return action_preds, loss
34.616071
125
0.66082
79572ff9f733a4ca33f1dd4ba2c1a114c25cacdf
3,614
py
Python
PaddleCV/metric_learning/eval.py
suytingwan/models
ccdbfe77d071cc19b55fb9f4b738912e35d982ef
[ "Apache-2.0" ]
5
2021-09-28T13:28:01.000Z
2021-12-21T07:25:44.000Z
PaddleCV/metric_learning/eval.py
suytingwan/models
ccdbfe77d071cc19b55fb9f4b738912e35d982ef
[ "Apache-2.0" ]
null
null
null
PaddleCV/metric_learning/eval.py
suytingwan/models
ccdbfe77d071cc19b55fb9f4b738912e35d982ef
[ "Apache-2.0" ]
3
2021-09-28T15:33:45.000Z
2021-09-29T01:44:32.000Z
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import math import time import argparse import functools import numpy as np import paddle import paddle.fluid as fluid import models import reader from utility import add_arguments, print_arguments, check_cuda from utility import fmt_time, recall_topk # yapf: disable parser = argparse.ArgumentParser(description=__doc__) add_arg = functools.partial(add_arguments, argparser=parser) add_arg('model', str, "ResNet50", "Set the network to use.") add_arg('embedding_size', int, 0, "Embedding size.") add_arg('batch_size', int, 10, "Minibatch size.") add_arg('image_shape', str, "3,224,224", "Input image size.") add_arg('use_gpu', bool, True, "Whether to use GPU or not.") add_arg('pretrained_model', str, None, "Whether to use pretrained model.") # yapf: enable model_list = [m for m in dir(models) if "__" not in m] def eval(args): # parameters from arguments model_name = args.model pretrained_model = args.pretrained_model image_shape = [int(m) for m in args.image_shape.split(",")] assert model_name in model_list, "{} is not in lists: {}".format(args.model, model_list) image = fluid.layers.data(name='image', shape=image_shape, dtype='float32') label = fluid.layers.data(name='label', shape=[1], dtype='int64') # model definition model = models.__dict__[model_name]() out = model.net(input=image, embedding_size=args.embedding_size) test_program = fluid.default_main_program().clone(for_test=True) place = fluid.CUDAPlace(0) if args.use_gpu else fluid.CPUPlace() exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) if pretrained_model: def if_exist(var): return os.path.exists(os.path.join(pretrained_model, var.name)) fluid.io.load_vars(exe, pretrained_model, predicate=if_exist) test_reader = paddle.batch(reader.test(args), batch_size=args.batch_size, drop_last=False) feeder = fluid.DataFeeder(place=place, feed_list=[image, label]) fetch_list = [out.name] f, l = [], [] for batch_id, data in enumerate(test_reader()): t1 = time.time() [feas] = exe.run(test_program, fetch_list=fetch_list, feed=feeder.feed(data)) label = np.asarray([x[1] for x in data]) f.append(feas) l.append(label) t2 = time.time() period = t2 - t1 if batch_id % 20 == 0: print("[%s] testbatch %d, time %2.2f sec" % \ (fmt_time(), batch_id, period)) f = np.vstack(f) l = np.hstack(l) recall = recall_topk(f, l, k=1) print("[%s] End test %d, test_recall %.5f" % (fmt_time(), len(f), recall)) sys.stdout.flush() def main(): args = parser.parse_args() print_arguments(args) check_cuda(args.use_gpu) eval(args) if __name__ == '__main__': main()
32.854545
94
0.683177
795730b00ff3293429e80e108e77b0238982f206
625
py
Python
invenio_subjects_gnd/writer.py
ulbmuenster/invenio-subjects-gnd
20fc042df2675ee59d9def4b96e77ceb7035841c
[ "MIT" ]
null
null
null
invenio_subjects_gnd/writer.py
ulbmuenster/invenio-subjects-gnd
20fc042df2675ee59d9def4b96e77ceb7035841c
[ "MIT" ]
2
2022-01-27T09:46:26.000Z
2022-02-03T12:03:59.000Z
invenio_subjects_gnd/writer.py
ulbmuenster/invenio-subjects-gnd
20fc042df2675ee59d9def4b96e77ceb7035841c
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # # Copyright (C) 2021 Northwestern University. # Copyright (C) 2022 University of Münster. # # invenio-subjects-gnd is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see LICENSE file for more # details. """GND subjects_gnd.yaml writer.""" from pathlib import Path import yaml def write_yaml( entries, filepath=Path(__file__).parent / "vocabularies/subjects_gnd.yaml" ): """Write the GND yaml file. Return filepath to written file. """ with open(filepath, "w") as f: yaml.dump(list(entries), f) return filepath
21.551724
73
0.688
7957319283ec8e1c961dcbf617e8d00eb10094b4
85,839
py
Python
Bio/Restriction/Restriction.py
rchurt/biopython
4e9a15172ba26bae104eaa7f05819cd6d41d0da8
[ "BSD-3-Clause" ]
2
2020-06-25T12:52:03.000Z
2020-07-11T09:47:34.000Z
Bio/Restriction/Restriction.py
EmmanuelOwusu/biopython
4e9a15172ba26bae104eaa7f05819cd6d41d0da8
[ "BSD-3-Clause" ]
null
null
null
Bio/Restriction/Restriction.py
EmmanuelOwusu/biopython
4e9a15172ba26bae104eaa7f05819cd6d41d0da8
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # # Restriction Analysis Libraries. # Copyright (C) 2004. Frederic Sohm. # # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. # """Restriction Enzyme classes. Notes about the diverses class of the restriction enzyme implementation:: RestrictionType is the type of all restriction enzymes. ----------------------------------------------------------------------- AbstractCut implements some methods that are common to all enzymes. ----------------------------------------------------------------------- NoCut, OneCut,TwoCuts represent the number of double strand cuts produced by the enzyme. they correspond to the 4th field of the rebase record emboss_e.NNN. 0->NoCut : the enzyme is not characterised. 2->OneCut : the enzyme produce one double strand cut. 4->TwoCuts : two double strand cuts. ----------------------------------------------------------------------- Meth_Dep, Meth_Undep represent the methylation susceptibility to the enzyme. Not implemented yet. ----------------------------------------------------------------------- Palindromic, if the site is palindromic or not. NotPalindromic allow some optimisations of the code. No need to check the reverse strand with palindromic sites. ----------------------------------------------------------------------- Unknown, Blunt, represent the overhang. Ov5, Ov3 Unknown is here for symmetry reasons and correspond to enzymes that are not characterised in rebase. ----------------------------------------------------------------------- Defined, Ambiguous, represent the sequence of the overhang. NotDefined NotDefined is for enzymes not characterised in rebase. Defined correspond to enzymes that display a constant overhang whatever the sequence. ex : EcoRI. G^AATTC -> overhang :AATT CTTAA^G Ambiguous : the overhang varies with the sequence restricted. Typically enzymes which cut outside their restriction site or (but not always) inside an ambiguous site. ex: AcuI CTGAAG(22/20) -> overhang : NN AasI GACNNN^NNNGTC -> overhang : NN CTGN^NNNNNCAG note : these 3 classes refers to the overhang not the site. So the enzyme ApoI (RAATTY) is defined even if its restriction site is ambiguous. ApoI R^AATTY -> overhang : AATT -> Defined YTTAA^R Accordingly, blunt enzymes are always Defined even when they cut outside their restriction site. ----------------------------------------------------------------------- Not_available, as found in rebase file emboss_r.NNN files. Commercially_available allow the selection of the enzymes according to their suppliers to reduce the quantity of results. Also will allow the implementation of buffer compatibility tables. Not implemented yet. the list of suppliers is extracted from emboss_s.NNN ----------------------------------------------------------------------- """ import warnings import re import itertools from Bio.Seq import Seq, MutableSeq from Bio.Restriction.Restriction_Dictionary import rest_dict as enzymedict from Bio.Restriction.Restriction_Dictionary import typedict from Bio.Restriction.Restriction_Dictionary import suppliers as suppliers_dict from Bio.Restriction.PrintFormat import PrintFormat from Bio import BiopythonWarning # Used to use Bio.Restriction.DNAUtils.check_bases (and expose it under this # namespace), but have deprecated that module. def _check_bases(seq_string): """Check characters in a string (PRIVATE). Remove digits and white space present in string. Allows any valid ambiguous IUPAC DNA single letters codes (ABCDGHKMNRSTVWY, lower case are converted). Other characters (e.g. symbols) trigger a TypeError. Returns the string WITH A LEADING SPACE (!). This is for backwards compatibility, and may in part be explained by the fact that ``Bio.Restriction`` doesn't use zero based counting. """ # Remove white space and make upper case: seq_string = "".join(seq_string.split()).upper() # Remove digits for c in "0123456789": seq_string = seq_string.replace(c, "") # Check only allowed IUPAC letters if not set(seq_string).issubset(set("ABCDGHKMNRSTVWY")): raise TypeError("Invalid character found in %s" % repr(seq_string)) return " " + seq_string matching = { "A": "ARWMHVDN", "C": "CYSMHBVN", "G": "GRSKBVDN", "T": "TYWKHBDN", "R": "ABDGHKMNSRWV", "Y": "CBDHKMNSTWVY", "W": "ABDHKMNRTWVY", "S": "CBDGHKMNSRVY", "M": "ACBDHMNSRWVY", "K": "BDGHKNSRTWVY", "H": "ACBDHKMNSRTWVY", "B": "CBDGHKMNSRTWVY", "V": "ACBDGHKMNSRWVY", "D": "ABDGHKMNSRTWVY", "N": "ACBDGHKMNSRTWVY", } DNA = Seq class FormattedSeq: """A linear or circular sequence object for restriction analysis. Translates a Bio.Seq into a formatted sequence to be used with Restriction. Roughly: remove anything which is not IUPAC alphabet and then add a space in front of the sequence to get a biological index instead of a python index (i.e. index of the first base is 1 not 0). Retains information about the shape of the molecule linear (default) or circular. Restriction sites are search over the edges of circular sequence. """ def __init__(self, seq, linear=True): """Initialize ``FormattedSeq`` with sequence and topology (optional). ``seq`` is either a ``Bio.Seq``, ``Bio.MutableSeq`` or a ``FormattedSeq``. If ``seq`` is a ``FormattedSeq``, ``linear`` will have no effect on the shape of the sequence. """ if isinstance(seq, (Seq, MutableSeq)): stringy = str(seq) self.lower = stringy.islower() # Note this adds a leading space to the sequence (!) self.data = _check_bases(stringy) self.linear = linear self.klass = seq.__class__ elif isinstance(seq, FormattedSeq): self.lower = seq.lower self.data = seq.data self.linear = seq.linear self.klass = seq.klass else: raise TypeError("expected Seq or MutableSeq, got %s" % type(seq)) def __len__(self): """Return length of ``FormattedSeq``. ``FormattedSeq`` has a leading space, thus substract 1. """ return len(self.data) - 1 def __repr__(self): """Represent ``FormattedSeq`` class as a string.""" return "FormattedSeq(%s, linear=%s)" % (repr(self[1:]), repr(self.linear)) def __eq__(self, other): """Implement equality operator for ``FormattedSeq`` object.""" if isinstance(other, FormattedSeq): if repr(self) == repr(other): return True else: return False return False def circularise(self): """Circularise sequence in place.""" self.linear = False return def linearise(self): """Linearise sequence in place.""" self.linear = True return def to_linear(self): """Make a new instance of sequence as linear.""" new = self.__class__(self) new.linear = True return new def to_circular(self): """Make a new instance of sequence as circular.""" new = self.__class__(self) new.linear = False return new def is_linear(self): """Return if sequence is linear (True) or circular (False).""" return self.linear def finditer(self, pattern, size): """Return a list of a given pattern which occurs in the sequence. The list is made of tuple (location, pattern.group). The latter is used with non palindromic sites. Pattern is the regular expression pattern corresponding to the enzyme restriction site. Size is the size of the restriction enzyme recognition-site size. """ if self.is_linear(): data = self.data else: data = self.data + self.data[1:size] return [(i.start(), i.group) for i in re.finditer(pattern, data)] def __getitem__(self, i): """Return substring of ``FormattedSeq``. The class of the returned object is the class of the respective sequence. Note that due to the leading space, indexing is 1-based: >>> from Bio.Seq import Seq >>> from Bio.Restriction.Restriction import FormattedSeq >>> f_seq = FormattedSeq(Seq('ATGCATGC')) >>> f_seq[1] Seq('A') """ if self.lower: return self.klass(self.data[i].lower()) return self.klass(self.data[i]) class RestrictionType(type): """RestrictionType. Type from which all enzyme classes are derived. Implement the operator methods. """ def __init__(cls, name="", bases=(), dct=None): """Initialize RestrictionType instance. Not intended to be used in normal operation. The enzymes are instantiated when importing the module. See below. """ if "-" in name: raise ValueError("Problem with hyphen in %s as enzyme name" % repr(name)) # 2011/11/26 - Nobody knows what this call was supposed to accomplish, # but all unit tests seem to pass without it. # super().__init__(cls, name, bases, dct) try: cls.compsite = re.compile(cls.compsite) except AttributeError: # Can happen if initialised wrongly. # (This was seen when Sphinx api-doc imports the classes, and # tried to automatically general documentation for them) pass except Exception: raise ValueError( "Problem with regular expression, re.compiled(%r)" % cls.compsite ) from None def __add__(cls, other): """Add restriction enzyme to a RestrictionBatch(). If other is an enzyme returns a batch of the two enzymes. If other is already a RestrictionBatch add enzyme to it. """ if isinstance(other, RestrictionType): return RestrictionBatch([cls, other]) elif isinstance(other, RestrictionBatch): return other.add_nocheck(cls) else: raise TypeError def __truediv__(cls, other): """Override '/' operator to use as search method. >>> from Bio.Restriction import EcoRI >>> EcoRI/Seq('GAATTC') [2] Returns RE.search(other). """ return cls.search(other) def __rtruediv__(cls, other): """Override division with reversed operands to use as search method. >>> from Bio.Restriction import EcoRI >>> Seq('GAATTC')/EcoRI [2] Returns RE.search(other). """ return cls.search(other) def __floordiv__(cls, other): """Override '//' operator to use as catalyse method. >>> from Bio.Restriction import EcoRI >>> EcoRI//Seq('GAATTC') (Seq('G'), Seq('AATTC')) Returns RE.catalyse(other). """ return cls.catalyse(other) def __rfloordiv__(cls, other): """As __floordiv__, with reversed operands. >>> from Bio.Restriction import EcoRI >>> Seq('GAATTC')//EcoRI (Seq('G'), Seq('AATTC')) Returns RE.catalyse(other). """ return cls.catalyse(other) def __str__(cls): """Return the name of the enzyme as string.""" return cls.__name__ def __repr__(cls): """Implement repr method. Used with eval or exec will instantiate the enzyme. """ return "%s" % cls.__name__ def __len__(cls): """Return length of recognition site of enzyme as int.""" try: return cls.size except AttributeError: # Happens if the instance was not initialised as expected. # e.g. if instance created by a documentation framework # like Sphinx trying to inspect the class automatically, # Also seen within IPython. return 0 def __hash__(cls): """Implement ``hash()`` method for ``RestrictionType``. Python default is to use ``id(...)`` This is consistent with the ``__eq__`` implementation """ return id(cls) def __eq__(cls, other): """Override '==' operator. True if RE and other are the same enzyme. Specifically this checks they are the same Python object. """ # assert (id(cls)==id(other)) == (other is cls) == (cls is other) return id(cls) == id(other) def __ne__(cls, other): """Override '!=' operator. Isoschizomer strict (same recognition site, same restriction) -> False All the other-> True WARNING - This is not the inverse of the __eq__ method >>> from Bio.Restriction import SacI, SstI >>> SacI != SstI # true isoschizomers False >>> SacI == SstI False """ if not isinstance(other, RestrictionType): return True elif cls.charac == other.charac: return False else: return True def __rshift__(cls, other): """Override '>>' operator to test for neoschizomers. neoschizomer : same recognition site, different restriction. -> True all the others : -> False >>> from Bio.Restriction import SmaI, XmaI >>> SmaI >> XmaI True """ if not isinstance(other, RestrictionType): return False elif cls.site == other.site and cls.charac != other.charac: return True else: return False def __mod__(cls, other): """Override '%' operator to test for compatible overhangs. True if a and b have compatible overhang. >>> from Bio.Restriction import XhoI, SalI >>> XhoI % SalI True """ if not isinstance(other, RestrictionType): raise TypeError("expected RestrictionType, got %s instead" % type(other)) return cls._mod1(other) def __ge__(cls, other): """Compare length of recognition site of two enzymes. Override '>='. a is greater or equal than b if the a site is longer than b site. If their site have the same length sort by alphabetical order of their names. >>> from Bio.Restriction import EcoRI, EcoRV >>> EcoRI.size 6 >>> EcoRV.size 6 >>> EcoRI >= EcoRV False """ if not isinstance(other, RestrictionType): raise NotImplementedError if len(cls) > len(other): return True elif cls.size == len(other) and cls.__name__ >= other.__name__: return True else: return False def __gt__(cls, other): """Compare length of recognition site of two enzymes. Override '>'. Sorting order: 1. size of the recognition site. 2. if equal size, alphabetical order of the names. """ if not isinstance(other, RestrictionType): raise NotImplementedError if len(cls) > len(other): return True elif cls.size == len(other) and cls.__name__ > other.__name__: return True else: return False def __le__(cls, other): """Compare length of recognition site of two enzymes. Override '<='. Sorting order: 1. size of the recognition site. 2. if equal size, alphabetical order of the names. """ if not isinstance(other, RestrictionType): raise NotImplementedError elif len(cls) < len(other): return True elif len(cls) == len(other) and cls.__name__ <= other.__name__: return True else: return False def __lt__(cls, other): """Compare length of recognition site of two enzymes. Override '<'. Sorting order: 1. size of the recognition site. 2. if equal size, alphabetical order of the names. """ if not isinstance(other, RestrictionType): raise NotImplementedError elif len(cls) < len(other): return True elif len(cls) == len(other) and cls.__name__ < other.__name__: return True else: return False class AbstractCut(RestrictionType): """Implement the methods that are common to all restriction enzymes. All the methods are classmethod. For internal use only. Not meant to be instantiated. """ @classmethod def search(cls, dna, linear=True): """Return a list of cutting sites of the enzyme in the sequence. Compensate for circular sequences and so on. dna must be a Bio.Seq.Seq instance or a Bio.Seq.MutableSeq instance. If linear is False, the restriction sites that span over the boundaries will be included. The positions are the first base of the 3' fragment, i.e. the first base after the position the enzyme will cut. """ # # Separating search from _search allow a (very limited) optimisation # of the search when using a batch of restriction enzymes. # in this case the DNA is tested once by the class which implements # the batch instead of being tested by each enzyme single. # see RestrictionBatch.search() for example. # if isinstance(dna, FormattedSeq): cls.dna = dna return cls._search() else: cls.dna = FormattedSeq(dna, linear) return cls._search() @classmethod def all_suppliers(cls): """Print all the suppliers of restriction enzyme.""" supply = sorted(x[0] for x in suppliers_dict.values()) print(",\n".join(supply)) return @classmethod def is_equischizomer(cls, other): """Test for real isoschizomer. True if other is an isoschizomer of RE, but not an neoschizomer, else False. Equischizomer: same site, same position of restriction. >>> from Bio.Restriction import SacI, SstI, SmaI, XmaI >>> SacI.is_equischizomer(SstI) True >>> SmaI.is_equischizomer(XmaI) False """ return not cls != other @classmethod def is_neoschizomer(cls, other): """Test for neoschizomer. True if other is an isoschizomer of RE, else False. Neoschizomer: same site, different position of restriction. """ return cls >> other @classmethod def is_isoschizomer(cls, other): """Test for same recognition site. True if other has the same recognition site, else False. Isoschizomer: same site. >>> from Bio.Restriction import SacI, SstI, SmaI, XmaI >>> SacI.is_isoschizomer(SstI) True >>> SmaI.is_isoschizomer(XmaI) True """ return (not cls != other) or cls >> other @classmethod def equischizomers(cls, batch=None): """List equischizomers of the enzyme. Return a tuple of all the isoschizomers of RE. If batch is supplied it is used instead of the default AllEnzymes. Equischizomer: same site, same position of restriction. """ if not batch: batch = AllEnzymes r = [x for x in batch if not cls != x] i = r.index(cls) del r[i] r.sort() return r @classmethod def neoschizomers(cls, batch=None): """List neoschizomers of the enzyme. Return a tuple of all the neoschizomers of RE. If batch is supplied it is used instead of the default AllEnzymes. Neoschizomer: same site, different position of restriction. """ if not batch: batch = AllEnzymes r = sorted(x for x in batch if cls >> x) return r @classmethod def isoschizomers(cls, batch=None): """List all isoschizomers of the enzyme. Return a tuple of all the equischizomers and neoschizomers of RE. If batch is supplied it is used instead of the default AllEnzymes. """ if not batch: batch = AllEnzymes r = [x for x in batch if (cls >> x) or (not cls != x)] i = r.index(cls) del r[i] r.sort() return r @classmethod def frequency(cls): """Return the theoretically cutting frequency of the enzyme. Frequency of the site, given as 'one cut per x bases' (int). """ return cls.freq class NoCut(AbstractCut): """Implement the methods specific to the enzymes that do not cut. These enzymes are generally enzymes that have been only partially characterised and the way they cut the DNA is unknow or enzymes for which the pattern of cut is to complex to be recorded in Rebase (ncuts values of 0 in emboss_e.###). When using search() with these enzymes the values returned are at the start of the restriction site. Their catalyse() method returns a TypeError. Unknown and NotDefined are also part of the base classes of these enzymes. Internal use only. Not meant to be instantiated. """ @classmethod def cut_once(cls): """Return if the cutting pattern has one cut. True if the enzyme cut the sequence one time on each strand. """ return False @classmethod def cut_twice(cls): """Return if the cutting pattern has two cuts. True if the enzyme cut the sequence twice on each strand. """ return False @classmethod def _modify(cls, location): """Return a generator that moves the cutting position by 1 (PRIVATE). For internal use only. location is an integer corresponding to the location of the match for the enzyme pattern in the sequence. _modify returns the real place where the enzyme will cut. Example:: EcoRI pattern : GAATTC EcoRI will cut after the G. so in the sequence: ______ GAATACACGGAATTCGA | 10 dna.finditer(GAATTC, 6) will return 10 as G is the 10th base EcoRI cut after the G so: EcoRI._modify(10) -> 11. If the enzyme cut twice _modify will returns two integer corresponding to each cutting site. """ yield location @classmethod def _rev_modify(cls, location): """Return a generator that moves the cutting position by 1 (PRIVATE). For internal use only. As _modify for site situated on the antiparallel strand when the enzyme is not palindromic. """ yield location @classmethod def characteristic(cls): """Return a list of the enzyme's characteristics as tuple. the tuple contains the attributes: - fst5 -> first 5' cut ((current strand) or None - fst3 -> first 3' cut (complementary strand) or None - scd5 -> second 5' cut (current strand) or None - scd5 -> second 3' cut (complementary strand) or None - site -> recognition site. """ return None, None, None, None, cls.site class OneCut(AbstractCut): """Implement the methods for enzymes that cut the DNA only once. Correspond to ncuts values of 2 in emboss_e.### Internal use only. Not meant to be instantiated. """ @classmethod def cut_once(cls): """Return if the cutting pattern has one cut. True if the enzyme cut the sequence one time on each strand. """ return True @classmethod def cut_twice(cls): """Return if the cutting pattern has two cuts. True if the enzyme cut the sequence twice on each strand. """ return False @classmethod def _modify(cls, location): """Return a generator that moves the cutting position by 1 (PRIVATE). For internal use only. location is an integer corresponding to the location of the match for the enzyme pattern in the sequence. _modify returns the real place where the enzyme will cut. Example:: EcoRI pattern : GAATTC EcoRI will cut after the G. so in the sequence: ______ GAATACACGGAATTCGA | 10 dna.finditer(GAATTC, 6) will return 10 as G is the 10th base EcoRI cut after the G so: EcoRI._modify(10) -> 11. if the enzyme cut twice _modify will returns two integer corresponding to each cutting site. """ yield location + cls.fst5 @classmethod def _rev_modify(cls, location): """Return a generator that moves the cutting position by 1 (PRIVATE). For internal use only. As _modify for site situated on the antiparallel strand when the enzyme is not palindromic """ yield location - cls.fst3 @classmethod def characteristic(cls): """Return a list of the enzyme's characteristics as tuple. The tuple contains the attributes: - fst5 -> first 5' cut ((current strand) or None - fst3 -> first 3' cut (complementary strand) or None - scd5 -> second 5' cut (current strand) or None - scd5 -> second 3' cut (complementary strand) or None - site -> recognition site. """ return cls.fst5, cls.fst3, None, None, cls.site class TwoCuts(AbstractCut): """Implement the methods for enzymes that cut the DNA twice. Correspond to ncuts values of 4 in emboss_e.### Internal use only. Not meant to be instantiated. """ @classmethod def cut_once(cls): """Return if the cutting pattern has one cut. True if the enzyme cut the sequence one time on each strand. """ return False @classmethod def cut_twice(cls): """Return if the cutting pattern has two cuts. True if the enzyme cut the sequence twice on each strand. """ return True @classmethod def _modify(cls, location): """Return a generator that moves the cutting position by 1 (PRIVATE). For internal use only. location is an integer corresponding to the location of the match for the enzyme pattern in the sequence. _modify returns the real place where the enzyme will cut. example:: EcoRI pattern : GAATTC EcoRI will cut after the G. so in the sequence: ______ GAATACACGGAATTCGA | 10 dna.finditer(GAATTC, 6) will return 10 as G is the 10th base EcoRI cut after the G so: EcoRI._modify(10) -> 11. if the enzyme cut twice _modify will returns two integer corresponding to each cutting site. """ yield location + cls.fst5 yield location + cls.scd5 @classmethod def _rev_modify(cls, location): """Return a generator that moves the cutting position by 1 (PRIVATE). for internal use only. as _modify for site situated on the antiparallel strand when the enzyme is not palindromic """ yield location - cls.fst3 yield location - cls.scd3 @classmethod def characteristic(cls): """Return a list of the enzyme's characteristics as tuple. the tuple contains the attributes: - fst5 -> first 5' cut ((current strand) or None - fst3 -> first 3' cut (complementary strand) or None - scd5 -> second 5' cut (current strand) or None - scd5 -> second 3' cut (complementary strand) or None - site -> recognition site. """ return cls.fst5, cls.fst3, cls.scd5, cls.scd3, cls.site class Meth_Dep(AbstractCut): """Implement the information about methylation. Enzymes of this class possess a site which is methylable. """ @classmethod def is_methylable(cls): """Return if recognition site can be methylated. True if the recognition site is a methylable. """ return True class Meth_Undep(AbstractCut): """Implement information about methylation sensitibility. Enzymes of this class are not sensible to methylation. """ @classmethod def is_methylable(cls): """Return if recognition site can be methylated. True if the recognition site is a methylable. """ return False class Palindromic(AbstractCut): """Implement methods for enzymes with palindromic recognition sites. palindromic means : the recognition site and its reverse complement are identical. Remarks : an enzyme with a site CGNNCG is palindromic even if some of the sites that it will recognise are not. for example here : CGAACG Internal use only. Not meant to be instantiated. """ @classmethod def _search(cls): """Return a list of cutting sites of the enzyme in the sequence (PRIVATE). For internal use only. Implement the search method for palindromic enzymes. """ siteloc = cls.dna.finditer(cls.compsite, cls.size) cls.results = [r for s, g in siteloc for r in cls._modify(s)] if cls.results: cls._drop() return cls.results @classmethod def is_palindromic(cls): """Return if the enzyme has a palindromic recoginition site.""" return True class NonPalindromic(AbstractCut): """Implement methods for enzymes with non-palindromic recognition sites. Palindromic means : the recognition site and its reverse complement are identical. Internal use only. Not meant to be instantiated. """ @classmethod def _search(cls): """Return a list of cutting sites of the enzyme in the sequence (PRIVATE). For internal use only. Implement the search method for non palindromic enzymes. """ iterator = cls.dna.finditer(cls.compsite, cls.size) cls.results = [] modif = cls._modify revmodif = cls._rev_modify s = str(cls) cls.on_minus = [] for start, group in iterator: if group(s): cls.results += list(modif(start)) else: cls.on_minus += list(revmodif(start)) cls.results += cls.on_minus if cls.results: cls.results.sort() cls._drop() return cls.results @classmethod def is_palindromic(cls): """Return if the enzyme has a palindromic recoginition site.""" return False class Unknown(AbstractCut): """Implement methods for enzymes that produce unknown overhangs. These enzymes are also NotDefined and NoCut. Internal use only. Not meant to be instantiated. """ @classmethod def catalyse(cls, dna, linear=True): """List the sequence fragments after cutting dna with enzyme. Return a tuple of dna as will be produced by using RE to restrict the dna. dna must be a Bio.Seq.Seq instance or a Bio.Seq.MutableSeq instance. If linear is False, the sequence is considered to be circular and the output will be modified accordingly. """ raise NotImplementedError("%s restriction is unknown." % cls.__name__) catalyze = catalyse @classmethod def is_blunt(cls): """Return if the enzyme produces blunt ends. True if the enzyme produces blunt end. Related methods: - RE.is_3overhang() - RE.is_5overhang() - RE.is_unknown() """ return False @classmethod def is_5overhang(cls): """Return if the enzymes produces 5' overhanging ends. True if the enzyme produces 5' overhang sticky end. Related methods: - RE.is_3overhang() - RE.is_blunt() - RE.is_unknown() """ return False @classmethod def is_3overhang(cls): """Return if the enzyme produces 3' overhanging ends. True if the enzyme produces 3' overhang sticky end. Related methods: - RE.is_5overhang() - RE.is_blunt() - RE.is_unknown() """ return False @classmethod def overhang(cls): """Return the type of the enzyme's overhang as string. Can be "3' overhang", "5' overhang", "blunt", "unknown". """ return "unknown" @classmethod def compatible_end(cls): """List all enzymes that produce compatible ends for the enzyme.""" return [] @classmethod def _mod1(cls, other): """Test if other enzyme produces compatible ends for enzyme (PRIVATE). For internal use only. Test for the compatibility of restriction ending of RE and other. """ return False class Blunt(AbstractCut): """Implement methods for enzymes that produce blunt ends. The enzyme cuts the + strand and the - strand of the DNA at the same place. Internal use only. Not meant to be instantiated. """ @classmethod def catalyse(cls, dna, linear=True): """List the sequence fragments after cutting dna with enzyme. Return a tuple of dna as will be produced by using RE to restrict the dna. dna must be a Bio.Seq.Seq instance or a Bio.Seq.MutableSeq instance. If linear is False, the sequence is considered to be circular and the output will be modified accordingly. """ r = cls.search(dna, linear) d = cls.dna if not r: return (d[1:],) fragments = [] length = len(r) - 1 if d.is_linear(): # # START of the sequence to FIRST site. # fragments.append(d[1 : r[0]]) if length: # # if more than one site add them. # fragments += [d[r[x] : r[x + 1]] for x in range(length)] # # LAST site to END of the sequence. # fragments.append(d[r[-1] :]) else: # # circular : bridge LAST site to FIRST site. # fragments.append(d[r[-1] :] + d[1 : r[0]]) if not length: # # one site we finish here. # return tuple(fragments) # # add the others. # fragments += [d[r[x] : r[x + 1]] for x in range(length)] return tuple(fragments) catalyze = catalyse @classmethod def is_blunt(cls): """Return if the enzyme produces blunt ends. True if the enzyme produces blunt end. Related methods: - RE.is_3overhang() - RE.is_5overhang() - RE.is_unknown() """ return True @classmethod def is_5overhang(cls): """Return if the enzymes produces 5' overhanging ends. True if the enzyme produces 5' overhang sticky end. Related methods: - RE.is_3overhang() - RE.is_blunt() - RE.is_unknown() """ return False @classmethod def is_3overhang(cls): """Return if the enzyme produces 3' overhanging ends. True if the enzyme produces 3' overhang sticky end. Related methods: - RE.is_5overhang() - RE.is_blunt() - RE.is_unknown() """ return False @classmethod def overhang(cls): """Return the type of the enzyme's overhang as string. Can be "3' overhang", "5' overhang", "blunt", "unknown". """ return "blunt" @classmethod def compatible_end(cls, batch=None): """List all enzymes that produce compatible ends for the enzyme.""" if not batch: batch = AllEnzymes r = sorted(x for x in iter(AllEnzymes) if x.is_blunt()) return r @staticmethod def _mod1(other): """Test if other enzyme produces compatible ends for enzyme (PRIVATE). For internal use only Test for the compatibility of restriction ending of RE and other. """ return issubclass(other, Blunt) class Ov5(AbstractCut): """Implement methods for enzymes that produce 5' overhanging ends. The enzyme cuts the + strand after the - strand of the DNA. Internal use only. Not meant to be instantiated. """ @classmethod def catalyse(cls, dna, linear=True): """List the sequence fragments after cutting dna with enzyme. Return a tuple of dna as will be produced by using RE to restrict the dna. dna must be a Bio.Seq.Seq instance or a Bio.Seq.MutableSeq instance. If linear is False, the sequence is considered to be circular and the output will be modified accordingly. """ r = cls.search(dna, linear) d = cls.dna if not r: return (d[1:],) length = len(r) - 1 fragments = [] if d.is_linear(): # # START of the sequence to FIRST site. # fragments.append(d[1 : r[0]]) if length: # # if more than one site add them. # fragments += [d[r[x] : r[x + 1]] for x in range(length)] # # LAST site to END of the sequence. # fragments.append(d[r[-1] :]) else: # # circular : bridge LAST site to FIRST site. # fragments.append(d[r[-1] :] + d[1 : r[0]]) if not length: # # one site we finish here. # return tuple(fragments) # # add the others. # fragments += [d[r[x] : r[x + 1]] for x in range(length)] return tuple(fragments) catalyze = catalyse @classmethod def is_blunt(cls): """Return if the enzyme produces blunt ends. True if the enzyme produces blunt end. Related methods: - RE.is_3overhang() - RE.is_5overhang() - RE.is_unknown() """ return False @classmethod def is_5overhang(cls): """Return if the enzymes produces 5' overhanging ends. True if the enzyme produces 5' overhang sticky end. Related methods: - RE.is_3overhang() - RE.is_blunt() - RE.is_unknown() """ return True @classmethod def is_3overhang(cls): """Return if the enzyme produces 3' overhanging ends. True if the enzyme produces 3' overhang sticky end. Related methods: - RE.is_5overhang() - RE.is_blunt() - RE.is_unknown() """ return False @classmethod def overhang(cls): """Return the type of the enzyme's overhang as string. Can be "3' overhang", "5' overhang", "blunt", "unknown". """ return "5' overhang" @classmethod def compatible_end(cls, batch=None): """List all enzymes that produce compatible ends for the enzyme.""" if not batch: batch = AllEnzymes r = sorted(x for x in iter(AllEnzymes) if x.is_5overhang() and x % cls) return r @classmethod def _mod1(cls, other): """Test if other enzyme produces compatible ends for enzyme (PRIVATE). For internal use only. Test for the compatibility of restriction ending of RE and other. """ if issubclass(other, Ov5): return cls._mod2(other) else: return False class Ov3(AbstractCut): """Implement methods for enzymes that produce 3' overhanging ends. The enzyme cuts the - strand after the + strand of the DNA. Internal use only. Not meant to be instantiated. """ @classmethod def catalyse(cls, dna, linear=True): """List the sequence fragments after cutting dna with enzyme. Return a tuple of dna as will be produced by using RE to restrict the dna. dna must be a Bio.Seq.Seq instance or a Bio.Seq.MutableSeq instance. If linear is False, the sequence is considered to be circular and the output will be modified accordingly. """ r = cls.search(dna, linear) d = cls.dna if not r: return (d[1:],) fragments = [] length = len(r) - 1 if d.is_linear(): # # START of the sequence to FIRST site. # fragments.append(d[1 : r[0]]) if length: # # if more than one site add them. # fragments += [d[r[x] : r[x + 1]] for x in range(length)] # # LAST site to END of the sequence. # fragments.append(d[r[-1] :]) else: # # circular : bridge LAST site to FIRST site. # fragments.append(d[r[-1] :] + d[1 : r[0]]) if not length: # # one site we finish here. # return tuple(fragments) # # add the others. # fragments += [d[r[x] : r[x + 1]] for x in range(length)] return tuple(fragments) catalyze = catalyse @classmethod def is_blunt(cls): """Return if the enzyme produces blunt ends. True if the enzyme produces blunt end. Related methods: - RE.is_3overhang() - RE.is_5overhang() - RE.is_unknown() """ return False @classmethod def is_5overhang(cls): """Return if the enzymes produces 5' overhanging ends. True if the enzyme produces 5' overhang sticky end. Related methods: - RE.is_3overhang() - RE.is_blunt() - RE.is_unknown() """ return False @classmethod def is_3overhang(cls): """Return if the enzyme produces 3' overhanging ends. True if the enzyme produces 3' overhang sticky end. Related methods: - RE.is_5overhang() - RE.is_blunt() - RE.is_unknown() """ return True @classmethod def overhang(cls): """Return the type of the enzyme's overhang as string. Can be "3' overhang", "5' overhang", "blunt", "unknown". """ return "3' overhang" @classmethod def compatible_end(cls, batch=None): """List all enzymes that produce compatible ends for the enzyme.""" if not batch: batch = AllEnzymes r = sorted(x for x in iter(AllEnzymes) if x.is_3overhang() and x % cls) return r @classmethod def _mod1(cls, other): """Test if other enzyme produces compatible ends for enzyme (PRIVATE). For internal use only. Test for the compatibility of restriction ending of RE and other. """ # # called by RE._mod1(other) when the one of the enzyme is ambiguous # if issubclass(other, Ov3): return cls._mod2(other) else: return False class Defined(AbstractCut): """Implement methods for enzymes with defined recognition site and cut. Typical example : EcoRI -> G^AATT_C The overhang will always be AATT Notes: Blunt enzymes are always defined. Even if their site is GGATCCNNN^_N Their overhang is always the same : blunt! Internal use only. Not meant to be instantiated. """ @classmethod def _drop(cls): """Remove cuts that are outsite of the sequence (PRIVATE). For internal use only. Drop the site that are situated outside the sequence in linear sequence. Modify the index for site in circular sequences. """ # # remove or modify the results that are outside the sequence. # This is necessary since after finding the site we add the distance # from the site to the cut with the _modify and _rev_modify methods. # For linear we will remove these sites altogether. # For circular sequence, we modify the result rather than _drop it # since the site is in the sequence. # length = len(cls.dna) drop = itertools.dropwhile take = itertools.takewhile if cls.dna.is_linear(): cls.results = list(drop(lambda x: x <= 1, cls.results)) cls.results = list(take(lambda x: x <= length, cls.results)) else: for index, location in enumerate(cls.results): if location < 1: cls.results[index] += length else: break for index, location in enumerate(cls.results[::-1]): if location > length: cls.results[-(index + 1)] -= length else: break return @classmethod def is_defined(cls): """Return if recognition sequence and cut are defined. True if the sequence recognised and cut is constant, i.e. the recognition site is not degenerated AND the enzyme cut inside the site. Related methods: - RE.is_ambiguous() - RE.is_unknown() """ return True @classmethod def is_ambiguous(cls): """Return if recognition sequence and cut may be ambiguous. True if the sequence recognised and cut is ambiguous, i.e. the recognition site is degenerated AND/OR the enzyme cut outside the site. Related methods: - RE.is_defined() - RE.is_unknown() """ return False @classmethod def is_unknown(cls): """Return if recognition sequence is unknown. True if the sequence is unknown, i.e. the recognition site has not been characterised yet. Related methods: - RE.is_defined() - RE.is_ambiguous() """ return False @classmethod def elucidate(cls): """Return a string representing the recognition site and cuttings. Return a representation of the site with the cut on the (+) strand represented as '^' and the cut on the (-) strand as '_'. ie: >>> from Bio.Restriction import EcoRI, KpnI, EcoRV, SnaI >>> EcoRI.elucidate() # 5' overhang 'G^AATT_C' >>> KpnI.elucidate() # 3' overhang 'G_GTAC^C' >>> EcoRV.elucidate() # blunt 'GAT^_ATC' >>> SnaI.elucidate() # NotDefined, cut profile unknown. '? GTATAC ?' >>> """ f5 = cls.fst5 f3 = cls.fst3 site = cls.site if cls.cut_twice(): re = "cut twice, not yet implemented sorry." elif cls.is_5overhang(): if f5 == f3 == 0: re = "N^" + cls.site + "_N" elif f3 == 0: re = site[:f5] + "^" + site[f5:] + "_N" else: re = site[:f5] + "^" + site[f5:f3] + "_" + site[f3:] elif cls.is_blunt(): re = site[:f5] + "^_" + site[f5:] else: if f5 == f3 == 0: re = "N_" + site + "^N" else: re = site[:f3] + "_" + site[f3:f5] + "^" + site[f5:] return re @classmethod def _mod2(cls, other): """Test if other enzyme produces compatible ends for enzyme (PRIVATE). For internal use only. Test for the compatibility of restriction ending of RE and other. """ # # called by RE._mod1(other) when the one of the enzyme is ambiguous # if other.ovhgseq == cls.ovhgseq: return True elif issubclass(other, Ambiguous): return other._mod2(cls) else: return False class Ambiguous(AbstractCut): """Implement methods for enzymes that produce variable overhangs. Typical example : BstXI -> CCAN_NNNN^NTGG The overhang can be any sequence of 4 bases. Notes: Blunt enzymes are always defined. Even if their site is GGATCCNNN^_N Their overhang is always the same : blunt! Internal use only. Not meant to be instantiated. """ @classmethod def _drop(cls): """Remove cuts that are outsite of the sequence (PRIVATE). For internal use only. Drop the site that are situated outside the sequence in linear sequence. Modify the index for site in circular sequences. """ length = len(cls.dna) drop = itertools.dropwhile take = itertools.takewhile if cls.dna.is_linear(): cls.results = list(drop(lambda x: x <= 1, cls.results)) cls.results = list(take(lambda x: x <= length, cls.results)) else: for index, location in enumerate(cls.results): if location < 1: cls.results[index] += length else: break for index, location in enumerate(cls.results[::-1]): if location > length: cls.results[-(index + 1)] -= length else: break return @classmethod def is_defined(cls): """Return if recognition sequence and cut are defined. True if the sequence recognised and cut is constant, i.e. the recognition site is not degenerated AND the enzyme cut inside the site. Related methods: - RE.is_ambiguous() - RE.is_unknown() """ return False @classmethod def is_ambiguous(cls): """Return if recognition sequence and cut may be ambiguous. True if the sequence recognised and cut is ambiguous, i.e. the recognition site is degenerated AND/OR the enzyme cut outside the site. Related methods: - RE.is_defined() - RE.is_unknown() """ return True @classmethod def is_unknown(cls): """Return if recognition sequence is unknown. True if the sequence is unknown, i.e. the recognition site has not been characterised yet. Related methods: - RE.is_defined() - RE.is_ambiguous() """ return False @classmethod def _mod2(cls, other): """Test if other enzyme produces compatible ends for enzyme (PRIVATE). For internal use only. Test for the compatibility of restriction ending of RE and other. """ # # called by RE._mod1(other) when the one of the enzyme is ambiguous # if len(cls.ovhgseq) != len(other.ovhgseq): return False else: se = cls.ovhgseq for base in se: if base in "ATCG": pass if base in "N": se = ".".join(se.split("N")) if base in "RYWMSKHDBV": expand = "[" + matching[base] + "]" se = expand.join(se.split(base)) if re.match(se, other.ovhgseq): return True else: return False @classmethod def elucidate(cls): """Return a string representing the recognition site and cuttings. Return a representation of the site with the cut on the (+) strand represented as '^' and the cut on the (-) strand as '_'. ie: >>> from Bio.Restriction import EcoRI, KpnI, EcoRV, SnaI >>> EcoRI.elucidate() # 5' overhang 'G^AATT_C' >>> KpnI.elucidate() # 3' overhang 'G_GTAC^C' >>> EcoRV.elucidate() # blunt 'GAT^_ATC' >>> SnaI.elucidate() # NotDefined, cut profile unknown. '? GTATAC ?' >>> """ f5 = cls.fst5 f3 = cls.fst3 length = len(cls) site = cls.site if cls.cut_twice(): re = "cut twice, not yet implemented sorry." elif cls.is_5overhang(): if f3 == f5 == 0: re = "N^" + site + "_N" elif 0 <= f5 <= length and 0 <= f3 + length <= length: re = site[:f5] + "^" + site[f5:f3] + "_" + site[f3:] elif 0 <= f5 <= length: re = site[:f5] + "^" + site[f5:] + f3 * "N" + "_N" elif 0 <= f3 + length <= length: re = "N^" + abs(f5) * "N" + site[:f3] + "_" + site[f3:] elif f3 + length < 0: re = "N^" * abs(f5) * "N" + "_" + abs(length + f3) * "N" + site elif f5 > length: re = site + (f5 - length) * "N" + "^" + (length + f3 - f5) * "N" + "_N" else: re = "N^" + abs(f5) * "N" + site + f3 * "N" + "_N" elif cls.is_blunt(): if f5 < 0: re = "N^_" + abs(f5) * "N" + site elif f5 > length: re = site + (f5 - length) * "N" + "^_N" else: raise ValueError("%s.easyrepr() : error f5=%i" % (cls.name, f5)) else: if f3 == 0: if f5 == 0: re = "N_" + site + "^N" else: re = site + "_" + (f5 - length) * "N" + "^N" elif 0 < f3 + length <= length and 0 <= f5 <= length: re = site[:f3] + "_" + site[f3:f5] + "^" + site[f5:] elif 0 < f3 + length <= length: re = site[:f3] + "_" + site[f3:] + (f5 - length) * "N" + "^N" elif 0 <= f5 <= length: re = "N_" + "N" * (f3 + length) + site[:f5] + "^" + site[f5:] elif f3 > 0: re = site + f3 * "N" + "_" + (f5 - f3 - length) * "N" + "^N" elif f5 < 0: re = "N_" + abs(f3 - f5 + length) * "N" + "^" + abs(f5) * "N" + site else: re = "N_" + abs(f3 + length) * "N" + site + (f5 - length) * "N" + "^N" return re class NotDefined(AbstractCut): """Implement methods for enzymes with non-characterized overhangs. Correspond to NoCut and Unknown. Internal use only. Not meant to be instantiated. """ @classmethod def _drop(cls): """Remove cuts that are outsite of the sequence (PRIVATE). For internal use only. Drop the site that are situated outside the sequence in linear sequence. Modify the index for site in circular sequences. """ if cls.dna.is_linear(): return else: length = len(cls.dna) for index, location in enumerate(cls.results): if location < 1: cls.results[index] += length else: break for index, location in enumerate(cls.results[:-1]): if location > length: cls.results[-(index + 1)] -= length else: break return @classmethod def is_defined(cls): """Return if recognition sequence and cut are defined. True if the sequence recognised and cut is constant, i.e. the recognition site is not degenerated AND the enzyme cut inside the site. Related methods: - RE.is_ambiguous() - RE.is_unknown() """ return False @classmethod def is_ambiguous(cls): """Return if recognition sequence and cut may be ambiguous. True if the sequence recognised and cut is ambiguous, i.e. the recognition site is degenerated AND/OR the enzyme cut outside the site. Related methods: - RE.is_defined() - RE.is_unknown() """ return False @classmethod def is_unknown(cls): """Return if recognition sequence is unknown. True if the sequence is unknown, i.e. the recognition site has not been characterised yet. Related methods: - RE.is_defined() - RE.is_ambiguous() """ return True @classmethod def _mod2(cls, other): """Test if other enzyme produces compatible ends for enzyme (PRIVATE). For internal use only. Test for the compatibility of restriction ending of RE and other. """ # # Normally we should not arrive here. But well better safe than # sorry. # the overhang is not defined we are compatible with nobody. # could raise an Error may be rather than return quietly. # # return False raise ValueError( "%s.mod2(%s), %s : NotDefined. pas glop pas glop!" % (str(cls), str(other), str(cls)) ) @classmethod def elucidate(cls): """Return a string representing the recognition site and cuttings. Return a representation of the site with the cut on the (+) strand represented as '^' and the cut on the (-) strand as '_'. ie: >>> from Bio.Restriction import EcoRI, KpnI, EcoRV, SnaI >>> EcoRI.elucidate() # 5' overhang 'G^AATT_C' >>> KpnI.elucidate() # 3' overhang 'G_GTAC^C' >>> EcoRV.elucidate() # blunt 'GAT^_ATC' >>> SnaI.elucidate() # NotDefined, cut profile unknown. '? GTATAC ?' >>> """ return "? %s ?" % cls.site class Commercially_available(AbstractCut): """Implement methods for enzymes which are commercially available. Internal use only. Not meant to be instantiated. """ # # Recent addition to Rebase make this naming convention uncertain. # May be better to says enzymes which have a supplier. # @classmethod def suppliers(cls): """Print a list of suppliers of the enzyme.""" for s in cls.suppl: print(suppliers_dict[s][0] + ",") return @classmethod def supplier_list(cls): """Return a list of suppliers of the enzyme.""" return [v[0] for k, v in suppliers_dict.items() if k in cls.suppl] @classmethod def buffers(cls, supplier): """Return the recommended buffer of the supplier for this enzyme. Not implemented yet. """ return @classmethod def is_comm(cls): """Return if enzyme is commercially available. True if RE has suppliers. """ return True class Not_available(AbstractCut): """Implement methods for enzymes which are not commercially available. Internal use only. Not meant to be instantiated. """ @staticmethod def suppliers(): """Print a list of suppliers of the enzyme.""" return None @classmethod def supplier_list(cls): """Return a list of suppliers of the enzyme.""" return [] @classmethod def buffers(cls, supplier): """Return the recommended buffer of the supplier for this enzyme. Not implemented yet. """ raise TypeError("Enzyme not commercially available.") @classmethod def is_comm(cls): """Return if enzyme is commercially available. True if RE has suppliers. """ return False ############################################################################### # # # Restriction Batch # # # ############################################################################### class RestrictionBatch(set): """Class for operations on more than one enzyme.""" def __init__(self, first=(), suppliers=()): """Initialize empty RB or pre-fill with enzymes (from supplier).""" first = [self.format(x) for x in first] first += [eval(x) for n in suppliers for x in suppliers_dict[n][1]] set.__init__(self, first) self.mapping = dict.fromkeys(self) self.already_mapped = None self.suppliers = [x for x in suppliers if x in suppliers_dict] def __str__(self): """Return a readable representation of the ``RestrictionBatch``.""" if len(self) < 5: return "+".join(self.elements()) else: return "...".join( ("+".join(self.elements()[:2]), "+".join(self.elements()[-2:])) ) def __repr__(self): """Represent ``RestrictionBatch`` class as a string for debugging.""" return "RestrictionBatch(%s)" % self.elements() def __contains__(self, other): """Implement ``in`` for ``RestrictionBatch``.""" try: other = self.format(other) except ValueError: # other is not a restriction enzyme return False return set.__contains__(self, other) def __div__(self, other): """Override '/' operator to use as search method.""" return self.search(other) def __rdiv__(self, other): """Override division with reversed operands to use as search method.""" return self.search(other) def __truediv__(self, other): """Override Python 3 division operator to use as search method. Like __div__. """ return self.search(other) def __rtruediv__(self, other): """As __truediv___, with reversed operands. Like __rdiv__. """ return self.search(other) def get(self, enzyme, add=False): """Check if enzyme is in batch and return it. If add is True and enzyme is not in batch add enzyme to batch. If add is False (which is the default) only return enzyme. If enzyme is not a RestrictionType or can not be evaluated to a RestrictionType, raise a ValueError. """ e = self.format(enzyme) if e in self: return e elif add: self.add(e) return e else: raise ValueError("enzyme %s is not in RestrictionBatch" % e.__name__) def lambdasplit(self, func): """Filter enzymes in batch with supplied function. The new batch will contain only the enzymes for which func return True. """ d = list(filter(func, self)) new = RestrictionBatch() new._data = dict(zip(d, [True] * len(d))) return new def add_supplier(self, letter): """Add all enzymes from a given supplier to batch. letter represents the suppliers as defined in the dictionary RestrictionDictionary.suppliers Returns None. Raise a KeyError if letter is not a supplier code. """ supplier = suppliers_dict[letter] self.suppliers.append(letter) for x in supplier[1]: self.add_nocheck(eval(x)) return def current_suppliers(self): """List the current suppliers for the restriction batch. Return a sorted list of the suppliers which have been used to create the batch. """ suppl_list = sorted(suppliers_dict[x][0] for x in self.suppliers) return suppl_list def __iadd__(self, other): """Override '+=' for use with sets. b += other -> add other to b, check the type of other. """ self.add(other) return self def __add__(self, other): """Overide '+' for use with sets. b + other -> new RestrictionBatch. """ new = self.__class__(self) new.add(other) return new def remove(self, other): """Remove enzyme from restriction batch. Safe set.remove method. Verify that other is a RestrictionType or can be evaluated to a RestrictionType. Raise a ValueError if other can not be evaluated to a RestrictionType. Raise a KeyError if other is not in B. """ return set.remove(self, self.format(other)) def add(self, other): """Add a restriction enzyme to the restriction batch. Safe set.add method. Verify that other is a RestrictionType or can be evaluated to a RestrictionType. Raise a ValueError if other can not be evaluated to a RestrictionType. """ return set.add(self, self.format(other)) def add_nocheck(self, other): """Add restriction enzyme to batch without checking its type.""" return set.add(self, other) def format(self, y): """Evaluate enzyme (name) and return it (as RestrictionType). If y is a RestrictionType return y. If y can be evaluated to a RestrictionType return eval(y). Raise a ValueError in all other case. """ try: if isinstance(y, RestrictionType): return y elif isinstance(eval(str(y)), RestrictionType): return eval(y) except (NameError, SyntaxError): pass raise ValueError("%s is not a RestrictionType" % y.__class__) def is_restriction(self, y): """Return if enzyme (name) is a known enzyme. True if y or eval(y) is a RestrictionType. """ return isinstance(y, RestrictionType) or isinstance( eval(str(y)), RestrictionType ) def split(self, *classes, **bool): """Extract enzymes of a certain class and put in new RestrictionBatch. It works but it is slow, so it has really an interest when splitting over multiple conditions. """ def splittest(element): for klass in classes: b = bool.get(klass.__name__, True) if issubclass(element, klass): if b: continue else: return False elif b: return False else: continue return True d = list(filter(splittest, self)) new = RestrictionBatch() new._data = dict(zip(d, [True] * len(d))) return new def elements(self): """List the enzymes of the RestrictionBatch as list of strings. Give all the names of the enzymes in B sorted alphabetically. """ return sorted(str(e) for e in self) def as_string(self): """List the names of the enzymes of the RestrictionBatch. Return a list of the name of the elements of the batch. """ return [str(e) for e in self] @classmethod def suppl_codes(cls): """Return a dicionary with supplier codes. Letter code for the suppliers. """ supply = {k: v[0] for k, v in suppliers_dict.items()} return supply @classmethod def show_codes(cls): """Print a list of supplier codes.""" supply = [" = ".join(i) for i in cls.suppl_codes().items()] print("\n".join(supply)) return def search(self, dna, linear=True): """Return a dic of cutting sites in the seq for the batch enzymes.""" # # here we replace the search method of the individual enzymes # with one unique testing method. # if not hasattr(self, "already_mapped"): # TODO - Why does this happen! # Try the "doctest" at the start of PrintFormat.py self.already_mapped = None if isinstance(dna, DNA): # For the searching, we just care about the sequence as a string, # if that is the same we can use the cached search results. # At the time of writing, Seq == method isn't implemented, # and therefore does object identity which is stricter. if (str(dna), linear) == self.already_mapped: return self.mapping else: self.already_mapped = str(dna), linear fseq = FormattedSeq(dna, linear) self.mapping = {x: x.search(fseq) for x in self} return self.mapping elif isinstance(dna, FormattedSeq): if (str(dna), dna.linear) == self.already_mapped: return self.mapping else: self.already_mapped = str(dna), dna.linear self.mapping = {x: x.search(dna) for x in self} return self.mapping raise TypeError( "Expected Seq or MutableSeq instance, got %s instead" % type(dna) ) ############################################################################### # # # Restriction Analysis # # # ############################################################################### _empty_DNA = DNA("") _restrictionbatch = RestrictionBatch() class Analysis(RestrictionBatch, PrintFormat): """Provide methods for enhanced analysis and pretty printing.""" def __init__( self, restrictionbatch=_restrictionbatch, sequence=_empty_DNA, linear=True ): """Initialize an Analysis with RestrictionBatch and sequence. For most of the methods of this class if a dictionary is given it will be used as the base to calculate the results. If no dictionary is given a new analysis using the RestrictionBatch which has been given when the Analysis class has been instantiated, will be carried out and used. """ RestrictionBatch.__init__(self, restrictionbatch) self.rb = restrictionbatch self.sequence = sequence self.linear = linear if self.sequence: self.search(self.sequence, self.linear) def __repr__(self): """Represent ``Analysis`` class as a string.""" return "Analysis(%s,%s,%s)" % (repr(self.rb), repr(self.sequence), self.linear) def _sub_set(self, wanted): """Filter result for keys which are in wanted (PRIVATE). Internal use only. Returns a dict. Screen the results through wanted set. Keep only the results for which the enzymes is in wanted set. """ # It seems that this method is not used in the whole class! return {k: v for k, v in self.mapping.items() if k in wanted} def _boundaries(self, start, end): """Set boundaries to correct values (PRIVATE). Format the boundaries for use with the methods that limit the search to only part of the sequence given to analyse. """ if not isinstance(start, int): raise TypeError("expected int, got %s instead" % type(start)) if not isinstance(end, int): raise TypeError("expected int, got %s instead" % type(end)) if start < 1: # Looks like this tries to do python list like indexing start += len(self.sequence) if end < 1: end += len(self.sequence) if start < end: pass else: start, end = end, start if start < end: return start, end, self._test_normal def _test_normal(self, start, end, site): """Test if site is between start and end (PRIVATE). Internal use only """ return start <= site < end def _test_reverse(self, start, end, site): """Test if site is between end and start, for circular sequences (PRIVATE). Internal use only. """ return start <= site <= len(self.sequence) or 1 <= site < end def format_output(self, dct=None, title="", s1=""): """Collect data and pass to PrintFormat. If dct is not given the full dictionary is used. """ if not dct: dct = self.mapping return PrintFormat.format_output(self, dct, title, s1) def print_that(self, dct=None, title="", s1=""): """Print the output of the analysis. If dct is not given the full dictionary is used. s1: Title for non-cutting enzymes This method prints the output of A.format_output() and it is here for backwards compatibility. """ print(self.format_output(dct, title, s1)) def change(self, **what): """Change parameters of print output. It is possible to change the width of the shell by setting self.ConsoleWidth to what you want. self.NameWidth refer to the maximal length of the enzyme name. Changing one of these parameters here might not give the results you expect. In which case, you can settle back to a 80 columns shell or try to change self.Cmodulo and self.PrefWidth in PrintFormat until you get it right. """ for k, v in what.items(): if k in ("NameWidth", "ConsoleWidth"): setattr(self, k, v) self.Cmodulo = self.ConsoleWidth % self.NameWidth self.PrefWidth = self.ConsoleWidth - self.Cmodulo elif k == "sequence": setattr(self, "sequence", v) self.search(self.sequence, self.linear) elif k == "rb": self = Analysis.__init__(self, v, self.sequence, self.linear) elif k == "linear": setattr(self, "linear", v) self.search(self.sequence, v) elif k in ("Indent", "Maxsize"): setattr(self, k, v) elif k in ("Cmodulo", "PrefWidth"): raise AttributeError( "To change %s, change NameWidth and/or ConsoleWidth" % k ) else: raise AttributeError("Analysis has no attribute %s" % k) return def full(self, linear=True): """Perform analysis with all enzymes of batch and return all results. Full Restriction Map of the sequence, as a dictionary. """ return self.mapping def blunt(self, dct=None): """Return only cuts that have blunt ends.""" if not dct: dct = self.mapping return {k: v for k, v in dct.items() if k.is_blunt()} def overhang5(self, dct=None): """Return only cuts that have 5' overhangs.""" if not dct: dct = self.mapping return {k: v for k, v in dct.items() if k.is_5overhang()} def overhang3(self, dct=None): """Return only cuts that have 3' overhangs.""" if not dct: dct = self.mapping return {k: v for k, v in dct.items() if k.is_3overhang()} def defined(self, dct=None): """Return only results from enzymes that produce defined overhangs.""" if not dct: dct = self.mapping return {k: v for k, v in dct.items() if k.is_defined()} def with_sites(self, dct=None): """Return only results from enzyme with at least one cut.""" if not dct: dct = self.mapping return {k: v for k, v in dct.items() if v} def without_site(self, dct=None): """Return only results from enzymes that don't cut the sequence.""" if not dct: dct = self.mapping return {k: v for k, v in dct.items() if not v} def with_N_sites(self, N, dct=None): """Return only results from enzymes that cut the sequence N times.""" if not dct: dct = self.mapping return {k: v for k, v in dct.items() if len(v) == N} def with_number_list(self, list, dct=None): """Return only results from enzymes that cut (x,y,z,...) times.""" if not dct: dct = self.mapping return {k: v for k, v in dct.items() if len(v) in list} def with_name(self, names, dct=None): """Return only results from enzymes which names are listed.""" for i, enzyme in enumerate(names): if enzyme not in AllEnzymes: warnings.warn("no data for the enzyme: %s" % enzyme, BiopythonWarning) del names[i] if not dct: return RestrictionBatch(names).search(self.sequence, self.linear) return {n: dct[n] for n in names if n in dct} def with_site_size(self, site_size, dct=None): """Return only results form enzymes with a given site size.""" sites = [name for name in self if name.size == site_size] if not dct: return RestrictionBatch(sites).search(self.sequence) return {k: v for k, v in dct.items() if k in site_size} def only_between(self, start, end, dct=None): """Return only results from enzymes that only cut within start, end.""" start, end, test = self._boundaries(start, end) if not dct: dct = self.mapping d = dict(dct) for key, sites in dct.items(): if not sites: del d[key] continue for site in sites: if test(start, end, site): continue else: del d[key] break return d def between(self, start, end, dct=None): """Return only results from enzymes that cut at least within borders. Enzymes that cut the sequence at least in between start and end. They may cut outside as well. """ start, end, test = self._boundaries(start, end) d = {} if not dct: dct = self.mapping for key, sites in dct.items(): for site in sites: if test(start, end, site): d[key] = sites break continue return d def show_only_between(self, start, end, dct=None): """Return only results from within start, end. Enzymes must cut inside start/end and may also cut outside. However, only the cutting positions within start/end will be returned. """ d = [] if start <= end: d = [ (k, [vv for vv in v if start <= vv <= end]) for k, v in self.between(start, end, dct).items() ] else: d = [ (k, [vv for vv in v if start <= vv or vv <= end]) for k, v in self.between(start, end, dct).items() ] return dict(d) def only_outside(self, start, end, dct=None): """Return only results from enzymes that only cut outside start, end. Enzymes that cut the sequence outside of the region in between start and end but do not cut inside. """ start, end, test = self._boundaries(start, end) if not dct: dct = self.mapping d = dict(dct) for key, sites in dct.items(): if not sites: del d[key] continue for site in sites: if test(start, end, site): del d[key] break else: continue return d def outside(self, start, end, dct=None): """Return only results from enzymes that at least cut outside borders. Enzymes that cut outside the region in between start and end. They may cut inside as well. """ start, end, test = self._boundaries(start, end) if not dct: dct = self.mapping d = {} for key, sites in dct.items(): for site in sites: if test(start, end, site): continue else: d[key] = sites break return d def do_not_cut(self, start, end, dct=None): """Return only results from enzymes that don't cut between borders.""" if not dct: dct = self.mapping d = self.without_site() d.update(self.only_outside(start, end, dct)) return d # # The restriction enzyme classes are created dynamically when the module is # imported. Here is the magic which allow the creation of the # restriction-enzyme classes. # # The reason for the two dictionaries in Restriction_Dictionary # one for the types (which will be called pseudo-type as they really # correspond to the values that instances of RestrictionType can take) # and one for the enzymes is efficiency as the bases are evaluated # once per pseudo-type. # # However Restriction is still a very inefficient module at import. But # remember that around 660 classes (which is more or less the size of Rebase) # have to be created dynamically. However, this processing take place only # once. # This inefficiency is however largely compensated by the use of metaclass # which provide a very efficient layout for the class themselves mostly # alleviating the need of if/else loops in the class methods. # # It is essential to run Restriction with doc string optimisation (-OO # switch) as the doc string of 660 classes take a lot of processing. # CommOnly = RestrictionBatch() # commercial enzymes NonComm = RestrictionBatch() # not available commercially for TYPE, (bases, enzymes) in typedict.items(): # # The keys are the pseudo-types TYPE (stored as type1, type2...) # The names are not important and are only present to differentiate # the keys in the dict. All the pseudo-types are in fact RestrictionType. # These names will not be used after and the pseudo-types are not # kept in the locals() dictionary. It is therefore impossible to # import them. # Now, if you have look at the dictionary, you will see that not all the # types are present as those without corresponding enzymes have been # removed by Dictionary_Builder(). # # The values are tuples which contain # as first element a tuple of bases (as string) and # as second element the names of the enzymes. # # First eval the bases. # bases = tuple(eval(x) for x in bases) # # now create the particular value of RestrictionType for the classes # in enzymes. # T = type.__new__(RestrictionType, "RestrictionType", bases, {}) for k in enzymes: # # Now, we go through all the enzymes and assign them their type. # enzymedict[k] contains the values of the attributes for this # particular class (self.site, self.ovhg,....). # newenz = T(k, bases, enzymedict[k]) # # we add the enzymes to the corresponding batch. # # No need to verify the enzyme is a RestrictionType -> add_nocheck # if newenz.is_comm(): CommOnly.add_nocheck(newenz) else: NonComm.add_nocheck(newenz) # # AllEnzymes is a RestrictionBatch with all the enzymes from Rebase. # AllEnzymes = RestrictionBatch(CommOnly) AllEnzymes.update(NonComm) # # Now, place the enzymes in locals so they can be imported. # names = [str(x) for x in AllEnzymes] locals().update(dict(zip(names, AllEnzymes))) __all__ = ( "FormattedSeq", "Analysis", "RestrictionBatch", "AllEnzymes", "CommOnly", "NonComm", ) + tuple(names) del k, enzymes, TYPE, bases, names
31.721729
87
0.559909
795731e8b34c63fd3198fba82e6ae88c169d68e0
6,127
py
Python
work_dirs/deeplabv3_r50-d8_512x512_4x4_80k_coco_stuff10k/deeplabv3_r50-d8_512x512_4x4_80k_coco_stuff10k.py
Junjun2016/COCO-Stuff_benchmark
d303d4606798b746bacc6a7f6df0274e6ce2fb21
[ "Apache-2.0" ]
3
2021-08-31T05:49:13.000Z
2021-12-05T13:03:44.000Z
work_dirs/deeplabv3_r50-d8_512x512_4x4_80k_coco_stuff10k/deeplabv3_r50-d8_512x512_4x4_80k_coco_stuff10k.py
Junjun2016/COCO-Stuff_benchmark
d303d4606798b746bacc6a7f6df0274e6ce2fb21
[ "Apache-2.0" ]
null
null
null
work_dirs/deeplabv3_r50-d8_512x512_4x4_80k_coco_stuff10k/deeplabv3_r50-d8_512x512_4x4_80k_coco_stuff10k.py
Junjun2016/COCO-Stuff_benchmark
d303d4606798b746bacc6a7f6df0274e6ce2fb21
[ "Apache-2.0" ]
null
null
null
norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='open-mmlab://resnet50_v1c', backbone=dict( type='ResNetV1c', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), dilations=(1, 1, 2, 4), strides=(1, 2, 1, 1), norm_cfg=dict(type='SyncBN', requires_grad=True), norm_eval=False, style='pytorch', contract_dilation=True), decode_head=dict( type='ASPPHead', in_channels=2048, in_index=3, channels=512, dilations=(1, 12, 24, 36), dropout_ratio=0.1, num_classes=171, norm_cfg=dict(type='SyncBN', requires_grad=True), align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=dict( type='FCNHead', in_channels=1024, in_index=2, channels=256, num_convs=1, concat_input=False, dropout_ratio=0.1, num_classes=171, norm_cfg=dict(type='SyncBN', requires_grad=True), align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=0.4)), train_cfg=dict(), test_cfg=dict(mode='whole')) dataset_type = 'COCOStuffDataset' data_root = 'data/coco_stuff10k' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) crop_size = (512, 512) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', reduce_zero_label=True), dict(type='Resize', img_scale=(2048, 512), ratio_range=(0.5, 2.0)), dict(type='RandomCrop', crop_size=(512, 512), cat_max_ratio=0.75), dict(type='RandomFlip', prob=0.5), dict(type='PhotoMetricDistortion'), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size=(512, 512), pad_val=0, seg_pad_val=255), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_semantic_seg']) ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(2048, 512), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ] data = dict( samples_per_gpu=4, workers_per_gpu=4, train=dict( type='COCOStuffDataset', data_root='data/coco_stuff10k', reduce_zero_label=True, img_dir='images/train2014', ann_dir='annotations/train2014', pipeline=[ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', reduce_zero_label=True), dict(type='Resize', img_scale=(2048, 512), ratio_range=(0.5, 2.0)), dict(type='RandomCrop', crop_size=(512, 512), cat_max_ratio=0.75), dict(type='RandomFlip', prob=0.5), dict(type='PhotoMetricDistortion'), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size=(512, 512), pad_val=0, seg_pad_val=255), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_semantic_seg']) ]), val=dict( type='COCOStuffDataset', data_root='data/coco_stuff10k', reduce_zero_label=True, img_dir='images/test2014', ann_dir='annotations/test2014', pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(2048, 512), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ]), test=dict( type='COCOStuffDataset', data_root='data/coco_stuff10k', reduce_zero_label=True, img_dir='images/test2014', ann_dir='annotations/test2014', pipeline=[ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(2048, 512), flip=False, transforms=[ dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict( type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']) ]) ])) log_config = dict( interval=50, hooks=[dict(type='TextLoggerHook', by_epoch=False)]) dist_params = dict(backend='nccl') log_level = 'INFO' load_from = None resume_from = None workflow = [('train', 1)] cudnn_benchmark = True optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0005) optimizer_config = dict() lr_config = dict(policy='poly', power=0.9, min_lr=0.0001, by_epoch=False) runner = dict(type='IterBasedRunner', max_iters=80000) checkpoint_config = dict(by_epoch=False, interval=8000) evaluation = dict(interval=8000, metric='mIoU', efficient_test=True) work_dir = './work_dirs/deeplabv3_r50-d8_512x512_4x4_80k_coco_stuff10k' gpu_ids = range(0, 1)
35.830409
79
0.551167
7957323299a587c9d991359973b60295d8de3d17
40,263
py
Python
tests/file_storage/tests.py
cdunn6754/django
1e87c9fe71703fab23039aa63fafe4f6aac98bbc
[ "PSF-2.0", "BSD-3-Clause" ]
1
2020-09-16T05:38:54.000Z
2020-09-16T05:38:54.000Z
tests/file_storage/tests.py
cdunn6754/django
1e87c9fe71703fab23039aa63fafe4f6aac98bbc
[ "PSF-2.0", "BSD-3-Clause" ]
null
null
null
tests/file_storage/tests.py
cdunn6754/django
1e87c9fe71703fab23039aa63fafe4f6aac98bbc
[ "PSF-2.0", "BSD-3-Clause" ]
1
2019-10-29T22:04:21.000Z
2019-10-29T22:04:21.000Z
import os import shutil import sys import tempfile import threading import time import unittest from datetime import datetime, timedelta from io import StringIO from urllib.request import urlopen from django.core.cache import cache from django.core.exceptions import SuspiciousFileOperation from django.core.files.base import ContentFile, File from django.core.files.storage import FileSystemStorage, get_storage_class from django.core.files.uploadedfile import ( InMemoryUploadedFile, SimpleUploadedFile, TemporaryUploadedFile, ) from django.db.models.fields.files import FileDescriptor from django.test import ( LiveServerTestCase, SimpleTestCase, TestCase, override_settings, ) from django.test.utils import requires_tz_support from django.urls import NoReverseMatch, reverse_lazy from django.utils import timezone from .models import Storage, temp_storage, temp_storage_location FILE_SUFFIX_REGEX = '[A-Za-z0-9]{7}' class GetStorageClassTests(SimpleTestCase): def test_get_filesystem_storage(self): """ get_storage_class returns the class for a storage backend name/path. """ self.assertEqual( get_storage_class('django.core.files.storage.FileSystemStorage'), FileSystemStorage) def test_get_invalid_storage_module(self): """ get_storage_class raises an error if the requested import don't exist. """ with self.assertRaisesMessage(ImportError, "No module named 'storage'"): get_storage_class('storage.NonexistentStorage') def test_get_nonexistent_storage_class(self): """ get_storage_class raises an error if the requested class don't exist. """ with self.assertRaises(ImportError): get_storage_class('django.core.files.storage.NonexistentStorage') def test_get_nonexistent_storage_module(self): """ get_storage_class raises an error if the requested module don't exist. """ with self.assertRaisesMessage(ImportError, "No module named 'django.core.files.nonexistent_storage'"): get_storage_class('django.core.files.nonexistent_storage.NonexistentStorage') class FileSystemStorageTests(unittest.TestCase): def test_deconstruction(self): path, args, kwargs = temp_storage.deconstruct() self.assertEqual(path, "django.core.files.storage.FileSystemStorage") self.assertEqual(args, ()) self.assertEqual(kwargs, {'location': temp_storage_location}) kwargs_orig = { 'location': temp_storage_location, 'base_url': 'http://myfiles.example.com/' } storage = FileSystemStorage(**kwargs_orig) path, args, kwargs = storage.deconstruct() self.assertEqual(kwargs, kwargs_orig) def test_lazy_base_url_init(self): """ FileSystemStorage.__init__() shouldn't evaluate base_url. """ storage = FileSystemStorage(base_url=reverse_lazy('app:url')) with self.assertRaises(NoReverseMatch): storage.url(storage.base_url) class FileStorageTests(SimpleTestCase): storage_class = FileSystemStorage def setUp(self): self.temp_dir = tempfile.mkdtemp() self.storage = self.storage_class(location=self.temp_dir, base_url='/test_media_url/') # Set up a second temporary directory which is ensured to have a mixed # case name. self.temp_dir2 = tempfile.mkdtemp(suffix='aBc') def tearDown(self): shutil.rmtree(self.temp_dir) shutil.rmtree(self.temp_dir2) def test_empty_location(self): """ Makes sure an exception is raised if the location is empty """ storage = self.storage_class(location='') self.assertEqual(storage.base_location, '') self.assertEqual(storage.location, os.getcwd()) def test_file_access_options(self): """ Standard file access options are available, and work as expected. """ self.assertFalse(self.storage.exists('storage_test')) f = self.storage.open('storage_test', 'w') f.write('storage contents') f.close() self.assertTrue(self.storage.exists('storage_test')) f = self.storage.open('storage_test', 'r') self.assertEqual(f.read(), 'storage contents') f.close() self.storage.delete('storage_test') self.assertFalse(self.storage.exists('storage_test')) def _test_file_time_getter(self, getter): # Check for correct behavior under both USE_TZ=True and USE_TZ=False. # The tests are similar since they both set up a situation where the # system time zone, Django's TIME_ZONE, and UTC are distinct. self._test_file_time_getter_tz_handling_on(getter) self._test_file_time_getter_tz_handling_off(getter) @override_settings(USE_TZ=True, TIME_ZONE='Africa/Algiers') def _test_file_time_getter_tz_handling_on(self, getter): # Django's TZ (and hence the system TZ) is set to Africa/Algiers which # is UTC+1 and has no DST change. We can set the Django TZ to something # else so that UTC, Django's TIME_ZONE, and the system timezone are all # different. now_in_algiers = timezone.make_aware(datetime.now()) with timezone.override(timezone.get_fixed_timezone(-300)): # At this point the system TZ is +1 and the Django TZ # is -5. The following will be aware in UTC. now = timezone.now() self.assertFalse(self.storage.exists('test.file.tz.on')) f = ContentFile('custom contents') f_name = self.storage.save('test.file.tz.on', f) self.addCleanup(self.storage.delete, f_name) dt = getter(f_name) # dt should be aware, in UTC self.assertTrue(timezone.is_aware(dt)) self.assertEqual(now.tzname(), dt.tzname()) # The three timezones are indeed distinct. naive_now = datetime.now() algiers_offset = now_in_algiers.tzinfo.utcoffset(naive_now) django_offset = timezone.get_current_timezone().utcoffset(naive_now) utc_offset = timezone.utc.utcoffset(naive_now) self.assertGreater(algiers_offset, utc_offset) self.assertLess(django_offset, utc_offset) # dt and now should be the same effective time. self.assertLess(abs(dt - now), timedelta(seconds=2)) @override_settings(USE_TZ=False, TIME_ZONE='Africa/Algiers') def _test_file_time_getter_tz_handling_off(self, getter): # Django's TZ (and hence the system TZ) is set to Africa/Algiers which # is UTC+1 and has no DST change. We can set the Django TZ to something # else so that UTC, Django's TIME_ZONE, and the system timezone are all # different. now_in_algiers = timezone.make_aware(datetime.now()) with timezone.override(timezone.get_fixed_timezone(-300)): # At this point the system TZ is +1 and the Django TZ # is -5. self.assertFalse(self.storage.exists('test.file.tz.off')) f = ContentFile('custom contents') f_name = self.storage.save('test.file.tz.off', f) self.addCleanup(self.storage.delete, f_name) dt = getter(f_name) # dt should be naive, in system (+1) TZ self.assertTrue(timezone.is_naive(dt)) # The three timezones are indeed distinct. naive_now = datetime.now() algiers_offset = now_in_algiers.tzinfo.utcoffset(naive_now) django_offset = timezone.get_current_timezone().utcoffset(naive_now) utc_offset = timezone.utc.utcoffset(naive_now) self.assertGreater(algiers_offset, utc_offset) self.assertLess(django_offset, utc_offset) # dt and naive_now should be the same effective time. self.assertLess(abs(dt - naive_now), timedelta(seconds=2)) # If we convert dt to an aware object using the Algiers # timezone then it should be the same effective time to # now_in_algiers. _dt = timezone.make_aware(dt, now_in_algiers.tzinfo) self.assertLess(abs(_dt - now_in_algiers), timedelta(seconds=2)) def test_file_get_accessed_time(self): """ File storage returns a Datetime object for the last accessed time of a file. """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) self.addCleanup(self.storage.delete, f_name) atime = self.storage.get_accessed_time(f_name) self.assertEqual(atime, datetime.fromtimestamp(os.path.getatime(self.storage.path(f_name)))) self.assertLess(timezone.now() - self.storage.get_accessed_time(f_name), timedelta(seconds=2)) @requires_tz_support def test_file_get_accessed_time_timezone(self): self._test_file_time_getter(self.storage.get_accessed_time) def test_file_get_created_time(self): """ File storage returns a datetime for the creation time of a file. """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) self.addCleanup(self.storage.delete, f_name) ctime = self.storage.get_created_time(f_name) self.assertEqual(ctime, datetime.fromtimestamp(os.path.getctime(self.storage.path(f_name)))) self.assertLess(timezone.now() - self.storage.get_created_time(f_name), timedelta(seconds=2)) @requires_tz_support def test_file_get_created_time_timezone(self): self._test_file_time_getter(self.storage.get_created_time) def test_file_get_modified_time(self): """ File storage returns a datetime for the last modified time of a file. """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) self.addCleanup(self.storage.delete, f_name) mtime = self.storage.get_modified_time(f_name) self.assertEqual(mtime, datetime.fromtimestamp(os.path.getmtime(self.storage.path(f_name)))) self.assertLess(timezone.now() - self.storage.get_modified_time(f_name), timedelta(seconds=2)) @requires_tz_support def test_file_get_modified_time_timezone(self): self._test_file_time_getter(self.storage.get_modified_time) def test_file_save_without_name(self): """ File storage extracts the filename from the content object if no name is given explicitly. """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f.name = 'test.file' storage_f_name = self.storage.save(None, f) self.assertEqual(storage_f_name, f.name) self.assertTrue(os.path.exists(os.path.join(self.temp_dir, f.name))) self.storage.delete(storage_f_name) def test_file_save_with_path(self): """ Saving a pathname should create intermediate directories as necessary. """ self.assertFalse(self.storage.exists('path/to')) self.storage.save('path/to/test.file', ContentFile('file saved with path')) self.assertTrue(self.storage.exists('path/to')) with self.storage.open('path/to/test.file') as f: self.assertEqual(f.read(), b'file saved with path') self.assertTrue(os.path.exists( os.path.join(self.temp_dir, 'path', 'to', 'test.file'))) self.storage.delete('path/to/test.file') def test_save_doesnt_close(self): with TemporaryUploadedFile('test', 'text/plain', 1, 'utf8') as file: file.write(b'1') file.seek(0) self.assertFalse(file.closed) self.storage.save('path/to/test.file', file) self.assertFalse(file.closed) self.assertFalse(file.file.closed) file = InMemoryUploadedFile(StringIO('1'), '', 'test', 'text/plain', 1, 'utf8') with file: self.assertFalse(file.closed) self.storage.save('path/to/test.file', file) self.assertFalse(file.closed) self.assertFalse(file.file.closed) def test_file_path(self): """ File storage returns the full path of a file """ self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) self.assertEqual(self.storage.path(f_name), os.path.join(self.temp_dir, f_name)) self.storage.delete(f_name) def test_file_url(self): """ File storage returns a url to access a given file from the Web. """ self.assertEqual(self.storage.url('test.file'), self.storage.base_url + 'test.file') # should encode special chars except ~!*()' # like encodeURIComponent() JavaScript function do self.assertEqual( self.storage.url(r"~!*()'@#$%^&*abc`+ =.file"), "/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%20%3D.file" ) self.assertEqual(self.storage.url("ab\0c"), "/test_media_url/ab%00c") # should translate os path separator(s) to the url path separator self.assertEqual(self.storage.url("""a/b\\c.file"""), "/test_media_url/a/b/c.file") # #25905: remove leading slashes from file names to prevent unsafe url output self.assertEqual(self.storage.url("/evil.com"), "/test_media_url/evil.com") self.assertEqual(self.storage.url(r"\evil.com"), "/test_media_url/evil.com") self.assertEqual(self.storage.url("///evil.com"), "/test_media_url/evil.com") self.assertEqual(self.storage.url(r"\\\evil.com"), "/test_media_url/evil.com") self.assertEqual(self.storage.url(None), "/test_media_url/") def test_base_url(self): """ File storage returns a url even when its base_url is unset or modified. """ self.storage.base_url = None with self.assertRaises(ValueError): self.storage.url('test.file') # #22717: missing ending slash in base_url should be auto-corrected storage = self.storage_class(location=self.temp_dir, base_url='/no_ending_slash') self.assertEqual( storage.url('test.file'), '%s%s' % (storage.base_url, 'test.file') ) def test_listdir(self): """ File storage returns a tuple containing directories and files. """ self.assertFalse(self.storage.exists('storage_test_1')) self.assertFalse(self.storage.exists('storage_test_2')) self.assertFalse(self.storage.exists('storage_dir_1')) self.storage.save('storage_test_1', ContentFile('custom content')) self.storage.save('storage_test_2', ContentFile('custom content')) os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1')) dirs, files = self.storage.listdir('') self.assertEqual(set(dirs), {'storage_dir_1'}) self.assertEqual(set(files), {'storage_test_1', 'storage_test_2'}) self.storage.delete('storage_test_1') self.storage.delete('storage_test_2') os.rmdir(os.path.join(self.temp_dir, 'storage_dir_1')) def test_file_storage_prevents_directory_traversal(self): """ File storage prevents directory traversal (files can only be accessed if they're below the storage location). """ with self.assertRaises(SuspiciousFileOperation): self.storage.exists('..') with self.assertRaises(SuspiciousFileOperation): self.storage.exists('/etc/passwd') def test_file_storage_preserves_filename_case(self): """The storage backend should preserve case of filenames.""" # Create a storage backend associated with the mixed case name # directory. other_temp_storage = self.storage_class(location=self.temp_dir2) # Ask that storage backend to store a file with a mixed case filename. mixed_case = 'CaSe_SeNsItIvE' file = other_temp_storage.open(mixed_case, 'w') file.write('storage contents') file.close() self.assertEqual(os.path.join(self.temp_dir2, mixed_case), other_temp_storage.path(mixed_case)) other_temp_storage.delete(mixed_case) def test_makedirs_race_handling(self): """ File storage should be robust against directory creation race conditions. """ real_makedirs = os.makedirs # Monkey-patch os.makedirs, to simulate a normal call, a raced call, # and an error. def fake_makedirs(path): if path == os.path.join(self.temp_dir, 'normal'): real_makedirs(path) elif path == os.path.join(self.temp_dir, 'raced'): real_makedirs(path) raise FileNotFoundError() elif path == os.path.join(self.temp_dir, 'error'): raise FileExistsError() else: self.fail('unexpected argument %r' % path) try: os.makedirs = fake_makedirs self.storage.save('normal/test.file', ContentFile('saved normally')) with self.storage.open('normal/test.file') as f: self.assertEqual(f.read(), b'saved normally') self.storage.save('raced/test.file', ContentFile('saved with race')) with self.storage.open('raced/test.file') as f: self.assertEqual(f.read(), b'saved with race') # Exceptions aside from FileNotFoundError are raised. with self.assertRaises(FileExistsError): self.storage.save('error/test.file', ContentFile('not saved')) finally: os.makedirs = real_makedirs def test_remove_race_handling(self): """ File storage should be robust against file removal race conditions. """ real_remove = os.remove # Monkey-patch os.remove, to simulate a normal call, a raced call, # and an error. def fake_remove(path): if path == os.path.join(self.temp_dir, 'normal.file'): real_remove(path) elif path == os.path.join(self.temp_dir, 'raced.file'): real_remove(path) raise FileNotFoundError() elif path == os.path.join(self.temp_dir, 'error.file'): raise PermissionError() else: self.fail('unexpected argument %r' % path) try: os.remove = fake_remove self.storage.save('normal.file', ContentFile('delete normally')) self.storage.delete('normal.file') self.assertFalse(self.storage.exists('normal.file')) self.storage.save('raced.file', ContentFile('delete with race')) self.storage.delete('raced.file') self.assertFalse(self.storage.exists('normal.file')) # Exceptions aside from FileNotFoundError are raised. self.storage.save('error.file', ContentFile('delete with error')) with self.assertRaises(PermissionError): self.storage.delete('error.file') finally: os.remove = real_remove def test_file_chunks_error(self): """ Test behavior when file.chunks() is raising an error """ f1 = ContentFile('chunks fails') def failing_chunks(): raise IOError f1.chunks = failing_chunks with self.assertRaises(IOError): self.storage.save('error.file', f1) def test_delete_no_name(self): """ Calling delete with an empty name should not try to remove the base storage directory, but fail loudly (#20660). """ with self.assertRaises(AssertionError): self.storage.delete('') def test_delete_deletes_directories(self): tmp_dir = tempfile.mkdtemp(dir=self.storage.location) self.storage.delete(tmp_dir) self.assertFalse(os.path.exists(tmp_dir)) @override_settings( MEDIA_ROOT='media_root', MEDIA_URL='media_url/', FILE_UPLOAD_PERMISSIONS=0o777, FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o777, ) def test_setting_changed(self): """ Properties using settings values as defaults should be updated on referenced settings change while specified values should be unchanged. """ storage = self.storage_class( location='explicit_location', base_url='explicit_base_url/', file_permissions_mode=0o666, directory_permissions_mode=0o666, ) defaults_storage = self.storage_class() settings = { 'MEDIA_ROOT': 'overriden_media_root', 'MEDIA_URL': 'overriden_media_url/', 'FILE_UPLOAD_PERMISSIONS': 0o333, 'FILE_UPLOAD_DIRECTORY_PERMISSIONS': 0o333, } with self.settings(**settings): self.assertEqual(storage.base_location, 'explicit_location') self.assertIn('explicit_location', storage.location) self.assertEqual(storage.base_url, 'explicit_base_url/') self.assertEqual(storage.file_permissions_mode, 0o666) self.assertEqual(storage.directory_permissions_mode, 0o666) self.assertEqual(defaults_storage.base_location, settings['MEDIA_ROOT']) self.assertIn(settings['MEDIA_ROOT'], defaults_storage.location) self.assertEqual(defaults_storage.base_url, settings['MEDIA_URL']) self.assertEqual(defaults_storage.file_permissions_mode, settings['FILE_UPLOAD_PERMISSIONS']) self.assertEqual( defaults_storage.directory_permissions_mode, settings['FILE_UPLOAD_DIRECTORY_PERMISSIONS'] ) class CustomStorage(FileSystemStorage): def get_available_name(self, name, max_length=None): """ Append numbers to duplicate files rather than underscores, like Trac. """ basename, *ext = name.split('.') number = 2 while self.exists(name): name = '.'.join([basename, str(number)] + ext) number += 1 return name class CustomStorageTests(FileStorageTests): storage_class = CustomStorage def test_custom_get_available_name(self): first = self.storage.save('custom_storage', ContentFile('custom contents')) self.assertEqual(first, 'custom_storage') second = self.storage.save('custom_storage', ContentFile('more contents')) self.assertEqual(second, 'custom_storage.2') self.storage.delete(first) self.storage.delete(second) class OverwritingStorage(FileSystemStorage): """ Overwrite existing files instead of appending a suffix to generate an unused name. """ # Mask out O_EXCL so os.open() doesn't raise OSError if the file exists. OS_OPEN_FLAGS = FileSystemStorage.OS_OPEN_FLAGS & ~os.O_EXCL def get_available_name(self, name, max_length=None): """Override the effort to find an used name.""" return name class OverwritingStorageTests(FileStorageTests): storage_class = OverwritingStorage def test_save_overwrite_behavior(self): """Saving to same file name twice overwrites the first file.""" name = 'test.file' self.assertFalse(self.storage.exists(name)) content_1 = b'content one' content_2 = b'second content' f_1 = ContentFile(content_1) f_2 = ContentFile(content_2) stored_name_1 = self.storage.save(name, f_1) try: self.assertEqual(stored_name_1, name) self.assertTrue(self.storage.exists(name)) self.assertTrue(os.path.exists(os.path.join(self.temp_dir, name))) with self.storage.open(name) as fp: self.assertEqual(fp.read(), content_1) stored_name_2 = self.storage.save(name, f_2) self.assertEqual(stored_name_2, name) self.assertTrue(self.storage.exists(name)) self.assertTrue(os.path.exists(os.path.join(self.temp_dir, name))) with self.storage.open(name) as fp: self.assertEqual(fp.read(), content_2) finally: self.storage.delete(name) class DiscardingFalseContentStorage(FileSystemStorage): def _save(self, name, content): if content: return super()._save(name, content) return '' class DiscardingFalseContentStorageTests(FileStorageTests): storage_class = DiscardingFalseContentStorage def test_custom_storage_discarding_empty_content(self): """ When Storage.save() wraps a file-like object in File, it should include the name argument so that bool(file) evaluates to True (#26495). """ output = StringIO('content') self.storage.save('tests/stringio', output) self.assertTrue(self.storage.exists('tests/stringio')) with self.storage.open('tests/stringio') as f: self.assertEqual(f.read(), b'content') class FileFieldStorageTests(TestCase): def tearDown(self): shutil.rmtree(temp_storage_location) def _storage_max_filename_length(self, storage): """ Query filesystem for maximum filename length (e.g. AUFS has 242). """ dir_to_test = storage.location while not os.path.exists(dir_to_test): dir_to_test = os.path.dirname(dir_to_test) try: return os.pathconf(dir_to_test, 'PC_NAME_MAX') except Exception: return 255 # Should be safe on most backends def test_files(self): self.assertIsInstance(Storage.normal, FileDescriptor) # An object without a file has limited functionality. obj1 = Storage() self.assertEqual(obj1.normal.name, "") with self.assertRaises(ValueError): obj1.normal.size # Saving a file enables full functionality. obj1.normal.save("django_test.txt", ContentFile("content")) self.assertEqual(obj1.normal.name, "tests/django_test.txt") self.assertEqual(obj1.normal.size, 7) self.assertEqual(obj1.normal.read(), b"content") obj1.normal.close() # File objects can be assigned to FileField attributes, but shouldn't # get committed until the model it's attached to is saved. obj1.normal = SimpleUploadedFile("assignment.txt", b"content") dirs, files = temp_storage.listdir("tests") self.assertEqual(dirs, []) self.assertNotIn("assignment.txt", files) obj1.save() dirs, files = temp_storage.listdir("tests") self.assertEqual(sorted(files), ["assignment.txt", "django_test.txt"]) # Save another file with the same name. obj2 = Storage() obj2.normal.save("django_test.txt", ContentFile("more content")) obj2_name = obj2.normal.name self.assertRegex(obj2_name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX) self.assertEqual(obj2.normal.size, 12) obj2.normal.close() # Deleting an object does not delete the file it uses. obj2.delete() obj2.normal.save("django_test.txt", ContentFile("more content")) self.assertNotEqual(obj2_name, obj2.normal.name) self.assertRegex(obj2.normal.name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX) obj2.normal.close() def test_filefield_read(self): # Files can be read in a little at a time, if necessary. obj = Storage.objects.create( normal=SimpleUploadedFile("assignment.txt", b"content")) obj.normal.open() self.assertEqual(obj.normal.read(3), b"con") self.assertEqual(obj.normal.read(), b"tent") self.assertEqual(list(obj.normal.chunks(chunk_size=2)), [b"co", b"nt", b"en", b"t"]) obj.normal.close() def test_filefield_write(self): # Files can be written to. obj = Storage.objects.create(normal=SimpleUploadedFile('rewritten.txt', b'content')) with obj.normal as normal: normal.open('wb') normal.write(b'updated') obj.refresh_from_db() self.assertEqual(obj.normal.read(), b'updated') obj.normal.close() def test_filefield_reopen(self): obj = Storage.objects.create(normal=SimpleUploadedFile('reopen.txt', b'content')) with obj.normal as normal: normal.open() obj.normal.open() obj.normal.file.seek(0) obj.normal.close() def test_duplicate_filename(self): # Multiple files with the same name get _(7 random chars) appended to them. objs = [Storage() for i in range(2)] for o in objs: o.normal.save("multiple_files.txt", ContentFile("Same Content")) try: names = [o.normal.name for o in objs] self.assertEqual(names[0], "tests/multiple_files.txt") self.assertRegex(names[1], "tests/multiple_files_%s.txt" % FILE_SUFFIX_REGEX) finally: for o in objs: o.delete() def test_file_truncation(self): # Given the max_length is limited, when multiple files get uploaded # under the same name, then the filename get truncated in order to fit # in _(7 random chars). When most of the max_length is taken by # dirname + extension and there are not enough characters in the # filename to truncate, an exception should be raised. objs = [Storage() for i in range(2)] filename = 'filename.ext' for o in objs: o.limited_length.save(filename, ContentFile('Same Content')) try: # Testing truncation. names = [o.limited_length.name for o in objs] self.assertEqual(names[0], 'tests/%s' % filename) self.assertRegex(names[1], 'tests/fi_%s.ext' % FILE_SUFFIX_REGEX) # Testing exception is raised when filename is too short to truncate. filename = 'short.longext' objs[0].limited_length.save(filename, ContentFile('Same Content')) with self.assertRaisesMessage(SuspiciousFileOperation, 'Storage can not find an available filename'): objs[1].limited_length.save(*(filename, ContentFile('Same Content'))) finally: for o in objs: o.delete() @unittest.skipIf( sys.platform.startswith('win'), "Windows supports at most 260 characters in a path.", ) def test_extended_length_storage(self): # Testing FileField with max_length > 255. Most systems have filename # length limitation of 255. Path takes extra chars. filename = (self._storage_max_filename_length(temp_storage) - 4) * 'a' # 4 chars for extension. obj = Storage() obj.extended_length.save('%s.txt' % filename, ContentFile('Same Content')) self.assertEqual(obj.extended_length.name, 'tests/%s.txt' % filename) self.assertEqual(obj.extended_length.read(), b'Same Content') obj.extended_length.close() def test_filefield_default(self): # Default values allow an object to access a single file. temp_storage.save('tests/default.txt', ContentFile('default content')) obj = Storage.objects.create() self.assertEqual(obj.default.name, "tests/default.txt") self.assertEqual(obj.default.read(), b"default content") obj.default.close() # But it shouldn't be deleted, even if there are no more objects using # it. obj.delete() obj = Storage() self.assertEqual(obj.default.read(), b"default content") obj.default.close() def test_empty_upload_to(self): # upload_to can be empty, meaning it does not use subdirectory. obj = Storage() obj.empty.save('django_test.txt', ContentFile('more content')) self.assertEqual(obj.empty.name, "django_test.txt") self.assertEqual(obj.empty.read(), b"more content") obj.empty.close() def test_random_upload_to(self): # Verify the fix for #5655, making sure the directory is only # determined once. obj = Storage() obj.random.save("random_file", ContentFile("random content")) self.assertTrue(obj.random.name.endswith("/random_file")) obj.random.close() def test_custom_valid_name_callable_upload_to(self): """ Storage.get_valid_name() should be called when upload_to is a callable. """ obj = Storage() obj.custom_valid_name.save("random_file", ContentFile("random content")) # CustomValidNameStorage.get_valid_name() appends '_valid' to the name self.assertTrue(obj.custom_valid_name.name.endswith("/random_file_valid")) obj.custom_valid_name.close() def test_filefield_pickling(self): # Push an object into the cache to make sure it pickles properly obj = Storage() obj.normal.save("django_test.txt", ContentFile("more content")) obj.normal.close() cache.set("obj", obj) self.assertEqual(cache.get("obj").normal.name, "tests/django_test.txt") def test_file_object(self): # Create sample file temp_storage.save('tests/example.txt', ContentFile('some content')) # Load it as python file object with open(temp_storage.path('tests/example.txt')) as file_obj: # Save it using storage and read its content temp_storage.save('tests/file_obj', file_obj) self.assertTrue(temp_storage.exists('tests/file_obj')) with temp_storage.open('tests/file_obj') as f: self.assertEqual(f.read(), b'some content') def test_stringio(self): # Test passing StringIO instance as content argument to save output = StringIO() output.write('content') output.seek(0) # Save it and read written file temp_storage.save('tests/stringio', output) self.assertTrue(temp_storage.exists('tests/stringio')) with temp_storage.open('tests/stringio') as f: self.assertEqual(f.read(), b'content') # Tests for a race condition on file saving (#4948). # This is written in such a way that it'll always pass on platforms # without threading. class SlowFile(ContentFile): def chunks(self): time.sleep(1) return super().chunks() class FileSaveRaceConditionTest(SimpleTestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) self.thread = threading.Thread(target=self.save_file, args=['conflict']) def tearDown(self): shutil.rmtree(self.storage_dir) def save_file(self, name): name = self.storage.save(name, SlowFile(b"Data")) def test_race_condition(self): self.thread.start() self.save_file('conflict') self.thread.join() files = sorted(os.listdir(self.storage_dir)) self.assertEqual(files[0], 'conflict') self.assertRegex(files[1], 'conflict_%s' % FILE_SUFFIX_REGEX) @unittest.skipIf(sys.platform.startswith('win'), "Windows only partially supports umasks and chmod.") class FileStoragePermissions(unittest.TestCase): def setUp(self): self.umask = 0o027 self.old_umask = os.umask(self.umask) self.storage_dir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.storage_dir) os.umask(self.old_umask) @override_settings(FILE_UPLOAD_PERMISSIONS=0o654) def test_file_upload_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save("the_file", ContentFile("data")) actual_mode = os.stat(self.storage.path(name))[0] & 0o777 self.assertEqual(actual_mode, 0o654) @override_settings(FILE_UPLOAD_PERMISSIONS=None) def test_file_upload_default_permissions(self): self.storage = FileSystemStorage(self.storage_dir) fname = self.storage.save("some_file", ContentFile("data")) mode = os.stat(self.storage.path(fname))[0] & 0o777 self.assertEqual(mode, 0o666 & ~self.umask) @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765) def test_file_upload_directory_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save("the_directory/the_file", ContentFile("data")) dir_mode = os.stat(os.path.dirname(self.storage.path(name)))[0] & 0o777 self.assertEqual(dir_mode, 0o765) @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=None) def test_file_upload_directory_default_permissions(self): self.storage = FileSystemStorage(self.storage_dir) name = self.storage.save("the_directory/the_file", ContentFile("data")) dir_mode = os.stat(os.path.dirname(self.storage.path(name)))[0] & 0o777 self.assertEqual(dir_mode, 0o777 & ~self.umask) class FileStoragePathParsing(SimpleTestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) def tearDown(self): shutil.rmtree(self.storage_dir) def test_directory_with_dot(self): """Regression test for #9610. If the directory name contains a dot and the file name doesn't, make sure we still mangle the file name instead of the directory name. """ self.storage.save('dotted.path/test', ContentFile("1")) self.storage.save('dotted.path/test', ContentFile("2")) files = sorted(os.listdir(os.path.join(self.storage_dir, 'dotted.path'))) self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path'))) self.assertEqual(files[0], 'test') self.assertRegex(files[1], 'test_%s' % FILE_SUFFIX_REGEX) def test_first_character_dot(self): """ File names with a dot as their first character don't have an extension, and the underscore should get added to the end. """ self.storage.save('dotted.path/.test', ContentFile("1")) self.storage.save('dotted.path/.test', ContentFile("2")) files = sorted(os.listdir(os.path.join(self.storage_dir, 'dotted.path'))) self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path'))) self.assertEqual(files[0], '.test') self.assertRegex(files[1], '.test_%s' % FILE_SUFFIX_REGEX) class ContentFileStorageTestCase(unittest.TestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(self.storage_dir) def tearDown(self): shutil.rmtree(self.storage_dir) def test_content_saving(self): """ ContentFile can be saved correctly with the filesystem storage, if it was initialized with either bytes or unicode content. """ self.storage.save('bytes.txt', ContentFile(b"content")) self.storage.save('unicode.txt', ContentFile("español")) @override_settings(ROOT_URLCONF='file_storage.urls') class FileLikeObjectTestCase(LiveServerTestCase): """ Test file-like objects (#15644). """ available_apps = [] def setUp(self): self.temp_dir = tempfile.mkdtemp() self.storage = FileSystemStorage(location=self.temp_dir) def tearDown(self): shutil.rmtree(self.temp_dir) def test_urllib_request_urlopen(self): """ Test the File storage API with a file-like object coming from urllib.request.urlopen(). """ file_like_object = urlopen(self.live_server_url + '/') f = File(file_like_object) stored_filename = self.storage.save("remote_file.html", f) remote_file = urlopen(self.live_server_url + '/') with self.storage.open(stored_filename) as stored_file: self.assertEqual(stored_file.read(), remote_file.read())
40.343687
113
0.653081
7957323a1b2d918cf0de85a6a1a0b87814fa0c01
3,478
py
Python
Ago-Dic-2019/Horacio Góngora/Practica 1/3-4 a 3-7.py
Andremm303/DAS_Sistemas
0163505737e2b24365ea8b4e8135773a6801add4
[ "MIT" ]
null
null
null
Ago-Dic-2019/Horacio Góngora/Practica 1/3-4 a 3-7.py
Andremm303/DAS_Sistemas
0163505737e2b24365ea8b4e8135773a6801add4
[ "MIT" ]
null
null
null
Ago-Dic-2019/Horacio Góngora/Practica 1/3-4 a 3-7.py
Andremm303/DAS_Sistemas
0163505737e2b24365ea8b4e8135773a6801add4
[ "MIT" ]
null
null
null
'''3-4. Guest List: If you could invite anyone, living or deceased, to dinner, who would you invite? Make a list that includes at least three people you’d like to invite to dinner. Then use your list to print a message to each person, inviting them to dinner.''' guests = ['Angelina Jolie', 'Jennifer Aniston', 'Adam Sandler'] for i in guests: print(f"Estimad@ {i} se le hace de la manera mas atenta una invitacion a cenar habra su comida favorita y fiesta !!!") '''3-5. Changing Guest List: You just heard that one of your guests can’t make the dinner, so you need to send out a new set of invitations. You’ll have to think of someone else to invite. • Start with your program from Exercise 3-4. Add a print statement at the end of your program stating the name of the guest who can’t make it. • Modify your list, replacing the name of the guest who can’t make it with the name of the new person you are inviting. • Print a second set of invitation messages, one for each person who is still in your list.''' print(f"El invitado {guests[2].title()} no podra asistir ya que esta filmando una pelicula super genial.") guests.pop() guests.append('Anne Hathaway') for i in guests: print(f"Estimad@ {i} se le hace de la manera mas atenta una invitacion a cenar habra su comida favorita y fiesta !!!") '''3-6. More Guests: You just found a bigger dinner table, so now more space is available. Think of three more guests to invite to dinner. • Start with your program from Exercise 3-4 or Exercise 3-5. Add a print statement to the end of your program informing people that you found a bigger dinner table. • Use insert() to add one new guest to the beginning of your list. • Use insert() to add one new guest to the middle of your list. • Use append() to add one new guest to the end of your list. • Print a new set of invitation messages, one for each person in your list.''' print(f"Estiamdos invitados acabo de conseguir una mesa mas grande asi que la fiesta sera mas grande con mas invitados ;)") guests.insert(0, "Antonio Banderas") guests.insert(1, "Halle Berry") guests.append("Johnny Deep") for i in guests: print(f"Estimad@ {i} se le hace de la manera mas atenta una invitacion a cenar habra su comida favorita y fiesta !!!") '''3-7. Shrinking Guest List: You just found out that your new dinner table won’t arrive in time for the dinner, and you have space for only two guests. • Start with your program from Exercise 3-6. Add a new line that prints a message saying that you can invite only two people for dinner. • Use pop() to remove guests from your list one at a time until only two names remain in your list. Each time you pop a name from your list, print a message to that person letting them know you’re sorry you can’t invite them to dinner. • Print a message to each of the two people still on your list, letting them know they’re still invited. • Use del to remove the last two names from your list, so you have an empty list. Print your list to make sure you actually have an empty list at the end of your program.''' print(f"Lo siento los malvados de las mesas al final solo me entregaran una mesa para dos personas asi que empieza la purga") while len(guests) > 2: desinvited = guests.pop() print(f"Lo siento {desinvited} pero solo tengo espacio para dos personas, te invito a la proxima cena") for i in guests: print(f"Eres afortunado {i} de seguir en la lista de invitados :D") del guests[1] del guests[0] print(guests)
48.305556
125
0.747269
7957325d21552aa53367ca42b788f1e77c0cd438
725
py
Python
var/spack/repos/builtin.mock/packages/dev-build-test-install-phases/package.py
padamson/spack
d3f67a48552691b4846ccc4a10f76740b154090c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2
2021-03-05T10:54:32.000Z
2021-03-05T14:14:52.000Z
var/spack/repos/builtin.mock/packages/dev-build-test-install-phases/package.py
padamson/spack
d3f67a48552691b4846ccc4a10f76740b154090c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
32
2020-12-15T17:29:20.000Z
2022-03-21T15:08:31.000Z
var/spack/repos/builtin.mock/packages/dev-build-test-install-phases/package.py
padamson/spack
d3f67a48552691b4846ccc4a10f76740b154090c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2
2021-07-19T20:31:27.000Z
2021-07-19T21:14:14.000Z
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from time import sleep class DevBuildTestInstallPhases(Package): homepage = "example.com" url = "fake.com" version('0.0.0', sha256='0123456789abcdefgh') phases = ['one', 'two', 'three', 'install'] def one(self, spec, prefix): sleep(1) print("One locomoco") def two(self, spec, prefix): sleep(2) print("Two locomoco") def three(self, spec, prefix): sleep(3) print("Three locomoco") def install(self, spec, prefix): print("install")
23.387097
73
0.637241
795732a8c0e281cdfac7da10096227b4e0e8a06e
1,318
py
Python
smallab/runner_implementations/main_process_runner.py
imrf6/smallab
519530c798e5eb0df8227f65a444afdb4ab1daad
[ "BSD-2-Clause" ]
5
2019-11-01T20:55:40.000Z
2021-06-17T06:15:32.000Z
smallab/runner_implementations/main_process_runner.py
imrf6/smallab
519530c798e5eb0df8227f65a444afdb4ab1daad
[ "BSD-2-Clause" ]
58
2019-11-01T18:02:20.000Z
2021-08-31T21:54:41.000Z
smallab/runner_implementations/main_process_runner.py
imrf6/smallab
519530c798e5eb0df8227f65a444afdb4ab1daad
[ "BSD-2-Clause" ]
2
2020-05-06T23:29:05.000Z
2020-10-07T05:07:09.000Z
import logging import typing from tqdm import tqdm from smallab.runner_implementations.abstract_runner import SimpleAbstractRunner from smallab.smallab_types import Specification from smallab.utilities.tqdm_to_logger import TqdmToLogger class MainRunner(SimpleAbstractRunner): """ The simplest runner which runs each specification in serial on the main process and thread. """ def __init__(self, show_progress=True): super().__init__() self.show_progress = show_progress def run(self, specifications_to_run: typing.List[Specification], run_and_save_fn): completed_specifications = [] failed_specifications = [] exceptions = [] for specification in tqdm(specifications_to_run, file=TqdmToLogger(logging.getLogger("smallab.main_process_runner")), desc="Experiments", disable=not self.show_progress): exception_thrown = run_and_save_fn(specification) if exception_thrown is None: completed_specifications.append(specification) else: failed_specifications.append(specification) exceptions.append(exception_thrown) self.finish(completed_specifications, failed_specifications, exceptions)
37.657143
102
0.695751
7957331e2ee767048e7f60fbcae6dcdac17fcbaa
12,796
py
Python
virt/ansible-latest/lib/python2.7/site-packages/ansible/modules/storage/netapp/na_ontap_quotas.py
lakhlaifi/RedHat-Ansible
27c5077cced9d416081fcd5d69ea44bca0317fa4
[ "Apache-2.0" ]
1
2020-03-22T01:04:39.000Z
2020-03-22T01:04:39.000Z
.v/lib/python3.6/site-packages/ansible/modules/storage/netapp/na_ontap_quotas.py
binRick/ansible-callback-concise
fd7b05596b30872af3f79a32f223a0458bffbedd
[ "MIT" ]
null
null
null
.v/lib/python3.6/site-packages/ansible/modules/storage/netapp/na_ontap_quotas.py
binRick/ansible-callback-concise
fd7b05596b30872af3f79a32f223a0458bffbedd
[ "MIT" ]
1
2020-03-22T01:04:48.000Z
2020-03-22T01:04:48.000Z
#!/usr/bin/python # (c) 2018-2019, NetApp, Inc # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'} DOCUMENTATION = ''' module: na_ontap_quotas short_description: NetApp ONTAP Quotas extends_documentation_fragment: - netapp.na_ontap version_added: '2.8' author: NetApp Ansible Team (@carchi8py) <ng-ansibleteam@netapp.com> description: - Set/Modify/Delete quota on ONTAP options: state: description: - Whether the specified quota should exist or not. choices: ['present', 'absent'] default: present type: str vserver: required: true description: - Name of the vserver to use. type: str volume: description: - The name of the volume that the quota resides on. required: true type: str quota_target: description: - The quota target of the type specified. required: true type: str qtree: description: - Name of the qtree for the quota. - For user or group rules, it can be the qtree name or "" if no qtree. - For tree type rules, this field must be "". default: "" type: str type: description: - The type of quota rule choices: ['user', 'group', 'tree'] required: true type: str policy: description: - Name of the quota policy from which the quota rule should be obtained. type: str set_quota_status: description: - Whether the specified volume should have quota status on or off. type: bool file_limit: description: - The number of files that the target can have. default: '-' type: str disk_limit: description: - The amount of disk space that is reserved for the target. default: '-' type: str threshold: description: - The amount of disk space the target would have to exceed before a message is logged. default: '-' type: str ''' EXAMPLES = """ - name: Add/Set quota na_ontap_quotas: state: present vserver: ansible volume: ansible quota_target: /vol/ansible type: user policy: ansible file_limit: 2 disk_limit: 3 set_quota_status: True hostname: "{{ netapp_hostname }}" username: "{{ netapp_username }}" password: "{{ netapp_password }}" - name: modify quota na_ontap_quotas: state: present vserver: ansible volume: ansible quota_target: /vol/ansible type: user policy: ansible file_limit: 2 disk_limit: 3 threshold: 3 set_quota_status: False hostname: "{{ netapp_hostname }}" username: "{{ netapp_username }}" password: "{{ netapp_password }}" - name: Delete quota na_ontap_quotas: state: absent vserver: ansible volume: ansible quota_target: /vol/ansible type: user policy: ansible hostname: "{{ netapp_hostname }}" username: "{{ netapp_username }}" password: "{{ netapp_password }}" """ RETURN = """ """ import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native import ansible.module_utils.netapp as netapp_utils from ansible.module_utils.netapp_module import NetAppModule HAS_NETAPP_LIB = netapp_utils.has_netapp_lib() class NetAppONTAPQuotas(object): '''Class with quotas methods''' def __init__(self): self.argument_spec = netapp_utils.na_ontap_host_argument_spec() self.argument_spec.update(dict( state=dict(required=False, choices=['present', 'absent'], default='present'), vserver=dict(required=True, type='str'), volume=dict(required=True, type='str'), quota_target=dict(required=True, type='str'), qtree=dict(required=False, type='str', default=""), type=dict(required=True, type='str', choices=['user', 'group', 'tree']), policy=dict(required=False, type='str'), set_quota_status=dict(required=False, type='bool'), file_limit=dict(required=False, type='str', default='-'), disk_limit=dict(required=False, type='str', default='-'), threshold=dict(required=False, type='str', default='-') )) self.module = AnsibleModule( argument_spec=self.argument_spec, supports_check_mode=True ) self.na_helper = NetAppModule() self.parameters = self.na_helper.set_parameters(self.module.params) if HAS_NETAPP_LIB is False: self.module.fail_json( msg="the python NetApp-Lib module is required") else: self.server = netapp_utils.setup_na_ontap_zapi(module=self.module, vserver=self.parameters['vserver']) def get_quota_status(self): """ Return details about the quota status :param: name : volume name :return: status of the quota. None if not found. :rtype: dict """ quota_status_get = netapp_utils.zapi.NaElement('quota-status') quota_status_get.translate_struct({ 'volume': self.parameters['volume'] }) try: result = self.server.invoke_successfully(quota_status_get, enable_tunneling=True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg='Error fetching quotas status info: %s' % to_native(error), exception=traceback.format_exc()) if result: return result['status'] return None def get_quotas(self): """ Get quota details :return: name of volume if quota exists, None otherwise """ quota_get = netapp_utils.zapi.NaElement('quota-list-entries-iter') query = { 'query': { 'quota-entry': { 'volume': self.parameters['volume'], 'quota-target': self.parameters['quota_target'], 'quota-type': self.parameters['type'] } } } quota_get.translate_struct(query) if self.parameters.get('policy'): quota_get['query']['quota-entry'].add_new_child('policy', self.parameters['policy']) try: result = self.server.invoke_successfully(quota_get, enable_tunneling=True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg='Error fetching quotas info: %s' % to_native(error), exception=traceback.format_exc()) if result.get_child_by_name('num-records') and int(result.get_child_content('num-records')) >= 1: return_values = {'volume': result['attributes-list']['quota-entry']['volume'], 'file_limit': result['attributes-list']['quota-entry']['file-limit'], 'disk_limit': result['attributes-list']['quota-entry']['disk-limit'], 'threshold': result['attributes-list']['quota-entry']['threshold']} return return_values return None def quota_entry_set(self): """ Adds a quota entry """ options = {'volume': self.parameters['volume'], 'quota-target': self.parameters['quota_target'], 'quota-type': self.parameters['type'], 'qtree': self.parameters['qtree'], 'file-limit': self.parameters['file_limit'], 'disk-limit': self.parameters['disk_limit'], 'threshold': self.parameters['threshold']} if self.parameters.get('policy'): options['policy'] = self.parameters['policy'] set_entry = netapp_utils.zapi.NaElement.create_node_with_children( 'quota-set-entry', **options) try: self.server.invoke_successfully(set_entry, enable_tunneling=True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg='Error adding/modifying quota entry %s: %s' % (self.parameters['volume'], to_native(error)), exception=traceback.format_exc()) def quota_entry_delete(self): """ Deletes a quota entry """ options = {'volume': self.parameters['volume'], 'quota-target': self.parameters['quota_target'], 'quota-type': self.parameters['type'], 'qtree': self.parameters['qtree']} set_entry = netapp_utils.zapi.NaElement.create_node_with_children( 'quota-delete-entry', **options) if self.parameters.get('policy'): set_entry.add_new_child('policy', self.parameters['policy']) try: self.server.invoke_successfully(set_entry, enable_tunneling=True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg='Error deleting quota entry %s: %s' % (self.parameters['volume'], to_native(error)), exception=traceback.format_exc()) def quota_entry_modify(self, modify_attrs): """ Modifies a quota entry """ options = {'volume': self.parameters['volume'], 'quota-target': self.parameters['quota_target'], 'quota-type': self.parameters['type'], 'qtree': self.parameters['qtree']} options.update(modify_attrs) if self.parameters.get('policy'): options['policy'] = str(self.parameters['policy']) modify_entry = netapp_utils.zapi.NaElement.create_node_with_children( 'quota-modify-entry', **options) try: self.server.invoke_successfully(modify_entry, enable_tunneling=True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg='Error modifying quota entry %s: %s' % (self.parameters['volume'], to_native(error)), exception=traceback.format_exc()) def on_or_off_quota(self, status): """ on or off quota """ quota = netapp_utils.zapi.NaElement.create_node_with_children( status, **{'volume': self.parameters['volume']}) try: self.server.invoke_successfully(quota, enable_tunneling=True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json(msg='Error setting %s for %s: %s' % (status, self.parameters['volume'], to_native(error)), exception=traceback.format_exc()) def apply(self): """ Apply action to quotas """ netapp_utils.ems_log_event("na_ontap_quotas", self.server) modify_quota_status = None modify_quota = None current = self.get_quotas() if 'set_quota_status' in self.parameters: quota_status = self.get_quota_status() if quota_status is not None: quota_status_action = self.na_helper.get_modified_attributes( {'set_quota_status': True if quota_status == 'on' else False}, self.parameters) if quota_status_action: modify_quota_status = 'quota-on' if quota_status_action['set_quota_status'] else 'quota-off' cd_action = self.na_helper.get_cd_action(current, self.parameters) if cd_action is None: modify_quota = self.na_helper.get_modified_attributes(current, self.parameters) if self.na_helper.changed: if self.module.check_mode: pass else: if cd_action == 'create': self.quota_entry_set() elif cd_action == 'delete': self.quota_entry_delete() elif modify_quota is not None: for key in list(modify_quota): modify_quota[key.replace("_", "-")] = modify_quota.pop(key) self.quota_entry_modify(modify_quota) if modify_quota_status is not None: self.on_or_off_quota(modify_quota_status) self.module.exit_json(changed=self.na_helper.changed) def main(): '''Execute action''' quota_obj = NetAppONTAPQuotas() quota_obj.apply() if __name__ == '__main__': main()
37.089855
114
0.592685
79573410fbdc7696120118aa533d8294268ccad0
4,869
py
Python
payabbhi/resources/virtual_account.py
ppm-avinder/payabbhi-python
0f84f01349e365753f4b83eee584618e1a855567
[ "MIT" ]
1
2018-03-06T08:30:38.000Z
2018-03-06T08:30:38.000Z
payabbhi/resources/virtual_account.py
ppm-avinder/payabbhi-python
0f84f01349e365753f4b83eee584618e1a855567
[ "MIT" ]
null
null
null
payabbhi/resources/virtual_account.py
ppm-avinder/payabbhi-python
0f84f01349e365753f4b83eee584618e1a855567
[ "MIT" ]
5
2018-10-08T05:56:44.000Z
2020-05-22T11:31:07.000Z
from ..error import InvalidRequestError from .api_resource import APIResource class VirtualAccount(APIResource): def __init__(self, client=None): super(VirtualAccount, self).__init__(client) def all(self, data=None, **kwargs): """" Get all Virtual Accounts. Args: data : Dictionary having keys using which virtual Account list will be filtered count : A limit on the number of virtual account objects to be returned. This can range between 1 and 100. skip : Represents number of virtual account objects to be skipped from : A filter criterion based on the created_at field of the virtual account object. Value can be a timestamp. Returns Virtual accounts created on or after this timestamp. to : A filter criterion based on the created_at field of the virtual account object. Value can be a timestamp. Returns Virtual accounts created on or before this timestamp. Returns: List of Virtual Account objects """ if data is None: data = {} return self._all(data, **kwargs) def create(self, data, **kwargs): """" Create V from virtual Account given data Args: data : Dictionary having keys using which virtual Account has to be created customer_id :Unique identifier of the customer who will pay to this virtual account. email : Email ID of the customer who will pay to this virtual account. contact_no : Contact Number of the customer who will pay to this virtual account. order_id : Unique identifier of an Order object created using Payabbhi API. invoice_id : Unique identifier of an Invoice object created using Payabbhi API. description : Description of the virtual account. collection_methods : A list of collection methods that should be used to collect payments for the virtual account. The values can be bank_account. notification_method : Describes how the customer would be notified about the virtual account. The value is one of email, sms, both, none. The default value is email. customer_notification_by : Indicates who is responsible for sharing the virtual account details and sending notifications to the customers for important life cycle events. The value can be either merchant or platform. The default value is platform. notes : Set of key/value pairs that you can attach to a virtual account object. It can be useful for storing additional information about the virtual account object in a structured format. Returns: Returns the virtual account object if the virtual account is created successfully. Else it returns an error response. """ return self._post(self.class_url(), data, **kwargs) def retrieve(self, virtual_account_id, **kwargs): """" Retrieve virtual account for given virtual account id Args: virtual_account_id: The identifier of the virtual account to be retrieved. Returns: Returns a virtual account object, given a valid virtual account identifier was provided, and returns an error otherwise. """ return self._retrieve(virtual_account_id, **kwargs) def close(self, virtual_account_id,**kwargs): """" Close virtual account for given virtual account id Args: virtual_account_id : Id for which virtual account is to be closed Returns: Returns the virtual account object if the virtual account is closed successfully. Else it returns an error response. """ return self._patch(virtual_account_id, **kwargs) def payments(self, virtual_account_id, data=None, **kwargs): """" Retrieve all payments for given virtual account Id Args: virtual_account_id: The identifier of the virtual account whose payments are to be retrieved. Returns: An object with total_count attribute containing the total count of payments corresponding to the given Virtual account, object attribute containing list and a data attribute containing an array of payment objects. """ if data is None: data = {} url = "{0}/payments".format(self.instance_url(virtual_account_id)) return self._get(url, data, **kwargs)
52.354839
189
0.62559
7957348f87371d3b2bccbdd8269aacf90a5fbf9c
3,088
py
Python
pytorch_dqn/visualize.py
pierg/wiseml-patterns
2decf2954001296bd04261b00ae144f53359a2b8
[ "BSD-3-Clause" ]
null
null
null
pytorch_dqn/visualize.py
pierg/wiseml-patterns
2decf2954001296bd04261b00ae144f53359a2b8
[ "BSD-3-Clause" ]
6
2021-03-18T21:24:56.000Z
2022-03-11T23:34:25.000Z
pytorch_dqn/visualize.py
pierg/wiseml-patterns
2decf2954001296bd04261b00ae144f53359a2b8
[ "BSD-3-Clause" ]
null
null
null
import numpy as np vis = None cum_rwd_f = None goal_f = None avg_rwd_f = None last_epsilon_f = None steps_goal = None expected_q_value = None cum_rwd_e = None def visdom_plot(what, x, x_label, y, y_label, where='main'): from visdom import Visdom global vis global cum_rwd_f global goal_f global avg_rwd_f global last_epsilon_f global steps_goal global expected_q_value global cum_rwd_e if vis is None: vis = Visdom(env=where) vis.close() else: vis = Visdom(env=where) assert vis.check_connection() # if vis is None: # vis = Visdom(env=where) # assert vis.check_connection() # # Close all existing plots # vis.close() if what == "cum_rwd": cum_rwd_f = vis.line( X=np.array(x), Y=np.array(y), opts=dict( xlabel=x_label, ylabel=y_label, ytickmin=0, width=300, height=250 ), win=cum_rwd_f ) if what == "expected_q_value": expected_q_value = vis.line( X=np.array(x), Y=np.array(y), opts=dict( xlabel=x_label, ylabel=y_label, ytickmin=0, width=300, height=250 ), win=expected_q_value ) if what == "steps_goal": steps_goal = vis.line( X=np.array(x), Y=np.array(y), opts=dict( xlabel=x_label, ylabel=y_label, ytickmin=0, width=300, height=250 ), win=steps_goal ) if what == "cum_rwd_e": cum_rwd_e = vis.line( X=np.array(x), Y=np.array(y), opts=dict( xlabel=x_label, ylabel=y_label, ytickmin=0, width=300, height=250 ), win=cum_rwd_e ) if what == "avg_rwd": avg_rwd_f = vis.line( X=np.array(x), Y=np.array(y), opts=dict( xlabel=x_label, ylabel=y_label, ytickmin=0, width=300, height=250 ), win=avg_rwd_f ) if what == "goal": goal_f = vis.line( X=np.array(x), Y=np.array(y), opts=dict( xlabel=x_label, ylabel=y_label, ytickmin=0, width=300, height=250 ), win=goal_f ) if what == "last_epsilon": last_epsilon_f = vis.line( X=np.array(x), Y=np.array(y), opts=dict( xlabel=x_label, ylabel=y_label, ytickmin=0, width=300, height=250 ), win=last_epsilon_f )
22.215827
60
0.435557
795734b7e0dee3908488124c867ebe95445652f6
1,915
py
Python
benchmark/tests/test_14.py
trxw/qutip
b923c973edd9a071d86eb849650661549f73585f
[ "BSD-3-Clause" ]
1
2015-11-06T06:35:06.000Z
2015-11-06T06:35:06.000Z
benchmark/tests/test_14.py
trxw/qutip
b923c973edd9a071d86eb849650661549f73585f
[ "BSD-3-Clause" ]
null
null
null
benchmark/tests/test_14.py
trxw/qutip
b923c973edd9a071d86eb849650661549f73585f
[ "BSD-3-Clause" ]
null
null
null
from qutip import * from numpy import * from time import time def test_14(runs=1): """ mcsolve evolution of 8-spin chain """ test_name='8-spin MC [256]' N = 6# number of spins # uniform parameters h = 1.0 * 2 * pi * ones(N) Jz = 0.1 * 2 * pi * ones(N) Jx = 0.1 * 2 * pi * ones(N) Jy = 0.1 * 2 * pi * ones(N) # dephasing rate gamma = 0.01 * ones(N) # intial state, first spin in state |1>, the rest in state |0> psi_list = [] psi_list.append(basis(2,1)) for n in range(N-1): psi_list.append(basis(2,0)) psi0 = tensor(psi_list) tlist = linspace(0, 10, 200) # Hamiltonian si = qeye(2) sx = sigmax() sy = sigmay() sz = sigmaz() sx_list = [] sy_list = [] sz_list = [] for n in range(N): op_list = [] for m in range(N): op_list.append(si) op_list[n] = sx sx_list.append(tensor(op_list)) op_list[n] = sy sy_list.append(tensor(op_list)) op_list[n] = sz sz_list.append(tensor(op_list)) # construct the hamiltonian H = 0 # energy splitting terms for n in range(N): H += - 0.5 * h[n] * sz_list[n] # interaction terms for n in range(N-1): H += - 0.5 * Jx[n] * sx_list[n] * sx_list[n+1] H += - 0.5 * Jy[n] * sy_list[n] * sy_list[n+1] H += - 0.5 * Jz[n] * sz_list[n] * sz_list[n+1] # collapse operators c_op_list = [] # spin dephasing for n in range(N): c_op_list.append(sqrt(gamma[n]) * sz_list[n]) # evolve and calculate expectation values opts=Odeoptions(gui=False) tot_elapsed = 0 for n in range(runs): tic=time() mcsolve(H, psi0, tlist, c_op_list, sz_list,options=opts) toc=time() tot_elapsed += toc - tic return [test_name], [tot_elapsed / runs] if __name__=='__main__': test_14()
25.533333
66
0.543603
7957358944f3c0d20f1ee1459cec3381ef00f625
765
py
Python
test/conftest.py
cybergarage/uecho-py
6b0dc72b9c3770d79b812bad75ea201c820b089a
[ "Apache-2.0" ]
null
null
null
test/conftest.py
cybergarage/uecho-py
6b0dc72b9c3770d79b812bad75ea201c820b089a
[ "Apache-2.0" ]
null
null
null
test/conftest.py
cybergarage/uecho-py
6b0dc72b9c3770d79b812bad75ea201c820b089a
[ "Apache-2.0" ]
null
null
null
# Copyright (C) 2021 Satoshi Konno. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from uecho import Controller @pytest.fixture(scope='function', autouse=True) def ctrl(): ctrl = Controller() yield (ctrl) ctrl.stop()
30.6
74
0.746405
795736587201c3ebcb597e1370ec5a7861c883ec
648
py
Python
autograder-master/autograder/checks/required_files_present_check.py
Diana1320622/AILabs
315a6f4b8f8dd60e4f53d348e06e23b4d827d179
[ "MIT" ]
null
null
null
autograder-master/autograder/checks/required_files_present_check.py
Diana1320622/AILabs
315a6f4b8f8dd60e4f53d348e06e23b4d827d179
[ "MIT" ]
null
null
null
autograder-master/autograder/checks/required_files_present_check.py
Diana1320622/AILabs
315a6f4b8f8dd60e4f53d348e06e23b4d827d179
[ "MIT" ]
null
null
null
from base_check import BaseCheck import os class RequiredFilesPresentCheck(BaseCheck): def __init__(self, context): super(RequiredFilesPresentCheck, self).__init__(context) def run(self): required_files = ['report.pdf'] for required_file in required_files: self.check_presence(required_file) def check_presence(self, required_file): file = os.path.join(self.context.repo_dir, required_file) if os.path.isfile(file): self.info("Required file '{}' found.".format(required_file)) else: self.error("Required file '{}' not found.".format(required_file))
34.105263
77
0.674383
7957367cb6ac56650c2ce0f6ddc135fab3831208
3,833
py
Python
python/demos/linear_quadratic_partial.py
machines-in-motion/dynamic_game_optimizer
5849ae11918f68f346aa4a869d57fc8242162f5c
[ "BSD-3-Clause" ]
null
null
null
python/demos/linear_quadratic_partial.py
machines-in-motion/dynamic_game_optimizer
5849ae11918f68f346aa4a869d57fc8242162f5c
[ "BSD-3-Clause" ]
null
null
null
python/demos/linear_quadratic_partial.py
machines-in-motion/dynamic_game_optimizer
5849ae11918f68f346aa4a869d57fc8242162f5c
[ "BSD-3-Clause" ]
null
null
null
import os, sys, time from cv2 import solve src_path = os.path.abspath("../") sys.path.append(src_path) import numpy as np import crocoddyl from models import lin_quad_action as lin_quad import matplotlib.pyplot as plt from utils.measurements import FullStateMeasurement, MeasurementTrajectory from solvers.partial import PartialDGSolver import crocoddyl LINE_WIDTH = 100 horizon = 100 plan_dt = 1.0e-2 x0 = np.zeros(4) MAX_ITER = 100 PLOT_DDP = True pm = 1e-2 * np.eye(4) # process error weight matrix mm = 1e-2 * np.eye(4) # measurement error weight matrix P0 = 1e-2 * np.eye(4) MU = 0.01 t_solve = 50 # solve problem for t = 50 if __name__ == "__main__": lq_diff_running = lin_quad.DifferentialActionModelLQ() lq_diff_terminal = lin_quad.DifferentialActionModelLQ(isTerminal=True) lq_running = crocoddyl.IntegratedActionModelEuler(lq_diff_running, plan_dt) lq_terminal = crocoddyl.IntegratedActionModelEuler(lq_diff_terminal, plan_dt) process_models = [lq_running] * (horizon) + [lq_terminal] print(" Constructing integrated models completed ".center(LINE_WIDTH, "-")) ddp_problem = crocoddyl.ShootingProblem(x0, process_models[:-1], process_models[-1]) measurement_models = [FullStateMeasurement(lq_running, mm)] * horizon + [ FullStateMeasurement(lq_terminal, mm) ] print(" Constructing shooting problem completed ".center(LINE_WIDTH, "-")) measurement_trajectory = MeasurementTrajectory(measurement_models) xs = [x0] * (horizon + 1) # ________ Solve DDP to generate measurements ____________________# ddp_solver = crocoddyl.SolverDDP(ddp_problem) ddp_solver.setCallbacks([crocoddyl.CallbackLogger(), crocoddyl.CallbackVerbose()]) ddp_xs = [x0] * (horizon + 1) ddp_us = [np.zeros(2)] * horizon ddp_converged = ddp_solver.solve(ddp_xs, ddp_us, MAX_ITER) ys = measurement_trajectory.calc(ddp_solver.xs[: t_solve + 1], ddp_solver.us[:t_solve]) dg_solver = PartialDGSolver(ddp_problem, MU, pm, P0, measurement_trajectory) print(" Constructor and Data Allocation for Partial Solver Works ".center(LINE_WIDTH, "-")) u_init = [np.zeros(2)] * horizon u_init[:t_solve] = ddp_solver.us[:t_solve] dg_solver.solve(init_xs=xs, init_us=u_init, init_ys=ys) print(" Plotting DDP and DG Solutions ".center(LINE_WIDTH, "-")) time_array = plan_dt * np.arange(horizon + 1) plt.figure() x = np.array(dg_solver.xs) x_n = [d.xnext.copy() for d in dg_solver.problem.runningDatas] for t in range(len(np.array(dg_solver.xs[: t_solve - 1]))): if t == 0: plt.plot(np.array([x[t][0], x_n[t][0]]), np.array([x[t][1], x_n[t][1]]), "green", label="DG estimation") else: plt.plot(np.array([x[t][0], x_n[t][0]]), np.array([x[t][1], x_n[t][1]]), "green") for t_ in range(len(np.array(dg_solver.xs[t_solve - 1 : -1]))): t = t_ + t_solve - 1 if t_ == 0: plt.plot(np.array([x[t][0], x_n[t][0]]), np.array([x[t][1], x_n[t][1]]), "red", label="DG control") else: plt.plot(np.array([x[t][0], x_n[t][0]]), np.array([x[t][1], x_n[t][1]]), "red") plt.plot(np.array(ddp_solver.xs)[:, 0], np.array(ddp_solver.xs)[:, 1], label="DDP Trajectory") plt.plot( np.array(ddp_solver.xs)[:t_solve, 0], np.array(ddp_solver.xs)[:t_solve, 1], "black", label="Measurements") plt.xlabel("x") plt.ylabel("y") plt.title("Position trajectory") plt.legend() plt.figure() plt.plot(np.array(ddp_solver.us)[:, 0], label="DDP u_0") plt.plot(np.array(ddp_solver.us)[:, 1], label="DDP u_1") plt.plot(np.array(dg_solver.us)[:, 0], label="DG u_0") plt.plot(np.array(dg_solver.us)[:, 1], label="DG u_1") plt.xlabel("Time") plt.ylabel("Control") plt.title("Control inputs") plt.legend() plt.show()
38.33
120
0.669189
7957369f10d91dd5389ee6410c5847cbbb2d8c1b
10,567
py
Python
clk/alias.py
Konubinix/click_project
be0d52e8babb2df4bcf58208d067609ed3bf20d6
[ "MIT" ]
9
2021-08-12T08:49:47.000Z
2021-11-10T17:23:34.000Z
clk/alias.py
Konubinix/click_project
be0d52e8babb2df4bcf58208d067609ed3bf20d6
[ "MIT" ]
1
2022-01-21T20:49:20.000Z
2022-01-24T21:23:15.000Z
clk/alias.py
Konubinix/click_project
be0d52e8babb2df4bcf58208d067609ed3bf20d6
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import shlex import click from clk.commandresolver import CommandResolver from clk.config import config from clk.core import get_ctx, run from clk.decorators import pass_context from clk.flow import clean_flow_arguments, flowdeps from clk.lib import ordered_unique, quote from clk.log import get_logger from clk.overloads import AutomaticOption, Command, Group, command, get_command, group, list_commands LOGGER = get_logger(__name__) def parse(words): """Split a list of words into a list of commands""" sep = ',' commands = [] while sep in words: index = words.index(sep) commands.append(words[:index]) del words[:index + 1] if words: commands.append(words) return commands def format(cmds, sep=' , '): """Format the alias command""" return sep.join(' '.join(cmd) for cmd in cmds) def edit_alias_command_in_profile(path, profile): old_value = profile.settings.get('alias', {}).get(path) old_value = format(old_value['commands'], sep='\n') value = click.edit(old_value, extension=f'_{path}.txt') if value == old_value: LOGGER.info('Nothing changed') elif value == '': LOGGER.info('Aboooooort !!') else: value = value.strip().replace('\n', ' , ') LOGGER.status(f"Replacing alias {path} in {profile.name} from '{old_value}' to '{value}'") profile.settings['alias'][path]['commands'] = parse(shlex.split(value)) profile.write_settings() def edit_alias_command(path): for profile in config.all_enabled_profiles: if profile.settings.get('alias', {}).get(path): edit_alias_command_in_profile(path, profile) break exit(0) class AliasToGroupResolver(CommandResolver): name = 'alias to group' def _list_command_paths(self, parent): try: original_command = parent.original_command except AttributeError: return [] return ['{}.{}'.format(parent.path, cmd_name) for cmd_name in list_commands(original_command.path)] def _get_command(self, path, parent): cmd_name = path.split('.')[-1] parent = parent.original_command original_path = '{}.{}'.format(parent.path, cmd_name) return get_command(original_path) class AliasCommandResolver(CommandResolver): name = 'alias' def _list_command_paths(self, parent): if isinstance(parent, config.main_command.__class__): return [a for a in config.get_settings('alias').keys()] else: return [ a for a in config.get_settings('alias').keys() if a.startswith(parent.path + '.') and a[len(parent.path) + 1:] != 0 ] def _get_command(self, path, parent=None): name = path.split('.')[-1] commands_to_run = config.get_settings('alias')[path]['commands'] cmdhelp = config.get_settings('alias')[path]['documentation'] cmdhelp = cmdhelp or 'Alias for: {}'.format(' , '.join(' '.join(quote(arg) for arg in cmd) for cmd in commands_to_run)) short_help = cmdhelp.splitlines()[0] if len(cmdhelp) > 55: short_help = cmdhelp[:52] + '...' deps = [] for cmd in commands_to_run[:-1]: # get the contexts of the commands to capture the flow. I don't want # to allow side effects because they are only supposed to be run, # not to impact how the alias will behave in completion, parameters # etc. cmdctx = get_ctx(cmd, resilient_parsing=True, side_effects=False) deps += flowdeps[cmdctx.command.path] # also get the context of the last command to capture its flow. In that # case, I wan't to allow side effects because I want this command to # impact the behavior of the generated alias. Its parameters, completion # or whatever should transpire in the aliased command. The parsing must # be resilient though because the aliased command might be incomplete # (like it might be missing an argument) c = get_ctx(commands_to_run[-1], side_effects=True, resilient_parsing=True) deps += flowdeps[c.command.path] deps = ordered_unique(deps) kind = None def create_cls(cls): return cls(name=name, help=cmdhelp, short_help=short_help, ignore_unknown_options=c is not None and c.ignore_unknown_options) if c is not None: if isinstance(c.command, Group): cls = create_cls(group) kind = 'group' elif isinstance(c.command, Command): cls = create_cls(command) kind = 'command' elif isinstance(c.command, config.main_command.__class__): cls = click.group(cls=config.main_command.__class__, name=name, help=cmdhelp, short_help=short_help) kind = config.main_command.path else: raise NotImplementedError() elif commands_to_run[-1][0] == config.main_command.path: cls = click.group(cls=config.main_command.__class__, name=name, help=cmdhelp, short_help=short_help) del commands_to_run[-1][0] c = get_ctx(commands_to_run[-1]) kind = config.main_command.path else: cls = create_cls(command) def alias_command(ctx, *args, **kwargs): if 'config' in kwargs: del kwargs['config'] commands = list(commands_to_run) for command_ in commands[:-1]: LOGGER.debug('Running command: {}'.format(' '.join(quote(c) for c in command_))) run(command_) arguments = ctx.complete_arguments[:] arguments = clean_flow_arguments(arguments) if '--' in commands[-1]: separator_index = commands[-1].index('--') processed_part = commands[-1][:separator_index] ignored_part = commands[-1][separator_index + 1:] whole_command = processed_part + arguments + ['--'] + ignored_part else: whole_command = commands[-1] + arguments original_command_ctx = get_ctx(whole_command, side_effects=True) cur_ctx = original_command_ctx ctxs = [] # if the resolution of the context brought too many commands, we # must not call the call back of the children of the original_command while cur_ctx and ctx.command.original_command != cur_ctx.command: cur_ctx = cur_ctx.parent while cur_ctx: ctxs.insert(0, cur_ctx) cur_ctx = cur_ctx.parent LOGGER.develop('Running command: {}'.format(' '.join(quote(c) for c in commands[-1]))) def run_callback(_ctx): LOGGER.develop('Running callback of {} with args {}, params {}'.format( _ctx.command.path, config.commandline_profile.get_settings('parameters')[_ctx.command.path], _ctx.params, )) # this alias already captured the complete flow, hence we should # not trigger any flow behavior of the aliased commands for flow_param in 'flow', 'flow_from', 'flow_after': if flow_param in _ctx.params: _ctx.params[flow_param] = None with _ctx: old_resilient_parsing = _ctx.resilient_parsing _ctx.resilient_parsing = ctx.resilient_parsing _ctx.command.callback(**_ctx.params) _ctx.resilient_parsing = old_resilient_parsing for cur_ctx in ctxs: run_callback(cur_ctx) alias_command = pass_context(alias_command) alias_command = cls(alias_command) alias_command.params.append( AutomaticOption(['--edit-alias'], help='Edit the alias', expose_value=False, is_flag=True, callback=lambda ctx, param, value: edit_alias_command(path) if value is True else None)) if deps: alias_command.clk_flowdepends = deps alias_command.clk_flow = c.params['flow'] alias_command.clk_flowfrom = c.params['flow_from'] alias_command.clk_flowafter = c.params['flow_after'] alias_command.commands_to_run = commands_to_run if c is not None: alias_command.original_command = c.command if kind == 'group': if c.command.default_cmd_name is not None: alias_command.set_default_command(c.command.default_cmd_name) elif kind == 'command': alias_command.handle_dry_run = c.command.handle_dry_run alias_param_names = list(map(lambda c: c.name, alias_command.params)) def was_given(param): return not ( # catched the default value only because it was not # given to the command line param.name in c.clk_default_catch or # not given for sure c.params.get(param.name) == param.default) alias_command.params = [ param for param in c.command.params if param.name not in alias_param_names and param.name not in ('flow', 'flow_from', 'flow_after') and ( # options may be given several times isinstance(param, click.Option) or ( # it is an argument then! not was_given(param) or # may be given, but may be given again param.multiple or # may be given, but may be given again param.nargs == -1)) ] + alias_command.params # any option required with nargs=-1 that was already given should be # no more required for param in alias_command.params: if param.nargs == -1 and param.required and was_given(param): param.required = False return alias_command
42.608871
118
0.581433
795736d5ae279c4934533ca155028dbd9dd18a7e
62,631
py
Python
tests/common.py
cyyynthia/emscripten
9ee232c0eb562cb1fed229a6ece80645d0ab4db5
[ "MIT" ]
10
2021-09-13T20:36:34.000Z
2021-10-19T10:46:25.000Z
tests/common.py
cyyynthia/emscripten
9ee232c0eb562cb1fed229a6ece80645d0ab4db5
[ "MIT" ]
null
null
null
tests/common.py
cyyynthia/emscripten
9ee232c0eb562cb1fed229a6ece80645d0ab4db5
[ "MIT" ]
null
null
null
# Copyright 2021 The Emscripten Authors. All rights reserved. # Emscripten is available under two separate licenses, the MIT license and the # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. from enum import Enum from functools import wraps from pathlib import Path from subprocess import PIPE, STDOUT from urllib.parse import unquote, unquote_plus from http.server import HTTPServer, SimpleHTTPRequestHandler import contextlib import difflib import hashlib import logging import multiprocessing import os import shlex import shutil import stat import string import subprocess import sys import tempfile import time import webbrowser import unittest import clang_native import jsrun from jsrun import NON_ZERO from tools.shared import TEMP_DIR, EMCC, EMXX, DEBUG, EMCONFIGURE, EMCMAKE from tools.shared import EMSCRIPTEN_TEMP_DIR from tools.shared import EM_BUILD_VERBOSE from tools.shared import get_canonical_temp_dir, try_delete, path_from_root from tools.utils import MACOS, WINDOWS from tools import shared, line_endings, building, config logger = logging.getLogger('common') # User can specify an environment variable EMTEST_BROWSER to force the browser # test suite to run using another browser command line than the default system # browser. Setting '0' as the browser disables running a browser (but we still # see tests compile) EMTEST_BROWSER = None EMTEST_DETECT_TEMPFILE_LEAKS = None EMTEST_SAVE_DIR = None # generally js engines are equivalent, testing 1 is enough. set this # to force testing on all js engines, good to find js engine bugs EMTEST_ALL_ENGINES = None EMTEST_SKIP_SLOW = None EMTEST_LACKS_NATIVE_CLANG = None EMTEST_VERBOSE = None EMTEST_REBASELINE = None TEST_ROOT = path_from_root('tests') WEBIDL_BINDER = shared.bat_suffix(path_from_root('tools/webidl_binder')) EMBUILDER = shared.bat_suffix(path_from_root('embuilder')) EMMAKE = shared.bat_suffix(path_from_root('emmake')) def delete_contents(pathname): for entry in os.listdir(pathname): try_delete(os.path.join(pathname, entry)) def test_file(*path_components): """Construct a path relative to the emscripten "tests" directory.""" return str(Path(TEST_ROOT, *path_components)) def read_file(*path_components): return Path(*path_components).read_text() def read_binary(*path_components): return Path(*path_components).read_bytes() # checks if browser testing is enabled def has_browser(): return EMTEST_BROWSER != '0' def compiler_for(filename, force_c=False): if shared.suffix(filename) in ('.cc', '.cxx', '.cpp') and not force_c: return EMXX else: return EMCC # Generic decorator that calls a function named 'condition' on the test class and # skips the test if that function returns true def skip_if(func, condition, explanation='', negate=False): assert callable(func) explanation_str = ' : %s' % explanation if explanation else '' @wraps(func) def decorated(self, *args, **kwargs): choice = self.__getattribute__(condition)() if negate: choice = not choice if choice: self.skipTest(condition + explanation_str) func(self, *args, **kwargs) return decorated def needs_dylink(func): assert callable(func) @wraps(func) def decorated(self): self.check_dylink() return func(self) return decorated def is_slow_test(func): assert callable(func) @wraps(func) def decorated(self, *args, **kwargs): if EMTEST_SKIP_SLOW: return self.skipTest('skipping slow tests') return func(self, *args, **kwargs) return decorated def disabled(note=''): assert not callable(note) return unittest.skip(note) def no_mac(note=''): assert not callable(note) if MACOS: return unittest.skip(note) return lambda f: f def no_windows(note=''): assert not callable(note) if WINDOWS: return unittest.skip(note) return lambda f: f def requires_native_clang(func): assert callable(func) def decorated(self, *args, **kwargs): if EMTEST_LACKS_NATIVE_CLANG: return self.skipTest('native clang tests are disabled') return func(self, *args, **kwargs) return decorated def require_node(func): assert callable(func) def decorated(self, *args, **kwargs): self.require_node() return func(self, *args, **kwargs) return decorated def require_v8(func): assert callable(func) def decorated(self, *args, **kwargs): self.require_v8() return func(self, *args, **kwargs) return decorated def node_pthreads(f): def decorated(self): self.set_setting('USE_PTHREADS') self.emcc_args += ['-Wno-pthreads-mem-growth'] if self.get_setting('MINIMAL_RUNTIME'): self.skipTest('node pthreads not yet supported with MINIMAL_RUNTIME') self.js_engines = [config.NODE_JS] self.node_args += ['--experimental-wasm-threads', '--experimental-wasm-bulk-memory'] f(self) return decorated @contextlib.contextmanager def env_modify(updates): """A context manager that updates os.environ.""" # This could also be done with mock.patch.dict() but taking a dependency # on the mock library is probably not worth the benefit. old_env = os.environ.copy() print("env_modify: " + str(updates)) # Seting a value to None means clear the environment variable clears = [key for key, value in updates.items() if value is None] updates = {key: value for key, value in updates.items() if value is not None} os.environ.update(updates) for key in clears: if key in os.environ: del os.environ[key] try: yield finally: os.environ.clear() os.environ.update(old_env) # Decorator version of env_modify def with_env_modify(updates): def decorated(f): def modified(self): with env_modify(updates): return f(self) return modified return decorated def ensure_dir(dirname): dirname = Path(dirname) dirname.mkdir(parents=True, exist_ok=True) def limit_size(string, maxbytes=800000 * 20, maxlines=100000, max_line=5000): lines = string.splitlines() for i, line in enumerate(lines): if len(line) > max_line: lines[i] = line[:max_line] + '[..]' if len(lines) > maxlines: lines = lines[0:maxlines // 2] + ['[..]'] + lines[-maxlines // 2:] string = '\n'.join(lines) + '\n' if len(string) > maxbytes: string = string[0:maxbytes // 2] + '\n[..]\n' + string[-maxbytes // 2:] return string def create_file(name, contents, binary=False): name = Path(name) assert not name.is_absolute() if binary: name.write_bytes(contents) else: name.write_text(contents) def make_executable(name): Path(name).chmod(stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC) def parameterized(parameters): """ Mark a test as parameterized. Usage: @parameterized({ 'subtest1': (1, 2, 3), 'subtest2': (4, 5, 6), }) def test_something(self, a, b, c): ... # actual test body This is equivalent to defining two tests: def test_something_subtest1(self): # runs test_something(1, 2, 3) def test_something_subtest2(self): # runs test_something(4, 5, 6) """ def decorator(func): func._parameterize = parameters return func return decorator class RunnerMeta(type): @classmethod def make_test(mcs, name, func, suffix, args): """ This is a helper function to create new test functions for each parameterized form. :param name: the original name of the function :param func: the original function that we are parameterizing :param suffix: the suffix to append to the name of the function for this parameterization :param args: the positional arguments to pass to the original function for this parameterization :returns: a tuple of (new_function_name, new_function_object) """ # Create the new test function. It calls the original function with the specified args. # We use @functools.wraps to copy over all the function attributes. @wraps(func) def resulting_test(self): return func(self, *args) # Add suffix to the function name so that it displays correctly. if suffix: resulting_test.__name__ = f'{name}_{suffix}' else: resulting_test.__name__ = name # On python 3, functions have __qualname__ as well. This is a full dot-separated path to the # function. We add the suffix to it as well. resulting_test.__qualname__ = f'{func.__qualname__}_{suffix}' return resulting_test.__name__, resulting_test def __new__(mcs, name, bases, attrs): # This metaclass expands parameterized methods from `attrs` into separate ones in `new_attrs`. new_attrs = {} for attr_name, value in attrs.items(): # Check if a member of the new class has _parameterize, the tag inserted by @parameterized. if hasattr(value, '_parameterize'): # If it does, we extract the parameterization information, build new test functions. for suffix, args in value._parameterize.items(): new_name, func = mcs.make_test(attr_name, value, suffix, args) assert new_name not in new_attrs, 'Duplicate attribute name generated when parameterizing %s' % attr_name new_attrs[new_name] = func else: # If not, we just copy it over to new_attrs verbatim. assert attr_name not in new_attrs, '%s collided with an attribute from parameterization' % attr_name new_attrs[attr_name] = value # We invoke type, the default metaclass, to actually create the new class, with new_attrs. return type.__new__(mcs, name, bases, new_attrs) class RunnerCore(unittest.TestCase, metaclass=RunnerMeta): # default temporary directory settings. set_temp_dir may be called later to # override these temp_dir = TEMP_DIR canonical_temp_dir = get_canonical_temp_dir(TEMP_DIR) # This avoids cluttering the test runner output, which is stderr too, with compiler warnings etc. # Change this to None to get stderr reporting, for debugging purposes stderr_redirect = STDOUT def is_wasm(self): return self.get_setting('WASM') != 0 def check_dylink(self): if self.get_setting('ALLOW_MEMORY_GROWTH') == 1 and not self.is_wasm(): self.skipTest('no dynamic linking with memory growth (without wasm)') if not self.is_wasm(): self.skipTest('no dynamic linking support in wasm2js yet') if '-fsanitize=address' in self.emcc_args: self.skipTest('no dynamic linking support in ASan yet') if '-fsanitize=leak' in self.emcc_args: self.skipTest('no dynamic linking support in LSan yet') def require_v8(self): if not config.V8_ENGINE or config.V8_ENGINE not in config.JS_ENGINES: if 'EMTEST_SKIP_V8' in os.environ: self.skipTest('test requires v8 and EMTEST_SKIP_V8 is set') else: self.fail('d8 required to run this test. Use EMTEST_SKIP_V8 to skip') self.js_engines = [config.V8_ENGINE] self.emcc_args.append('-sENVIRONMENT=shell') def require_node(self): if not config.NODE_JS or config.NODE_JS not in config.JS_ENGINES: if 'EMTEST_SKIP_NODE' in os.environ: self.skipTest('test requires node and EMTEST_SKIP_NODE is set') else: self.fail('node required to run this test. Use EMTEST_SKIP_NODE to skip') self.js_engines = [config.NODE_JS] def uses_memory_init_file(self): if self.get_setting('SIDE_MODULE') or (self.is_wasm() and not self.get_setting('WASM2JS')): return False elif '--memory-init-file' in self.emcc_args: return int(self.emcc_args[self.emcc_args.index('--memory-init-file') + 1]) else: # side modules handle memory differently; binaryen puts the memory in the wasm module opt_supports = any(opt in self.emcc_args for opt in ('-O2', '-O3', '-Os', '-Oz')) return opt_supports def set_temp_dir(self, temp_dir): self.temp_dir = temp_dir self.canonical_temp_dir = get_canonical_temp_dir(self.temp_dir) # Explicitly set dedicated temporary directory for parallel tests os.environ['EMCC_TEMP_DIR'] = self.temp_dir @classmethod def setUpClass(cls): super().setUpClass() print('(checking sanity from test runner)') # do this after we set env stuff shared.check_sanity(force=True) def setUp(self): super().setUp() self.settings_mods = {} self.emcc_args = ['-Werror'] self.node_args = ['--stack-trace-limit=50'] self.v8_args = [] self.env = {} self.temp_files_before_run = [] self.uses_es6 = False self.js_engines = config.JS_ENGINES.copy() self.wasm_engines = config.WASM_ENGINES.copy() self.banned_js_engines = [] self.use_all_engines = EMTEST_ALL_ENGINES if EMTEST_DETECT_TEMPFILE_LEAKS: for root, dirnames, filenames in os.walk(self.temp_dir): for dirname in dirnames: self.temp_files_before_run.append(os.path.normpath(os.path.join(root, dirname))) for filename in filenames: self.temp_files_before_run.append(os.path.normpath(os.path.join(root, filename))) if EMTEST_SAVE_DIR: self.working_dir = os.path.join(self.temp_dir, 'emscripten_test') if os.path.exists(self.working_dir): if EMTEST_SAVE_DIR == 2: print('Not clearing existing test directory') else: print('Clearing existing test directory') # Even when EMTEST_SAVE_DIR we still try to start with an empty directoy as many tests # expect this. EMTEST_SAVE_DIR=2 can be used to keep the old contents for the new test # run. This can be useful when iterating on a given test with extra files you want to keep # around in the output directory. delete_contents(self.working_dir) else: print('Creating new test output directory') ensure_dir(self.working_dir) else: self.working_dir = tempfile.mkdtemp(prefix='emscripten_test_' + self.__class__.__name__ + '_', dir=self.temp_dir) os.chdir(self.working_dir) if not EMTEST_SAVE_DIR: self.has_prev_ll = False for temp_file in os.listdir(TEMP_DIR): if temp_file.endswith('.ll'): self.has_prev_ll = True def tearDown(self): if not EMTEST_SAVE_DIR: # rmtree() fails on Windows if the current working directory is inside the tree. os.chdir(os.path.dirname(self.get_dir())) try_delete(self.get_dir()) if EMTEST_DETECT_TEMPFILE_LEAKS and not DEBUG: temp_files_after_run = [] for root, dirnames, filenames in os.walk(self.temp_dir): for dirname in dirnames: temp_files_after_run.append(os.path.normpath(os.path.join(root, dirname))) for filename in filenames: temp_files_after_run.append(os.path.normpath(os.path.join(root, filename))) # Our leak detection will pick up *any* new temp files in the temp dir. # They may not be due to us, but e.g. the browser when running browser # tests. Until we figure out a proper solution, ignore some temp file # names that we see on our CI infrastructure. ignorable_file_prefixes = [ '/tmp/tmpaddon', '/tmp/circleci-no-output-timeout', '/tmp/wasmer' ] left_over_files = set(temp_files_after_run) - set(self.temp_files_before_run) left_over_files = [f for f in left_over_files if not any([f.startswith(prefix) for prefix in ignorable_file_prefixes])] if len(left_over_files): print('ERROR: After running test, there are ' + str(len(left_over_files)) + ' new temporary files/directories left behind:', file=sys.stderr) for f in left_over_files: print('leaked file: ' + f, file=sys.stderr) self.fail('Test leaked ' + str(len(left_over_files)) + ' temporary files!') def get_setting(self, key, default=None): return self.settings_mods.get(key, default) def set_setting(self, key, value=1): if value is None: self.clear_setting(key) self.settings_mods[key] = value def has_changed_setting(self, key): return key in self.settings_mods def clear_setting(self, key): self.settings_mods.pop(key, None) def serialize_settings(self): ret = [] for key, value in self.settings_mods.items(): if value == 1: ret.append(f'-s{key}') elif type(value) == list: ret.append(f'-s{key}={",".join(value)}') else: ret.append(f'-s{key}={value}') return ret def get_dir(self): return self.working_dir def in_dir(self, *pathelems): return os.path.join(self.get_dir(), *pathelems) def add_pre_run(self, code): create_file('prerun.js', 'Module.preRun = function() { %s }' % code) self.emcc_args += ['--pre-js', 'prerun.js'] def add_post_run(self, code): create_file('postrun.js', 'Module.postRun = function() { %s }' % code) self.emcc_args += ['--pre-js', 'postrun.js'] def add_on_exit(self, code): create_file('onexit.js', 'Module.onExit = function() { %s }' % code) self.emcc_args += ['--pre-js', 'onexit.js'] # returns the full list of arguments to pass to emcc # param @main_file whether this is the main file of the test. some arguments # (like --pre-js) do not need to be passed when building # libraries, for example def get_emcc_args(self, main_file=False): args = self.serialize_settings() + self.emcc_args if not main_file: for i, arg in enumerate(args): if arg in ('--pre-js', '--post-js'): args[i] = None args[i + 1] = None args = [arg for arg in args if arg is not None] return args def verify_es5(self, filename): es_check = shared.get_npm_cmd('es-check') # use --quiet once its available # See: https://github.com/dollarshaveclub/es-check/pull/126/ es_check_env = os.environ.copy() es_check_env['PATH'] = os.path.dirname(config.NODE_JS[0]) + os.pathsep + es_check_env['PATH'] try: shared.run_process(es_check + ['es5', os.path.abspath(filename), '--quiet'], stderr=PIPE, env=es_check_env) except subprocess.CalledProcessError as e: print(e.stderr) self.fail('es-check failed to verify ES5 output compliance') # Build JavaScript code from source code def build(self, filename, libraries=[], includes=[], force_c=False, js_outfile=True, emcc_args=[]): suffix = '.js' if js_outfile else '.wasm' compiler = [compiler_for(filename, force_c)] if compiler[0] == EMCC: # TODO(https://github.com/emscripten-core/emscripten/issues/11121) # We link with C++ stdlibs, even when linking with emcc for historical reasons. We can remove # this if this issues is fixed. compiler.append('-nostdlib++') if force_c: compiler.append('-xc') dirname, basename = os.path.split(filename) output = shared.unsuffixed(basename) + suffix cmd = compiler + [filename, '-o', output] + self.get_emcc_args(main_file=True) + emcc_args + libraries if shared.suffix(filename) not in ('.i', '.ii'): # Add the location of the test file to include path. cmd += ['-I.'] cmd += ['-I' + str(include) for include in includes] self.run_process(cmd, stderr=self.stderr_redirect if not DEBUG else None) self.assertExists(output) if js_outfile and not self.uses_es6: self.verify_es5(output) if js_outfile and self.uses_memory_init_file(): src = read_file(output) # side memory init file, or an empty one in the js assert ('/* memory initializer */' not in src) or ('/* memory initializer */ allocate([]' in src) return output def get_func(self, src, name): start = src.index('function ' + name + '(') t = start n = 0 while True: if src[t] == '{': n += 1 elif src[t] == '}': n -= 1 if n == 0: return src[start:t + 1] t += 1 assert t < len(src) def count_funcs(self, javascript_file): num_funcs = 0 start_tok = "// EMSCRIPTEN_START_FUNCS" end_tok = "// EMSCRIPTEN_END_FUNCS" start_off = 0 end_off = 0 js = read_file(javascript_file) blob = "".join(js.splitlines()) start_off = blob.find(start_tok) + len(start_tok) end_off = blob.find(end_tok) asm_chunk = blob[start_off:end_off] num_funcs = asm_chunk.count('function ') return num_funcs def count_wasm_contents(self, wasm_binary, what): out = self.run_process([os.path.join(building.get_binaryen_bin(), 'wasm-opt'), wasm_binary, '--metrics'], stdout=PIPE).stdout # output is something like # [?] : 125 for line in out.splitlines(): if '[' + what + ']' in line: ret = line.split(':')[1].strip() return int(ret) self.fail('Failed to find [%s] in wasm-opt output' % what) def get_wasm_text(self, wasm_binary): return self.run_process([os.path.join(building.get_binaryen_bin(), 'wasm-dis'), wasm_binary], stdout=PIPE).stdout def is_exported_in_wasm(self, name, wasm): wat = self.get_wasm_text(wasm) return ('(export "%s"' % name) in wat def run_js(self, filename, engine=None, args=[], output_nicerizer=None, assert_returncode=0): # use files, as PIPE can get too full and hang us stdout = self.in_dir('stdout') stderr = self.in_dir('stderr') error = None if not engine: engine = self.js_engines[0] if engine == config.NODE_JS: engine = engine + self.node_args if engine == config.V8_ENGINE: engine = engine + self.v8_args if EMTEST_VERBOSE: print(f"Running '{filename}' under '{shared.shlex_join(engine)}'") try: jsrun.run_js(filename, engine, args, stdout=open(stdout, 'w'), stderr=open(stderr, 'w'), assert_returncode=assert_returncode) except subprocess.CalledProcessError as e: error = e # Make sure that we produced proper line endings to the .js file we are about to run. if not filename.endswith('.wasm'): self.assertEqual(line_endings.check_line_endings(filename), 0) out = read_file(stdout) err = read_file(stderr) if output_nicerizer: ret = output_nicerizer(out, err) else: ret = out + err if error or EMTEST_VERBOSE: ret = limit_size(ret) print('-- begin program output --') print(ret, end='') print('-- end program output --') if error: if assert_returncode == NON_ZERO: self.fail('JS subprocess unexpectedly succeeded (%s): Output:\n%s' % (error.cmd, ret)) else: self.fail('JS subprocess failed (%s): %s. Output:\n%s' % (error.cmd, error.returncode, ret)) # We should pass all strict mode checks self.assertNotContained('strict warning:', ret) return ret def assertExists(self, filename, msg=None): if not msg: msg = 'Expected file not found: ' + filename self.assertTrue(os.path.exists(filename), msg) def assertNotExists(self, filename, msg=None): if not msg: msg = 'Unexpected file exists: ' + filename self.assertFalse(os.path.exists(filename), msg) # Tests that the given two paths are identical, modulo path delimiters. E.g. "C:/foo" is equal to "C:\foo". def assertPathsIdentical(self, path1, path2): path1 = path1.replace('\\', '/') path2 = path2.replace('\\', '/') return self.assertIdentical(path1, path2) # Tests that the given two multiline text content are identical, modulo line # ending differences (\r\n on Windows, \n on Unix). def assertTextDataIdentical(self, text1, text2, msg=None, fromfile='expected', tofile='actual'): text1 = text1.replace('\r\n', '\n') text2 = text2.replace('\r\n', '\n') return self.assertIdentical(text1, text2, msg, fromfile, tofile) def assertIdentical(self, values, y, msg=None, fromfile='expected', tofile='actual'): if type(values) not in (list, tuple): values = [values] for x in values: if x == y: return # success diff_lines = difflib.unified_diff(x.splitlines(), y.splitlines(), fromfile=fromfile, tofile=tofile) diff = ''.join([a.rstrip() + '\n' for a in diff_lines]) if EMTEST_VERBOSE: print("Expected to have '%s' == '%s'" % (limit_size(values[0]), limit_size(y))) fail_message = 'Unexpected difference:\n' + limit_size(diff) if not EMTEST_VERBOSE: fail_message += '\nFor full output run with EMTEST_VERBOSE=1.' if msg: fail_message += '\n' + msg self.fail(fail_message) def assertTextDataContained(self, text1, text2): text1 = text1.replace('\r\n', '\n') text2 = text2.replace('\r\n', '\n') return self.assertContained(text1, text2) def assertContained(self, values, string, additional_info=''): if type(values) not in [list, tuple]: values = [values] if callable(string): string = string() if not any(v in string for v in values): diff = difflib.unified_diff(values[0].split('\n'), string.split('\n'), fromfile='expected', tofile='actual') diff = ''.join(a.rstrip() + '\n' for a in diff) self.fail("Expected to find '%s' in '%s', diff:\n\n%s\n%s" % ( limit_size(values[0]), limit_size(string), limit_size(diff), additional_info )) def assertNotContained(self, value, string): if callable(value): value = value() # lazy loading if callable(string): string = string() if value in string: self.fail("Expected to NOT find '%s' in '%s', diff:\n\n%s" % ( limit_size(value), limit_size(string), limit_size(''.join([a.rstrip() + '\n' for a in difflib.unified_diff(value.split('\n'), string.split('\n'), fromfile='expected', tofile='actual')])) )) def assertContainedIf(self, value, string, condition): if condition: self.assertContained(value, string) else: self.assertNotContained(value, string) def assertBinaryEqual(self, file1, file2): self.assertEqual(os.path.getsize(file1), os.path.getsize(file2)) self.assertEqual(read_binary(file1), read_binary(file2)) library_cache = {} def get_build_dir(self): ret = os.path.join(self.get_dir(), 'building') ensure_dir(ret) return ret def get_library(self, name, generated_libs, configure=['sh', './configure'], configure_args=[], make=['make'], make_args=None, env_init=None, cache_name_extra='', native=False): if env_init is None: env_init = {} if make_args is None: make_args = ['-j', str(shared.get_num_cores())] build_dir = self.get_build_dir() output_dir = self.get_dir() emcc_args = self.get_emcc_args() hash_input = (str(emcc_args) + ' $ ' + str(env_init)).encode('utf-8') cache_name = name + ','.join([opt for opt in emcc_args if len(opt) < 7]) + '_' + hashlib.md5(hash_input).hexdigest() + cache_name_extra valid_chars = "_%s%s" % (string.ascii_letters, string.digits) cache_name = ''.join([(c if c in valid_chars else '_') for c in cache_name]) if self.library_cache.get(cache_name): print('<load %s from cache> ' % cache_name, file=sys.stderr) generated_libs = [] for basename, contents in self.library_cache[cache_name]: bc_file = os.path.join(build_dir, cache_name + '_' + basename) with open(bc_file, 'wb') as f: f.write(contents) generated_libs.append(bc_file) return generated_libs print(f'<building and saving {cache_name} into cache>', file=sys.stderr) if configure is not None: # Avoid += so we don't mutate the default arg configure = configure + configure_args cflags = ' '.join(self.get_emcc_args()) env_init.setdefault('CFLAGS', cflags) env_init.setdefault('CXXFLAGS', cflags) return build_library(name, build_dir, output_dir, generated_libs, configure, make, make_args, self.library_cache, cache_name, env_init=env_init, native=native) def clear(self): delete_contents(self.get_dir()) if EMSCRIPTEN_TEMP_DIR: delete_contents(EMSCRIPTEN_TEMP_DIR) def run_process(self, cmd, check=True, **args): # Wrapper around shared.run_process. This is desirable so that the tests # can fail (in the unittest sense) rather than error'ing. # In the long run it would nice to completely remove the dependency on # core emscripten code (shared.py) here. try: return shared.run_process(cmd, check=check, **args) except subprocess.CalledProcessError as e: if check and e.returncode != 0: self.fail('subprocess exited with non-zero return code(%d): `%s`' % (e.returncode, shared.shlex_join(cmd))) def emcc(self, filename, args=[], output_filename=None, **kwargs): if output_filename is None: output_filename = filename + '.o' try_delete(output_filename) self.run_process([compiler_for(filename), filename] + args + ['-o', output_filename], **kwargs) # Shared test code between main suite and others def expect_fail(self, cmd, **args): """Run a subprocess and assert that it returns non-zero. Return the stderr of the subprocess. """ proc = self.run_process(cmd, check=False, stderr=PIPE, **args) self.assertNotEqual(proc.returncode, 0, 'subprocess unexpectedly succeeded. stderr:\n' + proc.stderr) # When we check for failure we expect a user-visible error, not a traceback. # However, on windows a python traceback can happen randomly sometimes, # due to "Access is denied" https://github.com/emscripten-core/emscripten/issues/718 if not WINDOWS or 'Access is denied' not in proc.stderr: self.assertNotContained('Traceback', proc.stderr) return proc.stderr # excercise dynamic linker. # # test that linking to shared library B, which is linked to A, loads A as well. # main is also linked to C, which is also linked to A. A is loaded/initialized only once. # # B # main < > A # C # # this test is used by both test_core and test_browser. # when run under broswer it excercises how dynamic linker handles concurrency # - because B and C are loaded in parallel. def _test_dylink_dso_needed(self, do_run): create_file('liba.cpp', r''' #include <stdio.h> #include <emscripten.h> static const char *afunc_prev; extern "C" { EMSCRIPTEN_KEEPALIVE void afunc(const char *s); } void afunc(const char *s) { printf("a: %s (prev: %s)\n", s, afunc_prev); afunc_prev = s; } struct ainit { ainit() { puts("a: loaded"); } }; static ainit _; ''') create_file('libb.c', r''' #include <emscripten.h> void afunc(const char *s); EMSCRIPTEN_KEEPALIVE void bfunc() { afunc("b"); } ''') create_file('libc.c', r''' #include <emscripten.h> void afunc(const char *s); EMSCRIPTEN_KEEPALIVE void cfunc() { afunc("c"); } ''') # _test_dylink_dso_needed can be potentially called several times by a test. # reset dylink-related options first. self.clear_setting('MAIN_MODULE') self.clear_setting('SIDE_MODULE') # XXX in wasm each lib load currently takes 5MB; default INITIAL_MEMORY=16MB is thus not enough self.set_setting('INITIAL_MEMORY', '32mb') so = '.wasm' if self.is_wasm() else '.js' def ccshared(src, linkto=[]): cmdv = [EMCC, src, '-o', shared.unsuffixed(src) + so, '-s', 'SIDE_MODULE'] + self.get_emcc_args() cmdv += linkto self.run_process(cmdv) ccshared('liba.cpp') ccshared('libb.c', ['liba' + so]) ccshared('libc.c', ['liba' + so]) self.set_setting('MAIN_MODULE') extra_args = ['-L.', 'libb' + so, 'libc' + so] do_run(r''' #ifdef __cplusplus extern "C" { #endif void bfunc(); void cfunc(); #ifdef __cplusplus } #endif int test_main() { bfunc(); cfunc(); return 0; } ''', 'a: loaded\na: b (prev: (null))\na: c (prev: b)\n', emcc_args=extra_args) for libname in ['liba', 'libb', 'libc']: self.emcc_args += ['--embed-file', libname + so] do_run(r''' #include <assert.h> #include <dlfcn.h> #include <stddef.h> int test_main() { void *bdso, *cdso; void (*bfunc_ptr)(), (*cfunc_ptr)(); // FIXME for RTLD_LOCAL binding symbols to loaded lib is not currently working bdso = dlopen("libb%(so)s", RTLD_NOW|RTLD_GLOBAL); assert(bdso != NULL); cdso = dlopen("libc%(so)s", RTLD_NOW|RTLD_GLOBAL); assert(cdso != NULL); bfunc_ptr = (void (*)())dlsym(bdso, "bfunc"); assert(bfunc_ptr != NULL); cfunc_ptr = (void (*)())dlsym(cdso, "cfunc"); assert(cfunc_ptr != NULL); bfunc_ptr(); cfunc_ptr(); return 0; } ''' % locals(), 'a: loaded\na: b (prev: (null))\na: c (prev: b)\n') def filtered_js_engines(self, js_engines=None): if js_engines is None: js_engines = self.js_engines for engine in js_engines: assert engine in config.JS_ENGINES, "js engine does not exist in config.JS_ENGINES" assert type(engine) == list for engine in self.banned_js_engines: assert type(engine) in (list, type(None)) banned = [b[0] for b in self.banned_js_engines if b] return [engine for engine in js_engines if engine and engine[0] not in banned] def do_run(self, src, expected_output, force_c=False, **kwargs): if 'no_build' in kwargs: filename = src else: if force_c: filename = 'src.c' else: filename = 'src.cpp' with open(filename, 'w') as f: f.write(src) self._build_and_run(filename, expected_output, **kwargs) def do_runf(self, filename, expected_output=None, **kwargs): self._build_and_run(filename, expected_output, **kwargs) ## Just like `do_run` but with filename of expected output def do_run_from_file(self, filename, expected_output_filename, **kwargs): self._build_and_run(filename, read_file(expected_output_filename), **kwargs) def do_run_in_out_file_test(self, *path, **kwargs): srcfile = test_file(*path) out_suffix = kwargs.pop('out_suffix', '') outfile = shared.unsuffixed(srcfile) + out_suffix + '.out' expected = read_file(outfile) self._build_and_run(srcfile, expected, **kwargs) ## Does a complete test - builds, runs, checks output, etc. def _build_and_run(self, filename, expected_output, args=[], output_nicerizer=None, no_build=False, js_engines=None, libraries=[], includes=[], assert_returncode=0, assert_identical=False, assert_all=False, check_for_error=True, force_c=False, emcc_args=[]): logger.debug(f'_build_and_run: {filename}') if no_build: js_file = filename else: self.build(filename, libraries=libraries, includes=includes, force_c=force_c, emcc_args=emcc_args) js_file = shared.unsuffixed(os.path.basename(filename)) + '.js' self.assertExists(js_file) engines = self.filtered_js_engines(js_engines) if len(engines) > 1 and not self.use_all_engines: engines = engines[:1] # In standalone mode, also add wasm vms as we should be able to run there too. if self.get_setting('STANDALONE_WASM'): # TODO once standalone wasm support is more stable, apply use_all_engines # like with js engines, but for now as we bring it up, test in all of them if not self.wasm_engines: logger.warning('no wasm engine was found to run the standalone part of this test') engines += self.wasm_engines if self.get_setting('WASM2C') and not EMTEST_LACKS_NATIVE_CLANG: # compile the c file to a native executable. c = shared.unsuffixed(js_file) + '.wasm.c' executable = shared.unsuffixed(js_file) + '.exe' cmd = [shared.CLANG_CC, c, '-o', executable] + clang_native.get_clang_native_args() self.run_process(cmd, env=clang_native.get_clang_native_env()) # we can now run the executable directly, without an engine, which # we indicate with None as the engine engines += [[None]] if len(engines) == 0: self.skipTest('No JS engine present to run this test with. Check %s and the paths therein.' % config.EM_CONFIG) for engine in engines: js_output = self.run_js(js_file, engine, args, output_nicerizer=output_nicerizer, assert_returncode=assert_returncode) js_output = js_output.replace('\r\n', '\n') if expected_output: try: if assert_identical: self.assertIdentical(expected_output, js_output) elif assert_all: for o in expected_output: self.assertContained(o, js_output) else: self.assertContained(expected_output, js_output) if check_for_error: self.assertNotContained('ERROR', js_output) except Exception: print('(test did not pass in JS engine: %s)' % engine) raise def get_freetype_library(self): if '-Werror' in self.emcc_args: self.emcc_args.remove('-Werror') return self.get_library(os.path.join('third_party', 'freetype'), os.path.join('objs', '.libs', 'libfreetype.a'), configure_args=['--disable-shared', '--without-zlib']) def get_poppler_library(self, env_init=None): # The fontconfig symbols are all missing from the poppler build # e.g. FcConfigSubstitute self.set_setting('ERROR_ON_UNDEFINED_SYMBOLS', 0) self.emcc_args += [ '-I' + test_file('third_party/freetype/include'), '-I' + test_file('third_party/poppler/include') ] freetype = self.get_freetype_library() # Poppler has some pretty glaring warning. Suppress them to keep the # test output readable. if '-Werror' in self.emcc_args: self.emcc_args.remove('-Werror') self.emcc_args += [ '-Wno-sentinel', '-Wno-logical-not-parentheses', '-Wno-unused-private-field', '-Wno-tautological-compare', '-Wno-unknown-pragmas', ] env_init = env_init.copy() if env_init else {} env_init['FONTCONFIG_CFLAGS'] = ' ' env_init['FONTCONFIG_LIBS'] = ' ' poppler = self.get_library( os.path.join('third_party', 'poppler'), [os.path.join('utils', 'pdftoppm.o'), os.path.join('utils', 'parseargs.o'), os.path.join('poppler', '.libs', 'libpoppler.a')], env_init=env_init, configure_args=['--disable-libjpeg', '--disable-libpng', '--disable-poppler-qt', '--disable-poppler-qt4', '--disable-cms', '--disable-cairo-output', '--disable-abiword-output', '--disable-shared']) return poppler + freetype def get_zlib_library(self): if WINDOWS: return self.get_library(os.path.join('third_party', 'zlib'), os.path.join('libz.a'), configure=['cmake', '.'], make=['cmake', '--build', '.'], make_args=[]) return self.get_library(os.path.join('third_party', 'zlib'), os.path.join('libz.a'), make_args=['libz.a']) # Run a server and a web page. When a test runs, we tell the server about it, # which tells the web page, which then opens a window with the test. Doing # it this way then allows the page to close() itself when done. def harness_server_func(in_queue, out_queue, port): class TestServerHandler(SimpleHTTPRequestHandler): # Request header handler for default do_GET() path in # SimpleHTTPRequestHandler.do_GET(self) below. def send_head(self): if self.path.endswith('.js'): path = self.translate_path(self.path) try: f = open(path, 'rb') except IOError: self.send_error(404, "File not found: " + path) return None self.send_response(200) self.send_header('Content-type', 'application/javascript') self.send_header('Connection', 'close') self.end_headers() return f else: return SimpleHTTPRequestHandler.send_head(self) # Add COOP, COEP, CORP, and no-caching headers def end_headers(self): self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Cross-Origin-Opener-Policy', 'same-origin') self.send_header('Cross-Origin-Embedder-Policy', 'require-corp') self.send_header('Cross-Origin-Resource-Policy', 'cross-origin') self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate') return SimpleHTTPRequestHandler.end_headers(self) def do_GET(self): if self.path == '/run_harness': if DEBUG: print('[server startup]') self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(read_binary(test_file('browser_harness.html'))) elif 'report_' in self.path: # the test is reporting its result. first change dir away from the # test dir, as it will be deleted now that the test is finishing, and # if we got a ping at that time, we'd return an error os.chdir(path_from_root()) # for debugging, tests may encode the result and their own url (window.location) as result|url if '|' in self.path: path, url = self.path.split('|', 1) else: path = self.path url = '?' if DEBUG: print('[server response:', path, url, ']') if out_queue.empty(): out_queue.put(path) else: # a badly-behaving test may send multiple xhrs with reported results; we just care # about the first (if we queued the others, they might be read as responses for # later tests, or maybe the test sends more than one in a racy manner). # we place 'None' in the queue here so that the outside knows something went wrong # (none is not a valid value otherwise; and we need the outside to know because if we # raise an error in here, it is just swallowed in python's webserver code - we want # the test to actually fail, which a webserver response can't do). out_queue.put(None) raise Exception('browser harness error, excessive response to server - test must be fixed! "%s"' % self.path) self.send_response(200) self.send_header('Content-type', 'text/plain') self.send_header('Cache-Control', 'no-cache, must-revalidate') self.send_header('Connection', 'close') self.send_header('Expires', '-1') self.end_headers() self.wfile.write(b'OK') elif 'stdout=' in self.path or 'stderr=' in self.path or 'exception=' in self.path: ''' To get logging to the console from browser tests, add this to print/printErr/the exception handler in src/shell.html: var xhr = new XMLHttpRequest(); xhr.open('GET', encodeURI('http://localhost:8888?stdout=' + text)); xhr.send(); ''' print('[client logging:', unquote_plus(self.path), ']') self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() elif self.path == '/check': self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() if not in_queue.empty(): # there is a new test ready to be served url, dir = in_queue.get() if DEBUG: print('[queue command:', url, dir, ']') assert in_queue.empty(), 'should not be any blockage - one test runs at a time' assert out_queue.empty(), 'the single response from the last test was read' # tell the browser to load the test self.wfile.write(b'COMMAND:' + url.encode('utf-8')) # move us to the right place to serve the files for the new test os.chdir(dir) else: # the browser must keep polling self.wfile.write(b'(wait)') else: # Use SimpleHTTPServer default file serving operation for GET. if DEBUG: print('[simple HTTP serving:', unquote_plus(self.path), ']') SimpleHTTPRequestHandler.do_GET(self) def log_request(code=0, size=0): # don't log; too noisy pass # allows streaming compilation to work SimpleHTTPRequestHandler.extensions_map['.wasm'] = 'application/wasm' httpd = HTTPServer(('localhost', port), TestServerHandler) httpd.serve_forever() # test runner will kill us class Reporting(Enum): """When running browser tests we normally automatically include support code for reporting results back to the browser. This enum allows tests to decide what type of support code they need/want. """ NONE = 0 # Include the JS helpers for reporting results JS_ONLY = 1 # Include C/C++ reporting code (REPORT_RESULT mactros) as well as JS helpers FULL = 2 class BrowserCore(RunnerCore): # note how many tests hang / do not send an output. if many of these # happen, likely something is broken and it is best to abort the test # suite early, as otherwise we will wait for the timeout on every # single test (hundreds of minutes) MAX_UNRESPONSIVE_TESTS = 10 unresponsive_tests = 0 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @staticmethod def browser_open(url): if not EMTEST_BROWSER: logger.info('Using default system browser') webbrowser.open_new(url) return browser_args = shlex.split(EMTEST_BROWSER) # If the given browser is a scalar, treat it like one of the possible types # from https://docs.python.org/2/library/webbrowser.html if len(browser_args) == 1: try: # This throws if the type of browser isn't available webbrowser.get(browser_args[0]).open_new(url) logger.info('Using Emscripten browser: %s', browser_args[0]) return except webbrowser.Error: # Ignore the exception and fallback to the custom command logic pass # Else assume the given browser is a specific program with additional # parameters and delegate to that logger.info('Using Emscripten browser: %s', str(browser_args)) subprocess.Popen(browser_args + [url]) @classmethod def setUpClass(cls): super().setUpClass() cls.also_asmjs = int(os.getenv('EMTEST_BROWSER_ALSO_ASMJS', '0')) == 1 cls.port = int(os.getenv('EMTEST_BROWSER_PORT', '8888')) if not has_browser(): return cls.browser_timeout = 60 cls.harness_in_queue = multiprocessing.Queue() cls.harness_out_queue = multiprocessing.Queue() cls.harness_server = multiprocessing.Process(target=harness_server_func, args=(cls.harness_in_queue, cls.harness_out_queue, cls.port)) cls.harness_server.start() print('[Browser harness server on process %d]' % cls.harness_server.pid) cls.browser_open('http://localhost:%s/run_harness' % cls.port) @classmethod def tearDownClass(cls): super().tearDownClass() if not has_browser(): return cls.harness_server.terminate() print('[Browser harness server terminated]') if WINDOWS: # On Windows, shutil.rmtree() in tearDown() raises this exception if we do not wait a bit: # WindowsError: [Error 32] The process cannot access the file because it is being used by another process. time.sleep(0.1) def assert_out_queue_empty(self, who): if not self.harness_out_queue.empty(): while not self.harness_out_queue.empty(): self.harness_out_queue.get() raise Exception('excessive responses from %s' % who) # @param extra_tries: how many more times to try this test, if it fails. browser tests have # many more causes of flakiness (in particular, they do not run # synchronously, so we have a timeout, which can be hit if the VM # we run on stalls temporarily), so we let each test try more than # once by default def run_browser(self, html_file, message, expectedResult=None, timeout=None, extra_tries=1): if not has_browser(): return if BrowserCore.unresponsive_tests >= BrowserCore.MAX_UNRESPONSIVE_TESTS: self.skipTest('too many unresponsive tests, skipping browser launch - check your setup!') self.assert_out_queue_empty('previous test') if DEBUG: print('[browser launch:', html_file, ']') if expectedResult is not None: try: self.harness_in_queue.put(( 'http://localhost:%s/%s' % (self.port, html_file), self.get_dir() )) received_output = False output = '[no http server activity]' start = time.time() if timeout is None: timeout = self.browser_timeout while time.time() - start < timeout: if not self.harness_out_queue.empty(): output = self.harness_out_queue.get() received_output = True break time.sleep(0.1) if not received_output: BrowserCore.unresponsive_tests += 1 print('[unresponsive tests: %d]' % BrowserCore.unresponsive_tests) if output is None: # the browser harness reported an error already, and sent a None to tell # us to also fail the test raise Exception('failing test due to browser harness error') if output.startswith('/report_result?skipped:'): self.skipTest(unquote(output[len('/report_result?skipped:'):]).strip()) else: # verify the result, and try again if we should do so output = unquote(output) try: self.assertContained(expectedResult, output) except Exception as e: if extra_tries > 0: print('[test error (see below), automatically retrying]') print(e) return self.run_browser(html_file, message, expectedResult, timeout, extra_tries - 1) else: raise e finally: time.sleep(0.1) # see comment about Windows above self.assert_out_queue_empty('this test') else: webbrowser.open_new(os.path.abspath(html_file)) print('A web browser window should have opened a page containing the results of a part of this test.') print('You need to manually look at the page to see that it works ok: ' + message) print('(sleeping for a bit to keep the directory alive for the web browser..)') time.sleep(5) print('(moving on..)') # @manually_trigger If set, we do not assume we should run the reftest when main() is done. # Instead, call doReftest() in JS yourself at the right time. def reftest(self, expected, manually_trigger=False): # make sure the pngs used here have no color correction, using e.g. # pngcrush -rem gAMA -rem cHRM -rem iCCP -rem sRGB infile outfile basename = os.path.basename(expected) shutil.copyfile(expected, os.path.join(self.get_dir(), basename)) reporting = read_file(test_file('browser_reporting.js')) with open('reftest.js', 'w') as out: out.write(''' function doReftest() { if (doReftest.done) return; doReftest.done = true; var img = new Image(); img.onload = function() { assert(img.width == Module.canvas.width, 'Invalid width: ' + Module.canvas.width + ', should be ' + img.width); assert(img.height == Module.canvas.height, 'Invalid height: ' + Module.canvas.height + ', should be ' + img.height); var canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); var expected = ctx.getImageData(0, 0, img.width, img.height).data; var actualUrl = Module.canvas.toDataURL(); var actualImage = new Image(); actualImage.onload = function() { /* document.body.appendChild(img); // for comparisons var div = document.createElement('div'); div.innerHTML = '^=expected, v=actual'; document.body.appendChild(div); document.body.appendChild(actualImage); // to grab it for creating the test reference */ var actualCanvas = document.createElement('canvas'); actualCanvas.width = actualImage.width; actualCanvas.height = actualImage.height; var actualCtx = actualCanvas.getContext('2d'); actualCtx.drawImage(actualImage, 0, 0); var actual = actualCtx.getImageData(0, 0, actualImage.width, actualImage.height).data; var total = 0; var width = img.width; var height = img.height; for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { total += Math.abs(expected[y*width*4 + x*4 + 0] - actual[y*width*4 + x*4 + 0]); total += Math.abs(expected[y*width*4 + x*4 + 1] - actual[y*width*4 + x*4 + 1]); total += Math.abs(expected[y*width*4 + x*4 + 2] - actual[y*width*4 + x*4 + 2]); } } var wrong = Math.floor(total / (img.width*img.height*3)); // floor, to allow some margin of error for antialiasing // If the main JS file is in a worker, or modularize, then we need to supply our own reporting logic. if (typeof reportResultToServer === 'undefined') { (function() { %s reportResultToServer(wrong); })(); } else { reportResultToServer(wrong); } }; actualImage.src = actualUrl; } img.src = '%s'; }; // Automatically trigger the reftest? if (!%s) { // Yes, automatically Module['postRun'] = doReftest; if (typeof WebGLClient !== 'undefined') { // trigger reftest from RAF as well, needed for workers where there is no pre|postRun on the main thread var realRAF = window.requestAnimationFrame; window.requestAnimationFrame = /** @suppress{checkTypes} */ (function(func) { realRAF(function() { func(); realRAF(doReftest); }); }); // trigger reftest from canvas render too, for workers not doing GL var realWOM = worker.onmessage; worker.onmessage = function(event) { realWOM(event); if (event.data.target === 'canvas' && event.data.op === 'render') { realRAF(doReftest); } }; } } else { // Manually trigger the reftest. // The user will call it. // Add an event loop iteration to ensure rendering, so users don't need to bother. var realDoReftest = doReftest; doReftest = function() { setTimeout(realDoReftest, 1); }; } ''' % (reporting, basename, int(manually_trigger))) def compile_btest(self, args, reporting=Reporting.FULL): # Inject support code for reporting results. This adds an include a header so testcases can # use REPORT_RESULT, and also adds a cpp file to be compiled alongside the testcase, which # contains the implementation of REPORT_RESULT (we can't just include that implementation in # the header as there may be multiple files being compiled here). args += ['-s', 'IN_TEST_HARNESS'] if reporting != Reporting.NONE: # For basic reporting we inject JS helper funtions to report result back to server. args += ['-DEMTEST_PORT_NUMBER=%d' % self.port, '--pre-js', test_file('browser_reporting.js')] if reporting == Reporting.FULL: # If C reporting (i.e. REPORT_RESULT macro) is required # also compile in report_result.cpp and forice-include report_result.h args += ['-I' + TEST_ROOT, '-include', test_file('report_result.h'), test_file('report_result.cpp')] self.run_process([EMCC] + self.get_emcc_args() + args) def btest_exit(self, filename, assert_returncode=0, *args, **kwargs): """Special case of btest that reports its result solely via exiting with a give result code. In this case we set EXIT_RUNTIME and we don't need to provide the REPORT_RESULT macro to the C code. """ self.set_setting('EXIT_RUNTIME') kwargs['reporting'] = Reporting.JS_ONLY kwargs['expected'] = 'exit:%d' % assert_returncode return self.btest(filename, *args, **kwargs) def btest(self, filename, expected=None, reference=None, reference_slack=0, manual_reference=False, post_build=None, args=None, message='.', also_proxied=False, url_suffix='', timeout=None, also_asmjs=False, manually_trigger_reftest=False, extra_tries=1, reporting=Reporting.FULL): assert expected or reference, 'a btest must either expect an output, or have a reference image' if args is None: args = [] original_args = args.copy() if not os.path.exists(filename): filename = test_file(filename) if reference: self.reference = reference expected = [str(i) for i in range(0, reference_slack + 1)] self.reftest(test_file(reference), manually_trigger=manually_trigger_reftest) if not manual_reference: args += ['--pre-js', 'reftest.js', '-s', 'GL_TESTING'] outfile = 'test.html' args += [filename, '-o', outfile] # print('all args:', args) try_delete(outfile) self.compile_btest(args, reporting=reporting) self.assertExists(outfile) if post_build: post_build() if not isinstance(expected, list): expected = [expected] self.run_browser(outfile + url_suffix, message, ['/report_result?' + e for e in expected], timeout=timeout, extra_tries=extra_tries) # Tests can opt into being run under asmjs as well if 'WASM=0' not in original_args and (also_asmjs or self.also_asmjs): print('WASM=0') self.btest(filename, expected, reference, reference_slack, manual_reference, post_build, original_args + ['-s', 'WASM=0'], message, also_proxied=False, timeout=timeout) if also_proxied: print('proxied...') if reference: assert not manual_reference manual_reference = True assert not post_build post_build = self.post_manual_reftest # run proxied self.btest(filename, expected, reference, reference_slack, manual_reference, post_build, original_args + ['--proxy-to-worker', '-s', 'GL_TESTING'], message, timeout=timeout) ################################################################################################### def build_library(name, build_dir, output_dir, generated_libs, configure, make, make_args=[], cache=None, cache_name=None, env_init={}, native=False): """Build a library and cache the result. We build the library file once and cache it for all our tests. (We cache in memory since the test directory is destroyed and recreated for each test. Note that we cache separately for different compilers). This cache is just during the test runner. There is a different concept of caching as well, see |Cache|. """ if type(generated_libs) is not list: generated_libs = [generated_libs] source_dir = test_file(name.replace('_native', '')) project_dir = Path(build_dir, name) if os.path.exists(project_dir): shutil.rmtree(project_dir) # Useful in debugging sometimes to comment this out, and two lines above shutil.copytree(source_dir, project_dir) generated_libs = [os.path.join(project_dir, lib) for lib in generated_libs] if native: env = clang_native.get_clang_native_env() else: env = os.environ.copy() env.update(env_init) if not native: # Inject emcmake, emconfigure or emmake accordingly, but only if we are # cross compiling. if configure: if configure[0] == 'cmake': configure = [EMCMAKE] + configure else: configure = [EMCONFIGURE] + configure else: make = [EMMAKE] + make if configure: try: with open(os.path.join(project_dir, 'configure_out'), 'w') as out: with open(os.path.join(project_dir, 'configure_err'), 'w') as err: stdout = out if EM_BUILD_VERBOSE < 2 else None stderr = err if EM_BUILD_VERBOSE < 1 else None shared.run_process(configure, env=env, stdout=stdout, stderr=stderr, cwd=project_dir) except subprocess.CalledProcessError: print('-- configure stdout --') print(read_file(Path(project_dir, 'configure_out'))) print('-- end configure stdout --') print('-- configure stderr --') print(read_file(Path(project_dir, 'configure_err'))) print('-- end configure stderr --') raise # if we run configure or cmake we don't then need any kind # of special env when we run make below env = None def open_make_out(mode='r'): return open(os.path.join(project_dir, 'make.out'), mode) def open_make_err(mode='r'): return open(os.path.join(project_dir, 'make.err'), mode) if EM_BUILD_VERBOSE >= 3: make_args += ['VERBOSE=1'] try: with open_make_out('w') as make_out: with open_make_err('w') as make_err: stdout = make_out if EM_BUILD_VERBOSE < 2 else None stderr = make_err if EM_BUILD_VERBOSE < 1 else None shared.run_process(make + make_args, stdout=stdout, stderr=stderr, env=env, cwd=project_dir) except subprocess.CalledProcessError: with open_make_out() as f: print('-- make stdout --') print(f.read()) print('-- end make stdout --') with open_make_err() as f: print('-- make stderr --') print(f.read()) print('-- end stderr --') raise if cache is not None: cache[cache_name] = [] for f in generated_libs: basename = os.path.basename(f) cache[cache_name].append((basename, read_binary(f))) return generated_libs
37.638822
205
0.648145
7957397709d9c058dd519f8dbbb734869b6cb252
15,433
py
Python
ndmg/scripts/ndmg_cloud.py
luochuankai-JHU/ndmg
1307cc4dbaf84e33d61b13a6f83f9bcc4e5cfad6
[ "Apache-2.0" ]
null
null
null
ndmg/scripts/ndmg_cloud.py
luochuankai-JHU/ndmg
1307cc4dbaf84e33d61b13a6f83f9bcc4e5cfad6
[ "Apache-2.0" ]
14
2018-09-12T15:02:01.000Z
2019-11-13T16:13:56.000Z
ndmg/scripts/ndmg_cloud.py
luochuankai-JHU/ndmg
1307cc4dbaf84e33d61b13a6f83f9bcc4e5cfad6
[ "Apache-2.0" ]
2
2018-10-23T21:47:09.000Z
2019-10-30T00:43:05.000Z
#!/usr/bin/env python # Copyright 2016 NeuroData (http://neurodata.io) # # 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. # # ndmg_cloud.py # Created by Greg Kiar on 2017-02-02. # Edited a ton by Alex Loftus # Email: gkiar@jhu.edu, aloftus2@jhu.edu #%% import subprocess import ast import csv import re import os import sys import json from copy import deepcopy from collections import OrderedDict from argparse import ArgumentParser import warnings import shutil import time from pathlib import Path import boto3 import ndmg import ndmg.utils as mgu from ndmg.utils.s3_utils import get_credentials, get_matching_s3_objects, s3_client participant_templ = "https://raw.githubusercontent.com/neurodata/ndmg/staging/templates/ndmg_cloud_participant.json" def batch_submit( bucket, path, jobdir, credentials=None, state="participant", debug=False, dataset=None, log=False, bg=False, modif="", reg_style="", mod_type="", ): """ Searches through an S3 bucket, gets all subject-ids, creates json files for each, submits batch jobs, and returns list of job ids to query status upon later. """ print(("Getting list from s3://{}/{}/...".format(bucket, path))) threads = crawl_bucket(bucket, path, jobdir) print("Generating job for each subject...") jobs = create_json( bucket, path, threads, jobdir, credentials, debug, dataset, bg, modif=modif, reg_style=reg_style, ) print("Submitting jobs to the queue...") ids = submit_jobs(jobs, jobdir) def crawl_bucket(bucket, path, jobdir): """ Gets subject list for a given S3 bucket and path """ # if jobdir has seshs info file in it, use that instead sesh_path = "{}/seshs.json".format(jobdir) if os.path.isfile(sesh_path): print("seshs.json found -- loading bucket info from there") with open(sesh_path, "r") as f: seshs = json.load(f) print("Information obtained from s3.") return seshs subj_pattern = r"(?<=sub-)(\w*)(?=/ses)" sesh_pattern = r"(?<=ses-)(\d*)" all_subfiles = get_matching_s3_objects(bucket, path + "/sub-") subjs = list(set(re.findall(subj_pattern, obj)[0] for obj in all_subfiles)) # cmd = "aws s3 ls s3://{}/{}/".format(bucket, path) # try: # ACCESS, SECRET = get_credentials() # os.environ["AWS_ACCESS_KEY_ID"] = ACCESS # os.environ["AWS_SECRET_ACCESS_KEY"] = SECRET # except: # cmd += " --no-sign-request" # out = subprocess.check_output(cmd, shell=True) # pattern = r"(?<=sub-)(\w*)(?=/ses)" # subjs = re.findall(pattern, out.decode("utf-8")) # cmd = "aws s3 ls s3://{}/{}/sub-{}/" # if not ACCESS: # cmd += " --no-sign-request" seshs = OrderedDict() # TODO : use boto3 for this. for subj in subjs: prefix = path + "/sub-{}/".format(subj) all_seshfiles = get_matching_s3_objects(bucket, prefix) sesh = list(set([re.findall(sesh_pattern, obj)[0] for obj in all_seshfiles])) # cmd = cmd.format(bucket, path, subj) # out = subprocess.check_output(cmd, shell=True) # TODO: get this information outside of a loop # sesh = re.findall("ses-(.+)/", out.decode("utf-8")) if sesh != []: seshs[subj] = sesh print("{} added to seshs.".format(subj)) else: seshs[subj] = None print("{} not added (no sessions).".format(subj)) # seshs[subj] = sesh if sesh != [] else [None] print( ( "Session IDs: " + ", ".join( [ subj + "-" + sesh if sesh is not None else subj for subj in subjs for sesh in seshs[subj] ] ) ) ) with open(sesh_path, "w") as f: json.dump(seshs, f) print("{} created.".format(sesh_path)) print("Information obtained from s3.") return seshs def create_json( bucket, path, threads, jobdir, credentials=None, debug=False, dataset=None, bg=False, modif="", reg_style="", mod_type="", ): """ Takes parameters to make jsons """ jobsjson = "{}/jobs.json".format(jobdir) if os.path.isfile(jobsjson): with open(jobsjson, "r") as f: jobs = json.load(f) return jobs # set up infrastructure out = subprocess.check_output("mkdir -p {}".format(jobdir), shell=True) out = subprocess.check_output("mkdir -p {}/jobs/".format(jobdir), shell=True) out = subprocess.check_output("mkdir -p {}/ids/".format(jobdir), shell=True) template = participant_templ seshs = threads # make template if not os.path.isfile("{}/{}".format(jobdir, template.split("/")[-1])): cmd = "wget --quiet -P {} {}".format(jobdir, template) subprocess.check_output(cmd, shell=True) with open("{}/{}".format(jobdir, template.split("/")[-1]), "r") as inf: template = json.load(inf) cmd = template["containerOverrides"]["command"] env = template["containerOverrides"]["environment"] # TODO : This checks for any credentials csv file, rather than `/.aws/credentials`. # modify template if credentials is not None: env[0]["value"], env[1]["value"] = get_credentials() else: env = [] template["containerOverrides"]["environment"] = env # edit non-defaults jobs = [] cmd[cmd.index("<BUCKET>")] = bucket cmd[cmd.index("<PATH>")] = path # edit defaults if necessary if reg_style: cmd[cmd.index("--sp") + 1] = reg_style if mod_type: cmd[cmd.index("--mod") + 1] = reg_style if bg: cmd.append("--big") if modif: cmd.insert(cmd.index("--push_data") + 1, u"--modif") cmd.insert(cmd.index("--push_data") + 2, modif) # edit participant-specific values () # loop over every session of every participant for subj in seshs.keys(): print("... Generating job for sub-{}".format(subj)) # and for each subject number in each participant number, for sesh in seshs[subj]: # add format-specific commands, job_cmd = deepcopy(cmd) job_cmd[job_cmd.index("<SUBJ>")] = subj if sesh is not None: job_cmd.insert(7, u"--session_label") job_cmd.insert(8, u"{}".format(sesh)) if debug: job_cmd += [u"--debug"] # then, grab the template, # add additional parameters, # make the json file for this iteration, # and add the path to its json file to `jobs`. job_json = deepcopy(template) ver = ndmg.VERSION.replace(".", "-") if dataset: name = "ndmg_{}_{}_sub-{}".format(ver, dataset, subj) else: name = "ndmg_{}_sub-{}".format(ver, subj) if sesh is not None: name = "{}_ses-{}".format(name, sesh) print(job_cmd) job_json["jobName"] = name job_json["containerOverrides"]["command"] = job_cmd job = os.path.join(jobdir, "jobs", name + ".json") with open(job, "w") as outfile: json.dump(job_json, outfile) jobs += [job] # return list of job jsons with open(jobsjson, "w") as f: json.dump(jobs, f) return jobs def submit_jobs(jobs, jobdir): """ Give list of jobs to submit, submits them to AWS Batch """ batch = s3_client(service="batch") cmd_template = "--cli-input-json file://{}" # cmd_template = batch.submit_jobs for job in jobs: # use this to start wherever # if jobs.index(job) >= jobs.index('/jobs/jobs/ndmg_0-1-2_SWU4_sub-0025768_ses-1.json'): with open(job, "r") as f: kwargs = json.load(f) print(("... Submitting job {}...".format(job))) submission = batch.submit_job(**kwargs) # out = subprocess.check_output(cmd, shell=True) # time.sleep(0.1) # jobs sometimes hang, seeing if this helps # submission = ast.literal_eval(out.decode("utf-8")) print( ( "Job Name: {}, Job ID: {}".format( submission["jobName"], submission["jobId"] ) ) ) sub_file = os.path.join(jobdir, "ids", submission["jobName"] + ".json") with open(sub_file, "w") as outfile: json.dump(submission, outfile) print("Submitted.") return 0 def get_status(jobdir, jobid=None): """ Given list of jobs, returns status of each. """ cmd_template = "aws batch describe-jobs --jobs {}" if jobid is None: print(("Describing jobs in {}/ids/...".format(jobdir))) jobs = os.listdir(jobdir + "/ids/") for job in jobs: with open("{}/ids/{}".format(jobdir, job), "r") as inf: submission = json.load(inf) cmd = cmd_template.format(submission["jobId"]) print(("... Checking job {}...".format(submission["jobName"]))) out = subprocess.check_output(cmd, shell=True) status = re.findall('"status": "([A-Za-z]+)",', out.decode("utf-8"))[0] print(("... ... Status: {}".format(status))) return 0 else: print(("Describing job id {}...".format(jobid))) cmd = cmd_template.format(jobid) out = subprocess.check_output(cmd, shell=True) status = re.findall('"status": "([A-Za-z]+)",', out.decode("utf-8"))[0] print(("... Status: {}".format(status))) return status def kill_jobs(jobdir, reason='"Killing job"'): """ Given a list of jobs, kills them all. """ cmd_template1 = "aws batch cancel-job --job-id {} --reason {}" cmd_template2 = "aws batch terminate-job --job-id {} --reason {}" print(("Canelling/Terminating jobs in {}/ids/...".format(jobdir))) jobs = os.listdir(jobdir + "/ids/") batch = s3_client(service="batch") jids = [] names = [] # grab info about all the jobs for job in jobs: with open("{}/ids/{}".format(jobdir, job), "r") as inf: submission = json.load(inf) jid = submission["jobId"] name = submission["jobName"] jids.append(jid) names.append(name) for jid in jids: print("Terminating job {}".format(jid)) batch.terminate_job(jobId=jid, reason=reason) # status = get_status(jobdir, jid) # if status in ["SUCCEEDED", "FAILED"]: # print(("... No action needed for {}...".format(name))) # elif status in ["SUBMITTED", "PENDING", "RUNNABLE"]: # cmd = cmd_template1.format(jid, reason) # print(("... Cancelling job {}...".format(name))) # out = subprocess.check_output(cmd, shell=True) # elif status in ["STARTING", "RUNNING"]: # cmd = cmd_template2.format(jid, reason) # print(("... Terminating job {}...".format(name))) # out = subprocess.check_output(cmd, shell=True) # else: # print("... Unknown status??") #%% def main(): parser = ArgumentParser( description="This is a pipeline for running BIDs-formatted diffusion MRI datasets through AWS S3 to produce connectomes." ) parser.add_argument( "state", choices=["participant", "status", "kill"], default="participant", help="determines the function to be performed by " "this function.", ) parser.add_argument( "--bucket", help="The S3 bucket with the input dataset" " formatted according to the BIDS standard.", ) parser.add_argument( "--bidsdir", help="The directory where the dataset" " lives on the S3 bucket should be stored. If you" " level analysis this folder should be prepopulated" " with the results of the participant level analysis.", ) parser.add_argument( "--jobdir", action="store", help="Dir of batch jobs to" " generate/check up on." ) parser.add_argument( "--credentials", action="store", help="AWS formatted" " csv of credentials." ) parser.add_argument( "--log", action="store_true", help="flag to indicate" " log plotting in group analysis.", default=False, ) parser.add_argument( "--debug", action="store_true", help="flag to store " "temp files along the path of processing.", default=False, ) parser.add_argument("--dataset", action="store", help="Dataset name") parser.add_argument( "-b", "--big", action="store", default="False", help="whether or not to produce voxelwise big graph", ) parser.add_argument( "--modif", action="store", help="Name of folder on s3 to push to. If empty, push to a folder with ndmg's version number.", default="", ) parser.add_argument( "--sp", action="store", help="Space for tractography. Default is native.", default="native", ) parser.add_argument( "--mod", action="store", help="Determinstic (det) or probabilistic (prob) tracking. Default is det.", default="det", ) result = parser.parse_args() bucket = result.bucket path = result.bidsdir path = path.strip("/") if path is not None else path debug = result.debug state = result.state creds = result.credentials jobdir = result.jobdir dset = result.dataset log = result.log bg = result.big != "False" modif = result.modif reg_style = result.sp mod_type = result.mod if jobdir is None: jobdir = "./" if (bucket is None or path is None) and (state != "status" and state != "kill"): sys.exit( "Requires either path to bucket and data, or the status flag" " and job IDs to query.\n Try:\n ndmg_cloud --help" ) if state == "status": print("Checking job status...") get_status(jobdir) elif state == "kill": print("Killing jobs...") kill_jobs(jobdir) elif state == "participant": print("Beginning batch submission process...") if not os.path.exists(jobdir): print("job directory not found. Creating...") Path(jobdir).mkdir(parents=True) batch_submit( bucket, path, jobdir, creds, state, debug, dset, log, bg, modif=modif, reg_style=reg_style, mod_type=mod_type, ) sys.exit(0) if __name__ == "__main__": main()
31.952381
129
0.57403
79573a8bb6e9d2c63db90cbe052b63d2b566ce22
644
py
Python
basics/lamdaFunctions.py
pktippa/python-basics
329f048dc312cc2bcc308934142b0aa766d77307
[ "MIT" ]
1
2018-02-01T10:07:18.000Z
2018-02-01T10:07:18.000Z
basics/lamdaFunctions.py
pktippa/python-basics
329f048dc312cc2bcc308934142b0aa766d77307
[ "MIT" ]
1
2018-10-02T12:27:41.000Z
2018-10-02T12:27:41.000Z
basics/lamdaFunctions.py
pktippa/python-basics
329f048dc312cc2bcc308934142b0aa766d77307
[ "MIT" ]
1
2018-10-02T02:20:36.000Z
2018-10-02T02:20:36.000Z
# Lambdas are functions without names, in other words they are anonymous functions. # They take inputs and return outputs but do not have a name. # They are shortcuts to create simple temporary functions. # Like functions Lambda expressions cannot have multiple statements h = lambda x: x >40 and x< 50 print(h(45)) print(h(20)) def sum_all(function, data): result_sum=0; for w in data: if(function(w)): result_sum = result_sum+ w return result_sum Q=[1,3,4,5,6,7,8,9,10,15,20] p = lambda x:x q = lambda x : x%2 == 0 r = lambda x : x%3 == 0 print(sum_all(p,Q)) print(sum_all(q,Q)) print(sum_all(r,Q))
23
84
0.67236
79573ab752bf0bd702a6a0cc7878acb3c5efd9d6
1,280
py
Python
wsdetect/settings.py
Marcnuth/white-screenshot-detection
8ff75d8e2b91eeed499d232a5967c1e6c20fd6b5
[ "Apache-2.0" ]
null
null
null
wsdetect/settings.py
Marcnuth/white-screenshot-detection
8ff75d8e2b91eeed499d232a5967c1e6c20fd6b5
[ "Apache-2.0" ]
null
null
null
wsdetect/settings.py
Marcnuth/white-screenshot-detection
8ff75d8e2b91eeed499d232a5967c1e6c20fd6b5
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python3 # coding=utf-8 import os from pathlib import Path import logging from logging.config import dictConfig # Constant directory & files DIR_BASE = Path(os.path.dirname(os.path.realpath(__file__))).parent RESOURCE_DIR = DIR_BASE / 'resources' LOGGING_FILE = Path('/tmp/wsdetect.log') # Logging dictConfig({ "version": 1, "disable_existing_loggers": False, "formatters": { "basic": { "format" : "[%(asctime)s] [%(process)d:%(thread)d] [%(levelname)s] [%(name)s] %(filename)s:%(funcName)s:%(lineno)d %(message)s", "datefmt" : "%Y-%m-%d %H:%M:%S" } }, "handlers": { "wsdetect": { "level": "INFO", "class": "logging.handlers.TimedRotatingFileHandler", "filename": LOGGING_FILE.absolute().as_posix(), "formatter": "basic", "encoding": "utf-8", "when": "midnight", "interval": 1, "backupCount": 7 }, }, "loggers": { "wsdetect" : { "handlers" : ["wsdetect"], "propagate": "true", "level" : "INFO" } } }) logger = logging.getLogger(__name__) logger.info('wsdetect logs will be output in dir:%s', LOGGING_FILE.absolute().as_posix())
28.444444
141
0.551563
79573b7933fdcae7c9793ef1e76eb9002290e3cd
12,791
py
Python
src/unit_parse/core.py
dylanwal/unit_parse
07a74d43b9f161bd7ad6ef12ab0f362f1bf6a90d
[ "BSD-3-Clause" ]
1
2022-01-29T17:14:40.000Z
2022-01-29T17:14:40.000Z
src/unit_parse/core.py
dylanwal/unit_parse
07a74d43b9f161bd7ad6ef12ab0f362f1bf6a90d
[ "BSD-3-Clause" ]
null
null
null
src/unit_parse/core.py
dylanwal/unit_parse
07a74d43b9f161bd7ad6ef12ab0f362f1bf6a90d
[ "BSD-3-Clause" ]
null
null
null
""" Core This code does the heavy lifting of turning strings into Quantities. Its the functions that need to deal with the most mess. """ from typing import List, Union import re from unit_parse.config import Unit, Quantity, config from unit_parse.pre_processing_substitution import sub_general from unit_parse.utils import flatten_list, contains_number, sig_figs, remove_empty_str, split_list from unit_parse.logger import log_debug, log_info, logger @log_info def text_list_to_quantity(text_list: Union[list[list[str]], list[str]]) -> list[Quantity]: """ text list to quantity Entry point for quantity parsing. It just loops through text_list and directs text to the quantity parsing. Parameters ---------- text_list: list[list[str]], list[str] pre-parsed text list Returns ------- Quantity: list[list[Quantity]], list[Quantity] """ text_list = last_minute_sub(text_list) out = [] for text in text_list: if len(text) == 1: result = get_quantity(text[0]) else: result = get_quantity_and_cond(text) if result is not None: out.append(result) return out @log_debug def last_minute_sub(text_list: Union[list[list[str]], list[str]]) -> Union[list[list[str]], list[str]]: for i, obj in enumerate(text_list): if isinstance(obj, list): for ii, text in enumerate(obj): text_list[i][ii] = sub_general(text, config.last_minute_sub) else: text_list[i] = sub_general(obj, config.last_minute_sub) return text_list @log_debug def get_quantity_and_cond(text_list: list[str]) -> Union[Quantity, list[Quantity], None]: """ get quantity and condition Deals with a list[str] that should be a single quantity or two quantities. Parameters ---------- text_list: list[str] Returns ------- quantity: Quantity, list[Quantity], None """ out = [] for text in text_list: result = try_to_convert(text) if result is None: logger.warning(f"Text ignored: '{text}' in '{' '.join(text_list)}'") else: out.append(result) out = reduce_list(out) return out def try_to_convert(text: str) -> Union[float, Unit, Quantity, None]: """ try to convert Try to turn string into a number, unit, quantity in that order. If all fails try complex parsing. Parameters ---------- text: str Returns ------- out: float, Unit, Quantity, None """ try: return float(text) except Exception: pass try: return Unit(text) except Exception: pass try: return Quantity(text) except Exception: pass return get_quantity(text) def reduce_list(obj_list: list[Union[str, int, float, Unit, Quantity]]) -> list[Union[str, Unit, Quantity]]: """ Reduce a list of value, int, Unit, Quantity and "/" to a single or multiple quantities. Parameters ---------- obj_list: list[Union[str, int, float, Unit, Quantity]] Returns ------- out: list[Union[str, Unit, Quantity]] """ # guard statement if len(obj_list) <= 1: return obj_list types_ = [type(obj) for obj in obj_list] out = [obj_list[0]] for t, obj in zip(types_[1:], obj_list[1:]): if type(out[-1]) in (int, float, Quantity) and t is Unit: out[-1] = out[-1] * obj else: out.append(obj) return out @log_debug def get_quantity(text_in: str) -> Union[Quantity, None]: """ get quantity Attempt to create Quantity from string. Parameters ---------- text_in: str Returns ------- quantity: quantity, None If unsuccessful return None """ if not contains_number(text_in): return None try: # let pint give it an attempt return Quantity(text_in) except Exception: # if Pint can't do it try our custom method return to_quantity_expanded(text_in) def to_quantity_expanded(text_in: str) -> Union[Quantity, None]: """ to quantity expanded Attempt to create Quantity from string stepwise process. Get value followed by get unit. Parameters ---------- text_in: str Returns ------- quantity: quantity, None If unsuccessful return None """ value, text_value = get_value(text_in) if value is None: logger.warning(f"No value found: '{text_in}'") return None unit = get_unit(text_in.replace(text_value, "")) if unit is None: logger.warning(f"No unit found: '{text_in}' (value found: '{value})'") return None return value * unit @log_debug def get_value(text_in: str) -> tuple[Union[float, int, None], str]: """ get value Extracts value out of string. Value must be at the start of string. Parameters ---------- text_in Returns ------- value: float or int The value extracted value_text: str The text corresponding to the value. Examples -------- "42.3 gcm-3" --> (42.3, '42.3') """ try: result = re.findall('^[-]?[0-9.]+[*]?[0-9.]*[*]{0,2}[-]?[0-9.]*', text_in.lstrip())[0] return sig_figs(eval(result, {'__builtins__': None}), sig_digit=15), result except IndexError: return None, "" @log_debug def get_unit(text_in: str) -> Unit: """ get unit Attempts to turn string into unit Parameters ---------- text_in Returns ------- """ if text_in is None or text_in == "": return None # pre-process unit chunk text_in = text_in.strip() split_text = split_on_powers(text_in) split_text = split_on_multiplication_symbol(split_text) split_text = split_on_division_symbol(split_text) # check if the pre-processing was enough to get a unit if all([isinstance(text, Unit) or text == "/" for text in split_text]): return merge_split_text(split_text) # dealing with messed up units split_text = split_list(split_text, " ", maxsplit=10) split_text = remove_empty_str(split_text) reduced_list = [] for obj in split_text: if isinstance(obj, str) and obj != "/": result = frame_shift(obj) if result is None: logger.warning(f"Parsing unit warning: skipped text: '{obj}' in '{text_in}'") else: reduced_list.append(result) else: reduced_list.append(obj) return merge_split_text(reduced_list) def split_on_powers(text_in: Union[str, list[str]]) -> List[Union[str, Unit]]: """ Splits text up into a list of strings based on ** locations. Parameters ---------- text_in Returns ------- Examples -------- "g**2cm**-3" --> [Unit("g**2"), Unit("cm**-3")] """ if isinstance(text_in, str): text_in = [text_in] for i, text in enumerate(text_in): if isinstance(text, str) and "**" in text: out = re.split("([a-zA-Z]+[ ]?[*]{2}[ ]?[-+]?[0-9]+)", text, maxsplit=1) try: # splits into 3 chunks, middle chunk may be a valid unit out[1] = Unit(out[1]) except Exception: pass if "**" in out[2]: last_term = out.pop(2) out += split_on_powers(last_term) text_in[i] = out return remove_empty_str(flatten_list(text_in)) def split_on_multiplication_symbol(text_in: Union[str, list[str], list[Union[str, Unit]]]) -> \ Union[List[Union[str, Unit]], None]: """ Splits text up into a list of strings based on * Parameters ---------- text_in Returns ------- Examples -------- "g*cm" --> [Unit("g"), Unit("cm")] """ if isinstance(text_in, str): text_in = [text_in] for i, text in enumerate(text_in): if isinstance(text, str) and "*" in text: new_splits = re.split("([^*]+)[ ]?[*][ ]?([^*-0-9].*)", text) if len(new_splits) > 1: new_splits = [chunk for chunk in new_splits if chunk != ""] for ii, split in enumerate(new_splits): try: new_splits[ii] = Unit(split) continue except Exception: pass if bool(re.match("([^*]+)[ ]?[*][ ]?([^*-0-9].*)", split)): new_splits[ii] = split_on_multiplication_symbol(split) # pragma: no cover recursive text_in[i] = new_splits continue else: if text[-1].strip() == "*": if not bool(re.match(".*[a-zA-Z]+", text)): return [] try: text_in[i] = Unit(text[:-1]) continue except Exception: text_in[i] = text[:-1] return flatten_list(text_in) def split_on_division_symbol(text_in: Union[str, list[str]]) -> List[str]: """ Splits text up into a list of strings based on / Parameters ---------- text_in Returns ------- """ if isinstance(text_in, str): text_in = [text_in] for i, text in enumerate(text_in): if isinstance(text, str) and "/" in text: new_splits = re.split("([/])", text) if len(new_splits) > 1: new_splits = [chunk for chunk in new_splits if chunk != ""] for ii, split in enumerate(new_splits): try: new_splits[ii] = Unit(split) continue except Exception: pass text_in[i] = new_splits continue return remove_empty_str(flatten_list(text_in)) def merge_split_text(obj_list: List[Union[str, Unit]]) -> Union[Unit, None]: """ Turns list[Unit] and "/" into a single Unit Parameters ---------- obj_list Returns ------- """ unit: Unit = None buffer: Unit = None for obj in obj_list: if isinstance(obj, Unit): if buffer is None: buffer = obj else: # do multiplication buffer = buffer * obj elif obj == "/": if unit is None: unit = buffer else: unit = unit / buffer buffer = None if buffer is not None: if unit is None: unit = buffer else: unit = unit / buffer return unit @log_debug def frame_shift(text_in: str) -> Unit: """ Warning: "/" should not be in text """ _frame_dict = {} for set_size in range(1, 9): for i in range(len(text_in)): upper_bound = i + set_size if upper_bound > len(text_in): break text = text_in[i: i + set_size] try: unit_ = Unit(text) _frame_dict[text] = { "set_size": set_size, "unit": unit_, "bounds": [i, i + set_size] } except Exception: pass if _frame_dict == {}: return None replace = {} for i in range(10): # get max frame max_value = 0 max_key = "" for k, v in _frame_dict.items(): if v["set_size"] > max_value: max_value = v["set_size"] max_key = k replace[max_key] = _frame_dict.pop(max_key) remove_keys = [] for k, v in _frame_dict.items(): if replace[max_key]["bounds"][0] <= v["bounds"][0] < replace[max_key]["bounds"][1] or \ replace[max_key]["bounds"][0] < v["bounds"][1] <= replace[max_key]["bounds"][1]: remove_keys.append(k) for k in remove_keys: _frame_dict.pop(k) if not _frame_dict: break # dictionary is empty # Taking "replace" and "text in" and merging count_list = list(range(0, len(text_in), 1)) compile_list = [] for i in range(0, len(text_in)): int_ = count_list[0] for v in replace.values(): if v["bounds"][0] <= int_ < v["bounds"][1]: compile_list.append(v["unit"]) remove_num = range(v["bounds"][0], v["bounds"][1]) for num in remove_num: count_list.remove(num) if not count_list: break else: return None out = compile_list[0] for i in compile_list[1:]: out = out * i return out
25.179134
113
0.543898
79573c6177847546cbaea38eefe03f75023b7ecc
16,266
py
Python
exe/portable-python/App/Lib/email/_parseaddr.py
jaredmusil/iawsc-data-toolbox
65b97d45e13813935017f8b3c5726784027b065f
[ "MIT" ]
null
null
null
exe/portable-python/App/Lib/email/_parseaddr.py
jaredmusil/iawsc-data-toolbox
65b97d45e13813935017f8b3c5726784027b065f
[ "MIT" ]
1
2018-04-15T22:59:15.000Z
2018-04-15T22:59:15.000Z
exe/portable-python/App/Lib/email/_parseaddr.py
jaredmusil/iawsc-data-toolbox
65b97d45e13813935017f8b3c5726784027b065f
[ "MIT" ]
null
null
null
# Copyright (C) 2002-2007 Python Software Foundation # Contact: email-sig@python.org """Email address parsing code. Lifted directly from rfc822.py. This should eventually be rewritten. """ __all__ = [ 'mktime_tz', 'parsedate', 'parsedate_tz', 'quote', ] import time, calendar SPACE = ' ' EMPTYSTRING = '' COMMASPACE = ', ' # Parse a date field _monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] _daynames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] # The timezone table does not include the military time zones defined # in RFC822, other than Z. According to RFC1123, the description in # RFC822 gets the signs wrong, so we can't rely on any such time # zones. RFC1123 recommends that numeric timezone indicators be used # instead of timezone names. _timezones = {'UT':0, 'UTC':0, 'GMT':0, 'Z':0, 'AST': -400, 'ADT': -300, # Atlantic (used in Canada) 'EST': -500, 'EDT': -400, # Eastern 'CST': -600, 'CDT': -500, # Central 'MST': -700, 'MDT': -600, # Mountain 'PST': -800, 'PDT': -700 # Pacific } def parsedate_tz(data): """Convert a date string to a time tuple. Accounts for military timezones. """ data = data.split() # The FWS after the comma after the day-of-week is optional, so search and # adjust for this. if data[0].endswith(',') or data[0].lower() in _daynames: # There's a dayname here. Skip it del data[0] else: i = data[0].rfind(',') if i >= 0: data[0] = data[0][i+1:] if len(data) == 3: # RFC 850 date, deprecated stuff = data[0].split('-') if len(stuff) == 3: data = stuff + data[1:] if len(data) == 4: s = data[3] i = s.find('+') if i == -1: i = s.find('-') if i > 0: data[3:] = [s[:i], s[i:]] else: data.append('') # Dummy tz if len(data) < 5: return None data = data[:5] [dd, mm, yy, tm, tz] = data mm = mm.lower() if mm not in _monthnames: dd, mm = mm, dd.lower() if mm not in _monthnames: return None mm = _monthnames.index(mm) + 1 if mm > 12: mm -= 12 if dd[-1] == ',': dd = dd[:-1] i = yy.find(':') if i > 0: yy, tm = tm, yy if yy[-1] == ',': yy = yy[:-1] if not yy[0].isdigit(): yy, tz = tz, yy if tm[-1] == ',': tm = tm[:-1] tm = tm.split(':') if len(tm) == 2: [thh, tmm] = tm tss = '0' elif len(tm) == 3: [thh, tmm, tss] = tm else: return None try: yy = int(yy) dd = int(dd) thh = int(thh) tmm = int(tmm) tss = int(tss) except ValueError: return None # Check for a yy specified in two-digit format, then convert it to the # appropriate four-digit format, according to the POSIX standard. RFC 822 # calls for a two-digit yy, but RFC 2822 (which obsoletes RFC 822) # mandates a 4-digit yy. For more information, see the documentation for # the time module. if yy < 100: # The year is between 1969 and 1999 (inclusive). if yy > 68: yy += 1900 # The year is between 2000 and 2068 (inclusive). else: yy += 2000 tzoffset = None tz = tz.upper() if tz in _timezones: tzoffset = _timezones[tz] else: try: tzoffset = int(tz) except ValueError: pass # Convert a timezone offset into seconds ; -0500 -> -18000 if tzoffset: if tzoffset < 0: tzsign = -1 tzoffset = -tzoffset else: tzsign = 1 tzoffset = tzsign * ( (tzoffset//100)*3600 + (tzoffset % 100)*60) # Daylight Saving Time flag is set to -1, since DST is unknown. return yy, mm, dd, thh, tmm, tss, 0, 1, -1, tzoffset def parsedate(data): """Convert a time string to a time tuple.""" t = parsedate_tz(data) if isinstance(t, tuple): return t[:9] else: return t def mktime_tz(data): """Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.""" if data[9] is None: # No zone info, so localtime is better assumption than GMT return time.mktime(data[:8] + (-1,)) else: t = calendar.timegm(data) return t - data[9] def quote(str): """Prepare string to be used in a quoted string. Turns backslash and double quote characters into quoted pairs. These are the only characters that need to be quoted inside a quoted string. Does not add the surrounding double quotes. """ return str.replace('\\', '\\\\').replace('"', '\\"') class AddrlistClass: """Address parser class by Ben Escoto. To understand what this class does, it helps to have a copy of RFC 2822 in front of you. Note: this class interface is deprecated and may be removed in the future. Use email.utils.AddressList instead. """ def __init__(self, field): """Initialize a new instance. `field' is an unparsed address header field, containing one or more addresses. """ self.specials = '()<>@,:;.\"[]' self.pos = 0 self.LWS = ' \t' self.CR = '\r\n' self.FWS = self.LWS + self.CR self.atomends = self.specials + self.LWS + self.CR # Note that RFC 2822 now specifies `.' as obs-phrase, meaning that it # is obsolete syntax. RFC 2822 requires that we recognize obsolete # syntax, so allow dots in phrases. self.phraseends = self.atomends.replace('.', '') self.field = field self.commentlist = [] def gotonext(self): """Skip white space and extract comments.""" wslist = [] while self.pos < len(self.field): if self.field[self.pos] in self.LWS + '\n\r': if self.field[self.pos] not in '\n\r': wslist.append(self.field[self.pos]) self.pos += 1 elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) else: break return EMPTYSTRING.join(wslist) def getaddrlist(self): """Parse all addresses. Returns a list containing all of the addresses. """ result = [] while self.pos < len(self.field): ad = self.getaddress() if ad: result += ad else: result.append(('', '')) return result def getaddress(self): """Parse the next address.""" self.commentlist = [] self.gotonext() oldpos = self.pos oldcl = self.commentlist plist = self.getphraselist() self.gotonext() returnlist = [] if self.pos >= len(self.field): # Bad email address technically, no domain. if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in '.@': # email address is just an addrspec # this isn't very efficient since we start over self.pos = oldpos self.commentlist = oldcl addrspec = self.getaddrspec() returnlist = [(SPACE.join(self.commentlist), addrspec)] elif self.field[self.pos] == ':': # address is a group returnlist = [] fieldlen = len(self.field) self.pos += 1 while self.pos < len(self.field): self.gotonext() if self.pos < fieldlen and self.field[self.pos] == ';': self.pos += 1 break returnlist = returnlist + self.getaddress() elif self.field[self.pos] == '<': # Address is a phrase then a route addr routeaddr = self.getrouteaddr() if self.commentlist: returnlist = [(SPACE.join(plist) + ' (' + ' '.join(self.commentlist) + ')', routeaddr)] else: returnlist = [(SPACE.join(plist), routeaddr)] else: if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in self.specials: self.pos += 1 self.gotonext() if self.pos < len(self.field) and self.field[self.pos] == ',': self.pos += 1 return returnlist def getrouteaddr(self): """Parse a route address (Return-path value). This method just skips all the route stuff and returns the addrspec. """ if self.field[self.pos] != '<': return expectroute = False self.pos += 1 self.gotonext() adlist = '' while self.pos < len(self.field): if expectroute: self.getdomain() expectroute = False elif self.field[self.pos] == '>': self.pos += 1 break elif self.field[self.pos] == '@': self.pos += 1 expectroute = True elif self.field[self.pos] == ':': self.pos += 1 else: adlist = self.getaddrspec() self.pos += 1 break self.gotonext() return adlist def getaddrspec(self): """Parse an RFC 2822 addr-spec.""" aslist = [] self.gotonext() while self.pos < len(self.field): preserve_ws = True if self.field[self.pos] == '.': if aslist and not aslist[-1].strip(): aslist.pop() aslist.append('.') self.pos += 1 preserve_ws = False elif self.field[self.pos] == '"': aslist.append('"%s"' % quote(self.getquote())) elif self.field[self.pos] in self.atomends: if aslist and not aslist[-1].strip(): aslist.pop() break else: aslist.append(self.getatom()) ws = self.gotonext() if preserve_ws and ws: aslist.append(ws) if self.pos >= len(self.field) or self.field[self.pos] != '@': return EMPTYSTRING.join(aslist) aslist.append('@') self.pos += 1 self.gotonext() return EMPTYSTRING.join(aslist) + self.getdomain() def getdomain(self): """Get the complete domain name from an address.""" sdlist = [] while self.pos < len(self.field): if self.field[self.pos] in self.LWS: self.pos += 1 elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) elif self.field[self.pos] == '[': sdlist.append(self.getdomainliteral()) elif self.field[self.pos] == '.': self.pos += 1 sdlist.append('.') elif self.field[self.pos] in self.atomends: break else: sdlist.append(self.getatom()) return EMPTYSTRING.join(sdlist) def getdelimited(self, beginchar, endchars, allowcomments=True): """Parse a header fragment delimited by special characters. `beginchar' is the start character for the fragment. If self is not looking at an instance of `beginchar' then getdelimited returns the empty string. `endchars' is a sequence of allowable end-delimiting characters. Parsing stops when one of these is encountered. If `allowcomments' is non-zero, embedded RFC 2822 comments are allowed within the parsed fragment. """ if self.field[self.pos] != beginchar: return '' slist = [''] quote = False self.pos += 1 while self.pos < len(self.field): if quote: slist.append(self.field[self.pos]) quote = False elif self.field[self.pos] in endchars: self.pos += 1 break elif allowcomments and self.field[self.pos] == '(': slist.append(self.getcomment()) continue # have already advanced pos from getcomment elif self.field[self.pos] == '\\': quote = True else: slist.append(self.field[self.pos]) self.pos += 1 return EMPTYSTRING.join(slist) def getquote(self): """Get a quote-delimited fragment from self's field.""" return self.getdelimited('"', '"\r', False) def getcomment(self): """Get a parenthesis-delimited fragment from self's field.""" return self.getdelimited('(', ')\r', True) def getdomainliteral(self): """Parse an RFC 2822 domain-literal.""" return '[%s]' % self.getdelimited('[', ']\r', False) def getatom(self, atomends=None): """Parse an RFC 2822 atom. Optional atomends specifies a different set of end token delimiters (the default is to use self.atomends). This is used e.g. in getphraselist() since phrase endings must not include the `.' (which is legal in phrases).""" atomlist = [''] if atomends is None: atomends = self.atomends while self.pos < len(self.field): if self.field[self.pos] in atomends: break else: atomlist.append(self.field[self.pos]) self.pos += 1 return EMPTYSTRING.join(atomlist) def getphraselist(self): """Parse a sequence of RFC 2822 phrases. A phrase is a sequence of words, which are in turn either RFC 2822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space. """ plist = [] while self.pos < len(self.field): if self.field[self.pos] in self.FWS: self.pos += 1 elif self.field[self.pos] == '"': plist.append(self.getquote()) elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) elif self.field[self.pos] in self.phraseends: break else: plist.append(self.getatom(self.phraseends)) return plist class AddressList(AddrlistClass): """An AddressList encapsulates a list of parsed RFC 2822 addresses.""" def __init__(self, field): AddrlistClass.__init__(self, field) if field: self.addresslist = self.getaddrlist() else: self.addresslist = [] def __len__(self): return len(self.addresslist) def __add__(self, other): # Set union newaddr = AddressList(None) newaddr.addresslist = self.addresslist[:] for x in other.addresslist: if not x in self.addresslist: newaddr.addresslist.append(x) return newaddr def __iadd__(self, other): # Set union, in-place for x in other.addresslist: if not x in self.addresslist: self.addresslist.append(x) return self def __sub__(self, other): # Set difference newaddr = AddressList(None) for x in self.addresslist: if not x in other.addresslist: newaddr.addresslist.append(x) return newaddr def __isub__(self, other): # Set difference, in-place for x in other.addresslist: if x in self.addresslist: self.addresslist.remove(x) return self def __getitem__(self, index): # Make indexing, slices, and 'in' work return self.addresslist[index]
31.769531
79
0.529878
79573c8322db1e9a8981a6a69ac3a343273b0ad1
2,819
py
Python
workers/test-delay/python/workerTestDelay.py
getgearbox/gearbox
7366083a2fa03fd7a020bfb63331c44c0c470ece
[ "Artistic-1.0-Perl", "BSD-3-Clause" ]
1
2015-04-24T16:47:43.000Z
2015-04-24T16:47:43.000Z
workers/test-delay/python/workerTestDelay.py
getgearbox/gearbox
7366083a2fa03fd7a020bfb63331c44c0c470ece
[ "Artistic-1.0-Perl", "BSD-3-Clause" ]
null
null
null
workers/test-delay/python/workerTestDelay.py
getgearbox/gearbox
7366083a2fa03fd7a020bfb63331c44c0c470ece
[ "Artistic-1.0-Perl", "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python import os import sys from gearbox import Worker def file_get_contents(filename): with open(filename, 'r') as f: contents = f.read() return contents def file_put_contents(filename, contents): with open(filename, 'wb') as f: f.write(contents) class WorkerTestDelayPython(Worker): DBDIR = "/var/gearbox/db/test-delay-python/" def __init__(self, config): super(WorkerTestDelayPython, self).__init__(config) self.register_handler("do_get_testdelaypython_counter_v1") self.register_handler("do_post_testdelaypython_counter_v1") self.register_handler("do_delete_testdelaypython_counter_v1") self.register_handler("do_increment_testdelaypython_counter_v1") def do_get_testdelaypython_counter_v1(self, job, resp): resource_file = os.path.join(self.DBDIR, job.resource_name()) resp.content(file_get_contents(resource_file)) return Worker.WORKER_SUCCESS def do_post_testdelaypython_counter_v1(self, job, resp): matrix = job.matrix_arguments() #grab start if available, else default to 0 start = matrix.get("start", "0") resource_file = os.path.join(self.DBDIR, job.resource_name()) file_put_contents(resource_file, start) seconds = int(matrix.get("delay", "1")) self.afterwards(job, "do_increment_testdelaypython_counter_v1", seconds) return Worker.WORKER_CONTINUE def do_delete_testdelaypython_counter_v1(self, job, resp): args = self.arguments() os.unlink(os.path.join(self.DBDIR, args[0])) return Worker.WORKER_SUCCESS def do_increment_testdelaypython_counter_v1(self, job, resp): resource_file = os.path.join(self.DBDIR, job.resource_name()) newval = 1 + int(file_get_contents(resource_file)) file_put_contents(resource_file, str(newval)) matrix = job.matrix_arguments() start = int(matrix.get("start", "0")) end = int(matrix.get("end", "10")) resp.status().add_message("set to %s" % newval) if newval == end: return Worker.WORKER_SUCCESS else: resp.status().progress(int(resp.status().progress()) + (end - start)) matrix = job.matrix_arguments() seconds = int(matrix.get("delay", "1")) if "retry" in matrix and matrix["retry"]: msg = "retry attempt number %s" % \ (int(resp.status().failures()) + 1) resp.status().add_message(msg) return Worker.WORKER_RETRY else: self.afterwards(job, seconds) return Worker.WORKER_CONTINUE if __name__ == "__main__": worker = WorkerTestDelayPython(sys.argv[2]) worker.run()
32.77907
72
0.645974
79573cd29f813a75888eb49d6fd55b26d18f882f
4,447
py
Python
colour/models/rgb/transfer_functions/itur_bt_1886.py
jchwei/colour
2b2ad0a0f2052a1a0b4b076b489687235e804fdf
[ "BSD-3-Clause" ]
null
null
null
colour/models/rgb/transfer_functions/itur_bt_1886.py
jchwei/colour
2b2ad0a0f2052a1a0b4b076b489687235e804fdf
[ "BSD-3-Clause" ]
null
null
null
colour/models/rgb/transfer_functions/itur_bt_1886.py
jchwei/colour
2b2ad0a0f2052a1a0b4b076b489687235e804fdf
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """ ITU-R BT.1886 ============= Defines *Recommendation ITU-R BT.1886* electro-optical transfer function (EOTF / EOCF) and its inverse: - :func:`colour.models.eotf_inverse_BT1886` - :func:`colour.models.eotf_BT1886` References ---------- - :cite:`InternationalTelecommunicationUnion2011h` : International Telecommunication Union. (2011). Recommendation ITU-R BT.1886 - Reference electro-optical transfer function for flat panel displays used in HDTV studio production BT Series Broadcasting service. Retrieved from https://www.itu.int/dms_pubrec/itu-r/rec/bt/\ R-REC-BT.1886-0-201103-I!!PDF-E.pdf """ from __future__ import division, unicode_literals import numpy as np from colour.utilities import from_range_1, to_domain_1 __author__ = 'Colour Developers' __copyright__ = 'Copyright (C) 2013-2020 - Colour Developers' __license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause' __maintainer__ = 'Colour Developers' __email__ = 'colour-developers@colour-science.org' __status__ = 'Production' __all__ = ['eotf_inverse_BT1886', 'eotf_BT1886'] def eotf_inverse_BT1886(L, L_B=0, L_W=1): """ Defines *Recommendation ITU-R BT.1886* inverse electro-optical transfer function (EOTF / EOCF). Parameters ---------- L : numeric or array_like Screen luminance in :math:`cd/m^2`. L_B : numeric, optional Screen luminance for black. L_W : numeric, optional Screen luminance for white. Returns ------- numeric or ndarray Input video signal level (normalised, black at :math:`V = 0`, to white at :math:`V = 1`. Notes ----- +------------+-----------------------+---------------+ | **Domain** | **Scale - Reference** | **Scale - 1** | +============+=======================+===============+ | ``L`` | [0, 1] | [0, 1] | +------------+-----------------------+---------------+ +------------+-----------------------+---------------+ | **Range** | **Scale - Reference** | **Scale - 1** | +============+=======================+===============+ | ``V`` | [0, 1] | [0, 1] | +------------+-----------------------+---------------+ References ---------- :cite:`InternationalTelecommunicationUnion2011h` Examples -------- >>> eotf_inverse_BT1886(0.11699185725296059) # doctest: +ELLIPSIS 0.4090077... """ L = to_domain_1(L) gamma = 2.40 gamma_d = 1 / gamma n = L_W ** gamma_d - L_B ** gamma_d a = n ** gamma b = L_B ** gamma_d / n V = (L / a) ** gamma_d - b return from_range_1(V) def eotf_BT1886(V, L_B=0, L_W=1): """ Defines *Recommendation ITU-R BT.1886* electro-optical transfer function (EOTF / EOCF). Parameters ---------- V : numeric or array_like Input video signal level (normalised, black at :math:`V = 0`, to white at :math:`V = 1`. For content mastered per *Recommendation ITU-R BT.709*, 10-bit digital code values :math:`D` map into values of :math:`V` per the following equation: :math:`V = (D-64)/876` L_B : numeric, optional Screen luminance for black. L_W : numeric, optional Screen luminance for white. Returns ------- numeric or ndarray Screen luminance in :math:`cd/m^2`. Notes ----- +------------+-----------------------+---------------+ | **Domain** | **Scale - Reference** | **Scale - 1** | +============+=======================+===============+ | ``V`` | [0, 1] | [0, 1] | +------------+-----------------------+---------------+ +------------+-----------------------+---------------+ | **Range** | **Scale - Reference** | **Scale - 1** | +============+=======================+===============+ | ``L`` | [0, 1] | [0, 1] | +------------+-----------------------+---------------+ References ---------- :cite:`InternationalTelecommunicationUnion2011h` Examples -------- >>> eotf_BT1886(0.409007728864150) # doctest: +ELLIPSIS 0.1169918... """ V = to_domain_1(V) gamma = 2.40 gamma_d = 1 / gamma n = L_W ** gamma_d - L_B ** gamma_d a = n ** gamma b = L_B ** gamma_d / n L = a * np.maximum(V + b, 0) ** gamma return from_range_1(L)
28.50641
79
0.489319
79573dccf41abab241b93bc5dc8aee1ba3ca797a
9,269
py
Python
transcript/extra_app/xadmin/plugins/auth.py
Harrymissi/transcript-system
c7c3a8e505e4e8e5ca6ab5f934338bb8ff314260
[ "Apache-2.0" ]
1
2019-02-25T23:17:18.000Z
2019-02-25T23:17:18.000Z
transcript/extra_app/xadmin/plugins/auth.py
Harrymissi/transcript-system
c7c3a8e505e4e8e5ca6ab5f934338bb8ff314260
[ "Apache-2.0" ]
null
null
null
transcript/extra_app/xadmin/plugins/auth.py
Harrymissi/transcript-system
c7c3a8e505e4e8e5ca6ab5f934338bb8ff314260
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 from django import forms from django.contrib.auth.forms import (UserCreationForm, UserChangeForm, AdminPasswordChangeForm, PasswordChangeForm) from django.contrib.auth.models import Group, Permission from django.core.exceptions import PermissionDenied from django.conf import settings from django.template.response import TemplateResponse from django.utils.decorators import method_decorator from django.http import HttpResponseRedirect from django.utils.html import escape from django.utils.encoding import smart_text from django.utils.translation import ugettext as _ from django.views.decorators.debug import sensitive_post_parameters from django.forms import ModelMultipleChoiceField from django.contrib.auth import get_user_model from xadmin.layout import Fieldset, Main, Side, Row, FormHelper from xadmin.sites import site from xadmin.util import unquote from xadmin.views import BaseAdminPlugin, ModelFormAdminView, ModelAdminView, CommAdminView, csrf_protect_m User = get_user_model() ACTION_NAME = { 'add': _('Can add %s'), 'change': _('Can change %s'), 'edit': _('Can edit %s'), 'delete': _('Can delete %s'), 'view': _('Can view %s'), } def get_permission_name(p): action = p.codename.split('_')[0] if action in ACTION_NAME: return ACTION_NAME[action] % str(p.content_type) else: return p.name class PermissionModelMultipleChoiceField(ModelMultipleChoiceField): def label_from_instance(self, p): return get_permission_name(p) class GroupAdmin(object): search_fields = ('name',) ordering = ('name',) style_fields = {'permissions': 'm2m_transfer'} model_icon = 'fa fa-group' def get_field_attrs(self, db_field, **kwargs): attrs = super(GroupAdmin, self).get_field_attrs(db_field, **kwargs) if db_field.name == 'permissions': attrs['form_class'] = PermissionModelMultipleChoiceField return attrs class UserAdmin(object): change_user_password_template = None list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff') list_filter = ('is_staff', 'is_superuser', 'is_active') search_fields = ('username', 'first_name', 'last_name', 'email') ordering = ('username',) style_fields = {'user_permissions': 'm2m_transfer'} model_icon = 'fa fa-all_user' relfield_style = 'fk-ajax' def get_field_attrs(self, db_field, **kwargs): attrs = super(UserAdmin, self).get_field_attrs(db_field, **kwargs) if db_field.name == 'user_permissions': attrs['form_class'] = PermissionModelMultipleChoiceField return attrs def get_model_form(self, **kwargs): if self.org_obj is None: self.form = UserCreationForm else: self.form = UserChangeForm return super(UserAdmin, self).get_model_form(**kwargs) def get_form_layout(self): if self.org_obj: self.form_layout = ( Main( Fieldset('', 'username', 'password', css_class='unsort no_title' ), Fieldset(_('Personal info'), Row('first_name', 'last_name'), 'email' ), Fieldset(_('Permissions'), 'groups', 'user_permissions' ), Fieldset(_('Important dates'), 'last_login', 'date_joined' ), ), Side( Fieldset(_('Status'), 'is_active', 'is_staff', 'is_superuser', ), ) ) return super(UserAdmin, self).get_form_layout() class PermissionAdmin(object): def show_name(self, p): return get_permission_name(p) show_name.short_description = _('Permission Name') show_name.is_column = True model_icon = 'fa fa-lock' list_display = ('show_name', ) site.register(Group, GroupAdmin) site.register(User, UserAdmin) site.register(Permission, PermissionAdmin) class UserFieldPlugin(BaseAdminPlugin): user_fields = [] def get_field_attrs(self, __, db_field, **kwargs): if self.user_fields and db_field.name in self.user_fields: return {'widget': forms.HiddenInput} return __() def get_form_datas(self, datas): if self.user_fields and 'data' in datas: if hasattr(datas['data'],'_mutable') and not datas['data']._mutable: datas['data'] = datas['data'].copy() for f in self.user_fields: datas['data'][f] = self.user.id return datas site.register_plugin(UserFieldPlugin, ModelFormAdminView) class ModelPermissionPlugin(BaseAdminPlugin): user_can_access_owned_objects_only = False user_owned_objects_field = 'all_user' def queryset(self, qs): if self.user_can_access_owned_objects_only and \ not self.user.is_superuser: filters = {self.user_owned_objects_field: self.user} qs = qs.filter(**filters) return qs def get_list_display(self, list_display): if self.user_can_access_owned_objects_only and \ not self.user.is_superuser and \ self.user_owned_objects_field in list_display: list_display.remove(self.user_owned_objects_field) return list_display site.register_plugin(ModelPermissionPlugin, ModelAdminView) class AccountMenuPlugin(BaseAdminPlugin): def block_top_account_menu(self, context, nodes): return '<li><a href="%s"><i class="fa fa-key"></i> %s</a></li>' % (self.get_admin_url('account_password'), _('Change Password')) site.register_plugin(AccountMenuPlugin, CommAdminView) class ChangePasswordView(ModelAdminView): model = User change_password_form = AdminPasswordChangeForm change_user_password_template = None @csrf_protect_m def get(self, request, object_id): if not self.has_change_permission(request): raise PermissionDenied self.obj = self.get_object(unquote(object_id)) self.form = self.change_password_form(self.obj) return self.get_response() def get_media(self): media = super(ChangePasswordView, self).get_media() media = media + self.vendor('xadmin.form.css', 'xadmin.page.form.js') + self.form.media return media def get_context(self): context = super(ChangePasswordView, self).get_context() helper = FormHelper() helper.form_tag = False helper.include_media = False self.form.helper = helper context.update({ 'title': _('Change password: %s') % escape(smart_text(self.obj)), 'form': self.form, 'has_delete_permission': False, 'has_change_permission': True, 'has_view_permission': True, 'original': self.obj, }) return context def get_response(self): return TemplateResponse(self.request, [ self.change_user_password_template or 'xadmin/auth/all_user/change_password.html' ], self.get_context()) @method_decorator(sensitive_post_parameters()) @csrf_protect_m def post(self, request, object_id): if not self.has_change_permission(request): raise PermissionDenied self.obj = self.get_object(unquote(object_id)) self.form = self.change_password_form(self.obj, request.POST) if self.form.is_valid(): self.form.save() self.message_user(_('Password changed successfully.'), 'success') return HttpResponseRedirect(self.model_admin_url('change', self.obj.pk)) else: return self.get_response() class ChangeAccountPasswordView(ChangePasswordView): change_password_form = PasswordChangeForm @csrf_protect_m def get(self, request): self.obj = self.user self.form = self.change_password_form(self.obj) return self.get_response() def get_context(self): context = super(ChangeAccountPasswordView, self).get_context() context.update({ 'title': _('Change password'), 'account_view': True, }) return context @method_decorator(sensitive_post_parameters()) @csrf_protect_m def post(self, request): self.obj = self.user self.form = self.change_password_form(self.obj, request.POST) if self.form.is_valid(): self.form.save() self.message_user(_('Password changed successfully.'), 'success') return HttpResponseRedirect(self.get_admin_url('index')) else: return self.get_response() user_model = settings.AUTH_USER_MODEL.lower().replace('.','/') site.register_view(r'^%s/(.+)/password/$' % user_model, ChangePasswordView, name='user_change_password') site.register_view(r'^account/password/$', ChangeAccountPasswordView, name='account_password')
34.32963
136
0.63653