code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
tinyMCE.addToLang('table',{ general_tab : 'Chung', advanced_tab : 'Nâng cao', general_props : 'Thuộc tính chung', advanced_props : 'Thuộc tính nâng cao', desc : 'Thêm một bảng mới', row_before_desc : 'Thêm hàng trước', row_after_desc : 'Thêm hàng sau', delete_row_desc : 'Xóa hàng', col_before_desc : 'Thêm cột bên trái', col_after_desc : 'Thêm cột bên phải', delete_col_desc : 'Xóa cột', rowtype : 'Hàng trong một phần bảng', title : 'Thêm/Sửa bảng', width : 'Độ rộng', height : 'Chiều cao', cols : 'Cột', rows : 'Hàng', cellspacing : 'Khoảng cách ô', cellpadding : 'Căn lề ô', border : 'Khung bao quanh', align : 'Căn lề', align_default : 'Mặc định', align_left : 'Trái', align_right : 'Phải', align_middle : 'Giữa', row_title : 'Thuộc tính hàng', cell_title : 'Thuộc tính ô', cell_type : 'Kiểu ô', row_desc : 'Thuộc tính hàng', cell_desc : 'Thuộc tính ô', valign : 'Căn lề chiều dọc', align_top : 'Trên cùng', align_bottom : 'Dưới cùng', props_desc : 'Thuộc tính bảng', bordercolor : 'Màu khung', bgcolor : 'Màu nền', merge_cells_title : 'Trộn ô', split_cells_desc : 'Tách ô', merge_cells_desc : 'Trộn ô', cut_row_desc : 'Cắt hàng của bảng', copy_row_desc : 'Sao chép hàng của bảng', paste_row_before_desc : 'Dán hàng lên trên', paste_row_after_desc : 'Dán hàng xuống dưới', id : 'Id', style: 'Style', langdir : 'Hướng ngôn ngữ', langcode : 'Mã ngôn ngữ', mime : 'Kiểu MIME mục tiêu', ltr : 'Trái sang phải', rtl : 'Phải sang trái', bgimage : 'Ảnh nền', summary : 'Tóm tắt', td : "Dữ liệu", th : "Tiêu đề", cell_cell : 'Cập nhật ô hiện thời', cell_row : 'Cập nhật tất cả các ô trong hàng', cell_all : 'Cập nhật tất cả các ô trong bảng', row_row : 'Cập nhật hàng hiện thời', row_odd : 'Cập nhật các hàng lẻ trong bảng', row_even : 'Cập nhật các hàng chẵn trong bảng', row_all : 'Cập nhật tất cả các hàng trong bảng', thead : 'Đầu bảng', tbody : 'Thân bảng', tfoot : 'Chân bảng', del : 'Xóa bảng', scope : 'Phạm vi', row : 'Hàng', col : 'Cột', rowgroup : 'Nhóm hàng', colgroup : 'Nhóm cột', missing_scope: 'Bạn có chắc bạn muốn tiếp tục mà không cần xác định phạm vi cho ô tiêu đề bảng này? Nếu thiếu nó, có thể những người sử dụng khuyết thiếu sẽ khó có thể hiểu nội dung của dữ liệu trong bảng.' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/vi.js
vi.js
tinyMCE.addToLang('table',{ general_tab : 'General', advanced_tab : 'Advanced', general_props : 'General properties', advanced_props : 'Advanced properties', desc : 'Inserts a new table', row_before_desc : 'Insert row before', row_after_desc : 'Insert row after', delete_row_desc : 'Delete row', col_before_desc : 'Insert column before', col_after_desc : 'Insert column after', delete_col_desc : 'Remove column', rowtype : 'Row in table part', title : 'Insert/Modify table', width : 'Width', height : 'Height', cols : 'Columns', rows : 'Rows', cellspacing : 'Cellspacing', cellpadding : 'Cellpadding', border : 'Border', align : 'Alignment', align_default : 'Default', align_left : 'Left', align_right : 'Right', align_middle : 'Center', row_title : 'Table row properties', cell_title : 'Table cell properties', cell_type : 'Cell type', row_desc : 'Table row properties', cell_desc : 'Table cell properties', valign : 'Vertical alignment', align_top : 'Top', align_bottom : 'Bottom', props_desc : 'Table properties', bordercolor : 'Border color', bgcolor : 'Background color', merge_cells_title : 'Merge table cells', split_cells_desc : 'Split table cells', merge_cells_desc : 'Merge table cells', cut_row_desc : 'Cut table row', copy_row_desc : 'Copy table row', paste_row_before_desc : 'Paste table row before', paste_row_after_desc : 'Paste table row after', id : 'Id', style: 'Style', langdir : 'Language direction', langcode : 'Language code', mime : 'Target MIME type', ltr : 'Left to right', rtl : 'Right to left', bgimage : 'Background image', summary : 'Summary', td : "Data", th : "Header", cell_cell : 'Update current cell', cell_row : 'Update all cells in row', cell_all : 'Update all cells in table', row_row : 'Update current row', row_odd : 'Update odd rows in table', row_even : 'Update even rows in table', row_all : 'Update all rows in table', thead : 'Table Head', tbody : 'Table Body', tfoot : 'Table Foot', del : 'Delete table', scope : 'Scope', row : 'Row', col : 'Col', rowgroup : 'Row Group', colgroup : 'Col Group', col_limit : 'You\'ve exceeded the maximum number of columns of {$cols}.', row_limit : 'You\'ve exceeded the maximum number of rows of {$rows}.', cell_limit : 'You\'ve exceeded the maximum number of cells of {$cells}.', missing_scope: 'Are you sure you want to continue without specifying a scope for this table header cell. Without it, it may be difficult for some users with disabilities to understand the content or data displayed of the table.' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/en.js
en.js
tinyMCE.addToLang('table',{ general_tab : 'Cyffredinol', advanced_tab : 'Uwch', general_props : 'Priodoleddau cyffredinol', advanced_props : 'Priodoleddau uwch', desc : 'Mewnosod tabl newydd', row_before_desc : 'Mewnosod rhes cyn', row_after_desc : 'Mewnosod rhes ar ôl', delete_row_desc : 'Dileu rhes', col_before_desc : 'Mewnosod colofn cyn', col_after_desc : 'Mewnosod colofn ar ôl', delete_col_desc : 'Dileu colofn', rowtype : 'Rhan tabl y rhes', title : 'Mewnosod/golygu tabl', width : 'Lled', height : 'Uchder', cols : 'Colofnau', rows : 'Rhesi', cellspacing : 'Bylchu celloedd', cellpadding : 'Padio celliodd', border : 'Ffin', align : 'Unioni', align_default : 'Arferol', align_left : 'Chwith', align_right : 'Dde', align_middle : 'Canol', row_title : 'Priodoleddau rhes tabl', cell_title : 'Priodoleddau cell tabl', cell_type : 'Math cell', row_desc : 'Priodoleddau rhes tabl', cell_desc : 'Priodoleddau cell tabl', valign : 'Unioni fertigol', align_top : 'Brig', align_bottom : 'Gwaelod', props_desc : 'Priodoleddau tabl', bordercolor : 'Lliw ffin', bgcolor : 'Lliw cefndir', merge_cells_title : 'Uno celloedd tabl', split_cells_desc : 'Rhannu celloedd tabl', merge_cells_desc : 'Uno celloedd tabl', cut_row_desc : 'Torri rhes tabl', copy_row_desc : 'Copïo rhes tabl', paste_row_before_desc : 'Gludo rhes tabl cyn', paste_row_after_desc : 'Gludo rhes tabl ar ôl', id : 'Id', style: 'Arddull', langdir : 'Cyfeiriad iaith', langcode : 'Côd iaith', mime : 'Math MIME y targed', ltr : 'Chwith i\'r dde', rtl : 'Dde i\'r chwith', bgimage : 'Delwedd cefndir', summary : 'Crynodeb', td : "Data", th : "Pennawd", cell_cell : 'Diweddaru\'r gell bresennoll', cell_row : 'Diweddaru holl gelloedd y rhes', cell_all : 'Diweddaru holl gelloedd y tabl', row_row : 'Diweddaru\'r rhes presennol', row_odd : 'Diweddaru rhesi odrif y tabl', row_even : 'Diweddaru rhesi eilrif y tabl', row_all : 'Diweddaru holl rhesi\'r tabl', thead : 'Pennawd Tabl', tbody : 'Corff Tabl', tfoot : 'Troedyn Tabl', del : 'Dileu tabl', scope : 'Maes', row : 'Rhes', col : 'Colofn', rowgroup : 'Grŵp Rhesi', colgroup : 'Grŵp Colofnau', missing_scope: 'Wyt ti\'n sicr eisiau parhau heb gynnwys maes ar gyfer y cell pennawd tabl hwn? Heb un, gallai fod yn anodd i rai defnyddwyr gydag anableddau ddeall cynnwys neu ddata y tabl.', cellprops_delta_width : 50 });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/cy.js
cy.js
tinyMCE.addToLang('table',{ general_tab : 'Algemeen', advanced_tab : 'Geavanceerd', general_props : 'Algemene eigenschappen', advanced_props : 'Geavanceerde eigenschappen', desc : 'Nieuwe tabel invoegen', row_before_desc : 'Rij boven invoegen', row_after_desc : 'Rij onder invoegen', delete_row_desc : 'Rij verwijderen', col_before_desc : 'Kolom links invoegen', col_after_desc : 'Kolom rechts invoegen', delete_col_desc : 'Kolom verwijderen', rowtype : 'Row in table part', title : 'Tabel invoegen/bewerken', width : 'Breedte', height : 'Hoogte', cols : 'Kolommen', rows : 'Rijen', cellspacing : 'Ruimte om cel', cellpadding : 'Ruimte in cel', border : 'Rand', align : 'Uitlijning', align_default : 'Standaard', align_left : 'Links', align_right : 'Rechts', align_middle : 'Centreren', row_title : 'Tabelrij-eigenschappen', cell_title : 'Tabelcel-eigenschappen', cell_type : 'Celtype', row_desc : 'Tabelrij-eigenschappen', cell_desc : 'Tabelcel-eigenschappen', valign : 'Verticale uitlijning', align_top : 'Boven', align_bottom : 'Onder', props_desc : 'Tabeleigenschappen', bordercolor : 'Randkleur', bgcolor : 'Achtergrondkleur', merge_cells_title : 'Tabelcellen samenvoegen', split_cells_desc : 'Tabelcellen splitsen', merge_cells_desc : 'Tabelcellen samenvoegen', cut_row_desc : 'Tabelrij knippen', copy_row_desc : 'Tebelrij kopiëren', paste_row_before_desc : 'Tabelrij boven plakken', paste_row_after_desc : 'tabelrij onder plakken', id : 'Id', style: 'Stijl', langdir : 'Taalrichting', langcode : 'Taalcode', mime : 'MIME type', ltr : 'Links naar rechts', rtl : 'Rechts naar links', bgimage : 'Achtergrondafbeelding', summary : 'Samenvatting', td : "Data", th : "Kop", cell_cell : 'Huidige cel bijwerken', cell_row : 'Alle cellen in rij bijwerken', cell_all : 'Alle cellen in tabel bijwerken', row_row : 'Huidige rij bijwerken', row_odd : 'Oneven rijen in tabel bijwerken', row_even : 'Even rijen in tabel bijwerken', row_all : 'Alle rijen in tabel bijwerken', thead : 'Tabel-kop', tbody : 'Tabel-body', tfoot : 'Tabel-voet', del : 'Tabel verwijderen', scope : 'Bereik', row : 'Rij', col : 'Kolom', rowgroup : 'Rijgroep', colgroup : 'Kolomgroep', missing_scope: 'Zonder een bereik van een tabelkop, is het moeilijk voor mensen met een visuele handicap deze pagina te begrijpen. Weet u zeker dat u zonder bereik verder wilt gaan?' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/nl.js
nl.js
tinyMCE.addToLang('table',{ general_tab : 'Generella inställningar', advanced_tab : 'Avancerade inställningar', general_props : 'Generella inställningar', advanced_props : 'Avancerade inställningar', desc : 'Skapa ny tabell', before_desc : 'Skapa rad före', after_desc : 'Skapa rad efter', row_before_desc : 'Skapa rad före', row_after_desc : 'Skapa rad efter', delete_row_desc : 'Ta bort rad', col_before_desc : 'Skapa kolumn före', col_after_desc : 'Skapa kolumn efter', delete_col_desc : 'Ta bort kolumn', rowtype : 'Rad typ', title : 'Skapa/redigera ny tabell', width : 'Bredd', height : 'Höjd', cols : 'Columner', rows : 'Rader', cellspacing : 'Cellmellanrum', cellpadding : 'Cellutfyllnad', border : 'Ram', align : 'Justering', align_default : 'Ingen', align_left : 'Vänster', align_right : 'Höger', align_middle : 'Mitten', row_title : 'Tabell radsinställningar', cell_title : 'Tabell cellsinställningar', cell_type : 'Cell typ', row_desc : 'Tabell rads inställningar', cell_desc : 'Tabell cells inställningar', valign : 'Vertical justering', align_top : 'Toppen', align_bottom : 'Botten', props_desc : 'Tabell inställningar', bordercolor : 'Ram färg', bgcolor : 'Bakgrundsfärg', merge_cells_title : 'Sammanfoga tabell celler', split_cells_desc : 'Delaupp tabell celler', merge_cells_desc : 'Sammanfoga tabell celler', cut_row_desc : 'Klipput tabell rad', copy_row_desc : 'Kopiera tabell rad', paste_row_before_desc : 'Klistra in tabell rad före', paste_row_after_desc : 'Klistra in tabell rad efter', id : 'Id', style: 'Stil', langdir : 'Skrift riktning', langcode : 'Språk kåd', ltr : 'Vänster till höger', rtl : 'Höger till vänster', bgimage : 'Bakgrundsbild', summary : 'Sammanfattning', td : "Data", th : "Huvud", cell_cell : 'Updatera nuvarande cell', cell_row : 'Updatera alla celler i raden', cell_all : 'Updatera alla celler t tabellen', row_row : 'Updatera nuvarande rad', row_odd : 'Updatera udda rader i tabellen', row_even : 'Updatera jämna rader i tabellen', row_all : 'Updatera alla rader i tabellen', thead : 'Tabell Huvud', tbody : 'Tabell Kropp', tfoot : 'Tabell Fot', del : 'Tabort tabell', scope : 'Scope', row : 'Rad', col : 'Kolumn', rowgroup : 'Rad grupp', colgroup : 'Kolumn grupp', col_limit : 'Du har angivit mer kolumner än vad som är tillåtet. Max är: {$cols}.', row_limit : 'Du har angivit mer rader än vad som är tillåtet. Max är: {$rows}.', cell_limit : 'Du har angivit mer celler än vad som är tillåtet. Max är: {$cells}.', missing_scope: 'Är du säker på att du vill fortsätta utan att specifisera ett scope, utan denna kan det bli svårt för handikappade att förstå tabellen.' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/sv.js
sv.js
tinyMCE.addToLang('table',{ general_tab : 'Splošno', advanced_tab : 'Napredno', general_props : 'Splošne lastnosti', advanced_props : 'Napredne lastnosti', desc : 'Vstavi novo tabelo', row_before_desc : 'Vstavi vrstico pred', row_after_desc : 'Vstavi vrstico za', delete_row_desc : 'Zbriši vrstico', col_before_desc : 'Vstavi stolpec pred', col_after_desc : 'Vstavi stolpec za', delete_col_desc : 'Zbriši stolpec', rowtype : 'Vrstica v delu tabele', title : 'Vstavi/uredi tabelo', width : 'Širina', height : 'Višina', cols : 'Št. stolpcev', rows : 'Št. vrstic', cellspacing : 'Razmik med celicami', cellpadding : 'Odmik med celicami', border : 'Okvir', align : 'Poravnava', align_default : 'Privzeto', align_left : 'Levo', align_right : 'Desno', align_middle : 'Na sredino', row_title : 'Lastnosti vrstice', cell_title : 'Lastnosti celice', cell_type : 'Tip celice', row_desc : 'Lastnosti vrstice', cell_desc : 'Lastnosti celice', valign : 'Navpična poravnava', align_top : 'Na vrh', align_bottom : 'Na dno', props_desc : 'Lastnosti tabele', bordercolor : 'Barva okvirja', bgcolor : 'Barva ozadja', merge_cells_title : 'Združi celice', split_cells_desc : 'Razdeli celice', merge_cells_desc : 'Združi celice', cut_row_desc : 'Izreži vrstico', copy_row_desc : 'Kopiraj vrstico', paste_row_before_desc : 'Prilepi tabelo pred', paste_row_after_desc : 'Prilepi tabelo za', id : 'Id', style: 'Stil', langdir : 'Smer jezika', langcode : 'Koda jezika', mime : 'MIME type tarče', ltr : 'Od leve proti desni', rtl : 'Od desne proti levi', bgimage : 'Slika za ozadje', summary : 'Naslov', td : "Podatki", th : "Glava", cell_cell : 'Posodobi trenutno celico', cell_row : 'Posodobi vse celice v vrstici', cell_all : 'Posodobi vse celice v tabeli', row_row : 'Posodobi trenutno vrstico', row_odd : 'Posodobi lihe vrstice v tabeli', row_even : 'Posodobi sode vrstice v tabeli', row_all : 'Posodobi vse vrstice v tabeli', thead : 'Glava tabele', tbody : 'Telo tabele', tfoot : 'Dno tabele', del : 'Zbriši tabelo', scope : 'Domena', row : 'Vrstica', col : 'Stolpec', rowgroup : 'Skupina vrstic', colgroup : 'Skupina stolpcev', missing_scope: 'Ali ste prepričani, da želite nadaljevati brez domene za to celico v glavi tabele? Brez nje bodo lahko imeli uporabniki s posebnimi potrebami probleme pri razumevanju vsebine tabele.' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/si.js
si.js
tinyMCE.addToLang('',{ table_desc : 'إدراج/تحرير جدول', table_insert_row_before_desc : 'Insert row before', table_insert_row_after_desc : 'Insert row after', table_delete_row_desc : 'حذف صفوف', table_insert_col_before_desc : 'Insert column before', table_insert_col_after_desc : 'Insert column after', table_delete_col_desc : 'حذف أعمدة', insert_table_title : 'إدراج/تحرير جدول', insert_table_width : 'العرض', insert_table_height : 'الارتفاع', insert_table_cols : 'أعمدة', insert_table_rows : 'صفوف', insert_table_cellspacing : 'تباعد الخلايا', insert_table_cellpadding : 'المسافة البادئة', insert_table_border : 'سمك الحدود', insert_table_align : 'المحاذاة', insert_table_align_default : 'Default', insert_table_align_left : 'يسار', insert_table_align_right : 'يمين', insert_table_align_middle : 'وسط', insert_table_class : 'Class', table_row_title : 'Table row properties', table_cell_title : 'Table cell properties', table_row_desc : 'Table row properties', table_cell_desc : 'Table cell properties', insert_table_valign : 'Vertical alignment', insert_table_align_top : 'Top', insert_table_align_bottom : 'Bottom', table_props_desc : 'Table properties', table_bordercolor : 'Border color', table_bgcolor : 'Bg color', table_merge_cells_title : 'Merge table cells', table_split_cells_desc : 'Split table cells', table_merge_cells_desc : 'Merge table cells', table_cut_row_desc : 'Cut table row', table_copy_row_desc : 'Copy table row', table_paste_row_before_desc : 'Paste table row before', table_paste_row_after_desc : 'Paste table row after', table_insert_desc : 'Insert a new table' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/ar.js
ar.js
tinyMCE.addToLang('table',{ general_tab : 'Obecné', advanced_tab : 'Pokročilé', general_props : 'Obecné vlastnosti', advanced_props : 'Pokročilé vlastnosti', desc : 'Vložit novou tabulku', row_before_desc : 'Vložit řádek před', row_after_desc : 'Vložit řádek za', delete_row_desc : 'Smazat řádek', col_before_desc : 'Vložit sloupec před', col_after_desc : 'VLožit sloupec za', delete_col_desc : 'Smazat sloupec', rowtype : 'Řádek v tabulce', title : 'Vložit/Modifikovat tabulku', width : 'Šířka', height : 'Výška', cols : 'Sloupce', rows : 'Řádky', cellspacing : 'Mezera mezi buňkami', cellpadding : 'Výplň buněk', border : 'Rámeček', align : 'Zarovnání', align_default : 'Automatické', align_left : 'Vlevo', align_right : 'Vpravo', align_middle : 'Na střed', row_title : 'Vlastnosti řádku', cell_title : 'Vlastnosti buňky', cell_type : 'Typ buňky', row_desc : 'Vlastnosti řádku', cell_desc : 'Vlastnosti buňky', valign : 'Vertikální zarovnání', align_top : 'Nahoru', align_bottom : 'Dolů', props_desc : 'Vlastnosti tabulky', bordercolor : 'Barva rámečku', bgcolor : 'Barva pozadí', merge_cells_title : 'Sloučit buňky', split_cells_desc : 'Rozdělit buňky', merge_cells_desc : 'Sloučit buňky', cut_row_desc : 'Vyjmout řádek', copy_row_desc : 'Kopírovat řádek', paste_row_before_desc : 'Vložit řádek před', paste_row_after_desc : 'Vložit řádek za', id : 'Id', style: 'Styl', langdir : 'Směr textu', langcode : 'Kód jazyka', mime : 'Cílový MIME typ', ltr : 'Z leva doprava', rtl : 'Z prava doleva', bgimage : 'Obrázek pozadí', summary : 'Obsah', td : "Data", th : "Hlavička", cell_cell : 'Aktualizovat současnou buňku', cell_row : 'Aktualizovat všechny buňky v řádku', cell_all : 'Aktualizovat všechny buňky v tabulce', row_row : 'Aktualizovat současný řádek', row_odd : 'Aktualizovat liché řádky tabulky', row_even : 'Aktualizovat sudé řádky v tabulce', row_all : 'Aktualizovat všechny řádky v tabulce', thead : 'Hlavička tabulky', tbody : 'Tělo tabulky', tfoot : 'Patička tabulky', del : 'Smazat tabulku', scope : 'Scope', row : 'Řádek', col : 'Sloupec', rowgroup : 'Skupina řádků', colgroup : 'Skupina sloupců', missing_scope: 'Jste si jistý(á), že chcete pokračovat bez vyplnění rozsahu pro tuto buňku tabulky? Bez něj může být težké handicapovaným uživatelům porozumět obsahu nebo datům obsažených v tabulce.' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/cs.js
cs.js
tinyMCE.addToLang('table',{ general_tab : 'Generelt', advanced_tab : 'Avansert', general_props : 'Generelle egenskaper', advanced_props : 'Avanserte egenskaper', desc : 'Opprett/endre tabell', row_before_desc : 'Opprett rad foran', row_after_desc : 'Opprett rad etter', delete_row_desc : 'Fjern rad', col_before_desc : 'Opprett kolonne foran', col_after_desc : 'Opprett kolonne etter', delete_col_desc : 'Fjern kolonne', rowtype : 'Rad i tabell', title : 'Opprett/endre tabell', width : 'Bredde', height : 'Høgde', cols : 'Kolonner', rows : 'Rader', cellspacing : 'Celle mellomrom', cellpadding : 'Celle fylling', border : 'Rammebredde', align : 'Justering', align_default : 'Ingen', align_left : 'Venstre', align_right : 'Høgre', align_middle : 'Midtstilt', row_title : 'tabell rad egenskaper', cell_title : 'tabell celle egenskaper', cell_type : 'Celle type', row_desc : 'tabell rad egenskaper', cell_desc : 'tabell celle egenskaper', valign : 'Vertikal justering', align_top : 'Topp', align_bottom : 'Bunn', props_desc : 'tabell egenskaper', bordercolor : 'Rammefarge', bgcolor : 'Bakgrunnsfarge', merge_cells_title : 'Slå sammen tabell celler', split_cells_desc : 'Splitt tabell celler', merge_cells_desc : 'Slå sammen tabell celler', cut_row_desc : 'Fjern tabell rad', copy_row_desc : 'Kopier tabell rad', paste_row_before_desc : 'Lim inn tabell rad foran', paste_row_after_desc : 'Lim inn tabell rad etter', id : 'Id', style: 'Stil', langdir : 'Språk retning', langcode : 'Språk kode', mime : 'Målets MIME type', ltr : 'Venstre mot høgre', rtl : 'Høgre mot venstre', bgimage : 'Bakgrunnsbilde', summary : 'Sum', td : "Data", th : "Overskrift", cell_cell : 'Oppdater valgt celle', cell_row : 'Oppdater alle celler i raden', cell_all : 'Oppdater alle celler i tabellen', row_row : 'Oppdater valgt rad', row_odd : 'Oppdater ulike rader i tabellen', row_even : 'Oppdater like rader i tabellen', row_all : 'Oppdater alle rader i tabellen', thead : 'Tabell Hode', tbody : 'Tabell Kropp', tfoot : 'Tabell Fot', del : 'Slett tabell', scope : 'Hensikt', row : 'Rad', col : 'Kolonne', rowgroup : 'Rad gruppe', colgroup : 'Kolonne gruppe', missing_scope: 'Er du sikker på at du vil fortsette uten å oppgi hensikten med denne tabellens hode celle.', cellprops_delta_width : 30 });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/nn.js
nn.js
tinyMCE.addToLang('table',{ general_tab : 'Allgemein', advanced_tab : 'Erweitert', general_props : 'Allgemeine Eigenschaften', advanced_props : 'Erweiterte Eigenschaften', desc : 'Neue Tabelle einfügen', row_before_desc : 'Zeile oberhalb einfügen', row_after_desc : 'Zeile unterhalb einfügen', delete_row_desc : 'Zeile löschen', col_before_desc : 'Spalte nach links einfügen', col_after_desc : 'Spalte nach rechts einfügen', delete_col_desc : 'Spalte löschen', rowtype : 'Zeile in Tabellen-Teil', title : 'Tabelle hinzufügen/bearbeiten', width : 'Breite', height : 'Höhe', cols : 'Spalten', rows : 'Zeilen', cellspacing : 'Zellenabstand', cellpadding : 'Zellenauffüllung', border : 'Rahmen', align : 'Ausrichtung', align_default : 'Standard', align_left : 'Links', align_right : 'Rechts', align_middle : 'Zentriert', row_title : 'Zeileneigenschaften', cell_title : 'Zelleneigenschaften', cell_type : 'Zellentyp', row_desc : 'Zeileneigenschaften', cell_desc : 'Zelleneigenschaften', valign : 'Vertikale Ausrichtung', align_top : 'Oben', align_bottom : 'Unten', props_desc : 'Tabelleneigenschaften', bordercolor : 'Rahmenfarbe', bgcolor : 'Hintergrundbild', merge_cells_title : 'Zellen zusammenfügen', split_cells_desc : 'Zelle teilen', merge_cells_desc : 'Zellen zusammenfügen', cut_row_desc : 'Zeile ausschneiden', copy_row_desc : 'Zeile kopieren', paste_row_before_desc : 'Zeile oberhalb einfügen', paste_row_after_desc : 'Zeile unterhalb einfügen', id : 'ID', style: 'CSS-Stil', langdir : 'Sprachrichtung', langcode : 'Sprachcode', mime : 'MIME-Typ', ltr : 'Von links nach rechts', rtl : 'Von rechts nach links', bgimage : 'Hintergrundfarbe', summary : 'Zusammenfassung', td : "Daten", th : "Kopfzeile", cell_cell : 'Diese Zelle aktualisieren', cell_row : 'Alle Zellen in dieser Zeile aktualisieren', cell_all : 'Alle Zellen in dieser Tabelle aktualisieren', row_row : 'Diese Zeile aktualisieren', row_odd : 'Ungerade Zeilen aktualisieren', row_even : 'Gerade Zeilen aktualisieren', row_all : 'Alle Zeilen in dieser Tabelle aktualisieren', thead : 'Tabellenkopf', tbody : 'Tabellenkörper', tfoot : 'Tabellenfuß', del : 'Tabelle löschen', scope : 'Scope', row : 'Row', col : 'Col', rowgroup : 'Row Group', colgroup : 'Col Group', missing_scope: 'Are you sure you want to continue without specifying a scope for this table header cell. Without it, it may be difficult for some users with disabilities to understand the content or data displayed of the table.', table_delta_width : 45 });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/de.js
de.js
tinyMCE.addToLang('table',{ general_tab : 'Основные', advanced_tab : 'Расширенные', general_props : 'Основные свойства', advanced_props : 'Расширенные свойства', desc : 'Вставить новую таблицу', row_before_desc : 'Вставить строку перед', row_after_desc : 'Вставить строку после', delete_row_desc : 'Удалить строку', col_before_desc : 'Вставить колонку перед', col_after_desc : 'Вставить колонку после', delete_col_desc : 'Удалить колонку', rowtype : 'Строка в части таблицы', title : 'Вставить/Изменить таблицу', width : 'Ширина', height : 'Высота', cols : 'Колонки', rows : 'Строки', cellspacing : 'Расстояние между ячейками', cellpadding : 'Отступ в ячейках', border : 'Граница', align : 'Выравнивание', align_default : 'По-умолчанию', align_left : 'Всево', align_right : 'Вправо', align_middle : 'По центру', row_title : 'Свойства строки таблицы', cell_title : 'Свойства ячейки таблицы', cell_type : 'Тип ячейки', row_desc : 'Свойства строки таблицы', cell_desc : 'Свойства ячейки таблицы', valign : 'Вертикальное выравнивание', align_top : 'По верху', align_bottom : 'По низу', props_desc : 'Свойства таблицы', bordercolor : 'Цвет рамки', bgcolor : 'Цвет фона', merge_cells_title : 'Объединить ячейки таблицы', split_cells_desc : 'Разделить ячейки таблицы', merge_cells_desc : 'Объединить ячейки таблицы', cut_row_desc : 'Вылезать строку таблицы', copy_row_desc : 'Скопировать строку таблицы', paste_row_before_desc : 'Вставить строку таблицы перед', paste_row_after_desc : 'Вставить строку таблицы после', id : 'Id', style: 'Стиль', langdir : 'Описание языка', langcode : 'Код языка', mime : 'Целевой MIME тип', ltr : 'Слева направо', rtl : 'Справа налево', bgimage : 'Фоновое изображение', summary : 'Краткое описание', td : "Тело", th : "Заголовок", cell_cell : 'Обновить текущую ячейку', cell_row : 'Обновить текущую строку', cell_all : 'Обновить все ячейки в таблице', row_row : 'Обновить текущую строку', row_odd : 'Update odd rows in table', row_even : 'Update even rows in table', row_all : 'Обновить все строки в таблице', thead : 'Заголовок таблицы', tbody : 'Тело таблицы', tfoot : 'Футер таблицы', del : 'Удалить таблицу', scope : 'Границы', row : 'Строка', col : 'Колонка', rowgroup : 'Группа строк', colgroup : 'Группа колонок', missing_scope: 'Вы уверены, что хотите продолжать не обозначив границы ячеек шапки таблицы? Без этого, возможно, некоторым пользователям будет затруднительно понять, что за данные находятся в таблице.' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/langs/ru_UTF-8.js
ru_UTF-8.js
function init() { tinyMCEPopup.resizeToInnerSize(); document.getElementById('backgroundimagebrowsercontainer').innerHTML = getBrowserHTML('backgroundimagebrowser','backgroundimage','image','table'); document.getElementById('bordercolor_pickcontainer').innerHTML = getColorPickerHTML('bordercolor_pick','bordercolor'); document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor') var inst = tinyMCE.selectedInstance; var tdElm = tinyMCE.getParentElement(inst.getFocusElement(), "td,th"); var formObj = document.forms[0]; var st = tinyMCE.parseStyle(tinyMCE.getAttrib(tdElm, "style")); // Get table cell data var celltype = tdElm.nodeName.toLowerCase(); var align = tinyMCE.getAttrib(tdElm, 'align'); var valign = tinyMCE.getAttrib(tdElm, 'valign'); var width = trimSize(getStyle(tdElm, 'width', 'width')); var height = trimSize(getStyle(tdElm, 'height', 'height')); var bordercolor = convertRGBToHex(getStyle(tdElm, 'bordercolor', 'borderLeftColor')); var bgcolor = convertRGBToHex(getStyle(tdElm, 'bgcolor', 'backgroundColor')); var className = tinyMCE.getVisualAidClass(tinyMCE.getAttrib(tdElm, 'class'), false); var backgroundimage = getStyle(tdElm, 'background', 'backgroundImage').replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1");; var id = tinyMCE.getAttrib(tdElm, 'id'); var lang = tinyMCE.getAttrib(tdElm, 'lang'); var dir = tinyMCE.getAttrib(tdElm, 'dir'); var scope = tinyMCE.getAttrib(tdElm, 'scope'); // Setup form addClassesToList('class', 'table_cell_styles'); formObj.bordercolor.value = bordercolor; formObj.bgcolor.value = bgcolor; formObj.backgroundimage.value = backgroundimage; formObj.width.value = width; formObj.height.value = height; formObj.id.value = id; formObj.lang.value = lang; formObj.style.value = tinyMCE.serializeStyle(st); selectByValue(formObj, 'align', align); selectByValue(formObj, 'valign', valign); selectByValue(formObj, 'class', className); selectByValue(formObj, 'celltype', celltype); selectByValue(formObj, 'dir', dir); selectByValue(formObj, 'scope', scope); // Resize some elements if (isVisible('backgroundimagebrowser')) document.getElementById('backgroundimage').style.width = '180px'; updateColor('bordercolor_pick', 'bordercolor'); updateColor('bgcolor_pick', 'bgcolor'); if (tinyMCE.getParam('class_selectors', true)) { var sr = document.getElementById('styleSelectRow'); sr.style.display = 'none'; } } function updateAction() { tinyMCEPopup.restoreSelection(); var inst = tinyMCE.selectedInstance; var tdElm = tinyMCE.getParentElement(inst.getFocusElement(), "td,th"); var trElm = tinyMCE.getParentElement(inst.getFocusElement(), "tr"); var tableElm = tinyMCE.getParentElement(inst.getFocusElement(), "table"); var formObj = document.forms[0]; inst.execCommand('mceBeginUndoLevel'); switch (getSelectValue(formObj, 'action')) { case "cell": var celltype = getSelectValue(formObj, 'celltype'); var scope = getSelectValue(formObj, 'scope'); if (tinyMCE.getParam("accessibility_warnings")) { if (celltype == "th" && scope == "") var answer = confirm(tinyMCE.getLang('lang_table_missing_scope', '', true)); else var answer = true; if (!answer) return; } updateCell(tdElm); break; case "row": var cell = trElm.firstChild; if (cell.nodeName != "TD" && cell.nodeName != "TH") cell = nextCell(cell); do { cell = updateCell(cell, true); } while ((cell = nextCell(cell)) != null); break; case "all": var rows = tableElm.getElementsByTagName("tr"); for (var i=0; i<rows.length; i++) { var cell = rows[i].firstChild; if (cell.nodeName != "TD" && cell.nodeName != "TH") cell = nextCell(cell); do { cell = updateCell(cell, true); } while ((cell = nextCell(cell)) != null); } break; } tinyMCE.handleVisualAid(inst.getBody(), true, inst.visualAid, inst); tinyMCE.triggerNodeChange(); inst.execCommand('mceEndUndoLevel'); tinyMCEPopup.close(); } function nextCell(elm) { while ((elm = elm.nextSibling) != null) { if (elm.nodeName == "TD" || elm.nodeName == "TH") return elm; } return null; } function updateCell(td, skip_id) { var inst = tinyMCE.selectedInstance; var formObj = document.forms[0]; var curCellType = td.nodeName.toLowerCase(); var celltype = getSelectValue(formObj, 'celltype'); var doc = inst.getDoc(); if (!skip_id) td.setAttribute('id', formObj.id.value); td.setAttribute('align', formObj.align.value); td.setAttribute('vAlign', formObj.valign.value); td.setAttribute('lang', formObj.lang.value); td.setAttribute('dir', getSelectValue(formObj, 'dir')); td.setAttribute('style', tinyMCE.serializeStyle(tinyMCE.parseStyle(formObj.style.value))); td.setAttribute('scope', formObj.scope.value); tinyMCE.setAttrib(td, 'class', getSelectValue(formObj, 'class')); // Clear deprecated attributes tinyMCE.setAttrib(td, 'width', ''); tinyMCE.setAttrib(td, 'height', ''); tinyMCE.setAttrib(td, 'bgColor', ''); tinyMCE.setAttrib(td, 'borderColor', ''); tinyMCE.setAttrib(td, 'background', ''); // Set styles td.style.width = getCSSSize(formObj.width.value); td.style.height = getCSSSize(formObj.height.value); if (formObj.bordercolor.value != "") { td.style.borderColor = formObj.bordercolor.value; td.style.borderStyle = td.style.borderStyle == "" ? "solid" : td.style.borderStyle; td.style.borderWidth = td.style.borderWidth == "" ? "1px" : td.style.borderWidth; } else td.style.borderColor = ''; td.style.backgroundColor = formObj.bgcolor.value; if (formObj.backgroundimage.value != "") td.style.backgroundImage = "url('" + formObj.backgroundimage.value + "')"; else td.style.backgroundImage = ''; if (curCellType != celltype) { // changing to a different node type var newCell = doc.createElement(celltype); for (var c=0; c<td.childNodes.length; c++) newCell.appendChild(td.childNodes[c].cloneNode(1)); for (var a=0; a<td.attributes.length; a++) { var attr = td.attributes[a]; newCell.setAttribute(attr.name, attr.value); } td.parentNode.replaceChild(newCell, td); td = newCell; } return td; } function changedBackgroundImage() { var formObj = document.forms[0]; var st = tinyMCE.parseStyle(formObj.style.value); st['background-image'] = "url('" + formObj.backgroundimage.value + "')"; formObj.style.value = tinyMCE.serializeStyle(st); } function changedSize() { var formObj = document.forms[0]; var st = tinyMCE.parseStyle(formObj.style.value); var width = formObj.width.value; if (width != "") st['width'] = getCSSSize(width); else st['width'] = ""; var height = formObj.height.value; if (height != "") st['height'] = getCSSSize(height); else st['height'] = ""; formObj.style.value = tinyMCE.serializeStyle(st); } function changedColor() { var formObj = document.forms[0]; var st = tinyMCE.parseStyle(formObj.style.value); st['background-color'] = formObj.bgcolor.value; st['border-color'] = formObj.bordercolor.value; formObj.style.value = tinyMCE.serializeStyle(st); } function changedStyle() { var formObj = document.forms[0]; var st = tinyMCE.parseStyle(formObj.style.value); if (st['background-image']) formObj.backgroundimage.value = st['background-image'].replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1"); else formObj.backgroundimage.value = ''; if (st['width']) formObj.width.value = trimSize(st['width']); if (st['height']) formObj.height.value = trimSize(st['height']); if (st['background-color']) { formObj.bgcolor.value = st['background-color']; updateColor('bgcolor_pick','bgcolor'); } if (st['border-color']) { formObj.bordercolor.value = st['border-color']; updateColor('bordercolor_pick','bordercolor'); } }
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/jscripts/cell.js
cell.js
function init() { tinyMCEPopup.resizeToInnerSize(); document.getElementById('backgroundimagebrowsercontainer').innerHTML = getBrowserHTML('backgroundimagebrowser','backgroundimage','image','table'); document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor'); var inst = tinyMCE.selectedInstance; var trElm = tinyMCE.getParentElement(inst.getFocusElement(), "tr"); var formObj = document.forms[0]; var st = tinyMCE.parseStyle(tinyMCE.getAttrib(trElm, "style")); // Get table row data var rowtype = trElm.parentNode.nodeName.toLowerCase(); var align = tinyMCE.getAttrib(trElm, 'align'); var valign = tinyMCE.getAttrib(trElm, 'valign'); var height = trimSize(getStyle(trElm, 'height', 'height')); var className = tinyMCE.getVisualAidClass(tinyMCE.getAttrib(trElm, 'class'), false); var bgcolor = convertRGBToHex(getStyle(trElm, 'bgcolor', 'backgroundColor')); var backgroundimage = getStyle(trElm, 'background', 'backgroundImage').replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1");; var id = tinyMCE.getAttrib(trElm, 'id'); var lang = tinyMCE.getAttrib(trElm, 'lang'); var dir = tinyMCE.getAttrib(trElm, 'dir'); // Setup form addClassesToList('class', 'table_row_styles'); formObj.bgcolor.value = bgcolor; formObj.backgroundimage.value = backgroundimage; formObj.height.value = height; formObj.id.value = id; formObj.lang.value = lang; formObj.style.value = tinyMCE.serializeStyle(st); selectByValue(formObj, 'align', align); selectByValue(formObj, 'valign', valign); selectByValue(formObj, 'class', className); selectByValue(formObj, 'rowtype', rowtype); selectByValue(formObj, 'dir', dir); // Resize some elements if (isVisible('backgroundimagebrowser')) document.getElementById('backgroundimage').style.width = '180px'; updateColor('bgcolor_pick', 'bgcolor'); if (tinyMCE.getParam('class_selectors', true)) { var sr = document.getElementById('styleSelectRow'); sr.style.display = 'none'; } } function updateAction() { tinyMCEPopup.restoreSelection(); var inst = tinyMCE.selectedInstance; var trElm = tinyMCE.getParentElement(inst.getFocusElement(), "tr"); var tableElm = tinyMCE.getParentElement(inst.getFocusElement(), "table"); var formObj = document.forms[0]; var action = getSelectValue(formObj, 'action'); inst.execCommand('mceBeginUndoLevel'); switch (action) { case "row": updateRow(trElm); break; case "all": var rows = tableElm.getElementsByTagName("tr"); for (var i=0; i<rows.length; i++) updateRow(rows[i], true); break; case "odd": case "even": var rows = tableElm.getElementsByTagName("tr"); for (var i=0; i<rows.length; i++) { if ((i % 2 == 0 && action == "odd") || (i % 2 != 0 && action == "even")) updateRow(rows[i], true, true); } break; } tinyMCE.handleVisualAid(inst.getBody(), true, inst.visualAid, inst); tinyMCE.triggerNodeChange(); inst.execCommand('mceEndUndoLevel'); tinyMCEPopup.close(); } function updateRow(tr_elm, skip_id, skip_parent) { var inst = tinyMCE.selectedInstance; var formObj = document.forms[0]; var curRowType = tr_elm.parentNode.nodeName.toLowerCase(); var rowtype = getSelectValue(formObj, 'rowtype'); var doc = inst.getDoc(); // Update row element if (!skip_id) tr_elm.setAttribute('id', formObj.id.value); tr_elm.setAttribute('align', getSelectValue(formObj, 'align')); tr_elm.setAttribute('vAlign', getSelectValue(formObj, 'valign')); tr_elm.setAttribute('lang', formObj.lang.value); tr_elm.setAttribute('dir', getSelectValue(formObj, 'dir')); tr_elm.setAttribute('style', tinyMCE.serializeStyle(tinyMCE.parseStyle(formObj.style.value))); tinyMCE.setAttrib(tr_elm, 'class', getSelectValue(formObj, 'class')); // Clear deprecated attributes tr_elm.setAttribute('background', ''); tr_elm.setAttribute('bgColor', ''); tr_elm.setAttribute('height', ''); // Set styles tr_elm.style.height = getCSSSize(formObj.height.value); tr_elm.style.backgroundColor = formObj.bgcolor.value; if (formObj.backgroundimage.value != "") tr_elm.style.backgroundImage = "url('" + formObj.backgroundimage.value + "')"; else tr_elm.style.backgroundImage = ''; // Setup new rowtype if (curRowType != rowtype && !skip_parent) { // first, clone the node we are working on var newRow = tr_elm.cloneNode(1); // next, find the parent of its new destination (creating it if necessary) var theTable = tinyMCE.getParentElement(tr_elm, "table"); var dest = rowtype; var newParent = null; for (var i = 0; i < theTable.childNodes.length; i++) { if (theTable.childNodes[i].nodeName.toLowerCase() == dest) newParent = theTable.childNodes[i]; } if (newParent == null) { newParent = doc.createElement(dest); if (dest == "thead") theTable.insertBefore(newParent, theTable.firstChild); else theTable.appendChild(newParent); } // append the row to the new parent newParent.appendChild(newRow); // remove the original tr_elm.parentNode.removeChild(tr_elm); // set tr_elm to the new node tr_elm = newRow; } } function changedBackgroundImage() { var formObj = document.forms[0]; var st = tinyMCE.parseStyle(formObj.style.value); st['background-image'] = "url('" + formObj.backgroundimage.value + "')"; formObj.style.value = tinyMCE.serializeStyle(st); } function changedStyle() { var formObj = document.forms[0]; var st = tinyMCE.parseStyle(formObj.style.value); if (st['background-image']) formObj.backgroundimage.value = st['background-image'].replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1"); else formObj.backgroundimage.value = ''; if (st['height']) formObj.height.value = trimSize(st['height']); if (st['background-color']) { formObj.bgcolor.value = st['background-color']; updateColor('bgcolor_pick','bgcolor'); } } function changedSize() { var formObj = document.forms[0]; var st = tinyMCE.parseStyle(formObj.style.value); var height = formObj.height.value; if (height != "") st['height'] = getCSSSize(height); else st['height'] = ""; formObj.style.value = tinyMCE.serializeStyle(st); } function changedColor() { var formObj = document.forms[0]; var st = tinyMCE.parseStyle(formObj.style.value); st['background-color'] = formObj.bgcolor.value; formObj.style.value = tinyMCE.serializeStyle(st); }
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/jscripts/row.js
row.js
var action, orgTableWidth, orgTableHeight; function insertTable() { var formObj = document.forms[0]; var inst = tinyMCE.selectedInstance; var cols = 2, rows = 2, border = 0, cellpadding = -1, cellspacing = -1, align, width, height, className; var html = ''; var elm = tinyMCE.tableElm; var cellLimit, rowLimit, colLimit; tinyMCEPopup.restoreSelection(); // Get form data cols = formObj.elements['cols'].value; rows = formObj.elements['rows'].value; border = formObj.elements['border'].value != "" ? formObj.elements['border'].value : 0; cellpadding = formObj.elements['cellpadding'].value != "" ? formObj.elements['cellpadding'].value : ""; cellspacing = formObj.elements['cellspacing'].value != "" ? formObj.elements['cellspacing'].value : ""; align = formObj.elements['align'].options[formObj.elements['align'].selectedIndex].value; width = formObj.elements['width'].value; height = formObj.elements['height'].value; bordercolor = formObj.elements['bordercolor'].value; bgcolor = formObj.elements['bgcolor'].value; className = formObj.elements['class'].options[formObj.elements['class'].selectedIndex].value; id = formObj.elements['id'].value; summary = formObj.elements['summary'].value; style = formObj.elements['style'].value; dir = formObj.elements['dir'].value; lang = formObj.elements['lang'].value; background = formObj.elements['backgroundimage'].value; cellLimit = tinyMCE.getParam('table_cell_limit', false); rowLimit = tinyMCE.getParam('table_row_limit', false); colLimit = tinyMCE.getParam('table_col_limit', false); // Validate table size if (colLimit && cols > colLimit) { alert(tinyMCE.getLang('lang_table_col_limit', '', true, {cols : colLimit})); return false; } else if (rowLimit && rows > rowLimit) { alert(tinyMCE.getLang('lang_table_row_limit', '', true, {rows : rowLimit})); return false; } else if (cellLimit && cols * rows > cellLimit) { alert(tinyMCE.getLang('lang_table_cell_limit', '', true, {cells : cellLimit})); return false; } // Update table if (action == "update") { inst.execCommand('mceBeginUndoLevel'); tinyMCE.setAttrib(elm, 'cellPadding', cellpadding, true); tinyMCE.setAttrib(elm, 'cellSpacing', cellspacing, true); tinyMCE.setAttrib(elm, 'border', border, true); tinyMCE.setAttrib(elm, 'align', align); tinyMCE.setAttrib(elm, 'class', className); tinyMCE.setAttrib(elm, 'style', style); tinyMCE.setAttrib(elm, 'id', id); tinyMCE.setAttrib(elm, 'summary', summary); tinyMCE.setAttrib(elm, 'dir', dir); tinyMCE.setAttrib(elm, 'lang', lang); // Not inline styles if (!tinyMCE.getParam("inline_styles")) tinyMCE.setAttrib(elm, 'width', width, true); // Remove these since they are not valid XHTML tinyMCE.setAttrib(elm, 'borderColor', ''); tinyMCE.setAttrib(elm, 'bgColor', ''); tinyMCE.setAttrib(elm, 'background', ''); tinyMCE.setAttrib(elm, 'height', ''); if (background != '') elm.style.backgroundImage = "url('" + background + "')"; else elm.style.backgroundImage = ''; if (tinyMCE.getParam("inline_styles")) elm.style.borderWidth = border + "px"; if (tinyMCE.getParam("inline_styles")) { if (width != '') elm.style.width = getCSSSize(width); } if (bordercolor != "") { elm.style.borderColor = bordercolor; elm.style.borderStyle = elm.style.borderStyle == "" ? "solid" : elm.style.borderStyle; elm.style.borderWidth = border == "" ? "1px" : border; } else elm.style.borderColor = ''; elm.style.backgroundColor = bgcolor; elm.style.height = getCSSSize(height); tinyMCE.handleVisualAid(tinyMCE.tableElm, false, inst.visualAid, inst); // Fix for stange MSIE align bug tinyMCE.tableElm.outerHTML = tinyMCE.tableElm.outerHTML; tinyMCE.handleVisualAid(inst.getBody(), true, inst.visualAid, inst); tinyMCE.triggerNodeChange(); inst.execCommand('mceEndUndoLevel'); // Repaint if dimensions changed if (formObj.width.value != orgTableWidth || formObj.height.value != orgTableHeight) inst.repaint(); tinyMCEPopup.close(); return true; } // Create new table html += '<table'; html += makeAttrib('id', id); html += makeAttrib('border', border); html += makeAttrib('cellpadding', cellpadding); html += makeAttrib('cellspacing', cellspacing); html += makeAttrib('width', width); //html += makeAttrib('height', height); //html += makeAttrib('bordercolor', bordercolor); //html += makeAttrib('bgcolor', bgcolor); html += makeAttrib('align', align); html += makeAttrib('class', tinyMCE.getVisualAidClass(className, border == 0)); html += makeAttrib('style', style); html += makeAttrib('summary', summary); html += makeAttrib('dir', dir); html += makeAttrib('lang', lang); html += '>'; for (var y=0; y<rows; y++) { html += "<tr>"; for (var x=0; x<cols; x++) html += '<td>&nbsp;</td>'; html += "</tr>"; } html += "</table>"; inst.execCommand('mceBeginUndoLevel'); inst.execCommand('mceInsertContent', false, html); tinyMCE.handleVisualAid(inst.getBody(), true, tinyMCE.settings['visual']); inst.execCommand('mceEndUndoLevel'); tinyMCEPopup.close(); } function makeAttrib(attrib, value) { var formObj = document.forms[0]; var valueElm = formObj.elements[attrib]; if (typeof(value) == "undefined" || value == null) { value = ""; if (valueElm) value = valueElm.value; } if (value == "") return ""; // XML encode it value = value.replace(/&/g, '&amp;'); value = value.replace(/\"/g, '&quot;'); value = value.replace(/</g, '&lt;'); value = value.replace(/>/g, '&gt;'); return ' ' + attrib + '="' + value + '"'; } function init() { tinyMCEPopup.resizeToInnerSize(); document.getElementById('backgroundimagebrowsercontainer').innerHTML = getBrowserHTML('backgroundimagebrowser','backgroundimage','image','table'); document.getElementById('backgroundimagebrowsercontainer').innerHTML = getBrowserHTML('backgroundimagebrowser','backgroundimage','image','table'); document.getElementById('bordercolor_pickcontainer').innerHTML = getColorPickerHTML('bordercolor_pick','bordercolor'); document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor'); var cols = 2, rows = 2, border = 0, cellpadding = "", cellspacing = ""; var align = "", width = "", height = "", bordercolor = "", bgcolor = "", className = ""; var id = "", summary = "", style = "", dir = "", lang = "", background = "", bgcolor = "", bordercolor = ""; var inst = tinyMCE.selectedInstance; var formObj = document.forms[0]; var elm = tinyMCE.getParentElement(inst.getFocusElement(), "table"); tinyMCE.tableElm = elm; action = tinyMCE.getWindowArg('action'); if (action == null) action = tinyMCE.tableElm ? "update" : "insert"; if (tinyMCE.tableElm && action != "insert") { var rowsAr = tinyMCE.tableElm.rows; var cols = 0; for (var i=0; i<rowsAr.length; i++) if (rowsAr[i].cells.length > cols) cols = rowsAr[i].cells.length; cols = cols; rows = rowsAr.length; st = tinyMCE.parseStyle(tinyMCE.getAttrib(tinyMCE.tableElm, "style")); border = trimSize(getStyle(elm, 'border', 'borderWidth')); cellpadding = tinyMCE.getAttrib(tinyMCE.tableElm, 'cellpadding', ""); cellspacing = tinyMCE.getAttrib(tinyMCE.tableElm, 'cellspacing', ""); width = trimSize(getStyle(elm, 'width', 'width')); height = trimSize(getStyle(elm, 'height', 'height')); bordercolor = convertRGBToHex(getStyle(elm, 'bordercolor', 'borderLeftColor')); bgcolor = convertRGBToHex(getStyle(elm, 'bgcolor', 'backgroundColor')); align = tinyMCE.getAttrib(tinyMCE.tableElm, 'align', align); className = tinyMCE.getVisualAidClass(tinyMCE.getAttrib(tinyMCE.tableElm, 'class'), false); id = tinyMCE.getAttrib(tinyMCE.tableElm, 'id'); summary = tinyMCE.getAttrib(tinyMCE.tableElm, 'summary'); style = tinyMCE.serializeStyle(st); dir = tinyMCE.getAttrib(tinyMCE.tableElm, 'dir'); lang = tinyMCE.getAttrib(tinyMCE.tableElm, 'lang'); background = getStyle(elm, 'background', 'backgroundImage').replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1"); orgTableWidth = width; orgTableHeight = height; action = "update"; } addClassesToList('class', "table_styles"); // Update form selectByValue(formObj, 'align', align); selectByValue(formObj, 'class', className); formObj.cols.value = cols; formObj.rows.value = rows; formObj.border.value = border; formObj.cellpadding.value = cellpadding; formObj.cellspacing.value = cellspacing; formObj.width.value = width; formObj.height.value = height; formObj.bordercolor.value = bordercolor; formObj.bgcolor.value = bgcolor; formObj.id.value = id; formObj.summary.value = summary; formObj.style.value = style; formObj.dir.value = dir; formObj.lang.value = lang; formObj.backgroundimage.value = background; formObj.insert.value = tinyMCE.getLang('lang_' + action, 'Insert', true); updateColor('bordercolor_pick', 'bordercolor'); updateColor('bgcolor_pick', 'bgcolor'); // Resize some elements if (isVisible('backgroundimagebrowser')) document.getElementById('backgroundimage').style.width = '180px'; // Disable some fields in update mode if (action == "update") { formObj.cols.disabled = true; formObj.rows.disabled = true; } if (tinyMCE.getParam ('class_selectors', true)) { var sr = document.getElementById('styleSelectRow'); sr.style.display = 'none'; } } function changedSize() { var formObj = document.forms[0]; var st = tinyMCE.parseStyle(formObj.style.value); var width = formObj.width.value; if (width != "") st['width'] = tinyMCE.getParam("inline_styles") ? getCSSSize(width) : ""; else st['width'] = ""; var height = formObj.height.value; if (height != "") st['height'] = getCSSSize(height); else st['height'] = ""; formObj.style.value = tinyMCE.serializeStyle(st); } function changedBackgroundImage() { var formObj = document.forms[0]; var st = tinyMCE.parseStyle(formObj.style.value); st['background-image'] = "url('" + formObj.backgroundimage.value + "')"; formObj.style.value = tinyMCE.serializeStyle(st); } function changedBorder() { var formObj = document.forms[0]; var st = tinyMCE.parseStyle(formObj.style.value); // Update border width if the element has a color if (formObj.border.value != "" && formObj.bordercolor.value != "") st['border-width'] = formObj.border.value + "px"; formObj.style.value = tinyMCE.serializeStyle(st); } function changedColor() { var formObj = document.forms[0]; var st = tinyMCE.parseStyle(formObj.style.value); st['background-color'] = formObj.bgcolor.value; if (formObj.bordercolor.value != "") { st['border-color'] = formObj.bordercolor.value; // Add border-width if it's missing if (!st['border-width']) st['border-width'] = formObj.border.value == "" ? "1px" : formObj.border.value + "px"; } formObj.style.value = tinyMCE.serializeStyle(st); } function changedStyle() { var formObj = document.forms[0]; var st = tinyMCE.parseStyle(formObj.style.value); if (st['background-image']) formObj.backgroundimage.value = st['background-image'].replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1"); else formObj.backgroundimage.value = ''; if (st['width']) formObj.width.value = trimSize(st['width']); if (st['height']) formObj.height.value = trimSize(st['height']); if (st['background-color']) { formObj.bgcolor.value = st['background-color']; updateColor('bgcolor_pick','bgcolor'); } if (st['border-color']) { formObj.bordercolor.value = st['border-color']; updateColor('bordercolor_pick','bordercolor'); } }
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/table/jscripts/table.js
table.js
tinyMCE.importPluginLanguagePack('searchreplace','en,tr,sv,zh_cn,fa,fr_ca,fr,de,pl,pt_br,cs,nl,da,he,nb,hu,ru,ru_KOI8-R,ru_UTF-8,nn,fi,cy,es,is,zh_tw,zh_tw_utf8,sk');var TinyMCE_SearchReplacePlugin={getInfo:function(){return{longname:'Search/Replace',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_searchreplace.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion};},initInstance:function(inst){inst.addShortcut('ctrl','f','lang_searchreplace_search_desc','mceSearch',true);},getControlHTML:function(cn){switch(cn){case"search":return tinyMCE.getButtonHTML(cn,'lang_searchreplace_search_desc','{$pluginurl}/images/search.gif','mceSearch',true);case"replace":return tinyMCE.getButtonHTML(cn,'lang_searchreplace_replace_desc','{$pluginurl}/images/replace.gif','mceSearchReplace',true);}return"";},execCommand:function(editor_id,element,command,user_interface,value){var instance=tinyMCE.getInstanceById(editor_id);function defValue(key,default_value){value[key]=typeof(value[key])=="undefined"?default_value:value[key];}function replaceSel(search_str,str,back){instance.execCommand('mceInsertContent',false,str);}if(!value)value=new Array();defValue("editor_id",editor_id);defValue("searchstring","");defValue("replacestring",null);defValue("replacemode","none");defValue("casesensitive",false);defValue("backwards",false);defValue("wrap",false);defValue("wholeword",false);defValue("inline","yes");switch(command){case"mceResetSearch":tinyMCE.lastSearchRng=null;return true;case"mceSearch":if(user_interface){var template=new Array();if(value['replacestring']!=null){template['file']='../../plugins/searchreplace/replace.htm';template['width']=320;template['height']=100+(tinyMCE.isNS7?20:0);template['width']+=tinyMCE.getLang('lang_searchreplace_replace_delta_width',0);template['height']+=tinyMCE.getLang('lang_searchreplace_replace_delta_height',0);}else{template['file']='../../plugins/searchreplace/search.htm';template['width']=310;template['height']=105+(tinyMCE.isNS7?25:0);template['width']+=tinyMCE.getLang('lang_searchreplace_search_delta_width',0);template['height']+=tinyMCE.getLang('lang_searchreplace_replace_delta_height',0);}instance.execCommand('SelectAll');if(tinyMCE.isMSIE){var r=instance.selection.getRng();r.collapse(true);r.select();}else instance.selection.getSel().collapseToStart();tinyMCE.openWindow(template,value);}else{var win=tinyMCE.getInstanceById(editor_id).contentWindow;var doc=tinyMCE.getInstanceById(editor_id).contentWindow.document;var body=tinyMCE.getInstanceById(editor_id).contentWindow.document.body;if(body.innerHTML==""){alert(tinyMCE.getLang('lang_searchreplace_notfound'));return true;}if(value['replacemode']=="current"){replaceSel(value['string'],value['replacestring'],value['backwards']);value['replacemode']="none";tinyMCE.execInstanceCommand(editor_id,'mceSearch',user_interface,value,false);return true;}if(tinyMCE.isMSIE){var rng=tinyMCE.lastSearchRng?tinyMCE.lastSearchRng:doc.selection.createRange();var flags=0;if(value['wholeword'])flags=flags|2;if(value['casesensitive'])flags=flags|4;if(!rng.findText){alert('This operation is currently not supported by this browser.');return true;}if(value['replacemode']=="all"){while(rng.findText(value['string'],value['backwards']?-1:1,flags)){rng.scrollIntoView();rng.select();rng.collapse(false);replaceSel(value['string'],value['replacestring'],value['backwards']);}alert(tinyMCE.getLang('lang_searchreplace_allreplaced'));return true;}if(rng.findText(value['string'],value['backwards']?-1:1,flags)){rng.scrollIntoView();rng.select();rng.collapse(value['backwards']);tinyMCE.lastSearchRng=rng;}else alert(tinyMCE.getLang('lang_searchreplace_notfound'));}else{if(value['replacemode']=="all"){while(win.find(value['string'],value['casesensitive'],value['backwards'],value['wrap'],value['wholeword'],false,false))replaceSel(value['string'],value['replacestring'],value['backwards']);alert(tinyMCE.getLang('lang_searchreplace_allreplaced'));return true;}if(!win.find(value['string'],value['casesensitive'],value['backwards'],value['wrap'],value['wholeword'],false,false))alert(tinyMCE.getLang('lang_searchreplace_notfound'));}}return true;case"mceSearchReplace":value['replacestring']="";tinyMCE.execInstanceCommand(editor_id,'mceSearch',user_interface,value,false);return true;}return false;}};tinyMCE.addPlugin("searchreplace",TinyMCE_SearchReplacePlugin);
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/searchreplace/editor_plugin.js
editor_plugin.js
tinyMCE.importPluginLanguagePack('preview','en,tr,cs,de,el,fr_ca,it,ko,pt,sv,zh_cn,fa,fr,pl,pt_br,nl,da,he,nb,hu,ru,ru_KOI8-R,ru_UTF-8,nn,es,cy,is,zh_tw,zh_tw_utf8,sk');var TinyMCE_PreviewPlugin={getInfo:function(){return{longname:'Preview',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_preview.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion};},getControlHTML:function(cn){switch(cn){case"preview":return tinyMCE.getButtonHTML(cn,'lang_preview_desc','{$pluginurl}/images/preview.gif','mcePreview');}return"";},execCommand:function(editor_id,element,command,user_interface,value){switch(command){case"mcePreview":var previewPage=tinyMCE.getParam("plugin_preview_pageurl",null);var previewWidth=tinyMCE.getParam("plugin_preview_width","550");var previewHeight=tinyMCE.getParam("plugin_preview_height","600");if(previewPage){var template=new Array();template['file']=previewPage;template['width']=previewWidth;template['height']=previewHeight;tinyMCE.openWindow(template,{editor_id:editor_id,resizable:"yes",scrollbars:"yes",inline:"yes",content:tinyMCE.getContent(),content_css:tinyMCE.getParam("content_css")});}else{var win=window.open("","mcePreview","menubar=no,toolbar=no,scrollbars=yes,resizable=yes,left=20,top=20,width="+previewWidth+",height="+previewHeight);var html="";var c=tinyMCE.getContent();var pos=c.indexOf('<body'),pos2;if(pos!=-1){pos=c.indexOf('>',pos);pos2=c.lastIndexOf('</body>');c=c.substring(pos+1,pos2);}html+=tinyMCE.getParam('doctype');html+='<html xmlns="http://www.w3.org/1999/xhtml">';html+='<head>';html+='<title>'+tinyMCE.getLang('lang_preview_desc')+'</title>';html+='<base href="'+tinyMCE.settings['base_href']+'" />';html+='<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';html+='<link href="'+tinyMCE.getParam("content_css")+'" rel="stylesheet" type="text/css" />';html+='</head>';html+='<body dir="'+tinyMCE.getParam("directionality")+'">';html+=c;html+='</body>';html+='</html>';win.document.write(html);win.document.close();}return true;}return false;}};tinyMCE.addPlugin("preview",TinyMCE_PreviewPlugin);
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/preview/editor_plugin.js
editor_plugin.js
var TinyMCE_NonEditablePlugin={getInfo:function(){return{longname:'Non editable elements',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_noneditable.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion};},initInstance:function(inst){tinyMCE.importCSS(inst.getDoc(),tinyMCE.baseURL+"/plugins/noneditable/css/noneditable.css");if(tinyMCE.isMSIE5_0)tinyMCE.settings['plugins']=tinyMCE.settings['plugins'].replace(/noneditable/gi,'Noneditable');if(tinyMCE.isGecko){tinyMCE.addEvent(inst.getDoc(),"keyup",TinyMCE_NonEditablePlugin._fixKeyUp);}},cleanup:function(type,content,inst){switch(type){case"insert_to_editor_dom":var nodes=tinyMCE.getNodeTree(content,new Array(),1);var editClass=tinyMCE.getParam("noneditable_editable_class","mceEditable");var nonEditClass=tinyMCE.getParam("noneditable_noneditable_class","mceNonEditable");for(var i=0;i<nodes.length;i++){var elm=nodes[i];var editable=tinyMCE.getAttrib(elm,"contenteditable");if(new RegExp("true|false","gi").test(editable))TinyMCE_NonEditablePlugin._setEditable(elm,editable=="true");if(tinyMCE.isMSIE){var className=elm.className?elm.className:"";if(className.indexOf(editClass)!=-1)elm.contentEditable=true;if(className.indexOf(nonEditClass)!=-1)elm.contentEditable=false;}}break;case"insert_to_editor":if(tinyMCE.isMSIE){var editClass=tinyMCE.getParam("noneditable_editable_class","mceEditable");var nonEditClass=tinyMCE.getParam("noneditable_noneditable_class","mceNonEditable");content=content.replace(new RegExp("class=\"(.*)("+editClass+")([^\"]*)\"","gi"),'class="$1$2$3" contenteditable="true"');content=content.replace(new RegExp("class=\"(.*)("+nonEditClass+")([^\"]*)\"","gi"),'class="$1$2$3" contenteditable="false"');}break;case"get_from_editor_dom":if(tinyMCE.getParam("noneditable_leave_contenteditable",false)){var nodes=tinyMCE.getNodeTree(content,new Array(),1);for(var i=0;i<nodes.length;i++)nodes[i].removeAttribute("contenteditable");}break;}return content;},_fixKeyUp:function(e){var inst=tinyMCE.selectedInstance;var sel=inst.getSel();var rng=inst.getRng();var an=sel.anchorNode;if((e.keyCode==38||e.keyCode==37||e.keyCode==40||e.keyCode==39)&&(elm=TinyMCE_NonEditablePlugin._isNonEditable(an))!=null){rng=inst.getDoc().createRange();rng.selectNode(elm);rng.collapse(true);sel.removeAllRanges();sel.addRange(rng);tinyMCE.cancelEvent(e);}},_isNonEditable:function(elm){var editClass=tinyMCE.getParam("noneditable_editable_class","mceEditable");var nonEditClass=tinyMCE.getParam("noneditable_noneditable_class","mceNonEditable");if(!elm)return;do{var className=elm.className?elm.className:"";if(className.indexOf(editClass)!=-1)return null;if(className.indexOf(nonEditClass)!=-1)return elm;}while(elm=elm.parentNode);return null;},_setEditable:function(elm,state){var editClass=tinyMCE.getParam("noneditable_editable_class","mceEditable");var nonEditClass=tinyMCE.getParam("noneditable_noneditable_class","mceNonEditable");var className=elm.className?elm.className:"";if(className.indexOf(editClass)!=-1||className.indexOf(nonEditClass)!=-1)return;if((className=tinyMCE.getAttrib(elm,"class"))!="")className+=" ";className+=state?editClass:nonEditClass;elm.setAttribute("class",className);elm.className=className;}};tinyMCE.addPlugin("noneditable",TinyMCE_NonEditablePlugin);
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/noneditable/editor_plugin.js
editor_plugin.js
if(!tinyMCE.settings['contextmenu_skip_plugin_css']){tinyMCE.loadCSS(tinyMCE.baseURL+"/plugins/contextmenu/css/contextmenu.css");}var TinyMCE_ContextMenuPlugin={_contextMenu:null,getInfo:function(){return{longname:'Context menus',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_contextmenu.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion};},initInstance:function(inst){if(tinyMCE.isMSIE5_0&&tinyMCE.isOpera)return;TinyMCE_ContextMenuPlugin._contextMenu=new TinyMCE_ContextMenu({commandhandler:"TinyMCE_ContextMenuPlugin._commandHandler",spacer_image:tinyMCE.baseURL+"/plugins/contextmenu/images/spacer.gif"});tinyMCE.addEvent(inst.getDoc(),"click",TinyMCE_ContextMenuPlugin._hideContextMenu);tinyMCE.addEvent(inst.getDoc(),"keypress",TinyMCE_ContextMenuPlugin._hideContextMenu);tinyMCE.addEvent(inst.getDoc(),"keydown",TinyMCE_ContextMenuPlugin._hideContextMenu);tinyMCE.addEvent(document,"click",TinyMCE_ContextMenuPlugin._hideContextMenu);tinyMCE.addEvent(document,"keypress",TinyMCE_ContextMenuPlugin._hideContextMenu);tinyMCE.addEvent(document,"keydown",TinyMCE_ContextMenuPlugin._hideContextMenu);if(tinyMCE.isGecko){tinyMCE.addEvent(inst.getDoc(),"contextmenu",function(e){TinyMCE_ContextMenuPlugin._showContextMenu(tinyMCE.isMSIE?inst.contentWindow.event:e,inst);});}else tinyMCE.addEvent(inst.getDoc(),"contextmenu",TinyMCE_ContextMenuPlugin._onContextMenu);},_onContextMenu:function(e){var elm=tinyMCE.isMSIE?e.srcElement:e.target;var targetInst,body;if((body=tinyMCE.getParentElement(elm,"body"))!=null){for(var n in tinyMCE.instances){var inst=tinyMCE.instances[n];if(!tinyMCE.isInstance(inst))continue;if(body==inst.getBody()){targetInst=inst;break;}}return TinyMCE_ContextMenuPlugin._showContextMenu(tinyMCE.isMSIE?targetInst.contentWindow.event:e,targetInst);}},_showContextMenu:function(e,inst){function getAttrib(elm,name){return elm.getAttribute(name)?elm.getAttribute(name):"";}var x,y,elm,contextMenu;var pos=tinyMCE.getAbsPosition(inst.iframeElement);x=tinyMCE.isMSIE?e.screenX:pos.absLeft+(e.pageX-inst.getBody().scrollLeft);y=tinyMCE.isMSIE?e.screenY:pos.absTop+(e.pageY-inst.getBody().scrollTop);elm=tinyMCE.isMSIE?e.srcElement:e.target;contextMenu=this._contextMenu;contextMenu.inst=inst;window.setTimeout(function(){var theme=tinyMCE.getParam("theme");contextMenu.clearAll();var sel=inst.selection.getSelectedText().length!=0||elm.nodeName=="IMG";contextMenu.addItem(tinyMCE.baseURL+"/themes/"+theme+"/images/cut.gif","$lang_cut_desc","Cut","",!sel);contextMenu.addItem(tinyMCE.baseURL+"/themes/"+theme+"/images/copy.gif","$lang_copy_desc","Copy","",!sel);contextMenu.addItem(tinyMCE.baseURL+"/themes/"+theme+"/images/paste.gif","$lang_paste_desc","Paste","",false);if(sel||(elm?(elm.nodeName=='A')||(elm.nodeName=='IMG'):false)){contextMenu.addSeparator();contextMenu.addItem(tinyMCE.baseURL+"/themes/advanced/images/link.gif","$lang_link_desc",inst.hasPlugin("advlink")?"mceAdvLink":"mceLink");contextMenu.addItem(tinyMCE.baseURL+"/themes/advanced/images/unlink.gif","$lang_unlink_desc","unlink","",(elm?(elm.nodeName!='A')&&(elm.nodeName!='IMG'):true));}elm=tinyMCE.getParentElement(elm,"img,table,td"+(inst.hasPlugin("advhr")?',hr':''));if(elm){switch(elm.nodeName){case"IMG":contextMenu.addSeparator();if(tinyMCE.getAttrib(elm,'class').indexOf('mceItemFlash')!=-1)contextMenu.addItem(tinyMCE.baseURL+"/plugins/flash/images/flash.gif","$lang_flash_props","mceFlash");else contextMenu.addItem(tinyMCE.baseURL+"/themes/"+theme+"/images/image.gif","$lang_image_props_desc",inst.hasPlugin("advimage")?"mceAdvImage":"mceImage");break;case"HR":contextMenu.addSeparator();contextMenu.addItem(tinyMCE.baseURL+"/plugins/advhr/images/advhr.gif","$lang_insert_advhr_desc","mceAdvancedHr");break;case"TABLE":case"TD":if(inst.hasPlugin("table")){var colspan=(elm.nodeName=="TABLE")?"":getAttrib(elm,"colspan");var rowspan=(elm.nodeName=="TABLE")?"":getAttrib(elm,"rowspan");colspan=colspan==""?"1":colspan;rowspan=rowspan==""?"1":rowspan;contextMenu.addSeparator();contextMenu.addItem(tinyMCE.baseURL+"/themes/"+theme+"/images/cut.gif","$lang_table_cut_row_desc","mceTableCutRow");contextMenu.addItem(tinyMCE.baseURL+"/themes/"+theme+"/images/copy.gif","$lang_table_copy_row_desc","mceTableCopyRow");contextMenu.addItem(tinyMCE.baseURL+"/themes/"+theme+"/images/paste.gif","$lang_table_paste_row_before_desc","mceTablePasteRowBefore","",inst.tableRowClipboard==null);contextMenu.addItem(tinyMCE.baseURL+"/themes/"+theme+"/images/paste.gif","$lang_table_paste_row_after_desc","mceTablePasteRowAfter","",inst.tableRowClipboard==null);contextMenu.addSeparator();contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table.gif","$lang_table_desc","mceInsertTable","insert");contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table.gif","$lang_table_props_desc","mceInsertTable");contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table_cell_props.gif","$lang_table_cell_desc","mceTableCellProps");contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table_delete.gif","$lang_table_del","mceTableDelete");contextMenu.addSeparator();contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table_row_props.gif","$lang_table_row_desc","mceTableRowProps");contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table_insert_row_before.gif","$lang_table_row_before_desc","mceTableInsertRowBefore");contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table_insert_row_after.gif","$lang_table_row_after_desc","mceTableInsertRowAfter");contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table_delete_row.gif","$lang_table_delete_row_desc","mceTableDeleteRow");contextMenu.addSeparator();contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table_insert_col_before.gif","$lang_table_col_before_desc","mceTableInsertColBefore");contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table_insert_col_after.gif","$lang_table_col_after_desc","mceTableInsertColAfter");contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table_delete_col.gif","$lang_table_delete_col_desc","mceTableDeleteCol");contextMenu.addSeparator();contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table_split_cells.gif","$lang_table_split_cells_desc","mceTableSplitCells","",(colspan=="1"&&rowspan=="1"));contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table_merge_cells.gif","$lang_table_merge_cells_desc","mceTableMergeCells","",false);}break;}}else{if(inst.hasPlugin("table")){contextMenu.addSeparator();contextMenu.addItem(tinyMCE.baseURL+"/plugins/table/images/table.gif","$lang_table_desc","mceInsertTable","insert");}}contextMenu.show(x,y);},10);tinyMCE.cancelEvent(e);return false;},_hideContextMenu:function(){if(TinyMCE_ContextMenuPlugin._contextMenu)TinyMCE_ContextMenuPlugin._contextMenu.hide();},_commandHandler:function(command,value){var cm=TinyMCE_ContextMenuPlugin._contextMenu;cm.hide();var ui=false;if(command=="mceInsertTable"||command=="mceTableCellProps"||command=="mceTableRowProps"||command=="mceTableMergeCells")ui=true;if(command=="Paste")value=null;if(tinyMCE.getParam("dialog_type")=="modal"&&tinyMCE.isMSIE){window.setTimeout(function(){cm.inst.execCommand(command,ui,value);},100);}else cm.inst.execCommand(command,ui,value);}};tinyMCE.addPlugin("contextmenu",TinyMCE_ContextMenuPlugin);function TinyMCE_ContextMenu(settings){function defParam(key,def_val){settings[key]=typeof(settings[key])!="undefined"?settings[key]:def_val;}var self=this;this.isMSIE=(navigator.appName=="Microsoft Internet Explorer");this.contextMenuDiv=document.createElement("div");this.contextMenuDiv.className="contextMenu";this.contextMenuDiv.setAttribute("class","contextMenu");this.contextMenuDiv.style.display="none";this.contextMenuDiv.style.position='absolute';this.contextMenuDiv.style.zindex=1000;this.contextMenuDiv.style.left='0';this.contextMenuDiv.style.top='0';this.contextMenuDiv.unselectable="on";document.body.appendChild(this.contextMenuDiv);defParam("commandhandler","");defParam("spacer_image","images/spacer.gif");this.items=new Array();this.settings=settings;this.html="";if(tinyMCE.isMSIE&&!tinyMCE.isMSIE5_0&&!tinyMCE.isOpera){this.pop=window.createPopup();doc=this.pop.document;doc.open();doc.write('<html><head><link href="'+tinyMCE.baseURL+'/plugins/contextmenu/css/contextmenu.css" rel="stylesheet" type="text/css" /></head><body unselectable="yes" class="contextMenuIEPopup"></body></html>');doc.close();}};TinyMCE_ContextMenu.prototype={clearAll:function(){this.html="";this.contextMenuDiv.innerHTML="";},addSeparator:function(){this.html+='<tr class="contextMenuItem"><td class="contextMenuIcon"><img src="'+this.settings['spacer_image']+'" width="20" height="1" class="contextMenuImage" /></td><td><img class="contextMenuSeparator" width="1" height="1" src="'+this.settings['spacer_image']+'" /></td></tr>';},addItem:function(icon,title,command,value,disabled){if(title.charAt(0)=='$')title=tinyMCE.getLang(title.substring(1));var onMouseDown='';var html='';if(tinyMCE.isMSIE&&!tinyMCE.isMSIE5_0)onMouseDown='contextMenu.execCommand(\''+command+'\', \''+value+'\');return false;';else onMouseDown=this.settings['commandhandler']+'(\''+command+'\', \''+value+'\');return false;';if(icon=="")icon=this.settings['spacer_image'];if(!disabled)html+='<tr class="contextMenuItem">';else html+='<tr class="contextMenuItemDisabled">';html+='<td class="contextMenuIcon"><img src="'+icon+'" width="20" height="20" class="contextMenuImage" /></td>';html+='<td><div class="contextMenuText">';html+='<a href="javascript:void(0);" onclick="'+onMouseDown+'" onmousedown="return false;">&nbsp;';html+=title;html+='&nbsp;</a>';html+='</div></td>';html+='</tr>';this.html+=html;},show:function(x,y){if(this.html=="")return;var html='';html+='<a href="#"></a><table border="0" cellpadding="0" cellspacing="0">';html+=this.html;html+='</table>';this.contextMenuDiv.innerHTML=html;if(tinyMCE.isMSIE&&!tinyMCE.isMSIE5_0&&!tinyMCE.isOpera){var width,height;this.contextMenuDiv.style.display="block";width=this.contextMenuDiv.offsetWidth;height=this.contextMenuDiv.offsetHeight;this.contextMenuDiv.style.display="none";this.pop.document.body.innerHTML='<div class="contextMenu">'+html+"</div>";this.pop.document.tinyMCE=tinyMCE;this.pop.document.contextMenu=this;this.pop.show(x,y,width,height);}else{this.contextMenuDiv.style.left=x+'px';this.contextMenuDiv.style.top=y+'px';this.contextMenuDiv.style.display="block";}},hide:function(){if(tinyMCE.isMSIE&&!tinyMCE.isMSIE5_0&&!tinyMCE.isOpera)this.pop.hide();else this.contextMenuDiv.style.display="none";},execCommand:function(command,value){eval(this.settings['commandhandler']+"(command, value);");}};
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/contextmenu/editor_plugin.js
editor_plugin.js
tinyMCE.importPluginLanguagePack('template','en,tr,he,nb,ru,ru_KOI8-R,ru_UTF-8,nn,fi,cy,es,is,pl');var TinyMCE_TemplatePlugin={getInfo:function(){return{longname:'Template plugin',author:'Your name',authorurl:'http://www.yoursite.com',infourl:'http://www.yoursite.com/docs/template.html',version:"1.0"};},initInstance:function(inst){alert("Initialization parameter:"+tinyMCE.getParam("template_someparam",false));inst.addShortcut('ctrl','t','lang_template_desc','mceTemplate');},getControlHTML:function(cn){switch(cn){case"template":return tinyMCE.getButtonHTML(cn,'lang_template_desc','{$pluginurl}/images/template.gif','mceTemplate',true);}return"";},execCommand:function(editor_id,element,command,user_interface,value){switch(command){case"mceTemplate":if(user_interface){var template=new Array();template['file']='../../plugins/template/popup.htm';template['width']=300;template['height']=200;tinyMCE.openWindow(template,{editor_id:editor_id,some_custom_arg:"somecustomdata"});tinyMCE.triggerNodeChange(false);}else{alert("execCommand: mceTemplate gets called from popup.");}return true;}return false;},handleNodeChange:function(editor_id,node,undo_index,undo_levels,visual_aid,any_selection){if(node.parentNode.nodeName=="STRONG"||node.parentNode.nodeName=="B"){tinyMCE.switchClass(editor_id+'_template','mceButtonSelected');return true;}tinyMCE.switchClass(editor_id+'_template','mceButtonNormal');},setupContent:function(editor_id,body,doc){},onChange:function(inst){},handleEvent:function(e){top.status="template plugin event: "+e.type;return true;},cleanup:function(type,content,inst){switch(type){case"get_from_editor":alert("[FROM] Value HTML string: "+content);break;case"insert_to_editor":alert("[TO] Value HTML string: "+content);break;case"get_from_editor_dom":alert("[FROM] Value DOM Element "+content.innerHTML);break;case"insert_to_editor_dom":alert("[TO] Value DOM Element: "+content.innerHTML);break;}return content;},_someInternalFunction:function(a,b){return 1;}};tinyMCE.addPlugin("template",TinyMCE_TemplatePlugin);
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/_template/editor_plugin.js
editor_plugin.js
var TinyMCE_InlinePopupsPlugin={getInfo:function(){return{longname:'Inline Popups',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_inlinepopups.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion};}};tinyMCE.addPlugin("inlinepopups",TinyMCE_InlinePopupsPlugin);TinyMCE_Engine.prototype.orgOpenWindow=TinyMCE_Engine.prototype.openWindow;TinyMCE_Engine.prototype.openWindow=function(template,args){if(args['inline']!="yes"||tinyMCE.isOpera||tinyMCE.getParam("plugins").indexOf('inlinepopups')==-1){mcWindows.selectedWindow=null;args['mce_inside_iframe']=false;this.orgOpenWindow(template,args);return;}var url,resizable,scrollbars;args['mce_inside_iframe']=true;tinyMCE.windowArgs=args;if(template['file'].charAt(0)!='/'&&template['file'].indexOf('://')==-1)url=tinyMCE.baseURL+"/themes/"+tinyMCE.getParam("theme")+"/"+template['file'];else url=template['file'];if(!(width=parseInt(template['width'])))width=320;if(!(height=parseInt(template['height'])))height=200;resizable=(args&&args['resizable'])?args['resizable']:"no";scrollbars=(args&&args['scrollbars'])?args['scrollbars']:"no";height+=18;for(var name in args){if(typeof(args[name])=='function')continue;url=tinyMCE.replaceVar(url,name,escape(args[name]));}var elm=document.getElementById(this.selectedInstance.editorId+'_parent');var pos=tinyMCE.getAbsPosition(elm);pos.absLeft+=Math.round((elm.firstChild.clientWidth/2)-(width/2));pos.absTop+=Math.round((elm.firstChild.clientHeight/2)-(height/2));mcWindows.open(url,mcWindows.idCounter++,"modal=yes,width="+width+",height="+height+",resizable="+resizable+",scrollbars="+scrollbars+",statusbar="+resizable+",left="+pos.absLeft+",top="+pos.absTop);};TinyMCE_Engine.prototype.orgCloseWindow=TinyMCE_Engine.prototype.closeWindow;TinyMCE_Engine.prototype.closeWindow=function(win){if(mcWindows.selectedWindow!=null)mcWindows.selectedWindow.close();else this.orgCloseWindow(win);};TinyMCE_Engine.prototype.setWindowTitle=function(win_ref,title){for(var n in mcWindows.windows){var win=mcWindows.windows[n];if(typeof(win)=='function')continue;if(win_ref.name==win.id+"_iframe")window.frames[win.id+"_iframe"].document.getElementById(win.id+'_title').innerHTML=title;}};function TinyMCE_Windows(){this.settings=new Array();this.windows=new Array();this.isMSIE=(navigator.appName=="Microsoft Internet Explorer");this.isGecko=navigator.userAgent.indexOf('Gecko')!=-1;this.isSafari=navigator.userAgent.indexOf('Safari')!=-1;this.isMac=navigator.userAgent.indexOf('Mac')!=-1;this.isMSIE5_0=this.isMSIE&&(navigator.userAgent.indexOf('MSIE 5.0')!=-1);this.action="none";this.selectedWindow=null;this.lastSelectedWindow=null;this.zindex=100;this.mouseDownScreenX=0;this.mouseDownScreenY=0;this.mouseDownLayerX=0;this.mouseDownLayerY=0;this.mouseDownWidth=0;this.mouseDownHeight=0;this.idCounter=0;};TinyMCE_Windows.prototype.init=function(settings){this.settings=settings;if(this.isMSIE)this.addEvent(document,"mousemove",mcWindows.eventDispatcher);else this.addEvent(window,"mousemove",mcWindows.eventDispatcher);this.addEvent(document,"mouseup",mcWindows.eventDispatcher);this.doc=document;};TinyMCE_Windows.prototype.getParam=function(name,default_value){var value=null;value=(typeof(this.settings[name])=="undefined")?default_value:this.settings[name];if(value=="true"||value=="false")return(value=="true");return value;};TinyMCE_Windows.prototype.eventDispatcher=function(e){e=typeof(e)=="undefined"?window.event:e;if(mcWindows.selectedWindow==null)return;if(mcWindows.isGecko&&e.type=="mousedown"){var elm=e.currentTarget;for(var n in mcWindows.windows){var win=mcWindows.windows[n];if(win.headElement==elm||win.resizeElement==elm){win.focus();break;}}}switch(e.type){case"mousemove":mcWindows.selectedWindow.onMouseMove(e);break;case"mouseup":mcWindows.selectedWindow.onMouseUp(e);break;case"mousedown":mcWindows.selectedWindow.onMouseDown(e);break;case"focus":mcWindows.selectedWindow.onFocus(e);break;}};TinyMCE_Windows.prototype.addEvent=function(obj,name,handler){if(this.isMSIE)obj.attachEvent("on"+name,handler);else obj.addEventListener(name,handler,true);};TinyMCE_Windows.prototype.cancelEvent=function(e){if(this.isMSIE){e.returnValue=false;e.cancelBubble=true;}else e.preventDefault();};TinyMCE_Windows.prototype.parseFeatures=function(opts){opts=opts.toLowerCase();opts=opts.replace(/;/g,",");opts=opts.replace(/[^0-9a-z=,]/g,"");var optionChunks=opts.split(',');var options=new Array();options['left']="10";options['top']="10";options['width']="300";options['height']="300";options['resizable']="yes";options['minimizable']="yes";options['maximizable']="yes";options['close']="yes";options['movable']="yes";options['statusbar']="yes";options['scrollbars']="auto";options['modal']="no";if(opts=="")return options;for(var i=0;i<optionChunks.length;i++){var parts=optionChunks[i].split('=');if(parts.length==2)options[parts[0]]=parts[1];}options['left']=parseInt(options['left']);options['top']=parseInt(options['top']);options['width']=parseInt(options['width']);options['height']=parseInt(options['height']);return options;};TinyMCE_Windows.prototype.open=function(url,name,features){this.lastSelectedWindow=this.selectedWindow;var win=new TinyMCE_Window();var winDiv,html="",id;var imgPath=this.getParam("images_path");features=this.parseFeatures(features);id="mcWindow_"+name;win.deltaHeight=18;if(features['statusbar']=="yes"){win.deltaHeight+=13;if(this.isMSIE)win.deltaHeight+=1;}width=parseInt(features['width']);height=parseInt(features['height'])-win.deltaHeight;if(this.isMSIE)width-=2;win.id=id;win.url=url;win.name=name;win.features=features;this.windows[name]=win;iframeWidth=width;iframeHeight=height;html+='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">';html+='<html>';html+='<head>';html+='<title>Wrapper iframe</title>';html+='<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';html+='<link href="'+this.getParam("css_file")+'" rel="stylesheet" type="text/css" />';html+='</head>';html+='<body onload="parent.mcWindows.onLoad(\''+name+'\');">';html+='<div id="'+id+'_container" class="mceWindow">';html+='<div id="'+id+'_head" class="mceWindowHead" onmousedown="parent.mcWindows.windows[\''+name+'\'].focus();">';html+=' <div id="'+id+'_title" class="mceWindowTitle"';html+=' onselectstart="return false;" unselectable="on" style="-moz-user-select: none !important;"></div>';html+=' <div class="mceWindowHeadTools">';html+=' <a href="javascript:parent.mcWindows.windows[\''+name+'\'].close();" target="_self" onmousedown="return false;" class="mceWindowClose"><img border="0" src="'+imgPath+'/window_close.gif" /></a>';html+=' </div>';html+='</div><div id="'+id+'_body" class="mceWindowBody" style="width: '+width+'px; height: '+height+'px;">';html+='<iframe id="'+id+'_iframe" name="'+id+'_iframe" frameborder="0" width="'+iframeWidth+'" height="'+iframeHeight+'" src="'+url+'" class="mceWindowBodyIframe" scrolling="'+features['scrollbars']+'"></iframe></div>';if(features['statusbar']=="yes"){html+='<div id="'+id+'_statusbar" class="mceWindowStatusbar" onmousedown="parent.mcWindows.windows[\''+name+'\'].focus();">';if(features['resizable']=="yes"){if(this.isGecko)html+='<div id="'+id+'_resize" class="mceWindowResize"><div style="background-image: url(\''+imgPath+'/window_resize.gif\'); width: 12px; height: 12px;"></div></div>';else html+='<div id="'+id+'_resize" class="mceWindowResize"><img onmousedown="parent.mcWindows.windows[\''+name+'\'].focus();" border="0" src="'+imgPath+'/window_resize.gif" /></div>';}html+='</div>';}html+='</div>';html+='</body>';html+='</html>';this.createFloatingIFrame(id,features['left'],features['top'],features['width'],features['height'],html);};TinyMCE_Windows.prototype.setDocumentLock=function(state){if(state){var elm=document.getElementById('mcWindowEventBlocker');if(elm==null){elm=document.createElement("div");elm.id="mcWindowEventBlocker";elm.style.position="absolute";elm.style.left="0";elm.style.top="0";document.body.appendChild(elm);}elm.style.display="none";var imgPath=this.getParam("images_path");var width=document.body.clientWidth;var height=document.body.clientHeight;elm.style.width=width;elm.style.height=height;elm.innerHTML='<img src="'+imgPath+'/spacer.gif" width="'+width+'" height="'+height+'" />';elm.style.zIndex=mcWindows.zindex-1;elm.style.display="block";}else{var elm=document.getElementById('mcWindowEventBlocker');if(mcWindows.windows.length==0)elm.parentNode.removeChild(elm);else elm.style.zIndex=mcWindows.zindex-1;}};TinyMCE_Windows.prototype.onLoad=function(name){var win=mcWindows.windows[name];var id="mcWindow_"+name;var wrapperIframe=window.frames[id+"_iframe"].frames[0];var wrapperDoc=window.frames[id+"_iframe"].document;var doc=window.frames[id+"_iframe"].document;var winDiv=document.getElementById("mcWindow_"+name+"_div");var realIframe=window.frames[id+"_iframe"].frames[0];win.id="mcWindow_"+name;win.winElement=winDiv;win.bodyElement=doc.getElementById(id+'_body');win.iframeElement=doc.getElementById(id+'_iframe');win.headElement=doc.getElementById(id+'_head');win.titleElement=doc.getElementById(id+'_title');win.resizeElement=doc.getElementById(id+'_resize');win.containerElement=doc.getElementById(id+'_container');win.left=win.features['left'];win.top=win.features['top'];win.frame=window.frames[id+'_iframe'].frames[0];win.wrapperFrame=window.frames[id+'_iframe'];win.wrapperIFrameElement=document.getElementById(id+"_iframe");mcWindows.addEvent(win.headElement,"mousedown",mcWindows.eventDispatcher);if(win.resizeElement!=null)mcWindows.addEvent(win.resizeElement,"mousedown",mcWindows.eventDispatcher);if(mcWindows.isMSIE){mcWindows.addEvent(realIframe.document,"mousemove",mcWindows.eventDispatcher);mcWindows.addEvent(realIframe.document,"mouseup",mcWindows.eventDispatcher);}else{mcWindows.addEvent(realIframe,"mousemove",mcWindows.eventDispatcher);mcWindows.addEvent(realIframe,"mouseup",mcWindows.eventDispatcher);mcWindows.addEvent(realIframe,"focus",mcWindows.eventDispatcher);}for(var i=0;i<window.frames.length;i++){if(!window.frames[i]._hasMouseHandlers){if(mcWindows.isMSIE){mcWindows.addEvent(window.frames[i].document,"mousemove",mcWindows.eventDispatcher);mcWindows.addEvent(window.frames[i].document,"mouseup",mcWindows.eventDispatcher);}else{mcWindows.addEvent(window.frames[i],"mousemove",mcWindows.eventDispatcher);mcWindows.addEvent(window.frames[i],"mouseup",mcWindows.eventDispatcher);}window.frames[i]._hasMouseHandlers=true;}}if(mcWindows.isMSIE){mcWindows.addEvent(win.frame.document,"mousemove",mcWindows.eventDispatcher);mcWindows.addEvent(win.frame.document,"mouseup",mcWindows.eventDispatcher);}else{mcWindows.addEvent(win.frame,"mousemove",mcWindows.eventDispatcher);mcWindows.addEvent(win.frame,"mouseup",mcWindows.eventDispatcher);mcWindows.addEvent(win.frame,"focus",mcWindows.eventDispatcher);}var func=this.getParam("on_open_window","");if(func!="")eval(func+"(win);");win.focus();if(win.features['modal']=="yes")mcWindows.setDocumentLock(true);};TinyMCE_Windows.prototype.createFloatingIFrame=function(id_prefix,left,top,width,height,html){var iframe=document.createElement("iframe");var div=document.createElement("div");width=parseInt(width);height=parseInt(height)+1;div.setAttribute("id",id_prefix+"_div");div.setAttribute("width",width);div.setAttribute("height",(height));div.style.position="absolute";div.style.left=left+"px";div.style.top=top+"px";div.style.width=width+"px";div.style.height=(height)+"px";div.style.backgroundColor="white";div.style.display="none";if(this.isGecko){iframeWidth=width+2;iframeHeight=height+2;}else{iframeWidth=width;iframeHeight=height+1;}iframe.setAttribute("id",id_prefix+"_iframe");iframe.setAttribute("name",id_prefix+"_iframe");iframe.setAttribute("border","0");iframe.setAttribute("frameBorder","0");iframe.setAttribute("marginWidth","0");iframe.setAttribute("marginHeight","0");iframe.setAttribute("leftMargin","0");iframe.setAttribute("topMargin","0");iframe.setAttribute("width",iframeWidth);iframe.setAttribute("height",iframeHeight);iframe.setAttribute("scrolling","no");iframe.style.width=iframeWidth+"px";iframe.style.height=iframeHeight+"px";iframe.style.backgroundColor="white";div.appendChild(iframe);document.body.appendChild(div);div.innerHTML=div.innerHTML;if(this.isSafari){window.setTimeout(function(){doc=window.frames[id_prefix+'_iframe'].document;doc.open();doc.write(html);doc.close();},10);}else{doc=window.frames[id_prefix+'_iframe'].window.document;doc.open();doc.write(html);doc.close();}div.style.display="block";return div;};function TinyMCE_Window(){};TinyMCE_Window.prototype.focus=function(){if(this!=mcWindows.selectedWindow){this.winElement.style.zIndex=++mcWindows.zindex;mcWindows.lastSelectedWindow=mcWindows.selectedWindow;mcWindows.selectedWindow=this;}};TinyMCE_Window.prototype.minimize=function(){};TinyMCE_Window.prototype.maximize=function(){};TinyMCE_Window.prototype.startResize=function(){mcWindows.action="resize";};TinyMCE_Window.prototype.startMove=function(e){mcWindows.action="move";};TinyMCE_Window.prototype.close=function(){if(this.frame&&this.frame['tinyMCEPopup'])this.frame['tinyMCEPopup'].restoreSelection();if(mcWindows.lastSelectedWindow!=null)mcWindows.lastSelectedWindow.focus();var mcWindowsNew=new Array();for(var n in mcWindows.windows){var win=mcWindows.windows[n];if(typeof(win)=='function')continue;if(win.name!=this.name)mcWindowsNew[n]=win;}mcWindows.windows=mcWindowsNew;var e=mcWindows.doc.getElementById(this.id+"_iframe");e.parentNode.removeChild(e);var e=mcWindows.doc.getElementById(this.id+"_div");e.parentNode.removeChild(e);mcWindows.setDocumentLock(false);};TinyMCE_Window.prototype.onMouseMove=function(e){var scrollX=0;var scrollY=0;var dx=e.screenX-mcWindows.mouseDownScreenX;var dy=e.screenY-mcWindows.mouseDownScreenY;switch(mcWindows.action){case"resize":width=mcWindows.mouseDownWidth+(e.screenX-mcWindows.mouseDownScreenX);height=mcWindows.mouseDownHeight+(e.screenY-mcWindows.mouseDownScreenY);width=width<100?100:width;height=height<100?100:height;this.wrapperIFrameElement.style.width=width+2;this.wrapperIFrameElement.style.height=height+2;this.wrapperIFrameElement.width=width+2;this.wrapperIFrameElement.height=height+2;this.winElement.style.width=width;this.winElement.style.height=height;height=height-this.deltaHeight;this.containerElement.style.width=width;this.iframeElement.style.width=width;this.iframeElement.style.height=height;this.bodyElement.style.width=width;this.bodyElement.style.height=height;this.headElement.style.width=width;mcWindows.cancelEvent(e);break;case"move":this.left=mcWindows.mouseDownLayerX+(e.screenX-mcWindows.mouseDownScreenX);this.top=mcWindows.mouseDownLayerY+(e.screenY-mcWindows.mouseDownScreenY);this.winElement.style.left=this.left+"px";this.winElement.style.top=this.top+"px";mcWindows.cancelEvent(e);break;}};function debug(msg){document.getElementById('debug').value+=msg+"\n";}TinyMCE_Window.prototype.onMouseUp=function(e){mcWindows.action="none";};TinyMCE_Window.prototype.onFocus=function(e){var winRef=e.currentTarget;for(var n in mcWindows.windows){var win=mcWindows.windows[n];if(typeof(win)=='function')continue;if(winRef.name==win.id+"_iframe"){win.focus();return;}}};TinyMCE_Window.prototype.onMouseDown=function(e){var elm=mcWindows.isMSIE?this.wrapperFrame.event.srcElement:e.target;var scrollX=0;var scrollY=0;mcWindows.mouseDownScreenX=e.screenX;mcWindows.mouseDownScreenY=e.screenY;mcWindows.mouseDownLayerX=this.left;mcWindows.mouseDownLayerY=this.top;mcWindows.mouseDownWidth=parseInt(this.winElement.style.width);mcWindows.mouseDownHeight=parseInt(this.winElement.style.height);if(this.resizeElement!=null&&elm==this.resizeElement.firstChild)this.startResize(e);else this.startMove(e);mcWindows.cancelEvent(e);};var mcWindows=new TinyMCE_Windows();mcWindows.init({images_path:tinyMCE.baseURL+"/plugins/inlinepopups/images",css_file:tinyMCE.baseURL+"/plugins/inlinepopups/css/inlinepopup.css"});
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/inlinepopups/editor_plugin.js
editor_plugin.js
tinyMCE.importPluginLanguagePack('paste','en,tr,sv,cs,zh_cn,fr_ca,da,he,nb,de,hu,ru,ru_KOI8-R,ru_UTF-8,nn,fi,es,cy,is,pl,nl,fr,pt_br');var TinyMCE_PastePlugin={getInfo:function(){return{longname:'Paste text/word',author:'Moxiecode Systems',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_paste.html',version:tinyMCE.majorVersion+"."+tinyMCE.minorVersion};},initInstance:function(inst){if(tinyMCE.isMSIE&&tinyMCE.getParam("paste_auto_cleanup_on_paste",false))tinyMCE.addEvent(inst.getBody(),"paste",TinyMCE_PastePlugin._handlePasteEvent);},getControlHTML:function(cn){switch(cn){case"pastetext":return tinyMCE.getButtonHTML(cn,'lang_paste_text_desc','{$pluginurl}/images/pastetext.gif','mcePasteText',true);case"pasteword":return tinyMCE.getButtonHTML(cn,'lang_paste_word_desc','{$pluginurl}/images/pasteword.gif','mcePasteWord',true);case"selectall":return tinyMCE.getButtonHTML(cn,'lang_selectall_desc','{$pluginurl}/images/selectall.gif','mceSelectAll',true);}return'';},execCommand:function(editor_id,element,command,user_interface,value){switch(command){case"mcePasteText":if(user_interface){if((tinyMCE.isMSIE&&!tinyMCE.isOpera)&&!tinyMCE.getParam('paste_use_dialog',false))TinyMCE_PastePlugin._insertText(clipboardData.getData("Text"),true);else{var template=new Array();template['file']='../../plugins/paste/pastetext.htm';template['width']=450;template['height']=400;var plain_text="";tinyMCE.openWindow(template,{editor_id:editor_id,plain_text:plain_text,resizable:"yes",scrollbars:"no",inline:"yes",mceDo:'insert'});}}else TinyMCE_PastePlugin._insertText(value['html'],value['linebreaks']);return true;case"mcePasteWord":if(user_interface){if((tinyMCE.isMSIE&&!tinyMCE.isOpera)&&!tinyMCE.getParam('paste_use_dialog',false)){var html=TinyMCE_PastePlugin._clipboardHTML();if(html&&html.length>0)TinyMCE_PastePlugin._insertWordContent(html);}else{var template=new Array();template['file']='../../plugins/paste/pasteword.htm';template['width']=450;template['height']=400;var plain_text="";tinyMCE.openWindow(template,{editor_id:editor_id,plain_text:plain_text,resizable:"yes",scrollbars:"no",inline:"yes",mceDo:'insert'});}}else TinyMCE_PastePlugin._insertWordContent(value);return true;case"mceSelectAll":tinyMCE.execInstanceCommand(editor_id,'selectall');return true;}return false;},_handlePasteEvent:function(e){switch(e.type){case"paste":var html=TinyMCE_PastePlugin._clipboardHTML();var r,inst=tinyMCE.selectedInstance;if(inst&&(r=inst.getRng())&&r.text.length>0)tinyMCE.execCommand('delete');if(html&&html.length>0)tinyMCE.execCommand('mcePasteWord',false,html);tinyMCE.cancelEvent(e);return false;}return true;},_insertText:function(content,bLinebreaks){if(content&&content.length>0){if(bLinebreaks){if(tinyMCE.getParam("paste_create_paragraphs",true)){var rl=tinyMCE.getParam("paste_replace_list",'\u2122,<sup>TM</sup>,\u2026,...,\u201c|\u201d,",\u2019,\',\u2013|\u2014|\u2015|\u2212,-').split(',');for(var i=0;i<rl.length;i+=2)content=content.replace(new RegExp(rl[i],'gi'),rl[i+1]);content=tinyMCE.regexpReplace(content,"\r\n\r\n","</p><p>","gi");content=tinyMCE.regexpReplace(content,"\r\r","</p><p>","gi");content=tinyMCE.regexpReplace(content,"\n\n","</p><p>","gi");if((pos=content.indexOf('</p><p>'))!=-1){tinyMCE.execCommand("Delete");var node=tinyMCE.selectedInstance.getFocusElement();var breakElms=new Array();do{if(node.nodeType==1){if(node.nodeName=="TD"||node.nodeName=="BODY")break;breakElms[breakElms.length]=node;}}while(node=node.parentNode);var before="",after="</p>";before+=content.substring(0,pos);for(var i=0;i<breakElms.length;i++){before+="</"+breakElms[i].nodeName+">";after+="<"+breakElms[(breakElms.length-1)-i].nodeName+">";}before+="<p>";content=before+content.substring(pos+7)+after;}}if(tinyMCE.getParam("paste_create_linebreaks",true)){content=tinyMCE.regexpReplace(content,"\r\n","<br />","gi");content=tinyMCE.regexpReplace(content,"\r","<br />","gi");content=tinyMCE.regexpReplace(content,"\n","<br />","gi");}}tinyMCE.execCommand("mceInsertRawHTML",false,content);}},_insertWordContent:function(content){if(content&&content.length>0){var bull=String.fromCharCode(8226);var middot=String.fromCharCode(183);var cb;if((cb=tinyMCE.getParam("paste_insert_word_content_callback",""))!="")content=eval(cb+"('before', content)");var rl=tinyMCE.getParam("paste_replace_list",'\u2122,<sup>TM</sup>,\u2026,...,\u201c|\u201d,",\u2019,\',\u2013|\u2014|\u2015|\u2212,-').split(',');for(var i=0;i<rl.length;i+=2)content=content.replace(new RegExp(rl[i],'gi'),rl[i+1]);if(tinyMCE.getParam("paste_convert_headers_to_strong",false)){content=content.replace(new RegExp('<p class=MsoHeading.*?>(.*?)<\/p>','gi'),'<p><b>$1</b></p>');}content=content.replace(new RegExp('tab-stops: list [0-9]+.0pt">','gi'),'">'+"--list--");content=content.replace(new RegExp(bull+"(.*?)<BR>","gi"),"<p>"+middot+"$1</p>");content=content.replace(new RegExp('<SPAN style="mso-list: Ignore">','gi'),"<span>"+bull);content=content.replace(/<o:p><\/o:p>/gi,"");content=content.replace(new RegExp('<br style="page-break-before: always;.*>','gi'),'-- page break --');content=content.replace(new RegExp('<(!--)([^>]*)(--)>','g'),"");if(tinyMCE.getParam("paste_remove_spans",true))content=content.replace(/<\/?span[^>]*>/gi,"");if(tinyMCE.getParam("paste_remove_styles",true))content=content.replace(new RegExp('<(\\w[^>]*) style="([^"]*)"([^>]*)','gi'),"<$1$3");content=content.replace(/<\/?font[^>]*>/gi,"");switch(tinyMCE.getParam("paste_strip_class_attributes","all")){case"all":content=content.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi,"<$1$3");break;case"mso":content=content.replace(new RegExp('<(\\w[^>]*) class="?mso([^ |>]*)([^>]*)','gi'),"<$1$3");break;}content=content.replace(new RegExp('href="?'+TinyMCE_PastePlugin._reEscape(""+document.location)+'','gi'),'href="'+tinyMCE.settings['document_base_url']);content=content.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi,"<$1$3");content=content.replace(/<\\?\?xml[^>]*>/gi,"");content=content.replace(/<\/?\w+:[^>]*>/gi,"");content=content.replace(/-- page break --\s*<p>&nbsp;<\/p>/gi,"");content=content.replace(/-- page break --/gi,"");if(!tinyMCE.settings['force_p_newlines']){content=content.replace('','','gi');content=content.replace('</p>','<br /><br />','gi');}if(!tinyMCE.isMSIE&&!tinyMCE.settings['force_p_newlines']){content=content.replace(/<\/?p[^>]*>/gi,"");}content=content.replace(/<\/?div[^>]*>/gi,"");if(tinyMCE.getParam("paste_convert_middot_lists",true)){var div=document.createElement("div");div.innerHTML=content;var className=tinyMCE.getParam("paste_unindented_list_class","unIndentedList");while(TinyMCE_PastePlugin._convertMiddots(div,"--list--"));while(TinyMCE_PastePlugin._convertMiddots(div,middot,className));while(TinyMCE_PastePlugin._convertMiddots(div,bull));content=div.innerHTML;}if(tinyMCE.getParam("paste_convert_headers_to_strong",false)){content=content.replace(/<h[1-6]>&nbsp;<\/h[1-6]>/gi,'<p>&nbsp;&nbsp;</p>');content=content.replace(/<h[1-6]>/gi,'<p><b>');content=content.replace(/<\/h[1-6]>/gi,'</b></p>');content=content.replace(/<b>&nbsp;<\/b>/gi,'<b>&nbsp;&nbsp;</b>');content=content.replace(/^(&nbsp;)*/gi,'');}content=content.replace(/--list--/gi,"");if((cb=tinyMCE.getParam("paste_insert_word_content_callback",""))!="")content=eval(cb+"('after', content)");tinyMCE.execCommand("mceInsertContent",false,content);window.setTimeout('tinyMCE.execCommand("mceCleanup");',1);}},_reEscape:function(s){var l="?.\\*[](){}+^$:";var o="";for(var i=0;i<s.length;i++){var c=s.charAt(i);if(l.indexOf(c)!=-1)o+='\\'+c;else o+=c;}return o;},_convertMiddots:function(div,search,class_name){var mdot=String.fromCharCode(183);var bull=String.fromCharCode(8226);var nodes=div.getElementsByTagName("p");var prevul;for(var i=0;i<nodes.length;i++){var p=nodes[i];if(p.innerHTML.indexOf(search)==0){var ul=document.createElement("ul");if(class_name)ul.className=class_name;var li=document.createElement("li");li.innerHTML=p.innerHTML.replace(new RegExp(''+mdot+'|'+bull+'|--list--|&nbsp;',"gi"),'');ul.appendChild(li);var np=p.nextSibling;while(np){if(np.nodeType==3&&/^\s$/m.test(np.nodeValue)){np=np.nextSibling;continue;}if(search==mdot){if(np.nodeType==1&&/^o(\s+|&nbsp;)/.test(np.innerHTML)){if(!prevul){prevul=ul;ul=document.createElement("ul");prevul.appendChild(ul);}np.innerHTML=np.innerHTML.replace(/^o/,'');}else{if(prevul){ul=prevul;prevul=null;}if(np.nodeType!=1||np.innerHTML.indexOf(search)!=0)break;}}else{if(np.nodeType!=1||np.innerHTML.indexOf(search)!=0)break;}var cp=np.nextSibling;var li=document.createElement("li");li.innerHTML=np.innerHTML.replace(new RegExp(''+mdot+'|'+bull+'|--list--|&nbsp;',"gi"),'');np.parentNode.removeChild(np);ul.appendChild(li);np=cp;}p.parentNode.replaceChild(ul,p);return true;}}return false;},_clipboardHTML:function(){var div=document.getElementById('_TinyMCE_clipboardHTML');if(!div){var div=document.createElement('DIV');div.id='_TinyMCE_clipboardHTML';with(div.style){visibility='hidden';overflow='hidden';position='absolute';width=1;height=1;}document.body.appendChild(div);}div.innerHTML='';var rng=document.body.createTextRange();rng.moveToElementText(div);rng.execCommand('Paste');var html=div.innerHTML;div.innerHTML='';return html;}};tinyMCE.addPlugin("paste",TinyMCE_PastePlugin);
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/plugins/paste/editor_plugin.js
editor_plugin.js
tinyMCE.addToLang('',{ dir : 'rtl', bold_desc : '&#1594;&#1575;&#1605;&#1602;', italic_desc : '&#1605;&#1575;&#1574;&#1604;', underline_desc : '&#1578;&#1587;&#1591;&#1610;&#1585;', striketrough_desc : '&#1610;&#1578;&#1608;&#1587;&#1591;&#1607; &#1582;&#1591;', justifyleft_desc : '&#1605;&#1581;&#1575;&#1584;&#1575;&#1577; &#1573;&#1604;&#1609; &#1575;&#1604;&#1610;&#1587;&#1575;&#1585;', justifycenter_desc : '&#1578;&#1608;&#1587;&#1610;&#1591;', justifyright_desc : '&#1605;&#1581;&#1575;&#1584;&#1575;&#1577; &#1573;&#1604;&#1609; &#1575;&#1604;&#1610;&#1605;&#1610;&#1606;', justifyfull_desc : '&#1590;&#1576;&#1591;', bullist_desc : '&#1578;&#1593;&#1583;&#1575;&#1583; &#1606;&#1602;&#1591;&#1610;', numlist_desc : '&#1578;&#1593;&#1583;&#1575;&#1583; &#1585;&#1602;&#1605;&#1610;', outdent_desc : '&#1573;&#1606;&#1602;&#1575;&#1589; &#1575;&#1604;&#1605;&#1587;&#1575;&#1601;&#1577; &#1575;&#1604;&#1576;&#1575;&#1583;&#1574;&#1577;', indent_desc : '&#1586;&#1610;&#1575;&#1583;&#1577; &#1575;&#1604;&#1605;&#1587;&#1575;&#1601;&#1577; &#1575;&#1604;&#1576;&#1575;&#1583;&#1574;&#1577;', undo_desc : '&#1578;&#1585;&#1575;&#1580;&#1593;', redo_desc : '&#1573;&#1593;&#1575;&#1583;&#1577;', link_desc : '&#1573;&#1583;&#1585;&#1575;&#1580;/&#1578;&#1581;&#1585;&#1610;&#1585; &#1585;&#1575;&#1576;&#1591;', unlink_desc : '&#1573;&#1586;&#1575;&#1604;&#1577; &#1585;&#1575;&#1576;&#1591;', image_desc : '&#1573;&#1583;&#1585;&#1575;&#1580;/&#1578;&#1581;&#1585;&#1610;&#1585; &#1589;&#1608;&#1585;&#1577;', cleanup_desc : 'Cleanup messy code', focus_alert : 'A editor instance must be focused before using this command.', edit_confirm : 'Do you want to use the WYSIWYG mode for this textarea?', insert_link_title : '&#1573;&#1583;&#1585;&#1575;&#1580;/&#1578;&#1581;&#1585;&#1610;&#1585; &#1585;&#1575;&#1576;&#1591;', insert : '&#1573;&#1583;&#1585;&#1575;&#1580;', update : '&#1573;&#1583;&#1585;&#1575;&#1580;', cancel : '&#1571;&#1604;&#1594;&#1610;', insert_link_url : '&#1585;&#1575;&#1576;&#1591; URL', insert_link_target : '&#1575;&#1604;&#1607;&#1583;&#1601;', insert_link_target_same : '&#1606;&#1601;&#1587; &#1575;&#1604;&#1573;&#1591;&#1575;&#1585;', insert_link_target_blank : '&#1573;&#1591;&#1575;&#1585; &#1580;&#1583;&#1610;&#1583; (_blank)', insert_image_title : '&#1573;&#1583;&#1585;&#1575;&#1580;/&#1578;&#1581;&#1585;&#1610;&#1585; &#1589;&#1608;&#1585;&#1577;', insert_image_src : '&#1589;&#1608;&#1585;&#1577; URL', insert_image_alt : '&#1575;&#1604;&#1608;&#1589;&#1601;', help_desc : '&#1575;&#1604;&#1605;&#1587;&#1575;&#1593;&#1583;&#1577;', bold_img : 'bold.gif', italic_img : 'italic.gif', underline_img : "underline.gif", clipboard_msg : 'Copy/Cut/Paste is not available in Mozilla and Firefox.\nDo you want more information about this issue?', popup_blocked : 'Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/langs/ar.js
ar.js
var TinyMCE_SimpleTheme={_buttonMap:'bold,bullist,cleanup,italic,numlist,redo,strikethrough,underline,undo',getEditorTemplate:function(){var html='';html+='<table class="mceEditor" border="0" cellpadding="0" cellspacing="0" width="{$width}" height="{$height}">';html+='<tr><td align="center">';html+='<span id="{$editor_id}">IFRAME</span>';html+='</td></tr>';html+='<tr><td class="mceToolbar" align="center" height="1">';html+=tinyMCE.getButtonHTML('bold','lang_bold_desc','{$themeurl}/images/{$lang_bold_img}','Bold');html+=tinyMCE.getButtonHTML('italic','lang_italic_desc','{$themeurl}/images/{$lang_italic_img}','Italic');html+=tinyMCE.getButtonHTML('underline','lang_underline_desc','{$themeurl}/images/{$lang_underline_img}','Underline');html+=tinyMCE.getButtonHTML('strikethrough','lang_striketrough_desc','{$themeurl}/images/strikethrough.gif','Strikethrough');html+='<img src="{$themeurl}/images/separator.gif" width="2" height="20" class="mceSeparatorLine">';html+=tinyMCE.getButtonHTML('undo','lang_undo_desc','{$themeurl}/images/undo.gif','Undo');html+=tinyMCE.getButtonHTML('redo','lang_redo_desc','{$themeurl}/images/redo.gif','Redo');html+='<img src="{$themeurl}/images/separator.gif" width="2" height="20" class="mceSeparatorLine">';html+=tinyMCE.getButtonHTML('cleanup','lang_cleanup_desc','{$themeurl}/images/cleanup.gif','mceCleanup') html+='<img src="{$themeurl}/images/separator.gif" width="2" height="20" class="mceSeparatorLine">';html+=tinyMCE.getButtonHTML('bullist','lang_bullist_desc','{$themeurl}/images/bullist.gif','InsertUnorderedList') html+=tinyMCE.getButtonHTML('numlist','lang_numlist_desc','{$themeurl}/images/numlist.gif','InsertOrderedList') html+='</td></tr></table>';return{delta_width:0,delta_height:20,html:html};},handleNodeChange:function(editor_id,node){tinyMCE.switchClass(editor_id+'_bold','mceButtonNormal');tinyMCE.switchClass(editor_id+'_italic','mceButtonNormal');tinyMCE.switchClass(editor_id+'_underline','mceButtonNormal');tinyMCE.switchClass(editor_id+'_strikethrough','mceButtonNormal');tinyMCE.switchClass(editor_id+'_bullist','mceButtonNormal');tinyMCE.switchClass(editor_id+'_numlist','mceButtonNormal');do{switch(node.nodeName.toLowerCase()){case"b":case"strong":tinyMCE.switchClass(editor_id+'_bold','mceButtonSelected');break;case"i":case"em":tinyMCE.switchClass(editor_id+'_italic','mceButtonSelected');break;case"u":tinyMCE.switchClass(editor_id+'_underline','mceButtonSelected');break;case"strike":tinyMCE.switchClass(editor_id+'_strikethrough','mceButtonSelected');break;case"ul":tinyMCE.switchClass(editor_id+'_bullist','mceButtonSelected');break;case"ol":tinyMCE.switchClass(editor_id+'_numlist','mceButtonSelected');break;}}while((node=node.parentNode)!=null);}};tinyMCE.addTheme("simple",TinyMCE_SimpleTheme);tinyMCE.addButtonMap(TinyMCE_SimpleTheme._buttonMap);
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/simple/editor_template.js
editor_template.js
tinyMCE.importThemeLanguagePack('advanced');var TinyMCE_AdvancedTheme={_autoImportCSSClasses:true,_resizer:{},_buttons:[['bold','{$lang_bold_img}','lang_bold_desc','Bold'],['italic','{$lang_italic_img}','lang_italic_desc','Italic'],['underline','{$lang_underline_img}','lang_underline_desc','Underline'],['strikethrough','strikethrough.gif','lang_striketrough_desc','Strikethrough'],['justifyleft','justifyleft.gif','lang_justifyleft_desc','JustifyLeft'],['justifycenter','justifycenter.gif','lang_justifycenter_desc','JustifyCenter'],['justifyright','justifyright.gif','lang_justifyright_desc','JustifyRight'],['justifyfull','justifyfull.gif','lang_justifyfull_desc','JustifyFull'],['bullist','bullist.gif','lang_bullist_desc','InsertUnorderedList'],['numlist','numlist.gif','lang_numlist_desc','InsertOrderedList'],['outdent','outdent.gif','lang_outdent_desc','Outdent'],['indent','indent.gif','lang_indent_desc','Indent'],['cut','cut.gif','lang_cut_desc','Cut'],['copy','copy.gif','lang_copy_desc','Copy'],['paste','paste.gif','lang_paste_desc','Paste'],['undo','undo.gif','lang_undo_desc','Undo'],['redo','redo.gif','lang_redo_desc','Redo'],['link','link.gif','lang_link_desc','mceLink',true],['unlink','unlink.gif','lang_unlink_desc','unlink'],['image','image.gif','lang_image_desc','mceImage',true],['cleanup','cleanup.gif','lang_cleanup_desc','mceCleanup'],['help','help.gif','lang_help_desc','mceHelp'],['code','code.gif','lang_theme_code_desc','mceCodeEditor'],['hr','hr.gif','lang_theme_hr_desc','inserthorizontalrule'],['removeformat','removeformat.gif','lang_theme_removeformat_desc','removeformat'],['sub','sub.gif','lang_theme_sub_desc','subscript'],['sup','sup.gif','lang_theme_sup_desc','superscript'],['forecolor','forecolor.gif','lang_theme_forecolor_desc','mceForeColor',true],['backcolor','backcolor.gif','lang_theme_backcolor_desc','mceBackColor',true],['charmap','charmap.gif','lang_theme_charmap_desc','mceCharMap'],['visualaid','visualaid.gif','lang_theme_visualaid_desc','mceToggleVisualAid'],['anchor','anchor.gif','lang_theme_anchor_desc','mceInsertAnchor'],['newdocument','newdocument.gif','lang_newdocument_desc','mceNewDocument']],_buttonMap:'anchor,backcolor,bold,bullist,charmap,cleanup,code,copy,cut,forecolor,help,hr,image,indent,italic,justifycenter,justifyfull,justifyleft,justifyright,link,newdocument,numlist,outdent,paste,redo,removeformat,strikethrough,sub,sup,underline,undo,unlink,visualaid,advhr,ltr,rtl,emotions,flash,fullpage,fullscreen,iespell,insertdate,inserttime,pastetext,pasteword,selectall,preview,print,save,replace,search,table,cell_props,delete_col,delete_row,col_after,col_before,row_after,row_before,merge_cells,row_props,split_cells',getControlHTML:function(button_name){var i,x;for(i=0;i<TinyMCE_AdvancedTheme._buttons.length;i++){var but=TinyMCE_AdvancedTheme._buttons[i];if(but[0]==button_name)return tinyMCE.getButtonHTML(but[0],but[2],'{$themeurl}/images/'+but[1],but[3],(but.length>4?but[4]:false),(but.length>5?but[5]:null));}switch(button_name){case"formatselect":var html='<select id="{$editor_id}_formatSelect" name="{$editor_id}_formatSelect" onfocus="tinyMCE.addSelectAccessibility(event, this, window);" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'FormatBlock\',false,this.options[this.selectedIndex].value);" class="mceSelectList">';var formats=tinyMCE.getParam("theme_advanced_blockformats","p,address,pre,h1,h2,h3,h4,h5,h6",true).split(',');var lookup=[['p','{$lang_theme_paragraph}'],['address','{$lang_theme_address}'],['pre','{$lang_theme_pre}'],['h1','{$lang_theme_h1}'],['h2','{$lang_theme_h2}'],['h3','{$lang_theme_h3}'],['h4','{$lang_theme_h4}'],['h5','{$lang_theme_h5}'],['h6','{$lang_theme_h6}']];html+='<option value="">{$lang_theme_block}</option>';for(var i=0;i<formats.length;i++){for(var x=0;x<lookup.length;x++){if(formats[i]==lookup[x][0])html+='<option value="<'+lookup[x][0]+'>">'+lookup[x][1]+'</option>';}}html+='</select>';return html;case"styleselect":return'<select id="{$editor_id}_styleSelect" onmousedown="tinyMCE.themes.advanced._setupCSSClasses(\'{$editor_id}\');" name="{$editor_id}_styleSelect" onfocus="tinyMCE.addSelectAccessibility(event,this,window);" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceSetCSSClass\',false,this.options[this.selectedIndex].value);" class="mceSelectList">{$style_select_options}</select>';case"fontselect":var fontHTML='<select id="{$editor_id}_fontNameSelect" name="{$editor_id}_fontNameSelect" onfocus="tinyMCE.addSelectAccessibility(event, this, window);" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'FontName\',false,this.options[this.selectedIndex].value);" class="mceSelectList"><option value="">{$lang_theme_fontdefault}</option>';var iFonts='Arial=arial,helvetica,sans-serif;Courier New=courier new,courier,monospace;Georgia=georgia,times new roman,times,serif;Tahoma=tahoma,arial,helvetica,sans-serif;Times New Roman=times new roman,times,serif;Verdana=verdana,arial,helvetica,sans-serif;Impact=impact;WingDings=wingdings';var nFonts='Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sand;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats';var fonts=tinyMCE.getParam("theme_advanced_fonts",nFonts).split(';');for(i=0;i<fonts.length;i++){if(fonts[i]!=''){var parts=fonts[i].split('=');fontHTML+='<option value="'+parts[1]+'">'+parts[0]+'</option>';}}fontHTML+='</select>';return fontHTML;case"fontsizeselect":return'<select id="{$editor_id}_fontSizeSelect" name="{$editor_id}_fontSizeSelect" onfocus="tinyMCE.addSelectAccessibility(event, this, window);" onchange="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'FontSize\',false,this.options[this.selectedIndex].value);" class="mceSelectList">\ <option value="0">{$lang_theme_font_size}</option>\ <option value="1">1 (8 pt)</option>\ <option value="2">2 (10 pt)</option>\ <option value="3">3 (12 pt)</option>\ <option value="4">4 (14 pt)</option>\ <option value="5">5 (18 pt)</option>\ <option value="6">6 (24 pt)</option>\ <option value="7">7 (36 pt)</option>\ </select>';case"|":case"separator":return'<img src="{$themeurl}/images/separator.gif" width="2" height="20" class="mceSeparatorLine" />';case"spacer":return'<img src="{$themeurl}/images/separator.gif" width="2" height="15" border="0" class="mceSeparatorLine" style="vertical-align: middle" />';case"rowseparator":return'<br />';}return"";},execCommand:function(editor_id,element,command,user_interface,value){switch(command){case"mceLink":var inst=tinyMCE.getInstanceById(editor_id);var doc=inst.getDoc();var selectedText="";if(tinyMCE.isMSIE){var rng=doc.selection.createRange();selectedText=rng.text;}else selectedText=inst.getSel().toString();if(!tinyMCE.linkElement){if((tinyMCE.selectedElement.nodeName.toLowerCase()!="img")&&(selectedText.length<=0))return true;}var href="",target="",title="",onclick="",action="insert",style_class="";if(tinyMCE.selectedElement.nodeName.toLowerCase()=="a")tinyMCE.linkElement=tinyMCE.selectedElement;if(tinyMCE.linkElement!=null&&tinyMCE.getAttrib(tinyMCE.linkElement,'href')=="")tinyMCE.linkElement=null;if(tinyMCE.linkElement){href=tinyMCE.getAttrib(tinyMCE.linkElement,'href');target=tinyMCE.getAttrib(tinyMCE.linkElement,'target');title=tinyMCE.getAttrib(tinyMCE.linkElement,'title');onclick=tinyMCE.getAttrib(tinyMCE.linkElement,'onclick');style_class=tinyMCE.getAttrib(tinyMCE.linkElement,'class');if(onclick=="")onclick=tinyMCE.getAttrib(tinyMCE.linkElement,'onclick');onclick=tinyMCE.cleanupEventStr(onclick);href=eval(tinyMCE.settings['urlconverter_callback']+"(href, tinyMCE.linkElement, true);");mceRealHref=tinyMCE.getAttrib(tinyMCE.linkElement,'mce_href');if(mceRealHref!=""){href=mceRealHref;if(tinyMCE.getParam('convert_urls'))href=eval(tinyMCE.settings['urlconverter_callback']+"(href, tinyMCE.linkElement, true);");}action="update";}var template=new Array();template['file']='link.htm';template['width']=310;template['height']=200;template['width']+=tinyMCE.getLang('lang_insert_link_delta_width',0);template['height']+=tinyMCE.getLang('lang_insert_link_delta_height',0);if(inst.settings['insertlink_callback']){var returnVal=eval(inst.settings['insertlink_callback']+"(href, target, title, onclick, action, style_class);");if(returnVal&&returnVal['href'])TinyMCE_AdvancedTheme._insertLink(returnVal['href'],returnVal['target'],returnVal['title'],returnVal['onclick'],returnVal['style_class']);}else{tinyMCE.openWindow(template,{href:href,target:target,title:title,onclick:onclick,action:action,className:style_class,inline:"yes"});}return true;case"mceImage":var src="",alt="",border="",hspace="",vspace="",width="",height="",align="";var title="",onmouseover="",onmouseout="",action="insert";var img=tinyMCE.imgElement;var inst=tinyMCE.getInstanceById(editor_id);if(tinyMCE.selectedElement!=null&&tinyMCE.selectedElement.nodeName.toLowerCase()=="img"){img=tinyMCE.selectedElement;tinyMCE.imgElement=img;}if(img){if(tinyMCE.getAttrib(img,'name').indexOf('mce_')==0)return true;src=tinyMCE.getAttrib(img,'src');alt=tinyMCE.getAttrib(img,'alt');if(alt=="")alt=tinyMCE.getAttrib(img,'title');if(tinyMCE.isGecko){var w=img.style.width;if(w!=null&&w!="")img.setAttribute("width",w);var h=img.style.height;if(h!=null&&h!="")img.setAttribute("height",h);}border=tinyMCE.getAttrib(img,'border');hspace=tinyMCE.getAttrib(img,'hspace');vspace=tinyMCE.getAttrib(img,'vspace');width=tinyMCE.getAttrib(img,'width');height=tinyMCE.getAttrib(img,'height');align=tinyMCE.getAttrib(img,'align');onmouseover=tinyMCE.getAttrib(img,'onmouseover');onmouseout=tinyMCE.getAttrib(img,'onmouseout');title=tinyMCE.getAttrib(img,'title');if(tinyMCE.isMSIE){width=img.attributes['width'].specified?width:"";height=img.attributes['height'].specified?height:"";}src=eval(tinyMCE.settings['urlconverter_callback']+"(src, img, true);");mceRealSrc=tinyMCE.getAttrib(img,'mce_src');if(mceRealSrc!=""){src=mceRealSrc;if(tinyMCE.getParam('convert_urls'))src=eval(tinyMCE.settings['urlconverter_callback']+"(src, img, true);");}action="update";}var template=new Array();template['file']='image.htm?src={$src}';template['width']=355;template['height']=265+(tinyMCE.isMSIE?25:0);template['width']+=tinyMCE.getLang('lang_insert_image_delta_width',0);template['height']+=tinyMCE.getLang('lang_insert_image_delta_height',0);if(inst.settings['insertimage_callback']){var returnVal=eval(inst.settings['insertimage_callback']+"(src, alt, border, hspace, vspace, width, height, align, title, onmouseover, onmouseout, action);");if(returnVal&&returnVal['src'])TinyMCE_AdvancedTheme._insertImage(returnVal['src'],returnVal['alt'],returnVal['border'],returnVal['hspace'],returnVal['vspace'],returnVal['width'],returnVal['height'],returnVal['align'],returnVal['title'],returnVal['onmouseover'],returnVal['onmouseout']);}else tinyMCE.openWindow(template,{src:src,alt:alt,border:border,hspace:hspace,vspace:vspace,width:width,height:height,align:align,title:title,onmouseover:onmouseover,onmouseout:onmouseout,action:action,inline:"yes"});return true;case"mceForeColor":var template=new Array();var elm=tinyMCE.selectedInstance.getFocusElement();var inputColor=tinyMCE.getAttrib(elm,"color");if(inputColor=='')inputColor=elm.style.color;if(!inputColor)inputColor="#000000";template['file']='color_picker.htm';template['width']=220;template['height']=190;tinyMCE.openWindow(template,{editor_id:editor_id,inline:"yes",command:"forecolor",input_color:inputColor});return true;case"mceBackColor":var template=new Array();var elm=tinyMCE.selectedInstance.getFocusElement();var inputColor=elm.style.backgroundColor;if(!inputColor)inputColor="#000000";template['file']='color_picker.htm';template['width']=220;template['height']=190;template['width']+=tinyMCE.getLang('lang_theme_advanced_backcolor_delta_width',0);template['height']+=tinyMCE.getLang('lang_theme_advanced_backcolor_delta_height',0);tinyMCE.openWindow(template,{editor_id:editor_id,inline:"yes",command:"HiliteColor",input_color:inputColor});return true;case"mceColorPicker":if(user_interface){var template=new Array();var inputColor=value['document'].getElementById(value['element_id']).value;template['file']='color_picker.htm';template['width']=220;template['height']=190;template['close_previous']="no";template['width']+=tinyMCE.getLang('lang_theme_advanced_colorpicker_delta_width',0);template['height']+=tinyMCE.getLang('lang_theme_advanced_colorpicker_delta_height',0);if(typeof(value['store_selection'])=="undefined")value['store_selection']=true;tinyMCE.lastColorPickerValue=value;tinyMCE.openWindow(template,{editor_id:editor_id,mce_store_selection:value['store_selection'],inline:"yes",command:"mceColorPicker",input_color:inputColor});}else{var savedVal=tinyMCE.lastColorPickerValue;var elm=savedVal['document'].getElementById(savedVal['element_id']);elm.value=value;if(elm.onchange!=null&&elm.onchange!='')eval('elm.onchange();');}return true;case"mceCodeEditor":var template=new Array();template['file']='source_editor.htm';template['width']=parseInt(tinyMCE.getParam("theme_advanced_source_editor_width",720));template['height']=parseInt(tinyMCE.getParam("theme_advanced_source_editor_height",580));tinyMCE.openWindow(template,{editor_id:editor_id,resizable:"yes",scrollbars:"no",inline:"yes"});return true;case"mceCharMap":var template=new Array();template['file']='charmap.htm';template['width']=550+(tinyMCE.isOpera?40:0);template['height']=250;template['width']+=tinyMCE.getLang('lang_theme_advanced_charmap_delta_width',0);template['height']+=tinyMCE.getLang('lang_theme_advanced_charmap_delta_height',0);tinyMCE.openWindow(template,{editor_id:editor_id,inline:"yes"});return true;case"mceInsertAnchor":var template=new Array();template['file']='anchor.htm';template['width']=320;template['height']=90+(tinyMCE.isNS7?30:0);template['width']+=tinyMCE.getLang('lang_theme_advanced_anchor_delta_width',0);template['height']+=tinyMCE.getLang('lang_theme_advanced_anchor_delta_height',0);tinyMCE.openWindow(template,{editor_id:editor_id,inline:"yes"});return true;case"mceNewDocument":if(confirm(tinyMCE.getLang('lang_newdocument')))tinyMCE.execInstanceCommand(editor_id,'mceSetContent',false,' ');return true;}return false;},getEditorTemplate:function(settings,editorId){function removeFromArray(in_array,remove_array){var outArray=new Array();for(var i=0;i<in_array.length;i++){skip=false;for(var j=0;j<remove_array.length;j++){if(in_array[i]==remove_array[j]){skip=true;}}if(!skip){outArray[outArray.length]=in_array[i];}}return outArray;}function addToArray(in_array,add_array){for(var i=0;i<add_array.length;i++){in_array[in_array.length]=add_array[i];}return in_array;}var template=new Array();var deltaHeight=0;var resizing=tinyMCE.getParam("theme_advanced_resizing",false);var path=tinyMCE.getParam("theme_advanced_path",true);var statusbarHTML='<div id="{$editor_id}_path" class="mceStatusbarPathText" style="display: '+(path?"block":"none")+'">&nbsp;</div><div id="{$editor_id}_resize" class="mceStatusbarResize" style="display: '+(resizing?"block":"none")+'" onmousedown="tinyMCE.themes.advanced._setResizing(event,\'{$editor_id}\',true);"></div><br style="clear: both" />';var layoutManager=tinyMCE.getParam("theme_advanced_layout_manager","SimpleLayout");var styleSelectHTML='<option value="">{$lang_theme_style_select}</option>';if(settings['theme_advanced_styles']){var stylesAr=settings['theme_advanced_styles'].split(';');for(var i=0;i<stylesAr.length;i++){var key,value;key=stylesAr[i].split('=')[0];value=stylesAr[i].split('=')[1];styleSelectHTML+='<option value="'+value+'">'+key+'</option>';}TinyMCE_AdvancedTheme._autoImportCSSClasses=false;}switch(layoutManager){case"SimpleLayout":var toolbarHTML="";var toolbarLocation=tinyMCE.getParam("theme_advanced_toolbar_location","bottom");var toolbarAlign=tinyMCE.getParam("theme_advanced_toolbar_align","center");var pathLocation=tinyMCE.getParam("theme_advanced_path_location","none");var statusbarLocation=tinyMCE.getParam("theme_advanced_statusbar_location",pathLocation);var defVals={theme_advanced_buttons1:"bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,styleselect,formatselect",theme_advanced_buttons2:"bullist,numlist,separator,outdent,indent,separator,undo,redo,separator,link,unlink,anchor,image,cleanup,help,code",theme_advanced_buttons3:"hr,removeformat,visualaid,separator,sub,sup,separator,charmap"};toolbarHTML+='<a href="#" accesskey="q" title="'+tinyMCE.getLang("lang_toolbar_focus")+'"';if(!tinyMCE.getParam("accessibility_focus"))toolbarHTML+=' onfocus="tinyMCE.getInstanceById(\''+editorId+'\').getWin().focus();"';toolbarHTML+='></a>';for(var i=1;i<100;i++){var def=defVals["theme_advanced_buttons"+i];var buttons=tinyMCE.getParam("theme_advanced_buttons"+i,def==null?'':def,true,',');if(buttons.length==0)break;buttons=removeFromArray(buttons,tinyMCE.getParam("theme_advanced_disable","",true,','));buttons=addToArray(buttons,tinyMCE.getParam("theme_advanced_buttons"+i+"_add","",true,','));buttons=addToArray(tinyMCE.getParam("theme_advanced_buttons"+i+"_add_before","",true,','),buttons);for(var b=0;b<buttons.length;b++)toolbarHTML+=tinyMCE.getControlHTML(buttons[b]);if(buttons.length>0){toolbarHTML+="<br />";deltaHeight-=23;}}toolbarHTML+='<a href="#" accesskey="z" onfocus="tinyMCE.getInstanceById(\''+editorId+'\').getWin().focus();"></a>';template['html']='<table class="mceEditor" border="0" cellpadding="0" cellspacing="0" width="{$width}" height="{$height}" style="width:{$width}px;height:{$height}px"><tbody>';if(toolbarLocation=="top"){template['html']+='<tr><td class="mceToolbarTop" align="'+toolbarAlign+'" height="1" nowrap="nowrap">'+toolbarHTML+'</td></tr>';}if(statusbarLocation=="top"){template['html']+='<tr><td class="mceStatusbarTop" height="1">'+statusbarHTML+'</td></tr>';deltaHeight-=23;}template['html']+='<tr><td align="center"><span id="{$editor_id}"></span></td></tr>';if(toolbarLocation=="bottom"){template['html']+='<tr><td class="mceToolbarBottom" align="'+toolbarAlign+'" height="1">'+toolbarHTML+'</td></tr>';}if(toolbarLocation=="external"){var bod=document.body;var elm=document.createElement("div");toolbarHTML=tinyMCE.replaceVar(toolbarHTML,'style_select_options',styleSelectHTML);toolbarHTML=tinyMCE.applyTemplate(toolbarHTML,{editor_id:editorId});elm.className="mceToolbarExternal";elm.id=editorId+"_toolbar";elm.innerHTML='<table width="100%" border="0" align="center"><tr><td align="center">'+toolbarHTML+'</td></tr></table>';bod.appendChild(elm);deltaHeight=0;tinyMCE.getInstanceById(editorId).toolbarElement=elm;}else{tinyMCE.getInstanceById(editorId).toolbarElement=null;}if(statusbarLocation=="bottom"){template['html']+='<tr><td class="mceStatusbarBottom" height="1">'+statusbarHTML+'</td></tr>';deltaHeight-=23;}template['html']+='</tbody></table>';break;case"RowLayout":template['html']='<table class="mceEditor" border="0" cellpadding="0" cellspacing="0" width="{$width}" height="{$height}" style="width:{$width}px;height:{$height}px"><tbody>';var containers=tinyMCE.getParam("theme_advanced_containers","",true,",");var defaultContainerCSS=tinyMCE.getParam("theme_advanced_containers_default_class","container");var defaultContainerAlign=tinyMCE.getParam("theme_advanced_containers_default_align","center");for(var i=0;i<containers.length;i++){if(containers[i]=="mceEditor"){template['html']+='<tr><td align="center" class="mceEditor_border">\ <span id="{$editor_id}"></span>\ </td></tr>';}else if(containers[i]=="mceElementpath"||containers[i]=="mceStatusbar"){var pathClass="mceStatusbar";if(i==containers.length-1){pathClass="mceStatusbarBottom";}else if(i==0){pathClass="mceStatusbar";}else{deltaHeight-=2;}template['html']+='<tr><td class="'+pathClass+'" height="1">'+statusbarHTML+'</td></tr>';deltaHeight-=22;}else{var curContainer=tinyMCE.getParam("theme_advanced_container_"+containers[i],"",true,',');var curContainerHTML="";var curAlign=tinyMCE.getParam("theme_advanced_container_"+containers[i]+"_align",defaultContainerAlign);var curCSS=tinyMCE.getParam("theme_advanced_container_"+containers[i]+"_class",defaultContainerCSS);for(var j=0;j<curContainer.length;j++){curContainerHTML+=tinyMCE.getControlHTML(curContainer[j]);}if(curContainer.length>0){curContainerHTML+="<br />";deltaHeight-=23;}template['html']+='<tr><td class="'+curCSS+'" align="'+curAlign+'" height="1">'+curContainerHTML+'</td></tr>';}}template['html']+='</tbody></table>';break;case"CustomLayout":var customLayout=tinyMCE.getParam("theme_advanced_custom_layout","");if(customLayout!=""&&eval("typeof("+customLayout+")")!="undefined"){template=eval(customLayout+"(template);");}break;}if(resizing)template['html']+='<span id="{$editor_id}_resize_box" class="mceResizeBox"></span>';template['html']=tinyMCE.replaceVar(template['html'],'style_select_options',styleSelectHTML);template['delta_width']=0;template['delta_height']=deltaHeight;return template;},initInstance:function(inst){if(tinyMCE.getParam("theme_advanced_resizing",false)){if(tinyMCE.getParam("theme_advanced_resizing_use_cookie",true)){var w=TinyMCE_AdvancedTheme._getCookie("TinyMCE_"+inst.editorId+"_width");var h=TinyMCE_AdvancedTheme._getCookie("TinyMCE_"+inst.editorId+"_height");TinyMCE_AdvancedTheme._resizeTo(inst,w,h,tinyMCE.getParam("theme_advanced_resize_horizontal",true));}}inst.addShortcut('ctrl','k','lang_link_desc','mceLink');},handleNodeChange:function(editor_id,node,undo_index,undo_levels,visual_aid,any_selection,setup_content){function selectByValue(select_elm,value,first_index){first_index=typeof(first_index)=="undefined"?false:true;if(select_elm){for(var i=0;i<select_elm.options.length;i++){var ov=""+select_elm.options[i].value;if(first_index&&ov.toLowerCase().indexOf(value.toLowerCase())==0){select_elm.selectedIndex=i;return true;}if(ov==value){select_elm.selectedIndex=i;return true;}}}return false;};function getAttrib(elm,name){return elm.getAttribute(name)?elm.getAttribute(name):"";};if(node==null)return;var pathElm=document.getElementById(editor_id+"_path");var inst=tinyMCE.getInstanceById(editor_id);var doc=inst.getDoc();if(pathElm){var parentNode=node;var path=new Array();while(parentNode!=null){if(parentNode.nodeName.toUpperCase()=="BODY"){break;}if(parentNode.nodeType==1&&tinyMCE.getAttrib(parentNode,"class").indexOf('mceItemHidden')==-1){path[path.length]=parentNode;}parentNode=parentNode.parentNode;}var html="";for(var i=path.length-1;i>=0;i--){var nodeName=path[i].nodeName.toLowerCase();var nodeData="";if(nodeName=="b"){nodeName="strong";}if(nodeName=="i"){nodeName="em";}if(nodeName=="span"){var cn=tinyMCE.getAttrib(path[i],"class");if(cn!=""&&cn.indexOf('mceItem')==-1)nodeData+="class: "+cn+" ";var st=tinyMCE.getAttrib(path[i],"style");if(st!=""){st=tinyMCE.serializeStyle(tinyMCE.parseStyle(st));nodeData+="style: "+st+" ";}}if(nodeName=="font"){if(tinyMCE.getParam("convert_fonts_to_spans"))nodeName="span";var face=tinyMCE.getAttrib(path[i],"face");if(face!="")nodeData+="font: "+face+" ";var size=tinyMCE.getAttrib(path[i],"size");if(size!="")nodeData+="size: "+size+" ";var color=tinyMCE.getAttrib(path[i],"color");if(color!="")nodeData+="color: "+color+" ";}if(getAttrib(path[i],'id')!=""){nodeData+="id: "+path[i].getAttribute('id')+" ";}var className=tinyMCE.getVisualAidClass(tinyMCE.getAttrib(path[i],"class"),false);if(className!=""&&className.indexOf('mceItem')==-1)nodeData+="class: "+className+" ";if(getAttrib(path[i],'src')!=""){var src=tinyMCE.getAttrib(path[i],"mce_src");if(src=="")src=tinyMCE.getAttrib(path[i],"src");nodeData+="src: "+src+" ";}if(getAttrib(path[i],'href')!=""){var href=tinyMCE.getAttrib(path[i],"mce_href");if(href=="")href=tinyMCE.getAttrib(path[i],"href");nodeData+="href: "+href+" ";}if(nodeName=="img"&&tinyMCE.getAttrib(path[i],"class").indexOf('mceItemFlash')!=-1){nodeName="flash";nodeData="src: "+path[i].getAttribute('title');}if(nodeName=="a"&&(anchor=tinyMCE.getAttrib(path[i],"name"))!=""){nodeName="a";nodeName+="#"+anchor;nodeData="";}if(getAttrib(path[i],'name').indexOf("mce_")!=0){var className=tinyMCE.getVisualAidClass(tinyMCE.getAttrib(path[i],"class"),false);if(className!=""&&className.indexOf('mceItem')==-1){nodeName+="."+className;}}var cmd='tinyMCE.execInstanceCommand(\''+editor_id+'\',\'mceSelectNodeDepth\',false,\''+i+'\');';html+='<a title="'+nodeData+'" href="javascript:'+cmd+'" onclick="'+cmd+'return false;" onmousedown="return false;" target="_self" class="mcePathItem">'+nodeName+'</a>';if(i>0){html+=" &raquo; ";}}pathElm.innerHTML='<a href="#" accesskey="x"></a>'+tinyMCE.getLang('lang_theme_path')+": "+html+'&nbsp;';}tinyMCE.switchClass(editor_id+'_justifyleft','mceButtonNormal');tinyMCE.switchClass(editor_id+'_justifyright','mceButtonNormal');tinyMCE.switchClass(editor_id+'_justifycenter','mceButtonNormal');tinyMCE.switchClass(editor_id+'_justifyfull','mceButtonNormal');tinyMCE.switchClass(editor_id+'_bold','mceButtonNormal');tinyMCE.switchClass(editor_id+'_italic','mceButtonNormal');tinyMCE.switchClass(editor_id+'_underline','mceButtonNormal');tinyMCE.switchClass(editor_id+'_strikethrough','mceButtonNormal');tinyMCE.switchClass(editor_id+'_bullist','mceButtonNormal');tinyMCE.switchClass(editor_id+'_numlist','mceButtonNormal');tinyMCE.switchClass(editor_id+'_sub','mceButtonNormal');tinyMCE.switchClass(editor_id+'_sup','mceButtonNormal');tinyMCE.switchClass(editor_id+'_anchor','mceButtonNormal');tinyMCE.switchClass(editor_id+'_link','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_unlink','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_outdent','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_image','mceButtonNormal');tinyMCE.switchClass(editor_id+'_hr','mceButtonNormal');if(node.nodeName=="A"&&tinyMCE.getAttrib(node,"class").indexOf('mceItemAnchor')!=-1)tinyMCE.switchClass(editor_id+'_anchor','mceButtonSelected');var anchorLink=tinyMCE.getParentElement(node,"a","href");if(anchorLink||any_selection){tinyMCE.switchClass(editor_id+'_link',anchorLink?'mceButtonSelected':'mceButtonNormal');tinyMCE.switchClass(editor_id+'_unlink',anchorLink?'mceButtonSelected':'mceButtonNormal');}tinyMCE.switchClass(editor_id+'_visualaid',visual_aid?'mceButtonSelected':'mceButtonNormal');if(undo_levels!=-1){tinyMCE.switchClass(editor_id+'_undo','mceButtonDisabled');tinyMCE.switchClass(editor_id+'_redo','mceButtonDisabled');}if(tinyMCE.getParentElement(node,"li,blockquote"))tinyMCE.switchClass(editor_id+'_outdent','mceButtonNormal');if(undo_index!=-1&&(undo_index<undo_levels-1&&undo_levels>0))tinyMCE.switchClass(editor_id+'_redo','mceButtonNormal');if(undo_index!=-1&&(undo_index>0&&undo_levels>0))tinyMCE.switchClass(editor_id+'_undo','mceButtonNormal');var selectElm=document.getElementById(editor_id+"_styleSelect");if(selectElm){TinyMCE_AdvancedTheme._setupCSSClasses(editor_id);classNode=node;breakOut=false;var index=0;do{if(classNode&&classNode.className){for(var i=0;i<selectElm.options.length;i++){if(selectElm.options[i].value==classNode.className){index=i;breakOut=true;break;}}}}while(!breakOut&&classNode!=null&&(classNode=classNode.parentNode)!=null);selectElm.selectedIndex=index;}var selectElm=document.getElementById(editor_id+"_formatSelect");if(selectElm){var elm=tinyMCE.getParentElement(node,"p,div,h1,h2,h3,h4,h5,h6,pre,address");if(elm)selectByValue(selectElm,"<"+elm.nodeName.toLowerCase()+">");else selectByValue(selectElm,"");}var selectElm=document.getElementById(editor_id+"_fontNameSelect");if(selectElm){if(!tinyMCE.isSafari&&!(tinyMCE.isMSIE&&!tinyMCE.isOpera)){var face=inst.queryCommandValue('FontName');face=face==null||face==""?"":face;selectByValue(selectElm,face,face!="");}else{var elm=tinyMCE.getParentElement(node,"font","face");if(elm){var family=tinyMCE.getAttrib(elm,"face");if(family=='')family=''+elm.style.fontFamily;if(!selectByValue(selectElm,family,family!=""))selectByValue(selectElm,"");}else selectByValue(selectElm,"");}}var selectElm=document.getElementById(editor_id+"_fontSizeSelect");if(selectElm){if(!tinyMCE.isSafari&&!tinyMCE.isOpera){var size=inst.queryCommandValue('FontSize');selectByValue(selectElm,size==null||size==""?"0":size);}else{var elm=tinyMCE.getParentElement(node,"font","size");if(elm){var size=tinyMCE.getAttrib(elm,"size");if(size==''){var sizes=new Array('','8px','10px','12px','14px','18px','24px','36px');size=''+elm.style.fontSize;for(var i=0;i<sizes.length;i++){if((''+sizes[i])==size){size=i;break;}}}if(!selectByValue(selectElm,size))selectByValue(selectElm,"");}else selectByValue(selectElm,"0");}}alignNode=node;breakOut=false;do{if(!alignNode.getAttribute||!alignNode.getAttribute('align'))continue;switch(alignNode.getAttribute('align').toLowerCase()){case"left":tinyMCE.switchClass(editor_id+'_justifyleft','mceButtonSelected');breakOut=true;break;case"right":tinyMCE.switchClass(editor_id+'_justifyright','mceButtonSelected');breakOut=true;break;case"middle":case"center":tinyMCE.switchClass(editor_id+'_justifycenter','mceButtonSelected');breakOut=true;break;case"justify":tinyMCE.switchClass(editor_id+'_justifyfull','mceButtonSelected');breakOut=true;break;}}while(!breakOut&&(alignNode=alignNode.parentNode)!=null);var div=tinyMCE.getParentElement(node,"div");if(div&&div.style.textAlign=="center")tinyMCE.switchClass(editor_id+'_justifycenter','mceButtonSelected');if(!setup_content){var ar=new Array("Bold","_bold","Italic","_italic","Strikethrough","_strikethrough","superscript","_sup","subscript","_sub");for(var i=0;i<ar.length;i+=2){if(inst.queryCommandState(ar[i]))tinyMCE.switchClass(editor_id+ar[i+1],'mceButtonSelected');}if(inst.queryCommandState("Underline")&&(node.parentNode==null||node.parentNode.nodeName!="A"))tinyMCE.switchClass(editor_id+'_underline','mceButtonSelected');}do{switch(node.nodeName){case"UL":tinyMCE.switchClass(editor_id+'_bullist','mceButtonSelected');break;case"OL":tinyMCE.switchClass(editor_id+'_numlist','mceButtonSelected');break;case"HR":tinyMCE.switchClass(editor_id+'_hr','mceButtonSelected');break;case"IMG":if(getAttrib(node,'name').indexOf('mce_')!=0){tinyMCE.switchClass(editor_id+'_image','mceButtonSelected');}break;}}while((node=node.parentNode)!=null);},_setupCSSClasses:function(editor_id){var i,selectElm;if(!TinyMCE_AdvancedTheme._autoImportCSSClasses)return;selectElm=document.getElementById(editor_id+'_styleSelect');if(selectElm&&selectElm.getAttribute('cssImported')!='true'){var csses=tinyMCE.getCSSClasses(editor_id);if(csses&&selectElm){for(i=0;i<csses.length;i++)selectElm.options[selectElm.options.length]=new Option(csses[i],csses[i]);}if(csses!=null&&csses.length>0)selectElm.setAttribute('cssImported','true');}},_setCookie:function(name,value,expires,path,domain,secure){var curCookie=name+"="+escape(value)+((expires)?"; expires="+expires.toGMTString():"")+((path)?"; path="+escape(path):"")+((domain)?"; domain="+domain:"")+((secure)?"; secure":"");document.cookie=curCookie;},_getCookie:function(name){var dc=document.cookie;var prefix=name+"=";var begin=dc.indexOf("; "+prefix);if(begin==-1){begin=dc.indexOf(prefix);if(begin!=0)return null;}else begin+=2;var end=document.cookie.indexOf(";",begin);if(end==-1)end=dc.length;return unescape(dc.substring(begin+prefix.length,end));},_resizeTo:function(inst,w,h,set_w){var editorContainer=document.getElementById(inst.editorId+'_parent');var tableElm=editorContainer.firstChild;var iframe=inst.iframeElement;if(w==null||w=="null"){set_w=false;w=0;}if(h==null||h=="null")return;w=parseInt(w);h=parseInt(h);if(tinyMCE.isGecko){w+=2;h+=2;}var dx=w-tableElm.clientWidth;var dy=h-tableElm.clientHeight;w=w<1?30:w;h=h<1?30:h;if(set_w)tableElm.style.width=w+"px";tableElm.style.height=h+"px";iw=iframe.clientWidth+dx;ih=iframe.clientHeight+dy;iw=iw<1?30:iw;ih=ih<1?30:ih;if(tinyMCE.isGecko){iw-=2;ih-=2;}if(set_w)iframe.style.width=iw+"px";iframe.style.height=ih+"px";if(set_w){var tableBodyElm=tableElm.firstChild;var minIframeWidth=tableBodyElm.scrollWidth;if(inst.iframeElement.clientWidth<minIframeWidth){dx=minIframeWidth-inst.iframeElement.clientWidth;inst.iframeElement.style.width=(iw+dx)+"px";}}},_resizeEventHandler:function(e){var resizer=TinyMCE_AdvancedTheme._resizer;if(!resizer.resizing)return;e=typeof(e)=="undefined"?window.event:e;var dx=e.screenX-resizer.downX;var dy=e.screenY-resizer.downY;var resizeBox=resizer.resizeBox;var editorId=resizer.editorId;switch(e.type){case"mousemove":var w,h;w=resizer.width+dx;h=resizer.height+dy;w=w<1?1:w;h=h<1?1:h;if(resizer.horizontal)resizeBox.style.width=w+"px";resizeBox.style.height=h+"px";break;case"mouseup":TinyMCE_AdvancedTheme._setResizing(e,editorId,false);TinyMCE_AdvancedTheme._resizeTo(tinyMCE.getInstanceById(editorId),resizer.width+dx,resizer.height+dy,resizer.horizontal);if(tinyMCE.getParam("theme_advanced_resizing_use_cookie",true)){var expires=new Date();expires.setTime(expires.getTime()+3600000*24*30);TinyMCE_AdvancedTheme._setCookie("TinyMCE_"+editorId+"_width",""+(resizer.horizontal?resizer.width+dx:""),expires);TinyMCE_AdvancedTheme._setCookie("TinyMCE_"+editorId+"_height",""+(resizer.height+dy),expires);}break;}},_setResizing:function(e,editor_id,state){e=typeof(e)=="undefined"?window.event:e;var resizer=TinyMCE_AdvancedTheme._resizer;var editorContainer=document.getElementById(editor_id+'_parent');var editorArea=document.getElementById(editor_id+'_parent').firstChild;var resizeBox=document.getElementById(editor_id+'_resize_box');var inst=tinyMCE.getInstanceById(editor_id);if(state){var width=editorArea.clientWidth;var height=editorArea.clientHeight;resizeBox.style.width=width+"px";resizeBox.style.height=height+"px";resizer.iframeWidth=inst.iframeElement.clientWidth;resizer.iframeHeight=inst.iframeElement.clientHeight;editorArea.style.display="none";resizeBox.style.display="block";if(!resizer.eventHandlers){if(tinyMCE.isMSIE)tinyMCE.addEvent(document,"mousemove",TinyMCE_AdvancedTheme._resizeEventHandler);else tinyMCE.addEvent(window,"mousemove",TinyMCE_AdvancedTheme._resizeEventHandler);tinyMCE.addEvent(document,"mouseup",TinyMCE_AdvancedTheme._resizeEventHandler);resizer.eventHandlers=true;}resizer.resizing=true;resizer.downX=e.screenX;resizer.downY=e.screenY;resizer.width=parseInt(resizeBox.style.width);resizer.height=parseInt(resizeBox.style.height);resizer.editorId=editor_id;resizer.resizeBox=resizeBox;resizer.horizontal=tinyMCE.getParam("theme_advanced_resize_horizontal",true);}else{resizer.resizing=false;resizeBox.style.display="none";editorArea.style.display=tinyMCE.isMSIE&&!tinyMCE.isOpera?"block":"table";tinyMCE.execCommand('mceResetDesignMode');}},_insertImage:function(src,alt,border,hspace,vspace,width,height,align,title,onmouseover,onmouseout){tinyMCE.execCommand('mceBeginUndoLevel');if(src=="")return;if(!tinyMCE.imgElement&&tinyMCE.isSafari){var html="";html+='<img src="'+src+'" alt="'+alt+'"';html+=' border="'+border+'" hspace="'+hspace+'"';html+=' vspace="'+vspace+'" width="'+width+'"';html+=' height="'+height+'" align="'+align+'" title="'+title+'" onmouseover="'+onmouseover+'" onmouseout="'+onmouseout+'" />';tinyMCE.execCommand("mceInsertContent",false,html);}else{if(!tinyMCE.imgElement&&tinyMCE.selectedInstance){if(tinyMCE.isSafari)tinyMCE.execCommand("mceInsertContent",false,'<img src="'+tinyMCE.uniqueURL+'" />');else tinyMCE.selectedInstance.contentDocument.execCommand("insertimage",false,tinyMCE.uniqueURL);tinyMCE.imgElement=tinyMCE.getElementByAttributeValue(tinyMCE.selectedInstance.contentDocument.body,"img","src",tinyMCE.uniqueURL);}}if(tinyMCE.imgElement){var needsRepaint=false;var msrc=src;src=eval(tinyMCE.settings['urlconverter_callback']+"(src, tinyMCE.imgElement);");if(tinyMCE.getParam('convert_urls'))msrc=src;if(onmouseover&&onmouseover!="")onmouseover="this.src='"+eval(tinyMCE.settings['urlconverter_callback']+"(onmouseover, tinyMCE.imgElement);")+"';";if(onmouseout&&onmouseout!="")onmouseout="this.src='"+eval(tinyMCE.settings['urlconverter_callback']+"(onmouseout, tinyMCE.imgElement);")+"';";if(typeof(title)=="undefined")title=alt;if(width!=tinyMCE.imgElement.getAttribute("width")||height!=tinyMCE.imgElement.getAttribute("height")||align!=tinyMCE.imgElement.getAttribute("align"))needsRepaint=true;tinyMCE.setAttrib(tinyMCE.imgElement,'src',src);tinyMCE.setAttrib(tinyMCE.imgElement,'mce_src',msrc);tinyMCE.setAttrib(tinyMCE.imgElement,'alt',alt);tinyMCE.setAttrib(tinyMCE.imgElement,'title',title);tinyMCE.setAttrib(tinyMCE.imgElement,'align',align);tinyMCE.setAttrib(tinyMCE.imgElement,'border',border,true);tinyMCE.setAttrib(tinyMCE.imgElement,'hspace',hspace,true);tinyMCE.setAttrib(tinyMCE.imgElement,'vspace',vspace,true);tinyMCE.setAttrib(tinyMCE.imgElement,'width',width,true);tinyMCE.setAttrib(tinyMCE.imgElement,'height',height,true);tinyMCE.setAttrib(tinyMCE.imgElement,'onmouseover',onmouseover);tinyMCE.setAttrib(tinyMCE.imgElement,'onmouseout',onmouseout);if(width&&width!="")tinyMCE.imgElement.style.pixelWidth=width;if(height&&height!="")tinyMCE.imgElement.style.pixelHeight=height;if(needsRepaint)tinyMCE.selectedInstance.repaint();}tinyMCE.execCommand('mceEndUndoLevel');},_insertLink:function(href,target,title,onclick,style_class){tinyMCE.execCommand('mceBeginUndoLevel');if(tinyMCE.selectedInstance&&tinyMCE.selectedElement&&tinyMCE.selectedElement.nodeName.toLowerCase()=="img"){var doc=tinyMCE.selectedInstance.getDoc();var linkElement=tinyMCE.getParentElement(tinyMCE.selectedElement,"a");var newLink=false;if(!linkElement){linkElement=doc.createElement("a");newLink=true;}var mhref=href;var thref=eval(tinyMCE.settings['urlconverter_callback']+"(href, linkElement);");mhref=tinyMCE.getParam('convert_urls')?href:mhref;tinyMCE.setAttrib(linkElement,'href',thref);tinyMCE.setAttrib(linkElement,'mce_href',mhref);tinyMCE.setAttrib(linkElement,'target',target);tinyMCE.setAttrib(linkElement,'title',title);tinyMCE.setAttrib(linkElement,'onclick',onclick);tinyMCE.setAttrib(linkElement,'class',style_class);if(newLink){linkElement.appendChild(tinyMCE.selectedElement.cloneNode(true));tinyMCE.selectedElement.parentNode.replaceChild(linkElement,tinyMCE.selectedElement);}return;}if(!tinyMCE.linkElement&&tinyMCE.selectedInstance){if(tinyMCE.isSafari){tinyMCE.execCommand("mceInsertContent",false,'<a href="'+tinyMCE.uniqueURL+'">'+tinyMCE.selectedInstance.selection.getSelectedHTML()+'</a>');}else tinyMCE.selectedInstance.contentDocument.execCommand("createlink",false,tinyMCE.uniqueURL);tinyMCE.linkElement=tinyMCE.getElementByAttributeValue(tinyMCE.selectedInstance.contentDocument.body,"a","href",tinyMCE.uniqueURL);var elementArray=tinyMCE.getElementsByAttributeValue(tinyMCE.selectedInstance.contentDocument.body,"a","href",tinyMCE.uniqueURL);for(var i=0;i<elementArray.length;i++){var mhref=href;var thref=eval(tinyMCE.settings['urlconverter_callback']+"(href, elementArray[i]);");mhref=tinyMCE.getParam('convert_urls')?href:mhref;tinyMCE.setAttrib(elementArray[i],'href',thref);tinyMCE.setAttrib(elementArray[i],'mce_href',mhref);tinyMCE.setAttrib(elementArray[i],'target',target);tinyMCE.setAttrib(elementArray[i],'title',title);tinyMCE.setAttrib(elementArray[i],'onclick',onclick);tinyMCE.setAttrib(elementArray[i],'class',style_class);}tinyMCE.linkElement=elementArray[0];}if(tinyMCE.linkElement){var mhref=href;href=eval(tinyMCE.settings['urlconverter_callback']+"(href, tinyMCE.linkElement);");mhref=tinyMCE.getParam('convert_urls')?href:mhref;tinyMCE.setAttrib(tinyMCE.linkElement,'href',href);tinyMCE.setAttrib(tinyMCE.linkElement,'mce_href',mhref);tinyMCE.setAttrib(tinyMCE.linkElement,'target',target);tinyMCE.setAttrib(tinyMCE.linkElement,'title',title);tinyMCE.setAttrib(tinyMCE.linkElement,'onclick',onclick);tinyMCE.setAttrib(tinyMCE.linkElement,'class',style_class);}tinyMCE.execCommand('mceEndUndoLevel');}};tinyMCE.addTheme("advanced",TinyMCE_AdvancedTheme);tinyMCE.addButtonMap(TinyMCE_AdvancedTheme._buttonMap);
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/editor_template.js
editor_template.js
tinyMCE.addToLang('',{ theme_style_select : '-- Tyylit --', theme_code_desc : 'Muokkaa HTML-l&auml;hdekoodia', theme_code_title : 'HTML-L&auml;hdekoodin muokkaus', theme_code_wordwrap : 'Word wrap', theme_sub_desc : 'Alaindeksi', theme_sup_desc : 'Yl&auml;indeksi', theme_hr_desc : 'Lis&auml;&auml; vaakaviiva', theme_removeformat_desc : 'Poista muotoilu', theme_custom1_desc : 'Kirjoita oma selityksesi t&auml;h&auml;n', insert_image_border : 'Reuna', insert_image_dimensions : 'Mitat', insert_image_vspace : 'Pystyv&auml;li', insert_image_hspace : 'Vaakav&auml;li', insert_image_align : 'Asettelu', insert_image_align_default : 'Oletus', insert_image_align_baseline : 'Perustasoon', insert_image_align_top : 'Yl&auml;laitaan', insert_image_align_middle : 'Keskelle', insert_image_align_bottom : 'Alalaitaan', insert_image_align_texttop : 'Tekstin yl&auml;laitaan', insert_image_align_absmiddle : 'Absoluuttisen keskelle', insert_image_align_absbottom : 'Absoluuttisen alas', insert_image_align_left : 'Vasemmalle', insert_image_align_right : 'Oikealle', theme_font_size : '-- Fonttikoko --', theme_fontdefault : '-- Fontti --', theme_block : '-- Muotoilu --', theme_paragraph : 'Kappale', theme_div : 'Div', theme_address : 'Osoite', theme_pre : 'Etuk&auml;teen muotoiltu', theme_h1 : 'Otsikko 1', theme_h2 : 'Otsikko 2', theme_h3 : 'Otsikko 3', theme_h4 : 'Otsikko 4', theme_h5 : 'Otsikko 5', theme_h6 : 'Otsikko 6', theme_colorpicker_title : 'Valitse v&auml;ri', theme_colorpicker_apply : 'Aseta v&auml;ri', theme_forecolor_desc : 'Valitse fontin v&auml;ri', theme_backcolor_desc : 'Valitse taustav&auml;ri', theme_charmap_title : 'Valitse erikoismerkki', theme_charmap_desc : 'Lis&auml;&auml; oma erikoismerkki', theme_visualaid_desc : 'N&auml;yt&auml;/piilota apuviivat', insert_anchor_title : 'Lis&auml;&auml;/muokkaa ankkuria', insert_anchor_name : 'Ankkurin nimi', theme_anchor_desc : 'Lis&auml;&auml;/muokkaa ankkuria', theme_insert_link_titlefield : 'Title', theme_clipboard_msg : 'Leikkaus/Kopiointi/Liit&auml;minen ei onnistu Mozilla eik&auml; Firefox -selaimilla tietoturvasyist&auml;. \n Haluatko lis&auml;tietoa aiheesta?', theme_path : 'Polku', cut_desc : 'Leikkaa', copy_desc : 'Kopioi', paste_desc : 'Liit&auml;', link_list : 'Linkkilista', image_list : 'Kuvalista', browse : 'Selaa', image_props_desc : 'Kuvan ominaisuudet', newdocument_desc : 'Uusi dokumentti', class_name : 'Luokka', newdocument : 'Oletko varma, ett&auml; haluat poistaa kaiken sis&auml;ll&ouml;n?', about_title : 'TinyMCE:n tiedot', about : 'Tiedot', license : 'Lisenssi', plugins : 'Pluginit', plugin : 'Plugini', author : 'Tekij&auml;', version : 'Versio', loaded_plugins : 'Ladatut pluginit', help : 'Apua', not_set : '-- Ei asetettu --', close : 'Sulje', toolbar_focus : 'Hypp&auml;&auml; ty&ouml;kalupainikkeisiin - Alt+Q, Hypp&auml;&auml; editoriin - Alt-Z, Hypp&auml;&auml; polkuun - Alt-X' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/fi.js
fi.js
tinyMCE.addToLang('',{ theme_style_select : 'Stiler', theme_code_desc : 'Redigere HTML Koden', theme_code_title : 'HTML Kildekode Redigering', theme_code_wordwrap : 'Ord deling', theme_sub_desc : 'Nedsenket skrift', theme_sup_desc : 'Opph&oslash;yd skrift', theme_hr_desc : 'Sett inn horisontal linje', theme_removeformat_desc : 'Fjern formatering', theme_custom1_desc : 'Din spesialfunksjons beskrivelse her', insert_image_border : 'Ramme', insert_image_dimensions : 'Dimensjoner', insert_image_vspace : 'Vertikalt tomrom', insert_image_hspace : 'Horisontalt tomrom', insert_image_align : 'Justering', insert_image_align_default : 'Intet', insert_image_align_baseline : 'Bunnlinjen', insert_image_align_top : 'Lengst opp', insert_image_align_middle : 'Midten', insert_image_align_bottom : 'Lengst ned', insert_image_align_texttop : 'Tekstens topp', insert_image_align_absmiddle : 'Absolutt midten', insert_image_align_absbottom : 'Absolutt lengst ned', insert_image_align_left : 'Venstre', insert_image_align_right : 'H&oslash;yre', insert_image_delta_width : 30, insert_image_delta_height : 10, theme_font_size : '-- Font st&oslash;rrelse --', theme_fontdefault : '-- Font familie --', theme_block : '-- Format --', theme_paragraph : 'Paragraf', theme_div : 'Div', theme_address : 'Adresse', theme_pre : 'Pre-formattert', theme_h1 : 'Overskrift 1', theme_h2 : 'Overskrift 2', theme_h3 : 'Overskrift 3', theme_h4 : 'Overskrift 4', theme_h5 : 'Overskrift 5', theme_h6 : 'Overskrift 6', theme_colorpicker_title : 'Velg en farge', theme_colorpicker_apply : 'Bruk', theme_forecolor_desc : 'Velg forgrunnsfarge', theme_backcolor_desc : 'Velg bakgrunnsfarge', theme_charmap_title : 'Velg spesialtegn', theme_charmap_desc : 'Sett inn spesialtegn', theme_visualaid_desc : 'Sl&aring; av/p&aring; usynlige elementer', insert_anchor_title : 'Opprette/endre anker', insert_anchor_name : 'Ankernavn', theme_anchor_desc : 'Opprette/endre anker', theme_insert_link_titlefield : 'Tittel', theme_clipboard_msg : 'Kopier/Klipp ut/Lim inn er ikke tilgjengelig i Mozilla/Firefox.\nVil du ha mere informasjon om dette?', theme_path : 'S&oslash;kevei', cut_desc : 'Klipp ut', copy_desc : 'Kopier', paste_desc : 'Lim inn', link_list : 'Lenke liste', image_list : 'Bilde liste', browse : 'Bla gjennom', image_props_desc : 'Bilde egenskaper', newdocument_desc : 'Nytt dokument', class_name : 'Stil', newdocument : 'Er du sikker p&aring; at du vil t&oslash;mme hele redigeringsomr&aring;det?', about_title : 'Om TinyMCE', about : 'Om', license : 'Lisens', plugins : 'Innstikksprogrammer', plugin : 'Innstikksprogram', author : 'Utviklere', version : 'Versjon', loaded_plugins : 'Lastet innstikksprogram', help : 'Hjelp', not_set : '-- Ikke satt --', close : 'Stopp' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/nb.js
nb.js
tinyMCE.addToLang('',{ dir : 'rtl', theme_style_select : '????', theme_code_desc : '?????? ????', theme_code_title : 'HTML ???????? ????', theme_code_wordwrap : '?? ???', theme_sub_desc : '??? ????', theme_sup_desc : '???? ????', theme_hr_desc : '??? ?? ????', theme_removeformat_desc : '??? ?? ??? ???? ????', theme_custom1_desc : 'Your custom description here', insert_image_border : '?????', insert_image_dimensions : '?????', insert_image_vspace : '????? ?????', insert_image_hspace : '????? ????', insert_image_align : '??? ????????', insert_image_align_default : '??? ???', insert_image_align_baseline : '?? ????', insert_image_align_top : '????', insert_image_align_middle : '???', insert_image_align_bottom : '?????', insert_image_align_texttop : '????? ???', insert_image_align_absmiddle : '??? ????', insert_image_align_absbottom : '????? ????', insert_image_align_left : '??', insert_image_align_right : '????', theme_font_size : '-- Font size --', theme_fontdefault : '-- Font family --', theme_block : '-- Format --', theme_paragraph : '????????', theme_div : 'Div', theme_address : '????', theme_pre : '?? ??? ????? ???', theme_h1 : '???? 1', theme_h2 : '???? 2', theme_h3 : '???? 3', theme_h4 : '???? 4', theme_h5 : '???? 5', theme_h6 : '???? 6', theme_colorpicker_title : '??? ?? ?????? ????', theme_colorpicker_apply : '?????', theme_forecolor_desc : '?????? ??? ???', theme_backcolor_desc : '?????? ??? ?????', theme_charmap_title : '?????? ??????? ????', theme_charmap_desc : '??? ??????? ????', theme_visualaid_desc : '????? ???? ???? ? ????? ??????', insert_anchor_title : '??? ? ?????? Anchor', insert_anchor_name : '??? Anchor', theme_anchor_desc : '??? ? ?????? Anchor', theme_insert_link_titlefield : '?????', theme_clipboard_msg : 'Copy/Cut/Paste is not available in Mozilla and Firefox.\nDo you want more information about this issue?', theme_path : '????', cut_desc : 'Cut', copy_desc : 'Copy', paste_desc : 'Paste', image_props_desc : 'Image properties', newdocument_desc : 'New document', newdocument : 'Are you sure you want clear all contents?' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/fa.js
fa.js
tinyMCE.addToLang('',{ theme_style_select : '-- Styles --', theme_code_desc : 'Rediger HTML kode', theme_code_title : 'HTML Kodeeditor', theme_code_wordwrap : 'Ombrydning', theme_sub_desc : 'S&aelig;nket skrift', theme_sup_desc : 'H&aelig;vet skrift', theme_hr_desc : 'Inds&aelig;t horisontal linje', theme_removeformat_desc : 'Fjern formatering', theme_custom1_desc : 'Inds&aelig;t din egen beskrivelse her', insert_image_border : 'Kant', insert_image_dimensions : 'Dimensioner', insert_image_vspace : 'Flyt til venstre', insert_image_hspace : 'Flyt til h&oslash;jre', insert_image_align : 'Justering', insert_image_align_default : 'Standard', insert_image_align_baseline : 'Bundlinje', insert_image_align_top : 'Top', insert_image_align_middle : 'Midt i', insert_image_align_bottom : 'I bunden', insert_image_align_texttop : 'I toppen af teksten', insert_image_align_absmiddle : 'Absolut midte', insert_image_align_absbottom : 'Absolut bund', insert_image_align_left : 'Venstre', insert_image_align_right : 'H&oslash;jre', theme_font_size : '-- Skrift st&oslash;rrelse --', theme_fontdefault : '-- Skrifttype --', theme_block : '-- Typografi --', theme_paragraph : 'Afsnit', theme_div : 'Div', theme_address : 'Adresse', theme_pre : 'Pr&aelig;formateret', theme_h1 : 'Overskrift 1', theme_h2 : 'Overskrift 2', theme_h3 : 'Overskrift 3', theme_h4 : 'Overskrift 4', theme_h5 : 'Overskrift 5', theme_h6 : 'Overskrift 6', theme_colorpicker_title : 'V&aelig;lg en farve', theme_colorpicker_apply : 'Anvend', theme_forecolor_desc : 'V&aelig;lg forgrundsfarve', theme_backcolor_desc : 'V&aelig;lg baggrundsfarve', theme_charmap_title : 'V&aelig;lg specialtegn', theme_charmap_desc : 'Inds&aelig;t specialtegn', theme_visualaid_desc : 'Sl&aring; linjer/usynlige elementer til og fra', insert_anchor_title : 'Inds&aelig;t/rediger bogm&aelig;rke', insert_anchor_name : 'Bogm&aelig;rkets navn', theme_anchor_desc : 'Inds&aelig;t/rediger bogm&aelig;rke', theme_insert_link_titlefield : 'Titel', theme_clipboard_msg : 'Kopier/Klip/Inds&aelig;t virker ikke i Mozilla og Firefox.\nVil du vide mere om dette?', theme_path : 'Sti', cut_desc : 'Klip', copy_desc : 'Kopier', paste_desc : 'Inds&aelig;t', link_list : 'Linkliste', image_list : 'Billedliste', browse : 'Gennemse', image_props_desc : 'Billedegenskaber', newdocument_desc : 'Nyt dokument', class_name : 'Klasse', newdocument : 'Er du sikker p&aring;, at du vil slette alt?', about_title : 'Om TinyMCE', about : 'Om', license : 'Licens', plugins : 'Plugins', plugin : 'Plugin', author : 'Forfatter', version : 'Version', loaded_plugins : 'Indl&aelig;ste plugins', help : 'Hj&aelig;lp', not_set : '-- Ikke valgt --', close : 'Luk', toolbar_focus : 'Hop til v&aelig;rkt&oslash;jslinje - Alt+Q, Hop til editor - Alt-Z, Hop til element sti - Alt-X' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/da.js
da.js
tinyMCE.addToLang('',{ theme_style_select : '-- 格式 --', theme_code_desc : '编辑HTML源代码', theme_code_title : 'HTML源代码编辑器', theme_code_wordwrap : '自动换行', theme_sub_desc : '下标', theme_sup_desc : '上标', theme_hr_desc : '插入水平线', theme_removeformat_desc : '移除格式', theme_custom1_desc : '这里填写用户自定义描述', insert_image_border : '边框', insert_image_dimensions : '维数', insert_image_vspace : '垂直间距', insert_image_hspace : '水平间距', insert_image_align : '对齐方式', insert_image_align_default : '-- 默认 --', insert_image_align_baseline : '基线', insert_image_align_top : '顶端', insert_image_align_middle : '居中', insert_image_align_bottom : '底部', insert_image_align_texttop : '文字上方', insert_image_align_absmiddle : '绝对居中', insert_image_align_absbottom : '绝对底部', insert_image_align_left : '左对齐', insert_image_align_right : '右对齐', theme_font_size : '-- 字号 --', theme_fontdefault : '-- 字体 --', theme_block : '-- 格式 --', theme_paragraph : '段落', theme_div : '层', theme_address : '地址', theme_pre : '预格式化', theme_h1 : '标题 1', theme_h2 : '标题 2', theme_h3 : '标题 3', theme_h4 : '标题 4', theme_h5 : '标题 5', theme_h6 : '标题 6', theme_colorpicker_title : '选择颜色', theme_colorpicker_apply : '应用', theme_forecolor_desc : '选择文字颜色', theme_backcolor_desc : '选择背景颜色', theme_charmap_title : '选择特殊符号', theme_charmap_desc : '插入特殊符号', theme_visualaid_desc : '开关不可见元素', insert_anchor_title : '插入/编辑 锚点', insert_anchor_name : '锚点名称', theme_anchor_desc : '插入/编辑 锚点', theme_insert_link_titlefield : '标题', theme_clipboard_msg : '剪切/复制/粘贴功能在 Mozilla 和 Firefox 浏览器中不支持。\n您希望获得更多的信息吗?', theme_path : '路径', cut_desc : '剪切', copy_desc : '复制', paste_desc : '粘贴', link_list : '链接列表', image_list : '图像列表', browse : '浏览', image_props_desc : '图像属性', newdocument_desc : '新建间档', class_name : '类', newdocument : '您确认要清除所有内容吗?', about_title : '关于 TinyMCE', about : '关于', license : '授权书', plugins : '所有插件', plugin : '插件', author : '作者', version : '版本', loaded_plugins : '读取插件', help : '帮助', not_set : '-- 空设定 --', close : '关闭', toolbar_focus : '跳到工具按钮 - Alt+Q, 跳到编辑器 - Alt-Z, 跳到元素路径 - Alt-X' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/zh_cn_utf8.js
zh_cn_utf8.js
tinyMCE.addToLang('',{ theme_style_select : '-- Phong cách --', theme_code_desc : 'Sửa mã nguồn HTML', theme_code_title : 'Bộ soạn thảo mã HTML', theme_code_wordwrap : 'Gói gọn các từ - Word wrap', theme_sub_desc : 'Chỉ số dưới', theme_sup_desc : 'Chỉ số trên', theme_hr_desc : 'Thêm đường thẳng ngang', theme_removeformat_desc : 'Xóa định dạng', theme_custom1_desc : 'Mô tả của bạn ở đây', insert_image_border : 'Khung', insert_image_dimensions : 'Kích thước', insert_image_vspace : 'Khoảng cách dọc', insert_image_hspace : 'Khoảng cách ngang', insert_image_align : 'Căn lề', insert_image_align_default : '-- Chưa đặt --', insert_image_align_baseline : 'Theo dòng', insert_image_align_top : 'Trên cùng', insert_image_align_middle : 'Giữa', insert_image_align_bottom : 'Dưới cùng', insert_image_align_texttop : 'Văn bản trên cùng', insert_image_align_absmiddle : 'Tuyệt đối giữa', insert_image_align_absbottom : 'Tuyệt đối dưới cùng', insert_image_align_left : 'Trái', insert_image_align_right : 'Phải', theme_font_size : '-- Kích thước chữ --', theme_fontdefault : '-- Font chữ --', theme_block : '-- Định dạng --', theme_paragraph : 'Đoạn', theme_div : 'Div', theme_address : 'Địa chỉ', theme_pre : 'Định dạng trước', theme_h1 : 'Tiêu đề cấp 1', theme_h2 : 'Tiêu đề cấp 2', theme_h3 : 'Tiêu đề cấp 3', theme_h4 : 'Tiêu đề cấp 4', theme_h5 : 'Tiêu đề cấp 5', theme_h6 : 'Tiêu đề cấp 6', theme_colorpicker_title : 'Chọn một màu', theme_colorpicker_apply : 'Áp&nbsp;dụng', theme_forecolor_desc : 'Chọn màu chữ', theme_backcolor_desc : 'Chọn màu nền', theme_charmap_title : 'Chọn ký tự đặc biệt', theme_charmap_desc : 'Thêm ký tự đặc biệt', theme_visualaid_desc : 'Bật tắt chế độ hướng dẫn', insert_anchor_title : 'Thêm/sửa neo', insert_anchor_name : 'Tên neo', theme_anchor_desc : 'Thêm/sửa neo', theme_insert_link_titlefield : 'Tiêu đề', theme_clipboard_msg : 'Trên Mozilla và Firefox không sử dụng được các thao tác Sao chép/Cắt/Dán. \nBạn cần thêm thông tin về điều này?', theme_path : 'Đường dẫn', cut_desc : 'Cắt', copy_desc : 'Sao chép', paste_desc : 'Dán', link_list : 'Danh sách liên kết', image_list : 'Danh sách ảnh', browse : 'Duyệt', image_props_desc : 'Thuộc tính ảnh', newdocument_desc : 'Văn bản mới', class_name : 'Lớp', newdocument : 'Bạn có chắc muốn xóa sạch nội dung?', about_title : 'Thông tin về TinyMCE', about : 'Thông tin', license : 'Chứng nhận', plugins : 'Chức năng', plugin : 'Chức năng', author : 'Tác giả', version : 'Phiên bản', loaded_plugins : 'Chức năng đã nạp', help : 'Trợ giúp', not_set : '-- Chưa đặt --', close : 'Đóng', toolbar_focus : 'Nút chuyển tới công cụ - Alt+Q, Chuyển tới bộ soạn thảo - Alt-Z, Chuyển tới đường dẫn thành phần - Alt-X' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/vi.js
vi.js
tinyMCE.addToLang('',{ theme_style_select : '-- Styles --', theme_code_desc : 'Edit HTML Source', theme_code_title : 'HTML Source Editor', theme_code_wordwrap : 'Word wrap', theme_sub_desc : 'Subscript', theme_sup_desc : 'Superscript', theme_hr_desc : 'Insert horizontal ruler', theme_removeformat_desc : 'Remove formatting', theme_custom1_desc : 'Your custom description here', insert_image_border : 'Border', insert_image_dimensions : 'Dimensions', insert_image_vspace : 'Vertical space', insert_image_hspace : 'Horizontal space', insert_image_align : 'Alignment', insert_image_align_default : '-- Not set --', insert_image_align_baseline : 'Baseline', insert_image_align_top : 'Top', insert_image_align_middle : 'Middle', insert_image_align_bottom : 'Bottom', insert_image_align_texttop : 'TextTop', insert_image_align_absmiddle : 'Absolute Middle', insert_image_align_absbottom : 'Absolute Bottom', insert_image_align_left : 'Left', insert_image_align_right : 'Right', theme_font_size : '-- Font size --', theme_fontdefault : '-- Font family --', theme_block : '-- Format --', theme_paragraph : 'Paragraph', theme_div : 'Div', theme_address : 'Address', theme_pre : 'Preformatted', theme_h1 : 'Heading 1', theme_h2 : 'Heading 2', theme_h3 : 'Heading 3', theme_h4 : 'Heading 4', theme_h5 : 'Heading 5', theme_h6 : 'Heading 6', theme_colorpicker_title : 'Select a color', theme_colorpicker_apply : 'Apply', theme_forecolor_desc : 'Select text color', theme_backcolor_desc : 'Select background color', theme_charmap_title : 'Select custom character', theme_charmap_desc : 'Insert custom character', theme_visualaid_desc : 'Toggle guidelines/invisible elements', insert_anchor_title : 'Insert/edit anchor', insert_anchor_name : 'Anchor name', theme_anchor_desc : 'Insert/edit anchor', theme_insert_link_titlefield : 'Title', theme_clipboard_msg : 'Copy/Cut/Paste is not available in Mozilla and Firefox.\nDo you want more information about this issue?', theme_path : 'Path', cut_desc : 'Cut', copy_desc : 'Copy', paste_desc : 'Paste', link_list : 'Link list', image_list : 'Image list', browse : 'Browse', image_props_desc : 'Image properties', newdocument_desc : 'New document', class_name : 'Class', newdocument : 'Are you sure you want clear all contents?', about_title : 'About TinyMCE', about : 'About', license : 'License', plugins : 'Plugins', plugin : 'Plugin', author : 'Author', version : 'Version', loaded_plugins : 'Loaded plugins', help : 'Help', not_set : '-- Not set --', close : 'Close', toolbar_focus : 'Jump to tool buttons - Alt+Q, Jump to editor - Alt-Z, Jump to element path - Alt-X' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/en.js
en.js
tinyMCE.addToLang('',{ theme_style_select : 'Štýly', theme_code_desc : 'Zobraziť HTML', theme_code_title : 'Editácia HTML', theme_code_wordwrap : 'Bez delení slov', theme_sub_desc : 'Dolný index', theme_sup_desc : 'Horný index', theme_hr_desc : 'Vložiť vodorovný oddeľovač', theme_removeformat_desc : 'Zrušiť formátovanie', theme_custom1_desc : 'Ľubovolný popisok', insert_image_border : 'Rámček', insert_image_dimensions : 'Rozmery', insert_image_vspace : 'Vertikálný okraj', insert_image_hspace : 'Horizontálný okraj', insert_image_align : 'Zarovnánie', insert_image_align_default : 'Výchozi', insert_image_align_baseline : 'Na čiare', insert_image_align_top : 'Nahor', insert_image_align_middle : 'Na stred', insert_image_align_bottom : 'Dole', insert_image_align_texttop : 'Najvyšší bod textu', insert_image_align_absmiddle : 'Stred riadku', insert_image_align_absbottom : 'Spodok riadku', insert_image_align_left : 'Vľavo', insert_image_align_right : 'Vpravo', theme_font_size : '-- Veľkosť textu --', theme_fontdefault : '-- Písmo --', theme_block : '-- Formát --', theme_paragraph : 'Odstavec', theme_div : 'Div', theme_address : 'Adresa', theme_pre : 'Predformát', theme_h1 : 'Nádpis 1', theme_h2 : 'Nádpis 2', theme_h3 : 'Nádpis 3', theme_h4 : 'Nádpis 4', theme_h5 : 'Nádpis 5', theme_h6 : 'Nádpis 6', theme_colorpicker_title : 'Výber farby', theme_colorpicker_apply : 'Vybrať', theme_forecolor_desc : 'Farba popredia', theme_backcolor_desc : 'Farba pozadia', theme_charmap_title : 'Výber znaku', theme_charmap_desc : 'Vložiť znak', theme_visualaid_desc : 'Zapnúť značky/neviditeľné prvky', insert_anchor_title : 'Vloženie/editácia záložky', insert_anchor_name : 'Názov', theme_anchor_desc : 'Vložiť/editovať záložku', theme_insert_link_titlefield : 'Názov', theme_clipboard_msg : 'Funkcie Kopírovať/vystrihnúť/vložiť niesú použiteľné v Mozille a Firefoxe.\nChcete viac informacií o tomto probléme?', theme_path : 'Cesta', cut_desc : 'Vystrihnúť', copy_desc : 'Kopírovať', paste_desc : 'Vložiť', link_list : 'Zoznam', image_list : 'Zoznam', browse : 'Prechádzať', image_props_desc : 'Vlastnosti obrázku', newdocument_desc : 'Nový dokument', newdocument : 'Ste si istý(á), že chcete vymazať všetok obsah?' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/sk.js
sk.js
tinyMCE.addToLang('',{ theme_style_select : '-- Arddulliau --', theme_code_desc : 'Golygu c&ocirc;d HTML', theme_code_title : 'Golygydd C&ocirc;d HTML', theme_code_wordwrap : 'Amlapio geiriau', theme_sub_desc : 'Is-sgript', theme_sup_desc : 'Uwch-sgript', theme_hr_desc : 'Mewnosod llinell llorweddol', theme_removeformat_desc : 'Diddymu fformatio', theme_custom1_desc : 'Dy ddisgrifiad fan hyn', insert_image_border : 'Ymyl', insert_image_dimensions : 'Meintiau', insert_image_vspace : 'Gofod fertigol', insert_image_hspace : 'Gofod llorweddol', insert_image_align : 'Unioniad', insert_image_align_default : '-- Heb ddewis --', insert_image_align_baseline : 'Gwaelodlin', insert_image_align_top : 'Brig', insert_image_align_middle : 'Canol', insert_image_align_bottom : 'Gwaelod', insert_image_align_texttop : 'Brig Testun', insert_image_align_absmiddle : 'Canol Union', insert_image_align_absbottom : 'Gwaelod Union', insert_image_align_left : 'Chwith', insert_image_align_right : 'Dde', theme_font_size : '-- Maint ffont --', theme_fontdefault : '-- Teulu ffont --', theme_block : '-- Fformat --', theme_paragraph : 'Paragraff', theme_div : 'Div', theme_address : 'Cyfeiriad', theme_pre : 'Rhag-fformatiwyd', theme_h1 : 'Pennawd 1', theme_h2 : 'Pennawd 2', theme_h3 : 'Pennawd 3', theme_h4 : 'Pennawd 4', theme_h5 : 'Pennawd 5', theme_h6 : 'Pennawd 6', theme_colorpicker_title : 'Dewis lliw', theme_colorpicker_apply : 'Gosod', theme_forecolor_desc : 'Dewis lliw testun', theme_backcolor_desc : 'Dewis lliw cefndir', theme_charmap_title : 'Dewis llythyren arbennig', theme_charmap_desc : 'Gosod llythyren arbennig', theme_visualaid_desc : 'Gwrthdroi canllawiau/elfennau anweledig', insert_anchor_title : 'Mewnosod/golygu angor', insert_anchor_name : 'Enw angor', theme_anchor_desc : 'Mewnosod/golygu angor', theme_insert_link_titlefield : 'Teitl', theme_clipboard_msg : 'Dyw Cop&iuml;o/Torri/Gludo ddim ar gael ym Mozilla na Firefox.\nHoffet ti ragor o wybodaeth ynghylch hyn?', theme_path : 'Llwybr', cut_desc : 'Torri', copy_desc : 'Cop&iuml;o', paste_desc : 'Gludo', link_list : 'Rhestr dolenni', image_list : 'Rhestr delweddau', browse : 'Pori', image_props_desc : 'Priodoleddau delwedd', newdocument_desc : 'Dogfen newydd', class_name : 'Dosbarth', newdocument : 'Wyt ti\'n sicr eisiau clirio\'r holl gynnwys?', about_title : 'Yngl&#375;n &acirc; TinyMCE', about : 'Yngl&#375;n &acirc;', license : 'Trwydded', plugins : 'Ategynnau', plugin : 'Ategyn', author : 'Awdur', version : 'Fersiwn', loaded_plugins : 'Ategynnau gweithredol', help : 'Cymorth', not_set : '-- Heb ddewis --', close : 'Cau', toolbar_focus : 'Neidio i fotymau offer - Alt+Q, Neidio i\'r golygydd - Alt+Z, Neidio i lwybr y elfen - Alt+X' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/cy.js
cy.js
tinyMCE.addToLang('',{ theme_style_select : '-- Stilar --', theme_code_desc : 'Editera HTML-koden', theme_code_title : 'HTML-k&auml;llkodseditor', theme_code_wordwrap : 'Automatiskt radbyte', theme_sub_desc : 'Neds&auml;nkt text', theme_sup_desc : 'Upph&ouml;jd text', theme_hr_desc : 'S&auml;tt in horisontell linje', theme_removeformat_desc : 'Ta bort formatering', theme_custom1_desc : 'Din specialbeskriving h&auml;r', insert_image_border : 'Ram', insert_image_dimensions : 'Dimensioner', insert_image_vspace : 'Vertikalt tomrum', insert_image_hspace : 'Horisontellt tomrum', insert_image_align : 'Justering', insert_image_align_default : 'Ingen', insert_image_align_baseline : 'Bottenlinjen', insert_image_align_top : 'L&auml;ngst upp', insert_image_align_middle : 'Mitten', insert_image_align_bottom : 'L&auml;ngst ner', insert_image_align_texttop : 'Textens top', insert_image_align_absmiddle : 'Absoluta mitten', insert_image_align_absbottom : 'Absolut l&auml;ngst ner', insert_image_align_left : 'V&auml;nster', insert_image_align_right : 'H&ouml;ger', insert_image_delta_width : 30, insert_image_delta_height : 10, theme_font_size : '-- Fontstorlek --', theme_fontdefault : '-- Font familj --', theme_block : '-- Stycke --', theme_paragraph : 'Paragraf', theme_div : 'Div', theme_address : 'Adress', theme_pre : 'F&ouml;rformatterad', theme_h1 : 'Rubrik 1', theme_h2 : 'Rubrik 2', theme_h3 : 'Rubrik 3', theme_h4 : 'Rubrik 4', theme_h5 : 'Rubrik 5', theme_h6 : 'Rubrik 6', theme_colorpicker_title : 'V&auml;lj en f&auml;rg', theme_colorpicker_apply : 'Verkst&auml;ll', theme_forecolor_desc : 'V&auml;lj f&ouml;rgrundsf&auml;rg', theme_backcolor_desc : 'V&auml;lj bakgrundsf&auml;rg', theme_charmap_title : 'V&auml;lj specialtecken', theme_charmap_desc : 'S&auml;tt in specialtecken', theme_visualaid_desc : 'Sl&aring; av/p&aring; osynliga element', insert_anchor_title : 'Skapa/redigera ankare', insert_anchor_name : 'Ankarnamn', theme_anchor_desc : 'Skapa/redigera ankare', theme_insert_link_titlefield : 'Titel', theme_clipboard_msg : 'Klipput/Kopiera/Klistra fungerar inte Mozilla och Firefox. Vill du veta mer om detta?', theme_path : 'S&ouml;kv&auml;g', cut_desc : 'Klipp ut', copy_desc : 'Kopiera', paste_desc : 'Klistra in', link_list : 'L&auml;nkar', image_list : 'Bilder', browse : 'Bl&auml;ddra', image_props_desc : 'Bild egenskaper', newdocument_desc : 'Nytt dokument', class_name : 'Stil', newdocument : '&Auml;r du s&auml;ker p&aring; att du vill t&ouml;mma hela redigerings ytan?', about_title : 'Om TinyMCE', about : 'Om', license : 'Licens', plugins : 'Insticksprogram', plugin : 'Insticksprogram', author : 'Utvecklare', version : 'Version', loaded_plugins : 'Laddade insticksprogram', help : 'Hj&auml;lp', not_set : '-- Inte satt --', close : 'St&auml;ng' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/sv.js
sv.js
tinyMCE.addToLang('',{ theme_style_select : '-- Stili --', theme_code_desc : 'Uredi HTML kodo', theme_code_title : 'Urejevalnik HTML kode', theme_code_wordwrap : 'Odre&#382;i vrstice', theme_sub_desc : 'Podpisano', theme_sup_desc : 'Nadpisano', theme_hr_desc : 'Vstavi vodoravno &#269;rto', theme_removeformat_desc : 'Odstrani oblikovanje', theme_custom1_desc : 'Va&#353; opis', insert_image_border : 'Okvir', insert_image_dimensions : 'Dimenzije', insert_image_vspace : 'Vertikalni razmak', insert_image_hspace : 'Horizontalni razmak', insert_image_align : 'Poravnava', insert_image_align_default : '-- Brez --', insert_image_align_baseline : 'Ob osnovni &#269;rti', insert_image_align_top : 'Na vrh', insert_image_align_middle : 'Na sredo', insert_image_align_bottom : 'Na dno', insert_image_align_texttop : 'Na vrh besedila', insert_image_align_absmiddle : 'Absolutna sredina', insert_image_align_absbottom : 'Absolutno dno', insert_image_align_left : 'Levo', insert_image_align_right : 'Desno', theme_font_size : '-- Velikost pisave --', theme_fontdefault : '-- Pisava --', theme_block : '-- Format --', theme_paragraph : 'Odstavek', theme_div : 'Div', theme_address : 'Naslov', theme_pre : 'Oblikovano besedilo', theme_h1 : 'Naslov 1', theme_h2 : 'Naslov 2', theme_h3 : 'Naslov 3', theme_h4 : 'Naslov 4', theme_h5 : 'Naslov 5', theme_h6 : 'Naslov 6', theme_colorpicker_title : 'Izberite barvo', theme_colorpicker_apply : 'Uporabi', theme_forecolor_desc : 'Izberite barvo pisave', theme_backcolor_desc : 'Izberite barvo ozadja', theme_charmap_title : 'Izberite poseben znak', theme_charmap_desc : 'Vstavi poseben znak', theme_visualaid_desc : 'Prika&#382;i/skrij skrite elemente', insert_anchor_title : 'Vstavi/uredi povezavo', insert_anchor_name : 'Ime povezave', theme_anchor_desc : 'Vstavi/uredi povezavo', theme_insert_link_titlefield : 'Naslov', theme_clipboard_msg : 'Kopiraj/Izre&#382;i/Prilepi ni na voljo v brskalnikih Mozilla in Firefox.\nAli &#382;elite ve&#269; informacij glede tega?', theme_path : 'Pot', cut_desc : 'Izre&#382;i', copy_desc : 'Kopiraj', paste_desc : 'Prilepi', link_list : 'Seznam povezav', image_list : 'Seznam slik', browse : 'Prebrskaj', image_props_desc : 'Lastnosti slike', newdocument_desc : 'Nov dokument', class_name : 'Razred', newdocument : 'Ali ste prepri&#269;ani, da &#382;elite zbrisati vso vsebino?', about_title : 'O urejevalniku TinyMCE', about : 'O urejevalniku', license : 'Licenca', plugins : 'Vti&#269;niki', plugin : 'Vti&#269;nik', author : 'Avtor', version : 'Razli&#269;ica', loaded_plugins : 'Nalo&#382;eni vti&#269;niki', help : 'Pomo&#269;', not_set : '-- Ni nastavljeno --', close : 'Zapri', toolbar_focus : 'Skok na orodne gumbe - Alt+Q, Skok na urejevalnik - Alt-Z, Skok na pot elementa - Alt-X' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/si.js
si.js
tinyMCE.addToLang('',{ theme_style_select : '&#1578;&#1589;&#1575;&#1605;&#1610;&#1605;', theme_code_desc : '&#1588;&#1601;&#1585;&#1577; &#1575;&#1604;&#1605;&#1589;&#1583;&#1585;', theme_code_title : '&#1588;&#1601;&#1585;&#1577; &#1575;&#1604;&#1605;&#1589;&#1583;&#1585;', theme_code_wordwrap : 'Word wrap', theme_sub_desc : '&#1605;&#1606;&#1582;&#1601;&#1590;', theme_sup_desc : '&#1605;&#1585;&#1578;&#1601;&#1593;', theme_hr_desc : '&#1573;&#1583;&#1585;&#1575;&#1580; &#1582;&#1591; &#1601;&#1575;&#1589;&#1604;', theme_removeformat_desc : '&#1573;&#1586;&#1575;&#1604;&#1577; &#1575;&#1604;&#1578;&#1606;&#1587;&#1610;&#1602;&#1575;&#1578;', theme_custom1_desc : 'Your custom description here', insert_image_border : '&#1587;&#1605;&#1603; &#1575;&#1604;&#1581;&#1583;&#1608;&#1583;', insert_image_dimensions : '&#1575;&#1604;&#1605;&#1608;&#1575;&#1589;&#1601;&#1575;&#1578;', insert_image_vspace : '&#1578;&#1576;&#1575;&#1593;&#1583; &#1593;&#1605;&#1608;&#1583;&#1610;', insert_image_hspace : '&#1578;&#1576;&#1575;&#1593;&#1583; &#1571;&#1601;&#1602;&#1610;', insert_image_align : '&#1605;&#1581;&#1575;&#1584;&#1575;&#1577;', insert_image_align_default : 'Default', insert_image_align_baseline : '&#1593;&#1604;&#1609; &#1575;&#1604;&#1587;&#1591;&#1585;', insert_image_align_top : '&#1571;&#1593;&#1604;&#1609;', insert_image_align_middle : '&#1608;&#1587;&#1591;', insert_image_align_bottom : '&#1571;&#1587;&#1601;&#1604;', insert_image_align_texttop : '&#1571;&#1593;&#1604;&#1609; &#1575;&#1604;&#1606;&#1589;', insert_image_align_absmiddle : '&#1608;&#1587;&#1591; &#1575;&#1604;&#1587;&#1591;&#1585;', insert_image_align_absbottom : '&#1571;&#1587;&#1601;&#1604; &#1575;&#1604;&#1606;&#1589;', insert_image_align_left : '&#1610;&#1587;&#1575;&#1585;', insert_image_align_right : '&#1610;&#1605;&#1610;&#1606;', theme_font_size : '-- Font size --', theme_fontdefault : '-- Font family --', theme_block : '-- Format --', theme_paragraph : 'Paragraph', theme_div : 'Div', theme_address : 'Address', theme_pre : 'Preformatted', theme_h1 : 'Heading 1', theme_h2 : 'Heading 2', theme_h3 : 'Heading 3', theme_h4 : 'Heading 4', theme_h5 : 'Heading 5', theme_h6 : 'Heading 6', theme_colorpicker_title : '&#1604;&#1608;&#1606; &#1575;&#1604;&#1606;&#1589;', theme_colorpicker_apply : 'Apply', theme_forecolor_desc : '&#1604;&#1608;&#1606; &#1575;&#1604;&#1606;&#1589;', theme_backcolor_desc : 'Select background color', theme_charmap_title : '&#1573;&#1583;&#1585;&#1575;&#1580; &#1585;&#1605;&#1586;..&#1616;', theme_charmap_desc : '&#1573;&#1583;&#1585;&#1575;&#1580; &#1585;&#1605;&#1586;..&#1616;', theme_visualaid_desc : 'Toggle guidelines/invisible elements', insert_anchor_title : 'Insert/edit anchor', insert_anchor_name : 'Anchor name', theme_anchor_desc : 'Insert/edit anchor', theme_insert_link_titlefield : 'Title', theme_clipboard_msg : 'Copy/Cut/Paste is not available in Mozilla and Firefox.\nDo you want more information about this issue?', theme_path : 'Path', cut_desc : 'Cut', copy_desc : 'Copy', paste_desc : 'Paste', link_list : 'Link list', image_list : 'Image list', browse : 'Browse', image_props_desc : 'Image properties', newdocument_desc : 'New document', newdocument : 'Are you sure you want clear all contents?' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/ar.js
ar.js
tinyMCE.addToLang('',{ theme_style_select : 'Styly', theme_code_desc : 'Zobrazit HTML', theme_code_title : 'Editace HTML', theme_code_wordwrap : 'Bez dělení slov', theme_sub_desc : 'Dolní index', theme_sup_desc : 'Horní index', theme_hr_desc : 'Vložit vodorovný oddělovač', theme_removeformat_desc : 'Zrušit formátování', theme_custom1_desc : 'Libovolný popisek', insert_image_border : 'Rámeček', insert_image_dimensions : 'Rozměry', insert_image_vspace : 'Vertikální okraj', insert_image_hspace : 'Horizontální okraj', insert_image_align : 'Zarovnání', insert_image_align_default : 'Výchozí', insert_image_align_baseline : 'Na účaří', insert_image_align_top : 'Nahoru', insert_image_align_middle : 'Na střed', insert_image_align_bottom : 'Dolů', insert_image_align_texttop : 'Nejvyšší bod textu', insert_image_align_absmiddle : 'Střed řádku', insert_image_align_absbottom : 'Spodek řádku', insert_image_align_left : 'Vlevo', insert_image_align_right : 'Vpravo', theme_font_size : '-- Velikost textu --', theme_fontdefault : '-- Písmo --', theme_block : '-- Formát --', theme_paragraph : 'Odstavec', theme_div : 'Div', theme_address : 'Adresa', theme_pre : 'Předformát', theme_h1 : 'Nadpis 1', theme_h2 : 'Nadpis 2', theme_h3 : 'Nadpis 3', theme_h4 : 'Nadpis 4', theme_h5 : 'Nadpis 5', theme_h6 : 'Nadpis 6', theme_colorpicker_title : 'Výběr barvy', theme_colorpicker_apply : 'Vybrat', theme_forecolor_desc : 'Barva popředí', theme_backcolor_desc : 'Barva pozadí', theme_charmap_title : 'Výběr znaku', theme_charmap_desc : 'Vložit znak', theme_visualaid_desc : 'Zapnout značky/neviditelné prvky', insert_anchor_title : 'Vložení/editace záložky', insert_anchor_name : 'Název', theme_anchor_desc : 'Vložit/editovat záložku', theme_insert_link_titlefield : 'Název', theme_clipboard_msg : 'Funkce Kopírovat/vyjmout/vložit nejsou použitelné v Mozille a Firefoxu.\nChcete více informací o tomto problému?', theme_path : 'Cesta', cut_desc : 'Vyjmout', copy_desc : 'Kopírovat', paste_desc : 'Vložit', link_list : 'Seznam', image_list : 'Seznam', browse : 'Procházet', image_props_desc : 'Vlastnosti obrázku', newdocument_desc : 'Nový dokument', newdocument : 'Jste si opravdu jistý(á), že chcete vymazat veškerý obsah?' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/cs.js
cs.js
tinyMCE.addToLang('',{ theme_style_select : 'Stiler', theme_code_desc : 'Redigere HTML Koden', theme_code_title : 'HTML Kildekode Redigering', theme_code_wordwrap : 'Ord deling', theme_sub_desc : 'Nedsenket skrift', theme_sup_desc : 'Opph&oslash;gd skrift', theme_hr_desc : 'Sett inn horisontal linje', theme_removeformat_desc : 'Fjern formatering', theme_custom1_desc : 'Din spesialfunksjons beskrivelse her', insert_image_border : 'Ramme', insert_image_dimensions : 'Dimensjoner', insert_image_vspace : 'Vertikalt tomrom', insert_image_hspace : 'Horisontalt tomrom', insert_image_align : 'Justering', insert_image_align_default : 'Intet', insert_image_align_baseline : 'Bunnlinjen', insert_image_align_top : 'Lengst opp', insert_image_align_middle : 'Midten', insert_image_align_bottom : 'Lengst ned', insert_image_align_texttop : 'Tekstens topp', insert_image_align_absmiddle : 'Absolutt midten', insert_image_align_absbottom : 'Absolutt lengst ned', insert_image_align_left : 'Venstre', insert_image_align_right : 'H&oslash;gre', insert_image_delta_width : 30, insert_image_delta_height : 10, theme_font_size : '-- Font st&oslash;rrelse --', theme_fontdefault : '-- Font familie --', theme_block : '-- Format --', theme_paragraph : 'Paragraf', theme_div : 'Div', theme_address : 'Adresse', theme_pre : 'Pre-formattert', theme_h1 : 'Overskrift 1', theme_h2 : 'Overskrift 2', theme_h3 : 'Overskrift 3', theme_h4 : 'Overskrift 4', theme_h5 : 'Overskrift 5', theme_h6 : 'Overskrift 6', theme_colorpicker_title : 'Velg en farge', theme_colorpicker_apply : 'Bruk', theme_forecolor_desc : 'Velg forgrunnsfarge', theme_backcolor_desc : 'Velg bakgrunnsfarge', theme_charmap_title : 'Velg spesialtegn', theme_charmap_desc : 'Sett inn spesialtegn', theme_visualaid_desc : 'Sl&aring; av/p&aring; usynlige elementer', insert_anchor_title : 'Opprette/endre anker', insert_anchor_name : 'Ankernavn', theme_anchor_desc : 'Opprette/endre anker', theme_insert_link_titlefield : 'Tittel', theme_clipboard_msg : 'Kopier/Klipp ut/Lim inn er ikke tilgjengelig i Mozilla/Firefox.\nVil du ha mere informasjon om dette?', theme_path : 'S&oslash;kevei', cut_desc : 'Klipp ut', copy_desc : 'Kopier', paste_desc : 'Lim inn', link_list : 'Lenke liste', image_list : 'Bilde liste', browse : 'Bla gjennom', image_props_desc : 'Bilde egenskaper', newdocument_desc : 'Nytt dokument', class_name : 'Stil', newdocument : 'Er du sikker p&aring; at du vil t&oslash;mme hele redigeringsomr&aring;det?', about_title : 'Om TinyMCE', about : 'Om', license : 'Lisens', plugins : 'Innstikksprogrammer', plugin : 'Innstikksprogram', author : 'Utviklere', version : 'Versjon', loaded_plugins : 'Lastet innstikksprogram', help : 'Hjelp', not_set : '-- Ikkje satt --', close : 'Stopp' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/nn.js
nn.js
tinyMCE.addToLang('',{ theme_style_select : '-- CSS-Stile --', theme_code_desc : 'HTML-Quelltext editieren', theme_code_title : 'HTML-Quelltexteditor', theme_code_wordwrap : 'Zeilenumbruch', theme_sub_desc : 'Tiefergestellt', theme_sup_desc : 'Hochgestellt', theme_hr_desc : 'Horizontalen Balken einf&uuml;gen', theme_removeformat_desc : 'Formatierung l&ouml;schen', theme_custom1_desc : 'Eigene Beschreibung', insert_image_border : 'Rahmen', insert_image_dimensions : 'Gr&ouml;&szlig;e', insert_image_vspace : 'Vertikaler Raum', insert_image_hspace : 'Horizontaler Raum', insert_image_align : 'Ausrichtung', insert_image_align_default : '-- Nicht festgelegt --', insert_image_align_baseline : 'Grundlinie', insert_image_align_top : 'Oben', insert_image_align_middle : 'Mitte', insert_image_align_bottom : 'Unten', insert_image_align_texttop : 'Mit dem Text', insert_image_align_absmiddle : 'Absolute mittig', insert_image_align_absbottom : 'Absolut unten', insert_image_align_left : 'Links', insert_image_align_right : 'Rechts', theme_font_size : '-- Schriftgr&ouml;&szlig;e --', theme_fontdefault : '-- Schriftfamilie --', theme_block : '-- Format --', theme_paragraph : 'Absatz', theme_div : 'Block', theme_address : 'Adresse', theme_pre : 'Vorformatiert', theme_h1 : '&Uuml;berschrift 1', theme_h2 : '&Uuml;berschrift 2', theme_h3 : '&Uuml;berschrift 3', theme_h4 : '&Uuml;berschrift 4', theme_h5 : '&Uuml;berschrift 5', theme_h6 : '&Uuml;berschrift 6', theme_colorpicker_title : 'Farbe ausw&auml;hlen', theme_colorpicker_apply : 'Farbe festlegen', theme_forecolor_desc : 'Schriftfarbe ausw&auml;hlen', theme_backcolor_desc : 'Hintergrundfarbe ausw&auml;hlen', theme_charmap_title : 'Sonderzeichen einf&uuml;gen', theme_charmap_desc : 'Sonderzeichen einf&uuml;gen', theme_visualaid_desc : 'Hilfslinen/Unsichtbare Elemente anzeigen', insert_anchor_title : 'Anker einf&uuml;gen/bearbeiten', insert_anchor_name : 'Ankername', theme_anchor_desc : 'Anker einf&uuml;gen/bearbeiten', theme_insert_link_titlefield : 'Titel', theme_clipboard_msg : 'Zwischenablagefunktionen sind in Mozilla und Firefox nicht verf&uuml;gbar.\nW&uuml;nschen Sie hierzu weitere Informationen?', theme_path : 'Pfad', cut_desc : 'Ausschneiden', copy_desc : 'Kopieren', paste_desc : 'Einf&uuml;gen', link_list : 'Hyperlink-Liste', image_list : 'Bild-Liste', browse : 'Durchsuchen', image_props_desc : 'Bildeigenschaften', newdocument_desc : 'Neues Dokument', class_name : 'CSS-Klasse', newdocument : 'Sind Sie sicher, dass Sie alle Inhalte l&ouml;schen wollen?', about_title : '&Uuml;ber TinyMCE', about : '&Uuml;ber', license : 'Lizenz', plugins : 'Plugins', plugin : 'Plugin', author : 'Autor', version : 'Version', loaded_plugins : 'Geladene Plugins', help : 'Hilfe', not_set : '-- Nicht festgelegt --', close : 'Schlie&szlig;en', toolbar_focus : 'Jump to tool buttons - Alt+Q, Jump to editor - Alt-Z, Jump to element path - Alt-X', insert_link_delta_width : 40 });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/de.js
de.js
tinyMCE.addToLang('',{ theme_style_select : '-- Стили --', theme_code_desc : 'Редактировать HTML коды', theme_code_title : 'Редактор HTML кодов', theme_code_wordwrap : 'Перенос по словам', theme_sub_desc : 'Нижний индекс', theme_sup_desc : 'Верхний индекс', theme_hr_desc : 'Вставить горизонтальный разделитель', theme_removeformat_desc : 'Убрать форматирование', theme_custom1_desc : 'Ваше произвольное описание', insert_image_border : 'Рамка', insert_image_dimensions : 'Размеры', insert_image_vspace : 'Вертикальный отступ', insert_image_hspace : 'Горизонтальный отступ', insert_image_align : 'Выравнивание', insert_image_align_default : '-- Не задано --', insert_image_align_baseline : 'По базовой линии', insert_image_align_top : 'По верху', insert_image_align_middle : 'Посредине', insert_image_align_bottom : 'По низу', insert_image_align_texttop : 'По верху текста', insert_image_align_absmiddle : 'Абсолютно посредине', insert_image_align_absbottom : 'Абсолютно сверху', insert_image_align_left : 'Влево', insert_image_align_right : 'Вправо', theme_font_size : '-- Размер шрифта --', theme_fontdefault : '-- Семейство шрифтов --', theme_block : '-- Формат --', theme_paragraph : 'Абзац', theme_div : 'Div', theme_address : 'Стиль адреса', theme_pre : ':`Предварительно форматированный', theme_h1 : 'Заголовок 1', theme_h2 : 'Заголовок 2', theme_h3 : 'Заголовок 3', theme_h4 : 'Заголовок 4', theme_h5 : 'Заголовок 5', theme_h6 : 'Заголовок 6', theme_colorpicker_title : 'Выбрать цвет', theme_colorpicker_apply : 'Применить', theme_forecolor_desc : 'Выбрать цвет текста', theme_backcolor_desc : 'Выбрать цвет фона', theme_charmap_title : 'Выбор произвольного символа', theme_charmap_desc : 'Вставить произвольный символ', theme_visualaid_desc : 'Показать границы скрытых элементов', insert_anchor_title : 'Вставить/редактировать якорь', insert_anchor_name : 'Имя якоря', theme_anchor_desc : 'Вставить/редактировать якорь', theme_insert_link_titlefield : 'Заголовок', theme_clipboard_msg : 'Копировать/Вырезать/Вставить недоступны для Mozilla и Firefox.\nХотите узнать об этом подробнее?', theme_path : 'Путь', cut_desc : 'Вырезать', copy_desc : 'Копировать', paste_desc : 'Вставить', link_list : 'Перечань ссылок', image_list : 'Перечень картинок', browse : 'Подобрать', image_props_desc : 'Свойства картинки', newdocument_desc : 'Новый документ', class_name : 'Класс', newdocument : 'Вы уверены, что хотите очистить всё содержимое?', about_title : 'О TinyMCE', about : 'О TinyMCE', license : 'Лицензия', plugins : 'Плагины', plugin : 'Плагин', author : 'Автор', version : 'Версия', loaded_plugins : 'Загруженные плагины', help : 'Помощь', not_set : '-- не установлено --', close : 'Закрыть', toolbar_focus : 'Переместить фокус на панель инструментов - Alt+Q, Переместить фокус в редактор - Alt-Z, Переместить фокус на элемент пути - Alt-X' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/ru_UTF-8.js
ru_UTF-8.js
tinyMCE.addToLang('',{ theme_style_select : '-- 式樣 --', theme_code_desc : '編輯 HTML 碼', theme_code_title : 'HTML 碼編輯器', theme_code_wordwrap : '字詞環繞', theme_sub_desc : '下標', theme_sup_desc : '上標', theme_hr_desc : '插入水平線', theme_removeformat_desc : '清除格式設定', theme_custom1_desc : '自訂說明在此輸入', insert_image_border : '框線', insert_image_dimensions : '尺寸', insert_image_vspace : '圖像上下側間距', insert_image_hspace : '圖像左右邊間距', insert_image_align : '垂直對齊', insert_image_align_default : '-- 未設置 --', insert_image_align_baseline : '底線', insert_image_align_top : '頂端', insert_image_align_middle : '中線', insert_image_align_bottom : '底部', insert_image_align_texttop : '文字頂端', insert_image_align_absmiddle : '絕對中線', insert_image_align_absbottom : '絕對底部', insert_image_align_left : '左', insert_image_align_right : '右', theme_font_size : '-- 字體大小 --', theme_fontdefault : '-- 字體選擇 --', theme_block : '-- 格式 --', theme_paragraph : '段落', theme_div : '分界', theme_address : '位置', theme_pre : '內定格式', theme_h1 : '標題一', theme_h2 : '標題二', theme_h3 : '標題三', theme_h4 : '標題四', theme_h5 : '標題五', theme_h6 : '標題六', theme_colorpicker_title : '選取顏色', theme_colorpicker_apply : '套用', theme_forecolor_desc : '選取文字顏色', theme_backcolor_desc : '選取背景顏色', theme_charmap_title : '選取自訂字元', theme_charmap_desc : '插入自訂字元', theme_visualaid_desc : '切換指示或非可見元件', insert_anchor_title : '插入或編輯連結點', insert_anchor_name : '連結點名稱', theme_anchor_desc : '插入或編輯連結點', theme_insert_link_titlefield : '標題', theme_clipboard_msg : '在 Mozilla 和 Firefox 中無法使用複製或剪下或貼上功能。\n需要更多關於此的訊息嗎?', theme_path : '路徑', cut_desc : '剪下', copy_desc : '複製', paste_desc : '貼上', link_list : '連結列表', image_list : '圖檔列表', browse : '瀏覽', image_props_desc : '圖檔屬性', newdocument_desc : '新文件', class_name : '分類', newdocument : '確定要清除全部內容?', about_title : '關於 TinyMCE', about : '關於', license : '授權', plugins : '應用套件', plugin : '應用套件', author : '作者', version : '版本', loaded_plugins : '已載入應用套件', help : '協助', not_set : '-- 未設置 --', close : '關閉', toolbar_focus : '快速啟用工具紐 - Alt+Q;快速啟用編輯器 - Alt-Z;快速移至元件路徑 - Alt-X' });
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/langs/zh_tw_utf8.js
zh_tw_utf8.js
var url = tinyMCE.getParam("external_link_list_url"); if (url != null) { // Fix relative if (url.charAt(0) != '/' && url.indexOf('://') == -1) url = tinyMCE.documentBasePath + "/" + url; document.write('<sc'+'ript language="javascript" type="text/javascript" src="' + url + '"></sc'+'ript>'); } function init() { tinyMCEPopup.resizeToInnerSize(); document.getElementById('hrefbrowsercontainer').innerHTML = getBrowserHTML('hrefbrowser','href','file','theme_advanced_link'); // Handle file browser if (isVisible('hrefbrowser')) document.getElementById('href').style.width = '180px'; var formObj = document.forms[0]; for (var i=0; i<document.forms[0].target.options.length; i++) { var option = document.forms[0].target.options[i]; if (option.value == tinyMCE.getWindowArg('target')) option.selected = true; } document.forms[0].href.value = tinyMCE.getWindowArg('href'); document.forms[0].linktitle.value = tinyMCE.getWindowArg('title'); document.forms[0].insert.value = tinyMCE.getLang('lang_' + tinyMCE.getWindowArg('action'), 'Insert', true); addClassesToList('styleSelect', 'theme_advanced_link_styles'); selectByValue(formObj, 'styleSelect', tinyMCE.getWindowArg('className'), true); // Hide css select row if no CSS classes if (formObj.styleSelect && formObj.styleSelect.options.length <= 1) { var sr = document.getElementById('styleSelectRow'); sr.style.display = 'none'; sr.parentNode.removeChild(sr); } // Auto select link in list if (typeof(tinyMCELinkList) != "undefined" && tinyMCELinkList.length > 0) { var formObj = document.forms[0]; for (var i=0; i<formObj.link_list.length; i++) { if (formObj.link_list.options[i].value == tinyMCE.getWindowArg('href')) formObj.link_list.options[i].selected = true; } } } function insertLink() { var href = document.forms[0].href.value; var target = document.forms[0].target.options[document.forms[0].target.selectedIndex].value; var title = document.forms[0].linktitle.value; var style_class = document.forms[0].styleSelect ? document.forms[0].styleSelect.value : ""; var dummy; // Make anchors absolute if (href.charAt(0) == '#') href = tinyMCE.settings['document_base_url'] + href; if (target == '_self') target = ''; tinyMCEPopup.restoreSelection(); tinyMCE.themes['advanced']._insertLink(href, target, title, dummy, style_class); tinyMCEPopup.close(); }
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/jscripts/link.js
link.js
function init() { var inst; tinyMCEPopup.resizeToInnerSize(); inst = tinyMCE.selectedInstance; // Give FF some time window.setTimeout('insertHelpIFrame();', 10); var tcont = document.getElementById('plugintablecontainer'); var plugins = tinyMCE.getParam('plugins', '', true, ','); if (plugins.length == 0) document.getElementById('plugins_tab').style.display = 'none'; var html = ""; html += '<table id="plugintable">'; html += '<thead>'; html += '<tr>'; html += '<td>' + tinyMCE.getLang('lang_plugin') + '</td>'; html += '<td>' + tinyMCE.getLang('lang_author') + '</td>'; html += '<td>' + tinyMCE.getLang('lang_version') + '</td>'; html += '</tr>'; html += '</thead>'; html += '<tbody>'; for (var i=0; i<inst.plugins.length; i++) { var info = getPluginInfo(inst.plugins[i]); html += '<tr>'; if (info.infourl != null && info.infourl != '') html += '<td width="50%" title="' + plugins[i] + '"><a href="' + info.infourl + '" target="mceplugin">' + info.longname + '</a></td>'; else html += '<td width="50%" title="' + plugins[i] + '">' + info.longname + '</td>'; if (info.authorurl != null && info.authorurl != '') html += '<td width="35%"><a href="' + info.authorurl + '" target="mceplugin">' + info.author + '</a></td>'; else html += '<td width="35%">' + info.author + '</td>'; html += '<td width="15%">' + info.version + '</td>'; html += '</tr>'; } html += '</tbody>'; html += '</table>'; tcont.innerHTML = html; } function getPluginInfo(name) { if (tinyMCE.plugins[name].getInfo) return tinyMCE.plugins[name].getInfo(); return { longname : name, authorurl : '', infourl : '', author : '--', version : '--' }; } function insertHelpIFrame() { var html = '<iframe width="100%" height="300" src="' + tinyMCE.themeURL + "/docs/" + tinyMCE.settings['docs_language'] + "/index.htm" + '"></iframe>'; document.getElementById('iframecontainer').innerHTML = html; html = ''; html += '<a href="http://www.moxiecode.com" target="_blank"><img src="http://tinymce.moxiecode.com/images/gotmoxie.png" alt="Got Moxie?" border="0" /></a> '; html += '<a href="http://sourceforge.net/projects/tinymce/" target="_blank"><img src="http://sourceforge.net/sflogo.php?group_id=103281" alt="Hosted By Sourceforge" border="0" /></a> '; html += '<a href="http://www.freshmeat.net/projects/tinymce" target="_blank"><img src="http://tinymce.moxiecode.com/images/fm.gif" alt="Also on freshmeat" border="0" /></a> '; document.getElementById('buttoncontainer').innerHTML = html; }
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/jscripts/about.js
about.js
function init() { tinyMCEPopup.resizeToInnerSize(); } var charmap = new Array(); // for mor details please see w3c.org // now here is the complete list ;) charmap = [ ['&nbsp;', '&#160;', true, 'no-break space'], ['&amp;', '&#38;', true, 'ampersand'], ['&quot;', '&#34;', true, 'quotation mark'], // finance ['&cent;', '&#162;', true, 'cent sign'], ['&euro;', '&#8364;', true, 'euro sign'], ['&pound;', '&#163;', true, 'pound sign'], ['&yen;', '&#165;', true, 'yen sign'], // signs ['&copy;', '&#169;', true, 'copyright sign'], ['&reg;', '&#174;', true, 'registered sign'], ['&trade;', '&#8482;', true, 'trade mark sign'], ['&permil;', '&#8240;', true, 'per mille sign'], ['&micro;', '&#181;', true, 'micro sign'], ['&middot;', '&#183;', true, 'middle dot'], ['&bull;', '&#8226;', true, 'bullet'], ['&hellip;', '&#8230;', true, 'three dot leader'], ['&prime;', '&#8242;', true, 'minutes / feet'], ['&Prime;', '&#8243;', true, 'seconds / inches'], ['&sect;', '&#167;', true, 'section sign'], ['&para;', '&#182;', true, 'paragraph sign'], ['&szlig;', '&#223;', true, 'sharp s / ess-zed'], // quotations ['&lsaquo;', '&#8249;', true, 'single left-pointing angle quotation mark'], ['&rsaquo;', '&#8250;', true, 'single right-pointing angle quotation mark'], ['&laquo;', '&#171;', true, 'left pointing guillemet'], ['&raquo;', '&#187;', true, 'right pointing guillemet'], ['&lsquo;', '&#8216;', true, 'left single quotation mark'], ['&rsquo;', '&#8217;', true, 'right single quotation mark'], ['&ldquo;', '&#8220;', true, 'left double quotation mark'], ['&rdquo;', '&#8221;', true, 'right double quotation mark'], ['&sbquo;', '&#8218;', true, 'single low-9 quotation mark'], ['&bdquo;', '&#8222;', true, 'double low-9 quotation mark'], ['&lt;', '&#60;', true, 'less-than sign'], ['&gt;', '&#62;', true, 'greater-than sign'], ['&le;', '&#8804;', true, 'less-than or equal to'], ['&ge;', '&#8805;', true, 'greater-than or equal to'], ['&ndash;', '&#8211;', true, 'en dash'], ['&mdash;', '&#8212;', true, 'em dash'], ['&macr;', '&#175;', true, 'macron'], ['&oline;', '&#8254;', true, 'overline'], ['&curren;', '&#164;', true, 'currency sign'], ['&brvbar;', '&#166;', true, 'broken bar'], ['&uml;', '&#168;', true, 'diaeresis'], ['&iexcl;', '&#161;', true, 'inverted exclamation mark'], ['&iquest;', '&#191;', true, 'turned question mark'], ['&circ;', '&#710;', true, 'circumflex accent'], ['&tilde;', '&#732;', true, 'small tilde'], ['&deg;', '&#176;', true, 'degree sign'], ['&minus;', '&#8722;', true, 'minus sign'], ['&plusmn;', '&#177;', true, 'plus-minus sign'], ['&divide;', '&#247;', true, 'division sign'], ['&frasl;', '&#8260;', true, 'fraction slash'], ['&times;', '&#215;', true, 'multiplication sign'], ['&sup1;', '&#185;', true, 'superscript one'], ['&sup2;', '&#178;', true, 'superscript two'], ['&sup3;', '&#179;', true, 'superscript three'], ['&frac14;', '&#188;', true, 'fraction one quarter'], ['&frac12;', '&#189;', true, 'fraction one half'], ['&frac34;', '&#190;', true, 'fraction three quarters'], // math / logical ['&fnof;', '&#402;', true, 'function / florin'], ['&int;', '&#8747;', true, 'integral'], ['&sum;', '&#8721;', true, 'n-ary sumation'], ['&infin;', '&#8734;', true, 'infinity'], ['&radic;', '&#8730;', true, 'square root'], ['&sim;', '&#8764;', false,'similar to'], ['&cong;', '&#8773;', false,'approximately equal to'], ['&asymp;', '&#8776;', true, 'almost equal to'], ['&ne;', '&#8800;', true, 'not equal to'], ['&equiv;', '&#8801;', true, 'identical to'], ['&isin;', '&#8712;', false,'element of'], ['&notin;', '&#8713;', false,'not an element of'], ['&ni;', '&#8715;', false,'contains as member'], ['&prod;', '&#8719;', true, 'n-ary product'], ['&and;', '&#8743;', false,'logical and'], ['&or;', '&#8744;', false,'logical or'], ['&not;', '&#172;', true, 'not sign'], ['&cap;', '&#8745;', true, 'intersection'], ['&cup;', '&#8746;', false,'union'], ['&part;', '&#8706;', true, 'partial differential'], ['&forall;', '&#8704;', false,'for all'], ['&exist;', '&#8707;', false,'there exists'], ['&empty;', '&#8709;', false,'diameter'], ['&nabla;', '&#8711;', false,'backward difference'], ['&lowast;', '&#8727;', false,'asterisk operator'], ['&prop;', '&#8733;', false,'proportional to'], ['&ang;', '&#8736;', false,'angle'], // undefined ['&acute;', '&#180;', true, 'acute accent'], ['&cedil;', '&#184;', true, 'cedilla'], ['&ordf;', '&#170;', true, 'feminine ordinal indicator'], ['&ordm;', '&#186;', true, 'masculine ordinal indicator'], ['&dagger;', '&#8224;', true, 'dagger'], ['&Dagger;', '&#8225;', true, 'double dagger'], // alphabetical special chars ['&Agrave;', '&#192;', true, 'A - grave'], ['&Aacute;', '&#193;', true, 'A - acute'], ['&Acirc;', '&#194;', true, 'A - circumflex'], ['&Atilde;', '&#195;', true, 'A - tilde'], ['&Auml;', '&#196;', true, 'A - diaeresis'], ['&Aring;', '&#197;', true, 'A - ring above'], ['&AElig;', '&#198;', true, 'ligature AE'], ['&Ccedil;', '&#199;', true, 'C - cedilla'], ['&Egrave;', '&#200;', true, 'E - grave'], ['&Eacute;', '&#201;', true, 'E - acute'], ['&Ecirc;', '&#202;', true, 'E - circumflex'], ['&Euml;', '&#203;', true, 'E - diaeresis'], ['&Igrave;', '&#204;', true, 'I - grave'], ['&Iacute;', '&#205;', true, 'I - acute'], ['&Icirc;', '&#206;', true, 'I - circumflex'], ['&Iuml;', '&#207;', true, 'I - diaeresis'], ['&ETH;', '&#208;', true, 'ETH'], ['&Ntilde;', '&#209;', true, 'N - tilde'], ['&Ograve;', '&#210;', true, 'O - grave'], ['&Oacute;', '&#211;', true, 'O - acute'], ['&Ocirc;', '&#212;', true, 'O - circumflex'], ['&Otilde;', '&#213;', true, 'O - tilde'], ['&Ouml;', '&#214;', true, 'O - diaeresis'], ['&Oslash;', '&#216;', true, 'O - slash'], ['&OElig;', '&#338;', true, 'ligature OE'], ['&Scaron;', '&#352;', true, 'S - caron'], ['&Ugrave;', '&#217;', true, 'U - grave'], ['&Uacute;', '&#218;', true, 'U - acute'], ['&Ucirc;', '&#219;', true, 'U - circumflex'], ['&Uuml;', '&#220;', true, 'U - diaeresis'], ['&Yacute;', '&#221;', true, 'Y - acute'], ['&Yuml;', '&#376;', true, 'Y - diaeresis'], ['&THORN;', '&#222;', true, 'THORN'], ['&agrave;', '&#224;', true, 'a - grave'], ['&aacute;', '&#225;', true, 'a - acute'], ['&acirc;', '&#226;', true, 'a - circumflex'], ['&atilde;', '&#227;', true, 'a - tilde'], ['&auml;', '&#228;', true, 'a - diaeresis'], ['&aring;', '&#229;', true, 'a - ring above'], ['&aelig;', '&#230;', true, 'ligature ae'], ['&ccedil;', '&#231;', true, 'c - cedilla'], ['&egrave;', '&#232;', true, 'e - grave'], ['&eacute;', '&#233;', true, 'e - acute'], ['&ecirc;', '&#234;', true, 'e - circumflex'], ['&euml;', '&#235;', true, 'e - diaeresis'], ['&igrave;', '&#236;', true, 'i - grave'], ['&iacute;', '&#237;', true, 'i - acute'], ['&icirc;', '&#238;', true, 'i - circumflex'], ['&iuml;', '&#239;', true, 'i - diaeresis'], ['&eth;', '&#240;', true, 'eth'], ['&ntilde;', '&#241;', true, 'n - tilde'], ['&ograve;', '&#242;', true, 'o - grave'], ['&oacute;', '&#243;', true, 'o - acute'], ['&ocirc;', '&#244;', true, 'o - circumflex'], ['&otilde;', '&#245;', true, 'o - tilde'], ['&ouml;', '&#246;', true, 'o - diaeresis'], ['&oslash;', '&#248;', true, 'o slash'], ['&oelig;', '&#339;', true, 'ligature oe'], ['&scaron;', '&#353;', true, 's - caron'], ['&ugrave;', '&#249;', true, 'u - grave'], ['&uacute;', '&#250;', true, 'u - acute'], ['&ucirc;', '&#251;', true, 'u - circumflex'], ['&uuml;', '&#252;', true, 'u - diaeresis'], ['&yacute;', '&#253;', true, 'y - acute'], ['&thorn;', '&#254;', true, 'thorn'], ['&yuml;', '&#255;', true, 'y - diaeresis'], ['&Alpha;', '&#913;', true, 'Alpha'], ['&Beta;', '&#914;', true, 'Beta'], ['&Gamma;', '&#915;', true, 'Gamma'], ['&Delta;', '&#916;', true, 'Delta'], ['&Epsilon;', '&#917;', true, 'Epsilon'], ['&Zeta;', '&#918;', true, 'Zeta'], ['&Eta;', '&#919;', true, 'Eta'], ['&Theta;', '&#920;', true, 'Theta'], ['&Iota;', '&#921;', true, 'Iota'], ['&Kappa;', '&#922;', true, 'Kappa'], ['&Lambda;', '&#923;', true, 'Lambda'], ['&Mu;', '&#924;', true, 'Mu'], ['&Nu;', '&#925;', true, 'Nu'], ['&Xi;', '&#926;', true, 'Xi'], ['&Omicron;', '&#927;', true, 'Omicron'], ['&Pi;', '&#928;', true, 'Pi'], ['&Rho;', '&#929;', true, 'Rho'], ['&Sigma;', '&#931;', true, 'Sigma'], ['&Tau;', '&#932;', true, 'Tau'], ['&Upsilon;', '&#933;', true, 'Upsilon'], ['&Phi;', '&#934;', true, 'Phi'], ['&Chi;', '&#935;', true, 'Chi'], ['&Psi;', '&#936;', true, 'Psi'], ['&Omega;', '&#937;', true, 'Omega'], ['&alpha;', '&#945;', true, 'alpha'], ['&beta;', '&#946;', true, 'beta'], ['&gamma;', '&#947;', true, 'gamma'], ['&delta;', '&#948;', true, 'delta'], ['&epsilon;', '&#949;', true, 'epsilon'], ['&zeta;', '&#950;', true, 'zeta'], ['&eta;', '&#951;', true, 'eta'], ['&theta;', '&#952;', true, 'theta'], ['&iota;', '&#953;', true, 'iota'], ['&kappa;', '&#954;', true, 'kappa'], ['&lambda;', '&#955;', true, 'lambda'], ['&mu;', '&#956;', true, 'mu'], ['&nu;', '&#957;', true, 'nu'], ['&xi;', '&#958;', true, 'xi'], ['&omicron;', '&#959;', true, 'omicron'], ['&pi;', '&#960;', true, 'pi'], ['&rho;', '&#961;', true, 'rho'], ['&sigmaf;', '&#962;', true, 'final sigma'], ['&sigma;', '&#963;', true, 'sigma'], ['&tau;', '&#964;', true, 'tau'], ['&upsilon;', '&#965;', true, 'upsilon'], ['&phi;', '&#966;', true, 'phi'], ['&chi;', '&#967;', true, 'chi'], ['&psi;', '&#968;', true, 'psi'], ['&omega;', '&#969;', true, 'omega'], // symbols ['&alefsym;', '&#8501;', false,'alef symbol'], ['&piv;', '&#982;', false,'pi symbol'], ['&real;', '&#8476;', false,'real part symbol'], ['&thetasym;','&#977;', false,'theta symbol'], ['&upsih;', '&#978;', false,'upsilon - hook symbol'], ['&weierp;', '&#8472;', false,'Weierstrass p'], ['&image;', '&#8465;', false,'imaginary part'], // arrows ['&larr;', '&#8592;', true, 'leftwards arrow'], ['&uarr;', '&#8593;', true, 'upwards arrow'], ['&rarr;', '&#8594;', true, 'rightwards arrow'], ['&darr;', '&#8595;', true, 'downwards arrow'], ['&harr;', '&#8596;', true, 'left right arrow'], ['&crarr;', '&#8629;', false,'carriage return'], ['&lArr;', '&#8656;', false,'leftwards double arrow'], ['&uArr;', '&#8657;', false,'upwards double arrow'], ['&rArr;', '&#8658;', false,'rightwards double arrow'], ['&dArr;', '&#8659;', false,'downwards double arrow'], ['&hArr;', '&#8660;', false,'left right double arrow'], ['&there4;', '&#8756;', false,'therefore'], ['&sub;', '&#8834;', false,'subset of'], ['&sup;', '&#8835;', false,'superset of'], ['&nsub;', '&#8836;', false,'not a subset of'], ['&sube;', '&#8838;', false,'subset of or equal to'], ['&supe;', '&#8839;', false,'superset of or equal to'], ['&oplus;', '&#8853;', false,'circled plus'], ['&otimes;', '&#8855;', false,'circled times'], ['&perp;', '&#8869;', false,'perpendicular'], ['&sdot;', '&#8901;', false,'dot operator'], ['&lceil;', '&#8968;', false,'left ceiling'], ['&rceil;', '&#8969;', false,'right ceiling'], ['&lfloor;', '&#8970;', false,'left floor'], ['&rfloor;', '&#8971;', false,'right floor'], ['&lang;', '&#9001;', false,'left-pointing angle bracket'], ['&rang;', '&#9002;', false,'right-pointing angle bracket'], ['&loz;', '&#9674;', true,'lozenge'], ['&spades;', '&#9824;', false,'black spade suit'], ['&clubs;', '&#9827;', true, 'black club suit'], ['&hearts;', '&#9829;', true, 'black heart suit'], ['&diams;', '&#9830;', true, 'black diamond suit'], ['&ensp;', '&#8194;', false,'en space'], ['&emsp;', '&#8195;', false,'em space'], ['&thinsp;', '&#8201;', false,'thin space'], ['&zwnj;', '&#8204;', false,'zero width non-joiner'], ['&zwj;', '&#8205;', false,'zero width joiner'], ['&lrm;', '&#8206;', false,'left-to-right mark'], ['&rlm;', '&#8207;', false,'right-to-left mark'], ['&shy;', '&#173;', false,'soft hyphen'] ]; function renderCharMapHTML() { var charsPerRow = 20, tdWidth=20, tdHeight=20; var html = '<table border="0" cellspacing="1" cellpadding="0" width="' + (tdWidth*charsPerRow) + '"><tr height="' + tdHeight + '">'; var cols=-1; for (var i=0; i<charmap.length; i++) { if (charmap[i][2]==true) { cols++; html += '' + '<td width="' + tdWidth + '" height="' + tdHeight + '" class="charmap"' + ' onmouseover="this.className=\'charmapOver\';' + 'previewChar(\'' + charmap[i][1].substring(1,charmap[i][1].length) + '\',\'' + charmap[i][0].substring(1,charmap[i][0].length) + '\',\'' + charmap[i][3] + '\');"' + ' onmouseout="this.className=\'charmap\';"' + ' nowrap="nowrap" onclick="insertChar(\'' + charmap[i][1].substring(2,charmap[i][1].length-1) + '\');"><a style="text-decoration: none;" onfocus="previewChar(\'' + charmap[i][1].substring(1,charmap[i][1].length) + '\',\'' + charmap[i][0].substring(1,charmap[i][0].length) + '\',\'' + charmap[i][3] + '\');" href="javascript:insertChar(\'' + charmap[i][1].substring(2,charmap[i][1].length-1) + '\');" onclick="return false;" onmousedown="return false;" title="' + charmap[i][3] + '">' + charmap[i][1] + '</a></td>'; if ((cols+1) % charsPerRow == 0) html += '</tr><tr height="' + tdHeight + '">'; } } if (cols % charsPerRow > 0) { var padd = charsPerRow - (cols % charsPerRow); for (var i=0; i<padd-1; i++) html += '<td width="' + tdWidth + '" height="' + tdHeight + '" class="charmap">&nbsp;</td>'; } html += '</tr></table>'; document.write(html); } function insertChar(chr) { tinyMCEPopup.execCommand('mceInsertContent', false, '&#' + chr + ';'); // Refocus in window if (tinyMCEPopup.isWindow) window.focus(); tinyMCEPopup.close(); } function previewChar(codeA, codeB, codeN) { var elmA = document.getElementById('codeA'); var elmB = document.getElementById('codeB'); var elmV = document.getElementById('codeV'); var elmN = document.getElementById('codeN'); if (codeA=='#160;') { elmV.innerHTML = '__'; } else { elmV.innerHTML = '&' + codeA; } elmB.innerHTML = '&amp;' + codeA; elmA.innerHTML = '&amp;' + codeB; elmN.innerHTML = codeN; }
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/jscripts/charmap.js
charmap.js
function init() { if (tinyMCE.isMSIE) tinyMCEPopup.resizeToInnerSize(); } function selectColor() { var color = document.getElementById("selectedColorBox").value; tinyMCEPopup.execCommand(tinyMCE.getWindowArg('command'), false, color); tinyMCEPopup.close(); } function showColor(color) { document.getElementById("selectedColor").style.backgroundColor = color; document.getElementById("selectedColorBox").value = color; } var colors = new Array( "#000000","#000033","#000066","#000099","#0000cc","#0000ff","#330000","#330033", "#330066","#330099","#3300cc","#3300ff","#660000","#660033","#660066","#660099", "#6600cc","#6600ff","#990000","#990033","#990066","#990099","#9900cc","#9900ff", "#cc0000","#cc0033","#cc0066","#cc0099","#cc00cc","#cc00ff","#ff0000","#ff0033", "#ff0066","#ff0099","#ff00cc","#ff00ff","#003300","#003333","#003366","#003399", "#0033cc","#0033ff","#333300","#333333","#333366","#333399","#3333cc","#3333ff", "#663300","#663333","#663366","#663399","#6633cc","#6633ff","#993300","#993333", "#993366","#993399","#9933cc","#9933ff","#cc3300","#cc3333","#cc3366","#cc3399", "#cc33cc","#cc33ff","#ff3300","#ff3333","#ff3366","#ff3399","#ff33cc","#ff33ff", "#006600","#006633","#006666","#006699","#0066cc","#0066ff","#336600","#336633", "#336666","#336699","#3366cc","#3366ff","#666600","#666633","#666666","#666699", "#6666cc","#6666ff","#996600","#996633","#996666","#996699","#9966cc","#9966ff", "#cc6600","#cc6633","#cc6666","#cc6699","#cc66cc","#cc66ff","#ff6600","#ff6633", "#ff6666","#ff6699","#ff66cc","#ff66ff","#009900","#009933","#009966","#009999", "#0099cc","#0099ff","#339900","#339933","#339966","#339999","#3399cc","#3399ff", "#669900","#669933","#669966","#669999","#6699cc","#6699ff","#999900","#999933", "#999966","#999999","#9999cc","#9999ff","#cc9900","#cc9933","#cc9966","#cc9999", "#cc99cc","#cc99ff","#ff9900","#ff9933","#ff9966","#ff9999","#ff99cc","#ff99ff", "#00cc00","#00cc33","#00cc66","#00cc99","#00cccc","#00ccff","#33cc00","#33cc33", "#33cc66","#33cc99","#33cccc","#33ccff","#66cc00","#66cc33","#66cc66","#66cc99", "#66cccc","#66ccff","#99cc00","#99cc33","#99cc66","#99cc99","#99cccc","#99ccff", "#cccc00","#cccc33","#cccc66","#cccc99","#cccccc","#ccccff","#ffcc00","#ffcc33", "#ffcc66","#ffcc99","#ffcccc","#ffccff","#00ff00","#00ff33","#00ff66","#00ff99", "#00ffcc","#00ffff","#33ff00","#33ff33","#33ff66","#33ff99","#33ffcc","#33ffff", "#66ff00","#66ff33","#66ff66","#66ff99","#66ffcc","#66ffff","#99ff00","#99ff33", "#99ff66","#99ff99","#99ffcc","#99ffff","#ccff00","#ccff33","#ccff66","#ccff99", "#ccffcc","#ccffff","#ffff00","#ffff33","#ffff66","#ffff99","#ffffcc","#ffffff" ); function convertRGBToHex(col) { var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi"); var rgb = col.replace(re, "$1,$2,$3").split(','); if (rgb.length == 3) { r = parseInt(rgb[0]).toString(16); g = parseInt(rgb[1]).toString(16); b = parseInt(rgb[2]).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; return "#" + r + g + b; } return col; } function convertHexToRGB(col) { if (col.indexOf('#') != -1) { col = col.replace(new RegExp('[^0-9A-F]', 'gi'), ''); r = parseInt(col.substring(0, 2), 16); g = parseInt(col.substring(2, 4), 16); b = parseInt(col.substring(4, 6), 16); return "rgb(" + r + "," + g + "," + b + ")"; } return col; } function renderColorMap() { var html = ""; var inputColor = convertRGBToHex(tinyMCE.getWindowArg('input_color')); html += '<table border="0" cellspacing="1" cellpadding="0">' + '<tr>'; for (var i=0; i<colors.length; i++) { html += '<td bgcolor="' + colors[i] + '">' + '<a href="javascript:selectColor();" onfocus="showColor(\'' + colors[i] + '\');" onmouseover="showColor(\'' + colors[i] + '\');">' + '<img border="0" src="images/spacer.gif" width="10" height="10" title="' + colors[i] + '" alt="' + colors[i] + '" /></a></td>'; if ((i+1) % 18 == 0) html += '</tr><tr>'; } html += '<tr><td colspan="18">' + '<table width="100%" border="0" cellspacing="0" cellpadding="0">' + '<tr><td>' + '<img id="selectedColor" style="background-color:' + tinyMCE.getWindowArg('input_color') + '" border="0" src="images/spacer.gif" width="80" height="16" />' + '</td><td align="right">' + '<input id="selectedColorBox" name="selectedColorBox" type="text" size="7" maxlength="7" style="width:65px" value="' + inputColor + '" />' + '</td></tr>' + '</table>' + '<div style="float: left"><input type="button" id="insert" name="insert" value="{$lang_theme_colorpicker_apply}" style="margin-top:3px" onclick="selectColor();"></div>' + '<div style="float: right"><input type="button" name="cancel" value="{$lang_cancel}" style="margin-top:3px" onclick="tinyMCEPopup.close();" id="cancel" /></div>' + '</td></tr>' + '</table>'; document.write(html); }
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/jscripts/color_picker.js
color_picker.js
var url = tinyMCE.getParam("external_image_list_url"); if (url != null) { // Fix relative if (url.charAt(0) != '/' && url.indexOf('://') == -1) url = tinyMCE.documentBasePath + "/" + url; document.write('<sc'+'ript language="javascript" type="text/javascript" src="' + url + '"></sc'+'ript>'); } function insertImage() { var src = document.forms[0].src.value; var alt = document.forms[0].alt.value; var border = document.forms[0].border.value; var vspace = document.forms[0].vspace.value; var hspace = document.forms[0].hspace.value; var width = document.forms[0].width.value; var height = document.forms[0].height.value; var align = document.forms[0].align.options[document.forms[0].align.selectedIndex].value; tinyMCEPopup.restoreSelection(); tinyMCE.themes['advanced']._insertImage(src, alt, border, hspace, vspace, width, height, align); tinyMCEPopup.close(); } function init() { tinyMCEPopup.resizeToInnerSize(); document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image'); var formObj = document.forms[0]; for (var i=0; i<document.forms[0].align.options.length; i++) { if (document.forms[0].align.options[i].value == tinyMCE.getWindowArg('align')) document.forms[0].align.options.selectedIndex = i; } formObj.src.value = tinyMCE.getWindowArg('src'); formObj.alt.value = tinyMCE.getWindowArg('alt'); formObj.border.value = tinyMCE.getWindowArg('border'); formObj.vspace.value = tinyMCE.getWindowArg('vspace'); formObj.hspace.value = tinyMCE.getWindowArg('hspace'); formObj.width.value = tinyMCE.getWindowArg('width'); formObj.height.value = tinyMCE.getWindowArg('height'); formObj.insert.value = tinyMCE.getLang('lang_' + tinyMCE.getWindowArg('action'), 'Insert', true); // Handle file browser if (isVisible('srcbrowser')) document.getElementById('src').style.width = '180px'; // Auto select image in list if (typeof(tinyMCEImageList) != "undefined" && tinyMCEImageList.length > 0) { for (var i=0; i<formObj.image_list.length; i++) { if (formObj.image_list.options[i].value == tinyMCE.getWindowArg('src')) formObj.image_list.options[i].selected = true; } } } var preloadImg = new Image(); function resetImageData() { var formObj = document.forms[0]; formObj.width.value = formObj.height.value = ""; } function updateImageData() { var formObj = document.forms[0]; if (formObj.width.value == "") formObj.width.value = preloadImg.width; if (formObj.height.value == "") formObj.height.value = preloadImg.height; } function getImageData() { preloadImg = new Image(); tinyMCE.addEvent(preloadImg, "load", updateImageData); tinyMCE.addEvent(preloadImg, "error", function () {var formObj = document.forms[0];formObj.width.value = formObj.height.value = "";}); preloadImg.src = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], document.forms[0].src.value); }
z3c.widget
/z3c.widget-0.3.0.tar.gz/z3c.widget-0.3.0/src/z3c/widget/tiny/tiny_mce/themes/advanced/jscripts/image.js
image.js
=================== FLASH UPLOAD WIDGET =================== the flashupload vars page configures the flash frontend >>> from z3c.widgets.flashupload import upload >>> from zope.testing.doctestunit import DocTestSuite >>> from zope.publisher.browser import TestRequest >>> from zope.app.pagetemplate import ViewPageTemplateFile >>> from zope.app.pagetemplate.simpleviewclass import SimpleViewClass >>> request = TestRequest() >>> context = object() >>> viewClass = SimpleViewClass( ... 'flashuploadvars.pt', bases=(upload.FlashUploadVars,)) >>> view = viewClass(context, request) >>> print view() <?xml version="1.0" ?> <var> <var name="file_progress">File Progress</var> <var name="overall_progress">Overall Progress</var> <var name="error">Error on uploading files</var> <var name="uploadcomplete">all files uploaded</var> <var name="uploadpartial">files uploaded</var> <var name="notuploaded">files were not uploaded because they're too big</var> <var name="maxfilesize">maximum file size is</var> </var> >>> view.allowedFileTypes = ('.jpg', '.gif') >>> print view() <?xml version="1.0" ?> <var> ... <var name="allowedFileType">.jpg</var> <var name="allowedFileType">.gif</var> </var>
z3c.widgets.flashupload
/z3c.widgets.flashupload-1.0c1.zip/z3c.widgets.flashupload-1.0c1/src/z3c/widgets/flashupload/README.txt
README.txt
from zope.app.container.interfaces import INameChooser from ticket import validateTicket, invalidateTicket from zope.security.interfaces import Unauthorized from zope.publisher.browser import BrowserView from zope import interface from zope.traversing.browser.absoluteurl import absoluteURL from zope.security.proxy import removeSecurityProxy from zope.filerepresentation.interfaces import IFileFactory from zope.app.pagetemplate import ViewPageTemplateFile from zope.app.container.constraints import checkObject from zope import event from zope.app.component.interfaces import ISite from z3c.widgets.flashupload.interfaces import (IFlashUploadForm, IUploadFileView, FlashUploadedEvent) try: from zc import resourcelibrary haveResourceLibrary = True except ImportError: haveResourceLibrary = False class FlashUploadVars(BrowserView): """simple view for the flashupload.pt to configure the flash upload swf""" allowedFileTypes = () # empty tuple for all file types class UploadFile(object): """handles file upload for the flash client. flash client sends the data via post as u'Filedata' the filename gets sent as: u'Filename' """ interface.implements(IUploadFileView) def __call__(self): ticket = self.request.form.get('ticket',None) url = None if ticket is None: # we cannot set post headers in flash, so get the # querystring manually qs = self.request.get('QUERY_STRING','ticket=') ticket = qs.split('=')[-1] or None if ticket is None: raise Unauthorized else: url = absoluteURL(self,self.request) if not validateTicket(url,ticket): raise Unauthorized invalidateTicket(url,ticket) if self.request.form.get('Filedata', None) is None: # flash sends a emtpy form in a pre request in flash version 8.0 return "" fileUpload = self.request.form['Filedata'] fileName = self.request.form['Filename'] contentType = self.request.form.get('Content-Type',None) factory = IFileFactory(self.context) f = factory(fileName, contentType, fileUpload) # get the namechooser for the container by adapting the # container to INameChooser nameChooser = INameChooser(self.context) # namechooser selects a name for us name = nameChooser.chooseName(fileName, f) # check precondition checkObject(self.context, name, f) # store the file inside the container removeSecurityProxy(self.context)[name]=f event.notify(FlashUploadedEvent(f)) return "filename=%s" %name class UploadForm(BrowserView): """displays the swf for uploading files """ template = ViewPageTemplateFile('uploadform.pt') interface.implements(IFlashUploadForm) @property def configUrl(self): return '%s/@@flashuploadvars.xml' % self.siteUrl @property def siteUrl(self): return absoluteURL(ISite(None), self.request) def __call__(self, *args, **kw): if haveResourceLibrary: resourcelibrary.need('z3c.widgets.flashupload') return self.template(*args, **kw)
z3c.widgets.flashupload
/z3c.widgets.flashupload-1.0c1.zip/z3c.widgets.flashupload-1.0c1/src/z3c/widgets/flashupload/upload.py
upload.py
if(typeof deconcept=="undefined"){var deconcept=new Object();} if(typeof deconcept.util=="undefined"){deconcept.util=new Object();} if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();} deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){ if(!document.createElement||!document.getElementById){return;} this.DETECT_KEY=_b?_b:"detectflash"; this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY); this.params=new Object(); this.variables=new Object(); this.attributes=new Array(); if(_1){this.setAttribute("swf",_1);} if(id){this.setAttribute("id",id);} if(w){this.setAttribute("width",w);} if(h){this.setAttribute("height",h);} if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));} this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion(this.getAttribute("version"),_7); if(c){this.addParam("bgcolor",c);} var q=_8?_8:"high"; this.addParam("quality",q); this.setAttribute("useExpressInstall",_7); this.setAttribute("doExpressInstall",false); var _d=(_9)?_9:window.location; this.setAttribute("xiRedirectUrl",_d); this.setAttribute("redirectUrl",""); if(_a){this.setAttribute("redirectUrl",_a);}}; deconcept.SWFObject.prototype={setAttribute:function(_e,_f){ this.attributes[_e]=_f; },getAttribute:function(_10){ return this.attributes[_10]; },addParam:function(_11,_12){ this.params[_11]=_12; },getParams:function(){ return this.params; },addVariable:function(_13,_14){ this.variables[_13]=_14; },getVariable:function(_15){ return this.variables[_15]; },getVariables:function(){ return this.variables; },getVariablePairs:function(){ var _16=new Array(); var key; var _18=this.getVariables(); for(key in _18){ _16.push(key+"="+_18[key]);} return _16; },getSWFHTML:function(){ var _19=""; if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){ if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");} _19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\""; _19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" "; var _1a=this.getParams(); for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";} var _1c=this.getVariablePairs().join("&"); if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";} _19+="/>"; }else{ if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");} _19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">"; _19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />"; var _1d=this.getParams(); for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";} var _1f=this.getVariablePairs().join("&"); if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";} _19+="</object>";} return _19; },write:function(_20){ if(this.getAttribute("useExpressInstall")){ var _21=new deconcept.PlayerVersion([6,0,65]); if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){ this.setAttribute("doExpressInstall",true); this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl"))); document.title=document.title.slice(0,47)+" - Flash Player Installation"; this.addVariable("MMdoctitle",document.title);}} if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){ var n=(typeof _20=="string")?document.getElementById(_20):_20; n.innerHTML=this.getSWFHTML(); return true; }else{ if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}} return false;}}; deconcept.SWFObjectUtil.getPlayerVersion=function(_23,_24){ var _25=new deconcept.PlayerVersion([0,0,0]); if(navigator.plugins&&navigator.mimeTypes.length){ var x=navigator.plugins["Shockwave Flash"]; if(x&&x.description){_25=new deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));} }else{try{ var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); for(var i=15;i>6;i--){ try{ axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i); _25=new deconcept.PlayerVersion([i,0,0]); break;} catch(e){}}} catch(e){} if(_23&&_25.major>_23.major){return _25;} if(!_23||((_23.minor!=0||_23.rev!=0)&&_25.major==_23.major)||_25.major!=6||_24){ try{_25=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));} catch(e){}}} return _25;}; deconcept.PlayerVersion=function(_29){ this.major=parseInt(_29[0])!=null?parseInt(_29[0]):0; this.minor=parseInt(_29[1])||0; this.rev=parseInt(_29[2])||0;}; deconcept.PlayerVersion.prototype.versionIsValid=function(fv){ if(this.major<fv.major){return false;} if(this.major>fv.major){return true;} if(this.minor<fv.minor){return false;} if(this.minor>fv.minor){return true;} if(this.rev<fv.rev){return false;}return true;}; deconcept.util={getRequestParameter:function(_2b){ var q=document.location.search||document.location.hash; if(q){ var _2d=q.indexOf(_2b+"="); var _2e=(q.indexOf("&",_2d)>-1)?q.indexOf("&",_2d):q.length; if(q.length>1&&_2d>-1){ return q.substring(q.indexOf("=",_2d)+1,_2e); }}return "";}}; if(Array.prototype.push==null){ Array.prototype.push=function(_2f){ this[this.length]=_2f; return this.length;};} var getQueryParamValue=deconcept.util.getRequestParameter; var FlashObject=deconcept.SWFObject; // for backwards compatibility var SWFObject=deconcept.SWFObject;
z3c.widgets.flashupload
/z3c.widgets.flashupload-1.0c1.zip/z3c.widgets.flashupload-1.0c1/src/z3c/widgets/flashupload/resources/swfobject.js
swfobject.js
function z3cFlashUploadStartBrowsing(){ // tells flash to start with browsing if(window.fuploader){ window.document["fuploader"].SetVariable("startBrowse", "go"); }else if(document.fuploader){ document.fuploader.SetVariable("startBrowse", "go"); } } function z3cFlashUploadEnableBrowseButton(){ document.getElementById("flash.start.browsing").style.visibility = "visible"; document.getElementById("flash.start.browsing").disabled = false; } function z3cFlashUploadDisableBrowseButton(){ document.getElementById("flash.start.browsing").style.visibility = "hidden"; document.getElementById("flash.start.browsing").disabled = "disabled"; } function z3cFlashUploadOnUploadCompleteFEvent(status){ // always fired from flash if (typeof(z3cFlashUploadOnUploadComplete) == "function"){ z3cFlashUploadOnUploadComplete(status); } } function z3cFlashUploadOnFileCompleteFEvent(filename){ // always fired from flash if (typeof(z3cFlashUploadOnFileComplete) =="function"){ z3cFlashUploadOnFileComplete(filename); } } /** called when the user presses the cancel button while browsing */ function z3cFlashUploadOnCancelFEvent(){ if (typeof(z3cFlashUploadOnCancelEvent) =="function"){ z3cFlashUploadOnCancelEvent(); } } /** called if an error occured during the upload progress */ function z3cFlashUploadOnErrorFEvent(error_str){ if (typeof(z3cFlashUploadOnErrorEvent) =="function"){ z3cFlashUploadOnErrorEvent(error_str); } } function prepareUrlForFlash(url){ return escape(url).split("+").join("%2B"); } /** creates a instance of the multifile upload widget insidde the target div. Required global variable: swf_upload_target_path */ function createFlashUpload() { var so = new SWFObject(swf_upload_url, "fuploader", "100%", "100%", "8.0.33", "#f8f8f8"); so.addParam("allowScriptAccess", "sameDomain"); so.addParam("wmode", "transparent"); // we need to manually quote the "+" signs to make sure they do not // result in a " " sign inside flash so.addVariable("target_path", swf_upload_target_path); so.addVariable("site_path", prepareUrlForFlash(swf_upload_site_url)); so.addVariable("config_path", prepareUrlForFlash(swf_upload_config_url)); var success = so.write("flashuploadtarget"); if (!success){ $("#flashuploadtarget").load("noflashupload.html") } } if (window.addEventListener){ window.addEventListener('load', createFlashUpload, false); } else if(window.attachEvent){ window.attachEvent('onload', createFlashUpload); }
z3c.widgets.flashupload
/z3c.widgets.flashupload-1.0c1.zip/z3c.widgets.flashupload-1.0c1/src/z3c/widgets/flashupload/resources/upload.js
upload.js
.. contents:: Introduction ============ z3c.winpdb is a trivial package that calls rpbd2.start_embedded_debugger when IDatabaseOpenedWithRootEvent is fired during the startup of the Zope / Plone instance thus making it possible to debug the running instance with winpdb. Two environment variables are evaluated: RPDB2_ENABLE must be set to "true" for start_embedded_debugger to be called. You most probably don't want this in a production environment. Default is "false". In RPDB2_PASSWD you can set the password needed to attach winpdb to the embedded debugger. Default is "passwd". Note ==== You can't use z3c.winpdb and use python profiling concurrently, as this causes an infinite recursion in rpdb2's CDebuggerCoreThread.profile_recursion method. So if you use z3c.winpdb make sure to remove any publisher-profile-file directive from zope.conf file.
z3c.winpdb
/z3c.winpdb-0.1.4.tar.gz/z3c.winpdb-0.1.4/README.txt
README.txt
====== Wizard ====== The goal of this package is to offer a form wizard. This implementation doesn't use a session. It just offers the wizard logic, the data which the wizard will change or add is not a part of this implementation. If you like to implement some additional wizard logic you probably need to use a session and collect the values in the different wizard steps and create and add an object in the wizard's ``doComplete`` or ``doFinish`` or the step's ``doComplete`` method. All steps are available by their own url. This allows us to cache each step if needed. Each step url is only available if we are allowed to access a step. If a step is accessible depends on the conditions of each step. Since steps are adapters, we can register steps for already existing wizards or we can also override existing steps by registering a UnavailableStep step which always will return ``False`` for the ``available`` argument. If the wizard is completed we get redirected to the confirmation page. If we access a completed wizard again, we will get redirected to the confirmation page again. Now let's show how this works and setup our tests. Form support ------------ We need to load the formui configuration, which will make sure that all macros get registered correctly: >>> from zope.configuration import xmlconfig >>> import z3c.form >>> import z3c.formui >>> import z3c.macro >>> import z3c.template >>> import zope.browserresource >>> import zope.component >>> import zope.i18n >>> import zope.security >>> import zope.viewlet >>> xmlconfig.XMLConfig('meta.zcml', z3c.form)() >>> xmlconfig.XMLConfig('meta.zcml', z3c.macro)() >>> xmlconfig.XMLConfig('meta.zcml', z3c.template)() >>> xmlconfig.XMLConfig('meta.zcml', zope.browserresource)() >>> xmlconfig.XMLConfig('meta.zcml', zope.component)() >>> xmlconfig.XMLConfig('meta.zcml', zope.i18n)() >>> xmlconfig.XMLConfig('meta.zcml', zope.security)() >>> xmlconfig.XMLConfig('meta.zcml', zope.viewlet)() >>> xmlconfig.XMLConfig('configure.zcml', z3c.form)() >>> xmlconfig.XMLConfig('configure.zcml', z3c.formui)() And load the z3c.wizard macro configuration: >>> import z3c.wizard >>> xmlconfig.XMLConfig('configure.zcml', z3c.wizard)() Sample data setup ----------------- Let's define a sample content class: >>> import zope.interface >>> import zope.schema >>> from zope.location.interfaces import ILocation >>> from zope.schema.fieldproperty import FieldProperty >>> class IPerson(ILocation): ... """Person interface.""" ... ... firstName = zope.schema.TextLine(title=u'First Name') ... lastName = zope.schema.TextLine(title=u'Last Name') ... street = zope.schema.TextLine(title=u'Street') ... city = zope.schema.TextLine(title=u'City') >>> @zope.interface.implementer(IPerson) ... class Person(object): ... """Person content.""" ... ... ... __name__ = __parent__ = None ... ... firstName = FieldProperty(IPerson['firstName']) ... lastName = FieldProperty(IPerson['lastName']) ... street = FieldProperty(IPerson['street']) ... city = FieldProperty(IPerson['city']) Setup a person for our wizard: >>> person = Person() >>> root['person'] = person >>> person.__parent__ = root >>> person.__name__ = u'person' Step ---- Let's define some steps. First use a step which knows how to store the name of a person: >>> from z3c.form import form >>> from z3c.form import field >>> from z3c.wizard import step >>> class PersonStep(step.EditStep): ... label = u'Person' ... fields = field.Fields(IPerson).select('firstName', 'lastName') And another step for collect some address data: >>> class AddressStep(step.EditStep): ... label = u'Address' ... fields = field.Fields(IPerson).select('street', 'city') Wizard ------ Now we can define our ``Wizard`` including our steps. Steps are named adapters. Let's use the global method ``addStep`` for doing the step setup: >>> from z3c.wizard import wizard >>> class IPersonWizard(z3c.wizard.interfaces.IWizard): ... """Person wizard marker.""" >>> @zope.interface.implementer(IPersonWizard) ... class PersonWizard(wizard.Wizard): ... ... label = u'Person Wizard' ... ... def setUpSteps(self): ... return [ ... step.addStep(self, 'person', weight=1), ... step.addStep(self, 'address', weight=2), ... ] As next, we need to register our steps as named ``IStep`` adapters. This can be done by the ``z3c:wizardStep`` directive. Let's define our adapters with the provideAdapter method for now: >>> import zope.interface >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> from zope.publisher.interfaces.browser import IBrowserRequest >>> import z3c.wizard.interfaces >>> zope.component.provideAdapter( ... PersonStep, (None, IBrowserRequest, None), ... z3c.wizard.interfaces.IStep, name='person') >>> zope.component.provideAdapter( ... AddressStep, (None, IBrowserRequest, None), ... z3c.wizard.interfaces.IStep, name='address') We need to support the div form layer for our request. This is needed for the form part we use in our steps. Because our steps are forms: >>> from z3c.formui.interfaces import IDivFormLayer >>> from zope.interface import alsoProvides >>> import zope.publisher.browser >>> import z3c.form.interfaces >>> @zope.interface.implementer(z3c.form.interfaces.IFormLayer) ... class TestRequest(zope.publisher.browser.TestRequest): ... pass >>> request = TestRequest() >>> alsoProvides(request, IDivFormLayer) Now we can use our wizard. Our wizard will allways force to traverse to the current active step. This means the wizard provides a browserDefault which returns the default step instead of rendering the wizard as view. This allows us to use the step as an adapter discriminator for viewlets and other adapters like the menu implementation uses. The wizard acts like a dispatcher to the right step and not as a view itself. >>> personWizard = PersonWizard(person, request) >>> personWizard.__parent__ = person >>> personWizard.__name__ = u'wizard' Now get the default view (step) arguments from the wizard: >>> obj, names = personWizard.browserDefault(request) >>> obj <PersonWizard 'wizard'> >>> names ('person',) Now traverse to the step, update and render it: >>> personStep = obj.publishTraverse(request, names[0]) >>> personStep.update() >>> print(personStep.render()) <div class="wizard"> <div class="header">Person Wizard</div> <div class="wizardMenu"> <span class="selected"> <span>Person</span> </span> <span> <a href="http://127.0.0.1/person/wizard/address">Address</a> </span> </div> <form action="http://127.0.0.1" method="post" enctype="multipart/form-data" class="edit-form" id="form" name="form"> <div class="viewspace"> <div class="label">Person</div> <div class="required-info"> <span class="required">*</span>&ndash; required </div> <div class="step"> <div id="form-widgets-firstName-row" class="row required"> <div class="label"> <label for="form-widgets-firstName"> <span>First Name</span> <span class="required">*</span> </label> </div> <div class="widget"> <input id="form-widgets-firstName" name="form.widgets.firstName" class="text-widget required textline-field" value="" type="text" /> </div> </div> <div id="form-widgets-lastName-row" class="row required"> <div class="label"> <label for="form-widgets-lastName"> <span>Last Name</span> <span class="required">*</span> </label> </div> <div class="widget"> <input id="form-widgets-lastName" name="form.widgets.lastName" class="text-widget required textline-field" value="" type="text" /> </div> </div> </div> <div> <div class="buttons"> <span class="back"> </span> <span class="step"> <input id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" type="submit" /> </span> <span class="forward"> <input id="form-buttons-next" name="form.buttons.next" class="submit-widget button-field" value="Next" type="submit" /> </span> </div> </div> </div> </form> </div> We can't go to the next step if we not complete the first step: >>> request = TestRequest(form={'form.buttons.next': 'Next'}) >>> alsoProvides(request, IDivFormLayer) >>> personWizard = PersonWizard(person, request) >>> personWizard.__parent__ = person >>> personWizard.__name__ = u'wizard' >>> personStep = personWizard.publishTraverse(request, names[0]) >>> personStep.update() >>> print(personStep.render()) <div class="wizard"> ... <div class="summary">There were some errors.</div> ... <div class="error">Required input is missing.</div> ... <div class="error">Required input is missing.</div> ... We can complete this step if we fill in the required values and click next: >>> request = TestRequest(form={'form.widgets.firstName': u'Roger', ... 'form.widgets.lastName': u'Ineichen', ... 'form.buttons.next': 'Next'}) >>> alsoProvides(request, IDivFormLayer) >>> personWizard = PersonWizard(person, request) >>> personWizard.__parent__ = person >>> personWizard.__name__ = u'wizard' >>> personStep = personWizard.publishTraverse(request, names[0]) >>> personStep.update() >>> print(personStep.render()) As you can see the step get processed and the wizard will redirect to the next step using the response redirect concept: >>> personWizard.nextURL 'http://127.0.0.1/person/wizard/address' Let's access the next step using the traverser. This will setup the next step and them. >>> request = TestRequest() >>> alsoProvides(request, IDivFormLayer) >>> personWizard = PersonWizard(person, request) >>> personWizard.__parent__ = person >>> personWizard.__name__ = u'wizard' As you can see we see our next step is the address step: >>> addressStep = personWizard.publishTraverse(request, 'address') >>> addressStep <AddressStep 'address'> Update and render it: >>> addressStep.update() >>> print(addressStep.render()) <div class="wizard"> <div class="header">Person Wizard</div> <div class="wizardMenu"> <span> <a href="http://127.0.0.1/person/wizard/person">Person</a> </span> <span class="selected"> <span>Address</span> </span> </div> <form action="http://127.0.0.1" method="post" enctype="multipart/form-data" class="edit-form" id="form" name="form"> <div class="viewspace"> <div class="label">Address</div> <div class="required-info"> <span class="required">*</span>&ndash; required </div> <div class="step"> <div id="form-widgets-street-row" class="row required"> <div class="label"> <label for="form-widgets-street"> <span>Street</span> <span class="required">*</span> </label> </div> <div class="widget"> <input id="form-widgets-street" name="form.widgets.street" class="text-widget required textline-field" value="" type="text" /> </div> </div> <div id="form-widgets-city-row" class="row required"> <div class="label"> <label for="form-widgets-city"> <span>City</span> <span class="required">*</span> </label> </div> <div class="widget"> <input id="form-widgets-city" name="form.widgets.city" class="text-widget required textline-field" value="" type="text" /> </div> </div> </div> <div> <div class="buttons"> <span class="back"> <input id="form-buttons-back" name="form.buttons.back" class="submit-widget button-field" value="Back" type="submit" /> </span> <span class="step"> <input id="form-buttons-apply" name="form.buttons.apply" class="submit-widget button-field" value="Apply" type="submit" /> </span> <span class="forward"> </span> </div> </div> </div> </form> </div>
z3c.wizard
/z3c.wizard-2.0-py3-none-any.whl/z3c/wizard/README.rst
README.rst
========================= Wizard and Step directive ========================= Show how we can use the ``wizard`` and ``wizardStep`` directives. Register the meta configuration for the directive. >>> import sys >>> from zope.configuration import xmlconfig >>> import z3c.wizard >>> context = xmlconfig.file('meta.zcml', z3c.wizard) We need also a custom wizard class: >>> import z3c.wizard >>> class MyWizard(z3c.wizard.wizard.Wizard): ... """Custom wizard""" Make them available under the fake package `custom`: >>> sys.modules['custom'] = type( ... 'Module', (), ... {'MyWizard': MyWizard})() Register a wizard within the directive with minimal attributes: >>> context = xmlconfig.string(""" ... <configure ... xmlns:z3c="http://namespaces.zope.org/z3c"> ... <z3c:wizard ... name="wizard" ... class="custom.MyWizard" ... permission="zope.Public" ... /> ... </configure> ... """, context) Now define a step, >>> import z3c.wizard >>> class FirstStep(z3c.wizard.step.Step): ... """First step""" register the new step classes in the custom module >>> sys.modules['custom'].FirstStep = FirstStep and use them in the ``wizardStep`` directive: >>> context = xmlconfig.string(""" ... <configure ... xmlns:z3c="http://namespaces.zope.org/z3c"> ... <z3c:wizardStep ... name="first" ... wizard="custom.MyWizard" ... class="custom.FirstStep" ... permission="zope.Public" ... /> ... </configure> ... """, context) Let's get the wizard >>> import zope.component >>> from zope.publisher.browser import TestRequest >>> wizard = zope.component.queryMultiAdapter((object(), TestRequest()), ... name='wizard') and check it: >>> wizard <MyWizard 'wizard'> >>> z3c.wizard.interfaces.IWizard.providedBy(wizard) True Let's get the wizard step >>> import zope.component >>> from zope.publisher.browser import TestRequest >>> firstStep = zope.component.queryMultiAdapter( ... (object(), TestRequest(), wizard), name='first') and check it >>> firstStep <FirstStep 'first'> >>> firstStep.context <object object at ...> >>> firstStep.wizard <MyWizard 'wizard'> >>> z3c.wizard.interfaces.IStep.providedBy(firstStep) True >>> z3c.wizard.interfaces.IWizard.providedBy(firstStep.wizard) True Clean up the custom module: >>> del sys.modules['custom']
z3c.wizard
/z3c.wizard-2.0-py3-none-any.whl/z3c/wizard/zcml.rst
zcml.rst
import zope.component import zope.interface from z3c.form import button from z3c.formui import form from zope.publisher.interfaces import NotFound from zope.traversing.browser import absoluteURL from z3c.wizard import interfaces from z3c.wizard.button import WizardButtonActions def nameStep(step, name): """Give a step a __name__.""" step.__name__ = name return step @zope.interface.implementer(interfaces.IWizard) class Wizard(form.Form): """Wizard form. The wizard is responsible for manage the steps and offers the wizard menu navigation and knows the step order. The wizard can check the conditions given from the steps. The wizard is also responsible for delegate the back, next and complete actions to the steps. This IWizard object is modelled as a Controller known from the MVC (Model, view, controller) patter version 2.0 and the step is implemented as a view. """ buttons = button.Buttons(interfaces.IWizardButtons) # customize this part if needed stepInterface = interfaces.IStep firstStepAsDefault = True adjustStep = True confirmationPageName = None nextURL = None cssActive = 'selected' cssInActive = None # None will skip class attribute in DOM element # for internal use __name__ = None steps = None step = None @property def baseURL(self): return absoluteURL(self, self.request) def setUpSteps(self): """Return a list of steps. This implementation uses IStep adapters. Take a look at the addStep method defined in step.py. This method allows you to setup steps directly in the method and offers an API for customized step setup. """ steps = list(zope.component.getAdapters( (self.context, self.request, self), self.stepInterface)) return [nameStep(step, name) for name, step in steps] def filterSteps(self, steps): """Make sure to only select available steps and we give a name.""" return [step for step in steps if step.available] def orderSteps(self, steps): # order steps by it's weight return sorted(steps, key=lambda step: step.weight) @property def steps(self): steps = self.setUpSteps() steps = self.filterSteps(steps) return self.orderSteps(steps) @property def completed(self): for step in self.steps: if not step.completed: return False return True @property def isFirstStep(self): """See interfaces.IWizard""" return self.step and self.step.__name__ == self.steps[0].__name__ @property def isLastStep(self): """See interfaces.IWizard""" return self.step and self.step.__name__ == self.steps[-1].__name__ @property def showBackButton(self): """Ask the step.""" return self.step and self.step.showBackButton @property def showNextButton(self): """Ask the step.""" return self.step and self.step.showNextButton @property def showCompleteButton(self): """Ask the step.""" return self.step.showCompleteButton @property def previousStepName(self): if self.step is None: return stepNames = [step.__name__ for step in self.steps] idx = stepNames.index(self.step.__name__) if idx == 0: return return stepNames[idx - 1] @property def nextStepName(self): if self.step is None: return stepNames = [step.__name__ for step in self.steps] idx = stepNames.index(self.step.__name__) if idx == len(stepNames) - 1: return return stepNames[idx + 1] @property def stepMenu(self): items = [] append = items.append lenght = len(self.steps) - 1 for idx, step in enumerate(self.steps): firstStep = False lastStep = False if step.visible: isSelected = self.step and self.step.__name__ == step.__name__ cssClass = isSelected and self.cssActive or self.cssInActive if idx == 0: firstStep = True if idx == lenght: lastStep = True append({ 'name': step.__name__, 'title': step.label, 'number': str(idx + 1), 'url': '{}/{}'.format(self.baseURL, step.__name__), 'selected': self.step.__name__ == step.__name__, 'class': cssClass, 'first': firstStep, 'last': lastStep }) return items def getDefaultStep(self): """Can return the first or first not completed step as default.""" # return first step if this option is set if self.firstStepAsDefault: return self.steps[0] # return first not completed step for step in self.steps: if not step.completed: return step # fallback to first step if all steps completed return self.steps[0] def doAdjustStep(self): # Make sure all previous steps got completed. If not, redirect to the # last incomplete step if not self.adjustStep: return False for step in self.steps: if step.__name__ is self.step.__name__: break if not step.completed: # prepare redirect to not completed step and return True self.nextURL = '{}/{}'.format(self.baseURL, step.__name__) return True # or return False return False def updateActions(self): self.actions = WizardButtonActions(self, self.request, self.context) self.actions.update() def update(self): if self.doAdjustStep(): return self.updateActions() def publishTraverse(self, request, name): """Traverse to step by it's name.""" # Remove HTML ending if '.' in name: rawName = name.rsplit('.', 1)[0] else: rawName = name # Find the active step for step in self.steps: if step.__name__ == rawName: self.step = step return self.step raise NotFound(self, name, request) def browserDefault(self, request): """The default step is our browserDefault traversal setp.""" if self.step is None: step = self.getDefaultStep() # always return default step as default view for our wizard return self, (step.__name__,) def goToStep(self, stepName): self.nextURL = '{}/{}'.format(self.baseURL, stepName) def goToBack(self): # redirect to next step if previous get sucessfuly processed self.goToStep(self.previousStepName) def goToNext(self): # redirect to next step if previous get sucessfuly processed self.goToStep(self.nextStepName) def doBack(self, action): if self.step.doBack(action): self.goToBack() def doNext(self, action): if self.step.doNext(action): self.goToNext() def doComplete(self, action): if self.step.doComplete(action): # do finsih after step get completed is completed self.doFinish() def doFinish(self): """Force redirect after doComplete if confirmationPageName is given.""" if self.confirmationPageName is not None: self.nextURL = '{}/{}'.format( absoluteURL(self.context, self.request), self.confirmationPageName) @button.handler(interfaces.IWizardButtons['back']) def handleBack(self, action): self.doBack(action) @button.handler(interfaces.IWizardButtons['next']) def handleNext(self, action): self.doNext(action) @button.handler(interfaces.IWizardButtons['complete']) def handleComplete(self, action): self.doComplete(action) def render(self, *args, **kws): raise NotImplementedError('render is no supported') def __repr__(self): return "<{} '{}'>".format(self.__class__.__name__, self.__name__)
z3c.wizard
/z3c.wizard-2.0-py3-none-any.whl/z3c/wizard/wizard.py
wizard.py
import z3c.pagelet.zcml import zope.component import zope.configuration.fields import zope.interface import zope.schema import zope.security.checker import zope.security.zcml from zope.browserpage.metaconfigure import _handle_allowed_attributes from zope.browserpage.metaconfigure import _handle_allowed_interface from zope.browserpage.metaconfigure import _handle_for from zope.browserpage.metaconfigure import _handle_permission from zope.configuration.exceptions import ConfigurationError from zope.publisher.interfaces.browser import IDefaultBrowserLayer from z3c.wizard import interfaces from z3c.wizard import step from z3c.wizard import wizard class IWizardDirective(z3c.pagelet.zcml.IPageletDirective): """A directive to register a new wizard. The wizard directive also supports an undefined set of keyword arguments that are set as attributes on the wizard after creation. """ class IWizardStepDirective(zope.interface.Interface): """A directive to register a new wizard step. The wizard step directive also supports an undefined set of keyword arguments that are set as attributes on the wizard step after creation. """ name = zope.schema.TextLine( title="The name of the pagelet.", description="The name shows up in URLs/paths. For example 'foo'.", required=True) class_ = zope.configuration.fields.GlobalObject( title="Class", description="A class that provides attributes used by the pagelet.", required=True) permission = zope.security.zcml.Permission( title="Permission", description="The permission needed to use the pagelet.", required=True) for_ = zope.configuration.fields.GlobalObject( title="Context", description="The content interface or class this pagelet is for.", required=False) layer = zope.configuration.fields.GlobalInterface( title="The layer the view is in.", description=""" A skin is composed of layers. It is common to put skin specific views in a layer named after the skin. If the 'layer' attribute is not supplied, it defaults to 'default'.""", required=False) wizard = zope.configuration.fields.GlobalObject( title="Wizard", description="The wizard interface or class this step is for.", required=False) provides = zope.configuration.fields.GlobalInterface( title="The interface this pagelets provides.", description=""" A pagelet can provide an interface. This would be used for views that support other views.""", required=False, default=interfaces.IPagelet) allowed_interface = zope.configuration.fields.Tokens( title="Interface that is also allowed if user has permission.", description=""" By default, 'permission' only applies to viewing the view and any possible sub views. By specifying this attribute, you can make the permission also apply to everything described in the supplied interface. Multiple interfaces can be provided, separated by whitespace.""", required=False, value_type=zope.configuration.fields.GlobalInterface()) allowed_attributes = zope.configuration.fields.Tokens( title="View attributes that are also allowed if the user" " has permission.", description=""" By default, 'permission' only applies to viewing the view and any possible sub views. By specifying 'allowed_attributes', you can make the permission also apply to the extra attributes on the view object.""", required=False, value_type=zope.configuration.fields.PythonIdentifier()) # Arbitrary keys and values are allowed to be passed to the wizard. IWizardDirective.setTaggedValue('keyword_arguments', True) # Arbitrary keys and values are allowed to be passed to the step. IWizardStepDirective.setTaggedValue('keyword_arguments', True) # wizard directive def wizardDirective( _context, class_, name, permission, for_=zope.interface.Interface, layer=IDefaultBrowserLayer, provides=interfaces.IWizard, allowed_interface=None, allowed_attributes=None, **kwargs): # Security map dictionary required = {} # Get the permission; mainly to correctly handle CheckerPublic. permission = _handle_permission(_context, permission) # The class must be specified. if not class_: raise ConfigurationError("Must specify a class.") if not zope.interface.interfaces.IInterface.providedBy(provides): raise ConfigurationError("Provides interface provide IInterface.") ifaces = list(zope.interface.Declaration(provides).flattened()) if interfaces.IWizard not in ifaces: raise ConfigurationError("Provides interface must inherit IWizard.") # Build a new class that we can use different permission settings if we # use the class more then once. cdict = {} cdict['__name__'] = name cdict.update(kwargs) new_class = type(class_.__name__, (class_, wizard.Wizard), cdict) # Set up permission mapping for various accessible attributes _handle_allowed_interface( _context, allowed_interface, permission, required) _handle_allowed_attributes( _context, allowed_attributes, permission, required) _handle_allowed_attributes( _context, kwargs.keys(), permission, required) _handle_allowed_attributes( _context, ('__call__', 'browserDefault', 'update', 'render', 'publishTraverse'), permission, required) # Register the interfaces. _handle_for(_context, for_) # provide the custom provides interface if not allready provided if not provides.implementedBy(new_class): zope.interface.classImplements(new_class, provides) # Create the security checker for the new class zope.security.checker.defineChecker( new_class, zope.security.checker.Checker(required)) # register pagelet _context.action( discriminator=('pagelet', for_, layer, name), callable=zope.component.zcml.handler, args=('registerAdapter', new_class, (for_, layer), provides, name, _context.info),) def wizardStepDirective( _context, class_, name, permission, for_=zope.interface.Interface, layer=IDefaultBrowserLayer, wizard=interfaces.IWizard, provides=interfaces.IStep, allowed_interface=None, allowed_attributes=None, **kwargs): # Security map dictionary required = {} # Get the permission; mainly to correctly handle CheckerPublic. permission = _handle_permission(_context, permission) # The class must be specified. if not class_: raise ConfigurationError("Must specify a class.") if not zope.interface.interfaces.IInterface.providedBy(provides): raise ConfigurationError("Provides interface provide IInterface.") ifaces = list(zope.interface.Declaration(provides).flattened()) if interfaces.IPagelet not in ifaces: raise ConfigurationError("Provides interface must inherit IPagelet.") if not interfaces.IWizard.implementedBy(wizard): raise ConfigurationError("Provides interface must inherit IWizard.") # Build a new class that we can use different permission settings if we # use the class more then once. cdict = {} cdict['__name__'] = name cdict.update(kwargs) new_class = type(class_.__name__, (class_, step.Step), cdict) # Set up permission mapping for various accessible attributes _handle_allowed_interface( _context, allowed_interface, permission, required) _handle_allowed_attributes( _context, allowed_attributes, permission, required) _handle_allowed_attributes( _context, kwargs.keys(), permission, required) _handle_allowed_attributes( _context, ('__call__', 'browserDefault', 'update', 'render', 'publishTraverse'), permission, required) # Register the interfaces. _handle_for(_context, for_) # provide the custom provides interface if not allready provided if not provides.implementedBy(new_class): zope.interface.classImplements(new_class, provides) # Create the security checker for the new class zope.security.checker.defineChecker( new_class, zope.security.checker.Checker(required)) # register pagelet _context.action( discriminator=('pagelet', for_, layer, name), callable=zope.component.zcml.handler, args=('registerAdapter', new_class, (for_, layer, wizard), provides, name, _context.info))
z3c.wizard
/z3c.wizard-2.0-py3-none-any.whl/z3c/wizard/zcml.py
zcml.py
import zope.i18nmessageid import zope.interface import zope.location.interfaces import zope.schema from z3c.form import button from z3c.form import interfaces from z3c.pagelet.interfaces import IPagelet _ = zope.i18nmessageid.MessageFactory('z3c') class IBackButton(interfaces.IButton): """A button that redirects to the previous step.""" class INextButton(interfaces.IButton): """A button that redirects to the next step.""" class IWizardButtons(zope.interface.Interface): """Wizard button interfaces.""" back = button.Button( title=_('Back'), condition=lambda form: form.showBackButton) zope.interface.alsoProvides(back, (IBackButton,)) next = button.Button( title=_('Next'), condition=lambda form: form.showNextButton) zope.interface.alsoProvides(next, (INextButton,)) complete = button.Button( title=_('Complete'), condition=lambda form: form.showCompleteButton) zope.interface.alsoProvides(complete, (INextButton,)) class IStep(interfaces.IForm, IPagelet): """An interface marking a step sub-form.""" available = zope.schema.Bool( title='Available', description='Marker for available step', default=True, required=False) visible = zope.schema.Bool( title='Show step in wizard step menu', description='Show step in wizard step menu', default=True, required=False) showRequired = zope.schema.Bool( title='Show required label', description='Show required label', default=True, required=False) weight = zope.schema.Int( title='Step weight in wizard', description='Step weight in wizard', default=0, required=False) completed = zope.schema.Bool( title='Completed', description='Marker for completed step', default=False, required=False) handleApplyOnBack = zope.schema.Bool( title='Handle apply changes on back', description='Handle apply changes on back will force validation', default=False, required=False) handleApplyOnNext = zope.schema.Bool( title='Handle apply changes on next', description='Handle apply changes on next will force validation', default=True, required=False) handleApplyOnComplete = zope.schema.Bool( title='Handle apply changes on complete', description='Handle apply changes on complete will force validation', default=True, required=False) showSaveButton = zope.schema.Bool( title='Show save button', description='Show save button', default=True, required=False) showBackButton = zope.schema.Bool( title='Show back button', description='Back button condition', default=True, required=False) showNextButton = zope.schema.Bool( title='Show next button', description='Next button condition', default=True, required=False) showCompleteButton = zope.schema.Bool( title='Show complete button', description='Complete button condition', default=True, required=False) def goToStep(stepName): """Redirect to step by name.""" def goToNext(): """Redirect to next step.""" def goToBack(): """Redirect to back step.""" def applyChanges(data): """Generic form save method taken from z3c.form.form.EditForm.""" def doHandleApply(action): """Extract data and calls applyChanges.""" def doBack(action): """Process back action and return True on sucess.""" def doNext(action): """Process next action and return True on sucess.""" def doComplete(action): """Process complete action and return True on sucess.""" def update(): """Update the step.""" def render(): """Render the step content w/o wrapped layout.""" def __call__(): """Compute a response body including the layout""" class IWizard(zope.location.interfaces.ILocation): """An interface marking the controlling wizard form.""" firstStepAsDefault = zope.schema.Bool( title='Show first step as default', description='Show first step or first not completed step as default', default=True, required=True) adjustStep = zope.schema.Bool( title='Adjust step', description='Force fallback (redirect) to last incomplete step', default=True, required=False) confirmationPageName = zope.schema.ASCIILine( title='Confirmation page name', description='The confirmation page name shown after completed', default=None, required=False) cssActive = zope.schema.ASCIILine( title='Active step menu CSS class', description='The active step menu CSS class', default='selected', required=False) cssInActive = zope.schema.ASCIILine( title='In-Active step menu item CSS class', description='The in-active step menu item CSS class', default=None, required=False) stepInterface = zope.interface.Attribute('Step lookup interface.') steps = zope.interface.Attribute( """List of one or more IStep (can be lazy).""") stepMenu = zope.interface.Attribute("""Step menu info.""") step = zope.schema.Object( title='Current step', description='Current step', schema=IStep) completed = zope.schema.Bool( title='Completed', description='Marker for completed step', default=False, required=False) isFirstStep = zope.schema.Bool( title='Is first step', description='Is first step', default=False, required=False) isLastStep = zope.schema.Bool( title='Is last step', description='Is last step', default=False, required=False) previousStepName = zope.schema.TextLine( title='Previous step name', description='Previous step name', default=None, required=False) nextStepName = zope.schema.TextLine( title='Next step name', description='Next step name', default=None, required=False) def doAdjustStep(): """Ensure traversal is only possible up to first not completed step. Trying to traverse to another step redirects to the first incomplete one. """ def getDefaultStep(): """Can return the first or first not completed step as default.""" def updateActions(): """Update wizard actions.""" def publishTraverse(request, name): """Traverse to step by it's name.""" def browserDefault(request): """The default step is our browserDefault traversal setp.""" def goToStep(stepName): """Redirect to the step by name.""" def goToBack(): """Redirect to next step if previous get sucessfuly processed.""" def goToNext(): """Redirect to next step if previous get sucessfuly processed.""" def doBack(action): """Process something if back action get exceuted.""" def doNext(action): """Process something if next action get exceuted.""" def doComplete(action): """Process something if complete action get exceuted.""" def doFinish(): """Process something on complete wizard.""" def update(): """Adjust step and update actions."""
z3c.wizard
/z3c.wizard-2.0-py3-none-any.whl/z3c/wizard/interfaces.py
interfaces.py
import zope.component import zope.event import zope.interface import zope.lifecycleevent from z3c.form import button from z3c.form.interfaces import IDataManager from z3c.formui import form from z3c.wizard import interfaces from z3c.wizard.interfaces import _ def addStep(self, name, label=None, weight=None, available=None, **kws): step = zope.component.getMultiAdapter((self.context, self.request, self), interfaces.IStep, name=name) step.__name__ = name if label is not None: step.label = label if weight is not None: step.weight = weight if available is not None: step.available = available for name, value in kws.items(): setattr(step, name, value) return step @zope.interface.implementer(interfaces.IStep) class Step(form.Form): """Wizard base step implementation. The step offers hooks for action handlers for all wizard actions. The step can also provide own actions and handlers. This actions get rendered as step actions. Between the back an next wizard actions. A step can access the context or any object which you return by the getContent method. See z3c.form for more info about that. If you need a complexer wizard setup, you probably have to use a session and store temporary collected values in the session and store it if the wizard will call doComplete on the last step or in the wizard itself. Such a session is not a part of this implementation. This wizard implementation works on any context like other z3c.form IForm implementations. For more infos see z3c.form which this wizard is based on. """ label = None available = True visible = True weight = 0 showRequired = True handleApplyOnBack = False handleApplyOnNext = True handleApplyOnComplete = True # button condition showSaveButton = True formErrorsMessage = _('There were some errors.') successMessage = _('Data successfully updated.') noChangesMessage = _('No changes were applied.') def __init__(self, context, request, wizard): self.context = context self.request = request self.wizard = self.__parent__ = wizard @property def showBackButton(self): """Back button condition.""" return not self.wizard.isFirstStep @property def showNextButton(self): """Next button condition.""" return not self.wizard.isLastStep @property def showCompleteButton(self): """Complete button condition.""" return self.wizard.isLastStep and self.wizard.completed @property def nextURL(self): """Next step URL known by wizard.""" return self.wizard.nextURL @property def completed(self): """Simple default check for find out if a step is complete. This method will ensure that we store at least all required form values and that this values are valid. You can implement any other or additional condition in your custom step implementation. """ content = self.getContent() for field in self.fields.values(): if not field.field.required: continue dm = zope.component.getMultiAdapter( (content, field.field), IDataManager) if dm.query( field.field.missing_value) is field.field.missing_value: return False return True def goToStep(self, stepName): self.wizard.goToStep(stepName) def goToNext(self): self.wizard.goToNext() def goToBack(self): self.wizard.goToBack() def applyChanges(self, data): """Generic form save method taken from z3c.form.form.EditForm.""" content = self.getContent() changes = form.applyChanges(self, content, data) # ``changes`` is a dictionary; if empty, there were no changes if changes: # Construct change-descriptions for the object-modified event descriptions = [] for interface, names in changes.items(): descriptions.append( zope.lifecycleevent.Attributes(interface, *names)) # Send out a detailed object-modified event zope.event.notify( zope.lifecycleevent.ObjectModifiedEvent( content, *descriptions)) return changes def doHandleApply(self, action): """Extract data and calls applyChanges.""" data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return False changes = self.applyChanges(data) if changes: self.status = self.successMessage else: self.status = self.noChangesMessage return True def doBack(self, action): """Process back action and return True on success.""" if self.handleApplyOnBack: return self.doHandleApply(action) return True def doNext(self, action): """Process next action and return True on success.""" if self.handleApplyOnNext: return self.doHandleApply(action) return True def doComplete(self, action): """Process complete action and return True on success.""" if self.handleApplyOnComplete: return self.doHandleApply(action) return True def update(self): # setup wizard actions self.wizard.update() if self.nextURL is not None: # abort and do redirect in render method return # update and execute step actions super().update() # execute wizard actions self.wizard.actions.execute() def render(self): # render content template if self.nextURL is not None: self.request.response.redirect(self.nextURL) return '' return super().render() def __repr__(self): return "<{} '{}'>".format(self.__class__.__name__, self.__name__) class EditStep(Step): """Step with default save button action.""" @button.buttonAndHandler(_('Apply'), name='apply') def handleApply(self, action): self.doHandleApply(action) class UnavailableStep(Step): """A step that is not available. This class is particularly useful for turning off an adapter step. """ available = False
z3c.wizard
/z3c.wizard-2.0-py3-none-any.whl/z3c/wizard/step.py
step.py
* @fileoverview Cross browser XMLHttpRequest implementation * Make sure the response set the Header to 'no-cache'. * * @author Roger Ineichen dev at projekt01 dot ch * @version Draft, not complete documented */ //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // public API //---------------------------------------------------------------------------- /** * Construct a new XMLHttp. * @class This is the basic XMLHttp class. * @constructor * @param {string} url URL pointing to the server * @return A new XMLHttp */ function XMLHttp(url) { this.url = url; this.method = 'GET'; this.async = false; this.username = null; this.password = null; this.timeout = null; this.argString = ""; this.parameters = new Array(); this.headers = new Array(); this.headers['Content-Type'] = 'application/x-www-form-urlencoded' /* internal status flags */ this.isAborted = false; this.isLoading = false; this.isLoaded = false; this.isInteractive = false; this.isComplete = false; /* event handlers (attached functions get called if readyState reached) */ this.onLoading = null; // if readyState 1 this.onLoaded = null; // if readyState 2 this.onInteractive = null; // if readyState 3 this.onComplete = null; // if readyState 4 this.onError = null; // if readyState 4 and status != 200 this.onTimeout = null; // if timeout reached this.callback = null; // if readyState 4 and status == 200 this.callbackArgs = null; /* response variables */ this.responseText = null; this.responseXML = null; /* setup the xmlhttp request now */ this.xmlhttp = getXmlHttpRequest() } /** * Set the header information for the XMLHttp instance. * @param {array} args of key, value */ XMLHttp.prototype.setHeaders = function(args) { for (var i in args) { this.headers[i] = args[i]; } } /** * Set the arguments for the request or the XMLHttp instance. * @param {array} args of key, value */ XMLHttp.prototype.setArguments = function(args) { for (var i in args) { // set parameter to the xmlhttp instance or to the parameter array if (typeof(this[i])=="undefined") { this.parameters[i] = args[i]; } else { this[i] = args[i]; } } } /** * Process a 'POST' request. * @param {function} callback callback funtion * @param {array} callbackArgs callback arguments */ XMLHttp.prototype.post = function(callback, callbackArgs) { this.method = 'POST'; this.async = false; if (typeof(callback)=="function") { this.callback = callback; this.async = true } if (typeof(callbackArgs)!="undefined") { this.callbackArgs = callbackArgs; } if (this.async) { this.process(); } else { return this.process(); } } /** * Process a 'GET' request. * @param {function} callback callback funtion * @param {array} callbackArgs callback arguments */ XMLHttp.prototype.get = function(callback, callbackArgs) { this.method = 'GET'; this.async = false; if (typeof(callback)=="function") { this.callback = callback; this.async = true } if (typeof(callbackArgs)!="undefined") { this.callbackArgs = callbackArgs; } if (this.async) { this.process(); } else { return this.process(); } } //---------------------------------------------------------------------------- // helper methods (can be used directly if you need enhanced access, but the // method post and get are the prefered methods for processing a request.) //---------------------------------------------------------------------------- /** @private */ XMLHttp.prototype.process = function() { if (!this.xmlhttp) return false; var self = this; this.xmlhttp.onreadystatechange = function() { if (self.xmlhttp == null) { return; } if (self.xmlhttp.readyState == 1) { self._doLoading(self); } if (self.xmlhttp.readyState == 2) { self._doLoaded(self); } if (self.xmlhttp.readyState == 3) { self._doInteractive(self); } if (self.xmlhttp.readyState == 4) { self._doComplete(self); } }; try { var args = null; for ( var i = 0; i < this.parameters.length; i++ ) { if (this.argString.length>0) { this.argString += "&"; } this.argString += encodeURIComponent(i) + "=" + encodeURIComponent(this.parameters[i]); } if (this.method == "GET") { if (this.argString.length>0) { this.url += ((this.url.indexOf("?")>-1)?"&":"?") + this.argString; } this.xmlhttp.open(this.method, this.url, this.async); } if (this.method == "POST") { this.xmlhttp.open(this.method, this.url, this.async, this.username, this.password); args = this.argString; } if (typeof(this.xmlhttp.setRequestHeader)!="undefined" && this.xmlhttp.readyState == 1) { for (var i in this.headers) { this.xmlhttp.setRequestHeader(i, this.headers[i]); } } if (this.timeout > 0) { setTimeout(this._doTimeout, this.timeout); } this.xmlhttp.send(args); } catch(z) { return false; } /* on async call we return false and on sync calls we return the xmlhttp request */ if (this.async) { return false; } else { return this.xmlhttp; } } //---------------------------------------------------------------------------- // helper methods (can be used as a standalone cross browser xmlhttp request) //---------------------------------------------------------------------------- /** * Global helper function for a cross browser XMLHttpRequest object. * @class This is a global helper function for a cross browser XMLHttpRequest object. * @constructor * @return A XMLHttpRequest instance for gecko browsers and a ActiveXObjecct * for ie browsers. Unsuported browsers get null returned. */ getXmlHttpRequest = function() { if (window.XMLHttpRequest) { var req = new XMLHttpRequest(); // some older versions of Moz did not support the readyState property // and the onreadystate event so we patch it! if (req.readyState == null) { req.readyState = 1; req.addEventListener("load", function () { req.readyState = 4; if (typeof req.onreadystatechange == "function") { req.onreadystatechange(); } }, false); } return req; } // see comments about the MSXML2.XMLHTTP order, // http://blogs.msdn.com/b/xmlteam/archive/2006/10/23/ // using-the-right-version-of-msxml-in-internet-explorer.aspx else if (window.ActiveXObject) { var MSXML_XMLHTTP_IDS = new Array( "MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "Microsoft.XMLHTTP"); var success = false; for (var i = 0; i < MSXML_XMLHTTP_IDS.length && !success; i++) { try { return new ActiveXObject(MSXML_XMLHTTP_IDS[i]); success = true; } catch (e) {} } } else { return null; } } //---------------------------------------------------------------------------- // built in helper methods //---------------------------------------------------------------------------- /** @private */ XMLHttp.prototype._doLoading = function(self) { if (self.isLoading) { return; } if (typeof(self.onLoading)=="function") { self.onLoading(self.xmlhttp); } self.isLoading = true; } /** @private */ XMLHttp.prototype._doLoaded = function(self) { if (self.isLoaded) { return; } if (typeof(self.onLoaded)=="function") { self.onLoaded(self.xmlhttp); } self.isLoaded = true; } /** @private */ XMLHttp.prototype._doInteractive = function(self) { if (self.isInteractive) { return; } if (typeof(self.onInteractive)=="function") { self.onInteractive(self.xmlhttp); } self.isInteractive = true; } /** @private */ XMLHttp.prototype._doComplete = function(self) { if (self.isComplete || self.isAborted) { return; } self.isComplete = true; self.status = self.xmlhttp.status; self.statusText = self.xmlhttp.statusText; self.responseText = self.xmlhttp.responseText; self.responseXML = self.xmlhttp.responseXML; if (typeof(self.onComplete)=="function") { self.onComplete(self.xmlhttp); } if (self.xmlhttp.status==200 && typeof(self.callback)=="function") { if (self.callbackArgs) { self.callback(self.xmlhttp, self.callbackArgs); } else { self.callback(self.xmlhttp); } } if (self.xmlhttp.status!=200 && typeof(self.onError)=="function") { self.onError(self.xmlhttp); } if (self.async) { // on async calls, clean up so IE doesn't leak memory delete self.xmlhttp['onreadystatechange']; self.xmlhttp = null; } } /** @private */ XMLHttp.prototype._doTimeout = function(self) { if (self.xmlhttp!=null && !self.isComplete) { self.xmlhttp.abort(); self.isAborted = true; if (typeof(self.onTimeout)=="function") { self.onTimeout(self.xmlhttp); } // Opera won't fire onreadystatechange after abort, but other browsers do. // So we can't rely on the onreadystate function getting called. // Clean up here! delete self.xmlhttp['onreadystatechange']; self.xmlhttp = null; } }
z3c.xmlhttp
/z3c.xmlhttp-0.5.1.zip/z3c.xmlhttp-0.5.1/src/z3c/xmlhttp/js/z3c.xmlhttp-0.5.0.js
z3c.xmlhttp-0.5.0.js
import persistent import transaction from zope.interface import implements from zope.component import queryUtility, getUtility, getUtilitiesFor from zope.schema.fieldproperty import FieldProperty from transaction.interfaces import IDataManager, ISynchronizer from transaction.interfaces import IDataManagerSavepoint import z3c.zalchemy.interfaces import sqlalchemy from sqlalchemy.orm.mapper import global_extensions from sqlalchemy.ext.sessioncontext import SessionContext from sqlalchemy.orm.session import Session class AlchemyEngineUtility(persistent.Persistent): """A utility providing a database engine. """ implements(z3c.zalchemy.interfaces.IAlchemyEngineUtility) def __init__(self, name, dsn, echo=False, encoding='utf-8', convert_unicode=False, **kwargs): self.name = name self.dsn = dsn self.encoding = encoding self.convert_unicode = convert_unicode self.echo = echo self.kw={} self.kw.update(kwargs) def getEngine(self): engine = getattr(self, '_v_engine', None) if engine: return engine # create_engine consumes the keywords, so better to make a copy first kw = {} kw.update(self.kw) # create a new engine and configure it thread-local self._v_engine = sqlalchemy.create_engine( self.dsn, echo=self.echo, encoding=self.encoding, convert_unicode=self.convert_unicode, strategy='threadlocal', **kw) return self._v_engine def _resetEngine(self): engine = getattr(self, '_v_engine', None) if engine is not None: engine.dispose() self._v_engine = None for name in z3c.zalchemy.interfaces.IAlchemyEngineUtility: setattr(AlchemyEngineUtility, name, FieldProperty( z3c.zalchemy.interfaces.IAlchemyEngineUtility[name])) _tableToEngine = {} _classToEngine = {} _tablesToCreate = [] # SQLAlchemy session management through thread-locals and our own data # manager. def createSession(): """Creates a new session that is bound to the default engine utility and hooked up with the Zope transaction machinery. """ util = queryUtility(z3c.zalchemy.interfaces.IAlchemyEngineUtility) if util is None: raise ValueError("No engine utility registered") engine = util.getEngine() session = sqlalchemy.create_session(bind_to=engine) # This session is now only bound to the default engine. We need to bind # the other explicitly bound tables and classes as well. bind_session(session) transaction.get().join(AlchemyDataManager(session)) return session def bind_session(session): """Applies all table and class bindings to the given session.""" for table, engine in _tableToEngine.items(): _assignTable(table, engine, session) for class_, engine in _classToEngine.items(): _assignClass(class_, engine, session) ctx = SessionContext(createSession) global_extensions.append(ctx.mapper_extension) def getSession(): return ctx.current def getEngineForTable(t): name = _tableToEngine[t] util = getUtility(z3c.zalchemy.interfaces.IAlchemyEngineUtility, name=name) return util.getEngine() def inSession(): return True def assignTable(table, engine, immediate=True): """Assign a table to an engine and propagate the binding to the current session. The binding is not applied to the current session if `immediate` is False. """ _tableToEngine[table]=engine if immediate: _assignTable(table, engine) def assignClass(class_, engine, immediate=True): """Assign a class to an engine and propagate the binding to the current session. The binding is not applied to the current session if `immediate` is False. """ _classToEngine[class_]=engine if immediate: _assignClass(class_, engine) def createTable(table, engine): _tablesToCreate.append((table, engine)) _createTables() def _assignTable(table, engine, session=None): t = metadata.getTable(engine, table, True) util = getUtility(z3c.zalchemy.interfaces.IAlchemyEngineUtility, name=engine) if session is None: session = ctx.current session.bind_table(t, util.getEngine()) def _assignClass(class_, engine, session=None): m = sqlalchemy.orm.class_mapper(class_) util = getUtility(z3c.zalchemy.interfaces.IAlchemyEngineUtility, name=engine) if session is None: session = ctx.current session.bind_mapper(m,util.getEngine()) def _createTables(): tables = _tablesToCreate[:] del _tablesToCreate[:] for table, engine in tables: _doCreateTable(table, engine) def _doCreateTable(table, engine): util = getUtility(z3c.zalchemy.interfaces.IAlchemyEngineUtility, name=engine) t = metadata.getTable(engine, table, True) try: util.getEngine().create(t) except: pass def dropTable(table, engine=''): util = getUtility(z3c.zalchemy.interfaces.IAlchemyEngineUtility, name=engine) t = metadata.getTable(engine, table, True) try: util.getEngine().drop(t) except: pass class AlchemyDataManager(object): """Takes care of the transaction process in Zope. """ implements(IDataManager) def __init__(self, session): self.session = session self.transaction = session.create_transaction() def abort(self, trans): self.transaction.rollback() self._cleanup() def tpc_begin(self, trans): pass def commit(self, trans): self._flush_session() def tpc_vote(self, trans): pass def tpc_finish(self, trans): self.transaction.commit() self._cleanup() def tpc_abort(self, trans): self.transaction.rollback() self._cleanup() def sortKey(self): return str(id(self)) def savepoint(self): self._flush_session() return AlchemySavepoint() def _cleanup(self): self.session.clear() del ctx.current def _flush_session(self): try: self.session.flush() except Exception, e: conflict = z3c.zalchemy.interfaces.IConflictError(e, None) if conflict is None: raise raise conflict class AlchemySavepoint(object): """A savepoint for the AlchemyDataManager that only supports optimistic savepoints. """ implements(IDataManagerSavepoint) def rollback(self): raise Exception("Can't roll back zalchemy savepoints.") class MetaManager(object): """A manager for metadata to be able to use the same table name in different databases. """ def __init__(self): self.metadata = {} def getTable(self, engine, table, fallback): md = self.metadata.get(engine) if md and table in md.tables: return md.tables[table] if fallback and engine: md = self.metadata.get('') if md and table in md.tables: return md.tables[table] return None def __call__(self, engine=''): md = self.metadata.get(engine) if md is None: md = self.metadata[engine] = sqlalchemy.MetaData() return md metadata = MetaManager()
z3c.zalchemy
/z3c.zalchemy-0.2.2.tar.gz/z3c.zalchemy-0.2.2/src/z3c/zalchemy/datamanager.py
datamanager.py
from zope import interface from zope import schema from zope.app.container.interfaces import IContainerNamesContainer from zope.app.container.constraints import contains, containers class ISQLAlchemyObject(interface.Interface): """Marker interface for mapped sqlalchemy objects. """ class ISQLAlchemyContainer(IContainerNamesContainer): """A zope container containing sqlalchemy objects. """ className = schema.TextLine( title = u'Class', required = True, ) contains(ISQLAlchemyObject) class ISQLAlchemyObjectContained(interface.Interface): """Limit containment to SQLAlchemy containers """ containers(ISQLAlchemyContainer) class IAlchemyEngineUtility(interface.Interface): dsn = schema.URI( title=u'DSN', required=True, default='sqlite://', ) encoding = schema.BytesLine( title=u'Encoding', required=True, default='utf-8', ) convert_unicode = schema.Bool( title=u'Convert Unicode', required=False, default=False ) echo = schema.Bool( title=u'Echo SQL', required=False, default=False ) class IAlchemy(interface.Interface): def getSession(createTransaction=False): """Get a new session for the current thread. createTransaction : Create a zope transaction if none exists for the current thread. """ def inSession(): """Return True if the thread is in a transaction. """ def assignTable(table, engine): """Assign a table to an engine. The table is immediately assigned to the engine if a session is active for the thread. If no session is active the table is assigned when the next session starts. table : Name of the table. engine : Name of the engine utility. """ def assignClass(class_, engine): """Assign a class to an engine. The class is immediately assigned to the engine if a session is active for the thread. If no session is active the class is assigned when the next session starts. class_ : The class to assign to an engine. The class must have a primary mapper assigned. engine : Name of the engine utility. """ def createTable(table, engine=''): """Automatically create a table in the database. The table is immediately created if a session is active for the thread. If no session is active the table is created when the next session starts. table : Name of the table. engine : Name of the engine utility. """ def dropTable(table, engine=''): """Drop a table. Drops the table immediately without the need of a session. table : Name of the table. engine : Name of the engine utility. """ def getEngineForTable(t): """returns an sqlalchemy engine for the given table name, this is usefull for using the engine to execute literal sql statements """ class IConflictError(interface.Interface): """Two transactions tried to modify the same object at once. Exceptions occuring on commit/flush will be adapted to this interface. Registered adapters must either return an ZODB.POSException.ConflictError or None. A ConflictError will tell the publisher to retry the transaction. """
z3c.zalchemy
/z3c.zalchemy-0.2.2.tar.gz/z3c.zalchemy-0.2.2/src/z3c/zalchemy/interfaces.py
interfaces.py
===================== SQLAlchemy and Zope 3 ===================== "z3c.zalchemy" integrates the object relational mapper SQLAlchemy into Zope 3 as SQLOS integrates sqlobject. zalchemy tries to do its best not to interfere with the standard SQLAlchemy usage. The main part of zalchemy is the integration of the SQLAlchemy transaction into the Zope transaction. This is solved by using a data manager which joins the Zope transaction for every newly created thread. zalchemy uses the two phase commit system from zope. This is how the two phase commit is used in zope. 1. tpc_begin(txn) 2. commit(txn) 3. tpc_vote(txn) 4. tpc_finish(txn) - commit does a session.flush() which actually executes all sql statements. - tpc_finish() does a transaction.commit() in the sqlalchemy transaction - tpc_abort() does a transaction.rollback() in the sqlalchemy transaction If commit fails or another DataManager fails data is not commited to the database. Important ========= Zope uses the transaction module to handle transactions. zalchemy plugs into this mechanism and uses its own data manager to use Zope's transaction module. zalchemy provides the method z3c.zalchemy.getSession to obtain a SQLAlchemy session object. This method makes sure the session is connected to Zope's transactions. Never get a session directly from SQLAlchemy! It is also important to never store an instance of a session. Always directly use z3c.zalchemy.getSession. This is necessary because you never know when a transaction is commited. A commit always invalidates the current session. A new call to getSession makes sure a new session is created. zalchemy Class Implementation ============================= There is no difference between the usage of SQLAlchemy together with Zope. zalchemy provides a transparent way to connect a table to a database (engine). A SQLAlchemy engine is represented as a utility: >>> from z3c.zalchemy.datamanager import AlchemyEngineUtility >>> engineUtility = AlchemyEngineUtility( ... 'database', ... 'sqlite:///%s'%dbFilename, ... echo=False, ... ) We create our table as a normal SQLAlchemy table. The important thing here is, that the metadata from zalchemy must be used. Please note that you need to call z3c.zalchemy.metadata. >>> import sqlalchemy >>> import z3c.zalchemy >>> table3 = sqlalchemy.Table( ... 'table3', ... z3c.zalchemy.metadata(), ... sqlalchemy.Column('id', sqlalchemy.Integer, ... sqlalchemy.Sequence('atable_id'), primary_key=True), ... sqlalchemy.Column('value', sqlalchemy.Integer), ... ) Define a simple class which will be used later to map to a database table. >>> class A(object): ... pass Now we map the table to our class. >>> sqlalchemy.mapper(A, table3) is not None True To let zalchemy do its work we need to register our database utility. >>> from z3c.zalchemy.interfaces import IAlchemyEngineUtility >>> from zope.component import provideUtility >>> provideUtility(engineUtility, IAlchemyEngineUtility) Tables can be created without an open transaction or session. If no session is created then the table creation is deferred to the next call to zalchemy.getSession. >>> z3c.zalchemy.createTable('table3', '') zalchemy automatically coordinates Zope's transaction manager with SQLAlchemy's sessions. All mapped classes are automatically associated with thread-local session, which in turn is automatically connected to a special data manager that coordinates with Zope's transactions. >>> a = A() >>> a.value = 1 Committing a transaction will automatically trigger a flush and clear the session. >>> import transaction >>> transaction.commit() Now let's try to get the object back in a new transaction (we're in a new transaction already because the old transaction was committed): >>> from z3c.zalchemy.datamanager import getSession as session >>> a = session().get(A, 1) >>> a.value 1 >>> transaction.commit() Multiple databases ------------------ The above example assumed that there is only one database. The database engine was registered as an unnamed utility. The unnamed utility is always the default database for new sessions. This automatically assigns every table to the default engine. For multiple databases tables can be assigned to engines. We create a new database engine : >>> engine2Util = AlchemyEngineUtility( ... 'engine2', ... 'sqlite:///%s'%dbFilename2, ... echo=False, ... ) Because there is already a default engine we must provide a name for the new engine. >>> provideUtility(engine2Util, IAlchemyEngineUtility, name='engine2') >>> bTable = sqlalchemy.Table( ... 'bTable', ... z3c.zalchemy.metadata(), ... sqlalchemy.Column('id', sqlalchemy.Integer, ... sqlalchemy.Sequence('btable_id'), primary_key=True), ... sqlalchemy.Column('value', sqlalchemy.String), ... ) >>> class B(object): ... pass >>> B.mapper = sqlalchemy.mapper(B, bTable) Assign bTable to the new engine and create the table. This time we do it inside of a session. >>> z3c.zalchemy.assignTable('bTable', 'engine2') >>> z3c.zalchemy.createTable('bTable', 'engine2') >>> b = B() >>> b.value = 'b1' >>> a = A() >>> a.value = 321 >>> transaction.commit() >>> a = session().get(A, 1) >>> b = session().get(B, 1) >>> str(b.value) 'b1' >>> transaction.commit() It is also possible to assign a class to a database : >>> class Aa(object): ... pass >>> sqlalchemy.mapper(Aa, table3) is not None True Now we can assign the class to the engine : >>> z3c.zalchemy.assignClass(Aa, 'engine2') The problem is now that we do not have the table in 'engine2'. We can use an additional parameter to createTable : >>> z3c.zalchemy.createTable('table3', 'engine2') >>> aa = Aa() >>> aa.value = 100 >>> transaction.commit() Tables With The Same Name In Different Databases ------------------------------------------------ IF we have two databases containing tables with the same name but with a different structure we need to assign a table explicitely to a database. This must be done by requesting metadata for a specific engine. >>> b2Table = sqlalchemy.Table( ... 'bTable', ... z3c.zalchemy.metadata('b2Engine'), ... sqlalchemy.Column('id', sqlalchemy.Integer, ... sqlalchemy.Sequence('btable_id'), primary_key=True), ... sqlalchemy.Column('b2value', sqlalchemy.String), ... ) We can now request the table by providing the engine. >>> z3c.zalchemy.metadata.getTable('b2Engine', 'bTable', True) Table('bTable',... If we have specified a table for the 'default' engine then we can request 'bTable' for 'b2Engine' with a fallback to the default engine. >>> z3c.zalchemy.metadata.getTable('b2Engine', 'table3', True) Table('table3',...
z3c.zalchemy
/z3c.zalchemy-0.2.2.tar.gz/z3c.zalchemy-0.2.2/src/z3c/zalchemy/README.txt
README.txt
from persistent import Persistent from zope.security.proxy import removeSecurityProxy from zope.proxy import ProxyBase, sameProxiedObjects from zope.app.container.contained import Contained from zope.app.container.contained import ContainedProxy from zope.app.container.contained import NameChooser from zope.app.container.interfaces import IContained from zope.location.interfaces import ILocation from zope.exceptions.interfaces import UserError from zope import interface from zope.interface import directlyProvides, directlyProvidedBy from zope.configuration.name import resolve import sqlalchemy import z3c.zalchemy from interfaces import ISQLAlchemyContainer def contained(obj, parent=None, name=None): """An implementation of zope.app.container.contained.contained that doesn't generate events, for internal use. Borrowed from SQLOS. """ if (parent is None): raise TypeError, 'Must provide a parent' if not IContained.providedBy(obj): if ILocation.providedBy(obj): directlyProvides(obj, IContained, directlyProvidedBy(obj)) else: obj = ContainedProxy(obj) oldparent = obj.__parent__ oldname = obj.__name__ if (oldparent is None) or not (oldparent is parent or sameProxiedObjects(oldparent, parent)): obj.__parent__ = parent if oldname != name and name is not None: obj.__name__ = name return obj class SQLAlchemyNameChooser(NameChooser): def checkName(self, name, content): if isinstance(name, str): name = unicode(name) elif not isinstance(name, unicode): raise TypeError("Invalid name type", type(name)) unproxied = removeSecurityProxy(self.context) if not name.startswith(unproxied._class.__name__+'-'): raise UserError("Invalid name for SQLAlchemy object") return True def chooseName(self, name, obj): # flush the object to make sure it contains an id session = z3c.zalchemy.getSession() session.save(obj) session.flush() return self.context._toStringIdentifier(obj) class SQLAlchemyContainer(Persistent, Contained): interface.implements(ISQLAlchemyContainer) _className = '' _class = None def setClassName(self, name): self._className = name self._class=resolve(name) def getClassName(self): return self._className className = property(getClassName, setClassName) def keys(self): for name, obj in self.items(): yield name def values(self): for name, obj in self.items(): yield obj def __iter__(self): return iter(self.keys()) def items(self): session = z3c.zalchemy.getSession() query = session.query(self._class) for obj in query.select(): name = self._toStringIdentifier(obj) yield (name, contained(obj, self, name) ) def __getitem__(self, name): if not isinstance(name, basestring): raise KeyError, "%s is not a string" % name obj = self._fromStringIdentifier(name) if obj is None: raise KeyError(name) return contained(obj, self, name) def get(self, name, default=None): try: return self[name] except KeyError: return default def __contains__(self, name): return self.get(name) is not None def __len__(self): try: session = z3c.zalchemy.getSession() query = session.query(self._class) return query.count() except sqlalchemy.exceptions.SQLError: # we don't want an exception in case of database problems return 0 def __delitem__(self, name): obj = self[name] #TODO: better delete objects using a delete adapter # for dependency handling. session = z3c.zalchemy.getSession() session.delete(obj) def __setitem__(self, name, item): session = z3c.zalchemy.getSession() session.save(item) session.flush() def _toStringIdentifier(self, obj): session = z3c.zalchemy.getSession() mapper = session.mapper(obj.__class__) instance_key = mapper.instance_key(obj) ident = '-'.join(map(str, instance_key[1])) return '%s-%s'%(instance_key[0].__name__, ident) def _fromStringIdentifier(self, name): class_base_name = self._class.__name__ prefix = class_base_name + '-' if not name.startswith(prefix): return None ident = name[len(prefix):] keys = ident.split('-') session = z3c.zalchemy.getSession() return session.query(self._class).get([str(key) for key in keys])
z3c.zalchemy
/z3c.zalchemy-0.2.2.tar.gz/z3c.zalchemy-0.2.2/src/z3c/zalchemy/container.py
container.py
from zope import interface from zope import schema from zope.configuration.fields import GlobalObject class IEngineDirective(interface.Interface): """Define an engine. """ url = schema.URI( title = u'Databse URL', description = u'RFC-1738 compliant URL for the database connection', required = True, ) name = schema.Text( title = u'Engine name', description = u'Empty if this engine is the default engine.', required = False, default = u'', ) echo = schema.Bool( title = u'Echo SQL statements', required = False, default=False ) # Arbitrary keys and values are allowed to be passed to the engine. IEngineDirective.setTaggedValue('keyword_arguments', True) class ITableConnectDirective(interface.Interface): """Connect a table to an engine. This is only neccessary if a table should not be uses in the default database. """ table = schema.TextLine( title = u'Table', description = u'The name of the table to connect an engine to.', required = True, ) engine = schema.TextLine( title = u'Engine', description = u'The name of an engine to connect the table to.', required = True, ) class IClassConnectDirective(interface.Interface): """Connect a class to an engine. This is only neccessary if a class should not be uses in the default database. The class must be mapped to a table. """ class_ = GlobalObject( title = u'Class', description = u'The class to connect an engine to.', required = True, ) engine = schema.TextLine( title = u'Engine', description = u'The name of an engine to connect the table to.', required = True, ) class ICreateTableDirective(interface.Interface): """Create a table if not exist. """ table = schema.TextLine( title = u'Table', description = u'The name of the table.', required = True, ) engine = schema.TextLine( title = u'Engine', description = u""" The name of an engine in which the table should be created. """, required = True, )
z3c.zalchemy
/z3c.zalchemy-0.2.2.tar.gz/z3c.zalchemy-0.2.2/src/z3c/zalchemy/metadirectives.py
metadirectives.py
ZAlchemy demos ============== These demos show how ZAlchemy can be used to create Zope3 web applications that use SQLAlchemy to persist data in an RDBMS. To try a demo, copy the included z3c.zalchemy.demo-configure.zcml file to your etc/package-includes/ directory and uncomment the demos you want to try. Because of incompatibilities between the database schemas, each demo defines a different database connection string, to avoid conflicts. To try any particular demo, add a 'Message Container X' to a folder, where 'X' is the number of the demo. So for example, if you've uncommented demo_3 from z3c.zalchemy.demo-configure.zcml, restarting Zope should show a 'Message Container 3' object that can be added. Inside these message containers 'Message X' objects can be added and edited. Adding a second 'Message Container X' will show the same set of messages, as the container just gets all messages in the database. Demo 1: Subclasses the included SQLAlchemyContainer to create a container that is preconfigured to hold only one class (HelloWordMessage) Demo 2: Creates a container from scratch that is specialized to only hold one class (HelloWorldMessage2). Demo 3: Demonstrates a rudimentary adapter for storing Dublin Core metadata in the RDBMS for HelloWorldMessage3 objects. HelloWorldMessage3 objects have editable title and description fields incorporated into the add and edit forms. The metadata is stored in a second table. Demo 4: Demonstrates a contained HelloWorldMessage4 class that is in itself a container for HelloWorldFragment classes.
z3c.zalchemy
/z3c.zalchemy-0.2.2.tar.gz/z3c.zalchemy-0.2.2/src/z3c/zalchemy/demo/README.txt
README.txt
from datetime import datetime import sqlalchemy import z3c.zalchemy from zope.interface import implements from zope.component import adapts from zope.schema.fieldproperty import FieldProperty from zope.component.factory import Factory from zope.dublincore.interfaces import IZopeDublinCore from interfaces import IHelloWorldMessage3 # Define and create the table for storing dublin core metadata RelationalDCTable = sqlalchemy.Table( 'dublin_core', z3c.zalchemy.metadata('DemoEngine-3'), sqlalchemy.Column('id', sqlalchemy.Integer, sqlalchemy.Sequence('metadata_seq'), primary_key = True), sqlalchemy.Column('title', sqlalchemy.Unicode), sqlalchemy.Column('description', sqlalchemy.Unicode), sqlalchemy.Column('created', sqlalchemy.DateTime), sqlalchemy.Column('modified', sqlalchemy.DateTime) ) z3c.zalchemy.createTable('dublin_core', 'DemoEngine-3') # Define and create the table for storing the message # Note the explicit setting of the FK relationship, and that the # primary key does *not* autoincrement HelloWorldMessageTable3 = sqlalchemy.Table( 'message', z3c.zalchemy.metadata('DemoEngine-3'), sqlalchemy.Column('id', sqlalchemy.Integer, sqlalchemy.ForeignKey(RelationalDCTable.c.id), primary_key = True, autoincrement = False), sqlalchemy.Column('who', sqlalchemy.Unicode), ) z3c.zalchemy.createTable('message', 'DemoEngine-3') # The class defining the object containing the metadata class RelationalDC(object): creators = FieldProperty(IZopeDublinCore['creators']) title = FieldProperty(IZopeDublinCore['title']) description = FieldProperty(IZopeDublinCore['description']) created = FieldProperty(IZopeDublinCore['created']) modified = FieldProperty(IZopeDublinCore['modified']) def __init__(self, title=None, description=None, created=None, modified=None): self.title = title self.description = description if created is None: self.created = datetime.now() else: self.created = created if modified is None: self.modified = datetime.now() else: self.modified = modified # Map the metadata table to the metadata class relationalmapper = sqlalchemy.mapper(RelationalDC, RelationalDCTable) # The class defining the adapter between the message object and the # IZopeDublinCore interface. class RelationalDCAdapter(object): adapts(IHelloWorldMessage3) implements(IZopeDublinCore) # The adapter implementation selects the correct # RelationalDC instance based on the message id. def __init__(self, context): self.context = context self.__parent__ = context session = z3c.zalchemy.getSession() query = session.query(RelationalDC).select_by(id=context.id) self.result = None try: self.result = query[0] except IndexError: pass # faking the creators property for now def getCreators(self): return () def setCreators(self, creators): pass creators = property(getCreators, setCreators, doc="RelationalDC creators") def getTitle(self): return self.result.title def setTitle(self, title): self.result.title = title title = property(getTitle, setTitle, doc="RelationalDC title") def getDescription(self): return self.result.description def setDescription(self, description): self.result.description = description description = property(getDescription, setDescription, doc="RelationalDC description") # The class defining the message object class HelloWorldMessage3(object): implements(IHelloWorldMessage3) who = FieldProperty(IHelloWorldMessage3['who']) # instantiate a RelationalDC object to get an id # (the metadata.id column autoincrements) def __init__(self, title, description, who): self.rdc = RelationalDC(title, description) self.who = who # map the message class to the message table messagemapper = sqlalchemy.mapper(HelloWorldMessage3, HelloWorldMessageTable3) # add an additional property to the message mapper that maps # to the metadata class messagemapper.add_property('rdc', sqlalchemy.relation(RelationalDC, cascade="all")) messageFactory=Factory( HelloWorldMessage3, title=u"Create a new message", description=u"This factory instantiates new messages" )
z3c.zalchemy
/z3c.zalchemy-0.2.2.tar.gz/z3c.zalchemy-0.2.2/src/z3c/zalchemy/demo/demo_3/message.py
message.py
from zope.app.container.contained import Contained from persistent import Persistent from zope.interface import implements import z3c.zalchemy from z3c.zalchemy.container import contained from interfaces import IMessageContainer3 from message import HelloWorldMessage3 # Class for the container for storing RDBMS-persistent HelloWorlMessage objects class MessageContainer3(Persistent, Contained): implements(IMessageContainer3) def keys(self): for name, obj in self.items(): yield name def values(self): for name, obj in self.items(): yield obj def __iter__(self): return iter(self.keys()) def items(self): session = z3c.zalchemy.getSession() query = session.query(HelloWorldMessage3) for obj in query.select(): name = self._toStringIdentifier(obj) yield (name, contained(obj, self, name) ) def __getitem__(self, name): if not isinstance(name, basestring): raise KeyError, "%s is not a string" % name obj = self._fromStringIdentifier(name) if obj is None: raise KeyError(name) return contained(obj, self, name) def get(self, name, default=None): try: return self[name] except KeyError: return default def __contains__(self, name): return self.get(name) is not None def __len__(self): try: session = z3c.zalchemy.getSession() query = session.query(HelloWorldMessage3) return query.count() except sqlalchemy.exceptions.SQLError: # we don't want an exception in case of database problems return 0 def __delitem__(self, name): obj = self[name] #TODO: better delete objects using a delete adapter # for dependency handling. session = z3c.zalchemy.getSession() session.delete(obj) def __setitem__(self, name, item): session = z3c.zalchemy.getSession() session.save(item) session.flush() def _toStringIdentifier(self, obj): session = z3c.zalchemy.getSession() mapper = session.mapper(HelloWorldMessage3) instance_key = mapper.instance_key(obj) ident = '-'.join(map(str, instance_key[1])) return 'HelloWorldMessage3-'+ident def _fromStringIdentifier(self, name): prefix = 'HelloWorldMessage3-' if not name.startswith(prefix): return None ident = name[len(prefix):] session = z3c.zalchemy.getSession() return session.query(HelloWorldMessage3).get(ident)
z3c.zalchemy
/z3c.zalchemy-0.2.2.tar.gz/z3c.zalchemy-0.2.2/src/z3c/zalchemy/demo/demo_3/container.py
container.py
from zope.app.container.contained import Contained from persistent import Persistent from zope.interface import implements import sqlalchemy import z3c.zalchemy from z3c.zalchemy.container import contained from interfaces import IMessageContainer2 from message import HelloWorldMessage2 # class that defines a container for storing RDBMS HelloWorlMessage objects class MessageContainer2(Persistent, Contained): implements(IMessageContainer2) def keys(self): for name, obj in self.items(): yield name def values(self): for name, obj in self.items(): yield obj def __iter__(self): return iter(self.keys()) def items(self): session = z3c.zalchemy.getSession() query = session.query(HelloWorldMessage2) for obj in query.select(): name = self._toStringIdentifier(obj) yield (name, contained(obj, self, name) ) def __getitem__(self, name): if not isinstance(name, basestring): raise KeyError, "%s is not a string" % name obj = self._fromStringIdentifier(name) if obj is None: raise KeyError(name) return contained(obj, self, name) def get(self, name, default=None): try: return self[name] except KeyError: return default def __contains__(self, name): return self.get(name) is not None def __len__(self): try: session = z3c.zalchemy.getSession() query = session.query(HelloWorldMessage2) return query.count() except sqlalchemy.exceptions.SQLError: # we don't want an exception in case of database problems return 0 def __delitem__(self, name): obj = self[name] #TODO: better delete objects using a delete adapter # for dependency handling. session = z3c.zalchemy.getSession() session.delete(obj) def __setitem__(self, name, item): session = z3c.zalchemy.getSession() session.save(item) session.flush() def _toStringIdentifier(self, obj): session = z3c.zalchemy.getSession() mapper = session.mapper(HelloWorldMessage2) instance_key = mapper.instance_key(obj) ident = '-'.join(map(str, instance_key[1])) return 'HelloWorldMessage2-'+ident def _fromStringIdentifier(self, name): prefix = 'HelloWorldMessage2-' if not name.startswith(prefix): return None ident = name[len(prefix):] session = z3c.zalchemy.getSession() return session.query(HelloWorldMessage2).get(ident)
z3c.zalchemy
/z3c.zalchemy-0.2.2.tar.gz/z3c.zalchemy-0.2.2/src/z3c/zalchemy/demo/demo_2/container.py
container.py
from datetime import datetime import sqlalchemy import z3c.zalchemy from z3c.zalchemy.container import contained from zope.app.container.contained import Contained from zope.interface import implements from zope.component import adapts from zope.schema.fieldproperty import FieldProperty from zope.component.factory import Factory from zope.dublincore.interfaces import IZopeDublinCore from interfaces import IHelloWorldMessage4, IHelloWorldFragment RelationalDCTable = sqlalchemy.Table( 'dublin_core', z3c.zalchemy.metadata('DemoEngine-4'), sqlalchemy.Column('id', sqlalchemy.Integer, sqlalchemy.Sequence('metadata_seq'), primary_key = True), sqlalchemy.Column('title', sqlalchemy.Unicode), sqlalchemy.Column('description', sqlalchemy.Unicode), sqlalchemy.Column('created', sqlalchemy.DateTime), sqlalchemy.Column('modified', sqlalchemy.DateTime) ) z3c.zalchemy.createTable('dublin_core', 'DemoEngine-4') HelloWorldMessageTable4 = sqlalchemy.Table( 'message', z3c.zalchemy.metadata('DemoEngine-4'), sqlalchemy.Column('id', sqlalchemy.Integer, sqlalchemy.ForeignKey(RelationalDCTable.c.id), primary_key = True, autoincrement = False), sqlalchemy.Column('who', sqlalchemy.Unicode), ) z3c.zalchemy.createTable('message', 'DemoEngine-4') HelloWorldFragmentTable = sqlalchemy.Table( 'fragment', z3c.zalchemy.metadata('DemoEngine-4'), sqlalchemy.Column('id', sqlalchemy.Integer, primary_key = True), sqlalchemy.Column('message_id', sqlalchemy.Integer, sqlalchemy.ForeignKey(HelloWorldMessageTable4.c.id)), sqlalchemy.Column('what', sqlalchemy.Unicode), ) z3c.zalchemy.createTable('fragment', 'DemoEngine-4') class RelationalDC(object): creators = FieldProperty(IZopeDublinCore['creators']) title = FieldProperty(IZopeDublinCore['title']) description = FieldProperty(IZopeDublinCore['description']) created = FieldProperty(IZopeDublinCore['created']) modified = FieldProperty(IZopeDublinCore['modified']) def __init__(self, title=None, description=None, created=None, modified=None): self.title = title self.description = description if created is None: self.created = datetime.now() else: self.created = created if modified is None: self.modified = datetime.now() else: self.modified = modified relationalmapper = sqlalchemy.mapper(RelationalDC, RelationalDCTable) class RelationalDCAdapter(object): adapts(IHelloWorldMessage4) implements(IZopeDublinCore) def __init__(self, context): self.context = context self.__parent__ = context session = z3c.zalchemy.getSession() query = session.query(RelationalDC).select_by(id=context.id) self.result = None try: self.result = query[0] except IndexError: pass def getCreators(self): return () def setCreators(self, creators): pass creators = property(getCreators, setCreators, doc="RelationalDC creators") def getTitle(self): return self.result.title def setTitle(self, title): self.result.title = title title = property(getTitle, setTitle, doc="RelationalDC title") def getDescription(self): return self.result.description def setDescription(self, description): self.result.description = description description = property(getDescription, setDescription, doc="RelationalDC description") class HelloWorldFragment(Contained): implements(IHelloWorldFragment) what = FieldProperty(IHelloWorldFragment['what']) def __init__(self, what): self.what = what fragmentmapper = sqlalchemy.mapper(HelloWorldFragment, HelloWorldFragmentTable) class HelloWorldMessage4(Contained): implements(IHelloWorldMessage4) who = FieldProperty(IHelloWorldMessage4['who']) def __init__(self, title, description, who): self.rdc = RelationalDC(title, description) self.who = who def keys(self): for name, obj in self.items(): yield name def values(self): for name, obj in self.items(): yield obj def __iter__(self): return iter(self.keys()) def items(self): for obj in self.fragments: name = self._toStringIdentifier(obj) yield (name, contained(obj, self, name) ) def __getitem__(self, name): if not isinstance(name, basestring): raise KeyError, "%s is not a string" % name obj = self._fromStringIdentifier(name) if obj is None: raise KeyError(name) return contained(obj, self, name) def get(self, name, default=None): try: return self[name] except KeyError: return default def __contains__(self, name): return self.get(name) is not None def __len__(self): return len(self.fragments) def __delitem__(self, name): obj = self[name] #TODO: better delete objects using a delete adapter # for dependency handling. session = z3c.zalchemy.getSession() session.delete(obj) def __setitem__(self, name, item): session = z3c.zalchemy.getSession() self.fragments.append(item) session.flush() def _toStringIdentifier(self, obj): session = z3c.zalchemy.getSession() mapper = session.mapper(HelloWorldFragment) instance_key = mapper.instance_key(obj) ident = '-'.join(map(str, instance_key[1])) return 'HelloWorldFragment-'+ident def _fromStringIdentifier(self, name): prefix = 'HelloWorldFragment' + '-' if not name.startswith(prefix): return None ident = name[len(prefix):] session = z3c.zalchemy.getSession() return session.query(HelloWorldFragment).get_by(id=ident) messagemapper = sqlalchemy.mapper(HelloWorldMessage4, HelloWorldMessageTable4) messagemapper.add_property('rdc', sqlalchemy.relation(RelationalDC, cascade="all")) messagemapper.add_property('fragments', sqlalchemy.relation(HelloWorldFragment, cascade="all")) messageFactory=Factory( HelloWorldMessage4, title=u"Create a new message", description=u"This factory instantiates new messages" ) fragmentFactory=Factory( HelloWorldFragment, title=u"Create a new message fragment", description=u"This factory instantiates new message fragments" )
z3c.zalchemy
/z3c.zalchemy-0.2.2.tar.gz/z3c.zalchemy-0.2.2/src/z3c/zalchemy/demo/demo_4/message.py
message.py
from zope.app.container.contained import Contained from persistent import Persistent from zope.interface import implements import z3c.zalchemy from z3c.zalchemy.container import contained from interfaces import IMessageContainer4 from message import HelloWorldMessage4 class MessageContainer4(Persistent, Contained): implements(IMessageContainer4) def keys(self): for name, obj in self.items(): yield name def values(self): for name, obj in self.items(): yield obj def __iter__(self): return iter(self.keys()) def items(self): session = z3c.zalchemy.getSession() query = session.query(HelloWorldMessage4) for obj in query.select(): name = self._toStringIdentifier(obj) yield (name, contained(obj, self, name) ) def __getitem__(self, name): if not isinstance(name, basestring): raise KeyError, "%s is not a string" % name obj = self._fromStringIdentifier(name) if obj is None: raise KeyError(name) return contained(obj, self, name) def get(self, name, default=None): try: return self[name] except KeyError: return default def __contains__(self, name): return self.get(name) is not None def __len__(self): try: session = z3c.zalchemy.getSession() query = session.query(HelloWorldMessage4) return query.count() except sqlalchemy.exceptions.SQLError: # we don't want an exception in case of database problems return 0 def __delitem__(self, name): obj = self[name] #TODO: better delete objects using a delete adapter # for dependency handling. session = z3c.zalchemy.getSession() session.delete(obj) def __setitem__(self, name, item): session = z3c.zalchemy.getSession() session.save(item) session.flush() def _toStringIdentifier(self, obj): session = z3c.zalchemy.getSession() mapper = session.mapper(HelloWorldMessage4) instance_key = mapper.instance_key(obj) ident = '-'.join(map(str, instance_key[1])) return 'HelloWorldMessage4-'+ident def _fromStringIdentifier(self, name): prefix = 'HelloWorldMessage4-' if not name.startswith(prefix): return None ident = name[len(prefix):] session = z3c.zalchemy.getSession() return session.query(HelloWorldMessage4).get(ident)
z3c.zalchemy
/z3c.zalchemy-0.2.2.tar.gz/z3c.zalchemy-0.2.2/src/z3c/zalchemy/demo/demo_4/container.py
container.py
Introduction ============ This package provides means of hooking into the Zope (ZCML) configuration process. Custom ZCML actions ------------------- It is sometimes useful to execute a function during the execution of configuration actions, for example to perform one-off configuration that does not warrant a new directive. The ``<zcml:customAction />`` directive is provided for this purpose. For example, you may want to call a function called ``my.package.finalConfiguration()`` "late" in the configuration action execution cycle. This can be achieved with the following ZCML statements:: <configure xmlns="http://namespaces.zope.org/zope" xmlns:zcml="http://namespaces.zope.org/zcml" i18n_domain="my.package"> <include package="z3c.zcmlhook" file="meta.zcml" /> <zcml:customAction handler="my.package.finalConfiguration" order="9999" /> </configure> The ``handler`` attribute gives the name of a function to execute. The function should take no arguments. The ``order`` attribute is optional, and can be used to influence when in the configuration cycle the function is executed. The default value for this, as for most Zope configuration actions, is ``0``. Overriding custom actions ------------------------- If you want to override the invocation of a custom handler in an ``overrides.zcml``, you need to tell ``zope.configuration`` which handler to override. You can do that by setting the *discriminator* explicitly. A discriminator is used to uniquely identify a configuration action. In the case of the ``<zcml:customAction />`` directive, the discriminator is based on the full dotted name to the function by default. Thus, you could override the function call above like so:: <zcml:customAction handler="my.otherpackage.overrideFinalConfiguration" discriminator="my.package.finalConfiguration" order="9999" /> Using a handler more than once ------------------------------ The ``discriminator`` attribute can also be used to explicitly allow using the same handler more than once. If you wanted to call ``my.package.finalConfiguration`` again, you would normally get a configuration conflict. However, with a (unique) custom discriminator, the second call is allowed:: <zcml:customAction handler="my.package.finalConfiguration" discriminator="my.package.finalConfiguration:early" order="-9999" /> <zcml:customAction handler="my.package.finalConfiguration" discriminator="my.package.finalConfiguration:late" order="9999" /> Here, we are attempting to call our configuration action "very early" as well as "very late" in the configuration process.
z3c.zcmlhook
/z3c.zcmlhook-2.0.tar.gz/z3c.zcmlhook-2.0/README.rst
README.rst
import os, shutil, sys, tempfile, urllib, urllib2, subprocess from optparse import OptionParser if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: quote = str # See zc.buildout.easy_install._has_broken_dash_S for motivation and comments. stdout, stderr = subprocess.Popen( [sys.executable, '-Sc', 'try:\n' ' import ConfigParser\n' 'except ImportError:\n' ' print 1\n' 'else:\n' ' print 0\n'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() has_broken_dash_S = bool(int(stdout.strip())) # In order to be more robust in the face of system Pythons, we want to # run without site-packages loaded. This is somewhat tricky, in # particular because Python 2.6's distutils imports site, so starting # with the -S flag is not sufficient. However, we'll start with that: if not has_broken_dash_S and 'site' in sys.modules: # We will restart with python -S. args = sys.argv[:] args[0:0] = [sys.executable, '-S'] args = map(quote, args) os.execv(sys.executable, args) # Now we are running with -S. We'll get the clean sys.path, import site # because distutils will do it later, and then reset the path and clean # out any namespace packages from site-packages that might have been # loaded by .pth files. clean_path = sys.path[:] import site # imported because of its side effects sys.path[:] = clean_path for k, v in sys.modules.items(): if k in ('setuptools', 'pkg_resources') or ( hasattr(v, '__path__') and len(v.__path__) == 1 and not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))): # This is a namespace package. Remove it. sys.modules.pop(k) is_jython = sys.platform.startswith('java') setuptools_source = 'http://peak.telecommunity.com/dist/ez_setup.py' distribute_source = 'http://python-distribute.org/distribute_setup.py' # parsing arguments def normalize_to_url(option, opt_str, value, parser): if value: if '://' not in value: # It doesn't smell like a URL. value = 'file://%s' % ( urllib.pathname2url( os.path.abspath(os.path.expanduser(value))),) if opt_str == '--download-base' and not value.endswith('/'): # Download base needs a trailing slash to make the world happy. value += '/' else: value = None name = opt_str[2:].replace('-', '_') setattr(parser.values, name, value) usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --setup-source and --download-base to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="use_distribute", default=False, help="Use Distribute rather than Setuptools.") parser.add_option("--setup-source", action="callback", dest="setup_source", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or file location for the setup file. " "If you use Setuptools, this will default to " + setuptools_source + "; if you use Distribute, this " "will default to " + distribute_source + ".")) parser.add_option("--download-base", action="callback", dest="download_base", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or directory for downloading " "zc.buildout and either Setuptools or Distribute. " "Defaults to PyPI.")) parser.add_option("--eggs", help=("Specify a directory for storing eggs. Defaults to " "a temporary directory that is deleted when the " "bootstrap script completes.")) parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() if options.eggs: eggs_dir = os.path.abspath(os.path.expanduser(options.eggs)) else: eggs_dir = tempfile.mkdtemp() if options.setup_source is None: if options.use_distribute: options.setup_source = distribute_source else: options.setup_source = setuptools_source if options.accept_buildout_test_releases: args.insert(0, 'buildout:accept-buildout-test-releases=true') try: import pkg_resources import setuptools # A flag. Sometimes pkg_resources is installed alone. if not hasattr(pkg_resources, '_distribute'): raise ImportError except ImportError: ez_code = urllib2.urlopen( options.setup_source).read().replace('\r\n', '\n') ez = {} exec ez_code in ez setup_args = dict(to_dir=eggs_dir, download_delay=0) if options.download_base: setup_args['download_base'] = options.download_base if options.use_distribute: setup_args['no_fake'] = True if sys.version_info[:2] == (2, 4): setup_args['version'] = '0.6.32' ez['use_setuptools'](**setup_args) if 'pkg_resources' in sys.modules: reload(sys.modules['pkg_resources']) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) cmd = [quote(sys.executable), '-c', quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(eggs_dir)] if not has_broken_dash_S: cmd.insert(1, '-S') find_links = options.download_base if not find_links: find_links = os.environ.get('bootstrap-testing-find-links') if not find_links and options.accept_buildout_test_releases: find_links = 'http://downloads.buildout.org/' if find_links: cmd.extend(['-f', quote(find_links)]) if options.use_distribute: setup_requirement = 'distribute' else: setup_requirement = 'setuptools' ws = pkg_resources.working_set setup_requirement_path = ws.find( pkg_resources.Requirement.parse(setup_requirement)).location env = dict( os.environ, PYTHONPATH=setup_requirement_path) requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setup_requirement_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if distv >= pkg_resources.parse_version('2dev'): continue if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement += '=='+version else: requirement += '<2dev' cmd.append(requirement) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) if exitcode != 0: sys.stdout.flush() sys.stderr.flush() print ("An error occurred when trying to install zc.buildout. " "Look above this message for any errors that " "were output by easy_install.") sys.exit(exitcode) ws.add_entry(eggs_dir) ws.require(requirement) import zc.buildout.buildout # If there isn't already a command in the args, add bootstrap if not [a for a in args if '=' not in a]: args.append('bootstrap') # if -c was provided, we push it back into args for buildout's main function if options.config_file is not None: args[0:0] = ['-c', options.config_file] zc.buildout.buildout.main(args) if not options.eggs: # clean up temporary egg directory shutil.rmtree(eggs_dir)
z3c.zrtresource
/z3c.zrtresource-1.4.0.zip/z3c.zrtresource-1.4.0/bootstrap.py
bootstrap.py
__docformat__='restructuredtext' import zope.interface import zope.schema import zope.component.interfaces class UnknownZRTCommand(ValueError): """An unknown ZRT Command was specified""" class ArgumentError(ValueError): """Error while parsing the command arguments.""" class IZRTProcessor(zope.interface.Interface): """ZRT Processor""" source = zope.schema.Bytes( title=u'Source', description=u'The source of the expression.') def compile(): """Compile the source to binary form.""" def process(context, request): """Process the source with given context and request. Return the result string. """ class IZRTCommand(zope.interface.Interface): """A ZRT command""" isAvailable = zope.schema.Bool( title=u'Is Available', description=u'Tell whether the command is still available.') def process(text, context, request): """Process the given text with given context and request. Return the result string. """ class IZRTCommandFactory(zope.component.interfaces.IFactory): """ factory for IZRTCommand """ class IZRTExpression(zope.interface.Interface): """An expression to be used in a command.""" source = zope.schema.Bytes( title=u'Source', description=u'The source of the expression.') context = zope.schema.Object( title=u'Context', description=u'Context of the template, usually a site.', schema=zope.interface.Interface) request = zope.schema.Object( title=u'Request', description=u'Request of the template, usually a site.', schema=zope.interface.Interface) class IZRTInputExpression(IZRTExpression): def process(text, outputExpr): """Evaluate the expression and update the """ class IZRTOutputExpression(IZRTExpression): def process(**kw): """Process the expression and return the output string. The keyword arguments are additional namespaces. """
z3c.zrtresource
/z3c.zrtresource-1.4.0.zip/z3c.zrtresource-1.4.0/src/z3c/zrtresource/interfaces.py
interfaces.py
=================== Templated Resources =================== One of the design goals of Zope is to allow designers to check in HTML template, CSS and Javascript files, which just work (with some additional information). For HTML code we use Zope's Page Templates to accomplish this objective. For CSS and Javascript we did not need such a feature until now, since those files were largely static or variables could be inserted using other ways at runtime. However, in CSS URLs -- for example for background images -- are now frequently inserted into CSS directives. However, the path layout for the designer might not equal the resource file structure. This package provides a simple mechanism to replace strings by another. To accomplish this, a templated resource is provided. The template syntax is provided in a way that it does not interfere with the syntax of the resource. For both, Javascript and CSS, this is a comment of the form ``/* ... */``. Here is the general syntax:: <COMMAND-BEGIN> <ZRT-COMMAND>: <COMMAND-ARGUMENTS> <COMMAND-END> Here is an example for CSS:: /* zrt-replace: ".." "@@" */ To demonstrate this feature, we first have to create a CSS file. >>> import tempfile >>> fn = tempfile.mktemp('.css') >>> open(fn, 'w').write('''\ ... /* zrt-replace: "../img1" "++resource++/img" */ ... /* zrt-replace: "fontName" "Arial, Tahoma" */ ... h1 { ... color: red; ... font: fontName; ... background: url('../img1/mybackground.gif'); ... } ... ... h2 { ... color: red; ... background: url('../img2/mybackground.gif'); ... } ... /* zrt-replace: "../img2" "++resource++/img" */ ... ''') The global replace command replaces a string with another. It is only active in the lines *after* it was declared. Thus, in this case, the second command is meaningless. Now we create a ZRT resource from the resource factory ... >>> from z3c.zrtresource import ZRTFileResourceFactory >>> cssFactory = ZRTFileResourceFactory(fn, None, 'site.css') >>> from zope.publisher.browser import TestRequest >>> css = cssFactory(TestRequest()) and render the resource: >>> print css.GET() h1 { color: red; font: Arial, Tahoma; background: url('++resource++/img/mybackground.gif'); } <BLANKLINE> h2 { color: red; background: url('../img2/mybackground.gif'); } As you can see only the first URL was replaced, because of the incorrect position of the second statement. And that's all! In your ZCML you can use this factory as follows:: <zrt-resource name="site.css" path="css/site.css" /> Replacing Strings ----------------- The ``zrt-replace`` command replaces any matches with the output string as many times as specified. Here is the syntax: zrt-replace: <EXPR-TYPE>"<INPUT-EXPR>" <EXPR-TYPE>"<OUTPUT-EXPR>" <NUM> As seen in the example above, ``zrt-replace`` calls can be placed anywhere in the file. Let's make sure that some special cases work as well: >>> from z3c.zrtresource import processor, replace >>> def process(text): ... p = processor.ZRTProcessor( ... text, commands={'replace': replace.Replace}) ... return p.process(None, None) >>> print process('''\ ... /* zrt-replace: "foo" "bar" */ ... foo''') bar >>> print process('''\ ... /* zrt-replace: "foo" "bar" */ ... foo''') bar >>> print process('''\ ... /* zrt-replace: "foo" "bar" */ ... foo''') bar But the following does not work: >>> print process('''\ ... /* zrt-replace : "foo" "bar" */ ... foo''') /* zrt-replace : "foo" "bar" */ foo >>> print process('''\ ... /* zrt -replace : "foo" "bar" */ ... foo''') /* zrt -replace : "foo" "bar" */ foo Until now we have only considered multiple replacements. Let's now restrict the number of replacements with the final argument. Initially all occurences of a matching string are replaced: >>> print process('''\ ... /* zrt-replace: "foo" "bar" */ ... foo foo foo foo foo''') bar bar bar bar bar When we specify a number of replacements, then only that amount is replaced: >>> print process('''\ ... /* zrt-replace: "foo" "bar" 1 */ ... foo foo foo foo foo''') bar foo foo foo foo >>> print process('''\ ... /* zrt-replace: "foo" "bar" 3 */ ... foo foo foo foo foo''') bar bar bar foo foo >>> print process('''\ ... /* zrt-replace: "foo" "bar" 6 */ ... foo foo foo foo foo''') bar bar bar bar bar The String Expression ~~~~~~~~~~~~~~~~~~~~~ Until now we have only dealt with simple string replacement, since it is the default expression type. Another way of spelling the expression type is: >>> print process('''\ ... /* zrt-replace: str"foo" "bar" */ ... foo''') bar >>> print process('''\ ... /* zrt-replace: "foo" str"bar" */ ... foo''') bar >>> print process('''\ ... /* zrt-replace: str"foo" str"bar" */ ... foo''') bar The Regex Expression ~~~~~~~~~~~~~~~~~~~~ Regular expressions make only sense as input expressions, so they are only supported there: >>> print process('''\ ... /* zrt-replace: re"foo" "bar" */ ... foo''') bar >>> print process('''\ ... /* zrt-replace: re"[a-z]*foo" "bar" */ ... myfoo''') bar We also support groups: >>> print process('''\ ... /* zrt-replace: re"([a-z]*)foo" "bar" */ ... myfoo''') bar >>> print process('''\ ... /* zrt-replace: re"([a-z]*)foo" "bar" */ ... myfoo''') bar >>> print process('''\ ... /* zrt-replace: re"([a-z]*)foo" "bar" */ ... myfoo mybar''') bar mybar Yes, even group replacement works: >>> print process('''\ ... /* zrt-replace: re"([a-z]*)foo" "bar\\1" */ ... myfoo a9foo''') barmy a9bar >>> print process('''\ ... /* zrt-replace: re"(?P<prefix>[a-z]*)foo" "bar\\g<prefix>" */ ... myfoo a9foo''') barmy a9bar The TALES Expression ~~~~~~~~~~~~~~~~~~~~ What would be a Zope-based templating language without TALES expressions? This is particularly useful, if you want to create absolute URLs and other dynamic bits based on the request and the context: >>> import zope.interface >>> from zope.traversing.interfaces import IContainmentRoot >>> class Root(object): ... zope.interface.implements(IContainmentRoot) >>> from zope.publisher.browser import TestRequest >>> def process(text): ... p = processor.ZRTProcessor( ... text, commands={'replace': replace.Replace}) ... return p.process(Root(), TestRequest()) >>> print process('''\ ... /* zrt-replace: "foo" tal"string:${context/@@absolute_url}/@@/foo" */ ... foo''') http://127.0.0.1/@@/foo Custom ZRT Command ~~~~~~~~~~~~~~~~~~ We can create custom ZRT commands. For this we should register a named IZRTCommandFactory utility >>> import re >>> from zope import interface >>> from zope.component import provideUtility >>> from z3c.zrtresource import interfaces >>> class MyCustomCommand(object): ... interface.implements(interfaces.IZRTCommand) ... ... data = {'color1': 'red', 'color2': 'green'} ... ... isAvailable = True ... ... def __init__(self, args, start, end): ... self.args = args ... self.start = start ... self.end = end ... ... def process(self, text, context, request): ... for key, value in self.data.items(): ... regex = re.compile(re.escape(key)) ... text = regex.subn(value, text)[0] ... ... return text >>> from zope.component.factory import Factory >>> my_command = Factory(MyCustomCommand, 'mycommand') >>> interface.directlyProvides(my_command, interfaces.IZRTCommandFactory) >>> provideUtility(my_command, interfaces.IZRTCommandFactory, name='mycommand') >>> open(fn, 'w').write('''\ ... /* zrt-replace: "../img1" "++resource++/img" */ ... /* zrt-replace: "fontFamily" "Arial, Tahoma" */ ... /* zrt-mycommand: */ ... /* oh, and we're testing that when the file changes, it is reloaded */ ... h1 { ... color: color1; ... font: fontFamily; ... background: url('../img1/mybackground.gif'); ... } ... ... h2 { ... color: color2; ... background: url('../img2/mybackground.gif'); ... } ... /* zrt-replace: "../img2" "++resource++/img" */ ... ''') We have to recreate the ZRTFileResourceFactory to reload the changed file contents (don't worry -- in real life Zope creates these anew for every request, since resources are actually registered as IResourceFactoryFactory utilities). >>> cssFactory = ZRTFileResourceFactory(fn, None, 'site.css') >>> css = cssFactory(TestRequest()) >>> print css.GET() /* oh, and we're testing that when the file changes, it is reloaded */ h1 { color: red; font: Arial, Tahoma; background: url('++resource++/img/mybackground.gif'); } <BLANKLINE> h2 { color: green; background: url('../img2/mybackground.gif'); } <BLANKLINE> Edge case --------- On windows blank lines were left in the result >>> open(fn, 'w').write('''\ ... some-head ... /* zrt-replace: "../img1" "++resource++/img" */ ... /* zrt-replace: "fontName" "Arial, Tahoma" */ ... some-in-the-middle ... /* zrt-replace: "../img2" "++resource++/img" */ ... some-at-the-end ... ''') >>> cssFactory = ZRTFileResourceFactory(fn, None, 'site.css') >>> from zope.publisher.browser import TestRequest >>> css = cssFactory(TestRequest()) and render the resource: >>> css.GET().splitlines() ['some-head', 'some-in-the-middle', 'some-at-the-end']
z3c.zrtresource
/z3c.zrtresource-1.4.0.zip/z3c.zrtresource-1.4.0/src/z3c/zrtresource/README.txt
README.txt
__docformat__='restructuredtext' import re import zope.interface from zope.pagetemplate import engine from z3c.zrtresource import interfaces # <EXPR-TYPE>"<INPUT-EXPR>" <EXPR-TYPE>"<OUTPUT-EXPR>" <NUM> NAME = r'[a-zA-Z0-9_-]*' ARGS_REGEX = re.compile(r' *(%s)"([^"]*)" *(%s)"([^"]*)" *([0-9]*)' %(NAME, NAME)) class BaseExpression(object): def __init__(self, source, context, request): self.source = source self.context = context self.request = request class StringInputExpression(BaseExpression): """A simple string input expression""" zope.interface.implements(interfaces.IZRTInputExpression) def process(self, text, outputExpr, count=None): regex = re.compile(re.escape(self.source)) return regex.subn(outputExpr.process(), text, count or 0) class StringOutputExpression(BaseExpression): """A simple string input expression""" zope.interface.implements(interfaces.IZRTOutputExpression) def process(self, **kw): # Ignore any keyword arguments, since this is static replacement return self.source class RegexInputExpression(BaseExpression): """A regex string input expression""" zope.interface.implements(interfaces.IZRTInputExpression) def process(self, text, outputExpr, count=None): regex = re.compile(self.source) return regex.subn(outputExpr.process(), text, count or 0) class TALESOutputExpression(BaseExpression): """A simple string input expression""" zope.interface.implements(interfaces.IZRTOutputExpression) def process(self, **kw): expr = engine.TrustedEngine.compile(self.source) kw.update({'context': self.context, 'request': self.request}) econtext = engine.TrustedEngine.getContext(kw) return expr(econtext) class Replace(object): """A ZRT Command to replace sub-strings of the text""" zope.interface.implements(interfaces.IZRTCommand) inputExpressions = { '': StringInputExpression, 'str': StringInputExpression, 're': RegexInputExpression, } outputExpressions = { '': StringOutputExpression, 'str': StringOutputExpression, 'tal': TALESOutputExpression, } def __init__(self, args, start, end): self.start = start self.end = end self.processArguments(args) @property def isAvailable(self): return self.num is None or self.num > 0 def processArguments(self, args): match = ARGS_REGEX.match(args) if match is None: raise interfaces.ArgumentError(args) self.itype, self.input, self.otype, self.output, self.num = match.groups() self.num = self.num and int(self.num) or None if self.itype not in self.inputExpressions: raise ValueError(self.itype) if self.otype not in self.outputExpressions: raise ValueError(self.otype) def process(self, text, context, request): iexpr = self.inputExpressions[self.itype]( self.input, context, request) oexpr = self.outputExpressions[self.otype]( self.output, context, request) text, num = iexpr.process(text, oexpr, self.num) if self.num is not None: self.num -= num return text
z3c.zrtresource
/z3c.zrtresource-1.4.0.zip/z3c.zrtresource-1.4.0/src/z3c/zrtresource/replace.py
replace.py
__docformat__='restructuredtext' import re import zope.interface import zope.component from z3c.zrtresource import interfaces # <COMMAND-BEGIN> <ZRT-COMMAND>: <COMMAND-ARGUMENTS> <COMMAND-END> NAME = r'[a-zA-Z0-9_-]*' COMMAND_REGEX = r'%%s(%s):\s*(.*?)\s*%%s' %NAME TEXTBLOCK=0 COMMAND=1 EXTRCOMMAND=2 class ZRTProcessor(object): """A ZRT Processor""" zope.interface.implements(interfaces.IZRTProcessor) commandStartRegex = r'/\*\s*zrt-' commandEndRegex = r'\*/' def __init__(self, source, commands=None): self.source = source if not commands: commands = {} self.commands = commands self._bytecode = None def compile(self): """See interfaces.IZRTProcessor""" bytecode = [] pos = 0 # Regular Expression to find commands. regex = re.compile(COMMAND_REGEX %(self.commandStartRegex, self.commandEndRegex)) nextlinelen = 1 if '\r\n' in self.source: # work around windows: it has a 2 char next line sequence nextlinelen = 2 # Find all commands for match in regex.finditer(self.source): command, args = match.groups() # Add the previous text block and update position bytecode.append((TEXTBLOCK, self.source[pos:match.start()])) pos = match.end() + nextlinelen # Make sure the command exists if command not in self.commands: cmd = zope.component.queryUtility( interfaces.IZRTCommandFactory, command) if cmd is None: raise interfaces.UnknownZRTCommand(command) # Add the command bytecode.append((EXTRCOMMAND, (cmd, args, match.start(), match.end()))) else: # Add the command bytecode.append( (COMMAND, (command, args, match.start(), match.end()))) # Add the final textblock bytecode.append((TEXTBLOCK, self.source[pos:])) self._bytecode = bytecode def process(self, context, request): """See interfaces.IZRTProcessor""" if self._bytecode is None: self.compile() # List active commands active = [] result = [] for type, value in self._bytecode: # If the type is a command, simply add it to the list of commands if type is COMMAND: cmd, args, start, end = value active.append( self.commands[cmd](args, start, end)) # If the type is a external command elif type is EXTRCOMMAND: cmd, args, start, end = value active.append(cmd(args, start, end)) # If we have a textblock, then work on it. elif type is TEXTBLOCK: # Process any command for cmd in active: value = cmd.process(value, context, request) # If the command is no longer available, remove it if not cmd.isAvailable: active.remove(cmd) # This block is fully processed now. result.append(value) else: raise ValueError(type) return ''.join(result)
z3c.zrtresource
/z3c.zrtresource-1.4.0.zip/z3c.zrtresource-1.4.0/src/z3c/zrtresource/processor.py
processor.py
.. This README is meant for consumption by humans and pypi. Pypi can render rst files so please do not use Sphinx features. If you want to learn more about writing documentation, please check out: http://docs.plone.org/about/documentation_styleguide.html This text does not appear on pypi or github. It is a comment. ============================================================================== z3cform.locationwidget ============================================================================== Widget for graphically select location in to a map, and save cordinates into field Based in gmaps.js library Features -------- - Gmaps library - Api Key Google maps definition in control panel - Coordinates default point definition in control panel - You can show de coordinates field via checkbox Usage ----- You need to set the widget to needed fields into your form instance:: from z3cform.locationwidget.field import LocationField from plone.supermodel import model class IMyModel(model.Schema): my_location_field = LocationField( title=_(u'Map Location'), description=_(u'Set the location mark on the map'), required=False, ) Translations ------------ This product has been translated into - Catalan - Spanish - French Installation ------------ Install z3cform.locationwidget by adding it to your buildout:: [buildout] ... eggs = z3cform.locationwidget and then running ``bin/buildout`` Contributors ============ - aormazabal, [email protected] Changelog ========= 1.1.0 (released) ------------------ - Initial release
z3cform.locationwidget
/z3cform.locationwidget-1.1.0-py38-none-any.whl/z3cform.locationwidget-1.1.0.dist-info/DESCRIPTION.rst
DESCRIPTION.rst
"use strict"; (function(root, factory) { if(typeof exports === 'object') { module.exports = factory(); } else if(typeof define === 'function' && define.amd) { define(['jquery'], factory); } else { root.GMaps = factory(); } }(this, function() { /*! * GMaps.js v0.4.22 * http://hpneo.github.com/gmaps/ * * Copyright 2016, Gustavo Leon * Released under the MIT License. */ var extend_object = function(obj, new_obj) { var name; if (obj === new_obj) { return obj; } for (name in new_obj) { if (new_obj[name] !== undefined) { obj[name] = new_obj[name]; } } return obj; }; var replace_object = function(obj, replace) { var name; if (obj === replace) { return obj; } for (name in replace) { if (obj[name] != undefined) { obj[name] = replace[name]; } } return obj; }; var array_map = function(array, callback) { var original_callback_params = Array.prototype.slice.call(arguments, 2), array_return = [], array_length = array.length, i; if (Array.prototype.map && array.map === Array.prototype.map) { array_return = Array.prototype.map.call(array, function(item) { var callback_params = original_callback_params.slice(0); callback_params.splice(0, 0, item); return callback.apply(this, callback_params); }); } else { for (i = 0; i < array_length; i++) { callback_params = original_callback_params; callback_params.splice(0, 0, array[i]); array_return.push(callback.apply(this, callback_params)); } } return array_return; }; var array_flat = function(array) { var new_array = [], i; for (i = 0; i < array.length; i++) { new_array = new_array.concat(array[i]); } return new_array; }; var coordsToLatLngs = function(coords, useGeoJSON) { var first_coord = coords[0], second_coord = coords[1]; if (useGeoJSON) { first_coord = coords[1]; second_coord = coords[0]; } return new google.maps.LatLng(first_coord, second_coord); }; var arrayToLatLng = function(coords, useGeoJSON) { var i; for (i = 0; i < coords.length; i++) { if (!(coords[i] instanceof google.maps.LatLng)) { if (coords[i].length > 0 && typeof(coords[i][0]) === "object") { coords[i] = arrayToLatLng(coords[i], useGeoJSON); } else { coords[i] = coordsToLatLngs(coords[i], useGeoJSON); } } } return coords; }; var getElementsByClassName = function (class_name, context) { var element, _class = class_name.replace('.', ''); if ('jQuery' in this && context) { element = $("." + _class, context)[0]; } else { element = document.getElementsByClassName(_class)[0]; } return element; }; var getElementById = function(id, context) { var element, id = id.replace('#', ''); if ('jQuery' in window && context) { element = $('#' + id, context)[0]; } else { element = document.getElementById(id); }; return element; }; var findAbsolutePosition = function(obj) { var curleft = 0, curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } return [curleft, curtop]; }; var GMaps = (function(global) { "use strict"; var doc = document; var GMaps = function(options) { if (!(typeof window.google === 'object' && window.google.maps)) { if (typeof window.console === 'object' && window.console.error) { console.error('Google Maps API is required. Please register the following JavaScript library https://maps.googleapis.com/maps/api/js.'); } return function() {}; } if (!this) return new GMaps(options); options.zoom = options.zoom || 15; options.mapType = options.mapType || 'roadmap'; var valueOrDefault = function(value, defaultValue) { return value === undefined ? defaultValue : value; }; var self = this, i, events_that_hide_context_menu = [ 'bounds_changed', 'center_changed', 'click', 'dblclick', 'drag', 'dragend', 'dragstart', 'idle', 'maptypeid_changed', 'projection_changed', 'resize', 'tilesloaded', 'zoom_changed' ], events_that_doesnt_hide_context_menu = ['mousemove', 'mouseout', 'mouseover'], options_to_be_deleted = ['el', 'lat', 'lng', 'mapType', 'width', 'height', 'markerClusterer', 'enableNewStyle'], identifier = options.el || options.div, markerClustererFunction = options.markerClusterer, mapType = google.maps.MapTypeId[options.mapType.toUpperCase()], map_center = new google.maps.LatLng(options.lat, options.lng), zoomControl = valueOrDefault(options.zoomControl, true), zoomControlOpt = options.zoomControlOpt || { style: 'DEFAULT', position: 'TOP_LEFT' }, zoomControlStyle = zoomControlOpt.style || 'DEFAULT', zoomControlPosition = zoomControlOpt.position || 'TOP_LEFT', panControl = valueOrDefault(options.panControl, true), mapTypeControl = valueOrDefault(options.mapTypeControl, true), scaleControl = valueOrDefault(options.scaleControl, true), streetViewControl = valueOrDefault(options.streetViewControl, true), overviewMapControl = valueOrDefault(overviewMapControl, true), map_options = {}, map_base_options = { zoom: this.zoom, center: map_center, mapTypeId: mapType }, map_controls_options = { panControl: panControl, zoomControl: zoomControl, zoomControlOptions: { style: google.maps.ZoomControlStyle[zoomControlStyle], position: google.maps.ControlPosition[zoomControlPosition] }, mapTypeControl: mapTypeControl, scaleControl: scaleControl, streetViewControl: streetViewControl, overviewMapControl: overviewMapControl }; if (typeof(options.el) === 'string' || typeof(options.div) === 'string') { if (identifier.indexOf("#") > -1) { this.el = getElementById(identifier, options.context); } else { this.el = getElementsByClassName.apply(this, [identifier, options.context]); } } else { this.el = identifier; } if (typeof(this.el) === 'undefined' || this.el === null) { throw 'No element defined.'; } window.context_menu = window.context_menu || {}; window.context_menu[self.el.id] = {}; this.controls = []; this.overlays = []; this.layers = []; // array with kml/georss and fusiontables layers, can be as many this.singleLayers = {}; // object with the other layers, only one per layer this.markers = []; this.polylines = []; this.routes = []; this.polygons = []; this.infoWindow = null; this.overlay_el = null; this.zoom = options.zoom; this.registered_events = {}; this.el.style.width = options.width || this.el.scrollWidth || this.el.offsetWidth; this.el.style.height = options.height || this.el.scrollHeight || this.el.offsetHeight; google.maps.visualRefresh = options.enableNewStyle; for (i = 0; i < options_to_be_deleted.length; i++) { delete options[options_to_be_deleted[i]]; } if(options.disableDefaultUI != true) { map_base_options = extend_object(map_base_options, map_controls_options); } map_options = extend_object(map_base_options, options); for (i = 0; i < events_that_hide_context_menu.length; i++) { delete map_options[events_that_hide_context_menu[i]]; } for (i = 0; i < events_that_doesnt_hide_context_menu.length; i++) { delete map_options[events_that_doesnt_hide_context_menu[i]]; } this.map = new google.maps.Map(this.el, map_options); if (markerClustererFunction) { this.markerClusterer = markerClustererFunction.apply(this, [this.map]); } var buildContextMenuHTML = function(control, e) { var html = '', options = window.context_menu[self.el.id][control]; for (var i in options){ if (options.hasOwnProperty(i)) { var option = options[i]; html += '<li><a id="' + control + '_' + i + '" href="#">' + option.title + '</a></li>'; } } if (!getElementById('gmaps_context_menu')) return; var context_menu_element = getElementById('gmaps_context_menu'); context_menu_element.innerHTML = html; var context_menu_items = context_menu_element.getElementsByTagName('a'), context_menu_items_count = context_menu_items.length, i; for (i = 0; i < context_menu_items_count; i++) { var context_menu_item = context_menu_items[i]; var assign_menu_item_action = function(ev){ ev.preventDefault(); options[this.id.replace(control + '_', '')].action.apply(self, [e]); self.hideContextMenu(); }; google.maps.event.clearListeners(context_menu_item, 'click'); google.maps.event.addDomListenerOnce(context_menu_item, 'click', assign_menu_item_action, false); } var position = findAbsolutePosition.apply(this, [self.el]), left = position[0] + e.pixel.x - 15, top = position[1] + e.pixel.y- 15; context_menu_element.style.left = left + "px"; context_menu_element.style.top = top + "px"; // context_menu_element.style.display = 'block'; }; this.buildContextMenu = function(control, e) { if (control === 'marker') { e.pixel = {}; var overlay = new google.maps.OverlayView(); overlay.setMap(self.map); overlay.draw = function() { var projection = overlay.getProjection(), position = e.marker.getPosition(); e.pixel = projection.fromLatLngToContainerPixel(position); buildContextMenuHTML(control, e); }; } else { buildContextMenuHTML(control, e); } var context_menu_element = getElementById('gmaps_context_menu'); setTimeout(function() { context_menu_element.style.display = 'block'; }, 0); }; this.setContextMenu = function(options) { window.context_menu[self.el.id][options.control] = {}; var i, ul = doc.createElement('ul'); for (i in options.options) { if (options.options.hasOwnProperty(i)) { var option = options.options[i]; window.context_menu[self.el.id][options.control][option.name] = { title: option.title, action: option.action }; } } ul.id = 'gmaps_context_menu'; ul.style.display = 'none'; ul.style.position = 'absolute'; ul.style.minWidth = '100px'; ul.style.background = 'white'; ul.style.listStyle = 'none'; ul.style.padding = '8px'; ul.style.boxShadow = '2px 2px 6px #ccc'; if (!getElementById('gmaps_context_menu')) { doc.body.appendChild(ul); } var context_menu_element = getElementById('gmaps_context_menu'); google.maps.event.addDomListener(context_menu_element, 'mouseout', function(ev) { if (!ev.relatedTarget || !this.contains(ev.relatedTarget)) { window.setTimeout(function(){ context_menu_element.style.display = 'none'; }, 400); } }, false); }; this.hideContextMenu = function() { var context_menu_element = getElementById('gmaps_context_menu'); if (context_menu_element) { context_menu_element.style.display = 'none'; } }; var setupListener = function(object, name) { google.maps.event.addListener(object, name, function(e){ if (e == undefined) { e = this; } options[name].apply(this, [e]); self.hideContextMenu(); }); }; //google.maps.event.addListener(this.map, 'idle', this.hideContextMenu); google.maps.event.addListener(this.map, 'zoom_changed', this.hideContextMenu); for (var ev = 0; ev < events_that_hide_context_menu.length; ev++) { var name = events_that_hide_context_menu[ev]; if (name in options) { setupListener(this.map, name); } } for (var ev = 0; ev < events_that_doesnt_hide_context_menu.length; ev++) { var name = events_that_doesnt_hide_context_menu[ev]; if (name in options) { setupListener(this.map, name); } } google.maps.event.addListener(this.map, 'rightclick', function(e) { if (options.rightclick) { options.rightclick.apply(this, [e]); } if(window.context_menu[self.el.id]['map'] != undefined) { self.buildContextMenu('map', e); } }); this.refresh = function() { google.maps.event.trigger(this.map, 'resize'); }; this.fitZoom = function() { var latLngs = [], markers_length = this.markers.length, i; for (i = 0; i < markers_length; i++) { if(typeof(this.markers[i].visible) === 'boolean' && this.markers[i].visible) { latLngs.push(this.markers[i].getPosition()); } } this.fitLatLngBounds(latLngs); }; this.fitLatLngBounds = function(latLngs) { var total = latLngs.length, bounds = new google.maps.LatLngBounds(), i; for(i = 0; i < total; i++) { bounds.extend(latLngs[i]); } this.map.fitBounds(bounds); }; this.setCenter = function(lat, lng, callback) { this.map.panTo(new google.maps.LatLng(lat, lng)); if (callback) { callback(); } }; this.getElement = function() { return this.el; }; this.zoomIn = function(value) { value = value || 1; this.zoom = this.map.getZoom() + value; this.map.setZoom(this.zoom); }; this.zoomOut = function(value) { value = value || 1; this.zoom = this.map.getZoom() - value; this.map.setZoom(this.zoom); }; var native_methods = [], method; for (method in this.map) { if (typeof(this.map[method]) == 'function' && !this[method]) { native_methods.push(method); } } for (i = 0; i < native_methods.length; i++) { (function(gmaps, scope, method_name) { gmaps[method_name] = function(){ return scope[method_name].apply(scope, arguments); }; })(this, this.map, native_methods[i]); } }; return GMaps; })(this); GMaps.prototype.createControl = function(options) { var control = document.createElement('div'); control.style.cursor = 'pointer'; if (options.disableDefaultStyles !== true) { control.style.fontFamily = 'Roboto, Arial, sans-serif'; control.style.fontSize = '11px'; control.style.boxShadow = 'rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px'; } for (var option in options.style) { control.style[option] = options.style[option]; } if (options.id) { control.id = options.id; } if (options.title) { control.title = options.title; } if (options.classes) { control.className = options.classes; } if (options.content) { if (typeof options.content === 'string') { control.innerHTML = options.content; } else if (options.content instanceof HTMLElement) { control.appendChild(options.content); } } if (options.position) { control.position = google.maps.ControlPosition[options.position.toUpperCase()]; } for (var ev in options.events) { (function(object, name) { google.maps.event.addDomListener(object, name, function(){ options.events[name].apply(this, [this]); }); })(control, ev); } control.index = 1; return control; }; GMaps.prototype.addControl = function(options) { var control = this.createControl(options); this.controls.push(control); this.map.controls[control.position].push(control); return control; }; GMaps.prototype.removeControl = function(control) { var position = null, i; for (i = 0; i < this.controls.length; i++) { if (this.controls[i] == control) { position = this.controls[i].position; this.controls.splice(i, 1); } } if (position) { for (i = 0; i < this.map.controls.length; i++) { var controlsForPosition = this.map.controls[control.position]; if (controlsForPosition.getAt(i) == control) { controlsForPosition.removeAt(i); break; } } } return control; }; GMaps.prototype.createMarker = function(options) { if (options.lat == undefined && options.lng == undefined && options.position == undefined) { throw 'No latitude or longitude defined.'; } var self = this, details = options.details, fences = options.fences, outside = options.outside, base_options = { position: new google.maps.LatLng(options.lat, options.lng), map: null }, marker_options = extend_object(base_options, options); delete marker_options.lat; delete marker_options.lng; delete marker_options.fences; delete marker_options.outside; var marker = new google.maps.Marker(marker_options); marker.fences = fences; if (options.infoWindow) { marker.infoWindow = new google.maps.InfoWindow(options.infoWindow); var info_window_events = ['closeclick', 'content_changed', 'domready', 'position_changed', 'zindex_changed']; for (var ev = 0; ev < info_window_events.length; ev++) { (function(object, name) { if (options.infoWindow[name]) { google.maps.event.addListener(object, name, function(e){ options.infoWindow[name].apply(this, [e]); }); } })(marker.infoWindow, info_window_events[ev]); } } var marker_events = ['animation_changed', 'clickable_changed', 'cursor_changed', 'draggable_changed', 'flat_changed', 'icon_changed', 'position_changed', 'shadow_changed', 'shape_changed', 'title_changed', 'visible_changed', 'zindex_changed']; var marker_events_with_mouse = ['dblclick', 'drag', 'dragend', 'dragstart', 'mousedown', 'mouseout', 'mouseover', 'mouseup']; for (var ev = 0; ev < marker_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(){ options[name].apply(this, [this]); }); } })(marker, marker_events[ev]); } for (var ev = 0; ev < marker_events_with_mouse.length; ev++) { (function(map, object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(me){ if(!me.pixel){ me.pixel = map.getProjection().fromLatLngToPoint(me.latLng) } options[name].apply(this, [me]); }); } })(this.map, marker, marker_events_with_mouse[ev]); } google.maps.event.addListener(marker, 'click', function() { this.details = details; if (options.click) { options.click.apply(this, [this]); } if (marker.infoWindow) { self.hideInfoWindows(); marker.infoWindow.open(self.map, marker); } }); google.maps.event.addListener(marker, 'rightclick', function(e) { e.marker = this; if (options.rightclick) { options.rightclick.apply(this, [e]); } if (window.context_menu[self.el.id]['marker'] != undefined) { self.buildContextMenu('marker', e); } }); if (marker.fences) { google.maps.event.addListener(marker, 'dragend', function() { self.checkMarkerGeofence(marker, function(m, f) { outside(m, f); }); }); } return marker; }; GMaps.prototype.addMarker = function(options) { var marker; if(options.hasOwnProperty('gm_accessors_')) { // Native google.maps.Marker object marker = options; } else { if ((options.hasOwnProperty('lat') && options.hasOwnProperty('lng')) || options.position) { marker = this.createMarker(options); } else { throw 'No latitude or longitude defined.'; } } marker.setMap(this.map); if(this.markerClusterer) { this.markerClusterer.addMarker(marker); } this.markers.push(marker); GMaps.fire('marker_added', marker, this); return marker; }; GMaps.prototype.addMarkers = function(array) { for (var i = 0, marker; marker=array[i]; i++) { this.addMarker(marker); } return this.markers; }; GMaps.prototype.hideInfoWindows = function() { for (var i = 0, marker; marker = this.markers[i]; i++){ if (marker.infoWindow) { marker.infoWindow.close(); } } }; GMaps.prototype.removeMarker = function(marker) { for (var i = 0; i < this.markers.length; i++) { if (this.markers[i] === marker) { this.markers[i].setMap(null); this.markers.splice(i, 1); if(this.markerClusterer) { this.markerClusterer.removeMarker(marker); } GMaps.fire('marker_removed', marker, this); break; } } return marker; }; GMaps.prototype.removeMarkers = function (collection) { var new_markers = []; if (typeof collection == 'undefined') { for (var i = 0; i < this.markers.length; i++) { var marker = this.markers[i]; marker.setMap(null); if(this.markerClusterer) { this.markerClusterer.removeMarker(marker); } GMaps.fire('marker_removed', marker, this); } this.markers = new_markers; } else { for (var i = 0; i < collection.length; i++) { var index = this.markers.indexOf(collection[i]); if (index > -1) { var marker = this.markers[index]; marker.setMap(null); if(this.markerClusterer) { this.markerClusterer.removeMarker(marker); } GMaps.fire('marker_removed', marker, this); } } for (var i = 0; i < this.markers.length; i++) { var marker = this.markers[i]; if (marker.getMap() != null) { new_markers.push(marker); } } this.markers = new_markers; } }; GMaps.prototype.drawOverlay = function(options) { var overlay = new google.maps.OverlayView(), auto_show = true; overlay.setMap(this.map); if (options.auto_show != null) { auto_show = options.auto_show; } overlay.onAdd = function() { var el = document.createElement('div'); el.style.borderStyle = "none"; el.style.borderWidth = "0px"; el.style.position = "absolute"; el.style.zIndex = 100; el.innerHTML = options.content; overlay.el = el; if (!options.layer) { options.layer = 'overlayLayer'; } var panes = this.getPanes(), overlayLayer = panes[options.layer], stop_overlay_events = ['contextmenu', 'DOMMouseScroll', 'dblclick', 'mousedown']; overlayLayer.appendChild(el); for (var ev = 0; ev < stop_overlay_events.length; ev++) { (function(object, name) { google.maps.event.addDomListener(object, name, function(e){ if (navigator.userAgent.toLowerCase().indexOf('msie') != -1 && document.all) { e.cancelBubble = true; e.returnValue = false; } else { e.stopPropagation(); } }); })(el, stop_overlay_events[ev]); } if (options.click) { panes.overlayMouseTarget.appendChild(overlay.el); google.maps.event.addDomListener(overlay.el, 'click', function() { options.click.apply(overlay, [overlay]); }); } google.maps.event.trigger(this, 'ready'); }; overlay.draw = function() { var projection = this.getProjection(), pixel = projection.fromLatLngToDivPixel(new google.maps.LatLng(options.lat, options.lng)); options.horizontalOffset = options.horizontalOffset || 0; options.verticalOffset = options.verticalOffset || 0; var el = overlay.el, content = el.children[0], content_height = content.clientHeight, content_width = content.clientWidth; switch (options.verticalAlign) { case 'top': el.style.top = (pixel.y - content_height + options.verticalOffset) + 'px'; break; default: case 'middle': el.style.top = (pixel.y - (content_height / 2) + options.verticalOffset) + 'px'; break; case 'bottom': el.style.top = (pixel.y + options.verticalOffset) + 'px'; break; } switch (options.horizontalAlign) { case 'left': el.style.left = (pixel.x - content_width + options.horizontalOffset) + 'px'; break; default: case 'center': el.style.left = (pixel.x - (content_width / 2) + options.horizontalOffset) + 'px'; break; case 'right': el.style.left = (pixel.x + options.horizontalOffset) + 'px'; break; } el.style.display = auto_show ? 'block' : 'none'; if (!auto_show) { options.show.apply(this, [el]); } }; overlay.onRemove = function() { var el = overlay.el; if (options.remove) { options.remove.apply(this, [el]); } else { overlay.el.parentNode.removeChild(overlay.el); overlay.el = null; } }; this.overlays.push(overlay); return overlay; }; GMaps.prototype.removeOverlay = function(overlay) { for (var i = 0; i < this.overlays.length; i++) { if (this.overlays[i] === overlay) { this.overlays[i].setMap(null); this.overlays.splice(i, 1); break; } } }; GMaps.prototype.removeOverlays = function() { for (var i = 0, item; item = this.overlays[i]; i++) { item.setMap(null); } this.overlays = []; }; GMaps.prototype.drawPolyline = function(options) { var path = [], points = options.path; if (points.length) { if (points[0][0] === undefined) { path = points; } else { for (var i = 0, latlng; latlng = points[i]; i++) { path.push(new google.maps.LatLng(latlng[0], latlng[1])); } } } var polyline_options = { map: this.map, path: path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight, geodesic: options.geodesic, clickable: true, editable: false, visible: true }; if (options.hasOwnProperty("clickable")) { polyline_options.clickable = options.clickable; } if (options.hasOwnProperty("editable")) { polyline_options.editable = options.editable; } if (options.hasOwnProperty("icons")) { polyline_options.icons = options.icons; } if (options.hasOwnProperty("zIndex")) { polyline_options.zIndex = options.zIndex; } var polyline = new google.maps.Polyline(polyline_options); var polyline_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polyline_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polyline, polyline_events[ev]); } this.polylines.push(polyline); GMaps.fire('polyline_added', polyline, this); return polyline; }; GMaps.prototype.removePolyline = function(polyline) { for (var i = 0; i < this.polylines.length; i++) { if (this.polylines[i] === polyline) { this.polylines[i].setMap(null); this.polylines.splice(i, 1); GMaps.fire('polyline_removed', polyline, this); break; } } }; GMaps.prototype.removePolylines = function() { for (var i = 0, item; item = this.polylines[i]; i++) { item.setMap(null); } this.polylines = []; }; GMaps.prototype.drawCircle = function(options) { options = extend_object({ map: this.map, center: new google.maps.LatLng(options.lat, options.lng) }, options); delete options.lat; delete options.lng; var polygon = new google.maps.Circle(options), polygon_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polygon_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polygon, polygon_events[ev]); } this.polygons.push(polygon); return polygon; }; GMaps.prototype.drawRectangle = function(options) { options = extend_object({ map: this.map }, options); var latLngBounds = new google.maps.LatLngBounds( new google.maps.LatLng(options.bounds[0][0], options.bounds[0][1]), new google.maps.LatLng(options.bounds[1][0], options.bounds[1][1]) ); options.bounds = latLngBounds; var polygon = new google.maps.Rectangle(options), polygon_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polygon_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polygon, polygon_events[ev]); } this.polygons.push(polygon); return polygon; }; GMaps.prototype.drawPolygon = function(options) { var useGeoJSON = false; if(options.hasOwnProperty("useGeoJSON")) { useGeoJSON = options.useGeoJSON; } delete options.useGeoJSON; options = extend_object({ map: this.map }, options); if (useGeoJSON == false) { options.paths = [options.paths.slice(0)]; } if (options.paths.length > 0) { if (options.paths[0].length > 0) { options.paths = array_flat(array_map(options.paths, arrayToLatLng, useGeoJSON)); } } var polygon = new google.maps.Polygon(options), polygon_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polygon_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polygon, polygon_events[ev]); } this.polygons.push(polygon); GMaps.fire('polygon_added', polygon, this); return polygon; }; GMaps.prototype.removePolygon = function(polygon) { for (var i = 0; i < this.polygons.length; i++) { if (this.polygons[i] === polygon) { this.polygons[i].setMap(null); this.polygons.splice(i, 1); GMaps.fire('polygon_removed', polygon, this); break; } } }; GMaps.prototype.removePolygons = function() { for (var i = 0, item; item = this.polygons[i]; i++) { item.setMap(null); } this.polygons = []; }; GMaps.prototype.getFromFusionTables = function(options) { var events = options.events; delete options.events; var fusion_tables_options = options, layer = new google.maps.FusionTablesLayer(fusion_tables_options); for (var ev in events) { (function(object, name) { google.maps.event.addListener(object, name, function(e) { events[name].apply(this, [e]); }); })(layer, ev); } this.layers.push(layer); return layer; }; GMaps.prototype.loadFromFusionTables = function(options) { var layer = this.getFromFusionTables(options); layer.setMap(this.map); return layer; }; GMaps.prototype.getFromKML = function(options) { var url = options.url, events = options.events; delete options.url; delete options.events; var kml_options = options, layer = new google.maps.KmlLayer(url, kml_options); for (var ev in events) { (function(object, name) { google.maps.event.addListener(object, name, function(e) { events[name].apply(this, [e]); }); })(layer, ev); } this.layers.push(layer); return layer; }; GMaps.prototype.loadFromKML = function(options) { var layer = this.getFromKML(options); layer.setMap(this.map); return layer; }; GMaps.prototype.addLayer = function(layerName, options) { //var default_layers = ['weather', 'clouds', 'traffic', 'transit', 'bicycling', 'panoramio', 'places']; options = options || {}; var layer; switch(layerName) { case 'weather': this.singleLayers.weather = layer = new google.maps.weather.WeatherLayer(); break; case 'clouds': this.singleLayers.clouds = layer = new google.maps.weather.CloudLayer(); break; case 'traffic': this.singleLayers.traffic = layer = new google.maps.TrafficLayer(); break; case 'transit': this.singleLayers.transit = layer = new google.maps.TransitLayer(); break; case 'bicycling': this.singleLayers.bicycling = layer = new google.maps.BicyclingLayer(); break; case 'panoramio': this.singleLayers.panoramio = layer = new google.maps.panoramio.PanoramioLayer(); layer.setTag(options.filter); delete options.filter; //click event if (options.click) { google.maps.event.addListener(layer, 'click', function(event) { options.click(event); delete options.click; }); } break; case 'places': this.singleLayers.places = layer = new google.maps.places.PlacesService(this.map); //search, nearbySearch, radarSearch callback, Both are the same if (options.search || options.nearbySearch || options.radarSearch) { var placeSearchRequest = { bounds : options.bounds || null, keyword : options.keyword || null, location : options.location || null, name : options.name || null, radius : options.radius || null, rankBy : options.rankBy || null, types : options.types || null }; if (options.radarSearch) { layer.radarSearch(placeSearchRequest, options.radarSearch); } if (options.search) { layer.search(placeSearchRequest, options.search); } if (options.nearbySearch) { layer.nearbySearch(placeSearchRequest, options.nearbySearch); } } //textSearch callback if (options.textSearch) { var textSearchRequest = { bounds : options.bounds || null, location : options.location || null, query : options.query || null, radius : options.radius || null }; layer.textSearch(textSearchRequest, options.textSearch); } break; } if (layer !== undefined) { if (typeof layer.setOptions == 'function') { layer.setOptions(options); } if (typeof layer.setMap == 'function') { layer.setMap(this.map); } return layer; } }; GMaps.prototype.removeLayer = function(layer) { if (typeof(layer) == "string" && this.singleLayers[layer] !== undefined) { this.singleLayers[layer].setMap(null); delete this.singleLayers[layer]; } else { for (var i = 0; i < this.layers.length; i++) { if (this.layers[i] === layer) { this.layers[i].setMap(null); this.layers.splice(i, 1); break; } } } }; var travelMode, unitSystem; GMaps.prototype.getRoutes = function(options) { switch (options.travelMode) { case 'bicycling': travelMode = google.maps.TravelMode.BICYCLING; break; case 'transit': travelMode = google.maps.TravelMode.TRANSIT; break; case 'driving': travelMode = google.maps.TravelMode.DRIVING; break; default: travelMode = google.maps.TravelMode.WALKING; break; } if (options.unitSystem === 'imperial') { unitSystem = google.maps.UnitSystem.IMPERIAL; } else { unitSystem = google.maps.UnitSystem.METRIC; } var base_options = { avoidHighways: false, avoidTolls: false, optimizeWaypoints: false, waypoints: [] }, request_options = extend_object(base_options, options); request_options.origin = /string/.test(typeof options.origin) ? options.origin : new google.maps.LatLng(options.origin[0], options.origin[1]); request_options.destination = /string/.test(typeof options.destination) ? options.destination : new google.maps.LatLng(options.destination[0], options.destination[1]); request_options.travelMode = travelMode; request_options.unitSystem = unitSystem; delete request_options.callback; delete request_options.error; var self = this, service = new google.maps.DirectionsService(); service.route(request_options, function(result, status) { if (status === google.maps.DirectionsStatus.OK) { for (var r in result.routes) { if (result.routes.hasOwnProperty(r)) { self.routes.push(result.routes[r]); } } if (options.callback) { options.callback(self.routes, result, status); } } else { if (options.error) { options.error(result, status); } } }); }; GMaps.prototype.removeRoutes = function() { this.routes.length = 0; }; GMaps.prototype.getElevations = function(options) { options = extend_object({ locations: [], path : false, samples : 256 }, options); if (options.locations.length > 0) { if (options.locations[0].length > 0) { options.locations = array_flat(array_map([options.locations], arrayToLatLng, false)); } } var callback = options.callback; delete options.callback; var service = new google.maps.ElevationService(); //location request if (!options.path) { delete options.path; delete options.samples; service.getElevationForLocations(options, function(result, status) { if (callback && typeof(callback) === "function") { callback(result, status); } }); //path request } else { var pathRequest = { path : options.locations, samples : options.samples }; service.getElevationAlongPath(pathRequest, function(result, status) { if (callback && typeof(callback) === "function") { callback(result, status); } }); } }; GMaps.prototype.cleanRoute = GMaps.prototype.removePolylines; GMaps.prototype.renderRoute = function(options, renderOptions) { var self = this, panel = ((typeof renderOptions.panel === 'string') ? document.getElementById(renderOptions.panel.replace('#', '')) : renderOptions.panel), display; renderOptions.panel = panel; renderOptions = extend_object({ map: this.map }, renderOptions); display = new google.maps.DirectionsRenderer(renderOptions); this.getRoutes({ origin: options.origin, destination: options.destination, travelMode: options.travelMode, waypoints: options.waypoints, unitSystem: options.unitSystem, error: options.error, avoidHighways: options.avoidHighways, avoidTolls: options.avoidTolls, optimizeWaypoints: options.optimizeWaypoints, callback: function(routes, response, status) { if (status === google.maps.DirectionsStatus.OK) { display.setDirections(response); } } }); }; GMaps.prototype.drawRoute = function(options) { var self = this; this.getRoutes({ origin: options.origin, destination: options.destination, travelMode: options.travelMode, waypoints: options.waypoints, unitSystem: options.unitSystem, error: options.error, avoidHighways: options.avoidHighways, avoidTolls: options.avoidTolls, optimizeWaypoints: options.optimizeWaypoints, callback: function(routes) { if (routes.length > 0) { var polyline_options = { path: routes[routes.length - 1].overview_path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }; if (options.hasOwnProperty("icons")) { polyline_options.icons = options.icons; } self.drawPolyline(polyline_options); if (options.callback) { options.callback(routes[routes.length - 1]); } } } }); }; GMaps.prototype.travelRoute = function(options) { if (options.origin && options.destination) { this.getRoutes({ origin: options.origin, destination: options.destination, travelMode: options.travelMode, waypoints : options.waypoints, unitSystem: options.unitSystem, error: options.error, callback: function(e) { //start callback if (e.length > 0 && options.start) { options.start(e[e.length - 1]); } //step callback if (e.length > 0 && options.step) { var route = e[e.length - 1]; if (route.legs.length > 0) { var steps = route.legs[0].steps; for (var i = 0, step; step = steps[i]; i++) { step.step_number = i; options.step(step, (route.legs[0].steps.length - 1)); } } } //end callback if (e.length > 0 && options.end) { options.end(e[e.length - 1]); } } }); } else if (options.route) { if (options.route.legs.length > 0) { var steps = options.route.legs[0].steps; for (var i = 0, step; step = steps[i]; i++) { step.step_number = i; options.step(step); } } } }; GMaps.prototype.drawSteppedRoute = function(options) { var self = this; if (options.origin && options.destination) { this.getRoutes({ origin: options.origin, destination: options.destination, travelMode: options.travelMode, waypoints : options.waypoints, error: options.error, callback: function(e) { //start callback if (e.length > 0 && options.start) { options.start(e[e.length - 1]); } //step callback if (e.length > 0 && options.step) { var route = e[e.length - 1]; if (route.legs.length > 0) { var steps = route.legs[0].steps; for (var i = 0, step; step = steps[i]; i++) { step.step_number = i; var polyline_options = { path: step.path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }; if (options.hasOwnProperty("icons")) { polyline_options.icons = options.icons; } self.drawPolyline(polyline_options); options.step(step, (route.legs[0].steps.length - 1)); } } } //end callback if (e.length > 0 && options.end) { options.end(e[e.length - 1]); } } }); } else if (options.route) { if (options.route.legs.length > 0) { var steps = options.route.legs[0].steps; for (var i = 0, step; step = steps[i]; i++) { step.step_number = i; var polyline_options = { path: step.path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }; if (options.hasOwnProperty("icons")) { polyline_options.icons = options.icons; } self.drawPolyline(polyline_options); options.step(step); } } } }; GMaps.Route = function(options) { this.origin = options.origin; this.destination = options.destination; this.waypoints = options.waypoints; this.map = options.map; this.route = options.route; this.step_count = 0; this.steps = this.route.legs[0].steps; this.steps_length = this.steps.length; var polyline_options = { path: new google.maps.MVCArray(), strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }; if (options.hasOwnProperty("icons")) { polyline_options.icons = options.icons; } this.polyline = this.map.drawPolyline(polyline_options).getPath(); }; GMaps.Route.prototype.getRoute = function(options) { var self = this; this.map.getRoutes({ origin : this.origin, destination : this.destination, travelMode : options.travelMode, waypoints : this.waypoints || [], error: options.error, callback : function() { self.route = e[0]; if (options.callback) { options.callback.call(self); } } }); }; GMaps.Route.prototype.back = function() { if (this.step_count > 0) { this.step_count--; var path = this.route.legs[0].steps[this.step_count].path; for (var p in path){ if (path.hasOwnProperty(p)){ this.polyline.pop(); } } } }; GMaps.Route.prototype.forward = function() { if (this.step_count < this.steps_length) { var path = this.route.legs[0].steps[this.step_count].path; for (var p in path){ if (path.hasOwnProperty(p)){ this.polyline.push(path[p]); } } this.step_count++; } }; GMaps.prototype.checkGeofence = function(lat, lng, fence) { return fence.containsLatLng(new google.maps.LatLng(lat, lng)); }; GMaps.prototype.checkMarkerGeofence = function(marker, outside_callback) { if (marker.fences) { for (var i = 0, fence; fence = marker.fences[i]; i++) { var pos = marker.getPosition(); if (!this.checkGeofence(pos.lat(), pos.lng(), fence)) { outside_callback(marker, fence); } } } }; GMaps.prototype.toImage = function(options) { var options = options || {}, static_map_options = {}; static_map_options['size'] = options['size'] || [this.el.clientWidth, this.el.clientHeight]; static_map_options['lat'] = this.getCenter().lat(); static_map_options['lng'] = this.getCenter().lng(); if (this.markers.length > 0) { static_map_options['markers'] = []; for (var i = 0; i < this.markers.length; i++) { static_map_options['markers'].push({ lat: this.markers[i].getPosition().lat(), lng: this.markers[i].getPosition().lng() }); } } if (this.polylines.length > 0) { var polyline = this.polylines[0]; static_map_options['polyline'] = {}; static_map_options['polyline']['path'] = google.maps.geometry.encoding.encodePath(polyline.getPath()); static_map_options['polyline']['strokeColor'] = polyline.strokeColor static_map_options['polyline']['strokeOpacity'] = polyline.strokeOpacity static_map_options['polyline']['strokeWeight'] = polyline.strokeWeight } return GMaps.staticMapURL(static_map_options); }; GMaps.staticMapURL = function(options){ var parameters = [], data, static_root = (location.protocol === 'file:' ? 'http:' : location.protocol ) + '//maps.googleapis.com/maps/api/staticmap'; if (options.url) { static_root = options.url; delete options.url; } static_root += '?'; var markers = options.markers; delete options.markers; if (!markers && options.marker) { markers = [options.marker]; delete options.marker; } var styles = options.styles; delete options.styles; var polyline = options.polyline; delete options.polyline; /** Map options **/ if (options.center) { parameters.push('center=' + options.center); delete options.center; } else if (options.address) { parameters.push('center=' + options.address); delete options.address; } else if (options.lat) { parameters.push(['center=', options.lat, ',', options.lng].join('')); delete options.lat; delete options.lng; } else if (options.visible) { var visible = encodeURI(options.visible.join('|')); parameters.push('visible=' + visible); } var size = options.size; if (size) { if (size.join) { size = size.join('x'); } delete options.size; } else { size = '630x300'; } parameters.push('size=' + size); if (!options.zoom && options.zoom !== false) { options.zoom = 15; } var sensor = options.hasOwnProperty('sensor') ? !!options.sensor : true; delete options.sensor; parameters.push('sensor=' + sensor); for (var param in options) { if (options.hasOwnProperty(param)) { parameters.push(param + '=' + options[param]); } } /** Markers **/ if (markers) { var marker, loc; for (var i = 0; data = markers[i]; i++) { marker = []; if (data.size && data.size !== 'normal') { marker.push('size:' + data.size); delete data.size; } else if (data.icon) { marker.push('icon:' + encodeURI(data.icon)); delete data.icon; } if (data.color) { marker.push('color:' + data.color.replace('#', '0x')); delete data.color; } if (data.label) { marker.push('label:' + data.label[0].toUpperCase()); delete data.label; } loc = (data.address ? data.address : data.lat + ',' + data.lng); delete data.address; delete data.lat; delete data.lng; for(var param in data){ if (data.hasOwnProperty(param)) { marker.push(param + ':' + data[param]); } } if (marker.length || i === 0) { marker.push(loc); marker = marker.join('|'); parameters.push('markers=' + encodeURI(marker)); } // New marker without styles else { marker = parameters.pop() + encodeURI('|' + loc); parameters.push(marker); } } } /** Map Styles **/ if (styles) { for (var i = 0; i < styles.length; i++) { var styleRule = []; if (styles[i].featureType){ styleRule.push('feature:' + styles[i].featureType.toLowerCase()); } if (styles[i].elementType) { styleRule.push('element:' + styles[i].elementType.toLowerCase()); } for (var j = 0; j < styles[i].stylers.length; j++) { for (var p in styles[i].stylers[j]) { var ruleArg = styles[i].stylers[j][p]; if (p == 'hue' || p == 'color') { ruleArg = '0x' + ruleArg.substring(1); } styleRule.push(p + ':' + ruleArg); } } var rule = styleRule.join('|'); if (rule != '') { parameters.push('style=' + rule); } } } /** Polylines **/ function parseColor(color, opacity) { if (color[0] === '#'){ color = color.replace('#', '0x'); if (opacity) { opacity = parseFloat(opacity); opacity = Math.min(1, Math.max(opacity, 0)); if (opacity === 0) { return '0x00000000'; } opacity = (opacity * 255).toString(16); if (opacity.length === 1) { opacity += opacity; } color = color.slice(0,8) + opacity; } } return color; } if (polyline) { data = polyline; polyline = []; if (data.strokeWeight) { polyline.push('weight:' + parseInt(data.strokeWeight, 10)); } if (data.strokeColor) { var color = parseColor(data.strokeColor, data.strokeOpacity); polyline.push('color:' + color); } if (data.fillColor) { var fillcolor = parseColor(data.fillColor, data.fillOpacity); polyline.push('fillcolor:' + fillcolor); } var path = data.path; if (path.join) { for (var j=0, pos; pos=path[j]; j++) { polyline.push(pos.join(',')); } } else { polyline.push('enc:' + path); } polyline = polyline.join('|'); parameters.push('path=' + encodeURI(polyline)); } /** Retina support **/ var dpi = window.devicePixelRatio || 1; parameters.push('scale=' + dpi); parameters = parameters.join('&'); return static_root + parameters; }; GMaps.prototype.addMapType = function(mapTypeId, options) { if (options.hasOwnProperty("getTileUrl") && typeof(options["getTileUrl"]) == "function") { options.tileSize = options.tileSize || new google.maps.Size(256, 256); var mapType = new google.maps.ImageMapType(options); this.map.mapTypes.set(mapTypeId, mapType); } else { throw "'getTileUrl' function required."; } }; GMaps.prototype.addOverlayMapType = function(options) { if (options.hasOwnProperty("getTile") && typeof(options["getTile"]) == "function") { var overlayMapTypeIndex = options.index; delete options.index; this.map.overlayMapTypes.insertAt(overlayMapTypeIndex, options); } else { throw "'getTile' function required."; } }; GMaps.prototype.removeOverlayMapType = function(overlayMapTypeIndex) { this.map.overlayMapTypes.removeAt(overlayMapTypeIndex); }; GMaps.prototype.addStyle = function(options) { var styledMapType = new google.maps.StyledMapType(options.styles, { name: options.styledMapName }); this.map.mapTypes.set(options.mapTypeId, styledMapType); }; GMaps.prototype.setStyle = function(mapTypeId) { this.map.setMapTypeId(mapTypeId); }; GMaps.prototype.createPanorama = function(streetview_options) { if (!streetview_options.hasOwnProperty('lat') || !streetview_options.hasOwnProperty('lng')) { streetview_options.lat = this.getCenter().lat(); streetview_options.lng = this.getCenter().lng(); } this.panorama = GMaps.createPanorama(streetview_options); this.map.setStreetView(this.panorama); return this.panorama; }; GMaps.createPanorama = function(options) { var el = getElementById(options.el, options.context); options.position = new google.maps.LatLng(options.lat, options.lng); delete options.el; delete options.context; delete options.lat; delete options.lng; var streetview_events = ['closeclick', 'links_changed', 'pano_changed', 'position_changed', 'pov_changed', 'resize', 'visible_changed'], streetview_options = extend_object({visible : true}, options); for (var i = 0; i < streetview_events.length; i++) { delete streetview_options[streetview_events[i]]; } var panorama = new google.maps.StreetViewPanorama(el, streetview_options); for (var i = 0; i < streetview_events.length; i++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(){ options[name].apply(this); }); } })(panorama, streetview_events[i]); } return panorama; }; GMaps.prototype.on = function(event_name, handler) { return GMaps.on(event_name, this, handler); }; GMaps.prototype.off = function(event_name) { GMaps.off(event_name, this); }; GMaps.prototype.once = function(event_name, handler) { return GMaps.once(event_name, this, handler); }; GMaps.custom_events = ['marker_added', 'marker_removed', 'polyline_added', 'polyline_removed', 'polygon_added', 'polygon_removed', 'geolocated', 'geolocation_failed']; GMaps.on = function(event_name, object, handler) { if (GMaps.custom_events.indexOf(event_name) == -1) { if(object instanceof GMaps) object = object.map; return google.maps.event.addListener(object, event_name, handler); } else { var registered_event = { handler : handler, eventName : event_name }; object.registered_events[event_name] = object.registered_events[event_name] || []; object.registered_events[event_name].push(registered_event); return registered_event; } }; GMaps.off = function(event_name, object) { if (GMaps.custom_events.indexOf(event_name) == -1) { if(object instanceof GMaps) object = object.map; google.maps.event.clearListeners(object, event_name); } else { object.registered_events[event_name] = []; } }; GMaps.once = function(event_name, object, handler) { if (GMaps.custom_events.indexOf(event_name) == -1) { if(object instanceof GMaps) object = object.map; return google.maps.event.addListenerOnce(object, event_name, handler); } }; GMaps.fire = function(event_name, object, scope) { if (GMaps.custom_events.indexOf(event_name) == -1) { google.maps.event.trigger(object, event_name, Array.prototype.slice.apply(arguments).slice(2)); } else { if(event_name in scope.registered_events) { var firing_events = scope.registered_events[event_name]; for(var i = 0; i < firing_events.length; i++) { (function(handler, scope, object) { handler.apply(scope, [object]); })(firing_events[i]['handler'], scope, object); } } } }; GMaps.geolocate = function(options) { var complete_callback = options.always || options.complete; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { options.success(position); if (complete_callback) { complete_callback(); } }, function(error) { options.error(error); if (complete_callback) { complete_callback(); } }, options.options); } else { options.not_supported(); if (complete_callback) { complete_callback(); } } }; GMaps.geocode = function(options) { this.geocoder = new google.maps.Geocoder(); var callback = options.callback; if (options.hasOwnProperty('lat') && options.hasOwnProperty('lng')) { options.latLng = new google.maps.LatLng(options.lat, options.lng); } delete options.lat; delete options.lng; delete options.callback; this.geocoder.geocode(options, function(results, status) { callback(results, status); }); }; if (typeof window.google === 'object' && window.google.maps) { //========================== // Polygon containsLatLng // https://github.com/tparkin/Google-Maps-Point-in-Polygon // Poygon getBounds extension - google-maps-extensions // http://code.google.com/p/google-maps-extensions/source/browse/google.maps.Polygon.getBounds.js if (!google.maps.Polygon.prototype.getBounds) { google.maps.Polygon.prototype.getBounds = function(latLng) { var bounds = new google.maps.LatLngBounds(); var paths = this.getPaths(); var path; for (var p = 0; p < paths.getLength(); p++) { path = paths.getAt(p); for (var i = 0; i < path.getLength(); i++) { bounds.extend(path.getAt(i)); } } return bounds; }; } if (!google.maps.Polygon.prototype.containsLatLng) { // Polygon containsLatLng - method to determine if a latLng is within a polygon google.maps.Polygon.prototype.containsLatLng = function(latLng) { // Exclude points outside of bounds as there is no way they are in the poly var bounds = this.getBounds(); if (bounds !== null && !bounds.contains(latLng)) { return false; } // Raycast point in polygon method var inPoly = false; var numPaths = this.getPaths().getLength(); for (var p = 0; p < numPaths; p++) { var path = this.getPaths().getAt(p); var numPoints = path.getLength(); var j = numPoints - 1; for (var i = 0; i < numPoints; i++) { var vertex1 = path.getAt(i); var vertex2 = path.getAt(j); if (vertex1.lng() < latLng.lng() && vertex2.lng() >= latLng.lng() || vertex2.lng() < latLng.lng() && vertex1.lng() >= latLng.lng()) { if (vertex1.lat() + (latLng.lng() - vertex1.lng()) / (vertex2.lng() - vertex1.lng()) * (vertex2.lat() - vertex1.lat()) < latLng.lat()) { inPoly = !inPoly; } } j = i; } } return inPoly; }; } if (!google.maps.Circle.prototype.containsLatLng) { google.maps.Circle.prototype.containsLatLng = function(latLng) { if (google.maps.geometry) { return google.maps.geometry.spherical.computeDistanceBetween(this.getCenter(), latLng) <= this.getRadius(); } else { return true; } }; } google.maps.LatLngBounds.prototype.containsLatLng = function(latLng) { return this.contains(latLng); }; google.maps.Marker.prototype.setFences = function(fences) { this.fences = fences; }; google.maps.Marker.prototype.addFence = function(fence) { this.fences.push(fence); }; google.maps.Marker.prototype.getId = function() { return this['__gm_id']; }; } //========================== // Array indexOf // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { "use strict"; if (this == null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { // shortcut for verifying if it's NaN n = 0; } else if (n != 0 && n != Infinity && n != -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; } } return GMaps; }));
z3cform.locationwidget
/z3cform.locationwidget-1.1.0-py38-none-any.whl/z3cform/locationwidget/browser/static/gmaps.js
gmaps.js
========= z3locales ========= The code is distributed under terms of the Zope Public License version 2.1. See also LICENSE.txt. Z3locales is a library which translates dates in Zope 2 to the current user language using Zope 3 technology. Those functions are available in the module ``localdatetime``: ``get_formatted_now(request)`` Return the current date formatted and translated in the current user language. The target user language is determined via the provided request. ``get_formatted_date(date, size="full", request=_marker, locale=_marker, display_time=True)`` Take a date (should be a tuple ``(year, month, day[, hour[, minute[, second]]])`` or a Python datetime object), format it and translate it in the target user language (determined via locale or the given request). The modifier size and display_time can be used to change the output. ``get_month_names(request=_marker, locale=_marker, calendar='gregorian')`` Return a list of month names translated in the target language (determined via locale or the given request). ``get_month_abbreviations(request=_marker, locale=_marker, calendar='gregorian')`` Return a list of month abbreviations (usually the first three letters) translated in the target user language (determined via locale or the given request). ``get_locale_info(request)`` Return the locale representing the target user language using the provided request. This locale can be used after by other functions of this package. Compatibility API exists with previous versions.
z3locales
/z3locales-0.4.1.tar.gz/z3locales-0.4.1/README.txt
README.txt
from datetime import datetime import time from zope.i18n.locales import locales, LoadLocaleError from zope.i18n.interfaces import IUserPreferredLanguages _marker = object() def get_locale_info(request): if request == _marker: return 'en' languages = IUserPreferredLanguages(request).getPreferredLanguages() return (languages and languages[0]) or 'en' def get_locale_dates(request=_marker, locale=_marker): """Return the date formatter given the request. """ local_info = locale if local_info is _marker: local_info = get_locale_info(request) try: return locales.getLocale(*local_info.split('-')).dates except LoadLocaleError: return locales.getLocale('en').dates def get_formatted_now(request): """Return the current date formatted given the request local """ now = time.gmtime() formatter = get_locale_dates(request).getFormatter('dateTime', 'full') return formatter.format(datetime(*now[:6])) def get_formatted_date( date, size="full", request=_marker, locale=_marker, display_time=True): """Return a formatted date given the locale or request. date should be a tuple (year, month, day[, hour[, minute[, second]]]) or a datetime instance. """ if not isinstance(date, datetime): date = datetime(*date) format = 'dateTime' if display_time else 'date' formatter = get_locale_dates(request, locale).getFormatter(format, size) return formatter.format(date) def get_month_names( request=_marker, locale=_marker, calendar='gregorian'): """returns a list of month names for the current locale """ dates = get_locale_dates(request, locale) return dates.calendars[calendar].getMonthNames() def get_month_abbreviations( request=_marker, locale=_marker, calendar='gregorian'): """returns a list of abbreviated month names for the current locale """ dates = get_locale_dates(request, locale) return dates.calendars[calendar].getMonthAbbreviations() # BBB getlocaleinfo = lambda self: get_locale_info(self.REQUEST) getFormattedNow = lambda self, *args, **kwargs: get_formatted_now( self.REQUEST, *args, **kwargs) getFormattedDate = lambda self, *args, **kwargs: get_formatted_date( self.REQUEST, *args, **kwargs) getMonthNames = lambda self, *args, **kwargs: get_month_names( self.REQUEST, *args, **kwargs) getMonthAbbreviations = lambda self, *args, **kwargs: get_month_abbreviations( self.REQUEST, *args, **kwargs)
z3locales
/z3locales-0.4.1.tar.gz/z3locales-0.4.1/src/localdatetime/__init__.py
__init__.py
import os import regex as re import random import numpy as np import subprocess import sys from .config.path import * from .config.config import * from .argument import Arguments from .utils import * from typing import Dict, List class Verilog: def __init__(self, benchmark_name: str, samples: list = []): """ takes in a circuit and creates a verilog object out of it :param benchmark_name: the input circuit in verilog format :param samples: number of samples for the mc simulation; it is an empty list by default """ self.__circuit_name = get_pure_name(benchmark_name) folder, extension = INPUT_PATH['ver'] self.__circuit_in_path = f'{folder}/{benchmark_name}.{extension}' folder, extension = OUTPUT_PATH['ver'] self.__circuit_out_path = f'{folder}/{benchmark_name}.{extension}' folder, extension = OUTPUT_PATH['aig'] self.__aig_out_path = f'{folder}/{benchmark_name}.{extension}' folder, extension = TEST_PATH['tb'] self.__testbench_out_path = f'{folder}/{benchmark_name}_tb.{extension}' folder, extension = TEST_PATH['tb'] self.__tmp_verilog = f'{folder}/{TMP}.{extension}' folder, extension = TEST_PATH['iver'] self.__iverilog_out_path = f'{folder}/{benchmark_name}.{extension}' folder, extension = LOG_PATH['iver'] self.__iverilog_log_path = f'{folder}/{benchmark_name}_{IVERILOG}_{LOG}.{extension}' folder, extension = TEST_PATH['vvp'] self.__vvp_out_path = f'{folder}/{benchmark_name}.{extension}' self.__num_inputs, self.__num_outputs = self.extract_module_io() self.__sample_results = None self.__samples = samples self.synthesize_to_gate_level(self.in_path, self.out_path) # self.unwrap_variables() @property def name(self): return self.__circuit_name @name.setter def name(self, newname): self.__circuit_name == newname @property def num_inputs(self): return self.__num_inputs @property def num_outputs(self): return self.__num_outputs @property def in_path(self): return self.__circuit_in_path @property def out_path(self): return self.__circuit_out_path @property def aig_out_path(self): return self.__aig_out_path @property def cleaned_verilog(self): return self.__circuit_out_path @property def tmp(self): return self.__tmp_verilog @property def testbench(self): return self.__testbench_out_path @property def samples(self): return self.__samples @property def iverilog_out_path(self): return self.__iverilog_out_path @property def iverilog_log_path(self): return self.__iverilog_log_path @property def vvp_in_path(self): return self.__iverilog_out_path @property def vvp_out_path(self): return self.__vvp_out_path def set_samples(self, samples: np.array or list): self.__samples = samples @property def sample_results(self): return self.__sample_results def set_sample_results(self, results): self.__sample_results = results # methods def import_results(self): arr = [] with open(self.vvp_out_path, 'r') as f: lines = f.readlines() for line in lines: line = line.replace('\n', '') arr.append(int(line, 2)) results = np.array(arr) return results def import_circuit(self): with open(self.in_path, 'r') as f: lines = f.readlines() return lines def check_multi_vector_declaration(self, cur_list: List[str]) -> List[str]: # for lines such as: # input [1:0]a, b; # cur_list will be = ['[1:0]a', 'b'] which should be ['[1:0]a', '[1:0]b'] if self.is_vector(cur_list[0]): # find the range vector_range = re.search('\[\d+:\d+\]', cur_list[0]).group() # propagate the range for the rest of the elements of cur_list for i in range(1, len(cur_list)): cur_list[i] = vector_range + cur_list[i] return cur_list def is_vector(self, var_name: str) -> bool: """ checks whether var_name variable is a vector :param var_name: the variable name :return: True if the variable is a vector, otherwise returns False """ if re.search('(\[\d+:\d+\])', var_name): return True else: return False def get_name(self, var_name: str) -> str: """ if var_name is an array, e.g., [1:0]a, it will return a. Otherwise, it will return var_name. :param var_name: the name of the variable :return: a string representing variable name """ if self.is_vector(var_name): # remove [n:m] part match_obj = re.search('(\[\d+:\d+\])(.*)', var_name) return match_obj.group(2) else: return var_name def get_width(self, var_name: str) -> int: """ computes the bit-width of a given variable :param var_name: the name of the variable :return: an integer representing the bit-width of the given variable """ if self.is_vector(var_name): # compute the length match = re.search('\[(\d+):(\d+)\]', var_name) # [1:0]a l_bound = int(match.group(1)) # 1 r_bound = int(match.group(2)) # 0 return abs((l_bound - r_bound) + 1) else: return 1 def extract_inputs_outputs(self, verilog_str: List[str], port_list: List[str]): input_dict: Dict[int:(str, int)] = {} output_dict: Dict[int:(str, int)] = {} # example: # for module circuit(a, b, c, d) # input [1:0] a; # input [2:0]b; # output d; # output [3:0]c; # example input_dict = {0:(a, 2), 1:(b, 3)} # example input_dict = {3:(d, 1), 2:(c, 3)} for line in verilog_str: line = line.strip() # remove all whitespaces at the beginning or end of the line # extract inputs if line.startswith('input'): match_obj = re.search('input (.+);', line) # input a, b, c; or input [1:0] a; cur_input_str = match_obj.group(1) # a, b, c or [1:0] a cur_input_list = cur_input_str.strip().replace(" ", "").split(',') # ['a', 'b', 'c'] or ['[1:0]a'] cur_input_list = self.check_multi_vector_declaration(cur_input_list) for inp in cur_input_list: if self.get_name(inp) in port_list: position_in_module_signature = port_list.index(self.get_name(inp)) input_dict[position_in_module_signature] = (self.get_name(inp), self.get_width(inp)) else: raise Exception(f"input name {self.get_name(inp)} is not in the port_list") # extract outputs if line.startswith('output'): match_obj = re.search('output (.+);', line) # input a, b, c; or input [1:0] a; cur_output_str = match_obj.group(1) # a, b, c or [1:0] a cur_output_list = cur_output_str.strip().replace(" ", "").split(',') # ['a', 'b', 'c'] or ['[1:0]a'] cur_output_list = self.check_multi_vector_declaration(cur_output_list) for out in cur_output_list: if self.get_name(out) in port_list: position_in_module_signature = port_list.index(self.get_name(out)) output_dict[position_in_module_signature] = (self.get_name(out), self.get_width(out)) else: raise Exception(f"output name {self.get_name(out)} is not in the port_list") return input_dict, output_dict def extract_module_signature(self, verilog_str: List[str]): """ reads the first line of a Verilog netlist and extracts module and port names :param verilog_str1: the Verilog description as a string :return: modulename as a string variable and port names as a list """ module_name = None port_list = None for line in verilog_str: line = line.strip() # remove whitespaces at the beginning or end of the line if line.startswith('module'): # extract module match_object = re.search('module (\w+)', line) # module adder(a, b, c) module_name = match_object.group(1) # adder # extract port list match_object = re.search('.*\((.+)\).*', line) # module adder(a, b, c) ports_str = match_object.group(1) # a, b, c port_list = ports_str.strip().replace(" ", "").split(',') assert module_name and port_list, f'Either module_name or port_list is None' return module_name, port_list def synthesize_to_gate_level(self, input_path: str, output_path: str): yosys_command = f""" read_verilog {input_path}; synth -flatten; opt; opt_clean -purge; abc -g NAND; opt; opt_clean -purge; splitnets -ports; opt; opt_clean -purge; write_verilog -noattr {output_path}; """ process = subprocess.run(['yosys', '-p', yosys_command], stderr=subprocess.PIPE, stdout=subprocess.PIPE) if process.stderr.decode(): print(f'Error!') raise Exception(f'ERROR!!! yosys cannot do its pass on file {input_path}\n{process.stderr.decode()}') self.rename_variables(output_path, output_path) def rename_variables(self, input_path: str, output_path: str): with open(f'{input_path}', 'r') as infile: verilog_str = infile.readlines() module_name, port_list = self.extract_module_signature(verilog_str) input_dict, output_dict = self.extract_inputs_outputs(verilog_str, port_list) new_labels = self.create_new_labels(port_list, input_dict, output_dict) verilog_str = self.relabel_nodes(verilog_str, new_labels) with open(f'{output_path}', 'w') as outfile: outfile.writelines(verilog_str) def create_new_labels(self, port_list: List, input_dict: Dict, output_dict: Dict): new_labels: Dict = {} for port_idx in input_dict: if input_dict[port_idx][0] == port_list[port_idx]: new_labels[port_list[port_idx]] = f'in{port_idx}' else: raise Exception(f'Error!!! {input_dict[port_idx][0]} is not equal to {port_list[port_idx]}') out_idx = 0 for port_idx in output_dict: if output_dict[port_idx][0] == port_list[port_idx]: new_labels[port_list[port_idx]] = f'out{out_idx}' out_idx += 1 else: raise Exception(f'Error!!! {output_dict[port_idx][0]} is not equal to {port_list[port_idx]}') return new_labels def relabel_nodes(self, verilog_str: List[str], new_labels: Dict): verilog_str_tmp = verilog_str for line_idx, line in enumerate(verilog_str): for key, value in new_labels.items(): if key in line: line = line.replace(key, value) verilog_str_tmp[line_idx] = line return verilog_str_tmp # Deprecated! # def synthesize_to_gate_level(self): # yosys_command = f""" # read_verilog {self.in_path} # synth -flatten # opt # opt_clean -purge # abc -g AND,OR # write_verilog -noattr {self.out_path} # abc -g NAND; # aigmap; # opt; # opt_clean -purge; # write_aiger {self.aig_out_path}; # """ # with open('log.txt', 'w') as y: # subprocess.call([YOSYS, '-p', yosys_command]) def unwrap_variables(self) -> None: """ :return: """ lsoracle_command = f""" read_aig {self.aig_out_path}; write_verilog {self.out_path} """ with open('lsoracle_log.txt', 'w') as f: subprocess.call([LSORACLE, '-c', lsoracle_command]) self.fix_module_name() def fix_module_name(self): with open(self.out_path, 'r') as f: lines = f.readlines() with open(self.out_path, 'w') as g: for idx, line in enumerate(lines): if re.search('top', line): line = line.replace('top', self.name) lines[idx] = line break for line in lines: g.write(line) def create_test_bench(self, samples: 'list[int]' = []): # read a clean verilog # create a test bench for it num = len(self.samples) with open(self.testbench, 'w') as f: modulename, port_list, inp, n_inputs, out, n_outputs = self.extract_module_info() f.write("module " + modulename + "_tb;\n") f.write('reg [' + str(n_inputs - 1) + ':0] pi;\n') f.write('wire [' + str(n_outputs - 1) + ':0] po;\n') f.write(modulename + ' dut(') first = True inp_count = 0 out_count = 0 for i in port_list: if not first: f.write(',') first = False if i in inp: if inp[i] > 1: f.write(' pi[{}:{}] '.format(inp_count + inp[i] - 1, inp_count)) else: f.write(' pi[{}] '.format(inp_count)) inp_count += inp[i] elif i in out: if out[i] > 1: f.write(' po[{}:{}] '.format(out_count + out[i] - 1, out_count)) else: f.write(' po[{}] '.format(out_count)) out_count += out[i] else: print('[Error] Port {} is not defined as input or output.'.format(i)) sys.exit(0) f.write(');\n') f.write("initial\n") f.write("begin\n") for idx, sample in enumerate(self.samples): f.write('# 1 pi=' + str(n_inputs) + '\'b') f.write('{0:0>{1}}'.format(str(bin(sample))[2:], n_inputs)) f.write(';\n') f.write("#1 $display(\"%b\", po);\n") f.write("end\n") f.write("endmodule\n") def extract_module_io(self) -> (int, int): clean_verilog = self.in_path yosys_command = 'read_verilog ' + clean_verilog + '; synth -flatten; opt; opt_clean; techmap; write_verilog ' + self.tmp + ';\n' process = subprocess.run([YOSYS, '-p', yosys_command], stderr=subprocess.PIPE, stdout=subprocess.PIPE) if process.stderr.decode(): print(f'Error!') raise Exception(f'ERROR!!! yosys cannot do its pass on file {clean_verilog}\n{process.stderr.decode()}') with open(self.tmp) as tmp_file: inp = {} inp_count = 0 out = {} out_count = 0 modulename = None line = tmp_file.readline() while line: tokens = re.split('[ ()]', line.strip().strip(';').strip()) if len(tokens) > 0 and tokens[0] == 'module' and modulename is None: modulename = tokens[1] port_list = re.split('[,()]', line.strip().strip(';').strip())[1:] port_list = [s.strip() for s in port_list if s.strip() != ''] if len(tokens) == 2 and (tokens[0] == 'input' or tokens[0] == 'output'): if tokens[0] == 'input': inp[tokens[1]] = 1 inp_count += 1 if tokens[0] == 'output': out[tokens[1]] = 1 out_count += 1 if len(tokens) == 3 and (tokens[0] == 'input' or tokens[0] == 'output'): range_str = tokens[1][1:-1].split(':') range_int = list(map(int, range_str)) length = max(range_int) - min(range_int) + 1 if tokens[0] == 'input': inp[tokens[2]] = length inp_count += length if tokens[0] == 'output': out[tokens[2]] = length out_count += length line = tmp_file.readline() os.remove(self.tmp) return inp_count, out_count def extract_module_info(self) -> 'tuple(str, list(str), dict, int, dict, int)': """ reads a verilog file and extracts the signature :return: a tuple containing the modulename, the list of input and output names, two dictionary that hold the bitwidth of all inputs and outputs, and the number of inputs and outputs """ clean_verilog = self.out_path yosys_command = 'read_verilog ' + clean_verilog + '; synth -flatten; opt; opt_clean; techmap; write_verilog ' + self.tmp + ';\n' subprocess.call([YOSYS, '-p', yosys_command], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) with open(self.tmp) as tmp_file: inp = {} inp_count = 0 out = {} out_count = 0 modulename = None line = tmp_file.readline() while line: tokens = re.split('[ ()]', line.strip().strip(';').strip()) if len(tokens) > 0 and tokens[0] == 'module' and modulename is None: modulename = tokens[1] port_list = re.split('[,()]', line.strip().strip(';').strip())[1:] port_list = [s.strip() for s in port_list if s.strip() != ''] if len(tokens) == 2 and (tokens[0] == 'input' or tokens[0] == 'output'): if tokens[0] == 'input': inp[tokens[1]] = 1 inp_count += 1 if tokens[0] == 'output': out[tokens[1]] = 1 out_count += 1 if len(tokens) == 3 and (tokens[0] == 'input' or tokens[0] == 'output'): range_str = tokens[1][1:-1].split(':') range_int = list(map(int, range_str)) length = max(range_int) - min(range_int) + 1 if tokens[0] == 'input': inp[tokens[2]] = length inp_count += length if tokens[0] == 'output': out[tokens[2]] = length out_count += length line = tmp_file.readline() os.remove(self.tmp) return modulename, port_list, inp, inp_count, out, out_count def run_test_bench(self): iverilog_command = f'{IVERILOG} -o {self.iverilog_out_path} ' \ f'{self.cleaned_verilog} ' \ f'{self.testbench} ' vvp_command = f'{self.iverilog_out_path}' with open(f'{self.iverilog_log_path}', 'w') as f: subprocess.call(iverilog_command, shell=True, stdout=f) with open(f'{self.vvp_out_path}', 'w') as f: subprocess.call([VVP, vvp_command], stdout=f) os.remove(f'{self.iverilog_out_path}') self.set_sample_results(self.import_results()) def export_circuit(self): self.synthesize_to_gate_level(self.in_path, self.out_path) # self.unwrap_variables() def __repr__(self): return f'An object of class Verilog\n' \ f'{self.name = }\n' \ f'{self.in_path = }\n' \ f'{self.out_path = }\n'
z3log
/z3log-1.1.1.tar.gz/z3log-1.1.1/Z3Log/verilog.py
verilog.py
import csv import re from .config.config import * from .utils import * class Stats: def __init__(self, file_path: str): """ stores a csv file contents as a an object where each row of the csv file is an attribute :param file_path: the path to a csv file """ full_name = get_pure_name(file_path) idx = re.search(r'o\d+',full_name) s, e = idx.span() # print(full_name[:e]) self.__name = full_name[:e] self.__experiment = None self.__wce = None self.___runtime = None self.__sat_runtime = None self.__unsat_runtime = None self.__num_sats = None self.__num_unsats = None self.__jumps = None self.__file_in_path = file_path self.import_csv() @property def name(self): return self.__name @property def path(self): return self.__file_in_path @property def experiment(self): return self.__experiment @experiment.setter def experiment(self, experiment): self.__experiment = experiment @property def wce(self): return self.__wce @wce.setter def wce(self, wce): self.__wce = wce @property def total_runtime(self): return self.___runtime @total_runtime.setter def total_runtime(self, total_runtime): self.___runtime = total_runtime @property def sat_runtime(self): return self.__sat_runtime @sat_runtime.setter def sat_runtime(self, sat_runtime): self.__sat_runtime = sat_runtime @property def num_sats(self): return self.__num_sats @num_sats.setter def num_sats(self, num_sats): self.__num_sats = num_sats @property def unsat_runtime(self): return self.__unsat_runtime @unsat_runtime.setter def unsat_runtime(self, unsat_runtime): self.__unsat_runtime = unsat_runtime @property def num_unsats(self): return self.__num_unsats @num_unsats.setter def num_unsats(self, num_unsats): self.__num_unsats = num_unsats @property def jump_list(self): return self.__jumps @jump_list.setter def jump_list(self, jump_list): self.__jumps = jump_list @property def file_path(self): return self.__file_in_path def import_csv(self): with open(self.path, 'r') as f: csvreader = csv.reader(f) for row in csvreader: if re.search(EXPERIMENT, row[0]): self.experiment = row[1] elif re.search(WCE, row[0]): self.wce = row[1] elif re.search(TOTAL_RUNTIME, row[0]): self.total_runtime = row[1] elif re.search(SAT_RUNTIME, row[0]): self.sat_runtime = row[1] elif re.search(UNSAT_RUNTIME, row[0]): self.unsat_runtime = row[1] elif re.search(N_SATS, row[0]): self.num_sats = row[1] elif re.search(N_UNSATS, row[0]): self.num_unsats = row[1] elif re.search(JUMPS, row[0]): self.jump_list = row[1] def __repr__(self): return f'An object of class Stats:\n' \ f'{self.name = }\n' \ f'{self.experiment = }\n' \ f'{self.wce = }\n' \ f'{self.total_runtime = }\n' \ f'{self.sat_runtime = }\n' \ f'{self.unsat_runtime}\n' \ f'{self.num_sats = }\n' \ f'{self.num_unsats = }\n' \ f'{self.jump_list = }\n' \ f''
z3log
/z3log-1.1.1.tar.gz/z3log-1.1.1/Z3Log/stats.py
stats.py
import argparse import sys from .utils import * import typing class Arguments: def __init__(self, tmp_args: argparse): benchmark = get_pure_name(tmp_args.benchmark) approximate_benchmark = get_pure_name(tmp_args.approximate_benchmark) self.__benchmark_name: str = benchmark self.__approximate_benchmark: str = approximate_benchmark self.__mc_samples: int = tmp_args.samples self.__metric: str = tmp_args.metric self.__precision: int = tmp_args.precision self.__strategy: str = tmp_args.strategy self.__optimization: str = tmp_args.optimization self.__experiment: str = tmp_args.experiment self.__pruning_percentage: int = tmp_args.pruning_percentage self.__clean = tmp_args.clean @property def benchmark_name(self): return self.__benchmark_name @property def approximate_benchmark(self): return self.__approximate_benchmark @property def num_samples(self): return self.__mc_samples @property def metric(self): return self.__metric @property def precision(self): return self.__precision @property def strategy(self): return self.__strategy @property def optimization(self): return self.__optimization @property def experiment(self): return self.__experiment @property def pruning_percentage(self): return self.__pruning_percentage # @property # def approach(self): # return self.__approach @property def clean(self): return self.__clean def __repr__(self): return f'An object of class Arguments\n' \ f'{self.benchmark_name = }\n' \ f'{self.approximate_benchmark = }\n' \ f'{self.num_samples = }\n' \ f'{self.metric = }\n' \ f'{self.precision = }\n' \ f'{self.strategy = }\n' \ f'{self.optimization = }\n' \ f'{self.experiment = }\n' \ f'{self.pruning_percentage = }\n' \ f'{self.clean = }\n' @classmethod def parse(cls): my_parser = argparse.ArgumentParser(description='converts different formats to one another', prog=sys.argv[0], usage='%(prog)s benchmark-name|benchmark-path') my_parser.add_argument('benchmark', type=str, default=None, help='benchmark-name') my_parser.add_argument('--samples', '-s', default=100, type=int, help='number-of-monte-carlo-samples') my_parser.add_argument('--approximate_benchmark', '-app', type=str, default=None, help='approximate-benchmark-name in gv/verilog format') my_parser.add_argument('--metric', '-metric', type=str, default=WAE, help='the-desired-worst-case-error-metric') my_parser.add_argument('--precision', '-p', type=int, default=2, help='number-of-decimal-points-for-wre') my_parser.add_argument('--strategy', '-strategy', type=str, default=MONOTONIC, help='the-solver-strategy-to-find-metric') my_parser.add_argument('--optimization', '-opt', type=str, default=None, help='the-solver-optimization (Solver, Optimize, Maximize)') my_parser.add_argument('--experiment', '-e', type=str, default=SINGLE, help="the-experiment-name [SINGLE|QOR|RANDOM]") my_parser.add_argument('--pruning_percentage', '-pp', type=int, default=10, help='gate-percentage-carved-out') my_parser.add_argument('--clean', type=bool, default=False) tmp_args = my_parser.parse_args() return Arguments(tmp_args)
z3log
/z3log-1.1.1.tar.gz/z3log-1.1.1/Z3Log/argument.py
argument.py
import numpy as np import os import copy import csv from typing import * import networkx as nx from subprocess import PIPE from .utils import * from .graph import * class Z3solver: def __init__(self, benchmark_name: str, approximate_benchmark_name: str = None, samples: list = [], experiment: str = SINGLE, pruned_percentage: int = None, pruned_gates=None, metric: str = WAE, precision: int = 4, optimization: str = None): """ :param benchmark_name: the input benchmark in gv format :param approximate_benchmark_name: the approximate benchmark in gv format :param samples: number of samples for the mc evaluation; by defaults it is an empty list """ self.__circuit_name = get_pure_name(benchmark_name) folder, extension = OUTPUT_PATH['gv'] self.__graph_in_path = f'{folder}/{benchmark_name}.{extension}' self.__graph = Graph(benchmark_name, True) self.__pyscript_results_out_path = None folder, extension = LOG_PATH['z3'] os.makedirs(f'{folder}/{benchmark_name}_{Z3}_{LOG}', exist_ok=True) self.__z3_log_path = f'{folder}/{benchmark_name}_{Z3}_{LOG}/{benchmark_name}_{Z3}_{LOG}.{extension}' self.__approximate_verilog_in_path = None self.__approximate_graph = None if approximate_benchmark_name: self.__approximate_circuit_name = approximate_benchmark_name folder, extension = INPUT_PATH['app_gv'] self.__approximate_verilog_in_path = f'{folder}/{approximate_benchmark_name}.{extension}' self.__approximate_graph = Graph(approximate_benchmark_name, True) self.relabel_approximate_graph() self.approximate_graph.set_input_dict(self.approximate_graph.extract_inputs()) self.approximate_graph.set_output_dict(self.approximate_graph.extract_outputs()) self.approximate_graph.set_gate_dict(self.approximate_graph.extract_gates()) self.approximate_graph.set_constant_dict(self.approximate_graph.extract_constants()) self.__labeling_graph = copy.deepcopy(self.approximate_graph) self.__experiment = experiment self.__pruned_percentage = None # TODO # Later create and internal method that can generate pruned gates self.__pruned_gates = None if experiment == RANDOM: self.__pruned_percentage = pruned_percentage self.__pruned_gates = pruned_gates self.__metric = metric self.__precision = precision self.__z3_report = None self.__samples = samples self.__sample_results = None self.__z3string = None self.__z3pyscript = None self.__strategy = None self.__optimization = optimization self.__pyscript_files_for_labeling: list = [] self.__z3_out_path = None @property def name(self): return self.__circuit_name @name.setter def name(self, this_name): self.__circuit_name = this_name @property def approximate_benchmark(self): return self.__approximate_circuit_name @property def graph_in_path(self): return self.__graph_in_path @property def out_path(self): return self.__z3_out_path def set_out_path(self, out_path: str): self.__z3_out_path = out_path @property def z3_log_path(self): return self.__z3_log_path @property def approximate_in_path(self): return self.__approximate_verilog_in_path @property def z3pyscript(self): return self.__z3pyscript @property def strategy(self): return self.__strategy def set_strategy(self, strategy: str): self.__strategy = strategy @property def optimization(self): return self.__optimization @optimization.setter def optimization(self, optimization): self.__optimization = optimization @property def metric(self): return self.__metric @metric.setter def metric(self, metric): self.__metric = metric @property def precision(self): return self.__precision @precision.setter def precision(self, precision): self.__precision = precision @property def experiment(self): return self.__experiment @experiment.setter def experiment(self, experiment): self.__experiment = experiment @property def pruned_percentage(self): return self.__pruned_percentage @pruned_percentage.setter def pruned_percentage(self, pruned_percentage): self.__pruned_percentage = pruned_percentage @property def pruned_gates(self): return self.__pruned_gates @pruned_gates.setter def pruned_gates(self, pruned_gates: List[int]): self.__pruned_gates = pruned_gates @property def z3_report(self): return self.__z3_report def set_z3_report(self, z3_report: str): self.__z3_report = z3_report @property def pyscript_files_for_labeling(self): return self.__pyscript_files_for_labeling def set_pyscript_files_for_labeling(self, pyscript_files_for_labeling): self.__pyscript_files_for_labeling = pyscript_files_for_labeling def append_pyscript_files_for_labeling(self, pyscript_file): self.__pyscript_files_for_labeling.append(pyscript_file) # TODO @property def z3string(self): return self.__z3string @property def samples(self): return self.__samples def set_samples(self, samples: np.array or list): self.__samples = samples @property def sample_results(self): return self.__sample_results def set_sample_results(self, results): self.__sample_results = results def import_results(self): arr = [] with open(self.pyscript_results_out_path, 'r') as f: lines = f.readlines() for line in lines: line = line.replace('\n', '') arr.append(int(line)) results = np.array(arr) return results def append_z3string(self, new_string): self.__z3string = f'{self.__z3string}\n' \ f'{new_string}' def set_z3string(self, new_string): self.__z3string = new_string @property def pyscript_results_out_path(self): return self.__pyscript_results_out_path def set_pyscript_results_out_path(self, pyscript_results_out_path: str): self.__pyscript_results_out_path = pyscript_results_out_path @property def graph(self): return self.__graph @property def approximate_graph(self): return self.__approximate_graph def set_approximate_graph(self, tmp_graph): self.__approximate_graph = tmp_graph @property def labeling_graph(self): return self.__labeling_graph def label_circuit(self, constant_value: bool = False): self.experiment = SINGLE self.set_strategy(MONOTONIC) removed_gate = [] for key in self.labeling_graph.gate_dict: removed_gate = [self.labeling_graph.gate_dict[key]] self.create_pruned_z3pyscript_approximate(removed_gate, constant_value) self.run_z3pyscript_labeling() return self.import_labels(constant_value) def import_labels(self, constant_value: bool=False) -> Dict: label_dict: Dict[str, int] = {} folder, extension = OUTPUT_PATH['report'] all_dirs = [f for f in os.listdir(folder)] # print(f'{all_dirs = }') relevant_dir = None for dir in all_dirs: if re.search(self.approximate_benchmark, dir) and os.path.isdir(f'{folder}/{dir}') and re.search(f'{constant_value}', dir): relevant_dir = f'{folder}/{dir}' # print(f'{relevant_dir = }') all_csv = [f for f in os.listdir(relevant_dir)] for report in all_csv: if re.search(self.approximate_benchmark, report) and report.endswith(extension): gate_label = re.search('(g\d+)', report).group(1) with open(f'{relevant_dir}/{report}', 'r') as r: csvreader = csv.reader(r) for line in csvreader: if re.search(WCE, line[0]): gate_wce = int(line[1]) label_dict[gate_label] = gate_wce return label_dict # TODO # Deprecated def import_z3_expression(self): pass def set_z3pyscript(self, this_script): self.__z3pyscript = this_script def relabel_approximate_graph(self): gate_mapping = {} constant_mapping = {} output_mapping = {} for key in self.approximate_graph.gate_dict.keys(): gate_mapping[self.approximate_graph.gate_dict[key]] = f'app_{self.approximate_graph.gate_dict[key]}' for key in self.approximate_graph.constant_dict.keys(): constant_mapping[ self.approximate_graph.constant_dict[key]] = f'app_{self.approximate_graph.constant_dict[key]}' for key in self.approximate_graph.output_dict.keys(): output_mapping[self.approximate_graph.output_dict[key]] = f'app_{self.approximate_graph.output_dict[key]}' self.approximate_graph.set_graph(nx.relabel_nodes(self.approximate_graph.graph, gate_mapping)) self.approximate_graph.set_graph(nx.relabel_nodes(self.approximate_graph.graph, constant_mapping)) self.approximate_graph.set_graph(nx.relabel_nodes(self.approximate_graph.graph, output_mapping)) def convert_gv_to_z3pyscript_test(self): folder, extension = OUTPUT_PATH['report'] os.makedirs(f'{folder}/{self.name}', exist_ok=True) self.set_z3_report(f'{folder}/{self.name}/{self.name}_{TEST}.{extension}') folder, extension = OUTPUT_PATH['z3'] os.makedirs(f'{folder}/{self.name}', exist_ok=True) self.set_out_path(f'{folder}/{self.name}/{self.name}_{TEST}.{extension}') folder, extension = TEST_PATH['z3'] os.makedirs(f'{folder}/{self.name}', exist_ok=True) self.set_pyscript_results_out_path(f'{folder}/{self.name}/{self.name}_{TEST}.{extension}') import_string = self.create_imports() abs_function = self.create_abs_function() exact_circuit_declaration = self.declare_original_circuit() exact_circuit_expression = self.express_original_circuit() # TODO: Fix Later if self.metric == WHD: output_declaration = '' print(f'ERROR!!! Right now testing is not possible on WHD!') else: output_declaration = self.declare_original_output() exact_function = self.declare_original_function() solver = self.declare_solver() sample_expression = self.express_samples() store_results = self.store_results() self.set_z3pyscript(import_string + abs_function + exact_circuit_declaration + exact_circuit_expression + output_declaration + exact_function + solver + sample_expression + store_results) def convert_gv_to_z3pyscript_maxerror_qor(self, strategy: str = DEFAULT_STRATEGY): self.experiment = QOR self.set_strategy(strategy) if self.metric == WRE: folder, extension = OUTPUT_PATH['report'] if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): self.set_z3_report( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{self.optimization}.{extension}') else: self.set_z3_report( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}.{extension}') folder, extension = OUTPUT_PATH['z3'] if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): self.set_out_path( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{self.optimization}.{extension}') else: self.set_out_path( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}.{extension}') else: folder, extension = OUTPUT_PATH['report'] if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): self.set_z3_report( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}_{self.optimization}.{extension}') else: self.set_z3_report( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}.{extension}') folder, extension = OUTPUT_PATH['z3'] if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): self.set_out_path( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}_{self.optimization}.{extension}') else: self.set_out_path( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}.{extension}') import_string = self.create_imports() abs_function = self.create_abs_function() # exact_part original_circuit_declaration = self.declare_original_circuit() original_circuit_expression = self.express_original_circuit() if self.metric == WHD: original_output_declaration = 'Blah Blah Blah\n' else: original_output_declaration = self.declare_original_output() # approximate_part approximate_circuit_declaration = self.declare_approximate_circuit() approximate_circuit_expression = self.express_approximate_circuit() if self.metric == WHD: approximate_output_declaration = 'Blah Blah Blah\n' else: approximate_output_declaration = self.declare_approximate_output() # error distance function declare_error_distance_function = self.declare_error_distance_function() # strategy strategy = self.express_strategy() self.set_z3pyscript(import_string + abs_function + original_circuit_declaration + original_circuit_expression + original_output_declaration + approximate_circuit_declaration + approximate_circuit_expression + approximate_output_declaration + declare_error_distance_function + strategy) def convert_gv_to_z3pyscript_maxerror_labeling(self, strategy: str = DEFAULT_STRATEGY): self.experiment = SINGLE self.set_strategy(strategy) removed_gate = [] for key in self.graph.input_dict: removed_gate = [self.graph.input_dict[key]] self.create_pruned_z3pyscript(removed_gate) for key in self.graph.gate_dict: removed_gate = [self.graph.gate_dict[key]] self.create_pruned_z3pyscript(removed_gate) def convert_gv_to_z3pyscript_maxerror_random_pruning(self, strategy: str = DEFAULT_STRATEGY): self.experiment = RANDOM self.set_strategy(strategy) removed_gates = [] for idx in self.pruned_gates: if idx < self.graph.num_inputs: # remove pi removed_gates.append(self.graph.input_dict[idx]) else: # remove gate removed_gates.append(self.graph.gate_dict[idx - self.graph.num_inputs + 1]) # print(f'{removed_gates}') self.create_pruned_z3pyscript(removed_gates) # TODO # Naming problems for more than one gate removal def create_pruned_z3pyscript(self, gates: list, constant_value: bool = False): self.create_pruned_graph_approximate(gates, constant_value) if self.experiment == SINGLE: gate = gates[0] # TODO elif self.experiment == RANDOM: gate = 'id0' folder, extension = OUTPUT_PATH['report'] if self.metric == WRE: if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): folder = f'{folder}/{self.name}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{self.optimization}' os.makedirs(folder, exist_ok=True) self.set_z3_report( f'{folder}/{self.name}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{self.optimization}_{gate}.{extension}') else: folder = f'{folder}/{self.name}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}' os.makedirs(folder, exist_ok=True) self.set_z3_report( f'{folder}/{self.name}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{gate}.{extension}') else: if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): folder = f'{folder}/{self.name}_{self.experiment}_{self.metric}_{self.strategy}_{self.optimization}' os.makedirs(folder, exist_ok=True) self.set_z3_report( f'{folder}/{self.name}_{self.experiment}_{self.metric}_{self.strategy}_{self.optimization}_{gate}.{extension}') else: folder = f'{folder}/{self.name}_{self.experiment}_{self.metric}_{self.strategy}' os.makedirs(folder, exist_ok=True) self.set_z3_report( f'{folder}/{self.name}_{self.experiment}_{self.metric}_{self.strategy}_{gate}.{extension}') folder, extension = OUTPUT_PATH['z3'] if self.metric == WRE: if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): folder = f'{folder}/{self.name}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{self.optimization}' os.makedirs(folder, exist_ok=True) self.set_out_path( f'{folder}/{self.name}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{self.optimization}_{gate}.{extension}') else: folder = f'{folder}/{self.name}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}' os.makedirs(folder, exist_ok=True) self.set_out_path( f'{folder}/{self.name}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{gate}.{extension}') else: if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): folder = f'{folder}/{self.name}_{self.experiment}_{self.metric}_{self.strategy}_{self.optimization}' os.makedirs(folder, exist_ok=True) self.set_out_path( f'{folder}/{self.name}_{self.experiment}_{self.metric}_{self.strategy}_{self.optimization}_{gate}.{extension}') else: folder = f'{folder}/{self.name}_{self.experiment}_{self.metric}_{self.strategy}' os.makedirs(folder, exist_ok=True) self.set_out_path( f'{folder}/{self.name}_{self.experiment}_{self.metric}_{self.strategy}_{gate}.{extension}') self.append_pyscript_files_for_labeling(self.out_path) import_string = self.create_imports() abs_function = self.create_abs_function() # exact_part original_circuit_declaration = self.declare_original_circuit() original_circuit_expression = self.express_original_circuit() if self.metric == WHD: original_output_declaration = f'\n' else: original_output_declaration = self.declare_original_output() approximate_circuit_declaration = self.declare_approximate_circuit() approximate_circuit_expression = self.express_approximate_circuit() if self.metric == WHD: xor_miter_declaration = self.declare_xor_miter() else: approximate_output_declaration = self.declare_approximate_output() # error distance function declare_error_distance_function = self.declare_error_distance_function() # strategy strategy = self.express_strategy() if self.metric == WHD: self.set_z3pyscript( import_string + abs_function + original_circuit_declaration + original_circuit_expression + approximate_circuit_expression + xor_miter_declaration + declare_error_distance_function + strategy) else: self.set_z3pyscript( import_string + abs_function + original_circuit_declaration + original_circuit_expression + original_output_declaration + approximate_circuit_declaration + approximate_circuit_expression + approximate_output_declaration + declare_error_distance_function + strategy) self.export_z3pyscript() def create_pruned_z3pyscript_approximate(self, gates: list, constant_value: bool = False): self.create_pruned_graph_approximate(gates, constant_value) if self.experiment == SINGLE: gate = gates[0] # TODO elif self.experiment == RANDOM: gate = 'id0' folder, extension = OUTPUT_PATH['report'] if self.metric == WRE: if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): folder = f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{self.optimization}_{constant_value}' os.makedirs(folder, exist_ok=True) self.set_z3_report( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{self.optimization}_{gate}.{extension}') else: folder = f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{constant_value}' os.makedirs(folder, exist_ok=True) self.set_z3_report( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{gate}.{extension}') else: if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): folder = f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}_{self.optimization}_{constant_value}' os.makedirs(folder, exist_ok=True) self.set_z3_report( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}_{self.optimization}_{gate}.{extension}') else: folder = f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}_{constant_value}' os.makedirs(folder, exist_ok=True) self.set_z3_report( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}_{gate}.{extension}') folder, extension = OUTPUT_PATH['z3'] if self.metric == WRE: if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): folder = f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{self.optimization}_{constant_value}' os.makedirs(folder, exist_ok=True) self.set_out_path( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{self.optimization}_{gate}.{extension}') else: folder = f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{constant_value}' os.makedirs(folder, exist_ok=True) self.set_out_path( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{gate}.{extension}') else: if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): folder = f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}_{self.optimization}_{constant_value}' os.makedirs(folder, exist_ok=True) self.set_out_path( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}_{self.optimization}_{gate}.{extension}') else: folder = f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}_{constant_value}' os.makedirs(folder, exist_ok=True) self.set_out_path( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}_{gate}.{extension}') self.append_pyscript_files_for_labeling(self.out_path) import_string = self.create_imports() abs_function = self.create_abs_function() # exact_part original_circuit_declaration = self.declare_original_circuit() original_circuit_expression = self.express_original_circuit() if self.metric == WHD: original_output_declaration = f'\n' else: original_output_declaration = self.declare_original_output() approximate_circuit_declaration = self.declare_approximate_circuit() approximate_circuit_expression = self.express_approximate_circuit() if self.metric == WHD: xor_miter_declaration = self.declare_xor_miter() else: approximate_output_declaration = self.declare_approximate_output() # error distance function declare_error_distance_function = self.declare_error_distance_function() # strategy strategy = self.express_strategy() if self.metric == WHD: self.set_z3pyscript( import_string + abs_function + original_circuit_declaration + original_circuit_expression + approximate_circuit_expression + xor_miter_declaration + declare_error_distance_function + strategy) else: self.set_z3pyscript( import_string + abs_function + original_circuit_declaration + original_circuit_expression + original_output_declaration + approximate_circuit_declaration + approximate_circuit_expression + approximate_output_declaration + declare_error_distance_function + strategy) self.export_z3pyscript() def convert_gv_to_z3pyscript_xpat(self): pass def create_pruned_graph(self, gates: list): tmp_graph = copy.deepcopy(self.graph) self.set_approximate_graph(tmp_graph) mapping_dict = {} for gate in gates: if self.graph.is_pi(gate) or self.graph.is_cleaned_pi(gate) or self.graph.is_pruned_pi(gate): mapping_dict[gate] = f'app_{gate}' for gate in gates: self.approximate_graph.graph.nodes[gate][PRUNED] = True self.approximate_graph.set_graph(nx.relabel_nodes(self.approximate_graph.graph, mapping_dict)) self.relabel_approximate_graph() self.approximate_graph.set_input_dict(self.approximate_graph.extract_inputs()) self.approximate_graph.set_output_dict(self.approximate_graph.extract_outputs()) self.approximate_graph.set_gate_dict(self.approximate_graph.extract_gates()) self.approximate_graph.set_constant_dict(self.approximate_graph.extract_constants()) def create_pruned_graph_approximate(self, gates: list, constant_value: bool =False): tmp_graph = copy.deepcopy(self.labeling_graph) self.set_approximate_graph(tmp_graph) mapping_dict = {} for gate in gates: if self.labeling_graph.is_pi(gate) or self.labeling_graph.is_cleaned_pi(gate) or self.labeling_graph.is_pruned_pi(gate): mapping_dict[gate] = f'{gate}' for gate in gates: self.approximate_graph.graph.nodes[gate][PRUNED] = constant_value self.approximate_graph.set_graph(nx.relabel_nodes(self.approximate_graph.graph, mapping_dict)) self.relabel_approximate_graph() self.approximate_graph.set_input_dict(self.approximate_graph.extract_inputs()) self.approximate_graph.set_output_dict(self.approximate_graph.extract_outputs()) self.approximate_graph.set_gate_dict(self.approximate_graph.extract_gates()) self.approximate_graph.set_constant_dict(self.approximate_graph.extract_constants()) # TODO # for other back-ends as well def declare_error_distance_function(self): ed_function = '' if self.metric == WAE: ed_function += f"f_exact = Function('f_exact', IntSort(), IntSort())\n" \ f"f_approx = Function('f_approx', IntSort(), IntSort())\n" ed_function += f"f_error = Function('f_error', IntSort(), IntSort(), IntSort())\n" elif self.metric == WHD: ed_function += f"f_error = Function('f_error', IntSort(), " for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: ed_function += f"IntSort() )\n" else: ed_function += f"IntSort(), " elif self.metric == WRE: ed_function += f"f_exact = Function('f_exact', IntSort(), IntSort())\n" \ f"f_approx = Function('f_approx', IntSort(), IntSort())\n" ed_function += f"f_error = Function('f_error', IntSort(), IntSort(), RealSort())\n" ed_function += f'\n' return ed_function def express_strategy(self, metric: str = None): strategy_expressed = '' if re.search(MONOTONIC, self.strategy): strategy_expressed += self.express_monotonic_strategy() elif re.search(BISECTION, self.strategy): strategy_expressed += self.express_bisection_strategy() elif re.search(MC, self.strategy): strategy_expressed += self.express_mc_strategy() elif re.search(KIND_BISECTION, self.strategy): strategy_expressed += self.express_kind_bisection_strategy() else: print(f'ERROR!!! no strategy is specified!') exit() return strategy_expressed def declare_stats(self): stats = '' stats = f'foundWCE = False\n' \ f'stats: dict = {{}}\n' \ f"stats['wce'] = 0\n" if self.metric == WAE: stats += f"stats['et'] = 0\n" elif self.metric == WHD: stats += f"stats['et'] = 0\n" elif self.metric == WRE: stats += f"stats['et'] = float(\"{{:.{self.precision}f}}\".format(0))\n" stats += f"stats['num_sats'] = 0\n" \ f"stats['num_unsats'] = 0\n" \ f"stats['sat_runtime'] = 0.0\n" \ f"stats['unsat_runtime'] = 0.0\n" \ f"stats['jumps'] = []\n" if self.metric == WAE or self.metric == WRE: stats += f"max = (2 ** {self.graph.num_outputs}) -1\n" elif self.metric == WHD: stats += f"max = {self.graph.num_outputs}\n" return stats def express_mc_while_loop(self): loop = '' loop += f's=Solver()\n' \ f'start_whole = time.time()\n' for sample in self.samples: loop += f's.push()\n' \ f's.add(f_error(exact_out, approx_out) == z3_abs(exact_out - approx_out))\n' \ f'{self.express_push_input_sample(sample)}' \ f'response=s.check()\n' \ f'returned_model = s.model()\n' \ f'returned_value = abs(int(returned_model[f_error].else_value().as_long()))\n' \ f'returned_value_reval = abs(int(returned_model.evaluate(f_error(exact_out, approx_out)).as_long()))\n' \ f'if returned_value == returned_value_reval:\n' \ f"{TAB}print(f'double-check is passed!')\n" \ f"else:\n" \ f"{TAB}print(f'ERROR!!! double-check failed! exiting...')\n" \ f"{TAB}exit()\n" \ f"if returned_value > stats['wce']:\n" \ f"{TAB}stats['wce'] = returned_value\n" \ f"s.pop()\n" \ f"\n" \ f"" loop += self.express_stats() return loop def express_push_input_sample(self, sample: int): sample_expression = '' s_expression = [True if i == '1' else False for i in list(f'{sample:0{self.graph.num_inputs}b}')] s_expression.reverse() sample_expression += f's.add(' for idx, e in enumerate(s_expression): if idx == len(s_expression) - 1: sample_expression += f'{self.graph.input_dict[idx]}=={e})\n' else: sample_expression += f'{self.graph.input_dict[idx]}=={e}, ' return sample_expression def express_kind_bisection_while_loop(self): loop = '' if self.metric == WAE or self.metric == WRE: loop += f'upper_bound = 2**({self.graph.num_outputs}) - 1\n' \ f'lower_bound = 0 \n' \ f'start_whole = time.time()\n' else: loop += f'upper_bound = {self.graph.num_outputs}\n' \ f'lower_bound = 0 \n' \ f'start_whole = time.time()\n' loop += f's = Solver()\n' loop += f'while(not foundWCE):\n' if self.metric == WAE: loop += f"{TAB}stats['et'] = (upper_bound + lower_bound) // 2\n" elif self.metric == WHD: loop += f"{TAB}stats['et'] = (upper_bound + lower_bound) // 2\n" elif self.metric == WRE: loop += f"{TAB}import math\n" loop += f"{TAB}stats['et'] = math.floor((float(upper_bound + lower_bound) / 2) * {10 ** self.precision}) / {10 ** self.precision}\n" # Check termination if self.metric == WAE: loop += f"{TAB}if upper_bound - lower_bound <= 1:\n" \ f"{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}if stats['et'] in stats['jumps']:\n" \ f"{TAB}{TAB}{TAB}break\n" elif self.metric == WHD: loop += f"{TAB}if upper_bound - lower_bound <= 1:\n" \ f"{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}if lower_bound == 0:\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = upper_bound\n" \ f"{TAB}{TAB}if stats['et'] in stats['jumps']:\n" \ f"{TAB}{TAB}{TAB}break\n" elif self.metric == WRE: loop += f"{TAB}if stats['et'] == lower_bound:\n" \ f"{TAB}{TAB}if stats['et'] in stats['jumps']:\n" \ f"{TAB}{TAB}{TAB}if lower_bound == 0:\n" \ f"{TAB}{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = upper_bound\n" loop += f"{TAB}elif round(upper_bound - lower_bound, 2) <= (10 ** -{self.precision}):\n" \ f"{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}if stats['et'] in stats['jumps']:\n" \ f"{TAB}{TAB}{TAB}break\n" loop += f"{TAB}if stats['et'] not in stats['jumps']:\n" \ f"{TAB}{TAB}stats['jumps'].append(stats['et'])\n" loop += f'{TAB}start_iteration = time.time()\n' \ f'{TAB}s.push()\n' if self.metric == WAE or self.metric == WRE: loop += f'{TAB}s.add(f_exact(exact_out) == exact_out)\n' \ f'{TAB}s.add(f_approx(approx_out) == approx_out)\n' if self.metric == WAE: loop += f'{TAB}s.add(f_error(exact_out, approx_out) == exact_out - approx_out)\n' \ f"{TAB}s.add(z3_abs(f_error(exact_out, approx_out)) > stats['et'])\n" elif self.metric == WHD: if self.optimization == MAXIMIZE and (self.strategy != BISECTION): pass else: loop += f"{TAB}s.add(f_error(" for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: loop += f"o{i}_{XOR}_{INT}) == " else: loop += f"o{i}_{XOR}_{INT}, " for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: loop += f"o{i}_{XOR}_{INT})\n" else: loop += f"o{i}_{XOR}_{INT} + " loop += f"{TAB}s.add(f_error(" for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: loop += f"o{i}_{XOR}_{INT}) > stats['et'])\n" else: loop += f"o{i}_{XOR}_{INT}, " # TODO elif self.metric == WRE: loop += f'{TAB}s.add(f_error(exact_out, approx_out) == z3_abs(exact_out - approx_out) / (z3_abs(exact_out) + z3_abs(1.0)) )\n' \ f"{TAB}s.add(z3_abs(f_error(exact_out, approx_out)) > stats['et'])\n" loop += f"{TAB}response = s.check()\n" loop += self.express_kind_bisection_while_loop_sat() loop += self.express_kind_bisection_while_loop_unsat() loop += self.express_stats() return loop def express_bisection_while_loop(self): loop = '' if self.metric == WAE or self.metric == WRE: loop += f'upper_bound = 2**({self.graph.num_outputs}) - 1\n' \ f'lower_bound = 0 \n' \ f'start_whole = time.time()\n' else: loop += f'upper_bound = {self.graph.num_outputs}\n' \ f'lower_bound = 0 \n' \ f'start_whole = time.time()\n' loop += f's = Solver()\n' loop += f'while(not foundWCE):\n' if self.metric == WAE: loop += f"{TAB}stats['et'] = (upper_bound + lower_bound) // 2\n" elif self.metric == WHD: loop += f"{TAB}stats['et'] = (upper_bound + lower_bound) // 2\n" elif self.metric == WRE: loop += f"{TAB}import math\n" loop += f"{TAB}stats['et'] = math.floor((float(upper_bound + lower_bound) / 2) * {10 ** self.precision}) / {10 ** self.precision}\n" # Check termination if self.metric == WAE: loop += f"{TAB}if upper_bound - lower_bound <= 1:\n" \ f"{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}if lower_bound == 0:\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = upper_bound\n" \ f"{TAB}{TAB}if stats['et'] in stats['jumps']:\n" \ f"{TAB}{TAB}{TAB}break\n" elif self.metric == WHD: loop += f"{TAB}if upper_bound - lower_bound <= 1:\n" \ f"{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}if lower_bound == 0:\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = upper_bound\n" \ f"{TAB}{TAB}if stats['et'] in stats['jumps']:\n" \ f"{TAB}{TAB}{TAB}break\n" elif self.metric == WRE: loop += f"{TAB}if stats['et'] == lower_bound:\n" \ f"{TAB}{TAB}if stats['et'] in stats['jumps']:\n" \ f"{TAB}{TAB}{TAB}if lower_bound == 0:\n" \ f"{TAB}{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = upper_bound\n" loop += f"{TAB}if round(upper_bound - lower_bound, 2) <= (10 ** -{self.precision}):\n" \ f"{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}if lower_bound == 0:\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = upper_bound\n" \ f"{TAB}{TAB}if stats['et'] in stats['jumps']:\n" \ f"{TAB}{TAB}{TAB}break\n" loop += f"{TAB}if stats['et'] not in stats['jumps']:\n" \ f"{TAB}{TAB}stats['jumps'].append(stats['et'])\n" loop += f'{TAB}start_iteration = time.time()\n' \ f'{TAB}s.push()\n' if self.metric == WAE or self.metric == WRE: loop += f'{TAB}s.add(f_exact(exact_out) == exact_out)\n' \ f'{TAB}s.add(f_approx(approx_out) == approx_out)\n' if self.metric == WAE: loop += f'{TAB}s.add(f_error(exact_out, approx_out) == exact_out - approx_out)\n' \ f"{TAB}s.add(z3_abs(f_error(exact_out, approx_out)) > stats['et'])\n" elif self.metric == WHD: if self.optimization == MAXIMIZE and (self.strategy != BISECTION): pass else: loop += f"{TAB}s.add(f_error(" for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: loop += f"o{i}_{XOR}_{INT}) == " else: loop += f"o{i}_{XOR}_{INT}, " for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: loop += f"o{i}_{XOR}_{INT})\n" else: loop += f"o{i}_{XOR}_{INT} + " loop += f"{TAB}s.add(f_error(" for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: loop += f"o{i}_{XOR}_{INT}) > stats['et'])\n" else: loop += f"o{i}_{XOR}_{INT}, " # TODO elif self.metric == WRE: loop += f'{TAB}s.add(f_error(exact_out, approx_out) == z3_abs(exact_out - approx_out) / (z3_abs(exact_out) + z3_abs(1.0)) )\n' \ f"{TAB}s.add(z3_abs(f_error(exact_out, approx_out)) > stats['et'])\n" loop += f"{TAB}response = s.check()\n" loop += self.express_bisection_while_loop_sat() loop += self.express_bisection_while_loop_unsat() loop += self.express_stats() return loop def express_monotonic_while_loop(self): loop = '' loop += f'start_whole = time.time()\n' # print(f'{self.optimization == MAXIMIZE = }') # print(f'{self.optimization = }') if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): loop += f's = Optimize()\n' else: # print('We are here') loop += f's = Solver()\n' loop += f"stats['jumps'].append(stats['et'])\n" \ f'while(not foundWCE):\n' \ f'{TAB}start_iteration = time.time()\n' \ f'{TAB}s.push()\n' if self.metric == WAE or self.metric == WRE: loop += f'{TAB}s.add(f_exact(exact_out) == exact_out)\n' \ f'{TAB}s.add(f_approx(approx_out) == approx_out)\n' if self.metric == WAE: if self.optimization == MAXIMIZE and (self.strategy != BISECTION): loop += f'{TAB}s.add(f_error(exact_out, approx_out) == exact_out - approx_out)\n' \ f"{TAB}s.add(z3_abs(f_error(exact_out, approx_out)) > stats['et'])\n" \ f"{TAB}s.maximize(z3_abs(f_error(exact_out, approx_out)))\n" else: loop += f'{TAB}s.add(f_error(exact_out, approx_out) == exact_out - approx_out)\n' \ f"{TAB}s.add(z3_abs(f_error(exact_out, approx_out)) > stats['et'])\n" # TODO add optimization thingy right here elif self.metric == WHD: if self.optimization == MAXIMIZE and (self.strategy != BISECTION): pass else: loop += f"{TAB}s.add(f_error(" for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: loop += f"o{i}_{XOR}_{INT}) == " else: loop += f"o{i}_{XOR}_{INT}, " for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: loop += f"o{i}_{XOR}_{INT})\n" else: loop += f"o{i}_{XOR}_{INT} + " loop += f"{TAB}s.add(f_error(" for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: loop += f"o{i}_{XOR}_{INT}) > stats['et'])\n" else: loop += f"o{i}_{XOR}_{INT}, " # TODO elif self.metric == WRE: if self.optimization == MAXIMIZE and (self.strategy != BISECTION): loop += f'{TAB}s.add(f_error(exact_out, approx_out) == z3_abs(exact_out - approx_out) / (z3_abs(exact_out) + z3_abs(1.0)) )\n' \ f"{TAB}s.add(z3_abs(f_error(exact_out, approx_out)) > stats['et'])\n" \ f"{TAB}s.maximize(z3_abs(f_error(exact_out, approx_out)))\n" else: loop += f'{TAB}s.add(f_error(exact_out, approx_out) == z3_abs(exact_out - approx_out) / (z3_abs(exact_out) + z3_abs(1.0)) )\n' \ f"{TAB}s.add(z3_abs(f_error(exact_out, approx_out)) > stats['et'])\n" loop += f"{TAB}response = s.check()\n" loop += self.express_monotonic_while_loop_sat() loop += self.express_monotonic_while_loop_unsat() loop += self.express_stats() return loop def express_kind_bisection_while_loop_sat(self): if_sat = '' if_sat += f"{TAB}if response == sat:\n" \ f"{TAB}{TAB}print(f'sat')\n" \ f"{TAB}{TAB}end_iteration = time.time()\n" \ f"{TAB}{TAB}returned_model = s.model()\n" \ f"{TAB}{TAB}print(f\"{{returned_model[f_error].else_value() = }}\")\n" if self.metric == WAE: if_sat += f"{TAB}{TAB}returned_value = abs(int(returned_model[f_error].else_value().as_long()))\n" \ f"{TAB}{TAB}returned_value_reval = abs(int(returned_model.evaluate(f_error(exact_out, approx_out)).as_long()))\n" elif self.metric == WHD: if_sat += f"{TAB}{TAB}returned_value = abs(int(returned_model[f_error].else_value().as_long()))\n" if_sat += f"{TAB}{TAB}returned_value_reval = abs(int(returned_model.evaluate(f_error(" for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: if_sat += f"o{i}_{XOR}_{INT})).as_long()))\n" else: if_sat += f"o{i}_{XOR}_{INT}, " # TODO elif self.metric == WRE: if_sat += f"{TAB}{TAB}returned_value = ((returned_model[f_error].else_value().as_decimal({self.precision})))\n" \ f"{TAB}{TAB}returned_value_reval = ((returned_model.evaluate(f_error(exact_out, approx_out)).as_decimal({self.precision})))\n" # Double-check if_sat += f"{TAB}{TAB}if returned_value == returned_value_reval:\n" \ f"{TAB}{TAB}{TAB}print(f'double-check is passed!')\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}print(f'ERROR!!! double-check failed! exiting...')\n" \ f"{TAB}{TAB}{TAB}exit()\n" if self.metric == WRE: if_sat += f"{TAB}{TAB}if returned_value[-1] == '?':\n" \ f"{TAB}{TAB}{TAB}print('removing the last question mark!')\n" \ f"{TAB}{TAB}{TAB}returned_value = abs(float(returned_value[:-1])) + 10 ** -({self.precision})\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}returned_value = abs(float(returned_value))\n" if self.metric == WAE: if_sat += f"{TAB}{TAB}if upper_bound - lower_bound <= 1:\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = returned_value\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}lower_bound = returned_value\n" elif self.metric == WHD: if_sat += f"{TAB}{TAB}if upper_bound - lower_bound <= 1:\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = returned_value\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}lower_bound = returned_value\n" elif self.metric == WRE: if_sat += f"{TAB}{TAB}if round(upper_bound - lower_bound, 2) <= (10 ** -{self.precision}):\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = float(\"{{:.{self.precision}f}}\".format(returned_value))\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}lower_bound = float(\"{{:.{self.precision}f}}\".format(returned_value))\n" if_sat += f"{TAB}{TAB}stats['num_sats'] += 1\n" \ f"{TAB}{TAB}stats['sat_runtime'] += (end_iteration - start_iteration)\n" \ f"{TAB}{TAB}if stats['et'] == max:\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = stats['et']\n" return if_sat def express_bisection_while_loop_sat(self): if_sat = '' if_sat += f"{TAB}if response == sat:\n" \ f"{TAB}{TAB}print(f'sat')\n" \ f"{TAB}{TAB}end_iteration = time.time()\n" \ f"{TAB}{TAB}returned_model = s.model()\n" \ f"{TAB}{TAB}print(f'{{returned_model = }}')\n" if self.metric == WAE or self.metric == WRE: f"{TAB}{TAB}print(f\"{{returned_model[f_exact].else_value() = }}\")\n" \ f"{TAB}{TAB}print(f\"{{returned_model[f_approx].else_value() = }}\")\n" \ f"{TAB}{TAB}print(f\"{{returned_model[f_error].else_value() = }}\")\n" elif self.metric == WHD: f"{TAB}{TAB}print(f\"{{returned_model[f_error].else_value() = }}\")\n" if self.metric == WAE: if_sat += f"{TAB}{TAB}returned_value = abs(int(returned_model[f_error].else_value().as_long()))\n" \ f"{TAB}{TAB}returned_value_reval = abs(int(returned_model.evaluate(f_error(exact_out, approx_out)).as_long()))\n" elif self.metric == WHD: if_sat += f"{TAB}{TAB}returned_value = abs(int(returned_model[f_error].else_value().as_long()))\n" if_sat += f"{TAB}{TAB}returned_value_reval = abs(int(returned_model.evaluate(f_error(" for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: if_sat += f"o{i}_{XOR}_{INT})).as_long()))\n" else: if_sat += f"o{i}_{XOR}_{INT}, " # TODO elif self.metric == WRE: if_sat += f"{TAB}{TAB}returned_value = ((returned_model[f_error].else_value().as_decimal({self.precision})))\n" \ f"{TAB}{TAB}returned_value_reval = ((returned_model.evaluate(f_error(exact_out, approx_out)).as_decimal({self.precision})))\n" if_sat += f"{TAB}{TAB}if returned_value == returned_value_reval:\n" \ f"{TAB}{TAB}{TAB}print(f'double-check is passed!')\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}print(f'ERROR!!! double-check failed! exiting...')\n" \ f"{TAB}{TAB}{TAB}exit()\n" if self.metric == WRE: if_sat += f"{TAB}{TAB}if returned_value[-1] == '?':\n" \ f"{TAB}{TAB}{TAB}print('removing the last question mark!')\n" \ f"{TAB}{TAB}{TAB}returned_value = abs(float(returned_value[:-1])) + 10 ** -(2)\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}returned_value = abs(float(returned_value))\n" if self.metric == WAE: if_sat += f"{TAB}{TAB}if upper_bound - lower_bound <= 1:\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = upper_bound\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}lower_bound = stats['et']\n" elif self.metric == WHD: if_sat += f"{TAB}{TAB}if upper_bound - lower_bound <= 1:\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = upper_bound\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}lower_bound = stats['et']\n" elif self.metric == WRE: if_sat += f'{TAB}{TAB}if round(upper_bound - lower_bound, 2) <= (10 ** - {self.precision}):\n' \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = upper_bound\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}lower_bound = float(stats['et'])\n" if_sat += f"{TAB}{TAB}stats['num_sats'] += 1\n" \ f"{TAB}{TAB}stats['sat_runtime'] += (end_iteration - start_iteration)\n" \ f"{TAB}{TAB}if stats['et'] == max:\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = stats['et']\n" return if_sat def express_monotonic_while_loop_sat(self): if_sat = '' if_sat += f"{TAB}if response == sat:\n" \ f"{TAB}{TAB}print(f'sat')\n" \ f"{TAB}{TAB}end_iteration = time.time()\n" \ f"{TAB}{TAB}returned_model = s.model()\n" \ f"{TAB}{TAB}print(f'{{returned_model = }}')\n" if self.metric == WAE or self.metric == WRE: f"{TAB}{TAB}print(f\"{{returned_model[f_exact].else_value() = }}\")\n" \ f"{TAB}{TAB}print(f\"{{returned_model[f_approx].else_value() = }}\")\n" \ f"{TAB}{TAB}print(f\"{{returned_model[f_error].else_value() = }}\")\n" elif self.metric == WHD: f"{TAB}{TAB}print(f\"{{returned_model[f_error].else_value() = }}\")\n" if self.metric == WAE: if_sat += f"{TAB}{TAB}returned_value = abs(int(returned_model[f_error].else_value().as_long()))\n" \ f"{TAB}{TAB}returned_value_reval = abs(int(returned_model.evaluate(f_error(exact_out, approx_out)).as_long()))\n" elif self.metric == WHD: if_sat += f"{TAB}{TAB}returned_value = abs(int(returned_model[f_error].else_value().as_long()))\n" if_sat += f"{TAB}{TAB}returned_value_reval = abs(int(returned_model.evaluate(f_error(" for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: if_sat += f"o{i}_{XOR}_{INT})).as_long()))\n" else: if_sat += f"o{i}_{XOR}_{INT}, " elif self.metric == WRE: if_sat += f"{TAB}{TAB}returned_value = ((returned_model[f_error].else_value().as_decimal({self.precision})))\n" \ f"{TAB}{TAB}returned_value_reval = ((returned_model.evaluate(f_error(exact_out, approx_out)).as_decimal({self.precision})))\n" if_sat += f"{TAB}{TAB}if returned_value == returned_value_reval:\n" \ f"{TAB}{TAB}{TAB}print(f'double-check is passed!')\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}print(f'ERROR!!! double-check failed! exiting...')\n" \ f"{TAB}{TAB}{TAB}exit()\n" if self.metric == WRE: if_sat += f"{TAB}{TAB}if returned_value[-1] == '?':\n" \ f"{TAB}{TAB}{TAB}print('removing the last question mark!')\n" \ f"{TAB}{TAB}{TAB}returned_value = abs(float(returned_value[:-1])) + 10 ** -({self.precision})\n" \ f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}returned_value = abs(float(returned_value))\n" if self.metric == WAE: if_sat += f"{TAB}{TAB}stats['et'] = returned_value\n" elif self.metric == WHD: if_sat += f"{TAB}{TAB}stats['et'] = returned_value\n" elif self.metric == WRE: if_sat += f"{TAB}{TAB}stats['et'] = \"{{:.{self.precision}f}}\".format(returned_value)\n" if_sat += f"{TAB}{TAB}stats['num_sats'] += 1\n" \ f"{TAB}{TAB}stats['sat_runtime'] += (end_iteration - start_iteration)\n" \ f"{TAB}{TAB}stats['jumps'].append(returned_value)\n" \ f"{TAB}{TAB}if stats['et'] == max:\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = stats['et']\n" return if_sat def express_kind_bisection_while_loop_unsat(self): if_unsat = '' if_unsat += f"\n" \ f"{TAB}if response == unsat:\n" \ f"{TAB}{TAB}print('unsat')\n" \ f"{TAB}{TAB}end_iteration = time.time()\n" if self.metric == WAE: if_unsat += f"{TAB}{TAB}if upper_bound - lower_bound <= 1:\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}if lower_bound == 0:\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" elif self.metric == WHD: if_unsat += f"{TAB}{TAB}if upper_bound - lower_bound <= 1:\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}if lower_bound == 0:\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" elif self.metric == WRE: if_unsat += f"{TAB}{TAB}if round(upper_bound - lower_bound, 2) <= (10 ** -{self.precision}):\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}{TAB}if lower_bound == 0:\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" if_unsat += f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}upper_bound = float(stats['et'])\n" \ f"{TAB}{TAB}stats['num_unsats'] += 1\n" \ f"{TAB}{TAB}stats['unsat_runtime'] += (end_iteration - start_iteration)\n" \ f"{TAB}s.pop()\n" return if_unsat def express_bisection_while_loop_unsat(self): if_unsat = '' if_unsat += f"\n" \ f"{TAB}if response == unsat:\n" \ f"{TAB}{TAB}print('unsat')\n" \ f"{TAB}{TAB}end_iteration = time.time()\n" if self.metric == WAE: if_unsat += f"{TAB}{TAB}if upper_bound - lower_bound <= 1:\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}if lower_bound == 0:\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = upper_bound\n" elif self.metric == WHD: if_unsat += f"{TAB}{TAB}if upper_bound - lower_bound <= 1:\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}if lower_bound == 0:\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = upper_bound\n" elif self.metric == WRE: if_unsat += f"{TAB}{TAB}if round(upper_bound - lower_bound, 2) <= (10 ** -{self.precision}):\n" \ f"{TAB}{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}{TAB}if lower_bound == 0:\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = lower_bound\n" \ f"{TAB}{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}{TAB}stats['wce'] = upper_bound\n" if_unsat += f"{TAB}{TAB}else:\n" \ f"{TAB}{TAB}{TAB}upper_bound = float(stats['et'])\n" \ f"{TAB}{TAB}stats['num_unsats'] += 1\n" \ f"{TAB}{TAB}stats['unsat_runtime'] += (end_iteration - start_iteration)\n" \ f"{TAB}s.pop()\n" return if_unsat def express_monotonic_while_loop_unsat(self): if_unsat = '' if_unsat += f"\n" \ f"{TAB}if response == unsat:\n" \ f"{TAB}{TAB}print('unsat')\n" \ f"{TAB}{TAB}end_iteration = time.time()\n" \ f"{TAB}{TAB}foundWCE = True\n" \ f"{TAB}{TAB}stats['num_unsats'] += 1\n" \ f"{TAB}{TAB}stats['unsat_runtime'] += (end_iteration - start_iteration)\n" \ f"{TAB}{TAB}stats['wce'] = stats['et']\n" \ f"{TAB}s.pop()\n" return if_unsat def express_stats(self): stats = '' stats += f"end_whole = time.time()\n" \ f"with open('{self.z3_report}', 'w') as f:\n" \ f"{TAB}csvwriter = csv.writer(f)\n" \ f"{TAB}header = ['field', 'value']\n" \ f"{TAB}csvwriter.writerow(['Experiment', '{self.experiment}'])\n" \ f"{TAB}csvwriter.writerow(['WCE', stats['wce']])\n" \ f"{TAB}csvwriter.writerow(['Total Runtime', end_whole - start_whole])\n" \ f"{TAB}csvwriter.writerow(['SAT Runtime', stats['sat_runtime']])\n" \ f"{TAB}csvwriter.writerow(['UNSAT Runtime', stats['unsat_runtime']])\n" \ f"{TAB}csvwriter.writerow(['Number of SAT calls', stats['num_sats']])\n" \ f"{TAB}csvwriter.writerow(['Number of UNSAT calls', stats['num_unsats']])\n" \ f"{TAB}csvwriter.writerow(['Jumps', stats['jumps']])\n" return stats def express_monotonic_strategy(self): monotonic_strategy = '' monotonic_strategy += self.declare_stats() monotonic_strategy += self.express_monotonic_while_loop() return monotonic_strategy def express_mc_strategy(self): mc_strategy = '' mc_strategy += self.declare_stats() mc_strategy += self.express_mc_while_loop() return mc_strategy def express_bisection_strategy(self): bisection_strategy = '' bisection_strategy += self.declare_stats() bisection_strategy += self.express_bisection_while_loop() return bisection_strategy def express_kind_bisection_strategy(self): kind_bisection_strategy = '' kind_bisection_strategy += self.declare_stats() kind_bisection_strategy += self.express_kind_bisection_while_loop() return kind_bisection_strategy def export_z3pyscript(self): with open(self.out_path, 'w') as z: z.writelines(self.z3pyscript) def __repr__(self): return f'An object of class Z3solver\n' \ f'{self.name = }\n' \ f'{self.graph_in_path = }\n' \ f'{self.out_path = }\n' def create_imports(self): import_string = f'from z3 import *\n' \ f'import sys\n' \ f'import time\n' \ f'import csv\n' \ f'\n' return import_string def create_abs_function(self): abs_function = f'def z3_abs(x):\n' \ f'\treturn If(x >= 0, x, -x)\n' \ f'\n' return abs_function def declare_original_circuit(self): exact_circuit_declaration = '' # inputs for n in self.graph.graph.nodes: if re.search(r'in\d+', self.graph.graph.nodes[n]['label']): exact_circuit_declaration = f'{exact_circuit_declaration}' \ f'{self.declare_gate(n)}\n' exact_circuit_declaration += f'\n' # gates for n in self.graph.graph.nodes: if re.search(r'g\d+', n): exact_circuit_declaration = f'{exact_circuit_declaration}' \ f'{self.declare_gate(n)}\n' # outputs for n in self.graph.graph.nodes: if re.search(r'out\d+', self.graph.graph.nodes[n]['label']): exact_circuit_declaration = f'{exact_circuit_declaration}' \ f'{self.declare_gate(n)}\n' return exact_circuit_declaration def declare_approximate_circuit(self): exact_circuit_declaration = '' # inputs for n in self.approximate_graph.graph.nodes: if self.approximate_graph.is_pruned_pi(n): exact_circuit_declaration = f'{exact_circuit_declaration}' \ f'{self.declare_gate(n)}\n' exact_circuit_declaration += f'\n' # gates for n in self.approximate_graph.graph.nodes: if re.search(r'g\d+', n): exact_circuit_declaration = f'{exact_circuit_declaration}' \ f'{self.declare_gate(n)}\n' # outputs for n in self.approximate_graph.graph.nodes: if re.search(r'out\d+', self.approximate_graph.graph.nodes[n]['label']): exact_circuit_declaration = f'{exact_circuit_declaration}' \ f'{self.declare_gate(n)}\n' return exact_circuit_declaration def declare_gate(self, this_key: str): declaration = f"{this_key} = {Z3BOOL}('{this_key}')" return declaration def express_original_circuit(self): exact_circuit_function = '' for n in self.graph.graph.nodes: if self.graph.is_cleaned_gate(n): exact_circuit_function += f'{self.express_exact_gate(n)}\n' elif self.graph.is_cleaned_constant(n): exact_circuit_function += f'{self.express_exact_constant(n)}\n' elif self.graph.is_cleaned_po(n): exact_circuit_function += f'{self.express_exact_output(n)}\n' exact_circuit_function += f'\n' return exact_circuit_function def express_approximate_circuit(self): approximate_circuit_function = '' for n in self.approximate_graph.graph.nodes: if self.approximate_graph.is_cleaned_pi(n): approximate_circuit_function += f'{self.express_approximate_gate(n)}\n' elif self.approximate_graph.is_cleaned_gate(n): approximate_circuit_function += f'{self.express_approximate_gate(n)}\n' elif self.approximate_graph.is_cleaned_constant(n): approximate_circuit_function += f'{self.express_approximate_constant(n)}\n' elif self.approximate_graph.is_cleaned_po(n): approximate_circuit_function += f'{self.express_approximate_output(n)}\n' approximate_circuit_function += f'\n' return approximate_circuit_function def express_exact_output(self, this_key): cur_node = '' predecessor = list(self.graph.graph.predecessors(this_key))[0] cur_node = f'{this_key} = {predecessor}\n' return cur_node def express_exact_constant(self, this_key): cur_node = '' this_constant = re.search(r'TRUE|FALSE', self.graph.graph.nodes[this_key][LABEL]).group() cur_node += f'{this_key} = {Z3_GATES_DICTIONARY[this_constant]}\n' return cur_node def express_exact_gate(self, this_key: str): # sth like this: g110 = Not(And(g108, g109)) cur_node = '' if self.graph.is_cleaned_gate(this_key): this_gate = re.search(POSSIBLE_GATES, self.graph.graph.nodes[this_key]['label']).group() cur_gate = Z3_GATES_DICTIONARY[this_gate] predecessor_list = list(self.graph.graph.predecessors(this_key)) cur_node = f"{this_key}={cur_gate}(" for idx, u in enumerate(predecessor_list): cur_node += f'{u}' if idx == len(predecessor_list) - 1: cur_node += f')' else: cur_node += f',' elif self.graph.is_cleaned_pi(this_key): pass elif self.graph.is_cleaned_po(this_key): cur_node = f'{this_key}=' predecessor_list = list(self.graph.graph.predecessors(this_key)) for idx, u in enumerate(predecessor_list): cur_node += f'{u}' return cur_node def express_approximate_output(self, this_key): cur_node = '' predecessor = list(self.approximate_graph.graph.predecessors(this_key))[0] cur_node = f'{this_key} = {predecessor}\n' return cur_node def express_approximate_constant(self, this_key): cur_node = '' this_constant = re.search(r'TRUE|FALSE', self.approximate_graph.graph.nodes[this_key][LABEL]).group() cur_node += f'{this_key} = {Z3_GATES_DICTIONARY[this_constant]}\n' return cur_node def express_approximate_gate(self, this_key: str): # sth like this: g110 = Not(And(g108, g109)) cur_node = '' if self.approximate_graph.is_pruned_gate(this_key): cur_node = f'{this_key} = {self.approximate_graph.graph.nodes[this_key][PRUNED]}' elif self.approximate_graph.is_cleaned_gate(this_key): this_gate = re.search(POSSIBLE_GATES, self.approximate_graph.graph.nodes[this_key]['label']).group() cur_gate = Z3_GATES_DICTIONARY[this_gate] predecessor_list = list(self.approximate_graph.graph.predecessors(this_key)) cur_node = f"{this_key}={cur_gate}(" for idx, u in enumerate(predecessor_list): cur_node += f'{u}' if idx == len(predecessor_list) - 1: cur_node += f')' else: cur_node += f',' elif self.approximate_graph.is_pruned_pi(this_key): cur_node = f'{this_key}= {self.approximate_graph.graph.nodes[this_key][PRUNED]}' elif self.approximate_graph.is_cleaned_po(this_key): cur_node = f'{this_key}=' predecessor_list = list(self.approximate_graph.graph.predecessors(this_key)) for idx, u in enumerate(predecessor_list): cur_node += f'{u}' return cur_node def declare_original_output(self): output_declaration = '' # print(f'{self.graph.output_dict = }') for i in range(self.graph.num_outputs): output_declaration += f"exact_out{i}=Int('exact_out{i}')\n" output_declaration += f"exact_out{i}={self.graph.output_dict[i]}*{2 ** i}*2/2\n" output_declaration += f"exact_out = Int('exact_out')\n" output_declaration += f'exact_out=' for i in range(self.graph.num_outputs): if i == self.graph.num_outputs - 1: output_declaration += f'exact_out{i}' else: output_declaration += f'exact_out{i}+' output_declaration += f'\n' return output_declaration def declare_approximate_output(self): output_declaration = '' # print(f'{self.approximate_graph.output_dict = }') for i in range(self.approximate_graph.num_outputs): output_declaration += f"approx_out{i}=Int('approx_out{i}')\n" output_declaration += f"approx_out{i}={self.approximate_graph.output_dict[i]}*{2 ** i}*2/2\n" # print(f'{self.approximate_graph.output_dict = }') output_declaration += f"approx_out = Int('approx_out')\n" output_declaration += f'approx_out=' for i in range(self.approximate_graph.num_outputs): if i == self.approximate_graph.num_outputs - 1: output_declaration += f'approx_out{i}' else: output_declaration += f'approx_out{i}+' output_declaration += f'\n' return output_declaration def declare_xor_miter(self): xor_miter_declaration = f'' # o0_xor = Bool('o0_xor') # o1_xor = Bool('o1_xor') # o2_xor = Bool('o2_xor') for i in range(self.graph.num_outputs): xor_miter_declaration += f"{MITER}_o{i}_{XOR} = {Z3BOOL}('o{i}_{XOR}')\n" # o0_xor = Xor(g27, a27) # o1_xor = Xor(g105, a105) # o2_xor = Xor(g99, a99) for i in range(self.graph.num_outputs): xor_miter_declaration += f"o{i}_{XOR} = {Z3XOR}({self.graph.output_dict[i]}, app_{self.graph.output_dict[i]})\n" # o0_xor_int = Int('o0_xor_int') # o0_xor_int = o0_xor * 2 / 2 # o1_xor_int = Int('o1_xor_int') # o1_xor_int = o1_xor * 2 / 2 # o2_xor_int = Int('o2_xor_int') # o2_xor_int = o2_xor * 2 / 2 for i in range(self.graph.num_outputs): xor_miter_declaration += f"o{i}_{XOR}_{INT} = {Z3INT}('o{i}_{XOR}_{INT}')\n" \ f"o{i}_{XOR}_{INT} = o{i}_{XOR} * 2/2\n" return xor_miter_declaration def declare_original_function(self): exact_function = '' exact_function += f'results = []\n' exact_function += f"f_exact = Function('f', IntSort(), IntSort())" exact_function += f'\n' return exact_function def declare_approximate_function(self): exact_function = '' exact_function += f'results = []\n' exact_function += f"f_exact = Function('f', IntSort(), IntSort())" exact_function += f'\n' return exact_function def declare_solver(self): solver = '' if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE: solver += f's = Optimize()\n' else: solver += f's = Solver()\n' solver += f's.add(f_exact(exact_out) == exact_out)\n' solver += f'\n' return solver def express_samples(self): sample_expression = '' for s in self.samples: sample_expression += f's.push()\n' s_expression = [True if i == '1' else False for i in list(f'{s:0{self.graph.num_inputs}b}')] # a 1101 is considered as in3,in2,in1,in0 => in3=1, in2=1, in1=0, in0=1 s_expression.reverse() # to keep it consistent with the verilog testbench sample_expression += f's.add(' for idx, e in enumerate(s_expression): if idx == len(s_expression) - 1: sample_expression += f'{self.graph.input_dict[idx]}=={e})\n' else: sample_expression += f'{self.graph.input_dict[idx]}=={e}, ' sample_expression += f'sol = s.check()\n' sample_expression += f'm = s.model()\n' sample_expression += f"print(f'{{m = }}')\n" sample_expression += f'cur_result = m[f_exact].else_value().as_string()\n' sample_expression += f'results.append(cur_result)\n' sample_expression += f's.pop()\n\n' return sample_expression def store_results(self): store_results = '' store_results += f"with open('{self.pyscript_results_out_path}', 'w') as f:\n" \ f"\tfor line in results:\n" \ f"\t\tf.write(line)\n" \ f"\t\tf.write('\\n')\n" store_results += f"print(f'{{results = }}')" return store_results # TODO: decorators----------------------------- def run_z3pyscript_qor(self): with open(self.z3_log_path, 'w') as f: process = subprocess.run([PYTHON3, self.out_path], stderr=PIPE, stdout=PIPE) def run_z3pyscript_labeling(self): # print(self.pyscript_files_for_labeling ) for pyscript in self.pyscript_files_for_labeling: with open(self.z3_log_path, 'w') as f: # process = subprocess.run([PYTHON3, pyscript], stdout=PIPE, stderr=PIPE) process = subprocess.run([PYTHON3, pyscript], stderr=PIPE, stdout=PIPE) if process.stderr: print(Fore.RED + f'ERROR!!! cannot run {pyscript} properly!') print(f'{process.stderr.decode()}') def run_z3pyscript_random(self): with open(self.z3_log_path, 'w') as f: process = subprocess.run([PYTHON3, self.out_path], stdout=PIPE, stderr=PIPE) def run_z3pyscript_test(self): with open(self.z3_log_path, 'w') as f: # process = subprocess.run([PYTHON3, self.out_path], stdout=PIPE, stderr=PIPE) process = subprocess.run([PYTHON3, self.out_path], stderr=PIPE, stdout=PIPE) self.set_sample_results(self.import_results()) # TODO: decorators (end)--------------------------
z3log
/z3log-1.1.1.tar.gz/z3log-1.1.1/Z3Log/z3solver.py
z3solver.py
import re import subprocess import os import shutil from .config.path import * from .config.config import * def get_pure_name(file_name: str) -> str: if file_name is None: return file_name name = file_name if re.search('/', file_name): name = file_name.split('/')[-1] if re.search('\.', name): name = name.split('.')[0] return name def fix_direction(file_name: str) -> str: file_name = get_pure_name(file_name) folder, extension = OUTPUT_PATH['dot'] dot_in_path = f'{folder}/{file_name}.{extension}' folder, extension = OUTPUT_PATH['gv'] gv_out_path = f'{folder}/{file_name}.{extension}' dot_command = f'{DOT} {dot_in_path} -Grankdir=TB -o {gv_out_path}' subprocess.call([dot_command], shell=True) def convert_verilog_to_gv(file_name: str) -> None: file_name = get_pure_name(file_name) folder, extension = OUTPUT_PATH['ver'] verilog_in_path = f'{folder}/{file_name}.{extension}' folder, extension = OUTPUT_PATH['gv'] gv_out_path = f'{folder}/{file_name}.{extension}' yosys_command = f""" read_verilog {verilog_in_path} show -prefix {gv_out_path[:-3]} -format gv """ folder, extension = LOG_PATH['yosys'] log_out_path = f'{folder}/{file_name}_{YOSYS}_v2gv.{extension}' with open(f'{log_out_path}', 'w') as y: subprocess.call([YOSYS, '-p', yosys_command], stdout=y) fix_direction(file_name) def setup_folder_structure(): # Setting up the folder structure directories = [OUTPUT_PATH['ver'][0], OUTPUT_PATH['aig'][0], OUTPUT_PATH['gv'][0], OUTPUT_PATH['z3'][0], OUTPUT_PATH['report'][0], OUTPUT_PATH['figure'][0], TEST_PATH['tb'][0], TEST_PATH['z3'][0], INPUT_PATH['ver'][0], INPUT_PATH['gv'][0], LOG_PATH['yosys'][0]] for directory in directories: if ~os.path.exists(directory): os.makedirs(directory, exist_ok=True) def clean_all(): """ Cleans the contents of output and test (alongside their subfolders) :return: Nothing """ shutil.rmtree('output/') shutil.rmtree('test/')
z3log
/z3log-1.1.1.tar.gz/z3log-1.1.1/Z3Log/utils.py
utils.py
import subprocess import networkx as nx import re import os from .config.path import * from .config.config import * from typing import Dict from .argument import Arguments class Graph: def __init__(self, benchmark_name, is_clean: bool = False, address: str = None): """ takes in a circuit and creates a networkx graph out of it :param benchmark_name: the input benchmark in gv format :param is_clean: leave empty for now """ self.__graph_name = benchmark_name folder, extension = INPUT_PATH['gv'] # input/gv/ self.__graph_in_path = f'{folder}/{benchmark_name}.{extension}' folder, extension = OUTPUT_PATH['gv'] # output/gv self.__graph_out_path = f'{folder}/{benchmark_name}.{extension}' folder, extension = OUTPUT_PATH['dot'] # output/gv self.__dot_in_path = f'{folder}/{benchmark_name}.{extension}' folder, extension = OUTPUT_PATH['ver'] # output/ver self.__verilog_in_path = f'{folder}/{benchmark_name}.{extension}' self.__graph = self.import_graph(address) self.__sorted_node_list = None self.__is_clean = is_clean if not self.is_clean: self.clean_graph() # print(f'After cleaning!') # for n in self.graph.nodes: # print(f'{n = }, {self.graph.nodes[n] = }') self.sort_graph() self.__input_dict = self.extract_inputs() self.__output_dict = self.extract_outputs() self.__gate_dict = self.extract_gates() self.__constant_dict = self.extract_constants() self.__num_inputs = len(self.__input_dict) self.__num_outputs = len(self.__output_dict) self.__num_gates = len(self.__gate_dict) self.__num_constants = len(self.__constant_dict) self.remove_output_outgoing_edges() @property def name(self): return self.__graph_name @property def is_clean(self): return self.__is_clean def set_is_clean(self, is_clean: bool): self.__is_clean = is_clean @property def in_path(self): return self.__graph_in_path @property def out_path(self): return self.__graph_out_path @property def verilog_in_path(self): return self.__verilog_in_path @property def dot_in_path(self): return self.__dot_in_path @property def graph(self): return self.__graph def set_graph(self, graph): self.__graph = graph @property def input_dict(self): return self.__input_dict def set_input_dict(self, input_dict): self.__input_dict = input_dict @property def output_dict(self): return self.__output_dict def set_output_dict(self, output_dict): self.__output_dict = output_dict @property def gate_dict(self): return self.__gate_dict def set_gate_dict(self, gate_dict): self.__gate_dict = gate_dict @property def constant_dict(self): return self.__constant_dict def set_constant_dict(self, constant_dict): self.__constant_dict = constant_dict @property def num_inputs(self): return self.__num_inputs def set_num_inputs(self, input_count): self.__num_inputs = input_count @property def num_outputs(self): return self.__num_outputs def set_num_outputs(self, output_count): self.__num_outputs = output_count @property def num_gates(self): return self.__num_gates def set_num_gates(self, gate_count): self.__num_gates = gate_count @property def sorted_node_list(self): return self.__sorted_node_list def set_sorted_node_list(self, sorted_node_list): self.__sorted_node_list = sorted_node_list def remove_output_outgoing_edges(self): for n in self.graph.nodes: if self.is_cleaned_po(n): if len(list(self.graph.successors(n))) > 0: if len(list(self.graph.predecessors(n))) > 1: raise Exception(Fore.RED + f'Output {n} has more than 1 predecessors!' + Style.RESET_ALL) pred = list(self.graph.predecessors(n))[0] for s in list(self.graph.successors(n)): self.graph.remove_edge(n, s) self.graph.add_edge(pred, s) def extract_inputs(self): # print(f'Extracting inputs...') input_dict = {} idx = 0 for n in self.graph.nodes(): if self.is_pi(n): idx = re.search('\d+', n).group() input_dict[int(idx)] = n # idx += 1 return input_dict def extract_outputs(self): # print(f'Extracting outputs...') output_dict = {} idx = 0 for n in self.graph.nodes(): if self.is_po(n): idx = re.search('\d+', n).group() output_dict[int(idx)] = n # idx += 1 return output_dict def extract_gates(self): gate_dict = {} idx = 0 for n in self.graph.nodes: if self.is_cleaned_gate(n): idx = re.search('\d+', n).group() gate_dict[int(idx)] = n # idx += 1 return gate_dict def extract_constants(self): constant_dict = {} idx = 0 for n in self.graph.nodes: if self.is_constant(n): idx = re.search('\d+', n).group() constant_dict[int(idx)] = n # idx += 1 return constant_dict # methods def create_sort_map(self) -> 'dict[str, str]': """ sorts the nodes in topological order and returns them in a form of a list :return: a sorted list of node labels """ sorted_node_list = list(nx.topological_sort(self.graph)) sort_map = {} idx = 0 for n in sorted_node_list: if re.search(r'in\d+', n): sort_map[n] = n elif re.search(r'out\d+', n): sort_map[n] = n elif re.search(r'g\d+', n): sort_map[n] = f'g{idx}' idx += 1 return sort_map def sort_graph(self): sort_map = self.create_sort_map() self.set_graph(nx.relabel_nodes(self.graph, sort_map)) self.set_sorted_node_list(list(nx.topological_sort(self.graph))) tmp_graph = nx.DiGraph() tmp_graph.add_nodes_from(self.sorted_node_list) tmp_graph.add_edges_from(self.graph.edges()) for (k, v) in self.graph.nodes(data=True): for attr in v.keys(): tmp_graph.nodes[k][attr] = v[attr] self.set_graph(tmp_graph) # print(f'{tmp_graph.nodes = }') # TODO # Deprecated def count_iog(self): """ counts the number of primary inputs and outputs, and gates and sets the corresponding fields :return: Nothing """ count_i = 0 count_o = 0 count_g = 0 for n in self.graph.nodes: if re.search(r'in\d+', n) and re.search(r'in\d+', self.graph.nodes[n]['label']): count_i += 1 elif re.search(r'out\d+', n) and re.search(r'out\d+', self.graph.nodes[n]['label']): count_o += 1 elif re.search(r'g\d+', n) and re.search(POSSIBLE_GATES, self.graph.nodes[n]['label']): count_g += 1 self.set_num_inputs(count_i) self.set_num_outputs(count_o) self.set_num_gates(count_g) def convert_verilog_to_gv(self): yosys_command = f""" read_verilog {self.verilog_in_path} show -prefix {self.out_path[:-3]} -format gv """ with open(f'yosys_graph.log', 'w') as y: subprocess.call([YOSYS, '-p', yosys_command], stdout=y) self.fix_direction() def fix_direction(self): dot_command = f'{DOT} {self.dot_in_path} -Grankdir=TB -o {self.out_path}' subprocess.call([dot_command], shell=True) def clean_graph(self): self.clean_input_labels() self.clean_output_labels() self.clean_wire_labels() self.clean_gate_labels() self.clean_constant_labels() self.merge_buffers_into_gates() self.merge_wires_into_gates() self.relabel_nodes() self.delete_extra_fields() self.set_is_clean(True) self.count_iog() self.set_input_dict(self.extract_inputs()) self.set_output_dict(self.extract_outputs()) self.set_gate_dict(self.extract_gates()) self.set_constant_dict(self.extract_constants()) def delete_extra_fields(self): for n in self.graph.nodes: for field in REDUNDANT_FIELDS: if field in self.graph.nodes[n].keys(): self.graph.nodes[n].pop(field) # delete all edge attributes for (n1, n2, d) in self.graph.edges(data=True): d.clear() def clean_input_labels(self): self.delete_extra_fields() for n in self.graph.nodes: if self.is_pi(n): idx = re.search('\d+', self.graph.nodes[n]['label']).group() # pi7 => idx=7 self.graph.nodes[n]['label'] = f'in{idx}' self.graph.nodes[n]['shape'] = f'circle' def clean_output_labels(self): for n in self.graph.nodes: if self.is_po(n): idx = re.search('\d+', self.graph.nodes[n]['label']).group() # po12 => idx=12 self.graph.nodes[n]['label'] = f'out{idx}' self.graph.nodes[n]['shape'] = f'doublecircle' def clean_wire_labels(self): for n in self.graph.nodes: if self.is_wire(n): idx = re.search('\d+', self.graph.nodes[n]['label']).group() # n317 => idx=317 self.graph.nodes[n]['label'] = f'g{idx}' self.graph.nodes[n]['shape'] = f'square' def clean_gate_labels(self): for n in self.graph.nodes: if self.is_gate(n): if re.search(POSSIBLE_GATES, self.graph.nodes[n]['label']): cur_gate = re.search(POSSIBLE_GATES, self.graph.nodes[n]['label']).group() self.graph.nodes[n]['label'] = cur_gate self.graph.nodes[n]['shape'] = 'invhouse' def clean_constant_labels(self): # g16[label = "F", shape = circle, fillcolor = white] for n in self.graph.nodes: if self.is_constant(n): const_value = re.search(f'{CONST_0}|{CONST_1}', self.graph.nodes[n][LABEL]).group() self.graph.nodes[n][LABEL] = f"{'FALSE' if const_value == CONST_0 else 'TRUE'}" self.graph.nodes[n][SHAPE] = f'square' def merge_buffers_into_gates(self): tmp_graph = self.graph.copy(as_view=False) for e in self.graph.edges: if self.graph.nodes[e[1]]['label'] == 'BUF': src_node = e[0] des_node = e[1] tmp_graph = nx.contracted_nodes(tmp_graph, src_node, des_node, self_loops=False) self.set_graph(tmp_graph) def merge_wires_into_gates(self): tmp_graph = self.graph.copy(as_view=False) for e in self.graph.edges: # if (re.search(POSSIBLE_GATES, self.graph.nodes[e[0]]['label']) and # re.search('g\d+', self.graph.nodes[e[1]]['label'])): if re.search('g\d+', self.graph.nodes[e[1]]['label']): src_node = e[0] des_node = e[1] tmp_graph = nx.contracted_nodes(tmp_graph, src_node, des_node, self_loops=False) self.set_graph(tmp_graph) def relabel_nodes(self): tmp_graph = self.graph.copy() gate_idx = 0 for n in self.graph.nodes: if self.is_cleaned_pi(n): old_name = n new_name = self.graph.nodes[n]['label'] mapping = {old_name: new_name} tmp_graph = nx.relabel_nodes(tmp_graph, mapping) elif self.is_cleaned_po(n): old_name = n new_name = self.graph.nodes[n]['label'] mapping = {old_name: new_name} tmp_graph = nx.relabel_nodes(tmp_graph, mapping) elif self.is_merged_gate(n): old_name = n new_name = f'g{gate_idx}' gate_idx += 1 mapping = {old_name: new_name} tmp_graph = nx.relabel_nodes(tmp_graph, mapping) elif self.is_cleaned_gate(n): old_name = n new_name = f'g{gate_idx}' gate_idx += 1 mapping = {old_name: new_name} tmp_graph = nx.relabel_nodes(tmp_graph, mapping) elif self.is_constant(n): old_name = n new_name = f'g{gate_idx}' gate_idx += 1 mapping = {old_name: new_name} tmp_graph = nx.relabel_nodes(tmp_graph, mapping) else: print('WARNING! No mapping needed!') self.set_graph(tmp_graph) def is_cleaned_pi(self, node): if not self.is_constant(node): if re.search(r'in\d+', self.graph.nodes[node][LABEL]): return True else: return False else: return False def is_pruned_pi(self, node): if not self.is_constant(node): if (re.search(r'in\d+', self.graph.nodes[node][LABEL]) and PRUNED in self.graph.nodes[node]): return True else: return False else: return False def is_pi(self, node): if not self.is_constant(node): if re.search(r'pi\d+', self.graph.nodes[node][LABEL]) or \ self.graph.nodes[node][LABEL].startswith('in'): return True else: return False else: return False def is_cleaned_po(self, node): if not self.is_constant(node): if re.search(r'out\d+', self.graph.nodes[node][LABEL]): return True else: return False else: return False def is_po(self, node): if not self.is_constant(node): if re.search(r'po\d+', self.graph.nodes[node][LABEL]) or \ self.graph.nodes[node][LABEL].startswith('out'): return True else: return False else: return False def is_wire(self, node): if not self.is_constant(node): if (not self.is_pi(node) and not self.is_po(node) and not self.is_gate(node) and re.search('diamond', self.graph.nodes[node]['shape'])): return True else: return False else: return False def is_cleaned_gate(self, node): if not self.is_constant(node): if (re.search('invhouse', self.graph.nodes[node][SHAPE]) and 'contraction' not in self.graph.nodes[node].keys() and 'contractions' not in self.graph.nodes[ node]): return True elif (re.search('invhouse', self.graph.nodes[node][SHAPE]) and re.search(r'g\d+', node) and 'contraction' not in self.graph.nodes[node].keys() and 'contractions' not in self.graph.nodes[ node]): return True else: return False else: return False def is_pruned_gate(self, node): if not self.is_constant(node): if self.is_cleaned_gate(node) and PRUNED in self.graph.nodes[node]: return True else: return False else: return False def is_gate(self, node): if not self.is_constant(node): if re.search('record', self.graph.nodes[node]['shape']): return True else: return False else: return False def is_constant(self, node): if (SHAPE not in self.graph.nodes[node] and LABEL in self.graph.nodes[node] and re.search(f'{CONST_0}|{CONST_1}', self.graph.nodes[node][LABEL])): return True elif re.search(r'(TRUE|FALSE)', self.graph.nodes[node][LABEL]): regex_constant = re.search(f'', self.graph.nodes[node][LABEL]).group() return True else: return False def is_cleaned_constant(self, node): if re.search(r'(TRUE|FALSE)', self.graph.nodes[node][LABEL]): return True else: return False def is_buff(self, node): if not self.is_constant(node): if (re.search('BUF', self.graph.nodes[node]['label']) and re.search('box', self.graph.nodes[node]['shape'])): return True else: return False else: return False def is_merged_gate(self, node): if not self.is_constant(node): if (re.search(POSSIBLE_GATES, self.graph.nodes[node]['label']) and re.search('invhouse', self.graph.nodes[node]['shape']) and ('contraction' in self.graph.nodes[node].keys() or 'contractions' in self.graph.nodes[ node].keys())): return True else: return False else: return False def import_graph(self, address: str = None): """ :param address: the location of the gv file. default is self.out_path (output/gv/) :return: the graph object of networkx """ if address: DG = nx.drawing.nx_agraph.read_dot(address) else: DG = nx.drawing.nx_agraph.read_dot(self.out_path) return DG def export_graph(self): with open(self.out_path, 'w') as f: f.write(f"strict digraph \"\" {{\n") for n in self.graph.nodes: self.export_node(n, f) for e in self.graph.edges: self.export_edge(e, f) f.write(f"}}\n") if os.path.exists(f'{self.dot_in_path}'): os.remove(f'{self.dot_in_path}') def export_node(self, n, file_handler: 'class _io.TextIOWrapper'): # in3 [label=in3,shape=circle]; if self.is_cleaned_pi(n) or self.is_cleaned_po(n): line = f"{n} [label=\"{self.graph.nodes[n]['label']}\", shape={self.graph.nodes[n]['shape']}];\n" elif self.is_cleaned_gate(n): line = f"{n} [label=\"{self.graph.nodes[n]['label']}\\n{n}\", shape={self.graph.nodes[n]['shape']}];\n" elif self.is_cleaned_constant(n): line = f"{n} [label=\"{self.graph.nodes[n]['label']}\\n{n}\", shape={self.graph.nodes[n]['shape']}];\n" else: print('WARNING!!! found a node that is not a PI, PO, WIRE, CONSTANT, GATE') raise Exception('NodeTypeError') file_handler.write(line) def export_edge(self, e: tuple, file_handler): # in3 -> g2; src, des = e line = f"{src} -> {des};\n" file_handler.write(line) def convert_to_verilog(self): pass def __repr__(self): return f'An object of class Graph\n' \ f'{self.name = }\n' \ f'{self.in_path = }\n' \ f'{self.out_path = }\n' \ f'{self.num_inputs = }\n' \ f'{self.num_outputs = }\n' \ f'{self.num_gates = }\n'
z3log
/z3log-1.1.1.tar.gz/z3log-1.1.1/Z3Log/graph.py
graph.py
import os import re import natsort from typing import List from copy import deepcopy from stats import Stats from specs import Specs from .config.path import * from .utils import * import matplotlib import matplotlib.pyplot as plt import csv import numpy as np class Result: def __init__(self, specifications: Specs): self.__benchmark: str = get_pure_name(specifications.benchmark) self.__approximate_benchmark: str = get_pure_name(specifications.approximate_benchmark) self.__experiment: str = specifications.experiment self.__strategy: str = specifications.strategy self.__optimization: str = specifications.optimization self.__metric: str = specifications.metric self.__precision: int = specifications.precision # Todo: Make this part a bit more generic! # Sometimes we want the result of only one benchmark # Sometimes we want the result of a family of benchmarks or a whole experiment self.__in_paths: List[str] = self.find_input_report_paths() self.__reports: List[Stats] = self.import_reports() @property def benchmark(self): return self.__benchmark @property def approximate_benchmark(self): return self.__approximate_benchmark @property def experiment(self): return self.__experiment @property def strategy(self): return self.__strategy @property def optimization(self): return self.__optimization @property def metric(self): return self.__metric @property def precision(self): return self.__precision @property def reports(self): return self.__reports @reports.setter def reports(self, reports: List[Stats]): self.__reports = deepcopy(reports) @property def in_paths(self): return self.__in_paths @in_paths.setter def in_paths(self, list): self.__in_paths = list # TODO # fix naming: include num_samples def find_relevant_csv(self): relevant_csv = [] folder, extension = INPUT_PATH['report'] if self.metric == WRE: if (self.optimization == OPTIMIZE or self.optimization == MAXIMIZE) and (self.strategy != BISECTION): cur_dir = f'{folder}/{self.benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{self.optimization}' else: cur_dir = f'{folder}/{self.benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}' else: if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): cur_dir = f'{folder}/{self.benchmark}_{self.experiment}_{self.metric}_{self.strategy}_{self.optimization}' else: cur_dir = f'{folder}/{self.benchmark}_{self.experiment}_{self.metric}_{self.strategy}' all_csv = [f for f in os.listdir(cur_dir)] for f in all_csv: if f.endswith(extension): relevant_csv.append(f'{cur_dir}/{f}') relevant_csv = natsort.natsorted(relevant_csv) # sorting the files alphabetically in descending order return relevant_csv def find_input_report_paths(self): input_paths = [] folder, extension = INPUT_PATH['report'] if self.experiment == SINGLE: input_paths = self.find_relevant_csv() elif self.experiment == QOR: if self.metric == WRE: if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): input_paths.append( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}_{self.optimization}.{extension}') else: input_paths.append( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_d{self.precision}_{self.strategy}.{extension}') else: if self.optimization == OPTIMIZE or self.optimization == MAXIMIZE and (self.strategy != BISECTION): input_paths.append( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}_{self.optimization}.{extension}') else: input_paths.append( f'{folder}/{self.approximate_benchmark}_{self.experiment}_{self.metric}_{self.strategy}.{extension}') elif self.experiment == RANDOM: pass return input_paths def import_reports(self): reports: List = [] for report_path in self.in_paths: reports.append(Stats(report_path)) return reports def find_relevant_paths(self, folder: str, extension: str): all = [f for f in os.listdir(folder)] labelling_folders = [] qor_paths = [] for f in all: if re.search(self.metric, f): if f.endswith(extension): qor_paths.append(f'{folder}/{f}') else: labelling_folders.append(f'{folder}/{f}') labelling_paths = [] for fold in labelling_folders: cur_files = [f for f in os.listdir(fold)] for c_file in cur_files: if c_file.endswith(extension): labelling_paths.append(f'{fold}/{c_file}') relevant_paths = labelling_paths + qor_paths self.in_paths = [] self.in_paths = relevant_paths def extract_fields_for_three_strategies(self): monotonic_files = [] kind_files = [] bisection_files = [] for report_path in self.in_paths: if re.search(MONOTONIC, report_path): monotonic_files.append(report_path) elif re.search(KIND_BISECTION, report_path): kind_files.append(report_path) elif re.search(BISECTION, report_path): bisection_files.append(report_path) monotonic_files = natsort.natsorted(monotonic_files) kind_files = natsort.natsorted(kind_files) bisection_files = natsort.natsorted(bisection_files) count = 0 for i in range(len(monotonic_files)): mono = monotonic_files[i].replace(MONOTONIC, '') kind = kind_files[i].replace(KIND_BISECTION, '') bisec = bisection_files[i].replace(BISECTION, '') if mono == kind == bisec: count += 1 if count == len(monotonic_files): print(f'TEST -> PASS') monotonic_reports = [] kind_reports = [] bisection_reports = [] for report_path in monotonic_files: monotonic_reports.append(Stats(report_path)) for report_path in kind_files: kind_reports.append(Stats(report_path)) for report_path in bisection_files: bisection_reports.append(Stats(report_path)) return monotonic_reports, kind_reports, bisection_reports def collect_reports_for_three_strategies(self): folder, extension = OUTPUT_PATH['report'] self.find_relevant_paths(folder, extension) monotonic_reports, kind_reports, bisection_reports = self.extract_fields_for_three_strategies() return monotonic_reports, kind_reports, bisection_reports def extract_fields_as_list(self, reports: List[Stats], field): field_list = [] i = 0 for stat in reports: if field == TOTAL_RUNTIME: field_list.append(float(stat.total_runtime)) elif field == N_SATS or field == N_UNSATS: field_list.append(int(stat.num_sats) + int(stat.num_unsats)) else: print(f'ERROR!!! No such attribute in class Stats') return field_list def draw_scatter_plot_all(self, field: str): monotonic_reports, kind_reports, bisection_reports = self.collect_reports_for_three_strategies() folder, extension = OUTPUT_PATH['figure'] os.makedirs(f'{folder}', exist_ok=True) filename1 = f'{folder}/{SCATTER}_{self.metric}_{MONOTONIC}_{KIND_BISECTION}.{extension}' filename2 = f'{folder}/{SCATTER}_{self.metric}_{MONOTONIC}_{BISECTION}.{extension}' # print(f'{monotonic_reports = }') monotonic_list = self.extract_fields_as_list(monotonic_reports, field) kind_list = self.extract_fields_as_list(kind_reports, field) bisection_list = self.extract_fields_as_list(bisection_reports, field) max_monotonic = max(monotonic_list) max_kind = max(kind_list) max_bisection = max(bisection_list) max_value1 = max(max_monotonic, max_kind) max_value2 = max(max_monotonic, max_bisection) if self.metric == WAE: color = 'blue' elif self.metric == WRE: color = 'red' elif self.metric == WHD: color = 'black' a = [1] * 10 # monotonic_list = [1] * len(monotonic_list) plt.rc('font', size=SMALL_SIZE+6) # controls default text sizes plt.rc('axes', titlesize=BIGGER_SIZE+6) # fontsize of the axes title plt.rc('axes', labelsize=BIGGER_SIZE+5) # fontsize of the x and y labels plt.rc('xtick', labelsize=MEDIUM_SIZE+1) # fontsize of the tick labels plt.rc('ytick', labelsize=MEDIUM_SIZE+1) # fontsize of the tick labels plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title plt.tight_layout() plt.rcParams["figure.figsize"] = (6, 5) plt.tight_layout() fig1, ax1 = plt.subplots() ax1.locator_params(tight=True, nbins=4) ErrorEval = 'ErrorEval' ax1.set( xlabel=f'bisection+ runtime', ylabel=f'{ErrorEval} runtime') ax1.set_title(f'{self.metric.upper()}: {ErrorEval} vs. bisection+') plt.scatter(kind_list, monotonic_list, c=color, s=10, marker='o', edgecolors=color, linewidths=1, alpha=0.1) plt.plot(list(np.arange(0, (max_value1), 0.01)), list(np.arange(0, (max_value1), 0.01)), c='grey') plt.xscale('log') plt.yscale('log') ax1.get_xaxis().set_major_formatter(matplotlib.ticker.LogFormatter()) ax1.get_yaxis().set_major_formatter(matplotlib.ticker.LogFormatter()) ax1.set_xticks([10 ** -2, 1, 100] * 10) ax1.set_yticks([10 ** -2, 1, 100] * 10) ax1.yaxis.set_label_coords(-.1, .5) plt.savefig(f'{filename1}') plt.close() # Figure2: Monotonic vs bisection fig2, ax2 = plt.subplots() ax2.set(xlabel=f'{BISECTION} runtime', ylabel=f'{ErrorEval} runtime') ax2.set_title(f'{self.metric.upper()}: {ErrorEval} vs. {BISECTION}') plt.scatter(bisection_list, monotonic_list, c=color, s=10, marker='o', edgecolors=color, linewidths=0.5, alpha=0.1) plt.plot(list(np.arange(0, (max_value2), 0.01)), list(np.arange(0, (max_value2), 0.01)), c='grey') plt.yscale('log') plt.xscale('log') ax2.get_xaxis().set_major_formatter(matplotlib.ticker.LogFormatter()) ax2.get_yaxis().set_major_formatter(matplotlib.ticker.LogFormatter()) ax2.set_xticks([10**-2, 1, 100] * 10) ax2.set_yticks([10**-2, 1, 100] * 10) ax2.yaxis.set_label_coords(-.1, .5) plt.savefig(f'{filename2}') plt.close() pass def avg_runtime(self, field): monotonic_reports, kind_reports, bisection_reports = self.collect_reports_for_three_strategies() monotonic_list = self.extract_fields_as_list(monotonic_reports, field) kind_list = self.extract_fields_as_list(kind_reports, field) bisection_list = self.extract_fields_as_list(bisection_reports, field) total_count = len(monotonic_list) monotonic_is_less_than_kind = 0 monotonic_is_less_than_bisection = 0 for i in range(len(monotonic_list)): if monotonic_list[i] < kind_list[i]: monotonic_is_less_than_kind += 1 if monotonic_list[i] < bisection_list[i]: monotonic_is_less_than_bisection += 1 print(f'monotonic < bisection+ (%) = {(monotonic_is_less_than_kind/total_count) * 100}%') print(f'monotonic < bisection (%) = {(monotonic_is_less_than_bisection / total_count) * 100}%') print(f'{len(monotonic_list) = }') def draw_avg_plot_all(self, field): monotonic_reports, kind_reports, bisection_reports = self.collect_reports_for_three_strategies() folder, extension = OUTPUT_PATH['figure'] os.makedirs(f'{folder}', exist_ok=True) filename1 = f'{folder}/{AVERAGE}_{self.metric}_{MONOTONIC}_{KIND_BISECTION}.{extension}' filename2 = f'{folder}/{AVERAGE}_{self.metric}_{MONOTONIC}_{BISECTION}.{extension}' monotonic_list = self.extract_fields_as_list(monotonic_reports, field) kind_list = self.extract_fields_as_list(kind_reports, field) bisection_list = self.extract_fields_as_list(bisection_reports, field) # print(monotonic_list[0]) # print(kind_list[0]) # print(bisection_list[0]) # Create iterator object def __iter__(self): pass def __next__(self): pass def __repr__(self): return f'An object of class Result\n' \ f'{self.benchmark = }\n' \ f'{self.approximate_benchmark = }\n' \ f'{self.experiment = }\n' \ f'{self.strategy = }\n' \ f'{self.metric = }\n' def __len__(self): return len(self.__dict__)
z3log
/z3log-1.1.1.tar.gz/z3log-1.1.1/Z3Log/result.py
result.py
from zope import interface, schema, component from zope.component.interfaces import IFactory from zope.i18n import MessageFactory _ = MessageFactory('z3wingdbg') # The main debug service class IWingDebugService(interface.Interface): """Debug service manager""" def startDebugServer(): """Start the debug server May throw a DebugServerStartError. """ def stopDebugServer(): """Stop the debug server""" debugServerRunning = interface.Attribute( 'Boolean flag indicating wether or not the debug server is running') def connectIDE(): """Connect the debug server to the IDE May throw a IDEConnectionError. """ def disconnectIDE(): """Disconnect the IDE""" connectedToIDE = interface.Attribute( 'Boolean flag indicating wether or not the debug server is connected ' 'to the IDE') server = interface.Attribute('The currently running debug server, or None') debugger = interface.Attribute('The active debugger, or None') # Service exceptions class DebugServerStartError(Exception): """The debug server failed to start""" class IDEConnectionError(Exception): """The debugger failed to connect to the IDE""" # The networked debugger class INetworkDebugger(interface.Interface): """The network debug server This object is actually both a client to the debugger and a server to the remote debug client. """ def connectClient(): """Establish a connection to client if there isn't one already.""" def disconnectClient(): """Drop connection to client""" clientConnected = interface.Attribute( 'Boolean determining if the IDE is connected') def start(): """Start the debugger Subsequent code in the current thread is under control of the debugger. """ def stop(): """Stop the debug session and drop connection to remote client""" # A debug server class IDebugServer(interface.Interface): """A server publishing code under debugger control Upon creation, the server should run all requests in a debugger context. The runInDebugContext method should allow passed-in callables to be run within the same context. The server is responsible for starting and eventually stopping the debugger. """ def shutdown(): """Shut down the server""" def runInDebugContext(callable): """Run code in the debugger context""" # Attachment password source types PWD_PROFILE, PWD_PATH, PWD_MANUAL = range(3) # Configuration of the service and debug server class IWingConfiguration(interface.Interface): """Debug service configuration""" wingHome = schema.TextLine( title=_(u'Wing Home'), description=_(u'wing-home-description', u'The directory where Wing IDE is installed on this ' u"machine. This is used to find Wing IDE's debugger " u'support modules.')) ideHost = schema.TextLine( title=_(u'IDE hostname'), description=_(u'ide-hostname-description', u'The host where Wing IDE is listening for the debug ' u'connection.'), default=u'localhost') idePort = schema.Int( title=_(u'IDE port'), description=_(u'ide-port-description', u'The port where Wing IDE is listening for the debug ' u'connection.'), default=50005, min=0, max=65535) serverType = schema.Choice( title=_(u'Debug server type'), description=_(u'server-type-description', u'Type of server to use for the debug server'), default=u'http', vocabulary=u'z3wingdbg.servertypes') autoStart = schema.Bool( title=_(u'Auto-start debug server'), description=_(u'auto-start-description', u'Automatically start the debug server when Zope starts ' u'and is running in Developer Mode.'), default=False) autoConnect = schema.Bool( title=_(u'Auto-connect IDE'), description=_(u'auto-connect-description', u'Automatically try to connect to the IDE when the ' u'debug server is started'), default=True) attachPort = schema.Int( title=_(u'Attachment port'), description=_(u'attach-port-description', u'Optional port where the debugger will listen for ' u'incoming connections from the Wing IDE.'), default=None, min=0, max=65535, required=False) @interface.invariant def noAutoStartAndAttachPort(obj): """Cannot specify both auto-starting and an attachment port""" if obj.autoStart and (obj.attachPort is not None): raise interface.Invalid( _(u'Cannot specify both auto-start and an attachment port')) attachPasswordSource = schema.Choice( title=_(u'Password source'), description=_(u'attach-password-source-description', u'Where to source the password information for the ' u'attaching IDE'), vocabulary=schema.vocabulary.SimpleVocabulary.fromItems(( (_(u'Wing Profile Directory'), PWD_PROFILE), (_(u'Specified path'), PWD_PATH), (_(u'Specified password'), PWD_MANUAL))), default=PWD_PROFILE) attachPasswordPath = schema.TextLine( title=_(u'Password source path'), description=_(u'attach-password-path-description', u'The path to a password source file. Can be both a ' u'file as well as a directory path; in the latter case ' u'the file .wingdebugpw in that directory will be ' u'used.'), required=False) attachPassword = schema.BytesLine( title=_(u'Attach password'), description=_(u'attach-password-description', u'Password to be supplied by attaching IDE'), required=False) @interface.invariant def checkAttachPassword(obj): """If source is not PWD_PROFILE, the source needs to be specified""" if obj.attachPasswordSource == PWD_PATH and not obj.attachPasswordPath: raise interface.Invalid( _(u'Please specify the path of the password source')) elif obj.attachPasswordSource == PWD_MANUAL and not obj.attachPassword: raise interface.Invalid( _(u'Please specify an attach password')) class IDebugServerConfiguration(interface.Interface): """Debug server configuration""" host = schema.TextLine( title=_(u'Host'), description=_(u'server-host-description', u'The host where the debugger will listen for requests ' u'from your client.'), default=u'localhost') port = schema.Int( title=_(u'Port'), description=_(u'server-port-description', u'The port where the debugger will listen for requests'), min=0, max=65535) # Factories class INetworkDebuggerFactory(IFactory): """Networked debugger factory""" def __call__(configuration): """Create a networked debugger instance""" class IDebugServerFactory(IFactory): """Debug server factory""" def __call__(configuration, debugger): """Create a debug server""" # Utilities class IWingDebuggerVersion(interface.Interface): """Wing Debugger version""" def getWingDebuggerVersion(): """Return a string containing the debugger version (possibly including SVN information)""" class IWingPathInformation(interface.Interface): """Wing path information""" platformDefault = interface.Attribute( 'Default wingHome value for the current platform') softwareHome = interface.Attribute( 'Path to Wing software installation. Raises a ValueError when set ' 'to an invalid path (e.g. not a Wing installation. If set it may ' 'be readjusted to the reflect a platform-specific path.') # Events class IDebugStateChangedEvent(interface.Interface): """Indicates that the debugger states changed.""" service = interface.Attribute('The debug service') class IDebugServerStartedEvent(IDebugStateChangedEvent): """The debug server has started""" class IDebugServerStoppedEvent(IDebugStateChangedEvent): """The debug server has been stopped""" class IIDEConnectedEvent(IDebugStateChangedEvent): """The debugger connected to the IDE Note that this event is only fired when the connection is started by the Zope3 service, not when the IDE starts the connection. """ class IIDEDisconnectedEvent(IDebugStateChangedEvent): """The debugger disconnected from the IDE Note that this event is only fired when the connection is closed by the Zope3 service, not when the IDE closes the connection. """ class DebugStateChangedEvent(object): interface.implements(IDebugStateChangedEvent) def __init__(self): self.service = component.getUtility(IWingDebugService) # Generate the rest of the events as simple subclasses for iface in (IDebugServerStartedEvent, IDebugServerStoppedEvent, IIDEConnectedEvent, IIDEDisconnectedEvent): name = iface.__name__[1:] klass = type(name, (DebugStateChangedEvent,), {}) interface.classImplements(klass, iface) globals()[name] = klass # Vocabularies def getServerTypesVocabulary(context): """List all available debug server types""" types = component.getUtilitiesFor(IDebugServerFactory) return schema.vocabulary.SimpleVocabulary.fromValues(t[0] for t in types)
z3wingdbg
/z3wingdbg-0.2.0.tar.gz/z3wingdbg-0.2.0/interfaces.py
interfaces.py
-------------------------------------------------- z3wingdbg: Wing IDE debugger integration for Zope3 -------------------------------------------------- Overview -------- Zope3 package providing debug integration with the Wing IDE, allowing you to run Zope3 applications under the control of the Wing debugger. Requirements ------------ - Zope 3 (>= 3.3) - Wing IDE (>= 2.0.2) Installation ------------ Simply install this package using the standard distutils mantra:: $ python setup.py install Alternatively, you can install z3wingdbg straight into a Zope3 instance by using the --home switch:: $ python setup.py install --home=/path/to/instance Then copy the included ``z3wingdbg-include.zcml`` file to your Zope3 instance's ``etc/package-includes`` directory (or link it) to have Zope3 load z3wingdbg. Usage ----- z3wingdbg adds a few configuration objects to the root site manager at /++etc++site/default/WingConfiguration. Server configuration objects can be found on the Contents tab, while the Edit tab lets you set general options. In a future release the included debugger management views will include a more userfriendly way of altering the configation, as well as documentation. In the root ZMI view of your Zope3 instance, a link titled 'Manage Wing Debugger' leads to /++wing++debugger/, where you can control the debug server. Once started, all calls to the debug server (by default, an HTTP server listening on http://localhost:50080/) can be controlled by the Wing IDE. Links ----- Project homepage (including downloads) http://www.zopatista.com/projects/z3wingdbg Development http://trac.zopatista.com/zopatista/z3wingdbg Subversion Repository https://svn.zopatista.com/zopatista/z3wingdbg http://trac.zopatista.com/zopatista/browser/z3wingdbg Reporting bugs, feature requests http://trac.zopatista.com/zopatista/
z3wingdbg
/z3wingdbg-0.2.0.tar.gz/z3wingdbg-0.2.0/README.txt
README.txt
import logging import time from ZODB.interfaces import IDatabase from zope import component, event, interface from zope.i18n import MessageFactory from zope.app.appsetup.appsetup import getConfigContext from zope.app.component.hooks import getSite from zope.app.publication.zopepublication import ZopePublication from interfaces import IWingDebugService, IWingConfiguration from interfaces import IDebugServerConfiguration, INetworkDebuggerFactory from interfaces import IDebugServerFactory, DebugServerStartError from interfaces import IDEConnectionError, IDEConnectedEvent from interfaces import IDEDisconnectedEvent _ = MessageFactory('z3wingdbg') class WingDebugService(object): interface.implements(IWingDebugService) server = None debugger = None def startDebugServer(self, context=None): if self.debugServerRunning: return if context is None: context = getSite() config = component.getUtility(IWingConfiguration, context=context) serverconfig = component.queryUtility(IDebugServerConfiguration, config.serverType, context=context) if not serverconfig: raise DebugServerStartError( _(u'debugserver-config-not-found', u'Could not find any configuration for the ${serverType} ' u'debug server', dict(serverType=config.serverType))) debuggerFactory = component.getUtility(INetworkDebuggerFactory) serverFactory = component.queryUtility(IDebugServerFactory, config.serverType) if not serverFactory: raise DebugServerStartError( _(u'debugserver-factory-not-found', u'Could not find a factory for the ${serverType} ' u'debug server', dict(serverType=config.serverType))) try: self.debugger = debuggerFactory(config) except (ValueError, ImportError): raise DebugServerStartError(_( u'winghome-incorrect', u'The Wing debug libraries could not be loaded, please verify ' u'your configured Wing Home')) self.server = serverFactory(serverconfig, self.debugger) if config.autoConnect: self.connectIDE() def stopDebugServer(self): if not self.debugServerRunning: return self.server.shutdown() self.server = self.debugger = None @property def debugServerRunning(self): return self.server is not None def connectIDE(self): if not self.debugServerRunning or self.connectedToIDE: return connected = [] def connectClient(): self.debugger.connectClient() connected.append(self.debugger.clientConnected) self.server.runInDebugContext(connectClient) # time out the call, up to 5 seconds timeout = time.time() + 5 while time.time() < timeout and not connected: time.sleep(0.05) if not connected or not connected[0]: message = _(u'ide-connection-failure', u'Failed to connect to the IDE. Check your IDE host ' u'and port are correct.') if not connected: message = _(u'ide-connection-timeout', u'Connection to IDE timed out') raise IDEConnectionError(message) else: event.notify(IDEConnectedEvent()) def disconnectIDE(self): if not (self.debugServerRunning and self.connectedToIDE): return # Call disconnect from the current thread. Not entirely thread-safe, # but with multiple calls to disconnectClient, we at the worst get # exceptions from an already cleared __fChannel. try: self.debugger.disconnectClient() except: pass else: event.notify(IDEDisconnectedEvent()) @property def connectedToIDE(self): return self.debugger is not None and self.debugger.clientConnected WingDebugServiceUtility = WingDebugService() def handleProcessStart(event): """Start the Wing Debug Server at startup if so configured""" # Open a context database = component.getUtility(IDatabase) connection = database.open() root = connection.root() root_folder = root.get(ZopePublication.root_name, None) log = logging.getLogger('z3wingdbg.wingdebugservice') try: if root_folder is None: return debugmode = getConfigContext().hasFeature('devmode') if not debugmode: return config = component.queryUtility(IWingConfiguration, context=root_folder) if not config: return if not config.autoStart: return if config.attachPort is not None: log.warn('Not autostarting the wing debug server when allowing ' 'remote connections.') return service = component.getUtility(IWingDebugService) try: service.startDebugServer(context=root_folder) except (DebugServerStartError, IDEConnectionError): pass finally: connection.close()
z3wingdbg
/z3wingdbg-0.2.0.tar.gz/z3wingdbg-0.2.0/wingdebugservice.py
wingdebugservice.py
from zope import component from zope.publisher.browser import BrowserView from zope.i18n import MessageFactory from z3wingdbg.interfaces import IWingDebuggerVersion, IWingDebugService from z3wingdbg.interfaces import DebugServerStartError, IDEConnectionError _ = MessageFactory('z3wingdbg') class ControlView(BrowserView): def getService(self): return component.getUtility(IWingDebugService) def getVersion(self): version = component.getUtility(IWingDebuggerVersion) return version.getWingDebuggerVersion() def getStatus(self): service = self.getService() if service.debugServerRunning: debugger = dict( color='green', status=_(u'Started'), action='debugger.stop', action_label=_(u'Stop Debugger')) if service.connectedToIDE: ide = dict( color='green', status=_(u'Connected'), action='ide.disconnect', action_label=_(u'Disconnect IDE')) else: ide = dict( color='red', status=_(u'Not connected'), action='ide.connect', action_label=_(u'Connect IDE')) else: debugger = dict( color='red', status=_(u'Stopped'), action='debugger.start', action_label=_(u'Start Debugger')) ide = dict( color='grey', status=_(u'No debugger'), action='ide.connect', action_label=_(u'Connect IDE'), disabled=True) return dict(debugger=debugger, ide=ide) actions = ('debugger.start', 'debugger.stop', 'ide.connect', 'ide.disconnect') def action(self): service = self.getService() for action in self.actions: if action in self.request: return getattr(self, action.replace('.', '_'))(service) def debugger_start(self, service): if service.debugServerRunning: return _(u'The server is already running') try: service.startDebugServer() except (DebugServerStartError, IDEConnectionError), exception: return exception.args[0] return _(u'Debugger started') def debugger_stop(self, service): if not service.debugServerRunning: return _(u'The server is not running') service.stopDebugServer() return _(u'Debugger stopped') def ide_connect(self, service): if service.connectedToIDE: return _(u'The debugger is already connected to the IDE') try: service.connectIDE() except IDEConnectionError, exception: return exception.args[0] return _(u'Connected to IDE') def ide_disconnect(self, service): if not service.connectedToIDE: return _(u'The debugger is not connected to the IDE') service.disconnectIDE() return _(u'Disconnected the IDE')
z3wingdbg
/z3wingdbg-0.2.0.tar.gz/z3wingdbg-0.2.0/browser/debuggercontrol.py
debuggercontrol.py
import logging import os from zope import component, interface from zope.i18n import MessageFactory from z3wingdbg.interfaces import INetworkDebugger, INetworkDebuggerFactory from z3wingdbg.interfaces import IWingPathInformation, DebugServerStartError from z3wingdbg.interfaces import PWD_PROFILE, PWD_PATH, PWD_MANUAL from netservermodule import INetServerModule _ = MessageFactory('z3wingdbg') class LogWrapper(object): """Wrapper around the standard logging module for Wing NetworkServer Strips subsystem and datestamp from written lines (log module already provides these) and logs lines with DEBUG severity """ _data = '' def __init__(self): self._logger = logging.getLogger('z3wingdbg.debugger.networkdebugger') def _strip(self, line): # Lines are of the form "wingdb - Y/m/d H:M:S - log info"; discard # everything before the second ' - ' return line.split(' - ', 3)[-1] def write(self, text): self._data += text while '\n' in self._data: line, self._data = self._data.split('\n', 1) self._logger.debug(self._strip(line)) class NetworkDebugger(object): """Network Debugger implementation Simple wrapper around netserver.CNetworkServer """ interface.implements(INetworkDebugger) _networkserver = None def __init__(self, wing_home, host, port, attachport, pwsource=PWD_PROFILE, pwpath=None, pw=None): pathinfo = component.getUtility(IWingPathInformation) nsmodule = component.getUtility(INetServerModule) pathinfo.softwareHome = wing_home netserver = nsmodule.netserver if netserver.dbgserver.dbgtracer.get_tracing(): raise DebugServerStartError( _(u'Another debugger is already active. Wing currently only ' u'supports one active debugger per process.')) attach = -1 pwdir = (netserver.abstract.kPWFilePathUserProfileDir,) pwfile = '.wingdebugpw' if attachport is not None: attach = attachport if pwsource == PWD_PATH: if not os.path.exists(pwpath or ''): raise DebugServerStartError( _(u'No valid password source path specified')) if os.path.isfile(pwpath): pwpath, pwfile = os.path.split(pwpath) pwdir = (pwpath,) logger = netserver.abstract.CErrStream((LogWrapper(),)) server = netserver.CNetworkServer( host, port, attach, logger, pwfile_path=pwdir, pwfile_name=pwfile) if attachport is None or pwsource == PWD_MANUAL: # netserver insists we set a non-empty string, but only uses # the password for verifying incoming attachment requests. password = (pwsource != PWD_MANUAL) and 'ignored' or pw server.SetSecurityInfo( netserver.abstract.securechannel.kNoEncryption, password) if attachport is not None and not server.IsSecurityInfoValid(): raise DebugServerStartError( _(u'No valid password source was provided, please check your ' u'configuration')) # We set our own sockethook later server.SetUseSocketHooksOnImport(False) self._networkserver = server def connectClient(self): self._networkserver.ConnectToClient() def disconnectClient(self): # This appears naughty: we call a private method. This is pretty # harmless though, you can also disconnect from the client side, which # results in the same method being called. self._networkserver._CNetworkServer__CloseChannel() @property def clientConnected(self): return not self._networkserver.ChannelClosed() def start(self): self._networkserver.StartDebug(connect=False) def stop(self): self._networkserver.StopDebug() def setSocketRegistrationHook(self, hook): self._networkserver.SetSocketRegHook(hook) def createDebugger(config): return NetworkDebugger(config.wingHome, config.ideHost, config.idePort, config.attachPort, config.attachPasswordSource, config.attachPasswordPath, config.attachPassword) factory = component.factory.Factory( createDebugger, interfaces=interface.implementedBy(NetworkDebugger)) interface.alsoProvides(factory, INetworkDebuggerFactory)
z3wingdbg
/z3wingdbg-0.2.0.tar.gz/z3wingdbg-0.2.0/debugger/networkdebugger.py
networkdebugger.py
import logging from twisted.internet.interfaces import IReadDescriptor from zope import component, interface from z3wingdbg.interfaces import IWingDebugService class WingDebuggerClientSocketDescriptor(object): """Wrapper around the netserver IDE client connection socket""" interface.implements(IReadDescriptor) fileno = None def __init__(self, socket, callback): socket.setblocking(0) self.socket = socket self.fileno = socket.fileno self.callback = callback self.service = component.getUtility(IWingDebugService) self.log = logging.getLogger('z3wingdbg.debugger.twistedmainloop') from twisted.internet import reactor self.reactor = reactor self.startReading() def startReading(self): """Start waiting for read availability.""" self.reactor.addReader(self) def stopReading(self): """Stop waiting for read availability""" self.reactor.removeReader(self) def logPrefix(self): """The select loop calls this on every select to log information""" return 'z3wingdbg.debugger.twistedmainloop.socketdescriptor' def connectionLost(self, *args): """Called when twisted reactor shuts down""" pass def close(self): del self.socket self.stopReading() def doRead(self): if not self.socket: return # Stop polling until the debug thread has dealt with us self.stopReading() self.log.debug('Dispatching callback on debugthread') self.service.server.runInDebugContext(self.debugThreadCallback) def debugThreadCallback(self): # Called in debug thread. Call callback and resume polling if not self.socket: return self.log.debug('In debug thread, dispatching callback') self.callback() self.startReading() # Wake up the reactor now that we are reading again self.reactor.wakeUp() class WingDebuggerClientSocketHook(object): """netserver._extensions._SocketHook implementation This class integrates the IDE client connection socket into the twisted mainloop when asked. """ descriptors = None def __init__(self): self.log = logging.getLogger('z3wingdbg.debugger.twistedmainloop') self.descriptors = {} def _Setup(self, ignored, socket, callback): """Immediatly register the passed socket""" return self._RegisterSocket(socket, callback) def _RegisterSocket(self, socket, callback): self.log.debug( 'Registering client socket %s, %#x callback with twisted', socket.getsockname(), id(socket)) descriptor = WingDebuggerClientSocketDescriptor(socket, callback) self.descriptors[socket] = descriptor return socket def _UnregisterSocket(self, socket): self.log.debug('Removing wrapped socket %#x from twisted' % id(socket)) descriptor = self.descriptors.get(socket) if descriptor: del self.descriptors[socket] descriptor.close() def handleDebugServerStart(event): """Register our sockethook with the debugger""" event.service.debugger.setSocketRegistrationHook( WingDebuggerClientSocketHook())
z3wingdbg
/z3wingdbg-0.2.0.tar.gz/z3wingdbg-0.2.0/debugger/twistedmainloop.py
twistedmainloop.py
import os # Copyright (C) 2006, Martijn Pieters <[email protected]> # This program is open source. For license terms, see the LICENSE.txt file. import sys from zope import interface from zope.cachedescriptors import property from z3wingdbg.classproperty import classproperty from z3wingdbg.interfaces import IWingPathInformation _searchPaths = ('bin', 'src') _darwinPaths = ('Contents/MacOS', 'WingIDE.app/Contents/MacOS') def _wingDebugModulePath(softwareHome): """Return a valid Wing software home containing wingdb.py, or None""" # On Mac OSX, the path needs to be extended into user-hidden directories if sys.platform.startswith('darwin'): for extra in _darwinPaths: internal = os.path.join(softwareHome, extra) for path in _searchPaths: if os.path.isfile(os.path.join(internal, path, 'wingdb.py')): return internal else: for path in _searchPaths: if os.path.isfile(os.path.join(softwareHome, path, 'wingdb.py')): return softwareHome class WingPathInformation(object): interface.implements(IWingPathInformation) _softwareHome = None @property.Lazy def platformDefault(self): if sys.platform == 'win32': return ur'c:\Program Files\Wing IDE 2.1' elif sys.platform.startswith('darwin'): return u'/Applications/WingIDE.app/Contents/MacOS' else: return u'/usr/lib/wingide2.1' class softwareHome(classproperty): def __get__(self): return self._softwareHome def __set__(self, softwareHome): if not os.path.isdir(softwareHome): raise ValueError('Not a directory') softwareHome = _wingDebugModulePath(softwareHome) if not softwareHome: raise ValueError('Not a Wing installation, wingdb.py not found') self._softwareHome = softwareHome WingPathInformationUtility = WingPathInformation()
z3wingdbg
/z3wingdbg-0.2.0.tar.gz/z3wingdbg-0.2.0/debugger/wingpathinformation.py
wingpathinformation.py
from z3 import * # noqa class Z3SolveException(Exception): pass class Z3Unsat(Z3SolveException): pass class Z3Unknown(Z3SolveException): pass class Z3CounterExample(Z3SolveException): model: ModelRef def __init__(self, model: ModelRef): super().__init__(model) self.model = model def easy_solve(constraints): solver = Solver() solver.add(*constraints) res = solver.check() if res == unsat: raise Z3Unsat elif res == unknown: raise Z3Unknown return solver.model() def find_all_solutions(constraints): """ >>> def normalize_result(r): ... return sorted(sorted((f.name(), m[f].as_long()) for f in m) for m in r) >>> a, b, c = Ints("a b c") >>> normalize_result(find_all_solutions([0 <= a, a < 3])) [[('a', 0)], [('a', 1)], [('a', 2)]] >>> normalize_result(find_all_solutions([0 <= a, a < 2, b == 2 * a])) [[('a', 0), ('b', 0)], [('a', 1), ('b', 2)]] """ solver = Solver() solver.add(*constraints) while True: res = solver.check() if res == unknown: raise Z3Unknown elif res == unsat: return model = solver.model() yield model solver.add(Not(And([f() == model[f] for f in model if f.arity() == 0]))) def easy_prove(claim): solver = Solver() solver.add(Not(claim)) res = solver.check() if res == unknown: raise Z3Unknown elif res == sat: raise Z3CounterExample(solver.model()) else: return True BitVecRef.__rshift__ = LShR BitVecRef.__rrshift__ = lambda a, b: LShR(b, a) BoolRef.__and__ = And BoolRef.__rand__ = lambda a, b: a & b BoolRef.__or__ = Or BoolRef.__ror__ = lambda a, b: a | b BoolRef.__xor__ = Xor BoolRef.__rxor__ = lambda a, b: a ^ b BoolRef.__invert__ = Not BoolRef.__add__ = lambda a, b: BoolToInt(a) + ( BoolToInt(b) if isinstance(b, BoolRef) else b ) BoolRef.__radd__ = lambda a, b: a + b _original_bool_ref_mul = BoolRef.__mul__ BoolRef.__mul__ = ( lambda a, b: BoolToInt(a) * BoolToInt(b) if isinstance(b, BoolRef) else _original_bool_ref_mul(a, b) ) BoolRef.__rmul__ = lambda a, b: a * b class ByteVec(BitVecRef): def __init__(self, name, byte_count, ctx=None): self.byte_count = byte_count self.bv = BitVec(name, byte_count * 8, ctx) def __getattr__(self, attr): return getattr(self.bv, attr) def __len__(self): return self.byte_count def __getitem__(self, i): if not isinstance(i, int): raise TypeError if i < 0: i += len(self) if not (0 <= i < len(self)): raise IndexError return Extract(8 * i + 7, 8 * i, self.bv) def value(self, model): v = model[self.bv].as_long() return v.to_bytes(self.byte_count, "little") def BoolToInt(x): return If(x, 1, 0) def Sgn(x): return If(x == 0, 0, If(x > 0, 1, -1)) def Abs(x): return If(x >= 0, x, -x) def TruncDiv(a, b): """ Truncated division, a / b rounded towards zero. >>> a, b, c = Ints("a b c") >>> easy_prove(Implies(TruncDiv(a, b) == c, Abs(b) * Abs(c) <= Abs(a))) True """ v = Abs(a) / Abs(b) return Sgn(a) * Sgn(b) * v
z4-solver
/z4_solver-2022.12.18.1.tar.gz/z4_solver-2022.12.18.1/z4.py
z4.py
# z4 [![PyPI](https://img.shields.io/pypi/v/z4-solver)](https://pypi.org/project/z4-solver/) [z3](https://github.com/Z3Prover/z3) with some improvements: * Change the right shift operation on `BitVec`'s to be logical instead of arithmetic * Extend the `*` operation on `BoolRef`'s to work between two `BoolRef`'s. * Add additional operations to `BoolRef`'s: * `+`, returning an Int kind such that e.g `True + True + False == 2` * `&`, utilizing `And()` * `|`, utilizing `Or()` * `~`, utilizing `Not()` * Add the `ByteVec` class * Some helper methods for solving: * `easy_solve` * `find_all_solutions` * `easy_prove` * Add some helper functions for z3 variables/constants: * `BoolToInt` * `Sgn` * `Abs` * `TruncDiv` ## Usage Install with `pip install z4-solver`. ### `easy_solve` ```python3 import z4 a, b = z4.Ints("a b") print(z4.easy_solve([a <= 10, b <= 10, a + b == 15])) ``` Output: ``` [b = 5, a = 10] ``` ### `find_all_solutions` ```python3 import z4 a, b = z4.Ints("a b") print(*z4.find_all_solutions([a <= 10, b <= 10, a + b == 15]), sep="\n") ``` Output: ``` [b = 5, a = 10] [b = 6, a = 9] [b = 7, a = 8] [b = 8, a = 7] [b = 9, a = 6] [b = 10, a = 5] ``` ### `easy_prove` Let's try and prove that `2 * a >= a` for all integers `a`: ```python3 import z4 a = z4.Int("a") print(z4.easy_prove(2 * a >= a)) ``` Output ``` Traceback (most recent call last): ... z4.Z3CounterExample: [a = -1] ``` This isn't true so we get an exception with the counter-example `a = -1`. Of course `2 * -1 = -2` which is less than `-1`. Let's try again with the assumption that `a` must be non-negative: ```python3 print(z4.easy_prove(z4.Implies(a >= 0, 2 * a >= a))) ``` Output: ``` True ```
z4-solver
/z4_solver-2022.12.18.1.tar.gz/z4_solver-2022.12.18.1/README.md
README.md
# cmake_example for pybind11 [![Build Status](https://travis-ci.org/pybind/cmake_example.svg?branch=master)](https://travis-ci.org/pybind/cmake_example) [![Build status](https://ci.appveyor.com/api/projects/status/57nnxfm4subeug43/branch/master?svg=true)](https://ci.appveyor.com/project/dean0x7d/cmake-example/branch/master) An example [pybind11](https://github.com/pybind/pybind11) module built with a CMake-based build system. This is useful for C++ codebases that have an existing CMake project structure. ## Prerequisites **On Unix (Linux, OS X)** * A compiler with C++11 support * CMake >= 2.8.12 **On Windows** * Visual Studio 2015 (required for all Python versions, see notes below) * CMake >= 3.1 ## Installation Just clone this repository and pip install. Note the `--recursive` option which is needed for the pybind11 submodule: ```bash git clone --recursive https://github.com/pybind/cmake_example.git pip install ./cmake_example ``` With the `setup.py` file included in this example, the `pip install` command will invoke CMake and build the pybind11 module as specified in `CMakeLists.txt`. ## Special notes for Windows **Compiler requirements** Pybind11 requires a C++11 compliant compiler, i.e Visual Studio 2015 on Windows. This applies to all Python versions, including 2.7. Unlike regular C extension modules, it's perfectly fine to compile a pybind11 module with a VS version newer than the target Python's VS version. See the [FAQ] for more details. **Runtime requirements** The Visual C++ 2015 redistributable packages are a runtime requirement for this project. It can be found [here][vs2015_runtime]. If you use the Anaconda Python distribution, you can add `vs2015_runtime` as a platform-dependent runtime requirement for you package: see the `conda.recipe/meta.yaml` file in this example. ## Building the documentation Documentation for the example project is generated using Sphinx. Sphinx has the ability to automatically inspect the signatures and documentation strings in the extension module to generate beautiful documentation in a variety formats. The following command generates HTML-based reference documentation; for other formats please refer to the Sphinx manual: - `cd cmake_example/docs` - `make html` ## License Pybind11 is provided under a BSD-style license that can be found in the LICENSE file. By using, distributing, or contributing to this project, you agree to the terms and conditions of this license. ## Test call ```python import cmake_example cmake_example.add(1, 2) ``` [FAQ]: http://pybind11.rtfd.io/en/latest/faq.html#working-with-ancient-visual-studio-2009-builds-on-windows [vs2015_runtime]: https://www.microsoft.com/en-us/download/details.aspx?id=48145
z4
/z4-0.0.1.tar.gz/z4-0.0.1/README.md
README.md
import plotly.graph_objs as go import plotly.io as pio pio.templates["z43_base"] = go.layout.Template( layout=dict( font=dict( size=14, family="Roboto" ), title=dict( x=0.5, font=dict( size=22, family="Roboto" ), ), xaxis=dict( title=dict( font=dict( size=16, family="Roboto" ) ), ticks="outside" ), yaxis=dict( title=dict( font=dict( size=16, family="Roboto" ) ), ticks="outside" ), images=[dict( x=1, y=0, sizex=0.1, sizey=0.1, source="https://github.com/odeimaiz/z43_plot_styles/blob/master/imgs/z43_logo.png?raw=true", opacity=0.5, visible=True )] ) ) pio.templates["z43_poster"] = go.layout.Template( layout=dict( font=dict( size=22, family="Roboto" ), title=dict( x=0.5, font=dict( size=40, family="Roboto" ), ), xaxis=dict( title=dict( font=dict( size=24, family="Roboto" ) ), ticks="outside" ), yaxis=dict( title=dict( font=dict( size=24, family="Roboto" ) ), ticks="outside" ), images=[dict( x=1, y=0, sizex=0.2, sizey=0.2, source="https://github.com/odeimaiz/z43_plot_styles/blob/master/imgs/z43_logo.png?raw=true", opacity=0.5, visible=True )] ) ) text_dark = "#FFFFFF" text_axes_dark = "#BFBFBF" bg_dark = "#202020" grid_dark = "#373737" pio.templates["z43_dark"] = go.layout.Template( layout=dict( font=dict( color=text_dark ), plot_bgcolor=bg_dark, paper_bgcolor=bg_dark, xaxis=dict( title=dict( font=dict( color=text_axes_dark ) ), tickfont=dict( color=text_axes_dark ), tickcolor=text_axes_dark, gridcolor=grid_dark, linecolor=grid_dark, zerolinecolor=grid_dark ), yaxis=dict( title=dict( font=dict( color=text_axes_dark ) ), tickfont=dict( color=text_axes_dark ), tickcolor=text_axes_dark, gridcolor=grid_dark, linecolor=grid_dark, zerolinecolor=grid_dark ) ) ) text_light = "#000000" text_axes_light = "#404040" bg_light = "#DFDFDF" grid_light = "#C8C8C8" pio.templates["z43_light"] = go.layout.Template( layout=dict( font=dict( color=text_light ), plot_bgcolor=bg_light, paper_bgcolor=bg_light, xaxis=dict( title=dict( font=dict( color=text_axes_light ) ), tickfont=dict( color=text_axes_light ), tickcolor=text_axes_light, gridcolor=grid_light, linecolor=grid_light, zerolinecolor=grid_light ), yaxis=dict( title=dict( font=dict( color=text_axes_light ) ), tickfont=dict( color=text_axes_light ), tickcolor=text_axes_light, gridcolor=grid_light, linecolor=grid_light, zerolinecolor=grid_light ) ) )
z43-styles
/z43_styles-0.4.tar.gz/z43_styles-0.4/z43_styles/z43_styles.py
z43_styles.py
__all__ = 'ITEMLOCATIONS', 'SKULLTULALOCATIONS' ITEMLOCATIONS = { # Overworld "Kokiri Sword Chest": { 'maps': ('item_child',), 'coordinates': (991, 2092), 'type': 'chest'}, "Deku Baba Sticks": { 'maps': (), 'coordinates': (), 'type': 'enemy'}, "Deku Baba Nuts": { 'maps': (), 'coordinates': (), 'type': 'enemy'}, "Links Pocket": { 'maps': (), 'coordinates': (), 'type': 'standard'}, "Mido House": { 'maps': ('item_child',), 'coordinates': (902, 2133), 'type': 'chest'}, "Kokiri Shop": { 'maps': ('item_child', 'item_adult'), 'coordinates': (917, 2220), 'type': 'shop', 'restriction': 'shopsanity'}, "Skull Kid": { 'maps': ('item_child',), 'coordinates': (785, 2085), 'type': 'npc'}, "Ocarina Memory Game": { 'maps': ('item_child',), 'coordinates': (810, 2232), 'type': 'npc'}, "Target in Woods": { 'maps': ('item_child',), 'coordinates': (777, 2192), 'type': 'npc'}, "LW Deku Scrub Deku Stick Upgrade": { 'maps': ('item_child',), 'coordinates': (927, 1970), 'type': 'deku'}, "LW Deku Scrub Deku Nuts": { 'maps': ('item_child',), 'coordinates': (710, 2038), 'type': 'deku', 'restriction': 'scrubshuffle'}, "LW Deku Scrub Deku Sticks": { 'maps': ('item_child',), 'coordinates': (750, 2038), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Song from Saria": { 'maps': ('item_child',), 'coordinates': (626, 2160), 'type': 'song'}, "Gift from Saria": { 'maps': ('item_child',), 'coordinates': (883, 1930), 'type': 'npc'}, "Song from Ocarina of Time": { 'maps': ('item_child',), 'coordinates': (440, 1439), 'type': 'song'}, "Ocarina of Time": { 'maps': ('item_child',), 'coordinates': (440, 1479), 'type': 'free'}, "Underwater Bottle": { 'maps': ('item_child',), 'coordinates': (1263, 1049), 'type': 'free'}, "Lake Hylia Sun": { 'maps': ('item_adult',), 'coordinates': (1435, 1080), 'type': 'chest'}, "Lake Hylia Freestanding PoH": { 'maps': ('item_adult',), 'coordinates': (1160, 961), 'type': 'heart'}, "Diving in the Lab": { 'maps': ('item_child', 'item_adult'), 'coordinates': (1200, 961), 'type': 'npc'}, "Child Fishing": { 'maps': ('item_child',), 'coordinates': (1215, 1270), 'type': 'npc'}, "Adult Fishing": { 'maps': ('item_adult',), 'coordinates': (1215, 1270), 'type': 'npc'}, "Gerudo Valley Waterfall Freestanding PoH": { 'maps': ('item_child', 'item_adult'), 'coordinates': (520, 701), 'type': 'heart'}, "Gerudo Valley Crate Freestanding PoH": { 'maps': ('item_child', 'item_adult'), 'coordinates': (633, 654), 'type': 'heart'}, "Gerudo Valley Hammer Rocks Chest": { 'maps': ('item_adult',), 'coordinates': (581, 601), 'type': 'chest'}, "Gerudo Fortress Rooftop Chest": { 'maps': ('item_adult',), 'coordinates': (318, 544), 'type': 'chest'}, "Horseback Archery 1000 Points": { 'maps': ('item_adult',), 'coordinates': (418, 620), 'type': 'npc'}, "Horseback Archery 1500 Points": { 'maps': ('item_adult',), 'coordinates': (458, 620), 'type': 'npc'}, "Gerudo Fortress North F1 Carpenter": { 'maps': (), 'coordinates': (), 'type': 'standard'}, "Gerudo Fortress North F2 Carpenter": { 'maps': (), 'coordinates': (), 'type': 'standard'}, "Gerudo Fortress South F1 Carpenter": { 'maps': (), 'coordinates': (), 'type': 'standard'}, "Gerudo Fortress South F2 Carpenter": { 'maps': (), 'coordinates': (), 'type': 'standard'}, "Gerudo Fortress Carpenter Rescue": { 'maps': ('item_adult',), 'coordinates': (358, 524), 'type': 'npc'}, "Gerudo Fortress Membership Card": { 'maps': ('item_adult',), 'coordinates': (358, 564), 'type': 'npc'}, "Haunted Wasteland Structure Chest": { 'maps': ('item_adult',), 'coordinates': (343, 380), 'type': 'chest'}, "Colossus Freestanding PoH": { 'maps': ('item_adult',), 'coordinates': (305, 160), 'type': 'heart'}, "Sheik at Colossus": { 'maps': ('item_child', 'item_adult'), 'coordinates': (347, 128), 'type': 'song'}, "Desert Colossus Fairy Reward": { 'maps': ('item_child', 'item_adult'), 'coordinates': (297, 276), 'type': 'fairy'}, "Zelda": { 'maps': ('item_adult',), 'coordinates': (279, 1519), 'type': 'npc'}, "Master Sword Pedestal": { 'maps': ('item_child',), 'coordinates': (279, 1559), 'type': 'free'}, "Sheik at Temple": { 'maps': ('item_adult',), 'coordinates': (279, 1559), 'type': 'song'}, "Malon Egg": { 'maps': ('item_child',), 'coordinates': (246, 1420), 'type': 'npc'}, "Zeldas Letter": { 'maps': ('item_child',), 'coordinates': (173, 1408), 'type': 'npc'}, "Impa at Castle": { 'maps': ('item_child',), 'coordinates': (173, 1448), 'type': 'song'}, "Hyrule Castle Fairy Reward": { 'maps': ('item_child',), 'coordinates': (236, 1505), 'type': 'fairy'}, "Ganons Castle Fairy Reward": { 'maps': ('item_adult',), 'coordinates': (206, 1520), 'type': 'fairy'}, "10 Big Poes": { 'maps': ('item_adult',), 'coordinates': (390, 1464), 'type': 'npc'}, "Castle Town Bazaar": { 'maps': ('item_child',), 'coordinates': (355, 1503), 'type': 'shop', 'restriction': 'shopsanity'}, "Child Shooting Gallery": { 'maps': ('item_child',), 'coordinates': (299, 1427), 'type': 'npc'}, "Castle Town Bombchu Bowling": { 'maps': ('item_child',), 'coordinates': (314, 1387), 'type': 'npc'}, "Castle Town Potion Shop": { 'maps': ('item_child',), 'coordinates': (315, 1503), 'type': 'shop', 'restriction': 'shopsanity'}, "Treasure Chest Game": { 'maps': ('item_child',), 'coordinates': (360, 1416), 'type': 'npc'}, "Castle Town Bombchu Shop": { 'maps': ('item_child',), 'coordinates': (360, 1376), 'type': 'shop', 'restriction': 'shopsanity'}, "Dog Lady": { 'maps': ('item_child',), 'coordinates': (355, 1463), 'type': 'npc'}, "Man on Roof": { 'maps': ('item_child', 'item_adult'), 'coordinates': (371, 1830), 'type': 'npc'}, "Anju as Adult": { 'maps': ('item_adult',), 'coordinates': (451, 1867), 'type': 'npc'}, "Anjus Chickens": { 'maps': ('item_child',), 'coordinates': (431, 1867), 'type': 'npc'}, "Sheik in Kakariko": { 'maps': ('item_adult',), 'coordinates': (387, 1734), 'type': 'song'}, "10 Gold Skulltula Reward": { 'maps': ('item_child', 'item_adult'), 'coordinates': (1200, 280), 'type': 'npc'}, "20 Gold Skulltula Reward": { 'maps': ('item_child', 'item_adult'), 'coordinates': (1200, 320), 'type': 'npc'}, "30 Gold Skulltula Reward": { 'maps': ('item_child', 'item_adult'), 'coordinates': (1200, 360), 'type': 'npc'}, "40 Gold Skulltula Reward": { 'maps': ('item_child', 'item_adult'), 'coordinates': (1200, 400), 'type': 'npc'}, "50 Gold Skulltula Reward": { 'maps': ('item_child', 'item_adult'), 'coordinates': (1200, 440), 'type': 'npc'}, "Impa House Freestanding PoH": { 'maps': ('item_child', 'item_adult'), 'coordinates': (451, 1827), 'type': 'heart'}, "Windmill Freestanding PoH": { 'maps': ('item_child', 'item_adult'), 'coordinates': (356, 1915), 'type': 'heart'}, "Song at Windmill": { 'maps': ('item_adult',), 'coordinates': (396, 1915), 'type': 'song'}, "Kakariko Bazaar": { 'maps': ('item_adult',), 'coordinates': (347, 1780), 'type': 'shop', 'restriction': 'shopsanity'}, "Adult Shooting Gallery": { 'maps': ('item_adult',), 'coordinates': (411, 1837), 'type': 'npc'}, "Kakariko Potion Shop Front": { 'maps': ('item_adult',), 'coordinates': (331, 1824), 'type': 'shop', 'restriction': 'shopsanity'}, "Graveyard Freestanding PoH": { 'maps': ('item_child', 'item_adult'), 'coordinates': (335, 1980), 'type': 'heart'}, "Gravedigging Tour": { 'maps': ('item_child',), 'coordinates': (342, 2030), 'type': 'npc'}, "Shield Grave Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (382, 2030), 'type': 'sub'}, "Heart Piece Grave Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (350, 2070), 'type': 'sub'}, "Composer Grave Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (333, 2110), 'type': 'sub'}, "Song from Composer Grave": { 'maps': ('item_child', 'item_adult'), 'coordinates': (373, 2110), 'type': 'song'}, "Hookshot Chest": { 'maps': ('item_adult',), 'coordinates': (342, 2030), 'type': 'sub'}, "Dampe Race Freestanding PoH": { 'maps': ('item_adult',), 'coordinates': (302, 2030), 'type': 'sub'}, "Death Mountain Bombable Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (221, 1744), 'type': 'chest'}, "DM Trail Freestanding PoH": { 'maps': ('item_child', 'item_adult'), 'coordinates': (190, 1664), 'type': 'heart'}, "Goron City Leftmost Maze Chest": { 'maps': ('item_adult',), 'coordinates': (98, 1556), 'type': 'chest'}, "Goron City Left Maze Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (78, 1596), 'type': 'chest'}, "Goron City Right Maze Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (118, 1596), 'type': 'chest'}, "Goron City Pot Freestanding PoH": { 'maps': ('item_child',), 'coordinates': (70, 1684), 'type': 'heart'}, "Rolling Goron as Child": { 'maps': ('item_child',), 'coordinates': (110, 1684), 'type': 'npc'}, "Link the Goron": { 'maps': ('item_adult',), 'coordinates': (110, 1684), 'type': 'npc'}, "Goron City Stick Pot": { 'maps': (), 'coordinates': (), 'type': 'free'}, "Goron Shop": { 'maps': ('item_child', 'item_adult'), 'coordinates': (128, 1646), 'type': 'shop', 'restriction': 'shopsanity'}, "Darunias Joy": { 'maps': ('item_child',), 'coordinates': (90, 1646), 'type': 'npc'}, "DM Crater Wall Freestanding PoH": { 'maps': ('item_child', 'item_adult'), 'coordinates': (66, 1834), 'type': 'heart'}, "Biggoron": { 'maps': ('item_adult',), 'coordinates': (100, 1790), 'type': 'npc'}, "DMC Deku Scrub Bombs": { 'maps': ('item_child',), 'coordinates': (26, 1744), 'type': 'deku', 'restriction': 'scrubshuffle'}, "DM Crater Volcano Freestanding PoH": { 'maps': ('item_adult',), 'coordinates': (26, 1754), 'type': 'heart'}, "Sheik in Crater": { 'maps': ('item_child', 'item_adult'), 'coordinates': (26, 1834), 'type': 'song'}, "Crater Fairy Reward": { 'maps': ('item_adult',), 'coordinates': (66, 1874), 'type': 'fairy'}, "Mountain Summit Fairy Reward": { 'maps': ('item_child', 'item_adult'), 'coordinates': (66, 1744), 'type': 'fairy'}, "Magic Bean Salesman": { 'maps': (), 'coordinates': (), 'type': 'npc'}, "Frog Ocarina Game": { 'maps': ('item_child',), 'coordinates': (481, 2184), 'type': 'npc'}, "Frogs in the Rain": { 'maps': ('item_child',), 'coordinates': (481, 2144), 'type': 'npc'}, "Zora River Lower Freestanding PoH": { 'maps': ('item_child', 'item_adult'), 'coordinates': (474, 2037), 'type': 'heart'}, "Zora River Upper Freestanding PoH": { 'maps': ('item_child', 'item_adult'), 'coordinates': (425, 2347), 'type': 'heart'}, "Diving Minigame": { 'maps': ('item_child',), 'coordinates': (429, 2556), 'type': 'npc'}, "Zoras Domain Torch Run": { 'maps': ('item_child',), 'coordinates': (442, 2610), 'type': 'chest'}, "King Zora Moves": { 'maps': (), 'coordinates': (373, 2550), 'type': 'npc'}, "Zoras Domain Stick Pot": { 'maps': (), 'coordinates': (), 'type': 'free'}, "Zoras Domain Nut Pot": { 'maps': (), 'coordinates': (), 'type': 'free'}, "King Zora Thawed": { 'maps': ('item_adult',), 'coordinates': (373, 2550), 'type': 'npc'}, "Zoras Fountain Iceberg Freestanding PoH": { 'maps': ('item_adult',), 'coordinates': (292, 2554), 'type': 'heart'}, "Zoras Fountain Bottom Freestanding PoH": { 'maps': ('item_adult',), 'coordinates': (319, 2514), 'type': 'heart'}, "Zora Shop": { 'maps': ('item_child', 'item_adult'), 'coordinates': (499, 2619), 'type': 'shop', 'restriction': 'shopsanity'}, "Zoras Fountain Fairy Reward": { 'maps': ('item_child', 'item_adult'), 'coordinates': (333, 2553), 'type': 'fairy'}, "Epona": { 'maps': (), 'coordinates': (), 'type': 'npc'}, "Song from Malon": { 'maps': ('item_child',), 'coordinates': (647, 1295), 'type': 'song'}, "Talons Chickens": { 'maps': ('item_child',), 'coordinates': (580, 1348), 'type': 'npc'}, "Lon Lon Tower Freestanding PoH": { 'maps': ('item_child',), 'coordinates': (690, 1227), 'type': 'heart'}, "Sheik Forest Song": { 'maps': ('item_adult',), 'coordinates': (626, 2160), 'type': 'song'}, "Kokiri Forest Storms Grotto Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (845, 2192), 'type': 'sub'}, "Lost Woods Generic Grotto Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (777, 2149), 'type': 'sub'}, "Deku Theater Skull Mask": { 'maps': ('item_child',), 'coordinates': (730, 2078), 'type': 'sub'}, "Deku Theater Mask of Truth": { 'maps': ('item_child',), 'coordinates': (730, 2118), 'type': 'sub'}, "LW Grotto Deku Scrub Arrows": { 'maps': ('item_child', 'item_adult'), 'coordinates': (724, 2260), 'type': 'deku', 'restriction': 'scrubshuffle'}, "LW Grotto Deku Scrub Deku Nut Upgrade": { 'maps': ('item_child', 'item_adult'), 'coordinates': (724, 2220), 'type': 'deku'}, "SFM Grotto Deku Scrub Red Potion": { 'maps': ('item_child', 'item_adult'), 'coordinates': (626, 2220), 'type': 'deku', 'restriction': 'scrubshuffle'}, "SFM Grotto Deku Scrub Green Potion": { 'maps': ('item_child', 'item_adult'), 'coordinates': (626, 2260), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Wolfos Grotto Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (710, 2180), 'type': 'sub'}, "LLR Grotto Deku Scrub Deku Nuts": { 'maps': ('item_child',), 'coordinates': (690, 1375), 'type': 'deku', 'restriction': 'scrubshuffle'}, "LLR Grotto Deku Scrub Bombs": { 'maps': ('item_child',), 'coordinates': (670, 1415), 'type': 'deku', 'restriction': 'scrubshuffle'}, "LLR Grotto Deku Scrub Arrows": { 'maps': ('item_child',), 'coordinates': (710, 1335), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Remote Southern Grotto Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (925, 1427), 'type': 'sub'}, "Field Near Lake Outside Fence Grotto Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (997, 1206), 'type': 'sub'}, "HF Grotto Deku Scrub Piece of Heart": { 'maps': ('item_child', 'item_adult'), 'coordinates': (999, 1141), 'type': 'deku'}, "Field West Castle Town Grotto Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (440, 1372), 'type': 'sub'}, "Tektite Grotto Freestanding PoH": { 'maps': ('item_child', 'item_adult'), 'coordinates': (481, 1152), 'type': 'sub'}, "Redead Grotto Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (406, 1774), 'type': 'sub'}, "Kakariko Back Grotto Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (326, 1865), 'type': 'sub'}, "Mountain Storms Grotto Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (158, 1705), 'type': 'sub'}, "Goron Grotto Deku Scrub Deku Nuts": { 'maps': ('item_adult',), 'coordinates': (115, 1689), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Goron Grotto Deku Scrub Bombs": { 'maps': ('item_adult',), 'coordinates': (75, 1689), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Goron Grotto Deku Scrub Arrows": { 'maps': ('item_adult',), 'coordinates': (35, 1689), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Top of Crater Grotto Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (42, 1794), 'type': 'sub'}, "DMC Grotto Deku Scrub Deku Nuts": { 'maps': ('item_adult',), 'coordinates': (146, 1830), 'type': 'deku', 'restriction': 'scrubshuffle'}, "DMC Grotto Deku Scrub Bombs": { 'maps': ('item_adult',), 'coordinates': (126, 1870), 'type': 'deku', 'restriction': 'scrubshuffle'}, "DMC Grotto Deku Scrub Arrows": { 'maps': ('item_adult',), 'coordinates': (106, 1910), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Zora River Plateau Open Grotto Chest": { 'maps': ('item_child', 'item_adult'), 'coordinates': (540, 2092), 'type': 'sub'}, "ZR Grotto Deku Scrub Red Potion": { 'maps': ('item_child', 'item_adult'), 'coordinates': (560, 2052), 'type': 'deku', 'restriction': 'scrubshuffle'}, "ZR Grotto Deku Scrub Green Potion": { 'maps': ('item_child', 'item_adult'), 'coordinates': (580, 2012), 'type': 'deku', 'restriction': 'scrubshuffle'}, "LH Grotto Deku Scrub Deku Nuts": { 'maps': ('item_child', 'item_adult'), 'coordinates': (1309, 870), 'type': 'deku', 'restriction': 'scrubshuffle'}, "LH Grotto Deku Scrub Bombs": { 'maps': ('item_child', 'item_adult'), 'coordinates': (1289, 830), 'type': 'deku', 'restriction': 'scrubshuffle'}, "LH Grotto Deku Scrub Arrows": { 'maps': ('item_child', 'item_adult'), 'coordinates': (1329, 830), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Desert Grotto Deku Scrub Red Potion": { 'maps': ('item_adult',), 'coordinates': (245, 200), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Desert Grotto Deku Scrub Green Potion": { 'maps': ('item_adult',), 'coordinates': (285, 200), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Valley Grotto Deku Scrub Red Potion": { 'maps': ('item_adult',), 'coordinates': (630, 605), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Valley Grotto Deku Scrub Green Potion": { 'maps': ('item_adult',), 'coordinates': (630, 565), 'type': 'deku', 'restriction': 'scrubshuffle'}, # Deku Tree "Deku Tree Lobby Chest": { 'maps': ('Deku Tree',), 'coordinates': (565, 1283), 'type': 'chest'}, "Deku Tree Compass Chest": { 'maps': ('Deku Tree',), 'coordinates': (140, 769), 'type': 'chest'}, "Deku Tree Compass Room Side Chest": { 'maps': ('Deku Tree',), 'coordinates': (260, 760), 'type': 'chest'}, "Deku Tree Basement Chest": { 'maps': ('Deku Tree',), 'coordinates': (1280, 1350), 'type': 'chest'}, "Deku Tree Slingshot Chest": { 'maps': ('Deku Tree',), 'coordinates': (480, 350), 'type': 'chest'}, "Deku Tree Slingshot Room Side Chest": { 'maps': ('Deku Tree',), 'coordinates': (390, 470), 'type': 'chest'}, "Queen Gohma Heart": { 'maps': ('Deku Tree',), 'coordinates': (1580, 1590), 'type': 'chest'}, "Queen Gohma": { 'maps': ('Deku Tree',), 'coordinates': (1530, 1650), 'type': 'chest'}, # Dodongo's Cavern "Dodongos Cavern Map Chest": { 'maps': ('Dodongos Cavern',), 'coordinates': (1530, 930), 'type': 'chest'}, "Dodongos Cavern Compass Chest": { 'maps': ('Dodongos Cavern',), 'coordinates': (1460, 110), 'type': 'chest'}, "DC Deku Scrub Deku Sticks": { 'maps': ('Dodongos Cavern',), 'coordinates': (1580, 760), 'type': 'deku', 'restriction': 'scrubshuffle'}, "DC Deku Scrub Deku Shield": { 'maps': ('Dodongos Cavern',), 'coordinates': (1640, 2760), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Dodongos Cavern Bomb Flower Platform": { 'maps': ('Dodongos Cavern',), 'coordinates': (790, 1470), 'type': 'chest'}, "DC Deku Scrub Deku Seeds": { 'maps': ('Dodongos Cavern',), 'coordinates': (600, 2030), 'type': 'deku', 'restriction': 'scrubshuffle'}, "DC Deku Scrub Deku Nuts": { 'maps': ('Dodongos Cavern',), 'coordinates': (640, 2150), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Dodongos Cavern Bomb Bag Chest": { 'maps': ('Dodongos Cavern',), 'coordinates': (630, 1680), 'type': 'chest'}, "Dodongos Cavern End of Bridge Chest": { 'maps': ('Dodongos Cavern',), 'coordinates': (360, 1070), 'type': 'chest'}, "Chest Above King Dodongo": { 'maps': ('Dodongos Cavern',), 'coordinates': (1200, 1450), 'type': 'chest'}, "King Dodongo Heart": { 'maps': ('Dodongos Cavern',), 'coordinates': (1100, 980), 'type': 'chest'}, "King Dodongo": { 'maps': ('Dodongos Cavern',), 'coordinates': (1090, 1040), 'type': 'chest'}, # Jabu Jabus Belly's Belly "Boomerang Chest": { 'maps': ('Jabu Jabus Belly',), 'coordinates': (830, 2600), 'type': 'chest'}, "Jabu Deku Scrub Deku Nuts": { 'maps': ('Jabu Jabus Belly',), 'coordinates': (1250, 730), 'type': 'deku', 'restriction': 'scrubshuffle'}, "Jabu Jabus Belly Map Chest": { 'maps': ('Jabu Jabus Belly',), 'coordinates': (450, 1450), 'type': 'chest'}, "Jabu Jabus Belly Compass Chest": { 'maps': ('Jabu Jabus Belly',), 'coordinates': (460, 2150), 'type': 'chest'}, "Barinade Heart": { 'maps': ('Jabu Jabus Belly',), 'coordinates': (1070, 2120), 'type': 'chest'}, "Barinade": { 'maps': ('Jabu Jabus Belly',), 'coordinates': (1040, 2200), 'type': 'chest'}, # Forest Temple "Forest Temple First Chest": { 'maps': ('Forest Temple',), 'coordinates': (1850, 180), 'type': 'chest'}, "Forest Temple Chest Behind Lobby": { 'maps': ('Forest Temple',), 'coordinates': (1520, 1740), 'type': 'chest'}, "Forest Temple Well Chest": { 'maps': ('Forest Temple',), 'coordinates': (2280, 1500), 'type': 'chest'}, "Forest Temple Map Chest": { 'maps': ('Forest Temple',), 'coordinates': (1080, 1520), 'type': 'chest'}, "Forest Temple Outside Hookshot Chest": { 'maps': ('Forest Temple',), 'coordinates': (1750, 2340), 'type': 'chest'}, "Forest Temple Falling Room Chest": { 'maps': ('Forest Temple',), 'coordinates': (2040, 2420), 'type': 'chest'}, "Forest Temple Block Push Chest": { 'maps': ('Forest Temple',), 'coordinates': (1420, 320), 'type': 'chest'}, "Forest Temple Boss Key Chest": { 'maps': ('Forest Temple',), 'coordinates': (560, 1350), 'type': 'chest'}, "Forest Temple Floormaster Chest": { 'maps': ('Forest Temple',), 'coordinates': (1000, 490), 'type': 'chest'}, "Forest Temple Bow Chest": { 'maps': ('Forest Temple',), 'coordinates': (610, 2010), 'type': 'chest'}, "Forest Temple Red Poe Chest": { 'maps': ('Forest Temple',), 'coordinates': (490, 1880), 'type': 'chest'}, "Forest Temple Blue Poe Chest": { 'maps': ('Forest Temple',), 'coordinates': (650, 2260), 'type': 'chest'}, "Forest Temple Near Boss Chest": { 'maps': ('Forest Temple',), 'coordinates': (2560, 310), 'type': 'chest'}, "Phantom Ganon Heart": { 'maps': ('Forest Temple',), 'coordinates': (2340, 1240), 'type': 'chest'}, "Phantom Ganon": { 'maps': ('Forest Temple',), 'coordinates': (2290, 1200), 'type': 'chest'}, # Fire Temple "Fire Temple Chest Near Boss": { 'maps': ('Fire Temple',), 'coordinates': (2400, 960), 'type': 'chest'}, "Fire Temple Fire Dancer Chest": { 'maps': ('Fire Temple',), 'coordinates': (2040, 2210), 'type': 'chest'}, "Fire Temple Boss Key Chest": { 'maps': ('Fire Temple',), 'coordinates': (2190, 1920), 'type': 'chest'}, "Fire Temple Big Lava Room Bombable Chest": { 'maps': ('Fire Temple',), 'coordinates': (3020, 1880), 'type': 'chest'}, "Fire Temple Big Lava Room Open Chest": { 'maps': ('Fire Temple',), 'coordinates': (2650, 3330), 'type': 'chest'}, "Volvagia Heart": { 'maps': ('Fire Temple',), 'coordinates': (2160, 660), 'type': 'chest'}, "Volvagia": { 'maps': ('Fire Temple',), 'coordinates': (2120, 510), 'type': 'chest'}, "Fire Temple Boulder Maze Lower Chest": { 'maps': ('Fire Temple',), 'coordinates': (1890, 2800), 'type': 'chest'}, "Fire Temple Boulder Maze Upper Chest": { 'maps': ('Fire Temple',), 'coordinates': (1820, 2640), 'type': 'chest'}, "Fire Temple Boulder Maze Side Room": { 'maps': ('Fire Temple',), 'coordinates': (1480, 3470), 'type': 'chest'}, "Fire Temple Boulder Maze Bombable Pit": { 'maps': ('Fire Temple',), 'coordinates': (2240, 3120), 'type': 'chest'}, "Fire Temple Scarecrow Chest": { 'maps': ('Fire Temple',), 'coordinates': (820, 3250), 'type': 'chest'}, "Fire Temple Map Chest": { 'maps': ('Fire Temple',), 'coordinates': (1500, 2000), 'type': 'chest'}, "Fire Temple Compass Chest": { 'maps': ('Fire Temple',), 'coordinates': (1100, 1540), 'type': 'chest'}, "Fire Temple Highest Goron Chest": { 'maps': ('Fire Temple',), 'coordinates': (1650, 900), 'type': 'chest'}, "Fire Temple Megaton Hammer Chest": { 'maps': ('Fire Temple',), 'coordinates': (270, 140), 'type': 'chest'}, # Water Temple "Water Temple Map Chest": { 'maps': ('Water Temple',), 'coordinates': (1970, 2690), 'type': 'chest'}, "Water Temple Compass Chest": { 'maps': ('Water Temple',), 'coordinates': (1700, 2920), 'type': 'chest'}, "Water Temple Torches Chest": { 'maps': ('Water Temple',), 'coordinates': (2220, 2550), 'type': 'chest'}, "Water Temple Dragon Chest": { 'maps': ('Water Temple',), 'coordinates': (890, 1430), 'type': 'chest'}, "Water Temple Central Bow Target Chest": { 'maps': ('Water Temple',), 'coordinates': (2280, 1400), 'type': 'chest'}, "Water Temple Boss Key Chest": { 'maps': ('Water Temple',), 'coordinates': (1290, 2390), 'type': 'chest'}, "Morpha Heart": { 'maps': ('Water Temple',), 'coordinates': (970, 2670), 'type': 'chest'}, "Morpha": { 'maps': ('Water Temple',), 'coordinates': (930, 2740), 'type': 'chest'}, "Water Temple Central Pillar Chest": { 'maps': ('Water Temple',), 'coordinates': (2630, 2000), 'type': 'chest'}, "Water Temple Cracked Wall Chest": { 'maps': ('Water Temple',), 'coordinates': (1980, 2380), 'type': 'chest'}, "Water Temple Dark Link Chest": { 'maps': ('Water Temple',), 'coordinates': (170, 1700), 'type': 'chest'}, "Water Temple River Chest": { 'maps': ('Water Temple',), 'coordinates': (760, 1930), 'type': 'chest'}, # Spirit Temple "Spirit Temple Child Left Chest": { 'maps': ('Spirit Temple',), 'coordinates': (1310, 140), 'type': 'chest'}, "Spirit Temple Child Right Chest": { 'maps': ('Spirit Temple',), 'coordinates': (1370, 660), 'type': 'chest'}, "Spirit Temple Nut Crate": { 'maps': (), 'coordinates': (), 'type': 'free'}, "Spirit Temple Child Climb East Chest": { 'maps': ('Spirit Temple',), 'coordinates': (340, 1280), 'type': 'chest'}, "Spirit Temple Child Climb North Chest": { 'maps': ('Spirit Temple',), 'coordinates': (280, 1210), 'type': 'chest'}, "Spirit Temple Compass Chest": { 'maps': ('Spirit Temple',), 'coordinates': (1320, 950), 'type': 'chest'}, "Spirit Temple Early Adult Right Chest": { 'maps': ('Spirit Temple',), 'coordinates': (1120, 1440), 'type': 'chest'}, "Spirit Temple First Mirror Right Chest": { 'maps': ('Spirit Temple',), 'coordinates': (520, 2100), 'type': 'chest'}, "Spirit Temple First Mirror Left Chest": { 'maps': ('Spirit Temple',), 'coordinates': (460, 2100), 'type': 'chest'}, "Spirit Temple Map Chest": { 'maps': ('Spirit Temple',), 'coordinates': (320, 1600), 'type': 'chest'}, "Spirit Temple Sun Block Room Chest": { 'maps': ('Spirit Temple',), 'coordinates': (2280, 2100), 'type': 'chest'}, "Spirit Temple Statue Hand Chest": { 'maps': ('Spirit Temple',), 'coordinates': (1610, 2480), 'type': 'chest'}, "Spirit Temple NE Main Room Chest": { 'maps': ('Spirit Temple',), 'coordinates': (1500, 2890), 'type': 'chest'}, "Silver Gauntlets Chest": { 'maps': ('Spirit Temple',), 'coordinates': (2710, 2410), 'type': 'chest'}, "Mirror Shield Chest": { 'maps': ('Spirit Temple',), 'coordinates': (2710, 2920), 'type': 'chest'}, "Spirit Temple Near Four Armos Chest": { 'maps': ('Spirit Temple',), 'coordinates': (1840, 3380), 'type': 'chest'}, "Spirit Temple Hallway Left Invisible Chest": { 'maps': ('Spirit Temple',), 'coordinates': (2460, 3440), 'type': 'chest'}, "Spirit Temple Hallway Right Invisible Chest": { 'maps': ('Spirit Temple',), 'coordinates': (2460, 3370), 'type': 'chest'}, "Spirit Temple Boss Key Chest": { 'maps': ('Spirit Temple',), 'coordinates': (90, 890), 'type': 'chest'}, "Spirit Temple Topmost Chest": { 'maps': ('Spirit Temple',), 'coordinates': (370, 340), 'type': 'chest'}, "Twinrova Heart": { 'maps': ('Spirit Temple',), 'coordinates': (250, 2810), 'type': 'chest'}, "Twinrova": { 'maps': ('Spirit Temple',), 'coordinates': (420, 2640), 'type': 'chest'}, # Shadow Temple "Shadow Temple Map Chest": { 'maps': ('Shadow Temple',), 'coordinates': (550, 3130), 'type': 'chest'}, "Shadow Temple Hover Boots Chest": { 'maps': ('Shadow Temple',), 'coordinates': (850, 2700), 'type': 'chest'}, "Shadow Temple Compass Chest": { 'maps': ('Shadow Temple',), 'coordinates': (550, 5020), 'type': 'chest'}, "Shadow Temple Early Silver Rupee Chest": { 'maps': ('Shadow Temple',), 'coordinates': (210, 4480), 'type': 'chest'}, "Shadow Temple Invisible Blades Visible Chest": { 'maps': ('Shadow Temple',), 'coordinates': (700, 5870), 'type': 'chest'}, "Shadow Temple Invisible Blades Invisible Chest": { 'maps': ('Shadow Temple',), 'coordinates': (750, 5990), 'type': 'chest'}, "Shadow Temple Falling Spikes Lower Chest": { 'maps': ('Shadow Temple',), 'coordinates': (1640, 4760), 'type': 'chest'}, "Shadow Temple Falling Spikes Upper Chest": { 'maps': ('Shadow Temple',), 'coordinates': (1740, 4830), 'type': 'chest'}, "Shadow Temple Falling Spikes Switch Chest": { 'maps': ('Shadow Temple',), 'coordinates': (1610, 4970), 'type': 'chest'}, "Shadow Temple Invisible Spikes Chest": { 'maps': ('Shadow Temple',), 'coordinates': (1430, 4070), 'type': 'chest'}, "Shadow Temple Freestanding Key": { 'maps': ('Shadow Temple',), 'coordinates': (1470, 3646), 'type': 'chest'}, "Shadow Temple Wind Hint Chest": { 'maps': ('Shadow Temple',), 'coordinates': (970, 4440), 'type': 'chest'}, "Shadow Temple After Wind Enemy Chest": { 'maps': ('Shadow Temple',), 'coordinates': (910, 3640), 'type': 'chest'}, "Shadow Temple After Wind Hidden Chest": { 'maps': ('Shadow Temple',), 'coordinates': (940, 3790), 'type': 'chest'}, "Shadow Temple Spike Walls Left Chest": { 'maps': ('Shadow Temple',), 'coordinates': (2060, 240), 'type': 'chest'}, "Shadow Temple Boss Key Chest": { 'maps': ('Shadow Temple',), 'coordinates': (2000, 430), 'type': 'chest'}, "Shadow Temple Hidden Floormaster Chest": { 'maps': ('Shadow Temple',), 'coordinates': (2330, 1210), 'type': 'chest'}, "Bongo Bongo Heart": { 'maps': ('Shadow Temple',), 'coordinates': (2290, 2800), 'type': 'chest'}, "Bongo Bongo": { 'maps': ('Shadow Temple',), 'coordinates': (2260, 2930), 'type': 'chest'}, # Bottom of the Well "Bottom of the Well Front Left Hidden Wall": { 'maps': ('Bottom of the Well',), 'coordinates': (630, 870), 'type': 'chest'}, "Bottom of the Well Front Center Bombable": { 'maps': ('Bottom of the Well',), 'coordinates': (620, 970), 'type': 'chest'}, "Bottom of the Well Right Bottom Hidden Wall": { 'maps': ('Bottom of the Well',), 'coordinates': (620, 1240), 'type': 'chest'}, "Bottom of the Well Center Large Chest": { 'maps': ('Bottom of the Well',), 'coordinates': (530, 920), 'type': 'chest'}, "Bottom of the Well Center Small Chest": { 'maps': ('Bottom of the Well',), 'coordinates': (530, 1180), 'type': 'chest'}, "Bottom of the Well Back Left Bombable": { 'maps': ('Bottom of the Well',), 'coordinates': (100, 620), 'type': 'chest'}, "Bottom of the Well Freestanding Key": { 'maps': ('Bottom of the Well',), 'coordinates': (450, 110), 'type': 'chest'}, "Bottom of the Well Defeat Boss": { 'maps': ('Bottom of the Well',), 'coordinates': (790, 1560), 'type': 'chest'}, "Bottom of the Well Invisible Chest": { 'maps': ('Bottom of the Well',), 'coordinates': (780, 1680), 'type': 'chest'}, "Bottom of the Well Underwater Front Chest": { 'maps': ('Bottom of the Well',), 'coordinates': (780, 1010), 'type': 'chest'}, "Bottom of the Well Underwater Left Chest": { 'maps': ('Bottom of the Well',), 'coordinates': (400, 510), 'type': 'chest'}, "Bottom of the Well Basement Chest": { 'maps': ('Bottom of the Well',), 'coordinates': (1560, 1900), 'type': 'chest'}, "Bottom of the Well Locked Pits": { 'maps': ('Bottom of the Well',), 'coordinates': (330, 1510), 'type': 'chest'}, "Bottom of the Well Behind Right Grate": { 'maps': ('Bottom of the Well',), 'coordinates': (400, 1480), 'type': 'chest'}, "Bottom of the Well Stick Pot": { 'maps': (), 'coordinates': (), 'type': 'free'}, # Ice Caverns "Ice Cavern Map Chest": { 'maps': ('Ice Cavern',), 'coordinates': (240, 1990), 'type': 'chest'}, "Ice Cavern Compass Chest": { 'maps': ('Ice Cavern',), 'coordinates': (1070, 1530), 'type': 'chest'}, "Ice Cavern Iron Boots Chest": { 'maps': ('Ice Cavern',), 'coordinates': (620, 510), 'type': 'chest'}, "Ice Cavern Freestanding PoH": { 'maps': ('Ice Cavern',), 'coordinates': (1020, 1730), 'type': 'chest'}, "Sheik in Ice Cavern": { 'maps': ('Ice Cavern',), 'coordinates': (580, 510), 'type': 'chest'}, # Gerudo Training Grounds "Gerudo Training Grounds Lobby Left Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (1540, 730), 'type': 'chest'}, "Gerudo Training Grounds Lobby Right Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (1540, 910), 'type': 'chest'}, "Gerudo Training Grounds Stalfos Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (1500, 170), 'type': 'chest'}, "Gerudo Training Grounds Beamos Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (1630, 1440), 'type': 'chest'}, "Gerudo Training Grounds Hidden Ceiling Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (1470, 1180), 'type': 'chest'}, "Gerudo Training Grounds Maze Path First Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (1080, 580), 'type': 'chest'}, "Gerudo Training Grounds Maze Path Second Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (880, 660), 'type': 'chest'}, "Gerudo Training Grounds Maze Path Third Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (890, 720), 'type': 'chest'}, "Gerudo Training Grounds Maze Path Final Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (1050, 820), 'type': 'chest'}, "Gerudo Training Grounds Maze Right Central Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (1080, 920), 'type': 'chest'}, "Gerudo Training Grounds Maze Right Side Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (1020, 980), 'type': 'chest'}, "Gerudo Training Grounds Freestanding Key": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (1080, 1270), 'type': 'chest'}, "Gerudo Training Grounds Underwater Silver Rupee Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (1060, 1730), 'type': 'chest'}, "Gerudo Training Grounds Hammer Room Clear Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (470, 1430), 'type': 'chest'}, "Gerudo Training Grounds Hammer Room Switch Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (590, 1430), 'type': 'chest'}, "Gerudo Training Grounds Eye Statue Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (570, 870), 'type': 'chest'}, "Gerudo Training Grounds Near Scarecrow Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (1330, 1170), 'type': 'chest'}, "Gerudo Training Grounds Before Heavy Block Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (540, 290), 'type': 'chest'}, "Gerudo Training Grounds Heavy Block First Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (200, 240), 'type': 'chest'}, "Gerudo Training Grounds Heavy Block Second Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (160, 170), 'type': 'chest'}, "Gerudo Training Grounds Heavy Block Third Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (110, 250), 'type': 'chest'}, "Gerudo Training Grounds Heavy Block Fourth Chest": { 'maps': ('Gerudo Training Grounds',), 'coordinates': (70, 170), 'type': 'chest'}, # Ganon's Castle "GC Deku Scrub Bombs": { 'maps': ('Ganons Castle',), 'coordinates': (2720, 2060), 'type': 'chest', 'restriction': 'scrubshuffle'}, "GC Deku Scrub Arrows": { 'maps': ('Ganons Castle',), 'coordinates': (2770, 1990), 'type': 'chest', 'restriction': 'scrubshuffle'}, "GC Deku Scrub Red Potion": { 'maps': ('Ganons Castle',), 'coordinates': (2770, 1920), 'type': 'chest', 'restriction': 'scrubshuffle'}, "GC Deku Scrub Green Potion": { 'maps': ('Ganons Castle',), 'coordinates': (2720, 1850), 'type': 'chest', 'restriction': 'scrubshuffle'}, "Ganons Castle Forest Trial Chest": { 'maps': ('Ganons Castle',), 'coordinates': (2400, 2140), 'type': 'chest'}, "Ganons Castle Forest Trial Clear": { 'maps': (), 'coordinates': (), 'type': 'chest'}, "Ganons Castle Fire Trial Clear": { 'maps': (), 'coordinates': (), 'type': 'chest'}, "Ganons Castle Water Trial Left Chest": { 'maps': ('Ganons Castle',), 'coordinates': (1620, 2580), 'type': 'chest'}, "Ganons Castle Water Trial Right Chest": { 'maps': ('Ganons Castle',), 'coordinates': (1850, 2580), 'type': 'chest'}, "Ganons Castle Water Trial Clear": { 'maps': (), 'coordinates': (), 'type': 'chest'}, "Ganons Castle Shadow Trial First Chest": { 'maps': ('Ganons Castle',), 'coordinates': (1090, 1980), 'type': 'chest'}, "Ganons Castle Shadow Trial Second Chest": { 'maps': ('Ganons Castle',), 'coordinates': (660, 2470), 'type': 'chest'}, "Ganons Castle Shadow Trial Clear": { 'maps': (), 'coordinates': (), 'type': 'chest'}, "Ganons Castle Spirit Trial First Chest": { 'maps': ('Ganons Castle',), 'coordinates': (2310, 1130), 'type': 'chest'}, "Ganons Castle Spirit Trial Second Chest": { 'maps': ('Ganons Castle',), 'coordinates': (2450, 1050), 'type': 'chest'}, "Ganons Castle Spirit Trial Clear": { 'maps': (), 'coordinates': (), 'type': 'chest'}, "Ganons Castle Light Trial First Left Chest": { 'maps': ('Ganons Castle',), 'coordinates': (1860, 1210), 'type': 'chest'}, "Ganons Castle Light Trial Second Left Chest": { 'maps': ('Ganons Castle',), 'coordinates': (1900, 1120), 'type': 'chest'}, "Ganons Castle Light Trial Third Left Chest": { 'maps': ('Ganons Castle',), 'coordinates': (1860, 990), 'type': 'chest'}, "Ganons Castle Light Trial First Right Chest": { 'maps': ('Ganons Castle',), 'coordinates': (1650, 1210), 'type': 'chest'}, "Ganons Castle Light Trial Second Right Chest": { 'maps': ('Ganons Castle',), 'coordinates': (1610, 1120), 'type': 'chest'}, "Ganons Castle Light Trial Third Right Chest": { 'maps': ('Ganons Castle',), 'coordinates': (1650, 990), 'type': 'chest'}, "Ganons Castle Light Trial Invisible Enemies Chest": { 'maps': ('Ganons Castle',), 'coordinates': (1750, 1120), 'type': 'chest'}, "Ganons Castle Light Trial Lullaby Chest": { 'maps': ('Ganons Castle',), 'coordinates': (1710, 930), 'type': 'chest'}, "Ganons Castle Light Trial Clear": { 'maps': (), 'coordinates': (), 'type': 'chest'}, "Ganons Tower Boss Key Chest": { 'maps': ('Ganons Castle',), 'coordinates': (1850, 3670), 'type': 'chest'}, # The final destination "Ganon": { 'maps': ('item_adult',), 'coordinates': (50, 1440), 'type': 'ganon'}, # Gossip stones 'Kokiri Forest Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (890, 2095), 'type': 'stone'}, 'Deku Tree Gossip Stone (Left)': { 'maps': ('item_child', 'item_adult'), 'coordinates': (790, 2400), 'type': 'stone'}, 'Deku Tree Gossip Stone (Right)': { 'maps': ('item_child', 'item_adult'), 'coordinates': (840, 2550), 'type': 'stone'}, 'Sacred Forest Meadow Maze Gossip Stone (Lower)': { 'maps': ('item_child', 'item_adult'), 'coordinates': (670, 2180), 'type': 'stone'}, 'Sacred Forest Meadow Saria Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (620, 2120), 'type': 'stone'}, 'Lost Woods Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (940, 1930), 'type': 'stone'}, 'Temple of Time Gossip Stone (Left)': { 'maps': ('item_child', 'item_adult'), 'coordinates': (320, 1543), 'type': 'stone'}, 'Hyrule Castle Malon Gossip Stone': { 'maps': ('item_child',), 'coordinates': (270, 1465), 'type': 'stone'}, 'Hyrule Castle Rock Wall Gossip Stone': { 'maps': ('item_child',), 'coordinates': (210, 1360), 'type': 'stone'}, 'Castle Storms Grotto Gossip Stone': { 'maps': ('item_child',), 'coordinates': (196, 1520), 'type': 'stone'}, 'Graveyard Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (380, 2150), 'type': 'stone'}, 'Goron City Medigoron Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (158, 1606), 'type': 'stone'}, 'Goron City Maze Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (50, 1636), 'type': 'stone'}, 'Dodongos Cavern Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (230, 1700), 'type': 'stone'}, 'Death Mountain Trail Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (140, 1790), 'type': 'stone'}, 'Death Mountain Crater Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (105, 1830), 'type': 'stone'}, 'Zoras River Plateau Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (470, 2100), 'type': 'stone'}, 'Zoras River Waterfall Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (470, 2400), 'type': 'stone'}, 'Zoras Domain Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (373, 2590), 'type': 'stone'}, 'Lake Hylia Lab Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (1220, 870), 'type': 'stone'}, 'Lake Hylia Gossip Stone (Southwest)': { 'maps': ('item_child', 'item_adult'), 'coordinates': (1520, 930), 'type': 'stone'}, 'Lake Hylia Gossip Stone (Southeast)': { 'maps': ('item_child', 'item_adult'), 'coordinates': (1520, 1190), 'type': 'stone'}, 'Zoras Fountain Jabu Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (359, 2510), 'type': 'stone'}, 'Zoras River Plateau Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (313, 2593), 'type': 'stone'}, 'Field Valley Grotto Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (680, 950), 'type': 'stone'}, 'Gerudo Valley Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (530, 661), 'type': 'stone'}, 'Desert Colossus Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (370, 50), 'type': 'stone'}, 'Generic Grotto Gossip Stone': { 'maps': ('item_child', 'item_adult'), 'coordinates': (1200, 480), 'type': 'stone'} } SKULLTULALOCATIONS = { "GS Kokiri Know It All House": { 'maps': ('skulls_child',), 'coordinates': (958, 2055), 'type': 'night'}, "GS Kokiri Bean Patch": { 'maps': ('skulls_child',), 'coordinates': (917, 2256), 'type': 'bean'}, "GS Kokiri House of Twins": { 'maps': ('skulls_adult',), 'coordinates': (981, 2262), 'type': 'night'}, "GS Lost Woods Bean Patch Near Bridge": { 'maps': ('skulls_child',), 'coordinates': (824, 2062), 'type': 'bean'}, "GS Lost Woods Bean Patch Near Stage": { 'maps': ('skulls_child',), 'coordinates': (740, 2142), 'type': 'bean'}, "GS Lake Hylia Bean Patch": { 'maps': ('skulls_child',), 'coordinates': (1179, 1002), 'type': 'bean'}, "GS Lake Hylia Lab Wall": { 'maps': ('skulls_child',), 'coordinates': (1207, 930), 'type': 'night'}, "GS Lake Hylia Small Island": { 'maps': ('skulls_child',), 'coordinates': (1405, 1132), 'type': 'night'}, "GS Lake Hylia Giant Tree": { 'maps': ('skulls_adult',), 'coordinates': (1415, 1009), 'type': 'night'}, "GS Lab Underwater Crate": { 'maps': ('skulls_adult',), 'coordinates': (1229, 959), 'type': 'tree'}, "GS Gerudo Valley Small Bridge": { 'maps': ('skulls_child',), 'coordinates': (560, 806), 'type': 'night'}, "GS Gerudo Valley Bean Patch": { 'maps': ('skulls_child',), 'coordinates': (594, 667), 'type': 'bean'}, "GS Gerudo Valley Behind Tent": { 'maps': ('skulls_adult',), 'coordinates': (517, 635), 'type': 'night'}, "GS Gerudo Valley Pillar": { 'maps': ('skulls_adult',), 'coordinates': (581, 571), 'type': 'night'}, "GS Gerudo Fortress Archery Range": { 'maps': ('skulls_adult',), 'coordinates': (306, 660), 'type': 'night'}, "GS Gerudo Fortress Top Floor": { 'maps': ('skulls_adult',), 'coordinates': (375, 544), 'type': 'night'}, "GS Wasteland Ruins": { 'maps': ('skulls_adult',), 'coordinates': (313, 360), 'type': 'high'}, "GS Desert Colossus Bean Patch": { 'maps': ('skulls_child',), 'coordinates': (347, 88), 'type': 'bean'}, "GS Desert Colossus Tree": { 'maps': ('skulls_adult',), 'coordinates': (433, 157), 'type': 'night'}, "GS Desert Colossus Hill": { 'maps': ('skulls_adult',), 'coordinates': (322, 233), 'type': 'night'}, "GS Hyrule Castle Tree": { 'maps': ('skulls_child',), 'coordinates': (246, 1409), 'type': 'tree'}, "GS Outside Ganon's Castle": { 'maps': ('skulls_adult',), 'coordinates': (206, 1490), 'type': 'spider'}, "GS Castle Market Guard House": { 'maps': ('skulls_child',), 'coordinates': (390, 1464), 'type': 'tree'}, "GS Kakariko House Under Construction": { 'maps': ('skulls_child',), 'coordinates': (401, 1837), 'type': 'night'}, "GS Kakariko Skulltula House": { 'maps': ('skulls_child',), 'coordinates': (427, 1767), 'type': 'night'}, "GS Kakariko Guard's House": { 'maps': ('skulls_child',), 'coordinates': (347, 1774), 'type': 'night'}, "GS Kakariko Tree": { 'maps': ('skulls_child',), 'coordinates': (387, 1734), 'type': 'tree'}, "GS Kakariko Watchtower": { 'maps': ('skulls_child',), 'coordinates': (341, 1814), 'type': 'night'}, "GS Kakariko Above Impa's House": { 'maps': ('skulls_adult',), 'coordinates': (418, 1767), 'type': 'night'}, "GS Graveyard Wall": { 'maps': ('skulls_child',), 'coordinates': (380, 2065), 'type': 'night'}, "GS Graveyard Bean Patch": { 'maps': ('skulls_child',), 'coordinates': (335, 2000), 'type': 'bean'}, "GS Mountain Trail Bean Patch": { 'maps': ('skulls_child',), 'coordinates': (252, 1684), 'type': 'bean'}, "GS Mountain Trail Bomb Alcove": { 'maps': ('skulls_child', 'skulls_adult'), 'coordinates': (278, 1728), 'type': 'spider'}, "GS Mountain Trail Path to Crater": { 'maps': ('skulls_adult',), 'coordinates': (190, 1694), 'type': 'night'}, "GS Mountain Trail Above Dodongo's Cavern": { 'maps': ('skulls_adult',), 'coordinates': (158, 1744), 'type': 'night'}, "GS Goron City Boulder Maze": { 'maps': ('skulls_child',), 'coordinates': (68, 1591), 'type': 'tree'}, "GS Goron City Center Platform": { 'maps': ('skulls_adult',), 'coordinates': (90, 1646), 'type': 'spider'}, "GS Death Mountain Crater Crate": { 'maps': ('skulls_child',), 'coordinates': (80, 1796), 'type': 'tree'}, "GS Mountain Crater Bean Patch": { 'maps': ('skulls_child',), 'coordinates': (66, 1871), 'type': 'bean'}, "GS Zora River Tree": { 'maps': ('skulls_child',), 'coordinates': (545, 1935), 'type': 'tree'}, "GS Zora River Ladder": { 'maps': ('skulls_child',), 'coordinates': (458, 2360), 'type': 'tree'}, "GS Zora River Near Raised Grottos": { 'maps': ('skulls_adult',), 'coordinates': (540, 2060), 'type': 'night'}, "GS Zora River Above Bridge": { 'maps': ('skulls_adult',), 'coordinates': (465, 2280), 'type': 'night'}, "GS Zora's Fountain Tree": { 'maps': ('skulls_child',), 'coordinates': (310, 2519), 'type': 'tree'}, "GS Zora's Fountain Above the Log": { 'maps': ('skulls_child',), 'coordinates': (350, 2519), 'type': 'night'}, "GS Zora's Domain Frozen Waterfall": { 'maps': ('skulls_adult',), 'coordinates': (418, 2558), 'type': 'night'}, "GS Zora's Fountain Hidden Cave": { 'maps': ('skulls_adult',), 'coordinates': (310, 2585), 'type': 'high'}, "GS Lon Lon Ranch Tree": { 'maps': ('skulls_child',), 'coordinates': (617, 1363), 'type': 'tree'}, "GS Lon Lon Ranch Rain Shed": { 'maps': ('skulls_child',), 'coordinates': (677, 1325), 'type': 'night'}, "GS Lon Lon Ranch House Window": { 'maps': ('skulls_child',), 'coordinates': (610, 1323), 'type': 'night'}, "GS Lon Lon Ranch Back Wall": { 'maps': ('skulls_child',), 'coordinates': (663, 1197), 'type': 'night'}, "GS Lost Woods Above Stage": { 'maps': ('skulls_adult',), 'coordinates': (740, 2142), 'type': 'high'}, "GS Sacred Forest Meadow": { 'maps': ('skulls_adult',), 'coordinates': (664, 2230), 'type': 'night'}, "GS Hyrule Field Near Gerudo Valley": { 'maps': ('skulls_child', 'skulls_adult'), 'coordinates': (658, 972), 'type': 'high'}, "GS Hyrule Field near Kakariko": { 'maps': ('skulls_child', 'skulls_adult'), 'coordinates': (406, 1552), 'type': 'high'}, "GS Hyrule Castle Grotto": { 'maps': ('skulls_child',), 'coordinates': (206, 1479), 'type': 'spider'}, "GS Deku Tree Compass Room": { 'maps': ('Deku Tree',), 'coordinates': (220, 660), 'type': 'spider'}, "GS Deku Tree Basement Vines": { 'maps': ('Deku Tree',), 'coordinates': (1150, 1280), 'type': 'spider'}, "GS Deku Tree Basement Gate": { 'maps': ('Deku Tree',), 'coordinates': (1320, 1010), 'type': 'spider'}, "GS Deku Tree Basement Back Room": { 'maps': ('Deku Tree',), 'coordinates': (750, 490), 'type': 'spider'}, "GS Dodongo's Cavern East Side Room": { 'maps': ('Dodongos Cavern',), 'coordinates': (2350, 1310), 'type': 'spider'}, "GS Dodongo's Cavern Scarecrow": { 'maps': ('Dodongos Cavern',), 'coordinates': (2060, 1720), 'type': 'spider'}, "GS Dodongo's Cavern Vines Above Stairs": { 'maps': ('Dodongos Cavern',), 'coordinates': (130, 520), 'type': 'spider'}, "GS Dodongo's Cavern Alcove Above Stairs": { 'maps': ('Dodongos Cavern',), 'coordinates': (90, 740), 'type': 'spider'}, "GS Dodongo's Cavern Back Room": { 'maps': ('Dodongos Cavern',), 'coordinates': (1250, 2990), 'type': 'spider'}, "GS Jabu Jabu Water Switch Room": { 'maps': ('Jabu Jabus Belly',), 'coordinates': (1870, 2160), 'type': 'spider'}, "GS Jabu Jabu Lobby Basement Lower": { 'maps': ('Jabu Jabus Belly',), 'coordinates': (1480, 2170), 'type': 'spider'}, "GS Jabu Jabu Lobby Basement Upper": { 'maps': ('Jabu Jabus Belly',), 'coordinates': (1460, 2060), 'type': 'spider'}, "GS Jabu Jabu Near Boss": { 'maps': ('Jabu Jabus Belly',), 'coordinates': (1270, 1700), 'type': 'spider'}, "GS Forest Temple First Room": { 'maps': ('Forest Temple',), 'coordinates': (1850, 340), 'type': 'spider'}, "GS Forest Temple Lobby": { 'maps': ('Forest Temple',), 'coordinates': (1660, 1410), 'type': 'spider'}, "GS Forest Temple Outdoor West": { 'maps': ('Forest Temple',), 'coordinates': (920, 1130), 'type': 'spider'}, "GS Forest Temple Outdoor East": { 'maps': ('Forest Temple',), 'coordinates': (1690, 2370), 'type': 'spider'}, "GS Forest Temple Basement": { 'maps': ('Forest Temple',), 'coordinates': (2480, 360), 'type': 'spider'}, "GS Fire Temple Song of Time Room": { 'maps': ('Fire Temple',), 'coordinates': (2420, 2950), 'type': 'spider'}, "GS Fire Temple Basement": { 'maps': ('Fire Temple',), 'coordinates': (2130, 2610), 'type': 'spider'}, "GS Fire Temple Unmarked Bomb Wall": { 'maps': ('Fire Temple',), 'coordinates': (1640, 3470), 'type': 'spider'}, "GS Fire Temple East Tower Climb": { 'maps': ('Fire Temple',), 'coordinates': (1120, 3060), 'type': 'spider'}, "GS Fire Temple East Tower Top": { 'maps': ('Fire Temple',), 'coordinates': (840, 3090), 'type': 'spider'}, "GS Water Temple South Basement": { 'maps': ('Water Temple',), 'coordinates': (1590, 840), 'type': 'spider'}, "GS Water Temple Near Boss Key Chest": { 'maps': ('Water Temple',), 'coordinates': (1390, 2210), 'type': 'spider'}, "GS Water Temple Central Room": { 'maps': ('Water Temple',), 'coordinates': (1970, 1900), 'type': 'spider'}, "GS Water Temple Serpent River": { 'maps': ('Water Temple',), 'coordinates': (590, 1970), 'type': 'spider'}, "GS Water Temple Falling Platform Room": { 'maps': ('Water Temple',), 'coordinates': (930, 930), 'type': 'spider'}, "GS Spirit Temple Metal Fence": { 'maps': ('Spirit Temple',), 'coordinates': (1460, 670), 'type': 'spider'}, "GS Spirit Temple Bomb for Light Room": { 'maps': ('Spirit Temple',), 'coordinates': (1370, 360), 'type': 'spider'}, "GS Spirit Temple Boulder Room": { 'maps': ('Spirit Temple',), 'coordinates': (1440, 1320), 'type': 'spider'}, "GS Spirit Temple Hall to West Iron Knuckle": { 'maps': ('Spirit Temple',), 'coordinates': (2310, 1930), 'type': 'spider'}, "GS Spirit Temple Lobby": { 'maps': ('Spirit Temple',), 'coordinates': (1490, 2360), 'type': 'spider'}, "GS Shadow Temple Like Like Room": { 'maps': ('Shadow Temple',), 'coordinates': (670, 5950), 'type': 'spider'}, "GS Shadow Temple Crusher Room": { 'maps': ('Shadow Temple',), 'coordinates': (1720, 4980), 'type': 'spider'}, "GS Shadow Temple Single Giant Pot": { 'maps': ('Shadow Temple',), 'coordinates': (1590, 3590), 'type': 'spider'}, "GS Shadow Temple Near Ship": { 'maps': ('Shadow Temple',), 'coordinates': (1180, 3230), 'type': 'spider'}, "GS Shadow Temple Triple Giant Pot": { 'maps': ('Shadow Temple',), 'coordinates': (2360, 170), 'type': 'spider'}, "GS Well West Inner Room": { 'maps': ('Bottom of the Well',), 'coordinates': (180, 920), 'type': 'spider'}, "GS Well East Inner Room": { 'maps': ('Bottom of the Well',), 'coordinates': (210, 1090), 'type': 'spider'}, "GS Well Like Like Cage": { 'maps': ('Bottom of the Well',), 'coordinates': (400, 1520), 'type': 'spider'}, "GS Ice Cavern Spinning Scythe Room": { 'maps': ('Ice Cavern',), 'coordinates': (680, 1420), 'type': 'spider'}, "GS Ice Cavern Heart Piece Room": { 'maps': ('Ice Cavern',), 'coordinates': (970, 1720), 'type': 'spider'}, "GS Ice Cavern Push Block Room": { 'maps': ('Ice Cavern',), 'coordinates': (290, 1180), 'type': 'spider'}, }
z5-tracker
/z5_tracker-1.2.1-py3-none-any.whl/z5tracker/maps/maps.py
maps.py
__all__ = 'MAPSCALE', 'MAPSPEC', 'BUTTONTYPE' MAPSCALE = 0.25 MAPSPEC = { 'item_child': { 'title': 'Child Item Map', 'loctype': 'item', 'mapscale': 1}, 'item_adult': { 'title': 'Adult Item Map', 'loctype': 'item', 'mapscale': 1}, 'skulls_child': { 'title': 'Child Skulltula Map', 'loctype': 'skulltula', 'mapscale': 1}, 'skulls_adult': { 'title': 'Adult Skulltula Map', 'loctype': 'skulltula', 'mapscale': 1}, 'skulls_child': { 'title': 'Child Skultula Map', 'loctype': 'skulltula', 'mapscale': 1}, 'skulls_adult': { 'title': 'Adult Skultula Map', 'loctype': 'skulltula', 'mapscale': 1}, 'Deku Tree': { 'title': 'Inside the Deku Tree', 'loctype': 'dungeon', 'mapscale': 1}, 'Dodongos Cavern': { 'title': "Dodongo's Cavern", 'loctype': 'dungeon', 'mapscale': 1}, 'Jabu Jabus Belly': { 'title': "Jabu-Jabu's Belly", 'loctype': 'dungeon', 'mapscale': 1}, 'Ice Cavern': { 'title': 'Ice Cavern', 'loctype': 'dungeon', 'mapscale': 1}, 'Bottom of the Well': { 'title': 'Bottom of the Well', 'loctype': 'dungeon', 'mapscale': 1}, 'Gerudo Training Grounds': { 'title': 'Gerudo Training Grounds', 'loctype': 'dungeon', 'mapscale': 1}, 'Forest Temple': { 'title': 'Forest Temple', 'loctype': 'dungeon', 'mapscale': 1}, 'Fire Temple': { 'title': 'Fire Temple', 'loctype': 'dungeon', 'mapscale': 1}, 'Water Temple': { 'title': 'Water Temple', 'loctype': 'dungeon', 'mapscale': 1}, 'Shadow Temple': { 'title': 'Shadow Temple', 'loctype': 'dungeon', 'mapscale': 0.5}, 'Spirit Temple': { 'title': 'Spirit Temple', 'loctype': 'dungeon', 'mapscale': 1}, 'Ganons Castle': { 'title': "Ganon's Castle", 'loctype': 'dungeon', 'mapscale': 1} } BUTTONTYPE = {} BUTTONTYPE['standard'] = { 'colours': { 'on': {'active': '#0f0', 'normal': '#0c0'}, 'off': {'active': '#aaa', 'normal': 'grey'}, 'unavailable': {'active': '#f00', 'normal': '#c00'} }, 'shape': lambda self, location: self._standard_icon(location)} BUTTONTYPE['chest'] = BUTTONTYPE['standard'] BUTTONTYPE['enemy'] = { 'colours': BUTTONTYPE['standard']['colours'], 'shape': lambda self, location: self._enemy_icon(location)} BUTTONTYPE['npc'] = { 'colours': BUTTONTYPE['standard']['colours'], 'shape': lambda self, location: self._npc_icon(location)} BUTTONTYPE['shop'] = { 'colours': BUTTONTYPE['standard']['colours'], 'shape': lambda self, location: self._shop_icon(location)} BUTTONTYPE['song'] = { 'colours': BUTTONTYPE['standard']['colours'], 'shape': lambda self, location: self._song_icon(location)} BUTTONTYPE['free'] = { 'colours': BUTTONTYPE['standard']['colours'], 'shape': lambda self, location: self._free_icon(location)} BUTTONTYPE['heart'] = { 'colours': BUTTONTYPE['standard']['colours'], 'shape': lambda self, location: self._heart_icon(location)} BUTTONTYPE['fairy'] = { 'colours': BUTTONTYPE['standard']['colours'], 'shape': lambda self, location: self._fairy_icon(location)} BUTTONTYPE['sub'] = { 'colours': BUTTONTYPE['standard']['colours'], 'shape': lambda self, location: self._sub_icon(location)} BUTTONTYPE['stone'] = { 'colours': { 'on': {'active': '#9aa', 'normal': '#ddd'}, 'off': {'active': '#aaa', 'normal': 'grey'}, 'unavailable': {'active': '#f00', 'normal': '#c00'}}, 'shape': lambda self, location: self._stone_icon(location)} BUTTONTYPE['dungeon'] = { 'colours': { 'on': {'active': '#0f0', 'normal': '#0c0'}, 'off': {'active': '#aaa', 'normal': 'grey'}, 'unavailable': {'active': '#f00', 'normal': '#c00'}, 'partial': {'active': '#ff0', 'normal': '#cc0'}}, 'shape': lambda self, location: self._dungeon_icon(location)} BUTTONTYPE['ganon'] = { 'colours': BUTTONTYPE['standard']['colours'], 'shape': lambda self, location: self._ganon_icon(location)} BUTTONTYPE['spider'] = { 'colours': { 'on': {'active': '#ff0', 'normal': '#f80'}, 'off': {'active': '#aaa', 'normal': 'grey'}, 'unavailable': {'active': '#f0f','normal': '#c0a'}, 'partial': {'active': '#ff0', 'normal': '#cc0'}}, 'shape': lambda self, location: self._standard_icon(location)} BUTTONTYPE['night'] = { 'colours': BUTTONTYPE['spider']['colours'], 'shape': lambda self, location: self._night_icon(location)} BUTTONTYPE['high'] = { 'colours': BUTTONTYPE['spider']['colours'], 'shape': lambda self, location: self._high_icon(location)} BUTTONTYPE['bean'] = { 'colours': BUTTONTYPE['spider']['colours'], 'shape': lambda self, location: self._bean_icon(location)} BUTTONTYPE['tree'] = { 'colours': BUTTONTYPE['spider']['colours'], 'shape': lambda self, location: self._tree_icon(location)}
z5-tracker
/z5_tracker-1.2.1-py3-none-any.whl/z5tracker/maps/info.py
info.py
import json import os import sys import typing from ..version import __version__ as version from .default import DEFAULT, OVERWRITE __all__ = 'Config', class _c(dict): ''' Single entry info for configuration file. Instance variables: name: name of the config option valtype: type of the config option default: default value ''' def __init__( self, name: str, valtype: typing.Callable[[typing.Any], typing.Any], default: typing.Any): ''' Args: name: name of the config option valtype: type of the config option default: default value ''' super().__init__() self.name = name self.valtype = valtype self.default = default class Config(dict): ''' Program configuration. Instance variables: filename: full path to config filename scheme: config file layout _changed: True if config has changed and should be saved ''' def __init__(self): super().__init__() self._get_scheme() self.filename = _config_filename() try: fid = open(self.filename, 'r') except FileNotFoundError: imported = None else: imported = fid.read() try: imp_dict = {} if imported is None else json.loads(imported) except json.decoder.JSONDecodeError: imp_dict = {} self._changed = False for entry in imp_dict: self._insert_entry(entry, imp_dict[entry]) self._check_missing() self.set('version', version) self.__setitem__ = self._change_entry def _get_scheme(self) -> None: ''' Get config file info. Writes: scheme ''' self.scheme = {} for entry in DEFAULT: self.scheme[entry[0]] = _c(*entry) def _insert_entry(self, entry_name: str, entry_value: typing.Any) -> None: ''' Insert imported entry. Args: entry: config file entry read from file Reads: scheme Writes: self ''' try: scheme = self.scheme[entry_name] except KeyError: self._changed = True return self[scheme.name] = scheme.valtype(entry_value) def _check_missing(self) -> None: ''' Insert missing entries into configuration. Reads: scheme Writes: self ''' if 'version' not in self or self['version'] != version: for entry in OVERWRITE[version]: print(entry) self[entry] = self.scheme[entry].default self._changed = True for entry in self.scheme: if entry not in self: self[entry] = self.scheme[entry].default self._changed = True def _string(self) -> str: ''' Convert config into JSON string. Reads: self Returns: str: JSON string ''' return json.dumps(dict(self)) def _write_to_file(self) -> None: ''' Write config to file if there are any changes. ''' if self._changed: with open(self.filename, 'w') as fid: fid.write(self._string()) self._changed = False def _change_entry(self, key, value) -> None: ''' Replacement for __setitem__() once config file has been loaded. ''' super().__setitem__(key, value) self._changed = True self._write_to_file() def set(self, key, value) -> None: ''' Set dict item. For some reason, _change_entry() doesn't overload __setitem__(). ''' self[key] = value self._changed = True self._write_to_file() def config_directory() -> str: ''' Return configuration directory. This will create said directory if it doesn't exist. Returns: str: full path to configuration directory ''' if sys.platform.startswith('win32'): configdir = os.path.join(os.getenv('LOCALAPPDATA'), 'z5-tracker') else: configdir = os.path.expanduser('~/.z5-tracker') if not os.path.isdir(configdir): os.mkdir(configdir) return configdir def _config_filename() -> str: ''' Return config file name. This will create the config directory if it doesn't exist. The config file itself, however, might not exist. Returns: str: fill path to config file ''' return os.path.join(config_directory(), 'config.json')
z5-tracker
/z5_tracker-1.2.1-py3-none-any.whl/z5tracker/config/config.py
config.py