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
# vi: ts=4 expandtab syntax=python ############################################################################## # Copyright (c) 2008 IBM Corporation # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at # http://www.eclipse.org/legal/epl-v10.html # # Contributors: # Dave Leskovec (IBM) - initial implementation ############################################################################## """ This module contains functions dealing with platform information. """ import OvfLibvirt from locale import getlocale, getdefaultlocale from time import timezone def virtTypeIsAvailable(virtType): """ Check if the given virt type is available on this system @type node: String @param node: Platform type to check @rtype: Boolean @return: Indication if type is available or not """ if virtType: return True return False def getVsSystemType(vs): """ This function gets the list of system types for the virtual system and selects one based on the libvirt capabilities. It will select the first type in the list that is present on the system. @type node: DOM node @param node: Virtual System node @rtype: String @return: Platform type for Virtual System """ virtTypes = OvfLibvirt.getOvfSystemType(vs) for virtType in virtTypes: # check if this virtType is available if virtTypeIsAvailable(virtType): return virtType return None def getPlatformDict(vs, virtPlatform=None): """ Get the platform information @type node: DOM node @param node: Virtual System node @type virtPlatform: String @param node: Virtual Platform type. If None, will be taken from vs @rtype: String @return: Dictionary containing platform information for the virtual system the contents are defined by the ovf specification for the environment. """ retDict = {} if not virtPlatform: virtPlatform = getVsSystemType(vs) retDict['Kind'] = virtPlatform # We could possibly look up the version and vendor here # gather the details of the platform (langCode, encoding) = getlocale() if langCode == None: (langCode, encoding) = getdefaultlocale() retDict['Locale'] = langCode retDict['Timezone'] = timezone return retDict
Awingu/open-ovf
py/ovf/OvfPlatform.py
Python
epl-1.0
2,476
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on Jul 1, 2014 @author: anroco I have a list in python and I want to invest the elements, ie the latter is the first, how I can do? Tengo una lista en python y quiero invertir los elementos de la lista, es decir que el último sea el primero, ¿como puedo hacerlo? ''' #create a list lista = [9, 2, 5, 10, 9, 1, 3] print (lista) #reverses the order of the list lista.reverse() print (lista) #create a list lista = ['abc', 'a', 'bcd', 'c', 'bb', 'abcd'] print (lista) #reverses the order of the list lista.reverse() print (lista)
OxPython/Python_lists_reverse
src/reverse_lists.py
Python
epl-1.0
594
import os import glob import subprocess def expand_path(path): return os.path.abspath(os.path.expandvars(os.path.expanduser(path))) def is_file(path): if not path: return False if not os.path.isfile(path): return False return True def arg_is_file(path): try: if not is_file(path): raise except: msg = '{0!r} is not a file'.format(path) raise argparse.ArgumentTypeError(msg) return expand_path(path) def run_jmodeltest(name): jmodel_proc=subprocess.Popen('java -jar ~/phylo_tools/jmodeltest-2.1.5/jModelTest.jar -d '+str(name)+' -s 3 -f -i -g 4 -BIC -c 0.95 > '+str(name)+'.results.txt', shell=True, executable='/bin/bash') jmodel_proc.wait() def get_models(f, gene_name, out): fl=file(f) for line in fl: line=line.strip() if "the 95% confidence interval" in line: model=line.split(': ')[1] out.write(str(gene_name)+'\t'+str(model)+'\n') def main(): for f in glob.glob('*.nex'): run_jmodeltest(f) out=open('models.txt','w') for f in glob.glob('*.results.txt'): gene_name=f.split('.')[0] get_models(f, gene_name,out) ''' description = ('This program will run jModelTest on a single file or set ' 'of files in nexus format. User can choose the set of models' 'and type of summary using flags. The standard 24 models used' 'in MrBayes and BIC summary with 95% credible set are defaults.') FILE_FORMATS = ['nex'] parser = argparse.ArgumentParser(description = description) parser.add_argument('input_files', metavar='INPUT-SEQ-FILE', nargs = '+', type = arg_is_file, help = ('Input sequence file(s) name ')) parser.add_argument('-o', '--out-format', type = str, choices = ['nex', 'fasta', 'phy'], help = ('The format of the output sequence file(s). Valid options ')) parser.add_argument('-j', '--path-to-jModelTest', type = str, help=('The full path to the jModelTest executable')) parser.add_argument('-s', '--substitution-models', type = str, choices = ['3','5','7','11'] default = ['3'] help = ('Number of substitution schemes to test. Default is all GTR models "-s 3".')) parser.add_argument('-g', '--gamma', type = str, default = ['4'] help = ('Include models with rate variation among sites and number of categories (e.g., -g 8)')) parser.add_argument('-i', '--invar', type = str, default = ['false'] help = ('include models with a proportion invariable sites (e.g., -i)')) args = parser.parse_args() for f in args.input_files: in_type=os.path.splitext(f)[1] filename=os.path.splitext(f)[0] if in_type == '.nex' or in_type == '.nexus': dict=in_nex(f) elif in_type == '.fa' or in_type == '.fas' or in_type == '.fasta': dict=in_fasta(f) elif in_type == '.phy' or in_type == '.phylip': dict=in_phy(f) if args.out_format == 'nex': out_nex(dict, filename) elif args.out_format == 'fasta': out_fasta(dict, filename) elif args.out_format == 'phy': out_phy(dict, filename)''' if __name__ == '__main__': main()
cwlinkem/linkuce
modeltest_runner.py
Python
gpl-2.0
2,993
#resource, resources, Resources from flask import Blueprint, render_template, request,flash, redirect, url_for from app.{resources}.models import {Resources}, {Resources}Schema {resources} = Blueprint('{resources}', __name__, template_folder='templates') #http://marshmallow.readthedocs.org/en/latest/quickstart.html#declaring-schemas schema = {Resources}Schema() #{Resources} @{resources}.route('/' ) def {resource}_index(): {resources} = {Resources}.query.all() results = schema.dump({resources}, many=True).data return render_template('/{resources}/index.html', results=results) @{resources}.route('/add' , methods=['POST', 'GET']) def {resource}_add(): if request.method == 'POST': #Validate form values by de-serializing the request, http://marshmallow.readthedocs.org/en/latest/quickstart.html#validation form_errors = schema.validate(request.form.to_dict()) if not form_errors: {resource}={Resources}({add_fields}) return add({resource}, success_url = '{resources}.{resource}_index', fail_url = '{resources}.{resource}_add') else: flash(form_errors) return render_template('/{resources}/add.html') @{resources}.route('/update/<int:id>' , methods=['POST', 'GET']) def {resource}_update (id): #Get {resource} by primary key: {resource}={Resources}.query.get_or_404(id) if request.method == 'POST': form_errors = schema.validate(request.form.to_dict()) if not form_errors: {update_fields} return update({resource} , id, success_url = '{resources}.{resource}_index', fail_url = '{resources}.{resource}_update') else: flash(form_errors) return render_template('/{resources}/update.html', {resource}={resource}) @{resources}.route('/delete/<int:id>' , methods=['POST', 'GET']) def {resource}_delete (id): {resource} = {Resources}.query.get_or_404(id) return delete({resource}, fail_url = '{resources}.{resource}_index') #CRUD FUNCTIONS #Arguments are data to add, function to redirect to if the add was successful and if not def add (data, success_url = '', fail_url = ''): add = data.add(data) #if does not return any error if not add : flash("Add was successful") return redirect(url_for(success_url)) else: message=add flash(message) return redirect(url_for(fail_url)) def update (data, id, success_url = '', fail_url = ''): update=data.update() #if does not return any error if not update : flash("Update was successful") return redirect(url_for(success_url)) else: message=update flash(message) return redirect(url_for(fail_url, id=id)) def delete (data, fail_url=''): delete=data.delete(data) if not delete : flash("Delete was successful") else: message=delete flash(message) return redirect(url_for(fail_url))
jstacoder/Flask-Scaffold
scaffold/app/views.py
Python
gpl-2.0
3,123
# -*- coding: utf-8 -*- """ /*************************************************************************** DsgTools A QGIS plugin Brazilian Army Cartographic Production Tools ------------------- begin : 2019-04-26 git sha : $Format:%H$ copyright : (C) 2019 by Philipe Borba - Cartographic Engineer @ Brazilian Army email : [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. * * * ***************************************************************************/ """ import os from PyQt5.QtCore import QCoreApplication from qgis.core import (QgsDataSourceUri, QgsExpression, QgsExpressionContext, QgsExpressionContextUtils, QgsProcessing, QgsProcessingAlgorithm, QgsProcessingOutputMultipleLayers, QgsProcessingParameterExpression, QgsProcessingParameterMultipleLayers, QgsProcessingParameterNumber, QgsProcessingParameterString, QgsProject) from qgis.utils import iface class GroupLayersAlgorithm(QgsProcessingAlgorithm): """ Algorithm to group layers according to primitive, dataset and a category. INPUT_LAYERS: list of QgsVectorLayer CATEGORY_TOKEN: token used to split layer name CATEGORY_TOKEN_INDEX: index of the split list OUTPUT: list of outputs """ INPUT_LAYERS = 'INPUT_LAYERS' CATEGORY_EXPRESSION = 'CATEGORY_EXPRESSION' OUTPUT = 'OUTPUT' def initAlgorithm(self, config): """ Parameter setting. """ self.addParameter( QgsProcessingParameterMultipleLayers( self.INPUT_LAYERS, self.tr('Input Layers'), QgsProcessing.TypeVector ) ) self.addParameter( QgsProcessingParameterExpression( self.CATEGORY_EXPRESSION, self.tr('Expression used to find out the category'), defaultValue="regexp_substr(@layer_name ,'([^_]+)')" ) ) self.addOutput( QgsProcessingOutputMultipleLayers( self.OUTPUT, self.tr('Original reorganized layers') ) ) def processAlgorithm(self, parameters, context, feedback): """ Here is where the processing itself takes place. """ inputLyrList = self.parameterAsLayerList( parameters, self.INPUT_LAYERS, context ) categoryExpression = self.parameterAsExpression( parameters, self.CATEGORY_EXPRESSION, context ) listSize = len(inputLyrList) progressStep = 100/listSize if listSize else 0 rootNode = QgsProject.instance().layerTreeRoot() inputLyrList.sort(key=lambda x: (x.geometryType(), x.name())) geometryNodeDict = { 0 : self.tr('Point'), 1 : self.tr('Line'), 2 : self.tr('Polygon'), 4 : self.tr('Non spatial') } iface.mapCanvas().freeze(True) for current, lyr in enumerate(inputLyrList): if feedback.isCanceled(): break rootDatabaseNode = self.getLayerRootNode(lyr, rootNode) geometryNode = self.createGroup( geometryNodeDict[lyr.geometryType()], rootDatabaseNode ) categoryNode = self.getLayerCategoryNode( lyr, geometryNode, categoryExpression ) lyrNode = rootNode.findLayer(lyr.id()) myClone = lyrNode.clone() categoryNode.addChildNode(myClone) # not thread safe, must set flag to FlagNoThreading rootNode.removeChildNode(lyrNode) feedback.setProgress(current*progressStep) iface.mapCanvas().freeze(False) return {self.OUTPUT: [i.id() for i in inputLyrList]} def getLayerRootNode(self, lyr, rootNode): """ Finds the database name of the layer and creates (if not exists) a node with the found name. lyr: (QgsVectorLayer) rootNode: (node item) """ uriText = lyr.dataProvider().dataSourceUri() candidateUri = QgsDataSourceUri(uriText) rootNodeName = candidateUri.database() if not rootNodeName: rootNodeName = self.getRootNodeName(uriText) #creates database root return self.createGroup(rootNodeName, rootNode) def getRootNodeName(self, uriText): """ Gets root node name from uri according to provider type. """ if 'memory?' in uriText: rootNodeName = 'memory' elif 'dbname' in uriText: rootNodeName = uriText.replace('dbname=', '').split(' ')[0] elif '|' in uriText: rootNodeName = os.path.dirname(uriText.split(' ')[0].split('|')[0]) else: rootNodeName = 'unrecognised_format' return rootNodeName def getLayerCategoryNode(self, lyr, rootNode, categoryExpression): """ Finds category node based on category expression and creates it (if not exists a node) """ exp = QgsExpression(categoryExpression) context = QgsExpressionContext() context.appendScopes( QgsExpressionContextUtils.globalProjectLayerScopes(lyr) ) if exp.hasParserError(): raise Exception(exp.parserErrorString()) if exp.hasEvalError(): raise ValueError(exp.evalErrorString()) categoryText = exp.evaluate(context) return self.createGroup(categoryText, rootNode) def createGroup(self, groupName, rootNode): """ Create group with the name groupName and parent rootNode. """ groupNode = rootNode.findGroup(groupName) return groupNode if groupNode else rootNode.addGroup(groupName) def name(self): """ Returns the algorithm name, used for identifying the algorithm. This string should be fixed for the algorithm, and must not be localised. The name should be unique within each provider. Names should contain lowercase alphanumeric characters only and no spaces or other formatting characters. """ return 'grouplayers' def displayName(self): """ Returns the translated algorithm name, which should be used for any user-visible display of the algorithm name. """ return self.tr('Group Layers') def group(self): """ Returns the name of the group this algorithm belongs to. This string should be localised. """ return self.tr('Layer Management Algorithms') def groupId(self): """ Returns the unique ID of the group this algorithm belongs to. This string should be fixed for the algorithm, and must not be localised. The group id should be unique within each provider. Group id should contain lowercase alphanumeric characters only and no spaces or other formatting characters. """ return 'DSGTools: Layer Management Algorithms' def tr(self, string): """ Translates input string. """ return QCoreApplication.translate('GroupLayersAlgorithm', string) def createInstance(self): """ Creates an instance of this class """ return GroupLayersAlgorithm() def flags(self): """ This process is not thread safe due to the fact that removeChildNode method from QgsLayerTreeGroup is not thread safe. """ return super().flags() | QgsProcessingAlgorithm.FlagNoThreading
lcoandrade/DsgTools
core/DSGToolsProcessingAlgs/Algs/LayerManagementAlgs/groupLayersAlgorithm.py
Python
gpl-2.0
8,547
""" Default configuration values for certmaster items when not specified in config file. Copyright 2008, Red Hat, Inc see AUTHORS This software may be freely redistributed under the terms of the GNU general public license. 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., 675 Mass Ave, Cambridge, MA 02139, USA. """ from config import BaseConfig, BoolOption, IntOption, Option class CMConfig(BaseConfig): log_level = Option('INFO') listen_addr = Option('') listen_port = IntOption(51235) cadir = Option('/etc/pki/certmaster/ca') cert_dir = Option('/etc/pki/certmaster') certroot = Option('/var/lib/certmaster/certmaster/certs') csrroot = Option('/var/lib/certmaster/certmaster/csrs') cert_extension = Option('cert') autosign = BoolOption(False) sync_certs = BoolOption(False) peering = BoolOption(True) peerroot = Option('/var/lib/certmaster/peers') hash_function = Option('sha256') class MinionConfig(BaseConfig): log_level = Option('INFO') certmaster = Option('certmaster') certmaster_port = IntOption(51235) cert_dir = Option('/etc/pki/certmaster')
jude/certmaster
certmaster/commonconfig.py
Python
gpl-2.0
1,224
import forge from forge.models.groups import Group class Add(object): def __init__(self,json_args,session): if type(json_args) != type({}): raise TypeError("JSON Arg must be dict type") if 'name' and 'distribution' not in json_args.keys(): raise forge.ArgumentError() self.name = json_args['name'] self.distribution = json_args['distribution'] self.session = session def call(self): group = Group(self.name,self.distribution) self.session.add(group) self.session.commit() return {'name':self.name, 'distribution':self.distribution}
blhughes/forge
forge/commands/group/add.py
Python
gpl-2.0
734
#!/usr/bin/env python # encoding: utf-8 'A simple client for accessing api.ly.g0v.tw.' import json import unittest try: import urllib.request as request import urllib.parse as urlparse except: import urllib2 as request import urllib as urlparse def assert_args(func, *args): def inner(*args): required_arg = args[1] assert(len(required_arg) > 0) return func(*args) return inner class LY_G0V_Client: BASE_URL = 'http://api-beta.ly.g0v.tw/v0/' # BASE_URL = 'http://api.ly.g0v.tw/v0/' def _fetch_data(self, url_path): URL = LY_G0V_Client.BASE_URL + url_path try: f = request.urlopen(URL) r = f.read() r = r.decode('utf-8') return json.loads(r) except Exception as e: print("Failed to call " + URL) raise e def fetch_all_bills(self): 'Fetch all bills.' return self._fetch_data('collections/bills') def fetch_all_motions(self): 'Fetch all motions.' return self._fetch_data('collections/motions') def fetch_all_sittings(self): 'Fetch all sittings.' return self._fetch_data('collections/sittings') @assert_args def fetch_bill(self, bill_id): 'Fetch metadata of a specific bill.' return self._fetch_data('collections/bills/' + str(bill_id)) @assert_args def fetch_bill_data(self, bill_id): 'Fetch data of a specific bill.' assert(len(bill_id) > 0) return self._fetch_data('collections/bills/' + str(bill_id) + '/data') @assert_args def fetch_motions_related_with_bill(self, bill_id): 'Fetch motions related with a specific bill.' query = json.dumps({'bill_ref': bill_id}) query = urlparse.quote(query) return self._fetch_data('collections/motions/?q='+query) @assert_args def fetch_sitting(self, sitting_id): 'Fetch metadata of a specific bill.' return self._fetch_data('collections/bills/' + str(bill_id)) class TestClient(unittest.TestCase): def setUp(self): import time time.sleep(1) self.client = LY_G0V_Client() def _test_bill(self, bill): self.assertTrue(isinstance(bill, dict), str(type(bill))) keys = ('proposed_by', 'doc', 'abstract', 'sponsors', 'summary', 'bill_ref', 'motions', 'cosponsors', 'bill_id'); for key in keys: self.assertTrue(key in bill) if isinstance(bill['doc'], dict): self.assertTrue('pdf' in bill['doc']) self.assertTrue('doc' in bill['doc']) def _test_bills(self, bills): for key in ('entries', 'paging'): self.assertTrue(key in bills) for key in ('l', 'sk', 'count'): self.assertTrue(key in bills['paging']) for bill in bills['entries']: self._test_bill(bill) def _test_motion(self, motion): self.assertTrue(isinstance(motion, dict), str(type(motion))) keys = ('result', 'resolution', 'motion_class', 'bill_id', 'agenda_item', 'bill_ref', 'tts_id', 'subitem', 'status', 'sitting_id', 'item', 'summary', 'tts_seq', 'proposed_by', 'doc') for key in keys: self.assertTrue(key in motion, key) if isinstance(motion['doc'], dict): self.assertTrue('pdf' in motion['doc']) self.assertTrue('doc' in motion['doc']) def _test_motions(self, motions): self.assertTrue(isinstance(motions, dict), str(type(motions))) for key in ('entries', 'paging'): self.assertTrue(key in motions) for key in ('l', 'sk', 'count'): self.assertTrue(key in motions['paging']) for motion in motions['entries']: self._test_motion(motion) def _test_data(self, data): for key in ('related', 'content'): self.assertTrue(key in data) self.assertTrue(isinstance(data['related'], list)) self.assertTrue(isinstance(data['content'], list)) for item in data['content']: content_keys = ('name', 'type', 'content', 'header') for content_key in content_keys: self.assertTrue(content_key in item) self.assertTrue(len(item['name']) > 0) self.assertTrue(isinstance(item['name'], str) or \ isinstance(item['name'], unicode)) self.assertTrue(len(item['type']) > 0) self.assertTrue(isinstance(item['type'], str) or \ isinstance(item['type'], unicode)) self.assertTrue(len(item['content']) > 0) self.assertTrue(isinstance(item['content'], list)) for content in item['content']: self.assertTrue(isinstance(content, list)) for line in content: self.assertTrue(isinstance(line, str)) self.assertTrue(len(item['header']) > 0) self.assertTrue(isinstance(item['header'], list)) for header in item['header']: self.assertTrue(isinstance(header, str) or \ isinstance(header, unicode)) def _test_sitting(self, sitting): self.assertTrue(isinstance(sitting, dict), str(type(sitting))) keys = ('dates', 'ad', 'videos', 'extra', 'motions', 'sitting', 'summary', 'session', 'committee', 'id', 'name') for key in keys: self.assertTrue(key in sitting, key) def _test_sittings(self, sittings): self.assertTrue(isinstance(sittings, dict), str(type(sittings))) for key in ('entries', 'paging'): self.assertTrue(key in sittings) for key in ('l', 'sk', 'count'): self.assertTrue(key in sittings['paging']) for sitting in sittings['entries']: self._test_sitting(sitting) def test_all_bills(self): bills = self.client.fetch_all_bills() self._test_bills(bills) def test_all_motions(self): motions = self.client.fetch_all_motions() self._test_motions(motions) def test_all_sittings(self): sittings = self.client.fetch_all_sittings() self._test_sittings(sittings) def test_fetch_bill(self): bill = self.client.fetch_bill('1021021071000400') self._test_bill(bill) def test_fetch_bill_data(self): data = self.client.fetch_bill_data('1021021071000400') self._test_data(data) def test_fetch_motions_related_with_bill(self): motions = self.client.fetch_motions_related_with_bill('1021021071000400') self._test_motions(motions) if __name__ == '__main__': unittest.main()
zonble/lyg0vtw_client.py
lyg0vtw_client/lyg0vtw_client.py
Python
gpl-2.0
5,779
# -*- coding: utf-8 -*- # Inforevealer # Copyright (C) 2010 Francois Boulogne <fboulogne at april dot org> # # 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. import io, readconf, getinfo, pastebin import os, sys, gettext,string, pexpect,getpass gettext.textdomain('inforevealer') _ = gettext.gettext __version__="0.5.1" def askYesNo(question,default='y'): """ Yes/no question throught a console """ if string.lower(default) == 'y': question = question + " [Y/n]" else: question = question + " [y/N]" ret = string.lower(raw_input(question)) if ret == 'y' or ret == "": answer=True else: answer=False return answer def RunAs(category_info,gui=False): """ Check if root is needed, if user want to be root... """ if gui: from gui import yesNoDialog run_as='user' if os.getuid() == 0: #we are root run_as='root' else: #check if root is needed root_needed=False for i in category_info: if i.root: root_needed=True break if root_needed: #ask if the user want to substitute question=_("""To generate a complete report, root access is needed. Do you want to substitute user?""") if gui: #substitute=yesNoDialog(question=question) substitute=True #It seems more confortable to remove the question else: #substitute=askYesNo(question) substitute=True #It seems more confortable to remove the question if substitute: run_as="substitute" else: run_as="user" else: run_as='user' return run_as def CompleteReportAsRoot(run_as,tmp_configfile,gui=False): """Run a new instance of inforevealer with root priviledge to complete tmp_configfile""" if gui: from gui import askPassword if run_as == "substitute": #find the substitute user command and run the script if pexpect.which('su') != None: message=_("Please, enter the root password.") root_instance = str(pexpect.which('su')) + " - -c \'"+ os.path.abspath(sys.argv[0])+" --runfile "+ tmp_configfile+"\'" elif pexpect.which('sudo') != None: #TODO checkme message=_("Please, enter your user password.") root_instance = str(pexpect.which('sudo')) + ' ' + os.path.abspath(sys.argv[0])+' --runfile '+ tmp_configfile else: sys.stderr.write(_("Error: No substitute user command available.\n")) return 1 ret="" count=0 while ret!=[' \r\n'] and count <3: #Get password count+=1 if gui: password=askPassword(question=message) else: print(message) password=getpass.getpass() if password != False: #askPassword could return False #Run the command #TODO exceptions ? child = pexpect.spawn(root_instance) ret=child.expect([".*:",pexpect.EOF]) #Could we do more ? child.sendline(password) ret = child.readlines() if ret ==[' \r\n']: return 0 message=_("Wrong password.\nThe log will be generated without root priviledge.") if gui: import gtk md = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, message) md.set_title(_("Error")) md.run() md.destroy() else: print(message) def action(category,dumpfile,configfile,tmp_configfile,verbosity,gui=False): if gui: from gui import yesNoDialog ##################### # Write in dumpfile ##################### dumpfile_handler= open(dumpfile,'w') io.print_write_header(dumpfile_handler) dumpfile_handler.write('Category: '+ category+'\n') category_info = readconf.LoadCategoryInfo(configfile,category) #need/want to run commands as... run_as = RunAs(category_info,gui) #detect which distribution the user uses linux_distrib=getinfo.General_info(dumpfile_handler) # In the case of run_as='substitute' # a configuration file is generated # su/sudo is used to run a new instance of inforevealer in append mode # to complete the report tmp_configfile_handler= open(tmp_configfile,'w') for i in category_info: i.write(linux_distrib,verbosity,dumpfile_handler,dumpfile,run_as,tmp_configfile_handler) tmp_configfile_handler.close() #Use su or sudo to complete the report dumpfile_handler.close() #the next function will modify the report, close the dumpfile CompleteReportAsRoot(run_as,tmp_configfile,gui) # Message to close the report dumpfile_handler= open(dumpfile,'a') io.write_title("You didn\'t find what you expected?",dumpfile_handler) dumpfile_handler.write( 'Please, open a bug report on\nhttp://github.com/sciunto/inforevealer\n') dumpfile_handler.close() print( _("The output has been dumped in %s") %dumpfile)
sciunto/inforevealer
src/action.py
Python
gpl-2.0
5,161
#!/usr/bin/env python #-*- coding: ascii -*- from __future__ import print_function import sys from blib_util import * def build_kfont(build_info): for compiler_info in build_info.compilers: build_a_project("kfont", "kfont", build_info, compiler_info, True) if __name__ == "__main__": cfg = cfg_from_argv(sys.argv) bi = build_info(cfg.compiler, cfg.archs, cfg.cfg) print("Building kfont...") build_kfont(bi)
zhangf911/KlayGE
build_kfont.py
Python
gpl-2.0
435
# Copyright (c) 2014, Canon Inc. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of Canon Inc. nor the names of # its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY CANON INC. AND ITS CONTRIBUTORS "AS IS" AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL CANON INC. AND ITS CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import json import logging import sys import time from webkitpy.common.system.autoinstall import AutoInstaller from webkitpy.layout_tests.servers import http_server_base _log = logging.getLogger(__name__) def doc_root(port_obj): doc_root = port_obj.get_option("wptserver_doc_root") if doc_root is None: return port_obj.host.filesystem.join("imported", "w3c", "web-platform-tests") return doc_root def base_url(port_obj): config_wk_filepath = port_obj._filesystem.join(port_obj.layout_tests_dir(), "imported", "w3c", "resources", "config.json") if not port_obj.host.filesystem.isfile(config_wk_filepath): # This should only be hit by webkitpy unit tests _log.debug("No WPT config file found") return "http://localhost:8800/" json_data = port_obj._filesystem.read_text_file(config_wk_filepath) config = json.loads(json_data) ports = config["ports"] return "http://" + config["host"] + ":" + str(ports["http"][0]) + "/" class WebPlatformTestServer(http_server_base.HttpServerBase): def __init__(self, port_obj, name, pidfile=None): http_server_base.HttpServerBase.__init__(self, port_obj) self._output_dir = port_obj.results_directory() self._name = name self._log_file_name = '%s_process_log.out.txt' % (self._name) self._wsout = None self._process = None self._pid_file = pidfile if not self._pid_file: self._pid_file = self._filesystem.join(self._runtime_path, '%s.pid' % self._name) self._servers_file = self._filesystem.join(self._runtime_path, '%s_servers.json' % (self._name)) self._stdout_data = None self._stderr_data = None self._filesystem = port_obj.host.filesystem self._layout_root = port_obj.layout_tests_dir() self._doc_root = self._filesystem.join(self._layout_root, doc_root(port_obj)) self._resources_files_to_copy = ['testharness.css', 'testharnessreport.js'] current_dir_path = self._filesystem.abspath(self._filesystem.split(__file__)[0]) self._start_cmd = ["python", self._filesystem.join(current_dir_path, "web_platform_test_launcher.py"), self._servers_file] self._doc_root_path = self._filesystem.join(self._layout_root, self._doc_root) def _install_modules(self): modules_file_path = self._filesystem.join(self._doc_root_path, "..", "resources", "web-platform-tests-modules.json") if not self._filesystem.isfile(modules_file_path): _log.warning("Cannot read " + modules_file_path) return modules = json.loads(self._filesystem.read_text_file(modules_file_path)) for module in modules: path = module["path"] name = path.pop() AutoInstaller(target_dir=self._filesystem.join(self._doc_root, self._filesystem.sep.join(path))).install(url=module["url"], url_subpath=module["url_subpath"], target_name=name) def _copy_webkit_test_files(self): _log.debug('Copying WebKit resources files') for f in self._resources_files_to_copy: webkit_filename = self._filesystem.join(self._layout_root, "resources", f) if self._filesystem.isfile(webkit_filename): self._filesystem.copyfile(webkit_filename, self._filesystem.join(self._doc_root, "resources", f)) _log.debug('Copying WebKit web platform server config.json') config_wk_filename = self._filesystem.join(self._layout_root, "imported", "w3c", "resources", "config.json") if self._filesystem.isfile(config_wk_filename): config_json = self._filesystem.read_text_file(config_wk_filename).replace("%CERTS_DIR%", self._filesystem.join(self._output_dir, "_wpt_certs")) self._filesystem.write_text_file(self._filesystem.join(self._doc_root, "config.json"), config_json) wpt_testharnessjs_file = self._filesystem.join(self._doc_root, "resources", "testharness.js") layout_tests_testharnessjs_file = self._filesystem.join(self._layout_root, "resources", "testharness.js") # FIXME: Next line to be removed once all bots have wpt_testharnessjs_file updated correctly. See https://bugs.webkit.org/show_bug.cgi?id=152257. self._filesystem.copyfile(layout_tests_testharnessjs_file, wpt_testharnessjs_file) if (not self._filesystem.compare(wpt_testharnessjs_file, layout_tests_testharnessjs_file)): _log.warning("\n//////////\nWPT tests are not using the same testharness.js file as other WebKit Layout tests.\nWebKit testharness.js might need to be updated according WPT testharness.js.\n//////////\n") def _clean_webkit_test_files(self): _log.debug('Cleaning WPT resources files') for f in self._resources_files_to_copy: wpt_filename = self._filesystem.join(self._doc_root, "resources", f) if self._filesystem.isfile(wpt_filename): self._filesystem.remove(wpt_filename) _log.debug('Cleaning WPT web platform server config.json') config_wpt_filename = self._filesystem.join(self._doc_root, "config.json") if self._filesystem.isfile(config_wpt_filename): self._filesystem.remove(config_wpt_filename) def _prepare_config(self): if self._filesystem.exists(self._output_dir): output_log = self._filesystem.join(self._output_dir, self._log_file_name) self._wsout = self._filesystem.open_text_file_for_writing(output_log) self._install_modules() self._copy_webkit_test_files() def _spawn_process(self): self._stdout_data = None self._stderr_data = None if self._wsout: self._process = self._executive.popen(self._start_cmd, cwd=self._doc_root_path, shell=False, stdin=self._executive.PIPE, stdout=self._wsout, stderr=self._wsout) else: self._process = self._executive.popen(self._start_cmd, cwd=self._doc_root_path, shell=False, stdin=self._executive.PIPE, stdout=self._executive.PIPE, stderr=self._executive.STDOUT) self._filesystem.write_text_file(self._pid_file, str(self._process.pid)) # Wait a second for the server to actually start so that tests do not start until server is running. time.sleep(1) return self._process.pid def _stop_running_subservers(self): if self._filesystem.exists(self._servers_file): try: json_data = self._filesystem.read_text_file(self._servers_file) started_servers = json.loads(json_data) for server in started_servers: if self._executive.check_running_pid(server['pid']): _log.warning('Killing server process (protocol: %s , port: %d, pid: %d).' % (server['protocol'], server['port'], server['pid'])) self._executive.kill_process(server['pid']) finally: self._filesystem.remove(self._servers_file) def stop(self): super(WebPlatformTestServer, self).stop() # In case of orphaned pid, kill the running subservers if any still alive. self._stop_running_subservers() def _stop_running_server(self): _log.debug('Stopping %s server' % (self._name)) self._clean_webkit_test_files() if self._process: (self._stdout_data, self._stderr_data) = self._process.communicate(input='\n') if self._wsout: self._wsout.close() self._wsout = None if self._pid and self._executive.check_running_pid(self._pid): _log.warning('Cannot stop %s server normally.' % (self._name)) _log.warning('Killing server launcher process (pid: %d).' % (self._pid)) self._executive.kill_process(self._pid) self._remove_pid_file() self._stop_running_subservers()
teamfx/openjfx-9-dev-rt
modules/javafx.web/src/main/native/Tools/Scripts/webkitpy/layout_tests/servers/web_platform_test_server.py
Python
gpl-2.0
9,422
""" OK resolveurl XBMC Addon Copyright (C) 2016 Seberoth Version 0.0.2 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 json, urllib from resolveurl import common from lib import helpers from resolveurl.resolver import ResolveUrl, ResolverError class OKResolver(ResolveUrl): name = "ok.ru" domains = ['ok.ru', 'odnoklassniki.ru'] pattern = '(?://|\.)(ok\.ru|odnoklassniki\.ru)/(?:videoembed|video)/(\d+)' header = {"User-Agent": common.OPERA_USER_AGENT} qual_map = {'ultra': '2160', 'quad': '1440', 'full': '1080', 'hd': '720', 'sd': '480', 'low': '360', 'lowest': '240', 'mobile': '144'} def __init__(self): self.net = common.Net() def get_media_url(self, host, media_id): vids = self.__get_Metadata(media_id) sources = [] for entry in vids['urls']: quality = self.__replaceQuality(entry['name']) sources.append((quality, entry['url'])) try: sources.sort(key=lambda x: int(x[0]), reverse=True) except: pass source = helpers.pick_source(sources) source = source.encode('utf-8') + helpers.append_headers(self.header) return source def __replaceQuality(self, qual): return self.qual_map.get(qual.lower(), '000') def __get_Metadata(self, media_id): url = "http://www.ok.ru/dk" data = {'cmd': 'videoPlayerMetadata', 'mid': media_id} data = urllib.urlencode(data) html = self.net.http_POST(url, data, headers=self.header).content json_data = json.loads(html) if 'error' in json_data: raise ResolverError('File Not Found or removed') info = dict() info['urls'] = [] for entry in json_data['videos']: info['urls'].append(entry) return info def get_url(self, host, media_id): return self._default_get_url(host, media_id, 'http://{host}/videoembed/{media_id}')
felipenaselva/felipe.repository
script.module.resolveurl/lib/resolveurl/plugins/ok.py
Python
gpl-2.0
2,491
from functions.str import w_str from wtypes.control import WEvalRequired, WRaisedException, WReturnValue from wtypes.exception import WException from wtypes.magic_macro import WMagicMacro from wtypes.boolean import WBoolean class WAssert(WMagicMacro): def call_magic_macro(self, exprs, scope): if len(exprs) != 1: raise Exception( "Macro assert expected 1 argument. " "Got {} instead.".format(len(exprs))) expr = exprs[0] src = w_str(expr) def callback(_value): if _value is WBoolean.false: return WRaisedException( exception=WException(f'Assertion failed: {src}')) return WReturnValue(expr=_value) return WEvalRequired(expr=expr, callback=callback)
izrik/wodehouse
macros/assert_.py
Python
gpl-2.0
802
""" Builds out and synchronizes yum repo mirrors. Initial support for rsync, perhaps reposync coming later. Copyright 2006-2007, Red Hat, Inc Michael DeHaan <[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 """ import os import os.path import time import yaml # Howell-Clark version import sys HAS_YUM = True try: import yum except: HAS_YUM = False import utils from cexceptions import * import traceback import errno from utils import _ import clogger class RepoSync: """ Handles conversion of internal state to the tftpboot tree layout """ # ================================================================================== def __init__(self,config,tries=1,nofail=False,logger=None): """ Constructor """ self.verbose = True self.api = config.api self.config = config self.distros = config.distros() self.profiles = config.profiles() self.systems = config.systems() self.settings = config.settings() self.repos = config.repos() self.rflags = self.settings.reposync_flags self.tries = tries self.nofail = nofail self.logger = logger if logger is None: self.logger = clogger.Logger() self.logger.info("hello, reposync") # =================================================================== def run(self, name=None, verbose=True): """ Syncs the current repo configuration file with the filesystem. """ self.logger.info("run, reposync, run!") try: self.tries = int(self.tries) except: utils.die(self.logger,"retry value must be an integer") self.verbose = verbose report_failure = False for repo in self.repos: env = repo.environment for k in env.keys(): self.logger.info("environment: %s=%s" % (k,env[k])) if env[k] is not None: os.putenv(k,env[k]) if name is not None and repo.name != name: # invoked to sync only a specific repo, this is not the one continue elif name is None and not repo.keep_updated: # invoked to run against all repos, but this one is off self.logger.info("%s is set to not be updated" % repo.name) continue repo_mirror = os.path.join(self.settings.webdir, "repo_mirror") repo_path = os.path.join(repo_mirror, repo.name) mirror = repo.mirror if not os.path.isdir(repo_path) and not repo.mirror.lower().startswith("rhn://"): os.makedirs(repo_path) # which may actually NOT reposync if the repo is set to not mirror locally # but that's a technicality for x in range(self.tries+1,1,-1): success = False try: self.sync(repo) success = True except: utils.log_exc(self.logger) self.logger.warning("reposync failed, tries left: %s" % (x-2)) if not success: report_failure = True if not self.nofail: utils.die(self.logger,"reposync failed, retry limit reached, aborting") else: self.logger.error("reposync failed, retry limit reached, skipping") self.update_permissions(repo_path) if report_failure: utils.die(self.logger,"overall reposync failed, at least one repo failed to synchronize") return True # ================================================================================== def sync(self, repo): """ Conditionally sync a repo, based on type. """ if repo.breed == "rhn": return self.rhn_sync(repo) elif repo.breed == "yum": return self.yum_sync(repo) #elif repo.breed == "apt": # return self.apt_sync(repo) elif repo.breed == "rsync": return self.rsync_sync(repo) else: utils.die(self.logger,"unable to sync repo (%s), unknown or unsupported repo type (%s)" % (repo.name, repo.breed)) # ==================================================================================== def createrepo_walker(self, repo, dirname, fnames): """ Used to run createrepo on a copied Yum mirror. """ if os.path.exists(dirname) or repo['breed'] == 'rsync': utils.remove_yum_olddata(dirname) # add any repo metadata we can use mdoptions = [] if os.path.isfile("%s/.origin/repomd.xml" % (dirname)): if not HAS_YUM: utils.die(self.logger,"yum is required to use this feature") rmd = yum.repoMDObject.RepoMD('', "%s/.origin/repomd.xml" % (dirname)) if rmd.repoData.has_key("group"): groupmdfile = rmd.getData("group").location[1] mdoptions.append("-g %s" % groupmdfile) if rmd.repoData.has_key("prestodelta"): # need createrepo >= 0.9.7 to add deltas if utils.check_dist() == "redhat" or utils.check_dist() == "suse": cmd = "/usr/bin/rpmquery --queryformat=%{VERSION} createrepo" createrepo_ver = utils.subprocess_get(self.logger, cmd) if createrepo_ver >= "0.9.7": mdoptions.append("--deltas") else: utils.die(self.logger,"this repo has presto metadata; you must upgrade createrepo to >= 0.9.7 first and then need to resync the repo through cobbler.") blended = utils.blender(self.api, False, repo) flags = blended.get("createrepo_flags","(ERROR: FLAGS)") try: # BOOKMARK cmd = "createrepo %s %s %s" % (" ".join(mdoptions), flags, dirname) utils.subprocess_call(self.logger, cmd) except: utils.log_exc(self.logger) self.logger.error("createrepo failed.") del fnames[:] # we're in the right place # ==================================================================================== def rsync_sync(self, repo): """ Handle copying of rsync:// and rsync-over-ssh repos. """ repo_mirror = repo.mirror if not repo.mirror_locally: utils.die(self.logger,"rsync:// urls must be mirrored locally, yum cannot access them directly") if repo.rpm_list != "" and repo.rpm_list != []: self.logger.warning("--rpm-list is not supported for rsync'd repositories") # FIXME: don't hardcode dest_path = os.path.join("/var/www/cobbler/repo_mirror", repo.name) spacer = "" if not repo.mirror.startswith("rsync://") and not repo.mirror.startswith("/"): spacer = "-e ssh" if not repo.mirror.endswith("/"): repo.mirror = "%s/" % repo.mirror # FIXME: wrapper for subprocess that logs to logger cmd = "rsync -rltDv %s --delete --exclude-from=/etc/cobbler/rsync.exclude %s %s" % (spacer, repo.mirror, dest_path) rc = utils.subprocess_call(self.logger, cmd) if rc !=0: utils.die(self.logger,"cobbler reposync failed") os.path.walk(dest_path, self.createrepo_walker, repo) self.create_local_file(dest_path, repo) # ==================================================================================== def rhn_sync(self, repo): """ Handle mirroring of RHN repos. """ repo_mirror = repo.mirror # FIXME? warn about not having yum-utils. We don't want to require it in the package because # RHEL4 and RHEL5U0 don't have it. if not os.path.exists("/usr/bin/reposync"): utils.die(self.logger,"no /usr/bin/reposync found, please install yum-utils") cmd = "" # command to run has_rpm_list = False # flag indicating not to pull the whole repo # detect cases that require special handling if repo.rpm_list != "" and repo.rpm_list != []: has_rpm_list = True # create yum config file for use by reposync # FIXME: don't hardcode dest_path = os.path.join("/var/www/cobbler/repo_mirror", repo.name) temp_path = os.path.join(dest_path, ".origin") if not os.path.isdir(temp_path): # FIXME: there's a chance this might break the RHN D/L case os.makedirs(temp_path) # how we invoke yum-utils depends on whether this is RHN content or not. # this is the somewhat more-complex RHN case. # NOTE: this requires that you have entitlements for the server and you give the mirror as rhn://$channelname if not repo.mirror_locally: utils.die("rhn:// repos do not work with --mirror-locally=1") if has_rpm_list: self.logger.warning("warning: --rpm-list is not supported for RHN content") rest = repo.mirror[6:] # everything after rhn:// cmd = "/usr/bin/reposync %s -r %s --download_path=%s" % (self.rflags, rest, "/var/www/cobbler/repo_mirror") if repo.name != rest: args = { "name" : repo.name, "rest" : rest } utils.die(self.logger,"ERROR: repository %(name)s needs to be renamed %(rest)s as the name of the cobbler repository must match the name of the RHN channel" % args) if repo.arch == "i386": # counter-intuitive, but we want the newish kernels too repo.arch = "i686" if repo.arch != "": cmd = "%s -a %s" % (cmd, repo.arch) # now regardless of whether we're doing yumdownloader or reposync # or whether the repo was http://, ftp://, or rhn://, execute all queued # commands here. Any failure at any point stops the operation. if repo.mirror_locally: rc = utils.subprocess_call(self.logger, cmd) # Don't die if reposync fails, it is logged # if rc !=0: # utils.die(self.logger,"cobbler reposync failed") # some more special case handling for RHN. # create the config file now, because the directory didn't exist earlier temp_file = self.create_local_file(temp_path, repo, output=False) # now run createrepo to rebuild the index if repo.mirror_locally: os.path.walk(dest_path, self.createrepo_walker, repo) # create the config file the hosts will use to access the repository. self.create_local_file(dest_path, repo) # ==================================================================================== def yum_sync(self, repo): """ Handle copying of http:// and ftp:// yum repos. """ repo_mirror = repo.mirror # warn about not having yum-utils. We don't want to require it in the package because # RHEL4 and RHEL5U0 don't have it. if not os.path.exists("/usr/bin/reposync"): utils.die(self.logger,"no /usr/bin/reposync found, please install yum-utils") cmd = "" # command to run has_rpm_list = False # flag indicating not to pull the whole repo # detect cases that require special handling if repo.rpm_list != "" and repo.rpm_list != []: has_rpm_list = True # create yum config file for use by reposync dest_path = os.path.join("/var/www/cobbler/repo_mirror", repo.name) temp_path = os.path.join(dest_path, ".origin") if not os.path.isdir(temp_path) and repo.mirror_locally: # FIXME: there's a chance this might break the RHN D/L case os.makedirs(temp_path) # create the config file that yum will use for the copying if repo.mirror_locally: temp_file = self.create_local_file(temp_path, repo, output=False) if not has_rpm_list and repo.mirror_locally: # if we have not requested only certain RPMs, use reposync cmd = "/usr/bin/reposync %s --config=%s --repoid=%s --download_path=%s" % (self.rflags, temp_file, repo.name, "/var/www/cobbler/repo_mirror") if repo.arch != "": if repo.arch == "x86": repo.arch = "i386" # FIX potential arch errors if repo.arch == "i386": # counter-intuitive, but we want the newish kernels too cmd = "%s -a i686" % (cmd) else: cmd = "%s -a %s" % (cmd, repo.arch) elif repo.mirror_locally: # create the output directory if it doesn't exist if not os.path.exists(dest_path): os.makedirs(dest_path) use_source = "" if repo.arch == "src": use_source = "--source" # older yumdownloader sometimes explodes on --resolvedeps # if this happens to you, upgrade yum & yum-utils extra_flags = self.settings.yumdownloader_flags cmd = "/usr/bin/yumdownloader %s %s --disablerepo=* --enablerepo=%s -c %s --destdir=%s %s" % (extra_flags, use_source, repo.name, temp_file, dest_path, " ".join(repo.rpm_list)) # now regardless of whether we're doing yumdownloader or reposync # or whether the repo was http://, ftp://, or rhn://, execute all queued # commands here. Any failure at any point stops the operation. if repo.mirror_locally: rc = utils.subprocess_call(self.logger, cmd) if rc !=0: utils.die(self.logger,"cobbler reposync failed") repodata_path = os.path.join(dest_path, "repodata") if not os.path.exists("/usr/bin/wget"): utils.die(self.logger,"no /usr/bin/wget found, please install wget") # grab repomd.xml and use it to download any metadata we can use cmd2 = "/usr/bin/wget -q %s/repodata/repomd.xml -O %s/repomd.xml" % (repo_mirror, temp_path) rc = utils.subprocess_call(self.logger,cmd2) if rc == 0: # create our repodata directory now, as any extra metadata we're # about to download probably lives there if not os.path.isdir(repodata_path): os.makedirs(repodata_path) rmd = yum.repoMDObject.RepoMD('', "%s/repomd.xml" % (temp_path)) for mdtype in rmd.repoData.keys(): # don't download metadata files that are created by default if mdtype not in ["primary", "primary_db", "filelists", "filelists_db", "other", "other_db"]: mdfile = rmd.getData(mdtype).location[1] cmd3 = "/usr/bin/wget -q %s/%s -O %s/%s" % (repo_mirror, mdfile, dest_path, mdfile) utils.subprocess_call(self.logger,cmd3) if rc !=0: utils.die(self.logger,"wget failed") # now run createrepo to rebuild the index if repo.mirror_locally: os.path.walk(dest_path, self.createrepo_walker, repo) # create the config file the hosts will use to access the repository. self.create_local_file(dest_path, repo) # ==================================================================================== # def apt_sync(self, repo): # # """ # Handle copying of http:// and ftp:// debian repos. # """ # # repo_mirror = repo.mirror # # # warn about not having mirror program. # # mirror_program = "/usr/bin/debmirror" # if not os.path.exists(mirror_program): # utils.die(self.logger,"no %s found, please install it"%(mirror_program)) # # cmd = "" # command to run # has_rpm_list = False # flag indicating not to pull the whole repo # # # detect cases that require special handling # # if repo.rpm_list != "" and repo.rpm_list != []: # utils.die(self.logger,"has_rpm_list not yet supported on apt repos") # # if not repo.arch: # utils.die(self.logger,"Architecture is required for apt repositories") # # # built destination path for the repo # dest_path = os.path.join("/var/www/cobbler/repo_mirror", repo.name) # # if repo.mirror_locally: # mirror = repo.mirror.replace("@@suite@@",repo.os_version) # # idx = mirror.find("://") # method = mirror[:idx] # mirror = mirror[idx+3:] # # idx = mirror.find("/") # host = mirror[:idx] # mirror = mirror[idx+1:] # # idx = mirror.rfind("/dists/") # suite = mirror[idx+7:] # mirror = mirror[:idx] # # mirror_data = "--method=%s --host=%s --root=%s --dist=%s " % ( method , host , mirror , suite ) # # # FIXME : flags should come from repo instead of being hardcoded # # rflags = "--passive --nocleanup" # for x in repo.yumopts: # if repo.yumopts[x]: # rflags += " %s %s" % ( x , repo.yumopts[x] ) # else: # rflags += " %s" % x # cmd = "%s %s %s %s" % (mirror_program, rflags, mirror_data, dest_path) # if repo.arch == "src": # cmd = "%s --source" % cmd # else: # arch = repo.arch # if arch == "x86": # arch = "i386" # FIX potential arch errors # if arch == "x86_64": # arch = "amd64" # FIX potential arch errors # cmd = "%s --nosource -a %s" % (cmd, arch) # # rc = utils.subprocess_call(self.logger, cmd) # if rc !=0: # utils.die(self.logger,"cobbler reposync failed") # ================================================================================== def create_local_file(self, dest_path, repo, output=True): """ Creates Yum config files for use by reposync Two uses: (A) output=True, Create local files that can be used with yum on provisioned clients to make use of this mirror. (B) output=False, Create a temporary file for yum to feed into yum for mirroring """ # the output case will generate repo configuration files which are usable # for the installed systems. They need to be made compatible with --server-override # which means they are actually templates, which need to be rendered by a cobbler-sync # on per profile/system basis. if output: fname = os.path.join(dest_path,"config.repo") else: fname = os.path.join(dest_path, "%s.repo" % repo.name) self.logger.debug("creating: %s" % fname) if not os.path.exists(dest_path): utils.mkdir(dest_path) config_file = open(fname, "w+") config_file.write("[%s]\n" % repo.name) config_file.write("name=%s\n" % repo.name) optenabled = False optgpgcheck = False if output: if repo.mirror_locally: line = "baseurl=http://${server}/cobbler/repo_mirror/%s\n" % (repo.name) else: mstr = repo.mirror if mstr.startswith("/"): mstr = "file://%s" % mstr line = "baseurl=%s\n" % mstr config_file.write(line) # user may have options specific to certain yum plugins # add them to the file for x in repo.yumopts: config_file.write("%s=%s\n" % (x, repo.yumopts[x])) if x == "enabled": optenabled = True if x == "gpgcheck": optgpgcheck = True else: mstr = repo.mirror if mstr.startswith("/"): mstr = "file://%s" % mstr line = "baseurl=%s\n" % mstr if self.settings.http_port not in (80, '80'): http_server = "%s:%s" % (self.settings.server, self.settings.http_port) else: http_server = self.settings.server line = line.replace("@@server@@",http_server) config_file.write(line) if not optenabled: config_file.write("enabled=1\n") config_file.write("priority=%s\n" % repo.priority) # FIXME: potentially might want a way to turn this on/off on a per-repo basis if not optgpgcheck: config_file.write("gpgcheck=0\n") config_file.close() return fname # ================================================================================== def update_permissions(self, repo_path): """ Verifies that permissions and contexts after an rsync are as expected. Sending proper rsync flags should prevent the need for this, though this is largely a safeguard. """ # all_path = os.path.join(repo_path, "*") cmd1 = "chown -R root:apache %s" % repo_path utils.subprocess_call(self.logger, cmd1) cmd2 = "chmod -R 755 %s" % repo_path utils.subprocess_call(self.logger, cmd2)
colloquium/cobbler
cobbler/action_reposync.py
Python
gpl-2.0
22,241
"""Copyright (c) 2017 abhishek-sehgal954 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. """ import sys import os import re import subprocess import math import numpy as np import inkex import simpletransform from PIL import Image, ImageStat, ImageDraw import simplestyle inkex.localize() class ordered_dithering(inkex.Effect): def __init__(self): """Init the effect library and get options from gui.""" inkex.Effect.__init__(self) self.OptionParser.add_option("-t", "--width", action="store", type="int", dest="width", default=200, help="this variable will be used to resize the original selected image to a width of whatever \ you enter and height proportional to the new width, thus maintaining the aspect ratio") self.OptionParser.add_option("--inkscape_path", action="store", type="string", dest="inkscape_path", default="", help="") self.OptionParser.add_option("--temp_path", action="store", type="string", dest="temp_path", default="", help="") def effect(self): outfile = self.options.temp_path curfile = self.args[-1] self.exportPage(curfile,outfile) def draw_rectangle(self,(x, y), (l,b), color, parent, id_): style = {'stroke': 'none', 'stroke-width': '1', 'fill': color,"mix-blend-mode" : "multiply"} attribs = {'style': simplestyle.formatStyle(style), 'x': str(x), 'y': str(y), 'width': str(l), 'height':str(b)} if id_ is not None: attribs.update({'id': id_}) obj = inkex.etree.SubElement(parent, inkex.addNS('rect', 'svg'), attribs) return obj def draw_circle(self,(x, y), r, color, parent, id_): style = {'stroke': 'none', 'stroke-width': '1', 'fill': color,"mix-blend-mode" : "multiply"} attribs = {'style': simplestyle.formatStyle(style), 'cx': str(x), 'cy': str(y), 'r': str(r)} if id_ is not None: attribs.update({'id': id_}) obj = inkex.etree.SubElement(parent, inkex.addNS('circle', 'svg'), attribs) return obj def draw_ellipse(self,(x, y), (r1,r2), color, parent, id_,transform): style = {'stroke': 'none', 'stroke-width': '1', 'fill': color,"mix-blend-mode" : "multiply"} if(transform == 1.5): attribs = {'style': simplestyle.formatStyle(style), 'cx': str(x), 'cy': str(y), 'rx': str(r1), 'ry': str(r2)} elif(transform == 3): attribs = {'style': simplestyle.formatStyle(style), 'cx': str(x), 'cy': str(y), 'rx': str(r1), 'ry': str(r2)} else: attribs = {'style': simplestyle.formatStyle(style), 'cx': str(x), 'cy': str(y), 'rx': str(r1), 'ry': str(r2)} if id_ is not None: attribs.update({'id': id_}) obj = inkex.etree.SubElement(parent, inkex.addNS('ellipse', 'svg'), attribs) return obj def draw_svg(self,output,parent): startu = 0 endu = 0 for i in range(len(output)): for j in range(len(output[i])): if (output[i][j]==0): self.draw_circle((int((startu+startu+1)/2),int((endu+endu+1)/2)),1,'black',parent,'id') #dwg.add(dwg.circle((int((startu+startu+1)/2),int((endu+endu+1)/2)),1,fill='black')) startu = startu+2 endu = endu+2 startu = 0 #dwg.save() def intensity(self,arr): # calcluates intensity of a pixel from 0 to 9 mini = 999 maxi = 0 for i in range(len(arr)): for j in range(len(arr[0])): maxi = max(arr[i][j],maxi) mini = min(arr[i][j],mini) level = float(float(maxi-mini)/float(10)); brr = [[0]*len(arr[0]) for i in range(len(arr))] for i in range(10): l1 = mini+level*i l2 = l1+level for j in range(len(arr)): for k in range(len(arr[0])): if(arr[j][k] >= l1 and arr[j][k] <= l2): brr[j][k]=i return brr def order_dither(self,image): arr = np.asarray(image) brr = self.intensity(arr) crr = [[8, 3, 4], [6, 1, 2], [7, 5, 9]] drr = np.zeros((len(arr),len(arr[0]))) for i in range(len(arr)): for j in range(len(arr[0])): if(brr[i][j] > crr[i%3][j%3]): drr[i][j] = 255 else: drr[i][j] = 0 return drr def dithering(self,node,image): if image: basewidth = self.options.width wpercent = (basewidth/float(image.size[0])) hsize = int((float(image.size[1])*float(wpercent))) image = image.resize((basewidth,hsize), Image.ANTIALIAS) (width, height) = image.size nodeParent = node.getparent() nodeIndex = nodeParent.index(node) pixel2svg_group = inkex.etree.Element(inkex.addNS('g', 'svg')) pixel2svg_group.set('id', "%s_pixel2svg" % node.get('id')) nodeParent.insert(nodeIndex+1, pixel2svg_group) nodeParent.remove(node) image = image.convert("RGBA") pixel_data = image.load() if image.mode == "RGBA": for y in xrange(image.size[1]): for x in xrange(image.size[0]): if pixel_data[x, y][3] < 255: pixel_data[x, y] = (255, 255, 255, 255) image.thumbnail([image.size[0], image.size[1]], Image.ANTIALIAS) image = image.convert('L') self.draw_rectangle((0,0),(width,height),'white',pixel2svg_group,'id') output = self.order_dither(image) self.draw_svg(output,pixel2svg_group) else: inkex.errormsg(_("Bailing out: No supported image file or data found")) sys.exit(1) def exportPage(self, curfile, outfile): command = "%s %s --export-png %s" %(self.options.inkscape_path,curfile,outfile) p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return_code = p.wait() f = p.stdout err = p.stderr img = Image.open(outfile) if (self.options.ids): for node in self.selected.itervalues(): found_image = True self.dithering(node,img) def main(): e = ordered_dithering() e.affect() exit() if __name__=="__main__": main()
abhishek-sehgal954/Inkscape_extensions_for_halftone_filters
SVG_to_SVG/svg_to_svg_ordered_dithering.py
Python
gpl-2.0
7,450
# coding=utf-8 # generate_completion_cache.py - generate cache for dnf bash completion # Copyright © 2013 Elad Alfassa <[email protected]> # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties 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 dnfpluginscore import logger import dnf import os.path class BashCompletionCache(dnf.Plugin): name = 'generate_completion_cache' def __init__(self, base, cli): self.base = base self.available_cache_file = '/var/cache/dnf/available.cache' self.installed_cache_file = '/var/cache/dnf/installed.cache' def _out(self, msg): logger.debug('Completion plugin: %s', msg) def sack(self): ''' Generate cache of available packages ''' # We generate this cache only if the repos were just freshed or if the # cache file doesn't exist fresh = False for repo in self.base.repos.iter_enabled(): if repo.metadata is not None and repo.metadata.fresh: # One fresh repo is enough to cause a regen of the cache fresh = True break if not os.path.exists(self.available_cache_file) or fresh: try: with open(self.available_cache_file, 'w') as cache_file: self._out('Generating completion cache...') available_packages = self.base.sack.query().available() for package in available_packages: cache_file.write(package.name + '\n') except Exception as e: self._out('Can\'t write completion cache: %s' % e) def transaction(self): ''' Generate cache of installed packages ''' try: with open(self.installed_cache_file, 'w') as cache_file: installed_packages = self.base.sack.query().installed() self._out('Generating completion cache...') for package in installed_packages: cache_file.write(package.name + '\n') except Exception as e: self._out('Can\'t write completion cache: %s' % e)
rholy/dnf-plugins-core
plugins/generate_completion_cache.py
Python
gpl-2.0
2,729
from django.conf.urls import * urlpatterns = patterns('foo.views', # Listing URL url(r'^$', view='browse', name='foo.browse'), # Detail URL url(r'^(?P<slug>(?!overview\-)[\w\-\_\.\,]+)/$', view='detail', name='foo.detail'), )
barseghyanartur/django-slim
example/example/foo/urls.py
Python
gpl-2.0
243
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Author: Joseph Herlant <[email protected]> # File name: hdfs_disk_usage_per_datanode.py # Creation date: 2014-10-08 # # Distributed under terms of the GNU GPLv3 license. """ This nagios active check parses the Hadoop HDFS web interface url: http://<namenode>:<port>/dfsnodelist.jsp?whatNodes=LIVE to check for active datanodes that use disk beyond the given thresholds. The output includes performance datas and is truncated if longer than 1024 chars. Tested on: Hadoop CDH3U5 """ __author__ = 'Joseph Herlant' __copyright__ = 'Copyright 2014, Joseph Herlant' __credits__ = ['Joseph Herlant'] __license__ = 'GNU GPLv3' __version__ = '1.0.2' __maintainer__ = 'Joseph Herlant' __email__ = '[email protected]' __status__ = 'Production' __website__ = 'https://github.com/aerostitch/' from mechanize import Browser from BeautifulSoup import BeautifulSoup import argparse, sys if __name__ == '__main__': # use -h argument to get help parser = argparse.ArgumentParser( description='A Nagios check to verify all datanodes disk usage in \ an HDFS cluster from the namenode web interface.') parser.add_argument('-n', '--namenode', required=True, help='hostname of the namenode of the cluster') parser.add_argument('-p', '--port', type=int, default=50070, help='port of the namenode http interface. \ Defaults to 50070.') parser.add_argument('-w', '--warning', type=int, default=80, help='warning threshold. Defaults to 80.') parser.add_argument('-c', '--critical', type=int, default=90, help='critical threshold. Defaults to 90.') args = parser.parse_args() # Get the web page from the namenode url = "http://%s:%d/dfsnodelist.jsp?whatNodes=LIVE" % \ (args.namenode, args.port) try: page = Browser().open(url) except IOError: print 'CRITICAL: Cannot access namenode interface on %s:%d!' % \ (args.namenode, args.port) sys.exit(2) # parse the page html = page.read() soup = BeautifulSoup(html) datanodes = soup.findAll('td', {'class' : 'name'}) pcused = soup.findAll('td', {'class' : 'pcused', 'align' : 'right'}) w_msg = '' c_msg = '' perfdata = '' for (idx, node) in enumerate(datanodes): pct = float(pcused[idx].contents[0].strip()) node = datanodes[idx].findChildren('a')[0].contents[0].strip() if pct >= args.critical: c_msg += ' %s=%.1f%%,' % (node, pct) perfdata += ' %s=%.1f,' % (node, pct) elif pct >= args.warning: w_msg += ' %s=%.1f%%,' % (node, pct) perfdata += ' %s=%.1f,' % (node, pct) else: perfdata += ' %s=%.1f,' % (node, pct) # Prints the values and exits with the nagios exit code if len(c_msg) > 0: print ('CRITICAL:%s%s |%s' % (c_msg, w_msg, perfdata)).strip(',')[:1024] sys.exit(2) elif len(w_msg) > 0: print ('WARNING:%s |%s' % (w_msg, perfdata)).strip(',')[:1024] sys.exit(1) elif len(perfdata) == 0: print 'CRITICAL: Unable to find any node data in the page.' sys.exit(2) else: print ('OK |%s' % (perfdata)).strip(',')[:1024] sys.exit(0)
aerostitch/nagios_checks
hdfs_disk_usage_per_datanode.py
Python
gpl-2.0
3,375
# -*- coding: utf-8 -*- # Asymmetric Base Framework - A collection of utilities for django frameworks # Copyright (C) 2013 Asymmetric Ventures 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; 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. # # 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 __future__ import absolute_import, division, print_function, unicode_literals from django.template.response import TemplateResponse from django.template.context import RequestContext from asymmetricbase.jinja import jinja_env from asymmetricbase.logging import logger #@UnusedImport class JinjaTemplateResponse(TemplateResponse): def resolve_template(self, template): if isinstance(template, (list, tuple)): return jinja_env.select_template(template) elif isinstance(template, basestring): return jinja_env.get_template(template) else: return template def resolve_context(self, context): context = super(JinjaTemplateResponse, self).resolve_context(context) if isinstance(context, RequestContext): context = jinja_env.context_to_dict(context) return context
AsymmetricVentures/asymmetricbase
asymmetricbase/jinja/response.py
Python
gpl-2.0
1,647
#!/usr/bin/env python3 """ * Copyright (c) 2015 BEEVC - Electronic Systems This file is part of BEESOFT * 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. BEESOFT 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 * BEESOFT. If not, see <http://www.gnu.org/licenses/>. """ __author__ = "Marcos Gomes" __license__ = "MIT" import json import FileFinder import pygame class PrinterInfoLoader(): interfaceJson = None lblJson = None lblValJson = None lblFont = None lblFontColor = None lblXPos = None lblYPos = None lblText = None lblValFont = None lblValFontColor = None lblValXPos = None lblValFont = None lblValFontColor = None displayWidth = 480 displayHeight = 320 """************************************************************************* Init Method Inits current screen components *************************************************************************""" def __init__(self, interfaceJson, dispWidth, dispHeight): self.displayWidth = dispWidth self.displayHeight = dispHeight self.interfaceJson = interfaceJson self.lblJson = json.loads(json.dumps(self.interfaceJson['Labels'])) self.lblValJson = json.loads(json.dumps(self.interfaceJson['ValuesSettings'])) """ Values Labels Configuration "X":"220", "FontType":"Bold", "FontSize":"12", "FontColor":"0,0,0" """ self.lblValXPos = int(float(self.lblValJson['X'])*self.displayWidth) lblValFontType = self.lblValJson['FontType'] lblValFontSize = int(float(self.lblValJson['FontSize'])*self.displayHeight) self.lblValFont = self.GetFont(lblValFontType,lblValFontSize) lblValFColor = self.lblValJson['FontColor'] splitColor = lblValFColor.split(",") self.lblValFontColor = pygame.Color(int(splitColor[0]),int(splitColor[1]),int(splitColor[2])) """ Load Labels Configuration """ self.lblText = [] self.lblXPos = [] self.lblYPos = [] self.lblFont = [] self.lblFontColor = [] for lbl in self.lblJson: lblFontType = lbl['FontType'] lblFontSize = int(float(lbl['FontSize'])*self.displayHeight) lblFColor = lbl['FontColor'] self.lblXPos.append(int(float(lbl['X'])*self.displayWidth)) self.lblYPos.append(int(float(lbl['Y'])*self.displayHeight)) self.lblText.append(lbl['Text']) font = self.GetFont(lblFontType,lblFontSize) self.lblFont.append(font) splitColor = lblFColor.split(",") fontColor = pygame.Color(int(splitColor[0]),int(splitColor[1]),int(splitColor[2])) self.lblFontColor.append(fontColor) return """ GetFont """ def GetFont(self,fontType,fontSize): r""" GetFont method Receives as arguments: fontType - Regular,Bold,Italic,Light fontSize - font size Returns: pygame font object """ ff = FileFinder.FileFinder() font = None if fontType == "Regular": font = pygame.font.Font(ff.GetAbsPath("/Fonts/DejaVuSans-Regular.ttf"),fontSize) elif fontType == "Bold": font = pygame.font.Font(ff.GetAbsPath("/Fonts/DejaVuSans-Bold.ttf"),fontSize) elif fontType == "Italic": font = pygame.font.Font(ff.GetAbsPath("/Fonts/DejaVuSans-Italic.ttf"),fontSize) elif fontType == "Light": font = pygame.font.Font(ff.GetAbsPath("/Fonts/DejaVuSans-Light.ttf"),fontSize) return font """ GetlblText(self) returns the list with the label text """ def GetlblText(self): return self.lblText """ GetlblFont """ def GetlblFont(self): return self.lblFont """ GetlblFontColor """ def GetlblFontColor(self): return self.lblFontColor """ GetlblXPos """ def GetlblXPos(self): return self.lblXPos """ GetlblYPos """ def GetlblYPos(self): return self.lblYPos """ GetlblValFont """ def GetlblValFont(self): return self.lblValFont """ GetlblValFontColor """ def GetlblValFontColor(self): return self.lblValFontColor """ GetlblValXPos """ def GetlblValXPos(self): return self.lblValXPos
beeverycreative/beeconnect
Loaders/PrinterInfoLoader.py
Python
gpl-2.0
5,218
# # Copyright (C) 2006-2008, 2013 Red Hat, Inc. # Copyright (C) 2006 Daniel P. Berrange <[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. # import logging import traceback # pylint: disable=E0611 from gi.repository import GObject from gi.repository import Gtk from gi.repository import Gdk # pylint: enable=E0611 import libvirt import virtManager.uihelpers as uihelpers from virtManager.storagebrowse import vmmStorageBrowser from virtManager.baseclass import vmmGObjectUI from virtManager.addhardware import vmmAddHardware from virtManager.choosecd import vmmChooseCD from virtManager.console import vmmConsolePages from virtManager.serialcon import vmmSerialConsole from virtManager.graphwidgets import Sparkline from virtManager import util as util import virtinst # Parameters that can be editted in the details window EDIT_TOTAL = 37 (EDIT_NAME, EDIT_ACPI, EDIT_APIC, EDIT_CLOCK, EDIT_MACHTYPE, EDIT_SECURITY, EDIT_DESC, EDIT_VCPUS, EDIT_CPUSET, EDIT_CPU, EDIT_TOPOLOGY, EDIT_MEM, EDIT_AUTOSTART, EDIT_BOOTORDER, EDIT_BOOTMENU, EDIT_KERNEL, EDIT_INIT, EDIT_DISK_RO, EDIT_DISK_SHARE, EDIT_DISK_CACHE, EDIT_DISK_IO, EDIT_DISK_BUS, EDIT_DISK_SERIAL, EDIT_DISK_FORMAT, EDIT_DISK_IOTUNE, EDIT_SOUND_MODEL, EDIT_SMARTCARD_MODE, EDIT_NET_MODEL, EDIT_NET_VPORT, EDIT_NET_SOURCE, EDIT_GFX_PASSWD, EDIT_GFX_TYPE, EDIT_GFX_KEYMAP, EDIT_VIDEO_MODEL, EDIT_WATCHDOG_MODEL, EDIT_WATCHDOG_ACTION, EDIT_CONTROLLER_MODEL ) = range(EDIT_TOTAL) # Columns in hw list model HW_LIST_COL_LABEL = 0 HW_LIST_COL_ICON_NAME = 1 HW_LIST_COL_ICON_SIZE = 2 HW_LIST_COL_TYPE = 3 HW_LIST_COL_DEVICE = 4 # Types for the hw list model: numbers specify what order they will be listed HW_LIST_TYPE_GENERAL = 0 HW_LIST_TYPE_STATS = 1 HW_LIST_TYPE_CPU = 2 HW_LIST_TYPE_MEMORY = 3 HW_LIST_TYPE_BOOT = 4 HW_LIST_TYPE_DISK = 5 HW_LIST_TYPE_NIC = 6 HW_LIST_TYPE_INPUT = 7 HW_LIST_TYPE_GRAPHICS = 8 HW_LIST_TYPE_SOUND = 9 HW_LIST_TYPE_CHAR = 10 HW_LIST_TYPE_HOSTDEV = 11 HW_LIST_TYPE_VIDEO = 12 HW_LIST_TYPE_WATCHDOG = 13 HW_LIST_TYPE_CONTROLLER = 14 HW_LIST_TYPE_FILESYSTEM = 15 HW_LIST_TYPE_SMARTCARD = 16 HW_LIST_TYPE_REDIRDEV = 17 remove_pages = [HW_LIST_TYPE_NIC, HW_LIST_TYPE_INPUT, HW_LIST_TYPE_GRAPHICS, HW_LIST_TYPE_SOUND, HW_LIST_TYPE_CHAR, HW_LIST_TYPE_HOSTDEV, HW_LIST_TYPE_DISK, HW_LIST_TYPE_VIDEO, HW_LIST_TYPE_WATCHDOG, HW_LIST_TYPE_CONTROLLER, HW_LIST_TYPE_FILESYSTEM, HW_LIST_TYPE_SMARTCARD, HW_LIST_TYPE_REDIRDEV] # Boot device columns BOOT_DEV_TYPE = 0 BOOT_LABEL = 1 BOOT_ICON = 2 BOOT_ACTIVE = 3 # Main tab pages PAGE_CONSOLE = 0 PAGE_DETAILS = 1 PAGE_DYNAMIC_OFFSET = 2 def prettyify_disk_bus(bus): if bus in ["ide", "sata", "scsi", "usb"]: return bus.upper() if bus in ["xen"]: return bus.capitalize() if bus == "virtio": return "VirtIO" if bus == "spapr-vscsi": return "vSCSI" return bus def prettyify_disk(devtype, bus, idx): busstr = prettyify_disk_bus(bus) or "" if devtype == "floppy": devstr = "Floppy" busstr = "" elif devtype == "cdrom": devstr = "CDROM" else: devstr = devtype.capitalize() if busstr: ret = "%s %s" % (busstr, devstr) else: ret = devstr return "%s %s" % (ret, idx) def safeint(val, fmt="%.3d"): try: int(val) except: return str(val) return fmt % int(val) def prettyify_bytes(val): if val > (1024 * 1024 * 1024): return "%2.2f GB" % (val / (1024.0 * 1024.0 * 1024.0)) else: return "%2.2f MB" % (val / (1024.0 * 1024.0)) def build_redir_label(redirdev): # String shown in the devices details section addrlabel = "" # String shown in the VMs hardware list hwlabel = "" if redirdev.type == 'spicevmc': addrlabel = None elif redirdev.type == 'tcp': addrlabel += _("%s:%s") % (redirdev.host, redirdev.service) else: raise RuntimeError("unhandled redirection kind: %s" % redirdev.type) hwlabel = _("Redirected %s") % redirdev.bus.upper() return addrlabel, hwlabel def build_hostdev_label(hostdev): # String shown in the devices details section srclabel = "" # String shown in the VMs hardware list hwlabel = "" typ = hostdev.type vendor = hostdev.vendor product = hostdev.product addrbus = hostdev.bus addrdev = hostdev.device addrslt = hostdev.slot addrfun = hostdev.function addrdom = hostdev.domain def dehex(val): if val.startswith("0x"): val = val[2:] return val hwlabel = typ.upper() srclabel = typ.upper() if vendor and product: # USB by vendor + product devstr = " %s:%s" % (dehex(vendor), dehex(product)) srclabel += devstr hwlabel += devstr elif addrbus and addrdev: # USB by bus + dev srclabel += (" Bus %s Device %s" % (safeint(addrbus), safeint(addrdev))) hwlabel += " %s:%s" % (safeint(addrbus), safeint(addrdev)) elif addrbus and addrslt and addrfun and addrdom: # PCI by bus:slot:function devstr = (" %s:%s:%s.%s" % (dehex(addrdom), dehex(addrbus), dehex(addrslt), dehex(addrfun))) srclabel += devstr hwlabel += devstr return srclabel, hwlabel def lookup_nodedev(vmmconn, hostdev): def intify(val, do_hex=False): try: if do_hex: return int(val or '0x00', 16) else: return int(val) except: return -1 def attrVal(node, attr): if not hasattr(node, attr): return None return getattr(node, attr) devtype = hostdev.type found_dev = None vendor_id = product_id = bus = device = \ domain = slot = func = None # For USB we want a device, not a bus if devtype == 'usb': devtype = 'usb_device' vendor_id = hostdev.vendor or -1 product_id = hostdev.product or -1 bus = intify(hostdev.bus) device = intify(hostdev.device) elif devtype == 'pci': domain = intify(hostdev.domain, True) bus = intify(hostdev.bus, True) slot = intify(hostdev.slot, True) func = intify(hostdev.function, True) devs = vmmconn.get_nodedevs(devtype, None) for dev in devs: # Try to match with product_id|vendor_id|bus|device if (attrVal(dev, "product_id") == product_id and attrVal(dev, "vendor_id") == vendor_id and attrVal(dev, "bus") == bus and attrVal(dev, "device") == device): found_dev = dev break else: # Try to get info from bus/addr dev_id = intify(attrVal(dev, "device")) bus_id = intify(attrVal(dev, "bus")) dom_id = intify(attrVal(dev, "domain")) func_id = intify(attrVal(dev, "function")) slot_id = intify(attrVal(dev, "slot")) if ((dev_id == device and bus_id == bus) or (dom_id == domain and func_id == func and bus_id == bus and slot_id == slot)): found_dev = dev break return found_dev class vmmDetails(vmmGObjectUI): __gsignals__ = { "action-save-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]), "action-destroy-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]), "action-suspend-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]), "action-resume-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]), "action-run-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]), "action-shutdown-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]), "action-reset-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]), "action-reboot-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]), "action-exit-app": (GObject.SignalFlags.RUN_FIRST, None, []), "action-view-manager": (GObject.SignalFlags.RUN_FIRST, None, []), "action-migrate-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]), "action-clone-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]), "details-closed": (GObject.SignalFlags.RUN_FIRST, None, []), "details-opened": (GObject.SignalFlags.RUN_FIRST, None, []), "customize-finished": (GObject.SignalFlags.RUN_FIRST, None, []), } def __init__(self, vm, parent=None): vmmGObjectUI.__init__(self, "vmm-details.ui", "vmm-details") self.vm = vm self.conn = self.vm.conn self.is_customize_dialog = False if parent: # Details window is being abused as a 'configure before install' # dialog, set things as appropriate self.is_customize_dialog = True self.topwin.set_type_hint(Gdk.WindowTypeHint.DIALOG) self.topwin.set_transient_for(parent) self.widget("toolbar-box").show() self.widget("customize-toolbar").show() self.widget("details-toolbar").hide() self.widget("details-menubar").hide() pages = self.widget("details-pages") pages.set_current_page(PAGE_DETAILS) self.active_edits = [] self.serial_tabs = [] self.last_console_page = PAGE_CONSOLE self.addhw = None self.media_choosers = {"cdrom": None, "floppy": None} self.storage_browser = None self.ignorePause = False self.ignoreDetails = False self._cpu_copy_host = False self.console = vmmConsolePages(self.vm, self.builder, self.topwin) # Set default window size w, h = self.vm.get_details_window_size() self.topwin.set_default_size(w or 800, h or 600) self.oldhwkey = None self.addhwmenu = None self.keycombo_menu = None self.init_menus() self.init_details() self.cpu_usage_graph = None self.memory_usage_graph = None self.disk_io_graph = None self.network_traffic_graph = None self.init_graphs() self.builder.connect_signals({ "on_close_details_clicked": self.close, "on_details_menu_close_activate": self.close, "on_vmm_details_delete_event": self.close, "on_vmm_details_configure_event": self.window_resized, "on_details_menu_quit_activate": self.exit_app, "on_control_vm_details_toggled": self.details_console_changed, "on_control_vm_console_toggled": self.details_console_changed, "on_control_run_clicked": self.control_vm_run, "on_control_shutdown_clicked": self.control_vm_shutdown, "on_control_pause_toggled": self.control_vm_pause, "on_control_fullscreen_toggled": self.control_fullscreen, "on_details_customize_finish_clicked": self.customize_finish, "on_details_cancel_customize_clicked": self.close, "on_details_menu_run_activate": self.control_vm_run, "on_details_menu_poweroff_activate": self.control_vm_shutdown, "on_details_menu_reboot_activate": self.control_vm_reboot, "on_details_menu_save_activate": self.control_vm_save, "on_details_menu_reset_activate": self.control_vm_reset, "on_details_menu_destroy_activate": self.control_vm_destroy, "on_details_menu_pause_activate": self.control_vm_pause, "on_details_menu_clone_activate": self.control_vm_clone, "on_details_menu_migrate_activate": self.control_vm_migrate, "on_details_menu_screenshot_activate": self.control_vm_screenshot, "on_details_menu_view_toolbar_activate": self.toggle_toolbar, "on_details_menu_view_manager_activate": self.view_manager, "on_details_menu_view_details_toggled": self.details_console_changed, "on_details_menu_view_console_toggled": self.details_console_changed, "on_details_pages_switch_page": self.switch_page, "on_overview_name_changed": lambda *x: self.enable_apply(x, EDIT_NAME), "on_overview_acpi_changed": self.config_acpi_changed, "on_overview_apic_changed": self.config_apic_changed, "on_overview_clock_changed": lambda *x: self.enable_apply(x, EDIT_CLOCK), "on_machine_type_changed": lambda *x: self.enable_apply(x, EDIT_MACHTYPE), "on_security_label_changed": lambda *x: self.enable_apply(x, EDIT_SECURITY), "on_security_relabel_changed": lambda *x: self.enable_apply(x, EDIT_SECURITY), "on_security_type_changed": self.security_type_changed, "on_config_vcpus_changed": self.config_vcpus_changed, "on_config_maxvcpus_changed": self.config_maxvcpus_changed, "on_config_vcpupin_changed": lambda *x: self.enable_apply(x, EDIT_CPUSET), "on_config_vcpupin_generate_clicked": self.config_vcpupin_generate, "on_cpu_model_changed": lambda *x: self.enable_apply(x, EDIT_CPU), "on_cpu_cores_changed": lambda *x: self.enable_apply(x, EDIT_TOPOLOGY), "on_cpu_sockets_changed": lambda *x: self.enable_apply(x, EDIT_TOPOLOGY), "on_cpu_threads_changed": lambda *x: self.enable_apply(x, EDIT_TOPOLOGY), "on_cpu_copy_host_clicked": self.config_cpu_copy_host, "on_cpu_topology_enable_toggled": self.config_cpu_topology_enable, "on_config_memory_changed": self.config_memory_changed, "on_config_maxmem_changed": self.config_maxmem_changed, "on_config_boot_moveup_clicked" : lambda *x: self.config_boot_move(x, True), "on_config_boot_movedown_clicked" : lambda *x: self.config_boot_move(x, False), "on_config_autostart_changed": lambda *x: self.enable_apply(x, x, EDIT_AUTOSTART), "on_boot_menu_changed": lambda *x: self.enable_apply(x, EDIT_BOOTMENU), "on_boot_kernel_changed": lambda *x: self.enable_apply(x, EDIT_KERNEL), "on_boot_kernel_initrd_changed": lambda *x: self.enable_apply(x, EDIT_KERNEL), "on_boot_kernel_args_changed": lambda *x: self.enable_apply(x, EDIT_KERNEL), "on_boot_kernel_browse_clicked": self.browse_kernel, "on_boot_kernel_initrd_browse_clicked": self.browse_initrd, "on_boot_init_path_changed": lambda *x: self.enable_apply(x, EDIT_INIT), "on_disk_readonly_changed": lambda *x: self.enable_apply(x, EDIT_DISK_RO), "on_disk_shareable_changed": lambda *x: self.enable_apply(x, EDIT_DISK_SHARE), "on_disk_cache_combo_changed": lambda *x: self.enable_apply(x, EDIT_DISK_CACHE), "on_disk_io_combo_changed": lambda *x: self.enable_apply(x, EDIT_DISK_IO), "on_disk_bus_combo_changed": lambda *x: self.enable_apply(x, EDIT_DISK_BUS), "on_disk_format_changed": lambda *x: self.enable_apply(x, EDIT_DISK_FORMAT), "on_disk_serial_changed": lambda *x: self.enable_apply(x, EDIT_DISK_SERIAL), "on_disk_iotune_changed": self.iotune_changed, "on_network_source_combo_changed": lambda *x: self.enable_apply(x, EDIT_NET_SOURCE), "on_network_bridge_changed": lambda *x: self.enable_apply(x, EDIT_NET_SOURCE), "on_network-source-mode-combo_changed": lambda *x: self.enable_apply(x, EDIT_NET_SOURCE), "on_network_model_combo_changed": lambda *x: self.enable_apply(x, EDIT_NET_MODEL), "on_vport_type_changed": lambda *x: self.enable_apply(x, EDIT_NET_VPORT), "on_vport_managerid_changed": lambda *x: self.enable_apply(x, EDIT_NET_VPORT), "on_vport_typeid_changed": lambda *x: self.enable_apply(x, EDIT_NET_VPORT), "on_vport_typeidversion_changed": lambda *x: self.enable_apply(x, EDIT_NET_VPORT), "on_vport_instanceid_changed": lambda *x: self.enable_apply(x, EDIT_NET_VPORT), "on_gfx_type_combo_changed": lambda *x: self.enable_apply(x, EDIT_GFX_TYPE), "on_vnc_keymap_combo_changed": lambda *x: self.enable_apply(x, EDIT_GFX_KEYMAP), "on_vnc_password_changed": lambda *x: self.enable_apply(x, EDIT_GFX_PASSWD), "on_sound_model_combo_changed": lambda *x: self.enable_apply(x, EDIT_SOUND_MODEL), "on_video_model_combo_changed": lambda *x: self.enable_apply(x, EDIT_VIDEO_MODEL), "on_watchdog_model_combo_changed": lambda *x: self.enable_apply(x, EDIT_WATCHDOG_MODEL), "on_watchdog_action_combo_changed": lambda *x: self.enable_apply(x, EDIT_WATCHDOG_ACTION), "on_smartcard_mode_combo_changed": lambda *x: self.enable_apply(x, EDIT_SMARTCARD_MODE), "on_config_apply_clicked": self.config_apply, "on_config_cancel_clicked": self.config_cancel, "on_config_cdrom_connect_clicked": self.toggle_storage_media, "on_config_remove_clicked": self.remove_xml_dev, "on_add_hardware_button_clicked": self.add_hardware, "on_hw_list_button_press_event": self.popup_addhw_menu, # Listeners stored in vmmConsolePages "on_details_menu_view_fullscreen_activate": self.console.toggle_fullscreen, "on_details_menu_view_size_to_vm_activate": self.console.size_to_vm, "on_details_menu_view_scale_always_toggled": self.console.set_scale_type, "on_details_menu_view_scale_fullscreen_toggled": self.console.set_scale_type, "on_details_menu_view_scale_never_toggled": self.console.set_scale_type, "on_console_pages_switch_page": self.console.page_changed, "on_console_auth_password_activate": self.console.auth_login, "on_console_auth_login_clicked": self.console.auth_login, "on_controller_model_combo_changed": lambda *x: self.enable_apply(x, EDIT_CONTROLLER_MODEL), }) # Deliberately keep all this after signal connection self.vm.connect("status-changed", self.refresh_vm_state) self.vm.connect("config-changed", self.refresh_vm_state) self.vm.connect("resources-sampled", self.refresh_resources) self.widget("hw-list").get_selection().connect("changed", self.hw_changed) self.widget("config-boot-list").get_selection().connect( "changed", self.config_bootdev_selected) finish_img = Gtk.Image.new_from_stock(Gtk.STOCK_ADD, Gtk.IconSize.BUTTON) self.widget("add-hardware-button").set_image(finish_img) self.populate_hw_list() self.repopulate_boot_list() self.hw_selected() self.refresh_vm_state() def _cleanup(self): self.oldhwkey = None if self.addhw: self.addhw.cleanup() self.addhw = None if self.storage_browser: self.storage_browser.cleanup() self.storage_browser = None for key in self.media_choosers: if self.media_choosers[key]: self.media_choosers[key].cleanup() self.media_choosers = {} for serial in self.serial_tabs: self._close_serial_tab(serial) self.console.cleanup() self.console = None self.vm = None self.conn = None self.addhwmenu = None def show(self): logging.debug("Showing VM details: %s", self.vm) vis = self.is_visible() self.topwin.present() if vis: return self.emit("details-opened") self.refresh_vm_state() def customize_finish(self, src): ignore = src if self.has_unapplied_changes(self.get_hw_row()): return return self._close(customize_finish=True) def close(self, ignore1=None, ignore2=None): logging.debug("Closing VM details: %s", self.vm) return self._close() def _close(self, customize_finish=False): fs = self.widget("details-menu-view-fullscreen") if fs.get_active(): fs.set_active(False) if not self.is_visible(): return self.topwin.hide() if (self.console.viewer and self.console.viewer.display and self.console.viewer.display.get_visible()): try: self.console.close_viewer() except: logging.error("Failure when disconnecting from desktop server") if customize_finish: self.emit("customize-finished") else: self.emit("details-closed") return 1 def is_visible(self): return bool(self.topwin.get_visible()) ########################## # Initialization helpers # ########################## def init_menus(self): # Shutdown button menu uihelpers.build_shutdown_button_menu(self.widget("control-shutdown"), self.control_vm_shutdown, self.control_vm_reboot, self.control_vm_reset, self.control_vm_destroy, self.control_vm_save) for name in ["details-menu-shutdown", "details-menu-reboot", "details-menu-reset", "details-menu-poweroff", "details-menu-destroy"]: image = Gtk.Image.new_from_icon_name("system-shutdown", Gtk.IconSize.MENU) self.widget(name).set_image(image) # Add HW popup menu self.addhwmenu = Gtk.Menu() addHW = Gtk.ImageMenuItem(_("_Add Hardware")) addHW.set_use_underline(True) addHWImg = Gtk.Image() addHWImg.set_from_stock(Gtk.STOCK_ADD, Gtk.IconSize.MENU) addHW.set_image(addHWImg) addHW.show() addHW.connect("activate", self.add_hardware) rmHW = Gtk.ImageMenuItem(_("_Remove Hardware")) rmHW.set_use_underline(True) rmHWImg = Gtk.Image() rmHWImg.set_from_stock(Gtk.STOCK_REMOVE, Gtk.IconSize.MENU) rmHW.set_image(rmHWImg) rmHW.show() rmHW.connect("activate", self.remove_xml_dev) self.addhwmenu.add(addHW) self.addhwmenu.add(rmHW) # Serial list menu smenu = Gtk.Menu() smenu.connect("show", self.populate_serial_menu) self.widget("details-menu-view-serial-list").set_submenu(smenu) # Don't allowing changing network/disks for Dom0 dom0 = self.vm.is_management_domain() self.widget("add-hardware-button").set_sensitive(not dom0) self.widget("hw-panel").set_show_tabs(False) self.widget("details-pages").set_show_tabs(False) self.widget("console-pages").set_show_tabs(False) self.widget("details-menu-view-toolbar").set_active( self.config.get_details_show_toolbar()) # Keycombo menu (ctrl+alt+del etc.) self.keycombo_menu = uihelpers.build_keycombo_menu( self.console.send_key) self.widget("details-menu-send-key").set_submenu(self.keycombo_menu) def init_graphs(self): graph_table = self.widget("graph-table") self.cpu_usage_graph = Sparkline() self.cpu_usage_graph.set_property("reversed", True) graph_table.attach(self.cpu_usage_graph, 1, 2, 0, 1) self.memory_usage_graph = Sparkline() self.memory_usage_graph.set_property("reversed", True) graph_table.attach(self.memory_usage_graph, 1, 2, 1, 2) self.disk_io_graph = Sparkline() self.disk_io_graph.set_property("reversed", True) self.disk_io_graph.set_property("filled", False) self.disk_io_graph.set_property("num_sets", 2) self.disk_io_graph.set_property("rgb", [x / 255.0 for x in [0x82, 0x00, 0x3B, 0x29, 0x5C, 0x45]]) graph_table.attach(self.disk_io_graph, 1, 2, 2, 3) self.network_traffic_graph = Sparkline() self.network_traffic_graph.set_property("reversed", True) self.network_traffic_graph.set_property("filled", False) self.network_traffic_graph.set_property("num_sets", 2) self.network_traffic_graph.set_property("rgb", [x / 255.0 for x in [0x82, 0x00, 0x3B, 0x29, 0x5C, 0x45]]) graph_table.attach(self.network_traffic_graph, 1, 2, 3, 4) graph_table.show_all() def init_details(self): # Hardware list # [ label, icon name, icon size, hw type, hw data/class] hw_list_model = Gtk.ListStore(str, str, int, int, object) self.widget("hw-list").set_model(hw_list_model) hwCol = Gtk.TreeViewColumn("Hardware") hwCol.set_spacing(6) hwCol.set_min_width(165) hw_txt = Gtk.CellRendererText() hw_img = Gtk.CellRendererPixbuf() hwCol.pack_start(hw_img, False) hwCol.pack_start(hw_txt, True) hwCol.add_attribute(hw_txt, 'text', HW_LIST_COL_LABEL) hwCol.add_attribute(hw_img, 'stock-size', HW_LIST_COL_ICON_SIZE) hwCol.add_attribute(hw_img, 'icon-name', HW_LIST_COL_ICON_NAME) self.widget("hw-list").append_column(hwCol) # Description text view desc = self.widget("overview-description") buf = Gtk.TextBuffer() buf.connect("changed", self.enable_apply, EDIT_DESC) desc.set_buffer(buf) # List of applications. apps_list = self.widget("inspection-apps") apps_model = Gtk.ListStore(str, str, str) apps_list.set_model(apps_model) name_col = Gtk.TreeViewColumn(_("Name")) version_col = Gtk.TreeViewColumn(_("Version")) summary_col = Gtk.TreeViewColumn() apps_list.append_column(name_col) apps_list.append_column(version_col) apps_list.append_column(summary_col) name_text = Gtk.CellRendererText() name_col.pack_start(name_text, True) name_col.add_attribute(name_text, 'text', 0) name_col.set_sort_column_id(0) version_text = Gtk.CellRendererText() version_col.pack_start(version_text, True) version_col.add_attribute(version_text, 'text', 1) version_col.set_sort_column_id(1) summary_text = Gtk.CellRendererText() summary_col.pack_start(summary_text, True) summary_col.add_attribute(summary_text, 'text', 2) summary_col.set_sort_column_id(2) # Clock combo clock_combo = self.widget("overview-clock-combo") clock_model = Gtk.ListStore(str) clock_combo.set_model(clock_model) text = Gtk.CellRendererText() clock_combo.pack_start(text, True) clock_combo.add_attribute(text, 'text', 0) clock_model.set_sort_column_id(0, Gtk.SortType.ASCENDING) for offset in ["localtime", "utc"]: clock_model.append([offset]) arch = self.vm.get_arch() caps = self.vm.conn.get_capabilities() machines = [] if len(caps.guests) > 0: for guest in caps.guests: if len(guest.domains) > 0: for domain in guest.domains: machines = list(set(machines + domain.machines)) if arch in ["i686", "x86_64"]: self.widget("label81").hide() self.widget("hbox30").hide() else: machtype_combo = self.widget("machine-type-combo") machtype_model = Gtk.ListStore(str) machtype_combo.set_model(machtype_model) text = Gtk.CellRendererText() machtype_combo.pack_start(text, True) machtype_combo.add_attribute(text, 'text', 0) machtype_model.set_sort_column_id(0, Gtk.SortType.ASCENDING) if len(machines) > 0: for machine in machines: machtype_model.append([machine]) # Security info tooltips self.widget("security-static-info").set_tooltip_text( _("Static SELinux security type tells libvirt to always start the guest process with the specified label. Unless 'relabel' is set, the administrator is responsible for making sure the images are labeled correctly on disk.")) self.widget("security-dynamic-info").set_tooltip_text( _("The dynamic SELinux security type tells libvirt to automatically pick a unique label for the guest process and guest image, ensuring total isolation of the guest. (Default)")) # VCPU Pinning list generate_cpuset = self.widget("config-vcpupin-generate") generate_warn = self.widget("config-vcpupin-generate-err") if not self.conn.get_capabilities().host.topology: generate_cpuset.set_sensitive(False) generate_warn.show() generate_warn.set_tooltip_text(_("Libvirt did not detect NUMA capabilities.")) # [ VCPU #, Currently running on Phys CPU #, CPU Pinning list ] vcpu_list = self.widget("config-vcpu-list") vcpu_model = Gtk.ListStore(str, str, str) vcpu_list.set_model(vcpu_model) vcpuCol = Gtk.TreeViewColumn(_("VCPU")) physCol = Gtk.TreeViewColumn(_("On CPU")) pinCol = Gtk.TreeViewColumn(_("Pinning")) vcpu_list.append_column(vcpuCol) vcpu_list.append_column(physCol) vcpu_list.append_column(pinCol) vcpu_text = Gtk.CellRendererText() vcpuCol.pack_start(vcpu_text, True) vcpuCol.add_attribute(vcpu_text, 'text', 0) vcpuCol.set_sort_column_id(0) phys_text = Gtk.CellRendererText() physCol.pack_start(phys_text, True) physCol.add_attribute(phys_text, 'text', 1) physCol.set_sort_column_id(1) pin_text = Gtk.CellRendererText() pin_text.set_property("editable", True) pin_text.connect("edited", self.config_vcpu_pin) pinCol.pack_start(pin_text, True) pinCol.add_attribute(pin_text, 'text', 2) # Boot device list boot_list = self.widget("config-boot-list") # model = [ XML boot type, display name, icon name, enabled ] boot_list_model = Gtk.ListStore(str, str, str, bool) boot_list.set_model(boot_list_model) chkCol = Gtk.TreeViewColumn() txtCol = Gtk.TreeViewColumn() boot_list.append_column(chkCol) boot_list.append_column(txtCol) chk = Gtk.CellRendererToggle() chk.connect("toggled", self.config_boot_toggled) chkCol.pack_start(chk, False) chkCol.add_attribute(chk, 'active', BOOT_ACTIVE) icon = Gtk.CellRendererPixbuf() txtCol.pack_start(icon, False) txtCol.add_attribute(icon, 'icon-name', BOOT_ICON) text = Gtk.CellRendererText() txtCol.pack_start(text, True) txtCol.add_attribute(text, 'text', BOOT_LABEL) txtCol.add_attribute(text, 'sensitive', BOOT_ACTIVE) no_default = not self.is_customize_dialog # CPU features caps = self.vm.conn.get_capabilities() cpu_values = None cpu_names = [] all_features = [] try: cpu_values = caps.get_cpu_values(self.vm.get_arch()) cpu_names = sorted([c.model for c in cpu_values.cpus], key=str.lower) all_features = cpu_values.features except: logging.exception("Error populating CPU model list") # [ feature name, mode] feat_list = self.widget("cpu-features") feat_model = Gtk.ListStore(str, str) feat_list.set_model(feat_model) nameCol = Gtk.TreeViewColumn() polCol = Gtk.TreeViewColumn() polCol.set_min_width(80) feat_list.append_column(nameCol) feat_list.append_column(polCol) # Feature name col name_text = Gtk.CellRendererText() nameCol.pack_start(name_text, True) nameCol.add_attribute(name_text, 'text', 0) nameCol.set_sort_column_id(0) # Feature policy col feat_combo = Gtk.CellRendererCombo() m = Gtk.ListStore(str) for p in virtinst.CPUFeature.POLICIES: m.append([p]) m.append(["default"]) feat_combo.set_property("model", m) feat_combo.set_property("text-column", 0) feat_combo.set_property("editable", True) polCol.pack_start(feat_combo, False) polCol.add_attribute(feat_combo, 'text', 1) polCol.set_sort_column_id(1) def feature_changed(src, index, treeiter, model): model[index][1] = src.get_property("model")[treeiter][0] self.enable_apply(EDIT_CPU) feat_combo.connect("changed", feature_changed, feat_model) for name in all_features: feat_model.append([name, "default"]) # CPU model combo cpu_model = self.widget("cpu-model") model = Gtk.ListStore(str, object) cpu_model.set_model(model) cpu_model.set_entry_text_column(0) model.set_sort_column_id(0, Gtk.SortType.ASCENDING) for name in cpu_names: model.append([name, cpu_values.get_cpu(name)]) # Disk cache combo disk_cache = self.widget("disk-cache-combo") uihelpers.build_cache_combo(self.vm, disk_cache) # Disk io combo disk_io = self.widget("disk-io-combo") uihelpers.build_io_combo(self.vm, disk_io) # Disk format combo format_list = self.widget("disk-format") uihelpers.build_storage_format_combo(self.vm, format_list) # Disk bus combo disk_bus = self.widget("disk-bus-combo") uihelpers.build_disk_bus_combo(self.vm, disk_bus) # Disk iotune expander if not (self.conn.is_qemu() or self.conn.is_test_conn()): self.widget("iotune-expander").set_property("visible", False) # Network source net_source = self.widget("network-source-combo") net_bridge = self.widget("network-bridge-box") source_mode_box = self.widget("network-source-mode-box") source_mode_label = self.widget("network-source-mode") vport_expander = self.widget("vport-expander") uihelpers.init_network_list(net_source, net_bridge, source_mode_box, source_mode_label, vport_expander) # source mode source_mode = self.widget("network-source-mode-combo") uihelpers.build_source_mode_combo(self.vm, source_mode) # Network model net_model = self.widget("network-model-combo") uihelpers.build_netmodel_combo(self.vm, net_model) # Graphics type gfx_type = self.widget("gfx-type-combo") model = Gtk.ListStore(str, str) gfx_type.set_model(model) text = Gtk.CellRendererText() gfx_type.pack_start(text, True) gfx_type.add_attribute(text, 'text', 1) model.append([virtinst.VirtualGraphics.TYPE_VNC, "VNC"]) model.append([virtinst.VirtualGraphics.TYPE_SPICE, "Spice"]) gfx_type.set_active(-1) # Graphics keymap gfx_keymap = self.widget("gfx-keymap-combo") uihelpers.build_vnc_keymap_combo(self.vm, gfx_keymap, no_default=no_default) # Sound model sound_dev = self.widget("sound-model-combo") uihelpers.build_sound_combo(self.vm, sound_dev, no_default=no_default) # Video model combo video_dev = self.widget("video-model-combo") uihelpers.build_video_combo(self.vm, video_dev, no_default=no_default) # Watchdog model combo combo = self.widget("watchdog-model-combo") uihelpers.build_watchdogmodel_combo(self.vm, combo, no_default=no_default) # Watchdog action combo combo = self.widget("watchdog-action-combo") uihelpers.build_watchdogaction_combo(self.vm, combo, no_default=no_default) # Smartcard mode sc_mode = self.widget("smartcard-mode-combo") uihelpers.build_smartcard_mode_combo(self.vm, sc_mode) # Redirection type combo = self.widget("redir-type-combo") uihelpers.build_redir_type_combo(self.vm, combo) # Controller model combo = self.widget("controller-model-combo") model = Gtk.ListStore(str, str) combo.set_model(model) text = Gtk.CellRendererText() combo.pack_start(text, True) combo.add_attribute(text, 'text', 1) combo.set_active(-1) # Helper function to handle the combo/label pattern used for # video model, sound model, network model, etc. def set_combo_label(self, prefix, value, model_idx=0, label="", comparefunc=None): label = label or value model_label = self.widget(prefix + "-label") model_combo = self.widget(prefix + "-combo") idx = -1 if comparefunc: model_in_list, idx = comparefunc(model_combo.get_model(), value) else: model_list = [x[model_idx] for x in model_combo.get_model()] model_in_list = (value in model_list) if model_in_list: idx = model_list.index(value) model_label.set_property("visible", not model_in_list) model_combo.set_property("visible", model_in_list) model_label.set_text(label or "") if model_in_list: model_combo.set_active(idx) else: model_combo.set_active(-1) # Helper for accessing value of combo/label pattern def get_combo_value(self, widgetname, model_idx=0): combo = self.widget(widgetname) if combo.get_active() < 0: return None return combo.get_model()[combo.get_active()][model_idx] def get_combo_label_value(self, prefix, model_idx=0): comboname = prefix + "-combo" label = self.widget(prefix + "-label") value = None if label.get_property("visible"): value = label.get_text() else: value = self.get_combo_value(comboname, model_idx) return value ########################## # Window state listeners # ########################## def window_resized(self, ignore, event): # Sometimes dimensions change when window isn't visible if not self.is_visible(): return self.vm.set_details_window_size(event.width, event.height) def popup_addhw_menu(self, widget, event): ignore = widget if event.button != 3: return self.addhwmenu.popup(None, None, None, None, 0, event.time) def build_serial_list(self): ret = [] def add_row(text, err, sensitive, do_radio, cb, serialidx): ret.append([text, err, sensitive, do_radio, cb, serialidx]) devs = self.vm.get_serial_devs() if len(devs) == 0: add_row(_("No text console available"), None, False, False, None, None) def build_desc(dev): if dev.virtual_device_type == "console": return "Text Console %d" % (dev.vmmindex + 1) return "Serial %d" % (dev.vmmindex + 1) for dev in devs: desc = build_desc(dev) idx = dev.vmmindex err = vmmSerialConsole.can_connect(self.vm, dev) sensitive = not bool(err) def cb(src): return self.control_serial_tab(src, desc, idx) add_row(desc, err, sensitive, True, cb, idx) return ret def current_serial_dev(self): showing_serial = (self.last_console_page >= PAGE_DYNAMIC_OFFSET) if not showing_serial: return serial_idx = self.last_console_page - PAGE_DYNAMIC_OFFSET if len(self.serial_tabs) < serial_idx: return return self.serial_tabs[serial_idx] def populate_serial_menu(self, src): for ent in src: src.remove(ent) serial_page_dev = self.current_serial_dev() showing_graphics = (self.last_console_page == PAGE_CONSOLE) # Populate serial devices group = None itemlist = self.build_serial_list() for msg, err, sensitive, do_radio, cb, ignore in itemlist: if do_radio: item = Gtk.RadioMenuItem(group) item.set_label(msg) if group is None: group = item else: item = Gtk.MenuItem(msg) item.set_sensitive(sensitive) if err and not sensitive: item.set_tooltip_text(err) if cb: item.connect("toggled", cb) # Tab is already open, make sure marked as such if (sensitive and serial_page_dev and serial_page_dev.name == msg): item.set_active(True) src.add(item) src.add(Gtk.SeparatorMenuItem()) # Populate graphical devices devs = self.vm.get_graphics_devices() if len(devs) == 0: item = Gtk.MenuItem(_("No graphical console available")) item.set_sensitive(False) src.add(item) else: dev = devs[0] item = Gtk.RadioMenuItem(group) item.set_label(_("Graphical Console %s") % dev.pretty_type_simple(dev.type)) if group is None: group = item if showing_graphics: item.set_active(True) item.connect("toggled", self.control_serial_tab, dev.virtual_device_type, dev.type) src.add(item) src.show_all() def control_fullscreen(self, src): menu = self.widget("details-menu-view-fullscreen") if src.get_active() != menu.get_active(): menu.set_active(src.get_active()) def toggle_toolbar(self, src): if self.is_customize_dialog: return active = src.get_active() self.config.set_details_show_toolbar(active) if (active and not self.widget("details-menu-view-fullscreen").get_active()): self.widget("toolbar-box").show() else: self.widget("toolbar-box").hide() def get_selected_row(self, widget): selection = widget.get_selection() model, treepath = selection.get_selected() if treepath is None: return None return model[treepath] def get_boot_selection(self): return self.get_selected_row(self.widget("config-boot-list")) def set_hw_selection(self, page, disable_apply=True): if disable_apply: self.disable_apply() hwlist = self.widget("hw-list") selection = hwlist.get_selection() selection.select_path(str(page)) def get_hw_row(self): return self.get_selected_row(self.widget("hw-list")) def get_hw_selection(self, field): row = self.get_hw_row() if not row: return None return row[field] def force_get_hw_pagetype(self, page=None): if page: return page page = self.get_hw_selection(HW_LIST_COL_TYPE) if page is None: page = HW_LIST_TYPE_GENERAL self.set_hw_selection(0) return page def has_unapplied_changes(self, row): if not row: return False if not self.widget("config-apply").get_sensitive(): return False if not util.chkbox_helper(self, self.config.get_confirm_unapplied, self.config.set_confirm_unapplied, text1=(_("There are unapplied changes. Would you like to apply " "them now?")), chktext=_("Don't warn me again."), alwaysrecord=True, default=False): return False return not self.config_apply(row=row) def hw_changed(self, ignore): newrow = self.get_hw_row() model = self.widget("hw-list").get_model() if newrow[HW_LIST_COL_DEVICE] == self.oldhwkey: return oldhwrow = None for row in model: if row[HW_LIST_COL_DEVICE] == self.oldhwkey: oldhwrow = row break if self.has_unapplied_changes(oldhwrow): # Unapplied changes, and syncing them failed pageidx = 0 for idx in range(len(model)): if model[idx][HW_LIST_COL_DEVICE] == self.oldhwkey: pageidx = idx break self.set_hw_selection(pageidx, disable_apply=False) else: self.oldhwkey = newrow[HW_LIST_COL_DEVICE] self.hw_selected() def hw_selected(self, page=None): pagetype = self.force_get_hw_pagetype(page) self.widget("config-remove").set_sensitive(True) self.widget("hw-panel").set_sensitive(True) self.widget("hw-panel").show() try: if pagetype == HW_LIST_TYPE_GENERAL: self.refresh_overview_page() elif pagetype == HW_LIST_TYPE_STATS: self.refresh_stats_page() elif pagetype == HW_LIST_TYPE_CPU: self.refresh_config_cpu() elif pagetype == HW_LIST_TYPE_MEMORY: self.refresh_config_memory() elif pagetype == HW_LIST_TYPE_BOOT: self.refresh_boot_page() elif pagetype == HW_LIST_TYPE_DISK: self.refresh_disk_page() elif pagetype == HW_LIST_TYPE_NIC: self.refresh_network_page() elif pagetype == HW_LIST_TYPE_INPUT: self.refresh_input_page() elif pagetype == HW_LIST_TYPE_GRAPHICS: self.refresh_graphics_page() elif pagetype == HW_LIST_TYPE_SOUND: self.refresh_sound_page() elif pagetype == HW_LIST_TYPE_CHAR: self.refresh_char_page() elif pagetype == HW_LIST_TYPE_HOSTDEV: self.refresh_hostdev_page() elif pagetype == HW_LIST_TYPE_VIDEO: self.refresh_video_page() elif pagetype == HW_LIST_TYPE_WATCHDOG: self.refresh_watchdog_page() elif pagetype == HW_LIST_TYPE_CONTROLLER: self.refresh_controller_page() elif pagetype == HW_LIST_TYPE_FILESYSTEM: self.refresh_filesystem_page() elif pagetype == HW_LIST_TYPE_SMARTCARD: self.refresh_smartcard_page() elif pagetype == HW_LIST_TYPE_REDIRDEV: self.refresh_redir_page() else: pagetype = -1 except Exception, e: self.err.show_err(_("Error refreshing hardware page: %s") % str(e)) return rem = pagetype in remove_pages self.disable_apply() self.widget("config-remove").set_property("visible", rem) self.widget("hw-panel").set_current_page(pagetype) def details_console_changed(self, src): if self.ignoreDetails: return if not src.get_active(): return is_details = False if (src == self.widget("control-vm-details") or src == self.widget("details-menu-view-details")): is_details = True pages = self.widget("details-pages") if pages.get_current_page() == PAGE_DETAILS: if self.has_unapplied_changes(self.get_hw_row()): self.sync_details_console_view(True) return self.disable_apply() if is_details: pages.set_current_page(PAGE_DETAILS) else: pages.set_current_page(self.last_console_page) def sync_details_console_view(self, is_details): details = self.widget("control-vm-details") details_menu = self.widget("details-menu-view-details") console = self.widget("control-vm-console") console_menu = self.widget("details-menu-view-console") try: self.ignoreDetails = True details.set_active(is_details) details_menu.set_active(is_details) console.set_active(not is_details) console_menu.set_active(not is_details) finally: self.ignoreDetails = False def switch_page(self, ignore1=None, ignore2=None, newpage=None): self.page_refresh(newpage) self.sync_details_console_view(newpage == PAGE_DETAILS) self.console.set_allow_fullscreen() if newpage == PAGE_CONSOLE or newpage >= PAGE_DYNAMIC_OFFSET: self.last_console_page = newpage def change_run_text(self, can_restore): if can_restore: text = _("_Restore") else: text = _("_Run") strip_text = text.replace("_", "") self.widget("details-menu-run").get_child().set_label(text) self.widget("control-run").set_label(strip_text) def refresh_vm_state(self, ignore1=None, ignore2=None, ignore3=None): vm = self.vm status = self.vm.status() self.toggle_toolbar(self.widget("details-menu-view-toolbar")) active = vm.is_active() destroy = vm.is_destroyable() run = vm.is_runable() stop = vm.is_stoppable() paused = vm.is_paused() ro = vm.is_read_only() if vm.managedsave_supported: self.change_run_text(vm.hasSavedImage()) self.widget("details-menu-destroy").set_sensitive(destroy) self.widget("control-run").set_sensitive(run) self.widget("details-menu-run").set_sensitive(run) self.widget("details-menu-migrate").set_sensitive(stop) self.widget("control-shutdown").set_sensitive(stop) self.widget("details-menu-shutdown").set_sensitive(stop) self.widget("details-menu-save").set_sensitive(stop) self.widget("control-pause").set_sensitive(stop) self.widget("details-menu-pause").set_sensitive(stop) self.set_pause_state(paused) self.widget("overview-name").set_editable(not active) self.widget("config-vcpus").set_sensitive(not ro) self.widget("config-vcpupin").set_sensitive(not ro) self.widget("config-memory").set_sensitive(not ro) self.widget("config-maxmem").set_sensitive(not ro) # Disable send key menu entries for offline VM self.console.send_key_button.set_sensitive(not (run or paused)) send_key = self.widget("details-menu-send-key") for c in send_key.get_submenu().get_children(): c.set_sensitive(not (run or paused)) self.console.update_widget_states(vm, status) if not run: self.activate_default_console_page() self.widget("overview-status-text").set_text( self.vm.run_status()) self.widget("overview-status-icon").set_from_icon_name( self.vm.run_status_icon_name(), Gtk.IconSize.MENU) details = self.widget("details-pages") self.page_refresh(details.get_current_page()) # This is safe to refresh, and is dependent on domain state self._refresh_runtime_pinning() ############################# # External action listeners # ############################# def view_manager(self, src_ignore): self.emit("action-view-manager") def exit_app(self, src_ignore): self.emit("action-exit-app") def activate_default_console_page(self): if self.vm.get_graphics_devices() or not self.vm.get_serial_devs(): return # Only show serial page if we are already on console view pages = self.widget("details-pages") if pages.get_current_page() != PAGE_CONSOLE: return # Show serial console devs = self.build_serial_list() for name, ignore, sensitive, ignore, cb, serialidx in devs: if not sensitive or not cb: continue self._show_serial_tab(name, serialidx) break def activate_default_page(self): pages = self.widget("details-pages") pages.set_current_page(PAGE_CONSOLE) self.activate_default_console_page() def activate_console_page(self): pages = self.widget("details-pages") pages.set_current_page(PAGE_CONSOLE) def activate_performance_page(self): self.widget("details-pages").set_current_page(PAGE_DETAILS) self.set_hw_selection(HW_LIST_TYPE_STATS) def activate_config_page(self): self.widget("details-pages").set_current_page(PAGE_DETAILS) def add_hardware(self, src_ignore): try: if self.addhw is None: self.addhw = vmmAddHardware(self.vm) self.addhw.show(self.topwin) except Exception, e: self.err.show_err((_("Error launching hardware dialog: %s") % str(e))) def remove_xml_dev(self, src_ignore): info = self.get_hw_selection(HW_LIST_COL_DEVICE) if not info: return devtype = info.virtual_device_type self.remove_device(devtype, info) def set_pause_state(self, paused): # Set pause widget states try: self.ignorePause = True self.widget("control-pause").set_active(paused) self.widget("details-menu-pause").set_active(paused) finally: self.ignorePause = False def control_vm_pause(self, src): if self.ignorePause: return # Let state handler listener change things if necc. self.set_pause_state(not src.get_active()) if not self.vm.is_paused(): self.emit("action-suspend-domain", self.vm.conn.get_uri(), self.vm.get_uuid()) else: self.emit("action-resume-domain", self.vm.conn.get_uri(), self.vm.get_uuid()) def control_vm_run(self, src_ignore): self.emit("action-run-domain", self.vm.conn.get_uri(), self.vm.get_uuid()) def control_vm_shutdown(self, src_ignore): self.emit("action-shutdown-domain", self.vm.conn.get_uri(), self.vm.get_uuid()) def control_vm_reboot(self, src_ignore): self.emit("action-reboot-domain", self.vm.conn.get_uri(), self.vm.get_uuid()) def control_vm_save(self, src_ignore): self.emit("action-save-domain", self.vm.conn.get_uri(), self.vm.get_uuid()) def control_vm_reset(self, src_ignore): self.emit("action-reset-domain", self.vm.conn.get_uri(), self.vm.get_uuid()) def control_vm_destroy(self, src_ignore): self.emit("action-destroy-domain", self.vm.conn.get_uri(), self.vm.get_uuid()) def control_vm_clone(self, src_ignore): self.emit("action-clone-domain", self.vm.conn.get_uri(), self.vm.get_uuid()) def control_vm_migrate(self, src_ignore): self.emit("action-migrate-domain", self.vm.conn.get_uri(), self.vm.get_uuid()) def control_vm_screenshot(self, src_ignore): image = self.console.viewer.get_pixbuf() # If someone feels kind they could extend this code to allow # user to choose what image format they'd like to save in.... path = util.browse_local( self.topwin, _("Save Virtual Machine Screenshot"), self.vm.conn, _type=("png", "PNG files"), dialog_type=Gtk.FileChooserAction.SAVE, browse_reason=self.config.CONFIG_DIR_SCREENSHOT) if not path: return filename = path if not filename.endswith(".png"): filename += ".png" # Save along with a little metadata about us & the domain image.save(filename, 'png', {'tEXt::Hypervisor URI': self.vm.conn.get_uri(), 'tEXt::Domain Name': self.vm.get_name(), 'tEXt::Domain UUID': self.vm.get_uuid(), 'tEXt::Generator App': self.config.get_appname(), 'tEXt::Generator Version': self.config.get_appversion()}) msg = Gtk.MessageDialog(self.topwin, Gtk.DialogFlags.MODAL, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, (_("The screenshot has been saved to:\n%s") % filename)) msg.set_title(_("Screenshot saved")) msg.run() msg.destroy() ######################### # Serial Console pieces # ######################### def control_serial_tab(self, src_ignore, name, target_port): pages = self.widget("details-pages") is_graphics = (name == "graphics") is_serial = not is_graphics if is_graphics: pages.set_current_page(PAGE_CONSOLE) elif is_serial: self._show_serial_tab(name, target_port) def _show_serial_tab(self, name, target_port): serial = None for s in self.serial_tabs: if s.name == name: serial = s break if not serial: serial = vmmSerialConsole(self.vm, target_port, name) title = Gtk.Label(label=name) self.widget("details-pages").append_page(serial.box, title) self.serial_tabs.append(serial) serial.open_console() page_idx = self.serial_tabs.index(serial) + PAGE_DYNAMIC_OFFSET self.widget("details-pages").set_current_page(page_idx) def _close_serial_tab(self, serial): if not serial in self.serial_tabs: return page_idx = self.serial_tabs.index(serial) + PAGE_DYNAMIC_OFFSET self.widget("details-pages").remove_page(page_idx) serial.cleanup() self.serial_tabs.remove(serial) ############################ # Details/Hardware getters # ############################ def get_config_boot_devs(self): boot_model = self.widget("config-boot-list").get_model() devs = [] for row in boot_model: if row[BOOT_ACTIVE]: devs.append(row[BOOT_DEV_TYPE]) return devs def get_config_cpu_model(self): cpu_list = self.widget("cpu-model") model = cpu_list.get_child().get_text() for row in cpu_list.get_model(): if model == row[0]: return model, row[1].vendor return model, None def get_config_cpu_features(self): feature_list = self.widget("cpu-features") ret = [] for row in feature_list.get_model(): if row[1] in ["off", "model"]: continue ret.append(row) return ret ############################## # Details/Hardware listeners # ############################## def _browse_file(self, callback, is_media=False): if is_media: reason = self.config.CONFIG_DIR_ISO_MEDIA else: reason = self.config.CONFIG_DIR_IMAGE if self.storage_browser is None: self.storage_browser = vmmStorageBrowser(self.conn) self.storage_browser.set_finish_cb(callback) self.storage_browser.set_browse_reason(reason) self.storage_browser.show(self.topwin, self.conn) def browse_kernel(self, src_ignore): def cb(ignore, path): self.widget("boot-kernel").set_text(path) self._browse_file(cb) def browse_initrd(self, src_ignore): def cb(ignore, path): self.widget("boot-kernel-initrd").set_text(path) self._browse_file(cb) def disable_apply(self): self.active_edits = [] self.widget("config-apply").set_sensitive(False) self.widget("config-cancel").set_sensitive(False) def enable_apply(self, *arglist): edittype = arglist[-1] self.widget("config-apply").set_sensitive(True) self.widget("config-cancel").set_sensitive(True) if edittype not in self.active_edits: self.active_edits.append(edittype) # Overview -> Machine settings def config_acpi_changed(self, ignore): widget = self.widget("overview-acpi") incon = widget.get_inconsistent() widget.set_inconsistent(False) if incon: widget.set_active(True) self.enable_apply(EDIT_ACPI) def config_apic_changed(self, ignore): widget = self.widget("overview-apic") incon = widget.get_inconsistent() widget.set_inconsistent(False) if incon: widget.set_active(True) self.enable_apply(EDIT_APIC) # Overview -> Security def security_type_changed(self, button): self.enable_apply(EDIT_SECURITY) self.widget("security-label").set_sensitive(not button.get_active()) self.widget("security-relabel").set_sensitive(not button.get_active()) # Memory def config_get_maxmem(self): return uihelpers.spin_get_helper(self.widget("config-maxmem")) def config_get_memory(self): return uihelpers.spin_get_helper(self.widget("config-memory")) def config_maxmem_changed(self, src_ignore): self.enable_apply(EDIT_MEM) def config_memory_changed(self, src_ignore): self.enable_apply(EDIT_MEM) maxadj = self.widget("config-maxmem") mem = self.config_get_memory() if maxadj.get_value() < mem: maxadj.set_value(mem) ignore, upper = maxadj.get_range() maxadj.set_range(mem, upper) def generate_cpuset(self): mem = int(self.vm.get_memory()) / 1024 / 1024 return virtinst.Guest.generate_cpuset(self.conn.vmm, mem) # VCPUS def config_get_vcpus(self): return uihelpers.spin_get_helper(self.widget("config-vcpus")) def config_get_maxvcpus(self): return uihelpers.spin_get_helper(self.widget("config-maxvcpus")) def config_vcpupin_generate(self, ignore): try: pinstr = self.generate_cpuset() except Exception, e: return self.err.val_err( _("Error generating CPU configuration"), e) self.widget("config-vcpupin").set_text("") self.widget("config-vcpupin").set_text(pinstr) def config_vcpus_changed(self, ignore): self.enable_apply(EDIT_VCPUS) conn = self.vm.conn host_active_count = conn.host_active_processor_count() cur = self.config_get_vcpus() # Warn about overcommit warn = bool(cur > host_active_count) self.widget("config-vcpus-warn-box").set_property("visible", warn) maxadj = self.widget("config-maxvcpus") maxval = self.config_get_maxvcpus() if maxval < cur: maxadj.set_value(cur) ignore, upper = maxadj.get_range() maxadj.set_range(cur, upper) def config_maxvcpus_changed(self, ignore): self.enable_apply(EDIT_VCPUS) def config_cpu_copy_host(self, src_ignore): # Update UI with output copied from host try: CPU = virtinst.CPU(self.vm.conn.vmm) CPU.copy_host_cpu() self._refresh_cpu_config(CPU) self._cpu_copy_host = True except Exception, e: self.err.show_err(_("Error copying host CPU: %s") % str(e)) return def config_cpu_topology_enable(self, src): do_enable = src.get_active() self.widget("cpu-topology-table").set_sensitive(do_enable) self.enable_apply(EDIT_TOPOLOGY) # Boot device / Autostart def config_bootdev_selected(self, ignore): boot_row = self.get_boot_selection() boot_selection = boot_row and boot_row[BOOT_DEV_TYPE] boot_devs = self.get_config_boot_devs() up_widget = self.widget("config-boot-moveup") down_widget = self.widget("config-boot-movedown") down_widget.set_sensitive(bool(boot_devs and boot_selection and boot_selection in boot_devs and boot_selection != boot_devs[-1])) up_widget.set_sensitive(bool(boot_devs and boot_selection and boot_selection in boot_devs and boot_selection != boot_devs[0])) def config_boot_toggled(self, ignore, index): boot_model = self.widget("config-boot-list").get_model() boot_row = boot_model[index] is_active = boot_row[BOOT_ACTIVE] boot_row[BOOT_ACTIVE] = not is_active self.repopulate_boot_list(self.get_config_boot_devs(), boot_row[BOOT_DEV_TYPE]) self.enable_apply(EDIT_BOOTORDER) def config_boot_move(self, src, move_up): ignore = src boot_row = self.get_boot_selection() if not boot_row: return boot_selection = boot_row[BOOT_DEV_TYPE] boot_devs = self.get_config_boot_devs() boot_idx = boot_devs.index(boot_selection) if move_up: new_idx = boot_idx - 1 else: new_idx = boot_idx + 1 if new_idx < 0 or new_idx >= len(boot_devs): # Somehow we got out of bounds return swap_dev = boot_devs[new_idx] boot_devs[new_idx] = boot_selection boot_devs[boot_idx] = swap_dev self.repopulate_boot_list(boot_devs, boot_selection) self.enable_apply(EDIT_BOOTORDER) # IO Tuning def iotune_changed(self, ignore): iotune_rbs = int(self.get_text("disk-iotune-rbs") or 0) iotune_ris = int(self.get_text("disk-iotune-ris") or 0) iotune_tbs = int(self.get_text("disk-iotune-tbs") or 0) iotune_tis = int(self.get_text("disk-iotune-tis") or 0) iotune_wbs = int(self.get_text("disk-iotune-wbs") or 0) iotune_wis = int(self.get_text("disk-iotune-wis") or 0) # libvirt doesn't support having read/write settings along side total # settings, so disable the widgets accordingly. have_rw_bytes = (iotune_rbs > 0 or iotune_wbs > 0) have_t_bytes = (not have_rw_bytes and iotune_tbs > 0) self.widget("disk-iotune-rbs").set_sensitive(have_rw_bytes or not have_t_bytes) self.widget("disk-iotune-wbs").set_sensitive(have_rw_bytes or not have_t_bytes) self.widget("disk-iotune-tbs").set_sensitive(have_t_bytes or not have_rw_bytes) if have_rw_bytes: self.widget("disk-iotune-tbs").set_value(0) elif have_t_bytes: self.widget("disk-iotune-rbs").set_value(0) self.widget("disk-iotune-wbs").set_value(0) have_rw_iops = (iotune_ris > 0 or iotune_wis > 0) have_t_iops = (not have_rw_iops and iotune_tis > 0) self.widget("disk-iotune-ris").set_sensitive(have_rw_iops or not have_t_iops) self.widget("disk-iotune-wis").set_sensitive(have_rw_iops or not have_t_iops) self.widget("disk-iotune-tis").set_sensitive(have_t_iops or not have_rw_iops) if have_rw_iops: self.widget("disk-iotune-tis").set_value(0) elif have_t_iops: self.widget("disk-iotune-ris").set_value(0) self.widget("disk-iotune-wis").set_value(0) self.enable_apply(EDIT_DISK_IOTUNE) # CDROM Eject/Connect def toggle_storage_media(self, src_ignore): disk = self.get_hw_selection(HW_LIST_COL_DEVICE) if not disk: return dev_id_info = disk curpath = disk.path devtype = disk.device try: if curpath: # Disconnect cdrom self.change_storage_media(dev_id_info, None) return except Exception, e: self.err.show_err((_("Error disconnecting media: %s") % e)) return try: def change_cdrom_wrapper(src_ignore, dev_id_info, newpath): return self.change_storage_media(dev_id_info, newpath) # Launch 'Choose CD' dialog if self.media_choosers[devtype] is None: ret = vmmChooseCD(self.vm, dev_id_info) ret.connect("cdrom-chosen", change_cdrom_wrapper) self.media_choosers[devtype] = ret dialog = self.media_choosers[devtype] dialog.dev_id_info = dev_id_info dialog.show(self.topwin) except Exception, e: self.err.show_err((_("Error launching media dialog: %s") % e)) return ################################################## # Details/Hardware config changes (apply button) # ################################################## def config_cancel(self, ignore=None): # Remove current changes and deactive 'apply' button self.hw_selected() def config_apply(self, ignore=None, row=None): pagetype = None devobj = None if not row: row = self.get_hw_row() if row: pagetype = row[HW_LIST_COL_TYPE] devobj = row[HW_LIST_COL_DEVICE] key = devobj ret = False try: if pagetype is HW_LIST_TYPE_GENERAL: ret = self.config_overview_apply() elif pagetype is HW_LIST_TYPE_CPU: ret = self.config_vcpus_apply() elif pagetype is HW_LIST_TYPE_MEMORY: ret = self.config_memory_apply() elif pagetype is HW_LIST_TYPE_BOOT: ret = self.config_boot_options_apply() elif pagetype is HW_LIST_TYPE_DISK: ret = self.config_disk_apply(key) elif pagetype is HW_LIST_TYPE_NIC: ret = self.config_network_apply(key) elif pagetype is HW_LIST_TYPE_GRAPHICS: ret = self.config_graphics_apply(key) elif pagetype is HW_LIST_TYPE_SOUND: ret = self.config_sound_apply(key) elif pagetype is HW_LIST_TYPE_VIDEO: ret = self.config_video_apply(key) elif pagetype is HW_LIST_TYPE_WATCHDOG: ret = self.config_watchdog_apply(key) elif pagetype is HW_LIST_TYPE_SMARTCARD: ret = self.config_smartcard_apply(key) elif pagetype is HW_LIST_TYPE_CONTROLLER: ret = self.config_controller_apply(key) else: ret = False except Exception, e: return self.err.show_err(_("Error apply changes: %s") % e) if ret is not False: self.disable_apply() return True def get_text(self, widgetname, strip=True): ret = self.widget(widgetname).get_text() if strip: ret = ret.strip() return ret def editted(self, pagetype): if pagetype not in range(EDIT_TOTAL): raise RuntimeError("crap! %s" % pagetype) return pagetype in self.active_edits def make_apply_data(self): definefuncs = [] defineargs = [] hotplugfuncs = [] hotplugargs = [] def add_define(func, *args): definefuncs.append(func) defineargs.append(args) def add_hotplug(func, *args): hotplugfuncs.append(func) hotplugargs.append(args) return (definefuncs, defineargs, add_define, hotplugfuncs, hotplugargs, add_hotplug) # Overview section def config_overview_apply(self): df, da, add_define, hf, ha, add_hotplug = self.make_apply_data() ignore = add_hotplug if self.editted(EDIT_NAME): name = self.widget("overview-name").get_text() add_define(self.vm.define_name, name) if self.editted(EDIT_ACPI): enable_acpi = self.widget("overview-acpi").get_active() if self.widget("overview-acpi").get_inconsistent(): enable_acpi = None add_define(self.vm.define_acpi, enable_acpi) if self.editted(EDIT_APIC): enable_apic = self.widget("overview-apic").get_active() if self.widget("overview-apic").get_inconsistent(): enable_apic = None add_define(self.vm.define_apic, enable_apic) if self.editted(EDIT_CLOCK): clock = self.get_combo_label_value("overview-clock") add_define(self.vm.define_clock, clock) if self.editted(EDIT_MACHTYPE): machtype = self.get_combo_label_value("machine-type") add_define(self.vm.define_machtype, machtype) if self.editted(EDIT_SECURITY): semodel = None setype = "static" selabel = self.get_text("security-label") relabel = self.widget("security-relabel").get_active() if self.widget("security-dynamic").get_active(): setype = "dynamic" relabel = True if self.widget("security-type-box").get_sensitive(): semodel = self.get_text("security-model") add_define(self.vm.define_seclabel, semodel, setype, selabel, relabel) if self.editted(EDIT_DESC): desc_widget = self.widget("overview-description") desc = desc_widget.get_buffer().get_property("text") or "" add_define(self.vm.define_description, desc) add_hotplug(self.vm.hotplug_description, desc) return self._change_config_helper(df, da, hf, ha) # CPUs def config_vcpus_apply(self): df, da, add_define, hf, ha, add_hotplug = self.make_apply_data() if self.editted(EDIT_VCPUS): vcpus = self.config_get_vcpus() maxv = self.config_get_maxvcpus() add_define(self.vm.define_vcpus, vcpus, maxv) add_hotplug(self.vm.hotplug_vcpus, vcpus) if self.editted(EDIT_CPUSET): cpuset = self.get_text("config-vcpupin") print cpuset add_define(self.vm.define_cpuset, cpuset) add_hotplug(self.config_vcpu_pin_cpuset, cpuset) if self.editted(EDIT_CPU): model, vendor = self.get_config_cpu_model() features = self.get_config_cpu_features() add_define(self.vm.define_cpu, model, vendor, self._cpu_copy_host, features) if self.editted(EDIT_TOPOLOGY): do_top = self.widget("cpu-topology-enable").get_active() sockets = self.widget("cpu-sockets").get_value() cores = self.widget("cpu-cores").get_value() threads = self.widget("cpu-threads").get_value() if not do_top: sockets = None cores = None threads = None add_define(self.vm.define_cpu_topology, sockets, cores, threads) ret = self._change_config_helper(df, da, hf, ha) if ret: self._cpu_copy_host = False return ret def config_vcpu_pin(self, src_ignore, path, new_text): vcpu_list = self.widget("config-vcpu-list") vcpu_model = vcpu_list.get_model() row = vcpu_model[path] conn = self.vm.conn try: new_text = new_text.strip() vcpu_num = int(row[0]) pinlist = virtinst.Guest.cpuset_str_to_tuple(conn.vmm, new_text) except Exception, e: self.err.val_err(_("Error building pin list"), e) return try: self.vm.pin_vcpu(vcpu_num, pinlist) except Exception, e: self.err.show_err(_("Error pinning vcpus"), e) return self._refresh_runtime_pinning() def config_vcpu_pin_cpuset(self, cpuset): conn = self.vm.conn vcpu_list = self.widget("config-vcpu-list") vcpu_model = vcpu_list.get_model() if self.vm.vcpu_pinning() == cpuset: return pinlist = virtinst.Guest.cpuset_str_to_tuple(conn.vmm, cpuset) for row in vcpu_model: vcpu_num = row[0] self.vm.pin_vcpu(int(vcpu_num), pinlist) # Memory def config_memory_apply(self): df, da, add_define, hf, ha, add_hotplug = self.make_apply_data() if self.editted(EDIT_MEM): curmem = None maxmem = self.config_get_maxmem() if self.widget("config-memory").get_sensitive(): curmem = self.config_get_memory() if curmem: curmem = int(curmem) * 1024 if maxmem: maxmem = int(maxmem) * 1024 add_define(self.vm.define_both_mem, curmem, maxmem) add_hotplug(self.vm.hotplug_both_mem, curmem, maxmem) return self._change_config_helper(df, da, hf, ha) # Boot device / Autostart def config_boot_options_apply(self): df, da, add_define, hf, ha, add_hotplug = self.make_apply_data() ignore = add_hotplug if self.editted(EDIT_AUTOSTART): auto = self.widget("config-autostart") try: self.vm.set_autostart(auto.get_active()) except Exception, e: self.err.show_err( (_("Error changing autostart value: %s") % str(e))) return False if self.editted(EDIT_BOOTORDER): bootdevs = self.get_config_boot_devs() add_define(self.vm.set_boot_device, bootdevs) if self.editted(EDIT_BOOTMENU): bootmenu = self.widget("boot-menu").get_active() add_define(self.vm.set_boot_menu, bootmenu) if self.editted(EDIT_KERNEL): kernel = self.get_text("boot-kernel") initrd = self.get_text("boot-kernel-initrd") args = self.get_text("boot-kernel-args") if initrd and not kernel: return self.err.val_err( _("Cannot set initrd without specifying a kernel path")) if args and not kernel: return self.err.val_err( _("Cannot set kernel arguments without specifying a kernel path")) add_define(self.vm.set_boot_kernel, kernel, initrd, args) if self.editted(EDIT_INIT): init = self.get_text("boot-init-path") if not init: return self.err.val_err(_("An init path must be specified")) add_define(self.vm.set_boot_init, init) return self._change_config_helper(df, da, hf, ha) # CDROM def change_storage_media(self, dev_id_info, newpath): return self._change_config_helper(self.vm.define_storage_media, (dev_id_info, newpath), self.vm.hotplug_storage_media, (dev_id_info, newpath)) # Disk options def config_disk_apply(self, dev_id_info): df, da, add_define, hf, ha, add_hotplug = self.make_apply_data() ignore = add_hotplug if self.editted(EDIT_DISK_RO): do_readonly = self.widget("disk-readonly").get_active() add_define(self.vm.define_disk_readonly, dev_id_info, do_readonly) if self.editted(EDIT_DISK_SHARE): do_shareable = self.widget("disk-shareable").get_active() add_define(self.vm.define_disk_shareable, dev_id_info, do_shareable) if self.editted(EDIT_DISK_CACHE): cache = self.get_combo_label_value("disk-cache") add_define(self.vm.define_disk_cache, dev_id_info, cache) if self.editted(EDIT_DISK_IO): io = self.get_combo_label_value("disk-io") add_define(self.vm.define_disk_io, dev_id_info, io) if self.editted(EDIT_DISK_FORMAT): fmt = self.widget("disk-format").get_child().get_text().strip() add_define(self.vm.define_disk_driver_type, dev_id_info, fmt) if self.editted(EDIT_DISK_SERIAL): serial = self.get_text("disk-serial") add_define(self.vm.define_disk_serial, dev_id_info, serial) if self.editted(EDIT_DISK_IOTUNE): iotune_rbs = int(self.widget("disk-iotune-rbs").get_value() * 1024) iotune_ris = int(self.widget("disk-iotune-ris").get_value()) iotune_tbs = int(self.widget("disk-iotune-tbs").get_value() * 1024) iotune_tis = int(self.widget("disk-iotune-tis").get_value()) iotune_wbs = int(self.widget("disk-iotune-wbs").get_value() * 1024) iotune_wis = int(self.widget("disk-iotune-wis").get_value()) add_define(self.vm.define_disk_iotune_rbs, dev_id_info, iotune_rbs) add_define(self.vm.define_disk_iotune_ris, dev_id_info, iotune_ris) add_define(self.vm.define_disk_iotune_tbs, dev_id_info, iotune_tbs) add_define(self.vm.define_disk_iotune_tis, dev_id_info, iotune_tis) add_define(self.vm.define_disk_iotune_wbs, dev_id_info, iotune_wbs) add_define(self.vm.define_disk_iotune_wis, dev_id_info, iotune_wis) # Do this last since it can change uniqueness info of the dev if self.editted(EDIT_DISK_BUS): bus = self.get_combo_label_value("disk-bus") addr = None if bus == "spapr-vscsi": bus = "scsi" addr = "spapr-vio" add_define(self.vm.define_disk_bus, dev_id_info, bus, addr) return self._change_config_helper(df, da, hf, ha) # Audio options def config_sound_apply(self, dev_id_info): df, da, add_define, hf, ha, add_hotplug = self.make_apply_data() ignore = add_hotplug if self.editted(EDIT_SOUND_MODEL): model = self.get_combo_label_value("sound-model") if model: add_define(self.vm.define_sound_model, dev_id_info, model) return self._change_config_helper(df, da, hf, ha) # Smartcard options def config_smartcard_apply(self, dev_id_info): df, da, add_define, hf, ha, add_hotplug = self.make_apply_data() ignore = add_hotplug if self.editted(EDIT_SMARTCARD_MODE): model = self.get_combo_label_value("smartcard-mode") if model: add_define(self.vm.define_smartcard_mode, dev_id_info, model) return self._change_config_helper(df, da, hf, ha) # Network options def config_network_apply(self, dev_id_info): df, da, add_define, hf, ha, add_hotplug = self.make_apply_data() ignore = add_hotplug if self.editted(EDIT_NET_MODEL): model = self.get_combo_label_value("network-model") addr = None if model == "spapr-vlan": addr = "spapr-vio" add_define(self.vm.define_network_model, dev_id_info, model, addr) if self.editted(EDIT_NET_SOURCE): mode = None net_list = self.widget("network-source-combo") net_bridge = self.widget("network-bridge") nettype, source = uihelpers.get_network_selection(net_list, net_bridge) if nettype == "direct": mode = self.get_combo_label_value("network-source-mode") add_define(self.vm.define_network_source, dev_id_info, nettype, source, mode) if self.editted(EDIT_NET_VPORT): vport_type = self.get_text("vport-type") vport_managerid = self.get_text("vport-managerid") vport_typeid = self.get_text("vport-typeid") vport_idver = self.get_text("vport-typeidversion") vport_instid = self.get_text("vport-instanceid") add_define(self.vm.define_virtualport, dev_id_info, vport_type, vport_managerid, vport_typeid, vport_idver, vport_instid) return self._change_config_helper(df, da, hf, ha) # Graphics options def _do_change_spicevmc(self, gdev, newgtype): has_multi_spice = (len([d for d in self.vm.get_graphics_devices() if d.type == d.TYPE_SPICE]) > 1) has_spicevmc = bool([d for d in self.vm.get_char_devices() if (d.dev_type == d.DEV_CHANNEL and d.char_type == d.CHAR_SPICEVMC)]) fromspice = (gdev.type == "spice") tospice = (newgtype == "spice") if fromspice and tospice: return False if not fromspice and not tospice: return False if tospice and has_spicevmc: return False if fromspice and not has_spicevmc: return False if fromspice and has_multi_spice: # Don't offer to remove if there are other spice displays return False msg = (_("You are switching graphics type to %(gtype)s, " "would you like to %(action)s Spice agent channels?") % {"gtype": newgtype, "action": fromspice and "remove" or "add"}) return self.err.yes_no(msg) def config_graphics_apply(self, dev_id_info): df, da, add_define, hf, ha, add_hotplug = self.make_apply_data() if self.editted(EDIT_GFX_PASSWD): passwd = self.get_text("gfx-password", strip=False) or None add_define(self.vm.define_graphics_password, dev_id_info, passwd) add_hotplug(self.vm.hotplug_graphics_password, dev_id_info, passwd) if self.editted(EDIT_GFX_KEYMAP): keymap = self.get_combo_label_value("gfx-keymap") add_define(self.vm.define_graphics_keymap, dev_id_info, keymap) # Do this last since it can change graphics unique ID if self.editted(EDIT_GFX_TYPE): gtype = self.get_combo_label_value("gfx-type") change_spicevmc = self._do_change_spicevmc(dev_id_info, gtype) add_define(self.vm.define_graphics_type, dev_id_info, gtype, change_spicevmc) return self._change_config_helper(df, da, hf, ha) # Video options def config_video_apply(self, dev_id_info): df, da, add_define, hf, ha, add_hotplug = self.make_apply_data() ignore = add_hotplug if self.editted(EDIT_VIDEO_MODEL): model = self.get_combo_label_value("video-model") if model: add_define(self.vm.define_video_model, dev_id_info, model) return self._change_config_helper(df, da, hf, ha) # Controller options def config_controller_apply(self, dev_id_info): df, da, add_define, hf, ha, add_hotplug = self.make_apply_data() ignore = add_hotplug if self.editted(EDIT_CONTROLLER_MODEL): model = self.get_combo_label_value("controller-model") if model: add_define(self.vm.define_controller_model, dev_id_info, model) return self._change_config_helper(df, da, hf, ha) # Watchdog options def config_watchdog_apply(self, dev_id_info): df, da, add_define, hf, ha, add_hotplug = self.make_apply_data() ignore = add_hotplug if self.editted(EDIT_WATCHDOG_MODEL): model = self.get_combo_label_value("watchdog-model") add_define(self.vm.define_watchdog_model, dev_id_info, model) if self.editted(EDIT_WATCHDOG_ACTION): action = self.get_combo_label_value("watchdog-action") add_define(self.vm.define_watchdog_action, dev_id_info, action) return self._change_config_helper(df, da, hf, ha) # Device removal def remove_device(self, dev_type, dev_id_info): logging.debug("Removing device: %s %s", dev_type, dev_id_info) if not util.chkbox_helper(self, self.config.get_confirm_removedev, self.config.set_confirm_removedev, text1=(_("Are you sure you want to remove this device?"))): return # Define the change try: self.vm.remove_device(dev_id_info) except Exception, e: self.err.show_err(_("Error Removing Device: %s" % str(e))) return # Try to hot remove detach_err = False try: if self.vm.is_active(): self.vm.detach_device(dev_id_info) except Exception, e: logging.debug("Device could not be hotUNplugged: %s", str(e)) detach_err = (str(e), "".join(traceback.format_exc())) if not detach_err: self.disable_apply() return self.err.show_err( _("Device could not be removed from the running machine"), details=(detach_err[0] + "\n\n" + detach_err[1]), text2=_("This change will take effect after the next guest " "shutdown."), buttons=Gtk.ButtonsType.OK, dialog_type=Gtk.MessageType.INFO) # Generic config change helpers def _change_config_helper(self, define_funcs, define_funcs_args, hotplug_funcs=None, hotplug_funcs_args=None): """ Requires at least a 'define' function and arglist to be specified (a function where we change the inactive guest config). Arguments can be a single arg or a list or appropriate arg type (e.g. a list of functions for define_funcs) """ def listify(val): if not val: return [] if type(val) is not list: return [val] return val define_funcs = listify(define_funcs) define_funcs_args = listify(define_funcs_args) hotplug_funcs = listify(hotplug_funcs) hotplug_funcs_args = listify(hotplug_funcs_args) hotplug_err = [] active = self.vm.is_active() # Hotplug change func = None if active and hotplug_funcs: for idx in range(len(hotplug_funcs)): func = hotplug_funcs[idx] args = hotplug_funcs_args[idx] try: func(*args) except Exception, e: logging.debug("Hotplug failed: func=%s: %s", func, str(e)) hotplug_err.append((str(e), "".join(traceback.format_exc()))) # Persistent config change try: for idx in range(len(define_funcs)): func = define_funcs[idx] args = define_funcs_args[idx] func(*args) if define_funcs: self.vm.redefine_cached() except Exception, e: self.err.show_err((_("Error changing VM configuration: %s") % str(e))) # If we fail, make sure we flush the cache self.vm.refresh_xml() return False if (hotplug_err or (active and not len(hotplug_funcs) == len(define_funcs))): if len(define_funcs) > 1: msg = _("Some changes may require a guest shutdown " "to take effect.") else: msg = _("These changes will take effect after " "the next guest shutdown.") dtype = hotplug_err and Gtk.MessageType.WARNING or Gtk.MessageType.INFO hotplug_msg = "" for err1, tb in hotplug_err: hotplug_msg += (err1 + "\n\n" + tb + "\n") self.err.show_err(msg, details=hotplug_msg, buttons=Gtk.ButtonsType.OK, dialog_type=dtype) return True ######################## # Details page refresh # ######################## def refresh_resources(self, ignore): details = self.widget("details-pages") page = details.get_current_page() # If the dialog is visible, we want to make sure the XML is always # up to date if self.is_visible(): self.vm.refresh_xml() # Stats page needs to be refreshed every tick if (page == PAGE_DETAILS and self.get_hw_selection(HW_LIST_COL_TYPE) == HW_LIST_TYPE_STATS): self.refresh_stats_page() def page_refresh(self, page): if page != PAGE_DETAILS: return # This function should only be called when the VM xml actually # changes (not everytime it is refreshed). This saves us from blindly # parsing the xml every tick # Add / remove new devices self.repopulate_hw_list() pagetype = self.get_hw_selection(HW_LIST_COL_TYPE) if pagetype is None: return if self.widget("config-apply").get_sensitive(): # Apply button sensitive means user is making changes, don't # erase them return self.hw_selected(page=pagetype) def refresh_overview_page(self): # Basic details self.widget("overview-name").set_text(self.vm.get_name()) self.widget("overview-uuid").set_text(self.vm.get_uuid()) desc = self.vm.get_description() or "" desc_widget = self.widget("overview-description") desc_widget.get_buffer().set_text(desc) # Hypervisor Details self.widget("overview-hv").set_text(self.vm.get_pretty_hv_type()) arch = self.vm.get_arch() or _("Unknown") emu = self.vm.get_emulator() or _("None") self.widget("overview-arch").set_text(arch) self.widget("overview-emulator").set_text(emu) # Operating System (ie. inspection data) hostname = self.vm.inspection.hostname if not hostname: hostname = _("unknown") self.widget("inspection-hostname").set_text(hostname) product_name = self.vm.inspection.product_name if not product_name: product_name = _("unknown") self.widget("inspection-product-name").set_text(product_name) # Applications (also inspection data) apps = self.vm.inspection.applications or [] apps_list = self.widget("inspection-apps") apps_model = apps_list.get_model() apps_model.clear() for app in apps: name = "" if app["app_name"]: name = app["app_name"] if app["app_display_name"]: name = app["app_display_name"] version = "" if app["app_version"]: version = app["app_version"] if app["app_release"]: version += "-" + app["app_release"] summary = "" if app["app_summary"]: summary = app["app_summary"] apps_model.append([name, version, summary]) # Machine settings acpi = self.vm.get_acpi() apic = self.vm.get_apic() clock = self.vm.get_clock() machtype = self.vm.get_machtype() # Hack in a way to represent 'default' acpi/apic for customize dialog self.widget("overview-acpi").set_active(bool(acpi)) self.widget("overview-acpi").set_inconsistent( acpi is None and self.is_customize_dialog) self.widget("overview-apic").set_active(bool(apic)) self.widget("overview-apic").set_inconsistent( apic is None and self.is_customize_dialog) if not clock: clock = _("Same as host") self.set_combo_label("overview-clock", clock) if not arch in ["i686", "x86_64"]: if machtype is not None: self.set_combo_label("machine-type", machtype) # Security details semodel, sectype, vmlabel, relabel = self.vm.get_seclabel() caps = self.vm.conn.get_capabilities() if caps.host.secmodel and caps.host.secmodel.model: semodel = caps.host.secmodel.model self.widget("security-model").set_text(semodel or _("None")) if not semodel or semodel == "apparmor": self.widget("security-type-box").hide() self.widget("security-type-label").hide() else: self.widget("security-type-box").set_sensitive(bool(semodel)) if sectype == "static": self.widget("security-static").set_active(True) self.widget("security-relabel").set_sensitive(True) # As "no" is default for relabel with 'static' label and # 'dynamic' must have relabel='yes', this will work properly # for both False (relabel='no') and None (relabel not # specified) self.widget("security-relabel").set_active(relabel) else: self.widget("security-dynamic").set_active(True) # Dynamic label type must use resource labeling self.widget("security-relabel").set_active(True) self.widget("security-relabel").set_sensitive(False) self.widget("security-label").set_text(vmlabel) def refresh_stats_page(self): def _dsk_rx_tx_text(rx, tx, unit): return ('<span color="#82003B">%(rx)d %(unit)s read</span>\n' '<span color="#295C45">%(tx)d %(unit)s write</span>' % {"rx": rx, "tx": tx, "unit": unit}) def _net_rx_tx_text(rx, tx, unit): return ('<span color="#82003B">%(rx)d %(unit)s in</span>\n' '<span color="#295C45">%(tx)d %(unit)s out</span>' % {"rx": rx, "tx": tx, "unit": unit}) cpu_txt = _("Disabled") mem_txt = _("Disabled") dsk_txt = _("Disabled") net_txt = _("Disabled") cpu_txt = "%d %%" % self.vm.guest_cpu_time_percentage() cur_vm_memory = self.vm.stats_memory() vm_memory = self.vm.maximum_memory() mem_txt = "%s of %s" % (util.pretty_mem(cur_vm_memory), util.pretty_mem(vm_memory)) if self.config.get_stats_enable_disk_poll(): dsk_txt = _dsk_rx_tx_text(self.vm.disk_read_rate(), self.vm.disk_write_rate(), "KB/s") if self.config.get_stats_enable_net_poll(): net_txt = _net_rx_tx_text(self.vm.network_rx_rate(), self.vm.network_tx_rate(), "KB/s") self.widget("overview-cpu-usage-text").set_text(cpu_txt) self.widget("overview-memory-usage-text").set_text(mem_txt) self.widget("overview-network-traffic-text").set_markup(net_txt) self.widget("overview-disk-usage-text").set_markup(dsk_txt) self.cpu_usage_graph.set_property("data_array", self.vm.guest_cpu_time_vector()) self.memory_usage_graph.set_property("data_array", self.vm.stats_memory_vector()) self.disk_io_graph.set_property("data_array", self.vm.disk_io_vector()) self.network_traffic_graph.set_property("data_array", self.vm.network_traffic_vector()) def _refresh_cpu_count(self): conn = self.vm.conn host_active_count = conn.host_active_processor_count() maxvcpus = self.vm.vcpu_max_count() curvcpus = self.vm.vcpu_count() curadj = self.widget("config-vcpus") maxadj = self.widget("config-maxvcpus") curadj.set_value(int(curvcpus)) maxadj.set_value(int(maxvcpus)) self.widget("state-host-cpus").set_text(str(host_active_count)) # Warn about overcommit warn = bool(self.config_get_vcpus() > host_active_count) self.widget("config-vcpus-warn-box").set_property("visible", warn) def _refresh_cpu_pinning(self): # Populate VCPU pinning vcpupin = self.vm.vcpu_pinning() self.widget("config-vcpupin").set_text(vcpupin) def _refresh_runtime_pinning(self): conn = self.vm.conn host_active_count = conn.host_active_processor_count() vcpu_list = self.widget("config-vcpu-list") vcpu_model = vcpu_list.get_model() vcpu_model.clear() reason = "" if not self.vm.is_active(): reason = _("VCPU info only available for running domain.") else: try: vcpu_info, vcpu_pinning = self.vm.vcpu_info() except Exception, e: reason = _("Error getting VCPU info: %s") % str(e) if not self.vm.getvcpus_supported: reason = _("Virtual machine does not support runtime " "VPCU info.") vcpu_list.set_sensitive(not bool(reason)) vcpu_list.set_tooltip_text(reason or "") if reason: return def build_cpuset_str(pin_info): pinstr = "" for i in range(host_active_count): if i < len(pin_info) and pin_info[i]: pinstr += (",%s" % str(i)) return pinstr.strip(",") for idx in range(len(vcpu_info)): vcpu = str(vcpu_info[idx][0]) vcpucur = str(vcpu_info[idx][3]) vcpupin = build_cpuset_str(vcpu_pinning[idx]) vcpu_model.append([vcpu, vcpucur, vcpupin]) def _refresh_cpu_config(self, cpu): feature_ui = self.widget("cpu-features") model = cpu.model or "" caps = self.vm.conn.get_capabilities() capscpu = None try: arch = self.vm.get_arch() if arch: cpu_values = caps.get_cpu_values(arch) for c in cpu_values.cpus: if model and c.model == model: capscpu = c break except: pass show_top = bool(cpu.sockets or cpu.cores or cpu.threads) sockets = cpu.sockets or 1 cores = cpu.cores or 1 threads = cpu.threads or 1 self.widget("cpu-topology-enable").set_active(show_top) self.widget("cpu-model").get_child().set_text(model) self.widget("cpu-sockets").set_value(sockets) self.widget("cpu-cores").set_value(cores) self.widget("cpu-threads").set_value(threads) def get_feature_policy(name): for f in cpu.features: if f.name == name: return f.policy if capscpu: for f in capscpu.features: if f == name: return "model" return "off" for row in feature_ui.get_model(): row[1] = get_feature_policy(row[0]) def refresh_config_cpu(self): self._cpu_copy_host = False cpu = self.vm.get_cpu_config() self._refresh_cpu_count() self._refresh_cpu_pinning() self._refresh_runtime_pinning() self._refresh_cpu_config(cpu) def refresh_config_memory(self): host_mem_widget = self.widget("state-host-memory") host_mem = self.vm.conn.host_memory_size() / 1024 vm_cur_mem = self.vm.get_memory() / 1024.0 vm_max_mem = self.vm.maximum_memory() / 1024.0 host_mem_widget.set_text("%d MB" % (int(round(host_mem)))) curmem = self.widget("config-memory") maxmem = self.widget("config-maxmem") curmem.set_value(int(round(vm_cur_mem))) maxmem.set_value(int(round(vm_max_mem))) if not self.widget("config-memory").get_sensitive(): ignore, upper = maxmem.get_range() maxmem.set_range(curmem.get_value(), upper) def refresh_disk_page(self): disk = self.get_hw_selection(HW_LIST_COL_DEVICE) if not disk: return path = disk.path devtype = disk.device ro = disk.read_only share = disk.shareable bus = disk.bus addr = disk.address.type idx = disk.disk_bus_index cache = disk.driver_cache io = disk.driver_io driver_type = disk.driver_type or "" serial = disk.serial iotune_rbs = (disk.iotune_rbs or 0) / 1024 iotune_ris = (disk.iotune_ris or 0) iotune_tbs = (disk.iotune_tbs or 0) / 1024 iotune_tis = (disk.iotune_tis or 0) iotune_wbs = (disk.iotune_wbs or 0) / 1024 iotune_wis = (disk.iotune_wis or 0) show_format = (not self.is_customize_dialog or disk.path_exists(disk.conn, disk.path)) size = _("Unknown") if not path: size = "-" else: vol = self.conn.get_vol_by_path(path) if vol: size = vol.get_pretty_capacity() elif not self.conn.is_remote(): ignore, val = virtinst.VirtualDisk.stat_local_path(path) if val != 0: size = prettyify_bytes(val) is_cdrom = (devtype == virtinst.VirtualDisk.DEVICE_CDROM) is_floppy = (devtype == virtinst.VirtualDisk.DEVICE_FLOPPY) if addr == "spapr-vio": bus = "spapr-vscsi" pretty_name = prettyify_disk(devtype, bus, idx) self.widget("disk-source-path").set_text(path or "-") self.widget("disk-target-type").set_text(pretty_name) self.widget("disk-readonly").set_active(ro) self.widget("disk-readonly").set_sensitive(not is_cdrom) self.widget("disk-shareable").set_active(share) self.widget("disk-size").set_text(size) self.set_combo_label("disk-cache", cache) self.set_combo_label("disk-io", io) self.widget("disk-format").set_sensitive(show_format) self.widget("disk-format").get_child().set_text(driver_type) no_default = not self.is_customize_dialog self.populate_disk_bus_combo(devtype, no_default) self.set_combo_label("disk-bus", bus) self.widget("disk-serial").set_text(serial or "") self.widget("disk-iotune-rbs").set_value(iotune_rbs) self.widget("disk-iotune-ris").set_value(iotune_ris) self.widget("disk-iotune-tbs").set_value(iotune_tbs) self.widget("disk-iotune-tis").set_value(iotune_tis) self.widget("disk-iotune-wbs").set_value(iotune_wbs) self.widget("disk-iotune-wis").set_value(iotune_wis) button = self.widget("config-cdrom-connect") if is_cdrom or is_floppy: if not path: # source device not connected button.set_label(Gtk.STOCK_CONNECT) else: button.set_label(Gtk.STOCK_DISCONNECT) button.show() else: button.hide() def refresh_network_page(self): net = self.get_hw_selection(HW_LIST_COL_DEVICE) if not net: return nettype = net.type source = net.get_source() source_mode = net.source_mode model = net.model netobj = None if nettype == virtinst.VirtualNetworkInterface.TYPE_VIRTUAL: name_dict = {} for uuid in self.conn.list_net_uuids(): vnet = self.conn.get_net(uuid) name = vnet.get_name() name_dict[name] = vnet if source and source in name_dict: netobj = name_dict[source] desc = uihelpers.pretty_network_desc(nettype, source, netobj) self.widget("network-mac-address").set_text(net.macaddr) uihelpers.populate_network_list( self.widget("network-source-combo"), self.conn) self.widget("network-source-combo").set_active(-1) self.widget("network-bridge").set_text("") def compare_network(model, info): for idx in range(len(model)): row = model[idx] if row[0] == info[0] and row[1] == info[1]: return True, idx if info[0] == virtinst.VirtualNetworkInterface.TYPE_BRIDGE: idx = (len(model) - 1) self.widget("network-bridge").set_text(str(info[1])) return True, idx return False, 0 self.set_combo_label("network-source", (nettype, source), label=desc, comparefunc=compare_network) # source mode uihelpers.populate_source_mode_combo(self.vm, self.widget("network-source-mode-combo")) self.set_combo_label("network-source-mode", source_mode) # Virtualport config show_vport = (nettype == "direct") vport = net.virtualport self.widget("vport-expander").set_property("visible", show_vport) self.widget("vport-type").set_text(vport.type or "") self.widget("vport-managerid").set_text(vport.managerid or "") self.widget("vport-typeid").set_text(vport.typeid or "") self.widget("vport-typeidversion").set_text(vport.typeidversion or "") self.widget("vport-instanceid").set_text(vport.instanceid or "") uihelpers.populate_netmodel_combo(self.vm, self.widget("network-model-combo")) self.set_combo_label("network-model", model) def refresh_input_page(self): inp = self.get_hw_selection(HW_LIST_COL_DEVICE) if not inp: return ident = "%s:%s" % (inp.type, inp.bus) if ident == "tablet:usb": dev = _("EvTouch USB Graphics Tablet") elif ident == "mouse:usb": dev = _("Generic USB Mouse") elif ident == "mouse:xen": dev = _("Xen Mouse") elif ident == "mouse:ps2": dev = _("PS/2 Mouse") else: dev = inp.bus + " " + inp.type if inp.type == "tablet": mode = _("Absolute Movement") else: mode = _("Relative Movement") self.widget("input-dev-type").set_text(dev) self.widget("input-dev-mode").set_text(mode) # Can't remove primary Xen or PS/2 mice if inp.type == "mouse" and inp.bus in ("xen", "ps2"): self.widget("config-remove").set_sensitive(False) else: self.widget("config-remove").set_sensitive(True) def refresh_graphics_page(self): gfx = self.get_hw_selection(HW_LIST_COL_DEVICE) if not gfx: return title = self.widget("graphics-title") table = self.widget("graphics-table") table.foreach(lambda w, ignore: w.hide(), ()) def set_title(text): title.set_markup("<b>%s</b>" % text) def show_row(widget_name, suffix=""): base = "gfx-%s" % widget_name self.widget(base + "-title").show() self.widget(base + suffix).show() def show_text(widget_name, text): show_row(widget_name) self.widget("gfx-" + widget_name).set_text(text) def port_to_string(port): if port is None: return "-" return (port == -1 and _("Automatically allocated") or str(port)) gtype = gfx.type is_vnc = (gtype == "vnc") is_sdl = (gtype == "sdl") is_spice = (gtype == "spice") is_other = not (True in [is_vnc, is_sdl, is_spice]) set_title(_("%(graphicstype)s Server") % {"graphicstype" : gfx.pretty_type_simple(gtype)}) settype = "" if is_vnc or is_spice: port = port_to_string(gfx.port) address = (gfx.listen or "127.0.0.1") keymap = (gfx.keymap or None) passwd = gfx.passwd or "" show_text("password", passwd) show_text("port", port) show_text("address", address) show_row("keymap", "-box") self.set_combo_label("gfx-keymap", keymap) settype = gtype if is_spice: tlsport = port_to_string(gfx.tlsPort) show_text("tlsport", tlsport) if is_sdl: set_title(_("Local SDL Window")) display = gfx.display or _("Unknown") xauth = gfx.xauth or _("Unknown") show_text("display", display) show_text("xauth", xauth) if is_other: settype = gfx.pretty_type_simple(gtype) if settype: show_row("type", "-box") self.set_combo_label("gfx-type", gtype, label=settype) def refresh_sound_page(self): sound = self.get_hw_selection(HW_LIST_COL_DEVICE) if not sound: return self.set_combo_label("sound-model", sound.model) def refresh_smartcard_page(self): sc = self.get_hw_selection(HW_LIST_COL_DEVICE) if not sc: return self.set_combo_label("smartcard-mode", sc.mode) def refresh_redir_page(self): rd = self.get_hw_selection(HW_LIST_COL_DEVICE) if not rd: return address = build_redir_label(rd)[0] or "-" devlabel = "<b>Redirected %s Device</b>" % rd.bus.upper() self.widget("redir-title").set_markup(devlabel) self.widget("redir-address").set_text(address) self.widget("redir-type-label").set_text(rd.type) self.widget("redir-type-combo").hide() def refresh_char_page(self): chardev = self.get_hw_selection(HW_LIST_COL_DEVICE) if not chardev: return show_target_type = not (chardev.dev_type in [chardev.DEV_SERIAL, chardev.DEV_PARALLEL]) def show_ui(param, val=None): widgetname = "char-" + param.replace("_", "-") labelname = widgetname + "-label" doshow = chardev.supports_property(param, ro=True) # Exception: don't show target type for serial/parallel if (param == "target_type" and not show_target_type): doshow = False if not val and doshow: val = getattr(chardev, param) self.widget(widgetname).set_property("visible", doshow) self.widget(labelname).set_property("visible", doshow) self.widget(widgetname).set_text(val or "-") def build_host_str(base): if (not chardev.supports_property(base + "_host") or not chardev.supports_property(base + "_port")): return "" host = getattr(chardev, base + "_host") or "" port = getattr(chardev, base + "_port") or "" ret = str(host) if port: ret += ":%s" % str(port) return ret char_type = chardev.virtual_device_type.capitalize() target_port = chardev.target_port dev_type = chardev.char_type or "pty" primary = hasattr(chardev, "virtmanager_console_dup") typelabel = "" if char_type == "serial": typelabel = _("Serial Device") elif char_type == "parallel": typelabel = _("Parallel Device") elif char_type == "console": typelabel = _("Console Device") elif char_type == "channel": typelabel = _("Channel Device") else: typelabel = _("%s Device") % char_type.capitalize() if target_port is not None and not show_target_type: typelabel += " %s" % (int(target_port) + 1) if primary: typelabel += " (%s)" % _("Primary Console") typelabel = "<b>%s</b>" % typelabel self.widget("char-type").set_markup(typelabel) self.widget("char-dev-type").set_text(dev_type) # Device type specific properties, only show if apply to the cur dev show_ui("source_host", build_host_str("source")) show_ui("bind_host", build_host_str("bind")) show_ui("source_path") show_ui("target_type") show_ui("target_name") def refresh_hostdev_page(self): hostdev = self.get_hw_selection(HW_LIST_COL_DEVICE) if not hostdev: return devtype = hostdev.type pretty_name = None nodedev = lookup_nodedev(self.vm.conn, hostdev) if nodedev: pretty_name = nodedev.pretty_name() if not pretty_name: pretty_name = build_hostdev_label(hostdev)[0] or "-" devlabel = "<b>Physical %s Device</b>" % devtype.upper() self.widget("hostdev-title").set_markup(devlabel) self.widget("hostdev-source").set_text(pretty_name) def refresh_video_page(self): vid = self.get_hw_selection(HW_LIST_COL_DEVICE) if not vid: return no_default = not self.is_customize_dialog uihelpers.populate_video_combo(self.vm, self.widget("video-model-combo"), no_default=no_default) model = vid.model_type ram = vid.vram heads = vid.heads try: ramlabel = ram and "%d MB" % (int(ram) / 1024) or "-" except: ramlabel = "-" self.widget("video-ram").set_text(ramlabel) self.widget("video-heads").set_text(heads and heads or "-") self.set_combo_label("video-model", model, label=vid.pretty_model(model)) def refresh_watchdog_page(self): watch = self.get_hw_selection(HW_LIST_COL_DEVICE) if not watch: return model = watch.model action = watch.action self.set_combo_label("watchdog-model", model) self.set_combo_label("watchdog-action", action) def refresh_controller_page(self): dev = self.get_hw_selection(HW_LIST_COL_DEVICE) if not dev: return type_label = virtinst.VirtualController.pretty_type(dev.type) model_label = dev.model if not model_label: model_label = _("Default") self.widget("controller-type").set_text(type_label) combo = self.widget("controller-model-combo") model = combo.get_model() model.clear() if dev.type == virtinst.VirtualController.CONTROLLER_TYPE_USB: model.append(["Default", "Default"]) model.append(["ich9-ehci1", "USB 2"]) self.widget("config-remove").set_sensitive(False) else: self.widget("config-remove").set_sensitive(True) self.set_combo_label("controller-model", model_label) def refresh_filesystem_page(self): dev = self.get_hw_selection(HW_LIST_COL_DEVICE) if not dev: return self.widget("fs-type").set_text(dev.type) # mode can be irrelevant depending on the fs driver type # selected. if dev.mode: self.show_pair("fs-mode", True) self.widget("fs-mode").set_text(dev.mode) else: self.show_pair("fs-mode", False) self.widget("fs-driver").set_text(dev.driver or _("Default")) self.widget("fs-wrpolicy").set_text(dev.wrpolicy or _("Default")) self.widget("fs-source").set_text(dev.source) self.widget("fs-target").set_text(dev.target) if dev.readonly: self.widget("fs-readonly").set_text("Yes") else: self.widget("fs-readonly").set_text("No") def refresh_boot_page(self): # Refresh autostart try: # Older libvirt versions return None if not supported autoval = self.vm.get_autostart() except libvirt.libvirtError: autoval = None # Autostart autostart_chk = self.widget("config-autostart") enable_autostart = (autoval is not None) autostart_chk.set_sensitive(enable_autostart) autostart_chk.set_active(enable_autostart and autoval or False) show_kernel = not self.vm.is_container() show_init = self.vm.is_container() show_boot = (not self.vm.is_container() and not self.vm.is_xenpv()) self.widget("boot-order-align").set_property("visible", show_boot) self.widget("boot-kernel-align").set_property("visible", show_kernel) self.widget("boot-init-align").set_property("visible", show_init) # Kernel/initrd boot kernel, initrd, args = self.vm.get_boot_kernel_info() expand = bool(kernel or initrd or args) self.widget("boot-kernel").set_text(kernel or "") self.widget("boot-kernel-initrd").set_text(initrd or "") self.widget("boot-kernel-args").set_text(args or "") if expand: self.widget("boot-kernel-expander").set_expanded(True) # <init> populate init = self.vm.get_init() self.widget("boot-init-path").set_text(init or "") # Boot menu populate menu = self.vm.get_boot_menu() or False self.widget("boot-menu").set_active(menu) self.repopulate_boot_list() ############################ # Hardware list population # ############################ def populate_disk_bus_combo(self, devtype, no_default): buslist = self.widget("disk-bus-combo") busmodel = buslist.get_model() busmodel.clear() buses = [] if devtype == virtinst.VirtualDisk.DEVICE_FLOPPY: buses.append(["fdc", "Floppy"]) elif devtype == virtinst.VirtualDisk.DEVICE_CDROM: buses.append(["ide", "IDE"]) if self.vm.rhel6_defaults(): buses.append(["scsi", "SCSI"]) else: if self.vm.is_hvm(): buses.append(["ide", "IDE"]) if self.vm.rhel6_defaults(): buses.append(["scsi", "SCSI"]) buses.append(["usb", "USB"]) if self.vm.get_hv_type() in ["kvm", "test"]: buses.append(["sata", "SATA"]) buses.append(["virtio", "Virtio"]) if (self.vm.get_hv_type() == "kvm" and self.vm.get_machtype() == "pseries"): buses.append(["spapr-vscsi", "sPAPR-vSCSI"]) if self.vm.conn.is_xen() or self.vm.get_hv_type() == "test": buses.append(["xen", "Xen"]) for row in buses: busmodel.append(row) if not no_default: busmodel.append([None, "default"]) def populate_hw_list(self): hw_list_model = self.widget("hw-list").get_model() hw_list_model.clear() def add_hw_list_option(title, page_id, icon_name): hw_list_model.append([title, icon_name, Gtk.IconSize.LARGE_TOOLBAR, page_id, title]) add_hw_list_option("Overview", HW_LIST_TYPE_GENERAL, "computer") if not self.is_customize_dialog: add_hw_list_option("Performance", HW_LIST_TYPE_STATS, "utilities-system-monitor") add_hw_list_option("Processor", HW_LIST_TYPE_CPU, "device_cpu") add_hw_list_option("Memory", HW_LIST_TYPE_MEMORY, "device_mem") add_hw_list_option("Boot Options", HW_LIST_TYPE_BOOT, "system-run") self.repopulate_hw_list() def repopulate_hw_list(self): hw_list = self.widget("hw-list") hw_list_model = hw_list.get_model() currentDevices = [] def dev_cmp(origdev, newdev): if isinstance(origdev, str): return False if origdev == newdev: return True if not origdev.get_xml_node_path(): return False return origdev.get_xml_node_path() == newdev.get_xml_node_path() def add_hw_list_option(idx, name, page_id, info, icon_name): hw_list_model.insert(idx, [name, icon_name, Gtk.IconSize.LARGE_TOOLBAR, page_id, info]) def update_hwlist(hwtype, info, name, icon_name): """ See if passed hw is already in list, and if so, update info. If not in list, add it! """ currentDevices.append(info) insertAt = 0 for row in hw_list_model: rowdev = row[HW_LIST_COL_DEVICE] if dev_cmp(rowdev, info): # Update existing HW info row[HW_LIST_COL_DEVICE] = info row[HW_LIST_COL_LABEL] = name row[HW_LIST_COL_ICON_NAME] = icon_name return if row[HW_LIST_COL_TYPE] <= hwtype: insertAt += 1 # Add the new HW row add_hw_list_option(insertAt, name, hwtype, info, icon_name) # Populate list of disks for disk in self.vm.get_disk_devices(): devtype = disk.device bus = disk.bus idx = disk.disk_bus_index icon = "drive-harddisk" if devtype == "cdrom": icon = "media-optical" elif devtype == "floppy": icon = "media-floppy" if disk.address.type == "spapr-vio": bus = "spapr-vscsi" label = prettyify_disk(devtype, bus, idx) update_hwlist(HW_LIST_TYPE_DISK, disk, label, icon) # Populate list of NICs for net in self.vm.get_network_devices(): mac = net.macaddr update_hwlist(HW_LIST_TYPE_NIC, net, "NIC %s" % mac[-9:], "network-idle") # Populate list of input devices for inp in self.vm.get_input_devices(): inptype = inp.type icon = "input-mouse" if inptype == "tablet": label = _("Tablet") icon = "input-tablet" elif inptype == "mouse": label = _("Mouse") else: label = _("Input") update_hwlist(HW_LIST_TYPE_INPUT, inp, label, icon) # Populate list of graphics devices for gfx in self.vm.get_graphics_devices(): update_hwlist(HW_LIST_TYPE_GRAPHICS, gfx, _("Display %s") % gfx.pretty_type_simple(gfx.type), "video-display") # Populate list of sound devices for sound in self.vm.get_sound_devices(): update_hwlist(HW_LIST_TYPE_SOUND, sound, _("Sound: %s" % sound.model), "audio-card") # Populate list of char devices for chardev in self.vm.get_char_devices(): devtype = chardev.virtual_device_type port = chardev.target_port label = devtype.capitalize() if devtype not in ["console", "channel"]: # Don't show port for console label += " %s" % (int(port) + 1) update_hwlist(HW_LIST_TYPE_CHAR, chardev, label, "device_serial") # Populate host devices for hostdev in self.vm.get_hostdev_devices(): devtype = hostdev.type label = build_hostdev_label(hostdev)[1] if devtype == "usb": icon = "device_usb" else: icon = "device_pci" update_hwlist(HW_LIST_TYPE_HOSTDEV, hostdev, label, icon) # Populate redir devices for redirdev in self.vm.get_redirdev_devices(): bus = redirdev.bus label = build_redir_label(redirdev)[1] if bus == "usb": icon = "device_usb" else: icon = "device_pci" update_hwlist(HW_LIST_TYPE_REDIRDEV, redirdev, label, icon) # Populate video devices for vid in self.vm.get_video_devices(): update_hwlist(HW_LIST_TYPE_VIDEO, vid, _("Video %s") % vid.pretty_model(vid.model_type), "video-display") # Populate watchdog devices for watch in self.vm.get_watchdog_devices(): update_hwlist(HW_LIST_TYPE_WATCHDOG, watch, _("Watchdog"), "device_pci") # Populate controller devices for cont in self.vm.get_controller_devices(): # skip USB2 ICH9 companion controllers if cont.model in ["ich9-uhci1", "ich9-uhci2", "ich9-uhci3"]: continue pretty_type = virtinst.VirtualController.pretty_type(cont.type) update_hwlist(HW_LIST_TYPE_CONTROLLER, cont, _("Controller %s") % pretty_type, "device_pci") # Populate filesystem devices for fs in self.vm.get_filesystem_devices(): target = fs.target[:8] update_hwlist(HW_LIST_TYPE_FILESYSTEM, fs, _("Filesystem %s") % target, Gtk.STOCK_DIRECTORY) # Populate list of smartcard devices for sc in self.vm.get_smartcard_devices(): update_hwlist(HW_LIST_TYPE_SMARTCARD, sc, _("Smartcard"), "device_serial") devs = range(len(hw_list_model)) devs.reverse() for i in devs: _iter = hw_list_model.iter_nth_child(None, i) olddev = hw_list_model[i][HW_LIST_COL_DEVICE] # Existing device, don't remove it if type(olddev) is str or olddev in currentDevices: continue hw_list_model.remove(_iter) def repopulate_boot_list(self, bootdevs=None, dev_select=None): boot_list = self.widget("config-boot-list") boot_model = boot_list.get_model() old_order = [x[BOOT_DEV_TYPE] for x in boot_model] boot_model.clear() if bootdevs is None: bootdevs = self.vm.get_boot_device() boot_rows = { "hd" : ["hd", "Hard Disk", "drive-harddisk", False], "cdrom" : ["cdrom", "CDROM", "media-optical", False], "network" : ["network", "Network (PXE)", "network-idle", False], "fd" : ["fd", "Floppy", "media-floppy", False], } for dev in bootdevs: foundrow = None for key, row in boot_rows.items(): if key == dev: foundrow = row del(boot_rows[key]) break if not foundrow: # Some boot device listed that we don't know about. foundrow = [dev, "Boot type '%s'" % dev, "drive-harddisk", True] foundrow[BOOT_ACTIVE] = True boot_model.append(foundrow) # Append all remaining boot_rows that aren't enabled for dev in old_order: if dev in boot_rows: boot_model.append(boot_rows[dev]) del(boot_rows[dev]) for row in boot_rows.values(): boot_model.append(row) boot_list.set_model(boot_model) selection = boot_list.get_selection() if dev_select: idx = 0 for row in boot_model: if row[BOOT_DEV_TYPE] == dev_select: break idx += 1 boot_list.get_selection().select_path(str(idx)) elif not selection.get_selected()[1]: # Set a default selection selection.select_path("0") def show_pair(self, basename, show): combo = self.widget(basename) label = self.widget(basename + "-title") combo.set_property("visible", show) label.set_property("visible", show)
yumingfei/virt-manager
virtManager/details.py
Python
gpl-2.0
134,336
# This file is part of the Hotwire Shell user interface. # # Copyright (C) 2007,2008 Colin Walters <[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. import logging import gobject import gtk from .wraplabel import WrapLabel _logger = logging.getLogger("hotwire.ui.MsgArea") # This file is a Python translation of gedit/gedit/gedit-message-area.c class MsgArea(gtk.HBox): __gtype_name__ = "MsgArea" __gsignals__ = { "response" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_INT,)), "close" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, []) } def __init__(self, buttons, **kwargs): super(MsgArea, self).__init__(**kwargs) self.__contents = None self.__labels = [] self.__changing_style = False self.__main_hbox = gtk.HBox(False, 16) # FIXME: use style properties self.__main_hbox.show() self.__main_hbox.set_border_width(8) # FIXME: use style properties self.__action_area = gtk.VBox(True, 4); # FIXME: use style properties self.__action_area.show() self.__main_hbox.pack_end (self.__action_area, False, True, 0) self.pack_start(self.__main_hbox, True, True, 0) self.set_app_paintable(True) self.connect("expose-event", self.__paint) # Note that we connect to style-set on one of the internal # widgets, not on the message area itself, since gtk does # not deliver any further style-set signals for a widget on # which the style has been forced with gtk_widget_set_style() self.__main_hbox.connect("style-set", self.__on_style_set) self.add_buttons(buttons) def __get_response_data(self, w, create): d = w.get_data('hotwire-msg-area-data') if (d is None) and create: d = {'respid': None} w.set_data('hotwire-msg-area-data', d) return d def __find_button(self, respid): children = self.__actionarea.get_children() for child in children: rd = self.__get_response_data(child, False) if rd is not None and rd['respid'] == respid: return child def __close(self): cancel = self.__find_button(gtk.RESPONSE_CANCEL) if cancel is None: return self.response(gtk.RESPONSE_CANCEL) def __paint(self, w, event): gtk.Style.paint_flat_box(w.style, w.window, gtk.STATE_NORMAL, gtk.SHADOW_OUT, None, w, "tooltip", w.allocation.x + 1, w.allocation.y + 1, w.allocation.width - 2, w.allocation.height - 2) return False def __on_style_set(self, w, style): if self.__changing_style: return # This is a hack needed to use the tooltip background color window = gtk.Window(gtk.WINDOW_POPUP); window.set_name("gtk-tooltip") window.ensure_style() style = window.get_style() self.__changing_style = True self.set_style(style) for label in self.__labels: label.set_style(style) self.__changing_style = False window.destroy() self.queue_draw() def __get_response_for_widget(self, w): rd = self.__get_response_data(w, False) if rd is None: return gtk.RESPONSE_NONE return rd['respid'] def __on_action_widget_activated(self, w): response_id = self.__get_response_for_widget(w) self.response(response_id) def add_action_widget(self, child, respid): rd = self.__get_response_data(child, True) rd['respid'] = respid if not isinstance(child, gtk.Button): raise ValueError("Can only pack buttons as action widgets") child.connect('clicked', self.__on_action_widget_activated) if respid != gtk.RESPONSE_HELP: self.__action_area.pack_start(child, False, False, 0) else: self.__action_area.pack_end(child, False, False, 0) def set_contents(self, contents): self.__contents = contents self.__main_hbox.pack_start(contents, True, True, 0) def add_button(self, btext, respid): button = gtk.Button(stock=btext) button.set_focus_on_click(False) button.set_flags(gtk.CAN_DEFAULT) button.show() self.add_action_widget(button, respid) return button def add_buttons(self, args): _logger.debug("init buttons: %r", args) for (btext, respid) in args: self.add_button(btext, respid) def set_response_sensitive(self, respid, setting): for child in self.__action_area.get_children(): rd = self.__get_response_data(child, False) if rd is not None and rd['respid'] == respid: child.set_sensitive(setting) break def set_default_response(self, respid): for child in self.__action_area.get_children(): rd = self.__get_response_data(child, False) if rd is not None and rd['respid'] == respid: child.grab_default() break def response(self, respid): self.emit('response', respid) def add_stock_button_with_text(self, text, stockid, respid): b = gtk.Button(label=text) b.set_focus_on_click(False) img = gtk.Image() img.set_from_stock(stockid, gtk.ICON_SIZE_BUTTON) b.set_image(img) b.show_all() self.add_action_widget(b, respid) return b def set_text_and_icon(self, stockid, primary_text, secondary_text=None): hbox_content = gtk.HBox(False, 8) hbox_content.show() image = gtk.Image() image.set_from_stock(stockid, gtk.ICON_SIZE_DIALOG) image.show() hbox_content.pack_start(image, False, False, 0) image.set_alignment(0.5, 0.5) vbox = gtk.VBox(False, 6) vbox.show() hbox_content.pack_start (vbox, True, True, 0) self.__labels = [] primary_markup = "<b>%s</b>" % (primary_text,) primary_label = WrapLabel(primary_markup) primary_label.show() vbox.pack_start(primary_label, True, True, 0) primary_label.set_use_markup(True) primary_label.set_line_wrap(True) primary_label.set_alignment(0, 0.5) primary_label.set_flags(gtk.CAN_FOCUS) primary_label.set_selectable(True) self.__labels.append(primary_label) if secondary_text: secondary_markup = "<small>%s</small>" % (secondary_text,) secondary_label = WrapLabel(secondary_markup) secondary_label.show() vbox.pack_start(secondary_label, True, True, 0) secondary_label.set_flags(gtk.CAN_FOCUS) secondary_label.set_use_markup(True) secondary_label.set_line_wrap(True) secondary_label.set_selectable(True) secondary_label.set_alignment(0, 0.5) self.__labels.append(secondary_label) self.set_contents(hbox_content) class MsgAreaController(gtk.HBox): __gtype_name__ = "MsgAreaController" def __init__(self): super(MsgAreaController, self).__init__() self.__msgarea = None self.__msgid = None def has_message(self): return self.__msgarea is not None def get_msg_id(self): return self.__msgid def set_msg_id(self, msgid): self.__msgid = msgid def clear(self): if self.__msgarea is not None: self.remove(self.__msgarea) self.__msgarea.destroy() self.__msgarea = None self.__msgid = None def new_from_text_and_icon(self, stockid, primary, secondary=None, buttons=[]): self.clear() msgarea = self.__msgarea = MsgArea(buttons) msgarea.set_text_and_icon(stockid, primary, secondary) self.pack_start(msgarea, expand=True) return msgarea
pedrox/meld
meld/ui/msgarea.py
Python
gpl-2.0
8,901
# -*- coding: utf-8 -*- """ /*************************************************************************** BirdChooserDialog A QGIS plugin Show bird observations ------------------- begin : 2015-11-05 git sha : $Format:%H$ copyright : (C) 2015 by Jerome email : [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. * * * ***************************************************************************/ """ import os import psycopg2 from PyQt4 import QtGui, uic from qgis.core import QgsDataSourceURI, QgsVectorLayer, QgsMapLayerRegistry, QgsMarkerSymbolV2, QgsMessageLog FORM_CLASS, _ = uic.loadUiType(os.path.join( os.path.dirname(__file__), 'bird_chooser_dialog_base.ui')) class BirdChooserDialog(QtGui.QDialog, FORM_CLASS): def __init__(self, iface, parent=None): """Constructor.""" super(BirdChooserDialog, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html # #widgets-and-dialogs-with-auto-connect self.setupUi(self) self.iface = iface # Connecter les slots self._connectSlots() #self.conn = psycopg2.connect(database = "jguelat", user = "jguelat", password = "") self.conn = psycopg2.connect(service = "local_jguelat") def _connectSlots(self): self.tableCombo.activated.connect(self.getSpecies) # Quand la fenetre est fermee (d'une maniere ou d'une autre) self.finished.connect(self.closeConnection) self.addLayerButton.clicked.connect(self.addLayer) def getSpecies(self): self.speciesCombo.clear() cur = self.conn.cursor() cur.execute("SELECT DISTINCT species_id from " + self.tableCombo.currentText() + " ORDER BY species_id") rows = cur.fetchall() self.speciesCombo.addItems([str(elem[0]) for elem in rows]) self.addLayerButton.setEnabled(True) cur.close() def addLayer(self): uri = QgsDataSourceURI() # set host name, port, database name, username and password #uri.setConnection("localhost", "5432", "jguelat", "jguelat", "") uri.setConnection("local_jguelat", "", "", "") # set database schema, table name, geometry column and optionally subset (WHERE clause) uri.setDataSource("public", self.tableCombo.currentText(), "geom", "species_id = " + self.speciesCombo.currentText()) #vlayer = self.iface.addVectorLayer(uri.uri(), "Species " + self.speciesCombo.currentText(), "postgres") vlayer = QgsVectorLayer(uri.uri(), "Species " + self.speciesCombo.currentText(), "postgres") props = vlayer.rendererV2().symbol().symbolLayer(0).properties() props['size'] = '3' props['color'] = 'blue' vlayer.rendererV2().setSymbol(QgsMarkerSymbolV2.createSimple(props)) QgsMapLayerRegistry.instance().addMapLayer(vlayer) QgsMessageLog.logMessage("Tout est OK", 'BirdChooser', QgsMessageLog.INFO) def closeConnection(self): self.conn.close()
jguelat/BirdChooser
bird_chooser_dialog.py
Python
gpl-2.0
3,907
from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.channel_list), url(r'^play', views.play_channel), url(r'^hello', views.hello), ]
Sistemas-Multimedia/Icecast-tracker
Django/rocio333/IcecastTracker333/IcecastTracker333app/urls.py
Python
gpl-2.0
179
from django.conf import settings from geopy import distance, geocoders import pygeoip def get_geodata_by_ip(addr): gi = pygeoip.GeoIP(settings.GEO_CITY_FILE, pygeoip.MEMORY_CACHE) geodata = gi.record_by_addr(addr) return geodata def get_geodata_by_region(*args): gn = geocoders.GeoNames() return gn.geocode(' '.join(args), exactly_one=False)[0] def get_distance(location1, location2): """ Calculate distance between two locations, given the (lat, long) of each. Required Arguments: location1 A tuple of (lat, long). location2 A tuple of (lat, long). """ return distance.distance(location1, location2).miles
iuscommunity/dmirr
src/dmirr.hub/dmirr/hub/lib/geo.py
Python
gpl-2.0
735
# Copright (C) 2015 Eric Skoglund # # 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, see http://www.gnu.org/licenses/gpl-2.0.html import requests import sys class NotSupported(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class PasteSite(object): def __init__(self, url): self.url = url self.paste_url = None self.data = None @staticmethod def siteFactory(site_name): if site_name == 'slexy.org': return Slexy() elif site_name == 'pastebin.mozilla.org': return Mozilla() else: raise NotSupported("This site is not supported") def parse(self, args): """ Internal method used by the PasteSite class. Returns a dictionary of the parsed input arguments. Parses the arguments given at the command line. Many pastebin like sites use different arguments for the paste so this method should be implemented for each subclass of PasteSite. See the slexy class for an example of how to implement this method for subclasses. """ self.data = args def paste(self): """Posts the data to the paste site. This method tries to post the data to the paste site. If the resulting request does not have a ok status the program exits else we return the resulting paste url. The method assumes that the data is in a dictionary. """ if self.data == None: print('You can only paste after a parse') sys.exit(-1) res = requests.post(self.url, self.data) if not res.ok: print('Bad response {0} {1}'.format(res.reason, res.status_code)) sys.exit(-1) self.paste_url = res.url class Slexy(PasteSite): def __init__(self): super(Slexy, self).__init__('http://slexy.org/submit') def parse(self, args): form_data = {} arg_translation = {'text' : 'raw_paste', 'language' : 'language', 'expiration' : 'expire', 'comment' : 'comment', 'description' : 'descr', 'visibility' : 'permissions', 'linum' : 'linenumbers', 'author' : 'author'} for k,v in args.items(): if arg_translation.get(k): form_data[arg_translation[k]] = v form_data['submit'] = 'Submit Paste' self.data = form_data class Mozilla(PasteSite): def __init__(self): super(Mozilla, self).__init__('https://pastebin.mozilla.org') def parse(self, args): form_data = {} arg_translation = {'text' : 'code2', 'expiration' : 'expiry', 'syntax_highlight' : 'format', 'author' : 'poster'} for k,v in args.items(): if arg_translation.get(k): form_data[arg_translation[k]] = v form_data['paste'] = 'Send' form_data['parent_pid'] = '' self.data = form_data
EricIO/pasteit
pasteit/PasteSites.py
Python
gpl-2.0
3,878
import os import string import random import logging from thug.ActiveX.modules import WScriptShell from thug.ActiveX.modules import TextStream from thug.ActiveX.modules import File from thug.ActiveX.modules import Folder from thug.OS.Windows import win32_files from thug.OS.Windows import win32_folders log = logging.getLogger("Thug") def BuildPath(self, arg0, arg1): # pylint:disable=unused-argument log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] BuildPath("{arg0}", "{arg1}")') return f"{arg0}\\{arg1}" def CopyFile(self, source, destination, overwritefiles = False): # pylint:disable=unused-argument log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] CopyFile("{source}", "{destination}")') log.TextFiles[destination] = log.TextFiles[source] def DeleteFile(self, filespec, force = False): # pylint:disable=unused-argument log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] DeleteFile("{filespec}", {force})') def CreateTextFile(self, filename, overwrite = False, _unicode = False): # pylint:disable=unused-argument log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] CreateTextFile("{filename}", ' f'"{overwrite}", ' f'"{_unicode}")') stream = TextStream.TextStream() stream._filename = filename return stream def CreateFolder(self, path): # pylint:disable=unused-argument log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] CreateFolder("{path}")') return Folder.Folder(path) def FileExists(self, filespec): # pylint:disable=unused-argument log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] FileExists("{filespec}")') if not filespec: return True if filespec.lower() in win32_files: return True if getattr(log, "TextFiles", None) and filespec in log.TextFiles: return True return False def FolderExists(self, folder): # pylint:disable=unused-argument log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] FolderExists("{folder}")') return str(folder).lower() in win32_folders def GetExtensionName(self, path): # pylint:disable=unused-argument log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] GetExtensionName("{path}")') ext = os.path.splitext(path)[1] return ext if ext else "" def GetFile(self, filespec): # pylint:disable=unused-argument log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] GetFile("{filespec}")') return File.File(filespec) def GetSpecialFolder(self, arg): log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] GetSpecialFolder("{arg}")') arg = int(arg) folder = '' if arg == 0: folder = WScriptShell.ExpandEnvironmentStrings(self, "%windir%") elif arg == 1: folder = WScriptShell.ExpandEnvironmentStrings(self, "%SystemRoot%\\system32") elif arg == 2: folder = WScriptShell.ExpandEnvironmentStrings(self, "%TEMP%") log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] Returning {folder} for GetSpecialFolder("{arg}")') return folder def GetTempName(self): # pylint:disable=unused-argument log.ThugLogging.add_behavior_warn('[Scripting.FileSystemObject ActiveX] GetTempName()') return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8)) def MoveFile(self, source, destination): # pylint:disable=unused-argument log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] MoveFile("{source}", "{destination}")') log.TextFiles[destination] = log.TextFiles[source] del log.TextFiles[source] def OpenTextFile(self, sFilePathAndName, ForWriting = True, flag = True): log.ThugLogging.add_behavior_warn(f'[Scripting.FileSystemObject ActiveX] OpenTextFile("{sFilePathAndName}", ' f'"{ForWriting}" ,' f'"{flag}")') log.ThugLogging.log_exploit_event(self._window.url, "Scripting.FileSystemObject ActiveX", "OpenTextFile", data = { "filename" : sFilePathAndName, "ForWriting": ForWriting, "flag" : flag }, forward = False) if getattr(log, 'TextFiles', None) is None: log.TextFiles = {} if sFilePathAndName in log.TextFiles: return log.TextFiles[sFilePathAndName] stream = TextStream.TextStream() stream._filename = sFilePathAndName if log.ThugOpts.local and sFilePathAndName in (log.ThugLogging.url, ): # pragma: no cover with open(sFilePathAndName, encoding = 'utf-8', mode = 'r') as fd: data = fd.read() stream.Write(data) log.TextFiles[sFilePathAndName] = stream return stream
buffer/thug
thug/ActiveX/modules/ScriptingFileSystemObject.py
Python
gpl-2.0
5,185
# # Copyright 2015 Red Hat, 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 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 # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import import sys import inspect import unittest from mock import patch from mock import MagicMock from . import get_driver from . import get_driver_class from . import get_driver_names from .driverbase import VirtDeployDriverBase if sys.version_info[0] == 3: # pragma: no cover builtin_import = 'builtins.__import__' else: # pragma: no cover builtin_import = '__builtin__.__import__' def try_import(spec): def fake_import(name, globals={}, locals={}, fromlist=[], level=0): try: return spec(name, globals, locals, fromlist, level) except ImportError: return MagicMock() return fake_import class TestVirtDeployDriverBase(unittest.TestCase): def _get_driver_methods(self): return inspect.getmembers(VirtDeployDriverBase, inspect.ismethod) def _get_driver_class(self, name): with patch(builtin_import, spec=True, new_callable=try_import): return get_driver_class(name) def _get_driver(self, name): with patch(builtin_import, spec=True, new_callable=try_import): return get_driver(name) def test_base_not_implemented(self): driver = VirtDeployDriverBase() for name, method in self._get_driver_methods(): spec = inspect.getargspec(method) with self.assertRaises(NotImplementedError) as cm: getattr(driver, name)(*(None,) * (len(spec.args) - 1)) self.assertEqual(cm.exception.args[0], name) def test_drivers_interface(self): for driver_name in get_driver_names(): driver = self._get_driver_class(driver_name) for name, method in self._get_driver_methods(): driver_method = getattr(driver, name) self.assertNotEqual(driver_method, method) self.assertEqual(inspect.getargspec(method), inspect.getargspec(driver_method)) def test_get_drivers(self): for driver_name in get_driver_names(): driver = self._get_driver(driver_name) self.assertTrue(isinstance(driver, VirtDeployDriverBase))
jaryn/virt-deploy
virtdeploy/test_driverbase.py
Python
gpl-2.0
2,986
# ============================================================================ ''' This file is part of the lenstractor project. Copyright 2012 David W. Hogg (NYU) and Phil Marshall (Oxford). Description ----------- General-purpose data management classes and functions: * Order a pile of FITS files into scifiles and matching varfiles * Read in a deck of postcard images in FITS files and return an array of tractor image data structures. ''' import numpy as np import os,glob,string,pyfits,subprocess from astrometry.util import util import tractor import lenstractor # ============================================================================ # Parse filenames for sci and wht images: def Riffle(filenames,vb=False): if vb: print "Looking at",len(filenames),"files: ",filenames # Break down file names. Naming convention: fruit_flavor.fits fruits = [] flavors = [] for filename in set(filenames): pieces = string.split(filename,'_') fruits.append(string.join(pieces[0:-1],'_')) flavors.append(string.split(pieces[-1],'.')[0]) if len(set(flavors)) > 2: raise ValueError("ERROR: expecting 1 or 2 flavors of datafile, got more") elif len(set(flavors)) == 0: raise ValueError("ERROR: expecting 1 or 2 flavors of datafile, got none") if 'sci' not in set(flavors): raise ValueError("ERROR: expecting at least some files to be xxx_sci.fits") if len(set(flavors)) == 1: whttype = 'No-one_will_ever_choose_this_flavor' else: for x in (set(flavors) - set(['sci'])): whttype = x number = len(set(fruits)) scifiles = [] whtfiles = [] for fruit in set(fruits): x = fruit+'_sci.fits' if os.path.exists(x): scifiles.append(x) else: scifiles.append(None) x = fruit+'_'+whttype+'.fits' if os.path.exists(x): whtfiles.append(x) else: whtfiles.append(None) if vb: print "Riffled files into",number,"pair(s)" if len(set(flavors)) == 1: print "Only 1 flavor of file found, sci" else: print "2 flavors of file found: sci and",whttype for i in range(number): print " ",i+1,"th pair:",[scifiles[i],whtfiles[i]] return scifiles,whtfiles # ============================================================================ # Read in data and organise into Tractor Image objects. # Some of this is survey specific: subroutines to be stored in $survey.py. def Deal(scifiles,varfiles,SURVEY='PS1',vb=False): images = [] bands = [] epochs = [] centroids = [] total_mags = [] for scifile,varfile in zip(scifiles,varfiles): name = scifile.replace('_sci.fits','') if vb: print " " print "Making Tractor image from "+name+"_*.fits:" # Read in sci and wht images. Note assumptions about file format: sci,invvar,hdr,total_flux = Read_in_data(scifile,varfile,SURVEY=SURVEY,vb=vb) if total_flux == 0.0: print "No flux found in image from "+scifile print "Skipping to next image!" continue # Initialize a PSF object (single Gaussian by default), first # getting FWHM from somewhere. Start with FWHM a little small, # then refine it: if SURVEY=='PS1': try: FWHM = lenstractor.PS1_IQ(hdr) except: FWHM = 1.4 elif SURVEY=='KIDS': FWHM = lenstractor.KIDS_IQ(hdr) elif SURVEY=='SDSS': try: FWHM = lenstractor.SDSS_IQ(hdr) except: FWHM = 'NaN' if FWHM == 'NaN': print "Problem with initialising PSF for SDSS, using (1.4,0.4) default" FWHM = 1.4/0.4 else: raise ValueError('Unrecognised survey name '+SURVEY) if vb: print " PSF FWHM =",FWHM,"pixels" # MAGIC shrinkage factor: shrink = 0.8 psf = Initial_PSF(shrink*FWHM) if vb: print psf # Now get the photometric calibration from the image header. if SURVEY=='PS1': try: band,photocal = lenstractor.PS1_photocal(hdr) except: band,photocal = lenstractor.SDSS_photocal(hdr) elif SURVEY=='KIDS': band,photocal = lenstractor.KIDS_photocal(hdr) elif SURVEY=='SDSS': band,photocal = lenstractor.SDSS_photocal(hdr) else: print "Unrecognised survey name "+SURVEY+", assuming SDSS" band,photocal = lenstractor.SDSS_photocal(hdr) if vb: print photocal bands.append(band) if SURVEY=='PS1': try: epochs.append(lenstractor.PS1_epoch(hdr)) except: epochs.append(lenstractor.SDSS_epoch(hdr)) elif SURVEY=='KIDS': epochs.append(lenstractor.KIDS_epoch(hdr)) elif SURVEY=='SDSS': epochs.append(lenstractor.SDSS_epoch(hdr)) # Use photocal to return a total magnitude: total_mag = photocal.countsToMag(total_flux) if vb: print "Total brightness of image (mag):",total_mag total_mags.append(total_mag) # Set up sky to be varied: median = np.median(sci[invvar > 0]) sky = tractor.ConstantSky(median) delta = 0.1*np.sqrt(1.0/np.sum(invvar)) assert delta > 0 sky.stepsize = delta if vb: print sky # Get WCS from FITS header: if SURVEY=='PS1': try: wcs = lenstractor.PS1WCS(hdr) except: wcs = lenstractor.SDSSWCS(hdr) elif SURVEY=='KIDS': wcs = lenstractor.KIDSWCS(hdr) else: try: wcs = lenstractor.SDSSWCS(hdr) except: wcs = lenstractor.SDSSWCS(hdr) # if vb: # print wcs # Compute flux-weighted centroid, in world coordinates: NX,NY = sci.shape x = np.outer(np.ones(NX),np.linspace(0,NY-1,NY)) y = np.outer(np.linspace(0,NX-1,NX),np.ones(NY)) x0 = np.sum(sci*x)/np.sum(sci) y0 = np.sum(sci*y)/np.sum(sci) # BUG: this returns pretty much the image center, not # the object center... Need a better object finder! radec = wcs.pixelToPosition(x0,y0) centroids.append(radec) print "Flux centroid: ",radec # Make a tractor Image object out of all this stuff, and add it to the array: images.append(tractor.Image(data=sci, invvar=invvar, name=name, psf=psf, wcs=wcs, sky=sky, photocal=photocal)) # Figure out the unique band names and epochs: uniqbands = np.unique(np.array(bands)) if vb: print " " print "Read in",len(images),"image datasets" print " in",len(uniqbands),"bands:",uniqbands print " at",len(epochs),"epochs" print " " return images,centroids,np.array(total_mags),np.array(bands) # ============================================================================ # Read in sci and wht images. Note assumptions about file format: def Read_in_data(scifile,varfile,SURVEY='PS1',vb=False): hdulist = pyfits.open(scifile) sci = hdulist[0].data hdr = hdulist[0].header hdulist.close() NX,NY = sci.shape if (varfile is not None): hdulist = pyfits.open(varfile) var = hdulist[0].data hdulist.close() else: # Make a var image from the sci image... background = np.median(sci) diffimage = sci - background # Get the flux-to-count conversion factor from header, at least in SDSS: try: tmpsurvey = hdr['ORIGIN'] if (tmpsurvey == 'SDSS'): tempmtoc = hdr['NMGY'] else: tempmtoc = 1. except: tempmtoc = 1. background, diffimage = background/tempmtoc, diffimage/tempmtoc # units: counts variance = np.median(diffimage*diffimage) # sky count variance var = diffimage + variance # variance in the whole image number-counts # Go again in fluxes var = (tempmtoc**2)*var # Ensure positivity: var[var <= 0] = variance*(tempmtoc**2) # Check image sizes... assert sci.shape == var.shape if SURVEY == 'KIDS': # Var image is actually already an inverse variance image! invvar = var.copy() var = 1.0/invvar else: # Convert var to wht, and find median uncertainty as well: # Regardless of maggy-count conversion, start again here: invvar = 1.0/var # Assign zero weight to var=nan, var<=0: invvar[var != var] = 0.0 invvar[var <= 0] = 0.0 bad = np.where(invvar == 0) # Zero out sci image where wht is 0.0: sci[bad] = 0.0 assert(all(np.isfinite(sci.ravel()))) assert(all(np.isfinite(invvar.ravel()))) # Measure total flux in sci image: # total_flux = np.sum(sci) # background-subtracted background = np.median(sci) diffimage = sci - background total_flux = np.sum(diffimage) # Report on progress so far: if vb: print 'Science image:', sci.shape #, sci print 'Total flux:', total_flux print 'Variance image:', var.shape #, var if total_flux != 0.0: # Very rough estimates of background level and rms, never used: good = np.where(invvar > 0) sciback = np.median(sci[good]) scirms = np.sqrt(np.median(var[good])) if vb: print 'Useful variance range:', var[good].min(), var[good].max() print 'Useful image median level:', sciback print 'Useful image median pixel uncertainty:', scirms return sci,invvar,hdr,total_flux # ============================================================================ # Initialize a PSF object - by default, a single circularly symmetric Gaussian # defined on same grid as sci image: def Initial_PSF(FWHM,double=False): # NB. FWHM of PSF is given in pixels. if not double: # Single Gaussian default: w = np.array([1.0]) # amplitude at peak mu = np.array([[0.0,0.0]]) # centroid position in pixels var = (FWHM/2.35)**2.0 cov = np.array([[[var,0.0],[0.0,var]]]) # pixels^2, covariance matrix else: # Double Gaussian alternative: w = np.array([1.0,1.0]) mu = np.array([[0.0,0.0],[0.0,0.0]]) var = (FWHM/2.35)**2.0 cov = np.array([[[1.0,0.0],[0.0,1.0]],[[var,0.0],[0.0,var]]]) return tractor.GaussianMixturePSF(w,mu,cov) # ============================================================================ # Compute suitable mean centroid and magnitudes in each band: def Turnover(allbands,allmagnitudes,allcentroids,vb=False): # Models need good initial fluxes to avoid wasting time getting these # right. Take a quick look at the data to do this: # 1) Get rough idea of object position from wcs of first image - works # OK if all images are the same size and well registered, and the # target is in the center of the field... ra, dec = 0.0, 0.0 for radec in allcentroids: ra += radec.ra dec += radec.dec ra, dec = ra/len(allcentroids), dec/len(allcentroids) centroid = tractor.RaDecPos(ra,dec) print "Mean flux-weighted centroid: ",centroid # 2) Get rough idea of total object magnitudes from median of images # in each filter. (Models have non-variable flux, by assumption!) bandnames = np.unique(allbands) magnitudes = np.zeros(len(bandnames)) for i,bandname in enumerate(bandnames): index = np.where(allbands == bandname) magnitudes[i] = np.median(allmagnitudes[index]) SED = tractor.Mags(order=bandnames, **dict(zip(bandnames,magnitudes))) if vb: print "Mean SED: ",SED return centroid,SED # ============================================================================ if __name__ == '__main__': if True: # Basic test on lenstractor examples dir: folder = os.environ['LENSTRACTOR_DIR']+'/examples' inputfiles = glob.glob(os.path.join(folder,'*.fits')) scifiles,varfiles = riffle(inputfiles)
davidwhogg/LensTractor
lenstractor/dm.py
Python
gpl-2.0
12,090
# -*- coding: utf-8 -*- """ This file is part of quiedit. quiedit 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. quiedit 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 quiedit. If not, see <http://www.gnu.org/licenses/>. """ from PyQt4 import QtGui, QtCore import yaml class theme(object): """Handles theming.""" def __init__(self, editor): """ Constructor. Arguments: editor -- A qtquiedit object. """ self.editor = editor self.themeDict = yaml.load(open(self.editor.get_resource( \ u'themes.yaml')).read()) self.theme = self.recTheme(self.editor.theme) def apply(self): """Applies the theme.""" stylesheet = u""" background: %(editor_background)s; color: %(font_color)s; selection-color: %(editor_background)s; selection-background-color: %(font_color)s; font-family: %(font_family)s; font-size: %(font_size)spt; """ % self.theme self.editor.main_widget.setStyleSheet(u"background: %s;" \ % self.theme[u"main_background"]) self.editor.editor_frame.setStyleSheet(u"color: %s;" \ % self.theme[u"border_color"]) self.editor.search_box.setStyleSheet(stylesheet) self.editor.search_edit.setStyleSheet(u"border: 0;") self.editor.search_edit.setFont(self.font()) self.editor.search_label.setFont(self.font()) self.editor.command_box.setStyleSheet(stylesheet) self.editor.command_edit.setStyleSheet(u"border: 0;") self.editor.command_edit.setFont(self.font()) self.editor.command_label.setFont(self.font()) self.editor.status.setFont(self.font()) self.editor.status.setStyleSheet(u"color: %s;" % self.theme[ \ u"status_color"]) self.editor.central_widget.setMinimumWidth(int(self.theme[ \ u"editor_width"])) self.editor.central_widget.setMaximumWidth(int(self.theme[ \ u"editor_width"])) # Apply the theme to all quieditors for quieditor in self.editor.editor, self.editor.help, \ self.editor._markdown: quieditor.setStyleSheet(stylesheet) if not self.theme[u"scrollbar"]: quieditor.setVerticalScrollBarPolicy( \ QtCore.Qt.ScrollBarAlwaysOff) quieditor.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) # Apply the theme to the preferences screen self.editor.prefs.setStyleSheet(stylesheet) # Redo spellingcheck in the editor self.editor.editor.check_entire_document() # Hide the cursor for the main screen self.editor.setCursor(QtCore.Qt.BlankCursor) def font(self): """ Gives the theme font. Returns: A QFont. """ font = QtGui.QFont() font.setPointSize(int(self.theme[u'font_size'])) font.setFamily(self.theme[u'font_family']) return font def recTheme(self, theme): """ Gets the current theme, respecting inheritance. Arguments: theme -- The theme name. Returns: A dictionary with with the theme information. """ if theme not in self.themeDict: print(u'theme.__init__(): %s is not a valid theme' % theme) theme = u'default' d = self.themeDict[theme] if u'inherits' in d: _d = self.recTheme(d[u'inherits']) for key, val in _d.items(): if key not in d: d[key] = val return d
smathot/quiedit
libquiedit/theme.py
Python
gpl-2.0
3,523
#!/usr/bin/python # -*- coding: utf-8 -*- import common import connection import m3u8 import base64 import os import ustvpaths import re import simplejson import sys import time import urllib import xbmc import xbmcaddon import xbmcgui import xbmcplugin from bs4 import BeautifulSoup, SoupStrainer addon = xbmcaddon.Addon() pluginHandle = int(sys.argv[1]) def masterlist(SITE, SHOWS): master_db = [] master_data = connection.getURL(SHOWS) master_tree = simplejson.loads(master_data) for master_item in master_tree: if (master_item['hasNoVideo'] == 'false'): #print master_item try: master_name = common.smart_unicode(master_item['detailTitle']) master_db.append((master_name, SITE, 'seasons', urllib.quote_plus(master_item['showID']))) except Exception,e: print "Exception", e, master_item return master_db def seasons(SITE, SEASONSEPISODE, SEASONSCLIPS, EPISODES, CLIPS, season_url = common.args.url): seasons = [] season_data = connection.getURL(SEASONSEPISODE % season_url) season_tree = simplejson.loads(season_data)['season'] for season_item in season_tree: season_name = 'Season ' + str(season_item) seasons.append((season_name, SITE, 'episodes', EPISODES % (season_url, season_item), -1, -1)) season_url = common.args.url season_data = connection.getURL(SEASONSCLIPS % season_url) season_tree = simplejson.loads(season_data)['season'] for season_item in season_tree: season_name = 'Season Clips ' + str(season_item) seasons.append((season_name, SITE, 'episodes', CLIPS % (season_url, season_item), -1, -1)) return seasons def episodes(SITE, episode_url = common.args.url): episodes = [] episode_data = connection.getURL(episode_url) episode_tree = simplejson.loads(episode_data)['Items'] for episode_item in episode_tree: if episode_item['isBehindWall'] == 'false': url = episode_item['playURL_HLS'] episode_duration = int(episode_item['totalVideoDuration']) / 1000 try: episode_airdate = common.format_date(episode_item['airDate'].split('T')[0],'%Y-%m-%d') except: episode_airdate = -1 episode_name = episode_item['title'] try: season_number = int(episode_item['season']) except: season_number = -1 try: episode_number = int(episode_item['episode']) except: episode_number = -1 try: episode_thumb = episode_item['thumbnailImageURL'] except: try: episode_thumb = episode_item['stillImageURL'] except: try: episode_thumb = episode_item['modalImageURL'] except: episode_thumb = None episode_plot = episode_item['description'] episode_showtitle = episode_item['seriesName'] try: episode_mpaa = episode_item['rating'].upper() except: episode_mpaa = None try: episode_expires = episode_item['expirationDate'].split('T')[0] except: episode_expires = None if episode_item['mrssLengthType'] == 'Episode': episode_type = 'Full Episode' else: episode_type = 'Clips' try: if episode_item['isHD'] == 'true': episode_HD = True else: episode_HD = False except: episode_HD = False u = sys.argv[0] u += '?url="' + urllib.quote_plus(url) + '"' u += '&mode="' + SITE + '"' u += '&sitemode="play_video"' infoLabels={ 'title' : episode_name, 'durationinseconds' : episode_duration, 'season' : season_number, 'episode' : episode_number, 'plot' : episode_plot, 'premiered' : episode_airdate, 'TVShowTitle' : episode_showtitle, 'mpaa' : episode_mpaa } episodes.append((u, episode_name, episode_thumb, infoLabels, 'list_qualities', episode_HD, episode_type)) return episodes def list_qualities(): video_url = common.args.url bitrates = [] sig = sign_url(video_url) smil_url = re.compile('(.+)\?').findall(video_url)[0] + '?switch=hls&assetTypes=medium_video_s3&mbr=true&metafile=true&sig=' + sig video_data = connection.getURL(smil_url) smil_tree = BeautifulSoup(video_data, 'html.parser') video_url2 = smil_tree.video['src'] m3u_master_data = connection.getURL(video_url2) m3u_master = m3u8.parse(m3u_master_data) for video_index in m3u_master.get('playlists'): bitrate = int(video_index.get('stream_info')['bandwidth']) display = int(bitrate) / 1024 bitrates.append((display, bitrate)) return bitrates def play_video(): try: qbitrate = common.args.quality except: qbitrate = None closedcaption = None video_url = common.args.url sig = sign_url(video_url) smil_url = re.compile('(.+)\?').findall(video_url)[0] + '?switch=hls&assetTypes=medium_video_s3&mbr=true&metafile=true&sig=' + sig smil_data = connection.getURL(smil_url) smil_tree = BeautifulSoup(smil_data, 'html.parser') video_url2 = smil_tree.video['src'] try: closedcaption = smil_tree.textstream['src'] except: pass m3u_master_data = connection.getURL(video_url2, savecookie = True) m3u_master = m3u8.parse(m3u_master_data) hbitrate = -1 sbitrate = int(addon.getSetting('quality')) * 1024 for video_index in m3u_master.get('playlists'): bitrate = int(video_index.get('stream_info')['bandwidth']) if qbitrate is None: if bitrate > hbitrate and bitrate <= sbitrate: hbitrate = bitrate m3u8_url = video_index.get('uri') elif bitrate == qbitrate: m3u8_url = video_index.get('uri') m3u_data = connection.getURL(m3u8_url, loadcookie = True) key_url = re.compile('URI="(.*?)"').findall(m3u_data)[0] key_data = connection.getURL(key_url, loadcookie = True) key_file = open(ustvpaths.KEYFILE % '0', 'wb') key_file.write(key_data) key_file.close() video_url5 = re.compile('(http:.*?)\n').findall(m3u_data) for i, video_item in enumerate(video_url5): newurl = base64.b64encode(video_item) newurl = urllib.quote_plus(newurl) m3u_data = m3u_data.replace(video_item, 'http://127.0.0.1:12345/0/foxstation/' + newurl) localhttpserver = True filestring = 'XBMC.RunScript(' + os.path.join(ustvpaths.LIBPATH,'proxy.py') + ', 12345)' xbmc.executebuiltin(filestring) time.sleep(20) m3u_data = m3u_data.replace(key_url, 'http://127.0.0.1:12345/play0.key') playfile = open(ustvpaths.PLAYFILE, 'w') playfile.write(m3u_data) playfile.close() finalurl = ustvpaths.PLAYFILE if (addon.getSetting('enablesubtitles') == 'true') and (closedcaption is not None): convert_subtitles(closedcaption) item = xbmcgui.ListItem(path = finalurl) try: item.setThumbnailImage(common.args.thumb) except: pass try: item.setInfo('Video', { 'title' : common.args.name, 'season' : common.args.season_number, 'episode' : common.args.episode_number, 'TVShowTitle' : common.args.show_title}) except: pass xbmcplugin.setResolvedUrl(pluginHandle, True, item) if ((addon.getSetting('enablesubtitles') == 'true') and (closedcaption is not None)) or localhttpserver is True: while not xbmc.Player().isPlaying(): xbmc.sleep(100) if (addon.getSetting('enablesubtitles') == 'true') and (closedcaption is not None): xbmc.Player().setSubtitles(ustvpaths.SUBTITLE) if localhttpserver is True: while xbmc.Player().isPlaying(): xbmc.sleep(1000) connection.getURL('http://localhost:12345/stop', connectiontype = 0) def clean_subs(data): br = re.compile(r'<br.*?>') tag = re.compile(r'<.*?>') space = re.compile(r'\s\s\s+') apos = re.compile(r'&amp;apos;') gt = re.compile(r'&gt;') sub = br.sub('\n', data) sub = tag.sub(' ', sub) sub = space.sub(' ', sub) sub = apos.sub('\'', sub) sub = gt.sub('>', sub) return sub def convert_subtitles(closedcaption): str_output = '' subtitle_data = connection.getURL(closedcaption, connectiontype = 0) subtitle_data = BeautifulSoup(subtitle_data, 'html.parser', parse_only = SoupStrainer('div')) srt_output = '' lines = subtitle_data.find_all('p') i = 0 last_start_time = '' last_end_time = '' for line in lines: try: if line is not None: sub = clean_subs(common.smart_utf8(line)) start_time = common.smart_utf8(line['begin'].replace('.', ',')) end_time = common.smart_utf8(line['end'].replace('.', ',')) if start_time != last_start_time and end_time != last_end_time: str_output += '\n' + str(i + 1) + '\n' + start_time + ' --> ' + end_time + '\n' + sub + '\n' i = i + 1 last_end_time = end_time last_start_time = start_time else: str_output += sub + '\n\n' except: pass file = open(ustvpaths.SUBTITLE, 'w') file.write(str_output) file.close() return True def sign_url(url): query = { 'url' : re.compile('/[sz]/(.+)\?').findall(url)[0] } encoded = urllib.urlencode(query) sig = connection.getURL('http://servicesaetn-a.akamaihd.net/jservice/video/components/get-signed-signature?' + encoded) return sig
moneymaker365/plugin.video.ustvvod
resources/lib/main_aenetwork.py
Python
gpl-2.0
8,687
__author__ = 'bruno' import unittest import algorithms.graphs.complementGraph as ComplementGraph class TestComplementGraph(unittest.TestCase): def setUp(self): pass def test_complement_graph_1(self): graph = {'a': {'b': 1, 'c': 1}, 'b': {'a': 1, 'c': 1, 'd': 1}, 'c': {'a': 1, 'b': 1, 'd': 1}, 'd': {'b': 1, 'c': 1}} self.assertEqual({'a': {'d': 1}, 'd': {'a': 1}}, ComplementGraph.make_complement_graph(graph)) def test_complement_graph_2(self): graph = {'a': {'b': 1, 'd': 1}, 'b': {'a': 1, 'c': 1}, 'c': {'b': 1, 'd': 1}, 'd': {'a': 1, 'c': 1}} complement = {'a': {'c': 1}, 'b': {'d': 1}, 'c': {'a': 1}, 'd': {'b': 1}} self.assertEqual(complement, ComplementGraph.make_complement_graph(graph)) def test_complement_graph_3(self): graph = {'a': {'c': 1, 'd': 1}, 'b': {'c': 1, 'd': 1}, 'c': {'a': 1, 'b': 1}, 'd': {'a': 1, 'b': 1, 'e': 1, 'f': 1}, 'e': {'d': 1, 'f': 1}, 'f': {'d': 1, 'e': 1}} complement = {'a': {'b': 1, 'e': 1, 'f': 1}, 'b': {'a': 1, 'e': 1, 'f': 1}, 'c': {'e': 1, 'd': 1, 'f': 1}, 'd': {'c': 1}, 'e': {'a': 1, 'c': 1, 'b': 1}, 'f': {'a': 1, 'c': 1, 'b': 1}} self.assertEqual(complement, ComplementGraph.make_complement_graph(graph)) def test_complement_graph_4(self): graph = {'a': {'b': 1, 'f': 1}, 'b': {'a': 1, 'c': 1}, 'c': {'b': 1, 'd': 1}, 'd': {'c': 1, 'e': 1}, 'e': {'d': 1, 'f': 1}, 'f': {'a': 1, 'e': 1}} complement = {'a': {'c': 1, 'e': 1, 'd': 1}, 'b': {'e': 1, 'd': 1, 'f': 1}, 'c': {'a': 1, 'e': 1, 'f': 1}, 'd': {'a': 1, 'b': 1, 'f': 1}, 'e': {'a': 1, 'c': 1, 'b': 1}, 'f': {'c': 1, 'b': 1, 'd': 1}} self.assertEqual(complement, ComplementGraph.make_complement_graph(graph)) def test_complement_graph_5(self): graph = {'a': {'b': 1, 'c': 1, 'd': 1, 'e': 1}, 'b': {'a': 1, 'c': 1, 'd': 1, 'e': 1}, 'c': {'a': 1, 'b': 1, 'd': 1, 'e': 1}, 'd': {'a': 1, 'b': 1, 'c': 1, 'e': 1}, 'e': {'a': 1, 'b': 1, 'c': 1, 'd': 1, 'f': 1}, 'f': {'e': 1}} complement = {'a': {'f': 1}, 'b': {'f': 1}, 'c': {'f': 1}, 'd': {'f': 1}, 'f': {'a': 1, 'c': 1, 'b': 1, 'd': 1}} self.assertEqual(complement, ComplementGraph.make_complement_graph(graph))
bnsantos/python-junk-code
tests/graphs/complementGraphTest.py
Python
gpl-2.0
2,970
# Django settings for imageuploads project. import os PROJECT_DIR = os.path.dirname(__file__) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '[email protected]'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True MEDIA_ROOT = os.path.join(PROJECT_DIR, "media") STATIC_ROOT = os.path.join(PROJECT_DIR, "static") MEDIA_URL = "/media/" STATIC_URL = "/static/" # Additional locations of static files STATICFILES_DIRS = ( os.path.join(PROJECT_DIR, "site_static"), ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'qomeppi59pg-(^lh7o@seb!-9d(yr@5n^=*y9w&(=!yd2p7&e^' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'imageuploads.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'imageuploads.wsgi.application' TEMPLATE_DIRS = ( os.path.join(PROJECT_DIR, "templates"), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'south', 'crispy_forms', 'ajaxuploader', 'images', ) SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer' # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } CRISPY_TEMPLATE_PACK = 'bootstrap3' try: execfile(os.path.join(os.path.dirname(__file__), "local_settings.py")) except IOError: pass
archatas/imageuploads
imageuploads/settings.py
Python
gpl-2.0
4,670
from StateMachine.State import State from StateMachine.StateMachine import StateMachine from StateMachine.InputAction import InputAction from GameData.GameData import GameData class StateT(State): state_stack = list() game_data = GameData() def __init__(self): self.transitions = None def next(self, input): if self.transitions.has_key(input): return self.transitions[input] else: raise Exception("Input not supported for current state") class NightBegins(StateT): def run(self): print("NightTime Falls") def next(self, input): StateT.state_stack.append(self) if not self.transitions: self.transitions = { InputAction.getGameData : GameStates.nightBegins, InputAction.playHeroCard : GameStates.nightBegins, InputAction.playQuestCard : GameStates.nightBegins, InputAction.drawDSCard : GameStates.drawDSCard, } return StateT.next(self, input) class DrawDSCard(StateT): def run(self): print("Darkness Spreads drawing card") StateT.current_ds_card = StateT.game_data.ds_cards.pop() StateT.current_ds_card.display() print "STACK: " + str(StateT.state_stack) def next(self, input): StateT.state_stack.append(self) if not self.transitions: self.transitions = { InputAction.getGameData : GameStates.nightBegins, InputAction.playHeroCard : GameStates.nightBegins, InputAction.playQuestCard : GameStates.nightBegins, InputAction.drawDSCard : GameStates.drawDSCard, InputAction.executeDSCard : GameStates.executeDSCard, } return StateT.next(self, input) class ExecuteDSCard(StateT): def run(self): print("Darkness Spreads - executing card") StateT.current_ds_card.execute(StateT.game_data) print "STACK: " + str(StateT.state_stack) def next(self, input): StateT.state_stack.append(self) if not self.transitions: self.transitions = { InputAction.getGameData : GameStates.nightBegins, InputAction.playHeroCard : GameStates.nightBegins, InputAction.playQuestCard : GameStates.nightBegins, InputAction.drawDSCard : GameStates.drawDSCard, InputAction.advanceToDay : GameStates.dayBegins, } return StateT.next(self, input) class DayBegins(StateT): def run(self): print("Day Time") print "STACK: " + str(StateT.state_stack) def next(self, input): if not self.transitions: self.transitions = { InputAction.getGameData : GameStates.nightBegins, InputAction.playHeroCard : GameStates.nightBegins, InputAction.PlayQuestCard : GameStates.nightBegins, InputAction.advanceToEvening : GameStates.eveningBegins, } return StateT.next(self, input) class EveningBegins(StateT): def run(self): print("Day Time") print "STACK: " + str(StateT.state_stack) def next(self, input): if not self.transitions: self.transitions = { InputAction.getGameData : GameStates.nightBegins, InputAction.playHeroCard : GameStates.nightBegins, InputAction.PlayQuestCard : GameStates.nightBegins, InputAction.advanceToNight : GameStates.nightBegins, } return StateT.next(self, input) class GameStates(StateMachine): def __init__(self): # Initial state StateMachine.__init__(self, GameStates.nightBegins) # Static variable initialization: GameStates.nightBegins = NightBegins() GameStates.drawDSCard = DrawDSCard() GameStates.executeDSCard = ExecuteDSCard() GameStates.eveningBegins = EveningBegins() GameStates.dayBegins = DayBegins()
jmacleod/dotr
GameStates.py
Python
gpl-2.0
3,904
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from distutils.core import setup setup(name = "palabre", version = "0.6b", description = "XML Socket Python Server", long_description = "Flash XML Multiuser Socket Server", author = "Célio Conort", author_email = "[email protected]", url = "http://palabre.gavroche.net/", license = "GPL, see COPYING for details", platforms = "Linux", packages = ["palabre","modules"], scripts = ["scripts/palabre","setup.py"], data_files = [('',['Palabre.py']), ("/etc", ["etc/palabre.conf"] ), ("doc",["doc/README.txt"]), ("./",["AUTHORS","COPYING","MANIFEST","MANIFEST.in","PKG-INFO"]), ("/usr/local/share/doc/palabre", ["doc/README.txt"]) ] )
opixido/palabre
setup.py
Python
gpl-2.0
879
import sys #Se le pasa la flag deseada, y devuelve lo que hay que escribir en el binario. CUIDADO CON LAS BACKSLASHES; hay que escaparlas if len(sys.argv) != 2: print "Syntax: python2 flag.py <FLAG>" sys.exit(0) flag = sys.argv[1] i = 0 j = len(flag)-1 l = j flag2 = "" while (i<l+1): if i <= l/2: c = 7 else: c = 10 flag2 += chr(ord(flag[j])+c) i = i+1 j = j-1 print flag2
0-wHiTeHand-0/CTFs
made_faqin2k18/heap/flag.py
Python
gpl-2.0
413
import subprocess import sys import numpy as np import fluidfoam import matplotlib.pyplot as plt plt.ion() ############### Plot properties ##################### import matplotlib.ticker as mticker from matplotlib.ticker import StrMethodFormatter, NullFormatter from matplotlib import rc #rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) rc('text', usetex=True) label_size = 20 legend_size = 12 fontsize=25 linewidth=2 plt.rcParams['xtick.labelsize'] = label_size plt.rcParams['ytick.labelsize'] = label_size plt.rcParams['legend.fontsize'] = legend_size plt.rcParams['lines.linewidth'] = linewidth plt.rcParams['axes.labelsize'] = fontsize #################################################### ###################### # Load DEM data ###################### zDEM, phiDEM, vxPDEM, vxFDEM, TDEM = np.loadtxt('DATA/BedloadTurbDEM.txt', unpack=True) ###################### #Read SedFoam results ###################### sol = '../1DBedLoadTurb/' try: proc = subprocess.Popen( ["foamListTimes", "-latestTime", "-case", sol], stdout=subprocess.PIPE,) except: print("foamListTimes : command not found") print("Do you have load OpenFoam environement?") sys.exit(0) output = proc.stdout.read() #to obtain the output of function foamListTimes from the subprocess timeStep = output.decode().rstrip().split('\n')[0] #Some management on the output to obtain a number #Read the data X, Y, Z = fluidfoam.readmesh(sol) z = Y phi = fluidfoam.readscalar(sol, timeStep, 'alpha_a') vxPart = fluidfoam.readvector(sol, timeStep, 'Ua')[0] vxFluid = fluidfoam.readvector(sol, timeStep, 'Ub')[0] T = fluidfoam.readscalar(sol, timeStep, 'Theta') ###################### #Plot results ###################### d = 0.006 #6mm diameter particles plt.figure(figsize=[10,5]) plt.subplot(141) plt.plot(phiDEM, zDEM/d, 'k--', label=r'DEM') plt.plot(phi, z/d, label=r'SedFoam') plt.xlabel(r'$\phi$', fontsize=25) plt.ylabel(r'$\frac{z}{d}$', fontsize=30, rotation=True, horizontalalignment='right') plt.grid() plt.ylim([-1.525, 32.025]) plt.legend() plt.subplot(142) I = np.where(phiDEM>0.001)[0] plt.plot(vxPDEM[I], zDEM[I]/d, 'r--') I = np.where(phi>0.001)[0] plt.plot(vxPart[I], z[I]/d, 'r', label=r'$v_x^p$') plt.plot(vxFDEM, zDEM/d, 'b--') plt.plot(vxFluid, z/d, 'b', label=r'$u_x^f$') plt.xlabel(r'$v_x^p$, $u_x^f$', fontsize=25) plt.ylim([-1.525, 32.025]) plt.grid() plt.legend() ax = plt.gca() ax.set_yticklabels([]) plt.legend() plt.subplot(143) plt.plot(phiDEM*vxPDEM, zDEM/d, 'k--', label=r'DEM') plt.plot(phi*vxPart, z/d, label=r'SedFoam') plt.xlabel(r'$q = \phi v_x^p$', fontsize=25) plt.grid() plt.ylim([-1.525, 32.025]) ax = plt.gca() ax.set_yticklabels([]) plt.subplot(144) I = np.where(phiDEM>0.001)[0] plt.plot(TDEM[I], zDEM[I]/d, 'k--', label=r'DEM') I = np.where(phi>0.001)[0] plt.plot(T[I], z[I]/d, label=r'SedFoam') plt.xlabel(r'$T$', fontsize=25) plt.grid() plt.ylim([-1.525, 32.025]) ax = plt.gca() ax.set_yticklabels([]) plt.savefig('Figures/res_TutoBedloadTurb.png', bbox_inches='tight') plt.show(block=True)
SedFoam/sedfoam
tutorials/Py/plot_tuto1DBedLoadTurb.py
Python
gpl-2.0
3,062
# Copyright (C) 2002-2006 Stephen Kennedy <[email protected]> # Copyright (C) 2009-2013 Kai Willadsen <[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, see <http://www.gnu.org/licenses/>. import math from gi.repository import Gtk from meld.misc import get_common_theme from meld.settings import meldsettings # Rounded rectangle corner radius for culled changes display RADIUS = 3 class LinkMap(Gtk.DrawingArea): __gtype_name__ = "LinkMap" def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed) def associate(self, filediff, left_view, right_view): self.filediff = filediff self.views = [left_view, right_view] if self.get_direction() == Gtk.TextDirection.RTL: self.views.reverse() self.view_indices = [filediff.textview.index(t) for t in self.views] self.on_setting_changed(meldsettings, 'style-scheme') def on_setting_changed(self, settings, key): if key == 'style-scheme': self.fill_colors, self.line_colors = get_common_theme() def do_draw(self, context): if not self.filediff: return context.set_line_width(1.0) allocation = self.get_allocation() pix_start = [t.get_visible_rect().y for t in self.views] y_offset = [ t.translate_coordinates(self, 0, 0)[1] + 1 for t in self.views] clip_y = min(y_offset) - 1 clip_height = max(t.get_visible_rect().height for t in self.views) + 2 context.rectangle(0, clip_y, allocation.width, clip_height) context.clip() height = allocation.height visible = [self.views[0].get_line_num_for_y(pix_start[0]), self.views[0].get_line_num_for_y(pix_start[0] + height), self.views[1].get_line_num_for_y(pix_start[1]), self.views[1].get_line_num_for_y(pix_start[1] + height)] wtotal = allocation.width # For bezier control points x_steps = [-0.5, (1. / 3) * wtotal, (2. / 3) * wtotal, wtotal + 0.5] q_rad = math.pi / 2 left, right = self.view_indices view_offset_line = lambda v, l: (self.views[v].get_y_for_line_num(l) - pix_start[v] + y_offset[v]) for c in self.filediff.linediffer.pair_changes(left, right, visible): # f and t are short for "from" and "to" f0, f1 = [view_offset_line(0, l) for l in c[1:3]] t0, t1 = [view_offset_line(1, l) for l in c[3:5]] # We want the last pixel of the previous line f1 = f1 if f1 == f0 else f1 - 1 t1 = t1 if t1 == t0 else t1 - 1 # If either endpoint is completely off-screen, we cull for clarity if (t0 < 0 and t1 < 0) or (t0 > height and t1 > height): if f0 == f1: continue context.arc(x_steps[0], f0 - 0.5 + RADIUS, RADIUS, -q_rad, 0) context.arc(x_steps[0], f1 - 0.5 - RADIUS, RADIUS, 0, q_rad) context.close_path() elif (f0 < 0 and f1 < 0) or (f0 > height and f1 > height): if t0 == t1: continue context.arc_negative(x_steps[3], t0 - 0.5 + RADIUS, RADIUS, -q_rad, q_rad * 2) context.arc_negative(x_steps[3], t1 - 0.5 - RADIUS, RADIUS, q_rad * 2, q_rad) context.close_path() else: context.move_to(x_steps[0], f0 - 0.5) context.curve_to(x_steps[1], f0 - 0.5, x_steps[2], t0 - 0.5, x_steps[3], t0 - 0.5) context.line_to(x_steps[3], t1 - 0.5) context.curve_to(x_steps[2], t1 - 0.5, x_steps[1], f1 - 0.5, x_steps[0], f1 - 0.5) context.close_path() context.set_source_rgba(*self.fill_colors[c[0]]) context.fill_preserve() chunk_idx = self.filediff.linediffer.locate_chunk(left, c[1])[0] if chunk_idx == self.filediff.cursor.chunk: highlight = self.fill_colors['current-chunk-highlight'] context.set_source_rgba(*highlight) context.fill_preserve() context.set_source_rgba(*self.line_colors[c[0]]) context.stroke() def do_scroll_event(self, event): self.filediff.next_diff(event.direction) class ScrollLinkMap(Gtk.DrawingArea): __gtype_name__ = "ScrollLinkMap" def __init__(self): self.melddoc = None def associate(self, melddoc): self.melddoc = melddoc def do_scroll_event(self, event): if not self.melddoc: return self.melddoc.next_diff(event.direction)
Spitfire1900/meld
meld/linkmap.py
Python
gpl-2.0
5,512
import csv, sqlite3 con = sqlite3.connect("toto.db") # change to 'sqlite:///your_filename.db' cur = con.cursor() cur.execute("CREATE TABLE t (col1, col2);") # use your column names here with open('data.csv','r') as fin: # `with` statement available in 2.5+ # csv.DictReader uses first line in file for column headings by default dr = csv.DictReader(fin) # comma is default delimiter to_db = [(i['col1'], i['col2']) for i in dr] cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db) con.commit() con.close()
fccagou/tools
python/sql/csv-to-sql.py
Python
gpl-2.0
537
# select the data using the like API # use the python 3.5 as default import sqlite3 def select_data(db_name, table_name, condition): "find all the data with the same kind" with sqlite3.connect(db_name) as db: cursor = db.cursor() cursor.execute("SELECT title, releaseYear FROM {0} WHERE title LIKE ?".format(table_name), (condition,)) result = cursor.fetchall() return result def select_from_multi(db_name, table_name, conditon): "select from multiple tables" with sqlite3.connect(db_name) as db: cursor = db.cursor() cursor.execute("SELECT title, genreName FROM {0}, {1} WHERE title=? AND genreName IN (?,?)".format(table_name[0], table_name[1]), (condition[0], condition[1], condition[2])) result = cursor.fetchall() return result if __name__ == '__main__': db_name = "movie.db" table_name = "film" condition = "Die Hard%" result = select_data(db_name, table_name, condition) print(result) table_name = ("film", "genre") condition = ("Die Hard", "Action", "Thriller") result = select_from_multi(db_name, table_name, condition) print(result)
smileboywtu/SQLite3
coffee-shop/demon/select-like.py
Python
gpl-2.0
1,166
# This function runs a .bat file that job handles multiple GridLAB-D files import subprocess #C:\Projects\GridLAB-D_Builds\trunk\test\input\batch test\13_node_fault2.glm def create_batch_file(glm_folder,batch_name): batch_file = open('{:s}'.format(batch_name),'w') batch_file.write('gridlabd.exe -T 0 --job\n') #batch_file.write('pause\n') batch_file.close() return None def run_batch_file(glm_folder,batch_name): p = subprocess.Popen('{:s}'.format(batch_name),cwd=glm_folder) code = p.wait() #print(code) return None def main(): #tests here glm_folder = 'C:\\Projects\\GridLAB-D_Builds\\trunk\\test\\input\\batch_test' batch_name = 'C:\\Projects\\GridLAB-D_Builds\\trunk\\test\\input\\batch_test\\calibration_batch_file.bat' create_batch_file(glm_folder,batch_name) run_batch_file(batch_name) if __name__ == '__main__': main()
NREL/glmgen
glmgen/run_gridlabd_batch_file.py
Python
gpl-2.0
850
# -*- coding: utf-8 -*- { ' (late)': ' (verspätet)', '!=': '!=', '!langcode!': 'de', '!langname!': 'Deutsch (DE)', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '""Update" ist ein optionaler Ausdruck wie "Feld1 = \'newvalue". JOIN Ergebnisse können nicht aktualisiert oder gelöscht werden', '%(nrows)s records found': '%(nrows)s Einträge gefunden', '%d.%m.%Y': '%d.%m.%Y', '%s %%(shop)': '%s %%(shop)', '%s %%(shop[0])': '%s %%(shop[0])', '%s %%{quark[0]}': '%s %%{quark[0]}', '%s %%{row} deleted': '%s %%{row} gelöscht', '%s %%{row} updated': '%s %%{row} aktualisiert', '%s %%{shop[0]}': '%s %%{shop[0]}', '%s %%{shop}': '%s %%{shop}', '%s selected': '%s ausgewählt', '%Y-%m-%d': '%d.%m.%Y', '%Y-%m-%d %H:%M:%S': '%d.%m.%Y %H:%M:%S', '+ And': '+ Und', '+ Or': '+ Oder', '<': '<', '<=': '<=', '=': '=', '>': '>', '>=': '>=', '?': '?', '@markmin\x01**Hello World**': '**Hallo Welt**', '@markmin\x01An error occured, please [[reload %s]] the page': 'Ein Fehler ist aufgetreten, bitte [[laden %s]] Sie die Seite neu', 'A file ({filename}) was uploaded for task {task} by {firstname} {lastname} with the hash (SHA256) {hash}.': 'Eine Datei ({filename}) für die Aufgabe {task} mit dem Hash (SHA256) {hash} wurde von {firstname} {lastname} hochgeladen.', 'About': 'Über', 'Access Control': 'Zugangskontrolle', 'Add Record': 'Eintrag hinzufügen', 'Add record to database': 'Eintrag in Datenbank hinzufügen', 'Add this to the search as an AND term': 'Add this to the search as an AND term', 'Add this to the search as an OR term': 'Add this to the search as an OR term', 'admin': 'admin', 'Administrative Interface': 'Administrationsoberfläche', 'Administrator view: Task of all users are shown!': 'Administrator-Ansicht: Es werden die Aufgaben aller Benutzer angezeigt!', 'After the file was uploaded, the chosen teacher will be informed by email. The uploader also gets an email with the hash (SHA256) of the uploaded file.': 'Nach Betätigung des Upload-Buttons wird die Datei übermittelt und die ausgewählte Lehrkraft per Mail darüber informiert. Der Uploader bekommt ebenfalls eine Benachrichtigungsmail mit der Hash (SHA256) der hochgeladenen Datei.', 'Ajax Recipes': 'Ajax Rezepte', 'appadmin is disabled because insecure channel': 'Appadmin ist deaktiviert, wegen der Benutzung eines unsicheren Kanals', 'Apply changes': 'Änderungen übernehmen', 'Are you sure you want to delete this object?': 'Sind Sie sich sicher, dass Sie dieses Objekt löschen wollen?', 'AttendingClass': 'Klasse', 'Available Databases and Tables': 'Verfügbare Datenbanken und Tabellen', 'Back': 'Zurück', 'Buy this book': 'Dieses Buch kaufen', "Buy web2py's book": "Buy web2py's book", 'cache': 'cache', 'Cache': 'Cache', 'Cache Cleared': 'Cache geleert', 'Cache Keys': 'Cache Schlüssel', 'Cannot be empty': 'Darf nicht leer sein', 'Change Password': 'Passwort ändern', 'Change password': 'Passwort ändern', 'Check to delete': 'Auswählen um zu löschen', 'Choose a file to be uploaded!': 'Wählen Sie eine Datei aus, die hochgeladen werden soll!', 'Choose a task:': 'Wählen Sie eine Aufgabe aus:', 'choose one': 'Wählen Sie einen aus', 'Class': 'Klasse', 'Clear': 'Löschen', 'Clear CACHE?': 'CACHE löschen?', 'Clear DISK': 'DISK löschen', 'Clear RAM': 'RAM löschen', 'Click on the link %(link)s to reset your password': 'Click on the link %(link)s to reset your password', 'Client IP': 'Client IP', 'Close': 'Schließen', 'Collect uploaded files': 'Hochgeladene Dateien einsammeln', 'Comma-separated export including columns not shown; fields from other tables are exported as raw values for faster export': 'Comma-separated export including columns not shown; fields from other tables are exported as raw values for faster export', 'Comma-separated export of visible columns. Fields from other tables are exported as they appear on-screen but this may be slow for many rows': 'Comma-separated export of visible columns. Fields from other tables are exported as they appear on-screen but this may be slow for many rows', 'Community': 'Community', 'Components and Plugins': 'Komponenten und Plugins', 'Config.ini': 'Config.ini', 'Confirm Password': 'Passwort bestätigen', 'contains': 'contains', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Created By': 'Erstellt von', 'Created On': 'Erstellt am', 'CSV': 'CSV', 'CSV (hidden cols)': 'CSV (versteckte Spalten)', 'Current request': 'Derzeitiger Request', 'Current response': 'Derzeitige Response', 'Current session': 'Derzeitige Session', 'customize me!': 'Pass mich an!', 'data uploaded': 'Datei hochgeladen', 'Database': 'Datenbank', 'Database %s select': 'Datenbank %s ausgewählt', 'Database Administration (appadmin)': 'Datenbankadministration (appadmin)', 'db': 'db', 'DB Model': 'Muster-DB', 'Delete': 'Löschen', 'Delete:': 'Löschen:', 'Demo': 'Demo', 'Deployment Recipes': 'Entwicklungsrezepte', 'Description': 'Beschreibung', 'design': 'Design', 'Design': 'Design', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk gelöscht', 'Documentation': 'Dokumentation', "Don't know what to do?": 'Wissen Sie nicht weiter?', 'done!': 'Fertig!', 'Download': 'Download', 'Download all uploaded files...': 'Alle hochgeladenen Dateien herunterladen...', 'Download files': 'Dateien herunterladen', 'Duedate': 'Fälligkeit', 'DueDate': 'Fälligkeit', 'E-mail': 'Email', 'Edit': 'Bearbeiten', 'Edit current record': 'Diesen Eintrag editieren', 'Email and SMS': 'Email und SMS', 'Email sent': 'Email wurde versandt', 'Enter a valid email address': 'Geben Sie eine gültige Email-Adresse ein', 'Enter a value': 'Geben Sie einen Wert ein', 'Enter an integer between %(min)g and %(max)g': 'Eine Zahl zwischen %(min)g und %(max)g eingeben', 'enter an integer between %(min)g and %(max)g': 'eine Zahl zwischen %(min)g und %(max)g eingeben', 'enter date and time as %(format)s': 'ein Datum und eine Uhrzeit als %(format)s eingeben', 'Enter date as %(format)s': 'Geben Sie ein Datum mit dem Format %(format)s an', 'Enter from %(min)g to %(max)g characters': 'Geben Sie zwischen %(min)g und %(max)g Zeichen ein', 'Errors': 'Fehlermeldungen', 'Errors in form, please check it out.': 'Bitte überprüfen Sie das Formular, denn es enthält Fehler.', 'export as csv file': 'als csv Datei exportieren', 'Export:': 'Export:', 'FAQ': 'FAQ', 'file': 'file', 'file ## download': 'Datei ## herunterladen', 'File size is to large!': 'Datei ist zu groß!', 'File successfully uploaded': 'Datei erfolgreich hochgeladen', 'File successfully uploaded!': 'Datei erfolgreich hochgeladen!', 'File to be uploaded': 'Hochzuladene Datei', 'File uploaded for task {task}': 'Datei hochgeladen für Aufgabe {task}', 'First name': 'Vorname', 'First Name': 'Vorname', 'FirstName': 'FirstName', 'Forgot username?': 'Benutzernamen vergessen?', 'Forms and Validators': 'Forms und Validators', 'Free Applications': 'Kostenlose Anwendungen', 'Given task and teacher does not match!': 'Angegebene Aufgabe und Lehrkraft passen nicht zusammen!', 'Graph Model': 'Muster-Graph', 'Group %(group_id)s created': 'Gruppe %(group_id)s erstellt', 'Group ID': 'Gruppen ID', 'Group uniquely assigned to user %(id)s': 'Gruppe eindeutigem Benutzer %(id)s zugewiesen', 'Groups': 'Gruppen', 'Hash': 'Hash', 'Hello World': 'Hallo Welt', 'Hello World ## Kommentar': 'Hallo Welt ', 'Hello World## Kommentar': 'Hallo Welt', 'Help': 'Hilfe', 'Helping web2py': 'web2py helfen', 'Home': 'Startseite', 'Hosted on': 'Hosted on', 'How did you get here?': 'Wie sind Sie hier her gelangt?', 'HTML': 'HTML', 'HTML export of visible columns': 'Sichtbare Spalten nach HTML exportieren', 'Id': 'Id', 'import': 'Importieren', 'Import/Export': 'Importieren/Exportieren', 'in': 'in', 'Insufficient privileges': 'Keine ausreichenden Rechte', 'Internal State': 'Innerer Zustand', 'Introduction': 'Einführung', 'Invalid email': 'Ungültige Email', 'Invalid login': 'Ungültiger Login', 'Invalid Query': 'Ungültige Query', 'invalid request': 'Ungültiger Request', 'Is Active': 'Ist aktiv', 'JSON': 'JSON', 'JSON export of visible columns': 'Sichtbare Spalten nach JSON exportieren', 'Key': 'Schlüssel', 'Klasse': 'Klasse', 'Last name': 'Nachname', 'Last Name': 'Nachname', 'LastName': 'Nachname', 'Layout': 'Layout', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'Live Chat': 'Live Chat', 'Log In': 'Einloggen', 'Log Out': 'Ausloggen', 'Logged in': 'Eingeloggt', 'Logged out': 'Ausgeloggt', 'Login': 'Einloggen', 'Login to UpLoad': 'In UpLoad einloggen', 'Logout': 'Ausloggen', 'Lost Password': 'Passwort vergessen', 'Lost password?': 'Passwort vergessen?', 'Mail': 'Mail', 'Manage %(action)s': '%(action)s verwalten', 'Manage Access Control': 'Zugangskontrolle verwalten', 'Manage Cache': 'Cache verwalten', 'Manage tasks': 'Aufgaben verwalten', 'Manage teachers': 'Lehrkräfte verwalten', 'Memberships': 'Mitgliedschaften', 'Menu Model': 'Menü-Muster', 'Modified By': 'Verändert von', 'Modified On': 'Verändert am', 'My Sites': 'Meine Seiten', 'Nachname': 'Nachname', 'Name': 'Name', 'New password': 'Neues Passwort', 'New Record': 'Neuer Eintrag', 'new record inserted': 'neuer Eintrag hinzugefügt', 'New Search': 'Neue Suche', 'next %s rows': 'nächste %s Reihen', 'No databases in this application': 'Keine Datenbank in dieser Anwendung', 'No hash for upload given.': 'Kein Upload mit angegebener Hash gefunden', 'No records found': 'Keine Einträge gefunden', 'No task number given.': 'Es wurde keine Aufgabe gewählt.', 'Not Authorized': 'Zugriff verboten', 'not authorized': 'Zugriff verboten', 'not in': 'not in', 'Object or table name': 'Objekt- oder Tabellenname', 'Old password': 'Altes Passwort', 'Online book': 'Online book', 'Online examples': 'Online Beispiele', 'OpenForSubmission': 'Upload freigeschaltet', 'or import from csv file': 'oder von csv Datei importieren', 'Origin': 'Ursprung', 'Other Plugins': 'Andere Plugins', 'Other Recipes': 'Andere Rezepte', 'Overview': 'Überblick', 'Password': 'Passwort', 'Password changed': 'Passwort wurde geändert', "Password fields don't match": 'Passwortfelder sind nicht gleich', 'Password reset': 'Passwort wurde zurückgesetzt', 'Permission': 'Zugriffsrecht', 'Permissions': 'Zugriffsrechte', 'please input your password again': 'Bitte geben Sie ihr Passwort erneut ein', 'Plugins': 'Plugins', 'Powered by': 'Unterstützt von', 'Preface': 'Allgemeines', 'previous %s rows': 'vorherige %s Reihen', 'Profile': 'Profil', 'Profile updated': 'Profil aktualisiert', 'pygraphviz library not found': 'pygraphviz Bibliothek wurde nicht gefunden', 'Python': 'Python', 'Query:': 'Query:', 'Quick Examples': 'Kurze Beispiele', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Cleared', 'Recipes': 'Rezepte', 'Record': 'Eintrag', 'record does not exist': 'Eintrag existiert nicht', 'Record ID': 'ID des Eintrags', 'Record id': 'id des Eintrags', 'Register': 'Register', 'Registration identifier': 'Registrierungsbezeichnung', 'Registration key': 'Registierungsschlüssel', 'Registration successful': 'Registrierung erfolgreich', 'Remember me (for 30 days)': 'Eingeloggt bleiben (30 Tage lang)', 'Request reset password': 'Request reset password', 'Request Reset Password': 'Request Reset Password', 'Reset Password': 'Reset Password', 'Reset Password key': 'Passwortschlüssel zurücksetzen', 'Role': 'Rolle', 'Roles': 'Rollen', 'Rows in Table': 'Tabellenreihen', 'Rows selected': 'Reihen ausgewählt', 'Save model as...': 'Speichere Vorlage als...', 'Search': 'Suche', 'Semantic': 'Semantik', 'SendMessages': 'Sende Nachrichten', 'Services': 'Dienste', 'Sign Up': 'Sign Up', 'Size of cache:': 'Cachegröße:', 'Spreadsheet-optimised export of tab-separated content including hidden columns. May be slow': 'Spreadsheet-optimised export of tab-separated content including hidden columns. May be slow', 'Spreadsheet-optimised export of tab-separated content, visible columns only. May be slow.': 'Spreadsheet-optimised export of tab-separated content, visible columns only. May be slow.', 'Start building a new search': 'Start building a new search', 'StartDate': 'Beginn', 'starts with': 'starts with', 'state': 'Status', 'Statistics': 'Statistik', 'Stylesheet': 'Stylesheet', 'Submission for given task no yet allowed!': 'Upload für die gegebene Aufgabe ist noch nicht erlaubt!', 'submit': 'Abschicken', 'Submit': 'Abschicken', 'SubmittedOnTime': 'Pünklich abgegeben', 'Submittedontime': 'Pünklich abgegeben', 'Success!': 'Erfolg!', 'Support': 'Support', 'Table': 'Tabelle', 'Task': 'Aufgabe', 'Task is currently not open for submission.': 'Für diese Aufgabe sind im Moment keine Uploads erlaubt.', 'Teacher': 'Lehrkraft', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'Die "query" ist eine Bedingung wie "db.tabelle1.feld1==\'wert\'". So etwas wie "db.tabelle1.feld1==db.tabelle2.feld2" resultiert in einem SQL JOIN.', 'The Core': 'Der Core', 'The output of the file is a dictionary that was rendered by the view %s': 'Die Ausgabe der Datei ist ein "dictionary", welches vom "view" %s gerendert wurde', 'The Views': 'Die Views', 'This App': 'Diese App', 'This email already has an account': 'Zu dieser Email-Adresse gibt es bereits einen Benutzer.', 'This exact file has been uploaded already by a user.': 'Exakt diese Datei wurde bereits von einem Benutzer hochgeladen.', 'This page only works with JavaScript.': 'Diese Seite funktioniert nur mit JavaScript.', 'Time in Cache (h:m:s)': 'Zeit im Cache (h:m:s)', 'Timestamp': 'Zeitstempel', 'Token': 'Token', 'Traceback': 'Traceback', 'TSV (Spreadsheets)': 'TSV (Tabellenkalkulation)', 'TSV (Spreadsheets, hidden cols)': 'TSV (Tabellenkalkulation, versteckte Spalten)', 'Twitter': 'Twitter', 'unable to parse csv file': 'csv Datei konnte nicht geparst werden', 'Update:': 'Update:', 'Upload file': 'Datei hochladen', 'UpLoad@BBS is used to upload presentations, project documentation and tests. To upload a file you have to fill out the form with information about the uploader, the teacher and the task for which you want to upload a file. Then you can choose a file to be uploaded. The maximum file size is 5MiB.': 'UpLoad@BBS dient dem einfachen Abgeben von Projektarbeiten, Präsentationen und Klassenarbeiten. Um eine Datei hochzuladen, müssen zunächst Informationen zum Absender, der Lehrkraft und der Aufgabe angegeben werden. Anschließend ist die abzugebende Datei auszuwählen. Die maximal erlaubte Dateigröße beträgt 5MiB.', 'UploadedFile': 'Hochgeladene Datei', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Benutze (...)&(...) für AND, (...)|(...) für OR, und ~(...) für NOT um komplexere Queries zu erstellen.', 'User': 'Benutzer', 'User %(id)s Logged-in': 'Benutzer %(id)s hat sich eingeloggt', 'User %(id)s Logged-out': 'Benutzer %(id)s hat sich ausgeloggt', 'User %(id)s Registered': 'Benutzer %(id)s hat sich registriert', 'User ID': 'Benutzer ID', 'Users': 'Benutzer', 'value already in database or empty': 'Wert ist bereits in der Datenbank oder leer', 'Value not in database': 'Ausgewählter Wert nicht in Datenbank enthalten', 'Verify Password': 'Passwort überprüfen', 'Videos': 'Videos', 'View': 'Ansicht', 'View uploaded file': 'Hochgeladene Datei ansehen', 'View uploaded files': 'Hochgeladene Dateien ansehen', 'View uploads': 'Hochgeladene Datei ansehen', 'Welcome': 'Willkommen', 'Welcome to web2py!': 'Willkommen bei web2py!', 'Which called the function %s located in the file %s': 'Welche die Funktion %s in der Datei %s aufrief', 'Working...': 'Arbeite...', 'Wrong token for given task.': 'Ungültiger Token für gewählte Aufgabe eingegeben.', 'Wrong token given!': 'Ungültiger Token eingegeben!', 'XML': 'XML', 'XML export of columns shown': 'XML export of columns shown', 'You already created a Task with the same name. Please delete the old task or rename this one.': 'Sie haben bereits eine Aufgabe mit diesem Namen erstellt. Bitte löschen sie die alte Aufgabe oder geben Sie einen anderen Namen an.', 'You already uploaded a file for this task!': 'Sie haben bereits eine Datei für diese Aufgabe hochgeladen!', 'You are successfully running web2py': 'web2py wird erfolgreich ausgeführt', 'You can modify this application and adapt it to your needs': 'Sie können diese Anwendung verändern und Ihren Bedürfnissen anpassen', 'You can only create tasks for yourself.': 'Sie dürfen nur eigene Aufgaben erstellen.', 'You visited the url %s': 'Sie haben die URL %s besucht', 'Your file ({filename}) with the hash (SHA256) {hash} has been successfully uploaded.': 'Ihre Datei ({filename}) mit dem Hash (SHA256) {hash} wurde erfolgreich hochgeladen.', }
wichmann/UpLoad
languages/de.py
Python
gpl-2.0
16,769
#!/usr/bin/python import pygeoip import json from logsparser.lognormalizer import LogNormalizer as LN import gzip import glob import socket import urllib2 IP = 'IP.Of,Your.Server' normalizer = LN('/usr/local/share/logsparser/normalizers') gi = pygeoip.GeoIP('../GeoLiteCity.dat') def complete(text, state): return (glob.glob(text+'*')+[none])[state] def sshcheck(): attacks = {} users = {} try: import readline, rlcompleter readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(complete) except ImportError: print 'No Tab Completion' LOGs = raw_input('Enter the path to the log file: ') for LOG in LOGs.split(' '): if LOG.endswith('.gz'): auth_logs = gzip.GzipFile(LOG, 'r') else: auth_logs = open(LOG, 'r') if len(LOGs) is '1': print "Parsing log file" else: print "Parsing log files" for log in auth_logs: l = {"raw": log } normalizer.normalize(l) if l.get('action') == 'fail' and l.get('program') == 'sshd': u = l['user'] p = l['source_ip'] o1, o2, o3, o4 = [int(i) for i in p.split('.')] if o1 == 192 and o2 == 168 or o1 == 172 and o2 in range(16, 32) or o1 == 10: print "Private IP, %s No geolocation data" %str(p) attacks[p] = attacks.get(p, 0) + 1 getip() dojson(attacks, IP) def getip(): global IP if IP is 0: try: i = urllib2.Request("http://icanhazip.com") p = urllib2.urlopen(i) IP = p.read() except: print "can't seem to grab your IP please set IP variable so We can better map attacks" def dojson(attacks, IP): data = {} for i,(a,p) in enumerate(attacks.iteritems()): datalist = [{ 'ip': a, 'attacks': p, 'local_ip': IP }] data[i] = datalist newdata = data newjson = json.dumps(newdata) print json.loads(newjson) send(newjson) def send(data): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('Ip.Of.Your.Server', 9999)) s.sendall(data) s.close() try: sshcheck() except KeyboardInterrupt: print '\nCtrl+C Exiting...' exit(0)
radman404/Who-s-attacking-me-now--
wamnclient.py
Python
gpl-2.0
2,126
# -*- coding: utf-8 -*- import logging # define here the methods needed to be run at install time def importVarious(context): if context.readDataFile('sc.blueprints.soundcloud_various.txt') is None: return logger = logging.getLogger('sc.blueprints.soundcloud') # add here your custom methods that need to be run when # sc.blueprints.soundcloud is installed
jsbueno/sc.blueprints.soundcloud
sc/blueprints/soundcloud/setuphandlers.py
Python
gpl-2.0
386
#! /usr/bin/env python #Written by Kjetil Matheussen: [email protected] import sys import os import urllib2 import readline executable_path = os.path.split(os.path.abspath(os.path.realpath(sys.argv[0])))[0] # TODO: Use bin/packages/s7/s7webserver instead, and delete the local s7webserver directory. sys.path += [os.path.join(executable_path,os.path.pardir,"s7webserver")] import s7webserver_repl portnum = "5080" if len(sys.argv)>1: portnum = sys.argv[1] s7webserver_repl.start("radium>", "http://localhost:"+portnum)
kmatheussen/radium
bin/scheme/repl.py
Python
gpl-2.0
543
# encoding: utf-8 from yast import import_module import_module('UI') from yast import * class Heading2Client: def main(self): UI.OpenDialog( VBox( Heading("This Is a Heading."), Label("This is a Label."), PushButton("&OK") ) ) UI.UserInput() UI.CloseDialog() Heading2Client().main()
yast/yast-python-bindings
examples/Heading2.py
Python
gpl-2.0
361
############################################################################### # # # Copyright 2019. Triad National Security, LLC. All rights reserved. # # This program was produced under U.S. Government contract 89233218CNA000001 # # for Los Alamos National Laboratory (LANL), which is operated by Triad # # National Security, LLC for the U.S. Department of Energy/National Nuclear # # Security Administration. # # # # All rights in the program are reserved by Triad National Security, LLC, and # # the U.S. Department of Energy/National Nuclear Security Administration. The # # Government is granted for itself and others acting on its behalf a # # nonexclusive, paid-up, irrevocable worldwide license in this material to # # reproduce, prepare derivative works, distribute copies to the public, # # perform publicly and display publicly, and to permit others to do so. # # # ############################################################################### ''' Created on 2015/07/01 @author: Eric Ball @change: 2015/12/07 eball Added information about REMOVEX CI to help text @change: 2016/07/06 eball Separated fix into discrete methods @change: 2017/06/02 bgonz12 - Change a conditional in reportUbuntu to search for "manual" using regex instead of direct comparison @change 2017/08/28 rsn Fixing to use new help text methods @change: 2017/10/23 rsn - change to new service helper interface @change: 2017/11/14 bgonz12 - Fix removeX dependency issue for deb systems ''' import os import re import traceback from KVEditorStonix import KVEditorStonix from logdispatcher import LogPriority from pkghelper import Pkghelper from rule import Rule from CommandHelper import CommandHelper from ServiceHelper import ServiceHelper from stonixutilityfunctions import iterate, readFile, writeFile, createFile from stonixutilityfunctions import resetsecon class DisableGUILogon(Rule): def __init__(self, config, environ, logger, statechglogger): Rule.__init__(self, config, environ, logger, statechglogger) self.logger = logger self.rulenumber = 105 self.rulename = "DisableGUILogon" self.formatDetailedResults("initialize") self.mandatory = False self.applicable = {'type': 'white', 'family': ['linux']} # Configuration item instantiation datatype = "bool" key = "DISABLEX" instructions = "To enable this item, set the value of DISABLEX " + \ "to True. When enabled, this rule will disable the automatic " + \ "GUI login, and the system will instead boot to the console " + \ "(runlevel 3). This will not remove any GUI components, and the " + \ "GUI can still be started using the \"startx\" command." default = False self.ci1 = self.initCi(datatype, key, instructions, default) datatype = "bool" key = "LOCKDOWNX" instructions = "To enable this item, set the value of LOCKDOWNX " + \ "to True. When enabled, this item will help secure X Windows by " + \ "disabling the X Font Server (xfs) service and disabling X " + \ "Window System Listening. This item should be enabled if X " + \ "Windows is disabled but will be occasionally started via " + \ "startx, unless there is a mission-critical need for xfs or " + \ "a remote display." default = False self.ci2 = self.initCi(datatype, key, instructions, default) datatype = "bool" key = "REMOVEX" instructions = "To enable this item, set the value of REMOVEX " + \ "to True. When enabled, this item will COMPLETELY remove X " + \ "Windows from the system, and on most platforms will disable " + \ "any currently running display manager. It is therefore " + \ "recommended that this rule be run from a console session " + \ "rather than from the GUI.\nREMOVEX cannot be undone." default = False self.ci3 = self.initCi(datatype, key, instructions, default) self.guidance = ["NSA 3.6.1.1", "NSA 3.6.1.2", "NSA 3.6.1.3", "CCE 4462-8", "CCE 4422-2", "CCE 4448-7", "CCE 4074-1"] self.iditerator = 0 self.ph = Pkghelper(self.logger, self.environ) self.ch = CommandHelper(self.logger) self.sh = ServiceHelper(self.environ, self.logger) self.myos = self.environ.getostype().lower() self.sethelptext() def report(self): '''@author: Eric Ball :param self: essential if you override this definition :returns: bool - True if system is compliant, False if it isn't ''' try: compliant = True results = "" if os.path.exists("/bin/systemctl"): self.initver = "systemd" compliant, results = self.reportSystemd() elif re.search("debian", self.myos): self.initver = "debian" compliant, results = self.reportDebian() elif re.search("ubuntu", self.myos): self.initver = "ubuntu" compliant, results = self.reportUbuntu() else: self.initver = "inittab" compliant, results = self.reportInittab() # NSA guidance specifies disabling of X Font Server (xfs), # however, this guidance seems to be obsolete as of RHEL 6, # and does not apply to the Debian family. if self.sh.auditService("xfs", _="_"): compliant = False results += "xfs is currently enabled\n" xremoved = True self.xservSecure = True if re.search("debian|ubuntu", self.myos): if self.ph.check("xserver-xorg-core"): compliant = False xremoved = False results += "Core X11 components are present\n" elif re.search("opensuse", self.myos): if self.ph.check("xorg-x11-server"): compliant = False xremoved = False results += "Core X11 components are present\n" else: if self.ph.check("xorg-x11-server-Xorg"): compliant = False xremoved = False results += "Core X11 components are present\n" # Removing X will take xserverrc with it. If X is not present, we # do not need to check for xserverrc if not xremoved: self.serverrc = "/etc/X11/xinit/xserverrc" self.xservSecure = False if os.path.exists(self.serverrc): serverrcText = readFile(self.serverrc, self.logger) if re.search("opensuse", self.myos): for line in serverrcText: reSearch = r'exec (/usr/bin/)?X \$dspnum.*\$args' if re.search(reSearch, line): self.xservSecure = True break else: for line in serverrcText: reSearch = r'^exec (/usr/bin/)?X (:0 )?-nolisten tcp ("$@"|.?\$@)' if re.search(reSearch, line): self.xservSecure = True break if not self.xservSecure: compliant = False results += self.serverrc + " does not contain proper " \ + "settings to disable X Window System " + \ "Listening/remote display\n" else: compliant = False results += self.serverrc + " does not exist; X Window " + \ "System Listening/remote display has not " + \ "been disabled\n" self.detailedresults = results self.compliant = compliant except (KeyboardInterrupt, SystemExit): raise except Exception: self.rulesuccess = False self.detailedresults = "\n" + traceback.format_exc() self.logger.log(LogPriority.ERROR, self.detailedresults) self.formatDetailedResults("report", self.compliant, self.detailedresults) self.logger.log(LogPriority.INFO, self.detailedresults) return self.compliant def reportInittab(self): compliant = False results = "" inittab = "/etc/inittab" if os.path.exists(inittab): initData = readFile(inittab, self.logger) for line in initData: if line.strip() == "id:3:initdefault:": compliant = True break else: self.logger.log(LogPriority.ERROR, inittab + " not found, init " + "system unknown") if not compliant: results = "inittab not set to runlevel 3; GUI logon is enabled\n" return compliant, results def reportSystemd(self): compliant = True results = "" cmd = ["/bin/systemctl", "get-default"] self.ch.executeCommand(cmd) defaultTarget = self.ch.getOutputString() if not re.search("multi-user.target", defaultTarget): compliant = False results = "systemd default target is not multi-user.target; " + \ "GUI logon is enabled\n" return compliant, results def reportDebian(self): compliant = True results = "" dmlist = ["gdm", "gdm3", "lightdm", "xdm", "kdm"] for dm in dmlist: if self.sh.auditService(dm, _="_"): compliant = False results = dm + \ " is still in init folders; GUI logon is enabled\n" return compliant, results def reportUbuntu(self): compliant = True results = "" ldmover = "/etc/init/lightdm.override" grub = "/etc/default/grub" if os.path.exists(ldmover): lightdmText = readFile(ldmover, self.logger) if not re.search("manual", lightdmText[0], re.IGNORECASE): compliant = False results += ldmover + ' exists, but does not contain text ' + \ '"manual". GUI logon is still enabled\n' else: compliant = False results += ldmover + " does not exist; GUI logon is enabled\n" if os.path.exists(grub): tmppath = grub + ".tmp" data = {"GRUB_CMDLINE_LINUX_DEFAULT": '"quiet"'} editor = KVEditorStonix(self.statechglogger, self.logger, "conf", grub, tmppath, data, "present", "closedeq") if not editor.report(): compliant = False results += grub + " does not contain the correct values: " + \ str(data) else: compliant = False results += "Cannot find file " + grub if not compliant: results += "/etc/init does not contain proper override file " + \ "for lightdm; GUI logon is enabled\n" return compliant, results def fix(self): '''@author: Eric Ball :param self: essential if you override this definition :returns: bool - True if fix is successful, False if it isn't ''' try: if not self.ci1.getcurrvalue() and not self.ci2.getcurrvalue() \ and not self.ci3.getcurrvalue(): return success = True self.detailedresults = "" # Delete past state change records from previous fix self.iditerator = 0 eventlist = self.statechglogger.findrulechanges(self.rulenumber) for event in eventlist: self.statechglogger.deleteentry(event) # If we are doing DISABLEX or REMOVEX, we want to boot to # non-graphical multi-user mode. if self.ci1.getcurrvalue() or self.ci3.getcurrvalue(): success &= self.fixBootMode() # Since LOCKDOWNX depends on having X installed, and REMOVEX # completely removes X from the system, LOCKDOWNX fix will only be # executed if REMOVEX is not. if self.ci3.getcurrvalue(): success &= self.fixRemoveX() elif self.ci2.getcurrvalue(): success &= self.fixLockdownX() self.rulesuccess = success except (KeyboardInterrupt, SystemExit): # User initiated exit raise except Exception: self.rulesuccess = False self.detailedresults += "\n" + traceback.format_exc() self.logdispatch.log(LogPriority.ERROR, self.detailedresults) self.formatDetailedResults("fix", self.rulesuccess, self.detailedresults) self.logdispatch.log(LogPriority.INFO, self.detailedresults) return self.rulesuccess def fixBootMode(self): success = True if self.initver == "systemd": cmd = ["/bin/systemctl", "set-default", "multi-user.target"] if not self.ch.executeCommand(cmd): success = False self.detailedresults += '"systemctl set-default ' \ + 'multi-user.target" did not succeed\n' else: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) commandstring = "/bin/systemctl set-default " + \ "graphical.target" event = {"eventtype": "commandstring", "command": commandstring} self.statechglogger.recordchgevent(myid, event) elif self.initver == "debian": dmlist = ["gdm", "gdm3", "lightdm", "xdm", "kdm"] for dm in dmlist: cmd = ["update-rc.d", "-f", dm, "disable"] if not self.ch.executeCommand(cmd): self.detailedresults += "Failed to disable desktop " + \ "manager " + dm else: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "servicehelper", "servicename": dm, "startstate": "enabled", "endstate": "disabled"} self.statechglogger.recordchgevent(myid, event) elif self.initver == "ubuntu": ldmover = "/etc/init/lightdm.override" tmpfile = ldmover + ".tmp" created = False if not os.path.exists(ldmover): createFile(ldmover, self.logger) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "creation", "filepath": ldmover} self.statechglogger.recordchgevent(myid, event) created = True writeFile(tmpfile, "manual\n", self.logger) if not created: self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "conf", "filepath": ldmover} self.statechglogger.recordchgevent(myid, event) self.statechglogger.recordfilechange(ldmover, tmpfile, myid) os.rename(tmpfile, ldmover) resetsecon(ldmover) grub = "/etc/default/grub" if not os.path.exists(grub): createFile(grub, self.logger) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "creation", "filepath": grub} self.statechglogger.recordchgevent(myid, event) tmppath = grub + ".tmp" data = {"GRUB_CMDLINE_LINUX_DEFAULT": '"quiet"'} editor = KVEditorStonix(self.statechglogger, self.logger, "conf", grub, tmppath, data, "present", "closedeq") editor.report() if editor.fixables: if editor.fix(): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) editor.setEventID(myid) debug = "kveditor fix ran successfully\n" self.logger.log(LogPriority.DEBUG, debug) if editor.commit(): debug = "kveditor commit ran successfully\n" self.logger.log(LogPriority.DEBUG, debug) else: error = "kveditor commit did not run " + \ "successfully\n" self.logger.log(LogPriority.ERROR, error) success = False else: error = "kveditor fix did not run successfully\n" self.logger.log(LogPriority.ERROR, error) success = False cmd = "update-grub" self.ch.executeCommand(cmd) else: inittab = "/etc/inittab" tmpfile = inittab + ".tmp" if os.path.exists(inittab): initText = open(inittab, "r").read() initre = r"id:\d:initdefault:" if re.search(initre, initText): initText = re.sub(initre, "id:3:initdefault:", initText) writeFile(tmpfile, initText, self.logger) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "conf", "filepath": inittab} self.statechglogger.recordchgevent(myid, event) self.statechglogger.recordfilechange(inittab, tmpfile, myid) os.rename(tmpfile, inittab) resetsecon(inittab) else: initText += "\nid:3:initdefault:\n" writeFile(tmpfile, initText, self.logger) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "conf", "filepath": inittab} self.statechglogger.recordchgevent(myid, event) self.statechglogger.recordfilechange(inittab, tmpfile, myid) os.rename(tmpfile, inittab) resetsecon(inittab) else: self.detailedresults += inittab + " not found, no other " + \ "init system found. If you are using a supported " + \ "Linux OS, please report this as a bug\n" return success def fixRemoveX(self): success = True # Due to automatic removal of dependent packages, the full # removal of X and related packages cannot be undone if re.search("opensuse", self.myos): cmd = ["zypper", "-n", "rm", "-u", "xorg-x11*", "kde*", "xinit*"] self.ch.executeCommand(cmd) elif re.search("debian|ubuntu", self.myos): xpkgs = ["unity.*", "xserver-xorg-video-ati", "xserver-xorg-input-synaptics", "xserver-xorg-input-wacom", "xserver-xorg-core", "xserver-xorg", "lightdm.*", "libx11-data"] for xpkg in xpkgs: self.ph.remove(xpkg) elif re.search("fedora", self.myos): # Fedora does not use the same group packages as other # RHEL-based OSs. Removing this package will remove the X # Windows system, just less efficiently than using a group self.ph.remove("xorg-x11-server-Xorg") self.ph.remove("xorg-x11-xinit*") else: cmd = ["yum", "groups", "mark", "convert"] self.ch.executeCommand(cmd) self.ph.remove("xorg-x11-xinit") self.ph.remove("xorg-x11-server-Xorg") cmd2 = ["yum", "groupremove", "-y", "X Window System"] if not self.ch.executeCommand(cmd2): success = False self.detailedresults += '"yum groupremove -y X Window System" command failed\n' return success def fixLockdownX(self): success = True if self.sh.disableService("xfs", _="_"): self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "servicehelper", "servicename": "xfs", "startstate": "enabled", "endstate": "disabled"} self.statechglogger.recordchgevent(myid, event) else: success = False self.detailedresults += "STONIX was unable to disable the " + \ "xfs service\n" if not self.xservSecure: serverrcString = "exec X :0 -nolisten tcp $@" if not os.path.exists(self.serverrc): createFile(self.serverrc, self.logger) self.iditerator += 1 myid = iterate(self.iditerator, self.rulenumber) event = {"eventtype": "creation", "filepath": self.serverrc} self.statechglogger.recordchgevent(myid, event) writeFile(self.serverrc, serverrcString, self.logger) else: open(self.serverrc, "a").write(serverrcString) return success
CSD-Public/stonix
src/stonix_resources/rules/DisableGUILogon.py
Python
gpl-2.0
22,537
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'FormPlugin' db.create_table(u'cmsplugin_formplugin', ( (u'cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)), ('form_class', self.gf('django.db.models.fields.CharField')(max_length=200)), ('success_url', self.gf('django.db.models.fields.URLField')(max_length=200, null=True)), ('post_to_url', self.gf('django.db.models.fields.URLField')(max_length=200)), )) db.send_create_signal(u'cms_form_plugin', ['FormPlugin']) def backwards(self, orm): # Deleting model 'FormPlugin' db.delete_table(u'cmsplugin_formplugin') models = { 'cms.cmsplugin': { 'Meta': {'object_name': 'CMSPlugin'}, 'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}), 'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}), 'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}), 'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, 'cms.placeholder': { 'Meta': {'object_name': 'Placeholder'}, 'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}) }, u'cms_form_plugin.formplugin': { 'Meta': {'object_name': 'FormPlugin', 'db_table': "u'cmsplugin_formplugin'", '_ormbases': ['cms.CMSPlugin']}, u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}), 'form_class': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'post_to_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}), 'success_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True'}) } } complete_apps = ['cms_form_plugin']
metzlar/cms-form-plugin
cms_form_plugin/migrations/0001_initial.py
Python
gpl-2.0
3,411
from utils import scaleToZoom def jsonScript(layer): json = """ <script src="data/json_{layer}.js\"></script>""".format(layer=layer) return json def scaleDependentLayerScript(layer, layerName): min = layer.minimumScale() max = layer.maximumScale() scaleDependentLayer = """ if (map.getZoom() <= {min} && map.getZoom() >= {max}) {{ feature_group.addLayer(json_{layerName}JSON); console.log("show"); //restackLayers(); }} else if (map.getZoom() > {min} || map.getZoom() < {max}) {{ feature_group.removeLayer(json_{layerName}JSON); console.log("hide"); //restackLayers(); }}""".format(min=scaleToZoom(min), max=scaleToZoom(max), layerName=layerName) return scaleDependentLayer def scaleDependentScript(layers): scaleDependent = """ map.on("zoomend", function(e) {""" scaleDependent += layers scaleDependent += """ });""" scaleDependent += layers return scaleDependent def openScript(): openScript = """ <script>""" return openScript def crsScript(crsAuthId, crsProj4): crs = """ var crs = new L.Proj.CRS('{crsAuthId}', '{crsProj4}', {{ resolutions: [2800, 1400, 700, 350, 175, 84, 42, 21, 11.2, 5.6, 2.8, 1.4, 0.7, 0.35, 0.14, 0.07], }});""".format(crsAuthId=crsAuthId, crsProj4=crsProj4) return crs def mapScript(extent, matchCRS, crsAuthId, measure, maxZoom, minZoom, bounds): map = """ var map = L.map('map', {""" if extent == "Canvas extent" and matchCRS and crsAuthId != 'EPSG:4326': map += """ crs: crs, continuousWorld: false, worldCopyJump: false, """ if measure: map += """ measureControl:true,""" map += """ zoomControl:true, maxZoom:""" + unicode(maxZoom) + """, minZoom:""" + unicode(minZoom) + """ })""" if extent == "Canvas extent": map += """.fitBounds(""" + bounds + """);""" map += """ var hash = new L.Hash(map); var additional_attrib = '<a href="https://github.com/tomchadwin/qgis2web" target ="_blank">qgis2web</a>';""" return map def featureGroupsScript(): featureGroups = """ var feature_group = new L.featureGroup([]); var raster_group = new L.LayerGroup([]);""" return featureGroups def basemapsScript(basemap, attribution): basemaps = """ var basemap = L.tileLayer('{basemap}', {{ attribution: additional_attrib + ' {attribution}' }}); basemap.addTo(map);""".format(basemap=basemap, attribution=attribution) return basemaps def layerOrderScript(): layerOrder = """ var layerOrder=new Array(); function restackLayers() { for (index = 0; index < layerOrder.length; index++) { feature_group.removeLayer(layerOrder[index]); feature_group.addLayer(layerOrder[index]); } } layerControl = L.control.layers({},{},{collapsed:false});""" return layerOrder def popFuncsScript(table): popFuncs = """ var popupContent = {table}; layer.bindPopup(popupContent);""".format(table=table) return popFuncs def popupScript(safeLayerName, popFuncs): popup = """ function pop_{safeLayerName}(feature, layer) {{{popFuncs} }}""".format(safeLayerName=safeLayerName, popFuncs=popFuncs) return popup def pointToLayerScript(radius, borderWidth, borderStyle, colorName, borderColor, borderOpacity, opacity, labeltext): pointToLayer = """ pointToLayer: function (feature, latlng) {{ return L.circleMarker(latlng, {{ radius: {radius}, fillColor: '{colorName}', color: '{borderColor}', weight: {borderWidth}, opacity: {borderOpacity}, dashArray: '{dashArray}', fillOpacity: {opacity} }}){labeltext}""".format(radius=radius, colorName=colorName, borderColor=borderColor, borderWidth=borderWidth * 4, borderOpacity=borderOpacity if borderStyle != 0 else 0, dashArray=getLineStyle(borderStyle, borderWidth), opacity=opacity, labeltext=labeltext) return pointToLayer def pointStyleScript(pointToLayer, popFuncs): pointStyle = """{pointToLayer} }}, onEachFeature: function (feature, layer) {{{popFuncs} }}""".format(pointToLayer=pointToLayer, popFuncs=popFuncs) return pointStyle def wfsScript(scriptTag): wfs = """ <script src='{scriptTag}'></script>""".format(scriptTag=scriptTag) return wfs def jsonPointScript(safeLayerName, pointToLayer, usedFields): if usedFields != 0: jsonPoint = """ var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{ onEachFeature: pop_{safeLayerName}, {pointToLayer} }} }}); layerOrder[layerOrder.length] = json_{safeLayerName}JSON;""".format(safeLayerName=safeLayerName, pointToLayer=pointToLayer) else: jsonPoint = """ var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{ {pointToLayer} }} }}); layerOrder[layerOrder.length] = json_{safeLayerName}JSON;""".format(safeLayerName=safeLayerName, pointToLayer=pointToLayer) return jsonPoint def clusterScript(safeLayerName): cluster = """ var cluster_group{safeLayerName}JSON = new L.MarkerClusterGroup({{showCoverageOnHover: false}}); cluster_group{safeLayerName}JSON.addLayer(json_{safeLayerName}JSON);""".format(safeLayerName=safeLayerName) return cluster def categorizedPointStylesScript(symbol, opacity, borderOpacity): styleValues = """ radius: '{radius}', fillColor: '{fillColor}', color: '{color}', weight: {borderWidth}, opacity: {borderOpacity}, dashArray: '{dashArray}', fillOpacity: '{opacity}', }}; break;""".format(radius=symbol.size() * 2, fillColor=symbol.color().name(), color=symbol.symbolLayer(0).borderColor().name(), borderWidth=symbol.symbolLayer(0).outlineWidth() * 4, borderOpacity=borderOpacity if symbol.symbolLayer(0).outlineStyle() != 0 else 0, dashArray=getLineStyle(symbol.symbolLayer(0).outlineStyle(), symbol.symbolLayer(0).outlineWidth()), opacity=opacity) return styleValues def simpleLineStyleScript(radius, colorName, penStyle, opacity): lineStyle = """ return {{ weight: {radius}, color: '{colorName}', dashArray: '{penStyle}', opacity: {opacity} }};""".format(radius=radius * 4, colorName=colorName, penStyle=penStyle, opacity=opacity) return lineStyle def singlePolyStyleScript(radius, colorName, borderOpacity, fillColor, penStyle, opacity): polyStyle = """ return {{ weight: {radius}, color: '{colorName}', fillColor: '{fillColor}', dashArray: '{penStyle}', opacity: {borderOpacity}, fillOpacity: {opacity} }};""".format(radius=radius, colorName=colorName, fillColor=fillColor, penStyle=penStyle, borderOpacity=borderOpacity, opacity=opacity) return polyStyle def nonPointStylePopupsScript(lineStyle, popFuncs): nonPointStylePopups = """ style: function (feature) {{{lineStyle} }}, onEachFeature: function (feature, layer) {{{popFuncs} }}""".format(lineStyle=lineStyle, popFuncs=popFuncs) return nonPointStylePopups def nonPointStyleFunctionScript(safeLayerName, lineStyle): nonPointStyleFunction = """ function doStyle{safeLayerName}(feature) {{{lineStyle} }}""".format(safeLayerName=safeLayerName, lineStyle=lineStyle) return nonPointStyleFunction def categoryScript(layerName, valueAttr): category = """ function doStyle{layerName}(feature) {{ switch (feature.properties.{valueAttr}) {{""".format(layerName=layerName, valueAttr=valueAttr) return category def defaultCategoryScript(): defaultCategory = """ default: return {""" return defaultCategory def eachCategoryScript(catValue): if isinstance(catValue, basestring): valQuote = "'" else: valQuote = "" eachCategory = """ case """ + valQuote + unicode(catValue) + valQuote + """: return {""" return eachCategory def endCategoryScript(): endCategory = """ } }""" return endCategory def categorizedPointWFSscript(layerName, labeltext, popFuncs): categorizedPointWFS = """ pointToLayer: function (feature, latlng) {{ return L.circleMarker(latlng, doStyle{layerName}(feature)){labeltext} }}, onEachFeature: function (feature, layer) {{{popFuncs} }}""".format(layerName=layerName, labeltext=labeltext, popFuncs=popFuncs) return categorizedPointWFS def categorizedPointJSONscript(safeLayerName, labeltext, usedFields): if usedFields != 0: categorizedPointJSON = """ var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{ onEachFeature: pop_{safeLayerName}, pointToLayer: function (feature, latlng) {{ return L.circleMarker(latlng, doStyle{safeLayerName}(feature)){labeltext} }} }}); layerOrder[layerOrder.length] = json_{safeLayerName}JSON;""".format(safeLayerName=safeLayerName, labeltext=labeltext) else: categorizedPointJSON = """ var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{ pointToLayer: function (feature, latlng) {{ return L.circleMarker(latlng, doStyle{safeLayerName}(feature)){labeltext} }} }}); layerOrder[layerOrder.length] = json_{safeLayerName}JSON;""".format(safeLayerName=safeLayerName, labeltext=labeltext) return categorizedPointJSON def categorizedLineStylesScript(symbol, opacity): categorizedLineStyles = """ color: '{color}', weight: '{weight}', dashArray: '{dashArray}', opacity: '{opacity}', }}; break;""".format(color=symbol.color().name(), weight=symbol.width() * 4, dashArray=getLineStyle(symbol.symbolLayer(0).penStyle(), symbol.width()), opacity=opacity) return categorizedLineStyles def categorizedNonPointStyleFunctionScript(layerName, popFuncs): categorizedNonPointStyleFunction = """ style: doStyle{layerName}, onEachFeature: function (feature, layer) {{{popFuncs} }}""".format(layerName=layerName, popFuncs=popFuncs) return categorizedNonPointStyleFunction def categorizedPolygonStylesScript(symbol, opacity, borderOpacity): categorizedPolygonStyles = """ weight: '{weight}', fillColor: '{fillColor}', color: '{color}', dashArray: '{dashArray}', opacity: '{borderOpacity}', fillOpacity: '{opacity}', }}; break;""".format(weight=symbol.symbolLayer(0).borderWidth() * 4, fillColor=symbol.color().name() if symbol.symbolLayer(0).brushStyle() != 0 else "none", color=symbol.symbolLayer(0).borderColor().name() if symbol.symbolLayer(0).borderStyle() != 0 else "none", dashArray=getLineStyle(symbol.symbolLayer(0).borderStyle(), symbol.symbolLayer(0).borderWidth()), borderOpacity=borderOpacity, opacity=opacity) return categorizedPolygonStyles def graduatedStyleScript(layerName): graduatedStyle = """ function doStyle{layerName}(feature) {{""".format(layerName=layerName) return graduatedStyle def rangeStartScript(valueAttr, r): rangeStart = """ if (feature.properties.{valueAttr} >= {lowerValue} && feature.properties.{valueAttr} <= {upperValue}) {{""".format(valueAttr=valueAttr, lowerValue=r.lowerValue(), upperValue=r.upperValue()) return rangeStart def graduatedPointStylesScript(valueAttr, r, symbol, opacity, borderOpacity): graduatedPointStyles = rangeStartScript(valueAttr, r) graduatedPointStyles += """ return {{ radius: '{radius}', fillColor: '{fillColor}', color: '{color}', weight: {lineWeight}, fillOpacity: '{opacity}', opacity: '{borderOpacity}', dashArray: '{dashArray}' }} }}""".format(radius=symbol.size() * 2, fillColor=symbol.color().name(), color=symbol.symbolLayer(0).borderColor().name(), lineWeight=symbol.symbolLayer(0).outlineWidth() * 4, opacity=opacity, borderOpacity=borderOpacity, dashArray=getLineStyle(symbol.symbolLayer(0).outlineStyle(), symbol.symbolLayer(0).outlineWidth())) return graduatedPointStyles def graduatedLineStylesScript(valueAttr, r, categoryStr, symbol, opacity): graduatedLineStyles = rangeStartScript(valueAttr, r) graduatedLineStyles += """ return {{ color: '{color}', weight: '{weight}', dashArray: '{dashArray}', opacity: '{opacity}', }} }}""".format(color=symbol.symbolLayer(0).color().name(), weight=symbol.width() * 4, dashArray=getLineStyle(symbol.symbolLayer(0).penStyle(), symbol.width()), opacity=opacity) return graduatedLineStyles def graduatedPolygonStylesScript(valueAttr, r, symbol, opacity, borderOpacity): graduatedPolygonStyles = rangeStartScript(valueAttr, r) graduatedPolygonStyles += """ return {{ color: '{color}', weight: '{weight}', dashArray: '{dashArray}', fillColor: '{fillColor}', opacity: '{borderOpacity}', fillOpacity: '{opacity}', }} }}""".format(color=symbol.symbolLayer(0).borderColor().name(), weight=symbol.symbolLayer(0).borderWidth() * 4 if symbol.symbolLayer(0).borderStyle() != 0 else "0", dashArray=getLineStyle(symbol.symbolLayer(0).borderStyle(), symbol.symbolLayer(0).borderWidth() if symbol.symbolLayer(0).borderStyle() != 0 else "0"), fillColor=symbol.color().name() if symbol.symbolLayer(0).brushStyle() != 0 else "none", borderOpacity=borderOpacity, opacity=opacity) return graduatedPolygonStyles def endGraduatedStyleScript(): endGraduatedStyle = """ }""" return endGraduatedStyle def customMarkerScript(safeLayerName, labeltext, usedFields): if usedFields != 0: customMarker = """ var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{ onEachFeature: pop_{safeLayerName}, pointToLayer: function (feature, latlng) {{ return L.marker(latlng, {{ icon: L.icon({{ iconUrl: feature.properties.icon_exp, iconSize: [24, 24], // size of the icon change this to scale your icon (first coordinate is x, second y from the upper left corner of the icon) iconAnchor: [12, 12], // point of the icon which will correspond to marker's location (first coordinate is x, second y from the upper left corner of the icon) popupAnchor: [0, -14] // point from which the popup should open relative to the iconAnchor (first coordinate is x, second y from the upper left corner of the icon) }}) }}){labeltext} }}}} );""".format(safeLayerName=safeLayerName, labeltext=labeltext) else: customMarker = """ var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{ pointToLayer: function (feature, latlng) {{ return L.marker(latlng, {{ icon: L.icon({{ iconUrl: feature.properties.icon_exp, iconSize: [24, 24], // size of the icon change this to scale your icon (first coordinate is x, second y from the upper left corner of the icon) iconAnchor: [12, 12], // point of the icon which will correspond to marker's location (first coordinate is x, second y from the upper left corner of the icon) popupAnchor: [0, -14] // point from which the popup should open relative to the iconAnchor (first coordinate is x, second y from the upper left corner of the icon) }}) }}){labeltext} }}}} );""".format(safeLayerName=safeLayerName, labeltext=labeltext) return customMarker def wmsScript(safeLayerName, wms_url, wms_layer, wms_format): wms = """ var overlay_{safeLayerName} = L.tileLayer.wms('{wms_url}', {{ layers: '{wms_layer}', format: '{wms_format}', transparent: true, continuousWorld : true, }});""".format(safeLayerName=safeLayerName, wms_url=wms_url, wms_layer=wms_layer, wms_format=wms_format) return wms def rasterScript(safeLayerName, out_raster_name, bounds): raster = """ var img_{safeLayerName} = '{out_raster_name}'; var img_bounds_{safeLayerName} = {bounds}; var overlay_{safeLayerName} = new L.imageOverlay(img_{safeLayerName}, img_bounds_{safeLayerName});""".format(safeLayerName=safeLayerName, out_raster_name=out_raster_name, bounds=bounds) return raster def titleSubScript(webmap_head, webmap_subhead): titleSub = """ var title = new L.Control(); title.onAdd = function (map) { this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info" this.update(); return this._div; }; title.update = function () { this._div.innerHTML = '<h2>""" + webmap_head.encode('utf-8') + """</h2>""" + webmap_subhead.encode('utf-8') + """' }; title.addTo(map);""" return titleSub def addressSearchScript(): addressSearch = """ var osmGeocoder = new L.Control.OSMGeocoder({ collapsed: false, position: 'topright', text: 'Search', }); osmGeocoder.addTo(map);""" return addressSearch def locateScript(): locate = """ map.locate({setView: true, maxZoom: 16}); function onLocationFound(e) { var radius = e.accuracy / 2; L.marker(e.latlng).addTo(map) .bindPopup("You are within " + radius + " meters from this point").openPopup(); L.circle(e.latlng, radius).addTo(map); } map.on('locationfound', onLocationFound); """ return locate def endHTMLscript(wfsLayers): endHTML = """ </script>{wfsLayers} </body> </html>""".format(wfsLayers=wfsLayers) return endHTML def getLineStyle(penType, lineWidth): dash = lineWidth * 10 dot = lineWidth * 1 gap = lineWidth * 5 if penType > 1: if penType == 2: penStyle = [dash, gap] if penType == 3: penStyle = [dot, gap] if penType == 4: penStyle = [dash, gap, dot, gap] if penType == 5: penStyle = [dash, gap, dot, gap, dot, gap] penStyle = ','.join(map(str, penStyle)) else: penStyle = "" return penStyle
radumas/qgis2web
leafletScriptStrings.py
Python
gpl-2.0
20,814
class Solution: def reverseWords(self, s) : print 1 / 0 tks = s.split(' '); tks = filter(None, tks) tks.reverse(); return ' '.join(tks).strip() test = ["the sky is blue", " a b "] sol = Solution(); for t in test : print sol.reverseWords(t)
yelu/leetcode
ReverseWords.py
Python
gpl-2.0
295
from netools import nextIpInPool, ping, aliveHost, hostsUnDone def main(): aliveHosts = [] # pool IP ipStart = "192.168.56.1" ipEnd = "192.168.56.5" print"Pools: ", ipStart + " -> " + ipEnd print"Scanning online Router on network..." aliveHosts = aliveHost(ipStart, ipEnd) print "online Router:" print aliveHosts # print"New Hosts Alive in Pools:",hostsUnDone(aliveHosts, aliveHost(ipStart,ipEnd)) if __name__ == '__main__': main()
gravufo/commotion-router-testbench
ping/mainTest.py
Python
gpl-2.0
479
import collections import re import sys import warnings from bs4.dammit import EntitySubstitution DEFAULT_OUTPUT_ENCODING = "utf-8" PY3K = (sys.version_info[0] > 2) whitespace_re = re.compile("\s+") def _alias(attr): """Alias one attribute name to another for backward compatibility""" @property def alias(self): return getattr(self, attr) @alias.setter def alias(self): return setattr(self, attr) return alias class NamespacedAttribute(unicode): def __new__(cls, prefix, name, namespace=None): if name is None: obj = unicode.__new__(cls, prefix) elif prefix is None: # Not really namespaced. obj = unicode.__new__(cls, name) else: obj = unicode.__new__(cls, prefix + ":" + name) obj.prefix = prefix obj.name = name obj.namespace = namespace return obj class AttributeValueWithCharsetSubstitution(unicode): """A stand-in object for a character encoding specified in HTML.""" class CharsetMetaAttributeValue(AttributeValueWithCharsetSubstitution): """A generic stand-in for the value of a meta tag's 'charset' attribute. When Beautiful Soup parses the markup '<meta charset="utf8">', the value of the 'charset' attribute will be one of these objects. """ def __new__(cls, original_value): obj = unicode.__new__(cls, original_value) obj.original_value = original_value return obj def encode(self, encoding): return encoding class ContentMetaAttributeValue(AttributeValueWithCharsetSubstitution): """A generic stand-in for the value of a meta tag's 'content' attribute. When Beautiful Soup parses the markup: <meta http-equiv="content-type" content="text/html; charset=utf8"> The value of the 'content' attribute will be one of these objects. """ CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)", re.M) def __new__(cls, original_value): match = cls.CHARSET_RE.search(original_value) if match is None: # No substitution necessary. return unicode.__new__(unicode, original_value) obj = unicode.__new__(cls, original_value) obj.original_value = original_value return obj def encode(self, encoding): def rewrite(match): return match.group(1) + encoding return self.CHARSET_RE.sub(rewrite, self.original_value) class HTMLAwareEntitySubstitution(EntitySubstitution): """Entity substitution rules that are aware of some HTML quirks. Specifically, the contents of <script> and <style> tags should not undergo entity substitution. Incoming NavigableString objects are checked to see if they're the direct children of a <script> or <style> tag. """ cdata_containing_tags = set(["script", "style"]) preformatted_tags = set(["pre"]) @classmethod def _substitute_if_appropriate(cls, ns, f): if (isinstance(ns, NavigableString) and ns.parent is not None and ns.parent.name in cls.cdata_containing_tags): # Do nothing. return ns # Substitute. return f(ns) @classmethod def substitute_html(cls, ns): return cls._substitute_if_appropriate( ns, EntitySubstitution.substitute_html) @classmethod def substitute_xml(cls, ns): return cls._substitute_if_appropriate( ns, EntitySubstitution.substitute_xml) class PageElement(object): """Contains the navigational information for some part of the page (either a tag or a piece of text)""" # There are five possible values for the "formatter" argument passed in # to methods like encode() and prettify(): # # "html" - All Unicode characters with corresponding HTML entities # are converted to those entities on output. # "minimal" - Bare ampersands and angle brackets are converted to # XML entities: &amp; &lt; &gt; # None - The null formatter. Unicode characters are never # converted to entities. This is not recommended, but it's # faster than "minimal". # A function - This function will be called on every string that # needs to undergo entity substitution. # # In an HTML document, the default "html" and "minimal" functions # will leave the contents of <script> and <style> tags alone. For # an XML document, all tags will be given the same treatment. HTML_FORMATTERS = { "html" : HTMLAwareEntitySubstitution.substitute_html, "minimal" : HTMLAwareEntitySubstitution.substitute_xml, None : None } XML_FORMATTERS = { "html" : EntitySubstitution.substitute_html, "minimal" : EntitySubstitution.substitute_xml, None : None } def format_string(self, s, formatter='minimal'): """Format the given string using the given formatter.""" if not callable(formatter): formatter = self._formatter_for_name(formatter) if formatter is None: output = s else: output = formatter(s) return output @property def _is_xml(self): """Is this element part of an XML tree or an HTML tree? This is used when mapping a formatter name ("minimal") to an appropriate function (one that performs entity-substitution on the contents of <script> and <style> tags, or not). It's inefficient, but it should be called very rarely. """ if self.parent is None: # This is the top-level object. It should have .is_xml set # from tree creation. If not, take a guess--BS is usually # used on HTML markup. return getattr(self, 'is_xml', False) return self.parent._is_xml def _formatter_for_name(self, name): "Look up a formatter function based on its name and the tree." if self._is_xml: return self.XML_FORMATTERS.get( name, EntitySubstitution.substitute_xml) else: return self.HTML_FORMATTERS.get( name, HTMLAwareEntitySubstitution.substitute_xml) def setup(self, parent=None, previous_element=None): """Sets up the initial relations between this element and other elements.""" self.parent = parent self.previous_element = previous_element if previous_element is not None: self.previous_element.next_element = self self.next_element = None self.previous_sibling = None self.next_sibling = None if self.parent is not None and self.parent.contents: self.previous_sibling = self.parent.contents[-1] self.previous_sibling.next_sibling = self nextSibling = _alias("next_sibling") # BS3 previousSibling = _alias("previous_sibling") # BS3 def replace_with(self, replace_with): if replace_with is self: return if replace_with is self.parent: raise ValueError("Cannot replace a Tag with its parent.") old_parent = self.parent my_index = self.parent.index(self) self.extract() old_parent.insert(my_index, replace_with) return self replaceWith = replace_with # BS3 def unwrap(self): my_parent = self.parent my_index = self.parent.index(self) self.extract() for child in reversed(self.contents[:]): my_parent.insert(my_index, child) return self replace_with_children = unwrap replaceWithChildren = unwrap # BS3 def wrap(self, wrap_inside): me = self.replace_with(wrap_inside) wrap_inside.append(me) return wrap_inside def extract(self): """Destructively rips this element out of the tree.""" if self.parent is not None: del self.parent.contents[self.parent.index(self)] #Find the two elements that would be next to each other if #this element (and any children) hadn't been parsed. Connect #the two. last_child = self._last_descendant() next_element = last_child.next_element if self.previous_element is not None: self.previous_element.next_element = next_element if next_element is not None: next_element.previous_element = self.previous_element self.previous_element = None last_child.next_element = None self.parent = None if self.previous_sibling is not None: self.previous_sibling.next_sibling = self.next_sibling if self.next_sibling is not None: self.next_sibling.previous_sibling = self.previous_sibling self.previous_sibling = self.next_sibling = None return self def _last_descendant(self): "Finds the last element beneath this object to be parsed." last_child = self while hasattr(last_child, 'contents') and last_child.contents: last_child = last_child.contents[-1] return last_child # BS3: Not part of the API! _lastRecursiveChild = _last_descendant def insert(self, position, new_child): if new_child is self: raise ValueError("Cannot insert a tag into itself.") if (isinstance(new_child, basestring) and not isinstance(new_child, NavigableString)): new_child = NavigableString(new_child) position = min(position, len(self.contents)) if hasattr(new_child, 'parent') and new_child.parent is not None: # We're 'inserting' an element that's already one # of this object's children. if new_child.parent is self: current_index = self.index(new_child) if current_index < position: # We're moving this element further down the list # of this object's children. That means that when # we extract this element, our target index will # jump down one. position -= 1 new_child.extract() new_child.parent = self previous_child = None if position == 0: new_child.previous_sibling = None new_child.previous_element = self else: previous_child = self.contents[position - 1] new_child.previous_sibling = previous_child new_child.previous_sibling.next_sibling = new_child new_child.previous_element = previous_child._last_descendant() if new_child.previous_element is not None: new_child.previous_element.next_element = new_child new_childs_last_element = new_child._last_descendant() if position >= len(self.contents): new_child.next_sibling = None parent = self parents_next_sibling = None while parents_next_sibling is None and parent is not None: parents_next_sibling = parent.next_sibling parent = parent.parent if parents_next_sibling is not None: # We found the element that comes next in the document. break if parents_next_sibling is not None: new_childs_last_element.next_element = parents_next_sibling else: # The last element of this tag is the last element in # the document. new_childs_last_element.next_element = None else: next_child = self.contents[position] new_child.next_sibling = next_child if new_child.next_sibling is not None: new_child.next_sibling.previous_sibling = new_child new_childs_last_element.next_element = next_child if new_childs_last_element.next_element is not None: new_childs_last_element.next_element.previous_element = new_childs_last_element self.contents.insert(position, new_child) def append(self, tag): """Appends the given tag to the contents of this tag.""" self.insert(len(self.contents), tag) def insert_before(self, predecessor): """Makes the given element the immediate predecessor of this one. The two elements will have the same parent, and the given element will be immediately before this one. """ if self is predecessor: raise ValueError("Can't insert an element before itself.") parent = self.parent if parent is None: raise ValueError( "Element has no parent, so 'before' has no meaning.") # Extract first so that the index won't be screwed up if they # are siblings. if isinstance(predecessor, PageElement): predecessor.extract() index = parent.index(self) parent.insert(index, predecessor) def insert_after(self, successor): """Makes the given element the immediate successor of this one. The two elements will have the same parent, and the given element will be immediately after this one. """ if self is successor: raise ValueError("Can't insert an element after itself.") parent = self.parent if parent is None: raise ValueError( "Element has no parent, so 'after' has no meaning.") # Extract first so that the index won't be screwed up if they # are siblings. if isinstance(successor, PageElement): successor.extract() index = parent.index(self) parent.insert(index+1, successor) def find_next(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears after this Tag in the document.""" return self._find_one(self.find_all_next, name, attrs, text, **kwargs) findNext = find_next # BS3 def find_all_next(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear after this Tag in the document.""" return self._find_all(name, attrs, text, limit, self.next_elements, **kwargs) findAllNext = find_all_next # BS3 def find_next_sibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document.""" return self._find_one(self.find_next_siblings, name, attrs, text, **kwargs) findNextSibling = find_next_sibling # BS3 def find_next_siblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear after this Tag in the document.""" return self._find_all(name, attrs, text, limit, self.next_siblings, **kwargs) findNextSiblings = find_next_siblings # BS3 fetchNextSiblings = find_next_siblings # BS2 def find_previous(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears before this Tag in the document.""" return self._find_one( self.find_all_previous, name, attrs, text, **kwargs) findPrevious = find_previous # BS3 def find_all_previous(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear before this Tag in the document.""" return self._find_all(name, attrs, text, limit, self.previous_elements, **kwargs) findAllPrevious = find_all_previous # BS3 fetchPrevious = find_all_previous # BS2 def find_previous_sibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears before this Tag in the document.""" return self._find_one(self.find_previous_siblings, name, attrs, text, **kwargs) findPreviousSibling = find_previous_sibling # BS3 def find_previous_siblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear before this Tag in the document.""" return self._find_all(name, attrs, text, limit, self.previous_siblings, **kwargs) findPreviousSiblings = find_previous_siblings # BS3 fetchPreviousSiblings = find_previous_siblings # BS2 def find_parent(self, name=None, attrs={}, **kwargs): """Returns the closest parent of this Tag that matches the given criteria.""" # NOTE: We can't use _find_one because findParents takes a different # set of arguments. r = None l = self.find_parents(name, attrs, 1, **kwargs) if l: r = l[0] return r findParent = find_parent # BS3 def find_parents(self, name=None, attrs={}, limit=None, **kwargs): """Returns the parents of this Tag that match the given criteria.""" return self._find_all(name, attrs, None, limit, self.parents, **kwargs) findParents = find_parents # BS3 fetchParents = find_parents # BS2 @property def next(self): return self.next_element @property def previous(self): return self.previous_element #These methods do the real heavy lifting. def _find_one(self, method, name, attrs, text, **kwargs): r = None l = method(name, attrs, text, 1, **kwargs) if l: r = l[0] return r def _find_all(self, name, attrs, text, limit, generator, **kwargs): "Iterates over a generator looking for things that match." if isinstance(name, SoupStrainer): strainer = name elif text is None and not limit and not attrs and not kwargs: # Optimization to find all tags. if name is True or name is None: return [element for element in generator if isinstance(element, Tag)] # Optimization to find all tags with a given name. elif isinstance(name, basestring): return [element for element in generator if isinstance(element, Tag) and element.name == name] else: strainer = SoupStrainer(name, attrs, text, **kwargs) else: # Build a SoupStrainer strainer = SoupStrainer(name, attrs, text, **kwargs) results = ResultSet(strainer) while True: try: i = next(generator) except StopIteration: break if i: found = strainer.search(i) if found: results.append(found) if limit and len(results) >= limit: break return results #These generators can be used to navigate starting from both #NavigableStrings and Tags. @property def next_elements(self): i = self.next_element while i is not None: yield i i = i.next_element @property def next_siblings(self): i = self.next_sibling while i is not None: yield i i = i.next_sibling @property def previous_elements(self): i = self.previous_element while i is not None: yield i i = i.previous_element @property def previous_siblings(self): i = self.previous_sibling while i is not None: yield i i = i.previous_sibling @property def parents(self): i = self.parent while i is not None: yield i i = i.parent # Methods for supporting CSS selectors. tag_name_re = re.compile('^[a-z0-9]+$') # /^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/ # \---/ \---/\-------------/ \-------/ # | | | | # | | | The value # | | ~,|,^,$,* or = # | Attribute # Tag attribselect_re = re.compile( r'^(?P<tag>\w+)?\[(?P<attribute>\w+)(?P<operator>[=~\|\^\$\*]?)' + r'=?"?(?P<value>[^\]"]*)"?\]$' ) def _attr_value_as_string(self, value, default=None): """Force an attribute value into a string representation. A multi-valued attribute will be converted into a space-separated stirng. """ value = self.get(value, default) if isinstance(value, list) or isinstance(value, tuple): value =" ".join(value) return value def _tag_name_matches_and(self, function, tag_name): if not tag_name: return function else: def _match(tag): return tag.name == tag_name and function(tag) return _match def _attribute_checker(self, operator, attribute, value=''): """Create a function that performs a CSS selector operation. Takes an operator, attribute and optional value. Returns a function that will return True for elements that match that combination. """ if operator == '=': # string representation of `attribute` is equal to `value` return lambda el: el._attr_value_as_string(attribute) == value elif operator == '~': # space-separated list representation of `attribute` # contains `value` def _includes_value(element): attribute_value = element.get(attribute, []) if not isinstance(attribute_value, list): attribute_value = attribute_value.split() return value in attribute_value return _includes_value elif operator == '^': # string representation of `attribute` starts with `value` return lambda el: el._attr_value_as_string( attribute, '').startswith(value) elif operator == '$': # string represenation of `attribute` ends with `value` return lambda el: el._attr_value_as_string( attribute, '').endswith(value) elif operator == '*': # string representation of `attribute` contains `value` return lambda el: value in el._attr_value_as_string(attribute, '') elif operator == '|': # string representation of `attribute` is either exactly # `value` or starts with `value` and then a dash. def _is_or_starts_with_dash(element): attribute_value = element._attr_value_as_string(attribute, '') return (attribute_value == value or attribute_value.startswith( value + '-')) return _is_or_starts_with_dash else: return lambda el: el.has_attr(attribute) # Old non-property versions of the generators, for backwards # compatibility with BS3. def nextGenerator(self): return self.next_elements def nextSiblingGenerator(self): return self.next_siblings def previousGenerator(self): return self.previous_elements def previousSiblingGenerator(self): return self.previous_siblings def parentGenerator(self): return self.parents class NavigableString(unicode, PageElement): PREFIX = '' SUFFIX = '' def __new__(cls, value): """Create a new NavigableString. When unpickling a NavigableString, this method is called with the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be passed in to the superclass's __new__ or the superclass won't know how to handle non-ASCII characters. """ if isinstance(value, unicode): return unicode.__new__(cls, value) return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING) def __copy__(self): return self def __getnewargs__(self): return (unicode(self),) def __getattr__(self, attr): """text.string gives you text. This is for backwards compatibility for Navigable*String, but for CData* it lets you get the string without the CData wrapper.""" if attr == 'string': return self else: raise AttributeError( "'%s' object has no attribute '%s'" % ( self.__class__.__name__, attr)) def output_ready(self, formatter="minimal"): output = self.format_string(self, formatter) return self.PREFIX + output + self.SUFFIX class PreformattedString(NavigableString): """A NavigableString not subject to the normal formatting rules. The string will be passed into the formatter (to trigger side effects), but the return value will be ignored. """ def output_ready(self, formatter="minimal"): """CData strings are passed into the formatter. But the return value is ignored.""" self.format_string(self, formatter) return self.PREFIX + self + self.SUFFIX class CData(PreformattedString): PREFIX = u'<![CDATA[' SUFFIX = u']]>' class ProcessingInstruction(PreformattedString): PREFIX = u'<?' SUFFIX = u'?>' class Comment(PreformattedString): PREFIX = u'<!--' SUFFIX = u'-->' class Declaration(PreformattedString): PREFIX = u'<!' SUFFIX = u'!>' class Doctype(PreformattedString): @classmethod def for_name_and_ids(cls, name, pub_id, system_id): value = name or '' if pub_id is not None: value += ' PUBLIC "%s"' % pub_id if system_id is not None: value += ' "%s"' % system_id elif system_id is not None: value += ' SYSTEM "%s"' % system_id return Doctype(value) PREFIX = u'<!DOCTYPE ' SUFFIX = u'>\n' class Tag(PageElement): """Represents a found HTML tag with its attributes and contents.""" def __init__(self, parser=None, builder=None, name=None, namespace=None, prefix=None, attrs=None, parent=None, previous=None): "Basic constructor." if parser is None: self.parser_class = None else: # We don't actually store the parser object: that lets extracted # chunks be garbage-collected. self.parser_class = parser.__class__ if name is None: raise ValueError("No value provided for new tag's name.") self.name = name self.namespace = namespace self.prefix = prefix if attrs is None: attrs = {} elif builder.cdata_list_attributes: attrs = builder._replace_cdata_list_attribute_values( self.name, attrs) else: attrs = dict(attrs) self.attrs = attrs self.contents = [] self.setup(parent, previous) self.hidden = False # Set up any substitutions, such as the charset in a META tag. if builder is not None: builder.set_up_substitutions(self) self.can_be_empty_element = builder.can_be_empty_element(name) else: self.can_be_empty_element = False parserClass = _alias("parser_class") # BS3 @property def is_empty_element(self): """Is this tag an empty-element tag? (aka a self-closing tag) A tag that has contents is never an empty-element tag. A tag that has no contents may or may not be an empty-element tag. It depends on the builder used to create the tag. If the builder has a designated list of empty-element tags, then only a tag whose name shows up in that list is considered an empty-element tag. If the builder has no designated list of empty-element tags, then any tag with no contents is an empty-element tag. """ return len(self.contents) == 0 and self.can_be_empty_element isSelfClosing = is_empty_element # BS3 @property def string(self): """Convenience property to get the single string within this tag. :Return: If this tag has a single string child, return value is that string. If this tag has no children, or more than one child, return value is None. If this tag has one child tag, return value is the 'string' attribute of the child tag, recursively. """ if len(self.contents) != 1: return None child = self.contents[0] if isinstance(child, NavigableString): return child return child.string @string.setter def string(self, string): self.clear() self.append(string.__class__(string)) def _all_strings(self, strip=False, types=(NavigableString, CData)): """Yield all strings of certain classes, possibly stripping them. By default, yields only NavigableString and CData objects. So no comments, processing instructions, etc. """ for descendant in self.descendants: if ( (types is None and not isinstance(descendant, NavigableString)) or (types is not None and type(descendant) not in types)): continue if strip: descendant = descendant.strip() if len(descendant) == 0: continue yield descendant strings = property(_all_strings) @property def stripped_strings(self): for string in self._all_strings(True): yield string def get_text(self, separator=u"", strip=False, types=(NavigableString, CData)): """ Get all child strings, concatenated using the given separator. """ return separator.join([s for s in self._all_strings( strip, types=types)]) getText = get_text text = property(get_text) def decompose(self): """Recursively destroys the contents of this tree.""" self.extract() i = self while i is not None: next = i.next_element i.__dict__.clear() i.contents = [] i = next def clear(self, decompose=False): """ Extract all children. If decompose is True, decompose instead. """ if decompose: for element in self.contents[:]: if isinstance(element, Tag): element.decompose() else: element.extract() else: for element in self.contents[:]: element.extract() def index(self, element): """ Find the index of a child by identity, not value. Avoids issues with tag.contents.index(element) getting the index of equal elements. """ for i, child in enumerate(self.contents): if child is element: return i raise ValueError("Tag.index: element not in tag") def get(self, key, default=None): """Returns the value of the 'key' attribute for the tag, or the value given for 'default' if it doesn't have that attribute.""" return self.attrs.get(key, default) def has_attr(self, key): return key in self.attrs def __hash__(self): return str(self).__hash__() def __getitem__(self, key): """tag[key] returns the value of the 'key' attribute for the tag, and throws an exception if it's not there.""" return self.attrs[key] def __iter__(self): "Iterating over a tag iterates over its contents." return iter(self.contents) def __len__(self): "The length of a tag is the length of its list of contents." return len(self.contents) def __contains__(self, x): return x in self.contents def __nonzero__(self): "A tag is non-None even if it has no contents." return True def __setitem__(self, key, value): """Setting tag[key] sets the value of the 'key' attribute for the tag.""" self.attrs[key] = value def __delitem__(self, key): "Deleting tag[key] deletes all 'key' attributes for the tag." self.attrs.pop(key, None) def __call__(self, *args, **kwargs): """Calling a tag like a function is the same as calling its find_all() method. Eg. tag('a') returns a list of all the A tags found within this tag.""" return self.find_all(*args, **kwargs) def __getattr__(self, tag): #print "Getattr %s.%s" % (self.__class__, tag) if len(tag) > 3 and tag.endswith('Tag'): # BS3: soup.aTag -> "soup.find("a") tag_name = tag[:-3] warnings.warn( '.%sTag is deprecated, use .find("%s") instead.' % ( tag_name, tag_name)) return self.find(tag_name) # We special case contents to avoid recursion. elif not tag.startswith("__") and not tag=="contents": return self.find(tag) raise AttributeError( "'%s' object has no attribute '%s'" % (self.__class__, tag)) def __eq__(self, other): """Returns true iff this tag has the same name, the same attributes, and the same contents (recursively) as the given tag.""" if self is other: return True if (not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other)): return False for i, my_child in enumerate(self.contents): if my_child != other.contents[i]: return False return True def __ne__(self, other): """Returns true iff this tag is not identical to the other tag, as defined in __eq__.""" return not self == other def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING): """Renders this tag as a string.""" return self.encode(encoding) def __unicode__(self): return self.decode() def __str__(self): return self.encode() if PY3K: __str__ = __repr__ = __unicode__ def encode(self, encoding=DEFAULT_OUTPUT_ENCODING, indent_level=None, formatter="minimal", errors="xmlcharrefreplace"): # Turn the data structure into Unicode, then encode the # Unicode. u = self.decode(indent_level, encoding, formatter) return u.encode(encoding, errors) def _should_pretty_print(self, indent_level): """Should this tag be pretty-printed?""" return ( indent_level is not None and (self.name not in HTMLAwareEntitySubstitution.preformatted_tags or self._is_xml)) def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter="minimal"): """Returns a Unicode representation of this tag and its contents. :param eventual_encoding: The tag is destined to be encoded into this encoding. This method is _not_ responsible for performing that encoding. This information is passed in so that it can be substituted in if the document contains a <META> tag that mentions the document's encoding. """ # First off, turn a string formatter into a function. This # will stop the lookup from happening over and over again. if not callable(formatter): formatter = self._formatter_for_name(formatter) attrs = [] if self.attrs: for key, val in sorted(self.attrs.items()): if val is None: decoded = key else: if isinstance(val, list) or isinstance(val, tuple): val = ' '.join(val) elif not isinstance(val, basestring): val = unicode(val) elif ( isinstance(val, AttributeValueWithCharsetSubstitution) and eventual_encoding is not None): val = val.encode(eventual_encoding) text = self.format_string(val, formatter) decoded = ( unicode(key) + '=' + EntitySubstitution.quoted_attribute_value(text)) attrs.append(decoded) close = '' closeTag = '' prefix = '' if self.prefix: prefix = self.prefix + ":" if self.is_empty_element: close = '/' else: closeTag = '</%s%s>' % (prefix, self.name) pretty_print = self._should_pretty_print(indent_level) space = '' indent_space = '' if indent_level is not None: indent_space = (' ' * (indent_level - 1)) if pretty_print: space = indent_space indent_contents = indent_level + 1 else: indent_contents = None contents = self.decode_contents( indent_contents, eventual_encoding, formatter) if self.hidden: # This is the 'document root' object. s = contents else: s = [] attribute_string = '' if attrs: attribute_string = ' ' + ' '.join(attrs) if indent_level is not None: # Even if this particular tag is not pretty-printed, # we should indent up to the start of the tag. s.append(indent_space) s.append('<%s%s%s%s>' % ( prefix, self.name, attribute_string, close)) if pretty_print: s.append("\n") s.append(contents) if pretty_print and contents and contents[-1] != "\n": s.append("\n") if pretty_print and closeTag: s.append(space) s.append(closeTag) if indent_level is not None and closeTag and self.next_sibling: # Even if this particular tag is not pretty-printed, # we're now done with the tag, and we should add a # newline if appropriate. s.append("\n") s = ''.join(s) return s def prettify(self, encoding=None, formatter="minimal"): if encoding is None: return self.decode(True, formatter=formatter) else: return self.encode(encoding, True, formatter=formatter) def decode_contents(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter="minimal"): """Renders the contents of this tag as a Unicode string. :param eventual_encoding: The tag is destined to be encoded into this encoding. This method is _not_ responsible for performing that encoding. This information is passed in so that it can be substituted in if the document contains a <META> tag that mentions the document's encoding. """ # First off, turn a string formatter into a function. This # will stop the lookup from happening over and over again. if not callable(formatter): formatter = self._formatter_for_name(formatter) pretty_print = (indent_level is not None) s = [] for c in self: text = None if isinstance(c, NavigableString): text = c.output_ready(formatter) elif isinstance(c, Tag): s.append(c.decode(indent_level, eventual_encoding, formatter)) if text and indent_level and not self.name == 'pre': text = text.strip() if text: if pretty_print and not self.name == 'pre': s.append(" " * (indent_level - 1)) s.append(text) if pretty_print and not self.name == 'pre': s.append("\n") return ''.join(s) def encode_contents( self, indent_level=None, encoding=DEFAULT_OUTPUT_ENCODING, formatter="minimal"): """Renders the contents of this tag as a bytestring.""" contents = self.decode_contents(indent_level, encoding, formatter) return contents.encode(encoding) # Old method for BS3 compatibility def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): if not prettyPrint: indentLevel = None return self.encode_contents( indent_level=indentLevel, encoding=encoding) #Soup methods def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs): """Return only the first child of this Tag matching the given criteria.""" r = None l = self.find_all(name, attrs, recursive, text, 1, **kwargs) if l: r = l[0] return r findChild = find def find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): """Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. The value of a key-value pair in the 'attrs' map can be a string, a list of strings, a regular expression object, or a callable that takes a string and returns whether or not the string matches for some custom definition of 'matches'. The same is true of the tag name.""" generator = self.descendants if not recursive: generator = self.children return self._find_all(name, attrs, text, limit, generator, **kwargs) findAll = find_all # BS3 findChildren = find_all # BS2 #Generator methods @property def children(self): # return iter() to make the purpose of the method clear return iter(self.contents) # XXX This seems to be untested. @property def descendants(self): if not len(self.contents): return stopNode = self._last_descendant().next_element current = self.contents[0] while current is not stopNode: yield current current = current.next_element # CSS selector code _selector_combinators = ['>', '+', '~'] _select_debug = False def select(self, selector, _candidate_generator=None): """Perform a CSS selection operation on the current element.""" tokens = selector.split() current_context = [self] if tokens[-1] in self._selector_combinators: raise ValueError( 'Final combinator "%s" is missing an argument.' % tokens[-1]) if self._select_debug: print 'Running CSS selector "%s"' % selector for index, token in enumerate(tokens): if self._select_debug: print ' Considering token "%s"' % token recursive_candidate_generator = None tag_name = None if tokens[index-1] in self._selector_combinators: # This token was consumed by the previous combinator. Skip it. if self._select_debug: print ' Token was consumed by the previous combinator.' continue # Each operation corresponds to a checker function, a rule # for determining whether a candidate matches the # selector. Candidates are generated by the active # iterator. checker = None m = self.attribselect_re.match(token) if m is not None: # Attribute selector tag_name, attribute, operator, value = m.groups() checker = self._attribute_checker(operator, attribute, value) elif '#' in token: # ID selector tag_name, tag_id = token.split('#', 1) def id_matches(tag): return tag.get('id', None) == tag_id checker = id_matches elif '.' in token: # Class selector tag_name, klass = token.split('.', 1) classes = set(klass.split('.')) def classes_match(candidate): return classes.issubset(candidate.get('class', [])) checker = classes_match elif ':' in token: # Pseudo-class tag_name, pseudo = token.split(':', 1) if tag_name == '': continue raise ValueError( "A pseudo-class must be prefixed with a tag name.") pseudo_attributes = re.match('([a-zA-Z\d-]+)\(([a-zA-Z\d]+)\)', pseudo) found = [] if pseudo_attributes is not None: pseudo_type, pseudo_value = pseudo_attributes.groups() if pseudo_type == 'nth-of-type': try: pseudo_value = int(pseudo_value) except: continue raise NotImplementedError( 'Only numeric values are currently supported for the nth-of-type pseudo-class.') if pseudo_value < 1: continue raise ValueError( 'nth-of-type pseudo-class value must be at least 1.') class Counter(object): def __init__(self, destination): self.count = 0 self.destination = destination def nth_child_of_type(self, tag): self.count += 1 if self.count == self.destination: return True if self.count > self.destination: # Stop the generator that's sending us # these things. raise StopIteration() return False checker = Counter(pseudo_value).nth_child_of_type else: continue raise NotImplementedError( 'Only the following pseudo-classes are implemented: nth-of-type.') elif token == '*': # Star selector -- matches everything pass elif token == '>': # Run the next token as a CSS selector against the # direct children of each tag in the current context. recursive_candidate_generator = lambda tag: tag.children elif token == '~': # Run the next token as a CSS selector against the # siblings of each tag in the current context. recursive_candidate_generator = lambda tag: tag.next_siblings elif token == '+': # For each tag in the current context, run the next # token as a CSS selector against the tag's next # sibling that's a tag. def next_tag_sibling(tag): yield tag.find_next_sibling(True) recursive_candidate_generator = next_tag_sibling elif self.tag_name_re.match(token): # Just a tag name. tag_name = token else: continue raise ValueError( 'Unsupported or invalid CSS selector: "%s"' % token) if recursive_candidate_generator: # This happens when the selector looks like "> foo". # # The generator calls select() recursively on every # member of the current context, passing in a different # candidate generator and a different selector. # # In the case of "> foo", the candidate generator is # one that yields a tag's direct children (">"), and # the selector is "foo". next_token = tokens[index+1] def recursive_select(tag): if self._select_debug: print ' Calling select("%s") recursively on %s %s' % (next_token, tag.name, tag.attrs) print '-' * 40 for i in tag.select(next_token, recursive_candidate_generator): if self._select_debug: print '(Recursive select picked up candidate %s %s)' % (i.name, i.attrs) yield i if self._select_debug: print '-' * 40 _use_candidate_generator = recursive_select elif _candidate_generator is None: # By default, a tag's candidates are all of its # children. If tag_name is defined, only yield tags # with that name. if self._select_debug: if tag_name: check = "[any]" else: check = tag_name print ' Default candidate generator, tag name="%s"' % check if self._select_debug: # This is redundant with later code, but it stops # a bunch of bogus tags from cluttering up the # debug log. def default_candidate_generator(tag): for child in tag.descendants: if not isinstance(child, Tag): continue if tag_name and not child.name == tag_name: continue yield child _use_candidate_generator = default_candidate_generator else: _use_candidate_generator = lambda tag: tag.descendants else: _use_candidate_generator = _candidate_generator new_context = [] new_context_ids = set([]) for tag in current_context: if self._select_debug: print " Running candidate generator on %s %s" % ( tag.name, repr(tag.attrs)) for candidate in _use_candidate_generator(tag): if not isinstance(candidate, Tag): continue if tag_name and candidate.name != tag_name: continue if checker is not None: try: result = checker(candidate) except StopIteration: # The checker has decided we should no longer # run the generator. break if checker is None or result: if self._select_debug: print " SUCCESS %s %s" % (candidate.name, repr(candidate.attrs)) if id(candidate) not in new_context_ids: # If a tag matches a selector more than once, # don't include it in the context more than once. new_context.append(candidate) new_context_ids.add(id(candidate)) elif self._select_debug: print " FAILURE %s %s" % (candidate.name, repr(candidate.attrs)) current_context = new_context if self._select_debug: print "Final verdict:" for i in current_context: print " %s %s" % (i.name, i.attrs) return current_context # Old names for backwards compatibility def childGenerator(self): return self.children def recursiveChildGenerator(self): return self.descendants def has_key(self, key): """This was kind of misleading because has_key() (attributes) was different from __in__ (contents). has_key() is gone in Python 3, anyway.""" warnings.warn('has_key is deprecated. Use has_attr("%s") instead.' % ( key)) return self.has_attr(key) # Next, a couple classes to represent queries and their results. class SoupStrainer(object): """Encapsulates a number of ways of matching a markup element (tag or text).""" def __init__(self, name=None, attrs={}, text=None, **kwargs): self.name = self._normalize_search_value(name) if not isinstance(attrs, dict): # Treat a non-dict value for attrs as a search for the 'class' # attribute. kwargs['class'] = attrs attrs = None if 'class_' in kwargs: # Treat class_="foo" as a search for the 'class' # attribute, overriding any non-dict value for attrs. kwargs['class'] = kwargs['class_'] del kwargs['class_'] if kwargs: if attrs: attrs = attrs.copy() attrs.update(kwargs) else: attrs = kwargs normalized_attrs = {} for key, value in attrs.items(): normalized_attrs[key] = self._normalize_search_value(value) self.attrs = normalized_attrs self.text = self._normalize_search_value(text) def _normalize_search_value(self, value): # Leave it alone if it's a Unicode string, a callable, a # regular expression, a boolean, or None. if (isinstance(value, unicode) or callable(value) or hasattr(value, 'match') or isinstance(value, bool) or value is None): return value # If it's a bytestring, convert it to Unicode, treating it as UTF-8. if isinstance(value, bytes): return value.decode("utf8") # If it's listlike, convert it into a list of strings. if hasattr(value, '__iter__'): new_value = [] for v in value: if (hasattr(v, '__iter__') and not isinstance(v, bytes) and not isinstance(v, unicode)): # This is almost certainly the user's mistake. In the # interests of avoiding infinite loops, we'll let # it through as-is rather than doing a recursive call. new_value.append(v) else: new_value.append(self._normalize_search_value(v)) return new_value # Otherwise, convert it into a Unicode string. # The unicode(str()) thing is so this will do the same thing on Python 2 # and Python 3. return unicode(str(value)) def __str__(self): if self.text: return self.text else: return "%s|%s" % (self.name, self.attrs) def search_tag(self, markup_name=None, markup_attrs={}): found = None markup = None if isinstance(markup_name, Tag): markup = markup_name markup_attrs = markup call_function_with_tag_data = ( isinstance(self.name, collections.Callable) and not isinstance(markup_name, Tag)) if ((not self.name) or call_function_with_tag_data or (markup and self._matches(markup, self.name)) or (not markup and self._matches(markup_name, self.name))): if call_function_with_tag_data: match = self.name(markup_name, markup_attrs) else: match = True markup_attr_map = None for attr, match_against in list(self.attrs.items()): if not markup_attr_map: if hasattr(markup_attrs, 'get'): markup_attr_map = markup_attrs else: markup_attr_map = {} for k, v in markup_attrs: markup_attr_map[k] = v attr_value = markup_attr_map.get(attr) if not self._matches(attr_value, match_against): match = False break if match: if markup: found = markup else: found = markup_name if found and self.text and not self._matches(found.string, self.text): found = None return found searchTag = search_tag def search(self, markup): # print 'looking for %s in %s' % (self, markup) found = None # If given a list of items, scan it for a text element that # matches. if hasattr(markup, '__iter__') and not isinstance(markup, (Tag, basestring)): for element in markup: if isinstance(element, NavigableString) \ and self.search(element): found = element break # If it's a Tag, make sure its name or attributes match. # Don't bother with Tags if we're searching for text. elif isinstance(markup, Tag): if not self.text or self.name or self.attrs: found = self.search_tag(markup) # If it's text, make sure the text matches. elif isinstance(markup, NavigableString) or \ isinstance(markup, basestring): if not self.name and not self.attrs and self._matches(markup, self.text): found = markup else: raise Exception( "I don't know how to match against a %s" % markup.__class__) return found def _matches(self, markup, match_against): # print u"Matching %s against %s" % (markup, match_against) result = False if isinstance(markup, list) or isinstance(markup, tuple): # This should only happen when searching a multi-valued attribute # like 'class'. if (isinstance(match_against, unicode) and ' ' in match_against): # A bit of a special case. If they try to match "foo # bar" on a multivalue attribute's value, only accept # the literal value "foo bar" # # XXX This is going to be pretty slow because we keep # splitting match_against. But it shouldn't come up # too often. return (whitespace_re.split(match_against) == markup) else: for item in markup: if self._matches(item, match_against): return True return False if match_against is True: # True matches any non-None value. return markup is not None if isinstance(match_against, collections.Callable): return match_against(markup) # Custom callables take the tag as an argument, but all # other ways of matching match the tag name as a string. if isinstance(markup, Tag): markup = markup.name # Ensure that `markup` is either a Unicode string, or None. markup = self._normalize_search_value(markup) if markup is None: # None matches None, False, an empty string, an empty list, and so on. return not match_against if isinstance(match_against, unicode): # Exact string match return markup == match_against if hasattr(match_against, 'match'): # Regexp match return match_against.search(markup) if hasattr(match_against, '__iter__'): # The markup must be an exact match against something # in the iterable. return markup in match_against class ResultSet(list): """A ResultSet is just a list that keeps track of the SoupStrainer that created it.""" def __init__(self, source): list.__init__([]) self.source = source
ruuk/script.web.viewer2
lib/webviewer/bs4/element.py
Python
gpl-2.0
61,200
# This file is part of the Enkel web programming library. # # Copyright (C) 2007 Espen Angell Kristiansen ([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 unittest import TestCase from enkel.wansgli.testhelpers import unit_case_suite, run_suite class Test(TestCase): def suite(): return unit_case_suite(Test) if __name__ == '__main__': run_suite(suite())
espenak/enkel
testsuite/unittest_tpl.py
Python
gpl-2.0
1,046
#!/usr/bin/env python # # Copyright (C) 2004 Mark H. Lyon <[email protected]> # # This file is the Mbox & Maildir to Gmail Loader (GML). # # Mbox & Maildir to Gmail Loader (GML) 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. # # GML 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 GML; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # Origional development thread at Ars Technica: # http://episteme.arstechnica.com/eve/ubb.x?a=tpc&s=50009562&f=6330927813&m=108000474631 # # Version 0.1 - 15 Jun 04 16:28 Supports Mbox # Version 0.2 - 15 Jun 04 18:48 Implementing Magus` suggestion for Maildir # Version 0.3 - 16 Jun 04 16:17 Implement Rold Gold suggestion for counters # Version 0.4 - 17 Jun 04 13:15 Add support for changing SMTP server at command line # Version 0.5 - 05 Oct 09 redo exception handling to see what Google's # complaints are on failure, update to use TLS import mailbox, smtplib, sys, time, string def main (): print "\nMbox & Maildir to Gmail Loader (GML) by Mark Lyon <[email protected]>\n" if len(sys.argv) in (5, 6) : boxtype_in = sys.argv[1] mailboxname_in = sys.argv[2] emailname_in = sys.argv[3] password_in = sys.argv[4] else: usage() try: smtpserver_in = sys.argv[5] except: smtpserver_in = 'smtp.gmail.com' print "Using smtpserver %s\n" % smtpserver_in count = [0,0,0] try: if boxtype_in == "maildir": mb = mailbox.Maildir(mailboxname_in) else: mb = mailbox.UnixMailbox (file(mailboxname_in,'r')) msg = mb.next() except: print "*** Can't open file or directory. Is the path correct? ***\n" usage() while msg is not None: try: document = msg.fp.read() except: count[2] = count[2] + 1 print "*** %d MESSAGE READ FAILED, SKIPPED" % (count[2]) msg = mb.next() if document is not None: fullmsg = msg.__str__( ) + '\x0a' + document server = smtplib.SMTP(smtpserver_in) #server.set_debuglevel(1) server.ehlo() server.starttls() # smtplib won't send auth info without this second ehlo after # starttls -- thanks to # http://bytes.com/topic/python/answers/475531-smtplib-authentication-required-error # for the tip server.ehlo() server.login(emailname_in, password_in) server.sendmail(msg.getaddr('From')[1], emailname_in, fullmsg) server.quit() count[0] = count[0] + 1 print " %d Forwarded a message from: %s" % (count[0], msg.getaddr('From')[1]) msg = mb.next() print "\nDone. Stats: %d success %d error %d skipped." % (count[0], count[1], count[2]) def usage(): print 'Usage: gml.py [mbox or maildir] [mbox file or maildir path] [gmail address] [gmail password] [Optional SMTP Server]' print 'Exmpl: gml.py mbox "c:\mail\Inbox" [email protected] password' print 'Exmpl: gml.py maildir "c:\mail\Inbox\" [email protected] password gsmtp171.google.com\n' sys.exit() if __name__ == '__main__': main ()
jslag/gml
gml.py
Python
gpl-2.0
3,630
# -*- coding: utf-8 -*- ## Comments and reviews for records. ## This file is part of Invenio. ## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio 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. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """HTML Templates for commenting features """ __revision__ = "$Id$" import cgi # Invenio imports from invenio.urlutils import create_html_link from invenio.webuser import get_user_info, collect_user_info, isGuestUser, get_email from invenio.dateutils import convert_datetext_to_dategui from invenio.webmessage_mailutils import email_quoted_txt2html from invenio.webcomment_config import \ CFG_WEBCOMMENT_MAX_ATTACHED_FILES, \ CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE from invenio.config import CFG_SITE_URL, \ CFG_SITE_SECURE_URL, \ CFG_SITE_LANG, \ CFG_SITE_NAME, \ CFG_SITE_NAME_INTL,\ CFG_SITE_SUPPORT_EMAIL,\ CFG_WEBCOMMENT_ALLOW_REVIEWS, \ CFG_WEBCOMMENT_ALLOW_COMMENTS, \ CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR, \ CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN, \ CFG_WEBCOMMENT_AUTHOR_DELETE_COMMENT_OPTION, \ CFG_CERN_SITE from invenio.htmlutils import get_html_text_editor from invenio.messages import gettext_set_language from invenio.bibformat import format_record from invenio.access_control_engine import acc_authorize_action from invenio.websearch_templates import get_fieldvalues class Template: """templating class, refer to webcomment.py for examples of call""" def tmpl_get_first_comments_without_ranking(self, recID, ln, comments, nb_comments_total, warnings): """ @param recID: record id @param ln: language @param comments: tuple as returned from webcomment.py/query_retrieve_comments_or_remarks @param nb_comments_total: total number of comments for this record @param warnings: list of warning tuples (warning_msg, arg1, arg2, ...) @return: html of comments """ # load the right message language _ = gettext_set_language(ln) # naming data fields of comments c_nickname = 0 c_user_id = 1 c_date_creation = 2 c_body = 3 c_id = 4 warnings = self.tmpl_warnings(warnings, ln) # comments comment_rows = '' max_comment_round_name = comments[-1][0] for comment_round_name, comments_list in comments: comment_rows += '<div id="cmtRound%i" class="cmtRound">' % (comment_round_name) comment_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name} + "<br/>" for comment in comments_list: if comment[c_nickname]: nickname = comment[c_nickname] display = nickname else: (uid, nickname, display) = get_user_info(comment[c_user_id]) messaging_link = self.create_messaging_link(nickname, display, ln) comment_rows += """ <tr> <td>""" report_link = '%s/record/%s/comments/report?ln=%s&amp;comid=%s' % (CFG_SITE_URL, recID, ln, comment[c_id]) reply_link = '%s/record/%s/comments/add?ln=%s&amp;comid=%s&amp;action=REPLY' % (CFG_SITE_URL, recID, ln, comment[c_id]) comment_rows += self.tmpl_get_comment_without_ranking(req=None, ln=ln, nickname=messaging_link, comment_uid=comment[c_user_id], date_creation=comment[c_date_creation], body=comment[c_body], status='', nb_reports=0, report_link=report_link, reply_link=reply_link, recID=recID) comment_rows += """ <br /> <br /> </td> </tr>""" # Close comment round comment_rows += '</div>' # write button write_button_label = _("Write a comment") write_button_link = '%s/record/%s/comments/add' % (CFG_SITE_URL, recID) write_button_form = '<input type="hidden" name="ln" value="%s"/>' % ln write_button_form = self.createhiddenform(action=write_button_link, method="get", text=write_button_form, button=write_button_label) # output if nb_comments_total > 0: out = warnings comments_label = len(comments) > 1 and _("Showing the latest %i comments:") % len(comments) \ or "" out += """ <table> <tr> <td class="blocknote">%(comment_title)s</td> </tr> </table> %(comments_label)s<br /> <table border="0" cellspacing="5" cellpadding="5" width="100%%"> %(comment_rows)s </table> %(view_all_comments_link)s <br /> <br /> %(write_button_form)s<br />""" % \ {'comment_title': _("Discuss this document"), 'comments_label': comments_label, 'nb_comments_total' : nb_comments_total, 'recID': recID, 'comment_rows': comment_rows, 'tab': '&nbsp;'*4, 'siteurl': CFG_SITE_URL, 's': nb_comments_total>1 and 's' or "", 'view_all_comments_link': nb_comments_total>0 and '''<a href="%s/record/%s/comments/display">View all %s comments</a>''' \ % (CFG_SITE_URL, recID, nb_comments_total) or "", 'write_button_form': write_button_form, 'nb_comments': len(comments) } else: out = """ <!-- comments title table --> <table> <tr> <td class="blocknote">%(discuss_label)s:</td> </tr> </table> %(detailed_info)s <br /> %(form)s <br />""" % {'form': write_button_form, 'discuss_label': _("Discuss this document"), 'detailed_info': _("Start a discussion about any aspect of this document.") } return out def tmpl_record_not_found(self, status='missing', recID="", ln=CFG_SITE_LANG): """ Displays a page when bad or missing record ID was given. @param status: 'missing' : no recID was given 'inexistant': recID doesn't have an entry in the database 'nan' : recID is not a number 'invalid' : recID is an error code, i.e. in the interval [-99,-1] @param return: body of the page """ _ = gettext_set_language(ln) if status == 'inexistant': body = _("Sorry, the record %s does not seem to exist.") % (recID,) elif status in ('nan', 'invalid'): body = _("Sorry, %s is not a valid ID value.") % (recID,) else: body = _("Sorry, no record ID was provided.") body += "<br /><br />" link = "<a href=\"%s?ln=%s\">%s</a>." % (CFG_SITE_URL, ln, CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME)) body += _("You may want to start browsing from %s") % link return body def tmpl_get_first_comments_with_ranking(self, recID, ln, comments=None, nb_comments_total=None, avg_score=None, warnings=[]): """ @param recID: record id @param ln: language @param comments: tuple as returned from webcomment.py/query_retrieve_comments_or_remarks @param nb_comments_total: total number of comments for this record @param avg_score: average score of all reviews @param warnings: list of warning tuples (warning_msg, arg1, arg2, ...) @return: html of comments """ # load the right message language _ = gettext_set_language(ln) # naming data fields of comments c_nickname = 0 c_user_id = 1 c_date_creation = 2 c_body = 3 c_nb_votes_yes = 4 c_nb_votes_total = 5 c_star_score = 6 c_title = 7 c_id = 8 warnings = self.tmpl_warnings(warnings, ln) #stars if avg_score > 0: avg_score_img = 'stars-' + str(avg_score).split('.')[0] + '-' + str(avg_score).split('.')[1] + '.png' else: avg_score_img = "stars-0-0.png" # voting links useful_dict = { 'siteurl' : CFG_SITE_URL, 'recID' : recID, 'ln' : ln, 'yes_img' : 'smchk_gr.gif', #'yes.gif', 'no_img' : 'iconcross.gif' #'no.gif' } link = '<a href="%(siteurl)s/record/%(recID)s/reviews/vote?ln=%(ln)s&amp;comid=%%(comid)s' % useful_dict useful_yes = link + '&amp;com_value=1">' + _("Yes") + '</a>' useful_no = link + '&amp;com_value=-1">' + _("No") + '</a>' #comment row comment_rows = ' ' max_comment_round_name = comments[-1][0] for comment_round_name, comments_list in comments: comment_rows += '<div id="cmtRound%i" class="cmtRound">' % (comment_round_name) comment_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name} + "<br/>" for comment in comments_list: if comment[c_nickname]: nickname = comment[c_nickname] display = nickname else: (uid, nickname, display) = get_user_info(comment[c_user_id]) messaging_link = self.create_messaging_link(nickname, display, ln) comment_rows += ''' <tr> <td>''' report_link = '%s/record/%s/reviews/report?ln=%s&amp;comid=%s' % (CFG_SITE_URL, recID, ln, comment[c_id]) comment_rows += self.tmpl_get_comment_with_ranking(None, ln=ln, nickname=messaging_link, comment_uid=comment[c_user_id], date_creation=comment[c_date_creation], body=comment[c_body], status='', nb_reports=0, nb_votes_total=comment[c_nb_votes_total], nb_votes_yes=comment[c_nb_votes_yes], star_score=comment[c_star_score], title=comment[c_title], report_link=report_link, recID=recID) comment_rows += ''' %s %s / %s<br />''' % (_("Was this review helpful?"), useful_yes % {'comid':comment[c_id]}, useful_no % {'comid':comment[c_id]}) comment_rows += ''' <br /> </td> </tr>''' # Close comment round comment_rows += '</div>' # write button write_button_link = '''%s/record/%s/reviews/add''' % (CFG_SITE_URL, recID) write_button_form = ' <input type="hidden" name="ln" value="%s"/>' % ln write_button_form = self.createhiddenform(action=write_button_link, method="get", text=write_button_form, button=_("Write a review")) if nb_comments_total > 0: avg_score_img = str(avg_score_img) avg_score = str(avg_score) nb_comments_total = str(nb_comments_total) score = '<b>' score += _("Average review score: %(x_nb_score)s based on %(x_nb_reviews)s reviews") % \ {'x_nb_score': '</b><img src="' + CFG_SITE_URL + '/img/' + avg_score_img + '" alt="' + avg_score + '" />', 'x_nb_reviews': nb_comments_total} useful_label = _("Readers found the following %s reviews to be most helpful.") useful_label %= len(comments) > 1 and len(comments) or "" view_all_comments_link ='<a href="%s/record/%s/reviews/display?ln=%s&amp;do=hh">' % (CFG_SITE_URL, recID, ln) view_all_comments_link += _("View all %s reviews") % nb_comments_total view_all_comments_link += '</a><br />' out = warnings + """ <!-- review title table --> <table> <tr> <td class="blocknote">%(comment_title)s:</td> </tr> </table> %(score_label)s<br /> %(useful_label)s <!-- review table --> <table style="border: 0px; border-collapse: separate; border-spacing: 5px; padding: 5px; width: 100%%"> %(comment_rows)s </table> %(view_all_comments_link)s %(write_button_form)s<br /> """ % \ { 'comment_title' : _("Rate this document"), 'score_label' : score, 'useful_label' : useful_label, 'recID' : recID, 'view_all_comments' : _("View all %s reviews") % (nb_comments_total,), 'write_comment' : _("Write a review"), 'comment_rows' : comment_rows, 'tab' : '&nbsp;'*4, 'siteurl' : CFG_SITE_URL, 'view_all_comments_link': nb_comments_total>0 and view_all_comments_link or "", 'write_button_form' : write_button_form } else: out = ''' <!-- review title table --> <table> <tr> <td class="blocknote">%s:</td> </tr> </table> %s<br /> %s <br />''' % (_("Rate this document"), _("Be the first to review this document."), write_button_form) return out def tmpl_get_comment_without_ranking(self, req, ln, nickname, comment_uid, date_creation, body, status, nb_reports, reply_link=None, report_link=None, undelete_link=None, delete_links=None, unreport_link=None, recID=-1, com_id='', attached_files=None): """ private function @param req: request object to fetch user info @param ln: language @param nickname: nickname @param date_creation: date comment was written @param body: comment body @param status: status of the comment: da: deleted by author dm: deleted by moderator ok: active @param nb_reports: number of reports the comment has @param reply_link: if want reply and report, give the http links @param report_link: if want reply and report, give the http links @param undelete_link: http link to delete the message @param delete_links: http links to delete the message @param unreport_link: http link to unreport the comment @param recID: recID where the comment is posted @param com_id: ID of the comment displayed @param attached_files: list of attached files @return: html table of comment """ from invenio.search_engine import guess_primary_collection_of_a_record # load the right message language _ = gettext_set_language(ln) date_creation = convert_datetext_to_dategui(date_creation, ln=ln) if attached_files is None: attached_files = [] out = '' final_body = email_quoted_txt2html(body) title = _('%(x_name)s wrote on %(x_date)s:') % {'x_name': nickname, 'x_date': '<i>' + date_creation + '</i>'} title += '<a name=%s></a>' % com_id links = '' moderator_links = '' if reply_link: links += '<a href="' + reply_link +'">' + _("Reply") +'</a>' if report_link and status != 'ap': links += ' | ' if report_link and status != 'ap': links += '<a href="' + report_link +'">' + _("Report abuse") + '</a>' # Check if user is a comment moderator record_primary_collection = guess_primary_collection_of_a_record(recID) user_info = collect_user_info(req) (auth_code, auth_msg) = acc_authorize_action(user_info, 'moderatecomments', collection=record_primary_collection) if status in ['dm', 'da'] and req: if not auth_code: if status == 'dm': final_body = '<div style="color:#a3a3a3;font-style:italic;">(Comment deleted by the moderator) - not visible for users<br /><br />' +\ final_body + '</div>' else: final_body = '<div style="color:#a3a3a3;font-style:italic;">(Comment deleted by the author) - not visible for users<br /><br />' +\ final_body + '</div>' links = '' moderator_links += '<a style="color:#8B0000;" href="' + undelete_link + '">' + _("Undelete comment") + '</a>' else: if status == 'dm': final_body = '<div style="color:#a3a3a3;font-style:italic;">Comment deleted by the moderator</div>' else: final_body = '<div style="color:#a3a3a3;font-style:italic;">Comment deleted by the author</div>' links = '' else: if not auth_code: moderator_links += '<a style="color:#8B0000;" href="' + delete_links['mod'] +'">' + _("Delete comment") + '</a>' elif (user_info['uid'] == comment_uid) and CFG_WEBCOMMENT_AUTHOR_DELETE_COMMENT_OPTION: moderator_links += '<a style="color:#8B0000;" href="' + delete_links['auth'] +'">' + _("Delete comment") + '</a>' if nb_reports >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN: if not auth_code: final_body = '<div style="color:#a3a3a3;font-style:italic;">(Comment reported. Pending approval) - not visible for users<br /><br />' + final_body + '</div>' links = '' moderator_links += ' | ' moderator_links += '<a style="color:#8B0000;" href="' + unreport_link +'">' + _("Unreport comment") + '</a>' else: final_body = '<div style="color:#a3a3a3;font-style:italic;">This comment is pending approval due to user reports</div>' links = '' if links and moderator_links: links = links + ' || ' + moderator_links elif not links: links = moderator_links attached_files_html = '' if attached_files: attached_files_html = '<div class="cmtfilesblock"><b>%s:</b><br/>' % (len(attached_files) == 1 and _("Attached file") or _("Attached files")) for (filename, filepath, fileurl) in attached_files: attached_files_html += create_html_link(urlbase=fileurl, urlargd={}, link_label=cgi.escape(filename)) + '<br />' attached_files_html += '</div>' out += """ <div style="margin-bottom:20px;background:#F9F9F9;border:1px solid #DDD">%(title)s<br /> <blockquote> %(body)s </blockquote> <br /> %(attached_files_html)s <div style="float:right">%(links)s</div> </div>""" % \ {'title' : '<div style="background-color:#EEE;padding:2px;"><img src="%s/img/user-icon-1-24x24.gif" alt="" />&nbsp;%s</div>' % (CFG_SITE_URL, title), 'body' : final_body, 'links' : links, 'attached_files_html': attached_files_html} return out def tmpl_get_comment_with_ranking(self, req, ln, nickname, comment_uid, date_creation, body, status, nb_reports, nb_votes_total, nb_votes_yes, star_score, title, report_link=None, delete_links=None, undelete_link=None, unreport_link=None, recID=-1): """ private function @param req: request object to fetch user info @param ln: language @param nickname: nickname @param date_creation: date comment was written @param body: comment body @param status: status of the comment @param nb_reports: number of reports the comment has @param nb_votes_total: total number of votes for this review @param nb_votes_yes: number of positive votes for this record @param star_score: star score for this record @param title: title of review @param report_link: if want reply and report, give the http links @param undelete_link: http link to delete the message @param delete_link: http link to delete the message @param unreport_link: http link to unreport the comment @param recID: recID where the comment is posted @return: html table of review """ from invenio.search_engine import guess_primary_collection_of_a_record # load the right message language _ = gettext_set_language(ln) if star_score > 0: star_score_img = 'stars-' + str(star_score) + '-0.png' else: star_score_img = 'stars-0-0.png' out = "" date_creation = convert_datetext_to_dategui(date_creation, ln=ln) reviewed_label = _("Reviewed by %(x_nickname)s on %(x_date)s") % {'x_nickname': nickname, 'x_date':date_creation} useful_label = _("%(x_nb_people)i out of %(x_nb_total)i people found this review useful") % {'x_nb_people': nb_votes_yes, 'x_nb_total': nb_votes_total} links = '' _body = '' if body != '': _body = ''' <blockquote> %s </blockquote>''' % email_quoted_txt2html(body, linebreak_html='') # Check if user is a comment moderator record_primary_collection = guess_primary_collection_of_a_record(recID) user_info = collect_user_info(req) (auth_code, auth_msg) = acc_authorize_action(user_info, 'moderatecomments', collection=record_primary_collection) if status in ['dm', 'da'] and req: if not auth_code: if status == 'dm': _body = '<div style="color:#a3a3a3;font-style:italic;">(Review deleted by moderator) - not visible for users<br /><br />' +\ _body + '</div>' else: _body = '<div style="color:#a3a3a3;font-style:italic;">(Review deleted by author) - not visible for users<br /><br />' +\ _body + '</div>' links = '<a style="color:#8B0000;" href="' + undelete_link + '">' + _("Undelete review") + '</a>' else: if status == 'dm': _body = '<div style="color:#a3a3a3;font-style:italic;">Review deleted by moderator</div>' else: _body = '<div style="color:#a3a3a3;font-style:italic;">Review deleted by author</div>' links = '' else: if not auth_code: links += '<a style="color:#8B0000;" href="' + delete_links['mod'] +'">' + _("Delete review") + '</a>' if nb_reports >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN: if not auth_code: _body = '<div style="color:#a3a3a3;font-style:italic;">(Review reported. Pending approval) - not visible for users<br /><br />' + _body + '</div>' links += ' | ' links += '<a style="color:#8B0000;" href="' + unreport_link +'">' + _("Unreport review") + '</a>' else: _body = '<div style="color:#a3a3a3;font-style:italic;">This review is pending approval due to user reports.</div>' links = '' out += ''' <div style="background:#F9F9F9;border:1px solid #DDD"> <div style="background-color:#EEE;padding:2px;"> <img src="%(siteurl)s/img/%(star_score_img)s" alt="%(star_score)s" style="margin-right:10px;"/><b>%(title)s</b><br /> %(reviewed_label)s<br /> %(useful_label)s </div> %(body)s </div> %(abuse)s''' % {'siteurl' : CFG_SITE_URL, 'star_score_img': star_score_img, 'star_score' : star_score, 'title' : title, 'reviewed_label': reviewed_label, 'useful_label' : useful_label, 'body' : _body, 'abuse' : links } return out def tmpl_get_comments(self, req, recID, ln, nb_per_page, page, nb_pages, display_order, display_since, CFG_WEBCOMMENT_ALLOW_REVIEWS, comments, total_nb_comments, avg_score, warnings, border=0, reviews=0, total_nb_reviews=0, nickname='', uid=-1, note='',score=5, can_send_comments=False, can_attach_files=False, user_is_subscribed_to_discussion=False, user_can_unsubscribe_from_discussion=False, display_comment_rounds=None): """ Get table of all comments @param recID: record id @param ln: language @param nb_per_page: number of results per page @param page: page number @param display_order: hh = highest helpful score, review only lh = lowest helpful score, review only hs = highest star score, review only ls = lowest star score, review only od = oldest date nd = newest date @param display_since: all= no filtering by date nd = n days ago nw = n weeks ago nm = n months ago ny = n years ago where n is a single digit integer between 0 and 9 @param CFG_WEBCOMMENT_ALLOW_REVIEWS: is ranking enable, get from config.py/CFG_WEBCOMMENT_ALLOW_REVIEWS @param comments: tuple as returned from webcomment.py/query_retrieve_comments_or_remarks @param total_nb_comments: total number of comments for this record @param avg_score: average score of reviews for this record @param warnings: list of warning tuples (warning_msg, color) @param border: boolean, active if want to show border around each comment/review @param reviews: boolean, enabled for reviews, disabled for comments @param can_send_comments: boolean, if user can send comments or not @param can_attach_files: boolean, if user can attach file to comment or not @param user_is_subscribed_to_discussion: True if user already receives new comments by email @param user_can_unsubscribe_from_discussion: True is user is allowed to unsubscribe from discussion """ # load the right message language _ = gettext_set_language(ln) # CERN hack begins: display full ATLAS user name. Check further below too. current_user_fullname = "" override_nickname_p = False if CFG_CERN_SITE: from invenio.search_engine import get_all_collections_of_a_record user_info = collect_user_info(uid) if 'atlas-readaccess-active-members [CERN]' in user_info['group']: # An ATLAS member is never anonymous to its colleagues # when commenting inside ATLAS collections recid_collections = get_all_collections_of_a_record(recID) if 'ATLAS' in str(recid_collections): override_nickname_p = True current_user_fullname = user_info.get('external_fullname', '') # CERN hack ends # naming data fields of comments if reviews: c_nickname = 0 c_user_id = 1 c_date_creation = 2 c_body = 3 c_status = 4 c_nb_reports = 5 c_nb_votes_yes = 6 c_nb_votes_total = 7 c_star_score = 8 c_title = 9 c_id = 10 c_round_name = 11 c_restriction = 12 reply_to = 13 discussion = 'reviews' comments_link = '<a href="%s/record/%s/comments/">%s</a> (%i)' % (CFG_SITE_URL, recID, _('Comments'), total_nb_comments) reviews_link = '<b>%s (%i)</b>' % (_('Reviews'), total_nb_reviews) add_comment_or_review = self.tmpl_add_comment_form_with_ranking(recID, uid, current_user_fullname or nickname, ln, '', score, note, warnings, show_title_p=True, can_attach_files=can_attach_files) else: c_nickname = 0 c_user_id = 1 c_date_creation = 2 c_body = 3 c_status = 4 c_nb_reports = 5 c_id = 6 c_round_name = 7 c_restriction = 8 reply_to = 9 discussion = 'comments' comments_link = '<b>%s (%i)</b>' % (_('Comments'), total_nb_comments) reviews_link = '<a href="%s/record/%s/reviews/">%s</a> (%i)' % (CFG_SITE_URL, recID, _('Reviews'), total_nb_reviews) add_comment_or_review = self.tmpl_add_comment_form(recID, uid, nickname, ln, note, warnings, can_attach_files=can_attach_files, user_is_subscribed_to_discussion=user_is_subscribed_to_discussion) # voting links useful_dict = { 'siteurl' : CFG_SITE_URL, 'recID' : recID, 'ln' : ln, 'do' : display_order, 'ds' : display_since, 'nb' : nb_per_page, 'p' : page, 'reviews' : reviews, 'discussion' : discussion } useful_yes = '<a href="%(siteurl)s/record/%(recID)s/%(discussion)s/vote?ln=%(ln)s&amp;comid=%%(comid)s&amp;com_value=1&amp;do=%(do)s&amp;ds=%(ds)s&amp;nb=%(nb)s&amp;p=%(p)s&amp;referer=%(siteurl)s/record/%(recID)s/%(discussion)s/display">' + _("Yes") + '</a>' useful_yes %= useful_dict useful_no = '<a href="%(siteurl)s/record/%(recID)s/%(discussion)s/vote?ln=%(ln)s&amp;comid=%%(comid)s&amp;com_value=-1&amp;do=%(do)s&amp;ds=%(ds)s&amp;nb=%(nb)s&amp;p=%(p)s&amp;referer=%(siteurl)s/record/%(recID)s/%(discussion)s/display">' + _("No") + '</a>' useful_no %= useful_dict warnings = self.tmpl_warnings(warnings, ln) link_dic = { 'siteurl' : CFG_SITE_URL, 'module' : 'comments', 'function' : 'index', 'discussion': discussion, 'arguments' : 'do=%s&amp;ds=%s&amp;nb=%s' % (display_order, display_since, nb_per_page), 'arg_page' : '&amp;p=%s' % page, 'page' : page, 'rec_id' : recID} if not req: req = None ## comments table comments_rows = '' last_comment_round_name = None comment_round_names = [comment[0] for comment in comments] if comment_round_names: last_comment_round_name = comment_round_names[-1] for comment_round_name, comments_list in comments: comment_round_style = "display:none;" comment_round_is_open = False if comment_round_name in display_comment_rounds: comment_round_is_open = True comment_round_style = "" comments_rows += '<div id="cmtRound%s" class="cmtround">' % (comment_round_name) if not comment_round_is_open and \ (comment_round_name or len(comment_round_names) > 1): new_cmtgrp = list(display_comment_rounds) new_cmtgrp.append(comment_round_name) comments_rows += '''<img src="/img/right-trans.gif" id="cmtarrowiconright%(grp_id)s" alt="Open group" /><img src="/img/down-trans.gif" id="cmtarrowicondown%(grp_id)s" alt="Close group" style="display:none" /> <a class="cmtgrpswitch" name="cmtgrpLink%(grp_id)s" onclick="var cmtarrowicondown=document.getElementById('cmtarrowicondown%(grp_id)s');var cmtarrowiconright=document.getElementById('cmtarrowiconright%(grp_id)s');var subgrp=document.getElementById('cmtSubRound%(grp_id)s');if (subgrp.style.display==''){subgrp.style.display='none';cmtarrowiconright.style.display='';cmtarrowicondown.style.display='none';}else{subgrp.style.display='';cmtarrowiconright.style.display='none';cmtarrowicondown.style.display='';};return false;"''' % {'grp_id': comment_round_name} comments_rows += 'href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s' % link_dic comments_rows += '&amp;' + '&amp;'.join(["cmtgrp=" + grp for grp in new_cmtgrp if grp != 'none']) + \ '#cmtgrpLink%s' % (comment_round_name) + '\">' comments_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name} + "</a><br/>" elif comment_round_name or len(comment_round_names) > 1: new_cmtgrp = list(display_comment_rounds) new_cmtgrp.remove(comment_round_name) comments_rows += '''<img src="/img/right-trans.gif" id="cmtarrowiconright%(grp_id)s" alt="Open group" style="display:none" /><img src="/img/down-trans.gif" id="cmtarrowicondown%(grp_id)s" alt="Close group" /> <a class="cmtgrpswitch" name="cmtgrpLink%(grp_id)s" onclick="var cmtarrowicondown=document.getElementById('cmtarrowicondown%(grp_id)s');var cmtarrowiconright=document.getElementById('cmtarrowiconright%(grp_id)s');var subgrp=document.getElementById('cmtSubRound%(grp_id)s');if (subgrp.style.display==''){subgrp.style.display='none';cmtarrowiconright.style.display='';cmtarrowicondown.style.display='none';}else{subgrp.style.display='';cmtarrowiconright.style.display='none';cmtarrowicondown.style.display='';};return false;"''' % {'grp_id': comment_round_name} comments_rows += 'href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s' % link_dic comments_rows += '&amp;' + ('&amp;'.join(["cmtgrp=" + grp for grp in new_cmtgrp if grp != 'none']) or 'cmtgrp=none' ) + \ '#cmtgrpLink%s' % (comment_round_name) + '\">' comments_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name}+ "</a><br/>" comments_rows += '<div id="cmtSubRound%s" class="cmtsubround" style="%s">' % (comment_round_name, comment_round_style) thread_history = [0] for comment in comments_list: if comment[reply_to] not in thread_history: # Going one level down in the thread thread_history.append(comment[reply_to]) depth = thread_history.index(comment[reply_to]) else: depth = thread_history.index(comment[reply_to]) thread_history = thread_history[:depth + 1] # CERN hack begins: display full ATLAS user name. comment_user_fullname = "" if CFG_CERN_SITE and override_nickname_p: comment_user_fullname = get_email(comment[c_user_id]) # CERN hack ends if comment[c_nickname]: _nickname = comment[c_nickname] display = _nickname else: (uid, _nickname, display) = get_user_info(comment[c_user_id]) messaging_link = self.create_messaging_link(_nickname, comment_user_fullname or display, ln) from invenio.webcomment import get_attached_files # FIXME files = get_attached_files(recID, comment[c_id]) # do NOT delete the HTML comment below. It is used for parsing... (I plead unguilty!) comments_rows += """ <!-- start comment row --> <div style="margin-left:%spx">""" % (depth*20) delete_links = {} if not reviews: report_link = '%(siteurl)s/record/%(recID)s/comments/report?ln=%(ln)s&amp;comid=%%(comid)s&amp;do=%(do)s&amp;ds=%(ds)s&amp;nb=%(nb)s&amp;p=%(p)s&amp;referer=%(siteurl)s/record/%(recID)s/comments/display' % useful_dict % {'comid':comment[c_id]} reply_link = '%(siteurl)s/record/%(recID)s/comments/add?ln=%(ln)s&amp;action=REPLY&amp;comid=%%(comid)s' % useful_dict % {'comid':comment[c_id]} delete_links['mod'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_mod?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) delete_links['auth'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_auth?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) undelete_link = "%s/admin/webcomment/webcommentadmin.py/undel_com?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) unreport_link = "%s/admin/webcomment/webcommentadmin.py/unreport_com?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) comments_rows += self.tmpl_get_comment_without_ranking(req, ln, messaging_link, comment[c_user_id], comment[c_date_creation], comment[c_body], comment[c_status], comment[c_nb_reports], reply_link, report_link, undelete_link, delete_links, unreport_link, recID, comment[c_id], files) else: report_link = '%(siteurl)s/record/%(recID)s/reviews/report?ln=%(ln)s&amp;comid=%%(comid)s&amp;do=%(do)s&amp;ds=%(ds)s&amp;nb=%(nb)s&amp;p=%(p)s&amp;referer=%(siteurl)s/record/%(recID)s/reviews/display' % useful_dict % {'comid': comment[c_id]} delete_links['mod'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_mod?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) delete_links['auth'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_auth?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) undelete_link = "%s/admin/webcomment/webcommentadmin.py/undel_com?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) unreport_link = "%s/admin/webcomment/webcommentadmin.py/unreport_com?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) comments_rows += self.tmpl_get_comment_with_ranking(req, ln, messaging_link, comment[c_user_id], comment[c_date_creation], comment[c_body], comment[c_status], comment[c_nb_reports], comment[c_nb_votes_total], comment[c_nb_votes_yes], comment[c_star_score], comment[c_title], report_link, delete_links, undelete_link, unreport_link, recID) helpful_label = _("Was this review helpful?") report_abuse_label = "(" + _("Report abuse") + ")" yes_no_separator = '<td> / </td>' if comment[c_nb_reports] >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN or comment[c_status] in ['dm', 'da']: report_abuse_label = "" helpful_label = "" useful_yes = "" useful_no = "" yes_no_separator = "" comments_rows += """ <table> <tr> <td>%(helpful_label)s %(tab)s</td> <td> %(yes)s </td> %(yes_no_separator)s <td> %(no)s </td> <td class="reportabuse">%(tab)s%(tab)s<a href="%(report)s">%(report_abuse_label)s</a></td> </tr> </table>""" \ % {'helpful_label': helpful_label, 'yes' : useful_yes % {'comid':comment[c_id]}, 'yes_no_separator': yes_no_separator, 'no' : useful_no % {'comid':comment[c_id]}, 'report' : report_link % {'comid':comment[c_id]}, 'report_abuse_label': comment[c_nb_reports] >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN and '' or report_abuse_label, 'tab' : '&nbsp;'*2} # do NOT remove HTML comment below. It is used for parsing... comments_rows += """ </div> <!-- end comment row -->""" comments_rows += '</div></div>' ## page links page_links = '' # Previous if page != 1: link_dic['arg_page'] = 'p=%s' % (page - 1) page_links += '<a href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s\">&lt;&lt;</a> ' % link_dic else: page_links += ' %s ' % ('&nbsp;'*(len(_('Previous'))+7)) # Page Numbers for i in range(1, nb_pages+1): link_dic['arg_page'] = 'p=%s' % i link_dic['page'] = '%s' % i if i != page: page_links += ''' <a href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s\">%(page)s</a> ''' % link_dic else: page_links += ''' <b>%s</b> ''' % i # Next if page != nb_pages: link_dic['arg_page'] = 'p=%s' % (page + 1) page_links += ''' <a href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s\">&gt;&gt;</a> ''' % link_dic else: page_links += '%s' % ('&nbsp;'*(len(_('Next'))+7)) ## stuff for ranking if enabled if reviews: if avg_score > 0: avg_score_img = 'stars-' + str(avg_score).split('.')[0] + '-' + str(avg_score).split('.')[1] + '.png' else: avg_score_img = "stars-0-0.png" ranking_average = '<br /><b>' ranking_average += _("Average review score: %(x_nb_score)s based on %(x_nb_reviews)s reviews") % \ {'x_nb_score': '</b><img src="' + CFG_SITE_URL + '/img/' + avg_score_img + '" alt="' + str(avg_score) + '" />', 'x_nb_reviews': str(total_nb_reviews)} ranking_average += '<br />' else: ranking_average = "" write_button_link = '''%s/record/%s/%s/add''' % (CFG_SITE_URL, recID, discussion) write_button_form = '<input type="hidden" name="ln" value="%s"/>' write_button_form = self.createhiddenform(action=write_button_link, method="get", text=write_button_form, button = reviews and _('Write a review') or _('Write a comment')) if reviews: total_label = _("There is a total of %s reviews") else: total_label = _("There is a total of %s comments") total_label %= total_nb_comments review_or_comment_first = '' if reviews == 0 and total_nb_comments == 0 and can_send_comments: review_or_comment_first = _("Start a discussion about any aspect of this document.") + '<br />' elif reviews == 1 and total_nb_reviews == 0 and can_send_comments: review_or_comment_first = _("Be the first to review this document.") + '<br />' # do NOT remove the HTML comments below. Used for parsing body = ''' %(comments_and_review_tabs)s <!-- start comments table --> <div style="border: %(border)spx solid black; width: 95%%; margin:10px;font-size:small"> %(comments_rows)s </div> <!-- end comments table --> %(review_or_comment_first)s <br />''' % \ { 'record_label': _("Record"), 'back_label': _("Back to search results"), 'total_label': total_label, 'write_button_form' : write_button_form, 'write_button_form_again' : total_nb_comments>3 and write_button_form or "", 'comments_rows' : comments_rows, 'total_nb_comments' : total_nb_comments, 'comments_or_reviews' : reviews and _('review') or _('comment'), 'comments_or_reviews_title' : reviews and _('Review') or _('Comment'), 'siteurl' : CFG_SITE_URL, 'module' : "comments", 'recid' : recID, 'ln' : ln, 'border' : border, 'ranking_avg' : ranking_average, 'comments_and_review_tabs' : CFG_WEBCOMMENT_ALLOW_REVIEWS and \ CFG_WEBCOMMENT_ALLOW_COMMENTS and \ '%s | %s <br />' % \ (comments_link, reviews_link) or '', 'review_or_comment_first' : review_or_comment_first } # form is not currently used. reserved for an eventual purpose #form = """ # Display <select name="nb" size="1"> per page # <option value="all">All</option> # <option value="10">10</option> # <option value="25">20</option> # <option value="50">50</option> # <option value="100" selected="selected">100</option> # </select> # comments per page that are <select name="ds" size="1"> # <option value="all" selected="selected">Any age</option> # <option value="1d">1 day old</option> # <option value="3d">3 days old</option> # <option value="1w">1 week old</option> # <option value="2w">2 weeks old</option> # <option value="1m">1 month old</option> # <option value="3m">3 months old</option> # <option value="6m">6 months old</option> # <option value="1y">1 year old</option> # </select> # and sorted by <select name="do" size="1"> # <option value="od" selected="selected">Oldest first</option> # <option value="nd">Newest first</option> # %s # </select> # """ % \ # (reviews==1 and ''' # <option value=\"hh\">most helpful</option> # <option value=\"lh\">least helpful</option> # <option value=\"hs\">highest star ranking</option> # <option value=\"ls\">lowest star ranking</option> # </select>''' or ''' # </select>''') # #form_link = "%(siteurl)s/%(module)s/%(function)s" % link_dic #form = self.createhiddenform(action=form_link, method="get", text=form, button='Go', recid=recID, p=1) pages = """ <div> %(v_label)s %(comments_or_reviews)s %(results_nb_lower)s-%(results_nb_higher)s <br /> %(page_links)s </div> """ % \ {'v_label': _("Viewing"), 'page_links': _("Page:") + page_links , 'comments_or_reviews': reviews and _('review') or _('comment'), 'results_nb_lower': len(comments)>0 and ((page-1) * nb_per_page)+1 or 0, 'results_nb_higher': page == nb_pages and (((page-1) * nb_per_page) + len(comments)) or (page * nb_per_page)} if nb_pages > 1: #body = warnings + body + form + pages body = warnings + body + pages else: body = warnings + body if reviews == 0: if not user_is_subscribed_to_discussion: body += '<small>' body += '<div class="comment-subscribe">' + '<img src="%s/img/mail-icon-12x8.gif" border="0" alt="" />' % CFG_SITE_URL + \ '&nbsp;' + '<b>' + create_html_link(urlbase=CFG_SITE_URL + '/record/' + \ str(recID) + '/comments/subscribe', urlargd={}, link_label=_('Subscribe')) + \ '</b>' + ' to this discussion. You will then receive all new comments by email.' + '</div>' body += '</small><br />' elif user_can_unsubscribe_from_discussion: body += '<small>' body += '<div class="comment-subscribe">' + '<img src="%s/img/mail-icon-12x8.gif" border="0" alt="" />' % CFG_SITE_URL + \ '&nbsp;' + '<b>' + create_html_link(urlbase=CFG_SITE_URL + '/record/' + \ str(recID) + '/comments/unsubscribe', urlargd={}, link_label=_('Unsubscribe')) + \ '</b>' + ' from this discussion. You will no longer receive emails about new comments.' + '</div>' body += '</small><br />' if can_send_comments: body += add_comment_or_review else: body += '<br/><em>' + _("You are not authorized to comment or review.") + '</em>' return '<div style="margin-left:10px;margin-right:10px;">' + body + '</div>' def create_messaging_link(self, to, display_name, ln=CFG_SITE_LANG): """prints a link to the messaging system""" link = "%s/yourmessages/write?msg_to=%s&amp;ln=%s" % (CFG_SITE_URL, to, ln) if to: return '<a href="%s" class="maillink">%s</a>' % (link, display_name) else: return display_name def createhiddenform(self, action="", method="get", text="", button="confirm", cnfrm='', **hidden): """ create select with hidden values and submit button @param action: name of the action to perform on submit @param method: 'get' or 'post' @param text: additional text, can also be used to add non hidden input @param button: value/caption on the submit button @param cnfrm: if given, must check checkbox to confirm @param **hidden: dictionary with name=value pairs for hidden input @return: html form """ output = """ <form action="%s" method="%s">""" % (action, method.lower().strip() in ['get', 'post'] and method or 'get') output += """ <table style="width:90%"> <tr> <td style="vertical-align: top"> """ output += text + '\n' if cnfrm: output += """ <input type="checkbox" name="confirm" value="1" />""" for key in hidden.keys(): if type(hidden[key]) is list: for value in hidden[key]: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, value) else: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, hidden[key]) output += """ </td> </tr> <tr> <td>""" output += """ <input class="adminbutton" type="submit" value="%s" />""" % (button, ) output += """ </td> </tr> </table> </form>""" return output def create_write_comment_hiddenform(self, action="", method="get", text="", button="confirm", cnfrm='', enctype='', **hidden): """ create select with hidden values and submit button @param action: name of the action to perform on submit @param method: 'get' or 'post' @param text: additional text, can also be used to add non hidden input @param button: value/caption on the submit button @param cnfrm: if given, must check checkbox to confirm @param **hidden: dictionary with name=value pairs for hidden input @return: html form """ enctype_attr = '' if enctype: enctype_attr = 'enctype=' + enctype output = """ <form action="%s" method="%s" %s>""" % (action, method.lower().strip() in ['get', 'post'] and method or 'get', enctype_attr) if cnfrm: output += """ <input type="checkbox" name="confirm" value="1" />""" for key in hidden.keys(): if type(hidden[key]) is list: for value in hidden[key]: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, value) else: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, hidden[key]) output += text + '\n' output += """ </form>""" return output def tmpl_warnings(self, warnings, ln=CFG_SITE_LANG): """ Prepare the warnings list @param warnings: list of warning tuples (warning_msg, arg1, arg2, etc) @return: html string of warnings """ red_text_warnings = ['WRN_WEBCOMMENT_FEEDBACK_NOT_RECORDED', 'WRN_WEBCOMMENT_ALREADY_VOTED'] green_text_warnings = ['WRN_WEBCOMMENT_FEEDBACK_RECORDED', 'WRN_WEBCOMMENT_SUBSCRIBED', 'WRN_WEBCOMMENT_UNSUBSCRIBED'] from invenio.errorlib import get_msgs_for_code_list span_class = 'important' out = "" if type(warnings) is not list: warnings = [warnings] if len(warnings) > 0: warnings_parsed = get_msgs_for_code_list(warnings, 'warning', ln) for (warning_code, warning_text) in warnings_parsed: if not warning_code.startswith('WRN'): #display only warnings that begin with WRN to user continue if warning_code in red_text_warnings: span_class = 'important' elif warning_code in green_text_warnings: span_class = 'exampleleader' else: span_class = 'important' out += ''' <span class="%(span_class)s">%(warning)s</span><br />''' % \ { 'span_class' : span_class, 'warning' : warning_text } return out else: return "" def tmpl_add_comment_form(self, recID, uid, nickname, ln, msg, warnings, textual_msg=None, can_attach_files=False, user_is_subscribed_to_discussion=False, reply_to=None): """ Add form for comments @param recID: record id @param uid: user id @param ln: language @param msg: comment body contents for when refreshing due to warning, or when replying to a comment @param textual_msg: same as 'msg', but contains the textual version in case user cannot display FCKeditor @param warnings: list of warning tuples (warning_msg, color) @param can_attach_files: if user can upload attach file to record or not @param user_is_subscribed_to_discussion: True if user already receives new comments by email @param reply_to: the ID of the comment we are replying to. None if not replying @return html add comment form """ _ = gettext_set_language(ln) link_dic = { 'siteurl' : CFG_SITE_URL, 'module' : 'comments', 'function' : 'add', 'arguments' : 'ln=%s&amp;action=%s' % (ln, 'SUBMIT'), 'recID' : recID} if textual_msg is None: textual_msg = msg # FIXME a cleaner handling of nicknames is needed. if not nickname: (uid, nickname, display) = get_user_info(uid) if nickname: note = _("Note: Your nickname, %s, will be displayed as author of this comment.") % ('<i>' + nickname + '</i>') else: (uid, nickname, display) = get_user_info(uid) link = '<a href="%s/youraccount/edit">' % CFG_SITE_SECURE_URL note = _("Note: you have not %(x_url_open)sdefined your nickname%(x_url_close)s. %(x_nickname)s will be displayed as the author of this comment.") % \ {'x_url_open': link, 'x_url_close': '</a>', 'x_nickname': ' <br /><i>' + display + '</i>'} if not CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR: note += '<br />' + '&nbsp;'*10 + cgi.escape('You can use some HTML tags: <a href>, <strong>, <blockquote>, <br />, <p>, <em>, <ul>, <li>, <b>, <i>') #from invenio.search_engine import print_record #record_details = print_record(recID=recID, format='hb', ln=ln) warnings = self.tmpl_warnings(warnings, ln) # Prepare file upload settings. We must enable file upload in # the fckeditor + a simple file upload interface (independant from editor) file_upload_url = None simple_attach_file_interface = '' if isGuestUser(uid): simple_attach_file_interface = "<small><em>%s</em></small><br/>" % _("Once logged in, authorized users can also attach files.") if can_attach_files: # Note that files can be uploaded only when user is logged in #file_upload_url = '%s/record/%i/comments/attachments/put' % \ # (CFG_SITE_URL, recID) simple_attach_file_interface = ''' <div id="uploadcommentattachmentsinterface"> <small>%(attach_msg)s: <em>(%(nb_files_limit_msg)s. %(file_size_limit_msg)s)</em></small><br /> <input class="multi max-%(CFG_WEBCOMMENT_MAX_ATTACHED_FILES)s" type="file" name="commentattachment[]"/><br /> <noscript> <input type="file" name="commentattachment[]" /><br /> </noscript> </div> ''' % \ {'CFG_WEBCOMMENT_MAX_ATTACHED_FILES': CFG_WEBCOMMENT_MAX_ATTACHED_FILES, 'attach_msg': CFG_WEBCOMMENT_MAX_ATTACHED_FILES == 1 and _("Optionally, attach a file to this comment") or \ _("Optionally, attach files to this comment"), 'nb_files_limit_msg': _("Max one file") and CFG_WEBCOMMENT_MAX_ATTACHED_FILES == 1 or \ _("Max %i files") % CFG_WEBCOMMENT_MAX_ATTACHED_FILES, 'file_size_limit_msg': CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE > 0 and _("Max %(x_nb_bytes)s per file") % {'x_nb_bytes': (CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE < 1024*1024 and (str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/1024) + 'KB') or (str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/(1024*1024)) + 'MB'))} or ''} editor = get_html_text_editor(name='msg', content=msg, textual_content=textual_msg, width='100%', height='400px', enabled=CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR, file_upload_url=file_upload_url, toolbar_set = "WebComment") subscribe_to_discussion = '' if not user_is_subscribed_to_discussion: # Offer to subscribe to discussion subscribe_to_discussion = '<small><input type="checkbox" name="subscribe" id="subscribe"/><label for="subscribe">%s</label></small>' % _("Send me an email when a new comment is posted") form = """<div id="comment-write"><h2>%(add_comment)s</h2> %(editor)s <br /> %(simple_attach_file_interface)s <span class="reportabuse">%(note)s</span> <div class="submit-area"> %(subscribe_to_discussion)s<br /> <input class="adminbutton" type="submit" value="Add comment" /> %(reply_to)s </div> """ % {'note': note, 'record_label': _("Article") + ":", 'comment_label': _("Comment") + ":", 'add_comment': _('Add comment'), 'editor': editor, 'subscribe_to_discussion': subscribe_to_discussion, 'reply_to': reply_to and '<input type="hidden" name="comid" value="%s"/>' % reply_to or '', 'simple_attach_file_interface': simple_attach_file_interface} form_link = "%(siteurl)s/record/%(recID)s/comments/%(function)s?%(arguments)s" % link_dic form = self.create_write_comment_hiddenform(action=form_link, method="post", text=form, button='Add comment', enctype='multipart/form-data') form += '</div>' return warnings + form def tmpl_add_comment_form_with_ranking(self, recID, uid, nickname, ln, msg, score, note, warnings, textual_msg=None, show_title_p=False, can_attach_files=False): """ Add form for reviews @param recID: record id @param uid: user id @param ln: language @param msg: comment body contents for when refreshing due to warning @param textual_msg: the textual version of 'msg' when user cannot display FCKeditor @param score: review score @param note: review title @param warnings: list of warning tuples (warning_msg, color) @param show_title_p: if True, prefix the form with "Add Review" as title @param can_attach_files: if user can upload attach file to record or not @return: html add review form """ _ = gettext_set_language(ln) link_dic = { 'siteurl' : CFG_SITE_URL, 'module' : 'comments', 'function' : 'add', 'arguments' : 'ln=%s&amp;action=%s' % (ln, 'SUBMIT'), 'recID' : recID} warnings = self.tmpl_warnings(warnings, ln) if textual_msg is None: textual_msg = msg #from search_engine import print_record #record_details = print_record(recID=recID, format='hb', ln=ln) if nickname: note_label = _("Note: Your nickname, %s, will be displayed as the author of this review.") note_label %= ('<i>' + nickname + '</i>') else: (uid, nickname, display) = get_user_info(uid) link = '<a href="%s/youraccount/edit">' % CFG_SITE_SECURE_URL note_label = _("Note: you have not %(x_url_open)sdefined your nickname%(x_url_close)s. %(x_nickname)s will be displayed as the author of this comment.") % \ {'x_url_open': link, 'x_url_close': '</a>', 'x_nickname': ' <br /><i>' + display + '</i>'} selected0 = '' selected1 = '' selected2 = '' selected3 = '' selected4 = '' selected5 = '' if score == 0: selected0 = ' selected="selected"' elif score == 1: selected1 = ' selected="selected"' elif score == 2: selected2 = ' selected="selected"' elif score == 3: selected3 = ' selected="selected"' elif score == 4: selected4 = ' selected="selected"' elif score == 5: selected5 = ' selected="selected"' ## file_upload_url = None ## if can_attach_files: ## file_upload_url = '%s/record/%i/comments/attachments/put' % \ ## (CFG_SITE_URL, recID) editor = get_html_text_editor(name='msg', content=msg, textual_content=msg, width='90%', height='400px', enabled=CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR, # file_upload_url=file_upload_url, toolbar_set = "WebComment") form = """%(add_review)s <table style="width: 100%%"> <tr> <td style="padding-bottom: 10px;">%(rate_label)s: <select name=\"score\" size=\"1\"> <option value=\"0\"%(selected0)s>-%(select_label)s-</option> <option value=\"5\"%(selected5)s>***** (best)</option> <option value=\"4\"%(selected4)s>****</option> <option value=\"3\"%(selected3)s>***</option> <option value=\"2\"%(selected2)s>**</option> <option value=\"1\"%(selected1)s>* (worst)</option> </select> </td> </tr> <tr> <td>%(title_label)s:</td> </tr> <tr> <td style="padding-bottom: 10px;"> <input type="text" name="note" maxlength="250" style="width:90%%" value="%(note)s" /> </td> </tr> <tr> <td>%(write_label)s:</td> </tr> <tr> <td> %(editor)s </td> </tr> <tr> <td class="reportabuse">%(note_label)s</td></tr> </table> """ % {'article_label': _('Article'), 'rate_label': _("Rate this article"), 'select_label': _("Select a score"), 'title_label': _("Give a title to your review"), 'write_label': _("Write your review"), 'note_label': note_label, 'note' : note!='' and note or "", 'msg' : msg!='' and msg or "", #'record' : record_details 'add_review': show_title_p and ('<h2>'+_('Add review')+'</h2>') or '', 'selected0': selected0, 'selected1': selected1, 'selected2': selected2, 'selected3': selected3, 'selected4': selected4, 'selected5': selected5, 'editor': editor, } form_link = "%(siteurl)s/record/%(recID)s/reviews/%(function)s?%(arguments)s" % link_dic form = self.createhiddenform(action=form_link, method="post", text=form, button=_('Add Review')) return warnings + form def tmpl_add_comment_successful(self, recID, ln, reviews, warnings, success): """ @param recID: record id @param ln: language @return: html page of successfully added comment/review """ _ = gettext_set_language(ln) link_dic = { 'siteurl' : CFG_SITE_URL, 'module' : 'comments', 'function' : 'display', 'arguments' : 'ln=%s&amp;do=od' % ln, 'recID' : recID, 'discussion': reviews == 1 and 'reviews' or 'comments'} link = "%(siteurl)s/record/%(recID)s/%(discussion)s/%(function)s?%(arguments)s" % link_dic if warnings: out = self.tmpl_warnings(warnings, ln) + '<br /><br />' else: if reviews: out = _("Your review was successfully added.") + '<br /><br />' else: out = _("Your comment was successfully added.") + '<br /><br />' link += "#%s" % success out += '<a href="%s">' % link out += _('Back to record') + '</a>' return out def tmpl_create_multiple_actions_form(self, form_name="", form_action="", method="get", action_display={}, action_field_name="", button_label="", button_name="", content="", **hidden): """ Creates an HTML form with a multiple choice of actions and a button to select it. @param form_action: link to the receiver of the formular @param form_name: name of the HTML formular @param method: either 'GET' or 'POST' @param action_display: dictionary of actions. action is HTML name (name of action) display is the string provided in the popup @param action_field_name: html name of action field @param button_label: what's written on the button @param button_name: html name of the button @param content: what's inside te formular @param **hidden: dictionary of name/value pairs of hidden fields. """ output = """ <form action="%s" method="%s">""" % (form_action, method) output += """ <table> <tr> <td style="vertical-align: top" colspan="2"> """ output += content + '\n' for key in hidden.keys(): if type(hidden[key]) is list: for value in hidden[key]: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, value) else: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, hidden[key]) output += """ </td> </tr> <tr> <td style="text-align:right;">""" if type(action_display) is dict and len(action_display.keys()): output += """ <select name="%s">""" % action_field_name for (key, value) in action_display.items(): output += """ <option value="%s">%s</option>""" % (key, value) output += """ </select>""" output += """ </td> <td style="text-align:left;"> <input class="adminbutton" type="submit" value="%s" name="%s"/>""" % (button_label, button_name) output += """ </td> </tr> </table> </form>""" return output def tmpl_admin_index(self, ln): """ Index page """ # load the right message language _ = gettext_set_language(ln) out = '<ol>' if CFG_WEBCOMMENT_ALLOW_COMMENTS or CFG_WEBCOMMENT_ALLOW_REVIEWS: if CFG_WEBCOMMENT_ALLOW_COMMENTS: out += '<h3>Comments status</h3>' out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/hot?ln=%(ln)s&amp;comments=1">%(hot_cmt_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'hot_cmt_label': _("View most commented records")} out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/latest?ln=%(ln)s&amp;comments=1">%(latest_cmt_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'latest_cmt_label': _("View latest commented records")} out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/comments?ln=%(ln)s&amp;reviews=0">%(reported_cmt_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'reported_cmt_label': _("View all comments reported as abuse")} if CFG_WEBCOMMENT_ALLOW_REVIEWS: out += '<h3>Reviews status</h3>' out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/hot?ln=%(ln)s&amp;comments=0">%(hot_rev_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'hot_rev_label': _("View most reviewed records")} out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/latest?ln=%(ln)s&amp;comments=0">%(latest_rev_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'latest_rev_label': _("View latest reviewed records")} out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/comments?ln=%(ln)s&amp;reviews=1">%(reported_rev_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'reported_rev_label': _("View all reviews reported as abuse")} #<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/delete?ln=%(ln)s&amp;comid=-1">%(delete_label)s</a></li> out +=""" <h3>General</h3> <li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/users?ln=%(ln)s">%(view_users)s</a></li> <li><a href="%(siteurl)s/help/admin/webcomment-admin-guide">%(guide)s</a></li> """ % {'siteurl' : CFG_SITE_URL, #'delete_label': _("Delete/Undelete comment(s) or suppress abuse report(s)"), 'view_users': _("View all users who have been reported"), 'ln' : ln, 'guide' : _("Guide")} else: out += _("Comments and reviews are disabled") + '<br />' out += '</ol>' from invenio.bibrankadminlib import addadminbox return addadminbox('<b>%s</b>'% _("Menu"), [out]) def tmpl_admin_delete_form(self, ln, warnings): """ Display admin interface to fetch list of records to delete @param warnings: list of warning_tuples where warning_tuple is (warning_message, text_color) see tmpl_warnings, color is optional """ # load the right message language _ = gettext_set_language(ln) warnings = self.tmpl_warnings(warnings, ln) out = ''' <br /> %s<br /> <br />'''% _("Please enter the ID of the comment/review so that you can view it before deciding whether to delete it or not") form = ''' <table> <tr> <td>%s</td> <td><input type=text name="comid" size="10" maxlength="10" value="" /></td> </tr> <tr> <td><br /></td> <tr> </table> <br /> %s <br/> <br /> <table> <tr> <td>%s</td> <td><input type=text name="recid" size="10" maxlength="10" value="" /></td> </tr> <tr> <td><br /></td> <tr> </table> <br /> ''' % (_("Comment ID:"), _("Or enter a record ID to list all the associated comments/reviews:"), _("Record ID:")) form_link = "%s/admin/webcomment/webcommentadmin.py/delete?ln=%s" % (CFG_SITE_URL, ln) form = self.createhiddenform(action=form_link, method="get", text=form, button=_('View Comment')) return warnings + out + form def tmpl_admin_users(self, ln, users_data): """ @param users_data: tuple of ct, i.e. (ct, ct, ...) where ct is a tuple (total_number_reported, total_comments_reported, total_reviews_reported, total_nb_votes_yes_of_reported, total_nb_votes_total_of_reported, user_id, user_email, user_nickname) sorted by order of ct having highest total_number_reported """ _ = gettext_set_language(ln) u_reports = 0 u_comment_reports = 1 u_reviews_reports = 2 u_nb_votes_yes = 3 u_nb_votes_total = 4 u_uid = 5 u_email = 6 u_nickname = 7 if not users_data: return self.tmpl_warnings([(_("There have been no reports so far."), 'green')]) user_rows = "" for utuple in users_data: com_label = _("View all %s reported comments") % utuple[u_comment_reports] com_link = '''<a href="%s/admin/webcomment/webcommentadmin.py/comments?ln=%s&amp;uid=%s&amp;reviews=0">%s</a><br />''' % \ (CFG_SITE_URL, ln, utuple[u_uid], com_label) rev_label = _("View all %s reported reviews") % utuple[u_reviews_reports] rev_link = '''<a href="%s/admin/webcomment/webcommentadmin.py/comments?ln=%s&amp;uid=%s&amp;reviews=1">%s</a>''' % \ (CFG_SITE_URL, ln, utuple[u_uid], rev_label) if not utuple[u_nickname]: user_info = get_user_info(utuple[u_uid]) nickname = user_info[2] else: nickname = utuple[u_nickname] if CFG_WEBCOMMENT_ALLOW_REVIEWS: review_row = """ <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>""" review_row %= (utuple[u_nb_votes_yes], utuple[u_nb_votes_total] - utuple[u_nb_votes_yes], utuple[u_nb_votes_total]) else: review_row = '' user_rows += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(nickname)s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(email)s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(uid)s</td>%(review_row)s <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray; font-weight: bold;">%(reports)s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(com_link)s%(rev_link)s</td> </tr>""" % { 'nickname' : nickname, 'email' : utuple[u_email], 'uid' : utuple[u_uid], 'reports' : utuple[u_reports], 'review_row': review_row, 'siteurl' : CFG_SITE_URL, 'ln' : ln, 'com_link' : CFG_WEBCOMMENT_ALLOW_COMMENTS and com_link or "", 'rev_link' : CFG_WEBCOMMENT_ALLOW_REVIEWS and rev_link or "" } out = "<br />" out += _("Here is a list, sorted by total number of reports, of all users who have had a comment reported at least once.") out += """ <br /> <br /> <table class="admin_wvar" style="width: 100%%;"> <thead> <tr class="adminheaderleft"> <th>""" out += _("Nickname") + '</th>\n' out += '<th>' + _("Email") + '</th>\n' out += '<th>' + _("User ID") + '</th>\n' if CFG_WEBCOMMENT_ALLOW_REVIEWS > 0: out += '<th>' + _("Number positive votes") + '</th>\n' out += '<th>' + _("Number negative votes") + '</th>\n' out += '<th>' + _("Total number votes") + '</th>\n' out += '<th>' + _("Total number of reports") + '</th>\n' out += '<th>' + _("View all user's reported comments/reviews") + '</th>\n' out += """ </tr> </thead> <tbody>%s </tbody> </table> """ % user_rows return out def tmpl_admin_select_comment_checkbox(self, cmt_id): """ outputs a checkbox named "comidXX" where XX is cmt_id """ return '<input type="checkbox" name="comid%i" />' % int(cmt_id) def tmpl_admin_user_info(self, ln, nickname, uid, email): """ prepares informations about a user""" _ = gettext_set_language(ln) out = """ %(nickname_label)s: %(messaging)s<br /> %(uid_label)s: %(uid)i<br /> %(email_label)s: <a href="mailto:%(email)s">%(email)s</a>""" out %= {'nickname_label': _("Nickname"), 'messaging': self.create_messaging_link(uid, nickname, ln), 'uid_label': _("User ID"), 'uid': int(uid), 'email_label': _("Email"), 'email': email} return out def tmpl_admin_review_info(self, ln, reviews, nb_reports, cmt_id, rec_id, status): """ outputs information about a review """ _ = gettext_set_language(ln) if reviews: reported_label = _("This review has been reported %i times") else: reported_label = _("This comment has been reported %i times") reported_label %= int(nb_reports) out = """ %(reported_label)s<br /> <a href="%(siteurl)s/record/%(rec_id)i?ln=%(ln)s">%(rec_id_label)s</a><br /> %(cmt_id_label)s""" out %= {'reported_label': reported_label, 'rec_id_label': _("Record") + ' #' + str(rec_id), 'siteurl': CFG_SITE_URL, 'rec_id': int(rec_id), 'cmt_id_label': _("Comment") + ' #' + str(cmt_id), 'ln': ln} if status in ['dm', 'da']: out += '<br /><div style="color:red;">Marked as deleted</div>' return out def tmpl_admin_latest(self, ln, comment_data, comments, error, user_collections, collection): """ @param comment_data: same type of tuple as that which is return by webcommentadminlib.py/query_get_latest i.e. tuple (nickname, uid, date_creation, body, id) if latest comments or tuple (nickname, uid, date_creation, body, star_score, id) if latest reviews """ _ = gettext_set_language(ln) out = """ <script type='text/javascript'> function collectionChange() { document.collection_form.submit(); } </script> """ out += '<form method="get" name="collection_form" action="%s/admin/webcomment/webcommentadmin.py/latest?ln=%s&comments=%s">' % (CFG_SITE_URL, ln, comments) out += '<input type="hidden" name="ln" value=%s>' % ln out += '<input type="hidden" name="comments" value=%s>' % comments out += '<div> Filter by collection: <select name="collection" onchange="javascript:collectionChange();">' for collection_name in user_collections: if collection_name == collection: out += '<option "SELECTED" value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} else: out += '<option value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} out += '</select></div></form><br />' if error == 1: out += "<i>User is not authorized to view such collection.</i><br />" return out elif error == 2: out += "<i>There are no %s for this collection.</i><br />" % (comments and 'comments' or 'reviews') return out out += """ <ol> """ for (cmt_tuple, meta_data) in comment_data: bibrec_id = meta_data[3] content = format_record(bibrec_id, "hs") if not comments: out += """ <li> %(content)s <br/> <span class="moreinfo"> <a class="moreinfo" href=%(comment_url)s> reviewed by %(user)s</a> (%(stars)s) \"%(body)s\" on <i> %(date)s </i></li> </span> <br/> """ % {'content': content, 'comment_url': CFG_SITE_URL + '/record/' + str(bibrec_id) + '/reviews', 'user':cmt_tuple[0] , 'stars': '*' * int(cmt_tuple[4]) , 'body': cmt_tuple[3][:20] + '...', 'date': cmt_tuple[2]} else: out += """ <li> %(content)s <br/> <span class="moreinfo"> <a class="moreinfo" href=%(comment_url)s> commented by %(user)s</a>, \"%(body)s\" on <i> %(date)s </i></li> </span> <br/> """ % {'content': content, 'comment_url': CFG_SITE_URL + '/record/' + str(bibrec_id) + '/comments', 'user':cmt_tuple[0] , 'body': cmt_tuple[3][:20] + '...', 'date': cmt_tuple[2]} out += """</ol>""" return out def tmpl_admin_hot(self, ln, comment_data, comments, error, user_collections, collection): """ @param comment_data: same type of tuple as that which is return by webcommentadminlib.py/query_get_hot i.e. tuple (id_bibrec, date_last_comment, users, count) """ _ = gettext_set_language(ln) out = """ <script type='text/javascript'> function collectionChange() { document.collection_form.submit(); } </script> """ out += '<form method="get" name="collection_form" action="%s/admin/webcomment/webcommentadmin.py/hot?ln=%s&comments=%s">' % (CFG_SITE_URL, ln, comments) out += '<input type="hidden" name="ln" value=%s>' % ln out += '<input type="hidden" name="comments" value=%s>' % comments out += '<div> Filter by collection: <select name="collection" onchange="javascript:collectionChange();">' for collection_name in user_collections: if collection_name == collection: out += '<option "SELECTED" value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} else: out += '<option value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} out += '</select></div></form><br />' if error == 1: out += "<i>User is not authorized to view such collection.</i><br />" return out elif error == 2: out += "<i>There are no %s for this collection.</i><br />" % (comments and 'comments' or 'reviews') return out for cmt_tuple in comment_data: bibrec_id = cmt_tuple[0] content = format_record(bibrec_id, "hs") last_comment_date = cmt_tuple[1] total_users = cmt_tuple[2] total_comments = cmt_tuple[3] if comments: comment_url = CFG_SITE_URL + '/record/' + str(bibrec_id) + '/comments' str_comment = int(total_comments) > 1 and 'comments' or 'comment' else: comment_url = CFG_SITE_URL + '/record/' + str(bibrec_id) + '/reviews' str_comment = int(total_comments) > 1 and 'reviews' or 'review' out += """ <li> %(content)s <br/> <span class="moreinfo"> <a class="moreinfo" href=%(comment_url)s> %(total_comments)s %(str_comment)s</a> (%(total_users)s %(user)s), latest on <i> %(last_comment_date)s </i></li> </span> <br/> """ % {'content': content, 'comment_url': comment_url , 'total_comments': total_comments, 'str_comment': str_comment, 'total_users': total_users, 'user': int(total_users) > 1 and 'users' or 'user', 'last_comment_date': last_comment_date} out += """</ol>""" return out def tmpl_admin_comments(self, ln, uid, comID, recID, comment_data, reviews, error, user_collections, collection): """ @param comment_data: same type of tuple as that which is returned by webcomment.py/query_retrieve_comments_or_remarks i.e. tuple of comment where comment is tuple (nickname, date_creation, body, id) if ranking disabled or tuple (nickname, date_creation, body, nb_votes_yes, nb_votes_total, star_score, title, id) """ _ = gettext_set_language(ln) coll_form = """ <script type='text/javascript'> function collectionChange() { document.collection_form.submit(); } </script> """ coll_form += '<form method="get" name="collection_form" action="%s/admin/webcomment/webcommentadmin.py/comments?ln=%s&reviews=%s">' % (CFG_SITE_URL, ln, reviews) coll_form += '<input type="hidden" name="ln" value=%s>' % ln coll_form += '<input type="hidden" name="reviews" value=%s>' % reviews coll_form += '<div> Filter by collection: <select name="collection" onchange="javascript:collectionChange();">' for collection_name in user_collections: if collection_name == collection: coll_form += '<option "SELECTED" value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} else: coll_form += '<option value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} coll_form += '</select></div></form><br />' if error == 1: coll_form += "<i>User is not authorized to view such collection.</i><br />" return coll_form elif error == 2: coll_form += "<i>There are no %s for this collection.</i><br />" % (reviews and 'reviews' or 'comments') return coll_form comments = [] comments_info = [] checkboxes = [] users = [] for (cmt_tuple, meta_data) in comment_data: if reviews: comments.append(self.tmpl_get_comment_with_ranking(None,#request object ln, cmt_tuple[0],#nickname cmt_tuple[1],#userid cmt_tuple[2],#date_creation cmt_tuple[3],#body cmt_tuple[9],#status 0, cmt_tuple[5],#nb_votes_total cmt_tuple[4],#nb_votes_yes cmt_tuple[6],#star_score cmt_tuple[7]))#title else: comments.append(self.tmpl_get_comment_without_ranking(None,#request object ln, cmt_tuple[0],#nickname cmt_tuple[1],#userid cmt_tuple[2],#date_creation cmt_tuple[3],#body cmt_tuple[5],#status 0, None, #reply_link None, #report_link None, #undelete_link None)) #delete_links users.append(self.tmpl_admin_user_info(ln, meta_data[0], #nickname meta_data[1], #uid meta_data[2]))#email if reviews: status = cmt_tuple[9] else: status = cmt_tuple[5] comments_info.append(self.tmpl_admin_review_info(ln, reviews, meta_data[5], # nb abuse reports meta_data[3], # cmt_id meta_data[4], # rec_id status)) # status checkboxes.append(self.tmpl_admin_select_comment_checkbox(meta_data[3])) form_link = "%s/admin/webcomment/webcommentadmin.py/del_com?ln=%s" % (CFG_SITE_URL, ln) out = """ <table class="admin_wvar" style="width:100%%;"> <thead> <tr class="adminheaderleft"> <th>%(review_label)s</th> <th>%(written_by_label)s</th> <th>%(review_info_label)s</th> <th>%(select_label)s</th> </tr> </thead> <tbody>""" % {'review_label': reviews and _("Review") or _("Comment"), 'written_by_label': _("Written by"), 'review_info_label': _("General informations"), 'select_label': _("Select")} for i in range (0, len(comments)): out += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintd" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> </tr>""" % (comments[i], users[i], comments_info[i], checkboxes[i]) out += """ </tbody> </table>""" if reviews: action_display = { 'delete': _('Delete selected reviews'), 'unreport': _('Suppress selected abuse report'), 'undelete': _('Undelete selected reviews') } else: action_display = { 'undelete': _('Undelete selected comments'), 'delete': _('Delete selected comments'), 'unreport': _('Suppress selected abuse report') } form = self.tmpl_create_multiple_actions_form(form_name="admin_comment", form_action=form_link, method="post", action_display=action_display, action_field_name='action', button_label=_("OK"), button_name="okbutton", content=out) if uid > 0: header = '<br />' if reviews: header += _("Here are the reported reviews of user %s") % uid else: header += _("Here are the reported comments of user %s") % uid header += '<br /><br />' if comID > 0 and recID <= 0 and uid <= 0: if reviews: header = '<br />' +_("Here is review %s")% comID + '<br /><br />' else: header = '<br />' +_("Here is comment %s")% comID + '<br /><br />' if uid > 0 and comID > 0 and recID <= 0: if reviews: header = '<br />' + _("Here is review %(x_cmtID)s written by user %(x_user)s") % {'x_cmtID': comID, 'x_user': uid} else: header = '<br />' + _("Here is comment %(x_cmtID)s written by user %(x_user)s") % {'x_cmtID': comID, 'x_user': uid} header += '<br/ ><br />' if comID <= 0 and recID <= 0 and uid <= 0: header = '<br />' if reviews: header += _("Here are all reported reviews sorted by the most reported") else: header += _("Here are all reported comments sorted by the most reported") header += "<br /><br />" elif recID > 0: header = '<br />' if reviews: header += _("Here are all reviews for record %i, sorted by the most reported" % recID) header += '<br /><a href="%s/admin/webcomment/webcommentadmin.py/delete?comid=&recid=%s&amp;reviews=0">%s</a>' % (CFG_SITE_URL, recID, _("Show comments")) else: header += _("Here are all comments for record %i, sorted by the most reported" % recID) header += '<br /><a href="%s/admin/webcomment/webcommentadmin.py/delete?comid=&recid=%s&amp;reviews=1">%s</a>' % (CFG_SITE_URL, recID, _("Show reviews")) header += "<br /><br />" return coll_form + header + form def tmpl_admin_del_com(self, del_res, ln=CFG_SITE_LANG): """ @param del_res: list of the following tuple (comment_id, was_successfully_deleted), was_successfully_deleted is boolean (0=false, >0=true """ _ = gettext_set_language(ln) table_rows = '' for deltuple in del_res: table_rows += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> </tr>""" % (deltuple[0], deltuple[1]>0 and _("Yes") or "<span class=\"important\">" +_("No") + "</span>") out = """ <table class="admin_wvar"> <tr class="adminheaderleft"> <td style="padding-right:10px;">%s</td> <td>%s</td> </tr>%s <table>""" % (_("comment ID"), _("successfully deleted"), table_rows) return out def tmpl_admin_undel_com(self, del_res, ln=CFG_SITE_LANG): """ @param del_res: list of the following tuple (comment_id, was_successfully_undeleted), was_successfully_undeleted is boolean (0=false, >0=true """ _ = gettext_set_language(ln) table_rows = '' for deltuple in del_res: table_rows += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> </tr>""" % (deltuple[0], deltuple[1]>0 and _("Yes") or "<span class=\"important\">" +_("No") + "</span>") out = """ <table class="admin_wvar"> <tr class="adminheaderleft"> <td style="padding-right:10px;">%s</td> <td>%s</td> </tr>%s <table>""" % (_("comment ID"), _("successfully undeleted"), table_rows) return out def tmpl_admin_suppress_abuse_report(self, del_res, ln=CFG_SITE_LANG): """ @param del_res: list of the following tuple (comment_id, was_successfully_deleted), was_successfully_deleted is boolean (0=false, >0=true """ _ = gettext_set_language(ln) table_rows = '' for deltuple in del_res: table_rows += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> </tr>""" % (deltuple[0], deltuple[1]>0 and _("Yes") or "<span class=\"important\">" +_("No") + "</span>") out = """ <table class="admin_wvar"> <tr class="adminheaderleft"> <td style ="padding-right: 10px;">%s</td> <td>%s</td> </tr>%s <table>""" % (_("comment ID"), _("successfully suppressed abuse report"), table_rows) return out def tmpl_mini_review(self, recID, ln=CFG_SITE_LANG, action='SUBMIT', avg_score=0, nb_comments_total=0): """Display the mini version of reviews (only the grading part)""" _ = gettext_set_language(ln) url = '%s/record/%s/reviews/add?ln=%s&amp;action=%s' % (CFG_SITE_URL, recID, ln, action) if avg_score > 0: score = _("Average review score: %(x_nb_score)s based on %(x_nb_reviews)s reviews") % \ {'x_nb_score': '<b>%.1f</b>' % avg_score, 'x_nb_reviews': nb_comments_total} else: score = '(' +_("Not yet reviewed") + ')' if avg_score == 5: s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'full', 'full' elif avg_score >= 4.5: s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'full', 'half' elif avg_score >= 4: s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'full', '' elif avg_score >= 3.5: s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'half', '' elif avg_score >= 3: s1, s2, s3, s4, s5 = 'full', 'full', 'full', '', '' elif avg_score >= 2.5: s1, s2, s3, s4, s5 = 'full', 'full', 'half', '', '' elif avg_score >= 2: s1, s2, s3, s4, s5 = 'full', 'full', '', '', '' elif avg_score >= 1.5: s1, s2, s3, s4, s5 = 'full', 'half', '', '', '' elif avg_score == 1: s1, s2, s3, s4, s5 = 'full', '', '', '', '' else: s1, s2, s3, s4, s5 = '', '', '', '', '' out = ''' <small class="detailedRecordActions">%(rate)s:</small><br /><br /> <div style="margin:auto;width:160px;"> <span style="display:none;">Rate this document:</span> <div class="star %(s1)s" ><a href="%(url)s&amp;score=1">1</a> <div class="star %(s2)s" ><a href="%(url)s&amp;score=2">2</a> <div class="star %(s3)s" ><a href="%(url)s&amp;score=3">3</a> <div class="star %(s4)s" ><a href="%(url)s&amp;score=4">4</a> <div class="star %(s5)s" ><a href="%(url)s&amp;score=5">5</a></div></div></div></div></div> <div style="clear:both">&nbsp;</div> </div> <small>%(score)s</small> ''' % {'url': url, 'score': score, 'rate': _("Rate this document"), 's1': s1, 's2': s2, 's3': s3, 's4': s4, 's5': s5 } return out def tmpl_email_new_comment_header(self, recID, title, reviews, comID, report_numbers, can_unsubscribe=True, ln=CFG_SITE_LANG, uid=-1): """ Prints the email header used to notify subscribers that a new comment/review was added. @param recid: the ID of the commented/reviewed record @param title: the title of the commented/reviewed record @param reviews: True if it is a review, else if a comment @param comID: the comment ID @param report_numbers: the report number(s) of the record @param can_unsubscribe: True if user can unsubscribe from alert @param ln: language """ # load the right message language _ = gettext_set_language(ln) user_info = collect_user_info(uid) out = _("Hello:") + '\n\n' + \ (reviews and _("The following review was sent to %(CFG_SITE_NAME)s by %(user_nickname)s:") or \ _("The following comment was sent to %(CFG_SITE_NAME)s by %(user_nickname)s:")) % \ {'CFG_SITE_NAME': CFG_SITE_NAME, 'user_nickname': user_info['nickname']} out += '\n(<%s>)' % (CFG_SITE_URL + '/record/' + str(recID)) out += '\n\n\n' return out def tmpl_email_new_comment_footer(self, recID, title, reviews, comID, report_numbers, can_unsubscribe=True, ln=CFG_SITE_LANG): """ Prints the email footer used to notify subscribers that a new comment/review was added. @param recid: the ID of the commented/reviewed record @param title: the title of the commented/reviewed record @param reviews: True if it is a review, else if a comment @param comID: the comment ID @param report_numbers: the report number(s) of the record @param can_unsubscribe: True if user can unsubscribe from alert @param ln: language """ # load the right message language _ = gettext_set_language(ln) out = '\n\n-- \n' out += _("This is an automatic message, please don't reply to it.") out += '\n' out += _("To post another comment, go to <%(x_url)s> instead.") % \ {'x_url': CFG_SITE_URL + '/record/' + str(recID) + \ (reviews and '/reviews' or '/comments') + '/add'} out += '\n' if not reviews: out += _("To specifically reply to this comment, go to <%(x_url)s>") % \ {'x_url': CFG_SITE_URL + '/record/' + str(recID) + \ '/comments/add?action=REPLY&comid=' + str(comID)} out += '\n' if can_unsubscribe: out += _("To unsubscribe from this discussion, go to <%(x_url)s>") % \ {'x_url': CFG_SITE_URL + '/record/' + str(recID) + \ '/comments/unsubscribe'} out += '\n' out += _("For any question, please use <%(CFG_SITE_SUPPORT_EMAIL)s>") % \ {'CFG_SITE_SUPPORT_EMAIL': CFG_SITE_SUPPORT_EMAIL} return out def tmpl_email_new_comment_admin(self, recID): """ Prints the record information used in the email to notify the system administrator that a new comment has been posted. @param recID: the ID of the commented/reviewed record """ out = "" title = get_fieldvalues(recID, "245__a") authors = ', '.join(get_fieldvalues(recID, "100__a") + get_fieldvalues(recID, "700__a")) #res_author = "" #res_rep_num = "" #for author in authors: # res_author = res_author + ' ' + author dates = get_fieldvalues(recID, "260__c") report_nums = get_fieldvalues(recID, "037__a") report_nums += get_fieldvalues(recID, "088__a") report_nums = ', '.join(report_nums) #for rep_num in report_nums: # res_rep_num = res_rep_num + ', ' + rep_num out += " Title = %s \n" % (title and title[0] or "No Title") out += " Authors = %s \n" % authors if dates: out += " Date = %s \n" % dates[0] out += " Report number = %s" % report_nums return out
kaplun/Invenio-OpenAIRE
modules/webcomment/lib/webcomment_templates.py
Python
gpl-2.0
109,494
#!/usr/bin/python import os, subprocess amsDecode = "/usr/local/bin/amsDecode" path = "/usr/local/bin" specDataFile = "specData.csv" f = open("processFile.log", "w") if os.path.exists(specDataFile): os.remove(specDataFile) for fileName in os.listdir('.'): if fileName.endswith('.bin'): #print 'file :' + fileName cmnd = [amsDecode, fileName, "-t -95", "-b", "68", "468" ] subprocess.call(cmnd,stdout=f) f.close
jennyb/amsDecode
processBinFiles.py
Python
gpl-2.0
451
#!/usr/bin/env python # -*- coding: utf-8 -*- # # vertexdomain.py # # Copyright 2016 notna <[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. # #
not-na/peng3d
docs/pyglet/graphics/vertexdomain.py
Python
gpl-2.0
851
#!/usr/bin/python3 from distutils.core import setup setup(name='PySh', version='0.0.1', py_modules=['pysh'], description="A tiny interface to intuitively access shell commands.", author="Bede Kelly", author_email="[email protected]", url="https://github.com/bedekelly/pysh", provides=['pysh'])
bedekelly/pysh
setup.py
Python
gpl-2.0
340
# ------------------------------------------------------------------------------------------------ # Software: Stem Applier (staply) # Description: Applies inflections to stem morphemes # Version: 0.0.1a # Module: Main # # Author: Frederic Bayer # Email: [email protected] # Institution: University of Aberdeen # # Copyright: (c) Frederic S. Bayer 2015 # # 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-13SA. # ----------------------------------------------------------------------------------------------- __author__ = 'Frederic Bayer'
fsbayer/staply
staply/__init__.py
Python
gpl-2.0
1,227
from socket import * import sys clientSocket = socket(AF_INET, SOCK_STREAM) #creates socket server_address = ('127.0.0.1', 80)#create connection at this given port print >>sys.stderr, 'CONNECTING TO %s AT PORT %s' % server_address clientSocket.connect(server_address)#connect to server at given address filename=raw_input("ENTER THE FILENAME: ") f = open(filename[0:]) outputdata = f.read()#read the input file into variable print "HTML CODE OF THE GIVEN FILE:", outputdata #display the html code of the file clientSocket.close() #close the connection
HarmeetDhillon/Socket-Programming
Client.py
Python
gpl-2.0
561
import contextvars import gettext import os from telebot.asyncio_handler_backends import BaseMiddleware try: from babel.support import LazyProxy babel_imported = True except ImportError: babel_imported = False class I18N(BaseMiddleware): """ This middleware provides high-level tool for internationalization It is based on gettext util. """ context_lang = contextvars.ContextVar('language', default=None) def __init__(self, translations_path, domain_name: str): super().__init__() self.update_types = self.process_update_types() self.path = translations_path self.domain = domain_name self.translations = self.find_translations() @property def available_translations(self): return list(self.translations) def gettext(self, text: str, lang: str = None): """ Singular translations """ if lang is None: lang = self.context_lang.get() if lang not in self.translations: return text translator = self.translations[lang] return translator.gettext(text) def ngettext(self, singular: str, plural: str, lang: str = None, n=1): """ Plural translations """ if lang is None: lang = self.context_lang.get() if lang not in self.translations: if n == 1: return singular return plural translator = self.translations[lang] return translator.ngettext(singular, plural, n) def lazy_gettext(self, text: str, lang: str = None): if not babel_imported: raise RuntimeError('babel module is not imported. Check that you installed it.') return LazyProxy(self.gettext, text, lang, enable_cache=False) def lazy_ngettext(self, singular: str, plural: str, lang: str = None, n=1): if not babel_imported: raise RuntimeError('babel module is not imported. Check that you installed it.') return LazyProxy(self.ngettext, singular, plural, lang, n, enable_cache=False) async def get_user_language(self, obj): """ You need to override this method and return user language """ raise NotImplementedError def process_update_types(self) -> list: """ You need to override this method and return any update types which you want to be processed """ raise NotImplementedError async def pre_process(self, message, data): """ context language variable will be set each time when update from 'process_update_types' comes value is the result of 'get_user_language' method """ self.context_lang.set(await self.get_user_language(obj=message)) async def post_process(self, message, data, exception): pass def find_translations(self): """ Looks for translations with passed 'domain' in passed 'path' """ if not os.path.exists(self.path): raise RuntimeError(f"Translations directory by path: {self.path!r} was not found") result = {} for name in os.listdir(self.path): translations_path = os.path.join(self.path, name, 'LC_MESSAGES') if not os.path.isdir(translations_path): continue po_file = os.path.join(translations_path, self.domain + '.po') mo_file = po_file[:-2] + 'mo' if os.path.isfile(po_file) and not os.path.isfile(mo_file): raise FileNotFoundError(f"Translations for: {name!r} were not compiled!") with open(mo_file, 'rb') as file: result[name] = gettext.GNUTranslations(file) return result
eternnoir/pyTelegramBotAPI
examples/asynchronous_telebot/middleware/i18n_middleware_example/i18n_base_midddleware.py
Python
gpl-2.0
3,751
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> import bpy from bpy.types import Header, Menu, Panel from bpy.app.translations import pgettext_iface as iface_ from bpy.app.translations import contexts as i18n_contexts def opengl_lamp_buttons(column, lamp): split = column.row() split.prop(lamp, "use", text="", icon='OUTLINER_OB_LAMP' if lamp.use else 'LAMP_DATA') col = split.column() col.active = lamp.use row = col.row() row.label(text="Diffuse:") row.prop(lamp, "diffuse_color", text="") row = col.row() row.label(text="Specular:") row.prop(lamp, "specular_color", text="") col = split.column() col.active = lamp.use col.prop(lamp, "direction", text="") class USERPREF_HT_header(Header): bl_space_type = 'USER_PREFERENCES' def draw(self, context): layout = self.layout layout.template_header() userpref = context.user_preferences layout.operator_context = 'EXEC_AREA' layout.operator("wm.save_userpref") layout.operator_context = 'INVOKE_DEFAULT' if userpref.active_section == 'INPUT': layout.operator("wm.keyconfig_import") layout.operator("wm.keyconfig_export") elif userpref.active_section == 'ADDONS': layout.operator("wm.addon_install", icon='FILESEL') layout.operator("wm.addon_refresh", icon='FILE_REFRESH') layout.menu("USERPREF_MT_addons_online_resources") elif userpref.active_section == 'THEMES': layout.operator("ui.reset_default_theme") layout.operator("wm.theme_install") class USERPREF_PT_tabs(Panel): bl_label = "" bl_space_type = 'USER_PREFERENCES' bl_region_type = 'WINDOW' bl_options = {'HIDE_HEADER'} def draw(self, context): layout = self.layout userpref = context.user_preferences layout.prop(userpref, "active_section", expand=True) class USERPREF_MT_interaction_presets(Menu): bl_label = "Presets" preset_subdir = "interaction" preset_operator = "script.execute_preset" draw = Menu.draw_preset class USERPREF_MT_appconfigs(Menu): bl_label = "AppPresets" preset_subdir = "keyconfig" preset_operator = "wm.appconfig_activate" def draw(self, context): self.layout.operator("wm.appconfig_default", text="Blender (default)") # now draw the presets Menu.draw_preset(self, context) class USERPREF_MT_splash(Menu): bl_label = "Splash" def draw(self, context): layout = self.layout split = layout.split() row = split.row() row.label("") row = split.row() row.label("Interaction:") text = bpy.path.display_name(context.window_manager.keyconfigs.active.name) if not text: text = "Blender (default)" row.menu("USERPREF_MT_appconfigs", text=text) # only for addons class USERPREF_MT_splash_footer(Menu): bl_label = "" def draw(self, context): pass class USERPREF_PT_interface(Panel): bl_space_type = 'USER_PREFERENCES' bl_label = "Interface" bl_region_type = 'WINDOW' bl_options = {'HIDE_HEADER'} @classmethod def poll(cls, context): userpref = context.user_preferences return (userpref.active_section == 'INTERFACE') def draw(self, context): import sys layout = self.layout userpref = context.user_preferences view = userpref.view row = layout.row() col = row.column() col.label(text="Display:") col.prop(view, "show_tooltips") col.prop(view, "show_tooltips_python") col.prop(view, "show_object_info", text="Object Info") col.prop(view, "show_large_cursors") col.prop(view, "show_view_name", text="View Name") col.prop(view, "show_playback_fps", text="Playback FPS") col.prop(view, "use_global_scene") col.prop(view, "object_origin_size") col.separator() col.separator() col.separator() col.prop(view, "show_mini_axis", text="Display Mini Axis") sub = col.column() sub.active = view.show_mini_axis sub.prop(view, "mini_axis_size", text="Size") sub.prop(view, "mini_axis_brightness", text="Brightness") col.separator() if sys.platform[:3] == "win": col.label("Warnings") col.prop(view, "use_quit_dialog") row.separator() row.separator() col = row.column() col.label(text="View Manipulation:") col.prop(view, "use_mouse_depth_cursor") col.prop(view, "use_mouse_depth_navigate") col.prop(view, "use_zoom_to_mouse") col.prop(view, "use_rotate_around_active") col.prop(view, "use_global_pivot") col.prop(view, "use_camera_lock_parent") col.separator() col.prop(view, "use_auto_perspective") col.prop(view, "smooth_view") col.prop(view, "rotation_angle") col.separator() col.separator() col.label(text="2D Viewports:") col.prop(view, "view2d_grid_spacing_min", text="Minimum Grid Spacing") col.prop(view, "timecode_style") col.prop(view, "view_frame_type") if (view.view_frame_type == 'SECONDS'): col.prop(view, "view_frame_seconds") elif (view.view_frame_type == 'KEYFRAMES'): col.prop(view, "view_frame_keyframes") row.separator() row.separator() col = row.column() #Toolbox doesn't exist yet #col.label(text="Toolbox:") #col.prop(view, "show_column_layout") #col.label(text="Open Toolbox Delay:") #col.prop(view, "open_left_mouse_delay", text="Hold LMB") #col.prop(view, "open_right_mouse_delay", text="Hold RMB") col.prop(view, "show_manipulator") sub = col.column() sub.active = view.show_manipulator sub.prop(view, "manipulator_size", text="Size") sub.prop(view, "manipulator_handle_size", text="Handle Size") sub.prop(view, "manipulator_hotspot", text="Hotspot") col.separator() col.separator() col.separator() col.label(text="Menus:") col.prop(view, "use_mouse_over_open") sub = col.column() sub.active = view.use_mouse_over_open sub.prop(view, "open_toplevel_delay", text="Top Level") sub.prop(view, "open_sublevel_delay", text="Sub Level") col.separator() col.label(text="Pie Menus:") sub = col.column(align=True) sub.prop(view, "pie_animation_timeout") sub.prop(view, "pie_initial_timeout") sub.prop(view, "pie_menu_radius") sub.prop(view, "pie_menu_threshold") sub.prop(view, "pie_menu_confirm") col.separator() col.separator() col.separator() col.prop(view, "show_splash") class USERPREF_PT_edit(Panel): bl_space_type = 'USER_PREFERENCES' bl_label = "Edit" bl_region_type = 'WINDOW' bl_options = {'HIDE_HEADER'} @classmethod def poll(cls, context): userpref = context.user_preferences return (userpref.active_section == 'EDITING') def draw(self, context): layout = self.layout userpref = context.user_preferences edit = userpref.edit row = layout.row() col = row.column() col.label(text="Link Materials To:") col.prop(edit, "material_link", text="") col.separator() col.separator() col.separator() col.label(text="New Objects:") col.prop(edit, "use_enter_edit_mode") col.label(text="Align To:") col.prop(edit, "object_align", text="") col.separator() col.separator() col.separator() col.label(text="Undo:") col.prop(edit, "use_global_undo") col.prop(edit, "undo_steps", text="Steps") col.prop(edit, "undo_memory_limit", text="Memory Limit") row.separator() row.separator() col = row.column() col.label(text="Grease Pencil:") col.prop(edit, "grease_pencil_eraser_radius", text="Eraser Radius") col.separator() col.prop(edit, "grease_pencil_manhattan_distance", text="Manhattan Distance") col.prop(edit, "grease_pencil_euclidean_distance", text="Euclidean Distance") col.separator() col.prop(edit, "grease_pencil_default_color", text="Default Color") col.separator() col.prop(edit, "use_grease_pencil_simplify_stroke", text="Simplify Stroke") col.separator() col.separator() col.separator() col.separator() col.label(text="Playback:") col.prop(edit, "use_negative_frames") col.separator() col.separator() col.separator() col.label(text="Node Editor:") col.prop(edit, "node_margin") col.label(text="Animation Editors:") col.prop(edit, "fcurve_unselected_alpha", text="F-Curve Visibility") row.separator() row.separator() col = row.column() col.label(text="Keyframing:") col.prop(edit, "use_visual_keying") col.prop(edit, "use_keyframe_insert_needed", text="Only Insert Needed") col.separator() col.prop(edit, "use_auto_keying", text="Auto Keyframing:") col.prop(edit, "use_auto_keying_warning") sub = col.column() #~ sub.active = edit.use_keyframe_insert_auto # incorrect, time-line can enable sub.prop(edit, "use_keyframe_insert_available", text="Only Insert Available") col.separator() col.label(text="New F-Curve Defaults:") col.prop(edit, "keyframe_new_interpolation_type", text="Interpolation") col.prop(edit, "keyframe_new_handle_type", text="Handles") col.prop(edit, "use_insertkey_xyz_to_rgb", text="XYZ to RGB") col.separator() col.separator() col.separator() col.label(text="Transform:") col.prop(edit, "use_drag_immediately") row.separator() row.separator() col = row.column() col.prop(edit, "sculpt_paint_overlay_color", text="Sculpt Overlay Color") col.separator() col.separator() col.separator() col.label(text="Duplicate Data:") col.prop(edit, "use_duplicate_mesh", text="Mesh") col.prop(edit, "use_duplicate_surface", text="Surface") col.prop(edit, "use_duplicate_curve", text="Curve") col.prop(edit, "use_duplicate_text", text="Text") col.prop(edit, "use_duplicate_metaball", text="Metaball") col.prop(edit, "use_duplicate_armature", text="Armature") col.prop(edit, "use_duplicate_lamp", text="Lamp") col.prop(edit, "use_duplicate_material", text="Material") col.prop(edit, "use_duplicate_texture", text="Texture") #col.prop(edit, "use_duplicate_fcurve", text="F-Curve") col.prop(edit, "use_duplicate_action", text="Action") col.prop(edit, "use_duplicate_particle", text="Particle") class USERPREF_PT_system(Panel): bl_space_type = 'USER_PREFERENCES' bl_label = "System" bl_region_type = 'WINDOW' bl_options = {'HIDE_HEADER'} @classmethod def poll(cls, context): userpref = context.user_preferences return (userpref.active_section == 'SYSTEM') def draw(self, context): import sys layout = self.layout userpref = context.user_preferences system = userpref.system split = layout.split() # 1. Column column = split.column() colsplit = column.split(percentage=0.85) col = colsplit.column() col.label(text="General:") col.prop(system, "dpi") col.label("Virtual Pixel Mode:") col.prop(system, "virtual_pixel_mode", text="") col.separator() col.prop(system, "frame_server_port") col.prop(system, "scrollback", text="Console Scrollback") col.separator() col.label(text="Sound:") col.row().prop(system, "audio_device", expand=False) sub = col.column() sub.active = system.audio_device != 'NONE' and system.audio_device != 'Null' #sub.prop(system, "use_preview_images") sub.prop(system, "audio_channels", text="Channels") sub.prop(system, "audio_mixing_buffer", text="Mixing Buffer") sub.prop(system, "audio_sample_rate", text="Sample Rate") sub.prop(system, "audio_sample_format", text="Sample Format") col.separator() col.label(text="Screencast:") col.prop(system, "screencast_fps") col.prop(system, "screencast_wait_time") col.separator() if userpref.addons.find('cycles') != -1: userpref.addons['cycles'].preferences.draw_impl(col, context) if hasattr(system, "opensubdiv_compute_type"): col.label(text="OpenSubdiv compute:") col.row().prop(system, "opensubdiv_compute_type", text="") # 2. Column column = split.column() colsplit = column.split(percentage=0.85) col = colsplit.column() col.label(text="OpenGL:") col.prop(system, "gl_clip_alpha", slider=True) col.prop(system, "use_mipmaps") col.prop(system, "use_gpu_mipmap") col.prop(system, "use_16bit_textures") col.separator() col.label(text="Selection") col.prop(system, "select_method", text="") col.separator() col.label(text="Anisotropic Filtering") col.prop(system, "anisotropic_filter", text="") col.separator() col.label(text="Window Draw Method:") col.prop(system, "window_draw_method", text="") col.prop(system, "multi_sample", text="") if sys.platform == "linux" and system.multi_sample != 'NONE': col.label(text="Might fail for Mesh editing selection!") col.separator() col.prop(system, "use_region_overlap") col.separator() col.label(text="Text Draw Options:") col.prop(system, "use_text_antialiasing") col.separator() col.label(text="Textures:") col.prop(system, "gl_texture_limit", text="Limit Size") col.prop(system, "texture_time_out", text="Time Out") col.prop(system, "texture_collection_rate", text="Collection Rate") col.separator() col.label(text="Images Draw Method:") col.prop(system, "image_draw_method", text="") col.separator() col.label(text="Sequencer/Clip Editor:") # currently disabled in the code # col.prop(system, "prefetch_frames") col.prop(system, "memory_cache_limit") # 3. Column column = split.column() column.label(text="Solid OpenGL lights:") split = column.split(percentage=0.1) split.label() split.label(text="Colors:") split.label(text="Direction:") lamp = system.solid_lights[0] opengl_lamp_buttons(column, lamp) lamp = system.solid_lights[1] opengl_lamp_buttons(column, lamp) lamp = system.solid_lights[2] opengl_lamp_buttons(column, lamp) column.separator() column.label(text="Color Picker Type:") column.row().prop(system, "color_picker_type", text="") column.separator() column.prop(system, "use_weight_color_range", text="Custom Weight Paint Range") sub = column.column() sub.active = system.use_weight_color_range sub.template_color_ramp(system, "weight_color_range", expand=True) column.separator() column.prop(system, "font_path_ui") column.prop(system, "font_path_ui_mono") if bpy.app.build_options.international: column.prop(system, "use_international_fonts") if system.use_international_fonts: column.prop(system, "language") row = column.row() row.label(text="Translate:", text_ctxt=i18n_contexts.id_windowmanager) row = column.row(align=True) row.prop(system, "use_translate_interface", text="Interface", toggle=True) row.prop(system, "use_translate_tooltips", text="Tooltips", toggle=True) row.prop(system, "use_translate_new_dataname", text="New Data", toggle=True) class USERPREF_MT_interface_theme_presets(Menu): bl_label = "Presets" preset_subdir = "interface_theme" preset_operator = "script.execute_preset" preset_type = 'XML' preset_xml_map = ( ("user_preferences.themes[0]", "Theme"), ("user_preferences.ui_styles[0]", "ThemeStyle"), ) draw = Menu.draw_preset class USERPREF_PT_theme(Panel): bl_space_type = 'USER_PREFERENCES' bl_label = "Themes" bl_region_type = 'WINDOW' bl_options = {'HIDE_HEADER'} # not essential, hard-coded UI delimiters for the theme layout ui_delimiters = { 'VIEW_3D': { "text_grease_pencil", "text_keyframe", "speaker", "freestyle_face_mark", "split_normal", "bone_solid", "paint_curve_pivot", }, 'GRAPH_EDITOR': { "handle_vertex_select", }, 'IMAGE_EDITOR': { "paint_curve_pivot", }, 'NODE_EDITOR': { "layout_node", }, 'CLIP_EDITOR': { "handle_vertex_select", } } @staticmethod def _theme_generic(split, themedata, theme_area): col = split.column() def theme_generic_recurse(data): col.label(data.rna_type.name) row = col.row() subsplit = row.split(percentage=0.95) padding1 = subsplit.split(percentage=0.15) padding1.column() subsplit = row.split(percentage=0.85) padding2 = subsplit.split(percentage=0.15) padding2.column() colsub_pair = padding1.column(), padding2.column() props_type = {} for i, prop in enumerate(data.rna_type.properties): if prop.identifier == "rna_type": continue props_type.setdefault((prop.type, prop.subtype), []).append(prop) th_delimiters = USERPREF_PT_theme.ui_delimiters.get(theme_area) for props_type, props_ls in sorted(props_type.items()): if props_type[0] == 'POINTER': for i, prop in enumerate(props_ls): theme_generic_recurse(getattr(data, prop.identifier)) else: if th_delimiters is None: # simple, no delimiters for i, prop in enumerate(props_ls): colsub_pair[i % 2].row().prop(data, prop.identifier) else: # add hard coded delimiters i = 0 for prop in props_ls: colsub = colsub_pair[i] colsub.row().prop(data, prop.identifier) i = (i + 1) % 2 if prop.identifier in th_delimiters: if i: colsub = colsub_pair[1] colsub.row().label("") colsub_pair[0].row().label("") colsub_pair[1].row().label("") i = 0 theme_generic_recurse(themedata) @staticmethod def _theme_widget_style(layout, widget_style): row = layout.row() subsplit = row.split(percentage=0.95) padding = subsplit.split(percentage=0.15) colsub = padding.column() colsub = padding.column() colsub.row().prop(widget_style, "outline") colsub.row().prop(widget_style, "item", slider=True) colsub.row().prop(widget_style, "inner", slider=True) colsub.row().prop(widget_style, "inner_sel", slider=True) subsplit = row.split(percentage=0.85) padding = subsplit.split(percentage=0.15) colsub = padding.column() colsub = padding.column() colsub.row().prop(widget_style, "text") colsub.row().prop(widget_style, "text_sel") colsub.prop(widget_style, "show_shaded") subsub = colsub.column(align=True) subsub.active = widget_style.show_shaded subsub.prop(widget_style, "shadetop") subsub.prop(widget_style, "shadedown") layout.separator() @staticmethod def _ui_font_style(layout, font_style): split = layout.split() col = split.column() col.label(text="Kerning Style:") col.row().prop(font_style, "font_kerning_style", expand=True) col.prop(font_style, "points") col = split.column() col.label(text="Shadow Offset:") col.prop(font_style, "shadow_offset_x", text="X") col.prop(font_style, "shadow_offset_y", text="Y") col = split.column() col.prop(font_style, "shadow") col.prop(font_style, "shadow_alpha") col.prop(font_style, "shadow_value") layout.separator() @classmethod def poll(cls, context): userpref = context.user_preferences return (userpref.active_section == 'THEMES') def draw(self, context): layout = self.layout theme = context.user_preferences.themes[0] split_themes = layout.split(percentage=0.2) sub = split_themes.column() sub.label(text="Presets:") subrow = sub.row(align=True) subrow.menu("USERPREF_MT_interface_theme_presets", text=USERPREF_MT_interface_theme_presets.bl_label) subrow.operator("wm.interface_theme_preset_add", text="", icon='ZOOMIN') subrow.operator("wm.interface_theme_preset_add", text="", icon='ZOOMOUT').remove_active = True sub.separator() sub.prop(theme, "theme_area", expand=True) split = layout.split(percentage=0.4) layout.separator() layout.separator() split = split_themes.split() if theme.theme_area == 'USER_INTERFACE': col = split.column() ui = theme.user_interface col.label(text="Regular:") self._theme_widget_style(col, ui.wcol_regular) col.label(text="Tool:") self._theme_widget_style(col, ui.wcol_tool) col.label(text="Radio Buttons:") self._theme_widget_style(col, ui.wcol_radio) col.label(text="Text:") self._theme_widget_style(col, ui.wcol_text) col.label(text="Option:") self._theme_widget_style(col, ui.wcol_option) col.label(text="Toggle:") self._theme_widget_style(col, ui.wcol_toggle) col.label(text="Number Field:") self._theme_widget_style(col, ui.wcol_num) col.label(text="Value Slider:") self._theme_widget_style(col, ui.wcol_numslider) col.label(text="Box:") self._theme_widget_style(col, ui.wcol_box) col.label(text="Menu:") self._theme_widget_style(col, ui.wcol_menu) col.label(text="Pie Menu:") self._theme_widget_style(col, ui.wcol_pie_menu) col.label(text="Pulldown:") self._theme_widget_style(col, ui.wcol_pulldown) col.label(text="Menu Back:") self._theme_widget_style(col, ui.wcol_menu_back) col.label(text="Tooltip:") self._theme_widget_style(col, ui.wcol_tooltip) col.label(text="Menu Item:") self._theme_widget_style(col, ui.wcol_menu_item) col.label(text="Scroll Bar:") self._theme_widget_style(col, ui.wcol_scroll) col.label(text="Progress Bar:") self._theme_widget_style(col, ui.wcol_progress) col.label(text="List Item:") self._theme_widget_style(col, ui.wcol_list_item) ui_state = theme.user_interface.wcol_state col.label(text="State:") row = col.row() subsplit = row.split(percentage=0.95) padding = subsplit.split(percentage=0.15) colsub = padding.column() colsub = padding.column() colsub.row().prop(ui_state, "inner_anim") colsub.row().prop(ui_state, "inner_anim_sel") colsub.row().prop(ui_state, "inner_driven") colsub.row().prop(ui_state, "inner_driven_sel") subsplit = row.split(percentage=0.85) padding = subsplit.split(percentage=0.15) colsub = padding.column() colsub = padding.column() colsub.row().prop(ui_state, "inner_key") colsub.row().prop(ui_state, "inner_key_sel") colsub.row().prop(ui_state, "blend") col.separator() col.separator() col.label("Styles:") row = col.row() subsplit = row.split(percentage=0.95) padding = subsplit.split(percentage=0.15) colsub = padding.column() colsub = padding.column() colsub.row().prop(ui, "menu_shadow_fac") subsplit = row.split(percentage=0.85) padding = subsplit.split(percentage=0.15) colsub = padding.column() colsub = padding.column() colsub.row().prop(ui, "menu_shadow_width") row = col.row() subsplit = row.split(percentage=0.95) padding = subsplit.split(percentage=0.15) colsub = padding.column() colsub = padding.column() colsub.row().prop(ui, "icon_alpha") subsplit = row.split(percentage=0.85) padding = subsplit.split(percentage=0.15) colsub = padding.column() colsub = padding.column() colsub.row().prop(ui, "widget_emboss") col.separator() col.separator() col.label("Axis Colors:") row = col.row() subsplit = row.split(percentage=0.95) padding = subsplit.split(percentage=0.15) colsub = padding.column() colsub = padding.column() colsub.row().prop(ui, "axis_x") colsub.row().prop(ui, "axis_y") colsub.row().prop(ui, "axis_z") subsplit = row.split(percentage=0.85) padding = subsplit.split(percentage=0.15) colsub = padding.column() colsub = padding.column() layout.separator() layout.separator() elif theme.theme_area == 'BONE_COLOR_SETS': col = split.column() for i, ui in enumerate(theme.bone_color_sets): col.label(text=iface_("Color Set %d:") % (i + 1), translate=False) # i starts from 0 row = col.row() subsplit = row.split(percentage=0.95) padding = subsplit.split(percentage=0.15) colsub = padding.column() colsub = padding.column() colsub.row().prop(ui, "normal") colsub.row().prop(ui, "select") colsub.row().prop(ui, "active") subsplit = row.split(percentage=0.85) padding = subsplit.split(percentage=0.15) colsub = padding.column() colsub = padding.column() colsub.row().prop(ui, "show_colored_constraints") elif theme.theme_area == 'STYLE': col = split.column() style = context.user_preferences.ui_styles[0] col.label(text="Panel Title:") self._ui_font_style(col, style.panel_title) col.separator() col.label(text="Widget:") self._ui_font_style(col, style.widget) col.separator() col.label(text="Widget Label:") self._ui_font_style(col, style.widget_label) else: self._theme_generic(split, getattr(theme, theme.theme_area.lower()), theme.theme_area) class USERPREF_PT_file(Panel): bl_space_type = 'USER_PREFERENCES' bl_label = "Files" bl_region_type = 'WINDOW' bl_options = {'HIDE_HEADER'} @classmethod def poll(cls, context): userpref = context.user_preferences return (userpref.active_section == 'FILES') def draw(self, context): layout = self.layout userpref = context.user_preferences paths = userpref.filepaths system = userpref.system split = layout.split(percentage=0.7) col = split.column() col.label(text="File Paths:") colsplit = col.split(percentage=0.95) col1 = colsplit.split(percentage=0.3) sub = col1.column() sub.label(text="Fonts:") sub.label(text="Textures:") sub.label(text="Render Output:") sub.label(text="Scripts:") sub.label(text="Sounds:") sub.label(text="Temp:") sub.label(text="Render Cache:") sub.label(text="I18n Branches:") sub.label(text="Image Editor:") sub.label(text="Animation Player:") sub = col1.column() sub.prop(paths, "font_directory", text="") sub.prop(paths, "texture_directory", text="") sub.prop(paths, "render_output_directory", text="") sub.prop(paths, "script_directory", text="") sub.prop(paths, "sound_directory", text="") sub.prop(paths, "temporary_directory", text="") sub.prop(paths, "render_cache_directory", text="") sub.prop(paths, "i18n_branches_directory", text="") sub.prop(paths, "image_editor", text="") subsplit = sub.split(percentage=0.3) subsplit.prop(paths, "animation_player_preset", text="") subsplit.prop(paths, "animation_player", text="") col.separator() col.separator() colsplit = col.split(percentage=0.95) sub = colsplit.column() row = sub.split(percentage=0.3) row.label(text="Auto Execution:") row.prop(system, "use_scripts_auto_execute") if system.use_scripts_auto_execute: box = sub.box() row = box.row() row.label(text="Excluded Paths:") row.operator("wm.userpref_autoexec_path_add", text="", icon='ZOOMIN', emboss=False) for i, path_cmp in enumerate(userpref.autoexec_paths): row = box.row() row.prop(path_cmp, "path", text="") row.prop(path_cmp, "use_glob", text="", icon='FILTER') row.operator("wm.userpref_autoexec_path_remove", text="", icon='X', emboss=False).index = i col = split.column() col.label(text="Save & Load:") col.prop(paths, "use_relative_paths") col.prop(paths, "use_file_compression") col.prop(paths, "use_load_ui") col.prop(paths, "use_filter_files") col.prop(paths, "show_hidden_files_datablocks") col.prop(paths, "hide_recent_locations") col.prop(paths, "hide_system_bookmarks") col.prop(paths, "show_thumbnails") col.separator() col.prop(paths, "save_version") col.prop(paths, "recent_files") col.prop(paths, "use_save_preview_images") col.separator() col.label(text="Auto Save:") col.prop(paths, "use_keep_session") col.prop(paths, "use_auto_save_temporary_files") sub = col.column() sub.active = paths.use_auto_save_temporary_files sub.prop(paths, "auto_save_time", text="Timer (mins)") col.separator() col.label(text="Text Editor:") col.prop(system, "use_tabs_as_spaces") colsplit = col.split(percentage=0.95) col1 = colsplit.split(percentage=0.3) sub = col1.column() sub.label(text="Author:") sub = col1.column() sub.prop(system, "author", text="") class USERPREF_MT_ndof_settings(Menu): # accessed from the window key-bindings in C (only) bl_label = "3D Mouse Settings" def draw(self, context): layout = self.layout input_prefs = context.user_preferences.inputs is_view3d = context.space_data.type == 'VIEW_3D' layout.prop(input_prefs, "ndof_sensitivity") layout.prop(input_prefs, "ndof_orbit_sensitivity") layout.prop(input_prefs, "ndof_deadzone") if is_view3d: layout.separator() layout.prop(input_prefs, "ndof_show_guide") layout.separator() layout.label(text="Orbit style") layout.row().prop(input_prefs, "ndof_view_navigate_method", text="") layout.row().prop(input_prefs, "ndof_view_rotate_method", text="") layout.separator() layout.label(text="Orbit options") layout.prop(input_prefs, "ndof_rotx_invert_axis") layout.prop(input_prefs, "ndof_roty_invert_axis") layout.prop(input_prefs, "ndof_rotz_invert_axis") # view2d use pan/zoom layout.separator() layout.label(text="Pan options") layout.prop(input_prefs, "ndof_panx_invert_axis") layout.prop(input_prefs, "ndof_pany_invert_axis") layout.prop(input_prefs, "ndof_panz_invert_axis") layout.prop(input_prefs, "ndof_pan_yz_swap_axis") layout.label(text="Zoom options") layout.prop(input_prefs, "ndof_zoom_invert") if is_view3d: layout.separator() layout.label(text="Fly/Walk options") layout.prop(input_prefs, "ndof_fly_helicopter", icon='NDOF_FLY') layout.prop(input_prefs, "ndof_lock_horizon", icon='NDOF_DOM') class USERPREF_MT_keyconfigs(Menu): bl_label = "KeyPresets" preset_subdir = "keyconfig" preset_operator = "wm.keyconfig_activate" def draw(self, context): props = self.layout.operator("wm.context_set_value", text="Blender (default)") props.data_path = "window_manager.keyconfigs.active" props.value = "context.window_manager.keyconfigs.default" # now draw the presets Menu.draw_preset(self, context) class USERPREF_PT_input(Panel): bl_space_type = 'USER_PREFERENCES' bl_label = "Input" bl_region_type = 'WINDOW' bl_options = {'HIDE_HEADER'} @classmethod def poll(cls, context): userpref = context.user_preferences return (userpref.active_section == 'INPUT') @staticmethod def draw_input_prefs(inputs, layout): import sys # General settings row = layout.row() col = row.column() sub = col.column() sub.label(text="Presets:") subrow = sub.row(align=True) subrow.menu("USERPREF_MT_interaction_presets", text=bpy.types.USERPREF_MT_interaction_presets.bl_label) subrow.operator("wm.interaction_preset_add", text="", icon='ZOOMIN') subrow.operator("wm.interaction_preset_add", text="", icon='ZOOMOUT').remove_active = True sub.separator() sub.label(text="Mouse:") sub1 = sub.column() sub1.active = (inputs.select_mouse == 'RIGHT') sub1.prop(inputs, "use_mouse_emulate_3_button") sub.prop(inputs, "use_mouse_continuous") sub.prop(inputs, "drag_threshold") sub.prop(inputs, "tweak_threshold") sub.label(text="Select With:") sub.row().prop(inputs, "select_mouse", expand=True) sub = col.column() sub.label(text="Double Click:") sub.prop(inputs, "mouse_double_click_time", text="Speed") sub.separator() sub.prop(inputs, "use_emulate_numpad") sub.separator() sub.label(text="Orbit Style:") sub.row().prop(inputs, "view_rotate_method", expand=True) sub.separator() sub.label(text="Zoom Style:") sub.row().prop(inputs, "view_zoom_method", text="") if inputs.view_zoom_method in {'DOLLY', 'CONTINUE'}: sub.row().prop(inputs, "view_zoom_axis", expand=True) sub.prop(inputs, "invert_mouse_zoom", text="Invert Mouse Zoom Direction") #sub.prop(inputs, "use_mouse_mmb_paste") #col.separator() sub = col.column() sub.prop(inputs, "invert_zoom_wheel", text="Invert Wheel Zoom Direction") #sub.prop(view, "wheel_scroll_lines", text="Scroll Lines") if sys.platform == "darwin": sub = col.column() sub.prop(inputs, "use_trackpad_natural", text="Natural Trackpad Direction") col.separator() sub = col.column() sub.label(text="View Navigation:") sub.row().prop(inputs, "navigation_mode", expand=True) if inputs.navigation_mode == 'WALK': walk = inputs.walk_navigation sub.prop(walk, "use_mouse_reverse") sub.prop(walk, "mouse_speed") sub.prop(walk, "teleport_time") sub = col.column(align=True) sub.prop(walk, "walk_speed") sub.prop(walk, "walk_speed_factor") sub.separator() sub.prop(walk, "use_gravity") sub = col.column(align=True) sub.active = walk.use_gravity sub.prop(walk, "view_height") sub.prop(walk, "jump_height") if inputs.use_ndof: col.separator() col.label(text="NDOF Device:") sub = col.column(align=True) sub.prop(inputs, "ndof_sensitivity", text="NDOF Sensitivity") sub.prop(inputs, "ndof_orbit_sensitivity", text="NDOF Orbit Sensitivity") sub.prop(inputs, "ndof_deadzone", text="NDOF Deadzone") sub = col.column(align=True) sub.row().prop(inputs, "ndof_view_navigate_method", expand=True) sub.row().prop(inputs, "ndof_view_rotate_method", expand=True) row.separator() def draw(self, context): from rna_keymap_ui import draw_keymaps layout = self.layout #import time #start = time.time() userpref = context.user_preferences inputs = userpref.inputs split = layout.split(percentage=0.25) # Input settings self.draw_input_prefs(inputs, split) # Keymap Settings draw_keymaps(context, split) #print("runtime", time.time() - start) class USERPREF_MT_addons_online_resources(Menu): bl_label = "Online Resources" # menu to open web-pages with addons development guides def draw(self, context): layout = self.layout layout.operator( "wm.url_open", text="Add-ons Catalog", icon='URL', ).url = "http://wiki.blender.org/index.php/Extensions:2.6/Py/Scripts" layout.separator() layout.operator( "wm.url_open", text="How to share your add-on", icon='URL', ).url = "http://wiki.blender.org/index.php/Dev:Py/Sharing" layout.operator( "wm.url_open", text="Add-on Guidelines", icon='URL', ).url = "http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Guidelines/Addons" layout.operator( "wm.url_open", text="API Concepts", icon='URL', ).url = bpy.types.WM_OT_doc_view._prefix + "/info_quickstart.html" layout.operator("wm.url_open", text="Add-on Tutorial", icon='URL', ).url = "http://www.blender.org/api/blender_python_api_current/info_tutorial_addon.html" class USERPREF_PT_addons(Panel): bl_space_type = 'USER_PREFERENCES' bl_label = "Add-ons" bl_region_type = 'WINDOW' bl_options = {'HIDE_HEADER'} _support_icon_mapping = { 'OFFICIAL': 'FILE_BLEND', 'COMMUNITY': 'POSE_DATA', 'TESTING': 'MOD_EXPLODE', } @classmethod def poll(cls, context): userpref = context.user_preferences return (userpref.active_section == 'ADDONS') @staticmethod def is_user_addon(mod, user_addon_paths): import os if not user_addon_paths: for path in (bpy.utils.script_path_user(), bpy.utils.script_path_pref()): if path is not None: user_addon_paths.append(os.path.join(path, "addons")) for path in user_addon_paths: if bpy.path.is_subdir(mod.__file__, path): return True return False @staticmethod def draw_error(layout, message): lines = message.split("\n") box = layout.box() sub = box.row() sub.label(lines[0]) sub.label(icon='ERROR') for l in lines[1:]: box.label(l) def draw(self, context): import os import addon_utils layout = self.layout userpref = context.user_preferences used_ext = {ext.module for ext in userpref.addons} userpref_addons_folder = os.path.join(userpref.filepaths.script_directory, "addons") scripts_addons_folder = bpy.utils.user_resource('SCRIPTS', "addons") # collect the categories that can be filtered on addons = [(mod, addon_utils.module_bl_info(mod)) for mod in addon_utils.modules(refresh=False)] split = layout.split(percentage=0.2) col = split.column() col.prop(context.window_manager, "addon_search", text="", icon='VIEWZOOM') col.label(text="Supported Level") col.prop(context.window_manager, "addon_support", expand=True) col.label(text="Categories") col.prop(context.window_manager, "addon_filter", expand=True) col = split.column() # set in addon_utils.modules_refresh() if addon_utils.error_duplicates: self.draw_error(col, "Multiple addons using the same name found!\n" "likely a problem with the script search path.\n" "(see console for details)", ) if addon_utils.error_encoding: self.draw_error(col, "One or more addons do not have UTF-8 encoding\n" "(see console for details)", ) filter = context.window_manager.addon_filter search = context.window_manager.addon_search.lower() support = context.window_manager.addon_support # initialized on demand user_addon_paths = [] for mod, info in addons: module_name = mod.__name__ is_enabled = module_name in used_ext if info["support"] not in support: continue # check if addon should be visible with current filters if ((filter == "All") or (filter == info["category"]) or (filter == "Enabled" and is_enabled) or (filter == "Disabled" and not is_enabled) or (filter == "User" and (mod.__file__.startswith((scripts_addons_folder, userpref_addons_folder)))) ): if search and search not in info["name"].lower(): if info["author"]: if search not in info["author"].lower(): continue else: continue # Addon UI Code col_box = col.column() box = col_box.box() colsub = box.column() row = colsub.row(align=True) row.operator( "wm.addon_expand", icon='TRIA_DOWN' if info["show_expanded"] else 'TRIA_RIGHT', emboss=False, ).module = module_name row.operator( "wm.addon_disable" if is_enabled else "wm.addon_enable", icon='CHECKBOX_HLT' if is_enabled else 'CHECKBOX_DEHLT', text="", emboss=False, ).module = module_name sub = row.row() sub.active = is_enabled sub.label(text='%s: %s' % (info["category"], info["name"])) if info["warning"]: sub.label(icon='ERROR') # icon showing support level. sub.label(icon=self._support_icon_mapping.get(info["support"], 'QUESTION')) # Expanded UI (only if additional info is available) if info["show_expanded"]: if info["description"]: split = colsub.row().split(percentage=0.15) split.label(text="Description:") split.label(text=info["description"]) if info["location"]: split = colsub.row().split(percentage=0.15) split.label(text="Location:") split.label(text=info["location"]) if mod: split = colsub.row().split(percentage=0.15) split.label(text="File:") split.label(text=mod.__file__, translate=False) if info["author"]: split = colsub.row().split(percentage=0.15) split.label(text="Author:") split.label(text=info["author"], translate=False) if info["version"]: split = colsub.row().split(percentage=0.15) split.label(text="Version:") split.label(text='.'.join(str(x) for x in info["version"]), translate=False) if info["warning"]: split = colsub.row().split(percentage=0.15) split.label(text="Warning:") split.label(text=' ' + info["warning"], icon='ERROR') user_addon = USERPREF_PT_addons.is_user_addon(mod, user_addon_paths) tot_row = bool(info["wiki_url"]) + bool(user_addon) if tot_row: split = colsub.row().split(percentage=0.15) split.label(text="Internet:") if info["wiki_url"]: split.operator("wm.url_open", text="Documentation", icon='HELP').url = info["wiki_url"] split.operator("wm.url_open", text="Report a Bug", icon='URL').url = info.get( "tracker_url", "https://developer.blender.org/maniphest/task/edit/form/2") if user_addon: split.operator("wm.addon_remove", text="Remove", icon='CANCEL').module = mod.__name__ for i in range(4 - tot_row): split.separator() # Show addon user preferences if is_enabled: addon_preferences = userpref.addons[module_name].preferences if addon_preferences is not None: draw = getattr(addon_preferences, "draw", None) if draw is not None: addon_preferences_class = type(addon_preferences) box_prefs = col_box.box() box_prefs.label("Preferences:") addon_preferences_class.layout = box_prefs try: draw(context) except: import traceback traceback.print_exc() box_prefs.label(text="Error (see console)", icon='ERROR') del addon_preferences_class.layout # Append missing scripts # First collect scripts that are used but have no script file. module_names = {mod.__name__ for mod, info in addons} missing_modules = {ext for ext in used_ext if ext not in module_names} if missing_modules and filter in {"All", "Enabled"}: col.column().separator() col.column().label(text="Missing script files") module_names = {mod.__name__ for mod, info in addons} for module_name in sorted(missing_modules): is_enabled = module_name in used_ext # Addon UI Code box = col.column().box() colsub = box.column() row = colsub.row(align=True) row.label(text="", icon='ERROR') if is_enabled: row.operator("wm.addon_disable", icon='CHECKBOX_HLT', text="", emboss=False).module = module_name row.label(text=module_name, translate=False) if __name__ == "__main__": # only for live edit. bpy.utils.register_module(__name__)
AndrewPeelMV/Blender2.78c
2.78/scripts/startup/bl_ui/space_userpref.py
Python
gpl-2.0
50,089
__author__ = 'Artur Barseghyan <[email protected]>' __copyright__ = 'Copyright (c) 2013 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('FIT_METHOD_CROP_SMART', 'FIT_METHOD_CROP_CENTER', 'FIT_METHOD_CROP_SCALE', 'FIT_METHOD_FIT_WIDTH', 'FIT_METHOD_FIT_HEIGHT', 'DEFAULT_FIT_METHOD', 'FIT_METHODS_CHOICES', 'FIT_METHODS_CHOICES_WITH_EMPTY_OPTION', 'IMAGES_UPLOAD_DIR') from django.utils.translation import ugettext_lazy as _ FIT_METHOD_CROP_SMART = 'smart' FIT_METHOD_CROP_CENTER = 'center' FIT_METHOD_CROP_SCALE = 'scale' FIT_METHOD_FIT_WIDTH = 'fit_width' FIT_METHOD_FIT_HEIGHT = 'fit_height' DEFAULT_FIT_METHOD = FIT_METHOD_CROP_CENTER FIT_METHODS_CHOICES = ( (FIT_METHOD_CROP_SMART, _("Smart crop")), (FIT_METHOD_CROP_CENTER, _("Crop center")), (FIT_METHOD_CROP_SCALE, _("Crop scale")), (FIT_METHOD_FIT_WIDTH, _("Fit width")), (FIT_METHOD_FIT_HEIGHT, _("Fit height")), ) FIT_METHODS_CHOICES_WITH_EMPTY_OPTION = [('', '---------')] + list(FIT_METHODS_CHOICES) IMAGES_UPLOAD_DIR = 'dash-image-plugin-images'
georgistanev/django-dash
src/dash/contrib/plugins/image/defaults.py
Python
gpl-2.0
1,080
#!/usr/bin/python # -*- coding: utf-8 -*- """Layman is a complete library for the operation and maintainance on all gentoo repositories and overlays """ import sys try: from layman.api import LaymanAPI from layman.config import BareConfig from layman.output import Message except ImportError: sys.stderr.write("!!! Layman API imports failed.") raise class Layman(LaymanAPI): """A complete high level interface capable of performing all overlay repository actions.""" def __init__(self, stdout=sys.stdout, stdin=sys.stdin, stderr=sys.stderr, config=None, read_configfile=True, quiet=False, quietness=4, verbose=False, nocolor=False, width=0, root=None ): """Input parameters are optional to override the defaults. sets up our LaymanAPI with defaults or passed in values and returns an instance of it""" self.message = Message(out=stdout, err=stderr) self.config = BareConfig( output=self.message, stdout=stdout, stdin=stdin, stderr=stderr, config=config, read_configfile=read_configfile, quiet=quiet, quietness=quietness, verbose=verbose, nocolor=nocolor, width=width, root=root ) LaymanAPI.__init__(self, self.config, report_errors=True, output=self.config['output'] ) return
jmesmon/layman
layman/__init__.py
Python
gpl-2.0
1,585
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-08-21 18:59 from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): dependencies = [ ('dispatch', '0017_subsections'), ] operations = [ migrations.CreateModel( name='Podcast', fields=[ ('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)), ('slug', models.SlugField(unique=True)), ('title', models.CharField(max_length=255)), ('description', models.TextField()), ('author', models.CharField(max_length=255)), ('owner_name', models.CharField(max_length=255)), ('owner_email', models.EmailField(max_length=255)), ('category', models.CharField(max_length=255)), ('image', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='dispatch.Image')), ], ), migrations.CreateModel( name='PodcastEpisode', fields=[ ('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)), ('title', models.CharField(max_length=255)), ('description', models.TextField()), ('author', models.CharField(max_length=255)), ('duration', models.PositiveIntegerField(null=True)), ('published_at', models.DateTimeField()), ('explicit', models.CharField(choices=[(b'no', b'No'), (b'yes', b'Yes'), (b'clean', b'Clean')], default=b'no', max_length=5)), ('file', models.FileField(upload_to=b'podcasts/')), ('type', models.CharField(default='audio/mp3', max_length=255)), ('image', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='dispatch.Image')), ('podcast', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dispatch.Podcast')), ], ), ]
ubyssey/dispatch
dispatch/migrations/0018_podcasts.py
Python
gpl-2.0
2,099
""" This module instructs the setuptools to setpup this package properly :copyright: (c) 2016 by Mehdy Khoshnoody. :license: GPLv3, see LICENSE for more details. """ import os from distutils.core import setup setup( name='pyeez', version='0.1.0', packages=['pyeez'], classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='terminal console', url='https://github.com/mehdy/pyeez', license='GPLv3', author='Mehdy Khoshnoody', author_email='[email protected]', description='A micro-framework to create console-based applications like' 'htop, vim and etc' )
mehdy/pyeez
setup.py
Python
gpl-2.0
1,167
#!/usr/bin/env python import re import sys from urllib import urlopen def isup(domain): resp = urlopen("http://www.isup.me/%s" % domain).read() return "%s" % ("UP" if re.search("It's just you.", resp, re.DOTALL) else "DOWN") if __name__ == '__main__': if len(sys.argv) > 1: print "\n".join(isup(d) for d in sys.argv[1:]) else: print "usage: %s domain1 [domain2 .. domainN]" % sys.argv[0]
BogdanWDK/ajaxbot
src/files/isup.py
Python
gpl-2.0
433
from django import forms from django.forms import ModelForm from models import * from django.forms import Textarea from django.contrib.auth.hashers import make_password from django.contrib.auth.models import Group class OgretimElemaniFormu(ModelForm): parolasi=forms.CharField(label="Parolasi", help_text='Parola yazilmazsa onceki parola gecerlidir', required=False) class Meta: model = OgretimElemani fields = ('unvani','first_name','last_name', 'username','parolasi','email','telefonu') def save(self,commit=True): instance = super(OgretimElemaniFormu,self).save(commit=False) if self.cleaned_data.get('parolasi'): instance.password=make_password(self.cleaned_data['parolasi']) if commit: instance.save() if instance.group.filter(name='ogretimelemanlari'): grp = Group.objects.get(name='ogretimelemanlari') instance.group.add(grp) return instance class DersFormu(ModelForm): class Meta: model = Ders widgets = { 'tanimi':Textarea(attrs={'cols':35, 'rows':5}), } #class OgretimElemaniAltFormu(ModelForm): # class Meta: # model = OgretimElemani # fields = ('username','parolasi','email') #exclude=('unvani','telefonu') bu da ayni gorevi gorur # fields kullanarak hangi sirada gozukmesini istiyorsak ayarlayabiliriz # yada exclude diyerek istemedigimiz alanlari formdan cikartabiliriz class AramaFormu(forms.Form): aranacak_kelime = forms.CharField() def clean_aranacak_kelime(self): kelime=self.cleaned_data['aranacak_kelime'] if len(kelime) < 3: raise forms.ValidationError('Aranacak kelime 3 harften az olamaz') return kelime
dogancankilment/Django-obs
yonetim/forms.py
Python
gpl-2.0
1,672
#!/usr/bin/python import unittest import ldc import uuid class TestLDCDNSInterface(unittest.TestCase): def test_ldcdns(self): rand_str = str(uuid.uuid4()) ldc.dns.add(rand_str, '1.1.1.1') assert ldc.dns.resolve(rand_str) == [ '1.1.1.1' ] ldc.dns.replace_all(rand_str,'2.2.2.2') assert ldc.dns.resolve(rand_str) == [ '2.2.2.2' ] ldc.dns.delete(rand_str) assert ldc.dns.resolve(rand_str) == [] if __name__ == '__main__': unittest.main()
udragon/ldc
ldc/test/test_ldcdns.py
Python
gpl-2.0
502
# -*- coding: utf-8 -*- """ Script: GotoLineCol.py Utility: 1. Moves the cursor position to the specified line and column for a file in Notepad++. Especially useful for inspecting data files in fixed-width record formats. 2. Also, displays the character code (SBCS & LTR) in decimal and hex at the specified position. Requires: Python Script plugin in Notepad++ Customizable parameters for the goToLineCol function call in main(): bRepeatPrompt: Whether to repeat prompting when the specified number value is out of range iEdgeBuffer: Ensures that the caret will be that many characters inside the left and right edges of the editor viewing area, when possible iCaretHiliteDuration: Caret will be in Block mode for specified seconds bCallTipAutoHide: Whether to hide the call tip automatically in sync when caret highlighting is turned off bBraceHilite: Whether to use brace highlighting style for the character at the specified position. Automatically turns off when current line changes. Known Issues: 1. Character code display in the call tip is functional with SBCS (Single-Byte Character Sets) and LTR (left-to-right) direction. With MBCS (Bulti-Bytes Character Sets) or RTL (right-to-left) direction, results will not be reliable. 2. If iCaretHiliteDuration is set to a high value (>3 seconds), and the user tries to rerun the script while the previous execution is still running, the Python Script plugin will display an error message: "Another script is still running..." So set this parameter to 3 seconds or lower. Author: Shridhar Kumar Date: 2019-08-15 """ def main(): goToLineCol(bRepeatPrompt = True, iEdgeBuffer = 5, iCaretHiliteDuration = 5, bCallTipAutoHide = False, bBraceHilite = True) def getDisplayLineCol(): iCurrLine = editor.lineFromPosition(editor.getCurrentPos()) iCurrCol = editor.getCurrentPos() - editor.positionFromLine(iCurrLine) return str(iCurrLine + 1), str(iCurrCol + 1) def promptValue(sInfoText, sTitleText, sDefaultVal, iMinVal, iMaxVal, sRangeError, bRepeatPrompt): while True: sNewVal = notepad.prompt(sInfoText, sTitleText, sDefaultVal) if sNewVal == None: return None try: iNewVal = int(sNewVal) if iMinVal <= iNewVal <= iMaxVal: return iNewVal else: raise except: notepad.messageBox(sRangeError + '.\n\nYou specified: ' + sNewVal + '\n\nPlease specify a number between ' + str(iMinVal) + ' and ' + str(iMaxVal) + '.', 'Specified value is out of range') if not bRepeatPrompt: return None def goToLineCol(bRepeatPrompt, iEdgeBuffer, iCaretHiliteDuration, bCallTipAutoHide, bBraceHilite): import time sCurrLine, sCurrCol = getDisplayLineCol() iMaxLines = editor.getLineCount() iNewLine = promptValue(sInfoText = 'Line number (between 1 and ' + str(iMaxLines) + '):', sTitleText = 'Specify line number', sDefaultVal = sCurrLine, iMinVal = 1, iMaxVal = iMaxLines, sRangeError = 'File line count is only ' + str(iMaxLines), bRepeatPrompt = bRepeatPrompt) if iNewLine == None: return # Get the character count plus 1 for the specified line # Plus 1 is to account for the caret position at the end of the line, past all characters but before EOL/EOF # Since lineLength already includes EOL, we just need to subtract 1 only when EOL is 2 chars. i.e., CRLF # For the last line in file, there is no 2-character CRLF EOL; only a single character EOF. iMaxCols = max(1, editor.lineLength(iNewLine - 1)) if (editor.getEOLMode() == ENDOFLINE.CRLF) and (iNewLine < iMaxLines): iMaxCols -= 1 iNewCol = promptValue(sInfoText = 'Column position (between 1 and ' + str(iMaxCols) + ') for line ' + str(iNewLine) + ':', sTitleText = 'Specify column position', sDefaultVal = sCurrCol, iMinVal = 1, iMaxVal = iMaxCols, sRangeError = 'There are only ' + str(iMaxCols) + ' characters in line ' + str(iNewLine), bRepeatPrompt = bRepeatPrompt) # Navigate to the specified position in the document iLineStartPos = editor.positionFromLine(iNewLine - 1) iNewPos = iLineStartPos + iNewCol - 1 editor.ensureVisible(iNewLine - 1) editor.gotoPos( min(iLineStartPos + iMaxCols, iNewPos + iEdgeBuffer) ) # Ensure that caret is 'iEdgeBuffer' characters inside right edge when possible editor.gotoPos( max(iLineStartPos, iNewPos - iEdgeBuffer) ) # Ensure that caret is 'iEdgeBuffer' characters inside left edge when possible editor.gotoPos(iNewPos) # Finally, move caret to the specified position # Obtain current caret style to restore it later on currCS = editor.getCaretStyle() # Set the caret to block style to highlight the new position editor.setCaretStyle(CARETSTYLE.BLOCK) # Display a call tip with the new line and column numbers with verification # Also display the character code in decimal and hex sCurrLine, sCurrCol = getDisplayLineCol() editor.callTipShow(iNewPos, ' Line: ' + sCurrLine + '\n Column: ' + sCurrCol + '\nChar Code: ' + str(editor.getCharAt(iNewPos)) + ' [' + hex(editor.getCharAt(iNewPos)) + ']') if iCaretHiliteDuration > 0: time.sleep(iCaretHiliteDuration) # Reset the caret style editor.setCaretStyle(currCS) if bCallTipAutoHide: editor.callTipCancel() if bBraceHilite: editor.braceHighlight(iNewPos, iNewPos) main()
bruderstein/PythonScript
scripts/Samples/GotoLineCol.py
Python
gpl-2.0
6,088
''' Created on 22/02/2015 @author: Ismail Faizi ''' import models class ModelFactory(object): """ Factory for creating entities of models """ @classmethod def create_user(cls, name, email, training_journal): """ Factory method for creating User entity. NOTE: you must explicitly call the put() method """ user = models.User(parent=models.USER_KEY) user.name = name user.email = email user.training_journal = training_journal.key return user @classmethod def create_training_journal(cls): """ Factory method for creating TrainingJournal entity. NOTE: you must explicitly call the put() method """ return models.TrainingJournal(parent=models.TRAINING_JOURNAL_KEY) @classmethod def create_workout_session(cls, started_at, ended_at, training_journal): """ Factory method for creating WorkoutSession entity. NOTE: you must explicitly call the put() method """ workout_session = models.WorkoutSession(parent=models.WORKOUT_SESSION_KEY) workout_session.started_at = started_at workout_session.ended_at = ended_at workout_session.training_journal = training_journal.key return workout_session @classmethod def create_workout_set(cls, repetitions, weight, workout_session, workout): """ Factory method for creating WorkoutSet entity. NOTE: you must explicitly call the put() method """ workout_set = models.WorkoutSet(parent=models.WORKOUT_SET_KEY) workout_set.repetitions = repetitions workout_set.weight = weight workout_set.workout_session = workout_session.key workout_set.workout = workout.key return workout_set @classmethod def create_workout(cls, muscle_group, names=[], description='', images=[]): """ Factory method for creating WorkoutSet entity. NOTE: you must explicitly call the put() method """ workout = models.Workout(parent=models.WORKOUT_KEY) workout.names = names workout.muscle_group = muscle_group workout.description = description workout.images = images return workout
kanafghan/fiziq-backend
src/models/factories.py
Python
gpl-2.0
2,302
############################################################################# ## ## Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ## Contact: Qt Software Information ([email protected]) ## ## This file is part of the Graphics Dojo project on Qt Labs. ## ## This file may be used under the terms of the GNU General Public ## License version 2.0 or 3.0 as published by the Free Software Foundation ## and appearing in the file LICENSE.GPL included in the packaging of ## this file. Please review the following information to ensure GNU ## General Public Licensing requirements will be met: ## http:#www.fsf.org/licensing/licenses/info/GPLv2.html and ## http:#www.gnu.org/copyleft/gpl.html. ## ## If you are unsure which license is appropriate for your use, please ## contact the sales department at [email protected]. ## ## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ## ############################################################################# import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import * if QT_VERSION < 0x0040500: sys.stderr.write("You need Qt 4.5 or newer to run this example.\n") sys.exit(1) SNAP_THRESHOLD = 10 class SnapView(QWebView): def __init__(self): QWebView.__init__(self) self.snapEnabled = True self.setWindowTitle(self.tr("Snap-scrolling is ON")) # rects hit by the line, in main frame's view coordinate def hitBoundingRects(self, line): hitRects = [] points = 8 delta = QPoint(line.dx() / points, line.dy() / points) point = line.p1() i = 0 while i < points - 1: point += delta hit = self.page().mainFrame().hitTestContent(point) if not hit.boundingRect().isEmpty(): hitRects.append(hit.boundingRect()) i += 1 return hitRects def keyPressEvent(self, event): # toggle snapping if event.key() == Qt.Key_F3: self.snapEnabled = not self.snapEnabled if self.snapEnabled: self.setWindowTitle(self.tr("Snap-scrolling is ON")) else: self.setWindowTitle(self.tr("Snap-scrolling is OFF")) event.accept() return # no snapping? do not bother... if not self.snapEnabled: QWebView.keyReleaseEvent(self, event) return previousOffset = self.page().mainFrame().scrollPosition() QWebView.keyReleaseEvent(self, event) if not event.isAccepted(): return if event.key() == Qt.Key_Down: ofs = self.page().mainFrame().scrollPosition() jump = ofs.y() - previousOffset.y() if jump == 0: return jump += SNAP_THRESHOLD rects = self.hitBoundingRects(QLine(1, 1, self.width() - 1, 1)) i = 0 while i < len(rects): j = rects[i].top() - previousOffset.y() if j > SNAP_THRESHOLD and j < jump: jump = j i += 1 self.page().mainFrame().setScrollPosition(previousOffset + QPoint(0, jump)) if __name__ == "__main__": app = QApplication(sys.argv) view = SnapView() view.load(QUrl("http://news.bbc.co.uk/text_only.stm")) view.resize(320, 500) view.show() QMessageBox.information(view, "Hint", "Use F3 to toggle snapping on and off") sys.exit(app.exec_())
anak10thn/graphics-dojo-qt5
snapscroll/snapscroll.py
Python
gpl-2.0
3,660
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #Uncomment to debug. If you aren't me, I bet you want to change the paths, too. import sys from wsnamelet import wsnamelet_globals if wsnamelet_globals.debug: sys.stdout = open ("/home/munizao/hacks/wsnamelet/debug.stdout", "w", buffering=1) sys.stderr = open ("/home/munizao/hacks/wsnamelet/debug.stderr", "w", buffering=1) import gi gi.require_version("Gtk", "3.0") gi.require_version("MatePanelApplet", "4.0") from gi.repository import Gtk from gi.repository import Gdk from gi.repository import GObject from gi.repository import Pango from gi.repository import MatePanelApplet gi.require_version ("Wnck", "3.0") from gi.repository import Wnck from gi.repository import Gio #Internationalize import locale import gettext gettext.bindtextdomain('wsnamelet', wsnamelet_globals.localedir) gettext.textdomain('wsnamelet') locale.bindtextdomain('wsnamelet', wsnamelet_globals.localedir) locale.textdomain('wsnamelet') gettext.install('wsnamelet', wsnamelet_globals.localedir) #screen = None class WSNamePrefs(object): def __init__(self, applet): self.applet = applet self.dialog = Gtk.Dialog("Workspace Name Applet Preferences", None, Gtk.DialogFlags.DESTROY_WITH_PARENT, (Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)) self.dialog.set_border_width(10) width_spin_label = Gtk.Label(label=_("Applet width in pixels:")) width_adj = Gtk.Adjustment(lower=30, upper=500, step_incr=1) self.width_spin_button = Gtk.SpinButton.new(width_adj, 0.0, 0) self.applet.settings.bind("width", self.width_spin_button, "value", Gio.SettingsBindFlags.DEFAULT) width_spin_hbox = Gtk.HBox() width_spin_hbox.pack_start(width_spin_label, True, True, 0) width_spin_hbox.pack_start(self.width_spin_button, True, True, 0) self.dialog.vbox.add(width_spin_hbox) class WSNameEntry(Gtk.Entry): def __init__(self, applet): Gtk.Widget.__init__(self) self.connect("activate", self._on_activate) self.connect("key-release-event", self._on_key_release) self.applet = applet def _on_activate(self, event): text = self.get_text() self.applet.workspace.change_name(text) self.applet.label.set_text(text) self.applet.exit_editing() def _on_key_release(self, widget, event): if event.keyval == Gdk.KEY_Escape: self.applet.exit_editing() class WSNameApplet(MatePanelApplet.Applet): _name_change_handler_id = None workspace = None settings = None prefs = None width = 100 editing = False def __init__(self, applet): self.applet = applet; menuxml = """ <menuitem name="Prefs" action="Prefs" /> <menuitem name="About" action="About" /> """ actions = [("Prefs", Gtk.STOCK_PREFERENCES, "Preferences", None, None, self._display_prefs), ("About", Gtk.STOCK_ABOUT, "About", None, None, self._display_about)] actiongroup = Gtk.ActionGroup.new("WsnameActions") actiongroup.add_actions(actions, None) applet.setup_menu(menuxml, actiongroup) self.init() def _display_about(self, action): about = Gtk.AboutDialog() about.set_program_name("Workspace Name Applet") about.set_version(wsnamelet_globals.version) about.set_copyright("© 2006 - 2015 Alexandre Muñiz") about.set_comments("View and change the name of the current workspace.\n\nTo change the workspace name, click on the applet, type the new name, and press Enter.") about.set_website("https://github.com/munizao/mate-workspace-name-applet") about.connect ("response", lambda self, *args: self.destroy ()) about.show_all() def _display_prefs(self, action): self.prefs.dialog.show_all() self.prefs.dialog.run() self.prefs.dialog.hide() def set_width(self, width): self.width = width self.button.set_size_request(width, -1) self.button.queue_resize() self.entry.set_size_request(width, -1) self.entry.queue_resize() def on_width_changed(self, settings, key): width = settings.get_int(key) self.set_width(width) def init(self): self.button = Gtk.Button() self.button.connect("button-press-event", self._on_button_press) self.button.connect("button-release-event", self._on_button_release) self.label = Gtk.Label() self.label.set_ellipsize(Pango.EllipsizeMode.END) self.applet.add(self.button) self.button.add(self.label) self.entry = WSNameEntry(self) self.entry.connect("button-press-event", self._on_entry_button_press) try: self.settings = Gio.Settings.new("com.puzzleapper.wsname-applet-py") self.set_width(self.settings.get_int("width")) self.settings.connect("changed::width", self.on_width_changed) except: self.set_width(100) self.screen = Wnck.Screen.get_default() self.workspace = really_get_active_workspace(self.screen) self.screen.connect("active_workspace_changed", self._on_workspace_changed) self.button.set_tooltip_text(_("Click to change the name of the current workspace")) self._name_change_handler_id = None self.prefs = WSNamePrefs(self) self.show_workspace_name() self.applet.show_all() return True def _on_button_press(self, button, event, data=None): if event.button != 1: button.stop_emission("button-press-event") def _on_button_release(self, button, event, data=None): if event.type == Gdk.EventType.BUTTON_RELEASE and event.button == 1: self.editing = True self.applet.remove(self.button) self.applet.add(self.entry) self.entry.set_text(self.workspace.get_name()) self.entry.set_position(-1) self.entry.select_region(0, -1) self.applet.request_focus(event.time) GObject.timeout_add(0, self.entry.grab_focus) self.applet.show_all() def _on_entry_button_press(self, entry, event, data=None): self.applet.request_focus(event.time) def _on_workspace_changed(self, event, old_workspace): if self.editing: self.exit_editing() if (self._name_change_handler_id): self.workspace.disconnect(self._name_change_handler_id) self.workspace = really_get_active_workspace(self.screen) self._name_change_handler_id = self.workspace.connect("name-changed", self._on_workspace_name_changed) self.show_workspace_name() def _on_workspace_name_changed(self, event): self.show_workspace_name() def show_workspace_name(self): if self.workspace: self.label.set_text(self.workspace.get_name()) self.applet.show_all() def exit_editing(self): self.editing = False self.applet.remove(self.entry) self.applet.add(self.button) def really_get_active_workspace(screen): # This bit is needed because wnck is asynchronous. while Gtk.events_pending(): Gtk.main_iteration() return screen.get_active_workspace() def applet_factory(applet, iid, data): WSNameApplet(applet) return True MatePanelApplet.Applet.factory_main("WsnameAppletFactory", True, MatePanelApplet.Applet.__gtype__, applet_factory, None)
munizao/mate-workspace-name-applet
wsname_applet.py
Python
gpl-2.0
7,780
# -*- coding: utf-8 -*- """ Created on Wed Aug 19 17:08:36 2015 @author: jgimenez """ from PyQt4 import QtGui, QtCore import os import time import subprocess types = {} types['p'] = 'scalar' types['U'] = 'vector' types['p_rgh'] = 'scalar' types['k'] = 'scalar' types['epsilon'] = 'scalar' types['omega'] = 'scalar' types['alpha'] = 'scalar' types['nut'] = 'scalar' types['nuTilda'] = 'scalar' types['nuSgs'] = 'scalar' unknowns = ['U','p','p_rgh','alpha','k','nuSgs','epsilon','omega','nuTilda','nut'] def drange(start, stop, step): r = start while r < stop: yield r r += step def command_window(palette): brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ToolTipText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Button, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Light, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Mid, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Shadow, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.AlternateBase, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 220)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipBase, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ToolTipText, brush) def currentFields(currentFolder,filterTurb=True,nproc=1): #veo los campos que tengo en el directorio inicial timedir = 0 currtime = 0 logname = '%s/dirFeatures.log'%currentFolder logerrorname = '%s/error.log'%currentFolder #print 'nproc: %s'%nproc if nproc<=1: command = 'dirFeaturesFoam -case %s 1> %s 2> %s' % (currentFolder,logname,logerrorname) else: command = 'mpirun -np %s dirFeaturesFoam -case %s -parallel 1> %s 2> %s' % (nproc,currentFolder,logname,logerrorname) #print 'command: %s'%command #p = subprocess.Popen([command],shell=True) #p.wait() os.system(command) log = open(logname, 'r') for linea in log: if "Current Time" in linea: currtime = linea.split('=')[1].strip() timedir = '%s/%s'%(currentFolder,currtime) from PyFoam.RunDictionary.ParsedParameterFile import ParsedParameterFile #Levanto todos los campos y me fijo cual se ca a utilizar (dependiendo del turbulence model) allturb = ['k','epsilon','omega','nuSgs','nut','nuTilda'] #le dejo los que voy a utilizar filename = '%s/constant/turbulenceProperties'%currentFolder e=False try: tprop = ParsedParameterFile(filename,createZipped=False) except IOError as e: tprop = {} if (not e): if tprop['simulationType']=='RASModel': filename = '%s/constant/RASProperties'%currentFolder Rprop = ParsedParameterFile(filename,createZipped=False) if Rprop['RASModel']=='kEpsilon': allturb.remove('k') allturb.remove('epsilon') if Rprop['RASModel']=='kOmega' or Rprop['RASModel']=='kOmegaSST': allturb.remove('k') allturb.remove('omega') elif tprop['simulationType']=='LESModel': filename = '%s/constant/LESProperties'%currentFolder Lprop = ParsedParameterFile(filename,createZipped=False) if Lprop['LESModel']=='Smagorinsky': allturb.remove('nuSgs') NO_FIELDS = ['T0', 'T1', 'T2', 'T3', 'T4', 'nonOrth', 'skew'] if filterTurb: for it in allturb: NO_FIELDS.append(it) command = 'rm -f %s/*~ %s/*.old'%(timedir,timedir) os.system(command) while not os.path.isfile(logname): continue #Esta linea la agrego porque a veces se resetea el caso y se borra #el folder de currentTime. Por eso uso el 0, siempre estoy seguro que #esta presente if not os.path.isdir(str(timedir)): timedir = '%s/0'%currentFolder fields = [ f for f in os.listdir(timedir) if (f not in NO_FIELDS and f in unknowns) ] return [timedir,fields,currtime] def backupFile(f): filename = f if os.path.isfile(filename) and os.path.getsize(filename) > 0: newfilepath = filename+'.backup' command = 'cp %s %s'%(filename,newfilepath) os.system(command) def get_screen_resolutions(): output = subprocess.Popen('xrandr | grep "\*" | cut -d" " -f4',shell=True, stdout=subprocess.PIPE).communicate()[0] resolution = output.split()[0].split(b'x') return resolution
jmarcelogimenez/petroSym
petroSym/utils.py
Python
gpl-2.0
11,739
import os import numpy as np import matplotlib.pyplot as plt from matplotlib import cm, colors initDir = '../init/' nlat = 31 nlon = 30 # Dimensions L = 1.5e7 c0 = 2 timeDim = L / c0 / (60. * 60. * 24) H = 200 tau_0 = 1.0922666667e-2 delta_T = 1. sampFreq = 0.35 / 0.06 * 12 # (in year^-1) # Case definition muRng = np.array([2.1, 2.5, 2.7, 2.75, 2.8, 2.85, 2.9, 2.95, 3., 3.1, 3.3, 3.7]) #amu0Rng = np.arange(0.1, 0.51, 0.1) #amu0Rng = np.array([0.2]) amu0Rng = np.array([0.75, 1.]) #epsRng = np.arange(0., 0.11, 0.05) epsRng = np.array([0.]) sNoise = 'without noise' # spinup = int(sampFreq * 10) # timeWin = np.array([0, -1]) spinup = 0 timeWin = np.array([0, int(sampFreq * 1000)]) neof = 1 prefix = 'zc' simType = '_%deof_seasonal' % (neof,) indicesDir = '../observables/' field_h = (1, 'Thermocline depth', r'$h$', 'm', H, r'$h^2$') field_T = (2, 'SST', 'T', r'$^\circ C$', delta_T, r'$(^\circ C)^2$') #field_u_A = (3, 'Wind stress due to coupling', r'$u_A$', 'm/s', tau_0) #field_taux = (4, 'External wind-stress', 'taux', 'm/s', tau_0) # Indices definition # Nino3 #nino3Def = ('NINO3', 'nino3') nino3Def = ('Eastern', 'nino3') # Nino4 #nino4Def = ('NINO4', 'nino4') nino4Def = ('Western', 'nino4') # Field and index choice fieldDef = field_T indexDef = nino3Def #fieldDef = field_h #indexDef = nino4Def #fieldDef = field_u_A #indexDef = nino4Def #fieldDef = field_taux #indexDef = nino4Def fs_default = 'x-large' fs_latex = 'xx-large' fs_xlabel = fs_default fs_ylabel = fs_default fs_xticklabels = fs_default fs_yticklabels = fs_default fs_legend_title = fs_default fs_legend_labels = fs_default fs_cbar_label = fs_default # figFormat = 'eps' figFormat = 'png' dpi = 300 for eps in epsRng: for amu0 in amu0Rng: for mu in muRng: postfix = '_mu%04d_amu0%04d_eps%04d' \ % (np.round(mu * 1000, 1), np.round(amu0 * 1000, 1), np.round(eps * 1000, 1)) resDir = '%s%s%s/' % (prefix, simType, postfix) indicesPath = '%s/%s' % (indicesDir, resDir) pltDir = resDir os.system('mkdir %s %s 2> /dev/null' % (pltDir, indicesPath)) # Read dataset indexData = np.loadtxt('%s/%s.txt' % (indicesPath, indexDef[1])) timeND = indexData[:, 0] timeFull = timeND * timeDim / 365 indexFull = indexData[:, fieldDef[0]] * fieldDef[4] # Remove spinup index = indexFull[spinup:] time = timeFull[spinup:] nt = time.shape[0] # Plot time-series linewidth = 2 fig = plt.figure() ax = fig.add_subplot(111) ax.plot(time[timeWin[0]:timeWin[1]], index[timeWin[0]:timeWin[1]], linewidth=linewidth) # plt.title('Time-series of %s averaged over %s\nfor mu = %.4f and eps = %.4f' % (fieldDef[1], indexDef[0], mu, eps)) ax.set_xlabel('years', fontsize=fs_latex) ax.set_ylabel('%s %s (%s)' \ % (indexDef[0], fieldDef[1], fieldDef[3]), fontsize=fs_latex) # ax.set_xlim(0, 250) # ax.set_ylim(29.70, 30.) plt.setp(ax.get_xticklabels(), fontsize=fs_xticklabels) plt.setp(ax.get_yticklabels(), fontsize=fs_yticklabels) fig.savefig('%s/%s%s%s.png' % (pltDir, indexDef[1], fieldDef[2], postfix), bbox_inches='tight') # Get periodogram of zonal wind stress averaged over index nRAVG = 1 window = np.hamming(nt) # Get nearest larger power of 2 if np.log2(nt) != int(np.log2(nt)): nfft = 2**(int(np.log2(nt)) + 1) else: nfft = nt # Get frequencies and shift zero frequency to center freq = np.fft.fftfreq(nfft, d=1./sampFreq) freq = np.fft.fftshift(freq) ts = index - index.mean(0) # Apply window tsWindowed = ts * window # Fourier transform and shift zero frequency to center fts = np.fft.fft(tsWindowed, nfft, 0) fts = np.fft.fftshift(fts) # Get periodogram perio = np.abs(fts / nt)**2 # Apply running average perioRAVG = perio.copy() for iavg in np.arange(nRAVG/2, nfft-nRAVG/2): perioRAVG[iavg] = perio[iavg-nRAVG/2:iavg+nRAVG/2 + 1].mean()\ / nRAVG # Plot fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(freq, np.log10(perioRAVG), '-k') # ax.set_xscale('log') # ax.set_yscale('log') ax.set_xlim(0, 4) #ax.set_ylim(0, vmax) ax.set_xlabel(r'years$^{-1}$', fontsize=fs_latex) ax.set_ylabel(fieldDef[5], fontsize=fs_latex) plt.setp(ax.get_xticklabels(), fontsize=fs_xticklabels) plt.setp(ax.get_yticklabels(), fontsize=fs_yticklabels) xlim = ax.get_xlim() ylim = ax.get_ylim() ax.text(xlim[0] + 0.2 * (xlim[1] - xlim[0]), ylim[0] + 0.1 * (ylim[1] - ylim[0]), r'$\mu = %.3f$ %s' % (mu, sNoise), fontsize=32) # plt.title('Periodogram of %s averaged over %s\nfor mu = %.1f and eps = %.2f' % (fieldDef[1], indexDef[0], mu, eps)) fig.savefig('%s/%s%sPerio%s.%s' \ % (pltDir, indexDef[1], fieldDef[2], postfix, figFormat), bbox_inches='tight', dpi=dpi)
atantet/transferCZ
plot/plot_index_loop_seasonal.py
Python
gpl-2.0
5,743
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "annotator.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
richard-schwab/annotatorjs-django
manage.py
Python
gpl-2.0
252
# _dialogs.py import wx import _widgets as _wgt from wx.lib.wordwrap import wordwrap __version__ = '1.0.0' import logging log = logging.getLogger('root') class CustomDialog(wx.Dialog): def __init__(self, parent, *arg, **kw): style = (wx.NO_BORDER | wx.CLIP_CHILDREN) self.borderColour = wx.BLACK wx.Dialog.__init__(self, parent, title='Fancy', style = style) self.Bind(wx.EVT_MOTION, self.OnMouse) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnSetBorderColour(self, color): self.borderColour = color def OnPaint(self, event): evtObj = event.GetEventObject() evtObjBG = evtObj.GetBackgroundColour() dc = wx.PaintDC(evtObj) dc = wx.GCDC(dc) w, h = self.GetSizeTuple() r = 10 dc.SetPen( wx.Pen(self.borderColour,3) ) dc.SetBrush( wx.Brush(evtObjBG)) dc.DrawRectangle( 0,0,w,h ) def OnMouse(self, event): """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 ) self.ReleaseMouse() event.Skip() class MyMessageDialog(CustomDialog): def __init__(self, parent, msg, myStyle, *arg, **kw): self._msg = msg self._style = myStyle super(MyMessageDialog, self).__init__(parent, *arg, **kw) self._panel = wx.Panel(self) self._message = wordwrap(str(self._msg), 350, wx.ClientDC(self)) self.stcText = wx.StaticText(self._panel, -1, self._message) self.stcText.SetFocus() self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK') mainSizer = wx.BoxSizer(wx.HORIZONTAL) panelSizer = wx.BoxSizer(wx.VERTICAL) panelSizer.Add(self.stcText, 1, wx.ALL|wx.EXPAND|wx.CENTRE, 2) btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer.Add(self.btnOk, 0, wx.ALL|wx.CENTRE, 5) if self._style != None and 'INC_CANCEL' in self._style: self.btnCancel = _wgt.CustomPB(self._panel, id=wx.ID_CANCEL, label='Cancel') btnSizer.Add(self.btnCancel, 0, wx.ALL|wx.CENTRE, 5) panelSizer.Add(btnSizer, 0, wx.ALL|wx.CENTRE, 5) self._panel.SetSizer(panelSizer) mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND|wx.CENTRE, 2) self.SetSizerAndFit(mainSizer) self._panel.Bind(wx.EVT_MOTION, self.OnMouse) self.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.ID_OK) self.CenterOnParent() def OnOk(self, event): self.EndModal(wx.ID_OK) class ClearBtnLocks(CustomDialog): def __init__(self, parent, *arg, **kw): super(ClearBtnLocks, self).__init__(parent, *arg, **kw) self.parent = parent self.OnInitUI() self.OnInitLayout() self.OnBindEvents() self.CenterOnParent() self.OnSetBorderColour(wx.Colour(46,139,87,255)) def OnInitUI(self): self._panel = wx.Panel(self) self.cbDayStart = wx.CheckBox(self._panel, -1, 'Clear Start of Day') self.cbLunchStart = wx.CheckBox(self._panel, -1, 'Clear Start of Lunch') self.cbLunchEnd = wx.CheckBox(self._panel, -1, 'Clear End of Lunch') self.cbDayEnd = wx.CheckBox(self._panel, -1, 'Clear End of Day') self.cbCheckAll = wx.CheckBox(self._panel, 0, 'Select All') self.cbList = ( self.cbDayStart, self.cbLunchStart, self.cbLunchEnd, self.cbDayEnd ) self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK') self.btnCancel = _wgt.CustomPB(self._panel, id=wx.ID_CANCEL, label='Cancel') def OnInitLayout(self): mainSizer = wx.BoxSizer(wx.HORIZONTAL) panelSizer = wx.BoxSizer(wx.VERTICAL) statBox = wx.StaticBox(self._panel, label='Which Buttons to Enable?') sbSizer = wx.StaticBoxSizer(statBox, wx.VERTICAL) cbSizer = wx.FlexGridSizer(3, 2, 3, 3) cbSizer.AddMany( [ (self.cbDayStart, 0, wx.ALL, 1), (self.cbLunchStart, 0, wx.ALL, 1), (self.cbLunchEnd, 0, wx.ALL, 1), (self.cbDayEnd, 0, wx.ALL, 1), (self.cbCheckAll, 0, wx.ALL, 1) ] ) sbSizer.Add(cbSizer, 0, wx.ALL, 1) btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer.Add(self.btnOk, 0, wx.ALL, 5) btnSizer.Add(self.btnCancel, 0, wx.ALL, 5) sbSizer.Add(btnSizer, 1, wx.ALL|wx.CENTRE, 1) panelSizer.Add(sbSizer, 0, wx.ALL | wx.EXPAND, 5) self._panel.SetSizer(panelSizer) mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND|wx.CENTRE, 2) self.SetSizerAndFit(mainSizer) def OnBindEvents(self): self._panel.Bind(wx.EVT_MOTION, self.OnMouse) self.Bind(wx.EVT_BUTTON, self.OnOk, id=wx.ID_OK) for cbOption in self.cbList: cbOption.Bind(wx.EVT_CHECKBOX, self.ClearSelectAll) self.cbCheckAll.Bind(wx.EVT_CHECKBOX, self.OnSelectAll) def OnSelectAll(self, event): if self.cbCheckAll.GetValue(): self.cbDayStart.SetValue(True) self.cbLunchStart.SetValue(True) self.cbLunchEnd.SetValue(True) self.cbDayEnd.SetValue(True) else: self.cbDayStart.SetValue(False) self.cbLunchStart.SetValue(False) self.cbLunchEnd.SetValue(False) self.cbDayEnd.SetValue(False) def ClearSelectAll(self, event): self.cbCheckAll.SetValue(False) def OnOk(self, event): log.debug('User prompted: Confirm button reset.') _msg = 'You are about to reset button locks!\nDo you wish to continue?' _style = 'INC_CANCEL' dlg = MyMessageDialog(self, msg=_msg, myStyle=_style) dlg.OnSetBorderColour(wx.Colour(255,165,0,255)) if dlg.ShowModal() == wx.ID_OK: if self.cbDayStart.GetValue(): self.parent.btnStartDay.Enable(True) self.parent.txtStartDay.SetValue('') log.debug( '\'Start of Day\' button enabled by user.') if self.cbLunchStart.GetValue(): self.parent.btnStartLunch.Enable(True) self.parent.txtStartLunch.SetValue('') log.debug( '\'Start of Lunch\' button enabled by user.') if self.cbLunchEnd.GetValue(): self.parent.btnEndLunch.Enable(True) self.parent.txtEndLunch.SetValue('') log.debug( '\'End of Lunch\' button enabled by user.') if self.cbDayEnd.GetValue(): self.parent.btnEndDay.Enable(True) self.parent.txtEndDay.SetValue('') log.debug( '\'End of Day\' button enabled by user.') event.Skip() self.EndModal(wx.ID_OK) def OnCancel(self, event): self.EndModal(wx.ID_CANCEL) class EnterEmail(CustomDialog): def __init__(self, parent, eType, *arg, **kw): self.eType = eType super(EnterEmail, self).__init__(parent, *arg, **kw) self.parent = parent self.idEmail = wx.NewId() self.OnInitUI() self.OnInitLayout() self.OnBindEvents() self.OnSetBorderColour(wx.Colour(205,133,63,255)) def OnInitUI(self): self._panel = wx.Panel(self) self.sb = wx.StaticBox(self._panel, label='') self.dEmail = wx.TextCtrl(self._panel, id=self.idEmail, value='', style=wx.TE_PROCESS_ENTER|wx.SIMPLE_BORDER) if self.eType == 'DEST': self.sb.SetLabel('Confirm destination email address:') #log.debug( # 'User is updating Destination email address.') self.dEmail.SetValue('enter @ default . email') elif self.eType == 'CC': #log.debug( # 'User is updating CC email address.') self.sb.SetLabel('Enter email address to CC:') elif self.eType == 'BUG': self.sb.SetLabel('Confirm email address for Bug Reports:') self.dEmail.SetValue('bug @ report . email') self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK') self.btnCancel = _wgt.CustomPB(self._panel, id=wx.ID_CANCEL, label='Cancel') def OnInitLayout(self): mainSizer = wx.BoxSizer(wx.HORIZONTAL) panelSizer = wx.BoxSizer(wx.VERTICAL) sbSizer1 = wx.StaticBoxSizer(self.sb, wx.VERTICAL) sbSizer1.Add(self.dEmail, 1, wx.ALL|wx.EXPAND, 5) btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer.Add(self.btnOk, 1, wx.ALL, 5) btnSizer.Add(self.btnCancel, 1, wx.ALL, 5) sbSizer1.Add(btnSizer, 1, wx.ALL|wx.EXPAND, 5) panelSizer.Add(sbSizer1, 1, wx.ALL|wx.EXPAND, 3) self._panel.SetSizer(panelSizer) mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND, 2) self.SetSizerAndFit(mainSizer) self.SetPosition( (400,300) ) def OnBindEvents(self): self._panel.Bind(wx.EVT_MOTION, self.OnMouse) self.dEmail.Bind(wx.EVT_TEXT_ENTER, self.OnOk) def GetAddress(self): emailAddress = self.dEmail.GetValue() if '@' in emailAddress and '.' in emailAddress.split('@')[1]: return emailAddress else: return '' def OnOk(self, event): self.EndModal(wx.ID_OK) class ViewEmail(CustomDialog): def __init__(self, parent, eType, eMail, *arg, **kw): self.eType = eType self.eMail = eMail super(ViewEmail, self).__init__(parent, *arg, **kw) self.OnInitUI() self.OnInitLayout() self.OnSetBorderColour(wx.Colour(55,95,215,255)) def OnInitUI(self): self._panel = wx.Panel(self) self.statBox = wx.StaticBox(self._panel, label='') self.statEmail = wx.StaticText(self._panel, label='') statFont = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.NORMAL) self.statEmail.SetFont(statFont) if self.eType == 'DEST': self.statBox.SetLabel('Destination Address:') elif self.eType == 'CC': self.statBox.SetLabel('\'Carbon Copy\' Address:') elif self.eType == 'BUG': self.statBox.SetLabel('\'Bug Report\' Address:') emailString = wordwrap( str(self.eMail), 350,wx.ClientDC(self._panel)) self.statEmail.SetLabel(emailString) self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK') def OnInitLayout(self): mainSizer = wx.BoxSizer(wx.HORIZONTAL) panelSizer = wx.BoxSizer(wx.VERTICAL) sbSizer1 = wx.StaticBoxSizer(self.statBox, wx.VERTICAL) sbSizer1.Add(self.statEmail, 1, wx.ALL|wx.CENTER, 3) btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer.Add(self.btnOk, 1, wx.ALL|wx.CENTER, 5) sbSizer1.Add(btnSizer, 1, wx.ALL|wx.CENTER, 5) panelSizer.Add(sbSizer1, 1, wx.ALL|wx.EXPAND, 5) self._panel.SetSizer(panelSizer) mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND, 3) self.SetSizerAndFit(mainSizer) def OnOk(self, event): if self.IsModal(): self.EndModal(wx.ID_OK) class AboutWindow(CustomDialog): def __init__(self, parent, ver, *arg, **kw): self._ver = ver super(AboutWindow, self).__init__(parent, *arg, **kw) '''Create and define the About dialog window.''' self._idHyperlink = wx.NewId() self.OnInitWidgets() self.OnInitLayout() self.OnBindEvents() self.CenterOnParent() def OnInitWidgets(self): self._panel = wx.Panel(self) self.titleText = wx.StaticText(self._panel, -1, 'Clock Punch v%s' % self._ver) titleFont = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.BOLD) self.titleText.SetFont(titleFont) self.webLink = _wgt.CustomHyperlink(self._panel, self._idHyperlink, label = 'Written using Python', url = "http://en.wikipedia.org/wiki/Python_programming_language" ) description = wordwrap( "This is the Clock Puncher." " \n-The original Time Punch application re-written." " \nIt allows you to easily send the various time punch" " emails at the click of a button." "\n\nPlease do not report any issues with this program to DS IT as" " it is not an officially supported application.", 350, wx.ClientDC(self)) self.descText = wx.StaticText(self._panel, -1, description) self.licenseHeader = wx.StaticText(self._panel, -1, 'Licensing:') licenseFont = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.BOLD) self.licenseHeader.SetFont(licenseFont) license = wordwrap('Main program: GPL v3' '\nPython: PSF License' '\npyWin32: PSF License' '\nWMI: MIT License' '\nwxPython: wxWidgets License', 350, wx.ClientDC(self)) self.licenseText = wx.StaticText(self._panel, -1, license) self.devHeader = wx.StaticText(self._panel, -1, 'Developer(s):') devFont = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.BOLD) self.devHeader.SetFont(devFont) developers = wordwrap( 'Program Writer:' '\nMichael Stover', 500, wx.ClientDC(self)) self.devText = wx.StaticText(self._panel, -1, developers) self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK', size=(50,-1)) def OnInitLayout(self): mainSizer = wx.BoxSizer(wx.HORIZONTAL) panelSizer = wx.BoxSizer(wx.VERTICAL) titleSizer = wx.BoxSizer(wx.HORIZONTAL) titleSizer.Add(self.titleText, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER, 2) descriptSizer = wx.BoxSizer(wx.VERTICAL) descriptSizer.Add(self.descText, 1, wx.ALL|wx.EXPAND, 2) descriptSizer.Add(self.webLink, 0, wx.ALL, 2) licenseSizer = wx.BoxSizer(wx.VERTICAL) licenseSizer.Add(self.licenseHeader, 0, wx.ALL|wx.EXPAND|wx.CENTER, 2) licenseSizer.Add(self.licenseText, 1, wx.ALL|wx.EXPAND, 2) developSizer = wx.BoxSizer(wx.VERTICAL) developSizer.Add(self.devHeader, 0, wx.ALL|wx.EXPAND|wx.CENTER, 2) developSizer.Add(self.devText, 1, wx.ALL|wx.EXPAND, 2) buttonSizer = wx.BoxSizer(wx.HORIZONTAL) buttonSizer.Add(self.btnOk, 0, wx.ALL|wx.ALIGN_RIGHT, 2) panelSizer.Add(titleSizer, 0, wx.ALL|wx.EXPAND|wx.ALIGN_CENTER, 2) panelSizer.Add(descriptSizer, 0, wx.ALL|wx.EXPAND, 2) panelSizer.Add(wx.StaticLine( self._panel, -1, style=wx.LI_HORIZONTAL ), 1, wx.ALL|wx.EXPAND, 5 ) panelSizer.Add(licenseSizer, 0, wx.ALL|wx.EXPAND, 2) panelSizer.Add(wx.StaticLine( self._panel, -1, style=wx.LI_HORIZONTAL ), 1, wx.ALL|wx.EXPAND, 5 ) panelSizer.Add(developSizer, 0, wx.ALL|wx.EXPAND, 2) panelSizer.Add(buttonSizer, 0, wx.ALL|wx.ALIGN_CENTER, 2) self._panel.SetSizer(panelSizer) mainSizer.Add(self._panel, 1, wx.ALL|wx.EXPAND, 2) self.SetSizerAndFit(mainSizer) def OnBindEvents(self): self.Bind(wx.EVT_HYPERLINK, self.OnLinkClicked, id=self._idHyperlink) self._panel.Bind(wx.EVT_MOTION, self.OnMouse) def OnLinkClicked(self, event=None): evtObj = event.GetEventObject() if isinstance(evtObj, wx.HyperlinkCtrl): print evtObj.GetURL() def OnOk(self, event): if self.IsModal(): self.EndModal(wx.ID_OK) class HelpWindow(CustomDialog): def __init__(self, parent, *arg, **kw): super(HelpWindow, self).__init__(parent, *arg, **kw) pass class BugReport(CustomDialog): def __init__(self, parent, *arg, **kw): super(BugReport, self).__init__(parent, *arg, **kw) self.OnSetBorderColour(wx.Colour(153, 0, 0, 255)) self.OnInitUI() self.OnInitLayout() self.OnBindEvents() def OnInitUI(self): self._panel = wx.Panel(self) self._panel.SetBackgroundColour(wx.Colour(230,230,230,255)) self._titleBox = wx.StaticText( self._panel, -1, ' Bug Report Submission', style=wx.NO_BORDER ) titleFont = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.BOLD) self._titleBox.SetFont(titleFont) self._titleBox.SetBackgroundColour(wx.WHITE) summary = wordwrap( 'Thank you for taking this opportunity to submit ' 'a bug report for this program.\n\nPlease enter a ' 'brief description into the box below. I will ' 'investigate the bug report as soon as possible.' '\n\nUpon clicking Submit the program will also ' 'locate and collect any logs for review. These ' 'will be sent as attachments to the email.' '\n\nNo personal information is collected.' '\nYou will be able to preview the report before ' 'it is sent.', 350, wx.ClientDC(self)) self.bugTips = wx.StaticText(self._panel, -1, summary, style=wx.NO_BORDER|wx.TE_CENTER ) self.bugTips.SetBackgroundColour(wx.WHITE) self.summaryBox = wx.TextCtrl(self._panel, -1, value='', style=wx.TE_MULTILINE|wx.SIMPLE_BORDER) self.btnOk = _wgt.CustomPB(self._panel, id=wx.ID_OK, label='OK') self.btnCancel = _wgt.CustomPB(self._panel, id=wx.ID_CANCEL, label='Cancel') def OnInitLayout(self): mainSizer = wx.BoxSizer(wx.HORIZONTAL) panelSizer = wx.BoxSizer(wx.VERTICAL) titleSizer = wx.BoxSizer(wx.HORIZONTAL) titleSizer.Add(self._titleBox, 1, wx.ALL|wx.EXPAND, 3) panelSizer.Add(titleSizer, 0, wx.EXPAND|wx.CENTRE, 3) tipsSizer = wx.BoxSizer(wx.HORIZONTAL) tipsSizer.Add(self.bugTips, 1, wx.EXPAND, 3) panelSizer.Add(tipsSizer, 1, wx.ALL|wx.EXPAND, 3) summarySizer = wx.BoxSizer(wx.HORIZONTAL) summarySizer.Add(self.summaryBox, 1, wx.ALL|wx.EXPAND, 3) panelSizer.Add(summarySizer, 1, wx.ALL|wx.EXPAND, 1) buttonSizer = wx.BoxSizer(wx.HORIZONTAL) buttonSizer.Add(self.btnOk, 1, wx.ALL, 3) buttonSizer.Add(self.btnCancel, 1, wx.ALL, 3) panelSizer.Add(buttonSizer, 0, wx.EXPAND, 1) self._panel.SetSizer(panelSizer) mainSizer.Add(self._panel, 1, wx.ALL, 3) self.SetSizerAndFit(mainSizer) def OnBindEvents(self): self._panel.Bind(wx.EVT_MOTION, self.OnMouse) self._titleBox.Bind(wx.EVT_MOTION, self.OnMouse) self.bugTips.Bind(wx.EVT_MOTION, self.OnMouse) def OnGetSummary(self, event=None): return self.summaryBox.GetValue() def OnClose(self, event): self.EndModal(event.GetId()) import logging log = logging.getLogger('root') log.debug('Dialogs Module %s Initialized.' % __version__)
Hakugin/TimeClock
_dialogs.py
Python
gpl-2.0
19,476
""" WSGI config for SysuLesson 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.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SysuLesson.settings") application = get_wsgi_application()
chenzeyuczy/keba
src/SysuLesson/wsgi.py
Python
gpl-2.0
397
# -- coding: utf-8 -- # Das Modul argv aus Packet sys wird importiert from sys import argv # Die Variablen script und filename werden entpackt # sie müssen dem Script als Argumente mitgegeben werden beim ausführen # z.B so: python ex15_reading_files.py ex15_sample.txt script, filename = argv # Der Inhalt der Datei ex15_sample.txt, der # dem Script beim Ausführen als Argument mitgegeben wurde, # wird in die Variable txt geschrieben txt = open(filename) # Der Dateiname von ex15_sample.txt wird ausgegeben print "Here's your file %r:" % filename # Der Inhalt von txt (und damit der Inhalt von ex15_sample.txt) wird ausgegeben print txt.read() # Man könnte denken, dass man es auch so machen könnte ... # print 'ex15_sample.txt'.read() # aber das geht NICHT, weil # String kein Attribut read haben!!! # AttributeError: 'str' object has no attribute 'read' print "Type the filename again:" # neue Eingabeaufforderung, dadurch wird der Inhalt der Datei (deren Namen man eingibt) # in die Variable file_again geschrieben file_again = open(raw_input("> ")) # Der Inhalt von file_again wird ausgegeben print file_again.read(), 'geht!!!' # Inhalt von ex15_sample.txt wird in die Variable txt_again geschrieben txt_again = open('ex15_sample.txt') # Inhalt von txt_again wird ausgegeben print txt_again.read(), 'das geht auch'
Tset-Noitamotua/_learnpython
LearnPythonTheHardWay/ex15_reading_files.py
Python
gpl-2.0
1,354
# coding=utf-8 """DockWidget test. .. note:: 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. """ __author__ = '[email protected]' __date__ = '2016-12-20' __copyright__ = 'Copyright 2016, neeraj' import unittest from PyQt4.QtGui import QDockWidget from pt_stop_calc_dockwidget import PTStopCalcDockWidget from utilities import get_qgis_app QGIS_APP = get_qgis_app() class PTStopCalcDockWidgetTest(unittest.TestCase): """Test dockwidget works.""" def setUp(self): """Runs before each test.""" self.dockwidget = PTStopCalcDockWidget(None) def tearDown(self): """Runs after each test.""" self.dockwidget = None def test_dockwidget_ok(self): """Test we can click OK.""" pass if __name__ == "__main__": suite = unittest.makeSuite(PTStopCalcDialogTest) runner = unittest.TextTestRunner(verbosity=2) runner.run(suite)
NiekB4/2016_Group07_Transit-BuiltEnvironment
PTStopCalc_Plugin_Neeraj/test/test_pt_stop_calc_dockwidget.py
Python
gpl-2.0
1,110
from django.db import models from django_crypto_fields.fields import EncryptedTextField from edc_base.model.models import BaseUuidModel try: from edc_sync.mixins import SyncMixin except ImportError: SyncMixin = type('SyncMixin', (object, ), {}) from ..managers import CallLogManager class CallLog (SyncMixin, BaseUuidModel): """Maintains a log of calls for a particular participant.""" subject_identifier = models.CharField( verbose_name="Subject Identifier", max_length=50, blank=True, db_index=True, unique=True, ) locator_information = EncryptedTextField( help_text=('This information has been imported from' 'the previous locator. You may update as required.') ) contact_notes = EncryptedTextField( null=True, blank=True, help_text='' ) label = models.CharField( max_length=25, null=True, editable=False, help_text="from followup list" ) # history = AuditTrail() objects = CallLogManager() def natural_key(self): return self.subject_identifier class Meta: app_label = 'edc_contact'
botswana-harvard/edc-contact
edc_contact/models/call_log.py
Python
gpl-2.0
1,199
# SecuML # Copyright (C) 2016-2017 ANSSI # # SecuML 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. # # SecuML 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 SecuML. If not, see <http://www.gnu.org/licenses/>. import copy import pandas as pd import scipy from SecuML.core.Tools import matrix_tools from .AnnotationQuery import AnnotationQuery class Category(object): def __init__(self, label=None, family=None): self.assignLabelFamily(label, family) self.instances_ids = [] self.probas = [] self.entropy = [] self.likelihood = [] self.df = None self.annotation_queries = {} self.annotated_instances = [] self.num_annotated_instances = 0 # To display the annotation queries in the web GUI self.queries = [] self.queries_confidence = [] def generateAnnotationQuery(self, instance_id, predicted_proba, suggested_label, suggested_family, confidence=None): return AnnotationQuery(instance_id, predicted_proba, suggested_label, suggested_family, confidence=confidence) def assignLabelFamily(self, label, family): self.family = family if label != 'all': self.label = label else: self.label = label def numInstances(self): return len(self.instances_ids) def setWeight(self, weight): self.weight = weight def setNumAnnotations(self, num_annotations): self.num_annotations = num_annotations def addInstance(self, instance_id, probas, annotated): self.instances_ids.append(instance_id) entropy = None proba = None likelihood = None if probas is not None: entropy = scipy.stats.entropy(probas) proba = max(probas) self.entropy.append(entropy) self.probas.append(proba) self.likelihood.append(likelihood) if annotated: self.annotated_instances.append(instance_id) self.num_annotated_instances += 1 def finalComputation(self): self.df = pd.DataFrame({'proba': self.probas, 'entropy': self.entropy, 'likelihood': self.likelihood}, index=list(map(str, self.instances_ids))) def annotateAuto(self, iteration): for k, queries in self.annotation_queries.items(): for q, query in enumerate(queries): query.annotateAuto(iteration, self.label) def getManualAnnotations(self, iteration): for k, queries in self.annotation_queries.items(): for q, query in enumerate(queries): query.getManualAnnotation(iteration) def checkAnnotationQueriesAnswered(self, iteration): for k, queries in self.annotation_queries.items(): for q, query in enumerate(queries): if not query.checkAnswered(iteration): return False return True def setLikelihood(self, likelihood): self.likelihood = likelihood self.df['likelihood'] = likelihood def getLikelihood(self, instances): df = pd.DataFrame({'likelihood': self.likelihood}, index=list(map(str, self.instances_ids))) selected_df = df.loc[list(map(str, instances)), :] return selected_df['likelihood'].tolist() def getCategoryLabel(self): return self.label def getCategoryFamily(self): return self.family def toJson(self): obj = {} obj['label'] = self.label obj['family'] = self.family obj['annotation_queries'] = {} for kind, queries in self.annotation_queries.items(): obj['annotation_queries'][kind] = [] for q, query in enumerate(queries): obj['annotation_queries'][kind].append(query.toJson()) return obj @staticmethod def fromJson(obj): category = Category() category.instances_ids = obj['instances_ids'] category.label = obj['label'] return category def exportAnnotationQueries(self): annotation_queries = {} annotation_queries['instance_ids'] = self.queries annotation_queries['confidence'] = self.queries_confidence annotation_queries['label'] = self.label return annotation_queries def generateAnnotationQueries(self, cluster_strategy): queries_types = cluster_strategy.split('_') num_queries_types = len(queries_types) total_num_queries = 0 annotated_instances = copy.deepcopy(self.annotated_instances) for q, queries_type in enumerate(queries_types): if q == (num_queries_types - 1): num_queries = self.num_annotations - total_num_queries else: num_queries = self.num_annotations // num_queries_types if queries_type == 'center': queries = self.queryHighLikelihoodInstances( annotated_instances, num_queries) elif queries_type == 'anomalous': queries = self.queryLowLikelihoodInstances( annotated_instances, num_queries) elif queries_type == 'uncertain': queries = self.queryUncertainInstances( annotated_instances, num_queries) elif queries_type == 'random': queries = self.queryRandomInstances( annotated_instances, num_queries) else: raise ValueError() annotated_instances += queries total_num_queries += len(queries) assert(total_num_queries == self.num_annotations) def queryUncertainInstances(self, drop_instances, num_instances): if num_instances == 0: return [] queries_df = self.getSelectedInstancesDataframe(drop_instances) matrix_tools.sortDataFrame(queries_df, 'entropy', False, True) queries_df = queries_df.head(num_instances) self.addAnnotationQueries('uncertain', 'low', queries_df) return list(map(int, queries_df.index.values.tolist())) def queryHighLikelihoodInstances(self, drop_instances, num_instances): if num_instances == 0: return [] queries_df = self.getSelectedInstancesDataframe(drop_instances) matrix_tools.sortDataFrame(queries_df, 'likelihood', False, True) queries_df = queries_df.head(num_instances) self.addAnnotationQueries('high_likelihood', 'high', queries_df) return list(map(int, queries_df.index.values.tolist())) def queryLowLikelihoodInstances(self, drop_instances, num_instances): if num_instances == 0: return [] queries_df = self.getSelectedInstancesDataframe(drop_instances) matrix_tools.sortDataFrame(queries_df, 'likelihood', True, True) queries_df = queries_df.head(num_instances) self.addAnnotationQueries('low_likelihood', 'low', queries_df) return list(map(int, queries_df.index.values.tolist())) def queryRandomInstances(self, drop_instances, num_instances): if num_instances == 0: return [] queries_df = self.getSelectedInstancesDataframe(drop_instances) queries_df = queries_df.sample(n=num_instances, axis=0) self.addAnnotationQueries('random', 'low', queries_df) return list(map(int, queries_df.index.values.tolist())) def addAnnotationQueries(self, kind, confidence, queries_df): if kind not in list(self.annotation_queries.keys()): self.annotation_queries[kind] = [] for index, row in queries_df.iterrows(): query = self.generateAnnotationQuery(int(index), row['likelihood'], self.label, self.family, confidence=confidence) self.annotation_queries[kind].append(query) self.queries.append(int(index)) self.queries_confidence.append(confidence) def getSelectedInstancesDataframe(self, drop_instances): if drop_instances is None: selected_instances = self.instances_ids else: selected_instances = [ x for x in self.instances_ids if x not in drop_instances] selected_df = self.df.loc[list(map(str, selected_instances)), :] return selected_df
ah-anssi/SecuML
SecuML/core/ActiveLearning/QueryStrategies/AnnotationQueries/Category.py
Python
gpl-2.0
8,916
#!/usr/bin/env python # -*- coding: utf-8 -*- """ python library for the AR.Drone 1.0 (1.11.5) and 2.0 (2.2.9). parts of code from Bastian Venthur, Jean-Baptiste Passot, Florian Lacrampe. tested with Python 2.7.3 and AR.Drone vanilla firmware 1.11.5. """ # < imports >-------------------------------------------------------------------------------------- import logging import multiprocessing import sys import threading import time import arATCmds import arNetwork import arIPCThread # < variáveis globais >---------------------------------------------------------------------------- # logging level w_logLvl = logging.ERROR # < class ARDrone >-------------------------------------------------------------------------------- class ARDrone ( object ): """ ARDrone class. instanciate this class to control AR.Drone and receive decoded video and navdata. """ # --------------------------------------------------------------------------------------------- # ARDrone::__init__ # --------------------------------------------------------------------------------------------- def __init__ ( self ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::__init__" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.seq_nr = 1 self.timer_t = 0.2 self.com_watchdog_timer = threading.Timer ( self.timer_t, self.commwdg ) self.lock = threading.Lock () self.speed = 0.2 self.at ( arATCmds.at_config, "general:navdata_demo", "TRUE" ) self.vid_pipe, vid_pipe_other = multiprocessing.Pipe () self.nav_pipe, nav_pipe_other = multiprocessing.Pipe () self.com_pipe, com_pipe_other = multiprocessing.Pipe () self.network_process = arNetwork.ARDroneNetworkProcess ( nav_pipe_other, vid_pipe_other, com_pipe_other ) self.network_process.start () self.ipc_thread = arIPCThread.IPCThread ( self ) self.ipc_thread.start () self.image = None self.navdata = {} self.time = 0 # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::apply_command # --------------------------------------------------------------------------------------------- def apply_command ( self, f_command ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::apply_command" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) las_available_commands = [ "emergency", "hover", "land", "move_backward", "move_down", "move_forward", "move_left", "move_right", "move_up", "takeoff", "turn_left", "turn_right", ] # validade command if ( f_command not in las_available_commands ): # sherlock logger # l_log.error ( "Command %s not recognized !" % f_command ) # sherlock logger # l_log.debug ( "<< (E01)" ) return if ( "hover" != f_command ): self.last_command_is_hovering = False if ( "emergency" == f_command ): self.reset () elif (( "hover" == f_command ) and ( not self.last_command_is_hovering )): self.hover () self.last_command_is_hovering = True elif ( "land" == f_command ): self.land () self.last_command_is_hovering = True elif ( "move_backward" == f_command ): self.move_backward () elif ( "move_forward" == f_command ): self.move_forward () elif ( "move_down" == f_command ): self.move_down () elif ( "move_up" == f_command ): self.move_up () elif ( "move_left" == f_command ): self.move_left () elif ( "move_right" == f_command ): self.move_right () elif ( "takeoff" == f_command ): self.takeoff () self.last_command_is_hovering = True elif ( "turn_left" == f_command ): self.turn_left () elif ( "turn_right" == f_command ): self.turn_right () # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::at # --------------------------------------------------------------------------------------------- def at ( self, f_cmd, *args, **kwargs ): """ wrapper for the low level at commands. this method takes care that the sequence number is increased after each at command and the watchdog timer is started to make sure the drone receives a command at least every second. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::at" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.lock.acquire () self.com_watchdog_timer.cancel () f_cmd ( self.seq_nr, *args, **kwargs ) self.seq_nr += 1 self.com_watchdog_timer = threading.Timer ( self.timer_t, self.commwdg ) self.com_watchdog_timer.start () self.lock.release () # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::commwdg # --------------------------------------------------------------------------------------------- def commwdg ( self ): """ communication watchdog signal. this needs to be send regulary to keep the communication with the drone alive. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::commwdg" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_comwdg ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_boom # --------------------------------------------------------------------------------------------- def event_boom ( self ): """ boom event """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_boom" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_THETA_30_DEG # total duration in seconds of the animation lf_secs = 1000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_thetamixed # --------------------------------------------------------------------------------------------- def event_thetamixed ( self ): """ make the drone execute thetamixed ! """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_thetamixed" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_THETA_MIXED # total duration in seconds of the animation lf_secs = 5000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_turnarround # --------------------------------------------------------------------------------------------- def event_turnarround ( self ): """ make the drone turnarround. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_turnarround" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_TURNAROUND # total duration in seconds of the animation lf_secs = 5000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_yawdance # --------------------------------------------------------------------------------------------- def event_yawdance ( self ): """ make the drone execute yawdance YEAH ! """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_yawdance" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_YAW_DANCE # total duration in seconds of the animation lf_secs = 5000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::event_yawshake # --------------------------------------------------------------------------------------------- def event_yawshake ( self ): """ Make the drone execute yawshake YEAH ! """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::event_yawshake" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # animation to play li_anim = arDefs.ARDRONE_LED_ANIMATION_DOUBLE_MISSILE # frequence in HZ of the animation lf_freq = 2. # total duration in seconds of the animation lf_secs = 4 # play LED animation self.at ( arATCmds.at_led, li_anim, lf_freq, lf_secs ) # animation to play li_anim = arDefs.ARDRONE_ANIMATION_YAW_SHAKE # total duration in seconds of the animation lf_secs = 2000 # play motion animation self.at ( arATCmds.at_anim, li_anim, lf_secs ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::get_image # --------------------------------------------------------------------------------------------- def get_image ( self ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::get_image" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) _im = np.copy ( self.image ) # sherlock logger # l_log.debug ( "<<" ) return _im # --------------------------------------------------------------------------------------------- # ARDrone::get_navdata # --------------------------------------------------------------------------------------------- def get_navdata ( self ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::get_navdata" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( "><" ) return self.navdata # --------------------------------------------------------------------------------------------- # ARDrone::halt # --------------------------------------------------------------------------------------------- def halt ( self ): """ shutdown the drone. does not land or halt the actual drone, but the communication with the drone. Should call it at the end of application to close all sockets, pipes, processes and threads related with this object. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::halt" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.lock.acquire () self.com_watchdog_timer.cancel () self.com_pipe.send ( "die!" ) self.network_process.terminate () # 2.0 ? self.network_process.join () self.ipc_thread.stop () # 2.0 ? self.ipc_thread.join () # 2.0 ? self.lock.release () # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::hover # --------------------------------------------------------------------------------------------- def hover ( self ): """ make the drone hover. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::hover" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, False, 0, 0, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::land # --------------------------------------------------------------------------------------------- def land ( self ): """ make the drone land. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::land" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_ref, False ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move # --------------------------------------------------------------------------------------------- def move ( self, ff_lr, ff_fb, ff_vv, ff_va ): """ makes the drone move (translate/rotate). @param lr : left-right tilt: float [-1..1] negative: left / positive: right @param rb : front-back tilt: float [-1..1] negative: forwards / positive: backwards @param vv : vertical speed: float [-1..1] negative: go down / positive: rise @param va : angular speed: float [-1..1] negative: spin left / positive: spin right """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # validate inputs # assert ( 1. >= ff_lr >= -1. ) # assert ( 1. >= ff_fb >= -1. ) # assert ( 1. >= ff_vv >= -1. ) # assert ( 1. >= ff_va >= -1. ) # move drone self.at ( arATCmds.at_pcmd, True, float ( ff_lr ), float ( ff_fb ), float ( ff_vv ), float ( ff_va )) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_backward # --------------------------------------------------------------------------------------------- def move_backward ( self ): """ make the drone move backwards. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_backward" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, self.speed, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_down # --------------------------------------------------------------------------------------------- def move_down ( self ): """ make the drone decent downwards. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_down" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, 0, -self.speed, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_forward # --------------------------------------------------------------------------------------------- def move_forward ( self ): """ make the drone move forward. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_forward" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, -self.speed, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_left # --------------------------------------------------------------------------------------------- def move_left ( self ): """ make the drone move left. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_left" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, -self.speed, 0, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_right # --------------------------------------------------------------------------------------------- def move_right ( self ): """ make the drone move right. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_right" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, self.speed, 0, 0, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::move_up # --------------------------------------------------------------------------------------------- def move_up ( self ): """ make the drone rise upwards. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::move_up" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, 0, self.speed, 0 ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::reset # --------------------------------------------------------------------------------------------- def reset ( self ): """ toggle the drone's emergency state. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::reset" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_ftrim ) time.sleep ( 0.1 ) self.at ( arATCmds.at_ref, False, True ) time.sleep ( 0.1 ) self.at ( arATCmds.at_ref, False, False ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::set_image # --------------------------------------------------------------------------------------------- def set_image ( self, fo_image ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::set_image" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) if ( f_image.shape == self.image_shape ): self.image = fo_image self.image = fo_image # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::set_navdata # --------------------------------------------------------------------------------------------- def set_navdata ( self, fo_navdata ): # sherlock logger # l_log = logging.getLogger ( "ARDrone::set_navdata" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.navdata = fo_navdata # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::set_speed # --------------------------------------------------------------------------------------------- def set_speed ( self, ff_speed ): """ set the drone's speed. valid values are floats from [0..1] """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::set_speed" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # validate input # assert ( 1. >= ff_speed >= 0. ) # set speed self.speed = float ( ff_speed ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::takeoff # --------------------------------------------------------------------------------------------- def takeoff ( self ): """ make the drone takeoff. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::takeoff" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # calibrate drone self.at ( arATCmds.at_ftrim ) # set maximum altitude self.at ( arATCmds.at_config, "control:altitude_max", "20000" ) # take-off self.at ( arATCmds.at_ref, True ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::trim # --------------------------------------------------------------------------------------------- def trim ( self ): """ flat trim the drone. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::trim" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_ftrim ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::turn_left # --------------------------------------------------------------------------------------------- def turn_left ( self ): """ make the drone rotate left. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::turn_left" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, 0, 0, -self.speed ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone::turn_right # --------------------------------------------------------------------------------------------- def turn_right ( self ): """ make the drone rotate right. """ # sherlock logger # l_log = logging.getLogger ( "ARDrone::turn_right" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_pcmd, True, 0, 0, 0, self.speed ) # sherlock logger # l_log.debug ( "<<" ) # < class ARDrone2 >------------------------------------------------------------------------------- class ARDrone2 ( ARDrone ): """ ARDrone2 class instanciate this class to control your drone and receive decoded video and navdata. """ # --------------------------------------------------------------------------------------------- # ARDrone2::__init__ # --------------------------------------------------------------------------------------------- def __init__ ( self, is_ar_drone_2 = True, hd = False ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::__init__" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) # init super class ARDrone.__init__ ( self ) self.seq_nr = 1 self.timer_t = 0.2 self.com_watchdog_timer = threading.Timer ( self.timer_t, self.commwdg ) self.lock = threading.Lock () self.speed = 0.2 self.image_shape = ( 720, 1080, 1 ) time.sleep ( 0.2 ) self.config_ids_string = [ arDefs.SESSION_ID, arDefs.USER_ID, arDefs.APP_ID ] self.configure_multisession ( arDefs.SESSION_ID, arDefs.USER_ID, arDefs.APP_ID, self.config_ids_string ) self.set_session_id ( self.config_ids_string, arDefs.SESSION_ID ) time.sleep ( 0.2 ) self.set_profile_id ( self.config_ids_string, arDefs.USER_ID ) time.sleep ( 0.2 ) self.set_app_id ( self.config_ids_string, arDefs.APP_ID ) time.sleep ( 0.2 ) self.set_video_bitrate_control_mode ( self.config_ids_string, "1" ) time.sleep ( 0.2 ) self.set_video_bitrate ( self.config_ids_string, "500" ) time.sleep ( 0.2 ) self.set_max_bitrate ( self.config_ids_string, "500" ) time.sleep ( 0.2 ) self.set_fps ( self.config_ids_string, "30" ) time.sleep ( 0.2 ) self.set_video_codec ( self.config_ids_string, 0x80 ) self.last_command_is_hovering = True self.com_pipe, com_pipe_other = multiprocessing.Pipe () self.navdata = {} self.navdata [ 0 ] = { "ctrl_state":0, "battery":0, "theta":0, "phi":0, "psi":0, "altitude":0, "vx":0, "vy":0, "vz":0, "num_frames":0 } self.network_process = arNetwork.ARDrone2NetworkProcess ( com_pipe_other, is_ar_drone_2, self ) self.network_process.start () self.image = np.zeros ( self.image_shape, np.uint8 ) self.time = 0 self.last_command_is_hovering = True time.sleep ( 1.0 ) self.at ( arATCmds.at_config_ids, self.config_ids_string ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::configure_multisession # --------------------------------------------------------------------------------------------- def configure_multisession ( self, f_session_id, f_user_id, f_app_id, f_config_ids_string ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::configure_multisession" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config, "custom:session_id", f_session_id ) self.at ( arATCmds.at_config, "custom:profile_id", f_user_id ) self.at ( arATCmds.at_config, "custom:application_id", f_app_id ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_app_id # --------------------------------------------------------------------------------------------- def set_app_id ( self, f_config_ids_string, f_app_id ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_app_id" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "custom:application_id", f_app_id ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_fps # --------------------------------------------------------------------------------------------- def set_fps ( self, f_config_ids_string, f_fps ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_fps" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:codec_fps", f_fps ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_max_bitrate # --------------------------------------------------------------------------------------------- def set_max_bitrate ( self, f_config_ids_string, f_max_bitrate ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_max_bitrate" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:max_bitrate", f_max_bitrate ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_profile_id # --------------------------------------------------------------------------------------------- def set_profile_id ( self, f_config_ids_string, f_profile_id ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_profile_id" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "custom:profile_id", f_profile_id ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_session_id # --------------------------------------------------------------------------------------------- def set_session_id ( self, f_config_ids_string, f_session_id ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_session_id" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "custom:session_id", f_session_id ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_video_bitrate # --------------------------------------------------------------------------------------------- def set_video_bitrate ( self, f_config_ids_string, f_bitrate ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_video_bitrate" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:bitrate", f_bitrate ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_video_bitrate_control_mode # --------------------------------------------------------------------------------------------- def set_video_bitrate_control_mode ( self, f_config_ids_string, f_mode ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_video_bitrate_control_mode" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:bitrate_control_mode", f_mode ) # sherlock logger # l_log.debug ( "<<" ) # --------------------------------------------------------------------------------------------- # ARDrone2::set_video_codec # --------------------------------------------------------------------------------------------- def set_video_codec ( self, f_config_ids_string, f_codec ): # sherlock logger # l_log = logging.getLogger ( "ARDrone2::set_video_codec" ) # l_log.setLevel ( w_logLvl ) # l_log.debug ( ">>" ) self.at ( arATCmds.at_config_ids, f_config_ids_string ) self.at ( arATCmds.at_config, "video:video_codec", f_codec ) # sherlock logger # l_log.debug ( "<<" ) # ------------------------------------------------------------------------------------------------- # the bootstrap process # ------------------------------------------------------------------------------------------------- if ( "__main__" == __name__ ): import termios import fcntl import os l_fd = sys.stdin.fileno () l_old_term = termios.tcgetattr ( l_fd ) l_new_attr = termios.tcgetattr ( l_fd ) l_new_attr [ 3 ] = l_new_attr [ 3 ] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr ( l_fd, termios.TCSANOW, l_new_attr ) l_old_flags = fcntl.fcntl ( l_fd, fcntl.F_GETFL ) fcntl.fcntl ( l_fd, fcntl.F_SETFL, l_old_flags | os.O_NONBLOCK ) lo_drone = ARDrone () # assert ( lo_drone ) try: while ( True ): try: lc_c = sys.stdin.read ( 1 ) lc_c = lc_c.lower () print "Got character", lc_c # left ? if ( 'a' == lc_c ): lo_drone.move_left () # right ? elif ( 'd' == lc_c ): lo_drone.move_right () # forward ? elif ( 'w' == lc_c ): lo_drone.move_forward () # backward ? elif ( 's' == lc_c ): lo_drone.move_backward () # land ? elif ( ' ' == lc_c ): lo_drone.land () # takeoff ? elif ( '\n' == lc_c ): lo_drone.takeoff () # turn left ? elif ( 'q' == lc_c ): lo_drone.turn_left () # turn right ? elif ( 'e' == lc_c ): lo_drone.turn_right () # move up ? elif ( '1' == lc_c ): lo_drone.move_up () # hover ? elif ( '2' == lc_c ): lo_drone.hover () # move down ? elif ( '3' == lc_c ): lo_drone.move_down () # reset ? elif ( 't' == lc_c ): lo_drone.reset () # hover ? elif ( 'x' == lc_c ): lo_drone.hover () # trim ? elif ( 'y' == lc_c ): lo_drone.trim () except IOError: pass finally: termios.tcsetattr ( l_fd, termios.TCSAFLUSH, l_old_term ) fcntl.fcntl ( l_fd, fcntl.F_SETFL, l_old_flags ) lo_drone.halt () # < the end >-------------------------------------------------------------------------------------- #
projeto-si-lansab/si-lansab
ARDrone/libARDrone.py
Python
gpl-2.0
36,206
import logging from gettext import gettext as _ from typing import Tuple from aai_framework.dial import ColorTxt from aai_framework.interface import ModuleInterface from .main import vars_, Vars logger = logging.getLogger(__name__) class Module(ModuleInterface): ID = 'pkgs' LEN_INSTALL = 2665 @property def vars_(self) -> Vars: return vars_ @property def name(self) -> str: return _('Дополнительное ПО') @property def menu_item(self) -> Tuple[str, str]: text = [ColorTxt('(' + _('ВЫПОЛНЕНО') + ')').green.bold if self.is_run else ''] return super().get_menu_item(text)
AnTAVR/aai2
src/modules/pkgs/m_main.py
Python
gpl-2.0
667
# -*- coding: utf-8 -*- # Copyright 2009,2014 Jaap Karssenberg <[email protected]> '''This module contains helper classes for running external applications. See L{zim.gui.applications} for classes with desktop integration for applications defined in desktop entry files. ''' import sys import os import logging import subprocess import gobject import zim.fs import zim.errors from zim.fs import File from zim.parsing import split_quoted_strings, is_uri_re, is_win32_path_re from zim.environ import environ logger = logging.getLogger('zim.applications') def _main_is_frozen(): # Detect whether we are running py2exe compiled version return hasattr(sys, 'frozen') and sys.frozen class ApplicationError(zim.errors.Error): '''Error raises for error in sub process errors''' description = None def __init__(self, cmd, args, retcode, stderr): '''Constructor @param cmd: the application command as string @param args: tuple of arguments given to the command @param retcode: the return code of the command (non-zero!) @param stderr: the error output of the command ''' self.msg = _('Failed to run application: %s') % cmd # T: Error message when external application failed, %s is the command self.description = \ _('%(cmd)s\nreturned non-zero exit status %(code)i') \ % {'cmd': cmd + ' "' + '" "'.join(args) + '"', 'code': retcode} # T: Error message when external application failed, %(cmd)s is the command, %(code)i the exit code if stderr: self.description += '\n\n' + stderr class Application(object): '''Base class for objects representing an external application or command. @ivar name: the name of the command (default to first item of C{cmd}) @ivar cmd: the command and arguments as a tuple or a string (when given as a string it will be parsed for quoted arguments) @ivar tryexeccmd: the command to check in L{tryexec()}, if C{None} fall back to first item of C{cmd} ''' STATUS_OK = 0 #: return code when the command executed succesfully def __init__(self, cmd, tryexeccmd=None, encoding=None): '''Constructor @param cmd: the command for the external application, either a string for the command, or a tuple or list with the command and arguments @param tryexeccmd: command to check in L{tryexec()} as string. If C{None} will default to C{cmd} or the first item of C{cmd}. @param encoding: the encoding to use for commandline args if known, else falls back to system default ''' if isinstance(cmd, basestring): cmd = split_quoted_strings(cmd) else: assert isinstance(cmd, (tuple, list)) assert tryexeccmd is None or isinstance(tryexeccmd, basestring) self.cmd = tuple(cmd) self.tryexeccmd = tryexeccmd self.encoding = encoding or zim.fs.ENCODING if self.encoding == 'mbcs': self.encoding = 'utf-8' def __repr__(self): if hasattr(self, 'key'): return '<%s: %s>' % (self.__class__.__name__, self.key) elif hasattr(self, 'cmd'): return '<%s: %s>' % (self.__class__.__name__, self.cmd) else: return '<%s: %s>' % (self.__class__.__name__, self.name) @property def name(self): return self.cmd[0] @staticmethod def _lookup(cmd): '''Lookup cmd in PATH''' if zim.fs.isabs(cmd): if zim.fs.isfile(cmd): return cmd else: return None elif os.name == 'nt': # Check executable extensions from windows environment extensions = environ.get_list('PATHEXT', '.com;.exe;.bat;.cmd') for dir in environ.get_list('PATH'): for ext in extensions: file = os.sep.join((dir, cmd + ext)) if zim.fs.isfile(file) and os.access(file, os.X_OK): return file else: return None else: # On POSIX no extension is needed to make scripts executable for dir in environ.get_list('PATH'): file = os.sep.join((dir, cmd)) if zim.fs.isfile(file) and os.access(file, os.X_OK): return file else: return None def _cmd(self, args): # substitute args in the command - to be overloaded by child classes if args: return self.cmd + tuple(map(unicode, args)) else: return self.cmd def tryexec(self): '''Check if the executable exists without calling it. This method is used e.g. to decide what applications to show in the gui. Uses the C{tryexeccmd}, or the first item of C{cmd} as the executable name. @returns: C{True} when the executable was found ''' cmd = self.tryexeccmd or self.cmd[0] return not self._lookup(cmd) is None def _checkargs(self, cwd, args): assert args is None or isinstance(args, (tuple, list)) argv = self._cmd(args) # Expand home dir if argv[0].startswith('~'): cmd = File(argv[0]).path argv = list(argv) argv[0] = cmd # if it is a python script, insert interpreter as the executable if argv[0].endswith('.py') and not _main_is_frozen(): argv = list(argv) argv.insert(0, sys.executable) # TODO: consider an additional commandline arg to re-use compiled python interpreter argv = [a.encode(self.encoding) for a in argv] if cwd: cwd = unicode(cwd).encode(zim.fs.ENCODING) return cwd, argv def run(self, args=None, cwd=None): '''Run the application in a sub-process and wait for it to finish. Even when the application runs successfully, any message to stderr is logged as a warning by zim. @param args: additional arguments to give to the command as tuple or list @param cwd: the folder to set as working directory for the command @raises ApplicationError: if the sub-process returned an error. ''' cwd, argv = self._checkargs(cwd, args) logger.info('Running: %s (cwd: %s)', argv, cwd) if os.name == 'nt': # http://code.activestate.com/recipes/409002/ info = subprocess.STARTUPINFO() try: info.dwFlags |= subprocess.STARTF_USESHOWWINDOW except AttributeError: info.dwFlags |= 1 # STARTF_USESHOWWINDOW = 0x01 p = subprocess.Popen(argv, cwd=cwd, stdout=open(os.devnull, 'w'), stderr=subprocess.PIPE, startupinfo=info, bufsize=4096, #~ close_fds=True ) else: p = subprocess.Popen(argv, cwd=cwd, stdout=open(os.devnull, 'w'), stderr=subprocess.PIPE, bufsize=4096, close_fds=True ) stdout, stderr = p.communicate() if not p.returncode == self.STATUS_OK: raise ApplicationError(argv[0], argv[1:], p.returncode, stderr) #~ elif stderr: #~ logger.warn(stderr) def pipe(self, args=None, cwd=None, input=None): '''Run the application in a sub-process and capture the output. Like L{run()}, but connects to stdin and stdout for the sub-process. @note: The data read is buffered in memory, so do not use this method if the data size is large or unlimited. @param args: additional arguments to give to the command as tuple or list @param cwd: the folder to set as working directory for the command @param input: input for the command as string @returns: output as a list of lines @raises ApplicationError: if the sub-process returned an error. ''' cwd, argv = self._checkargs(cwd, args) logger.info('Running: %s (cwd: %s)', argv, cwd) p = subprocess.Popen(argv, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate(input) # TODO: handle ApplicationERror here as well ? #~ if not p.returncode == self.STATUS_OK: #~ raise ApplicationError(argv[0], argv[1:], p.returncode, stderr) #~ elif stderr: if stderr: logger.warn(stderr) # TODO: allow user to get this error as well - e.g. for logging image generator cmd # Explicit newline conversion, e.g. on windows \r\n -> \n # FIXME Assume local encoding is respected (!?) text = [unicode(line + '\n', errors='replace') for line in stdout.splitlines()] if text and text[-1].endswith('\n') and not stdout.endswith('\n'): text[-1] = text[-1][:-1] # strip additional \n return text def spawn(self, args=None, callback=None, data=None, cwd=None): '''Start the application in the background and return immediately. This is used to start an external in parallel with zim that is not expected to exit immediatly, so we do not want to wait for it - e.g. a webbrowser to show an URL that was clicked. @param args: additional arguments to give to the command as tuple or list @param callback: optional callback can be used to trigger when the application exits. The signature is:: callback(status, data) where 'C{status}' is the exit status of the process. The application object provides a constant 'C{STATUS_OK}' which can be used to test if the application was successful or not. @param data: additional data for the callback @param cwd: the folder to set as working directory for the command @returns: the PID for the new process ''' cwd, argv = self._checkargs(cwd, args) opts = {} flags = gobject.SPAWN_SEARCH_PATH if callback: flags |= gobject.SPAWN_DO_NOT_REAP_CHILD # without this flag child is reaped automatically -> no zombies if not cwd: cwd = os.getcwd() logger.info('Spawning: %s (cwd: %s)', argv, cwd) try: pid, stdin, stdout, stderr = \ gobject.spawn_async(argv, flags=flags, working_directory=cwd, **opts) except gobject.GError: from zim.gui.widgets import ErrorDialog ErrorDialog(None, _('Failed running: %s') % argv[0]).run() #~ # T: error when application failed to start return None else: logger.debug('Process started with PID: %i', pid) if callback: # child watch does implicit reaping -> no zombies if data is None: gobject.child_watch_add(pid, lambda pid, status: callback(status)) else: gobject.child_watch_add(pid, lambda pid, status, data: callback(status, data), data) return pid class WebBrowser(Application): '''Application wrapper for the C{webbrowser} module. Can be used as fallback if no webbrowser is configured. ''' name = _('Default') + ' (webbrowser)' # T: label for default webbrowser key = 'webbrowser' # Used by zim.gui.applications def __init__(self, encoding=None): import webbrowser self.controller = None try: self.controller = webbrowser.get() except webbrowser.Error: pass # webbrowser throws an error when no browser is found self.encoding = encoding or zim.fs.ENCODING if self.encoding == 'mbcs': self.encoding = 'utf-8' def tryexec(self): return not self.controller is None def run(self, args): '''This method is not supported by this class @raises NotImplementedError: always ''' raise NotImplementedError('WebBrowser can not run in foreground') def spawn(self, args, callback=None): if callback: raise NotImplementedError('WebBrowser can not handle callback') for url in args: if isinstance(url, (zim.fs.File, zim.fs.Dir)): url = url.uri url = url.encode(self.encoding) logger.info('Opening in webbrowser: %s', url) self.controller.open(url) class StartFile(Application): '''Application wrapper for C{os.startfile()}. Can be used on windows to open files and URLs with the default application. ''' name = _('Default') + ' (os)' # T: label for default application key = 'startfile' # Used by zim.gui.applications def __init__(self): pass def tryexec(self): return hasattr(os, 'startfile') def run(self, args): '''This method is not supported by this class @raises NotImplementedError: always ''' raise NotImplementedError('StartFile can not run in foreground') def spawn(self, args, callback=None): if callback: logger.warn('os.startfile does not support a callback') for arg in args: if isinstance(arg, (zim.fs.File, zim.fs.Dir)): path = os.path.normpath(arg.path) elif is_uri_re.match(arg) and not is_win32_path_re.match(arg): # URL or e.g. mailto: or outlook: URI path = unicode(arg) else: # must be file path = os.path.normpath(unicode(arg)) logger.info('Opening with os.startfile: %s', path) os.startfile(path)
Osndok/zim-desktop-wiki
zim/applications.py
Python
gpl-2.0
11,848
# -*- coding: utf-8 -*- """ /*************************************************************************** QuickMapServices A QGIS plugin Collection of internet map services ------------------- begin : 2014-11-21 git sha : $Format:%H$ copyright : (C) 2014 by NextGIS email : [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. * * * ***************************************************************************/ """ from __future__ import absolute_import import codecs import os import sys from qgis.PyQt.QtCore import QCoreApplication from qgis.PyQt.QtGui import QIcon from qgis.PyQt.QtWidgets import QMenu from qgis.core import QgsMessageLog from .config_reader_helper import ConfigReaderHelper from . import extra_sources from .custom_translator import CustomTranslator from .group_info import GroupInfo, GroupCategory from .plugin_locale import Locale from .compat import configparser, get_file_dir from .compat2qgis import message_log_levels CURR_PATH = get_file_dir(__file__) INTERNAL_GROUP_PATHS = [os.path.join(CURR_PATH, extra_sources.GROUPS_DIR_NAME), ] CONTRIBUTE_GROUP_PATHS = [os.path.join(extra_sources.CONTRIBUTE_DIR_PATH, extra_sources.GROUPS_DIR_NAME), ] USER_GROUP_PATHS = [os.path.join(extra_sources.USER_DIR_PATH, extra_sources.GROUPS_DIR_NAME), ] ALL_GROUP_PATHS = INTERNAL_GROUP_PATHS + CONTRIBUTE_GROUP_PATHS + USER_GROUP_PATHS ROOT_MAPPING = { INTERNAL_GROUP_PATHS[0]: GroupCategory.BASE, CONTRIBUTE_GROUP_PATHS[0]: GroupCategory.CONTRIB, USER_GROUP_PATHS[0]: GroupCategory.USER } class GroupsList(object): def __init__(self, group_paths=ALL_GROUP_PATHS): self.locale = Locale.get_locale() self.translator = CustomTranslator() self.paths = group_paths self.groups = {} self._fill_groups_list() def _fill_groups_list(self): self.groups = {} for gr_path in self.paths: if gr_path in ROOT_MAPPING.keys(): category = ROOT_MAPPING[gr_path] else: category = GroupCategory.USER for root, dirs, files in os.walk(gr_path): for ini_file in [f for f in files if f.endswith('.ini')]: self._read_ini_file(root, ini_file, category) def _read_ini_file(self, root, ini_file_path, category): try: ini_full_path = os.path.join(root, ini_file_path) parser = configparser.ConfigParser() with codecs.open(ini_full_path, 'r', 'utf-8') as ini_file: if hasattr(parser, "read_file"): parser.read_file(ini_file) else: parser.readfp(ini_file) #read config group_id = parser.get('general', 'id') group_alias = parser.get('ui', 'alias') icon_file = ConfigReaderHelper.try_read_config(parser, 'ui', 'icon') group_icon_path = os.path.join(root, icon_file) if icon_file else None #try read translations posible_trans = parser.items('ui') for key, val in posible_trans: if type(key) is unicode and key == 'alias[%s]' % self.locale: self.translator.append(group_alias, val) break #create menu group_menu = QMenu(self.tr(group_alias)) group_menu.setIcon(QIcon(group_icon_path)) #append to all groups # set contrib&user self.groups[group_id] = GroupInfo(group_id, group_alias, group_icon_path, ini_full_path, group_menu, category) except Exception as e: error_message = self.tr('Group INI file can\'t be parsed: ') + e.message QgsMessageLog.logMessage(error_message, level=message_log_levels["Critical"]) def get_group_menu(self, group_id): if group_id in self.groups: return self.groups[group_id].menu else: info = GroupInfo(group_id=group_id, menu=QMenu(group_id)) self.groups[group_id] = info return info.menu # noinspection PyMethodMayBeStatic def tr(self, message): # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return self.translator.translate('QuickMapServices', message)
nextgis/quickmapservices
src/groups_list.py
Python
gpl-2.0
5,024
import fauxfactory import pytest from cfme import test_requirements from cfme.control.explorer.policies import VMControlPolicy from cfme.infrastructure.provider.virtualcenter import VMwareProvider from cfme.markers.env_markers.provider import ONE_PER_TYPE from cfme.services.myservice import MyService from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.conf import cfme_data from cfme.utils.conf import credentials from cfme.utils.update import update from cfme.utils.wait import wait_for pytestmark = [ pytest.mark.ignore_stream("upstream"), pytest.mark.long_running, pytest.mark.provider([VMwareProvider], selector=ONE_PER_TYPE, scope="module"), test_requirements.ansible, ] @pytest.fixture(scope="module") def wait_for_ansible(appliance): appliance.server.settings.enable_server_roles("embedded_ansible") appliance.wait_for_embedded_ansible() yield appliance.server.settings.disable_server_roles("embedded_ansible") @pytest.fixture(scope="module") def ansible_repository(appliance, wait_for_ansible): repositories = appliance.collections.ansible_repositories try: repository = repositories.create( name=fauxfactory.gen_alpha(), url=cfme_data.ansible_links.playbook_repositories.embedded_ansible, description=fauxfactory.gen_alpha()) except KeyError: pytest.skip("Skipping since no such key found in yaml") view = navigate_to(repository, "Details") wait_for( lambda: view.entities.summary("Properties").get_text_of("Status") == "successful", timeout=60, fail_func=view.toolbar.refresh.click ) yield repository repository.delete_if_exists() @pytest.fixture(scope="module") def ansible_catalog_item(appliance, ansible_repository): cat_item = appliance.collections.catalog_items.create( appliance.collections.catalog_items.ANSIBLE_PLAYBOOK, fauxfactory.gen_alphanumeric(), fauxfactory.gen_alphanumeric(), display_in_catalog=True, provisioning={ "repository": ansible_repository.name, "playbook": "dump_all_variables.yml", "machine_credential": "CFME Default Credential", "create_new": True, "provisioning_dialog_name": fauxfactory.gen_alphanumeric() } ) yield cat_item cat_item.delete_if_exists() @pytest.fixture(scope="module") def ansible_action(appliance, ansible_catalog_item): action_collection = appliance.collections.actions action = action_collection.create( fauxfactory.gen_alphanumeric(), action_type="Run Ansible Playbook", action_values={ "run_ansible_playbook": { "playbook_catalog_item": ansible_catalog_item.name } } ) yield action action.delete_if_exists() @pytest.fixture(scope="module") def policy_for_testing(appliance, full_template_vm_modscope, provider, ansible_action): vm = full_template_vm_modscope policy = appliance.collections.policies.create( VMControlPolicy, fauxfactory.gen_alpha(), scope="fill_field(VM and Instance : Name, INCLUDES, {})".format(vm.name) ) policy.assign_actions_to_event("Tag Complete", [ansible_action.description]) policy_profile = appliance.collections.policy_profiles.create( fauxfactory.gen_alpha(), policies=[policy]) provider.assign_policy_profiles(policy_profile.description) yield if policy.exists: policy.assign_events() provider.unassign_policy_profiles(policy_profile.description) policy_profile.delete() policy.delete() @pytest.fixture(scope="module") def ansible_credential(wait_for_ansible, appliance, full_template_modscope): credential = appliance.collections.ansible_credentials.create( fauxfactory.gen_alpha(), "Machine", username=credentials[full_template_modscope.creds]["username"], password=credentials[full_template_modscope.creds]["password"] ) yield credential credential.delete_if_exists() @pytest.fixture def service_request(appliance, ansible_catalog_item): request_desc = "Provisioning Service [{0}] from [{0}]".format(ansible_catalog_item.name) _service_request = appliance.collections.requests.instantiate(request_desc) yield _service_request _service_request.delete_if_exists() @pytest.fixture def service(appliance, ansible_catalog_item): service_ = MyService(appliance, ansible_catalog_item.name) yield service_ if service_.exists: service_.delete() @pytest.mark.tier(3) def test_action_run_ansible_playbook_localhost(request, ansible_catalog_item, ansible_action, policy_for_testing, full_template_vm_modscope, ansible_credential, service_request, service): """Tests a policy with ansible playbook action against localhost. Polarion: assignee: sbulage initialEstimate: 1/6h casecomponent: Ansible """ with update(ansible_action): ansible_action.run_ansible_playbook = {"inventory": {"localhost": True}} added_tag = full_template_vm_modscope.add_tag() request.addfinalizer(lambda: full_template_vm_modscope.remove_tag(added_tag)) wait_for(service_request.exists, num_sec=600) service_request.wait_for_request() view = navigate_to(service, "Details") assert view.provisioning.details.get_text_of("Hosts") == "localhost" assert view.provisioning.results.get_text_of("Status") == "successful" @pytest.mark.tier(3) def test_action_run_ansible_playbook_manual_address(request, ansible_catalog_item, ansible_action, policy_for_testing, full_template_vm_modscope, ansible_credential, service_request, service): """Tests a policy with ansible playbook action against manual address. Polarion: assignee: sbulage initialEstimate: 1/6h casecomponent: Ansible """ vm = full_template_vm_modscope with update(ansible_catalog_item): ansible_catalog_item.provisioning = {"machine_credential": ansible_credential.name} with update(ansible_action): ansible_action.run_ansible_playbook = { "inventory": { "specific_hosts": True, "hosts": vm.ip_address } } added_tag = vm.add_tag() request.addfinalizer(lambda: vm.remove_tag(added_tag)) wait_for(service_request.exists, num_sec=600) service_request.wait_for_request() view = navigate_to(service, "Details") assert view.provisioning.details.get_text_of("Hosts") == vm.ip_address assert view.provisioning.results.get_text_of("Status") == "successful" @pytest.mark.tier(3) def test_action_run_ansible_playbook_target_machine(request, ansible_catalog_item, ansible_action, policy_for_testing, full_template_vm_modscope, ansible_credential, service_request, service): """Tests a policy with ansible playbook action against target machine. Polarion: assignee: sbulage initialEstimate: 1/6h casecomponent: Ansible """ vm = full_template_vm_modscope with update(ansible_action): ansible_action.run_ansible_playbook = {"inventory": {"target_machine": True}} added_tag = vm.add_tag() request.addfinalizer(lambda: vm.remove_tag(added_tag)) wait_for(service_request.exists, num_sec=600) service_request.wait_for_request() view = navigate_to(service, "Details") assert view.provisioning.details.get_text_of("Hosts") == vm.ip_address assert view.provisioning.results.get_text_of("Status") == "successful" @pytest.mark.tier(3) def test_action_run_ansible_playbook_unavailable_address(request, ansible_catalog_item, full_template_vm_modscope, ansible_action, policy_for_testing, ansible_credential, service_request, service): """Tests a policy with ansible playbook action against unavailable address. Polarion: assignee: sbulage initialEstimate: 1/6h casecomponent: Ansible """ vm = full_template_vm_modscope with update(ansible_catalog_item): ansible_catalog_item.provisioning = {"machine_credential": ansible_credential.name} with update(ansible_action): ansible_action.run_ansible_playbook = { "inventory": { "specific_hosts": True, "hosts": "unavailable_address" } } added_tag = vm.add_tag() request.addfinalizer(lambda: vm.remove_tag(added_tag)) wait_for(service_request.exists, num_sec=600) service_request.wait_for_request() view = navigate_to(service, "Details") assert view.provisioning.details.get_text_of("Hosts") == "unavailable_address" assert view.provisioning.results.get_text_of("Status") == "failed" @pytest.mark.tier(3) def test_control_action_run_ansible_playbook_in_requests(request, full_template_vm_modscope, policy_for_testing, service_request): """Checks if execution of the Action result in a Task/Request being created. Polarion: assignee: sbulage initialEstimate: 1/6h casecomponent: Ansible """ vm = full_template_vm_modscope added_tag = vm.add_tag() request.addfinalizer(lambda: vm.remove_tag(added_tag)) assert service_request.exists
RedHatQE/cfme_tests
cfme/tests/ansible/test_embedded_ansible_actions.py
Python
gpl-2.0
9,360
################################################################ # LiveQ - An interactive volunteering computing batch system # Copyright (C) 2013 Ioannis Charalampidis # # 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. ################################################################ import numpy import re def parseFLATBuffer(buf, index=True): """ Parse FLAT buffer and return the structured data """ sections_list = [] section = None activesection = None # Pick appropriate return format sections = None if index: sections = {} else: sections = [] # Start processing the buffer line-by-line for line in buf.splitlines(): # Process lines if not line: # Empty line pass elif "# BEGIN " in line: # Ignore labels found some times in AIDA files dat = line.split(" ") section = dat[2] sectiontype = 0 # Get additional section title title = "" if len(dat) > 3: title = " ".join(dat[3:]) # Allocate section record activesection = { "d": { }, "v": [ ], "t": title } elif ("# END " in line) and (section != None): # Section end if index: sections[section] = activesection else: activesection['n'] = section sections.append(activesection) section = None elif line.startswith("#") or line.startswith(";"): # Comment pass elif section: # Data inside section # "SPECIAL" section is not parsable here if section == "SPECIAL": continue # Try to split data = line.split("=",1) # Could not split : They are histogram data if len(data) == 1: # Split data values data = FLATParser.WHITESPACE.split(line.strip()) # Check for faulty values if len(data) < 3: continue # Otherwise collect activesection['v'].append( numpy.array(data, dtype=numpy.float64) ) else: # Store value activesection['d'][data[0]] = data[1] # Return sections return sections class FLATParser: """ Simple function to parser histograms in FLAT format """ # Precompiled regex entry WHITESPACE = re.compile("\s+") @staticmethod def parseFileObject(fileobject, index=True): """ Function to read a FLAT file (by the file object descriptor) into python structures """ # Read entire file and use parseBuffer return parseFLATBuffer(fileobject.read(), index) @staticmethod def parse(filename, index=True): """ Function to read a FLAT file into python structures """ # Open file with open(filename, 'r') as f: # Use FileObject parser to read the file return parseFLATBuffer(f.read(), index) def parseBuffer(buf, index=True): """ Parse FLAT file from buffer """ return parseFLATBuffer(buf, index)
wavesoft/LiveQ
liveq-common/liveq/utils/FLAT.py
Python
gpl-2.0
3,333
# -*- coding: utf-8 -*- # $Id: $ ERROR_AUTH_FAILED = "Authorization failed" NO_SUCH_BACKEND = "No such backend" REDIRECTION_FAILED = "Redirection failed"
collective/ECSpooler
lib/util/errorcodes.py
Python
gpl-2.0
154
#!/usr/bin/python # -*- coding: utf-8 -*- corto = 10 largo = long(corto) print type(corto) print type(largo)
psicobyte/ejemplos-python
cap5/p62.py
Python
gpl-3.0
112
#!/usr/bin/python # FRANKEN CIPHER # WRITTEN FOR ACADEMIC PURPOSES # # AUTHORED BY: Dan C and [email protected] # # THIS SCRIPT IS WRITTEN TO DEMONSTRATE A UNIQUE ENCRYPTION ALGORITHM THAT IS INSPIRED BY A NUMBER # OF EXISTING ALGORITHMS. # THE SCRIPT IS WRITTEN ENTIRELY FOR ACADEMIC PURPOSES. NO WARRANTY OR GUARANTEES ARE # OFFERED BY THE AUTHORS IN RELATION TO THE USE OF THIS SCRIPT. # # Usage: franken.py <"-v" (verbose)> <"-d" (decrypt)> <"-k" (key phrase)> <"-m" (string to encrypt/decrypt)> # # indentation: TABS! import sys import getopt import collections import binascii import hashlib import itertools # GLOBALS # define -v and -d as false (-d defaults to encrypt mode) verbose_opt = False decrypt_opt = False key_phrase = '' # clear text key phrase key_hashed = '' # hashed key phrase clear_text = '' # starting message input pigpen_message = '' # message after pigpen stage encrypted_message = '' # the encrypted message decrypted_message = '' # the decrypted message # GLOBALS # pigpen dictionaries pigpen_A = {'A':'ETL', 'B':'ETM', 'C':'ETR', 'D':'EML', 'E':'EMM', 'F':'EMR', 'G':'EBL', 'H':'EBM', 'I':'EBR', 'J':'DTL', 'K':'DTM', 'L':'DTR', 'M':'DML', 'N':'DMM', 'O':'DMR', 'P':'DBL', 'Q':'DBM', 'R':'DBR', 'S':'EXT', 'T':'EXL', 'U':'EXR', 'V':'EXB', 'W':'DXT', 'X':'DXL', 'Y':'DXR', 'Z':'DXB', ' ':'EPS', '.':'EPF', ',':'EPC', '!':'EPE', '?':'EPQ', '"':'EPD', '@':'EPA','0':'NTL', '1':'NTM', '2':'NTR', '3':'NML', '4':'NMM', '5':'NMR', '6':'NBL', '7':'NBM', '8':'NBR','9':'NXT'} pigpen_B = {'C':'ETL', 'D':'ETM', 'A':'ETR', 'B':'EML', 'G':'EMM', 'H':'EMR', 'E':'EBL', 'F':'EBM', 'K':'EBR', 'L':'DTL', 'I':'DTM', 'J':'DTR', 'O':'DML', 'P':'DMM', 'M':'DMR', 'N':'DBL', 'S':'DBM', 'T':'DBR', 'Q':'EXT', 'R':'EXL', 'W':'EXR', 'X':'EXB', 'U':'DXT', 'V':'DXL', ' ':'DXR', ',':'DXB', 'Y':'EPS', '!':'EPF', 'Z':'EPC', '.':'EPE', '@':'EPQ', '0':'EPD', '?':'EPA','"':'NTL', '3':'NTM', '4':'NTR', '1':'NML', '2':'NMM', '7':'NMR', '8':'NBL', '9':'NBM', '5':'NBR', '6':'NXT'} pigpen_C = {'K':'ETL', 'L':'ETM', 'M':'ETR', 'N':'EML', 'O':'EMM', 'P':'EMR', 'Q':'EBL', 'R':'EBM', 'S':'EBR', 'U':'DTL', 'V':'DTM', 'W':'DTR', 'X':'DML', 'Y':'DMM', 'Z':'DMR', ' ':'DBL', '.':'DBM', ',':'DBR', '!':'EXT', '"':'EXL', '?':'EXR', '@':'EXB', '0':'DXT', '1':'DXL', '2':'DXR', '3':'DXB', '4':'EPS', '5':'EPF', '6':'EPC', '7':'EPE', '8':'EPQ', '9':'EPD', 'A':'EPA','B':'NTL', 'C':'NTM', 'D':'NTR', 'E':'NML', 'F':'NMM', 'G':'NMR', 'H':'NBL', 'I':'NBM', 'J':'NBR','T':'NXT'} # creates hashes of the key phrase inputted by the user # in order for it to be used as a key # the clear text key phrase string is retained def keyGenerate(): global key_hashed # create the hashes of the key phrase string md5_hash = hashlib.md5(key_phrase.encode()) sha256_hash = hashlib.sha256(key_phrase.encode()) sha512_hash = hashlib.sha512(key_phrase.encode()) # concatenate the hash digests into one key key_hashed = md5_hash.hexdigest() + sha256_hash.hexdigest() + sha512_hash.hexdigest() # hash the entire key (so far) one more time and concatenate to make 1024bit key key_hashed_hash = hashlib.md5(key_hashed.encode()) key_hashed += key_hashed_hash.hexdigest() # vebose mode if verbose option is set if verbose_opt: print("[KEY GENERATION]: The key phrase is: \"" + key_phrase + "\"") print("[KEY GENERATION]: \"" + key_phrase + "\" is independantly hashed 3 times using MD5, SHA256 and SHA512") print("[KEY GENERATION]: The 3 hashes are concatenated with 1 more md5 hash, resulting in the 1024bit key:") print("[KEY GENERATION]: \"" + key_hashed + "\"\n") return # selects the appropriate pigpen dictionary based on summing all of the ascii # values in the key phrase and modulating the sum of the integers by 3 in order to retrieve # one of 3 values. Returns the appropriate dictionary def selectDict(): # sum ASCII value of each character in the clear text key phrase ascii_total = 0 for x in key_phrase: ascii_total += ord(x) # modulo 3 ascii_total to find 0-3 result to select pigpen dict if ascii_total % 3 == 0: pigpen_dict = pigpen_A elif ascii_total % 3 == 1: pigpen_dict = pigpen_B elif ascii_total % 3 == 2: pigpen_dict = pigpen_C # return the dictionary return pigpen_dict # convert message into pigpen alphabet. compare each letter to dict key. # first makes all chars uppercase and ignores some punctuation. # itterates through pigpen dict to find value based on clear message char as key def pigpenForward(): global pigpen_message # convert clear message to uppercase message = clear_text.upper() # itterate through dict looking for chars for letter in message: if letter in selectDict(): pigpen_message += selectDict().get(letter) # verbose mode if verbose option is set if verbose_opt: print("[ENCRYPTION - Phase 1]: The clear text is:") print("[ENCRYPTION - Phase 1]: \"" + clear_text + "\"") print("[ENCRYPTION - Phase 1]: 1 of 3 dictionaries is derived from the sum of the pre-hashed key ASCII values (mod 3)") print("[ENCRYPTION - Phase 1]: The clear text is converted into pigpen cipher text using the selected dictionary:") print("[ENCRYPTION - Phase 1]: \"" + pigpen_message + "\"\n") return # reverses the pigpen process. takes a pigpen string and converts it back to clear text # first creates a list of each 3 values from the inputted string (each element has 3 chars) # then compares those elements to the pigpen dictionary to create the decrypted string def pigpenBackward(): global decrypted_message # convert encrypted message (int array) back to a single ascii string message = '' try: for i in decrypted_message: message += chr(i) except: print("[ERROR]: Incorrect key. Cannot decrypt.") usageText() # retrieve each 3 chars (one pigpen value) and form a list message_list = [message[i:i+3] for i in range(0, len(message), 3)] # zero out decrypted message string in order to store pigpen deciphered characters decrypted_message = '' # itterate through list elements and compare against pigpen dict # to find correct key (clear text letter) and create decrypted string for element in message_list: for key, value in selectDict().iteritems(): if value == element: decrypted_message += key # verbose mode if verbose option is set if verbose_opt: print("[DECRYPTION - Phase 3]: 1 of 3 dictionaries is derived from the sum of the pre-hashed key ASCII values (mod 3)") print("[DECRYPTION - Phase 3]: The values of the pigpen cipher text are looked up in the selected dictionary") print("[DECRYPTION - Phase 3]: The pigpen cipher text is converted back into clear text:\n") print("[DECRYPTION - COMPLETE]: \"" + decrypted_message + "\"\n") return # XORs an int value derived from the hashed key to each ascii int value of the message. # The key value is looked up by using the value stored in that key array position to reference # the array position that value points to. That value is then XOR'ed with the corresponding value of the message # this occurs three times. Inspired by DES key sub key generation and RC4 def keyConfusion(message): # create array of base10 ints from ascii values of chars in hashed key key = [] for x in key_hashed: key.append(ord(x)) # create a variable for cycling through the key array (in case the message is longer than key) key_cycle = itertools.cycle(key) # loop through the key and XOR the resultant value with the corresponding value in the message for i in range(len(message)): # find the value pointed to by the value of each element of the key (for each value in the message array) key_pointer = key_cycle.next() % 128 # get the next key byte. mod 128 because 128 bytes in 1024bits key_byte = key[key_pointer] # XOR message byte with current key_byte message[i] = message[i] ^ key_byte # XOR message byte with the key byte pointed to by previous key byte value key_byte = key[(key_byte % 128)] message[i] = message[i] ^ key_byte # once again XOR message byte with the next key byte pointed to by previous key byte value key_byte = key[(key_byte % 128)] message[i] = message[i] ^ key_byte # verbose mode if verbose option is set if verbose_opt: # are we decrypting or encrypting? if decrypt_opt: en_or_de = "[DECRYPTION - Phase 2]: " en_or_de_text = " pigpen cipher text:" else: en_or_de = "[ENCRYPTION - Phase 2]: " en_or_de_text = " partially encrypted string:" # print the appropriate output for encrypting or decrypting print(en_or_de + "Each byte of the pigpen cipher is then XOR'ed against 3 bytes of the key") print(en_or_de + "The key byte is XOR'ed against the byte of the message and then used to select the") print(en_or_de + "position in the key array of the next key byte value. This occurs three times.") print(en_or_de + "Resulting in the" + en_or_de_text) print(en_or_de + "\"" + message + "\"\n") return message # xors the hashed key against the pigpenned message # each character in the message is xor'ed against each character # in the hashed key, resulting in the encrypted message def xorForward(): global encrypted_message # convert key and message into ints for xoring message = bytearray(pigpen_message) key = bytearray(key_hashed) # send pigpen message off for permution message = keyConfusion(message) # iterate over message and xor each character against each value in the key for x in range(len(message)): for y in range(len(key)): xored = key[y] ^ message[x] message[x] = xored # store hex value of encrypted string in global variable encrypted_message = binascii.hexlify(bytearray(message)) # verbose mode is verbose option is set if verbose_opt: print("[ENCRYPTION - Phase 3]: The partially encrypted cipher text and key are converted into a byte arrays") print("[ENCRYPTION - Phase 3]: Each byte of the message is XOR'ed against each byte of the key") print("[ENCRYPTION - Phase 3]: Resulting in the cipher text hex string:\n") print("[ENCRYPTION - COMPLETE]: \"" + encrypted_message + "\"\n") return # the reverse of the encrypt function, whereby the supplied key is reversed # and xored against the encrypted message. The message is first unhexlified # to facilitate xoring def xorBackward(): global decrypted_message # create byte array for key and to store decrypted message reverse_key = key_hashed[::-1] key = bytearray(reverse_key) # try to convert the encrypted message from hex to int, error if incorrect string try: message = bytearray(binascii.unhexlify(clear_text)) except: print("[ERROR]: Incorrect string. Cannot decrypt.") usageText() # iterate over the encrypted message and xor each value against each value in the key for x in range(len(message)): for y in range(len(key)): xored = key[y] ^ message[x] message[x] = xored # verbose mode is verbose option is set if verbose_opt: print("[DECRYPTION - Phase 1]: The cipher text is:") print("[DECRYPTION - Phase 1]: \"" + clear_text + "\"") print("[DECRYPTION - Phase 1]: The cipher text and key are converted into a byte arrays") print("[DECRYPTION - Phase 1]: The key is reversed in order to reverse this stage of XOR'ing") print("[DECRYPTION - Phase 1]: Each byte of the cipher text is XOR'ed against each byte of the key") print("[DECRYPTION - Phase 1]: Resulting in the partially decrypted string:") print("[DECRYPTION - Phase 1]: \"" + message + "\"\n") # send decrypted array off for permutation (reverse encrypted XOR'ing) decrypted_message = keyConfusion(message) return # text to be displayed on incorrect user input def usageText(): print("\n[USAGE]: franken.py -v (verbose) -d (decrypt) --keyphrase (-k) <phrase> --message (-m) <message to encrypt>") print("[USAGE]: -v and -d arguments are optional. --keyphrase(-k) and --message(-m) are required") print("\n[EXAMPLE]: python franken.py -v --keyphrase \"super secret\" --message \"This is a super secret message\"\n") print("[!] As with any cipher, your message is only as secure as your key phrase.") print("[!] REMEMBER: The more complicated your key phrase, the stronger your encrypted message will be!\n") sys.exit(2) # USER INPUT HANDLING # check that arguments have been supplied if len(sys.argv) < 2: usageText() # define the arguments and necessity. try: opts, args = getopt.getopt(sys.argv[1:], 'vdk:m:', ["verbose", "decrypt", "keyphrase=", "message="]) except getopt.GetoptError: usageText() # check for presence of args and assign values for opt, arg in opts: if opt == '-v': verbose_opt = True if opt == '-d': decrypt_opt = True if opt in ('-k', '--keyphrase'): key_phrase = arg if opt in ('-m', '--message'): clear_text = arg # Check that a keyphrase and message has been set if not key_phrase or not clear_text: usageText() print( ''' __ _ / _| | | | |_ _ __ __ _ _ __ | | _____ _ __ | _| '__/ _` | '_ \| |/ / _ \ '_ \ | | | | | (_| | | | | < __/ | | | |_| |_| \__,_|_| |_|_|\_\___|_| |_| _ _ __(_)_ __| |_ ___ _ _ / _| | '_ \ ' \/ -_) '_| \__|_| .__/_||_\___|_| |_| [!] franken.py An encryption algorithm inspired by a number of existing ciphers. Created for CC6004 Course Work 1. 2016/17 [@] Dan C and [email protected] __________________________________________________ ''' ) # are we decrypting or encrypting? defaults to encrypting # decrypt if decrypt_opt: keyGenerate() xorBackward() pigpenBackward() if not verbose_opt: print("[DECRYPTED]: " + decrypted_message + "\n") # encrypt else: keyGenerate() pigpenForward() xorForward() if not verbose_opt: print("[ENCRYPTED]: " + encrypted_message + "\n")
forScie/FrankenCipher
franken.py
Python
gpl-3.0
13,770
# -*- coding: utf-8 -*- # Copyright 2009 James Hensman # Licensed under the Gnu General Public license, see COPYING # # Gaussian Process Proper Orthogonal Decomposition.
jameshensman/pythonGPLVM
GPPOD.py
Python
gpl-3.0
171
#!/usr/bin/env python from distutils.core import setup setup( name="flowtools", description="Tools for flow maps from modified Gromacs simulations", long_description="See README.md", license='GPLv3', version='0.2.30', url="https://github.com/pjohansson/flowtools", author="Petter Johansson", author_email="[email protected]", packages=['flowtools'], requires=[ 'numpy (>=1.7.0)', 'matplotlib (>=1.2.0)', 'pandas (>=0.10.1)', 'scipy (>=0.11.0)' ], scripts=[ 'scripts/f_collect_spread.py', 'scripts/f_combine_maps.py', 'scripts/f_flowmaps.py', 'scripts/f_print.py', 'scripts/f_spread_delta_t.py', 'scripts/f_spread_plot.py', 'scripts/f_spread_ttest.py', 'scripts/f_spread_com.py', 'scripts/f_spread_std.py', 'scripts/f_velprofile.py', 'scripts/f_average_maps.py', 'scripts/f_spread_vel.py', 'scripts/f_combine_cells.py', 'scripts/f_viscous_dissipation.py', 'scripts/f_interface.py', 'scripts/f_shearmax.py', 'scripts/f_contactline.py' ] )
pjohansson/flowtools
setup.py
Python
gpl-3.0
1,324
__productname__ = 'dotinstall' __version__ = '0.1' __copyright__ = "Copyright (C) 2014 Cinghio Pinghio" __author__ = "Cinghio Pinghio" __author_email__ = "[email protected]" __description__ = "Install dotfiles" __long_description__ = "Install dofile based on some rules" __url__ = "cinghiopinghio...." __license__ = "Licensed under the GNU GPL v3+."
cinghiopinghio/dotinstall
dotinstall/__init__.py
Python
gpl-3.0
354
__all__ = ['appie.appie', 'appie.extensions'] from appie.appie import * from appie.extensions import *
sphaero/appie
appie/__init__.py
Python
gpl-3.0
104
from django.contrib.auth.models import User from django.views.generic.edit import CreateView, FormView from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from django.core.context_processors import csrf from django.http import HttpResponse, JsonResponse from django.contrib.auth.decorators import login_required def test_page(request): return render(request, "test.html")
godlike64/typhon
typhon/views.py
Python
gpl-3.0
468
#!/usr/bin/env python # # This file is part of pacman-mirrors. # # pacman-mirrors 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. # # pacman-mirrors 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 pacman-mirrors. If not, see <http://www.gnu.org/licenses/>. # # from https://wiki.maemo.org/Internationalize_a_Python_application """Pacman-Mirrors Translation Module""" import os import sys import locale import gettext # The translation files will be under # @LOCALE_DIR@/@LANGUAGE@/LC_MESSAGES/@[email protected] APP_NAME = "pacman_mirrors" APP_DIR = os.path.join(sys.prefix, "share") LOCALE_DIR = os.path.join(APP_DIR, "locale") CODESET = "utf-8" # Now we need to choose the language. We will provide a list, and gettext # will use the first translation available in the list LANGUAGES = [] try: user_locale = locale.getdefaultlocale()[0] if user_locale: LANGUAGES += user_locale except ValueError: pass LANGUAGES += os.environ.get("LANGUAGE", "").split(":") LANGUAGES += ["en_US"] # Lets tell those details to gettext # (nothing to change here for you) gettext.install(True) gettext.bindtextdomain(APP_NAME, LOCALE_DIR) gettext.bind_textdomain_codeset(APP_NAME, codeset=CODESET) gettext.textdomain(APP_NAME) language = gettext.translation(APP_NAME, LOCALE_DIR, LANGUAGES, fallback=True) # Add this to every module: # # import i18n # _ = i18n.language.gettext
fhdk/pacman-mirrors
pacman_mirrors/translation/i18n.py
Python
gpl-3.0
1,832
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2021 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser 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. # # qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>. """A QProcess which shows notifications in the GUI.""" import locale import shlex from PyQt5.QtCore import (pyqtSlot, pyqtSignal, QObject, QProcess, QProcessEnvironment) from qutebrowser.utils import message, log, utils from qutebrowser.browser import qutescheme class GUIProcess(QObject): """An external process which shows notifications in the GUI. Args: cmd: The command which was started. args: A list of arguments which gets passed. verbose: Whether to show more messages. _output_messages: Show output as messages. _started: Whether the underlying process is started. _proc: The underlying QProcess. _what: What kind of thing is spawned (process/editor/userscript/...). Used in messages. Signals: error/finished/started signals proxied from QProcess. """ error = pyqtSignal(QProcess.ProcessError) finished = pyqtSignal(int, QProcess.ExitStatus) started = pyqtSignal() def __init__(self, what, *, verbose=False, additional_env=None, output_messages=False, parent=None): super().__init__(parent) self._what = what self.verbose = verbose self._output_messages = output_messages self._started = False self.cmd = None self.args = None self._proc = QProcess(self) self._proc.errorOccurred.connect(self._on_error) self._proc.errorOccurred.connect(self.error) self._proc.finished.connect(self._on_finished) self._proc.finished.connect(self.finished) self._proc.started.connect(self._on_started) self._proc.started.connect(self.started) if additional_env is not None: procenv = QProcessEnvironment.systemEnvironment() for k, v in additional_env.items(): procenv.insert(k, v) self._proc.setProcessEnvironment(procenv) @pyqtSlot(QProcess.ProcessError) def _on_error(self, error): """Show a message if there was an error while spawning.""" if error == QProcess.Crashed and not utils.is_windows: # Already handled via ExitStatus in _on_finished return msg = self._proc.errorString() message.error("Error while spawning {}: {}".format(self._what, msg)) @pyqtSlot(int, QProcess.ExitStatus) def _on_finished(self, code, status): """Show a message when the process finished.""" self._started = False log.procs.debug("Process finished with code {}, status {}.".format( code, status)) encoding = locale.getpreferredencoding(do_setlocale=False) stderr = self._proc.readAllStandardError().data().decode( encoding, 'replace') stdout = self._proc.readAllStandardOutput().data().decode( encoding, 'replace') if self._output_messages: if stdout: message.info(stdout.strip()) if stderr: message.error(stderr.strip()) if status == QProcess.CrashExit: exitinfo = "{} crashed.".format(self._what.capitalize()) message.error(exitinfo) elif status == QProcess.NormalExit and code == 0: exitinfo = "{} exited successfully.".format( self._what.capitalize()) if self.verbose: message.info(exitinfo) else: assert status == QProcess.NormalExit # We call this 'status' here as it makes more sense to the user - # it's actually 'code'. exitinfo = ("{} exited with status {}, see :messages for " "details.").format(self._what.capitalize(), code) message.error(exitinfo) if stdout: log.procs.error("Process stdout:\n" + stdout.strip()) if stderr: log.procs.error("Process stderr:\n" + stderr.strip()) qutescheme.spawn_output = self._spawn_format(exitinfo, stdout, stderr) def _spawn_format(self, exitinfo, stdout, stderr): """Produce a formatted string for spawn output.""" stdout = (stdout or "(No output)").strip() stderr = (stderr or "(No output)").strip() spawn_string = ("{}\n" "\nProcess stdout:\n {}" "\nProcess stderr:\n {}").format(exitinfo, stdout, stderr) return spawn_string @pyqtSlot() def _on_started(self): """Called when the process started successfully.""" log.procs.debug("Process started.") assert not self._started self._started = True def _pre_start(self, cmd, args): """Prepare starting of a QProcess.""" if self._started: raise ValueError("Trying to start a running QProcess!") self.cmd = cmd self.args = args fake_cmdline = ' '.join(shlex.quote(e) for e in [cmd] + list(args)) log.procs.debug("Executing: {}".format(fake_cmdline)) if self.verbose: message.info('Executing: ' + fake_cmdline) def start(self, cmd, args): """Convenience wrapper around QProcess::start.""" log.procs.debug("Starting process.") self._pre_start(cmd, args) self._proc.start(cmd, args) self._proc.closeWriteChannel() def start_detached(self, cmd, args): """Convenience wrapper around QProcess::startDetached.""" log.procs.debug("Starting detached.") self._pre_start(cmd, args) ok, _pid = self._proc.startDetached( cmd, args, None) # type: ignore[call-arg] if not ok: message.error("Error while spawning {}".format(self._what)) return False log.procs.debug("Process started.") self._started = True return True def exit_status(self): return self._proc.exitStatus()
forkbong/qutebrowser
qutebrowser/misc/guiprocess.py
Python
gpl-3.0
6,787
"""Weighted maximum matching in general graphs. The algorithm is taken from "Efficient Algorithms for Finding Maximum Matching in Graphs" by Zvi Galil, ACM Computing Surveys, 1986. It is based on the "blossom" method for finding augmenting paths and the "primal-dual" method for finding a matching of maximum weight, both due to Jack Edmonds. Some ideas came from "Implementation of algorithms for maximum matching on non-bipartite graphs" by H.J. Gabow, Standford Ph.D. thesis, 1973. A C program for maximum weight matching by Ed Rothberg was used extensively to validate this new code. http://jorisvr.nl/article/maximum-matching#ref:4 """ # # Changes: # # 2013-04-07 # * Added Python 3 compatibility with contributions from Daniel Saunders. # # 2008-06-08 # * First release. # from __future__ import print_function # If assigned, DEBUG(str) is called with lots of debug messages. DEBUG = None """def DEBUG(s): from sys import stderr print('DEBUG:', s, file=stderr) """ # Check delta2/delta3 computation after every substage; # only works on integer weights, slows down the algorithm to O(n^4). CHECK_DELTA = False # Check optimality of solution before returning; only works on integer weights. CHECK_OPTIMUM = True def maxWeightMatching(edges, maxcardinality=False): """Compute a maximum-weighted matching in the general undirected weighted graph given by "edges". If "maxcardinality" is true, only maximum-cardinality matchings are considered as solutions. Edges is a sequence of tuples (i, j, wt) describing an undirected edge between vertex i and vertex j with weight wt. There is at most one edge between any two vertices; no vertex has an edge to itself. Vertices are identified by consecutive, non-negative integers. Return a list "mate", such that mate[i] == j if vertex i is matched to vertex j, and mate[i] == -1 if vertex i is not matched. This function takes time O(n ** 3).""" # # Vertices are numbered 0 .. (nvertex-1). # Non-trivial blossoms are numbered nvertex .. (2*nvertex-1) # # Edges are numbered 0 .. (nedge-1). # Edge endpoints are numbered 0 .. (2*nedge-1), such that endpoints # (2*k) and (2*k+1) both belong to edge k. # # Many terms used in the comments (sub-blossom, T-vertex) come from # the paper by Galil; read the paper before reading this code. # # Python 2/3 compatibility. from sys import version as sys_version if sys_version < '3': integer_types = (int, long) else: integer_types = (int,) # Deal swiftly with empty graphs. if not edges: return [ ] # Count vertices. nedge = len(edges) nvertex = 0 for (i, j, w) in edges: assert i >= 0 and j >= 0 and i != j if i >= nvertex: nvertex = i + 1 if j >= nvertex: nvertex = j + 1 # Find the maximum edge weight. maxweight = max(0, max([ wt for (i, j, wt) in edges ])) # If p is an edge endpoint, # endpoint[p] is the vertex to which endpoint p is attached. # Not modified by the algorithm. endpoint = [ edges[p//2][p%2] for p in range(2*nedge) ] # If v is a vertex, # neighbend[v] is the list of remote endpoints of the edges attached to v. # Not modified by the algorithm. neighbend = [ [ ] for i in range(nvertex) ] for k in range(len(edges)): (i, j, w) = edges[k] neighbend[i].append(2*k+1) neighbend[j].append(2*k) # If v is a vertex, # mate[v] is the remote endpoint of its matched edge, or -1 if it is single # (i.e. endpoint[mate[v]] is v's partner vertex). # Initially all vertices are single; updated during augmentation. mate = nvertex * [ -1 ] # If b is a top-level blossom, # label[b] is 0 if b is unlabeled (free); # 1 if b is an S-vertex/blossom; # 2 if b is a T-vertex/blossom. # The label of a vertex is found by looking at the label of its # top-level containing blossom. # If v is a vertex inside a T-blossom, # label[v] is 2 iff v is reachable from an S-vertex outside the blossom. # Labels are assigned during a stage and reset after each augmentation. label = (2 * nvertex) * [ 0 ] # If b is a labeled top-level blossom, # labelend[b] is the remote endpoint of the edge through which b obtained # its label, or -1 if b's base vertex is single. # If v is a vertex inside a T-blossom and label[v] == 2, # labelend[v] is the remote endpoint of the edge through which v is # reachable from outside the blossom. labelend = (2 * nvertex) * [ -1 ] # If v is a vertex, # inblossom[v] is the top-level blossom to which v belongs. # If v is a top-level vertex, v is itself a blossom (a trivial blossom) # and inblossom[v] == v. # Initially all vertices are top-level trivial blossoms. inblossom = list(range(nvertex)) # If b is a sub-blossom, # blossomparent[b] is its immediate parent (sub-)blossom. # If b is a top-level blossom, blossomparent[b] is -1. blossomparent = (2 * nvertex) * [ -1 ] # If b is a non-trivial (sub-)blossom, # blossomchilds[b] is an ordered list of its sub-blossoms, starting with # the base and going round the blossom. blossomchilds = (2 * nvertex) * [ None ] # If b is a (sub-)blossom, # blossombase[b] is its base VERTEX (i.e. recursive sub-blossom). blossombase = list(range(nvertex)) + nvertex * [ -1 ] # If b is a non-trivial (sub-)blossom, # blossomendps[b] is a list of endpoints on its connecting edges, # such that blossomendps[b][i] is the local endpoint of blossomchilds[b][i] # on the edge that connects it to blossomchilds[b][wrap(i+1)]. blossomendps = (2 * nvertex) * [ None ] # If v is a free vertex (or an unreached vertex inside a T-blossom), # bestedge[v] is the edge to an S-vertex with least slack, # or -1 if there is no such edge. # If b is a (possibly trivial) top-level S-blossom, # bestedge[b] is the least-slack edge to a different S-blossom, # or -1 if there is no such edge. # This is used for efficient computation of delta2 and delta3. bestedge = (2 * nvertex) * [ -1 ] # If b is a non-trivial top-level S-blossom, # blossombestedges[b] is a list of least-slack edges to neighbouring # S-blossoms, or None if no such list has been computed yet. # This is used for efficient computation of delta3. blossombestedges = (2 * nvertex) * [ None ] # List of currently unused blossom numbers. unusedblossoms = list(range(nvertex, 2*nvertex)) # If v is a vertex, # dualvar[v] = 2 * u(v) where u(v) is the v's variable in the dual # optimization problem (multiplication by two ensures integer values # throughout the algorithm if all edge weights are integers). # If b is a non-trivial blossom, # dualvar[b] = z(b) where z(b) is b's variable in the dual optimization # problem. dualvar = nvertex * [ maxweight ] + nvertex * [ 0 ] # If allowedge[k] is true, edge k has zero slack in the optimization # problem; if allowedge[k] is false, the edge's slack may or may not # be zero. allowedge = nedge * [ False ] # Queue of newly discovered S-vertices. queue = [ ] # Return 2 * slack of edge k (does not work inside blossoms). def slack(k): (i, j, wt) = edges[k] return dualvar[i] + dualvar[j] - 2 * wt # Generate the leaf vertices of a blossom. def blossomLeaves(b): if b < nvertex: yield b else: for t in blossomchilds[b]: if t < nvertex: yield t else: for v in blossomLeaves(t): yield v # Assign label t to the top-level blossom containing vertex w # and record the fact that w was reached through the edge with # remote endpoint p. def assignLabel(w, t, p): if DEBUG: DEBUG('assignLabel(%d,%d,%d)' % (w, t, p)) b = inblossom[w] assert label[w] == 0 and label[b] == 0 label[w] = label[b] = t labelend[w] = labelend[b] = p bestedge[w] = bestedge[b] = -1 if t == 1: # b became an S-vertex/blossom; add it(s vertices) to the queue. queue.extend(blossomLeaves(b)) if DEBUG: DEBUG('PUSH ' + str(list(blossomLeaves(b)))) elif t == 2: # b became a T-vertex/blossom; assign label S to its mate. # (If b is a non-trivial blossom, its base is the only vertex # with an external mate.) base = blossombase[b] assert mate[base] >= 0 assignLabel(endpoint[mate[base]], 1, mate[base] ^ 1) # Trace back from vertices v and w to discover either a new blossom # or an augmenting path. Return the base vertex of the new blossom or -1. def scanBlossom(v, w): if DEBUG: DEBUG('scanBlossom(%d,%d)' % (v, w)) # Trace back from v and w, placing breadcrumbs as we go. path = [ ] base = -1 while v != -1 or w != -1: # Look for a breadcrumb in v's blossom or put a new breadcrumb. b = inblossom[v] if label[b] & 4: base = blossombase[b] break assert label[b] == 1 path.append(b) label[b] = 5 # Trace one step back. assert labelend[b] == mate[blossombase[b]] if labelend[b] == -1: # The base of blossom b is single; stop tracing this path. v = -1 else: v = endpoint[labelend[b]] b = inblossom[v] assert label[b] == 2 # b is a T-blossom; trace one more step back. assert labelend[b] >= 0 v = endpoint[labelend[b]] # Swap v and w so that we alternate between both paths. if w != -1: v, w = w, v # Remove breadcrumbs. for b in path: label[b] = 1 # Return base vertex, if we found one. return base # Construct a new blossom with given base, containing edge k which # connects a pair of S vertices. Label the new blossom as S; set its dual # variable to zero; relabel its T-vertices to S and add them to the queue. def addBlossom(base, k): (v, w, wt) = edges[k] bb = inblossom[base] bv = inblossom[v] bw = inblossom[w] # Create blossom. b = unusedblossoms.pop() if DEBUG: DEBUG('addBlossom(%d,%d) (v=%d w=%d) -> %d' % (base, k, v, w, b)) blossombase[b] = base blossomparent[b] = -1 blossomparent[bb] = b # Make list of sub-blossoms and their interconnecting edge endpoints. blossomchilds[b] = path = [ ] blossomendps[b] = endps = [ ] # Trace back from v to base. while bv != bb: # Add bv to the new blossom. blossomparent[bv] = b path.append(bv) endps.append(labelend[bv]) assert (label[bv] == 2 or (label[bv] == 1 and labelend[bv] == mate[blossombase[bv]])) # Trace one step back. assert labelend[bv] >= 0 v = endpoint[labelend[bv]] bv = inblossom[v] # Reverse lists, add endpoint that connects the pair of S vertices. path.append(bb) path.reverse() endps.reverse() endps.append(2*k) # Trace back from w to base. while bw != bb: # Add bw to the new blossom. blossomparent[bw] = b path.append(bw) endps.append(labelend[bw] ^ 1) assert (label[bw] == 2 or (label[bw] == 1 and labelend[bw] == mate[blossombase[bw]])) # Trace one step back. assert labelend[bw] >= 0 w = endpoint[labelend[bw]] bw = inblossom[w] # Set label to S. assert label[bb] == 1 label[b] = 1 labelend[b] = labelend[bb] # Set dual variable to zero. dualvar[b] = 0 # Relabel vertices. for v in blossomLeaves(b): if label[inblossom[v]] == 2: # This T-vertex now turns into an S-vertex because it becomes # part of an S-blossom; add it to the queue. queue.append(v) inblossom[v] = b # Compute blossombestedges[b]. bestedgeto = (2 * nvertex) * [ -1 ] for bv in path: if blossombestedges[bv] is None: # This subblossom does not have a list of least-slack edges; # get the information from the vertices. nblists = [ [ p // 2 for p in neighbend[v] ] for v in blossomLeaves(bv) ] else: # Walk this subblossom's least-slack edges. nblists = [ blossombestedges[bv] ] for nblist in nblists: for k in nblist: (i, j, wt) = edges[k] if inblossom[j] == b: i, j = j, i bj = inblossom[j] if (bj != b and label[bj] == 1 and (bestedgeto[bj] == -1 or slack(k) < slack(bestedgeto[bj]))): bestedgeto[bj] = k # Forget about least-slack edges of the subblossom. blossombestedges[bv] = None bestedge[bv] = -1 blossombestedges[b] = [ k for k in bestedgeto if k != -1 ] # Select bestedge[b]. bestedge[b] = -1 for k in blossombestedges[b]: if bestedge[b] == -1 or slack(k) < slack(bestedge[b]): bestedge[b] = k if DEBUG: DEBUG('blossomchilds[%d]=' % b + repr(blossomchilds[b])) # Expand the given top-level blossom. def expandBlossom(b, endstage): if DEBUG: DEBUG('expandBlossom(%d,%d) %s' % (b, endstage, repr(blossomchilds[b]))) # Convert sub-blossoms into top-level blossoms. for s in blossomchilds[b]: blossomparent[s] = -1 if s < nvertex: inblossom[s] = s elif endstage and dualvar[s] == 0: # Recursively expand this sub-blossom. expandBlossom(s, endstage) else: for v in blossomLeaves(s): inblossom[v] = s # If we expand a T-blossom during a stage, its sub-blossoms must be # relabeled. if (not endstage) and label[b] == 2: # Start at the sub-blossom through which the expanding # blossom obtained its label, and relabel sub-blossoms untili # we reach the base. # Figure out through which sub-blossom the expanding blossom # obtained its label initially. assert labelend[b] >= 0 entrychild = inblossom[endpoint[labelend[b] ^ 1]] # Decide in which direction we will go round the blossom. j = blossomchilds[b].index(entrychild) if j & 1: # Start index is odd; go forward and wrap. j -= len(blossomchilds[b]) jstep = 1 endptrick = 0 else: # Start index is even; go backward. jstep = -1 endptrick = 1 # Move along the blossom until we get to the base. p = labelend[b] while j != 0: # Relabel the T-sub-blossom. label[endpoint[p ^ 1]] = 0 label[endpoint[blossomendps[b][j-endptrick]^endptrick^1]] = 0 assignLabel(endpoint[p ^ 1], 2, p) # Step to the next S-sub-blossom and note its forward endpoint. allowedge[blossomendps[b][j-endptrick]//2] = True j += jstep p = blossomendps[b][j-endptrick] ^ endptrick # Step to the next T-sub-blossom. allowedge[p//2] = True j += jstep # Relabel the base T-sub-blossom WITHOUT stepping through to # its mate (so don't call assignLabel). bv = blossomchilds[b][j] label[endpoint[p ^ 1]] = label[bv] = 2 labelend[endpoint[p ^ 1]] = labelend[bv] = p bestedge[bv] = -1 # Continue along the blossom until we get back to entrychild. j += jstep while blossomchilds[b][j] != entrychild: # Examine the vertices of the sub-blossom to see whether # it is reachable from a neighbouring S-vertex outside the # expanding blossom. bv = blossomchilds[b][j] if label[bv] == 1: # This sub-blossom just got label S through one of its # neighbours; leave it. j += jstep continue for v in blossomLeaves(bv): if label[v] != 0: break # If the sub-blossom contains a reachable vertex, assign # label T to the sub-blossom. if label[v] != 0: assert label[v] == 2 assert inblossom[v] == bv label[v] = 0 label[endpoint[mate[blossombase[bv]]]] = 0 assignLabel(v, 2, labelend[v]) j += jstep # Recycle the blossom number. label[b] = labelend[b] = -1 blossomchilds[b] = blossomendps[b] = None blossombase[b] = -1 blossombestedges[b] = None bestedge[b] = -1 unusedblossoms.append(b) # Swap matched/unmatched edges over an alternating path through blossom b # between vertex v and the base vertex. Keep blossom bookkeeping consistent. def augmentBlossom(b, v): if DEBUG: DEBUG('augmentBlossom(%d,%d)' % (b, v)) # Bubble up through the blossom tree from vertex v to an immediate # sub-blossom of b. t = v while blossomparent[t] != b: t = blossomparent[t] # Recursively deal with the first sub-blossom. if t >= nvertex: augmentBlossom(t, v) # Decide in which direction we will go round the blossom. i = j = blossomchilds[b].index(t) if i & 1: # Start index is odd; go forward and wrap. j -= len(blossomchilds[b]) jstep = 1 endptrick = 0 else: # Start index is even; go backward. jstep = -1 endptrick = 1 # Move along the blossom until we get to the base. while j != 0: # Step to the next sub-blossom and augment it recursively. j += jstep t = blossomchilds[b][j] p = blossomendps[b][j-endptrick] ^ endptrick if t >= nvertex: augmentBlossom(t, endpoint[p]) # Step to the next sub-blossom and augment it recursively. j += jstep t = blossomchilds[b][j] if t >= nvertex: augmentBlossom(t, endpoint[p ^ 1]) # Match the edge connecting those sub-blossoms. mate[endpoint[p]] = p ^ 1 mate[endpoint[p ^ 1]] = p if DEBUG: DEBUG('PAIR %d %d (k=%d)' % (endpoint[p], endpoint[p^1], p//2)) # Rotate the list of sub-blossoms to put the new base at the front. blossomchilds[b] = blossomchilds[b][i:] + blossomchilds[b][:i] blossomendps[b] = blossomendps[b][i:] + blossomendps[b][:i] blossombase[b] = blossombase[blossomchilds[b][0]] assert blossombase[b] == v # Swap matched/unmatched edges over an alternating path between two # single vertices. The augmenting path runs through edge k, which # connects a pair of S vertices. def augmentMatching(k): (v, w, wt) = edges[k] if DEBUG: DEBUG('augmentMatching(%d) (v=%d w=%d)' % (k, v, w)) if DEBUG: DEBUG('PAIR %d %d (k=%d)' % (v, w, k)) for (s, p) in ((v, 2*k+1), (w, 2*k)): # Match vertex s to remote endpoint p. Then trace back from s # until we find a single vertex, swapping matched and unmatched # edges as we go. while 1: bs = inblossom[s] assert label[bs] == 1 assert labelend[bs] == mate[blossombase[bs]] # Augment through the S-blossom from s to base. if bs >= nvertex: augmentBlossom(bs, s) # Update mate[s] mate[s] = p # Trace one step back. if labelend[bs] == -1: # Reached single vertex; stop. break t = endpoint[labelend[bs]] bt = inblossom[t] assert label[bt] == 2 # Trace one step back. assert labelend[bt] >= 0 s = endpoint[labelend[bt]] j = endpoint[labelend[bt] ^ 1] # Augment through the T-blossom from j to base. assert blossombase[bt] == t if bt >= nvertex: augmentBlossom(bt, j) # Update mate[j] mate[j] = labelend[bt] # Keep the opposite endpoint; # it will be assigned to mate[s] in the next step. p = labelend[bt] ^ 1 if DEBUG: DEBUG('PAIR %d %d (k=%d)' % (s, t, p//2)) # Verify that the optimum solution has been reached. def verifyOptimum(): if maxcardinality: # Vertices may have negative dual; # find a constant non-negative number to add to all vertex duals. vdualoffset = max(0, -min(dualvar[:nvertex])) else: vdualoffset = 0 # 0. all dual variables are non-negative assert min(dualvar[:nvertex]) + vdualoffset >= 0 assert min(dualvar[nvertex:]) >= 0 # 0. all edges have non-negative slack and # 1. all matched edges have zero slack; for k in range(nedge): (i, j, wt) = edges[k] s = dualvar[i] + dualvar[j] - 2 * wt iblossoms = [ i ] jblossoms = [ j ] while blossomparent[iblossoms[-1]] != -1: iblossoms.append(blossomparent[iblossoms[-1]]) while blossomparent[jblossoms[-1]] != -1: jblossoms.append(blossomparent[jblossoms[-1]]) iblossoms.reverse() jblossoms.reverse() for (bi, bj) in zip(iblossoms, jblossoms): if bi != bj: break s += 2 * dualvar[bi] assert s >= 0 if mate[i] // 2 == k or mate[j] // 2 == k: assert mate[i] // 2 == k and mate[j] // 2 == k assert s == 0 # 2. all single vertices have zero dual value; for v in range(nvertex): assert mate[v] >= 0 or dualvar[v] + vdualoffset == 0 # 3. all blossoms with positive dual value are full. for b in range(nvertex, 2*nvertex): if blossombase[b] >= 0 and dualvar[b] > 0: assert len(blossomendps[b]) % 2 == 1 for p in blossomendps[b][1::2]: assert mate[endpoint[p]] == p ^ 1 assert mate[endpoint[p ^ 1]] == p # Ok. # Check optimized delta2 against a trivial computation. def checkDelta2(): for v in range(nvertex): if label[inblossom[v]] == 0: bd = None bk = -1 for p in neighbend[v]: k = p // 2 w = endpoint[p] if label[inblossom[w]] == 1: d = slack(k) if bk == -1 or d < bd: bk = k bd = d if DEBUG and (bestedge[v] != -1 or bk != -1) and (bestedge[v] == -1 or bd != slack(bestedge[v])): DEBUG('v=' + str(v) + ' bk=' + str(bk) + ' bd=' + str(bd) + ' bestedge=' + str(bestedge[v]) + ' slack=' + str(slack(bestedge[v]))) assert (bk == -1 and bestedge[v] == -1) or (bestedge[v] != -1 and bd == slack(bestedge[v])) # Check optimized delta3 against a trivial computation. def checkDelta3(): bk = -1 bd = None tbk = -1 tbd = None for b in range(2 * nvertex): if blossomparent[b] == -1 and label[b] == 1: for v in blossomLeaves(b): for p in neighbend[v]: k = p // 2 w = endpoint[p] if inblossom[w] != b and label[inblossom[w]] == 1: d = slack(k) if bk == -1 or d < bd: bk = k bd = d if bestedge[b] != -1: (i, j, wt) = edges[bestedge[b]] assert inblossom[i] == b or inblossom[j] == b assert inblossom[i] != b or inblossom[j] != b assert label[inblossom[i]] == 1 and label[inblossom[j]] == 1 if tbk == -1 or slack(bestedge[b]) < tbd: tbk = bestedge[b] tbd = slack(bestedge[b]) if DEBUG and bd != tbd: DEBUG('bk=%d tbk=%d bd=%s tbd=%s' % (bk, tbk, repr(bd), repr(tbd))) assert bd == tbd # Main loop: continue until no further improvement is possible. for t in range(nvertex): # Each iteration of this loop is a "stage". # A stage finds an augmenting path and uses that to improve # the matching. if DEBUG: DEBUG('STAGE %d' % t) # Remove labels from top-level blossoms/vertices. label[:] = (2 * nvertex) * [ 0 ] # Forget all about least-slack edges. bestedge[:] = (2 * nvertex) * [ -1 ] blossombestedges[nvertex:] = nvertex * [ None ] # Loss of labeling means that we can not be sure that currently # allowable edges remain allowable througout this stage. allowedge[:] = nedge * [ False ] # Make queue empty. queue[:] = [ ] # Label single blossoms/vertices with S and put them in the queue. for v in range(nvertex): if mate[v] == -1 and label[inblossom[v]] == 0: assignLabel(v, 1, -1) # Loop until we succeed in augmenting the matching. augmented = 0 while 1: # Each iteration of this loop is a "substage". # A substage tries to find an augmenting path; # if found, the path is used to improve the matching and # the stage ends. If there is no augmenting path, the # primal-dual method is used to pump some slack out of # the dual variables. if DEBUG: DEBUG('SUBSTAGE') # Continue labeling until all vertices which are reachable # through an alternating path have got a label. while queue and not augmented: # Take an S vertex from the queue. v = queue.pop() if DEBUG: DEBUG('POP v=%d' % v) assert label[inblossom[v]] == 1 # Scan its neighbours: for p in neighbend[v]: k = p // 2 w = endpoint[p] # w is a neighbour to v if inblossom[v] == inblossom[w]: # this edge is internal to a blossom; ignore it continue if not allowedge[k]: kslack = slack(k) if kslack <= 0: # edge k has zero slack => it is allowable allowedge[k] = True if allowedge[k]: if label[inblossom[w]] == 0: # (C1) w is a free vertex; # label w with T and label its mate with S (R12). assignLabel(w, 2, p ^ 1) elif label[inblossom[w]] == 1: # (C2) w is an S-vertex (not in the same blossom); # follow back-links to discover either an # augmenting path or a new blossom. base = scanBlossom(v, w) if base >= 0: # Found a new blossom; add it to the blossom # bookkeeping and turn it into an S-blossom. addBlossom(base, k) else: # Found an augmenting path; augment the # matching and end this stage. augmentMatching(k) augmented = 1 break elif label[w] == 0: # w is inside a T-blossom, but w itself has not # yet been reached from outside the blossom; # mark it as reached (we need this to relabel # during T-blossom expansion). assert label[inblossom[w]] == 2 label[w] = 2 labelend[w] = p ^ 1 elif label[inblossom[w]] == 1: # keep track of the least-slack non-allowable edge to # a different S-blossom. b = inblossom[v] if bestedge[b] == -1 or kslack < slack(bestedge[b]): bestedge[b] = k elif label[w] == 0: # w is a free vertex (or an unreached vertex inside # a T-blossom) but we can not reach it yet; # keep track of the least-slack edge that reaches w. if bestedge[w] == -1 or kslack < slack(bestedge[w]): bestedge[w] = k if augmented: break # There is no augmenting path under these constraints; # compute delta and reduce slack in the optimization problem. # (Note that our vertex dual variables, edge slacks and delta's # are pre-multiplied by two.) deltatype = -1 delta = deltaedge = deltablossom = None # Verify data structures for delta2/delta3 computation. if CHECK_DELTA: checkDelta2() checkDelta3() # Compute delta1: the minumum value of any vertex dual. if not maxcardinality: deltatype = 1 delta = min(dualvar[:nvertex]) # Compute delta2: the minimum slack on any edge between # an S-vertex and a free vertex. for v in range(nvertex): if label[inblossom[v]] == 0 and bestedge[v] != -1: d = slack(bestedge[v]) if deltatype == -1 or d < delta: delta = d deltatype = 2 deltaedge = bestedge[v] # Compute delta3: half the minimum slack on any edge between # a pair of S-blossoms. for b in range(2 * nvertex): if ( blossomparent[b] == -1 and label[b] == 1 and bestedge[b] != -1 ): kslack = slack(bestedge[b]) if isinstance(kslack, integer_types): assert (kslack % 2) == 0 d = kslack // 2 else: d = kslack / 2 if deltatype == -1 or d < delta: delta = d deltatype = 3 deltaedge = bestedge[b] # Compute delta4: minimum z variable of any T-blossom. for b in range(nvertex, 2*nvertex): if ( blossombase[b] >= 0 and blossomparent[b] == -1 and label[b] == 2 and (deltatype == -1 or dualvar[b] < delta) ): delta = dualvar[b] deltatype = 4 deltablossom = b if deltatype == -1: # No further improvement possible; max-cardinality optimum # reached. Do a final delta update to make the optimum # verifyable. assert maxcardinality deltatype = 1 delta = max(0, min(dualvar[:nvertex])) # Update dual variables according to delta. for v in range(nvertex): if label[inblossom[v]] == 1: # S-vertex: 2*u = 2*u - 2*delta dualvar[v] -= delta elif label[inblossom[v]] == 2: # T-vertex: 2*u = 2*u + 2*delta dualvar[v] += delta for b in range(nvertex, 2*nvertex): if blossombase[b] >= 0 and blossomparent[b] == -1: if label[b] == 1: # top-level S-blossom: z = z + 2*delta dualvar[b] += delta elif label[b] == 2: # top-level T-blossom: z = z - 2*delta dualvar[b] -= delta # Take action at the point where minimum delta occurred. if DEBUG: DEBUG('delta%d=%f' % (deltatype, delta)) if deltatype == 1: # No further improvement possible; optimum reached. break elif deltatype == 2: # Use the least-slack edge to continue the search. allowedge[deltaedge] = True (i, j, wt) = edges[deltaedge] if label[inblossom[i]] == 0: i, j = j, i assert label[inblossom[i]] == 1 queue.append(i) elif deltatype == 3: # Use the least-slack edge to continue the search. allowedge[deltaedge] = True (i, j, wt) = edges[deltaedge] assert label[inblossom[i]] == 1 queue.append(i) elif deltatype == 4: # Expand the least-z blossom. expandBlossom(deltablossom, False) # End of a this substage. # Stop when no more augmenting path can be found. if not augmented: break # End of a stage; expand all S-blossoms which have dualvar = 0. for b in range(nvertex, 2*nvertex): if ( blossomparent[b] == -1 and blossombase[b] >= 0 and label[b] == 1 and dualvar[b] == 0 ): expandBlossom(b, True) # Verify that we reached the optimum solution. if CHECK_OPTIMUM: verifyOptimum() # Transform mate[] such that mate[v] is the vertex to which v is paired. for v in range(nvertex): if mate[v] >= 0: mate[v] = endpoint[mate[v]] for v in range(nvertex): assert mate[v] == -1 or mate[mate[v]] == v return mate
bvancsics/TCMC
maximum_matching.py
Python
gpl-3.0
35,707
########################################################################## # Copyright (C) 2009 - 2014 Huygens ING & Gerbrandy S.R.L. # # This file is part of bioport. # # bioport 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/gpl-3.0.html>. ########################################################################## import os #import sys import unittest import shutil import datetime from bioport_repository.common import to_date, format_date class CommonTestCase(unittest.TestCase): def test_to_date(self): self.assertEqual(to_date('2000'), datetime.datetime(2000, 1, 1, 0, 0)) self.assertEqual(to_date('2000-02'), datetime.datetime(2000, 2, 1, 0, 0)) self.assertEqual(to_date('2000-02-03'), datetime.datetime(2000, 2, 3, 0, 0)) self.assertEqual(to_date('2001-02', round='up'), datetime.datetime(2001, 2, 28, 0, 0)) #2000 is a leap year self.assertEqual(to_date('2000-02', round='up'), datetime.datetime(2000, 2, 29, 0, 0)) self.assertEqual(to_date('2000-12', round='up'), datetime.datetime(2000, 12, 31, 0, 0)) self.assertEqual(to_date('2000', round='up'), datetime.datetime(2000, 12, 31, 0, 0)) self.assertEqual(to_date('0200', round='up'), datetime.datetime(200, 12, 31, 0, 0)) self.assertEqual(to_date('1200', ), datetime.datetime(1200, 1, 1, 0, 0)) def test_format_date(self): d = datetime.datetime(1700, 3, 2) self.assertEqual(format_date(d), '1700-03-02 00:00') d = datetime.datetime(1, 3, 2) self.assertEqual(format_date(d), '0001-03-02 00:00') def test_suite(): return unittest.TestSuite(( unittest.makeSuite(CommonTestCase, 'test'), )) if __name__=='__main__': unittest.main(defaultTest='test_suite')
HuygensING/bioport-repository
bioport_repository/tests/test_common.py
Python
gpl-3.0
2,361