repo_name
stringlengths
5
100
path
stringlengths
4
294
copies
stringclasses
990 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
ZECTBynmo/notnode-gyp
gyp/test/mac/gyptest-ldflags.py
244
1864
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that filenames passed to various linker flags are converted into build-directory relative paths correctly. """ import TestGyp import sys if sys.platform == 'darwin': test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode']) CHDIR = 'ldflags' test.run_gyp('subdirectory/test.gyp', chdir=CHDIR) test.build('subdirectory/test.gyp', test.ALL, chdir=CHDIR) test.pass_test() # These flags from `man ld` couldl show up in OTHER_LDFLAGS and need path # translation. # # Done: # -exported_symbols_list filename # -unexported_symbols_list file # -reexported_symbols_list file # -sectcreate segname sectname file # # Will be done on demand: # -weak_library path_to_library # -reexport_library path_to_library # -lazy_library path_to_library # -upward_library path_to_library # -syslibroot rootdir # -framework name[,suffix] # -weak_framework name[,suffix] # -reexport_framework name[,suffix] # -lazy_framework name[,suffix] # -upward_framework name[,suffix] # -force_load path_to_archive # -filelist file[,dirname] # -dtrace file # -order_file file # should use ORDER_FILE # -exported_symbols_order file # -bundle_loader executable # should use BUNDLE_LOADER # -alias_list filename # -seg_addr_table filename # -dylib_file install_name:file_name # -interposable_list filename # -object_path_lto filename # # # obsolete: # -sectorder segname sectname orderfile # -seg_addr_table_filename path # # # ??: # -map map_file_path # -sub_library library_name # -sub_umbrella framework_name
mit
erkrishna9/odoo
openerp/report/render/rml2html/rml2html.py
438
15438
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2005, Fabien Pinckaers, UCL, FSA # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # ############################################################################## import sys import cStringIO from lxml import etree import copy from openerp.report.render.rml2pdf import utils class _flowable(object): def __init__(self, template, doc, localcontext = None): self._tags = { 'title': self._tag_title, 'spacer': self._tag_spacer, 'para': self._tag_para, 'section':self._section, 'nextFrame': self._tag_next_frame, 'blockTable': self._tag_table, 'pageBreak': self._tag_page_break, 'setNextTemplate': self._tag_next_template, } self.template = template self.doc = doc self.localcontext = localcontext self._cache = {} def _tag_page_break(self, node): return '<br/>'*3 def _tag_next_template(self, node): return '' def _tag_next_frame(self, node): result=self.template.frame_stop() result+='<br/>' result+=self.template.frame_start() return result def _tag_title(self, node): node.tag='h1' return etree.tostring(node) def _tag_spacer(self, node): length = 1+int(utils.unit_get(node.get('length')))/35 return "<br/>"*length def _tag_table(self, node): new_node = copy.deepcopy(node) for child in new_node: new_node.remove(child) new_node.tag = 'table' def process(node,new_node): for child in utils._child_get(node,self): new_child = copy.deepcopy(child) new_node.append(new_child) if len(child): for n in new_child: new_child.remove(n) process(child, new_child) else: new_child.text = utils._process_text(self, child.text) new_child.tag = 'p' try: if new_child.get('style').find('terp_tblheader')!= -1: new_node.tag = 'th' except Exception: pass process(node,new_node) if new_node.get('colWidths',False): sizes = map(lambda x: utils.unit_get(x), new_node.get('colWidths').split(',')) tr = etree.SubElement(new_node, 'tr') for s in sizes: etree.SubElement(tr, 'td', width=str(s)) return etree.tostring(new_node) def _tag_para(self, node): new_node = copy.deepcopy(node) new_node.tag = 'p' if new_node.attrib.get('style',False): new_node.set('class', new_node.get('style')) new_node.text = utils._process_text(self, node.text) return etree.tostring(new_node) def _section(self, node): result = '' for child in utils._child_get(node, self): if child.tag in self._tags: result += self._tags[child.tag](child) return result def render(self, node): result = self.template.start() result += self.template.frame_start() for n in utils._child_get(node, self): if n.tag in self._tags: result += self._tags[n.tag](n) else: pass result += self.template.frame_stop() result += self.template.end() return result.encode('utf-8').replace('"',"\'").replace('°','&deg;') class _rml_tmpl_tag(object): def __init__(self, *args): pass def tag_start(self): return '' def tag_end(self): return False def tag_stop(self): return '' def tag_mergeable(self): return True class _rml_tmpl_frame(_rml_tmpl_tag): def __init__(self, posx, width): self.width = width self.posx = posx def tag_start(self): return "<table border=\'0\' width=\'%d\'><tr><td width=\'%d\'>&nbsp;</td><td>" % (self.width+self.posx,self.posx) def tag_end(self): return True def tag_stop(self): return '</td></tr></table><br/>' def tag_mergeable(self): return False def merge(self, frame): pass class _rml_tmpl_draw_string(_rml_tmpl_tag): def __init__(self, node, style,localcontext = {}): self.localcontext = localcontext self.posx = utils.unit_get(node.get('x')) self.posy = utils.unit_get(node.get('y')) aligns = { 'drawString': 'left', 'drawRightString': 'right', 'drawCentredString': 'center' } align = aligns[node.tag] self.pos = [(self.posx, self.posy, align, utils._process_text(self, node.text), style.get('td'), style.font_size_get('td'))] def tag_start(self): self.pos.sort() res = "<table border='0' cellpadding='0' cellspacing='0'><tr>" posx = 0 i = 0 for (x,y,align,txt, style, fs) in self.pos: if align=="left": pos2 = len(txt)*fs res+="<td width=\'%d\'></td><td style=\'%s\' width=\'%d\'>%s</td>" % (x - posx, style, pos2, txt) posx = x+pos2 if align=="right": res+="<td width=\'%d\' align=\'right\' style=\'%s\'>%s</td>" % (x - posx, style, txt) posx = x if align=="center": res+="<td width=\'%d\' align=\'center\' style=\'%s\'>%s</td>" % ((x - posx)*2, style, txt) posx = 2*x-posx i+=1 res+='</tr></table>' return res def merge(self, ds): self.pos+=ds.pos class _rml_tmpl_draw_lines(_rml_tmpl_tag): def __init__(self, node, style, localcontext = {}): self.localcontext = localcontext coord = [utils.unit_get(x) for x in utils._process_text(self, node.text).split(' ')] self.ok = False self.posx = coord[0] self.posy = coord[1] self.width = coord[2]-coord[0] self.ok = coord[1]==coord[3] self.style = style self.style = style.get('hr') def tag_start(self): if self.ok: return "<table border=\'0\' cellpadding=\'0\' cellspacing=\'0\' width=\'%d\'><tr><td width=\'%d\'></td><td><hr width=\'100%%\' style=\'margin:0px; %s\'></td></tr></table>" % (self.posx+self.width,self.posx,self.style) else: return '' class _rml_stylesheet(object): def __init__(self, localcontext, stylesheet, doc): self.doc = doc self.localcontext = localcontext self.attrs = {} self._tags = { 'fontSize': lambda x: ('font-size',str(utils.unit_get(x)+5.0)+'px'), 'alignment': lambda x: ('text-align',str(x)) } result = '' for ps in stylesheet.findall('paraStyle'): attr = {} attrs = ps.attrib for key, val in attrs.items(): attr[key] = val attrs = [] for a in attr: if a in self._tags: attrs.append('%s:%s' % self._tags[a](attr[a])) if len(attrs): result += 'p.'+attr['name']+' {'+'; '.join(attrs)+'}\n' self.result = result def render(self): return self.result class _rml_draw_style(object): def __init__(self): self.style = {} self._styles = { 'fill': lambda x: {'td': {'color':x.get('color')}}, 'setFont': lambda x: {'td': {'font-size':x.get('size')+'px'}}, 'stroke': lambda x: {'hr': {'color':x.get('color')}}, } def update(self, node): if node.tag in self._styles: result = self._styles[node.tag](node) for key in result: if key in self.style: self.style[key].update(result[key]) else: self.style[key] = result[key] def font_size_get(self,tag): size = utils.unit_get(self.style.get('td', {}).get('font-size','16')) return size def get(self,tag): if not tag in self.style: return "" return ';'.join(['%s:%s' % (x[0],x[1]) for x in self.style[tag].items()]) class _rml_template(object): def __init__(self, template, localcontext=None): self.frame_pos = -1 self.localcontext = localcontext self.frames = [] self.template_order = [] self.page_template = {} self.loop = 0 self._tags = { 'drawString': _rml_tmpl_draw_string, 'drawRightString': _rml_tmpl_draw_string, 'drawCentredString': _rml_tmpl_draw_string, 'lines': _rml_tmpl_draw_lines } self.style = _rml_draw_style() rc = 'data:image/png;base64,' self.data = '' for pt in template.findall('pageTemplate'): frames = {} id = pt.get('id') self.template_order.append(id) for tmpl in pt.findall('frame'): posy = int(utils.unit_get(tmpl.get('y1'))) posx = int(utils.unit_get(tmpl.get('x1'))) frames[(posy,posx,tmpl.get('id'))] = _rml_tmpl_frame(posx, utils.unit_get(tmpl.get('width'))) for tmpl in pt.findall('pageGraphics'): for n in tmpl: if n.tag == 'image': self.data = rc + utils._process_text(self, n.text) if n.tag in self._tags: t = self._tags[n.tag](n, self.style,self.localcontext) frames[(t.posy,t.posx,n.tag)] = t else: self.style.update(n) keys = frames.keys() keys.sort() keys.reverse() self.page_template[id] = [] for key in range(len(keys)): if key>0 and keys[key-1][0] == keys[key][0]: if type(self.page_template[id][-1]) == type(frames[keys[key]]): if self.page_template[id][-1].tag_mergeable(): self.page_template[id][-1].merge(frames[keys[key]]) continue self.page_template[id].append(frames[keys[key]]) self.template = self.template_order[0] def _get_style(self): return self.style def set_next_template(self): self.template = self.template_order[(self.template_order.index(name)+1) % self.template_order] self.frame_pos = -1 def set_template(self, name): self.template = name self.frame_pos = -1 def frame_start(self): result = '' frames = self.page_template[self.template] ok = True while ok: self.frame_pos += 1 if self.frame_pos>=len(frames): self.frame_pos=0 self.loop=1 ok = False continue f = frames[self.frame_pos] result+=f.tag_start() ok = not f.tag_end() if ok: result+=f.tag_stop() return result def frame_stop(self): frames = self.page_template[self.template] f = frames[self.frame_pos] result=f.tag_stop() return result def start(self): return '' def end(self): result = '' while not self.loop: result += self.frame_start() result += self.frame_stop() return result class _rml_doc(object): def __init__(self, data, localcontext): self.dom = etree.XML(data) self.localcontext = localcontext self.filename = self.dom.get('filename') self.result = '' def render(self, out): self.result += '''<!DOCTYPE HTML PUBLIC "-//w3c//DTD HTML 4.0 Frameset//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> p {margin:0px; font-size:12px;} td {font-size:14px;} ''' style = self.dom.findall('stylesheet')[0] s = _rml_stylesheet(self.localcontext, style, self.dom) self.result += s.render() self.result+=''' </style> ''' list_story =[] for story in utils._child_get(self.dom, self, 'story'): template = _rml_template(self.dom.findall('template')[0], self.localcontext) f = _flowable(template, self.dom, localcontext = self.localcontext) story_text = f.render(story) list_story.append(story_text) del f if template.data: tag = '''<img src = '%s' width=80 height=72/>'''% template.data else: tag = '' self.result +=''' <script type="text/javascript"> var indexer = 0; var aryTest = %s ; function nextData() { if(indexer < aryTest.length -1) { indexer += 1; document.getElementById("tiny_data").innerHTML=aryTest[indexer]; } } function prevData() { if (indexer > 0) { indexer -= 1; document.getElementById("tiny_data").innerHTML=aryTest[indexer]; } } </script> </head> <body> %s <div id="tiny_data"> %s </div> <br> <input type="button" value="next" onclick="nextData();"> <input type="button" value="prev" onclick="prevData();"> </body></html>'''%(list_story,tag,list_story[0]) out.write( self.result) def parseString(data,localcontext = {}, fout=None): r = _rml_doc(data, localcontext) if fout: fp = file(fout,'wb') r.render(fp) fp.close() return fout else: fp = cStringIO.StringIO() r.render(fp) return fp.getvalue() def rml2html_help(): print 'Usage: rml2html input.rml >output.html' print 'Render the standard input (RML) and output an HTML file' sys.exit(0) if __name__=="__main__": if len(sys.argv)>1: if sys.argv[1]=='--help': rml2html_help() print parseString(file(sys.argv[1], 'r').read()), else: print 'Usage: rml2html input.rml >output.html' print 'Try \'rml2html --help\' for more information.' # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
courtarro/gnuradio
gr-digital/python/digital/qa_constellation_soft_decoder_cf.py
40
7930
#!/usr/bin/env python # # Copyright 2013-2014 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest, digital, blocks from math import sqrt from numpy import random, vectorize class test_constellation_soft_decoder(gr_unittest.TestCase): def setUp(self): self.tb = gr.top_block() def tearDown(self): self.tb = None def helper_with_lut(self, prec, src_data, const_gen, const_sd_gen): cnst_pts, code = const_gen() Es = max([abs(c) for c in cnst_pts]) lut = digital.soft_dec_table_generator(const_sd_gen, prec, Es) expected_result = list() for s in src_data: res = digital.calc_soft_dec_from_table(s, lut, prec, sqrt(2.0)) expected_result += res cnst = digital.constellation_calcdist(cnst_pts, code, 2, 1) cnst.set_soft_dec_lut(lut, int(prec)) src = blocks.vector_source_c(src_data) op = digital.constellation_soft_decoder_cf(cnst.base()) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() actual_result = dst.data() # fetch the contents of the sink #print "actual result", actual_result #print "expected result", expected_result self.assertFloatTuplesAlmostEqual(expected_result, actual_result, 5) def helper_no_lut(self, prec, src_data, const_gen, const_sd_gen): cnst_pts, code = const_gen() cnst = digital.constellation_calcdist(cnst_pts, code, 2, 1) expected_result = list() for s in src_data: res = digital.calc_soft_dec(s, cnst.points(), code) expected_result += res src = blocks.vector_source_c(src_data) op = digital.constellation_soft_decoder_cf(cnst.base()) dst = blocks.vector_sink_f() self.tb.connect(src, op) self.tb.connect(op, dst) self.tb.run() actual_result = dst.data() # fetch the contents of the sink #print "actual result", actual_result #print "expected result", expected_result # Double vs. float precision issues between Python and C++, so # use only 4 decimals in comparisons. self.assertFloatTuplesAlmostEqual(expected_result, actual_result, 4) def test_constellation_soft_decoder_cf_bpsk_3(self): prec = 3 src_data = (-1.0 - 1.0j, 1.0 - 1.0j, -1.0 + 1.0j, 1.0 + 1.0j, -2.0 - 2.0j, 2.0 - 2.0j, -2.0 + 2.0j, 2.0 + 2.0j, -0.2 - 0.2j, 0.2 - 0.2j, -0.2 + 0.2j, 0.2 + 0.2j, 0.3 + 0.4j, 0.1 - 1.2j, -0.8 - 0.1j, -0.4 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 + 1.2j, -1.7 - 0.9j) self.helper_with_lut(prec, src_data, digital.psk_2_0x0, digital.sd_psk_2_0x0) def test_constellation_soft_decoder_cf_bpsk_8(self): prec = 8 src_data = (-1.0 - 1.0j, 1.0 - 1.0j, -1.0 + 1.0j, 1.0 + 1.0j, -2.0 - 2.0j, 2.0 - 2.0j, -2.0 + 2.0j, 2.0 + 2.0j, -0.2 - 0.2j, 0.2 - 0.2j, -0.2 + 0.2j, 0.2 + 0.2j, 0.3 + 0.4j, 0.1 - 1.2j, -0.8 - 0.1j, -0.4 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 + 1.2j, -1.7 - 0.9j) self.helper_with_lut(prec, src_data, digital.psk_2_0x0, digital.sd_psk_2_0x0) def test_constellation_soft_decoder_cf_bpsk_8_rand(self): prec = 8 src_data = vectorize(complex)(2*random.randn(100), 2*random.randn(100)) self.helper_with_lut(prec, src_data, digital.psk_2_0x0, digital.sd_psk_2_0x0) def test_constellation_soft_decoder_cf_bpsk_8_rand2(self): prec = 8 src_data = vectorize(complex)(2*random.randn(100), 2*random.randn(100)) self.helper_no_lut(prec, src_data, digital.psk_2_0x0, digital.sd_psk_2_0x0) def test_constellation_soft_decoder_cf_qpsk_3(self): prec = 3 src_data = (-1.0 - 1.0j, 1.0 - 1.0j, -1.0 + 1.0j, 1.0 + 1.0j, -2.0 - 2.0j, 2.0 - 2.0j, -2.0 + 2.0j, 2.0 + 2.0j, -0.2 - 0.2j, 0.2 - 0.2j, -0.2 + 0.2j, 0.2 + 0.2j, 0.3 + 0.4j, 0.1 - 1.2j, -0.8 - 0.1j, -0.4 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 + 1.2j, -1.7 - 0.9j) self.helper_with_lut(prec, src_data, digital.psk_4_0x0_0_1, digital.sd_psk_4_0x0_0_1) def test_constellation_soft_decoder_cf_qpsk_8(self): prec = 8 src_data = (-1.0 - 1.0j, 1.0 - 1.0j, -1.0 + 1.0j, 1.0 + 1.0j, -2.0 - 2.0j, 2.0 - 2.0j, -2.0 + 2.0j, 2.0 + 2.0j, -0.2 - 0.2j, 0.2 - 0.2j, -0.2 + 0.2j, 0.2 + 0.2j, 0.3 + 0.4j, 0.1 - 1.2j, -0.8 - 0.1j, -0.4 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 + 1.2j, -1.7 - 0.9j) self.helper_with_lut(prec, src_data, digital.psk_4_0x0_0_1, digital.sd_psk_4_0x0_0_1) def test_constellation_soft_decoder_cf_qpsk_8_rand(self): prec = 8 src_data = vectorize(complex)(2*random.randn(100), 2*random.randn(100)) self.helper_with_lut(prec, src_data, digital.psk_4_0x0_0_1, digital.sd_psk_4_0x0_0_1) def test_constellation_soft_decoder_cf_qpsk_8_rand2(self): prec = 8 src_data = vectorize(complex)(2*random.randn(100), 2*random.randn(100)) self.helper_no_lut(prec, src_data, digital.psk_4_0x0_0_1, digital.sd_psk_4_0x0_0_1) def test_constellation_soft_decoder_cf_qam16_3(self): prec = 3 src_data = (-1.0 - 1.0j, 1.0 - 1.0j, -1.0 + 1.0j, 1.0 + 1.0j, -2.0 - 2.0j, 2.0 - 2.0j, -2.0 + 2.0j, 2.0 + 2.0j, -0.2 - 0.2j, 0.2 - 0.2j, -0.2 + 0.2j, 0.2 + 0.2j, 0.3 + 0.4j, 0.1 - 1.2j, -0.8 - 0.1j, -0.4 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 + 1.2j, -1.7 - 0.9j) self.helper_with_lut(prec, src_data, digital.qam_16_0x0_0_1_2_3, digital.sd_qam_16_0x0_0_1_2_3) def test_constellation_soft_decoder_cf_qam16_8(self): prec = 8 src_data = (-1.0 - 1.0j, 1.0 - 1.0j, -1.0 + 1.0j, 1.0 + 1.0j, -2.0 - 2.0j, 2.0 - 2.0j, -2.0 + 2.0j, 2.0 + 2.0j, -0.2 - 0.2j, 0.2 - 0.2j, -0.2 + 0.2j, 0.2 + 0.2j, 0.3 + 0.4j, 0.1 - 1.2j, -0.8 - 0.1j, -0.4 + 0.8j, 0.8 + 1.0j, -0.5 + 0.1j, 0.1 + 1.2j, -1.7 - 0.9j) self.helper_with_lut(prec, src_data, digital.qam_16_0x0_0_1_2_3, digital.sd_qam_16_0x0_0_1_2_3) def test_constellation_soft_decoder_cf_qam16_8_rand(self): prec = 8 src_data = vectorize(complex)(2*random.randn(100), 2*random.randn(100)) self.helper_with_lut(prec, src_data, digital.qam_16_0x0_0_1_2_3, digital.sd_qam_16_0x0_0_1_2_3) def test_constellation_soft_decoder_cf_qam16_8_rand2(self): prec = 8 #src_data = vectorize(complex)(2*random.randn(100), 2*random.randn(100)) src_data = vectorize(complex)(2*random.randn(2), 2*random.randn(2)) self.helper_no_lut(prec, src_data, digital.qam_16_0x0_0_1_2_3, digital.sd_qam_16_0x0_0_1_2_3) if __name__ == '__main__': #gr_unittest.run(test_constellation_soft_decoder, "test_constellation_soft_decoder.xml") gr_unittest.run(test_constellation_soft_decoder)
gpl-3.0
neno1978/pelisalacarta
python/main-classic/channels/lacajita.py
2
10703
# -*- coding: utf-8 -*- # ------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Canal para lacajita # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ # ------------------------------------------------------------ import re import urllib from core import config from core import httptools from core import logger from core import scrapertools from core import servertools from core import tmdb from core.item import Item __modo_grafico__ = config.get_setting("modo_grafico", "lacajita") __perfil__ = config.get_setting("perfil", "lacajita") # Fijar perfil de color perfil = [['0xFFFFE6CC', '0xFFFFCE9C', '0xFF994D00', '0xFFFE2E2E', '0xFF088A08'], ['0xFFA5F6AF', '0xFF5FDA6D', '0xFF11811E', '0xFFFE2E2E', '0xFF088A08'], ['0xFF58D3F7', '0xFF2E9AFE', '0xFF2E64FE', '0xFFFE2E2E', '0xFF088A08']] if __perfil__ - 1 >= 0: color1, color2, color3, color4, color5 = perfil[__perfil__-1] else: color1 = color2 = color3 = color4 = color5 = "" host = "http://lacajita.xyz" def mainlist(item): logger.info() itemlist = [] item.text_color = color1 itemlist.append(item.clone(title="Novedades DVD", action="")) item.text_color = color2 itemlist.append(item.clone(title=" En Español", action="entradas", url=host+"/estrenos-dvd/es/", page=0)) itemlist.append(item.clone(title=" En Latino", action="entradas", url=host+"/estrenos-dvd/la/", page=0)) itemlist.append(item.clone(title=" En VOSE", action="entradas", url=host+"/estrenos-dvd/vos/", page=0)) item.text_color = color1 itemlist.append(item.clone(title="Estrenos", action="")) item.text_color = color2 itemlist.append(item.clone(title=" En Español", action="entradas", url=host+"/estrenos/es/", page=0)) itemlist.append(item.clone(title=" En Latino", action="entradas", url=host+"/estrenos/la/", page=0)) itemlist.append(item.clone(title=" En VOSE", action="entradas", url=host+"/estrenos/vos/", page=0)) item.text_color = color1 itemlist.append(item.clone(title="Más Vistas", action="updated", url=host+"/listado-visto/", page=0)) itemlist.append(item.clone(title="Actualizadas", action="updated", url=host+"/actualizado/", page=0)) item.text_color = color5 itemlist.append(item.clone(title="Por género", action="indices")) itemlist.append(item.clone(title="Buscar...", action="search", text_color=color4)) itemlist.append(item.clone(action="configuracion", title="Configurar canal...", text_color="gold", folder=False)) return itemlist def configuracion(item): from platformcode import platformtools ret = platformtools.show_channel_settings() platformtools.itemlist_refresh() return ret def search(item, texto): logger.info() texto = texto.replace(" ", "+") try: item.url= "%s/search.php?q1=%s" % (host, texto) item.action = "busqueda" item.page = 0 return busqueda(item) # Se captura la excepción, para no interrumpir al buscador global si un canal falla except: import sys for line in sys.exc_info(): logger.error("%s" % line) return [] def entradas(item): logger.info() itemlist = [] data = httptools.downloadpage(item.url).data bloque = scrapertools.find_single_match(data, '<ul class="nav navbar-nav">(.*?)</ul>') patron = "<li.*?href='([^']+)'.*?src='([^']+)'.*?>([^<]+)</p>(.*?)</button>" matches = scrapertools.find_multiple_matches(bloque, patron) matches_ = matches[item.page:item.page+20] for scrapedurl, scrapedthumbnail, scrapedtitle, data_idioma in matches_: idiomas = [] if "es.png" in data_idioma: idiomas.append("ESP") if "la.png" in data_idioma: idiomas.append("LAT") if "vos.png" in data_idioma: idiomas.append("VOSE") titulo = scrapedtitle if idiomas: titulo += " [%s]" % "/".join(idiomas) scrapedurl = host + scrapedurl scrapedthumbnail = scrapedthumbnail.replace("/w342/", "/w500/") filtro_thumb = scrapedthumbnail.replace("https://image.tmdb.org/t/p/w500", "") filtro = {"poster_path": filtro_thumb}.items() itemlist.append(Item(channel=item.channel, action="findvideos", url=scrapedurl, title=titulo, contentTitle=scrapedtitle, infoLabels={'filtro': filtro}, text_color=color2, thumbnail=scrapedthumbnail, contentType="movie", fulltitle=scrapedtitle)) tmdb.set_infoLabels_itemlist(itemlist, __modo_grafico__) if len(matches) > item.page + 20: page = item.page + 20 itemlist.append(item.clone(title=">> Página Siguiente", page=page, text_color=color3)) return itemlist def updated(item): logger.info() itemlist = [] data = httptools.downloadpage(item.url).data bloque = scrapertools.find_single_match(data, '<ul class="nav navbar-nav">(.*?)</ul>') matches = scrapertools.find_multiple_matches(bloque, "<li.*?href='([^']+)'.*?src='([^']+)'.*?>([^<]+)</p>") matches_ = matches[item.page:item.page+20] for scrapedurl, scrapedthumbnail, scrapedtitle in matches_: if scrapedtitle == "Today": continue scrapedurl = host + scrapedurl scrapedthumbnail = scrapedthumbnail.replace("/w342/", "/w500/") filtro_thumb = scrapedthumbnail.replace("https://image.tmdb.org/t/p/w500", "") filtro = {"poster_path": filtro_thumb}.items() itemlist.append(Item(channel=item.channel, action="findvideos", url=scrapedurl, title=scrapedtitle, contentTitle=scrapedtitle, infoLabels={'filtro': filtro}, text_color=color2, thumbnail=scrapedthumbnail, contentType="movie", fulltitle=scrapedtitle)) tmdb.set_infoLabels_itemlist(itemlist, __modo_grafico__) if len(matches) > item.page + 20: page = item.page + 20 itemlist.append(item.clone(title=">> Página Siguiente", page=page, text_color=color3)) else: next = scrapertools.find_single_match(data, '<a href="([^"]+)">>>') if next: next = item.url + next itemlist.append(item.clone(title=">> Página Siguiente", page=0, url=next, text_color=color3)) return itemlist def busqueda(item): logger.info() itemlist = [] data = httptools.downloadpage(item.url).data bloque = scrapertools.find_single_match(data, '<ul class="nav navbar-nav">(.*?)</ul>') matches = scrapertools.find_multiple_matches(bloque, "<li.*?href='([^']+)'.*?src='([^']+)'.*?>\s*([^<]+)</a>") matches_ = matches[item.page:item.page+25] for scrapedurl, scrapedthumbnail, scrapedtitle in matches_: scrapedurl = host + scrapedurl scrapedthumbnail = scrapedthumbnail.replace("/w342/", "/w500/") if re.search(r"\(\d{4}\)", scrapedtitle): title = scrapedtitle.rsplit("(", 1)[0] year = scrapertools.find_single_match(scrapedtitle, '\((\d{4})\)') infoLabels = {'year': year} else: title = scrapedtitle filtro_thumb = scrapedthumbnail.replace("https://image.tmdb.org/t/p/w500", "") filtro = {"poster_path": filtro_thumb}.items() infoLabels = {'filtro': filtro} itemlist.append(Item(channel=item.channel, action="findvideos", url=scrapedurl, title=scrapedtitle, contentTitle=title, infoLabels=infoLabels, text_color=color2, thumbnail=scrapedthumbnail, contentType="movie", fulltitle=title)) tmdb.set_infoLabels_itemlist(itemlist, __modo_grafico__) if len(matches) > item.page + 25: page = item.page + 25 itemlist.append(item.clone(title=">> Página Siguiente", page=page, text_color=color3)) else: next = scrapertools.find_single_match(data, '<a href="([^"]+)">>>') if next: next = item.url + next itemlist.append(item.clone(title=">> Página Siguiente", page=0, url=next, text_color=color3)) return itemlist def indices(item): logger.info() itemlist = [] data = httptools.downloadpage(host).data matches = scrapertools.find_multiple_matches(data, '<li><a href="([^"]+)"><i class="fa fa-bookmark-o"></i>\s*(.*?)</a>') for scrapedurl, scrapedtitle in matches: scrapedurl = host + scrapedurl itemlist.append(item.clone(action="updated", url=scrapedurl, title=scrapedtitle, page=0)) return itemlist def findvideos(item): logger.info() itemlist = [] data = httptools.downloadpage(item.url).data patron = '<div class="grid_content2 sno">.*?src="([^"]+)".*?href="([^"]+)".*?src=\'(.*?)(?:.png|.jpg)\'' \ '.*?<span>.*?<span>(.*?)</span>.*?<span>(.*?)</span>' matches = scrapertools.find_multiple_matches(data, patron) for idioma, url, servidor, calidad, detalle in matches: url = host + url servidor = servidor.rsplit("/", 1)[1] servidor = servidor.replace("uploaded", "uploadedto").replace("streamin.to", "streaminto") if "streamix" in servidor: servidor = "streamixcloud" try: servers_module = __import__("servers." + servidor) mostrar_server = servertools.is_server_enabled(servidor) if not mostrar_server: continue except: continue if "es.png" in idioma: idioma = "ESP" elif "la.png" in idioma: idioma = "LAT" elif "vos.png" in idioma: idioma = "VOSE" title = "%s - %s - %s" % (servidor, idioma, calidad) if detalle: title += " (%s)" % detalle itemlist.append(item.clone(action="play", url=url, title=title, server=servidor, text_color=color3)) if item.extra != "findvideos" and config.get_library_support(): itemlist.append(item.clone(title="Añadir película a la biblioteca", action="add_pelicula_to_library", extra="findvideos", text_color="green")) return itemlist def play(item): logger.info() itemlist = [] data = httptools.downloadpage(item.url).data url = scrapertools.find_single_match(data, 'window.open\("([^"]+)"') enlaces = servertools.findvideosbyserver(url, item.server) if enlaces: itemlist.append(item.clone(action="play", url=enlaces[0][1])) else: enlaces = servertools.findvideos(url, True) if enlaces: itemlist.append(item.clone(action="play", server=enlaces[0][2], url=enlaces[0][1])) return itemlist
gpl-3.0
adamgreenhall/scikit-learn
doc/tutorial/machine_learning_map/svg2imagemap.py
360
3411
#!/usr/local/bin/python """ This script converts a subset of SVG into an HTML imagemap Note *subset*. It only handles <path> elements, for which it only pays attention to the M and L commands. Futher, it only notices the "translate" transform. It was written to generate the examples in the documentation for maphilight, and thus is very squarely aimed at handling several SVG maps from wikipedia. It *assumes* that all the <path>s it will need are inside a <g>. Any <path> outside of a <g> will be ignored. It takes several possible arguments, in the form: $ svn2imagemap.py FILENAME [x y [group1 group2 ... groupN]] FILENAME must be the name of an SVG file. All other arguments are optional. x and y, if present, are the dimensions of the image you'll be creating from the SVG. If not present, it assumes the values of the width and height attributes in the SVG file. group1 through groupN are group ids. If only want particular groups used, enter their ids here and all others will be ignored. """ import os import re import sys import xml.dom.minidom import parse_path if len(sys.argv) == 1: sys.exit("svn2imagemap.py FILENAME [x y [group1 group2 ... groupN]]") if not os.path.exists(sys.argv[1]): sys.exit("Input file does not exist") x, y, groups = None, None, None if len(sys.argv) >= 3: x = float(sys.argv[2]) y = float(sys.argv[3]) if len(sys.argv) > 3: groups = sys.argv[4:] svg_file = xml.dom.minidom.parse(sys.argv[1]) svg = svg_file.getElementsByTagName('svg')[0] raw_width = float(svg.getAttribute('width')) raw_height = float(svg.getAttribute('height')) width_ratio = x and (x / raw_width) or 1 height_ratio = y and (y / raw_height) or 1 if groups: elements = [g for g in svg.getElementsByTagName('g') if (g.hasAttribute('id') and g.getAttribute('id') in groups)] elements.extend([p for p in svg.getElementsByTagName('path') if (p.hasAttribute('id') and p.getAttribute('id') in groups)]) else: elements = svg.getElementsByTagName('g') parsed_groups = {} for e in elements: paths = [] if e.nodeName == 'g': for path in e.getElementsByTagName('path'): points = parse_path.get_points(path.getAttribute('d')) for pointset in points: paths.append([path.getAttribute('id'), pointset]) else: points = parse_path.get_points(e.getAttribute('d')) for pointset in points: paths.append([e.getAttribute('id'), pointset]) if e.hasAttribute('transform'): print e.getAttribute('id'), e.getAttribute('transform') for transform in re.findall(r'(\w+)\((-?\d+.?\d*),(-?\d+.?\d*)\)', e.getAttribute('transform')): if transform[0] == 'translate': x_shift = float(transform[1]) y_shift = float(transform[2]) for path in paths: path[1] = [(p[0] + x_shift, p[1] + y_shift) for p in path[1]] parsed_groups[e.getAttribute('id')] = paths out = [] for g in parsed_groups: for path in parsed_groups[g]: out.append('<area href="#" title="%s" shape="poly" coords="%s"></area>' % (path[0], ', '.join([("%d,%d" % (p[0]*width_ratio, p[1]*height_ratio)) for p in path[1]]))) outfile = open(sys.argv[1].replace('.svg', '.html'), 'w') outfile.write('\n'.join(out))
bsd-3-clause
jiajie999/zerorpc-python
zerorpc/core.py
18
15042
# -*- coding: utf-8 -*- # Open Source Initiative OSI - The MIT License (MIT):Licensing # # The MIT License (MIT) # Copyright (c) 2015 François-Xavier Bourlet (bombela+zerorpc@gmail.com) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is furnished to do # so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import sys import traceback import gevent.pool import gevent.queue import gevent.event import gevent.local import gevent.lock import gevent_zmq as zmq from .exceptions import TimeoutExpired, RemoteError, LostRemote from .channel import ChannelMultiplexer, BufferedChannel from .socket import SocketBase from .heartbeat import HeartBeatOnChannel from .context import Context from .decorators import DecoratorBase, rep import patterns from logging import getLogger logger = getLogger(__name__) class ServerBase(object): def __init__(self, channel, methods=None, name=None, context=None, pool_size=None, heartbeat=5): self._multiplexer = ChannelMultiplexer(channel) if methods is None: methods = self self._context = context or Context.get_instance() self._name = name or self._extract_name() self._task_pool = gevent.pool.Pool(size=pool_size) self._acceptor_task = None self._methods = self._filter_methods(ServerBase, self, methods) self._inject_builtins() self._heartbeat_freq = heartbeat for (k, functor) in self._methods.items(): if not isinstance(functor, DecoratorBase): self._methods[k] = rep(functor) @staticmethod def _filter_methods(cls, self, methods): if isinstance(methods, dict): return methods server_methods = set(k for k in dir(cls) if not k.startswith('_')) return dict((k, getattr(methods, k)) for k in dir(methods) if callable(getattr(methods, k)) and not k.startswith('_') and k not in server_methods ) @staticmethod def _extract_name(methods): return getattr(methods, '__name__', None) \ or getattr(type(methods), '__name__', None) \ or repr(methods) def close(self): self.stop() self._multiplexer.close() def _format_args_spec(self, args_spec, r=None): if args_spec: r = [dict(name=name) for name in args_spec[0]] default_values = args_spec[3] if default_values is not None: for arg, def_val in zip(reversed(r), reversed(default_values)): arg['default'] = def_val return r def _zerorpc_inspect(self): methods = dict((m, f) for m, f in self._methods.items() if not m.startswith('_')) detailled_methods = dict((m, dict(args=self._format_args_spec(f._zerorpc_args()), doc=f._zerorpc_doc())) for (m, f) in methods.items()) return {'name': self._name, 'methods': detailled_methods} def _inject_builtins(self): self._methods['_zerorpc_list'] = lambda: [m for m in self._methods if not m.startswith('_')] self._methods['_zerorpc_name'] = lambda: self._name self._methods['_zerorpc_ping'] = lambda: ['pong', self._name] self._methods['_zerorpc_help'] = lambda m: \ self._methods[m]._zerorpc_doc() self._methods['_zerorpc_args'] = \ lambda m: self._methods[m]._zerorpc_args() self._methods['_zerorpc_inspect'] = self._zerorpc_inspect def __call__(self, method, *args): if method not in self._methods: raise NameError(method) return self._methods[method](*args) def _print_traceback(self, protocol_v1, exc_infos): logger.exception('') exc_type, exc_value, exc_traceback = exc_infos if protocol_v1: return (repr(exc_value),) human_traceback = traceback.format_exc() name = exc_type.__name__ human_msg = str(exc_value) return (name, human_msg, human_traceback) def _async_task(self, initial_event): protocol_v1 = initial_event.header.get('v', 1) < 2 channel = self._multiplexer.channel(initial_event) hbchan = HeartBeatOnChannel(channel, freq=self._heartbeat_freq, passive=protocol_v1) bufchan = BufferedChannel(hbchan) exc_infos = None event = bufchan.recv() try: self._context.hook_load_task_context(event.header) functor = self._methods.get(event.name, None) if functor is None: raise NameError(event.name) functor.pattern.process_call(self._context, bufchan, event, functor) except LostRemote: exc_infos = list(sys.exc_info()) self._print_traceback(protocol_v1, exc_infos) except Exception: exc_infos = list(sys.exc_info()) human_exc_infos = self._print_traceback(protocol_v1, exc_infos) reply_event = bufchan.new_event('ERR', human_exc_infos, self._context.hook_get_task_context()) self._context.hook_server_inspect_exception(event, reply_event, exc_infos) bufchan.emit_event(reply_event) finally: del exc_infos bufchan.close() def _acceptor(self): while True: initial_event = self._multiplexer.recv() self._task_pool.spawn(self._async_task, initial_event) def run(self): self._acceptor_task = gevent.spawn(self._acceptor) try: self._acceptor_task.get() finally: self.stop() self._task_pool.join(raise_error=True) def stop(self): if self._acceptor_task is not None: self._acceptor_task.kill() self._acceptor_task = None class ClientBase(object): def __init__(self, channel, context=None, timeout=30, heartbeat=5, passive_heartbeat=False): self._multiplexer = ChannelMultiplexer(channel, ignore_broadcast=True) self._context = context or Context.get_instance() self._timeout = timeout self._heartbeat_freq = heartbeat self._passive_heartbeat = passive_heartbeat def close(self): self._multiplexer.close() def _handle_remote_error(self, event): exception = self._context.hook_client_handle_remote_error(event) if not exception: if event.header.get('v', 1) >= 2: (name, msg, traceback) = event.args exception = RemoteError(name, msg, traceback) else: (msg,) = event.args exception = RemoteError('RemoteError', msg, None) return exception def _select_pattern(self, event): for pattern in self._context.hook_client_patterns_list( patterns.patterns_list): if pattern.accept_answer(event): return pattern return None def _process_response(self, request_event, bufchan, timeout): def raise_error(ex): bufchan.close() self._context.hook_client_after_request(request_event, None, ex) raise ex try: reply_event = bufchan.recv(timeout=timeout) except TimeoutExpired: raise_error(TimeoutExpired(timeout, 'calling remote method {0}'.format(request_event.name))) pattern = self._select_pattern(reply_event) if pattern is None: raise_error(RuntimeError( 'Unable to find a pattern for: {0}'.format(request_event))) return pattern.process_answer(self._context, bufchan, request_event, reply_event, self._handle_remote_error) def __call__(self, method, *args, **kargs): timeout = kargs.get('timeout', self._timeout) channel = self._multiplexer.channel() hbchan = HeartBeatOnChannel(channel, freq=self._heartbeat_freq, passive=self._passive_heartbeat) bufchan = BufferedChannel(hbchan, inqueue_size=kargs.get('slots', 100)) xheader = self._context.hook_get_task_context() request_event = bufchan.new_event(method, args, xheader) self._context.hook_client_before_request(request_event) bufchan.emit_event(request_event) if kargs.get('async', False) is False: return self._process_response(request_event, bufchan, timeout) async_result = gevent.event.AsyncResult() gevent.spawn(self._process_response, request_event, bufchan, timeout).link(async_result) return async_result def __getattr__(self, method): return lambda *args, **kargs: self(method, *args, **kargs) class Server(SocketBase, ServerBase): def __init__(self, methods=None, name=None, context=None, pool_size=None, heartbeat=5): SocketBase.__init__(self, zmq.ROUTER, context) if methods is None: methods = self name = name or ServerBase._extract_name(methods) methods = ServerBase._filter_methods(Server, self, methods) ServerBase.__init__(self, self._events, methods, name, context, pool_size, heartbeat) def close(self): ServerBase.close(self) SocketBase.close(self) class Client(SocketBase, ClientBase): def __init__(self, connect_to=None, context=None, timeout=30, heartbeat=5, passive_heartbeat=False): SocketBase.__init__(self, zmq.DEALER, context=context) ClientBase.__init__(self, self._events, context, timeout, heartbeat, passive_heartbeat) if connect_to: self.connect(connect_to) def close(self): ClientBase.close(self) SocketBase.close(self) class Pusher(SocketBase): def __init__(self, context=None, zmq_socket=zmq.PUSH): super(Pusher, self).__init__(zmq_socket, context=context) def __call__(self, method, *args): self._events.emit(method, args, self._context.hook_get_task_context()) def __getattr__(self, method): return lambda *args: self(method, *args) class Puller(SocketBase): def __init__(self, methods=None, context=None, zmq_socket=zmq.PULL): super(Puller, self).__init__(zmq_socket, context=context) if methods is None: methods = self self._methods = ServerBase._filter_methods(Puller, self, methods) self._receiver_task = None def close(self): self.stop() super(Puller, self).close() def __call__(self, method, *args): if method not in self._methods: raise NameError(method) return self._methods[method](*args) def _receiver(self): while True: event = self._events.recv() try: if event.name not in self._methods: raise NameError(event.name) self._context.hook_load_task_context(event.header) self._context.hook_server_before_exec(event) self._methods[event.name](*event.args) # In Push/Pull their is no reply to send, hence None for the # reply_event argument self._context.hook_server_after_exec(event, None) except Exception: exc_infos = sys.exc_info() try: logger.exception('') self._context.hook_server_inspect_exception(event, None, exc_infos) finally: del exc_infos def run(self): self._receiver_task = gevent.spawn(self._receiver) try: self._receiver_task.get() finally: self._receiver_task = None def stop(self): if self._receiver_task is not None: self._receiver_task.kill(block=False) class Publisher(Pusher): def __init__(self, context=None): super(Publisher, self).__init__(context=context, zmq_socket=zmq.PUB) class Subscriber(Puller): def __init__(self, methods=None, context=None): super(Subscriber, self).__init__(methods=methods, context=context, zmq_socket=zmq.SUB) self._events.setsockopt(zmq.SUBSCRIBE, '') def fork_task_context(functor, context=None): '''Wrap a functor to transfer context. Usage example: gevent.spawn(zerorpc.fork_task_context(myfunction), args...) The goal is to permit context "inheritance" from a task to another. Consider the following example: zerorpc.Server receive a new event - task1 is created to handle this event this task will be linked to the initial event context. zerorpc.Server does that for you. - task1 make use of some zerorpc.Client instances, the initial event context is transfered on every call. - task1 spawn a new task2. - task2 make use of some zerorpc.Client instances, it's a fresh context. Thus there is no link to the initial context that spawned task1. - task1 spawn a new fork_task_context(task3). - task3 make use of some zerorpc.Client instances, the initial event context is transfered on every call. A real use case is a distributed tracer. Each time a new event is created, a trace_id is injected in it or copied from the current task context. This permit passing the trace_id from a zerorpc.Server to another via zerorpc.Client. The simple rule to know if a task need to be wrapped is: - if the new task will make any zerorpc call, it should be wrapped. ''' context = context or Context.get_instance() xheader = context.hook_get_task_context() def wrapped(*args, **kargs): context.hook_load_task_context(xheader) return functor(*args, **kargs) return wrapped
mit
terrorobe/barman
barman/fs.py
2
10057
# Copyright (C) 2013-2015 2ndQuadrant Italia (Devise.IT S.r.L.) # # This file is part of Barman. # # Barman 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. # # Barman 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 Barman. If not, see <http://www.gnu.org/licenses/>. import logging from barman.command_wrappers import Command _logger = logging.getLogger(__name__) class FsOperationFailed(Exception): """ Exception which represents a failed execution of a command on FS """ pass def _str(cmd_out): """ Make a string from the output of a CommandWrapper execution. If input is None returns a literal 'None' string :param cmd_out: String or ByteString to convert :return str: a string """ if hasattr(cmd_out, 'decode') and callable(cmd_out.decode): return cmd_out.decode('utf-8', 'replace') else: return str(cmd_out) class UnixLocalCommand(object): """ This class is a wrapper for local calls for file system operations """ def __init__(self): # initialize a shell self.cmd = Command(cmd='sh -c', shell=True) def create_dir_if_not_exists(self, dir_path): """ This method check for the existence of a directory. if exist and is not a directory throws exception. if is a directory everything is ok and no mkdir operation is required. Otherwise creates the directory using mkdir if the mkdir fails an error is raised :param dir_path full path for the directory """ _logger.debug('Create directory %s if it does not exists' % dir_path) exists = self.cmd('test -e %s' % dir_path) if exists == 0: is_dir = self.cmd('test -d %s' % dir_path) if is_dir != 0: raise FsOperationFailed( 'A file with the same name already exists') else: return False else: mkdir_ret = self.cmd('mkdir %s' % dir_path) if mkdir_ret == 0: return True else: raise FsOperationFailed('mkdir execution failed') def delete_if_exists(self, dir_path): """ This method check for the existence of a directory. if exists and is not a directory an exception is raised if is a directory, then is removed using a rm -fr command, and returns True. if the command fails an exception is raised. If the directory does not exists returns False :param dir_path the full path for the directory """ _logger.debug('Delete if directory %s exists' % dir_path) exists = self.cmd('test -e %s' % dir_path) if exists == 0: is_dir = self.cmd('test -d %s' % dir_path) if is_dir != 0: raise FsOperationFailed( 'A file with the same name exists, but is not a ' 'directory') else: rm_ret = self.cmd('rm -fr %s' % dir_path) if rm_ret == 0: return True else: raise FsOperationFailed('rm execution failed') else: return False def check_directory_exists(self, dir_path): """ Check for the existence of a directory in path. if the directory exists returns true. if the directory does not exists returns false. if exists a file and is not a directory raises an exception :param dir_path full path for the directory """ _logger.debug('Check if directory %s exists' % dir_path) exists = self.cmd('test -e %s' % dir_path) if exists == 0: is_dir = self.cmd('test -d %s' % dir_path) if is_dir != 0: raise FsOperationFailed( 'A file with the same name exists, but is not a directory') else: return True else: return False def check_write_permission(self, dir_path): """ check write permission for barman on a given path. Creates a hidden file using touch, then remove the file. returns true if the file is written and removed without problems raise exception if the creation fails. raise exception if the removal fails. :param dir_path full dir_path for the directory to check """ _logger.debug('Check if directory %s is writable' % dir_path) exists = self.cmd('test -e %s' % dir_path) if exists == 0: is_dir = self.cmd('test -d %s' % dir_path) if is_dir == 0: can_write = self.cmd('touch %s/.barman_write_check' % dir_path) if can_write == 0: can_remove = self.cmd( 'rm %s/.barman_write_check' % dir_path) if can_remove == 0: return True else: raise FsOperationFailed('Unable to remove file') else: raise FsOperationFailed('Unable to create write check file') else: raise FsOperationFailed('%s is not a directory' % dir_path) else: raise FsOperationFailed('%s does not exists' % dir_path) def create_symbolic_link(self, src, dst): """ Create a symlink pointing to src named dst. Check src exists, if so, checks that destination does not exists. if src is an invalid folder, raises an exception. if dst already exists, raises an exception. if ln -s command fails raises an exception :param src full path to the source of the symlink :param dst full path for the destination of the symlink """ _logger.debug('Create symbolic link %s -> %s' % (src, dst)) exists = self.cmd('test -e %s' % src) if exists == 0: exists_dst = self.cmd('test -e %s' % dst) if exists_dst != 0: link = self.cmd('ln -s %s %s' % (src, dst)) if link == 0: return True else: raise FsOperationFailed('ln command failed') else: raise FsOperationFailed('ln destination already exists') else: raise FsOperationFailed('ln source does not exists') def get_system_info(self): """ Gather important system information for 'barman diagnose' command """ result = {} # self.cmd.out can be None. The str() call will ensure it will be # translated to a literal 'None' release = '' if self.cmd("lsb_release -a") == 0: release = _str(self.cmd.out).rstrip() elif self.cmd('test -e /etc/lsb-release') == 0: self.cmd('cat /etc/lsb-release ') release = "Ubuntu Linux %s" % _str(self.cmd.out).rstrip() elif self.cmd('test -e /etc/debian_version') == 0: self.cmd('cat /etc/debian_version') release = "Debian GNU/Linux %s" % _str(self.cmd.out).rstrip() elif self.cmd('test -e /etc/redhat-release') == 0: self.cmd('cat /etc/redhat-release') release = "RedHat Linux %s" % _str(self.cmd.out).rstrip() elif self.cmd('sw_vers') == 0: release = _str(self.cmd.out).rstrip() result['release'] = release self.cmd('uname -a') result['kernel_ver'] = _str(self.cmd.out).rstrip() self.cmd('python --version 2>&1') result['python_ver'] = _str(self.cmd.out).rstrip() self.cmd('rsync --version 2>&1') result['rsync_ver'] = _str(self.cmd.out).splitlines(True)[0].rstrip() self.cmd('ssh -V 2>&1') result['ssh_ver'] = _str(self.cmd.out).rstrip() return result def get_file_content(self, path): """ Retrieve the content of a file If the file doesn't exist or isn't readable, it raises an exception. :param str path: full path to the file to read """ _logger.debug('Reading content of file %s' % path) result = self.cmd("test -e '%s'" % path) if result != 0: raise FsOperationFailed('The %s file does not exist' % path) result = self.cmd("test -r '%s'" % path) if result != 0: raise FsOperationFailed('The %s file is not readable' % path) result = self.cmd("cat '%s'" % path) if result != 0: raise FsOperationFailed('Failed to execute "cat \'%s\'"' % path) return self.cmd.out class UnixRemoteCommand(UnixLocalCommand): """ This class is a wrapper for remote calls for file system operations """ # noinspection PyMissingConstructor def __init__(self, ssh_command): """ Uses the same commands as the UnixLocalCommand but the constructor is overridden and a remote shell is initialized using the ssh_command provided by the user :param ssh_command the ssh command provided by the user """ if ssh_command is None: raise FsOperationFailed('No ssh command provided') self.cmd = Command(cmd=ssh_command, shell=True) ret = self.cmd("true") if ret != 0: raise FsOperationFailed("Connection failed using the command '%s'" % ssh_command)
gpl-3.0
kjbracey-arm/mbed
TESTS/host_tests/pyusb_basic.py
6
69827
""" mbed SDK Copyright (c) 2018-2019 ARM Limited SPDX-License-Identifier: Apache-2.0 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import print_function from mbed_host_tests import BaseHostTest from argparse import ArgumentParser import time import sys import inspect from threading import Thread, Event, Timer import array import random import os import traceback import usb.core from usb.util import build_request_type from usb.util import CTRL_OUT, CTRL_IN from usb.util import CTRL_TYPE_STANDARD, CTRL_TYPE_CLASS, CTRL_TYPE_VENDOR from usb.util import (CTRL_RECIPIENT_DEVICE, CTRL_RECIPIENT_INTERFACE, CTRL_RECIPIENT_ENDPOINT, CTRL_RECIPIENT_OTHER) from usb.util import (DESC_TYPE_DEVICE, DESC_TYPE_CONFIG, DESC_TYPE_STRING, DESC_TYPE_INTERFACE, DESC_TYPE_ENDPOINT) import struct if sys.platform.startswith('win'): # Use libusb0 on Windows. libusb1 implementation for Windows # does not support all features necessary for testing. import usb.backend.libusb0 USB_BACKEND = usb.backend.libusb0.get_backend() else: # Use a default backend on other platforms. USB_BACKEND = None def get_interface(dev, interface, alternate=0): intf = None for active_if in dev.get_active_configuration(): if active_if.bInterfaceNumber == interface and active_if.bAlternateSetting == alternate: assert intf is None, "duplicate interface" intf = active_if return intf VENDOR_TEST_CTRL_IN = 1 VENDOR_TEST_CTRL_OUT = 2 VENDOR_TEST_CTRL_NONE = 3 VENDOR_TEST_CTRL_IN_DELAY = 4 VENDOR_TEST_CTRL_OUT_DELAY = 5 VENDOR_TEST_CTRL_NONE_DELAY = 6 VENDOR_TEST_CTRL_IN_STATUS_DELAY = 7 VENDOR_TEST_CTRL_OUT_STATUS_DELAY = 8 VENDOR_TEST_CTRL_IN_SIZES = 9 VENDOR_TEST_CTRL_OUT_SIZES = 10 VENDOR_TEST_RW_RESTART = 11 VENDOR_TEST_ABORT_BUFF_CHECK = 12 VENDOR_TEST_UNSUPPORTED_REQUEST = 32 REQUEST_GET_STATUS = 0 REQUEST_CLEAR_FEATURE = 1 REQUEST_SET_FEATURE = 3 REQUEST_SET_ADDRESS = 5 REQUEST_GET_DESCRIPTOR = 6 REQUEST_SET_DESCRIPTOR = 7 REQUEST_GET_CONFIGURATION = 8 REQUEST_SET_CONFIGURATION = 9 REQUEST_GET_INTERFACE = 10 REQUEST_SET_INTERFACE = 11 REQUEST_SYNCH_FRAME = 12 FEATURE_ENDPOINT_HALT = 0 FEATURE_DEVICE_REMOTE_WAKEUP = 1 DEVICE_QUALIFIER_DESC_SIZE = 10 DESC_TYPE_DEVICE_QUALIFIER = 0x06 DEVICE_DESC_SIZE = 18 device_descriptor_parser = struct.Struct('BBHBBBBHHHBBBB') device_descriptor_keys = ['bLength', 'bDescriptorType', 'bcdUSB', 'bDeviceClass', 'bDeviceSubClass', 'bDeviceProtocol', 'bMaxPacketSize0', 'idVendor', 'idProduct', 'bcdDevice', 'iManufacturer', 'iProduct', 'iSerialNumber', 'bNumConfigurations'] CONFIGURATION_DESC_SIZE = 9 configuration_descriptor_parser = struct.Struct('BBHBBBBB') configuration_descriptor_keys = ['bLength', 'bDescriptorType', 'wTotalLength', 'bNumInterfaces', 'bConfigurationValue', 'iConfiguration', 'bmAttributes', 'bMaxPower'] INTERFACE_DESC_SIZE = 9 interface_descriptor_parser = struct.Struct('BBBBBBBBB') interface_descriptor_keys = ['bLength', 'bDescriptorType', 'bInterfaceNumber', 'bAlternateSetting', 'bNumEndpoints', 'bInterfaceClass', 'bInterfaceSubClass', 'bInterfaceProtocol', 'iInterface'] ENDPOINT_DESC_SIZE = 7 interface_descriptor_parser = struct.Struct('BBBBBHB') interface_descriptor_keys = ['bLength', 'bDescriptorType', 'bEndpointAddress', 'bmAttributes', 'wMaxPacketSize', 'bInterval'] ENDPOINT_TYPE_NAMES = { usb.ENDPOINT_TYPE_BULK: 'BULK', usb.ENDPOINT_TYPE_CONTROL: 'CONTROL', usb.ENDPOINT_TYPE_INTERRUPT: 'INTERRUPT', usb.ENDPOINT_TYPE_ISOCHRONOUS: 'ISOCHRONOUS'} # Greentea message keys used to notify DUT of test status MSG_KEY_TEST_CASE_FAILED = 'fail' MSG_KEY_TEST_CASE_PASSED = 'pass' MSG_VALUE_DUMMY = '0' def format_local_error_msg(fmt): """Return an error message formatted with the last traceback entry from this file. The message is formatted according to fmt with data from the last traceback enrty internal to this file. There are 4 arguments supplied to the format function: filename, line_number, exc_type and exc_value. Returns None if formatting fails. """ try: exc_type, exc_value, exc_traceback = sys.exc_info() # A list of 4-tuples (filename, line_number, function_name, text). tb_entries = traceback.extract_tb(exc_traceback) # Reuse the filename from the first tuple instead of relying on __file__: # 1. No need for path handling. # 2. No need for file extension handling (i.e. .py vs .pyc). name_of_this_file = tb_entries[0][0] last_internal_tb_entry = [tb for tb in tb_entries if tb[0] == name_of_this_file][-1] msg = fmt.format( filename=last_internal_tb_entry[0], line_number=last_internal_tb_entry[1], exc_type=str(exc_type).strip(), exc_value=str(exc_value).strip(), ) except (IndexError, KeyError): msg = None return msg class PyusbBasicTest(BaseHostTest): def test_usb_device(self, usb_dev_serial_number, test_fun, **test_fun_kwargs): """Find a USB device and execute a testing function. Search is based on usb_dev_serial_number. If the device is found, the test_fun is executed with its dev argument set to the device found and all other kwargs set as specified by test_fun_kwargs. The DUT is notified with either success, failure or error status. """ usb_device = self.find_device(usb_dev_serial_number) if usb_device is None: self.notify_error('USB device (SN={}) not found.'.format(usb_dev_serial_number)) return try: test_fun(usb_device, **test_fun_kwargs) self.notify_success() except RuntimeError as exc: self.notify_failure(exc) except usb.core.USBError as exc: error_msg = format_local_error_msg('[{filename}]:{line_number}, Dev-host transfer error ({exc_value}).') self.notify_failure(error_msg if error_msg is not None else exc) def _callback_control_basic_test(self, key, value, timestamp): serial_number, vendor_id, product_id = value.split(' ') self.test_usb_device( usb_dev_serial_number=serial_number, test_fun=control_basic_test, log=print, vendor_id=int(vendor_id), product_id=int(product_id) ) def _callback_control_stall_test(self, key, value, timestamp): self.test_usb_device( usb_dev_serial_number=value, test_fun=control_stall_test, log=print ) def _callback_control_sizes_test(self, key, value, timestamp): self.test_usb_device( usb_dev_serial_number=value, test_fun=control_sizes_test, log=print ) def _callback_control_stress_test(self, key, value, timestamp): self.test_usb_device( usb_dev_serial_number=value, test_fun=control_stress_test, log=print ) def _callback_device_reset_test(self, key, value, timestamp): self.test_usb_device( usb_dev_serial_number=value, # Advance the coroutine to the next yield statement # and send the usb_device to use. test_fun=self.device_reset_test.send ) def _callback_device_soft_reconnection_test(self, key, value, timestamp): self.test_usb_device( usb_dev_serial_number=value, # Advance the coroutine to the next yield statement # and send the usb_device to use. test_fun=self.device_soft_reconnection_test.send ) def _callback_device_suspend_resume_test(self, key, value, timestamp): self.test_usb_device( usb_dev_serial_number=value, # Advance the coroutine to the next yield statement # and send the usb_device to use. test_fun=self.device_suspend_resume_test.send ) def _callback_repeated_construction_destruction_test(self, key, value, timestamp): self.test_usb_device( usb_dev_serial_number=value, # Advance the coroutine to the next yield statement # and send the usb_device to use. test_fun=self.repeated_construction_destruction_test.send ) def _callback_ep_test_data_correctness(self, key, value, timestamp): self.test_usb_device( usb_dev_serial_number=value, test_fun=ep_test_data_correctness, log=print ) def _callback_ep_test_halt(self, key, value, timestamp): self.test_usb_device( usb_dev_serial_number=value, test_fun=ep_test_halt, log=print ) def _callback_ep_test_parallel_transfers(self, key, value, timestamp): self.test_usb_device( usb_dev_serial_number=value, test_fun=ep_test_parallel_transfers, log=print ) def _callback_ep_test_parallel_transfers_ctrl(self, key, value, timestamp): self.test_usb_device( usb_dev_serial_number=value, test_fun=ep_test_parallel_transfers_ctrl, log=print ) def _callback_ep_test_abort(self, key, value, timestamp): self.test_usb_device( usb_dev_serial_number=value, test_fun=ep_test_abort, log=print ) def _callback_ep_test_data_toggle(self, key, value, timestamp): self.test_usb_device( usb_dev_serial_number=value, test_fun=ep_test_data_toggle, log=print ) def _callback_reset_support(self, key, value, timestamp): status = "false" if sys.platform == "darwin" else "true" self.log("Reset supported: %s" % status) self.send_kv("placeholder", status) def find_device(self, serial_number): # to make it more reliable, 20 retries in 2[s] for _ in range(20): dev = usb.core.find(custom_match=TestMatch(serial_number), backend=USB_BACKEND) if dev is not None: break time.sleep(0.1) return dev def notify_success(self, value=None, msg=''): """Report a host side test success to the DUT.""" if msg: self.log('TEST PASSED: {}'.format(msg)) if value is None: value = MSG_VALUE_DUMMY self.send_kv(MSG_KEY_TEST_CASE_PASSED, value) def notify_failure(self, msg): """Report a host side test failure to the DUT.""" self.log('TEST FAILED: {}'.format(msg)) self.send_kv(MSG_KEY_TEST_CASE_FAILED, MSG_VALUE_DUMMY) def notify_error(self, msg): """Terminate the test with an error msg.""" self.log('TEST ERROR: {}'.format(msg)) self.notify_complete(None) def setup(self): self.__result = False self.device_reset_test = device_reset_test(log=print) self.device_reset_test.send(None) self.device_soft_reconnection_test = device_soft_reconnection_test(log=print) self.device_soft_reconnection_test.send(None) self.device_suspend_resume_test = device_suspend_resume_test(log=print) self.device_suspend_resume_test.send(None) self.repeated_construction_destruction_test = repeated_construction_destruction_test(log=print) self.repeated_construction_destruction_test.send(None) self.register_callback('control_basic_test', self._callback_control_basic_test) self.register_callback('control_stall_test', self._callback_control_stall_test) self.register_callback('control_sizes_test', self._callback_control_sizes_test) self.register_callback('control_stress_test', self._callback_control_stress_test) self.register_callback('device_reset_test', self._callback_device_reset_test) self.register_callback('device_soft_reconnection_test', self._callback_device_soft_reconnection_test) self.register_callback('device_suspend_resume_test', self._callback_device_suspend_resume_test) self.register_callback('repeated_construction_destruction_test', self._callback_repeated_construction_destruction_test) self.register_callback('ep_test_data_correctness', self._callback_ep_test_data_correctness) self.register_callback('ep_test_halt', self._callback_ep_test_halt) self.register_callback('ep_test_parallel_transfers', self._callback_ep_test_parallel_transfers) self.register_callback('ep_test_parallel_transfers_ctrl', self._callback_ep_test_parallel_transfers_ctrl) self.register_callback('ep_test_abort', self._callback_ep_test_abort) self.register_callback('ep_test_data_toggle', self._callback_ep_test_data_toggle) self.register_callback('reset_support', self._callback_reset_support) def result(self): return self.__result def teardown(self): pass class TestMatch(object): def __init__(self, serial): self.serial = serial def __call__(self, dev): try: return dev.serial_number == self.serial except ValueError: return False def lineno(): """Returns the current line number in our program.""" return inspect.currentframe().f_back.f_lineno def raise_if_different(expected, actual, line, text=''): """Raise a RuntimeError if actual is different than expected.""" if expected != actual: raise RuntimeError('[{}]:{}, {} Got {!r}, expected {!r}'.format(__file__, line, text, actual, expected)) def raise_unconditionally(line, text=''): """Raise a RuntimeError unconditionally.""" raise RuntimeError('[{}]:{}, {}'.format(__file__, line, text)) def control_basic_test(dev, vendor_id, product_id, log): get_set_configuration_test(dev, log) get_set_interface_test(dev, log) get_status_test(dev, log) set_clear_feature_test(dev, log) get_descriptor_test(dev, vendor_id, product_id, log) set_descriptor_test(dev, log) def get_set_configuration_test(dev, log): """ Test device configuration/deconfiguration Given an initialized USB (HOST <---> DUT connection established) When device configuration is checked just after initialization Then get_configuration returns 1 (default configuration is set) When device is deconfigured Then get_configuration returns 0 (no configuration is set) When each from supported configurations is set Then the configuration is set correctly """ print("<<< get_set_configuration_test >>>") # check if dafault(1) configuration set try: ret = usb.control.get_configuration(dev) raise_if_different(1, ret, lineno(), 'Invalid configuration.') except usb.core.USBError as error: raise_unconditionally(lineno(), 'get_configuration request failed ({}).'.format(str(error).strip())) cfg = dev.get_active_configuration() for intf in cfg: usb.util.release_interface(dev, intf) # deconfigure the device try: ret = dev.set_configuration(0) except usb.core.USBError as error: raise_unconditionally(lineno(), 'set_configuration request (deconfigure) failed ({}).'.format(str(error).strip())) # check if deconfigured try: ret = usb.control.get_configuration(dev) raise_if_different(0, ret, lineno(), 'Invalid configuration.') print("device deconfigured - OK") except usb.core.USBError as error: raise_unconditionally(lineno(), 'get_configuration request failed ({}).'.format(str(error).strip())) # for every configuration for cfg in dev: try: # set configuration ret = cfg.set() except usb.core.USBError as error: raise_unconditionally(lineno(), 'set_configuration request failed ({}).'.format(str(error).strip())) # check if configured try: ret = usb.control.get_configuration(dev) raise_if_different(cfg.bConfigurationValue, ret, lineno(), 'Invalid configuration.') print("configuration {} set - OK ".format(cfg.bConfigurationValue)) except usb.core.USBError as error: raise_unconditionally(lineno(), 'get_configuration request failed ({}).'.format(str(error).strip())) # test control data transfer after configuration set control_data_test(dev, [64, 256], log) print("") # new line def get_set_interface_test(dev, log): """ Test device interface setting Given an initialized USB (HOST <---> DUT connection established) When each altsetting from every supported configuration is set Then the interface altsetting is set correctly """ print("<<< get_set_interface_test >>>") # for every configuration for cfg in dev: cfg.set() # for every interface for intf in cfg: intf.set_altsetting() altsett = usb.control.get_interface(dev, intf.bInterfaceNumber) raise_if_different(intf.bAlternateSetting, altsett, lineno(), text='Wrong alternate setting for interface {}'.format(intf.bInterfaceNumber)) print("cfg({}) inteface {}.{} set - OK".format(cfg.bConfigurationValue, intf.bInterfaceNumber, intf.bAlternateSetting)) control_data_test(dev, [64, 256], log) release_interfaces(dev) restore_default_configuration(dev) # test control data transfer after default interface restoring control_data_test(dev, [64, 256], log) print("") # new line def get_status_test(dev, log): """ Test device/interface/endpoint status Given an initialized USB (HOST <---> DUT connection established) When device status is checked Then status is within allowed values (see status bits description below) When control endpoint status is checked Then control endpoint status is 0 When status of each interface from every supported configuration is checked Then interface status is 0 When status of each endpoint in every allowed device interface/configuration combination is checked Then endpoint status is 0 (not halted) """ print("<<< get_status_test >>>") # check device status ret = get_status(dev, CTRL_RECIPIENT_DEVICE) # Status bits # ret == 0b01 (D0)Self Powered # ret == 0b10 (D1)Remote Wakeup # (D2 - D15 reserved) Must be set to 0 if(ret < 0 or ret > 3): raise_unconditionally(lineno(), "GET_STATUS on DEVICE failed") # check endpoint 0 status ret = get_status(dev, CTRL_RECIPIENT_ENDPOINT, 0) # Status bits # ret == 0b1 (D0)endpoint Halt # (D1 - D15 reserved) Must be set to 0 # endpoint 0 can't be halted ret == 0 raise_if_different(0, ret, lineno(), "GET_STATUS on ENDPOINT 0 should return 0") # for every configuration for cfg in dev: cfg.set() raise_if_different(cfg.bConfigurationValue, usb.control.get_configuration(dev), lineno(), "Configuration {} set failed".format(cfg.bConfigurationValue)) for intf in cfg: intf.set_altsetting() # check interface status ret = get_status(dev, CTRL_RECIPIENT_INTERFACE, intf.bInterfaceNumber) # Status bits # ret == 0b0 # (D0 - D15 reserved) Must be set to 0 if(ret != 0): raise_unconditionally(lineno(), "GET_STATUS on INTERFACE ({},{}) failed".format(intf.bInterfaceNumber, intf.bAlternateSetting)) print("cfg({}) interface {}.{} status - OK".format(cfg.bConfigurationValue, intf.bInterfaceNumber, intf.bAlternateSetting)) # on every ENDPOINT in this altsetting for ep in intf: ret = usb.control.get_status(dev, ep) # Status bits # ret == 0b1 (D0)endpoint Halt # (D1 - D15 reserved) Must be set to 0 if(ret >= 1): raise_unconditionally(lineno(), "GET_STATUS on ENDPOINT {} failed - endpoint halted".format(ep.bEndpointAddress)) print("cfg({}) intf({}.{}) endpoint {} status - OK".format(cfg.bConfigurationValue, intf.bInterfaceNumber, intf.bAlternateSetting, ep.bEndpointAddress)) release_interfaces(dev) restore_default_configuration(dev) print("") # new line def set_clear_feature_test(dev, log): """ Test set/clear feature on device/interface/endpoint Given an initialized USB (HOST <---> DUT connection established) When for each endpoint in every allowed interface/configuration combination the feature is set and then cleared Then selected feature is set/cleared accordingly """ print("<<< set_clear_feature_test >>>") # TODO: # test set_feature on device (Remote wakeup feature not supported on DUT side) # test set_feature on interface (not supported at all) # for every configuration for cfg in dev: cfg.set() raise_if_different(cfg.bConfigurationValue, usb.control.get_configuration(dev), lineno(), "Configuration {} set failed".format(cfg.bConfigurationValue)) for intf in cfg: intf.set_altsetting() # on every ENDPOINT for ep in intf: # halt endpoint try: usb.control.set_feature(dev, FEATURE_ENDPOINT_HALT, ep) except usb.core.USBError as err: raise_unconditionally(lineno(), 'set_feature request (halt) failed for endpoint {} ({}).'.format(ep.bEndpointAddress, str(err).strip())) # check if endpoint was halted try: ret = usb.control.get_status(dev, ep) except usb.core.USBError as err: raise_unconditionally(lineno(), 'get_status request failed for endpoint {} ({}).'.format(ep.bEndpointAddress, str(err).strip())) if(ret != 1): raise_unconditionally(lineno(), "endpoint {} was not halted".format(ep.bEndpointAddress)) print("cfg({}) intf({}.{}) ep {} halted - OK".format(cfg.bConfigurationValue, intf.bInterfaceNumber, intf.bAlternateSetting, ep.bEndpointAddress)) # Control OUT CLEAR_FEATURE on endpoint - unhalt try: usb.control.clear_feature(dev, FEATURE_ENDPOINT_HALT, ep) except usb.core.USBError as err: raise_unconditionally(lineno(), "clear_feature request (unhalt) failed for endpoint {} ({})".format(ep.bEndpointAddress, str(err).strip())) # check if endpoint was unhalted ret = usb.control.get_status(dev, ep) if(ret != 0): raise_unconditionally(lineno(), "endpoint {} was not unhalted".format(ep.bEndpointAddress)) print("cfg({}) intf({}.{}) ep {} unhalted - OK".format(cfg.bConfigurationValue, intf.bInterfaceNumber, intf.bAlternateSetting, ep.bEndpointAddress)) release_interfaces(dev) restore_default_configuration(dev) print("") # new line def get_descriptor_test(dev, vendor_id, product_id, log): """ Test device/configuration/interface/endpoint descriptors Given an initialized USB (HOST <---> DUT connection established) When device descriptor is read Then the descriptor content is valid When configuration descriptor is read Then the descriptor content is valid When interface descriptor is read Then the error is thrown since it is not directly accessible When endpoint descriptor is read Then the error is thrown since it is not directly accessible """ print("<<< get_descriptor_test >>>") # device descriptor try: ret = get_descriptor(dev, (DESC_TYPE_DEVICE << 8) | (0 << 0), 0, DEVICE_DESC_SIZE) dev_desc = dict(zip(device_descriptor_keys, device_descriptor_parser.unpack(ret))) raise_if_different(DEVICE_DESC_SIZE, dev_desc['bLength'], lineno(), text='Wrong device descriptor size.') raise_if_different(vendor_id, dev_desc['idVendor'], lineno(), text='Wrong vendor ID.') raise_if_different(product_id, dev_desc['idProduct'], lineno(), text='Wrong product ID.') except usb.core.USBError: raise_unconditionally(lineno(), "Requesting device descriptor failed") # configuration descriptor try: ret = get_descriptor(dev, (DESC_TYPE_CONFIG << 8) | (0 << 0), 0, CONFIGURATION_DESC_SIZE) conf_desc = dict(zip(configuration_descriptor_keys, configuration_descriptor_parser.unpack(ret))) raise_if_different(CONFIGURATION_DESC_SIZE, conf_desc['bLength'], lineno(), text='Wrong configuration descriptor size.') except usb.core.USBError: raise_unconditionally(lineno(), "Requesting configuration descriptor failed") # interface descriptor try: ret = get_descriptor(dev, (DESC_TYPE_INTERFACE << 8) | (0 << 0), 0, INTERFACE_DESC_SIZE) raise_unconditionally(lineno(), "Requesting interface descriptor should fail since it is not directly accessible.") except usb.core.USBError: log("interface descriptor is not directly accessible - OK") # endpoint descriptor try: ret = get_descriptor(dev, (DESC_TYPE_ENDPOINT << 8) | (0 << 0), 0, ENDPOINT_DESC_SIZE) raise_unconditionally(lineno(), "Requesting endpoint descriptor should fail since it is not directly accessible.") except usb.core.USBError: log("endpoint descriptor is not directly accessible - OK") print("") # new line def set_descriptor_test(dev, log): """ Test descriptor setting Given an initialized USB (HOST <---> DUT connection established) When device descriptor is to be set Then error is thrown since descriptor setting command is not supported by Mbed """ print("<<< set_descriptor_test >>>") # SET_DESCRIPTOR is optional and not implemented in Mbed # command should fail with no action on device side # Control OUT SET_DESCRIPTOR request_type = build_request_type(CTRL_OUT, CTRL_TYPE_STANDARD, CTRL_RECIPIENT_DEVICE) request = REQUEST_SET_DESCRIPTOR value = (DESC_TYPE_DEVICE << 8) | (0 << 0) # Descriptor Type (H) and Descriptor Index (L) index = 0 # 0 or Language ID for this request data = bytearray(DEVICE_DESC_SIZE) # Descriptor data try: dev.ctrl_transfer(request_type, request, value, index, data) raise_unconditionally(lineno(), "set_descriptor request should fail since it is not implemented") except usb.core.USBError: log("SET_DESCRIPTOR is unsupported - OK") print("") # new line def synch_frame_test(dev, log): """ Test sync frame request Given an initialized USB (HOST <---> DUT connection established) When ... Then ... """ print("<<< synch_frame_test >>>") # only for isochronous endpoints request_type = build_request_type(CTRL_IN, CTRL_TYPE_STANDARD, CTRL_RECIPIENT_ENDPOINT) request = REQUEST_SYNCH_FRAME value = 0 # Always 0 for this request index = 1 # Endpoint index length = 2 # Always 2 for this request (size of return data) try: ret = dev.ctrl_transfer(request_type, request, value, index, length) ret = ret[0] | (ret[1] << 8) log("synch frame ret: %d" % (ret)) except usb.core.USBError: raise_unconditionally(lineno(), "SYNCH_FRAME request failed") print("") # new line def control_stall_test(dev, log): """ Test control endpoint stall on invalid request Given an initialized USB (HOST <---> DUT connection established) When unsupported request to control endpoint is to be sent Then the endpoint is stalled and error is thrown """ print("<<< control_stall_test >>>") # Control OUT stall try: request_type = build_request_type(CTRL_OUT, CTRL_TYPE_VENDOR, CTRL_RECIPIENT_DEVICE) request = VENDOR_TEST_UNSUPPORTED_REQUEST value = 0 # Always 0 for this request index = 0 # Communication interface data = bytearray(64) # Dummy data dev.ctrl_transfer(request_type, request, value, index, data, 5000) raise_unconditionally(lineno(), "Invalid request not stalled") except usb.core.USBError: log("Invalid request stalled - OK") # Control request with no data stage (Device-to-host) try: request_type = build_request_type(CTRL_IN, CTRL_TYPE_VENDOR, CTRL_RECIPIENT_DEVICE) request = VENDOR_TEST_UNSUPPORTED_REQUEST value = 0 # Always 0 for this request index = 0 # Communication interface length = 0 dev.ctrl_transfer(request_type, request, value, index, length, 5000) raise_unconditionally(lineno(), "Invalid request not stalled") except usb.core.USBError: log("Invalid request stalled - OK") # Control request with no data stage (Host-to-device) try: request_type = build_request_type(CTRL_OUT, CTRL_TYPE_VENDOR, CTRL_RECIPIENT_DEVICE) request = VENDOR_TEST_UNSUPPORTED_REQUEST value = 0 # Always 0 for this request index = 0 # Communication interface length = 0 dev.ctrl_transfer(request_type, request, value, index, length, 5000) raise_unconditionally(lineno(), "Invalid request not stalled") except usb.core.USBError: log("Invalid request stalled - OK") # Control IN stall try: request_type = build_request_type(CTRL_IN, CTRL_TYPE_VENDOR, CTRL_RECIPIENT_DEVICE) request = VENDOR_TEST_UNSUPPORTED_REQUEST value = 0 # Always 0 for this request index = 0 # Communication interface length = 255 dev.ctrl_transfer(request_type, request, value, index, length, 5000) raise_unconditionally(lineno(), "Invalid request not stalled") except usb.core.USBError: log("Invalid request stalled - OK") for i in (3, 4, 5): try: request_type = build_request_type(CTRL_IN, CTRL_TYPE_STANDARD, CTRL_RECIPIENT_DEVICE) request = 0x6 # GET_DESCRIPTOR value = (0x03 << 8) | (i << 0) # String descriptor index index = 0 # Communication interface length = 255 resp = dev.ctrl_transfer(request_type, request, value, index, length, 5000) except usb.core.USBError: raise_unconditionally(lineno(), "Requesting string failed i: " + str(i)) for i in (6, 7): try: request_type = build_request_type(CTRL_IN, CTRL_TYPE_STANDARD, CTRL_RECIPIENT_DEVICE) request = 0x6 # GET_DESCRIPTOR value = (0x03 << 8) | (i << 0) # String descriptor index index = 0 # Communication interface length = 255 resp = dev.ctrl_transfer(request_type, request, value, index, length, 5000) raise_unconditionally(lineno(), "Requesting string passed i: " + str(i)) except usb.core.USBError: log("Requesting string %s failed - OK" % i) print("") # new line def control_sizes_test(dev, log): """ Test various data sizes in control transfer Given an initialized USB (HOST <---> DUT connection established) When control data in each tested size is sent Then read data should match sent data """ list = [1, 2, 3, 7, 8, 9, 15, 16, 17, 31, 32, 33, 63, 64, 65, 127, 128, 129, 255, 256, 257, 511, 512, 513, 1023, 1024, 1025, 2047, 2048] control_data_test(dev, list, log) def control_data_test(dev, sizes_list, log): # Test control requests of various data stage sizes (1,8,16,32,64,255,256,...) count = 1 for i in sizes_list: request_type = build_request_type(CTRL_OUT, CTRL_TYPE_VENDOR, CTRL_RECIPIENT_DEVICE) request = VENDOR_TEST_CTRL_OUT_SIZES value = i # Size of data the device should actually read index = 0 # Unused - set for debugging only data = bytearray(os.urandom(i)) # Dummy data try: dev.ctrl_transfer(request_type, request, value, index, data, 5000) except usb.core.USBError: raise_unconditionally(lineno(), "VENDOR_TEST_CTRL_OUT_SIZES failed ") request_type = build_request_type(CTRL_IN, CTRL_TYPE_VENDOR, CTRL_RECIPIENT_DEVICE) request = VENDOR_TEST_CTRL_IN_SIZES value = 0 # Size of data the device should actually send index = 0 # Unused - set for debugging only length = i try: ret = dev.ctrl_transfer(request_type, request, value, index, length, 5000) raise_if_different(i, len(ret), lineno(), "send/receive data is the wrong size") for j in range(0, i): raise_if_different(data[j], ret[j], lineno(), "send/receive data mismatch") except usb.core.USBError: raise_unconditionally(lineno(), "VENDOR_TEST_CTRL_IN_SIZES failed") count += 1 def control_stress_test(dev, log): """ Test various patterns of control transfers Given an initialized USB (HOST <---> DUT connection established) When stress control transfer with a data in stage is performed Then transfer ends with success When stress control transfer with a data out stage followed by a control transfer with a data in stage is performed Then transfer ends with success When stress control transfer with a data out stage is performed Then transfer ends with success """ # Some devices have had problems with back-to-back # control transfers. Intentionally send these sequences # to make sure they are properly handled. count = 0 for _ in range(100): # Control transfer with a data in stage request_type = build_request_type(CTRL_IN, CTRL_TYPE_VENDOR, CTRL_RECIPIENT_DEVICE) request = VENDOR_TEST_CTRL_IN value = 8 # Size of data the device should actually send index = count # Unused - set for debugging only length = 255 dev.ctrl_transfer(request_type, request, value, index, length, 5000) count += 1 for _ in range(100): # Control transfer with a data out stage followed # by a control transfer with a data in stage request_type = build_request_type(CTRL_OUT, CTRL_TYPE_VENDOR, CTRL_RECIPIENT_DEVICE) request = VENDOR_TEST_CTRL_OUT value = 8 # Size of data the device should actually read index = count # Unused - set for debugging only data = bytearray(8) # Dummy data dev.ctrl_transfer(request_type, request, value, index, data, 5000) count += 1 request_type = build_request_type(CTRL_IN, CTRL_TYPE_VENDOR, CTRL_RECIPIENT_DEVICE) request = VENDOR_TEST_CTRL_IN value = 8 # Size of data the device should actually send index = count # Unused - set for debugging only length = 255 dev.ctrl_transfer(request_type, request, value, index, length, 5000) count += 1 for _ in range(100): # Control transfer with a data out stage request_type = build_request_type(CTRL_OUT, CTRL_TYPE_VENDOR, CTRL_RECIPIENT_DEVICE) request = VENDOR_TEST_CTRL_OUT value = 8 # Size of data the device should actually read index = count # Unused - set for debugging only data = bytearray(8) # Dummy data dev.ctrl_transfer(request_type, request, value, index, data, 5000) count += 1 def find_ep_pair(intf, endpoint_type): """Find an OUT and IN endpoint pair. Raise a RuntimeError if any endpoint could not be found or wMaxPacketSize is not equal for both endpoints. """ ep_out = usb.util.find_descriptor( intf, custom_match=lambda e: usb.util.endpoint_type(e.bmAttributes) == endpoint_type and usb.util.endpoint_direction(e.bEndpointAddress) == usb.ENDPOINT_OUT) ep_in = usb.util.find_descriptor( intf, custom_match=lambda e: usb.util.endpoint_type(e.bmAttributes) == endpoint_type and usb.util.endpoint_direction(e.bEndpointAddress) == usb.ENDPOINT_IN) if not all((ep_out, ep_in)): raise_unconditionally(lineno(), 'Unable to find {} endpoint pair.' .format(ENDPOINT_TYPE_NAMES[endpoint_type])) raise_if_different(ep_out.wMaxPacketSize, ep_in.wMaxPacketSize, lineno(), 'wMaxPacketSize not equal for OUT and IN {} endpoints.' .format(ENDPOINT_TYPE_NAMES[endpoint_type])) return ep_out, ep_in def loopback_ep_test(ep_out, ep_in, payload_size): """Send and receive random data using OUT/IN endpoint pair. Verify that data received from IN endpoint is equal to data sent to OUT endpoint. Raise a RuntimeError if data does not match. """ payload_out = array.array('B', (random.randint(0x00, 0xff) for _ in range(payload_size))) ep_out.write(payload_out) payload_in = ep_in.read(ep_in.wMaxPacketSize) raise_if_different(payload_out, payload_in, lineno(), 'Payloads mismatch.') def random_size_loopback_ep_test(ep_out, ep_in, failure, error, seconds, log, min_payload_size=1): """Repeat data transfer test for OUT/IN endpoint pair for a given time. Set a failure Event if OUT/IN data verification fails. Set an error Event if unexpected USB error occurs. """ end_ts = time.time() + seconds while time.time() < end_ts and not failure.is_set() and not error.is_set(): payload_size = random.randint(min_payload_size, ep_out.wMaxPacketSize) try: loopback_ep_test(ep_out, ep_in, payload_size) except RuntimeError as err: log(err) failure.set() return except usb.USBError as err: log(USB_ERROR_FMT.format(err, ep_out, ep_in, payload_size)) error.set() return time.sleep(0.01) def halt_ep_test(dev, ep_out, ep_in, log): """OUT/IN endpoint halt test. Verify that halting an endpoint at a random point of OUT or IN transfer raises a USBError. Raise a RuntimeError if halt fails or any unexpected error occurs. """ MIN_HALT_DELAY = 0.01 MAX_HALT_DELAY = 0.1 POST_HALT_DELAY = 0.1 ctrl_error = Event() for ep in (ep_out, ep_in): try: if (usb.control.get_status(dev, ep) == 1): raise_unconditionally(lineno(), 'Endpoints must NOT be halted at the start of this test') except usb.core.USBError as err: raise_unconditionally(lineno(), 'Unable to get endpoint status ({!r}).'.format(err)) ep_to_halt = random.choice([ep_out, ep_in]) def timer_handler(): """Halt an endpoint using a USB control request.""" try: usb.control.set_feature(dev, FEATURE_ENDPOINT_HALT, ep_to_halt) if (usb.control.get_status(dev, ep_to_halt) != 1): raise RuntimeError('Invalid endpoint status after halt operation') except Exception as err: ctrl_error.set() log('Endpoint {:#04x} halt failed ({!r}).'.format(ep_to_halt.bEndpointAddress, err)) # Whether the halt operation was successful or not, # wait a bit so the main thread has a chance to run into a USBError # or report the failure of halt operation. time.sleep(POST_HALT_DELAY) delay = random.uniform(MIN_HALT_DELAY, MAX_HALT_DELAY) delayed_halt = Timer(delay, timer_handler) delayed_halt.start() # Keep transferring data to and from the device until one of the endpoints # is halted. try: while delayed_halt.is_alive(): if ctrl_error.is_set(): break try: loopback_ep_test(ep_out, ep_in, ep_out.wMaxPacketSize) except usb.core.USBError as err: if ctrl_error.is_set(): break try: ep_status = usb.control.get_status(dev, ep_to_halt) except usb.core.USBError as err: if ctrl_error.is_set(): break raise_unconditionally(lineno(), 'Unable to get endpoint status ({!r}).'.format(err)) if ep_status == 1: # OK, got USBError because of endpoint halt return else: raise_unconditionally(lineno(), 'Unexpected error ({!r}).'.format(err)) if ctrl_error.is_set(): raise_unconditionally(lineno(), 'Halting endpoint {0.bEndpointAddress:#04x} failed' .format(ep_to_halt)) finally: # Always wait for the Timer thread created above. delayed_halt.join() if not ctrl_error.is_set(): ep_out.clear_halt() ep_in.clear_halt() raise_unconditionally(lineno(), 'Halting endpoint {0.bEndpointAddress:#04x}' ' during transmission did not raise USBError.' .format(ep_to_halt)) def request_endpoint_loops_restart(dev): ctrl_kwargs = { 'bmRequestType': build_request_type(CTRL_OUT, CTRL_TYPE_VENDOR, CTRL_RECIPIENT_DEVICE), 'bRequest': VENDOR_TEST_RW_RESTART, 'wValue': 0, 'wIndex': 0} dev.ctrl_transfer(**ctrl_kwargs) def request_abort_buff_check(dev, ep): ctrl_kwargs = { 'bmRequestType': build_request_type(CTRL_IN, CTRL_TYPE_VENDOR, CTRL_RECIPIENT_ENDPOINT), 'bRequest': VENDOR_TEST_ABORT_BUFF_CHECK, 'wValue': 0, 'wIndex': ep.bEndpointAddress, 'data_or_wLength': 1} return bool(dev.ctrl_transfer(**ctrl_kwargs)[0]) USB_ERROR_FMT = str('Got {0!r} while testing endpoints ' '{1.bEndpointAddress:#04x}({1.wMaxPacketSize:02}) and ' '{2.bEndpointAddress:#04x}({2.wMaxPacketSize:02}) with ' 'a random payload of {3} B.') def ep_test_data_correctness(dev, log, verbose=False): """Test data correctness for every OUT/IN endpoint pair. Given a USB device with multiple OUT/IN endpoint pairs When the host sends random payloads up to wMaxPacketSize in size to an OUT endpoint of the device, and then the device sends data back to host using an IN endpoint Then data sent and received by host is equal for every endpoint pair """ cfg = dev.get_active_configuration() for intf in cfg: log('interface {}, alt {} -- '.format(intf.bInterfaceNumber, intf.bAlternateSetting), end='') if intf.bAlternateSetting == 0: log('skipping the default AlternateSetting') continue log('running tests') intf.set_altsetting() bulk_out, bulk_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_BULK) interrupt_out, interrupt_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_INTERRUPT) iso_out, iso_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_ISOCHRONOUS) if verbose: log('\tbulk_out {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(bulk_out)) log('\tbulk_in {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(bulk_in)) log('\tinterrupt_out {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(interrupt_out)) log('\tinterrupt_in {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(interrupt_in)) log('\tiso_out {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(iso_out)) log('\tiso_in {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(iso_in)) if verbose: log('Testing OUT/IN data correctness for bulk endpoint pair.') for payload_size in range(bulk_out.wMaxPacketSize + 1): try: loopback_ep_test(bulk_out, bulk_in, payload_size) except usb.USBError as err: raise_unconditionally(lineno(), USB_ERROR_FMT.format(err, bulk_out, bulk_in, payload_size)) if verbose: log('Testing OUT/IN data correctness for interrupt endpoint pair.') for payload_size in range(interrupt_out.wMaxPacketSize + 1): try: loopback_ep_test(interrupt_out, interrupt_in, payload_size) except usb.USBError as err: raise_unconditionally(lineno(), USB_ERROR_FMT.format(err, interrupt_out, interrupt_in, payload_size)) # if verbose: # log('Testing OUT/IN data correctness for isochronous endnpoint pair.') # payload_size = 128 # range(1, iso_out.wMaxPacketSize + 1): # try: # loopback_ep_test(iso_out, iso_in, payload_size) # except usb.USBError as err: # log(err) # raise_unconditionally(lineno(), USB_ERROR_FMT.format(err, iso_out, iso_in, payload_size)) def ep_test_halt(dev, log, verbose=False): """Test endpoint halt for every OUT/IN endpoint pair. Given a USB device with multiple OUT/IN endpoint pairs When the host issues an endpoint halt control request at a random point of OUT or IN transfer Then the endpoint is stalled and all further transfers fail """ cfg = dev.get_active_configuration() for intf in cfg: log('interface {}, alt {} -- '.format(intf.bInterfaceNumber, intf.bAlternateSetting), end='') if intf.bAlternateSetting == 0: log('skipping the default AlternateSetting') continue log('running tests') intf.set_altsetting() bulk_out, bulk_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_BULK) interrupt_out, interrupt_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_INTERRUPT) if verbose: log('\tbulk_out {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(bulk_out)) log('\tbulk_in {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(bulk_in)) log('\tinterrupt_out {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(interrupt_out)) log('\tinterrupt_in {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(interrupt_in)) if verbose: log('Testing endpoint halt at a random point of bulk transmission.') end_ts = time.time() + 1.0 while time.time() < end_ts: halt_ep_test(dev, bulk_out, bulk_in, log) request_endpoint_loops_restart(dev) if verbose: log('Testing endpoint halt at a random point of interrupt transmission.') end_ts = time.time() + 1.0 while time.time() < end_ts: halt_ep_test(dev, interrupt_out, interrupt_in, log) request_endpoint_loops_restart(dev) def ep_test_parallel_transfers(dev, log, verbose=False): """Test simultaneous data transfers for multiple OUT/IN endpoint pairs. Given a USB device with multiple OUT/IN endpoint pairs When multiple OUT and IN endpoints are used to transfer random test data Then all transfers succeed and data received equals data sent for every endpoint pair """ cfg = dev.get_active_configuration() for intf in cfg: log('interface {}, alt {} -- '.format(intf.bInterfaceNumber, intf.bAlternateSetting), end='') if intf.bAlternateSetting == 0: log('skipping the default AlternateSetting') continue log('running tests') intf.set_altsetting() bulk_out, bulk_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_BULK) interrupt_out, interrupt_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_INTERRUPT) iso_out, iso_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_ISOCHRONOUS) if verbose: log('\tbulk_out {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(bulk_out)) log('\tbulk_in {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(bulk_in)) log('\tinterrupt_out {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(interrupt_out)) log('\tinterrupt_in {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(interrupt_in)) log('\tiso_out {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(iso_out)) log('\tiso_in {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(iso_in)) if verbose: log('Testing simultaneous transfers through bulk and interrupt endpoint pairs.') test_error = Event() test_failure = Event() test_kwargs_bulk_ep = { 'ep_out': bulk_out, 'ep_in': bulk_in, 'failure': test_failure, 'error': test_error, 'seconds': 1.0, 'log': log} test_kwargs_interrupt_ep = { 'ep_out': interrupt_out, 'ep_in': interrupt_in, 'failure': test_failure, 'error': test_error, 'seconds': 1.0, 'log': log} ep_test_threads = [] for kwargs in (test_kwargs_bulk_ep, test_kwargs_interrupt_ep): ep_test_threads.append(Thread(target=random_size_loopback_ep_test, kwargs=kwargs)) for t in ep_test_threads: t.start() for t in ep_test_threads: t.join() if test_failure.is_set(): raise_unconditionally(lineno(), 'Payload mismatch') if test_error.is_set(): raise_unconditionally(lineno(), 'USBError') def ep_test_parallel_transfers_ctrl(dev, log, verbose=False): """Test simultaneous data transfers in parallel with control transfers. Given a USB device with multiple OUT/IN endpoint pairs When multiple OUT and IN endpoints are used to transfer random data and control requests are processed in parallel Then all transfers succeed and for every endpoint pair, data received by host equals data sent by host """ cfg = dev.get_active_configuration() for intf in cfg: log('interface {}, alt {} -- '.format(intf.bInterfaceNumber, intf.bAlternateSetting), end='') if intf.bAlternateSetting == 0: log('skipping the default AlternateSetting') continue log('running tests') intf.set_altsetting() bulk_out, bulk_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_BULK) interrupt_out, interrupt_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_INTERRUPT) iso_out, iso_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_ISOCHRONOUS) if verbose: log('\tbulk_out {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(bulk_out)) log('\tbulk_in {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(bulk_in)) log('\tinterrupt_out {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(interrupt_out)) log('\tinterrupt_in {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(interrupt_in)) log('\tiso_out {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(iso_out)) log('\tiso_in {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(iso_in)) if verbose: log('Testing parallel data transfers through bulk, interrupt & control endpoint pairs.') test_error = Event() test_failure = Event() test_kwargs_bulk_ep = { 'ep_out': bulk_out, 'ep_in': bulk_in, 'failure': test_failure, 'error': test_error, 'seconds': 1.0, 'log': log} test_kwargs_interrupt_ep = { 'ep_out': interrupt_out, 'ep_in': interrupt_in, 'failure': test_failure, 'error': test_error, 'seconds': 1.0, 'log': log} ep_test_threads = [] for kwargs in (test_kwargs_bulk_ep, test_kwargs_interrupt_ep): ep_test_threads.append(Thread(target=random_size_loopback_ep_test, kwargs=kwargs)) for t in ep_test_threads: t.start() while any(t.is_alive() for t in ep_test_threads): control_stress_test(dev, log) control_sizes_test(dev, log) for t in ep_test_threads: t.join() if test_failure.is_set(): raise_unconditionally(lineno(), 'Payload mismatch') if test_error.is_set(): raise_unconditionally(lineno(), 'USBError') def ep_test_abort(dev, log, verbose=False): """Test aborting data transfer for every OUT/IN endpoint pair. Given a USB device with multiple OUT/IN endpoint pairs When a device aborts an in progress data transfer Then no more data is transmitted and endpoint buffer is correctly released on the device end """ NUM_PACKETS_UNTIL_ABORT = 2 NUM_PACKETS_AFTER_ABORT = 8 # If the host ever receives a payload with any byte set to this value, # the device does not handle abort operation correctly. The buffer # passed to aborted operation must not be used after call to abort(). FORBIDDEN_PAYLOAD_VALUE = NUM_PACKETS_AFTER_ABORT + 1 cfg = dev.get_active_configuration() for intf in cfg: log('interface {}, alt {} -- '.format(intf.bInterfaceNumber, intf.bAlternateSetting), end='') if intf.bAlternateSetting == 0: log('skipping the default AlternateSetting') continue log('running tests') intf.set_altsetting() bulk_out, bulk_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_BULK) interrupt_out, interrupt_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_INTERRUPT) if verbose: log('\tbulk_out {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(bulk_out)) log('\tbulk_in {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(bulk_in)) log('\tinterrupt_out {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(interrupt_out)) log('\tinterrupt_in {0.bEndpointAddress:#04x}, {0.wMaxPacketSize:02} B'.format(interrupt_in)) if verbose: log('Testing aborting an in progress transfer for IN endpoints.') for ep_in in (bulk_in, interrupt_in): payload_size = (NUM_PACKETS_UNTIL_ABORT + NUM_PACKETS_AFTER_ABORT) * ep_in.wMaxPacketSize payload_in = array.array('B') while len(payload_in) < payload_size: try: packet = ep_in.read(ep_in.wMaxPacketSize) payload_in.extend(packet) except usb.core.USBError as err: break if FORBIDDEN_PAYLOAD_VALUE in payload_in: raise_unconditionally( lineno(), 'Endpoint buffer not released when aborting the ' 'write operation on endpoint {0.bEndpointAddress:#04x}.' .format(ep_in)) if verbose: log('The size of data successfully received from endpoint {0.bEndpointAddress:#04x}: {1} B.' .format(ep_in, len(payload_in))) too_little = bool(len(payload_in) < (NUM_PACKETS_UNTIL_ABORT * ep_in.wMaxPacketSize)) too_much = bool(len(payload_in) >= payload_size) if too_little or too_much: raise_unconditionally( lineno(), 'Invalid size of data successfully received from endpoint ' '{0.bEndpointAddress:#04x} before aborting the transfer. ' 'Value {1} B out of range [{2}, {3}).' .format(ep_in, len(payload_in), NUM_PACKETS_UNTIL_ABORT * ep_in.wMaxPacketSize, payload_size)) if verbose: log('Testing aborting an in progress transfer for OUT endpoints.') for ep_out in (bulk_out, interrupt_out): payload_size = (NUM_PACKETS_UNTIL_ABORT + NUM_PACKETS_AFTER_ABORT) * ep_out.wMaxPacketSize num_bytes_written = 0 while num_bytes_written < payload_size: payload_out = array.array('B', (num_bytes_written//ep_out.wMaxPacketSize for _ in range(ep_out.wMaxPacketSize))) try: num_bytes_written += ep_out.write(payload_out) except usb.core.USBError: break try: ep_buff_correct = request_abort_buff_check(dev, ep_out) except (usb.core.USBError, IndexError, TypeError) as err: raise_unconditionally( lineno(), 'Unable to verify endpoint buffer content ({!r}).'.format(err)) if not ep_buff_correct: raise_unconditionally( lineno(), 'Endpoint buffer not released when aborting the ' 'read operation on endpoint {0.bEndpointAddress:#04x}.' .format(ep_out)) if verbose: log('The size of data successfully sent to endpoint {0.bEndpointAddress:#04x}: {1} B.' .format(ep_out, num_bytes_written)) too_little = bool(num_bytes_written < (NUM_PACKETS_UNTIL_ABORT * ep_out.wMaxPacketSize)) too_much = bool(num_bytes_written >= payload_size) if too_little or too_much: raise_unconditionally( lineno(), 'Invalid size of data successfully sent to endpoint ' '{0.bEndpointAddress:#04x} before aborting the transfer. ' 'Value {1} B out of range [{2}, {3}).' .format(ep_out, num_bytes_written, NUM_PACKETS_UNTIL_ABORT * ep_out.wMaxPacketSize, payload_size)) def ep_test_data_toggle(dev, log, verbose=False): """Test data toggle reset for bulk OUT/IN endpoint pairs. Given a USB device When an interface is set Then the data toggle bits for all endpoints are reset to DATA0 When clear feature is called for an endpoint that *IS NOT* stalled Then the data toggle is reset to DATA0 for that endpoint When clear halt is called for an endpoint that *IS* stalled Then the data toggle is reset to DATA0 for that endpoint """ cfg = dev.get_active_configuration() for intf in cfg: log('interface {}, alt {} -- '.format(intf.bInterfaceNumber, intf.bAlternateSetting), end='') if intf.bAlternateSetting == 0: log('skipping the default AlternateSetting') continue log('running tests') if verbose: log('Testing data toggle reset for bulk endpoint pair.') # 1.1 reset OUT and IN data toggle to DATA0 intf.set_altsetting() bulk_out, bulk_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_BULK) # 1.2 send and receive a single data packet, # so both OUT and IN endpoints switch to DATA1 loopback_ep_test(bulk_out, bulk_in, bulk_out.wMaxPacketSize) # 1.3 reset OUT and IN data toggle to DATA0 # USB spec, section 9.1.1.5 # " # Configuring a device or changing an alternate setting causes all of the status and # configuration values associated with endpoints in the affected interfaces to be set to their default values. # This includes setting the data toggle of any endpoint using data toggles to the value DATA0. # " intf.set_altsetting() bulk_out, bulk_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_BULK) # 1.4 verify that host and USB device are still in sync with respect to data toggle try: loopback_ep_test(bulk_out, bulk_in, bulk_out.wMaxPacketSize) except usb.USBError as err: if verbose: log(USB_ERROR_FMT.format(err, bulk_out, bulk_in, bulk_out.wMaxPacketSize)) raise_unconditionally(lineno(), 'Data toggle not reset when setting interface.') # 2.1 reset OUT and IN data toggle to DATA0 intf.set_altsetting() bulk_out, bulk_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_BULK) # 2.2 send and receive a single data packet, # so both OUT and IN endpoints switch to DATA1 loopback_ep_test(bulk_out, bulk_in, bulk_out.wMaxPacketSize) # 2.3 reset OUT data toggle to DATA0 # USB spec, section 9.4.5 # " # For endpoints using data toggle, regardless of whether an endpoint has the Halt feature set, a # ClearFeature(ENDPOINT_HALT) request always results in the data toggle being reinitialized to DATA0. # " bulk_out.clear_halt() # The ClearFeature(ENDPOINT_HALT) terminates a pending read operation on the device end. # Use a custom vendor request to restart reading on the OUT endpoint. # This does not impact the state of the data toggle bit. request_endpoint_loops_restart(dev) # 2.4 verify that host and USB device are still in sync with respect to data toggle try: loopback_ep_test(bulk_out, bulk_in, bulk_out.wMaxPacketSize) except usb.USBError as err: if verbose: log(USB_ERROR_FMT.format(err, bulk_out, bulk_in, bulk_out.wMaxPacketSize)) raise_unconditionally(lineno(), 'Data toggle not reset when calling ClearFeature(ENDPOINT_HALT) ' 'on an endpoint that has not been halted.') # 3.1 reset OUT and IN data toggle to DATA0 intf.set_altsetting() bulk_out, bulk_in = find_ep_pair(intf, usb.ENDPOINT_TYPE_BULK) # 3.2 send and receive a single data packet, # so both OUT and IN endpoints switch to DATA1 loopback_ep_test(bulk_out, bulk_in, bulk_out.wMaxPacketSize) # 3.3 reset IN data toggle to DATA0 # USB spec, section 9.4.5 # " # For endpoints using data toggle, regardless of whether an endpoint has the Halt feature set, a # ClearFeature(ENDPOINT_HALT) request always results in the data toggle being reinitialized to DATA0. # " usb.control.set_feature(dev, FEATURE_ENDPOINT_HALT, bulk_in) bulk_in.clear_halt() # 3.4 verify that host and USB device are still in sync with respect to data toggle try: loopback_ep_test(bulk_out, bulk_in, bulk_out.wMaxPacketSize) except usb.USBError as err: if verbose: log(USB_ERROR_FMT.format(err, bulk_out, bulk_in, bulk_out.wMaxPacketSize)) raise_unconditionally(lineno(), 'Data toggle not reset when clearing endpoint halt.') def device_reset_test(log): """ Test USB implementation against repeated reset Given an initialized USB (HOST <---> DUT connection established) When USB device is reset repeatedly Then the USB is operational with no errors """ dev = yield dev.reset(); dev = yield # run other test to check if USB works fine after reset control_data_test(dev, [64, 256], log) dev.reset(); dev = yield # run other test to check if USB works fine after reset control_data_test(dev, [64, 256], log) dev.reset(); dev = yield # run other test to check if USB works fine after reset control_data_test(dev, [64, 256], log) yield def device_soft_reconnection_test(log): """ Test USB implementation against repeated reconnection Given an initialized USB (HOST <---> DUT connection established) When USB device is disconnected and then connected repeatedly Then the USB is operational with no errors """ list = [64, 256] dev = yield # run other test to check if USB works fine before reconnection control_data_test(dev, list, log) dev = yield # run other test to check if USB works fine after reconnection control_data_test(dev, list, log) dev = yield # run other test to check if USB works fine after reconnection control_data_test(dev, list, log) dev = yield # run other test to check if USB works fine after reconnection control_data_test(dev, list, log) dev = yield # run other test to check if USB works fine after reconnection control_data_test(dev, list, log) yield def device_suspend_resume_test(log): """ Test USB implementation against repeated suspend and resume Given an initialized USB (HOST <---> DUT connection established) When USB device is suspended and then resumed repeatedly Then the USB is operational with no errors """ dev = yield control_data_test(dev, [64, 256], log) # suspend code goes here # ... # resume code here # ... # run other test to check if USB works fine after resume control_data_test(dev, [64, 256], log) # suspend code here # ... # resume code here # ... # run other test to check if USB works fine after resume control_data_test(dev, [64, 256], log) # suspend code here # ... # resume code here # ... # run other test to check if USB works fine after resume control_data_test(dev, [64, 256], log) yield def repeated_construction_destruction_test(log): """ Test USB implementation against repeated initialization and deinitialization Given an initialized USB (HOST <---> DUT connection established) When USB device is deinitialized and then initialized repeatedly Then the USB is operational with no errors """ list = [64, 256] dev = yield # run other test to check if USB works fine after repeated construction/destruction control_data_test(dev, list, log) dev = yield # run other test to check if USB works fine after repeated construction/destruction control_data_test(dev, list, log) dev = yield # run other test to check if USB works fine after repeated construction/destruction control_data_test(dev, list, log) yield def release_interfaces(dev): """ Releases interfaces to allow configuration switch Fixes error while configuration change(on Windows machines): USBError: [Errno None] libusb0-dll:err [set_configuration] can't change configuration, an interface is still in use (claimed) """ cfg = dev.get_active_configuration() for i in range(0, cfg.bNumInterfaces): usb.util.release_interface(dev, i) def restore_default_configuration(dev): """ Set default configuration """ cfg = dev[1] cfg.set() def get_status(dev, recipient, index = 0): """ Get status of the recipient Args: dev - pyusb device recipient - CTRL_RECIPIENT_DEVICE/CTRL_RECIPIENT_INTERFACE/CTRL_RECIPIENT_ENDPOINT index - 0 if recipient is device, interface index if recipient is interface, endpoint index if recipient is endpoint Returns: status flag 32b int """ request_type = build_request_type(CTRL_IN, CTRL_TYPE_STANDARD, recipient) request = REQUEST_GET_STATUS value = 0 # Always 0 for this request index = index # recipient index length = 2 # Always 2 for this request (size of return data) ret = dev.ctrl_transfer(request_type, request, value, index, length) ret = ret[0] | (ret[1] << 8) return ret def get_descriptor(dev, type_index, lang_id, length): # Control IN GET_DESCRIPTOR - device request_type = build_request_type(CTRL_IN, CTRL_TYPE_STANDARD, CTRL_RECIPIENT_DEVICE) request = REQUEST_GET_DESCRIPTOR value = type_index # Descriptor Type (H) and Descriptor Index (L) index = lang_id # 0 or Language ID for this request length = length # Descriptor Length ret = dev.ctrl_transfer(request_type, request, value, index, length) return ret
apache-2.0
heeraj123/oh-mainline
vendor/packages/bleach/bleach/tests/test_unicode.py
35
1909
# -*- coding: utf-8 -*- from nose.tools import eq_ from bleach import clean, linkify def test_japanese_safe_simple(): eq_(u'ヘルプとチュートリアル', clean(u'ヘルプとチュートリアル')) eq_(u'ヘルプとチュートリアル', linkify(u'ヘルプとチュートリアル')) def test_japanese_strip(): eq_(u'<em>ヘルプとチュートリアル</em>', clean(u'<em>ヘルプとチュートリアル</em>')) eq_(u'&lt;span&gt;ヘルプとチュートリアル&lt;/span&gt;', clean(u'<span>ヘルプとチュートリアル</span>')) def test_russian_simple(): eq_(u'Домашняя', clean(u'Домашняя')) eq_(u'Домашняя', linkify(u'Домашняя')) def test_mixed(): eq_(u'Домашняяヘルプとチュートリアル', clean(u'Домашняяヘルプとチュートリアル')) def test_mixed_linkify(): eq_(u'Домашняя <a href="http://example.com" rel="nofollow">' u'http://example.com</a> ヘルプとチュートリアル', linkify(u'Домашняя http://example.com ヘルプとチュートリアル')) def test_url_utf8(): """Allow UTF8 characters in URLs themselves.""" out = u'<a href="%(url)s" rel="nofollow">%(url)s</a>' tests = ( ('http://éxámplé.com/', out % {'url': u'http://éxámplé.com/'}), ('http://éxámplé.com/íàñá/', out % {'url': u'http://éxámplé.com/íàñá/'}), ('http://éxámplé.com/íàñá/?foo=bar', out % {'url': u'http://éxámplé.com/íàñá/?foo=bar'}), ('http://éxámplé.com/íàñá/?fóo=bár', out % {'url': u'http://éxámplé.com/íàñá/?fóo=bár'}), ) def check(test, expected_output): eq_(expected_output, linkify(test)) for test, expected_output in tests: yield check, test, expected_output
agpl-3.0
adborden/django-calaccess-raw-data
calaccess_raw/management/commands/cleancalaccessrawfile.py
29
5058
from __future__ import unicode_literals import os import csv from io import StringIO from django.utils import six from csvkit import CSVKitReader, CSVKitWriter from calaccess_raw import get_download_directory from django.core.management.base import LabelCommand from calaccess_raw.management.commands import CalAccessCommand class Command(CalAccessCommand, LabelCommand): help = 'Clean a source CAL-ACCESS file and reformat it as a CSV' args = '<file name>' def handle_label(self, label, **options): # Set options self.verbosity = int(options.get("verbosity")) self.data_dir = get_download_directory() self.tsv_dir = os.path.join(self.data_dir, "tsv/") self.csv_dir = os.path.join(self.data_dir, "csv/") self.log_dir = os.path.join(self.data_dir, "log/") # Do it self.clean(label) def clean(self, name): """ Cleans the provided source TSV file and writes it out in CSV format """ if self.verbosity > 2: self.log(" Cleaning %s" % name) # Up the CSV data limit csv.field_size_limit(1000000000) # Input and output paths tsv_path = os.path.join(self.tsv_dir, name) csv_path = os.path.join( self.csv_dir, name.lower().replace("tsv", "csv") ) # Writer csv_file = open(csv_path, 'w') csv_writer = CSVKitWriter(csv_file, quoting=csv.QUOTE_ALL) # Reader tsv_file = open(tsv_path, 'rb') # Pull and clean the headers try: headers = tsv_file.readline() except StopIteration: return headers = headers.decode("ascii", "replace") headers_csv = CSVKitReader(StringIO(headers), delimiter=str('\t')) try: headers_list = next(headers_csv) except StopIteration: return headers_count = len(headers_list) csv_writer.writerow(headers_list) log_rows = [] # Loop through the rest of the data line_number = 1 for tsv_line in tsv_file: # Goofing around with the encoding while we're in there. tsv_line = tsv_line.decode("ascii", "replace") if six.PY2: tsv_line = tsv_line.replace('\ufffd', '?') # Nuke any null bytes null_bytes = tsv_line.count('\x00') if null_bytes: tsv_line = tsv_line.replace('\x00', ' ') # Nuke ASCII 26 char, the "substitute character" # or chr(26) in python sub_char = tsv_line.count('\x1a') if sub_char: tsv_line = tsv_line.replace('\x1a', '') # Split on tabs so we can later spit it back out as CSV # and remove extra newlines while we are there. csv_field_list = tsv_line.replace("\r\n", "").split("\t") # Check if our values line up with our headers # and if not, see if CSVkit can sort out the problems if not len(csv_field_list) == headers_count: csv_field_list = next(CSVKitReader( StringIO(tsv_line), delimiter=str('\t') )) if not len(csv_field_list) == headers_count: if self.verbosity > 2: msg = ' Bad parse of line %s (%s headers, %s values)' self.failure(msg % ( line_number, len(headers_list), len(csv_field_list) )) log_rows.append([ line_number, len(headers_list), len(csv_field_list), ','.join(csv_field_list) ]) continue # Write out the row csv_writer.writerow(csv_field_list) line_number += 1 # Log errors if there are any if log_rows: if self.verbosity > 1: msg = ' %s errors' self.failure(msg % (len(log_rows) - 1)) self.log_errors(name, log_rows) # Shut it down tsv_file.close() csv_file.close() def log_errors(self, name, rows): """ Log any errors to a csv file """ # Make sure the log directory exists os.path.exists(self.log_dir) or os.mkdir(self.log_dir) # Log writer log_path = os.path.join( self.log_dir, name.lower().replace("tsv", "errors.csv") ) log_file = open(log_path, 'w') log_writer = CSVKitWriter(log_file, quoting=csv.QUOTE_ALL) # Add the headers log_writer.writerow([ 'Line number', 'Headers len', 'Fields len', 'Line value' ]) # Log out the rows log_writer.writerows(rows) # Shut it down log_file.close()
mit
loopCM/chromium
third_party/mesa/MesaLib/src/gallium/auxiliary/util/u_format_table.py
32
7132
#!/usr/bin/env python ''' /************************************************************************** * * Copyright 2010 VMware, Inc. * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ ''' import sys from u_format_parse import * import u_format_pack def layout_map(layout): return 'UTIL_FORMAT_LAYOUT_' + str(layout).upper() def colorspace_map(colorspace): return 'UTIL_FORMAT_COLORSPACE_' + str(colorspace).upper() colorspace_channels_map = { 'rgb': ['r', 'g', 'b', 'a'], 'srgb': ['sr', 'sg', 'sb', 'a'], 'zs': ['z', 's'], 'yuv': ['y', 'u', 'v'], } type_map = { VOID: "UTIL_FORMAT_TYPE_VOID", UNSIGNED: "UTIL_FORMAT_TYPE_UNSIGNED", SIGNED: "UTIL_FORMAT_TYPE_SIGNED", FIXED: "UTIL_FORMAT_TYPE_FIXED", FLOAT: "UTIL_FORMAT_TYPE_FLOAT", } def bool_map(value): if value: return "TRUE" else: return "FALSE" swizzle_map = { SWIZZLE_X: "UTIL_FORMAT_SWIZZLE_X", SWIZZLE_Y: "UTIL_FORMAT_SWIZZLE_Y", SWIZZLE_Z: "UTIL_FORMAT_SWIZZLE_Z", SWIZZLE_W: "UTIL_FORMAT_SWIZZLE_W", SWIZZLE_0: "UTIL_FORMAT_SWIZZLE_0", SWIZZLE_1: "UTIL_FORMAT_SWIZZLE_1", SWIZZLE_NONE: "UTIL_FORMAT_SWIZZLE_NONE", } def write_format_table(formats): print '/* This file is autogenerated by u_format_table.py from u_format.csv. Do not edit directly. */' print # This will print the copyright message on the top of this file print __doc__.strip() print print '#include "u_format.h"' print '#include "u_format_s3tc.h"' print u_format_pack.generate(formats) for format in formats: print 'const struct util_format_description' print 'util_format_%s_description = {' % (format.short_name(),) print " %s," % (format.name,) print " \"%s\"," % (format.name,) print " \"%s\"," % (format.short_name(),) print " {%u, %u, %u},\t/* block */" % (format.block_width, format.block_height, format.block_size()) print " %s," % (layout_map(format.layout),) print " %u,\t/* nr_channels */" % (format.nr_channels(),) print " %s,\t/* is_array */" % (bool_map(format.is_array()),) print " %s,\t/* is_bitmask */" % (bool_map(format.is_bitmask()),) print " %s,\t/* is_mixed */" % (bool_map(format.is_mixed()),) print " {" for i in range(4): channel = format.channels[i] if i < 3: sep = "," else: sep = "" if channel.size: print " {%s, %s, %u}%s\t/* %s = %s */" % (type_map[channel.type], bool_map(channel.norm), channel.size, sep, "xyzw"[i], channel.name) else: print " {0, 0, 0}%s" % (sep,) print " }," print " {" for i in range(4): swizzle = format.swizzles[i] if i < 3: sep = "," else: sep = "" try: comment = colorspace_channels_map[format.colorspace][i] except (KeyError, IndexError): comment = 'ignored' print " %s%s\t/* %s */" % (swizzle_map[swizzle], sep, comment) print " }," print " %s," % (colorspace_map(format.colorspace),) if format.colorspace != ZS: print " &util_format_%s_unpack_rgba_8unorm," % format.short_name() print " &util_format_%s_pack_rgba_8unorm," % format.short_name() if format.layout == 's3tc': print " &util_format_%s_fetch_rgba_8unorm," % format.short_name() else: print " NULL, /* fetch_rgba_8unorm */" print " &util_format_%s_unpack_rgba_float," % format.short_name() print " &util_format_%s_pack_rgba_float," % format.short_name() print " &util_format_%s_fetch_rgba_float," % format.short_name() else: print " NULL, /* unpack_rgba_8unorm */" print " NULL, /* pack_rgba_8unorm */" print " NULL, /* fetch_rgba_8unorm */" print " NULL, /* unpack_rgba_float */" print " NULL, /* pack_rgba_float */" print " NULL, /* fetch_rgba_float */" if format.colorspace == ZS and format.swizzles[0] != SWIZZLE_NONE: print " &util_format_%s_unpack_z_32unorm," % format.short_name() print " &util_format_%s_pack_z_32unorm," % format.short_name() print " &util_format_%s_unpack_z_float," % format.short_name() print " &util_format_%s_pack_z_float," % format.short_name() else: print " NULL, /* unpack_z_32unorm */" print " NULL, /* pack_z_32unorm */" print " NULL, /* unpack_z_float */" print " NULL, /* pack_z_float */" if format.colorspace == ZS and format.swizzles[1] != SWIZZLE_NONE: print " &util_format_%s_unpack_s_8uscaled," % format.short_name() print " &util_format_%s_pack_s_8uscaled" % format.short_name() else: print " NULL, /* unpack_s_8uscaled */" print " NULL /* pack_s_8uscaled */" print "};" print print "const struct util_format_description *" print "util_format_description(enum pipe_format format)" print "{" print " if (format >= PIPE_FORMAT_COUNT) {" print " return NULL;" print " }" print print " switch (format) {" for format in formats: print " case %s:" % format.name print " return &util_format_%s_description;" % (format.short_name(),) print " default:" print " return NULL;" print " }" print "}" print def main(): formats = [] for arg in sys.argv[1:]: formats.extend(parse(arg)) write_format_table(formats) if __name__ == '__main__': main()
bsd-3-clause
JeyZeta/Dangerous
Dangerous/Golismero/thirdparty_libs/django/utils/synch.py
251
2636
""" Synchronization primitives: - reader-writer lock (preference to writers) (Contributed to Django by eugene@lazutkin.com) """ import contextlib try: import threading except ImportError: import dummy_threading as threading class RWLock(object): """ Classic implementation of reader-writer lock with preference to writers. Readers can access a resource simultaneously. Writers get an exclusive access. API is self-descriptive: reader_enters() reader_leaves() writer_enters() writer_leaves() """ def __init__(self): self.mutex = threading.RLock() self.can_read = threading.Semaphore(0) self.can_write = threading.Semaphore(0) self.active_readers = 0 self.active_writers = 0 self.waiting_readers = 0 self.waiting_writers = 0 def reader_enters(self): with self.mutex: if self.active_writers == 0 and self.waiting_writers == 0: self.active_readers += 1 self.can_read.release() else: self.waiting_readers += 1 self.can_read.acquire() def reader_leaves(self): with self.mutex: self.active_readers -= 1 if self.active_readers == 0 and self.waiting_writers != 0: self.active_writers += 1 self.waiting_writers -= 1 self.can_write.release() @contextlib.contextmanager def reader(self): self.reader_enters() try: yield finally: self.reader_leaves() def writer_enters(self): with self.mutex: if self.active_writers == 0 and self.waiting_writers == 0 and self.active_readers == 0: self.active_writers += 1 self.can_write.release() else: self.waiting_writers += 1 self.can_write.acquire() def writer_leaves(self): with self.mutex: self.active_writers -= 1 if self.waiting_writers != 0: self.active_writers += 1 self.waiting_writers -= 1 self.can_write.release() elif self.waiting_readers != 0: t = self.waiting_readers self.waiting_readers = 0 self.active_readers += t while t > 0: self.can_read.release() t -= 1 @contextlib.contextmanager def writer(self): self.writer_enters() try: yield finally: self.writer_leaves()
mit
DiptoDas8/Biponi
lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/misc.py
103
1381
""" This module is for the miscellaneous GEOS routines, particularly the ones that return the area, distance, and length. """ from ctypes import POINTER, c_double, c_int from django.contrib.gis.geos.libgeos import GEOM_PTR from django.contrib.gis.geos.prototypes.errcheck import check_dbl, check_string from django.contrib.gis.geos.prototypes.geom import geos_char_p from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc from django.utils.six.moves import range __all__ = ['geos_area', 'geos_distance', 'geos_length', 'geos_isvalidreason'] # ### ctypes generator function ### def dbl_from_geom(func, num_geom=1): """ Argument is a Geometry, return type is double that is passed in by reference as the last argument. """ argtypes = [GEOM_PTR for i in range(num_geom)] argtypes += [POINTER(c_double)] func.argtypes = argtypes func.restype = c_int # Status code returned func.errcheck = check_dbl return func # ### ctypes prototypes ### # Area, distance, and length prototypes. geos_area = dbl_from_geom(GEOSFunc('GEOSArea')) geos_distance = dbl_from_geom(GEOSFunc('GEOSDistance'), num_geom=2) geos_length = dbl_from_geom(GEOSFunc('GEOSLength')) geos_isvalidreason = GEOSFunc('GEOSisValidReason') geos_isvalidreason.argtypes = [GEOM_PTR] geos_isvalidreason.restype = geos_char_p geos_isvalidreason.errcheck = check_string
mit
pabloborrego93/edx-platform
cms/lib/xblock/tagging/migrations/0001_initial.py
39
1187
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='TagAvailableValues', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('value', models.CharField(max_length=255)), ], options={ 'ordering': ('id',), }, ), migrations.CreateModel( name='TagCategories', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=255, unique=True)), ('title', models.CharField(max_length=255)), ], options={ 'ordering': ('title',), }, ), migrations.AddField( model_name='tagavailablevalues', name='category', field=models.ForeignKey(to='tagging.TagCategories'), ), ]
agpl-3.0
aeischeid/servo
tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_server.py
299
1320
import os import unittest import urllib2 import json import wptserve from base import TestUsingServer, doc_root class TestFileHandler(TestUsingServer): def test_not_handled(self): with self.assertRaises(urllib2.HTTPError) as cm: resp = self.request("/not_existing") self.assertEquals(cm.exception.code, 404) class TestRewriter(TestUsingServer): def test_rewrite(self): @wptserve.handlers.handler def handler(request, response): return request.request_path route = ("GET", "/test/rewritten", handler) self.server.rewriter.register("GET", "/test/original", route[1]) self.server.router.register(*route) resp = self.request("/test/original") self.assertEquals(200, resp.getcode()) self.assertEquals("/test/rewritten", resp.read()) class TestRequestHandler(TestUsingServer): def test_exception(self): @wptserve.handlers.handler def handler(request, response): raise Exception route = ("GET", "/test/raises", handler) self.server.router.register(*route) with self.assertRaises(urllib2.HTTPError) as cm: resp = self.request("/test/raises") self.assertEquals(cm.exception.code, 500) if __name__ == "__main__": unittest.main()
mpl-2.0
levilucio/SyVOLT
UMLRT2Kiltera_MM/collapse_rules/models/move_one_input_direct_apply_diff_rules_MDL.py
6
29876
""" __move_one_input_direct_apply_diff_rules_MDL.py_____________________________________________________ Automatically generated AToM3 Model File (Do not modify directly) Author: levi Modified: Wed Aug 21 16:40:54 2013 ____________________________________________________________________________________________________ """ from stickylink import * from widthXfillXdecoration import * from MT_pre__MetaModelElement_T import * from MT_pre__directLink_T import * from MT_post__MetaModelElement_T import * from MT_post__directLink_T import * from RHS import * from LHS import * from graph_MT_post__MetaModelElement_T import * from graph_LHS import * from graph_MT_post__directLink_T import * from graph_MT_pre__directLink_T import * from graph_MT_pre__MetaModelElement_T import * from graph_RHS import * from ATOM3Enum import * from ATOM3String import * from ATOM3BottomType import * from ATOM3Constraint import * from ATOM3Attribute import * from ATOM3Float import * from ATOM3List import * from ATOM3Link import * from ATOM3Connection import * from ATOM3Boolean import * from ATOM3Appearance import * from ATOM3Text import * from ATOM3Action import * from ATOM3Integer import * from ATOM3Port import * from ATOM3MSEnum import * def move_one_input_direct_apply_diff_rules_MDL(self, rootNode, MT_pre__GM2AUTOSAR_MMRootNode=None, MT_post__GM2AUTOSAR_MMRootNode=None, MoTifRuleRootNode=None): # --- Generating attributes code for ASG MT_pre__GM2AUTOSAR_MM --- if( MT_pre__GM2AUTOSAR_MMRootNode ): # author MT_pre__GM2AUTOSAR_MMRootNode.author.setValue('Annonymous') # description MT_pre__GM2AUTOSAR_MMRootNode.description.setValue('\n') MT_pre__GM2AUTOSAR_MMRootNode.description.setHeight(15) # name MT_pre__GM2AUTOSAR_MMRootNode.name.setValue('') MT_pre__GM2AUTOSAR_MMRootNode.name.setNone() # --- ASG attributes over --- # --- Generating attributes code for ASG MT_post__GM2AUTOSAR_MM --- if( MT_post__GM2AUTOSAR_MMRootNode ): # author MT_post__GM2AUTOSAR_MMRootNode.author.setValue('Annonymous') # description MT_post__GM2AUTOSAR_MMRootNode.description.setValue('\n') MT_post__GM2AUTOSAR_MMRootNode.description.setHeight(15) # name MT_post__GM2AUTOSAR_MMRootNode.name.setValue('') MT_post__GM2AUTOSAR_MMRootNode.name.setNone() # --- ASG attributes over --- # --- Generating attributes code for ASG MoTifRule --- if( MoTifRuleRootNode ): # author MoTifRuleRootNode.author.setValue('Annonymous') # description MoTifRuleRootNode.description.setValue('\n') MoTifRuleRootNode.description.setHeight(15) # name MoTifRuleRootNode.name.setValue('MoveOneInputDirectApplyDiffRules') # --- ASG attributes over --- self.obj71=MT_pre__MetaModelElement_T(self) self.obj71.isGraphObjectVisual = True if(hasattr(self.obj71, '_setHierarchicalLink')): self.obj71._setHierarchicalLink(False) # MT_pivotOut__ self.obj71.MT_pivotOut__.setValue('element1') # MT_subtypeMatching__ self.obj71.MT_subtypeMatching__.setValue(('True', 1)) self.obj71.MT_subtypeMatching__.config = 0 # MT_pre__classtype self.obj71.MT_pre__classtype.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n') self.obj71.MT_pre__classtype.setHeight(15) # MT_pivotIn__ self.obj71.MT_pivotIn__.setValue('element1') # MT_label__ self.obj71.MT_label__.setValue('3') # MT_pre__cardinality self.obj71.MT_pre__cardinality.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n') self.obj71.MT_pre__cardinality.setHeight(15) # MT_pre__name self.obj71.MT_pre__name.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n') self.obj71.MT_pre__name.setHeight(15) self.obj71.graphClass_= graph_MT_pre__MetaModelElement_T if self.genGraphics: new_obj = graph_MT_pre__MetaModelElement_T(34.0,303.0,self.obj71) new_obj.DrawObject(self.UMLmodel) self.UMLmodel.addtag_withtag("MT_pre__MetaModelElement_T", new_obj.tag) new_obj.layConstraints = dict() # Graphical Layout Constraints new_obj.layConstraints['scale'] = [1.0, 1.0] else: new_obj = None self.obj71.graphObject_ = new_obj # Add node to the root: rootNode rootNode.addNode(self.obj71) self.globalAndLocalPostcondition(self.obj71, rootNode) self.obj71.postAction( rootNode.CREATE ) self.obj72=MT_pre__MetaModelElement_T(self) self.obj72.isGraphObjectVisual = True if(hasattr(self.obj72, '_setHierarchicalLink')): self.obj72._setHierarchicalLink(False) # MT_pivotOut__ self.obj72.MT_pivotOut__.setValue('element2') # MT_subtypeMatching__ self.obj72.MT_subtypeMatching__.setValue(('True', 1)) self.obj72.MT_subtypeMatching__.config = 0 # MT_pre__classtype self.obj72.MT_pre__classtype.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n') self.obj72.MT_pre__classtype.setHeight(15) # MT_pivotIn__ self.obj72.MT_pivotIn__.setValue('element2') # MT_label__ self.obj72.MT_label__.setValue('4') # MT_pre__cardinality self.obj72.MT_pre__cardinality.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n') self.obj72.MT_pre__cardinality.setHeight(15) # MT_pre__name self.obj72.MT_pre__name.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n') self.obj72.MT_pre__name.setHeight(15) self.obj72.graphClass_= graph_MT_pre__MetaModelElement_T if self.genGraphics: new_obj = graph_MT_pre__MetaModelElement_T(141.0,186.0,self.obj72) new_obj.DrawObject(self.UMLmodel) self.UMLmodel.addtag_withtag("MT_pre__MetaModelElement_T", new_obj.tag) new_obj.layConstraints = dict() # Graphical Layout Constraints new_obj.layConstraints['scale'] = [1.0, 1.0] else: new_obj = None self.obj72.graphObject_ = new_obj # Add node to the root: rootNode rootNode.addNode(self.obj72) self.globalAndLocalPostcondition(self.obj72, rootNode) self.obj72.postAction( rootNode.CREATE ) self.obj73=MT_pre__MetaModelElement_T(self) self.obj73.isGraphObjectVisual = True if(hasattr(self.obj73, '_setHierarchicalLink')): self.obj73._setHierarchicalLink(False) # MT_pivotOut__ self.obj73.MT_pivotOut__.setValue('') self.obj73.MT_pivotOut__.setNone() # MT_subtypeMatching__ self.obj73.MT_subtypeMatching__.setValue(('True', 1)) self.obj73.MT_subtypeMatching__.config = 0 # MT_pre__classtype self.obj73.MT_pre__classtype.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n') self.obj73.MT_pre__classtype.setHeight(15) # MT_pivotIn__ self.obj73.MT_pivotIn__.setValue('') self.obj73.MT_pivotIn__.setNone() # MT_label__ self.obj73.MT_label__.setValue('5') # MT_pre__cardinality self.obj73.MT_pre__cardinality.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n') self.obj73.MT_pre__cardinality.setHeight(15) # MT_pre__name self.obj73.MT_pre__name.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n') self.obj73.MT_pre__name.setHeight(15) self.obj73.graphClass_= graph_MT_pre__MetaModelElement_T if self.genGraphics: new_obj = graph_MT_pre__MetaModelElement_T(240.0,303.0,self.obj73) new_obj.DrawObject(self.UMLmodel) self.UMLmodel.addtag_withtag("MT_pre__MetaModelElement_T", new_obj.tag) new_obj.layConstraints = dict() # Graphical Layout Constraints new_obj.layConstraints['scale'] = [1.0, 1.0] else: new_obj = None self.obj73.graphObject_ = new_obj # Add node to the root: rootNode rootNode.addNode(self.obj73) self.globalAndLocalPostcondition(self.obj73, rootNode) self.obj73.postAction( rootNode.CREATE ) self.obj74=MT_pre__directLink_T(self) self.obj74.isGraphObjectVisual = True if(hasattr(self.obj74, '_setHierarchicalLink')): self.obj74._setHierarchicalLink(False) # MT_label__ self.obj74.MT_label__.setValue('9') # MT_pivotOut__ self.obj74.MT_pivotOut__.setValue('') self.obj74.MT_pivotOut__.setNone() # MT_subtypeMatching__ self.obj74.MT_subtypeMatching__.setValue(('True', 0)) self.obj74.MT_subtypeMatching__.config = 0 # MT_pivotIn__ self.obj74.MT_pivotIn__.setValue('') self.obj74.MT_pivotIn__.setNone() # MT_pre__associationType self.obj74.MT_pre__associationType.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n') self.obj74.MT_pre__associationType.setHeight(15) self.obj74.graphClass_= graph_MT_pre__directLink_T if self.genGraphics: new_obj = graph_MT_pre__directLink_T(358.5,317.5,self.obj74) new_obj.DrawObject(self.UMLmodel) self.UMLmodel.addtag_withtag("MT_pre__directLink_T", new_obj.tag) new_obj.layConstraints = dict() # Graphical Layout Constraints else: new_obj = None self.obj74.graphObject_ = new_obj # Add node to the root: rootNode rootNode.addNode(self.obj74) self.globalAndLocalPostcondition(self.obj74, rootNode) self.obj74.postAction( rootNode.CREATE ) self.obj75=MT_post__MetaModelElement_T(self) self.obj75.isGraphObjectVisual = True if(hasattr(self.obj75, '_setHierarchicalLink')): self.obj75._setHierarchicalLink(False) # MT_label__ self.obj75.MT_label__.setValue('3') # MT_pivotOut__ self.obj75.MT_pivotOut__.setValue('element1') # MT_post__cardinality self.obj75.MT_post__cardinality.setValue('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n') self.obj75.MT_post__cardinality.setHeight(15) # MT_post__classtype self.obj75.MT_post__classtype.setValue('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n') self.obj75.MT_post__classtype.setHeight(15) # MT_post__name self.obj75.MT_post__name.setValue('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n') self.obj75.MT_post__name.setHeight(15) self.obj75.graphClass_= graph_MT_post__MetaModelElement_T if self.genGraphics: new_obj = graph_MT_post__MetaModelElement_T(560.0,321.0,self.obj75) new_obj.DrawObject(self.UMLmodel) self.UMLmodel.addtag_withtag("MT_post__MetaModelElement_T", new_obj.tag) new_obj.layConstraints = dict() # Graphical Layout Constraints new_obj.layConstraints['scale'] = [1.0, 1.0] else: new_obj = None self.obj75.graphObject_ = new_obj # Add node to the root: rootNode rootNode.addNode(self.obj75) self.globalAndLocalPostcondition(self.obj75, rootNode) self.obj75.postAction( rootNode.CREATE ) self.obj76=MT_post__MetaModelElement_T(self) self.obj76.isGraphObjectVisual = True if(hasattr(self.obj76, '_setHierarchicalLink')): self.obj76._setHierarchicalLink(False) # MT_label__ self.obj76.MT_label__.setValue('4') # MT_pivotOut__ self.obj76.MT_pivotOut__.setValue('element2') # MT_post__cardinality self.obj76.MT_post__cardinality.setValue('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n') self.obj76.MT_post__cardinality.setHeight(15) # MT_post__classtype self.obj76.MT_post__classtype.setValue('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n') self.obj76.MT_post__classtype.setHeight(15) # MT_post__name self.obj76.MT_post__name.setValue('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n') self.obj76.MT_post__name.setHeight(15) self.obj76.graphClass_= graph_MT_post__MetaModelElement_T if self.genGraphics: new_obj = graph_MT_post__MetaModelElement_T(654.0,185.0,self.obj76) new_obj.DrawObject(self.UMLmodel) self.UMLmodel.addtag_withtag("MT_post__MetaModelElement_T", new_obj.tag) new_obj.layConstraints = dict() # Graphical Layout Constraints new_obj.layConstraints['scale'] = [1.0, 1.0] else: new_obj = None self.obj76.graphObject_ = new_obj # Add node to the root: rootNode rootNode.addNode(self.obj76) self.globalAndLocalPostcondition(self.obj76, rootNode) self.obj76.postAction( rootNode.CREATE ) self.obj77=MT_post__MetaModelElement_T(self) self.obj77.isGraphObjectVisual = True if(hasattr(self.obj77, '_setHierarchicalLink')): self.obj77._setHierarchicalLink(False) # MT_label__ self.obj77.MT_label__.setValue('5') # MT_pivotOut__ self.obj77.MT_pivotOut__.setValue('') self.obj77.MT_pivotOut__.setNone() # MT_post__cardinality self.obj77.MT_post__cardinality.setValue('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n') self.obj77.MT_post__cardinality.setHeight(15) # MT_post__classtype self.obj77.MT_post__classtype.setValue('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n') self.obj77.MT_post__classtype.setHeight(15) # MT_post__name self.obj77.MT_post__name.setValue('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n') self.obj77.MT_post__name.setHeight(15) self.obj77.graphClass_= graph_MT_post__MetaModelElement_T if self.genGraphics: new_obj = graph_MT_post__MetaModelElement_T(773.0,318.0,self.obj77) new_obj.DrawObject(self.UMLmodel) self.UMLmodel.addtag_withtag("MT_post__MetaModelElement_T", new_obj.tag) new_obj.layConstraints = dict() # Graphical Layout Constraints new_obj.layConstraints['scale'] = [1.0, 1.0] else: new_obj = None self.obj77.graphObject_ = new_obj # Add node to the root: rootNode rootNode.addNode(self.obj77) self.globalAndLocalPostcondition(self.obj77, rootNode) self.obj77.postAction( rootNode.CREATE ) self.obj78=MT_post__directLink_T(self) self.obj78.isGraphObjectVisual = True if(hasattr(self.obj78, '_setHierarchicalLink')): self.obj78._setHierarchicalLink(False) # MT_label__ self.obj78.MT_label__.setValue('19') # MT_pivotOut__ self.obj78.MT_pivotOut__.setValue('') self.obj78.MT_pivotOut__.setNone() # MT_post__associationType self.obj78.MT_post__associationType.setValue('\n#===============================================================================\n# You can access the value of the current node\'s attribute value by: attr_value.\n# If the current node shall be created you MUST initialize it here!\n# You can access a node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# Note that the attribute values are those before the match is rewritten.\n# The order in which this code is executed depends on the label value\n# of the encapsulating node.\n# The given action must return the new value of the attribute.\n#===============================================================================\n\nreturn attr_value\n') self.obj78.MT_post__associationType.setHeight(15) self.obj78.graphClass_= graph_MT_post__directLink_T if self.genGraphics: new_obj = graph_MT_post__directLink_T(834.5,392.5,self.obj78) new_obj.DrawObject(self.UMLmodel) self.UMLmodel.addtag_withtag("MT_post__directLink_T", new_obj.tag) new_obj.layConstraints = dict() # Graphical Layout Constraints else: new_obj = None self.obj78.graphObject_ = new_obj # Add node to the root: rootNode rootNode.addNode(self.obj78) self.globalAndLocalPostcondition(self.obj78, rootNode) self.obj78.postAction( rootNode.CREATE ) self.obj79=RHS(self) self.obj79.isGraphObjectVisual = True if(hasattr(self.obj79, '_setHierarchicalLink')): self.obj79._setHierarchicalLink(False) # action self.obj79.action.setValue('PostNode(\'19\')[\'associationType\'] = PostNode(\'9\')[\'associationType\']\n') self.obj79.action.setHeight(15) self.obj79.graphClass_= graph_RHS if self.genGraphics: new_obj = graph_RHS(460.0,100.0,self.obj79) new_obj.DrawObject(self.UMLmodel) self.UMLmodel.addtag_withtag("RHS", new_obj.tag) new_obj.layConstraints = dict() # Graphical Layout Constraints new_obj.layConstraints['Text Scale'] = 1.0 new_obj.layConstraints['scale'] = [1.0, 1.0] else: new_obj = None self.obj79.graphObject_ = new_obj # Add node to the root: rootNode rootNode.addNode(self.obj79) self.globalAndLocalPostcondition(self.obj79, rootNode) self.obj79.postAction( rootNode.CREATE ) self.obj80=LHS(self) self.obj80.isGraphObjectVisual = True if(hasattr(self.obj80, '_setHierarchicalLink')): self.obj80._setHierarchicalLink(False) # constraint self.obj80.constraint.setValue('return True\n') self.obj80.constraint.setHeight(15) self.obj80.graphClass_= graph_LHS if self.genGraphics: new_obj = graph_LHS(20.0,100.0,self.obj80) new_obj.DrawObject(self.UMLmodel) self.UMLmodel.addtag_withtag("LHS", new_obj.tag) new_obj.layConstraints = dict() # Graphical Layout Constraints new_obj.layConstraints['Text Scale'] = 1.0 new_obj.layConstraints['scale'] = [1.0, 1.0] else: new_obj = None self.obj80.graphObject_ = new_obj # Add node to the root: rootNode rootNode.addNode(self.obj80) self.globalAndLocalPostcondition(self.obj80, rootNode) self.obj80.postAction( rootNode.CREATE ) # Connections for obj71 (graphObject_: Obj0) of type MT_pre__MetaModelElement_T self.drawConnections( ) # Connections for obj72 (graphObject_: Obj1) of type MT_pre__MetaModelElement_T self.drawConnections( ) # Connections for obj73 (graphObject_: Obj2) of type MT_pre__MetaModelElement_T self.drawConnections( (self.obj73,self.obj74,[408.0, 376.0, 358.5, 317.5],"true", 2) ) # Connections for obj74 (graphObject_: Obj3) of type MT_pre__directLink_T self.drawConnections( (self.obj74,self.obj72,[358.5, 317.5, 309.0, 259.0],"true", 2) ) # Connections for obj75 (graphObject_: Obj4) of type MT_post__MetaModelElement_T self.drawConnections( ) # Connections for obj76 (graphObject_: Obj5) of type MT_post__MetaModelElement_T self.drawConnections( ) # Connections for obj77 (graphObject_: Obj6) of type MT_post__MetaModelElement_T self.drawConnections( (self.obj77,self.obj78,[941.0, 391.0, 834.5, 392.5],"true", 2) ) # Connections for obj78 (graphObject_: Obj7) of type MT_post__directLink_T self.drawConnections( (self.obj78,self.obj75,[834.5, 392.5, 728.0, 394.0],"true", 2) ) # Connections for obj79 (graphObject_: Obj8) of type RHS self.drawConnections( ) # Connections for obj80 (graphObject_: Obj9) of type LHS self.drawConnections( ) newfunction = move_one_input_direct_apply_diff_rules_MDL loadedMMName = ['MT_pre__GM2AUTOSAR_MM_META', 'MT_post__GM2AUTOSAR_MM_META', 'MoTifRule_META'] atom3version = '0.3'
mit
endlessm/chromium-browser
third_party/chromite/third_party/python3/httplib2/iri2uri.py
18
4153
# -*- coding: utf-8 -*- """Converts an IRI to a URI.""" __author__ = "Joe Gregorio (joe@bitworking.org)" __copyright__ = "Copyright 2006, Joe Gregorio" __contributors__ = [] __version__ = "1.0.0" __license__ = "MIT" import urllib.parse # Convert an IRI to a URI following the rules in RFC 3987 # # The characters we need to enocde and escape are defined in the spec: # # iprivate = %xE000-F8FF / %xF0000-FFFFD / %x100000-10FFFD # ucschar = %xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF # / %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD # / %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD # / %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD # / %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD # / %xD0000-DFFFD / %xE1000-EFFFD escape_range = [ (0xA0, 0xD7FF), (0xE000, 0xF8FF), (0xF900, 0xFDCF), (0xFDF0, 0xFFEF), (0x10000, 0x1FFFD), (0x20000, 0x2FFFD), (0x30000, 0x3FFFD), (0x40000, 0x4FFFD), (0x50000, 0x5FFFD), (0x60000, 0x6FFFD), (0x70000, 0x7FFFD), (0x80000, 0x8FFFD), (0x90000, 0x9FFFD), (0xA0000, 0xAFFFD), (0xB0000, 0xBFFFD), (0xC0000, 0xCFFFD), (0xD0000, 0xDFFFD), (0xE1000, 0xEFFFD), (0xF0000, 0xFFFFD), (0x100000, 0x10FFFD), ] def encode(c): retval = c i = ord(c) for low, high in escape_range: if i < low: break if i >= low and i <= high: retval = "".join(["%%%2X" % o for o in c.encode("utf-8")]) break return retval def iri2uri(uri): """Convert an IRI to a URI. Note that IRIs must be passed in a unicode strings. That is, do not utf-8 encode the IRI before passing it into the function.""" if isinstance(uri, str): (scheme, authority, path, query, fragment) = urllib.parse.urlsplit(uri) authority = authority.encode("idna").decode("utf-8") # For each character in 'ucschar' or 'iprivate' # 1. encode as utf-8 # 2. then %-encode each octet of that utf-8 uri = urllib.parse.urlunsplit((scheme, authority, path, query, fragment)) uri = "".join([encode(c) for c in uri]) return uri if __name__ == "__main__": import unittest class Test(unittest.TestCase): def test_uris(self): """Test that URIs are invariant under the transformation.""" invariant = [ "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt", "ldap://[2001:db8::7]/c=GB?objectClass?one", "mailto:John.Doe@example.com", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", ] for uri in invariant: self.assertEqual(uri, iri2uri(uri)) def test_iri(self): """Test that the right type of escaping is done for each part of the URI.""" self.assertEqual( "http://xn--o3h.com/%E2%98%84", iri2uri("http://\N{COMET}.com/\N{COMET}"), ) self.assertEqual( "http://bitworking.org/?fred=%E2%98%84", iri2uri("http://bitworking.org/?fred=\N{COMET}"), ) self.assertEqual( "http://bitworking.org/#%E2%98%84", iri2uri("http://bitworking.org/#\N{COMET}"), ) self.assertEqual("#%E2%98%84", iri2uri("#\N{COMET}")) self.assertEqual( "/fred?bar=%E2%98%9A#%E2%98%84", iri2uri("/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}"), ) self.assertEqual( "/fred?bar=%E2%98%9A#%E2%98%84", iri2uri(iri2uri("/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}")), ) self.assertNotEqual( "/fred?bar=%E2%98%9A#%E2%98%84", iri2uri( "/fred?bar=\N{BLACK LEFT POINTING INDEX}#\N{COMET}".encode("utf-8") ), ) unittest.main()
bsd-3-clause
thomasgilgenast/gilgistatus-nonrel
django/contrib/localflavor/no/forms.py
309
2761
""" Norwegian-specific Form helpers """ import re, datetime from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.translation import ugettext_lazy as _ class NOZipCodeField(RegexField): default_error_messages = { 'invalid': _('Enter a zip code in the format XXXX.'), } def __init__(self, *args, **kwargs): super(NOZipCodeField, self).__init__(r'^\d{4}$', max_length=None, min_length=None, *args, **kwargs) class NOMunicipalitySelect(Select): """ A Select widget that uses a list of Norwegian municipalities (fylker) as its choices. """ def __init__(self, attrs=None): from no_municipalities import MUNICIPALITY_CHOICES super(NOMunicipalitySelect, self).__init__(attrs, choices=MUNICIPALITY_CHOICES) class NOSocialSecurityNumber(Field): """ Algorithm is documented at http://no.wikipedia.org/wiki/Personnummer """ default_error_messages = { 'invalid': _(u'Enter a valid Norwegian social security number.'), } def clean(self, value): super(NOSocialSecurityNumber, self).clean(value) if value in EMPTY_VALUES: return u'' if not re.match(r'^\d{11}$', value): raise ValidationError(self.error_messages['invalid']) day = int(value[:2]) month = int(value[2:4]) year2 = int(value[4:6]) inum = int(value[6:9]) self.birthday = None try: if 000 <= inum < 500: self.birthday = datetime.date(1900+year2, month, day) if 500 <= inum < 750 and year2 > 54: self.birthday = datetime.date(1800+year2, month, day) if 500 <= inum < 1000 and year2 < 40: self.birthday = datetime.date(2000+year2, month, day) if 900 <= inum < 1000 and year2 > 39: self.birthday = datetime.date(1900+year2, month, day) except ValueError: raise ValidationError(self.error_messages['invalid']) sexnum = int(value[8]) if sexnum % 2 == 0: self.gender = 'F' else: self.gender = 'M' digits = map(int, list(value)) weight_1 = [3, 7, 6, 1, 8, 9, 4, 5, 2, 1, 0] weight_2 = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2, 1] def multiply_reduce(aval, bval): return sum([(a * b) for (a, b) in zip(aval, bval)]) if multiply_reduce(digits, weight_1) % 11 != 0: raise ValidationError(self.error_messages['invalid']) if multiply_reduce(digits, weight_2) % 11 != 0: raise ValidationError(self.error_messages['invalid']) return value
bsd-3-clause
tmylk/deep_q_rl
deep_q_rl/updates.py
16
4939
""" Gradient update rules for the deep_q_rl package. Some code here is modified from the Lasagne package: https://github.com/Lasagne/Lasagne/blob/master/LICENSE """ import theano import theano.tensor as T from lasagne.updates import get_or_compute_grads from collections import OrderedDict import numpy as np # The MIT License (MIT) # Copyright (c) 2014 Sander Dieleman # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # The MIT License (MIT) # Copyright (c) 2014 Sander Dieleman # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. def deepmind_rmsprop(loss_or_grads, params, learning_rate, rho, epsilon): """RMSProp updates [1]_. Scale learning rates by dividing with the moving average of the root mean squared (RMS) gradients. Parameters ---------- loss_or_grads : symbolic expression or list of expressions A scalar loss expression, or a list of gradient expressions params : list of shared variables The variables to generate update expressions for learning_rate : float or symbolic scalar The learning rate controlling the size of update steps rho : float or symbolic scalar Gradient moving average decay factor epsilon : float or symbolic scalar Small value added for numerical stability Returns ------- OrderedDict A dictionary mapping each parameter to its update expression Notes ----- `rho` should be between 0 and 1. A value of `rho` close to 1 will decay the moving average slowly and a value close to 0 will decay the moving average fast. Using the step size :math:`\\eta` and a decay factor :math:`\\rho` the learning rate :math:`\\eta_t` is calculated as: .. math:: r_t &= \\rho r_{t-1} + (1-\\rho)*g^2\\\\ \\eta_t &= \\frac{\\eta}{\\sqrt{r_t + \\epsilon}} References ---------- .. [1] Tieleman, T. and Hinton, G. (2012): Neural Networks for Machine Learning, Lecture 6.5 - rmsprop. Coursera. http://www.youtube.com/watch?v=O3sxAc4hxZU (formula @5:20) """ grads = get_or_compute_grads(loss_or_grads, params) updates = OrderedDict() for param, grad in zip(params, grads): value = param.get_value(borrow=True) acc_grad = theano.shared(np.zeros(value.shape, dtype=value.dtype), broadcastable=param.broadcastable) acc_grad_new = rho * acc_grad + (1 - rho) * grad acc_rms = theano.shared(np.zeros(value.shape, dtype=value.dtype), broadcastable=param.broadcastable) acc_rms_new = rho * acc_rms + (1 - rho) * grad ** 2 updates[acc_grad] = acc_grad_new updates[acc_rms] = acc_rms_new updates[param] = (param - learning_rate * (grad / T.sqrt(acc_rms_new - acc_grad_new **2 + epsilon))) return updates
bsd-3-clause
intervigilium/android_kernel_htc_msm7x30
tools/perf/scripts/python/futex-contention.py
11261
1486
# futex contention # (c) 2010, Arnaldo Carvalho de Melo <acme@redhat.com> # Licensed under the terms of the GNU GPL License version 2 # # Translation of: # # http://sourceware.org/systemtap/wiki/WSFutexContention # # to perf python scripting. # # Measures futex contention import os, sys sys.path.append(os.environ['PERF_EXEC_PATH'] + '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from Util import * process_names = {} thread_thislock = {} thread_blocktime = {} lock_waits = {} # long-lived stats on (tid,lock) blockage elapsed time process_names = {} # long-lived pid-to-execname mapping def syscalls__sys_enter_futex(event, ctxt, cpu, s, ns, tid, comm, nr, uaddr, op, val, utime, uaddr2, val3): cmd = op & FUTEX_CMD_MASK if cmd != FUTEX_WAIT: return # we don't care about originators of WAKE events process_names[tid] = comm thread_thislock[tid] = uaddr thread_blocktime[tid] = nsecs(s, ns) def syscalls__sys_exit_futex(event, ctxt, cpu, s, ns, tid, comm, nr, ret): if thread_blocktime.has_key(tid): elapsed = nsecs(s, ns) - thread_blocktime[tid] add_stats(lock_waits, (tid, thread_thislock[tid]), elapsed) del thread_blocktime[tid] del thread_thislock[tid] def trace_begin(): print "Press control+C to stop and show the summary" def trace_end(): for (tid, lock) in lock_waits: min, max, avg, count = lock_waits[tid, lock] print "%s[%d] lock %x contended %d times, %d avg ns" % \ (process_names[tid], tid, lock, count, avg)
gpl-2.0
stevenmjo/cloud-custodian
tests/test_report.py
3
2513
# Copyright 2016 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from dateutil.parser import parse as date_parse from c7n.reports.csvout import RECORD_TYPE_FORMATTERS from .common import load_data class TestEC2Report(unittest.TestCase): def setUp(self): data = load_data('report.json') self.records = data['ec2']['records'] self.headers = data['ec2']['headers'] self.rows = data['ec2']['rows'] for rec in self.records.values(): rec['CustodianDate'] = date_parse(rec['CustodianDate']) def test_csv(self): formatter = RECORD_TYPE_FORMATTERS.get("ec2") tests = [ (['full'], ['full']), (['minimal'], ['minimal']), (['full', 'minimal'], ['full', 'minimal']), (['full', 'duplicate', 'minimal'], ['full', 'minimal']), (['full', 'terminated', 'minimal'], ['full', 'minimal'])] for rec_ids, row_ids in tests: recs = map(lambda x: self.records[x], rec_ids) rows = map(lambda x: self.rows[x], row_ids) self.assertEqual(formatter.to_csv(recs), rows) class TestASGReport(unittest.TestCase): def setUp(self): data = load_data('report.json') self.records = data['asg']['records'] self.headers = data['asg']['headers'] self.rows = data['asg']['rows'] for rec in self.records.values(): rec['CustodianDate'] = date_parse(rec['CustodianDate']) def test_csv(self): formatter = RECORD_TYPE_FORMATTERS.get("asg") tests = [ (['full'], ['full']), (['minimal'], ['minimal']), (['full', 'minimal'], ['full', 'minimal']), (['full', 'duplicate', 'minimal'], ['full', 'minimal'])] for rec_ids, row_ids in tests: recs = map(lambda x: self.records[x], rec_ids) rows = map(lambda x: self.rows[x], row_ids) self.assertEqual(formatter.to_csv(recs), rows)
apache-2.0
kiyoto/statsmodels
statsmodels/tsa/tests/test_arima_process.py
31
4536
from statsmodels.compat.python import range import numpy as np from numpy.testing import (assert_array_almost_equal, assert_almost_equal, assert_equal) from statsmodels.tsa.arima_process import (arma_generate_sample, arma_acovf, arma_acf, arma_impulse_response, lpol_fiar, lpol_fima) from statsmodels.sandbox.tsa.fftarma import ArmaFft from .results.results_process import armarep #benchmarkdata arlist = [[1.], [1, -0.9], #ma representation will need many terms to get high precision [1, 0.9], [1, -0.9, 0.3]] malist = [[1.], [1, 0.9], [1, -0.9], [1, 0.9, -0.3]] def test_arma_acovf(): # Check for specific AR(1) N = 20; phi = 0.9; sigma = 1; # rep 1: from module function rep1 = arma_acovf([1, -phi], [1], N); # rep 2: manually rep2 = [1.*sigma*phi**i/(1-phi**2) for i in range(N)]; assert_almost_equal(rep1, rep2, 7); # 7 is max precision here def test_arma_acf(): # Check for specific AR(1) N = 20; phi = 0.9; sigma = 1; # rep 1: from module function rep1 = arma_acf([1, -phi], [1], N); # rep 2: manually acovf = np.array([1.*sigma*phi**i/(1-phi**2) for i in range(N)]) rep2 = acovf / (1./(1-phi**2)); assert_almost_equal(rep1, rep2, 8); # 8 is max precision here def _manual_arma_generate_sample(ar, ma, eta): T = len(eta); ar = ar[::-1]; ma = ma[::-1]; p,q = len(ar), len(ma); rep2 = [0]*max(p,q); # initialize with zeroes for t in range(T): yt = eta[t]; if p: yt += np.dot(rep2[-p:], ar); if q: # left pad shocks with zeros yt += np.dot([0]*(q-t) + list(eta[max(0,t-q):t]), ma); rep2.append(yt); return np.array(rep2[max(p,q):]); def test_arma_generate_sample(): # Test that this generates a true ARMA process # (amounts to just a test that scipy.signal.lfilter does what we want) T = 100; dists = [np.random.randn] for dist in dists: np.random.seed(1234); eta = dist(T); for ar in arlist: for ma in malist: # rep1: from module function np.random.seed(1234); rep1 = arma_generate_sample(ar, ma, T, distrvs=dist); # rep2: "manually" create the ARMA process ar_params = -1*np.array(ar[1:]); ma_params = np.array(ma[1:]); rep2 = _manual_arma_generate_sample(ar_params, ma_params, eta) assert_array_almost_equal(rep1, rep2, 13); def test_fi(): #test identity of ma and ar representation of fi lag polynomial n = 100 mafromar = arma_impulse_response(lpol_fiar(0.4, n=n), [1], n) assert_array_almost_equal(mafromar, lpol_fima(0.4, n=n), 13) def test_arma_impulse_response(): arrep = arma_impulse_response(armarep.ma, armarep.ar, nobs=21)[1:] marep = arma_impulse_response(armarep.ar, armarep.ma, nobs=21)[1:] assert_array_almost_equal(armarep.marep.ravel(), marep, 14) #difference in sign convention to matlab for AR term assert_array_almost_equal(-armarep.arrep.ravel(), arrep, 14) def test_spectrum(): nfreq = 20 w = np.linspace(0, np.pi, nfreq, endpoint=False) for ar in arlist: for ma in malist: arma = ArmaFft(ar, ma, 20) spdr, wr = arma.spdroots(w) spdp, wp = arma.spdpoly(w, 200) spdd, wd = arma.spddirect(nfreq*2) assert_equal(w, wr) assert_equal(w, wp) assert_almost_equal(w, wd[:nfreq], decimal=14) assert_almost_equal(spdr, spdp, decimal=7, err_msg='spdr spdp not equal for %s, %s' % (ar, ma)) assert_almost_equal(spdr, spdd[:nfreq], decimal=7, err_msg='spdr spdd not equal for %s, %s' % (ar, ma)) def test_armafft(): #test other methods nfreq = 20 w = np.linspace(0, np.pi, nfreq, endpoint=False) for ar in arlist: for ma in malist: arma = ArmaFft(ar, ma, 20) ac1 = arma.invpowerspd(1024)[:10] ac2 = arma.acovf(10)[:10] assert_almost_equal(ac1, ac2, decimal=7, err_msg='acovf not equal for %s, %s' % (ar, ma)) if __name__ == '__main__': test_arma_acovf() test_arma_acf() test_arma_generate_sample() test_fi() test_arma_impulse_response() test_spectrum() test_armafft()
bsd-3-clause
antepsis/anteplahmacun
sympy/matrices/matrices.py
1
143503
from __future__ import print_function, division import collections from sympy.core.add import Add from sympy.core.basic import Basic, Atom from sympy.core.expr import Expr from sympy.core.function import count_ops from sympy.core.logic import fuzzy_and from sympy.core.power import Pow from sympy.core.symbol import Symbol, Dummy, symbols from sympy.core.numbers import Integer, ilcm, Float from sympy.core.singleton import S from sympy.core.sympify import sympify from sympy.core.compatibility import is_sequence, default_sort_key, range, NotIterable from sympy.polys import PurePoly, roots, cancel, gcd from sympy.simplify import simplify as _simplify, signsimp, nsimplify from sympy.utilities.iterables import flatten, numbered_symbols from sympy.functions.elementary.miscellaneous import sqrt, Max, Min from sympy.functions import exp, factorial from sympy.printing import sstr from sympy.core.compatibility import reduce, as_int, string_types from sympy.assumptions.refine import refine from types import FunctionType def _iszero(x): """Returns True if x is zero.""" return x.is_zero class MatrixError(Exception): pass class ShapeError(ValueError, MatrixError): """Wrong matrix shape""" pass class NonSquareMatrixError(ShapeError): pass class DeferredVector(Symbol, NotIterable): """A vector whose components are deferred (e.g. for use with lambdify) Examples ======== >>> from sympy import DeferredVector, lambdify >>> X = DeferredVector( 'X' ) >>> X X >>> expr = (X[0] + 2, X[2] + 3) >>> func = lambdify( X, expr) >>> func( [1, 2, 3] ) (3, 6) """ def __getitem__(self, i): if i == -0: i = 0 if i < 0: raise IndexError('DeferredVector index out of range') component_name = '%s[%d]' % (self.name, i) return Symbol(component_name) def __str__(self): return sstr(self) def __repr__(self): return "DeferredVector('%s')" % (self.name) class MatrixBase(object): # Added just for numpy compatibility __array_priority__ = 11 is_Matrix = True is_Identity = None _class_priority = 3 _sympify = staticmethod(sympify) __hash__ = None # Mutable def __add__(self, other): """Return self + other, raising ShapeError if shapes don't match.""" if getattr(other, 'is_Matrix', False): A = self B = other if A.shape != B.shape: raise ShapeError("Matrix size mismatch: %s + %s" % ( A.shape, B.shape)) alst = A.tolist() blst = B.tolist() ret = [S.Zero]*A.rows for i in range(A.shape[0]): ret[i] = [j + k for j, k in zip(alst[i], blst[i])] rv = classof(A, B)._new(ret) if 0 in A.shape: rv = rv.reshape(*A.shape) return rv raise TypeError('cannot add matrix and %s' % type(other)) def __array__(self): from .dense import matrix2numpy return matrix2numpy(self) def __div__(self, other): return self*(S.One / other) def __getattr__(self, attr): if attr in ('diff', 'integrate', 'limit'): def doit(*args): item_doit = lambda item: getattr(item, attr)(*args) return self.applyfunc(item_doit) return doit else: raise AttributeError( "%s has no attribute %s." % (self.__class__.__name__, attr)) def __len__(self): """Return the number of elements of self. Implemented mainly so bool(Matrix()) == False. """ return self.rows*self.cols def __mathml__(self): mml = "" for i in range(self.rows): mml += "<matrixrow>" for j in range(self.cols): mml += self[i, j].__mathml__() mml += "</matrixrow>" return "<matrix>" + mml + "</matrix>" def __mul__(self, other): """Return self*other where other is either a scalar or a matrix of compatible dimensions. Examples ======== >>> from sympy.matrices import Matrix >>> A = Matrix([[1, 2, 3], [4, 5, 6]]) >>> 2*A == A*2 == Matrix([[2, 4, 6], [8, 10, 12]]) True >>> B = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> A*B Matrix([ [30, 36, 42], [66, 81, 96]]) >>> B*A Traceback (most recent call last): ... ShapeError: Matrices size mismatch. >>> See Also ======== matrix_multiply_elementwise """ if getattr(other, 'is_Matrix', False): A = self B = other if A.cols != B.rows: raise ShapeError("Matrix size mismatch: %s * %s." % ( A.shape, B.shape)) if A.cols == 0: return classof(A, B)._new(A.rows, B.cols, lambda i, j: 0) try: blst = B.T.tolist() except AttributeError: # If B is a MatrixSymbol, B.T.tolist does not exist return NotImplemented alst = A.tolist() return classof(A, B)._new(A.rows, B.cols, lambda i, j: reduce(lambda k, l: k + l, [a_ik * b_kj for a_ik, b_kj in zip(alst[i], blst[j])])) else: return self._new(self.rows, self.cols, [i*other for i in self._mat]) def __neg__(self): return -1*self def __pow__(self, num): from sympy.matrices import eye, diag, MutableMatrix from sympy import binomial if not self.is_square: raise NonSquareMatrixError() if isinstance(num, int) or isinstance(num, Integer): n = int(num) if n < 0: return self.inv()**-n # A**-2 = (A**-1)**2 a = eye(self.cols) s = self while n: if n % 2: a *= s n -= 1 if not n: break s *= s n //= 2 return self._new(a) elif isinstance(num, (Expr, float)): def jordan_cell_power(jc, n): N = jc.shape[0] l = jc[0, 0] for i in range(N): for j in range(N-i): bn = binomial(n, i) if isinstance(bn, binomial): bn = bn._eval_expand_func() jc[j, i+j] = l**(n-i)*bn P, jordan_cells = self.jordan_cells() # Make sure jordan_cells matrices are mutable: jordan_cells = [MutableMatrix(j) for j in jordan_cells] for j in jordan_cells: jordan_cell_power(j, num) return self._new(P*diag(*jordan_cells)*P.inv()) else: raise TypeError( "Only SymPy expressions or int objects are supported as exponent for matrices") def __radd__(self, other): return self + other def __repr__(self): return sstr(self) def __rmul__(self, a): if getattr(a, 'is_Matrix', False): return self._new(a)*self return self._new(self.rows, self.cols, [a*i for i in self._mat]) def __rsub__(self, a): return (-self) + a def __str__(self): if self.rows == 0 or self.cols == 0: return 'Matrix(%s, %s, [])' % (self.rows, self.cols) return "Matrix(%s)" % str(self.tolist()) def __sub__(self, a): return self + (-a) def __truediv__(self, other): return self.__div__(other) def _diagonalize_clear_subproducts(self): del self._is_symbolic del self._is_symmetric del self._eigenvects def _format_str(self, printer=None): if not printer: from sympy.printing.str import StrPrinter printer = StrPrinter() # Handle zero dimensions: if self.rows == 0 or self.cols == 0: return 'Matrix(%s, %s, [])' % (self.rows, self.cols) if self.rows == 1: return "Matrix([%s])" % self.table(printer, rowsep=',\n') return "Matrix([\n%s])" % self.table(printer, rowsep=',\n') @classmethod def _handle_creation_inputs(cls, *args, **kwargs): """Return the number of rows, cols and flat matrix elements. Examples ======== >>> from sympy import Matrix, I Matrix can be constructed as follows: * from a nested list of iterables >>> Matrix( ((1, 2+I), (3, 4)) ) Matrix([ [1, 2 + I], [3, 4]]) * from un-nested iterable (interpreted as a column) >>> Matrix( [1, 2] ) Matrix([ [1], [2]]) * from un-nested iterable with dimensions >>> Matrix(1, 2, [1, 2] ) Matrix([[1, 2]]) * from no arguments (a 0 x 0 matrix) >>> Matrix() Matrix(0, 0, []) * from a rule >>> Matrix(2, 2, lambda i, j: i/(j + 1) ) Matrix([ [0, 0], [1, 1/2]]) """ from sympy.matrices.sparse import SparseMatrix flat_list = None if len(args) == 1: # Matrix(SparseMatrix(...)) if isinstance(args[0], SparseMatrix): return args[0].rows, args[0].cols, flatten(args[0].tolist()) # Matrix(Matrix(...)) elif isinstance(args[0], MatrixBase): return args[0].rows, args[0].cols, args[0]._mat # Matrix(MatrixSymbol('X', 2, 2)) elif isinstance(args[0], Basic) and args[0].is_Matrix: return args[0].rows, args[0].cols, args[0].as_explicit()._mat # Matrix(numpy.ones((2, 2))) elif hasattr(args[0], "__array__"): # NumPy array or matrix or some other object that implements # __array__. So let's first use this method to get a # numpy.array() and then make a python list out of it. arr = args[0].__array__() if len(arr.shape) == 2: rows, cols = arr.shape[0], arr.shape[1] flat_list = [cls._sympify(i) for i in arr.ravel()] return rows, cols, flat_list elif len(arr.shape) == 1: rows, cols = arr.shape[0], 1 flat_list = [S.Zero]*rows for i in range(len(arr)): flat_list[i] = cls._sympify(arr[i]) return rows, cols, flat_list else: raise NotImplementedError( "SymPy supports just 1D and 2D matrices") # Matrix([1, 2, 3]) or Matrix([[1, 2], [3, 4]]) elif is_sequence(args[0])\ and not isinstance(args[0], DeferredVector): in_mat = [] ncol = set() for row in args[0]: if isinstance(row, MatrixBase): in_mat.extend(row.tolist()) if row.cols or row.rows: # only pay attention if it's not 0x0 ncol.add(row.cols) else: in_mat.append(row) try: ncol.add(len(row)) except TypeError: ncol.add(1) if len(ncol) > 1: raise ValueError("Got rows of variable lengths: %s" % sorted(list(ncol))) cols = ncol.pop() if ncol else 0 rows = len(in_mat) if cols else 0 if rows: if not is_sequence(in_mat[0]): cols = 1 flat_list = [cls._sympify(i) for i in in_mat] return rows, cols, flat_list flat_list = [] for j in range(rows): for i in range(cols): flat_list.append(cls._sympify(in_mat[j][i])) elif len(args) == 3: rows = as_int(args[0]) cols = as_int(args[1]) # Matrix(2, 2, lambda i, j: i+j) if len(args) == 3 and isinstance(args[2], collections.Callable): op = args[2] flat_list = [] for i in range(rows): flat_list.extend( [cls._sympify(op(cls._sympify(i), cls._sympify(j))) for j in range(cols)]) # Matrix(2, 2, [1, 2, 3, 4]) elif len(args) == 3 and is_sequence(args[2]): flat_list = args[2] if len(flat_list) != rows*cols: raise ValueError('List length should be equal to rows*columns') flat_list = [cls._sympify(i) for i in flat_list] # Matrix() elif len(args) == 0: # Empty Matrix rows = cols = 0 flat_list = [] if flat_list is None: raise TypeError("Data type not understood") return rows, cols, flat_list def _jordan_block_structure(self): # To every eigenvalue may belong `i` blocks with size s(i) # and a chain of generalized eigenvectors # which will be determined by the following computations: # for every eigenvalue we will add a dictionary # containing, for all blocks, the blocksizes and the attached chain vectors # that will eventually be used to form the transformation P jordan_block_structures = {} _eigenvects = self.eigenvects() ev = self.eigenvals() if len(ev) == 0: raise AttributeError("could not compute the eigenvalues") for eigenval, multiplicity, vects in _eigenvects: l_jordan_chains={} geometrical = len(vects) if geometrical == multiplicity: # The Jordan chains have all length 1 and consist of only one vector # which is the eigenvector of course chains = [] for v in vects: chain=[v] chains.append(chain) l_jordan_chains[1] = chains jordan_block_structures[eigenval] = l_jordan_chains elif geometrical == 0: raise MatrixError("Matrix has the eigen vector with geometrical multiplicity equal zero.") else: # Up to now we know nothing about the sizes of the blocks of our Jordan matrix. # Note that knowledge of algebraic and geometrical multiplicity # will *NOT* be sufficient to determine this structure. # The blocksize `s` could be defined as the minimal `k` where # `kernel(self-lI)^k = kernel(self-lI)^(k+1)` # The extreme case would be that k = (multiplicity-geometrical+1) # but the blocks could be smaller. # Consider for instance the following matrix # [2 1 0 0] # [0 2 1 0] # [0 0 2 0] # [0 0 0 2] # which coincides with it own Jordan canonical form. # It has only one eigenvalue l=2 of (algebraic) multiplicity=4. # It has two eigenvectors, one belonging to the last row (blocksize 1) # and one being the last part of a jordan chain of length 3 (blocksize of the first block). # Note again that it is not not possible to obtain this from the algebraic and geometrical # multiplicity alone. This only gives us an upper limit for the dimension of one of # the subspaces (blocksize of according jordan block) given by # max=(multiplicity-geometrical+1) which is reached for our matrix # but not for # [2 1 0 0] # [0 2 0 0] # [0 0 2 1] # [0 0 0 2] # although multiplicity=4 and geometrical=2 are the same for this matrix. from sympy.matrices import MutableMatrix I = MutableMatrix.eye(self.rows) l = eigenval M = (self-l*I) # We will store the matrices `(self-l*I)^k` for further computations # for convenience only we store `Ms[0]=(sefl-lI)^0=I` # so the index is the same as the power for all further Ms entries # We also store the vectors that span these kernels (Ns[0] = []) # and also their dimensions `a_s` # this is mainly done for debugging since the number of blocks of a given size # can be computed from the a_s, in order to check our result which is obtained simpler # by counting the number of Jordan chains for `a` given `s` # `a_0` is `dim(Kernel(Ms[0]) = dim (Kernel(I)) = 0` since `I` is regular l_jordan_chains={} Ms = [I] Ns = [[]] a = [0] smax = 0 M_new = Ms[-1]*M Ns_new = M_new.nullspace() a_new = len(Ns_new) Ms.append(M_new) Ns.append(Ns_new) while a_new > a[-1]: # as long as the nullspaces increase compute further powers a.append(a_new) M_new = Ms[-1]*M Ns_new = M_new.nullspace() a_new=len(Ns_new) Ms.append(M_new) Ns.append(Ns_new) smax += 1 # We now have `Ms[-1]=((self-l*I)**s)=Z=0`. # We also know the size of the biggest Jordan block # associated with `l` to be `s`. # Now let us proceed with the computation of the associate part of the transformation matrix `P`. # We already know the kernel (=nullspace) `K_l` of (self-lI) which consists of the # eigenvectors belonging to eigenvalue `l`. # The dimension of this space is the geometric multiplicity of eigenvalue `l`. # For every eigenvector ev out of `K_l`, there exists a subspace that is # spanned by the Jordan chain of ev. The dimension of this subspace is # represented by the length `s` of the Jordan block. # The chain itself is given by `{e_0,..,e_s-1}` where: # `e_k+1 =(self-lI)e_k (*)` # and # `e_s-1=ev` # So it would be possible to start with the already known `ev` and work backwards until one # reaches `e_0`. Unfortunately this can not be done by simply solving system (*) since its matrix # is singular (by definition of the eigenspaces). # This approach would force us a choose in every step the degree of freedom undetermined # by (*). This is difficult to implement with computer algebra systems and also quite inefficient. # We therefore reformulate the problem in terms of nullspaces. # To do so we start from the other end and choose `e0`'s out of # `E=Kernel(self-lI)^s / Kernel(self-lI)^(s-1)` # Note that `Kernel(self-lI)^s = Kernel(Z) = V` (the whole vector space). # So in the first step `s=smax` this restriction turns out to actually restrict nothing at all # and the only remaining condition is to choose vectors in `Kernel(self-lI)^(s-1)`. # Subsequently we compute `e_1=(self-lI)e_0`, `e_2=(self-lI)*e_1` and so on. # The subspace `E` can have a dimension larger than one. # That means that we have more than one Jordan block of size `s` for the eigenvalue `l` # and as many Jordan chains (this is the case in the second example). # In this case we start as many Jordan chains and have as many blocks of size `s` in the jcf. # We now have all the Jordan blocks of size `s` but there might be others attached to the same # eigenvalue that are smaller. # So we will do the same procedure also for `s-1` and so on until 1 (the lowest possible order # where the Jordan chain is of length 1 and just represented by the eigenvector). for s in reversed(range(1, smax+1)): S = Ms[s] # We want the vectors in `Kernel((self-lI)^s)`, # but without those in `Kernel(self-lI)^s-1` # so we will add their adjoints as additional equations # to the system formed by `S` to get the orthogonal # complement. # (`S` will no longer be quadratic.) exclude_vectors = Ns[s-1] for k in range(0, a[s-1]): S = S.col_join((exclude_vectors[k]).adjoint()) # We also want to exclude the vectors # in the chains for the bigger blocks # that we have already computed (if there are any). # (That is why we start with the biggest s). # Since Jordan blocks are not orthogonal in general # (in the original space), only those chain vectors # that are on level s (index `s-1` in a chain) # are added. for chain_list in l_jordan_chains.values(): for chain in chain_list: S = S.col_join(chain[s-1].adjoint()) e0s = S.nullspace() # Determine the number of chain leaders # for blocks of size `s`. n_e0 = len(e0s) s_chains = [] # s_cells=[] for i in range(0, n_e0): chain=[e0s[i]] for k in range(1, s): v = M*chain[k-1] chain.append(v) # We want the chain leader appear as the last of the block. chain.reverse() s_chains.append(chain) l_jordan_chains[s] = s_chains jordan_block_structures[eigenval] = l_jordan_chains return jordan_block_structures def _jordan_split(self, algebraical, geometrical): """Return a list of integers with sum equal to 'algebraical' and length equal to 'geometrical'""" n1 = algebraical // geometrical res = [n1]*geometrical res[len(res) - 1] += algebraical % geometrical assert sum(res) == algebraical return res def _setitem(self, key, value): """Helper to set value at location given by key. Examples ======== >>> from sympy import Matrix, I, zeros, ones >>> m = Matrix(((1, 2+I), (3, 4))) >>> m Matrix([ [1, 2 + I], [3, 4]]) >>> m[1, 0] = 9 >>> m Matrix([ [1, 2 + I], [9, 4]]) >>> m[1, 0] = [[0, 1]] To replace row r you assign to position r*m where m is the number of columns: >>> M = zeros(4) >>> m = M.cols >>> M[3*m] = ones(1, m)*2; M Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 2, 2]]) And to replace column c you can assign to position c: >>> M[2] = ones(m, 1)*4; M Matrix([ [0, 0, 4, 0], [0, 0, 4, 0], [0, 0, 4, 0], [2, 2, 4, 2]]) """ from .dense import Matrix is_slice = isinstance(key, slice) i, j = key = self.key2ij(key) is_mat = isinstance(value, MatrixBase) if type(i) is slice or type(j) is slice: if is_mat: self.copyin_matrix(key, value) return if not isinstance(value, Expr) and is_sequence(value): self.copyin_list(key, value) return raise ValueError('unexpected value: %s' % value) else: if (not is_mat and not isinstance(value, Basic) and is_sequence(value)): value = Matrix(value) is_mat = True if is_mat: if is_slice: key = (slice(*divmod(i, self.cols)), slice(*divmod(j, self.cols))) else: key = (slice(i, i + value.rows), slice(j, j + value.cols)) self.copyin_matrix(key, value) else: return i, j, self._sympify(value) return def add(self, b): """Return self + b """ return self + b def adjoint(self): """Conjugate transpose or Hermitian conjugation.""" return self.T.C def adjugate(self, method="berkowitz"): """Returns the adjugate matrix. Adjugate matrix is the transpose of the cofactor matrix. http://en.wikipedia.org/wiki/Adjugate See Also ======== cofactorMatrix transpose berkowitz """ return self.cofactorMatrix(method).T def atoms(self, *types): """Returns the atoms that form the current object. Examples ======== >>> from sympy.abc import x, y >>> from sympy.matrices import Matrix >>> Matrix([[x]]) Matrix([[x]]) >>> _.atoms() set([x]) """ if types: types = tuple( [t if isinstance(t, type) else type(t) for t in types]) else: types = (Atom,) result = set() for i in self: result.update( i.atoms(*types) ) return result def berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_simplify): """Computes characteristic polynomial minors using Berkowitz method. A PurePoly is returned so using different variables for ``x`` does not affect the comparison or the polynomials: Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y >>> A = Matrix([[1, 3], [2, 0]]) >>> A.berkowitz_charpoly(x) == A.berkowitz_charpoly(y) True Specifying ``x`` is optional; a Dummy with name ``lambda`` is used by default (which looks good when pretty-printed in unicode): >>> A.berkowitz_charpoly().as_expr() _lambda**2 - _lambda - 6 No test is done to see that ``x`` doesn't clash with an existing symbol, so using the default (``lambda``) or your own Dummy symbol is the safest option: >>> A = Matrix([[1, 2], [x, 0]]) >>> A.charpoly().as_expr() _lambda**2 - _lambda - 2*x >>> A.charpoly(x).as_expr() x**2 - 3*x See Also ======== berkowitz """ return PurePoly(list(map(simplify, self.berkowitz()[-1])), x) def berkowitz_det(self): """Computes determinant using Berkowitz method. See Also ======== det berkowitz """ if not self.is_square: raise NonSquareMatrixError() if not self: return S.One poly = self.berkowitz()[-1] sign = (-1)**(len(poly) - 1) return sign*poly[-1] def berkowitz_eigenvals(self, **flags): """Computes eigenvalues of a Matrix using Berkowitz method. See Also ======== berkowitz """ return roots(self.berkowitz_charpoly(Dummy('x')), **flags) def berkowitz_minors(self): """Computes principal minors using Berkowitz method. See Also ======== berkowitz """ sign, minors = S.One, [] for poly in self.berkowitz(): minors.append(sign*poly[-1]) sign = -sign return tuple(minors) def berkowitz(self): """The Berkowitz algorithm. Given N x N matrix with symbolic content, compute efficiently coefficients of characteristic polynomials of 'self' and all its square sub-matrices composed by removing both i-th row and column, without division in the ground domain. This method is particularly useful for computing determinant, principal minors and characteristic polynomial, when 'self' has complicated coefficients e.g. polynomials. Semi-direct usage of this algorithm is also important in computing efficiently sub-resultant PRS. Assuming that M is a square matrix of dimension N x N and I is N x N identity matrix, then the following following definition of characteristic polynomial is begin used: charpoly(M) = det(t*I - M) As a consequence, all polynomials generated by Berkowitz algorithm are monic. >>> from sympy import Matrix >>> from sympy.abc import x, y, z >>> M = Matrix([[x, y, z], [1, 0, 0], [y, z, x]]) >>> p, q, r, s = M.berkowitz() >>> p # 0 x 0 M's sub-matrix (1,) >>> q # 1 x 1 M's sub-matrix (1, -x) >>> r # 2 x 2 M's sub-matrix (1, -x, -y) >>> s # 3 x 3 M's sub-matrix (1, -2*x, x**2 - y*z - y, x*y - z**2) For more information on the implemented algorithm refer to: [1] S.J. Berkowitz, On computing the determinant in small parallel time using a small number of processors, ACM, Information Processing Letters 18, 1984, pp. 147-150 [2] M. Keber, Division-Free computation of sub-resultants using Bezout matrices, Tech. Report MPI-I-2006-1-006, Saarbrucken, 2006 See Also ======== berkowitz_det berkowitz_minors berkowitz_charpoly berkowitz_eigenvals """ from sympy.matrices import zeros berk = ((1,),) if not self: return berk if not self.is_square: raise NonSquareMatrixError() A, N = self, self.rows transforms = [0]*(N - 1) for n in range(N, 1, -1): T, k = zeros(n + 1, n), n - 1 R, C = -A[k, :k], A[:k, k] A, a = A[:k, :k], -A[k, k] items = [C] for i in range(0, n - 2): items.append(A*items[i]) for i, B in enumerate(items): items[i] = (R*B)[0, 0] items = [S.One, a] + items for i in range(n): T[i:, i] = items[:n - i + 1] transforms[k - 1] = T polys = [self._new([S.One, -A[0, 0]])] for i, T in enumerate(transforms): polys.append(T*polys[i]) return berk + tuple(map(tuple, polys)) def cholesky_solve(self, rhs): """Solves Ax = B using Cholesky decomposition, for a general square non-singular matrix. For a non-square matrix with rows > cols, the least squares solution is returned. See Also ======== lower_triangular_solve upper_triangular_solve gauss_jordan_solve diagonal_solve LDLsolve LUsolve QRsolve pinv_solve """ if self.is_symmetric(): L = self._cholesky() elif self.rows >= self.cols: L = (self.T*self)._cholesky() rhs = self.T*rhs else: raise NotImplementedError('Under-determined System. ' 'Try M.gauss_jordan_solve(rhs)') Y = L._lower_triangular_solve(rhs) return (L.T)._upper_triangular_solve(Y) def cholesky(self): """Returns the Cholesky decomposition L of a matrix A such that L * L.T = A A must be a square, symmetric, positive-definite and non-singular matrix. Examples ======== >>> from sympy.matrices import Matrix >>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) >>> A.cholesky() Matrix([ [ 5, 0, 0], [ 3, 3, 0], [-1, 1, 3]]) >>> A.cholesky() * A.cholesky().T Matrix([ [25, 15, -5], [15, 18, 0], [-5, 0, 11]]) See Also ======== LDLdecomposition LUdecomposition QRdecomposition """ if not self.is_square: raise NonSquareMatrixError("Matrix must be square.") if not self.is_symmetric(): raise ValueError("Matrix must be symmetric.") return self._cholesky() def cofactor(self, i, j, method="berkowitz"): """Calculate the cofactor of an element. See Also ======== cofactorMatrix minorEntry minorMatrix """ if (i + j) % 2 == 0: return self.minorEntry(i, j, method) else: return -1*self.minorEntry(i, j, method) def cofactorMatrix(self, method="berkowitz"): """Return a matrix containing the cofactor of each element. See Also ======== cofactor minorEntry minorMatrix adjugate """ out = self._new(self.rows, self.cols, lambda i, j: self.cofactor(i, j, method)) return out def col_insert(self, pos, mti): """Insert one or more columns at the given column position. Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(3, 1) >>> M.col_insert(1, V) Matrix([ [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]]) See Also ======== col row_insert """ from sympy.matrices import MutableMatrix # Allows you to build a matrix even if it is null matrix if not self: return type(self)(mti) if pos == 0: return mti.row_join(self) elif pos < 0: pos = self.cols + pos if pos < 0: pos = 0 elif pos > self.cols: pos = self.cols if self.rows != mti.rows: raise ShapeError("self and mti must have the same number of rows.") newmat = MutableMatrix.zeros(self.rows, self.cols + mti.cols) i, j = pos, pos + mti.cols newmat[:, :i] = self[:, :i] newmat[:, i:j] = mti newmat[:, j:] = self[:, i:] return type(self)(newmat) def col_join(self, bott): """Concatenates two matrices along self's last and bott's first row Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(1, 3) >>> M.col_join(V) Matrix([ [0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 1, 1]]) See Also ======== col row_join """ from sympy.matrices import MutableMatrix # Allows you to build a matrix even if it is null matrix if not self: return type(self)(bott) if self.cols != bott.cols: raise ShapeError( "`self` and `bott` must have the same number of columns.") newmat = MutableMatrix.zeros(self.rows + bott.rows, self.cols) newmat[:self.rows, :] = self newmat[self.rows:, :] = bott return type(self)(newmat) def columnspace(self, simplify=False): """Returns list of vectors (Matrix objects) that span columnspace of self Examples ======== >>> from sympy.matrices import Matrix >>> m = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6]) >>> m Matrix([ [ 1, 3, 0], [-2, -6, 0], [ 3, 9, 6]]) >>> m.columnspace() [Matrix([ [ 1], [-2], [ 3]]), Matrix([ [0], [0], [6]])] See Also ======== nullspace """ simpfunc = simplify if isinstance( simplify, FunctionType) else _simplify reduced, pivots = self.rref(simplify=simpfunc) basis = [] # create a set of vectors for the basis for i in range(self.cols): if i in pivots: basis.append(self.col(i)) return [self._new(b) for b in basis] def condition_number(self): """Returns the condition number of a matrix. This is the maximum singular value divided by the minimum singular value Examples ======== >>> from sympy import Matrix, S >>> A = Matrix([[1, 0, 0], [0, 10, 0], [0, 0, S.One/10]]) >>> A.condition_number() 100 See Also ======== singular_values """ if not self: return S.Zero singularvalues = self.singular_values() return Max(*singularvalues) / Min(*singularvalues) def conjugate(self): """ Returns the conjugate of the matrix.""" return self._eval_conjugate() def copy(self): """ Returns the copy of a matrix. Examples ======== >>> from sympy import Matrix >>> A = Matrix(2, 2, [1, 2, 3, 4]) >>> A.copy() Matrix([ [1, 2], [3, 4]]) """ return self._new(self.rows, self.cols, self._mat) def cross(self, b): """Return the cross product of `self` and `b` relaxing the condition of compatible dimensions: if each has 3 elements, a matrix of the same type and shape as `self` will be returned. If `b` has the same shape as `self` then common identities for the cross product (like `a x b = - b x a`) will hold. See Also ======== dot multiply multiply_elementwise """ if not is_sequence(b): raise TypeError("`b` must be an ordered iterable or Matrix, not %s." % type(b)) if not (self.rows * self.cols == b.rows * b.cols == 3): raise ShapeError("Dimensions incorrect for cross product: %s x %s" % ((self.rows, self.cols), (b.rows, b.cols))) else: return self._new(self.rows, self.cols, ( (self[1]*b[2] - self[2]*b[1]), (self[2]*b[0] - self[0]*b[2]), (self[0]*b[1] - self[1]*b[0]))) @property def D(self): """Return Dirac conjugate (if self.rows == 4). Examples ======== >>> from sympy import Matrix, I, eye >>> m = Matrix((0, 1 + I, 2, 3)) >>> m.D Matrix([[0, 1 - I, -2, -3]]) >>> m = (eye(4) + I*eye(4)) >>> m[0, 3] = 2 >>> m.D Matrix([ [1 - I, 0, 0, 0], [ 0, 1 - I, 0, 0], [ 0, 0, -1 + I, 0], [ 2, 0, 0, -1 + I]]) If the matrix does not have 4 rows an AttributeError will be raised because this property is only defined for matrices with 4 rows. >>> Matrix(eye(2)).D Traceback (most recent call last): ... AttributeError: Matrix has no attribute D. See Also ======== conjugate: By-element conjugation H: Hermite conjugation """ from sympy.physics.matrices import mgamma if self.rows != 4: # In Python 3.2, properties can only return an AttributeError # so we can't raise a ShapeError -- see commit which added the # first line of this inline comment. Also, there is no need # for a message since MatrixBase will raise the AttributeError raise AttributeError return self.H*mgamma(0) def det_bareis(self): """Compute matrix determinant using Bareis' fraction-free algorithm which is an extension of the well known Gaussian elimination method. This approach is best suited for dense symbolic matrices and will result in a determinant with minimal number of fractions. It means that less term rewriting is needed on resulting formulae. TODO: Implement algorithm for sparse matrices (SFF), http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps. See Also ======== det berkowitz_det """ if not self.is_square: raise NonSquareMatrixError() if not self: return S.One M, n = self.copy().as_mutable(), self.rows if n == 1: det = M[0, 0] elif n == 2: det = M[0, 0]*M[1, 1] - M[0, 1]*M[1, 0] elif n == 3: det = (M[0, 0]*M[1, 1]*M[2, 2] + M[0, 1]*M[1, 2]*M[2, 0] + M[0, 2]*M[1, 0]*M[2, 1]) - \ (M[0, 2]*M[1, 1]*M[2, 0] + M[0, 0]*M[1, 2]*M[2, 1] + M[0, 1]*M[1, 0]*M[2, 2]) else: sign = 1 # track current sign in case of column swap for k in range(n - 1): # look for a pivot in the current column # and assume det == 0 if none is found if M[k, k] == 0: for i in range(k + 1, n): if M[i, k]: M.row_swap(i, k) sign *= -1 break else: return S.Zero # proceed with Bareis' fraction-free (FF) # form of Gaussian elimination algorithm for i in range(k + 1, n): for j in range(k + 1, n): D = M[k, k]*M[i, j] - M[i, k]*M[k, j] if k > 0: D /= M[k - 1, k - 1] if D.is_Atom: M[i, j] = D else: M[i, j] = cancel(D) det = sign*M[n - 1, n - 1] return det.expand() def det_LU_decomposition(self): """Compute matrix determinant using LU decomposition Note that this method fails if the LU decomposition itself fails. In particular, if the matrix has no inverse this method will fail. TODO: Implement algorithm for sparse matrices (SFF), http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps. See Also ======== det det_bareis berkowitz_det """ if not self.is_square: raise NonSquareMatrixError() if not self: return S.One M, n = self.copy(), self.rows p, prod = [], 1 l, u, p = M.LUdecomposition() if len(p) % 2: prod = -1 for k in range(n): prod = prod*u[k, k]*l[k, k] return prod.expand() def det(self, method="bareis"): """Computes the matrix determinant using the method "method". Possible values for "method": bareis ... det_bareis berkowitz ... berkowitz_det det_LU ... det_LU_decomposition See Also ======== det_bareis berkowitz_det det_LU """ # if methods were made internal and all determinant calculations # passed through here, then these lines could be factored out of # the method routines if not self.is_square: raise NonSquareMatrixError() if not self: return S.One if method == "bareis": return self.det_bareis() elif method == "berkowitz": return self.berkowitz_det() elif method == "det_LU": return self.det_LU_decomposition() else: raise ValueError("Determinant method '%s' unrecognized" % method) def diagonal_solve(self, rhs): """Solves Ax = B efficiently, where A is a diagonal Matrix, with non-zero diagonal entries. Examples ======== >>> from sympy.matrices import Matrix, eye >>> A = eye(2)*2 >>> B = Matrix([[1, 2], [3, 4]]) >>> A.diagonal_solve(B) == B/2 True See Also ======== lower_triangular_solve upper_triangular_solve gauss_jordan_solve cholesky_solve LDLsolve LUsolve QRsolve pinv_solve """ if not self.is_diagonal: raise TypeError("Matrix should be diagonal") if rhs.rows != self.rows: raise TypeError("Size mis-match") return self._diagonal_solve(rhs) def diagonalize(self, reals_only=False, sort=False, normalize=False): """ Return (P, D), where D is diagonal and D = P^-1 * M * P where M is current matrix. Examples ======== >>> from sympy import Matrix >>> m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2]) >>> m Matrix([ [1, 2, 0], [0, 3, 0], [2, -4, 2]]) >>> (P, D) = m.diagonalize() >>> D Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) >>> P Matrix([ [-1, 0, -1], [ 0, 0, -1], [ 2, 1, 2]]) >>> P.inv() * m * P Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) See Also ======== is_diagonal is_diagonalizable """ from sympy.matrices import diag if not self.is_square: raise NonSquareMatrixError() if not self.is_diagonalizable(reals_only, False): self._diagonalize_clear_subproducts() raise MatrixError("Matrix is not diagonalizable") else: if self._eigenvects is None: self._eigenvects = self.eigenvects(simplify=True) if sort: self._eigenvects.sort(key=default_sort_key) self._eigenvects.reverse() diagvals = [] P = self._new(self.rows, 0, []) for eigenval, multiplicity, vects in self._eigenvects: for k in range(multiplicity): diagvals.append(eigenval) vec = vects[k] if normalize: vec = vec / vec.norm() P = P.col_insert(P.cols, vec) D = diag(*diagvals) self._diagonalize_clear_subproducts() return (P, D) def diff(self, *args): """Calculate the derivative of each element in the matrix. Examples ======== >>> from sympy.matrices import Matrix >>> from sympy.abc import x, y >>> M = Matrix([[x, y], [1, 0]]) >>> M.diff(x) Matrix([ [1, 0], [0, 0]]) See Also ======== integrate limit """ return self._new(self.rows, self.cols, lambda i, j: self[i, j].diff(*args)) def doit(self, **kwargs): return self._new(self.rows, self.cols, [i.doit() for i in self._mat]) def dot(self, b): """Return the dot product of Matrix self and b relaxing the condition of compatible dimensions: if either the number of rows or columns are the same as the length of b then the dot product is returned. If self is a row or column vector, a scalar is returned. Otherwise, a list of results is returned (and in that case the number of columns in self must match the length of b). Examples ======== >>> from sympy import Matrix >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> v = [1, 1, 1] >>> M.row(0).dot(v) 6 >>> M.col(0).dot(v) 12 >>> M.dot(v) [6, 15, 24] See Also ======== cross multiply multiply_elementwise """ from .dense import Matrix if not isinstance(b, MatrixBase): if is_sequence(b): if len(b) != self.cols and len(b) != self.rows: raise ShapeError( "Dimensions incorrect for dot product: %s, %s" % ( self.shape, len(b))) return self.dot(Matrix(b)) else: raise TypeError("`b` must be an ordered iterable or Matrix, not %s." % type(b)) mat = self if mat.cols == b.rows: if b.cols != 1: mat = mat.T b = b.T prod = flatten((mat*b).tolist()) if len(prod) == 1: return prod[0] return prod if mat.cols == b.cols: return mat.dot(b.T) elif mat.rows == b.rows: return mat.T.dot(b) else: raise ShapeError("Dimensions incorrect for dot product: %s, %s" % ( self.shape, b.shape)) def dual(self): """Returns the dual of a matrix, which is: `(1/2)*levicivita(i, j, k, l)*M(k, l)` summed over indices `k` and `l` Since the levicivita method is anti_symmetric for any pairwise exchange of indices, the dual of a symmetric matrix is the zero matrix. Strictly speaking the dual defined here assumes that the 'matrix' `M` is a contravariant anti_symmetric second rank tensor, so that the dual is a covariant second rank tensor. """ from sympy import LeviCivita from sympy.matrices import zeros M, n = self[:, :], self.rows work = zeros(n) if self.is_symmetric(): return work for i in range(1, n): for j in range(1, n): acum = 0 for k in range(1, n): acum += LeviCivita(i, j, 0, k)*M[0, k] work[i, j] = acum work[j, i] = -acum for l in range(1, n): acum = 0 for a in range(1, n): for b in range(1, n): acum += LeviCivita(0, l, a, b)*M[a, b] acum /= 2 work[0, l] = -acum work[l, 0] = acum return work def eigenvals(self, **flags): """Return eigen values using the berkowitz_eigenvals routine. Since the roots routine doesn't always work well with Floats, they will be replaced with Rationals before calling that routine. If this is not desired, set flag ``rational`` to False. """ # roots doesn't like Floats, so replace them with Rationals # unless the nsimplify flag indicates that this has already # been done, e.g. in eigenvects mat = self if not mat: return {} if flags.pop('rational', True): if any(v.has(Float) for v in mat): mat = mat._new(mat.rows, mat.cols, [nsimplify(v, rational=True) for v in mat]) flags.pop('simplify', None) # pop unsupported flag return mat.berkowitz_eigenvals(**flags) def eigenvects(self, **flags): """Return list of triples (eigenval, multiplicity, basis). The flag ``simplify`` has two effects: 1) if bool(simplify) is True, as_content_primitive() will be used to tidy up normalization artifacts; 2) if nullspace needs simplification to compute the basis, the simplify flag will be passed on to the nullspace routine which will interpret it there. If the matrix contains any Floats, they will be changed to Rationals for computation purposes, but the answers will be returned after being evaluated with evalf. If it is desired to removed small imaginary portions during the evalf step, pass a value for the ``chop`` flag. """ from sympy.matrices import eye simplify = flags.get('simplify', True) primitive = bool(flags.get('simplify', False)) chop = flags.pop('chop', False) flags.pop('multiple', None) # remove this if it's there # roots doesn't like Floats, so replace them with Rationals float = False mat = self if any(v.has(Float) for v in self): float = True mat = mat._new(mat.rows, mat.cols, [nsimplify( v, rational=True) for v in mat]) flags['rational'] = False # to tell eigenvals not to do this out, vlist = [], mat.eigenvals(**flags) vlist = list(vlist.items()) vlist.sort(key=default_sort_key) flags.pop('rational', None) for r, k in vlist: tmp = mat.as_mutable() - eye(mat.rows)*r basis = tmp.nullspace() # whether tmp.is_symbolic() is True or False, it is possible that # the basis will come back as [] in which case simplification is # necessary. if not basis: # The nullspace routine failed, try it again with simplification basis = tmp.nullspace(simplify=simplify) if not basis: raise NotImplementedError( "Can't evaluate eigenvector for eigenvalue %s" % r) if primitive: # the relationship A*e = lambda*e will still hold if we change the # eigenvector; so if simplify is True we tidy up any normalization # artifacts with as_content_primtive (default) and remove any pure Integer # denominators. l = 1 for i, b in enumerate(basis[0]): c, p = signsimp(b).as_content_primitive() if c is not S.One: b = c*p l = ilcm(l, c.q) basis[0][i] = b if l != 1: basis[0] *= l if float: out.append((r.evalf(chop=chop), k, [ mat._new(b).evalf(chop=chop) for b in basis])) else: out.append((r, k, [mat._new(b) for b in basis])) return out def evalf(self, prec=None, **options): """Apply evalf() to each element of self.""" return self.applyfunc(lambda i: i.evalf(prec, **options)) def expand(self, deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints): """Apply core.function.expand to each entry of the matrix. Examples ======== >>> from sympy.abc import x >>> from sympy.matrices import Matrix >>> Matrix(1, 1, [x*(x+1)]) Matrix([[x*(x + 1)]]) >>> _.expand() Matrix([[x**2 + x]]) """ return self.applyfunc(lambda x: x.expand( deep, modulus, power_base, power_exp, mul, log, multinomial, basic, **hints)) def exp(self): """Return the exponentiation of a square matrix.""" if not self.is_square: raise NonSquareMatrixError( "Exponentiation is valid only for square matrices") try: P, cells = self.jordan_cells() except MatrixError: raise NotImplementedError("Exponentiation is implemented only for matrices for which the Jordan normal form can be computed") def _jblock_exponential(b): # This function computes the matrix exponential for one single Jordan block nr = b.rows l = b[0, 0] if nr == 1: res = exp(l) else: from sympy import eye # extract the diagonal part d = b[0, 0]*eye(nr) #and the nilpotent part n = b-d # compute its exponential nex = eye(nr) for i in range(1, nr): nex = nex+n**i/factorial(i) # combine the two parts res = exp(b[0, 0])*nex return(res) blocks = list(map(_jblock_exponential, cells)) from sympy.matrices import diag eJ = diag(* blocks) # n = self.rows ret = P*eJ*P.inv() return type(self)(ret) def extract(self, rowsList, colsList): """Return a submatrix by specifying a list of rows and columns. Negative indices can be given. All indices must be in the range -n <= i < n where n is the number of rows or columns. Examples ======== >>> from sympy import Matrix >>> m = Matrix(4, 3, range(12)) >>> m Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]) >>> m.extract([0, 1, 3], [0, 1]) Matrix([ [0, 1], [3, 4], [9, 10]]) Rows or columns can be repeated: >>> m.extract([0, 0, 1], [-1]) Matrix([ [2], [2], [5]]) Every other row can be taken by using range to provide the indices: >>> m.extract(range(0, m.rows, 2), [-1]) Matrix([ [2], [8]]) RowsList or colsList can also be a list of booleans, in which case the rows or columns corresponding to the True values will be selected: >>> m.extract([0, 1, 2, 3], [True, False, True]) Matrix([ [0, 2], [3, 5], [6, 8], [9, 11]]) """ cols = self.cols flat_list = self._mat if rowsList and all(isinstance(i, bool) for i in rowsList): rowsList = [index for index, item in enumerate(rowsList) if item] if colsList and all(isinstance(i, bool) for i in colsList): colsList = [index for index, item in enumerate(colsList) if item] rowsList = [a2idx(k, self.rows) for k in rowsList] colsList = [a2idx(k, self.cols) for k in colsList] return self._new(len(rowsList), len(colsList), lambda i, j: flat_list[rowsList[i]*cols + colsList[j]]) @property def free_symbols(self): """Returns the free symbols within the matrix. Examples ======== >>> from sympy.abc import x >>> from sympy.matrices import Matrix >>> Matrix([[x], [1]]).free_symbols set([x]) """ return set().union(*[i.free_symbols for i in self]) def gauss_jordan_solve(self, b, freevar=False): """ Solves Ax = b using Gauss Jordan elimination. There may be zero, one, or infinite solutions. If one solution exists, it will be returned. If infinite solutions exist, it will be returned parametrically. If no solutions exist, It will throw ValueError. Parameters ========== b : Matrix The right hand side of the equation to be solved for. Must have the same number of rows as matrix A. freevar : List If the system is underdetermined (e.g. A has more columns than rows), infinite solutions are possible, in terms of an arbitrary values of free variables. Then the index of the free variables in the solutions (column Matrix) will be returned by freevar, if the flag `freevar` is set to `True`. Returns ======= x : Matrix The matrix that will satisfy Ax = B. Will have as many rows as matrix A has columns, and as many columns as matrix B. params : Matrix If the system is underdetermined (e.g. A has more columns than rows), infinite solutions are possible, in terms of an arbitrary parameters. These arbitrary parameters are returned as params Matrix. Examples ======== >>> from sympy import Matrix >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]]) >>> b = Matrix([7, 12, 4]) >>> sol, params = A.gauss_jordan_solve(b) >>> sol Matrix([ [-2*_tau0 - 3*_tau1 + 2], [ _tau0], [ 2*_tau1 + 5], [ _tau1]]) >>> params Matrix([ [_tau0], [_tau1]]) >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> b = Matrix([3, 6, 9]) >>> sol, params = A.gauss_jordan_solve(b) >>> sol Matrix([ [-1], [ 2], [ 0]]) >>> params Matrix(0, 1, []) See Also ======== lower_triangular_solve upper_triangular_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv References ========== .. [1] http://en.wikipedia.org/wiki/Gaussian_elimination """ from sympy.matrices import Matrix, zeros aug = self.hstack(self.copy(), b.copy()) row, col = aug[:, :-1].shape # solve by reduced row echelon form A, pivots = aug.rref(simplify=True) A, v = A[:, :-1], A[:, -1] pivots = list(filter(lambda p: p < col, pivots)) rank = len(pivots) # Bring to block form permutation = Matrix(range(col)).T A = A.vstack(A, permutation) for i, c in enumerate(pivots): A.col_swap(i, c) A, permutation = A[:-1, :], A[-1, :] # check for existence of solutions # rank of aug Matrix should be equal to rank of coefficient matrix if not v[rank:, 0].is_zero: raise ValueError("Linear system has no solution") # Get index of free symbols (free parameters) free_var_index = permutation[len(pivots):] # non-pivots columns are free variables # Free parameters dummygen = numbered_symbols("tau", Dummy) tau = Matrix([next(dummygen) for k in range(col - rank)]).reshape(col - rank, 1) # Full parametric solution V = A[:rank, rank:] vt = v[:rank, 0] free_sol = tau.vstack(vt - V*tau, tau) # Undo permutation sol = zeros(col, 1) for k, v in enumerate(free_sol): sol[permutation[k], 0] = v if freevar: return sol, tau, free_var_index else: return sol, tau def get_diag_blocks(self): """Obtains the square sub-matrices on the main diagonal of a square matrix. Useful for inverting symbolic matrices or solving systems of linear equations which may be decoupled by having a block diagonal structure. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x, y, z >>> A = Matrix([[1, 3, 0, 0], [y, z*z, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]]) >>> a1, a2, a3 = A.get_diag_blocks() >>> a1 Matrix([ [1, 3], [y, z**2]]) >>> a2 Matrix([[x]]) >>> a3 Matrix([[0]]) """ sub_blocks = [] def recurse_sub_blocks(M): i = 1 while i <= M.shape[0]: if i == 1: to_the_right = M[0, i:] to_the_bottom = M[i:, 0] else: to_the_right = M[:i, i:] to_the_bottom = M[i:, :i] if any(to_the_right) or any(to_the_bottom): i += 1 continue else: sub_blocks.append(M[:i, :i]) if M.shape == M[:i, :i].shape: return else: recurse_sub_blocks(M[i:, i:]) return recurse_sub_blocks(self) return sub_blocks def has(self, *patterns): """Test whether any subexpression matches any of the patterns. Examples ======== >>> from sympy import Matrix, Float >>> from sympy.abc import x, y >>> A = Matrix(((1, x), (0.2, 3))) >>> A.has(x) True >>> A.has(y) False >>> A.has(Float) True """ return any(a.has(*patterns) for a in self._mat) @property def H(self): """Return Hermite conjugate. Examples ======== >>> from sympy import Matrix, I >>> m = Matrix((0, 1 + I, 2, 3)) >>> m Matrix([ [ 0], [1 + I], [ 2], [ 3]]) >>> m.H Matrix([[0, 1 - I, 2, 3]]) See Also ======== conjugate: By-element conjugation D: Dirac conjugation """ return self.T.C @classmethod def hstack(cls, *args): """Return a matrix formed by joining args horizontally (i.e. by repeated application of row_join). Examples ======== >>> from sympy.matrices import Matrix, eye >>> Matrix.hstack(eye(2), 2*eye(2)) Matrix([ [1, 0, 2, 0], [0, 1, 0, 2]]) """ return reduce(cls.row_join, args) def integrate(self, *args): """Integrate each element of the matrix. Examples ======== >>> from sympy.matrices import Matrix >>> from sympy.abc import x, y >>> M = Matrix([[x, y], [1, 0]]) >>> M.integrate((x, )) Matrix([ [x**2/2, x*y], [ x, 0]]) >>> M.integrate((x, 0, 2)) Matrix([ [2, 2*y], [2, 0]]) See Also ======== limit diff """ return self._new(self.rows, self.cols, lambda i, j: self[i, j].integrate(*args)) def inv_mod(self, m): """ Returns the inverse of the matrix `K` (mod `m`), if it exists. Method to find the matrix inverse of `K` (mod `m`) implemented in this function: * Compute `\mathrm{adj}(K) = \mathrm{cof}(K)^t`, the adjoint matrix of `K`. * Compute `r = 1/\mathrm{det}(K) \pmod m`. * `K^{-1} = r\cdot \mathrm{adj}(K) \pmod m`. Examples ======== >>> from sympy import Matrix >>> A = Matrix(2, 2, [1, 2, 3, 4]) >>> A.inv_mod(5) Matrix([ [3, 1], [4, 2]]) >>> A.inv_mod(3) Matrix([ [1, 1], [0, 1]]) """ from sympy.ntheory import totient if not self.is_square: raise NonSquareMatrixError() N = self.cols phi = totient(m) det_K = self.det() if gcd(det_K, m) != 1: raise ValueError('Matrix is not invertible (mod %d)' % m) det_inv = pow(int(det_K), int(phi - 1), int(m)) K_adj = self.cofactorMatrix().transpose() K_inv = self.__class__(N, N, [det_inv*K_adj[i, j] % m for i in range(N) for j in range(N)]) return K_inv def inverse_ADJ(self, iszerofunc=_iszero): """Calculates the inverse using the adjugate matrix and a determinant. See Also ======== inv inverse_LU inverse_GE """ if not self.is_square: raise NonSquareMatrixError("A Matrix must be square to invert.") d = self.berkowitz_det() zero = d.equals(0) if zero is None: # if equals() can't decide, will rref be able to? ok = self.rref(simplify=True)[0] zero = any(iszerofunc(ok[j, j]) for j in range(ok.rows)) if zero: raise ValueError("Matrix det == 0; not invertible.") return self.adjugate() / d def inverse_GE(self, iszerofunc=_iszero): """Calculates the inverse using Gaussian elimination. See Also ======== inv inverse_LU inverse_ADJ """ from .dense import Matrix if not self.is_square: raise NonSquareMatrixError("A Matrix must be square to invert.") big = Matrix.hstack(self.as_mutable(), Matrix.eye(self.rows)) red = big.rref(iszerofunc=iszerofunc, simplify=True)[0] if any(iszerofunc(red[j, j]) for j in range(red.rows)): raise ValueError("Matrix det == 0; not invertible.") return self._new(red[:, big.rows:]) def inverse_LU(self, iszerofunc=_iszero): """Calculates the inverse using LU decomposition. See Also ======== inv inverse_GE inverse_ADJ """ if not self.is_square: raise NonSquareMatrixError() ok = self.rref(simplify=True)[0] if any(iszerofunc(ok[j, j]) for j in range(ok.rows)): raise ValueError("Matrix det == 0; not invertible.") return self.LUsolve(self.eye(self.rows), iszerofunc=_iszero) def inv(self, method=None, **kwargs): """ Return the inverse of a matrix. CASE 1: If the matrix is a dense matrix. Return the matrix inverse using the method indicated (default is Gauss elimination). kwargs ====== method : ('GE', 'LU', or 'ADJ') Notes ===== According to the ``method`` keyword, it calls the appropriate method: GE .... inverse_GE(); default LU .... inverse_LU() ADJ ... inverse_ADJ() See Also ======== inverse_LU inverse_GE inverse_ADJ Raises ------ ValueError If the determinant of the matrix is zero. CASE 2: If the matrix is a sparse matrix. Return the matrix inverse using Cholesky or LDL (default). kwargs ====== method : ('CH', 'LDL') Notes ===== According to the ``method`` keyword, it calls the appropriate method: LDL ... inverse_LDL(); default CH .... inverse_CH() Raises ------ ValueError If the determinant of the matrix is zero. """ if not self.is_square: raise NonSquareMatrixError() if method is not None: kwargs['method'] = method return self._eval_inverse(**kwargs) def is_anti_symmetric(self, simplify=True): """Check if matrix M is an antisymmetric matrix, that is, M is a square matrix with all M[i, j] == -M[j, i]. When ``simplify=True`` (default), the sum M[i, j] + M[j, i] is simplified before testing to see if it is zero. By default, the SymPy simplify function is used. To use a custom function set simplify to a function that accepts a single argument which returns a simplified expression. To skip simplification, set simplify to False but note that although this will be faster, it may induce false negatives. Examples ======== >>> from sympy import Matrix, symbols >>> m = Matrix(2, 2, [0, 1, -1, 0]) >>> m Matrix([ [ 0, 1], [-1, 0]]) >>> m.is_anti_symmetric() True >>> x, y = symbols('x y') >>> m = Matrix(2, 3, [0, 0, x, -y, 0, 0]) >>> m Matrix([ [ 0, 0, x], [-y, 0, 0]]) >>> m.is_anti_symmetric() False >>> from sympy.abc import x, y >>> m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, ... -(x + 1)**2 , 0, x*y, ... -y, -x*y, 0]) Simplification of matrix elements is done by default so even though two elements which should be equal and opposite wouldn't pass an equality test, the matrix is still reported as anti-symmetric: >>> m[0, 1] == -m[1, 0] False >>> m.is_anti_symmetric() True If 'simplify=False' is used for the case when a Matrix is already simplified, this will speed things up. Here, we see that without simplification the matrix does not appear anti-symmetric: >>> m.is_anti_symmetric(simplify=False) False But if the matrix were already expanded, then it would appear anti-symmetric and simplification in the is_anti_symmetric routine is not needed: >>> m = m.expand() >>> m.is_anti_symmetric(simplify=False) True """ # accept custom simplification simpfunc = simplify if isinstance(simplify, FunctionType) else \ _simplify if simplify else False if not self.is_square: return False n = self.rows if simplify: for i in range(n): # diagonal if not simpfunc(self[i, i]).is_zero: return False # others for j in range(i + 1, n): diff = self[i, j] + self[j, i] if not simpfunc(diff).is_zero: return False return True else: for i in range(n): for j in range(i, n): if self[i, j] != -self[j, i]: return False return True def is_diagonal(self): """Check if matrix is diagonal, that is matrix in which the entries outside the main diagonal are all zero. Examples ======== >>> from sympy import Matrix, diag >>> m = Matrix(2, 2, [1, 0, 0, 2]) >>> m Matrix([ [1, 0], [0, 2]]) >>> m.is_diagonal() True >>> m = Matrix(2, 2, [1, 1, 0, 2]) >>> m Matrix([ [1, 1], [0, 2]]) >>> m.is_diagonal() False >>> m = diag(1, 2, 3) >>> m Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) >>> m.is_diagonal() True See Also ======== is_lower is_upper is_diagonalizable diagonalize """ for i in range(self.rows): for j in range(self.cols): if i != j and self[i, j]: return False return True def is_diagonalizable(self, reals_only=False, clear_subproducts=True): """Check if matrix is diagonalizable. If reals_only==True then check that diagonalized matrix consists of the only not complex values. Some subproducts could be used further in other methods to avoid double calculations, By default (if clear_subproducts==True) they will be deleted. Examples ======== >>> from sympy import Matrix >>> m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2]) >>> m Matrix([ [1, 2, 0], [0, 3, 0], [2, -4, 2]]) >>> m.is_diagonalizable() True >>> m = Matrix(2, 2, [0, 1, 0, 0]) >>> m Matrix([ [0, 1], [0, 0]]) >>> m.is_diagonalizable() False >>> m = Matrix(2, 2, [0, 1, -1, 0]) >>> m Matrix([ [ 0, 1], [-1, 0]]) >>> m.is_diagonalizable() True >>> m.is_diagonalizable(True) False See Also ======== is_diagonal diagonalize """ if not self.is_square: return False res = False self._is_symbolic = self.is_symbolic() self._is_symmetric = self.is_symmetric() self._eigenvects = None self._eigenvects = self.eigenvects(simplify=True) all_iscorrect = True for eigenval, multiplicity, vects in self._eigenvects: if len(vects) != multiplicity: all_iscorrect = False break elif reals_only and not eigenval.is_real: all_iscorrect = False break res = all_iscorrect if clear_subproducts: self._diagonalize_clear_subproducts() return res @property def is_hermitian(self): """Checks if the matrix is Hermitian. In a Hermitian matrix element i,j is the complex conjugate of element j,i. Examples ======== >>> from sympy.matrices import Matrix >>> from sympy import I >>> from sympy.abc import x >>> a = Matrix([[1, I], [-I, 1]]) >>> a Matrix([ [ 1, I], [-I, 1]]) >>> a.is_hermitian True >>> a[0, 0] = 2*I >>> a.is_hermitian False >>> a[0, 0] = x >>> a.is_hermitian >>> a[0, 1] = a[1, 0]*I >>> a.is_hermitian False """ def cond(): yield self.is_square yield fuzzy_and( self[i, i].is_real for i in range(self.rows)) yield fuzzy_and( (self[i, j] - self[j, i].conjugate()).is_zero for i in range(self.rows) for j in range(i + 1, self.cols)) return fuzzy_and(i for i in cond()) @property def is_lower_hessenberg(self): r"""Checks if the matrix is in the lower-Hessenberg form. The lower hessenberg matrix has zero entries above the first superdiagonal. Examples ======== >>> from sympy.matrices import Matrix >>> a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]]) >>> a Matrix([ [1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]]) >>> a.is_lower_hessenberg True See Also ======== is_upper_hessenberg is_lower """ return all(self[i, j].is_zero for i in range(self.rows) for j in range(i + 2, self.cols)) @property def is_lower(self): """Check if matrix is a lower triangular matrix. True can be returned even if the matrix is not square. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [1, 0, 0, 1]) >>> m Matrix([ [1, 0], [0, 1]]) >>> m.is_lower True >>> m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4 , 0, 6, 6, 5]) >>> m Matrix([ [0, 0, 0], [2, 0, 0], [1, 4, 0], [6, 6, 5]]) >>> m.is_lower True >>> from sympy.abc import x, y >>> m = Matrix(2, 2, [x**2 + y, y**2 + x, 0, x + y]) >>> m Matrix([ [x**2 + y, x + y**2], [ 0, x + y]]) >>> m.is_lower False See Also ======== is_upper is_diagonal is_lower_hessenberg """ return all(self[i, j].is_zero for i in range(self.rows) for j in range(i + 1, self.cols)) def is_nilpotent(self): """Checks if a matrix is nilpotent. A matrix B is nilpotent if for some integer k, B**k is a zero matrix. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[0, 0, 0], [1, 0, 0], [1, 1, 0]]) >>> a.is_nilpotent() True >>> a = Matrix([[1, 0, 1], [1, 0, 0], [1, 1, 0]]) >>> a.is_nilpotent() False """ if not self: return True if not self.is_square: raise NonSquareMatrixError( "Nilpotency is valid only for square matrices") x = Dummy('x') if self.charpoly(x).args[0] == x**self.rows: return True return False @property def is_square(self): """Checks if a matrix is square. A matrix is square if the number of rows equals the number of columns. The empty matrix is square by definition, since the number of rows and the number of columns are both zero. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[1, 2, 3], [4, 5, 6]]) >>> b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> c = Matrix([]) >>> a.is_square False >>> b.is_square True >>> c.is_square True """ return self.rows == self.cols def is_symbolic(self): """Checks if any elements contain Symbols. Examples ======== >>> from sympy.matrices import Matrix >>> from sympy.abc import x, y >>> M = Matrix([[x, y], [1, 0]]) >>> M.is_symbolic() True """ return any(element.has(Symbol) for element in self.values()) def is_symmetric(self, simplify=True): """Check if matrix is symmetric matrix, that is square matrix and is equal to its transpose. By default, simplifications occur before testing symmetry. They can be skipped using 'simplify=False'; while speeding things a bit, this may however induce false negatives. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [0, 1, 1, 2]) >>> m Matrix([ [0, 1], [1, 2]]) >>> m.is_symmetric() True >>> m = Matrix(2, 2, [0, 1, 2, 0]) >>> m Matrix([ [0, 1], [2, 0]]) >>> m.is_symmetric() False >>> m = Matrix(2, 3, [0, 0, 0, 0, 0, 0]) >>> m Matrix([ [0, 0, 0], [0, 0, 0]]) >>> m.is_symmetric() False >>> from sympy.abc import x, y >>> m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2 , 2, 0, y, 0, 3]) >>> m Matrix([ [ 1, x**2 + 2*x + 1, y], [(x + 1)**2, 2, 0], [ y, 0, 3]]) >>> m.is_symmetric() True If the matrix is already simplified, you may speed-up is_symmetric() test by using 'simplify=False'. >>> m.is_symmetric(simplify=False) False >>> m1 = m.expand() >>> m1.is_symmetric(simplify=False) True """ if not self.is_square: return False if simplify: delta = self - self.transpose() delta.simplify() return delta.equals(self.zeros(self.rows, self.cols)) else: return self == self.transpose() @property def is_upper_hessenberg(self): """Checks if the matrix is the upper-Hessenberg form. The upper hessenberg matrix has zero entries below the first subdiagonal. Examples ======== >>> from sympy.matrices import Matrix >>> a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]]) >>> a Matrix([ [1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]]) >>> a.is_upper_hessenberg True See Also ======== is_lower_hessenberg is_upper """ return all(self[i, j].is_zero for i in range(2, self.rows) for j in range(i - 1)) @property def is_upper(self): """Check if matrix is an upper triangular matrix. True can be returned even if the matrix is not square. Examples ======== >>> from sympy import Matrix >>> m = Matrix(2, 2, [1, 0, 0, 1]) >>> m Matrix([ [1, 0], [0, 1]]) >>> m.is_upper True >>> m = Matrix(4, 3, [5, 1, 9, 0, 4 , 6, 0, 0, 5, 0, 0, 0]) >>> m Matrix([ [5, 1, 9], [0, 4, 6], [0, 0, 5], [0, 0, 0]]) >>> m.is_upper True >>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1]) >>> m Matrix([ [4, 2, 5], [6, 1, 1]]) >>> m.is_upper False See Also ======== is_lower is_diagonal is_upper_hessenberg """ return all(self[i, j].is_zero for i in range(1, self.rows) for j in range(i)) @property def is_zero(self): """Checks if a matrix is a zero matrix. A matrix is zero if every element is zero. A matrix need not be square to be considered zero. The empty matrix is zero by the principle of vacuous truth. For a matrix that may or may not be zero (e.g. contains a symbol), this will be None Examples ======== >>> from sympy import Matrix, zeros >>> from sympy.abc import x >>> a = Matrix([[0, 0], [0, 0]]) >>> b = zeros(3, 4) >>> c = Matrix([[0, 1], [0, 0]]) >>> d = Matrix([]) >>> e = Matrix([[x, 0], [0, 0]]) >>> a.is_zero True >>> b.is_zero True >>> c.is_zero False >>> d.is_zero True >>> e.is_zero """ if any(i.is_zero == False for i in self): return False if any(i.is_zero == None for i in self): return None return True def jacobian(self, X): """Calculates the Jacobian matrix (derivative of a vectorial function). Parameters ========== self : vector of expressions representing functions f_i(x_1, ..., x_n). X : set of x_i's in order, it can be a list or a Matrix Both self and X can be a row or a column matrix in any order (i.e., jacobian() should always work). Examples ======== >>> from sympy import sin, cos, Matrix >>> from sympy.abc import rho, phi >>> X = Matrix([rho*cos(phi), rho*sin(phi), rho**2]) >>> Y = Matrix([rho, phi]) >>> X.jacobian(Y) Matrix([ [cos(phi), -rho*sin(phi)], [sin(phi), rho*cos(phi)], [ 2*rho, 0]]) >>> X = Matrix([rho*cos(phi), rho*sin(phi)]) >>> X.jacobian(Y) Matrix([ [cos(phi), -rho*sin(phi)], [sin(phi), rho*cos(phi)]]) See Also ======== hessian wronskian """ if not isinstance(X, MatrixBase): X = self._new(X) # Both X and self can be a row or a column matrix, so we need to make # sure all valid combinations work, but everything else fails: if self.shape[0] == 1: m = self.shape[1] elif self.shape[1] == 1: m = self.shape[0] else: raise TypeError("self must be a row or a column matrix") if X.shape[0] == 1: n = X.shape[1] elif X.shape[1] == 1: n = X.shape[0] else: raise TypeError("X must be a row or a column matrix") # m is the number of functions and n is the number of variables # computing the Jacobian is now easy: return self._new(m, n, lambda j, i: self[j].diff(X[i])) def jordan_cell(self, eigenval, n): n = int(n) from sympy.matrices import MutableMatrix out = MutableMatrix.zeros(n) for i in range(n-1): out[i, i] = eigenval out[i, i+1] = 1 out[n-1, n-1] = eigenval return type(self)(out) def jordan_cells(self, calc_transformation=True): r"""Return a list of Jordan cells of current matrix. This list shape Jordan matrix J. If calc_transformation is specified as False, then transformation P such that `J = P^{-1} \cdot M \cdot P` will not be calculated. Notes ===== Calculation of transformation P is not implemented yet. Examples ======== >>> from sympy import Matrix >>> m = Matrix(4, 4, [ ... 6, 5, -2, -3, ... -3, -1, 3, 3, ... 2, 1, -2, -3, ... -1, 1, 5, 5]) >>> P, Jcells = m.jordan_cells() >>> Jcells[0] Matrix([ [2, 1], [0, 2]]) >>> Jcells[1] Matrix([ [2, 1], [0, 2]]) See Also ======== jordan_form """ n = self.rows Jcells = [] Pcols_new = [] jordan_block_structures = self._jordan_block_structure() from sympy.matrices import MutableMatrix # Order according to default_sort_key, this makes sure the order is the same as in .diagonalize(): for eigenval in (sorted(list(jordan_block_structures.keys()), key=default_sort_key)): l_jordan_chains = jordan_block_structures[eigenval] for s in reversed(sorted((l_jordan_chains).keys())): # Start with the biggest block s_chains = l_jordan_chains[s] block = self.jordan_cell(eigenval, s) number_of_s_chains=len(s_chains) for i in range(0, number_of_s_chains): Jcells.append(type(self)(block)) chain_vectors = s_chains[i] lc = len(chain_vectors) assert lc == s for j in range(0, lc): generalized_eigen_vector = chain_vectors[j] Pcols_new.append(generalized_eigen_vector) P = MutableMatrix.zeros(n) for j in range(0, n): P[:, j] = Pcols_new[j] return type(self)(P), Jcells def jordan_form(self, calc_transformation=True): r"""Return Jordan form J of current matrix. Also the transformation P such that `J = P^{-1} \cdot M \cdot P` and the jordan blocks forming J will be calculated. Examples ======== >>> from sympy import Matrix >>> m = Matrix([ ... [ 6, 5, -2, -3], ... [-3, -1, 3, 3], ... [ 2, 1, -2, -3], ... [-1, 1, 5, 5]]) >>> P, J = m.jordan_form() >>> J Matrix([ [2, 1, 0, 0], [0, 2, 0, 0], [0, 0, 2, 1], [0, 0, 0, 2]]) See Also ======== jordan_cells """ P, Jcells = self.jordan_cells() from sympy.matrices import diag J = diag(*Jcells) return P, type(self)(J) def key2bounds(self, keys): """Converts a key with potentially mixed types of keys (integer and slice) into a tuple of ranges and raises an error if any index is out of self's range. See Also ======== key2ij """ islice, jslice = [isinstance(k, slice) for k in keys] if islice: if not self.rows: rlo = rhi = 0 else: rlo, rhi = keys[0].indices(self.rows)[:2] else: rlo = a2idx(keys[0], self.rows) rhi = rlo + 1 if jslice: if not self.cols: clo = chi = 0 else: clo, chi = keys[1].indices(self.cols)[:2] else: clo = a2idx(keys[1], self.cols) chi = clo + 1 return rlo, rhi, clo, chi def key2ij(self, key): """Converts key into canonical form, converting integers or indexable items into valid integers for self's range or returning slices unchanged. See Also ======== key2bounds """ if is_sequence(key): if not len(key) == 2: raise TypeError('key must be a sequence of length 2') return [a2idx(i, n) if not isinstance(i, slice) else i for i, n in zip(key, self.shape)] elif isinstance(key, slice): return key.indices(len(self))[:2] else: return divmod(a2idx(key, len(self)), self.cols) def LDLdecomposition(self): """Returns the LDL Decomposition (L, D) of matrix A, such that L * D * L.T == A This method eliminates the use of square root. Further this ensures that all the diagonal entries of L are 1. A must be a square, symmetric, positive-definite and non-singular matrix. Examples ======== >>> from sympy.matrices import Matrix, eye >>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) >>> L, D = A.LDLdecomposition() >>> L Matrix([ [ 1, 0, 0], [ 3/5, 1, 0], [-1/5, 1/3, 1]]) >>> D Matrix([ [25, 0, 0], [ 0, 9, 0], [ 0, 0, 9]]) >>> L * D * L.T * A.inv() == eye(A.rows) True See Also ======== cholesky LUdecomposition QRdecomposition """ if not self.is_square: raise NonSquareMatrixError("Matrix must be square.") if not self.is_symmetric(): raise ValueError("Matrix must be symmetric.") return self._LDLdecomposition() def LDLsolve(self, rhs): """Solves Ax = B using LDL decomposition, for a general square and non-singular matrix. For a non-square matrix with rows > cols, the least squares solution is returned. Examples ======== >>> from sympy.matrices import Matrix, eye >>> A = eye(2)*2 >>> B = Matrix([[1, 2], [3, 4]]) >>> A.LDLsolve(B) == B/2 True See Also ======== LDLdecomposition lower_triangular_solve upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LUsolve QRsolve pinv_solve """ if self.is_symmetric(): L, D = self.LDLdecomposition() elif self.rows >= self.cols: L, D = (self.T*self).LDLdecomposition() rhs = self.T*rhs else: raise NotImplementedError('Under-determined System. ' 'Try M.gauss_jordan_solve(rhs)') Y = L._lower_triangular_solve(rhs) Z = D._diagonal_solve(Y) return (L.T)._upper_triangular_solve(Z) def left_eigenvects(self, **flags): """Returns left eigenvectors and eigenvalues. This function returns the list of triples (eigenval, multiplicity, basis) for the left eigenvectors. Options are the same as for eigenvects(), i.e. the ``**flags`` arguments gets passed directly to eigenvects(). Examples ======== >>> from sympy import Matrix >>> M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]]) >>> M.eigenvects() [(-1, 1, [Matrix([ [-1], [ 1], [ 0]])]), (0, 1, [Matrix([ [ 0], [-1], [ 1]])]), (2, 1, [Matrix([ [2/3], [1/3], [ 1]])])] >>> M.left_eigenvects() [(-1, 1, [Matrix([[-2, 1, 1]])]), (0, 1, [Matrix([[-1, -1, 1]])]), (2, 1, [Matrix([[1, 1, 1]])])] """ mat = self left_transpose = mat.transpose().eigenvects(**flags) left = [] for (ev, mult, ltmp) in left_transpose: left.append( (ev, mult, [l.transpose() for l in ltmp]) ) return left def limit(self, *args): """Calculate the limit of each element in the matrix. Examples ======== >>> from sympy.matrices import Matrix >>> from sympy.abc import x, y >>> M = Matrix([[x, y], [1, 0]]) >>> M.limit(x, 2) Matrix([ [2, y], [1, 0]]) See Also ======== integrate diff """ return self._new(self.rows, self.cols, lambda i, j: self[i, j].limit(*args)) def lower_triangular_solve(self, rhs): """Solves Ax = B, where A is a lower triangular matrix. See Also ======== upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv_solve """ if not self.is_square: raise NonSquareMatrixError("Matrix must be square.") if rhs.rows != self.rows: raise ShapeError("Matrices size mismatch.") if not self.is_lower: raise ValueError("Matrix must be lower triangular.") return self._lower_triangular_solve(rhs) def LUdecomposition(self, iszerofunc=_iszero): """Returns the decomposition LU and the row swaps p. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[4, 3], [6, 3]]) >>> L, U, _ = a.LUdecomposition() >>> L Matrix([ [ 1, 0], [3/2, 1]]) >>> U Matrix([ [4, 3], [0, -3/2]]) See Also ======== cholesky LDLdecomposition QRdecomposition LUdecomposition_Simple LUdecompositionFF LUsolve """ combined, p = self.LUdecomposition_Simple(iszerofunc=_iszero) L = self.zeros(self.rows) U = self.zeros(self.rows) for i in range(self.rows): for j in range(self.rows): if i > j: L[i, j] = combined[i, j] else: if i == j: L[i, i] = 1 U[i, j] = combined[i, j] return L, U, p def LUdecomposition_Simple(self, iszerofunc=_iszero): """Returns A comprised of L, U (L's diag entries are 1) and p which is the list of the row swaps (in order). See Also ======== LUdecomposition LUdecompositionFF LUsolve """ if not self.is_square: raise NonSquareMatrixError("A Matrix must be square to apply LUdecomposition_Simple().") n = self.rows A = self.as_mutable() p = [] # factorization for j in range(n): for i in range(j): for k in range(i): A[i, j] = A[i, j] - A[i, k]*A[k, j] pivot = -1 for i in range(j, n): for k in range(j): A[i, j] = A[i, j] - A[i, k]*A[k, j] # find the first non-zero pivot, includes any expression if pivot == -1 and not iszerofunc(A[i, j]): pivot = i if pivot < 0: # this result is based on iszerofunc's analysis of the possible pivots, so even though # the element may not be strictly zero, the supplied iszerofunc's evaluation gave True raise ValueError("No nonzero pivot found; inversion failed.") if pivot != j: # row must be swapped A.row_swap(pivot, j) p.append([pivot, j]) scale = 1 / A[j, j] for i in range(j + 1, n): A[i, j] = A[i, j]*scale return A, p def LUdecompositionFF(self): """Compute a fraction-free LU decomposition. Returns 4 matrices P, L, D, U such that PA = L D**-1 U. If the elements of the matrix belong to some integral domain I, then all elements of L, D and U are guaranteed to belong to I. **Reference** - W. Zhou & D.J. Jeffrey, "Fraction-free matrix factors: new forms for LU and QR factors". Frontiers in Computer Science in China, Vol 2, no. 1, pp. 67-80, 2008. See Also ======== LUdecomposition LUdecomposition_Simple LUsolve """ from sympy.matrices import SparseMatrix zeros = SparseMatrix.zeros eye = SparseMatrix.eye n, m = self.rows, self.cols U, L, P = self.as_mutable(), eye(n), eye(n) DD = zeros(n, n) oldpivot = 1 for k in range(n - 1): if U[k, k] == 0: for kpivot in range(k + 1, n): if U[kpivot, k]: break else: raise ValueError("Matrix is not full rank") U[k, k:], U[kpivot, k:] = U[kpivot, k:], U[k, k:] L[k, :k], L[kpivot, :k] = L[kpivot, :k], L[k, :k] P[k, :], P[kpivot, :] = P[kpivot, :], P[k, :] L[k, k] = Ukk = U[k, k] DD[k, k] = oldpivot*Ukk for i in range(k + 1, n): L[i, k] = Uik = U[i, k] for j in range(k + 1, m): U[i, j] = (Ukk*U[i, j] - U[k, j]*Uik) / oldpivot U[i, k] = 0 oldpivot = Ukk DD[n - 1, n - 1] = oldpivot return P, L, DD, U def LUsolve(self, rhs, iszerofunc=_iszero): """Solve the linear system Ax = rhs for x where A = self. This is for symbolic matrices, for real or complex ones use mpmath.lu_solve or mpmath.qr_solve. See Also ======== lower_triangular_solve upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve QRsolve pinv_solve LUdecomposition """ if rhs.rows != self.rows: raise ShapeError("`self` and `rhs` must have the same number of rows.") A, perm = self.LUdecomposition_Simple(iszerofunc=_iszero) n = self.rows b = rhs.permuteFwd(perm).as_mutable() # forward substitution, all diag entries are scaled to 1 for i in range(n): for j in range(i): scale = A[i, j] b.zip_row_op(i, j, lambda x, y: x - y*scale) # backward substitution for i in range(n - 1, -1, -1): for j in range(i + 1, n): scale = A[i, j] b.zip_row_op(i, j, lambda x, y: x - y*scale) scale = A[i, i] b.row_op(i, lambda x, _: x/scale) return rhs.__class__(b) def minorEntry(self, i, j, method="berkowitz"): """Calculate the minor of an element. See Also ======== minorMatrix cofactor cofactorMatrix """ if not 0 <= i < self.rows or not 0 <= j < self.cols: raise ValueError("`i` and `j` must satisfy 0 <= i < `self.rows` " + "(%d)" % self.rows + "and 0 <= j < `self.cols` (%d)." % self.cols) return self.minorMatrix(i, j).det(method) def minorMatrix(self, i, j): """Creates the minor matrix of a given element. See Also ======== minorEntry cofactor cofactorMatrix """ if not 0 <= i < self.rows or not 0 <= j < self.cols: raise ValueError("`i` and `j` must satisfy 0 <= i < `self.rows` " + "(%d)" % self.rows + "and 0 <= j < `self.cols` (%d)." % self.cols) M = self.as_mutable() M.row_del(i) M.col_del(j) return self._new(M) def multiply_elementwise(self, b): """Return the Hadamard product (elementwise product) of A and B Examples ======== >>> from sympy.matrices import Matrix >>> A = Matrix([[0, 1, 2], [3, 4, 5]]) >>> B = Matrix([[1, 10, 100], [100, 10, 1]]) >>> A.multiply_elementwise(B) Matrix([ [ 0, 10, 200], [300, 40, 5]]) See Also ======== cross dot multiply """ from sympy.matrices import matrix_multiply_elementwise return matrix_multiply_elementwise(self, b) def multiply(self, b): """Returns self*b See Also ======== dot cross multiply_elementwise """ return self*b def normalized(self): """Return the normalized version of ``self``. See Also ======== norm """ if self.rows != 1 and self.cols != 1: raise ShapeError("A Matrix must be a vector to normalize.") norm = self.norm() out = self.applyfunc(lambda i: i / norm) return out def norm(self, ord=None): """Return the Norm of a Matrix or Vector. In the simplest case this is the geometric size of the vector Other norms can be specified by the ord parameter ===== ============================ ========================== ord norm for matrices norm for vectors ===== ============================ ========================== None Frobenius norm 2-norm 'fro' Frobenius norm - does not exist inf -- max(abs(x)) -inf -- min(abs(x)) 1 -- as below -1 -- as below 2 2-norm (largest sing. value) as below -2 smallest singular value as below other - does not exist sum(abs(x)**ord)**(1./ord) ===== ============================ ========================== Examples ======== >>> from sympy import Matrix, Symbol, trigsimp, cos, sin, oo >>> x = Symbol('x', real=True) >>> v = Matrix([cos(x), sin(x)]) >>> trigsimp( v.norm() ) 1 >>> v.norm(10) (sin(x)**10 + cos(x)**10)**(1/10) >>> A = Matrix([[1, 1], [1, 1]]) >>> A.norm(2)# Spectral norm (max of |Ax|/|x| under 2-vector-norm) 2 >>> A.norm(-2) # Inverse spectral norm (smallest singular value) 0 >>> A.norm() # Frobenius Norm 2 >>> Matrix([1, -2]).norm(oo) 2 >>> Matrix([-1, 2]).norm(-oo) 1 See Also ======== normalized """ # Row or Column Vector Norms vals = list(self.values()) or [0] if self.rows == 1 or self.cols == 1: if ord == 2 or ord is None: # Common case sqrt(<x, x>) return sqrt(Add(*(abs(i)**2 for i in vals))) elif ord == 1: # sum(abs(x)) return Add(*(abs(i) for i in vals)) elif ord == S.Infinity: # max(abs(x)) return Max(*[abs(i) for i in vals]) elif ord == S.NegativeInfinity: # min(abs(x)) return Min(*[abs(i) for i in vals]) # Otherwise generalize the 2-norm, Sum(x_i**ord)**(1/ord) # Note that while useful this is not mathematically a norm try: return Pow(Add(*(abs(i)**ord for i in vals)), S(1) / ord) except (NotImplementedError, TypeError): raise ValueError("Expected order to be Number, Symbol, oo") # Matrix Norms else: if ord == 2: # Spectral Norm # Maximum singular value return Max(*self.singular_values()) elif ord == -2: # Minimum singular value return Min(*self.singular_values()) elif (ord is None or isinstance(ord, string_types) and ord.lower() in ['f', 'fro', 'frobenius', 'vector']): # Reshape as vector and send back to norm function return self.vec().norm(ord=2) else: raise NotImplementedError("Matrix Norms under development") def nullspace(self, simplify=False): """Returns list of vectors (Matrix objects) that span nullspace of self Examples ======== >>> from sympy.matrices import Matrix >>> m = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6]) >>> m Matrix([ [ 1, 3, 0], [-2, -6, 0], [ 3, 9, 6]]) >>> m.nullspace() [Matrix([ [-3], [ 1], [ 0]])] See Also ======== columnspace """ from sympy.matrices import zeros simpfunc = simplify if isinstance( simplify, FunctionType) else _simplify reduced, pivots = self.rref(simplify=simpfunc) basis = [] # create a set of vectors for the basis for i in range(self.cols - len(pivots)): basis.append(zeros(self.cols, 1)) # contains the variable index to which the vector corresponds basiskey, cur = [-1]*len(basis), 0 for i in range(self.cols): if i not in pivots: basiskey[cur] = i cur += 1 for i in range(self.cols): if i not in pivots: # free var, just set vector's ith place to 1 basis[basiskey.index(i)][i, 0] = 1 else: # add negative of nonpivot entry to corr vector for j in range(i + 1, self.cols): line = pivots.index(i) v = reduced[line, j] if simplify: v = simpfunc(v) if v: if j in pivots: # XXX: Is this the correct error? raise NotImplementedError( "Could not compute the nullspace of `self`.") basis[basiskey.index(j)][i, 0] = -v return [self._new(b) for b in basis] def permuteBkwd(self, perm): """Permute the rows of the matrix with the given permutation in reverse. Examples ======== >>> from sympy.matrices import eye >>> M = eye(3) >>> M.permuteBkwd([[0, 1], [0, 2]]) Matrix([ [0, 1, 0], [0, 0, 1], [1, 0, 0]]) See Also ======== permuteFwd """ copy = self.copy() for i in range(len(perm) - 1, -1, -1): copy.row_swap(perm[i][0], perm[i][1]) return copy def permuteFwd(self, perm): """Permute the rows of the matrix with the given permutation. Examples ======== >>> from sympy.matrices import eye >>> M = eye(3) >>> M.permuteFwd([[0, 1], [0, 2]]) Matrix([ [0, 0, 1], [1, 0, 0], [0, 1, 0]]) See Also ======== permuteBkwd """ copy = self.copy() for i in range(len(perm)): copy.row_swap(perm[i][0], perm[i][1]) return copy def pinv_solve(self, B, arbitrary_matrix=None): """Solve Ax = B using the Moore-Penrose pseudoinverse. There may be zero, one, or infinite solutions. If one solution exists, it will be returned. If infinite solutions exist, one will be returned based on the value of arbitrary_matrix. If no solutions exist, the least-squares solution is returned. Parameters ========== B : Matrix The right hand side of the equation to be solved for. Must have the same number of rows as matrix A. arbitrary_matrix : Matrix If the system is underdetermined (e.g. A has more columns than rows), infinite solutions are possible, in terms of an arbitrary matrix. This parameter may be set to a specific matrix to use for that purpose; if so, it must be the same shape as x, with as many rows as matrix A has columns, and as many columns as matrix B. If left as None, an appropriate matrix containing dummy symbols in the form of ``wn_m`` will be used, with n and m being row and column position of each symbol. Returns ======= x : Matrix The matrix that will satisfy Ax = B. Will have as many rows as matrix A has columns, and as many columns as matrix B. Examples ======== >>> from sympy import Matrix >>> A = Matrix([[1, 2, 3], [4, 5, 6]]) >>> B = Matrix([7, 8]) >>> A.pinv_solve(B) Matrix([ [ _w0_0/6 - _w1_0/3 + _w2_0/6 - 55/18], [-_w0_0/3 + 2*_w1_0/3 - _w2_0/3 + 1/9], [ _w0_0/6 - _w1_0/3 + _w2_0/6 + 59/18]]) >>> A.pinv_solve(B, arbitrary_matrix=Matrix([0, 0, 0])) Matrix([ [-55/18], [ 1/9], [ 59/18]]) See Also ======== lower_triangular_solve upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv Notes ===== This may return either exact solutions or least squares solutions. To determine which, check ``A * A.pinv() * B == B``. It will be True if exact solutions exist, and False if only a least-squares solution exists. Be aware that the left hand side of that equation may need to be simplified to correctly compare to the right hand side. References ========== .. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse#Obtaining_all_solutions_of_a_linear_system """ from sympy.matrices import eye A = self A_pinv = self.pinv() if arbitrary_matrix is None: rows, cols = A.cols, B.cols w = symbols('w:{0}_:{1}'.format(rows, cols), cls=Dummy) arbitrary_matrix = self.__class__(cols, rows, w).T return A_pinv * B + (eye(A.cols) - A_pinv*A) * arbitrary_matrix def pinv(self): """Calculate the Moore-Penrose pseudoinverse of the matrix. The Moore-Penrose pseudoinverse exists and is unique for any matrix. If the matrix is invertible, the pseudoinverse is the same as the inverse. Examples ======== >>> from sympy import Matrix >>> Matrix([[1, 2, 3], [4, 5, 6]]).pinv() Matrix([ [-17/18, 4/9], [ -1/9, 1/9], [ 13/18, -2/9]]) See Also ======== inv pinv_solve References ========== .. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse """ A = self AH = self.H # Trivial case: pseudoinverse of all-zero matrix is its transpose. if A.is_zero: return AH try: if self.rows >= self.cols: return (AH * A).inv() * AH else: return AH * (A * AH).inv() except ValueError: # Matrix is not full rank, so A*AH cannot be inverted. raise NotImplementedError('Rank-deficient matrices are not yet ' 'supported.') def print_nonzero(self, symb="X"): """Shows location of non-zero entries for fast shape lookup. Examples ======== >>> from sympy.matrices import Matrix, eye >>> m = Matrix(2, 3, lambda i, j: i*3+j) >>> m Matrix([ [0, 1, 2], [3, 4, 5]]) >>> m.print_nonzero() [ XX] [XXX] >>> m = eye(4) >>> m.print_nonzero("x") [x ] [ x ] [ x ] [ x] """ s = [] for i in range(self.rows): line = [] for j in range(self.cols): if self[i, j] == 0: line.append(" ") else: line.append(str(symb)) s.append("[%s]" % ''.join(line)) print('\n'.join(s)) def project(self, v): """Return the projection of ``self`` onto the line containing ``v``. Examples ======== >>> from sympy import Matrix, S, sqrt >>> V = Matrix([sqrt(3)/2, S.Half]) >>> x = Matrix([[1, 0]]) >>> V.project(x) Matrix([[sqrt(3)/2, 0]]) >>> V.project(-x) Matrix([[sqrt(3)/2, 0]]) """ return v*(self.dot(v) / v.dot(v)) def QRdecomposition(self): """Return Q, R where A = Q*R, Q is orthogonal and R is upper triangular. Examples ======== This is the example from wikipedia: >>> from sympy import Matrix >>> A = Matrix([[12, -51, 4], [6, 167, -68], [-4, 24, -41]]) >>> Q, R = A.QRdecomposition() >>> Q Matrix([ [ 6/7, -69/175, -58/175], [ 3/7, 158/175, 6/175], [-2/7, 6/35, -33/35]]) >>> R Matrix([ [14, 21, -14], [ 0, 175, -70], [ 0, 0, 35]]) >>> A == Q*R True QR factorization of an identity matrix: >>> A = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> Q, R = A.QRdecomposition() >>> Q Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> R Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) See Also ======== cholesky LDLdecomposition LUdecomposition QRsolve """ cls = self.__class__ mat = self.as_mutable() if not mat.rows >= mat.cols: raise MatrixError( "The number of rows must be greater than columns") n = mat.rows m = mat.cols rank = n row_reduced = mat.rref()[0] for i in range(row_reduced.rows): if row_reduced.row(i).norm() == 0: rank -= 1 if not rank == mat.cols: raise MatrixError("The rank of the matrix must match the columns") Q, R = mat.zeros(n, m), mat.zeros(m) for j in range(m): # for each column vector tmp = mat[:, j] # take original v for i in range(j): # subtract the project of mat on new vector tmp -= Q[:, i]*mat[:, j].dot(Q[:, i]) tmp.expand() # normalize it R[j, j] = tmp.norm() Q[:, j] = tmp / R[j, j] if Q[:, j].norm() != 1: raise NotImplementedError( "Could not normalize the vector %d." % j) for i in range(j): R[i, j] = Q[:, i].dot(mat[:, j]) return cls(Q), cls(R) def QRsolve(self, b): """Solve the linear system 'Ax = b'. 'self' is the matrix 'A', the method argument is the vector 'b'. The method returns the solution vector 'x'. If 'b' is a matrix, the system is solved for each column of 'b' and the return value is a matrix of the same shape as 'b'. This method is slower (approximately by a factor of 2) but more stable for floating-point arithmetic than the LUsolve method. However, LUsolve usually uses an exact arithmetic, so you don't need to use QRsolve. This is mainly for educational purposes and symbolic matrices, for real (or complex) matrices use mpmath.qr_solve. See Also ======== lower_triangular_solve upper_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve pinv_solve QRdecomposition """ Q, R = self.as_mutable().QRdecomposition() y = Q.T*b # back substitution to solve R*x = y: # We build up the result "backwards" in the vector 'x' and reverse it # only in the end. x = [] n = R.rows for j in range(n - 1, -1, -1): tmp = y[j, :] for k in range(j + 1, n): tmp -= R[j, k]*x[n - 1 - k] x.append(tmp / R[j, j]) return self._new([row._mat for row in reversed(x)]) def rank(self, iszerofunc=_iszero, simplify=False): """ Returns the rank of a matrix >>> from sympy import Matrix >>> from sympy.abc import x >>> m = Matrix([[1, 2], [x, 1 - 1/x]]) >>> m.rank() 2 >>> n = Matrix(3, 3, range(1, 10)) >>> n.rank() 2 """ row_reduced = self.rref(iszerofunc=iszerofunc, simplify=simplify) rank = len(row_reduced[-1]) return rank def refine(self, assumptions=True): """Apply refine to each element of the matrix. Examples ======== >>> from sympy import Symbol, Matrix, Abs, sqrt, Q >>> x = Symbol('x') >>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]]) Matrix([ [ Abs(x)**2, sqrt(x**2)], [sqrt(x**2), Abs(x)**2]]) >>> _.refine(Q.real(x)) Matrix([ [ x**2, Abs(x)], [Abs(x), x**2]]) """ return self.applyfunc(lambda x: refine(x, assumptions)) def replace(self, F, G, map=False): """Replaces Function F in Matrix entries with Function G. Examples ======== >>> from sympy import symbols, Function, Matrix >>> F, G = symbols('F, G', cls=Function) >>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M Matrix([ [F(0), F(1)], [F(1), F(2)]]) >>> N = M.replace(F,G) >>> N Matrix([ [G(0), G(1)], [G(1), G(2)]]) """ M = self[:, :] return M.applyfunc(lambda x: x.replace(F, G, map)) def row_insert(self, pos, mti): """Insert one or more rows at the given row position. Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(1, 3) >>> M.row_insert(1, V) Matrix([ [0, 0, 0], [1, 1, 1], [0, 0, 0], [0, 0, 0]]) See Also ======== row col_insert """ from sympy.matrices import MutableMatrix # Allows you to build a matrix even if it is null matrix if not self: return type(self)(mti) if pos == 0: return mti.col_join(self) elif pos < 0: pos = self.rows + pos if pos < 0: pos = 0 elif pos > self.rows: pos = self.rows if self.cols != mti.cols: raise ShapeError( "`self` and `mti` must have the same number of columns.") newmat = self.zeros(self.rows + mti.rows, self.cols) i, j = pos, pos + mti.rows newmat[:i, :] = self[:i, :] newmat[i: j, :] = mti newmat[j:, :] = self[i:, :] return newmat def row_join(self, rhs): """Concatenates two matrices along self's last and rhs's first column Examples ======== >>> from sympy import zeros, ones >>> M = zeros(3) >>> V = ones(3, 1) >>> M.row_join(V) Matrix([ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1]]) See Also ======== row col_join """ from sympy.matrices import MutableMatrix # Allows you to build a matrix even if it is null matrix if not self: return type(self)(rhs) if self.rows != rhs.rows: raise ShapeError( "`self` and `rhs` must have the same number of rows.") newmat = MutableMatrix.zeros(self.rows, self.cols + rhs.cols) newmat[:, :self.cols] = self newmat[:, self.cols:] = rhs return type(self)(newmat) def rref(self, iszerofunc=_iszero, simplify=False): """Return reduced row-echelon form of matrix and indices of pivot vars. To simplify elements before finding nonzero pivots set simplify=True (to use the default SymPy simplify function) or pass a custom simplify function. Examples ======== >>> from sympy import Matrix >>> from sympy.abc import x >>> m = Matrix([[1, 2], [x, 1 - 1/x]]) >>> m.rref() (Matrix([ [1, 0], [0, 1]]), [0, 1]) >>> rref_matrix, rref_pivots = m.rref() >>> rref_matrix Matrix([ [1, 0], [0, 1]]) >>> rref_pivots [0, 1] """ simpfunc = simplify if isinstance( simplify, FunctionType) else _simplify # pivot: index of next row to contain a pivot pivot, r = 0, self.as_mutable() # pivotlist: indices of pivot variables (non-free) pivotlist = [] for i in range(r.cols): if pivot == r.rows: break if simplify: r[pivot, i] = simpfunc(r[pivot, i]) pivot_offset, pivot_val, assumed_nonzero, newly_determined = _find_reasonable_pivot(r[pivot:, i], iszerofunc, simpfunc) # `_find_reasonable_pivot` may have simplified # some elements along the way. If they were simplified # and then determined to be either zero or non-zero for # sure, they are stored in the `newly_determined` list for (offset, val) in newly_determined: r[pivot + offset, i] = val # if `pivot_offset` is None, this column has no # pivot if pivot_offset is None: continue # swap the pivot column into place pivot_pos = pivot + pivot_offset r.row_swap(pivot, pivot_pos) r.row_op(pivot, lambda x, _: x / pivot_val) for j in range(r.rows): if j == pivot: continue pivot_val = r[j, i] r.zip_row_op(j, pivot, lambda x, y: x - pivot_val*y) pivotlist.append(i) pivot += 1 return self._new(r), pivotlist @property def shape(self): """The shape (dimensions) of the matrix as the 2-tuple (rows, cols). Examples ======== >>> from sympy.matrices import zeros >>> M = zeros(2, 3) >>> M.shape (2, 3) >>> M.rows 2 >>> M.cols 3 """ return (self.rows, self.cols) def simplify(self, ratio=1.7, measure=count_ops): """Apply simplify to each element of the matrix. Examples ======== >>> from sympy.abc import x, y >>> from sympy import sin, cos >>> from sympy.matrices import SparseMatrix >>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2]) Matrix([[x*sin(y)**2 + x*cos(y)**2]]) >>> _.simplify() Matrix([[x]]) """ return self.applyfunc(lambda x: x.simplify(ratio, measure)) def singular_values(self): """Compute the singular values of a Matrix Examples ======== >>> from sympy import Matrix, Symbol >>> x = Symbol('x', real=True) >>> A = Matrix([[0, 1, 0], [0, x, 0], [-1, 0, 0]]) >>> A.singular_values() [sqrt(x**2 + 1), 1, 0] See Also ======== condition_number """ mat = self.as_mutable() # Compute eigenvalues of A.H A valmultpairs = (mat.H*mat).eigenvals() # Expands result from eigenvals into a simple list vals = [] for k, v in valmultpairs.items(): vals += [sqrt(k)]*v # dangerous! same k in several spots! # sort them in descending order vals.sort(reverse=True, key=default_sort_key) return vals def solve_least_squares(self, rhs, method='CH'): """Return the least-square fit to the data. By default the cholesky_solve routine is used (method='CH'); other methods of matrix inversion can be used. To find out which are available, see the docstring of the .inv() method. Examples ======== >>> from sympy.matrices import Matrix, ones >>> A = Matrix([1, 2, 3]) >>> B = Matrix([2, 3, 4]) >>> S = Matrix(A.row_join(B)) >>> S Matrix([ [1, 2], [2, 3], [3, 4]]) If each line of S represent coefficients of Ax + By and x and y are [2, 3] then S*xy is: >>> r = S*Matrix([2, 3]); r Matrix([ [ 8], [13], [18]]) But let's add 1 to the middle value and then solve for the least-squares value of xy: >>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy Matrix([ [ 5/3], [10/3]]) The error is given by S*xy - r: >>> S*xy - r Matrix([ [1/3], [1/3], [1/3]]) >>> _.norm().n(2) 0.58 If a different xy is used, the norm will be higher: >>> xy += ones(2, 1)/10 >>> (S*xy - r).norm().n(2) 1.5 """ if method == 'CH': return self.cholesky_solve(rhs) t = self.T return (t*self).inv(method=method)*t*rhs def solve(self, rhs, method='GE'): """Return solution to self*soln = rhs using given inversion method. For a list of possible inversion methods, see the .inv() docstring. """ if not self.is_square: if self.rows < self.cols: raise ValueError('Under-determined system. ' 'Try M.gauss_jordan_solve(rhs)') elif self.rows > self.cols: raise ValueError('For over-determined system, M, having ' 'more rows than columns, try M.solve_least_squares(rhs).') else: return self.inv(method=method)*rhs def subs(self, *args, **kwargs): # should mirror core.basic.subs """Return a new matrix with subs applied to each entry. Examples ======== >>> from sympy.abc import x, y >>> from sympy.matrices import SparseMatrix, Matrix >>> SparseMatrix(1, 1, [x]) Matrix([[x]]) >>> _.subs(x, y) Matrix([[y]]) >>> Matrix(_).subs(y, x) Matrix([[x]]) """ return self.applyfunc(lambda x: x.subs(*args, **kwargs)) def table(self, printer, rowstart='[', rowend=']', rowsep='\n', colsep=', ', align='right'): r""" String form of Matrix as a table. ``printer`` is the printer to use for on the elements (generally something like StrPrinter()) ``rowstart`` is the string used to start each row (by default '['). ``rowend`` is the string used to end each row (by default ']'). ``rowsep`` is the string used to separate rows (by default a newline). ``colsep`` is the string used to separate columns (by default ', '). ``align`` defines how the elements are aligned. Must be one of 'left', 'right', or 'center'. You can also use '<', '>', and '^' to mean the same thing, respectively. This is used by the string printer for Matrix. Examples ======== >>> from sympy import Matrix >>> from sympy.printing.str import StrPrinter >>> M = Matrix([[1, 2], [-33, 4]]) >>> printer = StrPrinter() >>> M.table(printer) '[ 1, 2]\n[-33, 4]' >>> print(M.table(printer)) [ 1, 2] [-33, 4] >>> print(M.table(printer, rowsep=',\n')) [ 1, 2], [-33, 4] >>> print('[%s]' % M.table(printer, rowsep=',\n')) [[ 1, 2], [-33, 4]] >>> print(M.table(printer, colsep=' ')) [ 1 2] [-33 4] >>> print(M.table(printer, align='center')) [ 1 , 2] [-33, 4] >>> print(M.table(printer, rowstart='{', rowend='}')) { 1, 2} {-33, 4} """ # Handle zero dimensions: if self.rows == 0 or self.cols == 0: return '[]' # Build table of string representations of the elements res = [] # Track per-column max lengths for pretty alignment maxlen = [0] * self.cols for i in range(self.rows): res.append([]) for j in range(self.cols): s = printer._print(self[i,j]) res[-1].append(s) maxlen[j] = max(len(s), maxlen[j]) # Patch strings together align = { 'left': 'ljust', 'right': 'rjust', 'center': 'center', '<': 'ljust', '>': 'rjust', '^': 'center', }[align] for i, row in enumerate(res): for j, elem in enumerate(row): row[j] = getattr(elem, align)(maxlen[j]) res[i] = rowstart + colsep.join(row) + rowend return rowsep.join(res) def trace(self): """ Returns the trace of a matrix i.e. the sum of the diagonal elements. Examples ======== >>> from sympy import Matrix >>> A = Matrix(2, 2, [1, 2, 3, 4]) >>> A.trace() 5 """ if not self.is_square: raise NonSquareMatrixError() return self._eval_trace() def transpose(self): """ Returns the transpose of the matrix. Examples ======== >>> from sympy import Matrix >>> A = Matrix(2, 2, [1, 2, 3, 4]) >>> A.transpose() Matrix([ [1, 3], [2, 4]]) """ return self._eval_transpose() T = property(transpose, None, None, "Matrix transposition.") C = property(conjugate, None, None, "By-element conjugation.") __matmul__ = __mul__ __rmatmul__ = __rmul__ def upper_triangular_solve(self, rhs): """Solves Ax = B, where A is an upper triangular matrix. See Also ======== lower_triangular_solve gauss_jordan_solve cholesky_solve diagonal_solve LDLsolve LUsolve QRsolve pinv_solve """ if not self.is_square: raise NonSquareMatrixError("Matrix must be square.") if rhs.rows != self.rows: raise TypeError("Matrix size mismatch.") if not self.is_upper: raise TypeError("Matrix is not upper triangular.") return self._upper_triangular_solve(rhs) n = evalf def values(self): """Return non-zero values of self.""" return [i for i in flatten(self.tolist()) if not i.is_zero] def vech(self, diagonal=True, check_symmetry=True): """Return the unique elements of a symmetric Matrix as a one column matrix by stacking the elements in the lower triangle. Arguments: diagonal -- include the diagonal cells of self or not check_symmetry -- checks symmetry of self but not completely reliably Examples ======== >>> from sympy import Matrix >>> m=Matrix([[1, 2], [2, 3]]) >>> m Matrix([ [1, 2], [2, 3]]) >>> m.vech() Matrix([ [1], [2], [3]]) >>> m.vech(diagonal=False) Matrix([[2]]) See Also ======== vec """ from sympy.matrices import zeros c = self.cols if c != self.rows: raise ShapeError("Matrix must be square") if check_symmetry: self.simplify() if self != self.transpose(): raise ValueError("Matrix appears to be asymmetric; consider check_symmetry=False") count = 0 if diagonal: v = zeros(c*(c + 1) // 2, 1) for j in range(c): for i in range(j, c): v[count] = self[i, j] count += 1 else: v = zeros(c*(c - 1) // 2, 1) for j in range(c): for i in range(j + 1, c): v[count] = self[i, j] count += 1 return v def vec(self): """Return the Matrix converted into a one column matrix by stacking columns Examples ======== >>> from sympy import Matrix >>> m=Matrix([[1, 3], [2, 4]]) >>> m Matrix([ [1, 3], [2, 4]]) >>> m.vec() Matrix([ [1], [2], [3], [4]]) See Also ======== vech """ return self.T.reshape(len(self), 1) @classmethod def vstack(cls, *args): """Return a matrix formed by joining args vertically (i.e. by repeated application of col_join). Examples ======== >>> from sympy.matrices import Matrix, eye >>> Matrix.vstack(eye(2), 2*eye(2)) Matrix([ [1, 0], [0, 1], [2, 0], [0, 2]]) """ return reduce(cls.col_join, args) def xreplace(self, rule): # should mirror core.basic.xreplace """Return a new matrix with xreplace applied to each entry. Examples ======== >>> from sympy.abc import x, y >>> from sympy.matrices import SparseMatrix, Matrix >>> SparseMatrix(1, 1, [x]) Matrix([[x]]) >>> _.xreplace({x: y}) Matrix([[y]]) >>> Matrix(_).xreplace({y: x}) Matrix([[x]]) """ return self.applyfunc(lambda x: x.xreplace(rule)) _eval_simplify = simplify charpoly = berkowitz_charpoly def classof(A, B): """ Get the type of the result when combining matrices of different types. Currently the strategy is that immutability is contagious. Examples ======== >>> from sympy import Matrix, ImmutableMatrix >>> from sympy.matrices.matrices import classof >>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix >>> IM = ImmutableMatrix([[1, 2], [3, 4]]) >>> classof(M, IM) <class 'sympy.matrices.immutable.ImmutableMatrix'> """ try: if A._class_priority > B._class_priority: return A.__class__ else: return B.__class__ except Exception: pass try: import numpy if isinstance(A, numpy.ndarray): return B.__class__ if isinstance(B, numpy.ndarray): return A.__class__ except Exception: pass raise TypeError("Incompatible classes %s, %s" % (A.__class__, B.__class__)) def a2idx(j, n=None): """Return integer after making positive and validating against n.""" if type(j) is not int: try: j = j.__index__() except AttributeError: raise IndexError("Invalid index a[%r]" % (j, )) if n is not None: if j < 0: j += n if not (j >= 0 and j < n): raise IndexError("Index out of range: a[%s]" % (j, )) return int(j) def _find_reasonable_pivot(col, iszerofunc=_iszero, simpfunc=_simplify): """ Find the lowest index of an item in `col` that is suitable for a pivot. If `col` consists only of Floats, the pivot with the largest norm is returned. Otherwise, the first element where `iszerofunc` returns False is used. If `iszerofunc` doesn't return false, items are simplified and retested until a suitable pivot is found. Returns a 4-tuple (pivot_offset, pivot_val, assumed_nonzero, newly_determined) where pivot_offset is the index of the pivot, pivot_val is the (possibly simplified) value of the pivot, assumed_nonzero is True if an assumption that the pivot was non-zero was made without being probed, and newly_determined are elements that were simplified during the process of pivot finding.""" newly_determined = [] col = list(col) # a column that contains a mix of floats and integers # but at least one float is considered a numerical # column, and so we do partial pivoting if all(isinstance(x, (Float, Integer)) for x in col) and any(isinstance(x, Float) for x in col): col_abs = [abs(x) for x in col] max_value = max(col_abs) if iszerofunc(max_value): # just because iszerofunc returned True, doesn't # mean the value is numerically zero. Make sure # to replace all entries with numerical zeros if max_value != 0: newly_determined = [(i, 0) for i,x in enumerate(col) if x != 0] return (None, None, False, newly_determined) index = col_abs.index(max_value) return (index, col[index], False, newly_determined) # PASS 1 (iszerofunc directly) possible_zeros = [] for i,x in enumerate(col): is_zero = iszerofunc(x) # is someone wrote a custom iszerofunc, it may return # BooleanFalse or BooleanTrue instead of True or False, # so use == for comparison instead of `is` if is_zero == False: # we found something that is definitely not zero return (i, x, False, newly_determined) possible_zeros.append(is_zero) # by this point, we've found no certain non-zeros if all(possible_zeros): # if everything is definitely zero, we have # no pivot return (None, None, False, newly_determined) # PASS 2 (iszerofunc after simplify) # we haven't found any for-sure non-zeros, so # go through the elements iszerofunc couldn't # make a determination about and opportunistically # simplify to see if we find something for i,x in enumerate(col): if possible_zeros[i] is not None: continue simped = simpfunc(x) is_zero = iszerofunc(simped) if is_zero == True or is_zero == False: newly_determined.append( (i, simped) ) if is_zero == False: return (i, simped, False, newly_determined) possible_zeros[i] = is_zero # after simplifying, some things that were recognized # as zeros might be zeros if all(possible_zeros): # if everything is definitely zero, we have # no pivot return (None, None, False, newly_determined) # PASS 3 (.equals(0)) # some expressions fail to simplify to zero, but # `.equals(0)` evaluates to True. As a last-ditch # attempt, apply `.equals` to these expressions for i,x in enumerate(col): if possible_zeros[i] is not None: continue if x.equals(S.Zero): # `.iszero` may return False with # an implicit assumption (e.g., `x.equals(0)` # when `x` is a symbol), so only treat it # as proved when `.equals(0)` returns True possible_zeros[i] = True newly_determined.append( (i, S.Zero) ) if all(possible_zeros): return (None, None, False, newly_determined) # at this point there is nothing that could definitely # be a pivot. To maintain compatibility with existing # behavior, we'll assume that an illdetermined thing is # non-zero. We should probably raise a warning in this case i = possible_zeros.index(None) return (i, col[i], True, newly_determined)
bsd-3-clause
bernardokyotoku/skillplant
settings.py
1
3712
# Initialize App Engine and import the default settings (DB backend, etc.). # If you want to use a different backend you have to remove all occurences # of "djangoappengine" from this file. try: from djangoappengine.settings_base import * has_djangoappengine = True except ImportError: has_djangoappengine = False DEBUG = True TEMPLATE_DEBUG = DEBUG import os #DATABASE_ENGINE = 'sqlite3' #DATABASE_NAME = 'Users/bernardo/Project/skillplant/db/data' #DATABASE_USER = '' # Not used with sqlite3. #DATABASE_PASSWORD = '' # Not used with sqlite3. #DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. #DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. # Uncomment the following if you want to use MongoDB # ----------------- #DATABASES = { # 'default': { # 'ENGINE': 'django_mongodb_engine.mongodb', # 'NAME': 'test', # 'USER': '', # 'PASSWORD': '', # 'HOST': 'localhost', # 'PORT': 27017, # 'SUPPORTS_TRANSACTIONS': False, # } #} # ----------------- SITE_NAME = '' SITE_DESCRIPTION = '' SITE_COPYRIGHT = '' DISQUS_SHORTNAME = '' GOOGLE_ANALYTICS_ID = '' # Get the ID from the CSE "Basics" control panel ("Search engine unique ID") GOOGLE_CUSTOM_SEARCH_ID = '' # Set RT username for retweet buttons TWITTER_USERNAME = '' # In order to always have uniform URLs in retweets and FeedBurner we redirect # any access to URLs that are not in ALLOWED_DOMAINS to the first allowed # domain. You can have additional domains for testing. ALLOWED_DOMAINS = () SECRET_KEY = '=r-$b*8hglm+858&9t043hlm6-&6-3d3vfc4((7yd0dbrakhvi' INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.contenttypes', 'django.contrib.sitemaps', 'djangotoolbox', 'socialauth', 'openid_consumer', 'addition', ) if has_djangoappengine: # djangoappengine should come last, so it can override a few manage.py commands INSTALLED_APPS += ('djangoappengine',) # This test runner captures stdout and associates tracebacks with their # corresponding output. Helps a lot with print-debugging. TEST_RUNNER = 'djangotoolbox.test.CapturingTestSuiteRunner' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'djangotoolbox.middleware.RedirectMiddleware', 'google.appengine.ext.appstats.recording.AppStatsDjangoMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'openid_consumer.middleware.OpenIDMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.request', 'django.core.context_processors.media', "socialauth.context_processors.facebook_api_key", ) TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),) ADMIN_MEDIA_PREFIX = '/media/admin/' ROOT_URLCONF = 'urls' NON_REDIRECTED_PATHS = ('/admin/',) ## Activate django-dbindexer if available try: import dbindexer DATABASES['native'] = DATABASES['default'] DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': 'native'} INSTALLED_APPS += ('dbindexer',) DBINDEXER_SITECONF = 'dbindexes' MIDDLEWARE_CLASSES = ('dbindexer.middleware.DBIndexerMiddleware',) + \ MIDDLEWARE_CLASSES except ImportError: pass try: from localsettings import * except ImportError: pass LOGIN_REDIRECT_URL = '/static/question.html' LOGOUT_REDIRECT_URL = '/' #SITE_ID = 29
bsd-3-clause
akhilari7/pa-dude
lib/python2.7/site-packages/oauthlib/oauth2/rfc6749/tokens.py
27
9306
""" oauthlib.oauth2.rfc6749.tokens ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains methods for adding two types of access tokens to requests. - Bearer http://tools.ietf.org/html/rfc6750 - MAC http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01 """ from __future__ import absolute_import, unicode_literals from binascii import b2a_base64 import hashlib import hmac try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse from oauthlib.common import add_params_to_uri, add_params_to_qs, unicode_type from oauthlib import common from . import utils class OAuth2Token(dict): def __init__(self, params, old_scope=None): super(OAuth2Token, self).__init__(params) self._new_scope = None if 'scope' in params: self._new_scope = set(utils.scope_to_list(params['scope'])) if old_scope is not None: self._old_scope = set(utils.scope_to_list(old_scope)) if self._new_scope is None: # the rfc says that if the scope hasn't changed, it's optional # in params so set the new scope to the old scope self._new_scope = self._old_scope else: self._old_scope = self._new_scope @property def scope_changed(self): return self._new_scope != self._old_scope @property def old_scope(self): return utils.list_to_scope(self._old_scope) @property def old_scopes(self): return list(self._old_scope) @property def scope(self): return utils.list_to_scope(self._new_scope) @property def scopes(self): return list(self._new_scope) @property def missing_scopes(self): return list(self._old_scope - self._new_scope) @property def additional_scopes(self): return list(self._new_scope - self._old_scope) def prepare_mac_header(token, uri, key, http_method, nonce=None, headers=None, body=None, ext='', hash_algorithm='hmac-sha-1', issue_time=None, draft=0): """Add an `MAC Access Authentication`_ signature to headers. Unlike OAuth 1, this HMAC signature does not require inclusion of the request payload/body, neither does it use a combination of client_secret and token_secret but rather a mac_key provided together with the access token. Currently two algorithms are supported, "hmac-sha-1" and "hmac-sha-256", `extension algorithms`_ are not supported. Example MAC Authorization header, linebreaks added for clarity Authorization: MAC id="h480djs93hd8", nonce="1336363200:dj83hs9s", mac="bhCQXTVyfj5cmA9uKkPFx1zeOXM=" .. _`MAC Access Authentication`: http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01 .. _`extension algorithms`: http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-7.1 :param uri: Request URI. :param headers: Request headers as a dictionary. :param http_method: HTTP Request method. :param key: MAC given provided by token endpoint. :param hash_algorithm: HMAC algorithm provided by token endpoint. :param issue_time: Time when the MAC credentials were issued (datetime). :param draft: MAC authentication specification version. :return: headers dictionary with the authorization field added. """ http_method = http_method.upper() host, port = utils.host_from_uri(uri) if hash_algorithm.lower() == 'hmac-sha-1': h = hashlib.sha1 elif hash_algorithm.lower() == 'hmac-sha-256': h = hashlib.sha256 else: raise ValueError('unknown hash algorithm') if draft == 0: nonce = nonce or '{0}:{1}'.format(utils.generate_age(issue_time), common.generate_nonce()) else: ts = common.generate_timestamp() nonce = common.generate_nonce() sch, net, path, par, query, fra = urlparse(uri) if query: request_uri = path + '?' + query else: request_uri = path # Hash the body/payload if body is not None and draft == 0: body = body.encode('utf-8') bodyhash = b2a_base64(h(body).digest())[:-1].decode('utf-8') else: bodyhash = '' # Create the normalized base string base = [] if draft == 0: base.append(nonce) else: base.append(ts) base.append(nonce) base.append(http_method.upper()) base.append(request_uri) base.append(host) base.append(port) if draft == 0: base.append(bodyhash) base.append(ext or '') base_string = '\n'.join(base) + '\n' # hmac struggles with unicode strings - http://bugs.python.org/issue5285 if isinstance(key, unicode_type): key = key.encode('utf-8') sign = hmac.new(key, base_string.encode('utf-8'), h) sign = b2a_base64(sign.digest())[:-1].decode('utf-8') header = [] header.append('MAC id="%s"' % token) if draft != 0: header.append('ts="%s"' % ts) header.append('nonce="%s"' % nonce) if bodyhash: header.append('bodyhash="%s"' % bodyhash) if ext: header.append('ext="%s"' % ext) header.append('mac="%s"' % sign) headers = headers or {} headers['Authorization'] = ', '.join(header) return headers def prepare_bearer_uri(token, uri): """Add a `Bearer Token`_ to the request URI. Not recommended, use only if client can't use authorization header or body. http://www.example.com/path?access_token=h480djs93hd8 .. _`Bearer Token`: http://tools.ietf.org/html/rfc6750 """ return add_params_to_uri(uri, [(('access_token', token))]) def prepare_bearer_headers(token, headers=None): """Add a `Bearer Token`_ to the request URI. Recommended method of passing bearer tokens. Authorization: Bearer h480djs93hd8 .. _`Bearer Token`: http://tools.ietf.org/html/rfc6750 """ headers = headers or {} headers['Authorization'] = 'Bearer %s' % token return headers def prepare_bearer_body(token, body=''): """Add a `Bearer Token`_ to the request body. access_token=h480djs93hd8 .. _`Bearer Token`: http://tools.ietf.org/html/rfc6750 """ return add_params_to_qs(body, [(('access_token', token))]) def random_token_generator(request, refresh_token=False): return common.generate_token() def signed_token_generator(private_pem, **kwargs): def signed_token_generator(request): request.claims = kwargs return common.generate_signed_token(private_pem, request) return signed_token_generator class TokenBase(object): def __call__(self, request, refresh_token=False): raise NotImplementedError('Subclasses must implement this method.') def validate_request(self, request): raise NotImplementedError('Subclasses must implement this method.') def estimate_type(self, request): raise NotImplementedError('Subclasses must implement this method.') class BearerToken(TokenBase): def __init__(self, request_validator=None, token_generator=None, expires_in=None, refresh_token_generator=None): self.request_validator = request_validator self.token_generator = token_generator or random_token_generator self.refresh_token_generator = ( refresh_token_generator or self.token_generator ) self.expires_in = expires_in or 3600 def create_token(self, request, refresh_token=False): """Create a BearerToken, by default without refresh token.""" if callable(self.expires_in): expires_in = self.expires_in(request) else: expires_in = self.expires_in request.expires_in = expires_in token = { 'access_token': self.token_generator(request), 'expires_in': expires_in, 'token_type': 'Bearer', } if request.scopes is not None: token['scope'] = ' '.join(request.scopes) if request.state is not None: token['state'] = request.state if refresh_token: if (request.refresh_token and not self.request_validator.rotate_refresh_token(request)): token['refresh_token'] = request.refresh_token else: token['refresh_token'] = self.refresh_token_generator(request) token.update(request.extra_credentials or {}) token = OAuth2Token(token) self.request_validator.save_bearer_token(token, request) return token def validate_request(self, request): token = None if 'Authorization' in request.headers: token = request.headers.get('Authorization')[7:] else: token = request.access_token return self.request_validator.validate_bearer_token( token, request.scopes, request) def estimate_type(self, request): if request.headers.get('Authorization', '').startswith('Bearer'): return 9 elif request.access_token is not None: return 5 else: return 0
mit
akhilaananthram/nupic.research
sensorimotor/sensorimotor/abstract_agent.py
4
4268
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import abc from prettytable import PrettyTable class AbstractAgent(object): __metaclass__ = abc.ABCMeta def __init__(self, world): """ @param world (AbstractWorld) The world this agent belongs in. """ self.world = world def sense(self): """ Returns the encoding of the sensor pattern at the current position (as indices of active bits) @return (set) Sensor pattern """ return self.world.universe.encodeSensorValue(self.getSensorValue()) @abc.abstractmethod def getSensorValue(self): """ Returns the sensor value at the current position @return (set) Sensor pattern """ return @abc.abstractmethod def chooseMotorValue(self): """ Return a plausible next motor value. @return (object) motor value (type depends on world) """ return @abc.abstractmethod def move(self, motorValue): """ Given a motor value, return an encoding of the motor command and move the agent based on that command. @param motorValue (object) Action to perform in world. Type depends on world. @return (set) Motor pattern """ return def generateSensorimotorSequence(self, length, verbosity=0): """ Generate a sensorimotor sequence of the given length through this agent's world. @param length (int) Length of sequence to generate @param verbosity (int) If > 0 print the sequence details @return (tuple) (sensor sequence, motor sequence, sensorimotor sequence) """ sensorSequence = [] motorSequence = [] sensorimotorSequence = [] sensorValues = [] motorCommands = [] for _ in xrange(length): sensorValues.append(self.getSensorValue()) sensorPattern = self.sense() motorValue = self.chooseMotorValue() motorCommands.append(motorValue) motorPattern = self.move(motorValue) sensorSequence.append(sensorPattern) motorSequence.append(motorPattern) sensorimotorPattern = (sensorPattern | set([x + self.world.universe.nSensor for x in motorPattern])) sensorimotorSequence.append(sensorimotorPattern) if verbosity > 1: print "Generating sensorimotor sequence for world:", self.world.toString() self._printSequence(sensorSequence, motorSequence, sensorValues, motorCommands) print return (sensorSequence, motorSequence, sensorimotorSequence) def _printSequence(self, sensorSequence, motorSequence, sensorValues, motorCommands): """ Nicely print the sequence to console for debugging purposes. """ table = PrettyTable(["#", "Sensor Pattern", "Motor Pattern", "Sensor Value", "Motor Value"]) for i in xrange(len(sensorSequence)): sensorPattern = sensorSequence[i] motorPattern = motorSequence[i] if sensorPattern is None: table.add_row([i, "<reset>", "<reset>"]) else: table.add_row([i, sorted(list(sensorPattern)), sorted(list(motorPattern)), self.world.universe.decodeSensorValue(sensorValues[i]), motorCommands[i]]) print table
gpl-3.0
nick-thompson/servo
tests/wpt/web-platform-tests/tools/webdriver/webdriver/driver.py
158
6732
"""Entry point for WebDriver.""" import alert import command import searchcontext import webelement import base64 class WebDriver(searchcontext.SearchContext): """Controls a web browser.""" def __init__(self, host, required, desired, mode='strict'): args = { 'desiredCapabilities': desired } if required: args['requiredCapabilities'] = required self._executor = command.CommandExecutor(host, mode) resp = self._executor.execute( 'POST', '/session', None, 'newSession', args) self.capabilities = resp['value'] self._session_id = resp['sessionId'] self.mode = mode def execute(self, method, path, name, parameters= None): """Execute a command against the current WebDriver session.""" data = self._executor.execute( method, '/session/' + self._session_id + path, self._session_id, name, parameters, self._object_hook) if data: return data['value'] def get(self, url): """Navigate to url.""" self.execute('POST', '/url', 'get', { 'url': url }) def get_current_url(self): """Get the current value of the location bar.""" return self.execute('GET', '/url', 'getCurrentUrl') def go_back(self): """Hit the browser back button.""" self.execute('POST', '/back', 'goBack') def go_forward(self): """Hit the browser forward button.""" self.execute('POST', '/forward', 'goForward') def refresh(self): """Refresh the current page in the browser.""" self.execute('POST', '/refresh', 'refresh') def quit(self): """Shutdown the current WebDriver session.""" self.execute('DELETE', '', 'quit') def get_window_handle(self): """Get the handle for the browser window/tab currently accepting commands. """ return self.execute('GET', '/window_handle', 'getWindowHandle') def get_window_handles(self): """Get handles for all open windows/tabs.""" return self.execute('GET', '/window_handles', 'getWindowHandles') def close(self): """Close the current tab or window. If this is the last tab or window, then this is the same as calling quit. """ self.execute('DELETE', '/window', 'close') def maximize_window(self): """Maximize the current window.""" return self._window_command('POST', '/maximize', 'maximize') def get_window_size(self): """Get the dimensions of the current window.""" result = self._window_command('GET', '/size', 'getWindowSize') return { 'height': result[height], 'width': result[width] } def set_window_size(self, height, width): """Set the size of the current window.""" self._window_command( 'POST', '/size', 'setWindowSize', { 'height': height, 'width': width}) def fullscreen_window(self): """Make the current window fullscreen.""" pass # implement when end point is defined def switch_to_window(self, name): """Switch to the window with the given handle or name.""" self.execute('POST', '/window', 'switchToWindow', { 'name': name }) def switch_to_frame(self, id): """Switch to a frame. id can be either a WebElement or an integer. """ self.execute('POST', '/frame', 'switchToFrame', { 'id': id}) def switch_to_parent_frame(self): """Move to the browsing context containing the currently selected frame. If in the top-level browsing context, this is a no-op. """ self.execute('POST', '/frame/parent', 'switchToParentFrame') def switch_to_alert(self): """Return an Alert object to interact with a modal dialog.""" alert_ = alert.Alert(self) alert_.get_text() return alert_ def execute_script(self, script, args=[]): """Execute a Javascript script in the current browsing context.""" return self.execute( 'POST', '/execute', 'executeScript', { 'script': script, 'args': args }) def execute_script_async(self, script, args=[]): """Execute a Javascript script in the current browsing context.""" return self.execute( 'POST', '/execute_async', 'executeScriptAsync', { 'script': script, 'args': args }) def take_screenshot(self, element=None): """Take a screenshot. If element is not provided, the screenshot should be of the current page, otherwise the screenshot should be of the given element. """ if self.mode == 'strict': pass # implement when endpoint is defined elif self.mode == 'compatibility': if element: pass # element screenshots are unsupported in compatibility else: return base64.standard_b64decode( self.execute('GET', '/screenshot', 'takeScreenshot')) def add_cookie(self, cookie): """Add a cookie to the browser.""" self.execute('POST', '/cookie', 'addCookie', { 'cookie': cookie }) def get_cookie(self, name = None): """Get the cookies accessible from the current page.""" if self.mode == 'compatibility': cookies = self.execute('GET', '/cookie', 'getCookie') if name: cookies_ = [] for cookie in cookies: if cookie['name'] == name: cookies_.append(cookie) return cookies_ return cookies elif self.mode == 'strict': pass # implement when wire protocol for this has been defined def set_implicit_timeout(self, ms): self._set_timeout('implicit', ms) def set_page_load_timeout(self, ms): self._set_timeout('page load', ms) def set_script_timeout(self, ms): self._set_timeout('script', ms) def _set_timeout(self, type, ms): params = { 'type': type, 'ms': ms } self.execute('POST', '/timeouts', 'timeouts', params) def _window_command(self, method, path, name, parameters = None): if self.mode == 'compatibility': return self.execute( method, '/window/current' + path, name, parameters) elif self.mode == 'strict': pass # implement this when end-points are defined in doc def _object_hook(self, obj): if 'ELEMENT' in obj: return webelement.WebElement(self, obj['ELEMENT']) return obj
mpl-2.0
Dziolas/invenio
modules/websearch/lib/websearch_external_collections_unit_tests.py
16
4127
# -*- coding: utf-8 -*- ## This file is part of Invenio. ## Copyright (C) 2006, 2007, 2008, 2010, 2011, 2013 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. """Testing functions for the external collections search. More tests of the page getter module can be done with websearch_external_collections_getter_tests.py """ __revision__ = "$Id$" from invenio.testutils import InvenioTestCase from invenio.websearch_external_collections_searcher import external_collections_dictionary from invenio.websearch_external_collections_getter import HTTPAsyncPageGetter, async_download from invenio.testutils import make_test_suite, run_test_suite, nottest def download_and_parse(): """Try to make a query that always return results on all search engines. Check that a page is well returned and that the result can be parsed. This test is not included in the general test suite. This test give false positive if any of the external server is non working or too slow. """ test = [['+', 'ieee', '', 'w']] errors = [] external_collections = external_collections_dictionary.values() urls = [engine.build_search_url(test) for engine in external_collections] pagegetters = [HTTPAsyncPageGetter(url) for url in urls] dummy = async_download(pagegetters, None, None, 30) for (page, engine, url) in zip(pagegetters, external_collections, urls): if not url: errors.append("Unable to build url for : " + engine.name) continue if len(page.data) == 0: errors.append("Zero sized page with : " + engine.name) continue if engine.parser: results = engine.parser.parse_and_get_results(page.data) num_results = engine.parser.parse_num_results() if len(results) == 0: errors.append("Unable to parse results for : " + engine.name) continue if not num_results: errors.append("Unable to parse (None returned) number of results for : " + engine.name) try: num_results = int(num_results) except: errors.append("Unable to parse (not a number) number of results for : " + engine.name) return errors @nottest def build_search_urls_test(): """Build some classical urls from basic_search_units.""" print "Testing external_search_engines build_search_url functions." tests = [ [['+', 'ellis', 'author', 'w'], ['+', 'unification', 'title', 'w'], ['-', 'Ross', 'author', 'w'], ['+', 'large', '', 'w'], ['-', 'helloworld', '', 'w']], [['+', 'ellis', 'author', 'w'], ['+', 'unification', 'title', 'w']], [['+', 'ellis', 'author', 'w']], [['-', 'Ross', 'author', 'w']] ] for engine in external_collections_dictionary.values(): print engine.name for test in tests: url = engine.build_search_url(test) print " Url: " + str(url) class ExtCollTests(InvenioTestCase): """Test cases for websearch_external_collections_*""" @nottest def test_download_and_parse(self): """websearch_external_collections - download_and_parse (not reliable, see docstring)""" self.assertEqual([], download_and_parse()) # FIXME: the above tests not plugged into global unit test suite TEST_SUITE = make_test_suite() #ExtCollTests,) if __name__ == "__main__": build_search_urls_test() run_test_suite(TEST_SUITE)
gpl-2.0
camradal/ansible
lib/ansible/modules/cloud/azure/azure.py
25
24565
#!/usr/bin/python # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'committer', 'version': '1.0'} DOCUMENTATION = ''' --- module: azure short_description: create or terminate a virtual machine in azure description: - Creates or terminates azure instances. When created optionally waits for it to be 'running'. version_added: "1.7" options: name: description: - name of the virtual machine and associated cloud service. required: true default: null location: description: - the azure location to use (e.g. 'East US') required: true default: null subscription_id: description: - azure subscription id. Overrides the AZURE_SUBSCRIPTION_ID environment variable. required: false default: null management_cert_path: description: - path to an azure management certificate associated with the subscription id. Overrides the AZURE_CERT_PATH environment variable. required: false default: null storage_account: description: - the azure storage account in which to store the data disks. required: true image: description: - system image for creating the virtual machine (e.g., b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu_DAILY_BUILD-precise-12_04_3-LTS-amd64-server-20131205-en-us-30GB) required: true default: null role_size: description: - azure role size for the new virtual machine (e.g., Small, ExtraLarge, A6). You have to pay attention to the fact that instances of type G and DS are not available in all regions (locations). Make sure if you selected the size and type of instance available in your chosen location. required: false default: Small endpoints: description: - a comma-separated list of TCP ports to expose on the virtual machine (e.g., "22,80") required: false default: 22 user: description: - the unix username for the new virtual machine. required: false default: null password: description: - the unix password for the new virtual machine. required: false default: null ssh_cert_path: description: - path to an X509 certificate containing the public ssh key to install in the virtual machine. See http://www.windowsazure.com/en-us/manage/linux/tutorials/intro-to-linux/ for more details. - if this option is specified, password-based ssh authentication will be disabled. required: false default: null virtual_network_name: description: - Name of virtual network. required: false default: null hostname: description: - hostname to write /etc/hostname. Defaults to <name>.cloudapp.net. required: false default: null wait: description: - wait for the instance to be in state 'running' before returning required: false default: "no" choices: [ "yes", "no" ] aliases: [] wait_timeout: description: - how long before wait gives up, in seconds default: 600 aliases: [] wait_timeout_redirects: description: - how long before wait gives up for redirects, in seconds default: 300 aliases: [] state: description: - create or terminate instances required: false default: 'present' aliases: [] auto_updates: description: - Enable Auto Updates on Windows Machines required: false version_added: "2.0" default: "no" choices: [ "yes", "no" ] enable_winrm: description: - Enable winrm on Windows Machines required: false version_added: "2.0" default: "yes" choices: [ "yes", "no" ] os_type: description: - The type of the os that is gettings provisioned required: false version_added: "2.0" default: "linux" choices: [ "windows", "linux" ] requirements: - "python >= 2.6" - "azure >= 0.7.1" author: "John Whitbeck (@jwhitbeck)" ''' EXAMPLES = ''' # Note: None of these examples set subscription_id or management_cert_path # It is assumed that their matching environment variables are set. - name: Provision virtual machine example azure: name: my-virtual-machine role_size: Small image: b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu_DAILY_BUILD-precise-12_04_3-LTS-amd64-server-20131205-en-us-30GB location: East US user: ubuntu ssh_cert_path: /path/to/azure_x509_cert.pem storage_account: my-storage-account wait: True state: present delegate_to: localhost - name: Terminate virtual machine example azure: name: my-virtual-machine state: absent delegate_to: localhost - name: Create windows machine azure: name: ben-Winows-23 hostname: win123 os_type: windows enable_winrm: True subscription_id: '{{ azure_sub_id }}' management_cert_path: '{{ azure_cert_path }}' role_size: Small image: bd507d3a70934695bc2128e3e5a255ba__RightImage-Windows-2012-x64-v13.5 location: East Asia password: xxx storage_account: benooytes user: admin wait: True state: present virtual_network_name: '{{ vnet_name }}' delegate_to: localhost ''' import base64 import datetime import os import time from urlparse import urlparse from ansible.module_utils.facts import * # TimeoutError AZURE_LOCATIONS = ['South Central US', 'Central US', 'East US 2', 'East US', 'West US', 'North Central US', 'North Europe', 'West Europe', 'East Asia', 'Southeast Asia', 'Japan West', 'Japan East', 'Brazil South'] AZURE_ROLE_SIZES = ['ExtraSmall', 'Small', 'Medium', 'Large', 'ExtraLarge', 'A5', 'A6', 'A7', 'A8', 'A9', 'Basic_A0', 'Basic_A1', 'Basic_A2', 'Basic_A3', 'Basic_A4', 'Standard_D1', 'Standard_D2', 'Standard_D3', 'Standard_D4', 'Standard_D11', 'Standard_D12', 'Standard_D13', 'Standard_D14', 'Standard_D1_v2', 'Standard_D2_v2', 'Standard_D3_v2', 'Standard_D4_v2', 'Standard_D5_v2', 'Standard_D11_v2', 'Standard_D12_v2', 'Standard_D13_v2', 'Standard_D14_v2', 'Standard_DS1', 'Standard_DS2', 'Standard_DS3', 'Standard_DS4', 'Standard_DS11', 'Standard_DS12', 'Standard_DS13', 'Standard_DS14', 'Standard_G1', 'Standard_G2', 'Standard_G3', 'Standard_G4', 'Standard_G5'] from distutils.version import LooseVersion try: import azure as windows_azure if hasattr(windows_azure, '__version__') and LooseVersion(windows_azure.__version__) <= "0.11.1": from azure import WindowsAzureError as AzureException from azure import WindowsAzureMissingResourceError as AzureMissingException else: from azure.common import AzureException as AzureException from azure.common import AzureMissingResourceHttpError as AzureMissingException from azure.servicemanagement import (ServiceManagementService, OSVirtualHardDisk, SSH, PublicKeys, PublicKey, LinuxConfigurationSet, ConfigurationSetInputEndpoints, ConfigurationSetInputEndpoint, Listener, WindowsConfigurationSet) HAS_AZURE = True except ImportError: HAS_AZURE = False from types import MethodType import json def _wait_for_completion(azure, promise, wait_timeout, msg): if not promise: return wait_timeout = time.time() + wait_timeout while wait_timeout > time.time(): operation_result = azure.get_operation_status(promise.request_id) time.sleep(5) if operation_result.status == "Succeeded": return raise AzureException('Timed out waiting for async operation ' + msg + ' "' + str(promise.request_id) + '" to complete.') def _delete_disks_when_detached(azure, wait_timeout, disk_names): def _handle_timeout(signum, frame): raise TimeoutError("Timeout reached while waiting for disks to become detached.") signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(wait_timeout) try: while len(disk_names) > 0: for disk_name in disk_names: disk = azure.get_disk(disk_name) if disk.attached_to is None: azure.delete_disk(disk.name, True) disk_names.remove(disk_name) except AzureException as e: module.fail_json(msg="failed to get or delete disk, error was: %s" % (disk_name, str(e))) finally: signal.alarm(0) def get_ssh_certificate_tokens(module, ssh_cert_path): """ Returns the sha1 fingerprint and a base64-encoded PKCS12 version of the certificate. """ # This returns a string such as SHA1 Fingerprint=88:60:0B:13:A9:14:47:DA:4E:19:10:7D:34:92:2B:DF:A1:7D:CA:FF rc, stdout, stderr = module.run_command(['openssl', 'x509', '-in', ssh_cert_path, '-fingerprint', '-noout']) if rc != 0: module.fail_json(msg="failed to generate the key fingerprint, error was: %s" % stderr) fingerprint = stdout.strip()[17:].replace(':', '') rc, stdout, stderr = module.run_command(['openssl', 'pkcs12', '-export', '-in', ssh_cert_path, '-nokeys', '-password', 'pass:']) if rc != 0: module.fail_json(msg="failed to generate the pkcs12 signature from the certificate, error was: %s" % stderr) pkcs12_base64 = base64.b64encode(stdout.strip()) return (fingerprint, pkcs12_base64) def create_virtual_machine(module, azure): """ Create new virtual machine module : AnsibleModule object azure: authenticated azure ServiceManagementService object Returns: True if a new virtual machine and/or cloud service was created, false otherwise """ name = module.params.get('name') os_type = module.params.get('os_type') hostname = module.params.get('hostname') or name + ".cloudapp.net" endpoints = module.params.get('endpoints').split(',') ssh_cert_path = module.params.get('ssh_cert_path') user = module.params.get('user') password = module.params.get('password') location = module.params.get('location') role_size = module.params.get('role_size') storage_account = module.params.get('storage_account') image = module.params.get('image') virtual_network_name = module.params.get('virtual_network_name') wait = module.params.get('wait') wait_timeout = int(module.params.get('wait_timeout')) changed = False # Check if a deployment with the same name already exists cloud_service_name_available = azure.check_hosted_service_name_availability(name) if cloud_service_name_available.result: # cloud service does not exist; create it try: result = azure.create_hosted_service(service_name=name, label=name, location=location) _wait_for_completion(azure, result, wait_timeout, "create_hosted_service") changed = True except AzureException as e: module.fail_json(msg="failed to create the new service, error was: %s" % str(e)) try: # check to see if a vm with this name exists; if so, do nothing azure.get_role(name, name, name) except AzureMissingException: # vm does not exist; create it if os_type == 'linux': # Create linux configuration disable_ssh_password_authentication = not password vm_config = LinuxConfigurationSet(hostname, user, password, disable_ssh_password_authentication) else: #Create Windows Config vm_config = WindowsConfigurationSet(hostname, password, None, module.params.get('auto_updates'), None, user) vm_config.domain_join = None if module.params.get('enable_winrm'): listener = Listener('Http') vm_config.win_rm.listeners.listeners.append(listener) else: vm_config.win_rm = None # Add ssh certificates if specified if ssh_cert_path: fingerprint, pkcs12_base64 = get_ssh_certificate_tokens(module, ssh_cert_path) # Add certificate to cloud service result = azure.add_service_certificate(name, pkcs12_base64, 'pfx', '') _wait_for_completion(azure, result, wait_timeout, "add_service_certificate") # Create ssh config ssh_config = SSH() ssh_config.public_keys = PublicKeys() authorized_keys_path = u'/home/%s/.ssh/authorized_keys' % user ssh_config.public_keys.public_keys.append(PublicKey(path=authorized_keys_path, fingerprint=fingerprint)) # Append ssh config to linux machine config vm_config.ssh = ssh_config # Create network configuration network_config = ConfigurationSetInputEndpoints() network_config.configuration_set_type = 'NetworkConfiguration' network_config.subnet_names = [] network_config.public_ips = None for port in endpoints: network_config.input_endpoints.append(ConfigurationSetInputEndpoint(name='TCP-%s' % port, protocol='TCP', port=port, local_port=port)) # First determine where to store disk today = datetime.date.today().strftime('%Y-%m-%d') disk_prefix = u'%s-%s' % (name, name) media_link = u'http://%s.blob.core.windows.net/vhds/%s-%s.vhd' % (storage_account, disk_prefix, today) # Create system hard disk os_hd = OSVirtualHardDisk(image, media_link) # Spin up virtual machine try: result = azure.create_virtual_machine_deployment(service_name=name, deployment_name=name, deployment_slot='production', label=name, role_name=name, system_config=vm_config, network_config=network_config, os_virtual_hard_disk=os_hd, role_size=role_size, role_type='PersistentVMRole', virtual_network_name=virtual_network_name) _wait_for_completion(azure, result, wait_timeout, "create_virtual_machine_deployment") changed = True except AzureException as e: module.fail_json(msg="failed to create the new virtual machine, error was: %s" % str(e)) try: deployment = azure.get_deployment_by_name(service_name=name, deployment_name=name) return (changed, urlparse(deployment.url).hostname, deployment) except AzureException as e: module.fail_json(msg="failed to lookup the deployment information for %s, error was: %s" % (name, str(e))) def terminate_virtual_machine(module, azure): """ Terminates a virtual machine module : AnsibleModule object azure: authenticated azure ServiceManagementService object Returns: True if a new virtual machine was deleted, false otherwise """ # Whether to wait for termination to complete before returning wait = module.params.get('wait') wait_timeout = int(module.params.get('wait_timeout')) name = module.params.get('name') delete_empty_services = module.params.get('delete_empty_services') changed = False deployment = None public_dns_name = None disk_names = [] try: deployment = azure.get_deployment_by_name(service_name=name, deployment_name=name) except AzureMissingException as e: pass # no such deployment or service except AzureException as e: module.fail_json(msg="failed to find the deployment, error was: %s" % str(e)) # Delete deployment if deployment: changed = True try: # gather disk info results = [] for role in deployment.role_list: role_props = azure.get_role(name, deployment.name, role.role_name) if role_props.os_virtual_hard_disk.disk_name not in disk_names: disk_names.append(role_props.os_virtual_hard_disk.disk_name) except AzureException as e: module.fail_json(msg="failed to get the role %s, error was: %s" % (role.role_name, str(e))) try: result = azure.delete_deployment(name, deployment.name) _wait_for_completion(azure, result, wait_timeout, "delete_deployment") except AzureException as e: module.fail_json(msg="failed to delete the deployment %s, error was: %s" % (deployment.name, str(e))) # It's unclear when disks associated with terminated deployment get detached. # Thus, until the wait_timeout is reached, we continue to delete disks as they # become detached by polling the list of remaining disks and examining the state. try: _delete_disks_when_detached(azure, wait_timeout, disk_names) except (AzureException, TimeoutError) as e: module.fail_json(msg=str(e)) try: # Now that the vm is deleted, remove the cloud service result = azure.delete_hosted_service(service_name=name) _wait_for_completion(azure, result, wait_timeout, "delete_hosted_service") except AzureException as e: module.fail_json(msg="failed to delete the service %s, error was: %s" % (name, str(e))) public_dns_name = urlparse(deployment.url).hostname return changed, public_dns_name, deployment def get_azure_creds(module): # Check module args for credentials, then check environment vars subscription_id = module.params.get('subscription_id') if not subscription_id: subscription_id = os.environ.get('AZURE_SUBSCRIPTION_ID', None) if not subscription_id: module.fail_json(msg="No subscription_id provided. Please set 'AZURE_SUBSCRIPTION_ID' or use the 'subscription_id' parameter") management_cert_path = module.params.get('management_cert_path') if not management_cert_path: management_cert_path = os.environ.get('AZURE_CERT_PATH', None) if not management_cert_path: module.fail_json(msg="No management_cert_path provided. Please set 'AZURE_CERT_PATH' or use the 'management_cert_path' parameter") return subscription_id, management_cert_path def main(): module = AnsibleModule( argument_spec=dict( ssh_cert_path=dict(), name=dict(), hostname=dict(), os_type=dict(default='linux', choices=['linux', 'windows']), location=dict(choices=AZURE_LOCATIONS), role_size=dict(choices=AZURE_ROLE_SIZES), subscription_id=dict(no_log=True), storage_account=dict(), management_cert_path=dict(), endpoints=dict(default='22'), user=dict(), password=dict(no_log=True), image=dict(), virtual_network_name=dict(default=None), state=dict(default='present'), wait=dict(type='bool', default=False), wait_timeout=dict(default=600), wait_timeout_redirects=dict(default=300), auto_updates=dict(type='bool', default=False), enable_winrm=dict(type='bool', default=True), ) ) if not HAS_AZURE: module.fail_json(msg='azure python module required for this module') # create azure ServiceManagementService object subscription_id, management_cert_path = get_azure_creds(module) wait_timeout_redirects = int(module.params.get('wait_timeout_redirects')) if hasattr(windows_azure, '__version__') and LooseVersion(windows_azure.__version__) <= "0.8.0": # wrapper for handling redirects which the sdk <= 0.8.0 is not following azure = Wrapper(ServiceManagementService(subscription_id, management_cert_path), wait_timeout_redirects) else: azure = ServiceManagementService(subscription_id, management_cert_path) cloud_service_raw = None if module.params.get('state') == 'absent': (changed, public_dns_name, deployment) = terminate_virtual_machine(module, azure) elif module.params.get('state') == 'present': # Changed is always set to true when provisioning new instances if not module.params.get('name'): module.fail_json(msg='name parameter is required for new instance') if not module.params.get('image'): module.fail_json(msg='image parameter is required for new instance') if not module.params.get('user'): module.fail_json(msg='user parameter is required for new instance') if not module.params.get('location'): module.fail_json(msg='location parameter is required for new instance') if not module.params.get('storage_account'): module.fail_json(msg='storage_account parameter is required for new instance') if not (module.params.get('password') or module.params.get('ssh_cert_path')): module.fail_json(msg='password or ssh_cert_path parameter is required for new instance') (changed, public_dns_name, deployment) = create_virtual_machine(module, azure) module.exit_json(changed=changed, public_dns_name=public_dns_name, deployment=json.loads(json.dumps(deployment, default=lambda o: o.__dict__))) class Wrapper(object): def __init__(self, obj, wait_timeout): self.other = obj self.wait_timeout = wait_timeout def __getattr__(self, name): if hasattr(self.other, name): func = getattr(self.other, name) return lambda *args, **kwargs: self._wrap(func, args, kwargs) raise AttributeError(name) def _wrap(self, func, args, kwargs): if isinstance(func, MethodType): result = self._handle_temporary_redirects(lambda: func(*args, **kwargs)) else: result = self._handle_temporary_redirects(lambda: func(self.other, *args, **kwargs)) return result def _handle_temporary_redirects(self, f): wait_timeout = time.time() + self.wait_timeout while wait_timeout > time.time(): try: return f() except AzureException as e: if not str(e).lower().find("temporary redirect") == -1: time.sleep(5) pass else: raise e # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
gpl-3.0
huntxu/neutron
neutron/tests/unit/db/test_agents_db.py
2
15790
# pylint: disable=pointless-string-statement # Copyright (c) 2013 OpenStack Foundation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import datetime import mock from neutron_lib import constants from neutron_lib import context from neutron_lib import exceptions as n_exc from oslo_config import cfg from oslo_db import exception as exc from oslo_utils import timeutils import testscenarios from neutron.db import agents_db from neutron.db import db_base_plugin_v2 as base_plugin from neutron.objects import agent as agent_obj from neutron.objects import base from neutron.tests.unit import testlib_api # the below code is required for the following reason # (as documented in testscenarios) """Multiply tests depending on their 'scenarios' attribute. This can be assigned to 'load_tests' in any test module to make this automatically work across tests in the module. """ load_tests = testscenarios.load_tests_apply_scenarios TEST_RESOURCE_VERSIONS = {"A": "1.0"} AGENT_STATUS = {'agent_type': 'Open vSwitch agent', 'binary': 'neutron-openvswitch-agent', 'host': 'overcloud-notcompute', 'topic': 'N/A', 'resource_versions': TEST_RESOURCE_VERSIONS} TEST_TIME = '2016-02-26T17:08:06.116' class FakePlugin(base_plugin.NeutronDbPluginV2, agents_db.AgentDbMixin): """A fake plugin class containing all DB methods.""" class TestAgentsDbBase(testlib_api.SqlTestCase): def setUp(self): super(TestAgentsDbBase, self).setUp() self.context = context.get_admin_context() self.plugin = FakePlugin() def _get_agents(self, hosts, agent_type): return [ agent_obj.Agent( context=self.context, binary='foo-agent', host=host, agent_type=agent_type, topic='foo_topic', configurations="{}", created_at=timeutils.utcnow(), started_at=timeutils.utcnow(), heartbeat_timestamp=timeutils.utcnow()) for host in hosts ] def _create_and_save_agents(self, hosts, agent_type, down_agents_count=0, down_but_version_considered=0): agents = self._get_agents(hosts, agent_type) # bring down the specified agents for agent in agents[:down_agents_count]: agent['heartbeat_timestamp'] -= datetime.timedelta(minutes=60) # bring down just enough so their version is still considered for agent in agents[down_agents_count:( down_but_version_considered + down_agents_count)]: agent['heartbeat_timestamp'] -= datetime.timedelta( seconds=(cfg.CONF.agent_down_time + 1)) for agent in agents: agent.create() return agents class TestAgentsDbMixin(TestAgentsDbBase): def setUp(self): super(TestAgentsDbMixin, self).setUp() self.agent_status = dict(AGENT_STATUS) def test_get_enabled_agent_on_host_found(self): agents = self._create_and_save_agents(['foo_host'], constants.AGENT_TYPE_L3) expected = self.plugin.get_enabled_agent_on_host( self.context, constants.AGENT_TYPE_L3, 'foo_host') self.assertEqual(expected, agents[0]) def test_get_enabled_agent_on_host_not_found(self): with mock.patch.object(agents_db.LOG, 'debug') as mock_log: agent = self.plugin.get_enabled_agent_on_host( self.context, constants.AGENT_TYPE_L3, 'foo_agent') self.assertIsNone(agent) self.assertTrue(mock_log.called) def _assert_ref_fields_are_equal(self, reference, result): """Compare (key, value) pairs of a reference dict with the result Note: the result MAY have additional keys """ for field, value in reference.items(): self.assertEqual(value, result[field], field) def test_create_or_update_agent_new_entry(self): self.plugin.create_or_update_agent(self.context, self.agent_status) agent = self.plugin.get_agents(self.context)[0] self._assert_ref_fields_are_equal(self.agent_status, agent) def test_create_or_update_agent_existing_entry(self): self.plugin.create_or_update_agent(self.context, self.agent_status) self.plugin.create_or_update_agent(self.context, self.agent_status) self.plugin.create_or_update_agent(self.context, self.agent_status) agents = self.plugin.get_agents(self.context) self.assertEqual(len(agents), 1) agent = agents[0] self._assert_ref_fields_are_equal(self.agent_status, agent) def test_create_or_update_agent_logs_heartbeat(self): status = self.agent_status.copy() status['configurations'] = {'log_agent_heartbeats': True} with mock.patch.object(agents_db.LOG, 'info') as info: self.plugin.create_or_update_agent(self.context, status) self.assertTrue(info.called) status['configurations'] = {'log_agent_heartbeats': False} info.reset_mock() self.plugin.create_or_update_agent(self.context, status) self.assertFalse(info.called) def test_create_or_update_agent_concurrent_insert(self): # NOTE(rpodolyaka): emulate violation of the unique constraint caused # by a concurrent insert. Ensure we make another # attempt on fail mock.patch( 'neutron.objects.base.NeutronDbObject.modify_fields_from_db' ).start() with mock.patch('neutron.objects.db.api.create_object') as add_mock: add_mock.side_effect = [ exc.DBDuplicateEntry(), mock.Mock() ] self.plugin.create_or_update_agent(self.context, self.agent_status) self.assertEqual(add_mock.call_count, 2, "Agent entry creation hasn't been retried") def test_create_or_update_agent_disable_new_agents(self): cfg.CONF.set_override('enable_new_agents', False) self.plugin.create_or_update_agent(self.context, self.agent_status) agent = self.plugin.get_agents(self.context)[0] self.assertFalse(agent['admin_state_up']) def test_agent_health_check(self): agents = [{'agent_type': "DHCP Agent", 'heartbeat_timestamp': '2015-05-06 22:40:40.432295', 'host': 'some.node', 'alive': True}] with mock.patch.object(self.plugin, 'get_agents', return_value=agents),\ mock.patch.object(agents_db.LOG, 'warning') as warn,\ mock.patch.object(agents_db.LOG, 'debug') as debug: self.plugin.agent_health_check() self.assertTrue(debug.called) self.assertFalse(warn.called) agents[0]['alive'] = False self.plugin.agent_health_check() warn.assert_called_once_with( mock.ANY, {'count': 1, 'total': 1, 'data': " Type Last heartbeat host\n" " DHCP Agent 2015-05-06 22:40:40.432295 some.node"} ) def test__get_dict(self): db_obj = mock.Mock(conf1='{"test": "1234"}') conf1 = self.plugin._get_dict(db_obj, 'conf1') self.assertIn('test', conf1) self.assertEqual("1234", conf1['test']) def test__get_dict_missing(self): with mock.patch.object(agents_db.LOG, 'warning') as warn: db_obj = mock.Mock(spec=['agent_type', 'host']) self.plugin._get_dict(db_obj, 'missing_conf') self.assertTrue(warn.called) def test__get_dict_ignore_missing(self): with mock.patch.object(agents_db.LOG, 'warning') as warn: db_obj = mock.Mock(spec=['agent_type', 'host']) missing_conf = self.plugin._get_dict(db_obj, 'missing_conf', ignore_missing=True) self.assertEqual({}, missing_conf) warn.assert_not_called() def test__get_dict_broken(self): with mock.patch.object(agents_db.LOG, 'warning') as warn: db_obj = mock.Mock(conf1='{"test": BROKEN') conf1 = self.plugin._get_dict(db_obj, 'conf1', ignore_missing=True) self.assertEqual({}, conf1) self.assertTrue(warn.called) def get_configurations_dict(self): db_obj = mock.Mock(configurations='{"cfg1": "val1"}') cfg = self.plugin.get_configuration_dict(db_obj) self.assertIn('cfg', cfg) def test_get_agents_resource_versions(self): tracker = mock.Mock() self._create_and_save_agents( ['host-%d' % i for i in range(5)], constants.AGENT_TYPE_L3, down_agents_count=3, down_but_version_considered=2) self.plugin.get_agents_resource_versions(tracker) self.assertEqual(tracker.set_versions.call_count, 2) class TestAgentsDbGetAgents(TestAgentsDbBase): scenarios = [ ('Get all agents', dict(agents=5, down_agents=2, agents_alive=None, expected_agents=5)), ('Get alive agents (True)', dict(agents=5, down_agents=2, agents_alive='True', expected_agents=3)), ('Get down agents (False)', dict(agents=5, down_agents=2, agents_alive='False', expected_agents=2)), ('Get alive agents (true)', dict(agents=5, down_agents=2, agents_alive='true', expected_agents=3)), ('Get down agents (false)', dict(agents=5, down_agents=2, agents_alive='false', expected_agents=2)), ('Get agents invalid alive filter', dict(agents=5, down_agents=2, agents_alive='invalid', expected_agents=None)), ] def setUp(self): # ensure that the first scenario will execute with nosetests if not hasattr(self, 'agents'): self.__dict__.update(self.scenarios[0][1]) super(TestAgentsDbGetAgents, self).setUp() def test_get_agents(self): hosts = ['host-%s' % i for i in range(self.agents)] self._create_and_save_agents(hosts, constants.AGENT_TYPE_L3, down_agents_count=self.down_agents) if self.agents_alive == 'invalid': self.assertRaises(n_exc.InvalidInput, self.plugin.get_agents, self.context, filters={'alive': [self.agents_alive]}) else: returned_agents = self.plugin.get_agents( self.context, filters={'alive': [self.agents_alive]} if self.agents_alive else None) self.assertEqual(self.expected_agents, len(returned_agents)) if self.agents_alive: alive = (self.agents_alive == 'True' or self.agents_alive == 'true') for agent in returned_agents: self.assertEqual(alive, agent['alive']) class TestAgentExtRpcCallback(TestAgentsDbBase): def setUp(self): super(TestAgentExtRpcCallback, self).setUp() self.callback = agents_db.AgentExtRpcCallback(self.plugin) self.callback.server_versions_rpc = mock.Mock() self.versions_rpc = self.callback.server_versions_rpc self.callback.START_TIME = datetime.datetime(datetime.MINYEAR, 1, 1) self.update_versions = mock.patch( 'neutron.api.rpc.callbacks.version_manager.' 'update_versions').start() self.agent_state = {'agent_state': dict(AGENT_STATUS)} def test_create_or_update_agent_updates_version_manager(self): self.callback.report_state(self.context, agent_state=self.agent_state, time=TEST_TIME) self.update_versions.assert_called_once_with( mock.ANY, TEST_RESOURCE_VERSIONS) def test_create_or_update_agent_updates_other_servers(self): callback = self.callback callback.report_state(self.context, agent_state=self.agent_state, time=TEST_TIME) report_agent_resource_versions = ( self.versions_rpc.report_agent_resource_versions) report_agent_resource_versions.assert_called_once_with( mock.ANY, mock.ANY, mock.ANY, TEST_RESOURCE_VERSIONS) def test_no_version_updates_on_further_state_reports(self): self.test_create_or_update_agent_updates_version_manager() # agents include resource_versions only in the first report after # start so versions should not be updated on the second report second_agent_state = copy.deepcopy(self.agent_state) second_agent_state['agent_state'].pop('resource_versions') self.update_versions.reset_mock() report_agent_resource_versions = ( self.versions_rpc.report_agent_resource_versions) report_agent_resource_versions.reset_mock() self.callback.report_state(self.context, agent_state=second_agent_state, time=TEST_TIME) self.assertFalse(self.update_versions.called) self.assertFalse(report_agent_resource_versions.called) def test_version_updates_on_agent_revival(self): self.test_create_or_update_agent_updates_version_manager() second_agent_state = copy.deepcopy(self.agent_state) second_agent_state['agent_state'].pop('resource_versions') self._take_down_agent() self.update_versions.reset_mock() report_agent_resource_versions = ( self.versions_rpc.report_agent_resource_versions) report_agent_resource_versions.reset_mock() # agent didn't include resource_versions in report but server will # take them from db for the revived agent self.callback.report_state(self.context, agent_state=second_agent_state, time=TEST_TIME) self.update_versions.assert_called_once_with( mock.ANY, TEST_RESOURCE_VERSIONS) report_agent_resource_versions.assert_called_once_with( mock.ANY, mock.ANY, mock.ANY, TEST_RESOURCE_VERSIONS) def _take_down_agent(self): with self.context.session.begin(subtransactions=True): pager = base.Pager(limit=1) agent_objs = agent_obj.Agent.get_objects(self.context, _pager=pager) agent_objs[0].heartbeat_timestamp = ( agent_objs[0].heartbeat_timestamp - datetime.timedelta( hours=1)) agent_objs[0].update()
apache-2.0
wargo32/DOTCoin
contrib/devtools/symbol-check.py
149
4348
#!/usr/bin/python # Copyright (c) 2014 Wladimir J. van der Laan # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' A script to check that the (Linux) executables produced by gitian only contain allowed gcc, glibc and libstdc++ version symbols. This makes sure they are still compatible with the minimum supported Linux distribution versions. Example usage: find ../gitian-builder/build -type f -executable | xargs python contrib/devtools/symbol-check.py ''' from __future__ import division, print_function import subprocess import re import sys # Debian 6.0.9 (Squeeze) has: # # - g++ version 4.4.5 (https://packages.debian.org/search?suite=default&section=all&arch=any&searchon=names&keywords=g%2B%2B) # - libc version 2.11.3 (https://packages.debian.org/search?suite=default&section=all&arch=any&searchon=names&keywords=libc6) # - libstdc++ version 4.4.5 (https://packages.debian.org/search?suite=default&section=all&arch=any&searchon=names&keywords=libstdc%2B%2B6) # # Ubuntu 10.04.4 (Lucid Lynx) has: # # - g++ version 4.4.3 (http://packages.ubuntu.com/search?keywords=g%2B%2B&searchon=names&suite=lucid&section=all) # - libc version 2.11.1 (http://packages.ubuntu.com/search?keywords=libc6&searchon=names&suite=lucid&section=all) # - libstdc++ version 4.4.3 (http://packages.ubuntu.com/search?suite=lucid&section=all&arch=any&keywords=libstdc%2B%2B&searchon=names) # # Taking the minimum of these as our target. # # According to GNU ABI document (http://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html) this corresponds to: # GCC 4.4.0: GCC_4.4.0 # GCC 4.4.2: GLIBCXX_3.4.13, CXXABI_1.3.3 # (glibc) GLIBC_2_11 # MAX_VERSIONS = { 'GCC': (4,4,0), 'CXXABI': (1,3,3), 'GLIBCXX': (3,4,13), 'GLIBC': (2,11) } # Ignore symbols that are exported as part of every executable IGNORE_EXPORTS = { '_edata', '_end', '_init', '__bss_start', '_fini' } READELF_CMD = '/usr/bin/readelf' CPPFILT_CMD = '/usr/bin/c++filt' class CPPFilt(object): ''' Demangle C++ symbol names. Use a pipe to the 'c++filt' command. ''' def __init__(self): self.proc = subprocess.Popen(CPPFILT_CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE) def __call__(self, mangled): self.proc.stdin.write(mangled + '\n') return self.proc.stdout.readline().rstrip() def close(self): self.proc.stdin.close() self.proc.stdout.close() self.proc.wait() def read_symbols(executable, imports=True): ''' Parse an ELF executable and return a list of (symbol,version) tuples for dynamic, imported symbols. ''' p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode: raise IOError('Could not read symbols for %s: %s' % (executable, stderr.strip())) syms = [] for line in stdout.split('\n'): line = line.split() if len(line)>7 and re.match('[0-9]+:$', line[0]): (sym, _, version) = line[7].partition('@') is_import = line[6] == 'UND' if version.startswith('@'): version = version[1:] if is_import == imports: syms.append((sym, version)) return syms def check_version(max_versions, version): if '_' in version: (lib, _, ver) = version.rpartition('_') else: lib = version ver = '0' ver = tuple([int(x) for x in ver.split('.')]) if not lib in max_versions: return False return ver <= max_versions[lib] if __name__ == '__main__': cppfilt = CPPFilt() retval = 0 for filename in sys.argv[1:]: # Check imported symbols for sym,version in read_symbols(filename, True): if version and not check_version(MAX_VERSIONS, version): print('%s: symbol %s from unsupported version %s' % (filename, cppfilt(sym), version)) retval = 1 # Check exported symbols for sym,version in read_symbols(filename, False): if sym in IGNORE_EXPORTS: continue print('%s: export of symbol %s not allowed' % (filename, cppfilt(sym))) retval = 1 exit(retval)
mit
RTHMaK/RPGOne
circleci-demo-python-flask-master/tests/test_api.py
33
10692
import unittest import json import re from base64 import b64encode from flask import url_for from app import create_app, db from app.models import User, Role, Post, Comment class APITestCase(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() Role.insert_roles() self.client = self.app.test_client() def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def get_api_headers(self, username, password): return { 'Authorization': 'Basic ' + b64encode( (username + ':' + password).encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json' } def test_404(self): response = self.client.get( '/wrong/url', headers=self.get_api_headers('email', 'password')) self.assertTrue(response.status_code == 404) json_response = json.loads(response.data.decode('utf-8')) self.assertTrue(json_response['error'] == 'not found') def test_no_auth(self): response = self.client.get(url_for('api.get_posts'), content_type='application/json') self.assertTrue(response.status_code == 200) def test_bad_auth(self): # add a user r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u = User(email='john@example.com', password='cat', confirmed=True, role=r) db.session.add(u) db.session.commit() # authenticate with bad password response = self.client.get( url_for('api.get_posts'), headers=self.get_api_headers('john@example.com', 'dog')) self.assertTrue(response.status_code == 401) def test_token_auth(self): # add a user r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u = User(email='john@example.com', password='cat', confirmed=True, role=r) db.session.add(u) db.session.commit() # issue a request with a bad token response = self.client.get( url_for('api.get_posts'), headers=self.get_api_headers('bad-token', '')) self.assertTrue(response.status_code == 401) # get a token response = self.client.get( url_for('api.get_token'), headers=self.get_api_headers('john@example.com', 'cat')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertIsNotNone(json_response.get('token')) token = json_response['token'] # issue a request with the token response = self.client.get( url_for('api.get_posts'), headers=self.get_api_headers(token, '')) self.assertTrue(response.status_code == 200) def test_anonymous(self): response = self.client.get( url_for('api.get_posts'), headers=self.get_api_headers('', '')) self.assertTrue(response.status_code == 200) def test_unconfirmed_account(self): # add an unconfirmed user r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u = User(email='john@example.com', password='cat', confirmed=False, role=r) db.session.add(u) db.session.commit() # get list of posts with the unconfirmed account response = self.client.get( url_for('api.get_posts'), headers=self.get_api_headers('john@example.com', 'cat')) self.assertTrue(response.status_code == 403) def test_posts(self): # add a user r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u = User(email='john@example.com', password='cat', confirmed=True, role=r) db.session.add(u) db.session.commit() # write an empty post response = self.client.post( url_for('api.new_post'), headers=self.get_api_headers('john@example.com', 'cat'), data=json.dumps({'body': ''})) self.assertTrue(response.status_code == 400) # write a post response = self.client.post( url_for('api.new_post'), headers=self.get_api_headers('john@example.com', 'cat'), data=json.dumps({'body': 'body of the *blog* post'})) self.assertTrue(response.status_code == 201) url = response.headers.get('Location') self.assertIsNotNone(url) # get the new post response = self.client.get( url, headers=self.get_api_headers('john@example.com', 'cat')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertTrue(json_response['url'] == url) self.assertTrue(json_response['body'] == 'body of the *blog* post') self.assertTrue(json_response['body_html'] == '<p>body of the <em>blog</em> post</p>') json_post = json_response # get the post from the user response = self.client.get( url_for('api.get_user_posts', id=u.id), headers=self.get_api_headers('john@example.com', 'cat')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertIsNotNone(json_response.get('posts')) self.assertTrue(json_response.get('count', 0) == 1) self.assertTrue(json_response['posts'][0] == json_post) # get the post from the user as a follower response = self.client.get( url_for('api.get_user_followed_posts', id=u.id), headers=self.get_api_headers('john@example.com', 'cat')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertIsNotNone(json_response.get('posts')) self.assertTrue(json_response.get('count', 0) == 1) self.assertTrue(json_response['posts'][0] == json_post) # edit post response = self.client.put( url, headers=self.get_api_headers('john@example.com', 'cat'), data=json.dumps({'body': 'updated body'})) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertTrue(json_response['url'] == url) self.assertTrue(json_response['body'] == 'updated body') self.assertTrue(json_response['body_html'] == '<p>updated body</p>') def test_users(self): # add two users r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u1 = User(email='john@example.com', username='john', password='cat', confirmed=True, role=r) u2 = User(email='susan@example.com', username='susan', password='dog', confirmed=True, role=r) db.session.add_all([u1, u2]) db.session.commit() # get users response = self.client.get( url_for('api.get_user', id=u1.id), headers=self.get_api_headers('susan@example.com', 'dog')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertTrue(json_response['username'] == 'john') response = self.client.get( url_for('api.get_user', id=u2.id), headers=self.get_api_headers('susan@example.com', 'dog')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertTrue(json_response['username'] == 'susan') def test_comments(self): # add two users r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u1 = User(email='john@example.com', username='john', password='cat', confirmed=True, role=r) u2 = User(email='susan@example.com', username='susan', password='dog', confirmed=True, role=r) db.session.add_all([u1, u2]) db.session.commit() # add a post post = Post(body='body of the post', author=u1) db.session.add(post) db.session.commit() # write a comment response = self.client.post( url_for('api.new_post_comment', id=post.id), headers=self.get_api_headers('susan@example.com', 'dog'), data=json.dumps({'body': 'Good [post](http://example.com)!'})) self.assertTrue(response.status_code == 201) json_response = json.loads(response.data.decode('utf-8')) url = response.headers.get('Location') self.assertIsNotNone(url) self.assertTrue(json_response['body'] == 'Good [post](http://example.com)!') self.assertTrue( re.sub('<.*?>', '', json_response['body_html']) == 'Good post!') # get the new comment response = self.client.get( url, headers=self.get_api_headers('john@example.com', 'cat')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertTrue(json_response['url'] == url) self.assertTrue(json_response['body'] == 'Good [post](http://example.com)!') # add another comment comment = Comment(body='Thank you!', author=u1, post=post) db.session.add(comment) db.session.commit() # get the two comments from the post response = self.client.get( url_for('api.get_post_comments', id=post.id), headers=self.get_api_headers('susan@example.com', 'dog')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertIsNotNone(json_response.get('comments')) self.assertTrue(json_response.get('count', 0) == 2) # get all the comments response = self.client.get( url_for('api.get_comments', id=post.id), headers=self.get_api_headers('susan@example.com', 'dog')) self.assertTrue(response.status_code == 200) json_response = json.loads(response.data.decode('utf-8')) self.assertIsNotNone(json_response.get('comments')) self.assertTrue(json_response.get('count', 0) == 2)
apache-2.0
pferreir/indico-backup
indico/MaKaC/plugins/EPayment/yellowPay/webinterface/urlHandlers.py
2
1885
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico 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. ## ## Indico 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 Indico;if not, see <http://www.gnu.org/licenses/>. from MaKaC.webinterface.urlHandlers import URLHandler as MainURLHandler from MaKaC.plugins.EPayment.yellowPay import MODULE_ID class EPURLHandler(MainURLHandler): _requestTag = '' @classmethod def getURL(cls, target=None): return super(EPURLHandler, cls).getURL(target, EPaymentName=MODULE_ID, requestTag=cls._requestTag) class UHConfModifEPayment(EPURLHandler): _endpoint = 'event_mgmt.confModifEpayment-modifModule' class UHConfModifEPaymentYellowPay( UHConfModifEPayment ): _requestTag = "modifYellowPay" class UHConfModifEPaymentYellowPayDataModif( UHConfModifEPayment ): _requestTag = "modifYellowPayData" class UHConfModifEPaymentYellowPayPerformDataModif( UHConfModifEPayment ): _requestTag = "modifYellowPayPerformDataModif" class UHPay(EPURLHandler): _endpoint = 'misc.payment' class UHPayConfirmYellowPay( UHPay ): _requestTag = "effectuer" class UHPayNotconfirmYellowPay( UHPay ): _requestTag = "noneffectuer" class UHPayCancelYellowPay( UHPay ): _requestTag = "annuler" class UHPayParamsYellowPay( UHPay ): _requestTag = "params"
gpl-3.0
bruth/django-tracking2
tracking/tests/test_middleware.py
1
5348
import re import sys import django from django.contrib.auth.models import User from django.test import TestCase try: from unittest.mock import patch except ImportError: from mock import patch from tracking.models import Visitor, Pageview if sys.version_info[0] == 3: def _u(s): return s else: def _u(s): return unicode(s) OLD_VERSION = django.VERSION < (1, 10) class MiddlewareTestCase(TestCase): @patch('tracking.middleware.warnings', autospec=True) def test_no_session(self, mock_warnings): # ignore if session middleware is not present tracking = 'tracking.middleware.VisitorTrackingMiddleware' middleware = 'MIDDLEWARE_CLASSES' if OLD_VERSION else 'MIDDLEWARE' with self.settings(**{middleware: [tracking]}): self.client.get('/') self.assertEqual(Visitor.objects.count(), 0) self.assertEqual(Pageview.objects.count(), 0) # verify warning was issued msg = 'VisitorTrackingMiddleware installed withoutSessionMiddleware' mock_warnings.warn.assert_called_once_with(msg, RuntimeWarning) @patch('tracking.middleware.TRACK_AJAX_REQUESTS', False) def test_no_track_ajax(self): # ignore ajax-based requests self.client.get('/', HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(Visitor.objects.count(), 0) self.assertEqual(Pageview.objects.count(), 0) @patch('tracking.middleware.TRACK_IGNORE_STATUS_CODES', [404]) def test_no_track_status(self): # ignore 404 pages self.client.get('invalid') self.assertEqual(Visitor.objects.count(), 0) self.assertEqual(Pageview.objects.count(), 0) @patch('tracking.middleware.TRACK_PAGEVIEWS', False) def test_no_track_pageviews(self): # make a non PAGEVIEW tracking request self.client.get('/') self.assertEqual(Visitor.objects.count(), 1) self.assertEqual(Pageview.objects.count(), 0) @patch('tracking.middleware.TRACK_PAGEVIEWS', True) def test_track_pageviews(self): self.client.get('/') self.assertEqual(Visitor.objects.count(), 1) self.assertEqual(Pageview.objects.count(), 1) def test_track_user_agent(self): self.client.get('/', HTTP_USER_AGENT='django') self.assertEqual(Visitor.objects.count(), 1) visitor = Visitor.objects.get() self.assertEqual(visitor.user_agent, 'django') def test_track_user_agent_unicode(self): self.client.get('/', HTTP_USER_AGENT=_u('django')) self.assertEqual(Visitor.objects.count(), 1) visitor = Visitor.objects.get() self.assertEqual(visitor.user_agent, 'django') def test_track_user_anon(self): self.client.get('/') self.assertEqual(Visitor.objects.count(), 1) visitor = Visitor.objects.get() self.assertEqual(visitor.user, None) def test_track_user_me(self): auth = {'username': 'me', 'password': 'me'} user = User.objects.create_user(**auth) self.assertTrue(self.client.login(**auth)) self.client.get('/') self.assertEqual(Visitor.objects.count(), 1) visitor = Visitor.objects.get() self.assertEqual(visitor.user, user) @patch('tracking.middleware.TRACK_ANONYMOUS_USERS', False) def test_track_anonymous_users(self): self.client.get('/') self.assertEqual(Visitor.objects.count(), 0) self.assertEqual(Pageview.objects.count(), 0) @patch('tracking.middleware.TRACK_SUPERUSERS', True) def test_track_superusers_true(self): auth = {'username': 'me', 'email': 'me@me.com', 'password': 'me'} User.objects.create_superuser(**auth) self.assertTrue(self.client.login(**auth)) self.client.get('/') self.assertEqual(Visitor.objects.count(), 1) self.assertEqual(Pageview.objects.count(), 1) @patch('tracking.middleware.TRACK_SUPERUSERS', False) def test_track_superusers_false(self): auth = {'username': 'me', 'email': 'me@me.com', 'password': 'me'} User.objects.create_superuser(**auth) self.assertTrue(self.client.login(**auth)) self.client.get('/') self.assertEqual(Visitor.objects.count(), 0) self.assertEqual(Pageview.objects.count(), 0) def test_track_ignore_url(self): ignore_urls = [re.compile('foo')] with patch('tracking.middleware.track_ignore_urls', ignore_urls): self.client.get('/') self.client.get('/foo/') # tracking turns a blind eye towards ignore_urls, no visitor, no view self.assertEqual(Visitor.objects.count(), 1) self.assertEqual(Pageview.objects.count(), 1) @patch('tracking.middleware.TRACK_PAGEVIEWS', True) @patch('tracking.middleware.TRACK_REFERER', True) @patch('tracking.middleware.TRACK_QUERY_STRING', True) def test_track_referer_string(self): self.client.get('/?foo=bar&baz=bin', HTTP_REFERER='http://foo/bar') # Vistor is still tracked, but page is not (in second case self.assertEqual(Visitor.objects.count(), 1) self.assertEqual(Pageview.objects.count(), 1) view = Pageview.objects.get() self.assertEqual(view.referer, 'http://foo/bar') self.assertEqual(view.query_string, 'foo=bar&baz=bin')
bsd-2-clause
DirectXMan12/nova-hacking
nova/cmd/baremetal_manage.py
4
7164
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # Interactive shell based on Django: # # Copyright (c) 2005, the Lawrence Journal-World # 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 Django 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ CLI interface for nova bare-metal management. """ import os import sys from oslo.config import cfg from nova import config from nova.openstack.common import cliutils from nova.openstack.common import log as logging from nova import version from nova.virt.baremetal.db import migration as bmdb_migration CONF = cfg.CONF # Decorators for actions def args(*args, **kwargs): def _decorator(func): func.__dict__.setdefault('args', []).insert(0, (args, kwargs)) return func return _decorator class BareMetalDbCommands(object): """Class for managing the bare-metal database.""" def __init__(self): pass @args('--version', dest='version', metavar='<version>', help='Bare-metal Database version') def sync(self, version=None): """Sync the database up to the most recent version.""" bmdb_migration.db_sync(version) def version(self): """Print the current database version.""" v = bmdb_migration.db_version() print(v) # return for unittest return v CATEGORIES = { 'db': BareMetalDbCommands, } def methods_of(obj): """Get all callable methods of an object that don't start with underscore. returns a list of tuples of the form (method_name, method) """ result = [] for i in dir(obj): if callable(getattr(obj, i)) and not i.startswith('_'): result.append((i, getattr(obj, i))) return result def add_command_parsers(subparsers): parser = subparsers.add_parser('bash-completion') parser.add_argument('query_category', nargs='?') for category in CATEGORIES: command_object = CATEGORIES[category]() parser = subparsers.add_parser(category) parser.set_defaults(command_object=command_object) category_subparsers = parser.add_subparsers(dest='action') for (action, action_fn) in methods_of(command_object): parser = category_subparsers.add_parser(action) action_kwargs = [] for args, kwargs in getattr(action_fn, 'args', []): action_kwargs.append(kwargs['dest']) kwargs['dest'] = 'action_kwarg_' + kwargs['dest'] parser.add_argument(*args, **kwargs) parser.set_defaults(action_fn=action_fn) parser.set_defaults(action_kwargs=action_kwargs) parser.add_argument('action_args', nargs='*') category_opt = cfg.SubCommandOpt('category', title='Command categories', help='Available categories', handler=add_command_parsers) def main(): """Parse options and call the appropriate class/method.""" CONF.register_cli_opt(category_opt) try: config.parse_args(sys.argv) logging.setup("nova") except cfg.ConfigFilesNotFoundError: cfgfile = CONF.config_file[-1] if CONF.config_file else None if cfgfile and not os.access(cfgfile, os.R_OK): st = os.stat(cfgfile) print(_("Could not read %s. Re-running with sudo") % cfgfile) try: os.execvp('sudo', ['sudo', '-u', '#%s' % st.st_uid] + sys.argv) except Exception: print(_('sudo failed, continuing as if nothing happened')) print(_('Please re-run nova-manage as root.')) return(2) if CONF.category.name == "version": print(version.version_string_with_package()) return(0) if CONF.category.name == "bash-completion": if not CONF.category.query_category: print(" ".join(CATEGORIES.keys())) elif CONF.category.query_category in CATEGORIES: fn = CATEGORIES[CONF.category.query_category] command_object = fn() actions = methods_of(command_object) print(" ".join([k for (k, v) in actions])) return(0) fn = CONF.category.action_fn fn_args = [arg.decode('utf-8') for arg in CONF.category.action_args] fn_kwargs = {} for k in CONF.category.action_kwargs: v = getattr(CONF.category, 'action_kwarg_' + k) if v is None: continue if isinstance(v, basestring): v = v.decode('utf-8') fn_kwargs[k] = v # call the action with the remaining arguments # check arguments try: cliutils.validate_args(fn, *fn_args, **fn_kwargs) except cliutils.MissingArgs as e: print(fn.__doc__) print(e) return(1) try: fn(*fn_args, **fn_kwargs) return(0) except Exception: print(_("Command failed, please check log for more info")) raise
apache-2.0
awesto/djangocms-carousel
ci/appveyor-bootstrap.py
18
4205
""" AppVeyor will at least have few Pythons around so there's no point of implementing a bootstrapper in PowerShell. This is a port of https://github.com/pypa/python-packaging-user-guide/blob/master/source/code/install.ps1 with various fixes and improvements that just weren't feasible to implement in PowerShell. """ from __future__ import print_function from os import environ from os.path import exists from subprocess import CalledProcessError from subprocess import check_call try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve BASE_URL = "https://www.python.org/ftp/python/" GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py" GET_PIP_PATH = "C:\get-pip.py" URLS = { ("2.7", "64"): BASE_URL + "2.7.10/python-2.7.10.amd64.msi", ("2.7", "32"): BASE_URL + "2.7.10/python-2.7.10.msi", # NOTE: no .msi installer for 3.3.6 ("3.3", "64"): BASE_URL + "3.3.3/python-3.3.3.amd64.msi", ("3.3", "32"): BASE_URL + "3.3.3/python-3.3.3.msi", ("3.4", "64"): BASE_URL + "3.4.3/python-3.4.3.amd64.msi", ("3.4", "32"): BASE_URL + "3.4.3/python-3.4.3.msi", ("3.5", "64"): BASE_URL + "3.5.0/python-3.5.0-amd64.exe", ("3.5", "32"): BASE_URL + "3.5.0/python-3.5.0.exe", } INSTALL_CMD = { # Commands are allowed to fail only if they are not the last command. Eg: uninstall (/x) allowed to fail. "2.7": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"], ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]], "3.3": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"], ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]], "3.4": [["msiexec.exe", "/L*+!", "install.log", "/qn", "/x", "{path}"], ["msiexec.exe", "/L*+!", "install.log", "/qn", "/i", "{path}", "TARGETDIR={home}"]], "3.5": [["{path}", "/quiet", "TargetDir={home}"]], } def download_file(url, path): print("Downloading: {} (into {})".format(url, path)) progress = [0, 0] def report(count, size, total): progress[0] = count * size if progress[0] - progress[1] > 1000000: progress[1] = progress[0] print("Downloaded {:,}/{:,} ...".format(progress[1], total)) dest, _ = urlretrieve(url, path, reporthook=report) return dest def install_python(version, arch, home): print("Installing Python", version, "for", arch, "bit architecture to", home) if exists(home): return path = download_python(version, arch) print("Installing", path, "to", home) success = False for cmd in INSTALL_CMD[version]: cmd = [part.format(home=home, path=path) for part in cmd] print("Running:", " ".join(cmd)) try: check_call(cmd) except CalledProcessError as exc: print("Failed command", cmd, "with:", exc) if exists("install.log"): with open("install.log") as fh: print(fh.read()) else: success = True if success: print("Installation complete!") else: print("Installation failed") def download_python(version, arch): for _ in range(3): try: return download_file(URLS[version, arch], "installer.exe") except Exception as exc: print("Failed to download:", exc) print("Retrying ...") def install_pip(home): pip_path = home + "/Scripts/pip.exe" python_path = home + "/python.exe" if exists(pip_path): print("pip already installed.") else: print("Installing pip...") download_file(GET_PIP_URL, GET_PIP_PATH) print("Executing:", python_path, GET_PIP_PATH) check_call([python_path, GET_PIP_PATH]) def install_packages(home, *packages): cmd = [home + "/Scripts/pip.exe", "install"] cmd.extend(packages) check_call(cmd) if __name__ == "__main__": install_python(environ['PYTHON_VERSION'], environ['PYTHON_ARCH'], environ['PYTHON_HOME']) install_pip(environ['PYTHON_HOME']) install_packages(environ['PYTHON_HOME'], "setuptools>=18.0.1", "wheel", "tox", "virtualenv>=13.1.0")
mit
les69/calvin-base
calvin/actorstore/systemactors/json/FbPictureJson.py
1
1254
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # encoding: utf-8 from calvin.actor.actor import Actor, ActionResult, manage, condition, guard class FbPictureJson(Actor): """ Create a json for a photo status on Facebook Inputs: message: just a string picture: string path Outputs: json: the relative json file """ @manage(['']) def init(self): self.message = None self.picture = None @condition(['picture', 'message'], ['json']) def produce_json(self, picture, message): res = {'picture' : picture, 'message' : message} return ActionResult(production=(res, )) action_priority = (produce_json,)
apache-2.0
jswope00/GAI
lms/djangoapps/bulk_email/migrations/0007_load_course_email_template.py
182
5602
# -*- coding: utf-8 -*- from south.v2 import DataMigration class Migration(DataMigration): def forwards(self, orm): "Load data from fixture." from django.core.management import call_command call_command("loaddata", "course_email_template.json") def backwards(self, orm): "Perform a no-op to go backwards." pass models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'bulk_email.courseemail': { 'Meta': {'object_name': 'CourseEmail'}, 'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'html_message': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'sender': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.CharField', [], {'max_length': '128', 'db_index': 'True'}), 'subject': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'text_message': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'to_option': ('django.db.models.fields.CharField', [], {'default': "'myself'", 'max_length': '64'}) }, 'bulk_email.courseemailtemplate': { 'Meta': {'object_name': 'CourseEmailTemplate'}, 'html_template': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'plain_template': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}) }, 'bulk_email.optout': { 'Meta': {'unique_together': "(('user', 'course_id'),)", 'object_name': 'Optout'}, 'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) } } complete_apps = ['bulk_email'] symmetrical = True
agpl-3.0
valentin-krasontovitsch/ansible
lib/ansible/modules/cloud/scaleway/scaleway_volume_facts.py
48
2704
#!/usr/bin/python # -*- coding: utf-8 -*- # # (c) 2018, Yanis Guenane <yanis+ansible@guenane.org> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: scaleway_volume_facts short_description: Gather facts about the Scaleway volumes available. description: - Gather facts about the Scaleway volumes available. version_added: "2.7" author: - "Yanis Guenane (@Spredzy)" - "Remy Leone (@sieben)" extends_documentation_fragment: scaleway options: region: version_added: "2.8" description: - Scaleway region to use (for example par1). required: true choices: - ams1 - EMEA-NL-EVS - par1 - EMEA-FR-PAR1 ''' EXAMPLES = r''' - name: Gather Scaleway volumes facts scaleway_volume_facts: region: par1 ''' RETURN = r''' --- scaleway_volume_facts: description: Response from Scaleway API returned: success type: complex contains: "scaleway_volume_facts": [ { "creation_date": "2018-08-14T20:56:24.949660+00:00", "export_uri": null, "id": "b8d51a06-daeb-4fef-9539-a8aea016c1ba", "modification_date": "2018-08-14T20:56:24.949660+00:00", "name": "test-volume", "organization": "3f709602-5e6c-4619-b80c-e841c89734af", "server": null, "size": 50000000000, "state": "available", "volume_type": "l_ssd" } ] ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.scaleway import ( Scaleway, ScalewayException, scaleway_argument_spec, SCALEWAY_LOCATION) class ScalewayVolumeFacts(Scaleway): def __init__(self, module): super(ScalewayVolumeFacts, self).__init__(module) self.name = 'volumes' region = module.params["region"] self.module.params['api_url'] = SCALEWAY_LOCATION[region]["api_endpoint"] def main(): argument_spec = scaleway_argument_spec() argument_spec.update(dict( region=dict(required=True, choices=SCALEWAY_LOCATION.keys()), )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) try: module.exit_json( ansible_facts={'scaleway_volume_facts': ScalewayVolumeFacts(module).get_resources()} ) except ScalewayException as exc: module.fail_json(msg=exc.message) if __name__ == '__main__': main()
gpl-3.0
tangfeixiong/nova
nova/tests/functional/v3/test_quota_classes.py
33
2212
# Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg from nova.tests.functional.v3 import api_sample_base CONF = cfg.CONF CONF.import_opt('osapi_compute_extension', 'nova.api.openstack.compute.extensions') class QuotaClassesSampleJsonTests(api_sample_base.ApiSampleTestBaseV3): ADMIN_API = True extension_name = "os-quota-class-sets" set_id = 'test_class' # TODO(Park): Overriding '_api_version' till all functional tests # are merged between v2 and v2.1. After that base class variable # itself can be changed to 'v2' _api_version = 'v2' def _get_flags(self): f = super(QuotaClassesSampleJsonTests, self)._get_flags() f['osapi_compute_extension'] = CONF.osapi_compute_extension[:] f['osapi_compute_extension'].append( 'nova.api.openstack.compute.contrib.quota_classes.' 'Quota_classes') return f def test_show_quota_classes(self): # Get api sample to show quota classes. response = self._do_get('os-quota-class-sets/%s' % self.set_id) subs = {'set_id': self.set_id} self._verify_response('quota-classes-show-get-resp', subs, response, 200) def test_update_quota_classes(self): # Get api sample to update quota classes. response = self._do_put('os-quota-class-sets/%s' % self.set_id, 'quota-classes-update-post-req', {}) self._verify_response('quota-classes-update-post-resp', {}, response, 200)
apache-2.0
zahodi/ansible
lib/ansible/modules/monitoring/boundary_meter.py
14
8517
#!/usr/bin/python # -*- coding: utf-8 -*- """ Ansible module to add boundary meters. (c) 2013, curtis <curtis@serverascode.com> This file is part of Ansible Ansible 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. Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. """ ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' module: boundary_meter short_description: Manage boundary meters description: - This module manages boundary meters version_added: "1.3" author: "curtis (@ccollicutt)" requirements: - Boundary API access - bprobe is required to send data, but not to register a meter options: name: description: - meter name required: true state: description: - Whether to create or remove the client from boundary required: false default: true choices: ["present", "absent"] apiid: description: - Organizations boundary API ID required: true apikey: description: - Organizations boundary API KEY required: true validate_certs: description: - If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. required: false default: 'yes' choices: ['yes', 'no'] version_added: 1.5.1 notes: - This module does not yet support boundary tags. ''' EXAMPLES=''' - name: Create meter boundary_meter: apiid: AAAAAA apikey: BBBBBB state: present name: '{{ inventory_hostname }}' - name: Delete meter boundary_meter: apiid: AAAAAA apikey: BBBBBB state: absent name: '{{ inventory_hostname }}' ''' import base64 import os try: import json except ImportError: try: import simplejson as json except ImportError: # Let snippet from module_utils/basic.py return a proper error in this case pass from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import fetch_url api_host = "api.boundary.com" config_directory = "/etc/bprobe" # "resource" like thing or apikey? def auth_encode(apikey): auth = base64.standard_b64encode(apikey) auth.replace("\n", "") return auth def build_url(name, apiid, action, meter_id=None, cert_type=None): if action == "create": return 'https://%s/%s/meters' % (api_host, apiid) elif action == "search": return "https://%s/%s/meters?name=%s" % (api_host, apiid, name) elif action == "certificates": return "https://%s/%s/meters/%s/%s.pem" % (api_host, apiid, meter_id, cert_type) elif action == "tags": return "https://%s/%s/meters/%s/tags" % (api_host, apiid, meter_id) elif action == "delete": return "https://%s/%s/meters/%s" % (api_host, apiid, meter_id) def http_request(module, name, apiid, apikey, action, data=None, meter_id=None, cert_type=None): if meter_id is None: url = build_url(name, apiid, action) else: if cert_type is None: url = build_url(name, apiid, action, meter_id) else: url = build_url(name, apiid, action, meter_id, cert_type) headers = dict() headers["Authorization"] = "Basic %s" % auth_encode(apikey) headers["Content-Type"] = "application/json" return fetch_url(module, url, data=data, headers=headers) def create_meter(module, name, apiid, apikey): meters = search_meter(module, name, apiid, apikey) if len(meters) > 0: # If the meter already exists, do nothing module.exit_json(status="Meter " + name + " already exists",changed=False) else: # If it doesn't exist, create it body = '{"name":"' + name + '"}' response, info = http_request(module, name, apiid, apikey, data=body, action="create") if info['status'] != 200: module.fail_json(msg="Failed to connect to api host to create meter") # If the config directory doesn't exist, create it if not os.path.exists(config_directory): try: os.makedirs(config_directory) except: module.fail_json("Could not create " + config_directory) # Download both cert files from the api host types = ['key', 'cert'] for cert_type in types: try: # If we can't open the file it's not there, so we should download it cert_file = open('%s/%s.pem' % (config_directory,cert_type)) except IOError: # Now download the file... rc = download_request(module, name, apiid, apikey, cert_type) if rc == False: module.fail_json("Download request for " + cert_type + ".pem failed") return 0, "Meter " + name + " created" def search_meter(module, name, apiid, apikey): response, info = http_request(module, name, apiid, apikey, action="search") if info['status'] != 200: module.fail_json("Failed to connect to api host to search for meter") # Return meters return json.loads(response.read()) def get_meter_id(module, name, apiid, apikey): # In order to delete the meter we need its id meters = search_meter(module, name, apiid, apikey) if len(meters) > 0: return meters[0]['id'] else: return None def delete_meter(module, name, apiid, apikey): meter_id = get_meter_id(module, name, apiid, apikey) if meter_id is None: return 1, "Meter does not exist, so can't delete it" else: response, info = http_request(module, name, apiid, apikey, action, meter_id) if info['status'] != 200: module.fail_json("Failed to delete meter") # Each new meter gets a new key.pem and ca.pem file, so they should be deleted types = ['cert', 'key'] for cert_type in types: try: cert_file = '%s/%s.pem' % (config_directory,cert_type) os.remove(cert_file) except OSError: module.fail_json("Failed to remove " + cert_type + ".pem file") return 0, "Meter " + name + " deleted" def download_request(module, name, apiid, apikey, cert_type): meter_id = get_meter_id(module, name, apiid, apikey) if meter_id is not None: action = "certificates" response, info = http_request(module, name, apiid, apikey, action, meter_id, cert_type) if info['status'] != 200: module.fail_json("Failed to connect to api host to download certificate") if result: try: cert_file_path = '%s/%s.pem' % (config_directory,cert_type) body = response.read() cert_file = open(cert_file_path, 'w') cert_file.write(body) cert_file.close() os.chmod(cert_file_path, int('0600', 8)) except: module.fail_json("Could not write to certificate file") return True else: module.fail_json("Could not get meter id") def main(): module = AnsibleModule( argument_spec=dict( state=dict(required=True, choices=['present', 'absent']), name=dict(required=False), apikey=dict(required=True), apiid=dict(required=True), validate_certs = dict(default='yes', type='bool'), ) ) state = module.params['state'] name= module.params['name'] apikey = module.params['api_key'] apiid = module.params['api_id'] if state == "present": (rc, result) = create_meter(module, name, apiid, apikey) if state == "absent": (rc, result) = delete_meter(module, name, apiid, apikey) if rc != 0: module.fail_json(msg=result) module.exit_json(status=result,changed=True) if __name__ == '__main__': main()
gpl-3.0
plilja/adventofcode
2018/day13/day13.py
1
1914
import sys def step1(inp): crashes, remaining = solve(inp, lambda num_carts: 1) return crashes[0] def step2(inp): crashes, remaining = solve(inp, lambda num_carts: num_carts // 2) return remaining[0] def solve(inp, num_crashes_allowed_func): # parse carts carts = {} for y in range(0, len(inp)): for x in range(0, len(inp[y])): c = inp[y][x] if c == '<': carts[(x, y)] = (-1, 0, 0) elif c == '>': carts[(x, y)] = (1, 0, 0) elif c == '^': carts[(x, y)] = (0, -1, 0) elif c == 'v': carts[(x, y)] = (0, 1, 0) crashes = [] num_crashes_allowed = num_crashes_allowed_func(len(carts.keys())) while len(crashes) < num_crashes_allowed: for (x, y) in sorted(carts.keys(), key=lambda c: (c[1], c[0])): if (x, y) not in carts: # has crashed in previous loop step continue c = inp[y][x] dx, dy, turns = carts[(x, y)] if c == '+': r = [(1, 0), (0, 1), (-1, 0), (0, -1)] idx = r.index((-dx, -dy)) # Idx of previous place dx, dy = r[(idx + 1 + (turns % 3)) % 4] turns += 1 elif c == '\\': dx, dy = dy, dx elif c == '/': dx, dy = -dy, -dx else: assert c in ['-', '<', '>', '|', '^', 'v'] # dx, dy is unchanged x2 = x + dx y2 = y + dy if (x2, y2) in carts: del carts[(x, y)] del carts[(x2, y2)] crashes.append((x2, y2)) else: del carts[(x, y)] carts[(x2, y2)] = (dx, dy, turns) return crashes, list(carts.keys()) inp = sys.stdin.readlines() print(step1(inp)) print(step2(inp))
gpl-3.0
yjmade/odoo
addons/mrp/__init__.py
437
1165
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import mrp import stock import product import wizard import report import company import procurement import res_config # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
chushao/Gradesource-Uploader
requests/exceptions.py
105
1043
# -*- coding: utf-8 -*- """ requests.exceptions ~~~~~~~~~~~~~~~~~~~ This module contains the set of Requests' exceptions. """ class RequestException(RuntimeError): """There was an ambiguous exception that occurred while handling your request.""" class HTTPError(RequestException): """An HTTP error occurred.""" response = None class ConnectionError(RequestException): """A Connection error occurred.""" class SSLError(ConnectionError): """An SSL error occurred.""" class Timeout(RequestException): """The request timed out.""" class URLRequired(RequestException): """A valid URL is required to make a request.""" class TooManyRedirects(RequestException): """Too many redirects.""" class MissingSchema(RequestException, ValueError): """The URL schema (e.g. http or https) is missing.""" class InvalidSchema(RequestException, ValueError): """See defaults.py for valid schemas.""" class InvalidURL(RequestException, ValueError): """ The URL provided was somehow invalid. """
mit
TrimBiggs/libnetwork-plugin
tests/st/libnetwork/test_mainline_single_host.py
1
3979
# Copyright 2015 Metaswitch Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import uuid from tests.st.test_base import TestBase from tests.st.utils import utils from tests.st.utils.docker_host import DockerHost import logging from tests.st.utils.utils import assert_number_endpoints, assert_profile, \ get_profile_name, ETCD_CA, ETCD_CERT, ETCD_KEY, ETCD_HOSTNAME_SSL, \ ETCD_SCHEME logger = logging.getLogger(__name__) POST_DOCKER_COMMANDS = ["docker load -i /code/calico-node.tgz", "docker load -i /code/busybox.tgz", "docker load -i /code/calico-node-libnetwork.tgz"] if ETCD_SCHEME == "https": ADDITIONAL_DOCKER_OPTIONS = "--cluster-store=etcd://%s:2379 " \ "--cluster-store-opt kv.cacertfile=%s " \ "--cluster-store-opt kv.certfile=%s " \ "--cluster-store-opt kv.keyfile=%s " % \ (ETCD_HOSTNAME_SSL, ETCD_CA, ETCD_CERT, ETCD_KEY) else: ADDITIONAL_DOCKER_OPTIONS = "--cluster-store=etcd://%s:2379 " % \ utils.get_ip() class TestMainline(TestBase): def test_mainline(self): """ Setup two endpoints on one host and check connectivity then teardown. """ # TODO - add in IPv6 as part of this flow. with DockerHost('host', additional_docker_options=ADDITIONAL_DOCKER_OPTIONS, post_docker_commands=POST_DOCKER_COMMANDS, start_calico=False) as host: host.start_calico_node("--libnetwork") # Set up two endpoints on one host network = host.create_network("testnet") workload1 = host.create_workload("workload1", network=network) workload2 = host.create_workload("workload2", network=network) # Assert that endpoints are in Calico assert_number_endpoints(host, 2) # Assert that the profile has been created for the network profile_name = get_profile_name(host, network) assert_profile(host, profile_name) # Allow network to converge # Check connectivity. workload1.assert_can_ping("workload2", retries=5) workload2.assert_can_ping("workload1", retries=5) # Inspect the workload to ensure the MAC address is set # correctly. format = "'{{.NetworkSettings.Networks.%s.MacAddress}}'" % network mac = host.execute("docker inspect --format %s %s" % (format, workload1.name)) self.assertEquals(mac.lower(), "ee:ee:ee:ee:ee:ee") # Disconnect endpoints from the network # Assert can't ping and endpoints are removed from Calico network.disconnect(host, workload1) network.disconnect(host, workload2) workload1.assert_cant_ping(workload2.ip, retries=5) assert_number_endpoints(host, 0) # Remove the endpoints on the host # TODO (assert IPs are released) host.remove_workloads() # Remove the network and assert profile is removed network.delete() self.assertRaises(AssertionError, assert_profile, host, profile_name) # TODO - Remove this calico node
apache-2.0
skearnes/pylearn2
pylearn2/scripts/tutorials/stacked_autoencoders/tests/test_dae.py
4
2054
""" This module tests stacked_autoencoders.ipynb """ import os from pylearn2.testing import skip from pylearn2.testing import no_debug_mode from pylearn2.config import yaml_parse @no_debug_mode def train_yaml(yaml_file): train = yaml_parse.load(yaml_file) train.main_loop() def train_layer1(yaml_file_path, save_path): yaml = open("{0}/dae_l1.yaml".format(yaml_file_path), 'r').read() hyper_params = {'train_stop': 50, 'batch_size': 50, 'monitoring_batches': 1, 'nhid': 10, 'max_epochs': 1, 'save_path': save_path} yaml = yaml % (hyper_params) train_yaml(yaml) def train_layer2(yaml_file_path, save_path): yaml = open("{0}/dae_l2.yaml".format(yaml_file_path), 'r').read() hyper_params = {'train_stop': 50, 'batch_size': 50, 'monitoring_batches': 1, 'nvis': 10, 'nhid': 10, 'max_epochs': 1, 'save_path': save_path} yaml = yaml % (hyper_params) train_yaml(yaml) def train_mlp(yaml_file_path, save_path): yaml = open("{0}/dae_mlp.yaml".format(yaml_file_path), 'r').read() hyper_params = {'train_stop': 50, 'valid_stop': 50050, 'batch_size': 50, 'max_epochs': 1, 'save_path': save_path} yaml = yaml % (hyper_params) train_yaml(yaml) def test_sda(): skip.skip_if_no_data() yaml_file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) save_path = os.path.dirname(os.path.realpath(__file__)) train_layer1(yaml_file_path, save_path) train_layer2(yaml_file_path, save_path) train_mlp(yaml_file_path, save_path) try: os.remove("{}/dae_l1.pkl".format(save_path)) os.remove("{}/dae_l2.pkl".format(save_path)) except: pass if __name__ == '__main__': test_sda()
bsd-3-clause
markandrewj/node-gyp
gyp/tools/pretty_gyp.py
2618
4756
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Pretty-prints the contents of a GYP file.""" import sys import re # Regex to remove comments when we're counting braces. COMMENT_RE = re.compile(r'\s*#.*') # Regex to remove quoted strings when we're counting braces. # It takes into account quoted quotes, and makes sure that the quotes match. # NOTE: It does not handle quotes that span more than one line, or # cases where an escaped quote is preceeded by an escaped backslash. QUOTE_RE_STR = r'(?P<q>[\'"])(.*?)(?<![^\\][\\])(?P=q)' QUOTE_RE = re.compile(QUOTE_RE_STR) def comment_replace(matchobj): return matchobj.group(1) + matchobj.group(2) + '#' * len(matchobj.group(3)) def mask_comments(input): """Mask the quoted strings so we skip braces inside quoted strings.""" search_re = re.compile(r'(.*?)(#)(.*)') return [search_re.sub(comment_replace, line) for line in input] def quote_replace(matchobj): return "%s%s%s%s" % (matchobj.group(1), matchobj.group(2), 'x'*len(matchobj.group(3)), matchobj.group(2)) def mask_quotes(input): """Mask the quoted strings so we skip braces inside quoted strings.""" search_re = re.compile(r'(.*?)' + QUOTE_RE_STR) return [search_re.sub(quote_replace, line) for line in input] def do_split(input, masked_input, search_re): output = [] mask_output = [] for (line, masked_line) in zip(input, masked_input): m = search_re.match(masked_line) while m: split = len(m.group(1)) line = line[:split] + r'\n' + line[split:] masked_line = masked_line[:split] + r'\n' + masked_line[split:] m = search_re.match(masked_line) output.extend(line.split(r'\n')) mask_output.extend(masked_line.split(r'\n')) return (output, mask_output) def split_double_braces(input): """Masks out the quotes and comments, and then splits appropriate lines (lines that matche the double_*_brace re's above) before indenting them below. These are used to split lines which have multiple braces on them, so that the indentation looks prettier when all laid out (e.g. closing braces make a nice diagonal line). """ double_open_brace_re = re.compile(r'(.*?[\[\{\(,])(\s*)([\[\{\(])') double_close_brace_re = re.compile(r'(.*?[\]\}\)],?)(\s*)([\]\}\)])') masked_input = mask_quotes(input) masked_input = mask_comments(masked_input) (output, mask_output) = do_split(input, masked_input, double_open_brace_re) (output, mask_output) = do_split(output, mask_output, double_close_brace_re) return output def count_braces(line): """keeps track of the number of braces on a given line and returns the result. It starts at zero and subtracts for closed braces, and adds for open braces. """ open_braces = ['[', '(', '{'] close_braces = [']', ')', '}'] closing_prefix_re = re.compile(r'(.*?[^\s\]\}\)]+.*?)([\]\}\)],?)\s*$') cnt = 0 stripline = COMMENT_RE.sub(r'', line) stripline = QUOTE_RE.sub(r"''", stripline) for char in stripline: for brace in open_braces: if char == brace: cnt += 1 for brace in close_braces: if char == brace: cnt -= 1 after = False if cnt > 0: after = True # This catches the special case of a closing brace having something # other than just whitespace ahead of it -- we don't want to # unindent that until after this line is printed so it stays with # the previous indentation level. if cnt < 0 and closing_prefix_re.match(stripline): after = True return (cnt, after) def prettyprint_input(lines): """Does the main work of indenting the input based on the brace counts.""" indent = 0 basic_offset = 2 last_line = "" for line in lines: if COMMENT_RE.match(line): print line else: line = line.strip('\r\n\t ') # Otherwise doesn't strip \r on Unix. if len(line) > 0: (brace_diff, after) = count_braces(line) if brace_diff != 0: if after: print " " * (basic_offset * indent) + line indent += brace_diff else: indent += brace_diff print " " * (basic_offset * indent) + line else: print " " * (basic_offset * indent) + line else: print "" last_line = line def main(): if len(sys.argv) > 1: data = open(sys.argv[1]).read().splitlines() else: data = sys.stdin.read().splitlines() # Split up the double braces. lines = split_double_braces(data) # Indent and print the output. prettyprint_input(lines) return 0 if __name__ == '__main__': sys.exit(main())
mit
sestrella/ansible
test/units/modules/network/fortios/test_fortios_user_tacacsplus.py
21
11273
# Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <https://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest from mock import ANY from ansible.module_utils.network.fortios.fortios import FortiOSHandler try: from ansible.modules.network.fortios import fortios_user_tacacsplus except ImportError: pytest.skip("Could not load required modules for testing", allow_module_level=True) @pytest.fixture(autouse=True) def connection_mock(mocker): connection_class_mock = mocker.patch('ansible.modules.network.fortios.fortios_user_tacacsplus.Connection') return connection_class_mock fos_instance = FortiOSHandler(connection_mock) def test_user_tacacsplus_creation(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'user_tacacsplus': { 'authen_type': 'mschap', 'authorization': 'enable', 'key': 'test_value_5', 'name': 'default_name_6', 'port': '7', 'secondary_key': 'test_value_8', 'secondary_server': 'test_value_9', 'server': '192.168.100.10', 'source_ip': '84.230.14.11', 'tertiary_key': 'test_value_12', 'tertiary_server': 'test_value_13' }, 'vdom': 'root'} is_error, changed, response = fortios_user_tacacsplus.fortios_user(input_data, fos_instance) expected_data = { 'authen-type': 'mschap', 'authorization': 'enable', 'key': 'test_value_5', 'name': 'default_name_6', 'port': '7', 'secondary-key': 'test_value_8', 'secondary-server': 'test_value_9', 'server': '192.168.100.10', 'source-ip': '84.230.14.11', 'tertiary-key': 'test_value_12', 'tertiary-server': 'test_value_13' } set_method_mock.assert_called_with('user', 'tacacs+', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200 def test_user_tacacsplus_creation_fails(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'user_tacacsplus': { 'authen_type': 'mschap', 'authorization': 'enable', 'key': 'test_value_5', 'name': 'default_name_6', 'port': '7', 'secondary_key': 'test_value_8', 'secondary_server': 'test_value_9', 'server': '192.168.100.10', 'source_ip': '84.230.14.11', 'tertiary_key': 'test_value_12', 'tertiary_server': 'test_value_13' }, 'vdom': 'root'} is_error, changed, response = fortios_user_tacacsplus.fortios_user(input_data, fos_instance) expected_data = { 'authen-type': 'mschap', 'authorization': 'enable', 'key': 'test_value_5', 'name': 'default_name_6', 'port': '7', 'secondary-key': 'test_value_8', 'secondary-server': 'test_value_9', 'server': '192.168.100.10', 'source-ip': '84.230.14.11', 'tertiary-key': 'test_value_12', 'tertiary-server': 'test_value_13' } set_method_mock.assert_called_with('user', 'tacacs+', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 500 def test_user_tacacsplus_removal(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') delete_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} delete_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.delete', return_value=delete_method_result) input_data = { 'username': 'admin', 'state': 'absent', 'user_tacacsplus': { 'authen_type': 'mschap', 'authorization': 'enable', 'key': 'test_value_5', 'name': 'default_name_6', 'port': '7', 'secondary_key': 'test_value_8', 'secondary_server': 'test_value_9', 'server': '192.168.100.10', 'source_ip': '84.230.14.11', 'tertiary_key': 'test_value_12', 'tertiary_server': 'test_value_13' }, 'vdom': 'root'} is_error, changed, response = fortios_user_tacacsplus.fortios_user(input_data, fos_instance) delete_method_mock.assert_called_with('user', 'tacacs+', mkey=ANY, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200 def test_user_tacacsplus_deletion_fails(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') delete_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500} delete_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.delete', return_value=delete_method_result) input_data = { 'username': 'admin', 'state': 'absent', 'user_tacacsplus': { 'authen_type': 'mschap', 'authorization': 'enable', 'key': 'test_value_5', 'name': 'default_name_6', 'port': '7', 'secondary_key': 'test_value_8', 'secondary_server': 'test_value_9', 'server': '192.168.100.10', 'source_ip': '84.230.14.11', 'tertiary_key': 'test_value_12', 'tertiary_server': 'test_value_13' }, 'vdom': 'root'} is_error, changed, response = fortios_user_tacacsplus.fortios_user(input_data, fos_instance) delete_method_mock.assert_called_with('user', 'tacacs+', mkey=ANY, vdom='root') schema_method_mock.assert_not_called() assert is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 500 def test_user_tacacsplus_idempotent(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'error', 'http_method': 'DELETE', 'http_status': 404} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'user_tacacsplus': { 'authen_type': 'mschap', 'authorization': 'enable', 'key': 'test_value_5', 'name': 'default_name_6', 'port': '7', 'secondary_key': 'test_value_8', 'secondary_server': 'test_value_9', 'server': '192.168.100.10', 'source_ip': '84.230.14.11', 'tertiary_key': 'test_value_12', 'tertiary_server': 'test_value_13' }, 'vdom': 'root'} is_error, changed, response = fortios_user_tacacsplus.fortios_user(input_data, fos_instance) expected_data = { 'authen-type': 'mschap', 'authorization': 'enable', 'key': 'test_value_5', 'name': 'default_name_6', 'port': '7', 'secondary-key': 'test_value_8', 'secondary-server': 'test_value_9', 'server': '192.168.100.10', 'source-ip': '84.230.14.11', 'tertiary-key': 'test_value_12', 'tertiary-server': 'test_value_13' } set_method_mock.assert_called_with('user', 'tacacs+', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert not changed assert response['status'] == 'error' assert response['http_status'] == 404 def test_user_tacacsplus_filter_foreign_attributes(mocker): schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema') set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200} set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result) input_data = { 'username': 'admin', 'state': 'present', 'user_tacacsplus': { 'random_attribute_not_valid': 'tag', 'authen_type': 'mschap', 'authorization': 'enable', 'key': 'test_value_5', 'name': 'default_name_6', 'port': '7', 'secondary_key': 'test_value_8', 'secondary_server': 'test_value_9', 'server': '192.168.100.10', 'source_ip': '84.230.14.11', 'tertiary_key': 'test_value_12', 'tertiary_server': 'test_value_13' }, 'vdom': 'root'} is_error, changed, response = fortios_user_tacacsplus.fortios_user(input_data, fos_instance) expected_data = { 'authen-type': 'mschap', 'authorization': 'enable', 'key': 'test_value_5', 'name': 'default_name_6', 'port': '7', 'secondary-key': 'test_value_8', 'secondary-server': 'test_value_9', 'server': '192.168.100.10', 'source-ip': '84.230.14.11', 'tertiary-key': 'test_value_12', 'tertiary-server': 'test_value_13' } set_method_mock.assert_called_with('user', 'tacacs+', data=expected_data, vdom='root') schema_method_mock.assert_not_called() assert not is_error assert changed assert response['status'] == 'success' assert response['http_status'] == 200
gpl-3.0
imruahmed/microblog
flask/lib/python2.7/site-packages/whoosh/query/qcore.py
52
22789
# Copyright 2007 Matt Chaput. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``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 MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are # those of the authors and should not be interpreted as representing official # policies, either expressed or implied, of Matt Chaput. from __future__ import division import copy from array import array from whoosh import matching from whoosh.compat import u from whoosh.reading import TermNotFound from whoosh.compat import methodcaller # Exceptions class QueryError(Exception): """Error encountered while running a query. """ pass # Functions def error_query(msg, q=None): """Returns the query in the second argument (or a :class:`NullQuery` if the second argument is not given) with its ``error`` attribute set to ``msg``. """ if q is None: q = _NullQuery() q.error = msg return q def token_lists(q, phrases=True): """Returns the terms in the query tree, with the query hierarchy represented as nested lists. """ if q.is_leaf(): from whoosh.query import Phrase if phrases or not isinstance(q, Phrase): return list(q.tokens()) else: ls = [] for qq in q.children(): t = token_lists(qq, phrases=phrases) if len(t) == 1: t = t[0] if t: ls.append(t) return ls # Utility classes class Lowest(object): """A value that is always compares lower than any other object except itself. """ def __cmp__(self, other): if other.__class__ is Lowest: return 0 return -1 def __eq__(self, other): return self.__class__ is type(other) def __lt__(self, other): return type(other) is not self.__class__ def __ne__(self, other): return not self.__eq__(other) def __gt__(self, other): return not (self.__lt__(other) or self.__eq__(other)) def __le__(self, other): return self.__eq__(other) or self.__lt__(other) def __ge__(self, other): return self.__eq__(other) or self.__gt__(other) class Highest(object): """A value that is always compares higher than any other object except itself. """ def __cmp__(self, other): if other.__class__ is Highest: return 0 return 1 def __eq__(self, other): return self.__class__ is type(other) def __lt__(self, other): return type(other) is self.__class__ def __ne__(self, other): return not self.__eq__(other) def __gt__(self, other): return not (self.__lt__(other) or self.__eq__(other)) def __le__(self, other): return self.__eq__(other) or self.__lt__(other) def __ge__(self, other): return self.__eq__(other) or self.__gt__(other) Lowest = Lowest() Highest = Highest() # Base classes class Query(object): """Abstract base class for all queries. Note that this base class implements __or__, __and__, and __sub__ to allow slightly more convenient composition of query objects:: >>> Term("content", u"a") | Term("content", u"b") Or([Term("content", u"a"), Term("content", u"b")]) >>> Term("content", u"a") & Term("content", u"b") And([Term("content", u"a"), Term("content", u"b")]) >>> Term("content", u"a") - Term("content", u"b") And([Term("content", u"a"), Not(Term("content", u"b"))]) """ # For queries produced by the query parser, record where in the user # query this object originated startchar = endchar = None # For queries produced by the query parser, records an error that resulted # in this query error = None def __unicode__(self): raise NotImplementedError(self.__class__.__name__) def __getitem__(self, item): raise NotImplementedError def __or__(self, query): """Allows you to use | between query objects to wrap them in an Or query. """ from whoosh.query import Or return Or([self, query]).normalize() def __and__(self, query): """Allows you to use & between query objects to wrap them in an And query. """ from whoosh.query import And return And([self, query]).normalize() def __sub__(self, query): """Allows you to use - between query objects to add the right-hand query as a "NOT" query. """ from whoosh.query import And, Not return And([self, Not(query)]).normalize() def __hash__(self): raise NotImplementedError def __ne__(self, other): return not self.__eq__(other) def is_leaf(self): """Returns True if this is a leaf node in the query tree, or False if this query has sub-queries. """ return True def children(self): """Returns an iterator of the subqueries of this object. """ return iter([]) def is_range(self): """Returns True if this object searches for values within a range. """ return False def has_terms(self): """Returns True if this specific object represents a search for a specific term (as opposed to a pattern, as in Wildcard and Prefix) or terms (i.e., whether the ``replace()`` method does something meaningful on this instance). """ return False def needs_spans(self): for child in self.children(): if child.needs_spans(): return True return False def apply(self, fn): """If this query has children, calls the given function on each child and returns a new copy of this node with the new children returned by the function. If this is a leaf node, simply returns this object. This is useful for writing functions that transform a query tree. For example, this function changes all Term objects in a query tree into Variations objects:: def term2var(q): if isinstance(q, Term): return Variations(q.fieldname, q.text) else: return q.apply(term2var) q = And([Term("f", "alfa"), Or([Term("f", "bravo"), Not(Term("f", "charlie"))])]) q = term2var(q) Note that this method does not automatically create copies of nodes. To avoid modifying the original tree, your function should call the :meth:`Query.copy` method on nodes before changing their attributes. """ return self def accept(self, fn): """Applies the given function to this query's subqueries (if any) and then to this query itself:: def boost_phrases(q): if isintance(q, Phrase): q.boost *= 2.0 return q myquery = myquery.accept(boost_phrases) This method automatically creates copies of the nodes in the original tree before passing them to your function, so your function can change attributes on nodes without altering the original tree. This method is less flexible than using :meth:`Query.apply` (in fact it's implemented using that method) but is often more straightforward. """ def fn_wrapper(q): q = q.apply(fn_wrapper) return fn(q) return fn_wrapper(self) def replace(self, fieldname, oldtext, newtext): """Returns a copy of this query with oldtext replaced by newtext (if oldtext was anywhere in this query). Note that this returns a *new* query with the given text replaced. It *does not* modify the original query "in place". """ # The default implementation uses the apply method to "pass down" the # replace() method call if self.is_leaf(): return copy.copy(self) else: return self.apply(methodcaller("replace", fieldname, oldtext, newtext)) def copy(self): """Deprecated, just use ``copy.deepcopy``. """ return copy.deepcopy(self) def all_terms(self, phrases=True): """Returns a set of all terms in this query tree. This method exists for backwards-compatibility. Use iter_all_terms() instead. :param phrases: Whether to add words found in Phrase queries. :rtype: set """ return set(self.iter_all_terms(phrases=phrases)) def terms(self, phrases=False): """Yields zero or more (fieldname, text) pairs queried by this object. You can check whether a query object targets specific terms before you call this method using :meth:`Query.has_terms`. To get all terms in a query tree, use :meth:`Query.iter_all_terms`. """ return iter(()) def expanded_terms(self, ixreader, phrases=True): return self.terms(phrases=phrases) def existing_terms(self, ixreader, phrases=True, expand=False, fieldname=None): """Returns a set of all byteterms in this query tree that exist in the given ixreader. :param ixreader: A :class:`whoosh.reading.IndexReader` object. :param phrases: Whether to add words found in Phrase queries. :param expand: If True, queries that match multiple terms will return all matching expansions. :rtype: set """ schema = ixreader.schema termset = set() for q in self.leaves(): if fieldname and fieldname != q.field(): continue if expand: terms = q.expanded_terms(ixreader, phrases=phrases) else: terms = q.terms(phrases=phrases) for fieldname, text in terms: if (fieldname, text) in termset: continue if fieldname in schema: field = schema[fieldname] try: btext = field.to_bytes(text) except ValueError: continue if (fieldname, btext) in ixreader: termset.add((fieldname, btext)) return termset def leaves(self): """Returns an iterator of all the leaf queries in this query tree as a flat series. """ if self.is_leaf(): yield self else: for q in self.children(): for qq in q.leaves(): yield qq def iter_all_terms(self, phrases=True): """Returns an iterator of (fieldname, text) pairs for all terms in this query tree. >>> qp = qparser.QueryParser("text", myindex.schema) >>> q = myparser.parse("alfa bravo title:charlie") >>> # List the terms in a query >>> list(q.iter_all_terms()) [("text", "alfa"), ("text", "bravo"), ("title", "charlie")] >>> # Get a set of all terms in the query that don't exist in the index >>> r = myindex.reader() >>> missing = set(t for t in q.iter_all_terms() if t not in r) set([("text", "alfa"), ("title", "charlie")]) >>> # All terms in the query that occur in fewer than 5 documents in >>> # the index >>> [t for t in q.iter_all_terms() if r.doc_frequency(t[0], t[1]) < 5] [("title", "charlie")] :param phrases: Whether to add words found in Phrase queries. """ for q in self.leaves(): if q.has_terms(): for t in q.terms(phrases=phrases): yield t def all_tokens(self, boost=1.0): """Returns an iterator of :class:`analysis.Token` objects corresponding to all terms in this query tree. The Token objects will have the ``fieldname``, ``text``, and ``boost`` attributes set. If the query was built by the query parser, they Token objects will also have ``startchar`` and ``endchar`` attributes indexing into the original user query. """ if self.is_leaf(): for token in self.tokens(boost): yield token else: boost *= self.boost if hasattr(self, "boost") else 1.0 for child in self.children(): for token in child.all_tokens(boost): yield token def tokens(self, boost=1.0, exreader=None): """Yields zero or more :class:`analysis.Token` objects corresponding to the terms searched for by this query object. You can check whether a query object targets specific terms before you call this method using :meth:`Query.has_terms`. The Token objects will have the ``fieldname``, ``text``, and ``boost`` attributes set. If the query was built by the query parser, they Token objects will also have ``startchar`` and ``endchar`` attributes indexing into the original user query. To get all tokens for a query tree, use :meth:`Query.all_tokens`. :param exreader: a reader to use to expand multiterm queries such as prefixes and wildcards. The default is None meaning do not expand. """ return iter(()) def requires(self): """Returns a set of queries that are *known* to be required to match for the entire query to match. Note that other queries might also turn out to be required but not be determinable by examining the static query. >>> a = Term("f", u"a") >>> b = Term("f", u"b") >>> And([a, b]).requires() set([Term("f", u"a"), Term("f", u"b")]) >>> Or([a, b]).requires() set([]) >>> AndMaybe(a, b).requires() set([Term("f", u"a")]) >>> a.requires() set([Term("f", u"a")]) """ # Subclasses should implement the _add_required_to(qset) method return set([self]) def field(self): """Returns the field this query matches in, or None if this query does not match in a single field. """ return self.fieldname def with_boost(self, boost): """Returns a COPY of this query with the boost set to the given value. If a query type does not accept a boost itself, it will try to pass the boost on to its children, if any. """ q = self.copy() q.boost = boost return q def estimate_size(self, ixreader): """Returns an estimate of how many documents this query could potentially match (for example, the estimated size of a simple term query is the document frequency of the term). It is permissible to overestimate, but not to underestimate. """ raise NotImplementedError def estimate_min_size(self, ixreader): """Returns an estimate of the minimum number of documents this query could potentially match. """ return self.estimate_size(ixreader) def matcher(self, searcher, context=None): """Returns a :class:`~whoosh.matching.Matcher` object you can use to retrieve documents and scores matching this query. :rtype: :class:`whoosh.matching.Matcher` """ raise NotImplementedError def docs(self, searcher): """Returns an iterator of docnums matching this query. >>> with my_index.searcher() as searcher: ... list(my_query.docs(searcher)) [10, 34, 78, 103] :param searcher: A :class:`whoosh.searching.Searcher` object. """ try: context = searcher.boolean_context() return self.matcher(searcher, context).all_ids() except TermNotFound: return iter([]) def deletion_docs(self, searcher): """Returns an iterator of docnums matching this query for the purpose of deletion. The :meth:`~whoosh.writing.IndexWriter.delete_by_query` method will use this method when deciding what documents to delete, allowing special queries (e.g. nested queries) to override what documents are deleted. The default implementation just forwards to :meth:`Query.docs`. """ return self.docs(searcher) def normalize(self): """Returns a recursively "normalized" form of this query. The normalized form removes redundancy and empty queries. This is called automatically on query trees created by the query parser, but you may want to call it yourself if you're writing your own parser or building your own queries. >>> q = And([And([Term("f", u"a"), ... Term("f", u"b")]), ... Term("f", u"c"), Or([])]) >>> q.normalize() And([Term("f", u"a"), Term("f", u"b"), Term("f", u"c")]) Note that this returns a *new, normalized* query. It *does not* modify the original query "in place". """ return self def simplify(self, ixreader): """Returns a recursively simplified form of this query, where "second-order" queries (such as Prefix and Variations) are re-written into lower-level queries (such as Term and Or). """ return self # Null query class _NullQuery(Query): "Represents a query that won't match anything." boost = 1.0 def __init__(self): self.error = None def __unicode__(self): return u("<_NullQuery>") def __call__(self): return self def __repr__(self): return "<%s>" % (self.__class__.__name__) def __eq__(self, other): return isinstance(other, _NullQuery) def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return id(self) def __copy__(self): return self def __deepcopy__(self, memo): return self def field(self): return None def estimate_size(self, ixreader): return 0 def normalize(self): return self def simplify(self, ixreader): return self def docs(self, searcher): return [] def matcher(self, searcher, context=None): return matching.NullMatcher() NullQuery = _NullQuery() # Every class Every(Query): """A query that matches every document containing any term in a given field. If you don't specify a field, the query matches every document. >>> # Match any documents with something in the "path" field >>> q = Every("path") >>> # Matcher every document >>> q = Every() The unfielded form (matching every document) is efficient. The fielded is more efficient than a prefix query with an empty prefix or a '*' wildcard, but it can still be very slow on large indexes. It requires the searcher to read the full posting list of every term in the given field. Instead of using this query it is much more efficient when you create the index to include a single term that appears in all documents that have the field you want to match. For example, instead of this:: # Match all documents that have something in the "path" field q = Every("path") Do this when indexing:: # Add an extra field that indicates whether a document has a path schema = fields.Schema(path=fields.ID, has_path=fields.ID) # When indexing, set the "has_path" field based on whether the document # has anything in the "path" field writer.add_document(text=text_value1) writer.add_document(text=text_value2, path=path_value2, has_path="t") Then to find all documents with a path:: q = Term("has_path", "t") """ def __init__(self, fieldname=None, boost=1.0): """ :param fieldname: the name of the field to match, or ``None`` or ``*`` to match all documents. """ if not fieldname or fieldname == "*": fieldname = None self.fieldname = fieldname self.boost = boost def __repr__(self): return "%s(%r, boost=%s)" % (self.__class__.__name__, self.fieldname, self.boost) def __eq__(self, other): return (other and self.__class__ is other.__class__ and self.fieldname == other.fieldname and self.boost == other.boost) def __unicode__(self): return u("%s:*") % self.fieldname __str__ = __unicode__ def __hash__(self): return hash(self.fieldname) def estimate_size(self, ixreader): return ixreader.doc_count() def matcher(self, searcher, context=None): fieldname = self.fieldname reader = searcher.reader() if fieldname in (None, "", "*"): # This takes into account deletions doclist = array("I", reader.all_doc_ids()) else: # This is a hacky hack, but just create an in-memory set of all the # document numbers of every term in the field. This is SLOOOW for # large indexes doclist = set() for text in searcher.lexicon(fieldname): pr = searcher.postings(fieldname, text) doclist.update(pr.all_ids()) doclist = sorted(doclist) return matching.ListMatcher(doclist, all_weights=self.boost)
bsd-3-clause
Kagee/youtube-dl
youtube_dl/extractor/videomega.py
5
1971
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import ( compat_urllib_parse, compat_urllib_request, ) from ..utils import ( ExtractorError, remove_start, ) class VideoMegaIE(InfoExtractor): _VALID_URL = r'''(?x)https?:// (?:www\.)?videomega\.tv/ (?:iframe\.php)?\?ref=(?P<id>[A-Za-z0-9]+) ''' _TEST = { 'url': 'http://videomega.tv/?ref=QR0HCUHI1661IHUCH0RQ', 'md5': 'bf5c2f95c4c917536e80936af7bc51e1', 'info_dict': { 'id': 'QR0HCUHI1661IHUCH0RQ', 'ext': 'mp4', 'title': 'Big Buck Bunny', 'thumbnail': 're:^https?://.*\.jpg$', } } def _real_extract(self, url): video_id = self._match_id(url) iframe_url = 'http://videomega.tv/iframe.php?ref={0:}'.format(video_id) req = compat_urllib_request.Request(iframe_url) req.add_header('Referer', url) webpage = self._download_webpage(req, video_id) try: escaped_data = re.findall(r'unescape\("([^"]+)"\)', webpage)[-1] except IndexError: raise ExtractorError('Unable to extract escaped data') playlist = compat_urllib_parse.unquote(escaped_data) thumbnail = self._search_regex( r'image:\s*"([^"]+)"', playlist, 'thumbnail', fatal=False) video_url = self._search_regex(r'file:\s*"([^"]+)"', playlist, 'URL') title = remove_start(self._html_search_regex( r'<title>(.*?)</title>', webpage, 'title'), 'VideoMega.tv - ') formats = [{ 'format_id': 'sd', 'url': video_url, }] self._sort_formats(formats) return { 'id': video_id, 'title': title, 'formats': formats, 'thumbnail': thumbnail, 'http_headers': { 'Referer': iframe_url, }, }
unlicense
realsobek/freeipa
ipaserver/plugins/vault.py
2
37165
# Authors: # Endi S. Dewata <edewata@redhat.com> # # Copyright (C) 2015 Red Hat # see file 'COPYING' for use and warranty information # # 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 six from ipalib.frontend import Command, Object from ipalib import api, errors from ipalib import Bytes, Flag, Str, StrEnum from ipalib import output from ipalib.crud import PKQuery, Retrieve from ipalib.parameters import Principal from ipalib.plugable import Registry from .baseldap import LDAPObject, LDAPCreate, LDAPDelete,\ LDAPSearch, LDAPUpdate, LDAPRetrieve, LDAPAddMember, LDAPRemoveMember,\ LDAPModMember, pkey_to_value from ipalib.request import context from .service import normalize_principal, validate_realm from ipalib import _, ngettext from ipapython import kerberos from ipapython.dn import DN if api.env.in_server: import pki.account import pki.key if six.PY3: unicode = str __doc__ = _(""" Vaults """) + _(""" Manage vaults. """) + _(""" Vault is a secure place to store a secret. """) + _(""" Based on the ownership there are three vault categories: * user/private vault * service vault * shared vault """) + _(""" User vaults are vaults owned used by a particular user. Private vaults are vaults owned the current user. Service vaults are vaults owned by a service. Shared vaults are owned by the admin but they can be used by other users or services. """) + _(""" Based on the security mechanism there are three types of vaults: * standard vault * symmetric vault * asymmetric vault """) + _(""" Standard vault uses a secure mechanism to transport and store the secret. The secret can only be retrieved by users that have access to the vault. """) + _(""" Symmetric vault is similar to the standard vault, but it pre-encrypts the secret using a password before transport. The secret can only be retrieved using the same password. """) + _(""" Asymmetric vault is similar to the standard vault, but it pre-encrypts the secret using a public key before transport. The secret can only be retrieved using the private key. """) + _(""" EXAMPLES: """) + _(""" List vaults: ipa vault-find [--user <user>|--service <service>|--shared] """) + _(""" Add a standard vault: ipa vault-add <name> [--user <user>|--service <service>|--shared] --type standard """) + _(""" Add a symmetric vault: ipa vault-add <name> [--user <user>|--service <service>|--shared] --type symmetric --password-file password.txt """) + _(""" Add an asymmetric vault: ipa vault-add <name> [--user <user>|--service <service>|--shared] --type asymmetric --public-key-file public.pem """) + _(""" Show a vault: ipa vault-show <name> [--user <user>|--service <service>|--shared] """) + _(""" Modify vault description: ipa vault-mod <name> [--user <user>|--service <service>|--shared] --desc <description> """) + _(""" Modify vault type: ipa vault-mod <name> [--user <user>|--service <service>|--shared] --type <type> [old password/private key] [new password/public key] """) + _(""" Modify symmetric vault password: ipa vault-mod <name> [--user <user>|--service <service>|--shared] --change-password ipa vault-mod <name> [--user <user>|--service <service>|--shared] --old-password <old password> --new-password <new password> ipa vault-mod <name> [--user <user>|--service <service>|--shared] --old-password-file <old password file> --new-password-file <new password file> """) + _(""" Modify asymmetric vault keys: ipa vault-mod <name> [--user <user>|--service <service>|--shared] --private-key-file <old private key file> --public-key-file <new public key file> """) + _(""" Delete a vault: ipa vault-del <name> [--user <user>|--service <service>|--shared] """) + _(""" Display vault configuration: ipa vaultconfig-show """) + _(""" Archive data into standard vault: ipa vault-archive <name> [--user <user>|--service <service>|--shared] --in <input file> """) + _(""" Archive data into symmetric vault: ipa vault-archive <name> [--user <user>|--service <service>|--shared] --in <input file> --password-file password.txt """) + _(""" Archive data into asymmetric vault: ipa vault-archive <name> [--user <user>|--service <service>|--shared] --in <input file> """) + _(""" Retrieve data from standard vault: ipa vault-retrieve <name> [--user <user>|--service <service>|--shared] --out <output file> """) + _(""" Retrieve data from symmetric vault: ipa vault-retrieve <name> [--user <user>|--service <service>|--shared] --out <output file> --password-file password.txt """) + _(""" Retrieve data from asymmetric vault: ipa vault-retrieve <name> [--user <user>|--service <service>|--shared] --out <output file> --private-key-file private.pem """) + _(""" Add vault owners: ipa vault-add-owner <name> [--user <user>|--service <service>|--shared] [--users <users>] [--groups <groups>] [--services <services>] """) + _(""" Delete vault owners: ipa vault-remove-owner <name> [--user <user>|--service <service>|--shared] [--users <users>] [--groups <groups>] [--services <services>] """) + _(""" Add vault members: ipa vault-add-member <name> [--user <user>|--service <service>|--shared] [--users <users>] [--groups <groups>] [--services <services>] """) + _(""" Delete vault members: ipa vault-remove-member <name> [--user <user>|--service <service>|--shared] [--users <users>] [--groups <groups>] [--services <services>] """) register = Registry() vault_options = ( Principal( 'service?', validate_realm, doc=_('Service name of the service vault'), normalizer=normalize_principal, ), Flag( 'shared?', doc=_('Shared vault'), ), Str( 'username?', cli_name='user', doc=_('Username of the user vault'), ), ) class VaultModMember(LDAPModMember): def get_options(self): for param in super(VaultModMember, self).get_options(): if param.name == 'service' and param not in vault_options: param = param.clone_rename('services') yield param def get_member_dns(self, **options): if 'services' in options: options['service'] = options.pop('services') else: options.pop('service', None) return super(VaultModMember, self).get_member_dns(**options) def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options): for fail in failed.itervalues(): fail['services'] = fail.pop('service', []) self.obj.get_container_attribute(entry_attrs, options) return completed, dn @register() class vaultcontainer(LDAPObject): __doc__ = _(""" Vault Container object. """) container_dn = api.env.container_vault object_name = _('vaultcontainer') object_name_plural = _('vaultcontainers') object_class = ['ipaVaultContainer'] permission_filter_objectclasses = ['ipaVaultContainer'] attribute_members = { 'owner': ['user', 'group', 'service'], } label = _('Vault Containers') label_singular = _('Vault Container') managed_permissions = { 'System: Read Vault Containers': { 'ipapermlocation': api.env.basedn, 'ipapermtarget': DN(api.env.container_vault, api.env.basedn), 'ipapermright': {'read', 'search', 'compare'}, 'ipapermdefaultattr': { 'objectclass', 'cn', 'description', 'owner', }, 'default_privileges': {'Vault Administrators'}, }, 'System: Add Vault Containers': { 'ipapermlocation': api.env.basedn, 'ipapermtarget': DN(api.env.container_vault, api.env.basedn), 'ipapermright': {'add'}, 'default_privileges': {'Vault Administrators'}, }, 'System: Delete Vault Containers': { 'ipapermlocation': api.env.basedn, 'ipapermtarget': DN(api.env.container_vault, api.env.basedn), 'ipapermright': {'delete'}, 'default_privileges': {'Vault Administrators'}, }, 'System: Modify Vault Containers': { 'ipapermlocation': api.env.basedn, 'ipapermtarget': DN(api.env.container_vault, api.env.basedn), 'ipapermright': {'write'}, 'ipapermdefaultattr': { 'objectclass', 'cn', 'description', }, 'default_privileges': {'Vault Administrators'}, }, 'System: Manage Vault Container Ownership': { 'ipapermlocation': api.env.basedn, 'ipapermtarget': DN(api.env.container_vault, api.env.basedn), 'ipapermright': {'write'}, 'ipapermdefaultattr': { 'owner', }, 'default_privileges': {'Vault Administrators'}, }, } takes_params = ( Str( 'owner_user?', label=_('Owner users'), ), Str( 'owner_group?', label=_('Owner groups'), ), Str( 'owner_service?', label=_('Owner services'), ), Str( 'owner?', label=_('Failed owners'), ), Str( 'service?', label=_('Vault service'), flags={'virtual_attribute'}, ), Flag( 'shared?', label=_('Shared vault'), flags={'virtual_attribute'}, ), Str( 'username?', label=_('Vault user'), flags={'virtual_attribute'}, ), ) def get_dn(self, *keys, **options): """ Generates vault DN from parameters. """ service = options.get('service') shared = options.get('shared') user = options.get('username') count = (bool(service) + bool(shared) + bool(user)) if count > 1: raise errors.MutuallyExclusiveError( reason=_('Service, shared and user options ' + 'cannot be specified simultaneously')) parent_dn = super(vaultcontainer, self).get_dn(*keys, **options) if not count: principal = kerberos.Principal(getattr(context, 'principal')) if principal.is_host: raise errors.NotImplementedError( reason=_('Host is not supported')) elif principal.is_service: service = unicode(principal) else: user = principal.username if service: dn = DN(('cn', service), ('cn', 'services'), parent_dn) elif shared: dn = DN(('cn', 'shared'), parent_dn) elif user: dn = DN(('cn', user), ('cn', 'users'), parent_dn) else: raise RuntimeError return dn def get_container_attribute(self, entry, options): if options.get('raw', False): return container_dn = DN(self.container_dn, self.api.env.basedn) if entry.dn.endswith(DN(('cn', 'services'), container_dn)): entry['service'] = entry.dn[0]['cn'] elif entry.dn.endswith(DN(('cn', 'shared'), container_dn)): entry['shared'] = True elif entry.dn.endswith(DN(('cn', 'users'), container_dn)): entry['username'] = entry.dn[0]['cn'] @register() class vaultcontainer_show(LDAPRetrieve): __doc__ = _('Display information about a vault container.') takes_options = LDAPRetrieve.takes_options + vault_options has_output_params = LDAPRetrieve.has_output_params def pre_callback(self, ldap, dn, attrs_list, *keys, **options): assert isinstance(dn, DN) if not self.api.Command.kra_is_enabled()['result']: raise errors.InvocationError( format=_('KRA service is not enabled')) return dn def post_callback(self, ldap, dn, entry_attrs, *keys, **options): self.obj.get_container_attribute(entry_attrs, options) return dn @register() class vaultcontainer_del(LDAPDelete): __doc__ = _('Delete a vault container.') takes_options = LDAPDelete.takes_options + vault_options msg_summary = _('Deleted vault container') subtree_delete = False def pre_callback(self, ldap, dn, *keys, **options): assert isinstance(dn, DN) if not self.api.Command.kra_is_enabled()['result']: raise errors.InvocationError( format=_('KRA service is not enabled')) return dn def execute(self, *keys, **options): keys = keys + (u'',) return super(vaultcontainer_del, self).execute(*keys, **options) @register() class vaultcontainer_add_owner(VaultModMember, LDAPAddMember): __doc__ = _('Add owners to a vault container.') takes_options = LDAPAddMember.takes_options + vault_options member_attributes = ['owner'] member_param_label = _('owner %s') member_count_out = ('%i owner added.', '%i owners added.') has_output = ( output.Entry('result'), output.Output( 'failed', type=dict, doc=_('Owners that could not be added'), ), output.Output( 'completed', type=int, doc=_('Number of owners added'), ), ) @register() class vaultcontainer_remove_owner(VaultModMember, LDAPRemoveMember): __doc__ = _('Remove owners from a vault container.') takes_options = LDAPRemoveMember.takes_options + vault_options member_attributes = ['owner'] member_param_label = _('owner %s') member_count_out = ('%i owner removed.', '%i owners removed.') has_output = ( output.Entry('result'), output.Output( 'failed', type=dict, doc=_('Owners that could not be removed'), ), output.Output( 'completed', type=int, doc=_('Number of owners removed'), ), ) @register() class vault(LDAPObject): __doc__ = _(""" Vault object. """) container_dn = api.env.container_vault object_name = _('vault') object_name_plural = _('vaults') object_class = ['ipaVault'] permission_filter_objectclasses = ['ipaVault'] default_attributes = [ 'cn', 'description', 'ipavaulttype', 'ipavaultsalt', 'ipavaultpublickey', 'owner', 'member', ] search_display_attributes = [ 'cn', 'description', 'ipavaulttype', ] attribute_members = { 'owner': ['user', 'group', 'service'], 'member': ['user', 'group', 'service'], } label = _('Vaults') label_singular = _('Vault') managed_permissions = { 'System: Read Vaults': { 'ipapermlocation': api.env.basedn, 'ipapermtarget': DN(api.env.container_vault, api.env.basedn), 'ipapermright': {'read', 'search', 'compare'}, 'ipapermdefaultattr': { 'objectclass', 'cn', 'description', 'ipavaulttype', 'ipavaultsalt', 'ipavaultpublickey', 'owner', 'member', 'memberuser', 'memberhost', }, 'default_privileges': {'Vault Administrators'}, }, 'System: Add Vaults': { 'ipapermlocation': api.env.basedn, 'ipapermtarget': DN(api.env.container_vault, api.env.basedn), 'ipapermright': {'add'}, 'default_privileges': {'Vault Administrators'}, }, 'System: Delete Vaults': { 'ipapermlocation': api.env.basedn, 'ipapermtarget': DN(api.env.container_vault, api.env.basedn), 'ipapermright': {'delete'}, 'default_privileges': {'Vault Administrators'}, }, 'System: Modify Vaults': { 'ipapermlocation': api.env.basedn, 'ipapermtarget': DN(api.env.container_vault, api.env.basedn), 'ipapermright': {'write'}, 'ipapermdefaultattr': { 'objectclass', 'cn', 'description', 'ipavaulttype', 'ipavaultsalt', 'ipavaultpublickey', }, 'default_privileges': {'Vault Administrators'}, }, 'System: Manage Vault Ownership': { 'ipapermlocation': api.env.basedn, 'ipapermtarget': DN(api.env.container_vault, api.env.basedn), 'ipapermright': {'write'}, 'ipapermdefaultattr': { 'owner', }, 'default_privileges': {'Vault Administrators'}, }, 'System: Manage Vault Membership': { 'ipapermlocation': api.env.basedn, 'ipapermtarget': DN(api.env.container_vault, api.env.basedn), 'ipapermright': {'write'}, 'ipapermdefaultattr': { 'member', }, 'default_privileges': {'Vault Administrators'}, }, } takes_params = ( Str( 'cn', cli_name='name', label=_('Vault name'), primary_key=True, pattern='^[a-zA-Z0-9_.-]+$', pattern_errmsg='may only include letters, numbers, _, ., and -', maxlength=255, ), Str( 'description?', cli_name='desc', label=_('Description'), doc=_('Vault description'), ), StrEnum( 'ipavaulttype?', cli_name='type', label=_('Type'), doc=_('Vault type'), values=(u'standard', u'symmetric', u'asymmetric', ), default=u'symmetric', autofill=True, ), Bytes( 'ipavaultsalt?', cli_name='salt', label=_('Salt'), doc=_('Vault salt'), flags=['no_search'], ), Bytes( 'ipavaultpublickey?', cli_name='public_key', label=_('Public key'), doc=_('Vault public key'), flags=['no_search'], ), Str( 'owner_user?', label=_('Owner users'), flags=['no_create', 'no_update', 'no_search'], ), Str( 'owner_group?', label=_('Owner groups'), flags=['no_create', 'no_update', 'no_search'], ), Str( 'owner_service?', label=_('Owner services'), flags=['no_create', 'no_update', 'no_search'], ), Str( 'owner?', label=_('Failed owners'), flags=['no_create', 'no_update', 'no_search'], ), Str( 'service?', label=_('Vault service'), flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'}, ), Flag( 'shared?', label=_('Shared vault'), flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'}, ), Str( 'username?', label=_('Vault user'), flags={'virtual_attribute', 'no_create', 'no_update', 'no_search'}, ), ) def get_dn(self, *keys, **options): """ Generates vault DN from parameters. """ service = options.get('service') shared = options.get('shared') user = options.get('username') count = (bool(service) + bool(shared) + bool(user)) if count > 1: raise errors.MutuallyExclusiveError( reason=_('Service, shared, and user options ' + 'cannot be specified simultaneously')) # TODO: create container_dn after object initialization then reuse it container_dn = DN(self.container_dn, self.api.env.basedn) dn = super(vault, self).get_dn(*keys, **options) assert dn.endswith(container_dn) rdns = DN(*dn[:-len(container_dn)]) if not count: principal = kerberos.Principal(getattr(context, 'principal')) if principal.is_host: raise errors.NotImplementedError( reason=_('Host is not supported')) elif principal.is_service: service = unicode(principal) else: user = principal.username if service: parent_dn = DN(('cn', service), ('cn', 'services'), container_dn) elif shared: parent_dn = DN(('cn', 'shared'), container_dn) elif user: parent_dn = DN(('cn', user), ('cn', 'users'), container_dn) else: raise RuntimeError return DN(rdns, parent_dn) def create_container(self, dn, owner_dn): """ Creates vault container and its parents. """ # TODO: create container_dn after object initialization then reuse it container_dn = DN(self.container_dn, self.api.env.basedn) entries = [] while dn: assert dn.endswith(container_dn) rdn = dn[0] entry = self.backend.make_entry( dn, { 'objectclass': ['ipaVaultContainer'], 'cn': rdn['cn'], 'owner': [owner_dn], }) # if entry can be added, return try: self.backend.add_entry(entry) break except errors.NotFound: pass # otherwise, create parent entry first dn = DN(*dn[1:]) entries.insert(0, entry) # then create the entries again for entry in entries: self.backend.add_entry(entry) def get_key_id(self, dn): """ Generates a client key ID to archive/retrieve data in KRA. """ # TODO: create container_dn after object initialization then reuse it container_dn = DN(self.container_dn, self.api.env.basedn) # make sure the DN is a vault DN if not dn.endswith(container_dn, 1): raise ValueError('Invalid vault DN: %s' % dn) # construct the vault ID from the bottom up id = u'' for rdn in dn[:-len(container_dn)]: name = rdn['cn'] id = u'/' + name + id return 'ipa:' + id def get_container_attribute(self, entry, options): if options.get('raw', False): return container_dn = DN(self.container_dn, self.api.env.basedn) if entry.dn.endswith(DN(('cn', 'services'), container_dn)): entry['service'] = entry.dn[1]['cn'] elif entry.dn.endswith(DN(('cn', 'shared'), container_dn)): entry['shared'] = True elif entry.dn.endswith(DN(('cn', 'users'), container_dn)): entry['username'] = entry.dn[1]['cn'] @register() class vault_add_internal(LDAPCreate): NO_CLI = True takes_options = LDAPCreate.takes_options + vault_options msg_summary = _('Added vault "%(value)s"') def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options): assert isinstance(dn, DN) if not self.api.Command.kra_is_enabled()['result']: raise errors.InvocationError( format=_('KRA service is not enabled')) principal = kerberos.Principal(getattr(context, 'principal')) if principal.is_service: owner_dn = self.api.Object.service.get_dn(unicode(principal)) else: owner_dn = self.api.Object.user.get_dn(principal.username) parent_dn = DN(*dn[1:]) try: self.obj.create_container(parent_dn, owner_dn) except (errors.DuplicateEntry, errors.ACIError): pass # vault should be owned by the creator entry_attrs['owner'] = owner_dn return dn def post_callback(self, ldap, dn, entry, *keys, **options): self.obj.get_container_attribute(entry, options) return dn @register() class vault_del(LDAPDelete): __doc__ = _('Delete a vault.') takes_options = LDAPDelete.takes_options + vault_options msg_summary = _('Deleted vault "%(value)s"') def pre_callback(self, ldap, dn, *keys, **options): assert isinstance(dn, DN) if not self.api.Command.kra_is_enabled()['result']: raise errors.InvocationError( format=_('KRA service is not enabled')) return dn def post_callback(self, ldap, dn, *args, **options): assert isinstance(dn, DN) with self.api.Backend.kra.get_client() as kra_client: kra_account = pki.account.AccountClient(kra_client.connection) kra_account.login() client_key_id = self.obj.get_key_id(dn) # deactivate vault record in KRA response = kra_client.keys.list_keys( client_key_id, pki.key.KeyClient.KEY_STATUS_ACTIVE) for key_info in response.key_infos: kra_client.keys.modify_key_status( key_info.get_key_id(), pki.key.KeyClient.KEY_STATUS_INACTIVE) kra_account.logout() return True @register() class vault_find(LDAPSearch): __doc__ = _('Search for vaults.') takes_options = LDAPSearch.takes_options + vault_options + ( Flag( 'services?', doc=_('List all service vaults'), ), Flag( 'users?', doc=_('List all user vaults'), ), ) has_output_params = LDAPSearch.has_output_params msg_summary = ngettext( '%(count)d vault matched', '%(count)d vaults matched', 0, ) def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *args, **options): assert isinstance(base_dn, DN) if not self.api.Command.kra_is_enabled()['result']: raise errors.InvocationError( format=_('KRA service is not enabled')) if options.get('users') or options.get('services'): mutex = ['service', 'services', 'shared', 'username', 'users'] count = sum(bool(options.get(option)) for option in mutex) if count > 1: raise errors.MutuallyExclusiveError( reason=_('Service(s), shared, and user(s) options ' + 'cannot be specified simultaneously')) scope = ldap.SCOPE_SUBTREE container_dn = DN(self.obj.container_dn, self.api.env.basedn) if options.get('services'): base_dn = DN(('cn', 'services'), container_dn) else: base_dn = DN(('cn', 'users'), container_dn) else: base_dn = self.obj.get_dn(None, **options) return filter, base_dn, scope def post_callback(self, ldap, entries, truncated, *args, **options): for entry in entries: self.obj.get_container_attribute(entry, options) return truncated def exc_callback(self, args, options, exc, call_func, *call_args, **call_kwargs): if call_func.__name__ == 'find_entries': if isinstance(exc, errors.NotFound): # ignore missing containers since they will be created # automatically on vault creation. raise errors.EmptyResult(reason=str(exc)) raise exc @register() class vault_mod_internal(LDAPUpdate): NO_CLI = True takes_options = LDAPUpdate.takes_options + vault_options msg_summary = _('Modified vault "%(value)s"') def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options): assert isinstance(dn, DN) if not self.api.Command.kra_is_enabled()['result']: raise errors.InvocationError( format=_('KRA service is not enabled')) return dn def post_callback(self, ldap, dn, entry_attrs, *keys, **options): self.obj.get_container_attribute(entry_attrs, options) return dn @register() class vault_show(LDAPRetrieve): __doc__ = _('Display information about a vault.') takes_options = LDAPRetrieve.takes_options + vault_options has_output_params = LDAPRetrieve.has_output_params def pre_callback(self, ldap, dn, attrs_list, *keys, **options): assert isinstance(dn, DN) if not self.api.Command.kra_is_enabled()['result']: raise errors.InvocationError( format=_('KRA service is not enabled')) return dn def post_callback(self, ldap, dn, entry_attrs, *keys, **options): self.obj.get_container_attribute(entry_attrs, options) return dn @register() class vaultconfig(Object): __doc__ = _('Vault configuration') takes_params = ( Bytes( 'transport_cert', label=_('Transport Certificate'), ), Str( 'kra_server_server*', label=_('IPA KRA servers'), doc=_('IPA servers configured as key recovery agents'), flags={'virtual_attribute', 'no_create', 'no_update'} ) ) @register() class vaultconfig_show(Retrieve): __doc__ = _('Show vault configuration.') takes_options = ( Str( 'transport_out?', doc=_('Output file to store the transport certificate'), ), ) def execute(self, *args, **options): if not self.api.Command.kra_is_enabled()['result']: raise errors.InvocationError( format=_('KRA service is not enabled')) with self.api.Backend.kra.get_client() as kra_client: transport_cert = kra_client.system_certs.get_transport_cert() config = {'transport_cert': transport_cert.binary} config.update( self.api.Backend.serverroles.config_retrieve("KRA server") ) return { 'result': config, 'value': None, } @register() class vault_archive_internal(PKQuery): NO_CLI = True takes_options = vault_options + ( Bytes( 'session_key', doc=_('Session key wrapped with transport certificate'), ), Bytes( 'vault_data', doc=_('Vault data encrypted with session key'), ), Bytes( 'nonce', doc=_('Nonce'), ), ) has_output = output.standard_entry msg_summary = _('Archived data into vault "%(value)s"') def execute(self, *args, **options): if not self.api.Command.kra_is_enabled()['result']: raise errors.InvocationError( format=_('KRA service is not enabled')) wrapped_vault_data = options.pop('vault_data') nonce = options.pop('nonce') wrapped_session_key = options.pop('session_key') # retrieve vault info vault = self.api.Command.vault_show(*args, **options)['result'] # connect to KRA with self.api.Backend.kra.get_client() as kra_client: kra_account = pki.account.AccountClient(kra_client.connection) kra_account.login() client_key_id = self.obj.get_key_id(vault['dn']) # deactivate existing vault record in KRA response = kra_client.keys.list_keys( client_key_id, pki.key.KeyClient.KEY_STATUS_ACTIVE) for key_info in response.key_infos: kra_client.keys.modify_key_status( key_info.get_key_id(), pki.key.KeyClient.KEY_STATUS_INACTIVE) # forward wrapped data to KRA kra_client.keys.archive_encrypted_data( client_key_id, pki.key.KeyClient.PASS_PHRASE_TYPE, wrapped_vault_data, wrapped_session_key, None, nonce, ) kra_account.logout() response = { 'value': args[-1], 'result': {}, } response['summary'] = self.msg_summary % response return response @register() class vault_retrieve_internal(PKQuery): NO_CLI = True takes_options = vault_options + ( Bytes( 'session_key', doc=_('Session key wrapped with transport certificate'), ), ) has_output = output.standard_entry msg_summary = _('Retrieved data from vault "%(value)s"') def execute(self, *args, **options): if not self.api.Command.kra_is_enabled()['result']: raise errors.InvocationError( format=_('KRA service is not enabled')) wrapped_session_key = options.pop('session_key') # retrieve vault info vault = self.api.Command.vault_show(*args, **options)['result'] # connect to KRA with self.api.Backend.kra.get_client() as kra_client: kra_account = pki.account.AccountClient(kra_client.connection) kra_account.login() client_key_id = self.obj.get_key_id(vault['dn']) # find vault record in KRA response = kra_client.keys.list_keys( client_key_id, pki.key.KeyClient.KEY_STATUS_ACTIVE) if not len(response.key_infos): raise errors.NotFound(reason=_('No archived data.')) key_info = response.key_infos[0] # retrieve encrypted data from KRA key = kra_client.keys.retrieve_key( key_info.get_key_id(), wrapped_session_key) kra_account.logout() response = { 'value': args[-1], 'result': { 'vault_data': key.encrypted_data, 'nonce': key.nonce_data, }, } response['summary'] = self.msg_summary % response return response @register() class vault_add_owner(VaultModMember, LDAPAddMember): __doc__ = _('Add owners to a vault.') takes_options = LDAPAddMember.takes_options + vault_options member_attributes = ['owner'] member_param_label = _('owner %s') member_count_out = ('%i owner added.', '%i owners added.') has_output = ( output.Entry('result'), output.Output( 'failed', type=dict, doc=_('Owners that could not be added'), ), output.Output( 'completed', type=int, doc=_('Number of owners added'), ), ) @register() class vault_remove_owner(VaultModMember, LDAPRemoveMember): __doc__ = _('Remove owners from a vault.') takes_options = LDAPRemoveMember.takes_options + vault_options member_attributes = ['owner'] member_param_label = _('owner %s') member_count_out = ('%i owner removed.', '%i owners removed.') has_output = ( output.Entry('result'), output.Output( 'failed', type=dict, doc=_('Owners that could not be removed'), ), output.Output( 'completed', type=int, doc=_('Number of owners removed'), ), ) @register() class vault_add_member(VaultModMember, LDAPAddMember): __doc__ = _('Add members to a vault.') takes_options = LDAPAddMember.takes_options + vault_options @register() class vault_remove_member(VaultModMember, LDAPRemoveMember): __doc__ = _('Remove members from a vault.') takes_options = LDAPRemoveMember.takes_options + vault_options @register() class kra_is_enabled(Command): NO_CLI = True has_output = output.standard_value def execute(self, *args, **options): base_dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), self.api.env.basedn) filter = '(&(objectClass=ipaConfigObject)(cn=KRA))' try: self.api.Backend.ldap2.find_entries( base_dn=base_dn, filter=filter, attrs_list=[]) except errors.NotFound: result = False else: result = True return dict(result=result, value=pkey_to_value(None, options))
gpl-3.0
uannight/reposan
plugin.video.tvalacarta/channels/tvolucion.py
2
69664
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Canal para tvolucion.com # creado por lpedro aka cuatexoft # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import urlparse,urllib2,urllib,re import os, sys from core import logger from core import config from core import scrapertools from core.item import Item from servers import servertools from servers import youtube __channel__ = "tvolucion" __category__ = "F" __type__ = "generic" __title__ = "tvolucion" __language__ = "ES" __creationdate__ = "20111014" __vfanart__ = "http://img594.imageshack.us/img594/7788/fanart.png" DEBUG = config.get_setting("debug") def isGeneric(): return True def mainlist(item): logger.info("[tvolucion.py] mainlist") itemlist = [] # itemlist.append( Item(channel=__channel__, title="Buscar" , action="search") ) itemlist.append( Item(channel=__channel__, title="Cine", action="cine", url="http://tvolucion.esmas.com/entretenimiento/noticias/cine/", thumbnail="http://img690.imageshack.us/img690/690/cinev.png", fanart = __vfanart__)) itemlist.append( Item(channel=__channel__, title="Deportes", action="deportes", url="http://televisadeportes.esmas.com/video/", thumbnail="http://img217.imageshack.us/img217/2709/deportesk.png", fanart = __vfanart__)) itemlist.append( Item(channel=__channel__, title="Novelas Recientes", action="novelasr", url="http://tvolucion.esmas.com/secciones.php?canal=telenovelas", thumbnail="http://img651.imageshack.us/img651/4894/novelasq.png", fanart = __vfanart__)) itemlist.append( Item(channel=__channel__, title="Novelas Anteriores", action="novelasa", url="http://tvolucion.esmas.com/secciones.php?canal=telenovelas", thumbnail="http://img607.imageshack.us/img607/4232/novelasa.png", fanart = __vfanart__)) itemlist.append( Item(channel=__channel__, title="Programas", action="programas", url="http://tvolucion.esmas.com/secciones.php?canal=programas-de-tv", thumbnail="http://img845.imageshack.us/img845/9910/40000175.png", fanart = __vfanart__)) itemlist.append( Item(channel=__channel__, title="Kids", action="ninos", url="http://www2.esmas.com/chicoswaifai/videos/", thumbnail="http://img267.imageshack.us/img267/6987/kidsg.png", fanart = __vfanart__)) itemlist.append( Item(channel=__channel__, title="Noticias", action="noticias", url="http://tvolucion.esmas.com/secciones.php?canal=noticieros", thumbnail="http://img827.imageshack.us/img827/1724/noticiasir.png", fanart = __vfanart__)) # itemlist.append( Item(channel=__channel__, title="Todas las Novelas (Prueba)", action="novelas", url="http://www.tutelenovela.net/p/telenovelas.html", thumbnail="", fanart = __vfanart__)) itemlist.append( Item(channel=__channel__, title="En Vivo", action="tv", url="http://www.ilive.to/view/1598/", thumbnail="http://img716.imageshack.us/img716/9962/canal10.png", fanart = __vfanart__)) # itemlist.append( Item(channel=__channel__, title="Teresa", action="teresa", url="http://blog.cuatexoft.com/?p=537")) # http://tvolucion.esmas.com/home_mas_visto.php return itemlist def cine(item): logger.info("[tvolucion.py] cine") # Descarga la p‡gina data = scrapertools.cachePage(item.url) extra = item.extra # Extrae las entradas de la pagina seleccionada ''' style="padding-left:7px;"><a href="http://televisadeportes.esmas.com/video/ ''' patron = '<tr.*?>.*?<td><a href="([^"]+)">([^<]+)</a></td>.*?<td>([^<]+)</td>.*?<td>([^<]+)</td>.*?<td>([^<]+)</td>.*?</tr>' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = match[0] scrapedtitle = match[1] scrapedthumbnail = "http://www.tvyespectaculos.com/wp-content/uploads/2010/07/Televisa.jpg" scrapedplot = match[2]+chr(10)+"DURACION : "+match[3]+chr(10)+"AGREGADO : "+match[4]+chr(10)+scrapedurl logger.info(scrapedtitle) # baja thumbnail data2 = scrapertools.cachePage(scrapedurl) patron2 = 'videoImgFrame=\'(.*?)\';.*?videoUrlFrame=\'(.*?)\';' matches2 = re.compile(patron2,re.DOTALL).findall(data2) for match2 in matches2: scrapedthumbnail = match2[0] scrapedplot = scrapedplot +chr(10)+scrapedthumbnail # A–ade al listado itemlist.append( Item(channel=__channel__, action="video", title=scrapedtitle.upper() , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) return itemlist def ninos(item): logger.info("[tvolucion.py] ninos") # Descarga la p‡gina data = scrapertools.cachePage(item.url) extra = item.extra scrapedfanart = "NO" patron = '<div class="col-15 padding-L10 padding-T20">(.*?)</div>.*?<a class="thumbImgBorder" href="([^"]+)".*?<img src="([^"]+)" width="235" height="96"></a>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = match[1] scrapedtitle = match[0] scrapedthumbnail = match[2] scrapedplot = "" logger.info(scrapedtitle) # baja fanart data2 = scrapertools.cachePage(scrapedurl) patron2 = '<img src="([^"]+)" class="stage.*?>(.*?)</div>' matches2 = re.compile(patron2,re.DOTALL).findall(data2) for match2 in matches2: scrapedfanart = match2[0] #baja plot patron3 = '<div class="info" style=.*?<h3>(.*?)</h3>.*?<h4>(.*?)</h4>.*?<h5>(.*?)</h5>' matches3 = re.compile(patron3,re.DOTALL).findall(data2) for match3 in matches3: scrapedplot = match3[0] #+chr(10)+match2[1] +chr(10)+match2[2] +chr(10)+match2[3] +chr(10)+match2[4] # A–ade al listado itemlist.append( Item(channel=__channel__, action="capitulo", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=True) ) return itemlist def deportes(item): logger.info("[tvolucion.py] deportes") # Descarga la p‡gina data = scrapertools.cachePage(item.url) extra = item.extra # Extrae las entradas de la pagina seleccionada ''' style="padding-left:7px;"><a href="http://televisadeportes.esmas.com/video/ ''' patron = '</div><br><a href="http://televisadeportes.esmas.com/video/(.*?)/".*?class="(.*?)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = "http://televisadeportes.esmas.com/video/"+match[0]+"/" scrapedtitle = match[0] scrapedthumbnail = "http://www.tvyespectaculos.com/wp-content/uploads/2010/07/Televisa.jpg" scrapedplot = "El mejor contenido de videos deportivos, en exclusiva por internet."+chr(10)+scrapedurl logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="deportescap", title=scrapedtitle.upper() , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) patron = 'style="padding-left:7px;"><a href="http://televisadeportes.esmas.com/video/(.*?)/(.*?)".*?class' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) #itemlist = [] for match in matches: scrapedurl = "http://televisadeportes.esmas.com/video/"+match[0]+"/"+match[1] scrapedtitle = match[0] +" - " + match[1][0:len(match[1])-1] scrapedthumbnail = "http://www.tvyespectaculos.com/wp-content/uploads/2010/07/Televisa.jpg" scrapedplot = "El mejor contenido de videos deportivos, en exclusiva por internet."+chr(10)+scrapedurl logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="deportescap", title=scrapedtitle.upper() , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) return itemlist def deportescap(item): logger.info("[tvolucion.py] deportescap") # Descarga la p‡gina data = scrapertools.cachePage(item.url) extra = item.extra # COLECCION PRIVADA # Extrae las entradas de la pagina seleccionada ''' <li><span class="chaptersLongTitle"> <a href='http://televisadeportes.esmas.com/video/noticias/172742/coleccion-privada-golazos-santos' class="txtColor4 txtMedium">Colecci—n Privada: Golazos de Santos</a> </span> <span class="chaptersLen">00:01:24</span></li> <li><span class="chaptersLongTitle"> <a href='http://televisadeportes.esmas.com/video/noticias/172735/coleccion-privada-golazos-rayados' class="txtColor4 txtMedium">Colecci—n Privada: Golazos de Rayados</a> ''' #thumbnails patron = '<img class="thumbImageSizer" style="border:medium none; position:absolute;" src="([^"]+)"/>.*?<div class="playOverIcon" id="playOverIcon1_00" style="display:none;">.*?<a href=\'(.*?)\'>.*?<img src="http://i2.esmas.com/tvolucion/img/thumb_ico_play.gif" />.*?<\a>.*?<\div>.*?<div style="position:absolute;" onMouseOut="showhideplay.*?" onMouseOver="showhideplay.*?" class="TipsMask" title="<ul><li style=\'width:11px; height:40px; background-image:url(http://i2.esmas.com/tvolucion/img/piquito.gif); background-position:top; background-repeat:no-repeat; float:left;\'></li><li style=\'float:left; background-color:#E2E2E2; width:300px;\'><ul><li class=\'txtMedium txtColor3 txtBold left\' style=\'padding: 3px 10px 3px 10px;\'>([^<]+)</li><li class=\'txtMedium txtColor3 txtNormal left\' style=\'padding: 3px 10px 3px 10px;\'>([^<]+)</li><li class=\'txtSmall txtColor1 txtNormal left\' style=\'padding: 3px 10px 3px 10px;\'>([^<]+)</li></ul></li></ul>' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = match[1] scrapedtitle = match[2] + " - " + match[3] scrapedthumbnail = match[0] scrapedplot = match[2] + " - " + match[3] + chr(10) + match[4] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) #LISTADO ANTIGUO patron = 'style="background-image:url\((.*?)\);">.*?<a href="([^"]+)">.*?<img id="playOverIcon0_.*?" class="TipsMask3 playOverIcon" style="display:none;" onMouseOver="Javascript:keep_rollover.*?onMouseOut="Javascript:keep_rollover.*?src="http://i2.esmas.com/tvolucion/img/thumb_ico_play.gif" title="<ul style=\'list-style:none;\'><li style=\'width:11px; height:40px; background-image:.*?background-position:top; background-repeat:no-repeat; float:left;\'></li><li style=\'float:left; background-color:#E2E2E2; width:300px;\'><ul style=\'list-style:none;\'><li class=\'txtMedium txtColor1 txtBold left\' style=\'padding: 3px 10px 3px 10px;\'>([^<]+)</li><li class=\'txtMedium txtColor1 txtNormal left\' style=\'padding: 3px 10px 3px 10px;\'>([^<]+)</li><li class=\'txtSmall txtColor1 txtNormal left\' style=\'padding: 3px 10px 3px 10px;\'>([^<]+)</li></ul></li></ul>"/>' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) #itemlist = [] for match in matches: scrapedurl = match[1] scrapedtitle = match[2] + " - " + match[3] scrapedthumbnail = match[0] scrapedplot = match[2] + " - " + match[3] + chr(10) + match[4] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) #LISTADO NUEVO patron = '<li><span class="chaptersLongTitle">.*?<a href=\'http://televisadeportes.esmas.com/video/(.*?)\' class="txtColor4 txtMedium">([^<]+)</a>.*?</span>.*?<span class="chaptersLen">([^<]+)</span></li>' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) #itemlist = [] for match in matches: scrapedurl = "http://televisadeportes.esmas.com/video/"+match[0] scrapedtitle = match[1] scrapedthumbnail = "http://www.tvyespectaculos.com/wp-content/uploads/2010/07/Televisa.jpg" scrapedplot = match[1]+chr(10)+"DURACION: "+match[2]+chr(10)+scrapedurl logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) #temporadas patron = '<span class="seasonInfo">([^<]+)</span>.*?<span class="chaptersTitle"><a href="([^"]+)" class="txtColor4 txtMedium">([^<]+)</a></span>.*?<span class="chaptersLen">([^<]+)</span>' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) #itemlist = [] for match in matches: scrapedurl = match[1] scrapedtitle = match[0] + " - " + match[2] scrapedthumbnail = "http://www.tvyespectaculos.com/wp-content/uploads/2010/07/Televisa.jpg" scrapedplot = match[0] + " - " + match[2] + chr(10)+" DURACION : "+match[3] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) return itemlist def novelas(item): logger.info("[tvolucion.py] novelas") # Descarga la p‡gina data = scrapertools.cachePage(item.url) extra = item.extra # Extrae las entradas de la pagina seleccionada ''' <a class="ttn-list" href="http://tutelenovela.blogspot.com/2011/05/telenovela-corazon-abierto.html" title="A Corazon abierto"><div class="im"><img src="http://www.appelsiini.net/projects/lazyload/img/grey.gif" data-original="http://www.estadisco.com/tutelenovela/cover-novelas/a-corazon-abierto.jpg" /></div><div class="des"><span class="title">A Corazon abierto</span><span class="year">www.tutelenovela.net</span><span class="rep">Ver Capitulos de A Corazon abierto.</span></div></a> ''' patron = '<a class="ttn-list" href="(.*?)" title="([^<]+)"><div class="im"><img src="http://www.appelsiini.net/projects/lazyload/img/grey.gif" data-original="([^"]+)" /></div>'#<div class="im">.*?data-original="([^"]+)"/></a>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = match[0] scrapedtitle = match[1] scrapedthumbnail = match[2] scrapedplot = match[0] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="capitulo2", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) return itemlist def capitulo2(item): logger.info("[tvolucion.py] capitulo2") # Descarga la p‡gina data = scrapertools.cachePage(item.url) data.replace("<b>","") extra = item.extra # Extrae las entradas de la pagina seleccionada '''<a href="http://www.tutelenovela.net/2012/06/abismo-de-pasion-cap-97.html" style="background: orange;">Abismo de Pasion - Capitulo 97</a><br> <a href="http://www.tutelenovela.net/2012/06/abismo-de-pasion-cap-96.html" style="background: orange;">Abismo de Pasion - Capitulo 96</a><br> <a href="http://www.tutelenovela.net/2012/06/abismo-de-pasion-cap-95.html" style="background: #ccff00;">Abismo de Pasion - Capitulo 95</a><br> <a href="http://www.tutelenovela.info/teresa/800/capitulo-1.html">Teresa ~ Capitulo-1</a><br /> <a href="http://www.tutelenovela.info/teresa/801/capitulo-2.html">Teresa ~ Capitulo-2</a><br /> <a href="http://www.tutelenovela.net/2011/07/los-20-momentos-mas-importantes-de-la.html" style="background: orange;"><b>LOS 20 MOMENTOS MAS IMPORTANTES</b> | La Reina del Sur | TuTeleNovela.Net</a><br /> <a href="http://www.tutelenovela.net/2011/06/kate-del-castillo-y-teresa-entrevista.html" style="background: yellow;"><b>KATE DEL CASTILLO Y TERESA ENTREVISTA</b> | La Reina del Sur | TuTeleNovela.Net</a><br /> <a href="http://www.tutelenovela.net/2011/06/entrevista-kate-del-castillo-la-reina.html" style="background: ccffdd;"><b>ENTREVISTA A KATE DEL CASTILLO</b> | La Reina del Sur | TuTeleNovela.Net</a><br /> <a href="http://www.tutelenovela.net/2011/06/especial-con-los-actores-de-la-reina.html" style="background: pink;"><b>ESPECIAL CON LOS ACTORES</b> | La Reina del Sur | TuTeleNovela.Net</a><br /> <a href="http://www.tutelenovela.net/2011/05/especial-con-cristina-de-la-reina-del.html" style="background: skyblue;"><b>ESPECIAL CON CRISTINA</b> | La Reina del Sur | TuTeleNovela.Net</a><br /> <a href="http://www.tutelenovela.net/2011/05/telenovela-la-reina-del-sur-capitulo-63.html" style="background: yellow;">Capitulo 63 <b>[GRAN FINAL!!!]</b> | La Reina del Sur | TuTeleNovela.Net</a><br /> <a href="http://tutelenovela.blogspot.com/2011/05/telenovela-la-reina-del-sur-capitulo-62.html">Capitulo 62 | La Reina del Sur | TuTeleNovela.Net</a><br /> ''' #ESPECIALES # patron = '<td><a href="http://tvolucion.esmas.com/telenovelas/([^"]+)">([^<]+)</a>.*?<td>' patron = '<a href="([^"]+)" style=".*?"><b>([^<]+)<.*?<br' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = match[0] scrapedtitle = match[1] scrapedthumbnail = item.thumbnail scrapedplot = match[0] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video2", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) # CAPITULOS # patron = '<td><a href="http://tvolucion.esmas.com/telenovelas/([^"]+)">([^<]+)</a>.*?<td>' patron = '<a href="([^"]+)" style=".*?">([^<]+)<.*?<b' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) # itemlist = [] for match in matches: scrapedurl = match[0] scrapedtitle = match[1] scrapedthumbnail = item.thumbnail scrapedplot =match[0] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video2", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) # CAPITULOS .INFO patron = '<a href="http://www.tutelenovela.info/(.*?)">(.*?)</a><br' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) # itemlist = [] for match in matches: scrapedurl = "http://www.tutelenovela.info/"+match[0] scrapedtitle = match[1] scrapedthumbnail = item.thumbnail scrapedplot = "http://www.tutelenovela.info/"+match[0] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video2", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) # CAPITULOS BLOGSPOT patron = '<a href="http://tutelenovela.blogspot.com/(.*?)">(.*?)</a><br' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) # itemlist = [] for match in matches: scrapedurl = "http://tutelenovela.blogspot.com/"+match[0] scrapedtitle = match[1] scrapedthumbnail = item.thumbnail scrapedplot = "http://tutelenovela.blogspot.com/"+match[0] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video2", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) return itemlist def video2(item): logger.info("[tvolucion.py] video2") # Descarga la p‡gina data = scrapertools.cachePage(item.url) extra = item.extra # Extrae las entradas de la pagina seleccionada '''<div id="codtv" style="display:none;"> <embed type="application/x-shockwave-flash" src="http://data.tutelenovela.info/player2.swf" style="" id="mpl" name="mpl" quality="high" allowfullscreen="true" allowscriptaccess="always" flashvars="skin=&amp;plugins=fbit-1,tweetit-1,plusone-1,adttext&amp;file=mp4:/m4v/boh/abism/abism-c095/abism-c095-480&amp;streamer=rtmp://bright.tvolucion.com/ondemand/files/&amp;autostart=false&amp;adttext.config=http://http://data.tutelenovela.info/news.xml&amp;stretching=fill&amp;image=http://2.bp.blogspot.com/-8UbEL3s3LTw/TjHXDeARqsI/AAAAAAAAASw/ljTThn5olco/s1600/logoimage.jpg&amp;logo.file=http://4.bp.blogspot.com/-BqIUzzfYxFQ/TjHYQTa66KI/AAAAAAAAAS4/sxsPtxTnhZk/s1600/logoplayer.png&amp;logo.hide=false&amp;logo.position=top-left&amp;logo.link=http://www.tutelenovela.net&amp;abouttext=TUTELENOVELA.NET - Telenovelas y Series!&amp;aboutlink=http://www.tutelenovela.net/" height="450" width="700"> </div> rtmp://bright.tvolucion.com/ondemand/files/m4v/mp4:tln/t1-c101-desti/t1-c101-desti-150.mp4 ''' patron = 'file=mp4:(.*?)&amp;streamer=rtmp://(.*?)/files/&amp;' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: #scrapedurl = "rtmp://bright.tvolucion.com/ondemand/files/m4v/tln/t1-c101-desti/t1-c101-desti-150.mp4" scrapedurl = "rtmp://"+match[1]+"/files"+match[0]+".mp4" scrapedurlhd = scrapedurl.replace("-480.mp4","-600.mp4") scrapedtitle = item.title scrapedthumbnail = item.thumbnail scrapedplot = "rtmp://"+match[1]+"/files"+match[0]+".mp4" logger.info(scrapedtitle) # A–ade al listado # CALIDAD MEDIA itemlist.append( Item(channel=__channel__, action="play", title=scrapedtitle + " CALIDAD MEDIA ", url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) # CALIDAD HD itemlist.append( Item(channel=__channel__, action="play", title=scrapedtitle + " CALIDAD HD ", url=scrapedurlhd , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) # PARA BUSCAR FLV '''<div class="vvplayer"> <embed type='application/x-shockwave-flash' src='http://www.4shared.com/flash/player.swf' width='533' height='380' bgcolor='undefined' allowscriptaccess='always' allowfullscreen='true' wmode='transparent' flashvars='file=http://content2.catalog.video.msn.com/e2/ds/es-us/ESUS_Telemundo_Network/ESUS_Telemundo_La_Reina_del_Sur/e4962e44-1b59-4e0e-815e-ce967a79c3bc.flv&autostart=false&image=http://t1.gstatic.com/images?q=tbn:ANd9GcTO20FJSfFugNVmix_MOD3f9_rRO6VQfjygp4EY3Bfk0JIPu8hr&t=1&link=http://www.tutelenovela.net/&backcolor=000000&frontcolor=EEEEEE&lightcolor=FFFFFF&logo=http://4.bp.blogspot.com/-BqIUzzfYxFQ/TjHYQTa66KI/AAAAAAAAAS4/sxsPtxTnhZk/s1600/logoplayer.png&image=http://2.bp.blogspot.com/-8UbEL3s3LTw/TjHXDeARqsI/AAAAAAAAASw/ljTThn5olco/s1600/logoimage.jpg&volume=100&controlbar=over&stretching=exactfit'/></embed> </div>''' patron = '<embed type=.*?file=(.*?)flv(.*?)=false.*?</embed>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) # itemlist = [] for match in matches: #scrapedurl = "rtmp://bright.tvolucion.com/ondemand/files/m4v/tln/t1-c101-desti/t1-c101-desti-150.mp4" scrapedurl = match[0]+"flv" scrapedtitle = item.title scrapedthumbnail = item.thumbnail scrapedplot = match[0]+"flv" logger.info(scrapedtitle) # A–ade al listado # CALIDAD MEDIA itemlist.append( Item(channel=__channel__, action="play", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) return itemlist def novelasr(item): logger.info("[tvolucion.py] novelasr") # Descarga la p‡gina data = scrapertools.cachePage(item.url) extra = item.extra scrapedfanart = "NO" # Extrae las entradas de la pagina seleccionada '''<li> <a href="http://tvolucion.esmas.com/telenovelas/romantica/amor-bravio"><img src="http://i2.esmas.com/buttons/2012/03/01/25394/170x128.jpg" alt="Amor Brav’o"></a> <h3>Amor Brav’o</h3> <h4>2012</h4> </li> http://i2.esmas.com/img/espectaculos3/telenovelas/abismo-de-pasion/backArriba_usa.jpg http://i2.esmas.com/img/espectaculos3/telenovelas/cachitoDeCielo/back.jpg ''' patron = '<a href="http://tvolucion.esmas.com/telenovelas/([^"]+)"><img src="([^"]+)" alt="([^"]+)"></a>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: #scrapedurl1 = "http://m.tvolucion.esmas.com/telenovelas/"+match[0] scrapedurl1 = "http://tvolucion.esmas.com/telenovelas/"+match[0] string = match[0]+" " print "cadena " +string print string.find("/ ") if int(string.find("/ "))<0: scrapedurl = "http://googleak.esmas.com/search?q=site:http://tvolucion.esmas.com/telenovelas/"+match[0]+"&btnG=Google+Search&access=p&client=masarchivo&site=portal&output=xml_no_dtd&proxystylesheet=tv3vidrecientes&entqrm=0&oe=UTF-8&ie=UTF-8&ud=1&exclude_apps=1&getfields=*&num=25&sort=date:D:L:d1&entqr=6&filter=0&ip=189.254.126.103,63.99.211.110&start=0" else: string =string[0:string.find("/ ")] scrapedurl = "http://googleak.esmas.com/search?q=site:http://tvolucion.esmas.com/telenovelas/"+string+"&btnG=Google+Search&access=p&client=masarchivo&site=portal&output=xml_no_dtd&proxystylesheet=tv3vidrecientes&entqrm=0&oe=UTF-8&ie=UTF-8&ud=1&exclude_apps=1&getfields=*&num=25&sort=date:D:L:d1&entqr=6&filter=0&ip=189.254.126.103,63.99.211.110&start=0" print scrapedurl scrapedtitle = match[2] scrapedthumbnail = match[1] scrapedplot = scrapedurl logger.info(scrapedtitle) # baja fanart data2 = scrapertools.cachePage(scrapedurl1) patron2 = '<img src="([^"]+)" class="stage.*?>(.*?)</div>' matches2 = re.compile(patron2,re.DOTALL).findall(data2) for match2 in matches2: scrapedfanart = match2[0] #baja plot patron3 = '<div class="info" style=.*?<h3>(.*?)</h3>.*?<h4>(.*?)</h4>.*?<h5>(.*?)</h5>' matches3 = re.compile(patron3,re.DOTALL).findall(data2) for match3 in matches3: scrapedplot = match3[0] #+chr(10)+match2[1] +chr(10)+match2[2] +chr(10)+match2[3] +chr(10)+match2[4] # A–ade al listado itemlist.append( Item(channel=__channel__, action="capitulo", title=scrapedtitle , url=scrapedurl1 , thumbnail=scrapedthumbnail , fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=True) ) return itemlist def novelasa(item): logger.info("[tvolucion.py] novelasa") # Descarga la p‡gina data = scrapertools.cachePage(item.url) data2 = data.replace("**","=") extra = item.extra scrapedfanart = "NO" # Extrae las entradas de la pagina seleccionada patron = '"url"="([^"]+)",\';.*?elenco"="([^"]+)",\';.*?productor"="([^"]+)",\';.*?anio"="([^"]+)",\';.*?programa"="([^"]+)",\';.*?programaclean"="([^"]+)"\';' #patron = '"url"="([^"]+)",\';.*?elenco"="([^"]+)",\';.*?productor"="([^"]+)\';.*?anio"="([^"]+)",\';.*?programa"="([^"]+)",\';.*?programaclean"="([^"]+)"\';' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data2) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = match[0] scrapedtitle = match[4] scrapedthumbnail = "" scrapedplot = match[4]+chr(10)+"ELENCO :"+match[1]+chr(10)+"PRODUCTOR :"+match[2]+chr(10)+"A„O :"+match[3] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="capitulona", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=True) ) return itemlist def noticias(item): logger.info("[tvolucion.py] noticias") # Descarga la p‡gina data = scrapertools.cachePage(item.url) extra = item.extra scrapedfanart = "NO" # Extrae las entradas de la pagina seleccionada '''<li> <a href="http://tvolucion.esmas.com/telenovelas/romantica/amor-bravio"><img src="http://i2.esmas.com/buttons/2012/03/01/25394/170x128.jpg" alt="Amor Brav’o"></a> <h3>Amor Brav’o</h3> <h4>2012</h4> </li> ''' patron = '<a href="http://tvolucion.esmas.com/noticieros/([^"]+)"><img src="([^"]+)" alt="([^"]+)"></a>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = "http://tvolucion.esmas.com/noticieros/"+match[0] scrapedtitle = match[2] scrapedthumbnail = match[1] scrapedplot = "http://tvolucion.esmas.com/noticieros/"+match[0] logger.info(scrapedtitle) # baja fanart data2 = scrapertools.cachePage(scrapedurl) patron2 = '<img src="([^"]+)" class="stage.*?>(.*?)</div>' matches2 = re.compile(patron2,re.DOTALL).findall(data2) for match2 in matches2: scrapedfanart = match2[0] #baja plot patron3 = '<div class="info" style=.*?<h3>(.*?)</h3>.*?<h4>(.*?)</h4>.*?<h5>(.*?)</h5>' matches3 = re.compile(patron3,re.DOTALL).findall(data2) for match3 in matches3: scrapedplot = match3[0] #+chr(10)+match2[1] +chr(10)+match2[2] +chr(10)+match2[3] +chr(10)+match2[4] # A–ade al listado itemlist.append( Item(channel=__channel__, action="capitulo", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=True) ) return itemlist def programas(item): logger.info("[tvolucion.py] programas") # Descarga la p‡gina data = scrapertools.cachePage(item.url) extra = item.extra # Extrae las entradas de la pagina seleccionada '''<li> <a href="http://tvolucion.esmas.com/telenovelas/romantica/amor-bravio"><img src="http://i2.esmas.com/buttons/2012/03/01/25394/170x128.jpg" alt="Amor Brav’o"></a> <h3>Amor Brav’o</h3> <h4>2012</h4> </li> ''' # PROGRAMAS DE TV patron = '<a href="http://tvolucion.esmas.com/programas-de-tv/([^"]+)"><img src="([^"]+)" alt="([^"]+)"></a>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = "http://tvolucion.esmas.com/programas-de-tv/"+match[0] scrapedtitle = match[2] scrapedthumbnail = match[1] scrapedfanart = "" scrapedplot = "http://tvolucion.esmas.com/programas-de-tv/"+match[0] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="capitulo", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , fanart="", plot=scrapedplot , extra=extra , folder=True) ) # TELEHIT patron = '<a href="http://tvolucion.esmas.com/telehit/([^"]+)"><img src="([^"]+)" alt="([^"]+)"></a>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) #itemlist = [] for match in matches: scrapedurl = "http://tvolucion.esmas.com/telehit/"+match[0] scrapedtitle = match[2] scrapedthumbnail = match[1] scrapedfanart = "" scrapedplot = "http://tvolucion.esmas.com/telehit/"+match[0] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="capitulo", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , fanart="", plot=scrapedplot , extra=extra , folder=True) ) # COMICOS patron = '<a href="http://tvolucion.esmas.com/comicos/([^"]+)"><img src="([^"]+)" alt="([^"]+)"></a>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) #itemlist = [] for match in matches: scrapedurl = "http://tvolucion.esmas.com/comicos/"+match[0] scrapedtitle = match[2] scrapedthumbnail = match[1] scrapedfanart = "" scrapedplot = "http://tvolucion.esmas.com/comicos/"+match[0] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="capitulo", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , fanart="", plot=scrapedplot , extra=extra , folder=True) ) return itemlist def capitulo(item): logger.info("[tvolucion.py] capitulo") # Descarga la p‡gina data = scrapertools.cachePage(item.url) print data urlbase = item.url extra = item.extra # Extrae las entradas de la pagina seleccionada '''<tr class="odd"> <td><a href="http://tvolucion.esmas.com/telenovelas/drama/amores-verdaderos/200767/amores-verdaderos-capitulo-75">Amenaza de muerte</a></td> <td>En el capitulo 75 de Amores verdaderos, Leonardo amenaza a Beatriz, la maltrata y le asegura que si no regresa con l, la mata</td> <!-- <td class="right">8,572</td> --> <td>00:40:39</td> <td>14/12/12</td> <td class="noborder">75</td> </tr> ''' # NOVELAS # patron = '<td><a href="http://tvolucion.esmas.com/telenovelas/([^"]+)">([^<]+)</a>.*?<td>' patron = '<td><a href="http://tvolucion.esmas.com/telenovelas/([^"]+)">([^<]+)</a>.*?<td>([^<]+)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td class="noborder">(.*?)</td>.*?</tr>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = "http://tvolucion.esmas.com/telenovelas/"+match[0]+"/" scrapedtitle = match[5]+" - "+match[1] scrapedthumbnail = item.thumbnail scrapedfanart = item.fanart scrapedplot = match[2]+ chr(10)+" DURACION : "+match[3]+chr(10)+" ESTRENO : "+match[4] +chr(10)+item.fanart print scrapedtitle # A–ade al listado itemlist.append( Item(channel=__channel__, action="video", title=scrapedtitle , url=scrapedurl , page=urlbase, thumbnail=scrapedthumbnail ,fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=True) ) # NOVELAS V2 ''' <ul id="cont-fila-art"> <li class="thumb"><a href="http://tvolucion.esmas.com/telenovelas/drama/abismo-de-pasion/179216/abismo-pasion-capitulo-114/" target="_top"><img src="http://m4v.tvolucion.com/m4v/boh/abism/abism-c114/abism-c114.jpg" align="left"></a></li> <li class="nombrePrograma">Abismo de pasi—n</li> <li class="titulo-art">Cancelar el contrato</li> <li class="Duracion">Duracion: 00:42:12</li> <li class="capitulo">Capitulo: 114</li> <li class="pre-fecha">Fecha:&nbsp;</li> <li class="fecha-pub-art">&nbsp;29/06/2012</li> </ul> <R N="1"><U>http://tvolucion.esmas.com/telenovelas/drama/amores-verdaderos/200767/amores-verdaderos-capitulo-75/</U><UE>http://tvolucion.esmas.com/telenovelas/drama/amores-verdaderos/200767/amores-verdaderos-capitulo-75/</UE><T>Amenaza de muerte</T><RK>10</RK><CRAWLDATE>17 Dec 2012</CRAWLDATE><ENT_SOURCE>T2-A5AY6GP5HY2T5</ENT_SOURCE><FS NAME="date" VALUE="2012-12-17"/><S>Amenaza de muerte </S><LANG>en</LANG><HAS><L/><C SZ="1k" CID="9rajlf5d3UQJ" ENC="ISO-8859-1"/></HAS></R> <R N="2"><U>http://tvolucion.esmas.com/telenovelas/drama/amores-verdaderos/200431/amores-verdaderos-capitulo-73/</U><UE>http://tvolucion.esmas.com/telenovelas/drama/amores-verdaderos/200431/amores-verdaderos-capitulo-73/</UE><T>Culpa de padres</T><RK>10</RK><ENT_SOURCE>T2-A5AY6GP5HY2T5</ENT_SOURCE><FS NAME="date" VALUE="2012-12-13"/><S>Culpa de padres </S><LANG>en</LANG><HAS><L/><C SZ="1k" CID="JsPJNG5nJo8J" ENC="ISO-8859-1"/></HAS></R> <li> <a href="http://tvolucion.esmas.com/telenovelas/drama/amores-verdaderos/200767/amores-verdaderos-capitulo-75"><img src="http://m4v.tvolucion.com/m4v/boh/verda/b6206593f5defebda8ed2ed456a3230b/defebda8ed.jpg" /></a> <h3>Amores verdaderos</h3> <h4>Amenaza de muerte</h4> <h4>Duraci—n: 00:40:39</h4> <h4>Cap’tulo: 75</h4> <h4>Fecha: 14/12/12</h4> </li> <li>.*?<a href="([^"]+)"><img src="([^"]+)" /></a>.*?<h3>([^<]+)</h3>.*?<h4>([^<]+)</h4>.*?<h4>Duraci—n: ([^<]+)</h4>.*?<h4>Cap’tulo: ([^<]+)</h4>.*?<h4>Fecha: ([^<]+)</h4>.*?</li> 0 link 1 poster 2 novela 3 episodio 4 duracion 5 capitulo 6 fecha ''' #patron = '<ul id="cont-fila-art">.*?<li class="thumb"><a href="http://tvolucion.esmas.com/telenovelas/([^"]+)" target="_top"><img src="([^"]+)" align="left"></a></li>.*?<li class="nombrePrograma">(.*?)</li>.*?<li class="titulo-art">(.*?)</li>.*?<li class="Duracion">Duracion: (.*?)</li>.*?<li class="capitulo">Capitulo: (.*?)</li>.*?<li class="pre-fecha">Fecha:&nbsp;</li>.*?<li class="fecha-pub-art">&nbsp;(.*?)</li>.*?</ul>' #patron = '<li>.*?<a href="([^"]+)"><img src="([^"]+)" /></a>.*?<h3>(.*?)</h3>.*?<h4>(.*?)</h4>.*?<h4>Duraci—n: (.*?)</h4>.*?<h4>Cap’tulo: (.*?)</h4>.*?<h4>Fecha: (.*?)</h4>.*?</li>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' patron = '<R N=".*?"><U>([^<]+)</U><UE>.*?capitulo-(.*?)/</UE><T>([^<]+)</T><RK>.*?</RK>.*?<ENT_SOURCE>.*?</ENT_SOURCE><FS NAME="date" VALUE="([^"]+)"/><S>(.*?)</S><LANG>.*?</LANG><HAS><L/><C SZ=".*?" CID=".*?" ENC=".*?"/></HAS></R>' print "intenta obtener patron 2" matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = match[0] #"http://tvolucion.esmas.com/telenovelas/"+match[0]+"/" print scrapedurl scrapedtitle = match[1]+" - "+match[2] scrapedthumbnail = ""#match[1] scrapedfanart = item.fanart scrapedplot = ""#match[3]+ chr(10)+" DURACION : "+match[4]+chr(10)+" ESTRENO : "+match[6] +chr(10)+match[0] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video", title=scrapedtitle , url=scrapedurl , page=urlbase, thumbnail=scrapedthumbnail ,fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=True) ) # NOTICIAS # patron = '<td><a href="http://tvolucion.esmas.com/telenovelas/([^"]+)">([^<]+)</a>.*?<td>' patron = '<td><a href="http://tvolucion.esmas.com/noticieros/([^"]+)">([^<]+)</a>.*?<td>([^<]+)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td class="noborder">(.*?)</td>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) #itemlist = [] for match in matches: scrapedurl = "http://tvolucion.esmas.com/noticieros/"+match[0] scrapedtitle = match[5]+" - "+match[1] scrapedthumbnail = item.thumbnail scrapedfanart = item.fanart scrapedplot = match[2]+ chr(10)+" DURACION : "+match[3]+chr(10)+" ESTRENO : "+match[4] +chr(10)+"http://tvolucion.esmas.com/noticieros/"+match[0] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video", title=scrapedtitle , url=scrapedurl , page=urlbase, thumbnail=scrapedthumbnail ,fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=True) ) # COMICOS # patron = '<td><a href="http://tvolucion.esmas.com/telenovelas/([^"]+)">([^<]+)</a>.*?<td>' patron = '<td><a href="http://tvolucion.esmas.com/comicos/([^"]+)">([^<]+)</a>.*?<td>([^<]+)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td class="noborder">(.*?)</td>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) #itemlist = [] for match in matches: scrapedurl = "http://tvolucion.esmas.com/comicos/"+match[0]+"/" scrapedtitle = match[1] scrapedthumbnail = item.thumbnail scrapedplot = match[2]+ chr(10)+" DURACION : "+match[3]+chr(10)+" ESTRENO : "+match[4] +chr(10)+"http://tvolucion.esmas.com/comicos/"+match[0]+"/" scrapedfanart = item.fanart logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video", title=scrapedtitle , url=scrapedurl , page=urlbase, thumbnail=scrapedthumbnail ,fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=True) ) # PROGRAMAS TV # patron = '<td><a href="http://tvolucion.esmas.com/telenovelas/([^"]+)">([^<]+)</a>.*?<td>' patron = '<td><a href="http://tvolucion.esmas.com/programas-de-tv/([^"]+)">([^<]+)</a>.*?<td>([^<]+)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td class="noborder">(.*?)</td>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) #itemlist = [] for match in matches: scrapedurl = "http://tvolucion.esmas.com/programas-de-tv/"+match[0]+"/" scrapedtitle = match[5]+" - "+match[1] scrapedthumbnail = item.thumbnail scrapedplot = match[2]+ chr(10)+" DURACION : "+match[3]+chr(10)+" ESTRENO : "+match[4] scrapedfanart = item.fanart logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video", title=scrapedtitle , url=scrapedurl , page=urlbase, thumbnail=scrapedthumbnail ,fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=True) ) # PROGRAMAS - TELEHIT # patron = '<td><a href="http://tvolucion.esmas.com/telenovelas/([^"]+)">([^<]+)</a>.*?<td>' patron = '<td><a href="http://tvolucion.esmas.com/telehit/([^"]+)">([^<]+)</a>.*?<td>([^<]+)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td class="noborder">(.*?)</td>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) #itemlist = [] for match in matches: scrapedurl = "http://tvolucion.esmas.com/telehit/"+match[0]+"/" scrapedtitle = match[5]+" - "+match[1] scrapedthumbnail = item.thumbnail scrapedplot = match[2]+ chr(10)+" DURACION : "+match[3]+chr(10)+" ESTRENO : "+match[4] scrapedfanart = item.fanart logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video", title=scrapedtitle , url=scrapedurl , page=urlbase, thumbnail=scrapedthumbnail ,fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=True) ) # PROGRAMAS - EL CHAVO patron = 'var playlistURL_dos = \'(.*?)&callback=.*?start-index=(.*?)&max-results=50' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) number = item.extra print number flag = number.isdigit() print flag if flag : number = int(number) else : number = 1 print number if DEBUG: scrapertools.printMatches(matches) #baja json for match in matches: scrapedurl = match[0]+"&start-index="+str(number)+"&max-results=50&orderby=published" scrapedtitle = "test" scrapedthumbnail = "" scrapedplot = match[0] scrapedfanart = "" number = number +50 print number print scrapedurl # baja caps ''' "title":{"$t":"Juguetes de papel"},"content":{"type":"application/x-shockwave-flash","src":"http://www.youtube.com/v/0Tl1Okg_h48?version=3&f=playlists&app=youtube_gdata"},"link":[{"rel":"alternate","type":"text/html","href":"http://www.youtube.com/watch?v=0Tl1Okg_h48&feature=youtube_gdata"}, ''' data2 = scrapertools.cachePage(scrapedurl) data2 = data2.replace("$","") patron2 = '"title":{"t":"([^"]+)"},"content":{"type":"application/x-shockwave-flash","src":"(.*?)version=3&f=playlists&app=youtube_gdata"},"link.*?"alternate","type":"text/html","href":"(.*?)"}.*?"mediadescription":{"t":"([^"]+)","type":"plain"},"mediakeywords":' matches2 = re.compile(patron2,re.DOTALL).findall(data2) count = 1 for match2 in matches2: scrapedtitle = match2[0] scrapedurl = match2[2] #scrapedurl = match2[1][:match2[1].find("?")] #scrapedurl = scrapedurl.replace("http://www.youtube.com/v/","http://www.youtube.com/watch?v=") scrapedplot = match2[3] id = match2[1].replace("http://www.youtube.com/v/","") id = id[:id.find("?")] print str(count) + " " +id scrapedthumbnail = "http://i.ytimg.com/vi/"+id+"/hqdefault.jpg" count = count +1 # A–ade al listado itemlist.append( Item(channel=__channel__, action="play", server="youtube", title=scrapedtitle , url=scrapedurl , page=urlbase, thumbnail=scrapedthumbnail ,fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=False) ) # A–ade al listado print count if count > 35: itemlist.append( Item(channel=__channel__, action="capitulo", title="CAPITULOS ANTERIORES >>" , url=item.url , page=urlbase, thumbnail="" ,fanart=scrapedfanart, plot="Ver capitulos anteriores." , extra=str(number) , folder=True) ) # KIDS -CINE Y TV patron = '<td><a href="([^"]+)">([^<]+)</a>.*?<td>([^<]+)</td>.*?<td>([^<]+)</td>.*?<td>([^<]+)</td>' #patron = 'href="([^"]+)"><img src="([^"]+)" /></a>.*?<h4>([^<]+)</h4>.*?<h4>([^<]+)</h4>.*?<h4>([^<]+)</h4>.*?<h4>([^<]+)</h4>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) #itemlist = [] for match in matches: scrapedurl = match[0] scrapedtitle = match[1] scrapedthumbnail = "" scrapedplot = match[2]+ chr(10)+" DURACION : "+match[3]+chr(10)+" ESTRENO : "+match[4] scrapedfanart = "" # baja fanart data2 = scrapertools.cachePage(scrapedurl) ''' videoImgFrame='http://m4v.tvolucion.com/m4v/cus/trail/trail-20120223erahielo4/trail-20120223erahielo4.jpg'; ''' print "bajando imagen para video "+match[1] patron2 = 'videoUrlQvt = \'(.*?)\';.*?videoImgFrame=\'(.*?)\';.*?' matches2 = re.compile(patron2,re.DOTALL).findall(data2) for match2 in matches2: scrapedthumbnail = match2[1] scrapedurl2 = match2[0] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="video", title=scrapedtitle , url=scrapedurl , page=urlbase, thumbnail=scrapedthumbnail ,fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=True) ) return itemlist def playYoutube(item): logger.info("[tvolucion.py] playYoutube") itemlist = [] # Extrae el ID id = youtube.Extract_id(item.url) logger.info("[tvolucion.py] id="+id) # Descarga la p‡gina data = scrapertools.cache_page(item.url) # Obtiene la URL url = youtube.geturls(id,data) itemlist.append( Item(channel=CHANNELNAME, title=item.title , action="play" , server="Directo", url=url, thumbnail=item.thumbnail , folder=False) ) return itemlist def capitulona(item): logger.info("[tvolucion.py] capitulona") # Descarga la p‡gina data = scrapertools.cachePage(item.url) urlbase = item.url extra = item.extra # Extrae las entradas de la pagina seleccionada '''<td><a href="http://tvolucion.esmas.com/telenovelas/romantica/amor-bravio/175807/amor-bravio-capitulo-67">Regresa el padre de Ximena</a></td> <td>En el capitulo 67 de Amor brav’o, Francisco se presenta con Dionisio para cobrar la herencia de Daniel y es reconocido como el pap‡ de Ximena</td> <!-- <td class="right">8,572</td> --> <td>00:43:18</td> <td>05/06/12</td> <td class="noborder">67</td> ''' # NOVELAS # patron = '<td><a href="http://tvolucion.esmas.com/telenovelas/([^"]+)">([^<]+)</a>.*?<td>' patron = '<td><a href="http://tvolucion.esmas.com/telenovelas/([^"]+)">([^<]+)</a>.*?<td>([^<]+)</td>.*?<td>(.*?)</td>.*?<td>(.*?)</td>.*?<td class="noborder">(.*?)</td>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = "http://tvolucion.esmas.com/telenovelas/"+match[0]+"/" scrapedtitle = match[5]+" - "+match[1] scrapedthumbnail = item.thumbnail scrapedfanart = item.fanart scrapedplot = match[2]+ chr(10)+" DURACION : "+match[3]+chr(10)+" ESTRENO : "+match[4] +chr(10)+scrapedurl logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="videona", title=scrapedtitle , url=scrapedurl , page=urlbase, thumbnail=scrapedthumbnail ,fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=True) ) return itemlist def videona(item): logger.info("[tvolucion.py] videona") # Descarga la p‡gina data = scrapertools.cachePage(item.url) extra = item.extra ''' videoUrlQvt = 'http://m4v.tvolucion.com/m4v/boh/dadmi/dadmi-20111031derecho/dadmi-20111031derecho-480.mp4'; id: "8736919-e95e4cda-986a-4590-ae1f-6aa1e797de75", cat: "2012/06/08", profile: "bca", gbs : id: "133275", cat: "esmas", profile: "hls2", gbs: "716ee5cf447289f814a8ef5f9ad86bb5" http://publish20.cdn.movenetworks.com/cms/publish/vod/vodclip/esmas/133275.qvt http://media.esmas.com/criticalmedia/files/2012/06/08/8736919-e95e4cda-986a-4590-ae1f-6aa1e797de75.mp4 scrapedurl = "http://publish20.cdn.movenetworks.com/cms/publish/vod/vodclip/"+match[2]+"/"+match[1]+".qvt" patron = 'thumbnail: "([^"]+)".*?id: "([^"]+)".*?cat: "([^"]+)",.*?profile: "([^"]+)",.*?gbs: "([^"]+)",.*?extension = \'(.*?)\';' scrapedurl = "http://media.esmas.com/criticalmedia/files/"+match[2]+"/"+match[1]+".mp4" http://media.esmas.com/criticalmedia/files/2011/07/09/4297022-45b437e6-9db3-4425-a2cc-448cdde97c69.mp4 http://media.esmas.com/criticalmedia/assets/2713950-b790cc30-8ac1-48ff-95e3-37bc18b4db39.mp4 http://apps.tvolucion.com/m3u8/tln/t1-c143-teres/t1-c143-teres.m3u8 ''' #OTROS (WEB NORMAL) patron = 'videoUrlQvt = \'(.*?)\';.*?thumbnail: "([^"]+)".*?id: "([^"]+)".*?cat: "([^"]+)",.*?profile: "([^"]+)",.*?gbs: "([^"]+)",.*?extension = \'(.*?)\';' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: plus = "" extension = match[6][2:] flag = extension.isdigit() scrapedurl = match[0] find = scrapedurl.find("-480.mp4") if find >= 0 : scrapedurl = scrapedurl.replace("-480.mp4","/")+match[2] scrapedurl = scrapedurl.replace("-480",".m3u8") scrapedurl = scrapedurl.replace("m4v.","apps.") scrapedurl = scrapedurl.replace("/m4v/","/m3u8/") print "1 " + scrapedurl else : scrapedurl = match[0] print "1 " + scrapedurl #scrapedurl = scrapedurl.replace("http://","rtmp://") #scrapedurlhd = scrapedurlhd.replace("-480.mp4","-,15,48,60,0.mp4.csmil/bitrate=2") scrapedtitle = item.title scrapedthumbnail = match[1] scrapedfanart = item.fanart scrapedplot = item.plot logger.info(scrapedtitle) print scrapedurl # A–ade al listado # CALIDAD MEDIA if flag : if (float(extension) != 4) : ends = match[2] ends = ends[ends.find("/"):] scrapedurl = "http://apps.tvolucion.com/m4v/"+match[3]+"/"+match[2]+"/"+ends+"-600.mp4" scrapedplot=scrapedplot+chr(10)+scrapedurl +chr(10)+extension+chr(10)+match[0] itemlist.append( Item(channel=__channel__, action="play", title=scrapedtitle+" (Calidad: Media)" , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=False) ) else : scrapedplot=scrapedplot+chr(10)+scrapedurl +chr(10)+extension+chr(10)+match[0] itemlist.append( Item(channel=__channel__, action="capitulo", title="VIDEO NO COMPATIBLE" , url=item.page, thumbnail=scrapedthumbnail , plot="Video formato QVT, no compatible con XBMC" , extra=extra , folder=False) ) return itemlist def video(item): logger.info("[tvolucion.py] video") # Descarga la p‡gina data = scrapertools.cachePage(item.url) extra = item.extra print "entra a video" # Extrae las entradas de la pagina seleccionada '''<video width="294" height="165" controls autoplay="autoplay" poster="http://m4v.tvolucion.com/m4v/boh/abism/abism-c092/abism-c092.jpg" style="margin: 0pt 13px;"> <source src="http://apps.tvolucion.com/m4v/boh/abism/abism-c092/abism-c092-150.mp4" type="video/mp4; codecs='avc1,mp4a'" /> </video> http://m4vhd.tvolucion.com/m4v/boh/abism/abism-c001/abism-c001-,15,48,60,0.mp4.csmil/bitrate=2 <video width="294" height="165" controls autoplay="autoplay" poster="http://media.esmas.com/criticalmedia/files/2012/06/07/8721239-c7c8bd61-a196-471b-a98f-789b0468c458.jpg" style="margin: 0pt 13px;"> <source src="http://apps.esmas.com/criticalmedia/files/2012/06/07/8721242-9043291a-ab74-4c1e-bdde-326c425e341d.mp4" type="video/mp4; codecs='avc1,mp4a'" /> </video> videoUrlQvt = 'http://media.esmas.com/criticalmedia/files/2012/06/07/8721806-07abc298-eac0-4050-abfa-8199bb0ee2e9.mp4'; http://apps.esmas.com/criticalmedia/files/2012/06/07/8721242-9043291a-ab74-4c1e-bdde-326c425e341d.mp4 // alert('id: "8721806-07abc298-eac0-4050-abfa-8199bb0ee2e9", cat: "2012/06/07", profile: "bca", otro : '); ''' #NOVELAS (WEB MOVIL) print "INTENRTA MOVIL" patron = '<video id="video1" width="294" height="165" controls poster="([^"]+)" style=.*?<source src="([^"]+)" type="([^"]+)" />' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: print "encontro movil" scrapedurl = match[1] scrapedurl = scrapedurl.replace("-150.mp4","-480.mp4") #scrapedurl = scrapedurl.replace("http://","rtmp://") scrapedurlhd = scrapedurl.replace("apps.","apps.") scrapedurlhd = scrapedurlhd.replace("-480.mp4","-600.mp4") scrapedtitle = item.title scrapedthumbnail = match[0] scrapedfanart = item.fanart scrapedplot = item.plot +chr(10)+scrapedurl +chr(10)+scrapedurlhd logger.info(scrapedtitle) # A–ade al listado # CALIDAD MEDIA itemlist.append( Item(channel=__channel__, action="play", title=scrapedtitle+" (Calidad: Media)" , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) # CALIDAD HD itemlist.append( Item(channel=__channel__, action="play", title=scrapedtitle+" (Calidad: HD)" , url=scrapedurlhd , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) ''' videoUrlQvt = 'http://m4v.tvolucion.com/m4v/boh/dadmi/dadmi-20111031derecho/dadmi-20111031derecho-480.mp4'; id: "8736919-e95e4cda-986a-4590-ae1f-6aa1e797de75", cat: "2012/06/08", profile: "bca", gbs : id: "133275", cat: "esmas", profile: "hls2", gbs: "716ee5cf447289f814a8ef5f9ad86bb5" http://publish20.cdn.movenetworks.com/cms/publish/vod/vodclip/esmas/133275.qvt http://media.esmas.com/criticalmedia/files/2012/06/08/8736919-e95e4cda-986a-4590-ae1f-6aa1e797de75.mp4 scrapedurl = "http://publish20.cdn.movenetworks.com/cms/publish/vod/vodclip/"+match[2]+"/"+match[1]+".qvt" patron = 'thumbnail: "([^"]+)".*?id: "([^"]+)".*?cat: "([^"]+)",.*?profile: "([^"]+)",.*?gbs: "([^"]+)",.*?extension = \'(.*?)\';' scrapedurl = "http://media.esmas.com/criticalmedia/files/"+match[2]+"/"+match[1]+".mp4" ''' print "INTENTA WEB" #OTROS (WEB NORMAL) patron = 'videoUrlQvt = \'(.*?)\';.*?thumbnail: "([^"]+)".*?id: "([^"]+)".*?cat: "([^"]+)",.*?profile: "([^"]+)",.*?gbs: "([^"]+)",.*?extension = \'(.*?)\';' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) #itemlist = [] for match in matches: print "encontro web" plus = "" extension = match[6][2:] flag = extension.isdigit() print flag scrapedurl = match[0] #"http://media.esmas.com/criticalmedia/files/"+match[3]+"/"+match[2]+".mp4" scrapedurl = scrapedurl.replace("-480.mp4","-600.mp4") scrapedurl = scrapedurl.replace("m4v.","apps.") if "?" in scrapedurl: scrapedurl = scrapedurl[:scrapedurl.find("?")] #scrapedurl = scrapedurl.replace("http://","rtmp://") #scrapedurlhd = scrapedurlhd.replace("-480.mp4","-,15,48,60,0.mp4.csmil/bitrate=2") scrapedtitle = item.title scrapedthumbnail = match[1] scrapedfanart = item.fanart scrapedplot = item.plot logger.info(scrapedtitle) print str(scrapedurl) # A–ade al listado # CALIDAD MEDIA if flag : print "entra a la bandera" if (float(extension) != 4) : print "formato no es mp4" ismp4 = scrapedurl.find(".mp4") if ismp4 >=1: print "si es mp4, se queda el url original" else: ends = match[2] isf1 = ends.find("/") if isf1 >=1: print isf1 ends = ends[ends.find("/"):] scrapedurl = "http://apps.tvolucion.com/m4v/"+match[3]+"/"+match[2]+"/"+ends+"-600.mp4" else: scrapedurl = match[1].replace(".jpg","-600.mp4") scrapedurl = scrapedurl.replace("m4v.","apps.") scrapedplot=scrapedplot+chr(10)+scrapedurl +chr(10)+extension+chr(10)+match[0] itemlist.append( Item(channel=__channel__, action="play", title=scrapedtitle+" (Calidad: Media)" , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) else : if scrapedurl.find(".mp4"): itemlist.append( Item(channel=__channel__, action="play", title=scrapedtitle+" (Calidad: Web)" , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) else: print "no es mp, probablemente es formato anterior QVT" scrapedplot=scrapedplot+chr(10)+scrapedurl +chr(10)+extension+chr(10)+match[0] itemlist.append( Item(channel=__channel__, action="capitulo", title="VIDEO NO COMPATIBLE" , url=item.page, thumbnail=scrapedthumbnail , plot="Video formato QVT, no compatible con XBMC" , extra=extra , folder=True) ) return itemlist def tv(item): logger.info("[tvolucion.py] tv") # Descarga la p‡gina data = scrapertools.cachePage(item.url) extra = item.extra # Extrae las entradas de la pagina seleccionada '''<video width="294" height="165" controls autoplay="autoplay" poster="http://m4v.tvolucion.com/m4v/boh/abism/abism-c092/abism-c092.jpg" style="margin: 0pt 13px;"> <source src="http://apps.tvolucion.com/m4v/boh/abism/abism-c092/abism-c092-150.mp4" type="video/mp4; codecs='avc1,mp4a'" /> </video> http://apps.tvolucion.com/m4v/boh/teresa/teresa-capitulo-148/t1.148-teres-480.mp4 http://apps.tvolucion.com/m4v/tln/t1.148-teres-480.mp4 http://m4vhd.tvolucion.com/m4v/boh/abism/abism-c001/abism-c001-,15,48,60,0.mp4.csmil/bitrate=2 rtmp://bright.tvolucion.com/ondemand/files/m4v/mp4:tln/t1-c101-desti/t1-c101-desti-150.mp4 ''' patron = 'flashvars="&streamer=(.*?).flv&autostart=(.*?).*?/></embed>' # patron += 'href="([^"]+)"><img src="([^"]+)" alt="([^"]+)"' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = "rtmp://176.31.231.57/edge playpath=to8ykizy8es8pl5 swfUrl=http://cdn.static.ilive.to/jwplayer/player_new.swf pageUrl=http://www.ilive.to/view/1598/dansertv_2 timeout=60" scrapedtitle = "CANAL DE LAS ESTRELLAS" scrapedthumbnail = "http://3.bp.blogspot.com/-DI-1Ceh_4Tk/T0m0XVZ9KqI/AAAAAAAABKk/EIdylQgWr0w/s1600/Canal-Estrellas-En_Vivo.jpg" scrapedplot = "Es el canal familiar de Televisa, promueve los valores, las tradiciones y el respeto. Es l’der en la televisi—n mexicana y l’der de habla hispana en el mundo, transmite diariamente a Estados Unidos, Canad‡, Centro y SudamŽrica, Europa y Ocean’a. Su programaci—n incluye telenovelas, noticieros, espect‡culos, deportes, unitarios, etc." logger.info(scrapedtitle) # A–ade al listado # CALIDAD MEDIA itemlist.append( Item(channel=__channel__, action="play", title=scrapedtitle+" (Calidad: Media)" , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=False) ) # rtmp://cp77659.live.edgefcs.net:1935/live/1_pvpj8n23_1@60491 scrapedurl = "rtmp://c81.webcaston.com/live/channel/telerisa playpath:telerisa swfUrl=http://www.webcaston.com/player/player.swf pageUrl=http://www.webcaston.com/telerisa" scrapedtitle = "CANAL 13" scrapedthumbnail = "http://3.bp.blogspot.com/-DI-1Ceh_4Tk/T0m0XVZ9KqI/AAAAAAAABKk/EIdylQgWr0w/s1600/Canal-Estrellas-En_Vivo.jpg" scrapedplot = "Es el canal familiar de Televisa, promueve los valores, las tradiciones y el respeto. Es l’der en la televisi—n mexicana y l’der de habla hispana en el mundo, transmite diariamente a Estados Unidos, Canad‡, Centro y SudamŽrica, Europa y Ocean’a. Su programaci—n incluye telenovelas, noticieros, espect‡culos, deportes, unitarios, etc." logger.info(scrapedtitle) # A–ade al listado # CALIDAD MEDIA # itemlist.append( Item(channel=__channel__, action="play", title=scrapedtitle+" (Calidad: Media)" , url=scrapedurl , thumbnail=scrapedthumbnail , plot=scrapedplot , extra=extra , folder=True) ) return itemlist # patron = 'flashvars="&streamer=(.*?).flv&autostart=(.*?).*?/></embed>' # scrapedurl = "rtmp://live.ilive.to/redirect&file=to8ykizy8es8pl5.flv" # scrapedtitle = match[0] # scrapedthumbnail = "" # scrapedplot = "rtmp://live.ilive.to/redirect&file=to8ykizy8es8pl5.flv" # logger.info(scrapedtitle) def teresa(item): logger.info("[tvolucion.py] teresa") # Descarga la p‡gina data = scrapertools.cachePage(item.url) extra = item.extra scrapedfanart = "NO" # Extrae las entradas de la pagina seleccionada patron = '<td><a href="(.*?)">(.*?)</a></td>' matches = re.compile(patron,re.DOTALL).findall(data) if DEBUG: scrapertools.printMatches(matches) itemlist = [] for match in matches: scrapedurl = match[0] scrapedtitle = match[1] scrapedthumbnail = "" scrapedplot = match[1] logger.info(scrapedtitle) # A–ade al listado itemlist.append( Item(channel=__channel__, action="play", title=scrapedtitle , url=scrapedurl , thumbnail=scrapedthumbnail , fanart=scrapedfanart, plot=scrapedplot , extra=extra , folder=True) ) return itemlist def search(item,texto): logger.info("[tvolucion.py] search") itemlist = [] texto = texto.replace(" ","+") try: # Series item.url="http://www.peliculasaudiolatino.com/result.php?q=%s&type=search&x=0&y=0" item.url = item.url % texto item.extra = "" itemlist.extend(listado2(item)) itemlist = sorted(itemlist, key=lambda Item: Item.title) return itemlist # Se captura la excepci—n, para no interrumpir al buscador global si un canal falla except: import sys for line in sys.exc_info(): logger.error( "%s" % line ) return [] # Verificación automática de canales: Esta función debe devolver "True" si todo está ok en el canal. def test(): # Todas las opciones tienen que tener algo items = mainlist(Item()) series_items = novelasr(items[2]) for serie_item in series_items: exec "itemlist="+serie_item.action+"(serie_item)" if len(itemlist)>0: return True return True
gpl-2.0
frankier/mezzanine
mezzanine/core/templatetags/mezzanine_tags.py
2
27229
from __future__ import absolute_import, division, unicode_literals from future.builtins import int, open, str from hashlib import md5 import os try: from urllib.parse import quote, unquote except ImportError: from urllib import quote, unquote from django.apps import apps from django.contrib import admin from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.sites.models import Site from django.core.exceptions import ObjectDoesNotExist from django.core.files import File from django.core.files.storage import default_storage from django.urls import reverse, resolve, NoReverseMatch from django.db.models import Model from django.template import Node, Template, TemplateSyntaxError from django.template.base import (TOKEN_BLOCK, TOKEN_COMMENT, TOKEN_TEXT, TOKEN_VAR, TextNode) from django.template.defaultfilters import escape from django.template.loader import get_template from django.utils import translation from django.utils.html import strip_tags from django.utils.text import capfirst from django.utils.safestring import SafeText, mark_safe from mezzanine.conf import settings from mezzanine.core.fields import RichTextField from mezzanine.core.forms import get_edit_form from mezzanine.utils.cache import nevercache_token, cache_installed from mezzanine.utils.html import decode_entities from mezzanine.utils.importing import import_dotted_path from mezzanine.utils.sites import current_site_id, has_site_permission from mezzanine.utils.urls import admin_url, home_slug from mezzanine.utils.views import is_editable from mezzanine import template register = template.Library() if "compressor" in settings.INSTALLED_APPS: @register.tag def compress(parser, token): """ Shadows django-compressor's compress tag so it can be loaded from ``mezzanine_tags``, allowing us to provide a dummy version when django-compressor isn't installed. """ from compressor.templatetags.compress import compress return compress(parser, token) else: @register.to_end_tag def compress(parsed, context, token): """ Dummy tag for fallback when django-compressor isn't installed. """ return parsed def initialize_nevercache(): if cache_installed(): @register.tag def nevercache(parser, token): """ Tag for two phased rendering. Converts enclosed template code and content into text, which gets rendered separately in ``mezzanine.core.middleware.UpdateCacheMiddleware``. This is to bypass caching for the enclosed code and content. """ text = [] end_tag = "endnevercache" tag_mapping = { TOKEN_TEXT: ("", ""), TOKEN_VAR: ("{{", "}}"), TOKEN_BLOCK: ("{%", "%}"), TOKEN_COMMENT: ("{#", "#}"), } delimiter = nevercache_token() while parser.tokens: token = parser.next_token() token_type = token.token_type if token_type == TOKEN_BLOCK and token.contents == end_tag: return TextNode(delimiter + "".join(text) + delimiter) start, end = tag_mapping[token_type] text.append("%s%s%s" % (start, token.contents, end)) parser.unclosed_block_tag(end_tag) else: @register.to_end_tag def nevercache(parsed, context, token): """ Dummy fallback ``nevercache`` for when caching is not configured. """ return parsed initialize_nevercache() @register.simple_tag(takes_context=True) def fields_for(context, form, template="includes/form_fields.html"): """ Renders fields for a form with an optional template choice. """ context["form_for_fields"] = form return get_template(template).render(context.flatten()) @register.inclusion_tag("includes/form_errors.html") def errors_for(form): """ Renders an alert if the form has any errors. """ return {"form": form} @register.filter def sort_by(items, attr): """ General sort filter - sorts by either attribute or key. """ def key_func(item): try: return getattr(item, attr) except AttributeError: try: return item[attr] except TypeError: getattr(item, attr) # Reraise AttributeError return sorted(items, key=key_func) @register.filter def is_installed(app_name): """ Returns ``True`` if the given app name is in the ``INSTALLED_APPS`` setting. """ from warnings import warn warn("The is_installed filter is deprecated. Please use the tag " "{% ifinstalled appname %}{% endifinstalled %}") return app_name in settings.INSTALLED_APPS @register.tag def ifinstalled(parser, token): """ Old-style ``if`` tag that renders contents if the given app is installed. The main use case is: {% ifinstalled app_name %} {% include "app_name/template.html" %} {% endifinstalled %} so we need to manually pull out all tokens if the app isn't installed, since if we used a normal ``if`` tag with a False arg, the include tag will still try and find the template to include. """ try: tag, app = token.split_contents() except ValueError: raise TemplateSyntaxError("ifinstalled should be in the form: " "{% ifinstalled app_name %}" "{% endifinstalled %}") end_tag = "end" + tag unmatched_end_tag = 1 if app.strip("\"'") not in settings.INSTALLED_APPS: while unmatched_end_tag: token = parser.tokens.pop(0) if token.token_type == TOKEN_BLOCK: block_name = token.contents.split()[0] if block_name == tag: unmatched_end_tag += 1 if block_name == end_tag: unmatched_end_tag -= 1 parser.tokens.insert(0, token) nodelist = parser.parse((end_tag,)) parser.delete_first_token() class IfInstalledNode(Node): def render(self, context): return nodelist.render(context) return IfInstalledNode() @register.render_tag def set_short_url_for(context, token): """ Sets the ``short_url`` attribute of the given model for share links in the template. """ obj = context[token.split_contents()[1]] obj.set_short_url() return "" @register.simple_tag def gravatar_url(email, size=32): """ Return the full URL for a Gravatar given an email hash. """ bits = (md5(email.lower().encode("utf-8")).hexdigest(), size) return "//www.gravatar.com/avatar/%s?s=%s&d=identicon&r=PG" % bits @register.to_end_tag def metablock(parsed): """ Remove HTML tags, entities and superfluous characters from meta blocks. """ parsed = " ".join(parsed.replace("\n", "").split()).replace(" ,", ",") return escape(strip_tags(decode_entities(parsed))) @register.inclusion_tag("includes/pagination.html", takes_context=True) def pagination_for(context, current_page, page_var="page", exclude_vars=""): """ Include the pagination template and data for persisting querystring in pagination links. Can also contain a comma separated string of var names in the current querystring to exclude from the pagination links, via the ``exclude_vars`` arg. """ querystring = context["request"].GET.copy() exclude_vars = [v for v in exclude_vars.split(",") if v] + [page_var] for exclude_var in exclude_vars: if exclude_var in querystring: del querystring[exclude_var] querystring = querystring.urlencode() return { "current_page": current_page, "querystring": querystring, "page_var": page_var, } @register.inclusion_tag("includes/search_form.html", takes_context=True) def search_form(context, search_model_names=None): """ Includes the search form with a list of models to use as choices for filtering the search by. Models should be a string with models in the format ``app_label.model_name`` separated by spaces. The string ``all`` can also be used, in which case the models defined by the ``SEARCH_MODEL_CHOICES`` setting will be used. """ template_vars = { "request": context["request"], } if not search_model_names or not settings.SEARCH_MODEL_CHOICES: search_model_names = [] elif search_model_names == "all": search_model_names = list(settings.SEARCH_MODEL_CHOICES) else: search_model_names = search_model_names.split(" ") search_model_choices = [] for model_name in search_model_names: try: model = apps.get_model(*model_name.split(".", 1)) except LookupError: pass else: verbose_name = model._meta.verbose_name_plural.capitalize() search_model_choices.append((verbose_name, model_name)) template_vars["search_model_choices"] = sorted(search_model_choices) return template_vars @register.simple_tag def thumbnail(image_url, width, height, upscale=True, quality=95, left=.5, top=.5, padding=False, padding_color="#fff"): """ Given the URL to an image, resizes the image using the given width and height on the first time it is requested, and returns the URL to the new resized image. If width or height are zero then original ratio is maintained. When ``upscale`` is False, images smaller than the given size will not be grown to fill that size. The given width and height thus act as maximum dimensions. """ if not image_url: return "" try: from PIL import Image, ImageFile, ImageOps except ImportError: return "" image_url = unquote(str(image_url)).split("?")[0] if image_url.startswith(settings.MEDIA_URL): image_url = image_url.replace(settings.MEDIA_URL, "", 1) image_dir, image_name = os.path.split(image_url) image_prefix, image_ext = os.path.splitext(image_name) filetype = {".png": "PNG", ".gif": "GIF"}.get(image_ext.lower(), "JPEG") thumb_name = "%s-%sx%s" % (image_prefix, width, height) if not upscale: thumb_name += "-no-upscale" if left != .5 or top != .5: left = min(1, max(0, left)) top = min(1, max(0, top)) thumb_name = "%s-%sx%s" % (thumb_name, left, top) thumb_name += "-padded-%s" % padding_color if padding else "" thumb_name = "%s%s" % (thumb_name, image_ext) # `image_name` is used here for the directory path, as each image # requires its own sub-directory using its own name - this is so # we can consistently delete all thumbnails for an individual # image, which is something we do in filebrowser when a new image # is written, allowing us to purge any previously generated # thumbnails that may match a new image name. thumb_dir = os.path.join(settings.MEDIA_ROOT, image_dir, settings.THUMBNAILS_DIR_NAME, image_name) if not os.path.exists(thumb_dir): try: os.makedirs(thumb_dir) except OSError: pass thumb_path = os.path.join(thumb_dir, thumb_name) thumb_url = "%s/%s/%s" % (settings.THUMBNAILS_DIR_NAME, quote(image_name.encode("utf-8")), quote(thumb_name.encode("utf-8"))) image_url_path = os.path.dirname(image_url) if image_url_path: thumb_url = "%s/%s" % (image_url_path, thumb_url) try: thumb_exists = os.path.exists(thumb_path) except UnicodeEncodeError: # The image that was saved to a filesystem with utf-8 support, # but somehow the locale has changed and the filesystem does not # support utf-8. from mezzanine.core.exceptions import FileSystemEncodingChanged raise FileSystemEncodingChanged() if thumb_exists: # Thumbnail exists, don't generate it. return thumb_url elif not default_storage.exists(image_url): # Requested image does not exist, just return its URL. return image_url f = default_storage.open(image_url) try: image = Image.open(f) except: # Invalid image format. return image_url image_info = image.info # Transpose to align the image to its orientation if necessary. # If the image is transposed, delete the exif information as # not all browsers support the CSS image-orientation: # - http://caniuse.com/#feat=css-image-orientation try: orientation = image._getexif().get(0x0112) except: orientation = None if orientation: methods = { 2: (Image.FLIP_LEFT_RIGHT,), 3: (Image.ROTATE_180,), 4: (Image.FLIP_TOP_BOTTOM,), 5: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_90), 6: (Image.ROTATE_270,), 7: (Image.FLIP_LEFT_RIGHT, Image.ROTATE_270), 8: (Image.ROTATE_90,)}.get(orientation, ()) if methods: image_info.pop('exif', None) for method in methods: image = image.transpose(method) to_width = int(width) to_height = int(height) from_width = image.size[0] from_height = image.size[1] if not upscale: to_width = min(to_width, from_width) to_height = min(to_height, from_height) # Set dimensions. if to_width == 0: to_width = from_width * to_height // from_height elif to_height == 0: to_height = from_height * to_width // from_width if image.mode not in ("P", "L", "RGBA") \ and filetype not in ("JPG", "JPEG"): try: image = image.convert("RGBA") except: return image_url # Required for progressive jpgs. ImageFile.MAXBLOCK = 2 * (max(image.size) ** 2) # Padding. if padding and to_width and to_height: from_ratio = float(from_width) / from_height to_ratio = float(to_width) / to_height pad_size = None if to_ratio < from_ratio: pad_height = int(to_height * (float(from_width) / to_width)) pad_size = (from_width, pad_height) pad_top = (pad_height - from_height) // 2 pad_left = 0 elif to_ratio > from_ratio: pad_width = int(to_width * (float(from_height) / to_height)) pad_size = (pad_width, from_height) pad_top = 0 pad_left = (pad_width - from_width) // 2 if pad_size is not None: pad_container = Image.new("RGBA", pad_size, padding_color) pad_container.paste(image, (pad_left, pad_top)) image = pad_container # Create the thumbnail. to_size = (to_width, to_height) to_pos = (left, top) try: image = ImageOps.fit(image, to_size, Image.ANTIALIAS, 0, to_pos) image = image.save(thumb_path, filetype, quality=quality, **image_info) # Push a remote copy of the thumbnail if MEDIA_URL is # absolute. if "://" in settings.MEDIA_URL: with open(thumb_path, "rb") as f: default_storage.save(unquote(thumb_url), File(f)) except Exception: # If an error occurred, a corrupted image may have been saved, # so remove it, otherwise the check for it existing will just # return the corrupted image next time it's requested. try: os.remove(thumb_path) except Exception: pass return image_url return thumb_url @register.inclusion_tag("includes/editable_loader.html", takes_context=True) def editable_loader(context): """ Set up the required JS/CSS for the in-line editing toolbar and controls. """ user = context["request"].user template_vars = { "has_site_permission": has_site_permission(user), "request": context["request"], } if (settings.INLINE_EDITING_ENABLED and template_vars["has_site_permission"]): t = get_template("includes/editable_toolbar.html") template_vars["REDIRECT_FIELD_NAME"] = REDIRECT_FIELD_NAME template_vars["editable_obj"] = context.get("editable_obj", context.get("page", None)) template_vars["accounts_logout_url"] = context.get( "accounts_logout_url", None) template_vars["toolbar"] = t.render(template_vars) template_vars["richtext_media"] = RichTextField().formfield( ).widget.media return template_vars @register.filter def richtext_filters(content): """ Takes a value edited via the WYSIWYG editor, and passes it through each of the functions specified by the RICHTEXT_FILTERS setting. """ for filter_name in settings.RICHTEXT_FILTERS: filter_func = import_dotted_path(filter_name) content = filter_func(content) if not isinstance(content, SafeText): # raise TypeError( # filter_name + " must mark it's return value as safe. See " # "https://docs.djangoproject.com/en/stable/topics/security/" # "#cross-site-scripting-xss-protection") import warnings warnings.warn( filter_name + " needs to ensure that any untrusted inputs are " "properly escaped and mark the html it returns as safe. In a " "future release this will cause an exception. See " "https://docs.djangoproject.com/en/stable/topics/security/" "cross-site-scripting-xss-protection", FutureWarning) content = mark_safe(content) return content @register.to_end_tag def editable(parsed, context, token): """ Add the required HTML to the parsed content for in-line editing, such as the icon and edit form if the object is deemed to be editable - either it has an ``editable`` method which returns ``True``, or the logged in user has change permissions for the model. """ def parse_field(field): field = field.split(".") obj = context.get(field.pop(0), None) attr = field.pop() while field: obj = getattr(obj, field.pop(0)) if callable(obj): # Allows {% editable page.get_content_model.content %} obj = obj() return obj, attr fields = [parse_field(f) for f in token.split_contents()[1:]] if fields: fields = [f for f in fields if len(f) == 2 and f[0] is fields[0][0]] if not parsed.strip(): try: parsed = "".join([str(getattr(*field)) for field in fields]) except AttributeError: pass if settings.INLINE_EDITING_ENABLED and fields and "request" in context: obj = fields[0][0] if isinstance(obj, Model) and is_editable(obj, context["request"]): field_names = ",".join([f[1] for f in fields]) context["editable_form"] = get_edit_form(obj, field_names) context["original"] = parsed t = get_template("includes/editable_form.html") return t.render(context.flatten()) return parsed @register.simple_tag def try_url(url_name): """ Mimics Django's ``url`` template tag but fails silently. Used for url names in admin templates as these won't resolve when admin tests are running. """ from warnings import warn warn("try_url is deprecated, use the url tag with the 'as' arg instead.") try: url = reverse(url_name) except NoReverseMatch: return "" return url def admin_app_list(request): """ Adopted from ``django.contrib.admin.sites.AdminSite.index``. Returns a list of lists of models grouped and ordered according to ``mezzanine.conf.ADMIN_MENU_ORDER``. Called from the ``admin_dropdown_menu`` template tag as well as the ``app_list`` dashboard widget. """ app_dict = {} # Model or view --> (group index, group title, item index, item title). menu_order = {} for (group_index, group) in enumerate(settings.ADMIN_MENU_ORDER): group_title, items = group for (item_index, item) in enumerate(items): if isinstance(item, (tuple, list)): item_title, item = item else: item_title = None menu_order[item] = (group_index, group_title, item_index, item_title) # Add all registered models, using group and title from menu order. for (model, model_admin) in admin.site._registry.items(): opts = model._meta in_menu = not hasattr(model_admin, "in_menu") or model_admin.in_menu() if hasattr(model_admin, "in_menu"): import warnings warnings.warn( 'ModelAdmin.in_menu() has been replaced with ' 'ModelAdmin.has_module_permission(request). See ' 'https://docs.djangoproject.com/en/stable/ref/contrib/admin/' '#django.contrib.admin.ModelAdmin.has_module_permission.', DeprecationWarning) in_menu = in_menu and model_admin.has_module_permission(request) if in_menu and request.user.has_module_perms(opts.app_label): admin_url_name = "" if model_admin.has_change_permission(request): admin_url_name = "changelist" change_url = admin_url(model, admin_url_name) else: change_url = None if model_admin.has_add_permission(request): admin_url_name = "add" add_url = admin_url(model, admin_url_name) else: add_url = None if admin_url_name: model_label = "%s.%s" % (opts.app_label, opts.object_name) try: app_index, app_title, model_index, model_title = \ menu_order[model_label] except KeyError: app_index = None try: app_title = opts.app_config.verbose_name.title() except AttributeError: # Third party admin classes doing weird things. # See GH #1628 app_title = "" model_index = None model_title = None else: del menu_order[model_label] if not model_title: model_title = capfirst(model._meta.verbose_name_plural) if app_title not in app_dict: app_dict[app_title] = { "index": app_index, "name": app_title, "models": [], } app_dict[app_title]["models"].append({ "index": model_index, "perms": model_admin.get_model_perms(request), "name": model_title, "object_name": opts.object_name, "admin_url": change_url, "add_url": add_url }) # Menu may also contain view or url pattern names given as (title, name). for (item_url, item) in menu_order.items(): app_index, app_title, item_index, item_title = item try: item_url = reverse(item_url) except NoReverseMatch: continue if app_title not in app_dict: app_dict[app_title] = { "index": app_index, "name": app_title, "models": [], } app_dict[app_title]["models"].append({ "index": item_index, "perms": {"custom": True}, "name": item_title, "admin_url": item_url, }) app_list = list(app_dict.values()) sort = lambda x: (x["index"] if x["index"] is not None else 999, x["name"]) for app in app_list: app["models"].sort(key=sort) app_list.sort(key=sort) return app_list @register.inclusion_tag("admin/includes/dropdown_menu.html", takes_context=True) def admin_dropdown_menu(context): """ Renders the app list for the admin dropdown menu navigation. """ user = context["request"].user if user.is_staff: context["dropdown_menu_app_list"] = admin_app_list(context["request"]) if user.is_superuser: sites = Site.objects.all() else: try: sites = user.sitepermissions.sites.all() except ObjectDoesNotExist: sites = Site.objects.none() context["dropdown_menu_sites"] = list(sites) context["dropdown_menu_selected_site_id"] = current_site_id() return context.flatten() @register.inclusion_tag("admin/includes/app_list.html", takes_context=True) def app_list(context): """ Renders the app list for the admin dashboard widget. """ context["dashboard_app_list"] = admin_app_list(context["request"]) return context.flatten() @register.inclusion_tag("admin/includes/recent_actions.html", takes_context=True) def recent_actions(context): """ Renders the recent actions list for the admin dashboard widget. """ return context.flatten() @register.render_tag def dashboard_column(context, token): """ Takes an index for retrieving the sequence of template tags from ``mezzanine.conf.DASHBOARD_TAGS`` to render into the admin dashboard. """ column_index = int(token.split_contents()[1]) output = [] for tag in settings.DASHBOARD_TAGS[column_index]: t = Template("{%% load %s %%}{%% %s %%}" % tuple(tag.split("."))) output.append(t.render(context)) return "".join(output) @register.simple_tag(takes_context=True) def translate_url(context, language): """ Translates the current URL for the given language code, eg: {% translate_url "de" %} """ try: request = context["request"] except KeyError: return "" view = resolve(request.path) current_language = translation.get_language() translation.activate(language) if not view.namespace and view.url_name == "home": url = home_slug() else: try: url = reverse(view.func, args=view.args, kwargs=view.kwargs) except NoReverseMatch: try: url_name = (view.url_name if not view.namespace else '%s:%s' % (view.namespace, view.url_name)) url = reverse(url_name, args=view.args, kwargs=view.kwargs) except NoReverseMatch: url_name = "admin:" + view.url_name url = reverse(url_name, args=view.args, kwargs=view.kwargs) translation.activate(current_language) qs = context['request'].META.get("QUERY_STRING", "") if qs: url += "?" + qs return url
bsd-2-clause
xkcd1253/SocialNetworkforTwo
flask/lib/python2.7/site-packages/wtforms/ext/sqlalchemy/fields.py
54
6679
""" Useful form fields for use with SQLAlchemy ORM. """ from __future__ import unicode_literals import operator from wtforms import widgets from wtforms.compat import text_type, string_types from wtforms.fields import SelectFieldBase from wtforms.validators import ValidationError try: from sqlalchemy.orm.util import identity_key has_identity_key = True except ImportError: has_identity_key = False __all__ = ( 'QuerySelectField', 'QuerySelectMultipleField', ) class QuerySelectField(SelectFieldBase): """ Will display a select drop-down field to choose between ORM results in a sqlalchemy `Query`. The `data` property actually will store/keep an ORM model instance, not the ID. Submitting a choice which is not in the query will result in a validation error. This field only works for queries on models whose primary key column(s) have a consistent string representation. This means it mostly only works for those composed of string, unicode, and integer types. For the most part, the primary keys will be auto-detected from the model, alternately pass a one-argument callable to `get_pk` which can return a unique comparable key. The `query` property on the field can be set from within a view to assign a query per-instance to the field. If the property is not set, the `query_factory` callable passed to the field constructor will be called to obtain a query. Specify `get_label` to customize the label associated with each option. If a string, this is the name of an attribute on the model object to use as the label text. If a one-argument callable, this callable will be passed model instance and expected to return the label text. Otherwise, the model object's `__str__` or `__unicode__` will be used. If `allow_blank` is set to `True`, then a blank choice will be added to the top of the list. Selecting this choice will result in the `data` property being `None`. The label for this blank choice can be set by specifying the `blank_text` parameter. """ widget = widgets.Select() def __init__(self, label=None, validators=None, query_factory=None, get_pk=None, get_label=None, allow_blank=False, blank_text='', **kwargs): super(QuerySelectField, self).__init__(label, validators, **kwargs) self.query_factory = query_factory if get_pk is None: if not has_identity_key: raise Exception('The sqlalchemy identity_key function could not be imported.') self.get_pk = get_pk_from_identity else: self.get_pk = get_pk if get_label is None: self.get_label = lambda x: x elif isinstance(get_label, string_types): self.get_label = operator.attrgetter(get_label) else: self.get_label = get_label self.allow_blank = allow_blank self.blank_text = blank_text self.query = None self._object_list = None def _get_data(self): if self._formdata is not None: for pk, obj in self._get_object_list(): if pk == self._formdata: self._set_data(obj) break return self._data def _set_data(self, data): self._data = data self._formdata = None data = property(_get_data, _set_data) def _get_object_list(self): if self._object_list is None: query = self.query or self.query_factory() get_pk = self.get_pk self._object_list = list((text_type(get_pk(obj)), obj) for obj in query) return self._object_list def iter_choices(self): if self.allow_blank: yield ('__None', self.blank_text, self.data is None) for pk, obj in self._get_object_list(): yield (pk, self.get_label(obj), obj == self.data) def process_formdata(self, valuelist): if valuelist: if self.allow_blank and valuelist[0] == '__None': self.data = None else: self._data = None self._formdata = valuelist[0] def pre_validate(self, form): data = self.data if data is not None: for pk, obj in self._get_object_list(): if data == obj: break else: raise ValidationError(self.gettext('Not a valid choice')) elif self._formdata or not self.allow_blank: raise ValidationError(self.gettext('Not a valid choice')) class QuerySelectMultipleField(QuerySelectField): """ Very similar to QuerySelectField with the difference that this will display a multiple select. The data property will hold a list with ORM model instances and will be an empty list when no value is selected. If any of the items in the data list or submitted form data cannot be found in the query, this will result in a validation error. """ widget = widgets.Select(multiple=True) def __init__(self, label=None, validators=None, default=None, **kwargs): if default is None: default = [] super(QuerySelectMultipleField, self).__init__(label, validators, default=default, **kwargs) self._invalid_formdata = False def _get_data(self): formdata = self._formdata if formdata is not None: data = [] for pk, obj in self._get_object_list(): if not formdata: break elif pk in formdata: formdata.remove(pk) data.append(obj) if formdata: self._invalid_formdata = True self._set_data(data) return self._data def _set_data(self, data): self._data = data self._formdata = None data = property(_get_data, _set_data) def iter_choices(self): for pk, obj in self._get_object_list(): yield (pk, self.get_label(obj), obj in self.data) def process_formdata(self, valuelist): self._formdata = set(valuelist) def pre_validate(self, form): if self._invalid_formdata: raise ValidationError(self.gettext('Not a valid choice')) elif self.data: obj_list = list(x[1] for x in self._get_object_list()) for v in self.data: if v not in obj_list: raise ValidationError(self.gettext('Not a valid choice')) def get_pk_from_identity(obj): cls, key = identity_key(instance=obj) return ':'.join(text_type(x) for x in key)
gpl-2.0
jodizzle/hangups
docs/generate_proto_docs.py
3
7452
"""Generate reStructuredText documentation from Protocol Buffers.""" import argparse import subprocess import sys import tempfile import textwrap from google.protobuf import descriptor_pb2 INFINITY = 10000 # pylint: disable=no-member LABEL_TO_STR = {value: name.lower()[6:] for name, value in descriptor_pb2.FieldDescriptorProto.Label.items()} TYPE_TO_STR = {value: name.lower()[5:] for name, value in descriptor_pb2.FieldDescriptorProto.Type.items()} # pylint: enable=no-member def print_table(col_tuple, row_tuples): """Print column headers and rows as a reStructuredText table. Args: col_tuple: Tuple of column name strings. row_tuples: List of tuples containing row data. """ col_widths = [max(len(str(row[col])) for row in [col_tuple] + row_tuples) for col in range(len(col_tuple))] format_str = ' '.join('{{:<{}}}'.format(col_width) for col_width in col_widths) header_border = ' '.join('=' * col_width for col_width in col_widths) print(header_border) print(format_str.format(*col_tuple)) print(header_border) for row_tuple in row_tuples: print(format_str.format(*row_tuple)) print(header_border) print() def make_subsection(text): """Format text as reStructuredText subsection. Args: text: Text string to format. Returns: Formatted text string. """ return '{}\n{}\n'.format(text, '-' * len(text)) def make_link(text): """Format text as reStructuredText link. Args: text: Text string to format. Returns: Formatted text string. """ return '`{}`_'.format(text) def make_code(text): """Format text as reStructuredText code. Args: text: Text string to format. Returns: Formatted text string. """ return ':code:`{}`'.format(text) def make_comment(text): """Format text as reStructuredText comment. Args: text: Text string to format. Returns: Formatted text string. """ return '.. {}\n'.format(text) def get_comment_from_location(location): """Return comment text from location. Args: location: descriptor_pb2.SourceCodeInfo.Location instance to get comment from. Returns: Comment as string. """ return textwrap.dedent(location.leading_comments or location.trailing_comments) def generate_enum_doc(enum_descriptor, locations, path, name_prefix=''): """Generate doc for an enum. Args: enum_descriptor: descriptor_pb2.EnumDescriptorProto instance for enum to generate docs for. locations: Dictionary of location paths tuples to descriptor_pb2.SourceCodeInfo.Location instances. path: Path tuple to the enum definition. name_prefix: Optional prefix for this enum's name. """ print(make_subsection(name_prefix + enum_descriptor.name)) location = locations[path] if location.HasField('leading_comments'): print(textwrap.dedent(location.leading_comments)) row_tuples = [] for value_index, value in enumerate(enum_descriptor.value): field_location = locations[path + (2, value_index)] row_tuples.append(( make_code(value.name), value.number, textwrap.fill(get_comment_from_location(field_location), INFINITY), )) print_table(('Name', 'Number', 'Description'), row_tuples) def generate_message_doc(message_descriptor, locations, path, name_prefix=''): """Generate docs for message and nested messages and enums. Args: message_descriptor: descriptor_pb2.DescriptorProto instance for message to generate docs for. locations: Dictionary of location paths tuples to descriptor_pb2.SourceCodeInfo.Location instances. path: Path tuple to the message definition. name_prefix: Optional prefix for this message's name. """ # message_type is 4 prefixed_name = name_prefix + message_descriptor.name print(make_subsection(prefixed_name)) location = locations[path] if location.HasField('leading_comments'): print(textwrap.dedent(location.leading_comments)) row_tuples = [] for field_index, field in enumerate(message_descriptor.field): field_location = locations[path + (2, field_index)] if field.type not in [11, 14]: type_str = TYPE_TO_STR[field.type] else: type_str = make_link(field.type_name.lstrip('.')) row_tuples.append(( make_code(field.name), field.number, type_str, LABEL_TO_STR[field.label], textwrap.fill(get_comment_from_location(field_location), INFINITY), )) print_table(('Field', 'Number', 'Type', 'Label', 'Description'), row_tuples) # Generate nested messages nested_types = enumerate(message_descriptor.nested_type) for index, nested_message_desc in nested_types: generate_message_doc(nested_message_desc, locations, path + (3, index), name_prefix=prefixed_name + '.') # Generate nested enums for index, nested_enum_desc in enumerate(message_descriptor.enum_type): generate_enum_doc(nested_enum_desc, locations, path + (4, index), name_prefix=prefixed_name + '.') def compile_protofile(proto_file_path): """Compile proto file to descriptor set. Args: proto_file_path: Path to proto file to compile. Returns: Path to file containing compiled descriptor set. Raises: SystemExit if the compilation fails. """ out_file = tempfile.mkstemp()[1] try: subprocess.check_output(['protoc', '--include_source_info', '--descriptor_set_out', out_file, proto_file_path]) except subprocess.CalledProcessError as e: sys.exit('protoc returned status {}'.format(e.returncode)) return out_file def main(): """Parse arguments and print generated documentation to stdout.""" parser = argparse.ArgumentParser() parser.add_argument('protofilepath') args = parser.parse_args() out_file = compile_protofile(args.protofilepath) with open(out_file, 'rb') as proto_file: # pylint: disable=no-member file_descriptor_set = descriptor_pb2.FileDescriptorSet.FromString( proto_file.read() ) # pylint: enable=no-member for file_descriptor in file_descriptor_set.file: # Build dict of location tuples locations = {} for location in file_descriptor.source_code_info.location: locations[tuple(location.path)] = location # Add comment to top print(make_comment('This file was automatically generated from {} and ' 'should be be edited directly.' .format(args.protofilepath))) # Generate documentation for index, message_desc in enumerate(file_descriptor.message_type): generate_message_doc(message_desc, locations, (4, index)) for index, enum_desc in enumerate(file_descriptor.enum_type): generate_enum_doc(enum_desc, locations, (5, index)) if __name__ == '__main__': main()
mit
kawamon/hue
desktop/core/ext-py/asn1crypto-0.24.0/asn1crypto/parser.py
27
9149
# coding: utf-8 """ Functions for parsing and dumping using the ASN.1 DER encoding. Exports the following items: - emit() - parse() - peek() Other type classes are defined that help compose the types listed above. """ from __future__ import unicode_literals, division, absolute_import, print_function import sys from ._types import byte_cls, chr_cls, type_name from .util import int_from_bytes, int_to_bytes _PY2 = sys.version_info <= (3,) _INSUFFICIENT_DATA_MESSAGE = 'Insufficient data - %s bytes requested but only %s available' def emit(class_, method, tag, contents): """ Constructs a byte string of an ASN.1 DER-encoded value This is typically not useful. Instead, use one of the standard classes from asn1crypto.core, or construct a new class with specific fields, and call the .dump() method. :param class_: An integer ASN.1 class value: 0 (universal), 1 (application), 2 (context), 3 (private) :param method: An integer ASN.1 method value: 0 (primitive), 1 (constructed) :param tag: An integer ASN.1 tag value :param contents: A byte string of the encoded byte contents :return: A byte string of the ASN.1 DER value (header and contents) """ if not isinstance(class_, int): raise TypeError('class_ must be an integer, not %s' % type_name(class_)) if class_ < 0 or class_ > 3: raise ValueError('class_ must be one of 0, 1, 2 or 3, not %s' % class_) if not isinstance(method, int): raise TypeError('method must be an integer, not %s' % type_name(method)) if method < 0 or method > 1: raise ValueError('method must be 0 or 1, not %s' % method) if not isinstance(tag, int): raise TypeError('tag must be an integer, not %s' % type_name(tag)) if tag < 0: raise ValueError('tag must be greater than zero, not %s' % tag) if not isinstance(contents, byte_cls): raise TypeError('contents must be a byte string, not %s' % type_name(contents)) return _dump_header(class_, method, tag, contents) + contents def parse(contents, strict=False): """ Parses a byte string of ASN.1 BER/DER-encoded data. This is typically not useful. Instead, use one of the standard classes from asn1crypto.core, or construct a new class with specific fields, and call the .load() class method. :param contents: A byte string of BER/DER-encoded data :param strict: A boolean indicating if trailing data should be forbidden - if so, a ValueError will be raised when trailing data exists :raises: ValueError - when the contents do not contain an ASN.1 header or are truncated in some way TypeError - when contents is not a byte string :return: A 6-element tuple: - 0: integer class (0 to 3) - 1: integer method - 2: integer tag - 3: byte string header - 4: byte string content - 5: byte string trailer """ if not isinstance(contents, byte_cls): raise TypeError('contents must be a byte string, not %s' % type_name(contents)) contents_len = len(contents) info, consumed = _parse(contents, contents_len) if strict and consumed != contents_len: raise ValueError('Extra data - %d bytes of trailing data were provided' % (contents_len - consumed)) return info def peek(contents): """ Parses a byte string of ASN.1 BER/DER-encoded data to find the length This is typically used to look into an encoded value to see how long the next chunk of ASN.1-encoded data is. Primarily it is useful when a value is a concatenation of multiple values. :param contents: A byte string of BER/DER-encoded data :raises: ValueError - when the contents do not contain an ASN.1 header or are truncated in some way TypeError - when contents is not a byte string :return: An integer with the number of bytes occupied by the ASN.1 value """ if not isinstance(contents, byte_cls): raise TypeError('contents must be a byte string, not %s' % type_name(contents)) info, consumed = _parse(contents, len(contents)) return consumed def _parse(encoded_data, data_len, pointer=0, lengths_only=False): """ Parses a byte string into component parts :param encoded_data: A byte string that contains BER-encoded data :param data_len: The integer length of the encoded data :param pointer: The index in the byte string to parse from :param lengths_only: A boolean to cause the call to return a 2-element tuple of the integer number of bytes in the header and the integer number of bytes in the contents. Internal use only. :return: A 2-element tuple: - 0: A tuple of (class_, method, tag, header, content, trailer) - 1: An integer indicating how many bytes were consumed """ if data_len < pointer + 2: raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (2, data_len - pointer)) start = pointer first_octet = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer] pointer += 1 tag = first_octet & 31 # Base 128 length using 8th bit as continuation indicator if tag == 31: tag = 0 while True: num = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer] pointer += 1 tag *= 128 tag += num & 127 if num >> 7 == 0: break length_octet = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer] pointer += 1 if length_octet >> 7 == 0: if lengths_only: return (pointer, pointer + (length_octet & 127)) contents_end = pointer + (length_octet & 127) else: length_octets = length_octet & 127 if length_octets: pointer += length_octets contents_end = pointer + int_from_bytes(encoded_data[pointer - length_octets:pointer], signed=False) if lengths_only: return (pointer, contents_end) else: # To properly parse indefinite length values, we need to scan forward # parsing headers until we find a value with a length of zero. If we # just scanned looking for \x00\x00, nested indefinite length values # would not work. contents_end = pointer # Unfortunately we need to understand the contents of the data to # properly scan forward, which bleeds some representation info into # the parser. This condition handles the unused bits byte in # constructed bit strings. if tag == 3: contents_end += 1 while contents_end < data_len: sub_header_end, contents_end = _parse(encoded_data, data_len, contents_end, lengths_only=True) if contents_end == sub_header_end and encoded_data[contents_end - 2:contents_end] == b'\x00\x00': break if lengths_only: return (pointer, contents_end) if contents_end > data_len: raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (contents_end, data_len)) return ( ( first_octet >> 6, (first_octet >> 5) & 1, tag, encoded_data[start:pointer], encoded_data[pointer:contents_end - 2], b'\x00\x00' ), contents_end ) if contents_end > data_len: raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (contents_end, data_len)) return ( ( first_octet >> 6, (first_octet >> 5) & 1, tag, encoded_data[start:pointer], encoded_data[pointer:contents_end], b'' ), contents_end ) def _dump_header(class_, method, tag, contents): """ Constructs the header bytes for an ASN.1 object :param class_: An integer ASN.1 class value: 0 (universal), 1 (application), 2 (context), 3 (private) :param method: An integer ASN.1 method value: 0 (primitive), 1 (constructed) :param tag: An integer ASN.1 tag value :param contents: A byte string of the encoded byte contents :return: A byte string of the ASN.1 DER header """ header = b'' id_num = 0 id_num |= class_ << 6 id_num |= method << 5 if tag >= 31: header += chr_cls(id_num | 31) while tag > 0: continuation_bit = 0x80 if tag > 0x7F else 0 header += chr_cls(continuation_bit | (tag & 0x7F)) tag = tag >> 7 else: header += chr_cls(id_num | tag) length = len(contents) if length <= 127: header += chr_cls(length) else: length_bytes = int_to_bytes(length) header += chr_cls(0x80 | len(length_bytes)) header += length_bytes return header
apache-2.0
vfrc2/Flexget
tests/test_qualities.py
12
7700
from __future__ import unicode_literals, division, absolute_import from nose.plugins.skip import SkipTest from flexget.plugins.parsers.parser_guessit import ParserGuessit from flexget.plugins.parsers.parser_internal import ParserInternal from flexget.utils.qualities import Quality from tests import FlexGetBase, build_parser_function class TestQualityModule(object): def test_get(self): assert not Quality(), 'unknown quality is not false' assert Quality('foobar') == Quality(), 'unknown not returned' def test_common_name(self): for test_val in ('720p', '1280x720'): got_val = Quality(test_val).name assert got_val == '720p', got_val class QualityParser(object): def get_quality_failures(self): items = [('Test.File 1080p.web-dl', '1080p webdl'), ('Test.File.web-dl.1080p', '1080p webdl'), ('Test.File.WebHD.720p', '720p webdl'), ('Test.File.720p.bluray', '720p bluray'), ('Test.File.720hd.bluray', '720p bluray'), ('Test.File.1080p.bluray', '1080p bluray'), ('Test.File.1080p.cam', '1080p cam'), ('A Movie 2011 TS 576P XviD-DTRG', '576p ts xvid'), ('Test.File.720p.bluray.r5', '720p r5'), ('Test.File.1080p.bluray.rc', '1080p r5'), # 10bit ('Test.File.480p.10bit', '480p 10bit'), ('Test.File.720p.10bit', '720p 10bit'), ('Test.File.720p.bluray.10bit', '720p bluray 10bit'), ('Test.File.1080p.10bit', '1080p 10bit'), ('Test.File.1080p.bluray.10bit', '1080p bluray 10bit'), ('Test.File.720p.webdl', '720p webdl'), ('Test.File.1280x720_web dl', '720p webdl'), ('Test.File.720p.h264.web.dl', '720p webdl h264'), ('Test.File.1080p.webhd.x264', '1080p webdl h264'), ('Test.File.480.hdtv.x265', '480p hdtv h265'), ('Test.File.web-dl', 'webdl'), ('Test.File.720P', '720p'), ('Test.File.1920x1080', '1080p'), ('Test.File.1080i', '1080i'), ('Test File blurayrip', 'bluray'), ('Test.File.br-rip', 'bluray'), ('Test.File.720px', '720p'), ('Test.File.720p50', '720p'), ('Test.File.dvd.rip', 'dvdrip'), ('Test.File.dvd.rip.r5', 'r5'), ('Test.File.[576p][00112233].mkv', '576p'), ('Test.TS.FooBar', 'ts'), ('Test.File.360p.avi', '360p'), ('Test.File.[360p].mkv', '360p'), ('Test.File.368.avi', '368p'), ('Test.File.720p.hdtv.avi', '720p hdtv'), ('Test.File.1080p.hdtv.avi', '1080p hdtv'), ('Test.File.720p.preair.avi', '720p preair'), #('Test.File.ts.dvdrip.avi', 'ts'), This should no exists. Having Telesync and DVDRip is a non-sense. ('Test.File.HDTS.blah', 'ts'), #('Test.File.HDCAM.bluray.lie', 'cam'), This should no exists. Having Cam and Bluray is a non-sense. # Test qualities as part of words. #1593 ('Tsar.File.720p', '720p'), ('Camera.1080p', '1080p'), # Some audio formats ('Test.File.DTSHDMA', 'dtshd'), ('Test.File.DTSHD.MA', 'dtshd'), ('Test.File.DTS.HDMA', 'dtshd'), ('Test.File.dts.hd.ma', 'dtshd'), ('Test.File.DTS.HD', 'dtshd'), ('Test.File.DTSHD', 'dtshd'), ('Test.File.DTS', 'dts'), ('Test.File.truehd', 'truehd'), ('Test.File.DTSHDMA', 'dtshd')] failures = [] for item in items: quality = self.parser.parse_movie(item[0]).quality if str(quality) != item[1]: failures.append('`%s` quality should be `%s` not `%s`' % (item[0], item[1], quality)) return failures class TestInternalQualityParser(QualityParser): parser = ParserInternal() def test_qualities(self): failures = self.get_quality_failures() assert not failures, '%s failures:\n%s' % (len(failures), '\n'.join(failures)) class TestGuessitQualityParser(QualityParser): parser = ParserGuessit() def test_qualities(self): failures = self.get_quality_failures() if failures: raise SkipTest('Guessit quality parser does not match FlexGet: %s' % ', '.join(failures)) class TestFilterQuality(FlexGetBase): __yaml__ = """ templates: global: mock: - {title: 'Smoke.1280x720'} - {title: 'Smoke.HDTV'} - {title: 'Smoke.cam'} - {title: 'Smoke.HR'} accept_all: yes tasks: qual: quality: - hdtv - 720p min: quality: HR+ max: quality: "<=cam <HR" min_max: quality: HR-720i """ def test_quality(self): self.execute_task('qual') entry = self.task.find_entry('rejected', title='Smoke.cam') assert entry, 'Smoke.cam should have been rejected' entry = self.task.find_entry(title='Smoke.1280x720') assert entry, 'entry not found?' assert entry in self.task.accepted, '720p should be accepted' assert len(self.task.rejected) == 2, 'wrong number of entries rejected' assert len(self.task.accepted) == 2, 'wrong number of entries accepted' def test_min(self): self.execute_task('min') entry = self.task.find_entry('rejected', title='Smoke.HDTV') assert entry, 'Smoke.HDTV should have been rejected' entry = self.task.find_entry(title='Smoke.1280x720') assert entry, 'entry not found?' assert entry in self.task.accepted, '720p should be accepted' assert len(self.task.rejected) == 2, 'wrong number of entries rejected' assert len(self.task.accepted) == 2, 'wrong number of entries accepted' def test_max(self): self.execute_task('max') entry = self.task.find_entry('rejected', title='Smoke.1280x720') assert entry, 'Smoke.1280x720 should have been rejected' entry = self.task.find_entry(title='Smoke.cam') assert entry, 'entry not found?' assert entry in self.task.accepted, 'cam should be accepted' assert len(self.task.rejected) == 3, 'wrong number of entries rejected' assert len(self.task.accepted) == 1, 'wrong number of entries accepted' def test_min_max(self): self.execute_task('min_max') entry = self.task.find_entry('rejected', title='Smoke.1280x720') assert entry, 'Smoke.1280x720 should have been rejected' entry = self.task.find_entry(title='Smoke.HR') assert entry, 'entry not found?' assert entry in self.task.accepted, 'HR should be accepted' assert len(self.task.rejected) == 3, 'wrong number of entries rejected' assert len(self.task.accepted) == 1, 'wrong number of entries accepted' class TestGuessitFilterQuality(TestFilterQuality): def __init__(self): super(TestGuessitFilterQuality, self).__init__() self.add_tasks_function(build_parser_function('guessit')) class TestInternalFilterQuality(TestFilterQuality): def __init__(self): super(TestInternalFilterQuality, self).__init__() self.add_tasks_function(build_parser_function('internal'))
mit
sniemi/SamPy
sandbox/src1/TCSE3-3rd-examples/src/py/examples/Grid2D.py
1
6587
#!/usr/bin/env python from numpy import * from scitools.numpyutils import seq import time, sys class Grid2D: def __init__(self, xmin=0, xmax=1, dx=0.5, ymin=0, ymax=1, dy=0.5): # coordinates in each space direction: self.xcoor = seq(xmin, xmax, dx) self.ycoor = seq(ymin, ymax, dy) # store for convenience: self.dx = dx; self.dy = dy self.nx = self.xcoor.size; self.ny = self.ycoor.size # make two-dim. versions of the coordinate arrays: # (needed for vectorized function evaluations) self.xcoorv = self.xcoor[:, newaxis] self.ycoorv = self.ycoor[newaxis, :] def vectorized_eval(self, f): """Evaluate a vectorized function f at each grid point.""" return f(self.xcoorv, self.ycoorv) def __call__(self, f): a = f(self.xcoorv, self.ycoorv) return a def __str__(self): s = '\nx: ' + str(self.xcoor) + '\ny: ' + str(self.ycoor) return s def gridloop(self, f): """ Implement strights loops as a simple (and slow) alternative to the vectorized code in __call__. """ a = zeros((self.nx, self.ny)) for i in xrange(self.nx): x = self.xcoor[i] for j in xrange(self.ny): y = self.ycoor[j] a[i,j] = f(x, y) return a def gridloop_hardcoded_func(self): """As gridloop, but hardcode a function formula.""" a = zeros((self.nx, self.ny)) for i in xrange(self.nx): x = self.xcoor[i] for j in xrange(self.ny): y = self.ycoor[j] a[i,j] = sin(x*y) + 8*x return a def gridloop_list(self, f): """As gridloop, but use a list instead of a NumPy array.""" a = [] for i in xrange(self.nx): a.append([]) x = self.xcoor[i] for j in xrange(self.ny): y = self.ycoor[j] a_value = f(x, y) a[i].append(a_value) return a def gridloop_itemset(self, f): """ Implement strights loops, but use numpy's itemset method. """ a = zeros((self.nx, self.ny)) for i in xrange(self.nx): x = self.xcoor.item(i) for j in xrange(self.ny): y = self.ycoor.item(i) a.itemset(i,j, f(x, y)) return a def plot_easyviz(grid, func_values): from scitools.easyviz import mesh mesh(grid.xcoorv, grid.ycoorv, func_values, indexing='ij') # indexing='ij' will become standard def plot_Gnuplot(grid, func_values): import Gnuplot g = Gnuplot.Gnuplot(persist=1) g('set parametric') g('set data style lines') g('set hidden') g('set contour base') g.splot(Gnuplot.GridData(func_values, grid.xcoor, grid.ycoor)) time.sleep(2) # give Gnuplot some time to make the plot """ More examples on plotting two-dimensional scalar fields in Gnuplot can be found in the demo.py script that comes with the Python package containing the Gnuplot module. """ def timing1(n=2000): # timing: dx = 1.0/n g = Grid2D(xmin=0, xmax=1, dx=dx, ymin=0, ymax=1, dy=dx) def myfunc(x, y): return sin(x*y) + 8*x from scitools.StringFunction import StringFunction expression = StringFunction('sin(x*y) + 8*x', independent_variables=('x','y'), globals=globals() # needed for vectorization ) from scitools.misc import timer from scitools.EfficiencyTable import EfficiencyTable e = EfficiencyTable('Grid2D efficiency tests, %dx%d grid' % (n,n)) t0 = time.clock() # vectorized expressions are so fast that we run the code # repeatedly rep=20 t1 = timer(g.__call__, (expression,), repetitions=rep, comment='StringFunction') e.add('g.__call__, expression (vectorized)', t1) t2 = timer(g.__call__, (myfunc,), repetitions=rep, comment='myfunc') e.add('g.__call__, myfunc (vectorized)', t2) f = g.gridloop_hardcoded_func() t3 = timer(g.gridloop_hardcoded_func, (), repetitions=1, comment='') e.add('g.gridloop_hardcoded_func', t3) t4 = timer(g.gridloop, (expression,), repetitions=1, comment='StringFunction') e.add('g.gridloop, expression (explicit loops)', t4) t5 = timer(g.gridloop, (myfunc,), repetitions=1, comment='myfunc') e.add('g.gridloop, myfunc (explicit loops)', t4) t6 = timer(g.gridloop_list, (expression,), repetitions=1, comment='StringFunction') e.add('g.gridloop_list, expression (explicit loops)', t6) t7 = timer(g.gridloop_list, (myfunc,), repetitions=1, comment='myfunc') e.add('g.gridloop_list, myfunc (explicit loops)', t7) from math import sin as mathsin # efficiency trick # The scalar computations above used sin from NumPy, which is # known to be slow for scalar arguments. Here we use math.sin # (stored in mathsin, could also use the slightly slower math.sin # explicitly) # taken globally so eval works: from math import sin as mathsin def myfunc_scalar(x, y): return mathsin(x*y) + 8*x expression_scalar = StringFunction('mathsin(x*y) + 8*x', independent_variables=('x','y'), globals=globals()) t8 = timer(g.gridloop, (expression_scalar,), repetitions=1, comment='eval(str)') e.add('g.gridloop, expression_scalar', t8) t9 = timer(g.gridloop, (myfunc_scalar,), repetitions=1, comment='myfunc') e.add('g.gridloop, myfunc_scalar', t9) print e def verify1(): g = Grid2D() from scitools.StringFunction import StringFunction expression = StringFunction('x + a*y', independent_variables=('x','y'), globals=globals(), a=2) f = g(expression) print g, f f = g.gridloop(expression) print g, f g = Grid2D(dx=0.05, dy=0.025) f = g.vectorized_eval(expression) plot_easyviz(g, f) #plot_Gnuplot(g, f) def _run(): try: func = sys.argv[1] except: func = 'verify1' if func == 'timing1': try: n = int(sys.argv[2]) except: n = 2000 exec 'timing1(%d)' % n else: exec func + '()' if __name__ == '__main__': _run()
bsd-2-clause
hoogenm/compose
tests/unit/timeparse_test.py
11
1127
from __future__ import absolute_import from __future__ import unicode_literals from compose import timeparse def test_milli(): assert timeparse.timeparse('5ms') == 0.005 def test_milli_float(): assert timeparse.timeparse('50.5ms') == 0.0505 def test_second_milli(): assert timeparse.timeparse('200s5ms') == 200.005 def test_second_milli_micro(): assert timeparse.timeparse('200s5ms10us') == 200.00501 def test_second(): assert timeparse.timeparse('200s') == 200 def test_second_as_float(): assert timeparse.timeparse('20.5s') == 20.5 def test_minute(): assert timeparse.timeparse('32m') == 1920 def test_hour_minute(): assert timeparse.timeparse('2h32m') == 9120 def test_minute_as_float(): assert timeparse.timeparse('1.5m') == 90 def test_hour_minute_second(): assert timeparse.timeparse('5h34m56s') == 20096 def test_invalid_with_space(): assert timeparse.timeparse('5h 34m 56s') is None def test_invalid_with_comma(): assert timeparse.timeparse('5h,34m,56s') is None def test_invalid_with_empty_string(): assert timeparse.timeparse('') is None
apache-2.0
mancoast/CPythonPyc_test
cpython/341_script_helper.py
7
6886
# Common utility functions used by various script execution tests # e.g. test_cmd_line, test_cmd_line_script and test_runpy import importlib import sys import os import os.path import tempfile import subprocess import py_compile import contextlib import shutil import zipfile from importlib.util import source_from_cache from test.support import make_legacy_pyc, strip_python_stderr, temp_dir # Executing the interpreter in a subprocess def _assert_python(expected_success, *args, **env_vars): if '__isolated' in env_vars: isolated = env_vars.pop('__isolated') else: isolated = not env_vars cmd_line = [sys.executable, '-X', 'faulthandler'] if isolated: # isolated mode: ignore Python environment variables, ignore user # site-packages, and don't add the current directory to sys.path cmd_line.append('-I') elif not env_vars: # ignore Python environment variables cmd_line.append('-E') # Need to preserve the original environment, for in-place testing of # shared library builds. env = os.environ.copy() # But a special flag that can be set to override -- in this case, the # caller is responsible to pass the full environment. if env_vars.pop('__cleanenv', None): env = {} env.update(env_vars) cmd_line.extend(args) p = subprocess.Popen(cmd_line, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) try: out, err = p.communicate() finally: subprocess._cleanup() p.stdout.close() p.stderr.close() rc = p.returncode err = strip_python_stderr(err) if (rc and expected_success) or (not rc and not expected_success): raise AssertionError( "Process return code is %d, " "stderr follows:\n%s" % (rc, err.decode('ascii', 'ignore'))) return rc, out, err def assert_python_ok(*args, **env_vars): """ Assert that running the interpreter with `args` and optional environment variables `env_vars` succeeds (rc == 0) and return a (return code, stdout, stderr) tuple. If the __cleanenv keyword is set, env_vars is used a fresh environment. Python is started in isolated mode (command line option -I), except if the __isolated keyword is set to False. """ return _assert_python(True, *args, **env_vars) def assert_python_failure(*args, **env_vars): """ Assert that running the interpreter with `args` and optional environment variables `env_vars` fails (rc != 0) and return a (return code, stdout, stderr) tuple. See assert_python_ok() for more options. """ return _assert_python(False, *args, **env_vars) def spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw): """Run a Python subprocess with the given arguments. kw is extra keyword args to pass to subprocess.Popen. Returns a Popen object. """ cmd_line = [sys.executable, '-E'] cmd_line.extend(args) # Under Fedora (?), GNU readline can output junk on stderr when initialized, # depending on the TERM setting. Setting TERM=vt100 is supposed to disable # that. References: # - http://reinout.vanrees.org/weblog/2009/08/14/readline-invisible-character-hack.html # - http://stackoverflow.com/questions/15760712/python-readline-module-prints-escape-character-during-import # - http://lists.gnu.org/archive/html/bug-readline/2007-08/msg00004.html env = kw.setdefault('env', dict(os.environ)) env['TERM'] = 'vt100' return subprocess.Popen(cmd_line, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, **kw) def kill_python(p): """Run the given Popen process until completion and return stdout.""" p.stdin.close() data = p.stdout.read() p.stdout.close() # try to cleanup the child so we don't appear to leak when running # with regrtest -R. p.wait() subprocess._cleanup() return data def make_script(script_dir, script_basename, source, omit_suffix=False): script_filename = script_basename if not omit_suffix: script_filename += os.extsep + 'py' script_name = os.path.join(script_dir, script_filename) # The script should be encoded to UTF-8, the default string encoding script_file = open(script_name, 'w', encoding='utf-8') script_file.write(source) script_file.close() importlib.invalidate_caches() return script_name def make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None): zip_filename = zip_basename+os.extsep+'zip' zip_name = os.path.join(zip_dir, zip_filename) zip_file = zipfile.ZipFile(zip_name, 'w') if name_in_zip is None: parts = script_name.split(os.sep) if len(parts) >= 2 and parts[-2] == '__pycache__': legacy_pyc = make_legacy_pyc(source_from_cache(script_name)) name_in_zip = os.path.basename(legacy_pyc) script_name = legacy_pyc else: name_in_zip = os.path.basename(script_name) zip_file.write(script_name, name_in_zip) zip_file.close() #if test.support.verbose: # zip_file = zipfile.ZipFile(zip_name, 'r') # print 'Contents of %r:' % zip_name # zip_file.printdir() # zip_file.close() return zip_name, os.path.join(zip_name, name_in_zip) def make_pkg(pkg_dir, init_source=''): os.mkdir(pkg_dir) make_script(pkg_dir, '__init__', init_source) def make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, source, depth=1, compiled=False): unlink = [] init_name = make_script(zip_dir, '__init__', '') unlink.append(init_name) init_basename = os.path.basename(init_name) script_name = make_script(zip_dir, script_basename, source) unlink.append(script_name) if compiled: init_name = py_compile(init_name, doraise=True) script_name = py_compile(script_name, doraise=True) unlink.extend((init_name, script_name)) pkg_names = [os.sep.join([pkg_name]*i) for i in range(1, depth+1)] script_name_in_zip = os.path.join(pkg_names[-1], os.path.basename(script_name)) zip_filename = zip_basename+os.extsep+'zip' zip_name = os.path.join(zip_dir, zip_filename) zip_file = zipfile.ZipFile(zip_name, 'w') for name in pkg_names: init_name_in_zip = os.path.join(name, init_basename) zip_file.write(init_name, init_name_in_zip) zip_file.write(script_name, script_name_in_zip) zip_file.close() for name in unlink: os.unlink(name) #if test.support.verbose: # zip_file = zipfile.ZipFile(zip_name, 'r') # print 'Contents of %r:' % zip_name # zip_file.printdir() # zip_file.close() return zip_name, os.path.join(zip_name, script_name_in_zip)
gpl-3.0
adlius/osf.io
addons/bitbucket/migrations/0002_auto_20170808_1140.py
22
1427
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-08-08 16:40 from __future__ import unicode_literals import datetime import pytz from django.db import migrations import django_extensions.db.fields class Migration(migrations.Migration): dependencies = [ ('addons_bitbucket', '0001_initial'), ] operations = [ migrations.AddField( model_name='nodesettings', name='created', field=django_extensions.db.fields.CreationDateTimeField(auto_now_add=True, default=datetime.datetime(1970, 1, 1, 0, 0, tzinfo=pytz.utc), verbose_name='created'), preserve_default=False, ), migrations.AddField( model_name='nodesettings', name='modified', field=django_extensions.db.fields.ModificationDateTimeField(auto_now=True, verbose_name='modified'), ), migrations.AddField( model_name='usersettings', name='created', field=django_extensions.db.fields.CreationDateTimeField(auto_now_add=True, default=datetime.datetime(1970, 1, 1, 0, 0, tzinfo=pytz.utc), verbose_name='created'), preserve_default=False, ), migrations.AddField( model_name='usersettings', name='modified', field=django_extensions.db.fields.ModificationDateTimeField(auto_now=True, verbose_name='modified'), ), ]
apache-2.0
promptworks/horizon
openstack_dashboard/dashboards/admin/hypervisors/tables.py
32
3125
# Copyright 2013 B1 Systems GmbH # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from horizon import tables from horizon.templatetags import sizeformat class AdminHypervisorsTable(tables.DataTable): hostname = tables.Column("hypervisor_hostname", link="horizon:admin:hypervisors:detail", attrs={'data-type': 'naturalSort'}, verbose_name=_("Hostname")) hypervisor_type = tables.Column("hypervisor_type", verbose_name=_("Type")) vcpus_used = tables.Column("vcpus_used", verbose_name=_("VCPUs (used)")) vcpus = tables.Column("vcpus", verbose_name=_("VCPUs (total)")) memory_used = tables.Column('memory_mb_used', verbose_name=_("RAM (used)"), attrs={'data-type': 'size'}, filters=(sizeformat.mb_float_format,)) memory = tables.Column('memory_mb', verbose_name=_("RAM (total)"), attrs={'data-type': 'size'}, filters=(sizeformat.mb_float_format,)) local_used = tables.Column('local_gb_used', verbose_name=_("Local Storage (used)"), attrs={'data-type': 'size'}, filters=(sizeformat.diskgbformat,)) local = tables.Column('local_gb', verbose_name=_("Local Storage (total)"), attrs={'data-type': 'size'}, filters=(sizeformat.diskgbformat,)) running_vms = tables.Column("running_vms", verbose_name=_("Instances")) def get_object_id(self, hypervisor): return "%s_%s" % (hypervisor.id, hypervisor.hypervisor_hostname) class Meta(object): name = "hypervisors" verbose_name = _("Hypervisors") class AdminHypervisorInstancesTable(tables.DataTable): name = tables.Column("name", link="horizon:admin:instances:detail", verbose_name=_("Instance Name")) instance_id = tables.Column("uuid", verbose_name=_("Instance ID")) def get_object_id(self, server): return server['uuid'] class Meta(object): name = "hypervisor_instances" verbose_name = _("Hypervisor Instances")
apache-2.0
WikipediaLibrary/TWLight
TWLight/users/admin.py
1
4103
# -*- coding: utf-8 -*- from django.contrib import admin from django.contrib.auth.admin import UserAdmin as AuthUserAdmin from django.contrib.auth.models import User from django.contrib.sessions.models import Session from TWLight.users.models import ( Editor, EditorLog, UserProfile, Authorization, get_company_name, ) from TWLight.users.forms import AuthorizationAdminForm, AuthorizationInlineForm class EditorInline(admin.StackedInline): model = Editor max_num = 1 extra = 1 can_delete = False raw_id_fields = ("user",) readonly_fields = ( "wp_editcount", "wp_editcount_updated", ) class EditorLogInline(admin.StackedInline): model = EditorLog can_delete = False raw_id_fields = ("editor",) class UserProfileInline(admin.StackedInline): model = UserProfile max_num = 1 extra = 1 can_delete = False raw_id_fields = ("user",) fieldsets = ( ( None, {"fields": ("terms_of_use", "terms_of_use_date", "use_wp_email", "lang")}, ), ( "Email preferences", { "fields": ( "send_renewal_notices", "pending_app_reminders", "discussion_app_reminders", "approved_app_reminders", ) }, ), ) class AuthorizationAdmin(admin.ModelAdmin): list_display = ( "id", "get_partners_company_name", "stream", "get_authorizer_wp_username", "get_authorized_user_wp_username", ) search_fields = [ "partners__company_name", "stream__name", "authorizer__editor__wp_username", "user__editor__wp_username", ] form = AuthorizationAdminForm def get_authorized_user_wp_username(self, authorization): if authorization.user: user = authorization.user if hasattr(user, "editor"): return user.editor.wp_username else: return "" get_authorized_user_wp_username.short_description = "user" def get_authorizer_wp_username(self, authorization): if authorization.authorizer: user = authorization.authorizer if hasattr(user, "editor"): return user.editor.wp_username elif hasattr(user, "username"): return user.username else: return "" get_authorizer_wp_username.short_description = "authorizer" def get_partners_company_name(self, authorization): return get_company_name(authorization) get_partners_company_name.short_description = "partners" admin.site.register(Authorization, AuthorizationAdmin) class AuthorizationInline(admin.StackedInline): form = AuthorizationAdminForm model = Authorization fk_name = "user" extra = 0 class UserAdmin(AuthUserAdmin): inlines = [EditorInline, UserProfileInline, AuthorizationInline] list_display = ["username", "get_wp_username", "is_staff"] list_filter = ["is_staff", "is_active", "is_superuser"] default_filters = ["is_active__exact=1"] search_fields = ["editor__wp_username", "username"] def get_wp_username(self, user): if hasattr(user, "editor"): return user.editor.wp_username else: return "" get_wp_username.short_description = "Username" class EditorLogAdmin(admin.ModelAdmin): model = EditorLog list_display = ( "editor", "timestamp", "editcount", ) search_fields = [ "editor__wp_username", ] admin.site.register(EditorLog, EditorLogAdmin) # Unregister old user admin; register new, improved user admin. admin.site.unregister(User) admin.site.register(User, UserAdmin) # Cribbed from: https://stackoverflow.com/a/4978234 class SessionAdmin(admin.ModelAdmin): def _session_data(self, obj): return obj.get_decoded() list_display = ["session_key", "_session_data", "expire_date"] admin.site.register(Session, SessionAdmin)
mit
CiscoSystems/horizon
openstack_dashboard/dashboards/project/routers/tabs.py
6
1952
# Copyright 2012, Nachi Ueno, NTT MCL, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import tabs from openstack_dashboard import api from openstack_dashboard.dashboards.project.routers.extensions.routerrules\ import tabs as rr_tabs from openstack_dashboard.dashboards.project.routers.ports import tables as ptbl class InterfacesTab(tabs.TableTab): table_classes = (ptbl.PortsTable,) name = _("Interfaces") slug = "interfaces" template_name = "horizon/common/_detail_table.html" def get_interfaces_data(self): ports = self.tab_group.ports return ports class RouterDetailTabs(tabs.TabGroup): slug = "router_details" tabs = (InterfacesTab, rr_tabs.RulesGridTab, rr_tabs.RouterRulesTab) sticky = True def __init__(self, request, **kwargs): rid = kwargs['router_id'] self.router = {} if 'router' in kwargs: self.router = kwargs['router'] else: self.router = api.neutron.router_get(request, rid) try: self.ports = api.neutron.port_list(request, device_id=rid) except Exception: self.ports = [] msg = _('Unable to retrieve router details.') exceptions.handle(request, msg) super(RouterDetailTabs, self).__init__(request, **kwargs)
apache-2.0
saisai/phantomjs
src/breakpad/src/tools/gyp/gyptest.py
137
7245
#!/usr/bin/env python # Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. __doc__ = """ gyptest.py -- test runner for GYP tests. """ import os import optparse import subprocess import sys class CommandRunner: """ Executor class for commands, including "commands" implemented by Python functions. """ verbose = True active = True def __init__(self, dictionary={}): self.subst_dictionary(dictionary) def subst_dictionary(self, dictionary): self._subst_dictionary = dictionary def subst(self, string, dictionary=None): """ Substitutes (via the format operator) the values in the specified dictionary into the specified command. The command can be an (action, string) tuple. In all cases, we perform substitution on strings and don't worry if something isn't a string. (It's probably a Python function to be executed.) """ if dictionary is None: dictionary = self._subst_dictionary if dictionary: try: string = string % dictionary except TypeError: pass return string def display(self, command, stdout=None, stderr=None): if not self.verbose: return if type(command) == type(()): func = command[0] args = command[1:] s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args))) if type(command) == type([]): # TODO: quote arguments containing spaces # TODO: handle meta characters? s = ' '.join(command) else: s = self.subst(command) if not s.endswith('\n'): s += '\n' sys.stdout.write(s) sys.stdout.flush() def execute(self, command, stdout=None, stderr=None): """ Executes a single command. """ if not self.active: return 0 if type(command) == type(''): command = self.subst(command) cmdargs = shlex.split(command) if cmdargs[0] == 'cd': command = (os.chdir,) + tuple(cmdargs[1:]) if type(command) == type(()): func = command[0] args = command[1:] return func(*args) else: if stdout is sys.stdout: # Same as passing sys.stdout, except python2.4 doesn't fail on it. subout = None else: # Open pipe for anything else so Popen works on python2.4. subout = subprocess.PIPE if stderr is sys.stderr: # Same as passing sys.stderr, except python2.4 doesn't fail on it. suberr = None elif stderr is None: # Merge with stdout if stderr isn't specified. suberr = subprocess.STDOUT else: # Open pipe for anything else so Popen works on python2.4. suberr = subprocess.PIPE p = subprocess.Popen(command, shell=(sys.platform == 'win32'), stdout=subout, stderr=suberr) p.wait() if stdout is None: self.stdout = p.stdout.read() elif stdout is not sys.stdout: stdout.write(p.stdout.read()) if stderr not in (None, sys.stderr): stderr.write(p.stderr.read()) return p.returncode def run(self, command, display=None, stdout=None, stderr=None): """ Runs a single command, displaying it first. """ if display is None: display = command self.display(display) return self.execute(command, stdout, stderr) class Unbuffered: def __init__(self, fp): self.fp = fp def write(self, arg): self.fp.write(arg) self.fp.flush() def __getattr__(self, attr): return getattr(self.fp, attr) sys.stdout = Unbuffered(sys.stdout) sys.stderr = Unbuffered(sys.stderr) def find_all_gyptest_files(directory): result = [] for root, dirs, files in os.walk(directory): if '.svn' in dirs: dirs.remove('.svn') result.extend([ os.path.join(root, f) for f in files if f.startswith('gyptest') and f.endswith('.py') ]) result.sort() return result def main(argv=None): if argv is None: argv = sys.argv usage = "gyptest.py [-ahlnq] [-f formats] [test ...]" parser = optparse.OptionParser(usage=usage) parser.add_option("-a", "--all", action="store_true", help="run all tests") parser.add_option("-C", "--chdir", action="store", default=None, help="chdir to the specified directory") parser.add_option("-f", "--format", action="store", default='', help="run tests with the specified formats") parser.add_option("-l", "--list", action="store_true", help="list available tests and exit") parser.add_option("-n", "--no-exec", action="store_true", help="no execute, just print the command line") parser.add_option("--passed", action="store_true", help="report passed tests") parser.add_option("--path", action="append", default=[], help="additional $PATH directory") parser.add_option("-q", "--quiet", action="store_true", help="quiet, don't print test command lines") opts, args = parser.parse_args(argv[1:]) if opts.chdir: os.chdir(opts.chdir) if opts.path: os.environ['PATH'] += ':' + ':'.join(opts.path) if not args: if not opts.all: sys.stderr.write('Specify -a to get all tests.\n') return 1 args = ['test'] tests = [] for arg in args: if os.path.isdir(arg): tests.extend(find_all_gyptest_files(os.path.normpath(arg))) else: tests.append(arg) if opts.list: for test in tests: print test sys.exit(0) CommandRunner.verbose = not opts.quiet CommandRunner.active = not opts.no_exec cr = CommandRunner() os.environ['PYTHONPATH'] = os.path.abspath('test/lib') if not opts.quiet: sys.stdout.write('PYTHONPATH=%s\n' % os.environ['PYTHONPATH']) passed = [] failed = [] no_result = [] if opts.format: format_list = opts.format.split(',') else: # TODO: not duplicate this mapping from pylib/gyp/__init__.py format_list = [ { 'freebsd7': 'make', 'freebsd8': 'make', 'cygwin': 'msvs', 'win32': 'msvs', 'linux2': 'scons', 'darwin': 'xcode', }[sys.platform] ] for format in format_list: os.environ['TESTGYP_FORMAT'] = format if not opts.quiet: sys.stdout.write('TESTGYP_FORMAT=%s\n' % format) for test in tests: status = cr.run([sys.executable, test], stdout=sys.stdout, stderr=sys.stderr) if status == 2: no_result.append(test) elif status: failed.append(test) else: passed.append(test) if not opts.quiet: def report(description, tests): if tests: if len(tests) == 1: sys.stdout.write("\n%s the following test:\n" % description) else: fmt = "\n%s the following %d tests:\n" sys.stdout.write(fmt % (description, len(tests))) sys.stdout.write("\t" + "\n\t".join(tests) + "\n") if opts.passed: report("Passed", passed) report("Failed", failed) report("No result from", no_result) if failed: return 1 else: return 0 if __name__ == "__main__": sys.exit(main())
bsd-3-clause
Comunitea/OCB
addons/anonymization/anonymization.py
15
28790
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from lxml import etree import os import base64 try: import cPickle as pickle except ImportError: import pickle import random import datetime from openerp.osv import fields, osv from openerp.tools.translate import _ from openerp.tools.safe_eval import safe_eval as eval from itertools import groupby from operator import itemgetter FIELD_STATES = [('clear', 'Clear'), ('anonymized', 'Anonymized'), ('not_existing', 'Not Existing'), ('new', 'New')] ANONYMIZATION_STATES = FIELD_STATES + [('unstable', 'Unstable')] WIZARD_ANONYMIZATION_STATES = [('clear', 'Clear'), ('anonymized', 'Anonymized'), ('unstable', 'Unstable')] ANONYMIZATION_HISTORY_STATE = [('started', 'Started'), ('done', 'Done'), ('in_exception', 'Exception occured')] ANONYMIZATION_DIRECTION = [('clear -> anonymized', 'clear -> anonymized'), ('anonymized -> clear', 'anonymized -> clear')] def group(lst, cols): if isinstance(cols, basestring): cols = [cols] return dict((k, [v for v in itr]) for k, itr in groupby(sorted(lst, key=itemgetter(*cols)), itemgetter(*cols))) class ir_model_fields_anonymization(osv.osv): _name = 'ir.model.fields.anonymization' _rec_name = 'field_id' _columns = { 'model_name': fields.char('Object Name', required=True), 'model_id': fields.many2one('ir.model', 'Object', ondelete='set null'), 'field_name': fields.char('Field Name', required=True), 'field_id': fields.many2one('ir.model.fields', 'Field', ondelete='set null'), 'state': fields.selection(selection=FIELD_STATES, String='Status', required=True, readonly=True), } _sql_constraints = [ ('model_id_field_id_uniq', 'unique (model_name, field_name)', _("You cannot have two fields with the same name on the same object!")), ] def _get_global_state(self, cr, uid, context=None): ids = self.search(cr, uid, [('state', '<>', 'not_existing')], context=context) fields = self.browse(cr, uid, ids, context=context) if not len(fields) or len(fields) == len([f for f in fields if f.state == 'clear']): state = 'clear' # all fields are clear elif len(fields) == len([f for f in fields if f.state == 'anonymized']): state = 'anonymized' # all fields are anonymized else: state = 'unstable' # fields are mixed: this should be fixed return state def _check_write(self, cr, uid, context=None): """check that the field is created from the menu and not from an database update otherwise the database update can crash:""" if context is None: context = {} if context.get('manual'): global_state = self._get_global_state(cr, uid, context=context) if global_state == 'anonymized': raise osv.except_osv('Error!', "The database is currently anonymized, you cannot create, modify or delete fields.") elif global_state == 'unstable': msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \ " while some fields are not anonymized. You should try to solve this problem before trying to create, write or delete fields.") raise osv.except_osv('Error!', msg) return True def _get_model_and_field_ids(self, cr, uid, vals, context=None): model_and_field_ids = (False, False) if 'field_name' in vals and vals['field_name'] and 'model_name' in vals and vals['model_name']: ir_model_fields_obj = self.pool.get('ir.model.fields') ir_model_obj = self.pool.get('ir.model') model_ids = ir_model_obj.search(cr, uid, [('model', '=', vals['model_name'])], context=context) if model_ids: field_ids = ir_model_fields_obj.search(cr, uid, [('name', '=', vals['field_name']), ('model_id', '=', model_ids[0])], context=context) if field_ids: field_id = field_ids[0] model_and_field_ids = (model_ids[0], field_id) return model_and_field_ids def create(self, cr, uid, vals, context=None): # check field state: all should be clear before we can add a new field to anonymize: self._check_write(cr, uid, context=context) global_state = self._get_global_state(cr, uid, context=context) if 'field_name' in vals and vals['field_name'] and 'model_name' in vals and vals['model_name']: vals['model_id'], vals['field_id'] = self._get_model_and_field_ids(cr, uid, vals, context=context) # check not existing fields: if not vals.get('field_id'): vals['state'] = 'not_existing' else: vals['state'] = global_state res = super(ir_model_fields_anonymization, self).create(cr, uid, vals, context=context) return res def write(self, cr, uid, ids, vals, context=None): # check field state: all should be clear before we can modify a field: if not (len(vals.keys()) == 1 and vals.get('state') == 'clear'): self._check_write(cr, uid, context=context) if 'field_name' in vals and vals['field_name'] and 'model_name' in vals and vals['model_name']: vals['model_id'], vals['field_id'] = self._get_model_and_field_ids(cr, uid, vals, context=context) # check not existing fields: if 'field_id' in vals: if not vals.get('field_id'): vals['state'] = 'not_existing' else: global_state = self._get_global_state(cr, uid, context) if global_state != 'unstable': vals['state'] = global_state res = super(ir_model_fields_anonymization, self).write(cr, uid, ids, vals, context=context) return res def unlink(self, cr, uid, ids, context=None): # check field state: all should be clear before we can unlink a field: self._check_write(cr, uid, context=context) res = super(ir_model_fields_anonymization, self).unlink(cr, uid, ids, context=context) return res def onchange_model_id(self, cr, uid, ids, model_id, context=None): res = {'value': { 'field_name': False, 'field_id': False, 'model_name': False, }} if model_id: ir_model_obj = self.pool.get('ir.model') model_ids = ir_model_obj.search(cr, uid, [('id', '=', model_id)]) model_id = model_ids and model_ids[0] or None model_name = model_id and ir_model_obj.browse(cr, uid, model_id).model or False res['value']['model_name'] = model_name return res def onchange_model_name(self, cr, uid, ids, model_name, context=None): res = {'value': { 'field_name': False, 'field_id': False, 'model_id': False, }} if model_name: ir_model_obj = self.pool.get('ir.model') model_ids = ir_model_obj.search(cr, uid, [('model', '=', model_name)]) model_id = model_ids and model_ids[0] or False res['value']['model_id'] = model_id return res def onchange_field_name(self, cr, uid, ids, field_name, model_name): res = {'value': { 'field_id': False, }} if field_name and model_name: ir_model_fields_obj = self.pool.get('ir.model.fields') field_ids = ir_model_fields_obj.search(cr, uid, [('name', '=', field_name), ('model', '=', model_name)]) field_id = field_ids and field_ids[0] or False res['value']['field_id'] = field_id return res def onchange_field_id(self, cr, uid, ids, field_id, model_name): res = {'value': { 'field_name': False, }} if field_id: ir_model_fields_obj = self.pool.get('ir.model.fields') field = ir_model_fields_obj.browse(cr, uid, field_id) res['value']['field_name'] = field.name return res _defaults = { 'state': lambda *a: 'clear', } class ir_model_fields_anonymization_history(osv.osv): _name = 'ir.model.fields.anonymization.history' _order = "date desc" _columns = { 'date': fields.datetime('Date', required=True, readonly=True), 'field_ids': fields.many2many('ir.model.fields.anonymization', 'anonymized_field_to_history_rel', 'field_id', 'history_id', 'Fields', readonly=True), 'state': fields.selection(selection=ANONYMIZATION_HISTORY_STATE, string='Status', required=True, readonly=True), 'direction': fields.selection(selection=ANONYMIZATION_DIRECTION, string='Direction', size=20, required=True, readonly=True), 'msg': fields.text('Message', readonly=True), 'filepath': fields.char(string='File path', readonly=True), } class ir_model_fields_anonymize_wizard(osv.osv_memory): _name = 'ir.model.fields.anonymize.wizard' def _get_state(self, cr, uid, ids, name, arg, context=None): res = {} state = self._get_state_value(cr, uid, context=None) for id in ids: res[id] = state return res def _get_summary(self, cr, uid, ids, name, arg, context=None): res = {} summary = self._get_summary_value(cr, uid, context) for id in ids: res[id] = summary return res _columns = { 'name': fields.char(string='File Name'), 'summary': fields.function(_get_summary, type='text', string='Summary'), 'file_export': fields.binary(string='Export'), 'file_import': fields.binary(string='Import', help="This is the file created by the anonymization process. It should have the '.pickle' extention."), 'state': fields.function(_get_state, string='Status', type='selection', selection=WIZARD_ANONYMIZATION_STATES, readonly=False), 'msg': fields.text(string='Message'), } def _get_state_value(self, cr, uid, context=None): state = self.pool.get('ir.model.fields.anonymization')._get_global_state(cr, uid, context=context) return state def _get_summary_value(self, cr, uid, context=None): summary = u'' anon_field_obj = self.pool.get('ir.model.fields.anonymization') ir_model_fields_obj = self.pool.get('ir.model.fields') anon_field_ids = anon_field_obj.search(cr, uid, [('state', '<>', 'not_existing')], context=context) anon_fields = anon_field_obj.browse(cr, uid, anon_field_ids, context=context) field_ids = [anon_field.field_id.id for anon_field in anon_fields if anon_field.field_id] fields = ir_model_fields_obj.browse(cr, uid, field_ids, context=context) fields_by_id = dict([(f.id, f) for f in fields]) for anon_field in anon_fields: field = fields_by_id.get(anon_field.field_id.id) values = { 'model_name': field.model_id.name, 'model_code': field.model_id.model, 'field_code': field.name, 'field_name': field.field_description, 'state': anon_field.state, } summary += u" * %(model_name)s (%(model_code)s) -> %(field_name)s (%(field_code)s): state: (%(state)s)\n" % values return summary def default_get(self, cr, uid, fields_list, context=None): res = {} res['name'] = '.pickle' res['summary'] = self._get_summary_value(cr, uid, context) res['state'] = self._get_state_value(cr, uid, context) res['msg'] = _("""Before executing the anonymization process, you should make a backup of your database.""") return res def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, *args, **kwargs): state = self.pool.get('ir.model.fields.anonymization')._get_global_state(cr, uid, context=context) if context is None: context = {} step = context.get('step', 'new_window') res = super(ir_model_fields_anonymize_wizard, self).fields_view_get(cr, uid, view_id, view_type, context=context, *args, **kwargs) eview = etree.fromstring(res['arch']) placeholder = eview.xpath("group[@name='placeholder1']") if len(placeholder): placeholder = placeholder[0] if step == 'new_window' and state == 'clear': # clicked in the menu and the fields are not anonymized: warn the admin that backuping the db is very important placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'})) placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('label', {'string': 'Warning'})) eview.remove(placeholder) elif step == 'new_window' and state == 'anonymized': # clicked in the menu and the fields are already anonymized placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('field', {'name': 'file_import', 'required': "1"})) placeholder.addnext(etree.Element('label', {'string': 'Anonymization file'})) eview.remove(placeholder) elif step == 'just_anonymized': # we just ran the anonymization process, we need the file export field placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('field', {'name': 'file_export'})) # we need to remove the button: buttons = eview.xpath("button") for button in buttons: eview.remove(button) # and add a message: placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'})) placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('label', {'string': 'Result'})) # remove the placeholer: eview.remove(placeholder) elif step == 'just_desanonymized': # we just reversed the anonymization process, we don't need any field # we need to remove the button buttons = eview.xpath("button") for button in buttons: eview.remove(button) # and add a message # and add a message: placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'})) placeholder.addnext(etree.Element('newline')) placeholder.addnext(etree.Element('label', {'string': 'Result'})) # remove the placeholer: eview.remove(placeholder) else: msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \ " while some fields are not anonymized. You should try to solve this problem before trying to do anything else.") raise osv.except_osv('Error!', msg) res['arch'] = etree.tostring(eview) return res def _raise_after_history_update(self, cr, uid, history_id, error_type, error_msg): self.pool.get('ir.model.fields.anonymization.history').write(cr, uid, history_id, { 'state': 'in_exception', 'msg': error_msg, }) raise osv.except_osv(error_type, error_msg) def anonymize_database(self, cr, uid, ids, context=None): """Sets the 'anonymized' state to defined fields""" # create a new history record: anonymization_history_model = self.pool.get('ir.model.fields.anonymization.history') vals = { 'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'state': 'started', 'direction': 'clear -> anonymized', } history_id = anonymization_history_model.create(cr, uid, vals) # check that all the defined fields are in the 'clear' state state = self.pool.get('ir.model.fields.anonymization')._get_global_state(cr, uid, context=context) if state == 'anonymized': self._raise_after_history_update(cr, uid, history_id, _('Error !'), _("The database is currently anonymized, you cannot anonymize it again.")) elif state == 'unstable': msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \ " while some fields are not anonymized. You should try to solve this problem before trying to do anything.") self._raise_after_history_update(cr, uid, history_id, 'Error !', msg) # do the anonymization: dirpath = os.environ.get('HOME') or os.getcwd() rel_filepath = 'field_anonymization_%s_%s.pickle' % (cr.dbname, history_id) abs_filepath = os.path.abspath(os.path.join(dirpath, rel_filepath)) ir_model_fields_anonymization_model = self.pool.get('ir.model.fields.anonymization') field_ids = ir_model_fields_anonymization_model.search(cr, uid, [('state', '<>', 'not_existing')], context=context) fields = ir_model_fields_anonymization_model.browse(cr, uid, field_ids, context=context) if not fields: msg = "No fields are going to be anonymized." self._raise_after_history_update(cr, uid, history_id, 'Error !', msg) data = [] for field in fields: model_name = field.model_id.model field_name = field.field_id.name field_type = field.field_id.ttype table_name = self.pool[model_name]._table # get the current value sql = "select id, %s from %s" % (field_name, table_name) cr.execute(sql) records = cr.dictfetchall() for record in records: data.append({"model_id": model_name, "field_id": field_name, "id": record['id'], "value": record[field_name]}) # anonymize the value: anonymized_value = None sid = str(record['id']) if field_type == 'char': anonymized_value = 'xxx'+sid elif field_type == 'selection': anonymized_value = 'xxx'+sid elif field_type == 'text': anonymized_value = 'xxx'+sid elif field_type == 'html': anonymized_value = 'xxx'+sid elif field_type == 'boolean': anonymized_value = random.choice([True, False]) elif field_type == 'date': anonymized_value = '2011-11-11' elif field_type == 'datetime': anonymized_value = '2011-11-11 11:11:11' elif field_type == 'float': anonymized_value = 0.0 elif field_type == 'integer': anonymized_value = 0 elif field_type in ['binary', 'many2many', 'many2one', 'one2many', 'reference']: # cannot anonymize these kind of fields msg = _("Cannot anonymize fields of these types: binary, many2many, many2one, one2many, reference.") self._raise_after_history_update(cr, uid, history_id, 'Error !', msg) if anonymized_value is None: self._raise_after_history_update(cr, uid, history_id, _('Error !'), _("Anonymized value is None. This cannot happens.")) sql = "update %(table)s set %(field)s = %%(anonymized_value)s where id = %%(id)s" % { 'table': table_name, 'field': field_name, } cr.execute(sql, { 'anonymized_value': anonymized_value, 'id': record['id'] }) # save pickle: fn = open(abs_filepath, 'w') pickle.dump(data, fn, pickle.HIGHEST_PROTOCOL) # update the anonymization fields: values = { 'state': 'anonymized', } ir_model_fields_anonymization_model.write(cr, uid, field_ids, values, context=context) # add a result message in the wizard: msgs = ["Anonymization successful.", "", "Donot forget to save the resulting file to a safe place because you will not be able to revert the anonymization without this file.", "", "This file is also stored in the %s directory. The absolute file path is: %s.", ] msg = '\n'.join(msgs) % (dirpath, abs_filepath) fn = open(abs_filepath, 'r') self.write(cr, uid, ids, { 'msg': msg, 'file_export': base64.encodestring(fn.read()), }) fn.close() # update the history record: anonymization_history_model.write(cr, uid, history_id, { 'field_ids': [[6, 0, field_ids]], 'msg': msg, 'filepath': abs_filepath, 'state': 'done', }) # handle the view: view_id = self._id_get(cr, uid, 'ir.ui.view', 'view_ir_model_fields_anonymize_wizard_form', 'anonymization') return { 'res_id': ids[0], 'view_id': [view_id], 'view_type': 'form', "view_mode": 'form', 'res_model': 'ir.model.fields.anonymize.wizard', 'type': 'ir.actions.act_window', 'context': {'step': 'just_anonymized'}, 'target':'new', } def reverse_anonymize_database(self, cr, uid, ids, context=None): """Set the 'clear' state to defined fields""" ir_model_fields_anonymization_model = self.pool.get('ir.model.fields.anonymization') anonymization_history_model = self.pool.get('ir.model.fields.anonymization.history') # create a new history record: vals = { 'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'state': 'started', 'direction': 'anonymized -> clear', } history_id = anonymization_history_model.create(cr, uid, vals) # check that all the defined fields are in the 'anonymized' state state = ir_model_fields_anonymization_model._get_global_state(cr, uid, context=context) if state == 'clear': raise osv.except_osv_('Error!', "The database is not currently anonymized, you cannot reverse the anonymization.") elif state == 'unstable': msg = _("The database anonymization is currently in an unstable state. Some fields are anonymized," + \ " while some fields are not anonymized. You should try to solve this problem before trying to do anything.") raise osv.except_osv('Error!', msg) wizards = self.browse(cr, uid, ids, context=context) for wizard in wizards: if not wizard.file_import: msg = _("It is not possible to reverse the anonymization process without supplying the anonymization export file.") self._raise_after_history_update(cr, uid, history_id, 'Error !', msg) # reverse the anonymization: # load the pickle file content into a data structure: data = pickle.loads(base64.decodestring(wizard.file_import)) migration_fix_obj = self.pool.get('ir.model.fields.anonymization.migration.fix') fix_ids = migration_fix_obj.search(cr, uid, [('target_version', '=', '8.0')]) fixes = migration_fix_obj.read(cr, uid, fix_ids, ['model_name', 'field_name', 'query', 'query_type', 'sequence']) fixes = group(fixes, ('model_name', 'field_name')) for line in data: queries = [] table_name = self.pool[line['model_id']]._table if line['model_id'] in self.pool else None # check if custom sql exists: key = (line['model_id'], line['field_id']) custom_updates = fixes.get(key) if custom_updates: custom_updates.sort(key=itemgetter('sequence')) queries = [(record['query'], record['query_type']) for record in custom_updates if record['query_type']] elif table_name: queries = [("update %(table)s set %(field)s = %%(value)s where id = %%(id)s" % { 'table': table_name, 'field': line['field_id'], }, 'sql')] for query in queries: if query[1] == 'sql': sql = query[0] cr.execute(sql, { 'value': line['value'], 'id': line['id'] }) elif query[1] == 'python': raw_code = query[0] code = raw_code % line eval(code) else: raise Exception("Unknown query type '%s'. Valid types are: sql, python." % (query['query_type'], )) # update the anonymization fields: ir_model_fields_anonymization_model = self.pool.get('ir.model.fields.anonymization') field_ids = ir_model_fields_anonymization_model.search(cr, uid, [('state', '<>', 'not_existing')], context=context) values = { 'state': 'clear', } ir_model_fields_anonymization_model.write(cr, uid, field_ids, values, context=context) # add a result message in the wizard: msg = '\n'.join(["Successfully reversed the anonymization.", "", ]) self.write(cr, uid, ids, {'msg': msg}) # update the history record: anonymization_history_model.write(cr, uid, history_id, { 'field_ids': [[6, 0, field_ids]], 'msg': msg, 'filepath': False, 'state': 'done', }) # handle the view: view_id = self._id_get(cr, uid, 'ir.ui.view', 'view_ir_model_fields_anonymize_wizard_form', 'anonymization') return { 'res_id': ids[0], 'view_id': [view_id], 'view_type': 'form', "view_mode": 'form', 'res_model': 'ir.model.fields.anonymize.wizard', 'type': 'ir.actions.act_window', 'context': {'step': 'just_desanonymized'}, 'target':'new', } def _id_get(self, cr, uid, model, id_str, mod): if '.' in id_str: mod, id_str = id_str.split('.') try: idn = self.pool.get('ir.model.data')._get_id(cr, uid, mod, id_str) res = int(self.pool.get('ir.model.data').read(cr, uid, [idn], ['res_id'])[0]['res_id']) except: res = None return res class ir_model_fields_anonymization_migration_fix(osv.osv): _name = 'ir.model.fields.anonymization.migration.fix' _order = "sequence" _columns = { 'target_version': fields.char('Target Version'), 'model_name': fields.char('Model'), 'field_name': fields.char('Field'), 'query': fields.text('Query'), 'query_type': fields.selection(string='Query', selection=[('sql', 'sql'), ('python', 'python')]), 'sequence': fields.integer('Sequence'), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
rjschwei/boto
boto/ecs/item.py
89
5148
# Copyright (c) 2010 Chris Moyer http://coredumped.org/ # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. import xml.sax import cgi from StringIO import StringIO class ResponseGroup(xml.sax.ContentHandler): """A Generic "Response Group", which can be anything from the entire list of Items to specific response elements within an item""" def __init__(self, connection=None, nodename=None): """Initialize this Item""" self._connection = connection self._nodename = nodename self._nodepath = [] self._curobj = None self._xml = StringIO() def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self.__dict__) # # Attribute Functions # def get(self, name): return self.__dict__.get(name) def set(self, name, value): self.__dict__[name] = value def to_xml(self): return "<%s>%s</%s>" % (self._nodename, self._xml.getvalue(), self._nodename) # # XML Parser functions # def startElement(self, name, attrs, connection): self._xml.write("<%s>" % name) self._nodepath.append(name) if len(self._nodepath) == 1: obj = ResponseGroup(self._connection) self.set(name, obj) self._curobj = obj elif self._curobj: self._curobj.startElement(name, attrs, connection) return None def endElement(self, name, value, connection): self._xml.write("%s</%s>" % (cgi.escape(value).replace("&amp;amp;", "&amp;"), name)) if len(self._nodepath) == 0: return obj = None curval = self.get(name) if len(self._nodepath) == 1: if value or not curval: self.set(name, value) if self._curobj: self._curobj = None #elif len(self._nodepath) == 2: #self._curobj = None elif self._curobj: self._curobj.endElement(name, value, connection) self._nodepath.pop() return None class Item(ResponseGroup): """A single Item""" def __init__(self, connection=None): """Initialize this Item""" ResponseGroup.__init__(self, connection, "Item") class ItemSet(ResponseGroup): """A special ResponseGroup that has built-in paging, and only creates new Items on the "Item" tag""" def __init__(self, connection, action, params, page=0): ResponseGroup.__init__(self, connection, "Items") self.objs = [] self.iter = None self.page = page self.action = action self.params = params self.curItem = None self.total_results = 0 self.total_pages = 0 def startElement(self, name, attrs, connection): if name == "Item": self.curItem = Item(self._connection) elif self.curItem != None: self.curItem.startElement(name, attrs, connection) return None def endElement(self, name, value, connection): if name == 'TotalResults': self.total_results = value elif name == 'TotalPages': self.total_pages = value elif name == "Item": self.objs.append(self.curItem) self._xml.write(self.curItem.to_xml()) self.curItem = None elif self.curItem != None: self.curItem.endElement(name, value, connection) return None def next(self): """Special paging functionality""" if self.iter == None: self.iter = iter(self.objs) try: return self.iter.next() except StopIteration: self.iter = None self.objs = [] if int(self.page) < int(self.total_pages): self.page += 1 self._connection.get_response(self.action, self.params, self.page, self) return self.next() else: raise def __iter__(self): return self def to_xml(self): """Override to first fetch everything""" for item in self: pass return ResponseGroup.to_xml(self)
mit
faux123/kernel-msm
arch/ia64/scripts/unwcheck.py
13143
1714
#!/usr/bin/python # # Usage: unwcheck.py FILE # # This script checks the unwind info of each function in file FILE # and verifies that the sum of the region-lengths matches the total # length of the function. # # Based on a shell/awk script originally written by Harish Patil, # which was converted to Perl by Matthew Chapman, which was converted # to Python by David Mosberger. # import os import re import sys if len(sys.argv) != 2: print "Usage: %s FILE" % sys.argv[0] sys.exit(2) readelf = os.getenv("READELF", "readelf") start_pattern = re.compile("<([^>]*)>: \[0x([0-9a-f]+)-0x([0-9a-f]+)\]") rlen_pattern = re.compile(".*rlen=([0-9]+)") def check_func (func, slots, rlen_sum): if slots != rlen_sum: global num_errors num_errors += 1 if not func: func = "[%#x-%#x]" % (start, end) print "ERROR: %s: %lu slots, total region length = %lu" % (func, slots, rlen_sum) return num_funcs = 0 num_errors = 0 func = False slots = 0 rlen_sum = 0 for line in os.popen("%s -u %s" % (readelf, sys.argv[1])): m = start_pattern.match(line) if m: check_func(func, slots, rlen_sum) func = m.group(1) start = long(m.group(2), 16) end = long(m.group(3), 16) slots = 3 * (end - start) / 16 rlen_sum = 0L num_funcs += 1 else: m = rlen_pattern.match(line) if m: rlen_sum += long(m.group(1)) check_func(func, slots, rlen_sum) if num_errors == 0: print "No errors detected in %u functions." % num_funcs else: if num_errors > 1: err="errors" else: err="error" print "%u %s detected in %u functions." % (num_errors, err, num_funcs) sys.exit(1)
gpl-2.0
nuuuboo/odoo
addons/website_event_track/models/event.py
300
8344
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ from openerp.addons.website.models.website import slug import pytz class event_track_tag(osv.osv): _name = "event.track.tag" _order = 'name' _columns = { 'name': fields.char('Event Track Tag', translate=True) } class event_tag(osv.osv): _name = "event.tag" _order = 'name' _columns = { 'name': fields.char('Event Tag', translate=True) } # # Tracks: conferences # class event_track_stage(osv.osv): _name = "event.track.stage" _order = 'sequence' _columns = { 'name': fields.char('Track Stage', translate=True), 'sequence': fields.integer('Sequence') } _defaults = { 'sequence': 0 } class event_track_location(osv.osv): _name = "event.track.location" _columns = { 'name': fields.char('Track Rooms') } class event_track(osv.osv): _name = "event.track" _description = 'Event Tracks' _order = 'priority, date' _inherit = ['mail.thread', 'ir.needaction_mixin', 'website.seo.metadata'] def _website_url(self, cr, uid, ids, field_name, arg, context=None): res = dict.fromkeys(ids, '') for track in self.browse(cr, uid, ids, context=context): res[track.id] = "/event/%s/track/%s" % (slug(track.event_id), slug(track)) return res _columns = { 'name': fields.char('Track Title', required=True, translate=True), 'user_id': fields.many2one('res.users', 'Responsible'), 'speaker_ids': fields.many2many('res.partner', string='Speakers'), 'tag_ids': fields.many2many('event.track.tag', string='Tags'), 'stage_id': fields.many2one('event.track.stage', 'Stage'), 'description': fields.html('Track Description', translate=True), 'date': fields.datetime('Track Date'), 'duration': fields.float('Duration', digits=(16,2)), 'location_id': fields.many2one('event.track.location', 'Location'), 'event_id': fields.many2one('event.event', 'Event', required=True), 'color': fields.integer('Color Index'), 'priority': fields.selection([('3','Low'),('2','Medium (*)'),('1','High (**)'),('0','Highest (***)')], 'Priority', required=True), 'website_published': fields.boolean('Available in the website', copy=False), 'website_url': fields.function(_website_url, string="Website url", type="char"), 'image': fields.related('speaker_ids', 'image', type='binary', readonly=True) } def set_priority(self, cr, uid, ids, priority, context={}): return self.write(cr, uid, ids, {'priority' : priority}) def _default_stage_id(self, cr, uid, context={}): stage_obj = self.pool.get('event.track.stage') ids = stage_obj.search(cr, uid, [], context=context) return ids and ids[0] or False _defaults = { 'user_id': lambda self, cr, uid, ctx: uid, 'website_published': lambda self, cr, uid, ctx: False, 'duration': lambda *args: 1.5, 'stage_id': _default_stage_id, 'priority': '2' } def _read_group_stage_ids(self, cr, uid, ids, domain, read_group_order=None, access_rights_uid=None, context=None): stage_obj = self.pool.get('event.track.stage') result = stage_obj.name_search(cr, uid, '', context=context) return result, {} _group_by_full = { 'stage_id': _read_group_stage_ids, } # # Events # class event_event(osv.osv): _inherit = "event.event" def _list_tz(self,cr,uid, context=None): # put POSIX 'Etc/*' entries at the end to avoid confusing users - see bug 1086728 return [(tz,tz) for tz in sorted(pytz.all_timezones, key=lambda tz: tz if not tz.startswith('Etc/') else '_')] def _count_tracks(self, cr, uid, ids, field_name, arg, context=None): return { event.id: len(event.track_ids) for event in self.browse(cr, uid, ids, context=context) } def _get_tracks_tag_ids(self, cr, uid, ids, field_names, arg=None, context=None): res = dict((res_id, []) for res_id in ids) for event in self.browse(cr, uid, ids, context=context): for track in event.track_ids: res[event.id] += [tag.id for tag in track.tag_ids] res[event.id] = list(set(res[event.id])) return res _columns = { 'tag_ids': fields.many2many('event.tag', string='Tags'), 'track_ids': fields.one2many('event.track', 'event_id', 'Tracks', copy=True), 'sponsor_ids': fields.one2many('event.sponsor', 'event_id', 'Sponsorships', copy=True), 'blog_id': fields.many2one('blog.blog', 'Event Blog'), 'show_track_proposal': fields.boolean('Talks Proposals'), 'show_tracks': fields.boolean('Multiple Tracks'), 'show_blog': fields.boolean('News'), 'count_tracks': fields.function(_count_tracks, type='integer', string='Tracks'), 'tracks_tag_ids': fields.function(_get_tracks_tag_ids, type='one2many', relation='event.track.tag', string='Tags of Tracks'), 'allowed_track_tag_ids': fields.many2many('event.track.tag', string='Accepted Tags', help="List of available tags for track proposals."), 'timezone_of_event': fields.selection(_list_tz, 'Event Timezone', size=64), } _defaults = { 'show_track_proposal': False, 'show_tracks': False, 'show_blog': False, 'timezone_of_event':lambda self,cr,uid,c: self.pool.get('res.users').browse(cr, uid, uid, c).tz, } def _get_new_menu_pages(self, cr, uid, event, context=None): context = context or {} result = super(event_event, self)._get_new_menu_pages(cr, uid, event, context=context) if event.show_tracks: result.append( (_('Talks'), '/event/%s/track' % slug(event))) result.append( (_('Agenda'), '/event/%s/agenda' % slug(event))) if event.blog_id: result.append( (_('News'), '/blogpost'+slug(event.blog_ig))) if event.show_track_proposal: result.append( (_('Talk Proposals'), '/event/%s/track_proposal' % slug(event))) return result # # Sponsors # class event_sponsors_type(osv.osv): _name = "event.sponsor.type" _order = "sequence" _columns = { "name": fields.char('Sponsor Type', required=True, translate=True), "sequence": fields.integer('Sequence') } class event_sponsors(osv.osv): _name = "event.sponsor" _order = "sequence" _columns = { 'event_id': fields.many2one('event.event', 'Event', required=True), 'sponsor_type_id': fields.many2one('event.sponsor.type', 'Sponsoring Type', required=True), 'partner_id': fields.many2one('res.partner', 'Sponsor/Customer', required=True), 'url': fields.text('Sponsor Website'), 'sequence': fields.related('sponsor_type_id', 'sequence', string='Sequence', store=True), 'image_medium': fields.related('partner_id', 'image_medium', string='Logo', type='binary') } def has_access_to_partner(self, cr, uid, ids, context=None): partner_ids = [sponsor.partner_id.id for sponsor in self.browse(cr, uid, ids, context=context)] return len(partner_ids) == self.pool.get("res.partner").search(cr, uid, [("id", "in", partner_ids)], count=True, context=context)
agpl-3.0
vivisect/synapse
synapse/tests/test_lib_threads.py
1
4063
import synapse.lib.socket as s_socket import synapse.lib.threads as s_threads from synapse.tests.common import * def newtask(func, *args, **kwargs): return (func, args, kwargs) class ThreadsTest(SynTest): def test_threads_pool(self): def woot(x, y): return x + y with s_threads.Pool() as pool: with pool.task(woot, 20, 30) as task: pass self.true(task.waitfini(timeout=1)) def test_threads_pool_wrap(self): evnt = threading.Event() def woot(x, y): evnt.set() return x + y with s_threads.Pool() as pool: pool.wrap(woot)(20, 30) self.true(evnt.wait(timeout=1)) def test_threads_cancelable(self): sock1, sock2 = s_socket.socketpair() data = [] def echoloop(): with s_threads.cancelable(sock1.fini): byts = sock1.recv(1024) data.append(byts) sock1.sendall(byts) thr = s_threads.worker(echoloop) sock2.sendall(b'hi') self.eq(sock2.recv(1024), b'hi') thr.fini() thr.join() sock1.fini() sock2.fini() def test_threads_cantwait(self): self.true(s_threads.iMayWait()) s_threads.iCantWait() self.false(s_threads.iMayWait()) self.raises(MustNotWait, s_threads.iWillWait) del threading.currentThread()._syn_cantwait self.true(s_threads.iMayWait()) def test_threads_exception(self): data = {} def breakstuff(): data['key'] = True return 1 / 0 with self.getLoggerStream('synapse.lib.threads', 'error running task for') as stream: with s_threads.Pool() as pool: pool.call(breakstuff) self.true(stream.wait(2)) self.true(data.get('key')) def test_threads_retnwait(self): with s_threads.RetnWait() as retn: def work(): retn.retn(True) thrd = s_threads.worker(work) self.eq(retn.wait(timeout=1), (True, True)) thrd.join() self.eq(retn.wait(timeout=1), (True, True)) # no timeout with s_threads.RetnWait() as retn: def work(): retn.retn(True) thrd = s_threads.worker(work) self.eq(retn.wait(), (True, True)) thrd.join() self.eq(retn.wait(timeout=1), (True, True)) # Let a wait() timeout with s_threads.RetnWait() as retn: def work(): time.sleep(0.5) retn.retn(True) thrd = s_threads.worker(work) ok, retn = retn.wait(timeout=0.01) self.false(ok) self.eq(retn[0], 'TimeOut') thrd.join() with s_threads.RetnWait() as retn: def work(): try: 1 / 0 except ZeroDivisionError as e: retn.errx(e) thrd = s_threads.worker(work) ret = retn.wait(timeout=1) thrd.join() self.false(ret[0]) excfo = ret[1] self.istufo(excfo) self.eq(excfo[0], 'ZeroDivisionError') self.eq(excfo[1].get('msg'), 'division by zero') self.eq(excfo[1].get('name'), 'work') self.isin('test_lib_threads.py', excfo[1].get('file')) self.isin('line', excfo[1]) # Line may change self.isin('src', excfo[1]) # source for a inner function may not be available. # Test capture with s_threads.RetnWait() as retn: def work(a, b, c, callback): sum = a + b multiple = sum * c callback(sum, multiple, a=a, b=b, c=c) thrd = s_threads.worker(work, 1, 2, 3, retn.capture) ret = retn.wait(timeout=1) thrd.join() self.true(ret[0]) self.eq(ret[1], ((3, 9), {'a': 1, 'b': 2, 'c': 3}))
apache-2.0
ubuntu-chu/linux3.6.9-at91
tools/perf/util/setup.py
4998
1330
#!/usr/bin/python2 from distutils.core import setup, Extension from os import getenv from distutils.command.build_ext import build_ext as _build_ext from distutils.command.install_lib import install_lib as _install_lib class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_options(self) self.build_lib = build_lib self.build_temp = build_tmp class install_lib(_install_lib): def finalize_options(self): _install_lib.finalize_options(self) self.build_dir = build_lib cflags = ['-fno-strict-aliasing', '-Wno-write-strings'] cflags += getenv('CFLAGS', '').split() build_lib = getenv('PYTHON_EXTBUILD_LIB') build_tmp = getenv('PYTHON_EXTBUILD_TMP') ext_sources = [f.strip() for f in file('util/python-ext-sources') if len(f.strip()) > 0 and f[0] != '#'] perf = Extension('perf', sources = ext_sources, include_dirs = ['util/include'], extra_compile_args = cflags, ) setup(name='perf', version='0.1', description='Interface with the Linux profiling infrastructure', author='Arnaldo Carvalho de Melo', author_email='acme@redhat.com', license='GPLv2', url='http://perf.wiki.kernel.org', ext_modules=[perf], cmdclass={'build_ext': build_ext, 'install_lib': install_lib})
gpl-2.0
hollabaq86/haikuna-matata
env/lib/python2.7/site-packages/nltk/tree.py
5
64375
# -*- coding: utf-8 -*- # Natural Language Toolkit: Text Trees # # Copyright (C) 2001-2017 NLTK Project # Author: Edward Loper <edloper@gmail.com> # Steven Bird <stevenbird1@gmail.com> # Peter Ljunglöf <peter.ljunglof@gu.se> # Nathan Bodenstab <bodenstab@cslu.ogi.edu> (tree transforms) # URL: <http://nltk.org/> # For license information, see LICENSE.TXT """ Class for representing hierarchical language structures, such as syntax trees and morphological trees. """ from __future__ import print_function, unicode_literals # TODO: add LabelledTree (can be used for dependency trees) import re from nltk.grammar import Production, Nonterminal from nltk.probability import ProbabilisticMixIn from nltk.util import slice_bounds from nltk.compat import string_types, python_2_unicode_compatible, unicode_repr from nltk.internals import raise_unorderable_types ###################################################################### ## Trees ###################################################################### @python_2_unicode_compatible class Tree(list): """ A Tree represents a hierarchical grouping of leaves and subtrees. For example, each constituent in a syntax tree is represented by a single Tree. A tree's children are encoded as a list of leaves and subtrees, where a leaf is a basic (non-tree) value; and a subtree is a nested Tree. >>> from nltk.tree import Tree >>> print(Tree(1, [2, Tree(3, [4]), 5])) (1 2 (3 4) 5) >>> vp = Tree('VP', [Tree('V', ['saw']), ... Tree('NP', ['him'])]) >>> s = Tree('S', [Tree('NP', ['I']), vp]) >>> print(s) (S (NP I) (VP (V saw) (NP him))) >>> print(s[1]) (VP (V saw) (NP him)) >>> print(s[1,1]) (NP him) >>> t = Tree.fromstring("(S (NP I) (VP (V saw) (NP him)))") >>> s == t True >>> t[1][1].set_label('X') >>> t[1][1].label() 'X' >>> print(t) (S (NP I) (VP (V saw) (X him))) >>> t[0], t[1,1] = t[1,1], t[0] >>> print(t) (S (X him) (VP (V saw) (NP I))) The length of a tree is the number of children it has. >>> len(t) 2 The set_label() and label() methods allow individual constituents to be labeled. For example, syntax trees use this label to specify phrase tags, such as "NP" and "VP". Several Tree methods use "tree positions" to specify children or descendants of a tree. Tree positions are defined as follows: - The tree position *i* specifies a Tree's *i*\ th child. - The tree position ``()`` specifies the Tree itself. - If *p* is the tree position of descendant *d*, then *p+i* specifies the *i*\ th child of *d*. I.e., every tree position is either a single index *i*, specifying ``tree[i]``; or a sequence *i1, i2, ..., iN*, specifying ``tree[i1][i2]...[iN]``. Construct a new tree. This constructor can be called in one of two ways: - ``Tree(label, children)`` constructs a new tree with the specified label and list of children. - ``Tree.fromstring(s)`` constructs a new tree by parsing the string ``s``. """ def __init__(self, node, children=None): if children is None: raise TypeError("%s: Expected a node value and child list " % type(self).__name__) elif isinstance(children, string_types): raise TypeError("%s() argument 2 should be a list, not a " "string" % type(self).__name__) else: list.__init__(self, children) self._label = node #//////////////////////////////////////////////////////////// # Comparison operators #//////////////////////////////////////////////////////////// def __eq__(self, other): return (self.__class__ is other.__class__ and (self._label, list(self)) == (other._label, list(other))) def __lt__(self, other): if not isinstance(other, Tree): # raise_unorderable_types("<", self, other) # Sometimes children can be pure strings, # so we need to be able to compare with non-trees: return self.__class__.__name__ < other.__class__.__name__ elif self.__class__ is other.__class__: return (self._label, list(self)) < (other._label, list(other)) else: return self.__class__.__name__ < other.__class__.__name__ # @total_ordering doesn't work here, since the class inherits from a builtin class __ne__ = lambda self, other: not self == other __gt__ = lambda self, other: not (self < other or self == other) __le__ = lambda self, other: self < other or self == other __ge__ = lambda self, other: not self < other #//////////////////////////////////////////////////////////// # Disabled list operations #//////////////////////////////////////////////////////////// def __mul__(self, v): raise TypeError('Tree does not support multiplication') def __rmul__(self, v): raise TypeError('Tree does not support multiplication') def __add__(self, v): raise TypeError('Tree does not support addition') def __radd__(self, v): raise TypeError('Tree does not support addition') #//////////////////////////////////////////////////////////// # Indexing (with support for tree positions) #//////////////////////////////////////////////////////////// def __getitem__(self, index): if isinstance(index, (int, slice)): return list.__getitem__(self, index) elif isinstance(index, (list, tuple)): if len(index) == 0: return self elif len(index) == 1: return self[index[0]] else: return self[index[0]][index[1:]] else: raise TypeError("%s indices must be integers, not %s" % (type(self).__name__, type(index).__name__)) def __setitem__(self, index, value): if isinstance(index, (int, slice)): return list.__setitem__(self, index, value) elif isinstance(index, (list, tuple)): if len(index) == 0: raise IndexError('The tree position () may not be ' 'assigned to.') elif len(index) == 1: self[index[0]] = value else: self[index[0]][index[1:]] = value else: raise TypeError("%s indices must be integers, not %s" % (type(self).__name__, type(index).__name__)) def __delitem__(self, index): if isinstance(index, (int, slice)): return list.__delitem__(self, index) elif isinstance(index, (list, tuple)): if len(index) == 0: raise IndexError('The tree position () may not be deleted.') elif len(index) == 1: del self[index[0]] else: del self[index[0]][index[1:]] else: raise TypeError("%s indices must be integers, not %s" % (type(self).__name__, type(index).__name__)) #//////////////////////////////////////////////////////////// # Basic tree operations #//////////////////////////////////////////////////////////// def _get_node(self): """Outdated method to access the node value; use the label() method instead.""" raise NotImplementedError("Use label() to access a node label.") def _set_node(self, value): """Outdated method to set the node value; use the set_label() method instead.""" raise NotImplementedError("Use set_label() method to set a node label.") node = property(_get_node, _set_node) def label(self): """ Return the node label of the tree. >>> t = Tree.fromstring('(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))') >>> t.label() 'S' :return: the node label (typically a string) :rtype: any """ return self._label def set_label(self, label): """ Set the node label of the tree. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))") >>> t.set_label("T") >>> print(t) (T (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat)))) :param label: the node label (typically a string) :type label: any """ self._label = label def leaves(self): """ Return the leaves of the tree. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))") >>> t.leaves() ['the', 'dog', 'chased', 'the', 'cat'] :return: a list containing this tree's leaves. The order reflects the order of the leaves in the tree's hierarchical structure. :rtype: list """ leaves = [] for child in self: if isinstance(child, Tree): leaves.extend(child.leaves()) else: leaves.append(child) return leaves def flatten(self): """ Return a flat version of the tree, with all non-root non-terminals removed. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))") >>> print(t.flatten()) (S the dog chased the cat) :return: a tree consisting of this tree's root connected directly to its leaves, omitting all intervening non-terminal nodes. :rtype: Tree """ return Tree(self.label(), self.leaves()) def height(self): """ Return the height of the tree. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))") >>> t.height() 5 >>> print(t[0,0]) (D the) >>> t[0,0].height() 2 :return: The height of this tree. The height of a tree containing no children is 1; the height of a tree containing only leaves is 2; and the height of any other tree is one plus the maximum of its children's heights. :rtype: int """ max_child_height = 0 for child in self: if isinstance(child, Tree): max_child_height = max(max_child_height, child.height()) else: max_child_height = max(max_child_height, 1) return 1 + max_child_height def treepositions(self, order='preorder'): """ >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))") >>> t.treepositions() # doctest: +ELLIPSIS [(), (0,), (0, 0), (0, 0, 0), (0, 1), (0, 1, 0), (1,), (1, 0), (1, 0, 0), ...] >>> for pos in t.treepositions('leaves'): ... t[pos] = t[pos][::-1].upper() >>> print(t) (S (NP (D EHT) (N GOD)) (VP (V DESAHC) (NP (D EHT) (N TAC)))) :param order: One of: ``preorder``, ``postorder``, ``bothorder``, ``leaves``. """ positions = [] if order in ('preorder', 'bothorder'): positions.append( () ) for i, child in enumerate(self): if isinstance(child, Tree): childpos = child.treepositions(order) positions.extend((i,)+p for p in childpos) else: positions.append( (i,) ) if order in ('postorder', 'bothorder'): positions.append( () ) return positions def subtrees(self, filter=None): """ Generate all the subtrees of this tree, optionally restricted to trees matching the filter function. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))") >>> for s in t.subtrees(lambda t: t.height() == 2): ... print(s) (D the) (N dog) (V chased) (D the) (N cat) :type filter: function :param filter: the function to filter all local trees """ if not filter or filter(self): yield self for child in self: if isinstance(child, Tree): for subtree in child.subtrees(filter): yield subtree def productions(self): """ Generate the productions that correspond to the non-terminal nodes of the tree. For each subtree of the form (P: C1 C2 ... Cn) this produces a production of the form P -> C1 C2 ... Cn. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))") >>> t.productions() [S -> NP VP, NP -> D N, D -> 'the', N -> 'dog', VP -> V NP, V -> 'chased', NP -> D N, D -> 'the', N -> 'cat'] :rtype: list(Production) """ if not isinstance(self._label, string_types): raise TypeError('Productions can only be generated from trees having node labels that are strings') prods = [Production(Nonterminal(self._label), _child_names(self))] for child in self: if isinstance(child, Tree): prods += child.productions() return prods def pos(self): """ Return a sequence of pos-tagged words extracted from the tree. >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))") >>> t.pos() [('the', 'D'), ('dog', 'N'), ('chased', 'V'), ('the', 'D'), ('cat', 'N')] :return: a list of tuples containing leaves and pre-terminals (part-of-speech tags). The order reflects the order of the leaves in the tree's hierarchical structure. :rtype: list(tuple) """ pos = [] for child in self: if isinstance(child, Tree): pos.extend(child.pos()) else: pos.append((child, self._label)) return pos def leaf_treeposition(self, index): """ :return: The tree position of the ``index``-th leaf in this tree. I.e., if ``tp=self.leaf_treeposition(i)``, then ``self[tp]==self.leaves()[i]``. :raise IndexError: If this tree contains fewer than ``index+1`` leaves, or if ``index<0``. """ if index < 0: raise IndexError('index must be non-negative') stack = [(self, ())] while stack: value, treepos = stack.pop() if not isinstance(value, Tree): if index == 0: return treepos else: index -= 1 else: for i in range(len(value)-1, -1, -1): stack.append( (value[i], treepos+(i,)) ) raise IndexError('index must be less than or equal to len(self)') def treeposition_spanning_leaves(self, start, end): """ :return: The tree position of the lowest descendant of this tree that dominates ``self.leaves()[start:end]``. :raise ValueError: if ``end <= start`` """ if end <= start: raise ValueError('end must be greater than start') # Find the tree positions of the start & end leaves, and # take the longest common subsequence. start_treepos = self.leaf_treeposition(start) end_treepos = self.leaf_treeposition(end-1) # Find the first index where they mismatch: for i in range(len(start_treepos)): if i == len(end_treepos) or start_treepos[i] != end_treepos[i]: return start_treepos[:i] return start_treepos #//////////////////////////////////////////////////////////// # Transforms #//////////////////////////////////////////////////////////// def chomsky_normal_form(self, factor="right", horzMarkov=None, vertMarkov=0, childChar="|", parentChar="^"): """ This method can modify a tree in three ways: 1. Convert a tree into its Chomsky Normal Form (CNF) equivalent -- Every subtree has either two non-terminals or one terminal as its children. This process requires the creation of more"artificial" non-terminal nodes. 2. Markov (vertical) smoothing of children in new artificial nodes 3. Horizontal (parent) annotation of nodes :param factor: Right or left factoring method (default = "right") :type factor: str = [left|right] :param horzMarkov: Markov order for sibling smoothing in artificial nodes (None (default) = include all siblings) :type horzMarkov: int | None :param vertMarkov: Markov order for parent smoothing (0 (default) = no vertical annotation) :type vertMarkov: int | None :param childChar: A string used in construction of the artificial nodes, separating the head of the original subtree from the child nodes that have yet to be expanded (default = "|") :type childChar: str :param parentChar: A string used to separate the node representation from its vertical annotation :type parentChar: str """ from nltk.treetransforms import chomsky_normal_form chomsky_normal_form(self, factor, horzMarkov, vertMarkov, childChar, parentChar) def un_chomsky_normal_form(self, expandUnary = True, childChar = "|", parentChar = "^", unaryChar = "+"): """ This method modifies the tree in three ways: 1. Transforms a tree in Chomsky Normal Form back to its original structure (branching greater than two) 2. Removes any parent annotation (if it exists) 3. (optional) expands unary subtrees (if previously collapsed with collapseUnary(...) ) :param expandUnary: Flag to expand unary or not (default = True) :type expandUnary: bool :param childChar: A string separating the head node from its children in an artificial node (default = "|") :type childChar: str :param parentChar: A sting separating the node label from its parent annotation (default = "^") :type parentChar: str :param unaryChar: A string joining two non-terminals in a unary production (default = "+") :type unaryChar: str """ from nltk.treetransforms import un_chomsky_normal_form un_chomsky_normal_form(self, expandUnary, childChar, parentChar, unaryChar) def collapse_unary(self, collapsePOS = False, collapseRoot = False, joinChar = "+"): """ Collapse subtrees with a single child (ie. unary productions) into a new non-terminal (Tree node) joined by 'joinChar'. This is useful when working with algorithms that do not allow unary productions, and completely removing the unary productions would require loss of useful information. The Tree is modified directly (since it is passed by reference) and no value is returned. :param collapsePOS: 'False' (default) will not collapse the parent of leaf nodes (ie. Part-of-Speech tags) since they are always unary productions :type collapsePOS: bool :param collapseRoot: 'False' (default) will not modify the root production if it is unary. For the Penn WSJ treebank corpus, this corresponds to the TOP -> productions. :type collapseRoot: bool :param joinChar: A string used to connect collapsed node values (default = "+") :type joinChar: str """ from nltk.treetransforms import collapse_unary collapse_unary(self, collapsePOS, collapseRoot, joinChar) #//////////////////////////////////////////////////////////// # Convert, copy #//////////////////////////////////////////////////////////// @classmethod def convert(cls, tree): """ Convert a tree between different subtypes of Tree. ``cls`` determines which class will be used to encode the new tree. :type tree: Tree :param tree: The tree that should be converted. :return: The new Tree. """ if isinstance(tree, Tree): children = [cls.convert(child) for child in tree] return cls(tree._label, children) else: return tree def copy(self, deep=False): if not deep: return type(self)(self._label, self) else: return type(self).convert(self) def _frozen_class(self): return ImmutableTree def freeze(self, leaf_freezer=None): frozen_class = self._frozen_class() if leaf_freezer is None: newcopy = frozen_class.convert(self) else: newcopy = self.copy(deep=True) for pos in newcopy.treepositions('leaves'): newcopy[pos] = leaf_freezer(newcopy[pos]) newcopy = frozen_class.convert(newcopy) hash(newcopy) # Make sure the leaves are hashable. return newcopy #//////////////////////////////////////////////////////////// # Parsing #//////////////////////////////////////////////////////////// @classmethod def fromstring(cls, s, brackets='()', read_node=None, read_leaf=None, node_pattern=None, leaf_pattern=None, remove_empty_top_bracketing=False): """ Read a bracketed tree string and return the resulting tree. Trees are represented as nested brackettings, such as:: (S (NP (NNP John)) (VP (V runs))) :type s: str :param s: The string to read :type brackets: str (length=2) :param brackets: The bracket characters used to mark the beginning and end of trees and subtrees. :type read_node: function :type read_leaf: function :param read_node, read_leaf: If specified, these functions are applied to the substrings of ``s`` corresponding to nodes and leaves (respectively) to obtain the values for those nodes and leaves. They should have the following signature: read_node(str) -> value For example, these functions could be used to process nodes and leaves whose values should be some type other than string (such as ``FeatStruct``). Note that by default, node strings and leaf strings are delimited by whitespace and brackets; to override this default, use the ``node_pattern`` and ``leaf_pattern`` arguments. :type node_pattern: str :type leaf_pattern: str :param node_pattern, leaf_pattern: Regular expression patterns used to find node and leaf substrings in ``s``. By default, both nodes patterns are defined to match any sequence of non-whitespace non-bracket characters. :type remove_empty_top_bracketing: bool :param remove_empty_top_bracketing: If the resulting tree has an empty node label, and is length one, then return its single child instead. This is useful for treebank trees, which sometimes contain an extra level of bracketing. :return: A tree corresponding to the string representation ``s``. If this class method is called using a subclass of Tree, then it will return a tree of that type. :rtype: Tree """ if not isinstance(brackets, string_types) or len(brackets) != 2: raise TypeError('brackets must be a length-2 string') if re.search('\s', brackets): raise TypeError('whitespace brackets not allowed') # Construct a regexp that will tokenize the string. open_b, close_b = brackets open_pattern, close_pattern = (re.escape(open_b), re.escape(close_b)) if node_pattern is None: node_pattern = '[^\s%s%s]+' % (open_pattern, close_pattern) if leaf_pattern is None: leaf_pattern = '[^\s%s%s]+' % (open_pattern, close_pattern) token_re = re.compile('%s\s*(%s)?|%s|(%s)' % ( open_pattern, node_pattern, close_pattern, leaf_pattern)) # Walk through each token, updating a stack of trees. stack = [(None, [])] # list of (node, children) tuples for match in token_re.finditer(s): token = match.group() # Beginning of a tree/subtree if token[0] == open_b: if len(stack) == 1 and len(stack[0][1]) > 0: cls._parse_error(s, match, 'end-of-string') label = token[1:].lstrip() if read_node is not None: label = read_node(label) stack.append((label, [])) # End of a tree/subtree elif token == close_b: if len(stack) == 1: if len(stack[0][1]) == 0: cls._parse_error(s, match, open_b) else: cls._parse_error(s, match, 'end-of-string') label, children = stack.pop() stack[-1][1].append(cls(label, children)) # Leaf node else: if len(stack) == 1: cls._parse_error(s, match, open_b) if read_leaf is not None: token = read_leaf(token) stack[-1][1].append(token) # check that we got exactly one complete tree. if len(stack) > 1: cls._parse_error(s, 'end-of-string', close_b) elif len(stack[0][1]) == 0: cls._parse_error(s, 'end-of-string', open_b) else: assert stack[0][0] is None assert len(stack[0][1]) == 1 tree = stack[0][1][0] # If the tree has an extra level with node='', then get rid of # it. E.g.: "((S (NP ...) (VP ...)))" if remove_empty_top_bracketing and tree._label == '' and len(tree) == 1: tree = tree[0] # return the tree. return tree @classmethod def _parse_error(cls, s, match, expecting): """ Display a friendly error message when parsing a tree string fails. :param s: The string we're parsing. :param match: regexp match of the problem token. :param expecting: what we expected to see instead. """ # Construct a basic error message if match == 'end-of-string': pos, token = len(s), 'end-of-string' else: pos, token = match.start(), match.group() msg = '%s.read(): expected %r but got %r\n%sat index %d.' % ( cls.__name__, expecting, token, ' '*12, pos) # Add a display showing the error token itsels: s = s.replace('\n', ' ').replace('\t', ' ') offset = pos if len(s) > pos+10: s = s[:pos+10]+'...' if pos > 10: s = '...'+s[pos-10:] offset = 13 msg += '\n%s"%s"\n%s^' % (' '*16, s, ' '*(17+offset)) raise ValueError(msg) #//////////////////////////////////////////////////////////// # Visualization & String Representation #//////////////////////////////////////////////////////////// def draw(self): """ Open a new window containing a graphical diagram of this tree. """ from nltk.draw.tree import draw_trees draw_trees(self) def pretty_print(self, sentence=None, highlight=(), stream=None, **kwargs): """ Pretty-print this tree as ASCII or Unicode art. For explanation of the arguments, see the documentation for `nltk.treeprettyprinter.TreePrettyPrinter`. """ from nltk.treeprettyprinter import TreePrettyPrinter print(TreePrettyPrinter(self, sentence, highlight).text(**kwargs), file=stream) def __repr__(self): childstr = ", ".join(unicode_repr(c) for c in self) return '%s(%s, [%s])' % (type(self).__name__, unicode_repr(self._label), childstr) def _repr_png_(self): """ Draws and outputs in PNG for ipython. PNG is used instead of PDF, since it can be displayed in the qt console and has wider browser support. """ import os import base64 import subprocess import tempfile from nltk.draw.tree import tree_to_treesegment from nltk.draw.util import CanvasFrame from nltk.internals import find_binary _canvas_frame = CanvasFrame() widget = tree_to_treesegment(_canvas_frame.canvas(), self) _canvas_frame.add_widget(widget) x, y, w, h = widget.bbox() # print_to_file uses scrollregion to set the width and height of the pdf. _canvas_frame.canvas()['scrollregion'] = (0, 0, w, h) with tempfile.NamedTemporaryFile() as file: in_path = '{0:}.ps'.format(file.name) out_path = '{0:}.png'.format(file.name) _canvas_frame.print_to_file(in_path) _canvas_frame.destroy_widget(widget) subprocess.call([find_binary('gs', binary_names=['gswin32c.exe', 'gswin64c.exe'], env_vars=['PATH'], verbose=False)] + '-q -dEPSCrop -sDEVICE=png16m -r90 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dSAFER -dBATCH -dNOPAUSE -sOutputFile={0:} {1:}' .format(out_path, in_path).split()) with open(out_path, 'rb') as sr: res = sr.read() os.remove(in_path) os.remove(out_path) return base64.b64encode(res).decode() def __str__(self): return self.pformat() def pprint(self, **kwargs): """ Print a string representation of this Tree to 'stream' """ if "stream" in kwargs: stream = kwargs["stream"] del kwargs["stream"] else: stream = None print(self.pformat(**kwargs), file=stream) def pformat(self, margin=70, indent=0, nodesep='', parens='()', quotes=False): """ :return: A pretty-printed string representation of this tree. :rtype: str :param margin: The right margin at which to do line-wrapping. :type margin: int :param indent: The indentation level at which printing begins. This number is used to decide how far to indent subsequent lines. :type indent: int :param nodesep: A string that is used to separate the node from the children. E.g., the default value ``':'`` gives trees like ``(S: (NP: I) (VP: (V: saw) (NP: it)))``. """ # Try writing it on one line. s = self._pformat_flat(nodesep, parens, quotes) if len(s) + indent < margin: return s # If it doesn't fit on one line, then write it on multi-lines. if isinstance(self._label, string_types): s = '%s%s%s' % (parens[0], self._label, nodesep) else: s = '%s%s%s' % (parens[0], unicode_repr(self._label), nodesep) for child in self: if isinstance(child, Tree): s += '\n'+' '*(indent+2)+child.pformat(margin, indent+2, nodesep, parens, quotes) elif isinstance(child, tuple): s += '\n'+' '*(indent+2)+ "/".join(child) elif isinstance(child, string_types) and not quotes: s += '\n'+' '*(indent+2)+ '%s' % child else: s += '\n'+' '*(indent+2)+ unicode_repr(child) return s+parens[1] def pformat_latex_qtree(self): r""" Returns a representation of the tree compatible with the LaTeX qtree package. This consists of the string ``\Tree`` followed by the tree represented in bracketed notation. For example, the following result was generated from a parse tree of the sentence ``The announcement astounded us``:: \Tree [.I'' [.N'' [.D The ] [.N' [.N announcement ] ] ] [.I' [.V'' [.V' [.V astounded ] [.N'' [.N' [.N us ] ] ] ] ] ] ] See http://www.ling.upenn.edu/advice/latex.html for the LaTeX style file for the qtree package. :return: A latex qtree representation of this tree. :rtype: str """ reserved_chars = re.compile('([#\$%&~_\{\}])') pformat = self.pformat(indent=6, nodesep='', parens=('[.', ' ]')) return r'\Tree ' + re.sub(reserved_chars, r'\\\1', pformat) def _pformat_flat(self, nodesep, parens, quotes): childstrs = [] for child in self: if isinstance(child, Tree): childstrs.append(child._pformat_flat(nodesep, parens, quotes)) elif isinstance(child, tuple): childstrs.append("/".join(child)) elif isinstance(child, string_types) and not quotes: childstrs.append('%s' % child) else: childstrs.append(unicode_repr(child)) if isinstance(self._label, string_types): return '%s%s%s %s%s' % (parens[0], self._label, nodesep, " ".join(childstrs), parens[1]) else: return '%s%s%s %s%s' % (parens[0], unicode_repr(self._label), nodesep, " ".join(childstrs), parens[1]) class ImmutableTree(Tree): def __init__(self, node, children=None): super(ImmutableTree, self).__init__(node, children) # Precompute our hash value. This ensures that we're really # immutable. It also means we only have to calculate it once. try: self._hash = hash((self._label, tuple(self))) except (TypeError, ValueError): raise ValueError("%s: node value and children " "must be immutable" % type(self).__name__) def __setitem__(self, index, value): raise ValueError('%s may not be modified' % type(self).__name__) def __setslice__(self, i, j, value): raise ValueError('%s may not be modified' % type(self).__name__) def __delitem__(self, index): raise ValueError('%s may not be modified' % type(self).__name__) def __delslice__(self, i, j): raise ValueError('%s may not be modified' % type(self).__name__) def __iadd__(self, other): raise ValueError('%s may not be modified' % type(self).__name__) def __imul__(self, other): raise ValueError('%s may not be modified' % type(self).__name__) def append(self, v): raise ValueError('%s may not be modified' % type(self).__name__) def extend(self, v): raise ValueError('%s may not be modified' % type(self).__name__) def pop(self, v=None): raise ValueError('%s may not be modified' % type(self).__name__) def remove(self, v): raise ValueError('%s may not be modified' % type(self).__name__) def reverse(self): raise ValueError('%s may not be modified' % type(self).__name__) def sort(self): raise ValueError('%s may not be modified' % type(self).__name__) def __hash__(self): return self._hash def set_label(self, value): """ Set the node label. This will only succeed the first time the node label is set, which should occur in ImmutableTree.__init__(). """ if hasattr(self, '_label'): raise ValueError('%s may not be modified' % type(self).__name__) self._label = value ###################################################################### ## Parented trees ###################################################################### class AbstractParentedTree(Tree): """ An abstract base class for a ``Tree`` that automatically maintains pointers to parent nodes. These parent pointers are updated whenever any change is made to a tree's structure. Two subclasses are currently defined: - ``ParentedTree`` is used for tree structures where each subtree has at most one parent. This class should be used in cases where there is no"sharing" of subtrees. - ``MultiParentedTree`` is used for tree structures where a subtree may have zero or more parents. This class should be used in cases where subtrees may be shared. Subclassing =========== The ``AbstractParentedTree`` class redefines all operations that modify a tree's structure to call two methods, which are used by subclasses to update parent information: - ``_setparent()`` is called whenever a new child is added. - ``_delparent()`` is called whenever a child is removed. """ def __init__(self, node, children=None): super(AbstractParentedTree, self).__init__(node, children) # If children is None, the tree is read from node, and # all parents will be set during parsing. if children is not None: # Otherwise we have to set the parent of the children. # Iterate over self, and *not* children, because children # might be an iterator. for i, child in enumerate(self): if isinstance(child, Tree): self._setparent(child, i, dry_run=True) for i, child in enumerate(self): if isinstance(child, Tree): self._setparent(child, i) #//////////////////////////////////////////////////////////// # Parent management #//////////////////////////////////////////////////////////// def _setparent(self, child, index, dry_run=False): """ Update the parent pointer of ``child`` to point to ``self``. This method is only called if the type of ``child`` is ``Tree``; i.e., it is not called when adding a leaf to a tree. This method is always called before the child is actually added to the child list of ``self``. :type child: Tree :type index: int :param index: The index of ``child`` in ``self``. :raise TypeError: If ``child`` is a tree with an impropriate type. Typically, if ``child`` is a tree, then its type needs to match the type of ``self``. This prevents mixing of different tree types (single-parented, multi-parented, and non-parented). :param dry_run: If true, the don't actually set the child's parent pointer; just check for any error conditions, and raise an exception if one is found. """ raise NotImplementedError() def _delparent(self, child, index): """ Update the parent pointer of ``child`` to not point to self. This method is only called if the type of ``child`` is ``Tree``; i.e., it is not called when removing a leaf from a tree. This method is always called before the child is actually removed from the child list of ``self``. :type child: Tree :type index: int :param index: The index of ``child`` in ``self``. """ raise NotImplementedError() #//////////////////////////////////////////////////////////// # Methods that add/remove children #//////////////////////////////////////////////////////////// # Every method that adds or removes a child must make # appropriate calls to _setparent() and _delparent(). def __delitem__(self, index): # del ptree[start:stop] if isinstance(index, slice): start, stop, step = slice_bounds(self, index, allow_step=True) # Clear all the children pointers. for i in range(start, stop, step): if isinstance(self[i], Tree): self._delparent(self[i], i) # Delete the children from our child list. super(AbstractParentedTree, self).__delitem__(index) # del ptree[i] elif isinstance(index, int): if index < 0: index += len(self) if index < 0: raise IndexError('index out of range') # Clear the child's parent pointer. if isinstance(self[index], Tree): self._delparent(self[index], index) # Remove the child from our child list. super(AbstractParentedTree, self).__delitem__(index) elif isinstance(index, (list, tuple)): # del ptree[()] if len(index) == 0: raise IndexError('The tree position () may not be deleted.') # del ptree[(i,)] elif len(index) == 1: del self[index[0]] # del ptree[i1, i2, i3] else: del self[index[0]][index[1:]] else: raise TypeError("%s indices must be integers, not %s" % (type(self).__name__, type(index).__name__)) def __setitem__(self, index, value): # ptree[start:stop] = value if isinstance(index, slice): start, stop, step = slice_bounds(self, index, allow_step=True) # make a copy of value, in case it's an iterator if not isinstance(value, (list, tuple)): value = list(value) # Check for any error conditions, so we can avoid ending # up in an inconsistent state if an error does occur. for i, child in enumerate(value): if isinstance(child, Tree): self._setparent(child, start + i*step, dry_run=True) # clear the child pointers of all parents we're removing for i in range(start, stop, step): if isinstance(self[i], Tree): self._delparent(self[i], i) # set the child pointers of the new children. We do this # after clearing *all* child pointers, in case we're e.g. # reversing the elements in a tree. for i, child in enumerate(value): if isinstance(child, Tree): self._setparent(child, start + i*step) # finally, update the content of the child list itself. super(AbstractParentedTree, self).__setitem__(index, value) # ptree[i] = value elif isinstance(index, int): if index < 0: index += len(self) if index < 0: raise IndexError('index out of range') # if the value is not changing, do nothing. if value is self[index]: return # Set the new child's parent pointer. if isinstance(value, Tree): self._setparent(value, index) # Remove the old child's parent pointer if isinstance(self[index], Tree): self._delparent(self[index], index) # Update our child list. super(AbstractParentedTree, self).__setitem__(index, value) elif isinstance(index, (list, tuple)): # ptree[()] = value if len(index) == 0: raise IndexError('The tree position () may not be assigned to.') # ptree[(i,)] = value elif len(index) == 1: self[index[0]] = value # ptree[i1, i2, i3] = value else: self[index[0]][index[1:]] = value else: raise TypeError("%s indices must be integers, not %s" % (type(self).__name__, type(index).__name__)) def append(self, child): if isinstance(child, Tree): self._setparent(child, len(self)) super(AbstractParentedTree, self).append(child) def extend(self, children): for child in children: if isinstance(child, Tree): self._setparent(child, len(self)) super(AbstractParentedTree, self).append(child) def insert(self, index, child): # Handle negative indexes. Note that if index < -len(self), # we do *not* raise an IndexError, unlike __getitem__. This # is done for consistency with list.__getitem__ and list.index. if index < 0: index += len(self) if index < 0: index = 0 # Set the child's parent, and update our child list. if isinstance(child, Tree): self._setparent(child, index) super(AbstractParentedTree, self).insert(index, child) def pop(self, index=-1): if index < 0: index += len(self) if index < 0: raise IndexError('index out of range') if isinstance(self[index], Tree): self._delparent(self[index], index) return super(AbstractParentedTree, self).pop(index) # n.b.: like `list`, this is done by equality, not identity! # To remove a specific child, use del ptree[i]. def remove(self, child): index = self.index(child) if isinstance(self[index], Tree): self._delparent(self[index], index) super(AbstractParentedTree, self).remove(child) # We need to implement __getslice__ and friends, even though # they're deprecated, because otherwise list.__getslice__ will get # called (since we're subclassing from list). Just delegate to # __getitem__ etc., but use max(0, start) and max(0, stop) because # because negative indices are already handled *before* # __getslice__ is called; and we don't want to double-count them. if hasattr(list, '__getslice__'): def __getslice__(self, start, stop): return self.__getitem__(slice(max(0, start), max(0, stop))) def __delslice__(self, start, stop): return self.__delitem__(slice(max(0, start), max(0, stop))) def __setslice__(self, start, stop, value): return self.__setitem__(slice(max(0, start), max(0, stop)), value) class ParentedTree(AbstractParentedTree): """ A ``Tree`` that automatically maintains parent pointers for single-parented trees. The following are methods for querying the structure of a parented tree: ``parent``, ``parent_index``, ``left_sibling``, ``right_sibling``, ``root``, ``treeposition``. Each ``ParentedTree`` may have at most one parent. In particular, subtrees may not be shared. Any attempt to reuse a single ``ParentedTree`` as a child of more than one parent (or as multiple children of the same parent) will cause a ``ValueError`` exception to be raised. ``ParentedTrees`` should never be used in the same tree as ``Trees`` or ``MultiParentedTrees``. Mixing tree implementations may result in incorrect parent pointers and in ``TypeError`` exceptions. """ def __init__(self, node, children=None): self._parent = None """The parent of this Tree, or None if it has no parent.""" super(ParentedTree, self).__init__(node, children) if children is None: # If children is None, the tree is read from node. # After parsing, the parent of the immediate children # will point to an intermediate tree, not self. # We fix this by brute force: for i, child in enumerate(self): if isinstance(child, Tree): child._parent = None self._setparent(child, i) def _frozen_class(self): return ImmutableParentedTree #///////////////////////////////////////////////////////////////// # Methods #///////////////////////////////////////////////////////////////// def parent(self): """The parent of this tree, or None if it has no parent.""" return self._parent def parent_index(self): """ The index of this tree in its parent. I.e., ``ptree.parent()[ptree.parent_index()] is ptree``. Note that ``ptree.parent_index()`` is not necessarily equal to ``ptree.parent.index(ptree)``, since the ``index()`` method returns the first child that is equal to its argument. """ if self._parent is None: return None for i, child in enumerate(self._parent): if child is self: return i assert False, 'expected to find self in self._parent!' def left_sibling(self): """The left sibling of this tree, or None if it has none.""" parent_index = self.parent_index() if self._parent and parent_index > 0: return self._parent[parent_index-1] return None # no left sibling def right_sibling(self): """The right sibling of this tree, or None if it has none.""" parent_index = self.parent_index() if self._parent and parent_index < (len(self._parent)-1): return self._parent[parent_index+1] return None # no right sibling def root(self): """ The root of this tree. I.e., the unique ancestor of this tree whose parent is None. If ``ptree.parent()`` is None, then ``ptree`` is its own root. """ root = self while root.parent() is not None: root = root.parent() return root def treeposition(self): """ The tree position of this tree, relative to the root of the tree. I.e., ``ptree.root[ptree.treeposition] is ptree``. """ if self.parent() is None: return () else: return self.parent().treeposition() + (self.parent_index(),) #///////////////////////////////////////////////////////////////// # Parent Management #///////////////////////////////////////////////////////////////// def _delparent(self, child, index): # Sanity checks assert isinstance(child, ParentedTree) assert self[index] is child assert child._parent is self # Delete child's parent pointer. child._parent = None def _setparent(self, child, index, dry_run=False): # If the child's type is incorrect, then complain. if not isinstance(child, ParentedTree): raise TypeError('Can not insert a non-ParentedTree '+ 'into a ParentedTree') # If child already has a parent, then complain. if child._parent is not None: raise ValueError('Can not insert a subtree that already ' 'has a parent.') # Set child's parent pointer & index. if not dry_run: child._parent = self class MultiParentedTree(AbstractParentedTree): """ A ``Tree`` that automatically maintains parent pointers for multi-parented trees. The following are methods for querying the structure of a multi-parented tree: ``parents()``, ``parent_indices()``, ``left_siblings()``, ``right_siblings()``, ``roots``, ``treepositions``. Each ``MultiParentedTree`` may have zero or more parents. In particular, subtrees may be shared. If a single ``MultiParentedTree`` is used as multiple children of the same parent, then that parent will appear multiple times in its ``parents()`` method. ``MultiParentedTrees`` should never be used in the same tree as ``Trees`` or ``ParentedTrees``. Mixing tree implementations may result in incorrect parent pointers and in ``TypeError`` exceptions. """ def __init__(self, node, children=None): self._parents = [] """A list of this tree's parents. This list should not contain duplicates, even if a parent contains this tree multiple times.""" super(MultiParentedTree, self).__init__(node, children) if children is None: # If children is None, the tree is read from node. # After parsing, the parent(s) of the immediate children # will point to an intermediate tree, not self. # We fix this by brute force: for i, child in enumerate(self): if isinstance(child, Tree): child._parents = [] self._setparent(child, i) def _frozen_class(self): return ImmutableMultiParentedTree #///////////////////////////////////////////////////////////////// # Methods #///////////////////////////////////////////////////////////////// def parents(self): """ The set of parents of this tree. If this tree has no parents, then ``parents`` is the empty set. To check if a tree is used as multiple children of the same parent, use the ``parent_indices()`` method. :type: list(MultiParentedTree) """ return list(self._parents) def left_siblings(self): """ A list of all left siblings of this tree, in any of its parent trees. A tree may be its own left sibling if it is used as multiple contiguous children of the same parent. A tree may appear multiple times in this list if it is the left sibling of this tree with respect to multiple parents. :type: list(MultiParentedTree) """ return [parent[index-1] for (parent, index) in self._get_parent_indices() if index > 0] def right_siblings(self): """ A list of all right siblings of this tree, in any of its parent trees. A tree may be its own right sibling if it is used as multiple contiguous children of the same parent. A tree may appear multiple times in this list if it is the right sibling of this tree with respect to multiple parents. :type: list(MultiParentedTree) """ return [parent[index+1] for (parent, index) in self._get_parent_indices() if index < (len(parent)-1)] def _get_parent_indices(self): return [(parent, index) for parent in self._parents for index, child in enumerate(parent) if child is self] def roots(self): """ The set of all roots of this tree. This set is formed by tracing all possible parent paths until trees with no parents are found. :type: list(MultiParentedTree) """ return list(self._get_roots_helper({}).values()) def _get_roots_helper(self, result): if self._parents: for parent in self._parents: parent._get_roots_helper(result) else: result[id(self)] = self return result def parent_indices(self, parent): """ Return a list of the indices where this tree occurs as a child of ``parent``. If this child does not occur as a child of ``parent``, then the empty list is returned. The following is always true:: for parent_index in ptree.parent_indices(parent): parent[parent_index] is ptree """ if parent not in self._parents: return [] else: return [index for (index, child) in enumerate(parent) if child is self] def treepositions(self, root): """ Return a list of all tree positions that can be used to reach this multi-parented tree starting from ``root``. I.e., the following is always true:: for treepos in ptree.treepositions(root): root[treepos] is ptree """ if self is root: return [()] else: return [treepos+(index,) for parent in self._parents for treepos in parent.treepositions(root) for (index, child) in enumerate(parent) if child is self] #///////////////////////////////////////////////////////////////// # Parent Management #///////////////////////////////////////////////////////////////// def _delparent(self, child, index): # Sanity checks assert isinstance(child, MultiParentedTree) assert self[index] is child assert len([p for p in child._parents if p is self]) == 1 # If the only copy of child in self is at index, then delete # self from child's parent list. for i, c in enumerate(self): if c is child and i != index: break else: child._parents.remove(self) def _setparent(self, child, index, dry_run=False): # If the child's type is incorrect, then complain. if not isinstance(child, MultiParentedTree): raise TypeError('Can not insert a non-MultiParentedTree '+ 'into a MultiParentedTree') # Add self as a parent pointer if it's not already listed. if not dry_run: for parent in child._parents: if parent is self: break else: child._parents.append(self) class ImmutableParentedTree(ImmutableTree, ParentedTree): pass class ImmutableMultiParentedTree(ImmutableTree, MultiParentedTree): pass ###################################################################### ## Probabilistic trees ###################################################################### @python_2_unicode_compatible class ProbabilisticTree(Tree, ProbabilisticMixIn): def __init__(self, node, children=None, **prob_kwargs): Tree.__init__(self, node, children) ProbabilisticMixIn.__init__(self, **prob_kwargs) # We have to patch up these methods to make them work right: def _frozen_class(self): return ImmutableProbabilisticTree def __repr__(self): return '%s (p=%r)' % (Tree.unicode_repr(self), self.prob()) def __str__(self): return '%s (p=%.6g)' % (self.pformat(margin=60), self.prob()) def copy(self, deep=False): if not deep: return type(self)(self._label, self, prob=self.prob()) else: return type(self).convert(self) @classmethod def convert(cls, val): if isinstance(val, Tree): children = [cls.convert(child) for child in val] if isinstance(val, ProbabilisticMixIn): return cls(val._label, children, prob=val.prob()) else: return cls(val._label, children, prob=1.0) else: return val def __eq__(self, other): return (self.__class__ is other.__class__ and (self._label, list(self), self.prob()) == (other._label, list(other), other.prob())) def __lt__(self, other): if not isinstance(other, Tree): raise_unorderable_types("<", self, other) if self.__class__ is other.__class__: return ((self._label, list(self), self.prob()) < (other._label, list(other), other.prob())) else: return self.__class__.__name__ < other.__class__.__name__ @python_2_unicode_compatible class ImmutableProbabilisticTree(ImmutableTree, ProbabilisticMixIn): def __init__(self, node, children=None, **prob_kwargs): ImmutableTree.__init__(self, node, children) ProbabilisticMixIn.__init__(self, **prob_kwargs) self._hash = hash((self._label, tuple(self), self.prob())) # We have to patch up these methods to make them work right: def _frozen_class(self): return ImmutableProbabilisticTree def __repr__(self): return '%s [%s]' % (Tree.unicode_repr(self), self.prob()) def __str__(self): return '%s [%s]' % (self.pformat(margin=60), self.prob()) def copy(self, deep=False): if not deep: return type(self)(self._label, self, prob=self.prob()) else: return type(self).convert(self) @classmethod def convert(cls, val): if isinstance(val, Tree): children = [cls.convert(child) for child in val] if isinstance(val, ProbabilisticMixIn): return cls(val._label, children, prob=val.prob()) else: return cls(val._label, children, prob=1.0) else: return val def _child_names(tree): names = [] for child in tree: if isinstance(child, Tree): names.append(Nonterminal(child._label)) else: names.append(child) return names ###################################################################### ## Parsing ###################################################################### def bracket_parse(s): """ Use Tree.read(s, remove_empty_top_bracketing=True) instead. """ raise NameError("Use Tree.read(s, remove_empty_top_bracketing=True) instead.") def sinica_parse(s): """ Parse a Sinica Treebank string and return a tree. Trees are represented as nested brackettings, as shown in the following example (X represents a Chinese character): S(goal:NP(Head:Nep:XX)|theme:NP(Head:Nhaa:X)|quantity:Dab:X|Head:VL2:X)#0(PERIODCATEGORY) :return: A tree corresponding to the string representation. :rtype: Tree :param s: The string to be converted :type s: str """ tokens = re.split(r'([()| ])', s) for i in range(len(tokens)): if tokens[i] == '(': tokens[i-1], tokens[i] = tokens[i], tokens[i-1] # pull nonterminal inside parens elif ':' in tokens[i]: fields = tokens[i].split(':') if len(fields) == 2: # non-terminal tokens[i] = fields[1] else: tokens[i] = "(" + fields[-2] + " " + fields[-1] + ")" elif tokens[i] == '|': tokens[i] = '' treebank_string = " ".join(tokens) return Tree.fromstring(treebank_string, remove_empty_top_bracketing=True) # s = re.sub(r'^#[^\s]*\s', '', s) # remove leading identifier # s = re.sub(r'\w+:', '', s) # remove role tags # return s ###################################################################### ## Demonstration ###################################################################### def demo(): """ A demonstration showing how Trees and Trees can be used. This demonstration creates a Tree, and loads a Tree from the Treebank corpus, and shows the results of calling several of their methods. """ from nltk import Tree, ProbabilisticTree # Demonstrate tree parsing. s = '(S (NP (DT the) (NN cat)) (VP (VBD ate) (NP (DT a) (NN cookie))))' t = Tree.fromstring(s) print("Convert bracketed string into tree:") print(t) print(t.__repr__()) print("Display tree properties:") print(t.label()) # tree's constituent type print(t[0]) # tree's first child print(t[1]) # tree's second child print(t.height()) print(t.leaves()) print(t[1]) print(t[1,1]) print(t[1,1,0]) # Demonstrate tree modification. the_cat = t[0] the_cat.insert(1, Tree.fromstring('(JJ big)')) print("Tree modification:") print(t) t[1,1,1] = Tree.fromstring('(NN cake)') print(t) print() # Tree transforms print("Collapse unary:") t.collapse_unary() print(t) print("Chomsky normal form:") t.chomsky_normal_form() print(t) print() # Demonstrate probabilistic trees. pt = ProbabilisticTree('x', ['y', 'z'], prob=0.5) print("Probabilistic Tree:") print(pt) print() # Demonstrate parsing of treebank output format. t = Tree.fromstring(t.pformat()) print("Convert tree to bracketed string and back again:") print(t) print() # Demonstrate LaTeX output print("LaTeX output:") print(t.pformat_latex_qtree()) print() # Demonstrate Productions print("Production output:") print(t.productions()) print() # Demonstrate tree nodes containing objects other than strings t.set_label(('test', 3)) print(t) __all__ = ['ImmutableProbabilisticTree', 'ImmutableTree', 'ProbabilisticMixIn', 'ProbabilisticTree', 'Tree', 'bracket_parse', 'sinica_parse', 'ParentedTree', 'MultiParentedTree', 'ImmutableParentedTree', 'ImmutableMultiParentedTree']
mit
moddevices/mod-ui
modtools/utils.py
1
29240
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from ctypes import * import os # ------------------------------------------------------------------------------------------------------------ # Convert a ctypes c_char_p into a python string def charPtrToString(charPtr): if not charPtr: return "" if isinstance(charPtr, str): return charPtr return charPtr.decode("utf-8", errors="ignore") # ------------------------------------------------------------------------------------------------------------ # Convert a ctypes POINTER(c_char_p) into a python string list def charPtrPtrToStringList(charPtrPtr): if not charPtrPtr: return [] i = 0 charPtr = charPtrPtr[0] strList = [] while charPtr: strList.append(charPtr.decode("utf-8", errors="ignore")) i += 1 charPtr = charPtrPtr[i] return strList # ------------------------------------------------------------------------------------------------------------ # Convert a ctypes POINTER(c_<num>) into a python number list def numPtrToList(numPtr): if not numPtr: return [] i = 0 num = numPtr[0] #.value numList = [] while num not in (0, 0.0): numList.append(num) i += 1 num = numPtr[i] #.value return numList # ------------------------------------------------------------------------------------------------------------ def structPtrToList(structPtr): if not structPtr: return [] i = 0 ret = [] struct = structPtr[0] while struct.valid: ret.append(structToDict(struct)) i += 1 struct = structPtr[i] return ret def structPtrPtrToList(structPtr): if not structPtr: return [] i = 0 ret = [] struct = structPtr[0] while struct: ret.append(structToDict(struct.contents)) i += 1 struct = structPtr[i] return ret # ------------------------------------------------------------------------------------------------------------ # Convert a ctypes value into a python one c_int_types = (c_int, c_int8, c_int16, c_int32, c_int64, c_uint, c_uint8, c_uint16, c_uint32, c_uint64, c_long, c_longlong) c_float_types = (c_float, c_double, c_longdouble) c_intp_types = tuple(POINTER(i) for i in c_int_types) c_floatp_types = tuple(POINTER(i) for i in c_float_types) c_struct_types = () # redefined below c_structp_types = () # redefined below c_structpp_types = () # redefined below c_union_types = () def toPythonType(value, attr): #if value is None: #return "" if isinstance(value, (bool, int, float)): return value if isinstance(value, bytes): return charPtrToString(value) if isinstance(value, c_intp_types) or isinstance(value, c_floatp_types): return numPtrToList(value) if isinstance(value, POINTER(c_char_p)): return charPtrPtrToStringList(value) if isinstance(value, c_struct_types): return structToDict(value) if isinstance(value, c_structp_types): return structPtrToList(value) if isinstance(value, c_structpp_types): return structPtrPtrToList(value) if isinstance(value, c_union_types): return unionToDict(value) print("..............", attr, ".....................", value, ":", type(value)) return value # ------------------------------------------------------------------------------------------------------------ # Convert a ctypes struct into a python dict def structToDict(struct): return dict((attr, toPythonType(getattr(struct, attr), attr)) for attr, value in struct._fields_) def unionToDict(struct): if isinstance(struct, PluginParameterRanges): if struct.type == b'f': return structToDict(struct.f) if struct.type == b'l': return structToDict(struct.l) if struct.type == b's': return { 'minimum': "", 'maximum': "", 'default': charPtrToString(struct.s), } return None # ------------------------------------------------------------------------------------------------------------ tryPath1 = os.path.join(os.path.dirname(__file__), "libmod_utils.so") tryPath2 = os.path.join(os.path.dirname(__file__), "..", "utils", "libmod_utils.so") if os.path.exists(tryPath1): utils = cdll.LoadLibrary(tryPath1) else: utils = cdll.LoadLibrary(tryPath2) class PluginAuthor(Structure): _fields_ = [ ("name", c_char_p), ("homepage", c_char_p), ("email", c_char_p), ] class PluginGUIPort(Structure): _fields_ = [ ("valid", c_bool), ("index", c_uint), ("name", c_char_p), ("symbol", c_char_p), ] class PluginGUI(Structure): _fields_ = [ ("resourcesDirectory", c_char_p), ("iconTemplate", c_char_p), ("settingsTemplate", c_char_p), ("javascript", c_char_p), ("stylesheet", c_char_p), ("screenshot", c_char_p), ("thumbnail", c_char_p), ("brand", c_char_p), ("label", c_char_p), ("model", c_char_p), ("panel", c_char_p), ("color", c_char_p), ("knob", c_char_p), ("ports", POINTER(PluginGUIPort)), ("monitoredOutputs", POINTER(c_char_p)), ] class PluginGUI_Mini(Structure): _fields_ = [ ("resourcesDirectory", c_char_p), ("screenshot", c_char_p), ("thumbnail", c_char_p), ] class PluginPortRanges(Structure): _fields_ = [ ("minimum", c_float), ("maximum", c_float), ("default", c_float), ] class PluginPortUnits(Structure): _fields_ = [ ("label", c_char_p), ("render", c_char_p), ("symbol", c_char_p), ("_custom", c_bool), # internal, do not use ] class PluginPortScalePoint(Structure): _fields_ = [ ("valid", c_bool), ("value", c_float), ("label", c_char_p), ] class PluginPort(Structure): _fields_ = [ ("valid", c_bool), ("index", c_uint), ("name", c_char_p), ("symbol", c_char_p), ("ranges", PluginPortRanges), ("units", PluginPortUnits), ("comment", c_char_p), ("designation", c_char_p), ("properties", POINTER(c_char_p)), ("rangeSteps", c_int), ("scalePoints", POINTER(PluginPortScalePoint)), ("shortName", c_char_p), ] class PluginPortsI(Structure): _fields_ = [ ("input", POINTER(PluginPort)), ("output", POINTER(PluginPort)), ] class PluginPorts(Structure): _fields_ = [ ("audio", PluginPortsI), ("control", PluginPortsI), ("cv", PluginPortsI), ("midi", PluginPortsI), ] class PluginLongParameterRanges(Structure): _fields_ = [ ("minimum", c_int64), ("maximum", c_int64), ("default", c_int64), ] class _PluginParameterRangesU(Union): _fields_ = [ ("f", PluginPortRanges), ("l", PluginLongParameterRanges), ("s", c_char_p), ] class PluginParameterRanges(Structure): _anonymous_ = ("u",) _fields_ = [ ("type", c_char), ("u", _PluginParameterRangesU), ] class PluginParameter(Structure): _fields_ = [ ("valid", c_bool), ("readable", c_bool), ("writable", c_bool), ("uri", c_char_p), ("label", c_char_p), ("type", c_char_p), ("ranges", PluginParameterRanges), ("units", PluginPortUnits), ("comment", c_char_p), ("shortName", c_char_p), ("fileTypes", POINTER(c_char_p)), ("supportedExtensions", POINTER(c_char_p)), ] class PluginPreset(Structure): _fields_ = [ ("valid", c_bool), ("uri", c_char_p), ("label", c_char_p), ("path", c_char_p), ] class PluginInfo(Structure): _fields_ = [ ("valid", c_bool), ("uri", c_char_p), ("name", c_char_p), ("binary", c_char_p), ("brand", c_char_p), ("label", c_char_p), ("license", c_char_p), ("comment", c_char_p), ("buildEnvironment", c_char_p), ("category", POINTER(c_char_p)), ("microVersion", c_int), ("minorVersion", c_int), ("release", c_int), ("builder", c_int), ("licensed", c_int), ("version", c_char_p), ("stability", c_char_p), ("author", PluginAuthor), ("bundles", POINTER(c_char_p)), ("gui", PluginGUI), ("ports", PluginPorts), ("parameters", POINTER(PluginParameter)), ("presets", POINTER(PluginPreset)), ] # a subset of PluginInfo class NonCachedPluginInfo(Structure): _fields_ = [ ("licensed", c_int), ("presets", POINTER(PluginPreset)), ] class PluginInfo_Mini(Structure): _fields_ = [ ("valid", c_bool), ("uri", c_char_p), ("name", c_char_p), ("brand", c_char_p), ("label", c_char_p), ("comment", c_char_p), ("buildEnvironment", c_char_p), ("category", POINTER(c_char_p)), ("microVersion", c_int), ("minorVersion", c_int), ("release", c_int), ("builder", c_int), ("licensed", c_int), ("gui", PluginGUI_Mini), ] class PluginInfo_Essentials(Structure): _fields_ = [ ("controlInputs", POINTER(PluginPort)), ("monitoredOutputs", POINTER(c_char_p)), ("parameters", POINTER(PluginParameter)), ("buildEnvironment", c_char_p), ("microVersion", c_int), ("minorVersion", c_int), ("release", c_int), ("builder", c_int), ] class PedalboardMidiControl(Structure): _fields_ = [ ("channel", c_int8), ("control", c_uint8), # ranges added in v1.2, flag needed for old format compatibility ("hasRanges", c_bool), ("minimum", c_float), ("maximum", c_float), ] class PedalboardPluginPort(Structure): _fields_ = [ ("valid", c_bool), ("symbol", c_char_p), ("value", c_float), ("midiCC", PedalboardMidiControl), ] class PedalboardPlugin(Structure): _fields_ = [ ("valid", c_bool), ("bypassed", c_bool), ("instanceNumber", c_int), ("instance", c_char_p), ("uri", c_char_p), ("bypassCC", PedalboardMidiControl), ("x", c_float), ("y", c_float), ("ports", POINTER(PedalboardPluginPort)), ("preset", c_char_p), ] class PedalboardConnection(Structure): _fields_ = [ ("valid", c_bool), ("source", c_char_p), ("target", c_char_p), ] class PedalboardHardwareMidiPort(Structure): _fields_ = [ ("valid", c_bool), ("symbol", c_char_p), ("name", c_char_p), ] class PedalboardHardware(Structure): _fields_ = [ ("audio_ins", c_uint), ("audio_outs", c_uint), ("cv_ins", c_uint), ("cv_outs", c_uint), ("midi_ins", POINTER(PedalboardHardwareMidiPort)), ("midi_outs", POINTER(PedalboardHardwareMidiPort)), ("serial_midi_in", c_bool), ("serial_midi_out", c_bool), ("midi_merger_out", c_bool), ("midi_broadcaster_in", c_bool), ] kPedalboardTimeAvailableBPB = 0x1 kPedalboardTimeAvailableBPM = 0x2 kPedalboardTimeAvailableRolling = 0x4 class PedalboardTimeInfo(Structure): _fields_ = [ ("available", c_uint), ("bpb", c_float), ("bpbCC", PedalboardMidiControl), ("bpm", c_float), ("bpmCC", PedalboardMidiControl), ("rolling", c_bool), ("rollingCC", PedalboardMidiControl), ] class PedalboardInfo(Structure): _fields_ = [ ("title", c_char_p), ("width", c_int), ("height", c_int), ("midi_separated_mode", c_bool), ("midi_loopback", c_bool), ("plugins", POINTER(PedalboardPlugin)), ("connections", POINTER(PedalboardConnection)), ("hardware", PedalboardHardware), ("timeInfo", PedalboardTimeInfo), ("version", c_uint), ] class PedalboardInfo_Mini(Structure): _fields_ = [ ("valid", c_bool), ("broken", c_bool), ("uri", c_char_p), ("bundle", c_char_p), ("title", c_char_p), ("version", c_uint), ] class StatePortValue(Structure): _fields_ = [ ("valid", c_bool), ("symbol", c_char_p), ("value", c_float), ] class PedalboardPluginValues(Structure): _fields_ = [ ("valid", c_bool), ("bypassed", c_bool), ("instance", c_char_p), ("preset", c_char_p), ("ports", POINTER(StatePortValue)), ] class JackData(Structure): _fields_ = [ ("cpuLoad", c_float), ("xruns", c_uint), ("rolling", c_bool), ("bpb", c_double), ("bpm", c_double), ] JackBufSizeChanged = CFUNCTYPE(None, c_uint) JackPortAppeared = CFUNCTYPE(None, c_char_p, c_bool) JackPortDeleted = CFUNCTYPE(None, c_char_p) TrueBypassStateChanged = CFUNCTYPE(None, c_bool, c_bool) CvExpInputModeChanged = CFUNCTYPE(None, c_bool) c_struct_types = (PluginAuthor, PluginGUI, PluginGUI_Mini, PluginPortRanges, PluginPortUnits, PluginPortsI, PluginPorts, PluginLongParameterRanges, PedalboardMidiControl, PedalboardHardware, PedalboardTimeInfo) c_structp_types = (POINTER(PluginGUIPort), POINTER(PluginPortScalePoint), POINTER(PluginPort), POINTER(PluginParameter), POINTER(PluginPreset), POINTER(PedalboardPlugin), POINTER(PedalboardConnection), POINTER(PedalboardPluginPort), POINTER(PedalboardHardwareMidiPort), POINTER(StatePortValue)) c_structpp_types = (POINTER(POINTER(PluginInfo_Mini)), POINTER(POINTER(PedalboardInfo_Mini))) c_union_types = (PluginParameterRanges,) utils.init.argtypes = None utils.init.restype = None utils.cleanup.argtypes = None utils.cleanup.restype = None utils.is_bundle_loaded.argtypes = [c_char_p] utils.is_bundle_loaded.restype = c_bool utils.add_bundle_to_lilv_world.argtypes = [c_char_p] utils.add_bundle_to_lilv_world.restype = POINTER(c_char_p) utils.remove_bundle_from_lilv_world.argtypes = [c_char_p] utils.remove_bundle_from_lilv_world.restype = POINTER(c_char_p) utils.get_plugin_list.argtypes = None utils.get_plugin_list.restype = POINTER(c_char_p) utils.get_all_plugins.argtypes = None utils.get_all_plugins.restype = POINTER(POINTER(PluginInfo_Mini)) utils.get_plugin_info.argtypes = [c_char_p] utils.get_plugin_info.restype = POINTER(PluginInfo) utils.get_non_cached_plugin_info.argtypes = [c_char_p] utils.get_non_cached_plugin_info.restype = POINTER(NonCachedPluginInfo) utils.get_plugin_gui.argtypes = [c_char_p] utils.get_plugin_gui.restype = POINTER(PluginGUI) utils.get_plugin_gui_mini.argtypes = [c_char_p] utils.get_plugin_gui_mini.restype = POINTER(PluginGUI_Mini) utils.get_plugin_control_inputs.argtypes = [c_char_p] utils.get_plugin_control_inputs.restype = POINTER(PluginPort) utils.get_plugin_info_essentials.argtypes = [c_char_p] utils.get_plugin_info_essentials.restype = POINTER(PluginInfo_Essentials) utils.is_plugin_preset_valid.argtypes = [c_char_p, c_char_p] utils.is_plugin_preset_valid.restype = c_bool utils.rescan_plugin_presets.argtypes = [c_char_p] utils.rescan_plugin_presets.restype = None utils.get_all_pedalboards.argtypes = None utils.get_all_pedalboards.restype = POINTER(POINTER(PedalboardInfo_Mini)) utils.get_broken_pedalboards.argtypes = None utils.get_broken_pedalboards.restype = POINTER(c_char_p) utils.get_pedalboard_info.argtypes = [c_char_p] utils.get_pedalboard_info.restype = POINTER(PedalboardInfo) utils.get_pedalboard_size.argtypes = [c_char_p] utils.get_pedalboard_size.restype = POINTER(c_int) utils.get_pedalboard_plugin_values.argtypes = [c_char_p] utils.get_pedalboard_plugin_values.restype = POINTER(PedalboardPluginValues) utils.get_state_port_values.argtypes = [c_char_p] utils.get_state_port_values.restype = POINTER(StatePortValue) utils.list_plugins_in_bundle.argtypes = [c_char_p] utils.list_plugins_in_bundle.restype = POINTER(c_char_p) utils.file_uri_parse.argtypes = [c_char_p] utils.file_uri_parse.restype = c_char_p utils.init_jack.argtypes = None utils.init_jack.restype = c_bool utils.close_jack.argtypes = None utils.close_jack.restype = None utils.get_jack_data.argtypes = [c_bool] utils.get_jack_data.restype = POINTER(JackData) utils.get_jack_buffer_size.argtypes = None utils.get_jack_buffer_size.restype = c_uint utils.set_jack_buffer_size.argtypes = [c_uint] utils.set_jack_buffer_size.restype = c_uint utils.get_jack_sample_rate.argtypes = None utils.get_jack_sample_rate.restype = c_float utils.get_jack_port_alias.argtypes = [c_char_p] utils.get_jack_port_alias.restype = c_char_p utils.has_midi_beat_clock_sender_port.argtypes = None utils.has_midi_beat_clock_sender_port.restype = c_bool utils.has_serial_midi_input_port.argtypes = None utils.has_serial_midi_input_port.restype = c_bool utils.has_serial_midi_output_port.argtypes = None utils.has_serial_midi_output_port.restype = c_bool utils.has_midi_merger_output_port.argtypes = None utils.has_midi_merger_output_port.restype = c_bool utils.has_midi_broadcaster_input_port.argtypes = None utils.has_midi_broadcaster_input_port.restype = c_bool utils.get_jack_hardware_ports.argtypes = [c_bool, c_bool] utils.get_jack_hardware_ports.restype = POINTER(c_char_p) utils.connect_jack_ports.argtypes = [c_char_p, c_char_p] utils.connect_jack_ports.restype = c_bool utils.connect_jack_midi_output_ports.argtypes = [c_char_p] utils.connect_jack_midi_output_ports.restype = c_bool utils.disconnect_jack_ports.argtypes = [c_char_p, c_char_p] utils.disconnect_jack_ports.restype = c_bool utils.disconnect_all_jack_ports.argtypes = [c_char_p] utils.disconnect_all_jack_ports.restype = c_bool utils.reset_xruns.argtypes = None utils.reset_xruns.restype = None utils.init_bypass.argtypes = None utils.init_bypass.restype = None utils.get_truebypass_value.argtypes = [c_bool] utils.get_truebypass_value.restype = c_bool utils.set_truebypass_value.argtypes = [c_bool, c_bool] utils.set_truebypass_value.restype = c_bool utils.get_master_volume.argtypes = [c_bool] utils.get_master_volume.restype = c_float utils.set_util_callbacks.argtypes = [JackBufSizeChanged, JackPortAppeared, JackPortDeleted, TrueBypassStateChanged] utils.set_util_callbacks.restype = None utils.set_extra_util_callbacks.argtypes = [CvExpInputModeChanged] utils.set_extra_util_callbacks.restype = None # ------------------------------------------------------------------------------------------------------------ # initialize def init(): utils.init() # cleanup, cannot be used afterwards def cleanup(): utils.cleanup() # ------------------------------------------------------------------------------------------------------------ # check if a bundle is loaded in our lilv world def is_bundle_loaded(bundlepath): return bool(utils.is_bundle_loaded(bundlepath.encode("utf-8"))) # add a bundle to our lilv world # returns uri list of added plugins def add_bundle_to_lilv_world(bundlepath): return charPtrPtrToStringList(utils.add_bundle_to_lilv_world(bundlepath.encode("utf-8"))) # remove a bundle to our lilv world # returns uri list of removed plugins def remove_bundle_from_lilv_world(bundlepath): return charPtrPtrToStringList(utils.remove_bundle_from_lilv_world(bundlepath.encode("utf-8"))) # ------------------------------------------------------------------------------------------------------------ # get all available plugins # this triggers short scanning of all plugins def get_plugin_list(): return charPtrPtrToStringList(utils.get_plugin_list()) # get all available plugins # this triggers short scanning of all plugins def get_all_plugins(): return structPtrPtrToList(utils.get_all_plugins()) # get a specific plugin # NOTE: may throw def get_plugin_info(uri): info = utils.get_plugin_info(uri.encode("utf-8")) if not info: raise Exception return structToDict(info.contents) # get a specific plugin (non-cached specific info) # NOTE: may throw def get_non_cached_plugin_info(uri): info = utils.get_non_cached_plugin_info(uri.encode("utf-8")) if not info: raise Exception return structToDict(info.contents) # get a specific plugin's modgui # NOTE: may throw def get_plugin_gui(uri): info = utils.get_plugin_gui(uri.encode("utf-8")) if not info: raise Exception return structToDict(info.contents) # get a specific plugin's modgui (mini) # NOTE: may throw def get_plugin_gui_mini(uri): info = utils.get_plugin_gui_mini(uri.encode("utf-8")) if not info: raise Exception return structToDict(info.contents) def get_plugin_control_inputs(uri): return structPtrToList(utils.get_plugin_control_inputs(uri.encode("utf-8"))) # get essential plugin info for host control (control inputs, monitored outputs, parameters and build environment) def get_plugin_info_essentials(uri): info = utils.get_plugin_info_essentials(uri.encode("utf-8")) if not info: return { 'error': True, 'controlInputs': [], 'monitoredOutputs': [], 'parameters': [], 'buildEnvironment': '', 'microVersion': 0, 'minorVersion': 0, 'release': 0, 'builder': 0, } return structToDict(info.contents) # check if a plugin preset uri is valid (must exist) def is_plugin_preset_valid(plugin, preset): return bool(utils.is_plugin_preset_valid(plugin.encode("utf-8"), preset.encode("utf-8"))) # trigger a preset rescan for a plugin the next time it's loaded def rescan_plugin_presets(uri): utils.rescan_plugin_presets(uri.encode("utf-8")) # ------------------------------------------------------------------------------------------------------------ _allpedalboards = None # get all available pedalboards (ie, plugins with pedalboard type) def get_all_pedalboards(): global _allpedalboards if _allpedalboards is None: _allpedalboards = structPtrPtrToList(utils.get_all_pedalboards()) return _allpedalboards # handy function to reset our last call value def reset_get_all_pedalboards_cache(): global _allpedalboards _allpedalboards = None # handy function to update cached pedalboard version def update_cached_pedalboard_version(bundle): global _allpedalboards if _allpedalboards is None: return for pedalboard in _allpedalboards: if pedalboard['bundle'] == bundle: pedalboard['version'] += 1 return print("ERROR: update_cached_pedalboard_version() failed", bundle) # get all currently "broken" pedalboards (ie, pedalboards which contain unavailable plugins) def get_broken_pedalboards(): return charPtrPtrToStringList(utils.get_broken_pedalboards()) # Get a specific pedalboard # NOTE: may throw def get_pedalboard_info(bundle): info = utils.get_pedalboard_info(bundle.encode("utf-8")) if not info: raise Exception return structToDict(info.contents) # Get the size of a specific pedalboard # Returns a 2-size array with width and height # NOTE: may throw def get_pedalboard_size(bundle): size = utils.get_pedalboard_size(bundle.encode("utf-8")) if not size: raise Exception width = int(size[0]) height = int(size[1]) return (width, height) # Get plugin port values of a pedalboard def get_pedalboard_plugin_values(bundle): return structPtrToList(utils.get_pedalboard_plugin_values(bundle.encode("utf-8"))) # Get port values from a plugin state def get_state_port_values(state): values = structPtrToList(utils.get_state_port_values(state.encode("utf-8"))) return dict((v['symbol'], v['value']) for v in values) # list plugins present in a single bundle def list_plugins_in_bundle(bundle): return charPtrPtrToStringList(utils.list_plugins_in_bundle(bundle.encode("utf-8"))) # ------------------------------------------------------------------------------------------------------------ # Get the absolute directory of a file or bundle uri. def get_bundle_dirname(bundleuri): bundle = charPtrToString(utils.file_uri_parse(bundleuri)) if not bundle: raise IOError(bundleuri) if not os.path.exists(bundle): raise IOError(bundleuri) if os.path.isfile(bundle): bundle = os.path.dirname(bundle) return bundle # ------------------------------------------------------------------------------------------------------------ # jack stuff def init_jack(): return bool(utils.init_jack()) def close_jack(): utils.close_jack() def get_jack_data(withTransport): data = utils.get_jack_data(withTransport) if not data: raise Exception return { 'cpuLoad': data.contents.cpuLoad, 'xruns' : data.contents.xruns, 'rolling': data.contents.rolling, 'bpb' : data.contents.bpb, 'bpm' : data.contents.bpm } def get_jack_buffer_size(): return int(utils.get_jack_buffer_size()) def set_jack_buffer_size(size): return int(utils.set_jack_buffer_size(size)) def get_jack_sample_rate(): return float(utils.get_jack_sample_rate()) def get_jack_port_alias(portname): return charPtrToString(utils.get_jack_port_alias(portname.encode("utf-8"))) def has_midi_beat_clock_sender_port(): return bool(utils.has_midi_beat_clock_sender_port()) def has_serial_midi_input_port(): return bool(utils.has_serial_midi_input_port()) def has_serial_midi_output_port(): return bool(utils.has_serial_midi_output_port()) def has_midi_merger_output_port(): return bool(utils.has_midi_merger_output_port()) def has_midi_broadcaster_input_port(): return bool(utils.has_midi_broadcaster_input_port()) def get_jack_hardware_ports(isAudio, isOutput): return charPtrPtrToStringList(utils.get_jack_hardware_ports(isAudio, isOutput)) def connect_jack_ports(port1, port2): return bool(utils.connect_jack_ports(port1.encode("utf-8"), port2.encode("utf-8"))) def connect_jack_midi_output_ports(port): return bool(utils.connect_jack_midi_output_ports(port.encode("utf-8"))) def disconnect_jack_ports(port1, port2): return bool(utils.disconnect_jack_ports(port1.encode("utf-8"), port2.encode("utf-8"))) def disconnect_all_jack_ports(port): return bool(utils.disconnect_all_jack_ports(port.encode("utf-8"))) def reset_xruns(): utils.reset_xruns() # ------------------------------------------------------------------------------------------------------------ # alsa stuff def init_bypass(): utils.init_bypass() def get_truebypass_value(right): return bool(utils.get_truebypass_value(right)) def set_truebypass_value(right, bypassed): return bool(utils.set_truebypass_value(right, bypassed)) def get_master_volume(right): return float(utils.get_master_volume(right)) # ------------------------------------------------------------------------------------------------------------ # callbacks global bufSizeChangedCb, portAppearedCb, portDeletedCb, trueBypassChangedCb bufSizeChangedCb = portAppearedCb = portDeletedCb = trueBypassChangedCb = None def set_util_callbacks(bufSizeChanged, portAppeared, portDeleted, trueBypassChanged): global bufSizeChangedCb, portAppearedCb, portDeletedCb, trueBypassChangedCb bufSizeChangedCb = JackBufSizeChanged(bufSizeChanged) portAppearedCb = JackPortAppeared(portAppeared) portDeletedCb = JackPortDeleted(portDeleted) trueBypassChangedCb = TrueBypassStateChanged(trueBypassChanged) utils.set_util_callbacks(bufSizeChangedCb, portAppearedCb, portDeletedCb, trueBypassChangedCb) # ------------------------------------------------------------------------------------------------------------ # special case until HMI<->system comm is not in place yet global cvExpInputModeChangedCb cvExpInputModeChangedCb = None def set_extra_util_callbacks(cvExpInputModeChanged): global cvExpInputModeChangedCb cvExpInputModeChangedCb = CvExpInputModeChanged(cvExpInputModeChanged) utils.set_extra_util_callbacks(cvExpInputModeChangedCb) # ------------------------------------------------------------------------------------------------------------ # set process name def set_process_name(newname): PR_SET_NAME = 15 try: libc = cdll.LoadLibrary("libc.so.6") except: return libc.prctl.argtypes = [c_int, c_void_p, c_int, c_int, c_int] libc.prctl.restype = c_int libc.prctl(PR_SET_NAME, newname.encode("utf-8"), 0, 0, 0) # ------------------------------------------------------------------------------------------------------------
gpl-3.0
Canpio/Paddle
python/paddle/fluid/tests/unittests/test_multihead_attention.py
5
3100
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import paddle.fluid as fluid import paddle.fluid.core as core import numpy as np class TestMultiheadAttention(unittest.TestCase): def gen_random_input(self): """Generate random input data. """ # batch_size, max_sequence_length, hidden dimension self.input_shape = (3, 13, 16) self.queries = np.random.random(size=self.input_shape).astype("float32") self.keys = np.random.random(size=self.input_shape).astype("float32") def set_program(self): """Build the test program. """ queries = fluid.layers.data( name="queries", shape=self.input_shape, dtype="float32", append_batch_size=False) queries.stop_gradient = False keys = fluid.layers.data( name="keys", shape=self.input_shape, dtype="float32", append_batch_size=False) keys.stop_gradient = False contexts = fluid.nets.scaled_dot_product_attention( queries=queries, keys=keys, values=keys, num_heads=8, dropout_rate=0.) out = fluid.layers.reduce_sum(contexts, dim=None) fluid.backward.append_backward(loss=out) self.fetch_list = [contexts] def run_program(self): """Run the test program. """ places = [core.CPUPlace()] if core.is_compiled_with_cuda(): places.append(core.CUDAPlace(0)) for place in places: self.set_inputs(place) exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) output = exe.run(fluid.default_main_program(), feed=self.inputs, fetch_list=self.fetch_list, return_numpy=True) self.op_output = output def set_inputs(self, place): """Set the randomly generated data to the test program. """ self.inputs = {} queries = fluid.Tensor() queries.set(self.queries, place) keys = fluid.Tensor() keys.set(self.keys, place) self.inputs["keys"] = keys self.inputs["queries"] = queries def test_multihead_attention(self): self.gen_random_input() self.set_program() self.run_program() #fixme(caoying) add more meaningfull unittest. if __name__ == '__main__': unittest.main()
apache-2.0
alivecor/tensorflow
tensorflow/contrib/solvers/python/ops/linear_equations.py
117
4452
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Solvers for linear equations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from tensorflow.contrib.solvers.python.ops import util from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops def conjugate_gradient(operator, rhs, tol=1e-4, max_iter=20, name="conjugate_gradient"): r"""Conjugate gradient solver. Solves a linear system of equations `A*x = rhs` for selfadjoint, positive definite matrix `A` and righ-hand side vector `rhs`, using an iterative, matrix-free algorithm where the action of the matrix A is represented by `operator`. The iteration terminates when either the number of iterations exceeds `max_iter` or when the residual norm has been reduced to `tol` times its initial value, i.e. \\(||rhs - A x_k|| <= tol ||rhs||\\). Args: operator: An object representing a linear operator with attributes: - shape: Either a list of integers or a 1-D `Tensor` of type `int32` of length 2. `shape[0]` is the dimension on the domain of the operator, `shape[1]` is the dimension of the co-domain of the operator. On other words, if operator represents an N x N matrix A, `shape` must contain `[N, N]`. - dtype: The datatype of input to and output from `apply`. - apply: Callable object taking a vector `x` as input and returning a vector with the result of applying the operator to `x`, i.e. if `operator` represents matrix `A`, `apply` should return `A * x`. rhs: A rank-1 `Tensor` of shape `[N]` containing the right-hand size vector. tol: A float scalar convergence tolerance. max_iter: An integer giving the maximum number of iterations. name: A name scope for the operation. Returns: output: A namedtuple representing the final state with fields: - i: A scalar `int32` `Tensor`. Number of iterations executed. - x: A rank-1 `Tensor` of shape `[N]` containing the computed solution. - r: A rank-1 `Tensor` of shape `[M]` containing the residual vector. - p: A rank-1 `Tensor` of shape `[N]`. `A`-conjugate basis vector. - gamma: \\(||r||_2^2\\) """ # ephemeral class holding CG state. cg_state = collections.namedtuple("CGState", ["i", "x", "r", "p", "gamma"]) def stopping_criterion(i, state): return math_ops.logical_and(i < max_iter, state.gamma > tol) # TODO(rmlarsen): add preconditioning def cg_step(i, state): z = operator.apply(state.p) alpha = state.gamma / util.dot(state.p, z) x = state.x + alpha * state.p r = state.r - alpha * z gamma = util.l2norm_squared(r) beta = gamma / state.gamma p = r + beta * state.p return i + 1, cg_state(i + 1, x, r, p, gamma) with ops.name_scope(name): n = operator.shape[1:] rhs = array_ops.expand_dims(rhs, -1) gamma0 = util.l2norm_squared(rhs) tol = tol * tol * gamma0 x = array_ops.expand_dims( array_ops.zeros( n, dtype=rhs.dtype.base_dtype), -1) i = constant_op.constant(0, dtype=dtypes.int32) state = cg_state(i=i, x=x, r=rhs, p=rhs, gamma=gamma0) _, state = control_flow_ops.while_loop(stopping_criterion, cg_step, [i, state]) return cg_state( state.i, x=array_ops.squeeze(state.x), r=array_ops.squeeze(state.r), p=array_ops.squeeze(state.p), gamma=state.gamma)
apache-2.0
shengdie/lg_g2_d802_v30d_ker
tools/perf/scripts/python/sctop.py
11180
1924
# system call top # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Periodically displays system-wide system call totals, broken down by # syscall. If a [comm] arg is specified, only syscalls called by # [comm] are displayed. If an [interval] arg is specified, the display # will be refreshed every [interval] seconds. The default interval is # 3 seconds. import os, sys, thread, time sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * usage = "perf script -s sctop.py [comm] [interval]\n"; for_comm = None default_interval = 3 interval = default_interval if len(sys.argv) > 3: sys.exit(usage) if len(sys.argv) > 2: for_comm = sys.argv[1] interval = int(sys.argv[2]) elif len(sys.argv) > 1: try: interval = int(sys.argv[1]) except ValueError: for_comm = sys.argv[1] interval = default_interval syscalls = autodict() def trace_begin(): thread.start_new_thread(print_syscall_totals, (interval,)) pass def raw_syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, args): if for_comm is not None: if common_comm != for_comm: return try: syscalls[id] += 1 except TypeError: syscalls[id] = 1 def print_syscall_totals(interval): while 1: clear_term() if for_comm is not None: print "\nsyscall events for %s:\n\n" % (for_comm), else: print "\nsyscall events:\n\n", print "%-40s %10s\n" % ("event", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "----------"), for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \ reverse = True): try: print "%-40s %10d\n" % (syscall_name(id), val), except TypeError: pass syscalls.clear() time.sleep(interval)
gpl-2.0
Tatsh/youtube-dl
youtube_dl/extractor/odnoklassniki.py
12
9492
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import ( compat_etree_fromstring, compat_parse_qs, compat_urllib_parse_unquote, compat_urllib_parse_urlparse, ) from ..utils import ( ExtractorError, unified_strdate, int_or_none, qualities, unescapeHTML, urlencode_postdata, ) class OdnoklassnikiIE(InfoExtractor): _VALID_URL = r'''(?x) https?:// (?:(?:www|m|mobile)\.)? (?:odnoklassniki|ok)\.ru/ (?: video(?:embed)?/| web-api/video/moviePlayer/| live/| dk\?.*?st\.mvId= ) (?P<id>[\d-]+) ''' _TESTS = [{ # metadata in JSON 'url': 'http://ok.ru/video/20079905452', 'md5': '0b62089b479e06681abaaca9d204f152', 'info_dict': { 'id': '20079905452', 'ext': 'mp4', 'title': 'Культура меняет нас (прекрасный ролик!))', 'duration': 100, 'upload_date': '20141207', 'uploader_id': '330537914540', 'uploader': 'Виталий Добровольский', 'like_count': int, 'age_limit': 0, }, }, { # metadataUrl 'url': 'http://ok.ru/video/63567059965189-0?fromTime=5', 'md5': '6ff470ea2dd51d5d18c295a355b0b6bc', 'info_dict': { 'id': '63567059965189-0', 'ext': 'mp4', 'title': 'Девушка без комплексов ...', 'duration': 191, 'upload_date': '20150518', 'uploader_id': '534380003155', 'uploader': '☭ Андрей Мещанинов ☭', 'like_count': int, 'age_limit': 0, 'start_time': 5, }, }, { # YouTube embed (metadataUrl, provider == USER_YOUTUBE) 'url': 'http://ok.ru/video/64211978996595-1', 'md5': '2f206894ffb5dbfcce2c5a14b909eea5', 'info_dict': { 'id': 'V_VztHT5BzY', 'ext': 'mp4', 'title': 'Космическая среда от 26 августа 2015', 'description': 'md5:848eb8b85e5e3471a3a803dae1343ed0', 'duration': 440, 'upload_date': '20150826', 'uploader_id': 'tvroscosmos', 'uploader': 'Телестудия Роскосмоса', 'age_limit': 0, }, }, { # YouTube embed (metadata, provider == USER_YOUTUBE, no metadata.movie.title field) 'url': 'http://ok.ru/video/62036049272859-0', 'info_dict': { 'id': '62036049272859-0', 'ext': 'mp4', 'title': 'МУЗЫКА ДОЖДЯ .', 'description': 'md5:6f1867132bd96e33bf53eda1091e8ed0', 'upload_date': '20120106', 'uploader_id': '473534735899', 'uploader': 'МARINA D', 'age_limit': 0, }, 'params': { 'skip_download': True, }, 'skip': 'Video has not been found', }, { 'url': 'http://ok.ru/web-api/video/moviePlayer/20079905452', 'only_matching': True, }, { 'url': 'http://www.ok.ru/video/20648036891', 'only_matching': True, }, { 'url': 'http://www.ok.ru/videoembed/20648036891', 'only_matching': True, }, { 'url': 'http://m.ok.ru/video/20079905452', 'only_matching': True, }, { 'url': 'http://mobile.ok.ru/video/20079905452', 'only_matching': True, }, { 'url': 'https://www.ok.ru/live/484531969818', 'only_matching': True, }, { 'url': 'https://m.ok.ru/dk?st.cmd=movieLayer&st.discId=863789452017&st.retLoc=friend&st.rtu=%2Fdk%3Fst.cmd%3DfriendMovies%26st.mode%3Down%26st.mrkId%3D%257B%2522uploadedMovieMarker%2522%253A%257B%2522marker%2522%253A%25221519410114503%2522%252C%2522hasMore%2522%253Atrue%257D%252C%2522sharedMovieMarker%2522%253A%257B%2522marker%2522%253Anull%252C%2522hasMore%2522%253Afalse%257D%257D%26st.friendId%3D561722190321%26st.frwd%3Don%26_prevCmd%3DfriendMovies%26tkn%3D7257&st.discType=MOVIE&st.mvId=863789452017&_prevCmd=friendMovies&tkn=3648#lst#', 'only_matching': True, }, { # Paid video 'url': 'https://ok.ru/video/954886983203', 'only_matching': True, }] @staticmethod def _extract_url(webpage): mobj = re.search( r'<iframe[^>]+src=(["\'])(?P<url>(?:https?:)?//(?:odnoklassniki|ok)\.ru/videoembed/.+?)\1', webpage) if mobj: return mobj.group('url') def _real_extract(self, url): start_time = int_or_none(compat_parse_qs( compat_urllib_parse_urlparse(url).query).get('fromTime', [None])[0]) video_id = self._match_id(url) webpage = self._download_webpage( 'http://ok.ru/video/%s' % video_id, video_id) error = self._search_regex( r'[^>]+class="vp_video_stub_txt"[^>]*>([^<]+)<', webpage, 'error', default=None) if error: raise ExtractorError(error, expected=True) player = self._parse_json( unescapeHTML(self._search_regex( r'data-options=(?P<quote>["\'])(?P<player>{.+?%s.+?})(?P=quote)' % video_id, webpage, 'player', group='player')), video_id) flashvars = player['flashvars'] metadata = flashvars.get('metadata') if metadata: metadata = self._parse_json(metadata, video_id) else: data = {} st_location = flashvars.get('location') if st_location: data['st.location'] = st_location metadata = self._download_json( compat_urllib_parse_unquote(flashvars['metadataUrl']), video_id, 'Downloading metadata JSON', data=urlencode_postdata(data)) movie = metadata['movie'] # Some embedded videos may not contain title in movie dict (e.g. # http://ok.ru/video/62036049272859-0) thus we allow missing title # here and it's going to be extracted later by an extractor that # will process the actual embed. provider = metadata.get('provider') title = movie['title'] if provider == 'UPLOADED_ODKL' else movie.get('title') thumbnail = movie.get('poster') duration = int_or_none(movie.get('duration')) author = metadata.get('author', {}) uploader_id = author.get('id') uploader = author.get('name') upload_date = unified_strdate(self._html_search_meta( 'ya:ovs:upload_date', webpage, 'upload date', default=None)) age_limit = None adult = self._html_search_meta( 'ya:ovs:adult', webpage, 'age limit', default=None) if adult: age_limit = 18 if adult == 'true' else 0 like_count = int_or_none(metadata.get('likeCount')) info = { 'id': video_id, 'title': title, 'thumbnail': thumbnail, 'duration': duration, 'upload_date': upload_date, 'uploader': uploader, 'uploader_id': uploader_id, 'like_count': like_count, 'age_limit': age_limit, 'start_time': start_time, } if provider == 'USER_YOUTUBE': info.update({ '_type': 'url_transparent', 'url': movie['contentId'], }) return info assert title if provider == 'LIVE_TV_APP': info['title'] = self._live_title(title) quality = qualities(('4', '0', '1', '2', '3', '5')) formats = [{ 'url': f['url'], 'ext': 'mp4', 'format_id': f['name'], } for f in metadata['videos']] m3u8_url = metadata.get('hlsManifestUrl') if m3u8_url: formats.extend(self._extract_m3u8_formats( m3u8_url, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False)) dash_manifest = metadata.get('metadataEmbedded') if dash_manifest: formats.extend(self._parse_mpd_formats( compat_etree_fromstring(dash_manifest), 'mpd')) for fmt in formats: fmt_type = self._search_regex( r'\btype[/=](\d)', fmt['url'], 'format type', default=None) if fmt_type: fmt['quality'] = quality(fmt_type) # Live formats m3u8_url = metadata.get('hlsMasterPlaylistUrl') if m3u8_url: formats.extend(self._extract_m3u8_formats( m3u8_url, video_id, 'mp4', entry_protocol='m3u8', m3u8_id='hls', fatal=False)) rtmp_url = metadata.get('rtmpUrl') if rtmp_url: formats.append({ 'url': rtmp_url, 'format_id': 'rtmp', 'ext': 'flv', }) if not formats: payment_info = metadata.get('paymentInfo') if payment_info: raise ExtractorError('This video is paid, subscribe to download it', expected=True) self._sort_formats(formats) info['formats'] = formats return info
unlicense
ryfeus/lambda-packs
HDF4_H5_NETCDF/source2.7/numpy/ma/timer_comparison.py
33
15586
from __future__ import division, absolute_import, print_function import timeit from functools import reduce import numpy as np from numpy import float_ import numpy.core.fromnumeric as fromnumeric from numpy.testing import build_err_msg # Fixme: this does not look right. np.seterr(all='ignore') pi = np.pi class ModuleTester(object): def __init__(self, module): self.module = module self.allequal = module.allequal self.arange = module.arange self.array = module.array self.concatenate = module.concatenate self.count = module.count self.equal = module.equal self.filled = module.filled self.getmask = module.getmask self.getmaskarray = module.getmaskarray self.id = id self.inner = module.inner self.make_mask = module.make_mask self.masked = module.masked self.masked_array = module.masked_array self.masked_values = module.masked_values self.mask_or = module.mask_or self.nomask = module.nomask self.ones = module.ones self.outer = module.outer self.repeat = module.repeat self.resize = module.resize self.sort = module.sort self.take = module.take self.transpose = module.transpose self.zeros = module.zeros self.MaskType = module.MaskType try: self.umath = module.umath except AttributeError: self.umath = module.core.umath self.testnames = [] def assert_array_compare(self, comparison, x, y, err_msg='', header='', fill_value=True): """ Assert that a comparison of two masked arrays is satisfied elementwise. """ xf = self.filled(x) yf = self.filled(y) m = self.mask_or(self.getmask(x), self.getmask(y)) x = self.filled(self.masked_array(xf, mask=m), fill_value) y = self.filled(self.masked_array(yf, mask=m), fill_value) if (x.dtype.char != "O"): x = x.astype(float_) if isinstance(x, np.ndarray) and x.size > 1: x[np.isnan(x)] = 0 elif np.isnan(x): x = 0 if (y.dtype.char != "O"): y = y.astype(float_) if isinstance(y, np.ndarray) and y.size > 1: y[np.isnan(y)] = 0 elif np.isnan(y): y = 0 try: cond = (x.shape == () or y.shape == ()) or x.shape == y.shape if not cond: msg = build_err_msg([x, y], err_msg + '\n(shapes %s, %s mismatch)' % (x.shape, y.shape), header=header, names=('x', 'y')) assert cond, msg val = comparison(x, y) if m is not self.nomask and fill_value: val = self.masked_array(val, mask=m) if isinstance(val, bool): cond = val reduced = [0] else: reduced = val.ravel() cond = reduced.all() reduced = reduced.tolist() if not cond: match = 100-100.0*reduced.count(1)/len(reduced) msg = build_err_msg([x, y], err_msg + '\n(mismatch %s%%)' % (match,), header=header, names=('x', 'y')) assert cond, msg except ValueError: msg = build_err_msg([x, y], err_msg, header=header, names=('x', 'y')) raise ValueError(msg) def assert_array_equal(self, x, y, err_msg=''): """ Checks the elementwise equality of two masked arrays. """ self.assert_array_compare(self.equal, x, y, err_msg=err_msg, header='Arrays are not equal') def test_0(self): """ Tests creation """ x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] xm = self.masked_array(x, mask=m) xm[0] def test_1(self): """ Tests creation """ x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1] xm = self.masked_array(x, mask=m1) ym = self.masked_array(y, mask=m2) xf = np.where(m1, 1.e+20, x) xm.set_fill_value(1.e+20) assert((xm-ym).filled(0).any()) s = x.shape assert(xm.size == reduce(lambda x, y:x*y, s)) assert(self.count(xm) == len(m1) - reduce(lambda x, y:x+y, m1)) for s in [(4, 3), (6, 2)]: x.shape = s y.shape = s xm.shape = s ym.shape = s xf.shape = s assert(self.count(xm) == len(m1) - reduce(lambda x, y:x+y, m1)) def test_2(self): """ Tests conversions and indexing. """ x1 = np.array([1, 2, 4, 3]) x2 = self.array(x1, mask=[1, 0, 0, 0]) x3 = self.array(x1, mask=[0, 1, 0, 1]) x4 = self.array(x1) # test conversion to strings, no errors str(x2) repr(x2) # tests of indexing assert type(x2[1]) is type(x1[1]) assert x1[1] == x2[1] x1[2] = 9 x2[2] = 9 self.assert_array_equal(x1, x2) x1[1:3] = 99 x2[1:3] = 99 x2[1] = self.masked x2[1:3] = self.masked x2[:] = x1 x2[1] = self.masked x3[:] = self.masked_array([1, 2, 3, 4], [0, 1, 1, 0]) x4[:] = self.masked_array([1, 2, 3, 4], [0, 1, 1, 0]) x1 = np.arange(5)*1.0 x2 = self.masked_values(x1, 3.0) x1 = self.array([1, 'hello', 2, 3], object) x2 = np.array([1, 'hello', 2, 3], object) # check that no error occurs. x1[1] x2[1] assert x1[1:1].shape == (0,) # Tests copy-size n = [0, 0, 1, 0, 0] m = self.make_mask(n) m2 = self.make_mask(m) assert(m is m2) m3 = self.make_mask(m, copy=1) assert(m is not m3) def test_3(self): """ Tests resize/repeat """ x4 = self.arange(4) x4[2] = self.masked y4 = self.resize(x4, (8,)) assert self.allequal(self.concatenate([x4, x4]), y4) assert self.allequal(self.getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0]) y5 = self.repeat(x4, (2, 2, 2, 2), axis=0) self.assert_array_equal(y5, [0, 0, 1, 1, 2, 2, 3, 3]) y6 = self.repeat(x4, 2, axis=0) assert self.allequal(y5, y6) y7 = x4.repeat((2, 2, 2, 2), axis=0) assert self.allequal(y5, y7) y8 = x4.repeat(2, 0) assert self.allequal(y5, y8) def test_4(self): """ Test of take, transpose, inner, outer products. """ x = self.arange(24) y = np.arange(24) x[5:6] = self.masked x = x.reshape(2, 3, 4) y = y.reshape(2, 3, 4) assert self.allequal(np.transpose(y, (2, 0, 1)), self.transpose(x, (2, 0, 1))) assert self.allequal(np.take(y, (2, 0, 1), 1), self.take(x, (2, 0, 1), 1)) assert self.allequal(np.inner(self.filled(x, 0), self.filled(y, 0)), self.inner(x, y)) assert self.allequal(np.outer(self.filled(x, 0), self.filled(y, 0)), self.outer(x, y)) y = self.array(['abc', 1, 'def', 2, 3], object) y[2] = self.masked t = self.take(y, [0, 3, 4]) assert t[0] == 'abc' assert t[1] == 2 assert t[2] == 3 def test_5(self): """ Tests inplace w/ scalar """ x = self.arange(10) y = self.arange(10) xm = self.arange(10) xm[2] = self.masked x += 1 assert self.allequal(x, y+1) xm += 1 assert self.allequal(xm, y+1) x = self.arange(10) xm = self.arange(10) xm[2] = self.masked x -= 1 assert self.allequal(x, y-1) xm -= 1 assert self.allequal(xm, y-1) x = self.arange(10)*1.0 xm = self.arange(10)*1.0 xm[2] = self.masked x *= 2.0 assert self.allequal(x, y*2) xm *= 2.0 assert self.allequal(xm, y*2) x = self.arange(10)*2 xm = self.arange(10)*2 xm[2] = self.masked x /= 2 assert self.allequal(x, y) xm /= 2 assert self.allequal(xm, y) x = self.arange(10)*1.0 xm = self.arange(10)*1.0 xm[2] = self.masked x /= 2.0 assert self.allequal(x, y/2.0) xm /= self.arange(10) self.assert_array_equal(xm, self.ones((10,))) x = self.arange(10).astype(float_) xm = self.arange(10) xm[2] = self.masked x += 1. assert self.allequal(x, y + 1.) def test_6(self): """ Tests inplace w/ array """ x = self.arange(10, dtype=float_) y = self.arange(10) xm = self.arange(10, dtype=float_) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=float_) a[-1] = self.masked x += a xm += a assert self.allequal(x, y+a) assert self.allequal(xm, y+a) assert self.allequal(xm.mask, self.mask_or(m, a.mask)) x = self.arange(10, dtype=float_) xm = self.arange(10, dtype=float_) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=float_) a[-1] = self.masked x -= a xm -= a assert self.allequal(x, y-a) assert self.allequal(xm, y-a) assert self.allequal(xm.mask, self.mask_or(m, a.mask)) x = self.arange(10, dtype=float_) xm = self.arange(10, dtype=float_) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=float_) a[-1] = self.masked x *= a xm *= a assert self.allequal(x, y*a) assert self.allequal(xm, y*a) assert self.allequal(xm.mask, self.mask_or(m, a.mask)) x = self.arange(10, dtype=float_) xm = self.arange(10, dtype=float_) xm[2] = self.masked m = xm.mask a = self.arange(10, dtype=float_) a[-1] = self.masked x /= a xm /= a def test_7(self): "Tests ufunc" d = (self.array([1.0, 0, -1, pi/2]*2, mask=[0, 1]+[0]*6), self.array([1.0, 0, -1, pi/2]*2, mask=[1, 0]+[0]*6),) for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate', # 'sin', 'cos', 'tan', # 'arcsin', 'arccos', 'arctan', # 'sinh', 'cosh', 'tanh', # 'arcsinh', # 'arccosh', # 'arctanh', # 'absolute', 'fabs', 'negative', # # 'nonzero', 'around', # 'floor', 'ceil', # # 'sometrue', 'alltrue', # 'logical_not', # 'add', 'subtract', 'multiply', # 'divide', 'true_divide', 'floor_divide', # 'remainder', 'fmod', 'hypot', 'arctan2', # 'equal', 'not_equal', 'less_equal', 'greater_equal', # 'less', 'greater', # 'logical_and', 'logical_or', 'logical_xor', ]: try: uf = getattr(self.umath, f) except AttributeError: uf = getattr(fromnumeric, f) mf = getattr(self.module, f) args = d[:uf.nin] ur = uf(*args) mr = mf(*args) self.assert_array_equal(ur.filled(0), mr.filled(0), f) self.assert_array_equal(ur._mask, mr._mask) def test_99(self): # test average ott = self.array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) self.assert_array_equal(2.0, self.average(ott, axis=0)) self.assert_array_equal(2.0, self.average(ott, weights=[1., 1., 2., 1.])) result, wts = self.average(ott, weights=[1., 1., 2., 1.], returned=1) self.assert_array_equal(2.0, result) assert(wts == 4.0) ott[:] = self.masked assert(self.average(ott, axis=0) is self.masked) ott = self.array([0., 1., 2., 3.], mask=[1, 0, 0, 0]) ott = ott.reshape(2, 2) ott[:, 1] = self.masked self.assert_array_equal(self.average(ott, axis=0), [2.0, 0.0]) assert(self.average(ott, axis=1)[0] is self.masked) self.assert_array_equal([2., 0.], self.average(ott, axis=0)) result, wts = self.average(ott, axis=0, returned=1) self.assert_array_equal(wts, [1., 0.]) w1 = [0, 1, 1, 1, 1, 0] w2 = [[0, 1, 1, 1, 1, 0], [1, 0, 0, 0, 0, 1]] x = self.arange(6) self.assert_array_equal(self.average(x, axis=0), 2.5) self.assert_array_equal(self.average(x, axis=0, weights=w1), 2.5) y = self.array([self.arange(6), 2.0*self.arange(6)]) self.assert_array_equal(self.average(y, None), np.add.reduce(np.arange(6))*3./12.) self.assert_array_equal(self.average(y, axis=0), np.arange(6) * 3./2.) self.assert_array_equal(self.average(y, axis=1), [self.average(x, axis=0), self.average(x, axis=0) * 2.0]) self.assert_array_equal(self.average(y, None, weights=w2), 20./6.) self.assert_array_equal(self.average(y, axis=0, weights=w2), [0., 1., 2., 3., 4., 10.]) self.assert_array_equal(self.average(y, axis=1), [self.average(x, axis=0), self.average(x, axis=0) * 2.0]) m1 = self.zeros(6) m2 = [0, 0, 1, 1, 0, 0] m3 = [[0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0]] m4 = self.ones(6) m5 = [0, 1, 1, 1, 1, 1] self.assert_array_equal(self.average(self.masked_array(x, m1), axis=0), 2.5) self.assert_array_equal(self.average(self.masked_array(x, m2), axis=0), 2.5) self.assert_array_equal(self.average(self.masked_array(x, m5), axis=0), 0.0) self.assert_array_equal(self.count(self.average(self.masked_array(x, m4), axis=0)), 0) z = self.masked_array(y, m3) self.assert_array_equal(self.average(z, None), 20./6.) self.assert_array_equal(self.average(z, axis=0), [0., 1., 99., 99., 4.0, 7.5]) self.assert_array_equal(self.average(z, axis=1), [2.5, 5.0]) self.assert_array_equal(self.average(z, axis=0, weights=w2), [0., 1., 99., 99., 4.0, 10.0]) def test_A(self): x = self.arange(24) x[5:6] = self.masked x = x.reshape(2, 3, 4) if __name__ == '__main__': setup_base = ("from __main__ import ModuleTester \n" "import numpy\n" "tester = ModuleTester(module)\n") setup_cur = "import numpy.ma.core as module\n" + setup_base (nrepeat, nloop) = (10, 10) if 1: for i in range(1, 8): func = 'tester.test_%i()' % i cur = timeit.Timer(func, setup_cur).repeat(nrepeat, nloop*10) cur = np.sort(cur) print("#%i" % i + 50*'.') print(eval("ModuleTester.test_%i.__doc__" % i)) print("core_current : %.3f - %.3f" % (cur[0], cur[1]))
mit
smartbgp/yabgp
yabgp/message/attribute/mpunreachnlri.py
2
9951
# Copyright 2015-2017 Cisco Systems, Inc. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """BGP Attribute MP_UNREACH_NLRI """ import struct from yabgp.message.attribute import Attribute from yabgp.message.attribute import AttributeFlag from yabgp.message.attribute import AttributeID from yabgp.message.attribute.nlri.ipv4_mpls_vpn import IPv4MPLSVPN from yabgp.message.attribute.nlri.ipv6_mpls_vpn import IPv6MPLSVPN from yabgp.message.attribute.nlri.ipv4_flowspec import IPv4FlowSpec from yabgp.message.attribute.nlri.ipv6_unicast import IPv6Unicast from yabgp.message.attribute.nlri.labeled_unicast.ipv4 import IPv4LabeledUnicast from yabgp.message.attribute.nlri.evpn import EVPN from yabgp.message.attribute.nlri.linkstate import BGPLS from yabgp.message.attribute.nlri.ipv4_srte import IPv4SRTE from yabgp.common import afn from yabgp.common import safn from yabgp.common import exception as excep from yabgp.common import constants as bgp_cons class MpUnReachNLRI(Attribute): """ This is an optional non-transitive attribute that can be used for the purpose of withdrawing multiple unfeasible routes from service. An UPDATE message that contains the MP_UNREACH_NLRI is not required to carry any other path attributes. MP_UNREACH_NLRI coding information +---------------------------------------------------------+ | Address Family Identifier (2 octets) | +---------------------------------------------------------+ | Subsequent Address Family Identifier (1 octet) | +---------------------------------------------------------+ | Withdrawn Routes (variable) | +---------------------------------------------------------+ """ ID = AttributeID.MP_UNREACH_NLRI FLAG = AttributeFlag.OPTIONAL + AttributeFlag.EXTENDED_LENGTH @classmethod def parse(cls, value): try: afi, safi = struct.unpack('!HB', value[0:3]) except Exception: raise excep.UpdateMessageError(sub_error=bgp_cons.ERR_MSG_UPDATE_ATTR_LEN, data='') nlri_bin = value[3:] # for IPv4 if afi == afn.AFNUM_INET: # VPNv4 if safi == safn.SAFNUM_LAB_VPNUNICAST: nlri = IPv4MPLSVPN.parse(nlri_bin, iswithdraw=True) return dict(afi_safi=(afi, safi), withdraw=nlri) # BGP flow spec elif safi == safn.SAFNUM_FSPEC_RULE: # if nlri length is greater than 240 bytes, it is encoded over 2 bytes withdraw_list = [] while nlri_bin: length = ord(nlri_bin[0:1]) if length >> 4 == 0xf and len(nlri_bin) > 2: length = struct.unpack('!H', nlri_bin[:2])[0] nlri_tmp = nlri_bin[2: length + 2] nlri_bin = nlri_bin[length + 2:] else: nlri_tmp = nlri_bin[1: length + 1] nlri_bin = nlri_bin[length + 1:] nlri = IPv4FlowSpec.parse(nlri_tmp) if nlri: withdraw_list.append(nlri) return dict(afi_safi=(afi, safi), withdraw=withdraw_list) else: return dict(afi_safi=(afn.AFNUM_INET, safi), withdraw=repr(nlri_bin)) # for ipv6 elif afi == afn.AFNUM_INET6: # for ipv6 unicast if safi == safn.SAFNUM_UNICAST: return dict(afi_safi=(afi, safi), withdraw=IPv6Unicast.parse(nlri_data=nlri_bin)) elif safi == safn.SAFNUM_LAB_VPNUNICAST: return dict(afi_safi=(afi, safi), withdraw=IPv6MPLSVPN.parse(value=nlri_bin, iswithdraw=True)) else: return dict(afi_safi=(afi, safi), withdraw=repr(nlri_bin)) # for l2vpn elif afi == afn.AFNUM_L2VPN: # for evpn if safi == safn.SAFNUM_EVPN: return dict(afi_safi=(afi, safi), withdraw=EVPN.parse(nlri_data=nlri_bin)) else: return dict(afi_safi=(afi, safi), withdraw=repr(nlri_bin)) # BGP LS elif afi == afn.AFNUM_BGPLS: if safi == safn.SAFNUM_BGPLS: withdraw = BGPLS.parse(nlri_bin) return dict(afi_safi=(afi, safi), withdraw=withdraw) else: pass else: return dict(afi_safi=(afi, safi), withdraw=repr(nlri_bin)) @classmethod def construct(cls, value): """Construct a attribute :param value: python dictionary {'afi_safi': (1,128), 'withdraw': [] """ afi, safi = value['afi_safi'] if afi == afn.AFNUM_INET: if safi == safn.SAFNUM_LAB_VPNUNICAST: # MPLS VPN nlri = IPv4MPLSVPN.construct(value['withdraw'], iswithdraw=True) if nlri: attr_value = struct.pack('!H', afi) + struct.pack('!B', safi) + nlri return struct.pack('!B', cls.FLAG) + struct.pack('!B', cls.ID) \ + struct.pack('!H', len(attr_value)) + attr_value else: return None elif safi == safn.SAFNUM_FSPEC_RULE: try: nlri_list = value.get('withdraw') or [] if not nlri_list: return None nlri_hex = b'' nlri_hex += IPv4FlowSpec.construct(value=nlri_list) attr_value = struct.pack('!H', afi) + struct.pack('!B', safi) + nlri_hex return struct.pack('!B', cls.FLAG) + struct.pack('!B', cls.ID) \ + struct.pack('!H', len(attr_value)) + attr_value except Exception: raise excep.ConstructAttributeFailed( reason='failed to construct attributes', data=value ) elif safi == safn.SAFNUM_SRTE: try: nlri_list = value.get('withdraw') or {} if not nlri_list: return None nlri_hex = b'' nlri_hex += IPv4SRTE.construct(data=value['withdraw']) attr_value = struct.pack('!H', afi) + struct.pack('!B', safi) + nlri_hex return struct.pack('!B', cls.FLAG) + struct.pack('!B', cls.ID) \ + struct.pack('!H', len(attr_value)) + attr_value except Exception: raise excep.ConstructAttributeFailed( reason='failed to construct attributes', data=value ) elif safi == safn.SAFNUM_MPLS_LABEL: try: nlri_list = value.get('withdraw') or [] if not nlri_list: return None nlri_hex = b'' flag = 'withdraw' nlri_hex += IPv4LabeledUnicast.construct(nlri_list, flag) attr_value = struct.pack('!H', afi) + struct.pack('!B', safi) + nlri_hex return struct.pack('!B', cls.FLAG) + struct.pack('!B', cls.ID) \ + struct.pack('!H', len(attr_value)) + attr_value except Exception: raise excep.ConstructAttributeFailed( reason='failed to construct attributes', data=value ) else: raise excep.ConstructAttributeFailed( reason='unsupport this sub address family', data=value) elif afi == afn.AFNUM_INET6: if safi == safn.SAFNUM_UNICAST: nlri = IPv6Unicast.construct(nlri_list=value['withdraw']) if nlri: attr_value = struct.pack('!H', afi) + struct.pack('!B', safi) + nlri return struct.pack('!B', cls.FLAG) + struct.pack('!B', cls.ID) \ + struct.pack('!H', len(attr_value)) + attr_value elif safi == safn.SAFNUM_LAB_VPNUNICAST: nlri = IPv6MPLSVPN.construct(value=value['withdraw'], iswithdraw=True) if nlri: attr_value = struct.pack('!H', afi) + struct.pack('!B', safi) + nlri return struct.pack('!B', cls.FLAG) + struct.pack('!B', cls.ID) \ + struct.pack('!H', len(attr_value)) + attr_value else: return None # for l2vpn elif afi == afn.AFNUM_L2VPN: # for evpn if safi == safn.SAFNUM_EVPN: nlri = EVPN.construct(nlri_list=value['withdraw']) if nlri: attr_value = struct.pack('!H', afi) + struct.pack('!B', safi) + nlri return struct.pack('!B', cls.FLAG) + struct.pack('!B', cls.ID) \ + struct.pack('!H', len(attr_value)) + attr_value else: return None else: raise excep.ConstructAttributeFailed( reason='unsupport this sub address family', data=value)
apache-2.0
DonBeo/scikit-learn
examples/applications/topics_extraction_with_nmf.py
106
2313
""" ======================================================== Topics extraction with Non-Negative Matrix Factorization ======================================================== This is a proof of concept application of Non Negative Matrix Factorization of the term frequency matrix of a corpus of documents so as to extract an additive model of the topic structure of the corpus. The output is a list of topics, each represented as a list of terms (weights are not shown). The default parameters (n_samples / n_features / n_topics) should make the example runnable in a couple of tens of seconds. You can try to increase the dimensions of the problem, but be aware than the time complexity is polynomial. """ # Author: Olivier Grisel <olivier.grisel@ensta.org> # Lars Buitinck <L.J.Buitinck@uva.nl> # License: BSD 3 clause from __future__ import print_function from time import time from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import NMF from sklearn.datasets import fetch_20newsgroups n_samples = 2000 n_features = 1000 n_topics = 10 n_top_words = 20 # Load the 20 newsgroups dataset and vectorize it. We use a few heuristics # to filter out useless terms early on: the posts are stripped of headers, # footers and quoted replies, and common English words, words occurring in # only one document or in at least 95% of the documents are removed. t0 = time() print("Loading dataset and extracting TF-IDF features...") dataset = fetch_20newsgroups(shuffle=True, random_state=1, remove=('headers', 'footers', 'quotes')) vectorizer = TfidfVectorizer(max_df=0.95, min_df=2, max_features=n_features, stop_words='english') tfidf = vectorizer.fit_transform(dataset.data[:n_samples]) print("done in %0.3fs." % (time() - t0)) # Fit the NMF model print("Fitting the NMF model with n_samples=%d and n_features=%d..." % (n_samples, n_features)) nmf = NMF(n_components=n_topics, random_state=1).fit(tfidf) print("done in %0.3fs." % (time() - t0)) feature_names = vectorizer.get_feature_names() for topic_idx, topic in enumerate(nmf.components_): print("Topic #%d:" % topic_idx) print(" ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]])) print()
bsd-3-clause
eddiep1101/django-oscar
tests/integration/offer/tax_tests.py
60
1873
from decimal import Decimal as D from django.test import TestCase from oscar.apps.offer import models from oscar.apps.basket.models import Basket from oscar.apps.partner import strategy from oscar.test.basket import add_product class TestAValueBasedOffer(TestCase): def setUp(self): # Get 20% if spending more than 20.00 range = models.Range.objects.create( name="All products", includes_all_products=True) condition = models.Condition.objects.create( range=range, type=models.Condition.VALUE, value=D('10.00')) benefit = models.Benefit.objects.create( range=range, type=models.Benefit.PERCENTAGE, value=20) self.offer = models.ConditionalOffer.objects.create( name="Test", offer_type=models.ConditionalOffer.SITE, condition=condition, benefit=benefit) self.basket = Basket.objects.create() def test_respects_effective_price_when_taxes_not_known(self): # Assign US style strategy (no tax known) self.basket.strategy = strategy.US() # Add sufficient products to meet condition add_product(self.basket, price=D('6'), quantity=2) # Ensure discount is correct result = self.offer.apply_benefit(self.basket) self.assertEqual(D('2.40'), result.discount) def test_respects_effective_price_when_taxes_are_known(self): # Assign UK style strategy (20% tax) self.basket.strategy = strategy.UK() # Add sufficient products to meet condition add_product(self.basket, price=D('6'), quantity=2) # Ensure discount is calculated against tax-inclusive price result = self.offer.apply_benefit(self.basket) self.assertEqual(2 * D('6.00') * D('1.2') * D('0.20'), result.discount)
bsd-3-clause
nextcloud/appstore
scripts/generate_authors.py
1
1948
#!/usr/bin/env python3 import subprocess import re from typing import List, Dict, Tuple, Iterator from os import pardir from os.path import dirname, realpath, join def get_git_authors() -> List[str]: command = ['git', '--no-pager', 'shortlog', '-nse', 'HEAD'] authors = subprocess.check_output(command) return authors.decode('utf-8').split('\n') def parse_git_author(line: str) -> Dict[str, str]: format_regex = r'^\s*(?P<commit_count>\d+)\s*(?P<name>.*\w)\s*<(' \ r'?P<email>[^\s]+)>$' result = re.search(format_regex, line) if result: return { 'commits': result.group('commit_count'), 'name': result.group('name'), 'email': result.group('email') } else: raise ValueError('Could not extract authors from line %s' % line) def to_markdown(authors: Iterator[Dict[str, str]]) -> Tuple[str, str]: result = ['# Authors', ''] for author in authors: result += ['* [%s](mailto:%s)' % (author['name'], author['email'])] return '\n'.join(result), 'md' def to_rst(authors: Iterator[Dict[str, str]]) -> Tuple[str, str]: result = ['Authors', '=======', ''] for author in authors: result += ['* `%s <mailto:%s>`_' % (author['name'], author['email'])] return '\n'.join(result), 'rst' def get_authors_file(suffix: str) -> str: directory = dirname(realpath(__file__)) directory = join(directory, pardir) return join(directory, 'AUTHORS.%s' % suffix) def main() -> None: ignore = {'Nextcloud bot'} authors = get_git_authors() authors = filter(lambda name: name.strip() != '', authors) authors = [parse_git_author(author) for author in authors] authors = filter(lambda author: author['name'] not in ignore, authors) text, extension = to_markdown(authors) with open(get_authors_file(extension), 'w') as f: f.write(text) if __name__ == '__main__': main()
agpl-3.0
kenshay/ImageScripter
ProgramData/SystemFiles/Python/Lib/site-packages/dask/dataframe/io/tests/test_csv.py
2
39060
from __future__ import print_function, division, absolute_import from io import BytesIO import os import gzip from time import sleep import pytest pd = pytest.importorskip('pandas') dd = pytest.importorskip('dask.dataframe') from toolz import partition_all, valmap import pandas.util.testing as tm import dask import dask.dataframe as dd from dask.base import compute_as_if_collection from dask.dataframe.io.csv import (text_blocks_to_pandas, pandas_read_text, auto_blocksize) from dask.dataframe.utils import assert_eq, has_known_categories, PANDAS_VERSION from dask.bytes.core import read_bytes from dask.utils import filetexts, filetext, tmpfile, tmpdir from dask.bytes.compression import compress, files as cfiles, seekable_files fmt_bs = [(fmt, None) for fmt in cfiles] + [(fmt, 10) for fmt in seekable_files] def normalize_text(s): return '\n'.join(map(str.strip, s.strip().split('\n'))) def parse_filename(path): return os.path.split(path)[1] csv_text = """ name,amount Alice,100 Bob,-200 Charlie,300 Dennis,400 Edith,-500 Frank,600 Alice,200 Frank,-200 Bob,600 Alice,400 Frank,200 Alice,300 Edith,600 """.strip() tsv_text = csv_text.replace(',', '\t') tsv_text2 = """ name amount Alice 100 Bob -200 Charlie 300 Dennis 400 Edith -500 Frank 600 Alice 200 Frank -200 Bob 600 Alice 400 Frank 200 Alice 300 Edith 600 """.strip() timeseries = """ Date,Open,High,Low,Close,Volume,Adj Close 2015-08-28,198.50,199.839996,197.919998,199.240005,143298900,199.240005 2015-08-27,197.020004,199.419998,195.210007,199.160004,266244700,199.160004 2015-08-26,192.080002,194.789993,188.369995,194.679993,328058100,194.679993 2015-08-25,195.429993,195.449997,186.919998,187.229996,353966700,187.229996 2015-08-24,197.630005,197.630005,182.399994,189.550003,478672400,189.550003 2015-08-21,201.729996,203.940002,197.520004,197.630005,328271500,197.630005 2015-08-20,206.509995,208.289993,203.899994,204.009995,185865600,204.009995 2015-08-19,209.089996,210.009995,207.350006,208.279999,167316300,208.279999 2015-08-18,210.259995,210.679993,209.699997,209.929993,70043800,209.929993 """.strip() csv_files = {'2014-01-01.csv': (b'name,amount,id\n' b'Alice,100,1\n' b'Bob,200,2\n' b'Charlie,300,3\n'), '2014-01-02.csv': (b'name,amount,id\n'), '2014-01-03.csv': (b'name,amount,id\n' b'Dennis,400,4\n' b'Edith,500,5\n' b'Frank,600,6\n')} tsv_files = {k: v.replace(b',', b'\t') for (k, v) in csv_files.items()} expected = pd.concat([pd.read_csv(BytesIO(csv_files[k])) for k in sorted(csv_files)]) comment_header = b"""# some header lines # that may be present # in a data file # before any data""" csv_and_table = pytest.mark.parametrize('reader,files', [(pd.read_csv, csv_files), (pd.read_table, tsv_files)]) @csv_and_table def test_pandas_read_text(reader, files): b = files['2014-01-01.csv'] df = pandas_read_text(reader, b, b'', {}) assert list(df.columns) == ['name', 'amount', 'id'] assert len(df) == 3 assert df.id.sum() == 1 + 2 + 3 @csv_and_table def test_pandas_read_text_kwargs(reader, files): b = files['2014-01-01.csv'] df = pandas_read_text(reader, b, b'', {'usecols': ['name', 'id']}) assert list(df.columns) == ['name', 'id'] @csv_and_table def test_pandas_read_text_dtype_coercion(reader, files): b = files['2014-01-01.csv'] df = pandas_read_text(reader, b, b'', {}, {'amount': 'float'}) assert df.amount.dtype == 'float' @csv_and_table def test_pandas_read_text_with_header(reader, files): b = files['2014-01-01.csv'] header, b = b.split(b'\n', 1) header = header + b'\n' df = pandas_read_text(reader, b, header, {}) assert list(df.columns) == ['name', 'amount', 'id'] assert len(df) == 3 assert df.id.sum() == 1 + 2 + 3 @csv_and_table def test_text_blocks_to_pandas_simple(reader, files): blocks = [[files[k]] for k in sorted(files)] kwargs = {} head = pandas_read_text(reader, files['2014-01-01.csv'], b'', {}) header = files['2014-01-01.csv'].split(b'\n')[0] + b'\n' df = text_blocks_to_pandas(reader, blocks, header, head, kwargs, collection=True) assert isinstance(df, dd.DataFrame) assert list(df.columns) == ['name', 'amount', 'id'] values = text_blocks_to_pandas(reader, blocks, header, head, kwargs, collection=False) assert isinstance(values, list) assert len(values) == 3 assert all(hasattr(item, 'dask') for item in values) assert_eq(df.amount.sum(), 100 + 200 + 300 + 400 + 500 + 600) @csv_and_table def test_text_blocks_to_pandas_kwargs(reader, files): blocks = [files[k] for k in sorted(files)] blocks = [[b] for b in blocks] kwargs = {'usecols': ['name', 'id']} head = pandas_read_text(reader, files['2014-01-01.csv'], b'', kwargs) header = files['2014-01-01.csv'].split(b'\n')[0] + b'\n' df = text_blocks_to_pandas(reader, blocks, header, head, kwargs, collection=True) assert list(df.columns) == ['name', 'id'] result = df.compute() assert (result.columns == df.columns).all() @csv_and_table def test_text_blocks_to_pandas_blocked(reader, files): header = files['2014-01-01.csv'].split(b'\n')[0] + b'\n' blocks = [] for k in sorted(files): b = files[k] lines = b.split(b'\n') blocks.append([b'\n'.join(bs) for bs in partition_all(2, lines)]) df = text_blocks_to_pandas(reader, blocks, header, expected.head(), {}) assert_eq(df.compute().reset_index(drop=True), expected.reset_index(drop=True), check_dtype=False) expected2 = expected[['name', 'id']] df = text_blocks_to_pandas(reader, blocks, header, expected2.head(), {'usecols': ['name', 'id']}) assert_eq(df.compute().reset_index(drop=True), expected2.reset_index(drop=True), check_dtype=False) @pytest.mark.parametrize('dd_read,pd_read,files', [(dd.read_csv, pd.read_csv, csv_files), (dd.read_table, pd.read_table, tsv_files)]) def test_skiprows(dd_read, pd_read, files): files = {name: comment_header + b'\n' + content for name, content in files.items()} skip = len(comment_header.splitlines()) with filetexts(files, mode='b'): df = dd_read('2014-01-*.csv', skiprows=skip) expected_df = pd.concat([pd_read(n, skiprows=skip) for n in sorted(files)]) assert_eq(df, expected_df, check_dtype=False) csv_blocks = [[b'aa,bb\n1,1.0\n2,2.0', b'10,20\n30,40'], [b'aa,bb\n1,1.0\n2,2.0', b'10,20\n30,40']] tsv_blocks = [[b'aa\tbb\n1\t1.0\n2\t2.0', b'10\t20\n30\t40'], [b'aa\tbb\n1\t1.0\n2\t2.0', b'10\t20\n30\t40']] @pytest.mark.parametrize('reader,blocks', [(pd.read_csv, csv_blocks), (pd.read_table, tsv_blocks)]) def test_enforce_dtypes(reader, blocks): head = reader(BytesIO(blocks[0][0]), header=0) header = blocks[0][0].split(b'\n')[0] + b'\n' dfs = text_blocks_to_pandas(reader, blocks, header, head, {}, collection=False) dfs = dask.compute(*dfs, scheduler='sync') assert all(df.dtypes.to_dict() == head.dtypes.to_dict() for df in dfs) @pytest.mark.parametrize('reader,blocks', [(pd.read_csv, csv_blocks), (pd.read_table, tsv_blocks)]) def test_enforce_columns(reader, blocks): # Replace second header with different column name blocks = [blocks[0], [blocks[1][0].replace(b'a', b'A'), blocks[1][1]]] head = reader(BytesIO(blocks[0][0]), header=0) header = blocks[0][0].split(b'\n')[0] + b'\n' with pytest.raises(ValueError): dfs = text_blocks_to_pandas(reader, blocks, header, head, {}, collection=False, enforce=True) dask.compute(*dfs, scheduler='sync') ############################# # read_csv and read_table # ############################# @pytest.mark.parametrize('dd_read,pd_read,text,sep', [(dd.read_csv, pd.read_csv, csv_text, ','), (dd.read_table, pd.read_table, tsv_text, '\t'), (dd.read_table, pd.read_table, tsv_text2, '\s+')]) def test_read_csv(dd_read, pd_read, text, sep): with filetext(text) as fn: f = dd_read(fn, blocksize=30, lineterminator=os.linesep, sep=sep) assert list(f.columns) == ['name', 'amount'] # index may be different result = f.compute(scheduler='sync').reset_index(drop=True) assert_eq(result, pd_read(fn, sep=sep)) @pytest.mark.parametrize('dd_read,pd_read,files', [(dd.read_csv, pd.read_csv, csv_files), (dd.read_table, pd.read_table, tsv_files)]) def test_read_csv_files(dd_read, pd_read, files): with filetexts(files, mode='b'): df = dd_read('2014-01-*.csv') assert_eq(df, expected, check_dtype=False) fn = '2014-01-01.csv' df = dd_read(fn) expected2 = pd_read(BytesIO(files[fn])) assert_eq(df, expected2, check_dtype=False) @pytest.mark.parametrize('dd_read,pd_read,files', [(dd.read_csv, pd.read_csv, csv_files), (dd.read_table, pd.read_table, tsv_files)]) def test_read_csv_files_list(dd_read, pd_read, files): with filetexts(files, mode='b'): subset = sorted(files)[:2] # Just first 2 sol = pd.concat([pd_read(BytesIO(files[k])) for k in subset]) res = dd_read(subset) assert_eq(res, sol, check_dtype=False) with pytest.raises(ValueError): dd_read([]) @pytest.mark.parametrize('dd_read,files', [(dd.read_csv, csv_files), (dd.read_table, tsv_files)]) def test_read_csv_include_path_column(dd_read, files): with filetexts(files, mode='b'): df = dd_read('2014-01-*.csv', include_path_column=True, converters={'path': parse_filename}) filenames = df.path.compute().unique() assert '2014-01-01.csv' in filenames assert '2014-01-02.csv' not in filenames assert '2014-01-03.csv' in filenames @pytest.mark.parametrize('dd_read,files', [(dd.read_csv, csv_files), (dd.read_table, tsv_files)]) def test_read_csv_include_path_column_as_str(dd_read, files): with filetexts(files, mode='b'): df = dd_read('2014-01-*.csv', include_path_column='filename', converters={'filename': parse_filename}) filenames = df.filename.compute().unique() assert '2014-01-01.csv' in filenames assert '2014-01-02.csv' not in filenames assert '2014-01-03.csv' in filenames @pytest.mark.parametrize('dd_read,files', [(dd.read_csv, csv_files), (dd.read_table, tsv_files)]) def test_read_csv_include_path_column_with_duplicate_name(dd_read, files): with filetexts(files, mode='b'): with pytest.raises(ValueError): dd_read('2014-01-*.csv', include_path_column='name') @pytest.mark.parametrize('dd_read,files', [(dd.read_csv, csv_files), (dd.read_table, tsv_files)]) def test_read_csv_include_path_column_is_dtype_category(dd_read, files): with filetexts(files, mode='b'): df = dd_read('2014-01-*.csv', include_path_column=True) assert df.path.dtype == 'category' assert has_known_categories(df.path) dfs = dd_read('2014-01-*.csv', include_path_column=True, collection=False) result = dfs[0].compute() assert result.path.dtype == 'category' assert has_known_categories(result.path) # After this point, we test just using read_csv, as all functionality # for both is implemented using the same code. def test_read_csv_index(): with filetext(csv_text) as fn: f = dd.read_csv(fn, blocksize=20).set_index('amount') result = f.compute(scheduler='sync') assert result.index.name == 'amount' blocks = compute_as_if_collection(dd.DataFrame, f.dask, f.__dask_keys__(), scheduler='sync') for i, block in enumerate(blocks): if i < len(f.divisions) - 2: assert (block.index < f.divisions[i + 1]).all() if i > 0: assert (block.index >= f.divisions[i]).all() expected = pd.read_csv(fn).set_index('amount') assert_eq(result, expected) def test_usecols(): with filetext(timeseries) as fn: df = dd.read_csv(fn, blocksize=30, usecols=['High', 'Low']) expected = pd.read_csv(fn, usecols=['High', 'Low']) assert (df.compute().values == expected.values).all() def test_skipinitialspace(): text = normalize_text(""" name, amount Alice,100 Bob,-200 Charlie,300 Dennis,400 Edith,-500 Frank,600 """) with filetext(text) as fn: df = dd.read_csv(fn, skipinitialspace=True, blocksize=20) assert 'amount' in df.columns assert df.amount.max().compute() == 600 def test_consistent_dtypes(): text = normalize_text(""" name,amount Alice,100.5 Bob,-200.5 Charlie,300 Dennis,400 Edith,-500 Frank,600 """) with filetext(text) as fn: df = dd.read_csv(fn, blocksize=30) assert df.amount.compute().dtype == float def test_consistent_dtypes_2(): text1 = normalize_text(""" name,amount Alice,100 Bob,-200 Charlie,300 """) text2 = normalize_text(""" name,amount 1,400 2,-500 Frank,600 """) with filetexts({'foo.1.csv': text1, 'foo.2.csv': text2}): df = dd.read_csv('foo.*.csv', blocksize=25) assert df.name.dtype == object assert df.name.compute().dtype == object @pytest.mark.skipif(PANDAS_VERSION < '0.19.2', reason="Not available in pandas <= 0.19.2") def test_categorical_dtypes(): text1 = normalize_text(""" fruit,count apple,10 apple,25 pear,100 orange,15 """) text2 = normalize_text(""" fruit,count apple,200 banana,300 orange,400 banana,10 """) with filetexts({'foo.1.csv': text1, 'foo.2.csv': text2}): df = dd.read_csv('foo.*.csv', dtype={'fruit': 'category'}, blocksize=25) assert df.fruit.dtype == 'category' assert not has_known_categories(df.fruit) res = df.compute() assert res.fruit.dtype == 'category' assert (sorted(res.fruit.cat.categories) == ['apple', 'banana', 'orange', 'pear']) @pytest.mark.skipif(PANDAS_VERSION < '0.21.0', reason="Uses CategoricalDtype") def test_categorical_known(): text1 = normalize_text(""" A,B a,a b,b a,a """) text2 = normalize_text(""" A,B a,a b,b c,c """) dtype = pd.api.types.CategoricalDtype(['a', 'b', 'c']) with filetexts({"foo.1.csv": text1, "foo.2.csv": text2}): result = dd.read_csv("foo.*.csv", dtype={"A": 'category', "B": 'category'}) assert result.A.cat.known is False assert result.B.cat.known is False expected = pd.DataFrame({ "A": pd.Categorical(['a', 'b', 'a', 'a', 'b', 'c'], categories=dtype.categories), "B": pd.Categorical(['a', 'b', 'a', 'a', 'b', 'c'], categories=dtype.categories)}, index=[0, 1, 2, 0, 1, 2]) assert_eq(result, expected) # Specify a dtype result = dd.read_csv("foo.*.csv", dtype={'A': dtype, 'B': 'category'}) assert result.A.cat.known is True assert result.B.cat.known is False tm.assert_index_equal(result.A.cat.categories, dtype.categories) assert result.A.cat.ordered is False assert_eq(result, expected) # ordered dtype = pd.api.types.CategoricalDtype(['a', 'b', 'c'], ordered=True) result = dd.read_csv("foo.*.csv", dtype={'A': dtype, 'B': 'category'}) expected['A'] = expected['A'].cat.as_ordered() assert result.A.cat.known is True assert result.B.cat.known is False assert result.A.cat.ordered is True assert_eq(result, expected) # Specify "unknown" categories result = dd.read_csv("foo.*.csv", dtype=pd.api.types.CategoricalDtype()) assert result.A.cat.known is False result = dd.read_csv("foo.*.csv", dtype="category") assert result.A.cat.known is False @pytest.mark.slow def test_compression_multiple_files(): with tmpdir() as tdir: f = gzip.open(os.path.join(tdir, 'a.csv.gz'), 'wb') f.write(csv_text.encode()) f.close() f = gzip.open(os.path.join(tdir, 'b.csv.gz'), 'wb') f.write(csv_text.encode()) f.close() with tm.assert_produces_warning(UserWarning): df = dd.read_csv(os.path.join(tdir, '*.csv.gz'), compression='gzip') assert len(df.compute()) == (len(csv_text.split('\n')) - 1) * 2 def test_empty_csv_file(): with filetext('a,b') as fn: df = dd.read_csv(fn, header=0) assert len(df.compute()) == 0 assert list(df.columns) == ['a', 'b'] def test_read_csv_sensitive_to_enforce(): with filetexts(csv_files, mode='b'): a = dd.read_csv('2014-01-*.csv', enforce=True) b = dd.read_csv('2014-01-*.csv', enforce=False) assert a._name != b._name @pytest.mark.parametrize('fmt,blocksize', fmt_bs) def test_read_csv_compression(fmt, blocksize): files2 = valmap(compress[fmt], csv_files) with filetexts(files2, mode='b'): df = dd.read_csv('2014-01-*.csv', compression=fmt, blocksize=blocksize) assert_eq(df.compute(scheduler='sync').reset_index(drop=True), expected.reset_index(drop=True), check_dtype=False) def test_warn_non_seekable_files(): files2 = valmap(compress['gzip'], csv_files) with filetexts(files2, mode='b'): with pytest.warns(UserWarning) as w: df = dd.read_csv('2014-01-*.csv', compression='gzip') assert df.npartitions == 3 assert len(w) == 1 msg = str(w[0].message) assert 'gzip' in msg assert 'blocksize=None' in msg with pytest.warns(None) as w: df = dd.read_csv('2014-01-*.csv', compression='gzip', blocksize=None) assert len(w) == 0 with pytest.raises(NotImplementedError): with pytest.warns(UserWarning): # needed for pytest df = dd.read_csv('2014-01-*.csv', compression='foo') def test_windows_line_terminator(): text = 'a,b\r\n1,2\r\n2,3\r\n3,4\r\n4,5\r\n5,6\r\n6,7' with filetext(text) as fn: df = dd.read_csv(fn, blocksize=5, lineterminator='\r\n') assert df.b.sum().compute() == 2 + 3 + 4 + 5 + 6 + 7 assert df.a.sum().compute() == 1 + 2 + 3 + 4 + 5 + 6 def test_header_None(): with filetexts({'.tmp.1.csv': '1,2', '.tmp.2.csv': '', '.tmp.3.csv': '3,4'}): df = dd.read_csv('.tmp.*.csv', header=None) expected = pd.DataFrame({0: [1, 3], 1: [2, 4]}) assert_eq(df.compute().reset_index(drop=True), expected) def test_auto_blocksize(): assert isinstance(auto_blocksize(3000, 15), int) assert auto_blocksize(3000, 3) == 100 assert auto_blocksize(5000, 2) == 250 def test_auto_blocksize_max64mb(): blocksize = auto_blocksize(1000000000000, 3) assert blocksize == int(64e6) assert isinstance(blocksize, int) def test_auto_blocksize_csv(monkeypatch): psutil = pytest.importorskip('psutil') try: from unittest import mock except ImportError: mock = pytest.importorskip('mock') total_memory = psutil.virtual_memory().total cpu_count = psutil.cpu_count() mock_read_bytes = mock.Mock(wraps=read_bytes) monkeypatch.setattr(dask.dataframe.io.csv, 'read_bytes', mock_read_bytes) expected_block_size = auto_blocksize(total_memory, cpu_count) with filetexts(csv_files, mode='b'): dd.read_csv('2014-01-01.csv') assert mock_read_bytes.called assert mock_read_bytes.call_args[1]['blocksize'] == expected_block_size def test_head_partial_line_fix(): files = {'.overflow1.csv': ('a,b\n' '0,"abcdefghijklmnopqrstuvwxyz"\n' '1,"abcdefghijklmnopqrstuvwxyz"'), '.overflow2.csv': ('a,b\n' '111111,-11111\n' '222222,-22222\n' '333333,-33333\n')} with filetexts(files): # 64 byte file, 52 characters is mid-quote; this should not cause exception in head-handling code. dd.read_csv('.overflow1.csv', sample=52) # 35 characters is cuts off before the second number on the last line # Should sample to end of line, otherwise pandas will infer `b` to be # a float dtype df = dd.read_csv('.overflow2.csv', sample=35) assert (df.dtypes == 'i8').all() def test_read_csv_raises_on_no_files(): fn = '.not.a.real.file.csv' try: dd.read_csv(fn) assert False except (OSError, IOError) as e: assert fn in str(e) def test_read_csv_has_deterministic_name(): with filetext(csv_text) as fn: a = dd.read_csv(fn) b = dd.read_csv(fn) assert a._name == b._name assert sorted(a.dask.keys(), key=str) == sorted(b.dask.keys(), key=str) assert isinstance(a._name, str) c = dd.read_csv(fn, skiprows=1, na_values=[0]) assert a._name != c._name def test_multiple_read_csv_has_deterministic_name(): with filetexts({'_foo.1.csv': csv_text, '_foo.2.csv': csv_text}): a = dd.read_csv('_foo.*.csv') b = dd.read_csv('_foo.*.csv') assert sorted(a.dask.keys(), key=str) == sorted(b.dask.keys(), key=str) def test_csv_with_integer_names(): with filetext('alice,1\nbob,2') as fn: df = dd.read_csv(fn, header=None) assert list(df.columns) == [0, 1] @pytest.mark.slow def test_read_csv_of_modified_file_has_different_name(): with filetext(csv_text) as fn: sleep(1) a = dd.read_csv(fn) sleep(1) with open(fn, 'a') as f: f.write('\nGeorge,700') os.fsync(f) b = dd.read_csv(fn) assert sorted(a.dask, key=str) != sorted(b.dask, key=str) def test_late_dtypes(): text = 'numbers,names,more_numbers,integers,dates\n' for i in range(1000): text += '1,,2,3,2017-10-31 00:00:00\n' text += '1.5,bar,2.5,3,4998-01-01 00:00:00\n' date_msg = ("\n" "\n" "-------------------------------------------------------------\n" "\n" "The following columns also failed to properly parse as dates:\n" "\n" "- dates\n" "\n" "This is usually due to an invalid value in that column. To\n" "diagnose and fix it's recommended to drop these columns from the\n" "`parse_dates` keyword, and manually convert them to dates later\n" "using `dd.to_datetime`.") with filetext(text) as fn: sol = pd.read_csv(fn) msg = ("Mismatched dtypes found in `pd.read_csv`/`pd.read_table`.\n" "\n" "+--------------+---------+----------+\n" "| Column | Found | Expected |\n" "+--------------+---------+----------+\n" "| more_numbers | float64 | int64 |\n" "| names | object | float64 |\n" "| numbers | float64 | int64 |\n" "+--------------+---------+----------+\n" "\n" "- names\n" " ValueError(.*)\n" "\n" "Usually this is due to dask's dtype inference failing, and\n" "*may* be fixed by specifying dtypes manually by adding:\n" "\n" "dtype={'more_numbers': 'float64',\n" " 'names': 'object',\n" " 'numbers': 'float64'}\n" "\n" "to the call to `read_csv`/`read_table`.") with pytest.raises(ValueError) as e: dd.read_csv(fn, sample=50, parse_dates=['dates']).compute(scheduler='sync') assert e.match(msg + date_msg) with pytest.raises(ValueError) as e: dd.read_csv(fn, sample=50).compute(scheduler='sync') assert e.match(msg) msg = ("Mismatched dtypes found in `pd.read_csv`/`pd.read_table`.\n" "\n" "+--------------+---------+----------+\n" "| Column | Found | Expected |\n" "+--------------+---------+----------+\n" "| more_numbers | float64 | int64 |\n" "| numbers | float64 | int64 |\n" "+--------------+---------+----------+\n" "\n" "Usually this is due to dask's dtype inference failing, and\n" "*may* be fixed by specifying dtypes manually by adding:\n" "\n" "dtype={'more_numbers': 'float64',\n" " 'numbers': 'float64'}\n" "\n" "to the call to `read_csv`/`read_table`.\n" "\n" "Alternatively, provide `assume_missing=True` to interpret\n" "all unspecified integer columns as floats.") with pytest.raises(ValueError) as e: dd.read_csv(fn, sample=50, dtype={'names': 'O'}).compute(scheduler='sync') assert str(e.value) == msg with pytest.raises(ValueError) as e: dd.read_csv(fn, sample=50, parse_dates=['dates'], dtype={'names': 'O'}).compute(scheduler='sync') assert str(e.value) == msg + date_msg msg = ("Mismatched dtypes found in `pd.read_csv`/`pd.read_table`.\n" "\n" "The following columns failed to properly parse as dates:\n" "\n" "- dates\n" "\n" "This is usually due to an invalid value in that column. To\n" "diagnose and fix it's recommended to drop these columns from the\n" "`parse_dates` keyword, and manually convert them to dates later\n" "using `dd.to_datetime`.") with pytest.raises(ValueError) as e: dd.read_csv(fn, sample=50, parse_dates=['dates'], dtype={'more_numbers': float, 'names': object, 'numbers': float}).compute(scheduler='sync') assert str(e.value) == msg # Specifying dtypes works res = dd.read_csv(fn, sample=50, dtype={'more_numbers': float, 'names': object, 'numbers': float}) assert_eq(res, sol) def test_assume_missing(): text = 'numbers,names,more_numbers,integers\n' for i in range(1000): text += '1,foo,2,3\n' text += '1.5,bar,2.5,3\n' with filetext(text) as fn: sol = pd.read_csv(fn) # assume_missing affects all columns res = dd.read_csv(fn, sample=50, assume_missing=True) assert_eq(res, sol.astype({'integers': float})) # assume_missing doesn't override specified dtypes res = dd.read_csv(fn, sample=50, assume_missing=True, dtype={'integers': 'int64'}) assert_eq(res, sol) # assume_missing works with dtype=None res = dd.read_csv(fn, sample=50, assume_missing=True, dtype=None) assert_eq(res, sol.astype({'integers': float})) text = 'numbers,integers\n' for i in range(1000): text += '1,2\n' text += '1.5,2\n' with filetext(text) as fn: sol = pd.read_csv(fn) # assume_missing ignored when all dtypes specifed df = dd.read_csv(fn, sample=30, dtype='int64', assume_missing=True) assert df.numbers.dtype == 'int64' def test_index_col(): with filetext(csv_text) as fn: try: dd.read_csv(fn, blocksize=30, index_col='name') assert False except ValueError as e: assert 'set_index' in str(e) def test_read_csv_with_datetime_index_partitions_one(): with filetext(timeseries) as fn: df = pd.read_csv(fn, index_col=0, header=0, usecols=[0, 4], parse_dates=['Date']) # blocksize set to explicitly set to single chunk ddf = dd.read_csv(fn, header=0, usecols=[0, 4], parse_dates=['Date'], blocksize=10000000).set_index('Date') assert_eq(df, ddf) # because fn is so small, by default, this will only be one chunk ddf = dd.read_csv(fn, header=0, usecols=[0, 4], parse_dates=['Date']).set_index('Date') assert_eq(df, ddf) def test_read_csv_with_datetime_index_partitions_n(): with filetext(timeseries) as fn: df = pd.read_csv(fn, index_col=0, header=0, usecols=[0, 4], parse_dates=['Date']) # because fn is so small, by default, set chunksize small ddf = dd.read_csv(fn, header=0, usecols=[0, 4], parse_dates=['Date'], blocksize=400).set_index('Date') assert_eq(df, ddf) @pytest.mark.parametrize('encoding', ['utf-16', 'utf-16-le', 'utf-16-be']) def test_encoding_gh601(encoding): ar = pd.Series(range(0, 100)) br = ar % 7 cr = br * 3.3 dr = br / 1.9836 test_df = pd.DataFrame({'a': ar, 'b': br, 'c': cr, 'd': dr}) with tmpfile('.csv') as fn: test_df.to_csv(fn, encoding=encoding, index=False) a = pd.read_csv(fn, encoding=encoding) d = dd.read_csv(fn, encoding=encoding, blocksize=1000) d = d.compute() d.index = range(len(d.index)) assert_eq(d, a) def test_read_csv_header_issue_823(): text = '''a b c-d\n1 2 3\n4 5 6'''.replace(' ', '\t') with filetext(text) as fn: df = dd.read_csv(fn, sep='\t') assert_eq(df, pd.read_csv(fn, sep='\t')) df = dd.read_csv(fn, delimiter='\t') assert_eq(df, pd.read_csv(fn, delimiter='\t')) def test_none_usecols(): with filetext(csv_text) as fn: df = dd.read_csv(fn, usecols=None) assert_eq(df, pd.read_csv(fn, usecols=None)) def test_parse_dates_multi_column(): pdmc_text = normalize_text(""" ID,date,time 10,2003-11-04,180036 11,2003-11-05,125640 12,2003-11-01,2519 13,2003-10-22,142559 14,2003-10-24,163113 15,2003-10-20,170133 16,2003-11-11,160448 17,2003-11-03,171759 18,2003-11-07,190928 19,2003-10-21,84623 20,2003-10-25,192207 21,2003-11-13,180156 22,2003-11-15,131037 """) with filetext(pdmc_text) as fn: ddf = dd.read_csv(fn, parse_dates=[['date', 'time']]) df = pd.read_csv(fn, parse_dates=[['date', 'time']]) assert (df.columns == ddf.columns).all() assert len(df) == len(ddf) def test_read_csv_sep(): sep_text = normalize_text(""" name###amount alice###100 bob###200 charlie###300""") with filetext(sep_text) as fn: ddf = dd.read_csv(fn, sep="###", engine="python") df = pd.read_csv(fn, sep="###", engine="python") assert (df.columns == ddf.columns).all() assert len(df) == len(ddf) def test_read_csv_slash_r(): data = b'0,my\n1,data\n' * 1000 + b'2,foo\rbar' with filetext(data, mode='wb') as fn: dd.read_csv(fn, header=None, sep=',', lineterminator='\n', names=['a', 'b'], blocksize=200).compute(scheduler='sync') def test_read_csv_singleton_dtype(): data = b'a,b\n1,2\n3,4\n5,6' with filetext(data, mode='wb') as fn: assert_eq(pd.read_csv(fn, dtype=float), dd.read_csv(fn, dtype=float)) def test_robust_column_mismatch(): files = csv_files.copy() k = sorted(files)[-1] files[k] = files[k].replace(b'name', b'Name') with filetexts(files, mode='b'): ddf = dd.read_csv('2014-01-*.csv') df = pd.read_csv('2014-01-01.csv') assert (df.columns == ddf.columns).all() assert_eq(ddf, ddf) def test_error_if_sample_is_too_small(): text = ('AAAAA,BBBBB,CCCCC,DDDDD,EEEEE\n' '1,2,3,4,5\n' '6,7,8,9,10\n' '11,12,13,14,15') with filetext(text) as fn: # Sample size stops mid header row sample = 20 with pytest.raises(ValueError): dd.read_csv(fn, sample=sample) # Saying no header means this is fine assert_eq(dd.read_csv(fn, sample=sample, header=None), pd.read_csv(fn, header=None)) skiptext = ('# skip\n' '# these\n' '# lines\n') text = skiptext + text with filetext(text) as fn: # Sample size stops mid header row sample = 20 + len(skiptext) with pytest.raises(ValueError): dd.read_csv(fn, sample=sample, skiprows=3) # Saying no header means this is fine assert_eq(dd.read_csv(fn, sample=sample, header=None, skiprows=3), pd.read_csv(fn, header=None, skiprows=3)) def test_read_csv_names_not_none(): text = ('Alice,100\n' 'Bob,-200\n' 'Charlie,300\n' 'Dennis,400\n' 'Edith,-500\n' 'Frank,600\n') names = ['name', 'amount'] with filetext(text) as fn: ddf = dd.read_csv(fn, names=names, blocksize=16) df = pd.read_csv(fn, names=names) assert_eq(df, ddf, check_index=False) ############ # to_csv # ############ def test_to_csv(): df = pd.DataFrame({'x': ['a', 'b', 'c', 'd'], 'y': [1, 2, 3, 4]}) for npartitions in [1, 2]: a = dd.from_pandas(df, npartitions) with tmpdir() as dn: a.to_csv(dn, index=False) result = dd.read_csv(os.path.join(dn, '*')).compute().reset_index(drop=True) assert_eq(result, df) with tmpdir() as dn: r = a.to_csv(dn, index=False, compute=False) dask.compute(*r, scheduler='sync') result = dd.read_csv(os.path.join(dn, '*')).compute().reset_index(drop=True) assert_eq(result, df) with tmpdir() as dn: fn = os.path.join(dn, 'data_*.csv') a.to_csv(fn, index=False) result = dd.read_csv(fn).compute().reset_index(drop=True) assert_eq(result, df) def test_to_csv_multiple_files_cornercases(): df = pd.DataFrame({'x': ['a', 'b', 'c', 'd'], 'y': [1, 2, 3, 4]}) a = dd.from_pandas(df, 2) with tmpdir() as dn: with pytest.raises(ValueError): fn = os.path.join(dn, "data_*_*.csv") a.to_csv(fn) df16 = pd.DataFrame({'x': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'], 'y': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]}) a = dd.from_pandas(df16, 16) with tmpdir() as dn: fn = os.path.join(dn, 'data_*.csv') a.to_csv(fn, index=False) result = dd.read_csv(fn).compute().reset_index(drop=True) assert_eq(result, df16) # test handling existing files when links are optimized out a = dd.from_pandas(df, 2) with tmpdir() as dn: a.to_csv(dn, index=False) fn = os.path.join(dn, 'data_*.csv') a.to_csv(fn, mode='w', index=False) result = dd.read_csv(fn).compute().reset_index(drop=True) assert_eq(result, df) # test handling existing files when links are optimized out a = dd.from_pandas(df16, 16) with tmpdir() as dn: a.to_csv(dn, index=False) fn = os.path.join(dn, 'data_*.csv') a.to_csv(fn, mode='w', index=False) result = dd.read_csv(fn).compute().reset_index(drop=True) assert_eq(result, df16) @pytest.mark.xfail(reason="to_csv does not support compression") def test_to_csv_gzip(): df = pd.DataFrame({'x': ['a', 'b', 'c', 'd'], 'y': [1, 2, 3, 4]}, index=[1., 2., 3., 4.]) for npartitions in [1, 2]: a = dd.from_pandas(df, npartitions) with tmpfile('csv') as fn: a.to_csv(fn, compression='gzip') result = pd.read_csv(fn, index_col=0, compression='gzip') tm.assert_frame_equal(result, df) def test_to_csv_simple(): df0 = pd.DataFrame({'x': ['a', 'b', 'c', 'd'], 'y': [1, 2, 3, 4]}, index=[1., 2., 3., 4.]) df = dd.from_pandas(df0, npartitions=2) with tmpdir() as dir: dir = str(dir) df.to_csv(dir) assert os.listdir(dir) result = dd.read_csv(os.path.join(dir, '*')).compute() assert (result.x.values == df0.x.values).all() def test_to_csv_series(): df0 = pd.Series(['a', 'b', 'c', 'd'], index=[1., 2., 3., 4.]) df = dd.from_pandas(df0, npartitions=2) with tmpdir() as dir: dir = str(dir) df.to_csv(dir) assert os.listdir(dir) result = dd.read_csv(os.path.join(dir, '*'), header=None, names=['x']).compute() assert (result.x == df0).all() def test_to_csv_with_get(): from dask.multiprocessing import get as mp_get flag = [False] def my_get(*args, **kwargs): flag[0] = True return mp_get(*args, **kwargs) df = pd.DataFrame({'x': ['a', 'b', 'c', 'd'], 'y': [1, 2, 3, 4]}) ddf = dd.from_pandas(df, npartitions=2) with tmpdir() as dn: ddf.to_csv(dn, index=False, get=my_get) assert flag[0] result = dd.read_csv(os.path.join(dn, '*')).compute().reset_index(drop=True) assert_eq(result, df) def test_to_csv_paths(): df = pd.DataFrame({"A": range(10)}) ddf = dd.from_pandas(df, npartitions=2) assert ddf.to_csv("foo*.csv") == ['foo0.csv', 'foo1.csv'] os.remove('foo0.csv') os.remove('foo1.csv')
gpl-3.0
jxta/cc
vendor/boto/boto/mashups/interactive.py
119
2737
# Copyright (C) 2003-2007 Robey Pointer <robey@lag.net> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at your option) # any later version. # # Paramiko is distrubuted in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with Paramiko; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. import socket import sys # windows does not have termios... try: import termios import tty has_termios = True except ImportError: has_termios = False def interactive_shell(chan): if has_termios: posix_shell(chan) else: windows_shell(chan) def posix_shell(chan): import select oldtty = termios.tcgetattr(sys.stdin) try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) chan.settimeout(0.0) while True: r, w, e = select.select([chan, sys.stdin], [], []) if chan in r: try: x = chan.recv(1024) if len(x) == 0: print '\r\n*** EOF\r\n', break sys.stdout.write(x) sys.stdout.flush() except socket.timeout: pass if sys.stdin in r: x = sys.stdin.read(1) if len(x) == 0: break chan.send(x) finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty) # thanks to Mike Looijmans for this code def windows_shell(chan): import threading sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n") def writeall(sock): while True: data = sock.recv(256) if not data: sys.stdout.write('\r\n*** EOF ***\r\n\r\n') sys.stdout.flush() break sys.stdout.write(data) sys.stdout.flush() writer = threading.Thread(target=writeall, args=(chan,)) writer.start() try: while True: d = sys.stdin.read(1) if not d: break chan.send(d) except EOFError: # user hit ^Z or F6 pass
apache-2.0
codeb2cc/kubernetes
examples/cluster-dns/images/backend/server.py
468
1313
#!/usr/bin/env python # Copyright 2015 The Kubernetes Authors All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer PORT_NUMBER = 8000 # This class will handles any incoming request. class HTTPHandler(BaseHTTPRequestHandler): # Handler for the GET requests def do_GET(self): self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write("Hello World!") try: # Create a web server and define the handler to manage the incoming request. server = HTTPServer(('', PORT_NUMBER), HTTPHandler) print 'Started httpserver on port ' , PORT_NUMBER server.serve_forever() except KeyboardInterrupt: print '^C received, shutting down the web server' server.socket.close()
apache-2.0
yangchandle/FlaskTaskr
env/lib/python3.5/site-packages/wtforms/ext/django/orm.py
177
6096
""" Tools for generating forms based on Django models. """ from wtforms import fields as f from wtforms import Form from wtforms import validators from wtforms.compat import iteritems from wtforms.ext.django.fields import ModelSelectField __all__ = ( 'model_fields', 'model_form', ) class ModelConverterBase(object): def __init__(self, converters): self.converters = converters def convert(self, model, field, field_args): kwargs = { 'label': field.verbose_name, 'description': field.help_text, 'validators': [], 'filters': [], 'default': field.default, } if field_args: kwargs.update(field_args) if field.blank: kwargs['validators'].append(validators.Optional()) if field.max_length is not None and field.max_length > 0: kwargs['validators'].append(validators.Length(max=field.max_length)) ftype = type(field).__name__ if field.choices: kwargs['choices'] = field.choices return f.SelectField(**kwargs) elif ftype in self.converters: return self.converters[ftype](model, field, kwargs) else: converter = getattr(self, 'conv_%s' % ftype, None) if converter is not None: return converter(model, field, kwargs) class ModelConverter(ModelConverterBase): DEFAULT_SIMPLE_CONVERSIONS = { f.IntegerField: ['AutoField', 'IntegerField', 'SmallIntegerField', 'PositiveIntegerField', 'PositiveSmallIntegerField'], f.DecimalField: ['DecimalField', 'FloatField'], f.FileField: ['FileField', 'FilePathField', 'ImageField'], f.DateTimeField: ['DateTimeField'], f.DateField: ['DateField'], f.BooleanField: ['BooleanField'], f.TextField: ['CharField', 'PhoneNumberField', 'SlugField'], f.TextAreaField: ['TextField', 'XMLField'], } def __init__(self, extra_converters=None, simple_conversions=None): converters = {} if simple_conversions is None: simple_conversions = self.DEFAULT_SIMPLE_CONVERSIONS for field_type, django_fields in iteritems(simple_conversions): converter = self.make_simple_converter(field_type) for name in django_fields: converters[name] = converter if extra_converters: converters.update(extra_converters) super(ModelConverter, self).__init__(converters) def make_simple_converter(self, field_type): def _converter(model, field, kwargs): return field_type(**kwargs) return _converter def conv_ForeignKey(self, model, field, kwargs): return ModelSelectField(model=field.rel.to, **kwargs) def conv_TimeField(self, model, field, kwargs): def time_only(obj): try: return obj.time() except AttributeError: return obj kwargs['filters'].append(time_only) return f.DateTimeField(format='%H:%M:%S', **kwargs) def conv_EmailField(self, model, field, kwargs): kwargs['validators'].append(validators.email()) return f.TextField(**kwargs) def conv_IPAddressField(self, model, field, kwargs): kwargs['validators'].append(validators.ip_address()) return f.TextField(**kwargs) def conv_URLField(self, model, field, kwargs): kwargs['validators'].append(validators.url()) return f.TextField(**kwargs) def conv_NullBooleanField(self, model, field, kwargs): from django.db.models.fields import NOT_PROVIDED def coerce_nullbool(value): d = {'None': None, None: None, 'True': True, 'False': False} if isinstance(value, NOT_PROVIDED): return None elif value in d: return d[value] else: return bool(int(value)) choices = ((None, 'Unknown'), (True, 'Yes'), (False, 'No')) return f.SelectField(choices=choices, coerce=coerce_nullbool, **kwargs) def model_fields(model, only=None, exclude=None, field_args=None, converter=None): """ Generate a dictionary of fields for a given Django model. See `model_form` docstring for description of parameters. """ converter = converter or ModelConverter() field_args = field_args or {} model_fields = ((f.attname, f) for f in model._meta.fields) if only: model_fields = (x for x in model_fields if x[0] in only) elif exclude: model_fields = (x for x in model_fields if x[0] not in exclude) field_dict = {} for name, model_field in model_fields: field = converter.convert(model, model_field, field_args.get(name)) if field is not None: field_dict[name] = field return field_dict def model_form(model, base_class=Form, only=None, exclude=None, field_args=None, converter=None): """ Create a wtforms Form for a given Django model class:: from wtforms.ext.django.orm import model_form from myproject.myapp.models import User UserForm = model_form(User) :param model: A Django ORM model class :param base_class: Base form class to extend from. Must be a ``wtforms.Form`` subclass. :param only: An optional iterable with the property names that should be included in the form. Only these properties will have fields. :param exclude: An optional iterable with the property names that should be excluded from the form. All other properties will have fields. :param field_args: An optional dictionary of field names mapping to keyword arguments used to construct each field object. :param converter: A converter to generate the fields based on the model properties. If not set, ``ModelConverter`` is used. """ field_dict = model_fields(model, only, exclude, field_args, converter) return type(model._meta.object_name + 'Form', (base_class, ), field_dict)
mit
aweosomeabhijeet/android_kernel_sony_xmd
tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/Core.py
11088
3246
# Core.py - Python extension for perf script, core functions # # Copyright (C) 2010 by Tom Zanussi <tzanussi@gmail.com> # # This software may be distributed under the terms of the GNU General # Public License ("GPL") version 2 as published by the Free Software # Foundation. from collections import defaultdict def autodict(): return defaultdict(autodict) flag_fields = autodict() symbolic_fields = autodict() def define_flag_field(event_name, field_name, delim): flag_fields[event_name][field_name]['delim'] = delim def define_flag_value(event_name, field_name, value, field_str): flag_fields[event_name][field_name]['values'][value] = field_str def define_symbolic_field(event_name, field_name): # nothing to do, really pass def define_symbolic_value(event_name, field_name, value, field_str): symbolic_fields[event_name][field_name]['values'][value] = field_str def flag_str(event_name, field_name, value): string = "" if flag_fields[event_name][field_name]: print_delim = 0 keys = flag_fields[event_name][field_name]['values'].keys() keys.sort() for idx in keys: if not value and not idx: string += flag_fields[event_name][field_name]['values'][idx] break if idx and (value & idx) == idx: if print_delim and flag_fields[event_name][field_name]['delim']: string += " " + flag_fields[event_name][field_name]['delim'] + " " string += flag_fields[event_name][field_name]['values'][idx] print_delim = 1 value &= ~idx return string def symbol_str(event_name, field_name, value): string = "" if symbolic_fields[event_name][field_name]: keys = symbolic_fields[event_name][field_name]['values'].keys() keys.sort() for idx in keys: if not value and not idx: string = symbolic_fields[event_name][field_name]['values'][idx] break if (value == idx): string = symbolic_fields[event_name][field_name]['values'][idx] break return string trace_flags = { 0x00: "NONE", \ 0x01: "IRQS_OFF", \ 0x02: "IRQS_NOSUPPORT", \ 0x04: "NEED_RESCHED", \ 0x08: "HARDIRQ", \ 0x10: "SOFTIRQ" } def trace_flag_str(value): string = "" print_delim = 0 keys = trace_flags.keys() for idx in keys: if not value and not idx: string += "NONE" break if idx and (value & idx) == idx: if print_delim: string += " | "; string += trace_flags[idx] print_delim = 1 value &= ~idx return string def taskState(state): states = { 0 : "R", 1 : "S", 2 : "D", 64: "DEAD" } if state not in states: return "Unknown" return states[state] class EventHeaders: def __init__(self, common_cpu, common_secs, common_nsecs, common_pid, common_comm): self.cpu = common_cpu self.secs = common_secs self.nsecs = common_nsecs self.pid = common_pid self.comm = common_comm def ts(self): return (self.secs * (10 ** 9)) + self.nsecs def ts_format(self): return "%d.%d" % (self.secs, int(self.nsecs / 1000))
gpl-2.0
pabloborrego93/edx-platform
common/djangoapps/student/tasks.py
8
1813
""" This file contains celery tasks for sending email """ import logging from django.conf import settings from django.core import mail from celery.task import task # pylint: disable=no-name-in-module, import-error from celery.exceptions import MaxRetriesExceededError from boto.exception import NoAuthHandlerFound log = logging.getLogger('edx.celery.task') @task(bind=True) def send_activation_email(self, subject, message, from_address, dest_addr): """ Sending an activation email to the users. """ max_retries = settings.RETRY_ACTIVATION_EMAIL_MAX_ATTEMPTS retries = self.request.retries try: mail.send_mail(subject, message, from_address, [dest_addr], fail_silently=False) # Log that the Activation Email has been sent to user without an exception log.info("Activation Email has been sent to User {user_email}".format( user_email=dest_addr )) except NoAuthHandlerFound: # pylint: disable=broad-except log.info('Retrying sending email to user {dest_addr}, attempt # {attempt} of {max_attempts}'. format( dest_addr=dest_addr, attempt=retries, max_attempts=max_retries )) try: self.retry(countdown=settings.RETRY_ACTIVATION_EMAIL_TIMEOUT, max_retries=max_retries) except MaxRetriesExceededError: log.error( 'Unable to send activation email to user from "%s" to "%s"', from_address, dest_addr, exc_info=True ) except Exception: # pylint: disable=bare-except log.exception( 'Unable to send activation email to user from "%s" to "%s"', from_address, dest_addr, exc_info=True ) raise Exception
agpl-3.0
shreyans800755/coala-bears
bears/swift/TailorBear.py
12
3895
import json from coalib.bearlib.abstractions.Linter import linter from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY from coalib.results.Result import Result from coalib.settings.Setting import path from dependency_management.requirements.DistributionRequirement import ( DistributionRequirement) @linter(executable='tailor', output_format=None, prerequisite_check_command=('tailor', '-v'), prerequisite_check_fail_message='Tailor is not installed. Refer ' 'https://tailor.sh/ for installation details.') class TailorBear: """ Analyze Swift code and check for code style related warning messages. For more information on the analysis visit <https://tailor.sh/> """ LANGUAGES = {'Swift'} REQUIREMENT = {DistributionRequirement(brew='tailor')} AUTHORS = {'The coala developers'} AUTHORS_EMAILS = {'coala-devel@googlegroups.com'} LICENSE = 'AGPL-3.0' ASCIINEMA_URL = 'https://asciinema.org/a/45666' CAN_DETECT = {'Formatting'} severity_map = {'warning': RESULT_SEVERITY.NORMAL, 'error': RESULT_SEVERITY.MAJOR} def process_output(self, output, filename, file): output = json.loads(output) for item in output['files'][0]['violations']: column = (item['location']['column'] if 'column' in item['location'].keys() else None) yield Result.from_values( origin='{} ({})'.format(self.name, item['rule']), message=item['message'], file=filename, line=item['location']['line'], column=column, severity=self.severity_map[item['severity']]) @staticmethod def create_arguments(filename, file, config_file, max_line_length: int=79, max_class_length: int=0, max_closure_length: int=0, max_file_length: int=0, max_function_length: int=0, max_name_length: int=0, max_struct_length: int=0, min_name_length: int=1, tailor_config: path=''): """ Bear configuration arguments. Using '0' will disable the check. :param max_line_length: maximum number of characters in a Line <0-999>. :param max_class_length: maximum number of lines in a Class <0-999>. :param max_closure_length: maximum number of lines in a Closure <0-999>. :param max_file_length: maximum number of lines in a File <0-999>. :param max_function_length: maximum number of lines in a Function <0-999>. :param max_name_length: maximum length of Identifier name <0-999>. :param max_struct_length: maximum number od lines in a Struct <0-999>. :param min_name_length: minimum number of characters in Identifier name <1-999>. :param tailor_config: path to Tailor configuration file. """ args = ('--format=json', '--max-line-length', str(max_line_length), '--max-class-length', str(max_class_length), '--max-closure-length', str(max_closure_length), '--max-file-length', str(max_file_length), '--max-function-length', str(max_function_length), '--max-name-length', str(max_name_length), '--max-struct-length', str(max_struct_length), '--min-name-length', str(min_name_length)) if tailor_config: args += ('--config=' + tailor_config,) return args + (filename,)
agpl-3.0
drikinukoda/android_kernel_lge_e8lte
tools/perf/scripts/python/futex-contention.py
11261
1486
# futex contention # (c) 2010, Arnaldo Carvalho de Melo <acme@redhat.com> # Licensed under the terms of the GNU GPL License version 2 # # Translation of: # # http://sourceware.org/systemtap/wiki/WSFutexContention # # to perf python scripting. # # Measures futex contention import os, sys sys.path.append(os.environ['PERF_EXEC_PATH'] + '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from Util import * process_names = {} thread_thislock = {} thread_blocktime = {} lock_waits = {} # long-lived stats on (tid,lock) blockage elapsed time process_names = {} # long-lived pid-to-execname mapping def syscalls__sys_enter_futex(event, ctxt, cpu, s, ns, tid, comm, nr, uaddr, op, val, utime, uaddr2, val3): cmd = op & FUTEX_CMD_MASK if cmd != FUTEX_WAIT: return # we don't care about originators of WAKE events process_names[tid] = comm thread_thislock[tid] = uaddr thread_blocktime[tid] = nsecs(s, ns) def syscalls__sys_exit_futex(event, ctxt, cpu, s, ns, tid, comm, nr, ret): if thread_blocktime.has_key(tid): elapsed = nsecs(s, ns) - thread_blocktime[tid] add_stats(lock_waits, (tid, thread_thislock[tid]), elapsed) del thread_blocktime[tid] del thread_thislock[tid] def trace_begin(): print "Press control+C to stop and show the summary" def trace_end(): for (tid, lock) in lock_waits: min, max, avg, count = lock_waits[tid, lock] print "%s[%d] lock %x contended %d times, %d avg ns" % \ (process_names[tid], tid, lock, count, avg)
gpl-2.0
snasoft/QtCreatorPluginsPack
Bin/3rdParty/vera/bin/lib/test/test_linuxaudiodev.py
133
3179
from test import test_support test_support.requires('audio') from test.test_support import findfile, run_unittest import errno import sys import audioop import unittest linuxaudiodev = test_support.import_module('linuxaudiodev', deprecated=True) sunaudio = test_support.import_module('sunaudio', deprecated=True) SND_FORMAT_MULAW_8 = 1 class LinuxAudioDevTests(unittest.TestCase): def setUp(self): self.dev = linuxaudiodev.open('w') def tearDown(self): self.dev.close() def test_methods(self): # at least check that these methods can be invoked self.dev.bufsize() self.dev.obufcount() self.dev.obuffree() self.dev.getptr() self.dev.fileno() def test_play_sound_file(self): path = findfile("audiotest.au") fp = open(path, 'r') size, enc, rate, nchannels, extra = sunaudio.gethdr(fp) data = fp.read() fp.close() if enc != SND_FORMAT_MULAW_8: self.fail("Expect .au file with 8-bit mu-law samples") # convert the data to 16-bit signed data = audioop.ulaw2lin(data, 2) # set the data format if sys.byteorder == 'little': fmt = linuxaudiodev.AFMT_S16_LE else: fmt = linuxaudiodev.AFMT_S16_BE # set parameters based on .au file headers self.dev.setparameters(rate, 16, nchannels, fmt) self.dev.write(data) self.dev.flush() def test_errors(self): size = 8 fmt = linuxaudiodev.AFMT_U8 rate = 8000 nchannels = 1 try: self.dev.setparameters(-1, size, nchannels, fmt) except ValueError, err: self.assertEqual(err.args[0], "expected rate >= 0, not -1") try: self.dev.setparameters(rate, -2, nchannels, fmt) except ValueError, err: self.assertEqual(err.args[0], "expected sample size >= 0, not -2") try: self.dev.setparameters(rate, size, 3, fmt) except ValueError, err: self.assertEqual(err.args[0], "nchannels must be 1 or 2, not 3") try: self.dev.setparameters(rate, size, nchannels, 177) except ValueError, err: self.assertEqual(err.args[0], "unknown audio encoding: 177") try: self.dev.setparameters(rate, size, nchannels, linuxaudiodev.AFMT_U16_LE) except ValueError, err: self.assertEqual(err.args[0], "for linear unsigned 16-bit little-endian " "audio, expected sample size 16, not 8") try: self.dev.setparameters(rate, 16, nchannels, fmt) except ValueError, err: self.assertEqual(err.args[0], "for linear unsigned 8-bit audio, expected " "sample size 8, not 16") def test_main(): try: dsp = linuxaudiodev.open('w') except linuxaudiodev.error, msg: if msg.args[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY): raise unittest.SkipTest(msg) raise dsp.close() run_unittest(LinuxAudioDevTests) if __name__ == '__main__': test_main()
lgpl-3.0
robdobsn/KitchenProjectorCalPhotoApp
src/PhotoFileManager.py
1
6094
import os from os.path import join import threading import time import random from PhotoInfo import PhotoInfo from collections import deque class PhotoFilelistUpdateThread(threading.Thread): theParent = None continueRunning = True validFileExtList = [] rootPath = "" listUpdatePeriodSecs = 3600 def __init__(self, parent, validFileExtList, rootPath, listUpdatePeriodSecs): threading.Thread.__init__(self) self.theParent = parent self.validFileExtList = validFileExtList self.rootPath = rootPath self.listUpdatePeriodSecs = listUpdatePeriodSecs def stop(self): self.continueRunning = False print("PhotoFileManager stop requested") def run(self): REPORT_AFTER_N_FOUND = 10000 while (self.continueRunning): quickInitialUpdate = True lastFileCount = 0 totalFileCount = 0 foldersWithJpegs = [] for root, dirs, files in os.walk(self.rootPath): if not self.continueRunning: break jpegCount = len([fname for fname in files if fname[-3:].lower() in self.validFileExtList]) if jpegCount > 0: foldersWithJpegs.append((root, jpegCount)) totalFileCount += jpegCount # Since this process can take a long time - let's get the ball rolling with the first few images found if quickInitialUpdate and totalFileCount > 1000: self.theParent.setNewList(foldersWithJpegs, totalFileCount) quickInitialUpdate = False if totalFileCount > lastFileCount + REPORT_AFTER_N_FOUND: print("PhotoFileManager: Found", totalFileCount, "photos") lastFileCount = totalFileCount if not self.continueRunning: break self.theParent.setNewList(foldersWithJpegs, totalFileCount) for sleepIdx in range(int(self.listUpdatePeriodSecs)): time.sleep(1) if not self.continueRunning: break if not self.continueRunning: break print("PhotoFileManager update thread stopped") class PhotoFileManager(): totalPhotoCount = 0 photoFolderList = [] curPhotoFilename = "" validFileExtList = [] rootPath = "" listUpdateThread = None listUpdateLock = threading.Lock() previousPhotoNames = deque() MAX_BACK_STEPS_ALLOWED = 100 curPhotoOffset = 0 def __init__(self, validFileExtList, rootPath, listUpdateInterval, photoDeltas): self.listUpdateInterval = listUpdateInterval self.validFileExtList = validFileExtList self.rootPath = rootPath self.photoDeltas = photoDeltas def startPhotoListUpdate(self): self.listUpdateThread = PhotoFilelistUpdateThread(self, self.validFileExtList, self.rootPath, self.listUpdateInterval) self.listUpdateThread.start() # print("List Update Started") def setRootPath(self, rootPath): self.rootPath = rootPath def setValidFileExts(self, validExts): self.validFileExtList = validExts def stop(self): # print("PFM stopped") if self.listUpdateThread != None: self.listUpdateThread.stop() def setNewList(self, folderList, totalCount): with self.listUpdateLock: self.photoFolderList = folderList self.totalPhotoCount = totalCount # print(folderList, totalCount) def getNumPhotos(self): return self.totalPhotoCount def getCurPhotoFilename(self): if self.curPhotoFilename == "": self.moveNext() return self.curPhotoFilename def getCurPhotoInfo(self): curFileName = self.getCurPhotoFilename() newPhotoInfo = PhotoInfo() newPhotoInfo.setFromFile(curFileName) self.photoDeltas.applyDeltasToPhotoInfo(curFileName, newPhotoInfo) return newPhotoInfo def moveNext(self): # Check if we're moving back to latest if self.curPhotoOffset > 0: self.curPhotoOffset -= 1 self.curPhotoFilename = self.previousPhotoNames[len(self.previousPhotoNames) - 1 - self.curPhotoOffset] print("ReMoved to " + self.curPhotoFilename) return with self.listUpdateLock: if self.totalPhotoCount > 0: photoIdx = random.randrange(0,self.totalPhotoCount-1) photoCtr = 0 for photoFolder in self.photoFolderList: if photoIdx < photoCtr + photoFolder[1]: # print (photoIdx, photoCtr, photoFolder[1]) try: fileList = os.listdir(photoFolder[0]) except: print("Failed to access folder " + photoFolder[0]) break for fname in fileList: if fname[-3:].lower() in self.validFileExtList: if photoCtr == photoIdx: self.curPhotoFilename = join(photoFolder[0], fname) while len(self.previousPhotoNames) > self.MAX_BACK_STEPS_ALLOWED: self.previousPhotoNames.popleft() self.previousPhotoNames.append(self.curPhotoFilename) print("Moved to " + self.curPhotoFilename) photoCtr += 1 break photoCtr += photoFolder[1] def movePrev(self): if self.curPhotoOffset >= len(self.previousPhotoNames)-1: return self.curPhotoOffset += 1 self.curPhotoFilename = self.previousPhotoNames[len(self.previousPhotoNames)-1-self.curPhotoOffset] print("Moved back to " + self.curPhotoFilename)
mit
mancoast/CPythonPyc_test
cpython/277_test_sundry.py
23
3036
"""Do a minimal test of all the modules that aren't otherwise tested.""" from test import test_support import sys import unittest class TestUntestedModules(unittest.TestCase): def test_at_least_import_untested_modules(self): with test_support.check_warnings(quiet=True): import CGIHTTPServer import audiodev import bdb import cgitb import code import compileall import distutils.bcppcompiler import distutils.ccompiler import distutils.cygwinccompiler import distutils.emxccompiler import distutils.filelist if sys.platform.startswith('win'): import distutils.msvccompiler import distutils.text_file import distutils.unixccompiler import distutils.command.bdist_dumb if sys.platform.startswith('win'): import distutils.command.bdist_msi import distutils.command.bdist import distutils.command.bdist_rpm import distutils.command.bdist_wininst import distutils.command.build_clib import distutils.command.build_ext import distutils.command.build import distutils.command.clean import distutils.command.config import distutils.command.install_data import distutils.command.install_egg_info import distutils.command.install_headers import distutils.command.install_lib import distutils.command.register import distutils.command.sdist import distutils.command.upload import encodings import formatter import getpass import htmlentitydefs import ihooks import imputil import keyword import linecache import mailcap import mimify import nntplib import nturl2path import opcode import os2emxpath import pdb import posixfile import pstats import py_compile import rexec import sched import sndhdr import statvfs import stringold import sunau import sunaudio import symbol import tabnanny import timeit import toaiff import token try: import tty # not available on Windows except ImportError: if test_support.verbose: print "skipping tty" # Can't test the "user" module -- if the user has a ~/.pythonrc.py, it # can screw up all sorts of things (esp. if it prints!). #import user import webbrowser import xml def test_main(): test_support.run_unittest(TestUntestedModules) if __name__ == "__main__": test_main()
gpl-3.0
iglpdc/nipype
nipype/interfaces/elastix/tests/test_auto_AnalyzeWarp.py
12
1187
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..registration import AnalyzeWarp def test_AnalyzeWarp_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), num_threads=dict(argstr='-threads %01d', nohash=True, ), output_path=dict(argstr='-out %s', mandatory=True, usedefault=True, ), terminal_output=dict(nohash=True, ), transform_file=dict(argstr='-tp %s', mandatory=True, ), ) inputs = AnalyzeWarp.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(inputs.traits()[key], metakey), value def test_AnalyzeWarp_outputs(): output_map = dict(disp_field=dict(), jacdet_map=dict(), jacmat_map=dict(), ) outputs = AnalyzeWarp.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(outputs.traits()[key], metakey), value
bsd-3-clause
wrboyce/hueman
hueman/entities.py
1
12196
from copy import copy from itertools import chain import json import re import requests import yaml from hueman.groups import GroupController class Controller(object): _attributes = { 'on': {}, 'bri': { 'preprocessor': 'int', 'min': 0, 'max': 255 }, 'hue': { 'preprocessor': 'int', 'min': 0, 'max': 65535, }, 'sat': { 'preprocessor': 'int', 'min': 0, 'max': 255, }, 'xy': {}, 'ct': { 'preprocessor': 'int', 'min': 153, 'max': 500, }, 'colormode': {}, 'transitiontime': { 'preprocessor': 'time', }, 'reachable': { 'readonly': True, }, 'alert': {}, 'effect': {}, ## Aliases 'brightness': 'bri', 'saturation': 'sat', 'cie': 'xy', 'temp': 'ct', 'time': 'transitiontime', 'colourmode': 'colormode', 'mode': 'colormode', } def __str__(self): return '<{0}(id={1}, name="{2}")>'.format(self.__class__.__name__, self.id, self.name) def __init__(self, bridge, id, name, cstate=None, nstate=None): self._bridge = bridge self.id = id self.name = name.replace(' ', '-').lower() self._cstate = cstate # current state self._nstate = nstate if nstate is not None else {} # next state if self._cstate is None: self._get_state() ## get/put state def _get_state(self): self._cstate = self._bridge._get('{0}/{1}/{2}'.format(self._endpoint, self.id, self._state_endpoint))['state'] def commit(self): """ Send any outstanding changes to the Endpoint. """ self._bridge._put('{0}/{1}/{2}'.format(self._endpoint, self.id, self._state_endpoint), self._nstate) self._cstate = self._nstate.copy() self._nstate = {} return self def reset(self): """ Drop any uncommitted changes. """ self._nstate = {} return self @property def state(self): """ Return the current state """ ## TODO only return relevant parts return self._cstate.copy() ## State/value juggling magic ## usage: controller.brightness() -> current_brightness ## controller.brightness(100) def __getattr__(self, key): """ Complex Logic be here... TODO: Document Me! """ ## First we check for a plugin if key in self._bridge._plugins: def pluginwrapper(*args, **kwargs): self._apply_plugin(key, *args, **kwargs) return self return pluginwrapper try: attr_cfg = Light._attributes[key] while isinstance(attr_cfg, str): key = attr_cfg attr_cfg = Light._attributes[attr_cfg] except KeyError: raise AttributeError("'{0}' object has no attribute '{1}'".format(self.__class__.__name__, key)) attr_cfg = attr_cfg.copy() attr_cfg['key'] = key ## Get the preprocessor, if one is defined preprocessor = attr_cfg.get('preprocessor', None) if isinstance(preprocessor, str): # strings map to self._pp_{preprocessor} preprocessor = getattr(self, '_pp_{0}'.format(preprocessor), None) elif not callable(preprocessor): # if not, wrap in a lambda so we can call blindly later preprocessor = lambda v, c: v ## Return a wrapper for getting/setting the attribute def gettersetter(new_val=None, commit=False): # noqa # print('{0}.{1}({2})'.format(self, key, new_val)) if new_val is None: return self._cstate[key] elif attr_cfg.get('readonly', False): raise ValueError("Attempted to set readonly value '{0}'".format(key)) self._nstate[key] = preprocessor(new_val, attr_cfg) if commit: self.commit() return self return gettersetter ## Preprocessors def _pp_int(self, val, cfg): """ Parse a numerical value, keeping it within a min/max range, and allowing percentage changes. """ min_val, max_val = cfg.get('min', 0), cfg.get('max', None) try: val = int(val) except ValueError: if not val.endswith('%'): raise change = None # absolute val = val[:-1] if val[0] in ('+', '-', '~'): change, val = val[0], val[1:] val = int(val) if change is None: if max_val is None: raise ValueError("Cannot set to a percentage of an unknown value!") val = (max_val * val) / 100 else: current_val = self._cstate[cfg['key']] diff = (current_val * val) / 100 if change == '-': # decrease by... val = (current_val - diff) if change == '+': # increase by... val = (current_val + diff) if change == '~': # relative (percentages only) val = diff if min_val is not None and val < min_val: val = min_val if max_val is not None and val > max_val: val = max_val return int(val) def _pp_time(self, val, _cfg): """ Parse a time from "shorthand" format: 10m, 30s, 1m30s. """ time = 0 try: time = float(val) except ValueError: if 'm' in val: mins, val = val.split('m') time += (float(mins) * 60) val = val.strip('s') if val: time += float(val) return (time * 10) def preset(self, name, commit=False): """ Load a preset state """ def _transition(presets): # Transitions have to be applied immediately [TODO] state-stack for transitions for data in presets: commit = False if data is not presets[-1]: data['time'] = 0 commit = True self._apply(data, commit) return self preset_data = self._bridge._preset(name) if isinstance(preset_data, list): return _transition(preset_data) return self._apply(preset_data, commit) def _apply(self, state, commit=False): for key, val in state.items(): getattr(self, key)(val) if commit: self.commit() return self def _apply_plugin(self, plugin_name, *args, **kwargs): self._bridge._plugins[plugin_name](self, *args, **kwargs) if kwargs.get('commit', False): self.commit() return self def _apply_command(self, command, commit=False): """ Parse a command into a state change, and optionally commit it. Commands can look like: * on * off * plugin name * plugin:arg * preset name * arg:val arg2:val2 * preset name arg:val arg2:val2 * arg:val preset name * arg:val preset name arg2:val2 """ preset, kvs = [], [] if isinstance(command, str): command = command.split(' ') for s in command: if s.startswith('_'): continue if ':' not in s: preset.append(s) else: kvs.append(s.split(':')) if preset: preset = ' '.join(preset) if preset == 'on': self.on(True) elif preset == 'off': self.on(False) else: self.preset(preset) if kvs: for k, v in kvs: if k not in self._attributes: for k2 in chain(self._attributes.keys(), self._bridge._plugins.keys()): if k2.startswith(k): k = k2 break getattr(self, k)(v) if commit: self.commit() return self class Group(Controller): """ Mostly useless currently, until we can create new Groups using the Hue API. """ _endpoint = 'groups' _state_endpoint = 'action' def light(self, name): """ Lookup a light by name, if name is None return all lights. """ if name is None: group = GroupController(name='{0}.light:{1}'.format(self.name, name)) group.add_members(self._lights) return group try: return self._lights[name] except KeyError: return None def lights(self, *names): if not names: return self.light(None) return [l for l in self._lights if l.name in names] class Light(Controller): """ A light, a bulb... The fundamental endpoint. """ _endpoint = 'lights' _state_endpoint = 'state' class Bridge(Group): def __str__(self): tmpl = '<Bridge(hostname="{0}", groups=[{1}], lights=[{2}]>' return tmpl.format(self._hostname, ', '.join([str(g) for g in self._groups]), ', '.join([str(l) for l in self._lights])) def __init__(self, hostname, username, groups={}, plugins={}, presets={}, scenes={}): self._bridge = self self.id = 0 # Group with id=0 is reserved for all lights in system (conveniently) self._hostname = self.name = hostname self._username = username self._get_lights() self._build_groups(groups) self._plugins = plugins self._presets = presets self._load_global_presets() self._cstate = {} self._nstate = {} def _get_lights(self): d = self._get('') self._lights = GroupController(name='[{0}].lights'.format(self.name)) for l_id, l_data in d.get('lights', {}).items(): self._lights.add_member(Light(self, l_id, l_data['name'].replace(' ', '-'), l_data.get('state', None))) def _build_groups(self, g_cfg): self._groups = GroupController(name='[{0}].groups'.format(self.name)) for g_name, g_lights in g_cfg.items(): g = GroupController(g_name) g.add_members(self.find(*g_lights)) self._groups.add_member(g) def _load_global_presets(self): try: cfg_file = open('hueman.yml').read() cfg_dict = yaml.load(cfg_file) self._presets = cfg_dict.get('presets', {}).update(self._presets) except IOError: pass def _preset(self, name): name = name.replace(' ', '_') return copy(self._presets[name]) def _get(self, path): return requests.get('http://{0}/api/{1}/{2}'.format(self._hostname, self._username, path)).json() def _put(self, path, data): return requests.put('http://{0}/api/{1}/{2}'.format(self._hostname, self._username, path), json.dumps(data)).json() def group(self, name): """ Lookup a group by name, if name is None return all groups. """ if name is None: return self._groups try: return self._groups[name] except KeyError: matches = [g for g in self._groups if g.name.startswith(name)] if len(matches) == 1: return matches[0] raise def find(self, *names): group = GroupController() for name in names: if isinstance(name, re._pattern_type): group.add_members(filter(lambda l: name.match(l.name) is not None, self._lights)) elif isinstance(name, str): try: group.add_member(self.group(name)) except KeyError: try: group.add_member(self.light(name)) except KeyError: pass return group
bsd-3-clause
anntzer/scipy
benchmarks/benchmarks/integrate.py
13
3247
import numpy as np from .common import Benchmark, safe_import from scipy.integrate import quad with safe_import(): import ctypes import scipy.integrate._test_multivariate as clib_test from scipy._lib import _ccallback_c with safe_import() as exc: from scipy import LowLevelCallable from_cython = LowLevelCallable.from_cython if exc.error: LowLevelCallable = lambda func, data: (func, data) from_cython = lambda *a: a with safe_import() as exc: import cffi if exc.error: cffi = None with safe_import(): from scipy.integrate import solve_bvp class SolveBVP(Benchmark): TOL = 1e-5 def fun_flow(self, x, y, p): A = p[0] return np.vstack(( y[1], y[2], 100 * (y[1] ** 2 - y[0] * y[2] - A), y[4], -100 * y[0] * y[4] - 1, y[6], -70 * y[0] * y[6] )) def bc_flow(self, ya, yb, p): return np.array([ ya[0], ya[1], yb[0] - 1, yb[1], ya[3], yb[3], ya[5], yb[5] - 1]) def time_flow(self): x = np.linspace(0, 1, 10) y = np.ones((7, x.size)) solve_bvp(self.fun_flow, self.bc_flow, x, y, p=[1], tol=self.TOL) def fun_peak(self, x, y): eps = 1e-3 return np.vstack(( y[1], -(4 * x * y[1] + 2 * y[0]) / (eps + x**2) )) def bc_peak(self, ya, yb): eps = 1e-3 v = (1 + eps) ** -1 return np.array([ya[0] - v, yb[0] - v]) def time_peak(self): x = np.linspace(-1, 1, 5) y = np.zeros((2, x.size)) solve_bvp(self.fun_peak, self.bc_peak, x, y, tol=self.TOL) def fun_gas(self, x, y): alpha = 0.8 return np.vstack(( y[1], -2 * x * y[1] * (1 - alpha * y[0]) ** -0.5 )) def bc_gas(self, ya, yb): return np.array([ya[0] - 1, yb[0]]) def time_gas(self): x = np.linspace(0, 3, 5) y = np.empty((2, x.size)) y[0] = 0.5 y[1] = -0.5 solve_bvp(self.fun_gas, self.bc_gas, x, y, tol=self.TOL) class Quad(Benchmark): def setup(self): from math import sin self.f_python = lambda x: sin(x) self.f_cython = from_cython(_ccallback_c, "sine") try: from scipy.integrate.tests.test_quadpack import get_clib_test_routine self.f_ctypes = get_clib_test_routine('_multivariate_sin', ctypes.c_double, ctypes.c_int, ctypes.c_double) except ImportError: lib = ctypes.CDLL(clib_test.__file__) self.f_ctypes = lib._multivariate_sin self.f_ctypes.restype = ctypes.c_double self.f_ctypes.argtypes = (ctypes.c_int, ctypes.c_double) if cffi is not None: voidp = ctypes.cast(self.f_ctypes, ctypes.c_void_p) address = voidp.value ffi = cffi.FFI() self.f_cffi = LowLevelCallable(ffi.cast("double (*)(int, double *)", address)) def time_quad_python(self): quad(self.f_python, 0, np.pi) def time_quad_cython(self): quad(self.f_cython, 0, np.pi) def time_quad_ctypes(self): quad(self.f_ctypes, 0, np.pi) def time_quad_cffi(self): quad(self.f_cffi, 0, np.pi)
bsd-3-clause
zetaops/ulakbus
ulakbus/lib/data_grid.py
1
12395
#!/usr/bin/env python # -*- coding: utf-8 -*- """ """ # Copyright (C) 2015 ZetaOps Inc. # # This file is licensed under the GNU General Public License v3 # (GPLv3). See LICENSE.txt for details. import base64 import csv from datetime import datetime from io import BytesIO from ulakbus.settings import DATA_GRID_PAGE_SIZE, DATE_DEFAULT_FORMAT from ulakbus.lib.common import get_file_url from pyoko.fields import DATE_FORMAT from ulakbus.lib.s3_file_manager import S3FileManager from zengine.lib.cache import Cache from zengine.lib.translation import gettext as _ from collections import OrderedDict __author__ = 'Anıl Can Aydın' class GridCache(Cache): """ """ PREFIX = "GRIDCACHE" def __init__(self, key): super(GridCache, self).__init__(":".join(['grid_cache', key])) class GridQueryCache(Cache): """ """ PREFIX = "GRIDQUERYCACHE" def __init__(self, key): super(GridQueryCache, self).__init__(":".join(['grid_query_cache', key])) class DataGrid(object): def __init__(self, cache_key, model, page, filter_params, sort_params, columns, selectors=None, cache=None, query_cache=None, **kwargs): self.model = model self.grid_cache = GridCache(cache_key) if not cache else cache(cache_key) self.grid_query_cache = GridQueryCache if not query_cache else query_cache self.grid_cache_data = self.grid_cache.get() or {} self.page = page self.filter_params = filter_params self.sort_params = sort_params self.columns = columns self.default_fields = kwargs.get('default_fields', []) self.column_types_dict = kwargs.get('column_types_dict', {}) self.selectors = selectors or self.grid_cache_data.get('selectors', self.prepare_selectors()) self.filter_conditions = { # STARTS_WITH 2: '__startswith', # ENDS_WITH 4: '__endswith', # EXACT 8: '', # CONTAINS 16: '__contains', # GREATER_THAN 32: '__gt', # GREATER_THAN OR EQUAL 64: '__gte', # LESS_THAN 128: '__lt', # LESS_THAN OR EQUAL 256: '__lte', # NOT_EQUAL 512: '' } self.select_fields = self.column_types_dict.get('select_fields', {}) self.multiselect_fields = self.column_types_dict.get('multiselect_fields', {}) self.range_date_fields = self.column_types_dict.get('range_date_fields', []) self.field_filter_type_map = self.grid_cache_data.get('field_filter_type_map', {}) self.select_options_dict = self.grid_cache_data.get('select_options_dict', {}) self.column_defs = self.grid_cache_data.get('column_defs', self.prepare_column_defs()) self.grid_cache.set( { 'selectors': self.selectors, 'column_defs': self.column_defs, 'field_filter_type_map': self.field_filter_type_map, 'select_options_dict': self.select_options_dict } ) def prepare_column_defs(self): contains_fields = self.column_types_dict.get('contains_fields', []) ends_fields = self.column_types_dict.get('ends_fields', []) starts_fields = self.column_types_dict.get('starts_fields', []) range_num_fields = self.column_types_dict.get('range_num_fields', []) column_defs = [] for col, label in self.columns.items(): col_def = {} col_def['field'] = col if col in contains_fields: col_def['type'] = "INPUT" col_def['filter'] = { 'condition': "CONTAINS", 'placeholder': _(u"İçeren") } self.field_filter_type_map[col] = "INPUT" elif col in ends_fields: col_def['type'] = "INPUT" col_def['filter'] = { 'condition': "ENDS_WITH", 'placeholder': _(u"Biten") } self.field_filter_type_map[col] = "INPUT" elif col in starts_fields: col_def['type'] = "INPUT" col_def['filter'] = { 'condition': "STARTS_WITH", 'placeholder': _(u"Başlayan") } self.field_filter_type_map[col] = "INPUT" elif col in self.select_fields: col_def['type'] = 'SELECT' col_def['filter'] = { 'selectOptions': self.select_fields[col] } self.field_filter_type_map[col] = "SELECT" self.select_options_dict[col] = self._swith_to_dict_from_select_options( self.select_fields[col]) elif col in self.multiselect_fields: col_def['type'] = 'MULTISELECT' col_def['filter'] = { 'selectOptions': self.multiselect_fields[col] } self.field_filter_type_map[col] = "MULTISELECT" self.select_options_dict[col] = self._swith_to_dict_from_select_options( self.multiselect_fields[col]) elif col in self.range_date_fields: col_def['type'] = 'range' col_def['rangeType'] = 'datetime' filter_s = { 'condition': "START", 'placeholder': _(u"Başlangıç") } filter_e = { 'condition': "END", 'placeholder': _(u"Bitiş") } col_def['filters'] = [filter_s, filter_e] self.field_filter_type_map[col] = "RANGE-DATETIME" elif col in range_num_fields: col_def['type'] = "range" col_def['rangeType'] = "integer" filter_s = { 'condition': "MAX", 'placeholder': _(u"En çok") } filter_e = { 'condition': "MIN", 'placeholder': _(u"En az") } col_def['filters'] = [filter_s, filter_e] self.field_filter_type_map[col] = "RANGE-INTEGER" column_defs.append(col_def) return column_defs def prepare_selectors(self): selectors = [] for col, lbl in self.columns.items(): select = { 'name': col, 'label': lbl, 'checked': True if col in self.default_fields else False } selectors.append(select) return selectors def build_response(self): import json import hashlib cache_key = hashlib.sha256( "%s%s%s%s" % ( self.page, json.dumps(self.filter_params), json.dumps(self.sort_params), json.dumps(self.selectors), ) ).hexdigest() cache_key = hashlib.sha256(cache_key).hexdigest() query_cache = self.grid_query_cache(cache_key) cached_response = query_cache.get() if cached_response: return cached_response else: is_more_data_left, data = self.prepare_data() response = { 'gridOptions': { 'applyFilter': "Filtrele", 'cancelFilter': "Filtreleri Temizle", 'csvDownload': "Dışa Aktar", 'dataLoading': "Yükleniyor", 'selectColumns': "Kolon Seç", 'enableSorting': True, 'enableFiltering': True, 'toggleFiltering': True, 'enableRemoving': True, 'isMoreDataLeft': is_more_data_left, 'selectors': self.selectors, 'column_defs': self.column_defs, 'data': data } } return query_cache.set(response) def grid_query_parser(self): query_params = {} sort_params = [] fc = self.filter_conditions for element in self.filter_params: f = element['columnName'] qp = element['filterParam'] if qp: if self.field_filter_type_map[f] == "INPUT": query_params[f + fc.get(qp[0]['condition'])] = qp[0]['value'].lower() elif self.field_filter_type_map[f] == "SELECT": query_params[f] = qp[0]['value'] elif self.field_filter_type_map[f] == "MULTISELECT": multiselect_list = qp[0]['value'] query_params[f + "__in"] = multiselect_list else: start = end = "" for item in qp: if fc[item['condition']] == '__gt': start = item['value'] if fc[item['condition']] == '__lt': end = item['value'] if self.field_filter_type_map[f] == "RANGE-DATETIME": start = datetime.strptime(start, DATE_DEFAULT_FORMAT) end = datetime.strptime(end, DATE_DEFAULT_FORMAT) else: start, end = int(start, end) query_params[f + '__range'] = [start, end] for col in self.sort_params: if col['order'] == 'desc': sort_params.append("%s%s" % ("-", col['columnName'])) else: sort_params.append(col['columnName']) return query_params, sort_params def prepare_data(self, csv=False): page_size = DATA_GRID_PAGE_SIZE query_params, sort_params = self.grid_query_parser() active_columns = [] for col in self.selectors: if col['checked']: active_columns.append(col['name']) data_size = self.model.objects.all(**query_params).count() if not csv: qs = self.model.objects.set_params(start=(self.page - 1) * page_size, rows=page_size) else: qs = self.model.objects data_to_return = [] for data, key in qs.all(**query_params).order_by(*sort_params).data(): d = OrderedDict() for ac in active_columns: if ac in self.select_fields or ac in self.multiselect_fields: d[ac] = self.select_options_dict[ac][str(data[ac])] elif ac in self.range_date_fields: d[ac] = datetime.strftime( datetime.strptime(data[ac], DATE_FORMAT).date(), DATE_DEFAULT_FORMAT) else: d[ac] = data[ac] data_to_return.append(d) is_more_data_left = data_size / page_size > (self.page - 1) return is_more_data_left, data_to_return def generate_csv_link(self): output = BytesIO() csv_writer = csv.writer(output, delimiter=';', quotechar="'", quoting=csv.QUOTE_MINIMAL) is_more_data_left, data = self.prepare_data(csv=True) count = 0 for emp in data: if count == 0: header = emp.keys() csv_writer.writerow(header) count += 1 csv_writer.writerow(emp.values()) download_url = self._generate_temp_file( name=self._generate_file_name(), content=base64.b64encode(output.getvalue()), file_type='text/csv', ext='csv' ) return download_url @staticmethod def _generate_temp_file(name, content, file_type, ext): f = S3FileManager() key = f.store_file(name=name, content=content, type=file_type, ext=ext) return get_file_url(key) def _generate_file_name(self): return "%s-%s-%s" % (self.model().get_verbose_name(), _(u"rapor"), datetime.now().strftime( "%d.%m.%Y-%H.%M.%S")) @staticmethod def _swith_to_dict_from_select_options(sel_opts): sd = {} for so in sel_opts: sd[str(so['value'])] = so['label'] return sd
gpl-3.0
hackedhead/django-taggit-autosuggest
demo_project/demo_project/wsgi.py
3
1146
""" WSGI config for demo_project project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo_project.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
mit
samzhang111/scikit-learn
sklearn/manifold/tests/test_isomap.py
226
3941
from itertools import product import numpy as np from numpy.testing import assert_almost_equal, assert_array_almost_equal from sklearn import datasets from sklearn import manifold from sklearn import neighbors from sklearn import pipeline from sklearn import preprocessing from sklearn.utils.testing import assert_less eigen_solvers = ['auto', 'dense', 'arpack'] path_methods = ['auto', 'FW', 'D'] def test_isomap_simple_grid(): # Isomap should preserve distances when all neighbors are used N_per_side = 5 Npts = N_per_side ** 2 n_neighbors = Npts - 1 # grid of equidistant points in 2D, n_components = n_dim X = np.array(list(product(range(N_per_side), repeat=2))) # distances from each point to all others G = neighbors.kneighbors_graph(X, n_neighbors, mode='distance').toarray() for eigen_solver in eigen_solvers: for path_method in path_methods: clf = manifold.Isomap(n_neighbors=n_neighbors, n_components=2, eigen_solver=eigen_solver, path_method=path_method) clf.fit(X) G_iso = neighbors.kneighbors_graph(clf.embedding_, n_neighbors, mode='distance').toarray() assert_array_almost_equal(G, G_iso) def test_isomap_reconstruction_error(): # Same setup as in test_isomap_simple_grid, with an added dimension N_per_side = 5 Npts = N_per_side ** 2 n_neighbors = Npts - 1 # grid of equidistant points in 2D, n_components = n_dim X = np.array(list(product(range(N_per_side), repeat=2))) # add noise in a third dimension rng = np.random.RandomState(0) noise = 0.1 * rng.randn(Npts, 1) X = np.concatenate((X, noise), 1) # compute input kernel G = neighbors.kneighbors_graph(X, n_neighbors, mode='distance').toarray() centerer = preprocessing.KernelCenterer() K = centerer.fit_transform(-0.5 * G ** 2) for eigen_solver in eigen_solvers: for path_method in path_methods: clf = manifold.Isomap(n_neighbors=n_neighbors, n_components=2, eigen_solver=eigen_solver, path_method=path_method) clf.fit(X) # compute output kernel G_iso = neighbors.kneighbors_graph(clf.embedding_, n_neighbors, mode='distance').toarray() K_iso = centerer.fit_transform(-0.5 * G_iso ** 2) # make sure error agrees reconstruction_error = np.linalg.norm(K - K_iso) / Npts assert_almost_equal(reconstruction_error, clf.reconstruction_error()) def test_transform(): n_samples = 200 n_components = 10 noise_scale = 0.01 # Create S-curve dataset X, y = datasets.samples_generator.make_s_curve(n_samples, random_state=0) # Compute isomap embedding iso = manifold.Isomap(n_components, 2) X_iso = iso.fit_transform(X) # Re-embed a noisy version of the points rng = np.random.RandomState(0) noise = noise_scale * rng.randn(*X.shape) X_iso2 = iso.transform(X + noise) # Make sure the rms error on re-embedding is comparable to noise_scale assert_less(np.sqrt(np.mean((X_iso - X_iso2) ** 2)), 2 * noise_scale) def test_pipeline(): # check that Isomap works fine as a transformer in a Pipeline # only checks that no error is raised. # TODO check that it actually does something useful X, y = datasets.make_blobs(random_state=0) clf = pipeline.Pipeline( [('isomap', manifold.Isomap()), ('clf', neighbors.KNeighborsClassifier())]) clf.fit(X, y) assert_less(.9, clf.score(X, y))
bsd-3-clause
nathana1/FrameworkBenchmarks
toolset/benchmark/fortune_html_parser.py
20
7205
# -*- coding: utf-8 import re from HTMLParser import HTMLParser from difflib import unified_diff class FortuneHTMLParser(HTMLParser): body = [] valid = '''<!doctype html><html> <head><title>Fortunes</title></head> <body><table> <tr><th>id</th><th>message</th></tr> <tr><td>11</td><td>&lt;script&gt;alert(&quot;This should not be displayed in a browser alert box.&quot;);&lt;/script&gt;</td></tr> <tr><td>4</td><td>A bad random number generator: 1, 1, 1, 1, 1, 4.33e+67, 1, 1, 1</td></tr> <tr><td>5</td><td>A computer program does what you tell it to do, not what you want it to do.</td></tr> <tr><td>2</td><td>A computer scientist is someone who fixes things that aren&apos;t broken.</td></tr> <tr><td>8</td><td>A list is only as strong as its weakest link. — Donald Knuth</td></tr> <tr><td>0</td><td>Additional fortune added at request time.</td></tr> <tr><td>3</td><td>After enough decimal places, nobody gives a damn.</td></tr> <tr><td>7</td><td>Any program that runs right is obsolete.</td></tr> <tr><td>10</td><td>Computers make very fast, very accurate mistakes.</td></tr> <tr><td>6</td><td>Emacs is a nice operating system, but I prefer UNIX. — Tom Christaensen</td></tr> <tr><td>9</td><td>Feature: A bug with seniority.</td></tr> <tr><td>1</td><td>fortune: No such file or directory</td></tr> <tr><td>12</td><td>フレームワークのベンチマーク</td></tr> </table></body></html>''' # Is called when a doctype or other such tag is read in. # For our purposes, we assume this is only going to be # "DOCTYPE html", so we will surround it with "<!" and ">". def handle_decl(self, decl): # The spec says that for HTML this is case insensitive, # and since we did not specify xml compliance (where # incorrect casing would throw a syntax error), we must # allow all casings. We will lower for our normalization. self.body.append("<!{d}>".format(d=decl.lower())) # This is called when an HTML character is parsed (i.e. # &quot;). There are a number of issues to be resolved # here. For instance, some tests choose to leave the # "+" character as-is, which should be fine as far as # character escaping goes, but others choose to use the # character reference of "&#43;", which is also fine. # Therefore, this method looks for all possible character # references and normalizes them so that we can # validate the input against a single valid spec string. # Another example problem: "&quot;" is valid, but so is # "&#34;" def handle_charref(self, name): val = name.lower() # "&#34;" is a valid escaping, but we are normalizing # it so that our final parse can just be checked for # equality. if val == "34" or val == "034" or val == "x22": # Append our normalized entity reference to our body. self.body.append("&quot;") # "&#39;" is a valid escaping of "-", but it is not # required, so we normalize for equality checking. if val == "39" or val == "039" or val == "x27": self.body.append("&apos;") # Again, "&#43;" is a valid escaping of the "+", but # it is not required, so we need to normalize for out # final parse and equality check. if val == "43" or val == "043" or val == "x2b": self.body.append("+") # Again, "&#62;" is a valid escaping of ">", but we # need to normalize to "&gt;" for equality checking. if val == "62" or val == "062" or val == "x3e": self.body.append("&gt;") # Again, "&#60;" is a valid escaping of "<", but we # need to normalize to "&lt;" for equality checking. if val == "60" or val == "060" or val == "x3c": self.body.append("&lt;") # Not sure why some are escaping '/' if val == "47" or val == "047" or val == "x2f": self.body.append("/") # "&#40;" is a valid escaping of "(", but # it is not required, so we need to normalize for out # final parse and equality check. if val == "40" or val == "040" or val == "x28": self.body.append("(") # "&#41;" is a valid escaping of ")", but # it is not required, so we need to normalize for out # final parse and equality check. if val == "41" or val == "041" or val == "x29": self.body.append(")") def handle_entityref(self, name): # Again, "&mdash;" is a valid escaping of "—", but we # need to normalize to "—" for equality checking. if name == "mdash": self.body.append("—") else: self.body.append("&{n};".format(n=name)) # This is called every time a tag is opened. We append # each one wrapped in "<" and ">". def handle_starttag(self, tag, attrs): self.body.append("<{t}>".format(t=tag)) # Append a newline after the <table> and <html> if tag.lower() == 'table' or tag.lower() == 'html': self.body.append("\n") # This is called whenever data is presented inside of a # start and end tag. Generally, this will only ever be # the contents inside of "<td>" and "</td>", but there # are also the "<title>" and "</title>" tags. def handle_data (self, data): if data.strip() != '': # After a LOT of debate, these are now considered # valid in data. The reason for this approach is # because a few tests use tools which determine # at compile time whether or not a string needs # a given type of html escaping, and our fortune # test has apostrophes and quotes in html data # rather than as an html attribute etc. # example: # <td>A computer scientist is someone who fixes things that aren't broken.</td> # Semanticly, that apostrophe does not NEED to # be escaped. The same is currently true for our # quotes. # In fact, in data (read: between two html tags) # even the '>' need not be replaced as long as # the '<' are all escaped. # We replace them with their escapings here in # order to have a noramlized string for equality # comparison at the end. data = data.replace('\'', '&apos;') data = data.replace('"', '&quot;') data = data.replace('>', '&gt;') self.body.append("{d}".format(d=data)) # This is called every time a tag is closed. We append # each one wrapped in "</" and ">". def handle_endtag(self, tag): self.body.append("</{t}>".format(t=tag)) # Append a newline after each </tr> and </head> if tag.lower() == 'tr' or tag.lower() == 'head': self.body.append("\n") # Returns whether the HTML input parsed by this parser # is valid against our known "fortune" spec. # The parsed data in 'body' is joined on empty strings # and checked for equality against our spec. def isValidFortune(self, out): body = ''.join(self.body) same = self.valid == body diff_lines = [] if not same: out.write("Oh no! I compared %s\n\n\nto.....%s" % (self.valid, body)) out.write("Fortune invalid. Diff following:\n") headers_left = 3 for line in unified_diff(self.valid.split('\n'), body.split('\n'), fromfile='Valid', tofile='Response', n=0): diff_lines.append(line) out.write(line) headers_left -= 1 if headers_left <= 0: out.write('\n') return (same, diff_lines)
bsd-3-clause